comfy-ts 2.22.0 → 2.24.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 (99) hide show
  1. package/dist/{ServeApp-DuxYdaZZ.js → ServeApp-fsHtW5zG.js} +51 -17
  2. package/dist/ServeApp-fsHtW5zG.js.map +1 -0
  3. package/dist/cli.js +5 -5
  4. package/dist/{exampleAssets-1NHndnNB.js → exampleAssets-DZynSkZm.js} +405 -39
  5. package/dist/exampleAssets-DZynSkZm.js.map +1 -0
  6. package/dist/{findDefinedWorkflow-CRsBTTJK.js → findDefinedWorkflow-qyqFea7q.js} +2 -2
  7. package/dist/{findDefinedWorkflow-CRsBTTJK.js.map → findDefinedWorkflow-qyqFea7q.js.map} +1 -1
  8. package/dist/index.cjs +428 -46
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +147 -1
  11. package/dist/index.d.ts +147 -1
  12. package/dist/index.js +428 -47
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-run-Y5ZI48vV.js → run-run-Cn2JzKlE.js} +5 -5
  15. package/dist/{run-run-Y5ZI48vV.js.map → run-run-Cn2JzKlE.js.map} +1 -1
  16. package/dist/{run-serve-CICU_wTL.js → run-serve-BhGegaCI.js} +4 -4
  17. package/dist/{run-serve-CICU_wTL.js.map → run-serve-BhGegaCI.js.map} +1 -1
  18. package/dist/{run-tui-CViJXsHL.js → run-tui-CrM4ijkH.js} +4 -4
  19. package/dist/{run-tui-CViJXsHL.js.map → run-tui-CrM4ijkH.js.map} +1 -1
  20. package/dist/{schemaDrift-CzjaIwZX.js → schemaDrift-BGYJZGMD.js} +18 -3
  21. package/dist/{schemaDrift-CzjaIwZX.js.map → schemaDrift-BGYJZGMD.js.map} +1 -1
  22. package/dist/serve-web.js +46 -43
  23. package/dist/web.d.ts +147 -1
  24. package/dist/web.js +428 -47
  25. package/dist/web.js.map +1 -1
  26. package/examples/README.md +1 -0
  27. package/examples/comfy-cloud/sdk.d.ts +102 -1
  28. package/examples/depth-explorer/models.ts +6 -56
  29. package/examples/depth-explorer/serve.ts +12 -133
  30. package/examples/depth-explorer/web/App.tsx +20 -91
  31. package/examples/depth-explorer/web/index.html +1 -0
  32. package/examples/depth-explorer/web/state.ts +26 -109
  33. package/examples/depth-explorer/web/styles.css +1 -286
  34. package/examples/explorer-kit/catalog.ts +80 -0
  35. package/examples/explorer-kit/server.ts +167 -0
  36. package/examples/explorer-kit/web/base.css +289 -0
  37. package/examples/explorer-kit/web/runs.ts +160 -0
  38. package/examples/explorer-kit/web/ui.tsx +125 -0
  39. package/examples/rvion/17-relight.cflow.ts +2 -1
  40. package/examples/rvion/18-world.cflow.ts +101 -0
  41. package/examples/rvion/19-flythrough.cflow.ts +312 -0
  42. package/examples/rvion/20-grow-splat.cflow.ts +88 -0
  43. package/examples/rvion/21-photo-to-model.cflow.ts +191 -0
  44. package/examples/rvion/flythroughChain.ts +171 -0
  45. package/examples/rvion/flythroughColmap.ts +157 -0
  46. package/examples/rvion/flythroughFuse.ts +199 -0
  47. package/examples/rvion/flythroughGuide.ts +300 -0
  48. package/examples/rvion/flythroughPalette.ts +310 -0
  49. package/examples/rvion/flythroughPath.ts +177 -0
  50. package/examples/rvion/flythroughSplat.ts +73 -0
  51. package/examples/rvion/grow-splat/align.ts +114 -0
  52. package/examples/rvion/grow-splat/grow.ts +198 -0
  53. package/examples/rvion/grow-splat/ply.ts +166 -0
  54. package/examples/rvion/grow-splat/raster.ts +207 -0
  55. package/examples/rvion/grow-splat/sharp.ts +45 -0
  56. package/examples/rvion/splatDataset.ts +80 -0
  57. package/examples/rvion/splatEval.ts +380 -0
  58. package/examples/upscale-explorer/models.ts +341 -0
  59. package/examples/upscale-explorer/serve.ts +19 -0
  60. package/examples/upscale-explorer/web/App.tsx +250 -0
  61. package/examples/upscale-explorer/web/compare.tsx +285 -0
  62. package/examples/upscale-explorer/web/index.html +15 -0
  63. package/examples/upscale-explorer/web/main.tsx +12 -0
  64. package/examples/upscale-explorer/web/state.ts +279 -0
  65. package/examples/upscale-explorer/web/styles.css +241 -0
  66. package/examples/upscale-explorer/web/tsconfig.json +16 -0
  67. package/examples/upscale-explorer/web/viewport.tsx +130 -0
  68. package/examples/world-explorer/serve.ts +171 -0
  69. package/examples/world-explorer/web/index.html +14 -0
  70. package/examples/world-explorer/web/main.tsx +200 -0
  71. package/examples/world-explorer/web/state.ts +212 -0
  72. package/examples/world-explorer/web/styles.css +131 -0
  73. package/examples/world-explorer/web/thumb.ts +21 -0
  74. package/examples/world-explorer/web/tsconfig.json +11 -0
  75. package/examples/world-explorer/world-state.ts +40 -0
  76. package/package.json +7 -8
  77. package/src/cli/serve/ServeApp.ts +27 -2
  78. package/src/cli/serve/resultHistory.ts +22 -4
  79. package/src/cli/serve/thumbs.ts +19 -8
  80. package/src/cli/serve/web/api.ts +4 -0
  81. package/src/cli/serve/web/components/Gallery.tsx +24 -1
  82. package/src/cli/serve/web/styles.ts +3 -0
  83. package/src/coreExports.ts +6 -0
  84. package/src/graph/ComfyNode.ts +12 -2
  85. package/src/host/ComfyHost.ts +159 -2
  86. package/src/host/ResilientWebsocket.ts +10 -0
  87. package/src/manager/script-update-manager.bun.ts +0 -7
  88. package/src/runner/ComfyExecution.ts +185 -23
  89. package/src/runner/ComfyWorkflow.ts +22 -0
  90. package/src/runner/ComfyWsApi.ts +3 -1
  91. package/src/runner/comfyOrgApiKey.ts +44 -0
  92. package/src/runner/historyReplay.ts +53 -0
  93. package/src/runner/outputs3d.ts +18 -0
  94. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +2 -0
  95. package/src/sdk-generator/comfyui-sdk-codegen.ts +7 -2
  96. package/src/state.ts +2 -0
  97. package/src/vars/DefinedWorkflow.ts +1 -0
  98. package/dist/ServeApp-DuxYdaZZ.js.map +0 -1
  99. package/dist/exampleAssets-1NHndnNB.js.map +0 -1
