comfy-ts 2.1.0 → 2.2.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 (41) hide show
  1. package/README.md +65 -225
  2. package/dist/{DefinedWorkflow-CqNE_kgR.js → DefinedWorkflow-CwHInZgn.js} +4 -3
  3. package/dist/DefinedWorkflow-CwHInZgn.js.map +1 -0
  4. package/dist/{DraftsSt-C-gBk9v7.js → DraftsSt-omWuBSej.js} +2 -2
  5. package/dist/{DraftsSt-C-gBk9v7.js.map → DraftsSt-omWuBSej.js.map} +1 -1
  6. package/dist/cli.js +3 -3
  7. package/dist/index.cjs +22 -5
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +12 -2
  10. package/dist/index.d.ts +12 -2
  11. package/dist/index.js +22 -5
  12. package/dist/index.js.map +1 -1
  13. package/dist/{run-serve-CnlN_RFH.js → run-serve-C1oo5ilG.js} +170 -126
  14. package/dist/run-serve-C1oo5ilG.js.map +1 -0
  15. package/dist/{run-tui-DXI_Jufu.js → run-tui-CuVst-nc.js} +49 -50
  16. package/dist/run-tui-CuVst-nc.js.map +1 -0
  17. package/dist/{state-DC5BcG6d.js → state-CvMt0W1-.js} +23 -7
  18. package/dist/state-CvMt0W1-.js.map +1 -0
  19. package/dist/web.d.ts +12 -2
  20. package/dist/web.js +22 -5
  21. package/dist/web.js.map +1 -1
  22. package/examples/README.md +6 -18
  23. package/examples/images/README.md +2 -6
  24. package/guide-for-agents.md +25 -84
  25. package/package.json +1 -1
  26. package/src/cli/serve/ServeApp.ts +17 -11
  27. package/src/cli/serve/applyVarPayload.ts +91 -71
  28. package/src/cli/serve/describeVar.ts +57 -28
  29. package/src/cli/tui/components/StatusBar.tsx +1 -0
  30. package/src/cli/tui/components/TextOverlay.tsx +7 -3
  31. package/src/cli/tui/components/VarsPanel.tsx +2 -2
  32. package/src/cli/tui/state/ExecSt.ts +47 -52
  33. package/src/cli/tui/state/TuiSt.ts +11 -6
  34. package/src/host/ComfyHost.ts +5 -1
  35. package/src/runner/ComfyExecution.ts +15 -7
  36. package/src/runner/outputPath.ts +11 -0
  37. package/src/vars/ComfyVars.ts +12 -2
  38. package/dist/DefinedWorkflow-CqNE_kgR.js.map +0 -1
  39. package/dist/run-serve-CnlN_RFH.js.map +0 -1
  40. package/dist/run-tui-DXI_Jufu.js.map +0 -1
  41. package/dist/state-DC5BcG6d.js.map +0 -1
@@ -1,29 +1,17 @@
1
1
  # comfy-ts examples
2
2
 
3
- Every `*.cflow.ts` file here is a runnable workflow module: run it directly
4
- with bun, or browse them all in the TUI (`bunx comfy-ts tui` lists them under
5
- "comfy-ts examples", tweak vars, ⌃R to run).
3
+ Every `*.cflow.ts` file here is a runnable workflow module: run it directly with bun, or browse them all in the TUI (`bunx comfy-ts tui` lists them under "comfy-ts examples", tweak vars, ⌃R to run).
6
4
 
7
5
  ## Layout
8
6
 
