/* oxlint-disable testing-library/no-container */ /* oxlint-disable testing-library/no-node-access */ import { getActivePinia } from 'pinia' import type { Pinia } from 'pinia' import userEvent from '@testing-library/user-event' import { render, screen, waitFor } from '@testing-library/vue' import type { MenuItem } from '@comfyorg/design-system/lib/menu/types' import { assert, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { computed, defineComponent, h, nextTick, onMounted, ref } from 'vue' import type { Component } from 'vue' import { createI18n } from 'vue-i18n' import { useCurrentUser } from '@/composables/auth/useCurrentUser' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { useTelemetry } from '@comfyorg/telemetry' import { openDeployToComfyApiDialog } from '@/platform/workflow/deploy/composables/lazyDeployToComfyApiDialog' import QueueNotificationBannerHost from '@/components/queue/QueueNotificationBannerHost.vue' import TopMenuSection from '@/components/TopMenuSection.vue' import type { JobListItem, JobStatus } from '@/platform/remote/comfyui/jobs/jobTypes' import { useSettingStore } from '@/platform/settings/settingStore' import { DEPLOYMENT_LISTING_EXTENSIONS_WAIT_MS } from '@/platform/workspace/api/deploymentListingTimeouts' import { loadedEvent, reduceDeploymentPick } from '@/platform/workspace/deploymentPickState' import { openDeployCustomNodesDialog } from '@/platform/workspace/openCustomDeploymentDialog' import { useDeploymentPickStore } from '@/platform/workspace/stores/deploymentPickStore' import { useReleaseStore } from '@/platform/updates/common/releaseStore' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' import { useCommandStore } from '@/platform/keybindings/commandStore' import { useExecutionStore } from '@/stores/executionStore' import { TaskItemImpl, useQueueStore } from '@/stores/queueStore' import { useSidebarTabStore } from '@/stores/workspace/sidebarTabStore' import { useManagerState } from '@/platform/customNodes/manager/composables/useManagerState' vi.mock(import('firebase/auth')) const mockData = vi.hoisted(() => ({ setShowConflictRedDot: (_value: boolean) => {} })) const managerSurveyDialog = vi.hoisted(() => ({ show: vi.fn(), hide: vi.fn() })) vi.mock( import('@/platform/customNodes/manager/composables/useManagerSurveyDialog'), () => ({ useManagerSurveyDialog: () => managerSurveyDialog }) ) vi.mock(import('@/composables/auth/useCurrentUser')) const distribution = vi.hoisted(() => ({ isCloud: false })) vi.mock(import('@/platform/distribution/types'), () => ({ get isCloud() { return distribution.isCloud }, isNightly: false })) vi.mock(import('@/composables/useFeatureFlags')) vi.mock( import('@/platform/workflow/deploy/composables/lazyDeployToComfyApiDialog'), () => ({ openDeployToComfyApiDialog: vi.fn(async () => {}) }) ) vi.mock( import('@/platform/customNodes/manager/composables/useConflictAcknowledgment'), () => { const shouldShowConflictRedDot = ref(false) mockData.setShowConflictRedDot = (value: boolean) => { shouldShowConflictRedDot.value = value } return { useConflictAcknowledgment: () => ({ shouldShowRedDot: shouldShowConflictRedDot }) } } ) vi.mock( import('@/platform/customNodes/manager/composables/useManagerState'), () => { const managerState = { shouldShowExtensionsButton: computed(() => true) } return { useManagerState: vi.fn(() => { onTestFinished(() => { managerState.shouldShowExtensionsButton = computed(() => true) }) return managerState }) } } ) vi.mock(import('@/scripts/app')) vi.mock(import('@/platform/workspace/openCustomDeploymentDialog')) vi.mock(import('@/platform/customNodes/manager/composables/useManagerDialog')) vi.mock(import('@comfyorg/telemetry')) type WrapperOptions = { pinia?: Pinia stubs?: Record attachTo?: HTMLElement } function createWrapper({ pinia = getActivePinia()!, stubs = {}, attachTo }: WrapperOptions = {}) { Object.assign(useReleaseStore(pinia), { shouldShowRedDot: true }) const i18n = createI18n({ legacy: false, locale: 'en', messages: { en: { sideToolbar: { queueProgressOverlay: { viewJobHistory: 'View job history', expandCollapsedQueue: 'Expand collapsed queue', activeJobsShort: '{count} active | {count} active', clearQueueTooltip: 'Clear queue' } }, rightSidePanel: { togglePanel: 'Toggle properties panel' }, deployToComfyApi: { buttonLabel: 'Deploy to Comfy API' } } } }) const user = userEvent.setup() const renderOptions: Record = { global: { plugins: [pinia, i18n], stubs: { SubgraphBreadcrumb: true, QueueProgressOverlay: true, QueueInlineProgressSummary: true, QueueNotificationBannerHost: true, CurrentUserButton: true, LoginButton: true, ContextMenu: { name: 'ContextMenu', props: ['model'], template: '
' }, ...stubs } } } if (attachTo) { renderOptions.container = attachTo.appendChild( document.createElement('div') ) } const { container, unmount } = render(TopMenuSection, renderOptions) return { container, unmount, user } } function getLegacyCommandsContainer(container: Element): HTMLElement { const legacyContainer = container.querySelector( '[data-testid="legacy-topbar-container"]' ) if (!(legacyContainer instanceof HTMLElement)) { throw new Error('Expected legacy commands container to be present') } return legacyContainer } function createJob(id: string, status: JobStatus): JobListItem { return { id, status, create_time: 0, priority: 0 } } function createTask(id: string, status: JobStatus): TaskItemImpl { return new TaskItemImpl(createJob(id, status)) } function createComfyActionbarStub(actionbarTarget: HTMLElement) { return defineComponent({ name: 'ComfyActionbar', setup(_, { emit }) { onMounted(() => { emit('update:progressTarget', actionbarTarget) }) return () => h('div') } }) } describe('TopMenuSection', () => { beforeEach(() => { mockData.setShowConflictRedDot(false) }) describe('authentication state', () => { function createLegacyTabBarWrapper() { const pinia = getActivePinia()! const settingStore = useSettingStore(pinia) vi.mocked(settingStore.get).mockImplementation((key) => key === 'Comfy.UI.TabBarLayout' ? 'Legacy' : undefined ) return createWrapper({ pinia }) } describe('when user is logged in', () => { it('should display CurrentUserButton and not display LoginButton', () => { useCurrentUser().isLoggedIn = computed(() => true) const { container } = createLegacyTabBarWrapper() expect( container.querySelector('current-user-button-stub') ).not.toBeNull() expect(container.querySelector('login-button-stub')).toBeNull() }) }) describe('when user is not logged in', () => { it('should display LoginButton and not display CurrentUserButton', () => { const { container } = createLegacyTabBarWrapper() expect(container.querySelector('login-button-stub')).not.toBeNull() expect(container.querySelector('current-user-button-stub')).toBeNull() }) }) }) it('shows the active jobs label with the current count', async () => { createWrapper() const queueStore = useQueueStore() queueStore.pendingTasks = [createTask('pending-1', 'pending')] queueStore.runningTasks = [ createTask('running-1', 'in_progress'), createTask('running-2', 'in_progress') ] await nextTick() const queueButton = screen.getByTestId('queue-overlay-toggle') expect(queueButton.textContent).toContain('3 active') expect(screen.getByTestId('active-jobs-indicator')).toBeTruthy() }) it('hides the active jobs indicator when no jobs are active', () => { createWrapper() expect(screen.queryByTestId('active-jobs-indicator')).toBeNull() }) it('keeps action bars mounted while hiding the error overlay in node selection mode', () => { const pinia = getActivePinia()! useCanvasStore(pinia).isPickingNodes = true createWrapper({ pinia, stubs: { ErrorOverlay: { template: '
' } } }) expect(screen.getByTestId('top-menu-actionbars')).toHaveAttribute( 'aria-hidden', 'true' ) expect(screen.queryByTestId('error-overlay')).toBeNull() }) it('tracks right side panel opens', async () => { const { user } = createWrapper() await user.click( screen.getByRole('button', { name: 'Toggle properties panel' }) ) expect(useTelemetry()?.trackUiButtonClicked).toHaveBeenCalledWith({ button_id: 'right_side_panel_opened', element_group: 'top_menu' }) }) it('hides queue progress overlay when QPO V2 is enabled', async () => { const pinia = getActivePinia()! const settingStore = useSettingStore(pinia) vi.mocked(settingStore.get).mockImplementation((key) => key === 'Comfy.Queue.QPOV2' ? true : undefined ) const { container } = createWrapper({ pinia }) await nextTick() expect(screen.getByTestId('queue-overlay-toggle')).toBeTruthy() expect(container.querySelector('queue-progress-overlay-stub')).toBeNull() }) it('toggles the queue progress overlay when QPO V2 is disabled', async () => { const pinia = getActivePinia()! const settingStore = useSettingStore(pinia) vi.mocked(settingStore.get).mockImplementation((key) => key === 'Comfy.Queue.QPOV2' ? false : undefined ) const { user } = createWrapper({ pinia }) const commandStore = useCommandStore(pinia) await user.click(screen.getByTestId('queue-overlay-toggle')) expect(commandStore.execute).toHaveBeenCalledWith( 'Comfy.Queue.ToggleOverlay' ) }) it('opens the job history sidebar tab when QPO V2 is enabled', async () => { const pinia = getActivePinia()! const settingStore = useSettingStore(pinia) vi.mocked(settingStore.get).mockImplementation((key) => key === 'Comfy.Queue.QPOV2' ? true : undefined ) const { user } = createWrapper({ pinia }) const sidebarTabStore = useSidebarTabStore(pinia) await user.click(screen.getByTestId('queue-overlay-toggle')) expect(sidebarTabStore.activeSidebarTabId).toBe('job-history') }) it('toggles the job history sidebar tab when QPO V2 is enabled', async () => { const pinia = getActivePinia()! const settingStore = useSettingStore(pinia) vi.mocked(settingStore.get).mockImplementation((key) => key === 'Comfy.Queue.QPOV2' ? true : undefined ) const { user } = createWrapper({ pinia }) const sidebarTabStore = useSidebarTabStore(pinia) const toggleButton = screen.getByTestId('queue-overlay-toggle') await user.click(toggleButton) expect(sidebarTabStore.activeSidebarTabId).toBe('job-history') await user.click(toggleButton) expect(sidebarTabStore.activeSidebarTabId).toBe(null) }) describe('inline progress summary', () => { const configureSettings = ( pinia: Pinia, qpoV2Enabled: boolean, showRunProgressBar = true ) => { const settingStore = useSettingStore(pinia) vi.mocked(settingStore.get).mockImplementation((key) => { if (key === 'Comfy.Queue.QPOV2') return qpoV2Enabled if (key === 'Comfy.Queue.ShowRunProgressBar') return showRunProgressBar if (key === 'Comfy.UseNewMenu') return 'Top' return undefined }) } it('renders inline progress summary when QPO V2 is enabled', async () => { const pinia = getActivePinia()! configureSettings(pinia, true) const { container } = createWrapper({ pinia }) await nextTick() expect( container.querySelector('queue-inline-progress-summary-stub') ).not.toBeNull() }) it('does not render inline progress summary when QPO V2 is disabled', async () => { const pinia = getActivePinia()! configureSettings(pinia, false) const { container } = createWrapper({ pinia }) await nextTick() expect( container.querySelector('queue-inline-progress-summary-stub') ).toBeNull() }) it('does not render inline progress summary when run progress bar is disabled', async () => { const pinia = getActivePinia()! configureSettings(pinia, true, false) const { container } = createWrapper({ pinia }) await nextTick() expect( container.querySelector('queue-inline-progress-summary-stub') ).toBeNull() }) it('does not render inline progress summary while action bars are hidden', async () => { const pinia = getActivePinia()! configureSettings(pinia, true) useCanvasStore(pinia).isPickingNodes = true const { container } = createWrapper({ pinia }) await nextTick() expect( container.querySelector('queue-inline-progress-summary-stub') ).toBeNull() }) it('teleports inline progress summary when actionbar is floating', async () => { localStorage.setItem('Comfy.MenuPosition.Docked', 'false') const actionbarTarget = document.createElement('div') document.body.appendChild(actionbarTarget) const pinia = getActivePinia()! configureSettings(pinia, true) const executionStore = useExecutionStore(pinia) executionStore.activeJobId = 'job-1' const ComfyActionbarStub = createComfyActionbarStub(actionbarTarget) const { unmount } = createWrapper({ pinia, attachTo: document.body, stubs: { ComfyActionbar: ComfyActionbarStub, QueueInlineProgressSummary: false } }) try { await nextTick() expect(actionbarTarget.querySelector('[role="status"]')).not.toBeNull() } finally { unmount() actionbarTarget.remove() } }) }) describe(QueueNotificationBannerHost, () => { const configureSettings = (pinia: Pinia, qpoV2Enabled: boolean) => { const settingStore = useSettingStore(pinia) vi.mocked(settingStore.get).mockImplementation((key) => { if (key === 'Comfy.Queue.QPOV2') return qpoV2Enabled if (key === 'Comfy.Queue.ShowRunProgressBar') return true if (key === 'Comfy.UseNewMenu') return 'Top' return undefined }) } it('renders queue notification banners when QPO V2 is enabled', async () => { const pinia = getActivePinia()! configureSettings(pinia, true) const { container } = createWrapper({ pinia }) await nextTick() expect( container.querySelector('queue-notification-banner-host-stub') ).not.toBeNull() }) it.for([ { isActionBarsHidden: false, rendered: true }, { isActionBarsHidden: true, rendered: false } ])( 'renders the queue progress overlay: $rendered when action bars hidden is $isActionBarsHidden', async ({ isActionBarsHidden, rendered }) => { const pinia = getActivePinia()! configureSettings(pinia, false) useCanvasStore(pinia).isPickingNodes = isActionBarsHidden const { container } = createWrapper({ pinia }) await nextTick() expect( container.querySelector('queue-progress-overlay-stub') !== null ).toBe(rendered) } ) it.for([ { isActionBarsHidden: false, hidden: false }, { isActionBarsHidden: true, hidden: true } ])( 'keeps the queue notification banner host mounted and hidden=$hidden when action bars hidden is $isActionBarsHidden', async ({ isActionBarsHidden, hidden }) => { const pinia = getActivePinia()! configureSettings(pinia, false) useCanvasStore(pinia).isPickingNodes = isActionBarsHidden const { container } = createWrapper({ pinia }) await nextTick() const host = container.querySelector( 'queue-notification-banner-host-stub' ) if (!host) throw new Error('banner host is not mounted') expect(host.classList.contains('hidden')).toBe(hidden) } ) it('renders queue notification banners when QPO V2 is disabled', async () => { const pinia = getActivePinia()! configureSettings(pinia, false) const { container } = createWrapper({ pinia }) await nextTick() expect( container.querySelector('queue-notification-banner-host-stub') ).not.toBeNull() }) it('renders inline summary above banners when both are visible', async () => { const pinia = getActivePinia()! configureSettings(pinia, true) const { container } = createWrapper({ pinia }) await nextTick() const html = container.innerHTML const inlineSummaryIndex = html.indexOf( 'queue-inline-progress-summary-stub' ) const queueBannerIndex = html.indexOf( 'queue-notification-banner-host-stub' ) expect(inlineSummaryIndex).toBeGreaterThan(-1) expect(queueBannerIndex).toBeGreaterThan(-1) expect(inlineSummaryIndex).toBeLessThan(queueBannerIndex) }) it('does not teleport queue notification banners when actionbar is floating', async () => { localStorage.setItem('Comfy.MenuPosition.Docked', 'false') const actionbarTarget = document.createElement('div') document.body.appendChild(actionbarTarget) const pinia = getActivePinia()! configureSettings(pinia, true) const executionStore = useExecutionStore(pinia) executionStore.activeJobId = 'job-1' const ComfyActionbarStub = createComfyActionbarStub(actionbarTarget) const { container, unmount } = createWrapper({ pinia, attachTo: document.body, stubs: { ComfyActionbar: ComfyActionbarStub, QueueNotificationBannerHost: true } }) try { await nextTick() expect( actionbarTarget.querySelector('queue-notification-banner-host-stub') ).toBeNull() expect( container.querySelector('queue-notification-banner-host-stub') ).not.toBeNull() } finally { unmount() actionbarTarget.remove() } }) }) it('disables the clear queue context menu item when no queued jobs exist', () => { const { container } = createWrapper() const menuEl = container.querySelector('[data-testid="context-menu"]') const model = JSON.parse( menuEl?.getAttribute('data-model') ?? '[]' ) as MenuItem[] expect(model[0]?.label).toBe('Clear queue') expect(model[0]?.disabled).toBe(true) }) it('enables the clear queue context menu item when queued jobs exist', async () => { const { container } = createWrapper() const queueStore = useQueueStore() queueStore.pendingTasks = [createTask('pending-1', 'pending')] await nextTick() const menuEl = container.querySelector('[data-testid="context-menu"]') const model = JSON.parse( menuEl?.getAttribute('data-model') ?? '[]' ) as MenuItem[] expect(model[0]?.disabled).toBe(false) }) it('shows manager red dot only for manager conflicts', async () => { const { container } = createWrapper() // Release red dot is mocked as true globally for this test file. expect(container.querySelector('span.bg-destructive')).toBeNull() mockData.setShowConflictRedDot(true) await nextTick() expect(container.querySelector('span.bg-destructive')).not.toBeNull() }) it.for([ { listing: 'was served', state: reduceDeploymentPick( { phase: 'idle' }, loadedEvent({ builds_visible: true, items: [] }) ), pitchCount: 1, surveyCount: 0 }, { listing: 'was served without Build names', state: reduceDeploymentPick( { phase: 'idle' }, loadedEvent({ builds_visible: false, items: [] }) ), pitchCount: 1, surveyCount: 0 }, { listing: 'refused this account', state: { phase: 'hidden' }, pitchCount: 0, surveyCount: 1 } ] as const)( 'on Comfy Cloud, Extensions chooses between the custom deployment pitch and the survey when the deployments listing $listing', async ({ state, pitchCount, surveyCount }) => { distribution.isCloud = true onTestFinished(() => { distribution.isCloud = false }) vi.mocked(openDeployCustomNodesDialog).mockResolvedValue(true) useDeploymentPickStore().state = state const { user } = createWrapper() await user.click( screen.getByRole('button', { name: 'menu.manageExtensions' }) ) await waitFor(() => expect( vi.mocked(openDeployCustomNodesDialog).mock.calls.length + managerSurveyDialog.show.mock.calls.length ).toBe(1) ) expect(openDeployCustomNodesDialog).toHaveBeenCalledTimes(pitchCount) expect(managerSurveyDialog.show).toHaveBeenCalledTimes(surveyCount) } ) it('on Comfy Cloud, Extensions opens the survey when the deployments listing has not answered in time', async () => { distribution.isCloud = true vi.useFakeTimers() onTestFinished(() => { distribution.isCloud = false vi.useRealTimers() }) vi.spyOn(useDeploymentPickStore(), 'loadOnce').mockReturnValue( new Promise(() => {}) ) createWrapper() const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }) await user.click( screen.getByRole('button', { name: 'menu.manageExtensions' }) ) await vi.advanceTimersByTimeAsync(DEPLOYMENT_LISTING_EXTENSIONS_WAIT_MS) expect(managerSurveyDialog.show).toHaveBeenCalledOnce() expect(openDeployCustomNodesDialog).not.toHaveBeenCalled() }) it('keeps the floating actionbar container open for the extensions button', async () => { localStorage.setItem('Comfy.MenuPosition.Docked', 'false') const pinia = getActivePinia() assert.exists(pinia) const settingStore = useSettingStore(pinia) vi.mocked(settingStore.get).mockImplementation((key) => { if (key === 'Comfy.UseNewMenu') return 'Top' if (key === 'Comfy.UI.TabBarLayout') return 'Integrated' if (key === 'Comfy.RightSidePanel.IsOpen') return true return undefined }) const { container } = createWrapper({ pinia }) await nextTick() expect( screen.getByRole('button', { name: 'menu.manageExtensions' }) ).toBeInTheDocument() expect(container.querySelector('.actionbar-container')).not.toHaveClass( 'w-0' ) }) describe('Deploy to Comfy API button', () => { function enableDeployButton() { Object.assign(useFeatureFlags().flags, { deployToCloud: true }) } it.for([ { when: 'when the server allows it', deployToCloud: true, count: 1 }, { when: 'otherwise', deployToCloud: false, count: 0 } ])('renders $count deploy button $when', ({ deployToCloud, count }) => { Object.assign(useFeatureFlags().flags, { deployToCloud }) createWrapper({ stubs: { FreeTierQuota: true } }) expect( screen.queryAllByRole('button', { name: 'Deploy to Comfy API' }) ).toHaveLength(count) }) it('sits left of the panel toggle and opens the dialog for the installation', async () => { enableDeployButton() const { user } = createWrapper() const deploy = screen.getByRole('button', { name: 'Deploy to Comfy API' }) expect( deploy.compareDocumentPosition( screen.getByRole('button', { name: 'Toggle properties panel' }) ) & Node.DOCUMENT_POSITION_FOLLOWING ).toBeTruthy() await user.click(deploy) expect(openDeployToComfyApiDialog).toHaveBeenCalledExactlyOnceWith({ deploysInstallation: true }) }) it('tracks deploy button clicks', async () => { enableDeployButton() const { user } = createWrapper() await user.click( screen.getByRole('button', { name: 'Deploy to Comfy API' }) ) expect(useTelemetry()?.trackUiButtonClicked).toHaveBeenCalledWith({ button_id: 'run_bar_deploy_clicked', element_group: 'top_menu' }) }) it('keeps the floating actionbar container open for the deploy button', async () => { localStorage.setItem('Comfy.MenuPosition.Docked', 'false') useManagerState().shouldShowExtensionsButton = computed(() => false) enableDeployButton() const pinia = getActivePinia() assert.exists(pinia) vi.mocked(useSettingStore(pinia).get).mockImplementation((key) => { if (key === 'Comfy.UseNewMenu') return 'Top' if (key === 'Comfy.UI.TabBarLayout') return 'Integrated' if (key === 'Comfy.RightSidePanel.IsOpen') return true return undefined }) const { container } = createWrapper({ pinia }) await nextTick() expect(container.querySelector('.actionbar-container')).not.toHaveClass( 'w-0' ) }) }) it('coalesces legacy topbar mutation scans to one check per frame', async () => { localStorage.setItem('Comfy.MenuPosition.Docked', 'false') useManagerState().shouldShowExtensionsButton = computed(() => false) const rafCallbacks: FrameRequestCallback[] = [] vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => { rafCallbacks.push(cb) return rafCallbacks.length }) vi.stubGlobal('cancelAnimationFrame', vi.fn()) const pinia = getActivePinia()! const settingStore = useSettingStore(pinia) vi.mocked(settingStore.get).mockImplementation((key) => { if (key === 'Comfy.UseNewMenu') return 'Top' if (key === 'Comfy.UI.TabBarLayout') return 'Integrated' if (key === 'Comfy.RightSidePanel.IsOpen') return true return undefined }) const { container, unmount } = createWrapper({ pinia, attachTo: document.body }) try { await nextTick() const actionbarContainer = container.querySelector('.actionbar-container') expect(actionbarContainer).not.toBeNull() expect(actionbarContainer!.classList).toContain('w-0') const legacyContainer = getLegacyCommandsContainer(container) const querySpy = vi.spyOn(legacyContainer, 'querySelector') if (rafCallbacks.length > 0) { const initialCallbacks = [...rafCallbacks] rafCallbacks.length = 0 initialCallbacks.forEach((callback) => callback(0)) await nextTick() } querySpy.mockClear() querySpy.mockReturnValue(document.createElement('div')) for (let index = 0; index < 3; index++) { const outer = document.createElement('div') const inner = document.createElement('div') inner.textContent = `legacy-${index}` outer.appendChild(inner) legacyContainer.appendChild(outer) } await vi.waitFor(() => { expect(rafCallbacks.length).toBeGreaterThan(0) }) expect(querySpy).not.toHaveBeenCalled() const callbacks = [...rafCallbacks] rafCallbacks.length = 0 callbacks.forEach((callback) => callback(0)) await nextTick() expect(querySpy).toHaveBeenCalledTimes(1) expect(actionbarContainer!.classList).not.toContain('w-0') } finally { unmount() vi.unstubAllGlobals() } }) })