diff --git a/src/composables/useApiRequest.test.ts b/src/composables/useApiRequest.test.ts new file mode 100644 index 00000000000..bef4f39df78 --- /dev/null +++ b/src/composables/useApiRequest.test.ts @@ -0,0 +1,108 @@ +import type { AxiosResponse } from 'axios' +import axios, { AxiosHeaders, CanceledError } from 'axios' +import { describe, expect, it, vi } from 'vitest' + +import { useApiRequest } from '@/composables/useApiRequest' + +const client = axios.create() + +function response(data: T): AxiosResponse { + return { + data, + status: 200, + statusText: 'OK', + headers: {}, + config: { headers: new AxiosHeaders() } + } +} + +describe('useApiRequest', () => { + it('returns response data and toggles loading state', async () => { + const { isLoading, error, executeRequest } = useApiRequest({ + client, + mapError: vi.fn() + }) + expect(isLoading.value).toBe(false) + + const pending = executeRequest(async () => response('ok'), { + errorContext: 'ctx' + }) + expect(isLoading.value).toBe(true) + + await expect(pending).resolves.toBe('ok') + expect(isLoading.value).toBe(false) + expect(error.value).toBeNull() + }) + + it('stays loading until every concurrent request settles', async () => { + const { isLoading, executeRequest } = useApiRequest({ + client, + mapError: vi.fn() + }) + + let resolveFirst!: (value: AxiosResponse) => void + const first = executeRequest( + () => new Promise>((res) => (resolveFirst = res)), + { errorContext: 'ctx' } + ) + const second = executeRequest(async () => response('second'), { + errorContext: 'ctx' + }) + + await second + expect(isLoading.value).toBe(true) + + resolveFirst(response('first')) + await first + expect(isLoading.value).toBe(false) + }) + + it('passes the injected client to the api call', async () => { + const apiCall = vi.fn(async () => response(1)) + const { executeRequest } = useApiRequest({ client, mapError: vi.fn() }) + + await executeRequest(apiCall, { errorContext: 'ctx' }) + + expect(apiCall).toHaveBeenCalledWith(client) + }) + + it('maps errors through the injected mapper and stores the message', async () => { + const mapError = vi.fn(() => 'mapped message') + const routeSpecificErrors = { 404: 'nope' } + const boom = new Error('boom') + const { error, executeRequest } = useApiRequest({ client, mapError }) + + const result = await executeRequest( + () => { + throw boom + }, + { errorContext: 'ctx', routeSpecificErrors } + ) + + expect(result).toBeNull() + expect(mapError).toHaveBeenCalledWith(boom, 'ctx', routeSpecificErrors) + expect(error.value).toBe('mapped message') + }) + + it.for([ + { + kind: 'DOM AbortError', + cancellation: new DOMException('aborted', 'AbortError') + }, + { kind: 'axios CanceledError', cancellation: new CanceledError() } + ])('swallows a $kind without mapping an error', async ({ cancellation }) => { + const mapError = vi.fn(() => 'should not run') + const { error, executeRequest } = useApiRequest({ client, mapError }) + + const result = await executeRequest( + () => { + throw cancellation + }, + { errorContext: 'ctx' } + ) + + expect(result).toBeNull() + expect(mapError).not.toHaveBeenCalled() + expect(error.value).toBeNull() + }) +}) diff --git a/src/composables/useApiRequest.ts b/src/composables/useApiRequest.ts new file mode 100644 index 00000000000..74a133b217c --- /dev/null +++ b/src/composables/useApiRequest.ts @@ -0,0 +1,62 @@ +import type { AxiosInstance, AxiosResponse } from 'axios' +import axios from 'axios' +import { computed, ref } from 'vue' + +import { isAbortError } from '@/utils/typeGuardUtil' + +/** + * Maps a caught request error to a user-facing message string. + * Each service injects its own mapper so it keeps control of the exact + * status-to-message copy it presents. + */ +export type ApiErrorMapper = ( + err: unknown, + errorContext: string, + routeSpecificErrors?: Record +) => string + +export interface ExecuteRequestOptions { + errorContext: string + routeSpecificErrors?: Record +} + +/** + * Shared axios request wrapper: owns the `isLoading`/`error` state and the + * try/catch/finally plumbing, while the caller injects the axios instance and + * an error mapper. Cancellations are swallowed (no error set, `null` returned). + */ +export function useApiRequest({ + client, + mapError +}: { + client: AxiosInstance + mapError: ApiErrorMapper +}) { + const pendingCount = ref(0) + const isLoading = computed(() => pendingCount.value > 0) + const error = ref(null) + + async function executeRequest( + apiCall: (client: AxiosInstance) => Promise>, + options: ExecuteRequestOptions + ): Promise { + const { errorContext, routeSpecificErrors } = options + + pendingCount.value++ + error.value = null + + try { + const response = await apiCall(client) + return response.data + } catch (err) { + if (isAbortError(err) || axios.isCancel(err)) return null + + error.value = mapError(err, errorContext, routeSpecificErrors) + return null + } finally { + pendingCount.value-- + } + } + + return { isLoading, error, executeRequest } +} diff --git a/src/platform/customNodes/manager/composables/useConflictDetection.test.ts b/src/platform/customNodes/manager/composables/useConflictDetection.test.ts index e02eb9f0bb2..766750c5102 100644 --- a/src/platform/customNodes/manager/composables/useConflictDetection.test.ts +++ b/src/platform/customNodes/manager/composables/useConflictDetection.test.ts @@ -79,7 +79,7 @@ describe('useConflictDetection', () => { const mockComfyManagerService = { getImportFailInfoBulk: vi.fn(), listInstalledPacks: vi.fn(async () => ({})), - isLoading: ref(false), + isLoading: computed(() => false), error: ref(null) } as Partial> as ReturnType< typeof useComfyManagerService @@ -87,7 +87,7 @@ describe('useConflictDetection', () => { const mockRegistryService = { getBulkNodeVersions: vi.fn(), - isLoading: ref(false), + isLoading: computed(() => false), error: ref(null) } as Partial> as ReturnType< typeof useComfyRegistryService diff --git a/src/platform/customNodes/manager/services/comfyManagerService.apiBase.test.ts b/src/platform/customNodes/manager/services/comfyManagerService.apiBase.test.ts new file mode 100644 index 00000000000..bd73c2cbd6e --- /dev/null +++ b/src/platform/customNodes/manager/services/comfyManagerService.apiBase.test.ts @@ -0,0 +1,38 @@ +import type { InternalAxiosRequestConfig } from 'axios' +import axios from 'axios' +import { describe, expect, it, vi } from 'vitest' +import { computed } from 'vue' + +import { api } from '@/scripts/api' +import { useManagerState } from '@/platform/customNodes/manager/composables/useManagerState' + +vi.mock(import('axios'), { spy: true }) +vi.mock(import('@/scripts/api')) +vi.mock(import('@/platform/customNodes/manager/composables/useManagerState')) + +const requestedUrl = vi.fn<(url: string) => void>() + +async function captureRequestUrl(config: InternalAxiosRequestConfig) { + requestedUrl(axios.getUri(config)) + return { data: {}, status: 200, statusText: 'OK', headers: {}, config } +} + +vi.mocked(axios.create).mockImplementationOnce((config) => + axios.create({ ...config, adapter: captureRequestUrl }) +) + +const { useComfyManagerService } = + await import('@/platform/customNodes/manager/services/comfyManagerService') + +describe('useComfyManagerService', () => { + it('sends the request to the API base configured after import', async () => { + api.api_base = '/changed-base' + vi.mocked(useManagerState()).isNewManagerUI = computed(() => true) + + await useComfyManagerService().listInstalledPacks() + + expect(requestedUrl).toHaveBeenCalledWith( + '/changed-base/api/v2/customnode/installed' + ) + }) +}) diff --git a/src/platform/customNodes/manager/services/comfyManagerService.test.ts b/src/platform/customNodes/manager/services/comfyManagerService.test.ts index bd73c2cbd6e..86f3311701a 100644 --- a/src/platform/customNodes/manager/services/comfyManagerService.test.ts +++ b/src/platform/customNodes/manager/services/comfyManagerService.test.ts @@ -1,38 +1,306 @@ -import type { InternalAxiosRequestConfig } from 'axios' import axios from 'axios' -import { describe, expect, it, vi } from 'vitest' -import { computed } from 'vue' +import { beforeEach, describe, expect, it, vi } from 'vitest' -import { api } from '@/scripts/api' -import { useManagerState } from '@/platform/customNodes/manager/composables/useManagerState' +import { useComfyManagerService } from '@/platform/customNodes/manager/services/comfyManagerService' -vi.mock(import('axios'), { spy: true }) -vi.mock(import('@/scripts/api')) -vi.mock(import('@/platform/customNodes/manager/composables/useManagerState')) +const mockAxiosInstance = vi.hoisted(() => ({ + get: vi.fn(), + post: vi.fn(), + interceptors: { request: { use: vi.fn() } } +})) -const requestedUrl = vi.fn<(url: string) => void>() +const managerState = vi.hoisted(() => ({ isNewManagerUI: true })) -async function captureRequestUrl(config: InternalAxiosRequestConfig) { - requestedUrl(axios.getUri(config)) - return { data: {}, status: 200, statusText: 'OK', headers: {}, config } -} +vi.mock(import('axios'), () => ({ + default: { + create: vi.fn(() => mockAxiosInstance), + isAxiosError: vi.fn(), + isCancel: vi.fn(() => false) + } +})) -vi.mocked(axios.create).mockImplementationOnce((config) => - axios.create({ ...config, adapter: captureRequestUrl }) +vi.mock(import('@/scripts/api'), () => ({ + api: { + apiURL: (path: string) => path, + clientId: 'client-1', + initialClientId: null + } +})) + +vi.mock( + import('@/platform/customNodes/manager/composables/useManagerState'), + () => ({ + useManagerState: () => ({ + isNewManagerUI: { value: managerState.isNewManagerUI } + }) + }) ) -const { useComfyManagerService } = - await import('@/platform/customNodes/manager/services/comfyManagerService') +vi.mock(import('uuid'), () => ({ v4: () => 'generated-uuid' })) describe('useComfyManagerService', () => { - it('sends the request to the API base configured after import', async () => { - api.api_base = '/changed-base' - vi.mocked(useManagerState()).isNewManagerUI = computed(() => true) + let service: ReturnType + + beforeEach(() => { + managerState.isNewManagerUI = true + mockAxiosInstance.get.mockResolvedValue({ data: {} }) + mockAxiosInstance.post.mockResolvedValue({ data: null }) + service = useComfyManagerService() + }) + + describe('availability gate', () => { + it('short-circuits requests when Manager is not in NEW_UI mode', async () => { + managerState.isNewManagerUI = false + + const result = await service.listInstalledPacks() + + expect(result).toBeNull() + expect(mockAxiosInstance.get).not.toHaveBeenCalled() + expect(service.error.value).toBe( + 'Manager service is not available in current mode' + ) + }) + }) + + describe('read requests', () => { + it('getQueueStatus forwards the client_id param', async () => { + await service.getQueueStatus('abc') + + expect(mockAxiosInstance.get).toHaveBeenCalledWith( + 'manager/queue/status', + expect.objectContaining({ params: { client_id: 'abc' } }) + ) + }) + + it('listInstalledPacks hits the installed endpoint', async () => { + await service.listInstalledPacks() + + expect(mockAxiosInstance.get).toHaveBeenCalledWith( + 'customnode/installed', + expect.any(Object) + ) + }) + + it('getImportFailInfo hits the import-fail endpoint', async () => { + await service.getImportFailInfo() - await useComfyManagerService().listInstalledPacks() + expect(mockAxiosInstance.get).toHaveBeenCalledWith( + 'customnode/import_fail_info', + expect.any(Object) + ) + }) - expect(requestedUrl).toHaveBeenCalledWith( - '/changed-base/api/v2/customnode/installed' + it('getImportFailInfoBulk returns empty without identifiers', async () => { + const result = await service.getImportFailInfoBulk({}) + + expect(result).toEqual({}) + expect(mockAxiosInstance.post).not.toHaveBeenCalled() + }) + + it('getImportFailInfoBulk posts when identifiers are present', async () => { + await service.getImportFailInfoBulk({ cnr_ids: ['a'] }) + + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + 'customnode/import_fail_info_bulk', + { cnr_ids: ['a'] }, + expect.any(Object) + ) + }) + + it('isLegacyManagerUI hits the legacy-ui endpoint', async () => { + await service.isLegacyManagerUI() + + expect(mockAxiosInstance.get).toHaveBeenCalledWith( + 'manager/is_legacy_manager_ui', + expect.any(Object) + ) + }) + + it('getTaskHistory forwards options as params', async () => { + await service.getTaskHistory({ max_items: 5 }) + + expect(mockAxiosInstance.get).toHaveBeenCalledWith( + 'manager/queue/history', + expect.objectContaining({ params: { max_items: 5 } }) + ) + }) + }) + + describe('queue operations', () => { + const expectQueueNotStarted = () => + expect(mockAxiosInstance.post).not.toHaveBeenCalledWith( + 'manager/queue/start', + null, + expect.any(Object) + ) + + it.for([ + { + name: 'installPack', + kind: 'install', + call: () => + service.installPack({ + id: 'pack', + version: '1.0.0', + selected_version: '1.0.0', + mode: 'remote', + channel: 'default' + }) + }, + { + name: 'uninstallPack', + kind: 'uninstall', + call: () => + service.uninstallPack({ node_name: 'pack', is_unknown: false }) + }, + { + name: 'disablePack', + kind: 'disable', + call: () => + service.disablePack({ node_name: 'pack', is_unknown: false }) + }, + { + name: 'enablePack', + kind: 'enable', + call: () => service.enablePack({ cnr_id: 'pack' }) + }, + { + name: 'updatePack', + kind: 'update', + call: () => service.updatePack({ node_name: 'pack' }) + } + ])( + '$name queues a $kind task and leaves starting the queue to the caller', + async ({ call, kind }) => { + await call() + + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + 'manager/queue/task', + expect.objectContaining({ kind }), + expect.any(Object) + ) + expectQueueNotStarted() + } ) + + it.for([ + { + name: 'updateAllPacks', + url: 'manager/queue/update_all', + params: { mode: 'remote' }, + call: () => service.updateAllPacks({ mode: 'remote' }) + }, + { + name: 'updateComfyUI', + url: 'manager/queue/update_comfyui', + params: { is_stable: true }, + call: () => service.updateComfyUI({ is_stable: true }) + } + ])( + '$name posts to its endpoint and leaves starting the queue to the caller', + async ({ call, url, params }) => { + await call() + + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + url, + null, + expect.objectContaining({ params: expect.objectContaining(params) }) + ) + expectQueueNotStarted() + } + ) + + it('rebootComfyUI posts to the reboot endpoint', async () => { + await service.rebootComfyUI() + + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + 'manager/reboot', + null, + expect.any(Object) + ) + }) + + it('startQueue posts to the start endpoint and resolves to its response', async () => { + mockAxiosInstance.post.mockResolvedValue({ data: 'started' }) + + await expect(service.startQueue()).resolves.toBe('started') + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + 'manager/queue/start', + null, + expect.any(Object) + ) + }) + + it('startQueue resolves to null with a security message on 403', async () => { + mockAxiosInstance.post.mockRejectedValue({ + response: { status: 403, data: {} } + }) + vi.mocked(axios.isAxiosError).mockReturnValue(true) + + await expect(service.startQueue()).resolves.toBeNull() + expect(service.error.value).toBe( + 'Forbidden: A security error has occurred. Please check the terminal logs' + ) + }) + }) + + describe('error mapping', () => { + it('prefers a route-specific message for a matching status', async () => { + mockAxiosInstance.post.mockRejectedValue({ + response: { status: 403, data: {} } + }) + vi.mocked(axios.isAxiosError).mockReturnValue(true) + + await service.rebootComfyUI() + + expect(service.error.value).toBe( + 'Forbidden: Rebooting ComfyUI requires security_level of middle or below' + ) + }) + + it('maps 404 to a connection message', async () => { + mockAxiosInstance.get.mockRejectedValue({ + response: { status: 404, data: {} } + }) + vi.mocked(axios.isAxiosError).mockReturnValue(true) + + await service.listInstalledPacks() + + expect(service.error.value).toBe('Could not connect to ComfyUI-Manager') + }) + + it('falls back to the response message for other statuses', async () => { + mockAxiosInstance.get.mockRejectedValue({ + response: { status: 500, data: { message: 'server exploded' } } + }) + vi.mocked(axios.isAxiosError).mockReturnValue(true) + + await service.listInstalledPacks() + + expect(service.error.value).toBe('server exploded') + }) + + it('handles non-axios errors', async () => { + mockAxiosInstance.get.mockRejectedValue(new Error('boom')) + vi.mocked(axios.isAxiosError).mockReturnValue(false) + + await service.listInstalledPacks() + + expect(service.error.value).toBe('Fetching installed packs failed: boom') + }) + + it('reports a dedicated message when a network error has no response', async () => { + mockAxiosInstance.get.mockRejectedValue({ + message: 'Network Error', + response: undefined + }) + vi.mocked(axios.isAxiosError).mockReturnValue(true) + + await service.listInstalledPacks() + + expect(service.error.value).toBe( + 'Fetching installed packs failed: Network Error' + ) + }) }) }) diff --git a/src/platform/customNodes/manager/services/comfyManagerService.ts b/src/platform/customNodes/manager/services/comfyManagerService.ts index f6dfc22cbd6..eba51f5333f 100644 --- a/src/platform/customNodes/manager/services/comfyManagerService.ts +++ b/src/platform/customNodes/manager/services/comfyManagerService.ts @@ -1,10 +1,10 @@ -import type { AxiosError, AxiosResponse } from 'axios' +import type { AxiosInstance, AxiosResponse } from 'axios' import axios from 'axios' import { v4 as uuidv4 } from 'uuid' -import { ref } from 'vue' +import type { ExecuteRequestOptions } from '@/composables/useApiRequest' +import { useApiRequest } from '@/composables/useApiRequest' import { api } from '@/scripts/api' -import { isAbortError } from '@/utils/typeGuardUtil' import { useManagerState } from '@/platform/customNodes/manager/composables/useManagerState' import type { components } from '@comfyorg/api-client/generatedManagerTypes' @@ -55,70 +55,58 @@ managerApiClient.interceptors.request.use((config) => { * Note: This service should only be used when Manager state is NEW_UI */ export const useComfyManagerService = () => { - const isLoading = ref(false) - const error = ref(null) - // Check if manager service should be available const isManagerServiceAvailable = () => { const managerState = useManagerState() return managerState.isNewManagerUI.value } - const handleRequestError = ( + const mapError = ( err: unknown, context: string, routeSpecificErrors?: Record - ) => { - // Don't treat cancellation as an error - if (isAbortError(err)) return - - let message: string - if (!axios.isAxiosError(err)) { - message = `${context} failed: ${err instanceof Error ? err.message : String(err)}` - } else { - const axiosError = err as AxiosError<{ message: string }> - const status = axiosError.response?.status - if (status && routeSpecificErrors?.[status]) { - message = routeSpecificErrors[status] - } else if (status === 404) { - message = 'Could not connect to ComfyUI-Manager' - } else { - message = - axiosError.response?.data.message ?? - `${context} failed with status ${status}` - } + ): string => { + if (!axios.isAxiosError<{ message?: string }>(err)) { + return `${context} failed: ${err instanceof Error ? err.message : String(err)}` } - error.value = message - } + if (!err.response) { + return `${context} failed: ${err.message}` + } - const executeRequest = async ( - requestCall: () => Promise>, - options: { - errorContext: string - routeSpecificErrors?: Record + const status = err.response.status + if (routeSpecificErrors?.[status]) { + return routeSpecificErrors[status] + } + if (status === 404) { + return 'Could not connect to ComfyUI-Manager' } - ): Promise => { - const { errorContext, routeSpecificErrors } = options + return ( + err.response.data.message ?? `${context} failed with status ${status}` + ) + } + + const { + isLoading, + error, + executeRequest: sendRequest + } = useApiRequest({ + client: managerApiClient, + mapError + }) + + const executeRequest = ( + apiCall: (client: AxiosInstance) => Promise>, + options: ExecuteRequestOptions + ): Promise => { // Block service calls if not in NEW_UI state if (!isManagerServiceAvailable()) { error.value = 'Manager service is not available in current mode' - return null + return Promise.resolve(null) } - isLoading.value = true - error.value = null - - try { - const response = await requestCall() - return response.data - } catch (err) { - handleRequestError(err, errorContext, routeSpecificErrors) - return null - } finally { - isLoading.value = false - } + return sendRequest(apiCall, options) } const startQueue = async (signal?: AbortSignal) => { @@ -128,7 +116,7 @@ export const useComfyManagerService = () => { } return executeRequest( - () => managerApiClient.post(ManagerRoute.START_QUEUE, null, { signal }), + (client) => client.post(ManagerRoute.START_QUEUE, null, { signal }), { errorContext, routeSpecificErrors } ) } @@ -137,8 +125,8 @@ export const useComfyManagerService = () => { const errorContext = 'Getting ComfyUI-Manager queue status' return executeRequest( - () => - managerApiClient.get(ManagerRoute.QUEUE_STATUS, { + (client) => + client.get(ManagerRoute.QUEUE_STATUS, { params: client_id ? { client_id } : undefined, signal }), @@ -150,7 +138,7 @@ export const useComfyManagerService = () => { const errorContext = 'Fetching installed packs' return executeRequest( - () => managerApiClient.get(ManagerRoute.LIST_INSTALLED, { signal }), + (client) => client.get(ManagerRoute.LIST_INSTALLED, { signal }), { errorContext } ) } @@ -159,7 +147,7 @@ export const useComfyManagerService = () => { const errorContext = 'Fetching import failure information' return executeRequest>( - () => managerApiClient.get(ManagerRoute.IMPORT_FAIL_INFO, { signal }), + (client) => client.get(ManagerRoute.IMPORT_FAIL_INFO, { signal }), { errorContext } ) } @@ -175,8 +163,8 @@ export const useComfyManagerService = () => { } return executeRequest( - () => - managerApiClient.post(ManagerRoute.IMPORT_FAIL_INFO_BULK, params, { + (client) => + client.post(ManagerRoute.IMPORT_FAIL_INFO_BULK, params, { signal }), { errorContext } @@ -203,7 +191,7 @@ export const useComfyManagerService = () => { } return executeRequest( - () => managerApiClient.post(ManagerRoute.QUEUE_TASK, task, { signal }), + (client) => client.post(ManagerRoute.QUEUE_TASK, task, { signal }), { errorContext, routeSpecificErrors } ) } @@ -266,8 +254,8 @@ export const useComfyManagerService = () => { } return executeRequest( - () => - managerApiClient.post(ManagerRoute.UPDATE_ALL, null, { + (client) => + client.post(ManagerRoute.UPDATE_ALL, null, { params: queryParams, signal }), @@ -293,8 +281,8 @@ export const useComfyManagerService = () => { } return executeRequest( - () => - managerApiClient.post(ManagerRoute.UPDATE_COMFYUI, null, { + (client) => + client.post(ManagerRoute.UPDATE_COMFYUI, null, { params: queryParams, signal }), @@ -309,7 +297,7 @@ export const useComfyManagerService = () => { } return executeRequest( - () => managerApiClient.post(ManagerRoute.REBOOT, null, { signal }), + (client) => client.post(ManagerRoute.REBOOT, null, { signal }), { errorContext, routeSpecificErrors } ) } @@ -318,7 +306,7 @@ export const useComfyManagerService = () => { const errorContext = 'Checking if user set Manager to use the legacy UI' return executeRequest<{ is_legacy_manager_ui: boolean }>( - () => managerApiClient.get(ManagerRoute.IS_LEGACY_MANAGER_UI, { signal }), + (client) => client.get(ManagerRoute.IS_LEGACY_MANAGER_UI, { signal }), { errorContext } ) } @@ -335,8 +323,8 @@ export const useComfyManagerService = () => { const errorContext = 'Getting ComfyUI-Manager task history' return executeRequest( - () => - managerApiClient.get(ManagerRoute.TASK_HISTORY, { + (client) => + client.get(ManagerRoute.TASK_HISTORY, { params: options, signal }), diff --git a/src/platform/customNodes/manager/stores/comfyManagerStore.test.ts b/src/platform/customNodes/manager/stores/comfyManagerStore.test.ts index f5c603d97f8..ad3b57cd17b 100644 --- a/src/platform/customNodes/manager/stores/comfyManagerStore.test.ts +++ b/src/platform/customNodes/manager/stores/comfyManagerStore.test.ts @@ -9,7 +9,7 @@ import { onTestFinished, vi } from 'vitest' -import { nextTick, ref } from 'vue' +import { computed, nextTick, ref } from 'vue' import { createI18n } from 'vue-i18n' import en from '@/locales/en/main.json' @@ -94,7 +94,7 @@ describe('useComfyManagerStore', () => { api.clientId = previousClientId }) mockManagerService = { - isLoading: ref(false), + isLoading: computed(() => false), error: ref(null), startQueue: vi.fn().mockResolvedValue(''), getQueueStatus: vi.fn().mockResolvedValue({ diff --git a/src/platform/updates/common/releaseService.test.ts b/src/platform/updates/common/releaseService.test.ts index 8695de4365c..1c124e2ffcf 100644 --- a/src/platform/updates/common/releaseService.test.ts +++ b/src/platform/updates/common/releaseService.test.ts @@ -12,7 +12,8 @@ const mockAxiosInstance = vi.hoisted(() => ({ vi.mock(import('axios'), () => ({ default: { create: vi.fn(() => mockAxiosInstance), - isAxiosError: vi.fn() + isAxiosError: vi.fn(), + isCancel: vi.fn(() => false) } })) diff --git a/src/platform/updates/common/releaseService.ts b/src/platform/updates/common/releaseService.ts index 4de3d38d117..8b83c7d89e9 100644 --- a/src/platform/updates/common/releaseService.ts +++ b/src/platform/updates/common/releaseService.ts @@ -1,10 +1,8 @@ -import type { AxiosError, AxiosResponse } from 'axios' import axios from 'axios' -import { ref } from 'vue' +import { useApiRequest } from '@/composables/useApiRequest' import { getComfyApiBaseUrl } from '@/config/comfyApi' import type { components, operations } from '@/types/comfyRegistryTypes' -import { isAbortError } from '@/utils/typeGuardUtil' // Use generated types from OpenAPI spec export type ReleaseNote = components['schemas']['ReleaseNote'] @@ -20,23 +18,18 @@ const releaseApiClient = axios.create({ }) export const useReleaseService = () => { - const isLoading = ref(false) - const error = ref(null) - - const handleApiError = ( + const mapError = ( err: unknown, context: string, routeSpecificErrors?: Record ): string => { - if (!axios.isAxiosError(err)) + if (!axios.isAxiosError(err)) return err instanceof Error ? `${context}: ${err.message}` : `${context}: Unknown error occurred` - const axiosError = err as AxiosError - - if (axiosError.response) { - const { status, data } = axiosError.response + if (err.response) { + const { status, data } = err.response if (routeSpecificErrors && routeSpecificErrors[status]) return routeSpecificErrors[status] @@ -53,33 +46,17 @@ export const useReleaseService = () => { case 500: return `Server error: ${data.message || 'Internal server error'}` default: - return `${context}: ${data.message || axiosError.message}` + return `${context}: ${data.message || err.message}` } } - return `${context}: ${axiosError.message}` + return `${context}: ${err.message}` } - const executeApiRequest = async ( - apiCall: () => Promise>, - errorContext: string, - routeSpecificErrors?: Record - ): Promise => { - isLoading.value = true - error.value = null - - try { - const response = await apiCall() - return response.data - } catch (err) { - if (isAbortError(err)) return null - - error.value = handleApiError(err, errorContext, routeSpecificErrors) - return null - } finally { - isLoading.value = false - } - } + const { isLoading, error, executeRequest } = useApiRequest({ + client: releaseApiClient, + mapError + }) const getReleases = async ( params: GetReleasesParams, @@ -92,9 +69,9 @@ export const useReleaseService = () => { 400: 'Invalid project or version parameter' } - const apiResponse = await executeApiRequest( - () => - releaseApiClient.get(endpoint, { + const apiResponse = await executeRequest( + (client) => + client.get(endpoint, { baseURL: getComfyApiBaseUrl(), params, signal, @@ -102,8 +79,7 @@ export const useReleaseService = () => { ? { 'Comfy-Env': deployEnvironment } : undefined }), - errorContext, - routeSpecificErrors + { errorContext, routeSpecificErrors } ) return apiResponse diff --git a/src/platform/updates/common/releaseStore.test.ts b/src/platform/updates/common/releaseStore.test.ts index ae359bdbfb3..49716a1bca3 100644 --- a/src/platform/updates/common/releaseStore.test.ts +++ b/src/platform/updates/common/releaseStore.test.ts @@ -2,7 +2,7 @@ import { fromPartial } from '@total-typescript/shoehorn' import { createSharedComposable, until, useStorage } from '@vueuse/core' import { compare } from 'semver' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { ref } from 'vue' +import { computed, ref } from 'vue' import type { Ref } from 'vue' import { useOnboardingOverlayStore } from '@/platform/onboarding/onboardingOverlayStore' @@ -32,7 +32,7 @@ vi.mock(import('@/platform/distribution/types'), () => ({ vi.mock(import('@/platform/updates/common/releaseService'), () => { const getReleases = vi.fn() - const isLoading = ref(false) + const isLoading = computed(() => false) const error = ref(null) return { useReleaseService: () => ({ diff --git a/src/services/comfyRegistryService.test.ts b/src/services/comfyRegistryService.test.ts index a76b9737b0c..bd3061b704d 100644 --- a/src/services/comfyRegistryService.test.ts +++ b/src/services/comfyRegistryService.test.ts @@ -1,45 +1,222 @@ -import { describe, expect, it, vi } from 'vitest' +import axios from 'axios' +import { beforeEach, describe, expect, it, vi } from 'vitest' -const mockRegistryApiClient = vi.hoisted(() => ({ +import { useComfyRegistryService } from '@/services/comfyRegistryService' + +const mockAxiosInstance = vi.hoisted(() => ({ get: vi.fn(), post: vi.fn() })) vi.mock(import('axios'), () => ({ default: { - create: vi.fn(() => mockRegistryApiClient), - isAxiosError: vi.fn(() => false) + create: vi.fn(() => mockAxiosInstance), + isAxiosError: vi.fn(), + isCancel: vi.fn(() => false) } })) -import { useComfyRegistryService } from '@/services/comfyRegistryService' - describe('useComfyRegistryService', () => { - it.for([null, undefined, '', 'undefined'])( - 'does not query for node name %s', - async (nodeName) => { - const result = await Reflect.apply( - useComfyRegistryService().inferPackFromNodeName, - undefined, - [nodeName] + let service: ReturnType + + beforeEach(() => { + mockAxiosInstance.get.mockResolvedValue({ data: {} }) + mockAxiosInstance.post.mockResolvedValue({ data: {} }) + service = useComfyRegistryService() + }) + + describe('request routing', () => { + it('getNodeDefs hits the comfy-nodes endpoint', async () => { + await service.getNodeDefs({ packId: 'pack', version: '1.0.0' }) + + expect(mockAxiosInstance.get).toHaveBeenCalledWith( + '/nodes/pack/versions/1.0.0/comfy-nodes', + expect.objectContaining({ params: {} }) + ) + }) + + it('getNodeDefs returns null without a packId or version', async () => { + const result = await service.getNodeDefs({ packId: '', version: '' }) + + expect(result).toBeNull() + expect(mockAxiosInstance.get).not.toHaveBeenCalled() + }) + + it('search hits the search endpoint', async () => { + await service.search({ search: 'sampler' }) + + expect(mockAxiosInstance.get).toHaveBeenCalledWith( + '/nodes/search', + expect.objectContaining({ params: { search: 'sampler' } }) + ) + }) + + it('getPublisherById hits the publisher endpoint', async () => { + await service.getPublisherById('pub-1') + + expect(mockAxiosInstance.get).toHaveBeenCalledWith( + '/publishers/pub-1', + expect.any(Object) + ) + }) + + it('listPacksForPublisher forwards include_banned', async () => { + await service.listPacksForPublisher('pub-1', true) + + expect(mockAxiosInstance.get).toHaveBeenCalledWith( + '/publishers/pub-1/nodes', + expect.objectContaining({ params: { include_banned: true } }) + ) + }) + + it('postPackReview posts the star rating', async () => { + await service.postPackReview('pack', 5) + + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + '/nodes/pack/reviews', + null, + expect.objectContaining({ params: { star: 5 } }) + ) + }) + + it('listAllPacks hits the nodes endpoint', async () => { + await service.listAllPacks({ page: 1 }) + + expect(mockAxiosInstance.get).toHaveBeenCalledWith( + '/nodes', + expect.objectContaining({ params: { page: 1 } }) + ) + }) + + it('getPackVersions hits the versions endpoint', async () => { + await service.getPackVersions('pack') + + expect(mockAxiosInstance.get).toHaveBeenCalledWith( + '/nodes/pack/versions', + expect.any(Object) + ) + }) + + it('getPackByVersion hits the specific version endpoint', async () => { + await service.getPackByVersion('pack', 'v-1') + + expect(mockAxiosInstance.get).toHaveBeenCalledWith( + '/nodes/pack/versions/v-1', + expect.any(Object) + ) + }) + + it('getPackById hits the node endpoint', async () => { + await service.getPackById('pack') + + expect(mockAxiosInstance.get).toHaveBeenCalledWith( + '/nodes/pack', + expect.any(Object) + ) + }) + + it('inferPackFromNodeName hits the comfy-nodes lookup endpoint', async () => { + await service.inferPackFromNodeName('KSampler') + + expect(mockAxiosInstance.get).toHaveBeenCalledWith( + '/comfy-nodes/KSampler/node', + expect.any(Object) + ) + }) + + it('getBulkNodeVersions posts the identifiers', async () => { + const nodeVersions = [{ node_id: 'pack', version: '1.0.0' }] + await service.getBulkNodeVersions(nodeVersions) + + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + '/bulk/nodes/versions', + { node_versions: nodeVersions }, + expect.any(Object) ) + }) + + it('returns the response data on success', async () => { + mockAxiosInstance.get.mockResolvedValue({ data: { id: 'pack' } }) + + const result = await service.getPackById('pack') + + expect(result).toEqual({ id: 'pack' }) + }) + }) + + describe('error mapping', () => { + it('prefers a route-specific message for a matching status', async () => { + mockAxiosInstance.get.mockRejectedValue({ + response: { status: 404, data: {} } + }) + vi.mocked(axios.isAxiosError).mockReturnValue(true) + + const result = await service.getPackById('missing') expect(result).toBeNull() - expect(mockRegistryApiClient.get).not.toHaveBeenCalled() - } - ) + expect(service.error.value).toBe( + 'Pack not found: The pack with ID missing does not exist' + ) + }) + + it('maps generic status codes to friendly messages', async () => { + mockAxiosInstance.get.mockRejectedValue({ + response: { status: 401, data: {} } + }) + vi.mocked(axios.isAxiosError).mockReturnValue(true) + + await service.search() + + expect(service.error.value).toBe('Unauthorized: Authentication required') + }) + + it('falls back to the axios message when there is no response', async () => { + mockAxiosInstance.get.mockRejectedValue({ message: 'Network Error' }) + vi.mocked(axios.isAxiosError).mockReturnValue(true) + + await service.search() + + expect(service.error.value).toBe( + 'Failed to perform search: Network Error' + ) + }) - it('returns registry data for a valid node name', async () => { - const expected = { id: 'pack-id' } - mockRegistryApiClient.get.mockResolvedValueOnce({ data: expected }) + it('handles non-axios errors', async () => { + mockAxiosInstance.get.mockRejectedValue(new Error('boom')) + vi.mocked(axios.isAxiosError).mockReturnValue(false) - const result = - await useComfyRegistryService().inferPackFromNodeName('KSampler') + await service.search() - expect(result).toEqual(expected) - expect(mockRegistryApiClient.get).toHaveBeenCalledExactlyOnceWith( - '/comfy-nodes/KSampler/node', - { signal: undefined } + expect(service.error.value).toBe('Failed to perform search: boom') + }) + }) + + describe('inferPackFromNodeName guard', () => { + it.for([null, undefined, '', 'undefined'])( + 'does not query for node name %s', + async (nodeName) => { + const result = await Reflect.apply( + service.inferPackFromNodeName, + undefined, + [nodeName] + ) + + expect(result).toBeNull() + expect(mockAxiosInstance.get).not.toHaveBeenCalled() + } ) + + it('returns registry data for a valid node name', async () => { + const expected = { id: 'pack-id' } + mockAxiosInstance.get.mockResolvedValueOnce({ data: expected }) + + const result = await service.inferPackFromNodeName('KSampler') + + expect(result).toEqual(expected) + expect(mockAxiosInstance.get).toHaveBeenCalledExactlyOnceWith( + '/comfy-nodes/KSampler/node', + expect.any(Object) + ) + }) }) }) diff --git a/src/services/comfyRegistryService.ts b/src/services/comfyRegistryService.ts index 652ca5843d8..6b1af8f43c3 100644 --- a/src/services/comfyRegistryService.ts +++ b/src/services/comfyRegistryService.ts @@ -1,9 +1,7 @@ -import type { AxiosError, AxiosResponse } from 'axios' import axios from 'axios' -import { ref } from 'vue' +import { useApiRequest } from '@/composables/useApiRequest' import type { components, operations } from '@/types/comfyRegistryTypes' -import { isAbortError } from '@/utils/typeGuardUtil' const API_BASE_URL = 'https://api.comfy.org' @@ -22,23 +20,18 @@ const registryApiClient = axios.create({ * Service for interacting with the Comfy Registry API */ export const useComfyRegistryService = () => { - const isLoading = ref(false) - const error = ref(null) - - const handleApiError = ( + const mapError = ( err: unknown, context: string, routeSpecificErrors?: Record ): string => { - if (!axios.isAxiosError(err)) + if (!axios.isAxiosError(err)) return err instanceof Error ? `${context}: ${err.message}` : `${context}: Unknown error occurred` - const axiosError = err as AxiosError - - if (axiosError.response) { - const { status, data } = axiosError.response + if (err.response) { + const { status, data } = err.response if (routeSpecificErrors && routeSpecificErrors[status]) return routeSpecificErrors[status] @@ -57,41 +50,17 @@ export const useComfyRegistryService = () => { case 500: return `Server error: ${data.message || 'Internal server error'}` default: - return `${context}: ${data.message || axiosError.message}` + return `${context}: ${data.message || err.message}` } } - return `${context}: ${axiosError.message}` + return `${context}: ${err.message}` } - /** - * Execute an API request with error and loading state handling - * @param apiCall - Function that returns a promise with the API call - * @param errorContext - Context description for error messages - * @param routeSpecificErrors - Optional map of status codes to custom error messages - * @returns Promise with the API response data or null if the request failed - */ - const executeApiRequest = async ( - apiCall: () => Promise>, - errorContext: string, - routeSpecificErrors?: Record - ): Promise => { - isLoading.value = true - error.value = null - - try { - const response = await apiCall() - return response.data - } catch (err) { - // Don't treat cancellations as errors - if (isAbortError(err)) return null - - error.value = handleApiError(err, errorContext, routeSpecificErrors) - return null - } finally { - isLoading.value = false - } - } + const { isLoading, error, executeRequest } = useApiRequest({ + client: registryApiClient, + mapError + }) /** * Get the Comfy Node definitions in a specific version of a node pack @@ -116,16 +85,15 @@ export const useComfyRegistryService = () => { 404: 'The requested node, version, or comfy node does not exist' } - return executeApiRequest( - () => - registryApiClient.get< + return executeRequest( + (client) => + client.get< operations['ListComfyNodes']['responses'][200]['content']['application/json'] >(endpoint, { params: queryParams, signal }), - errorContext, - routeSpecificErrors + { errorContext, routeSpecificErrors } ) } @@ -140,12 +108,12 @@ export const useComfyRegistryService = () => { const endpoint = '/nodes/search' const errorContext = 'Failed to perform search' - return executeApiRequest( - () => - registryApiClient.get< + return executeRequest( + (client) => + client.get< operations['searchNodes']['responses'][200]['content']['application/json'] >(endpoint, { params, signal }), - errorContext + { errorContext } ) } @@ -162,13 +130,12 @@ export const useComfyRegistryService = () => { 404: `Publisher not found: The publisher with ID ${publisherId} does not exist` } - return executeApiRequest( - () => - registryApiClient.get(endpoint, { + return executeRequest( + (client) => + client.get(endpoint, { signal }), - errorContext, - routeSpecificErrors + { errorContext, routeSpecificErrors } ) } @@ -188,14 +155,13 @@ export const useComfyRegistryService = () => { 404: `Publisher not found: The publisher with ID ${publisherId} does not exist` } - return executeApiRequest( - () => - registryApiClient.get(endpoint, { + return executeRequest( + (client) => + client.get(endpoint, { params, signal }), - errorContext, - routeSpecificErrors + { errorContext, routeSpecificErrors } ) } @@ -215,14 +181,13 @@ export const useComfyRegistryService = () => { 404: `Pack not found: Pack with ID ${packId} does not exist` } - return executeApiRequest( - () => - registryApiClient.post(endpoint, null, { + return executeRequest( + (client) => + client.post(endpoint, null, { params, signal }), - errorContext, - routeSpecificErrors + { errorContext, routeSpecificErrors } ) } @@ -236,12 +201,12 @@ export const useComfyRegistryService = () => { const endpoint = '/nodes' const errorContext = 'Failed to list packs' - return executeApiRequest( - () => - registryApiClient.get< + return executeRequest( + (client) => + client.get< operations['listAllNodes']['responses'][200]['content']['application/json'] >(endpoint, { params, signal }), - errorContext + { errorContext } ) } @@ -260,14 +225,13 @@ export const useComfyRegistryService = () => { 404: `Pack not found: Pack with ID ${packId} does not exist` } - return executeApiRequest( - () => - registryApiClient.get( - endpoint, - { params, signal } - ), - errorContext, - routeSpecificErrors + return executeRequest( + (client) => + client.get(endpoint, { + params, + signal + }), + { errorContext, routeSpecificErrors } ) } @@ -286,13 +250,12 @@ export const useComfyRegistryService = () => { 404: `Pack not found: Pack with ID ${packId} does not exist` } - return executeApiRequest( - () => - registryApiClient.get(endpoint, { + return executeRequest( + (client) => + client.get(endpoint, { signal }), - errorContext, - routeSpecificErrors + { errorContext, routeSpecificErrors } ) } @@ -309,13 +272,12 @@ export const useComfyRegistryService = () => { 404: `Pack not found: The pack with ID ${packId} does not exist` } - return executeApiRequest( - () => - registryApiClient.get(endpoint, { + return executeRequest( + (client) => + client.get(endpoint, { signal }), - errorContext, - routeSpecificErrors + { errorContext, routeSpecificErrors } ) } @@ -355,13 +317,12 @@ export const useComfyRegistryService = () => { 404: `Comfy node not found: The node with name ${nodeName} does not exist in the registry` } - return executeApiRequest( - () => - registryApiClient.get(endpoint, { + return executeRequest( + (client) => + client.get(endpoint, { signal }), - errorContext, - routeSpecificErrors + { errorContext, routeSpecificErrors } ) } @@ -402,15 +363,16 @@ export const useComfyRegistryService = () => { node_versions: nodeVersions } - return executeApiRequest( - () => - registryApiClient.post< - components['schemas']['BulkNodeVersionsResponse'] - >(endpoint, requestBody, { - signal - }), - errorContext, - routeSpecificErrors + return executeRequest( + (client) => + client.post( + endpoint, + requestBody, + { + signal + } + ), + { errorContext, routeSpecificErrors } ) } diff --git a/src/stores/comfyRegistryStore.test.ts b/src/stores/comfyRegistryStore.test.ts index 92b28bbc872..ee866ee22d2 100644 --- a/src/stores/comfyRegistryStore.test.ts +++ b/src/stores/comfyRegistryStore.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { ref } from 'vue' +import type { ComputedRef } from 'vue' +import { computed, ref } from 'vue' import { useComfyRegistryService } from '@/services/comfyRegistryService' import { useComfyRegistryStore } from '@/stores/comfyRegistryStore' @@ -67,7 +68,7 @@ const mockListResult: operations['listAllNodes']['responses'][200]['content']['a describe('useComfyRegistryStore', () => { let mockRegistryService: { - isLoading: ReturnType> + isLoading: ComputedRef error: ReturnType> listAllPacks: ReturnType getPackById: ReturnType @@ -83,7 +84,7 @@ describe('useComfyRegistryStore', () => { beforeEach(() => { mockRegistryService = { - isLoading: ref(false), + isLoading: computed(() => false), error: ref(null), listAllPacks: vi.fn().mockImplementation((params) => { // If node_id is provided, return specific nodes