comfy-ts 2.8.0 → 2.10.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.
@@ -19,11 +19,22 @@ import {
19
19
  type ServeSettings,
20
20
  } from 'src/cli/serve/web/api.ts'
21
21
  import { EnhancerSt } from 'src/cli/serve/web/state/EnhancerSt.ts'
22
- import { FormSt } from 'src/cli/serve/web/state/FormSt.ts'
22
+ import { FormSt, type VarSt } from 'src/cli/serve/web/state/FormSt.ts'
23
23
  import { logWebError } from 'src/cli/serve/web/logWeb.ts'
24
24
  import { asSeedForm } from 'src/cli/serve/web/state/payload.ts'
25
25
  import { readUrlSelection, resolveSelection, writeUrlSelection } from 'src/cli/serve/web/state/urlSelection.ts'
26
26
  import { RunSt } from 'src/cli/serve/web/state/RunSt.ts'
27
+ import {
28
+ coerceHostValue,
29
+ isEmbedded,
30
+ parseFromHost,
31
+ pickPromptVar,
32
+ postTarget,
33
+ readUrlPrompt,
34
+ resolveHostSelection,
35
+ safeStringify,
36
+ } from 'src/cli/serve/web/state/host.ts'
37
+ import type { HostToPanel, PanelHostAction, PanelRequest, PanelToHost } from 'src/cli/serve/hostProtocol.ts'
27
38
 
28
39
  /** selection + drawer survive a reload: hand-tuned state persists and restores */
29
40
  const STORAGE_KEY = 'comfy-ts-serve-ui'
