comfy-ts 2.17.1 → 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.
Files changed (80) hide show
  1. package/dist/cli.js +3 -3
  2. package/dist/index.cjs +1078 -190
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +1185 -410
  5. package/dist/index.d.ts +1185 -410
  6. package/dist/index.js +1078 -190
  7. package/dist/index.js.map +1 -1
  8. package/dist/{run-run-tg82jUIk.js → run-run-Zr699h2S.js} +2 -2
  9. package/dist/{run-run-tg82jUIk.js.map → run-run-Zr699h2S.js.map} +1 -1
  10. package/dist/{run-tui-Bw7BA75d.js → run-tui-CeM1GOJP.js} +2 -2
  11. package/dist/{run-tui-Bw7BA75d.js.map → run-tui-CeM1GOJP.js.map} +1 -1
  12. package/dist/serve-web.js +47 -47
  13. package/dist/{state-zTow5ucI.js → state-C067Kbew.js} +1079 -191
  14. package/dist/state-C067Kbew.js.map +1 -0
  15. package/dist/web.d.ts +1203 -428
  16. package/dist/web.js +1078 -190
  17. package/dist/web.js.map +1 -1
  18. package/examples/comfy-cloud/ace-step15-t2a.cflow.ts +163 -0
  19. package/examples/comfy-cloud/anima-t2i-base.cflow.ts +57 -0
  20. package/examples/comfy-cloud/boogu-t2i.cflow.ts +55 -0
  21. package/examples/comfy-cloud/chronoedit-i2i.cflow.ts +95 -0
  22. package/examples/comfy-cloud/ernie-t2i-base.cflow.ts +81 -0
  23. package/examples/comfy-cloud/flux1-t2i-krea.cflow.ts +63 -0
  24. package/examples/comfy-cloud/flux2-i2i-dev.cflow.ts +83 -0
  25. package/examples/comfy-cloud/flux2-t2i-dev.cflow.ts +60 -0
  26. package/examples/comfy-cloud/hidream-o1-i2i.cflow.ts +71 -0
  27. package/examples/comfy-cloud/hidream-o1-t2i.cflow.ts +62 -0
  28. package/examples/comfy-cloud/krea2-i2i.cflow.ts +78 -0
  29. package/examples/comfy-cloud/ltx2-i2v.cflow.ts +175 -0
  30. package/examples/comfy-cloud/ltx2-t2v.cflow.ts +143 -0
  31. package/examples/comfy-cloud/ltx23-i2v.cflow.ts +189 -0
  32. package/examples/comfy-cloud/ltx23-t2v.cflow.ts +151 -0
  33. package/examples/comfy-cloud/mage-flow-i2i-turbo.cflow.ts +72 -0
  34. package/examples/comfy-cloud/mage-flow-i2i.cflow.ts +74 -0
  35. package/examples/comfy-cloud/mage-flow-t2i-turbo.cflow.ts +60 -0
  36. package/examples/comfy-cloud/mage-flow-t2i.cflow.ts +60 -0
  37. package/examples/comfy-cloud/minimax-h3-t2i.cflow.ts +64 -0
  38. package/examples/comfy-cloud/netayume-t2i.cflow.ts +60 -0
  39. package/examples/comfy-cloud/qwen-image-i2i-2509.cflow.ts +75 -0
  40. package/examples/comfy-cloud/qwen-image-t2i-2512.cflow.ts +63 -0
  41. package/examples/comfy-cloud/sdk.d.ts +21683 -13737
  42. package/examples/comfy-cloud/stable-audio3-t2a.cflow.ts +96 -0
  43. package/examples/comfy-cloud/z-image-t2i-base.cflow.ts +54 -0
  44. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +1 -1
  45. package/package.json +2 -2
  46. package/src/graph/ComfyNode.ts +93 -12
  47. package/src/host/ComfyHost.ts +37 -46
  48. package/src/host/ComfyManager.ts +576 -64
  49. package/src/litegraph/CanonicalWorkflow.ts +3 -0
  50. package/src/litegraph/LiteGraphJSON.ts +2 -2
  51. package/src/litegraph/LiteGraphNodeInput.ts +2 -2
  52. package/src/litegraph/LiteGraphNodeOutput.ts +2 -2
  53. package/src/litegraph/convertFlowToLiteGraphJSON.ts +112 -37
  54. package/src/litegraph/expandSubgraphs.ts +72 -4
  55. package/src/litegraph/normalizeWorkflow.ts +7 -1
  56. package/src/manager/ComfyRegistry.ts +2 -0
  57. package/src/manager/generated/KnownComfyCustomNodeName.ts +6354 -1680
  58. package/src/manager/generated/KnownComfyPluginTitle.ts +718 -356
  59. package/src/manager/generated/KnownComfyPluginURL.ts +357 -181
  60. package/src/manager/generated/KnownModel_Base.ts +9 -5
  61. package/src/manager/generated/KnownModel_FileName.ts +135 -0
  62. package/src/manager/generated/KnownModel_Name.ts +135 -0
  63. package/src/manager/generated/KnownModel_SavePath.ts +16 -14
  64. package/src/manager/generated/KnownModel_Type.ts +15 -13
  65. package/src/manager/installedView.ts +178 -0
  66. package/src/manager/json/custom-node-list.json +4018 -2248
  67. package/src/manager/json/extension-node-map.json +8903 -2964
  68. package/src/manager/json/github-stats.json +10796 -10036
  69. package/src/manager/json/model-list.json +298 -1
  70. package/src/manager/loaders/step4_model-list-loader.ts +1 -0
  71. package/src/manager/types/ComfyManagerAPIModelList.ts +3 -0
  72. package/src/manager/types/ComfyManagerAPIPluginList.ts +19 -0
  73. package/src/runner/ComfyExecution.ts +4 -1
  74. package/src/runner/ComfyWsApi.ts +82 -15
  75. package/src/sdk-generator/ComfySchema.ts +10 -1
  76. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +4 -1
  77. package/src/sdk-generator/comfyui-sdk-codegen.ts +61 -20
  78. package/src/sdk-generator/inputWidgetKind.ts +19 -4
  79. package/src/sdk-generator/litegraphToApiRequestPayload.ts +157 -35
  80. package/dist/state-zTow5ucI.js.map +0 -1
