comfy-ts 2.17.0 → 2.18.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 (100) hide show
  1. package/dist/{ServeApp-BSA5yzxZ.js → ServeApp-qXcQfdgT.js} +3 -3
  2. package/dist/ServeApp-qXcQfdgT.js.map +1 -0
  3. package/dist/cli.js +58 -8
  4. package/dist/cli.js.map +1 -1
  5. package/dist/index.cjs +956 -151
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +1154 -408
  8. package/dist/index.d.ts +1154 -408
  9. package/dist/index.js +956 -151
  10. package/dist/index.js.map +1 -1
  11. package/dist/{run-run-DnaMLCFn.js → run-run-Wn7H72Zg.js} +3 -3
  12. package/dist/{run-run-DnaMLCFn.js.map → run-run-Wn7H72Zg.js.map} +1 -1
  13. package/dist/{run-serve-CbKxIu6i.js → run-serve-DaXzoVTS.js} +58 -12
  14. package/dist/run-serve-DaXzoVTS.js.map +1 -0
  15. package/dist/{run-tui-B0AQWbad.js → run-tui-VWSj1D_j.js} +3 -3
  16. package/dist/{run-tui-B0AQWbad.js.map → run-tui-VWSj1D_j.js.map} +1 -1
  17. package/dist/serve-web.js +56 -48
  18. package/dist/{state-C2oDiQ26.js → state-DgwWhZWb.js} +957 -152
  19. package/dist/state-DgwWhZWb.js.map +1 -0
  20. package/dist/web.d.ts +1172 -426
  21. package/dist/web.js +956 -151
  22. package/dist/web.js.map +1 -1
  23. package/examples/comfy-cloud/ace-step15-t2a.cflow.ts +163 -0
  24. package/examples/comfy-cloud/anima-t2i-base.cflow.ts +57 -0
  25. package/examples/comfy-cloud/boogu-t2i.cflow.ts +55 -0
  26. package/examples/comfy-cloud/chronoedit-i2i.cflow.ts +95 -0
  27. package/examples/comfy-cloud/ernie-t2i-base.cflow.ts +81 -0
  28. package/examples/comfy-cloud/flux1-t2i-krea.cflow.ts +63 -0
  29. package/examples/comfy-cloud/flux2-i2i-dev.cflow.ts +83 -0
  30. package/examples/comfy-cloud/flux2-t2i-dev.cflow.ts +60 -0
  31. package/examples/comfy-cloud/hidream-o1-i2i.cflow.ts +71 -0
  32. package/examples/comfy-cloud/hidream-o1-t2i.cflow.ts +62 -0
  33. package/examples/comfy-cloud/krea2-i2i.cflow.ts +78 -0
  34. package/examples/comfy-cloud/ltx2-i2v.cflow.ts +175 -0
  35. package/examples/comfy-cloud/ltx2-t2v.cflow.ts +143 -0
  36. package/examples/comfy-cloud/ltx23-i2v.cflow.ts +189 -0
  37. package/examples/comfy-cloud/ltx23-t2v.cflow.ts +151 -0
  38. package/examples/comfy-cloud/mage-flow-i2i-turbo.cflow.ts +72 -0
  39. package/examples/comfy-cloud/mage-flow-i2i.cflow.ts +74 -0
  40. package/examples/comfy-cloud/mage-flow-t2i-turbo.cflow.ts +60 -0
  41. package/examples/comfy-cloud/mage-flow-t2i.cflow.ts +60 -0
  42. package/examples/comfy-cloud/minimax-h3-t2i.cflow.ts +64 -0
  43. package/examples/comfy-cloud/netayume-t2i.cflow.ts +60 -0
  44. package/examples/comfy-cloud/qwen-image-i2i-2509.cflow.ts +75 -0
  45. package/examples/comfy-cloud/qwen-image-t2i-2512.cflow.ts +63 -0
  46. package/examples/comfy-cloud/sdk.d.ts +21683 -13737
  47. package/examples/comfy-cloud/stable-audio3-t2a.cflow.ts +96 -0
  48. package/examples/comfy-cloud/z-image-t2i-base.cflow.ts +54 -0
  49. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +1 -1
  50. package/package.json +2 -2
  51. package/src/cli/bunHop.ts +49 -0
  52. package/src/cli/comfy-ts-cli.ts +4 -4
  53. package/src/cli/serve/run-serve.ts +51 -13
  54. package/src/cli/serve/web/components/App.tsx +2 -0
  55. package/src/cli/serve/web/components/DialogLayer.tsx +55 -0
  56. package/src/cli/serve/web/components/DraftTabs.tsx +8 -3
  57. package/src/cli/serve/web/components/PromptEnhancer.tsx +15 -9
  58. package/src/cli/serve/web/components/SideMenu.tsx +16 -8
  59. package/src/cli/serve/web/state/WebSt.ts +10 -1
  60. package/src/cli/serve/web/state/dialog.ts +59 -0
  61. package/src/cli/serve/web/state/keptLines.ts +1 -1
  62. package/src/cli/serve/web/styles.ts +8 -0
  63. package/src/graph/ComfyNode.ts +93 -12
  64. package/src/host/ComfyHost.ts +31 -10
  65. package/src/host/ComfyManager.ts +448 -62
  66. package/src/litegraph/CanonicalWorkflow.ts +3 -0
  67. package/src/litegraph/LiteGraphJSON.ts +2 -2
  68. package/src/litegraph/LiteGraphNodeInput.ts +2 -2
  69. package/src/litegraph/LiteGraphNodeOutput.ts +2 -2
  70. package/src/litegraph/convertFlowToLiteGraphJSON.ts +127 -34
  71. package/src/litegraph/expandSubgraphs.ts +14 -0
  72. package/src/litegraph/normalizeWorkflow.ts +1 -0
  73. package/src/manager/ComfyRegistry.ts +2 -0
  74. package/src/manager/generated/KnownComfyCustomNodeName.ts +6354 -1680
  75. package/src/manager/generated/KnownComfyPluginTitle.ts +718 -356
  76. package/src/manager/generated/KnownComfyPluginURL.ts +357 -181
  77. package/src/manager/generated/KnownModel_Base.ts +9 -5
  78. package/src/manager/generated/KnownModel_FileName.ts +135 -0
  79. package/src/manager/generated/KnownModel_Name.ts +135 -0
  80. package/src/manager/generated/KnownModel_SavePath.ts +16 -14
  81. package/src/manager/generated/KnownModel_Type.ts +15 -13
  82. package/src/manager/installedView.ts +176 -0
  83. package/src/manager/json/custom-node-list.json +4018 -2248
  84. package/src/manager/json/extension-node-map.json +8903 -2964
  85. package/src/manager/json/github-stats.json +10796 -10036
  86. package/src/manager/json/model-list.json +298 -1
  87. package/src/manager/loaders/step4_model-list-loader.ts +1 -0
  88. package/src/manager/types/ComfyManagerAPIModelList.ts +3 -0
  89. package/src/manager/types/ComfyManagerAPIPluginList.ts +19 -0
  90. package/src/promptEnhancers.ts +1 -1
  91. package/src/runner/ComfyExecution.ts +4 -1
  92. package/src/runner/ComfyWsApi.ts +82 -15
  93. package/src/sdk-generator/ComfySchema.ts +10 -1
  94. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +4 -1
  95. package/src/sdk-generator/comfyui-sdk-codegen.ts +61 -20
  96. package/src/sdk-generator/inputWidgetKind.ts +19 -4
  97. package/src/sdk-generator/litegraphToApiRequestPayload.ts +141 -33
  98. package/dist/ServeApp-BSA5yzxZ.js.map +0 -1
  99. package/dist/run-serve-CbKxIu6i.js.map +0 -1
  100. package/dist/state-C2oDiQ26.js.map +0 -1
