comfy-ts 2.16.0 → 2.17.1

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 (71) hide show
  1. package/README.md +23 -0
  2. package/dist/{run-serve-C78hD7t9.js → ServeApp-qXcQfdgT.js} +18 -445
  3. package/dist/ServeApp-qXcQfdgT.js.map +1 -0
  4. package/dist/cli.js +72 -9
  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-Ct7Le0S_.js → findDefinedWorkflow-0lG-VTEd.js} +201 -201
  9. package/dist/findDefinedWorkflow-0lG-VTEd.js.map +1 -0
  10. package/dist/index.cjs +182 -69
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +61 -8
  13. package/dist/index.d.ts +61 -8
  14. package/dist/index.js +182 -69
  15. package/dist/index.js.map +1 -1
  16. package/dist/run-run-tg82jUIk.js +450 -0
  17. package/dist/run-run-tg82jUIk.js.map +1 -0
  18. package/dist/run-serve-DaXzoVTS.js +464 -0
  19. package/dist/run-serve-DaXzoVTS.js.map +1 -0
  20. package/dist/{run-tui-nPETFRmk.js → run-tui-Bw7BA75d.js} +7 -38
  21. package/dist/run-tui-Bw7BA75d.js.map +1 -0
  22. package/dist/{schemaDrift-wb5XkrHV.js → schemaDrift-CbsABBuk.js} +3 -2
  23. package/dist/{schemaDrift-wb5XkrHV.js.map → schemaDrift-CbsABBuk.js.map} +1 -1
  24. package/dist/serve-web.js +56 -48
  25. package/dist/{state-BMW57_M0.js → state-zTow5ucI.js} +182 -70
  26. package/dist/state-zTow5ucI.js.map +1 -0
  27. package/dist/web.d.ts +61 -8
  28. package/dist/web.js +182 -69
  29. package/dist/web.js.map +1 -1
  30. package/examples/README.md +1 -0
  31. package/examples/rvion/15-tts-voice-clone.cflow.ts +8 -8
  32. package/examples/rvion/16-tts-voice-design.cflow.ts +71 -0
  33. package/guide-for-agents.md +3 -0
  34. package/package.json +2 -2
  35. package/src/cli/bunHop.ts +49 -0
  36. package/src/cli/comfy-ts-cli.ts +18 -5
  37. package/src/cli/run/findModules.ts +36 -0
  38. package/src/cli/run/flagValue.ts +61 -0
  39. package/src/cli/run/outputPaths.ts +41 -0
  40. package/src/cli/run/pickModule.ts +41 -0
  41. package/src/cli/run/run-run.ts +250 -0
  42. package/src/cli/run/runArgs.ts +61 -0
  43. package/src/cli/run/sidecar.ts +27 -0
  44. package/src/cli/serve/ServeApp.ts +13 -39
  45. package/src/cli/serve/run-serve.ts +51 -13
  46. package/src/cli/serve/web/components/App.tsx +2 -0
  47. package/src/cli/serve/web/components/DialogLayer.tsx +55 -0
  48. package/src/cli/serve/web/components/DraftTabs.tsx +16 -5
  49. package/src/cli/serve/web/components/PromptEnhancer.tsx +15 -9
  50. package/src/cli/serve/web/components/SideMenu.tsx +16 -8
  51. package/src/cli/serve/web/state/WebSt.ts +10 -1
  52. package/src/cli/serve/web/state/dialog.ts +59 -0
  53. package/src/cli/serve/web/state/draftTabs.ts +12 -0
  54. package/src/cli/serve/web/state/keptLines.ts +1 -1
  55. package/src/cli/serve/web/state/shortcutCatalog.ts +1 -0
  56. package/src/cli/serve/web/styles.ts +8 -0
  57. package/src/coreExports.ts +2 -0
  58. package/src/host/ComfyHost.ts +73 -40
  59. package/src/host/previewMethod.ts +29 -0
  60. package/src/litegraph/convertFlowToLiteGraphJSON.ts +38 -20
  61. package/src/promptEnhancers.ts +1 -1
  62. package/src/runner/ComfyExecution.ts +45 -1
  63. package/src/runner/ComfyWorkflow.ts +6 -1
  64. package/src/runner/ComfyWsApi.ts +1 -1
  65. package/src/runner/wsBinaryFrame.ts +48 -25
  66. package/src/vars/ComfyVars.ts +3 -0
  67. package/src/vars/DefinedWorkflow.ts +1 -0
  68. package/dist/LogsSt-Ct7Le0S_.js.map +0 -1
  69. package/dist/run-serve-C78hD7t9.js.map +0 -1
  70. package/dist/run-tui-nPETFRmk.js.map +0 -1
  71. package/dist/state-BMW57_M0.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