@@ -1,24 +1,112 @@
1
1
  /** 🔶 NAMING DISCLAIMER: I call a "custom node package" => "PLUGIN" */
2
2
 
3
- import type { Type } from 'arktype'
3
+ import { type ArkErrors, type Type, type } from 'arktype'
4
+ import { nanoid } from 'nanoid'
4
5
  import type { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'
5
6
  import type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'
6
7
  import type { KnownModel_Name } from 'src/manager/generated/KnownModel_Name.ts'
8
+ import {
9
+ attributePacks,
10
+ buildModelView,
11
+ buildPluginView,
12
+ type InstalledPacks,
13
+ InstalledPacks_ark,
14
+ type ManagerMirror,
15
+ modelFolders,
16
+ type PackMappings,
17
+ PackMappings_ark,
18
+ packIsInstalled,
19
+ repoPath,
20
+ } from 'src/manager/installedView.ts'
7
21
  import type { ComfyManagerAPIFetchPolicy } from 'src/manager/types/ComfyManagerAPIFetchPolicy.ts'
8
22
  import {
9
23
  type ComfyManagerAPIModelList,
10
24
  ComfyManagerAPIModelList_ark,
11
25
  } from 'src/manager/types/ComfyManagerAPIModelList.ts'
12
26
  import {
27
+ type ComfyManagerAPIPackList,
28
+ ComfyManagerAPIPackList_ark,
13
29
  type ComfyManagerAPIPluginList,
14
30
  ComfyManagerAPIPluginList_ark,
15
31
  } from 'src/manager/types/ComfyManagerAPIPluginList.ts'
16
32
  import type { ComfyManagerModelInfo } from 'src/manager/types/ComfyManagerModelInfo.ts'
17
33
  import type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'
18
34
  import type { Maybe } from 'src/types/index.ts'
19
- import { logError as toastError, logSuccess as toastSuccess } from 'src/utils/log.ts'
35
+ import { logError, logSuccess } from 'src/utils/log.ts'
20
36
  import { softValidate } from 'src/utils/softValidate.ts'
21
- import type { PluginInstallStatus } from 'src/host/Requirements.ts'
37
+ import type { PluginInstallStatus, Requirements } from 'src/host/Requirements.ts'
38
+
39
+ /**
40
+ * the three ComfyUI-Manager servers in the field (agent/architecture.md, Manager HTTP client):
41
+ * `v3` the legacy custom node (bare routes), `v4-legacy-ui` the pip package under
42
+ * `--enable-manager-legacy-ui` (/v2), `v4` the pip package with its default ui (/v2, no lists)
43
+ */
44
+ export type ManagerGeneration = 'v3' | 'v4-legacy-ui' | 'v4'
45
+ export type ManagerApi = { generation: ManagerGeneration; version: string }
46
+
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 {}
58
+
59
+ type ManagerRoute =
60
+ | '/manager/version'
61
+ | '/manager/reboot'
62
+ | '/manager/terminal'
63
+ | '/customnode/getlist'
64
+ | '/externalmodel/getlist'
65
+ | '/customnode/installed'
66
+ | '/customnode/getmappings'
67
+ | '/manager/queue/install'
68
+ | '/manager/queue/batch'
69
+ | '/manager/queue/task'
70
+ | '/manager/queue/install_model'
71
+ | '/manager/queue/start'
72
+ | '/manager/queue/status'
73
+ | '/manager/queue/history'
74
+
75
+ /** what each generation does NOT serve (history means the `?ui_id=` form) */
76
+ const NOT_SERVED: Record<ManagerGeneration, ManagerRoute[]> = {
77
+ v3: ['/manager/queue/batch', '/manager/queue/task', '/manager/queue/history'],
78
+ 'v4-legacy-ui': ['/manager/queue/install', '/manager/queue/task', '/manager/queue/history', '/manager/terminal'],
79
+ v4: [
80
+ '/customnode/getlist',
81
+ '/externalmodel/getlist',
82
+ '/manager/queue/install',
83
+ '/manager/queue/batch',
84
+ '/manager/terminal',
85
+ ],
86
+ }
87
+
88
+ /** everything that differs between generations beyond a route's spelling */
89
+ type ManagerStrategy = {
90
+ fetchPlugins: (mode: ComfyManagerAPIFetchPolicy, skipUpdate: boolean) => Promise<ComfyManagerAPIPluginList>
91
+ fetchModels: () => Promise<ComfyManagerAPIModelList>
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>
94
+ /** wait until the queued task ran: resolves when it succeeded, throws with why when not */
95
+ settle: (what: string, uiId: string, landed: () => Promise<boolean | null>, sentId?: string) => Promise<void>
96
+ }
97
+
98
+ const QueueStatus_ark = type({
99
+ is_processing: 'boolean',
100
+ 'pending_count?': 'number',
101
+ 'total_count?': 'number',
102
+ 'done_count?': 'number',
103
+ })
104
+ const TaskHistory_ark = type({
105
+ history: { 'status?': { status_str: 'string', 'messages?': 'string[]' }, 'result?': 'string' },
106
+ })
107
+ const ModelFolders_ark = type('string[]')
108
+
109
+ const errorText = (e: unknown): string => (e instanceof Error ? e.message : String(e))
22
110
 
23
111
  export class ComfyManager {
24
112
  constructor(
@@ -26,24 +114,115 @@ export class ComfyManager {
26
114
  getServerHostHTTP: () => string
27
115
  fetch: (route: string, init?: RequestInit, p?: { apiPrefix?: boolean }) => Promise<Response>
28
116
  },
29
- ) {
30
- // void this.updateHostPluginsAndModels()
31
- }
117
+ public timing: ManagerTiming = { ...MANAGER_TIMING },
118
+ /** the mirror the lists are joined to; the registry by default */
119
+ public mirror: () => ManagerMirror = () => comfyts.registry,
120
+ ) {}
32
121
 
33
122
  get registry(): ComfyRegistry {
34
123
  return comfyts.registry
35
124
  }
36
125
 
37
- fetchPluginsAndModels = async (): Promise<void> => {
38
- const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()])
39
- this.pluginList = _pluginList
40
- this.modelList = _modelList
126
+ /** identifies install tasks of this client in the Manager queue (4.x requires one) */
127
+ readonly clientId: string = `comfy-ts-${nanoid(8)}`
128
+
129
+ // generation ------------------------------------------------------------------------
130
+ private _api: Promise<ManagerApi> | null = null
131
+
132
+ /** which Manager answers: probed once, remembered, forgotten on failure and on reboot */
133
+ api = (): Promise<ManagerApi> => {
134
+ if (this._api == null) {
135
+ const probe = this.probeApi()
136
+ this._api = probe
137
+ probe.catch(() => {
138
+ if (this._api === probe) this._api = null
139
+ })
140
+ }
141
+ return this._api
142
+ }
143
+
144
+ private probeApi = async (): Promise<ManagerApi> => {
145
+ const v4 = await this.host.fetch('/v2/manager/version')
146
+ if (v4.ok) {
147
+ const version = (await v4.text()).trim()
148
+ const ui = await this.host.fetch('/v2/manager/is_legacy_manager_ui')
149
+ if (!ui.ok) {
150
+ logError(
151
+ `ComfyUI-Manager ${version}: GET /v2/manager/is_legacy_manager_ui → ${ui.status}, assuming the default ui`,
152
+ )
153
+ return { generation: 'v4', version }
154
+ }
155
+ const flag: unknown = await ui.json()
156
+ const legacy =
157
+ typeof flag === 'object' &&
158
+ flag != null &&
159
+ 'is_legacy_manager_ui' in flag &&
160
+ flag.is_legacy_manager_ui === true
161
+ return { generation: legacy ? 'v4-legacy-ui' : 'v4', version }
162
+ }
163
+ const v3 = await this.host.fetch('/manager/version')
164
+ if (v3.ok) return { generation: 'v3', version: (await v3.text()).trim() }
165
+ throw new Error(
166
+ `🔴 no ComfyUI-Manager answers at ${this.host.getServerHostHTTP()} ` +
167
+ `(GET /v2/manager/version → ${v4.status}, GET /manager/version → ${v3.status})`,
168
+ )
169
+ }
170
+
171
+ /** the one place a Manager route gets its generation's spelling */
172
+ private route = (api: ManagerApi, route: ManagerRoute, query: string = ''): string => {
173
+ if (NOT_SERVED[api.generation].includes(route))
174
+ throw new Error(`🔴 ComfyUI-Manager ${api.version} (${api.generation}) does not serve ${route}`)
175
+ return `${api.generation === 'v3' ? '' : '/v2'}${route}${query}`
176
+ }
177
+
178
+ /** the one place the generations differ beyond a route's spelling */
179
+ private strategy = (api: ManagerApi): ManagerStrategy => {
180
+ switch (api.generation) {
181
+ case 'v3':
182
+ return {
183
+ fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),
184
+ fetchModels: () => this.listedModels(api),
185
+ enqueuePlugin: (plugin, uiId) =>
186
+ this.enqueueListedPlugin(api, plugin, uiId, (body) =>
187
+ this.post(this.route(api, '/manager/queue/install'), body),
188
+ ),
189
+ settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed),
190
+ }
191
+ case 'v4-legacy-ui':
192
+ return {
193
+ fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),
194
+ fetchModels: () => this.listedModels(api),
195
+ enqueuePlugin: (plugin, uiId) =>
196
+ this.enqueueListedPlugin(api, plugin, uiId, async (body) => {
197
+ const route = this.route(api, '/manager/queue/batch')
198
+ const res = await this.post(route, { install: [body] })
199
+ const failed = typeof res === 'object' && res != null && 'failed' in res ? res.failed : null
200
+ if (Array.isArray(failed) && failed.length > 0)
201
+ throw new Error(
202
+ `POST ${route} refused ${JSON.stringify(failed)}: the batch reply carries ids only, ` +
203
+ `the ComfyUI console says why (a 4.x security policy refusal is the usual one)`,
204
+ )
205
+ }),
206
+ settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed),
207
+ }
208
+ case 'v4':
209
+ return {
210
+ fetchPlugins: () => this.installedPluginView(api),
211
+ fetchModels: () => this.installedModelView(),
212
+ enqueuePlugin: (plugin, uiId) => this.enqueuePluginTask(api, plugin, uiId),
213
+ settle: (what, uiId, landed, sentId) => this.settleByHistory(api, what, uiId, landed, sentId),
214
+ }
215
+ }
41
216
  }
