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
51 changes: 51 additions & 0 deletions browser_tests/fixtures/data/workspaceAuthFixtures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import type { RemoteConfig } from '@/platform/remoteConfig/types'
import type { WorkspaceWithRole } from '@/platform/workspace/api/workspaceApi'

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WorkspaceWithRole is imported from @/platform/workspace/api/workspaceApi, but workspaceAuthStore imports it from @/platform/workspace/workspaceTypes — these are two structurally similar but distinct interfaces. workspaceApi's version adds created_at, joined_at, and an optional subscription_tier; the store's zod schema only validates id, name, type, role.

The fixture objects should be typed against the canonical interface that the store actually works with (workspaceTypes.WorkspaceWithRole), not the richer API response type. Using the wrong type means the compiler will accept extra fields that the store will silently ignore, and a future field divergence between the two interfaces won't be caught here.

import type { WorkspaceTokenResponse } from '@/platform/workspace/stores/workspaceAuthStore'

export const mockWorkspacesRemoteConfig: RemoteConfig = {
team_workspaces_enabled: true
}

export const mockPersonalWorkspace: WorkspaceWithRole = {
id: 'ws-personal',
name: 'Personal Workspace',
type: 'personal',
created_at: '2026-01-01T00:00:00Z',
joined_at: '2026-01-01T00:00:00Z',
role: 'owner'
}

export const mockTeamWorkspace: WorkspaceWithRole = {
id: 'ws-team',
name: 'Team Workspace',
type: 'team',
created_at: '2026-01-02T00:00:00Z',
joined_at: '2026-01-02T00:00:00Z',
role: 'member'
}

export function makeWorkspaceTokenResponse(
workspace: WorkspaceWithRole,
token: string,
expiresInMs = 60 * 60 * 1000
): WorkspaceTokenResponse {
return {
token,
expires_at: new Date(Date.now() + expiresInMs).toISOString(),
workspace: {
id: workspace.id,
name: workspace.name,
type: workspace.type
},
role: workspace.role,
permissions: []
}
}

// On app boot, teamWorkspaceStore.initialize() auto-selects Personal Workspace
// and calls switchWorkspace → /api/auth/token. This default response absorbs
// that init call so per-test mocks only see explicit switches.
export const defaultWorkspaceTokenResponse = makeWorkspaceTokenResponse(
mockPersonalWorkspace,
'init-token'
)
69 changes: 69 additions & 0 deletions browser_tests/fixtures/helpers/WorkspaceAuthHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { expect } from '@playwright/test'
import type { Page, Route } from '@playwright/test'

import {
defaultWorkspaceTokenResponse,
mockPersonalWorkspace,
mockTeamWorkspace,
mockWorkspacesRemoteConfig
} from '@e2e/fixtures/data/workspaceAuthFixtures'

export class WorkspaceAuthHelper {
constructor(private readonly page: Page) {}

async mockWorkspaceRoutes(): Promise<void> {
await this.page.route('**/api/features', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(mockWorkspacesRemoteConfig)
})
)

await this.page.route('**/api/workspaces', async (route) => {
if (route.request().method() !== 'GET') {
await route.fallback()
return
}
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
workspaces: [mockPersonalWorkspace, mockTeamWorkspace]
})
})
})

// Default stub for the init-time auto-switch. Per-test mocks added via
// mockTokenRoute() take priority (Playwright matches routes LIFO).
await this.page.route('**/api/auth/token', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(defaultWorkspaceTokenResponse)
})
)

await this.page.route('**/api/auth/session', (route) =>
route.fulfill({ status: 204 })
)
}

async mockTokenRoute(
handler: (route: Route) => void | Promise<void>
): Promise<void> {
await this.page.route('**/api/auth/token', handler)
}

