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.
Files changed (67) hide show
  1. package/README.md +15 -2
  2. package/dist/{DefinedWorkflow-CnzmQrBh.js → DefinedWorkflow-BJgt5t0x.js} +14 -3
  3. package/dist/DefinedWorkflow-BJgt5t0x.js.map +1 -0
  4. package/dist/{DraftsSt-C1MbWnEp.js → DraftsSt-dizp3VcC.js} +2 -2
  5. package/dist/{DraftsSt-C1MbWnEp.js.map → DraftsSt-dizp3VcC.js.map} +1 -1
  6. package/dist/cli.js +5 -5
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +7 -2
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +24 -18
  11. package/dist/index.d.ts +24 -18
  12. package/dist/index.js +7 -2
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-serve-D47Zas-a.js → run-serve-D1Tsuru9.js} +494 -20
  15. package/dist/run-serve-D1Tsuru9.js.map +1 -0
  16. package/dist/{run-tui-t2TRBN0H.js → run-tui-JxlEbb_f.js} +511 -331
  17. package/dist/run-tui-JxlEbb_f.js.map +1 -0
  18. package/dist/serve-web.js +273 -0
  19. package/dist/{state-DY3Mp9Cl.js → state-CaHeDL-0.js} +7 -13
  20. package/dist/state-CaHeDL-0.js.map +1 -0
  21. package/dist/web.d.ts +24 -18
  22. package/dist/web.js +7 -2
  23. package/dist/web.js.map +1 -1
  24. package/examples/web/tsconfig.json +4 -1
  25. package/package.json +7 -5
  26. package/src/cli/comfy-ts-cli.ts +1 -1
  27. package/src/cli/serve/ServeApp.ts +383 -14
  28. package/src/cli/serve/describeVar.ts +6 -1
  29. package/src/cli/serve/promptEnhancers.ts +69 -0
  30. package/src/cli/serve/run-serve.ts +41 -7
  31. package/src/cli/serve/safeName.ts +12 -0
  32. package/src/cli/serve/web/api.ts +128 -0
  33. package/src/cli/serve/web/clipboard.ts +25 -0
  34. package/src/cli/serve/web/components/App.tsx +53 -0
  35. package/src/cli/serve/web/components/Gallery.tsx +186 -0
  36. package/src/cli/serve/web/components/PromptEnhancer.tsx +254 -0
  37. package/src/cli/serve/web/components/Sidebar.tsx +42 -0
  38. package/src/cli/serve/web/components/VarsForm.tsx +184 -0
  39. package/src/cli/serve/web/components/controls/BasicControls.tsx +95 -0
  40. package/src/cli/serve/web/components/controls/ImageControl.tsx +71 -0
  41. package/src/cli/serve/web/components/controls/LorasControl.tsx +340 -0
  42. package/src/cli/serve/web/components/controls/SeedControl.tsx +43 -0
  43. package/src/cli/serve/web/components/controls/SizeControl.tsx +49 -0
  44. package/src/cli/serve/web/llm.ts +254 -0
  45. package/src/cli/serve/web/main.tsx +18 -0
  46. package/src/cli/serve/web/state/EnhancerSt.ts +481 -0
  47. package/src/cli/serve/web/state/FormSt.ts +180 -0
  48. package/src/cli/serve/web/state/RunSt.ts +136 -0
  49. package/src/cli/serve/web/state/WebSt.ts +235 -0
  50. package/src/cli/serve/web/state/payload.ts +110 -0
  51. package/src/cli/serve/web/styles.ts +261 -0
  52. package/src/cli/serve/web/tsconfig.json +15 -0
  53. package/src/cli/serve/webBundle.ts +66 -0
  54. package/src/cli/tui/imageEscapes.ts +105 -0
  55. package/src/cli/tui/imagePicker/ImagePickerSt.ts +21 -8
  56. package/src/cli/tui/protocolImage.ts +39 -0
  57. package/src/cli/tui/protocolImagePainter.ts +56 -23
  58. package/src/cli/tui/run-tui.tsx +3 -2
  59. package/src/cli/tui/state/LorasSt.ts +22 -9
  60. package/src/cli/tui/state/PreviewSt.ts +31 -13
  61. package/src/cli/tui/state/SettingsSt.ts +1 -1
  62. package/src/state.ts +6 -0
  63. package/src/vars/ComfyVars.ts +4 -1
  64. package/dist/DefinedWorkflow-CnzmQrBh.js.map +0 -1
  65. package/dist/run-serve-D47Zas-a.js.map +0 -1
  66. package/dist/run-tui-t2TRBN0H.js.map +0 -1
  67. package/dist/state-DY3Mp9Cl.js.map +0 -1
@@ -1,10 +1,11 @@
1
- import { C as extractErrorMessage } from "./DefinedWorkflow-CnzmQrBh.js";
2
- import { c as findDefinedWorkflow, i as listDraftsForFile, n as draftKeyForFile, r as draftsDirForFile, u as scanCflowFiles } from "./DraftsSt-C1MbWnEp.js";
3
- import { pathToFileURL } from "node:url";
4
- import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
1
+ import { C as loraPreviewMapFrom, S as loraKey, T as bang, _ as fetchLoraList, d as getLoraPreviewUrl, f as getLoraTriggerWords, h as refreshLoraInfoCacheIfChanged, u as getLoraDisplayName, v as fetchLoraPreviewBytes, w as extractErrorMessage } from "./DefinedWorkflow-BJgt5t0x.js";
2
+ import { c as findDefinedWorkflow, i as listDraftsForFile, n as draftKeyForFile, r as draftsDirForFile, u as scanCflowFiles } from "./DraftsSt-dizp3VcC.js";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
5
5
  import { basename, dirname, extname, join, resolve } from "pathe";
