comfy-ts 2.6.0 → 2.8.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 (101) hide show
  1. package/README.md +22 -13
  2. package/dist/{DefinedWorkflow-BJgt5t0x.js → DefinedWorkflow-BatWaZO1.js} +199 -16
  3. package/dist/DefinedWorkflow-BatWaZO1.js.map +1 -0
  4. package/dist/{DraftsSt-dizp3VcC.js → LogsSt-DFxzQfDc.js} +152 -4
  5. package/dist/LogsSt-DFxzQfDc.js.map +1 -0
  6. package/dist/cli.js +8 -6
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +288 -35
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +128 -7
  11. package/dist/index.d.ts +128 -7
  12. package/dist/index.js +286 -37
  13. package/dist/index.js.map +1 -1
  14. package/dist/run-serve-_nrvJYyt.js +1948 -0
  15. package/dist/run-serve-_nrvJYyt.js.map +1 -0
  16. package/dist/{run-tui-idFhdO4f.js → run-tui-BPw-SZYW.js} +107 -158
  17. package/dist/run-tui-BPw-SZYW.js.map +1 -0
  18. package/dist/serve-web.js +434 -81
  19. package/dist/{state-C90kdjtB.js → state-B-boDz-Z.js} +184 -45
  20. package/dist/state-B-boDz-Z.js.map +1 -0
  21. package/dist/web.d.ts +112 -7
  22. package/dist/web.js +239 -36
  23. package/dist/web.js.map +1 -1
  24. package/examples/README.md +1 -0
  25. package/examples/comfy-cloud/sdk.d.ts +4066 -321
  26. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +18 -2
  27. package/examples/rvion/07-local-llm-text-gen.cflow.ts +220 -0
  28. package/examples/web/tsconfig.json +7 -1
  29. package/extra/README.md +32 -0
  30. package/extra/comfyui-textgen-stream/README.md +35 -0
  31. package/extra/comfyui-textgen-stream/__init__.py +166 -0
  32. package/extra/scripts/fetch_text_encoder.py +137 -0
  33. package/package.json +6 -3
  34. package/src/cli/comfy-ts-cli.ts +4 -2
  35. package/src/cli/serve/ServeApp.ts +825 -43
  36. package/src/cli/serve/applyVarPayload.ts +10 -3
  37. package/src/cli/serve/describeVar.ts +47 -7
  38. package/src/cli/serve/managerOnlyLoras.ts +27 -0
  39. package/src/cli/serve/run-serve.ts +58 -29
  40. package/src/cli/serve/serveSettings.ts +86 -0
  41. package/src/cli/serve/startupPrint.ts +111 -0
  42. package/src/cli/serve/web/api.ts +120 -1
  43. package/src/cli/serve/web/components/App.tsx +61 -22
  44. package/src/cli/serve/web/components/Gallery.tsx +243 -30
  45. package/src/cli/serve/web/components/Icon.tsx +160 -0
  46. package/src/cli/serve/web/components/PromptEnhancer.tsx +85 -38
  47. package/src/cli/serve/web/components/Sidebar.tsx +43 -19
  48. package/src/cli/serve/web/components/VarsForm.tsx +440 -80
  49. package/src/cli/serve/web/components/controls/BasicControls.tsx +38 -5
  50. package/src/cli/serve/web/components/controls/ImageControl.tsx +3 -2
  51. package/src/cli/serve/web/components/controls/LorasControl.tsx +498 -81
  52. package/src/cli/serve/web/components/controls/PresetPicker.tsx +60 -0
  53. package/src/cli/serve/web/components/controls/SeedControl.tsx +38 -20
  54. package/src/cli/serve/web/components/controls/SizeControl.tsx +3 -2
  55. package/src/cli/serve/web/llm.ts +254 -0
  56. package/src/cli/serve/web/logWeb.ts +6 -0
  57. package/src/cli/serve/web/state/EnhancerSt.ts +261 -157
  58. package/src/cli/serve/web/state/FormSt.ts +70 -18
  59. package/src/cli/serve/web/state/RunSt.ts +22 -1
  60. package/src/cli/serve/web/state/WebSt.ts +542 -13
  61. package/src/cli/serve/web/state/lightbox.ts +44 -0
  62. package/src/cli/serve/web/state/moduleTree.ts +52 -0
  63. package/src/cli/serve/web/state/payload.ts +44 -2
  64. package/src/cli/serve/web/state/urlSelection.ts +53 -0
  65. package/src/cli/serve/web/styles.ts +415 -57
  66. package/src/cli/serve/web/tsconfig.json +4 -0
  67. package/src/cli/tui/components/PickerOverlays.tsx +37 -0
  68. package/src/cli/tui/components/StatusBar.tsx +14 -1
  69. package/src/cli/tui/components/TuiApp.tsx +5 -2
  70. package/src/cli/tui/state/HostSt.ts +3 -2
  71. package/src/cli/tui/state/PickerSt.ts +48 -2
  72. package/src/cli/tui/state/TreeSt.ts +1 -1
  73. package/src/cli/tui/state/TuiSt.ts +2 -1
  74. package/src/coreExports.ts +8 -1
  75. package/src/graph/ComfyNode.ts +58 -1
  76. package/src/host/ComfyHost.ts +13 -2
  77. package/src/host/ComfyManager.ts +31 -13
  78. package/src/host/loraInfoCache.ts +35 -1
  79. package/src/host/loraManagerApi.ts +94 -0
  80. package/src/index.ts +2 -0
  81. package/src/promptEnhancers.ts +102 -0
  82. package/src/runner/ComfyExecution.ts +61 -6
  83. package/src/runner/ComfyWorkflow.ts +18 -4
  84. package/src/runner/ComfyWsApi.ts +3 -0
  85. package/src/runner/describePromptRejection.ts +34 -0
  86. package/src/sdk-generator/ComfySchema.ts +17 -4
  87. package/src/sdk-generator/comfyui-sdk-codegen.ts +56 -2
  88. package/src/state.ts +6 -0
  89. package/src/utils/ansi.ts +13 -0
  90. package/src/utils/matchesRegex.ts +13 -0
  91. package/src/utils/safeName.ts +29 -0
  92. package/src/utils/stringMap.ts +9 -0
  93. package/src/vars/ComfyVars.ts +61 -10
  94. package/src/vars/presets.ts +17 -0
  95. package/dist/DefinedWorkflow-BJgt5t0x.js.map +0 -1
  96. package/dist/DraftsSt-dizp3VcC.js.map +0 -1
  97. package/dist/run-serve-CVu39RNd.js +0 -1002
  98. package/dist/run-serve-CVu39RNd.js.map +0 -1
  99. package/dist/run-tui-idFhdO4f.js.map +0 -1
  100. package/dist/state-C90kdjtB.js.map +0 -1
  101. package/src/cli/serve/web/openrouter.ts +0 -142
