comfy-ts 2.7.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +20 -13
  2. package/dist/{DefinedWorkflow-BJgt5t0x.js → DefinedWorkflow-BatWaZO1.js} +199 -16
  3. package/dist/DefinedWorkflow-BatWaZO1.js.map +1 -0
  4. package/dist/{DraftsSt-dizp3VcC.js → LogsSt-DFxzQfDc.js} +152 -4
  5. package/dist/LogsSt-DFxzQfDc.js.map +1 -0
  6. package/dist/cli.js +7 -5
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +284 -35
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +125 -7
  11. package/dist/index.d.ts +125 -7
  12. package/dist/index.js +282 -37
  13. package/dist/index.js.map +1 -1
  14. package/dist/run-serve-_nrvJYyt.js +1948 -0
  15. package/dist/run-serve-_nrvJYyt.js.map +1 -0
  16. package/dist/{run-tui-JxlEbb_f.js → run-tui-BLEdTsOX.js} +106 -157
  17. package/dist/run-tui-BLEdTsOX.js.map +1 -0
  18. package/dist/serve-web.js +441 -72
  19. package/dist/{state-CaHeDL-0.js → state-BbgJeCe6.js} +180 -45
  20. package/dist/state-BbgJeCe6.js.map +1 -0
  21. package/dist/web.d.ts +185 -7
  22. package/dist/web.js +235 -36
  23. package/dist/web.js.map +1 -1
  24. package/examples/README.md +1 -0
  25. package/examples/comfy-cloud/sdk.d.ts +4066 -321
  26. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +18 -2
  27. package/examples/rvion/07-local-llm-text-gen.cflow.ts +220 -0
  28. package/examples/web/tsconfig.json +3 -0
  29. package/extra/README.md +32 -0
  30. package/extra/comfyui-textgen-stream/README.md +35 -0
  31. package/extra/comfyui-textgen-stream/__init__.py +166 -0
  32. package/extra/scripts/fetch_text_encoder.py +137 -0
  33. package/package.json +6 -3
  34. package/src/cli/comfy-ts-cli.ts +3 -1
  35. package/src/cli/serve/ServeApp.ts +754 -40
  36. package/src/cli/serve/applyVarPayload.ts +10 -3
  37. package/src/cli/serve/describeVar.ts +47 -7
  38. package/src/cli/serve/hostProtocol.ts +68 -0
  39. package/src/cli/serve/managerOnlyLoras.ts +27 -0
  40. package/src/cli/serve/run-serve.ts +35 -38
  41. package/src/cli/serve/serveSettings.ts +86 -0
  42. package/src/cli/serve/startupPrint.ts +111 -0
  43. package/src/cli/serve/web/api.ts +97 -1
  44. package/src/cli/serve/web/components/App.tsx +61 -22
  45. package/src/cli/serve/web/components/Gallery.tsx +306 -41
  46. package/src/cli/serve/web/components/Icon.tsx +160 -0
  47. package/src/cli/serve/web/components/PromptEnhancer.tsx +12 -9
  48. package/src/cli/serve/web/components/Sidebar.tsx +43 -19
  49. package/src/cli/serve/web/components/VarsForm.tsx +440 -91
  50. package/src/cli/serve/web/components/controls/BasicControls.tsx +38 -5
  51. package/src/cli/serve/web/components/controls/ImageControl.tsx +3 -2
  52. package/src/cli/serve/web/components/controls/LorasControl.tsx +498 -81
  53. package/src/cli/serve/web/components/controls/PresetPicker.tsx +60 -0
  54. package/src/cli/serve/web/components/controls/SeedControl.tsx +38 -20
  55. package/src/cli/serve/web/components/controls/SizeControl.tsx +3 -2
  56. package/src/cli/serve/web/llm.ts +1 -1
  57. package/src/cli/serve/web/logWeb.ts +6 -0
  58. package/src/cli/serve/web/state/EnhancerSt.ts +8 -15
  59. package/src/cli/serve/web/state/FormSt.ts +74 -18
  60. package/src/cli/serve/web/state/RunSt.ts +22 -1
  61. package/src/cli/serve/web/state/WebSt.ts +814 -22
  62. package/src/cli/serve/web/state/host.ts +206 -0
  63. package/src/cli/serve/web/state/lightbox.ts +44 -0
  64. package/src/cli/serve/web/state/moduleTree.ts +52 -0
  65. package/src/cli/serve/web/state/payload.ts +44 -2
  66. package/src/cli/serve/web/state/urlSelection.ts +53 -0
  67. package/src/cli/serve/web/styles.ts +422 -57
  68. package/src/cli/serve/web/tsconfig.json +4 -0
  69. package/src/cli/tui/components/PickerOverlays.tsx +37 -0
  70. package/src/cli/tui/components/StatusBar.tsx +14 -1
  71. package/src/cli/tui/components/TuiApp.tsx +5 -2
  72. package/src/cli/tui/state/HostSt.ts +3 -2
  73. package/src/cli/tui/state/PickerSt.ts +48 -2
  74. package/src/cli/tui/state/TreeSt.ts +1 -1
  75. package/src/cli/tui/state/TuiSt.ts +2 -1
  76. package/src/coreExports.ts +8 -1
  77. package/src/graph/ComfyNode.ts +58 -1
  78. package/src/host/ComfyHost.ts +13 -2
  79. package/src/host/ComfyManager.ts +31 -13
  80. package/src/host/loraInfoCache.ts +35 -1
  81. package/src/host/loraManagerApi.ts +94 -0
  82. package/src/index.ts +2 -0
  83. package/src/promptEnhancers.ts +102 -0
  84. package/src/runner/ComfyExecution.ts +61 -6
  85. package/src/runner/ComfyWorkflow.ts +18 -4
  86. package/src/runner/ComfyWsApi.ts +3 -0
  87. package/src/runner/describePromptRejection.ts +34 -0
  88. package/src/sdk-generator/ComfySchema.ts +17 -4
  89. package/src/sdk-generator/comfyui-sdk-codegen.ts +56 -2
  90. package/src/utils/ansi.ts +13 -0
  91. package/src/utils/matchesRegex.ts +13 -0
  92. package/src/utils/safeName.ts +29 -0
  93. package/src/utils/stringMap.ts +9 -0
  94. package/src/vars/ComfyVars.ts +61 -10
  95. package/src/vars/presets.ts +17 -0
  96. package/src/web.ts +12 -0
  97. package/dist/DefinedWorkflow-BJgt5t0x.js.map +0 -1
  98. package/dist/DraftsSt-dizp3VcC.js.map +0 -1
  99. package/dist/run-serve-D1Tsuru9.js +0 -1162
  100. package/dist/run-serve-D1Tsuru9.js.map +0 -1
  101. package/dist/run-tui-JxlEbb_f.js.map +0 -1
  102. package/dist/state-CaHeDL-0.js.map +0 -1
  103. package/src/cli/serve/promptEnhancers.ts +0 -69
  104. package/src/cli/serve/safeName.ts +0 -12
