comfy-native-apps 1.0.0 → 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.
@@ -131,6 +131,9 @@ stdio,不支持 HTTP(sse/streamable)。如确有需要可提 issue。
131
131
  | `COMFYUI_PUBLIC_URL` | 同 `COMFYUI_URL` | 客户端可达的 ComfyUI 地址;MCP 主机能连、客户端连不上时(容器/反代/隧道)用于生成下载链接 |
132
132
  | `WORKFLOWS_ROOT` | *(不设)* | 可选本地覆盖:从该目录读 `workflows/**/*.app.json` 代替服务器 API;普通情况下不需要 |
133
133
  | `RUN_TIMEOUT_S` | `300` | 单次渲染等待上限(秒) |
134
+ | `PREVIEW_MAX_SIDE` | `1024` | 内联预览图最长边(px) |
135
+ | `PREVIEW_MAX_PIXELS` | `1100000` | 内联预览图总像素上限 |
136
+ | `PREVIEW_MAX_BYTES` | `1500000` | 单张预览 PNG 字节上限 |
134
137
  | `DOWNLOAD_DIR` | `<MCP 进程 cwd>/downloads` | `download_output` 未给 `dest` 时的落盘目录 |
135
138
 
136
139
  > 旧写法 `COMFYUI_HOST` + `COMFYUI_PORT` 仍兼容,但推荐统一用 `COMFYUI_URL`。
package/README.md CHANGED
@@ -51,7 +51,7 @@ also feeds a real node is kept.
51
51
  `job_status` / `download_output` take the **UUID prompt_id** returned by `run_app`; the `queue_number` from `queue_status` is just a queue position and only works as a shortcut while the job is queued.
52
52
  `queue_status` reads `recent` from ComfyUI's `/history` (cleared when ComfyUI restarts). Each entry only carries `prompt_id`, `state`, output filenames and the finish time; use `job_status` for the full result of one history job.
53
53
  **Download**: `download_output` now writes the file to disk (bytes over `/view`) and returns `saved_to`. `dest` may be a file path (`E:/out/clip.mp4`, rename on the way), a directory (`E:/out`, `E:/out/`; no extension also means directory) or a relative path (against the MCP process cwd); omit it to use `DOWNLOAD_DIR`. The file lands on the **machine running this MCP server**, remote ComfyUI included.
54
- `run_app` only returns the image preview block and the `/view` URL (videos: URL only) — **no ComfyUI / MCP server file paths**. For a local file call `download_output`; its `saved_to` is the real on-disk path. When a job produced both a saved file and a temp preview, the saved file is the one returned (`download_output` uses the same order).
54
+ `run_app` only returns the image preview block and the `/view` URL (videos: URL only) — **no ComfyUI / MCP server file paths**. For a local file call `download_output`; its `saved_to` is the real on-disk path. When a job produced both a saved file and a temp preview, the saved file is the one returned (`download_output` uses the same order). When a job writes several files (multiple save nodes, or one save node with a batch of images), `run_app` lists the `/view` URL of **every** output in order and attaches **each one** as a preview image: PNG stills are downscaled and re-encoded on the MCP host (default longest side 1024, ≤1.1 MP, ≤1.5 MB per image — tune with `PREVIEW_*`), while the URLs always serve the full-resolution file. `job_status`'s `outputs` carry the same `index`, so `job_status(index)` and `download_output(index)` address the same file in one flat list (`job_status` previews only that one index, so polling does not re-send everything).
55
55
  **Waiting**: `run_app` blocks until the result by default; `wait_s: 0` only enqueues and returns the `prompt_id`. Then `job_status(prompt_id, wait_s)` blocks up to N seconds and returns `timed_out: true` plus the current `state` when the budget runs out — call it again to keep waiting instead of guessing client timeouts.