6
6
  import { nanoid } from "nanoid";
7
7
  import { createServer } from "node:http";
8
+ import { networkInterfaces } from "node:os";
8
9
  //#region src/cli/serve/describeVar.ts
9
10
  function rangeText(opts) {
10
11
  if (opts.min == null && opts.max == null) return "";
@@ -48,7 +49,7 @@ function describeVar(varDef) {
48
49
  return {
49
50
  ...base,
50
51
  default: {
51
- mode: v.mode,
52
+ mode: v.defaultMode,
52
53
  value: v.defaultValue
53
54
  },
54
55
  payload: "number (fixed) or {\"mode\":\"=|+|-|?\",\"value\":number}"
@@ -206,6 +207,71 @@ function applyVarPayload(varDef, raw) {
206
207
  }
207
208
  }
208
209
  //#endregion
210
+ //#region src/cli/serve/safeName.ts
211
+ /** the accepted name, or null. Rejects traversal, absolute paths, leading dots and empties */
212
+ function validStoreName(raw) {
213
+ const name = raw.trim();
214
+ if (name.length > 100) return null;
215
+ return /^[\w][\w .-]*$/.test(name) ? name : null;
216
+ }
217
+ //#endregion
218
+ //#region src/cli/serve/promptEnhancers.ts
219
+ const EXT = ".md";
220
+ function promptEnhancersDir() {
221
+ return comfyts.resolveFromPromptEnhancers("");
222
+ }
223
+ function promptEnhancerPath(name) {
224
+ const safe = validStoreName(name);
225
+ return safe == null ? null : join(promptEnhancersDir(), `${safe}${EXT}`);
226
+ }
227
+ /** the shipped starting point. It is a FILE from the first read on, so it can be edited
228
+ * on disk like everything else — the browser ships no copy of this text */
229
+ const SEED = {
230
+ name: "refine-krea2-prompt",
231
+ text: `You rewrite image prompts for krea2 turbo, a distilled 8 step text to image model whose text encoder reads flowing natural language, not tag soup, and which is steered by adjectives rather than by negatives.
232
+
233
+ Rewrite the user's prompt into ONE dense paragraph someone could picture with their eyes closed:
234
+ - keep every noun and every named subject the user wrote, they are the point
235
+ - add what is missing to make it fun to look at: lighting, palette, material, texture, camera angle, composition, mood
236
+ - prefer concrete visual nouns over praise, never write "masterpiece", "8k", "highly detailed", "award winning"
237
+ - stay under about 80 words, no lists, no headings, no quotes around the result
238
+ - keep any "// " comment line and any "- " negative line from the input verbatim, each on its own line
239
+
240
+ Answer with the rewritten prompt and nothing else: no preamble, no explanation.
241
+ `
242
+ };
243
+ /** seeds ONCE, on an absent folder. A folder he emptied on purpose stays empty */
244
+ function listPromptEnhancers() {
245
+ const dir = promptEnhancersDir();
246
+ if (!existsSync(dir)) writePromptEnhancer(SEED.name, SEED.text);
247
+ if (!existsSync(dir)) return [];
248
+ const out = [];
249
+ for (const file of readdirSync(dir).sort()) {
250
+ if (!file.endsWith(EXT)) continue;
251
+ const name = file.slice(0, -3);
252
+ if (validStoreName(name) == null) continue;
253
+ out.push({
254
+ name,
255
+ text: readFileSync(join(dir, file), "utf8")
256
+ });
257
+ }
258
+ return out;
259
+ }
260
+ function writePromptEnhancer(name, text) {
261
+ const path = promptEnhancerPath(name);
262
+ if (path == null) return null;
263
+ mkdirSync(promptEnhancersDir(), { recursive: true });
264
+ writeFileSync(path, text);
265
+ return path;
266
+ }
267
+ /** a missing file is still a success: the caller asked for it to be gone, and it is */
268
+ function deletePromptEnhancer(name) {
269
+ const path = promptEnhancerPath(name);
270
+ if (path == null) return false;
271
+ if (existsSync(path)) rmSync(path);
272
+ return true;
273
+ }
274
+ //#endregion
209
275
  //#region src/cli/serve/ServeApp.ts
210
276
  /** connect + fresh graph from current var values + send; done is awaited OUTSIDE the module mutex.
211
277
  * serve OPTS INTO local saving (library default is memory-only, architecture.md
@@ -225,6 +291,14 @@ const CONTENT_TYPES = {
225
291
  ".json": "application/json",
226
292
  ".txt": "text/plain"
227
293
  };
294
+ /** magic-byte sniff for the preview proxy — fetchLoraPreviewBytes already guarantees an image */
295
+ function sniffImageContentType(bytes) {
296
+ if (bytes[0] === 137 && bytes[1] === 80) return "image/png";
297
+ if (bytes[0] === 255 && bytes[1] === 216) return "image/jpeg";
298
+ if (bytes[0] === 71 && bytes[1] === 73) return "image/gif";
299
+ if (bytes[0] === 82 && bytes[1] === 73) return "image/webp";
300
+ return "application/octet-stream";
301
+ }
228
302
  function json(status, payload) {
229
303
  return {
230
304
  status,
@@ -233,18 +307,49 @@ function json(status, payload) {
233
307
  };
234
308
  }
235
309
  const USAGE = [
310
+ "GET / in a browser — web control panel (every var as a form control)",
236
311
  "GET /drafts — every served workflow, its drafts and var descriptors",
237
312
  "GET /drafts/<module>/<draft> — one draft with its stored values",
238
313
  "POST /generate/<module>/<draft> with { ...vars } — run, blocking",
239
314
  "POST /generate/<draft> — unqualified, when unambiguous",
315
+ "PUT /drafts/<module>/<draft> with { ...vars } — save (or duplicate to a new name) a draft",
316
+ "DELETE /drafts/<module>/<draft> — delete that draft file",
317
+ "GET /run/<module> — live run status · /run/<module>/preview — latent preview bytes",
318
+ "POST /upload with {\"name\",\"dataBase64\"} — store a browser file for an image var",
319
+ "GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)",
320
+ "GET /lora-preview/<hostId>/<lora> — preview image bytes",
321
+ "GET /prompt-enhancers — the web ui master prompts (.comfy-ts/prompt-enhancers/*.md)",
322
+ "PUT /prompt-enhancers/<name> with {\"text\"} — write one · DELETE /prompt-enhancers/<name> — remove it",
240
323
  "GET /outputs/<path> — generated files"
241
324
  ];
325
+ /** the html shell; the app itself is ONE bundle at /web/app.js */
326
+ const WEB_SHELL = `<!doctype html>
327
+ <html lang="en">
328
+ <head>
329
+ <meta charset="utf-8">
330
+ <meta name="viewport" content="width=device-width, initial-scale=1">
331
+ <title>comfy-ts serve</title>
332
+ <style>html{background:#101217;color:#e8eaf0}</style>
333
+ </head>
334
+ <body>
335
+ <div id="root"></div>
336
+ <script type="module" src="/web/app.js"><\/script>
337
+ </body>
338
+ </html>
339
+ `;
242
340
  var ServeApp = class {
243
341
  constructor(modules, opts = {}) {
244
342
  this.modules = modules;
245
343
  this.opts = opts;
246
344
  this.seedState = /* @__PURE__ */ new Map();
247
345
  this.chains = /* @__PURE__ */ new Map();
346
+ this.webJsCache = null;
347
+ this.liveRuns = /* @__PURE__ */ new Map();
348
+ this.latentPreviews = /* @__PURE__ */ new Map();
349
+ this.latentSeq = 0;
350
+ this.promptOwner = /* @__PURE__ */ new Map();
351
+ this.latentHosts = /* @__PURE__ */ new Set();
352
+ this.previewSweeps = /* @__PURE__ */ new Map();
248
353
  this.starter = opts.starter ?? realStarter;
249
354
  }
250
355
  get outputRoot() {
@@ -260,8 +365,22 @@ var ServeApp = class {
260
365
  return json(400, { error: `bad url encoding: ${path}` });
261
366
  }
262
367
  if (req.method === "GET") {
368
+ if (segs.length === 0 && this.opts.webJs != null && req.accept?.includes("text/html") === true) {
369
+ this.webJsCache ??= this.opts.webJs();
370
+ if (await this.webJsCache != null) return {
371
+ status: 200,
372
+ contentType: "text/html; charset=utf-8",
373
+ body: WEB_SHELL
374
+ };
375
+ }
263
376
  if (segs.length === 0 || segs[0] === "drafts" && segs.length === 1) return this.replyIndex();
377
+ if (segs[0] === "web" && segs[1] === "app.js" && segs.length === 2) return await this.replyWebJs();
264
378
  if (segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyDraft(segs[1], segs[2]);
379
+ if (segs[0] === "run" && segs.length === 2 && segs[1] != null) return this.replyRunStatus(segs[1]);
380
+ if (segs[0] === "run" && segs.length === 3 && segs[1] != null && segs[2] === "preview") return this.replyRunPreview(segs[1]);
381
+ if (segs[0] === "lora-info" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyLoraInfo(segs[1], segs[2]);
382
+ if (segs[0] === "lora-preview" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyLoraPreview(segs[1], segs[2]);
383
+ if (segs[0] === "prompt-enhancers" && segs.length === 1) return this.replyPromptEnhancers();
265
384
  if (segs[0] === "outputs") return this.replyOutput(segs.slice(1));
266
385
  return json(404, {
267
386
  error: `no route: GET ${path}`,
@@ -273,6 +392,11 @@ var ServeApp = class {
273
392
  if ("error" in target) return json(target.status, { error: target.error });
274
393
  return await this.generate(target.mod, target.draft, req);
275
394
  }
395
+ if (req.method === "POST" && segs[0] === "upload" && segs.length === 1) return this.replyUpload(req);
396
+ if (req.method === "PUT" && segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replySaveDraft(segs[1], segs[2], req);
397
+ if (req.method === "DELETE" && segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyDeleteDraft(segs[1], segs[2]);
398
+ if (req.method === "PUT" && segs[0] === "prompt-enhancers" && segs.length === 2 && segs[1] != null) return this.replySavePromptEnhancer(segs[1], req);
399
+ if (req.method === "DELETE" && segs[0] === "prompt-enhancers" && segs.length === 2 && segs[1] != null) return this.replyDeletePromptEnhancer(segs[1]);
276
400
  return json(404, {
277
401
  error: `no route: ${req.method} ${path}`,
278
402
  usage: USAGE
@@ -289,8 +413,20 @@ var ServeApp = class {
289
413
  draftsFor(mod) {
290
414
  return ["default", ...listDraftsForFile(mod.file).filter((n) => n !== "default")];
291
415
  }
416
+ /** THE draft-name gate, shared by every route that turns a url segment into a path
417
+ * (safeName.ts owns the rule — the prompt-enhancer routes call the same function) */
418
+ validDraftName(raw) {
419
+ return validStoreName(raw);
420
+ }
421
+ /** absolute path of a draft file, or null when the name is not one we accept */
422
+ draftPath(mod, draft) {
423
+ const name = this.validDraftName(draft);
424
+ return name == null ? null : join(draftsDirForFile(mod.file), `${name}.json`);
425
+ }
292
426
  draftExists(mod, draft) {
293
- return draft === "default" || existsSync(join(draftsDirForFile(mod.file), `${draft}.json`));
427
+ const path = this.draftPath(mod, draft);
428
+ if (path == null) return false;
429
+ return draft === "default" || existsSync(path);
294
430
  }
295
431
  resolveDraft(segs) {
296
432
  if (segs.length === 2 && segs[0] != null && segs[1] != null) {
@@ -341,8 +477,21 @@ var ServeApp = class {
341
477
  };
342
478
  }
343
479
  describeModule(mod) {
480
+ refreshLoraInfoCacheIfChanged();
481
+ const hostId = mod.dw.host.data.id;
344
482
  const vars = {};
345
- for (const [name, varDef] of mod.dw.entries()) vars[name] = describeVar(varDef);
483
+ for (const [name, varDef] of mod.dw.entries()) {
484
+ const desc = describeVar(varDef);
485
+ if (desc.kind === "loras" && desc.options != null) {
486
+ const labels = {};
487
+ for (const option of desc.options) {
488
+ const label = getLoraDisplayName(option, hostId);
489
+ if (label !== option) labels[option] = label;
490
+ }
491
+ if (Object.keys(labels).length > 0) desc.optionLabels = labels;
492
+ }
493
+ vars[name] = desc;
494
+ }
346
495
  return {
347
496
  module: mod.key,
348
497
  file: mod.file,
@@ -372,8 +521,8 @@ var ServeApp = class {
372
521
  }
373
522
  /** stored values (toJSON shapes); 'default' without a file falls back to descriptor defaults */
374
523
  draftValues(mod, draft) {
375
- const path = join(draftsDirForFile(mod.file), `${draft}.json`);
376
- if (existsSync(path)) return JSON.parse(readFileSync(path, "utf8"));
524
+ const path = this.draftPath(mod, draft);
525
+ if (path != null && existsSync(path)) return JSON.parse(readFileSync(path, "utf8"));
377
526
  const out = {};
378
527
  for (const [name, varDef] of mod.dw.entries()) out[name] = describeVar(varDef).default;
379
528
  return out;
@@ -388,6 +537,231 @@ var ServeApp = class {
388
537
  body: new Uint8Array(readFileSync(abs))
389
538
  };
390
539
  }
540
+ async replyWebJs() {
541
+ if (this.opts.webJs == null) return json(404, { error: "web ui not enabled on this server" });
542
+ this.webJsCache ??= this.opts.webJs();
543
+ const js = await this.webJsCache;
544
+ if (js == null) return json(404, { error: "web ui bundle unavailable — see the server log" });
545
+ return {
546
+ status: 200,
547
+ contentType: "text/javascript; charset=utf-8",
548
+ body: js
549
+ };
550
+ }
551
+ /** browser file → local file an image var can point at (downloadInput family) */
552
+ replyUpload(req) {
553
+ let parsed;
554
+ try {
555
+ parsed = JSON.parse(req.body ?? "");
556
+ } catch (e) {
557
+ return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
558
+ }
559
+ const o = parsed ?? {};
560
+ if (typeof o.name !== "string" || o.name === "" || typeof o.dataBase64 !== "string" || o.dataBase64 === "") return json(400, { error: "upload expects {\"name\":\"<filename>\",\"dataBase64\":\"<base64 bytes>\"}" });
561
+ const bytes = Buffer.from(o.dataBase64, "base64");
562
+ if (bytes.length === 0) return json(400, { error: "dataBase64 decoded to zero bytes" });
563
+ const safe = basename(o.name).replace(/[^\w.-]+/g, "_") || "upload";
564
+ const abs = join(this.outputRoot, "serve-inputs", `${nanoid(6)}-${safe}`);
565
+ mkdirSync(dirname(abs), { recursive: true });
566
+ writeFileSync(abs, bytes);
567
+ console.log(`[serve] upload → ${abs} (${bytes.length} bytes)`);
568
+ return json(200, {
569
+ ok: true,
570
+ path: abs,
571
+ url: this.outputUrl(abs)
572
+ });
573
+ }
574
+ async replySaveDraft(modKey, rawDraft, req) {
575
+ const mod = this.moduleByKey(modKey);
576
+ if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
577
+ const draft = this.validDraftName(rawDraft);
578
+ if (draft == null) return json(400, { error: `invalid draft name '${rawDraft}' — letters/digits then letters, digits, ". -_"` });
579
+ let parsed;
580
+ try {
581
+ parsed = JSON.parse(req.body ?? "");
582
+ } catch (e) {
583
+ return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
584
+ }
585
+ if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be a json object: { \"<var>\": value, … }" });
586
+ const values = parsed;
587
+ const known = new Set(mod.dw.entries().map(([k]) => k));
588
+ const unknown = Object.keys(values).filter((k) => !known.has(k));
589
+ if (unknown.length > 0) return json(400, { error: `unknown var(s) ${unknown.join(", ")} — vars: ${[...known].join(", ")}` });
590
+ const path = bang(this.draftPath(mod, draft), "draft name validated just above");
591
+ await this.exclusive(mod.key, () => {
592
+ mkdirSync(dirname(path), { recursive: true });
593
+ writeFileSync(path, JSON.stringify(values, null, 2));
594
+ return Promise.resolve();
595
+ });
596
+ return json(200, {
597
+ ok: true,
598
+ module: mod.key,
599
+ draft,
600
+ drafts: this.draftsFor(mod)
601
+ });
602
+ }
603
+ /** delete the draft FILE. `default` is deletable like any other: the implicit `default`
604
+ * draft (spec values, no file) survives it, which is exactly the reset. Missing file is
605
+ * still a 200 — the caller asked for it to be gone, and it is */
606
+ async replyDeleteDraft(modKey, rawDraft) {
607
+ const mod = this.moduleByKey(modKey);
608
+ if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
609
+ const path = this.draftPath(mod, rawDraft);
610
+ if (path == null) return json(400, { error: `invalid draft name '${rawDraft}'` });
611
+ await this.exclusive(mod.key, () => {
612
+ if (existsSync(path)) rmSync(path);
613
+ return Promise.resolve();
614
+ });
615
+ console.log(`[serve] draft deleted: ${mod.key}/${rawDraft.trim()}`);
616
+ return json(200, {
617
+ ok: true,
618
+ module: mod.key,
619
+ draft: rawDraft.trim(),
620
+ drafts: this.draftsFor(mod)
621
+ });
622
+ }
623
+ /** the folder is seeded on the first read, so `refine-krea2-prompt.md` exists to be edited */
624
+ replyPromptEnhancers() {
625
+ try {
626
+ return json(200, { enhancers: listPromptEnhancers() });
627
+ } catch (e) {
628
+ return json(500, { error: `prompt-enhancers folder unreadable: ${extractErrorMessage(e)}` });
629
+ }
630
+ }
631
+ replySavePromptEnhancer(rawName, req) {
632
+ const name = validStoreName(rawName);
633
+ if (name == null) return json(400, { error: `invalid enhancer name '${rawName}' — letters/digits then letters, digits, ". -_"` });
634
+ let parsed;
635
+ try {
636
+ parsed = JSON.parse(req.body ?? "");
637
+ } catch (e) {
638
+ return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
639
+ }
640
+ if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be { \"text\": \"<master prompt>\" }" });
641
+ const text = parsed.text;
642
+ if (typeof text !== "string") return json(400, { error: "body must be { \"text\": \"<master prompt>\" }" });
643
+ try {
644
+ writePromptEnhancer(name, text);
645
+ } catch (e) {
646
+ return json(500, { error: `could not write enhancer '${name}': ${extractErrorMessage(e)}` });
647
+ }
648
+ return json(200, {
649
+ ok: true,
650
+ name,
651
+ enhancers: listPromptEnhancers()
652
+ });
653
+ }
654
+ replyDeletePromptEnhancer(rawName) {
655
+ const name = validStoreName(rawName);
656
+ if (name == null) return json(400, { error: `invalid enhancer name '${rawName}'` });
657
+ try {
658
+ deletePromptEnhancer(name);
659
+ } catch (e) {
660
+ return json(500, { error: `could not delete enhancer '${name}': ${extractErrorMessage(e)}` });
661
+ }
662
+ console.log(`[serve] prompt enhancer deleted: ${name}`);
663
+ return json(200, {
664
+ ok: true,
665
+ name,
666
+ enhancers: listPromptEnhancers()
667
+ });
668
+ }
669
+ runningModules() {
670
+ return [...this.liveRuns.entries()].filter(([, e]) => e.status !== "Success" && e.status !== "Failure").map(([key]) => key);
671
+ }
672
+ /** one dispatcher per host, installed once and left in place (idempotent) */
673
+ wireLatents(host) {
674
+ if (this.latentHosts.has(host)) return;
675
+ this.latentHosts.add(host);
676
+ host.onLatentPreview = (p) => {
677
+ const owner = p.promptID != null ? this.promptOwner.get(p.promptID) : void 0;
678
+ const running = this.runningModules();
679
+ const key = owner ?? (running.length === 1 ? running[0] : void 0);
680
+ if (key == null) return;
681
+ this.latentPreviews.set(key, {
682
+ bytes: p.bytes,
683
+ mime: p.mime,
684
+ seq: ++this.latentSeq
685
+ });
686
+ };
687
+ }
688
+ replyRunStatus(modKey) {
689
+ const mod = this.moduleByKey(modKey);
690
+ if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
691
+ const exec = this.liveRuns.get(mod.key);
692
+ const running = exec != null && exec.status !== "Success" && exec.status !== "Failure";
693
+ return json(200, {
694
+ running,
695
+ status: exec?.status ?? "idle",
696
+ percent: running ? exec.progressGlobal?.percent ?? null : null,
697
+ hasPreview: this.latentPreviews.has(mod.key),
698
+ previewSeq: this.latentPreviews.get(mod.key)?.seq ?? null
699
+ });
700
+ }
701
+ replyRunPreview(modKey) {
702
+ const mod = this.moduleByKey(modKey);
703
+ if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
704
+ const preview = this.latentPreviews.get(mod.key);
705
+ if (preview == null) return json(404, { error: "no latent preview yet" });
706
+ return {
707
+ status: 200,
708
+ contentType: preview.mime !== "" ? preview.mime : sniffImageContentType(preview.bytes),
709
+ body: preview.bytes
710
+ };
711
+ }
712
+ hostById(hostId) {
713
+ return this.modules.map((m) => m.dw.host).find((h) => h.data.id === hostId) ?? null;
714
+ }
715
+ hostIds() {
716
+ return [...new Set(this.modules.map((m) => m.dw.host.data.id))].join(", ");
717
+ }
718
+ /** mirror-backed text for the hover pane, no network */
719
+ replyLoraInfo(hostId, lora) {
720
+ if (this.hostById(hostId) == null) return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` });
721
+ refreshLoraInfoCacheIfChanged();
722
+ return json(200, {
723
+ name: lora,
724
+ displayName: getLoraDisplayName(lora, hostId),
725
+ triggerWords: getLoraTriggerWords(lora, hostId)
726
+ });
727
+ }
728
+ async replyLoraPreview(hostId, lora) {
729
+ const host = this.hostById(hostId);
730
+ if (host == null) return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` });
731
+ refreshLoraInfoCacheIfChanged();
732
+ let url = getLoraPreviewUrl(lora, hostId);
733
+ if (url == null) {
734
+ let sweep = this.previewSweeps.get(hostId);
735
+ if (sweep == null) {
736
+ sweep = fetchLoraList(host).then((r) => {
737
+ if (r.status === "unreachable") {
738
+ this.previewSweeps.delete(hostId);
739
+ return {
740
+ status: r.status,
741
+ map: null
742
+ };
743
+ }
744
+ return {
745
+ status: r.status,
746
+ map: r.status === "absent" ? null : loraPreviewMapFrom(r.items)
747
+ };
748
+ });
749
+ this.previewSweeps.set(hostId, sweep);
750
+ }
751
+ const swept = await sweep;
752
+ url = swept.map?.get(loraKey(lora)) ?? null;
753
+ if (url == null && swept.status === "unreachable") return json(404, { error: `host '${hostId}' is unreachable — no preview to fetch` });
754
+ if (url == null && swept.status === "absent") return json(404, { error: `lora-manager extension not detected on '${hostId}'` });
755
+ }
756
+ if (url == null) return json(404, { error: `no preview known for '${lora}' (run: comfy-ts loras --id ${hostId})` });
757
+ const bytes = await fetchLoraPreviewBytes(host, url);
758
+ if (bytes == null) return json(404, { error: `no image preview for '${lora}' (host '${hostId}' unreachable, or not an image)` });
759
+ return {
760
+ status: 200,
761
+ contentType: sniffImageContentType(bytes),
762
+ body: bytes
763
+ };
764
+ }
391
765
  outputUrl(absPath) {
392
766
  if (!absPath.startsWith(this.outputRoot + "/")) return null;
393
767
  return "/outputs/" + absPath.slice(this.outputRoot.length + 1).split("/").map(encodeURIComponent).join("/");
@@ -409,8 +783,14 @@ var ServeApp = class {
409
783
  const started = await this.exclusive(mod.key, () => this.prepareAndStart(mod, draft, payload, seeds));
410
784
  if ("error" in started) return json(started.status, { error: started.error });
411
785
  const execution = started.execution;
786
+ this.liveRuns.set(mod.key, execution);
787
+ this.promptOwner.set(execution.data.id, mod.key);
412
788
  console.log(`[serve] → ${mod.key}/${draft} (prompt ${execution.data.id})`);
413
- await execution.done;
789
+ try {
790
+ await execution.done;
791
+ } finally {
792
+ this.promptOwner.delete(execution.data.id);
793
+ }
414
794
  const durationMs = Date.now() - t0;
415
795
  if (execution.status === "Failure") {
416
796
  console.error(`[serve] 🔴 ${mod.key}/${draft} failed after ${durationMs}ms`);
@@ -447,7 +827,11 @@ var ServeApp = class {
447
827
  /** everything that touches the module's SHARED vars, under the module mutex */
448
828
  async prepareAndStart(mod, draft, payload, seeds) {
449
829
  for (const [, varDef] of mod.dw.entries()) varDef.reset();
450
- const draftPath = join(draftsDirForFile(mod.file), `${draft}.json`);
830
+ const draftPath = this.draftPath(mod, draft);
831
+ if (draftPath == null) return {
832
+ status: 404,
833
+ error: `no draft '${draft}'`
834
+ };
451
835
  if (existsSync(draftPath)) try {
452
836
  const values = JSON.parse(readFileSync(draftPath, "utf8"));
453
837
  for (const [k, varDef] of mod.dw.entries()) if (k in values) varDef.loadJSON(values[k]);
@@ -457,6 +841,8 @@ var ServeApp = class {
457
841
  error: `draft file unreadable: ${draftPath} — ${extractErrorMessage(e)}`
458
842
  };
459
843
  }
844
+ const draftSeedValues = /* @__PURE__ */ new Map();
845
+ for (const [k, varDef] of mod.dw.entries()) if (varDef.kind === "seed") draftSeedValues.set(k, varDef.value);
460
846
  const varMap = new Map(mod.dw.entries());
461
847
  for (const [k, rawValue] of Object.entries(payload)) {
462
848
  const varDef = varMap.get(k);
@@ -491,16 +877,22 @@ var ServeApp = class {
491
877
  if (varDef.kind !== "seed") continue;
492
878
  const seedVar = varDef;
493
879
  const stateKey = `${mod.key}/${draft}/${k}`;
880
+ const draftValue = draftSeedValues.get(k) ?? seedVar.value;
494
881
  if (!(k in payload)) {
495
882
  if (seedVar.mode === "?") seedVar.randomize();
496
883
  else if (seedVar.mode === "+" || seedVar.mode === "-") {
497
- const last = this.seedState.get(stateKey);
498
- if (last != null) seedVar.set(last + (seedVar.mode === "+" ? 1 : -1));
884
+ const prev = this.seedState.get(stateKey);
885
+ if (prev != null && prev.draftBase === draftValue) seedVar.set(prev.last + (seedVar.mode === "+" ? 1 : -1));
499
886
  }
500
887
  }
501
- this.seedState.set(stateKey, seedVar.value);
888
+ this.seedState.set(stateKey, {
889
+ last: seedVar.value,
890
+ draftBase: draftValue
891
+ });
502
892
  seeds[k] = seedVar.value;
503
893
  }
894
+ this.latentPreviews.delete(mod.key);
895
+ this.wireLatents(mod.dw.host);
504
896
  try {
505
897
  return { execution: await this.starter(mod) };
506
898
  } catch (e) {
@@ -537,6 +929,60 @@ var ServeApp = class {
537
929
  }
538
930
  };
539
931
  //#endregion
932
+ //#region src/cli/serve/webBundle.ts
933
+ const WEB_ENTRY = "src/cli/serve/web/main.tsx";
934
+ /** nearest dir upward holding a package.json — the comfy-ts package root, from dist/ and src/ alike */
935
+ function packageRoot(fromDir) {
936
+ let dir = fromDir;
937
+ while (true) {
938
+ if (existsSync(join(dir, "package.json"))) return dir;
939
+ const parent = dirname(dir);
940
+ if (parent === dir) return null;
941
+ dir = parent;
942
+ }
943
+ }
944
+ /** bundle the web app to one browser file. Bun.build reads no tsconfig, so the
945
+ * house 'src/...' absolute imports resolve through the same plugin shape as
946
+ * tests/web-bundle.test.ts */
947
+ async function buildWebJsText(pkgRoot) {
948
+ const result = await Bun.build({
949
+ entrypoints: [join(pkgRoot, WEB_ENTRY)],
950
+ target: "browser",
951
+ minify: true,
952
+ throw: false,
953
+ define: { "process.env.NODE_ENV": "\"production\"" },
954
+ plugins: [{
955
+ name: "repo-src-paths",
956
+ setup(build) {
957
+ build.onResolve({ filter: /^src\// }, (args) => ({ path: join(pkgRoot, args.path) }));
958
+ }
959
+ }]
960
+ });
961
+ if (!result.success || result.outputs[0] == null) throw new Error(`web ui bundle failed:\n${result.logs.map((l) => String(l)).join("\n")}`);
962
+ return await result.outputs[0].text();
963
+ }
964
+ /** the runtime resolution chain; every miss logs loud and degrades to api-only */
965
+ async function loadOrBuildWebJs() {
966
+ const here = dirname(fileURLToPath(import.meta.url));
967
+ const prebuilt = join(here, "serve-web.js");
968
+ if (existsSync(prebuilt)) return readFileSync(prebuilt, "utf8");
969
+ if (typeof Bun === "undefined") {
970
+ console.error("[serve] 🔴 no serve-web.js next to the cli and not running under bun — api only, no web ui");
971
+ return null;
972
+ }
973
+ const pkgRoot = packageRoot(here);
974
+ if (pkgRoot == null || !existsSync(join(pkgRoot, WEB_ENTRY))) {
975
+ console.error(`[serve] 🔴 web ui source not found (looked for ${WEB_ENTRY} above ${here}) — api only, no web ui`);
976
+ return null;
977
+ }
978
+ try {
979
+ return await buildWebJsText(pkgRoot);
980
+ } catch (e) {
981
+ console.error("[serve] 🔴 web ui bundle failed — api only:", e);
982
+ return null;
983
+ }
984
+ }
985
+ //#endregion
540
986
  //#region src/cli/serve/run-serve.ts
541
987
  const DEFAULT_PORT = 8288;
542
988
  const BODY_CAP = 1e7;
@@ -550,9 +996,9 @@ function parseArgs(args) {
550
996
  const n = Number(args[++i]);
551
997
  if (!Number.isInteger(n) || n <= 0 || n > 65535) return { error: `--port expects 1..65535, got '${args[i]}'` };
552
998
  port = n;
553
- } else if (a === "--bind") {
999
+ } else if (a === "--host" || a === "--bind") {
554
1000
  const b = args[++i];
555
- if (b == null) return { error: "--bind expects an address" };
1001
+ if (b == null) return { error: `${a} expects an address (0.0.0.0 to reach it from another machine)` };
556
1002
  bind = b;
557
1003
  } else if (a != null && a.startsWith("--")) return { error: `unknown flag '${a}'` };
558
1004
  else if (a != null) {
@@ -571,7 +1017,7 @@ function makeRequestListener(app) {
571
1017
  return (req, res) => {
572
1018
  const cors = {
573
1019
  "access-control-allow-origin": "*",
574
- "access-control-allow-methods": "GET, POST, OPTIONS",
1020
+ "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
575
1021
  "access-control-allow-headers": "content-type, accept"
576
1022
  };
577
1023
  const chunks = [];
@@ -654,7 +1100,10 @@ async function runServe(args) {
654
1100
  console.error("[comfy-ts serve] every module failed to load — nothing to serve");
655
1101
  return 1;
656
1102
  }
657
- const app = new ServeApp(modules, { loadErrors });
1103
+ const app = new ServeApp(modules, {
1104
+ loadErrors,
1105
+ webJs: loadOrBuildWebJs
1106
+ });
658
1107
  printStartup(app, parsed.bind, parsed.port);
659
1108
  const server = createServer(makeRequestListener(app));
660
1109
  server.on("error", (e) => {
@@ -667,10 +1116,34 @@ async function runServe(args) {
667
1116
  server.on("close", () => resolveExit(typeof process.exitCode === "number" ? process.exitCode : 0));
668
1117
  });
669
1118
  }
1119
+ /** the addresses this bind actually answers on. `0.0.0.0` means every interface, so printing
1120
+ * only that back is useless: the LAN ip and the tailnet 100.x are the urls a phone can open */
1121
+ function reachableAddresses(bind, nics) {
1122
+ if (bind !== "0.0.0.0" && bind !== "::") return [bind];
1123
+ const found = [];
1124
+ for (const list of Object.values(nics)) for (const nic of list ?? []) {
1125
+ if (nic.internal || nic.family !== "IPv4" && nic.family !== 4) continue;
1126
+ found.push(nic.address);
1127
+ }
1128
+ return ["127.0.0.1", ...found];
1129
+ }
1130
+ /** 100.64.0.0/10 is the CGNAT range tailscale hands out — worth naming, it is the one he wants */
1131
+ function addressNote(addr) {
1132
+ const octets = addr.split(".").map(Number);
1133
+ const second = octets[1] ?? 0;
1134
+ return octets[0] === 100 && second >= 64 && second <= 127 ? " (tailnet)" : "";
1135
+ }
670
1136
  function printStartup(app, bind, port) {
671
1137
  const base = `http://${bind}:${port}`;
672
1138
  console.log(`comfy-ts serve · ${app.modules.length} workflow(s) · ${base}/`);
673
- if (bind !== "127.0.0.1" && bind !== "localhost") console.log(`⚠️ bound to ${bind} — this API has NO AUTH and runs workflows on your ComfyUI host`);
1139
+ if (bind !== "127.0.0.1" && bind !== "localhost") {
1140
+ console.log(`⚠️ bound to ${bind} — this API has NO AUTH and runs workflows on your ComfyUI host`);
1141
+ const urls = reachableAddresses(bind, networkInterfaces());
1142
+ if (urls.length > 1) {
1143
+ console.log("reachable at:");
1144
+ for (const addr of urls) console.log(` http://${addr}:${port}/${addressNote(addr)}`);
1145
+ }
1146
+ }
674
1147
  for (const mod of app.modules) {
675
1148
  console.log(`\n${mod.key} (host: ${mod.dw.host.data.id})`);
676
1149
  for (const draft of app.draftsFor(mod)) console.log(` POST ${base}/generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(draft)}`);
@@ -681,8 +1154,9 @@ function printStartup(app, bind, port) {
681
1154
  const firstMod = app.modules[0];
682
1155
  if (firstMod != null) console.log(`\ntry: curl -X POST ${base}/generate/${encodeURIComponent(firstMod.key)}/default -H 'content-type: application/json' -d '{}'`);
683
1156
  console.log(`docs: GET ${base}/drafts (json index of everything above)`);
1157
+ console.log(`ui: open ${base}/ in a browser (every var as a form control)`);
684
1158
  }
685
1159
  //#endregion
686
1160
  export { runServe };
687
1161
 
688
- //# sourceMappingURL=run-serve-D47Zas-a.js.map
1162
+ //# sourceMappingURL=run-serve-D1Tsuru9.js.map