@@ -26,8 +26,24 @@ export const t2i = host.defineWorkflow({
26
26
  // lines (both stripped from .positive; negatives land in .negative),
27
27
  // and the ACTIVE loras' keywords prefix .positive (assigned via ⌃K
28
28
  // in the TUI loras overlay, stored in .comfy-ts/lora-keywords.json)
29
- prompt: v.prompt('top-down, game sprite, spherical sheep', { loraKeywordsFrom: loras }),
30
- seed: v.seed(517),
29
+ // presets are named starting texts (`P` in the TUI, the presets button in the panel):
30
+ // this pipeline is a sprite factory, and the subject changes far more often than the
31
+ // framing does. Picking one REPLACES the box, so the draft is what reverts it
32
+ prompt: v.prompt('top-down, game sprite, spherical sheep', {
33
+ loraKeywordsFrom: loras,
34
+ presets: {
35
+ 'sheep sprite': 'top-down, game sprite, spherical sheep',
36
+ 'rabbit sprite': 'top-down, game sprite, round rabbit, long ears',
37
+ 'prop, isometric': 'isometric game prop, wooden crate, painted wood grain, soft top light',
38
+ 'icon, flat':
39
+ 'flat vector game icon, thick outline, two-tone shading, centered\n- gradient, photo, text',
40
+ 'portrait, painterly':
41
+ 'painterly character portrait, shoulders up, warm rim light, muted background\n- extra fingers, watermark',
42
+ },
43
+ }),
44
+ // '+' by default: a tuning session wants every run to be a new image, and the
45
+ // number still says exactly which one you are on
46
+ seed: v.seed(517, { mode: '+' }),
31
47
  steps: v.int(8, { min: 1, max: 40 }),
32
48
  size: v.size({ width: 1024, height: 1024 }),
33
49
  removeBg: v.toggle(true, 'remove bg'),
@@ -0,0 +1,220 @@
1
+ // local LLMs inside ComfyUI, no api key and no second service: core's `TextGenerate`
2
+ // (comfy_extras.nodes_textgen, aliased "LLM"/"gemma" in the node search) runs a chat model
3
+ // loaded through the ORDINARY text-encoder path — CLIPLoader with any `type`, the loader
4
+ // ignores it and hands the causal LM to the generator. A STRING output reaches TypeScript
5
+ // only through an output node's ui payload, so PreviewAny terminates the graph and the
6
+ // result lands in `execution.text`.
7
+ //
8
+ // The point of this one is measurement, not pictures: which text encoders on a given box
9
+ // are actually generative, how fast, and how well they expand a short prompt.
10
+ //
11
+ // run directly: bun examples/rvion/07-local-llm-text-gen.cflow.ts ["a cat on a roof"]
12
+ // probe the box: bun examples/rvion/07-local-llm-text-gen.cflow.ts --sweep
13
+ import { ComfyTS, promptEnhancerPresets, v } from 'comfy-ts'
14
+
15
+ const comfy = ComfyTS.create()
16
+ const host = comfy.host({ id: 'windows-1', host: 'desktop-im18794', port: 8085 })
17
+ await host.loadSchemaFromCache() // offline import; run() connects lazily
18
+
19
+ // generative on this box (measured, see --sweep). Every entry is a plain text_encoders/
20
+ // file: nothing here was installed for LLM use, they arrived with image models.
21
+ const GENERATIVE = [
22
+ 'qwen_3_4b.safetensors', // best answers, but REASONS first: needs ~1024 tokens to get past <think>
23
+ // abliterated = the refusal behaviour trained out. Same Qwen3-4B shape (hidden 2560), so
24
+ // ComfyUI detects and runs them exactly like the stock one. Fetched with
25
+ // extra/scripts/fetch_text_encoder.py, which merges the HF shards into one file
26
+ 'qwen_3_4b_abliterated_v2.safetensors', // huihui-ai/Huihui-Qwen3-4B-abliterated-v2
27
+ 'qwen_3_4b_abliterated.safetensors', // huihui-ai/Qwen3-4B-abliterated (the older v1)
28
+ 'ernie-image-prompt-enhancer.safetensors', // 4s, purpose-built expander; drifts into repetition past ~128 tokens
29
+ 'ernie-image-prompt-enhancer-abliterated.safetensors', // ponpoke/ERNIE-Image-Abliterated (abliterated_pe)
30
+ 'qwen3vl_4b_fp8_scaled.safetensors', // vision-language, also takes an `image` input
31
+ 'qwen3vl_4b_abliterated.safetensors', // huihui-ai/Huihui-Qwen3-VL-4B-Instruct-abliterated
32
+ 'ministral-3-3b.safetensors', // no chat template: echoes the instruction before answering
33
+ 'ministral-3-3b-abliterated.safetensors', // Nitral-Archive/mistralai_Ministral-3-3B-Instruct-2512-BF16-abliterated
34
+ ] as const
35
+
36
+ // every text encoder on the box, generative or not — the --sweep corpus. The non-generative
37
+ // ones are the control: an encoder-only T5/CLIP has no `.generate` and must fail.
38
+ const SWEEP_CANDIDATES = [
39
+ ...GENERATIVE,
40
+ 'qwen_3_8b_fp8mixed.safetensors',
41
+ 'mistral_3_small_flux2_bf16.safetensors',
42
+ 'qwen_2.5_vl_7b_fp8_scaled.safetensors',
43
+ 'clip_l.safetensors',
44
+ 't5\\t5xxl_fp8_e4m3fn_scaled.safetensors',
45
+ 'umt5_xxl_fp8_e4m3fn_scaled.safetensors',
46
+ ] as const
47
+
48
+ // the instruction IS the workflow: the same 4B model writes a krea2 paragraph or a terse tag
49
+ // line depending only on this text. So they ship as PRESETS on the var (`P` in the TUI, the
50
+ // presets button in the web panel) instead of living in five commented-out lines
51
+ const INSTRUCTIONS = {
52
+ 'expand, one sentence':
53
+ 'You expand short image prompts into vivid detailed ones. Reply with only the expanded prompt, one sentence.',
54
+ 'krea2 paragraph':
55
+ 'You expand short image prompts for a text to image model that reads flowing natural language. Reply with ONE paragraph of 60 to 150 words. Keep every subject, action and color the input names, then add lighting, palette, material and texture, camera angle and distance, composition, and the signature of the medium. No praise words, no lists, no preamble.',
56
+ 'cinematic photo':
57
+ 'You turn a short subject into a photographic brief. Reply with one paragraph: the subject first, then lens and distance, lighting setup, time of day, film stock or sensor look, depth of field, and the color palette. Photographic language only, no illustration or render terms.',
58
+ 'anime cel':
59
+ 'You turn a short subject into an anime cel-animation brief. Reply with one paragraph: character, expression, pose, hair and clothing, then background, key light color, line weight and shading style. Say what era or studio look it follows.',
60
+ 'terse tags':
61
+ 'You rewrite a subject as a comma separated tag list for an image model: 12 to 20 tags, concrete visual nouns and adjectives only, subject tags first, then style, lighting and composition. Reply with the tags on one line, nothing else.',
62
+ 'to english, unchanged':
63
+ 'You translate the input into English. Change nothing else: same subjects, same order, same level of detail. Reply with the translation only.',
64
+ } as const
65
+
66
+ type TextGenParams = {
67
+ model: (typeof SWEEP_CANDIDATES)[number]
68
+ instruction: string
69
+ subject: string
70
+ maxLength: number
71
+ temperature: number
72
+ repetitionPenalty: number
73
+ seed: number
74
+ thinking: boolean
75
+ streaming: boolean
76
+ }
77
+
78
+ /** core `TextGenerate` hands back the answer once, at the end. `StreamTextGenerate` publishes
79
+ * it every few tokens instead, so you WATCH it write — the protocol always could (a node
80
+ * publishes live text on binary ws frame type 3), core just never calls it. Ships in
81
+ * extra/comfyui-textgen-stream/, copy that folder into ComfyUI/custom_nodes/ to get it.
82
+ * Feature-detected, never assumed: on a host without it the graph falls back to core */
83
+ const STREAMING_NODE = 'StreamTextGenerate'
84
+ /** the builder key of a custom node is qualified by its python module, so it follows the
85
+ * FOLDER you installed it under (`comfyui-textgen-stream` → `textgen-stream.`) */
86
+ const STREAMING_NODE_KEY = 'textgen-stream.StreamTextGenerate'
87
+ const hasStreamingNode = host.schema.nodes.some((n) => n.nameInComfy === STREAMING_NODE)
88
+
89
+ /** the whole graph, shared by the tweakable workflow below and the --sweep probe */
90
+ const buildTextGen = (b: Comfy.Windows1.Builder, p: TextGenParams): void => {
91
+ const clip = b.CLIPLoader({
92
+ clip_name: p.model,
93
+ // the loader ignores `type` for a causal LM; the official llm templates spell it
94
+ // 'stable_diffusion' too
95
+ type: 'stable_diffusion',
96
+ device: 'default',
97
+ })
98
+ const shared = {
99
+ clip,
100
+ prompt: `${p.instruction}\n\n${p.subject}`,
101
+ max_length: p.maxLength,
102
+ thinking: p.thinking,
103
+ // the branch's remaining knobs (top_k, top_p, min_p) fill from the schema — the host
104
+ // declares them required and defaults none of them
105
+ sampling_mode: 'on',
106
+ 'sampling_mode.temperature': p.temperature,
107
+ 'sampling_mode.repetition_penalty': p.repetitionPenalty,
108
+ 'sampling_mode.seed': p.seed,
109
+ } as const
110
+ const generated = p.streaming ? b[STREAMING_NODE_KEY]({ ...shared, stream_every: 4 }) : b.TextGenerate({ ...shared })
111
+ b.PreviewAny({ source: generated._STRING })
112
+ }
113
+
114
+ export const localLlmTextGen = host.defineWorkflow({
115
+ id: 'local-llm-text-gen',
116
+ vars: {
117
+ model: v.choice(GENERATIVE, 'qwen_3_4b.safetensors', 'llm'),
118
+ // every one of these wants FRAMING: fed a bare subject, the enhancer models
119
+ // continue the text instead of expanding it (ernie writes a novel's front matter)
120
+ instruction: v.text(INSTRUCTIONS['expand, one sentence'], {
121
+ label: 'instruction',
122
+ // a system prompt is a paragraph you rewrite, not a value you type once
123
+ multiline: true,
124
+ // the six above, plus every master prompt in `.comfy-ts/prompt-enhancers/` — the same
125
+ // library the web panel's ✨ button uses. One place to tune a paragraph, two surfaces
126
+ // offering it. The folder is empty in a fresh checkout, and the inline six still stand
127
+ presets: { ...promptEnhancerPresets(), ...INSTRUCTIONS },
128
+ }),
129
+ subject: v.text('a cat on a roof', {
130
+ label: 'subject',
131
+ multiline: true,
132
+ presets: {
133
+ 'cat on a roof': 'a cat on a roof',
134
+ 'harvest mouse': 'a harvest mouse on a branch',
135
+ 'rocket launch': 'a rocket launch seen from very close',
136
+ 'jester, dark fantasy': 'a menacing jester with a glowing sword',
137
+ },
138
+ }),
139
+ // the budget must cover the whole answer INCLUDING a reasoning preamble, and a
140
+ // truncated run just stops mid-word: ~1024 for qwen3, ~128 for ernie (which pads
141
+ // with repetition once past its natural length)
142
+ maxLength: v.int(1024, { min: 16, max: 4096, label: 'max tokens' }),
143
+ temperature: v.float(0.7, { min: 0.01, max: 2 }),
144
+ // small models pad by repeating themselves; raising this is the lever against it
145
+ repetitionPenalty: v.float(1.05, { min: 1, max: 2, label: 'repetition penalty' }),
146
+ seed: v.seed(1),
147
+ // qwen3 reasons whatever this says (the flag only binds when the model's template
148
+ // exposes the toggle) — answerOf() below drops the <think> block either way
149
+ thinking: v.toggle(false, 'reason before answering'),
150
+ // defaults to ON where the host has the node, so it needs no explanation when it works
151
+ // and tells the truth when the node is absent
152
+ streaming: v.toggle(hasStreamingNode, 'watch it write (needs the streaming node)'),
153
+ },
154
+ build: (b, vars) => buildTextGen(b, { ...vars, streaming: vars.streaming && hasStreamingNode }),
155
+ })
156
+
157
+ export default localLlmTextGen
158
+
159
+ /** a reasoning model narrates inside <think> before answering; keep the answer */
160
+ const answerOf = (text: string): string => {
161
+ const closed = text.split('</think>')
162
+ const answer = (closed.length > 1 ? closed.at(-1) : text) ?? text
163
+ return answer.trim()
164
+ }
165
+
166
+ // standalone run (skipped when another driver — e.g. the TUI — imports this module)
167
+ if (import.meta.main) {
168
+ const sweeping = process.argv.includes('--sweep')
169
+
170
+ if (!sweeping) {
171
+ if (process.argv[2]) localLlmTextGen.vars.subject.set(process.argv[2])
172
+ const execution = await localLlmTextGen.run({ log: true })
173
+ const text = execution.text
174
+ if (text == null) console.log('🔴 no text output — the model produced nothing')
175
+ else console.log(`\n${answerOf(text)}\n`)
176
+ host.disconnect()
177
+ } else {
178
+ // one row per text encoder on the box: does it generate at all, how fast, what does it say
179
+ console.log(`probing ${SWEEP_CANDIDATES.length} text encoders on ${host.data.id}`)
180
+ // a ❌ row prints the host's python traceback above it, because a failed execution is
181
+ // loud everywhere else in the library. Here the traceback IS the answer: read the
182
+ // exception, `'T5' object has no attribute 'generate'` means encoder-only
183
+ console.log(`each failure prints its ComfyUI traceback — that is the answer for that model\n`)
184
+ // these run raw workflows rather than the defined one (the model var only offers the
185
+ // generative four), so the connect that DefinedWorkflow.run does is ours to make
186
+ await host.connect()
187
+ const vars = localLlmTextGen.vars
188
+ for (const model of SWEEP_CANDIDATES) {
189
+ // a cold model takes tens of seconds to load: say what is loading, not just what came back
190
+ console.log(`→ ${model}`)
191
+ const workflow = host.workflow({ id: `llm-probe-${model}` })
192
+ buildTextGen(workflow.builder, {
193
+ model,
194
+ instruction: vars.instruction.value,
195
+ subject: vars.subject.value,
196
+ maxLength: vars.maxLength.value,
197
+ temperature: vars.temperature.value,
198
+ repetitionPenalty: vars.repetitionPenalty.value,
199
+ streaming: false,
200
+ seed: vars.seed.value,
201
+ thinking: vars.thinking.value,
202
+ })
203
+ const startedAt = Date.now()
204
+ const execution = await workflow.run({})
205
+ const seconds = ((Date.now() - startedAt) / 1000).toFixed(1)
206
+ const text = execution.text
207
+ if (execution.status === 'Failure' || text == null) {
208
+ // an encoder-only model fails HERE, on the host: no `.generate` on a T5/CLIP
209
+ console.log(`❌ ${model} — no generation (${seconds}s)`)
210
+ continue
211
+ }
212
+ const answer = answerOf(text).replaceAll('\n', ' ').trim()
213
+ // it generated, but every token went into an unclosed <think>: a budget problem,
214
+ // not a capability one, and a blank row would read as the opposite
215
+ if (answer.length === 0) console.log(`🟡 ${model} — ${seconds}s, reasoned past the token budget`)
216
+ else console.log(`✅ ${model} — ${seconds}s\n ${answer.slice(0, 160)}`)
217
+ }
218
+ host.disconnect()
219
+ }
220
+ }
@@ -14,5 +14,8 @@
14
14
  // sets makes a typecheck fail on a symbol that exists (tests/tsconfig-buildinfo)
15
15
  "tsBuildInfoFile": "../../node_modules/.cache/tsbuildinfo-examples-web.json"
16
16
  },
17
+ // MUST override the root's exclude: it lists this directory (to keep dom types out of
18
+ // the library check), and inheriting it left these files unchecked by every config
19
+ "exclude": ["../../src/cli/serve/web"],
17
20
  "include": [".", "../../src"]
18
21
  }