56
56
  For apps with an image/video/audio/mask input: first call `upload_file` with a local path, then pass the returned **ComfyUI-side relative path** (e.g. `mybatch/wall.png`) as that param value in `run_app` - ComfyUI reads it from its input dir, not the Windows filesystem, so absolute paths like `E:/.../wall.png` wont resolve.
57
57
 
@@ -119,6 +119,9 @@ a local `<ComfyUI user>` dir.
119
119
  | `COMFYUI_PUBLIC_URL` | same as `COMFYUI_URL` | address clients use; set it only when this MCP host can reach ComfyUI but clients cannot (container / reverse proxy / tunnel), so download links stay reachable |
120
120
  | `WORKFLOWS_ROOT` | *(unset)* | optional override: read `workflows/**/*.app.json` from this local dir instead of the server API |
121
121
  | `RUN_TIMEOUT_S` | `300` | seconds to wait for a render |
122
+ | `PREVIEW_MAX_SIDE` | `1024` | longest side of an inline preview image (px); larger ones are scaled down |
123
+ | `PREVIEW_MAX_PIXELS` | `1100000` | total pixel budget for an inline preview (~1.1 MP), so tall images stay small too |
124
+ | `PREVIEW_MAX_BYTES` | `1500000` | byte cap for one preview PNG; if still over, it is scaled down and re-encoded again |
122
125
  | `DOWNLOAD_DIR` | `<MCP process cwd>/downloads` | where `download_output` writes when `dest` is omitted |
123
126
 
124
127
  > The old `COMFYUI_HOST` + `COMFYUI_PORT` pair still works as a fallback, but `COMFYUI_URL` replaces it.
