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
19 changes: 16 additions & 3 deletions browser_tests/fixtures/desktopAgentConsentFixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ declare global {
class DesktopConsentSignIn {
requests = 0
state: ComfyDesktop2AuthState = { status: 'signed_out' }
readonly consentAuthorizationHeaders: string[] = []
private resolve: (state: ComfyDesktop2AuthState) => void = () => {}
private readonly result = new Promise<ComfyDesktop2AuthState>((resolve) => {
this.resolve = resolve
Expand Down Expand Up @@ -47,11 +48,13 @@ export const desktopAgentConsentTest = mergeTests(
webSocketFixture
).extend<{
desktopConsentSignIn: DesktopConsentSignIn
desktopWorkspaceToken: string | null
}>({
desktopConsentSignIn: async ({ browserName: _browserName }, use) => {
await use(new DesktopConsentSignIn())
},
page: async ({ page, desktopConsentSignIn }, use) => {
desktopWorkspaceToken: ['mock-workspace-token', { option: true }],
page: async ({ page, desktopConsentSignIn, desktopWorkspaceToken }, use) => {
await mockWorkspace(page, workspace('personal', 'owner'), [])
await page.exposeFunction('__desktopConsentSignIn', () =>
desktopConsentSignIn.request()
Expand All @@ -60,7 +63,7 @@ export const desktopAgentConsentTest = mergeTests(
'__desktopConsentAuthState',
() => desktopConsentSignIn.state
)
await page.addInitScript(() => {
await page.addInitScript((workspaceToken) => {
let state: ComfyDesktop2AuthState | undefined
const listeners = new Set<(next: ComfyDesktop2AuthState) => void>()
const push = (next: ComfyDesktop2AuthState) => {
Expand All @@ -79,7 +82,7 @@ export const desktopAgentConsentTest = mergeTests(
(state ??= await window.__desktopConsentAuthState()),
getWorkspaceToken: async (workspaceId: string) =>
state?.status === 'signed_in' && state.workspaceId === workspaceId
? 'mock-workspace-token'
? workspaceToken
: null,
requestSignIn: async () => push(await window.__desktopConsentSignIn()),
signOut: async () => push({ status: 'signed_out' }),
Expand All @@ -95,6 +98,16 @@ export const desktopAgentConsentTest = mergeTests(
Auth: auth
}
})
}, desktopWorkspaceToken)
page.on('request', (request) => {
if (
request.method() === 'POST' &&
new URL(request.url()).pathname.endsWith('/api/global-settings')
) {
desktopConsentSignIn.consentAuthorizationHeaders.push(
request.headers()['authorization'] ?? ''
)
}
})
await use(page)
}
Expand Down
69 changes: 69 additions & 0 deletions browser_tests/tests/agent/desktopAgentConsent.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,52 @@ test.describe('Desktop Agent consent', { tag: ['@desktop', '@ui'] }, () => {
})
}

test.describe('without a workspace credential', () => {
test.use({ desktopWorkspaceToken: null })

test('refuses to write consent with the personal credential', async ({
comfyPage,
agentPanel,
desktopConsentSignIn,
agentConsentWrites,
postedMessages
}) => {
const signIn = comfyPage.page.getByTestId('desktop-host-sso')
const message = 'Keep this draft when the workspace credential is missing'
const semanticGraphBefore = await comfyPage.page.evaluate(() =>
JSON.stringify(window.app!.graph.serialize())
)

await agentPanel.consentRejectButton.click()
await agentPanel.composer.fill(message)
await agentPanel.sendButton.click()
await expect(agentPanel.consentDialog).toBeVisible()
await agentPanel.consentDialog
.getByRole('button', {
name: enMessages.agent.consent.agreeAndContinue
})
.click()
await expect(signIn).toBeVisible()
await signIn.click()
await expect.poll(() => desktopConsentSignIn.requests).toBe(1)
desktopConsentSignIn.complete()

await expect(agentPanel.consentDialog).toHaveCount(0)
await expect(agentPanel.root).toBeVisible()
await expect(agentPanel.composer).toBeVisible()
expect(agentConsentWrites).toEqual([])
expect(postedMessages).toEqual([])
expect(desktopConsentSignIn.consentAuthorizationHeaders).toEqual([])
await expect
.poll(() =>
comfyPage.page.evaluate(() =>
JSON.stringify(window.app!.graph.serialize())
)
)
.toBe(semanticGraphBefore)
})
})

test('sends the original signed-out submission once after sign-in and confirmed consent persistence', async ({
comfyPage,
agentPanel,
Expand All @@ -170,6 +216,9 @@ test.describe('Desktop Agent consent', { tag: ['@desktop', '@ui'] }, () => {
}) => {
const signIn = comfyPage.page.getByTestId('desktop-host-sso')
const message = 'Continue this Desktop submission after sign-in'
const semanticGraphBefore = await comfyPage.page.evaluate(() =>
JSON.stringify(window.app!.graph.serialize())
)
let releaseSave = () => {}
agentConsentSave.pending = new Promise<void>((resolve) => {
releaseSave = resolve
Expand Down Expand Up @@ -202,6 +251,16 @@ test.describe('Desktop Agent consent', { tag: ['@desktop', '@ui'] }, () => {
await expect.poll(() => agentConsentWrites).toEqual([true])
await expect(signIn).toHaveCount(0)
await expect(agentPanel.consentDialog).toHaveCount(0)
expect(desktopConsentSignIn.consentAuthorizationHeaders).toEqual([
'Bearer mock-workspace-token'
])
await expect
.poll(() =>
comfyPage.page.evaluate(() =>
JSON.stringify(window.app!.graph.serialize())
)
)
.toBe(semanticGraphBefore)
expect(postedMessages).toEqual([])
})

Expand All @@ -221,6 +280,16 @@ test.describe('Desktop Agent consent', { tag: ['@desktop', '@ui'] }, () => {
await expect(agentPanel.sendButton).toBeVisible()
await expect(agentPanel.consentDialog).toHaveCount(0)
expect(agentConsentWrites).toEqual([true])
expect(desktopConsentSignIn.consentAuthorizationHeaders).toEqual([
'Bearer mock-workspace-token'
])
await expect
.poll(() =>
comfyPage.page.evaluate(() =>
JSON.stringify(window.app!.graph.serialize())
)
)
.toBe(semanticGraphBefore)
expect(postedMessages).toHaveLength(1)
})
} finally {
Expand Down
22 changes: 0 additions & 22 deletions src/platform/settings/globalSettingsApi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'

import type { WebSessionSend } from '@/platform/auth/session/webSessionFetch'
import { api } from '@/scripts/api'
import { useAuthStore } from '@/stores/authStore'

import {
GlobalSettingsApiError,
getGlobalSetting,
getGlobalSettingsAuthHeader,
setGlobalSetting
} from './globalSettingsApi'

Expand Down Expand Up @@ -140,26 +138,6 @@ describe('Global Settings transport', () => {
).rejects.toMatchObject({ status: 500 })
})

it.for([
{ cloud: true, expected: 'Bearer workspace-token' },
{ cloud: false, expected: 'Bearer user-token' }
])(
'authenticates Cloud=$cloud with $expected',
async ({ cloud, expected }) => {
distribution.isCloud = cloud
const authStore = useAuthStore()
vi.mocked(authStore.getWorkspaceAuthHeader).mockResolvedValue({
Authorization: 'Bearer workspace-token'
})
vi.mocked(authStore.getUserAuthHeader).mockResolvedValue({
Authorization: 'Bearer user-token'
})

await expect(getGlobalSettingsAuthHeader()).resolves.toEqual({
Authorization: expected
})
}
)
describe('on the web session', () => {
const unavailable = () => new Response(null, { status: 503 })

Expand Down
8 changes: 0 additions & 8 deletions src/platform/settings/globalSettingsApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import {
import { isCloud } from '@/platform/distribution/types'
import { api } from '@/scripts/api'
import type { WebSessionSend } from '@/platform/auth/session/webSessionFetch'
import { useAuthStore } from '@/stores/authStore'
import type { AuthHeader } from '@/types/authTypes'
import { retryingSend } from '@/utils/fetchWithRetry'

Expand All @@ -32,13 +31,6 @@ function globalSettingsUrl(key?: GlobalSettingKey): string {
return isCloud ? api.apiURL(path) : `${getComfyApiBaseUrl()}/api${path}`
}

export async function getGlobalSettingsAuthHeader(): Promise<AuthHeader | null> {
const authStore = useAuthStore()
return isCloud
? authStore.getWorkspaceAuthHeader()
: authStore.getUserAuthHeader()
}

async function responseBody(response: Response): Promise<unknown> {
try {
return await response.json()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,10 @@ describe('useAgentConsent', () => {
vi.mocked(useAuthStore().getUserAuthHeader).mockResolvedValue({
Authorization: 'Bearer account-a-token'
})
Object.assign(useAuthStore(), { isAuthenticated: true })
vi.mocked(useAuthStore().getWorkspaceAuthTokenOrThrow).mockResolvedValue(
'workspace-a-token'
)
vi.mocked(api.fetchApi).mockReset()
fetchWithUnifiedRemint.mockReset()
fetchWithUnifiedRemint.mockResolvedValue(settingResponse(false))
Expand Down Expand Up @@ -639,7 +643,7 @@ describe('useAgentConsent', () => {
expect.objectContaining({
method: 'POST',
headers: expect.objectContaining({
Authorization: 'Bearer account-a-token'
Authorization: 'Bearer workspace-a-token'
}),
body: JSON.stringify({ key: stored.key, value: true })
}),
Expand Down Expand Up @@ -694,11 +698,39 @@ describe('useAgentConsent', () => {
expect(reportError).toHaveBeenCalledOnce()
})

it('writes no consent when the account has no workspace token', async () => {
const onOpen = vi.fn()
const request = useAgentConsent().withConsent('button_click', onOpen)
const dialog = await waitForConsentDialog()
vi.mocked(useAuthStore().getWorkspaceAuthTokenOrThrow).mockRejectedValue(
new Error('token exchange failed')
)
fetchWithUnifiedRemint.mockClear()

;(dialog.contentProps.onAccept as () => void)()
await vi.waitFor(() => {
expect(dialog.contentProps.error).toBe('save')
})

expect(fetchWithUnifiedRemint).not.toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ method: 'POST' }),
expect.anything()
)
expect(useAuthStore().getUserAuthHeader).not.toHaveBeenCalled()
expect(onOpen).not.toHaveBeenCalled()

useDialogStore().closeDialog({ key: 'agent-consent' })
await request
})

it('keeps a missing-auth save retryable in the same account', async () => {
const onOpen = vi.fn()
const request = useAgentConsent().withConsent('button_click', onOpen)
const dialog = await waitForConsentDialog()
vi.mocked(useAuthStore().getUserAuthHeader).mockResolvedValueOnce(null)
vi.mocked(
useAuthStore().getWorkspaceAuthTokenOrThrow
).mockRejectedValueOnce(new Error('token exchange failed'))

;(dialog.contentProps.onAccept as () => void)()
await vi.waitFor(() => expect(dialog.contentProps.error).toBe('save'))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { vi } from 'vitest'

import type {
agentSettingsAuthHeader as realAgentSettingsAuthHeader,
agentSocketAuthParams as realAgentSocketAuthParams,
ensureSignedIn as realEnsureSignedIn,
hasAgentCredential as realHasAgentCredential,
Expand All @@ -11,6 +12,10 @@ export const withAgentAuth = vi.fn<typeof realWithAgentAuth>(
async (init) => init
)

export const agentSettingsAuthHeader = vi.fn<
typeof realAgentSettingsAuthHeader
>(async () => ({ Authorization: 'Bearer workspace-token' }))

export const agentSocketAuthParams = vi.fn<typeof realAgentSocketAuthParams>(
async () => new URLSearchParams()
)
Expand Down
49 changes: 49 additions & 0 deletions src/workbench/extensions/agent/services/agent/agentAuth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import type { AuthCredential, AuthHeader, AuthScheme } from '@/types/authTypes'
import {
agentSocketAuthParams,
ensureSignedIn,
agentSettingsAuthHeader,
withAgentAuth
} from './agentAuth'

Expand Down Expand Up @@ -68,6 +69,54 @@ function signInWithout(token: undefined | Error, apiKey: boolean) {
workspaceToken(token)
}

describe('agentSettingsAuthHeader', () => {
it('carries the workspace bearer off-cloud, not the personal header', async () => {
signInPersonal()
workspaceToken('workspace-token')

await expect(agentSettingsAuthHeader()).resolves.toEqual({
Authorization: 'Bearer workspace-token'
})
})
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

it('sends a stored API key as itself off-cloud', async () => {
storedApiKey('comfyui-key')

await expect(agentSettingsAuthHeader()).resolves.toEqual({
'X-API-KEY': 'comfyui-key'
})
})

it('uses the workspace header on cloud', async () => {
distribution.isCloud = true
vi.spyOn(useAuthStore(), 'getWorkspaceAuthHeader').mockResolvedValue({
Authorization: 'Bearer cloud-workspace'
})

await expect(agentSettingsAuthHeader()).resolves.toEqual({
Authorization: 'Bearer cloud-workspace'
})
})

it.for(missingWorkspaceTokens)(
'resolves null rather than rejecting with $label',
async ({ token, apiKey }) => {
signInWithout(token, apiKey)

await expect(agentSettingsAuthHeader()).resolves.toBeNull()
}
)

it('resolves null when the cloud workspace header cannot be obtained', async () => {
distribution.isCloud = true
vi.spyOn(useAuthStore(), 'getWorkspaceAuthHeader').mockRejectedValue(
new Error('token exchange failed')
)

await expect(agentSettingsAuthHeader()).resolves.toBeNull()
})
})

describe('withAgentAuth', () => {
it.for<{
account: string
Expand Down
10 changes: 10 additions & 0 deletions src/workbench/extensions/agent/services/agent/agentAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,16 @@ async function agentAuthHeader(): Promise<AuthHeader | null> {
}
}

/** Returns the credential for Agent-owned Global Settings rows. */
export async function agentSettingsAuthHeader(): Promise<AuthHeader | null> {
try {
if (isCloud) return await useAuthStore().getWorkspaceAuthHeader()
return await agentAuthHeader()
} catch {
Comment thread
christian-byrne marked this conversation as resolved.
Resolved
return null
}
}

export async function withAgentAuth(
init: AgentRequestInit
): Promise<AgentRequestInit> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,12 @@ const accountApi = vi.hoisted(() => ({
}))
vi.mock(import('@/platform/settings/globalSettingsApi'), () => ({
getGlobalSetting: accountApi.get,
setGlobalSetting: accountApi.set,
getGlobalSettingsAuthHeader: accountApi.header
setGlobalSetting: accountApi.set
}))
vi.mock(
import('@/workbench/extensions/agent/services/agent/agentAuth'),
() => ({ agentSettingsAuthHeader: accountApi.header })
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

vi.mock(import('@/composables/auth/useCurrentUser'))
const stored: GlobalSetting = {
Expand Down
Loading
Loading