From 39340762e1821ed8481637c933aa047f6e442a85 Mon Sep 17 00:00:00 2001 From: jaeone lee <89377375+jaeone94@users.noreply.github.com> Date: Wed, 5 Aug 2026 11:35:37 +0900 Subject: [PATCH] fix(workflow): repair the A1111 import lifecycle and report broken installs accurately (#14556) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Splits out of #14251. Five lifecycle fixes on the A1111 image-import path. 30 production lines. ## What Dropping an A1111-generated PNG parses its `parameters` string and builds a ComfyUI graph from it. The path had four defects that only show up when something goes wrong, plus one that shows up always: 1. **`afterLoadNewGraph` was not awaited.** It suspends before the active workflow is reassigned, so `rootGraph.serialize()` on the next line captured the *outgoing* graph — the new tab was born dirty against a stale baseline. 2. **A rejection escaped an async DOM handler.** `importA1111` awaits `api.getEmbeddings()`, which does not check `resp.ok`. On a 500 with an HTML body it throws, `fileInput.value = ''` never runs, the input still holds the file, re-selecting it fires no `change` event, and Open silently does nothing on every retry. Now: `try`/`catch` with a toast, `finally` resets the input. 3. **Two identical alerts for one file.** The invalid-structure `else` and the parse `catch` each called `showErrorOnFileLoad`, then fell through to the final call at the end of `handleFile`. Those two are the `else` and `catch` of one `try`, so the maximum is two alerts, not three. 4. **`beforeLoadNewGraph()` ran before an import that might bail.** It calls `domWidgetStore.clear()`, and nothing re-registers on a bail path — a workflow with a multiline prompt on screen lost its DOM widget overlays when the user dropped a PNG that did not parse. It now runs immediately before the mutation, and the A1111 path gets the subgraph guard `clean()` already had. 5. **No message at all when required node types are unavailable, and silent corruption of the open workflow.** `importA1111` logged to the console and returned `void`. Because the call was unawaited, `afterLoadNewGraph` then registered the user's *unchanged* graph under the dropped file's name, after `beforeLoadNewGraph` had already cleared `domWidgetStore`. See below. ## The message The seven types this importer needs — `CheckpointLoaderSimple`, `CLIPSetLastLayer`, `CLIPTextEncode`, `KSampler`, `EmptyLatentImage`, `VAEDecode`, `SaveImage` — are all **core nodes**, as are `LoraLoader` and the hires chain. Their absence does not mean a node pack is missing. It means the backend did not load, or the install is broken. So this path deliberately writes nothing to the missing-node panel: no card, no entry, no placeholder. A type that was never added to the graph does not belong in a list of nodes missing *from the graph*, and naming the individual types would read as "install this pack" and send people looking for something that does not exist. ``` "Could not load the workflow because this ComfyUI installation is missing core nodes. Check that the backend started correctly." ``` `importA1111` returns `Promise<'imported' | 'not-a1111' | 'core-nodes-unavailable'>` — three string literals, replacing `Promise`. The boolean could not distinguish "bailed and already told the user" from "bailed silently", which is how an ordinary A1111 PNG could vanish with no feedback at all: A1111 omits the `Negative prompt:` line entirely when the negative prompt is empty. The `core-nodes-unavailable` return happens **before** the graph is touched, so a failed import leaves the open workflow intact. `pnginfo.test.ts` asserts that directly. ## What this deliberately does not do `pnginfo.ts` is **+8 −4**, with zero re-indentation (`git diff` and `git diff -w` report the same line count). The nesting in that file is not pretty and it is not this PR's business. An earlier revision restructured it; that diff was 759 lines, ~72% of it re-indentation, and none of it fixed a bug. If it deserves a refactor it deserves a PR where a reviewer sees only that. ## Verification 6 unit tests across `app.test.ts`, `pnginfo.test.ts` and `ui.test.ts`, each mutation-proved. typecheck, lint, format, knip clean. Full unit suite: only pre-existing timeout flakes, confirmed by re-running the same files at the merge base and getting byte-identical results. ## Related - Follow-up to #14251 (closed) - Independent of #14555 and of the narrow submission fix — no ordering constraint --- src/locales/en/main.json | 1 + src/scripts/app.test.ts | 128 ++++++++++++++++++++++++++++++++++-- src/scripts/app.ts | 18 +++-- src/scripts/pnginfo.test.ts | 69 ++++++++++++++++++- src/scripts/pnginfo.ts | 21 ++++-- src/scripts/ui.test.ts | 86 ++++++++++++++++++++++++ src/scripts/ui.ts | 10 ++- 7 files changed, 316 insertions(+), 17 deletions(-) create mode 100644 src/scripts/ui.test.ts diff --git a/src/locales/en/main.json b/src/locales/en/main.json index ae8452ddf3b..aeecc41a5a8 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -2274,6 +2274,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 e78450bfe69..b870a45bb88 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -39,6 +39,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, @@ -48,7 +52,9 @@ const { mockExtensionService, mockNodeOutputStore, mockWorkspaceWorkflow, - mockRefreshMissingModelPipeline + mockRefreshMissingModelPipeline, + mockImportA1111, + mockWorkflowService } = vi.hoisted(() => ({ mockApiKeyAuthStore: { getApiKey: vi.fn() @@ -74,7 +80,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', () => ({ @@ -111,6 +123,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() @@ -160,7 +180,8 @@ function createMockCanvas(): Partial { return { graph: mockGraph as LGraph, draw: vi.fn(), - selectItems: vi.fn() + selectItems: vi.fn(), + setGraph: vi.fn() } } @@ -187,7 +208,7 @@ describe('ComfyApp', () => { beforeEach(() => { setActivePinia(createTestingPinia({ stubActions: false })) - vi.clearAllMocks() + vi.resetAllMocks() app = new ComfyApp() mockCanvas = createMockCanvas() as LGraphCanvas app.canvas = mockCanvas as LGraphCanvas @@ -196,6 +217,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 ) @@ -1202,6 +1225,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 00b3bbe8ccf..a27a05a022f 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -1961,11 +1961,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 } } @@ -1988,9 +1986,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 df094a2c8c1..441e74079ed 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 = '' + } } } })