diff --git a/src/platform/auth/desktopHost/desktopHostAuthBridge.ts b/src/platform/auth/desktopHost/desktopHostAuthBridge.ts index 91e83800d5d..446404d48aa 100644 --- a/src/platform/auth/desktopHost/desktopHostAuthBridge.ts +++ b/src/platform/auth/desktopHost/desktopHostAuthBridge.ts @@ -18,5 +18,7 @@ export interface DesktopHostAuthBridge { getWorkspaceToken(workspaceId: string): Promise requestSignIn(): Promise signOut(): Promise + /** Absent on Desktop builds before Comfy-Desktop #1671. */ + switchWorkspace?(workspaceId: string): Promise onChanged(callback: (state: DesktopHostAuthState) => void): () => void } diff --git a/src/platform/auth/desktopHost/desktopHostSession.test.ts b/src/platform/auth/desktopHost/desktopHostSession.test.ts index 80cb4f89008..3704056c2c1 100644 --- a/src/platform/auth/desktopHost/desktopHostSession.test.ts +++ b/src/platform/auth/desktopHost/desktopHostSession.test.ts @@ -5,11 +5,13 @@ import type { DesktopHostAuthState } from '@/platform/auth/desktopHost/desktopHostAuthBridge' import { + canDesktopHostSwitchWorkspace, desktopHostUser, desktopHostWorkspaceToken, isDesktopHostSessionActive, requestDesktopHostSignIn, requestDesktopHostSignOut, + requestDesktopHostWorkspaceSwitch, startDesktopHostSession, stopDesktopHostSession } from '@/platform/auth/desktopHost/desktopHostSession' @@ -32,6 +34,14 @@ function fakeBridge(initial: DesktopHostAuthState) { signOut: vi.fn( async (): Promise => ({ status: 'signed_out' }) ), + switchWorkspace: vi.fn( + async (workspaceId: string): Promise => ({ + status: 'signed_in', + userId: 'user-1', + email: 'a@example.com', + workspaceId + }) + ), onChanged: vi.fn((callback: (state: DesktopHostAuthState) => void) => { listeners.add(callback) return () => listeners.delete(callback) @@ -189,6 +199,57 @@ describe('desktopHostSession', () => { } ) + describe('workspace switch', () => { + it('follows Desktop onto the workspace it switched to', async () => { + const { bridge } = fakeBridge(SIGNED_IN) + await startDesktopHostSession(bridge) + + expect(canDesktopHostSwitchWorkspace()).toBe(true) + await expect(requestDesktopHostWorkspaceSwitch('ws-2')).resolves.toBe( + true + ) + expect(bridge.switchWorkspace).toHaveBeenCalledWith('ws-2') + expect(desktopHostUser.value?.workspaceId).toBe('ws-2') + }) + + it.for([ + { name: 'Desktop stays on its workspace', result: SIGNED_IN }, + { name: 'the switch fails', result: undefined } + ])('reports no switch when $name', async ({ result }) => { + const { bridge } = fakeBridge(SIGNED_IN) + if (result) bridge.switchWorkspace.mockResolvedValue(result) + else bridge.switchWorkspace.mockRejectedValue(new Error('consent')) + await startDesktopHostSession(bridge) + + await expect(requestDesktopHostWorkspaceSwitch('ws-2')).resolves.toBe( + false + ) + expect(desktopHostUser.value?.workspaceId).toBe('ws-1') + }) + + it('cannot switch on a Desktop build without the bridge method', async () => { + const { bridge } = fakeBridge(SIGNED_IN) + const { switchWorkspace: _omitted, ...olderBridge } = bridge + await startDesktopHostSession(olderBridge) + + expect(canDesktopHostSwitchWorkspace()).toBe(false) + await expect(requestDesktopHostWorkspaceSwitch('ws-2')).resolves.toBe( + false + ) + }) + + it('cannot switch while signed out', async () => { + const { bridge } = fakeBridge({ status: 'signed_out' }) + await startDesktopHostSession(bridge) + + expect(canDesktopHostSwitchWorkspace()).toBe(false) + await expect(requestDesktopHostWorkspaceSwitch('ws-2')).resolves.toBe( + false + ) + expect(bridge.switchWorkspace).not.toHaveBeenCalled() + }) + }) + it('does not start a Desktop sign-in while inactive', async () => { await expect(requestDesktopHostSignIn()).resolves.toBe(false) }) diff --git a/src/platform/auth/desktopHost/desktopHostSession.ts b/src/platform/auth/desktopHost/desktopHostSession.ts index b7f14e53741..5d8c1663ef8 100644 --- a/src/platform/auth/desktopHost/desktopHostSession.ts +++ b/src/platform/auth/desktopHost/desktopHostSession.ts @@ -122,3 +122,23 @@ export async function requestDesktopHostSignOut(): Promise { if (next && bridge === current && revision === before) apply(next) return desktopHostUser.value === null } + +/** True when this Desktop can re-scope its session to another workspace. */ +export function canDesktopHostSwitchWorkspace(): boolean { + return isDesktopHostSignedIn() && bridge?.switchWorkspace !== undefined +} + +/** + * Asks Desktop to re-scope its session to `workspaceId`, which may run browser + * consent. Resolves true once the session is on that workspace. + */ +export async function requestDesktopHostWorkspaceSwitch( + workspaceId: string +): Promise { + const current = bridge + if (!current?.switchWorkspace || !isDesktopHostSignedIn()) return false + const before = revision + const next = await current.switchWorkspace(workspaceId).catch(() => undefined) + if (next && bridge === current && revision === before) apply(next) + return desktopHostUser.value?.workspaceId === workspaceId +} diff --git a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts index 55c78ed8343..45f33435644 100644 --- a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts +++ b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts @@ -6,7 +6,7 @@ import { render, screen, waitFor } from '@testing-library/vue' import userEvent from '@testing-library/user-event' import PrimeVue from 'primevue/config' import Tooltip from 'primevue/tooltip' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { computed, defineComponent, ref } from 'vue' import { createI18n } from 'vue-i18n' @@ -15,6 +15,11 @@ import { useBillingContext } from '@/composables/billing/useBillingContext' import { useBillingRouting } from '@/composables/billing/useBillingRouting' import type { BalanceInfo, SubscriptionInfo } from '@/composables/billing/types' import { useFeatureFlags } from '@/composables/useFeatureFlags' +import type { DesktopHostAuthBridge } from '@/platform/auth/desktopHost/desktopHostAuthBridge' +import { + startDesktopHostSession, + stopDesktopHostSession +} from '@/platform/auth/desktopHost/desktopHostSession' import enMessages from '@/locales/en/main.json' import { useSubscriptionDialog } from '@/platform/cloud/subscription/composables/useSubscriptionDialog' import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog' @@ -254,6 +259,39 @@ describe('CurrentUserPopoverWorkspace', () => { ).not.toBeInTheDocument() }) + describe('with a Desktop host session', () => { + const signedIn = { + status: 'signed_in', + userId: 'host-user', + workspaceId: 'ws-1' + } as const + const hostBridge = (canSwitch: boolean): DesktopHostAuthBridge => ({ + getState: async () => signedIn, + getWorkspaceToken: async () => 'host-token', + requestSignIn: async () => signedIn, + signOut: async () => ({ status: 'signed_out' }), + ...(canSwitch && { switchWorkspace: async () => signedIn }), + onChanged: () => () => {} + }) + + afterEach(() => stopDesktopHostSession()) + + it.for([ + { name: 'offers the switcher when Desktop can switch', canSwitch: true }, + { name: 'shows a fixed workspace on an older Desktop', canSwitch: false } + ])('$name', async ({ canSwitch }) => { + await startDesktopHostSession(hostBridge(canSwitch)) + renderComponent('team') + + expect(screen.queryByTestId('workspace-switcher-trigger') !== null).toBe( + canSwitch + ) + expect(screen.queryByTestId('workspace-context-row') !== null).toBe( + !canSwitch + ) + }) + }) + it('exposes the full workspace name on hover', async () => { const user = userEvent.setup() renderComponent('team') diff --git a/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue b/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue index 8b22ba190a0..8ea1d94de58 100644 --- a/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue +++ b/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue @@ -24,10 +24,11 @@
- +
@@ -263,6 +264,10 @@ import WorkspaceProfilePic from '@/platform/workspace/components/WorkspaceProfil import WorkspaceSwitcherPopover from '@/platform/workspace/components/WorkspaceSwitcherPopover.vue' import Button from '@/components/ui/button/Button.vue' import { useCurrentUser } from '@/composables/auth/useCurrentUser' +import { + canDesktopHostSwitchWorkspace, + isDesktopHostSignedIn +} from '@/platform/auth/desktopHost/desktopHostSession' import { useExternalLink } from '@/composables/useExternalLink' import { useBillingContext } from '@/composables/billing/useBillingContext' @@ -316,6 +321,9 @@ const { handleSignOut, isApiKeyLogin } = useCurrentUser() +const isDesktopHostWorkspaceFixed = computed( + () => isDesktopHostSignedIn() && !canDesktopHostSwitchWorkspace() +) const settingsDialog = useSettingsDialog() const dialogService = useDialogService() const { diff --git a/src/platform/workspace/stores/teamWorkspaceStore.test.ts b/src/platform/workspace/stores/teamWorkspaceStore.test.ts index 94689c23c87..80c912a80c8 100644 --- a/src/platform/workspace/stores/teamWorkspaceStore.test.ts +++ b/src/platform/workspace/stores/teamWorkspaceStore.test.ts @@ -1,12 +1,20 @@ -import { computed } from 'vue' +import { computed, nextTick } from 'vue' import { reportError } from '@/platform/telemetry/reportError' import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore' import { stubAccountIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { useCurrentUser } from '@/composables/auth/useCurrentUser' import { useFeatureFlags } from '@/composables/useFeatureFlags' +import type { + DesktopHostAuthBridge, + DesktopHostAuthState +} from '@/platform/auth/desktopHost/desktopHostAuthBridge' +import { + startDesktopHostSession, + stopDesktopHostSession +} from '@/platform/auth/desktopHost/desktopHostSession' import { NoWorkspaceAccessError } from '@/platform/workspace/api/workspaceApiError' import { WORKSPACE_STORAGE_KEYS } from '@/platform/workspace/workspaceConstants' @@ -2280,6 +2288,136 @@ describe('useTeamWorkspaceStore', () => { }) }) + describe('with a Desktop host session', () => { + const hostOn = (workspaceId: string): DesktopHostAuthState => ({ + status: 'signed_in', + userId: 'host-user', + workspaceId + }) + let pushHostState: (state: DesktopHostAuthState) => void + let hostSwitch: ReturnType< + typeof vi.fn<(workspaceId: string) => Promise> + > + + beforeEach(async () => { + mockDistributionTypes.isCloud = false + const listeners = new Set<(state: DesktopHostAuthState) => void>() + pushHostState = (state) => + listeners.forEach((listener) => listener(state)) + hostSwitch = vi.fn(async (workspaceId: string) => hostOn(workspaceId)) + const bridge: DesktopHostAuthBridge = { + getState: async () => hostOn(mockTeamWorkspace.id), + getWorkspaceToken: async () => 'host-token', + requestSignIn: async () => hostOn(mockTeamWorkspace.id), + signOut: async () => ({ status: 'signed_out' }), + switchWorkspace: hostSwitch, + onChanged: (callback) => { + listeners.add(callback) + return () => listeners.delete(callback) + } + } + await startDesktopHostSession(bridge) + }) + + afterEach(() => stopDesktopHostSession()) + + it('lists workspaces and takes the one Desktop is scoped to', async () => { + const store = useTeamWorkspaceStore() + + await store.initialize() + + expect(store.initState).toBe('ready') + expect(store.workspaces).toHaveLength(2) + expect(store.activeWorkspaceId).toBe(mockTeamWorkspace.id) + expect(useWorkspaceAuthStore().switchWorkspace).not.toHaveBeenCalled() + expect(mockEnsureSessionCookie).not.toHaveBeenCalled() + }) + + it('fails to initialize when Desktop is scoped to a workspace the account cannot list', async () => { + mockWorkspaceApi.list.mockResolvedValue({ + workspaces: [mockPersonalWorkspace] + }) + const store = useTeamWorkspaceStore() + + await expect(store.initialize()).rejects.toThrow() + expect(store.initState).toBe('error') + }) + + it('switches through Desktop without a reload or token exchange', async () => { + const store = useTeamWorkspaceStore() + await store.initialize() + + await store.switchWorkspace(mockPersonalWorkspace.id) + + expect(hostSwitch).toHaveBeenCalledWith(mockPersonalWorkspace.id) + expect(store.activeWorkspaceId).toBe(mockPersonalWorkspace.id) + expect(store.isSwitching).toBe(false) + expect(useWorkspaceAuthStore().switchWorkspace).not.toHaveBeenCalled() + expect(mockReload).not.toHaveBeenCalled() + }) + + it('stays on its workspace when Desktop does not switch', async () => { + hostSwitch.mockResolvedValue(hostOn(mockTeamWorkspace.id)) + const store = useTeamWorkspaceStore() + await store.initialize() + + await expect( + store.switchWorkspace(mockPersonalWorkspace.id) + ).rejects.toThrow() + expect(store.activeWorkspaceId).toBe(mockTeamWorkspace.id) + expect(store.isSwitching).toBe(false) + }) + + it('refreshes the list for a Desktop workspace it has not seen, then takes it', async () => { + const store = useTeamWorkspaceStore() + await store.initialize() + mockWorkspaceApi.list.mockResolvedValue({ + workspaces: [ + mockPersonalWorkspace, + mockTeamWorkspace, + mockMemberWorkspace + ] + }) + + pushHostState(hostOn(mockMemberWorkspace.id)) + await nextTick() + expect(store.activeWorkspaceId).toBeNull() + + await vi.waitFor(() => + expect(store.activeWorkspaceId).toBe(mockMemberWorkspace.id) + ) + }) + + it('keeps no active workspace when the refreshed list lacks the Desktop workspace', async () => { + const store = useTeamWorkspaceStore() + await store.initialize() + mockWorkspaceApi.list.mockClear() + + pushHostState(hostOn(mockMemberWorkspace.id)) + + await vi.waitFor(() => expect(mockWorkspaceApi.list).toHaveBeenCalled()) + await nextTick() + expect(store.activeWorkspaceId).toBeNull() + }) + + it('follows a switch made in Desktop', async () => { + mockWorkspaceApi.list.mockResolvedValue({ + workspaces: [ + mockPersonalWorkspace, + mockTeamWorkspace, + mockMemberWorkspace + ] + }) + const store = useTeamWorkspaceStore() + await store.initialize() + + pushHostState(hostOn(mockMemberWorkspace.id)) + await nextTick() + + expect(store.activeWorkspaceId).toBe(mockMemberWorkspace.id) + }) + }) + describe('cleanup', () => { it('destroy calls workspaceAuthStore.destroy', async () => { const store = useTeamWorkspaceStore() diff --git a/src/platform/workspace/stores/teamWorkspaceStore.ts b/src/platform/workspace/stores/teamWorkspaceStore.ts index 7d4b3aaabef..8ce967f0d17 100644 --- a/src/platform/workspace/stores/teamWorkspaceStore.ts +++ b/src/platform/workspace/stores/teamWorkspaceStore.ts @@ -1,8 +1,13 @@ import { defineStore } from 'pinia' -import { computed, ref, shallowRef } from 'vue' +import { computed, ref, shallowRef, watch } from 'vue' import { useCurrentUser } from '@/composables/auth/useCurrentUser' import { useFeatureFlags } from '@/composables/useFeatureFlags' +import { + desktopHostUser, + isDesktopHostSignedIn, + requestDesktopHostWorkspaceSwitch +} from '@/platform/auth/desktopHost/desktopHostSession' import { isCloud } from '@/platform/distribution/types' import { WORKSPACE_STORAGE_KEYS } from '@/platform/workspace/workspaceConstants' import { clearPreservedQuery } from '@/platform/navigation/preservedQueryManager' @@ -329,6 +334,24 @@ export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { // server. There is no discovery, switching, or token exchange for it: // the server echoes the binding back and the key itself authenticates // workspace-scoped calls. + // Desktop owns a host session's workspace: list what the account can + // reach and follow the workspace Desktop's session is scoped to. + if (isDesktopHostSignedIn()) { + const response = await workspaceApi.list() + if (isStaleIdentity(generation)) return + workspaces.value = sortWorkspaces( + response.workspaces.map(createWorkspaceState) + ) + const hostWorkspaceId = desktopHostUser.value?.workspaceId + if (!workspaces.value.some((w) => w.id === hostWorkspaceId)) { + throw new NoWorkspaceAccessError('Desktop workspace not available') + } + mutableActiveWorkspaceId.value = hostWorkspaceId ?? null + initState.value = 'ready' + isFetchingWorkspaces.value = false + return + } + if (isApiKeySession) { const current = await workspaceApi.getCurrentWorkspace() if (isStaleIdentity(generation)) return @@ -563,9 +586,15 @@ export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { if (isStaleIdentity(generation)) return if (!isCloud) { - await workspaceAuthStore.switchWorkspace(workspaceId) + const switched = isDesktopHostSignedIn() + ? await requestDesktopHostWorkspaceSwitch(workspaceId) + : await workspaceAuthStore + .switchWorkspace(workspaceId) + .then( + () => workspaceAuthStore.currentWorkspace?.id === workspaceId + ) if (isStaleIdentity(generation)) return - if (workspaceAuthStore.currentWorkspace?.id !== workspaceId) { + if (!switched) { throw new Error('Workspace authentication did not switch') } mutableActiveWorkspaceId.value = workspaceId @@ -1022,6 +1051,42 @@ export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { workspaceAuthStore.destroy() } + // A switch made in Desktop (its chooser, or another view) re-scopes this + // view's credential. The tab drops its old scope at once and takes the new + // workspace only once the account's list confirms it. + async function followDesktopHostWorkspace( + hostWorkspaceId: string + ): Promise { + const generation = identityGeneration + mutableActiveWorkspaceId.value = null + const isListed = () => + workspaces.value.some((w) => w.id === hostWorkspaceId) + if (!isListed()) { + await refreshWorkspaces().catch(() => undefined) + if ( + isStaleIdentity(generation) || + desktopHostUser.value?.workspaceId !== hostWorkspaceId + ) { + return + } + } + if (isListed()) mutableActiveWorkspaceId.value = hostWorkspaceId + } + + watch( + () => desktopHostUser.value?.workspaceId, + (hostWorkspaceId) => { + if ( + !hostWorkspaceId || + initState.value !== 'ready' || + hostWorkspaceId === mutableActiveWorkspaceId.value + ) { + return + } + void followDesktopHostWorkspace(hostWorkspaceId) + } + ) + function resetForIdentityChange(): void { identityGeneration++ mutableWorkspaceTransitionGeneration.value++ diff --git a/src/stores/authStore.test.ts b/src/stores/authStore.test.ts index dbe8e30f2de..42d15f31dba 100644 --- a/src/stores/authStore.test.ts +++ b/src/stores/authStore.test.ts @@ -2828,6 +2828,69 @@ describe('useAuthStore in local/desktop distribution', () => { expect(mockUser.getIdToken).not.toHaveBeenCalled() }) + it("loads the host account's workspaces when Desktop signs in", async () => { + const initialize = vi + .spyOn(useTeamWorkspaceStore(), 'initialize') + .mockResolvedValue() + const bridge = hostBridge({ status: 'signed_out' }) + await startDesktopHostSession(bridge) + expect(initialize).not.toHaveBeenCalled() + + bridge.push({ + status: 'signed_in', + userId: 'host-user', + workspaceId: 'ws-host' + }) + + await vi.waitFor(() => expect(initialize).toHaveBeenCalledOnce()) + }) + + it("loads the host account's workspaces when Desktop signed in before the store started", async () => { + store.$dispose() + const initialize = vi + .spyOn(useTeamWorkspaceStore(), 'initialize') + .mockResolvedValue() + await startDesktopHostSession( + hostBridge({ + status: 'signed_in', + userId: 'host-user', + workspaceId: 'ws-host' + }) + ) + await nextTick() + expect(initialize).not.toHaveBeenCalled() + + useAuthStore() + + expect(initialize).toHaveBeenCalledOnce() + }) + + it('drops workspaces loaded for the Firebase account when Desktop signs in', async () => { + const teams = useTeamWorkspaceStore() + teams.initState = 'ready' + const reset = vi.spyOn(teams, 'resetForIdentityChange') + const clearWorkspace = vi.spyOn( + useWorkspaceAuthStore(), + 'clearWorkspaceContext' + ) + const initialize = vi.spyOn(teams, 'initialize').mockResolvedValue() + const bridge = hostBridge({ status: 'signed_out' }) + await startDesktopHostSession(bridge) + + bridge.push({ + status: 'signed_in', + userId: 'host-user', + workspaceId: 'ws-host' + }) + await nextTick() + + expect(clearWorkspace).toHaveBeenCalled() + expect(reset).toHaveBeenCalledOnce() + expect(reset.mock.invocationCallOrder[0]).toBeLessThan( + initialize.mock.invocationCallOrder[0] + ) + }) + it('has no workspace credential when no workspace is known', async () => { const bridge = hostBridge({ status: 'signed_in', userId: 'host-user' }) await startDesktopHostSession(bridge) diff --git a/src/stores/authStore.ts b/src/stores/authStore.ts index 14ccc9265b5..ddc693ffde1 100644 --- a/src/stores/authStore.ts +++ b/src/stores/authStore.ts @@ -274,6 +274,27 @@ export const useAuthStore = defineStore('auth', () => { resetAccountState(previousUserId, nextUserId) ) + // Off Cloud, nothing else loads a host account's workspaces before the + // account menu needs them, including a Desktop sign-in that predates this + // store. A store already loaded for the Firebase or API-key account is + // dropped first, since Desktop now owns the credential. + watch( + () => desktopHostUser.value?.id ?? null, + (userId, previousUserId) => { + if (userId === null || isCloud) return + const teamWorkspaceStore = useTeamWorkspaceStore() + if ( + previousUserId == null && + teamWorkspaceStore.initState !== 'uninitialized' + ) { + useWorkspaceAuthStore().clearWorkspaceContext() + teamWorkspaceStore.resetForIdentityChange() + } + teamWorkspaceStore.initialize().catch(() => undefined) + }, + { immediate: true } + ) + // Listen for token refresh events firebaseIdentity.onTokenChanged((user) => { if (user && isCloud) {