@@ -168,6 +179,20 @@ export class WebSt {
168
179
  /** hosts this process knows + where each module runs (server-owned, like the drafts) */
169
180
  hosts: HostsPayload = { hosts: [], defaults: {}, overrides: {} }
170
181
  hostError: string | null = null
182
+ /** buttons the EMBEDDING page asked for on every result (host protocol, host.ts). Empty
183
+ * when the panel is a plain tab, so nothing here changes the standalone panel */
184
+ hostActions: PanelHostAction[] = []
185
+ /** the parent window's origin, pinned from its first host message — replies go there only */
186
+ private hostOrigin: string | null = null
187
+ /** module + draft + values of the last `state` posted, so the debounced mirror does not
188
+ * repeat what a reply (or the previous mirror) already told the host */
189
+ private lastPostedState: string | null = null
190
+ /** in-flight selection changes (select, delete, lora refresh): a host request waits for
191
+ * them to settle instead of answering against a form that is null for a moment */
192
+ private switches = new Set<Promise<unknown>>()
193
+ /** host messages run one after another, behind the boot: a message that lands while the
194
+ * index is still loading needs a form, and dropping it was the silent failure */
195
+ private hostChain: Promise<void> = Promise.resolve()
171
196
 
172
197
  constructor() {
173
198
  this.run = new RunSt()
@@ -192,7 +217,18 @@ export class WebSt {
192
217
  this.showLatent = stored.latent ?? true
193
218
  this.varOrder = stored.varOrder ?? {}
194
219
  this.showLogs = stored.logs ?? false
195
- makeAutoObservable(this, { run: false, enhancer: false, form: observableRef, modules: observableShallow })
220
+ makeAutoObservable<WebSt, 'hostOrigin' | 'hostChain' | 'lastPostedState' | 'switches'>(this, {
221
+ run: false,
222
+ enhancer: false,
223
+ form: observableRef,
224
+ modules: observableShallow,
225
+ hostOrigin: false,
226
+ hostChain: false,
227
+ lastPostedState: false,
228
+ switches: false,
229
+ })
230
+ // inside a host page → listen for what it asks; a plain tab never sees a message
231
+ if (isEmbedded()) window.addEventListener('message', (e) => this.onHostMessage(e))
196
232
  // a closing/hidden tab must not lose an edit still inside the autosave debounce
197
233
  window.addEventListener('beforeunload', () => this.form?.flushKeepalive())
198
234
  document.addEventListener('visibilitychange', () => {
@@ -200,7 +236,8 @@ export class WebSt {
200
236
  // keepalive is unchained by necessity and could land before an older one
201
237
  if (document.visibilityState === 'hidden') void this.form?.save()
202
238
  })
203
- void this.boot()
239
+ // boot catches its own failures; the chain only has to outlive them
240
+ this.hostChain = this.boot().catch((e: unknown) => logWebError('panel boot failed', e))
204
241
  }
205
242
 
206
243
  toggleSidebar(): void {
@@ -246,6 +283,7 @@ export class WebSt {
246
283
  varSt.setFromRun({ mode: current.mode, value: used })
247
284
  }
248
285
  })
286
+ this.mirrorState()
249
287
  }
250
288
 
251
289
  /** the address bar follows the selection, so the url on screen is always the one to share.
@@ -316,20 +354,57 @@ export class WebSt {
316
354
  stored: { module: stored.module ?? null, draft: stored.draft ?? null },
317
355
  modules: this.modules,
318
356
  })
319
- if (opening == null) return
357
+ // `ready` means "booted with a selection": without one the host must hear that the
358
+ // panel is dead, or it cannot tell dead from still loading
359
+ if (opening == null) {
360
+ this.postHost({ comfyTs: 'error', code: 'boot', message: 'no workflows are served' })
361
+ return
362
+ }
320
363
  await this.select(opening)
364
+ if (this.form == null) {
365
+ this.postHost({
366
+ comfyTs: 'error',
367
+ code: 'boot',
368
+ message: `the opening draft could not be read: ${this.formError ?? 'unknown error'}`,
369
+ })
370
+ return
371
+ }
372
+ // a host opens the panel with the prompt already typed (`?prompt=`)
373
+ const urlPrompt = readUrlPrompt(window.location.search)
374
+ if (urlPrompt != null) this.setPromptText(urlPrompt)
375
+ // last: the host replies with its buttons + its prompt, and both need a form
376
+ this.postHost({ comfyTs: 'ready' })
321
377
  } catch (e) {
378
+ const message = e instanceof Error ? e.message : String(e)
322
379
  runInAction(() => {
323
380
  this.phase = 'error'
324
- this.bootError = e instanceof Error ? e.message : String(e)
381
+ this.bootError = message
325
382
  })
383
+ this.postHost({ comfyTs: 'error', code: 'boot', message })
326
384
  }
327
385
  }
328
386
 
329
387
  /** latest-wins guard for rapid draft clicks: only the newest select may write form state */
330
388
  private selectToken = 0
331
389
 
332
- async select(p: { module: string; draft: string }): Promise<void> {
390
+ /** `mirror: false` when a host request will answer with its own `state` right after */
391
+ select(p: { module: string; draft: string }, o: { mirror?: boolean } = {}): Promise<void> {
392
+ return this.trackSwitch(this.selectNow(p, o.mirror ?? true))
393
+ }
394
+
395
+ private trackSwitch<T>(op: Promise<T>): Promise<T> {
396
+ this.switches.add(op)
397
+ const done = (): void => void this.switches.delete(op)
398
+ op.then(done, done)
399
+ return op
400
+ }
401
+
402
+ /** resolves once no selection change is in flight (a nested one included) */
403
+ private async switchSettled(): Promise<void> {
404
+ while (this.switches.size > 0) await Promise.allSettled(this.switches)
405
+ }
406
+
407
+ private async selectNow(p: { module: string; draft: string }, mirror: boolean): Promise<void> {
333
408
  const mod = this.moduleByKey(p.module)
334
409
  if (mod == null) return
335
410
  // re-picking the draft you are IN is a no-op, not a reload: a pending autosave would
@@ -367,12 +442,18 @@ export class WebSt {
367
442
  }
368
443
  try {
369
444
  const reply = await fetchDraftValues(p)
445
+ // a newer select owns the screen now: telling the host about this one would be a lie
446
+ if (token !== this.selectToken) return
447
+ const form = new FormSt(p.module, p.draft, mod, reply.values ?? {})
448
+ // the host mirrors user edits on the autosave's own debounce (pinned only)
449
+ form.onSettled = (): void => this.mirrorState()
370
450
  runInAction(() => {
371
- if (token !== this.selectToken) return
372
- this.form = new FormSt(p.module, p.draft, mod, reply.values ?? {})
451
+ this.form = form
373
452
  this.persist()
374
453
  this.syncUrl()
375
454
  })
455
+ this.postHost({ comfyTs: 'selection', module: form.moduleKey, draft: form.draft })
456
+ if (mirror) this.mirrorState()
376
457
  } catch (e) {
377
458
  runInAction(() => {
378
459
  if (token !== this.selectToken) return
@@ -389,6 +470,205 @@ export class WebSt {
389
470
  }
390
471
  }
391
472
 
473
+ // ── the host protocol (host.ts, types in hostProtocol.ts) ────────────────
474
+ promptVar(): VarSt | null {
475
+ return pickPromptVar(this.form?.vars ?? [])
476
+ }
477
+
478
+ /** `set-prompt` and `?prompt=`: through the same coercion as set-values */
479
+ setPromptText(text: string): void {
480
+ const v = this.promptVar()
481
+ if (v == null) return
482
+ const coerced = coerceHostValue(v.desc, text, v.value)
483
+ if (!coerced.ok) {
484
+ logWebError('host set-prompt', `'${v.name}' (${v.desc.kind}) rejected the text`)
485
+ return
486
+ }
487
+ runInAction(() => v.set(coerced.value))
488
+ }
489
+
490
+ private postHost(msg: PanelToHost): void {
491
+ if (!isEmbedded()) return
492
+ // host.ts owns the rule: before the pin only value-free messages leave, to '*'
493
+ const target = postTarget(msg, this.hostOrigin)
494
+ if (target == null) return
495
+ try {
496
+ window.parent.postMessage(msg, target)
497
+ } catch (e) {
498
+ logWebError('could not post to the host page', e)
499
+ }
500
+ }
501
+
502
+ /** set vars by name, each through coerceHostValue. Returns the names NOT applied (no such
503
+ * var, or a value its control cannot produce); those fields stay as they were */
504
+ setValues(values: Record<string, unknown>): string[] {
505
+ const form = this.form
506
+ if (form == null) return Object.keys(values)
507
+ const rejected: string[] = []
508
+ runInAction(() => {
509
+ for (const [name, raw] of Object.entries(values)) {
510
+ const varSt = form.vars.find((v) => v.name === name)
511
+ if (varSt == null) {
512
+ rejected.push(name)
513
+ logWebError('host set-values', `no var named '${name}' on ${form.moduleKey}`)
514
+ continue
515
+ }
516
+ const coerced = coerceHostValue(varSt.desc, raw, varSt.value)
517
+ if (coerced.ok) varSt.set(coerced.value)
518
+ else {
519
+ rejected.push(name)
520
+ logWebError('host set-values', `'${name}' (${varSt.desc.kind}) rejected ${safeStringify(raw)}`)
521
+ }
522
+ }
523
+ })
524
+ return rejected
525
+ }
526
+
527
+ private stateOf(form: FormSt): { key: string; values: Record<string, unknown> } {
528
+ const values = form.valuesJSON()
529
+ return { key: safeStringify([form.moduleKey, form.draft, values]), values }
530
+ }
531
+
532
+ /** the reply to a request: always posted (the host is pinned, it just spoke) */
533
+ private replyState(form: FormSt, request: PanelRequest, rejected?: string[]): void {
534
+ const { key, values } = this.stateOf(form)
535
+ this.lastPostedState = key
536
+ this.postHost({
537
+ comfyTs: 'state',
538
+ module: form.moduleKey,
539
+ draft: form.draft,
540
+ values,
541
+ request,
542
+ ...(rejected != null ? { rejected } : {}),
543
+ })
544
+ }
545
+
546
+ /** volunteered state (a user edit or switch, run seeds): only to a pinned host, and only
547
+ * when it differs from the last state the host was told */
548
+ private mirrorState(): void {
549
+ const form = this.form
550
+ if (form == null || this.hostOrigin == null) return
551
+ const { key, values } = this.stateOf(form)
552
+ if (key === this.lastPostedState) return
553
+ this.lastPostedState = key
554
+ this.postHost({ comfyTs: 'state', module: form.moduleKey, draft: form.draft, values })
555
+ }
556
+
557
+ private replyError(
558
+ request: PanelRequest,
559
+ code: 'unknown-module' | 'select-failed' | 'superseded' | 'no-form',
560
+ message: string,
561
+ ): void {
562
+ this.postHost({ comfyTs: 'error', code, message, request })
563
+ }
564
+
565
+ private onHostMessage(e: MessageEvent): void {
566
+ // the host is the parent window, nobody else: a sibling or child frame posting first used
567
+ // to pin ITS origin and lock the real host out
568
+ if (e.source !== window.parent) return
569
+ const msg = parseFromHost(e.data)
570
+ if (msg == null) return
571
+ if (this.hostOrigin == null) this.hostOrigin = e.origin
572
+ else if (e.origin !== this.hostOrigin) return
573
+ this.hostChain = this.hostChain
574
+ .then(() => this.applyHostMessage(msg))
575
+ .catch((err: unknown) => logWebError(`host message '${msg.comfyTs}' failed`, err))
576
+ }
577
+
578
+ /** every request (`set-selection`, `set-values`, `get-state`) answers exactly once, with
579
+ * `state` or `error`; the catch below keeps that true when something throws */
580
+ private async applyHostMessage(msg: HostToPanel): Promise<void> {
581
+ try {
582
+ await this.applyHostMessageNow(msg)
583
+ } catch (e) {
584
+ if (msg.comfyTs === 'set-selection' || msg.comfyTs === 'set-values' || msg.comfyTs === 'get-state')
585
+ this.replyError(msg.comfyTs, 'no-form', e instanceof Error ? e.message : String(e))
586
+ throw e
587
+ }
588
+ }
589
+
590
+ private async applyHostMessageNow(msg: HostToPanel): Promise<void> {
591
+ switch (msg.comfyTs) {
592
+ case 'host-actions':
593
+ runInAction(() => {
594
+ this.hostActions = msg.actions
595
+ })
596
+ return
597
+ case 'set-prompt':
598
+ await this.switchSettled()
599
+ this.setPromptText(msg.text)
600
+ return
601
+ case 'set-selection': {
602
+ await this.switchSettled()
603
+ const target = resolveHostSelection({ want: msg, modules: this.modules })
604
+ if (target == null) {
605
+ this.replyError('set-selection', 'unknown-module', `no workflow named '${msg.module}' is served`)
606
+ return
607
+ }
608
+ const open = this.form
609
+ if (open == null || open.moduleKey !== target.module || open.draft !== target.draft) {
610
+ await this.select(target, { mirror: false })
611
+ await this.switchSettled()
612
+ }
613
+ const form = this.form
614
+ if (form == null) {
615
+ const why = this.formError ?? 'the draft could not be read'
616
+ this.replyError('set-selection', 'select-failed', why)
617
+ } else if (form.moduleKey !== target.module || form.draft !== target.draft)
618
+ this.replyError(
619
+ 'set-selection',
620
+ 'superseded',
621
+ `the panel switched to ${form.moduleKey}/${form.draft} while ${target.module}/${target.draft} was loading`,
622
+ )
623
+ else this.replyState(form, 'set-selection')
624
+ return
625
+ }
626
+ case 'set-values': {
627
+ await this.switchSettled()
628
+ const form = this.form
629
+ if (form == null) {
630
+ this.replyError('set-values', 'no-form', this.noFormMessage())
631
+ return
632
+ }
633
+ this.replyState(form, 'set-values', this.setValues(msg.values))
634
+ return
635
+ }
636
+ case 'get-state': {
637
+ await this.switchSettled()
638
+ const form = this.form
639
+ if (form == null) this.replyError('get-state', 'no-form', this.noFormMessage())
640
+ else this.replyState(form, 'get-state')
641
+ return
642
+ }
643
+ }
644
+ }
645
+
646
+ private noFormMessage(): string {
647
+ return this.formError != null ? `no draft is open: ${this.formError}` : 'no draft is open'
648
+ }
649
+
650
+ /** a host button on a result: tell the page which image, and the prompt it came from */
651
+ postResultAction(
652
+ actionId: string,
653
+ r: { promptId: string; module: string; draft: string; seeds: Record<string, number> },
654
+ img: { url: string; filename: string },
655
+ ix: number,
656
+ ): void {
657
+ const pv = this.promptVar()
658
+ this.postHost({
659
+ comfyTs: 'result-action',
660
+ id: actionId,
661
+ promptId: r.promptId,
662
+ ix,
663
+ url: img.url,
664
+ filename: img.filename,
665
+ module: r.module,
666
+ draft: r.draft,
667
+ seeds: r.seeds,
668
+ prompt: pv != null && typeof pv.value === 'string' ? pv.value : null,
669
+ })
670
+ }
671
+
392
672
  /** side and pinned show the results next to (or over) the form, so the run button belongs
393
673
  * there: in pinned it stays on screen while the form scrolls */
394
674
  get generateInResults(): boolean {
@@ -482,6 +762,10 @@ export class WebSt {
482
762
  this.loraSyncing = true
483
763
  })
484
764
  await this.hostAction('refresh-loras')
765
+ await this.trackSwitch(this.reloadIndexAndForm())
766
+ }
767
+
768
+ private async reloadIndexAndForm(): Promise<void> {
485
769
  // the option lists (and the manager-only union) live in the descriptors: re-read them,
486
770
  // then re-select the same draft so the form is rebuilt against the new options
487
771
  try {
@@ -695,7 +979,11 @@ export class WebSt {
695
979
  /** delete the draft FILE, then fall back to another draft (DraftsSt.deleteDraft's rule).
696
980
  * ORDER: the form is dropped WITHOUT flushing FIRST, its autosave would otherwise
697
981
  * re-create the file the server is about to delete */
698
- async deleteDraft(p: { module: string; draft: string }): Promise<void> {
982
+ deleteDraft(p: { module: string; draft: string }): Promise<void> {
983
+ return this.trackSwitch(this.deleteDraftNow(p))
984
+ }
985
+
986
+ private async deleteDraftNow(p: { module: string; draft: string }): Promise<void> {
699
987
  const form = this.form
700
988
  if (form != null && form.moduleKey === p.module && form.draft === p.draft) {
701
989
  form.dispose({ flush: false })
@@ -0,0 +1,206 @@
1
+ // the HOST protocol: the panel inside an <iframe>, talking to the page that embeds it. A host
2
+ // cannot read a cross-origin frame (url, dom, storage), so everything it learns is something the
3
+ // panel SAYS. Every message carries a `comfyTs` discriminator, so an unrelated message on the
4
+ // window is ignored. The message types live in src/cli/serve/hostProtocol.ts (re-exported as
5
+ // types by `comfy-ts/web`); the full contract is agent/architecture.md → HOST PROTOCOL.
6
+ //
7
+ // WHO IS THE HOST: only `window.parent`. A message whose `source` is another window is ignored,
8
+ // and the parent's origin is pinned from its first host message (WebSt.onHostMessage).
9
+ // WHAT GOES OUT BEFORE THE PIN: `ready`, `selection` and `error {code:'boot'}` only, to '*'. They
10
+ // carry no draft value. `state` and everything else waits for the host to speak (postTarget).
11
+ //
12
+ // Host messages run IN ORDER, and not before the boot is done: a message that lands while the
13
+ // panel is still loading waits for the form instead of being dropped (WebSt.hostChain).
14
+ // PURE and DOM-free below `isEmbedded`: the parsers are headless-tested.
15
+ import type { VarDescriptor } from 'src/cli/serve/describeVar.ts'
16
+ import type { HostToPanel, PanelHostAction, PanelToHost } from 'src/cli/serve/hostProtocol.ts'
17
+ import { asSeedForm, pruneLorasRecord } from 'src/cli/serve/web/state/payload.ts'
18
+
19
+ function isRecord(v: unknown): v is Record<string, unknown> {
20
+ return v != null && typeof v === 'object'
21
+ }
22
+
23
+ function isPlainRecord(v: unknown): v is Record<string, unknown> {
24
+ return isRecord(v) && !Array.isArray(v)
25
+ }
26
+
27
+ /** a host message, or null for anything else on the window (other frames, devtools, ads).
28
+ * Never throws: a malformed message is simply not ours */
29
+ export function parseFromHost(data: unknown): HostToPanel | null {
30
+ if (!isRecord(data)) return null
31
+ switch (data.comfyTs) {
32
+ case 'set-prompt':
33
+ return typeof data.text === 'string' ? { comfyTs: 'set-prompt', text: data.text } : null
34
+ case 'host-actions': {
35
+ if (!Array.isArray(data.actions)) return null
36
+ const actions: PanelHostAction[] = []
37
+ for (const a of data.actions) {
38
+ if (!isRecord(a) || typeof a.id !== 'string' || a.id === '' || typeof a.label !== 'string') continue
39
+ // a button with no label is invisible, and a second id would make a click ambiguous
40
+ if (a.label === '' || actions.some((x) => x.id === a.id)) continue
41
+ actions.push({ id: a.id, label: a.label, ...(typeof a.title === 'string' ? { title: a.title } : {}) })
42
+ }
43
+ return { comfyTs: 'host-actions', actions }
44
+ }
45
+ case 'set-selection':
46
+ return typeof data.module === 'string' && data.module !== '' && typeof data.draft === 'string'
47
+ ? { comfyTs: 'set-selection', module: data.module, draft: data.draft }
48
+ : null
49
+ case 'set-values':
50
+ return isPlainRecord(data.values) ? { comfyTs: 'set-values', values: data.values } : null
51
+ case 'get-state':
52
+ return { comfyTs: 'get-state' }
53
+ default:
54
+ return null
55
+ }
56
+ }
57
+
58
+ /** where a host's set-selection lands. Same fallback as a url (resolveSelection) with one
59
+ * difference: an unknown MODULE is null, "change nothing", because the panel is already showing
60
+ * something and replacing it with an arbitrary first workflow is not what the host asked */
61
+ export function resolveHostSelection(p: {
62
+ want: { module: string; draft: string }
63
+ modules: readonly { module: string; drafts: readonly string[] }[]
64
+ }): { module: string; draft: string } | null {
65
+ const mod = p.modules.find((m) => m.module === p.want.module)
66
+ if (mod == null) return null
67
+ return { module: mod.module, draft: mod.drafts.includes(p.want.draft) ? p.want.draft : 'default' }
68
+ }
69
+
70
+ export type Coerced = { ok: true; value: unknown } | { ok: false }
71
+
72
+ const REJECT: Coerced = { ok: false }
73
+ const SEED_MODES: readonly string[] = ['=', '+', '-', '?']
74
+
75
+ function isFiniteNumber(v: unknown): v is number {
76
+ return typeof v === 'number' && Number.isFinite(v)
77
+ }
78
+
79
+ /** a strength a lora record may hold: off, on, one strength, or [model, clip] */
80
+ function isLoraEntry(v: unknown): boolean {
81
+ if (typeof v === 'boolean' || isFiniteNumber(v)) return true
82
+ return Array.isArray(v) && v.length === 2 && isFiniteNumber(v[0]) && isFiniteNumber(v[1])
83
+ }
84
+
85
+ /**
86
+ * a value a host sent for one var, held to what the var's CONTROL can produce: a text box
87
+ * gives a string, a number box a finite number (int truncated like parseInt), a select one of
88
+ * its choices, the seed row `{mode, value ≥ 0}`. Anything else is rejected rather than
89
+ * repaired, so a host bug shows up as an unchanged field, not a silently different one.
90
+ * `current` is the var's value now: a bare seed number keeps the current mode, as the box does.
91
+ */
92
+ export function coerceHostValue(desc: VarDescriptor, raw: unknown, current: unknown): Coerced {
93
+ switch (desc.kind) {
94
+ case 'prompt':
95
+ case 'text':
96
+ case 'image':
97
+ return typeof raw === 'string' ? { ok: true, value: raw } : REJECT
98
+ case 'int':
99
+ return isFiniteNumber(raw) ? { ok: true, value: Math.trunc(raw) } : REJECT
100
+ case 'float':
101
+ return isFiniteNumber(raw) ? { ok: true, value: raw } : REJECT
102
+ case 'toggle':
103
+ return typeof raw === 'boolean' ? { ok: true, value: raw } : REJECT
104
+ case 'choice':
105
+ return typeof raw === 'string' && (desc.choices ?? []).includes(raw) ? { ok: true, value: raw } : REJECT
106
+ case 'seed': {
107
+ const cur = asSeedForm(current)
108
+ if (isFiniteNumber(raw)) return { ok: true, value: { mode: cur.mode, value: Math.max(0, Math.floor(raw)) } }
109
+ if (!isPlainRecord(raw)) return REJECT
110
+ if (raw.mode !== undefined && !(typeof raw.mode === 'string' && SEED_MODES.includes(raw.mode))) return REJECT
111
+ if (raw.value !== undefined && !isFiniteNumber(raw.value)) return REJECT
112
+ return {
113
+ ok: true,
114
+ value: {
115
+ mode: typeof raw.mode === 'string' ? raw.mode : cur.mode,
116
+ value: isFiniteNumber(raw.value) ? Math.max(0, Math.floor(raw.value)) : cur.value,
117
+ },
118
+ }
119
+ }
120
+ case 'size': {
121
+ let width: unknown = null
122
+ let height: unknown = null
123
+ if (typeof raw === 'string') {
124
+ const m = /^\s*(\d+)\s*x\s*(\d+)\s*$/i.exec(raw)
125
+ if (m != null) {
126
+ width = Number(m[1])
127
+ height = Number(m[2])
128
+ }
129
+ } else if (isPlainRecord(raw)) {
130
+ width = raw.width
131
+ height = raw.height
132
+ }
133
+ if (!isFiniteNumber(width) || !isFiniteNumber(height) || width < 1 || height < 1) return REJECT
134
+ return { ok: true, value: { width: Math.floor(width), height: Math.floor(height) } }
135
+ }
136
+ case 'loras': {
137
+ if (!isPlainRecord(raw)) return REJECT
138
+ for (const st of Object.values(raw)) if (!isLoraEntry(st)) return REJECT
139
+ // the record the form keeps: known loras that are ON (payload.ts owns the why)
140
+ return { ok: true, value: pruneLorasRecord(raw, desc.options ?? []) }
141
+ }
142
+ default:
143
+ return REJECT
144
+ }
145
+ }
146
+
147
+ /** the var `set-prompt` and `?prompt=` fill: the one declared `kind:'prompt'`, else a TEXT var
148
+ * named like a prompt that is not the negative one. A name alone is not enough: a float
149
+ * `prompt_strength` or a `negative_prompt` declared first must never receive the prompt */
150
+ export function pickPromptVar<V extends { name: string; desc: VarDescriptor }>(vars: readonly V[]): V | null {
151
+ return (
152
+ vars.find((v) => v.desc.kind === 'prompt') ??
153
+ vars.find(
154
+ (v) => (v.desc.kind === 'text' || v.desc.kind === 'prompt') && /prompt/i.test(v.name) && !/neg/i.test(v.name),
155
+ ) ??
156
+ null
157
+ )
158
+ }
159
+
160
+ /** the targetOrigin a panel message goes out with, or null when it must not go out yet.
161
+ * Before the host origin is pinned only messages carrying no draft value may leave, to '*'.
162
+ * An opaque parent origin ("null") cannot be a targetOrigin (postMessage throws), so it is
163
+ * posted with '*': the post goes to window.parent only, which is the window that pinned it */
164
+ export function postTarget(msg: PanelToHost, pinnedOrigin: string | null): string | null {
165
+ if (pinnedOrigin == null) {
166
+ const unpinnedOk =
167
+ msg.comfyTs === 'ready' || msg.comfyTs === 'selection' || (msg.comfyTs === 'error' && msg.code === 'boot')
168
+ return unpinnedOk ? '*' : null
169
+ }
170
+ return pinnedOrigin === 'null' ? '*' : pinnedOrigin
171
+ }
172
+
173
+ /** a host value for a log line. JSON.stringify throws on a BigInt or a cycle, and a throw
174
+ * there used to abort the whole message, reply included */
175
+ export function safeStringify(v: unknown): string {
176
+ try {
177
+ const out = JSON.stringify(v, (_k, x: unknown) => (typeof x === 'bigint' ? `${x}n` : x))
178
+ if (typeof v === 'bigint') return `${v}n`
179
+ return out ?? String(v)
180
+ } catch {
181
+ try {
182
+ return String(v)
183
+ } catch {
184
+ return '[unprintable]'
185
+ }
186
+ }
187
+ }
188
+
189
+ /** `?prompt=<text>` — a host opens the panel with the prompt already in the box */
190
+ export function readUrlPrompt(search: string): string | null {
191
+ try {
192
+ const params = new URLSearchParams(search.startsWith('?') ? search.slice(1) : search)
193
+ const p = params.get('prompt')
194
+ return p == null || p === '' ? null : p
195
+ } catch {
196
+ return null
197
+ }
198
+ }
199
+
200
+ export function isEmbedded(): boolean {
201
+ try {
202
+ return typeof window !== 'undefined' && window.parent !== window
203
+ } catch {
204
+ return false
205
+ }
206
+ }
@@ -213,6 +213,15 @@ button.mode.sel { background: var(--accent-dim); border-color: var(--accent); co
213
213
  .run-card { background: var(--panel); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; }
214
214
  .run-card .meta { color: var(--dim); font-size: 12px; margin-bottom: 8px; display: flex; justify-content: space-between; gap: 8px; }
215
215
  .run-card .imgs { display: flex; flex-wrap: wrap; gap: 10px; }
216
+ .img-cell { display: flex; flex-direction: column; gap: 4px; }
217
+ /* the embedding page's buttons on a result (host protocol) — loud on purpose: they ARE the
218
+ reason the panel is inside that page */
219
+ .host-actions { display: flex; gap: 6px; flex-wrap: wrap; }
220
+ .host-action { border: 1px solid var(--accent); background: var(--accent); color: #fff; border-radius: 6px; padding: 4px 12px; font-size: 13px; font-weight: 600; cursor: pointer; }
221
+ .host-action:hover { filter: brightness(1.12); }
222
+ .host-action.danger { background: none; color: var(--dim); border-color: var(--dim); font-weight: 400; }
223
+ .host-action.danger:hover { color: var(--red); border-color: var(--red); }
224
+ .lightbox-bar .host-action { padding: 4px 10px; }
216
225
  .run-card img { max-width: min(320px, 100%); max-height: 320px; border-radius: 6px; display: block; }
217
226
  .run-card .noimg { color: var(--dim); font-style: italic; }
218
227
  .run-card.running { border-color: var(--accent-dim); }
@@ -4,7 +4,11 @@ import type { ComfyNodeSchema } from 'src/sdk-generator/ComfyNodeSchema.ts'
4
4
  import type { ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
5
5
  import type { NodeInputExt, NodeOutputExt } from 'src/sdk-generator/comfyui-types.ts'
6
6
  import { ComfyDefaultNodeWhenUnknown_Name } from 'src/sdk-generator/Primitives.ts'
7
- import { classifySchemaInput, defaultValueForWidget } from 'src/sdk-generator/inputWidgetKind.ts'
7
+ import {
8
+ classifySchemaInput,
9
+ containerInstanceSlotType,
10
+ defaultValueForWidget,
11
+ } from 'src/sdk-generator/inputWidgetKind.ts'
8
12
  import type { DynamicComboOption } from 'src/sdk-generator/inputWidgetKind.ts'
9
13
  import type { Maybe } from 'src/types/index.ts'
10
14
  import { comfyColors } from 'src/utils/ComfyColors.ts'
@@ -440,8 +444,20 @@ export class ComfyNode<
440
444
 
441
445
  private _getExpectedTypeForField(name: string): string {
442
446
  const input = this.$schema.inputs.find((i: NodeInputExt) => i.nameInComfy === name)
443
- if (input == null) throw new Error('🔴 input not found asdf')
444
- return input.typeName
447
+ if (input != null) return input.typeName
448
+ // autogrow instance key `decl.<instance>`: the container template carries the slot type
449
+ const dot = name.indexOf('.')
450
+ const decl =
451
+ dot > 0 ? this.$schema.inputs.find((i: NodeInputExt) => i.nameInComfy === name.slice(0, dot)) : undefined
452
+ if (decl != null) {
453
+ const kind = classifySchemaInput(decl)
454
+ const slotType = containerInstanceSlotType(decl.opts)
455
+ if (kind.kind === 'dynamic-container' && kind.instanceNames.includes(name.slice(dot + 1)) && slotType != null)
456
+ return slotType
457
+ }
458
+ throw new Error(
459
+ `🔴 no input "${name}" on ${this.$schema.nodeKey}: cannot tell which output of the linked node to use`,
460
+ )
445
461
  }
446
462
 
447
463
  private _getOutputForTypeOrCrash(type: string): ComfyNodeOutput<any> {
package/src/web.ts CHANGED
@@ -11,3 +11,15 @@ import { createMemoryStorage, setDefaultComfyStorage } from 'src/storage/ComfySt
11
11
  setDefaultComfyStorage(createMemoryStorage())
12
12
 
13
13
  export * from 'src/coreExports.ts'
14
+
15
+ // the serve web panel's postMessage host protocol, TYPES ONLY: a page embedding the panel in an
16
+ // <iframe> types what it sends and receives, and no runtime enters the browser graph
17
+ export type {
18
+ HostToPanel,
19
+ PanelError,
20
+ PanelHostAction,
21
+ PanelRequest,
22
+ PanelResultAction,
23
+ PanelState,
24
+ PanelToHost,
25
+ } from 'src/cli/serve/hostProtocol.ts'