diff --git a/browser_tests/fixtures/ComfyPage.ts b/browser_tests/fixtures/ComfyPage.ts index e9fe57a88a3..5785b58362f 100644 --- a/browser_tests/fixtures/ComfyPage.ts +++ b/browser_tests/fixtures/ComfyPage.ts @@ -16,6 +16,7 @@ import { TestIds } from '@e2e/fixtures/selectors' import { comfyExpect } from '@e2e/fixtures/utils/customMatchers' import { assetPath } from '@e2e/fixtures/utils/paths' import { nextFrame, sleep } from '@e2e/fixtures/utils/timing' +import { mockWorkspace, workspace } from '@e2e/fixtures/utils/workspaceMocks' import { VueNodeHelpers } from '@e2e/fixtures/VueNodeHelpers' import { BottomPanel } from '@e2e/fixtures/components/BottomPanel' import { ComfyNodeSearchBox } from '@e2e/fixtures/components/ComfyNodeSearchBox' @@ -564,6 +565,11 @@ export const comfyPageFixture = base.extend<{ } if (testInfo.tags.includes('@cloud')) { + const context = page.context() + await context.route('**/api/auth/session', (route) => + route.fulfill({ status: 204 }) + ) + await mockWorkspace(context, workspace('personal', 'owner'), []) await comfyPage.cloudAuth.mockAuth() } diff --git a/browser_tests/fixtures/utils/workspaceMocks.ts b/browser_tests/fixtures/utils/workspaceMocks.ts index 75b6f9b65c9..f2f2b180ea9 100644 --- a/browser_tests/fixtures/utils/workspaceMocks.ts +++ b/browser_tests/fixtures/utils/workspaceMocks.ts @@ -1,4 +1,4 @@ -import type { Page } from '@playwright/test' +import type { BrowserContext, Page } from '@playwright/test' import type { Member, @@ -38,10 +38,10 @@ export function member( * this the mint fails and auth cannot resolve the active workspace. */ export async function mockWorkspaceTokenMint( - page: Page, + routeTarget: Page | BrowserContext, ws: Pick ) { - await page.route('**/api/auth/token', (r) => + await routeTarget.route('**/api/auth/token', (r) => r.fulfill( jsonRoute({ token: 'mock-workspace-token', @@ -54,21 +54,29 @@ export async function mockWorkspaceTokenMint( ) } +/** Stub `GET /api/workspaces` with the given roster. */ +async function mockWorkspaceList( + routeTarget: Page | BrowserContext, + workspaces: WorkspaceWithRole[] +): Promise { + await routeTarget.route('**/api/workspaces', async (route) => { + if (route.request().method() !== 'GET') return route.fallback() + await route.fulfill(jsonRoute({ workspaces })) + }) +} + /** * Stub the workspace resolution + members list so the cloud app boots into the * given workspace with the given roster (drives the original-owner gate). */ export async function mockWorkspace( - page: Page, + routeTarget: Page | BrowserContext, ws: WorkspaceWithRole, members: Member[] ) { - await page.route('**/api/workspaces', async (route) => { - if (route.request().method() !== 'GET') return route.fallback() - await route.fulfill(jsonRoute({ workspaces: [ws] })) - }) - await mockWorkspaceTokenMint(page, ws) - await page.route('**/api/workspace/members**', (r) => + await mockWorkspaceList(routeTarget, [ws]) + await mockWorkspaceTokenMint(routeTarget, ws) + await routeTarget.route('**/api/workspace/members**', (r) => r.fulfill( jsonRoute({ members, diff --git a/src/components/topbar/CurrentUserButton.test.ts b/src/components/topbar/CurrentUserButton.test.ts index 610870a0bf8..4403b9648b0 100644 --- a/src/components/topbar/CurrentUserButton.test.ts +++ b/src/components/topbar/CurrentUserButton.test.ts @@ -88,6 +88,20 @@ vi.mock('@/platform/workspace/components/WorkspaceProfilePic.vue', () => ({ } })) +const CurrentUserPopoverWorkspaceStub = defineComponent({ + name: 'CurrentUserPopoverWorkspace', + props: { + accountActionsOnly: Boolean + }, + setup(props) { + return () => + h('div', [ + h('span', 'Workspace Popover Content'), + props.accountActionsOnly ? h('span', 'Account Actions Only') : '' + ]) + } +}) + // Mock the CurrentUserPopoverLegacy component vi.mock('./CurrentUserPopoverLegacy.vue', () => ({ default: defineComponent({ @@ -96,7 +110,7 @@ vi.mock('./CurrentUserPopoverLegacy.vue', () => ({ setup(_, { emit }) { return () => h('div', [ - 'Popover Content', + h('span', 'Popover Content'), h( 'button', { @@ -132,6 +146,7 @@ describe('CurrentUserButton', () => { global: { plugins: [i18n], stubs: { + CurrentUserPopoverWorkspace: CurrentUserPopoverWorkspaceStub, Popover: defineComponent({ setup(_, { slots, expose }) { const shown = ref(false) @@ -170,6 +185,21 @@ describe('CurrentUserButton', () => { expect(screen.getByText('Popover Content')).toBeInTheDocument() }) + it.for(['loading', 'error'])( + 'shows account actions while Cloud workspace initialization is %s', + async (initState) => { + mockIsCloud.value = true + mockFeatureFlags.teamWorkspacesEnabled = true + mockTeamWorkspaceStore.initState.value = initState + const { user } = renderComponent() + + await user.click(screen.getByRole('button', { name: 'Current user' })) + + expect(screen.getByText('Workspace Popover Content')).toBeInTheDocument() + expect(screen.getByText('Account Actions Only')).toBeInTheDocument() + } + ) + it('hides popover when closePopover is called', async () => { const { user } = renderComponent() diff --git a/src/components/topbar/CurrentUserButton.vue b/src/components/topbar/CurrentUserButton.vue index 22840928205..47c2c5988d8 100644 --- a/src/components/topbar/CurrentUserButton.vue +++ b/src/components/topbar/CurrentUserButton.vue @@ -48,17 +48,13 @@ }" @show="onPopoverShow" > - - - + diff --git a/src/locales/en/main.json b/src/locales/en/main.json index e3e847edf7e..e714db027bb 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -4624,6 +4624,10 @@ "switchFailed": "Failed to switch workspace. Please try again." }, "workspaceAuth": { + "initializationFailed": "Couldn't load your workspace", + "initializationFailedDetail": "Check your connection and try again.", + "initializationFailedSignOutDetail": "Sign out and log in again to continue.", + "retry": "Try again", "errors": { "notAuthenticated": "You must be logged in to access workspaces", "invalidFirebaseToken": "Authentication failed. Please try logging in again.", diff --git a/src/platform/remoteConfig/refreshRemoteConfig.test.ts b/src/platform/remoteConfig/refreshRemoteConfig.test.ts index 53a5fde8b8f..4fce51679e8 100644 --- a/src/platform/remoteConfig/refreshRemoteConfig.test.ts +++ b/src/platform/remoteConfig/refreshRemoteConfig.test.ts @@ -3,7 +3,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { api } from '@/scripts/api' import { refreshRemoteConfig } from './refreshRemoteConfig' -import { remoteConfig } from './remoteConfig' +import { + remoteConfig, + remoteConfigErrorStatus, + remoteConfigState +} from './remoteConfig' vi.mock('@/scripts/api', () => ({ api: { @@ -17,7 +21,7 @@ vi.stubGlobal('fetch', vi.fn()) describe('refreshRemoteConfig', () => { const mockConfig = { feature1: true, feature2: 'value' } - function mockSuccessResponse(config = mockConfig) { + function mockSuccessResponse(config: Record = mockConfig) { return { ok: true, json: async () => config @@ -33,8 +37,11 @@ describe('refreshRemoteConfig', () => { } beforeEach(() => { - vi.clearAllMocks() + vi.mocked(api.fetchApi).mockReset() + vi.mocked(global.fetch).mockReset() remoteConfig.value = {} + remoteConfigErrorStatus.value = null + remoteConfigState.value = 'unloaded' window.__CONFIG__ = {} }) @@ -62,13 +69,70 @@ describe('refreshRemoteConfig', () => { expect(global.fetch).not.toHaveBeenCalled() }) - it('does not pass an abort signal on the authed branch (so it is never aborted)', async () => { + it('passes an AbortSignal on the authenticated branch', async () => { vi.mocked(api.fetchApi).mockResolvedValue(mockSuccessResponse()) await refreshRemoteConfig({ useAuth: true }) const init = vi.mocked(api.fetchApi).mock.calls[0][1] - expect(init?.signal).toBeUndefined() + expect(init?.signal).toBeInstanceOf(AbortSignal) + }) + + it('discards a failed response from a superseded refresh', async () => { + let resolveFirst: ((response: Response) => void) | undefined + vi.mocked(api.fetchApi) + .mockImplementationOnce( + () => + new Promise((resolve) => { + resolveFirst = resolve + }) + ) + .mockResolvedValueOnce( + mockSuccessResponse({ subscription_required: true }) + ) + + const firstRefresh = refreshRemoteConfig({ useAuth: true }) + await vi.waitFor(() => expect(api.fetchApi).toHaveBeenCalledTimes(1)) + await refreshRemoteConfig({ useAuth: true }) + resolveFirst?.(mockErrorResponse(401, 'Unauthorized')) + await firstRefresh + + expect(remoteConfig.value).toEqual({ subscription_required: true }) + expect(remoteConfigState.value).toBe('authenticated') + expect(remoteConfigErrorStatus.value).toBeNull() + }) + + it('preserves shared state when the caller cancels the refresh', async () => { + const existingConfig = { subscription_required: true } + remoteConfig.value = existingConfig + remoteConfigState.value = 'authenticated' + remoteConfigErrorStatus.value = 500 + window.__CONFIG__ = existingConfig + vi.mocked(api.fetchApi).mockImplementation( + (_route, options) => + new Promise((_, reject) => { + if (options?.signal?.aborted) { + reject(new DOMException('Aborted', 'AbortError')) + return + } + options?.signal?.addEventListener('abort', () => { + reject(new DOMException('Aborted', 'AbortError')) + }) + }) + ) + const controller = new AbortController() + + const refresh = refreshRemoteConfig({ + useAuth: true, + signal: controller.signal + }) + controller.abort() + await refresh + + expect(remoteConfig.value).toEqual(existingConfig) + expect(remoteConfigState.value).toBe('authenticated') + expect(remoteConfigErrorStatus.value).toBe(500) + expect(window.__CONFIG__).toEqual(existingConfig) }) }) @@ -156,6 +220,8 @@ describe('refreshRemoteConfig', () => { expect(remoteConfig.value).toEqual(existingConfig) expect(window.__CONFIG__).toEqual(existingConfig) + expect(remoteConfigState.value).toBe('error') + expect(remoteConfigErrorStatus.value).toBeNull() }) }) }) diff --git a/src/platform/remoteConfig/refreshRemoteConfig.ts b/src/platform/remoteConfig/refreshRemoteConfig.ts index 441e6a4e205..6bf56352909 100644 --- a/src/platform/remoteConfig/refreshRemoteConfig.ts +++ b/src/platform/remoteConfig/refreshRemoteConfig.ts @@ -4,6 +4,7 @@ import { cachedTeamWorkspacesEnabled, cachedV1PaymentRecovery, remoteConfig, + remoteConfigErrorStatus, remoteConfigState } from './remoteConfig' @@ -18,8 +19,11 @@ interface RefreshRemoteConfigOptions { * Set to false during bootstrap before auth is initialized. */ useAuth?: boolean + signal?: AbortSignal } +let refreshGeneration = 0 + async function fetchRemoteConfig( useAuth: boolean, signal?: AbortSignal @@ -28,7 +32,7 @@ async function fetchRemoteConfig( if (!useAuth) { return fetch(api.apiURL('/features'), { cache: 'no-store', signal }) } - return api.fetchApi('/features', { cache: 'no-store' }) + return api.fetchApi('/features', { cache: 'no-store', signal }) } /** @@ -43,20 +47,30 @@ async function fetchRemoteConfig( export async function refreshRemoteConfig( options: RefreshRemoteConfigOptions = {} ): Promise { - const { useAuth = true } = options + const { useAuth = true, signal } = options + const generation = ++refreshGeneration + const controller = new AbortController() + const abort = () => controller.abort() + signal?.addEventListener('abort', abort, { once: true }) + if (signal?.aborted) abort() - const controller = useAuth ? null : new AbortController() - const timeoutId = controller - ? setTimeout(() => controller.abort(), FEATURES_FETCH_TIMEOUT_MS) - : null + const timeoutId = setTimeout( + () => controller.abort(), + FEATURES_FETCH_TIMEOUT_MS + ) try { - const response = await fetchRemoteConfig(useAuth, controller?.signal) + const response = await fetchRemoteConfig(useAuth, controller.signal) + if (generation !== refreshGeneration) return + if (signal?.aborted) return if (response.ok) { const config = await response.json() + if (generation !== refreshGeneration) return + if (signal?.aborted) return window.__CONFIG__ = config remoteConfig.value = config + remoteConfigErrorStatus.value = null remoteConfigState.value = useAuth ? 'authenticated' : 'anonymous' if (useAuth) { cachedTeamWorkspacesEnabled.value = Boolean( @@ -77,14 +91,21 @@ export async function refreshRemoteConfig( if (response.status === 401 || response.status === 403) { window.__CONFIG__ = {} remoteConfig.value = {} - remoteConfigState.value = 'error' + remoteConfigErrorStatus.value = response.status + } else { + remoteConfigErrorStatus.value = null } + remoteConfigState.value = 'error' } catch (error) { + if (generation !== refreshGeneration) return + if (signal?.aborted) return console.error('Failed to fetch remote config:', error) window.__CONFIG__ = {} remoteConfig.value = {} + remoteConfigErrorStatus.value = null remoteConfigState.value = 'error' } finally { - if (timeoutId !== null) clearTimeout(timeoutId) + clearTimeout(timeoutId) + signal?.removeEventListener('abort', abort) } } diff --git a/src/platform/remoteConfig/remoteConfig.ts b/src/platform/remoteConfig/remoteConfig.ts index 11f129d85f2..0a3a3abe5ca 100644 --- a/src/platform/remoteConfig/remoteConfig.ts +++ b/src/platform/remoteConfig/remoteConfig.ts @@ -32,6 +32,8 @@ type RemoteConfigState = 'unloaded' | 'anonymous' | 'authenticated' | 'error' */ export const remoteConfigState = ref('unloaded') +export const remoteConfigErrorStatus = ref(null) + /** * Whether the authenticated config has been loaded. * Use this to gate access to user-specific feature flags like teamWorkspacesEnabled. diff --git a/src/platform/settings/composables/useSettingUI.test.ts b/src/platform/settings/composables/useSettingUI.test.ts index 8f1cd7ecfaa..0d267f22028 100644 --- a/src/platform/settings/composables/useSettingUI.test.ts +++ b/src/platform/settings/composables/useSettingUI.test.ts @@ -199,6 +199,16 @@ describe('useSettingUI', () => { expect(defaultCategory.value).toBe(settingCategories.value[0]) }) + it('hides the empty Workspace navigation group for logged-out Cloud users', () => { + env.state.isCloud = true + env.state.isLoggedIn = false + env.state.teamWorkspacesEnabled = true + + const { navGroups } = useSettingUI() + + expect(navGroups.value.map(({ title }) => title)).not.toContain('Workspace') + }) + it('gives defaultPanel precedence over scrollToSettingId', () => { const { defaultCategory } = useSettingUI('about', 'Comfy.Locale') expect(defaultCategory.value.key).toBe('about') diff --git a/src/platform/settings/composables/useSettingUI.ts b/src/platform/settings/composables/useSettingUI.ts index 60bd2103cab..ac9bae324c7 100644 --- a/src/platform/settings/composables/useSettingUI.ts +++ b/src/platform/settings/composables/useSettingUI.ts @@ -438,23 +438,25 @@ export function useSettingUI( ) const navGroups = computed(() => - groupedMenuTreeNodes.value.map((group) => ({ - title: - (group as SettingTreeNode & { translatedLabel?: string }) - .translatedLabel ?? group.label, - items: (group.children ?? []).map((child) => ({ - id: child.key, - label: - (child as SettingTreeNode & { translatedLabel?: string }) - .translatedLabel ?? child.label, - icon: - child.key === 'workspace' && billingControlsEnabled.value - ? CATEGORY_ICONS.PlanCredits - : (CATEGORY_ICONS[child.key] ?? - CATEGORY_ICONS[child.label] ?? - 'icon-[lucide--plug]') + groupedMenuTreeNodes.value + .filter((group) => group.children?.length) + .map((group) => ({ + title: + (group as SettingTreeNode & { translatedLabel?: string }) + .translatedLabel ?? group.label, + items: (group.children ?? []).map((child) => ({ + id: child.key, + label: + (child as SettingTreeNode & { translatedLabel?: string }) + .translatedLabel ?? child.label, + icon: + child.key === 'workspace' && billingControlsEnabled.value + ? CATEGORY_ICONS.PlanCredits + : (CATEGORY_ICONS[child.key] ?? + CATEGORY_ICONS[child.label] ?? + 'icon-[lucide--plug]') + })) })) - })) ) function findCategoryByKey(key: string): SettingTreeNode | null { diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts index e52fde46ab6..81be966951d 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts +++ b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts @@ -1,8 +1,11 @@ import { render, screen } from '@testing-library/vue' +import userEvent from '@testing-library/user-event' import { beforeEach, describe, expect, it, vi } from 'vitest' import { ref } from 'vue' import { createI18n } from 'vue-i18n' +import enMessages from '@/locales/en/main.json' with { type: 'json' } + import WorkspaceAuthGate from './WorkspaceAuthGate.vue' async function flushPromises() { @@ -16,6 +19,7 @@ vi.mock('@sentry/vue', () => ({ const mockIsInitialized = ref(false) const mockCurrentUser = ref(null) +const mockLogout = vi.fn() vi.mock('@/stores/authStore', () => ({ useAuthStore: () => ({ @@ -24,6 +28,10 @@ vi.mock('@/stores/authStore', () => ({ }) })) +vi.mock('@/composables/auth/useAuthActions', () => ({ + useAuthActions: () => ({ logout: mockLogout }) +})) + const mockRefreshRemoteConfig = vi.fn() vi.mock('@/platform/remoteConfig/refreshRemoteConfig', () => ({ refreshRemoteConfig: (options: unknown) => mockRefreshRemoteConfig(options) @@ -36,8 +44,12 @@ const mockRemoteConfigState = vi.hoisted(() => ({ | 'authenticated' | 'error' })) +const mockRemoteConfigErrorStatus = vi.hoisted(() => ({ + value: null as number | null +})) vi.mock('@/platform/remoteConfig/remoteConfig', () => ({ - remoteConfigState: mockRemoteConfigState + remoteConfigState: mockRemoteConfigState, + remoteConfigErrorStatus: mockRemoteConfigErrorStatus })) const mockTeamWorkspacesEnabled = vi.hoisted(() => ({ value: false })) @@ -113,6 +125,7 @@ describe('WorkspaceAuthGate', () => { mockTeamWorkspacesEnabled.value = false mockUnifiedCloudAuthEnabled.value = false mockRemoteConfigState.value = 'authenticated' + mockRemoteConfigErrorStatus.value = null mockWorkspaceStoreInitState.value = 'uninitialized' mockActiveWorkspaceId.value = 'workspace-123' mockRefreshRemoteConfig.mockResolvedValue(undefined) @@ -123,7 +136,11 @@ describe('WorkspaceAuthGate', () => { mockGetUnifiedToken.mockReturnValue('cloud-jwt') }) - const i18n = createI18n({ legacy: false }) + const i18n = createI18n({ + legacy: false, + locale: 'en', + messages: { en: enMessages } + }) const mountComponent = () => render(WorkspaceAuthGate, { @@ -167,6 +184,22 @@ describe('WorkspaceAuthGate', () => { expect(screen.getByTestId('slot-content')).toBeInTheDocument() expect(mockRefreshRemoteConfig).not.toHaveBeenCalled() }) + + it('shows the recovery panel when Firebase initialization times out', async () => { + vi.useFakeTimers() + try { + mountComponent() + + await vi.advanceTimersByTimeAsync(16_001) + + expect( + screen.getByText("Couldn't load your workspace") + ).toBeInTheDocument() + expect(mockCaptureException).toHaveBeenCalledOnce() + } finally { + vi.useRealTimers() + } + }) }) describe('cloud builds - authenticated user', () => { @@ -179,7 +212,10 @@ describe('WorkspaceAuthGate', () => { mountComponent() await flushPromises() - expect(mockRefreshRemoteConfig).toHaveBeenCalledWith({ useAuth: true }) + expect(mockRefreshRemoteConfig).toHaveBeenCalledWith({ + useAuth: true, + signal: expect.any(AbortSignal) + }) }) it('renders slot when teamWorkspacesEnabled is false', async () => { @@ -214,6 +250,31 @@ describe('WorkspaceAuthGate', () => { expect(screen.getByTestId('slot-content')).toBeInTheDocument() }) + it('stops initialization when unmounted', async () => { + let resolveRefresh: (() => void) | undefined + mockTeamWorkspacesEnabled.value = true + mockRefreshRemoteConfig.mockImplementation( + () => + new Promise((resolve) => { + resolveRefresh = resolve + }) + ) + + const { unmount } = mountComponent() + await vi.waitFor(() => + expect(mockRefreshRemoteConfig).toHaveBeenCalledOnce() + ) + const signal = mockRefreshRemoteConfig.mock.calls[0][0].signal + unmount() + resolveRefresh?.() + await flushPromises() + + expect(signal.aborted).toBe(true) + expect(mockWorkspaceStoreInitialize).not.toHaveBeenCalled() + expect(mockResumePendingPricingFlow).not.toHaveBeenCalled() + expect(mockCaptureException).not.toHaveBeenCalled() + }) + it('calls resumePendingPricingFlow after successful workspace init', async () => { mockTeamWorkspacesEnabled.value = true mockWorkspaceStoreInitState.value = 'ready' @@ -242,14 +303,24 @@ describe('WorkspaceAuthGate', () => { mockCurrentUser.value = { uid: 'user-123' } }) - it('keeps the app gated when remote config refresh fails', async () => { + it('shows a recoverable error when remote config refresh fails', async () => { const error = new Error('Network error') mockRefreshRemoteConfig.mockRejectedValue(error) + const splashLoader = document.createElement('div') + splashLoader.id = 'splash-loader' + document.body.append(splashLoader) mountComponent() await flushPromises() - expect(screen.queryByTestId('slot-content')).not.toBeInTheDocument() + expect( + screen.getByText("Couldn't load your workspace") + ).toBeInTheDocument() + expect( + screen.getByRole('button', { name: 'Try again' }) + ).toBeInTheDocument() + expect(screen.getByRole('alert')).toHaveFocus() + expect(splashLoader).not.toBeInTheDocument() expect(mockCaptureException).toHaveBeenCalledWith(error, { tags: { error_type: 'workspace_auth_gate_initialization_failure' @@ -257,7 +328,7 @@ describe('WorkspaceAuthGate', () => { }) }) - it('keeps the app gated when remote config refresh times out', async () => { + it('shows a recoverable error when remote config refresh times out', async () => { vi.useFakeTimers() try { // Never-resolving promise simulates a hanging request @@ -268,37 +339,67 @@ describe('WorkspaceAuthGate', () => { // Slot not yet rendered before timeout expect(screen.queryByTestId('slot-content')).not.toBeInTheDocument() + expect( + screen.queryByText("Couldn't load your workspace") + ).not.toBeInTheDocument() // Advance past the 10 second timeout await vi.advanceTimersByTimeAsync(10_001) - expect(screen.queryByTestId('slot-content')).not.toBeInTheDocument() + expect( + screen.getByText("Couldn't load your workspace") + ).toBeInTheDocument() } finally { vi.useRealTimers() } }) - it('keeps the app gated when authenticated config is unavailable', async () => { + it('shows a recoverable error when authenticated config is unavailable', async () => { + mockTeamWorkspacesEnabled.value = true mockRemoteConfigState.value = 'error' mountComponent() await flushPromises() - expect(screen.queryByTestId('slot-content')).not.toBeInTheDocument() + expect( + screen.getByText("Couldn't load your workspace") + ).toBeInTheDocument() + expect(mockWorkspaceStoreInitialize).not.toHaveBeenCalled() }) - it('keeps the app gated when unified auth initialization fails', async () => { + it('requires sign out when authenticated config rejects the credential', async () => { + const user = userEvent.setup() + mockRemoteConfigState.value = 'error' + mockRemoteConfigErrorStatus.value = 401 + + mountComponent() + await flushPromises() + + expect( + screen.queryByRole('button', { name: 'Try again' }) + ).not.toBeInTheDocument() + expect( + screen.getByText('Sign out and log in again to continue.') + ).toBeInTheDocument() + + await user.click(screen.getByRole('button', { name: 'Log Out' })) + expect(mockLogout).toHaveBeenCalledOnce() + }) + + it('shows a recoverable error when unified auth initialization fails', async () => { mockUnifiedCloudAuthEnabled.value = true mockMintAtLogin.mockResolvedValue(false) mountComponent() await flushPromises() - expect(screen.queryByTestId('slot-content')).not.toBeInTheDocument() + expect( + screen.getByText("Couldn't load your workspace") + ).toBeInTheDocument() expect(mockWorkspaceStoreInitialize).not.toHaveBeenCalled() }) - it('keeps the app gated when workspace store initialization fails', async () => { + it('shows a recoverable error when workspace store initialization fails', async () => { mockTeamWorkspacesEnabled.value = true mockWorkspaceStoreInitialize.mockRejectedValue( new Error('Workspace init failed') @@ -307,10 +408,29 @@ describe('WorkspaceAuthGate', () => { mountComponent() await flushPromises() - expect(screen.queryByTestId('slot-content')).not.toBeInTheDocument() + expect( + screen.getByText("Couldn't load your workspace") + ).toBeInTheDocument() + }) + + it('requires sign out when no workspace is available', async () => { + mockTeamWorkspacesEnabled.value = true + mockWorkspaceStoreInitialize.mockRejectedValue( + new Error('No workspaces available') + ) + + mountComponent() + await flushPromises() + + expect( + screen.queryByRole('button', { name: 'Try again' }) + ).not.toBeInTheDocument() + expect( + screen.getByRole('button', { name: 'Log Out' }) + ).toBeInTheDocument() }) - it('keeps the app gated when workspace setup clears unified auth', async () => { + it('shows a recoverable error when workspace setup clears unified auth', async () => { mockUnifiedCloudAuthEnabled.value = true mockTeamWorkspacesEnabled.value = true mockGetUnifiedToken.mockReturnValue(undefined) @@ -318,17 +438,93 @@ describe('WorkspaceAuthGate', () => { mountComponent() await flushPromises() - expect(screen.queryByTestId('slot-content')).not.toBeInTheDocument() + expect( + screen.getByText("Couldn't load your workspace") + ).toBeInTheDocument() }) - it('keeps the app gated without a ready workspace context', async () => { + it('shows a recoverable error without a ready workspace context', async () => { mockTeamWorkspacesEnabled.value = true mockWorkspaceStoreInitState.value = 'loading' mountComponent() await flushPromises() - expect(screen.queryByTestId('slot-content')).not.toBeInTheDocument() + expect( + screen.getByText("Couldn't load your workspace") + ).toBeInTheDocument() + }) + + it('renders the app after retrying a failed initialization', async () => { + const user = userEvent.setup() + mockTeamWorkspacesEnabled.value = true + mockWorkspaceStoreInitialize + .mockImplementationOnce(async () => { + mockWorkspaceStoreInitState.value = 'error' + throw new Error('Workspace init failed') + }) + .mockImplementationOnce(async () => { + mockWorkspaceStoreInitState.value = 'ready' + }) + + mountComponent() + await flushPromises() + await user.click(screen.getByRole('button', { name: 'Try again' })) + await flushPromises() + + expect(screen.getByTestId('slot-content')).toBeInTheDocument() + expect(mockWorkspaceStoreInitialize).toHaveBeenCalledTimes(2) + }) + + it('keeps the retry action named while retrying', async () => { + const user = userEvent.setup() + let resolveRetry: (() => void) | undefined + mockRefreshRemoteConfig + .mockRejectedValueOnce(new Error('Network error')) + .mockImplementationOnce( + () => + new Promise((resolve) => { + resolveRetry = resolve + }) + ) + + mountComponent() + await flushPromises() + await user.click(screen.getByRole('button', { name: 'Try again' })) + + expect(screen.getByRole('button', { name: 'Try again' })).toHaveAttribute( + 'aria-busy', + 'true' + ) + + resolveRetry?.() + }) + + it('stops a pending retry before logging out', async () => { + const user = userEvent.setup() + let resolveRetry: (() => void) | undefined + mockTeamWorkspacesEnabled.value = true + mockRefreshRemoteConfig + .mockRejectedValueOnce(new Error('Network error')) + .mockImplementationOnce( + () => + new Promise((resolve) => { + resolveRetry = resolve + }) + ) + + mountComponent() + await flushPromises() + await user.click(screen.getByRole('button', { name: 'Try again' })) + const retrySignal = mockRefreshRemoteConfig.mock.calls[1][0].signal + await user.click(screen.getByRole('button', { name: 'Log Out' })) + resolveRetry?.() + await flushPromises() + + expect(retrySignal.aborted).toBe(true) + expect(mockLogout).toHaveBeenCalledOnce() + expect(mockWorkspaceStoreInitialize).not.toHaveBeenCalled() + expect(mockResumePendingPricingFlow).not.toHaveBeenCalled() }) }) }) diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.vue b/src/platform/workspace/auth/WorkspaceAuthGate.vue index d1bf54388d8..bf10e8c9fb8 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.vue +++ b/src/platform/workspace/auth/WorkspaceAuthGate.vue @@ -1,5 +1,44 @@ diff --git a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts index 1980902b09a..8910e239ad2 100644 --- a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts +++ b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts @@ -121,9 +121,11 @@ function createWorkspaceState( function renderComponent( type: 'personal' | 'team' = 'personal', - role: 'owner' | 'member' = 'member' + role: 'owner' | 'member' = 'member', + accountActionsOnly = false ) { return render(CurrentUserPopoverWorkspace, { + props: { accountActionsOnly }, global: { plugins: [ createTestingPinia({ @@ -182,6 +184,20 @@ describe('CurrentUserPopoverWorkspace', () => { ).not.toBeInTheDocument() }) + it('keeps account actions available without workspace context', () => { + renderComponent('personal', 'member', true) + + expect(screen.getByTestId('user-settings-menu-item')).toBeInTheDocument() + expect(screen.getByTestId('logout-menu-item')).toBeInTheDocument() + expect( + screen.queryByTestId('workspace-switcher-trigger') + ).not.toBeInTheDocument() + expect(screen.queryByTestId('credits-info-button')).not.toBeInTheDocument() + expect( + screen.queryByTestId('workspace-settings-menu-item') + ).not.toBeInTheDocument() + }) + it('exposes the full workspace name on hover', async () => { const user = userEvent.setup() renderComponent('team', 'member') diff --git a/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue b/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue index e5ed924182f..d28adf17494 100644 --- a/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue +++ b/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue @@ -25,7 +25,7 @@ -
+
-
+
- +
- +
() +const { accountActionsOnly = false } = defineProps<{ + accountActionsOnly?: boolean +}>() + const { buildDocsUrl, docsPaths } = useExternalLink() const { userDisplayName, userEmail, userPhotoUrl, handleSignOut } = @@ -365,7 +371,7 @@ const toggleWorkspaceSwitcher = () => { } const refreshBalance = () => { - void fetchBalance() + if (!accountActionsOnly) void fetchBalance() } defineExpose({ refreshBalance }) diff --git a/src/platform/workspace/stores/teamWorkspaceStore.test.ts b/src/platform/workspace/stores/teamWorkspaceStore.test.ts index a30cb071cac..c83841b9f41 100644 --- a/src/platform/workspace/stores/teamWorkspaceStore.test.ts +++ b/src/platform/workspace/stores/teamWorkspaceStore.test.ts @@ -317,6 +317,20 @@ describe('useTeamWorkspaceStore', () => { expect(mockWorkspaceApi.list).toHaveBeenCalledTimes(1) }) + it('can retry after initialization fails', async () => { + mockWorkspaceApi.list.mockResolvedValueOnce({ workspaces: [] }) + const store = useTeamWorkspaceStore() + + await expect(store.initialize()).rejects.toThrow( + 'No workspaces available' + ) + await store.initialize() + + expect(store.initState).toBe('ready') + expect(store.activeWorkspaceId).toBe(mockPersonalWorkspace.id) + expect(mockWorkspaceApi.list).toHaveBeenCalledTimes(2) + }) + it('can initialize the next user after identity state is reset', async () => { const store = useTeamWorkspaceStore() await store.initialize() diff --git a/src/platform/workspace/stores/teamWorkspaceStore.ts b/src/platform/workspace/stores/teamWorkspaceStore.ts index 5791b3df430..6eb1ca0cae1 100644 --- a/src/platform/workspace/stores/teamWorkspaceStore.ts +++ b/src/platform/workspace/stores/teamWorkspaceStore.ts @@ -270,7 +270,8 @@ export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { * Call once on app boot. */ async function initialize(): Promise { - if (initState.value !== 'uninitialized') return + if (initState.value !== 'uninitialized' && initState.value !== 'error') + return const generation = identityGeneration initState.value = 'loading'