comfy-ts 0.4.0 → 1.1.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 (158) hide show
  1. package/README.md +385 -255
  2. package/dist/DefinedWorkflow-BYyu5dK9.js +669 -0
  3. package/dist/DefinedWorkflow-BYyu5dK9.js.map +1 -0
  4. package/dist/cli.js +4106 -152
  5. package/dist/cli.js.map +1 -1
  6. package/dist/index.cjs +1560 -333
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +7826 -467
  9. package/dist/index.d.ts +7808 -449
  10. package/dist/index.js +1550 -333
  11. package/dist/index.js.map +1 -1
  12. package/dist/{run-tui-SDSJo1Qf.js → run-tui-DZ22HDHI.js} +631 -657
  13. package/dist/run-tui-DZ22HDHI.js.map +1 -0
  14. package/examples/01-txt2img.cflow.ts +50 -0
  15. package/examples/02-img2img-upload.cflow.ts +55 -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 +51 -0
  19. package/examples/README.md +30 -0
  20. package/examples/comfy-cloud/ace-step-t2a.cflow.ts +79 -0
  21. package/examples/comfy-cloud/anima-t2i.cflow.ts +57 -0
  22. package/examples/comfy-cloud/boogu-i2i.cflow.ts +76 -0
  23. package/examples/comfy-cloud/capybara-i2i.cflow.ts +85 -0
  24. package/examples/comfy-cloud/capybara-i2v.cflow.ts +90 -0
  25. package/examples/comfy-cloud/capybara-t2i.cflow.ts +67 -0
  26. package/examples/comfy-cloud/chatterbox-t2a.cflow.ts +79 -0
  27. package/examples/comfy-cloud/chroma-t2i.cflow.ts +62 -0
  28. package/examples/comfy-cloud/cloudHost.ts +41 -0
  29. package/examples/comfy-cloud/ernie-t2i.cflow.ts +59 -0
  30. package/examples/comfy-cloud/firered-i2i.cflow.ts +74 -0
  31. package/examples/comfy-cloud/flux1-i2i.cflow.ts +76 -0
  32. package/examples/comfy-cloud/flux1-t2i.cflow.ts +63 -0
  33. package/examples/comfy-cloud/flux2-i2i.cflow.ts +80 -0
  34. package/examples/comfy-cloud/flux2-t2i.cflow.ts +57 -0
  35. package/examples/comfy-cloud/hidream-i2i.cflow.ts +89 -0
  36. package/examples/comfy-cloud/hidream-t2i.cflow.ts +65 -0
  37. package/examples/comfy-cloud/hunyuan-video-i2v.cflow.ts +93 -0
  38. package/examples/comfy-cloud/hunyuan-video-t2v.cflow.ts +74 -0
  39. package/examples/comfy-cloud/ideogram4-t2i.cflow.ts +80 -0
  40. package/examples/comfy-cloud/kandinsky5-i2v.cflow.ts +95 -0
  41. package/examples/comfy-cloud/kandinsky5-t2i.cflow.ts +60 -0
  42. package/examples/comfy-cloud/kandinsky5-t2v.cflow.ts +78 -0
  43. package/examples/comfy-cloud/krea2-t2i.cflow.ts +59 -0
  44. package/examples/comfy-cloud/lens-t2i.cflow.ts +62 -0
  45. package/examples/comfy-cloud/longcat-i2i.cflow.ts +74 -0
  46. package/examples/comfy-cloud/longcat-t2i.cflow.ts +65 -0
  47. package/examples/comfy-cloud/ltxv-i2v.cflow.ts +92 -0
  48. package/examples/comfy-cloud/ltxv-t2v.cflow.ts +78 -0
  49. package/examples/comfy-cloud/newbie-t2i.cflow.ts +67 -0
  50. package/examples/comfy-cloud/omnigen2-i2i.cflow.ts +86 -0
  51. package/examples/comfy-cloud/omnigen2-t2i.cflow.ts +62 -0
  52. package/examples/comfy-cloud/ovis-t2i.cflow.ts +56 -0
  53. package/examples/comfy-cloud/pixeldit-t2i.cflow.ts +63 -0
  54. package/examples/comfy-cloud/qwen-image-i2i.cflow.ts +69 -0
  55. package/examples/comfy-cloud/qwen-image-t2i.cflow.ts +55 -0
  56. package/examples/comfy-cloud/sd35-t2i.cflow.ts +48 -0
  57. package/examples/comfy-cloud/sdk.d.ts +123062 -0
  58. package/examples/comfy-cloud/sdxl-t2i.cflow.ts +69 -0
  59. package/examples/comfy-cloud/stable-audio-t2a.cflow.ts +53 -0
  60. package/examples/comfy-cloud/svd-i2v.cflow.ts +75 -0
  61. package/examples/comfy-cloud/wan21-i2v.cflow.ts +83 -0
  62. package/examples/comfy-cloud/wan21-t2v.cflow.ts +64 -0
  63. package/examples/comfy-cloud/wan22-5b-t2v.cflow.ts +69 -0
  64. package/examples/comfy-cloud/wan22-i2v.cflow.ts +107 -0
  65. package/examples/comfy-cloud/wan22-t2v.cflow.ts +98 -0
  66. package/examples/comfy-cloud/z-image-t2i.cflow.ts +62 -0
  67. package/examples/images/README.md +18 -0
  68. package/examples/images/bear_1024x1024.jpg +0 -0
  69. package/examples/images/deer_768x1344.jpg +0 -0
  70. package/examples/images/dog_512x512.jpg +0 -0
  71. package/examples/images/lioness_768x768.jpg +0 -0
  72. package/examples/images/pug_200x300.jpg +0 -0
  73. package/examples/images/walrus_1344x768.jpg +0 -0
  74. package/guide-for-agents.md +172 -0
  75. package/package.json +20 -4
  76. package/src/cli/comfy-ts-cli.ts +19 -2
  77. package/src/cli/gen.ts +21 -12
  78. package/src/cli/tui/components/PreviewPanel.tsx +9 -8
  79. package/src/cli/tui/components/StatusBar.tsx +11 -0
  80. package/src/cli/tui/components/TreePanel.tsx +15 -2
  81. package/src/cli/tui/components/TuiApp.tsx +18 -0
  82. package/src/cli/tui/discoverWorkflows.ts +45 -0
  83. package/src/cli/tui/imagePicker/ImagePickerOverlay.tsx +72 -0
  84. package/src/cli/tui/imagePicker/ImagePickerSt.ts +288 -0
  85. package/src/cli/tui/imagePicker/fsListing.ts +46 -0
  86. package/src/cli/tui/imagePicker/pickerPrefs.ts +78 -0
  87. package/src/cli/tui/run-tui.tsx +52 -23
  88. package/src/cli/tui/state/HostSt.ts +2 -3
  89. package/src/cli/tui/state/LorasSt.ts +14 -36
  90. package/src/cli/tui/state/PreviewSt.ts +28 -2
  91. package/src/cli/tui/state/TreeSt.ts +30 -6
  92. package/src/cli/tui/state/TuiSt.ts +27 -3
  93. package/src/cli/tui/state/WorkflowsSt.ts +15 -1
  94. package/src/exampleAssets.ts +56 -0
  95. package/src/graph/ComfyNode.ts +4 -1
  96. package/src/host/ComfyHost.ts +203 -77
  97. package/src/host/ComfyManager.ts +10 -9
  98. package/src/host/ComfyUploader.ts +1 -2
  99. package/src/host/ResilientWebsocket.ts +3 -1
  100. package/src/host/hostUrl.ts +59 -0
  101. package/src/host/loraManagerApi.ts +5 -4
  102. package/src/index.ts +27 -1
  103. package/src/litegraph/CanonicalWorkflow.ts +77 -0
  104. package/src/litegraph/LiteGraphGroup.ts +9 -7
  105. package/src/litegraph/LiteGraphJSON.ts +34 -13
  106. package/src/litegraph/LiteGraphLink.ts +32 -2
  107. package/src/litegraph/LiteGraphNode.ts +18 -33
  108. package/src/litegraph/LiteGraphNodeInput.ts +10 -8
  109. package/src/litegraph/LiteGraphNodeOutput.ts +2 -3
  110. package/src/litegraph/LiteGraphSubgraphDef.ts +74 -0
  111. package/src/litegraph/convertFlowToLiteGraphJSON.ts +4 -4
  112. package/src/litegraph/expandSubgraphs.ts +352 -0
  113. package/src/litegraph/normalizeWorkflow.ts +141 -0
  114. package/src/manager/ComfyRegistry.ts +37 -9
  115. package/src/manager/generated/KnownComfyCustomNodeName.ts +23852 -1926
  116. package/src/manager/generated/KnownComfyPluginTitle.ts +6854 -236
  117. package/src/manager/generated/KnownComfyPluginURL.ts +3425 -111
  118. package/src/manager/generated/KnownModel_Base.ts +23 -7
  119. package/src/manager/generated/KnownModel_FileName.ts +421 -0
  120. package/src/manager/generated/KnownModel_Name.ts +421 -0
  121. package/src/manager/generated/KnownModel_SavePath.ts +34 -8
  122. package/src/manager/generated/KnownModel_Type.ts +18 -14
  123. package/src/manager/json/alter-list.json +221 -221
  124. package/src/manager/json/custom-node-list.json +61020 -21946
  125. package/src/manager/json/extension-node-map.json +81077 -31176
  126. package/src/manager/json/github-stats.json +29321 -12601
  127. package/src/manager/json/model-list.json +5935 -4997
  128. package/src/manager/loaders/parseReport.ts +55 -0
  129. package/src/manager/loaders/step1_downloadComfyManagerJSONs.ts +15 -49
  130. package/src/manager/loaders/step2_custom-node-list-loader.ts +38 -83
  131. package/src/manager/loaders/step3_extension-node-map-loader.ts +36 -142
  132. package/src/manager/loaders/step4_model-list-loader.ts +25 -36
  133. package/src/manager/loaders/step5_alter-list-loader.ts +29 -0
  134. package/src/manager/loaders/step6_github-stats-loader.ts +23 -0
  135. package/src/manager/script-update-manager.bun.ts +9 -1
  136. package/src/manager/types/ComfyManagerAlterInfo.ts +13 -0
  137. package/src/manager/types/ComfyManagerFileModelInfo.ts +7 -3
  138. package/src/manager/types/ComfyManagerFilePluginContent.ts +6 -9
  139. package/src/manager/types/ComfyManagerFilePluginList.ts +3 -3
  140. package/src/manager/types/ComfyManagerGithubStats.ts +9 -0
  141. package/src/manager/types/ComfyManagerPluginContentMetadata.ts +2 -3
  142. package/src/manager/types/ComfyManagerPluginInfo.ts +48 -34
  143. package/src/runner/ComfyExecution.ts +4 -5
  144. package/src/runner/ComfyWorkflow.ts +2 -2
  145. package/src/runner/wsBinaryFrame.ts +48 -0
  146. package/src/sdk-generator/ComfySchema.ts +14 -1
  147. package/src/sdk-generator/Primitives.ts +6 -24
  148. package/src/sdk-generator/comfy-api-json.ts +3 -1
  149. package/src/sdk-generator/comfyui-sdk-codegen.ts +15 -0
  150. package/src/sdk-generator/inputWidgetKind.ts +196 -0
  151. package/src/sdk-generator/litegraphToApiRequestPayload.ts +372 -96
  152. package/src/state.ts +13 -2
  153. package/src/vars/ComfyVars.ts +82 -2
  154. package/src/vars/DefinedWorkflow.ts +7 -2
  155. package/dist/log-CdfgILde.js +0 -10
  156. package/dist/log-CdfgILde.js.map +0 -1
  157. package/dist/run-tui-SDSJo1Qf.js.map +0 -1
  158. package/src/utils/tryExtracting.ts +0 -41