9
- - `rvion/01…04-*.cflow.ts` — the didactic sequence against a LOCAL ComfyUI
10
- host (edit the `comfy.host({...})` line to point at yours, then first run
11
- generates a typed SDK for it).
12
- - `rvion/05-comfy-cloud.cflow.ts` — the same t2i against [Comfy Cloud]
13
- (https://cloud.comfy.org): no local GPU needed, the typed catalog ships
14
- committed at `comfy-cloud/sdk.d.ts`.
15
- - `rvion/06-qwen-image-edit.cflow.ts` — image editing (qwen image edit 2511)
16
- against the same local host.
17
- - `comfy-cloud/<family>-<mode>.cflow.ts` — the model zoo: one clean example
18
- per model family × mode (`t2i`, `i2i`, `t2v`, `i2v`, `t2a`), each mirroring
19
- an official ComfyUI template (flux, qwen-image, z-image, wan, hidream,
20
- ace-step, …). All share `comfy-cloud/cloudHost.ts`.
7
+ - `rvion/01…04-*.cflow.ts` — the didactic sequence against a LOCAL ComfyUI host (edit the `comfy.host({...})` line to point at yours, then first run generates a typed SDK for it).
8
+ - `rvion/05-comfy-cloud.cflow.ts` — the same t2i against [Comfy Cloud] (https://cloud.comfy.org): no local GPU needed, the typed catalog ships committed at `comfy-cloud/sdk.d.ts`.
9
+ - `rvion/06-qwen-image-edit.cflow.ts` — image editing (qwen image edit 2511) against the same local host.
10
+ - `comfy-cloud/<family>-<mode>.cflow.ts` — the model zoo: one clean example per model family × mode (`t2i`, `i2i`, `t2v`, `i2v`, `t2a`), each mirroring an official ComfyUI template (flux, qwen-image, z-image, wan, hidream, ace-step, …). All share `comfy-cloud/cloudHost.ts`.
21
11
 
22
12
  ## Cloud API key
23
13
 
24
- Cloud examples read `COMFY_CLOUD_API_KEY` (create one at cloud.comfy.org,
25
- paid tiers). Without it everything still loads and typechecks — only `run()`
26
- needs the key:
14
+ Cloud examples read `COMFY_CLOUD_API_KEY` (create one at cloud.comfy.org, paid tiers). Without it everything still loads and typechecks — only `run()` needs the key:
27
15
 
28
16
  ```sh
29
17
  COMFY_CLOUD_API_KEY=… bun examples/rvion/05-comfy-cloud.cflow.ts "a fox in the snow" 42
@@ -1,12 +1,8 @@
1
1
  # Bundled example input images
2
2
 
3
- Default inputs for the i2i/i2v examples — they ship in the npm tarball so
4
- every example runs out of the box. The exact pixel size is in each filename.
3
+ Default inputs for the i2i/i2v examples — they ship in the npm tarball so every example runs out of the box. The exact pixel size is in each filename.
5
4
 
6
- Source: [picsum.photos](https://picsum.photos), which serves Unsplash-sourced
7
- photos, free to use. Fetched and re-encoded (jpeg q80, metadata stripped) by
8
- `scripts/fetch-example-images.ts` — the manifest in that script is the source
9
- of truth; regeneration is deliberate (`bun run examples:images`).
5
+ Source: [picsum.photos](https://picsum.photos), which serves Unsplash-sourced photos, free to use. Fetched and re-encoded (jpeg q80, metadata stripped) by `scripts/fetch-example-images.ts` — the manifest in that script is the source of truth; regeneration is deliberate (`bun run examples:images`).
10
6
 
11
7
  | file | size | picsum id | author |
12
8
  | --------------------- | --------- | ------------------------------------------ | ------------------------------------------------------------ |
@@ -1,11 +1,6 @@
1
1
  # comfy-ts, guide for coding agents
2
2
 
3
- You are working in a project that uses `comfy-ts`, a type-safe ComfyUI
4
- companion for TypeScript. It connects to one or more ComfyUI hosts, generates
5
- one typed SDK per host (global `Comfy.<HostNs>.*` namespaces), builds
6
- workflows in code with full autocomplete, executes them over websocket, and
7
- downloads the output images. Include this file from the project's CLAUDE.md:
8
- `@./node_modules/comfy-ts/guide-for-agents.md`.
3
+ You are working in a project that uses `comfy-ts`, a type-safe ComfyUI companion for TypeScript. It connects to one or more ComfyUI hosts, generates one typed SDK per host (global `Comfy.<HostNs>.*` namespaces), builds workflows in code with full autocomplete, executes them over websocket, and downloads the output images. Include this file from the project's CLAUDE.md: `@./node_modules/comfy-ts/guide-for-agents.md`.
9
4
 
10
5
  ## Setup flow
11
6
 
@@ -17,26 +12,20 @@ downloads the output images. Include this file from the project's CLAUDE.md:
17
12
  # writes .comfy-ts/hosts/my-gpu/{object_info.json,embeddings.json,sdk.d.ts}
18
13
  ```
19
14
 
20
- Or skip the CLI: a first `await host.connect()` fetches the schema and
21
- writes the same files.
15
+ Or skip the CLI: a first `await host.connect()` fetches the schema and writes the same files.
22
16
  3. Activate the generated types in tsconfig:
23
17
 
24
18
  ```jsonc
25
19
  { "include": ["src", ".comfy-ts/hosts/**/sdk.d.ts"] }
26
20
  ```
27
21
 
28
- 4. Gitignore `.comfy-ts/` entirely. It is local state: host schema dumps
29
- (often ~10MB, they describe that machine's models and paths), run outputs,
30
- TUI drafts and settings, lora keywords, preview cache. Everything in it is
31
- regenerable. (Exception: a private repo may commit `hosts/` to get typed CI.)
22
+ 4. Gitignore `.comfy-ts/` entirely. It is local state: host schema dumps (often ~10MB, they describe that machine's models and paths), run outputs, TUI drafts and settings, lora keywords, preview cache. Everything in it is regenerable. (Exception: a private repo may commit `hosts/` to get typed CI.)
32
23
 
33
- Before the first codegen the builder falls back to permissive base types, so
34
- code compiles either way. Types sharpen once a generated sdk.d.ts is in scope.
24
+ Before the first codegen the builder falls back to permissive base types, so code compiles either way. Types sharpen once a generated sdk.d.ts is in scope.
35
25
 
36
26
  ## The workflow pattern: defineWorkflow + vars + build
37
27
 
38
- A workflow module is a `*.cflow.ts` file (that suffix is what the TUI scans
39
- for). Minimal complete example:
28
+ A workflow module is a `*.cflow.ts` file (that suffix is what the TUI scans for). Minimal complete example:
40
29
 
41
30
  ```ts
42
31
  import { ComfyTS, v } from 'comfy-ts'
@@ -82,38 +71,21 @@ if (import.meta.main) {
82
71
  }
83
72
  ```
84
73
 
85
- Var kinds: `v.text`, `v.int`, `v.float`, `v.seed`, `v.toggle`, `v.choice`,
86
- `v.size`, `v.loras`, `v.prompt`, `v.image`. Notes:
87
-
88
- - `v.loras(/regex/)` resolves against the host's real lora list;
89
- `activeLoras(vars.loras)` returns `{ lora_name, strength_model, strength_clip }[]`
90
- for a standard `LoraLoader` chain.
91
- - `v.prompt` is structured: `//` lines are comments (stripped), `- ` lines go
92
- to the negative prompt, `{ loraKeywordsFrom: lorasVar }` prefixes lora
93
- trigger keywords. The value is `{ positive, negative }`.
94
- - `v.image` holds a local image path as a plain string; an empty value throws
95
- at build time instead of running a silent placeholder. Capture the var in a
96
- const and call `image.absPath()` in `build`. Default it to a bundled sample
97
- with `exampleImagePath('bear_1024x1024.jpg')` (ships in the package). In
98
- the TUI it opens an image picker (browse, favorite folders, recents,
99
- preview).
74
+ Var kinds: `v.text`, `v.int`, `v.float`, `v.seed`, `v.toggle`, `v.choice`, `v.size`, `v.loras`, `v.prompt`, `v.image`. Notes:
75
+
76
+ - `v.loras(/regex/)` resolves against the host's real lora list; `activeLoras(vars.loras)` returns `{ lora_name, strength_model, strength_clip }[]` for a standard `LoraLoader` chain.
77
+ - `v.prompt` is structured: `//` lines are comments (stripped), `- ` lines go to the negative prompt, `{ loraKeywordsFrom: lorasVar }` prefixes lora trigger keywords. The value is `{ positive, negative }`.
78
+ - `v.image` holds a local image path as a plain string; an empty value throws at build time instead of running a silent placeholder. Capture the var in a const and call `image.absPath()` in `build`. Default it to a bundled sample with `exampleImagePath('bear_1024x1024.jpg')` (ships in the package). In the TUI it opens an image picker (browse, favorite folders, recents, preview).
100
79
  - `vars` may be a lambda `(v) => ({ ... })` so vars can reference each other.
101
- - `build` may be async, for uploads: the third param `wf` feeds `MediaImage`
102
- helpers (`new MediaImage({ path }).loadInWorkflow_viaLoadImageNode(wf)`).
103
- Uploads are hash-named and deduped, nothing is re-sent.
80
+ - `build` may be async, for uploads: the third param `wf` feeds `MediaImage` helpers (`new MediaImage({ path }).loadInWorkflow_viaLoadImageNode(wf)`). Uploads are hash-named and deduped, nothing is re-sent.
104
81
 
105
82
  ## Running and getting images
106
83
 
107
- - `await workflow.run({ log: true })` connects (idempotent, one websocket per
108
- host), builds a fresh graph from current var values, executes, streams
109
- progress, and returns a `ComfyExecution`.
110
- - `execution.images` are downloaded `MediaImage`s: `img.absPath`,
111
- `img.width`, `img.height`.
112
- - Tweak then re-run: `workflow.vars.seed.randomize()` or
113
- `workflow.vars.prompt.set('...')`, then `run()` again.
84
+ - `await workflow.run({ log: true })` connects (idempotent, one websocket per host), builds a fresh graph from current var values, executes, streams progress, and returns a `ComfyExecution`.
85
+ - `execution.images` are downloaded `MediaImage`s: `img.absPath`, `img.width`, `img.height`.
86
+ - Tweak then re-run: `workflow.vars.seed.randomize()` or `workflow.vars.prompt.set('...')`, then `run()` again.
114
87
  - `run({ onProgress })` gives a progress callback instead of console logs.
115
- - Call `host.disconnect()` at the end of a standalone script or the process
116
- stays alive on the open websocket.
88
+ - Call `host.disconnect()` at the end of a standalone script or the process stays alive on the open websocket.
117
89
 
118
90
  ## CLI
119
91
 
@@ -123,50 +95,19 @@ bunx comfy-ts outline [file] [--section Name] [--lines N] # inspect a sdk.d.ts
123
95
  bunx comfy-ts tui [dir | module.cflow.ts] # interactive tweak & re-run
124
96
  ```
125
97
 
126
- The TUI scans `**/*.cflow.ts` (no arg: cwd PLUS the examples bundled with
127
- the package, grouped apart in the tree; an explicit dir or file limits to
128
- that scope), shows vars as editable knobs, runs with live progress and
129
- previews, and saves named drafts under `.comfy-ts/drafts/`. It re-execs
130
- through bun when launched under node (workflow modules are TypeScript, and
131
- node cannot import .ts from node_modules). Point users at it; as an agent
132
- you run modules with `bun path/to/module.cflow.ts`.
98
+ The TUI scans `**/*.cflow.ts` (no arg: cwd PLUS the examples bundled with the package, grouped apart in the tree; an explicit dir or file limits to that scope), shows vars as editable knobs, runs with live progress and previews, and saves named drafts under `.comfy-ts/drafts/`. It re-execs through bun when launched under node (workflow modules are TypeScript, and node cannot import .ts from node_modules). Point users at it; as an agent you run modules with `bun path/to/module.cflow.ts`.
133
99
 
134
100
  ## Import and export ComfyUI JSON
135
101
 
136
- - `host.importApiJson(json)` turns an `api.json` (prompt format) into a
137
- `ComfyWorkflow`.
138
- - `host.importWorkflowJson(json)` does the same for a saved `workflow.json`
139
- (litegraph format, handles muted nodes, Note/Reroute/PrimitiveNode).
140
- - `wf.toApiJson()` exports the prompt format;
141
- `await wf.toWorkflowJson()` exports an autolayouted `workflow.json` you can
142
- drag into the ComfyUI editor. Both work fully offline:
143
- `const wf = await workflow.build()` never needs a live server.
102
+ - `host.importApiJson(json)` turns an `api.json` (prompt format) into a `ComfyWorkflow`.
103
+ - `host.importWorkflowJson(json)` does the same for a saved `workflow.json` (litegraph format, handles muted nodes, Note/Reroute/PrimitiveNode).
104
+ - `wf.toApiJson()` exports the prompt format; `await wf.toWorkflowJson()` exports an autolayouted `workflow.json` you can drag into the ComfyUI editor. Both work fully offline: `const wf = await workflow.build()` never needs a live server.
144
105
 
145
106
  ## Gotchas
146
107
 
147
- - **Offline cache vs live connect.** `host.loadSchemaFromCache()` reads
148
- `.comfy-ts/hosts/<id>/` and never touches the network, so modules import
149
- instantly and offline. `run()` connects lazily. If the cache is missing,
150
- the import still works: you get the permissive base types plus a loud
151
- console message; run the `gen` command or `connect()` once to fix it.
152
- `connect()` reuses a cache
153
- younger than 24h; `connect({ schema: 'refresh' })` forces a re-fetch.
154
- - **Per-host namespaces.** Types come from `Comfy.<HostNs>` keyed by the host
155
- `id` you pass to `comfy.host({ id })` (`my-gpu` becomes `Comfy.MyGpu`). A
156
- new id has no generated sdk yet, so you silently get permissive base types:
157
- model names widen to `string` and typos stop being caught. Keep the id
158
- stable and regenerate after installing custom nodes on the host.
159
- - **Registries.** `ComfyTS.create()` returns the existing global instance,
160
- and `comfy.host({ id })` returns the already-registered host for that id.
161
- Modules can import each other safely in one process.
162
- - **Seeds.** `v.seed` carries a mode (`+` increment, `-` decrement, `=`
163
- fixed, `?` reroll) and advances itself after every run, so a batch of runs
164
- gets distinct seeds by default. When reproducibility matters, pin both the
165
- mode and the value: `vars.seed.setMode('=')` then `vars.seed.set(N)`.
166
- `set()` alone keeps the current mode, so a prior `?` would still reroll.
167
- - **`auto<T>()` slots.** From `import { auto } from 'comfy-ts'`: leave an
168
- input blank and comfy-ts wires the most recent node producing that type.
169
- Handy, but implicit; prefer explicit wiring in code meant to be read.
170
- - **Errors before the server.** Invalid graphs accumulate messages in
171
- `workflow.problems` before ComfyUI ever sees them. Check it when a run
172
- misbehaves.
108
+ - **Offline cache vs live connect.** `host.loadSchemaFromCache()` reads `.comfy-ts/hosts/<id>/` and never touches the network, so modules import instantly and offline. `run()` connects lazily. If the cache is missing, the import still works: you get the permissive base types plus a loud console message; run the `gen` command or `connect()` once to fix it. `connect()` reuses a cache younger than 24h; `connect({ schema: 'refresh' })` forces a re-fetch.
109
+ - **Per-host namespaces.** Types come from `Comfy.<HostNs>` keyed by the host `id` you pass to `comfy.host({ id })` (`my-gpu` becomes `Comfy.MyGpu`). A new id has no generated sdk yet, so you silently get permissive base types: model names widen to `string` and typos stop being caught. Keep the id stable and regenerate after installing custom nodes on the host.
110
+ - **Registries.** `ComfyTS.create()` returns the existing global instance, and `comfy.host({ id })` returns the already-registered host for that id. Modules can import each other safely in one process.
111
+ - **Seeds.** `v.seed` carries a mode (`+` increment, `-` decrement, `=` fixed, `?` reroll) and advances itself after every run, so a batch of runs gets distinct seeds by default. When reproducibility matters, pin both the mode and the value: `vars.seed.setMode('=')` then `vars.seed.set(N)`. `set()` alone keeps the current mode, so a prior `?` would still reroll.
112
+ - **`auto<T>()` slots.** From `import { auto } from 'comfy-ts'`: leave an input blank and comfy-ts wires the most recent node producing that type. Handy, but implicit; prefer explicit wiring in code meant to be read.
113
+ - **Errors before the server.** Invalid graphs accumulate messages in `workflow.problems` before ComfyUI ever sees them. Check it when a run misbehaves.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "comfy-ts",
3
- "version": "2.1.0",
3
+ "version": "2.2.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",
@@ -7,7 +7,7 @@ import { basename, dirname, extname, join, resolve } from 'pathe'
7
7
  import { applyVarPayload } from 'src/cli/serve/applyVarPayload.ts'
8
8
  import { describeVar, type VarDescriptor } from 'src/cli/serve/describeVar.ts'
9
9
  import { draftsDirForFile, listDraftsForFile } from 'src/cli/tui/state/DraftsSt.ts'
10
- import { ImageVar, ImageVarEmptyError, SeedVar } from 'src/vars/ComfyVars.ts'
10
+ import type { ImageVar, SeedVar } from 'src/vars/ComfyVars.ts'
11
11
  import type { DefinedWorkflow } from 'src/vars/DefinedWorkflow.ts'
12
12
  import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
13
13
 
@@ -314,7 +314,9 @@ export class ServeApp {
314
314
  if (varDef == null)
315
315
  return { status: 400, error: `unknown var '${k}' — vars: ${[...varMap.keys()].join(', ')}` }
316
316
  let value = rawValue
317
- if (varDef instanceof ImageVar && typeof rawValue === 'string' && /^https?:\/\//.test(rawValue)) {
317
+ // kind, never instanceof: consumer and cli hold different class copies (VarKind
318
+ // owns the WHY); casts are the kind-narrowing family, agent/coding.md whitelist 6
319
+ if (varDef.kind === 'image' && typeof rawValue === 'string' && /^https?:\/\//.test(rawValue)) {
318
320
  try {
319
321
  value = await this.downloadInput(rawValue)
320
322
  } catch (e) {
@@ -327,31 +329,35 @@ export class ServeApp {
327
329
 
328
330
  // 3. image vars must point at real files BEFORE anything is queued
329
331
  for (const [k, varDef] of varMap) {
330
- if (varDef instanceof ImageVar && varDef.isSet() && !existsSync(varDef.absPath()))
331
- return { status: 400, error: `image var '${k}': file not found: ${varDef.absPath()}` }
332
+ if (varDef.kind !== 'image') continue
333
+ const img = varDef as ImageVar
334
+ if (img.isSet() && !existsSync(img.absPath()))
335
+ return { status: 400, error: `image var '${k}': file not found: ${img.absPath()}` }
332
336
  }
333
337
 
334
338
  // 4. seed policy (architecture item 12): payload wins; '?' rerolls;
335
339
  // '+'/'-' continue from the last SERVED value; '=' keeps the draft value
336
340
  for (const [k, varDef] of varMap) {
337
- if (!(varDef instanceof SeedVar)) continue
341
+ if (varDef.kind !== 'seed') continue
342
+ const seedVar = varDef as SeedVar
338
343
  const stateKey = `${mod.key}/${draft}/${k}`
339
344
  if (!(k in payload)) {
340
- if (varDef.mode === '?') varDef.randomize()
341
- else if (varDef.mode === '+' || varDef.mode === '-') {
345
+ if (seedVar.mode === '?') seedVar.randomize()
346
+ else if (seedVar.mode === '+' || seedVar.mode === '-') {
342
347
  const last = this.seedState.get(stateKey)
343
- if (last != null) varDef.set(last + (varDef.mode === '+' ? 1 : -1))
348
+ if (last != null) seedVar.set(last + (seedVar.mode === '+' ? 1 : -1))
344
349
  }
345
350
  }
346
- this.seedState.set(stateKey, varDef.value)
347
- seeds[k] = varDef.value
351
+ this.seedState.set(stateKey, seedVar.value)
352
+ seeds[k] = seedVar.value
348
353
  }
349
354
 
350
355
  // 5. send (build + POST /prompt); the wait for outputs happens OUTSIDE the mutex
351
356
  try {
352
357
  return { execution: await this.starter(mod) }
353
358
  } catch (e) {
354
- if (e instanceof ImageVarEmptyError) return { status: 400, error: e.message }
359
+ // name, not instanceof: same two-copies problem as the var classes
360
+ if (e instanceof Error && e.name === 'ImageVarEmptyError') return { status: 400, error: e.message }
355
361
  return { status: 500, error: extractErrorMessage(e) }
356
362
  }
357
363
  }
@@ -1,13 +1,19 @@
1
1
  // PURE payload → var application: one POST body value onto one var, per kind.
2
2
  // Returns an error message (nothing applied) or null. No fs here — ImageVar
3
3
  // url download + existence checks are ServeApp's job.
4
- import {
5
- type AnyVar,
4
+ //
5
+ // Discrimination is by `kind`, NEVER instanceof: a consumer's `.cflow.ts` imports
6
+ // `comfy-ts` (dist/index.js) while `comfy-ts serve` runs from the cli bundle, and the
7
+ // two hold different copies of every class, so instanceof was false for EVERY var and
8
+ // every payload override answered "unsupported kind" (his repro 2026-07-31). The casts
9
+ // below are the sanctioned kind-narrowing family (agent/coding.md cast whitelist 6).
10
+ import type {
11
+ AnyVar,
6
12
  ChoiceVar,
7
13
  FloatVar,
8
14
  ImageVar,
9
15
  IntVar,
10
- type LoraStrength,
16
+ LoraStrength,
11
17
  LorasVar,
12
18
  PromptVar,
13
19
  SeedVar,
@@ -35,85 +41,99 @@ function listSome(items: readonly string[], cap: number = 20): string {
35
41
  export function applyVarPayload(varDef: AnyVar, raw: unknown): string | null {
36
42
  const name = varDef.name ?? varDef.label ?? varDef.kind
37
43
 
38
- if (varDef instanceof TextVar || varDef instanceof PromptVar) {
39
- if (typeof raw !== 'string') return `var '${name}' expects a string`
40
- varDef.set(raw)
41
- return null
42
- }
43
-
44
- if (varDef instanceof IntVar || varDef instanceof FloatVar) {
45
- if (isFiniteNumber(raw)) {
46
- varDef.set(raw) // set() clamps to min/max
44
+ switch (varDef.kind) {
45
+ case 'text':
46
+ case 'prompt': {
47
+ if (typeof raw !== 'string') return `var '${name}' expects a string`
48
+ ;(varDef as TextVar | PromptVar).set(raw)
47
49
  return null
48
50
  }
49
- if (typeof raw === 'string' && varDef.parse(raw)) return null
50
- const o = varDef.opts
51
- const range = o.min == null && o.max == null ? '' : ` (${o.min ?? '-∞'}..${o.max ?? '∞'})`
52
- return `var '${name}' expects a number${range}`
53
- }
54
51
 
55
- if (varDef instanceof SeedVar) {
56
- if (isFiniteNumber(raw)) {
57
- // an explicit payload seed is FIXED for this request
58
- varDef.setMode('=')
59
- varDef.set(raw)
60
- return null
52
+ case 'int':
53
+ case 'float': {
54
+ const v = varDef as IntVar | FloatVar
55
+ if (isFiniteNumber(raw)) {
56
+ v.set(raw) // set() clamps to min/max
57
+ return null
58
+ }
59
+ if (typeof raw === 'string' && v.parse(raw)) return null
60
+ const o = v.opts
61
+ const range = o.min == null && o.max == null ? '' : ` (${o.min ?? '-∞'}..${o.max ?? '∞'})`
62
+ return `var '${name}' expects a number${range}`
61
63
  }
62
- if (raw != null && typeof raw === 'object' && !Array.isArray(raw)) {
63
- const o = raw as { mode?: unknown; value?: unknown }
64
- const mode = o.mode === '=' || o.mode === '+' || o.mode === '-' || o.mode === '?' ? o.mode : null
65
- if (o.mode !== undefined && mode == null) return `var '${name}': mode must be one of = + - ?`
66
- if (o.value !== undefined && !isFiniteNumber(o.value)) return `var '${name}': value must be a number`
67
- if (mode == null && o.value === undefined) return `var '${name}': give "mode" and/or "value"`
68
- if (mode != null) varDef.setMode(mode)
69
- if (isFiniteNumber(o.value)) varDef.set(o.value)
70
- return null
64
+
65
+ case 'seed': {
66
+ const v = varDef as SeedVar
67
+ if (isFiniteNumber(raw)) {
68
+ // an explicit payload seed is FIXED for this request
69
+ v.setMode('=')
70
+ v.set(raw)
71
+ return null
72
+ }
73
+ if (raw != null && typeof raw === 'object' && !Array.isArray(raw)) {
74
+ const o = raw as { mode?: unknown; value?: unknown }
75
+ const mode = o.mode === '=' || o.mode === '+' || o.mode === '-' || o.mode === '?' ? o.mode : null
76
+ if (o.mode !== undefined && mode == null) return `var '${name}': mode must be one of = + - ?`
77
+ if (o.value !== undefined && !isFiniteNumber(o.value)) return `var '${name}': value must be a number`
78
+ if (mode == null && o.value === undefined) return `var '${name}': give "mode" and/or "value"`
79
+ if (mode != null) v.setMode(mode)
80
+ if (isFiniteNumber(o.value)) v.set(o.value)
81
+ return null
82
+ }
83
+ return `var '${name}' expects a number or {"mode":"=|+|-|?","value":number}`
71
84
  }
72
- return `var '${name}' expects a number or {"mode":"=|+|-|?","value":number}`
73
- }
74
85
 
75
- if (varDef instanceof ToggleVar) {
76
- if (typeof raw !== 'boolean') return `var '${name}' expects true or false`
77
- varDef.set(raw)
78
- return null
79
- }
86
+ case 'toggle': {
87
+ if (typeof raw !== 'boolean') return `var '${name}' expects true or false`
88
+ ;(varDef as ToggleVar).set(raw)
89
+ return null
90
+ }
80
91
 
81
- if (varDef instanceof ChoiceVar) {
82
- if (typeof raw === 'string' && varDef.parse(raw)) return null
83
- return `var '${name}' expects one of: ${listSome(varDef.choices)}`
84
- }
92
+ case 'choice': {
93
+ const v = varDef as ChoiceVar<string>
94
+ if (typeof raw === 'string' && v.parse(raw)) return null
95
+ return `var '${name}' expects one of: ${listSome(v.choices)}`
96
+ }
85
97
 
86
- if (varDef instanceof LorasVar) {
87
- if (raw == null || typeof raw !== 'object' || Array.isArray(raw))
88
- return `var '${name}' expects {"<lora name>": false | true | strength | [model, clip]}`
89
- const record = raw as Record<string, unknown>
90
- const known = new Set<string>(varDef.options)
91
- const unknownNames = Object.keys(record).filter((k) => !known.has(k))
92
- if (unknownNames.length > 0)
93
- return `var '${name}': unknown lora(s) ${unknownNames.join(', ')} — available: ${listSome(varDef.options)}`
94
- for (const [k, s] of Object.entries(record))
95
- if (!isLoraStrength(s)) return `var '${name}': '${k}' must be false | true | number | [model, clip]`
96
- varDef.set(record as Partial<Record<string, LoraStrength>>) // every entry validated just above
97
- return null
98
- }
98
+ case 'loras': {
99
+ const v = varDef as LorasVar<string>
100
+ if (raw == null || typeof raw !== 'object' || Array.isArray(raw))
101
+ return `var '${name}' expects {"<lora name>": false | true | strength | [model, clip]}`
102
+ const record = raw as Record<string, unknown>
103
+ const known = new Set<string>(v.options)
104
+ const unknownNames = Object.keys(record).filter((k) => !known.has(k))
105
+ if (unknownNames.length > 0)
106
+ return `var '${name}': unknown lora(s) ${unknownNames.join(', ')} — available: ${listSome(v.options)}`
107
+ for (const [k, st] of Object.entries(record))
108
+ if (!isLoraStrength(st)) return `var '${name}': '${k}' must be false | true | number | [model, clip]`
109
+ v.set(record as Partial<Record<string, LoraStrength>>) // every entry validated just above
110
+ return null
111
+ }
99
112
 
100
- if (varDef instanceof SizeVar) {
101
- if (typeof raw === 'string' && varDef.parse(raw)) return null
102
- if (raw != null && typeof raw === 'object' && !Array.isArray(raw)) {
103
- const o = raw as { width?: unknown; height?: unknown }
104
- if (isFiniteNumber(o.width) && isFiniteNumber(o.height)) {
105
- varDef.set({ width: o.width, height: o.height })
106
- return null
113
+ case 'size': {
114
+ const v = varDef as SizeVar
115
+ if (typeof raw === 'string' && v.parse(raw)) return null
116
+ if (raw != null && typeof raw === 'object' && !Array.isArray(raw)) {
117
+ const o = raw as { width?: unknown; height?: unknown }
118
+ if (isFiniteNumber(o.width) && isFiniteNumber(o.height)) {
119
+ v.set({ width: o.width, height: o.height })
120
+ return null
121
+ }
107
122
  }
123
+ return `var '${name}' expects {"width":W,"height":H}, "WxH", or a preset label`
108
124
  }
109
- return `var '${name}' expects {"width":W,"height":H}, "WxH", or a preset label`
110
- }
111
125
 
112
- if (varDef instanceof ImageVar) {
113
- if (typeof raw !== 'string') return `var '${name}' expects a file path or http(s) url string`
114
- varDef.set(raw)
115
- return null
116
- }
126
+ case 'image': {
127
+ if (typeof raw !== 'string') return `var '${name}' expects a file path or http(s) url string`
128
+ ;(varDef as ImageVar).set(raw)
129
+ return null
130
+ }
117
131
 
118
- return `var '${name}' has unsupported kind '${varDef.kind}'`
132
+ default: {
133
+ // same as describeVar: `never` is the compile-time check, the runtime path keeps
134
+ // the message a caller can act on instead of answering a bare token
135
+ const unknownKind: never = varDef.kind
136
+ return `var '${name}' has unsupported kind '${String(unknownKind)}'`
137
+ }
138
+ }
119
139
  }
@@ -1,17 +1,16 @@
1
1
  // PURE var → descriptor: ONE introspection pass feeds GET /drafts (json) AND
2
2
  // the startup print (renderDescriptorLine)
3
- import {
4
- type AnyVar,
3
+ import type {
4
+ AnyVar,
5
5
  ChoiceVar,
6
6
  FloatVar,
7
7
  ImageVar,
8
8
  IntVar,
9
9
  LorasVar,
10
- PromptVar,
11
10
  SeedVar,
11
+ SizePreset,
12
12
  SizeVar,
13
- type SizePreset,
14
- type VarKind,
13
+ VarKind,
15
14
  } from 'src/vars/ComfyVars.ts'
16
15
 
17
16
  export type VarDescriptor = {
@@ -36,31 +35,61 @@ function rangeText(opts: { min?: number; max?: number }): string {
36
35
 
37
36
  export function describeVar(varDef: AnyVar): VarDescriptor {
38
37
  const base = { kind: varDef.kind, label: varDef.label, default: varDef.defaultValue }
39
- if (varDef instanceof PromptVar) return { ...base, payload: 'string ("//" lines = comments, "- " lines = negative)' }
40
- if (varDef instanceof IntVar)
41
- return { ...base, payload: `integer${rangeText(varDef.opts)}`, min: varDef.opts.min, max: varDef.opts.max }
42
- if (varDef instanceof FloatVar)
43
- return { ...base, payload: `number${rangeText(varDef.opts)}`, min: varDef.opts.min, max: varDef.opts.max }
44
- if (varDef instanceof SeedVar)
45
- return {
46
- ...base,
47
- default: { mode: varDef.mode, value: varDef.defaultValue },
48
- payload: 'number (fixed) or {"mode":"=|+|-|?","value":number}',
38
+ // kind, never instanceof: the cli bundle and the consumer's `comfy-ts` import hold
39
+ // different copies of every class (VarKind owns the WHY). Casts are the sanctioned
40
+ // kind-narrowing family (agent/coding.md cast whitelist 6)
41
+ switch (varDef.kind) {
42
+ case 'prompt':
43
+ return { ...base, payload: 'string ("//" lines = comments, "- " lines = negative)' }
44
+ case 'text':
45
+ return { ...base, payload: 'string' }
46
+ case 'int': {
47
+ const v = varDef as IntVar
48
+ return { ...base, payload: `integer${rangeText(v.opts)}`, min: v.opts.min, max: v.opts.max }
49
49
  }
50
- if (varDef.kind === 'toggle') return { ...base, payload: 'true or false' }
51
- if (varDef instanceof ChoiceVar)
52
- return { ...base, payload: `one of: ${varDef.choices.join(' | ')}`, choices: varDef.choices }
53
- if (varDef instanceof LorasVar)
54
- return {
55
- ...base,
56
- payload: '{"<lora name>": false | true | strength | [model, clip]}',
57
- options: varDef.options,
50
+ case 'float': {
51
+ const v = varDef as FloatVar
52
+ return { ...base, payload: `number${rangeText(v.opts)}`, min: v.opts.min, max: v.opts.max }
58
53
  }
59
- if (varDef instanceof SizeVar)
60
- return { ...base, payload: '{"width":W,"height":H} or "WxH" or a preset label', presets: varDef.presets }
61
- if (varDef instanceof ImageVar)
62
- return { ...base, payload: 'local file path or http(s) url', extensions: varDef.extensions }
63
- return { ...base, payload: 'string' } // TextVar and future plain kinds
54
+ case 'seed': {
55
+ const v = varDef as SeedVar
56
+ return {
57
+ ...base,
58
+ default: { mode: v.mode, value: v.defaultValue },
59
+ payload: 'number (fixed) or {"mode":"=|+|-|?","value":number}',
60
+ }
61
+ }
62
+ case 'toggle':
63
+ return { ...base, payload: 'true or false' }
64
+ case 'choice': {
65
+ const v = varDef as ChoiceVar<string>
66
+ return { ...base, payload: `one of: ${v.choices.join(' | ')}`, choices: v.choices }
67
+ }
68
+ case 'loras': {
69
+ const v = varDef as LorasVar<string>
70
+ return {
71
+ ...base,
72
+ payload: '{"<lora name>": false | true | strength | [model, clip]}',
73
+ options: v.options,
74
+ }
75
+ }
76
+ case 'size': {
77
+ const v = varDef as SizeVar
78
+ return { ...base, payload: '{"width":W,"height":H} or "WxH" or a preset label', presets: v.presets }
79
+ }
80
+ case 'image': {
81
+ const v = varDef as ImageVar
82
+ return { ...base, payload: 'local file path or http(s) url', extensions: v.extensions }
83
+ }
84
+ default: {
85
+ // an unknown kind CAN reach here: a globally installed cli against a project on a
86
+ // newer comfy-ts (wire tolerance, agent/coding.md whitelist 4). The `never` binding
87
+ // is the compile-time exhaustiveness check; the RUNTIME path must degrade, because
88
+ // printStartup calls d.kind.padEnd() before the server ever listens
89
+ const unknownKind: never = varDef.kind
90
+ return { ...base, payload: `string (unrecognised kind '${String(unknownKind)}')` }
91
+ }
92
+ }
64
93
  }
65
94
 
66
95
  /** one aligned console line per var (startup print) */
@@ -51,6 +51,7 @@ export const ProgressLine = observer((p: { st: TuiSt }) => {
51
51
 
52
52
  const KIND_KEYS: Record<string, Hint[]> = {
53
53
  text: [['⏎/→', 'edit']],
54
+ prompt: [['⏎/→', 'edit']],
54
55
  int: [['⏎/→', 'edit']],
55
56
  float: [['⏎/→', 'edit']],
56
57
  seed: [
@@ -13,9 +13,13 @@ export const TextOverlay = observer((p: { st: TuiSt }) => {
13
13
  const s = p.st
14
14
  const ed = s.editor
15
15
  const winLines = s.overlayLines
16
- const promptVar = s.selected?.[1]
17
- const isPrompt = promptVar instanceof PromptVar
18
- const injected = isPrompt ? promptVar.injectedKeywords() : []
16
+ const selectedVar = s.selected?.[1]
17
+ // kind, never instanceof: the cli bundle and a consumer's `comfy-ts` import hold
18
+ // different copies of every var class (VarKind owns the WHY). Cast is the sanctioned
19
+ // kind-narrowing family (agent/coding.md whitelist 6)
20
+ const promptVar = selectedVar?.kind === 'prompt' ? (selectedVar as PromptVar) : null
21
+ const isPrompt = promptVar != null
22
+ const injected = promptVar?.injectedKeywords() ?? []
19
23
  // lines with their global code-point start offsets
20
24
  const lines: { text: string; start: number }[] = []
21
25
  let start = 0