Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/locales/en/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
128 changes: 124 additions & 4 deletions src/scripts/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof useWorkflowService>

const {
mockApiKeyAuthStore,
Expand All @@ -44,7 +48,9 @@ const {
mockExtensionService,
mockNodeOutputStore,
mockWorkspaceWorkflow,
mockRefreshMissingModelPipeline
mockRefreshMissingModelPipeline,
mockImportA1111,
mockWorkflowService
} = vi.hoisted(() => ({
mockApiKeyAuthStore: {
getApiKey: vi.fn()
Expand All @@ -70,7 +76,13 @@ const {
mockWorkspaceWorkflow: {
activeWorkflow: null as ComfyWorkflow | null
},
mockRefreshMissingModelPipeline: vi.fn()
mockRefreshMissingModelPipeline: vi.fn(),
mockImportA1111: vi.fn<typeof importA1111>(),
mockWorkflowService: {
beforeLoadNewGraph: vi.fn<WorkflowService['beforeLoadNewGraph']>(),
afterLoadNewGraph: vi.fn<WorkflowService['afterLoadNewGraph']>(),
showPendingWarnings: vi.fn<WorkflowService['showPendingWarnings']>()
}
}))

vi.mock('@/utils/litegraphUtil', () => ({
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -156,7 +176,8 @@ function createMockCanvas(): Partial<LGraphCanvas> {
return {
graph: mockGraph as LGraph,
draw: vi.fn(),
selectItems: vi.fn()
selectItems: vi.fn(),
setGraph: vi.fn()
}
}

Expand All @@ -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
Expand All @@ -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
)
Expand Down Expand Up @@ -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<void>((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', () => {
Expand Down
18 changes: 13 additions & 5 deletions src/scripts/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Expand All @@ -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
)
Expand Down
69 changes: 68 additions & 1 deletion src/scripts/pnginfo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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()
}))
Expand Down Expand Up @@ -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]
)
})
})
21 changes: 16 additions & 5 deletions src/scripts/pnginfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
parameters: string,
beforeGraphClear?: () => void
): Promise<A1111ImportOutcome> {
const p = parameters.lastIndexOf('\nSteps:')
if (p > -1) {
const embeddings = await api.getEmbeddings()
Expand All @@ -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<string, string> = matchResult.reduce(
(acc: Record<string, string>, n: string) => {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -331,6 +337,7 @@ export async function importA1111(
return v
}

beforeGraphClear?.()
graph.clear()
graph.add(ckptNode)
graph.add(clipSkipNode)
Expand Down Expand Up @@ -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'
}
Loading
Loading