@@ -1,566 +1,84 @@
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-BYyu5dK9.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
9
  import { imageMeta } from "image-meta";
10
+ import { homedir } from "node:os";
11
+ import { makeAutoObservable, observable, reaction, runInAction } from "mobx";
12
+ import { Box, Text, render, useApp, useInput, useStdin } from "ink";
10
13
  import { observer } from "mobx-react-lite";
11
14
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
12
- import { spawn } from "node:child_process";
13
- import { type } from "arktype";
14
15
  //#region src/cli/tui-env.ts
15
16
  const COMFY_TS_TUI_ENV = "COMFY_TS_TUI";
16
17
  //#endregion
17
- //#region src/vars/loraKeywords.ts
18
+ //#region src/cli/tui/discoverWorkflows.ts
18
19
  /**
19
- * hand-assigned trigger keyword(s) per lora name — set via ⌃K in the TUI loras
20
- * overlay, consumed by PromptVar's `loraKeywordsFrom` prefixing. Persisted at
21
- * `.comfy-ts/lora-keywords.json` (NOT under cache/: this is hand-entered data
22
- * and must survive a cache wipe). Observable map: overlay rows re-render on
23
- * assignment. Keys are the RAW lora names (folder/file.safetensors).
20
+ * recursive scan for the workflow-module naming convention. Entries BELOW a
21
+ * node_modules segment are skipped: packaged examples arrive via
22
+ * bundledExamplesDir (src/exampleAssets.ts — symlinked layouts like pnpm would
23
+ * otherwise list them twice, un-deduped, as the user's own files), and
24
+ * third-party packages shipping *.cflow.ts are not this project's workflows. A
25
+ * scan root that is ITSELF inside node_modules still works (the filter is
26
+ * relative to the root).
24
27
  */
25
- const keywords = observable.map();
26
- let loaded = false;
27
- function filePath() {
28
- return join(comfyts.baseFolder, "lora-keywords.json");
29
- }
30
- function loadOnce() {
31
- if (loaded) return;
32
- loaded = true;
33
- const path = filePath();
34
- if (!existsSync(path)) return;
35
- try {
36
- const raw = JSON.parse(readFileSync(path, "utf8"));
37
- if (raw == null || typeof raw !== "object") return;
38
- runInAction(() => {
39
- for (const [name, kw] of Object.entries(raw)) if (typeof kw === "string") keywords.set(name, kw);
40
- });
41
- } catch (e) {
42
- logError(`[loraKeywords] unreadable ${path}: ${String(e)}`);
43
- }
44
- }
45
- function getLoraKeyword(name) {
46
- loadOnce();
47
- return keywords.get(name) ?? "";
48
- }
49
- /** empty keyword deletes the entry; every set writes the file (tiny, rare) */
50
- function setLoraKeyword(name, keyword) {
51
- loadOnce();
52
- const trimmed = keyword.trim();
53
- runInAction(() => {
54
- if (trimmed === "") keywords.delete(name);
55
- else keywords.set(name, trimmed);
56
- });
57
- const path = filePath();
58
- try {
59
- mkdirSync(dirname(path), { recursive: true });
60
- writeFileSync(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2));
61
- } catch (e) {
62
- logError(`[loraKeywords] write failed ${path}: ${String(e)}`);
63
- }
28
+ function scanCflowFiles(dir) {
29
+ 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();
64
30
  }
65
- //#endregion
66
- //#region src/vars/ComfyVars.ts
67
31
  /**
68
- * full base: T is what's STORED/edited, Out what the GRAPH consumes at build
69
- * time. They usually coincide — extend `ComfyVar<T>` for that. PromptVar is
70
- * the one Out-specialized var (string in, PromptValue out); the split keeps
71
- * outValue() cast-free.
32
+ * PURE merge of the scan with the packaged examples (headless-tested). An
33
+ * explicit target keeps its scope only. Bundled files ALWAYS group under the
34
+ * bundled section, also when the scan already found them (repo dev: ./examples
35
+ * is under cwd) — dedupe relies on the caller passing realpath-normalized
36
+ * strings on both sides.
72
37
  */
73
- var ComfyVarBase = class {
74
- constructor(defaultValue, label) {
75
- this.defaultValue = defaultValue;
76
- this.label = label;
77
- this.value = defaultValue;
78
- makeObservable(this, {
79
- value: observable,
80
- set: action,
81
- reset: action,
82
- parse: action,
83
- loadJSON: action
84
- });
85
- }
86
- set(value) {
87
- this.value = value;
88
- return this;
89
- }
90
- /** what drafts persist for this var (subclasses may add fields, e.g. seed mode) */
91
- toJSON() {
92
- return this.value;
93
- }
94
- /**
95
- * restore a value produced by toJSON() (drafts). The cast is sanctioned:
96
- * drafts are our own round-trip, subclasses re-validate via set().
97
- */
98
- loadJSON(value) {
99
- return this.set(value);
100
- }
101
- reset() {
102
- this.value = this.defaultValue;
103
- return this;
104
- }
105
- /** how the value renders in a var list */
106
- display() {
107
- return String(this.value);
108
- }
109
- /** the string the inline editor starts from (round-trips through parse) */
110
- toEditBuffer() {
111
- return String(this.value);
112
- }
113
- /** hook run after every DefinedWorkflow.run() (default no-op; SeedVar advances) */
114
- afterRun() {}
115
- };
116
- /** the standard var: the graph consumes the stored value AS-IS (Out = T) */
117
- var ComfyVar = class extends ComfyVarBase {
118
- outValue() {
119
- return this.value;
120
- }
121
- };
122
- var TextVar = class extends ComfyVar {
123
- constructor(..._args) {
124
- super(..._args);
125
- this.kind = "text";
126
- }
127
- parse(raw) {
128
- this.set(raw);
129
- return true;
130
- }
131
- };
132
- const commentLineRe = /^\s*\/\//;
133
- const negativeLineRe = /^\s*- (.*)$/;
134
- /**
135
- * prompt text with editor comforts, all resolved at BUILD time (the editor and
136
- * drafts keep the raw text):
137
- * - `//` lines are COMMENTS — stripped
138
- * - `- ` lines are NEGATIVE prompt lines — removed from `.positive`,
139
- * comma-joined into `.negative`
140
- * - with `loraKeywordsFrom`, the ACTIVE loras' hand-assigned keywords
141
- * (src/vars/loraKeywords.ts, ⌃K in the TUI) prefix `.positive` —
142
- * `injectedKeywords()` is public so the TUI can PREVIEW the injection.
143
- */
144
- var PromptVar = class extends ComfyVarBase {
145
- constructor(defaultValue, promptOpts = {}) {
146
- super(defaultValue, promptOpts.label);
147
- this.promptOpts = promptOpts;
148
- this.kind = "text";
149
- }
150
- parse(raw) {
151
- this.set(raw);
152
- return true;
153
- }
154
- static isCommentLine(line) {
155
- return commentLineRe.test(line);
156
- }
157
- static isNegativeLine(line) {
158
- return negativeLineRe.test(line);
159
- }
160
- /** the keyword prefix the flag will inject (deduped, lora-list order) — the TUI previews this */
161
- injectedKeywords() {
162
- const src = this.promptOpts.loraKeywordsFrom;
163
- if (src == null) return [];
164
- return [...new Set(src.activeNames().map(getLoraKeyword).filter((k) => k !== ""))];
165
- }
166
- outValue() {
167
- const pos = [];
168
- const neg = [];
169
- for (const line of this.value.split("\n")) {
170
- if (commentLineRe.test(line)) continue;
171
- const m = negativeLineRe.exec(line);
172
- if (m != null) {
173
- const text = (m[1] ?? "").trim();
174
- if (text !== "") neg.push(text);
175
- } else pos.push(line);
176
- }
177
- const body = pos.join("\n").trim();
178
- const keywords = this.injectedKeywords();
179
- return {
180
- positive: keywords.length === 0 ? body : body === "" ? keywords.join(", ") : `${keywords.join(", ")}, ${body}`,
181
- negative: neg.join(", ")
182
- };
183
- }
184
- };
185
- var IntVar = class extends ComfyVar {
186
- constructor(defaultValue, opts = {}) {
187
- super(defaultValue, opts.label);
188
- this.opts = opts;
189
- this.kind = "int";
190
- }
191
- set(value) {
192
- const clamped = Math.round(Math.min(this.opts.max ?? Infinity, Math.max(this.opts.min ?? -Infinity, value)));
193
- return super.set(clamped);
194
- }
195
- parse(raw) {
196
- const n = Number(raw);
197
- if (Number.isNaN(n)) return false;
198
- this.set(n);
199
- return true;
200
- }
201
- };
202
- var FloatVar = class extends ComfyVar {
203
- constructor(defaultValue, opts = {}) {
204
- super(defaultValue, opts.label);
205
- this.opts = opts;
206
- this.kind = "float";
207
- }
208
- set(value) {
209
- return super.set(Math.min(this.opts.max ?? Infinity, Math.max(this.opts.min ?? -Infinity, value)));
210
- }
211
- parse(raw) {
212
- const n = Number(raw);
213
- if (Number.isNaN(n)) return false;
214
- this.set(n);
215
- return true;
216
- }
217
- };
218
- /**
219
- * a seed is a MODE + a number. `value` stays a plain number (what the graph
220
- * consumes); `mode` decides how it advances after each run (afterRun()):
221
- * `= 12` fixed · `+ 0` auto-increment · `- 0` auto-decrement · `? 0` random.
222
- * The number shown is always the seed the NEXT run will use.
223
- */
224
- var SeedVar = class extends ComfyVar {
225
- constructor(defaultValue = 0, label) {
226
- super(defaultValue, label);
227
- this.kind = "seed";
228
- this.mode = "=";
229
- makeObservable(this, {
230
- mode: observable,
231
- setMode: action,
232
- randomize: action,
233
- advance: action
234
- });
235
- }
236
- setMode(mode) {
237
- this.mode = mode;
238
- return this;
239
- }
240
- randomize() {
241
- return this.set(Math.floor(Math.random() * 2 ** 32));
242
- }
243
- set(value) {
244
- return super.set(Math.max(0, Math.floor(value)));
245
- }
246
- /** move the seed to what the NEXT run should use, per mode */
247
- advance() {
248
- if (this.mode === "+") return this.set(this.value + 1);
249
- if (this.mode === "-") return this.set(this.value - 1);
250
- if (this.mode === "?") return this.randomize();
251
- return this;
252
- }
253
- afterRun() {
254
- this.advance();
255
- }
256
- /** parse `+` `- 12` `= 5` `?` or a bare number (=> fixed). Keeps the current number when none given */
257
- parse(raw) {
258
- const m = raw.trim().match(/^([+\-=?])?\s*(\d+)?$/);
259
- if (m == null) return false;
260
- const modeChar = m[1];
261
- const numStr = m[2];
262
- if (modeChar == null && numStr == null) return false;
263
- this.setMode(modeChar == null ? "=" : modeChar);
264
- if (numStr != null) this.set(Number(numStr));
265
- return true;
266
- }
267
- display() {
268
- return `${this.mode} ${this.value}`;
269
- }
270
- toEditBuffer() {
271
- return `${this.mode} ${this.value}`;
272
- }
273
- toJSON() {
274
- return {
275
- mode: this.mode,
276
- value: this.value
277
- };
278
- }
279
- loadJSON(value) {
280
- if (typeof value === "number") return this.set(value);
281
- if (value != null && typeof value === "object") {
282
- const o = value;
283
- if (o.mode === "=" || o.mode === "+" || o.mode === "-" || o.mode === "?") this.setMode(o.mode);
284
- if (typeof o.value === "number") this.set(o.value);
285
- }
286
- return this;
287
- }
288
- };
289
- var ToggleVar = class extends ComfyVar {
290
- constructor(..._args2) {
291
- super(..._args2);
292
- this.kind = "toggle";
293
- }
294
- toggle() {
295
- return this.set(!this.value);
296
- }
297
- parse(raw) {
298
- if (raw !== "true" && raw !== "false") return false;
299
- this.set(raw === "true");
300
- return true;
301
- }
302
- display() {
303
- return this.value ? "ON" : "OFF";
304
- }
305
- };
306
- var ChoiceVar = class extends ComfyVar {
307
- constructor(choices, defaultValue, label) {
308
- super(defaultValue, label);
309
- this.choices = choices;
310
- this.kind = "choice";
311
- }
312
- next(delta = 1) {
313
- const nextIx = (this.choices.indexOf(this.value) + delta + this.choices.length) % this.choices.length;
314
- return this.set(this.choices[nextIx] ?? this.value);
315
- }
316
- parse(raw) {
317
- const hit = this.choices.find((c) => c === raw);
318
- if (hit == null) return false;
319
- this.set(hit);
320
- return true;
321
- }
322
- };
38
+ function mergeWorkflowSources(p) {
39
+ if (p.explicitTarget) return {
40
+ files: p.scanned,
41
+ bundled: /* @__PURE__ */ new Set()
42
+ };
43
+ const bundled = new Set(p.bundledFiles);
44
+ return {
45
+ files: [...p.scanned.filter((f) => !bundled.has(f)), ...p.bundledFiles],
46
+ bundled
47
+ };
48
+ }
49
+ //#endregion
50
+ //#region src/exampleAssets.ts
323
51
  /**
324
- * multi-select lora stack over a DYNAMIC options list — a RegExp resolves
325
- * against the host's loras at define time (DefinedWorkflow calls bindHost),
326
- * or feed it host discovery (`host.schema.getLoras(regex?)`) directly; never
327
- * a hardcoded inventory. Selection is empty by default.
52
+ * the examples/ folder shipped in the npm tarball, resolved from THIS module's
53
+ * own location (NEVER cwd): walking up to the nearest NAMED package.json finds
54
+ * <pkg>/examples both from a consumer's node_modules/comfy-ts/dist/ and from
55
+ * this repo's src/. Returns null when the examples are absent (a consumer may
56
+ * prune the folder) or when the nearest named package is not comfy-ts (the lib
57
+ * was inlined into someone else's bundle — its examples are not on disk); no
58
+ * package.json all the way up is a broken install and throws.
328
59
  */
