comfy-ts 2.8.0 → 2.9.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.
@@ -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); }
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'