comfy-ts 2.5.0 → 2.7.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 +15 -2
- 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 +5 -5
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +7 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +24 -18
- package/dist/index.d.ts +24 -18
- package/dist/index.js +7 -2
- package/dist/index.js.map +1 -1
- package/dist/{run-serve-D47Zas-a.js → run-serve-D1Tsuru9.js} +494 -20
- package/dist/run-serve-D1Tsuru9.js.map +1 -0
- package/dist/{run-tui-t2TRBN0H.js → run-tui-JxlEbb_f.js} +511 -331
- package/dist/run-tui-JxlEbb_f.js.map +1 -0
- package/dist/serve-web.js +273 -0
- package/dist/{state-DY3Mp9Cl.js → state-CaHeDL-0.js} +7 -13
- package/dist/state-CaHeDL-0.js.map +1 -0
- package/dist/web.d.ts +24 -18
- package/dist/web.js +7 -2
- package/dist/web.js.map +1 -1
- package/examples/web/tsconfig.json +4 -1
- package/package.json +7 -5
- package/src/cli/comfy-ts-cli.ts +1 -1
- package/src/cli/serve/ServeApp.ts +383 -14
- package/src/cli/serve/describeVar.ts +6 -1
- package/src/cli/serve/promptEnhancers.ts +69 -0
- package/src/cli/serve/run-serve.ts +41 -7
- package/src/cli/serve/safeName.ts +12 -0
- package/src/cli/serve/web/api.ts +128 -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 +254 -0
- package/src/cli/serve/web/components/Sidebar.tsx +42 -0
- package/src/cli/serve/web/components/VarsForm.tsx +184 -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/llm.ts +254 -0
- package/src/cli/serve/web/main.tsx +18 -0
- package/src/cli/serve/web/state/EnhancerSt.ts +481 -0
- package/src/cli/serve/web/state/FormSt.ts +180 -0
- package/src/cli/serve/web/state/RunSt.ts +136 -0
- package/src/cli/serve/web/state/WebSt.ts +235 -0
- package/src/cli/serve/web/state/payload.ts +110 -0
- package/src/cli/serve/web/styles.ts +261 -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/state.ts +6 -0
- 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
|
@@ -9,7 +9,10 @@
|
|
|
9
9
|
"src/*": ["../../src/*"],
|
|
10
10
|
"comfy-ts": ["../../src/index.ts"],
|
|
11
11
|
"comfy-ts/web": ["../../src/web.ts"]
|
|
12
|
-
}
|
|
12
|
+
},
|
|
13
|
+
// its own incremental cache: a shared one across configs with different include
|
|
14
|
+
// sets makes a typecheck fail on a symbol that exists (tests/tsconfig-buildinfo)
|
|
15
|
+
"tsBuildInfoFile": "../../node_modules/.cache/tsbuildinfo-examples-web.json"
|
|
13
16
|
},
|
|
14
17
|
"include": [".", "../../src"]
|
|
15
18
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "comfy-ts",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.7.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
|
}
|
package/src/cli/comfy-ts-cli.ts
CHANGED
|
@@ -31,7 +31,7 @@ Usage:
|
|
|
31
31
|
host.defineWorkflow(...)); no arg scans cwd + the examples bundled
|
|
32
32
|
with comfy-ts, an explicit dir/file limits to it (file preselected)
|
|
33
33
|
|
|
34
|
-
comfy-ts serve [dir | workflow-module.ts] [--port 8288] [--
|
|
34
|
+
comfy-ts serve [dir | workflow-module.ts] [--port 8288] [--host 127.0.0.1]
|
|
35
35
|
drafts as a local HTTP generation API: POST /generate/<module>/<draft>
|
|
36
36
|
with { ...vars } overriding the draft's values (blocking; raw image
|
|
37
37
|
bytes under Accept: image/*), GET /drafts self-describes every var,
|
|
@@ -1,14 +1,25 @@
|
|
|
1
1
|
// `comfy-ts serve` request handling, transport-free: run-serve owns node:http,
|
|
2
2
|
// tests call handle() directly with an injected starter. Full contract:
|
|
3
3
|
// agent/architecture.md item 12.
|
|
4
|
-
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
4
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
5
5
|
import { nanoid } from 'nanoid'
|
|
6
6
|
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
|
+
import { deletePromptEnhancer, listPromptEnhancers, writePromptEnhancer } from 'src/cli/serve/promptEnhancers.ts'
|
|
10
|
+
import { validStoreName } from 'src/cli/serve/safeName.ts'
|
|
9
11
|
import { draftsDirForFile, listDraftsForFile } from 'src/cli/tui/state/DraftsSt.ts'
|
|
12
|
+
import {
|
|
13
|
+
getLoraDisplayName,
|
|
14
|
+
getLoraPreviewUrl,
|
|
15
|
+
getLoraTriggerWords,
|
|
16
|
+
refreshLoraInfoCacheIfChanged,
|
|
17
|
+
} from 'src/host/loraInfoCache.ts'
|
|
18
|
+
import { fetchLoraList, fetchLoraPreviewBytes, loraKey, loraPreviewMapFrom } from 'src/host/loraManagerApi.ts'
|
|
19
|
+
import type { ComfyHost } from 'src/host/ComfyHost.ts'
|
|
10
20
|
import type { ImageVar, SeedVar } from 'src/vars/ComfyVars.ts'
|
|
11
21
|
import type { DefinedWorkflow } from 'src/vars/DefinedWorkflow.ts'
|
|
22
|
+
import { bang } from 'src/utils/bang.ts'
|
|
12
23
|
import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
|
|
13
24
|
|
|
14
25
|
export type ServeModule = { key: string; file: string; dw: DefinedWorkflow }
|
|
@@ -20,6 +31,8 @@ export type ServeExecution = {
|
|
|
20
31
|
status: string
|
|
21
32
|
images: { absPath: string | null; filename: string }[]
|
|
22
33
|
data: { id: string; error?: unknown }
|
|
34
|
+
/** live global progress (ComfyExecution has it; fakes may omit) — the /run/<module> poll reads it */
|
|
35
|
+
progressGlobal?: { percent: number }
|
|
23
36
|
}
|
|
24
37
|
|
|
25
38
|
export type ServeStarter = (mod: ServeModule) => Promise<ServeExecution>
|
|
@@ -48,28 +61,73 @@ const CONTENT_TYPES: Record<string, string> = {
|
|
|
48
61
|
'.txt': 'text/plain',
|
|
49
62
|
}
|
|
50
63
|
|
|
64
|
+
/** magic-byte sniff for the preview proxy — fetchLoraPreviewBytes already guarantees an image */
|
|
65
|
+
function sniffImageContentType(bytes: Uint8Array): string {
|
|
66
|
+
if (bytes[0] === 0x89 && bytes[1] === 0x50) return 'image/png'
|
|
67
|
+
if (bytes[0] === 0xff && bytes[1] === 0xd8) return 'image/jpeg'
|
|
68
|
+
if (bytes[0] === 0x47 && bytes[1] === 0x49) return 'image/gif'
|
|
69
|
+
if (bytes[0] === 0x52 && bytes[1] === 0x49) return 'image/webp' // RIFF container
|
|
70
|
+
return 'application/octet-stream'
|
|
71
|
+
}
|
|
72
|
+
|
|
51
73
|
function json(status: number, payload: unknown): ServeReply {
|
|
52
74
|
return { status, contentType: 'application/json', body: JSON.stringify(payload, null, 2) }
|
|
53
75
|
}
|
|
54
76
|
|
|
55
77
|
const USAGE = [
|
|
78
|
+
'GET / in a browser — web control panel (every var as a form control)',
|
|
56
79
|
'GET /drafts — every served workflow, its drafts and var descriptors',
|
|
57
80
|
'GET /drafts/<module>/<draft> — one draft with its stored values',
|
|
58
81
|
'POST /generate/<module>/<draft> with { ...vars } — run, blocking',
|
|
59
82
|
'POST /generate/<draft> — unqualified, when unambiguous',
|
|
83
|
+
'PUT /drafts/<module>/<draft> with { ...vars } — save (or duplicate to a new name) a draft',
|
|
84
|
+
'DELETE /drafts/<module>/<draft> — delete that draft file',
|
|
85
|
+
'GET /run/<module> — live run status · /run/<module>/preview — latent preview bytes',
|
|
86
|
+
'POST /upload with {"name","dataBase64"} — store a browser file for an image var',
|
|
87
|
+
'GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)',
|
|
88
|
+
'GET /lora-preview/<hostId>/<lora> — preview image bytes',
|
|
89
|
+
'GET /prompt-enhancers — the web ui master prompts (.comfy-ts/prompt-enhancers/*.md)',
|
|
90
|
+
'PUT /prompt-enhancers/<name> with {"text"} — write one · DELETE /prompt-enhancers/<name> — remove it',
|
|
60
91
|
'GET /outputs/<path> — generated files',
|
|
61
92
|
]
|
|
62
93
|
|
|
94
|
+
/** the html shell; the app itself is ONE bundle at /web/app.js */
|
|
95
|
+
const WEB_SHELL = `<!doctype html>
|
|
96
|
+
<html lang="en">
|
|
97
|
+
<head>
|
|
98
|
+
<meta charset="utf-8">
|
|
99
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
100
|
+
<title>comfy-ts serve</title>
|
|
101
|
+
<style>html{background:#101217;color:#e8eaf0}</style>
|
|
102
|
+
</head>
|
|
103
|
+
<body>
|
|
104
|
+
<div id="root"></div>
|
|
105
|
+
<script type="module" src="/web/app.js"></script>
|
|
106
|
+
</body>
|
|
107
|
+
</html>
|
|
108
|
+
`
|
|
109
|
+
|
|
63
110
|
export class ServeApp {
|
|
64
111
|
private starter: ServeStarter
|
|
65
|
-
/** last SERVED seed per `module/draft/var` — '+'/'-' modes continue from it
|
|
66
|
-
|
|
112
|
+
/** last SERVED seed per `module/draft/var` — '+'/'-' modes continue from it.
|
|
113
|
+
* draftBase remembers which DRAFT value the continuation grew from: when the
|
|
114
|
+
* draft's seed changes (the web form autosaves a typed value), the typed
|
|
115
|
+
* value wins and the continuation restarts there */
|
|
116
|
+
private seedState = new Map<string, { last: number; draftBase: number }>()
|
|
67
117
|
/** per-module promise chain: vars are shared mutable state, apply→send is exclusive */
|
|
68
118
|
private chains = new Map<string, Promise<unknown>>()
|
|
119
|
+
/** the bundle is built at most once per process, first browser hit pays it */
|
|
120
|
+
private webJsCache: Promise<string | null> | null = null
|
|
69
121
|
|
|
70
122
|
constructor(
|
|
71
123
|
public modules: ServeModule[],
|
|
72
|
-
private opts: {
|
|
124
|
+
private opts: {
|
|
125
|
+
starter?: ServeStarter
|
|
126
|
+
outputRoot?: string
|
|
127
|
+
loadErrors?: Record<string, string>
|
|
128
|
+
/** web ui bundle provider (run-serve wires loadOrBuildWebJs); absent = api only */
|
|
129
|
+
webJs?: () => Promise<string | null>
|
|
130
|
+
} = {},
|
|
73
131
|
) {
|
|
74
132
|
this.starter = opts.starter ?? realStarter
|
|
75
133
|
}
|
|
@@ -92,9 +150,26 @@ export class ServeApp {
|
|
|
92
150
|
return json(400, { error: `bad url encoding: ${path}` })
|
|
93
151
|
}
|
|
94
152
|
if (req.method === 'GET') {
|
|
153
|
+
// a browser lands on the control panel; every other client keeps the json index.
|
|
154
|
+
// the bundle resolves BEFORE the shell ships: a shell whose /web/app.js 404s is
|
|
155
|
+
// a blank dark page, the json index is a usable answer
|
|
156
|
+
if (segs.length === 0 && this.opts.webJs != null && req.accept?.includes('text/html') === true) {
|
|
157
|
+
this.webJsCache ??= this.opts.webJs()
|
|
158
|
+
if ((await this.webJsCache) != null)
|
|
159
|
+
return { status: 200, contentType: 'text/html; charset=utf-8', body: WEB_SHELL }
|
|
160
|
+
}
|
|
95
161
|
if (segs.length === 0 || (segs[0] === 'drafts' && segs.length === 1)) return this.replyIndex()
|
|
162
|
+
if (segs[0] === 'web' && segs[1] === 'app.js' && segs.length === 2) return await this.replyWebJs()
|
|
96
163
|
if (segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
97
164
|
return this.replyDraft(segs[1], segs[2])
|
|
165
|
+
if (segs[0] === 'run' && segs.length === 2 && segs[1] != null) return this.replyRunStatus(segs[1])
|
|
166
|
+
if (segs[0] === 'run' && segs.length === 3 && segs[1] != null && segs[2] === 'preview')
|
|
167
|
+
return this.replyRunPreview(segs[1])
|
|
168
|
+
if (segs[0] === 'lora-info' && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
169
|
+
return this.replyLoraInfo(segs[1], segs[2])
|
|
170
|
+
if (segs[0] === 'lora-preview' && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
171
|
+
return await this.replyLoraPreview(segs[1], segs[2])
|
|
172
|
+
if (segs[0] === 'prompt-enhancers' && segs.length === 1) return this.replyPromptEnhancers()
|
|
98
173
|
if (segs[0] === 'outputs') return this.replyOutput(segs.slice(1))
|
|
99
174
|
return json(404, { error: `no route: GET ${path}`, usage: USAGE })
|
|
100
175
|
}
|
|
@@ -103,6 +178,15 @@ export class ServeApp {
|
|
|
103
178
|
if ('error' in target) return json(target.status, { error: target.error })
|
|
104
179
|
return await this.generate(target.mod, target.draft, req)
|
|
105
180
|
}
|
|
181
|
+
if (req.method === 'POST' && segs[0] === 'upload' && segs.length === 1) return this.replyUpload(req)
|
|
182
|
+
if (req.method === 'PUT' && segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
183
|
+
return await this.replySaveDraft(segs[1], segs[2], req)
|
|
184
|
+
if (req.method === 'DELETE' && segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
185
|
+
return await this.replyDeleteDraft(segs[1], segs[2])
|
|
186
|
+
if (req.method === 'PUT' && segs[0] === 'prompt-enhancers' && segs.length === 2 && segs[1] != null)
|
|
187
|
+
return this.replySavePromptEnhancer(segs[1], req)
|
|
188
|
+
if (req.method === 'DELETE' && segs[0] === 'prompt-enhancers' && segs.length === 2 && segs[1] != null)
|
|
189
|
+
return this.replyDeletePromptEnhancer(segs[1])
|
|
106
190
|
return json(404, { error: `no route: ${req.method} ${path}`, usage: USAGE })
|
|
107
191
|
} catch (e) {
|
|
108
192
|
console.error('[serve] request crashed:', e)
|
|
@@ -120,8 +204,22 @@ export class ServeApp {
|
|
|
120
204
|
return ['default', ...onDisk.filter((n) => n !== 'default')]
|
|
121
205
|
}
|
|
122
206
|
|
|
207
|
+
/** THE draft-name gate, shared by every route that turns a url segment into a path
|
|
208
|
+
* (safeName.ts owns the rule — the prompt-enhancer routes call the same function) */
|
|
209
|
+
private validDraftName(raw: string): string | null {
|
|
210
|
+
return validStoreName(raw)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** absolute path of a draft file, or null when the name is not one we accept */
|
|
214
|
+
private draftPath(mod: ServeModule, draft: string): string | null {
|
|
215
|
+
const name = this.validDraftName(draft)
|
|
216
|
+
return name == null ? null : join(draftsDirForFile(mod.file), `${name}.json`)
|
|
217
|
+
}
|
|
218
|
+
|
|
123
219
|
private draftExists(mod: ServeModule, draft: string): boolean {
|
|
124
|
-
|
|
220
|
+
const path = this.draftPath(mod, draft)
|
|
221
|
+
if (path == null) return false
|
|
222
|
+
return draft === 'default' || existsSync(path)
|
|
125
223
|
}
|
|
126
224
|
|
|
127
225
|
private resolveDraft(segs: string[]): { mod: ServeModule; draft: string } | { error: string; status: number } {
|
|
@@ -163,8 +261,22 @@ export class ServeApp {
|
|
|
163
261
|
|
|
164
262
|
// #region introspection ----------------------------------------------------
|
|
165
263
|
private describeModule(mod: ServeModule): Record<string, unknown> {
|
|
264
|
+
refreshLoraInfoCacheIfChanged()
|
|
265
|
+
const hostId = mod.dw.host.data.id
|
|
166
266
|
const vars: Record<string, VarDescriptor> = {}
|
|
167
|
-
for (const [name, varDef] of mod.dw.entries())
|
|
267
|
+
for (const [name, varDef] of mod.dw.entries()) {
|
|
268
|
+
const desc = describeVar(varDef)
|
|
269
|
+
// the raw enum values stay the payload keys; the mirror's names are for humans
|
|
270
|
+
if (desc.kind === 'loras' && desc.options != null) {
|
|
271
|
+
const labels: Record<string, string> = {}
|
|
272
|
+
for (const option of desc.options) {
|
|
273
|
+
const label = getLoraDisplayName(option, hostId)
|
|
274
|
+
if (label !== option) labels[option] = label
|
|
275
|
+
}
|
|
276
|
+
if (Object.keys(labels).length > 0) desc.optionLabels = labels
|
|
277
|
+
}
|
|
278
|
+
vars[name] = desc
|
|
279
|
+
}
|
|
168
280
|
return {
|
|
169
281
|
module: mod.key,
|
|
170
282
|
file: mod.file,
|
|
@@ -200,8 +312,8 @@ export class ServeApp {
|
|
|
200
312
|
|
|
201
313
|
/** stored values (toJSON shapes); 'default' without a file falls back to descriptor defaults */
|
|
202
314
|
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>
|
|
315
|
+
const path = this.draftPath(mod, draft)
|
|
316
|
+
if (path != null && existsSync(path)) return JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>
|
|
205
317
|
const out: Record<string, unknown> = {}
|
|
206
318
|
for (const [name, varDef] of mod.dw.entries()) out[name] = describeVar(varDef).default
|
|
207
319
|
return out
|
|
@@ -219,6 +331,243 @@ export class ServeApp {
|
|
|
219
331
|
return { status: 200, contentType, body: new Uint8Array(readFileSync(abs)) }
|
|
220
332
|
}
|
|
221
333
|
|
|
334
|
+
private async replyWebJs(): Promise<ServeReply> {
|
|
335
|
+
if (this.opts.webJs == null) return json(404, { error: 'web ui not enabled on this server' })
|
|
336
|
+
this.webJsCache ??= this.opts.webJs()
|
|
337
|
+
const js = await this.webJsCache
|
|
338
|
+
if (js == null) return json(404, { error: 'web ui bundle unavailable — see the server log' })
|
|
339
|
+
return { status: 200, contentType: 'text/javascript; charset=utf-8', body: js }
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** browser file → local file an image var can point at (downloadInput family) */
|
|
343
|
+
private replyUpload(req: ServeRequest): ServeReply {
|
|
344
|
+
let parsed: unknown
|
|
345
|
+
try {
|
|
346
|
+
parsed = JSON.parse(req.body ?? '')
|
|
347
|
+
} catch (e) {
|
|
348
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })
|
|
349
|
+
}
|
|
350
|
+
const o = (parsed ?? {}) as { name?: unknown; dataBase64?: unknown }
|
|
351
|
+
if (typeof o.name !== 'string' || o.name === '' || typeof o.dataBase64 !== 'string' || o.dataBase64 === '')
|
|
352
|
+
return json(400, { error: 'upload expects {"name":"<filename>","dataBase64":"<base64 bytes>"}' })
|
|
353
|
+
const bytes = Buffer.from(o.dataBase64, 'base64')
|
|
354
|
+
if (bytes.length === 0) return json(400, { error: 'dataBase64 decoded to zero bytes' })
|
|
355
|
+
const safe = basename(o.name).replace(/[^\w.-]+/g, '_') || 'upload'
|
|
356
|
+
const abs = join(this.outputRoot, 'serve-inputs', `${nanoid(6)}-${safe}`)
|
|
357
|
+
mkdirSync(dirname(abs), { recursive: true })
|
|
358
|
+
writeFileSync(abs, bytes)
|
|
359
|
+
console.log(`[serve] upload → ${abs} (${bytes.length} bytes)`)
|
|
360
|
+
return json(200, { ok: true, path: abs, url: this.outputUrl(abs) })
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// #region drafts write (the web ui's autosave + duplicate ride this) --------
|
|
364
|
+
private async replySaveDraft(modKey: string, rawDraft: string, req: ServeRequest): Promise<ServeReply> {
|
|
365
|
+
const mod = this.moduleByKey(modKey)
|
|
366
|
+
if (mod == null) return json(404, { error: `unknown module '${modKey}'` })
|
|
367
|
+
const draft = this.validDraftName(rawDraft)
|
|
368
|
+
if (draft == null)
|
|
369
|
+
return json(400, { error: `invalid draft name '${rawDraft}' — letters/digits then letters, digits, ". -_"` })
|
|
370
|
+
let parsed: unknown
|
|
371
|
+
try {
|
|
372
|
+
parsed = JSON.parse(req.body ?? '')
|
|
373
|
+
} catch (e) {
|
|
374
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })
|
|
375
|
+
}
|
|
376
|
+
if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
377
|
+
return json(400, { error: 'body must be a json object: { "<var>": value, … }' })
|
|
378
|
+
const values = parsed as Record<string, unknown>
|
|
379
|
+
const known = new Set(mod.dw.entries().map(([k]) => k))
|
|
380
|
+
const unknown = Object.keys(values).filter((k) => !known.has(k))
|
|
381
|
+
if (unknown.length > 0)
|
|
382
|
+
return json(400, { error: `unknown var(s) ${unknown.join(', ')} — vars: ${[...known].join(', ')}` })
|
|
383
|
+
// values are written VERBATIM (toJSON shapes, loadJSON re-validates on read) —
|
|
384
|
+
// under the module mutex, so a save cannot interleave a generate's draft read
|
|
385
|
+
const path = bang(this.draftPath(mod, draft), 'draft name validated just above')
|
|
386
|
+
await this.exclusive(mod.key, () => {
|
|
387
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
388
|
+
writeFileSync(path, JSON.stringify(values, null, 2))
|
|
389
|
+
return Promise.resolve()
|
|
390
|
+
})
|
|
391
|
+
return json(200, { ok: true, module: mod.key, draft, drafts: this.draftsFor(mod) })
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** delete the draft FILE. `default` is deletable like any other: the implicit `default`
|
|
395
|
+
* draft (spec values, no file) survives it, which is exactly the reset. Missing file is
|
|
396
|
+
* still a 200 — the caller asked for it to be gone, and it is */
|
|
397
|
+
private async replyDeleteDraft(modKey: string, rawDraft: string): Promise<ServeReply> {
|
|
398
|
+
const mod = this.moduleByKey(modKey)
|
|
399
|
+
if (mod == null) return json(404, { error: `unknown module '${modKey}'` })
|
|
400
|
+
const path = this.draftPath(mod, rawDraft)
|
|
401
|
+
if (path == null) return json(400, { error: `invalid draft name '${rawDraft}'` })
|
|
402
|
+
await this.exclusive(mod.key, () => {
|
|
403
|
+
if (existsSync(path)) rmSync(path)
|
|
404
|
+
return Promise.resolve()
|
|
405
|
+
})
|
|
406
|
+
console.log(`[serve] draft deleted: ${mod.key}/${rawDraft.trim()}`)
|
|
407
|
+
return json(200, { ok: true, module: mod.key, draft: rawDraft.trim(), drafts: this.draftsFor(mod) })
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// #region prompt enhancers (the web ui's master prompts, as .md files) ------
|
|
411
|
+
/** the folder is seeded on the first read, so `refine-krea2-prompt.md` exists to be edited */
|
|
412
|
+
private replyPromptEnhancers(): ServeReply {
|
|
413
|
+
try {
|
|
414
|
+
return json(200, { enhancers: listPromptEnhancers() })
|
|
415
|
+
} catch (e) {
|
|
416
|
+
return json(500, { error: `prompt-enhancers folder unreadable: ${extractErrorMessage(e)}` })
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
private replySavePromptEnhancer(rawName: string, req: ServeRequest): ServeReply {
|
|
421
|
+
const name = validStoreName(rawName)
|
|
422
|
+
if (name == null)
|
|
423
|
+
return json(400, { error: `invalid enhancer name '${rawName}' — letters/digits then letters, digits, ". -_"` })
|
|
424
|
+
let parsed: unknown
|
|
425
|
+
try {
|
|
426
|
+
parsed = JSON.parse(req.body ?? '')
|
|
427
|
+
} catch (e) {
|
|
428
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })
|
|
429
|
+
}
|
|
430
|
+
if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
431
|
+
return json(400, { error: 'body must be { "text": "<master prompt>" }' })
|
|
432
|
+
const text = (parsed as Record<string, unknown>).text
|
|
433
|
+
if (typeof text !== 'string') return json(400, { error: 'body must be { "text": "<master prompt>" }' })
|
|
434
|
+
try {
|
|
435
|
+
writePromptEnhancer(name, text)
|
|
436
|
+
} catch (e) {
|
|
437
|
+
return json(500, { error: `could not write enhancer '${name}': ${extractErrorMessage(e)}` })
|
|
438
|
+
}
|
|
439
|
+
return json(200, { ok: true, name, enhancers: listPromptEnhancers() })
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
private replyDeletePromptEnhancer(rawName: string): ServeReply {
|
|
443
|
+
const name = validStoreName(rawName)
|
|
444
|
+
if (name == null) return json(400, { error: `invalid enhancer name '${rawName}'` })
|
|
445
|
+
try {
|
|
446
|
+
deletePromptEnhancer(name)
|
|
447
|
+
} catch (e) {
|
|
448
|
+
return json(500, { error: `could not delete enhancer '${name}': ${extractErrorMessage(e)}` })
|
|
449
|
+
}
|
|
450
|
+
console.log(`[serve] prompt enhancer deleted: ${name}`)
|
|
451
|
+
return json(200, { ok: true, name, enhancers: listPromptEnhancers() })
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// #region live run state (web ui polling: progress + latent preview) --------
|
|
455
|
+
private liveRuns = new Map<string, ServeExecution>()
|
|
456
|
+
/** seq counts frames so the poller refetches only on a NEW one, not every tick */
|
|
457
|
+
private latentPreviews = new Map<string, { bytes: Uint8Array; mime: string; seq: number }>()
|
|
458
|
+
private latentSeq = 0
|
|
459
|
+
/** promptId → module: `onLatentPreview` is ONE slot per host and two modules can share a
|
|
460
|
+
* host, so frames are routed by the prompt they belong to, never by "the last run started" */
|
|
461
|
+
private promptOwner = new Map<string, string>()
|
|
462
|
+
private latentHosts = new Set<ComfyHost>()
|
|
463
|
+
|
|
464
|
+
private runningModules(): string[] {
|
|
465
|
+
return [...this.liveRuns.entries()]
|
|
466
|
+
.filter(([, e]) => e.status !== 'Success' && e.status !== 'Failure')
|
|
467
|
+
.map(([key]) => key)
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** one dispatcher per host, installed once and left in place (idempotent) */
|
|
471
|
+
private wireLatents(host: ComfyHost): void {
|
|
472
|
+
if (this.latentHosts.has(host)) return
|
|
473
|
+
this.latentHosts.add(host)
|
|
474
|
+
host.onLatentPreview = (p) => {
|
|
475
|
+
const owner = p.promptID != null ? this.promptOwner.get(p.promptID) : undefined
|
|
476
|
+
// an unattributable frame (no promptID yet, e.g. before start() returned) is only
|
|
477
|
+
// safe to show when exactly ONE run is live; otherwise drop it rather than lie
|
|
478
|
+
const running = this.runningModules()
|
|
479
|
+
const key = owner ?? (running.length === 1 ? running[0] : undefined)
|
|
480
|
+
if (key == null) return
|
|
481
|
+
this.latentPreviews.set(key, { bytes: p.bytes, mime: p.mime, seq: ++this.latentSeq })
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
private replyRunStatus(modKey: string): ServeReply {
|
|
486
|
+
const mod = this.moduleByKey(modKey)
|
|
487
|
+
if (mod == null) return json(404, { error: `unknown module '${modKey}'` })
|
|
488
|
+
const exec = this.liveRuns.get(mod.key)
|
|
489
|
+
const running = exec != null && exec.status !== 'Success' && exec.status !== 'Failure'
|
|
490
|
+
return json(200, {
|
|
491
|
+
running,
|
|
492
|
+
status: exec?.status ?? 'idle',
|
|
493
|
+
percent: running ? (exec.progressGlobal?.percent ?? null) : null,
|
|
494
|
+
hasPreview: this.latentPreviews.has(mod.key),
|
|
495
|
+
previewSeq: this.latentPreviews.get(mod.key)?.seq ?? null,
|
|
496
|
+
})
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
private replyRunPreview(modKey: string): ServeReply {
|
|
500
|
+
const mod = this.moduleByKey(modKey)
|
|
501
|
+
if (mod == null) return json(404, { error: `unknown module '${modKey}'` })
|
|
502
|
+
const preview = this.latentPreviews.get(mod.key)
|
|
503
|
+
if (preview == null) return json(404, { error: 'no latent preview yet' })
|
|
504
|
+
return {
|
|
505
|
+
status: 200,
|
|
506
|
+
contentType: preview.mime !== '' ? preview.mime : sniffImageContentType(preview.bytes),
|
|
507
|
+
body: preview.bytes,
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// #region lora hover data ---------------------------------------------------
|
|
512
|
+
private hostById(hostId: string): ComfyHost | null {
|
|
513
|
+
return this.modules.map((m) => m.dw.host).find((h) => h.data.id === hostId) ?? null
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
private hostIds(): string {
|
|
517
|
+
return [...new Set(this.modules.map((m) => m.dw.host.data.id))].join(', ')
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/** mirror-backed text for the hover pane, no network */
|
|
521
|
+
private replyLoraInfo(hostId: string, lora: string): ServeReply {
|
|
522
|
+
if (this.hostById(hostId) == null)
|
|
523
|
+
return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` })
|
|
524
|
+
refreshLoraInfoCacheIfChanged()
|
|
525
|
+
return json(200, {
|
|
526
|
+
name: lora,
|
|
527
|
+
displayName: getLoraDisplayName(lora, hostId),
|
|
528
|
+
triggerWords: getLoraTriggerWords(lora, hostId),
|
|
529
|
+
})
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/** preview url resolution misses per host, so an absent lora-manager costs ONE sweep, not one
|
|
533
|
+
* per hover. An UNREACHABLE host evicts itself: the host coming back must not stay 404 forever */
|
|
534
|
+
private previewSweeps = new Map<string, Promise<{ status: string; map: Map<string, string> | null }>>()
|
|
535
|
+
|
|
536
|
+
private async replyLoraPreview(hostId: string, lora: string): Promise<ServeReply> {
|
|
537
|
+
const host = this.hostById(hostId)
|
|
538
|
+
if (host == null) return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` })
|
|
539
|
+
refreshLoraInfoCacheIfChanged()
|
|
540
|
+
let url = getLoraPreviewUrl(lora, hostId)
|
|
541
|
+
if (url == null) {
|
|
542
|
+
// the TUI's fallback: unsynced mirror (or a lora it never saw) → ask the live host once
|
|
543
|
+
let sweep = this.previewSweeps.get(hostId)
|
|
544
|
+
if (sweep == null) {
|
|
545
|
+
sweep = fetchLoraList(host).then((r) => {
|
|
546
|
+
if (r.status === 'unreachable') {
|
|
547
|
+
this.previewSweeps.delete(hostId)
|
|
548
|
+
return { status: r.status, map: null }
|
|
549
|
+
}
|
|
550
|
+
return { status: r.status, map: r.status === 'absent' ? null : loraPreviewMapFrom(r.items) }
|
|
551
|
+
})
|
|
552
|
+
this.previewSweeps.set(hostId, sweep)
|
|
553
|
+
}
|
|
554
|
+
const swept = await sweep
|
|
555
|
+
url = swept.map?.get(loraKey(lora)) ?? null
|
|
556
|
+
// each miss has its OWN cause (the LorasSt rule): the wrong advice sends the user hunting
|
|
557
|
+
if (url == null && swept.status === 'unreachable')
|
|
558
|
+
return json(404, { error: `host '${hostId}' is unreachable — no preview to fetch` })
|
|
559
|
+
if (url == null && swept.status === 'absent')
|
|
560
|
+
return json(404, { error: `lora-manager extension not detected on '${hostId}'` })
|
|
561
|
+
}
|
|
562
|
+
if (url == null)
|
|
563
|
+
return json(404, { error: `no preview known for '${lora}' (run: comfy-ts loras --id ${hostId})` })
|
|
564
|
+
const bytes = await fetchLoraPreviewBytes(host, url)
|
|
565
|
+
// one 404 for two causes on purpose: unreachable host and no-image both mean "nothing to show"
|
|
566
|
+
if (bytes == null)
|
|
567
|
+
return json(404, { error: `no image preview for '${lora}' (host '${hostId}' unreachable, or not an image)` })
|
|
568
|
+
return { status: 200, contentType: sniffImageContentType(bytes), body: bytes }
|
|
569
|
+
}
|
|
570
|
+
|
|
222
571
|
private outputUrl(absPath: string): string | null {
|
|
223
572
|
if (!absPath.startsWith(this.outputRoot + '/')) return null
|
|
224
573
|
const rel = absPath.slice(this.outputRoot.length + 1)
|
|
@@ -246,8 +595,14 @@ export class ServeApp {
|
|
|
246
595
|
if ('error' in started) return json(started.status, { error: started.error })
|
|
247
596
|
|
|
248
597
|
const execution = started.execution
|
|
598
|
+
this.liveRuns.set(mod.key, execution)
|
|
599
|
+
this.promptOwner.set(execution.data.id, mod.key)
|
|
249
600
|
console.log(`[serve] → ${mod.key}/${draft} (prompt ${execution.data.id})`)
|
|
250
|
-
|
|
601
|
+
try {
|
|
602
|
+
await execution.done
|
|
603
|
+
} finally {
|
|
604
|
+
this.promptOwner.delete(execution.data.id)
|
|
605
|
+
}
|
|
251
606
|
const durationMs = Date.now() - t0
|
|
252
607
|
|
|
253
608
|
if (execution.status === 'Failure') {
|
|
@@ -297,7 +652,8 @@ export class ServeApp {
|
|
|
297
652
|
): Promise<{ execution: ServeExecution } | { error: string; status: number }> {
|
|
298
653
|
// 1. reset, then load the draft FRESH from disk (TUI edits between requests apply)
|
|
299
654
|
for (const [, varDef] of mod.dw.entries()) varDef.reset()
|
|
300
|
-
const draftPath =
|
|
655
|
+
const draftPath = this.draftPath(mod, draft)
|
|
656
|
+
if (draftPath == null) return { status: 404, error: `no draft '${draft}'` }
|
|
301
657
|
if (existsSync(draftPath)) {
|
|
302
658
|
try {
|
|
303
659
|
const values = JSON.parse(readFileSync(draftPath, 'utf8')) as Record<string, unknown>
|
|
@@ -307,6 +663,12 @@ export class ServeApp {
|
|
|
307
663
|
}
|
|
308
664
|
}
|
|
309
665
|
|
|
666
|
+
// the DRAFT's seed values, before payload overrides: the +/- continuation
|
|
667
|
+
// compares against what the draft file says, not what a payload injected
|
|
668
|
+
const draftSeedValues = new Map<string, number>()
|
|
669
|
+
for (const [k, varDef] of mod.dw.entries())
|
|
670
|
+
if (varDef.kind === 'seed') draftSeedValues.set(k, (varDef as SeedVar).value)
|
|
671
|
+
|
|
310
672
|
// 2. payload overrides (image urls download first, so the var gets a local path)
|
|
311
673
|
const varMap = new Map(mod.dw.entries())
|
|
312
674
|
for (const [k, rawValue] of Object.entries(payload)) {
|
|
@@ -341,18 +703,25 @@ export class ServeApp {
|
|
|
341
703
|
if (varDef.kind !== 'seed') continue
|
|
342
704
|
const seedVar = varDef as SeedVar
|
|
343
705
|
const stateKey = `${mod.key}/${draft}/${k}`
|
|
706
|
+
const draftValue = draftSeedValues.get(k) ?? seedVar.value
|
|
344
707
|
if (!(k in payload)) {
|
|
345
708
|
if (seedVar.mode === '?') seedVar.randomize()
|
|
346
709
|
else if (seedVar.mode === '+' || seedVar.mode === '-') {
|
|
347
|
-
const
|
|
348
|
-
|
|
710
|
+
const prev = this.seedState.get(stateKey)
|
|
711
|
+
// continue only while the draft still holds the value the chain grew from
|
|
712
|
+
if (prev != null && prev.draftBase === draftValue)
|
|
713
|
+
seedVar.set(prev.last + (seedVar.mode === '+' ? 1 : -1))
|
|
349
714
|
}
|
|
350
715
|
}
|
|
351
|
-
this.seedState.set(stateKey, seedVar.value)
|
|
716
|
+
this.seedState.set(stateKey, { last: seedVar.value, draftBase: draftValue })
|
|
352
717
|
seeds[k] = seedVar.value
|
|
353
718
|
}
|
|
354
719
|
|
|
355
|
-
// 5. send (build + POST /prompt); the wait for outputs happens OUTSIDE the mutex
|
|
720
|
+
// 5. send (build + POST /prompt); the wait for outputs happens OUTSIDE the mutex.
|
|
721
|
+
// latent frames feed the web ui's /run/<module>/preview poll (ExecSt's pattern);
|
|
722
|
+
// the previous run's preview must not linger over the new one
|
|
723
|
+
this.latentPreviews.delete(mod.key)
|
|
724
|
+
this.wireLatents(mod.dw.host)
|
|
356
725
|
try {
|
|
357
726
|
return { execution: await this.starter(mod) }
|
|
358
727
|
} 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
|
}
|