comfy-ts 2.23.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 (76) hide show
  1. package/dist/{ServeApp-DolRCMHj.js → ServeApp-fsHtW5zG.js} +3 -3
  2. package/dist/{ServeApp-DolRCMHj.js.map → ServeApp-fsHtW5zG.js.map} +1 -1
  3. package/dist/cli.js +5 -5
  4. package/dist/{exampleAssets-Duneoq6r.js → exampleAssets-DZynSkZm.js} +79 -15
  5. package/dist/exampleAssets-DZynSkZm.js.map +1 -0
  6. package/dist/{findDefinedWorkflow-DjoJA8y7.js → findDefinedWorkflow-qyqFea7q.js} +2 -2
  7. package/dist/{findDefinedWorkflow-DjoJA8y7.js.map → findDefinedWorkflow-qyqFea7q.js.map} +1 -1
  8. package/dist/index.cjs +80 -14
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +53 -19
  11. package/dist/index.d.ts +53 -19
  12. package/dist/index.js +80 -15
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-run-Cr0L9lCK.js → run-run-Cn2JzKlE.js} +5 -5
  15. package/dist/{run-run-Cr0L9lCK.js.map → run-run-Cn2JzKlE.js.map} +1 -1
  16. package/dist/{run-serve---qA7o_m.js → run-serve-BhGegaCI.js} +4 -4
  17. package/dist/{run-serve---qA7o_m.js.map → run-serve-BhGegaCI.js.map} +1 -1
  18. package/dist/{run-tui-DxXiWo5J.js → run-tui-CrM4ijkH.js} +4 -4
  19. package/dist/{run-tui-DxXiWo5J.js.map → run-tui-CrM4ijkH.js.map} +1 -1
  20. package/dist/{schemaDrift-BTxdABHi.js → schemaDrift-BGYJZGMD.js} +3 -2
  21. package/dist/{schemaDrift-BTxdABHi.js.map → schemaDrift-BGYJZGMD.js.map} +1 -1
  22. package/dist/web.d.ts +53 -19
  23. package/dist/web.js +80 -15
  24. package/dist/web.js.map +1 -1
  25. package/examples/README.md +1 -0
  26. package/examples/depth-explorer/models.ts +6 -56
  27. package/examples/depth-explorer/serve.ts +12 -133
  28. package/examples/depth-explorer/web/App.tsx +20 -91
  29. package/examples/depth-explorer/web/index.html +1 -0
  30. package/examples/depth-explorer/web/state.ts +26 -109
  31. package/examples/depth-explorer/web/styles.css +1 -286
  32. package/examples/explorer-kit/catalog.ts +80 -0
  33. package/examples/explorer-kit/server.ts +167 -0
  34. package/examples/explorer-kit/web/base.css +289 -0
  35. package/examples/explorer-kit/web/runs.ts +160 -0
  36. package/examples/explorer-kit/web/ui.tsx +125 -0
  37. package/examples/rvion/17-relight.cflow.ts +2 -1
  38. package/examples/rvion/19-flythrough.cflow.ts +312 -0
  39. package/examples/rvion/20-grow-splat.cflow.ts +88 -0
  40. package/examples/rvion/21-photo-to-model.cflow.ts +191 -0
  41. package/examples/rvion/flythroughChain.ts +171 -0
  42. package/examples/rvion/flythroughColmap.ts +157 -0
  43. package/examples/rvion/flythroughFuse.ts +199 -0
  44. package/examples/rvion/flythroughGuide.ts +300 -0
  45. package/examples/rvion/flythroughPalette.ts +310 -0
  46. package/examples/rvion/flythroughPath.ts +177 -0
  47. package/examples/rvion/flythroughSplat.ts +73 -0
  48. package/examples/rvion/grow-splat/align.ts +114 -0
  49. package/examples/rvion/grow-splat/grow.ts +198 -0
  50. package/examples/rvion/grow-splat/ply.ts +166 -0
  51. package/examples/rvion/grow-splat/raster.ts +207 -0
  52. package/examples/rvion/grow-splat/sharp.ts +45 -0
  53. package/examples/rvion/splatDataset.ts +80 -0
  54. package/examples/rvion/splatEval.ts +380 -0
  55. package/examples/upscale-explorer/models.ts +341 -0
  56. package/examples/upscale-explorer/serve.ts +19 -0
  57. package/examples/upscale-explorer/web/App.tsx +250 -0
  58. package/examples/upscale-explorer/web/compare.tsx +285 -0
  59. package/examples/upscale-explorer/web/index.html +15 -0
  60. package/examples/upscale-explorer/web/main.tsx +12 -0
  61. package/examples/upscale-explorer/web/state.ts +279 -0
  62. package/examples/upscale-explorer/web/styles.css +241 -0
  63. package/examples/upscale-explorer/web/tsconfig.json +16 -0
  64. package/examples/upscale-explorer/web/viewport.tsx +130 -0
  65. package/examples/world-explorer/web/main.tsx +2 -2
  66. package/package.json +4 -3
  67. package/src/coreExports.ts +5 -0
  68. package/src/host/ComfyHost.ts +6 -0
  69. package/src/runner/ComfyExecution.ts +22 -5
  70. package/src/runner/ComfyWorkflow.ts +22 -0
  71. package/src/runner/ComfyWsApi.ts +1 -1
  72. package/src/runner/comfyOrgApiKey.ts +44 -0
  73. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +2 -0
  74. package/src/state.ts +2 -0
  75. package/src/vars/DefinedWorkflow.ts +1 -0
  76. package/dist/exampleAssets-Duneoq6r.js.map +0 -1
