Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/platform/auth/desktopHost/desktopHostAuthBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,7 @@ export interface DesktopHostAuthBridge {
getWorkspaceToken(workspaceId: string): Promise<string | null>
requestSignIn(): Promise<DesktopHostAuthState>
signOut(): Promise<DesktopHostAuthState>
/** Absent on Desktop builds before Comfy-Desktop #1671. */
switchWorkspace?(workspaceId: string): Promise<DesktopHostAuthState>
onChanged(callback: (state: DesktopHostAuthState) => void): () => void
}
61 changes: 61 additions & 0 deletions src/platform/auth/desktopHost/desktopHostSession.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -32,6 +34,14 @@ function fakeBridge(initial: DesktopHostAuthState) {
signOut: vi.fn(
async (): Promise<DesktopHostAuthState> => ({ status: 'signed_out' })
),
switchWorkspace: vi.fn(
async (workspaceId: string): Promise<DesktopHostAuthState> => ({
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)
Expand Down Expand Up @@ -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)
})
Expand Down
20 changes: 20 additions & 0 deletions src/platform/auth/desktopHost/desktopHostSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,23 @@ export async function requestDesktopHostSignOut(): Promise<boolean> {
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<boolean> {
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
}
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand All @@ -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'
Expand Down Expand Up @@ -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')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,11 @@

<!-- Workspace Selector -->
<div v-if="!accountActionsOnly" class="relative">
<!-- An API-key session is bound to one server-resolved workspace and
exposes no discovery or switching -->
<!-- An API-key session is bound to one server-resolved workspace, and a
Desktop build without workspace switching fixes the host session's;
neither exposes discovery or switching -->
<div
v-if="isApiKeyLogin"
v-if="isApiKeyLogin || isDesktopHostWorkspaceFixed"
class="flex w-full items-center gap-2 rounded-lg px-4 py-2"
data-testid="workspace-context-row"
>
Expand Down Expand Up @@ -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'
Expand Down Expand Up @@ -316,6 +321,9 @@ const {
handleSignOut,
isApiKeyLogin
} = useCurrentUser()
const isDesktopHostWorkspaceFixed = computed(
() => isDesktopHostSignedIn() && !canDesktopHostSwitchWorkspace()
)
const settingsDialog = useSettingsDialog()
const dialogService = useDialogService()
const {
Expand Down
142 changes: 140 additions & 2 deletions src/platform/workspace/stores/teamWorkspaceStore.test.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand Down Expand Up @@ -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<DesktopHostAuthState>>
>

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()
})
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

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()
Expand Down
Loading
Loading