comfy-ts 2.15.0 → 2.17.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/README.md +23 -0
  2. package/dist/{run-serve-B5PfIuhK.js → ServeApp-BSA5yzxZ.js} +28 -446
  3. package/dist/ServeApp-BSA5yzxZ.js.map +1 -0
  4. package/dist/cli.js +18 -5
  5. package/dist/cli.js.map +1 -1
  6. package/dist/exampleAssets-BfWzygoM.js +38 -0
  7. package/dist/exampleAssets-BfWzygoM.js.map +1 -0
  8. package/dist/{LogsSt-C3UIWR-o.js → findDefinedWorkflow-0lG-VTEd.js} +201 -201
  9. package/dist/findDefinedWorkflow-0lG-VTEd.js.map +1 -0
  10. package/dist/index.cjs +202 -62
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +115 -14
  13. package/dist/index.d.ts +115 -14
  14. package/dist/index.js +202 -62
  15. package/dist/index.js.map +1 -1
  16. package/dist/run-run-DnaMLCFn.js +450 -0
  17. package/dist/run-run-DnaMLCFn.js.map +1 -0
  18. package/dist/run-serve-CbKxIu6i.js +418 -0
  19. package/dist/run-serve-CbKxIu6i.js.map +1 -0
  20. package/dist/{run-tui-D-N4_yyX.js → run-tui-B0AQWbad.js} +6 -37
  21. package/dist/run-tui-B0AQWbad.js.map +1 -0
  22. package/dist/{schemaDrift-BkN8rLiZ.js → schemaDrift-CbsABBuk.js} +59 -5
  23. package/dist/schemaDrift-CbsABBuk.js.map +1 -0
  24. package/dist/serve-web.js +48 -48
  25. package/dist/{state-CZsYJqB6.js → state-C2oDiQ26.js} +146 -60
  26. package/dist/state-C2oDiQ26.js.map +1 -0
  27. package/dist/web.d.ts +115 -14
  28. package/dist/web.js +202 -62
  29. package/dist/web.js.map +1 -1
  30. package/examples/README.md +2 -0
  31. package/examples/media/README.md +6 -5
  32. package/examples/media/voice_en_6s.flac +0 -0
  33. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +9 -1
  34. package/examples/rvion/10-anima-t2i.cflow.ts +8 -1
  35. package/examples/rvion/15-tts-voice-clone.cflow.ts +111 -0
  36. package/examples/rvion/16-tts-voice-design.cflow.ts +71 -0
  37. package/guide-for-agents.md +5 -1
  38. package/package.json +2 -2
  39. package/src/cli/comfy-ts-cli.ts +14 -1
  40. package/src/cli/run/findModules.ts +36 -0
  41. package/src/cli/run/flagValue.ts +61 -0
  42. package/src/cli/run/outputPaths.ts +41 -0
  43. package/src/cli/run/pickModule.ts +41 -0
  44. package/src/cli/run/run-run.ts +250 -0
  45. package/src/cli/run/runArgs.ts +61 -0
  46. package/src/cli/run/sidecar.ts +27 -0
  47. package/src/cli/serve/ServeApp.ts +28 -42
  48. package/src/cli/serve/web/components/DraftTabs.tsx +10 -3
  49. package/src/cli/serve/web/components/Gallery.tsx +2 -1
  50. package/src/cli/serve/web/components/HistoryPicker.tsx +5 -3
  51. package/src/cli/serve/web/components/MenuButton.tsx +2 -4
  52. package/src/cli/serve/web/components/Omnibox.tsx +2 -1
  53. package/src/cli/serve/web/components/PromptEnhancer.tsx +4 -3
  54. package/src/cli/serve/web/components/ShortcutsModal.tsx +2 -1
  55. package/src/cli/serve/web/components/SideMenu.tsx +2 -1
  56. package/src/cli/serve/web/components/controls/LorasControl.tsx +4 -3
  57. package/src/cli/serve/web/components/controls/PresetPicker.tsx +2 -1
  58. package/src/cli/serve/web/components/controls/PromptControl.tsx +2 -1
  59. package/src/cli/serve/web/components/controls/SizeControl.tsx +2 -1
  60. package/src/cli/serve/web/state/draftTabs.ts +12 -0
  61. package/src/cli/serve/web/state/escape.ts +16 -0
  62. package/src/cli/serve/web/state/shortcutCatalog.ts +1 -0
  63. package/src/coreExports.ts +12 -1
  64. package/src/host/ComfyHost.ts +73 -40
  65. package/src/host/previewMethod.ts +29 -0
  66. package/src/runner/ComfyExecution.ts +45 -1
  67. package/src/runner/ComfyWorkflow.ts +6 -1
  68. package/src/runner/ComfyWsApi.ts +1 -1
  69. package/src/runner/wsBinaryFrame.ts +48 -25
  70. package/src/vars/ComfyVars.ts +86 -13
  71. package/src/vars/DefinedWorkflow.ts +36 -2
  72. package/dist/LogsSt-C3UIWR-o.js.map +0 -1
  73. package/dist/run-serve-B5PfIuhK.js.map +0 -1
  74. package/dist/run-tui-D-N4_yyX.js.map +0 -1
  75. package/dist/schemaDrift-BkN8rLiZ.js.map +0 -1
  76. package/dist/state-CZsYJqB6.js.map +0 -1
