Line data Source code
1 : import { until } from '@vueuse/core'
2 : import { find } from 'es-toolkit/compat'
3 : import { computed, getCurrentInstance, onUnmounted, readonly, ref } from 'vue'
4 :
5 : import { useComfyRegistryService } from '@/services/comfyRegistryService'
6 : import { useSystemStatsStore } from '@/stores/systemStatsStore'
7 : import type { components } from '@/types/comfyRegistryTypes'
8 : import { useInstalledPacks } from '@/platform/customNodes/manager/composables/nodePack/useInstalledPacks'
9 : import { useConflictAcknowledgment } from '@/platform/customNodes/manager/composables/useConflictAcknowledgment'
10 : import { useManagerState } from '@/platform/customNodes/manager/composables/useManagerState'
11 : import { useComfyManagerService } from '@/platform/customNodes/manager/services/comfyManagerService'
12 : import { useComfyManagerStore } from '@/platform/customNodes/manager/stores/comfyManagerStore'
13 : import { useConflictDetectionStore } from '@/platform/customNodes/manager/stores/conflictDetectionStore'
14 : import type {
15 : RegistryAccelerator,
16 : RegistryOS
17 : } from '@/platform/customNodes/manager/types/compatibility.types'
18 : import type {
19 : ConflictDetectionResponse,
20 : ConflictDetectionResult,
21 : ImportFailureMap,
22 : Node,
23 : NodeRequirements,
24 : SystemEnvironment
25 : } from '@/platform/customNodes/manager/types/conflictDetectionTypes'
26 : import {
27 : consolidateConflictsByPackage,
28 : deriveStatusFlags,
29 : evaluateCompatibility
30 : } from '@/platform/customNodes/manager/utils/conflictUtils'
31 : import { normalizeOSList } from '@/platform/customNodes/manager/utils/systemCompatibility'
32 : import { getFrontendVersion } from '@/platform/customNodes/manager/utils/versionUtil'
33 :
34 : /**
35 : * Composable for conflict detection system.
36 : * Error-resilient and asynchronous to avoid affecting other components.
37 : */
38 9371 : export function useConflictDetection() {
39 9371 : const managerStore = useComfyManagerStore()
40 :
41 9371 : const {
42 : startFetchInstalled,
43 : installedPacks,
44 : installedPacksWithVersions,
45 : isReady: installedPacksReady
46 : } = useInstalledPacks()
47 :
48 9371 : const isDetecting = ref(false)
49 9371 : const lastDetectionTime = ref<string | null>(null)
50 9371 : const detectionError = ref<string | null>(null)
51 :
52 9371 : const systemEnvironment = ref<SystemEnvironment | null>(null)
53 :
54 9371 : const detectionResults = ref<ConflictDetectionResult[]>([])
55 : // Store merged conflicts separately for testing
56 9371 : const storedMergedConflicts = ref<ConflictDetectionResult[]>([])
57 :
58 : // Registry API request cancellation
59 9371 : const abortController = ref<AbortController | null>(null)
60 :
61 9371 : const acknowledgment = useConflictAcknowledgment()
62 :
63 9371 : const conflictStore = useConflictDetectionStore()
64 :
65 9371 : const hasConflicts = computed(() => conflictStore.hasConflicts)
66 9371 : const conflictedPackages = computed(() => {
67 0 : return conflictStore.conflictedPackages
68 : })
69 :
70 9371 : const bannedPackages = computed(() => conflictStore.bannedPackages)
71 9371 : const securityPendingPackages = computed(
72 : () => conflictStore.securityPendingPackages
73 : )
74 :
75 : /**
76 : * Collects current system environment information.
77 : * Continues with default values even if errors occur.
78 : * @returns Promise that resolves to system environment information
79 : */
80 15 : async function collectSystemEnvironment(): Promise<SystemEnvironment> {
81 15 : try {
82 : // Get system stats from store (primary source of system information)
83 : // Wait for systemStats to be initialized if not already
84 15 : const systemStatsStore = useSystemStatsStore()
85 15 : const { systemStats } = systemStatsStore
86 :
87 : // Wait for initialization using the store's isInitialized property (correct reactive way)
88 15 : await until(() => systemStatsStore.isInitialized).toBe(true)
89 :
90 15 : const frontendVersion = getFrontendVersion()
91 :
92 15 : const environment: SystemEnvironment = {
93 : comfyui_version: systemStats?.system.comfyui_version ?? '',
94 : frontend_version: frontendVersion,
95 : os: systemStats?.system.os ?? '',
96 : accelerator: systemStats?.devices[0]?.type ?? ''
97 : }
98 :
99 15 : systemEnvironment.value = environment
100 15 : return environment
101 : } catch {
102 0 : const fallbackEnvironment: SystemEnvironment = {
103 : comfyui_version: undefined,
104 : frontend_version: undefined,
105 : os: undefined,
106 : accelerator: undefined
107 : }
108 0 : systemEnvironment.value = fallbackEnvironment
109 0 : return fallbackEnvironment
110 : }
111 : }
112 :
113 : /**
114 : * Fetches requirement information for installed packages using Registry Store.
115 : *
116 : * This function combines local installation data with Registry API compatibility metadata
117 : * using the established store layer pattern with caching and batch requests.
118 : *
119 : * Process
120 : * 1. Get locally installed packages
121 : * 2. Batch fetch Registry data using store layer
122 : * 3. Combine local + Registry data
123 : * 4. Extract compatibility requirements
124 : *
125 : * @returns Promise that resolves to array of node pack requirements
126 : */
127 15 : async function buildNodeRequirements(): Promise<NodeRequirements[]> {
128 15 : try {
129 : // Step 1: Use installed packs composable instead of direct API calls
130 15 : await startFetchInstalled() // Ensure data is loaded
131 :
132 15 : if (!installedPacksReady.value || installedPacks.value.length === 0) {
133 0 : console.warn(
134 : '[ConflictDetection] No installed packages available from useInstalledPacks'
135 : )
136 0 : return []
137 : }
138 :
139 : // Step 2: Get Registry service for bulk API calls
140 15 : const registryService = useComfyRegistryService()
141 :
142 : // Step 3: Setup abort controller for request cancellation
143 15 : abortController.value = new AbortController()
144 :
145 : // Step 4: Use bulk API to fetch all version data in a single request
146 15 : const versionDataMap = new Map<
147 : string,
148 : components['schemas']['NodeVersion']
149 : >()
150 :
151 : // Prepare bulk request with actual installed versions from Manager API
152 15 : const nodeVersions = installedPacksWithVersions.value.map((pack) => ({
153 : node_id: pack.id,
154 : version: pack.version
155 : }))
156 :
157 15 : if (nodeVersions.length > 0) {
158 15 : try {
159 15 : const bulkResponse = await registryService.getBulkNodeVersions(
160 : nodeVersions,
161 : abortController.value.signal
162 : )
163 :
164 15 : if (bulkResponse && bulkResponse.node_versions.length > 0) {
165 : // Process bulk response
166 0 : bulkResponse.node_versions.forEach((result) => {
167 0 : if (result.status === 'success' && result.node_version) {
168 0 : versionDataMap.set(
169 : result.identifier.node_id,
170 : result.node_version
171 : )
172 0 : } else if (result.status === 'error') {
173 0 : console.warn(
174 : `[ConflictDetection] Failed to fetch version data for ${result.identifier.node_id}@${result.identifier.version}:`,
175 : result.error_message
176 : )
177 : }
178 : })
179 : }
180 : } catch (error) {
181 0 : console.warn(
182 : '[ConflictDetection] Failed to fetch bulk version data:',
183 : error
184 : )
185 : }
186 : }
187 :
188 : // Step 5: Combine local installation data with Registry version data
189 15 : const requirements: NodeRequirements[] = []
190 :
191 : // IMPORTANT: Use installedPacksWithVersions to check ALL installed packages
192 : // not just the ones that exist in Registry (installedPacks)
193 15 : for (const installedPackVersion of installedPacksWithVersions.value) {
194 30 : const versionData = versionDataMap.get(installedPackVersion.id)
195 30 : const isEnabled = managerStore.isPackEnabled(installedPackVersion.id)
196 :
197 : // Find the pack info from Registry if available
198 30 : const packInfo = find(installedPacks.value, {
199 : id: installedPackVersion.id
200 : })
201 :
202 30 : if (versionData) {
203 0 : const { isBanned, isPending } = deriveStatusFlags(versionData.status)
204 :
205 : // Combine local installation data with version-specific Registry data
206 0 : const requirement: NodeRequirements = {
207 : // Basic package info
208 : id: installedPackVersion.id,
209 : name: packInfo?.name || installedPackVersion.id,
210 : installed_version: installedPackVersion.version,
211 : is_enabled: isEnabled,
212 :
213 : // Version-specific compatibility data
214 : supported_comfyui_version: versionData.supported_comfyui_version,
215 : supported_comfyui_frontend_version:
216 : versionData.supported_comfyui_frontend_version,
217 : supported_os: normalizeOSList(versionData.supported_os),
218 : supported_accelerators: versionData.supported_accelerators,
219 :
220 : // Status information
221 : version_status: versionData.status,
222 : is_banned: isBanned,
223 : is_pending: isPending
224 : }
225 :
226 0 : requirements.push(requirement)
227 : } else {
228 30 : console.warn(
229 : `[ConflictDetection] No Registry data found for ${installedPackVersion.id}, using fallback`
230 : )
231 :
232 : // Create fallback requirement without Registry data
233 30 : const fallbackRequirement: NodeRequirements = {
234 : id: installedPackVersion.id,
235 : name: packInfo?.name || installedPackVersion.id,
236 : installed_version: installedPackVersion.version,
237 : is_enabled: isEnabled,
238 : is_banned: false,
239 : is_pending: false
240 : }
241 :
242 30 : requirements.push(fallbackRequirement)
243 : }
244 : }
245 :
246 15 : return requirements
247 : } catch (error) {
248 0 : console.warn(
249 : '[ConflictDetection] Failed to fetch package requirements:',
250 : error
251 : )
252 0 : return []
253 : }
254 : }
255 :
256 : /**
257 : * Detects conflicts for an individual package using Registry API data.
258 : *
259 : * @param packageReq Package requirements from Registry
260 : * @param sysEnv Current system environment
261 : * @returns Conflict detection result for the package
262 : */
263 30 : function analyzePackageConflicts(
264 : packageReq: NodeRequirements,
265 : systemEnvInfo: SystemEnvironment
266 : ): ConflictDetectionResult {
267 30 : const conflicts = evaluateCompatibility(
268 : {
269 : supported_os: packageReq.supported_os as RegistryOS[] | undefined,
270 : supported_accelerators: packageReq.supported_accelerators as
271 : | RegistryAccelerator[]
272 : | undefined,
273 : supported_comfyui_version: packageReq.supported_comfyui_version,
274 : supported_comfyui_frontend_version:
275 : packageReq.supported_comfyui_frontend_version,
276 : isBanned: packageReq.is_banned,
277 : isPending: packageReq.is_pending
278 : },
279 : systemEnvInfo
280 : )
281 :
282 30 : const hasConflict = conflicts.length > 0
283 :
284 30 : return {
285 : package_id: packageReq.id ?? '',
286 : package_name: packageReq.name ?? '',
287 : has_conflict: hasConflict,
288 : conflicts,
289 : is_compatible: !hasConflict
290 : }
291 : }
292 :
293 : /**
294 : * Fetches Python import failure information from ComfyUI Manager.
295 : * Gets installed packages and checks each one for import failures using bulk API.
296 : * @returns Promise that resolves to import failure data
297 : */
298 15 : async function fetchImportFailInfo(): Promise<ImportFailureMap> {
299 15 : try {
300 15 : const comfyManagerService = useComfyManagerService()
301 :
302 : // Use installedPacksWithVersions to match what versions bulk API uses
303 : // This ensures both APIs check the same set of packages
304 15 : if (installedPacksWithVersions.value.length === 0) {
305 0 : console.warn(
306 : '[ConflictDetection] No installed packages available for import failure check'
307 : )
308 0 : return {}
309 : }
310 :
311 15 : const packageIds = installedPacksWithVersions.value.map((pack) => pack.id)
312 :
313 : // Use bulk API to get import failure info for all packages at once
314 15 : const bulkResult = await comfyManagerService.getImportFailInfoBulk(
315 : { cnr_ids: packageIds },
316 : abortController.value?.signal
317 : )
318 :
319 15 : if (bulkResult) {
320 : // Filter out null values (packages without import failures)
321 15 : const importFailures: ImportFailureMap = {}
322 :
323 15 : Object.entries(bulkResult).forEach(([packageId, failInfo]) => {
324 0 : if (failInfo !== null) {
325 0 : importFailures[packageId] = failInfo
326 : }
327 : })
328 :
329 15 : return importFailures
330 : }
331 :
332 0 : return {}
333 : } catch (error) {
334 0 : console.warn(
335 : '[ConflictDetection] Failed to fetch import failure information:',
336 : error
337 : )
338 0 : return {}
339 : }
340 : }
341 :
342 : /**
343 : * Detects runtime conflicts from Python import failures.
344 : * @param importFailInfo Import failure data from Manager API
345 : * @returns Array of conflict detection results for failed imports
346 : */
347 15 : function detectImportFailConflicts(
348 : importFailInfo: ImportFailureMap
349 : ): ConflictDetectionResult[] {
350 15 : const results: ConflictDetectionResult[] = []
351 15 : if (typeof importFailInfo !== 'object') {
352 0 : return results
353 : }
354 :
355 : // Process import failures
356 15 : for (const [packageId, failureInfo] of Object.entries(importFailInfo)) {
357 0 : if (!failureInfo || typeof failureInfo !== 'object') continue
358 :
359 0 : const errorMsg = failureInfo.error || 'Unknown import error'
360 0 : const fullErrorInfo = failureInfo.traceback || errorMsg
361 :
362 0 : results.push({
363 : package_id: packageId,
364 : package_name: packageId,
365 : has_conflict: true,
366 : conflicts: [
367 : {
368 : type: 'import_failed',
369 : current_value: errorMsg,
370 : required_value: fullErrorInfo
371 : }
372 : ],
373 : is_compatible: false
374 : })
375 :
376 0 : console.warn(
377 : `[ConflictDetection] Python import failure detected for ${packageId}:`,
378 : errorMsg
379 : )
380 : }
381 :
382 15 : return results
383 : }
384 :
385 : /**
386 : * Performs complete conflict detection.
387 : * @returns Promise that resolves to conflict detection response
388 : */
389 15 : async function runFullConflictAnalysis(): Promise<ConflictDetectionResponse> {
390 15 : if (isDetecting.value) {
391 0 : return {
392 : success: false,
393 : error_message: 'Already detecting conflicts',
394 : results: detectionResults.value
395 : }
396 : }
397 :
398 15 : isDetecting.value = true
399 15 : detectionError.value = null
400 :
401 15 : try {
402 : // 1. Collect system environment information
403 15 : const systemEnvInfo = await collectSystemEnvironment()
404 :
405 : // 2. Collect installed node requirement information
406 : const installedNodeRequirements = await buildNodeRequirements()
407 :
408 : // 3. Detect conflicts for each package (parallel processing)
409 15 : const conflictDetectionTasks = installedNodeRequirements.map(
410 : async (packageReq) => {
411 30 : try {
412 30 : return analyzePackageConflicts(packageReq, systemEnvInfo)
413 : } catch (error) {
414 0 : console.warn(
415 : `[ConflictDetection] Failed to detect conflicts for package ${packageReq.name}:`,
416 : error
417 : )
418 : // Return null for failed packages, will be filtered out
419 0 : return null
420 : }
421 : }
422 : )
423 :
424 : const conflictResults = await Promise.allSettled(conflictDetectionTasks)
425 15 : const packageResults: ConflictDetectionResult[] = conflictResults
426 : .map((result) => (result.status === 'fulfilled' ? result.value : null))
427 : .filter((result): result is ConflictDetectionResult => result !== null)
428 :
429 : // 4. Detect Python import failures
430 : const importFailInfo = await fetchImportFailInfo()
431 15 : const importFailResults = detectImportFailConflicts(importFailInfo)
432 :
433 : // 5. Combine all results
434 15 : const allResults = [...packageResults, ...importFailResults]
435 :
436 : // 6. Update state
437 15 : detectionResults.value = allResults
438 15 : lastDetectionTime.value = new Date().toISOString()
439 :
440 : // Store conflict results for later UI display
441 : // Dialog will be shown based on specific events, not on app mount
442 15 : if (allResults.some((result) => result.has_conflict)) {
443 : const conflictedResults = allResults.filter(
444 : (result) => result.has_conflict
445 : )
446 :
447 : // Merge conflicts for packages with the same name
448 0 : const mergedConflicts = consolidateConflictsByPackage(conflictedResults)
449 :
450 : // Store merged conflicts in Pinia store for UI usage
451 0 : conflictStore.setConflictedPackages(mergedConflicts)
452 :
453 : // Also update local state for backward compatibility
454 0 : detectionResults.value = [...mergedConflicts]
455 0 : storedMergedConflicts.value = [...mergedConflicts]
456 :
457 : // Use merged conflicts in response as well
458 : const response: ConflictDetectionResponse = {
459 : success: true,
460 : results: mergedConflicts,
461 : detected_system_environment: systemEnvInfo
462 : }
463 0 : return response
464 : } else {
465 : // No conflicts detected, clear the results
466 15 : conflictStore.clearConflicts()
467 15 : detectionResults.value = []
468 : }
469 :
470 : const response: ConflictDetectionResponse = {
471 : success: true,
472 : results: allResults,
473 : detected_system_environment: systemEnvInfo
474 : }
475 :
476 15 : return response
477 : } catch (error) {
478 0 : console.error(
479 : '[ConflictDetection] Error during conflict detection:',
480 : error
481 : )
482 0 : detectionError.value =
483 : error instanceof Error ? error.message : String(error)
484 :
485 0 : return {
486 : success: false,
487 : error_message: detectionError.value,
488 : results: []
489 : }
490 : } finally {
491 15 : isDetecting.value = false
492 : // Clear abort controller to prevent memory leaks
493 15 : if (abortController.value) {
494 15 : abortController.value = null
495 : }
496 : }
497 : }
498 :
499 : /**
500 : * Error-resilient initialization (called on app mount).
501 : * Async function that doesn't block UI setup.
502 : * Ensures proper order: system_stats -> manager state -> installed -> versions bulk -> import_fail_info_bulk
503 : */
504 2355 : async function initializeConflictDetection(): Promise<void> {
505 2355 : try {
506 : // First, wait for systemStats to be initialized
507 2355 : const systemStatsStore = useSystemStatsStore()
508 2355 : await until(() => systemStatsStore.isInitialized).toBe(true)
509 :
510 : // Now check if manager is new Manager
511 : const managerState = useManagerState()
512 :
513 2355 : if (!managerState.isNewManagerUI.value) {
514 2340 : return
515 : }
516 :
517 : // Manager is new Manager, perform conflict detection
518 : // The useInstalledPacks will handle fetching installed list if needed
519 15 : await runFullConflictAnalysis()
520 : } catch (error) {
521 0 : console.warn(
522 : '[ConflictDetection] Error during initialization (ignored):',
523 : error
524 : )
525 : // Errors do not affect other parts of the app
526 : }
527 : }
528 :
529 : // Cleanup function for request cancellation
530 517 : function cancelRequests(): void {
531 517 : if (abortController.value) {
532 0 : abortController.value.abort()
533 0 : abortController.value = null
534 : }
535 : }
536 :
537 : // Auto-cleanup on component unmount
538 : // Only register lifecycle hooks if we're in a Vue component context
539 : const instance = getCurrentInstance()
540 9371 : if (instance) {
541 9371 : onUnmounted(() => {
542 517 : cancelRequests()
543 : })
544 : }
545 :
546 : // Helper functions (implementations at the bottom of the file)
547 :
548 : /**
549 : * Check if conflicts should trigger modal display after "What's New" dismissal
550 : */
551 0 : async function shouldShowConflictModalAfterUpdate(): Promise<boolean> {
552 : // Ensure conflict detection has run
553 0 : if (detectionResults.value.length === 0) {
554 0 : await runFullConflictAnalysis()
555 : }
556 :
557 : // Check if this is a version update scenario
558 : // In a real scenario, this would check actual version change
559 : // For now, we'll assume it's an update if we have conflicts and modal hasn't been dismissed
560 0 : const hasActualConflicts = hasConflicts.value
561 0 : const canShowModal = acknowledgment.shouldShowConflictModal.value
562 :
563 0 : return hasActualConflicts && canShowModal
564 : }
565 :
566 : /**
567 : * Check compatibility for a node.
568 : * Used by components like PackVersionSelectorPopover.
569 : */
570 193 : function checkNodeCompatibility(
571 : node: Node | components['schemas']['NodeVersion']
572 : ) {
573 193 : const { isBanned, isPending } = deriveStatusFlags(node.status)
574 193 : const conflicts = evaluateCompatibility(
575 : {
576 : supported_os: normalizeOSList(node.supported_os),
577 : supported_accelerators:
578 : node.supported_accelerators as RegistryAccelerator[],
579 : supported_comfyui_version: node.supported_comfyui_version,
580 : supported_comfyui_frontend_version:
581 : node.supported_comfyui_frontend_version,
582 : isBanned,
583 : isPending
584 : },
585 : {
586 : comfyui_version: systemEnvironment.value?.comfyui_version,
587 : frontend_version: getFrontendVersion(),
588 : os: systemEnvironment.value?.os,
589 : accelerator: systemEnvironment.value?.accelerator
590 : }
591 : )
592 :
593 193 : return {
594 : hasConflict: conflicts.length > 0,
595 : conflicts
596 : }
597 : }
598 :
599 9371 : return {
600 : // State
601 : isDetecting: readonly(isDetecting),
602 : lastDetectionTime: readonly(lastDetectionTime),
603 : detectionError: readonly(detectionError),
604 : systemEnvironment: readonly(systemEnvironment),
605 : detectionResults: readonly(detectionResults),
606 :
607 : // Computed
608 : hasConflicts,
609 : conflictedPackages,
610 : bannedPackages,
611 : securityPendingPackages,
612 :
613 : // Methods
614 : runFullConflictAnalysis,
615 : collectSystemEnvironment,
616 : initializeConflictDetection,
617 : cancelRequests,
618 : shouldShowConflictModalAfterUpdate,
619 :
620 : // Helper functions for other components
621 : checkNodeCompatibility
622 : }
623 : }
|