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,77 @@
1
+ // small previews of LOCAL images for the panel: a choice option's thumb, a media preset, the
2
+ // current value of an image var. Not a file server: a path is served only when a served module
3
+ // declared it (a thumb, a preset, a default) or it lies under an allowed root (the output root,
4
+ // a served module's folder). An http(s) image is never proxied: the page loads it itself.
5
+ import { existsSync, statSync } from 'node:fs'
6
+ import { resolve } from 'pathe'
7
+ import { importSharp } from 'src/utils/lazySharp.ts'
8
+
9
+ export const isHttpUrl = (s: string): boolean => /^https?:\/\//i.test(s)
10
+
11
+ /** the url the page loads for a local image's preview */
12
+ export function thumbUrl(abs: string, width = 160): string {
13
+ return `/thumb?src=${encodeURIComponent(abs)}&w=${width}`
14
+ }
15
+
16
+ /** Bun's own image pipeline when the server runs on Bun, sharp only under Node (the cli runs on
17
+ * both). Both read the EXIF orientation */
18
+ async function webpThumb(path: string, width: number): Promise<Uint8Array> {
19
+ if (typeof Bun !== 'undefined')
20
+ return new Bun.Image(path)
21
+ .resize(width, width, { fit: 'inside', withoutEnlargement: true })
22
+ .webp({ quality: 78 })
23
+ .bytes()
24
+ const sharp = await importSharp('a thumbnail')
25
+ return new Uint8Array(
26
+ await sharp(path)
27
+ .rotate()
28
+ .resize({ width, height: width, fit: 'inside', withoutEnlargement: true })
29
+ .webp({ quality: 78 })
30
+ .toBuffer(),
31
+ )
32
+ }
33
+
34
+ const MAX_WIDTH = 640
35
+ const MAX_CACHED = 400
36
+
37
+ export class ThumbStore {
38
+ private allowed = new Set<string>()
39
+ private roots = new Set<string>()
40
+ private cache = new Map<string, Uint8Array>()
41
+
42
+ /** one file a served module declared */
43
+ allow(abs: string): void {
44
+ this.allowed.add(resolve(abs))
45
+ }
46
+
47
+ /** every image under this folder */
48
+ allowRoot(dir: string): void {
49
+ this.roots.add(resolve(dir))
50
+ }
51
+
52
+ isAllowed(abs: string): boolean {
53
+ const p = resolve(abs)
54
+ if (this.allowed.has(p)) return true
55
+ for (const root of this.roots) if (p.startsWith(`${root}/`)) return true
56
+ return false
57
+ }
58
+
59
+ /** a webp at most `width` wide, or why not: 'forbidden' (not declared, not under a root),
60
+ * 'missing' (not on this machine) */
61
+ async render(abs: string, width: number): Promise<Uint8Array | 'forbidden' | 'missing'> {
62
+ if (!this.isAllowed(abs)) return 'forbidden'
63
+ const p = resolve(abs)
64
+ if (!existsSync(p)) return 'missing'
65
+ const w = Math.max(16, Math.min(MAX_WIDTH, Math.round(width)))
66
+ const key = `${p}|${statSync(p).mtimeMs}|${w}`
67
+ const hit = this.cache.get(key)
68
+ if (hit != null) return hit
69
+ const bytes = await webpThumb(p, w)
70
+ if (this.cache.size >= MAX_CACHED) {
71
+ const oldest = this.cache.keys().next().value
72
+ if (oldest != null) this.cache.delete(oldest)
73
+ }
74
+ this.cache.set(key, bytes)
75
+ return bytes
76
+ }
77
+ }
@@ -1,6 +1,7 @@
1
1
  // typed fetch layer over the serve json api — the ONLY web-ui module that talks http
2
2
  import type { LlmConfigEntry } from 'src/cli/serve/llmConfigShape.ts'
3
3
  import type { VarDescriptor } from 'src/cli/serve/describeVar.ts'