@@ -1,25 +1,104 @@
1
1
  // ROOT state tree of the serve web ui (app-state-tree doctrine: one root,
2
2
  // child stores hang off it, components read and call)
3
3
  import { makeAutoObservable, observableRef, observableShallow, runInAction } from 'mobx'
4
- import { fetchDraftValues, fetchIndex, saveDraft, type ModuleDescription } from 'src/cli/serve/web/api.ts'
4
+ import {
5
+ deleteDraft,
6
+ fetchDraftValues,
7
+ fetchHostLogs,
8
+ fetchHosts,
9
+ fetchIndex,
10
+ fetchSettings,
11
+ pingHost,
12
+ postHostAction,
13
+ saveDraft,
14
+ saveSettings,
15
+ setModuleHost,
16
+ type HostAction,
17
+ type HostsPayload,
18
+ type ModuleDescription,
19
+ type ServeSettings,
20
+ } from 'src/cli/serve/web/api.ts'
5
21
  import { EnhancerSt } from 'src/cli/serve/web/state/EnhancerSt.ts'
6
22
  import { FormSt } from 'src/cli/serve/web/state/FormSt.ts'
23
+ import { logWebError } from 'src/cli/serve/web/logWeb.ts'
24
+ import { asSeedForm } from 'src/cli/serve/web/state/payload.ts'
25
+ import { readUrlSelection, resolveSelection, writeUrlSelection } from 'src/cli/serve/web/state/urlSelection.ts'
7
26
  import { RunSt } from 'src/cli/serve/web/state/RunSt.ts'
8
27
 
9
- /** selection + drawer survive a reload (his standing default: hand-tuned state persists and restores) */
28
+ /** selection + drawer survive a reload: hand-tuned state persists and restores */
10
29
  const STORAGE_KEY = 'comfy-ts-serve-ui'
11
30
 
