From 6b61a560f778ec17bd7d39e6d2685a3d8ef5ec6a Mon Sep 17 00:00:00 2001 From: Matt Miller Date: Thu, 2 Jul 2026 13:16:58 -0700 Subject: [PATCH 01/10] refactor: extract shared useApiRequest composable for axios services Four services duplicated the same axios request wrapper (isLoading/error state, try/catch/finally, cancellation handling). Extract the plumbing into useApiRequest({ client, mapError }) and inject the axios instance plus a per-service error mapper so each service keeps its exact user-facing status strings. Manager keeps its availability gate and queue-restart behavior via a thin wrapper over the shared executeRequest. --- src/composables/useApiRequest.test.ts | 104 ++++++++++++ src/composables/useApiRequest.ts | 63 +++++++ src/platform/updates/common/releaseService.ts | 49 ++---- src/services/comfyRegistryService.ts | 155 +++++++----------- src/services/customerEventsService.ts | 68 +++----- .../manager/services/comfyManagerService.ts | 111 ++++++------- 6 files changed, 311 insertions(+), 239 deletions(-) create mode 100644 src/composables/useApiRequest.test.ts create mode 100644 src/composables/useApiRequest.ts diff --git a/src/composables/useApiRequest.test.ts b/src/composables/useApiRequest.test.ts new file mode 100644 index 00000000000..04ad2c916f9 --- /dev/null +++ b/src/composables/useApiRequest.test.ts @@ -0,0 +1,104 @@ +import type { AxiosInstance, AxiosResponse } from 'axios' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { useApiRequest } from '@/composables/useApiRequest' + +const mockIsAbortError = vi.hoisted(() => vi.fn()) + +vi.mock('@/utils/typeGuardUtil', () => ({ + isAbortError: mockIsAbortError +})) + +const client = { id: 'test-client' } as unknown as AxiosInstance + +function response(data: T): AxiosResponse { + return { data } as AxiosResponse +} + +describe('useApiRequest', () => { + beforeEach(() => { + mockIsAbortError.mockReset() + mockIsAbortError.mockReturnValue(false) + }) + + 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('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('swallows cancellations without mapping an error', async () => { + mockIsAbortError.mockReturnValue(true) + const mapError = vi.fn(() => 'should not run') + const { error, executeRequest } = useApiRequest({ client, mapError }) + + const result = await executeRequest( + () => { + throw new Error('aborted') + }, + { errorContext: 'ctx' } + ) + + expect(result).toBeNull() + expect(mapError).not.toHaveBeenCalled() + expect(error.value).toBeNull() + }) + + it('runs onSuccess only after a successful response', async () => { + const onSuccess = vi.fn() + const { executeRequest } = useApiRequest({ client, mapError: vi.fn() }) + + await executeRequest(async () => response('ok'), { + errorContext: 'ctx', + onSuccess + }) + expect(onSuccess).toHaveBeenCalledTimes(1) + + onSuccess.mockClear() + await executeRequest( + () => { + throw new Error('boom') + }, + { errorContext: 'ctx', onSuccess } + ) + expect(onSuccess).not.toHaveBeenCalled() + }) +}) diff --git a/src/composables/useApiRequest.ts b/src/composables/useApiRequest.ts new file mode 100644 index 00000000000..90e1655c2ab --- /dev/null +++ b/src/composables/useApiRequest.ts @@ -0,0 +1,63 @@ +import type { AxiosInstance, AxiosResponse } from 'axios' +import { 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 + /** Side effect run after a successful response, before the data is returned. */ + onSuccess?: () => unknown +} + +/** + * 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 isLoading = ref(false) + const error = ref(null) + + async function executeRequest( + apiCall: (client: AxiosInstance) => Promise>, + options: ExecuteRequestOptions + ): Promise { + const { errorContext, routeSpecificErrors, onSuccess } = options + + isLoading.value = true + error.value = null + + try { + const response = await apiCall(client) + await onSuccess?.() + return response.data + } catch (err) { + if (isAbortError(err)) return null + + error.value = mapError(err, errorContext, routeSpecificErrors) + return null + } finally { + isLoading.value = false + } + } + + return { isLoading, error, executeRequest } +} diff --git a/src/platform/updates/common/releaseService.ts b/src/platform/updates/common/releaseService.ts index a58e9eea7b9..dd95c88d85a 100644 --- a/src/platform/updates/common/releaseService.ts +++ b/src/platform/updates/common/releaseService.ts @@ -1,10 +1,10 @@ -import type { AxiosError, AxiosResponse } from 'axios' +import type { AxiosError } from 'axios' import axios from 'axios' -import { ref, watch } from 'vue' +import { watch } 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'] @@ -22,9 +22,6 @@ const releaseApiClient = axios.create({ // Release service for fetching release notes export const useReleaseService = () => { - const isLoading = ref(false) - const error = ref(null) - watch( () => getComfyApiBaseUrl(), (url) => { @@ -32,10 +29,7 @@ export const useReleaseService = () => { } ) - // No transformation needed - API response matches the generated type - - // Handle API errors with context - const handleApiError = ( + const mapError = ( err: unknown, context: string, routeSpecificErrors?: Record @@ -72,28 +66,10 @@ export const useReleaseService = () => { return `${context}: ${axiosError.message}` } - // Execute API request with error handling - 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: releaseApiClient, + mapError + }) // Fetch release notes from API const getReleases = async ( @@ -107,17 +83,16 @@ export const useReleaseService = () => { 400: 'Invalid project or version parameter' } - const apiResponse = await executeApiRequest( - () => - releaseApiClient.get(endpoint, { + const apiResponse = await executeRequest( + (client) => + client.get(endpoint, { params, signal, headers: deployEnvironment ? { 'Comfy-Env': deployEnvironment } : undefined }), - errorContext, - routeSpecificErrors + { errorContext, routeSpecificErrors } ) return apiResponse diff --git a/src/services/comfyRegistryService.ts b/src/services/comfyRegistryService.ts index 753d9f23ff8..558d353e944 100644 --- a/src/services/comfyRegistryService.ts +++ b/src/services/comfyRegistryService.ts @@ -1,9 +1,8 @@ -import type { AxiosError, AxiosResponse } from 'axios' +import type { AxiosError } 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,10 +21,7 @@ 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 @@ -64,34 +60,10 @@ export const useComfyRegistryService = () => { return `${context}: ${axiosError.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 +88,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 +111,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 +133,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 +158,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 +184,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 +204,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 +228,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 +253,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 +275,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 } ) } @@ -350,13 +315,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 } ) } @@ -397,15 +361,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/services/customerEventsService.ts b/src/services/customerEventsService.ts index 1d413960951..39e87db9650 100644 --- a/src/services/customerEventsService.ts +++ b/src/services/customerEventsService.ts @@ -1,13 +1,13 @@ -import type { AxiosError, AxiosResponse } from 'axios' +import type { AxiosError } from 'axios' import axios from 'axios' -import { ref, watch } from 'vue' +import { watch } from 'vue' +import { useApiRequest } from '@/composables/useApiRequest' import { attachUnifiedRemintInterceptor } from '@/platform/auth/unified/remintRetry' import { getComfyApiBaseUrl } from '@/config/comfyApi' import { d, t } from '@/i18n' import { useAuthStore } from '@/stores/authStore' import type { components, operations } from '@/types/comfyRegistryTypes' -import { isAbortError } from '@/utils/typeGuardUtil' export enum EventType { CREDIT_ADDED = 'credit_added', @@ -34,9 +34,6 @@ const customerApiClient = axios.create({ attachUnifiedRemintInterceptor(customerApiClient) export const useCustomerEventsService = () => { - const isLoading = ref(false) - const error = ref(null) - watch( () => getComfyApiBaseUrl(), (url) => { @@ -44,55 +41,32 @@ export const useCustomerEventsService = () => { } ) - const handleRequestError = ( + const mapError = ( err: unknown, context: string, routeSpecificErrors?: Record - ) => { - // Don't treat cancellation as an error - if (isAbortError(err)) return - - let message: string + ): 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 { - message = - axiosError.response?.data?.message ?? - `${context} failed with status ${status}` - } + return `${context} failed: ${err instanceof Error ? err.message : String(err)}` } - error.value = message - } - - const executeRequest = async ( - requestCall: () => Promise>, - options: { - errorContext: string - routeSpecificErrors?: Record + const axiosError = err as AxiosError<{ message: string }> + const status = axiosError.response?.status + if (status && routeSpecificErrors?.[status]) { + return routeSpecificErrors[status] } - ): Promise => { - const { errorContext, routeSpecificErrors } = options - 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 ( + axiosError.response?.data?.message ?? + `${context} failed with status ${status}` + ) } + const { isLoading, error, executeRequest } = useApiRequest({ + client: customerApiClient, + mapError + }) + function formatEventType(eventType: string) { switch (eventType) { case 'credit_added': @@ -198,8 +172,8 @@ export const useCustomerEventsService = () => { } const result = await executeRequest( - () => - customerApiClient.get('/customers/events', { + (client) => + client.get('/customers/events', { params: { page, limit }, headers: authHeaders }), diff --git a/src/workbench/extensions/manager/services/comfyManagerService.ts b/src/workbench/extensions/manager/services/comfyManagerService.ts index 8f3eaf40656..72904b397d5 100644 --- a/src/workbench/extensions/manager/services/comfyManagerService.ts +++ b/src/workbench/extensions/manager/services/comfyManagerService.ts @@ -1,10 +1,9 @@ -import type { AxiosError, AxiosResponse } from 'axios' +import type { AxiosError, AxiosInstance, AxiosResponse } from 'axios' import axios from 'axios' import { v4 as uuidv4 } from 'uuid' -import { ref } from 'vue' +import { useApiRequest } from '@/composables/useApiRequest' import { api } from '@/scripts/api' -import { isAbortError } from '@/utils/typeGuardUtil' import { useManagerState } from '@/workbench/extensions/manager/composables/useManagerState' import type { components } from '@/workbench/extensions/manager/types/generatedManagerTypes' @@ -51,72 +50,64 @@ const managerApiClient = axios.create({ * 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 + ): 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}` - } + return `${context} failed: ${err instanceof Error ? err.message : String(err)}` + } + + const axiosError = err as AxiosError<{ message: string }> + const status = axiosError.response?.status + if (status && routeSpecificErrors?.[status]) { + return routeSpecificErrors[status] + } + if (status === 404) { + return 'Could not connect to ComfyUI-Manager' } - error.value = message + return ( + axiosError.response?.data?.message ?? + `${context} failed with status ${status}` + ) } - const executeRequest = async ( - requestCall: () => Promise>, + const { + isLoading, + error, + executeRequest: sendRequest + } = useApiRequest({ + client: managerApiClient, + mapError + }) + + const executeRequest = ( + apiCall: (client: AxiosInstance) => Promise>, options: { errorContext: string routeSpecificErrors?: Record isQueueOperation?: boolean } ): Promise => { - const { errorContext, routeSpecificErrors, isQueueOperation } = options - // 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() - if (isQueueOperation) await startQueue() - return response.data - } catch (err) { - handleRequestError(err, errorContext, routeSpecificErrors) - return null - } finally { - isLoading.value = false - } + const { isQueueOperation, ...requestOptions } = options + return sendRequest(apiCall, { + ...requestOptions, + onSuccess: isQueueOperation ? startQueue : undefined + }) } const startQueue = async (signal?: AbortSignal) => { @@ -126,7 +117,7 @@ export const useComfyManagerService = () => { } return executeRequest( - () => managerApiClient.post(ManagerRoute.START_QUEUE, null, { signal }), + (client) => client.post(ManagerRoute.START_QUEUE, null, { signal }), { errorContext, routeSpecificErrors } ) } @@ -135,8 +126,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 }), @@ -148,7 +139,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 } ) } @@ -157,7 +148,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 } ) } @@ -173,8 +164,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 } @@ -201,7 +192,7 @@ export const useComfyManagerService = () => { } return executeRequest( - () => managerApiClient.post(ManagerRoute.QUEUE_TASK, task, { signal }), + (client) => client.post(ManagerRoute.QUEUE_TASK, task, { signal }), { errorContext, routeSpecificErrors, isQueueOperation: true } ) } @@ -264,8 +255,8 @@ export const useComfyManagerService = () => { } return executeRequest( - () => - managerApiClient.post(ManagerRoute.UPDATE_ALL, null, { + (client) => + client.post(ManagerRoute.UPDATE_ALL, null, { params: queryParams, signal }), @@ -291,8 +282,8 @@ export const useComfyManagerService = () => { } return executeRequest( - () => - managerApiClient.post(ManagerRoute.UPDATE_COMFYUI, null, { + (client) => + client.post(ManagerRoute.UPDATE_COMFYUI, null, { params: queryParams, signal }), @@ -307,7 +298,7 @@ export const useComfyManagerService = () => { } return executeRequest( - () => managerApiClient.post(ManagerRoute.REBOOT, null, { signal }), + (client) => client.post(ManagerRoute.REBOOT, null, { signal }), { errorContext, routeSpecificErrors } ) } @@ -316,7 +307,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 } ) } @@ -333,8 +324,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 }), From 58f541b947766c366d8ca6fe18e03aa059e3c485 Mon Sep 17 00:00:00 2001 From: Matt Miller Date: Thu, 2 Jul 2026 13:55:02 -0700 Subject: [PATCH 02/10] test: cover comfyRegistryService and comfyManagerService request wrappers Add unit tests exercising the refactored useApiRequest call sites in both services, closing the codecov patch-coverage gap on this refactor. --- src/services/comfyRegistryService.test.ts | 198 ++++++++++++++ .../services/comfyManagerService.test.ts | 252 ++++++++++++++++++ 2 files changed, 450 insertions(+) create mode 100644 src/services/comfyRegistryService.test.ts create mode 100644 src/workbench/extensions/manager/services/comfyManagerService.test.ts diff --git a/src/services/comfyRegistryService.test.ts b/src/services/comfyRegistryService.test.ts new file mode 100644 index 00000000000..4d337e210a9 --- /dev/null +++ b/src/services/comfyRegistryService.test.ts @@ -0,0 +1,198 @@ +import axios from 'axios' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { useComfyRegistryService } from '@/services/comfyRegistryService' + +const mockAxiosInstance = vi.hoisted(() => ({ + get: vi.fn(), + post: vi.fn() +})) + +vi.mock('axios', () => ({ + default: { + create: vi.fn(() => mockAxiosInstance), + isAxiosError: vi.fn() + } +})) + +describe('useComfyRegistryService', () => { + let service: ReturnType + + beforeEach(() => { + vi.clearAllMocks() + mockAxiosInstance.get.mockResolvedValue({ data: {} }) + mockAxiosInstance.post.mockResolvedValue({ data: {} }) + service = useComfyRegistryService() + }) + + it('initializes with idle state', () => { + expect(service.isLoading.value).toBe(false) + expect(service.error.value).toBeNull() + }) + + 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(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('handles non-axios errors', async () => { + mockAxiosInstance.get.mockRejectedValue(new Error('boom')) + vi.mocked(axios.isAxiosError).mockReturnValue(false) + + await service.search() + + expect(service.error.value).toBe('Failed to perform search: boom') + }) + }) +}) diff --git a/src/workbench/extensions/manager/services/comfyManagerService.test.ts b/src/workbench/extensions/manager/services/comfyManagerService.test.ts new file mode 100644 index 00000000000..054f9f17e4d --- /dev/null +++ b/src/workbench/extensions/manager/services/comfyManagerService.test.ts @@ -0,0 +1,252 @@ +import axios from 'axios' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { useComfyManagerService } from '@/workbench/extensions/manager/services/comfyManagerService' + +const mockAxiosInstance = vi.hoisted(() => ({ + get: vi.fn(), + post: vi.fn() +})) + +const managerState = vi.hoisted(() => ({ isNewManagerUI: true })) + +vi.mock('axios', () => ({ + default: { + create: vi.fn(() => mockAxiosInstance), + isAxiosError: vi.fn() + } +})) + +vi.mock('@/scripts/api', () => ({ + api: { + apiURL: (path: string) => path, + clientId: 'client-1', + initialClientId: null + } +})) + +vi.mock('@/workbench/extensions/manager/composables/useManagerState', () => ({ + useManagerState: () => ({ + isNewManagerUI: { value: managerState.isNewManagerUI } + }) +})) + +vi.mock('uuid', () => ({ v4: () => 'generated-uuid' })) + +describe('useComfyManagerService', () => { + let service: ReturnType + + beforeEach(() => { + vi.clearAllMocks() + managerState.isNewManagerUI = true + mockAxiosInstance.get.mockResolvedValue({ data: {} }) + mockAxiosInstance.post.mockResolvedValue({ data: null }) + service = useComfyManagerService() + }) + + it('initializes with idle state', () => { + expect(service.isLoading.value).toBe(false) + expect(service.error.value).toBeNull() + }) + + 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() + + expect(mockAxiosInstance.get).toHaveBeenCalledWith( + 'customnode/import_fail_info', + expect.any(Object) + ) + }) + + 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', () => { + it('installPack queues an install task then starts the queue', async () => { + await service.installPack({ + id: 'pack', + version: '1.0.0', + selected_version: '1.0.0', + mode: 'remote', + channel: 'default' + }) + + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + 'manager/queue/task', + expect.objectContaining({ kind: 'install' }), + expect.any(Object) + ) + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + 'manager/queue/start', + null, + expect.any(Object) + ) + }) + + it('uninstallPack queues an uninstall task', async () => { + await service.uninstallPack({ node_name: 'pack', is_unknown: false }) + + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + 'manager/queue/task', + expect.objectContaining({ kind: 'uninstall' }), + expect.any(Object) + ) + }) + + it('updateAllPacks posts to the update_all endpoint', async () => { + await service.updateAllPacks({ mode: 'remote' }) + + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + 'manager/queue/update_all', + null, + expect.objectContaining({ + params: expect.objectContaining({ mode: 'remote' }) + }) + ) + }) + + it('updateComfyUI posts to the update_comfyui endpoint', async () => { + await service.updateComfyUI({ is_stable: true }) + + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + 'manager/queue/update_comfyui', + null, + expect.objectContaining({ + params: expect.objectContaining({ is_stable: true }) + }) + ) + }) + + 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', async () => { + await service.startQueue() + + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + 'manager/queue/start', + null, + expect.any(Object) + ) + }) + }) + + 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') + }) + }) +}) From 4e0298d4fcfd1c88df557bc266ed2ae66eed06c5 Mon Sep 17 00:00:00 2001 From: Matt Miller Date: Thu, 16 Jul 2026 17:57:44 -0700 Subject: [PATCH 03/10] fix: make useApiRequest loading state concurrency-safe Replace the single boolean isLoading ref with a pending-request counter exposed as a computed, so concurrent executeRequest calls on the same composable instance no longer flip isLoading back to false while siblings are still in flight. Update service mocks to the new ComputedRef type. --- src/composables/useApiRequest.test.ts | 23 +++++++++++++++++++ src/composables/useApiRequest.ts | 9 ++++---- src/stores/comfyRegistryStore.test.ts | 7 +++--- .../composables/useConflictDetection.test.ts | 4 ++-- .../manager/stores/comfyManagerStore.test.ts | 4 ++-- 5 files changed, 36 insertions(+), 11 deletions(-) diff --git a/src/composables/useApiRequest.test.ts b/src/composables/useApiRequest.test.ts index 04ad2c916f9..9bccd7d3137 100644 --- a/src/composables/useApiRequest.test.ts +++ b/src/composables/useApiRequest.test.ts @@ -38,6 +38,29 @@ describe('useApiRequest', () => { 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() }) diff --git a/src/composables/useApiRequest.ts b/src/composables/useApiRequest.ts index 90e1655c2ab..9351aa937b7 100644 --- a/src/composables/useApiRequest.ts +++ b/src/composables/useApiRequest.ts @@ -1,5 +1,5 @@ import type { AxiosInstance, AxiosResponse } from 'axios' -import { ref } from 'vue' +import { computed, ref } from 'vue' import { isAbortError } from '@/utils/typeGuardUtil' @@ -33,7 +33,8 @@ export function useApiRequest({ client: AxiosInstance mapError: ApiErrorMapper }) { - const isLoading = ref(false) + const pendingCount = ref(0) + const isLoading = computed(() => pendingCount.value > 0) const error = ref(null) async function executeRequest( @@ -42,7 +43,7 @@ export function useApiRequest({ ): Promise { const { errorContext, routeSpecificErrors, onSuccess } = options - isLoading.value = true + pendingCount.value++ error.value = null try { @@ -55,7 +56,7 @@ export function useApiRequest({ error.value = mapError(err, errorContext, routeSpecificErrors) return null } finally { - isLoading.value = false + pendingCount.value-- } } diff --git a/src/stores/comfyRegistryStore.test.ts b/src/stores/comfyRegistryStore.test.ts index 6cd1f73d3ac..af5153f5c38 100644 --- a/src/stores/comfyRegistryStore.test.ts +++ b/src/stores/comfyRegistryStore.test.ts @@ -1,7 +1,8 @@ import { createTestingPinia } from '@pinia/testing' import { setActivePinia } from 'pinia' 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' @@ -69,7 +70,7 @@ const mockListResult: operations['listAllNodes']['responses'][200]['content']['a describe('useComfyRegistryStore', () => { let mockRegistryService: { - isLoading: ReturnType> + isLoading: ComputedRef error: ReturnType> listAllPacks: ReturnType getPackById: ReturnType @@ -87,7 +88,7 @@ describe('useComfyRegistryStore', () => { setActivePinia(createTestingPinia({ stubActions: false })) vi.clearAllMocks() mockRegistryService = { - isLoading: ref(false), + isLoading: computed(() => false), error: ref(null), listAllPacks: vi.fn().mockImplementation((params) => { // If node_id is provided, return specific nodes diff --git a/src/workbench/extensions/manager/composables/useConflictDetection.test.ts b/src/workbench/extensions/manager/composables/useConflictDetection.test.ts index fca5e7de69d..2448998a912 100644 --- a/src/workbench/extensions/manager/composables/useConflictDetection.test.ts +++ b/src/workbench/extensions/manager/composables/useConflictDetection.test.ts @@ -120,7 +120,7 @@ describe('useConflictDetection', () => { const mockComfyManagerService = { getImportFailInfoBulk: vi.fn(), - isLoading: ref(false), + isLoading: computed(() => false), error: ref(null) } as Partial> as ReturnType< typeof useComfyManagerService @@ -128,7 +128,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/workbench/extensions/manager/stores/comfyManagerStore.test.ts b/src/workbench/extensions/manager/stores/comfyManagerStore.test.ts index fc8e00d5491..6ac10d36589 100644 --- a/src/workbench/extensions/manager/stores/comfyManagerStore.test.ts +++ b/src/workbench/extensions/manager/stores/comfyManagerStore.test.ts @@ -1,7 +1,7 @@ import { createTestingPinia } from '@pinia/testing' import { setActivePinia } from 'pinia' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { nextTick, ref } from 'vue' +import { computed, nextTick, ref } from 'vue' import { useComfyManagerService } from '@/workbench/extensions/manager/services/comfyManagerService' import { useComfyManagerStore } from '@/workbench/extensions/manager/stores/comfyManagerStore' @@ -80,7 +80,7 @@ describe('useComfyManagerStore', () => { setActivePinia(createTestingPinia({ stubActions: false })) vi.clearAllMocks() mockManagerService = { - isLoading: ref(false), + isLoading: computed(() => false), error: ref(null), startQueue: vi.fn().mockResolvedValue(null), getQueueStatus: vi.fn().mockResolvedValue(null), From b736b37339d4dbe89c0518a5c88dd58685f39f69 Mon Sep 17 00:00:00 2001 From: Matt Miller Date: Wed, 26 Aug 2026 08:39:56 -0700 Subject: [PATCH 04/10] fix: address review findings on error mapping and queue-start propagation - customerEventsService/comfyManagerService mapError now returns a dedicated message for axios errors with no response (network/timeout/ CORS), matching comfyRegistryService and releaseService instead of showing "failed with status undefined" - installPack/uninstallPack/etc. now propagate a startQueue failure instead of reporting the queued task as successful when the queue never actually starts - drop redundant vi.clearAllMocks() flagged by oxlint's no-redundant-vitest-cleanup rule --- src/services/comfyRegistryService.test.ts | 1 - src/services/customerEventsService.test.ts | 15 ++++++++ .../services/comfyManagerService.test.ts | 37 ++++++++++++++++++- .../manager/services/comfyManagerService.ts | 19 ++++++++-- 4 files changed, 66 insertions(+), 6 deletions(-) diff --git a/src/services/comfyRegistryService.test.ts b/src/services/comfyRegistryService.test.ts index 4d337e210a9..1fafb8dba56 100644 --- a/src/services/comfyRegistryService.test.ts +++ b/src/services/comfyRegistryService.test.ts @@ -19,7 +19,6 @@ describe('useComfyRegistryService', () => { let service: ReturnType beforeEach(() => { - vi.clearAllMocks() mockAxiosInstance.get.mockResolvedValue({ data: {} }) mockAxiosInstance.post.mockResolvedValue({ data: {} }) service = useComfyRegistryService() diff --git a/src/services/customerEventsService.test.ts b/src/services/customerEventsService.test.ts index 903521ffe3d..a674843fe0a 100644 --- a/src/services/customerEventsService.test.ts +++ b/src/services/customerEventsService.test.ts @@ -266,6 +266,21 @@ describe('useCustomerEventsService', () => { 'Fetching customer events failed: Network Error' ) }) + + it('should handle axios errors with no response (timeout/CORS)', async () => { + mockAxiosInstance.get.mockRejectedValue({ + message: 'timeout of 5000ms exceeded', + response: undefined + }) + vi.mocked(axios.isAxiosError).mockReturnValue(true) + + const result = await service.getMyEvents() + + expect(result).toBeNull() + expect(service.error.value).toBe( + 'Fetching customer events failed: timeout of 5000ms exceeded' + ) + }) }) describe('formatEventType', () => { diff --git a/src/workbench/extensions/manager/services/comfyManagerService.test.ts b/src/workbench/extensions/manager/services/comfyManagerService.test.ts index 054f9f17e4d..3805027b272 100644 --- a/src/workbench/extensions/manager/services/comfyManagerService.test.ts +++ b/src/workbench/extensions/manager/services/comfyManagerService.test.ts @@ -37,7 +37,6 @@ describe('useComfyManagerService', () => { let service: ReturnType beforeEach(() => { - vi.clearAllMocks() managerState.isNewManagerUI = true mockAxiosInstance.get.mockResolvedValue({ data: {} }) mockAxiosInstance.post.mockResolvedValue({ data: null }) @@ -202,6 +201,28 @@ describe('useComfyManagerService', () => { expect.any(Object) ) }) + + it('returns null when the task queues but the queue fails to start', async () => { + mockAxiosInstance.post.mockImplementation((url: string) => + url === 'manager/queue/start' + ? Promise.reject({ response: { status: 500, data: {} } }) + : Promise.resolve({ data: { queued: true } }) + ) + vi.mocked(axios.isAxiosError).mockReturnValue(true) + + const result = await service.installPack({ + id: 'pack', + version: '1.0.0', + selected_version: '1.0.0', + mode: 'remote', + channel: 'default' + }) + + expect(result).toBeNull() + expect(service.error.value).toContain( + 'Starting ComfyUI-Manager job queue failed with status 500' + ) + }) }) describe('error mapping', () => { @@ -248,5 +269,19 @@ describe('useComfyManagerService', () => { 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/workbench/extensions/manager/services/comfyManagerService.ts b/src/workbench/extensions/manager/services/comfyManagerService.ts index 72904b397d5..7c45b7c2204 100644 --- a/src/workbench/extensions/manager/services/comfyManagerService.ts +++ b/src/workbench/extensions/manager/services/comfyManagerService.ts @@ -66,8 +66,12 @@ export const useComfyManagerService = () => { } const axiosError = err as AxiosError<{ message: string }> - const status = axiosError.response?.status - if (status && routeSpecificErrors?.[status]) { + if (!axiosError.response) { + return `${context} failed: ${axiosError.message}` + } + + const status = axiosError.response.status + if (routeSpecificErrors?.[status]) { return routeSpecificErrors[status] } if (status === 404) { @@ -75,7 +79,7 @@ export const useComfyManagerService = () => { } return ( - axiosError.response?.data?.message ?? + axiosError.response.data?.message ?? `${context} failed with status ${status}` ) } @@ -106,7 +110,14 @@ export const useComfyManagerService = () => { const { isQueueOperation, ...requestOptions } = options return sendRequest(apiCall, { ...requestOptions, - onSuccess: isQueueOperation ? startQueue : undefined + onSuccess: isQueueOperation + ? async () => { + await startQueue() + if (error.value) { + throw new Error(error.value) + } + } + : undefined }) } From 6f7ddba3846af4956a66d8fa3591391d484b798d Mon Sep 17 00:00:00 2001 From: Matt Miller Date: Tue, 1 Sep 2026 05:35:23 -0700 Subject: [PATCH 05/10] fix: report queue-start failure instead of throwing main's new comfy/no-new-error-throw rule rejects the throw that signalled a failed queue start, so onSuccess now returns false to mark the request failed and reportError() carries the observability the throw used to provide. The caller contract is unchanged: executeRequest still resolves to null and error still holds the queue-start message, now without the redundant outer wrapper. Also unifies comfyManagerService's request options with ExecuteRequestOptions and covers the abort, queue-suppression, and pack-mutation paths raised in review. --- src/composables/useApiRequest.test.ts | 33 +++++++ src/composables/useApiRequest.ts | 10 ++- .../services/comfyManagerService.test.ts | 86 ++++++++++++++++++- .../manager/services/comfyManagerService.ts | 14 +-- 4 files changed, 133 insertions(+), 10 deletions(-) diff --git a/src/composables/useApiRequest.test.ts b/src/composables/useApiRequest.test.ts index 9bccd7d3137..5d77c16adb8 100644 --- a/src/composables/useApiRequest.test.ts +++ b/src/composables/useApiRequest.test.ts @@ -124,4 +124,37 @@ describe('useApiRequest', () => { ) expect(onSuccess).not.toHaveBeenCalled() }) + + it('does not run onSuccess when the request is aborted', async () => { + mockIsAbortError.mockReturnValue(true) + const onSuccess = vi.fn() + const { executeRequest } = useApiRequest({ client, mapError: vi.fn() }) + + const result = await executeRequest( + () => { + throw new Error('aborted') + }, + { errorContext: 'ctx', onSuccess } + ) + + expect(result).toBeNull() + expect(onSuccess).not.toHaveBeenCalled() + }) + + it('resolves to null and preserves error when onSuccess returns false', async () => { + const mapError = vi.fn() + const { executeRequest, error } = useApiRequest({ client, mapError }) + + const result = await executeRequest(async () => response('ok'), { + errorContext: 'ctx', + onSuccess: () => { + error.value = 'side effect failed' + return false + } + }) + + expect(result).toBeNull() + expect(error.value).toBe('side effect failed') + expect(mapError).not.toHaveBeenCalled() + }) }) diff --git a/src/composables/useApiRequest.ts b/src/composables/useApiRequest.ts index 9351aa937b7..84b19359edc 100644 --- a/src/composables/useApiRequest.ts +++ b/src/composables/useApiRequest.ts @@ -17,8 +17,12 @@ export type ApiErrorMapper = ( export interface ExecuteRequestOptions { errorContext: string routeSpecificErrors?: Record - /** Side effect run after a successful response, before the data is returned. */ - onSuccess?: () => unknown + /** + * Side effect run after a successful response, before the data is returned. + * Returning `false` marks the overall request as failed: `executeRequest` + * resolves to `null` and leaves `error` as the side effect set it. + */ + onSuccess?: () => boolean | void | Promise } /** @@ -48,7 +52,7 @@ export function useApiRequest({ try { const response = await apiCall(client) - await onSuccess?.() + if ((await onSuccess?.()) === false) return null return response.data } catch (err) { if (isAbortError(err)) return null diff --git a/src/workbench/extensions/manager/services/comfyManagerService.test.ts b/src/workbench/extensions/manager/services/comfyManagerService.test.ts index 3805027b272..d12db6260ef 100644 --- a/src/workbench/extensions/manager/services/comfyManagerService.test.ts +++ b/src/workbench/extensions/manager/services/comfyManagerService.test.ts @@ -33,11 +33,16 @@ vi.mock('@/workbench/extensions/manager/composables/useManagerState', () => ({ vi.mock('uuid', () => ({ v4: () => 'generated-uuid' })) +const { reportError } = vi.hoisted(() => ({ reportError: vi.fn() })) + +vi.mock('@/platform/telemetry/reportError', () => ({ reportError })) + describe('useComfyManagerService', () => { let service: ReturnType beforeEach(() => { managerState.isNewManagerUI = true + reportError.mockClear() mockAxiosInstance.get.mockResolvedValue({ data: {} }) mockAxiosInstance.post.mockResolvedValue({ data: null }) service = useComfyManagerService() @@ -182,6 +187,60 @@ describe('useComfyManagerService', () => { ) }) + it.for([ + { + name: 'updateAllPacks', + call: () => service.updateAllPacks({ mode: 'remote' }) + }, + { + name: 'updateComfyUI', + call: () => service.updateComfyUI({ is_stable: true }) + } + ])('$name starts the queue after posting', async ({ call }) => { + await call() + + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + 'manager/queue/start', + null, + expect.any(Object) + ) + }) + + it.for([ + { + 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 then starts the queue', + async ({ call, kind }) => { + await call() + + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + 'manager/queue/task', + expect.objectContaining({ kind }), + expect.any(Object) + ) + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + 'manager/queue/start', + null, + expect.any(Object) + ) + } + ) + it('rebootComfyUI posts to the reboot endpoint', async () => { await service.rebootComfyUI() @@ -202,6 +261,28 @@ describe('useComfyManagerService', () => { ) }) + it('does not start the queue when the task POST fails', async () => { + mockAxiosInstance.post.mockRejectedValue({ + response: { status: 500, data: {} } + }) + vi.mocked(axios.isAxiosError).mockReturnValue(true) + + const result = await service.installPack({ + id: 'pack', + version: '1.0.0', + selected_version: '1.0.0', + mode: 'remote', + channel: 'default' + }) + + expect(result).toBeNull() + expect(mockAxiosInstance.post).not.toHaveBeenCalledWith( + 'manager/queue/start', + null, + expect.any(Object) + ) + }) + it('returns null when the task queues but the queue fails to start', async () => { mockAxiosInstance.post.mockImplementation((url: string) => url === 'manager/queue/start' @@ -219,9 +300,12 @@ describe('useComfyManagerService', () => { }) expect(result).toBeNull() - expect(service.error.value).toContain( + expect(service.error.value).toBe( 'Starting ComfyUI-Manager job queue failed with status 500' ) + expect(reportError).toHaveBeenCalledWith(expect.any(Error), { + errorType: 'manager_queue_start_failed' + }) }) }) diff --git a/src/workbench/extensions/manager/services/comfyManagerService.ts b/src/workbench/extensions/manager/services/comfyManagerService.ts index 7c45b7c2204..4e5a469d22a 100644 --- a/src/workbench/extensions/manager/services/comfyManagerService.ts +++ b/src/workbench/extensions/manager/services/comfyManagerService.ts @@ -2,7 +2,9 @@ import type { AxiosError, AxiosInstance, AxiosResponse } from 'axios' import axios from 'axios' import { v4 as uuidv4 } from 'uuid' +import type { ExecuteRequestOptions } from '@/composables/useApiRequest' import { useApiRequest } from '@/composables/useApiRequest' +import { reportError } from '@/platform/telemetry/reportError' import { api } from '@/scripts/api' import { useManagerState } from '@/workbench/extensions/manager/composables/useManagerState' import type { components } from '@/workbench/extensions/manager/types/generatedManagerTypes' @@ -95,9 +97,7 @@ export const useComfyManagerService = () => { const executeRequest = ( apiCall: (client: AxiosInstance) => Promise>, - options: { - errorContext: string - routeSpecificErrors?: Record + options: Omit & { isQueueOperation?: boolean } ): Promise => { @@ -113,9 +113,11 @@ export const useComfyManagerService = () => { onSuccess: isQueueOperation ? async () => { await startQueue() - if (error.value) { - throw new Error(error.value) - } + if (!error.value) return + reportError(new Error(error.value), { + errorType: 'manager_queue_start_failed' + }) + return false } : undefined }) From f6b559bcd632f81b062710e4a922d879f08f4d62 Mon Sep 17 00:00:00 2001 From: Matt Miller Date: Tue, 1 Sep 2026 08:28:44 -0700 Subject: [PATCH 06/10] fix: derive queue-start outcome per request instead of shared error state - add an onError hook to useApiRequest so a caller can tell its own failure apart from the shared error ref - comfyManagerService: decide queue-start success from this invocation's result, so a concurrent Manager request failing no longer makes a queued operation report manager_queue_start_failed - customerEventsService: use the generated ErrorResponse schema type --- src/composables/useApiRequest.ts | 12 +++++- src/services/customerEventsService.ts | 4 +- .../services/comfyManagerService.test.ts | 26 ++++++++++++ .../manager/services/comfyManagerService.ts | 40 +++++++++++++++---- 4 files changed, 71 insertions(+), 11 deletions(-) diff --git a/src/composables/useApiRequest.ts b/src/composables/useApiRequest.ts index 84b19359edc..6d6fe1d11a4 100644 --- a/src/composables/useApiRequest.ts +++ b/src/composables/useApiRequest.ts @@ -23,6 +23,12 @@ export interface ExecuteRequestOptions { * resolves to `null` and leaves `error` as the side effect set it. */ onSuccess?: () => boolean | void | Promise + /** + * Called with the mapped message when *this* request fails, so a caller can + * tell its own failure apart from the shared `error` ref, which any + * concurrent request may reset or overwrite. Not called on cancellation. + */ + onError?: (message: string) => void } /** @@ -45,7 +51,7 @@ export function useApiRequest({ apiCall: (client: AxiosInstance) => Promise>, options: ExecuteRequestOptions ): Promise { - const { errorContext, routeSpecificErrors, onSuccess } = options + const { errorContext, routeSpecificErrors, onSuccess, onError } = options pendingCount.value++ error.value = null @@ -57,7 +63,9 @@ export function useApiRequest({ } catch (err) { if (isAbortError(err)) return null - error.value = mapError(err, errorContext, routeSpecificErrors) + const message = mapError(err, errorContext, routeSpecificErrors) + error.value = message + onError?.(message) return null } finally { pendingCount.value-- diff --git a/src/services/customerEventsService.ts b/src/services/customerEventsService.ts index 37fdbcfa731..192b00e3857 100644 --- a/src/services/customerEventsService.ts +++ b/src/services/customerEventsService.ts @@ -24,6 +24,8 @@ type CustomerEventsResponseQuery = export type AuditLog = components['schemas']['AuditLog'] +type ErrorResponse = components['schemas']['ErrorResponse'] + const customerApiClient = axios.create({ baseURL: getComfyApiBaseUrl(), headers: { @@ -53,7 +55,7 @@ export const useCustomerEventsService = () => { return `${context} failed: ${err instanceof Error ? err.message : String(err)}` } - const axiosError = err as AxiosError<{ message: string }> + const axiosError = err as AxiosError if (!axiosError.response) { return `${context} failed: ${axiosError.message}` } diff --git a/src/workbench/extensions/manager/services/comfyManagerService.test.ts b/src/workbench/extensions/manager/services/comfyManagerService.test.ts index d12db6260ef..a6be0cdfc6a 100644 --- a/src/workbench/extensions/manager/services/comfyManagerService.test.ts +++ b/src/workbench/extensions/manager/services/comfyManagerService.test.ts @@ -307,6 +307,32 @@ describe('useComfyManagerService', () => { errorType: 'manager_queue_start_failed' }) }) + + it('does not blame the queue start for a concurrent request failure', async () => { + mockAxiosInstance.post.mockImplementation((url: string) => + url === 'manager/queue/start' + ? Promise.resolve({ data: null }) + : Promise.resolve({ data: { queued: true } }) + ) + mockAxiosInstance.get.mockRejectedValue({ + response: { status: 500, data: {} } + }) + vi.mocked(axios.isAxiosError).mockReturnValue(true) + + const [result] = await Promise.all([ + service.installPack({ + id: 'pack', + version: '1.0.0', + selected_version: '1.0.0', + mode: 'remote', + channel: 'default' + }), + service.listInstalledPacks() + ]) + + expect(result).toEqual({ queued: true }) + expect(reportError).not.toHaveBeenCalled() + }) }) describe('error mapping', () => { diff --git a/src/workbench/extensions/manager/services/comfyManagerService.ts b/src/workbench/extensions/manager/services/comfyManagerService.ts index 4e5a469d22a..f8fbfb1564f 100644 --- a/src/workbench/extensions/manager/services/comfyManagerService.ts +++ b/src/workbench/extensions/manager/services/comfyManagerService.ts @@ -101,20 +101,24 @@ export const useComfyManagerService = () => { isQueueOperation?: boolean } ): Promise => { + const { isQueueOperation, ...requestOptions } = options + // Block service calls if not in NEW_UI state if (!isManagerServiceAvailable()) { - error.value = 'Manager service is not available in current mode' + const message = 'Manager service is not available in current mode' + error.value = message + requestOptions.onError?.(message) return Promise.resolve(null) } - const { isQueueOperation, ...requestOptions } = options return sendRequest(apiCall, { ...requestOptions, onSuccess: isQueueOperation ? async () => { - await startQueue() - if (!error.value) return - reportError(new Error(error.value), { + const queueStartError = await requestQueueStart() + if (!queueStartError) return + error.value = queueStartError + reportError(new Error(queueStartError), { errorType: 'manager_queue_start_failed' }) return false @@ -123,16 +127,36 @@ export const useComfyManagerService = () => { }) } - const startQueue = async (signal?: AbortSignal) => { + /** + * Resolves to *this* invocation's failure message, or `null` on success. + * The shared `error` ref cannot answer that: concurrent Manager requests + * reset it on start and overwrite it on failure. + */ + const requestQueueStart = async ( + signal?: AbortSignal + ): Promise => { const errorContext = 'Starting ComfyUI-Manager job queue' const routeSpecificErrors = { 201: 'Created: ComfyUI-Manager job queue is already running' } - return executeRequest( + let failure: string | null = null + await executeRequest( (client) => client.post(ManagerRoute.START_QUEUE, null, { signal }), - { errorContext, routeSpecificErrors } + { + errorContext, + routeSpecificErrors, + onError: (message) => { + failure = message + } + } ) + return failure + } + + const startQueue = async (signal?: AbortSignal): Promise => { + await requestQueueStart(signal) + return null } const getQueueStatus = async (client_id?: string, signal?: AbortSignal) => { From bd1955e038e05b06c054b61eedc5f801501b49b5 Mon Sep 17 00:00:00 2001 From: Matt Miller Date: Mon, 19 Oct 2026 14:05:36 +0000 Subject: [PATCH 07/10] fix: narrow axios errors with isAxiosError instead of casting Also use a real axios instance and complete AxiosResponse in the useApiRequest tests, and drop the idle-state default tests that only asserted ref initial values. Co-Authored-By: Claude Opus 5.5 --- src/composables/useApiRequest.test.ts | 13 ++++++++++--- src/platform/updates/common/releaseService.ts | 13 +++++-------- src/services/comfyRegistryService.test.ts | 5 ----- src/services/comfyRegistryService.ts | 13 +++++-------- src/services/customerEventsService.ts | 13 +++++-------- .../manager/services/comfyManagerService.test.ts | 5 ----- .../manager/services/comfyManagerService.ts | 14 ++++++-------- 7 files changed, 31 insertions(+), 45 deletions(-) diff --git a/src/composables/useApiRequest.test.ts b/src/composables/useApiRequest.test.ts index 0b2c9b617c3..3266c039961 100644 --- a/src/composables/useApiRequest.test.ts +++ b/src/composables/useApiRequest.test.ts @@ -1,4 +1,5 @@ -import type { AxiosInstance, AxiosResponse } from 'axios' +import type { AxiosResponse } from 'axios' +import axios, { AxiosHeaders } from 'axios' import { beforeEach, describe, expect, it, vi } from 'vitest' import { useApiRequest } from '@/composables/useApiRequest' @@ -9,10 +10,16 @@ vi.mock(import('@/utils/typeGuardUtil'), () => ({ isAbortError: mockIsAbortError })) -const client = { id: 'test-client' } as unknown as AxiosInstance +const client = axios.create() function response(data: T): AxiosResponse { - return { data } as AxiosResponse + return { + data, + status: 200, + statusText: 'OK', + headers: {}, + config: { headers: new AxiosHeaders() } + } } describe('useApiRequest', () => { diff --git a/src/platform/updates/common/releaseService.ts b/src/platform/updates/common/releaseService.ts index 41527aaf035..9540ceb580f 100644 --- a/src/platform/updates/common/releaseService.ts +++ b/src/platform/updates/common/releaseService.ts @@ -1,4 +1,3 @@ -import type { AxiosError } from 'axios' import axios from 'axios' import { watch } from 'vue' @@ -34,15 +33,13 @@ export const useReleaseService = () => { 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] @@ -59,11 +56,11 @@ 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 { isLoading, error, executeRequest } = useApiRequest({ diff --git a/src/services/comfyRegistryService.test.ts b/src/services/comfyRegistryService.test.ts index ef7adab1a69..069ed5606f4 100644 --- a/src/services/comfyRegistryService.test.ts +++ b/src/services/comfyRegistryService.test.ts @@ -24,11 +24,6 @@ describe('useComfyRegistryService', () => { service = useComfyRegistryService() }) - it('initializes with idle state', () => { - expect(service.isLoading.value).toBe(false) - expect(service.error.value).toBeNull() - }) - describe('request routing', () => { it('getNodeDefs hits the comfy-nodes endpoint', async () => { await service.getNodeDefs({ packId: 'pack', version: '1.0.0' }) diff --git a/src/services/comfyRegistryService.ts b/src/services/comfyRegistryService.ts index a9775adafa8..6b1af8f43c3 100644 --- a/src/services/comfyRegistryService.ts +++ b/src/services/comfyRegistryService.ts @@ -1,4 +1,3 @@ -import type { AxiosError } from 'axios' import axios from 'axios' import { useApiRequest } from '@/composables/useApiRequest' @@ -26,15 +25,13 @@ export const useComfyRegistryService = () => { 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,11 +50,11 @@ 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}` } const { isLoading, error, executeRequest } = useApiRequest({ diff --git a/src/services/customerEventsService.ts b/src/services/customerEventsService.ts index 56fb04ebef7..dc076d70e5e 100644 --- a/src/services/customerEventsService.ts +++ b/src/services/customerEventsService.ts @@ -1,4 +1,3 @@ -import type { AxiosError } from 'axios' import axios from 'axios' import { ref, watch } from 'vue' @@ -52,23 +51,21 @@ export const useCustomerEventsService = () => { context: string, routeSpecificErrors?: Record ): string => { - if (!axios.isAxiosError(err)) { + if (!axios.isAxiosError>(err)) { return `${context} failed: ${err instanceof Error ? err.message : String(err)}` } - const axiosError = err as AxiosError - if (!axiosError.response) { - return `${context} failed: ${axiosError.message}` + if (!err.response) { + return `${context} failed: ${err.message}` } - const status = axiosError.response.status + const status = err.response.status if (routeSpecificErrors?.[status]) { return routeSpecificErrors[status] } return ( - axiosError.response.data?.message ?? - `${context} failed with status ${status}` + err.response.data.message ?? `${context} failed with status ${status}` ) } diff --git a/src/workbench/extensions/manager/services/comfyManagerService.test.ts b/src/workbench/extensions/manager/services/comfyManagerService.test.ts index f80cf3c2a23..d922be97ddf 100644 --- a/src/workbench/extensions/manager/services/comfyManagerService.test.ts +++ b/src/workbench/extensions/manager/services/comfyManagerService.test.ts @@ -46,11 +46,6 @@ describe('useComfyManagerService', () => { service = useComfyManagerService() }) - it('initializes with idle state', () => { - expect(service.isLoading.value).toBe(false) - expect(service.error.value).toBeNull() - }) - describe('availability gate', () => { it('short-circuits requests when Manager is not in NEW_UI mode', async () => { managerState.isNewManagerUI = false diff --git a/src/workbench/extensions/manager/services/comfyManagerService.ts b/src/workbench/extensions/manager/services/comfyManagerService.ts index e38cde43202..92888dbeaff 100644 --- a/src/workbench/extensions/manager/services/comfyManagerService.ts +++ b/src/workbench/extensions/manager/services/comfyManagerService.ts @@ -1,4 +1,4 @@ -import type { AxiosError, AxiosInstance, AxiosResponse } from 'axios' +import type { AxiosInstance, AxiosResponse } from 'axios' import axios from 'axios' import { v4 as uuidv4 } from 'uuid' @@ -62,16 +62,15 @@ export const useComfyManagerService = () => { context: string, routeSpecificErrors?: Record ): string => { - if (!axios.isAxiosError(err)) { + if (!axios.isAxiosError<{ message?: string }>(err)) { return `${context} failed: ${err instanceof Error ? err.message : String(err)}` } - const axiosError = err as AxiosError<{ message: string }> - if (!axiosError.response) { - return `${context} failed: ${axiosError.message}` + if (!err.response) { + return `${context} failed: ${err.message}` } - const status = axiosError.response.status + const status = err.response.status if (routeSpecificErrors?.[status]) { return routeSpecificErrors[status] } @@ -80,8 +79,7 @@ export const useComfyManagerService = () => { } return ( - axiosError.response.data?.message ?? - `${context} failed with status ${status}` + err.response.data.message ?? `${context} failed with status ${status}` ) } From e6286fd063ba250e164984cce60fe5b84d53e5e3 Mon Sep 17 00:00:00 2001 From: Matt Miller Date: Mon, 19 Oct 2026 14:40:56 +0000 Subject: [PATCH 08/10] fix: keep a stale customer-events failure from overwriting a newer result Co-Authored-By: Claude Opus 5.5 --- src/composables/useApiRequest.test.ts | 30 ++++++++------- src/composables/useApiRequest.ts | 5 ++- src/services/customerEventsService.test.ts | 45 ++++++++++++++++++++++ src/services/customerEventsService.ts | 9 ++++- 4 files changed, 72 insertions(+), 17 deletions(-) diff --git a/src/composables/useApiRequest.test.ts b/src/composables/useApiRequest.test.ts index 3266c039961..195c315323e 100644 --- a/src/composables/useApiRequest.test.ts +++ b/src/composables/useApiRequest.test.ts @@ -1,15 +1,9 @@ import type { AxiosResponse } from 'axios' import axios, { AxiosHeaders } from 'axios' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { useApiRequest } from '@/composables/useApiRequest' -const mockIsAbortError = vi.hoisted(() => vi.fn()) - -vi.mock(import('@/utils/typeGuardUtil'), () => ({ - isAbortError: mockIsAbortError -})) - const client = axios.create() function response(data: T): AxiosResponse { @@ -23,10 +17,6 @@ function response(data: T): AxiosResponse { } describe('useApiRequest', () => { - beforeEach(() => { - mockIsAbortError.mockReturnValue(false) - }) - it('returns response data and toggles loading state', async () => { const { isLoading, error, executeRequest } = useApiRequest({ client, @@ -95,13 +85,12 @@ describe('useApiRequest', () => { }) it('swallows cancellations without mapping an error', async () => { - mockIsAbortError.mockReturnValue(true) const mapError = vi.fn(() => 'should not run') const { error, executeRequest } = useApiRequest({ client, mapError }) const result = await executeRequest( () => { - throw new Error('aborted') + throw new DOMException('aborted', 'AbortError') }, { errorContext: 'ctx' } ) @@ -110,4 +99,19 @@ describe('useApiRequest', () => { expect(mapError).not.toHaveBeenCalled() expect(error.value).toBeNull() }) + + it('does not publish an error once the request is no longer current', async () => { + const mapError = vi.fn(() => 'stale message') + const { error, executeRequest } = useApiRequest({ client, mapError }) + + const result = await executeRequest( + () => { + throw new Error('boom') + }, + { errorContext: 'ctx', isCurrent: () => false } + ) + + expect(result).toBeNull() + expect(error.value).toBeNull() + }) }) diff --git a/src/composables/useApiRequest.ts b/src/composables/useApiRequest.ts index b4ae5a5d5e5..e015746b56b 100644 --- a/src/composables/useApiRequest.ts +++ b/src/composables/useApiRequest.ts @@ -17,6 +17,7 @@ export type ApiErrorMapper = ( export interface ExecuteRequestOptions { errorContext: string routeSpecificErrors?: Record + isCurrent?: () => boolean } /** @@ -39,7 +40,7 @@ export function useApiRequest({ apiCall: (client: AxiosInstance) => Promise>, options: ExecuteRequestOptions ): Promise { - const { errorContext, routeSpecificErrors } = options + const { errorContext, routeSpecificErrors, isCurrent } = options pendingCount.value++ error.value = null @@ -48,7 +49,7 @@ export function useApiRequest({ const response = await apiCall(client) return response.data } catch (err) { - if (isAbortError(err)) return null + if (isAbortError(err) || isCurrent?.() === false) return null error.value = mapError(err, errorContext, routeSpecificErrors) return null diff --git a/src/services/customerEventsService.test.ts b/src/services/customerEventsService.test.ts index 0f6dc99a501..d03914db9f9 100644 --- a/src/services/customerEventsService.test.ts +++ b/src/services/customerEventsService.test.ts @@ -281,6 +281,51 @@ describe('useCustomerEventsService', () => { void activeRequest }) + it.for([ + { + newer: 'success', + expectedError: null, + startNewer: () => { + mockAxiosInstance.get.mockResolvedValueOnce({ + data: mockEventsResponse + }) + } + }, + { + newer: 'noPersonalWorkspace', + expectedError: 'toastMessages.noPersonalWorkspace', + startNewer: () => { + Object.assign(useAuthStore(), { hasPersonalWorkspace: false }) + } + } + ])( + 'keeps an older failure from overwriting a newer $newer result', + async ({ expectedError, startNewer }) => { + let rejectOlder!: (reason: unknown) => void + const olderRequestStarted = new Promise((requestStarted) => { + mockAxiosInstance.get.mockImplementationOnce(() => { + requestStarted() + return new Promise((_resolve, reject) => { + rejectOlder = reject + }) + }) + }) + vi.mocked(axios.isAxiosError).mockReturnValue(true) + + const olderRequest = service.getMyEvents() + await olderRequestStarted + startNewer() + await service.getMyEvents() + + rejectOlder({ + response: { status: 400, data: { message: 'older backend error' } } + }) + + await expect(olderRequest).resolves.toBeNull() + expect(service.error.value).toBe(expectedError) + } + ) + it('should handle 400 errors', async () => { const errorResponse = { response: { diff --git a/src/services/customerEventsService.ts b/src/services/customerEventsService.ts index dc076d70e5e..8741f19bd98 100644 --- a/src/services/customerEventsService.ts +++ b/src/services/customerEventsService.ts @@ -203,7 +203,13 @@ export const useCustomerEventsService = () => { params: { page, limit }, headers: authHeaders }), - { errorContext, routeSpecificErrors } + { + errorContext, + routeSpecificErrors, + isCurrent: () => + requestId === latestRequestId && + authStore.currentUserIdentity() === requestOwner + } ) if (requestId !== latestRequestId) { @@ -211,7 +217,6 @@ export const useCustomerEventsService = () => { } isLoading.value = false if (authStore.currentUserIdentity() !== requestOwner) { - error.value = null return null } return result From 5cf569db6a4d8300d137c0b377e774a68715baba Mon Sep 17 00:00:00 2001 From: Matt Miller Date: Thu, 22 Oct 2026 08:03:53 +0000 Subject: [PATCH 09/10] fix: treat axios cancellations as aborts in useApiRequest Co-Authored-By: Claude Opus 5.5 --- src/composables/useApiRequest.test.ts | 12 +++++++++--- src/composables/useApiRequest.ts | 4 +++- src/platform/updates/common/releaseService.test.ts | 3 ++- src/services/comfyRegistryService.test.ts | 3 ++- src/services/customerEventsService.test.ts | 3 ++- .../manager/services/comfyManagerService.test.ts | 3 ++- 6 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/composables/useApiRequest.test.ts b/src/composables/useApiRequest.test.ts index 195c315323e..d5b3ed0b69e 100644 --- a/src/composables/useApiRequest.test.ts +++ b/src/composables/useApiRequest.test.ts @@ -1,5 +1,5 @@ import type { AxiosResponse } from 'axios' -import axios, { AxiosHeaders } from 'axios' +import axios, { AxiosHeaders, CanceledError } from 'axios' import { describe, expect, it, vi } from 'vitest' import { useApiRequest } from '@/composables/useApiRequest' @@ -84,13 +84,19 @@ describe('useApiRequest', () => { expect(error.value).toBe('mapped message') }) - it('swallows cancellations without mapping an error', async () => { + 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 new DOMException('aborted', 'AbortError') + throw cancellation }, { errorContext: 'ctx' } ) diff --git a/src/composables/useApiRequest.ts b/src/composables/useApiRequest.ts index e015746b56b..9e219b42f11 100644 --- a/src/composables/useApiRequest.ts +++ b/src/composables/useApiRequest.ts @@ -1,4 +1,5 @@ import type { AxiosInstance, AxiosResponse } from 'axios' +import axios from 'axios' import { computed, ref } from 'vue' import { isAbortError } from '@/utils/typeGuardUtil' @@ -49,7 +50,8 @@ export function useApiRequest({ const response = await apiCall(client) return response.data } catch (err) { - if (isAbortError(err) || isCurrent?.() === false) return null + if (isAbortError(err) || axios.isCancel(err) || isCurrent?.() === false) + return null error.value = mapError(err, errorContext, routeSpecificErrors) return null 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/services/comfyRegistryService.test.ts b/src/services/comfyRegistryService.test.ts index 069ed5606f4..bd3061b704d 100644 --- a/src/services/comfyRegistryService.test.ts +++ b/src/services/comfyRegistryService.test.ts @@ -11,7 +11,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/services/customerEventsService.test.ts b/src/services/customerEventsService.test.ts index 4a52ce835cb..9d97e88710d 100644 --- a/src/services/customerEventsService.test.ts +++ b/src/services/customerEventsService.test.ts @@ -30,7 +30,8 @@ const mockI18n = 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/workbench/extensions/manager/services/comfyManagerService.test.ts b/src/workbench/extensions/manager/services/comfyManagerService.test.ts index 6b752945481..61cf1a84121 100644 --- a/src/workbench/extensions/manager/services/comfyManagerService.test.ts +++ b/src/workbench/extensions/manager/services/comfyManagerService.test.ts @@ -14,7 +14,8 @@ const managerState = vi.hoisted(() => ({ isNewManagerUI: true })) vi.mock(import('axios'), () => ({ default: { create: vi.fn(() => mockAxiosInstance), - isAxiosError: vi.fn() + isAxiosError: vi.fn(), + isCancel: vi.fn(() => false) } })) From d238397a47e4385401042077f8f071bf30e7859d Mon Sep 17 00:00:00 2001 From: Matt Miller Date: Mon, 2 Nov 2026 21:24:31 +0000 Subject: [PATCH 10/10] refactor: drop the unused isCurrent option from useApiRequest Customer events was its only caller, and main removed that request code. --- src/composables/useApiRequest.test.ts | 15 --------------- src/composables/useApiRequest.ts | 6 ++---- 2 files changed, 2 insertions(+), 19 deletions(-) diff --git a/src/composables/useApiRequest.test.ts b/src/composables/useApiRequest.test.ts index d5b3ed0b69e..bef4f39df78 100644 --- a/src/composables/useApiRequest.test.ts +++ b/src/composables/useApiRequest.test.ts @@ -105,19 +105,4 @@ describe('useApiRequest', () => { expect(mapError).not.toHaveBeenCalled() expect(error.value).toBeNull() }) - - it('does not publish an error once the request is no longer current', async () => { - const mapError = vi.fn(() => 'stale message') - const { error, executeRequest } = useApiRequest({ client, mapError }) - - const result = await executeRequest( - () => { - throw new Error('boom') - }, - { errorContext: 'ctx', isCurrent: () => false } - ) - - expect(result).toBeNull() - expect(error.value).toBeNull() - }) }) diff --git a/src/composables/useApiRequest.ts b/src/composables/useApiRequest.ts index 9e219b42f11..74a133b217c 100644 --- a/src/composables/useApiRequest.ts +++ b/src/composables/useApiRequest.ts @@ -18,7 +18,6 @@ export type ApiErrorMapper = ( export interface ExecuteRequestOptions { errorContext: string routeSpecificErrors?: Record - isCurrent?: () => boolean } /** @@ -41,7 +40,7 @@ export function useApiRequest({ apiCall: (client: AxiosInstance) => Promise>, options: ExecuteRequestOptions ): Promise { - const { errorContext, routeSpecificErrors, isCurrent } = options + const { errorContext, routeSpecificErrors } = options pendingCount.value++ error.value = null @@ -50,8 +49,7 @@ export function useApiRequest({ const response = await apiCall(client) return response.data } catch (err) { - if (isAbortError(err) || axios.isCancel(err) || isCurrent?.() === false) - return null + if (isAbortError(err) || axios.isCancel(err)) return null error.value = mapError(err, errorContext, routeSpecificErrors) return null