comfy-ts 2.5.0 → 2.6.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/README.md +12 -1
- package/dist/{DefinedWorkflow-CnzmQrBh.js → DefinedWorkflow-BJgt5t0x.js} +14 -3
- package/dist/DefinedWorkflow-BJgt5t0x.js.map +1 -0
- package/dist/{DraftsSt-C1MbWnEp.js → DraftsSt-dizp3VcC.js} +2 -2
- package/dist/{DraftsSt-C1MbWnEp.js.map → DraftsSt-dizp3VcC.js.map} +1 -1
- package/dist/cli.js +4 -4
- package/dist/index.cjs +3 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +21 -18
- package/dist/index.d.ts +21 -18
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/{run-serve-D47Zas-a.js → run-serve-CVu39RNd.js} +330 -16
- package/dist/run-serve-CVu39RNd.js.map +1 -0
- package/dist/{run-tui-t2TRBN0H.js → run-tui-idFhdO4f.js} +704 -524
- package/dist/run-tui-idFhdO4f.js.map +1 -0
- package/dist/serve-web.js +280 -0
- package/dist/{state-DY3Mp9Cl.js → state-C90kdjtB.js} +3 -13
- package/dist/state-C90kdjtB.js.map +1 -0
- package/dist/web.d.ts +21 -18
- package/dist/web.js +3 -2
- package/dist/web.js.map +1 -1
- package/package.json +7 -5
- package/src/cli/serve/ServeApp.ts +314 -13
- package/src/cli/serve/describeVar.ts +6 -1
- package/src/cli/serve/run-serve.ts +4 -2
- package/src/cli/serve/web/api.ts +105 -0
- package/src/cli/serve/web/clipboard.ts +25 -0
- package/src/cli/serve/web/components/App.tsx +53 -0
- package/src/cli/serve/web/components/Gallery.tsx +186 -0
- package/src/cli/serve/web/components/PromptEnhancer.tsx +210 -0
- package/src/cli/serve/web/components/Sidebar.tsx +42 -0
- package/src/cli/serve/web/components/VarsForm.tsx +173 -0
- package/src/cli/serve/web/components/controls/BasicControls.tsx +95 -0
- package/src/cli/serve/web/components/controls/ImageControl.tsx +71 -0
- package/src/cli/serve/web/components/controls/LorasControl.tsx +340 -0
- package/src/cli/serve/web/components/controls/SeedControl.tsx +43 -0
- package/src/cli/serve/web/components/controls/SizeControl.tsx +49 -0
- package/src/cli/serve/web/main.tsx +18 -0
- package/src/cli/serve/web/openrouter.ts +142 -0
- package/src/cli/serve/web/state/EnhancerSt.ts +370 -0
- package/src/cli/serve/web/state/FormSt.ts +177 -0
- package/src/cli/serve/web/state/RunSt.ts +136 -0
- package/src/cli/serve/web/state/WebSt.ts +210 -0
- package/src/cli/serve/web/state/payload.ts +110 -0
- package/src/cli/serve/web/styles.ts +259 -0
- package/src/cli/serve/web/tsconfig.json +15 -0
- package/src/cli/serve/webBundle.ts +66 -0
- package/src/cli/tui/imageEscapes.ts +105 -0
- package/src/cli/tui/imagePicker/ImagePickerSt.ts +21 -8
- package/src/cli/tui/protocolImage.ts +39 -0
- package/src/cli/tui/protocolImagePainter.ts +56 -23
- package/src/cli/tui/run-tui.tsx +3 -2
- package/src/cli/tui/state/LorasSt.ts +22 -9
- package/src/cli/tui/state/PreviewSt.ts +31 -13
- package/src/cli/tui/state/SettingsSt.ts +1 -1
- package/src/vars/ComfyVars.ts +4 -1
- package/dist/DefinedWorkflow-CnzmQrBh.js.map +0 -1
- package/dist/run-serve-D47Zas-a.js.map +0 -1
- package/dist/run-tui-t2TRBN0H.js.map +0 -1
- package/dist/state-DY3Mp9Cl.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "comfy-ts",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.6.0",
|
|
4
4
|
"description": "The complete TypeScript toolkit for ComfyUI and generative AI. Fully type-safe SDK with autocomplete on every node, companion CLI, TUI, agentic docs, and 50+ examples. Design, run and deploy creative pipelines for image, video, audio, 3d and text on any ComfyUI, local, cloud or hosted.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"comfyui",
|
|
@@ -65,12 +65,12 @@
|
|
|
65
65
|
"LICENSE"
|
|
66
66
|
],
|
|
67
67
|
"scripts": {
|
|
68
|
-
"build": "tsdown",
|
|
68
|
+
"build": "tsdown && bun scripts/build-serve-web.ts",
|
|
69
69
|
"build:watch": "tsdown --watch",
|
|
70
70
|
"test": "bun test",
|
|
71
71
|
"test:watch": "bun test --watch",
|
|
72
72
|
"typecheck": "tsc --noEmit && tsc -p examples/web/tsconfig.json",
|
|
73
|
-
"typecheck:lib": "tsc -p tsconfig.lib.json",
|
|
73
|
+
"typecheck:lib": "tsc -p tsconfig.lib.json && tsc -p src/cli/serve/web/tsconfig.json",
|
|
74
74
|
"lint": "oxlint src examples scripts tests",
|
|
75
75
|
"format": "oxfmt src examples scripts tests",
|
|
76
76
|
"format:check": "oxfmt --check src examples scripts tests",
|
|
@@ -93,7 +93,8 @@
|
|
|
93
93
|
"release:dry": "bun scripts/release.ts --dry-run",
|
|
94
94
|
"prepublishOnly": "bun run ci && bun run build",
|
|
95
95
|
"tui": "bun src/cli/comfy-ts-cli.ts tui",
|
|
96
|
-
"serve": "bun src/cli/comfy-ts-cli.ts serve"
|
|
96
|
+
"serve": "bun src/cli/comfy-ts-cli.ts serve",
|
|
97
|
+
"serve:watch": "bun src/cli/comfy-ts-cli.ts serve"
|
|
97
98
|
},
|
|
98
99
|
"rvt": {
|
|
99
100
|
"skip": [
|
|
@@ -122,11 +123,12 @@
|
|
|
122
123
|
"devDependencies": {
|
|
123
124
|
"@types/bun": "^1.3.14",
|
|
124
125
|
"@types/react": "^19.2.17",
|
|
126
|
+
"@types/react-dom": "^19.2.3",
|
|
125
127
|
"@types/ws": "^8.18.1",
|
|
126
128
|
"oxfmt": "^0.60.0",
|
|
127
129
|
"oxlint": "^1.75.0",
|
|
128
130
|
"oxlint-tsgolint": "^7.0.2001",
|
|
129
|
-
"rvlib-ts-tools": "^0.
|
|
131
|
+
"rvlib-ts-tools": "^0.3.3",
|
|
130
132
|
"tsdown": "^0.22.14",
|
|
131
133
|
"typescript": "^7.0.2"
|
|
132
134
|
}
|
|
@@ -7,8 +7,17 @@ import { basename, dirname, extname, join, resolve } from 'pathe'
|
|
|
7
7
|
import { applyVarPayload } from 'src/cli/serve/applyVarPayload.ts'
|
|
8
8
|
import { describeVar, type VarDescriptor } from 'src/cli/serve/describeVar.ts'
|
|
9
9
|
import { draftsDirForFile, listDraftsForFile } from 'src/cli/tui/state/DraftsSt.ts'
|
|
10
|
+
import {
|
|
11
|
+
getLoraDisplayName,
|
|
12
|
+
getLoraPreviewUrl,
|
|
13
|
+
getLoraTriggerWords,
|
|
14
|
+
refreshLoraInfoCacheIfChanged,
|
|
15
|
+
} from 'src/host/loraInfoCache.ts'
|
|
16
|
+
import { fetchLoraList, fetchLoraPreviewBytes, loraKey, loraPreviewMapFrom } from 'src/host/loraManagerApi.ts'
|
|
17
|
+
import type { ComfyHost } from 'src/host/ComfyHost.ts'
|
|
10
18
|
import type { ImageVar, SeedVar } from 'src/vars/ComfyVars.ts'
|
|
11
19
|
import type { DefinedWorkflow } from 'src/vars/DefinedWorkflow.ts'
|
|
20
|
+
import { bang } from 'src/utils/bang.ts'
|
|
12
21
|
import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
|
|
13
22
|
|
|
14
23
|
export type ServeModule = { key: string; file: string; dw: DefinedWorkflow }
|
|
@@ -20,6 +29,8 @@ export type ServeExecution = {
|
|
|
20
29
|
status: string
|
|
21
30
|
images: { absPath: string | null; filename: string }[]
|
|
22
31
|
data: { id: string; error?: unknown }
|
|
32
|
+
/** live global progress (ComfyExecution has it; fakes may omit) — the /run/<module> poll reads it */
|
|
33
|
+
progressGlobal?: { percent: number }
|
|
23
34
|
}
|
|
24
35
|
|
|
25
36
|
export type ServeStarter = (mod: ServeModule) => Promise<ServeExecution>
|
|
@@ -48,28 +59,70 @@ const CONTENT_TYPES: Record<string, string> = {
|
|
|
48
59
|
'.txt': 'text/plain',
|
|
49
60
|
}
|
|
50
61
|
|
|
62
|
+
/** magic-byte sniff for the preview proxy — fetchLoraPreviewBytes already guarantees an image */
|
|
63
|
+
function sniffImageContentType(bytes: Uint8Array): string {
|
|
64
|
+
if (bytes[0] === 0x89 && bytes[1] === 0x50) return 'image/png'
|
|
65
|
+
if (bytes[0] === 0xff && bytes[1] === 0xd8) return 'image/jpeg'
|
|
66
|
+
if (bytes[0] === 0x47 && bytes[1] === 0x49) return 'image/gif'
|
|
67
|
+
if (bytes[0] === 0x52 && bytes[1] === 0x49) return 'image/webp' // RIFF container
|
|
68
|
+
return 'application/octet-stream'
|
|
69
|
+
}
|
|
70
|
+
|
|
51
71
|
function json(status: number, payload: unknown): ServeReply {
|
|
52
72
|
return { status, contentType: 'application/json', body: JSON.stringify(payload, null, 2) }
|
|
53
73
|
}
|
|
54
74
|
|
|
55
75
|
const USAGE = [
|
|
76
|
+
'GET / in a browser — web control panel (every var as a form control)',
|
|
56
77
|
'GET /drafts — every served workflow, its drafts and var descriptors',
|
|
57
78
|
'GET /drafts/<module>/<draft> — one draft with its stored values',
|
|
58
79
|
'POST /generate/<module>/<draft> with { ...vars } — run, blocking',
|
|
59
80
|
'POST /generate/<draft> — unqualified, when unambiguous',
|
|
81
|
+
'PUT /drafts/<module>/<draft> with { ...vars } — save (or duplicate to a new name) a draft',
|
|
82
|
+
'GET /run/<module> — live run status · /run/<module>/preview — latent preview bytes',
|
|
83
|
+
'POST /upload with {"name","dataBase64"} — store a browser file for an image var',
|
|
84
|
+
'GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)',
|
|
85
|
+
'GET /lora-preview/<hostId>/<lora> — preview image bytes',
|
|
60
86
|
'GET /outputs/<path> — generated files',
|
|
61
87
|
]
|
|
62
88
|
|
|
89
|
+
/** the html shell; the app itself is ONE bundle at /web/app.js */
|
|
90
|
+
const WEB_SHELL = `<!doctype html>
|
|
91
|
+
<html lang="en">
|
|
92
|
+
<head>
|
|
93
|
+
<meta charset="utf-8">
|
|
94
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
95
|
+
<title>comfy-ts serve</title>
|
|
96
|
+
<style>html{background:#101217;color:#e8eaf0}</style>
|
|
97
|
+
</head>
|
|
98
|
+
<body>
|
|
99
|
+
<div id="root"></div>
|
|
100
|
+
<script type="module" src="/web/app.js"></script>
|
|
101
|
+
</body>
|
|
102
|
+
</html>
|
|
103
|
+
`
|
|
104
|
+
|
|
63
105
|
export class ServeApp {
|
|
64
106
|
private starter: ServeStarter
|
|
65
|
-
/** last SERVED seed per `module/draft/var` — '+'/'-' modes continue from it
|
|
66
|
-
|
|
107
|
+
/** last SERVED seed per `module/draft/var` — '+'/'-' modes continue from it.
|
|
108
|
+
* draftBase remembers which DRAFT value the continuation grew from: when the
|
|
109
|
+
* draft's seed changes (the web form autosaves a typed value), the typed
|
|
110
|
+
* value wins and the continuation restarts there */
|
|
111
|
+
private seedState = new Map<string, { last: number; draftBase: number }>()
|
|
67
112
|
/** per-module promise chain: vars are shared mutable state, apply→send is exclusive */
|
|
68
113
|
private chains = new Map<string, Promise<unknown>>()
|
|
114
|
+
/** the bundle is built at most once per process, first browser hit pays it */
|
|
115
|
+
private webJsCache: Promise<string | null> | null = null
|
|
69
116
|
|
|
70
117
|
constructor(
|
|
71
118
|
public modules: ServeModule[],
|
|
72
|
-
private opts: {
|
|
119
|
+
private opts: {
|
|
120
|
+
starter?: ServeStarter
|
|
121
|
+
outputRoot?: string
|
|
122
|
+
loadErrors?: Record<string, string>
|
|
123
|
+
/** web ui bundle provider (run-serve wires loadOrBuildWebJs); absent = api only */
|
|
124
|
+
webJs?: () => Promise<string | null>
|
|
125
|
+
} = {},
|
|
73
126
|
) {
|
|
74
127
|
this.starter = opts.starter ?? realStarter
|
|
75
128
|
}
|
|
@@ -92,9 +145,25 @@ export class ServeApp {
|
|
|
92
145
|
return json(400, { error: `bad url encoding: ${path}` })
|
|
93
146
|
}
|
|
94
147
|
if (req.method === 'GET') {
|
|
148
|
+
// a browser lands on the control panel; every other client keeps the json index.
|
|
149
|
+
// the bundle resolves BEFORE the shell ships: a shell whose /web/app.js 404s is
|
|
150
|
+
// a blank dark page, the json index is a usable answer
|
|
151
|
+
if (segs.length === 0 && this.opts.webJs != null && req.accept?.includes('text/html') === true) {
|
|
152
|
+
this.webJsCache ??= this.opts.webJs()
|
|
153
|
+
if ((await this.webJsCache) != null)
|
|
154
|
+
return { status: 200, contentType: 'text/html; charset=utf-8', body: WEB_SHELL }
|
|
155
|
+
}
|
|
95
156
|
if (segs.length === 0 || (segs[0] === 'drafts' && segs.length === 1)) return this.replyIndex()
|
|
157
|
+
if (segs[0] === 'web' && segs[1] === 'app.js' && segs.length === 2) return await this.replyWebJs()
|
|
96
158
|
if (segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
97
159
|
return this.replyDraft(segs[1], segs[2])
|
|
160
|
+
if (segs[0] === 'run' && segs.length === 2 && segs[1] != null) return this.replyRunStatus(segs[1])
|
|
161
|
+
if (segs[0] === 'run' && segs.length === 3 && segs[1] != null && segs[2] === 'preview')
|
|
162
|
+
return this.replyRunPreview(segs[1])
|
|
163
|
+
if (segs[0] === 'lora-info' && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
164
|
+
return this.replyLoraInfo(segs[1], segs[2])
|
|
165
|
+
if (segs[0] === 'lora-preview' && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
166
|
+
return await this.replyLoraPreview(segs[1], segs[2])
|
|
98
167
|
if (segs[0] === 'outputs') return this.replyOutput(segs.slice(1))
|
|
99
168
|
return json(404, { error: `no route: GET ${path}`, usage: USAGE })
|
|
100
169
|
}
|
|
@@ -103,6 +172,9 @@ export class ServeApp {
|
|
|
103
172
|
if ('error' in target) return json(target.status, { error: target.error })
|
|
104
173
|
return await this.generate(target.mod, target.draft, req)
|
|
105
174
|
}
|
|
175
|
+
if (req.method === 'POST' && segs[0] === 'upload' && segs.length === 1) return this.replyUpload(req)
|
|
176
|
+
if (req.method === 'PUT' && segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
177
|
+
return await this.replySaveDraft(segs[1], segs[2], req)
|
|
106
178
|
return json(404, { error: `no route: ${req.method} ${path}`, usage: USAGE })
|
|
107
179
|
} catch (e) {
|
|
108
180
|
console.error('[serve] request crashed:', e)
|
|
@@ -120,8 +192,26 @@ export class ServeApp {
|
|
|
120
192
|
return ['default', ...onDisk.filter((n) => n !== 'default')]
|
|
121
193
|
}
|
|
122
194
|
|
|
195
|
+
/** THE draft-name gate, shared by every route that turns a url segment into a path.
|
|
196
|
+
* handle() decodes per segment, so `%2F` reaches here as a real `/` while the segment
|
|
197
|
+
* count still looks right — an unguarded reader would read (and RUN) any json on disk */
|
|
198
|
+
private validDraftName(raw: string): string | null {
|
|
199
|
+
const name = raw.trim()
|
|
200
|
+
// length cap: past it the fs answers ENAMETOOLONG as a raw 500
|
|
201
|
+
if (name.length > 100) return null
|
|
202
|
+
return /^[\w][\w .-]*$/.test(name) ? name : null
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** absolute path of a draft file, or null when the name is not one we accept */
|
|
206
|
+
private draftPath(mod: ServeModule, draft: string): string | null {
|
|
207
|
+
const name = this.validDraftName(draft)
|
|
208
|
+
return name == null ? null : join(draftsDirForFile(mod.file), `${name}.json`)
|
|
209
|
+
}
|
|
210
|
+
|
|
123
211
|
private draftExists(mod: ServeModule, draft: string): boolean {
|
|
124
|
-
|
|
212
|
+
const path = this.draftPath(mod, draft)
|
|
213
|
+
if (path == null) return false
|
|
214
|
+
return draft === 'default' || existsSync(path)
|
|
125
215
|
}
|
|
126
216
|
|
|
127
217
|
private resolveDraft(segs: string[]): { mod: ServeModule; draft: string } | { error: string; status: number } {
|
|
@@ -163,8 +253,22 @@ export class ServeApp {
|
|
|
163
253
|
|
|
164
254
|
// #region introspection ----------------------------------------------------
|
|
165
255
|
private describeModule(mod: ServeModule): Record<string, unknown> {
|
|
256
|
+
refreshLoraInfoCacheIfChanged()
|
|
257
|
+
const hostId = mod.dw.host.data.id
|
|
166
258
|
const vars: Record<string, VarDescriptor> = {}
|
|
167
|
-
for (const [name, varDef] of mod.dw.entries())
|
|
259
|
+
for (const [name, varDef] of mod.dw.entries()) {
|
|
260
|
+
const desc = describeVar(varDef)
|
|
261
|
+
// the raw enum values stay the payload keys; the mirror's names are for humans
|
|
262
|
+
if (desc.kind === 'loras' && desc.options != null) {
|
|
263
|
+
const labels: Record<string, string> = {}
|
|
264
|
+
for (const option of desc.options) {
|
|
265
|
+
const label = getLoraDisplayName(option, hostId)
|
|
266
|
+
if (label !== option) labels[option] = label
|
|
267
|
+
}
|
|
268
|
+
if (Object.keys(labels).length > 0) desc.optionLabels = labels
|
|
269
|
+
}
|
|
270
|
+
vars[name] = desc
|
|
271
|
+
}
|
|
168
272
|
return {
|
|
169
273
|
module: mod.key,
|
|
170
274
|
file: mod.file,
|
|
@@ -200,8 +304,8 @@ export class ServeApp {
|
|
|
200
304
|
|
|
201
305
|
/** stored values (toJSON shapes); 'default' without a file falls back to descriptor defaults */
|
|
202
306
|
private draftValues(mod: ServeModule, draft: string): Record<string, unknown> {
|
|
203
|
-
const path =
|
|
204
|
-
if (existsSync(path)) return JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>
|
|
307
|
+
const path = this.draftPath(mod, draft)
|
|
308
|
+
if (path != null && existsSync(path)) return JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>
|
|
205
309
|
const out: Record<string, unknown> = {}
|
|
206
310
|
for (const [name, varDef] of mod.dw.entries()) out[name] = describeVar(varDef).default
|
|
207
311
|
return out
|
|
@@ -219,6 +323,183 @@ export class ServeApp {
|
|
|
219
323
|
return { status: 200, contentType, body: new Uint8Array(readFileSync(abs)) }
|
|
220
324
|
}
|
|
221
325
|
|
|
326
|
+
private async replyWebJs(): Promise<ServeReply> {
|
|
327
|
+
if (this.opts.webJs == null) return json(404, { error: 'web ui not enabled on this server' })
|
|
328
|
+
this.webJsCache ??= this.opts.webJs()
|
|
329
|
+
const js = await this.webJsCache
|
|
330
|
+
if (js == null) return json(404, { error: 'web ui bundle unavailable — see the server log' })
|
|
331
|
+
return { status: 200, contentType: 'text/javascript; charset=utf-8', body: js }
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** browser file → local file an image var can point at (downloadInput family) */
|
|
335
|
+
private replyUpload(req: ServeRequest): ServeReply {
|
|
336
|
+
let parsed: unknown
|
|
337
|
+
try {
|
|
338
|
+
parsed = JSON.parse(req.body ?? '')
|
|
339
|
+
} catch (e) {
|
|
340
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })
|
|
341
|
+
}
|
|
342
|
+
const o = (parsed ?? {}) as { name?: unknown; dataBase64?: unknown }
|
|
343
|
+
if (typeof o.name !== 'string' || o.name === '' || typeof o.dataBase64 !== 'string' || o.dataBase64 === '')
|
|
344
|
+
return json(400, { error: 'upload expects {"name":"<filename>","dataBase64":"<base64 bytes>"}' })
|
|
345
|
+
const bytes = Buffer.from(o.dataBase64, 'base64')
|
|
346
|
+
if (bytes.length === 0) return json(400, { error: 'dataBase64 decoded to zero bytes' })
|
|
347
|
+
const safe = basename(o.name).replace(/[^\w.-]+/g, '_') || 'upload'
|
|
348
|
+
const abs = join(this.outputRoot, 'serve-inputs', `${nanoid(6)}-${safe}`)
|
|
349
|
+
mkdirSync(dirname(abs), { recursive: true })
|
|
350
|
+
writeFileSync(abs, bytes)
|
|
351
|
+
console.log(`[serve] upload → ${abs} (${bytes.length} bytes)`)
|
|
352
|
+
return json(200, { ok: true, path: abs, url: this.outputUrl(abs) })
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// #region drafts write (the web ui's autosave + duplicate ride this) --------
|
|
356
|
+
private async replySaveDraft(modKey: string, rawDraft: string, req: ServeRequest): Promise<ServeReply> {
|
|
357
|
+
const mod = this.moduleByKey(modKey)
|
|
358
|
+
if (mod == null) return json(404, { error: `unknown module '${modKey}'` })
|
|
359
|
+
const draft = this.validDraftName(rawDraft)
|
|
360
|
+
if (draft == null)
|
|
361
|
+
return json(400, { error: `invalid draft name '${rawDraft}' — letters/digits then letters, digits, ". -_"` })
|
|
362
|
+
let parsed: unknown
|
|
363
|
+
try {
|
|
364
|
+
parsed = JSON.parse(req.body ?? '')
|
|
365
|
+
} catch (e) {
|
|
366
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })
|
|
367
|
+
}
|
|
368
|
+
if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
369
|
+
return json(400, { error: 'body must be a json object: { "<var>": value, … }' })
|
|
370
|
+
const values = parsed as Record<string, unknown>
|
|
371
|
+
const known = new Set(mod.dw.entries().map(([k]) => k))
|
|
372
|
+
const unknown = Object.keys(values).filter((k) => !known.has(k))
|
|
373
|
+
if (unknown.length > 0)
|
|
374
|
+
return json(400, { error: `unknown var(s) ${unknown.join(', ')} — vars: ${[...known].join(', ')}` })
|
|
375
|
+
// values are written VERBATIM (toJSON shapes, loadJSON re-validates on read) —
|
|
376
|
+
// under the module mutex, so a save cannot interleave a generate's draft read
|
|
377
|
+
const path = bang(this.draftPath(mod, draft), 'draft name validated just above')
|
|
378
|
+
await this.exclusive(mod.key, () => {
|
|
379
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
380
|
+
writeFileSync(path, JSON.stringify(values, null, 2))
|
|
381
|
+
return Promise.resolve()
|
|
382
|
+
})
|
|
383
|
+
return json(200, { ok: true, module: mod.key, draft, drafts: this.draftsFor(mod) })
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// #region live run state (web ui polling: progress + latent preview) --------
|
|
387
|
+
private liveRuns = new Map<string, ServeExecution>()
|
|
388
|
+
/** seq counts frames so the poller refetches only on a NEW one, not every tick */
|
|
389
|
+
private latentPreviews = new Map<string, { bytes: Uint8Array; mime: string; seq: number }>()
|
|
390
|
+
private latentSeq = 0
|
|
391
|
+
/** promptId → module: `onLatentPreview` is ONE slot per host and two modules can share a
|
|
392
|
+
* host, so frames are routed by the prompt they belong to, never by "the last run started" */
|
|
393
|
+
private promptOwner = new Map<string, string>()
|
|
394
|
+
private latentHosts = new Set<ComfyHost>()
|
|
395
|
+
|
|
396
|
+
private runningModules(): string[] {
|
|
397
|
+
return [...this.liveRuns.entries()]
|
|
398
|
+
.filter(([, e]) => e.status !== 'Success' && e.status !== 'Failure')
|
|
399
|
+
.map(([key]) => key)
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** one dispatcher per host, installed once and left in place (idempotent) */
|
|
403
|
+
private wireLatents(host: ComfyHost): void {
|
|
404
|
+
if (this.latentHosts.has(host)) return
|
|
405
|
+
this.latentHosts.add(host)
|
|
406
|
+
host.onLatentPreview = (p) => {
|
|
407
|
+
const owner = p.promptID != null ? this.promptOwner.get(p.promptID) : undefined
|
|
408
|
+
// an unattributable frame (no promptID yet, e.g. before start() returned) is only
|
|
409
|
+
// safe to show when exactly ONE run is live; otherwise drop it rather than lie
|
|
410
|
+
const running = this.runningModules()
|
|
411
|
+
const key = owner ?? (running.length === 1 ? running[0] : undefined)
|
|
412
|
+
if (key == null) return
|
|
413
|
+
this.latentPreviews.set(key, { bytes: p.bytes, mime: p.mime, seq: ++this.latentSeq })
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
private replyRunStatus(modKey: string): ServeReply {
|
|
418
|
+
const mod = this.moduleByKey(modKey)
|
|
419
|
+
if (mod == null) return json(404, { error: `unknown module '${modKey}'` })
|
|
420
|
+
const exec = this.liveRuns.get(mod.key)
|
|
421
|
+
const running = exec != null && exec.status !== 'Success' && exec.status !== 'Failure'
|
|
422
|
+
return json(200, {
|
|
423
|
+
running,
|
|
424
|
+
status: exec?.status ?? 'idle',
|
|
425
|
+
percent: running ? (exec.progressGlobal?.percent ?? null) : null,
|
|
426
|
+
hasPreview: this.latentPreviews.has(mod.key),
|
|
427
|
+
previewSeq: this.latentPreviews.get(mod.key)?.seq ?? null,
|
|
428
|
+
})
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
private replyRunPreview(modKey: string): ServeReply {
|
|
432
|
+
const mod = this.moduleByKey(modKey)
|
|
433
|
+
if (mod == null) return json(404, { error: `unknown module '${modKey}'` })
|
|
434
|
+
const preview = this.latentPreviews.get(mod.key)
|
|
435
|
+
if (preview == null) return json(404, { error: 'no latent preview yet' })
|
|
436
|
+
return {
|
|
437
|
+
status: 200,
|
|
438
|
+
contentType: preview.mime !== '' ? preview.mime : sniffImageContentType(preview.bytes),
|
|
439
|
+
body: preview.bytes,
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// #region lora hover data ---------------------------------------------------
|
|
444
|
+
private hostById(hostId: string): ComfyHost | null {
|
|
445
|
+
return this.modules.map((m) => m.dw.host).find((h) => h.data.id === hostId) ?? null
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
private hostIds(): string {
|
|
449
|
+
return [...new Set(this.modules.map((m) => m.dw.host.data.id))].join(', ')
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** mirror-backed text for the hover pane, no network */
|
|
453
|
+
private replyLoraInfo(hostId: string, lora: string): ServeReply {
|
|
454
|
+
if (this.hostById(hostId) == null)
|
|
455
|
+
return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` })
|
|
456
|
+
refreshLoraInfoCacheIfChanged()
|
|
457
|
+
return json(200, {
|
|
458
|
+
name: lora,
|
|
459
|
+
displayName: getLoraDisplayName(lora, hostId),
|
|
460
|
+
triggerWords: getLoraTriggerWords(lora, hostId),
|
|
461
|
+
})
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** preview url resolution misses per host, so an absent lora-manager costs ONE sweep, not one
|
|
465
|
+
* per hover. An UNREACHABLE host evicts itself: the host coming back must not stay 404 forever */
|
|
466
|
+
private previewSweeps = new Map<string, Promise<{ status: string; map: Map<string, string> | null }>>()
|
|
467
|
+
|
|
468
|
+
private async replyLoraPreview(hostId: string, lora: string): Promise<ServeReply> {
|
|
469
|
+
const host = this.hostById(hostId)
|
|
470
|
+
if (host == null) return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` })
|
|
471
|
+
refreshLoraInfoCacheIfChanged()
|
|
472
|
+
let url = getLoraPreviewUrl(lora, hostId)
|
|
473
|
+
if (url == null) {
|
|
474
|
+
// the TUI's fallback: unsynced mirror (or a lora it never saw) → ask the live host once
|
|
475
|
+
let sweep = this.previewSweeps.get(hostId)
|
|
476
|
+
if (sweep == null) {
|
|
477
|
+
sweep = fetchLoraList(host).then((r) => {
|
|
478
|
+
if (r.status === 'unreachable') {
|
|
479
|
+
this.previewSweeps.delete(hostId)
|
|
480
|
+
return { status: r.status, map: null }
|
|
481
|
+
}
|
|
482
|
+
return { status: r.status, map: r.status === 'absent' ? null : loraPreviewMapFrom(r.items) }
|
|
483
|
+
})
|
|
484
|
+
this.previewSweeps.set(hostId, sweep)
|
|
485
|
+
}
|
|
486
|
+
const swept = await sweep
|
|
487
|
+
url = swept.map?.get(loraKey(lora)) ?? null
|
|
488
|
+
// each miss has its OWN cause (the LorasSt rule): the wrong advice sends the user hunting
|
|
489
|
+
if (url == null && swept.status === 'unreachable')
|
|
490
|
+
return json(404, { error: `host '${hostId}' is unreachable — no preview to fetch` })
|
|
491
|
+
if (url == null && swept.status === 'absent')
|
|
492
|
+
return json(404, { error: `lora-manager extension not detected on '${hostId}'` })
|
|
493
|
+
}
|
|
494
|
+
if (url == null)
|
|
495
|
+
return json(404, { error: `no preview known for '${lora}' (run: comfy-ts loras --id ${hostId})` })
|
|
496
|
+
const bytes = await fetchLoraPreviewBytes(host, url)
|
|
497
|
+
// one 404 for two causes on purpose: unreachable host and no-image both mean "nothing to show"
|
|
498
|
+
if (bytes == null)
|
|
499
|
+
return json(404, { error: `no image preview for '${lora}' (host '${hostId}' unreachable, or not an image)` })
|
|
500
|
+
return { status: 200, contentType: sniffImageContentType(bytes), body: bytes }
|
|
501
|
+
}
|
|
502
|
+
|
|
222
503
|
private outputUrl(absPath: string): string | null {
|
|
223
504
|
if (!absPath.startsWith(this.outputRoot + '/')) return null
|
|
224
505
|
const rel = absPath.slice(this.outputRoot.length + 1)
|
|
@@ -246,8 +527,14 @@ export class ServeApp {
|
|
|
246
527
|
if ('error' in started) return json(started.status, { error: started.error })
|
|
247
528
|
|
|
248
529
|
const execution = started.execution
|
|
530
|
+
this.liveRuns.set(mod.key, execution)
|
|
531
|
+
this.promptOwner.set(execution.data.id, mod.key)
|
|
249
532
|
console.log(`[serve] → ${mod.key}/${draft} (prompt ${execution.data.id})`)
|
|
250
|
-
|
|
533
|
+
try {
|
|
534
|
+
await execution.done
|
|
535
|
+
} finally {
|
|
536
|
+
this.promptOwner.delete(execution.data.id)
|
|
537
|
+
}
|
|
251
538
|
const durationMs = Date.now() - t0
|
|
252
539
|
|
|
253
540
|
if (execution.status === 'Failure') {
|
|
@@ -297,7 +584,8 @@ export class ServeApp {
|
|
|
297
584
|
): Promise<{ execution: ServeExecution } | { error: string; status: number }> {
|
|
298
585
|
// 1. reset, then load the draft FRESH from disk (TUI edits between requests apply)
|
|
299
586
|
for (const [, varDef] of mod.dw.entries()) varDef.reset()
|
|
300
|
-
const draftPath =
|
|
587
|
+
const draftPath = this.draftPath(mod, draft)
|
|
588
|
+
if (draftPath == null) return { status: 404, error: `no draft '${draft}'` }
|
|
301
589
|
if (existsSync(draftPath)) {
|
|
302
590
|
try {
|
|
303
591
|
const values = JSON.parse(readFileSync(draftPath, 'utf8')) as Record<string, unknown>
|
|
@@ -307,6 +595,12 @@ export class ServeApp {
|
|
|
307
595
|
}
|
|
308
596
|
}
|
|
309
597
|
|
|
598
|
+
// the DRAFT's seed values, before payload overrides: the +/- continuation
|
|
599
|
+
// compares against what the draft file says, not what a payload injected
|
|
600
|
+
const draftSeedValues = new Map<string, number>()
|
|
601
|
+
for (const [k, varDef] of mod.dw.entries())
|
|
602
|
+
if (varDef.kind === 'seed') draftSeedValues.set(k, (varDef as SeedVar).value)
|
|
603
|
+
|
|
310
604
|
// 2. payload overrides (image urls download first, so the var gets a local path)
|
|
311
605
|
const varMap = new Map(mod.dw.entries())
|
|
312
606
|
for (const [k, rawValue] of Object.entries(payload)) {
|
|
@@ -341,18 +635,25 @@ export class ServeApp {
|
|
|
341
635
|
if (varDef.kind !== 'seed') continue
|
|
342
636
|
const seedVar = varDef as SeedVar
|
|
343
637
|
const stateKey = `${mod.key}/${draft}/${k}`
|
|
638
|
+
const draftValue = draftSeedValues.get(k) ?? seedVar.value
|
|
344
639
|
if (!(k in payload)) {
|
|
345
640
|
if (seedVar.mode === '?') seedVar.randomize()
|
|
346
641
|
else if (seedVar.mode === '+' || seedVar.mode === '-') {
|
|
347
|
-
const
|
|
348
|
-
|
|
642
|
+
const prev = this.seedState.get(stateKey)
|
|
643
|
+
// continue only while the draft still holds the value the chain grew from
|
|
644
|
+
if (prev != null && prev.draftBase === draftValue)
|
|
645
|
+
seedVar.set(prev.last + (seedVar.mode === '+' ? 1 : -1))
|
|
349
646
|
}
|
|
350
647
|
}
|
|
351
|
-
this.seedState.set(stateKey, seedVar.value)
|
|
648
|
+
this.seedState.set(stateKey, { last: seedVar.value, draftBase: draftValue })
|
|
352
649
|
seeds[k] = seedVar.value
|
|
353
650
|
}
|
|
354
651
|
|
|
355
|
-
// 5. send (build + POST /prompt); the wait for outputs happens OUTSIDE the mutex
|
|
652
|
+
// 5. send (build + POST /prompt); the wait for outputs happens OUTSIDE the mutex.
|
|
653
|
+
// latent frames feed the web ui's /run/<module>/preview poll (ExecSt's pattern);
|
|
654
|
+
// the previous run's preview must not linger over the new one
|
|
655
|
+
this.latentPreviews.delete(mod.key)
|
|
656
|
+
this.wireLatents(mod.dw.host)
|
|
356
657
|
try {
|
|
357
658
|
return { execution: await this.starter(mod) }
|
|
358
659
|
} catch (e) {
|
|
@@ -22,6 +22,8 @@ export type VarDescriptor = {
|
|
|
22
22
|
choices?: readonly string[]
|
|
23
23
|
/** loras: the resolved option list */
|
|
24
24
|
options?: readonly string[]
|
|
25
|
+
/** loras: human display names from the lora-manager mirror, keyed by option — entries only where the label differs (filled by ServeApp.describeModule, which knows the host) */
|
|
26
|
+
optionLabels?: Record<string, string>
|
|
25
27
|
min?: number
|
|
26
28
|
max?: number
|
|
27
29
|
presets?: SizePreset[]
|
|
@@ -55,7 +57,10 @@ export function describeVar(varDef: AnyVar): VarDescriptor {
|
|
|
55
57
|
const v = varDef as SeedVar
|
|
56
58
|
return {
|
|
57
59
|
...base,
|
|
58
|
-
|
|
60
|
+
// defaultMode, never the LIVE mode: serve's vars are shared mutable state, so a
|
|
61
|
+
// run under '?' would otherwise leak its mode into every fileless draft's defaults
|
|
62
|
+
// (and the web ui autosaves those defaults straight back into the draft file)
|
|
63
|
+
default: { mode: v.defaultMode, value: v.defaultValue },
|
|
59
64
|
payload: 'number (fixed) or {"mode":"=|+|-|?","value":number}',
|
|
60
65
|
}
|
|
61
66
|
}
|
|
@@ -9,6 +9,7 @@ import { findDefinedWorkflow } from 'src/cli/tui/findDefinedWorkflow.ts'
|
|
|
9
9
|
import { draftKeyForFile } from 'src/cli/tui/state/DraftsSt.ts'
|
|
10
10
|
import { describeVar, renderDescriptorLine } from 'src/cli/serve/describeVar.ts'
|
|
11
11
|
import { ServeApp, type ServeModule } from 'src/cli/serve/ServeApp.ts'
|
|
12
|
+
import { loadOrBuildWebJs } from 'src/cli/serve/webBundle.ts'
|
|
12
13
|
import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
|
|
13
14
|
|
|
14
15
|
const DEFAULT_PORT = 8288
|
|
@@ -43,7 +44,7 @@ export function makeRequestListener(app: ServeApp): (req: IncomingMessage, res:
|
|
|
43
44
|
// local bridge, no auth by design: open CORS so browser frontends can call it
|
|
44
45
|
const cors = {
|
|
45
46
|
'access-control-allow-origin': '*',
|
|
46
|
-
'access-control-allow-methods': 'GET, POST, OPTIONS',
|
|
47
|
+
'access-control-allow-methods': 'GET, POST, PUT, OPTIONS',
|
|
47
48
|
'access-control-allow-headers': 'content-type, accept',
|
|
48
49
|
}
|
|
49
50
|
const chunks: Buffer[] = []
|
|
@@ -129,7 +130,7 @@ export async function runServe(args: string[]): Promise<number> {
|
|
|
129
130
|
return 1
|
|
130
131
|
}
|
|
131
132
|
|
|
132
|
-
const app = new ServeApp(modules, { loadErrors })
|
|
133
|
+
const app = new ServeApp(modules, { loadErrors, webJs: loadOrBuildWebJs })
|
|
133
134
|
printStartup(app, parsed.bind, parsed.port)
|
|
134
135
|
|
|
135
136
|
const server = createServer(makeRequestListener(app))
|
|
@@ -166,4 +167,5 @@ function printStartup(app: ServeApp, bind: string, port: number): void {
|
|
|
166
167
|
`\ntry: curl -X POST ${base}/generate/${encodeURIComponent(firstMod.key)}/default -H 'content-type: application/json' -d '{}'`,
|
|
167
168
|
)
|
|
168
169
|
console.log(`docs: GET ${base}/drafts (json index of everything above)`)
|
|
170
|
+
console.log(`ui: open ${base}/ in a browser (every var as a form control)`)
|
|
169
171
|
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// typed fetch layer over the serve json api — the ONLY web-ui module that talks http
|
|
2
|
+
import type { VarDescriptor } from 'src/cli/serve/describeVar.ts'
|
|
3
|
+
|
|
4
|
+
export type ModuleDescription = {
|
|
5
|
+
module: string
|
|
6
|
+
file: string
|
|
7
|
+
host: string
|
|
8
|
+
drafts: string[]
|
|
9
|
+
vars: Record<string, VarDescriptor>
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export type IndexPayload = {
|
|
13
|
+
workflows: ModuleDescription[]
|
|
14
|
+
loadErrors?: Record<string, string>
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export type GeneratedImage = { filename: string; url: string | null; absPath: string | null }
|
|
18
|
+
|
|
19
|
+
export type GenerateOk = {
|
|
20
|
+
ok: true
|
|
21
|
+
module: string
|
|
22
|
+
draft: string
|
|
23
|
+
promptId: string
|
|
24
|
+
durationMs: number
|
|
25
|
+
seeds: Record<string, number>
|
|
26
|
+
images: GeneratedImage[]
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function jsonFetch<T>(url: string, init?: RequestInit): Promise<T> {
|
|
30
|
+
const res = await fetch(url, init)
|
|
31
|
+
const body = (await res.json().catch(() => null)) as (T & { error?: string }) | null
|
|
32
|
+
if (!res.ok || body == null) throw new Error(body?.error ?? `http ${res.status} on ${url}`)
|
|
33
|
+
return body
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function fetchIndex(): Promise<IndexPayload> {
|
|
37
|
+
return jsonFetch('/drafts')
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function fetchDraftValues(p: { module: string; draft: string }): Promise<{ values: Record<string, unknown> }> {
|
|
41
|
+
return jsonFetch(`/drafts/${encodeURIComponent(p.module)}/${encodeURIComponent(p.draft)}`)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function postGenerate(p: {
|
|
45
|
+
module: string
|
|
46
|
+
draft: string
|
|
47
|
+
payload: Record<string, unknown>
|
|
48
|
+
}): Promise<GenerateOk> {
|
|
49
|
+
return jsonFetch(`/generate/${encodeURIComponent(p.module)}/${encodeURIComponent(p.draft)}`, {
|
|
50
|
+
method: 'POST',
|
|
51
|
+
headers: { 'content-type': 'application/json' },
|
|
52
|
+
body: JSON.stringify(p.payload),
|
|
53
|
+
})
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function saveDraft(
|
|
57
|
+
p: { module: string; draft: string; values: Record<string, unknown> },
|
|
58
|
+
opts: { keepalive?: boolean } = {},
|
|
59
|
+
): Promise<{ ok: true; drafts: string[] }> {
|
|
60
|
+
return jsonFetch(`/drafts/${encodeURIComponent(p.module)}/${encodeURIComponent(p.draft)}`, {
|
|
61
|
+
method: 'PUT',
|
|
62
|
+
headers: { 'content-type': 'application/json' },
|
|
63
|
+
body: JSON.stringify(p.values),
|
|
64
|
+
// keepalive survives page teardown — the beforeunload flush rides it
|
|
65
|
+
keepalive: opts.keepalive === true,
|
|
66
|
+
})
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export type RunStatus = {
|
|
70
|
+
running: boolean
|
|
71
|
+
status: string
|
|
72
|
+
percent: number | null
|
|
73
|
+
hasPreview: boolean
|
|
74
|
+
previewSeq: number | null
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function fetchRunStatus(p: { module: string }): Promise<RunStatus> {
|
|
78
|
+
return jsonFetch(`/run/${encodeURIComponent(p.module)}`)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function runPreviewSrc(p: { module: string; tick: number }): string {
|
|
82
|
+
// tick busts the browser cache: same url, new latent every poll
|
|
83
|
+
return `/run/${encodeURIComponent(p.module)}/preview?t=${p.tick}`
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export type LoraInfo = { name: string; displayName: string; triggerWords: string[] }
|
|
87
|
+
|
|
88
|
+
export function fetchLoraInfo(p: { host: string; name: string }): Promise<LoraInfo> {
|
|
89
|
+
return jsonFetch(`/lora-info/${encodeURIComponent(p.host)}/${encodeURIComponent(p.name)}`)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function loraPreviewSrc(p: { host: string; name: string }): string {
|
|
93
|
+
return `/lora-preview/${encodeURIComponent(p.host)}/${encodeURIComponent(p.name)}`
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export async function uploadFile(p: { file: File }): Promise<{ path: string; url: string | null }> {
|
|
97
|
+
const bytes = new Uint8Array(await p.file.arrayBuffer())
|
|
98
|
+
let bin = ''
|
|
99
|
+
for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
|
|
100
|
+
return jsonFetch('/upload', {
|
|
101
|
+
method: 'POST',
|
|
102
|
+
headers: { 'content-type': 'application/json' },
|
|
103
|
+
body: JSON.stringify({ name: p.file.name, dataBase64: btoa(bin) }),
|
|
104
|
+
})
|
|
105
|
+
}
|