comfy-ts 0.3.0 → 1.0.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 (73) hide show
  1. package/README.md +349 -255
  2. package/dist/DefinedWorkflow-O3ynII3Y.js +598 -0
  3. package/dist/DefinedWorkflow-O3ynII3Y.js.map +1 -0
  4. package/dist/cli.js +3969 -128
  5. package/dist/cli.js.map +1 -1
  6. package/dist/index.cjs +1208 -170
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +449 -115
  9. package/dist/index.d.ts +449 -115
  10. package/dist/index.js +1200 -171
  11. package/dist/index.js.map +1 -1
  12. package/dist/{run-tui-Io8Xea0L.js → run-tui-BFhba_oG.js} +744 -665
  13. package/dist/run-tui-BFhba_oG.js.map +1 -0
  14. package/examples/01-txt2img.cflow.ts +50 -0
  15. package/examples/02-img2img-upload.cflow.ts +66 -0
  16. package/examples/03-export-workflow-json.cflow.ts +56 -0
  17. package/examples/04-krea2-turbo-t2i.cflow.ts +125 -0
  18. package/examples/05-comfy-cloud.cflow.ts +67 -0
  19. package/examples/comfy-cloud/sdk.d.ts +122674 -0
  20. package/guide-for-agents.md +166 -0
  21. package/package.json +7 -3
  22. package/src/cli/comfy-ts-cli.ts +19 -2
  23. package/src/cli/gen.ts +21 -12
  24. package/src/cli/tui/components/Header.tsx +5 -0
  25. package/src/cli/tui/components/LogsPanel.tsx +23 -0
  26. package/src/cli/tui/components/PreviewPanel.tsx +52 -7
  27. package/src/cli/tui/components/StatusBar.tsx +10 -4
  28. package/src/cli/tui/components/TreePanel.tsx +15 -2
  29. package/src/cli/tui/components/TuiApp.tsx +26 -3
  30. package/src/cli/tui/discoverWorkflows.ts +79 -0
  31. package/src/cli/tui/protocolImagePainter.ts +54 -18
  32. package/src/cli/tui/run-tui.tsx +55 -24
  33. package/src/cli/tui/state/ExecSt.ts +4 -1
  34. package/src/cli/tui/state/HostSt.ts +123 -1
  35. package/src/cli/tui/state/LogsSt.ts +107 -0
  36. package/src/cli/tui/state/PreviewSt.ts +173 -23
  37. package/src/cli/tui/state/SettingsSt.ts +48 -21
  38. package/src/cli/tui/state/TreeSt.ts +30 -6
  39. package/src/cli/tui/state/TuiSt.ts +27 -3
  40. package/src/cli/tui/state/WorkflowsSt.ts +16 -1
  41. package/src/host/ComfyHost.ts +241 -71
  42. package/src/host/ComfyManager.ts +10 -9
  43. package/src/host/ComfyUploader.ts +1 -2
  44. package/src/host/ResilientWebsocket.ts +3 -1
  45. package/src/host/hostUrl.ts +59 -0
  46. package/src/host/loraManagerApi.ts +5 -4
  47. package/src/index.ts +20 -1
  48. package/src/litegraph/CanonicalWorkflow.ts +77 -0
  49. package/src/litegraph/LiteGraphGroup.ts +9 -7
  50. package/src/litegraph/LiteGraphJSON.ts +34 -13
  51. package/src/litegraph/LiteGraphLink.ts +32 -2
  52. package/src/litegraph/LiteGraphNode.ts +18 -33
  53. package/src/litegraph/LiteGraphNodeInput.ts +10 -8
  54. package/src/litegraph/LiteGraphNodeOutput.ts +2 -3
  55. package/src/litegraph/LiteGraphSubgraphDef.ts +74 -0
  56. package/src/litegraph/convertFlowToLiteGraphJSON.ts +4 -4
  57. package/src/litegraph/expandSubgraphs.ts +352 -0
  58. package/src/litegraph/normalizeWorkflow.ts +141 -0
  59. package/src/runner/ComfyExecution.ts +4 -5
  60. package/src/runner/ComfyWorkflow.ts +2 -2
  61. package/src/runner/ComfyWsApi.ts +12 -1
  62. package/src/runner/wsBinaryFrame.ts +48 -0
  63. package/src/sdk-generator/Primitives.ts +6 -24
  64. package/src/sdk-generator/comfy-api-json.ts +3 -1
  65. package/src/sdk-generator/inputWidgetKind.ts +179 -0
  66. package/src/sdk-generator/litegraphToApiRequestPayload.ts +372 -96
  67. package/src/ssh-host-manager/ssh-manager.ts +0 -15
  68. package/src/state.ts +13 -2
  69. package/src/utils/ansi.ts +7 -0
  70. package/src/utils/mojibake.ts +60 -0
  71. package/dist/log-CdfgILde.js +0 -10
  72. package/dist/log-CdfgILde.js.map +0 -1
  73. package/dist/run-tui-Io8Xea0L.js.map +0 -1
@@ -1,564 +1,79 @@
1
- import { t as logError } from "./log-CdfgILde.js";
2
- import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
1
+ import { a as setLoraKeyword, c as stripAnsi, i as getLoraKeyword, n as LorasVar, o as extractErrorMessage, r as PromptVar, t as DefinedWorkflow, u as logError } from "./DefinedWorkflow-O3ynII3Y.js";
2
+ import { spawn } from "node:child_process";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
5
  import { basename, dirname, join, resolve } from "pathe";
4
6
  import { createHash } from "node:crypto";
5
- import { pathToFileURL } from "node:url";
6
- import { Box, Text, render, useApp, useInput, useStdin } from "ink";
7
- import { action, makeAutoObservable, makeObservable, observable, reaction, runInAction } from "mobx";
7
+ import { type } from "arktype";
8
8
  import sharp from "sharp";
9
+ import { imageMeta } from "image-meta";
10
+ import { makeAutoObservable, observable, reaction, runInAction } from "mobx";
11
+ import { Box, Text, render, useApp, useInput, useStdin } from "ink";
9
12
  import { observer } from "mobx-react-lite";
10
13
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
11
- import { spawn } from "node:child_process";
12
- import { type } from "arktype";
13
14
  //#region src/cli/tui-env.ts
14
15
  const COMFY_TS_TUI_ENV = "COMFY_TS_TUI";
15
16
  //#endregion
16
- //#region src/vars/loraKeywords.ts
17
+ //#region src/cli/tui/discoverWorkflows.ts
17
18
  /**
18
- * hand-assigned trigger keyword(s) per lora name — set via ⌃K in the TUI loras
19
- * overlay, consumed by PromptVar's `loraKeywordsFrom` prefixing. Persisted at
20
- * `.comfy-ts/lora-keywords.json` (NOT under cache/: this is hand-entered data
21
- * and must survive a cache wipe). Observable map: overlay rows re-render on
22
- * assignment. Keys are the RAW lora names (folder/file.safetensors).
19
+ * recursive scan for the workflow-module naming convention. Entries BELOW a
20
+ * node_modules segment are skipped: packaged examples arrive via
21
+ * bundledExamplesDir (symlinked layouts like pnpm would otherwise list them
22
+ * twice, un-deduped, as the user's own files), and third-party packages
23
+ * shipping *.cflow.ts are not this project's workflows. A scan root that is
24
+ * ITSELF inside node_modules still works (the filter is relative to the root).
23
25
  */
24
- const keywords = observable.map();
25
- let loaded = false;
26
- function filePath() {
27
- return join(comfyts.baseFolder, "lora-keywords.json");
28
- }
29
- function loadOnce() {
30
- if (loaded) return;
31
- loaded = true;
32
- const path = filePath();
33
- if (!existsSync(path)) return;
34
- try {
35
- const raw = JSON.parse(readFileSync(path, "utf8"));
36
- if (raw == null || typeof raw !== "object") return;
37
- runInAction(() => {
38
- for (const [name, kw] of Object.entries(raw)) if (typeof kw === "string") keywords.set(name, kw);
39
- });
40
- } catch (e) {
41
- logError(`[loraKeywords] unreadable ${path}: ${String(e)}`);
42
- }
43
- }
44
- function getLoraKeyword(name) {
45
- loadOnce();
46
- return keywords.get(name) ?? "";
47
- }
48
- /** empty keyword deletes the entry; every set writes the file (tiny, rare) */
49
- function setLoraKeyword(name, keyword) {
50
- loadOnce();
51
- const trimmed = keyword.trim();
52
- runInAction(() => {
53
- if (trimmed === "") keywords.delete(name);
54
- else keywords.set(name, trimmed);
55
- });
56
- const path = filePath();
57
- try {
58
- mkdirSync(dirname(path), { recursive: true });
59
- writeFileSync(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2));
60
- } catch (e) {
61
- logError(`[loraKeywords] write failed ${path}: ${String(e)}`);
62
- }
26
+ function scanCflowFiles(dir) {
27
+ return readdirSync(dir, { recursive: true }).map((f) => String(f)).filter((f) => !f.split("/").includes("node_modules")).map((f) => join(dir, f)).filter((f) => f.endsWith(".cflow.ts") || f.endsWith(".cflow.tsx")).sort();
63
28
  }
64
- //#endregion
65
- //#region src/vars/ComfyVars.ts
66
- /**
67
- * full base: T is what's STORED/edited, Out what the GRAPH consumes at build
68
- * time. They usually coincide — extend `ComfyVar<T>` for that. PromptVar is
69
- * the one Out-specialized var (string in, PromptValue out); the split keeps
70
- * outValue() cast-free.
71
- */
72
- var ComfyVarBase = class {
73
- constructor(defaultValue, label) {
74
- this.defaultValue = defaultValue;
75
- this.label = label;
76
- this.value = defaultValue;
77
- makeObservable(this, {
78
- value: observable,
79
- set: action,
80
- reset: action,
81
- parse: action,
82
- loadJSON: action
83
- });
84
- }
85
- set(value) {
86
- this.value = value;
87
- return this;
88
- }
89
- /** what drafts persist for this var (subclasses may add fields, e.g. seed mode) */
90
- toJSON() {
91
- return this.value;
92
- }
93
- /**
94
- * restore a value produced by toJSON() (drafts). The cast is sanctioned:
95
- * drafts are our own round-trip, subclasses re-validate via set().
96
- */
97
- loadJSON(value) {
98
- return this.set(value);
99
- }
100
- reset() {
101
- this.value = this.defaultValue;
102
- return this;
103
- }
104
- /** how the value renders in a var list */
105
- display() {
106
- return String(this.value);
107
- }
108
- /** the string the inline editor starts from (round-trips through parse) */
109
- toEditBuffer() {
110
- return String(this.value);
111
- }
112
- /** hook run after every DefinedWorkflow.run() (default no-op; SeedVar advances) */
113
- afterRun() {}
114
- };
115
- /** the standard var: the graph consumes the stored value AS-IS (Out = T) */
116
- var ComfyVar = class extends ComfyVarBase {
117
- outValue() {
118
- return this.value;
119
- }
120
- };
121
- var TextVar = class extends ComfyVar {
122
- constructor(..._args) {
123
- super(..._args);
124
- this.kind = "text";
125
- }
126
- parse(raw) {
127
- this.set(raw);
128
- return true;
129
- }
130
- };
131
- const commentLineRe = /^\s*\/\//;
132
- const negativeLineRe = /^\s*- (.*)$/;
133
29
  /**
134
- * prompt text with editor comforts, all resolved at BUILD time (the editor and
135
- * drafts keep the raw text):
136
- * - `//` lines are COMMENTS — stripped
137
- * - `- ` lines are NEGATIVE prompt lines — removed from `.positive`,
138
- * comma-joined into `.negative`
139
- * - with `loraKeywordsFrom`, the ACTIVE loras' hand-assigned keywords
140
- * (src/vars/loraKeywords.ts, ⌃K in the TUI) prefix `.positive` —
141
- * `injectedKeywords()` is public so the TUI can PREVIEW the injection.
30
+ * the examples/ folder shipped in the npm tarball, resolved from THIS module's
31
+ * own location (NEVER cwd): walking up to the nearest NAMED package.json finds
32
+ * <pkg>/examples both from a consumer's node_modules/comfy-ts/dist/cli.js and
33
+ * from this repo's src/cli/tui/. Returns null when the examples are absent
34
+ * (a consumer may prune the folder) or when the nearest named package is not
35
+ * comfy-ts (the lib was inlined into someone else's bundle — its examples are
36
+ * not on disk); no package.json all the way up is a broken install and throws.
142
37
  */
