comfy-ts 2.11.0 → 2.13.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 (122) hide show
  1. package/README.md +1 -0
  2. package/dist/{LogsSt-qtFzOKpu.js → LogsSt-CUeo843w.js} +51 -7
  3. package/dist/LogsSt-CUeo843w.js.map +1 -0
  4. package/dist/cli.js +4 -4
  5. package/dist/index.cjs +595 -73
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +286 -46
  8. package/dist/index.d.ts +286 -46
  9. package/dist/index.js +591 -74
  10. package/dist/index.js.map +1 -1
  11. package/dist/{run-serve-BK7BA2dn.js → run-serve-DlRBv_Nk.js} +738 -58
  12. package/dist/run-serve-DlRBv_Nk.js.map +1 -0
  13. package/dist/{run-tui-CQyvMf0N.js → run-tui-B5uxm2_l.js} +43 -18
  14. package/dist/run-tui-B5uxm2_l.js.map +1 -0
  15. package/dist/{schemaDrift-DjjEtwfx.js → schemaDrift-E95iTF7E.js} +473 -60
  16. package/dist/schemaDrift-E95iTF7E.js.map +1 -0
  17. package/dist/serve-web.js +710 -174
  18. package/dist/{state--wrz0BQc.js → state-CUp2J1Zy.js} +126 -14
  19. package/dist/state-CUp2J1Zy.js.map +1 -0
  20. package/dist/web.d.ts +286 -46
  21. package/dist/web.js +591 -74
  22. package/dist/web.js.map +1 -1
  23. package/examples/comfy-cloud/sdk.d.ts +163 -163
  24. package/examples/rvion/06-qwen-image-edit.cflow.ts +3 -2
  25. package/examples/rvion/10-anima-t2i.cflow.ts +252 -0
  26. package/examples/rvion/11-yue2-t2a.cflow.ts +105 -0
  27. package/examples/rvion/12-stable-audio-3-t2a.cflow.ts +78 -0
  28. package/examples/rvion/13-ace-step-15-xl-t2a.cflow.ts +153 -0
  29. package/examples/rvion/stableAudio3Prompts.ts +19 -0
  30. package/extra/README.md +4 -0
  31. package/extra/comfyui-fresh-model-lists/README.md +25 -0
  32. package/extra/comfyui-fresh-model-lists/__init__.py +36 -0
  33. package/extra/comfyui-fresh-model-lists/test_fresh_model_lists.py +97 -0
  34. package/package.json +15 -7
  35. package/src/cli/draftMeta.ts +39 -0
  36. package/src/cli/serve/ServeApp.ts +305 -30
  37. package/src/cli/serve/applyVarPayload.ts +50 -22
  38. package/src/cli/serve/byteRange.ts +48 -0
  39. package/src/cli/serve/describeVar.ts +42 -6
  40. package/src/cli/serve/llmConfigShape.ts +51 -0
  41. package/src/cli/serve/llmConfigs.ts +52 -0
  42. package/src/cli/serve/run-serve.ts +12 -3
  43. package/src/cli/serve/tagList.ts +92 -0
  44. package/src/cli/serve/tagSource.ts +69 -0
  45. package/src/cli/serve/web/api.ts +72 -0
  46. package/src/cli/serve/web/components/App.tsx +485 -44
  47. package/src/cli/serve/web/components/DraftTabs.tsx +167 -0
  48. package/src/cli/serve/web/components/Gallery.tsx +133 -31
  49. package/src/cli/serve/web/components/HistoryPicker.tsx +149 -0
  50. package/src/cli/serve/web/components/Icon.tsx +58 -2
  51. package/src/cli/serve/web/components/MenuButton.tsx +53 -0
  52. package/src/cli/serve/web/components/Omnibox.tsx +135 -0
  53. package/src/cli/serve/web/components/PromptEnhancer.tsx +476 -180
  54. package/src/cli/serve/web/components/SideMenu.tsx +414 -0
  55. package/src/cli/serve/web/components/TooltipLayer.tsx +46 -0
  56. package/src/cli/serve/web/components/VarIcon.tsx +24 -0
  57. package/src/cli/serve/web/components/VarsForm.tsx +223 -351
  58. package/src/cli/serve/web/components/controls/BasicControls.tsx +57 -32
  59. package/src/cli/serve/web/components/controls/LorasControl.tsx +646 -317
  60. package/src/cli/serve/web/components/controls/PresetPicker.tsx +1 -1
  61. package/src/cli/serve/web/components/controls/PromptControl.tsx +279 -0
  62. package/src/cli/serve/web/components/controls/PromptEditor.tsx +113 -0
  63. package/src/cli/serve/web/components/controls/SeedControl.tsx +17 -10
  64. package/src/cli/serve/web/components/controls/SizeControl.tsx +111 -18
  65. package/src/cli/serve/web/components/modKey.ts +2 -0
  66. package/src/cli/serve/web/llm.ts +23 -12
  67. package/src/cli/serve/web/promptEditor/promptExtensions.ts +284 -0
  68. package/src/cli/serve/web/state/EnhancerSt.ts +431 -101
  69. package/src/cli/serve/web/state/FormSt.ts +214 -30
  70. package/src/cli/serve/web/state/OmniboxSt.ts +59 -0
  71. package/src/cli/serve/web/state/WebSt.ts +364 -80
  72. package/src/cli/serve/web/state/choiceButtons.ts +61 -0
  73. package/src/cli/serve/web/state/draftNames.ts +16 -0
  74. package/src/cli/serve/web/state/draftTabs.ts +75 -0
  75. package/src/cli/serve/web/state/generateButton.ts +16 -0
  76. package/src/cli/serve/web/state/history.ts +54 -0
  77. package/src/cli/serve/web/state/host.ts +5 -2
  78. package/src/cli/serve/web/state/keptLines.ts +53 -0
  79. package/src/cli/serve/web/state/latentMode.ts +20 -0
  80. package/src/cli/serve/web/state/loraSort.ts +18 -0
  81. package/src/cli/serve/web/state/moduleTree.ts +2 -2
  82. package/src/cli/serve/web/state/omnibox.ts +133 -0
  83. package/src/cli/serve/web/state/payload.ts +38 -58
  84. package/src/cli/serve/web/state/shortcuts.ts +103 -0
  85. package/src/cli/serve/web/state/sizeStars.ts +31 -0
  86. package/src/cli/serve/web/state/stableSlots.ts +21 -0
  87. package/src/cli/serve/web/state/varGroups.ts +24 -0
  88. package/src/cli/serve/web/styles.ts +653 -154
  89. package/src/cli/serve/webBundle.ts +54 -10
  90. package/src/cli/serve/workflowTags.ts +42 -0
  91. package/src/cli/serve/workspaceLabels.ts +23 -0
  92. package/src/cli/tui/components/PickerOverlays.tsx +9 -2
  93. package/src/cli/tui/imagePicker/ImagePickerSt.ts +1 -1
  94. package/src/cli/tui/state/DraftsSt.ts +28 -8
  95. package/src/cli/tui/state/EditorSt.ts +1 -1
  96. package/src/cli/tui/state/LorasSt.ts +1 -1
  97. package/src/cli/tui/state/PickerSt.ts +25 -7
  98. package/src/cli/tui/state/SettingsSt.ts +1 -1
  99. package/src/cli/tui/state/TuiSt.ts +10 -0
  100. package/src/coreExports.ts +21 -0
  101. package/src/host/ComfyHost.ts +17 -2
  102. package/src/host/ResilientWebsocket.ts +54 -4
  103. package/src/host/loraInfoCache.ts +6 -0
  104. package/src/runner/ComfyExecution.ts +60 -0
  105. package/src/runner/ComfyWorkflow.ts +4 -0
  106. package/src/runner/ComfyWsApi.ts +2 -0
  107. package/src/runner/MediaImage.ts +2 -2
  108. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +5 -5
  109. package/src/sdk-generator/comfyui-sdk-codegen.ts +1 -1
  110. package/src/state.ts +5 -0
  111. package/src/utils/copyName.ts +12 -0
  112. package/src/vars/ComfyVars.ts +337 -67
  113. package/src/vars/DefinedWorkflow.ts +47 -20
  114. package/src/vars/lanes.ts +238 -0
  115. package/src/vars/loraEntry.ts +101 -0
  116. package/src/vars/promptSyntax.ts +382 -0
  117. package/dist/LogsSt-qtFzOKpu.js.map +0 -1
  118. package/dist/run-serve-BK7BA2dn.js.map +0 -1
  119. package/dist/run-tui-CQyvMf0N.js.map +0 -1
  120. package/dist/schemaDrift-DjjEtwfx.js.map +0 -1
  121. package/dist/state--wrz0BQc.js.map +0 -1
  122. package/src/cli/serve/web/components/Sidebar.tsx +0 -66
