From 2ab101cfea92a979ba1ea815f738c8343627cfa4 Mon Sep 17 00:00:00 2001 From: wangjinding Date: Mon, 23 Nov 2026 09:49:57 +0800 Subject: [PATCH] release: 1.0.0 --- .gitignore | 4 + LICENSE | 21 ++ README.md | 71 +++++ cordis.patch.yml | 19 ++ lib/client.js | 183 +++++++++++++ lib/index.js | 669 +++++++++++++++++++++++++++++++++++++++++++++++ package.json | 51 ++++ 7 files changed, 1018 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 cordis.patch.yml create mode 100644 lib/client.js create mode 100644 lib/index.js create mode 100644 package.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f8a080d --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +*.tgz +*.log +.DS_Store diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ca52806 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 dsh-comfyui contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..db41a2b --- /dev/null +++ b/README.md @@ -0,0 +1,71 @@ +# @wangjinding/dsh-comfyui + +把局域网里的 **ComfyUI** 接进 DeepSeek Harness:设置页填地址、一键测试,之后 agent 就能用它的显卡出图、跑任意工作流。 + +## 安装 + +```bash +cd ~/.dsh/profiles/ +pnpm add @wangjinding/dsh-comfyui +``` + +然后在 `package.json` 的 `dsh.profile.bundles` 里加上 `@wangjinding/dsh-comfyui`,重启 DSH。 + +## 配置 + +**设置 → ComfyUI**:填服务地址(如 `http://<主机>:8188`)→「保存并连接」。 + +地址也可写进 profile 的 `cordis.patch.yml`: + +```yaml +- id: comfyui + config: + baseUrl: http://<你的 ComfyUI 主机>:8188 +``` + +设置在 `~/.dsh/storages/dsh-comfyui/config.json`(600),**不写进 profile 配置**,也不进发布包。 + +## 工具 + +| 工具 | 作用 | +|---|---| +| `comfy_generate_image` | 内置 Z-Image Turbo 文生图(1024²/8 步约 20–25 秒) | +| `comfy_run_workflow` | 跑任意 **API 格式** 工作流,产物自动下载到本地 | +| `comfy_upload` | 上传本地文件到 ComfyUI 的 `input/`,供图生视频等使用 | +| `comfy_status` | 版本 / GPU 显存 / 队列 / 内置模型(不消耗算力) | + +## API 格式 vs UI 格式(重要) + +ComfyUI 的 `POST /prompt` 只接受 **API 格式**: + +```json +{ "节点id": { "class_type": "KSampler", "inputs": { ... } } } +``` + +ComfyUI 界面保存的工作流是 **UI 格式**(`nodes` / `links` / `widgets_values`),直接提交会报校验失败。 +在界面里右键 →「**导出 (API)**」得到的 JSON 才是能跑的。 + +## 内置工作流 + +`comfy_generate_image` 用的是 Z-Image Turbo 的 API 图: + +``` +CLIPLoader(qwen_3_4b, type=lumina2) ─┐ +UNETLoader(z_image_turbo_bf16) ─┼→ ModelSamplingAuraFlow(shift=3) → KSampler(8步, cfg=1, +VAELoader(ae.safetensors) ─┘ res_multistep, simple) +CLIPTextEncode(prompt) → ConditioningZeroOut → 作为负向条件(cfg=1 时这样做) + → VAEDecode → SaveImage +``` + +两个容易踩的点: + +1. **文本编码器类型是 `lumina2`**,不是 `qwen_image`。 +2. **负向条件用 `ConditioningZeroOut`** 把正向清零,而不是再写一个 `CLIPTextEncode`。 + +## 安全提示 + +ComfyUI 默认没有认证,通常监听 `0.0.0.0` —— 同一局域网内任何设备都能连上并占用显卡。建议只在可信内网使用,或在前置反向代理上加认证。 + +## 许可 + +MIT diff --git a/cordis.patch.yml b/cordis.patch.yml new file mode 100644 index 0000000..f05ad74 --- /dev/null +++ b/cordis.patch.yml @@ -0,0 +1,19 @@ +# dsh-comfyui bundle patch +# +# 把局域网里的 ComfyUI 接进 DSH: +# ① 设置页「ComfyUI」分区:填地址、测试连接、保存 +# ② 工具:comfy_status / comfy_generate_image / comfy_run_workflow / comfy_upload +# +# 地址等设置存在 ~/.dsh/storages/dsh-comfyui/config.json(插件自己的状态,不碰 profile 配置)。 +# 优先级:状态文件 > 本文件的 config > 空(未配置时设置页会提示填写) +# +# 要改默认地址就在你自己 profile 的 cordis.patch.yml 里覆盖: +# - id: comfyui +# config: +# baseUrl: http://<你的 ComfyUI 主机>:8188 +# +# 回滚:从 ~/.dsh/profiles/web/package.json 的 dsh.profile.bundles 里删掉本包,再重启。 + +- insert: + - id: comfyui + name: "@wangjinding/dsh-comfyui" diff --git a/lib/client.js b/lib/client.js new file mode 100644 index 0000000..3c55199 --- /dev/null +++ b/lib/client.js @@ -0,0 +1,183 @@ +window.__ModuleLoader__.load({ + id: '@wangjinding/dsh-comfyui', + factory(require) { + const React = require('react'); + const h = React.createElement; + const { useState, useEffect, useCallback } = React; + + const API = '/plugin/comfyui'; + + const T = { + text: 'var(--dsw-alias-label-primary, #1f2329)', + sub: 'var(--dsw-alias-label-secondary, #646a73)', + dim: 'var(--dsw-alias-label-tertiary, #8f959e)', + line: 'var(--dsw-alias-border-l2, #dee0e3)', + card: 'var(--dsw-alias-bg-layer-2, #ffffff)', + field: 'var(--dsw-alias-bg-layer-1, #f7f8fa)', + brand: 'var(--dsw-alias-brand-primary, #247bbf)', + ok: 'var(--dsw-alias-state-success-primary, #2ea121)', + err: 'var(--dsw-alias-state-error-primary, #f54a45)', + }; + + const css = { + wrap: { padding: '4px 0 24px', color: T.text, fontSize: 14, lineHeight: 1.6 }, + h1: { fontSize: 17, fontWeight: 600, margin: '0 0 6px' }, + desc: { color: T.sub, margin: '0 0 18px', fontSize: 13 }, + card: { border: `1px solid ${T.line}`, borderRadius: 10, background: T.card, padding: 16, marginBottom: 14 }, + label: { display: 'block', fontSize: 13, fontWeight: 600, marginBottom: 8, whiteSpace: 'nowrap', flexShrink: 0 }, + row: { display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }, + input: { + flex: '1 1 320px', minWidth: 220, height: 34, padding: '0 10px', borderRadius: 8, + border: `1px solid ${T.line}`, background: T.field, color: T.text, fontSize: 13, + fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', outline: 'none', + }, + btn: { height: 34, padding: '0 14px', borderRadius: 8, cursor: 'pointer', border: `1px solid ${T.line}`, background: T.card, color: T.text, fontSize: 13 }, + primary: { border: `1px solid ${T.brand}`, background: T.brand, color: '#fff', fontWeight: 600 }, + hint: { marginTop: 10, fontSize: 12, color: T.dim }, + status: { display: 'inline-flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap', flexShrink: 0, padding: '3px 10px', borderRadius: 999, fontSize: 12, fontWeight: 600 }, + kv: { display: 'grid', gridTemplateColumns: 'auto 1fr', gap: '6px 14px', fontSize: 13, marginTop: 12 }, + k: { color: T.dim }, + bullet: { margin: '6px 0 0', paddingLeft: 18, color: T.sub, fontSize: 13 }, + kbd: { fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', background: T.field, border: `1px solid ${T.line}`, borderRadius: 4, padding: '0 4px', fontSize: 12 }, + pre: { margin: '10px 0 0', padding: 10, borderRadius: 8, background: T.field, fontSize: 12, color: T.sub, whiteSpace: 'pre-wrap', wordBreak: 'break-all', fontFamily: 'ui-monospace, monospace' }, + }; + + async function call(path, init) { + const resp = await fetch(`${API}${path}`, { ...init, headers: { 'Content-Type': 'application/json', ...(init && init.headers) } }); + const body = await resp.json().catch(() => ({})); + if (!resp.ok || body.ok === false) throw new Error(body.error || `HTTP ${resp.status}`); + return body; + } + + function Dot({ on }) { + return h('span', { style: { width: 6, height: 6, borderRadius: 999, background: on ? T.ok : T.err, display: 'inline-block' } }); + } + + function ComfyPanel() { + const [info, setInfo] = useState(null); + const [url, setUrl] = useState(''); + const [busy, setBusy] = useState(''); + const [msg, setMsg] = useState(null); + + const refresh = useCallback(async (silent) => { + try { + const s = await call('/status', { method: 'GET' }); + setInfo(s); + setUrl((cur) => cur || s.baseUrl || ''); + } catch (e) { + if (!silent) setMsg({ kind: 'err', text: `读取状态失败:${e.message}` }); + } + }, []); + + useEffect(() => { refresh(true); }, [refresh]); + + const save = async (withTest) => { + setBusy(withTest ? 'save' : 'saveonly'); setMsg(null); + try { + await call('/config', { method: 'POST', body: JSON.stringify({ baseUrl: url }) }); + setMsg({ kind: 'ok', text: '地址已保存' }); + await refresh(true); + if (withTest) { + setBusy('test'); + const t = await call('/test', { method: 'POST', body: '{}' }); + setInfo(t); + setMsg({ kind: 'ok', text: `连接正常:ComfyUI ${t.version},${t.devices?.[0]?.name || '未知设备'}` }); + } + } catch (e) { + setMsg({ kind: 'err', text: `失败:${e.message}` }); + } finally { setBusy(''); } + }; + + const test = async () => { + setBusy('test'); setMsg(null); + try { + const t = await call('/test', { method: 'POST', body: '{}' }); + setInfo(t); + setMsg({ kind: 'ok', text: `连接正常(${t.devices?.[0]?.name || 'GPU 未知'},空闲 ${t.devices?.[0]?.vramFreeGB ?? '?'}GB)` }); + } catch (e) { + setMsg({ kind: 'err', text: `连不上:${e.message}` }); + } finally { setBusy(''); } + }; + + const reachable = !!info?.reachable; + const dev = info?.devices?.[0]; + + return h('div', { style: css.wrap }, + h('h1', { style: css.h1 }, 'ComfyUI'), + h('p', { style: css.desc }, + '接入局域网里的 ComfyUI 后,DSH 可以直接用它的显卡出图、跑视频工作流。工具:', + h('code', { style: css.kbd }, 'comfy_generate_image'), + ' / ', + h('code', { style: css.kbd }, 'comfy_run_workflow'), + ' / ', + h('code', { style: css.kbd }, 'comfy_upload'), + ' / ', + h('code', { style: css.kbd }, 'comfy_status')), + + h('div', { style: css.card }, + h('div', { style: { display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12, flexWrap: 'wrap' } }, + h('span', { style: css.label, marginBottom: 0 }, '服务地址'), + h('span', { style: { ...css.status, background: reachable ? 'rgba(46,161,33,.12)' : 'rgba(245,74,69,.12)', color: reachable ? T.ok : T.err } }, + h(Dot, { on: reachable }), + reachable ? `已连接 · v${info.version || '?'}` : '未连接')), + + h('div', { style: css.row }, + h('input', { + style: css.input, value: url, spellCheck: false, + placeholder: 'http://:8188', + onChange: (e) => setUrl(e.target.value), + onKeyDown: (e) => { if (e.key === 'Enter' && !busy) save(true); }, + }), + h('button', { style: { ...css.btn, ...css.primary, opacity: busy ? 0.6 : 1 }, disabled: !!busy, onClick: () => save(true) }, + busy === 'save' ? '连接中…' : '保存并连接'), + h('button', { style: { ...css.btn, opacity: busy ? 0.6 : 1 }, disabled: !!busy, onClick: test }, + busy === 'test' ? '测试中…' : '测试连接')), + + msg ? h('div', { style: { marginTop: 12, fontSize: 13, color: msg.kind === 'ok' ? T.ok : T.err } }, msg.text) : null, + + reachable && info ? h('div', { style: css.kv }, + h('span', { style: css.k }, 'GPU'), + h('span', null, `${dev?.name || '未知'}|显存 ${dev?.vramTotalGB ?? '?'}GB(空闲 ${dev?.vramFreeGB ?? '?'}GB)`), + h('span', { style: css.k }, '内存'), + h('span', null, `${info.ramTotalGB ?? '?'} GB`), + h('span', { style: css.k }, '队列'), + h('span', null, `${info.queue?.running ?? 0} 运行 / ${info.queue?.pending ?? 0} 排队`), + h('span', { style: css.k }, '输出目录'), + h('span', { style: { wordBreak: 'break-all' } }, info.outputDir || '—'), + h('span', { style: css.k }, '内置模型'), + h('span', null, `${info.models?.unet || '—'}(${info.models?.clip || '—'} / ${info.models?.vae || '—'})`)) + : null, + + !reachable && info?.error + ? h('div', { style: css.pre }, info.error) + : null, + + h('p', { style: css.hint }, + 'ComfyUI 默认没有认证,且通常监听 0.0.0.0 —— 同一局域网内任何设备都能连上并占用显卡。建议只在家里内网使用。')), + + h('div', { style: css.card }, + h('div', { style: css.label }, '能做什么'), + h('ul', { style: css.bullet }, + h('li', null, h('b', null, '出图'), ':内置 Z-Image Turbo 工作流,1024² / 8 步约 25 秒(本机实测)'), + h('li', null, h('b', null, '跑任意工作流'), ':把 ComfyUI 界面里「导出 (API)」得到的 JSON 交给 ', + h('code', { style: css.kbd }, 'comfy_run_workflow'), ',产物自动下载到本地'), + h('li', null, h('b', null, '本地图做输入'), ':先用 ', + h('code', { style: css.kbd }, 'comfy_upload'), ' 传到 ComfyUI 的 input 目录,再在 workflow 里引用'), + h('li', null, h('b', null, '视频 / 音频'), ':这台装了 LTX 2.5、MiniMax H3、Stable Audio 3,导出对应 API 工作流即可跑')), + h('p', { style: css.hint }, '设置保存在 ~/.dsh/storages/dsh-comfyui/config.json,不写进 profile 配置。'))); + } + + return { + inject: ['slots'], + apply(ctx) { + ctx.effect(() => ctx.slots.inject('settings.section', () => ctx.slots.register({ + name: 'settings.section', + id: 'comfyui', + order: 15, + label: () => 'ComfyUI', + inject: () => ({}), + }, ComfyPanel)), 'comfyui: settings section'); + }, + }; + }, +}); diff --git a/lib/index.js b/lib/index.js new file mode 100644 index 0000000..1fd1c4d --- /dev/null +++ b/lib/index.js @@ -0,0 +1,669 @@ +/** + * dsh-comfyui — 把局域网 ComfyUI 接进 DSH(服务端)。 + * + * 出口: + * ① 设置页接口 + * GET /plugin/comfyui/status 地址 + 是否可达 + 版本 + GPU + 队列 + 模型 + * POST /plugin/comfyui/config 保存 baseUrl / outputDir + * POST /plugin/comfyui/test 测试连接 + * ② 工具 + * comfy_status 只读体检 + * comfy_generate_image 内置 Z-Image Turbo 工作流(实测 24s / 1024² / 8 步) + * comfy_run_workflow 跑任意 **API 格式** 工作流(UI 里「Export (API)」导出的那种), + * 支持把本地图片先上传进 ComfyUI 的 input 目录 + * comfy_upload 单独上传文件,返回可用于 LoadImage 的文件名 + * + * 为什么内置工作流是「解出来的」:ComfyUI 的 /prompt 只吃 API 格式 + * ({"节点id": {class_type, inputs}}),而前端模板是 UI 格式(nodes/links/widgets)。 + * 官方 image_z_image_turbo.json 用的是子图(definitions.subgraphs), + * 这里已按它的连线还原成 API 图,并在 .4 上实测出图成功。 + * + * 设置存放:~/.dsh/storages/dsh-comfyui/config.json(插件自己的状态文件, + * 不去改用户的 cordis.patch.yml)。优先级:状态文件 > 插件 config > 内置默认。 + */ +import { createRequire } from "node:module"; +import { realpathSync } from "node:fs"; +import { mkdir, writeFile, readFile, readdir } from "node:fs/promises"; +import { dirname, join, basename } from "node:path"; +import { homedir } from "node:os"; + +export const name = "comfyui"; + +/** 只依赖三个 seam:HTTP 路由、工具注册、日志。 */ +export const inject = ["webServer", "tools"]; + +const DEFAULTS = { + /** 留空表示未配置:地址请在设置页填写,或写进 profile 的 cordis.patch.yml */ + baseUrl: "", + /** 落盘目录;留空 = /comfyui */ + outputDir: "", + /** 单次等待上限(毫秒) */ + timeoutMs: 600_000, + pollIntervalMs: 1_200, + /** 内置 Z-Image Turbo 工作流用的模型(换模型时在设置页改) */ + unet: "z_image_turbo_bf16.safetensors", + clip: "qwen_3_4b.safetensors", + clipType: "lumina2", + vae: "ae.safetensors", +}; + +/* ── 从运行中的 dsh 安装里解析内部包(createRequire 对任何路径都成功, + * 必须逐个候选真的去 req(spec),见 AGENTS.md 记录的坑) ── */ +function safeRealpath(p) { + try { return realpathSync(p); } catch { return undefined; } +} +function resolveFromDsh(spec) { + const entry = process.argv[1]; + const candidates = []; + if (entry) { + candidates.push(entry); + const real = safeRealpath(entry); + if (real) candidates.push(real); + } + try { + const root = dirname(dirname(process.execPath)); + candidates.push(join(root, "lib", "node_modules", "@deepseek-ai", "dsh", "lib", "bin.js")); + } catch { /* 忽略 */ } + for (const c of candidates) { + try { + return createRequire(`file://${c}`)(spec); + } catch { /* 下一个 */ } + } + return undefined; +} + +function cfgOf(config) { + if (!config) return {}; + if (typeof config.get === "function") { + try { return config.get() ?? {}; } catch { return {}; } + } + return config; +} + +const now = () => Date.now(); + +function stamp() { + const d = new Date(); + const p = (n) => String(n).padStart(2, "0"); + return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`; +} + +function slug(text, max = 24) { + const s = String(text || "").replace(/[\s\n\r\t]+/g, "-").replace(/[^\p{L}\p{N}\-_]/gu, "").slice(0, max); + return s || "output"; +} + +async function uniquePath(dir, base, ext) { + const taken = new Set(await readdir(dir).catch(() => [])); + let name = `${base}.${ext}`; + let n = 1; + while (taken.has(name)) name = `${base}-${++n}.${ext}`; + return join(dir, name); +} + +/** 状态文件路径(插件自己的设置,不进 profile 配置)。 */ +function stateFile() { + const home = process.env.DSH_HOME || join(homedir(), ".dsh"); + return join(home, "storages", "dsh-comfyui", "config.json"); +} + +/** 把上游错误压成一句话。 */ +function errText(status, body) { + if (!body) return `HTTP ${status}`; + if (typeof body === "string") return `${status}: ${body.slice(0, 240)}`; + const ne = body.node_errors || {}; + const first = Object.entries(ne)[0]; + if (first) { + const [nid, info] = first; + const msg = (info?.errors || []).map((e) => `${e.message || e.type}${e.details ? `:${e.details}` : ""}`).join(";"); + return `节点 ${nid} 校验失败:${msg || "未知错误"}`; + } + const e = body.error; + if (typeof e === "string") return e; + if (e?.message) return e.message + (e.details ? `:${e.details}` : ""); + return JSON.stringify(body).slice(0, 240); +} + +export function apply(ctx, config) { + const cfgNow = () => ({ ...DEFAULTS, ...cfgOf(config) }); + + const route = (spec) => ctx.effect(() => ctx.webServer.register(spec)); + const tool = (def) => ctx.effect(() => { ctx.tools.register(def); }); + + /* ── 设置:状态文件 > config > 默认 ─────────────────────────── */ + let state = {}; + async function loadState() { + try { + state = JSON.parse(await readFile(stateFile(), "utf8")) || {}; + } catch { state = {}; } + return state; + } + async function saveState(patch) { + const merged = { ...state, ...patch }; + const file = stateFile(); + await mkdir(dirname(file), { recursive: true }); + await writeFile(file, JSON.stringify(merged, null, 2) + "\n", { mode: 0o600 }); + state = merged; + return merged; + } + const settings = () => { + const c = cfgNow(); + return { + baseUrl: String(state.baseUrl || c.baseUrl || DEFAULTS.baseUrl).replace(/\/+$/, ""), + outputDir: String(state.outputDir ?? c.outputDir ?? "").trim(), + timeoutMs: Number(c.timeoutMs ?? DEFAULTS.timeoutMs), + pollIntervalMs: Number(c.pollIntervalMs ?? DEFAULTS.pollIntervalMs), + unet: String(state.unet || c.unet || DEFAULTS.unet), + clip: String(state.clip || c.clip || DEFAULTS.clip), + clipType: String(state.clipType || c.clipType || DEFAULTS.clipType), + vae: String(state.vae || c.vae || DEFAULTS.vae), + }; + }; + + /* ── HTTP ─────────────────────────────────────────────────── */ + async function cget(path, timeoutMs = 30_000) { + const s = settings(); + if (!s.baseUrl) throw new Error("还没有配置 ComfyUI 地址 —— 打开「设置 → ComfyUI」填一个再试"); + const ctrl = new AbortController(); + const t = setTimeout(() => ctrl.abort(), timeoutMs); + try { + const resp = await fetch(`${s.baseUrl}${path}`, { + signal: ctrl.signal, + headers: { Accept: "application/json" }, + }); + const text = await resp.text(); + let body = text; + try { body = JSON.parse(text); } catch { /* 保留文本 */ } + if (!resp.ok) { + const err = new Error(errText(resp.status, body)); + err.status = resp.status; + throw err; + } + return body; + } catch (e) { + if (e?.name === "AbortError") throw new Error(`连接 ComfyUI 超时(${s.baseUrl})`); + if (e?.status) throw e; + throw new Error(`连接不上 ComfyUI(${s.baseUrl}):${e?.message || e}`); + } finally { + clearTimeout(t); + } + } + + async function cpost(path, payload, timeoutMs = 60_000) { + const s = settings(); + if (!s.baseUrl) throw new Error("还没有配置 ComfyUI 地址 —— 打开「设置 → ComfyUI」填一个再试"); + const ctrl = new AbortController(); + const t = setTimeout(() => ctrl.abort(), timeoutMs); + try { + const resp = await fetch(`${s.baseUrl}${path}`, { + method: "POST", + signal: ctrl.signal, + headers: { "Content-Type": "application/json", Accept: "application/json" }, + body: JSON.stringify(payload), + }); + const text = await resp.text(); + let body = text; + try { body = JSON.parse(text); } catch { /* 保留文本 */ } + if (!resp.ok) { + const err = new Error(errText(resp.status, body)); + err.status = resp.status; + err.body = body; + throw err; + } + return body; + } catch (e) { + if (e?.name === "AbortError") throw new Error("提交任务超时"); + if (e?.status) throw e; + throw new Error(`提交任务失败:${e?.message || e}`); + } finally { + clearTimeout(t); + } + } + + /** 探测:拿 system_stats(最轻)。 */ + async function probe() { + const s = settings(); + const stats = await cget("/system_stats", 10_000); + const sys = stats?.system || {}; + const devices = (stats?.devices || []).map((d) => ({ + name: String(d.name || ""), + type: String(d.type || ""), + vramTotalGB: Math.round((d.vram_total || 0) / 2 ** 30 * 10) / 10, + vramFreeGB: Math.round((d.vram_free || 0) / 2 ** 30 * 10) / 10, + })); + let queue = { running: 0, pending: 0 }; + try { + const q = await cget("/queue", 8_000); + queue = { running: (q.queue_running || []).length, pending: (q.queue_pending || []).length }; + } catch { /* 队列查不到不算失败 */ } + return { + baseUrl: s.baseUrl, + version: String(sys.comfyui_version || ""), + os: String(sys.os || ""), + ramTotalGB: Math.round((sys.ram_total || 0) / 2 ** 30 * 10) / 10, + devices, + queue, + }; + } + + /* ── 提交并等待 ───────────────────────────────────────────── */ + async function submit(workflow, clientId) { + const s = settings(); + const body = await cpost("/prompt", { + prompt: workflow, + client_id: clientId || `dsh-${now()}`, + }); + const id = String(body?.prompt_id || ""); + if (!id) throw new Error("ComfyUI 没有返回 prompt_id"); + return id; + } + + async function waitFor(promptId, timeoutMs) { + const s = settings(); + const deadline = now() + (timeoutMs ?? s.timeoutMs); + while (now() < deadline) { + const h = await cget(`/history/${encodeURIComponent(promptId)}`, 20_000); + const item = h?.[promptId]; + if (item) { + const status = item.status || {}; + if (status.status_str === "error" || status.completed === false && status.status_str === "error") { + const msgs = (status.messages || []) + .filter((m) => m?.[0] === "execution_error") + .map((m) => m?.[1]?.exception_message || m?.[1]?.node_type || "执行错误"); + throw new Error(`工作流执行失败:${msgs.join(";") || "未知错误"}`); + } + if (status.status_str === "success" || status.completed === true) return item; + // 有的版本成功时不写 status_str,靠 outputs 判断 + if (status.completed !== false && Object.keys(item.outputs || {}).length > 0) return item; + } + await new Promise((r) => setTimeout(r, s.pollIntervalMs)); + } + throw new Error(`等待超时(${Math.round((timeoutMs ?? s.timeoutMs) / 1000)}s)。任务可能仍在跑:${promptId}`); + } + + /** 从 history 条目里下载产物。 */ + async function collectOutputs(item, nameHint) { + const s = settings(); + const dir = s.outputDir || join(process.cwd(), "comfyui"); + await mkdir(dir, { recursive: true }); + const saved = []; + const outputs = item.outputs || {}; + for (const [nodeId, out] of Object.entries(outputs)) { + const groups = [ + ["images", "png"], + ["gifs", "webp"], + ["videos", "mp4"], + ["audio", "wav"], + ]; + for (const [key, fallbackExt] of groups) { + for (const f of out?.[key] || []) { + const filename = String(f.filename || ""); + if (!filename) continue; + const sub = String(f.subfolder || ""); + const type = String(f.type || "output"); + const url = `${settings().baseUrl}/view?filename=${encodeURIComponent(filename)}&subfolder=${encodeURIComponent(sub)}&type=${encodeURIComponent(type)}`; + const resp = await fetch(url); + if (!resp.ok) throw new Error(`下载产物失败(${filename}):HTTP ${resp.status}`); + const buf = Buffer.from(await resp.arrayBuffer()); + const ext = (filename.match(/\.([a-z0-9]+)$/i)?.[1] || fallbackExt).toLowerCase(); + const file = await uniquePath(dir, `${stamp()}-${slug(nameHint || filename)}`, ext); + await writeFile(file, buf, { mode: 0o644 }); + saved.push({ nodeId, kind: key, path: file, bytes: buf.length }); + } + } + } + return saved; + } + + /* ── 内置工作流:Z-Image Turbo 文生图 ──────────────────────── + * 由官方 image_z_image_turbo.json 的子图连线还原而来,已在 .4 实测成功。 */ + function buildZImageWorkflow({ prompt, width, height, steps, seed, prefix }) { + const s = settings(); + return { + "30": { class_type: "CLIPLoader", inputs: { clip_name: s.clip, type: s.clipType, device: "default" } }, + "29": { class_type: "VAELoader", inputs: { vae_name: s.vae } }, + "28": { class_type: "UNETLoader", inputs: { unet_name: s.unet, weight_dtype: "default" } }, + "27": { class_type: "CLIPTextEncode", inputs: { clip: ["30", 0], text: prompt } }, + "33": { class_type: "ConditioningZeroOut", inputs: { conditioning: ["27", 0] } }, + "11": { class_type: "ModelSamplingAuraFlow", inputs: { model: ["28", 0], shift: 3 } }, + "13": { class_type: "EmptySD3LatentImage", inputs: { width, height, batch_size: 1 } }, + "3": { + class_type: "KSampler", + inputs: { + model: ["11", 0], positive: ["27", 0], negative: ["33", 0], latent_image: ["13", 0], + seed, steps, cfg: 1, sampler_name: "res_multistep", scheduler: "simple", denoise: 1, + }, + }, + "8": { class_type: "VAEDecode", inputs: { samples: ["3", 0], vae: ["29", 0] } }, + "9": { class_type: "SaveImage", inputs: { images: ["8", 0], filename_prefix: prefix } }, + }; + } + + async function generateImage(args) { + const prompt = String(args?.prompt || "").trim(); + if (!prompt) throw new Error("prompt 不能为空"); + const round16 = (v, fallback) => { + const n = Number(v); + if (!Number.isFinite(n) || n <= 0) return fallback; + return Math.max(256, Math.min(2048, Math.round(n / 16) * 16)); + }; + const width = round16(args?.width, 1024); + const height = round16(args?.height, 1024); + const steps = Math.max(1, Math.min(40, Number(args?.steps) || 8)); + const seed = Number.isFinite(Number(args?.seed)) ? Number(args.seed) : Math.floor(Math.random() * 1e12); + const t0 = now(); + + const wf = buildZImageWorkflow({ prompt, width, height, steps, seed, prefix: "dsh-comfy" }); + const id = await submit(wf); + const item = await waitFor(id); + const saved = await collectOutputs(item, prompt); + if (!saved.length) throw new Error("工作流跑完了,但没有产出图片"); + const first = saved[0]; + return { + path: first.path, + bytes: first.bytes, + width, + height, + steps, + seed, + model: settings().unet, + elapsedMs: now() - t0, + promptId: id, + }; + } + + /* ── 上传本地文件到 ComfyUI 的 input 目录 ─────────────────── */ + async function uploadFile(filePath, overrideName) { + const { readFile: rf } = await import("node:fs/promises"); + let buf; + try { + buf = await rf(filePath); + } catch (e) { + throw new Error(`读不到文件 ${filePath}:${e?.message || e}`); + } + const nm = overrideName || basename(filePath); + const s = settings(); + const form = new FormData(); + form.append("image", new Blob([buf]), nm); + form.append("overwrite", "true"); + const resp = await fetch(`${s.baseUrl}/upload/image`, { method: "POST", body: form }); + const text = await resp.text(); + let body = text; + try { body = JSON.parse(text); } catch { /* 文本 */ } + if (!resp.ok) throw new Error(`上传失败:${errText(resp.status, body)}`); + return { + name: String(body?.name || nm), + subfolder: String(body?.subfolder || ""), + type: String(body?.type || "input"), + }; + } + + /* ── 设置页路由 ───────────────────────────────────────────── */ + const PREFIX = "/plugin/comfyui"; + + function respond(res, code, body) { + const text = JSON.stringify(body); + res.writeHead(code, { + "Content-Type": "application/json; charset=utf-8", + "Cache-Control": "no-store", + "Content-Length": Buffer.byteLength(text), + }); + res.end(text); + } + + async function readBody(req) { + const chunks = []; + let size = 0; + for await (const chunk of req) { + size += chunk.length; + if (size > 64 * 1024) throw new Error("请求体过大"); + chunks.push(chunk); + } + if (!chunks.length) return {}; + try { return JSON.parse(Buffer.concat(chunks).toString("utf8")); } catch { throw new Error("请求体不是合法 JSON"); } + } + + route({ + kind: "exact", + path: `${PREFIX}/status`, + async handler(req, res) { + if (req.method !== "GET" && req.method !== "HEAD") return respond(res, 405, { ok: false, error: "只支持 GET" }); + const s = settings(); + if (!s.baseUrl) { + return respond(res, 200, { ok: true, reachable: false, baseUrl: "", error: "还没有配置 ComfyUI 地址" }); + } + try { + const info = await probe(); + respond(res, 200, { ok: true, reachable: true, ...info, outputDir: s.outputDir || join(process.cwd(), "comfyui"), models: { unet: s.unet, clip: s.clip, clipType: s.clipType, vae: s.vae } }); + } catch (e) { + respond(res, 200, { ok: true, reachable: false, baseUrl: s.baseUrl, error: String(e?.message || e) }); + } + }, + }); + + route({ + kind: "exact", + path: `${PREFIX}/config`, + async handler(req, res) { + if (req.method !== "POST") return respond(res, 405, { ok: false, error: "只支持 POST" }); + try { + const body = await readBody(req); + const patch = {}; + if (typeof body.baseUrl === "string") { + const url = body.baseUrl.trim().replace(/\/+$/, ""); + if (url && !/^https?:\/\//i.test(url)) return respond(res, 400, { ok: false, error: "地址要以 http:// 或 https:// 开头" }); + patch.baseUrl = url; + } + if (typeof body.outputDir === "string") patch.outputDir = body.outputDir.trim(); + for (const k of ["unet", "clip", "clipType", "vae"]) { + if (typeof body[k] === "string" && body[k].trim()) patch[k] = body[k].trim(); + } + const merged = await saveState(patch); + respond(res, 200, { ok: true, ...settings(), saved: Object.keys(patch) }); + } catch (e) { + ctx.logger?.warn?.("comfyui: 保存设置失败 %s", e?.message || e); + respond(res, 500, { ok: false, error: String(e?.message || e) }); + } + }, + }); + + route({ + kind: "exact", + path: `${PREFIX}/test`, + async handler(req, res) { + if (req.method !== "POST" && req.method !== "GET") return respond(res, 405, { ok: false, error: "只支持 GET / POST" }); + try { + const info = await probe(); + respond(res, 200, { ok: true, ...info }); + } catch (e) { + respond(res, 400, { ok: false, error: String(e?.message || e) }); + } + }, + }); + + /* ── 工具 ────────────────────────────────────────────────── */ + const defineTool = resolveFromDsh("@deepseek-ai/dsh-tools")?.defineTool; + const registered = []; + const registerTool = (def) => { registered.push(def.name); ctx.effect(() => { ctx.tools.register(def); }); }; + if (!defineTool) { + ctx.logger?.warn?.("comfyui: 未解析到 @deepseek-ai/dsh-tools,工具不注册(设置页仍可用)"); + return; + } + + registerTool(defineTool({ + name: "comfy_status", + description: "查看局域网 ComfyUI 的状态:是否连得上、版本、GPU 显存、队列、以及内置工作流用的模型。不消耗算力。", + parameters: {}, + output: { + schema: { + type: "object", + additionalProperties: false, + properties: { + reachable: { type: "boolean" }, + baseUrl: { type: "string" }, + version: { type: "string" }, + gpu: { type: "string", description: "第一块 GPU 的名字;空串表示没有" }, + vramFreeGB: { type: "number" }, + running: { type: "integer" }, + pending: { type: "integer" }, + unet: { type: "string" }, + error: { type: "string", description: "连不上时的原因;正常时为空串" }, + }, + }, + render: (_a, v) => [{ + type: "text", + text: v.reachable + ? `ComfyUI ${v.version} @ ${v.baseUrl}|${v.gpu}(空闲 ${v.vramFreeGB}GB)|队列 ${v.running} 运行 / ${v.pending} 排队|内置模型 ${v.unet}` + : `连不上 ComfyUI(${v.baseUrl}):${v.error}`, + }], + }, + async execute() { + const s = settings(); + if (!s.baseUrl) { + return respond(res, 200, { ok: true, reachable: false, baseUrl: "", error: "还没有配置 ComfyUI 地址" }); + } + try { + const info = await probe(); + const gpu = info.devices[0] || {}; + return { + reachable: true, baseUrl: info.baseUrl, version: info.version, + gpu: gpu.name || "", vramFreeGB: gpu.vramFreeGB || 0, + running: info.queue.running, pending: info.queue.pending, + unet: s.unet, error: "", + }; + } catch (e) { + return { + reachable: false, baseUrl: s.baseUrl, version: "", gpu: "", vramFreeGB: 0, + running: 0, pending: 0, unet: s.unet, error: String(e?.message || e), + }; + } + }, + })); + + registerTool(defineTool({ + name: "comfy_generate_image", + description: "用 .4 那台 ComfyUI 出图(内置 Z-Image Turbo 工作流,1024² / 8 步约 25 秒)。结果落盘并返回绝对路径。适合作图要快、想用本地显卡的时候。", + parameters: { + prompt: { type: "string", required: true, description: "画面描述,英文或中文都行" }, + width: { type: "integer", description: "宽度,默认 1024,会自动对齐到 16 的倍数,范围 256–2048" }, + height: { type: "integer", description: "高度,默认 1024,同上" }, + steps: { type: "integer", description: "采样步数,默认 8(turbo 模型 8 步够用),最多 40" }, + seed: { type: "integer", description: "随机种子;不给就随机" }, + }, + output: { + schema: { + type: "object", + additionalProperties: false, + properties: { + path: { type: "string" }, + bytes: { type: "integer" }, + width: { type: "integer" }, + height: { type: "integer" }, + steps: { type: "integer" }, + seed: { type: "integer" }, + model: { type: "string" }, + elapsedMs: { type: "integer" }, + promptId: { type: "string" }, + }, + }, + render: (_a, v) => [{ + type: "text", + text: `已生成图片:${v.path}\n${v.width}×${v.height},${(v.bytes / 1024).toFixed(0)}KB,${v.steps} 步,用时 ${(v.elapsedMs / 1000).toFixed(1)}s(${v.model})`, + }], + }, + async execute(args) { + return generateImage(args || {}); + }, + })); + + registerTool(defineTool({ + name: "comfy_run_workflow", + description: + "在 ComfyUI 上跑任意工作流(必须是 API 格式:在 ComfyUI 界面里用「导出 (API)」得到的那种 {\"节点id\":{class_type,inputs}})。会等它跑完并把产物下载到本地,返回文件路径。需要本地图片做输入时,先调 comfy_upload 拿到文件名,再在 workflow 里引用。", + parameters: { + workflow: { type: "string", required: true, description: "API 格式工作流 JSON(字符串形式)" }, + nameHint: { type: "string", description: "给产物文件起名用,通常填提示词摘要" }, + timeoutSeconds: { type: "integer", description: "最多等多久,默认 600 秒" }, + }, + output: { + schema: { + type: "object", + additionalProperties: false, + properties: { + promptId: { type: "string" }, + files: { type: "array", items: { type: "string" }, description: "下载到本地的产物路径" }, + bytes: { type: "integer" }, + elapsedMs: { type: "integer" }, + count: { type: "integer" }, + }, + }, + render: (_a, v) => [{ + type: "text", + text: v.count + ? `工作流跑完:${v.count} 个产物(${(v.bytes / 1024 / 1024).toFixed(1)}MB,${(v.elapsedMs / 1000).toFixed(1)}s)\n` + v.files.join("\n") + : "工作流跑完了,但没有下载到任何产物(检查 SaveImage / SaveVideo 之类节点)", + }], + }, + async execute(args) { + const raw = String(args?.workflow || "").trim(); + if (!raw) throw new Error("workflow 不能为空"); + let wf; + try { + wf = JSON.parse(raw); + } catch (e) { + throw new Error(`workflow 不是合法 JSON:${e?.message || e}。注意要 API 格式,不是界面里的 UI 格式`); + } + if (!wf || typeof wf !== "object" || Array.isArray(wf)) { + throw new Error("workflow 必须是 {节点id: {class_type, inputs}} 形式的对象(API 格式)"); + } + const firstKey = Object.keys(wf)[0]; + if (firstKey && !wf[firstKey]?.class_type) { + throw new Error("这看起来是 UI 格式(有 nodes/links)。请在 ComfyUI 界面里用「导出 (API)」再导出一次"); + } + const t0 = now(); + const id = await submit(wf); + const item = await waitFor(id, (Number(args?.timeoutSeconds) > 0 ? Number(args.timeoutSeconds) : undefined) ? Number(args.timeoutSeconds) * 1000 : undefined); + const saved = await collectOutputs(item, String(args?.nameHint || "workflow")); + return { + promptId: id, + files: saved.map((s) => s.path), + bytes: saved.reduce((a, b) => a + b.bytes, 0), + elapsedMs: now() - t0, + count: saved.length, + }; + }, + })); + + registerTool(defineTool({ + name: "comfy_upload", + description: "把本地文件上传到 ComfyUI 的 input 目录,返回文件名;用于给图生视频 / 图片编辑这类需要本地输入的工作流。", + parameters: { + path: { type: "string", required: true, description: "本地文件绝对路径" }, + name: { type: "string", description: "上传后在 ComfyUI 里的文件名;不给就用原文件名" }, + }, + output: { + schema: { + type: "object", + additionalProperties: false, + properties: { + name: { type: "string" }, + subfolder: { type: "string" }, + type: { type: "string" }, + }, + }, + render: (_a, v) => [{ type: "text", text: `已上传为 ${v.subfolder ? v.subfolder + "/" : ""}${v.name}` }], + }, + async execute(args) { + const p = String(args?.path || "").trim(); + if (!p) throw new Error("path 不能为空"); + return uploadFile(p, args?.name ? String(args.name) : undefined); + }, + })); + + // 首次启动读一次状态文件 + ctx.effect(() => { + loadState().catch(() => {}); + }); + + ctx.logger?.info?.("comfyui: 已就绪(设置页 + %d 个工具)", registered.length); +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..5afdcf4 --- /dev/null +++ b/package.json @@ -0,0 +1,51 @@ +{ + "name": "@wangjinding/dsh-comfyui", + "version": "1.0.0", + "type": "module", + "description": "把局域网 ComfyUI 接进 DSH:设置页配置地址并测试,提供 comfy_generate_image(内置 Z-Image Turbo)、comfy_run_workflow、comfy_upload、comfy_status 工具。", + "license": "MIT", + "main": "./lib/index.js", + "exports": { + ".": "./lib/index.js", + "./client": "./lib/client.js", + "./cordis.patch.yml": "./cordis.patch.yml", + "./package.json": "./package.json" + }, + "files": [ + "lib", + "cordis.patch.yml", + "README.md", + "LICENSE" + ], + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + }, + "client": { + "platform": "web", + "inject": [ + "@deepseek-ai/dsh-client-connection", + "@deepseek-ai/dsh-client-ui-settings" + ] + } + }, + "author": "wangjinding", + "homepage": "https://github.com/wangjinding/dsh-comfyui#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/wangjinding/dsh-comfyui.git", + "directory": "." + }, + "keywords": [ + "dsh", + "dsh-plugin", + "comfyui", + "stable-diffusion", + "image", + "video", + "workflow" + ], + "engines": { + "node": "^22.19.0 || >=24.0.0" + } +}