@@ -0,0 +1,96 @@
1
+ // stable-audio3 t2a on Comfy Cloud — Stable Audio 3 Medium text to audio: music, instruments, sound effects or one-shots; distilled or base model
2
+ // source template: audio_stable_audio_3_medium.json (official workflow-templates), the base choice follows audio_stable_audio_3_medium_base.json
3
+ // needs COMFY_CLOUD_API_KEY (https://cloud.comfy.org, paid tiers)
4
+ // note: audio outputs PERSIST on the host (upstream ships no websocket saver for audio — image examples stream ephemerally)
5
+ // run directly: bun examples/comfy-cloud/stable-audio3-t2a.cflow.ts ["prompt"] [seed]
6
+ import { v } from 'comfy-ts'
7
+ // the template's four per-category system prompts, verbatim, shared with rvion 12 (the same model on the local box)
8
+ import { SA3_CATEGORIES, sa3Reprompt } from '../rvion/stableAudio3Prompts.ts'
9
+ import { cloudHost, requireCloudKey } from './cloudHost.ts'
10
+
11
+ const host = await cloudHost()
12
+
13
+ // each checkpoint with its own template's sampling: the distilled one runs 8 steps at cfg 1, the base one 50 at cfg 7
14
+ const MODELS = {
15
+ medium: { ckpt: 'stable_audio_3_medium.safetensors', steps: 8, cfg: 1 },
16
+ 'medium base': { ckpt: 'stable_audio_3_medium_base.safetensors', steps: 50, cfg: 7 },
17
+ } as const
18
+
19
+ export const stableAudio3T2a = host.defineWorkflow({
20
+ id: 'stable-audio3-t2a',
21
+ vars: {
22
+ // ONE prompt var: a plain description is enough when `reprompt` is on (`//` lines are comments)
23
+ prompt: v.prompt(
24
+ 'Tropical house track with marimba, steel drums, soft synths, smooth bass, layered percussion, and light piano riffs for sunny chill dance vibes',
25
+ ),
26
+ seed: v.seed(42),
27
+ model: v.choice(['medium', 'medium base'], 'medium', 'model'),
28
+ category: v.choice(SA3_CATEGORIES, 'Music', 'category'),
29
+ // on: a qwen3.5 2b first rewrites the description with the category's system prompt and the target length
30
+ reprompt: v.toggle(true, 'reprompt'),
31
+ seconds: v.float(150, { min: 1, max: 300 }),
32
+ },
33
+ build: (b, vars) => {
34
+ const m = MODELS[vars.model]
35
+ const ckpt = b.CheckpointLoaderSimple({ ckpt_name: m.ckpt })
36
+ const clip = b.CLIPLoader({ clip_name: 't5gemma_b_b_ul2.safetensors', type: 'stable_audio', device: 'default' })
37
+
38
+ const text = vars.reprompt
39
+ ? b.TextGenerate({
40
+ clip: b.CLIPLoader({
41
+ clip_name: 'qwen3.5_2b_bf16.safetensors',
42
+ type: 'stable_diffusion',
43
+ device: 'default',
44
+ }),
45
+ prompt: sa3Reprompt({
46
+ category: vars.category,
47
+ input: vars.prompt.positive,
48
+ seconds: Math.floor(vars.seconds),
49
+ }),
50
+ max_length: 256,
51
+ sampling_mode: 'on',
52
+ 'sampling_mode.temperature': 0.7,
53
+ 'sampling_mode.top_k': 64,
54
+ 'sampling_mode.top_p': 0.95,
55
+ 'sampling_mode.min_p': 0.05,
56
+ 'sampling_mode.repetition_penalty': 1.05,
57
+ 'sampling_mode.seed': 0,
58
+ thinking: false,
59
+ use_default_template: true,
60
+ mtp: 'auto',
61
+ }).outputs.generated_text
62
+ : vars.prompt.positive
63
+
64
+ // lcm sampling against an empty negative
65
+ const samples = b.KSampler({
66
+ model: ckpt.outputs.MODEL,
67
+ positive: b.CLIPTextEncode({ clip, text }),
68
+ negative: b.CLIPTextEncode({ clip, text: '' }),
69
+ latent_image: b.EmptyLatentAudio({ seconds: vars.seconds, batch_size: 1 }),
70
+ seed: vars.seed,
71
+ steps: m.steps,
72
+ cfg: m.cfg,
73
+ sampler_name: 'lcm',
74
+ scheduler: 'simple',
75
+ denoise: 1,
76
+ })
77
+ b.SaveAudioAdvanced({
78
+ audio: b.VAEDecodeAudio({ samples, vae: ckpt.outputs.VAE }),
79
+ filename_prefix: 'comfy-ts-zoo/stable-audio3-t2a',
80
+ format: 'mp3',
81
+ 'format.quality': 'V0',
82
+ })
83
+ },
84
+ })
85
+
86
+ export default stableAudio3T2a
87
+
88
+ // standalone run (skipped when another driver — e.g. the TUI — imports this module)
89
+ if (import.meta.main) {
90
+ requireCloudKey()
91
+ if (process.argv[2]) stableAudio3T2a.vars.prompt.set(process.argv[2])
92
+ if (process.argv[3]) stableAudio3T2a.vars.seed.set(Number(process.argv[3]))
93
+ const execution = await stableAudio3T2a.run({ log: true, save: { prefix: 'comfy-ts-zoo/stable-audio3-t2a' } })
94
+ for (const audio of execution.audios) console.log(`🟢 ${audio.absPath}`)
95
+ host.disconnect()
96
+ }
@@ -0,0 +1,54 @@
1
+ // z-image t2i base on Comfy Cloud — Z-Image base bf16, the undistilled model: 25 steps with real cfg and a negative prompt
2
+ // source template: image_z_image.json (official workflow-templates)
3
+ // needs COMFY_CLOUD_API_KEY (https://cloud.comfy.org, paid tiers)
4
+ // run directly: bun examples/comfy-cloud/z-image-t2i-base.cflow.ts ["prompt"] [seed]
5
+ import { v } from 'comfy-ts'
6
+ import { cloudHost, requireCloudKey } from './cloudHost.ts'
7
+
8
+ const host = await cloudHost()
9
+
10
+ export const zImageT2iBase = host.defineWorkflow({
11
+ id: 'z-image-t2i-base',
12
+ vars: {
13
+ // ONE prompt var: `- ` lines are the NEGATIVE prompt, `//` lines are comments
14
+ prompt: v.prompt(
15
+ 'A fashion photograph full of surreal romanticism, low-angle shot against a clear light blue sky. The vegetation is rendered in shades of blue, from ice blue to deep cobalt, with delicate realistic leaves; warm brown trunks contrast with the cool foliage like a dreamy forest from another world. A model in a yellow and white vertically striped long dress walks slowly on the sand, the noon sun casting clear shadows. Clean, transparent colors, quiet and poetic high-fashion mood.',
16
+ ),
17
+ seed: v.seed(42),
18
+ steps: v.int(25, { min: 1, max: 80 }),
19
+ cfg: v.float(4, { min: 1, max: 10 }),
20
+ size: v.size({ width: 1024, height: 1024 }),
21
+ },
22
+ build: (b, vars) => {
23
+ const model = b.ModelSamplingAuraFlow({
24
+ model: b.UNETLoader({ unet_name: 'z_image_bf16.safetensors', weight_dtype: 'default' }),
25
+ shift: 3,
26
+ })
27
+ const clip = b.CLIPLoader({ clip_name: 'qwen_3_4b.safetensors', type: 'lumina2', device: 'default' })
28
+ const samples = b.KSampler({
29
+ model,
30
+ positive: b.CLIPTextEncode({ clip, text: vars.prompt.positive }),
31
+ negative: b.CLIPTextEncode({ clip, text: vars.prompt.negative }),
32
+ latent_image: b.EmptySD3LatentImage({ width: vars.size.width, height: vars.size.height, batch_size: 1 }),
33
+ seed: vars.seed,
34
+ steps: vars.steps,
35
+ cfg: vars.cfg,
36
+ sampler_name: 'res_multistep',
37
+ scheduler: 'simple',
38
+ denoise: 1,
39
+ })
40
+ b.SaveImageWebsocket({ images: b.VAEDecode({ samples, vae: b.VAELoader({ vae_name: 'ae.safetensors' }) }) })
41
+ },
42
+ })
43
+
44
+ export default zImageT2iBase
45
+
46
+ // standalone run (skipped when another driver — e.g. the TUI — imports this module)
47
+ if (import.meta.main) {
48
+ requireCloudKey()
49
+ if (process.argv[2]) zImageT2iBase.vars.prompt.set(process.argv[2])
50
+ if (process.argv[3]) zImageT2iBase.vars.seed.set(Number(process.argv[3]))
51
+ const execution = await zImageT2iBase.run({ log: true, save: { prefix: 'comfy-ts-zoo/z-image-t2i-base' } })
52
+ for (const img of execution.images) console.log(`🟢 ${img.absPath}`)
53
+ host.disconnect()
54
+ }
@@ -1,5 +1,5 @@
1
1
  // krea2 turbo text-to-image, ported from a real production pipeline