@@ -1,11 +1,11 @@
1
- import { A as fetchLoraExampleImages, B as lmSha256, D as writeLoraMirror, E as reloadLoraInfoCache, F as lmFilePath, G as loraPreviewMapFrom, I as lmFileSize, J as stripAnsi, K as ansi, L as lmFolder, M as fetchLoraPreviewBytes, N as lmBaseModel, O as fetchLoraCivitai, P as lmCivitai, S as loraMirrorEntries, T as refreshLoraInfoCacheIfChanged, V as lmTags, W as loraKey, Y as extractErrorMessage, Z as bang, _ as getLoraInfo, b as getLoraTriggers, g as getLoraDisplayName, h as getLoraAddedAt, i as summarizeDrift, it as statelessRegex, j as fetchLoraList, k as fetchLoraDescription, m as buildLoraMirror, o as DEFAULT_IMAGE_EXTENSIONS, q as colorsAvailable, r as driftChanged, u as getLoraKeyword, v as getLoraPreviewUrl, w as recordCivitaiMiss, y as getLoraTriggerWords, z as lmNotes } from "./schemaDrift-DjjEtwfx.js";
2
- import { a as draftsDirForFile, f as scanCflowFiles, i as draftKeyForFile, n as assembleLogChunks, o as listDraftsForFile, u as findDefinedWorkflow } from "./LogsSt-qtFzOKpu.js";
1
+ import { $ as stripAnsi, A as refreshLoraInfoCacheIfChanged, B as lmFilePath, C as getLoraTriggerWords, D as lorasMissingFromMirror, E as loraMirrorEntries, F as fetchLoraExampleImages, G as lmSha256, H as lmFolder, I as fetchLoraList, K as lmTags, L as fetchLoraPreviewBytes, M as writeLoraMirror, N as fetchLoraCivitai, P as fetchLoraDescription, Q as colorsAvailable, R as lmBaseModel, S as getLoraPreviewUrl, V as lmFileSize, W as lmNotes, X as loraPreviewMapFrom, Y as loraKey, Z as ansi, b as getLoraDisplayName, d as isPromptInput, dt as sha1HexOfString, et as extractErrorMessage, f as isLoraStrength, i as summarizeDrift, j as reloadLoraInfoCache, k as recordCivitaiMiss, l as isLoraLanes, lt as statelessRegex, m as getLoraKeyword, nt as bang, o as DEFAULT_IMAGE_EXTENSIONS, r as driftChanged, u as isLorasInput, v as buildLoraMirror, w as getLoraTriggers, x as getLoraInfo, y as getLoraAddedAt, z as lmCivitai } from "./schemaDrift-E95iTF7E.js";
2
+ import { a as draftsDirForFile, c as isDraftMetaKey, f as findDefinedWorkflow, i as draftKeyForFile, m as scanCflowFiles, n as assembleLogChunks, o as listDraftsForFile, s as ENHANCE_KEY } from "./LogsSt-CUeo843w.js";
3
3
  import { fileURLToPath, pathToFileURL } from "node:url";
4
4
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
5
- import { basename, dirname, extname, join, resolve } from "pathe";
5
+ import { basename, dirname, extname, isAbsolute, join, resolve } from "pathe";
6
6
  import { nanoid } from "nanoid";
7
7
  import { createServer } from "node:http";
8
- import { networkInterfaces } from "node:os";
8
+ import { homedir, networkInterfaces } from "node:os";
9
9
  //#region src/cli/serve/describeVar.ts
10
10
  /** an empty list is absent from the json: every var without presets would otherwise carry `[]` */