// Opens the profile popover then the workspace-switcher panel.
// useWorkspaceSwitch skips switchWorkspace when the target is already active,
// so always switch to a workspace other than the auto-selected Personal one.
async openSwitcherPanel(): Promise<void> {
await this.page.keyboard.press('Escape')
await this.page.getByRole('button', { name: 'Current user' }).click()
await this.page.getByTestId('workspace-switcher-trigger').click()
await expect(
this.page.getByTestId('workspace-switcher-panel')
).toBeVisible()
}
}
181 changes: 181 additions & 0 deletions browser_tests/tests/workspaceAuthRefresh.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
import { expect } from '@playwright/test'

import { comfyPageFixture } from '@e2e/fixtures/ComfyPage'
import {
makeWorkspaceTokenResponse,
mockTeamWorkspace
} from '@e2e/fixtures/data/workspaceAuthFixtures'
import { WorkspaceAuthHelper } from '@e2e/fixtures/helpers/WorkspaceAuthHelper'

const test = comfyPageFixture.extend<{ workspaceAuth: WorkspaceAuthHelper }>({

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two separate WorkspaceAuthHelper instances are created for every test — one in the page fixture override (used only to call mockWorkspaceRoutes) and a second one exposed as workspaceAuth. The page fixture helper is created, used once, and immediately discarded. Cleaner to call mockWorkspaceRoutes inside the workspaceAuth fixture itself and yield the same instance:

const test = comfyPageFixture.extend<{ workspaceAuth: WorkspaceAuthHelper }>({
  workspaceAuth: async ({ page }, use) => {
    const helper = new WorkspaceAuthHelper(page)
    await helper.mockWorkspaceRoutes()
    await use(helper)
  }
})

This removes the page override entirely and avoids the implicit coupling where page must be listed before workspaceAuth in the fixture order.

page: async ({ page }, use) => {
const helper = new WorkspaceAuthHelper(page)
await helper.mockWorkspaceRoutes()
await use(page)
},
workspaceAuth: async ({ page }, use) => {
await use(new WorkspaceAuthHelper(page))
}
})

