comfy-native-apps 0.0.0-stage → 1.0.0

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/native_lib.mjs ADDED
@@ -0,0 +1,1562 @@
1
+ // native_lib.mjs — standalone helpers for comfy-native-mcp.
2
+ //
3
+ // Works ONLY on ComfyUI's NATIVE ".app.json" apps — the files the built-in
4
+ // "构建应用 / Build App" feature writes into the workflows directory. It has ZERO
5
+ // dependency on the artokun comfyui-mcp / comfyui-mcp-panel plugin: no panel HTTP
6
+ // routes, no manifest.json app bundles. It reads the .app.json straight off disk
7
+ // and talks to ComfyUI's core HTTP API directly.
8
+ //
9
+ // Because this server does the UI→API conversion itself, it runs identically
10
+ // against a ComfyUI that is headless (--front-end-version=0 / no UI) or one with
11
+ // the web frontend loaded. Only the stable core API is used.
12
+ //
13
+ // A native app file is a UI-format workflow whose whole graph is wrapped in ONE
14
+ // subgraph. The subgraph carries the declared I/O:
15
+ //
16
+ // <…>/workflows/<any path>.app.json
17
+ // definitions.subgraphs[0] = {
18
+ // name, // friendly app name
19
+ // inputNode { id: -10 }, // the exposed-input "port" shell node
20
+ // outputNode { id: -20 }, // the exposed-output "port" shell node
21
+ // inputs[] { id,name,type,label,linkIds }, // EXPOSED INPUTS (the contract)
22
+ // outputs[] { id,name,type,linkIds }, // EXPOSED OUTPUTS
23
+ // nodes[] // the real workflow (CLIPTextEncode, KSampler, …)
24
+ // links[] { id,origin_id,origin_slot,target_id,target_slot,type }
25
+ // }
26
+ //
27
+ // Each exposed input port links to an internal node's widget (usually a Primitive
28
+ // node), so a port tells us exactly which internal node+widget to fill.
29
+
30
+ import fs from 'node:fs';
31
+ import os from 'node:os';
32
+ import path from 'node:path';
33
+
34
+ // --------------------------------------------------------------------------- #
35
+ // Config.
36
+ // --------------------------------------------------------------------------- #
37
+ // COMFYUI_URL is the one address the MCP server uses to reach ComfyUI, e.g.
38
+ // "http://127.0.0.1:8188" or "https://gpu.example.com/comfy". The old
39
+ // COMFYUI_HOST + COMFYUI_PORT pair still works as a fallback.
40
+ const trimSlashes = (u) => String(u).replace(/\/+$/, '');
41
+ export const BASE = trimSlashes(
42
+ process.env.COMFYUI_URL
43
+ ? process.env.COMFYUI_URL
44
+ : `http://${process.env.COMFYUI_HOST ?? '127.0.0.1'}:${process.env.COMFYUI_PORT ?? '8188'}`,
45
+ );
46
+ export const RUN_TIMEOUT_S = Number(process.env.RUN_TIMEOUT_S ?? 300);
47
+
48
+ // --------------------------------------------------------------------------- #
49
+ // App discovery. Native apps live in ComfyUI's user dir, and the server exposes
50
+ // that dir over HTTP (/userdata) — the same API the web frontend uses to list and
51
+ // open workflows. Preferring it keeps the MCP free of local file access: it works
52
+ // against a remote ComfyUI and needs no configured path.
53
+ //
54
+ // The API listing is mirrored into a temp dir so the (synchronous) converter can
55
+ // read apps as files. WORKFLOWS_ROOT stays as an explicit override for setups
56
+ // where /userdata is unavailable.
57
+ // --------------------------------------------------------------------------- #
58
+ const API_WORKFLOWS_DIR = 'workflows';
59
+ const MIRROR_ROOT = path.join(os.tmpdir(), 'comfy-native-apps-mirror');
60
+ const MIRROR_MANIFEST = path.join(MIRROR_ROOT, 'mirror.json');
61
+ const ROOT_CANDIDATES = [
62
+ path.join(os.homedir(), 'AppData', 'Local', 'Programs', 'ComfyUI', 'resources', 'ComfyUI', 'user'),
63
+ path.join(os.homedir(), 'Documents', 'ComfyUI', 'user'),
64
+ path.join(os.homedir(), 'ComfyUI', 'user'),
65
+ ];
66
+ // A mirror written against a different server must not be trusted.
67
+ function mirrorUsable() {
68
+ try { return JSON.parse(fs.readFileSync(MIRROR_MANIFEST, 'utf8')).base === BASE; } catch { return false; }
69
+ }
70
+ export function resolveWorkflowsRoot() {
71
+ if (process.env.WORKFLOWS_ROOT) return process.env.WORKFLOWS_ROOT;
72
+ if (mirrorUsable()) return MIRROR_ROOT;
73
+ for (const c of ROOT_CANDIDATES) if (fs.existsSync(c)) return c;
74
+ return ROOT_CANDIDATES[0];
75
+ }
76
+
77
+ // Mirror <server>/userdata/workflows/**/*.app.json into MIRROR_ROOT. Returns the
78
+ // app count, or null when the server does not serve /userdata (older build, or an
79
+ // unreachable server) so callers can fall back to local discovery.
80
+ export async function refreshApps({ maxAgeMs = 2000 } = {}) {
81
+ // An explicit local root means the caller wants those files, not the server's.
82
+ if (process.env.WORKFLOWS_ROOT) return null;
83
+ const now = Date.now();
84
+ if (maxAgeMs && refreshApps.cache && now - refreshApps.cache.at < maxAgeMs) return refreshApps.cache.value;
85
+ const value = await mirrorApps();
86
+ refreshApps.cache = { at: now, value };
87
+ return value;
88
+ }
89
+
90
+ async function mirrorApps() {
91
+ const listUrl = `${BASE}/userdata?dir=${API_WORKFLOWS_DIR}&recurse=true&full_info=true`;
92
+ let listed;
93
+ try {
94
+ const r = await fetch(listUrl, { signal: AbortSignal.timeout(5000) });
95
+ if (!r.ok) return null;
96
+ listed = await r.json();
97
+ } catch {
98
+ return null;
99
+ }
100
+ if (!Array.isArray(listed)) return null;
101
+ const wanted = listed.filter((e) => e && /\.app\.json$/i.test(String(e.path ?? '')));
102
+
103
+ let previous = {};
104
+ try { previous = JSON.parse(fs.readFileSync(MIRROR_MANIFEST, 'utf8')).files ?? {}; } catch { /* first run */ }
105
+
106
+ const files = {};
107
+ for (const e of wanted) {
108
+ const rel = String(e.path);
109
+ files[rel] = { size: e.size, modified: e.modified };
110
+ const dest = path.join(MIRROR_ROOT, API_WORKFLOWS_DIR, ...rel.split('/'));
111
+ const prev = previous[rel];
112
+ if (prev && prev.size === e.size && prev.modified === e.modified && fs.existsSync(dest)) continue;
113
+ try {
114
+ // The file route resolves against the user root, so keep the workflows/ prefix.
115
+ const r = await fetch(`${BASE}/userdata/${encodeURIComponent(`${API_WORKFLOWS_DIR}/${rel}`)}`, { signal: AbortSignal.timeout(30000) });
116
+ if (!r.ok) return null;
117
+ const json = await r.json();
118
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
119
+ fs.writeFileSync(dest, JSON.stringify(json));
120
+ } catch {
121
+ return null;
122
+ }
123
+ }
124
+ // Drop apps that no longer exist on the server.
125
+ for (const rel of Object.keys(previous)) {
126
+ if (files[rel]) continue;
127
+ try { fs.rmSync(path.join(MIRROR_ROOT, API_WORKFLOWS_DIR, ...rel.split('/'))); } catch { /* already gone */ }
128
+ }
129
+ fs.mkdirSync(MIRROR_ROOT, { recursive: true });
130
+ fs.writeFileSync(MIRROR_MANIFEST, JSON.stringify({ base: BASE, at: Date.now(), files }));
131
+ return wanted.length;
132
+ }
133
+
134
+ // Recursively collect every workflows/**\/*.app.json under the user root (apps may
135
+ // sit in nested subfolders like NSFW/文生图/…). Sorted for a stable numbering.
136
+ export function findNativeApps(root) {
137
+ const out = [];
138
+ const walk = (dir) => {
139
+ let ents;
140
+ try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
141
+ for (const e of ents) {
142
+ const p = path.join(dir, e.name);
143
+ if (e.isDirectory()) walk(p);
144
+ else if (/\.app\.json$/i.test(e.name)) out.push(p);
145
+ }
146
+ };
147
+ walk(root);
148
+ return out.sort();
149
+ }
150
+
151
+ // --------------------------------------------------------------------------- #
152
+ // Media ports. An IMAGE/MASK/VIDEO/AUDIO port carries a *file*, and the file is
153
+ // owned by a top-level loader node outside the subgraph (the app author wires a
154
+ // LoadImage into the subgraph reference node). Writing the filename onto the
155
+ // IMAGE socket inside the subgraph hands a string to a node that expects a
156
+ // tensor, so media values are routed to the loader widget instead.
157
+ // --------------------------------------------------------------------------- #
158
+ const MEDIA_TYPES = new Set(['IMAGE', 'MASK', 'VIDEO', 'AUDIO']);
159
+ const MEDIA_OVERRIDE_PREFIX = '@media:';
160
+ const LOADER_WIDGETS = {
161
+ LoadImage: 'image',
162
+ LoadImageMask: 'image',
163
+ LoadVideo: 'file',
164
+ LoadAudio: 'audio',
165
+ VHS_LoadVideo: 'video',
166
+ VHS_LoadAudio: 'audio',
167
+ };
168
+ const loaderWidgetOf = (n) => {
169
+ if (!n) return null;
170
+ if (LOADER_WIDGETS[n.type]) return LOADER_WIDGETS[n.type];
171
+ // LoadImageOutput reads the OUTPUT dir, not the input dir an upload lands in.
172
+ if (n.type === 'LoadImageOutput' || !/Load/i.test(String(n.type ?? ''))) return null;
173
+ const w = (n.inputs ?? []).find((i) => i.widget && ['image', 'file', 'audio', 'video'].includes(i.name));
174
+ return w ? w.name : null;
175
+ };
176
+
177
+ // Frontend-only node types. They draw UI on the canvas (notes, reroutes, the
178
+ // primitive-widget node) but have NO backend class_type — the web frontend strips
179
+ // them right before submitting. If one reaches /prompt, ComfyUI rejects the WHOLE
180
+ // job with `missing_node_type` ("Node 'Note' not found"). Skip them when converting.
181
+ const FRONTEND_ONLY_NODE_TYPES = new Set(['Note', 'MarkdownNote', 'Reroute', 'PrimitiveNode']);
182
+ const isFrontendOnly = (n) => !!n && FRONTEND_ONLY_NODE_TYPES.has(String(n.type));
183
+
184
+ // --------------------------------------------------------------------------- #
185
+ // Load a native app: extract the subgraph, its ports, and a link/node index.
186
+ // --------------------------------------------------------------------------- #
187
+ export function loadNativeApp(file) {
188
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
189
+ const sg = raw.definitions?.subgraphs?.[0] ?? null;
190
+ // A native app always wraps its graph in a subgraph. The one exception is a
191
+ // purely-linear app (frontend "linear" layout): subgraphs absent, but
192
+ // extra.linearMode + non-empty extra.linearData.inputs declare the whole
193
+ // TOP-LEVEL graph as its parameter surface, so the app is still a native app.
194
+ const linearOnly = !sg
195
+ && raw.extra?.linearMode === true
196
+ && Array.isArray(raw.extra?.linearData?.inputs)
197
+ && raw.extra?.linearData?.inputs.length > 0;
198
+ if (!sg && !linearOnly) throw new Error(`not a native app (no subgraph and no linear data): ${file}`);
199
+
200
+ const nodesById = new Map((sg?.nodes ?? []).map((n) => [n.id, n]));
201
+ const linksById = new Map((sg?.links ?? []).map((l) => [l.id, l]));
202
+
203
+ // Top-level graph: the subgraph REFERENCE node plus the output/saver nodes the
204
+ // app author left outside the subgraph (SaveImage, VHS_VideoCombine, SaveVideo,
205
+ // PrimitiveFloat feeding frame_rate, …). The top-level links use the compact
206
+ // UI array form [id, origin_id, origin_slot, target_id, target_slot, type].
207
+ const topNodes = raw.nodes ?? [];
208
+ const topLinks = (raw.links ?? []).map((l) => Array.isArray(l)
209
+ ? { id: l[0], origin_id: l[1], origin_slot: l[2], target_id: l[3], target_slot: l[4], type: l[5] }
210
+ : l);
211
+ const topById = new Map(topNodes.map((n) => [n.id, n]));
212
+ const topLinksById = new Map(topLinks.map((l) => [l.id, l]));
213
+ const shellIn = sg?.inputNode?.id ?? -10;
214
+ const nestedIds = new Set((raw.definitions?.subgraphs ?? []).map((s) => s.id));
215
+
216
+ // The subgraph REFERENCE node (top-level node whose type is the subgraph's id)
217
+ // holds the app's actual I/O values in its widgets, keyed by PORT NAME. This is
218
+ // the authoritative value for each exposed input port — the internal node's own
219
+ // widget (e.g. a UNETLoader's template default) may be stale/different.
220
+ const refNode = sg ? (raw.nodes ?? []).find((n) => n.type === sg.id) : null;
221
+ const portValues = refNode?.widgets_values_named ?? {};
222
+ const refInputs = refNode?.inputs ?? [];
223
+
224
+ // A bypassed node (mode 4) is absent from the API prompt: ComfyUI forwards an
225
+ // input of the same type to its output. Resolve such a link to the real source.
226
+ const resolveOrigin = (originId, originSlot) => {
227
+ const seen = new Set();
228
+ let id = originId;
229
+ let slot = originSlot;
230
+ for (;;) {
231
+ const n = topById.get(id);
232
+ if (!n || n.mode !== 4) return { nodeId: id, slot };
233
+ if (seen.has(id)) return null;
234
+ seen.add(id);
235
+ const outType = n.outputs?.[slot]?.type;
236
+ const idx = (n.inputs ?? []).findIndex((i) => i.type === outType && i.link != null);
237
+ const inLink = idx >= 0 ? topLinksById.get(n.inputs[idx].link) : undefined;
238
+ if (!inLink || inLink.origin_id === refNode?.id) return null;
239
+ id = inLink.origin_id;
240
+ slot = inLink.origin_slot;
241
+ }
242
+ };
243
+ const upstreamOf = (id) => {
244
+ const out = [];
245
+ for (const l of topLinks) {
246
+ if (l.target_id !== id || l.origin_id === refNode?.id) continue;
247
+ const src = resolveOrigin(l.origin_id, l.origin_slot);
248
+ if (src) out.push(src.nodeId);
249
+ }
250
+ return out;
251
+ };
252
+
253
+ // Follow a media port out of the subgraph: the port's shell link names the ref
254
+ // node input slot, whose top-level link is the feed (e.g. LoadImage #140, or
255
+ // Canny #57 fed by LoadImage #58). Returns the feed output, every top-level
256
+ // node needed to produce it, and the nearest upstream loader that owns the
257
+ // filename widget.
258
+ const mediaFeed = (p) => {
259
+ const shellLink = (p.linkIds ?? []).map((id) => linksById.get(id)).find((l) => l && l.origin_id === shellIn);
260
+ const refInput = (shellLink ? refInputs[shellLink.origin_slot] : null) ?? refInputs.find((i) => i.name === p.name);
261
+ const topLink = refInput?.link != null ? topLinksById.get(refInput.link) : undefined;
262
+ if (!topLink) return { feed: null, chain: [], loader: null };
263
+ const feed = resolveOrigin(topLink.origin_id, topLink.origin_slot);
264
+ if (!feed) return { feed: null, chain: [], loader: null };
265
+
266
+ const chain = new Set();
267
+ const queue = [feed.nodeId];
268
+ while (queue.length) {
269
+ const id = queue.shift();
270
+ const n = topById.get(id);
271
+ if (!n || chain.has(id) || (n.mode != null && n.mode !== 0) || nestedIds.has(n.type)) continue;
272
+ chain.add(id);
273
+ for (const src of upstreamOf(id)) queue.push(src);
274
+ }
275
+ // A feed through a nested subgraph cannot be expressed in an API prompt; fall
276
+ // back to the no-feed path rather than link to a node that will not exist.
277
+ if (!chain.has(feed.nodeId)) return { feed: null, chain: [], loader: null };
278
+
279
+ let loader = null;
280
+ const seen = new Set();
281
+ queue.push(feed.nodeId);
282
+ while (queue.length && !loader) {
283
+ const id = queue.shift();
284
+ if (seen.has(id)) continue;
285
+ seen.add(id);
286
+ const n = topById.get(id);
287
+ if (!n) continue;
288
+ const widget = loaderWidgetOf(n);
289
+ if (widget) loader = { nodeId: id, widget };
290
+ else for (const src of upstreamOf(id)) queue.push(src);
291
+ }
292
+ return { feed, chain: [...chain], loader };
293
+ };
294
+
295
+ // Display-only nodes: they draw a widget or an image on the canvas for a human
296
+ // to look at, but produce no value the workflow uses. If an author exposes one
297
+ // as an input port (a "prompt preview" / "resolution preview"), it is scaffolding,
298
+ // not a parameter — dropping it keeps get_app_params clean. A port is dropped
299
+ // only when ALL of its targets are display-only, so a real node that happens to
300
+ // feed a preview alongside it is never mistaken for one.
301
+ const DISPLAY_NODE_TYPES = new Set(['PreviewAny', 'PreviewImage', 'PreviewText', 'ShowText', 'Debug']);
302
+
303
+ // Exposed INPUT ports. A port's link lands on an internal node's widget — that
304
+ // (node, widget) pair is exactly where the model's value must go.
305
+ const buildShellInput = (p) => {
306
+ const link = p.linkIds?.[0] != null ? linksById.get(p.linkIds[0]) : undefined;
307
+ const target = link ? nodesById.get(link.target_id) : undefined;
308
+ const socket = target?.inputs?.[link.target_slot]?.name ?? null;
309
+ const named = target?.widgets_values_named ?? {};
310
+ // One port can fan out to several internal widgets; every one needs the value.
311
+ const targets = [];
312
+ for (const lid of p.linkIds ?? []) {
313
+ const l = linksById.get(lid);
314
+ const s = l ? nodesById.get(l.target_id)?.inputs?.[l.target_slot]?.name : undefined;
315
+ if (s) targets.push({ nodeId: l.target_id, socket: s });
316
+ }
317
+ const media = MEDIA_TYPES.has(p.type);
318
+ const ext = media ? mediaFeed(p) : null;
319
+ return {
320
+ portId: p.id,
321
+ portName: p.name,
322
+ label: p.label ?? p.name,
323
+ type: p.type,
324
+ targets,
325
+ default: p.name in portValues ? portValues[p.name] : (socket && socket in named ? named[socket] : null),
326
+ ...(ext ? { media: true, feed: ext.feed, chain: ext.chain, loader: ext.loader } : {}),
327
+ };
328
+ };
329
+ const shellInputs = (sg?.inputs ?? [])
330
+ .filter((p) => !(p.linkIds ?? []).length || (p.linkIds ?? []).some((lid) => {
331
+ const l = linksById.get(lid);
332
+ const n = l ? nodesById.get(l.target_id) : undefined;
333
+ return n && !DISPLAY_NODE_TYPES.has(n.type);
334
+ }))
335
+ .map(buildShellInput);
336
+ // The EXPOSED port surface. In a linearMode app (extra.linearData.inputs) the
337
+ // author hand-picks the parameters, one entry per ["<uuid>:<nodeId>:<socket>",
338
+ // label]. Those subgraph shell ports that are NOT picked (e.g. a nested
339
+ // subgraph's seed/sampler/scheduler/denoise/...) are exactly what the linear
340
+ // frontend hides — so they must not appear here either. `shellInputs` (the full
341
+ // derived list) is kept separately for graphToPrompt's media-link machinery.
342
+ // For a linearOnly app there is no subgraph: the linearData entries ARE the
343
+ // whole surface, every one being a port on a plain top-level node.
344
+ let inputs = shellInputs;
345
+ const ld = raw.extra?.linearData;
346
+ if (ld?.inputs?.length && (refNode || linearOnly)) {
347
+ const shellByName = new Map((sg?.inputs ?? []).map((p) => [p.name, p]));
348
+ const used = new Set();
349
+ // A linearMode port's NAME is whatever the frontend renders on the canvas: the
350
+ // TARGET socket's `label ?? localized_name ?? socket name`. The linearData
351
+ // second element is only a short key ("image", "value", "aspect_ratio", …),
352
+ // so it is kept as an ALIAS for existing run_app callers instead of the label.
353
+ const displayName = (node, socketName) => {
354
+ const s = (node.inputs ?? []).find((i) => i.name === socketName);
355
+ return s ? (s.label ?? s.localized_name ?? s.name) : socketName;
356
+ };
357
+ const linearInputs = [];
358
+ for (const [rawRef, rawLabel, rawMeta] of ld.inputs) {
359
+ const parts = String(rawRef).split(':');
360
+ const nodeId = Number(parts[1]);
361
+ let socket = parts.slice(2).join(':');
362
+ try { socket = decodeURIComponent(socket); } catch { /* keep verbatim */ }
363
+ const n = topById.get(nodeId);
364
+ if (!Number.isInteger(nodeId) || !socket || !n) continue;
365
+ let label = displayName(nodeId === refNode?.id ? refNode : n, socket);
366
+ if (used.has(label)) {
367
+ let i = 2;
368
+ while (used.has(`${label} (${i})`)) i++;
369
+ label = `${label} (${i})`;
370
+ }
371
+ used.add(label);
372
+ const oldLabel = rawLabel != null ? String(rawLabel) : socket;
373
+ if (!linearOnly && nodeId === refNode.id) {
374
+ // A socket on the main subgraph REF node = a subgraph input port. Adopt the
375
+ // matching shell port wholesale so its internal targets, media feed and
376
+ // default keep working (e.g. a ref-node scalar port, a `loras.*` port, or the
377
+ // media feed that ends at the ref's image input).
378
+ const sp = shellByName.get(socket);
379
+ if (!sp) continue;
380
+ const p = buildShellInput(sp);
381
+ p.label = label;
382
+ const old = sp.label ?? sp.name;
383
+ p.aliases = [...new Set([oldLabel, sp.name, old, socket])].filter((x) => x && x !== label);
384
+ if (rawMeta?.description) p.description = rawMeta.description;
385
+ linearInputs.push(p);
386
+ continue;
387
+ }
388
+ // A socket on a PLAIN top-level node (camera/encoder/sampler/loader/...).
389
+ const sock = (n.inputs ?? []).find((i) => i.name === socket) ?? null;
390
+ const loadW = loaderWidgetOf(n);
391
+ const media = !!loadW;
392
+ const port = {
393
+ portId: `@lin:${nodeId}:${socket}`,
394
+ portName: socket,
395
+ label,
396
+ // Old linearData key and the raw socket name remain valid run_app keys.
397
+ aliases: [...new Set([oldLabel, socket])].filter((a) => a && a !== label),
398
+ type: media ? (n.outputs?.[0]?.type ?? 'IMAGE') : (sock?.type ?? 'STRING'),
399
+ targets: [],
400
+ // Media values are filenames for the loader widget, never a socket default.
401
+ default: media ? undefined : (sock?.widget ? (n.widgets_values_named?.[socket] ?? null) : null),
402
+ // Routes run_app values to the TOP-LEVEL node's widget (`@top:<nodeId>:<socket>`).
403
+ linear: { nodeId, socket },
404
+ };
405
+ if (rawMeta?.description) port.description = rawMeta.description;
406
+ if (media) {
407
+ port.media = true;
408
+ port.feed = { nodeId, slot: 0 };
409
+ port.chain = [nodeId];
410
+ port.loader = { nodeId, widget: loadW };
411
+ }
412
+ linearInputs.push(port);
413
+ }
414
+ if (linearInputs.length) inputs = linearInputs;
415
+ }
416
+
417
+ // Pre-populated overrides: each port's real value (from the ref node) applied to
418
+ // the internal node+socket it feeds. User run_app values layer on top of these.
419
+ // A port can fan out to several nodes (e.g. one "channel" string driving two
420
+ // Branch nodes), so every link of the port must receive the value — the others
421
+ // would otherwise fall back to their own stale saved widget.
422
+ const portOverrides = new Map();
423
+ for (const p of sg?.inputs ?? []) {
424
+ // Media ports never take a literal from the ref node widget: their value is a
425
+ // filename owned by the top-level loader (see mediaFeed above).
426
+ if (MEDIA_TYPES.has(p.type)) continue;
427
+ if (!(p.name in portValues)) continue;
428
+ // If the ref node's socket feeding this port is itself LINKED to a top-level
429
+ // computed node (resolution switch, controlnet-channel branch, …), the saved
430
+ // widget is a stale fallback — the real value is the top-level link. Skip the
431
+ // literal so the converter resolves the link instead (a stale 0 here is what
432
+ // made the output latent 0x0 and crashed the control-image encode with a
433
+ // division by zero).
434
+ const shellLink = (p.linkIds ?? []).map((id) => linksById.get(id)).find((l) => l && l.origin_id === shellIn);
435
+ if (shellLink && refNode?.inputs?.[shellLink.origin_slot]?.link != null) continue;
436
+ for (const lid of p.linkIds ?? []) {
437
+ const link = linksById.get(lid);
438
+ if (!link) continue;
439
+ const socket = nodesById.get(link.target_id)?.inputs?.[link.target_slot]?.name;
440
+ if (socket) portOverrides.set(`${link.target_id}:${socket}`, portValues[p.name]);
441
+ }
442
+ }
443
+
444
+ // Exposed OUTPUT ports. A subgraph app's port is fed BY an internal node —
445
+ // record that producer (node, slot) so graphToPrompt can attach a synthetic
446
+ // saver when the app has no real top-level sink. A linear-layout app has no
447
+ // subgraph output ports: infer its outputs from the top-level sink nodes
448
+ // instead (SaveImage -> IMAGE, MeshToFile3D -> MESH, …), so the catalog and
449
+ // get_app_params still advertise what the app produces.
450
+ //
451
+ // Inferred sinks keep producerNodeId null: the real sink IS already converted
452
+ // as a top-level node, and a synthetic saver on top of it would double-save.
453
+ const SINK_TYPE_HINTS = {
454
+ VHS_VideoCombine: 'VIDEO', SaveAnimatedWEBM: 'ANIMATED', SaveAnimatedPNG: 'ANIMATED',
455
+ SaveImage: 'IMAGE', SaveImageAdvanced: 'IMAGE',
456
+ SaveAudio: 'AUDIO', SaveAudioMP3: 'AUDIO', SaveAudioOpus: 'AUDIO',
457
+ PreviewImage: 'IMAGE', PreviewAny: 'any', Preview3DAdvanced: 'MESH',
458
+ Save3DAdvanced: 'MESH', MeshToFile3D: 'MESH',
459
+ };
460
+ const SINK_NODE_RE = /^(VHS_VideoCombine|Save(Image|ImageAdvanced|Video|Audio|AudioMP3|AudioOpus|AnimatedWEBM|AnimatedPNG|3DAdvanced)|Preview(Image|Any|3DAdvanced)|MeshToFile3D|.*(Export|ToFile).*)/i;
461
+ const topSinkOutputs = () => {
462
+ const seen = new Map();
463
+ for (const n of topNodes) {
464
+ if (!(n.mode == null || n.mode === 0)) continue;
465
+ if (!SINK_NODE_RE.test(String(n.type ?? ''))) continue;
466
+ const sock = (n.inputs ?? []).find((i) => !/^(STRING|INT|FLOAT|BOOLEAN|COMBO|LATENT)$/i.test(String(i.type ?? '')));
467
+ const type = SINK_TYPE_HINTS[n.type] ?? sock?.type ?? 'IMAGE';
468
+ if (!seen.has(type)) seen.set(type, { name: type, type, producerNodeId: null, producerSlot: 0 });
469
+ }
470
+ return [...seen.values()];
471
+ };
472
+ const outputs = sg
473
+ ? (sg.outputs ?? []).map((p) => {
474
+ const link = p.linkIds?.[0] != null ? linksById.get(p.linkIds[0]) : undefined;
475
+ const producer = link ? nodesById.get(link.origin_id) : undefined;
476
+ return {
477
+ name: p.label ?? p.localized_name ?? p.name,
478
+ type: p.type,
479
+ producerNodeId: producer ? producer.id : null,
480
+ producerSlot: producer ? link.origin_slot : 0,
481
+ producerType: producer ? producer.type : null,
482
+ };
483
+ })
484
+ : topSinkOutputs();
485
+
486
+ return {
487
+ file,
488
+ id: path.relative(resolveWorkflowsRoot(), file).replace(/\.app\.json$/i, '').replace(/\\/g, '/'),
489
+ name: sg?.name ?? path.basename(file, '.app.json'),
490
+ description: raw.extra?.description ?? '',
491
+ shellIn,
492
+ refNodeId: refNode ? refNode.id : null,
493
+ // Ids of every subgraph defined in the file. A top-level node whose type is
494
+ // one of these is a NESTED subgraph reference: it cannot be sent to the API
495
+ // as-is (its class_type would be a UUID), so the converter inlines it
496
+ // (graphToPrompt) instead of sending a UUID class_type.
497
+ subgraphIds: [...nestedIds],
498
+ subgraphs: raw.definitions?.subgraphs ?? [],
499
+ // True when the app was built in the frontend's "linear" layout: no subgraph,
500
+ // the whole top-level graph is the app and extra.linearData lists its ports.
501
+ linearOnly: !!linearOnly,
502
+ nodesById,
503
+ linksById,
504
+ topNodes,
505
+ topLinks,
506
+ topById,
507
+ inputs,
508
+ // Full derived input-port list (all subgraph shell ports). `inputs` may be a
509
+ // smaller, linearData-picked surface; graphToPrompt consults shellInputs for
510
+ // the media-link wiring that keeps feeds flowing even for non-exposed ports.
511
+ shellInputs,
512
+ outputs,
513
+ portValues,
514
+ portOverrides,
515
+ };
516
+ }
517
+
518
+ // --------------------------------------------------------------------------- #
519
+ // UI → API conversion.
520
+ // --------------------------------------------------------------------------- #
521
+ // ComfyUI's web frontend expands %date:FORMAT% style tokens in filename prefixes
522
+ // right before submitting the prompt; the raw API does not. Without expanding them
523
+ // yourself, a workflow like VHS_VideoCombine's
524
+ // "%date:yyyy-MM-dd%/%date:yyyyMMdd_hhmmss%_Wan2.2" makes the backend mkdir a
525
+ // literal "%date:yyyy-MM-dd%" folder and fail with WinError 267.
526
+ const pad2 = (n, w = 2) => String(n).padStart(w, '0');
527
+ function formatDateTokens(date, fmt) {
528
+ const h24 = date.getHours();
529
+ const h12 = h24 % 12 || 12;
530
+ const map = {
531
+ yyyy: String(date.getFullYear()),
532
+ yy: pad2(date.getFullYear() % 100),
533
+ fff: pad2(date.getMilliseconds(), 3),
534
+ MM: pad2(date.getMonth() + 1),
535
+ M: String(date.getMonth() + 1),
536
+ dd: pad2(date.getDate()),
537
+ d: String(date.getDate()),
538
+ HH: pad2(h24),
539
+ H: String(h24),
540
+ hh: pad2(h12),
541
+ h: String(h12),
542
+ mm: pad2(date.getMinutes()),
543
+ m: String(date.getMinutes()),
544
+ ss: pad2(date.getSeconds()),
545
+ s: String(date.getSeconds()),
546
+ };
547
+ return fmt.replace(/yyyy|yy|fff|MM|M|dd|d|HH|H|hh|h|mm|m|ss|s/g, (t) => map[t]);
548
+ }
549
+ export function expandFilenameTokens(value) {
550
+ if (typeof value !== 'string' || !value.includes('%')) return value;
551
+ const now = new Date();
552
+ const out = value
553
+ .replace(/%date:([^%]+)%/g, (_, f) => formatDateTokens(now, f))
554
+ .replace(/%date%/g, formatDateTokens(now, 'yyyy-MM-dd'))
555
+ .replace(/%time%/g, formatDateTokens(now, 'HHmmss'))
556
+ .replace(/%year%/g, String(now.getFullYear()))
557
+ .replace(/%month%/g, pad2(now.getMonth() + 1))
558
+ .replace(/%day%/g, pad2(now.getDate()))
559
+ .replace(/%hour%/g, pad2(now.getHours()))
560
+ .replace(/%minute%/g, pad2(now.getMinutes()))
561
+ .replace(/%second%/g, pad2(now.getSeconds()));
562
+ // Anything still token-shaped would be an unknown token (e.g. %width%, %seed%):
563
+ // drop it rather than let it produce an invalid path on the backend.
564
+ return out.replace(/%[^%]*%/g, '');
565
+ }
566
+
567
+ // Build a { "<nodeId>": { class_type, inputs } } prompt from the subgraph.
568
+ // `overrides` is a Map keyed `${nodeId}:${socketName}` → literal value (the model's
569
+ // filled-in params). Rules per input socket:
570
+ // • override present -> the literal value
571
+ // • linked from a REAL internal node -> [origin_id, origin_slot]
572
+ // • linked from the inputNode shell (-10) -> an exposed-input port socket
573
+ // -> named default (no override)
574
+ // • not linked (plain widget) -> named default
575
+ // Plus any widget present in widgets_values_named that is not a socket
576
+ // (e.g. KSampler's "control_after_generate") is appended so the prompt is complete.
577
+ // A list widget value (e.g. BranchNode's `branch_names`, an ARRAY rendered as a
578
+ // widget) must not reach the API prompt as a bare list: the server reads any list
579
+ // as a [node_id, slot] link and rejects it with bad_linked_input. Execution
580
+ // unwraps `{"__value__": [...]}` back to the list, which is the only accepted shape.
581
+ const asWidgetValue = (v) => (Array.isArray(v) ? { __value__: v } : v);
582
+
583
+ export function graphToPrompt(app, overrides) {
584
+ const { nodesById, linksById, shellIn } = app;
585
+ // Port values (from the subgraph ref node) are the baseline; user overrides win.
586
+ // Media overrides arrive as `@media:<portId>` and are routed below, not applied
587
+ // as literals: their value is a filename for a loader, never an IMAGE socket.
588
+ const eff = new Map(app.portOverrides ?? []);
589
+ const mediaValues = new Map();
590
+ // Top-level widget overrides (`@top:<nodeId>:<socket>`, set by buildOverrides for
591
+ // linearData ports): keyed by TOP-LEVEL node id so the value lands on the widget
592
+ // of the emitted node (the node namespace differs from the subgraph's interior).
593
+ const TOP_OVERRIDE_RE = /^@top:(\d+):(.+)$/;
594
+ const topWidgetOverrides = new Map();
595
+ const topOverrideNodes = new Set();
596
+ for (const [k, v] of overrides ?? []) {
597
+ if (k.startsWith('@top:')) {
598
+ const m = TOP_OVERRIDE_RE.exec(k);
599
+ if (m) {
600
+ const nid = Number(m[1]);
601
+ let map = topWidgetOverrides.get(nid);
602
+ if (!map) topWidgetOverrides.set(nid, (map = new Map()));
603
+ map.set(m[2], v);
604
+ topOverrideNodes.add(nid);
605
+ }
606
+ } else if (k.startsWith(MEDIA_OVERRIDE_PREFIX)) mediaValues.set(k.slice(MEDIA_OVERRIDE_PREFIX.length), v);
607
+ else eff.set(k, v);
608
+ }
609
+ // Top-level node ids live in a different namespace than the subgraph's internal
610
+ // ids even in the UI, so prefix them to guarantee no key collision in the API prompt.
611
+ const topKey = (id) => `t${id}`;
612
+
613
+ // Media ports: internal consumers link to the top-level feed (or a synthetic
614
+ // LoadImage); a supplied filename goes on the loader's widget. Ports fed from
615
+ // outside keep working with their saved image even when no value is supplied.
616
+ const mediaLinks = new Map();
617
+ const feedReach = new Set();
618
+ const syntheticLoads = [];
619
+ let synthLoadId = 999100;
620
+ // Iterate both the exposed input ports AND the full shell list: a linearData
621
+ // media port (e.g. a loader's `image`) carries the filename for the same loader
622
+ // node that the hidden shell port (e.g. a control-image input) routes to its
623
+ // internal consumers. Skipping either side would orphan the feed or the consumer link.
624
+ const mediaPorts = [];
625
+ {
626
+ const seen = new Set();
627
+ for (const p of [...(app.shellInputs ?? []), ...app.inputs]) {
628
+ if (!p.media || seen.has(p.portId)) continue;
629
+ seen.add(p.portId);
630
+ mediaPorts.push(p);
631
+ }
632
+ }
633
+ for (const p of mediaPorts) {
634
+ if (!p.media) continue;
635
+ const value = mediaValues.get(p.portId);
636
+ let target = p.feed;
637
+ let synthetic = false;
638
+ if (value !== undefined) {
639
+ if (p.loader) {
640
+ let m = topWidgetOverrides.get(p.loader.nodeId);
641
+ if (!m) topWidgetOverrides.set(p.loader.nodeId, (m = new Map()));
642
+ m.set(p.loader.widget, String(value));
643
+ } else {
644
+ const type = p.type === 'AUDIO' ? 'LoadAudio' : p.type === 'VIDEO' ? 'LoadVideo' : 'LoadImage';
645
+ const widget = p.type === 'AUDIO' ? 'audio' : p.type === 'VIDEO' ? 'file' : 'image';
646
+ const id = ++synthLoadId;
647
+ syntheticLoads.push({ id, type, widget, value: String(value) });
648
+ target = { nodeId: id, slot: p.type === 'MASK' ? 1 : 0 };
649
+ synthetic = true;
650
+ }
651
+ }
652
+ if (!target) continue;
653
+ if (!synthetic) for (const id of p.chain ?? []) feedReach.add(id);
654
+ const linkId = synthetic ? String(target.nodeId) : topKey(target.nodeId);
655
+ for (const t of p.targets ?? []) mediaLinks.set(`${t.nodeId}:${t.socket}`, [linkId, target.slot]);
656
+ }
657
+ const prompt = {};
658
+ for (const s of syntheticLoads) prompt[s.id] = { class_type: s.type, inputs: { [s.widget]: s.value } };
659
+ // The main subgraph's internal nodes are converted below, after the top-level
660
+ // mechanism (resolveTopSource / inlineNested) is defined: a socket linked from the
661
+ // inputNode shell may itself be fed by a top-level node (a ComfySwitchNode picking
662
+ // the output resolution, a BranchNode for the controlnet channel, …), and that
663
+ // top-level link must be resolved rather than falling back to the stale saved widget.
664
+
665
+ // ------------------------------------------------------------------------- #
666
+ // Top-level output chain (THIS is what actually writes the file).
667
+ //
668
+ // A native app keeps only the model graph inside the subgraph; the node that
669
+ // saves the result (SaveImage / SaveImageAdvanced / VHS_VideoCombine /
670
+ // SaveVideo / SaveAnimatedWEBM / …) stays at the TOP level, fed by the
671
+ // subgraph reference node's outputs. Converting only the subgraph therefore
672
+ // never runs that saver: image-to-video apps used to come back as 48 loose
673
+ // PNG frames (and only the first one reached the model) instead of an .mp4.
674
+ // So convert every top-level node reachable from a subgraph output as well.
675
+ // ------------------------------------------------------------------------- #
676
+ const refId = app.refNodeId ?? null;
677
+ const topNodes = app.topNodes ?? [];
678
+ const topLinks = app.topLinks ?? [];
679
+ const topById = new Map(topNodes.map((n) => [n.id, n]));
680
+ const topLinksById = new Map(topLinks.map((l) => [l.id, l]));
681
+ const nestedIds = new Set(app.subgraphIds ?? []);
682
+ const refNode = refId != null ? topById.get(refId) : null;
683
+ // Bypassed nodes (mode 4) never reach the API prompt; follow their same-type
684
+ // input to the real source so a consumer still gets a valid link.
685
+ const resolveOrigin = (originId, originSlot) => {
686
+ const seen = new Set();
687
+ let id = originId;
688
+ let slot = originSlot;
689
+ for (;;) {
690
+ const n = topById.get(id);
691
+ if (!n || n.mode !== 4) return { nodeId: id, slot };
692
+ if (seen.has(id)) return null;
693
+ seen.add(id);
694
+ const outType = n.outputs?.[slot]?.type;
695
+ const idx = (n.inputs ?? []).findIndex((i) => i.type === outType && i.link != null);
696
+ const inLink = idx >= 0 ? topLinksById.get(n.inputs[idx].link) : undefined;
697
+ if (!inLink || inLink.origin_id === refId) return null;
698
+ id = inLink.origin_id;
699
+ slot = inLink.origin_slot;
700
+ }
701
+ };
702
+ // Only "always" nodes are converted. A node whose type is a subgraph UUID is a
703
+ // nested subgraph reference — the API can't execute it, so the chain stops here
704
+ // (the output falls back to a synthetic saver instead of an invalid prompt).
705
+ const isActive = (n) => !!n && (n.mode === undefined || n.mode === null || n.mode === 0) && !nestedIds.has(n.type);
706
+
707
+ // Nodes downstream of one specific subgraph output port (index = ref output slot).
708
+ const reachFromSlot = (slot) => {
709
+ const reach = new Set();
710
+ if (refId == null) return reach;
711
+ const queue = [];
712
+ const pushTarget = (l) => {
713
+ const t = topById.get(l.target_id);
714
+ if (!t || !isActive(t) || reach.has(l.target_id)) return;
715
+ reach.add(l.target_id);
716
+ queue.push(l.target_id);
717
+ };
718
+ for (const l of topLinks) if (l.origin_id === refId && l.origin_slot === slot) pushTarget(l);
719
+ while (queue.length) {
720
+ const cur = queue.shift();
721
+ for (const l of topLinks) if (l.origin_id === cur) pushTarget(l);
722
+ }
723
+ return reach;
724
+ };
725
+
726
+ const perPortReach = app.outputs.map((_, i) => reachFromSlot(i));
727
+ const allReach = new Set();
728
+ for (const r of perPortReach) for (const id of r) allReach.add(id);
729
+ // Downstream saver chain + upstream media-feed chain + overridden top widgets.
730
+ const converted = new Set([...allReach, ...feedReach, ...topOverrideNodes]);
731
+ // The ref node's input sockets that are LINKED to a top-level computed node (a
732
+ // ComfySwitchNode choosing the output resolution, a BranchNode for the controlnet
733
+ // channel, …) must be converted too: the subgraph's internal consumers resolve
734
+ // those shell links back to the top-level source, so dropping it collapses the
735
+ // switch to a literal and poisons the resolution chain (division by zero).
736
+ for (const s of refNode?.inputs ?? []) {
737
+ if (s.link == null) continue;
738
+ const tl = topLinksById.get(s.link);
739
+ const src = tl ? resolveOrigin(tl.origin_id, tl.origin_slot) : null;
740
+ if (src && src.nodeId !== refId && topById.has(src.nodeId)) converted.add(src.nodeId);
741
+ }
742
+ // A linear-layout app has no subgraph: the top-level graph IS the app, so every
743
+ // active top-level node is converted (mirroring how the frontend submits a linear
744
+ // workflow) instead of only the ref-node downstream chain.
745
+ if (app.linearOnly) {
746
+ for (const n of topNodes) if (isActive(n) && !isFrontendOnly(n)) converted.add(n.id);
747
+ }
748
+
749
+ // Literal value of a helper node that stayed outside the converted set
750
+ // (e.g. PrimitiveFloat -> VHS_VideoCombine.frame_rate). Only primitive-style
751
+ // nodes are read this way; anything else (a nested subgraph, another graph
752
+ // node) would hand the prompt a bogus value, so it is left unset.
753
+ const PRIMITIVE_RE = /^(Primitive(Int|Float|String|Boolean)?|INTConstant|FLOATConstant|STRINGConstant|BOOLEANConstant|.*Primitive.*|.*Seed.*|CR Seed|ComfySwitchNode)$/i;
754
+ const literalOf = (node) => {
755
+ if (!PRIMITIVE_RE.test(String(node.type ?? ''))) return null;
756
+ if (Array.isArray(node.widgets_values) && node.widgets_values.length) return node.widgets_values[0];
757
+ const vals = Object.values(node.widgets_values_named ?? {});
758
+ return vals.length ? vals[0] : null;
759
+ };
760
+
761
+ // Widget values of a top-level node. Plain nodes only have the positional
762
+ // widgets_values array (order = the node's widget inputs), while nodes saved by
763
+ // newer frontends may carry widgets_values_named or an object directly.
764
+ const widgetMapOf = (n) => {
765
+ const out = {};
766
+ const wv = n.widgets_values;
767
+ if (wv && !Array.isArray(wv) && typeof wv === 'object') Object.assign(out, wv);
768
+ else if (Array.isArray(wv)) {
769
+ const names = (n.inputs ?? []).filter((i) => i.widget).map((i) => i.name);
770
+ names.forEach((nm, i) => { if (i < wv.length) out[nm] = wv[i]; });
771
+ }
772
+ return { ...out, ...(n.widgets_values_named ?? {}) };
773
+ };
774
+
775
+ // ----------------------------------------------------------------------- #
776
+ // Nested subgraph references: a top-level node whose type is ANOTHER
777
+ // subgraph's UUID. The API can't run a UUID class_type and the ref node is
778
+ // only a shell — the frontend expands it into its internal nodes, so we do
779
+ // the same: convert the subgraph's real nodes under a `n<refId>_<id>` key and
780
+ // resolve its I/O to the internal producers / the ref node's own input links.
781
+ // ----------------------------------------------------------------------- #
782
+ const mainSgId = app.subgraphs?.[0]?.id;
783
+ const nestedSubgraphOf = (n) => {
784
+ if (!n || n.id === refId || n.type === mainSgId) return null;
785
+ return nestedIds.has(n.type) ? (app.subgraphs ?? []).find((s) => s.id === n.type) ?? null : null;
786
+ };
787
+ // Resolve a TOP-LEVEL link to its API value, transparently expanding a nested
788
+ // subgraph ref and a bypassed node. consumerTopId is the node being fed, so a
789
+ // media-feed node never re-resolves its own ref-origin to a subgraph output.
790
+ const resolveTopSource = (topLink, consumerTopId) => {
791
+ if (!topLink) return null;
792
+ const src = resolveOrigin(topLink.origin_id, topLink.origin_slot);
793
+ if (!src) return null;
794
+ if (src.nodeId === refId && !(consumerTopId != null && feedReach.has(consumerTopId))) {
795
+ const port = app.outputs[src.slot];
796
+ return port && port.producerNodeId != null ? [String(port.producerNodeId), port.producerSlot] : null;
797
+ }
798
+ const out = inlineNested(src.nodeId);
799
+ if (out) {
800
+ const pr = out[src.slot];
801
+ return pr ? [pr.key, pr.slot] : null;
802
+ }
803
+ const origin = topById.get(src.nodeId);
804
+ // A frontend-only node is never emitted; use its widget value if it is a
805
+ // primitive, otherwise the consumer keeps its own default (null link).
806
+ if (isFrontendOnly(origin)) {
807
+ const v = literalOf(origin);
808
+ return v !== null && v !== undefined ? v : null;
809
+ }
810
+ if (converted.has(src.nodeId)) return [topKey(src.nodeId), src.slot];
811
+ const v = origin ? literalOf(origin) : null;
812
+ return v !== null && v !== undefined ? v : null;
813
+ };
814
+ const nestedCache = new Map(); // refNodeId -> [{key,slot}] per output slot, or null
815
+ const inlineNested = (refNodeId) => {
816
+ if (nestedCache.has(refNodeId)) return nestedCache.get(refNodeId);
817
+ const n = topById.get(refNodeId);
818
+ const sg = n ? nestedSubgraphOf(n) : null;
819
+ if (!sg) { nestedCache.set(refNodeId, null); return null; }
820
+ const byId = new Map((sg.nodes ?? []).map((x) => [x.id, x]));
821
+ const linkById = new Map((sg.links ?? []).map((l) => [l.id, l]));
822
+ const shellInId = sg.inputNode?.id ?? -10;
823
+ const prefix = `n${refNodeId}_`;
824
+ // The ref node's own widgets hold the app's ACTUAL configured values (the
825
+ // internal nodes keep the subgraph template's stale defaults), so a shell
826
+ // widget port resolves to the ref value first, then the internal default.
827
+ const refWidgets = n.widgets_values_named ?? {};
828
+ // ref node output slot -> internal producer (prompt key, slot).
829
+ const out = [];
830
+ for (let slot = 0; slot < (sg.outputs ?? []).length; slot++) {
831
+ const l = sg.outputs[slot].linkIds?.[0] != null ? linkById.get(sg.outputs[slot].linkIds[0]) : undefined;
832
+ const producer = l ? byId.get(l.origin_id) : undefined;
833
+ out[slot] = producer && !isFrontendOnly(producer) ? { key: prefix + l.origin_id, slot: l.origin_slot } : null;
834
+ }
835
+ for (const inn of sg.nodes ?? []) {
836
+ if (isFrontendOnly(inn)) continue; // frontend-only: no backend class_type
837
+ const named = inn.widgets_values_named ?? {};
838
+ const inputs = {};
839
+ for (const s of inn.inputs ?? []) {
840
+ const l = s.link != null ? linkById.get(s.link) : undefined;
841
+ if (l && l.origin_id === shellInId) {
842
+ // Exposed input port: the shell link's origin_slot is the ref node's
843
+ // input slot. If that socket is itself linked (image/alpha/multiplier),
844
+ // the real source is the top-level link off the ref node. If it is a
845
+ // plain widget (seed/sampler/vae_name/…), the ref node's own value is
846
+ // the authoritative one, else the internal template default.
847
+ const refSock = n.inputs?.[l.origin_slot];
848
+ const src = refSock?.link != null ? resolveTopSource(topLinksById.get(refSock.link)) : undefined;
849
+ if (src !== undefined) {
850
+ inputs[s.name] = src ?? (s.name in named ? asWidgetValue(named[s.name]) : null);
851
+ } else {
852
+ const portName = refSock?.name ?? s.name;
853
+ inputs[s.name] = portName in refWidgets ? asWidgetValue(refWidgets[portName]) : (s.name in named ? asWidgetValue(named[s.name]) : null);
854
+ }
855
+ } else if (l && byId.has(l.origin_id) && !isFrontendOnly(byId.get(l.origin_id))) {
856
+ inputs[s.name] = [prefix + l.origin_id, l.origin_slot];
857
+ } else {
858
+ inputs[s.name] = s.name in named ? asWidgetValue(named[s.name]) : null;
859
+ }
860
+ }
861
+ for (const [k, v] of Object.entries(named)) if (!(k in inputs)) inputs[k] = asWidgetValue(v);
862
+ prompt[prefix + inn.id] = { class_type: inn.type, inputs };
863
+ }
864
+ nestedCache.set(refNodeId, out);
865
+ return out;
866
+ };
867
+
868
+ // Nested refs downstream of a subgraph output: reach them, but stop there —
869
+ // their internals are a separate graph inlined by inlineNested.
870
+ const nestedRefIds = new Set();
871
+ {
872
+ const q = [refId];
873
+ const seen = new Set([refId]);
874
+ while (q.length) {
875
+ const cur = q.shift();
876
+ for (const l of topLinks) {
877
+ if (l.origin_id !== cur || seen.has(l.target_id)) continue;
878
+ const t = topById.get(l.target_id);
879
+ if (!t) continue;
880
+ seen.add(l.target_id);
881
+ if (nestedSubgraphOf(t)) nestedRefIds.add(l.target_id);
882
+ else if (t.mode == null || t.mode === 0) q.push(l.target_id);
883
+ }
884
+ }
885
+ }
886
+ // Pull the FULL upstream closure of everything we convert. A socket whose
887
+ // source is a computed top-level node (ComfySwitchNode, ResolutionSelector,
888
+ // GetImageSize, BranchNode, PrimitiveBoolean, …) must be emitted as a real
889
+ // node reference — guessing a literal from its widgets yields garbage (e.g.
890
+ // the 输出宽度 switch literalizing to `true` inside the resize-multiplier
891
+ // NumberCalculator), which poisons the whole downstream saver chain. Nested
892
+ // refs' direct feeders AND their feeders' feeders are included recursively;
893
+ // the main subgraph ref (refId) is the terminal.
894
+ {
895
+ const q = [];
896
+ const queued = new Set();
897
+ const enqueue = (id) => { if (id === refId || queued.has(id)) return; queued.add(id); q.push(id); };
898
+ for (const id of new Set([...converted, ...nestedRefIds])) enqueue(id);
899
+ for (let i = 0; i < q.length; i++) {
900
+ const n = topById.get(q[i]);
901
+ if (!n) continue;
902
+ for (const s of n.inputs ?? []) {
903
+ if (s.link == null) continue;
904
+ const tl = topLinksById.get(s.link);
905
+ const src = tl ? resolveOrigin(tl.origin_id, tl.origin_slot) : null;
906
+ if (!src || src.nodeId === refId || !topById.has(src.nodeId)) continue;
907
+ converted.add(src.nodeId);
908
+ enqueue(src.nodeId);
909
+ }
910
+ }
911
+ }
912
+
913
+ // Main subgraph internal nodes. Runs AFTER the upstream closure so a shell
914
+ // socket fed by a top-level computed node resolves to that node (in `converted`)
915
+ // rather than collapsing to a literal.
916
+ for (const n of nodesById.values()) {
917
+ if (isFrontendOnly(n)) continue; // Note/MarkdownNote/Reroute/PrimitiveNode: no backend class_type
918
+ const named = n.widgets_values_named ?? {};
919
+ const inputs = {};
920
+ for (const s of n.inputs ?? []) {
921
+ const ml = mediaLinks.get(`${n.id}:${s.name}`);
922
+ if (ml) { inputs[s.name] = ml; continue; }
923
+ const ov = eff.get(`${n.id}:${s.name}`);
924
+ if (ov !== undefined) { inputs[s.name] = ov; continue; }
925
+ if (s.link != null) {
926
+ const l = linksById.get(s.link);
927
+ const origin = l && l.origin_id !== shellIn ? nodesById.get(l.origin_id) : null;
928
+ if (origin && !isFrontendOnly(origin)) {
929
+ // ComfyUI's API prompt uses STRING node ids, both as keys and as the
930
+ // first element of a [node_id, slot] link reference.
931
+ inputs[s.name] = [String(l.origin_id), l.origin_slot];
932
+ } else if (l && l.origin_id === shellIn) {
933
+ // Exposed-input port: the shell link's origin_slot is the ref node's input
934
+ // slot. If that socket is itself linked, the real source is the top-level
935
+ // link off the ref node (a ComfySwitchNode picking the resolution, a
936
+ // BranchNode for the channel, …) — resolve it. If it is a plain widget,
937
+ // the ref node's own value is authoritative, else the internal default.
938
+ const refSock = refNode?.inputs?.[l.origin_slot];
939
+ const src = refSock?.link != null ? resolveTopSource(topLinksById.get(refSock.link)) : undefined;
940
+ if (src !== undefined) {
941
+ inputs[s.name] = src ?? (s.name in named ? asWidgetValue(named[s.name]) : null);
942
+ } else {
943
+ const portName = refSock?.name ?? s.name;
944
+ inputs[s.name] = portName in (app.portValues ?? {}) ? asWidgetValue(app.portValues[portName]) : (s.name in named ? asWidgetValue(named[s.name]) : null);
945
+ }
946
+ } else {
947
+ inputs[s.name] = s.name in named ? asWidgetValue(named[s.name]) : null;
948
+ }
949
+ } else {
950
+ inputs[s.name] = s.name in named ? asWidgetValue(named[s.name]) : null;
951
+ }
952
+ }
953
+ for (const [k, v] of Object.entries(named)) if (!(k in inputs)) inputs[k] = asWidgetValue(v);
954
+ prompt[n.id] = { class_type: n.type, inputs };
955
+ }
956
+
957
+ for (const id of new Set([...converted, ...nestedRefIds])) {
958
+ const n = topById.get(id);
959
+ if (!n) continue;
960
+ // Frontend-only (Note/MarkdownNote/Reroute/PrimitiveNode) has no backend type.
961
+ if (isFrontendOnly(n)) continue;
962
+ // A nested ref is a shell: expand its subgraph, never emit the UUID class_type.
963
+ if (nestedSubgraphOf(n)) { inlineNested(id); continue; }
964
+ const named = widgetMapOf(n);
965
+ const inputs = {};
966
+ for (const s of n.inputs ?? []) {
967
+ if (s.link != null) {
968
+ const v = resolveTopSource(topLinksById.get(s.link), id);
969
+ if (v !== null && v !== undefined) inputs[s.name] = v;
970
+ } else if (s.widget && s.name in named) {
971
+ inputs[s.name] = asWidgetValue(named[s.name]);
972
+ }
973
+ }
974
+ // Widgets that belong to the API contract even though the UI lists them as
975
+ // plain widgets. Frontend-only extras (VHS "videopreview", …) are dropped.
976
+ for (const [k, v] of Object.entries(named)) {
977
+ if (k in inputs) continue;
978
+ if ((n.inputs ?? []).some((i) => i.name === k)) continue;
979
+ if (/preview/i.test(k)) continue;
980
+ inputs[k] = asWidgetValue(v);
981
+ }
982
+ // A supplied media path wins over the loader's saved widget value.
983
+ for (const [k, v] of topWidgetOverrides.get(n.id) ?? []) inputs[k] = asWidgetValue(v);
984
+ prompt[topKey(n.id)] = { class_type: n.type, inputs };
985
+ }
986
+
987
+ // Only add a synthetic saver when the app's own top-level sink is absent
988
+ // (hand-edited workflow, muted saver, headless import, …), so we never dump a
989
+ // frame sequence next to the real video/image the author configured. A
990
+ // PreviewImage counts as a sink: the app author chose not to persist that
991
+ // output, and its temp file is still downloadable from /history.
992
+ const SAVER_RE = /^(VHS_VideoCombine|SaveVideo|SaveAnimatedWEBM|SaveAnimatedPNG|SaveImage|SaveImageAdvanced|SaveAudio|SaveAudioMP3|SaveAudioOpus|PreviewImage|PreviewAny)$/;
993
+ let saverId = 999000;
994
+ for (let i = 0; i < app.outputs.length; i++) {
995
+ const out = app.outputs[i];
996
+ if (out.producerNodeId == null) continue;
997
+ const handled = [...perPortReach[i]].some((nid) => SAVER_RE.test(String(topById.get(nid)?.type ?? '')));
998
+ if (handled) continue;
999
+ const producer = String(out.producerNodeId);
1000
+ if (out.type === 'IMAGE') {
1001
+ prompt[++saverId] = {
1002
+ class_type: 'SaveImage',
1003
+ inputs: { images: [producer, out.producerSlot], filename_prefix: 'comfy_native_mcp' },
1004
+ };
1005
+ } else if (/VIDEO|ANIMATED|WEBM/i.test(out.type)) {
1006
+ prompt[++saverId] = {
1007
+ class_type: 'SaveAnimatedWEBM',
1008
+ inputs: { images: [producer, out.producerSlot], filename_prefix: 'comfy_native_mcp', fps: 8 },
1009
+ };
1010
+ }
1011
+ }
1012
+ // Expand %date:…% style filename tokens once for the whole prompt (frontend job).
1013
+ for (const node of Object.values(prompt)) {
1014
+ for (const [k, v] of Object.entries(node.inputs ?? {})) {
1015
+ if (typeof v === 'string' && /filename|prefix/i.test(k)) node.inputs[k] = expandFilenameTokens(v);
1016
+ }
1017
+ }
1018
+ return prompt;
1019
+ }
1020
+
1021
+ // Coerce a model-supplied value to the type the port declared, so a 9B model
1022
+ // sending seed "42" (string) or steps 8.0 instead of 8 still works.
1023
+ export function coerceByType(value, type) {
1024
+ if (value === undefined || value === null) return value;
1025
+ switch ((type ?? '').toUpperCase()) {
1026
+ case 'STRING': return String(value);
1027
+ case 'INT': {
1028
+ const n = Number(value);
1029
+ return Number.isNaN(n) ? value : Math.trunc(n);
1030
+ }
1031
+ case 'FLOAT': return Number(value);
1032
+ case 'BOOLEAN': return value === true || value === 'true' || value === 1;
1033
+ default: return value;
1034
+ }
1035
+ }
1036
+
1037
+ // Build the override map from the model's `values`. Keys may be a friendly port
1038
+ // label ("prompt") or the exact "<nodeId>.<widget>" form. seed = -1 rolls random.
1039
+ export function buildOverrides(app, values) {
1040
+ const ov = new Map();
1041
+ const byLabel = new Map();
1042
+ for (const i of app.inputs) {
1043
+ if (!byLabel.has(String(i.label))) byLabel.set(String(i.label), i);
1044
+ for (const a of i.aliases ?? []) if (!byLabel.has(String(a))) byLabel.set(String(a), i);
1045
+ }
1046
+ for (const [rawKey, rawVal] of Object.entries(values ?? {})) {
1047
+ const key = String(rawKey).trim();
1048
+ const m = /^(\d+):(.+)$/.exec(key) || /^(\d+)\.(.+)$/.exec(key);
1049
+ let port, targets, type;
1050
+ if (m) {
1051
+ port = app.inputs.find((i) => (i.targets ?? []).some((t) => String(t.nodeId) === m[1] && t.socket === m[2]))
1052
+ || app.inputs.find((i) => i.linear && String(i.linear.nodeId) === m[1] && i.linear.socket === m[2]);
1053
+ targets = port?.targets ?? [{ nodeId: m[1], socket: m[2] }];
1054
+ type = port?.type;
1055
+ } else {
1056
+ port = byLabel.get(key);
1057
+ if (!port) throw new Error(`unknown param "${key}" — call get_app_params("${app.name}") for its parameter list`);
1058
+ targets = port.targets ?? [];
1059
+ type = port.type;
1060
+ }
1061
+ if (port?.media) {
1062
+ // A media value is a filename for the port's loader, not a literal for the
1063
+ // IMAGE socket the port feeds. graphToPrompt routes it to the loader widget.
1064
+ ov.set(MEDIA_OVERRIDE_PREFIX + port.portId, String(rawVal));
1065
+ continue;
1066
+ }
1067
+ if (port?.linear) {
1068
+ // linearData port: the value goes to a TOP-LEVEL node's widget, which the
1069
+ // subgraph's own node-id namespace can't express (`@top:<nodeId>:<socket>`).
1070
+ let v = rawVal;
1071
+ if (/^seed$/i.test(port.linear.socket) && Number(v) === -1) v = Math.floor(Math.random() * 0xffffffff);
1072
+ ov.set(`@top:${port.linear.nodeId}:${port.linear.socket}`, coerceByType(v, type));
1073
+ continue;
1074
+ }
1075
+ if (!targets.length) throw new Error(`param "${key}" has no internal target`);
1076
+ let v = rawVal;
1077
+ if (/seed/i.test(targets[0].socket) && Number(v) === -1) v = Math.floor(Math.random() * 0xffffffff);
1078
+ for (const t of targets) ov.set(`${t.nodeId}:${t.socket}`, coerceByType(v, type));
1079
+ }
1080
+ return ov;
1081
+ }
1082
+
1083
+ // --------------------------------------------------------------------------- #
1084
+ // Resolve a model-supplied app reference: 1-based index, name, id (rel path), or filename stem.
1085
+ // --------------------------------------------------------------------------- #
1086
+ export function listApps() {
1087
+ const root = resolveWorkflowsRoot();
1088
+ const files = findNativeApps(root);
1089
+ const apps = files.map((f, i) => {
1090
+ let a;
1091
+ try { a = loadNativeApp(f); } catch (e) { return { number: i + 1, file: f, error: e.message }; }
1092
+ return {
1093
+ number: i + 1,
1094
+ name: a.name,
1095
+ id: a.id,
1096
+ file: f,
1097
+ description: a.description,
1098
+ outputs: a.outputs.map((o) => ({ name: o.name, type: o.type })),
1099
+ };
1100
+ });
1101
+ return { workflowsRoot: root, count: apps.length, apps };
1102
+ }
1103
+
1104
+ // list_apps payload: only what is needed to CHOOSE an app. The parameter contract
1105
+ // is a separate per-app call (appParams), so a 20-app catalog does not bury a
1106
+ // small model in a wall of inputs.
1107
+ export function appCatalog() {
1108
+ const { workflowsRoot, apps } = listApps();
1109
+ const list = apps.map((a) => {
1110
+ if (a.error) return { number: a.number, error: a.error.replace(`: ${a.file}`, '') };
1111
+ return {
1112
+ number: a.number,
1113
+ name: a.name,
1114
+ id: a.id,
1115
+ ...(a.description ? { description: a.description } : {}),
1116
+ outputs: [...new Set(a.outputs.map((o) => o.type))],
1117
+ };
1118
+ });
1119
+ const out = { count: list.length, apps: list };
1120
+ // Only surface the scan root when nothing was found — that is when it matters.
1121
+ if (!list.length) out.workflowsRoot = workflowsRoot;
1122
+ return out;
1123
+ }
1124
+
1125
+ // get_app_params payload: the full parameter contract of ONE app.
1126
+ // COMBO inputs always carry their `options` — the full list of legal values,
1127
+ // pulled from /object_info so a client can show a real dropdown and a model can
1128
+ // pick without guessing filenames. (Only real COMBOS have one: a port declared
1129
+ // STRING carries no choices.)
1130
+ export async function appParams(ref) {
1131
+ const app = resolveAppRef(ref);
1132
+ const a = loadNativeApp(app.file);
1133
+ // The node types behind this app's COMBO ports, deduped. linearData ports target
1134
+ // TOP-LEVEL nodes, so combine the subgraph-internal targets with the linear node.
1135
+ // Every port's backing node type, deduped — object_info supplies both the COMBO
1136
+ // option list and the per-socket tooltip (the same text the frontend shows on
1137
+ // hover), so gather specs for ALL inputs, not just COMBOS. linearData ports
1138
+ // target TOP-LEVEL nodes, so combine the subgraph-internal targets with the
1139
+ // linear node.
1140
+ const nodeTypes = new Set();
1141
+ for (const p of a.inputs) {
1142
+ for (const t of p.targets ?? []) {
1143
+ const type = a.nodesById.get(t.nodeId)?.type;
1144
+ if (type) nodeTypes.add(type);
1145
+ }
1146
+ if (p.linear) {
1147
+ const type = a.topById?.get(p.linear.nodeId)?.type;
1148
+ if (type) nodeTypes.add(type);
1149
+ }
1150
+ }
1151
+ const specs = {};
1152
+ await Promise.all([...nodeTypes].map(async (t) => {
1153
+ try { specs[t] = (await getJson(`/object_info/${encodeURIComponent(t)}`))[t]?.input; } catch { specs[t] = null; }
1154
+ }));
1155
+ // Resolve a port socket to its object_info spec. Newer nodes expose a whole
1156
+ // widget group as ONE socket (LoadLoraModel's `loras`, a COMFY_DYNAMICGROUP_V3
1157
+ // whose widget list lives under `template`), while the frontend flattens it to
1158
+ // `loras.0.lora_name`, `loras.0.strength`, … . The flat name is not a real
1159
+ // socket, so also look inside the group's template by the trailing name —
1160
+ // otherwise a LoRA picker's options never surface in get_app_params.
1161
+ const socketSpec = (spec, socket) => {
1162
+ const direct = spec?.required?.[socket] ?? spec?.optional?.[socket] ?? spec?.hidden?.[socket];
1163
+ if (direct !== undefined) return direct;
1164
+ if (!spec || !String(socket).includes('.')) return undefined;
1165
+ const parts = String(socket).split('.');
1166
+ const g = spec.required?.[parts[0]] ?? spec.optional?.[parts[0]] ?? spec.hidden?.[parts[0]];
1167
+ if (!Array.isArray(g) || !g[1]?.template) return undefined;
1168
+ // The middle numeric segments are just the repeated row index; the widget
1169
+ // itself is named by the last segment (lora_name, strength, enabled, …).
1170
+ return socketSpec(g[1].template, parts[parts.length - 1]);
1171
+ };
1172
+ // object_info encodes a COMBO socket several ways:
1173
+ // ["opt1","opt2"] — bare list
1174
+ // [["opt1","opt2"], {...}] — options + meta dict
1175
+ // ["COMBO", {options:[...]}] — dict-style combo (ResolutionSelector, …)
1176
+ const comboOptions = (raw) => {
1177
+ if (!Array.isArray(raw)) return undefined;
1178
+ if (Array.isArray(raw[0])) return raw[0];
1179
+ if (raw[0] === 'COMBO' && Array.isArray(raw[1]?.options)) return raw[1].options;
1180
+ return raw;
1181
+ };
1182
+ const optionsOf = (port) => {
1183
+ for (const t of port.targets ?? []) {
1184
+ const type = a.nodesById.get(t.nodeId)?.type;
1185
+ const spec = type ? specs[type] : undefined;
1186
+ const opts = comboOptions(socketSpec(spec, t.socket));
1187
+ if (Array.isArray(opts)) return opts;
1188
+ }
1189
+ if (port.linear) {
1190
+ const type = a.topById?.get(port.linear.nodeId)?.type;
1191
+ const spec = type ? specs[type] : undefined;
1192
+ const opts = comboOptions(socketSpec(spec, port.linear.socket));
1193
+ if (Array.isArray(opts)) return opts;
1194
+ }
1195
+ return null;
1196
+ };
1197
+ // The object_info meta dict (second element of ["COMBO", {tooltip: …}] or
1198
+ // [["opts"], {tooltip: …}]) carries the tooltip — the exact text the frontend
1199
+ // renders on widget hover. Surface it as the parameter's description.
1200
+ const tooltipOf = (port) => {
1201
+ const lookup = (nodeId, socket, nodesMap) => {
1202
+ const type = nodesMap.get(nodeId)?.type;
1203
+ const spec = type ? specs[type] : undefined;
1204
+ const raw = socketSpec(spec, socket);
1205
+ if (Array.isArray(raw) && raw[1] && typeof raw[1] === 'object' && !Array.isArray(raw[1]) && typeof raw[1].tooltip === 'string') return raw[1].tooltip;
1206
+ return undefined;
1207
+ };
1208
+ for (const t of port.targets ?? []) {
1209
+ const v = lookup(t.nodeId, t.socket, a.nodesById);
1210
+ if (v) return v;
1211
+ }
1212
+ if (port.linear) return lookup(port.linear.nodeId, port.linear.socket, a.topById);
1213
+ return undefined;
1214
+ };
1215
+ return {
1216
+ number: app.number,
1217
+ name: a.name,
1218
+ id: a.id,
1219
+ ...(a.description ? { description: a.description } : {}),
1220
+ inputs: a.inputs.map((inp) => {
1221
+ const p = { name: inp.label, type: inp.type };
1222
+ // The app author's own description (linearData entry meta, or the port's
1223
+ // description field) wins; otherwise fall back to the node's socket tooltip.
1224
+ const desc = inp.description || tooltipOf(inp);
1225
+ if (desc) p.description = desc;
1226
+ if (inp.default !== null && inp.default !== undefined) p.default = inp.default;
1227
+ if (inp.type === 'COMBO') {
1228
+ const opts = optionsOf(inp);
1229
+ if (opts?.length) p.options = opts;
1230
+ }
1231
+ return p;
1232
+ }),
1233
+ outputs: a.outputs.map((o) => ({ name: o.name, type: o.type })),
1234
+ };
1235
+ }
1236
+
1237
+ export function resolveAppRef(ref) {
1238
+ const { apps } = listApps();
1239
+ // Numbering matches list_apps: EVERY app gets a sequential number (bad apps too),
1240
+ // so a model that read list_apps and says "11" gets #11 here, never shifted.
1241
+ const n = Number(ref);
1242
+ if (Number.isInteger(n) && n >= 1 && n <= apps.length) {
1243
+ const a = apps[n - 1];
1244
+ if (a.error) throw new Error(`app #${n} is unreadable: ${a.error}`);
1245
+ return a;
1246
+ }
1247
+ if (/^\d+$/.test(String(ref))) {
1248
+ const i = Number(ref);
1249
+ if (i >= 1 && i <= apps.length) {
1250
+ const a = apps[i - 1];
1251
+ if (a.error) throw new Error(`app #${i} is unreadable: ${a.error}`);
1252
+ return a;
1253
+ }
1254
+ throw new Error(`app #${ref} out of range (1..${apps.length})`);
1255
+ }
1256
+ const ok = apps.filter((a) => !a.error);
1257
+ const r = String(ref).trim();
1258
+ const byId = ok.find((a) => a.id === r);
1259
+ if (byId) return byId;
1260
+ const byStem = ok.find((a) => path.basename(a.file, '.app.json') === r);
1261
+ if (byStem) return byStem;
1262
+ const byName = ok.find((a) => a.name === r);
1263
+ if (byName) return byName;
1264
+ const lower = r.toLowerCase();
1265
+ const fuzzy = ok.find((a) => a.name.toLowerCase() === lower);
1266
+ if (fuzzy) return fuzzy;
1267
+ throw new Error(`no app named "${ref}" - available: ${ok.map((a) => a.name).join(', ') || '(none)'}`);
1268
+ }
1269
+ export async function postPrompt(graph) {
1270
+ const r = await fetch(BASE + '/prompt', {
1271
+ method: 'POST',
1272
+ headers: { 'Content-Type': 'application/json' },
1273
+ body: JSON.stringify({ prompt: graph, client_id: 'comfy-native-mcp' }),
1274
+ });
1275
+ if (!r.ok) throw new Error(`ComfyUI /prompt HTTP ${r.status}: ${(await r.text()).slice(0, 400)}`);
1276
+ return r.json();
1277
+ }
1278
+
1279
+ export async function getJson(p) {
1280
+ const r = await fetch(BASE + p);
1281
+ if (!r.ok) throw new Error(`ComfyUI ${p} HTTP ${r.status}`);
1282
+ return r.json();
1283
+ }
1284
+
1285
+ export async function postJson(p, body) {
1286
+ const r = await fetch(BASE + p, {
1287
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body ?? {}),
1288
+ });
1289
+ if (!r.ok) throw new Error(`ComfyUI ${p} HTTP ${r.status}: ${(await r.text()).slice(0, 300)}`);
1290
+ // /interrupt and /queue?clear answer with an empty 200 body — only parse if there is one.
1291
+ const t = await r.text();
1292
+ return t ? JSON.parse(t) : { ok: true };
1293
+ }
1294
+
1295
+ // Upload a LOCAL file (image/video/audio/mask — anything you can load from the
1296
+ // input dir) into ComfyUI's /upload/ dir. Multipart like the frontend's Upload.
1297
+ // `subfolder` is relative to the input dir (e.g. "mybatch"); the returned path
1298
+ // ("mybatch/name") is exactly what a LoadImage / LoadAudio / LoadVideo / Load
1299
+ // Mask input expects in run_app values.
1300
+ export async function uploadFile(localPath, subfolder = '') {
1301
+ const abs = path.resolve(localPath);
1302
+ if (!fs.existsSync(abs)) throw new Error(`file not found: ${localPath}`);
1303
+ const name = path.basename(abs);
1304
+ const form = new FormData();
1305
+ form.append('image', new Blob([fs.readFileSync(abs)]), name);
1306
+ if (subfolder) form.append('subfolder', subfolder.replace(/\\/g, '/').replace(/^\/+|\/+$/g, ''));
1307
+ const r = await fetch(BASE + '/upload/image', { method: 'POST', body: form });
1308
+ if (!r.ok) throw new Error(`ComfyUI /upload/image HTTP ${r.status}: ${(await r.text()).slice(0, 300)}`);
1309
+ const j = await r.json();
1310
+ return { path: ((j.subfolder ? j.subfolder + '/' : '') + (j.name ?? name)).replace(/\\/g, '/') };
1311
+ }
1312
+
1313
+ export async function getBytes(p) {
1314
+ const r = await fetch(BASE + p);
1315
+ if (!r.ok) throw new Error(`ComfyUI ${p} HTTP ${r.status}`);
1316
+ return Buffer.from(await r.arrayBuffer());
1317
+ }
1318
+
1319
+ // Client-reachable base for download links. COMFYUI_PUBLIC_URL is for the case
1320
+ // where this MCP host can reach ComfyUI at COMFYUI_URL but the client cannot
1321
+ // (container network, reverse proxy, SSH tunnel, …).
1322
+ const PUBLIC_BASE = (process.env.COMFYUI_PUBLIC_URL || BASE).replace(/\/+$/, '');
1323
+
1324
+ export function outputViewUrl(it) {
1325
+ return `${PUBLIC_BASE}/view?filename=${encodeURIComponent(it.filename)}` +
1326
+ (it.subfolder ? `&subfolder=${encodeURIComponent(it.subfolder)}` : '') +
1327
+ `&type=${encodeURIComponent(it.type ?? 'output')}`;
1328
+ }
1329
+
1330
+ function viewQuery(it) {
1331
+ return `filename=${encodeURIComponent(it.filename)}` +
1332
+ (it.subfolder ? `&subfolder=${encodeURIComponent(it.subfolder)}` : '') +
1333
+ `&type=${encodeURIComponent(it.type ?? 'output')}`;
1334
+ }
1335
+
1336
+ // Where a download lands. dest may be a file, a directory, or absent:
1337
+ // "E:/out/clip.mp4" → that file
1338
+ // "E:/out/" → E:/out/clip.mp4 (no extension → treated as a dir too)
1339
+ // "clips" → <cwd>/clips/clip.mp4
1340
+ // omitted → $DOWNLOAD_DIR/clip.mp4, else <cwd>/downloads/clip.mp4
1341
+ function resolveDest(dest, filename) {
1342
+ let raw = String(dest ?? '').trim() || process.env.DOWNLOAD_DIR || path.join(process.cwd(), 'downloads');
1343
+ if (raw === '~' || raw.startsWith('~/') || raw.startsWith('~\\')) raw = path.join(os.homedir(), raw.slice(1));
1344
+ const full = path.resolve(raw);
1345
+ const isDir = /[\\/]$/.test(raw) ||
1346
+ (fs.existsSync(full) && fs.statSync(full).isDirectory()) ||
1347
+ !path.extname(full);
1348
+ return isDir ? path.join(full, filename) : full;
1349
+ }
1350
+
1351
+ // Resolve one finished output by prompt_id (+ index when a job wrote several),
1352
+ // fetch its bytes over /view and write them to a local file. Writing through
1353
+ // HTTP (instead of copying the server-side path) is what makes it work for a
1354
+ // remote ComfyUI: the file lands on the machine running THIS MCP server.
1355
+ export async function downloadOutput({ prompt_id, index = 0, dest }) {
1356
+ if (!prompt_id) throw new Error('prompt_id is required');
1357
+ if (/^\d+$/.test(String(prompt_id).trim())) {
1358
+ throw new Error(`"${prompt_id}" is a queue number, not a prompt_id. Use the UUID returned by run_app (e.g. "24700a6f-…").`);
1359
+ }
1360
+ const hist = await getJson(`/history/${encodeURIComponent(prompt_id)}`).catch(() => ({}));
1361
+ const entry = hist[prompt_id];
1362
+ if (!entry) throw new Error(`no history for prompt_id ${prompt_id} (unknown, or cleared by ComfyUI)`);
1363
+ if (entry.status?.status_str === 'error') {
1364
+ const msg = entry.status?.messages?.find((m) => m?.[0] === 'execution_error')?.[1]?.exception_message;
1365
+ throw new Error(`job ${prompt_id} failed: ${msg ?? 'execution error'}`);
1366
+ }
1367
+ const items = Object.values(entry.outputs ?? {})
1368
+ .flatMap((o) => ['images', 'videos', 'gifs'].flatMap((k) => (Array.isArray(o?.[k]) ? o[k] : [])))
1369
+ .filter((x) => x && typeof x === 'object' && x.filename)
1370
+ .sort((a, b) => Number(a.type === 'temp') - Number(b.type === 'temp'));
1371
+ if (!items.length) throw new Error(`job ${prompt_id} has no downloadable outputs (state: ${entry.status?.status_str ?? 'unknown'})`);
1372
+ const i = Math.max(0, Number(index) || 0);
1373
+ const it = items[i];
1374
+ if (!it) throw new Error(`index ${index} out of range: job ${prompt_id} has ${items.length} output(s)`);
1375
+
1376
+ const savedTo = resolveDest(dest, it.filename);
1377
+ const bytes = await getBytes(`/view?${viewQuery(it)}`);
1378
+ fs.mkdirSync(path.dirname(savedTo), { recursive: true });
1379
+ fs.writeFileSync(savedTo, bytes);
1380
+
1381
+ return {
1382
+ prompt_id,
1383
+ index: i,
1384
+ filename: it.filename,
1385
+ saved_to: savedTo,
1386
+ bytes: bytes.length,
1387
+ url: outputViewUrl(it),
1388
+ };
1389
+ }
1390
+
1391
+ // Pull the first image/video out of a finished job, plus any STRING outputs.
1392
+ // Only ComfyUI-side metadata (filename/subfolder/type + /view URL) is reported;
1393
+ // server filesystem paths are deliberately omitted — a client that wants a local
1394
+ // file calls download_output, which returns saved_to on the MCP host.
1395
+ export async function collectOutputs(entry, { index = 0 } = {}) {
1396
+ const texts = [];
1397
+ for (const [nodeId, nodeOut] of Object.entries(entry.outputs ?? {})) {
1398
+ for (const [key, items] of Object.entries(nodeOut)) {
1399
+ if (Array.isArray(items) && items.length && typeof items[0] === 'string') texts.push(`${key}: ${items[0]}`);
1400
+ }
1401
+ }
1402
+ // Saved files win over temp previews, so a PreviewImage inside the graph does
1403
+ // not shadow the real result. Order is otherwise preserved (first node wins).
1404
+ const cands = [];
1405
+ for (const nodeOut of Object.values(entry.outputs ?? {})) {
1406
+ for (const key of ['images', 'gifs', 'videos']) {
1407
+ const items = nodeOut[key];
1408
+ if (items?.length) cands.push({ key, it: items[0] });
1409
+ }
1410
+ }
1411
+ cands.sort((a, b) => Number(a.it.type === 'temp') - Number(b.it.type === 'temp'));
1412
+ const pick = cands[Math.max(0, Number(index) || 0)];
1413
+ if (pick) {
1414
+ const { key, it } = pick;
1415
+ const meta = { filename: it.filename, subfolder: it.subfolder ?? '', type: it.type ?? 'output', url: outputViewUrl(it) };
1416
+ if (key === 'videos' || /\.(mp4|webm|mov|mkv|gif)$/i.test(it.filename)) {
1417
+ return { kind: 'video', ...meta, extra: texts };
1418
+ }
1419
+ const data = await getBytes(`/view?${viewQuery(it)}`);
1420
+ const mime = /\.(jpe?g)$/i.test(it.filename) ? 'image/jpeg' : /\.webp$/i.test(it.filename) ? 'image/webp' : 'image/png';
1421
+ return { kind: 'image', ...meta, mime, b64: data.toString('base64'), extra: texts };
1422
+ }
1423
+ return { kind: 'none', text: 'job finished but no image/video output was found', extra: texts };
1424
+ }
1425
+
1426
+ // Preview a finished job WITHOUT writing anything to disk: re-read its /history
1427
+ // entry and return the index-th image inline (base64) plus its /view URL. This is
1428
+ // what makes the submit-only run_app flow viewable: the client calls
1429
+ // job_status(prompt_id, wait_s) and gets the picture, no download_output needed.
1430
+ export async function jobPreview(promptId, { index = 0 } = {}) {
1431
+ const hist = await getJson(`/history/${encodeURIComponent(promptId)}`).catch(() => ({}));
1432
+ const entry = hist[promptId];
1433
+ if (!entry || entry.status?.status_str === 'error') return null;
1434
+ const out = await collectOutputs(entry, { index });
1435
+ return out.kind === 'image' ? out : null;
1436
+ }
1437
+
1438
+ // --------------------------------------------------------------------------- #
1439
+ // Queue monitoring.
1440
+ // --------------------------------------------------------------------------- #
1441
+ // One finished job from /history, kept small enough for a small model to read.
1442
+ function summarizeHistory(promptId, e) {
1443
+ const msgs = e?.status?.messages ?? [];
1444
+ const stamp = (name) => msgs.find((m) => m?.[0] === name)?.[1]?.timestamp;
1445
+ const finished = stamp('execution_success') ?? stamp('execution_error') ?? stamp('execution_interrupted');
1446
+ const outputs = Object.values(e?.outputs ?? {})
1447
+ .flatMap((o) => Object.values(o ?? {}))
1448
+ .flat()
1449
+ .filter((x) => x && typeof x === 'object' && x.filename)
1450
+ .map((x) => (x.subfolder ? `${x.subfolder}/${x.filename}` : x.filename));
1451
+ return {
1452
+ prompt_id: promptId,
1453
+ state: e?.status?.status_str === 'error' ? 'error' : 'completed',
1454
+ outputs,
1455
+ ...(finished ? { finished_at: new Date(finished).toISOString() } : {}),
1456
+ };
1457
+ }
1458
+
1459
+ // recent > 0 also reads that many finished jobs from /history. jobStatus() leaves
1460
+ // it at 0 so polling a job does not re-download history on every call.
1461
+ async function getQueue({ recent = 0 } = {}) {
1462
+ const [q, hist] = await Promise.all([
1463
+ getJson('/queue'),
1464
+ recent > 0 ? getJson(`/history?max_items=${recent}`).catch(() => ({})) : null,
1465
+ ]);
1466
+ // ComfyUI queue entries are [queue_number, prompt_id, prompt, extra_data,
1467
+ // outputs_to_execute]. Very old builds sent [prompt_id, prompt, outputs].
1468
+ // Normalize both shapes and never confuse the queue number with the prompt_id.
1469
+ const slim = (arr) => (arr ?? []).map((e) => {
1470
+ const five = Array.isArray(e) && e.length >= 5;
1471
+ const queueNumber = five ? e[0] : null;
1472
+ const promptId = five ? e[1] : e?.[0];
1473
+ const prompt = (five ? e[2] : e?.[1]) ?? {};
1474
+ const classTypes = Object.values(prompt).slice(0, 4).map((n) => n?.class_type).filter(Boolean);
1475
+ return {
1476
+ prompt_id: String(promptId ?? ''),
1477
+ queue_number: queueNumber,
1478
+ node_count: Object.keys(prompt).length,
1479
+ class_types: classTypes,
1480
+ };
1481
+ });
1482
+ const out = { running: slim(q.queue_running), pending: slim(q.queue_pending) };
1483
+ if (hist) {
1484
+ // /history is ordered oldest -> newest; the model wants newest first.
1485
+ out.recent = Object.entries(hist).slice(-recent)
1486
+ .map(([id, e]) => summarizeHistory(id, e))
1487
+ .reverse();
1488
+ }
1489
+ return out;
1490
+ }
1491
+ export { getQueue };
1492
+
1493
+ const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
1494
+
1495
+ // One non-blocking look at a job: queue first, then history. Also resolves a
1496
+ // queue number shorthand while the job is still queued.
1497
+ async function inspectJob(promptId) {
1498
+ let id = String(promptId ?? '').trim();
1499
+ const q = await getQueue();
1500
+ if (/^\d+$/.test(id)) {
1501
+ const hit = [...q.running, ...q.pending].find((e) => String(e.queue_number) === id);
1502
+ if (hit) id = hit.prompt_id;
1503
+ }
1504
+ const running = q.running.find((e) => e.prompt_id === id);
1505
+ if (running) return { prompt_id: id, state: 'running', queue_number: running.queue_number };
1506
+ const pending = q.pending.find((e) => e.prompt_id === id);
1507
+ if (pending) return { prompt_id: id, state: 'pending', queue_number: pending.queue_number };
1508
+
1509
+ const hist = await getJson(`/history/${id}`).catch(() => ({}));
1510
+ const e = hist[id];
1511
+ if (!e) {
1512
+ return {
1513
+ prompt_id: id,
1514
+ state: 'unknown',
1515
+ hint: 'Pass the UUID prompt_id returned by run_app (unknown, or history cleared).',
1516
+ };
1517
+ }
1518
+ if (e.status?.status_str === 'error') {
1519
+ const error = e.status.messages?.find((m) => m?.[0] === 'execution_error')?.[1]?.exception_message ?? 'execution error';
1520
+ return { prompt_id: id, state: 'error', error, entry: e };
1521
+ }
1522
+ const outs = Object.entries(e.outputs ?? {})
1523
+ .flatMap(([, o]) => Object.entries(o).flatMap(([k, v]) => (Array.isArray(v) ? v : [v]).filter((x) => x && typeof x === 'object' && x.filename).map((x) => ({ key: k, filename: x.filename, ...(x.subfolder ? { subfolder: x.subfolder } : {}), type: x.type ?? 'output', url: outputViewUrl(x) }))));
1524
+ return { prompt_id: id, state: 'completed', outputs: outs, entry: e };
1525
+ }
1526
+
1527
+ // Block until the job is no longer running/pending, or the budget runs out.
1528
+ // `entry` (raw /history entry) stays on the result for internal callers.
1529
+ async function waitForFinal(promptId, waitS) {
1530
+ const started = Date.now();
1531
+ const budget = Math.max(0, Number(waitS) || 0) * 1000;
1532
+ const deadline = started + budget;
1533
+ for (;;) {
1534
+ const st = await inspectJob(promptId);
1535
+ if (st.state === 'completed' || st.state === 'error' || st.state === 'unknown') return st;
1536
+ const left = deadline - Date.now();
1537
+ if (left <= 0) {
1538
+ return { ...st, timed_out: true, waited_s: Math.round((Date.now() - started) / 1000) };
1539
+ }
1540
+ await sleep(Math.min(1000, left));
1541
+ }
1542
+ }
1543
+
1544
+ // External shape: never leak the full prompt graph back to the model.
1545
+ export async function jobStatus(promptId, { waitS = 0 } = {}) {
1546
+ const st = waitS > 0 ? await waitForFinal(promptId, waitS) : await inspectJob(promptId);
1547
+ const { entry, ...rest } = st;
1548
+ return rest;
1549
+ }
1550
+
1551
+ // Used by run_app: returns the raw /history entry, throws on error or timeout.
1552
+ export async function waitForJob(promptId, timeoutS = RUN_TIMEOUT_S) {
1553
+ const st = await waitForFinal(promptId, timeoutS);
1554
+ if (st.state === 'error') throw new Error(`ComfyUI error: ${st.error ?? 'execution error'}`);
1555
+ if (st.state === 'unknown') throw new Error(`no history for prompt_id ${st.prompt_id} (unknown, or cleared by ComfyUI)`);
1556
+ if (st.timed_out) {
1557
+ const err = new Error(`render not finished within ${timeoutS}s (prompt_id ${st.prompt_id}, state ${st.state})`);
1558
+ err.code = 'TIMEOUT';
1559
+ throw err;
1560
+ }
1561
+ return st.entry;
1562
+ }