Files
ComfyUI_frontend/tests-ui/tests/store/systemStatsStore.test.ts
Jin Yi 2eb5c2ab91 fix: feature flags and manager state handling (#5317)
* fix: Replace reactive feature flags with non-reactive approach

- Changed managerUIState from computed to getManagerUIState() function
- Ensures fresh computation on each call to avoid timing issues
- Updates all consumers to use the new function-based approach
- Fixes manager UI state determination issues

This change addresses the reactivity issues where feature flags were not
updating properly due to Vue's reactive system limitations with external
API values.

* fix: Add HelpCenter manager state handling and API version switching

- Fixed HelpCenter manager extension to check manager state
- Fixed 'Manager' command to respect manager state
- Added dynamic API prefix switching based on manager state
- Added debug logging for manager state determination

This ensures legacy manager uses /api/ prefix and new manager uses /api/v2/ prefix

* fix: Simplify manager state determination and fix API timing issues

- Remove unnecessary extension check from manager state store
- Use only feature flags (client and server) for state determination
- Default to NEW_UI when server flags not loaded (safer default)
- Fix ImportFailInfoBulk to not send empty requests
- Resolves initial 404 errors on installed API calls

* fix: Correct manager state determination for non-v4 servers

- Fix serverSupportsV4=false returning DISABLED instead of LEGACY_UI
- Server without v4 support should use legacy manager, not disable it
- Clarify condition for server v4 + client non-v4 case

* chore: Remove debug console.log statements

- Remove all debug logging from manager state store
- Remove logging from comfy manager service
- Clean up code for production

* test: Update manager state store tests to match new logic

- Update test expectations for server feature flags undefined case (returns NEW_UI)
- Update test expectations for server not supporting v4 case (returns LEGACY_UI)
- Tests now correctly reflect the actual behavior of the manager state logic

* fix: Remove dynamic API version handling in manager service

- Remove getApiBaseURL() function and axios interceptor
- Always use /api/v2/ for New Manager (hardcoded)
- Add isManagerServiceAvailable() to block service calls when not in NEW_UI state
- Simplify API handling as manager packages are now completely separated

* refactor: Add helper functions to managerStateStore for better code reuse

- Add isManagerEnabled(), isNewManagerUI(), isLegacyManagerUI() helpers
- Add shouldShowInstallButton(), shouldShowManagerButtons() for UI logic
- Update components to use helper functions where applicable
- Add comprehensive tests for new helper functions
- Centralize state checking logic to reduce duplication

* fix: Ensure SystemStats is loaded before conflict detection

- Move conflict detection from App.vue to GraphCanvas.vue
- Check manager state before running conflict detection
- Ensures SystemStats and feature flags are loaded first
- Prevents unnecessary API calls when manager is disabled

* docs: Clarify feature flag default behavior in manager state

- Add detailed comments explaining why NEW_UI is the default
- Clarify that undefined state is temporary during WebSocket connection
- Document graceful error handling when server doesn't support v2 API

* fix: Ensure consistent manager state handling for legacy commands

- Legacy commands now show error toast in NEW_UI mode
- Settings fallback for DISABLED mode
- Consistent error handling across all manager entry points
- Legacy commands only work in LEGACY_UI mode as expected

* refactor: centralize manager opening logic into managerStateStore

- Create openManager() function in managerStateStore to eliminate duplicate code
- Replace 8+ repeated switch statements across different files with single function
- Fix inconsistency where legacy command failure in LEGACY_UI mode incorrectly opened new manager
- Add support for legacy-only commands that should show error in NEW_UI mode
- Ensure all manager entry points behave consistently according to feature flags
- Clean up unused imports and fix ESLint errors

This addresses Christian's code review feedback about duplicate switch statements
and improves maintainability by providing a single source of truth for manager
opening logic.

* fix: use correct i18n import in managerStateStore

- Replace useI18n with direct t import from @/i18n
- Fixes issue where error messages showed as numbers (e.g. '26') instead of text
- Ensures toast messages display correctly in NEW_UI mode when legacy commands are invoked

* feature: initial tab fix

* test: Fix managerStateStore test failures by adding missing mocks

The test was failing because managerStateStore imports dialogService,
which imports ErrorDialogContent.vue that instantiates the app object.
This caused api.addEventListener errors in tests.

Added proper mocks for:
- dialogService
- commandStore
- toastStore

This prevents the problematic import chain and fixes the test failures.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: convert managerStateStore to composable

- Move managerStateStore from store to composable pattern
- All functions are non-reactive utilities that don't need state management
- Follows Pinia guideline: "If it's not reactive, it shouldn't be in a store"
- Update all import paths across 8 files
- Move and update test file accordingly

This change improves architecture consistency as other utility functions
in the codebase also use composables rather than stores when reactivity
is not required.

* refactor: use readonly computed properties instead of getter methods

- Convert all getter methods to readonly computed properties
- Follows Vue conventions for better performance through caching
- Change access pattern from function calls to .value properties
- Update all usages across 6 files
- Thanks to @DrJKL for the suggestion

This improves performance by caching computed values and aligns
with Vue's reactive system patterns.

* fix: check isManagerEnabled check to GraphCanvas.vue to avoid the side-effects of calling useConflictDetection which  include calling useComfyManagerStore

* chore: console.log to console.debug

* chore: useConflictDetection().initializeConflictDetection()

* test: add mockManagerDisabled option to disable manager in Playwright tests

- Add mockManagerDisabled parameter to ComfyPage.setup() (defaults to true)
- Override api.getServerFeature() to return false for manager feature flag
- Prevents manager initialization from interfering with subgraph tests
- Individual tests can still enable manager when needed by passing mockManagerDisabled: false

* chore: text modified

* fix: resolve CI/CD failures by fixing manager initialization timing

## Problem
GraphCanvas.vue was initializing conflict detection during component setup,
causing side effects in test environment where manager is disabled. This led
to 4 Playwright test failures in PR #5317.

## Root Cause
- GraphCanvas.vue called useConflictDetection() in setup phase
- This triggered store side effects even when manager was disabled
- systemStats wasn't ready when checking manager state

## Solution
1. Removed conflict detection initialization from GraphCanvas.vue entirely
2. Refactored systemStatsStore to use VueUse's useAsyncState pattern
3. Added isInitialized check in useManagerState to wait for systemStats
4. Updated useConflictDetection to check manager state internally

## Changes
- **GraphCanvas.vue**: Removed all conflict detection code
- **systemStatsStore**: Implemented useAsyncState for proper async handling
- **useManagerState**: Added isInitialized check before checking manager state
- **useConflictDetection**: Added internal manager state validation
- **App.vue**: Removed unnecessary fetchSystemStats calls
- **Tests**: Updated unit tests for new async behavior

## Test Results
All 4 previously failing Playwright tests now pass:
- featureFlags.spec.ts (feature flag handling)
- subgraph.spec.ts (breadcrumb updates, DOM cleanup)
- widget.spec.ts (image changes)

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* chore: modified the note

* fix: test code modified

* fix: when manager is new manager ui, conflict detectetion should work

* fix: ensure fetch system stats before determine manager stats & when new ui & call legacy ui, open new manger dialog by default

* chore: unnecessary .value deleted & fetch name modified to refetch

* fix: ref type .value needed

* chore: vue use until pattern for waiting initializing

* fix: .value added

* fix: useManagerState test to properly mock reactive refs

The test was failing because it was mocking systemStats and isInitialized as plain values instead of reactive refs. The actual composable uses storeToRefs which returns refs with .value properties.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: when system stats initialized, use until(systemStatsStore.isInitialized)

* fix: test

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-09-06 14:04:09 -07:00

359 lines
10 KiB
TypeScript

import { createPinia, setActivePinia } from 'pinia'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { api } from '@/scripts/api'
import { useSystemStatsStore } from '@/stores/systemStatsStore'
import { isElectron } from '@/utils/envUtil'
// Mock the API
vi.mock('@/scripts/api', () => ({
api: {
getSystemStats: vi.fn()
}
}))
// Mock the envUtil
vi.mock('@/utils/envUtil', () => ({
isElectron: vi.fn()
}))
describe('useSystemStatsStore', () => {
let store: ReturnType<typeof useSystemStatsStore>
beforeEach(() => {
// Mock API to prevent automatic fetch on store creation
vi.mocked(api.getSystemStats).mockResolvedValue(null as any)
setActivePinia(createPinia())
store = useSystemStatsStore()
vi.clearAllMocks()
})
it('should initialize and start fetching immediately', async () => {
// useAsyncState with immediate: true starts loading right away
// In test environment, the mock resolves immediately so loading might be false already
expect(store.systemStats).toBeNull() // Initial value is null
expect(store.error).toBeUndefined()
// Wait for initial fetch to complete
await new Promise((resolve) => setTimeout(resolve, 0))
expect(store.isInitialized).toBe(true) // Should be initialized after fetch
})
describe('refetchSystemStats', () => {
it('should fetch system stats successfully', async () => {
const mockStats = {
system: {
os: 'Windows',
python_version: '3.10.0',
embedded_python: false,
comfyui_version: '1.0.0',
pytorch_version: '2.0.0',
required_frontend_version: '1.24.0',
argv: [],
ram_total: 16000000000,
ram_free: 8000000000
},
devices: []
}
vi.mocked(api.getSystemStats).mockResolvedValue(mockStats)
await store.refetchSystemStats()
expect(store.systemStats).toEqual(mockStats)
expect(store.isLoading).toBe(false)
expect(store.error).toBeUndefined() // useAsyncState uses undefined for no error
expect(store.isInitialized).toBe(true)
expect(api.getSystemStats).toHaveBeenCalled()
})
it('should handle API errors', async () => {
const error = new Error('API Error')
vi.mocked(api.getSystemStats).mockRejectedValue(error)
await store.refetchSystemStats()
expect(store.systemStats).toBeNull() // Initial value stays null on error
expect(store.isLoading).toBe(false)
expect(store.error).toEqual(error) // useAsyncState stores the actual error object
})
it('should handle non-Error objects', async () => {
vi.mocked(api.getSystemStats).mockRejectedValue('String error')
await store.refetchSystemStats()
expect(store.error).toBe('String error') // useAsyncState stores the actual error
})
it('should set loading state correctly', async () => {
let resolvePromise: (value: any) => void = () => {}
const promise = new Promise<any>((resolve) => {
resolvePromise = resolve
})
vi.mocked(api.getSystemStats).mockReturnValue(promise)
const fetchPromise = store.refetchSystemStats()
expect(store.isLoading).toBe(true)
resolvePromise({})
await fetchPromise
expect(store.isLoading).toBe(false)
})
it('should handle system stats updates', async () => {
const updatedStats = {
system: {
os: 'Windows',
python_version: '3.11.0',
embedded_python: false,
comfyui_version: '1.1.0',
pytorch_version: '2.1.0',
required_frontend_version: '1.25.0',
argv: [],
ram_total: 16000000000,
ram_free: 7000000000
},
devices: []
}
vi.mocked(api.getSystemStats).mockResolvedValue(updatedStats)
await store.refetchSystemStats()
expect(store.systemStats).toEqual(updatedStats)
expect(store.isLoading).toBe(false)
expect(store.error).toBeUndefined()
expect(store.isInitialized).toBe(true)
expect(api.getSystemStats).toHaveBeenCalled()
})
})
describe('getFormFactor', () => {
beforeEach(() => {
// Reset systemStats for each test
store.systemStats = null
})
it('should return "other" when systemStats is null', () => {
expect(store.getFormFactor()).toBe('other')
})
it('should return "other" when os is not available', () => {
store.systemStats = {
system: {
python_version: '3.10.0',
embedded_python: false,
comfyui_version: '1.0.0',
pytorch_version: '2.0.0',
argv: [],
ram_total: 16000000000,
ram_free: 8000000000
} as any,
devices: []
}
expect(store.getFormFactor()).toBe('other')
})
describe('desktop environment (Electron)', () => {
beforeEach(() => {
vi.mocked(isElectron).mockReturnValue(true)
})
it('should return "desktop-windows" for Windows desktop', () => {
store.systemStats = {
system: {
os: 'Windows 11',
python_version: '3.10.0',
embedded_python: false,
comfyui_version: '1.0.0',
pytorch_version: '2.0.0',
argv: [],
ram_total: 16000000000,
ram_free: 8000000000
},
devices: []
}
expect(store.getFormFactor()).toBe('desktop-windows')
})
it('should return "desktop-mac" for macOS desktop', () => {
store.systemStats = {
system: {
os: 'Darwin 22.0.0',
python_version: '3.10.0',
embedded_python: false,
comfyui_version: '1.0.0',
pytorch_version: '2.0.0',
argv: [],
ram_total: 16000000000,
ram_free: 8000000000
},
devices: []
}
expect(store.getFormFactor()).toBe('desktop-mac')
})
it('should return "desktop-mac" for Mac desktop', () => {
store.systemStats = {
system: {
os: 'Mac OS X 13.0',
python_version: '3.10.0',
embedded_python: false,
comfyui_version: '1.0.0',
pytorch_version: '2.0.0',
argv: [],
ram_total: 16000000000,
ram_free: 8000000000
},
devices: []
}
expect(store.getFormFactor()).toBe('desktop-mac')
})
it('should return "other" for unknown desktop OS', () => {
store.systemStats = {
system: {
os: 'Linux',
python_version: '3.10.0',
embedded_python: false,
comfyui_version: '1.0.0',
pytorch_version: '2.0.0',
argv: [],
ram_total: 16000000000,
ram_free: 8000000000
},
devices: []
}
expect(store.getFormFactor()).toBe('other')
})
})
describe('git environment (non-Electron)', () => {
beforeEach(() => {
vi.mocked(isElectron).mockReturnValue(false)
})
it('should return "git-windows" for Windows git', () => {
store.systemStats = {
system: {
os: 'Windows 11',
python_version: '3.10.0',
embedded_python: false,
comfyui_version: '1.0.0',
pytorch_version: '2.0.0',
argv: [],
ram_total: 16000000000,
ram_free: 8000000000
},
devices: []
}
expect(store.getFormFactor()).toBe('git-windows')
})
it('should return "git-mac" for macOS git', () => {
store.systemStats = {
system: {
os: 'Darwin 22.0.0',
python_version: '3.10.0',
embedded_python: false,
comfyui_version: '1.0.0',
pytorch_version: '2.0.0',
argv: [],
ram_total: 16000000000,
ram_free: 8000000000
},
devices: []
}
expect(store.getFormFactor()).toBe('git-mac')
})
it('should return "git-linux" for Linux git', () => {
store.systemStats = {
system: {
os: 'linux Ubuntu 22.04',
python_version: '3.10.0',
embedded_python: false,
comfyui_version: '1.0.0',
pytorch_version: '2.0.0',
argv: [],
ram_total: 16000000000,
ram_free: 8000000000
},
devices: []
}
expect(store.getFormFactor()).toBe('git-linux')
})
it('should return "other" for unknown git OS', () => {
store.systemStats = {
system: {
os: 'FreeBSD',
python_version: '3.10.0',
embedded_python: false,
comfyui_version: '1.0.0',
pytorch_version: '2.0.0',
argv: [],
ram_total: 16000000000,
ram_free: 8000000000
},
devices: []
}
expect(store.getFormFactor()).toBe('other')
})
})
describe('case insensitive OS detection', () => {
beforeEach(() => {
vi.mocked(isElectron).mockReturnValue(false)
})
it('should handle uppercase OS names', () => {
store.systemStats = {
system: {
os: 'WINDOWS',
python_version: '3.10.0',
embedded_python: false,
comfyui_version: '1.0.0',
pytorch_version: '2.0.0',
argv: [],
ram_total: 16000000000,
ram_free: 8000000000
},
devices: []
}
expect(store.getFormFactor()).toBe('git-windows')
})
it('should handle mixed case OS names', () => {
store.systemStats = {
system: {
os: 'LiNuX',
python_version: '3.10.0',
embedded_python: false,
comfyui_version: '1.0.0',
pytorch_version: '2.0.0',
argv: [],
ram_total: 16000000000,
ram_free: 8000000000
},
devices: []
}
expect(store.getFormFactor()).toBe('git-linux')
})
})
})
})