+ }
@@ -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> = {
@@ -1447,31 +1453,6 @@ export class ServeApp {
1447
1453
  /** seq counts frames so the poller refetches only on a NEW one, not every tick */
1448
1454
  private latentPreviews = new Map<string, { bytes: Uint8Array; mime: string; seq: number }>()
1449
1455
  private latentSeq = 0
1450
- /** promptId → module: `onLatentPreview` is ONE slot per host and two modules can share a
1451
- * host, so frames are routed by the prompt they belong to, never by "the last run started" */
1452
- private promptOwner = new Map<string, string>()
1453
- private latentHosts = new Set<ComfyHost>()
1454
-
1455
- private runningModules(): string[] {
1456
- return [...this.liveRuns.entries()]
1457
- .filter(([, e]) => e.status !== 'Success' && e.status !== 'Failure')
1458
- .map(([key]) => key)
1459
- }
1460
-
1461
- /** one dispatcher per host, installed once and left in place (idempotent) */
1462
- private wireLatents(host: ComfyHost): void {
1463
- if (this.latentHosts.has(host)) return
1464
- this.latentHosts.add(host)
1465
- host.onLatentPreview = (p) => {
1466
- const owner = p.promptID != null ? this.promptOwner.get(p.promptID) : undefined
1467
- // an unattributable frame (no promptID yet, e.g. before start() returned) is only
1468
- // safe to show when exactly ONE run is live; otherwise drop it rather than lie
1469
- const running = this.runningModules()
1470
- const key = owner ?? (running.length === 1 ? running[0] : undefined)
1471
- if (key == null) return
1472
- this.latentPreviews.set(key, { bytes: p.bytes, mime: p.mime, seq: ++this.latentSeq })
1473
- }
1474
- }
1475
1456
 
1476
1457
  private replyRunStatus(modKey: string): ServeReply {
1477
1458
  const mod = this.moduleByKey(modKey)
@@ -1635,13 +1616,8 @@ export class ServeApp {
1635
1616
 
1636
1617
  const execution = started.execution
1637
1618
  this.liveRuns.set(mod.key, execution)
1638
- this.promptOwner.set(execution.data.id, mod.key)
1639
1619
  console.log(`[serve] → ${mod.key}/${draft} (prompt ${execution.data.id})`)
1640
- try {
1641
- await execution.done
1642
- } finally {
1643
- this.promptOwner.delete(execution.data.id)
1644
- }
1620
+ await execution.done
1645
1621
  const durationMs = Date.now() - t0
1646
1622
 
1647
1623
  if (execution.status === 'Failure') {
@@ -1858,20 +1834,18 @@ export class ServeApp {
1858
1834
  }
1859
1835
 
1860
1836
  // 5. send (build + POST /prompt); the wait for outputs happens OUTSIDE the mutex.
1861
- // latent frames feed the web ui's /run/<module>/preview poll (ExecSt's pattern);
1862
- // 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
1863
1839
  this.latentPreviews.delete(mod.key)
1864
- // the host the run ACTUALLY goes to: onLatentPreview is one slot per ComfyHost, so
1865
- // wiring the defining host while running on an override left the override host with no
1866
- // dispatcher, the panel simply never saw a frame, with nothing to say why
1867
1840
  const runHost = this.runHostFor(mod)
1868
- this.wireLatents(runHost ?? mod.dw.host)
1869
1841
  try {
1870
1842
  return {
1871
1843
  execution: await this.starter(mod, {
1872
1844
  saveToDisk: this.settings.saveToDisk,
1873
1845
  savePrefix: this.savePrefixFor(mod.key),
1874
1846
  host: runHost ?? undefined,
1847
+ onPreview: (p) =>
1848
+ this.latentPreviews.set(mod.key, { bytes: p.bytes, mime: p.mime, seq: ++this.latentSeq }),
1875
1849
  }),
1876
1850
  }
1877
1851
  } catch (e) {
@@ -1,7 +1,8 @@
1
1
  // `comfy-ts serve [dir | module.cflow.ts] [--port N] [--host ADDR]`
2
2
  // drafts as a local HTTP generation API — agent/architecture.md item 12
3
+ import { spawnSync } from 'node:child_process'
3
4
  import { statSync } from 'node:fs'
4
- import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
5
+ import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
5
6
  import { networkInterfaces } from 'node:os'
6
7
  import { pathToFileURL } from 'node:url'
7
8
  import { dirname, resolve } from 'pathe'
@@ -151,23 +152,60 @@ export async function runServe(args: string[]): Promise<number> {
151
152
  workspace: typeof comfyts === 'undefined' ? process.cwd() : comfyts.rootPath,
152
153
  root: statSync(target).isDirectory() ? target : dirname(target),
153
154
  })
154
- printStartup(app, parsed.bind, parsed.port)
155
-
156
- const server = createServer(makeRequestListener(app))
157
-
158
- server.on('error', (e) => {
159
- console.error(`[comfy-ts serve] server error: ${extractErrorMessage(e)}`)
160
- process.exitCode = 1
161
- server.close()
162
- })
163
- server.listen(parsed.port, parsed.bind)
155
+ return listenUntilClosed(createServer(makeRequestListener(app)), parsed.port, parsed.bind, () =>
156
+ printStartup(app, parsed.bind, parsed.port),
157
+ )
158
+ }
164
159
 
165
- // stays up until the process is interrupted or the server dies
160
+ /** listens, then stays up until the server closes; resolves the exit code. A listen
161
+ * failure resolves 1 AT ONCE: bun fires no `close` for a server that never listened,
162
+ * and a cli awaiting one never ends (agent/architecture.md item 12) */
163
+ export function listenUntilClosed(
164
+ server: Server,
165
+ port: number,
166
+ bind: string,
167
+ onListening?: () => void,
168
+ ): Promise<number> {
166
169
  return new Promise<number>((resolveExit) => {
167
- server.on('close', () => resolveExit(typeof process.exitCode === 'number' ? process.exitCode : 0))
170
+ let listening = false
171
+ server.once('listening', () => {
172
+ listening = true
173
+ onListening?.()
174
+ })
175
+ server.on('error', (e) => {
176
+ if (!listening) {
177
+ console.error(`[comfy-ts serve] 🔴 ${describeListenError(e, port, bind)}`)
178
+ resolveExit(1)
179
+ return
180
+ }
181
+ console.error(`[comfy-ts serve] server error: ${extractErrorMessage(e)}`)
182
+ server.close()
183
+ resolveExit(1)
184
+ })
185
+ server.on('close', () => resolveExit(0))
186
+ server.listen(port, bind)
168
187
  })
169
188
  }
170
189
 
190
+ function describeListenError(e: Error, port: number, bind: string): string {
191
+ const code = 'code' in e ? e.code : undefined
192
+ if (code !== 'EADDRINUSE') return `cannot listen on ${bind}:${port}: ${extractErrorMessage(e)}`
193
+ const holder = portHolder(port)
194
+ const by = holder == null ? '' : ` by ${holder}`
195
+ return `port ${port} on ${bind} is taken${by}: stop it, or pick another port with --port <n>`
196
+ }
197
+
198
+ /** `pid <n> (<command>)` of the process listening on a tcp port; null when unknowable
199
+ * (no lsof on this box, or the holder is not visible to this user) */
200
+ export function portHolder(port: number): string | null {
201
+ const lsof = spawnSync('lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-t'], { encoding: 'utf8', timeout: 2000 })
202
+ const pid = lsof.error == null ? lsof.stdout.split('\n')[0]?.trim() : undefined
203
+ if (pid == null || pid === '') return null
204
+ const ps = spawnSync('ps', ['-o', 'command=', '-p', pid], { encoding: 'utf8', timeout: 2000 })
205
+ const command = ps.error == null ? ps.stdout.trim().slice(0, 160) : ''
206
+ return command === '' ? `pid ${pid}` : `pid ${pid} (${command})`
207
+ }
208
+
171
209
  export type Nic = { address: string; family: string | number; internal: boolean }
172
210
 
173
211
  /** the addresses this bind actually answers on. `0.0.0.0` means every interface, so printing
@@ -18,6 +18,7 @@ import { collapsedPreview } from 'src/cli/serve/web/state/stableSlots.ts'
18
18
  import { GenerateButton, VarsForm } from 'src/cli/serve/web/components/VarsForm.tsx'
19
19
  import { DraftTabs, useTabShortcuts } from 'src/cli/serve/web/components/DraftTabs.tsx'
20
20
  import { ShortcutsModal } from 'src/cli/serve/web/components/ShortcutsModal.tsx'
21
+ import { DialogLayer } from 'src/cli/serve/web/components/DialogLayer.tsx'
21
22
  import type { WebSt } from 'src/cli/serve/web/state/WebSt.ts'
22
23
 
23
24
  /** ⌘A / ctrl+A selects the field you are in. The browser does this on its own until something
@@ -529,6 +530,7 @@ export const App = observer(function App(p: { st: WebSt }) {
529
530
  {narrow ? <MenuDrawer st={p.st} /> : null}
530
531
  <Omnibox st={p.st} />
531
532
  <ShortcutsModal st={p.st} />
533
+ <DialogLayer />
532
534
  <TooltipLayer />
533
535
  </div>
534
536
  )
@@ -0,0 +1,55 @@
1
+ // the one open confirm or text prompt (state/dialog.ts), above every modal. Enter and esc are
2
+ // caught on the window in the CAPTURE phase, so the modal under it never sees them (esc there
3
+ // would close the enhancer along with the dialog)
4
+ import { observer } from 'mobx-react-lite'
5
+ import { useEffect } from 'react'
6
+ import { dialogs } from 'src/cli/serve/web/state/dialog.ts'
7
+ import { onEscape } from 'src/cli/serve/web/state/escape.ts'
8
+
9
+ export const DialogLayer = observer(function DialogLayer() {
10
+ const c = dialogs.current
11
+ const open = c != null
12
+ useEffect(() => {
13
+ if (!open) return
14
+ const onKey = (ev: KeyboardEvent): void => {
15
+ const handled =
16
+ onEscape(ev, () => dialogs.cancel()) ||
17
+ (ev.key === 'Enter' && !ev.isComposing && (ev.preventDefault(), dialogs.accept(), true))
18
+ if (handled) ev.stopPropagation()
19
+ }
20
+ window.addEventListener('keydown', onKey, true)
21
+ return () => window.removeEventListener('keydown', onKey, true)
22
+ }, [open])
23
+ if (c == null) return null
24
+ return (
25
+ <div className="modal-overlay dialog-overlay" onClick={() => dialogs.cancel()}>
26
+ <div className="modal dialog-modal" role="dialog" onClick={(ev) => ev.stopPropagation()}>
27
+ <div className="modal-body dialog-body">
28
+ <div className="dialog-message">{c.message}</div>
29
+ {c.kind === 'prompt' ? (
30
+ <input
31
+ type="text"
32
+ autoFocus
33
+ value={c.value}
34
+ onFocus={(ev) => ev.currentTarget.select()}
35
+ onChange={(ev) => dialogs.setValue(ev.target.value)}
36
+ />
37
+ ) : null}
38
+ </div>
39
+ <div className="dialog-actions">
40
+ <button type="button" onClick={() => dialogs.cancel()}>
41
+ cancel
42
+ </button>
43
+ <button
44
+ type="button"
45
+ autoFocus={c.kind === 'confirm'}
46
+ className={c.kind === 'confirm' && c.danger ? 'dialog-danger' : 'primary'}
47
+ onClick={() => dialogs.accept()}
48
+ >
49
+ {c.kind === 'confirm' ? c.ok : 'ok'}
50
+ </button>
51
+ </div>
52
+ </div>
53
+ </div>
54
+ )
55
+ })
@@ -1,6 +1,7 @@
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
+ import { dialogs } from 'src/cli/serve/web/state/dialog.ts'
4
5
  import {
5
6
  autoUpdate,
6
7
  flip,
@@ -15,7 +16,7 @@ import { observer } from 'mobx-react-lite'
15
16
  import { useEffect, useState } from 'react'
16
17
  import { Icon } from 'src/cli/serve/web/components/Icon.tsx'
17
18
  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'
19
+ import { tabForKey, tabStepForKey, tabToCloseForKey, type DraftTab } from 'src/cli/serve/web/state/draftTabs.ts'
19
20
  import { shortcutLabel } from 'src/cli/serve/web/state/shortcuts.ts'
20
21
  import type { WebSt } from 'src/cli/serve/web/state/WebSt.ts'
21
22
  import { onEscape } from 'src/cli/serve/web/state/escape.ts'
@@ -23,6 +24,12 @@ import { onEscape } from 'src/cli/serve/web/state/escape.ts'
23
24
  export function useTabShortcuts(st: WebSt): void {
24
25
  useEffect(() => {
25
26
  const onKey = (e: KeyboardEvent): void => {
27
+ const closing = tabToCloseForKey(st.tabs, st.activeTab, e)
28
+ if (closing != null) {
29
+ e.preventDefault()
30
+ st.closeTab(closing)
31
+ return
32
+ }
26
33
  const t = tabForKey(st.tabs, e) ?? tabStepForKey(st.tabs, st.activeTab, e)
27
34
  if (t == null) return
28
35
  e.preventDefault()
@@ -153,9 +160,13 @@ const TabMenu = observer(function TabMenu(p: { st: WebSt; tab: DraftTab; anchor:
153
160
  type="button"
154
161
  className="menu-row menu-action danger"
155
162
  onClick={() =>
156
- run(() => {
157
- if (window.confirm(`delete draft '${p.tab.draft}' of ${p.tab.module}? the file is removed.`))
158
- return p.st.deleteDraft(p.tab)
163
+ run(async () => {
164
+ const ok = await dialogs.confirm({
165
+ message: `delete draft '${p.tab.draft}' of ${p.tab.module}? the file is removed.`,
166
+ ok: 'delete',
167
+ danger: true,
168
+ })
169
+ if (ok) await p.st.deleteDraft(p.tab)
159
170
  })
160
171
  }
161
172
  >