@@ -0,0 +1,32 @@
1
+ # extra
2
+
3
+ Things that live outside the TypeScript library but make it more useful. Nothing here is imported by `comfy-ts`; each folder stands alone.
4
+
5
+ ## [`comfyui-textgen-stream/`](comfyui-textgen-stream/), a ComfyUI custom node
6
+
7
+ `Generate Text (streaming)`: core `TextGenerate`, except it publishes the answer as it is produced instead of once at the end. Copy the folder into `ComfyUI/custom_nodes/` and restart. The live text arrives as `execution.progressText`, which `comfy-ts serve` renders while the run is in flight.
8
+
9
+ ## [`scripts/fetch_text_encoder.py`](scripts/fetch_text_encoder.py), a Hugging Face model, ready for `CLIPLoader`
10
+
11
+ ```
12
+ python fetch_text_encoder.py <hf-repo-id> <output-name.safetensors> [--dest DIR]
13
+ ```
14
+
15
+ ComfyUI does not use `transformers`. It reimplements a closed list of architectures with hardcoded dimensions and works out which one a file is from its **tensor shapes**, so only a model matching a supported architecture at a supported size can load. It also loads exactly one file, while Hugging Face ships sharded.
16
+
17
+ This checks the repo's `config.json` against what ComfyUI implements, refuses early with the reason when it does not match, and otherwise downloads the shards and merges them into a single `.safetensors` in `models/text_encoders/`.
18
+
19
+ What can generate text, as of ComfyUI 0.27: **Qwen3** (0.6B / 2B / 4B / 8B), **Gemma 2-2B**, **Gemma 3** (4B / 12B), **Ministral-3-3B**. A finetune of one of those, abliterated ones included, has the same shapes as its base and works; an architecture ComfyUI has no implementation for does not, whatever its size.
20
+
21
+ Run it with the same Python ComfyUI itself uses, so `torch` and `safetensors` are the ones already installed:
22
+
23
+ ```
24
+ <comfy-python> fetch_text_encoder.py huihui-ai/Huihui-Qwen3-4B-Instruct-2507-abliterated qwen_3_4b_abliterated.safetensors --dest <comfy>/models/text_encoders
25
+ ```
26
+
27
+ Restart ComfyUI afterwards: the model list is read at startup.
28
+
29
+ Two things it handles that trip up a hand-rolled merge, both found the hard way:
30
+
31
+ - **Key nesting differs per repo.** ComfyUI wants the transformer at `model.layers.*`, but a VL repo ships `model.language_model.layers.*` and some abliterations ship `language_model.model.layers.*`. Left alone the model loads and generates pure newlines. The script finds the key carrying `layers.0.input_layernorm.weight` and strips whatever sits in front of it, so any spelling normalises.
32
+ - **Some ComfyUI repacks embed the tokenizer as a tensor.** Ministral and ERNIE files carry `tekken_model`; a raw Hugging Face merge has no such key and `CLIPLoader` dies with `the JSON object must be str, bytes or bytearray, not NoneType`. `--borrow-from <working.safetensors>` copies any tensor the merge lacks from a working file of the same architecture.
@@ -0,0 +1,35 @@
1
+ # comfyui-textgen-stream
2
+
3
+ A ComfyUI custom node: **`Generate Text (streaming)`**, core `TextGenerate`, except you can watch it write.
4
+
5
+ ## Why it exists
6
+
7
+ ComfyUI's `TextGenerate` blocks for the whole generation and publishes its answer once, when the node finishes. Nothing partial reaches a client, so a long answer is a progress bar and a wait.
8
+
9
+ The protocol was never the limit. `PromptServer.send_progress_text(text, node_id)` pushes a node's live text as binary websocket frame type 3, and several nodes already use it. Core `TextGenerate` simply never calls it.
10
+
11
+ ## How it works
12
+
13
+ The generation loop (`comfy/text_encoders/llama.py`) keeps its token list local, so there is nothing to subscribe to. What is reachable is `sample_token`, called exactly once per generated token and returning the token it picked. This node wraps that method for the duration of one call, decodes what has accumulated every `stream_every` tokens, and publishes it. The real sampling loop runs unmodified, nothing is reimplemented, so sampling behaviour is identical to core.
14
+
15
+ The wrapper is installed and removed around a single `generate()` call, in a `finally`, so an exception cannot leave a patched model behind.
16
+
17
+ ## Install
18
+
19
+ Copy this folder into `ComfyUI/custom_nodes/` and restart ComfyUI:
20
+
21
+ ```
22
+ ComfyUI/custom_nodes/comfyui-textgen-stream/__init__.py
23
+ ```
24
+
25
+ Uninstall by deleting the folder. It patches nothing at import time.
26
+
27
+ ## Use from comfy-ts
28
+
29
+ `examples/rvion/07-local-llm-text-gen.cflow.ts` feature-detects it and falls back to core `TextGenerate` where it is absent. The live text arrives as `execution.progressText` (and on the `onProgress` callback), which `comfy-ts serve` renders in the results panel as the answer builds up.
30
+
31
+ Note the builder key is qualified by the folder you install it under: `comfyui-textgen-stream` becomes `textgen-stream.StreamTextGenerate`.
32
+
33
+ ## Limits
34
+
35
+ `stream_every: 1` is true token-by-token; decoding the accumulated ids each time costs a little, so a few tokens per frame reads the same and wastes less. A model whose text stack exposes no `sample_token` gets no live text and generates normally, the node says so in the ComfyUI log rather than failing.
@@ -0,0 +1,166 @@
1
+ """StreamTextGenerate: core TextGenerate, but you can watch it write.
2
+
3
+ ComfyUI's own TextGenerate blocks for the whole generation and publishes the answer once, at
4
+ the end. The protocol can already carry live text (PromptServer.send_progress_text, binary ws
5
+ frame type 3): the node simply never calls it.
6
+
7
+ The generation loop lives in comfy/text_encoders/llama.py and keeps its token list local, so
8
+ there is nothing to subscribe to. What IS reachable is `sample_token`, a method on the text
9
+ model called exactly once per generated token, returning the token it picked. Wrapping it for
10
+ the duration of one call gives every token as it is produced, at the cost of no reimplemented
11
+ sampling: the real loop still runs, unmodified.
12
+
13
+ Install: copy this folder into ComfyUI/custom_nodes/ and restart. Remove it by deleting the
14
+ folder, it patches nothing at import time and leaves no trace when the node is not running.
15
+ """
16
+
17
+ from server import PromptServer
18
+ from comfy_api.latest import ComfyExtension, io
19
+ from typing_extensions import override
20
+
21
+
22
+ class StreamTextGenerate(io.ComfyNode):
23
+ @classmethod
24
+ def define_schema(cls):
25
+ sampling_options = [
26
+ io.DynamicCombo.Option(
27
+ key="on",
28
+ inputs=[
29
+ io.Float.Input("temperature", default=0.7, min=0.01, max=2.0, step=0.000001),
30
+ io.Int.Input("top_k", default=64, min=0, max=1000),
31
+ io.Float.Input("top_p", default=0.95, min=0.0, max=1.0, step=0.01),
32
+ io.Float.Input("min_p", default=0.05, min=0.0, max=1.0, step=0.01),
33
+ io.Float.Input("repetition_penalty", default=1.05, min=0.0, max=5.0, step=0.01),
34
+ io.Int.Input("seed", default=0, min=0, max=0xFFFFFFFFFFFFFFFF),
35
+ io.Float.Input("presence_penalty", optional=True, default=0.0, min=0.0, max=5.0, step=0.01),
36
+ ],
37
+ ),
38
+ io.DynamicCombo.Option(key="off", inputs=[]),
39
+ ]
40
+ return io.Schema(
41
+ node_id="StreamTextGenerate",
42
+ display_name="Generate Text (streaming)",
43
+ category="text",
44
+ search_aliases=["LLM", "stream"],
45
+ inputs=[
46
+ io.Clip.Input("clip"),
47
+ io.String.Input("prompt", multiline=True, dynamic_prompts=True, default=""),
48
+ io.Image.Input("image", optional=True),
49
+ io.Audio.Input("audio", optional=True),
50
+ io.Int.Input("max_length", default=512, min=1, max=32768),
51
+ io.DynamicCombo.Input("sampling_mode", options=sampling_options, display_name="Sampling Mode"),
52
+ io.Int.Input(
53
+ "stream_every",
54
+ default=4,
55
+ min=1,
56
+ max=256,
57
+ tooltip="publish the text so far every N tokens. 1 is token-by-token; decoding costs a little, so a few tokens per frame reads the same and wastes less.",
58
+ ),
59
+ io.Boolean.Input("thinking", optional=True, default=False),
60
+ io.Boolean.Input("use_default_template", optional=True, default=True, advanced=True),
61
+ ],
62
+ outputs=[io.String.Output(display_name="generated_text")],
63
+ hidden=[io.Hidden.unique_id],
64
+ )
65
+
66
+ @staticmethod
67
+ def _find_sampler_owner(root, depth=4):
68
+ """the nearest object exposing sample_token, following the encoder chain"""
69
+ seen = []
70
+ node = root
71
+ for _ in range(depth):
72
+ if node is None:
73
+ break
74
+ if callable(getattr(node, "sample_token", None)):
75
+ return node
76
+ seen.append(type(node).__name__)
77
+ nxt = getattr(node, node.clip, None) if isinstance(getattr(node, "clip", None), str) else None
78
+ node = nxt if nxt is not None else getattr(node, "transformer", None)
79
+ print(f"[StreamTextGenerate] no sample_token under {' / '.join(seen)}, no live text for this model")
80
+ return None
81
+
82
+ @classmethod
83
+ def execute(
84
+ cls,
85
+ clip,
86
+ prompt,
87
+ max_length,
88
+ sampling_mode,
89
+ stream_every=4,
90
+ image=None,
91
+ audio=None,
92
+ thinking=False,
93
+ use_default_template=True,
94
+ ) -> io.NodeOutput:
95
+ tokens = clip.tokenize(
96
+ prompt,
97
+ image=image,
98
+ skip_template=not use_default_template,
99
+ min_length=1,
100
+ thinking=thinking,
101
+ audio=audio,
102
+ )
103
+
104
+ do_sample = sampling_mode.get("sampling_mode") == "on"
105
+ node_id = cls.hidden.unique_id
106
+
107
+ # walk down to whoever OWNS sample_token rather than hardcoding the depth: the chain is
108
+ # cond_stage_model, then getattr(it, it.clip), then .transformer today (comfy/sd1_clip.py), and
109
+ # it has changed shape before. Searching by capability survives that; a wrong guess here
110
+ # is silent, since a missing wrap just means no frames
111
+ model = cls._find_sampler_owner(clip.cond_stage_model)
112
+ original = getattr(model, "sample_token", None)
113
+
114
+ produced = []
115
+
116
+ def publish():
117
+ if node_id is None:
118
+ return
119
+ try:
120
+ PromptServer.instance.send_progress_text(clip.decode(produced), node_id)
121
+ except Exception:
122
+ # a failed publish must never kill a generation that is otherwise fine
123
+ pass
124
+
125
+ def sample_token(*args, **kwargs):
126
+ token = original(*args, **kwargs)
127
+ produced.append(token[0].item())
128
+ if len(produced) % max(1, stream_every) == 0:
129
+ publish()
130
+ return token
131
+
132
+ if original is not None:
133
+ model.sample_token = sample_token
134
+ try:
135
+ generated_ids = clip.generate(
136
+ tokens,
137
+ do_sample=do_sample,
138
+ max_length=max_length,
139
+ temperature=sampling_mode.get("temperature", 1.0),
140
+ top_k=sampling_mode.get("top_k", 50),
141
+ top_p=sampling_mode.get("top_p", 1.0),
142
+ min_p=sampling_mode.get("min_p", 0.0),
143
+ repetition_penalty=sampling_mode.get("repetition_penalty", 1.0),
144
+ presence_penalty=sampling_mode.get("presence_penalty", 0.0),
145
+ seed=sampling_mode.get("seed", None),
146
+ )
147
+ finally:
148
+ # restore even on an exception: the model object outlives this call and a leaked
149
+ # wrapper would keep appending to a dead list on every later generation
150
+ if original is not None:
151
+ model.sample_token = original
152
+
153
+ generated_text = clip.decode(generated_ids)
154
+ if node_id is not None:
155
+ publish()
156
+ return io.NodeOutput(generated_text)
157
+
158
+
159
+ class StreamTextGenExtension(ComfyExtension):
160
+ @override
161
+ async def get_node_list(self) -> list[type[io.ComfyNode]]:
162
+ return [StreamTextGenerate]
163
+
164
+
165
+ async def comfy_entrypoint() -> ComfyExtension:
166
+ return StreamTextGenExtension()
@@ -0,0 +1,137 @@
1
+ """Download a Hugging Face causal LM and write it as ONE safetensors file ComfyUI can load.
2
+
3
+ ComfyUI reimplements a closed list of architectures with hardcoded dimensions and detects
4
+ which one a file is from its TENSOR SHAPES (comfy/sd.py::detect_te_model), so only a model
5
+ matching a supported architecture AND size works. It also loads exactly one file, while HF
6
+ ships sharded, this merges the shards and drops the result in models/text_encoders/.
7
+
8
+ python fetch_text_encoder.py <hf-repo-id> <output-name.safetensors> [--dest DIR]
9
+
10
+ It refuses rather than writing a file ComfyUI would reject: the config must name a supported
11
+ architecture, and the hidden size must be one comfy has a config for.
12
+ """
13
+
14
+ import argparse
15
+ import json
16
+ import os
17
+ import sys
18
+
19
+ # hidden_size -> what comfy's detect_te_model will call it (comfy/sd.py, verified 0.27.0).
20
+ # Generation additionally needs the class to mix in BaseGenerate, which is true for all of these
21
+ SUPPORTED = {
22
+ "qwen3": {1024: "Qwen3-0.6B", 2048: "Qwen3-2B", 2560: "Qwen3-4B", 4096: "Qwen3-8B"},
23
+ "gemma2": {2304: "Gemma2-2B"},
24
+ "gemma3": {2560: "Gemma3-4B", 3840: "Gemma3-12B"},
25
+ "gemma3_text": {2560: "Gemma3-4B", 3840: "Gemma3-12B"},
26
+ "ministral3": {3072: "Ministral-3-3B"},
27
+ # a VL model keeps its language dims: comfy remaps model.language_model.* -> model.* on load
28
+ "qwen3_vl": {2560: "Qwen3-VL-4B", 4096: "Qwen3-VL-8B"},
29
+ # a VL repo names its TEXT config qwen3_vl_text; the vision tower rides along in the file
30
+ "qwen3_vl_text": {2560: "Qwen3-VL-4B", 4096: "Qwen3-VL-8B"},
31
+ }
32
+
33
+
34
+ # ComfyUI's text-encoder stack wants the transformer at `model.layers.*` and a vision tower
35
+ # at `visual.*` (its own repacks ship that way). Hugging Face repos nest them differently and
36
+ # INCONSISTENTLY: a VL repo uses `model.language_model.layers.*`, another abliteration ships
37
+ # `language_model.model.layers.*`, a plain text model is already `model.layers.*`. Rather than
38
+ # keep a table of prefixes per repo, find the key that carries the anchor and strip whatever
39
+ # sits in front of it, which normalizes every spelling seen so far and the next one too
40
+ LAYER_ANCHOR = "layers.0.input_layernorm.weight"
41
+
42
+
43
+ def normalize_keys(merged: dict) -> dict:
44
+ """rename so the transformer lands at model.* and any vision tower at visual.*"""
45
+ anchor_key = next((k for k in merged if k.endswith(LAYER_ANCHOR)), None)
46
+ if anchor_key is None:
47
+ return merged
48
+ prefix = anchor_key[: -len(LAYER_ANCHOR)]
49
+ if prefix == "model.":
50
+ return merged
51
+ print(f" normalizing key prefix {prefix!r} -> 'model.'")
52
+ out = {}
53
+ for k, v in merged.items():
54
+ if k.startswith(prefix):
55
+ out["model." + k[len(prefix) :]] = v
56
+ elif "visual." in k:
57
+ out["visual." + k.split("visual.", 1)[1]] = v
58
+ else:
59
+ out[k] = v
60
+ return out
61
+
62
+
63
+ def main() -> int:
64
+ ap = argparse.ArgumentParser()
65
+ ap.add_argument("repo")
66
+ ap.add_argument("out")
67
+ ap.add_argument("--dest", default=None, help="text_encoders dir (default: ./models/text_encoders)")
68
+ ap.add_argument("--subdir", default=None, help="repo subfolder holding the model (some repos ship several)")
69
+ ap.add_argument(
70
+ "--borrow-from",
71
+ default=None,
72
+ help="an existing working .safetensors to copy NON-MODEL tensors from. Some ComfyUI "
73
+ "repacks embed the tokenizer as a tensor (Ministral/ERNIE carry 'tekken_model'), and a "
74
+ "raw HF merge has no such key, so CLIPLoader dies on json.loads(None). Point this at the "
75
+ "stock file for the same architecture",
76
+ )
77
+ args = ap.parse_args()
78
+
79
+ from huggingface_hub import hf_hub_download, snapshot_download
80
+ from safetensors.torch import load_file, save_file
81
+
82
+ prefix = f"{args.subdir.rstrip('/')}/" if args.subdir else ""
83
+ cfg_path = hf_hub_download(args.repo, f"{prefix}config.json")
84
+ cfg = json.load(open(cfg_path, encoding="utf-8"))
85
+ text_cfg = cfg.get("text_config", cfg)
86
+ model_type = str(text_cfg.get("model_type", "")).lower()
87
+ hidden = int(text_cfg.get("hidden_size", 0))
88
+
89
+ sizes = SUPPORTED.get(model_type)
90
+ if sizes is None:
91
+ print(f"ERROR: '{model_type}' is not one of the architectures ComfyUI implements: {sorted(SUPPORTED)}")
92
+ return 1
93
+ if hidden not in sizes:
94
+ print(f"ERROR: {model_type} hidden_size {hidden} has no comfy config (it knows {sorted(sizes)})")
95
+ return 1
96
+ print(f"OK: {args.repo} is {sizes[hidden]} ({model_type}, hidden {hidden}), ComfyUI can run this")
97
+
98
+ dest = args.dest or os.path.join("models", "text_encoders")
99
+ os.makedirs(dest, exist_ok=True)
100
+ target = os.path.join(dest, args.out)
101
+ if os.path.exists(target):
102
+ print(f"SKIP: {target} already exists, nothing downloaded")
103
+ return 0
104
+
105
+ print("downloading weights...")
106
+ local = snapshot_download(args.repo, allow_patterns=[f"{prefix}*.safetensors", f"{prefix}*.safetensors.index.json"])
107
+ local = os.path.join(local, args.subdir) if args.subdir else local
108
+
109
+ # .bak siblings are a real thing in the wild and are NOT part of the model
110
+ shards = sorted(f for f in os.listdir(local) if f.endswith(".safetensors"))
111
+ if not shards:
112
+ print("ERROR: the repo publishes no .safetensors (a GGUF-only repo cannot be used here)")
113
+ return 1
114
+ merged: dict = {}
115
+ for shard in shards:
116
+ print(f" + {shard}")
117
+ # contiguous: a merged view can otherwise refuse to serialize
118
+ for k, v in load_file(os.path.join(local, shard)).items():
119
+ merged[k] = v.contiguous()
120
+ merged = normalize_keys(merged)
121
+
122
+ if args.borrow_from:
123
+ donor = load_file(args.borrow_from)
124
+ extra = {k: v.clone().contiguous() for k, v in donor.items() if k not in merged}
125
+ del donor
126
+ if extra:
127
+ print(f" borrowing {sorted(extra)} from {os.path.basename(args.borrow_from)}")
128
+ merged.update(extra)
129
+
130
+ print(f"writing {target} ({len(merged)} tensors)")
131
+ save_file(merged, target)
132
+ print(f"OK: done, restart ComfyUI and it appears in CLIPLoader as {args.out}")
133
+ return 0
134
+
135
+
136
+ if __name__ == "__main__":
137
+ sys.exit(main())