diff --git a/src/locales/en/main.json b/src/locales/en/main.json index c7d30dd342b..481acb07322 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -2232,6 +2232,7 @@ "failedToExportModel": "Failed to export model as {format}", "exportSuccess": "Successfully exported model as {format}", "fileLoadError": "Unable to find workflow in {fileName}", + "a1111CoreNodesUnavailable": "Could not load the workflow because this ComfyUI installation is missing core nodes. Check that the backend started correctly.", "dropFileError": "Unable to process dropped item: {error}", "missingMediaVerificationFailed": "Failed to verify missing media. Some inputs may not be shown in the Errors tab.", "missingModelVerificationFailed": "Failed to verify missing models. Some models may not be shown in the Errors tab.", diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index 797ea18a7a0..dc86658b550 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -35,6 +35,10 @@ import { createTestSubgraphNode } from '@/lib/litegraph/src/subgraph/__fixtures__/subgraphHelpers' import { useWidgetValueStore } from '@/stores/widgetValueStore' +import type { importA1111 } from './pnginfo' +import type { useWorkflowService } from '@/platform/workflow/core/services/workflowService' + +type WorkflowService = ReturnType const { mockApiKeyAuthStore, @@ -44,7 +48,9 @@ const { mockExtensionService, mockNodeOutputStore, mockWorkspaceWorkflow, - mockRefreshMissingModelPipeline + mockRefreshMissingModelPipeline, + mockImportA1111, + mockWorkflowService } = vi.hoisted(() => ({ mockApiKeyAuthStore: { getApiKey: vi.fn() @@ -70,7 +76,13 @@ const { mockWorkspaceWorkflow: { activeWorkflow: null as ComfyWorkflow | null }, - mockRefreshMissingModelPipeline: vi.fn() + mockRefreshMissingModelPipeline: vi.fn(), + mockImportA1111: vi.fn(), + mockWorkflowService: { + beforeLoadNewGraph: vi.fn(), + afterLoadNewGraph: vi.fn(), + showPendingWarnings: vi.fn() + } })) vi.mock('@/utils/litegraphUtil', () => ({ @@ -107,6 +119,14 @@ vi.mock('@/scripts/metadata/parser', () => ({ getWorkflowDataFromFile: vi.fn() })) +vi.mock('./pnginfo', () => ({ + importA1111: mockImportA1111 +})) + +vi.mock('@/platform/workflow/core/services/workflowService', () => ({ + useWorkflowService: vi.fn(() => mockWorkflowService) +})) + vi.mock('@/extensions/core/load3d/Load3dUtils', () => ({ default: { uploadFile: vi.fn() @@ -156,7 +176,8 @@ function createMockCanvas(): Partial { return { graph: mockGraph as LGraph, draw: vi.fn(), - selectItems: vi.fn() + selectItems: vi.fn(), + setGraph: vi.fn() } } @@ -183,7 +204,7 @@ describe('ComfyApp', () => { beforeEach(() => { setActivePinia(createTestingPinia({ stubActions: false })) - vi.clearAllMocks() + vi.resetAllMocks() app = new ComfyApp() mockCanvas = createMockCanvas() as LGraphCanvas app.canvas = mockCanvas as LGraphCanvas @@ -192,6 +213,8 @@ describe('ComfyApp', () => { mockAuthStore.getAuthToken.mockResolvedValue(undefined) mockExtensionService.invokeExtensions.mockReturnValue([]) mockExtensionService.invokeExtensionsAsync.mockResolvedValue(undefined) + mockImportA1111.mockResolvedValue('imported') + mockWorkflowService.afterLoadNewGraph.mockResolvedValue() mockSettingStore.get.mockImplementation((key: string) => key === 'Comfy.RightSidePanel.ShowErrorsTab' ? true : undefined ) @@ -908,6 +931,103 @@ describe('ComfyApp', () => { mockNode ) }) + + it.each([ + ['an invalid structure', '[]'], + ['invalid JSON', '{invalid'] + ])('shows one error for %s', async (_case, workflow) => { + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + vi.mocked(getWorkflowDataFromFile).mockResolvedValue({ workflow }) + + await app.handleFile(createTestFile('broken.json', 'application/json')) + + expect(mockToastStore.addAlert).toHaveBeenCalledTimes(1) + expect(mockToastStore.addAlert).toHaveBeenCalledWith( + 'Unable to find workflow in broken.json' + ) + consoleError.mockRestore() + }) + + it('preserves the current graph when A1111 core nodes are unavailable', async () => { + const graph = new LGraph() + const parameters = 'positive\nNegative prompt: negative\nSteps: 20' + Reflect.set(app, 'rootGraphInternal', graph) + vi.mocked(getWorkflowDataFromFile).mockResolvedValue({ parameters }) + mockImportA1111.mockResolvedValue('core-nodes-unavailable') + + await app.handleFile(createTestFile('a1111.png', 'image/png')) + + expect(mockImportA1111).toHaveBeenCalledWith( + graph, + parameters, + expect.any(Function) + ) + expect(mockCanvas.setGraph).not.toHaveBeenCalled() + expect(mockWorkflowService.beforeLoadNewGraph).not.toHaveBeenCalled() + expect(mockWorkflowService.afterLoadNewGraph).not.toHaveBeenCalled() + expect(mockToastStore.addAlert).toHaveBeenCalledOnce() + expect(mockToastStore.addAlert).toHaveBeenCalledWith( + 'Could not load the workflow because this ComfyUI installation is missing core nodes. Check that the backend started correctly.' + ) + }) + + it('shows one file-load error when parameters are not A1111-shaped', async () => { + const graph = new LGraph() + const parameters = 'positive\nSteps: 20' + Reflect.set(app, 'rootGraphInternal', graph) + vi.mocked(getWorkflowDataFromFile).mockResolvedValue({ parameters }) + mockImportA1111.mockResolvedValue('not-a1111') + + await app.handleFile(createTestFile('parameters.png', 'image/png')) + + expect(mockToastStore.addAlert).toHaveBeenCalledOnce() + expect(mockToastStore.addAlert).toHaveBeenCalledWith( + 'Unable to find workflow in parameters.png' + ) + expect(mockWorkflowService.beforeLoadNewGraph).not.toHaveBeenCalled() + expect(mockWorkflowService.afterLoadNewGraph).not.toHaveBeenCalled() + }) + + it('awaits persistence and orders its clear callback before setGraph', async () => { + const graph = new LGraph() + const parameters = 'positive\nNegative prompt: negative\nSteps: 20' + Reflect.set(app, 'rootGraphInternal', graph) + vi.mocked(getWorkflowDataFromFile).mockResolvedValue({ parameters }) + mockImportA1111.mockImplementation( + async (_graph, _parameters, beforeGraphClear) => { + beforeGraphClear?.() + return 'imported' + } + ) + let resolveAfterLoad: (() => void) | undefined + const afterLoad = new Promise((resolve) => { + resolveAfterLoad = resolve + }) + mockWorkflowService.afterLoadNewGraph.mockReturnValue(afterLoad) + + let settled = false + const handleFile = app + .handleFile(createTestFile('a1111.png', 'image/png')) + .then(() => { + settled = true + }) + await vi.waitFor(() => + expect(mockWorkflowService.afterLoadNewGraph).toHaveBeenCalled() + ) + + expect(mockCanvas.setGraph).toHaveBeenCalledWith(graph) + expect(mockWorkflowService.beforeLoadNewGraph).toHaveBeenCalledOnce() + expect( + mockWorkflowService.beforeLoadNewGraph.mock.invocationCallOrder[0] + ).toBeLessThan(vi.mocked(mockCanvas.setGraph).mock.invocationCallOrder[0]) + expect(settled).toBe(false) + + resolveAfterLoad?.() + await handleFile + expect(settled).toBe(true) + }) }) describe('drop handler', () => { diff --git a/src/scripts/app.ts b/src/scripts/app.ts index e0429038ff5..6f0b91d2c0c 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -1854,11 +1854,9 @@ export class ComfyApp { console.error( 'Invalid workflow structure, trying parameters fallback' ) - this.showErrorOnFileLoad(file) } } catch (err) { console.error('Failed to parse workflow:', err) - this.showErrorOnFileLoad(file) // Fall through to check parameters as fallback } } @@ -1881,9 +1879,19 @@ export class ComfyApp { // Use parameters strictly as the final fallback if (parameters && typeof parameters === 'string') { - useWorkflowService().beforeLoadNewGraph() - importA1111(this.rootGraph, parameters) - useWorkflowService().afterLoadNewGraph( + const outcome = await importA1111(this.rootGraph, parameters, () => { + useWorkflowService().beforeLoadNewGraph() + this.canvas.setGraph(this.rootGraph) + }) + if (outcome === 'core-nodes-unavailable') { + useToastStore().addAlert(t('toastMessages.a1111CoreNodesUnavailable')) + return + } + if (outcome === 'not-a1111') { + this.showErrorOnFileLoad(file) + return + } + await useWorkflowService().afterLoadNewGraph( fileName, this.rootGraph.serialize() as unknown as ComfyWorkflowJSON ) diff --git a/src/scripts/pnginfo.test.ts b/src/scripts/pnginfo.test.ts index c10aaa4b1ab..ae416be03a9 100644 --- a/src/scripts/pnginfo.test.ts +++ b/src/scripts/pnginfo.test.ts @@ -2,6 +2,9 @@ import fs from 'fs' import path from 'path' import { afterEach, describe, expect, it, vi } from 'vitest' +import { LGraph, LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph' + +import { api } from './api' import { getFromAvifFile } from './metadata/avif' import { getFromFlacFile } from './metadata/flac' import { getFromPngFile } from './metadata/png' @@ -10,9 +13,16 @@ import { getFlacMetadata, getLatentMetadata, getPngMetadata, - getWebpMetadata + getWebpMetadata, + importA1111 } from './pnginfo' +vi.mock('./api', () => ({ + api: { + getEmbeddings: vi.fn() + } +})) + vi.mock('./metadata/png', () => ({ getFromPngFile: vi.fn() })) @@ -234,3 +244,60 @@ describe('format-specific metadata wrappers', () => { expect(result).toEqual({ workflow: '{"avif":1}' }) }) }) + +describe('importA1111', () => { + const parameters = + 'positive\nNegative prompt: negative\nSteps: 20, Sampler: Euler, CFG scale: 7, Seed: 1, Size: 512x512, Model: model.safetensors' + + it.each([ + ['has no steps', 'positive'], + ['has no options', 'positive\nNegative prompt: negative\nSteps:'], + ['has no negative prompt', 'positive\nSteps: 20'] + ])('returns not-a1111 when parameters %s', async (_case, input) => { + const graph = new LGraph() + const beforeGraphClear = vi.fn() + vi.mocked(api.getEmbeddings).mockResolvedValue([]) + + const imported = await importA1111(graph, input, beforeGraphClear) + + expect(imported).toBe('not-a1111') + expect(beforeGraphClear).not.toHaveBeenCalled() + }) + + it('returns core-nodes-unavailable without clearing the graph', async () => { + const graph = new LGraph() + const clear = vi.spyOn(graph, 'clear') + const beforeGraphClear = vi.fn() + vi.mocked(api.getEmbeddings).mockResolvedValue([]) + vi.spyOn(LiteGraph, 'createNode').mockReturnValue(null) + + const imported = await importA1111(graph, parameters, beforeGraphClear) + + expect(imported).toBe('core-nodes-unavailable') + expect(beforeGraphClear).not.toHaveBeenCalled() + expect(clear).not.toHaveBeenCalled() + }) + + it('runs the lifecycle callback immediately before clearing the graph', async () => { + const graph = new LGraph() + const clear = vi.spyOn(graph, 'clear') + const beforeGraphClear = vi.fn() + vi.mocked(api.getEmbeddings).mockResolvedValue([]) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.spyOn(graph, 'arrange').mockImplementation(() => {}) + vi.spyOn(LiteGraph, 'createNode').mockImplementation((type) => { + const node = new LGraphNode(type) + node.type = type + vi.spyOn(node, 'connect').mockReturnValue(null) + return node + }) + + const imported = await importA1111(graph, parameters, beforeGraphClear) + + expect(imported).toBe('imported') + expect(beforeGraphClear).toHaveBeenCalledOnce() + expect(beforeGraphClear.mock.invocationCallOrder[0]).toBeLessThan( + clear.mock.invocationCallOrder[0] + ) + }) +}) diff --git a/src/scripts/pnginfo.ts b/src/scripts/pnginfo.ts index c27ee505282..ddebb685034 100644 --- a/src/scripts/pnginfo.ts +++ b/src/scripts/pnginfo.ts @@ -180,10 +180,16 @@ interface LoraEntry { weight: number } +export type A1111ImportOutcome = + | 'imported' + | 'not-a1111' + | 'core-nodes-unavailable' + export async function importA1111( graph: LGraph, - parameters: string -): Promise { + parameters: string, + beforeGraphClear?: () => void +): Promise { const p = parameters.lastIndexOf('\nSteps:') if (p > -1) { const embeddings = await api.getEmbeddings() @@ -193,7 +199,7 @@ export async function importA1111( .match( new RegExp('\\s*([^:]+:\\s*([^"\\{].*?|".*?"|\\{.*?\\}))\\s*(,|$)', 'g') ) - if (!matchResult) return + if (!matchResult) return 'not-a1111' const opts: Record = matchResult.reduce( (acc: Record, n: string) => { @@ -231,7 +237,7 @@ export async function importA1111( !saveNode ) { console.error('Failed to create required nodes for A1111 import') - return + return 'core-nodes-unavailable' } let hrSamplerNode: LGraphNode | null = null @@ -331,6 +337,7 @@ export async function importA1111( return v } + beforeGraphClear?.() graph.clear() graph.add(ckptNode) graph.add(clipSkipNode) @@ -550,7 +557,11 @@ export async function importA1111( delete opts[opt] } - console.warn('Unhandled parameters:', opts) + if (Object.keys(opts).length) { + console.warn('Unhandled parameters:', opts) + } + return 'imported' } } + return 'not-a1111' } diff --git a/src/scripts/ui.test.ts b/src/scripts/ui.test.ts new file mode 100644 index 00000000000..abd27ae616b --- /dev/null +++ b/src/scripts/ui.test.ts @@ -0,0 +1,86 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { ComfyUI } from './ui' + +const { mockApp } = vi.hoisted(() => ({ + mockApp: { + handleFile: vi.fn<(file: File, source: string) => Promise>(), + showErrorOnFileLoad: vi.fn(), + queuePrompt: vi.fn(), + loadGraphData: vi.fn(), + refreshComboInNodes: vi.fn(), + openClipspace: vi.fn(), + clean: vi.fn(), + lastExecutionError: null + } +})) + +vi.mock('./app', () => ({ + ComfyApp: class {}, + app: mockApp +})) + +vi.mock('./api', () => ({ + api: { + addEventListener: vi.fn() + } +})) + +vi.mock('./ui/dialog', () => ({ + ComfyDialog: class {} +})) + +vi.mock('./ui/settings', () => ({ + ComfySettingsDialog: class {} +})) + +vi.mock('./ui/toggleSwitch', () => ({ + toggleSwitch: vi.fn(() => document.createElement('div')) +})) + +describe('ComfyUI file input', () => { + beforeEach(() => { + vi.stubGlobal( + 'ResizeObserver', + class { + observe = vi.fn() + disconnect = vi.fn() + unobserve = vi.fn() + } + ) + mockApp.handleFile.mockReset() + mockApp.showErrorOnFileLoad.mockReset() + }) + + afterEach(() => { + document.body.replaceChildren() + vi.unstubAllGlobals() + }) + + it('reports rejected imports and resets the selected file', async () => { + const file = new File([''], 'a1111.png', { type: 'image/png' }) + const error = new Error('import failed') + mockApp.handleFile.mockRejectedValue(error) + new ComfyUI(mockApp) + const fileInput = document.getElementById( + 'comfy-file-input' + ) as HTMLInputElement + Object.defineProperties(fileInput, { + files: { value: [file], configurable: true }, + value: { value: 'a1111.png', writable: true, configurable: true } + }) + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + + fileInput.dispatchEvent(new Event('change')) + + await vi.waitFor(() => + expect(mockApp.showErrorOnFileLoad).toHaveBeenCalledWith(file) + ) + expect(mockApp.handleFile).toHaveBeenCalledWith(file, 'file_button') + expect(consoleError).toHaveBeenCalledWith('Failed to load file:', error) + expect(consoleError.mock.invocationCallOrder[0]).toBeLessThan( + mockApp.showErrorOnFileLoad.mock.invocationCallOrder[0] + ) + expect(fileInput.value).toBe('') + }) +}) diff --git a/src/scripts/ui.ts b/src/scripts/ui.ts index e8b8d122a00..b8ff76ed60d 100644 --- a/src/scripts/ui.ts +++ b/src/scripts/ui.ts @@ -407,8 +407,14 @@ export class ComfyUI { onchange: async () => { const file = fileInput.files?.[0] if (file) { - await app.handleFile(file, 'file_button') - fileInput.value = '' + try { + await app.handleFile(file, 'file_button') + } catch (error) { + console.error('Failed to load file:', error) + app.showErrorOnFileLoad(file) + } finally { + fileInput.value = '' + } } } })