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
Original file line number Diff line number Diff line change
@@ -1,23 +1,30 @@
import { useAuthStore } from '@/stores/authStore'
import { fromPartial } from '@total-typescript/shoehorn'
import axios from 'axios'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { WebSession } from '@comfyorg/account-core/webSession'

import type { IWidget } from '@/lib/litegraph/src/litegraph'
import type {
WebSessionRequestScope,
WebSessionRequests
} from '@/platform/auth/session/webSessionFetch'
import { provideWebSessionRequests } from '@/platform/auth/session/webSessionFetch'
import { api } from '@/scripts/api'
import { useRemoteWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget'
import type { RemoteWidgetConfig } from '@/schemas/nodeDefSchema'
import { createMockLGraphNode } from '@/utils/__tests__/litegraphTestUtils'
import { stubFirebaseAuthHarness } from '@/utils/__tests__/stubAccountIdentityPort'
import { useAuthStore } from '@/stores/authStore'

function createMockWidget(overrides: Partial<IWidget> = {}): IWidget {
return {
const widget = fromPartial<IWidget>({
name: 'test_widget',
type: 'text',
value: '',
options: {},
...overrides
} as Partial<IWidget> as IWidget
options: {}
})
return Object.assign(widget, overrides)
}

const mockCloudAuth = vi.hoisted(() => ({
Expand Down Expand Up @@ -461,7 +468,7 @@ describe('useRemoteWidget', () => {
const hook2 = useRemoteWidget(options)

// Since they have the same route, only one request will be made
await Promise.race([getResolvedValue(hook1), getResolvedValue(hook2)])
await Promise.all([getResolvedValue(hook1), getResolvedValue(hook2)])

const data1 = hook1.getValue()
const data2 = hook2.getValue()
Expand Down Expand Up @@ -583,6 +590,222 @@ describe('useRemoteWidget', () => {
})
})

describe('web session', () => {
const sessionScope = (): WebSessionRequestScope | undefined => ({
session: fromPartial<WebSession>({}),
epoch: 1
})
let release: (() => void) | undefined
let scope: () => WebSessionRequestScope | undefined
let send: ReturnType<
typeof vi.fn<(url: string, init: RequestInit) => Promise<Response>>
>

const provideSession = () => {
release = provideWebSessionRequests(
fromPartial<WebSessionRequests>({
scope: async () => scope(),
workspaceId: () => undefined,
send: (url, init) => send(url, init)
})
)
}

beforeEach(() => {
scope = sessionScope
send = vi.fn<(url: string, init: RequestInit) => Promise<Response>>()
vi.stubGlobal('fetch', vi.fn())
})

afterEach(() => {
release?.()
release = undefined
mockCloudAuth.isCloud = false
mockCloudAuth.authHeader = null
})

const jsonBody = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status })

let routeCount = 0
const uniqueRoute = () => `/api/models/${routeCount++}`

it.for([
{
name: 'a plain route',
suffix: '',
params: undefined,
responseKey: undefined,
body: ['a', 'b'],
value: ['a', 'b']
},
{
name: 'a route that already has a query',
suffix: '?a=1',
params: { b: '2' },
responseKey: undefined,
body: ['a'],
value: ['a'],
query: '?a=1&b=2'
},
{
name: 'query params on a plain route',
suffix: '',
params: { b: '2' },
responseKey: undefined,
body: ['a'],
value: ['a'],
query: '?b=2'
},
{
name: 'a response key',
suffix: '',
params: undefined,
responseKey: 'items',
body: { items: ['k'] },
value: ['k']
}
])(
'fetches on the web session: $name',
async ({ suffix, params, responseKey, body, value, query = '' }) => {
provideSession()
send.mockResolvedValueOnce(jsonBody(body))
const route = uniqueRoute()
const hook = useRemoteWidget(
createMockOptions({
route: `${route}${suffix}`,
query_params: params,
response_key: responseKey
})
)

await getResolvedValue(hook)

expect(send).toHaveBeenCalledExactlyOnceWith(
`${route}${query || suffix}`,
{
method: 'GET',
signal: expect.any(AbortSignal)
}
)
expect(vi.mocked(axios.get)).not.toHaveBeenCalled()
expect(hook.getCachedValue()).toEqual(value)
}
)

it('keeps a body that is not JSON as text', async () => {
provideSession()
send.mockResolvedValueOnce(new Response('plain'))
const hook = useRemoteWidget(createMockOptions())

await getResolvedValue(hook)

expect(hook.getCachedValue()).toBe('plain')
})

it('treats a failed status as an error and keeps the default', async () => {
provideSession()
send.mockResolvedValueOnce(jsonBody({ message: 'no' }, 500))
const hook = useRemoteWidget(createMockOptions())

await getResolvedValue(hook)

expect(hook.getInventoryStatus()).toBe('error')
expect(hook.getCachedValue()).toBe(DEFAULT_VALUE)
})

it('aborts a session request that outlives its timeout', async () => {
provideSession()
send.mockImplementationOnce(
(_url, init) =>
new Promise((_resolve, reject) => {
init.signal?.addEventListener('abort', () =>
reject(new Error('aborted'))
)
})
)
const hook = useRemoteWidget(createMockOptions({ timeout: 50 }))

const settled = getResolvedValue(hook)
await vi.advanceTimersByTimeAsync(50)
await settled

expect(hook.getInventoryStatus()).toBe('error')
})

it.for([
{
name: 'a cross-origin route',
route: 'https://example.com/x',
sessionScope: sessionScope
},
{
name: 'a protocol-relative route',
route: '//example.com/x',
sessionScope: sessionScope
},
{
name: 'a tab that is not on the session',
route: uniqueRoute(),
sessionScope: () => undefined
}
])(
'stays on axios for $name',
async ({ route, sessionScope: nextScope }) => {
mockCloudAuth.isCloud = true
mockCloudAuth.authHeader = { Authorization: 'Bearer test-token' }
scope = nextScope
provideSession()
mockAxiosResponse(['ax'])
const hook = useRemoteWidget(createMockOptions({ route }))

await getResolvedValue(hook)

expect(send).not.toHaveBeenCalled()
expect(vi.mocked(axios.get)).toHaveBeenCalledExactlyOnceWith(route, {
params: undefined,
signal: expect.any(AbortSignal),
timeout: 4096,
headers: { Authorization: 'Bearer test-token' }
})
expect(hook.getCachedValue()).toEqual(['ax'])
}
)

it.for([
{ name: 'not cloud', isCloud: false, headers: {} },
{
name: 'cloud with a token',
isCloud: true,
headers: { headers: { Authorization: 'Bearer test-token' } }
}
])(
'sends flag-off traffic through axios only ($name)',
async ({ isCloud, headers }) => {
mockCloudAuth.isCloud = isCloud
mockCloudAuth.authHeader = isCloud
? { Authorization: 'Bearer test-token' }
: null
mockAxiosResponse(['ax'])
const options = createMockOptions({ query_params: { q: '1' } })
const hook = useRemoteWidget(options)

await getResolvedValue(hook)

expect(vi.mocked(axios.get)).toHaveBeenCalledExactlyOnceWith(
options.remoteConfig.route,
{
params: { q: '1' },
signal: expect.any(AbortSignal),
timeout: 4096,
...headers
}
)
expect(fetch).not.toHaveBeenCalled()
}
)
})

describe('auto-refresh on task completion', () => {
it('should add auto-refresh toggle widget', () => {
const mockNode = createMockLGraphNode({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,71 @@ const isBackingOff = (entry: CacheEntry<unknown> | undefined) =>
entry.lastErrorTime &&
Date.now() - entry.lastErrorTime < getBackoff(entry.retryCount || 0)

class RemoteWidgetRequestError extends Error {}

const isSameOrigin = (route: string) =>
new URL(route, location.href).origin === location.origin

const withQuery = (
route: string,
params: RemoteWidgetConfig['query_params']
) => {
const query = new URLSearchParams(params).toString()
if (!query) return route
return `${route}${route.includes('?') ? '&' : '?'}${query}`
}

const parseBody = (text: string): unknown => {
try {
return JSON.parse(text)
} catch {
return text
}
}

const pickKey = (data: unknown, key: string | undefined) => {
if (!key) return data
return typeof data === 'object' && data !== null
? Reflect.get(data, key)
: undefined
}

const fetchOnSession = async (
config: RemoteWidgetConfig,
controller: AbortController
): Promise<{ data: unknown } | undefined> => {
const { route, query_params, timeout = TIMEOUT } = config
if (!isSameOrigin(route)) return undefined

const timeoutController = new AbortController()
const timer =
timeout > 0 ? setTimeout(() => timeoutController.abort(), timeout) : 0
try {
const res = await api.fetchOnWebSession(withQuery(route, query_params), {
method: 'GET',
signal: AbortSignal.any([controller.signal, timeoutController.signal])
})
if (!res) return undefined
if (!res.ok) {
throw new RemoteWidgetRequestError(
`Request failed with status ${res.status}`
)
}
return { data: parseBody(await res.text()) }
} finally {
clearTimeout(timer)
}
}

const fetchData = async (
config: RemoteWidgetConfig,
controller: AbortController
) => {
const { route, response_key, query_params, timeout = TIMEOUT } = config

const sessionRes = await fetchOnSession(config, controller)
if (sessionRes) return pickKey(sessionRes.data, response_key)

const authHeaders = await getAuthHeaders()

const res = await axios.get(route, {
Expand Down
Loading
Loading