@@ -0,0 +1,250 @@
1
+ // `comfy-ts run`: one generation from the command line, headless (architecture.md item 15).
2
+ // It is serve's generate path in process: a ServeApp over the one module, handle(POST
3
+ // /generate/…), so drafts, payload checks, the media gate and seeds are serve's own code. Only
4
+ // the starter differs (live progress, nothing saved by the runner) and the outputs land where
5
+ // --out says
6
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
7
+ import { pathToFileURL } from 'node:url'
8
+ import { basename, dirname, resolve } from 'pathe'
9
+ import type { DefinedWorkflow } from 'src/vars/DefinedWorkflow.ts'
10
+ import { flagValue, type FlagSpec } from 'src/cli/run/flagValue.ts'
11
+ import { outputPaths, sidecarPath } from 'src/cli/run/outputPaths.ts'
12
+ import { pickModule } from 'src/cli/run/pickModule.ts'
13
+ import { sidecarFills } from 'src/cli/run/sidecar.ts'
14
+ import { parseRunArgs } from 'src/cli/run/runArgs.ts'
15
+ import { describeVar, renderDescriptorLine } from 'src/cli/serve/describeVar.ts'
16
+ import { ServeApp, type ServeExecution, type ServeStarter } from 'src/cli/serve/ServeApp.ts'
17
+ import { findModules, workspaceOf } from 'src/cli/run/findModules.ts'
18
+ import { mergeWorkflowSources, scanCflowFiles } from 'src/cli/tui/discoverWorkflows.ts'
19
+ import { findDefinedWorkflow } from 'src/cli/tui/findDefinedWorkflow.ts'
20
+ import { moduleName } from 'src/cli/tui/treeRows.ts'
21
+ import { bundledExamplesDir } from 'src/exampleAssets.ts'
22
+ import { ComfyTS } from 'src/state.ts'
23
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
24
+
25
+ const USAGE = `comfy-ts run <name | module.cflow.ts> [--draft <name>] [--<var> <value>…] [--out <path>] [--json]
26
+ one generation, headless, with live progress. <name> is a module key (10-anima-t2i), the key
27
+ without its number (anima-t2i), or a unique part of it (anima). \`comfy-ts run <name> --help\`
28
+ lists the module's vars. --<var>-file <path> reads a text var from a file. --out a.png writes
29
+ there (several outputs: a-1.png, a-2.png), --out dir/ keeps the server's names, no --out
30
+ writes <module>-<id>.<ext> here. Text outputs go beside the first media output as <stem>.txt.
31
+ --json prints one line with every output path, --verbose shows the library log on stderr`
32
+
33
+ type Out = { path: string; note: string | null; bytes: Uint8Array | null; from: string | null }
34
+
35
+ function discover(cwd: string): string[] {
36
+ const bundledDir = bundledExamplesDir()
37
+ return mergeWorkflowSources({
38
+ explicitTarget: false,
39
+ scanned: findModules(cwd),
40
+ bundledFiles: bundledDir == null ? [] : scanCflowFiles(bundledDir),
41
+ }).files
42
+ }
43
+
44
+ const log = (line: string): void => void process.stderr.write(`${line}\n`)
45
+
46
+ export async function runRun(argv: string[]): Promise<number> {
47
+ const args = parseRunArgs(argv)
48
+ if ('error' in args) {
49
+ log(`[comfy-ts run] ${args.error}`)
50
+ return 1
51
+ }
52
+ // stdout carries the result lines only (one json line under --json): the library's info
53
+ // chatter is silenced, and a stray console.log reaches stderr under --verbose, else nowhere
54
+ const say = console.log.bind(console)
55
+ if (!args.verbose) process.env.COMFY_TS_QUIET = '1'
56
+ console.log = (...a: unknown[]): void => {
57
+ if (args.verbose) console.error(...a)
58
+ }
59
+ const cwd = process.cwd()
60
+ const explicit = args.name != null && /\.cflow\.tsx?$/.test(args.name) ? resolve(cwd, args.name) : null
61
+ const files = explicit != null ? [explicit] : discover(cwd)
62
+ if (args.name == null) {
63
+ say(USAGE)
64
+ const names = [...new Set(files.map((f) => `${basename(dirname(f))}/${moduleName(f)}`))]
65
+ say(`\nmodules:\n${names.map((k) => ` ${k}`).join('\n')}`)
66
+ return 0
67
+ }
68
+ if (explicit != null && !existsSync(explicit)) {
69
+ log(`[comfy-ts run] no such file: ${explicit}`)
70
+ return 1
71
+ }
72
+ const picked = explicit != null ? { file: explicit, key: moduleName(explicit) } : pickModule(files, args.name)
73
+ if ('error' in picked) {
74
+ log(`[comfy-ts run] ${picked.error}`)
75
+ return 1
76
+ }
77
+
78
+ // rooted at the module's workspace before its import registers one at the cwd: its schema
79
+ // cache and drafts are there, and --out and media paths still resolve against the cwd
80
+ ComfyTS.create({ rootPath: workspaceOf(picked.file) ?? cwd })
81
+ let dw: DefinedWorkflow
82
+ try {
83
+ const found = findDefinedWorkflow((await import(pathToFileURL(picked.file).href)) as Record<string, unknown>)
84
+ if (found == null) throw new Error('it exports no DefinedWorkflow')
85
+ dw = found
86
+ } catch (e) {
87
+ log(`[comfy-ts run] ${picked.file}: ${extractErrorMessage(e)}`)
88
+ return 1
89
+ }
90
+ const vars = new Map(dw.entries())
91
+
92
+ if (args.help) {
93
+ say(`comfy-ts run ${picked.key} (${picked.file})\n\nvars, each one a --<name> <value> flag:`)
94
+ const width = Math.max(0, ...[...vars.keys()].map((k) => k.length))
95
+ for (const [k, v] of vars) {
96
+ const d = describeVar(v)
97
+ // the cli's own forms where they differ from serve's json payload
98
+ const payload =
99
+ v.kind === 'seed'
100
+ ? 'a number, or ? for a random one'
101
+ : v.kind === 'toggle'
102
+ ? 'true | false, or the bare flag'
103
+ : v.kind === 'text' || v.kind === 'prompt'
104
+ ? `${d.payload}, or --${k}-file <path>`
105
+ : d.payload
106
+ say(renderDescriptorLine(k, { ...d, payload }, width))
107
+ }
108
+ return 0
109
+ }
110
+
111
+ // the flags, shaped by each var's own kind
112
+ const payload: Record<string, unknown> = {}
113
+ for (const [name, raw] of args.vars) {
114
+ const fileOf = name.endsWith('-file') ? name.slice(0, -'-file'.length) : null
115
+ const target = fileOf != null && vars.has(fileOf) ? fileOf : name
116
+ const v = vars.get(target)
117
+ if (v == null) {
118
+ log(`[comfy-ts run] ${picked.key} has no var '${name}'. Vars: ${[...vars.keys()].join(', ')}`)
119
+ return 1
120
+ }
121
+ if (target !== name) {
122
+ if (raw === true) {
123
+ log(`[comfy-ts run] --${name} needs a path`)
124
+ return 1
125
+ }
126
+ const path = resolve(cwd, raw)
127
+ if (!existsSync(path)) {
128
+ log(`[comfy-ts run] --${name}: no such file ${path}`)
129
+ return 1
130
+ }
131
+ payload[target] = readFileSync(path, 'utf8').trim()
132
+ continue
133
+ }
134
+ // kind, never instanceof (agent/coding.md cast whitelist 6)
135
+ const spec: FlagSpec = { kind: v.kind, select: v.kind === 'choice' ? describeVar(v).select : undefined }
136
+ const shaped = flagValue({ name, spec, raw, cwd })
137
+ if ('error' in shaped) {
138
+ log(`[comfy-ts run] ${shaped.error}`)
139
+ return 1
140
+ }
141
+ payload[name] = shaped.value
142
+ }
143
+ // a media file's <file>.txt fills the text var its declaration links (a clip's transcript)
144
+ for (const fill of sidecarFills([...vars], payload, existsSync)) {
145
+ payload[fill.name] = readFileSync(fill.from, 'utf8').trim()
146
+ if (!args.json) log(` ${fill.name} from ${fill.from}`)
147
+ }
148
+
149
+ let execution: ServeExecution | null = null
150
+ const starter: ServeStarter = async (mod, opts) => {
151
+ const host = opts.host ?? mod.dw.host
152
+ await host.connect()
153
+ const wf = await mod.dw.build({ advance: true, host })
154
+ const ex = await wf.start({ save: false, log: !args.json })
155
+ execution = ex
156
+ return ex
157
+ }
158
+ const app = new ServeApp([{ key: picked.key, file: picked.file, dw }], { starter })
159
+ if (!args.json) log(`▶ ${dw.host.data.id} · ${picked.key}/${args.draft}`)
160
+ const t0 = Date.now()
161
+ let code = 0
162
+ try {
163
+ const reply = await app.handle({
164
+ method: 'POST',
165
+ url: `/generate/${encodeURIComponent(picked.key)}/${encodeURIComponent(args.draft)}`,
166
+ body: JSON.stringify(payload),
167
+ })
168
+ const body = JSON.parse(typeof reply.body === 'string' ? reply.body : new TextDecoder().decode(reply.body)) as {
169
+ ok?: boolean
170
+ error?: string
171
+ seeds?: Record<string, number>
172
+ promptId?: string
173
+ durationMs?: number
174
+ }
175
+ const ex = execution as ServeExecution | null
176
+ if (reply.status !== 200 || body.ok !== true || ex == null) {
177
+ const error = body.error ?? `serve answered ${reply.status}`
178
+ if (args.json) say(JSON.stringify({ ok: false, module: picked.key, draft: args.draft, error }))
179
+ else log(`\n✗ ${picked.key}/${args.draft}: ${error}`)
180
+ return 1
181
+ }
182
+
183
+ const media: { filename: string; bytes: Uint8Array | null; from: string | null }[] = [
184
+ ...ex.images.map((i) => ({ filename: i.filename, bytes: i.buffer ?? null, from: i.absPath })),
185
+ ...(ex.audios ?? []).map((a) => ({ filename: a.filename, bytes: a.bytes, from: a.absPath })),
186
+ ...(ex.videos ?? []).map((a) => ({ filename: a.filename, bytes: a.bytes, from: a.absPath })),
187
+ ]
188
+ const outIsDir =
189
+ args.out != null &&
190
+ (/[/\\]$/.test(args.out) ||
191
+ (existsSync(resolve(cwd, args.out)) && statSync(resolve(cwd, args.out)).isDirectory()))
192
+ const dests = outputPaths({
193
+ out: args.out,
194
+ outIsDir,
195
+ module: picked.key,
196
+ promptId: body.promptId ?? ex.data.id,
197
+ items: media,
198
+ cwd,
199
+ })
200
+ const outs: Out[] = media.map((m, i) => ({ ...dests[i]!, bytes: m.bytes, from: m.from }))
201
+ for (const o of outs) {
202
+ const bytes = o.bytes ?? (o.from != null ? new Uint8Array(readFileSync(o.from)) : null)
203
+ if (bytes == null) throw new Error(`an output of ${picked.key} came back with no bytes`)
204
+ mkdirSync(dirname(o.path), { recursive: true })
205
+ writeFileSync(o.path, bytes)
206
+ }
207
+ const texts = (ex.texts ?? []).map((t) => t.text)
208
+ const written = outs.map((o) => o.path)
209
+ if (texts.length > 0) {
210
+ const first = outs[0]
211
+ if (first != null) {
212
+ writeFileSync(sidecarPath(first.path), `${texts.join('\n')}\n`)
213
+ written.push(sidecarPath(first.path))
214
+ } else if (args.out != null && !outIsDir) {
215
+ const path = resolve(cwd, args.out)
216
+ mkdirSync(dirname(path), { recursive: true })
217
+ writeFileSync(path, `${texts.join('\n')}\n`)
218
+ written.push(path)
219
+ } else if (!args.json) for (const t of texts) say(t)
220
+ }
221
+ const durationMs = body.durationMs ?? Date.now() - t0
222
+ if (args.json)
223
+ say(
224
+ JSON.stringify({
225
+ ok: true,
226
+ module: picked.key,
227
+ draft: args.draft,
228
+ seeds: body.seeds ?? {},
229
+ durationMs,
230
+ outputs: written,
231
+ texts,
232
+ }),
233
+ )
234
+ else {
235
+ const seeds = Object.entries(body.seeds ?? {})
236
+ .map(([k, v]) => `${k} ${v}`)
237
+ .join(', ')
238
+ for (const o of outs) log(`✓ ${o.path}${o.note == null ? '' : ` (${o.note})`}`)
239
+ for (const w of written.slice(outs.length)) log(`✓ ${w}`)
240
+ log(` ${(durationMs / 1000).toFixed(1)}s${seeds === '' ? '' : ` · ${seeds}`}`)
241
+ if (written.length === 0) log(' the run produced no output')
242
+ }
243
+ } catch (e) {
244
+ log(`[comfy-ts run] 🔴 ${extractErrorMessage(e)}`)
245
+ code = 1
246
+ } finally {
247
+ for (const [, h] of comfyts.hosts) h.disconnect()
248
+ }
249
+ return code
250
+ }
@@ -0,0 +1,61 @@
1
+ // `comfy-ts run [name] [--draft d] [--out p] [--json] [--verbose] [--help] [--<var> value | --<var>=value | --<toggle>]`
2
+ // Pure: the vars stay strings here, the module's own var kinds shape them later (flagValue)
3
+
4
+ export type RunArgs = {
5
+ name: string | null
6
+ draft: string
7
+ out: string | null
8
+ json: boolean
9
+ /** the library's own log lines, on stderr */
10
+ verbose: boolean
11
+ help: boolean
12
+ /** in command line order; `true` = a bare flag */
13
+ vars: [string, string | true][]
14
+ }
15
+
16
+ const OWN = new Set(['draft', 'out'])
17
+
18
+ export function parseRunArgs(argv: readonly string[]): RunArgs | { error: string } {
19
+ const r: RunArgs = { name: null, draft: 'default', out: null, json: false, verbose: false, help: false, vars: [] }
20
+ for (let i = 0; i < argv.length; i++) {
21
+ const a = argv[i]!
22
+ if (a === '-h' || a === '--help') {
23
+ r.help = true
24
+ continue
25
+ }
26
+ if (a === '--json') {
27
+ r.json = true
28
+ continue
29
+ }
30
+ if (a === '--verbose') {
31
+ r.verbose = true
32
+ continue
33
+ }
34
+ if (!a.startsWith('--')) {
35
+ if (r.name != null) return { error: `one module per run: got '${r.name}' and '${a}'` }
36
+ r.name = a
37
+ continue
38
+ }
39
+ const eq = a.indexOf('=')
40
+ const key = eq < 0 ? a.slice(2) : a.slice(2, eq)
41
+ if (key === '') return { error: `'${a}' names no var` }
42
+ let value: string | true
43
+ if (eq >= 0) value = a.slice(eq + 1)
44
+ else {
45
+ const next = argv[i + 1]
46
+ if (next == null || next.startsWith('--')) value = true
47
+ else {
48
+ value = next
49
+ i++
50
+ }
51
+ }
52
+ if (OWN.has(key)) {
53
+ if (value === true) return { error: `--${key} needs a value` }
54
+ if (key === 'draft') r.draft = value
55
+ else r.out = value
56
+ continue
57
+ }
58
+ r.vars.push([key, value])
59
+ }
60
+ return r
61
+ }
@@ -0,0 +1,27 @@
1
+ // the text a media file carries beside it: a media var set from `clip.flac` whose declaration
2
+ // links a text var (`v.audio(path, { sidecarText })`) fills that var from `clip.txt`, unless the
3
+ // flags set it. The link is the workflow's, so run knows no var name
4
+ import type { AnyVar, MediaVar } from 'src/vars/ComfyVars.ts'
5
+ import { sidecarPath } from 'src/cli/run/outputPaths.ts'
6
+
7
+ const MEDIA = new Set(['image', 'audio', 'video'])
8
+
9
+ /** each var to fill, with the sidecar it comes from */
10
+ export function sidecarFills(
11
+ entries: readonly (readonly [string, AnyVar])[],
12
+ payload: Readonly<Record<string, unknown>>,
13
+ exists: (path: string) => boolean,
14
+ ): { name: string; from: string }[] {
15
+ const out: { name: string; from: string }[] = []
16
+ for (const [k, v] of entries) {
17
+ const path = payload[k]
18
+ // kind, never instanceof (agent/coding.md cast whitelist 6)
19
+ if (!MEDIA.has(v.kind) || typeof path !== 'string' || /^https?:\/\//.test(path)) continue
20
+ const linked = (v as MediaVar).opts.sidecarText
21
+ const name = linked == null ? null : entries.find(([, x]) => x === linked)?.[0]
22
+ if (name == null || name in payload || out.some((o) => o.name === name)) continue
23
+ const from = sidecarPath(path)
24
+ if (exists(from)) out.push({ name, from })
25
+ }
26
+ return out
27
+ }
@@ -74,7 +74,7 @@ import {
74
74
  import { getLoraKeyword } from 'src/vars/loraKeywords.ts'
75
75
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
76
76
  import { DEFAULT_MEDIA_EXTENSIONS, MEDIA_KINDS, type MediaKind } from 'src/runner/mediaKinds.ts'
77
- import type { LorasVar, MediaVar, PromptVar, SeedVar } from 'src/vars/ComfyVars.ts'
77
+ import type { ChoiceVar, LorasVar, MediaVar, OptionalChoiceVar, PromptVar, SeedVar } from 'src/vars/ComfyVars.ts'
78
78
  import type { DefinedWorkflow } from 'src/vars/DefinedWorkflow.ts'
79
79
  import { bang } from 'src/utils/bang.ts'
80
80
  import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
@@ -111,7 +111,13 @@ export type ServeExecution = {
111
111
 
112
112
  export type ServeStarter = (
113
113
  mod: ServeModule,
114
- opts: { saveToDisk: boolean; savePrefix: string; host?: ComfyHost },
114
+ opts: {
115
+ saveToDisk: boolean
116
+ savePrefix: string
117
+ host?: ComfyHost
118
+ /** the run's live preview frames, feeding the /run/<module>/preview poll */
119
+ onPreview?: (p: { bytes: Uint8Array; mime: string }) => void
120
+ },
115
121
  ) => Promise<ServeExecution>
116
122
 
117
123
  export type ServeRequest = { method: string; url: string; accept?: string; body?: string }
@@ -231,7 +237,7 @@ const realStarter: ServeStarter = async (mod, opts) => {
231
237
  const wf = await mod.dw.build({ advance: true, host })
232
238
  // saving is a SETTING now (GET/PUT /settings): off keeps outputs in memory and the
233
239
  // reply points at /images/<promptId>/<ix> instead of a file url
234
- return await wf.start({ save: opts.saveToDisk ? { prefix: opts.savePrefix } : false })
240
+ return await wf.start({ save: opts.saveToDisk ? { prefix: opts.savePrefix } : false, onPreview: opts.onPreview })
235
241
  }
236
242
 
237
243
  const CONTENT_TYPES: Record<string, string> = {
@@ -950,13 +956,13 @@ export class ServeApp {
950
956
  const dropped =
951
957
  rebound.stale.length === 0
952
958
  ? ''
953
- : `. dropped ${rebound.stale.length} selection(s) this host no longer lists`
959
+ : `. ${rebound.stale.length} selection(s) this host no longer lists (a lora is dropped, a model stays picked)`
954
960
  return json(200, {
955
961
  ok: true,
956
962
  host: hostId,
957
963
  action,
958
964
  stale: rebound.stale,
959
- note: `schema refetched: ${nodes} node types, ${loras} loras, ${rebound.widened} lora var(s) changed${dropped}${lorasNote}`,
965
+ note: `schema refetched: ${nodes} node types, ${loras} loras, ${rebound.widened} lora or model var(s) changed${dropped}${lorasNote}`,
960
966
  })
961
967
  }
962
968
  if (action === 'restart') {
@@ -993,6 +999,18 @@ export class ServeApp {
993
999
  if (mod.dw.host.data.id !== hostId) continue
994
1000
  await this.exclusive(mod.key, () => {
995
1001
  for (const [name, varDef] of mod.dw.entries()) {
1002
+ if (varDef.kind === 'choice') {
1003
+ const choice = varDef as ChoiceVar<string> | OptionalChoiceVar<string>
1004
+ if (choice.hostSlot == null) continue
1005
+ const before = choice.choices.length
1006
+ choice.bindHost(host)
1007
+ if (choice.choices.length !== before) widened++
1008
+ // a model the box no longer lists stays picked: the run then fails on the host,
1009
+ // naming the file, instead of silently running another model
1010
+ if (choice.value != null && !choice.choices.includes(choice.value))
1011
+ stale.push(`${mod.key}/${name}: ${choice.value}`)
1012
+ continue
1013
+ }
996
1014
  if (varDef.kind !== 'loras') continue
997
1015
  const lorasVar = varDef as LorasVar<string>
998
1016
  if (lorasVar.optionsFilter == null) continue // a plain array never re-resolves
@@ -1435,31 +1453,6 @@ export class ServeApp {
1435
1453
  /** seq counts frames so the poller refetches only on a NEW one, not every tick */
1436
1454
  private latentPreviews = new Map<string, { bytes: Uint8Array; mime: string; seq: number }>()
1437
1455
  private latentSeq = 0
1438
- /** promptId → module: `onLatentPreview` is ONE slot per host and two modules can share a
1439
- * host, so frames are routed by the prompt they belong to, never by "the last run started" */
1440
- private promptOwner = new Map<string, string>()
1441
- private latentHosts = new Set<ComfyHost>()
1442
-
1443
- private runningModules(): string[] {
1444
- return [...this.liveRuns.entries()]
1445
- .filter(([, e]) => e.status !== 'Success' && e.status !== 'Failure')
1446
- .map(([key]) => key)
1447
- }
1448
-
1449
- /** one dispatcher per host, installed once and left in place (idempotent) */
1450
- private wireLatents(host: ComfyHost): void {
1451
- if (this.latentHosts.has(host)) return
1452
- this.latentHosts.add(host)
1453
- host.onLatentPreview = (p) => {
1454
- const owner = p.promptID != null ? this.promptOwner.get(p.promptID) : undefined
1455
- // an unattributable frame (no promptID yet, e.g. before start() returned) is only
1456
- // safe to show when exactly ONE run is live; otherwise drop it rather than lie
1457
- const running = this.runningModules()
1458
- const key = owner ?? (running.length === 1 ? running[0] : undefined)
1459
- if (key == null) return
1460
- this.latentPreviews.set(key, { bytes: p.bytes, mime: p.mime, seq: ++this.latentSeq })
1461
- }
1462
- }
1463
1456
 
1464
1457
  private replyRunStatus(modKey: string): ServeReply {
1465
1458
  const mod = this.moduleByKey(modKey)
@@ -1623,13 +1616,8 @@ export class ServeApp {
1623
1616
 
1624
1617
  const execution = started.execution
1625
1618
  this.liveRuns.set(mod.key, execution)
1626
- this.promptOwner.set(execution.data.id, mod.key)
1627
1619
  console.log(`[serve] → ${mod.key}/${draft} (prompt ${execution.data.id})`)
1628
- try {
1629
- await execution.done
1630
- } finally {
1631
- this.promptOwner.delete(execution.data.id)
1632
- }
1620
+ await execution.done
1633
1621
  const durationMs = Date.now() - t0
1634
1622
 
1635
1623
  if (execution.status === 'Failure') {
@@ -1846,20 +1834,18 @@ export class ServeApp {
1846
1834
  }
1847
1835
 
1848
1836
  // 5. send (build + POST /prompt); the wait for outputs happens OUTSIDE the mutex.
1849
- // latent frames feed the web ui's /run/<module>/preview poll (ExecSt's pattern);
1850
- // the previous run's preview must not linger over the new one
1837
+ // the run's own preview frames feed the web ui's /run/<module>/preview poll; the
1838
+ // previous run's preview must not linger over the new one
1851
1839
  this.latentPreviews.delete(mod.key)
1852
- // the host the run ACTUALLY goes to: onLatentPreview is one slot per ComfyHost, so
1853
- // wiring the defining host while running on an override left the override host with no
1854
- // dispatcher, the panel simply never saw a frame, with nothing to say why
1855
1840
  const runHost = this.runHostFor(mod)
1856
- this.wireLatents(runHost ?? mod.dw.host)
1857
1841
  try {
1858
1842
  return {
1859
1843
  execution: await this.starter(mod, {
1860
1844
  saveToDisk: this.settings.saveToDisk,
1861
1845
  savePrefix: this.savePrefixFor(mod.key),
1862
1846
  host: runHost ?? undefined,
1847
+ onPreview: (p) =>
1848
+ this.latentPreviews.set(mod.key, { bytes: p.bytes, mime: p.mime, seq: ++this.latentSeq }),
1863
1849
  }),
1864
1850
  }
1865
1851
  } catch (e) {
@@ -1,6 +1,6 @@
1
1
  // the open drafts as tabs over the work area: a click opens one (a click on the open one shows
2
2
  // its actions), × or a middle click closes it, ⌘1 to ⌘8 pick one, ⌘9 the last, ⌘PageUp and
3
- // ⌘PageDown step (ctrl elsewhere), from any focus
3
+ // ⌘PageDown step, ⌘W closes the open one unless it is the last (ctrl elsewhere), from any focus
4
4
  import {
5
5
  autoUpdate,
6
6
  flip,
@@ -15,13 +15,20 @@ import { observer } from 'mobx-react-lite'
15
15
  import { useEffect, useState } from 'react'
16
16
  import { Icon } from 'src/cli/serve/web/components/Icon.tsx'
17
17
  import { MOD_KEY } from 'src/cli/serve/web/components/modKey.ts'
18
- import { tabForKey, tabStepForKey, type DraftTab } from 'src/cli/serve/web/state/draftTabs.ts'
18
+ import { tabForKey, tabStepForKey, tabToCloseForKey, type DraftTab } from 'src/cli/serve/web/state/draftTabs.ts'
19
19
  import { shortcutLabel } from 'src/cli/serve/web/state/shortcuts.ts'
20
20
  import type { WebSt } from 'src/cli/serve/web/state/WebSt.ts'
21
+ import { onEscape } from 'src/cli/serve/web/state/escape.ts'
21
22
 
22
23
  export function useTabShortcuts(st: WebSt): void {
23
24
  useEffect(() => {
24
25
  const onKey = (e: KeyboardEvent): void => {
26
+ const closing = tabToCloseForKey(st.tabs, st.activeTab, e)
27
+ if (closing != null) {
28
+ e.preventDefault()
29
+ st.closeTab(closing)
30
+ return
31
+ }
25
32
  const t = tabForKey(st.tabs, e) ?? tabStepForKey(st.tabs, st.activeTab, e)
26
33
  if (t == null) return
27
34
  e.preventDefault()
@@ -128,7 +135,7 @@ const TabMenu = observer(function TabMenu(p: { st: WebSt; tab: DraftTab; anchor:
128
135
  onChange={(e) => setName(e.target.value)}
129
136
  onKeyDown={(e) => {
130
137
  if (e.key === 'Enter') rename()
131
- if (e.key === 'Escape') p.onClose()
138
+ onEscape(e, () => p.onClose())
132
139
  }}
133
140
  />
134
141
  <button
@@ -14,6 +14,7 @@ import { copyImageToClipboard } from 'src/cli/serve/web/clipboard.ts'
14
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
+ import { onEscape } from 'src/cli/serve/web/state/escape.ts'
17
18
 
18
19
  /** on an output only the serve process holds: a restart, or the memory budget, loses it */
19
20
  function EphemeralPill(p: { out: { url: string | null; absPath: string | null } }): ReactNode {
@@ -149,7 +150,7 @@ const Lightbox = observer(function Lightbox(p: { st: WebSt; local: GalleryLocal
149
150
  useEffect(() => {
150
151
  if (target == null) return
151
152
  const onKey = (e: KeyboardEvent): void => {
152
- if (e.key === 'Escape') return p.local.closeLightbox()
153
+ if (onEscape(e, () => p.local.closeLightbox())) return
153
154
  const dir =
154
155
  e.key === 'ArrowDown' || e.key === 'ArrowRight' ? 1 : e.key === 'ArrowUp' || e.key === 'ArrowLeft' ? -1 : 0
155
156
  if (dir === 0) return
@@ -4,6 +4,7 @@
4
4
  import { useEffect, useRef, useState, type ReactNode } from 'react'
5
5
  import { Icon } from 'src/cli/serve/web/components/Icon.tsx'
6
6
  import { searchHistory, timeAgo, type HistoryEntry } from 'src/cli/serve/web/state/history.ts'
7
+ import { onEscape } from 'src/cli/serve/web/state/escape.ts'
7
8
 
8
9
  /** the button that opens it: always there, disabled while nothing was submitted yet. Plain (not
9
10
  * an observer) to stay generic: the observer parent reads the list and passes it down */
@@ -67,9 +68,10 @@ function HistoryPicker<V>(p: {
67
68
  // listener runs first and stops the event there
68
69
  useEffect(() => {
69
70
  const onKey = (e: KeyboardEvent): void => {
70
- if (e.key !== 'Escape') return
71
- e.stopImmediatePropagation()
72
- p.onClose()
71
+ onEscape(e, () => {
72
+ e.stopImmediatePropagation()
73
+ p.onClose()
74
+ })
73
75
  }
74
76
  window.addEventListener('keydown', onKey, true)
75
77
  return () => window.removeEventListener('keydown', onKey, true)
@@ -3,6 +3,7 @@
3
3
  // click, no document listener to leak
4
4
  import { useState, type ReactNode } from 'react'
5
5
  import { Icon } from 'src/cli/serve/web/components/Icon.tsx'
6
+ import { onEscape } from 'src/cli/serve/web/state/escape.ts'
6
7
 
7
8
  export function MenuButton(p: {
8
9
  tip: string
@@ -13,10 +14,7 @@ export function MenuButton(p: {
13
14
  const [open, setOpen] = useState(false)
14
15
  const close = (): void => setOpen(false)
15
16
  return (
16
- <span
17
- className={`preset-box menu-box ${p.className ?? ''}`}
18
- onKeyDown={(e) => (e.key === 'Escape' ? close() : undefined)}
19
- >
17
+ <span className={`preset-box menu-box ${p.className ?? ''}`} onKeyDown={(e) => onEscape(e, close)}>
20
18
  <button
21
19
  type="button"
22
20
  className="menu-btn"
@@ -7,6 +7,7 @@ import { Icon, type IconName } from 'src/cli/serve/web/components/Icon.tsx'
7
7
  import { entryKey, type OmniboxEntry } from 'src/cli/serve/web/state/omnibox.ts'
8
8
  import { isOmniboxKey } from 'src/cli/serve/web/state/shortcuts.ts'
9
9
  import type { WebSt } from 'src/cli/serve/web/state/WebSt.ts'
10
+ import { onEscape } from 'src/cli/serve/web/state/escape.ts'
10
11
 
11
12
  /** the first media tag picks the icon: what the workflow makes */
12
13
  const ICON_BY_TAG: Record<string, IconName> = { image: 'image', audio: 'audio', video: 'video', text: 'text' }
@@ -94,10 +95,10 @@ export const Omnibox = observer(function Omnibox(p: { st: WebSt }) {
94
95
  value={o.query}
95
96
  onChange={(e) => o.setQuery(e.target.value)}
96
97
  onKeyDown={(e) => {
98
+ if (onEscape(e, () => o.close())) return
97
99
  if (e.key === 'ArrowDown') o.move(1)
98
100
  else if (e.key === 'ArrowUp') o.move(-1)
99
101
  else if (e.key === 'Enter') o.pick()
100
- else if (e.key === 'Escape') o.close()
101
102
  else return
102
103
  e.preventDefault()
103
104
  }}
@@ -16,6 +16,7 @@ import {
16
16
  SHORTCUT_KEYS,
17
17
  type EnhancerShortcut,
18
18
  } from 'src/cli/serve/web/state/shortcuts.ts'
19
+ import { onEscape } from 'src/cli/serve/web/state/escape.ts'
19
20
 
20
21
  const EFFORTS: ReasoningEffort[] = ['off', 'low', 'medium', 'high']
21
22
 
@@ -473,11 +474,11 @@ const Modal = observer(function Modal(p: { e: EnhancerSt; st: WebSt }) {
473
474
  useEffect(() => {
474
475
  const onKey = (ev: KeyboardEvent): void => {
475
476
  // esc closes the editor first, the modal only when nothing is open over the job
476
- if (ev.key === 'Escape') {
477
+ const closed = onEscape(ev, () => {
477
478
  if (e.editing != null) e.setEditing(null)
478
479
  else e.close()
479
- return
480
- }
480
+ })
481
+ if (closed) return
481
482
  const s = enhancerShortcutOf(ev)
482
483
  if (s == null) return
483
484
  ev.preventDefault()
@@ -4,13 +4,14 @@ import { useEffect } from 'react'
4
4
  import { Icon } from 'src/cli/serve/web/components/Icon.tsx'
5
5
  import { shortcutCatalog } from 'src/cli/serve/web/state/shortcutCatalog.ts'
6
6
  import type { WebSt } from 'src/cli/serve/web/state/WebSt.ts'
7
+ import { onEscape } from 'src/cli/serve/web/state/escape.ts'
7
8
 
8
9
  export const ShortcutsModal = observer(function ShortcutsModal(p: { st: WebSt }) {
9
10
  const open = p.st.showShortcuts
10
11
  useEffect(() => {
11
12
  if (!open) return
12
13
  const onKey = (e: KeyboardEvent): void => {
13
- if (e.key === 'Escape') p.st.setShowShortcuts(false)
14
+ onEscape(e, () => p.st.setShowShortcuts(false))
14
15
  }
15
16
  window.addEventListener('keydown', onKey)
16
17
  return () => window.removeEventListener('keydown', onKey)
@@ -8,6 +8,7 @@ import { SHORTCUT_KEYS, shortcutLabel } from 'src/cli/serve/web/state/shortcuts.
8
8
  import type { PathLabel } from 'src/cli/serve/web/api.ts'
9
9
  import type { FormSt } from 'src/cli/serve/web/state/FormSt.ts'
10
10
  import { LAYOUTS, type WebSt } from 'src/cli/serve/web/state/WebSt.ts'
11
+ import { onEscape } from 'src/cli/serve/web/state/escape.ts'
11
12
 
12
13
  /** a titled block of rows; `actions` sit at the right end of the title */
13
14
  function Section(p: { title: string; actions?: ReactNode; children: ReactNode }): ReactNode {
@@ -67,7 +68,7 @@ const DraftSection = observer(function DraftSection(p: { st: WebSt; form: FormSt
67
68
  onChange={(e) => p.st.setRenaming(e.target.value)}
68
69
  onKeyDown={(e) => {
69
70
  if (e.key === 'Enter') confirm()
70
- if (e.key === 'Escape') p.st.stopRename()
71
+ onEscape(e, () => p.st.stopRename())
71
72
  }}
72
73
  // blur CANCELS, it does not commit: picking another draft blurs this input, and a
73
74
  // rename committed on blur raced that selection, renameDraft bails when the form