42
217
 
43
218
  // -----------
44
- configureLogging = (mi: boolean): Promise<unknown> => {
45
- // return this.repository.getModelInfoFinalFilePath(mi)
46
- return this.fetchGetText(`/manager/terminal?mode=${mi}`)
219
+ configureLogging = async (mi: boolean): Promise<string> => {
220
+ const api = await this.api()
221
+ const route = this.route(api, '/manager/terminal', `?mode=${mi}`)
222
+ const response = await this.host.fetch(route)
223
+ const text = await response.text()
224
+ if (!response.ok) throw new Error(`🔴 GET ${route} → ${response.status} ${text}`)
225
+ return text
47
226
  }
48
227
 
49
228
  // utils ------------------------------------------------------------------------------
@@ -87,18 +266,21 @@ export class ComfyManager {
87
266
  * reboot the ComfyUI process (ComfyUI-Manager).
88
267
  *
89
268
  * The server dies mid-request, so a DROPPED CONNECTION is the success shape and the only
90
- * one most callers ever see. A 404 is not: the route is POST from Manager V3 on (verified
91
- * against V3.41), and a GET there answers 404 while the process keeps running — a caller
92
- * that treats every failure as "expected mid-reboot disconnect" then reports a reboot that
93
- * never happened. Both verbs are tried so an old and a new Manager both work, and anything
94
- * that is neither a disconnect nor a 404 throws with what the host actually said.
269
+ * one most callers ever see. A 404 is not: the route is POST from Manager V3 on, and a GET
270
+ * there answers 404 while the process keeps running. Both verbs are tried so a pre-V3
271
+ * Manager still reboots, and anything that is neither a disconnect nor a 404 throws with
272
+ * what the host actually said. The process may come back with another Manager, so the
273
+ * remembered generation is dropped.
95
274
  */
96
275
  restartComfyUI = async (): Promise<void> => {
276
+ const api = await this.api()
277
+ this._api = null
278
+ const route = this.route(api, '/manager/reboot')
97
279
  const refusals: string[] = []
98
280
  for (const method of ['POST', 'GET'] as const) {
99
281
  let response: Response
100
282
  try {
101
- response = await this.host.fetch('/manager/reboot', { method })
283
+ response = await this.host.fetch(route, { method })
102
284
  } catch {
103
285
  return // connection gone: the process is going down, which is what we asked for
104
286
  }
@@ -108,39 +290,58 @@ export class ComfyManager {
108
290
  if (response.status !== 404) break
109
291
  }
110
292
  throw new Error(
111
- `🔴 ${this.host.getServerHostHTTP()} refused to reboot (${refusals.join(', ')}) — ` +
112
- `ComfyUI-Manager is not installed there, or its reboot route moved again`,
293
+ `🔴 ${this.host.getServerHostHTTP()} refused to reboot (${route}: ${refusals.join(', ')}) — ` +
294
+ `ComfyUI-Manager ${api.version} is not there any more, or its reboot route moved again`,
113
295
  )
114
296
  }
115
297
 
298
+ // LISTS ----------------------------------------------------------------------------
299
+ fetchPluginsAndModels = async (): Promise<void> => {
300
+ const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()])
301
+ this.pluginList = _pluginList
302
+ this.modelList = _modelList
303
+ }
304
+
116
305
  modelList: Maybe<ComfyManagerAPIModelList> = null
117
306
 
118
- fetchModels = (): Promise<ComfyManagerAPIModelList> => {
119
- return this.fetchGetJSON('/externalmodel/getlist?mode=cache', ComfyManagerAPIModelList_ark)
307
+ /** what the host has of our model mirror; a model absent from the list reads `unknown` */
308
+ fetchModels = async (): Promise<ComfyManagerAPIModelList> => {
309
+ return this.strategy(await this.api()).fetchModels()
120
310
  }
121
311
 
122
312
  fetchLogs = (): Promise<any> => {
123
- return this.fetchGetJSON<unknown>('/internal/logs')
313
+ return this.getJSON<unknown>('/internal/logs')
124
314
  }
125
315
 
316
+ /** true only for a KNOWN install: false is "not known to be installed" (missing OR undecided), see `getModelStatus` */
126
317
  isModelInstalled = (name: KnownModel_Name): boolean => {
127
318
  return this.modelList?.models.some((x) => x.name === name && x.installed === 'True') ?? false
128
319
  }
129
320
 
130
321
  modelsBeeingInstalled = new Set<KnownModel_Name>()
131
322
 
132
- 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> => {
328
+ this.modelsBeeingInstalled.add(model.name)
133
329
  try {
134
- this.modelsBeeingInstalled.add(model.name)
135
- await this.fetchPost('/model/install', model)
136
- this.modelsBeeingInstalled.delete(model.name)
137
- toastSuccess('Model installed')
138
- return true
139
- } catch (exception) {
140
- console.error(`Install failed: ${/*model.title*/ ''} / ${exception}`)
141
- toastError('Model Installation Failed')
330
+ return await this.runInstall(`model "${model.name}"`, {
331
+ enqueue: async (api, uiId) => {
332
+ const body = { ...model, ui_id: uiId, client_id: this.clientId }
333
+ await this.post(this.route(api, '/manager/queue/install_model'), body)
334
+ },
335
+ landed: async (s) => {
336
+ // the triple the Manager's own install whitelist matches on
337
+ const row = (await s.fetchModels()).models.find(
338
+ (x) => x.filename === model.filename && x.save_path === model.save_path && x.base === model.base,
339
+ )
340
+ return row == null ? null : row.installed === 'True'
341
+ },
342
+ })
343
+ } finally {
142
344
  this.modelsBeeingInstalled.delete(model.name)
143
- return false
144
345
  }
145
346
  }
146
347
 
@@ -171,6 +372,7 @@ export class ComfyManager {
171
372
  )
172
373
  }
173
374
 
375
+ /** true only for a KNOWN install: false is "not known to be installed" (missing OR undecided), see `getPluginStatus` */
174
376
  isPluginInstalled = (title: KnownComfyPluginTitle): boolean => {
175
377
  if (!this.pluginList || !this.pluginList.custom_nodes) return false
176
378
  return this.pluginList.custom_nodes.some((x) => x.title === title && x.installed === 'True') ?? false
@@ -189,63 +391,373 @@ export class ComfyManager {
189
391
  return status
190
392
  }
191
393
 
192
- // --------------------------------------------------------------
193
- // https://github.com/ltdrdata/ComfyUI-Manager/blob/4649d216b1842aa48b95d3f064c679a1b698e506/js/custom-nodes-downloader.js#L14C25-L14C88
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
+
436
+ /** the host's plugin list in the public `custom_nodes` shape, titled like our mirror; absent = `unknown` */
194
437
  fetchPlugins = async (
195
438
  /** @default: 'cache' */
196
439
  mode: ComfyManagerAPIFetchPolicy = 'cache',
197
440
  /** @default: true */
198
441
  skipUpdate: boolean = true,
199
442
  ): Promise<ComfyManagerAPIPluginList> => {
443
+ return this.strategy(await this.api()).fetchPlugins(mode, skipUpdate)
444
+ }
445
+
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> => {
451
+ return this.runInstall(`plugin "${plugin.title}"`, {
452
+ enqueue: (api, uiId) => this.strategy(api).enqueuePlugin(plugin, uiId),
453
+ landed: async (_s, api) => {
454
+ const data = await this.installedData(api)
455
+ return packIsInstalled(attributePacks(data.installed, data.mappings), plugin)
456
+ },
457
+ })
458
+ }
459
+
460
+ // LIST BUILDERS: one per source, picked by the strategy -------------------------------
461
+ /** the Manager's own getlist (v3, v4 legacy ui), normalized */
462
+ private listedPlugins = async (
463
+ api: ManagerApi,
464
+ mode: ComfyManagerAPIFetchPolicy,
465
+ skipUpdate: boolean,
466
+ ): Promise<ComfyManagerAPIPluginList> => {
467
+ const raw = await this.fetchPluginWire(api, mode, skipUpdate)
468
+ if (!('node_packs' in raw)) return raw
469
+ const titleByRepo = new Map<string, KnownComfyPluginTitle>()
470
+ for (const p of this.mirror().plugins_byTitle.values())
471
+ for (const f of p.files) titleByRepo.set(repoPath(f), p.title)
472
+ return {
473
+ chanel: raw.channel,
474
+ custom_nodes: Object.values(raw.node_packs).map((p) => {
475
+ const repo = p.files?.[0]
476
+ return {
477
+ title: (repo != null ? titleByRepo.get(repoPath(repo)) : undefined) ?? p.title,
478
+ installed: p.state !== 'enabled' ? 'False' : p['update-state'] === 'true' ? 'Update' : 'True',
479
+ }
480
+ }),
481
+ }
482
+ }
483
+
484
+ private fetchPluginWire = async (
485
+ api: ManagerApi,
486
+ mode: ComfyManagerAPIFetchPolicy,
487
+ skipUpdate: boolean,
488
+ ): Promise<ComfyManagerAPIPackList | ComfyManagerAPIPluginList> => {
489
+ const query = `?mode=${mode}${skipUpdate ? '&skip_update=true' : ''}`
490
+ const json: unknown = await this.getJSON(this.route(api, '/customnode/getlist', query))
491
+ if (typeof json === 'object' && json != null && 'custom_nodes' in json)
492
+ return softValidate(ComfyManagerAPIPluginList_ark, json)
493
+ return softValidate(ComfyManagerAPIPackList_ark, json)
494
+ }
495
+
496
+ private listedModels = async (api: ManagerApi): Promise<ComfyManagerAPIModelList> => {
497
+ return this.getJSON(this.route(api, '/externalmodel/getlist', '?mode=cache'), ComfyManagerAPIModelList_ark)
498
+ }
499
+
500
+ /** what is installed, as the Manager scans it, joined through its own registry id mappings */
501
+ private installedData = async (api: ManagerApi): Promise<{ installed: InstalledPacks; mappings: PackMappings }> => {
502
+ const [installed, mappings] = await Promise.all([
503
+ this.getValid(this.route(api, '/customnode/installed'), InstalledPacks_ark),
504
+ this.getValid(this.route(api, '/customnode/getmappings', '?mode=cache'), PackMappings_ark),
505
+ ])
506
+ return { installed, mappings }
507
+ }
508
+
509
+ /** v4 serves no list: our mirror against what is installed */
510
+ private installedPluginView = async (api: ManagerApi): Promise<ComfyManagerAPIPluginList> => {
511
+ const view = buildPluginView({ mirror: this.mirror(), ...(await this.installedData(api)) })
512
+ if (view.unattributed.length > 0)
513
+ logError(
514
+ `ComfyUI-Manager ${api.version} reports installed packs no mirror row can be tied to ` +
515
+ `(${view.unattributed.join(', ')}): the mirror rows they could be read unknown`,
516
+ )
517
+ return view.list
518
+ }
519
+
520
+ /** v4 serves no model list: core ComfyUI's model folders against our mirror */
521
+ private installedModelView = async (): Promise<ComfyManagerAPIModelList> => {
522
+ const models = this.mirror().modelRows
523
+ const registered = new Set(await this.getValid('/models', ModelFolders_ark))
524
+ const folders = [...modelFolders(models)].filter((f) => registered.has(f))
525
+ const lists = await Promise.all(
526
+ folders.map(
527
+ async (f) => [f, await this.getValid(`/models/${encodeURIComponent(f)}`, ModelFolders_ark)] as const,
528
+ ),
529
+ )
530
+ return buildModelView({ models, files: new Map(lists) })
531
+ }
532
+
533
+ // INSTALL FLOW: enqueue → start → settle -------------------------------------------
534
+ /** v3 and v4 legacy ui: the Manager's own list row for the pack, sent like its own ui does */
535
+ private enqueueListedPlugin = async (
536
+ api: ManagerApi,
537
+ plugin: ComfyManagerPluginInfo,
538
+ uiId: string,
539
+ send: (body: Record<string, unknown>) => Promise<unknown>,
540
+ ): Promise<undefined> => {
541
+ const url = plugin.files[0] ?? plugin.reference
542
+ const list = await this.fetchPluginWire(api, 'cache', true)
543
+ if (!('node_packs' in list))
544
+ throw new Error(`ComfyUI-Manager ${api.version} lists packs in the pre-V3 shape and has no queue install`)
545
+ const found = Object.entries(list.node_packs).find(([, p]) =>
546
+ (p.files ?? []).some((f) => repoPath(f) === repoPath(url)),
547
+ )
548
+ if (found == null)
549
+ throw new Error(
550
+ `${url} is not in the Manager's own list (channel ${list.channel}), so it refuses to install it`,
551
+ )
552
+ const [key, row] = found
553
+ await send({
554
+ ...row,
555
+ id: row.id ?? key,
556
+ channel: list.channel,
557
+ mode: 'cache',
558
+ ui_id: uiId,
559
+ skip_post_install: false,
560
+ })
561
+ return undefined
562
+ }
563
+
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> => {
570
+ const url = plugin.files[0] ?? plugin.reference
571
+ const id = repoPath(url).split('/').pop() ?? url
572
+ const params = {
573
+ id,
574
+ version: 'nightly',
575
+ selected_version: 'nightly',
576
+ repository: url,
577
+ mode: 'cache',
578
+ channel: 'default',
579
+ }
580
+ await this.post(this.route(api, '/manager/queue/task'), {
581
+ ui_id: uiId,
582
+ client_id: this.clientId,
583
+ kind: 'install',
584
+ params,
585
+ })
586
+ return id
587
+ }
588
+
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> => {
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
599
+ const entry = await this.waitFor(what, async () => {
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
+ )
609
+ })
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
+ }
618
+ const messages = entry.messages ?? []
619
+ // the 4.x worker answers a bare `failed` from its security gate only (4.2.2 and 4.4 source)
620
+ const gate =
621
+ messages.length === 1 && messages[0] === 'failed'
622
+ ? ': refused by its security policy, which allows installs only with security_level normal or below ' +
623
+ 'AND either ComfyUI listening on localhost or network_mode personal_cloud (the ComfyUI console names the rule)'
624
+ : ''
625
+ throw new InstallFailed(`the Manager reports ${entry.status_str}: ${messages.join(' | ')}${gate}`)
626
+ }
627
+
628
+ /**
629
+ * a worker lingers a few seconds after a drain, then exits; a start in that window answers 201
630
+ * "already running" and leaves the new task pending with no worker (seen live on 4.2.2, same loop
631
+ * in V3 and 4.4). So an idle queue that still holds work is started again.
632
+ */
633
+ private restartIdleQueue = async (api: ManagerApi): Promise<'running' | 'restarted' | 'drained'> => {
634
+ const status = await this.getValid(this.route(api, '/manager/queue/status'), QueueStatus_ark)
635
+ if (status.is_processing) return 'running'
636
+ const waiting = status.pending_count ?? (status.total_count ?? 0) - (status.done_count ?? 0)
637
+ if (waiting <= 0) return 'drained'
638
+ await this.post(this.route(api, '/manager/queue/start'))
639
+ return 'restarted'
640
+ }
641
+
642
+ /** v3, v4 legacy ui: no per item result over http, so wait for the drain and look at the end state */
643
+ private settleByDrain = async (
644
+ api: ManagerApi,
645
+ what: string,
646
+ landed: () => Promise<boolean | null>,
647
+ ): Promise<void> => {
648
+ await this.waitFor(what, async () => ((await this.restartIdleQueue(api)) === 'drained' ? true : null))
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> => {
200
661
  try {
201
- const skip_update = skipUpdate ? '&skip_update=true' : ''
202
- return await this.fetchGetJSON(`/customnode/getlist?mode=${mode}${skip_update}`, ComfyManagerAPIPluginList_ark)
662
+ return await landed()
203
663
  } catch (exception) {
204
- console.error(`node list retrieval failed: ${exception}`)
205
- toastError('node list retrieveal failed')
206
- throw exception
664
+ throw new OutcomeUnknown(`the task ran, but its end state could not be read: ${errorText(exception)}`)
207
665
  }
208
666
  }
209
667
 
210
- installPlugin = async (model: ComfyManagerPluginInfo): Promise<boolean> => {
668
+ private runInstall = async (
669
+ what: string,
670
+ p: {
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>
675
+ },
676
+ ): Promise<InstallOutcome> => {
677
+ const host = this.host.getServerHostHTTP()
211
678
  try {
212
- await this.fetchPost('/customnode/install', model)
213
- console.log('✅ Custom Node installed')
214
- toastSuccess('Custom Node installed')
215
- return true
679
+ const api = await this.api()
680
+ const s = this.strategy(api)
681
+ const uiId = nanoid()
682
+ const sentId = await p.enqueue(api, uiId)
683
+ await this.post(this.route(api, '/manager/queue/start'))
684
+ await s.settle(what, uiId, () => p.landed(s, api), sentId)
685
+ logSuccess(`${what} installed`)
686
+ return 'installed'
216
687
  } catch (exception) {
217
- console.error(`Install failed: ${/*model.title*/ ''} / ${exception}`)
218
- toastError('Custom Node Installation Failed')
219
- 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'
698
+ }
699
+ }
700
+
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
+ */
706
+ private waitFor = async <T>(what: string, check: () => Promise<T | null>): Promise<T> => {
707
+ const deadline = Date.now() + this.timing.installTimeoutMs
708
+ let lastAnswer = Date.now()
709
+ for (;;) {
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
+ }
722
+ if (Date.now() >= deadline)
723
+ throw new OutcomeUnknown(
724
+ `still running after ${this.timing.installTimeoutMs} ms (manager.timing.installTimeoutMs)`,
725
+ )
726
+ await new Promise((resolve) => setTimeout(resolve, this.timing.pollMs))
220
727
  }
221
728
  }
222
729
 
223
730
  // --------------------------------------------------------------
224
- private fetchPost = async <IN, OUT = unknown>(endpoint: string, body: IN, validator?: Type<OUT>): Promise<OUT> => {
225
- const response = await this.host.fetch(endpoint, {
731
+ /** json POST (the Manager's csrf guard refuses simple form types); the reply json, or null when empty */
732
+ private post = async (route: string, body?: unknown): Promise<unknown> => {
733
+ const response = await this.host.fetch(route, {
226
734
  method: 'POST',
227
735
  headers: { 'Content-Type': 'application/json' },
228
- body: JSON.stringify(body),
736
+ body: body === undefined ? undefined : JSON.stringify(body),
229
737
  })
230
- if (!response.ok) throw new Error(`POST ${endpoint} failed: ${response.status} ${response.statusText}`)
231
- const status = await response.json()
232
- if (validator) return softValidate(validator, status)
233
- // wire tolerance (agent/coding.md): unvalidated endpoints return unknown-shaped json
234
- return status as OUT
738
+ const text = await response.text()
739
+ if (!response.ok) throw new Error(`POST ${route} → ${response.status} ${text}`.trim())
740
+ if (text === '') return null
741
+ try {
742
+ return JSON.parse(text)
743
+ } catch {
744
+ return text
745
+ }
235
746
  }
236
747
 
237
- private fetchGetJSON = async <OUT = unknown>(endpoint: string, validator?: Type<OUT>): Promise<OUT> => {
238
- const response = await this.host.fetch(endpoint)
239
- if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`)
748
+ private getJSON = async <OUT = unknown>(route: string, validator?: Type<OUT>): Promise<OUT> => {
749
+ const response = await this.host.fetch(route)
750
+ if (!response.ok) throw new Error(`GET ${route} → ${response.status} ${await response.text()}`.trim())
240
751
  const jsonResult = await response.json()
241
752
  if (validator) return softValidate(validator, jsonResult)
242
753
  // wire tolerance (agent/coding.md): unvalidated endpoints return unknown-shaped json
243
754
  return jsonResult as OUT
244
755
  }
245
756
 
246
- private fetchGetText = async (endopint: string): Promise<string> => {
247
- const response = await this.host.fetch(endopint)
248
- const status = await response.text()
249
- return status
757
+ /** a GET whose shape the decision depends on: a mismatch throws instead of lying */
758
+ private getValid = async <OUT>(route: string, schema: (json: unknown) => OUT | ArkErrors): Promise<OUT> => {
759
+ const res = schema(await this.getJSON(route))
760
+ if (res instanceof type.errors) throw new Error(`GET ${route}: ${res.summary}`)
761
+ return res
250
762
  }
251
763
  }