package/README.zh-CN.md CHANGED
@@ -33,7 +33,7 @@ artokun 的 comfyui-mcp 暴露了约 38 个带 action 参数的工具(外加 3
33
33
  `job_status` / `download_output` 要的是 `run_app` 返回的 **UUID prompt_id**;`queue_status` 里的 `queue_number` 只是队列序号,仅任务排队期间可当作快捷方式使用。
34
34
  `queue_status` 的 `recent` 读的是 ComfyUI 的 `/history`(ComfyUI 重启后清空),每条只给 `prompt_id`、`state`、输出文件名和完成时间;要某个历史任务的完整结果仍用 `job_status`。
35
35
  **下载**:`download_output` 会把文件真正写到本地(从 `/view` 取字节),返回 `saved_to`。`dest` 传文件路径(`E:/out/clip.mp4`,可顺便改名)、目录(`E:/out`、`E:/out/`,没有扩展名也按目录处理)或相对路径(相对 MCP 进程的 cwd);省略则写到 `DOWNLOAD_DIR`。文件落在 **MCP 服务端所在机器**,远程 ComfyUI 也一样。
36
- `run_app` 只返回图片预览块和 `/view` 链接(视频只有链接),**不再返回 ComfyUI / MCP 服务端的文件路径**——需要本地文件就调 `download_output`,它返回的 `saved_to` 才是真实落盘路径。同一个任务里既有落盘文件又有临时预览图时,优先返回落盘文件(`download_output` 的顺序一致)。
36
+ `run_app` 只返回图片预览块和 `/view` 链接(视频只有链接),**不再返回 ComfyUI / MCP 服务端的文件路径**——需要本地文件就调 `download_output`,它返回的 `saved_to` 才是真实落盘路径。同一个任务里既有落盘文件又有临时预览图时,优先返回落盘文件(`download_output` 的顺序一致)。一个任务写了多个文件时(图里有多个保存节点,或一个保存节点一次写了多张),`run_app` 会按顺序列出**全部**产物的 `/view` 链接,并把**每一张**都作为图片块内联返回——内联的是压缩预览:PNG 在本机缩放后重编码(默认最长边 1024、总像素 ≤1.1MP、单张 ≤1.5MB,可用 `PREVIEW_*` 调整),`/view` 链接始终是全分辨率原图。`job_status` 的 `outputs` 带着同一套 `index`,`job_status(index)` 与 `download_output(index)` 都指这份扁平列表里的同一个文件(`job_status` 只内联该 index 的一张,避免反复轮询时重复放大 payload)。
37
37
  **等待**:`run_app` 默认会阻塞到出结果;`wait_s: 0` 只入队并立刻返回 `prompt_id`。之后用 `job_status(prompt_id, wait_s)` 阻塞最多 N 秒,超时会返回 `timed_out: true` 和当前 `state`,再调一次即可接着等,不会靠猜客户端超时。
38
38
  有图片/视频/音频/mask 输入的应用:先调用 `upload_file`(给本地文件路径),再把返回的 **ComfyUI 侧相对路径**(如 `mybatch/wall.png`)作为该输入参数的值传给 `run_app` —— ComfyUI 是从它的 input 目录读文件的,不是从 Windows 文件系统,所以 `E:/.../wall.png` 这种绝对路径解析不到。
39
39
 
@@ -76,6 +76,9 @@ app 直接来自 ComfyUI 服务器本身,走的是 Web 前端列出/打开工
76
76
  | `COMFYUI_PUBLIC_URL` | 等于 `COMFYUI_URL` | 客户端访问 ComfyUI 的地址;仅当 MCP 主机能连、客户端连不上时(容器 / 反代 / 隧道)才需要设置,用于生成下载链接 |
77
77
  | `WORKFLOWS_ROOT` | *(不设)* | 可选本地覆盖:从该目录读 `workflows/**/*.app.json` 代替服务器 API;普通情况不需要 |
78
78
  | `RUN_TIMEOUT_S` | `300`(等待一次渲染的秒数) | 单次渲染等待上限 |
79
+ | `PREVIEW_MAX_SIDE` | `1024` | 内联预览图的最长边(px);超过就缩放 |
80
+ | `PREVIEW_MAX_PIXELS` | `1100000` | 内联预览图的总像素上限(约 1.1MP),竖图/长图也不会超 |
81
+ | `PREVIEW_MAX_BYTES` | `1500000` | 单张预览 PNG 的字节上限;仍超标则继续缩小重编码 |
79
82
  | `DOWNLOAD_DIR` | `<MCP 进程工作目录>/downloads` | `download_output` 未给 `dest` 时的落盘目录,可设成固定文件夹 |
80
83
 
81
84
  > 旧写法 `COMFYUI_HOST` + `COMFYUI_PORT` 仍然兼容,但已被 `COMFYUI_URL` 取代。
@@ -72,8 +72,9 @@ const TOOLS = [
72
72
  },
73
73
  {
74
74
  name: 'run_app',
75
- description: 'Run one app: fill its input params and generate. Waits for the job and returns the finished image ' +
76
- '(or the video URL). Pass app as its number from list_apps, its name, or its id. ' +
75
+ description: 'Run one app: fill its input params and generate. Waits for the job and returns a downscaled preview ' +
76
+ 'image of every output it wrote (or the video URL), plus the full-resolution URL of each file. ' +
77
+ 'Pass app as its number from list_apps, its name, or its id. ' +
77
78
  'Call get_app_params first, then pass the params you want to change in the "inputs" object ' +
78
79
  '(NOT at the top level — a stray field is an error, not a silently-ignored default). ' +
79
80
  'Omitted ones keep their defaults. A seed of -1 rolls a random seed. ' +
@@ -126,15 +127,16 @@ const TOOLS = [
126
127
  description: 'Report the state (running / pending / completed / error) and output files of one job. ' +
127
128
  'Pass the UUID prompt_id returned by run_app. While a job is still queued, its queue number also works. ' +
128
129
  'Set wait_s to block until the job finishes (or the budget runs out) instead of polling. ' +
129
- 'When the job is completed, each output carries a viewable "url", and (preview=true, the default) the ' +
130
- 'first image is returned inline so a submit-only run_app can be previewed without download_output.',
130
+ 'When the job is completed, "outputs" lists every file it wrote with a viewable "url" and a stable "index" ' +
131
+ '(saved files first, temp previews last), and (preview=true, the default) the image at "index" is returned ' +
132
+ 'inline as a downscaled preview, so a submit-only run_app can be previewed without download_output.',
131
133
  inputSchema: {
132
134
  type: 'object',
133
135
  properties: {
134
136
  prompt_id: { type: 'string', description: 'The prompt_id returned by run_app or seen in queue_status.' },
135
137
  wait_s: { type: 'integer', minimum: 0, maximum: 3600, description: 'Block until the job finishes, up to this many seconds. Defaults to 0 (return at once).' },
136
138
  preview: { type: 'boolean', description: 'When the job is completed, return the image inline (base64) for immediate viewing. Defaults to true; set false to get only the JSON status/URLs.' },
137
- index: { type: 'integer', minimum: 0, description: 'Which output to preview when the job wrote several. Defaults to 0.' },
139
+ index: { type: 'integer', description: 'Which output to preview when the job wrote several (index into job_status "outputs"). Defaults to 0.' },
138
140
  },
139
141
  required: ['prompt_id'],
140
142
  },
@@ -159,7 +161,7 @@ const TOOLS = [
159
161
  type: 'object',
160
162
  properties: {
161
163
  prompt_id: { type: 'string', description: 'The prompt_id returned by run_app or job_status.' },
162
- index: { type: 'integer', description: 'Which output to take when the job wrote several. Defaults to 0.', minimum: 0 },
164
+ index: { type: 'integer', description: 'Which output to take when the job wrote several (index into job_status "outputs"). Defaults to 0.', minimum: 0 },
163
165
  dest: { type: 'string', description: 'Local destination: a file ("E:/out/clip.mp4"), a directory ("E:/out" or "out/"), or a relative path. Omit for the default downloads folder.' },
164
166
  },
165
167
  required: ['prompt_id'],
@@ -257,23 +259,36 @@ async function runAppHandler({ app, wait_s, inputs, ...stray }) {
257
259
  }];
258
260
  }
259
261
 
260
- const out = await collectOutputs(entry);
262
+ const out = await collectOutputs(entry, { previews: true });
263
+ // A job can write several files (two save nodes, or one save node with a
264
+ // batch of images), so list every output and attach every image inline — as
265
+ // downscaled previews, keeping a 10 MB PNG out of the client's context.
266
+ const previews = out.previews ?? [];
267
+ const many = (out.files?.length ?? 0) > 1;
268
+ const listing = many
269
+ ? ['', `${out.files.length} outputs (attached previews are in this order):`,
270
+ ...out.files.map((f, i) => `${i}. ${f.url}`)]
271
+ : [];
272
+ const previewNote = (previews.some((p) => p.shrunk) || out.shrunk)
273
+ ? ['', 'Preview images are downscaled/re-encoded; open the URLs for full resolution.']
274
+ : [];
261
275
 
262
276
  if (out.kind === 'image') {
263
- const lines = [`Generated ${out.filename} with app "${a.name}".`, `URL: ${out.url}`];
264
- lines.push(`(prompt_id ${promptId})`);
277
+ const lines = many
278
+ ? [`App "${a.name}" finished (prompt_id ${promptId}).`, ...listing, ...previewNote]
279
+ : [`Generated ${out.filename} with app "${a.name}".`, `URL: ${out.url}`, `(prompt_id ${promptId})`, ...previewNote];
265
280
  if (out.extra?.length) lines.push('', 'Other outputs:', ...out.extra);
266
281
  return [
267
282
  { type: 'text', text: lines.join('\n') },
268
- { type: 'image', data: out.b64, mimeType: out.mime },
283
+ ...previews.map((p) => ({ type: 'image', data: p.b64, mimeType: p.mime })),
269
284
  ];
270
285
  }
271
286
  if (out.kind === 'video') {
272
- const lines = [`App "${a.name}" finished (prompt_id ${promptId}).`, `Video: ${out.url}`];
287
+ const lines = [`App "${a.name}" finished (prompt_id ${promptId}).`, `Video: ${out.url}`, ...listing];
273
288
  if (out.extra?.length) lines.push('', 'Other outputs:', ...out.extra);
274
289
  return [{ type: 'text', text: lines.join('\n') }];
275
290
  }
276
- const lines = [`App "${a.name}" finished (prompt_id ${promptId}).`, out.text];
291
+ const lines = [`App "${a.name}" finished (prompt_id ${promptId}).`, out.text, ...listing];
277
292
  if (out.extra?.length) lines.push('', 'Other outputs:', ...out.extra);
278
293
  return [{ type: 'text', text: lines.join('\n') }];
279
294
  }
package/native_lib.mjs CHANGED
@@ -30,6 +30,7 @@
30
30
  import fs from 'node:fs';
31
31
  import os from 'node:os';
32
32
  import path from 'node:path';
33
+ import { shrinkPng } from './preview_png.mjs';
33
34
 
34
35
  // --------------------------------------------------------------------------- #
35
36
  // Config.
@@ -45,6 +46,16 @@ export const BASE = trimSlashes(
45
46
  );
46
47
  export const RUN_TIMEOUT_S = Number(process.env.RUN_TIMEOUT_S ?? 300);
47
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
+
48
59
  // --------------------------------------------------------------------------- #
49
60
  // App discovery. Native apps live in ComfyUI's user dir, and the server exposes
50
61
  // that dir over HTTP (/userdata) — the same API the web frontend uses to list and
@@ -1348,6 +1359,37 @@ function resolveDest(dest, filename) {
1348
1359
  return isDir ? path.join(full, filename) : full;
1349
1360
  }
1350
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
+
1351
1393
  // Resolve one finished output by prompt_id (+ index when a job wrote several),
1352
1394
  // fetch its bytes over /view and write them to a local file. Writing through
1353
1395
  // HTTP (instead of copying the server-side path) is what makes it work for a
@@ -1364,17 +1406,14 @@ export async function downloadOutput({ prompt_id, index = 0, dest }) {
1364
1406
  const msg = entry.status?.messages?.find((m) => m?.[0] === 'execution_error')?.[1]?.exception_message;
1365
1407
  throw new Error(`job ${prompt_id} failed: ${msg ?? 'execution error'}`);
1366
1408
  }
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'));
1409
+ const items = outputFiles(entry);
1371
1410
  if (!items.length) throw new Error(`job ${prompt_id} has no downloadable outputs (state: ${entry.status?.status_str ?? 'unknown'})`);
1372
1411
  const i = Math.max(0, Number(index) || 0);
1373
1412
  const it = items[i];
1374
1413
  if (!it) throw new Error(`index ${index} out of range: job ${prompt_id} has ${items.length} output(s)`);
1375
1414
 
1376
1415
  const savedTo = resolveDest(dest, it.filename);
1377
- const bytes = await getBytes(`/view?${viewQuery(it)}`);
1416
+ const bytes = await getBytes(`/view?${viewQuery(it.raw)}`);
1378
1417
  fs.mkdirSync(path.dirname(savedTo), { recursive: true });
1379
1418
  fs.writeFileSync(savedTo, bytes);
1380
1419
 
@@ -1388,39 +1427,66 @@ export async function downloadOutput({ prompt_id, index = 0, dest }) {
1388
1427
  };
1389
1428
  }
