mcp-comfyui-proxy 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +169 -2
- package/extension/bridge.js +305 -0
- package/extension/validation.js +133 -0
- package/package.json +46 -4
- package/src/adapter.js +25 -0
- package/src/backend.js +176 -0
- package/src/browser.js +156 -0
- package/src/cache-promise.js +46 -0
- package/src/cli-runner.js +31 -0
- package/src/cli.js +57 -0
- package/src/daemon.js +85 -0
- package/src/files.js +66 -0
- package/src/index.js +9 -0
- package/src/inject.js +74 -0
- package/src/log.js +41 -0
- package/src/mcp.js +97 -0
- package/src/nodes.js +55 -0
- package/src/ports.js +39 -0
- package/src/proxy.js +197 -0
- package/src/retry-promise.js +11 -0
- package/src/sessions.js +209 -0
- package/src/settings.js +12 -0
- package/src/stdio.js +16 -0
- package/src/tools.js +48 -0
- package/src/workflow.js +44 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 kucharskill
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,170 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ComfyUI MCP Proxy
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Control ComfyUI workflows through MCP and a local reverse proxy. The proxy opens ComfyUI in your browser and injects JavaScript for working with its actual workflow tabs. No custom nodes, browser extension, userscript, Comfy CLI, Python environment or GPU are required on the MCP machine.
|
|
4
|
+
|
|
5
|
+
Requirements: an existing ComfyUI HTTP(S) backend and Node.js 24.12 or later with npm. All runtime code is JavaScript, with no build step or compiler. Rendering uses your backend and may incur its normal GPU/provider charges.
|
|
6
|
+
|
|
7
|
+
## Start through npx
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npx -y --prefer-online mcp-comfyui-proxy@latest mcp
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
A typical MCP client configuration is:
|
|
14
|
+
|
|
15
|
+
```json
|
|
16
|
+
{
|
|
17
|
+
"mcpServers": {
|
|
18
|
+
"comfyui": {
|
|
19
|
+
"command": "npx",
|
|
20
|
+
"args": ["-y", "--prefer-online", "mcp-comfyui-proxy@latest", "mcp"]
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
For Codex:
|
|
27
|
+
|
|
28
|
+
```toml
|
|
29
|
+
[mcp_servers.comfyui]
|
|
30
|
+
command = "npx"
|
|
31
|
+
args = ["-y", "--prefer-online", "mcp-comfyui-proxy@latest", "mcp"]
|
|
32
|
+
startup_timeout_sec = 120
|
|
33
|
+
tool_timeout_sec = 180
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The stdio adapter writes MCP messages only to stdout. Allow at least 180 seconds for tool calls involving file transfers. npm caches the package and dependencies and checks for updates through `--prefer-online`.
|
|
37
|
+
|
|
38
|
+
Tool discovery does not start HTTP. The first valid tool call starts a shared background HTTP server when needed, normally at `http://127.0.0.1:37861/mcp`. Set `COMFY_MCP_PORT` to select another port. HTTP and all session proxies bind to `127.0.0.1` only.
|
|
39
|
+
|
|
40
|
+
## Connect and edit
|
|
41
|
+
|
|
42
|
+
Tool-call examples use JavaScript object notation. Every `file` must be an absolute path on the MCP machine; Windows paths such as `C:/work/workflow.json` are also supported.
|
|
43
|
+
|
|
44
|
+
```js
|
|
45
|
+
connect({ url: "http://127.0.0.1:8188/" })
|
|
46
|
+
status({ session_id: "<session_id>" })
|
|
47
|
+
// Select an id from workflows_opened.
|
|
48
|
+
workflow_download({ id: "<workflow_id>", file: "/absolute/path/workflow.json" })
|
|
49
|
+
// Edit the local standard ComfyUI Workflow JSON, then:
|
|
50
|
+
workflow_upload({ id: "<workflow_id>", file: "/absolute/path/workflow.json" })
|
|
51
|
+
workflow_save({ id: "<workflow_id>" })
|
|
52
|
+
run({ id: "<workflow_id>" })
|
|
53
|
+
backend_status({ session_id: "<session_id>" })
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
`connect` probes reachability, creates an isolated proxy and opens its URL in your default browser. A login page, redirect, 401 or 403 counts as reachable. Log in through the proxied page when required. The injected bridge reports open workflow tabs and displays a connection banner with the real backend URL.
|
|
57
|
+
|
|
58
|
+
`session_id` selects a backend and its stored authentication. Workflow `id` selects one exact internal editor tab across browser tabs and windows. Obtain IDs from the responses; do not derive them from names or UUIDs. `workflow_uuid` is metadata for correlating executions, not an editor routing ID.
|
|
59
|
+
|
|
60
|
+
Reading or modifying a workflow activates its internal tab. Creating or opening a workflow uses the last focused connected browser page, or the first connected page if no focus was reported. It does not switch operating-system windows or browser tabs.
|
|
61
|
+
|
|
62
|
+
## Tools
|
|
63
|
+
|
|
64
|
+
The CLI supplies descriptions and JSON Schemas from one shared definition module.
|
|
65
|
+
|
|
66
|
+
| Tool | Purpose |
|
|
67
|
+
|---|---|
|
|
68
|
+
| `connect` | Probe a backend, create a proxy session and open the browser. |
|
|
69
|
+
| `status` | List sessions and open workflow tabs, with diagnostic log paths. |
|
|
70
|
+
| `disconnect` | Close one proxy session without stopping ComfyUI. |
|
|
71
|
+
| `backend_status` | Jobs accepted through proxy sessions, including UI runs. |
|
|
72
|
+
| `backend_history` | All backend jobs, including runs outside proxy sessions. |
|
|
73
|
+
| `backend_node_info` | Search node types or read one native object_info definition. |
|
|
74
|
+
| `backend_inputs_list` | Return the backend input list and its reported root scope. |
|
|
75
|
+
| `backend_workflow_list` | List saved workflow files recursively, without downloading graphs. |
|
|
76
|
+
| `backend_upload` | Upload a local file to the backend input root. |
|
|
77
|
+
| `backend_download` | Download an input, output or temporary file to a local path. |
|
|
78
|
+
| `workflow_new` | Create and activate a blank workflow. |
|
|
79
|
+
| `workflow_open` | Open a saved workflow, or report its existing ID if already open. |
|
|
80
|
+
| `workflow_download` | Write the current Workflow JSON to a local file, including unsaved edits. |
|
|
81
|
+
| `workflow_upload` | Validate a local Workflow JSON and replace the selected editor graph. |
|
|
82
|
+
| `workflow_save` | Save a workflow, optionally under a new name or path. |
|
|
83
|
+
| `run` | Submit the selected graph once and return acceptance or validation errors. |
|
|
84
|
+
|
|
85
|
+
`status`, `backend_status` and `backend_history` accept an optional `session_id`; omission covers all connected sessions. Job results include all active jobs and jobs finished in the last 12 hours. Outputs provide `path` and `type` for download, not media contents or URLs. Errors omit full tracebacks.
|
|
86
|
+
|
|
87
|
+
## Workflow validation and saving
|
|
88
|
+
|
|
89
|
+
Transfers use standard editor Workflow JSON: nodes, links, groups, positions, widget values, subgraphs and other graph metadata. This is not the API execution-prompt format.
|
|
90
|
+
|
|
91
|
+
`workflow_upload` parses JSON, checks its basic structure, refreshes the frontend node catalog, and validates a candidate in a detached frontend graph. Supported checks cover the native workflow schema, link consistency and missing node types, models and media references. Only successful validation activates and replaces the target graph. Failed checks return a compact issue list without replacing it.
|
|
92
|
+
|
|
93
|
+
Validation uses internal ComfyUI frontend APIs and can require compatibility updates. Unsupported APIs or failed catalog refreshes block replacement. These checks do not render or guarantee backend execution, parameter correctness or model compatibility. The backend still validates a run.
|
|
94
|
+
|
|
95
|
+
Upload changes the editor only. Saving and rendering are separate operations. `workflow_save` without a name uses its existing path; a temporary workflow returns `NAME_REQUIRED`. A new name/path cannot overwrite another saved workflow. Saving under a new name may create a new tab: use the returned ID. `temporary` means there is no saved backend file; `modified` means the graph differs from its loaded or saved state.
|
|
96
|
+
|
|
97
|
+
Operations on one page are queued, but there is no optimistic concurrency token. A later upload can overwrite edits made since download. After a timeout, inspect editor/backend status before retrying a save, upload or run: the previous operation may already have completed.
|
|
98
|
+
|
|
99
|
+
## Files and node discovery
|
|
100
|
+
|
|
101
|
+
```js
|
|
102
|
+
backend_upload({ session_id: "<session_id>", file: "/absolute/path/reference.png" })
|
|
103
|
+
backend_download({
|
|
104
|
+
session_id: "<session_id>", path: "renders/frame.png", type: "output",
|
|
105
|
+
file: "/absolute/path/frame.png"
|
|
106
|
+
})
|
|
107
|
+
backend_node_info({ session_id: "<session_id>", query: "image resize", limit: 10 })
|
|
108
|
+
backend_node_info({ session_id: "<session_id>", node_type: "LoadImage" })
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Upload supports the input root only, an optional filename, and native backend collision handling. There is no subfolder or overwrite parameter. Use the actual returned path in the workflow node; upload does not modify a graph. Download supports existing subfolders and input/output/temp types, streams to disk and refuses to overwrite an existing local file. Parent directories must exist.
|
|
112
|
+
|
|
113
|
+
`backend_inputs_list` preserves backend entries and ordering. `root_only` becomes false when an entry contains a folder separator. It does not scan workflow references or invent a recursive listing.
|
|
114
|
+
|
|
115
|
+
Node search returns compact paged summaries; an exact `node_type` returns its full native definition. Successful validated definitions are cached per session without a TTL. Successful uploads through the proxy and changed Authorization invalidate that cache. External backend changes require reconnecting. Frontend workflow validation refreshes its own catalog independently.
|
|
116
|
+
|
|
117
|
+
## Authentication and proxy behavior
|
|
118
|
+
|
|
119
|
+
Each session has an in-memory cookie jar, including upstream HttpOnly and Secure cookies, and the latest browser Authorization header. Subsequent browser requests and MCP backend operations reuse it. Credentials are not returned in status or logs. Backend cookies are not exposed as localhost browser cookies, so separate proxy ports do not share sessions.
|
|
120
|
+
|
|
121
|
+
HTTPS and WSS are supported, but upstream certificate verification is intentionally disabled. The local proxy remains HTTP. Basic Auth challenges pass through to the browser; same-backend redirects are rewritten to the proxy. OAuth, captcha, JavaScript-managed cookies, absolute URLs and secure-context requirements may need additional compatibility work.
|
|
122
|
+
|
|
123
|
+
HTTP, WebSocket, uploads, downloads and Range responses are proxied. Selected UTF-8/ASCII HTML responses are decompressed and buffered for injection; binary content remains streamed. Content Security Policy is not relaxed, so a restrictive policy can prevent the bridge from loading. Nothing is installed on the backend.
|
|
124
|
+
|
|
125
|
+
## Lifetime and updates
|
|
126
|
+
|
|
127
|
+
The stdio adapter fetches a CLI manifest at startup and each `tools/list`, then delegates each call to a fresh CLI process through `npx --prefer-online ...@latest`. A changed manifest emits the standard tool-list-changed notification; the client controls when it refreshes. Updating the adapter itself requires restarting it.
|
|
128
|
+
|
|
129
|
+
HTTP retains its loaded version and sessions until it stops. Compatible CLI releases reuse it through a separate `protocol_version`. Updates do not forcibly restart it. After exit, the next valid call starts HTTP from the current CLI. A new tool may be unavailable on an older HTTP runtime until restart.
|
|
130
|
+
|
|
131
|
+
HTTP shuts down after 30 minutes without meaningful activity. Tool calls, mutating browser requests, HTML navigation and media downloads reset the timer. Discovery, health checks, background polling and heartbeat do not. Shutdown forgets sessions, authentication and workflow IDs, without stopping ComfyUI or rendering. Old IDs fail explicitly; connect again.
|
|
132
|
+
|
|
133
|
+
Connecting again to the same normalized backend URL replaces its previous session after the new proxy and browser opening succeed. Its first proxy port is remembered for future connections. A busy port uses a free fallback without overwriting that preference.
|
|
134
|
+
|
|
135
|
+
## CLI and development
|
|
136
|
+
|
|
137
|
+
```sh
|
|
138
|
+
npx -y --prefer-online mcp-comfyui-proxy@latest --version
|
|
139
|
+
npx -y --prefer-online mcp-comfyui-proxy@latest --help
|
|
140
|
+
npx -y --prefer-online mcp-comfyui-proxy@latest --tool-manifest
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
The executable is `comfyui-mcp`. `--tool-manifest` prints JSON without HTTP. `--execute-tool NAME` reads one JSON argument object from stdin and prints one MCP result as JSON.
|
|
144
|
+
|
|
145
|
+
```sh
|
|
146
|
+
git clone https://github.com/kucharskill/mcp-comfyui-proxy.git
|
|
147
|
+
cd mcp-comfyui-proxy
|
|
148
|
+
npm ci
|
|
149
|
+
npm run start:stdio
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Local stdio uses `--local` to run this checkout's CLI without npm lookups. `npm start` runs HTTP manually. Files in `extension/` are served directly: refresh the page after editing them. Restart HTTP after changing server code. Development checks are available through `npm test`.
|
|
153
|
+
|
|
154
|
+
For an optional Windows CPU-only ComfyUI fixture, `test-confy-server.cmd` uses existing `uvx` and `git` commands to prepare ComfyUI 0.45.0 under `%TEMP%`, without models or Manager. This developer script is excluded from npm and is not required at runtime.
|
|
155
|
+
|
|
156
|
+
## Diagnostics
|
|
157
|
+
|
|
158
|
+
`status` includes `reverse_proxy_log_path`. Session logs record important requests, writes, status codes, errors and WebSocket lifecycle events. Request bodies, credential values and URL query values are omitted. Logs do not capture arbitrary browser JavaScript errors or full backend tracebacks.
|
|
159
|
+
|
|
160
|
+
Runtime files use the operating-system temporary directory:
|
|
161
|
+
|
|
162
|
+
- `comfyui-mcp/<session_id>.jsonl`: proxy diagnostics.
|
|
163
|
+
- `comfyui-mcp/proxy-ports.json`: preferred proxy ports.
|
|
164
|
+
- `comfyui-mcp-runtime/http-<port>.log`: HTTP process output.
|
|
165
|
+
|
|
166
|
+
Files may outlive a process. Sessions and credentials are not restored from them. `extension/` contains injected page JavaScript, not a separately installed browser extension. TLS keys/certificates in `test/fixtures/` are synthetic and excluded from npm.
|
|
167
|
+
|
|
168
|
+
## License
|
|
169
|
+
|
|
170
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import { createWorkflowValidator } from './validation.js';
|
|
2
|
+
|
|
3
|
+
console.log('[ComfyUI MCP] Injected script loaded');
|
|
4
|
+
|
|
5
|
+
(async function () {
|
|
6
|
+
if (window.top !== window.self) return;
|
|
7
|
+
window.__comfyMcpBridge?.dispose();
|
|
8
|
+
const clone = value => JSON.parse(JSON.stringify(value));
|
|
9
|
+
const fail = code => { throw Object.assign(new Error(code), { code }); };
|
|
10
|
+
const heartbeatInterval = 5000, heartbeatTimeout = 10_000;
|
|
11
|
+
let app, api, workflows, socket, stopped = false, suspended = false, reconnectTimer, heartbeatTimer, replyTimer;
|
|
12
|
+
let unsubscribe, unwatchActions, attempts = 0, lastInventory = '', syncing = false, queue = Promise.resolve();
|
|
13
|
+
let banner, backendUrl = '', connected = false;
|
|
14
|
+
const ids = new WeakMap(), tabs = new Map();
|
|
15
|
+
window.__comfyMcpBridge = {
|
|
16
|
+
status: () => ({ connected: connected && socket?.readyState === WebSocket.OPEN, workflow_tab_ids: [...tabs.keys()] }),
|
|
17
|
+
dispose() {
|
|
18
|
+
stopped = true; clearTimeout(reconnectTimer); clearHeartbeat(); connected = false; unsubscribe?.(); unwatchActions?.();
|
|
19
|
+
api?.removeEventListener('graphChanged', scheduleSync);
|
|
20
|
+
window.removeEventListener('pagehide', pause); window.removeEventListener('pageshow', resume);
|
|
21
|
+
window.removeEventListener('focus', focus);
|
|
22
|
+
socket?.close(1000, 'Bridge disposed'); tabs.clear();
|
|
23
|
+
banner?.remove();
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
function clearHeartbeat() { clearTimeout(heartbeatTimer); clearTimeout(replyTimer); }
|
|
27
|
+
function updateBanner(isConnected, url) {
|
|
28
|
+
connected = isConnected;
|
|
29
|
+
if (url) backendUrl = url;
|
|
30
|
+
if (!backendUrl) return;
|
|
31
|
+
if (!banner) {
|
|
32
|
+
banner = document.createElement('div');
|
|
33
|
+
banner.id = 'comfy-mcp-banner';
|
|
34
|
+
const root = banner.attachShadow({ mode: 'open' });
|
|
35
|
+
root.innerHTML = `<style>
|
|
36
|
+
:host { position:fixed; top:6px; left:50%; transform:translateX(-50%); z-index:2147483646;
|
|
37
|
+
max-width:calc(100vw - 24px); pointer-events:none; }
|
|
38
|
+
.banner { display:flex; align-items:center; gap:10px; padding:4px 10px; border:1px solid #377451;
|
|
39
|
+
border-radius:6px; background:rgba(20,39,28,.96); color:#a7edbf; box-shadow:0 2px 8px #0003;
|
|
40
|
+
font:11px/18px system-ui,sans-serif; white-space:nowrap; }
|
|
41
|
+
.status { font-weight:600; display:flex; align-items:center; gap:6px; }
|
|
42
|
+
.status::before { content:''; width:6px; height:6px; border-radius:50%; background:currentColor; }
|
|
43
|
+
.url { min-width:0; overflow:hidden; text-overflow:ellipsis; color:#c5d3ca; }
|
|
44
|
+
:host([data-connected="false"]) .banner { border-color:#b45858; background:rgba(55,23,23,.96); color:#ffaaaa; }
|
|
45
|
+
:host([data-connected="false"]) .url { color:#e1c4c4; }
|
|
46
|
+
</style><div class="banner" role="status"><span class="status"></span><span class="url"></span></div>`;
|
|
47
|
+
document.body.append(banner);
|
|
48
|
+
}
|
|
49
|
+
banner.dataset.connected = String(isConnected);
|
|
50
|
+
banner.shadowRoot.querySelector('.status').textContent = isConnected ? 'MCP Connect' : 'MCP Disconnect';
|
|
51
|
+
banner.shadowRoot.querySelector('.url').textContent = `Real URL: ${backendUrl}`;
|
|
52
|
+
}
|
|
53
|
+
// Only startup waits; the inventory is maintained through ComfyUI state events.
|
|
54
|
+
for (let n = 0; n < 300 && !stopped; n++) {
|
|
55
|
+
app = window.comfyAPI?.app?.app; api = window.comfyAPI?.api?.api;
|
|
56
|
+
workflows = app?.extensionManager?.workflow;
|
|
57
|
+
if (workflows?.openWorkflows && app.isGraphReady) break;
|
|
58
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
59
|
+
}
|
|
60
|
+
if (stopped || !workflows?.openWorkflows || !app?.isGraphReady) return;
|
|
61
|
+
if (typeof workflows.$subscribe !== 'function' || typeof workflows.$onAction !== 'function' ||
|
|
62
|
+
typeof app.rootGraph?.serialize !== 'function' || typeof app.loadGraphData !== 'function' || typeof api?.addEventListener !== 'function') {
|
|
63
|
+
console.warn('[ComfyUI MCP] Unsupported editor API; workflow bridge inactive'); return;
|
|
64
|
+
}
|
|
65
|
+
const validateWorkflow = createWorkflowValidator(app);
|
|
66
|
+
|
|
67
|
+
function sync() {
|
|
68
|
+
if (stopped) return;
|
|
69
|
+
const open = workflows.openWorkflows;
|
|
70
|
+
for (const [id, wf] of tabs) if (!open.includes(wf)) { tabs.delete(id); ids.delete(wf); }
|
|
71
|
+
for (const wf of open) if (!ids.has(wf)) { const id = crypto.randomUUID(); ids.set(wf, id); tabs.set(id, wf); }
|
|
72
|
+
const inventory = [...tabs].map(([id, wf]) => ({ workflow_tab_id: id, name: wf.filename ?? '',
|
|
73
|
+
active: workflows.activeWorkflow === wf, modified: Boolean(wf.isModified), temporary: Boolean(wf.isTemporary),
|
|
74
|
+
path: wf.isTemporary ? null : wf.path ?? null,
|
|
75
|
+
workflow_uuid: (workflows.activeWorkflow === wf ? app.rootGraph.id : wf.activeState?.id) ?? null }));
|
|
76
|
+
const encoded = JSON.stringify({ type: 'tabs', tabs: inventory });
|
|
77
|
+
if (socket?.readyState === WebSocket.OPEN && encoded !== lastInventory) { socket.send(encoded); lastInventory = encoded; }
|
|
78
|
+
}
|
|
79
|
+
function scheduleSync() {
|
|
80
|
+
if (syncing || stopped) return;
|
|
81
|
+
syncing = true; queueMicrotask(() => { syncing = false; sync(); });
|
|
82
|
+
}
|
|
83
|
+
unsubscribe = workflows.$subscribe(scheduleSync, { detached: true, flush: 'post' });
|
|
84
|
+
unwatchActions = workflows.$onAction(({ after, onError }) => { after(scheduleSync); onError(scheduleSync); }, true);
|
|
85
|
+
api.addEventListener('graphChanged', scheduleSync);
|
|
86
|
+
function requireTab(id) {
|
|
87
|
+
sync(); const wf = tabs.get(id);
|
|
88
|
+
if (!wf || !workflows.openWorkflows.includes(wf)) fail('TAB_CLOSED');
|
|
89
|
+
return wf;
|
|
90
|
+
}
|
|
91
|
+
function ready(wf) {
|
|
92
|
+
sync();
|
|
93
|
+
requireTab(ids.get(wf));
|
|
94
|
+
if (workflows.activeWorkflow !== wf) fail('TARGET_CHANGED');
|
|
95
|
+
if (app.configuringGraph || app.pendingGraphLoads?.size || wf.changeTracker?.changeCount > 0) fail('EDITOR_BUSY');
|
|
96
|
+
}
|
|
97
|
+
async function activate(id) {
|
|
98
|
+
const wf = requireTab(id);
|
|
99
|
+
if (workflows.activeWorkflow !== wf) {
|
|
100
|
+
if (app.configuringGraph || app.pendingGraphLoads?.size) fail('EDITOR_BUSY');
|
|
101
|
+
workflows.activeWorkflow?.changeTracker?.captureCanvasState();
|
|
102
|
+
await wf.load(); requireTab(id);
|
|
103
|
+
const baseline = clone(wf.changeTracker.initialState), dirty = wf.isModified;
|
|
104
|
+
const loaded = await app.loadGraphData(clone(wf.activeState), true, true, wf, { skipAssetScans: true, silentAssetErrors: true });
|
|
105
|
+
if (loaded === false || loaded === undefined) fail('ACTIVATION_FAILED');
|
|
106
|
+
ready(wf);
|
|
107
|
+
const rendered = clone(app.rootGraph.serialize());
|
|
108
|
+
wf.changeTracker.initialState = dirty ? baseline : clone(rendered);
|
|
109
|
+
wf.changeTracker.activeState = rendered; wf.isModified = dirty;
|
|
110
|
+
}
|
|
111
|
+
ready(wf); wf.changeTracker.captureCanvasState(); return wf;
|
|
112
|
+
}
|
|
113
|
+
function snapshot(id, wf) {
|
|
114
|
+
return { workflow_tab_id: id, modified: Boolean(wf.isModified), temporary: Boolean(wf.isTemporary), workflow: clone(app.rootGraph.serialize()) };
|
|
115
|
+
}
|
|
116
|
+
function metadata(wf) {
|
|
117
|
+
sync();
|
|
118
|
+
return { workflow_tab_id: ids.get(wf), name: wf.filename ?? '', path: wf.isTemporary ? null : wf.path ?? null,
|
|
119
|
+
modified: Boolean(wf.isModified), temporary: Boolean(wf.isTemporary) };
|
|
120
|
+
}
|
|
121
|
+
async function createWorkflow() {
|
|
122
|
+
if (typeof workflows.createNewTemporary !== 'function' || !window.comfyAPI?.defaultGraph?.blankGraph) fail('NEW_UNSUPPORTED');
|
|
123
|
+
if (app.configuringGraph || app.pendingGraphLoads?.size || workflows.isBusy) fail('EDITOR_BUSY');
|
|
124
|
+
workflows.activeWorkflow?.changeTracker?.captureCanvasState();
|
|
125
|
+
const graph = { ...clone(window.comfyAPI.defaultGraph.blankGraph), id: crypto.randomUUID() };
|
|
126
|
+
const wf = workflows.createNewTemporary(undefined, graph);
|
|
127
|
+
const loaded = await app.loadGraphData(graph, true, true, wf, { skipAssetScans: true, silentAssetErrors: true });
|
|
128
|
+
if (loaded === false || loaded === undefined) fail('LOAD_FAILED');
|
|
129
|
+
const opened = workflows.openWorkflows.find(item => item.path === wf.path);
|
|
130
|
+
if (!opened) fail('TAB_CLOSED');
|
|
131
|
+
ready(opened);
|
|
132
|
+
return metadata(opened);
|
|
133
|
+
}
|
|
134
|
+
async function openWorkflow(path) {
|
|
135
|
+
if (typeof path !== 'string' || !path.startsWith('workflows/') || !/\.json$/i.test(path) ||
|
|
136
|
+
/[\\\0:]/.test(path) || path.split('/').some(part => !part || part === '.' || part === '..')) fail('INVALID_WORKFLOW_PATH');
|
|
137
|
+
const existing = workflows.openWorkflows.find(wf => !wf.isTemporary && wf.path === path);
|
|
138
|
+
if (existing) return { ...metadata(existing), error: 'WORKFLOW_ALREADY_OPEN' };
|
|
139
|
+
if (typeof workflows.syncWorkflows !== 'function' || typeof workflows.getWorkflowByPath !== 'function') fail('OPEN_UNSUPPORTED');
|
|
140
|
+
if (app.configuringGraph || app.pendingGraphLoads?.size || workflows.isBusy) fail('EDITOR_BUSY');
|
|
141
|
+
await workflows.syncWorkflows();
|
|
142
|
+
const wf = workflows.getWorkflowByPath(path);
|
|
143
|
+
if (!wf || wf.isTemporary) fail('WORKFLOW_NOT_FOUND');
|
|
144
|
+
workflows.activeWorkflow?.changeTracker?.captureCanvasState();
|
|
145
|
+
try { await wf.load(); }
|
|
146
|
+
catch (error) { if (/\b404\b/.test(error.message)) fail('WORKFLOW_NOT_FOUND'); fail('OPEN_FAILED'); }
|
|
147
|
+
const loaded = await app.loadGraphData(clone(wf.activeState), true, true, wf, { skipAssetScans: true, silentAssetErrors: true, deferWarnings: true });
|
|
148
|
+
if (loaded === false || loaded === undefined) fail('LOAD_FAILED');
|
|
149
|
+
const opened = workflows.openWorkflows.find(item => item.path === path);
|
|
150
|
+
if (!opened) fail('TAB_CLOSED');
|
|
151
|
+
ready(opened);
|
|
152
|
+
return metadata(opened);
|
|
153
|
+
}
|
|
154
|
+
async function save(wf, name) {
|
|
155
|
+
if (typeof workflows.saveWorkflow !== 'function' || typeof wf.changeTracker?.prepareForSave !== 'function') fail('SAVE_UNSUPPORTED');
|
|
156
|
+
if (name === undefined && wf.isTemporary) fail('NAME_REQUIRED');
|
|
157
|
+
let target = wf;
|
|
158
|
+
if (name !== undefined) {
|
|
159
|
+
const normalized = name.replace(/\\/g, '/');
|
|
160
|
+
if (!normalized || normalized.startsWith('/') || /[\0:]/.test(normalized) || normalized.split('/').some(part => !part || part === '.' || part === '..')) fail('INVALID_WORKFLOW_NAME');
|
|
161
|
+
const path = 'workflows/' + (/\.json$/i.test(normalized) ? normalized : normalized + '.json');
|
|
162
|
+
if (path !== wf.path || wf.isTemporary) {
|
|
163
|
+
if (typeof api.getUserData !== 'function' || typeof workflows.getWorkflowByPath !== 'function' ||
|
|
164
|
+
typeof workflows.renameWorkflow !== 'function' || typeof workflows.saveAs !== 'function') fail('SAVE_UNSUPPORTED');
|
|
165
|
+
const existing = workflows.getWorkflowByPath(path);
|
|
166
|
+
if (existing && existing !== wf) fail('NAME_EXISTS');
|
|
167
|
+
const response = await api.getUserData(path);
|
|
168
|
+
await response.body?.cancel();
|
|
169
|
+
if (response.status === 200 || response.status === 409) fail('NAME_EXISTS');
|
|
170
|
+
if (response.status !== 404) fail('SAVE_CHECK_FAILED');
|
|
171
|
+
wf.changeTracker.prepareForSave();
|
|
172
|
+
if (wf.isTemporary) await workflows.renameWorkflow(wf, path);
|
|
173
|
+
else {
|
|
174
|
+
target = workflows.saveAs(wf, path);
|
|
175
|
+
const loaded = await app.loadGraphData(clone(JSON.parse(target.content)), true, true, target, { skipAssetScans: true, silentAssetErrors: true });
|
|
176
|
+
if (loaded === false || loaded === undefined) fail('LOAD_FAILED');
|
|
177
|
+
target = workflows.openWorkflows.find(item => item.path === target.path);
|
|
178
|
+
if (!target) fail('TAB_CLOSED');
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
ready(target);
|
|
183
|
+
target.changeTracker.prepareForSave();
|
|
184
|
+
try { await workflows.saveWorkflow(target); }
|
|
185
|
+
catch (error) { if (/\b409\b/.test(error.message)) fail('NAME_EXISTS'); fail('SAVE_FAILED'); }
|
|
186
|
+
ready(target);
|
|
187
|
+
return { ...metadata(target), saved: true };
|
|
188
|
+
}
|
|
189
|
+
async function operate(message) {
|
|
190
|
+
if (message.method === 'new') return createWorkflow();
|
|
191
|
+
if (message.method === 'open') return openWorkflow(message.path);
|
|
192
|
+
if (!['read', 'replace', 'run', 'save'].includes(message.method)) fail('UNKNOWN_METHOD');
|
|
193
|
+
let validation;
|
|
194
|
+
if (message.method === 'replace') {
|
|
195
|
+
requireTab(message.workflow_tab_id);
|
|
196
|
+
validation = await validateWorkflow(message.workflow);
|
|
197
|
+
requireTab(message.workflow_tab_id);
|
|
198
|
+
if (!validation.valid) return { workflow_tab_id: message.workflow_tab_id, error: 'WORKFLOW_VALIDATION_FAILED', validation };
|
|
199
|
+
}
|
|
200
|
+
const wf = await activate(message.workflow_tab_id);
|
|
201
|
+
if (message.method === 'read') return snapshot(message.workflow_tab_id, wf);
|
|
202
|
+
if (message.method === 'run') return run(message.workflow_tab_id, wf);
|
|
203
|
+
if (message.method === 'save') return save(wf, message.name);
|
|
204
|
+
const before = clone(app.rootGraph.serialize()), tracker = wf.changeTracker;
|
|
205
|
+
const baseline = clone(tracker.initialState), oldUndo = [...tracker.undoQueue], oldRedo = [...tracker.redoQueue], oldDirty = wf.isModified;
|
|
206
|
+
try {
|
|
207
|
+
const loaded = await app.loadGraphData(clone(message.workflow), true, true, wf, { skipAssetScans: true, silentAssetErrors: true });
|
|
208
|
+
if (loaded === false || loaded === undefined) fail('LOAD_FAILED');
|
|
209
|
+
ready(wf);
|
|
210
|
+
const current = wf.changeTracker;
|
|
211
|
+
current.initialState = baseline; current.activeState = clone(app.rootGraph.serialize());
|
|
212
|
+
current.undoQueue = [...oldUndo, before]; current.redoQueue = []; current.updateModified(before);
|
|
213
|
+
sync(); return { ...snapshot(message.workflow_tab_id, wf), replaced: true, saved: false, validation };
|
|
214
|
+
} catch (error) {
|
|
215
|
+
if (workflows.activeWorkflow === wf && workflows.openWorkflows.includes(wf)) {
|
|
216
|
+
const restored = await app.loadGraphData(before, true, true, wf, { skipAssetScans: true, silentAssetErrors: true });
|
|
217
|
+
if (restored === false || restored === undefined) fail('ROLLBACK_FAILED');
|
|
218
|
+
const current = wf.changeTracker;
|
|
219
|
+
current.initialState = baseline; current.activeState = clone(app.rootGraph.serialize());
|
|
220
|
+
current.undoQueue = oldUndo; current.redoQueue = oldRedo; wf.isModified = oldDirty;
|
|
221
|
+
}
|
|
222
|
+
throw error;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
function rejected(id, response, status = null) {
|
|
226
|
+
const issue = value => ({ type: String(value?.type ?? 'SUBMISSION_REJECTED'),
|
|
227
|
+
message: String(value?.message ?? value ?? 'Submission rejected').slice(0, 1000),
|
|
228
|
+
...(typeof value?.details === 'string' ? { details: value.details.slice(0, 1000) } : {}) });
|
|
229
|
+
return { workflow_tab_id: id, accepted: false, http_status: status, error: issue(response?.error),
|
|
230
|
+
node_errors: Object.fromEntries(Object.entries(response?.node_errors ?? {}).map(([node, data]) => [node, {
|
|
231
|
+
class_type: data.class_type, errors: (Array.isArray(data.errors) ? data.errors : []).map(issue),
|
|
232
|
+
}])) };
|
|
233
|
+
}
|
|
234
|
+
async function run(id, wf) {
|
|
235
|
+
if (typeof app.graphToPrompt !== 'function' || typeof api.queuePrompt !== 'function') fail('RUN_UNSUPPORTED');
|
|
236
|
+
let prompt;
|
|
237
|
+
try { prompt = await app.graphToPrompt(app.rootGraph); }
|
|
238
|
+
catch (error) { return rejected(id, { error: { type: 'PROMPT_BUILD_FAILED', message: error.message } }); }
|
|
239
|
+
ready(wf);
|
|
240
|
+
try {
|
|
241
|
+
const reply = await api.queuePrompt(0, prompt);
|
|
242
|
+
sync();
|
|
243
|
+
return typeof reply.prompt_id === 'string' && reply.prompt_id ?
|
|
244
|
+
{ workflow_tab_id: id, accepted: true, prompt_id: reply.prompt_id } : rejected(id, reply);
|
|
245
|
+
} catch (error) {
|
|
246
|
+
if (!error.response) fail('RUN_OUTCOME_UNKNOWN');
|
|
247
|
+
return rejected(id, error.response, error.status ?? null);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
function connect() {
|
|
251
|
+
if (stopped || suspended) return;
|
|
252
|
+
clearTimeout(reconnectTimer); clearHeartbeat(); updateBanner(false);
|
|
253
|
+
lastInventory = '';
|
|
254
|
+
const url = new URL('/_comfy_mcp/ws', location.origin); url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
255
|
+
const connection = socket = new WebSocket(url);
|
|
256
|
+
let ended = false, welcomed = false, pingId;
|
|
257
|
+
function lost(reason) {
|
|
258
|
+
if (connection !== socket || ended) return;
|
|
259
|
+
ended = true; clearHeartbeat(); updateBanner(false);
|
|
260
|
+
connection.close();
|
|
261
|
+
if (!stopped && !suspended) {
|
|
262
|
+
console.warn('[ComfyUI MCP] Workflow bridge disconnected:', reason);
|
|
263
|
+
reconnectTimer = setTimeout(connect, Math.min(1000 * 2 ** attempts++, 15_000));
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
function ping() {
|
|
267
|
+
if (stopped || suspended || ended || connection !== socket) return;
|
|
268
|
+
if (connection.readyState !== WebSocket.OPEN) { lost('Socket not open'); return; }
|
|
269
|
+
pingId = crypto.randomUUID();
|
|
270
|
+
replyTimer = setTimeout(() => lost('Heartbeat timeout'), heartbeatTimeout);
|
|
271
|
+
connection.send(JSON.stringify({ type: 'ping', id: pingId }));
|
|
272
|
+
}
|
|
273
|
+
replyTimer = setTimeout(() => lost('Handshake timeout'), heartbeatTimeout);
|
|
274
|
+
connection.addEventListener('message', event => {
|
|
275
|
+
let message; try { message = JSON.parse(event.data); } catch { return; }
|
|
276
|
+
if (stopped || suspended || ended || connection !== socket) return;
|
|
277
|
+
if (message.type === 'welcome' && !welcomed) {
|
|
278
|
+
welcomed = true; clearTimeout(replyTimer);
|
|
279
|
+
updateBanner(false, message.backend_url);
|
|
280
|
+
sync(); ping();
|
|
281
|
+
} else if (message.type === 'pong' && pingId && message.id === pingId) {
|
|
282
|
+
clearTimeout(replyTimer); pingId = undefined;
|
|
283
|
+
if (!connected) console.log('[ComfyUI MCP] Workflow bridge connected');
|
|
284
|
+
updateBanner(true); attempts = 0;
|
|
285
|
+
heartbeatTimer = setTimeout(ping, heartbeatInterval);
|
|
286
|
+
} else if (message.type === 'request') {
|
|
287
|
+
queue = queue.catch(() => {}).then(async () => {
|
|
288
|
+
if (stopped || ended || connection !== socket || connection.readyState !== WebSocket.OPEN) return;
|
|
289
|
+
let response;
|
|
290
|
+
try { response = { ok: true, result: await operate(message) }; }
|
|
291
|
+
catch (error) { response = { ok: false, error: { code: error.code ?? 'BROWSER_ERROR' } }; }
|
|
292
|
+
if (!ended && connection === socket && connection.readyState === WebSocket.OPEN) connection.send(JSON.stringify({ type: 'result', request_id: message.request_id, ...response }));
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
connection.addEventListener('close', () => lost('Socket closed'));
|
|
297
|
+
connection.addEventListener('error', () => lost('Socket error'));
|
|
298
|
+
}
|
|
299
|
+
function pause() { suspended = true; clearTimeout(reconnectTimer); clearHeartbeat(); updateBanner(false); socket?.close(1000, 'Page suspended'); }
|
|
300
|
+
function focus() { if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: 'focus' })); }
|
|
301
|
+
function resume() { if (suspended) { suspended = false; connect(); } }
|
|
302
|
+
window.addEventListener('pagehide', pause); window.addEventListener('pageshow', resume);
|
|
303
|
+
window.addEventListener('focus', focus);
|
|
304
|
+
sync(); connect();
|
|
305
|
+
})();
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
const copy = value => JSON.parse(JSON.stringify(value));
|
|
2
|
+
const fail = code => { throw Object.assign(new Error(code), { code }); };
|
|
3
|
+
let functions;
|
|
4
|
+
|
|
5
|
+
async function nativeFunctions() {
|
|
6
|
+
if (!functions) functions = (async () => {
|
|
7
|
+
// Reuse exports from the running frontend, without pinning its hashed filenames.
|
|
8
|
+
const urls = [...new Set(performance.getEntriesByType('resource').map(entry => entry.name))]
|
|
9
|
+
.filter(value => { const url = new URL(value); return url.origin === location.origin && /\/(api|app|missingModelScan|missingMediaScan|workflowSchema|treeUtil)-[^/]+\.js$/.test(url.pathname); });
|
|
10
|
+
const found = Object.create(null);
|
|
11
|
+
for (const url of urls) {
|
|
12
|
+
const module = await import(url);
|
|
13
|
+
for (const value of Object.values(module)) if (typeof value === 'function') found[value.name] ??= value;
|
|
14
|
+
}
|
|
15
|
+
for (const name of ['validateComfyWorkflow', 'scanAllModelCandidates', 'scanAllMediaCandidates']) {
|
|
16
|
+
if (!found[name]) fail('FRONTEND_VALIDATION_UNSUPPORTED');
|
|
17
|
+
}
|
|
18
|
+
return found;
|
|
19
|
+
})().catch(error => { functions = undefined; throw error; });
|
|
20
|
+
return functions;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function topology(data, issue) {
|
|
24
|
+
const definitions = data.definitions?.subgraphs ?? [];
|
|
25
|
+
const subgraphIds = new Set(definitions.map(graph => graph.id));
|
|
26
|
+
for (const graph of [data, ...definitions]) {
|
|
27
|
+
const nodes = new Map();
|
|
28
|
+
for (const node of graph.nodes ?? []) {
|
|
29
|
+
const id = String(node.id);
|
|
30
|
+
if (nodes.has(id)) issue('DUPLICATE_NODE_ID', 'Duplicate node ID', id);
|
|
31
|
+
nodes.set(id, node);
|
|
32
|
+
if (!(node.type in globalThis.LiteGraph.registered_node_types) && !subgraphIds.has(node.type)) {
|
|
33
|
+
issue('MISSING_NODE', node.type, id);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
// Subgraph interfaces are link endpoints, but are not ordinary serialized nodes.
|
|
37
|
+
if (graph.inputNode) nodes.set(String(graph.inputNode.id), { outputs: graph.inputs?.map(slot => ({ links: slot.linkIds })) });
|
|
38
|
+
if (graph.outputNode) nodes.set(String(graph.outputNode.id), { inputs: graph.outputs?.map(slot => ({ link: slot.linkIds?.[0] })) });
|
|
39
|
+
const linkIds = new Set();
|
|
40
|
+
for (const row of graph.links ?? []) {
|
|
41
|
+
const [id, from, output, to, input] = Array.isArray(row) ? row : [row.id, row.origin_id, row.origin_slot, row.target_id, row.target_slot];
|
|
42
|
+
const source = nodes.get(String(from)), target = nodes.get(String(to));
|
|
43
|
+
if (linkIds.has(String(id))) issue('DUPLICATE_LINK_ID', 'Duplicate link ID: ' + id);
|
|
44
|
+
linkIds.add(String(id));
|
|
45
|
+
if (!source || !target) { issue('INVALID_LINK', 'Link references a missing node: ' + id); continue; }
|
|
46
|
+
if (!Number.isInteger(output) || output < 0 || !Number.isInteger(input) || input < 0 ||
|
|
47
|
+
source.outputs && (!source.outputs[output] || !source.outputs[output].links?.some(value => String(value) === String(id))) ||
|
|
48
|
+
target.inputs && (!target.inputs[input] || String(target.inputs[input].link) !== String(id))) {
|
|
49
|
+
issue('INVALID_LINK', 'Inconsistent link or slot: ' + id);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
for (const node of nodes.values()) {
|
|
53
|
+
for (const input of node.inputs ?? []) if (input.link != null && !linkIds.has(String(input.link))) issue('INVALID_LINK', 'Input references a missing link', String(node.id));
|
|
54
|
+
for (const output of node.outputs ?? []) for (const id of output.links ?? []) if (!linkIds.has(String(id))) issue('INVALID_LINK', 'Output references a missing link', String(node.id));
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function configureDetached(graph, data, native) {
|
|
60
|
+
const candidate = copy(data), registry = globalThis.LiteGraph.registered_node_types, previous = new Map();
|
|
61
|
+
// LiteGraph keeps some runtime stores by graph UUID. Never share the live graph's UUID.
|
|
62
|
+
candidate.id = crypto.randomUUID();
|
|
63
|
+
try {
|
|
64
|
+
for (const definition of candidate.definitions?.subgraphs ?? []) {
|
|
65
|
+
if (!native.SubgraphNode) fail('FRONTEND_VALIDATION_UNSUPPORTED');
|
|
66
|
+
if (previous.has(definition.id)) continue;
|
|
67
|
+
previous.set(definition.id, Object.getOwnPropertyDescriptor(registry, definition.id));
|
|
68
|
+
Object.defineProperty(registry, definition.id, { configurable: true, writable: true, enumerable: true,
|
|
69
|
+
value: function () { return new native.SubgraphNode(graph, graph.subgraphs.get(definition.id), {}); } });
|
|
70
|
+
}
|
|
71
|
+
return graph.configure(candidate);
|
|
72
|
+
} finally {
|
|
73
|
+
// Configuration is synchronous; restore factories before any asynchronous checks.
|
|
74
|
+
for (const [id, descriptor] of previous) {
|
|
75
|
+
if (descriptor) Object.defineProperty(registry, id, descriptor);
|
|
76
|
+
else delete registry[id];
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function activeCandidate(root, candidate) {
|
|
82
|
+
let graph = root;
|
|
83
|
+
for (const id of String(candidate.sourceExecutionId ?? candidate.nodeId).split(':')) {
|
|
84
|
+
const node = graph?.nodes.find(node => String(node.id) === id);
|
|
85
|
+
if (!node) fail('RESOURCE_SCOPE_UNVERIFIED');
|
|
86
|
+
if (node.mode === 2 || node.mode === 4) return false;
|
|
87
|
+
graph = node.subgraph;
|
|
88
|
+
}
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// The returned function only receives the candidate JSON; frontend context is captured here.
|
|
93
|
+
export function createWorkflowValidator(app, loadFunctions = nativeFunctions) {
|
|
94
|
+
return async function validateWorkflow(data) {
|
|
95
|
+
const errors = [];
|
|
96
|
+
let errorCount = 0;
|
|
97
|
+
const issue = (code, message, node_id, field) => {
|
|
98
|
+
errorCount++;
|
|
99
|
+
if (errors.length < 50) errors.push({ code, message: String(message).slice(0, 1000),
|
|
100
|
+
...(node_id == null ? {} : { node_id: String(node_id) }), ...(field == null ? {} : { field }) });
|
|
101
|
+
};
|
|
102
|
+
const result = () => ({ valid: errorCount === 0, validator: 'frontend', error_count: errorCount, errors });
|
|
103
|
+
const native = await loadFunctions();
|
|
104
|
+
const parsed = await native.validateComfyWorkflow(copy(data), message => issue('WORKFLOW_SCHEMA', message));
|
|
105
|
+
if (!parsed || errorCount) { if (!errorCount) issue('WORKFLOW_SCHEMA', 'Invalid Workflow JSON'); return result(); }
|
|
106
|
+
if (typeof app.reloadNodeDefs !== 'function') fail('FRONTEND_VALIDATION_UNSUPPORTED');
|
|
107
|
+
try { if (await app.reloadNodeDefs() === false) fail('CATALOG_REFRESH_FAILED'); }
|
|
108
|
+
catch { fail('CATALOG_REFRESH_FAILED'); }
|
|
109
|
+
topology(data, issue);
|
|
110
|
+
if (errorCount) return result();
|
|
111
|
+
const graph = new app.rootGraph.constructor();
|
|
112
|
+
try {
|
|
113
|
+
if (configureDetached(graph, data, native)) { issue('GRAPH_CONFIGURATION', 'Frontend could not configure the candidate graph'); return result(); }
|
|
114
|
+
const nodes = [...graph.nodes, ...[...graph.subgraphs.values()].flatMap(subgraph => subgraph.nodes)];
|
|
115
|
+
const usesAssetWidget = (type, name) => nodes.some(node => node.type === type && node.widgets?.some(widget => widget.name === name && widget.type === 'asset'));
|
|
116
|
+
const models = native.scanAllModelCandidates(graph, usesAssetWidget).filter(candidate => activeCandidate(graph, candidate));
|
|
117
|
+
const media = native.scanAllMediaCandidates(graph).filter(candidate => activeCandidate(graph, candidate));
|
|
118
|
+
if (models.some(candidate => candidate.isMissing === undefined)) {
|
|
119
|
+
if (!native.verifyAssetSupportedCandidates) fail('FRONTEND_VALIDATION_UNSUPPORTED');
|
|
120
|
+
await native.verifyAssetSupportedCandidates(models);
|
|
121
|
+
}
|
|
122
|
+
if (media.some(candidate => candidate.isMissing === undefined)) {
|
|
123
|
+
if (!native.verifyMediaCandidates) fail('FRONTEND_VALIDATION_UNSUPPORTED');
|
|
124
|
+
await native.verifyMediaCandidates(media);
|
|
125
|
+
}
|
|
126
|
+
for (const [candidates, code] of [[models, 'MODEL_MISSING'], [media, 'REFERENCE_MISSING']]) for (const candidate of candidates) {
|
|
127
|
+
if (candidate.isMissing === true) issue(code, candidate.name, candidate.nodeId, candidate.widgetName);
|
|
128
|
+
else if (candidate.isMissing !== false) issue('RESOURCE_UNVERIFIED', candidate.name, candidate.nodeId, candidate.widgetName);
|
|
129
|
+
}
|
|
130
|
+
} finally { graph.clear(); }
|
|
131
|
+
return result();
|
|
132
|
+
};
|
|
133
|
+
}
|