11
11
  function presetsOrUndefined(presets) {
@@ -19,15 +19,21 @@ function describeVar(varDef) {
19
19
  const base = {
20
20
  kind: varDef.kind,
21
21
  label: varDef.label,
22
- default: varDef.defaultValue
22
+ default: varDef.defaultValue,
23
+ ...Object.keys(varDef.uiOpts).length > 0 ? { ui: varDef.uiOpts } : {}
23
24
  };
24
25
  switch (varDef.kind) {
25
26
  case "prompt": {
26
27
  const v = varDef;
27
28
  return {
28
29
  ...base,
29
- payload: "string (\"//\" lines = comments, \"- \" lines = negative)",
30
- textPresets: presetsOrUndefined(v.presets)
30
+ payload: "string (\"//\" starts a comment, \"- \" lines = negative)",
31
+ textPresets: presetsOrUndefined(v.presets),
32
+ tags: v.tags == null ? void 0 : {
33
+ underscores: v.tags.underscores === true,
34
+ artistPrefix: v.tags.artistPrefix
35
+ },
36
+ weights: v.promptOpts.weights === false ? false : void 0
31
37
  };
32
38
  }
33
39
  case "text": {
@@ -74,10 +80,13 @@ function describeVar(varDef) {
74
80
  };
75
81
  case "choice": {
76
82
  const v = varDef;
83
+ const list = v.choices.join(" | ");
84
+ const payload = v.select === "many" ? `a list of: ${list}` : v.select === "zero-or-one" ? `null or one of: ${list}` : `one of: ${list}`;
77
85
  return {
78
86
  ...base,
79
- payload: `one of: ${v.choices.join(" | ")}`,
80
- choices: v.choices
87
+ payload,
88
+ choices: v.choices,
89
+ select: v.select
81
90
  };
82
91
  }
83
92
  case "loras": {
@@ -94,7 +103,8 @@ function describeVar(varDef) {
94
103
  return {
95
104
  ...base,
96
105
  payload: "{\"width\":W,\"height\":H} or \"WxH\" or a preset label",
97
- presets: v.presets
106
+ presets: v.presets,
107
+ starredPresets: [...v.starred]
98
108
  };
99
109
  }
100
110
  case "image": {
@@ -134,11 +144,6 @@ function truncate(s, n) {
134
144
  function isFiniteNumber(x) {
135
145
  return typeof x === "number" && Number.isFinite(x);
136
146
  }
137
- function isLoraStrength(x) {
138
- if (typeof x === "boolean") return true;
139
- if (isFiniteNumber(x)) return true;
140
- return Array.isArray(x) && x.length === 2 && isFiniteNumber(x[0]) && isFiniteNumber(x[1]);
141
- }
142
147
  /** cap long option lists in error messages */
143
148
  function listSome(items, cap = 20) {
144
149
  if (items.length <= cap) return items.join(", ");
@@ -151,10 +156,13 @@ function applyVarPayload(varDef, raw, opts = {}) {
151
156
  const name = varDef.name ?? varDef.label ?? varDef.kind;
152
157
  switch (varDef.kind) {
153
158
  case "text":
154
- case "prompt":
155
159
  if (typeof raw !== "string") return `var '${name}' expects a string`;
156
160
  varDef.set(raw);
157
161
  return null;
162
+ case "prompt":
163
+ if (!isPromptInput(raw)) return `var '${name}' expects a string or {"lanes": [{"name": string, "prompt": string, "active": boolean}]}`;
164
+ varDef.set(raw);
165
+ return null;
158
166
  case "int":
159
167
  case "float": {
160
168
  const v = varDef;
@@ -191,18 +199,44 @@ function applyVarPayload(varDef, raw, opts = {}) {
191
199
  return null;
192
200
  case "choice": {
193
201
  const v = varDef;
194
- if (typeof raw === "string" && v.parse(raw)) return null;
202
+ const known = (x) => typeof x === "string" && v.choices.includes(x);
203
+ if (v.select === "many") {
204
+ if (known(raw)) {
205
+ v.set([raw]);
206
+ return null;
207
+ }
208
+ if (Array.isArray(raw) && raw.every(known)) {
209
+ v.set(v.choices.filter((c) => raw.includes(c)));
210
+ return null;
211
+ }
212
+ return `var '${name}' expects a list of: ${listSome(v.choices)}`;
213
+ }
214
+ if (v.select === "zero-or-one") {
215
+ if (raw === null || known(raw)) {
216
+ v.set(raw);
217
+ return null;
218
+ }
219
+ return `var '${name}' expects null or one of: ${listSome(v.choices)}`;
220
+ }
221
+ if (known(raw)) {
222
+ v.set(raw);
223
+ return null;
224
+ }
195
225
  return `var '${name}' expects one of: ${listSome(v.choices)}`;
196
226
  }
197
227
  case "loras": {
198
228
  const v = varDef;
199
- if (raw == null || typeof raw !== "object" || Array.isArray(raw)) return `var '${name}' expects {"<lora name>": false | true | strength | [model, clip]}`;
200
- const record = raw;
229
+ const SHAPE = `{"<lora name>": false | true | strength | [model, clip] | {strength, off?, mute?}} or {"lanes": [{"name", "active", "loras": {…}}]}`;
230
+ if (raw == null || typeof raw !== "object" || Array.isArray(raw)) return `var '${name}' expects ${SHAPE}`;
231
+ const records = isLoraLanes(raw) ? raw.lanes.map((l) => l.loras) : [raw];
201
232
  const known = /* @__PURE__ */ new Set([...v.options, ...opts.extraLoraOptions ?? []]);
202
- const unknownNames = Object.keys(record).filter((k) => !known.has(k));
203
- if (unknownNames.length > 0) return `var '${name}': unknown lora(s) ${unknownNames.join(", ")} — available: ${listSome([...known])}`;
204
- for (const [k, st] of Object.entries(record)) if (!isLoraStrength(st)) return `var '${name}': '${k}' must be false | true | number | [model, clip]`;
205
- v.set(record);
233
+ for (const record of records) {
234
+ const unknownNames = Object.keys(record).filter((k) => !known.has(k));
235
+ if (unknownNames.length > 0) return `var '${name}': unknown lora(s) ${unknownNames.join(", ")} — available: ${listSome([...known])}`;
236
+ for (const [k, st] of Object.entries(record)) if (!isLoraStrength(st)) return `var '${name}': '${k}' must be false | true | number | [model, clip] | { strength: [model, clip], off?, mute? }`;
237
+ }
238
+ if (!isLorasInput(raw)) return `var '${name}' expects ${SHAPE}`;
239
+ v.set(raw);
206
240
  return null;
207
241
  }
208
242
  case "size": {
@@ -252,13 +286,13 @@ function validSavePrefix(raw) {
252
286
  }
253
287
  //#endregion
254
288
  //#region src/promptEnhancers.ts
255
- const EXT = ".md";
289
+ const EXT$1 = ".md";
256
290
  function promptEnhancersDir() {
257
291
  return comfyts.resolveFromPromptEnhancers("");
258
292
  }
259
293
  function promptEnhancerPath(name) {
260
294
  const safe = validStoreName(name);
261
- return safe == null ? null : join(promptEnhancersDir(), `${safe}${EXT}`);
295
+ return safe == null ? null : join(promptEnhancersDir(), `${safe}${EXT$1}`);
262
296
  }
263
297
  /** the shipped starting point. It is a FILE from the first read on, so it can be edited
264
298
  * on disk like everything else, the browser ships no copy of this text */
@@ -294,7 +328,7 @@ function readPromptEnhancers() {
294
328
  if (!existsSync(dir)) return [];
295
329
  const out = [];
296
330
  for (const file of readdirSync(dir).sort()) {
297
- if (!file.endsWith(EXT)) continue;
331
+ if (!file.endsWith(EXT$1)) continue;
298
332
  const name = file.slice(0, -3);
299
333
  if (validStoreName(name) == null) continue;
300
334
  try {
@@ -323,6 +357,85 @@ function deletePromptEnhancer(name) {
323
357
  return true;
324
358
  }
325
359
  //#endregion
360
+ //#region src/cli/serve/web/llm.ts
361
+ const OPENROUTER_BASE = "https://openrouter.ai/api/v1";
362
+ const OPENWEBUI_BASE = "http://localhost:3000";
363
+ const OPENAI_COMPAT_BASE = "http://localhost:8080/v1";
364
+ function defaultBaseUrl(provider) {
365
+ if (provider === "openrouter") return OPENROUTER_BASE;
366
+ return provider === "openwebui" ? OPENWEBUI_BASE : OPENAI_COMPAT_BASE;
367
+ }
368
+ //#endregion
369
+ //#region src/cli/serve/llmConfigShape.ts
370
+ function isProvider(raw) {
371
+ return raw === "openrouter" || raw === "openwebui" || raw === "openai";
372
+ }
373
+ function isEffort(raw) {
374
+ return raw === "off" || raw === "low" || raw === "medium" || raw === "high";
375
+ }
376
+ /** explicit model ids, never an alias: behaviour and cost stay reproducible */
377
+ const DEFAULT_MODEL = {
378
+ openrouter: "anthropic/claude-sonnet-5",
379
+ openwebui: "",
380
+ openai: ""
381
+ };
382
+ /** a stored file → a usable config: a half-written or hand-broken field degrades to its
383
+ * default, never breaks the modal */
384
+ function normalizeLlmConfig(raw) {
385
+ const o = typeof raw === "object" && raw !== null && !Array.isArray(raw) ? raw : {};
386
+ const provider = isProvider(o.provider) ? o.provider : "openrouter";
387
+ return {
388
+ provider,
389
+ baseUrl: typeof o.baseUrl === "string" && o.baseUrl.trim() !== "" ? o.baseUrl.trim() : defaultBaseUrl(provider),
390
+ model: typeof o.model === "string" ? o.model : DEFAULT_MODEL[provider],
391
+ effort: isEffort(o.effort) ? o.effort : "medium",
392
+ thinkingOnly: o.thinkingOnly !== false
393
+ };
394
+ }
395
+ //#endregion
396
+ //#region src/cli/serve/llmConfigs.ts
397
+ const EXT = ".json";
398
+ function llmConfigsDir() {
399
+ return comfyts.resolveFromLlmConfigs("");
400
+ }
401
+ function llmConfigPath(name) {
402
+ const safe = validStoreName(name);
403
+ return safe == null ? null : join(llmConfigsDir(), `${safe}${EXT}`);
404
+ }
405
+ function listLlmConfigs() {
406
+ const dir = llmConfigsDir();
407
+ if (!existsSync(dir)) return [];
408
+ const out = [];
409
+ for (const file of readdirSync(dir).sort()) {
410
+ if (!file.endsWith(EXT)) continue;
411
+ const name = file.slice(0, -5);
412
+ if (validStoreName(name) == null) continue;
413
+ try {
414
+ out.push({
415
+ name,
416
+ config: normalizeLlmConfig(JSON.parse(readFileSync(join(dir, file), "utf8")))
417
+ });
418
+ } catch (e) {
419
+ console.error(`[serve] llm config '${name}' unreadable, skipped:`, e);
420
+ }
421
+ }
422
+ return out;
423
+ }
424
+ function writeLlmConfig(name, config) {
425
+ const path = llmConfigPath(name);
426
+ if (path == null) return null;
427
+ mkdirSync(llmConfigsDir(), { recursive: true });
428
+ writeFileSync(path, `${JSON.stringify(normalizeLlmConfig(config), null, 3)}\n`);
429
+ return path;
430
+ }
431
+ /** a missing file is still a success: the caller asked for it to be gone, and it is */
432
+ function deleteLlmConfig(name) {
433
+ const path = llmConfigPath(name);
434
+ if (path == null) return false;
435
+ if (existsSync(path)) rmSync(path);
436
+ return true;
437
+ }
438
+ //#endregion
326
439
  //#region src/cli/serve/managerOnlyLoras.ts
327
440
  /**
328
441
  * `options` is the host enum for this var: it decides both what counts as already-known
@@ -336,9 +449,223 @@ function managerOnlyLoraOptions(p) {
336
449
  return loraMirrorEntries(p.hostId, { separator }).filter((e) => !known.has(e.key)).map((e) => e.serverName).filter((n) => filter == null || filter.test(n));
337
450
  }
338
451
  //#endregion
452
+ //#region src/cli/serve/tagList.ts
453
+ /** one csv line, double-quoted fields with `""` escapes */
454
+ function csvFields(line) {
455
+ const out = [];
456
+ let cur = "";
457
+ let quoted = false;
458
+ for (let i = 0; i < line.length; i++) {
459
+ const ch = line[i];
460
+ if (quoted) if (ch === "\"" && line[i + 1] === "\"") {
461
+ cur += "\"";
462
+ i++;
463
+ } else if (ch === "\"") quoted = false;
464
+ else cur += ch;
465
+ else if (ch === "\"") quoted = true;
466
+ else if (ch === ",") {
467
+ out.push(cur);
468
+ cur = "";
469
+ } else cur += ch;
470
+ }
471
+ out.push(cur);
472
+ return out;
473
+ }
474
+ const intOrNull = (s) => s != null && /^\d+$/.test(s.trim()) ? Number(s) : null;
475
+ function parseTagList(text) {
476
+ const out = [];
477
+ for (const raw of text.split(/\r?\n/)) {
478
+ const line = raw.trim();
479
+ if (line === "" || line.startsWith("#")) continue;
480
+ const f = csvFields(line);
481
+ const name = (f[0] ?? "").trim();
482
+ if (name === "") continue;
483
+ const twoCols = f.length === 2;
484
+ out.push({
485
+ name,
486
+ category: twoCols ? null : intOrNull(f[1]),
487
+ count: (twoCols ? intOrNull(f[1]) : intOrNull(f[2])) ?? 0,
488
+ aliases: (f[3] ?? "").split(",").map((a) => a.trim()).filter((a) => a !== "")
489
+ });
490
+ }
491
+ return out;
492
+ }
493
+ /** the searchable form: lowercase, spaces as underscores (the lists write `long_hair`) */
494
+ const key = (s) => s.trim().toLowerCase().replace(/\s+/g, "_");
495
+ var TagList = class TagList {
496
+ constructor(entries) {
497
+ this.entries = entries;
498
+ this.rows = entries.map((e) => ({
499
+ e,
500
+ name: key(e.name),
501
+ aliases: e.aliases.map(key)
502
+ }));
503
+ this.rows.sort((a, b) => b.e.count - a.e.count);
504
+ }
505
+ static parse(text) {
506
+ return new TagList(parseTagList(text));
507
+ }
508
+ /** prefix of the name first, then prefix of an alias (answered with the name it points to),
509
+ * then a word inside the name (`hair` finds `long_hair`), each by post count */
510
+ search(query, limit = 20) {
511
+ const q = key(query);
512
+ if (q === "") return [];
513
+ const hits = [];
514
+ const seen = /* @__PURE__ */ new Set();
515
+ const take = (e, alias) => {
516
+ if (seen.has(e.name)) return false;
517
+ seen.add(e.name);
518
+ hits.push(alias == null ? {
519
+ name: e.name,
520
+ category: e.category,
521
+ count: e.count
522
+ } : {
523
+ ...pick(e),
524
+ alias
525
+ });
526
+ return hits.length >= limit;
527
+ };
528
+ for (const r of this.rows) if (r.name.startsWith(q) && take(r.e)) return hits;
529
+ for (const r of this.rows) {
530
+ const a = r.aliases.find((x) => x.startsWith(q));
531
+ if (a != null && take(r.e, a)) return hits;
532
+ }
533
+ for (const r of this.rows) if (r.name.includes(`_${q}`) && take(r.e)) return hits;
534
+ return hits;
535
+ }
536
+ };
537
+ const pick = (e) => ({
538
+ name: e.name,
539
+ category: e.category,
540
+ count: e.count
541
+ });
542
+ //#endregion
543
+ //#region src/cli/serve/tagSource.ts
544
+ /** http(s) stays a url; `file://`, `~/`, absolute and relative (to the workflow file) become a path */
545
+ function resolveTagSource(url, moduleFile) {
546
+ if (/^https?:\/\//i.test(url)) return {
547
+ kind: "http",
548
+ url
549
+ };
550
+ if (url.startsWith("file://")) return {
551
+ kind: "file",
552
+ path: fileURLToPath(url)
553
+ };
554
+ if (url === "~" || url.startsWith("~/")) return {
555
+ kind: "file",
556
+ path: join(homedir(), url.slice(1))
557
+ };
558
+ if (isAbsolute(url)) return {
559
+ kind: "file",
560
+ path: url
561
+ };
562
+ return {
563
+ kind: "file",
564
+ path: resolve(dirname(moduleFile), url)
565
+ };
566
+ }
567
+ var TagSources = class {
568
+ constructor(p) {
569
+ this.p = p;
570
+ this.files = /* @__PURE__ */ new Map();
571
+ this.remote = /* @__PURE__ */ new Map();
572
+ }
573
+ async load(ref) {
574
+ if (ref.kind === "file") return this.loadFile(ref.path);
575
+ const hit = this.remote.get(ref.url);
576
+ if (hit != null) return hit;
577
+ const pending = this.loadRemote(ref.url);
578
+ this.remote.set(ref.url, pending);
579
+ pending.catch(() => this.remote.delete(ref.url));
580
+ return pending;
581
+ }
582
+ loadFile(path) {
583
+ if (!existsSync(path)) throw new Error(`tag list not found: ${path}`);
584
+ const mtimeMs = statSync(path).mtimeMs;
585
+ const cached = this.files.get(path);
586
+ if (cached != null && cached.mtimeMs === mtimeMs) return cached.list;
587
+ const list = TagList.parse(readFileSync(path, "utf8"));
588
+ if (list.entries.length === 0) throw new Error(`tag list is empty: ${path}`);
589
+ this.files.set(path, {
590
+ mtimeMs,
591
+ list
592
+ });
593
+ return list;
594
+ }
595
+ async loadRemote(url) {
596
+ const file = join(this.p.cacheDir(), `${sha1HexOfString(url)}.txt`);
597
+ if (existsSync(file)) return TagList.parse(readFileSync(file, "utf8"));
598
+ console.log(`[serve] fetching tag list ${url}`);
599
+ const text = await this.p.fetchText(url);
600
+ const list = TagList.parse(text);
601
+ if (list.entries.length === 0) throw new Error(`tag list is empty: ${url}`);
602
+ mkdirSync(dirname(file), { recursive: true });
603
+ writeFileSync(file, text);
604
+ console.log(`[serve] tag list ${url}: ${list.entries.length} tags, kept in ${file}`);
605
+ return list;
606
+ }
607
+ };
608
+ //#endregion
339
609
  //#region src/cli/serve/favicon.ts
340
610
  const FAVICON_DATA_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAKUklEQVR42u1aaWxU1xW2DWEJZCENNgaK8iNRU5UAAYKBWW1ImwbaoqiuQkrUVlRdlDZSGpqAcTKrFyAoJRCRKmpRidKA98Sm0MQhRClOs7CIggiTtniZN4sZe8AeL/Puvef23LeMnwePQdWwhTnS9XvP8zzvft/5znfPfXJWViYykYlMZCITmchEJjKRiUxc4eCcj8ExFkfOzQg+23huvL5pwFNKf8wYexmvZ2m/H6cpQlHFV5IYIXvtaMEh4+CM83/hIS9ZGSOUSvYNnXUNyC3iGgA2KuAZ7+NqvI3jZ6iKp3GsIYQsw+sZOmFJZIy5Ec0uRzufhOMHjMGnGnAUAAdtJALUqxgwOIYs7UBCViFptycTekNkXcv4eMzsL/Hap2Pkw0MQQbTBkj/UbvDjj514ukQvh+uWCOPE8LgUpX7UAJxpY7QAzqh6b1+rzPslZuANvZMdIoR/3/CMMdfNcqqBVyZDOV+P53FV1kCNwCEFbi5uA/U2GjoI5MBsYJFPlTIBRqnxTxnAYTws056bc83VoAP3+XzjMUu7E8AZYRyIBkwreQDDuQBNlHMl7SwO5IvtIFdNAHr8GfUmhb9hJaOTKb71L7FYLN+40lwz8HicgODrtMmRlMkeIf2MxoH53wF6sAjI3vFA6/OA9ZwWAEFXRbI1aMoSdXFWlmXzNSFBb1q09bpGmxvRpU7P7AB6ZhvQ7qPA+kPA5Bhw0seY3Ass1g48/D6jp7wgN5sw65M5rbqNk6o7gDRbFVJUIUFq4phGAhfLKvmeNqexV63dNmR/hyZQYqx01lbNSP00kGvuBLnxXhhs+ibI+7/F5H3fALlhFpDaO4FU3QK0ZgqXa/G+uumM7EH5tzyh1QiDodUxlWsmlBAzKCFHm2B21pVqpAxO/Bt1AsOLVa9r2tsK5O8Pgbx3IsRr7gJScwcSMgXB5qLU84E2TMcjgq+9m+CR0KpJwA7/kCeMgolMj06CwRf+PSizXTJhf8Y/fQavc1N1munK/DwcF0YyeDV1qiDohdNAGu8TIBF4PiN1uaiMPAQ/DUhdHo6pEK/LpagWSpAcXAE4i0eHqUCQcEkvGZqDQsjeT/qPZi0+eVdCDene2OBTmgxLHb+IAM0SxJH4/ohynwRC6ghakKCBz0NScNTnIQE48DO55lYgrbvVr6CyAoxdhqnKuO7sOx6TPQ3R+GN/CA+aKy9w89Yem5hrcXHVmHRL/1GNarhUb6PcF+8C8rfZoGQYVYCAgdRPVbKvkFGfSxUS6vIJegaT92Mf0O/XyoCMaoh6C3m8dZDP39gOD6yXqGXTILe4g589/OzxSdrMs9OafTzWpcr+iFYlVHD4cYjvmYgZn0bluqlMrs0FMUh9Po+jF8j1+YzWTSNy/XRKqicD/fBRYINdWj+QmmeqOcDuf/TAvBI/FJWFwOwO1Fk2fvn1tMrfkP0ZCLx71OYuyaMUQ/zs17jOTxSARbZZvBalL4yxejKX944DuXq8MElGUAGk+nagb2YB3Xc/0NC7cKlHIQmw9vVOusgZ4csrAs8qsq8S800f+BwDASsuT/7DZUo/XoNgbwPSMFMtBQRNm+4B0rIa2KlNQFvfACY1qqPtLWA+7CE++SnQd+cCC7+n9pAouEQvCUPZP3hqkC0sDXKrR6JFXmm+mKfN8cHYtIB3OBy66+fh7u53uOae0vb17HLkr3phL7r7IrHmoxlOwPN5CHA7sL6AbnDDBhjNlA7g6OPDfgdDtR8bYPDEq520wBXhVm/wy4e3pLHu9SUP9+bfppQFjaiMk0iNX7UIFj7E4lWTUd63AzuxAWhimdPMTdkzEG1/oA1GeIpWWJW99uxtB87DnBK/XLSlVxDwmpq0NHSBuuHtbI7MiBMmac+ND8iMnuwYhM4LijsrE4GLcm7Y4QoYLY9TWj2JUalhaH2nRNn+jtblqJ8Nf3cCBuNrPjkABS9KYHJ2gMUT5uay0LK0LXs6i8srw+Z1ewd5eVOMr3urGx7bFmL4UPajV0LstBTXNuuqGgCSpyoSOQD0n08yFnpflbuyrDEY6a1Qyn7CEEQDf6JDhqKKECxxSsReHuUWT+QQTleXfXq7v7nPt5fPWe+Pzi/xxxe7OpnVE2AFpQFm9wbY20d62dBbi5RloTY06guP5DFi5kdShp75L4IEVmzthAJHAMRcrN5z3OYJP5LWpic5ntru/9qTlSdn2T2db1g39eIDA7LJJcGDJX72+z1drO2czBKvfy7yB9CrNjGM5qe1uhcN/TuMjn/k7CB8d0sYFqH0Le4AsW/u59ay0C5VtldqByi+WFsNbI72e23l0U5LWYSb3BKzugMwfyM2IOUB9sqBKAS6yTAnFxMXylCzOqyoRx3iXtz4c0L1P+PQdKwf1Sdh5hG8J0gs3m5u84Z9RWX/yUt7zz+CK2Yv+MXnyituuye41o4qMLkDFLsuZvMGweQKwtwNHbCsMsDKG6PsWBu+4UkycUGEAESTMs5GaHXVclIJO9/PwNsQhQWlaHhuAd5PLe4wWMvO9Vsc/7VeUeknh/4gm0tyFiIJZk+ImjEbZiQAywKWuPwwDxWx2CnBT14Lw58+7IGT/kGQaQqZM5UQNnLNw/4T/cJ44cGN6PQI3uTyM3wes1Vg9j3S6qGu7yqGTkKhq3WdvaKbmcu7uXDjpS6JCV+we0NgcQVgYWkA5pZICimrXw1DxTtRaDwaA18wDtjAsCQlGI0PPjozwH7++jnMekBZ6qweobIANXk6qb0iys3O1t9eE/AJErQH2zz+5ejAPmFGZndQEEBMeMTdmDApEOWBZaKAmLtBggUvIBi8XrklwNYiwOf3RMBV2wU73zsPcTLU8D21qxPuX9cGdqx5QSZ+JzF7z4HVG6EWl/9XaW13/09TyNZJWFHRNsXqkjZbPKE+++YYt3g7ccIBQQQ1aUQIEnDJQkLw3BmEpQ4/PFTqR2n7YfZz7XjeAYGonNDAX1su4ArTgWQpqiK2ivPY6ESiZkf7qusAvFEKSIK2/FjdHfcVYjuKkz5vq8SlUkwagSMAWRAiDNPsEhmVQBwFIVbF1ERtS9Di60+URPOpPrbwhQ6KpLJCQaoz8LnV3f7ANZX9qMtk8dD20+bwzbS7pOfMLv8RYVjWTQgAuzU0TI51jCRgD+EOyiYPkuLCFxi4muAKQkUp6AQ0Hu2nC51daHTBHqsr8OJKh3Tr9Qk+qX0uLh6aoDBLe3lHgd3d4UEgLWaPFLOWR3jhSwNclIoNX1tZUSXWcjyWdfECp8T2fNyDBknJ02/G+JySYH3xjrPT9O92OG6Q/yxRiEh6ISE2V49U+mYWlUmrcLkstTtbd1md/ibcwX2EajiEBnrMVBbBDs8vF3oCAyYkBZe6NQqRDj4u6wb9X4FsoQjVsFIA4HrZ8LHY1TUXbiXcUtHHbeWRTpvj7D1XvsO7qspw5NhsH4wVYB3KuwYNmAZw5UvS3bh8brW4gvvRKL/zlQKfSiEqCcaR/HnWzfWfZMX6snq1evtMZCITmchEJjKRiUxkIhM3ZfwPK9dyLD4coj4AAAAASUVORK5CYII=";
341
611
  //#endregion
612
+ //#region src/cli/serve/workflowTags.ts
613
+ /** display order: what the workflow makes first, then how it works, then free tags */
614
+ const MEDIA_BY_TYPE = {
615
+ IMAGE: "image",
616
+ AUDIO: "audio",
617
+ VIDEO: "video",
618
+ STRING: "text"
619
+ };
620
+ const MEDIA_ORDER = [
621
+ "image",
622
+ "audio",
623
+ "video",
624
+ "text"
625
+ ];
626
+ function workflowTags(p) {
627
+ const byId = new Map(p.nodes.map((n) => [n.id, n]));
628
+ const media = /* @__PURE__ */ new Set();
629
+ for (const node of p.nodes) {
630
+ if (!node.outputNode) continue;
631
+ for (const [producerId, ix] of node.links) {
632
+ const type = byId.get(producerId)?.outputTypes[ix];
633
+ const tag = type == null ? void 0 : MEDIA_BY_TYPE[type];
634
+ if (tag != null) media.add(tag);
635
+ }
636
+ }
637
+ const out = MEDIA_ORDER.filter((t) => media.has(t));
638
+ if (p.nodes.some((n) => /textgenerate/i.test(n.classType))) out.push("llm");
639
+ if (p.varKinds.includes("image")) out.push("edit");
640
+ for (const tag of p.extra ?? []) {
641
+ const t = tag.trim().toLowerCase();
642
+ if (t !== "" && !out.includes(t)) out.push(t);
643
+ }
644
+ return out;
645
+ }
646
+ //#endregion
647
+ //#region src/cli/serve/workspaceLabels.ts
648
+ function tilde(path, home) {
649
+ if (home === "" || home === "/") return path;
650
+ if (path === home) return "~";
651
+ return path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
652
+ }
653
+ function workspaceLabels(p) {
654
+ const ws = p.workspace.replace(/\/+$/, "");
655
+ const root = p.root.replace(/\/+$/, "");
656
+ const rootLabel = root === ws ? "." : root.startsWith(`${ws}/`) ? root.slice(ws.length + 1) : tilde(root, p.home);
657
+ return {
658
+ workspace: {
659
+ path: ws,
660
+ label: tilde(ws, p.home)
661
+ },
662
+ root: {
663
+ path: root,
664
+ label: rootLabel
665
+ }
666
+ };
667
+ }
668
+ //#endregion
342
669
  //#region src/utils/stringMap.ts
343
670
  function stringMap(raw) {
344
671
  const out = {};
@@ -417,6 +744,29 @@ function writeServeSettings(next) {
417
744
  }, null, 2));
418
745
  }
419
746
  //#endregion
747
+ //#region src/cli/serve/web/state/draftTabs.ts
748
+ /** where the serve process keeps them, under .comfy-ts/: draft names are private, so this file
749
+ * must stay gitignored (tests/serve-tabs.test.ts runs git check-ignore on it) */
750
+ const SERVE_TABS_FILE = "serve-tabs.json";
751
+ const same = (a, b) => a.module === b.module && a.draft === b.draft;
752
+ /** a stored list, shape-checked, keeping only drafts that still exist */
753
+ function readTabs(raw, modules) {
754
+ if (!Array.isArray(raw)) return [];
755
+ const out = [];
756
+ for (const x of raw) {
757
+ if (x == null || typeof x !== "object") continue;
758
+ const o = x;
759
+ if (typeof o.module !== "string" || typeof o.draft !== "string") continue;
760
+ const t = {
761
+ module: o.module,
762
+ draft: o.draft
763
+ };
764
+ if (!modules.some((m) => m.module === t.module && m.drafts.includes(t.draft))) continue;
765
+ if (!out.some((y) => same(y, t))) out.push(t);
766
+ }
767
+ return out;
768
+ }
769
+ //#endregion
420
770
  //#region src/cli/serve/ServeApp.ts
421
771
  /** what serve will read off the disk and upload. Wider than the picker default: ComfyUI's
422
772
  * LoadImage takes bmp and tiff too, and a var declaring one of those must not be refused */
@@ -466,6 +816,9 @@ var DownloadRefused = class extends Error {
466
816
  };
467
817
  const INPUT_DOWNLOAD_CAP = 5e7;
468
818
  const INPUT_DOWNLOAD_TIMEOUT_MS = 6e4;
819
+ /** the danbooru list is ~3.5 MB; ten times that is still a tag list, beyond is a wrong url */
820
+ const TAG_LIST_CAP = 4e7;
821
+ const TAG_LIST_TIMEOUT_MS = 12e4;
469
822
  /** read a reply STREAMING, aborting the moment it passes the cap. `arrayBuffer()` buffers the
470
823
  * whole body first, so a chunked reply with no content-length could exhaust the process before
471
824
  * anything checked its size, the cap then reported a number nobody survived to read. */
@@ -520,6 +873,12 @@ const CONTENT_TYPES = {
520
873
  ".gif": "image/gif",
521
874
  ".mp4": "video/mp4",
522
875
  ".webm": "video/webm",
876
+ ".flac": "audio/flac",
877
+ ".mp3": "audio/mpeg",
878
+ ".opus": "audio/ogg",
879
+ ".ogg": "audio/ogg",
880
+ ".wav": "audio/wav",
881
+ ".m4a": "audio/mp4",
523
882
  ".json": "application/json",
524
883
  ".txt": "text/plain"
525
884
  };
@@ -557,10 +916,12 @@ const USAGE = [
557
916
  "GET /drafts/<module>/<draft> — one draft with its stored values",
558
917
  "POST /generate/<module>/<draft> with { ...vars } — run, blocking",
559
918
  "POST /generate/<draft> — unqualified, when unambiguous",
919
+ "POST /preview/<module> with { ...draft values } — the workflow previews for those values, nothing is run",
560
920
  "PUT /drafts/<module>/<draft> with { ...vars } — save (or duplicate to a new name) a draft",
561
921
  "DELETE /drafts/<module>/<draft> — delete that draft file",
562
922
  "GET /run/<module> — live run status · /run/<module>/preview — latent preview bytes",
563
923
  "POST /upload with {\"name\",\"dataBase64\"} — store a browser file for an image var",
924
+ "GET /tags/<module>/<var>?q=<text>&limit=<n> — tag completion from the list a prompt var declares (`tags`)",
564
925
  "GET /hosts/<hostId>/drift[?full=1] — what changed on the host since the schema was loaded (model files; node types with full=1)",
565
926
  "GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)",
566
927
  "POST /hosts/<hostId>/lora-civitai/<lora> — fetch its civitai metadata (trigger words) through the lora manager, then re-sync the mirror",
@@ -568,12 +929,15 @@ const USAGE = [
568
929
  "GET /lora-about/<hostId>/<lora> — civitai description + example images (live from the extension)",
569
930
  "GET /prompt-enhancers — the web ui master prompts (.comfy-ts/prompt-enhancers/*.md)",
570
931
  "PUT /prompt-enhancers/<name> with {\"text\"} — write one · DELETE /prompt-enhancers/<name> — remove it",
932
+ "GET /llm-configs — the enhancer LLM configs (.comfy-ts/llm-configs/*.json)",
933
+ "PUT /llm-configs/<name> with {provider, baseUrl, model, effort, thinkingOnly} · DELETE /llm-configs/<name>",
571
934
  "GET /settings — { saveToDisk } · PUT /settings with {\"saveToDisk\"} — write outputs to disk, or keep them in memory",
572
935
  "GET /hosts — every host this process knows · PUT /hosts/<module> with {\"host\"} — run that workflow elsewhere",
573
936
  "POST /hosts/<hostId>/<interrupt|clear-queue|restart|refresh-loras|refresh-schema> — act on a ComfyUI host",
574
937
  "GET /hosts/<hostId>/ping — is that host answering right now (restart watch)",
575
938
  "GET /hosts/<hostId>/logs — the last lines of that host console",
576
939
  "GET /images/<promptId>/<ix> — an in-memory output (saving off), while the process lives",
940
+ "GET /audio/<promptId>/<ix> — the same for an in-memory audio output",
577
941
  "GET /outputs/<path> — generated files"
578
942
  ];
579
943
  /** content hash of the bundle, so the script URL CHANGES whenever the code does. no-store
@@ -613,10 +977,22 @@ var ServeApp = class {
613
977
  this.opts = opts;
614
978
  this.seedState = /* @__PURE__ */ new Map();
615
979
  this.chains = /* @__PURE__ */ new Map();
616
- this.webJsCache = null;
617
980
  this.settingsCache = null;
618
981
  this.memoryImages = /* @__PURE__ */ new Map();
982
+ this.tagsByModule = /* @__PURE__ */ new Map();
619
983
  this.MEMORY_IMAGE_CAP = 60;
984
+ this.tabs = null;
985
+ this.tagSources = new TagSources({
986
+ cacheDir: () => join(comfyts.baseFolder, "cache", "tags"),
987
+ fetchText: async (url) => {
988
+ const res = await fetch(url, {
989
+ redirect: "follow",
990
+ signal: AbortSignal.timeout(TAG_LIST_TIMEOUT_MS)
991
+ });
992
+ if (!res.ok) throw new Error(`tag list download failed (http ${res.status}): ${url}`);
993
+ return new TextDecoder().decode(await readCapped(res, TAG_LIST_CAP, url));
994
+ }
995
+ });
620
996
  this.liveRuns = /* @__PURE__ */ new Map();
621
997
  this.latentPreviews = /* @__PURE__ */ new Map();
622
998
  this.latentSeq = 0;
@@ -639,8 +1015,7 @@ var ServeApp = class {
639
1015
  }
640
1016
  if (req.method === "GET") {
641
1017
  if (segs.length === 0 && this.opts.webJs != null && req.accept?.includes("text/html") === true) {
642
- this.webJsCache ??= this.opts.webJs();
643
- const js = await this.webJsCache;
1018
+ const js = await this.opts.webJs();
644
1019
  if (js != null) return {
645
1020
  status: 200,
646
1021
  contentType: "text/html; charset=utf-8",
@@ -648,7 +1023,7 @@ var ServeApp = class {
648
1023
  headers: NO_STORE
649
1024
  };
650
1025
  }
651
- if (segs.length === 0 || segs[0] === "drafts" && segs.length === 1) return this.replyIndex();
1026
+ if (segs.length === 0 || segs[0] === "drafts" && segs.length === 1) return await this.replyIndex();
652
1027
  if (segs[0] === "web" && segs[1] === "app.js" && segs.length === 2) return await this.replyWebJs();
653
1028
  if (segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyDraft(segs[1], segs[2]);
654
1029
  if (segs[0] === "run" && segs.length === 2 && segs[1] != null) return this.replyRunStatus(segs[1]);
@@ -657,12 +1032,16 @@ var ServeApp = class {
657
1032
  if (segs[0] === "lora-preview" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyLoraPreview(segs[1], segs[2]);
658
1033
  if (segs[0] === "lora-about" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyLoraAbout(segs[1], segs[2]);
659
1034
  if (segs[0] === "prompt-enhancers" && segs.length === 1) return this.replyPromptEnhancers();
1035
+ if (segs[0] === "llm-configs" && segs.length === 1) return this.replyLlmConfigs();
1036
+ if (segs[0] === "tags" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyTags(segs[1], segs[2], req.url);
660
1037
  if (segs[0] === "settings" && segs.length === 1) return this.replySettings();
1038
+ if (segs[0] === "tabs" && segs.length === 1) return this.replyTabs();
661
1039
  if (segs[0] === "hosts" && segs.length === 1) return this.replyHosts();
662
1040
  if (segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] === "logs") return await this.replyHostLogs(segs[1]);
663
1041
  if (segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] === "ping") return await this.replyHostPing(segs[1]);
664
1042
  if (segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] === "drift") return await this.replyHostDrift(segs[1], req.url.includes("full=1"));
665
1043
  if (segs[0] === "images" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyMemoryImage(`${segs[1]}/${segs[2]}`);
1044
+ if (segs[0] === "audio" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyMemoryImage(`audio/${segs[1]}/${segs[2]}`);
666
1045
  if (segs[0] === "outputs") return this.replyOutput(segs.slice(1));
667
1046
  return json(404, {
668
1047
  error: `no route: GET ${path}`,
@@ -674,15 +1053,19 @@ var ServeApp = class {
674
1053
  if ("error" in target) return json(target.status, { error: target.error });
675
1054
  return await this.generate(target.mod, target.draft, req);
676
1055
  }
1056
+ if (req.method === "POST" && segs[0] === "preview" && segs.length === 2 && segs[1] != null) return await this.replyPreview(segs[1], req);
677
1057
  if (req.method === "POST" && segs[0] === "upload" && segs.length === 1) return this.replyUpload(req);
678
1058
  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);
679
1059
  if (req.method === "DELETE" && segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyDeleteDraft(segs[1], segs[2]);
680
1060
  if (req.method === "PUT" && segs[0] === "settings" && segs.length === 1) return this.replySaveSettings(req);
1061
+ if (req.method === "PUT" && segs[0] === "tabs" && segs.length === 1) return this.replySaveTabs(req);
681
1062
  if (req.method === "PUT" && segs[0] === "hosts" && segs.length === 2 && segs[1] != null) return this.replySetHost(segs[1], req);
682
1063
  if (req.method === "POST" && segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyHostAction(segs[1], segs[2]);
683
1064
  if (req.method === "POST" && segs[0] === "hosts" && segs.length === 4 && segs[1] != null && segs[2] === "lora-civitai" && segs[3] != null) return await this.replyLoraCivitaiFetch(segs[1], segs[3]);
684
1065
  if (req.method === "PUT" && segs[0] === "prompt-enhancers" && segs.length === 2 && segs[1] != null) return this.replySavePromptEnhancer(segs[1], req);
685
1066
  if (req.method === "DELETE" && segs[0] === "prompt-enhancers" && segs.length === 2 && segs[1] != null) return this.replyDeletePromptEnhancer(segs[1]);
1067
+ if (req.method === "PUT" && segs[0] === "llm-configs" && segs.length === 2 && segs[1] != null) return this.replySaveLlmConfig(segs[1], req);
1068
+ if (req.method === "DELETE" && segs[0] === "llm-configs" && segs.length === 2 && segs[1] != null) return this.replyDeleteLlmConfig(segs[1]);
686
1069
  return json(404, {
687
1070
  error: `no route: ${req.method} ${path}`,
688
1071
  usage: USAGE
@@ -823,14 +1206,51 @@ var ServeApp = class {
823
1206
  host: mod.dw.host.data.id,
824
1207
  drafts: this.draftsFor(mod),
825
1208
  routes: this.draftsFor(mod).map((d) => `POST /generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`),
826
- vars
1209
+ vars,
1210
+ previews: Object.keys(mod.dw.spec.previews ?? {}),
1211
+ tags: this.tagsByModule.get(mod.key) ?? mod.dw.spec.tags ?? []
827
1212
  };
828
1213
  }
829
- replyIndex() {
1214
+ async tagsFor(mod) {
1215
+ const known = this.tagsByModule.get(mod.key);
1216
+ if (known != null) return known;
1217
+ const extra = mod.dw.spec.tags ?? [];
1218
+ const varKinds = mod.dw.entries().map(([, varDef]) => varDef.kind);
1219
+ let tags;
1220
+ try {
1221
+ tags = workflowTags({
1222
+ nodes: (await mod.dw.build({ dry: true })).nodes.map((n) => ({
1223
+ id: n.uid,
1224
+ classType: n.json.class_type,
1225
+ outputNode: n.$schema.raw.output_node,
1226
+ outputTypes: n.$schema.outputs.map((o) => o.typeName),
1227
+ links: Object.values(n.json.inputs).flatMap((v) => Array.isArray(v) && v.length === 2 && typeof v[1] === "number" ? [[String(v[0]), v[1]]] : [])
1228
+ })),
1229
+ varKinds,
1230
+ extra
1231
+ });
1232
+ } catch (e) {
1233
+ console.error(`[serve] 🔴 tags for ${mod.key}: dry build failed, spec tags only: ${extractErrorMessage(e)}`);
1234
+ tags = workflowTags({
1235
+ nodes: [],
1236
+ varKinds,
1237
+ extra
1238
+ });
1239
+ }
1240
+ this.tagsByModule.set(mod.key, tags);
1241
+ return tags;
1242
+ }
1243
+ async replyIndex() {
1244
+ for (const m of this.modules) await this.tagsFor(m);
830
1245
  return json(200, {
831
1246
  server: "comfy-ts serve",
832
1247
  usage: USAGE,
833
1248
  workflows: this.modules.map((m) => this.describeModule(m)),
1249
+ ...this.opts.workspace == null ? {} : workspaceLabels({
1250
+ workspace: this.opts.workspace,
1251
+ root: this.opts.root ?? this.opts.workspace,
1252
+ home: process.env.HOME ?? ""
1253
+ }),
834
1254
  ...this.opts.loadErrors != null && Object.keys(this.opts.loadErrors).length > 0 ? { loadErrors: this.opts.loadErrors } : {}
835
1255
  });
836
1256
  }
@@ -844,6 +1264,31 @@ var ServeApp = class {
844
1264
  values: this.draftValues(mod, draft)
845
1265
  });
846
1266
  }
1267
+ /** the workflow's previews for the values the panel holds right now. The vars are SHARED
1268
+ * state (a run reads them), so this runs under the module lock: load the values, compute,
1269
+ * put the old values back. Nothing is queued, nothing is written */
1270
+ async replyPreview(key, req) {
1271
+ const mod = this.moduleByKey(key);
1272
+ if (mod == null) return json(404, { error: `unknown workflow '${key}'` });
1273
+ let values;
1274
+ try {
1275
+ values = JSON.parse(req.body ?? "{}");
1276
+ } catch (e) {
1277
+ return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
1278
+ }
1279
+ if (values == null || typeof values !== "object" || Array.isArray(values)) return json(400, { error: "expects { \"<var>\": value, … }" });
1280
+ const incoming = values;
1281
+ return json(200, { previews: await this.exclusive(mod.key, () => {
1282
+ const saved = mod.dw.entries().map(([k, v]) => [k, v.toJSON()]);
1283
+ try {
1284
+ for (const [k, v] of mod.dw.entries()) if (k in incoming) v.loadJSON(incoming[k]);
1285
+ return Promise.resolve(mod.dw.computePreviews());
1286
+ } finally {
1287
+ const byName = new Map(mod.dw.entries());
1288
+ for (const [k, json] of saved) byName.get(k)?.loadJSON(json);
1289
+ }
1290
+ }) });
1291
+ }
847
1292
  /** stored values (toJSON shapes); 'default' without a file falls back to descriptor defaults */
848
1293
  draftValues(mod, draft) {
849
1294
  const path = this.draftPath(mod, draft);
@@ -864,8 +1309,7 @@ var ServeApp = class {
864
1309
  }
865
1310
  async replyWebJs() {
866
1311
  if (this.opts.webJs == null) return json(404, { error: "web ui not enabled on this server" });
867
- this.webJsCache ??= this.opts.webJs();
868
- const js = await this.webJsCache;
1312
+ const js = await this.opts.webJs();
869
1313
  if (js == null) return json(404, { error: "web ui bundle unavailable — see the server log" });
870
1314
  return {
871
1315
  status: 200,
@@ -911,7 +1355,11 @@ var ServeApp = class {
911
1355
  if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be a json object: { \"<var>\": value, … }" });
912
1356
  const values = parsed;
913
1357
  const known = new Set(mod.dw.entries().map(([k]) => k));
914
- const unknown = Object.keys(values).filter((k) => !known.has(k));
1358
+ if ("$enhance" in values) {
1359
+ const raw = values[ENHANCE_KEY];
1360
+ if (!(raw != null && typeof raw === "object" && !Array.isArray(raw) && Object.values(raw).every((v) => typeof v === "string"))) return json(400, { error: `${ENHANCE_KEY} must be { "<prompt var>": "<intent>" }` });
1361
+ }
1362
+ const unknown = Object.keys(values).filter((k) => !known.has(k) && !isDraftMetaKey(k));
915
1363
  if (unknown.length > 0) return json(400, { error: `unknown var(s) ${unknown.join(", ")} — vars: ${[...known].join(", ")}` });
916
1364
  const path = bang(this.draftPath(mod, draft), "draft name validated just above");
917
1365
  await this.exclusive(mod.key, () => {
@@ -996,6 +1444,8 @@ var ServeApp = class {
996
1444
  if (action === "refresh-loras") return await this.refreshLoraMirror(hostId, host);
997
1445
  if (action === "refresh-schema") {
998
1446
  await host.fetchAndUpdateSchema();
1447
+ const unmirrored = lorasMissingFromMirror(host.schema.getLoras(), (n) => getLoraInfo(n, hostId) != null);
1448
+ const lorasNote = (await this.refreshLoraMirror(hostId, host)).status === 200 ? unmirrored.length > 0 ? `, lora list re-read (${unmirrored.length} new)` : ", lora list re-read" : ", the lora manager list could not be re-read";
999
1449
  const rebound = await this.rebindHostVars(hostId, host);
1000
1450
  const nodes = host.schema.nodes.length;
1001
1451
  const loras = host.schema.getLoras().length;
@@ -1005,7 +1455,7 @@ var ServeApp = class {
1005
1455
  host: hostId,
1006
1456
  action,
1007
1457
  stale: rebound.stale,
1008
- note: `schema refetched: ${nodes} node types, ${loras} loras, ${rebound.widened} lora var(s) changed${dropped}. no restart needed`
1458
+ note: `schema refetched: ${nodes} node types, ${loras} loras, ${rebound.widened} lora var(s) changed${dropped}${lorasNote}`
1009
1459
  });
1010
1460
  }
1011
1461
  if (action === "restart") {
@@ -1253,7 +1703,7 @@ var ServeApp = class {
1253
1703
  }
1254
1704
  replyMemoryImage(key) {
1255
1705
  const hit = this.memoryImages.get(key);
1256
- if (hit == null) return json(404, { error: `no in-memory image '${key}' — it expired (only the last ${this.MEMORY_IMAGE_CAP} are kept) or the server restarted. Turn saving on to keep outputs.` });
1706
+ if (hit == null) return json(404, { error: `no in-memory output '${key}' — it expired (only the last ${this.MEMORY_IMAGE_CAP} are kept) or the server restarted. Turn saving on to keep outputs.` });
1257
1707
  return {
1258
1708
  status: 200,
1259
1709
  contentType: hit.contentType,
@@ -1317,7 +1767,68 @@ var ServeApp = class {
1317
1767
  effectivePrefix: Object.fromEntries(this.modules.map((m) => [m.key, this.savePrefixFor(m.key)]))
1318
1768
  });
1319
1769
  }
1320
- /** the folder is seeded on the first read, so `refine-krea2-prompt.md` exists to be edited */
1770
+ tabsFile() {
1771
+ return join(comfyts.baseFolder, SERVE_TABS_FILE);
1772
+ }
1773
+ /** only drafts that still exist: a tab whose file was deleted elsewhere is dropped on read */
1774
+ liveTabs(raw) {
1775
+ return readTabs(raw, this.modules.map((m) => ({
1776
+ module: m.key,
1777
+ drafts: this.draftsFor(m)
1778
+ })));
1779
+ }
1780
+ replyTabs() {
1781
+ if (this.tabs == null) {
1782
+ const path = this.tabsFile();
1783
+ let raw = [];
1784
+ try {
1785
+ if (existsSync(path)) raw = JSON.parse(readFileSync(path, "utf8"));
1786
+ } catch (e) {
1787
+ console.error(`[serve] 🔴 open tabs unreadable (${path}), starting with none:`, e);
1788
+ }
1789
+ this.tabs = this.liveTabs(raw);
1790
+ }
1791
+ this.tabs = this.liveTabs(this.tabs);
1792
+ return json(200, { tabs: this.tabs });
1793
+ }
1794
+ replySaveTabs(req) {
1795
+ let parsed;
1796
+ try {
1797
+ parsed = JSON.parse(req.body ?? "");
1798
+ } catch (e) {
1799
+ return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
1800
+ }
1801
+ const raw = parsed != null && typeof parsed === "object" ? parsed.tabs : void 0;
1802
+ if (!Array.isArray(raw) || raw.length > 100) return json(400, { error: "expects { \"tabs\": [{ \"module\", \"draft\" }, …] }" });
1803
+ this.tabs = this.liveTabs(raw);
1804
+ try {
1805
+ mkdirSync(comfyts.baseFolder, { recursive: true });
1806
+ writeFileSync(this.tabsFile(), JSON.stringify(this.tabs, null, 2));
1807
+ } catch (e) {
1808
+ console.error(`[serve] 🔴 open tabs not saved to ${this.tabsFile()}:`, e);
1809
+ return json(200, {
1810
+ tabs: this.tabs,
1811
+ warning: `not saved: ${extractErrorMessage(e)}`
1812
+ });
1813
+ }
1814
+ return json(200, { tabs: this.tabs });
1815
+ }
1816
+ async replyTags(modKey, varName, url) {
1817
+ const mod = this.moduleByKey(modKey);
1818
+ if (mod == null) return json(404, { error: `unknown workflow '${modKey}'` });
1819
+ const found = mod.dw.entries().find(([k]) => k === varName)?.[1];
1820
+ if (found == null) return json(404, { error: `workflow '${modKey}' has no var '${varName}'` });
1821
+ const tags = found.kind === "prompt" ? found.tags : null;
1822
+ if (tags == null) return json(404, { error: `var '${varName}' declares no tag list (v.prompt(…, { tags }))` });
1823
+ const params = new URLSearchParams(url.split("?")[1] ?? "");
1824
+ const limit = Math.min(100, Math.max(1, Number(params.get("limit") ?? "20") || 20));
1825
+ try {
1826
+ return json(200, { hits: (await this.tagSources.load(resolveTagSource(tags.url, mod.file))).search(params.get("q") ?? "", limit) });
1827
+ } catch (e) {
1828
+ console.error(`[serve] 🔴 tag list for ${modKey}/${varName}: ${extractErrorMessage(e)}`);
1829
+ return json(502, { error: extractErrorMessage(e) });
1830
+ }
1831
+ }
1321
1832
  replyPromptEnhancers() {
1322
1833
  try {
1323
1834
  return json(200, { enhancers: listPromptEnhancers() });
@@ -1363,6 +1874,49 @@ var ServeApp = class {
1363
1874
  enhancers: listPromptEnhancers()
1364
1875
  });
1365
1876
  }
1877
+ replyLlmConfigs() {
1878
+ try {
1879
+ return json(200, { configs: listLlmConfigs() });
1880
+ } catch (e) {
1881
+ return json(500, { error: `llm-configs folder unreadable: ${extractErrorMessage(e)}` });
1882
+ }
1883
+ }
1884
+ replySaveLlmConfig(rawName, req) {
1885
+ const name = validStoreName(rawName);
1886
+ if (name == null) return json(400, { error: `invalid config name '${rawName}' — letters/digits then letters, digits, ". -_"` });
1887
+ let parsed;
1888
+ try {
1889
+ parsed = JSON.parse(req.body ?? "");
1890
+ } catch (e) {
1891
+ return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
1892
+ }
1893
+ if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be { provider, baseUrl, model, effort, thinkingOnly }" });
1894
+ try {
1895
+ writeLlmConfig(name, normalizeLlmConfig(parsed));
1896
+ } catch (e) {
1897
+ return json(500, { error: `could not write llm config '${name}': ${extractErrorMessage(e)}` });
1898
+ }
1899
+ return json(200, {
1900
+ ok: true,
1901
+ name,
1902
+ configs: listLlmConfigs()
1903
+ });
1904
+ }
1905
+ replyDeleteLlmConfig(rawName) {
1906
+ const name = validStoreName(rawName);
1907
+ if (name == null) return json(400, { error: `invalid config name '${rawName}'` });
1908
+ try {
1909
+ deleteLlmConfig(name);
1910
+ } catch (e) {
1911
+ return json(500, { error: `could not delete llm config '${name}': ${extractErrorMessage(e)}` });
1912
+ }
1913
+ console.log(`[serve] llm config deleted: ${name}`);
1914
+ return json(200, {
1915
+ ok: true,
1916
+ name,
1917
+ configs: listLlmConfigs()
1918
+ });
1919
+ }
1366
1920
  runningModules() {
1367
1921
  return [...this.liveRuns.entries()].filter(([, e]) => e.status !== "Success" && e.status !== "Failure").map(([key]) => key);
1368
1922
  }
@@ -1545,6 +2099,8 @@ var ServeApp = class {
1545
2099
  });
1546
2100
  }
1547
2101
  const produced = [`${execution.images.length} image(s)`];
2102
+ const audios = execution.audios ?? [];
2103
+ if (audios.length > 0) produced.push(`${audios.length} audio(s)`);
1548
2104
  if ((execution.texts ?? []).length > 0) produced.push(`${(execution.texts ?? []).length} text(s)`);
1549
2105
  console.log(`[serve] 🟢 ${mod.key}/${draft} done in ${(durationMs / 1e3).toFixed(1)}s · ${produced.join(" · ")}`);
1550
2106
  const memoryKeys = /* @__PURE__ */ new Map();
@@ -1554,6 +2110,13 @@ var ServeApp = class {
1554
2110
  this.rememberMemoryImage(key, img.buffer, img.filename);
1555
2111
  memoryKeys.set(ix, key);
1556
2112
  }
2113
+ const audioKeys = /* @__PURE__ */ new Map();
2114
+ for (const [ix, a] of audios.entries()) {
2115
+ if (a.absPath != null) continue;
2116
+ const key = `${execution.data.id}/${ix}`;
2117
+ this.rememberMemoryImage(`audio/${key}`, a.bytes, a.filename);
2118
+ audioKeys.set(ix, key);
2119
+ }
1557
2120
  const first = execution.images[0];
1558
2121
  if (req.accept?.includes("image/") && first != null) {
1559
2122
  if (first.absPath != null) return {
@@ -1584,6 +2147,12 @@ var ServeApp = class {
1584
2147
  filename: img.filename,
1585
2148
  url: img.absPath != null ? this.outputUrl(img.absPath) : memoryKeys.has(ix) ? `/images/${(memoryKeys.get(ix) ?? "").split("/").map((seg) => encodeURIComponent(seg)).join("/")}` : null,
1586
2149
  absPath: img.absPath
2150
+ })),
2151
+ audios: audios.map((a, ix) => ({
2152
+ filename: a.filename,
2153
+ mime: a.mime,
2154
+ url: a.absPath != null ? this.outputUrl(a.absPath) : audioKeys.has(ix) ? `/audio/${(audioKeys.get(ix) ?? "").split("/").map((seg) => encodeURIComponent(seg)).join("/")}` : null,
2155
+ absPath: a.absPath
1587
2156
  }))
1588
2157
  });
1589
2158
  }
@@ -1661,17 +2230,21 @@ var ServeApp = class {
1661
2230
  const seedVar = varDef;
1662
2231
  const stateKey = `${mod.key}/${draft}/${k}`;
1663
2232
  const draftValue = draftSeedValues.get(k) ?? seedVar.value;
1664
- if (!(k in payload)) {
1665
- if (seedVar.mode === "?") seedVar.randomize();
1666
- else if (seedVar.mode === "+" || seedVar.mode === "-") {
1667
- const prev = this.seedState.get(stateKey);
1668
- const ours = prev != null && (prev.draftBase === draftValue || prev.last === draftValue);
1669
- if (prev != null && ours) seedVar.set(prev.last + (seedVar.mode === "+" ? 1 : -1));
1670
- }
1671
- }
1672
- this.seedState.set(stateKey, {
2233
+ const prev = this.seedState.get(stateKey);
2234
+ const continues = !(k in payload) && (seedVar.mode === "+" || seedVar.mode === "-") && prev != null && (prev.draftBase === draftValue || prev.served.includes(draftValue));
2235
+ if (!(k in payload) && seedVar.mode === "?") seedVar.randomize();
2236
+ if (continues) {
2237
+ seedVar.set(prev.last + (seedVar.mode === "+" ? 1 : -1));
2238
+ const served = [...prev.served, seedVar.value].slice(-256);
2239
+ this.seedState.set(stateKey, {
2240
+ last: seedVar.value,
2241
+ draftBase: prev.draftBase,
2242
+ served
2243
+ });
2244
+ } else this.seedState.set(stateKey, {
1673
2245
  last: seedVar.value,
1674
- draftBase: draftValue
2246
+ draftBase: draftValue,
2247
+ served: [seedVar.value]
1675
2248
  });
1676
2249
  seeds[k] = seedVar.value;
1677
2250
  }
@@ -1734,6 +2307,68 @@ var ServeApp = class {
1734
2307
  }
1735
2308
  };
1736
2309
  //#endregion
2310
+ //#region src/cli/serve/byteRange.ts
2311
+ /** one range, the only kind media players send: `bytes=a-b`, `bytes=a-`, `bytes=-n` */
2312
+ function parseRange(header, size) {
2313
+ const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
2314
+ if (m == null) return null;
2315
+ const a = m[1] ?? "";
2316
+ const b = m[2] ?? "";
2317
+ if (a === "" && b === "") return null;
2318
+ if (a === "") {
2319
+ const n = Number(b);
2320
+ if (n === 0) return "unsatisfiable";
2321
+ return {
2322
+ start: Math.max(0, size - n),
2323
+ end: size - 1
2324
+ };
2325
+ }
2326
+ const start = Number(a);
2327
+ const end = b === "" ? size - 1 : Math.min(Number(b), size - 1);
2328
+ if (start >= size || start > end) return "unsatisfiable";
2329
+ return {
2330
+ start,
2331
+ end
2332
+ };
2333
+ }
2334
+ /** a whole 200 binary reply gets its length and `accept-ranges`; a range request gets 206 with
2335
+ * those bytes, or 416 past the end. Text replies and errors pass through untouched */
2336
+ function withByteRange(reply, req) {
2337
+ if (req.method !== "GET" || reply.status !== 200 || typeof reply.body === "string") return reply;
2338
+ const size = reply.body.length;
2339
+ const base = {
2340
+ ...reply.headers,
2341
+ "accept-ranges": "bytes"
2342
+ };
2343
+ const range = req.range == null ? null : parseRange(req.range, size);
2344
+ if (range == null) return {
2345
+ ...reply,
2346
+ headers: {
2347
+ ...base,
2348
+ "content-length": String(size)
2349
+ }
2350
+ };
2351
+ if (range === "unsatisfiable") return {
2352
+ status: 416,
2353
+ contentType: reply.contentType,
2354
+ body: /* @__PURE__ */ new Uint8Array(0),
2355
+ headers: {
2356
+ ...base,
2357
+ "content-range": `bytes */${size}`
2358
+ }
2359
+ };
2360
+ return {
2361
+ status: 206,
2362
+ contentType: reply.contentType,
2363
+ body: reply.body.subarray(range.start, range.end + 1),
2364
+ headers: {
2365
+ ...base,
2366
+ "content-range": `bytes ${range.start}-${range.end}/${size}`,
2367
+ "content-length": String(range.end - range.start + 1)
2368
+ }
2369
+ };
2370
+ }
2371
+ //#endregion
1737
2372
  //#region src/cli/serve/startupPrint.ts
1738
2373
  const RULE_WIDTH = 64;
1739
2374
  /** 100.64.0.0/10 is the CGNAT range tailscale hands out — worth naming, it is the one
@@ -1837,11 +2472,40 @@ async function buildWebJsText(pkgRoot) {
1837
2472
  if (!result.success || result.outputs[0] == null) throw new Error(`web ui bundle failed:\n${result.logs.map((l) => String(l)).join("\n")}`);
1838
2473
  return await result.outputs[0].text();
1839
2474
  }
1840
- /** the runtime resolution chain; every miss logs loud and degrades to api-only */
2475
+ /** changes whenever a file under `dir` is added, removed or rewritten. The web bundle reaches
2476
+ * outside web/ (vars, protocol types), so the whole src/ tree is the input: ~300 stats, a few ms */
2477
+ function sourceSignature(dir) {
2478
+ let count = 0;
2479
+ let newest = 0;
2480
+ let bytes = 0;
2481
+ const walk = (d) => {
2482
+ for (const entry of readdirSync(d, { withFileTypes: true })) {
2483
+ const abs = join(d, entry.name);
2484
+ if (entry.isDirectory()) walk(abs);
2485
+ else if (entry.isFile()) {
2486
+ const st = statSync(abs);
2487
+ count += 1;
2488
+ bytes += st.size;
2489
+ newest = Math.max(newest, st.mtimeMs);
2490
+ }
2491
+ }
2492
+ };
2493
+ walk(dir);
2494
+ return `${count}:${bytes}:${newest}`;
2495
+ }
2496
+ let prebuiltJs = null;
2497
+ let fromSource = null;
2498
+ /** the runtime resolution chain; every miss logs loud and degrades to api-only. Called on every
2499
+ * page load: a prebuilt file is read once, a source build is redone only when src/ changed, so
2500
+ * an edited panel shows on refresh under `bun --watch`, which never sees the bundled files */
1841
2501
  async function loadOrBuildWebJs() {
1842
2502
  const here = dirname(fileURLToPath(import.meta.url));
1843
2503
  const prebuilt = join(here, "serve-web.js");
1844
- if (existsSync(prebuilt)) return readFileSync(prebuilt, "utf8");
2504
+ if (prebuiltJs != null) return prebuiltJs;
2505
+ if (existsSync(prebuilt)) {
2506
+ prebuiltJs = readFileSync(prebuilt, "utf8");
2507
+ return prebuiltJs;
2508
+ }
1845
2509
  if (typeof Bun === "undefined") {
1846
2510
  console.error("[serve] 🔴 no serve-web.js next to the cli and not running under bun — api only, no web ui");
1847
2511
  return null;
@@ -1851,12 +2515,21 @@ async function loadOrBuildWebJs() {
1851
2515
  console.error(`[serve] 🔴 web ui source not found (looked for ${WEB_ENTRY} above ${here}) — api only, no web ui`);
1852
2516
  return null;
1853
2517
  }
1854
- try {
1855
- return await buildWebJsText(pkgRoot);
1856
- } catch (e) {
1857
- console.error("[serve] 🔴 web ui bundle failed — api only:", e);
1858
- return null;
2518
+ const signature = sourceSignature(join(pkgRoot, "src"));
2519
+ if (fromSource?.signature !== signature) {
2520
+ const rebuilt = fromSource != null;
2521
+ fromSource = {
2522
+ signature,
2523
+ js: buildWebJsText(pkgRoot).then((js) => {
2524
+ if (rebuilt) console.log("[serve] web ui rebuilt from source");
2525
+ return js;
2526
+ }, (e) => {
2527
+ console.error("[serve] 🔴 web ui bundle failed — api only until the next edit:", e);
2528
+ return null;
2529
+ })
2530
+ };
1859
2531
  }
2532
+ return await fromSource.js;
1860
2533
  }
1861
2534
  //#endregion
1862
2535
  //#region src/cli/serve/run-serve.ts
@@ -1929,7 +2602,12 @@ function makeRequestListener(app) {
1929
2602
  url: req.url ?? "/",
1930
2603
  accept: req.headers.accept,
1931
2604
  body: Buffer.concat(chunks).toString("utf8")
1932
- }).then((reply) => {
2605
+ }).then((whole) => {
2606
+ const range = req.headers.range;
2607
+ const reply = withByteRange(whole, {
2608
+ method: req.method ?? "GET",
2609
+ range
2610
+ });
1933
2611
  res.writeHead(reply.status, {
1934
2612
  "content-type": reply.contentType,
1935
2613
  ...reply.headers,
@@ -1984,7 +2662,9 @@ async function runServe(args) {
1984
2662
  }
1985
2663
  const app = new ServeApp(modules, {
1986
2664
  loadErrors,
1987
- webJs: loadOrBuildWebJs
2665
+ webJs: loadOrBuildWebJs,
2666
+ workspace: typeof comfyts === "undefined" ? process.cwd() : comfyts.rootPath,
2667
+ root: statSync(target).isDirectory() ? target : dirname(target)
1988
2668
  });
1989
2669
  printStartup(app, parsed.bind, parsed.port);
1990
2670
  const server = createServer(makeRequestListener(app));
@@ -2033,4 +2713,4 @@ function printStartup(app, bind, port) {
2033
2713
  //#endregion
2034
2714
  export { runServe };
2035
2715
 
2036
- //# sourceMappingURL=run-serve-BK7BA2dn.js.map
2716
+ //# sourceMappingURL=run-serve-DlRBv_Nk.js.map