comfy-ts 2.21.0 → 2.23.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 (104) hide show
  1. package/dist/{ServeApp-ByMobrWW.js → ServeApp-DolRCMHj.js} +183 -14
  2. package/dist/ServeApp-DolRCMHj.js.map +1 -0
  3. package/dist/cli.js +5 -5
  4. package/dist/{exampleAssets-B5sMqNia.js → exampleAssets-Duneoq6r.js} +331 -42
  5. package/dist/exampleAssets-Duneoq6r.js.map +1 -0
  6. package/dist/{findDefinedWorkflow-BNZgYIww.js → findDefinedWorkflow-DjoJA8y7.js} +2 -2
  7. package/dist/{findDefinedWorkflow-BNZgYIww.js.map → findDefinedWorkflow-DjoJA8y7.js.map} +1 -1
  8. package/dist/index.cjs +381 -34
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +201 -24
  11. package/dist/index.d.ts +201 -24
  12. package/dist/index.js +380 -35
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-run-CuBSygku.js → run-run-Cr0L9lCK.js} +5 -5
  15. package/dist/{run-run-CuBSygku.js.map → run-run-Cr0L9lCK.js.map} +1 -1
  16. package/dist/{run-serve-COk_G0Qz.js → run-serve---qA7o_m.js} +4 -4
  17. package/dist/{run-serve-COk_G0Qz.js.map → run-serve---qA7o_m.js.map} +1 -1
  18. package/dist/{run-tui-CB6i_x2y.js → run-tui-DxXiWo5J.js} +4 -4
  19. package/dist/{run-tui-CB6i_x2y.js.map → run-tui-DxXiWo5J.js.map} +1 -1
  20. package/dist/{schemaDrift-CHDVYlaj.js → schemaDrift-BTxdABHi.js} +36 -2
  21. package/dist/schemaDrift-BTxdABHi.js.map +1 -0
  22. package/dist/serve-web.js +207 -47
  23. package/dist/web.d.ts +201 -24
  24. package/dist/web.js +380 -35
  25. package/dist/web.js.map +1 -1
  26. package/examples/README.md +2 -0
  27. package/examples/comfy-cloud/sdk.d.ts +102 -1
  28. package/examples/depth-explorer/models.ts +722 -0
  29. package/examples/depth-explorer/serve.ts +140 -0
  30. package/examples/depth-explorer/thumbs/bae.webp +0 -0
  31. package/examples/depth-explorer/thumbs/da3-mono-large.webp +0 -0
  32. package/examples/depth-explorer/thumbs/dav1-vitl.webp +0 -0
  33. package/examples/depth-explorer/thumbs/dav2-vitl.webp +0 -0
  34. package/examples/depth-explorer/thumbs/dsine.webp +0 -0
  35. package/examples/depth-explorer/thumbs/iid-albedo.webp +0 -0
  36. package/examples/depth-explorer/thumbs/iid-metalness.webp +0 -0
  37. package/examples/depth-explorer/thumbs/iid-roughness.webp +0 -0
  38. package/examples/depth-explorer/thumbs/iid-shading.webp +0 -0
  39. package/examples/depth-explorer/thumbs/iid-specular.webp +0 -0
  40. package/examples/depth-explorer/thumbs/leres.webp +0 -0
  41. package/examples/depth-explorer/thumbs/lotus-depth.webp +0 -0
  42. package/examples/depth-explorer/thumbs/marigold2-albedo.webp +0 -0
  43. package/examples/depth-explorer/thumbs/marigold2-depth.webp +0 -0
  44. package/examples/depth-explorer/thumbs/marigold2-normal.webp +0 -0
  45. package/examples/depth-explorer/thumbs/metric3d-depth.webp +0 -0
  46. package/examples/depth-explorer/thumbs/metric3d-normal.webp +0 -0
  47. package/examples/depth-explorer/thumbs/midas-normal.webp +0 -0
  48. package/examples/depth-explorer/thumbs/midas.webp +0 -0
  49. package/examples/depth-explorer/thumbs/moge2-depth.webp +0 -0
  50. package/examples/depth-explorer/thumbs/moge2-normal.webp +0 -0
  51. package/examples/depth-explorer/thumbs/zoe-da.webp +0 -0
  52. package/examples/depth-explorer/thumbs/zoe.webp +0 -0
  53. package/examples/depth-explorer/web/App.tsx +457 -0
  54. package/examples/depth-explorer/web/gl.ts +202 -0
  55. package/examples/depth-explorer/web/index.html +14 -0
  56. package/examples/depth-explorer/web/main.tsx +19 -0
  57. package/examples/depth-explorer/web/pixels.ts +86 -0
  58. package/examples/depth-explorer/web/state.ts +329 -0
  59. package/examples/depth-explorer/web/styles.css +366 -0
  60. package/examples/depth-explorer/web/tsconfig.json +16 -0
  61. package/examples/rvion/17-relight.cflow.ts +110 -0
  62. package/examples/rvion/18-world.cflow.ts +101 -0
  63. package/examples/world-explorer/serve.ts +171 -0
  64. package/examples/world-explorer/web/index.html +14 -0
  65. package/examples/world-explorer/web/main.tsx +200 -0
  66. package/examples/world-explorer/web/state.ts +212 -0
  67. package/examples/world-explorer/web/styles.css +131 -0
  68. package/examples/world-explorer/web/thumb.ts +21 -0
  69. package/examples/world-explorer/web/tsconfig.json +11 -0
  70. package/examples/world-explorer/world-state.ts +40 -0
  71. package/package.json +6 -7
  72. package/src/cli/serve/ServeApp.ts +106 -6
  73. package/src/cli/serve/describeVar.ts +12 -1
  74. package/src/cli/serve/resultHistory.ts +28 -5
  75. package/src/cli/serve/thumbs.ts +77 -0
  76. package/src/cli/serve/web/api.ts +9 -1
  77. package/src/cli/serve/web/components/Gallery.tsx +26 -1
  78. package/src/cli/serve/web/components/controls/BasicControls.tsx +14 -17
  79. package/src/cli/serve/web/components/controls/MediaControl.tsx +62 -9
  80. package/src/cli/serve/web/components/controls/RichSelect.tsx +262 -0
  81. package/src/cli/serve/web/state/RunSt.poll.test.ts +4 -1
  82. package/src/cli/serve/web/state/choiceButtons.ts +26 -2
  83. package/src/cli/serve/web/styles.ts +42 -0
  84. package/src/cli/serve/web/widgets/OutputWidgets.tsx +19 -0
  85. package/src/cli/serve/web/widgets/RelightSt.ts +113 -0
  86. package/src/cli/serve/web/widgets/RelightWidget.tsx +305 -0
  87. package/src/cli/serve/web/widgets/relightGl.ts +305 -0
  88. package/src/cli/serve/web/widgets/widgetStyles.ts +19 -0
  89. package/src/coreExports.ts +10 -0
  90. package/src/graph/ComfyNode.ts +12 -2
  91. package/src/host/ComfyHost.ts +153 -2
  92. package/src/host/ResilientWebsocket.ts +10 -0
  93. package/src/manager/script-update-manager.bun.ts +0 -7
  94. package/src/runner/ComfyExecution.ts +165 -20
  95. package/src/runner/ComfyWsApi.ts +2 -0
  96. package/src/runner/historyReplay.ts +53 -0
  97. package/src/runner/outputs3d.ts +18 -0
  98. package/src/sdk-generator/comfyui-sdk-codegen.ts +7 -2
  99. package/src/vars/ComfyVars.ts +32 -2
  100. package/src/vars/DefinedWorkflow.ts +4 -0
  101. package/src/vars/outputWidgets.ts +47 -0
  102. package/dist/ServeApp-ByMobrWW.js.map +0 -1
  103. package/dist/exampleAssets-B5sMqNia.js.map +0 -1
  104. package/dist/schemaDrift-CHDVYlaj.js.map +0 -1