31
+ /** where the results live. every value is one of the buttons: a width rule would put the panel
32
+ * in a placement no button can show as selected, and a mode you cannot point at is not a mode.
33
+ * 'pinned' floats the newest image over the bottom, so a phone shows the knobs and what they
34
+ * produced without scrolling between them */
35
+ export type ResultsLayout = 'off' | 'bottom' | 'left' | 'side' | 'pinned'
36
+
37
+ /** results on the RIGHT: the wide-screen shape, and the one a first visit opens in */
38
+ export const DEFAULT_LAYOUT: ResultsLayout = 'side'
39
+
40
+ /** icon names live in Icon.tsx; this list stays a plain description of the modes */
41
+ export const LAYOUTS: {
42
+ id: ResultsLayout
43
+ icon: 'panel-off' | 'panel-bottom' | 'panel-left' | 'panel-side' | 'panel-corner'
44
+ title: string
45
+ }[] = [
46
+ { id: 'off', icon: 'panel-off', title: 'no preview: the form only' },
47
+ { id: 'bottom', icon: 'panel-bottom', title: 'results below the form' },
48
+ { id: 'left', icon: 'panel-left', title: 'results left of the form' },
49
+ { id: 'side', icon: 'panel-side', title: 'results right of the form' },
50
+ { id: 'pinned', icon: 'panel-corner', title: 'newest image in the bottom right corner, form scrolls under it' },
51
+ ]
52
+
53
+ function isLayout(raw: unknown): raw is ResultsLayout {
54
+ return raw === 'off' || raw === 'bottom' || raw === 'left' || raw === 'side' || raw === 'pinned'
55
+ }
56
+
12
57
  type StoredSelection = {
13
58
  module?: string
14
59
  draft?: string
15
60
  sidebar?: boolean
16
61
  loraImages?: boolean
17
62
  loraTitles?: boolean
63
+ /** lora previews fill their card (cover) instead of fitting inside it (contain) */
64
+ loraFill?: boolean
65
+ /** how many lora cards the popup draws before it stops */
66
+ loraCap?: number
67
+ /** the one-shot 60 → 200 default bump already happened for this browser */
68
+ loraCapMigrated?: boolean
69
+ layout?: string
70
+ latent?: boolean
71
+ logs?: boolean
72
+ /** module key → the var names in the order you dragged them into */
73
+ varOrder?: Record<string, string[]>
74
+ }
75
+
76
+ /** varOrder is the one stored field a reader INDEXES rather than merely reads, so a blob of
77
+ * the wrong shape (hand-edited, or written by an older version) crashed the whole panel to a
78
+ * blank page inside render. Every entry is shape-checked here, once */
79
+ export const DEFAULT_LORA_CAP = 200
80
+ /** the previous default, persisted whether or not anyone chose it: a stored 60 cannot be told
81
+ * apart from a deliberate one, so it is read as unset once (see loraCapMigrated) */
82
+ const LEGACY_LORA_CAP = 60
83
+ /** an upper bound, not a policy: 2000 cards is 2000 image requests, and a number typed by
84
+ * hand (or restored from an older blob) must not be able to hang the page */
85
+ export function clampLoraCap(raw: unknown): number {
86
+ const n = typeof raw === 'number' && Number.isFinite(raw) ? Math.floor(raw) : DEFAULT_LORA_CAP
87
+ return Math.min(2000, Math.max(1, n))
88
+ }
89
+
90
+ function readVarOrder(raw: unknown): Record<string, string[]> {
91
+ if (raw == null || typeof raw !== 'object' || Array.isArray(raw)) return {}
92
+ const out: Record<string, string[]> = {}
93
+ for (const [k, v] of Object.entries(raw as Record<string, unknown>))
94
+ if (Array.isArray(v)) out[k] = v.filter((n): n is string => typeof n === 'string')
95
+ return out
18
96
  }
19
97
 