test.describe('Workspace auth refresh', { tag: '@cloud' }, () => {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PR description promises 4 tests but the spec only has 3. The "switching to a different workspace replaces sessionStorage token" case is missing. That test is valuable because it verifies refreshRequestId is bumped on a second switch, preventing a stale first-workspace token from being written back after the second switch completes.

test('token is persisted to sessionStorage after switching workspace', async ({
comfyPage,
workspaceAuth
}) => {
const page = comfyPage.page

await workspaceAuth.mockTokenRoute((route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(
makeWorkspaceTokenResponse(mockTeamWorkspace, 'team-token')
)
})
)

await comfyPage.toast.closeToasts()
await workspaceAuth.openSwitcherPanel()
await page
.getByTestId('workspace-switcher-panel')
.getByText('Team Workspace')
.click()

await expect
.poll(
() =>
page.evaluate(() => sessionStorage.getItem('Comfy.Workspace.Token')),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Storage key strings are hardcoded here ("Comfy.Workspace.Token", "Comfy.Workspace.ExpiresAt", "Comfy.Workspace.Current") rather than referencing WORKSPACE_STORAGE_KEYS from workspaceConstants.ts. If a key is ever renamed, the test will silently pass while testing nothing. Import and use the constants:

import { WORKSPACE_STORAGE_KEYS } from '@/platform/workspace/workspaceConstants'

// then e.g.
page.evaluate(
  (key) => sessionStorage.getItem(key),
  WORKSPACE_STORAGE_KEYS.TOKEN
)

{ timeout: 5000 }
)
.toBe('team-token')

const expiresAt = await page.evaluate(() =>
sessionStorage.getItem('Comfy.Workspace.ExpiresAt')
)
expect(Number(expiresAt)).toBeGreaterThan(Date.now())
})

test('transient token refresh failure preserves the active workspace session', async ({
comfyPage,
workspaceAuth
}) => {
const page = comfyPage.page

// TOKEN_REFRESH_BUFFER_MS is 5 minutes. Setting expiresInMs just below the
// buffer means scheduleTokenRefresh computes delay ≈ 0 and fires immediately.
const expiresInMs = 5 * 60 * 1000 - 500

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

5 * 60 * 1000 - 500 is a magic literal copy of TOKEN_REFRESH_BUFFER_MS minus 500 ms — duplicated in both refresh tests. If the constant ever changes the tests will silently stop triggering the near-expiry path they are designed to exercise.

import { TOKEN_REFRESH_BUFFER_MS } from '@/platform/workspace/workspaceConstants'

const expiresInMs = TOKEN_REFRESH_BUFFER_MS - 500

let callCount = 0

await workspaceAuth.mockTokenRoute((route) => {
callCount++
if (callCount === 1) {
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(
makeWorkspaceTokenResponse(
mockTeamWorkspace,
'original-token',
expiresInMs
)
)
})
}
return route.fulfill({
status: 500,
contentType: 'application/json',
body: JSON.stringify({ message: 'Internal Server Error' })
})
})

await comfyPage.toast.closeToasts()
await workspaceAuth.openSwitcherPanel()
await page
.getByTestId('workspace-switcher-panel')
.getByText('Team Workspace')
.click()

await expect
.poll(
() =>
page.evaluate(() => sessionStorage.getItem('Comfy.Workspace.Token')),
{ timeout: 5000 }
)
.toBe('original-token')

// The scheduled refresh fires immediately (token expires within buffer window).
// Wait for the second route call (the failing refresh) to complete, then verify
// the token is preserved — a transient 500 must not clear the session.
await expect
.poll(() => callCount, { timeout: 5000 })

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

callCount >= 2 is the threshold for the token having settled, but refreshToken() has an internal retry loop (maxRetries = 3, exponential back-off 1 s / 2 s / 4 s) that calls switchWorkspace — and therefore the route — up to 4 times total before falling through to the "preserve token" path. The 500 case here is classified as TOKEN_EXCHANGE_FAILED (a transient error), so those retries will actually fire. In CI the extra await at callCount >= 2 may complete before the third or fourth attempt lands, meaning the final expect(...).toBe('original-token') runs against the wrong intermediate state.

Consider tracking resolveRefreshSettled with a Promise that the handler fulfills after the last response has been dispatched, or wait for the retry loop to fully exhaust (e.g. callCount >= 4). At minimum, document why 2 is the right threshold given the internal retry count.

.toBeGreaterThanOrEqual(2)

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
expect(
await page.evaluate(() => sessionStorage.getItem('Comfy.Workspace.Token'))
).toBe('original-token')
})

test('permanent auth failure (ACCESS_DENIED) clears the workspace session', async ({
comfyPage,
workspaceAuth
}) => {
const page = comfyPage.page

// TOKEN_REFRESH_BUFFER_MS is 5 minutes. Setting expiresInMs just below the
// buffer means scheduleTokenRefresh computes delay ≈ 0 and fires immediately.
const expiresInMs = 5 * 60 * 1000 - 500
let callCount = 0

await workspaceAuth.mockTokenRoute((route) => {
callCount++
if (callCount === 1) {
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(
makeWorkspaceTokenResponse(
mockTeamWorkspace,
'original-token',
expiresInMs
)
)
})
}
return route.fulfill({
status: 403,
contentType: 'application/json',
body: JSON.stringify({ message: 'Access denied' })
})
})

await comfyPage.toast.closeToasts()
await workspaceAuth.openSwitcherPanel()
await page
.getByTestId('workspace-switcher-panel')
.getByText('Team Workspace')
.click()

// Wait for both the switch (callCount=1) and the immediate refresh (callCount=2)
// to complete. The refresh fires at delay≈0 so token may already be cleared
// before we can assert the intermediate 'original-token' state.
await expect
.poll(() => callCount, { timeout: 5000 })
.toBeGreaterThanOrEqual(2)

// A 403 ACCESS_DENIED response must clear the workspace session entirely.
await expect
.poll(
() =>
page.evaluate(() => sessionStorage.getItem('Comfy.Workspace.Token')),
{ timeout: 5000 }
)
.toBeNull()

expect(
await page.evaluate(() =>
sessionStorage.getItem('Comfy.Workspace.Current')
)
).toBeNull()
})
})
Loading