2
- // (rabbits-vs-sheeps "unified"). krea2 turbo UNET + standard LoraLoader chain
2
+ // (a game's "unified" sprite flow). krea2 turbo UNET + standard LoraLoader chain
3
3
  // → KSampler(8 steps, cfg 1) → RMBG cutout → transparent png game sprite.
4
4
  //
5
5
  // run directly: bun examples/rvion/04-krea2-turbo-t2i.cflow.ts ["prompt"] [seed]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "comfy-ts",
3
- "version": "2.17.0",
3
+ "version": "2.18.0",
4
4
  "description": "The complete TypeScript toolkit for ComfyUI and generative AI. Fully type-safe SDK with autocomplete on every node, companion CLI, TUI, agentic docs, and 50+ examples. Design, run and deploy creative pipelines for image, video, audio, 3d and text on any ComfyUI, local, cloud or hosted.",
5
5
  "keywords": [
6
6
  "comfyui",
@@ -140,7 +140,7 @@
140
140
  "oxfmt": "^0.60.0",
141
141
  "oxlint": "^1.75.0",
142
142
  "oxlint-tsgolint": "^7.0.2001",
143
- "rvlib-shipkit": "^1.7.0",
143
+ "rvlib-shipkit": "^2.25.0",
144
144
  "rvlib-ts-tools": "^0.3.3",
145
145
  "tsdown": "^0.22.14",
146
146
  "typescript": "^7.0.2"
@@ -0,0 +1,49 @@
1
+ // `tui`, `serve` and `run` import .cflow.ts modules, which need bun: the bin's
2
+ // node shebang re-execs the same command line through it. The wrapper is the pid
3
+ // a terminal, a supervisor or an agent holds and stops, so the child must never
4
+ // outlive it (agent/architecture.md item 10)
5
+ import { spawn } from 'node:child_process'
6
+ import { constants } from 'node:os'
7
+
8
+ const HOP_PARENT_ENV = 'COMFY_TS_HOP_PARENT'
9
+ const FORWARDED: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGHUP']
10
+
11
+ /** runs `bun <argv>` with the terminal inherited, forwarding the stop signals;
12
+ * resolves the child's exit code, or `error` when bun cannot start */
13
+ export function hopToBun(argv: string[]): Promise<{ code: number } | { error: Error }> {
14
+ return new Promise((resolve) => {
15
+ const child = spawn('bun', argv, {
16
+ stdio: 'inherit',
17
+ env: { ...process.env, [HOP_PARENT_ENV]: String(process.pid) },
18
+ })
19
+ const forward = (signal: NodeJS.Signals): void => {
20
+ child.kill(signal)
21
+ }
22
+ for (const signal of FORWARDED) process.on(signal, forward)
23
+ const done = (r: { code: number } | { error: Error }): void => {
24
+ for (const signal of FORWARDED) process.off(signal, forward)
25
+ resolve(r)
26
+ }
27
+ child.once('error', (error) => done({ error }))
28
+ child.once('exit', (code, signal) => {
29
+ if (code != null) return done({ code })
30
+ done({ code: signal == null ? 1 : 128 + (constants.signals[signal] ?? 0) })
31
+ })
32
+ })
33
+ }
34
+
35
+ /** in the bun child: exit once the process that started it is gone. A SIGKILL to
36
+ * the wrapper reaches no handler, so the child polls its own ppid, which changes
37
+ * (to 1, or a subreaper) when its parent dies. It watches the ppid it started
38
+ * with, not the wrapper pid: a version manager shim may sit between the two */
39
+ export function armHopChild(p: { intervalMs?: number } = {}): void {
40
+ if (process.env[HOP_PARENT_ENV] == null) return
41
+ // a grandchild has another parent: it must never inherit the watch
42
+ Reflect.deleteProperty(process.env, HOP_PARENT_ENV)
43
+ const parent = process.ppid
44
+ setInterval(() => {
45
+ if (process.ppid === parent) return
46
+ console.error(`[comfy-ts] the process that started this one (pid ${parent}) is gone: exiting`)
47
+ process.exit(1)
48
+ }, p.intervalMs ?? 1000).unref()
49
+ }
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  // sidekick CLI: `bunx comfy-ts <command>` — codegen without writing any code
3
- import { spawnSync } from 'node:child_process'
3
+ import { armHopChild, hopToBun } from 'src/cli/bunHop.ts'
4
4
  import { fileURLToPath } from 'node:url'
5
5
  import { runGen } from 'src/cli/gen.ts'
6
6
  import { runLoras } from 'src/cli/loras.ts'
@@ -62,13 +62,13 @@ async function main(): Promise<number> {
62
62
  // node shebang means `bunx comfy-ts tui|serve` lands here under NODE. Hop
63
63
  // to bun when we are not already in it; without bun, degrade loudly.
64
64
  if (process.versions.bun == null) {
65
- const self = fileURLToPath(import.meta.url)
66
- const res = spawnSync('bun', [self, cmd, ...rest], { stdio: 'inherit' })
67
- if (res.error == null) return res.status ?? 1
65
+ const res = await hopToBun([fileURLToPath(import.meta.url), cmd, ...rest])
66
+ if ('code' in res) return res.code
68
67
  console.error(
69
68
  `[comfy-ts ${cmd}] bun not found (${res.error.message}) — continuing under node: the examples packaged in node_modules cannot load here, and your own .cflow.ts modules rely on node's type stripping`,
70
69
  )
71
70
  }
71
+ armHopChild()
72
72
  if (cmd === 'run') {
73
73
  const { runRun } = await import('src/cli/run/run-run.ts')
74
74
  return runRun(rest)
@@ -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
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,
@@ -159,9 +160,13 @@ const TabMenu = observer(function TabMenu(p: { st: WebSt; tab: DraftTab; anchor:
159
160
  type="button"
160
161
  className="menu-row menu-action danger"
161
162
  onClick={() =>
162
- run(() => {
163
- if (window.confirm(`delete draft '${p.tab.draft}' of ${p.tab.module}? the file is removed.`))
164
- 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)
165
170
  })
166
171
  }
167
172
  >
@@ -1,6 +1,7 @@
1
1
  // ✨ on a prompt row → the refine modal: the LLM configs and the master prompts as two lists of
2
2
  // vertical tabs on the left, the job (yours → rewrite) alone on the right. A tab's pen opens its
3
3
  // editor over the job. Nothing touches the var until APPLY.
4
+ import { dialogs } from 'src/cli/serve/web/state/dialog.ts'
4
5
  import { Icon } from 'src/cli/serve/web/components/Icon.tsx'
5
6
  import { observer } from 'mobx-react-lite'
6
7
  import { useEffect, useRef, type ReactNode } from 'react'
@@ -51,8 +52,8 @@ const TabList = observer(function TabList(p: {
51
52
  onSelect(name: string): void
52
53
  onCreate(name: string): void
53
54
  }) {
54
- const create = (): void => {
55
- const name = window.prompt(`name the new ${p.kind}`, p.newName)
55
+ const create = async (): Promise<void> => {
56
+ const name = await dialogs.prompt({ message: `name the new ${p.kind}`, value: p.newName })
56
57
  if (name != null) p.onCreate(name)
57
58
  }
58
59
  const dot = (name: string): ReactNode => {
@@ -96,7 +97,7 @@ const TabList = observer(function TabList(p: {
96
97
  ) : null}
97
98
  </div>
98
99
  ))}
99
- <button type="button" className="enh-tab-new" onClick={create}>
100
+ <button type="button" className="enh-tab-new" onClick={() => void create()}>
100
101
  <Icon name="plus" /> new {p.kind}
101
102
  </button>
102
103
  </div>
@@ -184,14 +185,19 @@ function EditPanel(p: {
184
185
  onClose(): void
185
186
  children: ReactNode
186
187
  }): ReactNode {
187
- const rename = (): void => {
188
+ const rename = async (): Promise<void> => {
188
189
  if (p.name == null) return
189
- const name = window.prompt(`rename this ${p.kind} (renames the file)`, p.name)
190
+ const name = await dialogs.prompt({ message: `rename this ${p.kind} (renames the file)`, value: p.name })
190
191
  if (name != null) p.onRename(name)
191
192
  }
192
- const remove = (): void => {
193
+ const remove = async (): Promise<void> => {
193
194
  if (p.name == null) return
194
- if (window.confirm(`delete ${p.kind} '${p.name}'? its file is removed.`)) p.onDelete()
195
+ const ok = await dialogs.confirm({
196
+ message: `delete ${p.kind} '${p.name}'? its file is removed.`,
197
+ ok: 'delete',
198
+ danger: true,
199
+ })
200
+ if (ok) p.onDelete()
195
201
  }
196
202
  return (
197
203
  <section className="enh-edit">
@@ -204,10 +210,10 @@ function EditPanel(p: {
204
210
  <button type="button" onClick={() => p.onDuplicate()}>
205
211
  duplicate
206
212
  </button>
207
- <button type="button" onClick={rename}>
213
+ <button type="button" onClick={() => void rename()}>
208
214
  rename
209
215
  </button>
210
- <button type="button" className="quiet-danger" onClick={remove}>
216
+ <button type="button" className="quiet-danger" onClick={() => void remove()}>
211
217
  <Icon name="trash" /> delete
212
218
  </button>
213
219
  </span>
@@ -1,5 +1,6 @@
1
1
  // the menu column: where you are, widest scope first (workspace, workflow, draft, host, preview).
2
2
  // a left Panel above 760px (collapsible to an icon rail), a drawer behind ☰ below
3
+ import { dialogs } from 'src/cli/serve/web/state/dialog.ts'
3
4
  import { observer, useLocalObservable } from 'mobx-react-lite'
4
5
  import type { ReactNode } from 'react'
5
6
  import { Icon, type IconName } from 'src/cli/serve/web/components/Icon.tsx'
@@ -96,11 +97,14 @@ const DraftSection = observer(function DraftSection(p: { st: WebSt; form: FormSt
96
97
  type="button"
97
98
  className="head-icon danger"
98
99
  data-tip="delete this draft's file (default resets to the workflow's own values)"
99
- onClick={() => {
100
- if (
101
- window.confirm(`delete draft '${p.form.draft}' of ${p.form.moduleKey}? the file is removed.`)
102
- )
103
- void p.st.deleteDraft({ module: p.form.moduleKey, draft: p.form.draft })
100
+ onClick={async () => {
101
+ const target = { module: p.form.moduleKey, draft: p.form.draft }
102
+ const ok = await dialogs.confirm({
103
+ message: `delete draft '${target.draft}' of ${target.module}? the file is removed.`,
104
+ ok: 'delete',
105
+ danger: true,
106
+ })
107
+ if (ok) void p.st.deleteDraft(target)
104
108
  }}
105
109
  >
106
110
  <Icon name="trash" />
@@ -277,9 +281,13 @@ export const MenuCards = observer(function MenuCards(p: { st: WebSt }) {
277
281
  type="button"
278
282
  className="head-icon danger"
279
283
  data-tip="restart ComfyUI on that host (manager reboot) — it reconnects when back"
280
- onClick={() => {
281
- if (window.confirm(`restart ComfyUI on '${p.st.hostFor(form.moduleKey)}'?`))
282
- void p.st.hostAction('restart')
284
+ onClick={async () => {
285
+ const ok = await dialogs.confirm({
286
+ message: `restart ComfyUI on '${p.st.hostFor(form.moduleKey)}'?`,
287
+ ok: 'restart',
288
+ danger: true,
289
+ })
290
+ if (ok) void p.st.hostAction('restart')
283
291
  }}
284
292
  >
285
293
  <Icon name="power" />
@@ -1,5 +1,6 @@
1
1
  // ROOT state tree of the serve web ui (app-state-tree doctrine: one root,
2
2
  // child stores hang off it, components read and call)
3
+ import { dialogs } from 'src/cli/serve/web/state/dialog.ts'
3
4
  import { makeAutoObservable, observableRef, observableShallow, runInAction } from 'mobx'
4
5
  import {
5
6
  deleteDraft,
@@ -1398,7 +1399,15 @@ export class WebSt {
1398
1399
  const name = rawName.trim()
1399
1400
  if (form == null || name === '') return
1400
1401
  const existing = this.moduleByKey(form.moduleKey)?.drafts.includes(name) === true
1401
- if (existing && !window.confirm(`draft '${name}' already exists — overwrite it?`)) return
1402
+ if (
1403
+ existing &&
1404
+ !(await dialogs.confirm({
1405
+ message: `draft '${name}' already exists: overwrite it?`,
1406
+ ok: 'overwrite',
1407
+ danger: true,
1408
+ }))
1409
+ )
1410
+ return
1402
1411
  try {
1403
1412
  const reply = await saveDraft({ module: form.moduleKey, draft: name, values })
1404
1413
  runInAction(() => {
@@ -0,0 +1,59 @@
1
+ // the panel's own confirm and text prompt, drawn in the page (DialogLayer). Never window.prompt /
2
+ // confirm / alert: sk gui's WKWebView implements no js panel, so there they return null / false
3
+ // at once and the button that asked does nothing; browsers also suppress them after a few.
4
+ // tests/serve-web-dialog.test.ts guards that no panel source calls the native ones
5
+ import { makeAutoObservable } from 'mobx'
6
+
7
+ export type DialogRequest =
8
+ | { kind: 'confirm'; message: string; ok: string; danger: boolean; resolve(ok: boolean): void }
9
+ | { kind: 'prompt'; message: string; value: string; resolve(value: string | null): void }
10
+
11
+ export class DialogSt {
12
+ current: DialogRequest | null = null
13
+
14
+ constructor() {
15
+ makeAutoObservable(this)
16
+ }
17
+
18
+ confirm(p: { message: string; ok?: string; danger?: boolean }): Promise<boolean> {
19
+ this.cancel()
20
+ return new Promise((resolve) => {
21
+ this.current = { kind: 'confirm', message: p.message, ok: p.ok ?? 'ok', danger: p.danger ?? false, resolve }
22
+ })
23
+ }
24
+
25
+ /** the typed text on ok, null on cancel */
26
+ prompt(p: { message: string; value: string }): Promise<string | null> {
27
+ this.cancel()
28
+ return new Promise((resolve) => {
29
+ this.current = { kind: 'prompt', message: p.message, value: p.value, resolve }
30
+ })
31
+ }
32
+
33
+ setValue(value: string): void {
34
+ if (this.current?.kind === 'prompt') this.current = { ...this.current, value }
35
+ }
36
+
37
+ accept(): void {
38
+ const c = this.current
39
+ if (c == null) return
40
+ this.current = null
41
+ if (c.kind === 'confirm') c.resolve(true)
42
+ else c.resolve(c.value)
43
+ }
44
+
45
+ cancel(): void {
46
+ const c = this.current
47
+ if (c == null) return
48
+ this.current = null
49
+ if (c.kind === 'confirm') c.resolve(false)
50
+ else c.resolve(null)
51
+ }
52
+ }
53
+
54
+ export const dialogs = new DialogSt()
55
+
56
+ /** the lines of a source that call a native browser dialog */
57
+ export function nativeDialogCalls(source: string): string[] {
58
+ return source.split('\n').filter((line) => /\b(window|globalThis)\.(prompt|confirm|alert)\s*\(/.test(line))
59
+ }
@@ -36,7 +36,7 @@ export function finishRewrite(model: string, kept: readonly string[]): string {
36
36
  const items = negativeItems(kept)
37
37
  const body = model
38
38
  .split('\n')
39
- .filter((l) => kept.length === 0 || !isKept(l))
39
+ .filter((l) => !isKept(l))
40
40
  .map((l) => {
41
41
  if (items.size === 0) return l
42
42
  let at = l.indexOf(' - ')
@@ -882,6 +882,14 @@ button.enh-big { font-size: 14px; padding: 8px 18px; }
882
882
  .modal-overlay.hist-overlay { z-index: 60; }
883
883
  .modal.hist-modal { width: min(1100px, 100%); height: min(76vh, 100%); max-height: none; }
884
884
  .hist-modal .modal-head { align-items: center; }
885
+ /* the panel's confirm and text prompt (DialogLayer): above every modal, the enhancer included */
886
+ .modal-overlay.dialog-overlay { z-index: 70; }
887
+ .modal.dialog-modal { width: min(420px, 100%); }
888
+ .dialog-body { display: flex; flex-direction: column; gap: 10px; }
889
+ .dialog-message { white-space: pre-line; }
890
+ .dialog-body input { width: 100%; }
891
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; padding: 0 10px 10px; }
892
+ .dialog-actions button.dialog-danger { color: var(--red); border-color: var(--red); }
885
893
  .hist-cols { flex: 1; min-height: 0; display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 3fr); }
886
894
  .hist-list { min-height: 0; overflow-y: auto; border-right: 1px solid var(--border); padding: 6px; display: flex; flex-direction: column; gap: 2px; }
887
895
  .hist-row {