1390
1429
 
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 } = {}) {
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 } = {}) {
1396
1460
  const texts = [];
1397
- for (const [nodeId, nodeOut] of Object.entries(entry.outputs ?? {})) {
1461
+ for (const [, nodeOut] of Object.entries(entry.outputs ?? {})) {
1398
1462
  for (const [key, items] of Object.entries(nodeOut)) {
1399
1463
  if (Array.isArray(items) && items.length && typeof items[0] === 'string') texts.push(`${key}: ${items[0]}`);
1400
1464
  }
1401
1465
  }
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)];
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];
1413
1472
  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 };
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 };
1418
1476
  }
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 };
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 };
1422
1488
  }
1423
- return { kind: 'none', text: 'job finished but no image/video output was found', extra: texts };
1489
+ return { kind: 'none', text: 'job finished but no image/video output was found', files, total: files.length, extra: texts };
1424
1490
  }
1425
1491
 
1426
1492
  // Preview a finished job WITHOUT writing anything to disk: re-read its /history
@@ -1519,9 +1585,12 @@ async function inspectJob(promptId) {
1519
1585
  const error = e.status.messages?.find((m) => m?.[0] === 'execution_error')?.[1]?.exception_message ?? 'execution error';
1520
1586
  return { prompt_id: id, state: 'error', error, entry: e };
1521
1587
  }
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 };
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 };
1525
1594
  }
