comfy-ts 2.18.0 → 2.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "comfy-ts",
3
- "version": "2.18.0",
3
+ "version": "2.18.1",
4
4
  "description": "The complete TypeScript toolkit for ComfyUI and generative AI. Fully type-safe SDK with autocomplete on every node, companion CLI, TUI, agentic docs, and 50+ examples. Design, run and deploy creative pipelines for image, video, audio, 3d and text on any ComfyUI, local, cloud or hosted.",
5
5
  "keywords": [
6
6
  "comfyui",
@@ -163,42 +163,12 @@ export class ComfyHost<ID extends string = string> {
163
163
  this.schema = new ComfySchema({ embeddings: [], spec: {} })
164
164
  }
165
165
 
166
- /** helper to check if your host have whatever it needs to run your workflow */
167
- matchRequirements = (requirements: Requirements[]): boolean => {
168
- const repo = comfyts.registry
169
- for (const req of requirements) {
170
- if (req.optional) continue
171
- if (req.type === 'customNodesByNodeKey') {
172
- const plugins: ComfyManagerPluginInfo[] = repo.plugins_byNodeKey.get(req.nodeName) ?? []
173
- if (!plugins.find((i) => this.manager.isPluginInstalled(i.title))) {
174
- // console.log(`[❌ A] ${JSON.stringify(req)} NOT MATCHED`)
175
- return false
176
- }
177
- } else if (req.type === 'customNodesByTitle') {
178
- const plugin: ComfyManagerPluginInfo | undefined = repo.plugins_byTitle.get(req.title)
179
- if (plugin == null) continue
180
- if (!this.manager.isPluginInstalled(plugin.title)) {
181
- // console.log(`[❌ B] ${JSON.stringify(req)} NOT MATCHED`)
182
- return false
183
- }
184
- } else if (req.type === 'customNodesByURI') {
185
- const plugin: ComfyManagerPluginInfo | undefined = repo.plugins_byFile.get(req.uri)
186
- if (plugin == null) continue
187
- if (!this.manager.isPluginInstalled(plugin.title)) {
188
- // console.log(`[❌ C] ${JSON.stringify(req)} NOT MATCHED`)
189
- return false
190
- }
191
- } else if (req.type === 'modelInManager') {
192
- if (!this.manager.isModelInstalled(req.modelName)) {
193
- // console.log(`[❌ D] ${JSON.stringify(req)} NOT MATCHED`)
194
- return false
195
- }
196
- } else {
197
- // exhaust(req.type)
198
- }
199
- }
200
- return true
201
- }
166
+ /** false only when a requirement is known missing; an undecided one passes with a warning (manager.matchRequirements) */
167
+ matchRequirements = (requirements: Requirements[]): boolean => this.manager.matchRequirements(requirements)
168
+
169
+ /** `missing` (known not installed, the only ones to queue for install) and `undecided` (the lists cannot say) */
170
+ checkRequirements = (requirements: Requirements[]): { missing: Requirements[]; undecided: Requirements[] } =>
171
+ this.manager.checkRequirements(requirements)
202
172
 
203
173
  // ----- Rotating srever logs -----
204
174
 
@@ -34,7 +34,7 @@ import type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPlugi
34
34
  import type { Maybe } from 'src/types/index.ts'
35
35
  import { logError, logSuccess } from 'src/utils/log.ts'
36
36
  import { softValidate } from 'src/utils/softValidate.ts'
37
- import type { PluginInstallStatus } from 'src/host/Requirements.ts'
37
+ import type { PluginInstallStatus, Requirements } from 'src/host/Requirements.ts'
38
38
 
39
39
  /**
40
40
  * the three ComfyUI-Manager servers in the field (agent/architecture.md, Manager HTTP client):
@@ -44,9 +44,17 @@ import type { PluginInstallStatus } from 'src/host/Requirements.ts'
44
44
  export type ManagerGeneration = 'v3' | 'v4-legacy-ui' | 'v4'
45
45
  export type ManagerApi = { generation: ManagerGeneration; version: string }
46
46
 
47
- /** install waits poll the queue; tests pass milliseconds */
48
- export type ManagerTiming = { pollMs: number; installTimeoutMs: number }
49
- export const MANAGER_TIMING: ManagerTiming = { pollMs: 1000, installTimeoutMs: 60 * 60_000 }
47
+ /** install waits poll the queue; `pollGraceMs`: how long the poll survives a host that does not answer */
48
+ export type ManagerTiming = { pollMs: number; installTimeoutMs: number; pollGraceMs: number }
49
+ export const MANAGER_TIMING: ManagerTiming = { pollMs: 1000, installTimeoutMs: 60 * 60_000, pollGraceMs: 120_000 }
50
+
51
+ /** `unknown`: we lost sight of the task, the Manager may still be installing (agent/architecture.md) */
52
+ export type InstallOutcome = 'installed' | 'failed' | 'unknown'
53
+
54
+ /** an install the host refused or reported failed: ends the wait at once */
55
+ class InstallFailed extends Error {}
56
+ /** we lost sight of the task: the outcome is not known */
57
+ class OutcomeUnknown extends Error {}
50
58
 
51
59
  type ManagerRoute =
52
60
  | '/manager/version'
@@ -81,9 +89,10 @@ const NOT_SERVED: Record<ManagerGeneration, ManagerRoute[]> = {
81
89
  type ManagerStrategy = {
82
90
  fetchPlugins: (mode: ComfyManagerAPIFetchPolicy, skipUpdate: boolean) => Promise<ComfyManagerAPIPluginList>
83
91
  fetchModels: () => Promise<ComfyManagerAPIModelList>
84
- enqueuePlugin: (plugin: ComfyManagerPluginInfo, uiId: string) => Promise<void>
92
+ /** resolves with the id the host installs by, when it is not the pack's own row */
93
+ enqueuePlugin: (plugin: ComfyManagerPluginInfo, uiId: string) => Promise<string | undefined>
85
94
  /** wait until the queued task ran: resolves when it succeeded, throws with why when not */
86
- settle: (what: string, uiId: string, landed: () => Promise<boolean>) => Promise<void>
95
+ settle: (what: string, uiId: string, landed: () => Promise<boolean | null>, sentId?: string) => Promise<void>
87
96
  }
88
97
 
89
98
  const QueueStatus_ark = type({
@@ -201,7 +210,7 @@ export class ComfyManager {
201
210
  fetchPlugins: () => this.installedPluginView(api),
202
211
  fetchModels: () => this.installedModelView(),
203
212
  enqueuePlugin: (plugin, uiId) => this.enqueuePluginTask(api, plugin, uiId),
204
- settle: (what, uiId) => this.settleByHistory(api, what, uiId),
213
+ settle: (what, uiId, landed, sentId) => this.settleByHistory(api, what, uiId, landed, sentId),
205
214
  }
206
215
  }
207
216
  }
@@ -304,14 +313,18 @@ export class ComfyManager {
304
313
  return this.getJSON<unknown>('/internal/logs')
305
314
  }
306
315
 
316
+ /** true only for a KNOWN install: false is "not known to be installed" (missing OR undecided), see `getModelStatus` */
307
317
  isModelInstalled = (name: KnownModel_Name): boolean => {
308
318
  return this.modelList?.models.some((x) => x.name === name && x.installed === 'True') ?? false
309
319
  }
310
320
 
311
321
  modelsBeeingInstalled = new Set<KnownModel_Name>()
312
322
 
313
- /** queue the install, wait until the Manager ran it; true only once the model is verified installed */
314
- installModel = async (model: ComfyManagerModelInfo): Promise<boolean> => {
323
+ /** queue the install, wait until the Manager ran it; true only once the model is verified installed (`installModelOutcome` tells failed from unknown) */
324
+ installModel = async (model: ComfyManagerModelInfo): Promise<boolean> =>
325
+ (await this.installModelOutcome(model)) === 'installed'
326
+
327
+ installModelOutcome = async (model: ComfyManagerModelInfo): Promise<InstallOutcome> => {
315
328
  this.modelsBeeingInstalled.add(model.name)
316
329
  try {
317
330
  return await this.runInstall(`model "${model.name}"`, {
@@ -324,7 +337,7 @@ export class ComfyManager {
324
337
  const row = (await s.fetchModels()).models.find(
325
338
  (x) => x.filename === model.filename && x.save_path === model.save_path && x.base === model.base,
326
339
  )
327
- return row?.installed === 'True'
340
+ return row == null ? null : row.installed === 'True'
328
341
  },
329
342
  })
330
343
  } finally {
@@ -359,6 +372,7 @@ export class ComfyManager {
359
372
  )
360
373
  }
361
374
 
375
+ /** true only for a KNOWN install: false is "not known to be installed" (missing OR undecided), see `getPluginStatus` */
362
376
  isPluginInstalled = (title: KnownComfyPluginTitle): boolean => {
363
377
  if (!this.pluginList || !this.pluginList.custom_nodes) return false
364
378
  return this.pluginList.custom_nodes.some((x) => x.title === title && x.installed === 'True') ?? false
@@ -377,6 +391,48 @@ export class ComfyManager {
377
391
  return status
378
392
  }
379
393
 
394
+ // REQUIREMENTS: undecided is not missing --------------------------------------------
395
+ /** one requirement against the fetched lists; `unknown` when they cannot say, null when the mirror does not know it */
396
+ requirementStatus = (req: Requirements): PluginInstallStatus | null => {
397
+ const mirror = this.mirror()
398
+ const packs = ((): readonly ComfyManagerPluginInfo[] | null => {
399
+ if (req.type === 'customNodesByNodeKey') return mirror.plugins_byNodeKey.get(req.nodeName) ?? []
400
+ if (req.type === 'customNodesByTitle') return [mirror.plugins_byTitle.get(req.title)].filter((x) => x != null)
401
+ if (req.type === 'customNodesByURI') return [mirror.plugins_byFile.get(req.uri)].filter((x) => x != null)
402
+ return null
403
+ })()
404
+ if (packs == null) return req.type === 'modelInManager' ? this.getModelStatus(req.modelName) : null
405
+ if (packs.length === 0) return req.type === 'customNodesByNodeKey' ? 'unknown' : null
406
+ const statuses = packs.map((x) => this.getPluginStatus(x.title))
407
+ if (statuses.some((x) => x === 'installed' || x === 'update-available')) return 'installed'
408
+ return statuses.every((x) => x === 'not-installed') ? 'not-installed' : 'unknown'
409
+ }
410
+
411
+ /** `missing`: known not installed, the only requirements an install flow may queue; `undecided`: the lists cannot say */
412
+ checkRequirements = (requirements: Requirements[]): { missing: Requirements[]; undecided: Requirements[] } => {
413
+ const out: { missing: Requirements[]; undecided: Requirements[] } = { missing: [], undecided: [] }
414
+ for (const req of requirements) {
415
+ if (req.optional) continue
416
+ const status = this.requirementStatus(req)
417
+ if (status === 'not-installed') out.missing.push(req)
418
+ else if (status === 'unknown' || status === 'error') out.undecided.push(req)
419
+ }
420
+ return out
421
+ }
422
+
423
+ /** false only when a requirement is known missing; an undecided one passes with a warning */
424
+ matchRequirements = (requirements: Requirements[]): boolean => {
425
+ const check = this.checkRequirements(requirements)
426
+ if (check.undecided.length > 0)
427
+ logError(
428
+ `requirements the host lists cannot decide, read as present: ${check.undecided.map((r) => JSON.stringify(r)).join(', ')}` +
429
+ (this.pluginList == null || this.modelList == null
430
+ ? ' (the lists are not fetched: call fetchPluginsAndModels)'
431
+ : ''),
432
+ )
433
+ return check.missing.length === 0
434
+ }
435
+
380
436
  /** the host's plugin list in the public `custom_nodes` shape, titled like our mirror; absent = `unknown` */
381
437
  fetchPlugins = async (
382
438
  /** @default: 'cache' */
@@ -387,8 +443,11 @@ export class ComfyManager {
387
443
  return this.strategy(await this.api()).fetchPlugins(mode, skipUpdate)
388
444
  }
389
445
 
390
- /** queue the install, wait until the Manager ran it; true only once the pack is verified installed */
391
- installPlugin = async (plugin: ComfyManagerPluginInfo): Promise<boolean> => {
446
+ /** queue the install, wait until the Manager ran it; true only once the pack is verified installed (`installPluginOutcome` tells failed from unknown) */
447
+ installPlugin = async (plugin: ComfyManagerPluginInfo): Promise<boolean> =>
448
+ (await this.installPluginOutcome(plugin)) === 'installed'
449
+
450
+ installPluginOutcome = async (plugin: ComfyManagerPluginInfo): Promise<InstallOutcome> => {
392
451
  return this.runInstall(`plugin "${plugin.title}"`, {
393
452
  enqueue: (api, uiId) => this.strategy(api).enqueuePlugin(plugin, uiId),
394
453
  landed: async (_s, api) => {
@@ -478,7 +537,7 @@ export class ComfyManager {
478
537
  plugin: ComfyManagerPluginInfo,
479
538
  uiId: string,
480
539
  send: (body: Record<string, unknown>) => Promise<unknown>,
481
- ): Promise<void> => {
540
+ ): Promise<undefined> => {
482
541
  const url = plugin.files[0] ?? plugin.reference
483
542
  const list = await this.fetchPluginWire(api, 'cache', true)
484
543
  if (!('node_packs' in list))
@@ -499,10 +558,15 @@ export class ComfyManager {
499
558
  ui_id: uiId,
500
559
  skip_post_install: false,
501
560
  })
561
+ return undefined
502
562
  }
503
563
 
504
- /** v4: no list to take a row from, so the pack goes by repo name at nightly */
505
- private enqueuePluginTask = async (api: ManagerApi, plugin: ComfyManagerPluginInfo, uiId: string): Promise<void> => {
564
+ /** v4: no list to take a row from, so the pack goes by repo name at nightly; resolves with that id */
565
+ private enqueuePluginTask = async (
566
+ api: ManagerApi,
567
+ plugin: ComfyManagerPluginInfo,
568
+ uiId: string,
569
+ ): Promise<string> => {
506
570
  const url = plugin.files[0] ?? plugin.reference
507
571
  const id = repoPath(url).split('/').pop() ?? url
508
572
  const params = {
@@ -519,17 +583,38 @@ export class ComfyManager {
519
583
  kind: 'install',
520
584
  params,
521
585
  })
586
+ return id
522
587
  }
523
588
 
524
- /** v4: the task's own history entry says how it ended */
525
- private settleByHistory = async (api: ManagerApi, what: string, uiId: string): Promise<void> => {
589
+ /** v4: the task's own history entry says how it ended; the end state confirms a success */
590
+ private settleByHistory = async (
591
+ api: ManagerApi,
592
+ what: string,
593
+ uiId: string,
594
+ landed: () => Promise<boolean | null>,
595
+ sentId?: string,
596
+ ): Promise<void> => {
526
597
  const route = this.route(api, '/manager/queue/history', `?ui_id=${encodeURIComponent(uiId)}`)
598
+ const readEntry = async () => (await this.getValid(route, TaskHistory_ark)).history.status ?? null
527
599
  const entry = await this.waitFor(what, async () => {
528
- const status = (await this.getValid(route, TaskHistory_ark)).history.status
529
- if (status == null) await this.restartIdleQueue(api)
530
- return status ?? null
600
+ const status = await readEntry()
601
+ if (status != null) return status
602
+ if ((await this.restartIdleQueue(api)) !== 'drained') return null
603
+ // the worker writes the entry before it lets go of the task: read once more to close that race
604
+ const late = await readEntry()
605
+ if (late != null) return late
606
+ throw new InstallFailed(
607
+ 'the task left the queue with no result (a queue/reset from the Manager UI or another client removes it)',
608
+ )
531
609
  })
532
- if (entry.status_str === 'success' || entry.status_str === 'skip') return
610
+ if (entry.status_str === 'success' || entry.status_str === 'skip') {
611
+ if ((await this.endState(landed)) !== false) return
612
+ throw new InstallFailed(
613
+ sentId != null
614
+ ? `the Manager reported success, but this pack does not read installed: another pack holds the id "${sentId}" it installs by`
615
+ : 'the Manager reported success, but it does not read installed afterwards',
616
+ )
617
+ }
533
618
  const messages = entry.messages ?? []
534
619
  // the 4.x worker answers a bare `failed` from its security gate only (4.2.2 and 4.4 source)
535
620
  const gate =
@@ -537,7 +622,7 @@ export class ComfyManager {
537
622
  ? ': refused by its security policy, which allows installs only with security_level normal or below ' +
538
623
  'AND either ComfyUI listening on localhost or network_mode personal_cloud (the ComfyUI console names the rule)'
539
624
  : ''
540
- throw new Error(`the Manager reports ${entry.status_str}: ${messages.join(' | ')}${gate}`)
625
+ throw new InstallFailed(`the Manager reports ${entry.status_str}: ${messages.join(' | ')}${gate}`)
541
626
  }
542
627
 
543
628
  /**
@@ -555,47 +640,88 @@ export class ComfyManager {
555
640
  }
556
641
 
557
642
  /** v3, v4 legacy ui: no per item result over http, so wait for the drain and look at the end state */
558
- private settleByDrain = async (api: ManagerApi, what: string, landed: () => Promise<boolean>): Promise<void> => {
643
+ private settleByDrain = async (
644
+ api: ManagerApi,
645
+ what: string,
646
+ landed: () => Promise<boolean | null>,
647
+ ): Promise<void> => {
559
648
  await this.waitFor(what, async () => ((await this.restartIdleQueue(api)) === 'drained' ? true : null))
560
- if (!(await landed()))
561
- throw new Error(
562
- `the Manager queue drained but it is not installed; ComfyUI-Manager ${api.version} ` +
563
- `reports why only over its websocket (cm-queue-status) and in the ComfyUI console`,
564
- )
649
+ const state = await this.endState(landed)
650
+ if (state === true) return
651
+ if (state === null)
652
+ throw new OutcomeUnknown('the queue drained, but the lists cannot say whether it is installed')
653
+ throw new InstallFailed(
654
+ `the Manager queue drained but it is not installed; ComfyUI-Manager ${api.version} ` +
655
+ `reports why only over its websocket (cm-queue-status) and in the ComfyUI console`,
656
+ )
657
+ }
658
+
659
+ /** the end state after the task ran: a host that does not answer here leaves the outcome unknown */
660
+ private endState = async (landed: () => Promise<boolean | null>): Promise<boolean | null> => {
661
+ try {
662
+ return await landed()
663
+ } catch (exception) {
664
+ throw new OutcomeUnknown(`the task ran, but its end state could not be read: ${errorText(exception)}`)
665
+ }
565
666
  }
566
667
 
567
668
  private runInstall = async (
568
669
  what: string,
569
670
  p: {
570
- enqueue: (api: ManagerApi, uiId: string) => Promise<void>
571
- /** the end state, read when the generation reports no per item result */
572
- landed: (s: ManagerStrategy, api: ManagerApi) => Promise<boolean>
671
+ /** resolves with the id the host installs by, when it is not the pack's own row */
672
+ enqueue: (api: ManagerApi, uiId: string) => Promise<string | undefined>
673
+ /** the end state: true installed, false not, null the lists cannot say */
674
+ landed: (s: ManagerStrategy, api: ManagerApi) => Promise<boolean | null>
573
675
  },
574
- ): Promise<boolean> => {
676
+ ): Promise<InstallOutcome> => {
677
+ const host = this.host.getServerHostHTTP()
575
678
  try {
576
679
  const api = await this.api()
577
680
  const s = this.strategy(api)
578
681
  const uiId = nanoid()
579
- await p.enqueue(api, uiId)
682
+ const sentId = await p.enqueue(api, uiId)
580
683
  await this.post(this.route(api, '/manager/queue/start'))
581
- await s.settle(what, uiId, () => p.landed(s, api))
684
+ await s.settle(what, uiId, () => p.landed(s, api), sentId)
582
685
  logSuccess(`${what} installed`)
583
- return true
686
+ return 'installed'
584
687
  } catch (exception) {
585
- logError(`${what}: install failed on ${this.host.getServerHostHTTP()}: ${errorText(exception)}`)
586
- return false
688
+ if (exception instanceof OutcomeUnknown) {
689
+ logError(
690
+ `${what}: OUTCOME UNKNOWN on ${host}: ${exception.message}. The Manager may still be installing it: ` +
691
+ `refetch the list (fetchModels / fetchPlugins) and read its status before installing again, ` +
692
+ `a blind retry queues a second download`,
693
+ )
694
+ return 'unknown'
695
+ }
696
+ logError(`${what}: install failed on ${host}: ${errorText(exception)}`)
697
+ return 'failed'
587
698
  }
588
699
  }
589
700
 
590
- /** poll until `check` gives a value, never past `timing.installTimeoutMs` */
701
+ /**
702
+ * poll until `check` gives a value. A failed request is a blip: logged, and the poll goes on until
703
+ * `timing.pollGraceMs` passes without one good answer. Giving up, or the deadline, is an UNKNOWN
704
+ * outcome (the task may still run); only an `InstallFailed` from `check` ends the wait as a failure.
705
+ */
591
706
  private waitFor = async <T>(what: string, check: () => Promise<T | null>): Promise<T> => {
592
707
  const deadline = Date.now() + this.timing.installTimeoutMs
708
+ let lastAnswer = Date.now()
593
709
  for (;;) {
594
- const value = await check()
595
- if (value != null) return value
710
+ try {
711
+ const value = await check()
712
+ lastAnswer = Date.now()
713
+ if (value != null) return value
714
+ } catch (exception) {
715
+ if (exception instanceof InstallFailed) throw exception
716
+ if (Date.now() - lastAnswer >= this.timing.pollGraceMs)
717
+ throw new OutcomeUnknown(
718
+ `the host gave no answer for ${this.timing.pollGraceMs} ms (manager.timing.pollGraceMs), last: ${errorText(exception)}`,
719
+ )
720
+ logError(`${what}: poll failed, still waiting: ${errorText(exception)}`)
721
+ }
596
722
  if (Date.now() >= deadline)
597
- throw new Error(
598
- `${what} still running after ${this.timing.installTimeoutMs} ms (manager.timing.installTimeoutMs)`,
723
+ throw new OutcomeUnknown(
724
+ `still running after ${this.timing.installTimeoutMs} ms (manager.timing.installTimeoutMs)`,
599
725
  )
600
726
  await new Promise((resolve) => setTimeout(resolve, this.timing.pollMs))
601
727
  }
@@ -23,8 +23,60 @@ export type CanonicalSubgraphDef = {
23
23
  const SUBGRAPH_INPUT_NODE_ID = -10
24
24
  const SUBGRAPH_OUTPUT_NODE_ID = -20
25
25
 
26
- /** 48 corpus files nest defs inside defs; a self-referencing def would loop forever */
27
- const MAX_EXPANSION_PASSES = 32
26
+ /** expanded node count above which a file is refused before expanding: the largest official
27
+ * template expands to 575 nodes, and fan-out nesting grows geometrically without any cycle */
28
+ export const MAX_EXPANDED_NODES = 100_000
29
+
30
+ /**
31
+ * before any expansion: the definitions as a graph (def → the defs its NORMAL-mode instances name,
32
+ * the only ones expansion follows). A cycle reachable from the root is refused with the defs it
33
+ * runs through, and the expanded size is counted, not built, and refused above
34
+ * MAX_EXPANDED_NODES. One explicit stack, no recursion: the file decides the depth
35
+ */
36
+ const checkExpansion = (wf: CanonicalWorkflow, defs: Map<string, CanonicalSubgraphDef>): void => {
37
+ const children = (nodes: CanonicalNode[]): string[] =>
38
+ nodes.filter((n) => n.mode === 'normal' && defs.has(n.type)).map((n) => n.type)
39
+ const own = (nodes: CanonicalNode[]): number =>
40
+ nodes.filter((n) => !(n.mode === 'normal' && defs.has(n.type))).length
41
+ const name = (id: string): string => JSON.stringify(defs.get(id)?.name ?? id)
42
+ const cap = (n: number): number => Math.min(n, MAX_EXPANDED_NODES + 1)
43
+ const size = new Map<string, number>() // done (black): expanded node count of one instance
44
+ const onPath = new Set<string>() // gray
45
+ for (const root of new Set(children(wf.nodes))) {
46
+ if (size.has(root)) continue
47
+ const stack: { id: string; kids: string[]; next: number }[] = [
48
+ { id: root, kids: children(bang(defs.get(root)).nodes), next: 0 },
49
+ ]
50
+ onPath.add(root)
51
+ while (stack.length > 0) {
52
+ const top = bang(stack[stack.length - 1])
53
+ const kid = top.kids[top.next++]
54
+ if (kid == null) {
55
+ const total = top.kids.reduce((acc, k) => cap(acc + (size.get(k) ?? 0)), own(bang(defs.get(top.id)).nodes))
56
+ size.set(top.id, total)
57
+ onPath.delete(top.id)
58
+ stack.pop()
59
+ continue
60
+ }
61
+ if (size.has(kid)) continue
62
+ if (onPath.has(kid)) {
63
+ const from = stack.findIndex((frame) => frame.id === kid)
64
+ const cycle = [...stack.slice(from).map((frame) => frame.id), kid].map(name).join(' → ')
65
+ throw new WorkflowNormalizeError('subgraph-cycle', `subgraph definitions contain themselves: ${cycle}`, {
66
+ cycle: stack.slice(from).map((frame) => frame.id),
67
+ })
68
+ }
69
+ onPath.add(kid)
70
+ stack.push({ id: kid, kids: children(bang(defs.get(kid)).nodes), next: 0 })
71
+ }
72
+ }
73
+ const total = children(wf.nodes).reduce((acc, k) => cap(acc + (size.get(k) ?? 0)), own(wf.nodes))
74
+ if (total > MAX_EXPANDED_NODES)
75
+ throw new WorkflowNormalizeError(
76
+ 'subgraph-too-large',
77
+ `subgraph expansion would produce more than ${MAX_EXPANDED_NODES} nodes (the largest official template has 575)`,
78
+ )
79
+ }
28
80
 
29
81
  /**
30
82
  * widget-kind fallback when a def input slot has no boundary target carrying a
@@ -43,14 +95,16 @@ const PRIMITIVE_WIDGET_TYPES: ReadonlySet<string> = new Set(['INT', 'FLOAT', 'ST
43
95
  * passthrough walk, which needs no interior.
44
96
  */
45
97
  export const expandSubgraphs = (wf: CanonicalWorkflow, defs: Map<string, CanonicalSubgraphDef>): CanonicalWorkflow => {
98
+ checkExpansion(wf, defs)
99
+ // acyclic now: each pass goes one definition deeper, so defs.size passes always suffice
46
100
  let passes = 0
47
101
  while (true) {
48
102
  const expandable = wf.nodes.filter((n) => defs.has(n.type) && n.mode !== 'bypassed')
49
103
  if (expandable.length === 0) return wf
50
- if (++passes > MAX_EXPANSION_PASSES)
104
+ if (++passes > defs.size + 1)
51
105
  throw new WorkflowNormalizeError(
52
106
  'subgraph-cycle',
53
- `subgraph expansion did not terminate after ${MAX_EXPANSION_PASSES} passes — self-referencing definitions?`,
107
+ `subgraph expansion still had instances after ${passes - 1} passes over ${defs.size} definitions`,
54
108
  )
55
109
  for (const instance of expandable) {
56
110
  if (instance.mode === 'muted') dropMutedInstance(wf, instance)
@@ -18,7 +18,12 @@ import type { LiteGraphNodeInput } from 'src/litegraph/LiteGraphNodeInput.ts'
18
18
  import type { LiteGraphNodeOutput } from 'src/litegraph/LiteGraphNodeOutput.ts'
19
19
  import type { LiteGraphSubgraphDef } from 'src/litegraph/LiteGraphSubgraphDef.ts'
20
20
 
21
- export type WorkflowNormalizeErrorCode = 'schema-reject' | 'subgraph-cycle' | 'subgraph-io-mismatch' | 'bad-document'
21
+ export type WorkflowNormalizeErrorCode =
22
+ | 'schema-reject'
23
+ | 'subgraph-cycle'
24
+ | 'subgraph-too-large'
25
+ | 'subgraph-io-mismatch'
26
+ | 'bad-document'
22
27
 
23
28
  /** a workflow JSON we cannot turn into a CanonicalWorkflow — loud, typed, never a cast */
24
29
  export class WorkflowNormalizeError extends Error {
@@ -13,6 +13,8 @@ import type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPlugi
13
13
  /** the part of the registry the views read */
14
14
  export type ManagerMirror = {
15
15
  plugins_byTitle: ReadonlyMap<KnownComfyPluginTitle, ComfyManagerPluginInfo>
16
+ plugins_byFile: ReadonlyMap<string, ComfyManagerPluginInfo>
17
+ plugins_byNodeKey: ReadonlyMap<string, readonly ComfyManagerPluginInfo[]>
16
18
  /** every model row: upstream ships a few names twice, with different files */
17
19
  modelRows: readonly ComfyManagerModelInfo[]
18
20
  }
@@ -102,6 +102,10 @@ export const convertLiteGraphToPrompt = (
102
102
  else if (Object.hasOwn(node.widgets.named, 'value')) PRIMITIVE_VALUES[node.id] = node.widgets.named['value']
103
103
  }
104
104
 
105
+ // indexes: a lookup per link must not scan the document (a large file stays linear)
106
+ const linksById = new Map(workflow.links.map((l) => [l.id, l]))
107
+ const nodesById = new Map(workflow.nodes.map((n) => [n.id, n]))
108
+
105
109
  // 2. every executable node
106
110
  for (const node of workflow.nodes) {
107
111
  if (isNeverExecuted(node)) continue // frontend-only nodes (reroutes/primitives unwrapped below)
@@ -339,14 +343,14 @@ export const convertLiteGraphToPrompt = (
339
343
  // 2.b links
340
344
  type ParentInfo = { node: CanonicalNode; link: CanonicalLink }
341
345
  const getParentNode = (linkId: LiteGraphLinkID): ParentInfo => {
342
- const link = workflow.links.find((link) => link.id === linkId)
346
+ const link = linksById.get(linkId)
343
347
  if (link == null)
344
348
  throw new WorkflowConvertError(
345
349
  'dangling-link',
346
350
  `node ${node.id}(${node.type}) references a non-existing link (id=${linkId})`,
347
351
  node,
348
352
  )
349
- const parentNode = workflow.nodes.find((n) => n.id === link.originId)
353
+ const parentNode = nodesById.get(link.originId)
350
354
  if (parentNode == null)
351
355
  throw new WorkflowConvertError(
352
356
  'dangling-link',
@@ -520,18 +524,28 @@ export const convertLiteGraphToPrompt = (
520
524
  }
521
525
  }
522
526
  if (missing.size > 0) {
523
- const complete = (id: string, seen: Set<string>): boolean => {
524
- if (seen.has(id)) return true
525
- seen.add(id)
526
- if (missing.has(id)) return false
527
- for (const value of Object.values(prompt[id]?.inputs ?? {}))
528
- if (Array.isArray(value) && typeof value[0] === 'string' && !complete(value[0], seen)) return false
529
- return true
530
- }
527
+ // blocked = every node downstream of a missing input, one queue walk over the consumer
528
+ // edges: a file decides the graph depth, so no recursion here
529
+ const consumers = new Map<string, string[]>()
530
+ for (const [id, n] of Object.entries(prompt))
531
+ for (const value of Object.values(n.inputs))
532
+ if (Array.isArray(value) && typeof value[0] === 'string') {
533
+ const list = consumers.get(value[0]) ?? []
534
+ list.push(id)
535
+ consumers.set(value[0], list)
536
+ }
537
+ const blocked = new Set(missing.keys())
538
+ const queue = [...blocked]
539
+ for (let head = 0; head < queue.length; head++)
540
+ for (const next of consumers.get(queue[head] ?? '') ?? [])
541
+ if (!blocked.has(next)) {
542
+ blocked.add(next)
543
+ queue.push(next)
544
+ }
531
545
  const outputs = Object.keys(prompt).filter(
532
546
  (id) => schema.data.spec[prompt[id]?.class_type ?? '']?.output_node === true,
533
547
  )
534
- const dropped = outputs.filter((id) => !complete(id, new Set()))
548
+ const dropped = outputs.filter((id) => blocked.has(id))
535
549
  const first = missing.values().next().value
536
550
  if (first != null && outputs.length > 0 && dropped.length === outputs.length)
537
551
  throw new WorkflowConvertError('missing-required-input', first.message, first.node)