@@ -0,0 +1,167 @@
1
+ // the server of an explorer page: the catalog with its live availability, the sample images, the
2
+ // uploaded source (by content hash, sent once by the page), and one ComfyUI prompt per run, so
3
+ // each card fills as its model finishes and one failure stays one card. The result never touches
4
+ // the host disk: the graph ends in SaveImageWebsocket.
5
+ import { createHash } from 'node:crypto'
6
+ import { readdirSync } from 'node:fs'
7
+ import { ComfyTS, exampleImagePath, MediaImage, type BaseNode, type ComfyWorkflow } from 'comfy-ts'
8
+ import { basename, dirname, resolve } from 'pathe'
9
+ import { availability, entryPayload, type CatalogEntry } from './catalog.ts'
10
+
11
+ export type HostId = 'windows-1'
12
+ export type ExplorerWf = ComfyWorkflow<HostId>
13
+ export type ExplorerImg = Comfy.Windows1.Accepts['IMAGE']
14
+
15
+ export type ExplorerSpec<E extends CatalogEntry, P> = {
16
+ /** the page title in the log line, and the workflow id prefix */
17
+ name: string
18
+ port: number
19
+ page: Bun.HTMLBundle
20
+ catalog: E[]
21
+ /** what a card shows beyond the shared facts */
22
+ card?: (m: E) => Record<string, unknown>
23
+ /** the run's settings out of its json body (beside `image` and `model`): checked and clamped, or a throw */
24
+ readParams: (raw: Record<string, unknown>) => P
25
+ /** the graph up to its output image; the server adds the websocket save node */
26
+ build: (wf: ExplorerWf, image: ExplorerImg, m: E, p: P) => ExplorerImg | BaseNode
27
+ }
28
+
29
+ const HOST_ID: HostId = 'windows-1'
30
+ const KEEP_RESULTS = 48
31
+
32
+ /** `box`: ComfyUI reused a prompt it ran before, so no node but the save ran and `ms` is the transfer */
33
+ type Result = { bytes: Uint8Array<ArrayBuffer>; type: string; ms: number; box: boolean }
34
+
35
+ const json = (data: unknown, status = 200): Response => Response.json(data, { status })
36
+
37
+ /** the bundled example images, plus every `--samples <dir>` of argv: name → file */
38
+ function samplesOf(argv: string[]): Map<string, string> {
39
+ const out = new Map<string, string>()
40
+ const dirs = [dirname(exampleImagePath('dog_512x512.jpg'))]
41
+ for (let i = 2; i < argv.length; i++)
42
+ if (argv[i] === '--samples' && argv[i + 1] != null) dirs.push(resolve(String(argv[++i])))
43
+ for (const dir of dirs)
44
+ for (const f of readdirSync(dir)) if (/\.(jpe?g|png|webp)$/i.test(f)) out.set(f, `${dir}/${f}`)
45
+ return out
46
+ }
47
+
48
+ export async function serveExplorer<E extends CatalogEntry, P>(p: ExplorerSpec<E, P>): Promise<void> {
49
+ const comfy = ComfyTS.create()
50
+ // COMFY_URL: another road to the same box (the ssh tunnel on 127.0.0.1:8085 when the tailnet is down)
51
+ const url = process.env.COMFY_URL
52
+ const host = comfy.host(url != null ? { id: HOST_ID, url } : { id: HOST_ID })
53
+ // a live schema: availability reads the loaders' file lists, and a weight downloaded since the
54
+ // cache was written must show up as runnable
55
+ await host.connect({ schema: 'refresh' })
56
+
57
+ const images = new Map<string, Uint8Array>()
58
+ /** the last runs by (image, model, params), in flight or done: a reload of the page gets them
59
+ * back at once (their time the run's own), and a second ask while one runs waits for it */
60
+ const runs = new Map<string, Promise<Result>>()
61
+ const answer = (r: Result, kept: boolean): Response =>
62
+ new Response(r.bytes, {
63
+ headers: {
64
+ 'content-type': `image/${r.type}`,
65
+ 'x-ms': String(r.ms),
66
+ 'x-cached': r.box ? 'box' : kept ? 'server' : 'no',
67
+ },
68
+ })
69
+ const samplePaths = samplesOf(process.argv)
70
+ const slug = p.name.replaceAll(' ', '-')
71
+
72
+ const modelsPayload = (): unknown => {
73
+ const info = host.schema.data.spec
74
+ return { host: HOST_ID, models: p.catalog.map((m) => ({ ...entryPayload(info, m), ...p.card?.(m) })) }
75
+ }
76
+
77
+ const run = async (raw: unknown): Promise<Response> => {
78
+ if (typeof raw !== 'object' || raw == null) return json({ error: 'body must be a json object' }, 400)
79
+ const body = Object.fromEntries(Object.entries(raw))
80
+ if (typeof body.image !== 'string' || typeof body.model !== 'string')
81
+ return json({ error: 'body needs { image: string, model: string }' }, 400)
82
+ const model = p.catalog.find((m) => m.id === body.model)
83
+ if (model == null) return json({ error: `unknown model ${body.model}` }, 404)
84
+ const avail = availability(host.schema.data.spec, model)
85
+ if (!avail.ok) return json({ error: 'not on this host', ...avail }, 409)
86
+ const bytes = images.get(body.image)
87
+ if (bytes == null) return json({ error: 'unknown image, upload it again' }, 404)
88
+ const params = p.readParams(body)
89
+ const key = `${body.image}:${model.id}:${JSON.stringify(params)}`
90
+ const kept = runs.get(key)
91
+ if (kept != null) return answer(await kept, true)
92
+ const fresh = runOnce(bytes, model, params)
93
+ runs.set(key, fresh)
94
+ // a failed run is never kept; the oldest results leave first (a 12 MP png weighs 15 to 30 MB)
95
+ fresh.catch(() => runs.delete(key))
96
+ for (const old of runs.keys()) {
97
+ if (runs.size <= KEEP_RESULTS) break
98
+ runs.delete(old)
99
+ }
100
+ return answer(await fresh, false)
101
+ }
102
+
103
+ const runOnce = async (bytes: Uint8Array, model: E, params: P): Promise<Result> => {
104
+ const started = performance.now()
105
+ const wf = host.workflow({ id: `${slug}-${model.id}` })
106
+ const loaded = await new MediaImage({ buffer: bytes }).loadInWorkflow_viaLoadImageNode(wf)
107
+ const out = p.build(wf, loaded, model, params)
108
+ const save = wf.builderBase.SaveImageWebsocket
109
+ if (save == null) throw new Error('this host has no SaveImageWebsocket node')
110
+ save({ images: out })
111
+ const execution = await wf.run({ scrubHistory: true })
112
+ const ms = Math.round(performance.now() - started)
113
+ const first = execution.images[0]
114
+ if (execution.status !== 'Success' || first == null) {
115
+ // ComfyUI's own reason (a missing weight, an oom) sits in the error message's data
116
+ const err = execution.data.error
117
+ const message =
118
+ err != null && 'exception_message' in err.data
119
+ ? `${err.data.node_type ?? 'a node'}: ${err.data.exception_message}`
120
+ : `run ended ${execution.status}, no image`
121
+ console.error(`🔴 ${model.id}: ${message}`)
122
+ throw new Error(message)
123
+ }
124
+ const box = !wf.nodes.some((n) => n.status === 'done' && n.json.class_type !== 'SaveImageWebsocket')
125
+ console.log(`🟢 ${model.id} ${ms} ms${box ? ' (the box reused its cache)' : ''}`)
126
+ return { bytes: first.buffer as Uint8Array<ArrayBuffer>, type: first.metadata.type ?? 'png', ms, box }
127
+ }
128
+
129
+ const server = Bun.serve({
130
+ port: Number(process.env.PORT ?? p.port),
131
+ hostname: '127.0.0.1',
132
+ development: true,
133
+ idleTimeout: 255, // a cold model load on the GPU box takes minutes
134
+ routes: {
135
+ '/': p.page,
136
+ '/api/models': () => json(modelsPayload()),
137
+ '/api/samples': () => json([...samplePaths.keys()]),
138
+ '/api/samples/:name': (req) => {
139
+ const path = samplePaths.get(basename(req.params.name))
140
+ if (path == null) return json({ error: 'no such sample' }, 404)
141
+ return new Response(Bun.file(path))
142
+ },
143
+ '/api/image': {
144
+ POST: async (req) => {
145
+ const bytes = new Uint8Array(await req.arrayBuffer())
146
+ if (bytes.length === 0) return json({ error: 'empty body' }, 400)
147
+ const key = createHash('sha1').update(bytes).digest('hex').slice(0, 16)
148
+ images.set(key, bytes)
149
+ return json({ key })
150
+ },
151
+ },
152
+ '/api/run': {
153
+ POST: async (req) => {
154
+ try {
155
+ return await run(await req.json())
156
+ } catch (e) {
157
+ const message = e instanceof Error ? e.message : String(e)
158
+ console.error('🔴 run failed:', message)
159
+ return json({ error: message }, 500)
160
+ }
161
+ },
162
+ },
163
+ },
164
+ })
165
+
166
+ console.log(`${p.name} → http://127.0.0.1:${server.port}/ (host ${HOST_ID})`)
167
+ }
@@ -0,0 +1,289 @@
1
+ /* the look every explorer page shares: tokens, sidebar, source picker, grid of cards, focus box */
2
+ :root {
3
+ --bg: #111316;
4
+ --panel: #181b20;
5
+ --card: #1d2127;
6
+ --line: #2a2f37;
7
+ --text: #e6e8eb;
8
+ --dim: #8a929c;
9
+ --accent: #6aa8ff;
10
+ --err: #ff7a7a;
11
+ color-scheme: dark;
12
+ }
13
+ * {
14
+ box-sizing: border-box;
15
+ }
16
+ body {
17
+ margin: 0;
18
+ background: var(--bg);
19
+ color: var(--text);
20
+ font:
21
+ 13px/1.4 ui-sans-serif,
22
+ system-ui,
23
+ -apple-system,
24
+ sans-serif;
25
+ }
26
+ button,
27
+ select,
28
+ a.ghost {
29
+ font: inherit;
30
+ color: var(--text);
31
+ background: var(--card);
32
+ border: 1px solid var(--line);
33
+ border-radius: 6px;
34
+ padding: 5px 10px;
35
+ cursor: pointer;
36
+ text-decoration: none;
37
+ }
38
+ button:disabled {
39
+ opacity: 0.45;
40
+ cursor: default;
41
+ }
42
+ button.primary {
43
+ background: var(--accent);
44
+ border-color: var(--accent);
45
+ color: #0b1220;
46
+ font-weight: 600;
47
+ width: 100%;
48
+ padding: 8px;
49
+ margin-top: 14px;
50
+ }
51
+ .ghost {
52
+ background: transparent;
53
+ }
54
+ .dim {
55
+ color: var(--dim);
56
+ }
57
+ .small {
58
+ font-size: 12px;
59
+ margin-top: 6px;
60
+ }
61
+ .err {
62
+ color: var(--err);
63
+ display: flex;
64
+ flex-direction: column;
65
+ gap: 6px;
66
+ padding: 10px;
67
+ font-size: 12px;
68
+ overflow: auto;
69
+ }
70
+ .app {
71
+ min-height: 100vh;
72
+ display: flex;
73
+ flex-direction: column;
74
+ }
75
+ header {
76
+ display: flex;
77
+ align-items: baseline;
78
+ gap: 14px;
79
+ padding: 12px 20px;
80
+ border-bottom: 1px solid var(--line);
81
+ }
82
+ h1 {
83
+ font-size: 16px;
84
+ margin: 0;
85
+ }
86
+ h2 {
87
+ font-size: 12px;
88
+ text-transform: uppercase;
89
+ letter-spacing: 0.08em;
90
+ color: var(--dim);
91
+ margin: 4px 0 10px;
92
+ }
93
+ .body {
94
+ display: flex;
95
+ flex: 1;
96
+ min-height: 0;
97
+ }
98
+ aside {
99
+ width: 280px;
100
+ flex-shrink: 0;
101
+ padding: 16px;
102
+ border-right: 1px solid var(--line);
103
+ background: var(--panel);
104
+ }
105
+ aside label {
106
+ display: block;
107
+ color: var(--dim);
108
+ margin: 14px 0 6px;
109
+ }
110
+ label.check {
111
+ display: flex;
112
+ gap: 8px;
113
+ align-items: center;
114
+ color: var(--text);
115
+ margin: 10px 0 0;
116
+ cursor: pointer;
117
+ }
118
+ .drop {
119
+ border: 1px dashed var(--line);
120
+ border-radius: 8px;
121
+ min-height: 140px;
122
+ display: grid;
123
+ place-items: center;
124
+ cursor: pointer;
125
+ overflow: hidden;
126
+ }
127
+ .drop.over {
128
+ border-color: var(--accent);
129
+ }
130
+ .drop img {
131
+ display: block;
132
+ width: 100%;
133
+ }
134
+ .samples {
135
+ display: flex;
136
+ gap: 6px;
137
+ flex-wrap: wrap;
138
+ margin-top: 10px;
139
+ }
140
+ .samples img {
141
+ width: 40px;
142
+ height: 40px;
143
+ object-fit: cover;
144
+ border-radius: 4px;
145
+ cursor: pointer;
146
+ opacity: 0.8;
147
+ }
148
+ .samples img:hover {
149
+ opacity: 1;
150
+ }
151
+ .seg {
152
+ display: flex;
153
+ }
154
+ .seg button {
155
+ flex: 1;
156
+ border-radius: 0;
157
+ }
158
+ .seg button:first-child {
159
+ border-radius: 6px 0 0 6px;
160
+ }
161
+ .seg button:last-child {
162
+ border-radius: 0 6px 6px 0;
163
+ }
164
+ .seg button.on {
165
+ background: #2c3542;
166
+ border-color: var(--accent);
167
+ }
168
+ main {
169
+ flex: 1;
170
+ padding: 16px 20px 40px;
171
+ overflow: auto;
172
+ }
173
+ section + section {
174
+ margin-top: 24px;
175
+ }
176
+ .grid {
177
+ display: grid;
178
+ grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
179
+ gap: 14px;
180
+ }
181
+ .card {
182
+ background: var(--card);
183
+ border: 1px solid var(--line);
184
+ border-radius: 8px;
185
+ overflow: hidden;
186
+ }
187
+ .card.off {
188
+ opacity: 0.6;
189
+ }
190
+ .cardHead {
191
+ display: flex;
192
+ justify-content: space-between;
193
+ gap: 8px;
194
+ padding: 8px 10px;
195
+ }
196
+ .name {
197
+ font-weight: 600;
198
+ }
199
+ .fam {
200
+ font-weight: 400;
201
+ color: var(--dim);
202
+ }
203
+ .meta {
204
+ color: var(--dim);
205
+ white-space: nowrap;
206
+ }
207
+ .frame {
208
+ background: #0c0d0f;
209
+ display: grid;
210
+ place-items: center;
211
+ position: relative;
212
+ overflow: hidden;
213
+ }
214
+ .card.done .frame {
215
+ cursor: zoom-in;
216
+ }
217
+ .frame > img,
218
+ .frame > canvas {
219
+ width: 100%;
220
+ height: 100%;
221
+ object-fit: contain;
222
+ display: block;
223
+ }
224
+ .frame .dim {
225
+ display: flex;
226
+ flex-direction: column;
227
+ align-items: center;
228
+ gap: 4px;
229
+ }
230
+ .blurb {
231
+ padding: 8px 10px;
232
+ color: var(--dim);
233
+ font-size: 12px;
234
+ }
235
+ .missing {
236
+ display: flex;
237
+ flex-direction: column;
238
+ gap: 4px;
239
+ padding: 10px;
240
+ font-size: 11px;
241
+ word-break: break-all;
242
+ }
243
+ .missing a {
244
+ color: var(--accent);
245
+ }
246
+ .spin {
247
+ display: inline-block;
248
+ width: 12px;
249
+ height: 12px;
250
+ border: 2px solid var(--line);
251
+ border-top-color: var(--accent);
252
+ border-radius: 50%;
253
+ animation: spin 0.8s linear infinite;
254
+ vertical-align: -2px;
255
+ }
256
+ @keyframes spin {
257
+ to {
258
+ transform: rotate(360deg);
259
+ }
260
+ }
261
+ .focus {
262
+ position: fixed;
263
+ inset: 0;
264
+ background: rgba(0, 0, 0, 0.75);
265
+ display: grid;
266
+ place-items: center;
267
+ padding: 24px;
268
+ z-index: 10;
269
+ }
270
+ .focusBox {
271
+ background: var(--panel);
272
+ border: 1px solid var(--line);
273
+ border-radius: 10px;
274
+ width: min(1200px, 100%);
275
+ max-height: 100%;
276
+ display: flex;
277
+ flex-direction: column;
278
+ overflow: hidden;
279
+ }
280
+ .focusBar {
281
+ display: flex;
282
+ align-items: center;
283
+ gap: 10px;
284
+ padding: 10px 14px;
285
+ border-bottom: 1px solid var(--line);
286
+ }
287
+ .focusBar b {
288
+ margin-right: auto;
289
+ }
@@ -0,0 +1,160 @@
1
+ // what every explorer page shares: the catalog and samples from its server, the uploaded source
2
+ // image, and a sequential run queue (one prompt at a time on the GPU), one RunSt per result key.
3
+ import { makeAutoObservable, runInAction } from 'mobx'
4
+
5
+ export type WeightFile = { node: string; input: string; file: string; folder: string; url: string }
6
+
7
+ /** a catalog entry as the server sends it (examples/explorer-kit/catalog.ts `entryPayload`) */
8
+ export type CardInfo = {
9
+ id: string
10
+ label: string
11
+ family: string
12
+ year: number
13
+ blurb: string
14
+ date: string
15
+ size: string
16
+ quality: number
17
+ speed: string
18
+ autoDownload: boolean
19
+ ok: boolean
20
+ missingNodes: string[]
21
+ missingFiles: WeightFile[]
22
+ }
23
+
24
+ export type Source = { key: string; url: string; name: string; width: number; height: number }
25
+
26
+ export async function fetchCatalog<M extends CardInfo>(): Promise<{ host: string; models: M[]; samples: string[] }> {
27
+ const [m, s] = await Promise.all([fetch('/api/models'), fetch('/api/samples')])
28
+ const mj = (await m.json()) as { host: string; models: M[] }
29
+ const samples = (await s.json()) as string[]
30
+ return { host: mj.host, models: mj.models, samples }
31
+ }
32
+
33
+ export async function sampleBlob(name: string): Promise<Blob> {
34
+ return (await fetch(`/api/samples/${encodeURIComponent(name)}`)).blob()
35
+ }
36
+
37
+ /** decodes the image and uploads it once to the server, which keys it by its content hash */
38
+ export async function uploadSource(blob: Blob, name: string): Promise<Source> {
39
+ const url = URL.createObjectURL(blob)
40
+ const img = new Image()
41
+ img.src = url
42
+ await img.decode()
43
+ const res = await fetch('/api/image', { method: 'POST', body: blob })
44
+ const j = (await res.json()) as { key?: string; error?: string }
45
+ if (j.key == null) throw new Error(j.error ?? 'upload failed')
46
+ return { key: j.key, url, name, width: img.naturalWidth, height: img.naturalHeight }
47
+ }
48
+
49
+ export class RunSt {
50
+ status: 'queued' | 'running' | 'done' | 'error' = 'queued'
51
+ url: string | null = null
52
+ ms: number | null = null
53
+ error: string | null = null
54
+ startedAt = 0
55
+ /** the result's file size and pixel size, once done */
56
+ bytes = 0
57
+ width = 0
58
+ height = 0
59
+ /** 'box': ComfyUI reused an earlier run (`ms` is then the transfer); 'server': the server kept it */
60
+ cached: 'no' | 'box' | 'server' = 'no'
61
+ constructor() {
62
+ makeAutoObservable(this)
63
+ }
64
+ }
65
+
66
+ export type RunBody = { image: string; model: string } & Record<string, unknown>
67
+
68
+ /** POSTs each job's body to /api/run in turn; the body names the image and the model */
69
+ export class RunQueue {
70
+ results = new Map<string, RunSt>()
71
+ private queue: { key: string; body: RunBody; onDone?: (r: RunSt) => void }[] = []
72
+ draining = false
73
+ /** ticks every 200 ms, for the elapsed timers of running cards */
74
+ now = Date.now()
75
+
76
+ constructor() {
77
+ makeAutoObservable(this, { results: true })
78
+ setInterval(() => runInAction(() => (this.now = Date.now())), 200)
79
+ }
80
+
81
+ get busy(): boolean {
82
+ return this.queue.length > 0 || this.draining
83
+ }
84
+
85
+ get(key: string): RunSt | undefined {
86
+ return this.results.get(key)
87
+ }
88
+
89
+ /** `onDone`: once this result is in (a page derives a thumbnail from it, say) */
90
+ enqueue(key: string, body: RunBody, onDone?: (r: RunSt) => void): void {
91
+ const prev = this.results.get(key)
92
+ if (prev != null && (prev.status === 'queued' || prev.status === 'running')) return
93
+ this.results.set(key, new RunSt())
94
+ this.queue.push({ key, body, onDone })
95
+ void this.drain()
96
+ }
97
+
98
+ /** resolves once the queue is empty */
99
+ settled(): Promise<void> {
100
+ return new Promise((resolve) => {
101
+ const tick = (): void => {
102
+ if (this.busy) setTimeout(tick, 100)
103
+ else resolve()
104
+ }
105
+ tick()
106
+ })
107
+ }
108
+
109
+ private async drain(): Promise<void> {
110
+ if (this.draining) return
111
+ this.draining = true
112
+ try {
113
+ for (;;) {
114
+ const job = this.queue.shift()
115
+ if (job == null) break
116
+ const r = this.results.get(job.key)
117
+ if (r == null) continue
118
+ runInAction(() => {
119
+ r.status = 'running'
120
+ r.startedAt = Date.now()
121
+ })
122
+ try {
123
+ const res = await fetch('/api/run', {
124
+ method: 'POST',
125
+ headers: { 'content-type': 'application/json' },
126
+ body: JSON.stringify(job.body),
127
+ })
128
+ if (!res.ok) {
129
+ const j = (await res.json()) as { error?: string }
130
+ throw new Error(j.error ?? `http ${res.status}`)
131
+ }
132
+ const blob = await res.blob()
133
+ const url = URL.createObjectURL(blob)
134
+ const img = new Image()
135
+ img.src = url
136
+ await img.decode()
137
+ const ms = Number(res.headers.get('x-ms'))
138
+ const cached = res.headers.get('x-cached')
139
+ runInAction(() => {
140
+ r.url = url
141
+ r.ms = ms
142
+ r.bytes = blob.size
143
+ r.width = img.naturalWidth
144
+ r.height = img.naturalHeight
145
+ r.cached = cached === 'box' || cached === 'server' ? cached : 'no'
146
+ r.status = 'done'
147
+ })
148
+ job.onDone?.(r)
149
+ } catch (e) {
150
+ runInAction(() => {
151
+ r.error = e instanceof Error ? e.message : String(e)
152
+ r.status = 'error'
153
+ })
154
+ }
155
+ }
156
+ } finally {
157
+ runInAction(() => (this.draining = false))
158
+ }
159
+ }
160
+ }