329
- var LorasVar = class LorasVar extends ComfyVar {
330
- constructor(optionsSource, initial = {}, label) {
331
- super(initial, label);
332
- this.optionsSource = optionsSource;
333
- this.kind = "loras";
334
- this.prev = {};
335
- this.resolvedOptions = null;
336
- }
337
- get options() {
338
- if (!(this.optionsSource instanceof RegExp)) return this.optionsSource;
339
- 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)`);
340
- return this.resolvedOptions;
341
- }
342
- /** DefinedWorkflow binds the host at define time: a RegExp source resolves here.
343
- * cast: whitelist family 1 (agent/coding.md) — getLoras() returns the runtime
344
- * values of the SAME object_info enum the generated E_LoraName union comes from */
345
- bindHost(host) {
346
- if (!(this.optionsSource instanceof RegExp)) return;
347
- this.resolvedOptions = host.schema.getLoras(this.optionsSource);
348
- }
349
- get names() {
350
- return [...this.options];
351
- }
352
- /** loras currently ON (PromptVar keyword prefixing consumes this) */
353
- activeNames() {
354
- return this.names.filter((n) => this.isOn(n));
355
- }
356
- isOn(name) {
357
- const s = this.value[name];
358
- return s != null && s !== false;
359
- }
360
- toggleItem(name) {
361
- const cur = this.value[name];
362
- if (cur == null || cur === false) return this.set({
363
- ...this.value,
364
- [name]: this.prev[name] ?? true
365
- });
366
- this.prev[name] = cur;
367
- return this.set({
368
- ...this.value,
369
- [name]: false
370
- });
371
- }
372
- /** step both strengths by delta (true becomes 1 first); no-op when off */
373
- adjustItem(name, delta) {
374
- const cur = this.value[name];
375
- if (cur == null || cur === false) return this;
376
- const step = (n) => Math.max(0, Math.round((n + delta) * 100) / 100);
377
- const next = Array.isArray(cur) ? [step(cur[0]), step(cur[1])] : step(cur === true ? 1 : cur);
378
- return this.set({
379
- ...this.value,
380
- [name]: next
381
- });
382
- }
383
- /** compact per-item strength label for lists */
384
- strengthLabel(name) {
385
- const s = this.value[name];
386
- if (s == null || s === false) return "";
387
- if (s === true) return "1.00";
388
- if (Array.isArray(s)) return `m:${s[0].toFixed(2)} c:${s[1].toFixed(2)}`;
389
- return s.toFixed(2);
390
- }
391
- parse(raw) {
392
- try {
393
- const parsed = JSON.parse(raw);
394
- if (typeof parsed !== "object" || parsed == null || Array.isArray(parsed)) return false;
395
- this.set(parsed);
396
- return true;
397
- } catch {
398
- return false;
399
- }
400
- }
401
- /** short human name: subfolder + extension stripped */
402
- static shortName(name) {
403
- return (name.split(/[\\/]/).pop() ?? name).replace(/\.safetensors$/, "");
404
- }
405
- /** tick (true) or untick (false) every lora in `names` (default: all options) */
406
- setAll(on, names = this.options) {
407
- const next = { ...this.value };
408
- for (const name of names) {
409
- const cur = next[name];
410
- if (on) {
411
- if (cur == null || cur === false) next[name] = this.prev[name] ?? true;
412
- } else {
413
- if (cur != null && cur !== false) this.prev[name] = cur;
414
- next[name] = false;
60
+ function bundledExamplesDir(moduleUrl = import.meta.url) {
61
+ let dir = dirname(fileURLToPath(moduleUrl));
62
+ let prev = "";
63
+ while (dir !== prev) {
64
+ const pkgPath = join(dir, "package.json");
65
+ if (existsSync(pkgPath)) {
66
+ let pkg = {};
67
+ try {
68
+ pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
69
+ } catch {}
70
+ if (pkg.name === "comfy-ts") {
71
+ const examples = join(dir, "examples");
72
+ return existsSync(examples) ? examples : null;
415
73
  }
74
+ if (pkg.name != null) return null;
416
75
  }
417
- return this.set(next);
418
- }
419
- display() {
420
- const on = this.activeNames();
421
- if (on.length === 0) return `(0/${this.options.length}) none`;
422
- return `(${on.length}/${this.options.length}) ${on.map((n) => LorasVar.shortName(n)).join(", ")}`;
76
+ prev = dir;
77
+ dir = dirname(dir);
423
78
  }
424
- };
425
- /** SDXL-style ~1MP buckets, multiples of 64 — safe for most latent models */
426
- const DEFAULT_SIZE_PRESETS = [
427
- {
428
- label: "1:1 square",
429
- width: 1024,
430
- height: 1024
431
- },
432
- {
433
- label: "4:3 landscape",
434
- width: 1152,
435
- height: 896
436
- },
437
- {
438
- label: "3:4 portrait",
439
- width: 896,
440
- height: 1152
441
- },
442
- {
443
- label: "3:2 landscape",
444
- width: 1216,
445
- height: 832
446
- },
447
- {
448
- label: "2:3 portrait",
449
- width: 832,
450
- height: 1216
451
- },
452
- {
453
- label: "16:9 widescreen",
454
- width: 1344,
455
- height: 768
456
- },
457
- {
458
- label: "9:16 tall",
459
- width: 768,
460
- height: 1344
461
- }
462
- ];
463
- /** width/height picker: presets + free `WxH` entry */
464
- var SizeVar = class extends ComfyVar {
465
- constructor(defaultValue = {
466
- width: 1024,
467
- height: 1024
468
- }, presets = DEFAULT_SIZE_PRESETS, label) {
469
- super(defaultValue, label);
470
- this.presets = presets;
471
- this.kind = "size";
472
- }
473
- /** accepts '1024x768' / '1024×768' / a preset label */
474
- parse(raw) {
475
- const m = raw.trim().match(/^(\d+)\s*[x×]\s*(\d+)$/);
476
- if (m != null) {
477
- this.set({
478
- width: Number(m[1]),
479
- height: Number(m[2])
480
- });
481
- return true;
482
- }
483
- const preset = this.presets.find((p) => p.label === raw.trim());
484
- if (preset != null) {
485
- this.set({
486
- width: preset.width,
487
- height: preset.height
488
- });
489
- return true;
490
- }
491
- return false;
492
- }
493
- display() {
494
- const { width, height } = this.value;
495
- const hit = this.presets.find((p) => p.width === width && p.height === height);
496
- return `${width}×${height}${hit ? ` (${hit.label})` : ""}`;
497
- }
498
- };
499
- /** the var constructors: v.text / v.prompt / v.int / v.float / v.seed / v.toggle / v.choice / v.loras / v.size */
500
- const v = {
501
- text: (defaultValue, label) => new TextVar(defaultValue, label),
502
- prompt: (defaultValue, opts = {}) => new PromptVar(defaultValue, opts),
503
- int: (defaultValue, opts = {}) => new IntVar(defaultValue, opts),
504
- float: (defaultValue, opts = {}) => new FloatVar(defaultValue, opts),
505
- seed: (defaultValue = 0, label) => new SeedVar(defaultValue, label),
506
- toggle: (defaultValue, label) => new ToggleVar(defaultValue, label),
507
- choice: (choices, defaultValue, label) => new ChoiceVar(choices, defaultValue, label),
508
- loras: (options, initial = {}, label) => new LorasVar(options, initial, label),
509
- size: (defaultValue, opts = {}) => new SizeVar(defaultValue, opts.presets, opts.label)
510
- };
511
- function varValues(vars) {
512
- const out = {};
513
- for (const [k, varDef] of Object.entries(vars)) out[k] = varDef.outValue();
514
- return out;
79
+ throw new Error(`[comfy-ts] no package.json found walking up from ${fileURLToPath(moduleUrl)}`);
515
80
  }
516
81
  //#endregion
517
- //#region src/vars/DefinedWorkflow.ts
518
- /** type predicate (not a cast): a VarsSpec is a plain record, never callable */
519
- function isVarsThunk(vars) {
520
- return typeof vars === "function";
521
- }
522
- /**
523
- * a re-runnable workflow definition: `build` re-executes per run with the
524
- * current var values, so every run gets a fresh, deterministic graph.
525
- */
526
- var DefinedWorkflow = class {
527
- constructor(host, spec) {
528
- this.host = host;
529
- this.spec = spec;
530
- this.lastWorkflow = null;
531
- this.lastExecution = null;
532
- this.vars = isVarsThunk(spec.vars) ? spec.vars(v) : spec.vars;
533
- for (const [, varDef] of this.entries()) varDef.bindHost?.(this.host);
534
- }
535
- /** [name, var] pairs, for drivers that enumerate the knobs */
536
- entries() {
537
- return Object.entries(this.vars);
538
- }
539
- /**
540
- * build a fresh graph from the CURRENT var values (no send). `p.advance`
541
- * (set by run()) fires each var's afterRun() right after snapshotting the
542
- * values — atomically, before any await — so the graph uses this run's seed
543
- * while the var moves to the next (queued runs get distinct seeds; a bare
544
- * build() for copy/export never advances).
545
- */
546
- async build(p = {}) {
547
- const wf = this.host.workflow({ id: this.spec.id });
548
- const values = varValues(this.vars);
549
- if (p.advance) for (const varDef of Object.values(this.vars)) varDef.afterRun();
550
- await this.spec.build(wf.builder, values, wf);
551
- this.lastWorkflow = wf;
552
- return wf;
553
- }
554
- /** build a fresh graph from the current var values, send it, wait for outputs.
555
- * connects first (idempotent) — modules can import offline from the schema cache */
556
- async run(settings = {}) {
557
- await this.host.connect();
558
- const execution = await (await this.build({ advance: true })).run(settings);
559
- this.lastExecution = execution;
560
- return execution;
561
- }
562
- };
563
- //#endregion
564
82
  //#region src/cli/tui/findDefinedWorkflow.ts
565
83
  /**
566
84
  * instanceof first; duck-type fallback covers a second copy of the library in
@@ -604,19 +122,6 @@ async function imageBufferToAnsi(input, p) {
604
122
  return rows.join("\n");
605
123
  }
606
124
  //#endregion
607
- //#region src/utils/extractErrorMessage.ts
608
- /** Extracts an error message from an exception stuff. */
609
- const extractErrorMessage = (error) => {
610
- if (error instanceof Error) return error.message;
611
- if (error === null) return "null";
612
- if (typeof error === "string") return error;
613
- if (typeof error === "object") {
614
- if ("message" in error && typeof error.message === "string") return error.message;
615
- return JSON.stringify(error);
616
- }
617
- return String(error);
618
- };
619
- //#endregion
620
125
  //#region src/cli/tui/state/PreviewSt.ts
621
126
  /** OSC 1337 support: the panel can show REAL images instead of half-blocks */
622
127
  function protocolCapable() {
@@ -645,6 +150,7 @@ var PreviewSt = class {
645
150
  this.latentDims = null;
646
151
  this.latentSeenThisRun = false;
647
152
  this.lastOutputPath = null;
153
+ this.overlay = null;
648
154
  this.menuIx = 0;
649
155
  this._busy = false;
650
156
  makeAutoObservable(this, { st: false });
@@ -664,6 +170,15 @@ var PreviewSt = class {
664
170
  get menuOpen() {
665
171
  return this.st.mode === "preview";
666
172
  }
173
+ get overlayActive() {
174
+ return this.st.mode === "overlay-loras" || this.st.mode === "overlay-image";
175
+ }
176
+ setOverlayImage(p) {
177
+ this.overlay = p;
178
+ }
179
+ clearOverlayImage() {
180
+ this.overlay = null;
181
+ }
667
182
  /** running + latents wanted + sampling well underway + none arrived = server
668
183
  * sends none. The ≥20% gate keeps healthy runs from red-flashing: the first
669
184
  * progress tick lands a beat before the first preview frame */
@@ -743,7 +258,7 @@ var PreviewSt = class {
743
258
  /** what the painter should show RIGHT NOW (native renderer only; mirrors the panel's source) */
744
259
  get protocolImage() {
745
260
  if (!this.useNative || !this.show || this.menuOpen) return null;
746
- if (this.st.mode === "overlay-loras") return this.st.loras.previewBytes;
261
+ if (this.overlayActive) return this.overlay?.bytes ?? null;
747
262
  if (this.st.exec.running) {
748
263
  if (this.duringRun === "latent") return this.latentBytes ?? this.outputBytes;
749
264
  return this.outputBytes;
@@ -753,7 +268,7 @@ var PreviewSt = class {
753
268
  /** small latent painted over the panel's top-right corner (native + 'latent small' only) */
754
269
  get protocolImageCorner() {
755
270
  if (!this.useNative || !this.show || this.menuOpen) return null;
756
- if (this.st.mode === "overlay-loras") return null;
271
+ if (this.overlayActive) return null;
757
272
  if (this.st.exec.running && this.duringRun === "latent-small") return this.latentBytes;
758
273
  return null;
759
274
  }
@@ -1044,7 +559,8 @@ const KIND_KEYS = {
1044
559
  toggle: [["⏎/→", "flip"]],
1045
560
  choice: [["⏎/→", "pick"]],
1046
561
  size: [["⏎/→", "pick"]],
1047
- loras: [["⏎/→", "select"]]
562
+ loras: [["⏎/→", "select"]],
563
+ image: [["⏎/→", "browse"]]
1048
564
  };
1049
565
  /** shown INSIDE the text editor box (TextOverlay footer), not in the keybar */
1050
566
  const TEXT_EDIT_HINTS = [
@@ -1095,6 +611,16 @@ const MODE_KEYS = {
1095
611
  ["⌃N", "none"],
1096
612
  ["esc", "done"]
1097
613
  ],
614
+ "overlay-image": [
615
+ ["⏎", "pick / enter dir"],
616
+ ["←", "parent"],
617
+ ["→", "enter dir"],
618
+ ["tab", "pane"],
619
+ ["↑↓", "move"],
620
+ ["type", "filter"],
621
+ ["⌃F", "fav folder"],
622
+ ["esc", "cancel"]
623
+ ],
1098
624
  "overlay-drafts": [
1099
625
  ["⏎", "load / new"],
1100
626
  ...DRAFT_OP_HINTS,
@@ -1497,12 +1023,12 @@ const PreviewPanel = observer((p) => {
1497
1023
  })
1498
1024
  ]
1499
1025
  });
1500
- const loraMode = s.mode === "overlay-loras";
1026
+ const overlayMode = pv.overlayActive;
1501
1027
  const wantLatent = s.exec.running && pv.duringRun !== "last-output";
1502
- const showLatent = !loraMode && wantLatent && (pv.latentAnsi != null || pv.latentBytes != null);
1503
- const label = loraMode ? `lora ${s.loras.previewName ?? "lora"}` : showLatent ? pv.duringRun === "latent-small" ? "latent small" : "latent" : "output";
1504
- 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)";
1505
- const content = pv.useNative ? null : loraMode ? s.loras.previewAnsi : showLatent ? pv.latentAnsi ?? pv.outputAnsi : pv.outputAnsi;
1028
+ const showLatent = !overlayMode && wantLatent && (pv.latentAnsi != null || pv.latentBytes != null);
1029
+ const label = overlayMode ? pv.overlay?.name ?? (s.mode === "overlay-loras" ? "lora" : "image") : showLatent ? pv.duringRun === "latent-small" ? "latent small" : "latent" : "output";
1030
+ const placeholder = overlayMode ? pv.overlay?.note ?? (s.mode === "overlay-loras" ? "(pick a lora)" : "(pick an image)") : pv.latentsMissing ? "(no latents from the server — launch comfy with --preview-method auto)" : "(no image yet)";
1031
+ const content = pv.useNative ? null : overlayMode ? pv.overlay?.ansi ?? null : showLatent ? pv.latentAnsi ?? pv.outputAnsi : pv.outputAnsi;
1506
1032
  const reserveRect = pv.useNative && (pv.protocolImage != null || pv.protocolImageCorner != null);
1507
1033
  return /* @__PURE__ */ jsxs(Box, {
1508
1034
  borderStyle: "round",
@@ -1580,6 +1106,430 @@ const PromptOverlay = observer((p) => {
1580
1106
  });
1581
1107
  });
1582
1108
  //#endregion
1109
+ //#region src/cli/tui/imagePicker/fsListing.ts
1110
+ /** `name.PNG` matches extensions `['png']` — extensions are lowercase, no dots */
1111
+ function hasImageExtension(name, extensions) {
1112
+ const dot = name.lastIndexOf(".");
1113
+ if (dot <= 0) return false;
1114
+ return extensions.includes(name.slice(dot + 1).toLowerCase());
1115
+ }
1116
+ /**
1117
+ * ONE folder for the picker: dirs first then images, both alphabetical,
1118
+ * dotfiles skipped, images filtered by extension. Symlinks are followed
1119
+ * (a dangling one is skipped). Pure over fs — an unreadable dir THROWS,
1120
+ * the caller surfaces it (never a silent empty listing).
1121
+ */
1122
+ function listImageDir(dir, extensions) {
1123
+ const dirs = [];
1124
+ const images = [];
1125
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
1126
+ if (entry.name.startsWith(".")) continue;
1127
+ let isDir = entry.isDirectory();
1128
+ let isFile = entry.isFile();
1129
+ if (entry.isSymbolicLink()) try {
1130
+ const target = statSync(join(dir, entry.name));
1131
+ isDir = target.isDirectory();
1132
+ isFile = target.isFile();
1133
+ } catch {
1134
+ continue;
1135
+ }
1136
+ if (isDir) dirs.push(entry.name);
1137
+ else if (isFile && hasImageExtension(entry.name, extensions)) images.push(entry.name);
1138
+ }
1139
+ dirs.sort((a, b) => a.localeCompare(b));
1140
+ images.sort((a, b) => a.localeCompare(b));
1141
+ return {
1142
+ dirs,
1143
+ images
1144
+ };
1145
+ }
1146
+ /** parent for `←` navigation — the fs root is its own parent (never ascends past it) */
1147
+ function parentDir(dir) {
1148
+ return dirname(dir);
1149
+ }
1150
+ /**
1151
+ * image-picker favorites + recents + lastFolder — loraKeywords pattern:
1152
+ * observable, loaded once, written through on every mutation. Human-editable
1153
+ * json at `.comfy-ts/image-picker.json` (hand-tuned data, NOT under cache/ —
1154
+ * survives a cache wipe):
1155
+ * { "favorites": ["/abs/dir"], "recents": ["/abs/img.png"], "lastFolder": "/abs/dir" }
1156
+ * A corrupt file logs loud and starts fresh, never blocks the TUI. The class
1157
+ * takes its file path explicitly so tests round-trip it headless; the TUI
1158
+ * uses the ONE lazy module singleton below.
1159
+ */
1160
+ var PickerPrefs = class {
1161
+ constructor(path) {
1162
+ this.path = path;
1163
+ this.favorites = [];
1164
+ this.recents = [];
1165
+ this.lastFolder = null;
1166
+ this.load();
1167
+ makeAutoObservable(this);
1168
+ }
1169
+ load() {
1170
+ if (!existsSync(this.path)) return;
1171
+ try {
1172
+ const raw = JSON.parse(readFileSync(this.path, "utf8"));
1173
+ if (raw == null || typeof raw !== "object") throw new Error("not a json object");
1174
+ const o = raw;
1175
+ if (Array.isArray(o.favorites)) this.favorites = o.favorites.filter((f) => typeof f === "string");
1176
+ if (Array.isArray(o.recents)) this.recents = o.recents.filter((r) => typeof r === "string").slice(0, 20);
1177
+ if (typeof o.lastFolder === "string") this.lastFolder = o.lastFolder;
1178
+ } catch (e) {
1179
+ logError(`[imagePicker] unreadable ${this.path} — starting fresh: ${String(e)}`);
1180
+ }
1181
+ }
1182
+ write() {
1183
+ try {
1184
+ mkdirSync(dirname(this.path), { recursive: true });
1185
+ const json = {
1186
+ favorites: this.favorites,
1187
+ recents: this.recents,
1188
+ lastFolder: this.lastFolder
1189
+ };
1190
+ writeFileSync(this.path, `${JSON.stringify(json, null, 2)}\n`);
1191
+ } catch (e) {
1192
+ logError(`[imagePicker] write failed ${this.path}: ${String(e)}`);
1193
+ }
1194
+ }
1195
+ isFavorite(dir) {
1196
+ return this.favorites.includes(dir);
1197
+ }
1198
+ toggleFavorite(dir) {
1199
+ this.favorites = this.favorites.includes(dir) ? this.favorites.filter((f) => f !== dir) : [...this.favorites, dir];
1200
+ this.write();
1201
+ }
1202
+ /** a pick records the image (newest first, deduped, capped) AND remembers its folder */
1203
+ recordPick(imagePath) {
1204
+ this.recents = [imagePath, ...this.recents.filter((r) => r !== imagePath)].slice(0, 20);
1205
+ this.lastFolder = dirname(imagePath);
1206
+ this.write();
1207
+ }
1208
+ };
1209
+ let _prefs = null;
1210
+ /** the TUI's store, bound lazily to `.comfy-ts/image-picker.json` (gitignored) */
1211
+ function pickerPrefs() {
1212
+ if (_prefs == null) _prefs = new PickerPrefs(join(comfyts.baseFolder, "image-picker.json"));
1213
+ return _prefs;
1214
+ }
1215
+ //#endregion
1216
+ //#region src/utils/fuzzyMatch.ts
1217
+ /** case-insensitive subsequence match: 'wide' hits '16:9 (Widescreen)' */
1218
+ function fuzzyMatch(needle, hay) {
1219
+ const n = needle.toLowerCase();
1220
+ const h = hay.toLowerCase();
1221
+ let i = 0;
1222
+ for (const ch of h) if (ch === n[i]) i++;
1223
+ return i >= n.length;
1224
+ }
1225
+ //#endregion
1226
+ //#region src/cli/tui/imagePicker/ImagePickerSt.ts
1227
+ const PICKER_PANES = [
1228
+ "browse",
1229
+ "favorites",
1230
+ "recents"
1231
+ ];
1232
+ /** `~`-contract $HOME for display (ImageVar.display's convention) */
1233
+ function contractHome(path) {
1234
+ const home = homedir();
1235
+ return path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
1236
+ }
1237
+ /**
1238
+ * image-picker overlay (mode 'overlay-image'): browse the disk for an image
1239
+ * var, three panes (browse / favorites / recents), filter-as-you-type, the
1240
+ * highlighted image previews into the panel via PreviewSt's overlay slot.
1241
+ */
1242
+ var ImagePickerSt = class {
1243
+ constructor(st) {
1244
+ this.st = st;
1245
+ this.pane = "browse";
1246
+ this.folder = process.cwd();
1247
+ this.ix = 0;
1248
+ this.filter = "";
1249
+ this._busy = false;
1250
+ makeAutoObservable(this, { st: false });
1251
+ this.st.disposers.push(reaction(() => this.st.mode === "overlay-image" ? this.highlightedImage : null, () => void this.refreshPreview(), { delay: 120 }));
1252
+ }
1253
+ /** kind-narrowing cast sanctioned (agent/coding.md), `kind` is the tag */
1254
+ get selectedVar() {
1255
+ const sel = this.st.selected?.[1];
1256
+ return sel?.kind === "image" ? sel : null;
1257
+ }
1258
+ get folderDisplay() {
1259
+ return contractHome(this.folder);
1260
+ }
1261
+ /** begin() open order: dirname(value) → persisted lastFolder → opts.folder → cwd */
1262
+ initialFolder(iv) {
1263
+ const candidates = [
1264
+ iv.isSet() ? dirname(iv.absPath()) : null,
1265
+ pickerPrefs().lastFolder,
1266
+ iv.opts.folder != null ? resolve(iv.opts.folder) : null
1267
+ ];
1268
+ for (const c of candidates) try {
1269
+ if (c != null && statSync(c).isDirectory()) return c;
1270
+ } catch {}
1271
+ return process.cwd();
1272
+ }
1273
+ begin() {
1274
+ const iv = this.selectedVar;
1275
+ if (iv == null) return;
1276
+ this.st.mode = "overlay-image";
1277
+ this.pane = "browse";
1278
+ this.filter = "";
1279
+ this.ix = 0;
1280
+ this.folder = this.initialFolder(iv);
1281
+ this.st.preview.clearOverlayImage();
1282
+ }
1283
+ cancel() {
1284
+ this.st.mode = "nav";
1285
+ }
1286
+ /** every row of the active pane BEFORE the filter, plus the browse-pane
1287
+ * read error (unreadable folder: shown IN the overlay, browsing elsewhere
1288
+ * stays possible). Computed with NO side effects — mobx forbids them. */
1289
+ get paneListing() {
1290
+ if (this.pane === "favorites") return {
1291
+ rows: pickerPrefs().favorites.map((dir) => ({
1292
+ kind: "dir",
1293
+ name: contractHome(dir),
1294
+ path: dir
1295
+ })),
1296
+ error: null
1297
+ };
1298
+ if (this.pane === "recents") return {
1299
+ rows: pickerPrefs().recents.map((img) => ({
1300
+ kind: "image",
1301
+ name: contractHome(img),
1302
+ path: img,
1303
+ missing: !existsSync(img)
1304
+ })),
1305
+ error: null
1306
+ };
1307
+ const iv = this.selectedVar;
1308
+ if (iv == null) return {
1309
+ rows: [],
1310
+ error: null
1311
+ };
1312
+ try {
1313
+ const listing = listImageDir(this.folder, iv.extensions);
1314
+ return {
1315
+ rows: [...listing.dirs.map((d) => ({
1316
+ kind: "dir",
1317
+ name: d,
1318
+ path: resolve(this.folder, d)
1319
+ })), ...listing.images.map((f) => ({
1320
+ kind: "image",
1321
+ name: f,
1322
+ path: resolve(this.folder, f),
1323
+ missing: false
1324
+ }))],
1325
+ error: null
1326
+ };
1327
+ } catch (e) {
1328
+ return {
1329
+ rows: [],
1330
+ error: extractErrorMessage(e)
1331
+ };
1332
+ }
1333
+ }
1334
+ get listingError() {
1335
+ return this.paneListing.error;
1336
+ }
1337
+ /** what the overlay renders: pane rows surviving the filter */
1338
+ get rows() {
1339
+ const all = this.paneListing.rows;
1340
+ if (this.filter === "") return all;
1341
+ return all.filter((r) => fuzzyMatch(this.filter, r.name));
1342
+ }
1343
+ get current() {
1344
+ return this.rows[this.ix] ?? null;
1345
+ }
1346
+ /** feeds the preview reaction: only a real, present image highlights */
1347
+ get highlightedImage() {
1348
+ const row = this.current;
1349
+ return row?.kind === "image" && !row.missing ? row.path : null;
1350
+ }
1351
+ move(delta) {
1352
+ const len = this.rows.length;
1353
+ if (len === 0) return;
1354
+ this.ix = (this.ix + delta + len) % len;
1355
+ }
1356
+ cyclePane() {
1357
+ const ix = PICKER_PANES.indexOf(this.pane);
1358
+ this.pane = PICKER_PANES[(ix + 1) % PICKER_PANES.length] ?? "browse";
1359
+ this.ix = 0;
1360
+ this.filter = "";
1361
+ }
1362
+ goto(dir) {
1363
+ this.pane = "browse";
1364
+ this.folder = dir;
1365
+ this.ix = 0;
1366
+ this.filter = "";
1367
+ }
1368
+ /** `→`: enter the highlighted dir (browse pane; images select via ⏎ only) */
1369
+ enter() {
1370
+ const row = this.current;
1371
+ if (this.pane === "browse" && row?.kind === "dir") this.goto(row.path);
1372
+ }
1373
+ /** `←`: parent dir (browse pane; the fs root is its own parent) */
1374
+ goParent() {
1375
+ if (this.pane !== "browse") return;
1376
+ const parent = parentDir(this.folder);
1377
+ if (parent !== this.folder) this.goto(parent);
1378
+ }
1379
+ /** ⏎: enter a dir (a favorite jumps browse into it), select an image */
1380
+ commit() {
1381
+ const row = this.current;
1382
+ if (row == null) return;
1383
+ if (row.kind === "dir") return this.goto(row.path);
1384
+ if (row.missing) return;
1385
+ this.select(row.path);
1386
+ }
1387
+ /** the pick: absolute path into the var, recents + lastFolder recorded */
1388
+ select(absPath) {
1389
+ const iv = this.selectedVar;
1390
+ if (iv == null) return;
1391
+ iv.set(absPath);
1392
+ pickerPrefs().recordPick(absPath);
1393
+ this.st.mode = "nav";
1394
+ }
1395
+ /** ⌃F: favorite FOLDERS only — a dir row favorites it, an image row favorites the current folder */
1396
+ toggleFavorite() {
1397
+ const row = this.current;
1398
+ const dir = row == null ? this.pane === "browse" ? this.folder : null : row.kind === "dir" ? row.path : this.pane === "browse" ? this.folder : dirname(row.path);
1399
+ if (dir == null) return;
1400
+ pickerPrefs().toggleFavorite(dir);
1401
+ this.ix = Math.max(0, Math.min(this.ix, this.rows.length - 1));
1402
+ }
1403
+ isFavorite(dir) {
1404
+ return pickerPrefs().isFavorite(dir);
1405
+ }
1406
+ filterInput(chunk) {
1407
+ this.filter += chunk;
1408
+ this.ix = 0;
1409
+ }
1410
+ filterBackspace() {
1411
+ this.filter = this.filter.slice(0, -1);
1412
+ this.ix = 0;
1413
+ }
1414
+ /** ⌥⌫ / ⌃W: drop the last word of the filter */
1415
+ filterDeleteWord() {
1416
+ this.filter = this.filter.replace(/\s*\S+\s*$/, "");
1417
+ this.ix = 0;
1418
+ }
1419
+ async refreshPreview() {
1420
+ if (this.st.mode !== "overlay-image") {
1421
+ if (!this.st.preview.overlayActive) this.st.preview.clearOverlayImage();
1422
+ return;
1423
+ }
1424
+ const path = this.highlightedImage;
1425
+ if (path == null) {
1426
+ this.st.preview.clearOverlayImage();
1427
+ return;
1428
+ }
1429
+ if (this._busy) return;
1430
+ this._busy = true;
1431
+ try {
1432
+ const bytes = new Uint8Array(readFileSync(path));
1433
+ if (this.st.preview.useNative) this.st.preview.setOverlayImage({
1434
+ bytes,
1435
+ ansi: null,
1436
+ name: basename(path),
1437
+ note: null
1438
+ });
1439
+ else {
1440
+ const ansi = await imageBufferToAnsi(bytes, {
1441
+ width: this.st.preview.width,
1442
+ height: this.st.preview.height
1443
+ });
1444
+ this.st.preview.setOverlayImage({
1445
+ bytes: null,
1446
+ ansi,
1447
+ name: basename(path),
1448
+ note: null
1449
+ });
1450
+ }
1451
+ } catch (e) {
1452
+ this.st.preview.setOverlayImage({
1453
+ bytes: null,
1454
+ ansi: null,
1455
+ name: basename(path),
1456
+ note: extractErrorMessage(e)
1457
+ });
1458
+ } finally {
1459
+ this._busy = false;
1460
+ if (this.st.mode === "overlay-image" && this.highlightedImage !== path) this.refreshPreview();
1461
+ }
1462
+ }
1463
+ };
1464
+ //#endregion
1465
+ //#region src/cli/tui/imagePicker/ImagePickerOverlay.tsx
1466
+ /** modal image browser: three panes (tab), dirs enter, ⏎ picks, ★ = favorite folder */
1467
+ const ImagePickerOverlay = observer((p) => {
1468
+ const s = p.st;
1469
+ const ip = s.imagePicker;
1470
+ const iv = ip.selectedVar;
1471
+ if (iv == null) return null;
1472
+ const rows = ip.rows;
1473
+ return /* @__PURE__ */ jsx(OverlayList, {
1474
+ title: /* @__PURE__ */ jsxs(Fragment, { children: [
1475
+ s.selected?.[1].label ?? s.selected?.[0],
1476
+ " ",
1477
+ /* @__PURE__ */ jsx(Text, {
1478
+ color: "gray",
1479
+ children: iv.display()
1480
+ })
1481
+ ] }),
1482
+ extraHeader: /* @__PURE__ */ jsxs(Box, {
1483
+ flexDirection: "column",
1484
+ children: [/* @__PURE__ */ jsxs(Text, { children: [PICKER_PANES.map((pane, ix) => /* @__PURE__ */ jsxs(Text, { children: [ix > 0 ? /* @__PURE__ */ jsx(Text, {
1485
+ color: "gray",
1486
+ children: " · "
1487
+ }) : null, /* @__PURE__ */ jsx(Text, {
1488
+ color: pane === ip.pane ? "cyan" : "gray",
1489
+ bold: pane === ip.pane,
1490
+ underline: pane === ip.pane,
1491
+ children: pane
1492
+ })] }, pane)), ip.pane === "browse" ? /* @__PURE__ */ jsxs(Text, {
1493
+ color: "gray",
1494
+ children: [" ", ip.folderDisplay]
1495
+ }) : null] }), /* @__PURE__ */ jsxs(Text, {
1496
+ color: "yellow",
1497
+ children: [
1498
+ "filter: ",
1499
+ ip.filter,
1500
+ "▌"
1501
+ ]
1502
+ })]
1503
+ }),
1504
+ selectedIx: ip.ix,
1505
+ lines: s.overlayLines,
1506
+ rows: rows.map((row, ix) => {
1507
+ const sel = ix === ip.ix;
1508
+ const fav = row.kind === "dir" && ip.isFavorite(row.path);
1509
+ const missing = row.kind === "image" && row.missing;
1510
+ return {
1511
+ key: `${row.kind}:${row.path}`,
1512
+ node: /* @__PURE__ */ jsxs(Text, {
1513
+ inverse: sel,
1514
+ color: row.kind === "dir" ? "blue" : missing ? "gray" : void 0,
1515
+ dimColor: missing,
1516
+ children: [
1517
+ sel ? "▸ " : " ",
1518
+ fav ? "★ " : " ",
1519
+ row.name,
1520
+ row.kind === "dir" ? "/" : "",
1521
+ missing ? " (missing)" : ""
1522
+ ]
1523
+ }, `${row.kind}:${row.path}`)
1524
+ };
1525
+ }),
1526
+ footer: rows.length === 0 ? /* @__PURE__ */ jsx(Text, {
1527
+ color: "red",
1528
+ children: ip.listingError ?? (ip.filter !== "" ? "no match" : "no images here")
1529
+ }) : void 0
1530
+ });
1531
+ });
1532
+ //#endregion
1583
1533
  //#region src/cli/tui/components/LogsPanel.tsx
1584
1534
  const ERROR_RE = /error|exception|traceback|failed/i;
1585
1535
  /** last server console lines (LogsSt), below the vars panel */
@@ -1729,15 +1679,22 @@ const TreePanel = observer((p) => {
1729
1679
  }),
1730
1680
  tree.rows.map((row, ix) => {
1731
1681
  const sel = focused && ix === tree.ix;
1682
+ if (row.kind === "section") return /* @__PURE__ */ jsxs(Text, {
1683
+ color: "gray",
1684
+ dimColor: true,
1685
+ wrap: "truncate",
1686
+ children: ["─ ", row.label]
1687
+ }, `section·${row.label}`);
1732
1688
  if (row.kind === "workflow") {
1733
1689
  const arrow = row.hasDrafts ? row.expanded ? "▾" : "▸" : " ";
1690
+ const marker = row.error != null ? "✗" : row.current ? "●" : " ";
1734
1691
  return /* @__PURE__ */ jsxs(Text, {
1735
1692
  inverse: sel,
1736
- color: row.current ? "green" : void 0,
1693
+ color: row.error != null ? "red" : row.current ? "green" : void 0,
1737
1694
  wrap: "truncate",
1738
1695
  children: [
1739
1696
  arrow,
1740
- row.current ? "●" : " ",
1697
+ marker,
1741
1698
  " ",
1742
1699
  row.name
1743
1700
  ]
@@ -1948,6 +1905,21 @@ const TuiApp = observer((p) => {
1948
1905
  if (input && !key.ctrl && !key.meta) return lo.filterInput(input);
1949
1906
  return;
1950
1907
  }
1908
+ if (s.mode === "overlay-image") {
1909
+ const ip = s.imagePicker;
1910
+ if (key.escape) return ip.cancel();
1911
+ if (key.tab || input === " ") return ip.cyclePane();
1912
+ if (key.ctrl && input === "f") return ip.toggleFavorite();
1913
+ if (key.return) return ip.commit();
1914
+ if (key.upArrow) return ip.move(-1);
1915
+ if (key.downArrow) return ip.move(1);
1916
+ if (key.leftArrow) return ip.goParent();
1917
+ if (key.rightArrow) return ip.enter();
1918
+ if (key.meta && (key.backspace || key.delete) || key.ctrl && input === "w") return ip.filterDeleteWord();
1919
+ if (key.backspace || key.delete) return ip.filterBackspace();
1920
+ if (input && !key.ctrl && !key.meta) return ip.filterInput(input);
1921
+ return;
1922
+ }
1951
1923
  if (s.mode === "tree") {
1952
1924
  const tr = s.tree;
1953
1925
  if (key.escape || input === "t") return tr.blur();
@@ -2052,7 +2024,7 @@ const TuiApp = observer((p) => {
2052
2024
  flexDirection: "column",
2053
2025
  flexGrow: 1,
2054
2026
  children: [
2055
- s.mode === "edit" && s.editor.isCustom ? /* @__PURE__ */ jsx(PromptOverlay, { st: s }) : s.mode === "host" ? /* @__PURE__ */ jsx(HostPanel, { st: s }) : s.mode === "overlay-text" ? /* @__PURE__ */ jsx(TextOverlay, { st: s }) : s.mode === "overlay-choice" ? /* @__PURE__ */ jsx(ChoiceOverlay, { st: s }) : s.mode === "overlay-size" ? /* @__PURE__ */ jsx(SizeOverlay, { st: s }) : s.mode === "overlay-loras" ? /* @__PURE__ */ jsx(LorasOverlay, { st: s }) : s.mode === "overlay-drafts" ? /* @__PURE__ */ jsx(DraftsOverlay, { st: s }) : /* @__PURE__ */ jsx(VarsPanel, { st: s }),
2027
+ s.mode === "edit" && s.editor.isCustom ? /* @__PURE__ */ jsx(PromptOverlay, { st: s }) : s.mode === "host" ? /* @__PURE__ */ jsx(HostPanel, { st: s }) : s.mode === "overlay-text" ? /* @__PURE__ */ jsx(TextOverlay, { st: s }) : s.mode === "overlay-choice" ? /* @__PURE__ */ jsx(ChoiceOverlay, { st: s }) : s.mode === "overlay-size" ? /* @__PURE__ */ jsx(SizeOverlay, { st: s }) : s.mode === "overlay-loras" ? /* @__PURE__ */ jsx(LorasOverlay, { st: s }) : s.mode === "overlay-image" ? /* @__PURE__ */ jsx(ImagePickerOverlay, { st: s }) : s.mode === "overlay-drafts" ? /* @__PURE__ */ jsx(DraftsOverlay, { st: s }) : /* @__PURE__ */ jsx(VarsPanel, { st: s }),
2056
2028
  /* @__PURE__ */ jsx(Box, {
2057
2029
  paddingX: 1,
2058
2030
  children: /* @__PURE__ */ jsx(ProgressLine, { st: s })
@@ -2806,7 +2778,7 @@ var HostSt = class {
2806
2778
  this.spinTimer = spin;
2807
2779
  let ok = false;
2808
2780
  try {
2809
- const res = await fetch(`${host.getServerHostHTTP()}/api/prompt`, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
2781
+ const res = await host.fetch("/prompt", { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
2810
2782
  res.body?.cancel();
2811
2783
  ok = res.ok;
2812
2784
  } catch {
@@ -2921,30 +2893,6 @@ var HostSt = class {
2921
2893
  }
2922
2894
  };
2923
2895
  //#endregion
2924
- //#region src/utils/ansi.ts
2925
- const codes = {
2926
- bold: [1, 22],
2927
- underline: [4, 24],
2928
- red: [31, 39],
2929
- green: [32, 39],
2930
- yellow: [33, 39],
2931
- blue: [34, 39],
2932
- greenBright: [92, 39]
2933
- };
2934
- function styler(open = "", close = "") {
2935
- const fn = (s) => open + s + close;
2936
- return new Proxy(fn, { get(_target, prop) {
2937
- const c = codes[prop];
2938
- if (c == null) throw new Error(`unknown ansi style: ${prop}`);
2939
- return styler(`${open}\x1b[${c[0]}m`, `\x1b[${c[1]}m${close}`);
2940
- } });
2941
- }
2942
- styler();
2943
- const ANSI_RE = /\x1b\[[0-9;?]*[A-Za-z]|\x1b[A-Za-z]/g;
2944
- function stripAnsi(s) {
2945
- return s.replace(ANSI_RE, "");
2946
- }
2947
- //#endregion
2948
2896
  //#region src/utils/mojibake.ts
2949
2897
  const CP1252_REVERSE = {
2950
2898
  "€": 128,
@@ -3111,13 +3059,12 @@ function loraPreviewKey(name) {
3111
3059
  * (server-relative). Returns null when the extension is absent (404/network).
3112
3060
  */
3113
3061
  async function fetchLoraPreviewMap(host) {
3114
- const base = host.getServerHostHTTP();
3115
3062
  const map = /* @__PURE__ */ new Map();
3116
3063
  const pageSize = 500;
3117
3064
  for (let page = 1; page <= 20; page++) {
3118
3065
  let res;
3119
3066
  try {
3120
- res = await fetch(`${base}/api/lm/loras/list?page=${page}&page_size=${pageSize}`);
3067
+ res = await host.fetch(`/api/lm/loras/list?page=${page}&page_size=${pageSize}`, {}, { apiPrefix: false });
3121
3068
  } catch {
3122
3069
  return null;
3123
3070
  }
@@ -3176,7 +3123,7 @@ async function fetchLoraPreviewBytes(host, previewUrl) {
3176
3123
  const cachePath = comfyts.resolveFromCache(`lora-previews/${createHash("sha1").update(previewUrl).digest("hex")}`);
3177
3124
  if (existsSync(cachePath)) return new Uint8Array(readFileSync(cachePath));
3178
3125
  try {
3179
- const res = await fetch(`${host.getServerHostHTTP()}${previewUrl}`);
3126
+ const res = await host.fetch(previewUrl, {}, { apiPrefix: false });
3180
3127
  if (!res.ok) return null;
3181
3128
  const ct = res.headers.get("content-type") ?? "";
3182
3129
  if (ct !== "" && !ct.startsWith("image/")) return null;
@@ -3190,16 +3137,6 @@ async function fetchLoraPreviewBytes(host, previewUrl) {
3190
3137
  }
3191
3138
  }
3192
3139
  //#endregion
3193
- //#region src/utils/fuzzyMatch.ts
3194
- /** case-insensitive subsequence match: 'wide' hits '16:9 (Widescreen)' */
3195
- function fuzzyMatch(needle, hay) {
3196
- const n = needle.toLowerCase();
3197
- const h = hay.toLowerCase();
3198
- let i = 0;
3199
- for (const ch of h) if (ch === n[i]) i++;
3200
- return i >= n.length;
3201
- }
3202
- //#endregion
3203
3140
  //#region src/cli/tui/state/LorasSt.ts
3204
3141
  /** loras overlay: fuzzy filter + tick/untick + strengths + bulk ops + lora-manager preview */
3205
3142
  var LorasSt = class {
@@ -3207,10 +3144,6 @@ var LorasSt = class {
3207
3144
  this.st = st;
3208
3145
  this.ix = 0;
3209
3146
  this.filter = "";
3210
- this.previewAnsi = null;
3211
- this.previewBytes = null;
3212
- this.previewName = null;
3213
- this.previewNote = null;
3214
3147
  this.previewMap = void 0;
3215
3148
  this.previewMapHostId = null;
3216
3149
  this._busy = false;
@@ -3234,6 +3167,7 @@ var LorasSt = class {
3234
3167
  this.st.mode = "overlay-loras";
3235
3168
  this.ix = 0;
3236
3169
  this.filter = "";
3170
+ this.st.preview.clearOverlayImage();
3237
3171
  }
3238
3172
  move(delta) {
3239
3173
  const len = this.filteredNames.length;
@@ -3286,14 +3220,10 @@ var LorasSt = class {
3286
3220
  get selectedName() {
3287
3221
  return this.filteredNames[this.ix] ?? null;
3288
3222
  }
3223
+ /** preview goes through PreviewSt's shared overlay slot (one code path with the image picker) */
3289
3224
  async refreshPreview() {
3290
3225
  if (this.st.mode !== "overlay-loras") {
3291
- runInAction(() => {
3292
- this.previewAnsi = null;
3293
- this.previewBytes = null;
3294
- this.previewName = null;
3295
- this.previewNote = null;
3296
- });
3226
+ if (!this.st.preview.overlayActive) this.st.preview.clearOverlayImage();
3297
3227
  return;
3298
3228
  }
3299
3229
  const name = this.selectedName;
@@ -3309,22 +3239,22 @@ var LorasSt = class {
3309
3239
  const url = map?.get(loraPreviewKey(name));
3310
3240
  const note = map == null ? "lora-manager extension not detected" : url == null ? "no preview available" : null;
3311
3241
  if (url == null) {
3312
- runInAction(() => {
3313
- this.previewAnsi = null;
3314
- this.previewBytes = null;
3315
- this.previewName = name;
3316
- this.previewNote = note;
3242
+ this.st.preview.setOverlayImage({
3243
+ bytes: null,
3244
+ ansi: null,
3245
+ name: `lora ${name}`,
3246
+ note
3317
3247
  });
3318
3248
  return;
3319
3249
  }
3320
3250
  const bytes = await fetchLoraPreviewBytes(host, url);
3321
3251
  if (bytes == null) throw new Error("no image preview on the server");
3322
3252
  if (this.st.preview.useNative) {
3323
- runInAction(() => {
3324
- this.previewBytes = bytes;
3325
- this.previewAnsi = null;
3326
- this.previewName = name;
3327
- this.previewNote = null;
3253
+ this.st.preview.setOverlayImage({
3254
+ bytes,
3255
+ ansi: null,
3256
+ name: `lora ${name}`,
3257
+ note: null
3328
3258
  });
3329
3259
  return;
3330
3260
  }
@@ -3332,17 +3262,18 @@ var LorasSt = class {
3332
3262
  width: this.st.preview.width,
3333
3263
  height: this.st.preview.height
3334
3264
  });
3335
- runInAction(() => {
3336
- this.previewAnsi = ansi;
3337
- this.previewName = name;
3338
- this.previewNote = null;
3265
+ this.st.preview.setOverlayImage({
3266
+ bytes: null,
3267
+ ansi,
3268
+ name: `lora ${name}`,
3269
+ note: null
3339
3270
  });
3340
3271
  } catch (e) {
3341
- runInAction(() => {
3342
- this.previewAnsi = null;
3343
- this.previewBytes = null;
3344
- this.previewName = name;
3345
- this.previewNote = extractErrorMessage(e);
3272
+ this.st.preview.setOverlayImage({
3273
+ bytes: null,
3274
+ ansi: null,
3275
+ name: `lora ${name}`,
3276
+ note: extractErrorMessage(e)
3346
3277
  });
3347
3278
  } finally {
3348
3279
  this._busy = false;
@@ -3580,7 +3511,15 @@ var TreeSt = class {
3580
3511
  this.st.drafts.version;
3581
3512
  const w = this.st.workflows;
3582
3513
  const rows = [];
3514
+ let sectionPushed = false;
3583
3515
  for (const file of w.files) {
3516
+ if (!sectionPushed && w.bundled.has(file)) {
3517
+ rows.push({
3518
+ kind: "section",
3519
+ label: "comfy-ts examples"
3520
+ });
3521
+ sectionPushed = true;
3522
+ }
3584
3523
  const current = file === w.currentPath;
3585
3524
  const expanded = this.expandedFiles.has(file);
3586
3525
  const drafts = listDraftsForFile(file);
@@ -3590,7 +3529,8 @@ var TreeSt = class {
3590
3529
  name: draftKeyForFile(file),
3591
3530
  expanded,
3592
3531
  current,
3593
- hasDrafts: drafts.length > 0
3532
+ hasDrafts: drafts.length > 0,
3533
+ error: w.loadErrors.get(file) ?? null
3594
3534
  });
3595
3535
  if (!expanded) continue;
3596
3536
  for (const draft of drafts) rows.push({
@@ -3624,22 +3564,28 @@ var TreeSt = class {
3624
3564
  this.st.mode = "nav";
3625
3565
  }
3626
3566
  move(delta) {
3627
- const len = this.rows.length;
3567
+ const rows = this.rows;
3568
+ const len = rows.length;
3628
3569
  if (len === 0) return;
3629
- this.ix = (this.ix + delta + len) % len;
3570
+ let ix = this.ix;
3571
+ for (let step = 0; step < len; step++) {
3572
+ ix = (ix + delta + len) % len;
3573
+ if (rows[ix]?.kind !== "section") break;
3574
+ }
3575
+ this.ix = ix;
3630
3576
  }
3631
3577
  /** →: unfold the workflow under the cursor; on a draft row there is nothing
3632
3578
  * left to unfold, so → continues rightwards into the vars panel */
3633
3579
  unfold() {
3634
3580
  const row = this.selected;
3635
- if (row == null) return;
3581
+ if (row == null || row.kind === "section") return;
3636
3582
  if (row.kind === "workflow") this.expandedFiles.add(row.file);
3637
3583
  else this.blur();
3638
3584
  }
3639
3585
  /** ←: fold the workflow under the cursor; on a draft row, jump to (and fold) its parent */
3640
3586
  fold() {
3641
3587
  const row = this.selected;
3642
- if (row == null) return;
3588
+ if (row == null || row.kind === "section") return;
3643
3589
  this.expandedFiles.delete(row.file);
3644
3590
  if (row.kind === "draft") {
3645
3591
  const ix = this.rows.findIndex((r) => r.kind === "workflow" && r.file === row.file);
@@ -3649,13 +3595,14 @@ var TreeSt = class {
3649
3595
  /** ⏎: load the workflow (into 'default'), or the exact draft under the cursor */
3650
3596
  async commit() {
3651
3597
  const row = this.selected;
3652
- if (row == null) return;
3598
+ if (row == null || row.kind === "section") return;
3653
3599
  if (row.kind === "workflow") return this.st.workflows.commit(row.file);
3654
3600
  return this.st.workflows.commit(row.file, row.draft);
3655
3601
  }
3656
3602
  /** n: new draft — current workflow only (a draft snapshots its LIVE var values) */
3657
3603
  promptNewDraft() {
3658
3604
  const row = this.selected;
3605
+ if (row?.kind === "section") return;
3659
3606
  if (row != null && row.file !== this.st.workflows.currentPath) {
3660
3607
  this.st.exec.notice = "load that workflow first (⏎) — a new draft snapshots its live vars";
3661
3608
  return;
@@ -3679,12 +3626,14 @@ var TreeSt = class {
3679
3626
  //#region src/cli/tui/state/WorkflowsSt.ts
3680
3627
  /** workflow-module data layer: scanned files, module loading, opened-host set (TreeSt is the UI over it) */
3681
3628
  var WorkflowsSt = class {
3682
- constructor(st, files, currentPath = null) {
3629
+ constructor(st, files, currentPath = null, bundled = /* @__PURE__ */ new Set(), loadErrors = /* @__PURE__ */ new Map()) {
3683
3630
  this.st = st;
3684
3631
  this.files = files;
3685
3632
  this.loading = false;
3686
3633
  this.loadedHosts = /* @__PURE__ */ new Set();
3687
3634
  this.currentPath = currentPath;
3635
+ this.bundled = bundled;
3636
+ this.loadErrors = loadErrors;
3688
3637
  makeAutoObservable(this, { st: false });
3689
3638
  }
3690
3639
  disconnectAllHosts() {
@@ -3718,6 +3667,7 @@ var WorkflowsSt = class {
3718
3667
  const wf = findDefinedWorkflow(await import(pathToFileURL(resolve(path)).href + (bustCache ? `?v=${Date.now()}` : "")));
3719
3668
  if (wf == null) throw new Error(`${path} exports no DefinedWorkflow`);
3720
3669
  runInAction(() => {
3670
+ this.loadErrors.delete(path);
3721
3671
  this.loadedHosts.add(this.st.wf.host);
3722
3672
  this.loadedHosts.add(wf.host);
3723
3673
  this.st.wf = wf;
@@ -3733,8 +3683,10 @@ var WorkflowsSt = class {
3733
3683
  });
3734
3684
  } catch (e) {
3735
3685
  runInAction(() => {
3686
+ const msg = extractErrorMessage(e);
3687
+ this.loadErrors.set(path, msg);
3736
3688
  this.st.mode = "nav";
3737
- this.st.exec.error = extractErrorMessage(e);
3689
+ this.st.exec.error = msg;
3738
3690
  });
3739
3691
  } finally {
3740
3692
  runInAction(() => {
@@ -3764,6 +3716,7 @@ var TuiSt = class {
3764
3716
  editor: false,
3765
3717
  picker: false,
3766
3718
  loras: false,
3719
+ imagePicker: false,
3767
3720
  workflows: false,
3768
3721
  tree: false,
3769
3722
  drafts: false,
@@ -3778,7 +3731,8 @@ var TuiSt = class {
3778
3731
  this.editor = new EditorSt(this);
3779
3732
  this.picker = new PickerSt(this);
3780
3733
  this.loras = new LorasSt(this);
3781
- this.workflows = new WorkflowsSt(this, opts.workflowFiles ?? [], opts.currentFile ?? null);
3734
+ this.imagePicker = new ImagePickerSt(this);
3735
+ this.workflows = new WorkflowsSt(this, opts.workflowFiles ?? [], opts.currentFile ?? null, opts.bundledFiles, opts.loadErrors);
3782
3736
  this.tree = new TreeSt(this);
3783
3737
  this.drafts = new DraftsSt(this);
3784
3738
  this.exec = new ExecSt(this);
@@ -3807,7 +3761,7 @@ var TuiSt = class {
3807
3761
  }
3808
3762
  /** left tree panel width: longest row (workflow or indented draft), clamped */
3809
3763
  get treeWidth() {
3810
- const longest = Math.max(8, ...this.tree.rows.map((r) => r.kind === "workflow" ? r.name.length : r.draft.length + 3));
3764
+ 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));
3811
3765
  return Math.min(32, longest + 7);
3812
3766
  }
3813
3767
  get entries() {
@@ -3830,6 +3784,7 @@ var TuiSt = class {
3830
3784
  else if (sel.kind === "choice") this.picker.beginChoice();
3831
3785
  else if (sel.kind === "size") this.picker.beginSize();
3832
3786
  else if (sel.kind === "loras") this.loras.begin();
3787
+ else if (sel.kind === "image") this.imagePicker.begin();
3833
3788
  else this.editor.beginInline();
3834
3789
  }
3835
3790
  /** kind-specific nav keys (documented in the keybar): seed `+`/`-`/`=`/`?` mode, `*` reroll */
@@ -3850,31 +3805,50 @@ var TuiSt = class {
3850
3805
  };
3851
3806
  //#endregion
3852
3807
  //#region src/cli/tui/run-tui.tsx
3853
- /** recursive scan for the workflow-module naming convention */
3854
- function scanCflowFiles(dir) {
3855
- return readdirSync(dir, { recursive: true }).map((f) => join(dir, String(f))).filter((f) => f.endsWith(".cflow.ts") || f.endsWith(".cflow.tsx")).sort();
3856
- }
3857
3808
  async function runTui(args) {
3858
- const target = args.find((a) => !a.startsWith("--")) ?? ".";
3809
+ const target = args.find((a) => !a.startsWith("--"));
3859
3810
  process.env[COMFY_TS_TUI_ENV] = "1";
3860
3811
  process.env.COMFY_TS_QUIET = "1";
3861
- const abs = resolve(target);
3812
+ const abs = realpathSync(resolve(target ?? "."));
3862
3813
  const isDir = statSync(abs).isDirectory();
3863
3814
  const scanned = scanCflowFiles(isDir ? abs : dirname(abs));
3864
- const workflowFiles = isDir || scanned.includes(abs) ? scanned : [abs, ...scanned];
3865
- const first = isDir ? workflowFiles[0] : abs;
3866
- if (first == null) {
3815
+ const scannedPlusArg = isDir || scanned.includes(abs) ? scanned : [abs, ...scanned];
3816
+ const canImportBundled = process.versions.bun != null;
3817
+ const examplesDir = canImportBundled ? bundledExamplesDir() : null;
3818
+ if (!canImportBundled && target == null) logError("packaged examples skipped: importing .cflow.ts from node_modules needs bun (bunx --bun comfy-ts tui)");
3819
+ const discovery = mergeWorkflowSources({
3820
+ explicitTarget: target != null,
3821
+ scanned: scannedPlusArg,
3822
+ bundledFiles: examplesDir == null ? [] : scanCflowFiles(realpathSync(examplesDir))
3823
+ });
3824
+ const workflowFiles = discovery.files;
3825
+ if (workflowFiles.length === 0) {
3867
3826
  console.error(`[comfy-ts tui] no **/*.cflow.ts found under ${abs}`);
3868
3827
  return 1;
3869
3828
  }
3870
- const wf = findDefinedWorkflow(await import(pathToFileURL(first).href));
3871
- if (wf == null) {
3872
- console.error(`[comfy-ts tui] ${first} exports no DefinedWorkflow — export the result of host.defineWorkflow(...)`);
3829
+ const candidates = !isDir && workflowFiles.includes(abs) ? [abs, ...workflowFiles.filter((f) => f !== abs)] : workflowFiles;
3830
+ const loadErrors = /* @__PURE__ */ new Map();
3831
+ let first = null;
3832
+ let wf = null;
3833
+ for (const file of candidates) try {
3834
+ const found = findDefinedWorkflow(await import(pathToFileURL(file).href));
3835
+ if (found == null) throw new Error(`${file} exports no DefinedWorkflow — export the result of host.defineWorkflow(...)`);
3836
+ first = file;
3837
+ wf = found;
3838
+ break;
3839
+ } catch (e) {
3840
+ loadErrors.set(file, extractErrorMessage(e));
3841
+ }
3842
+ if (first == null || wf == null) {
3843
+ console.error(`[comfy-ts tui] no loadable workflow module among ${candidates.length} file(s):`);
3844
+ for (const [file, err] of loadErrors) console.error(` ${file}: ${err}`);
3873
3845
  return 1;
3874
3846
  }
3875
3847
  const st = new TuiSt(wf, {
3876
3848
  workflowFiles,
3877
- currentFile: first
3849
+ currentFile: first,
3850
+ bundledFiles: discovery.bundled,
3851
+ loadErrors
3878
3852
  });
3879
3853
  const altScreen = process.stdout.isTTY === true;
3880
3854
  if (altScreen) process.stdout.write("\x1B[?1049h\x1B[H\x1B[>4;1m");
@@ -3893,4 +3867,4 @@ async function runTui(args) {
3893
3867
  //#endregion
3894
3868
  export { runTui };
3895
3869
 
3896
- //# sourceMappingURL=run-tui-SDSJo1Qf.js.map
3870
+ //# sourceMappingURL=run-tui-DZ22HDHI.js.map