@@ -0,0 +1,305 @@
1
+ // the relight renderer, raw WebGL2: one full quad, every pixel lit at its 3D position
2
+ // P = (x · aspect, y, depth · depthScale) (near = white in the depth map)
3
+ // by a point light and up to MAX_MOTES drifting light motes. Normals from the normal map (OpenGL,
4
+ // green up), else from the depth gradient. Shadows: a short march through the depth map toward
5
+ // each light. Materials: albedo, roughness, metalness and a specular (non diffuse) map, each
6
+ // optional. Pure renderer: the widget state owns every parameter.
7
+
8
+ export const MAX_MOTES = 16
9
+
10
+ export type RelightMaps = {
11
+ image: TexImageSource
12
+ depth?: TexImageSource
13
+ normal?: TexImageSource
14
+ albedo?: TexImageSource
15
+ roughness?: TexImageSource
16
+ metalness?: TexImageSource
17
+ specular?: TexImageSource
18
+ }
19
+
20
+ export type RelightView = 'lit' | 'albedo' | 'normal' | 'depth' | 'roughness' | 'metalness' | 'specular' | 'shadow'
21
+ export const VIEW_INDEX: Record<RelightView, number> = {
22
+ lit: 0,
23
+ albedo: 1,
24
+ normal: 2,
25
+ depth: 3,
26
+ roughness: 4,
27
+ metalness: 5,
28
+ specular: 6,
29
+ shadow: 7,
30
+ }
31
+
32
+ export type RelightParams = {
33
+ /** light position: x, y in 0..1 over the image (y down), z above the surface, in image heights */
34
+ light: [number, number, number]
35
+ color: [number, number, number]
36
+ intensity: number
37
+ /** distance (image heights) where the light falls to half */
38
+ falloff: number
39
+ /** how much of the original photo stays under the new light */
40
+ ambient: number
41
+ depthScale: number
42
+ shadows: boolean
43
+ /** each mote: x, y, z like the light */
44
+ motes: [number, number, number][]
45
+ moteIntensity: number
46
+ /** draw the light and the motes as glowing blobs */
47
+ showLights: boolean
48
+ view: RelightView
49
+ exposure: number
50
+ }
51
+
52
+ const VS = `#version 300 es
53
+ in vec2 a_uv;
54
+ uniform vec2 u_fit;
55
+ out vec2 v_uv;
56
+ void main() {
57
+ v_uv = a_uv;
58
+ gl_Position = vec4((a_uv.x * 2.0 - 1.0) * u_fit.x, (1.0 - a_uv.y * 2.0) * u_fit.y, 0.0, 1.0);
59
+ }`
60
+
61
+ const FS = `#version 300 es
62
+ precision highp float;
63
+ #define MAX_MOTES ${MAX_MOTES}
64
+ in vec2 v_uv;
65
+ uniform sampler2D u_image, u_depth, u_normal, u_albedo, u_rough, u_metal, u_spec;
66
+ uniform bool u_hasDepth, u_hasNormal, u_hasAlbedo, u_hasRough, u_hasMetal, u_hasSpec;
67
+ uniform float u_aspect, u_depthScale, u_intensity, u_falloff, u_ambient, u_moteIntensity, u_exposure;
68
+ uniform vec3 u_light, u_color;
69
+ uniform bool u_shadows, u_showLights;
70
+ uniform int u_moteCount, u_view;
71
+ uniform vec3 u_motes[MAX_MOTES];
72
+ uniform vec2 u_texel;
73
+ out vec4 o;
74
+
75
+ float depthAt(vec2 uv) { return u_hasDepth ? texture(u_depth, uv).r : 0.5; }
76
+ vec3 posAt(vec2 uv) { return vec3(uv.x * u_aspect, 1.0 - uv.y, depthAt(uv) * u_depthScale); }
77
+ vec3 lightPos(vec3 l) { return vec3(l.x * u_aspect, 1.0 - l.y, l.z); }
78
+
79
+ vec3 normalAt(vec2 uv) {
80
+ if (u_hasNormal) return normalize(texture(u_normal, uv).rgb * 2.0 - 1.0);
81
+ vec3 px = posAt(uv + vec2(u_texel.x, 0.0)) - posAt(uv - vec2(u_texel.x, 0.0));
82
+ vec3 py = posAt(uv - vec2(0.0, u_texel.y)) - posAt(uv + vec2(0.0, u_texel.y));
83
+ return normalize(cross(px, py));
84
+ }
85
+
86
+ /** 1 = lit, 0 = a surface between P and the light */
87
+ float shadow(vec2 uv, vec3 P, vec3 L) {
88
+ if (!u_shadows || !u_hasDepth) return 1.0;
89
+ vec3 d = L - P;
90
+ float occ = 0.0;
91
+ for (int i = 1; i <= 24; i++) {
92
+ float t = float(i) / 24.0;
93
+ vec3 q = P + d * t * 0.9;
94
+ vec2 quv = vec2(q.x / u_aspect, 1.0 - q.y);
95
+ if (quv.x < 0.0 || quv.x > 1.0 || quv.y < 0.0 || quv.y > 1.0) break;
96
+ float h = depthAt(quv) * u_depthScale;
97
+ occ = max(occ, smoothstep(0.004, 0.03, h - q.z));
98
+ }
99
+ return 1.0 - occ;
100
+ }
101
+
102
+ vec3 shade(vec2 uv, vec3 P, vec3 N, vec3 base, float rough, float metal, float specBoost, vec3 Lp, vec3 col, float power) {
103
+ vec3 Lv = Lp - P;
104
+ float dist = length(Lv);
105
+ vec3 L = Lv / dist;
106
+ float att = power / (1.0 + pow(dist / max(u_falloff, 0.01), 2.0));
107
+ float ndl = max(dot(N, L), 0.0);
108
+ vec3 V = vec3(0.0, 0.0, 1.0);
109
+ vec3 H = normalize(L + V);
110
+ float shin = mix(512.0, 6.0, rough);
111
+ float spec = pow(max(dot(N, H), 0.0), shin) * (shin + 8.0) / 25.0;
112
+ vec3 F0 = mix(vec3(0.04), base, metal) * specBoost;
113
+ vec3 diffuse = base * (1.0 - metal) * ndl;
114
+ vec3 specular = F0 * spec * ndl;
115
+ return (diffuse + specular) * col * att * shadow(uv, P, Lp);
116
+ }
117
+
118
+ float glow(vec2 uv, vec3 l, float size) {
119
+ vec2 d = (uv - l.xy) * vec2(u_aspect, 1.0);
120
+ float r = size * (0.6 + 0.6 / (0.3 + l.z));
121
+ return exp(-dot(d, d) / (r * r));
122
+ }
123
+
124
+ void main() {
125
+ vec2 uv = v_uv;
126
+ vec3 photo = texture(u_image, uv).rgb;
127
+ vec3 base = u_hasAlbedo ? texture(u_albedo, uv).rgb : photo;
128
+ float rough = u_hasRough ? texture(u_rough, uv).r : 0.6;
129
+ float metal = u_hasMetal ? texture(u_metal, uv).r : 0.0;
130
+ float specMap = u_hasSpec ? texture(u_spec, uv).r : 0.0;
131
+ vec3 N = normalAt(uv);
132
+ vec3 P = posAt(uv);
133
+
134
+ if (u_view == 1) { o = vec4(base, 1.0); return; }
135
+ if (u_view == 2) { o = vec4(N * 0.5 + 0.5, 1.0); return; }
136
+ if (u_view == 3) { o = vec4(vec3(depthAt(uv)), 1.0); return; }
137
+ if (u_view == 4) { o = vec4(vec3(rough), 1.0); return; }
138
+ if (u_view == 5) { o = vec4(vec3(metal), 1.0); return; }
139
+ if (u_view == 6) { o = vec4(vec3(specMap), 1.0); return; }
140
+ if (u_view == 7) { o = vec4(vec3(shadow(uv, P, lightPos(u_light))), 1.0); return; }
141
+
142
+ float specBoost = u_hasSpec ? 0.6 + specMap * 6.0 : 1.0;
143
+ vec3 c = photo * u_ambient;
144
+ c += shade(uv, P, N, base, rough, metal, specBoost, lightPos(u_light), u_color, u_intensity);
145
+ for (int i = 0; i < MAX_MOTES; i++) {
146
+ if (i >= u_moteCount) break;
147
+ c += shade(uv, P, N, base, rough, metal, specBoost, lightPos(u_motes[i]), u_color, u_moteIntensity);
148
+ }
149
+ c = vec3(1.0) - exp(-c * u_exposure);
150
+ if (u_showLights) {
151
+ c += u_color * glow(uv, u_light, 0.018) * 1.2;
152
+ for (int i = 0; i < MAX_MOTES; i++) {
153
+ if (i >= u_moteCount) break;
154
+ c += u_color * glow(uv, u_motes[i], 0.006) * 0.9;
155
+ }
156
+ }
157
+ o = vec4(c, 1.0);
158
+ }`
159
+
160
+ const SLOTS = ['image', 'depth', 'normal', 'albedo', 'roughness', 'metalness', 'specular'] as const
161
+ type Slot = (typeof SLOTS)[number]
162
+ const SAMPLER: Record<Slot, string> = {
163
+ image: 'u_image',
164
+ depth: 'u_depth',
165
+ normal: 'u_normal',
166
+ albedo: 'u_albedo',
167
+ roughness: 'u_rough',
168
+ metalness: 'u_metal',
169
+ specular: 'u_spec',
170
+ }
171
+ const HAS: Record<Slot, string | null> = {
172
+ image: null,
173
+ depth: 'u_hasDepth',
174
+ normal: 'u_hasNormal',
175
+ albedo: 'u_hasAlbedo',
176
+ roughness: 'u_hasRough',
177
+ metalness: 'u_hasMetal',
178
+ specular: 'u_hasSpec',
179
+ }
180
+
181
+ function compile(gl: WebGL2RenderingContext): WebGLProgram {
182
+ const prog = gl.createProgram()
183
+ for (const [type, src] of [
184
+ [gl.VERTEX_SHADER, VS],
185
+ [gl.FRAGMENT_SHADER, FS],
186
+ ] as const) {
187
+ const sh = gl.createShader(type)
188
+ if (sh == null) throw new Error('relight: createShader failed')
189
+ gl.shaderSource(sh, src)
190
+ gl.compileShader(sh)
191
+ if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) throw new Error(`relight shader: ${gl.getShaderInfoLog(sh)}`)
192
+ gl.attachShader(prog, sh)
193
+ }
194
+ gl.bindAttribLocation(prog, 0, 'a_uv')
195
+ gl.linkProgram(prog)
196
+ if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) throw new Error(`relight link: ${gl.getProgramInfoLog(prog)}`)
197
+ return prog
198
+ }
199
+
200
+ export class RelightGl {
201
+ private gl: WebGL2RenderingContext
202
+ private prog: WebGLProgram
203
+ private vao: WebGLVertexArrayObject
204
+ private tex = new Map<Slot, WebGLTexture>()
205
+ private has = new Set<Slot>()
206
+ private aspect = 1
207
+ private texel: [number, number] = [1 / 512, 1 / 512]
208
+
209
+ constructor(private canvas: HTMLCanvasElement) {
210
+ const gl = canvas.getContext('webgl2', { antialias: false, preserveDrawingBuffer: true })
211
+ if (gl == null) throw new Error('relight needs WebGL2, which this browser does not offer')
212
+ this.gl = gl
213
+ this.prog = compile(gl)
214
+ this.vao = gl.createVertexArray()
215
+ gl.bindVertexArray(this.vao)
216
+ gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer())
217
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]), gl.STATIC_DRAW)
218
+ gl.enableVertexAttribArray(0)
219
+ gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0)
220
+ gl.bindVertexArray(null)
221
+ for (const s of SLOTS) {
222
+ const t = gl.createTexture()
223
+ gl.bindTexture(gl.TEXTURE_2D, t)
224
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
225
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
226
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
227
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
228
+ gl.texImage2D(
229
+ gl.TEXTURE_2D,
230
+ 0,
231
+ gl.RGBA,
232
+ 1,
233
+ 1,
234
+ 0,
235
+ gl.RGBA,
236
+ gl.UNSIGNED_BYTE,
237
+ new Uint8Array([128, 128, 255, 255]),
238
+ )
239
+ this.tex.set(s, t)
240
+ }
241
+ }
242
+
243
+ /** the maps, any sizes: each is sampled by uv. `aspect` is the photo's width / height */
244
+ setMaps(maps: RelightMaps, aspect: number, width: number, height: number): void {
245
+ const gl = this.gl
246
+ this.aspect = aspect
247
+ this.texel = [1 / Math.max(1, width), 1 / Math.max(1, height)]
248
+ this.has.clear()
249
+ for (const s of SLOTS) {
250
+ const img = maps[s]
251
+ if (img == null) continue
252
+ gl.bindTexture(gl.TEXTURE_2D, this.tex.get(s) ?? null)
253
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img)
254
+ this.has.add(s)
255
+ }
256
+ }
257
+
258
+ hasMap(s: Slot): boolean {
259
+ return this.has.has(s)
260
+ }
261
+
262
+ draw(p: RelightParams): void {
263
+ const gl = this.gl
264
+ const dpr = window.devicePixelRatio || 1
265
+ const w = Math.round(this.canvas.clientWidth * dpr)
266
+ const h = Math.round(this.canvas.clientHeight * dpr)
267
+ if (w === 0 || h === 0) return
268
+ if (this.canvas.width !== w || this.canvas.height !== h) {
269
+ this.canvas.width = w
270
+ this.canvas.height = h
271
+ }
272
+ gl.viewport(0, 0, w, h)
273
+ gl.clearColor(0, 0, 0, 0)
274
+ gl.clear(gl.COLOR_BUFFER_BIT)
275
+ gl.useProgram(this.prog)
276
+ const u = (name: string): WebGLUniformLocation | null => gl.getUniformLocation(this.prog, name)
277
+ SLOTS.forEach((s, i) => {
278
+ gl.activeTexture(gl.TEXTURE0 + i)
279
+ gl.bindTexture(gl.TEXTURE_2D, this.tex.get(s) ?? null)
280
+ gl.uniform1i(u(SAMPLER[s]), i)
281
+ const flag = HAS[s]
282
+ if (flag != null) gl.uniform1i(u(flag), this.has.has(s) ? 1 : 0)
283
+ })
284
+ // the canvas keeps the photo's aspect (css), so the quad fills it
285
+ gl.uniform2f(u('u_fit'), 1, 1)
286
+ gl.uniform1f(u('u_aspect'), this.aspect)
287
+ gl.uniform2f(u('u_texel'), this.texel[0], this.texel[1])
288
+ gl.uniform1f(u('u_depthScale'), p.depthScale)
289
+ gl.uniform1f(u('u_intensity'), p.intensity)
290
+ gl.uniform1f(u('u_falloff'), p.falloff)
291
+ gl.uniform1f(u('u_ambient'), p.ambient)
292
+ gl.uniform1f(u('u_exposure'), p.exposure)
293
+ gl.uniform1f(u('u_moteIntensity'), p.moteIntensity)
294
+ gl.uniform3f(u('u_light'), p.light[0], p.light[1], p.light[2])
295
+ gl.uniform3f(u('u_color'), p.color[0], p.color[1], p.color[2])
296
+ gl.uniform1i(u('u_shadows'), p.shadows ? 1 : 0)
297
+ gl.uniform1i(u('u_showLights'), p.showLights ? 1 : 0)
298
+ gl.uniform1i(u('u_view'), VIEW_INDEX[p.view])
299
+ const n = Math.min(MAX_MOTES, p.motes.length)
300
+ gl.uniform1i(u('u_moteCount'), n)
301
+ if (n > 0) gl.uniform3fv(u('u_motes'), new Float32Array(p.motes.slice(0, n).flat()))
302
+ gl.bindVertexArray(this.vao)
303
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
304
+ }
305
+ }
@@ -0,0 +1,19 @@
1
+ // the output widgets' rules, one string: the panel's stylesheet embeds it, and a page outside the
2
+ // panel (examples/depth-explorer) injects it beside its own. Reads the panel's colour tokens
3
+ export const WIDGET_STYLES = /* css */ `
4
+ .output-widgets { display: flex; flex-direction: column; gap: 10px; margin-bottom: 10px; }
5
+ .relight { border: 1px solid var(--border); border-radius: 8px; overflow: hidden; background: #0b0c10; }
6
+ .relight-stage { display: flex; justify-content: center; background: #07080b; }
7
+ .relight-canvas { display: block; width: 100%; max-height: 70vh; max-width: calc(70vh * 4); object-fit: contain; cursor: crosshair; touch-action: none; }
8
+ .relight-bar { display: flex; flex-direction: column; gap: 6px; padding: 8px 10px; background: var(--panel-2); border-top: 1px solid var(--hairline); }
9
+ .relight-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 14px; }
10
+ .relight-title { font-weight: 600; margin-right: 6px; }
11
+ .relight-segs { display: flex; flex-wrap: wrap; gap: 4px; }
12
+ .relight .seg { font: inherit; font-size: 12px; color: var(--text); background: var(--panel); border: 1px solid var(--border); border-radius: 6px; padding: 3px 9px; cursor: pointer; }
13
+ .relight .seg.on { background: var(--sel-bg); border-color: var(--sel-border); color: var(--sel-text); }
14
+ .relight-slider { display: flex; align-items: center; gap: 6px; font-size: 12px; color: var(--dim); }
15
+ .relight-slider input { width: 92px; accent-color: var(--accent); }
16
+ .relight-color input { width: 28px; height: 22px; padding: 0; border: 1px solid var(--border); border-radius: 4px; background: none; cursor: pointer; }
17
+ .relight-hint { color: var(--dim); font-size: 12px; margin-left: auto; }
18
+ .relight-missing { color: var(--amber); font-size: 12px; padding: 6px 0; }
19
+ `
@@ -38,6 +38,7 @@ export {
38
38
  ComfyExecution,
39
39
  type ComfyAudioOutput,
40
40
  type ComfyVideoOutput,
41
+ type Comfy3DOutput,
41
42
  type ComfyExecutionData,
42
43
  type ComfyTextOutput,
43
44
  type ExecutionPreview,
@@ -113,6 +114,7 @@ export type {
113
114
  VarKind,
114
115
  VarsSpec,
115
116
  VarUi,
117
+ ChoiceOptionLook,
116
118
  AnyChoiceVar,
117
119
  ChoiceSelect,
118
120
  VarValues,
@@ -152,6 +154,14 @@ export {
152
154
  type SlotNameOf,
153
155
  type SlotValueOf,
154
156
  } from 'src/vars/DefinedWorkflow.ts'
157
+ export {
158
+ widget,
159
+ resolveWidgetRoles,
160
+ type OutputWidget,
161
+ type OutputWidgetKind,
162
+ type RelightRoles,
163
+ type RelightWidget,
164
+ } from 'src/vars/outputWidgets.ts'
155
165
  export {
156
166
  clearLoraKeywordOverride,
157
167
  getLoraKeyword,
@@ -542,7 +542,11 @@ export class ComfyNode<
542
542
  }
543
543
 
544
544
  private _getOutputForTypeOrCrash(type: string): ComfyNodeOutput<any> {
545
- const i: NodeOutputExt = this.$schema.outputs.find((i: NodeOutputExt) => i.typeName === type)!
545
+ const i = this.$schema.outputs.find((i: NodeOutputExt) => slotTypeAccepts(type, i.typeName))
546
+ if (i == null)
547
+ throw new Error(
548
+ `🔴 ${this.$schema.nodeKey} has no output of type ${type}: link one of its outputs by name instead`,
549
+ )
546
550
  const val = (this.outputs as any)[i.outKey]
547
551
  // console.log(`this[i.name] = ${this.$schema.name}[${i.name}] = ${val}`)
548
552
  if (val instanceof ComfyNodeOutput) return val
@@ -550,7 +554,7 @@ export class ComfyNode<
550
554
  }
551
555
 
552
556
  private _getOutputForTypeOrNull(type: string): ComfyNodeOutput<any> | null {
553
- const i: Maybe<NodeOutputExt> = this.$schema.outputs.find((i: NodeOutputExt) => i.typeName === type)
557
+ const i: Maybe<NodeOutputExt> = this.$schema.outputs.find((i: NodeOutputExt) => slotTypeAccepts(type, i.typeName))
554
558
  if (i == null) return null
555
559
  const val = (this.outputs as any)[i.outKey]
556
560
  if (val == null) return null
@@ -558,3 +562,9 @@ export class ComfyNode<
558
562
  throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`)
559
563
  }
560
564
  }
565
+
566
+ /** an input typed `MESH,FILE_3D_GLB` takes an output of ANY listed type (ComfyUI's SaveGLB) */
567
+ export function slotTypeAccepts(inputType: string, outputType: string): boolean {
568
+ if (inputType === outputType) return true
569
+ return inputType.includes(',') && inputType.split(',').some((part) => part.trim() === outputType)
570
+ }
@@ -95,6 +95,12 @@ export type ConnectOptions = {
95
95
  timeoutMs?: number
96
96
  }
97
97
 
98
+ /** the host answered a run check route, but not as ComfyUI does (no such route, another shape) */
99
+ export class HostRouteUnusableError extends Error {
100
+ /** name, not instanceof: the cli bundle and dist/index.js each define this class */
101
+ override readonly name = 'HostRouteUnusableError'
102
+ }
103
+
98
104
  /** the host never came up within ConnectOptions.timeoutMs */
99
105
  export class ComfyHostUnreachableError extends Error {
100
106
  /** name, not instanceof: the cli bundle and dist/index.js each define this class */
@@ -460,6 +466,7 @@ export class ComfyHost<ID extends string = string> {
460
466
  /** close the websocket (e.g. to let a script exit) */
461
467
  disconnect = (): void => {
462
468
  this.clearConnectTimer()
469
+ this.stopWatchdog()
463
470
  this.ws?.disconnectPermanently()
464
471
  this.ws = null
465
472
  this._ready = null
@@ -543,6 +550,9 @@ export class ComfyHost<ID extends string = string> {
543
550
  this.ws = new ResilientWebSocketClient({
544
551
  onConnectOrReconnect: async (): Promise<void> => {
545
552
  logInfo(`[👢] WEBSOCKET: connected to ComfyUI host ${this.data.id}`)
553
+ this._socketIsNew = true
554
+ // events sent while the socket was down are lost for good: each run in flight asks
555
+ void this.reconcileRuns([...this.executions.values()], 'reconnect')
546
556
  if (this.shouldUseSchemaCache()) {
547
557
  try {
548
558
  await this.loadSchemaFromCache()
@@ -561,7 +571,12 @@ export class ComfyHost<ID extends string = string> {
561
571
  this.markReady()
562
572
  },
563
573
  onMessage: (e: WsMessageEvent): void => this.onMessage(e),
564
- url: () => this.getWSUrl(),
574
+ // a reconnect keeps the session: ComfyUI routes a prompt's events to the client_id it
575
+ // was posted with, and drops them when that session has no socket
576
+ url: () =>
577
+ this.comfySessionId === 'temp'
578
+ ? this.getWSUrl()
579
+ : `${this.getWSUrl()}?clientId=${encodeURIComponent(this.comfySessionId)}`,
565
580
  // auth rides the upgrade headers; headerless transports (browser)
566
581
  // remap X-API-Key to ?token= inside the ws client
567
582
  headers: () => this.authHeaders(),
@@ -634,6 +649,135 @@ export class ComfyHost<ID extends string = string> {
634
649
  if (!res.ok) throw new Error(`POST ${route} failed on ${this.getServerHostHTTP()}: ${res.status}`)
635
650
  }
636
651
 
652
+ /** GET a json route for the run checks: an answer that is not json (a 404, a 405, a page) means the
653
+ * host has no such route, a HostRouteUnusableError; a network failure stays a plain error */
654
+ private fetchReconcileJSON_ = async (route: string): Promise<unknown> => {
655
+ const res = await this.fetch(route)
656
+ const contentType = res.headers.get('content-type') ?? ''
657
+ if (res.ok && contentType.includes('json')) return res.json()
658
+ void res.body?.cancel()
659
+ throw new HostRouteUnusableError(`GET ${route} answered ${res.status} ${contentType || 'no content-type'}`)
660
+ }
661
+
662
+ /** one prompt's `GET /history/<id>` reply, `{}` while the host has no entry for it */
663
+ fetchHistory = (promptId: PromptID): Promise<unknown> => {
664
+ return this.fetchReconcileJSON_(`/history/${encodeURIComponent(promptId)}`)
665
+ }
666
+
667
+ /** the ids of the prompts waiting or running on this host, every client counted (`GET /queue`) */
668
+ fetchQueuedPromptIds = async (): Promise<Set<string>> => {
669
+ const json = await this.fetchReconcileJSON_('/queue')
670
+ const ids = new Set<string>()
671
+ for (const key of ['queue_running', 'queue_pending']) {
672
+ const list: unknown = typeof json === 'object' && json != null ? Reflect.get(json, key) : null
673
+ if (!Array.isArray(list)) throw new HostRouteUnusableError(`GET /queue has no ${key} list`)
674
+ // an item of another shape (a cloud host) could hide a run: refuse the whole answer
675
+ for (const item of list) {
676
+ if (!Array.isArray(item) || typeof item[1] !== 'string')
677
+ throw new HostRouteUnusableError(`GET /queue: an item of ${key} is not [number, prompt_id, …]`)
678
+ ids.add(item[1])
679
+ }
680
+ }
681
+ return ids
682
+ }
683
+
684
+ /** why runs on this host are never checked over http: its /queue or /history is not ComfyUI's
685
+ * (a cloud host). Null while both answered as ComfyUI does, or were never asked */
686
+ reconcileOff: string | null = null
687
+
688
+ /** @internal a failed run check: true when it proved the host has no usable route (the checks then
689
+ * stop for good, said once), false for a passing failure the caller reports */
690
+ noteReconcileFailure(e: unknown): boolean {
691
+ if (!(e instanceof Error) || e.name !== 'HostRouteUnusableError') return false
692
+ if (this.reconcileOff == null) {
693
+ this.reconcileOff = e.message
694
+ this.stopWatchdog()
695
+ logInfo(`host '${this.data.id}': ${e.message}, not the ComfyUI shape: runs here are not checked over http, they wait for their events`)
696
+ }
697
+ return true
698
+ }
699
+
700
+ /** fetchQueuedPromptIds, null when the queue did not answer (logged once per message) or has another
701
+ * shape: a run is then never declared lost */
702
+ fetchQueuedPromptIdsOrNull = async (): Promise<Set<string> | null> => {
703
+ try {
704
+ return await this.fetchQueuedPromptIds()
705
+ } catch (e) {
706
+ if (this.noteReconcileFailure(e)) return null
707
+ const msg = extractErrorMessage(e)
708
+ if (!this._loggedQueueProblems.has(msg)) {
709
+ this._loggedQueueProblems.add(msg)
710
+ toastError(`host '${this.data.id}': its queue did not answer (${msg}); no run is failed as lost until it does`)
711
+ }
712
+ return null
713
+ }
714
+ }
715
+ private _loggedQueueProblems = new Set<string>()
716
+
717
+ // RUN WATCHDOG (architecture.md, ResilientWebsocket.ts) -------------------------------
718
+ /** a check needs the WHOLE socket quiet this long, and the run itself too */
719
+ runSilenceMs: number = 1000
720
+ /** the wait doubles after each check that ends no run, up to this; any ws message resets it */
721
+ runSilenceMaxMs: number = 30_000
722
+ private _silenceWaitMs: number | null = null
723
+ private _lastCheckAt: number = 0
724
+ private _checking: boolean = false
725
+ private _watchdog: Maybe<ReturnType<typeof setInterval>> = null
726
+
727
+ /** @internal a new run routes its ws messages here, and the watchdog watches it */
728
+ trackExecution(execution: ComfyExecution): void {
729
+ this.executions.set(execution.data.id, execution)
730
+ // a run with no socket (tests that drive messages by hand) has nothing to watch
731
+ if (this.ws == null || this._watchdog != null || this.reconcileOff != null) return
732
+ this._watchdog = setInterval(() => this.watchdogTick(), Math.min(250, this.runSilenceMs))
733
+ this._watchdog.unref?.()
734
+ }
735
+
736
+ private stopWatchdog(): void {
737
+ if (this._watchdog != null) clearInterval(this._watchdog)
738
+ this._watchdog = null
739
+ }
740
+
741
+ /** a socket that hears no broadcast and no event for a while is deaf, or the host runs one long
742
+ * quiet node: ask. A run queued behind a talking host is never asked about */
743
+ private watchdogTick(): void {
744
+ if (this.executions.size === 0 || this.ws == null) return this.stopWatchdog()
745
+ if (this._checking) return
746
+ const now = Date.now()
747
+ const wait = this._silenceWaitMs ?? this.runSilenceMs
748
+ if (now - Math.max(this.lastWsMessageAt ?? 0, this._lastCheckAt) < wait) return
749
+ const due = [...this.executions.values()].filter((e) => !e.reconciling && now - e.lastHeardAt >= this.runSilenceMs)
750
+ if (due.length === 0) return
751
+ this._checking = true
752
+ void this.reconcileRuns(due, 'silence').finally(() => {
753
+ this._checking = false
754
+ this._lastCheckAt = Date.now()
755
+ this._silenceWaitMs = Math.min(wait * 2, this.runSilenceMaxMs)
756
+ })
757
+ }
758
+
759
+ /** @internal one queue read for all the runs, then the history of each run not in it. A run that
760
+ * ends from its history while the socket looked fine means the socket hears nothing: ComfyUI removes
761
+ * a session BY KEY when a socket's handler ends, so an old handler that ends after a reconnect evicts
762
+ * the new socket of the same session. A clean close lets the server end that handler first */
763
+ async reconcileRuns(runs: ComfyExecution[], why: 'reconnect' | 'silence'): Promise<void> {
764
+ if (this.reconcileOff != null) return
765
+ const todo = runs.filter((r) => !r.reconciling)
766
+ if (todo.length === 0) return
767
+ for (const r of todo) r.beginReconcile(why)
768
+ const queued = await this.fetchQueuedPromptIdsOrNull()
769
+ if (this.reconcileOff != null) {
770
+ for (const r of todo) r.reconciling = false
771
+ return
772
+ }
773
+ const verdicts = await Promise.all(todo.map((r) => r.reconcile(queued)))
774
+ if (why === 'silence' && verdicts.includes('history') && this.ws?.isOpen === true) {
775
+ toastError(`host '${this.data.id}': a run ended without its end reaching the socket, which hears nothing; reconnecting`)
776
+ this.ws.reconnect()
777
+ }
778
+ }
779
+
780
+
637
781
  /** drop every PENDING prompt from the server queue (the running one keeps going) */
638
782
  clearQueue = (): Promise<void> => {
639
783
  return this.postJSON_('/queue', { clear: true })
@@ -870,6 +1014,9 @@ export class ComfyHost<ID extends string = string> {
870
1014
  private _unknownBinaryFrameTypes = new Set<number>()
871
1015
  private _unknownWsEventTypes = new Set<string>()
872
1016
 
1017
+ /** the socket opened and its first 'status' has not come yet */
1018
+ private _socketIsNew: boolean = false
1019
+
873
1020
  /** handy to keep around */
874
1021
  status: ComfyStatusData['status'] | null = null
875
1022
 
@@ -915,6 +1062,7 @@ export class ComfyHost<ID extends string = string> {
915
1062
 
916
1063
  onMessage(e: WsMessageEvent): void {
917
1064
  this.lastWsMessageAt = Date.now()
1065
+ this._silenceWaitMs = null
918
1066
  if (this.data.onWsMessageAny) this.data.onWsMessageAny(e)
919
1067
  if (e.data instanceof ArrayBuffer) {
920
1068
  if (isPreviewFrameType(binaryFrameType(e.data))) return this.onPreviewFrame(e.data)
@@ -974,10 +1122,13 @@ export class ComfyHost<ID extends string = string> {
974
1122
  if (msg.type === 'status') {
975
1123
  if (msg.data.sid) {
976
1124
  const sidChanged = msg.data.sid !== this.comfySessionId
1125
+ const socketIsNew = this._socketIsNew
1126
+ this._socketIsNew = false
977
1127
  this.comfySessionId = msg.data.sid
978
1128
  this._sessionResolve?.()
979
1129
  this._sessionResolve = null
980
- if (sidChanged) {
1130
+ // a reconnect keeps its sid (?clientId=), and still starts a new connection
1131
+ if (sidChanged || socketIsNew) {
981
1132
  this._unknownWsEventTypes.clear()
982
1133
  this._unknownBinaryFrameTypes.clear()
983
1134
  this.onSession?.(msg.data.sid)
@@ -77,6 +77,7 @@ export class ResilientWebSocketClient {
77
77
 
78
78
  constructor(
79
79
  public options: {
80
+ /** re-read on every connect */
80
81
  url: () => string
81
82
  /** upgrade-request headers (auth: X-API-Key & co) — a thunk, re-read on every reconnect.
82
83
  * On a headerless transport (browser) X-API-Key rides `?token=` instead
@@ -149,6 +150,13 @@ export class ResilientWebSocketClient {
149
150
  }, ms)
150
151
  }
151
152
 
153
+ /** close the socket cleanly, then reconnect as after any close: the server ends its handler first */
154
+ reconnect(): void {
155
+ if (this.permanentlyClosed || this.currentWS == null) return
156
+ this.addInfo('closing the socket to reconnect')
157
+ this.currentWS.close()
158
+ }
159
+
152
160
  /** close and stop reconnecting (lets a script exit cleanly) */
153
161
  disconnectPermanently(): void {
154
162
  this.permanentlyClosed = true
@@ -175,6 +183,8 @@ export class ResilientWebSocketClient {
175
183
 
176
184
  private async connect(): Promise<void> {
177
185
  this.isOpen = false
186
+ // re-read: a reconnect asks the server for the session the socket had (?clientId=)
187
+ this.url = this.options.url()
178
188
  const prevWS = this.currentWS
179
189
 
180
190
  // cleanup a possible re-connection timeout for an other url
@@ -17,10 +17,3 @@ console.log(` custom node keys: ${registry.plugins_byNodeKey.size}`)
17
17
  console.log(` models: ${registry.knownModels.size}`)
18
18
  console.log(` alterations: ${registry.alterations.length}`)
19
19
  console.log(` github stats: ${registry.githubStats.size}`)
20
-
21
- // the generator aligns its own `// x N` comments and emits trailing blank
22
- // lines; oxfmt disagrees on both, so WITHOUT this the ci gate goes red right
23
- // after any regeneration. Runs here, not chained in package.json: a `&&` there
24
- // swallows this script's own flags (`--skip-download` landed on oxfmt).
25
- const fmt = Bun.spawnSync(['oxfmt', 'src/manager/generated'], { stdout: 'inherit', stderr: 'inherit' })
26
- if (fmt.exitCode !== 0) throw new Error(`🔴 oxfmt failed on src/manager/generated (exit ${fmt.exitCode})`)