143
- var PromptVar = class extends ComfyVarBase {
144
- constructor(defaultValue, promptOpts = {}) {
145
- super(defaultValue, promptOpts.label);
146
- this.promptOpts = promptOpts;
147
- this.kind = "text";
148
- }
149
- parse(raw) {
150
- this.set(raw);
151
- return true;
152
- }
153
- static isCommentLine(line) {
154
- return commentLineRe.test(line);
155
- }
156
- static isNegativeLine(line) {
157
- return negativeLineRe.test(line);
158
- }
159
- /** the keyword prefix the flag will inject (deduped, lora-list order) — the TUI previews this */
160
- injectedKeywords() {
161
- const src = this.promptOpts.loraKeywordsFrom;
162
- if (src == null) return [];
163
- return [...new Set(src.activeNames().map(getLoraKeyword).filter((k) => k !== ""))];
164
- }
165
- outValue() {
166
- const pos = [];
167
- const neg = [];
168
- for (const line of this.value.split("\n")) {
169
- if (commentLineRe.test(line)) continue;
170
- const m = negativeLineRe.exec(line);
171
- if (m != null) {
172
- const text = (m[1] ?? "").trim();
173
- if (text !== "") neg.push(text);
174
- } else pos.push(line);
175
- }
176
- const body = pos.join("\n").trim();
177
- const keywords = this.injectedKeywords();
178
- return {
179
- positive: keywords.length === 0 ? body : body === "" ? keywords.join(", ") : `${keywords.join(", ")}, ${body}`,
180
- negative: neg.join(", ")
181
- };
182
- }
183
- };
184
- var IntVar = class extends ComfyVar {
185
- constructor(defaultValue, opts = {}) {
186
- super(defaultValue, opts.label);
187
- this.opts = opts;
188
- this.kind = "int";
189
- }
190
- set(value) {
191
- const clamped = Math.round(Math.min(this.opts.max ?? Infinity, Math.max(this.opts.min ?? -Infinity, value)));
192
- return super.set(clamped);
193
- }
194
- parse(raw) {
195
- const n = Number(raw);
196
- if (Number.isNaN(n)) return false;
197
- this.set(n);
198
- return true;
199
- }
200
- };
201
- var FloatVar = class extends ComfyVar {
202
- constructor(defaultValue, opts = {}) {
203
- super(defaultValue, opts.label);
204
- this.opts = opts;
205
- this.kind = "float";
206
- }
207
- set(value) {
208
- return super.set(Math.min(this.opts.max ?? Infinity, Math.max(this.opts.min ?? -Infinity, value)));
209
- }
210
- parse(raw) {
211
- const n = Number(raw);
212
- if (Number.isNaN(n)) return false;
213
- this.set(n);
214
- return true;
215
- }
216
- };
217
- /**
218
- * a seed is a MODE + a number. `value` stays a plain number (what the graph
219
- * consumes); `mode` decides how it advances after each run (afterRun()):
220
- * `= 12` fixed · `+ 0` auto-increment · `- 0` auto-decrement · `? 0` random.
221
- * The number shown is always the seed the NEXT run will use.
222
- */
223
- var SeedVar = class extends ComfyVar {
224
- constructor(defaultValue = 0, label) {
225
- super(defaultValue, label);
226
- this.kind = "seed";
227
- this.mode = "=";
228
- makeObservable(this, {
229
- mode: observable,
230
- setMode: action,
231
- randomize: action,
232
- advance: action
233
- });
234
- }
235
- setMode(mode) {
236
- this.mode = mode;
237
- return this;
238
- }
239
- randomize() {
240
- return this.set(Math.floor(Math.random() * 2 ** 32));
241
- }
242
- set(value) {
243
- return super.set(Math.max(0, Math.floor(value)));
244
- }
245
- /** move the seed to what the NEXT run should use, per mode */
246
- advance() {
247
- if (this.mode === "+") return this.set(this.value + 1);
248
- if (this.mode === "-") return this.set(this.value - 1);
249
- if (this.mode === "?") return this.randomize();
250
- return this;
251
- }
252
- afterRun() {
253
- this.advance();
254
- }
255
- /** parse `+` `- 12` `= 5` `?` or a bare number (=> fixed). Keeps the current number when none given */
256
- parse(raw) {
257
- const m = raw.trim().match(/^([+\-=?])?\s*(\d+)?$/);
258
- if (m == null) return false;
259
- const modeChar = m[1];
260
- const numStr = m[2];
261
- if (modeChar == null && numStr == null) return false;
262
- this.setMode(modeChar == null ? "=" : modeChar);
263
- if (numStr != null) this.set(Number(numStr));
264
- return true;
265
- }
266
- display() {
267
- return `${this.mode} ${this.value}`;
268
- }
269
- toEditBuffer() {
270
- return `${this.mode} ${this.value}`;
271
- }
272
- toJSON() {
273
- return {
274
- mode: this.mode,
275
- value: this.value
276
- };
277
- }
278
- loadJSON(value) {
279
- if (typeof value === "number") return this.set(value);
280
- if (value != null && typeof value === "object") {
281
- const o = value;
282
- if (o.mode === "=" || o.mode === "+" || o.mode === "-" || o.mode === "?") this.setMode(o.mode);
283
- if (typeof o.value === "number") this.set(o.value);
284
- }
285
- return this;
286
- }
287
- };
288
- var ToggleVar = class extends ComfyVar {
289
- constructor(..._args2) {
290
- super(..._args2);
291
- this.kind = "toggle";
292
- }
293
- toggle() {
294
- return this.set(!this.value);
295
- }
296
- parse(raw) {
297
- if (raw !== "true" && raw !== "false") return false;
298
- this.set(raw === "true");
299
- return true;
300
- }
301
- display() {
302
- return this.value ? "ON" : "OFF";
303
- }
304
- };
305
- var ChoiceVar = class extends ComfyVar {
306
- constructor(choices, defaultValue, label) {
307
- super(defaultValue, label);
308
- this.choices = choices;
309
- this.kind = "choice";
310
- }
311
- next(delta = 1) {
312
- const nextIx = (this.choices.indexOf(this.value) + delta + this.choices.length) % this.choices.length;
313
- return this.set(this.choices[nextIx] ?? this.value);
314
- }
315
- parse(raw) {
316
- const hit = this.choices.find((c) => c === raw);
317
- if (hit == null) return false;
318
- this.set(hit);
319
- return true;
320
- }
321
- };
322
- /**
323
- * multi-select lora stack over a DYNAMIC options list — a RegExp resolves
324
- * against the host's loras at define time (DefinedWorkflow calls bindHost),
325
- * or feed it host discovery (`host.schema.getLoras(regex?)`) directly; never
326
- * a hardcoded inventory. Selection is empty by default.
327
- */
328
- var LorasVar = class LorasVar extends ComfyVar {
329
- constructor(optionsSource, initial = {}, label) {
330
- super(initial, label);
331
- this.optionsSource = optionsSource;
332
- this.kind = "loras";
333
- this.prev = {};
334
- this.resolvedOptions = null;
335
- }
336
- get options() {
337
- if (!(this.optionsSource instanceof RegExp)) return this.optionsSource;
338
- if (this.resolvedOptions == null) throw new Error(`v.loras(${String(this.optionsSource)}) is host-bound — it only works inside defineWorkflow({ vars }) (pass a name list otherwise)`);
339
- return this.resolvedOptions;
340
- }
341
- /** DefinedWorkflow binds the host at define time: a RegExp source resolves here.
342
- * cast: whitelist family 1 (agent/coding.md) — getLoras() returns the runtime
343
- * values of the SAME object_info enum the generated E_LoraName union comes from */
344
- bindHost(host) {
345
- if (!(this.optionsSource instanceof RegExp)) return;
346
- this.resolvedOptions = host.schema.getLoras(this.optionsSource);
347
- }
348
- get names() {
349
- return [...this.options];
350
- }
351
- /** loras currently ON (PromptVar keyword prefixing consumes this) */
352
- activeNames() {
353
- return this.names.filter((n) => this.isOn(n));
354
- }
355
- isOn(name) {
356
- const s = this.value[name];
357
- return s != null && s !== false;
358
- }
359
- toggleItem(name) {
360
- const cur = this.value[name];
361
- if (cur == null || cur === false) return this.set({
362
- ...this.value,
363
- [name]: this.prev[name] ?? true
364
- });
365
- this.prev[name] = cur;
366
- return this.set({
367
- ...this.value,
368
- [name]: false
369
- });
370
- }
371
- /** step both strengths by delta (true becomes 1 first); no-op when off */
372
- adjustItem(name, delta) {
373
- const cur = this.value[name];
374
- if (cur == null || cur === false) return this;
375
- const step = (n) => Math.max(0, Math.round((n + delta) * 100) / 100);
376
- const next = Array.isArray(cur) ? [step(cur[0]), step(cur[1])] : step(cur === true ? 1 : cur);
377
- return this.set({
378
- ...this.value,
379
- [name]: next
380
- });
381
- }
382
- /** compact per-item strength label for lists */
383
- strengthLabel(name) {
384
- const s = this.value[name];
385
- if (s == null || s === false) return "";
386
- if (s === true) return "1.00";
387
- if (Array.isArray(s)) return `m:${s[0].toFixed(2)} c:${s[1].toFixed(2)}`;
388
- return s.toFixed(2);
389
- }
390
- parse(raw) {
391
- try {
392
- const parsed = JSON.parse(raw);
393
- if (typeof parsed !== "object" || parsed == null || Array.isArray(parsed)) return false;
394
- this.set(parsed);
395
- return true;
396
- } catch {
397
- return false;
398
- }
399
- }
400
- /** short human name: subfolder + extension stripped */
401
- static shortName(name) {
402
- return (name.split(/[\\/]/).pop() ?? name).replace(/\.safetensors$/, "");
403
- }
404
- /** tick (true) or untick (false) every lora in `names` (default: all options) */
405
- setAll(on, names = this.options) {
406
- const next = { ...this.value };
407
- for (const name of names) {
408
- const cur = next[name];
409
- if (on) {
410
- if (cur == null || cur === false) next[name] = this.prev[name] ?? true;
411
- } else {
412
- if (cur != null && cur !== false) this.prev[name] = cur;
413
- next[name] = false;
38
+ function bundledExamplesDir(moduleUrl = import.meta.url) {
39
+ let dir = dirname(fileURLToPath(moduleUrl));
40
+ let prev = "";
41
+ while (dir !== prev) {
42
+ const pkgPath = join(dir, "package.json");
43
+ if (existsSync(pkgPath)) {
44
+ let pkg = {};
45
+ try {
46
+ pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
47
+ } catch {}
48
+ if (pkg.name === "comfy-ts") {
49
+ const examples = join(dir, "examples");
50
+ return existsSync(examples) ? examples : null;
414
51
  }
52
+ if (pkg.name != null) return null;
415
53
  }
416
- return this.set(next);
417
- }
418
- display() {
419
- const on = this.activeNames();
420
- if (on.length === 0) return `(0/${this.options.length}) none`;
421
- return `(${on.length}/${this.options.length}) ${on.map((n) => LorasVar.shortName(n)).join(", ")}`;
422
- }
423
- };
424
- /** SDXL-style ~1MP buckets, multiples of 64 — safe for most latent models */
425
- const DEFAULT_SIZE_PRESETS = [
426
- {
427
- label: "1:1 square",
428
- width: 1024,
429
- height: 1024
430
- },
431
- {
432
- label: "4:3 landscape",
433
- width: 1152,
434
- height: 896
435
- },
436
- {
437
- label: "3:4 portrait",
438
- width: 896,
439
- height: 1152
440
- },
441
- {
442
- label: "3:2 landscape",
443
- width: 1216,
444
- height: 832
445
- },
446
- {
447
- label: "2:3 portrait",
448
- width: 832,
449
- height: 1216
450
- },
451
- {
452
- label: "16:9 widescreen",
453
- width: 1344,
454
- height: 768
455
- },
456
- {
457
- label: "9:16 tall",
458
- width: 768,
459
- height: 1344
460
- }
461
- ];
462
- /** width/height picker: presets + free `WxH` entry */
463
- var SizeVar = class extends ComfyVar {
464
- constructor(defaultValue = {
465
- width: 1024,
466
- height: 1024
467
- }, presets = DEFAULT_SIZE_PRESETS, label) {
468
- super(defaultValue, label);
469
- this.presets = presets;
470
- this.kind = "size";
471
- }
472
- /** accepts '1024x768' / '1024×768' / a preset label */
473
- parse(raw) {
474
- const m = raw.trim().match(/^(\d+)\s*[x×]\s*(\d+)$/);
475
- if (m != null) {
476
- this.set({
477
- width: Number(m[1]),
478
- height: Number(m[2])
479
- });
480
- return true;
481
- }
482
- const preset = this.presets.find((p) => p.label === raw.trim());
483
- if (preset != null) {
484
- this.set({
485
- width: preset.width,
486
- height: preset.height
487
- });
488
- return true;
489
- }
490
- return false;
491
- }
492
- display() {
493
- const { width, height } = this.value;
494
- const hit = this.presets.find((p) => p.width === width && p.height === height);
495
- return `${width}×${height}${hit ? ` (${hit.label})` : ""}`;
54
+ prev = dir;
55
+ dir = dirname(dir);
496
56
  }
497
- };
498
- /** the var constructors: v.text / v.prompt / v.int / v.float / v.seed / v.toggle / v.choice / v.loras / v.size */
499
- const v = {
500
- text: (defaultValue, label) => new TextVar(defaultValue, label),
501
- prompt: (defaultValue, opts = {}) => new PromptVar(defaultValue, opts),
502
- int: (defaultValue, opts = {}) => new IntVar(defaultValue, opts),
503
- float: (defaultValue, opts = {}) => new FloatVar(defaultValue, opts),
504
- seed: (defaultValue = 0, label) => new SeedVar(defaultValue, label),
505
- toggle: (defaultValue, label) => new ToggleVar(defaultValue, label),
506
- choice: (choices, defaultValue, label) => new ChoiceVar(choices, defaultValue, label),
507
- loras: (options, initial = {}, label) => new LorasVar(options, initial, label),
508
- size: (defaultValue, opts = {}) => new SizeVar(defaultValue, opts.presets, opts.label)
509
- };
510
- function varValues(vars) {
511
- const out = {};
512
- for (const [k, varDef] of Object.entries(vars)) out[k] = varDef.outValue();
513
- return out;
514
- }
515
- //#endregion
516
- //#region src/vars/DefinedWorkflow.ts
517
- /** type predicate (not a cast): a VarsSpec is a plain record, never callable */
518
- function isVarsThunk(vars) {
519
- return typeof vars === "function";
57
+ throw new Error(`[comfy-ts tui] no package.json found walking up from ${fileURLToPath(moduleUrl)}`);
520
58
  }
521
59
  /**
522
- * a re-runnable workflow definition: `build` re-executes per run with the
523
- * current var values, so every run gets a fresh, deterministic graph.
60
+ * PURE merge of the scan with the packaged examples (headless-tested). An
61
+ * explicit target keeps its scope only. Bundled files ALWAYS group under the
62
+ * bundled section, also when the scan already found them (repo dev: ./examples
63
+ * is under cwd) — dedupe relies on the caller passing realpath-normalized
64
+ * strings on both sides.
524
65
  */
525
- var DefinedWorkflow = class {
526
- constructor(host, spec) {
527
- this.host = host;
528
- this.spec = spec;
529
- this.lastWorkflow = null;
530
- this.lastExecution = null;
531
- this.vars = isVarsThunk(spec.vars) ? spec.vars(v) : spec.vars;
532
- for (const [, varDef] of this.entries()) varDef.bindHost?.(this.host);
533
- }
534
- /** [name, var] pairs, for drivers that enumerate the knobs */
535
- entries() {
536
- return Object.entries(this.vars);
537
- }
538
- /**
539
- * build a fresh graph from the CURRENT var values (no send). `p.advance`
540
- * (set by run()) fires each var's afterRun() right after snapshotting the
541
- * values — atomically, before any await — so the graph uses this run's seed
542
- * while the var moves to the next (queued runs get distinct seeds; a bare
543
- * build() for copy/export never advances).
544
- */
545
- async build(p = {}) {
546
- const wf = this.host.workflow({ id: this.spec.id });
547
- const values = varValues(this.vars);
548
- if (p.advance) for (const varDef of Object.values(this.vars)) varDef.afterRun();
549
- await this.spec.build(wf.builder, values, wf);
550
- this.lastWorkflow = wf;
551
- return wf;
552
- }
553
- /** build a fresh graph from the current var values, send it, wait for outputs.
554
- * connects first (idempotent) — modules can import offline from the schema cache */
555
- async run(settings = {}) {
556
- await this.host.connect();
557
- const execution = await (await this.build({ advance: true })).run(settings);
558
- this.lastExecution = execution;
559
- return execution;
560
- }
561
- };
66
+ function mergeWorkflowSources(p) {
67
+ if (p.explicitTarget) return {
68
+ files: p.scanned,
69
+ bundled: /* @__PURE__ */ new Set()
70
+ };
71
+ const bundled = new Set(p.bundledFiles);
72
+ return {
73
+ files: [...p.scanned.filter((f) => !bundled.has(f)), ...p.bundledFiles],
74
+ bundled
75
+ };
76
+ }
562
77
  //#endregion
563
78
  //#region src/cli/tui/findDefinedWorkflow.ts
564
79
  /**
@@ -603,19 +118,6 @@ async function imageBufferToAnsi(input, p) {
603
118
  return rows.join("\n");
604
119
  }
605
120
  //#endregion
606
- //#region src/utils/extractErrorMessage.ts
607
- /** Extracts an error message from an exception stuff. */
608
- const extractErrorMessage = (error) => {
609
- if (error instanceof Error) return error.message;
610
- if (error === null) return "null";
611
- if (typeof error === "string") return error;
612
- if (typeof error === "object") {
613
- if ("message" in error && typeof error.message === "string") return error.message;
614
- return JSON.stringify(error);
615
- }
616
- return String(error);
617
- };
618
- //#endregion
619
121
  //#region src/cli/tui/state/PreviewSt.ts
620
122
  /** OSC 1337 support: the panel can show REAL images instead of half-blocks */
621
123
  function protocolCapable() {
@@ -623,12 +125,16 @@ function protocolCapable() {
623
125
  const term = process.env.TERM_PROGRAM ?? "";
624
126
  return term === "iTerm.app" || term === "WezTerm" || term === "vscode" || process.env.LC_TERMINAL === "iTerm2";
625
127
  }
128
+ /** small-latent corner: fraction of the panel each dimension takes */
129
+ const CORNER_FRACTION = .38;
130
+ /** pixel 'latent small': the sharp-composited thumb takes this fraction of the panel */
131
+ const PIXEL_SMALL_FRACTION = .4;
626
132
  /**
627
- * right-side preview panel. The MODE (native/ansi/off) lives in SettingsSt and
628
- * is cycled with `p`. 'native' overlay-paints the REAL image over the panel rect
629
- * (protocolImagePainter.ts); 'ansi' renders truecolor half-blocks; 'off' hides
630
- * the panel. Sources: live latent while running, last output after, selected
631
- * lora while the loras overlay is open.
133
+ * right-side preview panel + its `p` settings menu (mode 'preview').
134
+ * Three independent axes live in SettingsSt: panel on/off, renderer
135
+ * native/pixel, and what to show while running (latent / latent small /
136
+ * last output). Sources: live latent while running, last output after,
137
+ * selected lora while the loras overlay is open.
632
138
  */
633
139
  var PreviewSt = class {
634
140
  constructor(st) {
@@ -637,45 +143,143 @@ var PreviewSt = class {
637
143
  this.latentAnsi = null;
638
144
  this.outputBytes = null;
639
145
  this.latentBytes = null;
146
+ this.latentDims = null;
147
+ this.latentSeenThisRun = false;
640
148
  this.lastOutputPath = null;
149
+ this.menuIx = 0;
641
150
  this._busy = false;
642
151
  makeAutoObservable(this, { st: false });
643
152
  }
644
- get mode() {
645
- return this.st.settings.previewMode;
646
- }
647
153
  get show() {
648
- return this.mode !== "off";
154
+ return this.st.settings.previewPanel;
155
+ }
156
+ get renderer() {
157
+ return this.st.settings.previewRenderer;
649
158
  }
650
- /** SettingsSt already downgrades native → ansi on incapable terminals */
651
159
  get useNative() {
652
- return this.mode === "native";
160
+ return this.renderer === "native";
161
+ }
162
+ get duringRun() {
163
+ return this.st.settings.previewDuringRun;
164
+ }
165
+ get menuOpen() {
166
+ return this.st.mode === "preview";
167
+ }
168
+ /** running + latents wanted + sampling well underway + none arrived = server
169
+ * sends none. The ≥20% gate keeps healthy runs from red-flashing: the first
170
+ * progress tick lands a beat before the first preview frame */
171
+ get latentsMissing() {
172
+ return this.st.exec.running && this.duringRun !== "last-output" && (this.st.exec.progress?.percent ?? 0) >= 20 && !this.latentSeenThisRun;
173
+ }
174
+ get menuRows() {
175
+ return [
176
+ {
177
+ key: "panel",
178
+ label: "panel",
179
+ value: this.show ? "on" : "off"
180
+ },
181
+ {
182
+ key: "renderer",
183
+ label: "renderer",
184
+ value: this.renderer + (protocolCapable() ? "" : " (no protocol support)")
185
+ },
186
+ {
187
+ key: "during-run",
188
+ label: "while running",
189
+ value: this.duringRun === "latent" ? "latent" : this.duringRun === "latent-small" ? "latent small" : "last output"
190
+ }
191
+ ];
192
+ }
193
+ beginMenu() {
194
+ this.st.mode = "preview";
195
+ this.menuIx = 0;
196
+ }
197
+ blurMenu() {
198
+ this.st.mode = "nav";
199
+ }
200
+ menuMove(delta) {
201
+ const len = this.menuRows.length;
202
+ this.menuIx = (this.menuIx + delta + len) % len;
203
+ }
204
+ /** cycle the selected row's value (settings persist via SettingsSt reaction) */
205
+ menuCycle(delta) {
206
+ const row = this.menuRows[this.menuIx];
207
+ if (row == null) return;
208
+ const s = this.st.settings;
209
+ if (row.key === "panel") s.previewPanel = !s.previewPanel;
210
+ else if (row.key === "renderer") {
211
+ if (protocolCapable()) s.previewRenderer = s.previewRenderer === "native" ? "pixel" : "native";
212
+ } else {
213
+ const order = [
214
+ "latent",
215
+ "latent-small",
216
+ "last-output"
217
+ ];
218
+ s.previewDuringRun = order[(order.indexOf(s.previewDuringRun) + delta + order.length) % order.length] ?? "latent";
219
+ }
220
+ this.onSettingsChanged();
653
221
  }
654
222
  reset() {
655
223
  this.outputAnsi = null;
656
224
  this.latentAnsi = null;
657
225
  this.outputBytes = null;
658
226
  this.latentBytes = null;
227
+ this.latentDims = null;
228
+ this.latentSeenThisRun = false;
659
229
  this.lastOutputPath = null;
660
230
  }
661
231
  /** run boundary: drop the latents so the next run never shows the previous one's */
662
232
  clearLatent() {
663
233
  this.latentAnsi = null;
664
234
  this.latentBytes = null;
235
+ this.latentDims = null;
236
+ this.latentSeenThisRun = false;
665
237
  }
666
- /** re-render the last output in the newly chosen mode */
667
- onModeChanged() {
238
+ /** re-render the last output for the newly chosen settings */
239
+ onSettingsChanged() {
668
240
  this.outputAnsi = null;
669
241
  this.outputBytes = null;
670
- if (this.mode !== "off" && this.lastOutputPath != null) this.renderOutput(this.lastOutputPath);
242
+ if (this.show && this.lastOutputPath != null) this.renderOutput(this.lastOutputPath);
671
243
  }
672
- /** what the painter should show RIGHT NOW (native mode only; mirrors the panel's source) */
244
+ /** what the painter should show RIGHT NOW (native renderer only; mirrors the panel's source) */
673
245
  get protocolImage() {
674
- if (!this.useNative || !this.show) return null;
246
+ if (!this.useNative || !this.show || this.menuOpen) return null;
675
247
  if (this.st.mode === "overlay-loras") return this.st.loras.previewBytes;
676
- if (this.st.exec.running && this.latentBytes != null) return this.latentBytes;
248
+ if (this.st.exec.running) {
249
+ if (this.duringRun === "latent") return this.latentBytes ?? this.outputBytes;
250
+ return this.outputBytes;
251
+ }
677
252
  return this.outputBytes;
678
253
  }
254
+ /** small latent painted over the panel's top-right corner (native + 'latent small' only) */
255
+ get protocolImageCorner() {
256
+ if (!this.useNative || !this.show || this.menuOpen) return null;
257
+ if (this.st.mode === "overlay-loras") return null;
258
+ if (this.st.exec.running && this.duringRun === "latent-small") return this.latentBytes;
259
+ return null;
260
+ }
261
+ /** corner cell box matched to the latent's REAL aspect (a mismatched box
262
+ * letterboxes in iTerm — his repro: "some vertical rectangle"). Cells are
263
+ * ~1:2 (w:h), hence the ×2 when converting image aspect to cells. */
264
+ get cornerBox() {
265
+ let w = Math.max(8, Math.floor(this.width * CORNER_FRACTION));
266
+ const maxH = Math.max(4, Math.floor(this.height * CORNER_FRACTION));
267
+ const dims = this.latentDims;
268
+ if (dims == null || dims.width === 0 || dims.height === 0) return {
269
+ w,
270
+ h: maxH
271
+ };
272
+ const aspect = dims.width / dims.height;
273
+ let h = Math.max(2, Math.round(w / aspect / 2));
274
+ if (h > maxH) {
275
+ h = maxH;
276
+ w = Math.max(4, Math.round(h * aspect * 2));
277
+ }
278
+ return {
279
+ w,
280
+ h
281
+ };
282
+ }
679
283
  get width() {
680
284
  return Math.max(24, Math.min(80, this.st.termCols - 68 - this.st.treeWidth));
681
285
  }
@@ -684,7 +288,7 @@ var PreviewSt = class {
684
288
  }
685
289
  async renderOutput(path) {
686
290
  this.lastOutputPath = path;
687
- if (this.mode === "off") return;
291
+ if (!this.show) return;
688
292
  try {
689
293
  if (this.useNative) {
690
294
  const shrunk = await sharp(path).resize(896, 896, {
@@ -710,15 +314,23 @@ var PreviewSt = class {
710
314
  }
711
315
  }
712
316
  async renderLatent(bytes) {
713
- if (this.mode === "off") return;
317
+ runInAction(() => {
318
+ this.latentSeenThisRun = true;
319
+ });
320
+ if (!this.show || this.duringRun === "last-output") return;
714
321
  if (this.useNative) {
322
+ const meta = imageMeta(bytes);
715
323
  this.latentBytes = bytes;
324
+ this.latentDims = meta.width != null && meta.height != null ? {
325
+ width: meta.width,
326
+ height: meta.height
327
+ } : null;
716
328
  return;
717
329
  }
718
330
  if (this._busy) return;
719
331
  this._busy = true;
720
332
  try {
721
- const ansi = await imageBufferToAnsi(bytes, {
333
+ const ansi = this.duringRun === "latent-small" ? await this.renderLatentSmallPixel(bytes) : await imageBufferToAnsi(bytes, {
722
334
  width: this.width,
723
335
  height: this.height
724
336
  });
@@ -733,46 +345,92 @@ var PreviewSt = class {
733
345
  this._busy = false;
734
346
  }
735
347
  }
348
+ /** pixel 'latent small': sharp-composite the latent thumb onto the last
349
+ * output (top-right), then ONE half-block render — a string-level overlay
350
+ * was tried and dropped: its space padding reads as black bars */
351
+ async renderLatentSmallPixel(bytes) {
352
+ const pxW = this.width;
353
+ const pxH = this.height * 2;
354
+ const thumb = await sharp(bytes).resize(Math.max(8, Math.floor(pxW * PIXEL_SMALL_FRACTION)), Math.max(8, Math.floor(pxH * PIXEL_SMALL_FRACTION)), { fit: "inside" }).png().toBuffer();
355
+ const outPath = this.lastOutputPath;
356
+ if (outPath == null) return imageBufferToAnsi(thumb, {
357
+ width: this.width,
358
+ height: this.height
359
+ });
360
+ return imageBufferToAnsi(await sharp(await sharp(outPath).resize(pxW, pxH, { fit: "inside" }).png().toBuffer()).composite([{
361
+ input: thumb,
362
+ gravity: "northeast"
363
+ }]).png().toBuffer(), {
364
+ width: this.width,
365
+ height: this.height
366
+ });
367
+ }
736
368
  };
737
369
  //#endregion
738
370
  //#region src/cli/tui/protocolImagePainter.ts
371
+ const SYNC_BEGIN = "\x1B[?2026h";
372
+ const SYNC_END = "\x1B[?2026l";
373
+ /** below this a write is a terminal query/reply, not a frame — no cells damaged */
374
+ const MIN_FRAME_BYTES = 64;
739
375
  /**
740
376
  * paints the REAL image (OSC 1337) over the preview panel's cell rect.
741
377
  * Protocol images cannot go THROUGH ink (layout shreds the escape) and every
742
378
  * ink frame write ERASES the image's cells — so this hooks stdout.write and
743
- * re-paints right after each flush, plus a mobx reaction for byte changes that
744
- * do not move a single frame cell (fresh output/latent/lora bytes).
379
+ * re-paints SYNCHRONOUSLY within the same flush, the whole batch wrapped in
380
+ * DEC 2026 synchronized-update markers: the terminal never presents the
381
+ * erased-frame intermediate state. (The previous deferred setImmediate
382
+ * repaint WAS the native-mode flicker — his repro.) A mobx reaction covers
383
+ * byte-only changes (fresh latent/output/lora bytes with no frame write).
745
384
  * NOT React: effects only fire for the component that re-rendered, which is
746
385
  * why a useEffect painter missed frames (his report: image waited for input).
747
386
  */
748
387
  function installProtocolImagePainter(st) {
749
388
  if (!protocolCapable() || process.stdout.isTTY !== true) return () => {};
750
389
  const original = process.stdout.write.bind(process.stdout);
751
- const paint = () => {
752
- const bytes = st.preview.protocolImage;
753
- if (bytes == null) return;
390
+ const imageEscape = (bytes, row, col, w, h) => {
391
+ const b64 = Buffer.from(bytes).toString("base64");
392
+ return `\u001b7\u001b[${row};${col}H\u001b]1337;File=inline=1;size=${bytes.byteLength};width=${w};height=${h};preserveAspectRatio=1:${b64}\u0007\u001b8`;
393
+ };
394
+ const CONTENT_ROW = 6;
395
+ /** both images as ONE escape string ('' when nothing to paint) */
396
+ const imageEscapes = () => {
754
397
  const pv = st.preview;
398
+ const main = pv.protocolImage;
399
+ const corner = pv.protocolImageCorner;
400
+ if (main == null && corner == null) return "";
755
401
  const col = Math.max(1, st.termCols - (pv.width + 4) + 3);
756
- const b64 = Buffer.from(bytes).toString("base64");
757
- original(`\u001b7\u001b[5;${col}H\u001b]1337;File=inline=1;size=${bytes.byteLength};width=${pv.width};height=${pv.height};preserveAspectRatio=1:${b64}\u0007\u001b8`);
402
+ let out = "";
403
+ if (main != null) out += imageEscape(main, CONTENT_ROW, col, pv.width, pv.height);
404
+ if (corner != null) {
405
+ const box = pv.cornerBox;
406
+ out += imageEscape(corner, CONTENT_ROW, col + pv.width - box.w, box.w, box.h);
407
+ }
408
+ return out;
758
409
  };
410
+ let disposed = false;
411
+ /** byte-only changes (no frame write erased anything): paint alone, atomically */
759
412
  let scheduled = false;
760
413
  const schedule = () => {
761
- if (scheduled) return;
414
+ if (scheduled || disposed) return;
762
415
  scheduled = true;
763
416
  setImmediate(() => {
764
- paint();
765
417
  scheduled = false;
418
+ if (disposed) return;
419
+ const images = imageEscapes();
420
+ if (images !== "") original(SYNC_BEGIN + images + SYNC_END);
766
421
  });
767
422
  };
768
423
  const patched = ((chunk, encodingOrCb, cb) => {
424
+ const images = !disposed && (typeof chunk === "string" ? chunk.length : chunk.byteLength) >= MIN_FRAME_BYTES ? imageEscapes() : "";
425
+ if (images !== "") original(SYNC_BEGIN);
769
426
  const res = typeof encodingOrCb === "function" ? original(chunk, encodingOrCb) : original(chunk, encodingOrCb, cb);
770
- schedule();
427
+ if (images !== "") original(images + SYNC_END);
771
428
  return res;
772
429
  });
773
430
  process.stdout.write = patched;
774
- const disposeReaction = reaction(() => st.preview.protocolImage, schedule);
431
+ const disposeReaction = reaction(() => [st.preview.protocolImage, st.preview.protocolImageCorner], schedule);
775
432
  return () => {
433
+ disposed = true;
776
434
  process.stdout.write = original;
777
435
  disposeReaction();
778
436
  };
@@ -956,6 +614,11 @@ const MODE_KEYS = {
956
614
  ["⏎", "run action"],
957
615
  ["↑↓", "move"],
958
616
  ["h/esc", "back"]
617
+ ],
618
+ preview: [
619
+ ["←→", "change"],
620
+ ["↑↓", "move"],
621
+ ["⏎/p/esc", "done"]
959
622
  ]
960
623
  };
961
624
  /** persistent 2-line keybar: EVERYTHING available right now, always visible */
@@ -967,13 +630,13 @@ const KeyBar = observer((p) => {
967
630
  ["←", "tree"],
968
631
  ...kind ? KIND_KEYS[kind] ?? [] : []
969
632
  ];
970
- const globalHints = s.mode === "nav" || s.mode === "tree" || s.mode === "host" ? [
633
+ const globalHints = s.mode === "nav" || s.mode === "tree" || s.mode === "host" || s.mode === "preview" ? [
971
634
  ["r", "run"],
972
635
  ["s", "reroll+run"],
973
636
  ...s.mode === "nav" ? [["e", "rename draft"]] : [],
974
- ...s.preview.show ? [] : [["p", "preview off"]],
637
+ ...s.preview.show || s.mode === "preview" ? [] : [["p", "preview (off)"]],
975
638
  ["o", "open image"],
976
- ...s.mode === "tree" ? [] : [["c/C", "copy wf/api"]],
639
+ ...s.mode === "tree" || s.mode === "preview" ? [] : [["c/C", "copy wf/api"]],
977
640
  ["q", "quit"]
978
641
  ] : [["⌃R", "run"], ["esc", "back"]];
979
642
  return /* @__PURE__ */ jsxs(Box, {
@@ -1061,21 +724,32 @@ const Header = observer((p) => {
1061
724
  }),
1062
725
  /* @__PURE__ */ jsx(HeaderBox, {
1063
726
  title: "(h)ost",
1064
- children: /* @__PURE__ */ jsxs(Text, { children: [/* @__PURE__ */ jsx(Text, {
1065
- bold: true,
1066
- color: "green",
1067
- children: s.wf.host.data.id
1068
- }), /* @__PURE__ */ jsxs(Text, {
1069
- color: "gray",
1070
- children: [
1071
- " ",
1072
- "(",
1073
- s.wf.host.data.host,
1074
- ":",
1075
- s.wf.host.data.port,
1076
- ")"
1077
- ]
1078
- })] })
727
+ children: /* @__PURE__ */ jsxs(Text, { children: [
728
+ /* @__PURE__ */ jsx(Text, {
729
+ color: s.host.status === "up" ? "green" : s.host.status === "down" ? "red" : "gray",
730
+ children: "● "
731
+ }),
732
+ /* @__PURE__ */ jsx(Text, {
733
+ bold: true,
734
+ color: "green",
735
+ children: s.wf.host.data.id
736
+ }),
737
+ /* @__PURE__ */ jsxs(Text, {
738
+ color: "gray",
739
+ children: [
740
+ " ",
741
+ "(",
742
+ s.wf.host.data.host,
743
+ ":",
744
+ s.wf.host.data.port,
745
+ ")"
746
+ ]
747
+ }),
748
+ s.host.status === "down" && /* @__PURE__ */ jsxs(Text, {
749
+ color: "red",
750
+ children: [" ", s.host.probing ? s.host.spinner : `↻ ${s.host.retryInS}s`]
751
+ })
752
+ ] })
1079
753
  })
1080
754
  ]
1081
755
  });
@@ -1281,17 +955,56 @@ const SizeOverlay = observer((p) => {
1281
955
  });
1282
956
  //#endregion
1283
957
  //#region src/cli/tui/components/PreviewPanel.tsx
1284
- /** right-side panel: selected-lora preview in the loras overlay, live latent while running, last output after.
958
+ /** right-side panel: selected-lora preview in the loras overlay, live latent while running,
959
+ * last output after — plus the `p` settings menu (mode 'preview') rendered in place.
1285
960
  * protocol terminals: the body is BLANK cells — useProtocolImage paints the real image over them */
1286
961
  const PreviewPanel = observer((p) => {
1287
962
  const s = p.st;
1288
963
  const pv = s.preview;
964
+ if (pv.menuOpen) return /* @__PURE__ */ jsxs(Box, {
965
+ borderStyle: "double",
966
+ paddingX: 1,
967
+ flexDirection: "column",
968
+ flexShrink: 0,
969
+ width: pv.width + 4,
970
+ children: [
971
+ /* @__PURE__ */ jsx(Box, {
972
+ marginTop: -1,
973
+ children: /* @__PURE__ */ jsx(Text, {
974
+ color: "gray",
975
+ children: "(p)review · settings"
976
+ })
977
+ }),
978
+ pv.menuRows.map((row, ix) => {
979
+ const sel = ix === pv.menuIx;
980
+ return /* @__PURE__ */ jsxs(Text, {
981
+ inverse: sel,
982
+ wrap: "truncate",
983
+ children: [
984
+ sel ? "▸ " : " ",
985
+ row.label.padEnd(14),
986
+ /* @__PURE__ */ jsx(Text, {
987
+ bold: true,
988
+ children: row.value
989
+ })
990
+ ]
991
+ }, row.key);
992
+ }),
993
+ /* @__PURE__ */ jsx(Text, { children: " " }),
994
+ /* @__PURE__ */ jsx(Text, {
995
+ color: "gray",
996
+ wrap: "truncate",
997
+ children: "←→ change · ↑↓ move · ⏎/p/esc done"
998
+ })
999
+ ]
1000
+ });
1289
1001
  const loraMode = s.mode === "overlay-loras";
1290
- const showLatent = !loraMode && s.exec.running && (pv.latentAnsi != null || pv.latentBytes != null);
1291
- const label = loraMode ? `lora ${s.loras.previewName ?? "lora"}` : showLatent ? "latent" : "output";
1292
- const placeholder = loraMode ? s.loras.previewNote ?? "(pick a lora)" : "(no image yet)";
1293
- const content = pv.useNative ? null : loraMode ? s.loras.previewAnsi : showLatent ? pv.latentAnsi : pv.outputAnsi;
1294
- const reserveRect = pv.useNative && pv.protocolImage != null;
1002
+ const wantLatent = s.exec.running && pv.duringRun !== "last-output";
1003
+ const showLatent = !loraMode && wantLatent && (pv.latentAnsi != null || pv.latentBytes != null);
1004
+ const label = loraMode ? `lora ${s.loras.previewName ?? "lora"}` : showLatent ? pv.duringRun === "latent-small" ? "latent small" : "latent" : "output";
1005
+ const placeholder = loraMode ? s.loras.previewNote ?? "(pick a lora)" : pv.latentsMissing ? "(no latents from the server — launch comfy with --preview-method auto)" : "(no image yet)";
1006
+ const content = pv.useNative ? null : loraMode ? s.loras.previewAnsi : showLatent ? pv.latentAnsi ?? pv.outputAnsi : pv.outputAnsi;
1007
+ const reserveRect = pv.useNative && (pv.protocolImage != null || pv.protocolImageCorner != null);
1295
1008
  return /* @__PURE__ */ jsxs(Box, {
1296
1009
  borderStyle: "round",
1297
1010
  paddingX: 1,
@@ -1303,7 +1016,16 @@ const PreviewPanel = observer((p) => {
1303
1016
  children: /* @__PURE__ */ jsxs(Text, {
1304
1017
  color: "gray",
1305
1018
  wrap: "truncate",
1306
- children: ["(p)review · ", label]
1019
+ children: [
1020
+ "(p)review · ",
1021
+ label,
1022
+ " · ",
1023
+ pv.renderer,
1024
+ pv.latentsMissing ? /* @__PURE__ */ jsx(Text, {
1025
+ color: "red",
1026
+ children: " · no latents!"
1027
+ }) : null
1028
+ ]
1307
1029
  })
1308
1030
  }), reserveRect ? Array.from({ length: pv.height }, (_, ix) => /* @__PURE__ */ jsx(Text, { children: " " }, ix)) : content != null ? /* @__PURE__ */ jsx(Text, { children: content }) : /* @__PURE__ */ jsx(Text, {
1309
1031
  color: "gray",
@@ -1359,6 +1081,32 @@ const PromptOverlay = observer((p) => {
1359
1081
  });
1360
1082
  });
1361
1083
  //#endregion
1084
+ //#region src/cli/tui/components/LogsPanel.tsx
1085
+ const ERROR_RE = /error|exception|traceback|failed/i;
1086
+ /** last server console lines (LogsSt), below the vars panel */
1087
+ const LogsPanel = observer((p) => {
1088
+ const rows = p.st.logs.tail(p.st.termRows < 30 ? 4 : 8);
1089
+ if (rows.length === 0) return null;
1090
+ return /* @__PURE__ */ jsxs(Box, {
1091
+ borderStyle: "round",
1092
+ borderColor: "gray",
1093
+ paddingX: 1,
1094
+ flexDirection: "column",
1095
+ flexShrink: 0,
1096
+ children: [/* @__PURE__ */ jsx(Box, {
1097
+ marginTop: -1,
1098
+ children: /* @__PURE__ */ jsx(Text, {
1099
+ color: "gray",
1100
+ children: "comfy host logs"
1101
+ })
1102
+ }), rows.map((line, ix) => /* @__PURE__ */ jsx(Text, {
1103
+ color: ERROR_RE.test(line) ? "red" : "gray",
1104
+ wrap: "truncate-end",
1105
+ children: line
1106
+ }, ix))]
1107
+ });
1108
+ });
1109
+ //#endregion
1362
1110
  //#region src/cli/tui/components/TextOverlay.tsx
1363
1111
  /** modal multiline editor: real newlines, caret rendered per code point.
1364
1112
  * The cursor's LOGICAL line is background-highlighted (word wrap hides line
@@ -1482,15 +1230,22 @@ const TreePanel = observer((p) => {
1482
1230
  }),
1483
1231
  tree.rows.map((row, ix) => {
1484
1232
  const sel = focused && ix === tree.ix;
1233
+ if (row.kind === "section") return /* @__PURE__ */ jsxs(Text, {
1234
+ color: "gray",
1235
+ dimColor: true,
1236
+ wrap: "truncate",
1237
+ children: ["─ ", row.label]
1238
+ }, `section·${row.label}`);
1485
1239
  if (row.kind === "workflow") {
1486
1240
  const arrow = row.hasDrafts ? row.expanded ? "▾" : "▸" : " ";
1241
+ const marker = row.error != null ? "✗" : row.current ? "●" : " ";
1487
1242
  return /* @__PURE__ */ jsxs(Text, {
1488
1243
  inverse: sel,
1489
- color: row.current ? "green" : void 0,
1244
+ color: row.error != null ? "red" : row.current ? "green" : void 0,
1490
1245
  wrap: "truncate",
1491
1246
  children: [
1492
1247
  arrow,
1493
- row.current ? "●" : " ",
1248
+ marker,
1494
1249
  " ",
1495
1250
  row.name
1496
1251
  ]
@@ -1718,7 +1473,7 @@ const TuiApp = observer((p) => {
1718
1473
  if (input === "s") return s.exec.randomizeSeedAndRun();
1719
1474
  if (input === "d") return s.drafts.begin();
1720
1475
  if (input === "h") return s.host.begin();
1721
- if (input === "p") return s.settings.cyclePreviewMode();
1476
+ if (input === "p") return s.preview.beginMenu();
1722
1477
  if (input === "o") return s.exec.openLastOutput();
1723
1478
  if (input === "q") {
1724
1479
  s.onExit();
@@ -1738,6 +1493,24 @@ const TuiApp = observer((p) => {
1738
1493
  }
1739
1494
  return;
1740
1495
  }
1496
+ if (s.mode === "preview") {
1497
+ const pv = s.preview;
1498
+ if (key.escape || key.return || input === "p" || input === "v") return pv.blurMenu();
1499
+ if (key.upArrow) return pv.menuMove(-1);
1500
+ if (key.downArrow) return pv.menuMove(1);
1501
+ if (key.leftArrow) return pv.menuCycle(-1);
1502
+ if (key.rightArrow || input === " ") return pv.menuCycle(1);
1503
+ if (input === "r") return void s.exec.run();
1504
+ if (input === "s") return s.exec.randomizeSeedAndRun();
1505
+ if (input === "d") return s.drafts.begin();
1506
+ if (input === "h") return s.host.begin();
1507
+ if (input === "o") return s.exec.openLastOutput();
1508
+ if (input === "q") {
1509
+ s.onExit();
1510
+ return app.exit();
1511
+ }
1512
+ return;
1513
+ }
1741
1514
  if (s.mode === "overlay-drafts") {
1742
1515
  const d = s.drafts;
1743
1516
  if (key.escape) return s.editor.cancel();
@@ -1768,7 +1541,7 @@ const TuiApp = observer((p) => {
1768
1541
  if (input === "t" || input === "w") return s.tree.focus();
1769
1542
  if (input === "h") return s.host.begin();
1770
1543
  if (input === "d") return s.drafts.begin();
1771
- if (input === "p") return s.settings.cyclePreviewMode();
1544
+ if (input === "p") return s.preview.beginMenu();
1772
1545
  if (input === "o") return s.exec.openLastOutput();
1773
1546
  if (input === "c") return void s.exec.copyWorkflowJson();
1774
1547
  if (input === "C") return void s.exec.copyApiJson();
@@ -1808,10 +1581,11 @@ const TuiApp = observer((p) => {
1808
1581
  })
1809
1582
  ]
1810
1583
  }, o))
1811
- })
1584
+ }),
1585
+ !s.mode.startsWith("overlay-") && !(s.mode === "edit" && s.editor.isCustom) && /* @__PURE__ */ jsx(LogsPanel, { st: s })
1812
1586
  ]
1813
1587
  }),
1814
- s.preview.show && /* @__PURE__ */ jsx(PreviewPanel, { st: s })
1588
+ (s.preview.show || s.preview.menuOpen) && /* @__PURE__ */ jsx(PreviewPanel, { st: s })
1815
1589
  ]
1816
1590
  }),
1817
1591
  /* @__PURE__ */ jsx(KeyBar, { st: s })
@@ -2323,7 +2097,7 @@ var ExecSt = class {
2323
2097
  this.progress = null;
2324
2098
  this.notice = null;
2325
2099
  this.currentPromptId = null;
2326
- this.st.preview.reset();
2100
+ this.st.preview.clearLatent();
2327
2101
  host.onLatentPreview = (p) => void this.st.preview.renderLatent(p.bytes);
2328
2102
  }
2329
2103
  });
@@ -2432,10 +2206,34 @@ var ExecSt = class {
2432
2206
  };
2433
2207
  //#endregion
2434
2208
  //#region src/cli/tui/state/HostSt.ts
2209
+ const PROBE_EVERY_MS = 5e3;
2210
+ const PROBE_TIMEOUT_MS = 3e3;
2211
+ const SPIN_FRAMES = [
2212
+ "⠋",
2213
+ "⠙",
2214
+ "⠹",
2215
+ "⠸",
2216
+ "⠼",
2217
+ "⠴",
2218
+ "⠦",
2219
+ "⠧",
2220
+ "⠇",
2221
+ "⠏"
2222
+ ];
2435
2223
  /** host panel (`h`): stats about the connected host + maintenance actions */
2436
2224
  var HostSt = class {
2437
2225
  constructor(st) {
2438
2226
  this.st = st;
2227
+ this.status = "unknown";
2228
+ this.statusVia = null;
2229
+ this.probing = false;
2230
+ this.retryInS = 0;
2231
+ this.spinFrame = 0;
2232
+ this.disposed = false;
2233
+ this.probeGen = 0;
2234
+ this.loopTimer = null;
2235
+ this.spinTimer = null;
2236
+ this.countdownTimer = null;
2439
2237
  this.ix = 0;
2440
2238
  this.running = null;
2441
2239
  this.actions = [
@@ -2457,6 +2255,84 @@ var HostSt = class {
2457
2255
  }
2458
2256
  ];
2459
2257
  makeAutoObservable(this, { st: false });
2258
+ this.probeLoop();
2259
+ this.st.disposers.push(() => {
2260
+ this.disposed = true;
2261
+ if (this.loopTimer != null) clearTimeout(this.loopTimer);
2262
+ if (this.spinTimer != null) clearInterval(this.spinTimer);
2263
+ if (this.countdownTimer != null) clearInterval(this.countdownTimer);
2264
+ });
2265
+ this.st.disposers.push(reaction(() => this.st.wf, () => {
2266
+ runInAction(() => {
2267
+ this.status = "unknown";
2268
+ this.statusVia = null;
2269
+ });
2270
+ this.probeGen++;
2271
+ if (this.loopTimer != null) clearTimeout(this.loopTimer);
2272
+ if (this.countdownTimer != null) clearInterval(this.countdownTimer);
2273
+ this.probeLoop();
2274
+ }));
2275
+ }
2276
+ get spinner() {
2277
+ return SPIN_FRAMES[this.spinFrame % SPIN_FRAMES.length] ?? "⠋";
2278
+ }
2279
+ /** probe → schedule the next one (setTimeout chain: the countdown is exact) */
2280
+ async probeLoop() {
2281
+ const gen = this.probeGen;
2282
+ await this.probe();
2283
+ if (this.disposed || gen !== this.probeGen) return;
2284
+ const nextAt = Date.now() + PROBE_EVERY_MS;
2285
+ runInAction(() => {
2286
+ this.retryInS = Math.ceil(PROBE_EVERY_MS / 1e3);
2287
+ });
2288
+ if (this.countdownTimer != null) clearInterval(this.countdownTimer);
2289
+ this.countdownTimer = setInterval(() => {
2290
+ runInAction(() => {
2291
+ this.retryInS = Math.max(0, Math.ceil((nextAt - Date.now()) / 1e3));
2292
+ });
2293
+ }, 250);
2294
+ this.countdownTimer.unref?.();
2295
+ this.loopTimer = setTimeout(() => {
2296
+ if (this.countdownTimer != null) clearInterval(this.countdownTimer);
2297
+ this.probeLoop();
2298
+ }, PROBE_EVERY_MS);
2299
+ this.loopTimer.unref?.();
2300
+ }
2301
+ /** http is the ground truth: a half-open ws keeps isOpen=true forever, and
2302
+ * trusting it would re-create the exact silent-death this dot exists to expose */
2303
+ async probe() {
2304
+ const host = this.host;
2305
+ runInAction(() => {
2306
+ this.probing = true;
2307
+ });
2308
+ const spin = setInterval(() => {
2309
+ runInAction(() => {
2310
+ this.spinFrame++;
2311
+ });
2312
+ }, 120);
2313
+ spin.unref?.();
2314
+ this.spinTimer = spin;
2315
+ let ok = false;
2316
+ try {
2317
+ const res = await host.fetch("/prompt", { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
2318
+ res.body?.cancel();
2319
+ ok = res.ok;
2320
+ } catch {
2321
+ ok = false;
2322
+ } finally {
2323
+ clearInterval(spin);
2324
+ if (this.spinTimer === spin) {
2325
+ this.spinTimer = null;
2326
+ runInAction(() => {
2327
+ this.probing = false;
2328
+ });
2329
+ }
2330
+ }
2331
+ if (this.host !== host) return;
2332
+ runInAction(() => {
2333
+ this.status = ok ? "up" : "down";
2334
+ this.statusVia = ok ? host.isConnected ? "ws" : "http" : null;
2335
+ });
2460
2336
  }
2461
2337
  get host() {
2462
2338
  return this.st.wf.host;
@@ -2464,6 +2340,10 @@ var HostSt = class {
2464
2340
  get stats() {
2465
2341
  const schema = this.host.schema;
2466
2342
  return [
2343
+ {
2344
+ label: "status",
2345
+ value: this.status === "down" ? `down · ${this.probing ? `${this.spinner} probing…` : `retry in ${this.retryInS}s`}` : this.status + (this.statusVia != null ? ` (${this.statusVia})` : "")
2346
+ },
2467
2347
  {
2468
2348
  label: "node types",
2469
2349
  value: String(schema.nodes.length)
@@ -2549,6 +2429,154 @@ var HostSt = class {
2549
2429
  }
2550
2430
  };
2551
2431
  //#endregion
2432
+ //#region src/utils/mojibake.ts
2433
+ const CP1252_REVERSE = {
2434
+ "€": 128,
2435
+ "‚": 130,
2436
+ ƒ: 131,
2437
+ "„": 132,
2438
+ "…": 133,
2439
+ "†": 134,
2440
+ "‡": 135,
2441
+ ˆ: 136,
2442
+ "‰": 137,
2443
+ Š: 138,
2444
+ "‹": 139,
2445
+ Œ: 140,
2446
+ Ž: 142,
2447
+ "‘": 145,
2448
+ "’": 146,
2449
+ "“": 147,
2450
+ "”": 148,
2451
+ "•": 149,
2452
+ "–": 150,
2453
+ "—": 151,
2454
+ "˜": 152,
2455
+ "™": 153,
2456
+ š: 154,
2457
+ "›": 155,
2458
+ œ: 156,
2459
+ ž: 158,
2460
+ Ÿ: 159
2461
+ };
2462
+ /**
2463
+ * repair UTF-8 that was decoded as cp1252 (a Windows server re-reading its own
2464
+ * output: `█` E2 96 88 arrives as `â–ˆ`). Reverses the cp1252 map back to
2465
+ * bytes and re-decodes as UTF-8; any unmappable char or invalid byte sequence
2466
+ * means the text was NOT mojibake — the original is returned untouched.
2467
+ */
2468
+ function repairMojibake(s) {
2469
+ let suspicious = false;
2470
+ for (let i = 0; i < s.length; i++) if (s.charCodeAt(i) > 127) {
2471
+ suspicious = true;
2472
+ break;
2473
+ }
2474
+ if (!suspicious) return s;
2475
+ const bytes = new Uint8Array(s.length);
2476
+ for (let i = 0; i < s.length; i++) {
2477
+ const code = s.charCodeAt(i);
2478
+ if (code <= 255) {
2479
+ bytes[i] = code;
2480
+ continue;
2481
+ }
2482
+ const mapped = CP1252_REVERSE[s[i] ?? ""];
2483
+ if (mapped == null) return s;
2484
+ bytes[i] = mapped;
2485
+ }
2486
+ const decoded = Buffer.from(bytes).toString("utf8");
2487
+ return decoded.includes("�") ? s : decoded;
2488
+ }
2489
+ //#endregion
2490
+ //#region src/cli/tui/state/LogsSt.ts
2491
+ const MAX_LINES = 400;
2492
+ /** fold write chunks into p.lines (mutated), returns the new partial tail.
2493
+ * `\n` commits a line, `\r` resets the partial (tqdm redraws collapse to
2494
+ * their last state), ANSI stripped, blank lines dropped. */
2495
+ function assembleLogChunks(p) {
2496
+ let partial = p.partial;
2497
+ for (const entry of p.entries) for (const piece of stripAnsi(repairMojibake(entry.m)).split(/(\r\n|\n|\r)/)) if (piece === "\n" || piece === "\r\n") {
2498
+ if (partial.trim() !== "") p.lines.push(partial);
2499
+ partial = "";
2500
+ } else if (piece === "\r") partial = "";
2501
+ else if (piece !== "") partial += piece;
2502
+ return partial;
2503
+ }
2504
+ /** server console mirror: /internal/logs/raw backfill + ws 'logs' stream.
2505
+ * Entries are write CHUNKS, not lines — assembled here (`\n` commits,
2506
+ * `\r` resets the partial, so tqdm redraws collapse to their last state). */
2507
+ var LogsSt = class {
2508
+ constructor(st) {
2509
+ this.st = st;
2510
+ this.lines = [];
2511
+ this.partial = "";
2512
+ this.attached = null;
2513
+ makeAutoObservable(this, { st: false });
2514
+ this.attach(this.st.wf.host);
2515
+ this.st.disposers.push(() => {
2516
+ if (this.attached != null) {
2517
+ this.attached.onLogs = null;
2518
+ this.attached.onSession = null;
2519
+ }
2520
+ });
2521
+ }
2522
+ /** follow the CURRENT workflow's host (re-called on workflow switch) */
2523
+ attach(host) {
2524
+ if (this.attached === host) return;
2525
+ if (this.attached != null) {
2526
+ this.attached.onLogs = null;
2527
+ this.attached.onSession = null;
2528
+ if (this.attached.isConnected && this.attached.comfySessionId !== "temp") this.attached.subscribeLogs({
2529
+ enabled: false,
2530
+ clientId: this.attached.comfySessionId
2531
+ }).catch(() => {});
2532
+ }
2533
+ this.attached = host;
2534
+ this.lines = [];
2535
+ this.partial = "";
2536
+ host.onLogs = (p) => this.feed(p.entries);
2537
+ host.onSession = (sid) => void this.hydrate(host, sid);
2538
+ if (host.isConnected && host.comfySessionId !== "temp") this.hydrate(host, host.comfySessionId);
2539
+ }
2540
+ /** backfill BEFORE subscribe: entries emitted in the gap are lost, which is
2541
+ * the right trade — the reverse order would clobber streamed entries at the
2542
+ * reset, and the backfill re-covers the recent past anyway */
2543
+ async hydrate(host, sid) {
2544
+ try {
2545
+ const raw = await host.fetchRawLogs();
2546
+ if (this.attached !== host || host.comfySessionId !== sid) return;
2547
+ runInAction(() => {
2548
+ this.lines = [];
2549
+ this.partial = "";
2550
+ });
2551
+ this.feed(raw.entries);
2552
+ await host.subscribeLogs({
2553
+ enabled: true,
2554
+ clientId: sid
2555
+ });
2556
+ } catch (e) {
2557
+ if (this.attached !== host) return;
2558
+ this.feed([{
2559
+ t: "",
2560
+ m: `[comfy-ts] server log stream unavailable: ${extractErrorMessage(e)}\n`
2561
+ }]);
2562
+ }
2563
+ }
2564
+ feed(entries) {
2565
+ runInAction(() => {
2566
+ this.partial = assembleLogChunks({
2567
+ lines: this.lines,
2568
+ partial: this.partial,
2569
+ entries
2570
+ });
2571
+ if (this.lines.length > MAX_LINES) this.lines.splice(0, this.lines.length - MAX_LINES);
2572
+ });
2573
+ }
2574
+ /** last rows to render, live partial included */
2575
+ tail(n) {
2576
+ return (this.partial.trim() !== "" ? [...this.lines, this.partial] : this.lines).slice(-n);
2577
+ }
2578
+ };
2579
+ //#endregion
2552
2580
  //#region src/host/loraManagerApi.ts
2553
2581
  const lmLoraPage = type({
2554
2582
  items: type({
@@ -2567,13 +2595,12 @@ function loraPreviewKey(name) {
2567
2595
  * (server-relative). Returns null when the extension is absent (404/network).
2568
2596
  */
2569
2597
  async function fetchLoraPreviewMap(host) {
2570
- const base = host.getServerHostHTTP();
2571
2598
  const map = /* @__PURE__ */ new Map();
2572
2599
  const pageSize = 500;
2573
2600
  for (let page = 1; page <= 20; page++) {
2574
2601
  let res;
2575
2602
  try {
2576
- res = await fetch(`${base}/api/lm/loras/list?page=${page}&page_size=${pageSize}`);
2603
+ res = await host.fetch(`/api/lm/loras/list?page=${page}&page_size=${pageSize}`, {}, { apiPrefix: false });
2577
2604
  } catch {
2578
2605
  return null;
2579
2606
  }
@@ -2632,7 +2659,7 @@ async function fetchLoraPreviewBytes(host, previewUrl) {
2632
2659
  const cachePath = comfyts.resolveFromCache(`lora-previews/${createHash("sha1").update(previewUrl).digest("hex")}`);
2633
2660
  if (existsSync(cachePath)) return new Uint8Array(readFileSync(cachePath));
2634
2661
  try {
2635
- const res = await fetch(`${host.getServerHostHTTP()}${previewUrl}`);
2662
+ const res = await host.fetch(previewUrl, {}, { apiPrefix: false });
2636
2663
  if (!res.ok) return null;
2637
2664
  const ct = res.headers.get("content-type") ?? "";
2638
2665
  if (ct !== "" && !ct.startsWith("image/")) return null;
@@ -2958,35 +2985,37 @@ var QueueSt = class {
2958
2985
  };
2959
2986
  //#endregion
2960
2987
  //#region src/cli/tui/state/SettingsSt.ts
2988
+ /** read stored preview settings, migrating the legacy single `previewMode`
2989
+ * (native|ansi|off) into the three independent axes */
2990
+ function migratePreviewSettings(raw, defaults) {
2991
+ const out = { ...defaults };
2992
+ const legacy = raw.previewMode;
2993
+ if (legacy === "native") out.previewRenderer = "native";
2994
+ if (legacy === "ansi") out.previewRenderer = "pixel";
2995
+ if (legacy === "off") out.previewPanel = false;
2996
+ if (typeof raw.previewPanel === "boolean") out.previewPanel = raw.previewPanel;
2997
+ if (raw.previewRenderer === "native" || raw.previewRenderer === "pixel") out.previewRenderer = raw.previewRenderer;
2998
+ if (raw.previewDuringRun === "latent" || raw.previewDuringRun === "latent-small" || raw.previewDuringRun === "last-output") out.previewDuringRun = raw.previewDuringRun;
2999
+ return out;
3000
+ }
2961
3001
  /** persisted TUI settings at `.comfy-ts/settings.json` (LOCAL state, gitignored) */
2962
3002
  var SettingsSt = class {
2963
3003
  constructor(st) {
2964
3004
  this.st = st;
2965
- this.previewMode = protocolCapable() ? "native" : "ansi";
3005
+ this.previewPanel = true;
3006
+ this.previewRenderer = protocolCapable() ? "native" : "pixel";
3007
+ this.previewDuringRun = "latent";
2966
3008
  this.lastDraft = {};
2967
3009
  this.load();
2968
- if (this.previewMode === "native" && !protocolCapable()) this.previewMode = "ansi";
3010
+ if (this.previewRenderer === "native" && !protocolCapable()) this.previewRenderer = "pixel";
2969
3011
  makeAutoObservable(this, { st: false });
2970
3012
  this.st.disposers.push(reaction(() => JSON.stringify({
2971
- previewMode: this.previewMode,
3013
+ previewPanel: this.previewPanel,
3014
+ previewRenderer: this.previewRenderer,
3015
+ previewDuringRun: this.previewDuringRun,
2972
3016
  lastDraft: this.lastDraft
2973
3017
  }), (json) => this.write(json), { delay: 300 }));
2974
3018
  }
2975
- setPreviewMode(mode) {
2976
- this.previewMode = mode;
2977
- this.st.preview.onModeChanged();
2978
- }
2979
- /** `p` cycles native → ansi → off (native skipped when the terminal can't do it) */
2980
- cyclePreviewMode() {
2981
- const order = protocolCapable() ? [
2982
- "native",
2983
- "ansi",
2984
- "off"
2985
- ] : ["ansi", "off"];
2986
- const next = order[(order.indexOf(this.previewMode) + 1) % order.length] ?? "off";
2987
- this.setPreviewMode(next);
2988
- this.st.exec.notice = `preview: ${next}`;
2989
- }
2990
3019
  rememberDraft(moduleKey, draft) {
2991
3020
  this.lastDraft[moduleKey] = draft;
2992
3021
  }
@@ -2997,7 +3026,14 @@ var SettingsSt = class {
2997
3026
  const raw = JSON.parse(readFileSync(path, "utf8"));
2998
3027
  if (raw == null || typeof raw !== "object") return;
2999
3028
  const o = raw;
3000
- if (o.previewMode === "native" || o.previewMode === "ansi" || o.previewMode === "off") this.previewMode = o.previewMode;
3029
+ const preview = migratePreviewSettings(o, {
3030
+ previewPanel: this.previewPanel,
3031
+ previewRenderer: this.previewRenderer,
3032
+ previewDuringRun: this.previewDuringRun
3033
+ });
3034
+ this.previewPanel = preview.previewPanel;
3035
+ this.previewRenderer = preview.previewRenderer;
3036
+ this.previewDuringRun = preview.previewDuringRun;
3001
3037
  if (o.lastDraft != null && typeof o.lastDraft === "object") this.lastDraft = { ...o.lastDraft };
3002
3038
  } catch {}
3003
3039
  }
@@ -3027,7 +3063,15 @@ var TreeSt = class {
3027
3063
  this.st.drafts.version;
3028
3064
  const w = this.st.workflows;
3029
3065
  const rows = [];
3066
+ let sectionPushed = false;
3030
3067
  for (const file of w.files) {
3068
+ if (!sectionPushed && w.bundled.has(file)) {
3069
+ rows.push({
3070
+ kind: "section",
3071
+ label: "comfy-ts examples"
3072
+ });
3073
+ sectionPushed = true;
3074
+ }
3031
3075
  const current = file === w.currentPath;
3032
3076
  const expanded = this.expandedFiles.has(file);
3033
3077
  const drafts = listDraftsForFile(file);
@@ -3037,7 +3081,8 @@ var TreeSt = class {
3037
3081
  name: draftKeyForFile(file),
3038
3082
  expanded,
3039
3083
  current,
3040
- hasDrafts: drafts.length > 0
3084
+ hasDrafts: drafts.length > 0,
3085
+ error: w.loadErrors.get(file) ?? null
3041
3086
  });
3042
3087
  if (!expanded) continue;
3043
3088
  for (const draft of drafts) rows.push({
@@ -3071,22 +3116,28 @@ var TreeSt = class {
3071
3116
  this.st.mode = "nav";
3072
3117
  }
3073
3118
  move(delta) {
3074
- const len = this.rows.length;
3119
+ const rows = this.rows;
3120
+ const len = rows.length;
3075
3121
  if (len === 0) return;
3076
- this.ix = (this.ix + delta + len) % len;
3122
+ let ix = this.ix;
3123
+ for (let step = 0; step < len; step++) {
3124
+ ix = (ix + delta + len) % len;
3125
+ if (rows[ix]?.kind !== "section") break;
3126
+ }
3127
+ this.ix = ix;
3077
3128
  }
3078
3129
  /** →: unfold the workflow under the cursor; on a draft row there is nothing
3079
3130
  * left to unfold, so → continues rightwards into the vars panel */
3080
3131
  unfold() {
3081
3132
  const row = this.selected;
3082
- if (row == null) return;
3133
+ if (row == null || row.kind === "section") return;
3083
3134
  if (row.kind === "workflow") this.expandedFiles.add(row.file);
3084
3135
  else this.blur();
3085
3136
  }
3086
3137
  /** ←: fold the workflow under the cursor; on a draft row, jump to (and fold) its parent */
3087
3138
  fold() {
3088
3139
  const row = this.selected;
3089
- if (row == null) return;
3140
+ if (row == null || row.kind === "section") return;
3090
3141
  this.expandedFiles.delete(row.file);
3091
3142
  if (row.kind === "draft") {
3092
3143
  const ix = this.rows.findIndex((r) => r.kind === "workflow" && r.file === row.file);
@@ -3096,13 +3147,14 @@ var TreeSt = class {
3096
3147
  /** ⏎: load the workflow (into 'default'), or the exact draft under the cursor */
3097
3148
  async commit() {
3098
3149
  const row = this.selected;
3099
- if (row == null) return;
3150
+ if (row == null || row.kind === "section") return;
3100
3151
  if (row.kind === "workflow") return this.st.workflows.commit(row.file);
3101
3152
  return this.st.workflows.commit(row.file, row.draft);
3102
3153
  }
3103
3154
  /** n: new draft — current workflow only (a draft snapshots its LIVE var values) */
3104
3155
  promptNewDraft() {
3105
3156
  const row = this.selected;
3157
+ if (row?.kind === "section") return;
3106
3158
  if (row != null && row.file !== this.st.workflows.currentPath) {
3107
3159
  this.st.exec.notice = "load that workflow first (⏎) — a new draft snapshots its live vars";
3108
3160
  return;
@@ -3126,12 +3178,14 @@ var TreeSt = class {
3126
3178
  //#region src/cli/tui/state/WorkflowsSt.ts
3127
3179
  /** workflow-module data layer: scanned files, module loading, opened-host set (TreeSt is the UI over it) */
3128
3180
  var WorkflowsSt = class {
3129
- constructor(st, files, currentPath = null) {
3181
+ constructor(st, files, currentPath = null, bundled = /* @__PURE__ */ new Set(), loadErrors = /* @__PURE__ */ new Map()) {
3130
3182
  this.st = st;
3131
3183
  this.files = files;
3132
3184
  this.loading = false;
3133
3185
  this.loadedHosts = /* @__PURE__ */ new Set();
3134
3186
  this.currentPath = currentPath;
3187
+ this.bundled = bundled;
3188
+ this.loadErrors = loadErrors;
3135
3189
  makeAutoObservable(this, { st: false });
3136
3190
  }
3137
3191
  disconnectAllHosts() {
@@ -3165,10 +3219,12 @@ var WorkflowsSt = class {
3165
3219
  const wf = findDefinedWorkflow(await import(pathToFileURL(resolve(path)).href + (bustCache ? `?v=${Date.now()}` : "")));
3166
3220
  if (wf == null) throw new Error(`${path} exports no DefinedWorkflow`);
3167
3221
  runInAction(() => {
3222
+ this.loadErrors.delete(path);
3168
3223
  this.loadedHosts.add(this.st.wf.host);
3169
3224
  this.loadedHosts.add(wf.host);
3170
3225
  this.st.wf = wf;
3171
3226
  this.st.queue.attach(wf.host);
3227
+ this.st.logs.attach(wf.host);
3172
3228
  this.currentPath = path;
3173
3229
  this.st.selIx = 0;
3174
3230
  this.st.mode = "nav";
@@ -3179,8 +3235,10 @@ var WorkflowsSt = class {
3179
3235
  });
3180
3236
  } catch (e) {
3181
3237
  runInAction(() => {
3238
+ const msg = extractErrorMessage(e);
3239
+ this.loadErrors.set(path, msg);
3182
3240
  this.st.mode = "nav";
3183
- this.st.exec.error = extractErrorMessage(e);
3241
+ this.st.exec.error = msg;
3184
3242
  });
3185
3243
  } finally {
3186
3244
  runInAction(() => {
@@ -3217,19 +3275,21 @@ var TuiSt = class {
3217
3275
  preview: false,
3218
3276
  host: false,
3219
3277
  queue: false,
3278
+ logs: false,
3220
3279
  settings: false
3221
3280
  });
3222
3281
  this.settings = new SettingsSt(this);
3223
3282
  this.editor = new EditorSt(this);
3224
3283
  this.picker = new PickerSt(this);
3225
3284
  this.loras = new LorasSt(this);
3226
- this.workflows = new WorkflowsSt(this, opts.workflowFiles ?? [], opts.currentFile ?? null);
3285
+ this.workflows = new WorkflowsSt(this, opts.workflowFiles ?? [], opts.currentFile ?? null, opts.bundledFiles, opts.loadErrors);
3227
3286
  this.tree = new TreeSt(this);
3228
3287
  this.drafts = new DraftsSt(this);
3229
3288
  this.exec = new ExecSt(this);
3230
3289
  this.preview = new PreviewSt(this);
3231
3290
  this.host = new HostSt(this);
3232
3291
  this.queue = new QueueSt(this);
3292
+ this.logs = new LogsSt(this);
3233
3293
  this.drafts.activateRemembered();
3234
3294
  if (opts.currentFile != null) this.tree.expandedFiles.add(opts.currentFile);
3235
3295
  const onResize = () => {
@@ -3251,7 +3311,7 @@ var TuiSt = class {
3251
3311
  }
3252
3312
  /** left tree panel width: longest row (workflow or indented draft), clamped */
3253
3313
  get treeWidth() {
3254
- const longest = Math.max(8, ...this.tree.rows.map((r) => r.kind === "workflow" ? r.name.length : r.draft.length + 3));
3314
+ const longest = Math.max(8, ...this.tree.rows.map((r) => r.kind === "workflow" ? r.name.length : r.kind === "draft" ? r.draft.length + 3 : r.label.length));
3255
3315
  return Math.min(32, longest + 7);
3256
3316
  }
3257
3317
  get entries() {
@@ -3294,31 +3354,50 @@ var TuiSt = class {
3294
3354
  };
3295
3355
  //#endregion
3296
3356
  //#region src/cli/tui/run-tui.tsx
3297
- /** recursive scan for the workflow-module naming convention */
3298
- function scanCflowFiles(dir) {
3299
- return readdirSync(dir, { recursive: true }).map((f) => join(dir, String(f))).filter((f) => f.endsWith(".cflow.ts") || f.endsWith(".cflow.tsx")).sort();
3300
- }
3301
3357
  async function runTui(args) {
3302
- const target = args.find((a) => !a.startsWith("--")) ?? ".";
3358
+ const target = args.find((a) => !a.startsWith("--"));
3303
3359
  process.env[COMFY_TS_TUI_ENV] = "1";
3304
3360
  process.env.COMFY_TS_QUIET = "1";
3305
- const abs = resolve(target);
3361
+ const abs = realpathSync(resolve(target ?? "."));
3306
3362
  const isDir = statSync(abs).isDirectory();
3307
3363
  const scanned = scanCflowFiles(isDir ? abs : dirname(abs));
3308
- const workflowFiles = isDir || scanned.includes(abs) ? scanned : [abs, ...scanned];
3309
- const first = isDir ? workflowFiles[0] : abs;
3310
- if (first == null) {
3364
+ const scannedPlusArg = isDir || scanned.includes(abs) ? scanned : [abs, ...scanned];
3365
+ const canImportBundled = process.versions.bun != null;
3366
+ const examplesDir = canImportBundled ? bundledExamplesDir() : null;
3367
+ if (!canImportBundled && target == null) logError("packaged examples skipped: importing .cflow.ts from node_modules needs bun (bunx --bun comfy-ts tui)");
3368
+ const discovery = mergeWorkflowSources({
3369
+ explicitTarget: target != null,
3370
+ scanned: scannedPlusArg,
3371
+ bundledFiles: examplesDir == null ? [] : scanCflowFiles(realpathSync(examplesDir))
3372
+ });
3373
+ const workflowFiles = discovery.files;
3374
+ if (workflowFiles.length === 0) {
3311
3375
  console.error(`[comfy-ts tui] no **/*.cflow.ts found under ${abs}`);
3312
3376
  return 1;
3313
3377
  }
3314
- const wf = findDefinedWorkflow(await import(pathToFileURL(first).href));
3315
- if (wf == null) {
3316
- console.error(`[comfy-ts tui] ${first} exports no DefinedWorkflow — export the result of host.defineWorkflow(...)`);
3378
+ const candidates = !isDir && workflowFiles.includes(abs) ? [abs, ...workflowFiles.filter((f) => f !== abs)] : workflowFiles;
3379
+ const loadErrors = /* @__PURE__ */ new Map();
3380
+ let first = null;
3381
+ let wf = null;
3382
+ for (const file of candidates) try {
3383
+ const found = findDefinedWorkflow(await import(pathToFileURL(file).href));
3384
+ if (found == null) throw new Error(`${file} exports no DefinedWorkflow — export the result of host.defineWorkflow(...)`);
3385
+ first = file;
3386
+ wf = found;
3387
+ break;
3388
+ } catch (e) {
3389
+ loadErrors.set(file, extractErrorMessage(e));
3390
+ }
3391
+ if (first == null || wf == null) {
3392
+ console.error(`[comfy-ts tui] no loadable workflow module among ${candidates.length} file(s):`);
3393
+ for (const [file, err] of loadErrors) console.error(` ${file}: ${err}`);
3317
3394
  return 1;
3318
3395
  }
3319
3396
  const st = new TuiSt(wf, {
3320
3397
  workflowFiles,
3321
- currentFile: first
3398
+ currentFile: first,
3399
+ bundledFiles: discovery.bundled,
3400
+ loadErrors
3322
3401
  });
3323
3402
  const altScreen = process.stdout.isTTY === true;
3324
3403
  if (altScreen) process.stdout.write("\x1B[?1049h\x1B[H\x1B[>4;1m");
@@ -3330,11 +3409,11 @@ async function runTui(args) {
3330
3409
  st.dispose();
3331
3410
  } finally {
3332
3411
  uninstallPainter();
3333
- if (altScreen) process.stdout.write("\x1B[>4;0m\x1B[?1049l");
3412
+ if (altScreen) process.stdout.write("\x1B[0m\x1B[2J\x1B[H\x1B[>4;0m\x1B[?1049l");
3334
3413
  }
3335
3414
  return 0;
3336
3415
  }
3337
3416
  //#endregion
3338
3417
  export { runTui };
3339
3418
 
3340
- //# sourceMappingURL=run-tui-Io8Xea0L.js.map
3419
+ //# sourceMappingURL=run-tui-BFhba_oG.js.map