LCOV - code coverage report
Current view: top level - src/platform/skills/stores - skillPacksStore.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 26.4 % 144 38
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { defineStore } from 'pinia'
       2              : import { computed, ref, watch } from 'vue'
       3              : 
       4              : import { useCurrentUser } from '@/composables/auth/useCurrentUser'
       5              : import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore'
       6              : import { api } from '@/scripts/api'
       7              : 
       8              : import { reportError } from '@comfyorg/telemetry/reportError'
       9              : 
      10              : import {
      11              :   listSkillPacks,
      12              :   SkillPacksApiError
      13              : } from '@/platform/skills/api/skillsApi'
      14              : import type { SkillPack } from '@/platform/skills/types'
      15              : 
      16         2355 : const AGENT_EXPERIENCE_FLAG = 'agent-in-app-experience'
      17         2355 : const SKILL_PACKS_FLAG = 'agent-skill-packs'
      18              : 
      19            0 : function isRoutesUnavailable(error: unknown): boolean {
      20            0 :   return error instanceof SkillPacksApiError && error.status === 404
      21              : }
      22              : 
      23         2355 : export const useSkillPacksStore = defineStore('skillPacks', () => {
      24          105 :   const packs = ref<SkillPack[]>([])
      25          105 :   const loading = ref(false)
      26          105 :   const hasLoaded = ref(false)
      27              :   // CRUD can populate a partial cache; only a full listing proves absence.
      28              :   // Refreshes keep the last confirmation until a response replaces it.
      29          105 :   const catalogConfirmed = ref(false)
      30          105 :   const loadFailed = ref(false)
      31          105 :   const flagsEnabled = ref(false)
      32              :   // Disabled backend gates answer 404, independently of PostHog flags.
      33          105 :   const routesAvailable = ref(true)
      34              : 
      35          105 :   const agentHosted = computed(
      36              :     () =>
      37              :       api.getServerFeature<{ state?: unknown } | null>('agent')?.state ===
      38              :       'ready'
      39              :   )
      40          105 :   const surfaceEnabled = computed(() => flagsEnabled.value || agentHosted.value)
      41          105 :   const enabled = computed(() => surfaceEnabled.value && routesAvailable.value)
      42              : 
      43          105 :   let flagGateStarted = false
      44          105 :   let fetchGeneration = 0
      45          105 :   let inFlight: Promise<void> | undefined
      46          105 :   let catalogRequested = false
      47          105 :   const { resolvedUserInfo } = useCurrentUser()
      48          105 :   const workspace = useTeamWorkspaceStore()
      49          210 :   function currentScope(): string {
      50          210 :     return JSON.stringify([
      51              :       location.origin,
      52              :       api.apiURL('/agent/skills'),
      53              :       resolvedUserInfo.value?.id ?? null,
      54              :       workspace.workspaceId ?? null
      55              :     ])
      56              :   }
      57          105 :   const scope = ref(currentScope())
      58              : 
      59            0 :   function invalidateCatalog(): void {
      60            0 :     fetchGeneration++
      61            0 :     inFlight = undefined
      62            0 :     packs.value = []
      63            0 :     loading.value = false
      64            0 :     hasLoaded.value = false
      65            0 :     catalogConfirmed.value = false
      66            0 :     loadFailed.value = false
      67            0 :     routesAvailable.value = true
      68              :   }
      69              : 
      70          105 :   watch(
      71              :     currentScope,
      72              :     (next) => {
      73            0 :       scope.value = next
      74            0 :       invalidateCatalog()
      75            0 :       if (catalogRequested && surfaceEnabled.value && resolvedUserInfo.value)
      76            0 :         void ensurePacks()
      77              :     },
      78              :     { flush: 'sync' }
      79              :   )
      80              : 
      81          105 :   watch(
      82              :     surfaceEnabled,
      83              :     (isEnabled, wasEnabled) => {
      84            0 :       if (wasEnabled && !isEnabled) invalidateCatalog()
      85            0 :       if (!wasEnabled && isEnabled && catalogRequested) {
      86            0 :         void fetchPacks().catch(reportFetchFailure)
      87              :       }
      88              :     },
      89              :     { flush: 'sync' }
      90              :   )
      91              : 
      92          108 :   async function startFlagGate({
      93              :     fetch = true
      94              :   }: { fetch?: boolean } = {}): Promise<void> {
      95          108 :     catalogRequested ||= fetch
      96          108 :     if (flagGateStarted) {
      97            3 :       if (fetch && surfaceEnabled.value) {
      98            0 :         if (!routesAvailable.value) void fetchPacks().catch(reportFetchFailure)
      99            0 :         else void ensurePacks()
     100              :       }
     101            3 :       return
     102              :     }
     103          105 :     flagGateStarted = true
     104          108 :     if (fetch && surfaceEnabled.value)
     105            0 :       void fetchPacks().catch(reportFetchFailure)
     106          108 :     try {
     107          105 :       const { default: posthog } = await import('posthog-js')
     108          102 :       const sync = () => {
     109          102 :         flagsEnabled.value =
     110              :           posthog.isFeatureEnabled(AGENT_EXPERIENCE_FLAG) === true &&
     111              :           posthog.isFeatureEnabled(SKILL_PACKS_FLAG) === true
     112              :       }
     113          102 :       posthog.onFeatureFlags((_flags, _variants, context) => {
     114              :         // Ignore failed flag deliveries.
     115            0 :         if (context?.errorsLoading) return
     116            0 :         sync()
     117              :       })
     118          102 :       sync()
     119              :     } catch (error) {
     120            0 :       flagGateStarted = false
     121            0 :       reportError(error, {
     122              :         errorType: 'agent_skill_packs_flag_gate_failure',
     123              :         surface: 'agent'
     124              :       })
     125              :     }
     126              :   }
     127              : 
     128            0 :   function reportFetchFailure(error: unknown): void {
     129            0 :     reportError(error, {
     130              :       errorType: 'error_fetching_agent_skill_packs',
     131              :       surface: 'agent'
     132              :     })
     133              :   }
     134              : 
     135            0 :   function syncScope(): void {
     136            0 :     const next = currentScope()
     137            0 :     if (scope.value === next) return
     138            0 :     scope.value = next
     139            0 :     invalidateCatalog()
     140              :   }
     141              : 
     142            0 :   function fetchPacks(): Promise<void> {
     143            0 :     syncScope()
     144            0 :     catalogRequested = true
     145            0 :     if (inFlight) return inFlight
     146            0 :     const request = fetchPacksOnce().finally(() => {
     147            0 :       if (inFlight === request) inFlight = undefined
     148              :     })
     149            0 :     inFlight = request
     150            0 :     return request
     151              :   }
     152              : 
     153            0 :   function isCurrentScope(requestScope: string): boolean {
     154            0 :     syncScope()
     155            0 :     return requestScope === scope.value
     156              :   }
     157              : 
     158              :   // Syncs first: a backend change has no reactive source, so a response may be
     159              :   // the first to notice it and must move the store to the new scope.
     160            0 :   function isSuperseded(generation: number, requestScope: string): boolean {
     161            0 :     return !isCurrentScope(requestScope) || generation !== fetchGeneration
     162              :   }
     163              : 
     164            0 :   function applyCatalog(nextPacks: SkillPack[]): void {
     165            0 :     packs.value = nextPacks
     166            0 :     hasLoaded.value = true
     167            0 :     catalogConfirmed.value = true
     168            0 :     routesAvailable.value = true
     169              :   }
     170              : 
     171            0 :   async function fetchPacksOnce(): Promise<void> {
     172            0 :     const generation = ++fetchGeneration
     173            0 :     const requestScope = scope.value
     174            0 :     loading.value = true
     175            0 :     loadFailed.value = false
     176            0 :     try {
     177            0 :       const nextPacks = await listSkillPacks()
     178            0 :       if (isSuperseded(generation, requestScope)) return
     179            0 :       applyCatalog(nextPacks)
     180              :     } catch (error) {
     181            0 :       if (isSuperseded(generation, requestScope)) return
     182            0 :       if (isRoutesUnavailable(error)) {
     183            0 :         markUnavailable()
     184            0 :         return
     185              :       }
     186            0 :       loadFailed.value = true
     187            0 :       throw error
     188              :     } finally {
     189            0 :       if (generation === fetchGeneration) loading.value = false
     190              :     }
     191              :   }
     192              : 
     193            0 :   function upsertPack(pack: SkillPack, requestScope = scope.value): void {
     194            0 :     syncScope()
     195            0 :     if (requestScope !== scope.value) return
     196            0 :     fetchGeneration++
     197            0 :     inFlight = undefined
     198            0 :     loading.value = false
     199            0 :     hasLoaded.value = true
     200            0 :     loadFailed.value = false
     201            0 :     const rest = packs.value.filter((existing) => existing.name !== pack.name)
     202            0 :     packs.value = [...rest, pack].sort((a, b) => a.name.localeCompare(b.name))
     203              :   }
     204              : 
     205            0 :   function removePack(name: string, requestScope = scope.value): void {
     206            0 :     syncScope()
     207            0 :     if (requestScope !== scope.value) return
     208            0 :     fetchGeneration++
     209            0 :     inFlight = undefined
     210            0 :     loading.value = false
     211            0 :     packs.value = packs.value.filter((pack) => pack.name !== name)
     212              :   }
     213              : 
     214            0 :   function markUnavailable(): void {
     215            0 :     fetchGeneration++
     216            0 :     inFlight = undefined
     217            0 :     loading.value = false
     218            0 :     routesAvailable.value = false
     219            0 :     hasLoaded.value = false
     220            0 :     catalogConfirmed.value = false
     221            0 :     packs.value = []
     222              :   }
     223              : 
     224            0 :   async function refreshPacks(): Promise<void> {
     225            0 :     syncScope()
     226            0 :     if (!enabled.value) return
     227            0 :     await fetchPacks().catch(reportFetchFailure)
     228              :   }
     229              : 
     230              :   // Lists after any in-flight request, so the result covers earlier changes.
     231            0 :   async function refreshPacksInBackground(): Promise<void> {
     232            0 :     syncScope()
     233            0 :     const requestScope = scope.value
     234            0 :     if (inFlight) await inFlight.catch(() => undefined)
     235            0 :     if (!isCurrentScope(requestScope) || !enabled.value) return
     236            0 :     await fetchPacks().catch(reportFetchFailure)
     237              :   }
     238              : 
     239            0 :   async function ensurePacks(): Promise<void> {
     240            0 :     syncScope()
     241            0 :     if (
     242              :       !enabled.value ||
     243              :       loading.value ||
     244              :       (hasLoaded.value && !loadFailed.value)
     245              :     )
     246            0 :       return
     247            0 :     await refreshPacks()
     248              :   }
     249              : 
     250          105 :   return {
     251              :     packs,
     252              :     loading,
     253              :     hasLoaded,
     254              :     catalogConfirmed,
     255              :     loadFailed,
     256              :     scope,
     257              :     enabled,
     258              :     flagsEnabled,
     259              :     routesAvailable,
     260              :     startFlagGate,
     261              :     fetchPacks,
     262              :     refreshPacks,
     263              :     refreshPacksInBackground,
     264              :     ensurePacks,
     265              :     isCurrentScope,
     266              :     upsertPack,
     267              :     removePack,
     268              :     markUnavailable
     269              :   }
     270              : })
        

Generated by: LCOV version 2.0-1