4
+ import type { OutputWidget } from 'src/vars/outputWidgets.ts'
4
5
 
5
6
  export type ModuleDescription = {
6
7
  module: string
@@ -24,7 +25,8 @@ export type IndexPayload = {
24
25
  loadErrors?: Record<string, string>
25
26
  }
26
27
 
27
- export type GeneratedImage = { filename: string; url: string | null; absPath: string | null }
28
+ /** `tags`: the save node's metadata tags, read by output widgets */
29
+ export type GeneratedImage = { filename: string; url: string | null; absPath: string | null; tags?: string[] }
28
30
 
29
31
  /** a STRING output (PreviewAny). An llm graph produces these and no images at all */
30
32
  export type GeneratedText = { nodeKey: string | null; text: string }
@@ -35,6 +37,9 @@ export type GeneratedAudio = { filename: string; mime: string; url: string | nul
35
37
  /** a video file (SaveVideo, SaveWEBM, VHS_VideoCombine): the panel plays it in a <video> player */
36
38
  export type GeneratedVideo = GeneratedAudio
37
39
 
40
+ /** a 3D file (SaveGLB, SaveGaussianSplat, SavePointCloud): the panel lists it as a download, `size` in bytes */
41
+ export type GeneratedModel3D = GeneratedAudio & { format: string; size: number }
42
+
38
43
  export type GenerateOk = {
39
44
  ok: true
40
45
  module: string
@@ -48,6 +53,9 @@ export type GenerateOk = {
48
53
  texts?: GeneratedText[]
49
54
  audios?: GeneratedAudio[]
50
55
  videos?: GeneratedVideo[]
56
+ models3d?: GeneratedModel3D[]
57
+ /** the module's output widgets (`widget.relight(...)`), drawn over this run's tagged images */
58
+ widgets?: OutputWidget[]
51
59
  }
52
60
 
53
61
  async function jsonFetch<T>(url: string, init?: RequestInit): Promise<T> {
@@ -15,6 +15,14 @@ import type { WebSt } from 'src/cli/serve/web/state/WebSt.ts'
15
15
  import { MOD_KEY } from 'src/cli/serve/web/components/modKey.ts'
16
16
  import { SHORTCUT_KEYS } from 'src/cli/serve/web/state/shortcuts.ts'
17
17
  import { onEscape } from 'src/cli/serve/web/state/escape.ts'
18
+ import { OutputWidgets } from 'src/cli/serve/web/widgets/OutputWidgets.tsx'
19
+
20
+ /** a 3D file is often tens of MB (a splat), sometimes a few KB (a small mesh) */
21
+ function formatSize(bytes: number): string {
22
+ if (bytes < 1024 * 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`
23
+ const mb = bytes / (1024 * 1024)
24
+ return `${mb < 10 ? mb.toFixed(1) : Math.round(mb)} MB`
25
+ }
18
26
 
19
27
  /** on an output only the serve process holds: a restart, or the memory budget, loses it */
20
28
  function EphemeralPill(p: { out: { url: string | null; absPath: string | null } }): ReactNode {
@@ -520,6 +528,7 @@ export const Gallery = observer(function Gallery(p: { st: WebSt; compact?: boole
520
528
  <Icon name="trash" />
521
529
  </button>
522
530
  </div>
531
+ <OutputWidgets widgets={r.widgets} images={r.images} />
523
532
  <div className="imgs">
524
533
  {r.images.map((img, ix) =>
525
534
  img.url != null ? (
@@ -641,10 +650,26 @@ export const Gallery = observer(function Gallery(p: { st: WebSt; compact?: boole
641
650
  </div>
642
651
  ),
643
652
  )}
653
+ {(r.models3d ?? []).map((m, ix) =>
654
+ m.url != null ? (
655
+ <div key={`${r.promptId}-model3d-${ix}`} className="model3d-cell">
656
+ <a href={m.url} download={m.filename} data-tip={`${m.format} 3D file, ${m.mime}`}>
657
+ <Icon name="save" /> {m.filename}
658
+ </a>
659
+ <span className="hint">{formatSize(m.size)}</span>
660
+ <EphemeralPill out={m} />
661
+ </div>
662
+ ) : (
663
+ <div key={`${r.promptId}-model3d-${ix}`} className="noimg">
664
+ {m.filename} (not saved, and no longer in memory)
665
+ </div>
666
+ ),
667
+ )}
644
668
  {r.images.length === 0 &&
645
669
  (r.texts ?? []).length === 0 &&
646
670
  (r.audios ?? []).length === 0 &&
647
- (r.videos ?? []).length === 0 ? (
671
+ (r.videos ?? []).length === 0 &&
672
+ (r.models3d ?? []).length === 0 ? (
648
673
  <div className="noimg">no outputs</div>
649
674
  ) : null}
650
675
  </div>
@@ -2,8 +2,9 @@
2
2
  // bigger kinds (prompt, seed, size, loras, image) have their own files
3
3
  import { observer } from 'mobx-react-lite'
4
4
  import { PresetPicker } from 'src/cli/serve/web/components/controls/PresetPicker.tsx'
5
+ import { RichSelect } from 'src/cli/serve/web/components/controls/RichSelect.tsx'
5
6
  import { VarIcon } from 'src/cli/serve/web/components/VarIcon.tsx'
6
- import { choiceAsButtons, clickChoice, pickedChoices } from 'src/cli/serve/web/state/choiceButtons.ts'
7
+ import { choiceAsButtons, clickChoice, hasRichLook, pickedChoices } from 'src/cli/serve/web/state/choiceButtons.ts'
7
8
  import type { VarSt } from 'src/cli/serve/web/state/FormSt.ts'
8
9
 
9
10
  export const TextControl = observer(function TextControl(p: { v: VarSt }) {
@@ -102,7 +103,11 @@ export const ChoiceControl = observer(function ChoiceControl(p: { v: VarSt }) {
102
103
  <span className="hint">(unset)</span>
103
104
  ) : null
104
105
  // many choices can always be several buttons at once: a select holds one value only
105
- if (choiceAsButtons(choices) || select !== 'one')
106
+ if (
107
+ choiceAsButtons(choices, looks) ||
108
+ select === 'many' ||
109
+ (select === 'zero-or-one' && !hasRichLook(choices, looks))
110
+ )
106
111
  return (
107
112
  <span className="row-inline">
108
113
  <span className="btn-group wrap">
@@ -140,21 +145,13 @@ export const ChoiceControl = observer(function ChoiceControl(p: { v: VarSt }) {
140
145
  {staleNote}
141
146
  </span>
142
147
  )
143
- const value = picked[0] ?? ''
144
148
  return (
145
- <select value={value} onChange={(e) => p.v.set(e.target.value)}>
146
- {/* honest display for a value outside the current union (stale draft): the
147
- browser would silently SHOW the first option while the state differs */}
148
- {choices.includes(value) ? null : (
149
- <option value={value} disabled>
150
- {value === '' ? '(unset)' : `${value} (not on this host)`}
151
- </option>
152
- )}
153
- {choices.map((c) => (
154
- <option key={c} value={c}>
155
- {c}
156
- </option>
157
- ))}
158
- </select>
149
+ <RichSelect
150
+ choices={choices}
151
+ value={picked[0] ?? (select === 'zero-or-one' ? null : '')}
152
+ looks={looks}
153
+ allowNone={select === 'zero-or-one'}
154
+ onPick={(c) => p.v.set(c)}
155
+ />
159
156
  )
160
157
  })
@@ -1,9 +1,12 @@
1
1
  // image, audio, video: a path/url input the api already accepts, a browser upload (POST /upload
2
2
  // → local file under outputs/serve-inputs/), and a DROP ZONE for desktop files and gallery
3
- // outputs. The preview plays the var's own medium when the value has a browser url
3
+ // outputs. The preview plays the var's own medium: a url as is, a local image through GET /thumb
4
+ // (which only serves what a served workflow declared, or what lies under its folder or the
5
+ // outputs). The workflow's presets are one-click tiles; one not on this machine is disabled
4
6
  import { Icon } from 'src/cli/serve/web/components/Icon.tsx'
5
7
  import { observer } from 'mobx-react-lite'
6
- import { useRef, useState, type DragEvent, type ReactNode } from 'react'
8
+ import { useEffect, useRef, useState, type DragEvent, type ReactNode } from 'react'
9
+ import type { MediaPresetDescriptor } from 'src/cli/serve/describeVar.ts'
7
10
  import { decodeDraggedOutput, OUTPUT_DRAG_MIME } from 'src/cli/serve/web/state/mediaDrop.ts'
8
11
  import type { VarSt } from 'src/cli/serve/web/state/FormSt.ts'
9
12
  import type { MediaKind } from 'src/runner/mediaKinds.ts'
@@ -14,17 +17,51 @@ function isMediaDrag(e: DragEvent): boolean {
14
17
  return types.includes(OUTPUT_DRAG_MIME) || types.includes('Files')
15
18
  }
16
19
 
17
- function Preview(p: { kind: MediaKind; url: string; alt: string }): ReactNode {
18
- if (p.kind === 'audio') return <audio controls preload="metadata" src={p.url} />
19
- if (p.kind === 'video') return <video controls muted preload="metadata" src={p.url} />
20
- return <img src={p.url} alt={p.alt} />
20
+ function Preview(p: { kind: MediaKind; url: string; alt: string; onError: () => void }): ReactNode {
21
+ if (p.kind === 'audio') return <audio controls preload="metadata" src={p.url} onError={p.onError} />
22
+ if (p.kind === 'video') return <video controls muted preload="metadata" src={p.url} onError={p.onError} />
23
+ return <img src={p.url} alt={p.alt} onError={p.onError} />
24
+ }
25
+
26
+ /** the workflow's starting files: a thumbnail and a name each, one click to use it */
27
+ function Presets(p: { presets: MediaPresetDescriptor[]; value: string; onPick: (value: string) => void }): ReactNode {
28
+ return (
29
+ <div className="media-presets">
30
+ {p.presets.map((preset) => (
31
+ <button
32
+ key={preset.label}
33
+ type="button"
34
+ className={`media-preset${preset.value === p.value ? ' sel' : ''}`}
35
+ disabled={preset.missing === true}
36
+ data-tip={
37
+ preset.missing === true ? `${preset.label}: not on this machine (${preset.value})` : preset.value
38
+ }
39
+ onClick={() => p.onPick(preset.value)}
40
+ >
41
+ {preset.thumb != null ? (
42
+ <img src={preset.thumb} alt="" loading="lazy" />
43
+ ) : (
44
+ <span className="media-preset-none" />
45
+ )}
46
+ <span>{preset.label}</span>
47
+ </button>
48
+ ))}
49
+ </div>
50
+ )
21
51
  }
22
52
 
23
53
  export const MediaControl = observer(function MediaControl(p: { v: VarSt; kind: MediaKind }) {
24
54
  const fileInput = useRef<HTMLInputElement>(null)
25
55
  const [over, setOver] = useState(false)
26
56
  const value = typeof p.v.value === 'string' ? p.v.value : ''
27
- const previewUrl = /^https?:\/\//.test(value) ? value : p.v.uploadedUrl
57
+ const isUrl = /^https?:\/\//.test(value)
58
+ const localThumb =
59
+ p.kind === 'image' && value !== '' && !isUrl ? `/thumb?src=${encodeURIComponent(value)}&w=360` : null
60
+ const previewUrl = isUrl ? value : (p.v.uploadedUrl ?? localThumb)
61
+ // a local file /thumb refuses (outside the workflow's folders) says so instead of a broken image
62
+ const [previewFailed, setPreviewFailed] = useState(false)
63
+ useEffect(() => setPreviewFailed(false), [previewUrl])
64
+ const presets = p.v.desc.mediaPresets ?? []
28
65
  const extensions = p.v.desc.extensions ?? []
29
66
  const onDrop = (e: DragEvent): void => {
30
67
  if (!isMediaDrag(e)) return
@@ -100,10 +137,26 @@ export const MediaControl = observer(function MediaControl(p: { v: VarSt; kind:
100
137
  <div className="hint media-drop-hint">
101
138
  drop a {p.kind} file here, or drag one from the results (or use its <b>→ {p.v.name}</b> button)
102
139
  </div>
140
+ {presets.length > 0 ? (
141
+ <Presets
142
+ presets={presets}
143
+ value={value}
144
+ onPick={(v) => {
145
+ p.v.set(v)
146
+ p.v.setUploadedUrl(null)
147
+ p.v.setMediaError(null)
148
+ }}
149
+ />
150
+ ) : null}
103
151
  {p.v.mediaError != null ? <div className="error">{p.v.mediaError}</div> : null}
104
- {previewUrl != null && previewUrl !== '' ? (
152
+ {previewUrl != null && previewUrl !== '' && !previewFailed ? (
105
153
  <div className={`img-preview media-preview-${p.kind}`}>
106
- <Preview kind={p.kind} url={previewUrl} alt={value} />
154
+ <Preview kind={p.kind} url={previewUrl} alt={value} onError={() => setPreviewFailed(true)} />
155
+ </div>
156
+ ) : null}
157
+ {previewFailed ? (
158
+ <div className="hint">
159
+ no preview: the panel shows files of the workflow's folders, the outputs and the presets
107
160
  </div>
108
161
  ) : null}
109
162
  </div>
@@ -0,0 +1,262 @@
1
+ // the panel's own dropdown for a single choice: each row its thumbnail, name, description,
2
+ // badges (date, size, speed, tags) and a 1..5 quality bar, read from `.ui({ options })`. A list
3
+ // longer than FILTER_FROM gets a filter box. Keys: arrows move, enter picks, escape closes,
4
+ // typing filters. A value outside the list (a stale draft) is said, never shown as an option.
5
+ // An optional choice (`select: 'zero-or-one'`) gets a first row « none », which picks null
6
+ import {
7
+ autoUpdate,
8
+ flip,
9
+ FloatingPortal,
10
+ offset,
11
+ shift,
12
+ size,
13
+ useDismiss,
14
+ useFloating,
15
+ useInteractions,
16
+ } from '@floating-ui/react'
17
+ import { observer, useLocalObservable } from 'mobx-react-lite'
18
+ import { useEffect, useRef, type KeyboardEvent, type ReactNode } from 'react'
19
+ import { VarIcon } from 'src/cli/serve/web/components/VarIcon.tsx'
20
+ import { onEscape } from 'src/cli/serve/web/state/escape.ts'
21
+ import type { ChoiceOptionLook } from 'src/vars/ComfyVars.ts'
22
+
23
+ const FILTER_FROM = 8
24
+
25
+ function Quality(p: { value: number | undefined }): ReactNode {
26
+ if (p.value == null) return null
27
+ const q = Math.max(0, Math.min(5, Math.round(p.value)))
28
+ return (
29
+ <span className="rs-quality" data-tip={`quality ${q} of 5`}>
30
+ {[1, 2, 3, 4, 5].map((i) => (
31
+ <i key={i} className={i <= q ? 'on' : ''} />
32
+ ))}
33
+ </span>
34
+ )
35
+ }
36
+
37
+ function Badges(p: { look: ChoiceOptionLook | undefined }): ReactNode {
38
+ const l = p.look
39
+ if (l == null) return null
40
+ const items = [l.date, l.size, l.speed, ...(l.tags ?? [])].filter((x): x is string => x != null && x !== '')
41
+ if (items.length === 0 && l.quality == null) return null
42
+ return (
43
+ <span className="rs-badges">
44
+ {items.map((b) => (
45
+ <span key={b} className="rs-badge">
46
+ {b}
47
+ </span>
48
+ ))}
49
+ <Quality value={l.quality} />
50
+ </span>
51
+ )
52
+ }
53
+
54
+ function Thumb(p: { look: ChoiceOptionLook | undefined; big?: boolean }): ReactNode {
55
+ const cls = p.big === true ? 'rs-thumb big' : 'rs-thumb'
56
+ if (p.look?.thumb != null) return <img className={cls} src={p.look.thumb} alt="" loading="lazy" />
57
+ if (p.look?.icon != null)
58
+ return (
59
+ <span className={`${cls} icon`}>
60
+ <VarIcon icon={p.look.icon} color={p.look.color} />
61
+ </span>
62
+ )
63
+ return null
64
+ }
65
+
66
+ const nameOf = (value: string, look: ChoiceOptionLook | undefined): string => look?.label ?? value
67
+
68
+ /** the « none » row of an optional choice: a key no option can hold */
69
+ const NONE = '\u0000none'
70
+
71
+ export const RichSelect = observer(function RichSelect(p: {
72
+ choices: readonly string[]
73
+ /** null: nothing picked (an optional choice) */
74
+ value: string | null
75
+ looks: Record<string, ChoiceOptionLook>
76
+ /** an optional choice: the list starts with « none » */
77
+ allowNone?: boolean
78
+ onPick: (value: string | null) => void
79
+ }) {
80
+ const st = useLocalObservable(() => ({
81
+ open: false,
82
+ query: '',
83
+ active: 0,
84
+ setOpen(v: boolean) {
85
+ this.open = v
86
+ this.query = ''
87
+ },
88
+ setQuery(q: string) {
89
+ this.query = q
90
+ this.active = 0
91
+ },
92
+ setActive(i: number) {
93
+ this.active = i
94
+ },
95
+ }))
96
+ const { refs, floatingStyles, context } = useFloating({
97
+ open: st.open,
98
+ onOpenChange: (o) => st.setOpen(o),
99
+ placement: 'bottom-start',
100
+ middleware: [
101
+ offset(4),
102
+ flip(),
103
+ shift({ padding: 8 }),
104
+ size({
105
+ padding: 8,
106
+ apply({ availableHeight, rects, elements }) {
107
+ elements.floating.style.maxHeight = `${Math.max(180, availableHeight)}px`
108
+ elements.floating.style.minWidth = `${Math.max(360, rects.reference.width)}px`
109
+ },
110
+ }),
111
+ ],
112
+ whileElementsMounted: autoUpdate,
113
+ })
114
+ const { getReferenceProps, getFloatingProps } = useInteractions([useDismiss(context)])
115
+ const filterRef = useRef<HTMLInputElement>(null)
116
+ const listRef = useRef<HTMLDivElement>(null)
117
+
118
+ const q = st.query.trim().toLowerCase()
119
+ const value = p.value ?? (p.allowNone === true ? NONE : '')
120
+ const rows = p.allowNone === true ? [NONE, ...p.choices] : p.choices
121
+ const shown = rows.filter((c) => {
122
+ if (q === '') return true
123
+ if (c === NONE) return 'none'.includes(q)
124
+ const l = p.looks[c]
125
+ return [c, l?.label, l?.description, ...(l?.tags ?? [])].some((s) => s?.toLowerCase().includes(q) === true)
126
+ })
127
+ const current = p.value == null ? undefined : p.looks[p.value]
128
+ const stale = value !== '' && value !== NONE && !p.choices.includes(value)
129
+
130
+ useEffect(() => {
131
+ if (!st.open) return
132
+ const ix = shown.indexOf(value)
133
+ st.setActive(ix >= 0 ? ix : 0)
134
+ if (p.choices.length >= FILTER_FROM) filterRef.current?.focus()
135
+ else listRef.current?.focus()
136
+ }, [st.open])
137
+ useEffect(() => {
138
+ listRef.current?.querySelector('.rs-row.active')?.scrollIntoView({ block: 'nearest' })
139
+ }, [st.active, st.open])
140
+
141
+ const pick = (c: string): void => {
142
+ p.onPick(c === NONE ? null : c)
143
+ st.setOpen(false)
144
+ }
145
+ const onKey = (e: KeyboardEvent): void => {
146
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
147
+ e.preventDefault()
148
+ const n = shown.length
149
+ if (n > 0) st.setActive((st.active + (e.key === 'ArrowDown' ? 1 : -1) + n) % n)
150
+ } else if (e.key === 'Enter') {
151
+ e.preventDefault()
152
+ const c = shown[st.active]
153
+ if (c != null) pick(c)
154
+ } else
155
+ onEscape(e, () => {
156
+ e.stopPropagation()
157
+ st.setOpen(false)
158
+ })
159
+ }
160
+
161
+ return (
162
+ <>
163
+ <button
164
+ type="button"
165
+ ref={refs.setReference}
166
+ className={st.open ? 'rs-trigger open' : 'rs-trigger'}
167
+ {...getReferenceProps({
168
+ onClick: () => st.setOpen(!st.open),
169
+ onKeyDown: (e) => {
170
+ if (!st.open && (e.key === 'ArrowDown' || e.key === 'Enter' || e.key === ' ')) {
171
+ e.preventDefault()
172
+ st.setOpen(true)
173
+ }
174
+ },
175
+ })}
176
+ >
177
+ <Thumb look={current} />
178
+ <span className="rs-trigger-text">
179
+ <span className="rs-name">
180
+ {value === NONE
181
+ ? 'none'
182
+ : value === ''
183
+ ? '(unset)'
184
+ : stale
185
+ ? `${value} (not on this host)`
186
+ : nameOf(value, current)}
187
+ </span>
188
+ {current?.label != null ? <span className="rs-value">{value}</span> : null}
189
+ </span>
190
+ <Badges look={current} />
191
+ <span className="rs-chevron">▾</span>
192
+ </button>
193
+ {st.open ? (
194
+ <FloatingPortal>
195
+ <div ref={refs.setFloating} style={floatingStyles} className="rs-pop" {...getFloatingProps()}>
196
+ {p.choices.length >= FILTER_FROM ? (
197
+ <input
198
+ ref={filterRef}
199
+ className="rs-filter"
200
+ placeholder={`filter ${p.choices.length} options`}
201
+ value={st.query}
202
+ onChange={(e) => st.setQuery(e.target.value)}
203
+ onKeyDown={onKey}
204
+ />
205
+ ) : null}
206
+ <div ref={listRef} className="rs-list" role="listbox" tabIndex={-1} onKeyDown={onKey}>
207
+ {shown.length === 0 ? <div className="rs-empty">nothing matches</div> : null}
208
+ {shown.map((c, i) => {
209
+ if (c === NONE)
210
+ return (
211
+ <div
212
+ key={c}
213
+ role="option"
214
+ aria-selected={value === NONE}
215
+ className={`rs-row rs-none${i === st.active ? ' active' : ''}${value === NONE ? ' sel' : ''}`}
216
+ onMouseEnter={() => st.setActive(i)}
217
+ onClick={() => pick(c)}
218
+ >
219
+ <span className="rs-thumb big icon">∅</span>
220
+ <span className="rs-row-text">
221
+ <span className="rs-name">none</span>
222
+ <span className="rs-desc">leave this out of the run</span>
223
+ </span>
224
+ {value === NONE ? <span className="rs-check">✓</span> : null}
225
+ </div>
226
+ )
227
+ const look = p.looks[c]
228
+ return (
229
+ <div
230
+ key={c}
231
+ role="option"
232
+ aria-selected={c === value}
233
+ className={`rs-row${i === st.active ? ' active' : ''}${c === value ? ' sel' : ''}`}
234
+ onMouseEnter={() => st.setActive(i)}
235
+ onClick={() => pick(c)}
236
+ >
237
+ <Thumb look={look} big />
238
+ <span className="rs-row-text">
239
+ <span className="rs-row-head">
240
+ <span className="rs-name">{nameOf(c, look)}</span>
241
+ {look?.label != null ? <span className="rs-value">{c}</span> : null}
242
+ </span>
243
+ {look?.description != null ? (
244
+ <span className="rs-desc">{look.description}</span>
245
+ ) : null}
246
+ <Badges look={look} />
247
+ </span>
248
+ {c === value ? <span className="rs-check">✓</span> : null}
249
+ </div>
250
+ )
251
+ })}
252
+ </div>
253
+ <div className="rs-foot">
254
+ {p.choices.length === 1 ? 'the only option on this host' : `${p.choices.length} options`} · ↑↓ ⏎
255
+ esc
256
+ </div>
257
+ </div>
258
+ </FloatingPortal>
259
+ ) : null}
260
+ </>
261
+ )
262
+ })
@@ -17,7 +17,10 @@ beforeEach(() => {
17
17
  return json({ running: true, percent: 50, hasPreview: true, previewSeq: statusReads })
18
18
  }
19
19
  if (url.startsWith('/generate/')) {
20
- await new Promise((r) => setTimeout(r, 400))
20
+ // the run ends once the panel read its status twice: a starved cpu delays the reads,
21
+ // it must not make the run end before them (the deadline keeps a broken poll red)
22
+ const deadline = Date.now() + 5000
23
+ while (statusReads < 2 && Date.now() < deadline) await new Promise((r) => setTimeout(r, 10))
21
24
  return json({ promptId: 'p1', module: 'm', draft: 'd', seeds: {}, outputs: [] })
22
25
  }
23
26
  return json({ runs: [], memory: { usedBytes: 0, budgetBytes: 1, outputs: 0, runs: 0 } })
@@ -1,12 +1,36 @@
1
1
  // a choice var with a few short options renders as a row of buttons, every option visible and
2
- // one click away; anything longer stays a select. PURE, tests/serve-web-choice-buttons.test.ts
2
+ // one click away; anything longer, or any option the workflow describes, is the dropdown. PURE,
3
+ // tests/serve-web-choice-buttons.test.ts
4
+ import type { ChoiceOptionLook } from 'src/vars/ComfyVars.ts'
5
+
3
6
  export const MAX_BUTTONS = 5
4
7
  export const MAX_BUTTON_LABEL = 16
5
8
 
6
- export function choiceAsButtons(choices: readonly string[]): boolean {
9
+ export function choiceAsButtons(choices: readonly string[], looks: Record<string, ChoiceOptionLook> = {}): boolean {
10
+ // an option the workflow describes (a picture, a name, a quality…) needs the dropdown's rows to show it
11
+ if (hasRichLook(choices, looks)) return false
7
12
  return choices.length > 0 && choices.length <= MAX_BUTTONS && choices.every((c) => c.length <= MAX_BUTTON_LABEL)
8
13
  }
9
14
 
15
+ export function hasRichLook(choices: readonly string[], looks: Record<string, ChoiceOptionLook>): boolean {
16
+ return choices.some((c) => isRichLook(looks[c]))
17
+ }
18
+
19
+ /** more than a button can say: anything beyond an icon and a colour */
20
+ export function isRichLook(look: ChoiceOptionLook | undefined): boolean {
21
+ if (look == null) return false
22
+ return (
23
+ look.label != null ||
24
+ look.description != null ||
25
+ look.thumb != null ||
26
+ look.date != null ||
27
+ look.size != null ||
28
+ look.quality != null ||
29
+ look.speed != null ||
30
+ (look.tags?.length ?? 0) > 0
31
+ )
32
+ }
33
+
10
34
  export type ChoiceSelectMode = 'one' | 'zero-or-one' | 'many'
11
35
 
12
36
  /** the options picked right now, whatever the shape: one value, one or null, or a list */