@@ -1,12 +1,5 @@
1
+ /* the depth explorer over the shared explorer look (examples/explorer-kit/web/base.css) */
1
2
  :root {
2
- --bg: #111316;
3
- --panel: #181b20;
4
- --card: #1d2127;
5
- --line: #2a2f37;
6
- --text: #e6e8eb;
7
- --dim: #8a929c;
8
- --accent: #6aa8ff;
9
- --err: #ff7a7a;
10
3
  /* the panel's tokens, which the shared widget rules read */
11
4
  --panel-2: var(--card);
12
5
  --border: var(--line);
@@ -15,7 +8,6 @@
15
8
  --sel-border: var(--accent);
16
9
  --sel-text: #c3d3fb;
17
10
  --amber: #e0af68;
18
- color-scheme: dark;
19
11
  }
20
12
  .relightWrap {
21
13
  padding: 10px;
@@ -23,283 +15,6 @@
23
15
  flex-direction: column;
24
16
  gap: 8px;
25
17
  }
26
- * {
27
- box-sizing: border-box;
28
- }
29
- body {
30
- margin: 0;
31
- background: var(--bg);
32
- color: var(--text);
33
- font:
34
- 13px/1.4 ui-sans-serif,
35
- system-ui,
36
- -apple-system,
37
- sans-serif;
38
- }
39
- button,
40
- select,
41
- a.ghost {
42
- font: inherit;
43
- color: var(--text);
44
- background: var(--card);
45
- border: 1px solid var(--line);
46
- border-radius: 6px;
47
- padding: 5px 10px;
48
- cursor: pointer;
49
- text-decoration: none;
50
- }
51
- button:disabled {
52
- opacity: 0.45;
53
- cursor: default;
54
- }
55
- button.primary {
56
- background: var(--accent);
57
- border-color: var(--accent);
58
- color: #0b1220;
59
- font-weight: 600;
60
- width: 100%;
61
- padding: 8px;
62
- margin-top: 14px;
63
- }
64
- .ghost {
65
- background: transparent;
66
- }
67
- .dim {
68
- color: var(--dim);
69
- }
70
- .small {
71
- font-size: 12px;
72
- margin-top: 6px;
73
- }
74
- .err {
75
- color: var(--err);
76
- display: flex;
77
- flex-direction: column;
78
- gap: 6px;
79
- padding: 10px;
80
- font-size: 12px;
81
- overflow: auto;
82
- }
83
- .app {
84
- min-height: 100vh;
85
- display: flex;
86
- flex-direction: column;
87
- }
88
- header {
89
- display: flex;
90
- align-items: baseline;
91
- gap: 14px;
92
- padding: 12px 20px;
93
- border-bottom: 1px solid var(--line);
94
- }
95
- h1 {
96
- font-size: 16px;
97
- margin: 0;
98
- }
99
- h2 {
100
- font-size: 12px;
101
- text-transform: uppercase;
102
- letter-spacing: 0.08em;
103
- color: var(--dim);
104
- margin: 4px 0 10px;
105
- }
106
- .body {
107
- display: flex;
108
- flex: 1;
109
- min-height: 0;
110
- }
111
- aside {
112
- width: 280px;
113
- flex-shrink: 0;
114
- padding: 16px;
115
- border-right: 1px solid var(--line);
116
- background: var(--panel);
117
- }
118
- aside label {
119
- display: block;
120
- color: var(--dim);
121
- margin: 14px 0 6px;
122
- }
123
- label.check {
124
- display: flex;
125
- gap: 8px;
126
- align-items: center;
127
- color: var(--text);
128
- margin: 10px 0 0;
129
- cursor: pointer;
130
- }
131
- .drop {
132
- border: 1px dashed var(--line);
133
- border-radius: 8px;
134
- min-height: 140px;
135
- display: grid;
136
- place-items: center;
137
- cursor: pointer;
138
- overflow: hidden;
139
- }
140
- .drop.over {
141
- border-color: var(--accent);
142
- }
143
- .drop img {
144
- display: block;
145
- width: 100%;
146
- }
147
- .samples {
148
- display: flex;
149
- gap: 6px;
150
- flex-wrap: wrap;
151
- margin-top: 10px;
152
- }
153
- .samples img {
154
- width: 40px;
155
- height: 40px;
156
- object-fit: cover;
157
- border-radius: 4px;
158
- cursor: pointer;
159
- opacity: 0.8;
160
- }
161
- .samples img:hover {
162
- opacity: 1;
163
- }
164
- .seg {
165
- display: flex;
166
- }
167
- .seg button {
168
- flex: 1;
169
- border-radius: 0;
170
- }
171
- .seg button:first-child {
172
- border-radius: 6px 0 0 6px;
173
- }
174
- .seg button:last-child {
175
- border-radius: 0 6px 6px 0;
176
- }
177
- .seg button.on {
178
- background: #2c3542;
179
- border-color: var(--accent);
180
- }
181
- main {
182
- flex: 1;
183
- padding: 16px 20px 40px;
184
- overflow: auto;
185
- }
186
- section + section {
187
- margin-top: 24px;
188
- }
189
- .grid {
190
- display: grid;
191
- grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
192
- gap: 14px;
193
- }
194
- .card {
195
- background: var(--card);
196
- border: 1px solid var(--line);
197
- border-radius: 8px;
198
- overflow: hidden;
199
- }
200
- .card.off {
201
- opacity: 0.6;
202
- }
203
- .cardHead {
204
- display: flex;
205
- justify-content: space-between;
206
- gap: 8px;
207
- padding: 8px 10px;
208
- }
209
- .name {
210
- font-weight: 600;
211
- }
212
- .fam {
213
- font-weight: 400;
214
- color: var(--dim);
215
- }
216
- .meta {
217
- color: var(--dim);
218
- white-space: nowrap;
219
- }
220
- .frame {
221
- background: #0c0d0f;
222
- display: grid;
223
- place-items: center;
224
- position: relative;
225
- overflow: hidden;
226
- }
227
- .card.done .frame {
228
- cursor: zoom-in;
229
- }
230
- .frame > img,
231
- .frame > canvas {
232
- width: 100%;
233
- height: 100%;
234
- object-fit: contain;
235
- display: block;
236
- }
237
- .frame .dim {
238
- display: flex;
239
- flex-direction: column;
240
- align-items: center;
241
- gap: 4px;
242
- }
243
- .blurb {
244
- padding: 8px 10px;
245
- color: var(--dim);
246
- font-size: 12px;
247
- }
248
- .missing {
249
- display: flex;
250
- flex-direction: column;
251
- gap: 4px;
252
- padding: 10px;
253
- font-size: 11px;
254
- word-break: break-all;
255
- }
256
- .missing a {
257
- color: var(--accent);
258
- }
259
- .spin {
260
- display: inline-block;
261
- width: 12px;
262
- height: 12px;
263
- border: 2px solid var(--line);
264
- border-top-color: var(--accent);
265
- border-radius: 50%;
266
- animation: spin 0.8s linear infinite;
267
- vertical-align: -2px;
268
- }
269
- @keyframes spin {
270
- to {
271
- transform: rotate(360deg);
272
- }
273
- }
274
- .focus {
275
- position: fixed;
276
- inset: 0;
277
- background: rgba(0, 0, 0, 0.75);
278
- display: grid;
279
- place-items: center;
280
- padding: 24px;
281
- z-index: 10;
282
- }
283
- .focusBox {
284
- background: var(--panel);
285
- border: 1px solid var(--line);
286
- border-radius: 10px;
287
- width: min(1200px, 100%);
288
- max-height: 100%;
289
- display: flex;
290
- flex-direction: column;
291
- overflow: hidden;
292
- }
293
- .focusBar {
294
- display: flex;
295
- align-items: center;
296
- gap: 10px;
297
- padding: 10px 14px;
298
- border-bottom: 1px solid var(--line);
299
- }
300
- .focusBar b {
301
- margin-right: auto;
302
- }
303
18
  .wipe {
304
19
  position: relative;
305
20
  flex-shrink: 0;
@@ -0,0 +1,80 @@
1
+ // what every explorer catalog shares: an entry's card facts, the weight files it needs, and its
2
+ // availability read from the LIVE host schema (a node or a weight file missing → the card shows
3
+ // the files and their urls instead of a run button).
4
+ import type { BaseNodeFactory, ComfyWorkflow } from 'comfy-ts'
5
+
6
+ /** a weight file the graph names, and where to get it when the host lacks it */
7
+ export type WeightFile = { node: string; input: string; file: string; folder: string; url: string }
8
+
9
+ /** the facts a card shows, and what the host must have to run the entry */
10
+ export type CatalogEntry = {
11
+ id: string
12
+ label: string
13
+ family: string
14
+ year: number
15
+ /** when it came out, as precise as known: `2025-11` */
16
+ date: string
17
+ /** its weights on disk */
18
+ size: string
19
+ /** 1 (rough) to 5 (the best of its kind), judged on the explorer's samples */
20
+ quality: number
21
+ /** one run on an RTX class GPU, weights loaded */
22
+ speed: string
23
+ blurb: string
24
+ nodes: string[]
25
+ /** weights the host must list; a node pack that downloads its own on the first run lists none */
26
+ files: WeightFile[]
27
+ /** the node pack downloads its weights on the first run (slow once) */
28
+ autoDownload?: boolean
29
+ }
30
+
31
+ /** a factory of the base (untyped) builder, or a loud error naming the node. For graphs that name
32
+ * weight files the generated host sdk does not know until they are downloaded */
33
+ export function base<ID extends string>(wf: ComfyWorkflow<ID>, name: string): BaseNodeFactory {
34
+ const f = wf.builderBase[name]
35
+ if (f == null) throw new Error(`this host has no ${name} node`)
36
+ return f
37
+ }
38
+
39
+ /** raw object_info, as the host schema keeps it */
40
+ export type ObjectInfo = Record<
41
+ string,
42
+ { input?: { required?: Record<string, unknown>; optional?: Record<string, unknown> } }
43
+ >
44
+
45
+ /** the options of a COMBO input in both object_info spellings: [[...]] and ['COMBO', { options }] */
46
+ function comboOptions(info: ObjectInfo, node: string, input: string): string[] {
47
+ const def = info[node]?.input
48
+ const slot = def?.required?.[input] ?? def?.optional?.[input]
49
+ if (!Array.isArray(slot)) return []
50
+ const head: unknown = slot[0]
51
+ if (Array.isArray(head)) return head.filter((x): x is string => typeof x === 'string')
52
+ const meta: unknown = slot[1]
53
+ const opts: unknown = typeof meta === 'object' && meta != null && 'options' in meta ? meta.options : null
54
+ return Array.isArray(opts) ? opts.filter((x): x is string => typeof x === 'string') : []
55
+ }
56
+
57
+ export type Availability = { ok: boolean; missingNodes: string[]; missingFiles: WeightFile[] }
58
+
59
+ export function availability(info: ObjectInfo, m: CatalogEntry): Availability {
60
+ const missingNodes = m.nodes.filter((n) => info[n] == null)
61
+ const missingFiles = m.files.filter((f) => !comboOptions(info, f.node, f.input).includes(f.file))
62
+ return { ok: missingNodes.length === 0 && missingFiles.length === 0, missingNodes, missingFiles }
63
+ }
64
+
65
+ /** an entry as the page gets it: its card facts and its availability, never its graph */
66
+ export function entryPayload(info: ObjectInfo, m: CatalogEntry): Record<string, unknown> {
67
+ return {
68
+ id: m.id,
69
+ label: m.label,
70
+ family: m.family,
71
+ year: m.year,
72
+ blurb: m.blurb,
73
+ date: m.date,
74
+ size: m.size,
75
+ quality: m.quality,
76
+ speed: m.speed,
77
+ autoDownload: m.autoDownload === true,
78
+ ...availability(info, m),
79
+ }
80
+ }
@@ -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
+ }