20
98
  function readStoredSelection(): StoredSelection {
21
99
  try {
22
- return (JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}') ?? {}) as StoredSelection
100
+ const raw = (JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}') ?? {}) as StoredSelection
101
+ return { ...raw, varOrder: readVarOrder(raw.varOrder) }
23
102
  } catch {
24
103
  return {}
25
104
  }
@@ -42,22 +121,84 @@ export class WebSt {
42
121
  /** lora image/title visibility, EVERY lora surface (row cards + popup) — the hide toggles are NSFW screens */
43
122
  showLoraImages: boolean
44
123
  showLoraTitles: boolean
124
+ /** cover vs contain for every lora preview: art crops well, a character sheet does not */
125
+ loraFill: boolean
126
+ /** how many lora cards the popup draws. A cap exists because each card is an image
127
+ * request; how many is a MACHINE question (your box, your collection), so it is yours */
128
+ loraCap: number
45
129
  run: RunSt
46
130
  /** prompt refiner: own store, own localStorage blob (the openrouter key never leaves the browser) */
47
131
  enhancer: EnhancerSt
132
+ /** SERVER settings, not browser ones: they decide whether a generation writes files at all
133
+ * and where, so they are shared by every client and read back from GET /settings */
134
+ settings: ServeSettings = { saveToDisk: true, hostOverride: {}, savePrefix: {}, effectivePrefix: {} }
135
+ savingError: string | null = null
136
+ /** what you are typing in a prefix field, before the debounced write lands */
137
+ private prefixEdits: Record<string, string> = {}
138
+ private prefixTimers = new Map<string, ReturnType<typeof setTimeout>>()
139
+
140
+ get saveToDisk(): boolean {
141
+ return this.settings.saveToDisk
142
+ }
143
+ /** where the results go — hand-tuned, so it persists and restores */
144
+ layout: ResultsLayout
145
+ /** var row order per module. A UI preference, so it lives in the browser blob: the draft
146
+ * file is the var VALUES contract shared with the TUI, and a layout key there would have to
147
+ * be filtered out by every reader of it */
148
+ varOrder: Record<string, string[]> = {}
149
+
150
+ /** the form's vars in YOUR order, with anything unknown (a new var) kept at the end */
151
+ orderedVars(moduleKey: string, names: readonly string[]): string[] {
152
+ const wanted = this.varOrder[moduleKey]
153
+ if (wanted == null) return [...names]
154
+ const known = new Set(names)
155
+ const ordered = wanted.filter((n) => known.has(n))
156
+ return [...ordered, ...names.filter((n) => !ordered.includes(n))]
157
+ }
158
+
159
+ moveVar(p: { module: string; names: readonly string[]; from: number; to: number }): void {
160
+ const order = this.orderedVars(p.module, p.names)
161
+ const [moved] = order.splice(p.from, 1)
162
+ if (moved == null) return
163
+ order.splice(p.to, 0, moved)
164
+ this.varOrder = { ...this.varOrder, [p.module]: order }
165
+ this.persist()
166
+ }
167
+
168
+ /** hosts this process knows + where each module runs (server-owned, like the drafts) */
169
+ hosts: HostsPayload = { hosts: [], defaults: {}, overrides: {} }
170
+ hostError: string | null = null
48
171
 
49
172
  constructor() {
50
173
  this.run = new RunSt()
174
+ // a finished run reports the seed it used; the form shows it, and the autosave carries it
175
+ // into the draft, which is also what the server continues from, so `+` keeps stepping
176
+ this.run.onSeeds = (p): void => this.applyRunSeeds(p)
51
177
  this.enhancer = new EnhancerSt()
52
178
  const stored = readStoredSelection()
53
- this.sidebarOpen = stored.sidebar ?? !isNarrowScreen()
179
+ // a stored 'auto' from before the mode was removed resolves to what it MEANT on a
180
+ // wide screen, which is where it spent most of its life
181
+ this.layout = isLayout(stored.layout) ? stored.layout : DEFAULT_LAYOUT
182
+ // CLOSED by default, on every width: the panel is a form, and a workflow tree taking a
183
+ // column of it before you have asked for one is chrome. It reopens from the workflow box
184
+ this.sidebarOpen = stored.sidebar ?? false
54
185
  this.showLoraImages = stored.loraImages ?? true
55
186
  this.showLoraTitles = stored.loraTitles ?? true
187
+ this.loraFill = stored.loraFill ?? true
188
+ // marked in the blob, so the bump happens once and a deliberate 60 sticks after it
189
+ this.loraCap = clampLoraCap(
190
+ stored.loraCapMigrated !== true && stored.loraCap === LEGACY_LORA_CAP ? DEFAULT_LORA_CAP : stored.loraCap,
191
+ )
192
+ this.showLatent = stored.latent ?? true
193
+ this.varOrder = stored.varOrder ?? {}
194
+ this.showLogs = stored.logs ?? false
56
195
  makeAutoObservable(this, { run: false, enhancer: false, form: observableRef, modules: observableShallow })
57
196
  // a closing/hidden tab must not lose an edit still inside the autosave debounce
58
197
  window.addEventListener('beforeunload', () => this.form?.flushKeepalive())
59
198
  document.addEventListener('visibilitychange', () => {
60
- if (document.visibilityState === 'hidden') this.form?.flushKeepalive()
199
+ // hiding a tab is not closing it: the ordinary chained save keeps writes in order.
200
+ // keepalive is unchained by necessity and could land before an older one
201
+ if (document.visibilityState === 'hidden') void this.form?.save()
61
202
  })
62
203
  void this.boot()
63
204
  }
@@ -77,6 +218,55 @@ export class WebSt {
77
218
  this.persist()
78
219
  }
79
220
 
221
+ toggleLoraFill(): void {
222
+ this.loraFill = !this.loraFill
223
+ this.persist()
224
+ }
225
+
226
+ setLoraCap(next: number): void {
227
+ this.loraCap = clampLoraCap(next)
228
+ this.persist()
229
+ }
230
+
231
+ /** put the seeds a run used back on the form, VALUE only: the mode is the draft's policy and
232
+ * a run never changes it. Writing the USED value (not the next one) is deliberate, the
233
+ * server restarts its continuation from the draft, so writing the next value would skip one */
234
+ private applyRunSeeds(p: { module: string; draft: string; seeds: Record<string, number> }): void {
235
+ const form = this.form
236
+ // the run that finished, not whatever is on screen now: a queued run resolving after you
237
+ // browsed away wrote its seed into ANOTHER draft, and the autosave put it on disk
238
+ if (form == null || form.moduleKey !== p.module || form.draft !== p.draft) return
239
+ runInAction(() => {
240
+ for (const varSt of form.vars) {
241
+ if (varSt.desc.kind !== 'seed') continue
242
+ const used = p.seeds[varSt.name]
243
+ if (typeof used !== 'number' || !Number.isFinite(used)) continue
244
+ const current = asSeedForm(varSt.value)
245
+ if (current.value === used) continue
246
+ varSt.setFromRun({ mode: current.mode, value: used })
247
+ }
248
+ })
249
+ }
250
+
251
+ /** the address bar follows the selection, so the url on screen is always the one to share.
252
+ * replaceState, not pushState: picking drafts is a browsing gesture here, and one history
253
+ * entry per click would make Back mean "undo the last twelve clicks" */
254
+ private syncUrl(): void {
255
+ const form = this.form
256
+ if (form == null) return
257
+ try {
258
+ const search = writeUrlSelection({
259
+ search: window.location.search,
260
+ module: form.moduleKey,
261
+ draft: form.draft,
262
+ })
263
+ window.history.replaceState(null, '', `${window.location.pathname}${search}${window.location.hash}`)
264
+ } catch (e) {
265
+ // a sandboxed frame can refuse history writes; the panel itself still works
266
+ logWebError('could not put the selection in the url', e)
267
+ }
268
+ }
269
+
80
270
  private persist(): void {
81
271
  try {
82
272
  // merge, never rebuild: toggling the sidebar before a draft loads must not
@@ -90,10 +280,17 @@ export class WebSt {
90
280
  sidebar: this.sidebarOpen,
91
281
  loraImages: this.showLoraImages,
92
282
  loraTitles: this.showLoraTitles,
283
+ loraFill: this.loraFill,
284
+ loraCap: this.loraCap,
285
+ loraCapMigrated: true,
286
+ layout: this.layout,
287
+ latent: this.showLatent,
288
+ logs: this.showLogs,
289
+ varOrder: this.varOrder,
93
290
  }),
94
291
  )
95
- } catch {
96
- // storage full/blocked: state just won't survive the reload
292
+ } catch (e) {
293
+ logWebError('ui state could not be stored (it will not survive a reload)', e)
97
294
  }
98
295
  }