1526
1595
 
1527
1596
  // Block until the job is no longer running/pending, or the budget runs out.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "comfy-native-apps",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "A 9-tool MCP server that runs ComfyUI's native .app.json workflow apps and manages the render queue, with zero plugin dependency.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -33,6 +33,7 @@
33
33
  "files": [
34
34
  "comfy_native_apps.mjs",
35
35
  "native_lib.mjs",
36
+ "preview_png.mjs",
36
37
  "drive_safe.mjs",
37
38
  "assert_media.mjs",
38
39
  "MCP-CONFIG.zh-CN.md"
@@ -0,0 +1,198 @@
1
+ // Downscale a PNG so it can be attached inline without blowing up a client's
2
+ // context. ComfyUI's SaveImage writes plain 8-bit, non-interlaced PNG (RGB or
3
+ // RGBA), which is all this decodes; any other PNG (16-bit, interlaced, …) is
4
+ // left untouched rather than risking a broken preview. Encoding uses the
5
+ // standard per-row filter heuristic plus zlib level 9, so it stays dependency
6
+ // free — no sharp / canvas / ImageMagick on the MCP host.
7
+ import zlib from 'node:zlib';
8
+
9
+ const SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
10
+ const CHANNELS = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 };
11
+
12
+ const CRC = (() => {
13
+ const t = new Int32Array(256);
14
+ for (let n = 0; n < 256; n++) {
15
+ let c = n;
16
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
17
+ t[n] = c;
18
+ }
19
+ return t;
20
+ })();
21
+
22
+ function crc32(buf) {
23
+ let c = -1;
24
+ for (let i = 0; i < buf.length; i++) c = CRC[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
25
+ return (c ^ -1) >>> 0;
26
+ }
27
+
28
+ function paeth(a, b, c) {
29
+ const p = a + b - c;
30
+ const pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c);
31
+ return pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
32
+ }
33
+
34
+ function readChunks(buf) {
35
+ const out = new Map();
36
+ for (let off = 8; off + 12 <= buf.length;) {
37
+ const len = buf.readUInt32BE(off);
38
+ const type = buf.toString('latin1', off + 4, off + 8);
39
+ if (off + 12 + len > buf.length) return null;
40
+ const data = buf.subarray(off + 8, off + 8 + len);
41
+ if (type === 'IDAT') {
42
+ const list = out.get('IDAT') ?? [];
43
+ list.push(data);
44
+ out.set('IDAT', list);
45
+ } else if (type === 'IHDR' || type === 'PLTE') out.set(type, data);
46
+ off += 12 + len;
47
+ }
48
+ return out;
49
+ }
50
+
51
+ function unfilter(raw, w, h, bpp, stride) {
52
+ const out = Buffer.alloc(stride * h);
53
+ for (let y = 0; y < h; y++) {
54
+ const ft = raw[y * (stride + 1)];
55
+ if (ft > 4) return null;
56
+ const src = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1));
57
+ const row = out.subarray(y * stride, (y + 1) * stride);
58
+ const prev = y ? out.subarray((y - 1) * stride, y * stride) : null;
59
+ for (let x = 0; x < stride; x++) {
60
+ const a = x >= bpp ? row[x - bpp] : 0;
61
+ const b = prev ? prev[x] : 0;
62
+ const c = prev && x >= bpp ? prev[x - bpp] : 0;
63
+ const v = src[x] + (ft === 0 ? 0 : ft === 1 ? a : ft === 2 ? b : ft === 3 ? (a + b) >> 1 : paeth(a, b, c));
64
+ row[x] = v & 0xff;
65
+ }
66
+ }
67
+ return out;
68
+ }
69
+
70
+ // RGB triples, alpha dropped: these are previews of opaque photographs, and
71
+ // keeping the alpha channel only inflates the encoded size.
72
+ function toRgb(px, w, h, color, palette) {
73
+ const n = w * h;
74
+ const rgb = Buffer.alloc(n * 3);
75
+ if (color === 2 || color === 6) {
76
+ const step = color === 6 ? 4 : 3;
77
+ for (let i = 0; i < n; i++) {
78
+ rgb[i * 3] = px[i * step];
79
+ rgb[i * 3 + 1] = px[i * step + 1];
80
+ rgb[i * 3 + 2] = px[i * step + 2];
81
+ }
82
+ } else if (color === 3) {
83
+ for (let i = 0; i < n; i++) {
84
+ const p = px[i] * 3;
85
+ rgb[i * 3] = palette[p];
86
+ rgb[i * 3 + 1] = palette[p + 1];
87
+ rgb[i * 3 + 2] = palette[p + 2];
88
+ }
89
+ } else {
90
+ for (let i = 0; i < n; i++) {
91
+ const g = px[i * (color === 4 ? 2 : 1)];
92
+ rgb[i * 3] = rgb[i * 3 + 1] = rgb[i * 3 + 2] = g;
93
+ }
94
+ }
95
+ return rgb;
96
+ }
97
+
98
+ function decode(buf) {
99
+ if (!buf.subarray(0, 8).equals(SIG)) return null;
100
+ const c = readChunks(buf);
101
+ const ihdr = c?.get('IHDR');
102
+ if (!ihdr || ihdr.length < 13) return null;
103
+ const w = ihdr.readUInt32BE(0), h = ihdr.readUInt32BE(4);
104
+ const depth = ihdr[8], color = ihdr[9], interlace = ihdr[12];
105
+ if (!w || !h || depth !== 8 || interlace !== 0 || !CHANNELS[color]) return null;
106
+ const palette = c.get('PLTE');
107
+ if (color === 3 && !palette) return null;
108
+ const stride = w * CHANNELS[color];
109
+ const raw = zlib.inflateSync(Buffer.concat(c.get('IDAT')), { maxOutputLength: stride * h + h });
110
+ const px = unfilter(raw, w, h, Math.max(1, Math.ceil(CHANNELS[color] * depth / 8)), stride);
111
+ return px ? { w, h, rgb: toRgb(px, w, h, color, palette) } : null;
112
+ }
113
+
114
+ function downscale(src, w, h, tw, th) {
115
+ const out = Buffer.alloc(tw * th * 3);
116
+ const xs = new Int32Array(tw + 1), ys = new Int32Array(th + 1);
117
+ for (let x = 0; x <= tw; x++) xs[x] = Math.floor(x * w / tw);
118
+ for (let y = 0; y <= th; y++) ys[y] = Math.floor(y * h / th);
119
+ for (let y = 0; y < th; y++) {
120
+ for (let x = 0; x < tw; x++) {
121
+ let r = 0, g = 0, b = 0, n = 0;
122
+ for (let sy = ys[y]; sy < ys[y + 1]; sy++) {
123
+ for (let sx = xs[x], o = sy * w * 3 + sx * 3; sx < xs[x + 1]; sx++, o += 3) {
124
+ r += src[o]; g += src[o + 1]; b += src[o + 2]; n++;
125
+ }
126
+ }
127
+ const o = (y * tw + x) * 3;
128
+ out[o] = Math.round(r / n);
129
+ out[o + 1] = Math.round(g / n);
130
+ out[o + 2] = Math.round(b / n);
131
+ }
132
+ }
133
+ return out;
134
+ }
135
+
136
+ function encode(w, h, rgb) {
137
+ const stride = w * 3;
138
+ const raw = Buffer.alloc((stride + 1) * h);
139
+ const prev = Buffer.alloc(stride);
140
+ const cand = Array.from({ length: 5 }, () => Buffer.alloc(stride));
141
+ for (let y = 0; y < h; y++) {
142
+ const row = rgb.subarray(y * stride, (y + 1) * stride);
143
+ let best = 0, bestSum = Infinity;
144
+ for (let f = 0; f < 5; f++) {
145
+ const c = cand[f];
146
+ let sum = 0;
147
+ for (let x = 0; x < stride; x++) {
148
+ const a = x >= 3 ? row[x - 3] : 0;
149
+ const b = prev[x];
150
+ const cc = x >= 3 ? prev[x - 3] : 0;
151
+ const v = (row[x] - (f === 0 ? 0 : f === 1 ? a : f === 2 ? b : f === 3 ? (a + b) >> 1 : paeth(a, b, cc))) & 0xff;
152
+ c[x] = v;
153
+ sum += v < 128 ? v : 256 - v;
154
+ }
155
+ if (sum < bestSum) { bestSum = sum; best = f; }
156
+ }
157
+ raw[y * (stride + 1)] = best;
158
+ cand[best].copy(raw, y * (stride + 1) + 1);
159
+ row.copy(prev);
160
+ }
161
+ const ihdr = Buffer.alloc(13);
162
+ ihdr.writeUInt32BE(w, 0);
163
+ ihdr.writeUInt32BE(h, 4);
164
+ ihdr[8] = 8;
165
+ ihdr[9] = 2;
166
+ const chunk = (type, data) => {
167
+ const out = Buffer.alloc(12 + data.length);
168
+ out.writeUInt32BE(data.length, 0);
169
+ out.write(type, 4, 'latin1');
170
+ data.copy(out, 8);
171
+ out.writeUInt32BE(crc32(out.subarray(4, 8 + data.length)), 8 + data.length);
172
+ return out;
173
+ };
174
+ return Buffer.concat([
175
+ SIG,
176
+ chunk('IHDR', ihdr),
177
+ chunk('IDAT', zlib.deflateSync(raw, { level: 9 })),
178
+ chunk('IEND', Buffer.alloc(0)),
179
+ ]);
180
+ }
181
+
182
+ // Returns the re-encoded PNG bytes, or null when the image is already inside
183
+ // both budgets (nothing worth doing) or its format is not supported.
184
+ export function shrinkPng(buf, { maxSide = 1024, maxPixels = 1100000, maxBytes = 1500000 } = {}) {
185
+ const img = decode(buf);
186
+ if (!img) return null;
187
+ let scale = Math.min(1, maxSide / Math.max(img.w, img.h), Math.sqrt(maxPixels / (img.w * img.h)));
188
+ if (scale >= 1 && buf.length <= maxBytes) return null;
189
+ for (let attempt = 0; attempt < 3; attempt++) {
190
+ const tw = Math.max(1, Math.round(img.w * scale));
191
+ const th = Math.max(1, Math.round(img.h * scale));
192
+ const out = encode(tw, th, scale >= 1 ? img.rgb : downscale(img.rgb, img.w, img.h, tw, th));
193
+ if (out.length <= maxBytes || (tw <= 64 && th <= 64)) return out;
194
+ // Still too heavy at this size: shrink further and try again.
195
+ scale *= Math.max(0.5, Math.min(0.9, Math.sqrt(maxBytes / out.length) * 0.95));
196
+ }
197
+ return null;
198
+ }