comfy-native-apps 0.0.0-stage → 1.0.1

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