99
296
 
@@ -109,11 +306,18 @@ export class WebSt {
109
306
  this.loadErrors = index.loadErrors ?? {}
110
307
  this.phase = 'ready'
111
308
  })
309
+ void this.loadSettings()
310
+ void this.loadHosts()
112
311
  const stored = readStoredSelection()
113
- const mod = (stored.module != null ? this.moduleByKey(stored.module) : null) ?? this.modules[0]
114
- if (mod == null) return
115
- const draft = stored.draft != null && mod.drafts.includes(stored.draft) ? stored.draft : 'default'
116
- await this.select({ module: mod.module, draft })
312
+ // the URL wins over the stored selection: a link someone sent is an instruction, the
313
+ // stored one is only a memory of this browser's last visit
314
+ const opening = resolveSelection({
315
+ url: readUrlSelection(window.location.search),
316
+ stored: { module: stored.module ?? null, draft: stored.draft ?? null },
317
+ modules: this.modules,
318
+ })
319
+ if (opening == null) return
320
+ await this.select(opening)
117
321
  } catch (e) {
118
322
  runInAction(() => {
119
323
  this.phase = 'error'
@@ -150,7 +354,16 @@ export class WebSt {
150
354
  const outgoing = this.form
151
355
  if (outgoing != null) {
152
356
  outgoing.dispose()
153
- await outgoing.save()
357
+ // OFF SCREEN before the round trip: its autosave reaction is already disposed, so
358
+ // leaving it rendered meant every keystroke during the fetch went nowhere, silently.
359
+ // app shows "loading draft…" while form is null
360
+ runInAction(() => {
361
+ this.form = null
362
+ })
363
+ if (!(await outgoing.save()))
364
+ runInAction(() => {
365
+ this.formError = `the previous draft could not be saved: ${outgoing.saveError ?? 'unknown error'}`
366
+ })
154
367
  }
155
368
  try {
156
369
  const reply = await fetchDraftValues(p)
@@ -158,10 +371,15 @@ export class WebSt {
158
371
  if (token !== this.selectToken) return
159
372
  this.form = new FormSt(p.module, p.draft, mod, reply.values ?? {})
160
373
  this.persist()
374
+ this.syncUrl()
161
375
  })
162
376
  } catch (e) {
163
377
  runInAction(() => {
164
378
  if (token !== this.selectToken) return
379
+ // the outgoing form was DISPOSED above: keeping it on screen leaves an editable
380
+ // form whose autosave reaction is dead, so edits silently stop persisting while
381
+ // the header still reads 'saved'. No form is honest, the error says what happened
382
+ this.form = null
165
383
  this.formError = e instanceof Error ? e.message : String(e)
166
384
  })
167
385
  } finally {
@@ -171,12 +389,271 @@ export class WebSt {
171
389
  }
172
390
  }
173
391
 
392
+ /** side and pinned show the results next to (or over) the form, so the run button belongs
393
+ * there: in pinned it stays on screen while the form scrolls */
394
+ get generateInResults(): boolean {
395
+ return this.layout === 'side' || this.layout === 'left' || this.layout === 'pinned'
396
+ }
397
+
398
+ setLayout(next: ResultsLayout): void {
399
+ // a click SETS the mode. cycling back to a width rule lands where no button is showing
400
+ this.layout = next
401
+ this.persist()
402
+ }
403
+
404
+ /** the host a module's runs go to right now (override if any, else the module's own) */
405
+ hostFor(moduleKey: string): string {
406
+ return this.hosts.overrides[moduleKey] ?? this.hosts.defaults[moduleKey] ?? ''
407
+ }
408
+
409
+ /** the host's OWN base url, for opening its pages (the lora manager lives there) */
410
+ hostUrlFor(moduleKey: string): string | null {
411
+ const id = this.hostFor(moduleKey)
412
+ return this.hosts.hosts.find((h) => h.id === id)?.httpUrl ?? null
413
+ }
414
+
415
+ isHostOverridden(moduleKey: string): boolean {
416
+ return this.hosts.overrides[moduleKey] != null
417
+ }
418
+
419
+ private async loadHosts(): Promise<void> {
420
+ try {
421
+ const hosts = await fetchHosts()
422
+ runInAction(() => {
423
+ this.hosts = hosts
424
+ })
425
+ } catch (e) {
426
+ // the process serving this page owns /hosts, so a failure here is a real one (500,
427
+ // transport) rather than an old server: never swallowed, or the host box silently
428
+ // shows the module default and every host action targets the wrong box
429
+ logWebError('could not read the host list', e)
430
+ }
431
+ }
432
+
433
+ /** the ComfyUI console, polled only while the logs panel is open (off by default: most of
434
+ * the time you do not care, and a closed panel must cost nothing) */
435
+ showLogs = false
436
+ logLines: string[] = []
437
+ logsError: string | null = null
438
+ hostNote: string | null = null
439
+ /** the latent frames during a run: on by default, off when you only want the final image */
440
+ showLatent = true
441
+ private logsTimer: ReturnType<typeof setInterval> | null = null
442
+
443
+ toggleLatent(): void {
444
+ this.showLatent = !this.showLatent
445
+ this.persist()
446
+ }
447
+
448
+ toggleLogs(): void {
449
+ this.showLogs = !this.showLogs
450
+ this.persist()
451
+ if (this.logsTimer != null) clearInterval(this.logsTimer)
452
+ this.logsTimer = null
453
+ if (!this.showLogs) return
454
+ void this.pullLogs()
455
+ this.logsTimer = setInterval(() => void this.pullLogs(), 3000)
456
+ }
457
+
458
+ private async pullLogs(): Promise<void> {
459
+ const host = this.form == null ? null : this.hostFor(this.form.moduleKey)
460
+ if (host == null || host === '') return
461
+ try {
462
+ const reply = await fetchHostLogs({ host })
463
+ runInAction(() => {
464
+ // already folded into lines server side, through the TUI's own assembly
465
+ this.logLines = reply.lines
466
+ this.logsError = null
467
+ })
468
+ } catch (e) {
469
+ runInAction(() => {
470
+ this.logsError = e instanceof Error ? e.message : String(e)
471
+ })
472
+ }
473
+ }
474
+
475
+ /** the lora mirror sweep, from the panel: the metadata (names, trigger words, previews) is
476
+ * re-downloaded and every surface re-reads it, which needs the descriptors reloaded too */
477
+ loraSyncing = false
478
+
479
+ async refreshLoras(): Promise<void> {
480
+ if (this.loraSyncing) return
481
+ runInAction(() => {
482
+ this.loraSyncing = true
483
+ })
484
+ await this.hostAction('refresh-loras')
485
+ // the option lists (and the manager-only union) live in the descriptors: re-read them,
486
+ // then re-select the same draft so the form is rebuilt against the new options
487
+ try {
488
+ const index = await fetchIndex()
489
+ const current = this.form
490
+ runInAction(() => {
491
+ this.modules = index.workflows
492
+ })
493
+ if (current != null) {
494
+ // flush and DISPOSE the outgoing form, in an action: dropping the reference alone
495
+ // leaked its autosave reaction and let it write the file the new form just read
496
+ current.dispose()
497
+ await current.save()
498
+ runInAction(() => {
499
+ this.form = null
500
+ })
501
+ await this.select({ module: current.moduleKey, draft: current.draft })
502
+ }
503
+ } catch (e) {
504
+ runInAction(() => {
505
+ this.hostError = e instanceof Error ? e.message : String(e)
506
+ })
507
+ } finally {
508
+ runInAction(() => {
509
+ this.loraSyncing = false
510
+ })
511
+ }
512
+ }
513
+
514
+ /** a restart takes the host down and back: this WATCHES it instead of leaving you guessing.
515
+ * polls until it answers, or gives up loudly after ~2 minutes */
516
+ hostWatch: 'idle' | 'down' | 'back' = 'idle'
517
+
518
+ private async watchHostComeBack(): Promise<void> {
519
+ const host = this.form == null ? null : this.hostFor(this.form.moduleKey)
520
+ if (host == null || host === '') return
521
+ runInAction(() => {
522
+ this.hostWatch = 'down'
523
+ })
524
+ const deadline = Date.now() + 120_000
525
+ for (;;) {
526
+ await new Promise((r) => setTimeout(r, 2500))
527
+ if (Date.now() > deadline) {
528
+ runInAction(() => {
529
+ this.hostWatch = 'idle'
530
+ this.hostError = `${host} has not answered for 2 minutes — check the console`
531
+ })
532
+ return
533
+ }
534
+ const up = await pingHost({ host })
535
+ .then((r) => r.up)
536
+ .catch(() => false)
537
+ if (!up) continue
538
+ runInAction(() => {
539
+ this.hostWatch = 'back'
540
+ this.hostNote = `${host} is back up`
541
+ })
542
+ setTimeout(() => runInAction(() => (this.hostWatch = 'idle')), 4000)
543
+ return
544
+ }
545
+ }
546
+
547
+ /** interrupt / clear the queue / reboot the box this workflow runs on */
548
+ async hostAction(action: HostAction): Promise<void> {
549
+ const host = this.form == null ? null : this.hostFor(this.form.moduleKey)
550
+ if (host == null || host === '') return
551
+ runInAction(() => {
552
+ this.hostError = null
553
+ this.hostNote = null
554
+ })
555
+ try {
556
+ const reply = await postHostAction({ host, action })
557
+ runInAction(() => {
558
+ this.hostNote = reply.note
559
+ })
560
+ // a reboot is the one action whose result arrives LATER: watch for it
561
+ if (action === 'restart') void this.watchHostComeBack()
562
+ } catch (e) {
563
+ runInAction(() => {
564
+ this.hostError = e instanceof Error ? e.message : String(e)
565
+ })
566
+ }
567
+ }
568
+
569
+ /** run this workflow somewhere else (the TUI's host override). null resets to its own host */
570
+ async setModuleHost(p: { module: string; host: string | null }): Promise<void> {
571
+ runInAction(() => {
572
+ this.hostError = null
573
+ })
574
+ try {
575
+ const reply = await setModuleHost(p)
576
+ runInAction(() => {
577
+ this.hosts = { ...this.hosts, overrides: reply.overrides }
578
+ })
579
+ } catch (e) {
580
+ runInAction(() => {
581
+ this.hostError = e instanceof Error ? e.message : String(e)
582
+ })
583
+ }
584
+ }
585
+
586
+ private async loadSettings(): Promise<void> {
587
+ try {
588
+ const s = await fetchSettings()
589
+ runInAction(() => {
590
+ this.settings = s
591
+ })
592
+ } catch (e) {
593
+ // same as the host list: this process owns /settings, so a failure is a real one and
594
+ // the panel would otherwise show the DEFAULT setting as if it were the server's
595
+ logWebError('could not read the serve settings', e)
596
+ }
597
+ }
598
+
599
+ /** what the prefix input shows: the typed value while editing, else the effective folder */
600
+ savePrefixDraft(moduleKey: string): string {
601
+ return this.prefixEdits[moduleKey] ?? this.settings.savePrefix[moduleKey] ?? ''
602
+ }
603
+
604
+ /** typing is local and instant; the write is debounced, the live-drafts idiom. An invalid
605
+ * folder is rejected by the server and shown, the field keeps what you typed */
606
+ setSavePrefix(moduleKey: string, value: string): void {
607
+ this.prefixEdits[moduleKey] = value
608
+ this.savingError = null
609
+ const timer = this.prefixTimers.get(moduleKey)
610
+ if (timer != null) clearTimeout(timer)
611
+ this.prefixTimers.set(
612
+ moduleKey,
613
+ setTimeout(() => {
614
+ void this.pushSettings({ savePrefix: { [moduleKey]: value } })
615
+ }, 500),
616
+ )
617
+ }
618
+
619
+ private async pushSettings(patch: { saveToDisk?: boolean; savePrefix?: Record<string, string> }): Promise<boolean> {
620
+ try {
621
+ const next = await saveSettings(patch)
622
+ runInAction(() => {
623
+ this.settings = next
624
+ this.savingError = null
625
+ })
626
+ return true
627
+ } catch (e) {
628
+ runInAction(() => {
629
+ this.savingError = e instanceof Error ? e.message : String(e)
630
+ })
631
+ return false
632
+ }
633
+ }
634
+
635
+ /** flip where outputs go. Optimistic, then reconciled with what the server confirms */
636
+ async toggleSaveToDisk(): Promise<void> {
637
+ const next = !this.saveToDisk
638
+ const before = this.settings
639
+ runInAction(() => {
640
+ this.settings = { ...this.settings, saveToDisk: next }
641
+ this.savingError = null
642
+ })
643
+ // pushSettings reports the failure; roll the optimistic flip back so the switch
644
+ // never shows a state the server refused
645
+ if (!(await this.pushSettings({ saveToDisk: next })))
646
+ runInAction(() => {
647
+ this.settings = before
648
+ })
649
+ }
650
+
174
651
  generate(): void {
175
652
  void this.generateNow()
176
653
  }
177
654
 
178
655
  /** flush the autosave first: the server reads the draft it just wrote — one source of truth.
179
- * Every click ENQUEUES, so hitting generate n times runs n prompts; the queued payload
656
+ * every click ENQUEUES, so hitting generate n times runs n prompts; the queued payload
180
657
  * freezes the values you saw, and seeds stay on the draft's server-side policy */
181
658
  private async generateNow(): Promise<void> {
182
659
  const form = this.form
@@ -188,6 +665,58 @@ export class WebSt {
188
665
  this.run.enqueue({ module: form.moduleKey, draft: form.draft, payload })
189
666
  }
190
667
 
668
+ /** rename = write the values under the new name, switch to it, then drop the old FILE.
669
+ * same shape as the enhancer presets: the name IS the identity, so there is nothing to
670
+ * "rename" server side. The old file is only removed once the new one is confirmed */
671
+ async renameDraft(rawName: string): Promise<void> {
672
+ const form = this.form
673
+ const name = rawName.trim()
674
+ if (form == null || name === '' || name === form.draft) return
675
+ const from = form.draft
676
+ await this.duplicateDraft(name)
677
+ // duplicateDraft reports its own failure; only drop the old file if the switch happened
678
+ if (this.form?.draft !== name) return
679
+ await deleteDraft({ module: form.moduleKey, draft: from }).then(
680
+ (reply) =>
681
+ runInAction(() => {
682
+ this.modules = this.modules.map((m) =>
683
+ m.module === form.moduleKey ? { ...m, drafts: reply.drafts } : m,
684
+ )
685
+ }),
686
+ (e: unknown) =>
687
+ runInAction(() => {
688
+ this.formError = `renamed to '${name}', but the old draft '${from}' could not be removed: ${
689
+ e instanceof Error ? e.message : String(e)
690
+ }`
691
+ }),
692
+ )
693
+ }
694
+
695
+ /** delete the draft FILE, then fall back to another draft (DraftsSt.deleteDraft's rule).
696
+ * ORDER: the form is dropped WITHOUT flushing FIRST, its autosave would otherwise
697
+ * re-create the file the server is about to delete */
698
+ async deleteDraft(p: { module: string; draft: string }): Promise<void> {
699
+ const form = this.form
700
+ if (form != null && form.moduleKey === p.module && form.draft === p.draft) {
701
+ form.dispose({ flush: false })
702
+ runInAction(() => {
703
+ this.form = null
704
+ })
705
+ }
706
+ try {
707
+ const reply = await deleteDraft(p)
708
+ runInAction(() => {
709
+ this.modules = this.modules.map((m) => (m.module === p.module ? { ...m, drafts: reply.drafts } : m))
710
+ })
711
+ const fallback = reply.drafts.includes('default') ? 'default' : (reply.drafts[0] ?? 'default')
712
+ await this.select({ module: p.module, draft: fallback })
713
+ } catch (e) {
714
+ runInAction(() => {
715
+ this.formError = e instanceof Error ? e.message : String(e)
716
+ })
717
+ }
718
+ }
719
+
191
720
  /** duplicate = save the current values under a new name, then switch to it */
192
721
  async duplicateDraft(rawName: string): Promise<void> {
193
722
  const form = this.form