comfy-ts 0.2.0 → 0.3.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/LICENSE +21 -0
  2. package/README.md +363 -0
  3. package/dist/cli.js +764 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/index.cjs +4128 -0
  6. package/dist/index.cjs.map +1 -0
  7. package/dist/index.d.cts +9862 -0
  8. package/dist/index.d.ts +9846 -58
  9. package/dist/index.js +4049 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/log-CdfgILde.js +10 -0
  12. package/dist/log-CdfgILde.js.map +1 -0
  13. package/dist/run-tui-Io8Xea0L.js +3340 -0
  14. package/dist/run-tui-Io8Xea0L.js.map +1 -0
  15. package/package.json +104 -75
  16. package/src/cli/comfy-ts-cli.ts +36 -0
  17. package/src/cli/gen.ts +47 -0
  18. package/src/cli/outline.ts +82 -0
  19. package/src/cli/tui/components/DraftsOverlay.tsx +44 -0
  20. package/src/cli/tui/components/EditField.tsx +27 -0
  21. package/src/cli/tui/components/Header.tsx +51 -0
  22. package/src/cli/tui/components/HostPanel.tsx +37 -0
  23. package/src/cli/tui/components/LorasOverlay.tsx +49 -0
  24. package/src/cli/tui/components/OverlayList.tsx +25 -0
  25. package/src/cli/tui/components/PickerOverlays.tsx +66 -0
  26. package/src/cli/tui/components/PreviewPanel.tsx +33 -0
  27. package/src/cli/tui/components/PromptOverlay.tsx +16 -0
  28. package/src/cli/tui/components/StatusBar.tsx +165 -0
  29. package/src/cli/tui/components/TextOverlay.tsx +72 -0
  30. package/src/cli/tui/components/TreePanel.tsx +51 -0
  31. package/src/cli/tui/components/TuiApp.tsx +223 -0
  32. package/src/cli/tui/components/VarsPanel.tsx +86 -0
  33. package/src/cli/tui/findDefinedWorkflow.ts +16 -0
  34. package/src/cli/tui/keys.ts +20 -0
  35. package/src/cli/tui/protocolImagePainter.ts +59 -0
  36. package/src/cli/tui/run-tui.tsx +73 -0
  37. package/src/cli/tui/state/DraftsSt.ts +273 -0
  38. package/src/cli/tui/state/EditorSt.ts +289 -0
  39. package/src/cli/tui/state/ExecSt.ts +170 -0
  40. package/src/cli/tui/state/HostSt.ts +107 -0
  41. package/src/cli/tui/state/LorasSt.ts +185 -0
  42. package/src/cli/tui/state/PickerSt.ts +112 -0
  43. package/src/cli/tui/state/PreviewSt.ts +138 -0
  44. package/src/cli/tui/state/QueueSt.ts +59 -0
  45. package/src/cli/tui/state/SettingsSt.ts +73 -0
  46. package/src/cli/tui/state/TreeSt.ts +122 -0
  47. package/src/cli/tui/state/TuiSt.ts +169 -0
  48. package/src/cli/tui/state/WorkflowsSt.ts +92 -0
  49. package/src/cli/tui-env.ts +8 -0
  50. package/src/errors/InvalidPromptError.ts +12 -0
  51. package/src/graph/ComfyNode.ts +403 -0
  52. package/src/graph/ComfyNodeID.ts +28 -0
  53. package/src/graph/ComfyNodeOutput.ts +16 -0
  54. package/src/graph/NodeSlotSize.ts +4 -0
  55. package/src/graph/autoValue.ts +17 -0
  56. package/src/host/ComfyHost.ts +646 -0
  57. package/src/host/ComfyInstallType.ts +15 -0
  58. package/src/host/ComfyManager.ts +232 -0
  59. package/src/host/ComfyUploader.ts +110 -0
  60. package/src/host/ComfyWorkflowBuilder.ts +60 -0
  61. package/src/host/Requirements.ts +55 -0
  62. package/src/host/ResilientWebsocket.ts +147 -0
  63. package/src/host/loraManagerApi.ts +98 -0
  64. package/src/image-utils/_getPngMetadata.ts +53 -0
  65. package/src/image-utils/_getWebpMetadata.ts +38 -0
  66. package/src/image-utils/_parseExifData.ts +53 -0
  67. package/src/index.ts +89 -0
  68. package/src/litegraph/LiteGraphGroup.ts +22 -0
  69. package/src/litegraph/LiteGraphJSON.ts +46 -0
  70. package/src/litegraph/LiteGraphLink.ts +23 -0
  71. package/src/litegraph/LiteGraphLinkID.ts +6 -0
  72. package/src/litegraph/LiteGraphNode.ts +69 -0
  73. package/src/litegraph/LiteGraphNodeInput.ts +27 -0
  74. package/src/litegraph/LiteGraphNodeOutput.ts +23 -0
  75. package/src/litegraph/LiteGraphSlotIndex.ts +6 -0
  76. package/src/litegraph/convertFlowToLiteGraphJSON.ts +114 -0
  77. package/src/manager/ComfyRegistry.ts +124 -0
  78. package/src/manager/generated/KnownComfyCustomNodeName.ts +19280 -0
  79. package/src/manager/generated/KnownComfyPluginTitle.ts +5130 -0
  80. package/src/manager/generated/KnownComfyPluginURL.ts +2589 -0
  81. package/src/manager/generated/KnownModel_Base.ts +126 -0
  82. package/src/manager/generated/KnownModel_FileName.ts +2287 -0
  83. package/src/manager/generated/KnownModel_Name.ts +2287 -0
  84. package/src/manager/generated/KnownModel_SavePath.ts +263 -0
  85. package/src/manager/generated/KnownModel_Type.ts +97 -0
  86. package/src/manager/json/alter-list.json +224 -0
  87. package/src/manager/json/custom-node-list.extra.ts +13 -0
  88. package/src/manager/json/custom-node-list.json +21948 -0
  89. package/src/manager/json/extension-node-map.json +31282 -0
  90. package/src/manager/json/github-stats.json +12602 -0
  91. package/src/manager/json/model-list.extra.ts +26 -0
  92. package/src/manager/json/model-list.json +5052 -0
  93. package/src/manager/loaders/step1_downloadComfyManagerJSONs.ts +56 -0
  94. package/src/manager/loaders/step2_custom-node-list-loader.ts +149 -0
  95. package/src/manager/loaders/step3_extension-node-map-loader.ts +189 -0
  96. package/src/manager/loaders/step4_model-list-loader.ts +159 -0
  97. package/src/manager/script-update-manager.bun.ts +18 -0
  98. package/src/manager/types/ComfyManagerAPIFetchPolicy.ts +9 -0
  99. package/src/manager/types/ComfyManagerAPIModelList.ts +10 -0
  100. package/src/manager/types/ComfyManagerAPIPluginList.ts +11 -0
  101. package/src/manager/types/ComfyManagerFileModelInfo.ts +5 -0
  102. package/src/manager/types/ComfyManagerFilePluginContent.ts +13 -0
  103. package/src/manager/types/ComfyManagerFilePluginList.ts +5 -0
  104. package/src/manager/types/ComfyManagerModelInfo.ts +18 -0
  105. package/src/manager/types/ComfyManagerPluginContentMetadata.ts +16 -0
  106. package/src/manager/types/ComfyManagerPluginEnums.ts +8 -0
  107. package/src/manager/types/ComfyManagerPluginInfo.ts +50 -0
  108. package/src/runner/ComfyExecution.ts +301 -0
  109. package/src/runner/ComfyExecutionStatus.ts +2 -0
  110. package/src/runner/ComfyWorkflow.ts +395 -0
  111. package/src/runner/ComfyWorkflowLayout.ts +96 -0
  112. package/src/runner/ComfyWsApi.ts +159 -0
  113. package/src/runner/MediaImage.ts +262 -0
  114. package/src/sdk-generator/ComfyNodeSchema.ts +79 -0
  115. package/src/sdk-generator/ComfySchema.ts +369 -0
  116. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +95 -0
  117. package/src/sdk-generator/Primitives.ts +76 -0
  118. package/src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts +39 -0
  119. package/src/sdk-generator/_pythonModuleToNamespace.ts +27 -0
  120. package/src/sdk-generator/_toQualifiedNodeKey.ts +5 -0
  121. package/src/sdk-generator/comfy-api-json.ts +16 -0
  122. package/src/sdk-generator/comfyui-sdk-codegen.ts +287 -0
  123. package/src/sdk-generator/comfyui-types.ts +56 -0
  124. package/src/sdk-generator/litegraphToApiRequestPayload.ts +157 -0
  125. package/src/ssh-host-manager/ssh-config-manager.ts +89 -0
  126. package/src/ssh-host-manager/ssh-config.windows.md +32 -0
  127. package/src/ssh-host-manager/ssh-manager.ts +129 -0
  128. package/src/state.ts +136 -0
  129. package/src/types/comfy-sdk.ts +106 -0
  130. package/src/types/index.ts +55 -0
  131. package/src/utils/CodeBuffer.ts +61 -0
  132. package/src/utils/ComfyColors.ts +38 -0
  133. package/src/utils/ansi.ts +26 -0
  134. package/src/utils/ansiImage.ts +36 -0
  135. package/src/utils/bang.ts +39 -0
  136. package/src/utils/deepCopyNaive.ts +1 -0
  137. package/src/utils/downloadFile.ts +77 -0
  138. package/src/utils/escapeJSKey.ts +32 -0
  139. package/src/utils/exhaust.ts +4 -0
  140. package/src/utils/extractErrorMessage.ts +11 -0
  141. package/src/utils/fuzzyMatch.ts +8 -0
  142. package/src/utils/githubRegexes.ts +2 -0
  143. package/src/utils/hashArrayBuffer.ts +6 -0
  144. package/src/utils/log.ts +9 -0
  145. package/src/utils/loraTag.ts +10 -0
  146. package/src/utils/printArkResultInConsole.ts +16 -0
  147. package/src/utils/softValidate.ts +8 -0
  148. package/src/utils/stringifyReadable.ts +32 -0
  149. package/src/utils/toposort.ts +59 -0
  150. package/src/utils/tryExtracting.ts +41 -0
  151. package/src/utils/writeFile.ts +16 -0
  152. package/src/vars/ComfyVars.ts +531 -0
  153. package/src/vars/DefinedWorkflow.ts +112 -0
  154. package/src/vars/loraKeywords.ts +56 -0
  155. package/dist/index.d.mts +0 -74
  156. package/dist/index.mjs +0 -3
  157. package/dist/index.mjs.map +0 -1
  158. package/readme.md +0 -40
@@ -0,0 +1,3340 @@
1
+ import { t as logError } from "./log-CdfgILde.js";
2
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, join, resolve } from "pathe";
4
+ 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";
8
+ import sharp from "sharp";
9
+ import { observer } from "mobx-react-lite";
10
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
11
+ import { spawn } from "node:child_process";
12
+ import { type } from "arktype";
13
+ //#region src/cli/tui-env.ts
14
+ const COMFY_TS_TUI_ENV = "COMFY_TS_TUI";
15
+ //#endregion
16
+ //#region src/vars/loraKeywords.ts
17
+ /**
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).
23
+ */
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
+ }
63
+ }
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
+ /**
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.
142
+ */
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;
414
+ }
415
+ }
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})` : ""}`;
496
+ }
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";
520
+ }
521
+ /**
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.
524
+ */
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
+ };
562
+ //#endregion
563
+ //#region src/cli/tui/findDefinedWorkflow.ts
564
+ /**
565
+ * instanceof first; duck-type fallback covers a second copy of the library in
566
+ * the module graph (linked dev setups, npm dedupe misses)
567
+ */
568
+ function findDefinedWorkflow(mod) {
569
+ const isDefined = (x) => x instanceof DefinedWorkflow || typeof x === "object" && x != null && "spec" in x && typeof x.run === "function" && typeof x.entries === "function";
570
+ return [mod.default, ...Object.values(mod)].find(isDefined) ?? null;
571
+ }
572
+ //#endregion
573
+ //#region src/utils/ansiImage.ts
574
+ /**
575
+ * render an image as truecolor half-block ANSI: each char cell is 1px wide and
576
+ * 2px tall (bg color = top pixel, fg '▄' = bottom pixel). Works in any
577
+ * truecolor terminal and — unlike protocol images (iTerm/kitty/sixel) —
578
+ * survives ink's layout engine. width/height are CHAR CELLS.
579
+ */
580
+ async function imageBufferToAnsi(input, p) {
581
+ const { data, info } = await sharp(input).flatten({ background: p.background ?? "#1e1e1e" }).resize(p.width, p.height * 2, { fit: "inside" }).raw().toBuffer({ resolveWithObject: true });
582
+ const w = info.width;
583
+ const h = info.height;
584
+ const c = info.channels;
585
+ const px = (x, y) => {
586
+ const i = (y * w + x) * c;
587
+ return [
588
+ data[i] ?? 0,
589
+ data[i + 1] ?? 0,
590
+ data[i + 2] ?? 0
591
+ ];
592
+ };
593
+ const rows = [];
594
+ for (let y = 0; y < h; y += 2) {
595
+ let row = "";
596
+ for (let x = 0; x < w; x++) {
597
+ const [tr, tg, tb] = px(x, y);
598
+ const [br, bg, bb] = y + 1 < h ? px(x, y + 1) : px(x, y);
599
+ row += `\x1b[48;2;${tr};${tg};${tb}m\x1b[38;2;${br};${bg};${bb}m▄`;
600
+ }
601
+ rows.push(row + "\x1B[0m");
602
+ }
603
+ return rows.join("\n");
604
+ }
605
+ //#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
+ //#region src/cli/tui/state/PreviewSt.ts
620
+ /** OSC 1337 support: the panel can show REAL images instead of half-blocks */
621
+ function protocolCapable() {
622
+ if (process.env.COMFY_TS_NO_ITERM_IMAGES === "1") return false;
623
+ const term = process.env.TERM_PROGRAM ?? "";
624
+ return term === "iTerm.app" || term === "WezTerm" || term === "vscode" || process.env.LC_TERMINAL === "iTerm2";
625
+ }
626
+ /**
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.
632
+ */
633
+ var PreviewSt = class {
634
+ constructor(st) {
635
+ this.st = st;
636
+ this.outputAnsi = null;
637
+ this.latentAnsi = null;
638
+ this.outputBytes = null;
639
+ this.latentBytes = null;
640
+ this.lastOutputPath = null;
641
+ this._busy = false;
642
+ makeAutoObservable(this, { st: false });
643
+ }
644
+ get mode() {
645
+ return this.st.settings.previewMode;
646
+ }
647
+ get show() {
648
+ return this.mode !== "off";
649
+ }
650
+ /** SettingsSt already downgrades native → ansi on incapable terminals */
651
+ get useNative() {
652
+ return this.mode === "native";
653
+ }
654
+ reset() {
655
+ this.outputAnsi = null;
656
+ this.latentAnsi = null;
657
+ this.outputBytes = null;
658
+ this.latentBytes = null;
659
+ this.lastOutputPath = null;
660
+ }
661
+ /** run boundary: drop the latents so the next run never shows the previous one's */
662
+ clearLatent() {
663
+ this.latentAnsi = null;
664
+ this.latentBytes = null;
665
+ }
666
+ /** re-render the last output in the newly chosen mode */
667
+ onModeChanged() {
668
+ this.outputAnsi = null;
669
+ this.outputBytes = null;
670
+ if (this.mode !== "off" && this.lastOutputPath != null) this.renderOutput(this.lastOutputPath);
671
+ }
672
+ /** what the painter should show RIGHT NOW (native mode only; mirrors the panel's source) */
673
+ get protocolImage() {
674
+ if (!this.useNative || !this.show) return null;
675
+ if (this.st.mode === "overlay-loras") return this.st.loras.previewBytes;
676
+ if (this.st.exec.running && this.latentBytes != null) return this.latentBytes;
677
+ return this.outputBytes;
678
+ }
679
+ get width() {
680
+ return Math.max(24, Math.min(80, this.st.termCols - 68 - this.st.treeWidth));
681
+ }
682
+ get height() {
683
+ return Math.max(10, this.st.termRows - 12);
684
+ }
685
+ async renderOutput(path) {
686
+ this.lastOutputPath = path;
687
+ if (this.mode === "off") return;
688
+ try {
689
+ if (this.useNative) {
690
+ const shrunk = await sharp(path).resize(896, 896, {
691
+ fit: "inside",
692
+ withoutEnlargement: true
693
+ }).png().toBuffer();
694
+ runInAction(() => {
695
+ this.outputBytes = new Uint8Array(shrunk);
696
+ });
697
+ return;
698
+ }
699
+ const rendered = await imageBufferToAnsi(path, {
700
+ width: this.width,
701
+ height: this.height
702
+ });
703
+ runInAction(() => {
704
+ this.outputAnsi = rendered;
705
+ });
706
+ } catch (e) {
707
+ runInAction(() => {
708
+ this.st.exec.notice = `preview: ${extractErrorMessage(e)}`;
709
+ });
710
+ }
711
+ }
712
+ async renderLatent(bytes) {
713
+ if (this.mode === "off") return;
714
+ if (this.useNative) {
715
+ this.latentBytes = bytes;
716
+ return;
717
+ }
718
+ if (this._busy) return;
719
+ this._busy = true;
720
+ try {
721
+ const ansi = await imageBufferToAnsi(bytes, {
722
+ width: this.width,
723
+ height: this.height
724
+ });
725
+ runInAction(() => {
726
+ this.latentAnsi = ansi;
727
+ });
728
+ } catch (e) {
729
+ runInAction(() => {
730
+ this.st.exec.notice = `latent preview: ${extractErrorMessage(e)}`;
731
+ });
732
+ } finally {
733
+ this._busy = false;
734
+ }
735
+ }
736
+ };
737
+ //#endregion
738
+ //#region src/cli/tui/protocolImagePainter.ts
739
+ /**
740
+ * paints the REAL image (OSC 1337) over the preview panel's cell rect.
741
+ * Protocol images cannot go THROUGH ink (layout shreds the escape) and every
742
+ * 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).
745
+ * NOT React: effects only fire for the component that re-rendered, which is
746
+ * why a useEffect painter missed frames (his report: image waited for input).
747
+ */
748
+ function installProtocolImagePainter(st) {
749
+ if (!protocolCapable() || process.stdout.isTTY !== true) return () => {};
750
+ const original = process.stdout.write.bind(process.stdout);
751
+ const paint = () => {
752
+ const bytes = st.preview.protocolImage;
753
+ if (bytes == null) return;
754
+ const pv = st.preview;
755
+ 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`);
758
+ };
759
+ let scheduled = false;
760
+ const schedule = () => {
761
+ if (scheduled) return;
762
+ scheduled = true;
763
+ setImmediate(() => {
764
+ paint();
765
+ scheduled = false;
766
+ });
767
+ };
768
+ const patched = ((chunk, encodingOrCb, cb) => {
769
+ const res = typeof encodingOrCb === "function" ? original(chunk, encodingOrCb) : original(chunk, encodingOrCb, cb);
770
+ schedule();
771
+ return res;
772
+ });
773
+ process.stdout.write = patched;
774
+ const disposeReaction = reaction(() => st.preview.protocolImage, schedule);
775
+ return () => {
776
+ process.stdout.write = original;
777
+ disposeReaction();
778
+ };
779
+ }
780
+ //#endregion
781
+ //#region src/cli/tui/components/OverlayList.tsx
782
+ /** generic modal list: title + rows windowed around the selected index */
783
+ const OverlayList = (p) => {
784
+ const winStart = Math.max(0, Math.min(p.selectedIx - Math.floor(p.lines / 2), p.rows.length - p.lines));
785
+ const visible = p.rows.slice(winStart, winStart + p.lines);
786
+ return /* @__PURE__ */ jsxs(Box, {
787
+ borderStyle: "double",
788
+ paddingX: 1,
789
+ flexDirection: "column",
790
+ children: [
791
+ /* @__PURE__ */ jsx(Text, {
792
+ bold: true,
793
+ children: p.title
794
+ }),
795
+ p.extraHeader,
796
+ winStart > 0 && /* @__PURE__ */ jsx(Text, {
797
+ color: "gray",
798
+ children: "…"
799
+ }),
800
+ visible.map((r) => r.node),
801
+ winStart + p.lines < p.rows.length && /* @__PURE__ */ jsx(Text, {
802
+ color: "gray",
803
+ children: "…"
804
+ }),
805
+ p.footer
806
+ ]
807
+ });
808
+ };
809
+ //#endregion
810
+ //#region src/cli/tui/components/StatusBar.tsx
811
+ /** keys cyan, labels gray — shared by the keybar and overlay footers */
812
+ const KeyHints = (p) => /* @__PURE__ */ jsx(Text, {
813
+ wrap: "wrap",
814
+ children: p.hints.map(([k, label], ix) => /* @__PURE__ */ jsxs(Text, { children: [
815
+ ix > 0 ? /* @__PURE__ */ jsx(Text, {
816
+ color: "gray",
817
+ children: " · "
818
+ }) : null,
819
+ /* @__PURE__ */ jsx(Text, {
820
+ color: "cyan",
821
+ children: k
822
+ }),
823
+ /* @__PURE__ */ jsxs(Text, {
824
+ color: "gray",
825
+ children: [" ", label]
826
+ })
827
+ ] }, `${k}·${label}`))
828
+ });
829
+ const ProgressLine = observer((p) => {
830
+ const s = p.st;
831
+ const e = s.exec;
832
+ const queued = s.queue.remaining;
833
+ if (s.mode === "edit" || s.mode === "overlay-text") return /* @__PURE__ */ jsx(Text, {
834
+ color: "gray",
835
+ children: "editing…"
836
+ });
837
+ if (e.running) {
838
+ const prog = e.progress;
839
+ const width = 16;
840
+ const filled = prog ? Math.round(prog.percent / 100 * width) : 0;
841
+ return /* @__PURE__ */ jsxs(Text, { children: [
842
+ ">> ",
843
+ "[",
844
+ "█".repeat(filled) + "░".repeat(width - filled),
845
+ "] ",
846
+ prog ? `${prog.percent.toFixed(0)}%` : "…",
847
+ prog?.nodeName ? ` · ${prog.nodeName}` : "",
848
+ prog ? ` · ${(prog.elapsedMs / 1e3).toFixed(0)}s` : "",
849
+ queued > 0 ? ` · queue ${queued}` : ""
850
+ ] });
851
+ }
852
+ if (e.error) return /* @__PURE__ */ jsx(Text, {
853
+ color: "red",
854
+ children: e.error
855
+ });
856
+ if (e.notice) return /* @__PURE__ */ jsx(Text, { children: e.notice });
857
+ if (queued > 0) return /* @__PURE__ */ jsxs(Text, {
858
+ color: "yellow",
859
+ children: [queued, " queued on the server"]
860
+ });
861
+ if (e.runCount > 0) return /* @__PURE__ */ jsxs(Text, {
862
+ color: e.lastStatus === "Success" ? "green" : "red",
863
+ children: [
864
+ "run #",
865
+ e.runCount,
866
+ " ",
867
+ e.lastStatus?.toLowerCase()
868
+ ]
869
+ });
870
+ return /* @__PURE__ */ jsx(Text, {
871
+ color: "gray",
872
+ children: "ready — r to run"
873
+ });
874
+ });
875
+ const KIND_KEYS = {
876
+ text: [["⏎/→", "edit"]],
877
+ int: [["⏎/→", "edit"]],
878
+ float: [["⏎/→", "edit"]],
879
+ seed: [
880
+ ["+", "increment"],
881
+ ["-", "decrement"],
882
+ ["?", "random"],
883
+ ["=", "fixed"],
884
+ ["⏎/→", "type value"],
885
+ ["*", "reroll"]
886
+ ],
887
+ toggle: [["⏎/→", "flip"]],
888
+ choice: [["⏎/→", "pick"]],
889
+ size: [["⏎/→", "pick"]],
890
+ loras: [["⏎/→", "select"]]
891
+ };
892
+ /** shown INSIDE the text editor box (TextOverlay footer), not in the keybar */
893
+ const TEXT_EDIT_HINTS = [
894
+ ["⏎", "save"],
895
+ ["⇧⏎/⌥⏎", "newline"],
896
+ ["esc", "cancel"],
897
+ ["⌥⌫", "del word"],
898
+ ["⌥←→", "jump"],
899
+ ["⌘←→/⌃A⌃E", "line ends"],
900
+ ["⌥↑↓", "move line"],
901
+ ["⌘/", "comment"],
902
+ ["⌃U/⌃K", "kill"]
903
+ ];
904
+ const DRAFT_OP_HINTS = [
905
+ ["n", "new"],
906
+ ["e", "rename"],
907
+ ["c", "duplicate"],
908
+ ["x", "delete"]
909
+ ];
910
+ const MODE_KEYS = {
911
+ edit: [
912
+ ["⏎", "apply"],
913
+ ["esc", "cancel"],
914
+ ["⌥⌫/⌃W", "del word"],
915
+ ["⌥←→", "jump"],
916
+ ["⌃A/⌃E", "line ends"],
917
+ ["⌃U/⌃K", "kill"]
918
+ ],
919
+ "overlay-text": TEXT_EDIT_HINTS,
920
+ "overlay-choice": [
921
+ ["⏎", "pick"],
922
+ ["↑↓", "move"],
923
+ ["type", "filter"],
924
+ ["esc", "cancel"]
925
+ ],
926
+ "overlay-size": [
927
+ ["⏎", "pick"],
928
+ ["↑↓", "move"],
929
+ ["type", "filter or WxH"],
930
+ ["esc", "cancel"]
931
+ ],
932
+ "overlay-loras": [
933
+ ["space/⏎", "tick"],
934
+ ["←→", "strength ±0.05"],
935
+ ["type", "filter"],
936
+ ["⌃K", "keyword"],
937
+ ["⌃A", "all"],
938
+ ["⌃N", "none"],
939
+ ["esc", "done"]
940
+ ],
941
+ "overlay-drafts": [
942
+ ["⏎", "load / new"],
943
+ ...DRAFT_OP_HINTS,
944
+ ["↑↓", "move"],
945
+ ["esc", "cancel"]
946
+ ],
947
+ tree: [
948
+ ["⏎", "load"],
949
+ ["↑↓", "move"],
950
+ ["←", "fold"],
951
+ ["→", "unfold / vars"],
952
+ ...DRAFT_OP_HINTS,
953
+ ["t/esc", "back"]
954
+ ],
955
+ host: [
956
+ ["⏎", "run action"],
957
+ ["↑↓", "move"],
958
+ ["h/esc", "back"]
959
+ ]
960
+ };
961
+ /** persistent 2-line keybar: EVERYTHING available right now, always visible */
962
+ const KeyBar = observer((p) => {
963
+ const s = p.st;
964
+ const kind = s.selected?.[1].kind;
965
+ const modeHints = MODE_KEYS[s.mode] ?? [
966
+ ["↑↓", "select"],
967
+ ["←", "tree"],
968
+ ...kind ? KIND_KEYS[kind] ?? [] : []
969
+ ];
970
+ const globalHints = s.mode === "nav" || s.mode === "tree" || s.mode === "host" ? [
971
+ ["r", "run"],
972
+ ["s", "reroll+run"],
973
+ ...s.mode === "nav" ? [["e", "rename draft"]] : [],
974
+ ...s.preview.show ? [] : [["p", "preview off"]],
975
+ ["o", "open image"],
976
+ ...s.mode === "tree" ? [] : [["c/C", "copy wf/api"]],
977
+ ["q", "quit"]
978
+ ] : [["⌃R", "run"], ["esc", "back"]];
979
+ return /* @__PURE__ */ jsxs(Box, {
980
+ flexDirection: "column",
981
+ paddingX: 1,
982
+ children: [s.mode !== "overlay-text" && /* @__PURE__ */ jsx(KeyHints, { hints: modeHints }), /* @__PURE__ */ jsx(KeyHints, { hints: globalHints })]
983
+ });
984
+ });
985
+ //#endregion
986
+ //#region src/cli/tui/components/DraftsOverlay.tsx
987
+ /** modal draft picker: row 0 creates a new draft, the rest load existing ones */
988
+ const DraftsOverlay = observer((p) => {
989
+ const s = p.st;
990
+ const d = s.drafts;
991
+ const rows = [{
992
+ key: "·new·",
993
+ node: /* @__PURE__ */ jsxs(Text, {
994
+ inverse: d.ix === 0,
995
+ children: [d.ix === 0 ? "▸ " : " ", "new draft"]
996
+ }, "·new·")
997
+ }, ...d.list.map((name, ix) => ({
998
+ key: name,
999
+ node: /* @__PURE__ */ jsxs(Text, {
1000
+ inverse: ix + 1 === d.ix,
1001
+ children: [
1002
+ ix + 1 === d.ix ? "▸ " : " ",
1003
+ name === d.active ? "● " : " ",
1004
+ name
1005
+ ]
1006
+ }, name)
1007
+ }))];
1008
+ return /* @__PURE__ */ jsx(OverlayList, {
1009
+ title: /* @__PURE__ */ jsxs(Fragment, { children: ["drafts ", /* @__PURE__ */ jsxs(Text, {
1010
+ color: "gray",
1011
+ children: ["· ", s.wf.spec.id ?? "workflow"]
1012
+ })] }),
1013
+ selectedIx: d.ix,
1014
+ lines: s.overlayLines,
1015
+ rows,
1016
+ footer: /* @__PURE__ */ jsx(KeyHints, { hints: DRAFT_OP_HINTS })
1017
+ });
1018
+ });
1019
+ //#endregion
1020
+ //#region src/cli/tui/components/Header.tsx
1021
+ const HeaderBox = (p) => /* @__PURE__ */ jsxs(Box, {
1022
+ borderStyle: "round",
1023
+ borderColor: "gray",
1024
+ paddingX: 1,
1025
+ flexDirection: "column",
1026
+ flexShrink: 0,
1027
+ children: [p.title != null && /* @__PURE__ */ jsx(Box, {
1028
+ marginTop: -1,
1029
+ children: /* @__PURE__ */ jsx(Text, {
1030
+ color: "gray",
1031
+ children: p.title
1032
+ })
1033
+ }), /* @__PURE__ */ jsx(Box, { children: p.children })]
1034
+ });
1035
+ /** labeled header boxes: brand · (w)orkflow · (d)raft · (h)ost — the keys open each surface */
1036
+ const Header = observer((p) => {
1037
+ const s = p.st;
1038
+ return /* @__PURE__ */ jsxs(Box, {
1039
+ flexDirection: "row",
1040
+ children: [
1041
+ /* @__PURE__ */ jsx(HeaderBox, { children: /* @__PURE__ */ jsx(Text, {
1042
+ bold: true,
1043
+ color: "magenta",
1044
+ children: "comfy-ts"
1045
+ }) }),
1046
+ /* @__PURE__ */ jsx(HeaderBox, {
1047
+ title: "(w)orkflow",
1048
+ children: /* @__PURE__ */ jsx(Text, {
1049
+ bold: true,
1050
+ color: "yellow",
1051
+ children: s.wf.spec.id ?? "workflow"
1052
+ })
1053
+ }),
1054
+ /* @__PURE__ */ jsx(HeaderBox, {
1055
+ title: "(d)raft",
1056
+ children: /* @__PURE__ */ jsx(Text, {
1057
+ bold: true,
1058
+ color: "cyan",
1059
+ children: s.drafts.active ?? "default"
1060
+ })
1061
+ }),
1062
+ /* @__PURE__ */ jsx(HeaderBox, {
1063
+ 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
+ })] })
1079
+ })
1080
+ ]
1081
+ });
1082
+ });
1083
+ //#endregion
1084
+ //#region src/cli/tui/components/HostPanel.tsx
1085
+ /** host stats + maintenance actions (mode 'host', key `h`) */
1086
+ const HostPanel = observer((p) => {
1087
+ const h = p.st.host;
1088
+ return /* @__PURE__ */ jsxs(Box, {
1089
+ borderStyle: "double",
1090
+ paddingX: 1,
1091
+ flexDirection: "column",
1092
+ children: [
1093
+ /* @__PURE__ */ jsxs(Text, {
1094
+ bold: true,
1095
+ children: [
1096
+ "host · ",
1097
+ /* @__PURE__ */ jsx(Text, {
1098
+ color: "green",
1099
+ children: h.host.data.id
1100
+ }),
1101
+ " ",
1102
+ /* @__PURE__ */ jsxs(Text, {
1103
+ color: "gray",
1104
+ children: [
1105
+ "(",
1106
+ h.host.data.host,
1107
+ ":",
1108
+ h.host.data.port,
1109
+ ")"
1110
+ ]
1111
+ })
1112
+ ]
1113
+ }),
1114
+ h.stats.map((row) => /* @__PURE__ */ jsxs(Text, { children: [/* @__PURE__ */ jsx(Text, {
1115
+ color: "gray",
1116
+ children: row.label.padEnd(12)
1117
+ }), row.value] }, row.label)),
1118
+ /* @__PURE__ */ jsx(Text, { children: " " }),
1119
+ h.actions.map((action, ix) => {
1120
+ const sel = ix === h.ix;
1121
+ const busy = h.running === action.key;
1122
+ return /* @__PURE__ */ jsxs(Text, {
1123
+ inverse: sel,
1124
+ color: busy ? "yellow" : void 0,
1125
+ children: [
1126
+ sel ? "▸ " : " ",
1127
+ action.label,
1128
+ busy ? " …" : ""
1129
+ ]
1130
+ }, action.key);
1131
+ })
1132
+ ]
1133
+ });
1134
+ });
1135
+ //#endregion
1136
+ //#region src/cli/tui/components/LorasOverlay.tsx
1137
+ /** modal multi-select: tick/untick loras, filter, bulk ops, step strengths */
1138
+ const LorasOverlay = observer((p) => {
1139
+ const s = p.st;
1140
+ const lo = s.loras;
1141
+ const lv = lo.selectedVar;
1142
+ if (lv == null) return null;
1143
+ const names = lo.filteredNames;
1144
+ return /* @__PURE__ */ jsx(OverlayList, {
1145
+ title: /* @__PURE__ */ jsxs(Fragment, { children: [
1146
+ s.selected?.[1].label ?? s.selected?.[0],
1147
+ " ",
1148
+ /* @__PURE__ */ jsx(Text, {
1149
+ color: "gray",
1150
+ children: lv.display()
1151
+ })
1152
+ ] }),
1153
+ extraHeader: /* @__PURE__ */ jsxs(Text, {
1154
+ color: "yellow",
1155
+ children: [
1156
+ "filter: ",
1157
+ lo.filter,
1158
+ "▌"
1159
+ ]
1160
+ }),
1161
+ selectedIx: lo.ix,
1162
+ lines: s.overlayLines,
1163
+ rows: names.map((name, ix) => {
1164
+ const on = lv.isOn(name);
1165
+ const keyword = getLoraKeyword(name);
1166
+ return {
1167
+ key: name,
1168
+ node: /* @__PURE__ */ jsxs(Text, {
1169
+ inverse: ix === lo.ix,
1170
+ bold: on,
1171
+ color: on ? "green" : "gray",
1172
+ children: [
1173
+ ix === lo.ix ? "▸ " : " ",
1174
+ on ? "✔" : "·",
1175
+ " ",
1176
+ basename(name.replaceAll("\\", "/")),
1177
+ on ? ` ${lv.strengthLabel(name)}` : "",
1178
+ keyword !== "" && /* @__PURE__ */ jsxs(Text, {
1179
+ color: "gray",
1180
+ dimColor: true,
1181
+ bold: false,
1182
+ children: [" kw: ", keyword]
1183
+ })
1184
+ ]
1185
+ }, name)
1186
+ };
1187
+ }),
1188
+ footer: names.length === 0 ? /* @__PURE__ */ jsx(Text, {
1189
+ color: "red",
1190
+ children: "no match"
1191
+ }) : void 0
1192
+ });
1193
+ });
1194
+ //#endregion
1195
+ //#region src/cli/tui/components/PickerOverlays.tsx
1196
+ /** modal option picker: type to fuzzy-filter, ↑/↓ to move, ⏎ to pick */
1197
+ const ChoiceOverlay = observer((p) => {
1198
+ const s = p.st;
1199
+ const pk = s.picker;
1200
+ const options = pk.options;
1201
+ return /* @__PURE__ */ jsx(OverlayList, {
1202
+ title: /* @__PURE__ */ jsxs(Fragment, { children: [
1203
+ "⌥ ",
1204
+ s.selected ? s.selected[1].label ?? s.selected[0] : "",
1205
+ " ",
1206
+ /* @__PURE__ */ jsxs(Text, {
1207
+ color: "gray",
1208
+ children: [
1209
+ "(",
1210
+ options.length,
1211
+ " option",
1212
+ options.length === 1 ? "" : "s",
1213
+ ")"
1214
+ ]
1215
+ })
1216
+ ] }),
1217
+ extraHeader: /* @__PURE__ */ jsxs(Text, {
1218
+ color: "yellow",
1219
+ children: [
1220
+ "filter: ",
1221
+ pk.filter,
1222
+ "▌"
1223
+ ]
1224
+ }),
1225
+ selectedIx: pk.ix,
1226
+ lines: s.overlayLines,
1227
+ rows: options.map((opt, ix) => ({
1228
+ key: opt,
1229
+ node: /* @__PURE__ */ jsxs(Text, {
1230
+ inverse: ix === pk.ix,
1231
+ children: [ix === pk.ix ? "▸ " : " ", opt]
1232
+ }, opt)
1233
+ })),
1234
+ footer: options.length === 0 ? /* @__PURE__ */ jsx(Text, {
1235
+ color: "red",
1236
+ children: "no match"
1237
+ }) : void 0
1238
+ });
1239
+ });
1240
+ /** modal size picker: presets, or type `WxH` and ⏎ for a custom size */
1241
+ const SizeOverlay = observer((p) => {
1242
+ const s = p.st;
1243
+ const pk = s.picker;
1244
+ const options = pk.options;
1245
+ return /* @__PURE__ */ jsx(OverlayList, {
1246
+ title: /* @__PURE__ */ jsxs(Fragment, { children: [
1247
+ "size ",
1248
+ s.selected ? s.selected[1].label ?? s.selected[0] : "",
1249
+ " ",
1250
+ /* @__PURE__ */ jsx(Text, {
1251
+ color: "gray",
1252
+ children: "· type WxH for custom"
1253
+ })
1254
+ ] }),
1255
+ extraHeader: /* @__PURE__ */ jsxs(Text, {
1256
+ color: pk.invalid ? "red" : "yellow",
1257
+ children: [
1258
+ "filter: ",
1259
+ pk.filter,
1260
+ "▌"
1261
+ ]
1262
+ }),
1263
+ selectedIx: pk.ix,
1264
+ lines: s.overlayLines,
1265
+ rows: options.map((opt, ix) => ({
1266
+ key: opt,
1267
+ node: /* @__PURE__ */ jsxs(Text, {
1268
+ inverse: ix === pk.ix,
1269
+ children: [ix === pk.ix ? "▸ " : " ", opt]
1270
+ }, opt)
1271
+ })),
1272
+ footer: options.length === 0 ? /* @__PURE__ */ jsxs(Text, {
1273
+ color: "cyan",
1274
+ children: [
1275
+ "⏎ to use custom size “",
1276
+ pk.filter,
1277
+ "”"
1278
+ ]
1279
+ }) : void 0
1280
+ });
1281
+ });
1282
+ //#endregion
1283
+ //#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.
1285
+ * protocol terminals: the body is BLANK cells — useProtocolImage paints the real image over them */
1286
+ const PreviewPanel = observer((p) => {
1287
+ const s = p.st;
1288
+ const pv = s.preview;
1289
+ 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;
1295
+ return /* @__PURE__ */ jsxs(Box, {
1296
+ borderStyle: "round",
1297
+ paddingX: 1,
1298
+ flexDirection: "column",
1299
+ flexShrink: 0,
1300
+ width: pv.width + 4,
1301
+ children: [/* @__PURE__ */ jsx(Box, {
1302
+ marginTop: -1,
1303
+ children: /* @__PURE__ */ jsxs(Text, {
1304
+ color: "gray",
1305
+ wrap: "truncate",
1306
+ children: ["(p)review · ", label]
1307
+ })
1308
+ }), reserveRect ? Array.from({ length: pv.height }, (_, ix) => /* @__PURE__ */ jsx(Text, { children: " " }, ix)) : content != null ? /* @__PURE__ */ jsx(Text, { children: content }) : /* @__PURE__ */ jsx(Text, {
1309
+ color: "gray",
1310
+ children: placeholder
1311
+ })]
1312
+ });
1313
+ });
1314
+ //#endregion
1315
+ //#region src/cli/tui/components/EditField.tsx
1316
+ const EDIT_WINDOW = 56;
1317
+ /** inline single-line editor rendering (numbers, custom prompts) */
1318
+ const EditField = observer((p) => {
1319
+ const ed = p.st.editor;
1320
+ const cs = [...ed.buffer];
1321
+ const windowStart = Math.max(0, Math.min(ed.cursor - Math.floor(EDIT_WINDOW * .7), cs.length - EDIT_WINDOW));
1322
+ const before = cs.slice(windowStart, ed.cursor).join("");
1323
+ const at = cs[ed.cursor] ?? " ";
1324
+ const after = cs.slice(ed.cursor + 1, windowStart + EDIT_WINDOW).join("");
1325
+ return /* @__PURE__ */ jsxs(Text, {
1326
+ color: ed.invalid ? "red" : "yellow",
1327
+ children: [
1328
+ windowStart > 0 ? "…" : "",
1329
+ before,
1330
+ /* @__PURE__ */ jsx(Text, {
1331
+ inverse: true,
1332
+ children: at
1333
+ }),
1334
+ after,
1335
+ windowStart + EDIT_WINDOW < cs.length ? "…" : ""
1336
+ ]
1337
+ });
1338
+ });
1339
+ //#endregion
1340
+ //#region src/cli/tui/components/PromptOverlay.tsx
1341
+ /** modal name prompt: renders any EditorSt CUSTOM session (new/rename/duplicate draft, …) */
1342
+ const PromptOverlay = observer((p) => {
1343
+ const ed = p.st.editor;
1344
+ return /* @__PURE__ */ jsxs(Box, {
1345
+ borderStyle: "double",
1346
+ paddingX: 1,
1347
+ flexDirection: "column",
1348
+ children: [
1349
+ /* @__PURE__ */ jsx(Text, {
1350
+ bold: true,
1351
+ children: ed.customTitle
1352
+ }),
1353
+ /* @__PURE__ */ jsx(EditField, { st: p.st }),
1354
+ /* @__PURE__ */ jsx(Text, {
1355
+ color: "gray",
1356
+ children: "⏎ apply · esc cancel"
1357
+ })
1358
+ ]
1359
+ });
1360
+ });
1361
+ //#endregion
1362
+ //#region src/cli/tui/components/TextOverlay.tsx
1363
+ /** modal multiline editor: real newlines, caret rendered per code point.
1364
+ * The cursor's LOGICAL line is background-highlighted (word wrap hides line
1365
+ * bounds — the highlight shows exactly what ⌥↑↓ will move); on prompt vars,
1366
+ * `//` comment lines render dim gray, `- ` negative lines red, and the
1367
+ * injected lora keywords show as a magenta chrome line (not editable). */
1368
+ const TextOverlay = observer((p) => {
1369
+ const s = p.st;
1370
+ const ed = s.editor;
1371
+ const winLines = s.overlayLines;
1372
+ const promptVar = s.selected?.[1];
1373
+ const isPrompt = promptVar instanceof PromptVar;
1374
+ const injected = isPrompt ? promptVar.injectedKeywords() : [];
1375
+ const lines = [];
1376
+ let start = 0;
1377
+ for (const text of ed.buffer.split("\n")) {
1378
+ lines.push({
1379
+ text,
1380
+ start
1381
+ });
1382
+ start += [...text].length + 1;
1383
+ }
1384
+ let cursorLine = 0;
1385
+ for (let i = 0; i < lines.length; i++) if ((lines[i]?.start ?? 0) <= ed.cursor) cursorLine = i;
1386
+ const winStart = Math.max(0, Math.min(cursorLine - Math.floor(winLines / 2), lines.length - winLines));
1387
+ const visible = lines.slice(winStart, winStart + winLines);
1388
+ const color = ed.invalid ? "red" : "yellow";
1389
+ return /* @__PURE__ */ jsxs(Box, {
1390
+ borderStyle: "double",
1391
+ paddingX: 1,
1392
+ flexDirection: "column",
1393
+ children: [
1394
+ /* @__PURE__ */ jsx(Text, {
1395
+ bold: true,
1396
+ children: s.selected ? s.selected[1].label ?? s.selected[0] : ""
1397
+ }),
1398
+ injected.length > 0 && /* @__PURE__ */ jsxs(Text, {
1399
+ color: "magenta",
1400
+ wrap: "wrap",
1401
+ children: [
1402
+ "↳ loras: ",
1403
+ injected.join(", "),
1404
+ " ",
1405
+ /* @__PURE__ */ jsx(Text, {
1406
+ dimColor: true,
1407
+ children: "(injected)"
1408
+ })
1409
+ ]
1410
+ }),
1411
+ winStart > 0 && /* @__PURE__ */ jsxs(Text, {
1412
+ color: "gray",
1413
+ children: [
1414
+ "… ",
1415
+ winStart,
1416
+ " more line(s)"
1417
+ ]
1418
+ }),
1419
+ visible.map((line, ix) => {
1420
+ const globalIx = winStart + ix;
1421
+ const comment = isPrompt && PromptVar.isCommentLine(line.text);
1422
+ const negative = isPrompt && !comment && PromptVar.isNegativeLine(line.text);
1423
+ const lineColor = comment ? "gray" : negative ? "red" : color;
1424
+ if (globalIx !== cursorLine) return /* @__PURE__ */ jsx(Text, {
1425
+ color: lineColor,
1426
+ dimColor: comment,
1427
+ children: line.text === "" ? " " : line.text
1428
+ }, globalIx);
1429
+ const cs = [...line.text];
1430
+ const col = ed.cursor - line.start;
1431
+ const before = cs.slice(0, col).join("");
1432
+ const at = cs[col] ?? " ";
1433
+ const after = cs.slice(col + 1).join("");
1434
+ return /* @__PURE__ */ jsxs(Text, {
1435
+ color: lineColor,
1436
+ dimColor: comment,
1437
+ backgroundColor: "blackBright",
1438
+ children: [
1439
+ before,
1440
+ /* @__PURE__ */ jsx(Text, {
1441
+ inverse: true,
1442
+ children: at
1443
+ }),
1444
+ after
1445
+ ]
1446
+ }, globalIx);
1447
+ }),
1448
+ winStart + winLines < lines.length && /* @__PURE__ */ jsxs(Text, {
1449
+ color: "gray",
1450
+ children: [
1451
+ "… ",
1452
+ lines.length - winStart - winLines,
1453
+ " more line(s)"
1454
+ ]
1455
+ }),
1456
+ /* @__PURE__ */ jsx(KeyHints, { hints: TEXT_EDIT_HINTS })
1457
+ ]
1458
+ });
1459
+ });
1460
+ //#endregion
1461
+ //#region src/cli/tui/components/TreePanel.tsx
1462
+ /** persistent left panel: workflows with their drafts nested; `t` (or ← from vars) focuses it */
1463
+ const TreePanel = observer((p) => {
1464
+ const s = p.st;
1465
+ const tree = s.tree;
1466
+ const focused = s.mode === "tree";
1467
+ return /* @__PURE__ */ jsxs(Box, {
1468
+ borderStyle: "round",
1469
+ borderColor: focused ? "cyan" : "gray",
1470
+ flexDirection: "column",
1471
+ flexShrink: 0,
1472
+ width: s.treeWidth,
1473
+ paddingX: 1,
1474
+ children: [
1475
+ /* @__PURE__ */ jsx(Box, {
1476
+ marginTop: -1,
1477
+ children: /* @__PURE__ */ jsx(Text, {
1478
+ color: focused ? "cyan" : "gray",
1479
+ bold: focused,
1480
+ children: "(t)ree"
1481
+ })
1482
+ }),
1483
+ tree.rows.map((row, ix) => {
1484
+ const sel = focused && ix === tree.ix;
1485
+ if (row.kind === "workflow") {
1486
+ const arrow = row.hasDrafts ? row.expanded ? "▾" : "▸" : " ";
1487
+ return /* @__PURE__ */ jsxs(Text, {
1488
+ inverse: sel,
1489
+ color: row.current ? "green" : void 0,
1490
+ wrap: "truncate",
1491
+ children: [
1492
+ arrow,
1493
+ row.current ? "●" : " ",
1494
+ " ",
1495
+ row.name
1496
+ ]
1497
+ }, row.file);
1498
+ }
1499
+ return /* @__PURE__ */ jsxs(Text, {
1500
+ inverse: sel,
1501
+ color: row.active ? "cyan" : "gray",
1502
+ wrap: "truncate",
1503
+ children: [
1504
+ " ",
1505
+ row.active ? "●" : "·",
1506
+ " ",
1507
+ row.draft
1508
+ ]
1509
+ }, `${row.file}·${row.draft}`);
1510
+ }),
1511
+ s.workflows.loading ? /* @__PURE__ */ jsx(Text, {
1512
+ color: "yellow",
1513
+ children: "loading…"
1514
+ }) : null
1515
+ ]
1516
+ });
1517
+ });
1518
+ //#endregion
1519
+ //#region src/cli/tui/components/VarsPanel.tsx
1520
+ const VALUE_CAP = 300;
1521
+ /** prompt value cell: magenta injected-keywords chrome line (not part of the
1522
+ * text), `//` comments dim gray, `- ` negative lines red */
1523
+ const PromptCell = observer((p) => {
1524
+ const injected = p.varDef.injectedKeywords();
1525
+ return /* @__PURE__ */ jsxs(Box, {
1526
+ flexDirection: "column",
1527
+ children: [injected.length > 0 && /* @__PURE__ */ jsxs(Text, {
1528
+ color: "magenta",
1529
+ wrap: "wrap",
1530
+ children: ["↳ loras: ", injected.join(", ")]
1531
+ }), p.value.split("\n").map((line, ix) => {
1532
+ const comment = PromptVar.isCommentLine(line);
1533
+ const negative = !comment && PromptVar.isNegativeLine(line);
1534
+ return /* @__PURE__ */ jsx(Text, {
1535
+ color: comment ? "gray" : negative ? "red" : "cyan",
1536
+ dimColor: comment,
1537
+ wrap: "wrap",
1538
+ children: line === "" ? " " : line
1539
+ }, ix);
1540
+ })]
1541
+ });
1542
+ });
1543
+ const VarRow = observer((p) => {
1544
+ const editing = p.selected && p.st.mode === "edit" && !p.st.editor.isCustom;
1545
+ const label = p.varDef.label ?? p.name;
1546
+ const raw = p.varDef.display();
1547
+ const value = raw.length > VALUE_CAP ? `${raw.slice(0, VALUE_CAP)}…` : raw;
1548
+ return /* @__PURE__ */ jsxs(Box, {
1549
+ flexDirection: "row",
1550
+ children: [
1551
+ /* @__PURE__ */ jsx(Box, {
1552
+ width: p.labelW,
1553
+ flexShrink: 0,
1554
+ children: /* @__PURE__ */ jsxs(Text, {
1555
+ inverse: p.selected,
1556
+ children: [p.selected ? "▸ " : " ", label]
1557
+ })
1558
+ }),
1559
+ /* @__PURE__ */ jsx(Box, {
1560
+ width: 9,
1561
+ flexShrink: 0,
1562
+ children: /* @__PURE__ */ jsxs(Text, {
1563
+ color: "gray",
1564
+ children: [
1565
+ "[",
1566
+ p.varDef.kind,
1567
+ "]"
1568
+ ]
1569
+ })
1570
+ }),
1571
+ /* @__PURE__ */ jsx(Box, {
1572
+ flexGrow: 1,
1573
+ children: editing ? /* @__PURE__ */ jsx(EditField, { st: p.st }) : p.varDef instanceof PromptVar ? /* @__PURE__ */ jsx(PromptCell, {
1574
+ varDef: p.varDef,
1575
+ value
1576
+ }) : /* @__PURE__ */ jsx(Text, {
1577
+ color: "cyan",
1578
+ wrap: "wrap",
1579
+ children: value
1580
+ })
1581
+ })
1582
+ ]
1583
+ });
1584
+ });
1585
+ const VarsPanel = observer((p) => {
1586
+ const s = p.st;
1587
+ const labelW = Math.max(6, ...s.entries.map(([name, v]) => (v.label ?? name).length)) + 3;
1588
+ const focused = s.mode === "nav" || s.mode === "edit";
1589
+ return /* @__PURE__ */ jsxs(Box, {
1590
+ borderStyle: "round",
1591
+ borderColor: focused ? "cyan" : "gray",
1592
+ paddingX: 1,
1593
+ flexDirection: "column",
1594
+ children: [/* @__PURE__ */ jsx(Box, {
1595
+ marginTop: -1,
1596
+ children: /* @__PURE__ */ jsx(Text, {
1597
+ color: focused ? "cyan" : "gray",
1598
+ bold: focused,
1599
+ children: "(v)ars"
1600
+ })
1601
+ }), s.entries.map(([name, varDef], ix) => /* @__PURE__ */ jsx(VarRow, {
1602
+ name,
1603
+ varDef,
1604
+ selected: ix === s.selIx,
1605
+ labelW,
1606
+ st: s
1607
+ }, name))]
1608
+ });
1609
+ });
1610
+ //#endregion
1611
+ //#region src/cli/tui/keys.ts
1612
+ /**
1613
+ * xterm modifyOtherKeys (vscode/xterm.js — enabled by run-tui via `CSI > 4;1 m`)
1614
+ * encodes modified ⏎ as `CSI 27;<mods>;13~`. ink 7 leaves that sequence
1615
+ * unparsed: it reaches useInput as the LITERAL input `[27;<mods>;13~` with no
1616
+ * key flags, which would otherwise be typed into editors/filters. Translate it
1617
+ * back into return + modifier bits (mods is xterm's modifier-1 bitfield:
1618
+ * 1 shift · 2 alt · 4 ctrl · 8 meta — alt|meta fold into ink's `meta`, same
1619
+ * mask ink uses for legacy fn-keys). Kitty-protocol terminals never hit this:
1620
+ * their `CSI 13;2u` is parsed natively by ink. Returns null when `input` is
1621
+ * not a modified enter.
1622
+ */
1623
+ function parseModifyOtherKeysEnter(input) {
1624
+ const m = /^\[27;(\d+);13~$/.exec(input);
1625
+ if (m == null) return null;
1626
+ const mods = Number(m[1]) - 1;
1627
+ return {
1628
+ return: true,
1629
+ shift: (mods & 1) !== 0,
1630
+ meta: (mods & 10) !== 0,
1631
+ ctrl: (mods & 4) !== 0
1632
+ };
1633
+ }
1634
+ //#endregion
1635
+ //#region src/cli/tui/components/TuiApp.tsx
1636
+ const TuiApp = observer((p) => {
1637
+ const app = useApp();
1638
+ const s = p.st;
1639
+ useInput((input, key) => {
1640
+ const modEnter = parseModifyOtherKeysEnter(input);
1641
+ if (modEnter != null) {
1642
+ input = "";
1643
+ key = {
1644
+ ...key,
1645
+ ...modEnter
1646
+ };
1647
+ }
1648
+ if (key.ctrl && input === "r") return void s.exec.run();
1649
+ if (s.mode === "edit" || s.mode === "overlay-text") {
1650
+ const ed = s.editor;
1651
+ const multi = s.mode === "overlay-text";
1652
+ if (key.escape) return ed.cancel();
1653
+ if (multi && key.ctrl && input === "s") return ed.commitMultiline();
1654
+ if (multi && key.return && (key.shift || key.meta)) return ed.newline();
1655
+ if (key.return) return multi ? ed.commitMultiline() : ed.commitInline();
1656
+ if (key.meta && (key.backspace || key.delete) || key.ctrl && input === "w") return ed.deleteWordBack();
1657
+ if (key.backspace || key.delete) return ed.backspace();
1658
+ if (key.meta && key.leftArrow) return ed.wordLeft();
1659
+ if (key.meta && key.rightArrow) return ed.wordRight();
1660
+ if (key.meta && input === "b") return ed.wordLeft();
1661
+ if (key.meta && input === "f") return ed.wordRight();
1662
+ if (key.super && key.leftArrow || key.home || key.ctrl && input === "a") return ed.lineHome();
1663
+ if (key.super && key.rightArrow || key.end || key.ctrl && input === "e") return ed.lineEnd();
1664
+ if (multi && key.meta && key.upArrow) return ed.moveLine(-1);
1665
+ if (multi && key.meta && key.downArrow) return ed.moveLine(1);
1666
+ if (multi && input === "/" && (key.super || key.ctrl || key.meta)) return ed.toggleComment();
1667
+ if (multi && input.length === 1 && input.charCodeAt(0) === 31) return ed.toggleComment();
1668
+ if (key.leftArrow) return ed.cursorLeft();
1669
+ if (key.rightArrow) return ed.cursorRight();
1670
+ if (multi && key.upArrow) return ed.cursorUp();
1671
+ if (multi && key.downArrow) return ed.cursorDown();
1672
+ if (key.ctrl && input === "u") return ed.killToStart();
1673
+ if (key.ctrl && input === "k") return ed.killToEnd();
1674
+ if (input && !key.ctrl && !key.meta) return ed.input(input);
1675
+ return;
1676
+ }
1677
+ if (s.mode === "overlay-choice" || s.mode === "overlay-size") {
1678
+ const pk = s.picker;
1679
+ if (key.escape) return s.editor.cancel();
1680
+ if (key.return) return pk.commit();
1681
+ if (key.upArrow) return pk.move(-1);
1682
+ if (key.downArrow) return pk.move(1);
1683
+ if (key.meta && (key.backspace || key.delete) || key.ctrl && input === "w") return pk.filterDeleteWord();
1684
+ if (key.backspace || key.delete) return pk.filterBackspace();
1685
+ if (input && !key.ctrl && !key.meta) return pk.filterInput(input);
1686
+ return;
1687
+ }
1688
+ if (s.mode === "overlay-loras") {
1689
+ const lo = s.loras;
1690
+ if (key.escape) return s.editor.cancel();
1691
+ if (key.ctrl && input === "a") return lo.setAll(true);
1692
+ if (key.ctrl && input === "n") return lo.setAll(false);
1693
+ if (key.ctrl && input === "k") return lo.beginKeyword();
1694
+ if (key.return || input === " ") return lo.toggle();
1695
+ if (key.upArrow) return lo.move(-1);
1696
+ if (key.downArrow) return lo.move(1);
1697
+ if (key.leftArrow) return lo.adjust(-.05);
1698
+ if (key.rightArrow) return lo.adjust(.05);
1699
+ if (key.meta && (key.backspace || key.delete) || key.ctrl && input === "w") return lo.filterDeleteWord();
1700
+ if (key.backspace || key.delete) return lo.filterBackspace();
1701
+ if (input && !key.ctrl && !key.meta) return lo.filterInput(input);
1702
+ return;
1703
+ }
1704
+ if (s.mode === "tree") {
1705
+ const tr = s.tree;
1706
+ if (key.escape || input === "t") return tr.blur();
1707
+ if (key.return || input === " ") return void tr.commit();
1708
+ if (key.upArrow) return tr.move(-1);
1709
+ if (key.downArrow) return tr.move(1);
1710
+ if (key.leftArrow) return tr.fold();
1711
+ if (key.rightArrow) return tr.unfold();
1712
+ if (input === "v") return tr.blur();
1713
+ if (input === "n") return tr.promptNewDraft();
1714
+ if (input === "e") return tr.draftOp("rename");
1715
+ if (input === "c") return tr.draftOp("duplicate");
1716
+ if (input === "x") return tr.draftOp("delete");
1717
+ if (input === "r") return void s.exec.run();
1718
+ if (input === "s") return s.exec.randomizeSeedAndRun();
1719
+ if (input === "d") return s.drafts.begin();
1720
+ if (input === "h") return s.host.begin();
1721
+ if (input === "p") return s.settings.cyclePreviewMode();
1722
+ if (input === "o") return s.exec.openLastOutput();
1723
+ if (input === "q") {
1724
+ s.onExit();
1725
+ return app.exit();
1726
+ }
1727
+ return;
1728
+ }
1729
+ if (s.mode === "host") {
1730
+ const h = s.host;
1731
+ if (key.escape || input === "h" || input === "v") return h.blur();
1732
+ if (key.return || input === " ") return void h.commit();
1733
+ if (key.upArrow) return h.move(-1);
1734
+ if (key.downArrow) return h.move(1);
1735
+ if (input === "q") {
1736
+ s.onExit();
1737
+ return app.exit();
1738
+ }
1739
+ return;
1740
+ }
1741
+ if (s.mode === "overlay-drafts") {
1742
+ const d = s.drafts;
1743
+ if (key.escape) return s.editor.cancel();
1744
+ if (key.return) return d.commit();
1745
+ if (key.upArrow) return d.move(-1);
1746
+ if (key.downArrow) return d.move(1);
1747
+ if (input === "n") return d.promptNew("overlay-drafts");
1748
+ if (input === "e" && d.selectedName != null) return d.promptRename(d.selectedName, void 0, "overlay-drafts");
1749
+ if (input === "c" && d.selectedName != null) return d.promptDuplicate(d.selectedName, void 0, "overlay-drafts");
1750
+ if (input === "x" && d.selectedName != null) {
1751
+ d.deleteDraft(d.selectedName);
1752
+ return d.begin();
1753
+ }
1754
+ return;
1755
+ }
1756
+ if (input === "q") {
1757
+ s.onExit();
1758
+ return app.exit();
1759
+ }
1760
+ if (key.upArrow) return s.moveSel(-1);
1761
+ if (key.downArrow) return s.moveSel(1);
1762
+ if (key.leftArrow) return s.tree.focus();
1763
+ if (key.rightArrow || key.return || input === " ") return s.activate();
1764
+ if (s.navKey(input)) return;
1765
+ if (input === "e") return s.drafts.beginRename();
1766
+ if (input === "r") return void s.exec.run();
1767
+ if (input === "s") return s.exec.randomizeSeedAndRun();
1768
+ if (input === "t" || input === "w") return s.tree.focus();
1769
+ if (input === "h") return s.host.begin();
1770
+ if (input === "d") return s.drafts.begin();
1771
+ if (input === "p") return s.settings.cyclePreviewMode();
1772
+ if (input === "o") return s.exec.openLastOutput();
1773
+ if (input === "c") return void s.exec.copyWorkflowJson();
1774
+ if (input === "C") return void s.exec.copyApiJson();
1775
+ }, { isActive: useStdin().isRawModeSupported === true });
1776
+ return /* @__PURE__ */ jsxs(Box, {
1777
+ flexDirection: "column",
1778
+ minHeight: s.termRows - 1,
1779
+ children: [
1780
+ /* @__PURE__ */ jsx(Header, { st: s }),
1781
+ /* @__PURE__ */ jsxs(Box, {
1782
+ flexDirection: "row",
1783
+ flexGrow: 1,
1784
+ children: [
1785
+ /* @__PURE__ */ jsx(TreePanel, { st: s }),
1786
+ /* @__PURE__ */ jsxs(Box, {
1787
+ flexDirection: "column",
1788
+ flexGrow: 1,
1789
+ children: [
1790
+ 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 }),
1791
+ /* @__PURE__ */ jsx(Box, {
1792
+ paddingX: 1,
1793
+ children: /* @__PURE__ */ jsx(ProgressLine, { st: s })
1794
+ }),
1795
+ s.exec.outputs.length > 0 && /* @__PURE__ */ jsx(Box, {
1796
+ borderStyle: "round",
1797
+ paddingX: 1,
1798
+ flexDirection: "column",
1799
+ children: s.exec.outputs.map((o) => /* @__PURE__ */ jsxs(Text, {
1800
+ color: "green",
1801
+ wrap: "truncate",
1802
+ children: [
1803
+ basename(o),
1804
+ " ",
1805
+ /* @__PURE__ */ jsx(Text, {
1806
+ color: "gray",
1807
+ children: o
1808
+ })
1809
+ ]
1810
+ }, o))
1811
+ })
1812
+ ]
1813
+ }),
1814
+ s.preview.show && /* @__PURE__ */ jsx(PreviewPanel, { st: s })
1815
+ ]
1816
+ }),
1817
+ /* @__PURE__ */ jsx(KeyBar, { st: s })
1818
+ ]
1819
+ });
1820
+ });
1821
+ //#endregion
1822
+ //#region src/cli/tui/state/DraftsSt.ts
1823
+ /** module basename (`01-txt2img`) keys the draft folder — knowable for EVERY tree file without importing it */
1824
+ function draftKeyForFile(file) {
1825
+ return basename(file).replace(/\.cflow\.tsx?$/, "");
1826
+ }
1827
+ function draftsDirForFile(file) {
1828
+ return comfyts.resolveFromDrafts(draftKeyForFile(file));
1829
+ }
1830
+ function listDraftsInDir(dir) {
1831
+ if (!existsSync(dir)) return [];
1832
+ return readdirSync(dir).filter((f) => f.endsWith(".json")).map((f) => f.slice(0, -5)).sort();
1833
+ }
1834
+ /** draft names stored for a workflow module (fs read — pair with DraftsSt.version for reactivity) */
1835
+ function listDraftsForFile(file) {
1836
+ return listDraftsInDir(draftsDirForFile(file));
1837
+ }
1838
+ /**
1839
+ * named var-value snapshots at `.comfy-ts/drafts/<module-basename>/<name>.json`
1840
+ * (LOCAL state, gitignored). The active draft autosaves debounced; the TUI is
1841
+ * ALWAYS in a draft (`default` unless another one is activated).
1842
+ */
1843
+ var DraftsSt = class {
1844
+ constructor(st) {
1845
+ this.st = st;
1846
+ this.active = null;
1847
+ this.list = [];
1848
+ this.ix = 0;
1849
+ this.version = 0;
1850
+ makeAutoObservable(this, { st: false });
1851
+ this.st.disposers.push(reaction(() => this.active == null ? null : JSON.stringify(this.snapshot()), (json) => {
1852
+ if (json != null && this.active != null) this.write(this.active, json);
1853
+ }, { delay: 300 }));
1854
+ }
1855
+ get dir() {
1856
+ const cur = this.st.workflows.currentPath;
1857
+ return cur != null ? draftsDirForFile(cur) : comfyts.resolveFromDrafts(this.st.wf.spec.id ?? "workflow");
1858
+ }
1859
+ snapshot() {
1860
+ return Object.fromEntries(this.st.entries.map(([k, varDef]) => [k, varDef.toJSON()]));
1861
+ }
1862
+ write(name, json) {
1863
+ const path = join(this.dir, `${name}.json`);
1864
+ mkdirSync(dirname(path), { recursive: true });
1865
+ writeFileSync(path, json);
1866
+ this.version++;
1867
+ }
1868
+ /** module key of the currently loaded workflow (settings.lastDraft is keyed by it) */
1869
+ get moduleKey() {
1870
+ const cur = this.st.workflows.currentPath;
1871
+ return cur != null ? draftKeyForFile(cur) : this.st.wf.spec.id ?? "workflow";
1872
+ }
1873
+ /** switch to a draft: load its stored values when the file exists, else it starts from current values */
1874
+ activate(name) {
1875
+ this.active = null;
1876
+ const path = join(this.dir, `${name}.json`);
1877
+ if (existsSync(path)) try {
1878
+ const values = JSON.parse(readFileSync(path, "utf8"));
1879
+ for (const [k, varDef] of this.st.entries) if (k in values) varDef.loadJSON(values[k]);
1880
+ } catch (e) {
1881
+ this.st.exec.error = extractErrorMessage(e);
1882
+ }
1883
+ this.active = name;
1884
+ this.st.settings.rememberDraft(this.moduleKey, name);
1885
+ }
1886
+ /** open the draft this workflow was last in (settings), else 'default' */
1887
+ activateRemembered() {
1888
+ const remembered = this.st.settings.lastDraft[this.moduleKey];
1889
+ if (remembered != null && remembered !== "default" && existsSync(join(this.dir, `${remembered}.json`))) this.activate(remembered);
1890
+ else this.activate("default");
1891
+ }
1892
+ /** every workflow starts in a draft; kept for callers that want 'default' explicitly */
1893
+ activateDefault() {
1894
+ this.activate("default");
1895
+ }
1896
+ dirFor(file) {
1897
+ return file != null ? draftsDirForFile(file) : this.dir;
1898
+ }
1899
+ /** true when ops on `file` touch the ACTIVE draft bookkeeping */
1900
+ isCurrent(file) {
1901
+ return file == null || file === this.st.workflows.currentPath;
1902
+ }
1903
+ validName(rawName) {
1904
+ const name = rawName.trim();
1905
+ if (/^[\w][\w .-]*$/.test(name)) return name;
1906
+ this.st.exec.notice = `invalid draft name: '${rawName}'`;
1907
+ return null;
1908
+ }
1909
+ /** create a NEW draft from the current var values (current workflow only) */
1910
+ createNamed(rawName) {
1911
+ const name = this.validName(rawName);
1912
+ if (name == null) return false;
1913
+ if (existsSync(join(this.dir, `${name}.json`))) {
1914
+ this.st.exec.notice = `draft '${name}' already exists`;
1915
+ return false;
1916
+ }
1917
+ this.write(name, JSON.stringify(this.snapshot(), null, 2));
1918
+ this.active = name;
1919
+ this.st.settings.rememberDraft(this.moduleKey, name);
1920
+ this.st.exec.notice = `new draft: ${name} (autosaves)`;
1921
+ return true;
1922
+ }
1923
+ rename(oldName, rawName, file) {
1924
+ const newName = this.validName(rawName);
1925
+ if (newName == null) return false;
1926
+ if (newName === oldName) return true;
1927
+ const dir = this.dirFor(file);
1928
+ const to = join(dir, `${newName}.json`);
1929
+ if (existsSync(to)) {
1930
+ this.st.exec.notice = `draft '${newName}' already exists`;
1931
+ return false;
1932
+ }
1933
+ const from = join(dir, `${oldName}.json`);
1934
+ if (existsSync(from)) renameSync(from, to);
1935
+ else if (this.isCurrent(file)) this.write(newName, JSON.stringify(this.snapshot(), null, 2));
1936
+ if (this.isCurrent(file) && this.active === oldName) {
1937
+ this.active = newName;
1938
+ this.st.settings.rememberDraft(this.moduleKey, newName);
1939
+ }
1940
+ this.version++;
1941
+ this.st.exec.notice = `draft renamed: ${oldName} → ${newName}`;
1942
+ return true;
1943
+ }
1944
+ duplicate(name, rawName, file) {
1945
+ const newName = this.validName(rawName);
1946
+ if (newName == null) return false;
1947
+ const dir = this.dirFor(file);
1948
+ const from = join(dir, `${name}.json`);
1949
+ const to = join(dir, `${newName}.json`);
1950
+ if (!existsSync(from)) {
1951
+ this.st.exec.notice = `draft '${name}' has no file yet (edit a var first)`;
1952
+ return false;
1953
+ }
1954
+ if (existsSync(to)) {
1955
+ this.st.exec.notice = `draft '${newName}' already exists`;
1956
+ return false;
1957
+ }
1958
+ copyFileSync(from, to);
1959
+ this.version++;
1960
+ this.st.exec.notice = `draft duplicated: ${name} → ${newName}`;
1961
+ return true;
1962
+ }
1963
+ deleteDraft(name, file) {
1964
+ const path = join(this.dirFor(file), `${name}.json`);
1965
+ if (existsSync(path)) rmSync(path);
1966
+ this.version++;
1967
+ if (this.isCurrent(file) && this.active === name) this.activateDefault();
1968
+ this.st.exec.notice = `draft deleted: ${name}`;
1969
+ }
1970
+ promptNew(returnMode = "nav") {
1971
+ this.st.editor.beginCustom({
1972
+ title: "new draft (from current values)",
1973
+ initial: "",
1974
+ onCommit: (raw) => {
1975
+ const ok = this.createNamed(raw);
1976
+ if (ok && returnMode === "overlay-drafts") this.begin();
1977
+ return ok;
1978
+ },
1979
+ returnMode
1980
+ });
1981
+ }
1982
+ promptRename(name, file, returnMode = "nav") {
1983
+ this.st.editor.beginCustom({
1984
+ title: `rename draft '${name}'`,
1985
+ initial: name,
1986
+ onCommit: (raw) => {
1987
+ const ok = this.rename(name, raw, file);
1988
+ if (ok && returnMode === "overlay-drafts") this.begin();
1989
+ return ok;
1990
+ },
1991
+ returnMode
1992
+ });
1993
+ }
1994
+ promptDuplicate(name, file, returnMode = "nav") {
1995
+ this.st.editor.beginCustom({
1996
+ title: `duplicate draft '${name}'`,
1997
+ initial: `${name}-copy`,
1998
+ onCommit: (raw) => {
1999
+ const ok = this.duplicate(name, raw, file);
2000
+ if (ok && returnMode === "overlay-drafts") this.begin();
2001
+ return ok;
2002
+ },
2003
+ returnMode
2004
+ });
2005
+ }
2006
+ /** f2 in nav: rename the ACTIVE draft */
2007
+ beginRename() {
2008
+ this.promptRename(this.active ?? "default");
2009
+ }
2010
+ begin() {
2011
+ this.list = listDraftsInDir(this.dir);
2012
+ this.st.mode = "overlay-drafts";
2013
+ const ix = this.active == null ? -1 : this.list.indexOf(this.active);
2014
+ this.ix = ix === -1 ? 0 : ix + 1;
2015
+ }
2016
+ move(delta) {
2017
+ const len = this.list.length + 1;
2018
+ this.ix = (this.ix + delta + len) % len;
2019
+ }
2020
+ /** draft name under the overlay cursor (row 0 is 'new') */
2021
+ get selectedName() {
2022
+ return this.ix === 0 ? null : this.list[this.ix - 1] ?? null;
2023
+ }
2024
+ commit() {
2025
+ if (this.ix === 0) return this.promptNew("overlay-drafts");
2026
+ const name = this.selectedName;
2027
+ if (name == null) return;
2028
+ this.activate(name);
2029
+ this.st.exec.notice = `draft: ${name} (autosaves)`;
2030
+ this.st.mode = "nav";
2031
+ }
2032
+ };
2033
+ //#endregion
2034
+ //#region src/cli/tui/state/EditorSt.ts
2035
+ /**
2036
+ * line/multiline editor. Inline mode ('edit') escapes newlines into a single
2037
+ * line (numbers only, in practice); multiline mode ('overlay-text') keeps REAL
2038
+ * newlines. All ops are code-point based so emoji/astral input never splits a
2039
+ * surrogate pair (flag/ZWJ clusters may still count as several points).
2040
+ */
2041
+ var EditorSt = class EditorSt {
2042
+ constructor(st) {
2043
+ this.st = st;
2044
+ this.buffer = "";
2045
+ this.cursor = 0;
2046
+ this.invalid = false;
2047
+ this.customCommit = null;
2048
+ this.customTitle = "";
2049
+ this.returnMode = "nav";
2050
+ makeAutoObservable(this, { st: false });
2051
+ }
2052
+ /** raw value -> escaped single-line buffer form (order matters: backslashes first) */
2053
+ static escapeForBuffer(raw) {
2054
+ return raw.replaceAll("\\", "\\\\").replaceAll("\r\n", "\n").replaceAll("\r", "\n").replaceAll("\n", "\\n");
2055
+ }
2056
+ /** escaped buffer form -> raw value */
2057
+ static unescapeBuffer(buffer) {
2058
+ return buffer.replace(/\\\\|\\n/g, (m) => m === "\\\\" ? "\\" : "\n");
2059
+ }
2060
+ get isCustom() {
2061
+ return this.customCommit != null;
2062
+ }
2063
+ /** inline single-line editor (numbers, seed `mode value`) */
2064
+ beginInline() {
2065
+ const sel = this.st.selected?.[1];
2066
+ if (sel == null) return;
2067
+ this.st.mode = "edit";
2068
+ this.buffer = EditorSt.escapeForBuffer(sel.toEditBuffer());
2069
+ this.cursor = [...this.buffer].length;
2070
+ this.invalid = false;
2071
+ }
2072
+ /** modal prompt over an arbitrary string (rendered as PromptOverlay);
2073
+ * onCommit returns false to keep editing (invalid); esc/apply lands on returnMode */
2074
+ beginCustom(p) {
2075
+ this.st.mode = "edit";
2076
+ this.customCommit = p.onCommit;
2077
+ this.customTitle = p.title;
2078
+ this.returnMode = p.returnMode ?? "nav";
2079
+ this.buffer = EditorSt.escapeForBuffer(p.initial);
2080
+ this.cursor = [...this.buffer].length;
2081
+ this.invalid = false;
2082
+ }
2083
+ /** modal multiline editor (text vars), no escaping */
2084
+ beginMultiline() {
2085
+ const sel = this.st.selected?.[1];
2086
+ if (sel == null) return;
2087
+ this.st.mode = "overlay-text";
2088
+ this.buffer = String(sel.value);
2089
+ this.cursor = [...this.buffer].length;
2090
+ this.invalid = false;
2091
+ }
2092
+ commitInline() {
2093
+ if (this.customCommit != null) {
2094
+ if (this.customCommit(EditorSt.unescapeBuffer(this.buffer))) {
2095
+ this.customCommit = null;
2096
+ this.st.mode = this.returnMode;
2097
+ } else this.invalid = true;
2098
+ return;
2099
+ }
2100
+ const sel = this.st.selected?.[1];
2101
+ if (sel == null) return;
2102
+ if (sel.parse(EditorSt.unescapeBuffer(this.buffer))) this.st.mode = "nav";
2103
+ else this.invalid = true;
2104
+ }
2105
+ commitMultiline() {
2106
+ const sel = this.st.selected?.[1];
2107
+ if (sel == null) return;
2108
+ if (sel.parse(this.buffer)) this.st.mode = "nav";
2109
+ else this.invalid = true;
2110
+ }
2111
+ cancel() {
2112
+ this.st.mode = this.customCommit != null ? this.returnMode : "nav";
2113
+ this.invalid = false;
2114
+ this.customCommit = null;
2115
+ }
2116
+ get chars() {
2117
+ return [...this.buffer];
2118
+ }
2119
+ setChars(cs, cursor) {
2120
+ this.buffer = cs.join("");
2121
+ this.cursor = Math.max(0, Math.min(cursor, cs.length));
2122
+ this.invalid = false;
2123
+ }
2124
+ input(chunk) {
2125
+ const insert = [...this.st.mode === "overlay-text" ? chunk.replaceAll("\r\n", "\n").replaceAll("\r", "\n") : EditorSt.escapeForBuffer(chunk)];
2126
+ const cs = this.chars;
2127
+ cs.splice(this.cursor, 0, ...insert);
2128
+ this.setChars(cs, this.cursor + insert.length);
2129
+ }
2130
+ backspace() {
2131
+ if (this.cursor === 0) return;
2132
+ const cs = this.chars;
2133
+ cs.splice(this.cursor - 1, 1);
2134
+ this.setChars(cs, this.cursor - 1);
2135
+ }
2136
+ newline() {
2137
+ const cs = this.chars;
2138
+ cs.splice(this.cursor, 0, "\n");
2139
+ this.setChars(cs, this.cursor + 1);
2140
+ }
2141
+ /** index of the start of the word left of the cursor */
2142
+ wordBoundLeft() {
2143
+ const cs = this.chars;
2144
+ let i = this.cursor;
2145
+ while (i > 0 && /\s/.test(cs[i - 1] ?? "")) i--;
2146
+ while (i > 0 && !/\s/.test(cs[i - 1] ?? "")) i--;
2147
+ return i;
2148
+ }
2149
+ /** index just past the word right of the cursor */
2150
+ wordBoundRight() {
2151
+ const cs = this.chars;
2152
+ let i = this.cursor;
2153
+ while (i < cs.length && /\s/.test(cs[i] ?? "")) i++;
2154
+ while (i < cs.length && !/\s/.test(cs[i] ?? "")) i++;
2155
+ return i;
2156
+ }
2157
+ /** alt+backspace / ctrl+w */
2158
+ deleteWordBack() {
2159
+ const from = this.wordBoundLeft();
2160
+ const cs = this.chars;
2161
+ cs.splice(from, this.cursor - from);
2162
+ this.setChars(cs, from);
2163
+ }
2164
+ /** ctrl+u: clear from start to cursor */
2165
+ killToStart() {
2166
+ this.setChars(this.chars.slice(this.cursor), 0);
2167
+ }
2168
+ /** ctrl+k: clear from cursor to end */
2169
+ killToEnd() {
2170
+ this.setChars(this.chars.slice(0, this.cursor), this.cursor);
2171
+ }
2172
+ cursorLeft() {
2173
+ if (this.cursor > 0) this.cursor--;
2174
+ }
2175
+ cursorRight() {
2176
+ if (this.cursor < this.chars.length) this.cursor++;
2177
+ }
2178
+ /** alt+left / esc-b */
2179
+ wordLeft() {
2180
+ this.cursor = this.wordBoundLeft();
2181
+ }
2182
+ /** alt+right / esc-f */
2183
+ wordRight() {
2184
+ this.cursor = this.wordBoundRight();
2185
+ }
2186
+ /** start index (in code points) of the line containing ix */
2187
+ lineStartAt(ix) {
2188
+ const cs = this.chars;
2189
+ let i = ix;
2190
+ while (i > 0 && cs[i - 1] !== "\n") i--;
2191
+ return i;
2192
+ }
2193
+ /** end index (exclusive, before the \n) of the line containing ix */
2194
+ lineEndAt(ix) {
2195
+ const cs = this.chars;
2196
+ let i = ix;
2197
+ while (i < cs.length && cs[i] !== "\n") i++;
2198
+ return i;
2199
+ }
2200
+ /** Home / ⌘← / ⌃A: start of the LOGICAL line; already there → the previous line's start */
2201
+ lineHome() {
2202
+ const start = this.lineStartAt(this.cursor);
2203
+ if (this.cursor !== start || start === 0) return void (this.cursor = start);
2204
+ this.cursor = this.lineStartAt(start - 1);
2205
+ }
2206
+ /** End / ⌘→ / ⌃E: end of the LOGICAL line; already there → the next line's end */
2207
+ lineEnd() {
2208
+ const end = this.lineEndAt(this.cursor);
2209
+ if (this.cursor !== end || end === this.chars.length) return void (this.cursor = end);
2210
+ this.cursor = this.lineEndAt(end + 1);
2211
+ }
2212
+ /** ⌥↑/⌥↓: swap the cursor's logical line with its neighbor, cursor rides along */
2213
+ moveLine(delta) {
2214
+ const cs = this.chars;
2215
+ const start = this.lineStartAt(this.cursor);
2216
+ const end = this.lineEndAt(this.cursor);
2217
+ const col = this.cursor - start;
2218
+ const cur = cs.slice(start, end);
2219
+ if (delta === -1) {
2220
+ if (start === 0) return;
2221
+ const prevStart = this.lineStartAt(start - 1);
2222
+ const prev = cs.slice(prevStart, start - 1);
2223
+ this.setChars([
2224
+ ...cs.slice(0, prevStart),
2225
+ ...cur,
2226
+ "\n",
2227
+ ...prev,
2228
+ ...cs.slice(end)
2229
+ ], prevStart + Math.min(col, cur.length));
2230
+ } else {
2231
+ if (end === cs.length) return;
2232
+ const nextEnd = this.lineEndAt(end + 1);
2233
+ const next = cs.slice(end + 1, nextEnd);
2234
+ this.setChars([
2235
+ ...cs.slice(0, start),
2236
+ ...next,
2237
+ "\n",
2238
+ ...cur,
2239
+ ...cs.slice(nextEnd)
2240
+ ], start + next.length + 1 + Math.min(col, cur.length));
2241
+ }
2242
+ }
2243
+ /** ⌘/ / ⌃/ / ⌥/: toggle `// ` at the start of the cursor's line */
2244
+ toggleComment() {
2245
+ const cs = this.chars;
2246
+ const start = this.lineStartAt(this.cursor);
2247
+ const end = this.lineEndAt(this.cursor);
2248
+ const line = cs.slice(start, end).join("");
2249
+ const m = /^(\s*)\/\/ ?/.exec(line);
2250
+ if (m == null) {
2251
+ cs.splice(start, 0, "/", "/", " ");
2252
+ this.setChars(cs, this.cursor + 3);
2253
+ return;
2254
+ }
2255
+ const indentLen = [...m[1] ?? ""].length;
2256
+ const removeLen = [...m[0]].length - indentLen;
2257
+ cs.splice(start + indentLen, removeLen);
2258
+ this.setChars(cs, Math.max(start, this.cursor - removeLen));
2259
+ }
2260
+ cursorUp() {
2261
+ const start = this.lineStartAt(this.cursor);
2262
+ if (start === 0) {
2263
+ this.cursor = 0;
2264
+ return;
2265
+ }
2266
+ const col = this.cursor - start;
2267
+ const prevStart = this.lineStartAt(start - 1);
2268
+ const prevLen = start - 1 - prevStart;
2269
+ this.cursor = prevStart + Math.min(col, prevLen);
2270
+ }
2271
+ cursorDown() {
2272
+ const cs = this.chars;
2273
+ const start = this.lineStartAt(this.cursor);
2274
+ const col = this.cursor - start;
2275
+ let end = this.cursor;
2276
+ while (end < cs.length && cs[end] !== "\n") end++;
2277
+ if (end === cs.length) {
2278
+ this.cursor = cs.length;
2279
+ return;
2280
+ }
2281
+ const nextStart = end + 1;
2282
+ let nextEnd = nextStart;
2283
+ while (nextEnd < cs.length && cs[nextEnd] !== "\n") nextEnd++;
2284
+ this.cursor = nextStart + Math.min(col, nextEnd - nextStart);
2285
+ }
2286
+ };
2287
+ //#endregion
2288
+ //#region src/cli/tui/state/ExecSt.ts
2289
+ /** run lifecycle + outputs + status line + clipboard/open actions */
2290
+ var ExecSt = class {
2291
+ constructor(st) {
2292
+ this.st = st;
2293
+ this.inFlight = 0;
2294
+ this.progress = null;
2295
+ this.outputs = [];
2296
+ this.runCount = 0;
2297
+ this.lastStatus = null;
2298
+ this.error = null;
2299
+ this.notice = null;
2300
+ this.currentPromptId = null;
2301
+ makeAutoObservable(this, { st: false });
2302
+ }
2303
+ get running() {
2304
+ return this.inFlight > 0;
2305
+ }
2306
+ /** workflow switch: wipe run artifacts, keep a hello notice */
2307
+ resetForWorkflow(notice) {
2308
+ this.outputs = [];
2309
+ this.error = null;
2310
+ this.notice = notice;
2311
+ this.runCount = 0;
2312
+ this.lastStatus = null;
2313
+ }
2314
+ /** every run takes THIS path, queued ones included: same progress, outputs, previews */
2315
+ async run() {
2316
+ const queued = this.running;
2317
+ const host = this.st.wf.host;
2318
+ runInAction(() => {
2319
+ this.inFlight++;
2320
+ this.error = null;
2321
+ if (queued) this.notice = `queued another run (server queue: ${this.st.queue.remaining + 1})`;
2322
+ else {
2323
+ this.progress = null;
2324
+ this.notice = null;
2325
+ this.currentPromptId = null;
2326
+ this.st.preview.reset();
2327
+ host.onLatentPreview = (p) => void this.st.preview.renderLatent(p.bytes);
2328
+ }
2329
+ });
2330
+ try {
2331
+ const execution = await this.st.wf.run({ onProgress: (p) => runInAction(() => this.onProgress(p)) });
2332
+ runInAction(() => {
2333
+ this.outputs = execution.images.map((i) => i.absPath);
2334
+ this.lastStatus = execution.status;
2335
+ this.runCount++;
2336
+ });
2337
+ const lastImage = execution.images[execution.images.length - 1];
2338
+ if (lastImage) this.st.preview.renderOutput(lastImage.absPath);
2339
+ } catch (e) {
2340
+ runInAction(() => {
2341
+ this.error = extractErrorMessage(e);
2342
+ });
2343
+ } finally {
2344
+ runInAction(() => {
2345
+ this.inFlight--;
2346
+ this.progress = null;
2347
+ this.currentPromptId = null;
2348
+ this.st.preview.clearLatent();
2349
+ if (this.inFlight === 0) host.onLatentPreview = null;
2350
+ });
2351
+ }
2352
+ }
2353
+ /** the server runs prompts one at a time: a NEW promptId = the next queued run just started */
2354
+ onProgress(p) {
2355
+ if (p.promptId !== this.currentPromptId) {
2356
+ this.currentPromptId = p.promptId;
2357
+ this.notice = null;
2358
+ this.st.preview.clearLatent();
2359
+ }
2360
+ this.progress = p;
2361
+ }
2362
+ randomizeSeedAndRun() {
2363
+ for (const [, varDef] of this.st.entries) if (varDef.kind === "seed") varDef.randomize();
2364
+ this.run();
2365
+ }
2366
+ /** 'o': real pixels in the OS viewer — the in-terminal ceiling is half-blocks */
2367
+ openLastOutput() {
2368
+ const last = this.outputs[this.outputs.length - 1];
2369
+ if (last == null) {
2370
+ this.notice = "no output image yet";
2371
+ return;
2372
+ }
2373
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
2374
+ const proc = spawn(cmd, [last], {
2375
+ stdio: "ignore",
2376
+ detached: true
2377
+ });
2378
+ proc.on("error", () => {
2379
+ runInAction(() => {
2380
+ this.notice = `could not launch ${cmd}`;
2381
+ });
2382
+ });
2383
+ proc.unref();
2384
+ this.notice = `opened ${basename(last)}`;
2385
+ }
2386
+ toClipboard(text) {
2387
+ const [cmd, ...args] = process.platform === "darwin" ? ["pbcopy"] : process.platform === "win32" ? ["clip"] : [
2388
+ "xclip",
2389
+ "-selection",
2390
+ "clipboard"
2391
+ ];
2392
+ return new Promise((resolve) => {
2393
+ const proc = spawn(cmd ?? "pbcopy", args, { stdio: [
2394
+ "pipe",
2395
+ "ignore",
2396
+ "ignore"
2397
+ ] });
2398
+ proc.on("error", () => resolve(false));
2399
+ proc.on("close", (code) => resolve(code === 0));
2400
+ proc.stdin.write(text);
2401
+ proc.stdin.end();
2402
+ });
2403
+ }
2404
+ /** 'c': copy workflow.json (litegraph, drag into the ComfyUI editor) */
2405
+ async copyWorkflowJson() {
2406
+ try {
2407
+ const json = await (await this.st.wf.build()).toWorkflowJson();
2408
+ const ok = await this.toClipboard(JSON.stringify(json, null, 2));
2409
+ runInAction(() => {
2410
+ this.notice = ok ? `workflow.json copied (${json.nodes.length} nodes)` : "clipboard copy failed";
2411
+ });
2412
+ } catch (e) {
2413
+ runInAction(() => {
2414
+ this.notice = `${extractErrorMessage(e)}`;
2415
+ });
2416
+ }
2417
+ }
2418
+ /** 'C': copy api.json (the POST /prompt payload) */
2419
+ async copyApiJson() {
2420
+ try {
2421
+ const json = (await this.st.wf.build()).toApiJson("use_stringified_numbers_only");
2422
+ const ok = await this.toClipboard(JSON.stringify(json, null, 2));
2423
+ runInAction(() => {
2424
+ this.notice = ok ? `api.json copied (${Object.keys(json).length} nodes)` : "clipboard copy failed";
2425
+ });
2426
+ } catch (e) {
2427
+ runInAction(() => {
2428
+ this.notice = `${extractErrorMessage(e)}`;
2429
+ });
2430
+ }
2431
+ }
2432
+ };
2433
+ //#endregion
2434
+ //#region src/cli/tui/state/HostSt.ts
2435
+ /** host panel (`h`): stats about the connected host + maintenance actions */
2436
+ var HostSt = class {
2437
+ constructor(st) {
2438
+ this.st = st;
2439
+ this.ix = 0;
2440
+ this.running = null;
2441
+ this.actions = [
2442
+ {
2443
+ key: "refresh",
2444
+ label: "re-codegen SDK (refetch object_info + reload workflow)"
2445
+ },
2446
+ {
2447
+ key: "restart",
2448
+ label: "restart ComfyUI (manager reboot)"
2449
+ },
2450
+ {
2451
+ key: "clear-queue",
2452
+ label: "clear pending queue"
2453
+ },
2454
+ {
2455
+ key: "interrupt",
2456
+ label: "interrupt current run"
2457
+ }
2458
+ ];
2459
+ makeAutoObservable(this, { st: false });
2460
+ }
2461
+ get host() {
2462
+ return this.st.wf.host;
2463
+ }
2464
+ get stats() {
2465
+ const schema = this.host.schema;
2466
+ return [
2467
+ {
2468
+ label: "node types",
2469
+ value: String(schema.nodes.length)
2470
+ },
2471
+ {
2472
+ label: "loras",
2473
+ value: String(schema.getLoras().length)
2474
+ },
2475
+ {
2476
+ label: "embeddings",
2477
+ value: String(schema.data.embeddings.length)
2478
+ },
2479
+ {
2480
+ label: "queue",
2481
+ value: String(this.st.queue.remaining)
2482
+ },
2483
+ {
2484
+ label: "ws",
2485
+ value: this.host.getWSUrl()
2486
+ }
2487
+ ];
2488
+ }
2489
+ begin() {
2490
+ this.st.mode = "host";
2491
+ this.ix = 0;
2492
+ }
2493
+ blur() {
2494
+ this.st.mode = "nav";
2495
+ }
2496
+ move(delta) {
2497
+ const len = this.actions.length;
2498
+ this.ix = (this.ix + delta + len) % len;
2499
+ }
2500
+ async commit() {
2501
+ const action = this.actions[this.ix];
2502
+ if (action == null || this.running != null) return;
2503
+ if (action.key === "refresh") return this.refreshSdk();
2504
+ if (action.key === "restart") return this.restartComfy();
2505
+ if (action.key === "clear-queue") return this.st.queue.clearPending();
2506
+ return this.st.queue.interrupt();
2507
+ }
2508
+ /** refetch object_info, regen the sdk, then cache-busted reload of the current
2509
+ * module so dynamic var options (v.loras…) see the new values */
2510
+ async refreshSdk() {
2511
+ runInAction(() => {
2512
+ this.running = "refresh";
2513
+ });
2514
+ try {
2515
+ await this.host.fetchAndUpdateSchema();
2516
+ await this.st.workflows.reload(this.st.drafts.active ?? "default");
2517
+ runInAction(() => {
2518
+ const schema = this.host.schema;
2519
+ this.st.exec.notice = `SDK regenerated: ${schema.nodes.length} node types, ${schema.getLoras().length} loras`;
2520
+ });
2521
+ } catch (e) {
2522
+ runInAction(() => {
2523
+ this.st.exec.error = extractErrorMessage(e);
2524
+ });
2525
+ } finally {
2526
+ runInAction(() => {
2527
+ this.running = null;
2528
+ });
2529
+ }
2530
+ }
2531
+ async restartComfy() {
2532
+ runInAction(() => {
2533
+ this.running = "restart";
2534
+ });
2535
+ try {
2536
+ await this.host.manager.restartComfyUI();
2537
+ runInAction(() => {
2538
+ this.st.exec.notice = "reboot requested — the ws reconnects when the host is back";
2539
+ });
2540
+ } catch (e) {
2541
+ runInAction(() => {
2542
+ this.st.exec.notice = `reboot requested (${extractErrorMessage(e)}) — the ws reconnects when the host is back`;
2543
+ });
2544
+ } finally {
2545
+ runInAction(() => {
2546
+ this.running = null;
2547
+ });
2548
+ }
2549
+ }
2550
+ };
2551
+ //#endregion
2552
+ //#region src/host/loraManagerApi.ts
2553
+ const lmLoraPage = type({
2554
+ items: type({
2555
+ folder: "string",
2556
+ file_name: "string",
2557
+ preview_url: "string"
2558
+ }).array(),
2559
+ total: "number"
2560
+ });
2561
+ /** normalize an object_info lora name OR an lm folder/file pair to one key */
2562
+ function loraPreviewKey(name) {
2563
+ return name.replaceAll("\\", "/").replace(/\.(safetensors|st|pt|ckpt)$/i, "").toLowerCase();
2564
+ }
2565
+ /**
2566
+ * fetch every lora known to lora-manager, mapped `loraPreviewKey` → preview_url
2567
+ * (server-relative). Returns null when the extension is absent (404/network).
2568
+ */
2569
+ async function fetchLoraPreviewMap(host) {
2570
+ const base = host.getServerHostHTTP();
2571
+ const map = /* @__PURE__ */ new Map();
2572
+ const pageSize = 500;
2573
+ for (let page = 1; page <= 20; page++) {
2574
+ let res;
2575
+ try {
2576
+ res = await fetch(`${base}/api/lm/loras/list?page=${page}&page_size=${pageSize}`);
2577
+ } catch {
2578
+ return null;
2579
+ }
2580
+ if (!res.ok) return page === 1 ? null : map;
2581
+ const json = await res.json();
2582
+ const parsed = lmLoraPage(json);
2583
+ if (parsed instanceof type.errors) {
2584
+ logError(`[loraManagerApi] /api/lm/loras/list page ${page} shape mismatch: ${parsed.summary}`);
2585
+ return map;
2586
+ }
2587
+ for (const item of parsed.items) {
2588
+ const rel = item.folder === "" ? item.file_name : `${item.folder}/${item.file_name}`;
2589
+ map.set(loraPreviewKey(rel), item.preview_url);
2590
+ }
2591
+ if (map.size >= parsed.total || parsed.items.length === 0) break;
2592
+ }
2593
+ return map;
2594
+ }
2595
+ /** the bytes look like an image (magic numbers) — guards against ComfyUI's SPA index.html fallback */
2596
+ function looksLikeImage(bytes) {
2597
+ if (bytes.length < 3) return false;
2598
+ const b = bytes;
2599
+ const is = (sig, off = 0) => sig.every((v, i) => b[off + i] === v);
2600
+ return is([
2601
+ 137,
2602
+ 80,
2603
+ 78,
2604
+ 71
2605
+ ]) || is([
2606
+ 255,
2607
+ 216,
2608
+ 255
2609
+ ]) || is([
2610
+ 71,
2611
+ 73,
2612
+ 70
2613
+ ]) || is([
2614
+ 82,
2615
+ 73,
2616
+ 70,
2617
+ 70
2618
+ ]) && is([
2619
+ 87,
2620
+ 69,
2621
+ 66,
2622
+ 80
2623
+ ], 8);
2624
+ }
2625
+ /**
2626
+ * fetch a preview image's bytes from its server-relative preview_url.
2627
+ * cached on success at `.comfy-ts/cache/lora-previews/<sha1(url)>`. Returns null
2628
+ * when the file is missing: lora-manager SPA-fallbacks to index.html (HTML), so
2629
+ * a non-image content-type OR non-image magic bytes => no preview, not a crash.
2630
+ */
2631
+ async function fetchLoraPreviewBytes(host, previewUrl) {
2632
+ const cachePath = comfyts.resolveFromCache(`lora-previews/${createHash("sha1").update(previewUrl).digest("hex")}`);
2633
+ if (existsSync(cachePath)) return new Uint8Array(readFileSync(cachePath));
2634
+ try {
2635
+ const res = await fetch(`${host.getServerHostHTTP()}${previewUrl}`);
2636
+ if (!res.ok) return null;
2637
+ const ct = res.headers.get("content-type") ?? "";
2638
+ if (ct !== "" && !ct.startsWith("image/")) return null;
2639
+ const bytes = new Uint8Array(await res.arrayBuffer());
2640
+ if (!looksLikeImage(bytes)) return null;
2641
+ mkdirSync(dirname(cachePath), { recursive: true });
2642
+ writeFileSync(cachePath, bytes);
2643
+ return bytes;
2644
+ } catch {
2645
+ return null;
2646
+ }
2647
+ }
2648
+ //#endregion
2649
+ //#region src/utils/fuzzyMatch.ts
2650
+ /** case-insensitive subsequence match: 'wide' hits '16:9 (Widescreen)' */
2651
+ function fuzzyMatch(needle, hay) {
2652
+ const n = needle.toLowerCase();
2653
+ const h = hay.toLowerCase();
2654
+ let i = 0;
2655
+ for (const ch of h) if (ch === n[i]) i++;
2656
+ return i >= n.length;
2657
+ }
2658
+ //#endregion
2659
+ //#region src/cli/tui/state/LorasSt.ts
2660
+ /** loras overlay: fuzzy filter + tick/untick + strengths + bulk ops + lora-manager preview */
2661
+ var LorasSt = class {
2662
+ constructor(st) {
2663
+ this.st = st;
2664
+ this.ix = 0;
2665
+ this.filter = "";
2666
+ this.previewAnsi = null;
2667
+ this.previewBytes = null;
2668
+ this.previewName = null;
2669
+ this.previewNote = null;
2670
+ this.previewMap = void 0;
2671
+ this.previewMapHostId = null;
2672
+ this._busy = false;
2673
+ makeAutoObservable(this, { st: false });
2674
+ this.st.disposers.push(reaction(() => this.st.mode === "overlay-loras" ? this.selectedName : null, () => void this.refreshPreview(), { delay: 120 }));
2675
+ }
2676
+ /** kind-narrowing cast sanctioned (agent/coding.md), `kind` is the tag */
2677
+ get selectedVar() {
2678
+ const sel = this.st.selected?.[1];
2679
+ return sel?.kind === "loras" ? sel : null;
2680
+ }
2681
+ /** options surviving the fuzzy filter (bulk ops apply to exactly these) */
2682
+ get filteredNames() {
2683
+ const lv = this.selectedVar;
2684
+ if (lv == null) return [];
2685
+ if (this.filter === "") return lv.names;
2686
+ return lv.names.filter((n) => fuzzyMatch(this.filter, n));
2687
+ }
2688
+ begin() {
2689
+ if (this.selectedVar == null) return;
2690
+ this.st.mode = "overlay-loras";
2691
+ this.ix = 0;
2692
+ this.filter = "";
2693
+ }
2694
+ move(delta) {
2695
+ const len = this.filteredNames.length;
2696
+ if (len === 0) return;
2697
+ this.ix = (this.ix + delta + len) % len;
2698
+ }
2699
+ filterInput(chunk) {
2700
+ this.filter += chunk;
2701
+ this.ix = 0;
2702
+ }
2703
+ filterBackspace() {
2704
+ this.filter = this.filter.slice(0, -1);
2705
+ this.ix = 0;
2706
+ }
2707
+ /** ⌥⌫ / ⌃W: drop the last word of the filter */
2708
+ filterDeleteWord() {
2709
+ this.filter = this.filter.replace(/\s*\S+\s*$/, "");
2710
+ this.ix = 0;
2711
+ }
2712
+ toggle() {
2713
+ const lv = this.selectedVar;
2714
+ const name = this.filteredNames[this.ix];
2715
+ if (lv == null || name == null) return;
2716
+ lv.toggleItem(name);
2717
+ }
2718
+ /** ⌃A / ⌃N: tick / untick every lora surviving the filter */
2719
+ setAll(on) {
2720
+ this.selectedVar?.setAll(on, this.filteredNames);
2721
+ }
2722
+ adjust(delta) {
2723
+ const lv = this.selectedVar;
2724
+ const name = this.filteredNames[this.ix];
2725
+ if (lv == null || name == null) return;
2726
+ lv.adjustItem(name, delta);
2727
+ }
2728
+ /** ⌃K: assign the selected lora's trigger keyword (PromptVar prefixes actives with it) */
2729
+ beginKeyword() {
2730
+ const name = this.selectedName;
2731
+ if (name == null) return;
2732
+ this.st.editor.beginCustom({
2733
+ title: `keyword for ${LorasVar.shortName(name)} (empty clears)`,
2734
+ initial: getLoraKeyword(name),
2735
+ onCommit: (raw) => {
2736
+ setLoraKeyword(name, raw);
2737
+ return true;
2738
+ },
2739
+ returnMode: "overlay-loras"
2740
+ });
2741
+ }
2742
+ get selectedName() {
2743
+ return this.filteredNames[this.ix] ?? null;
2744
+ }
2745
+ async refreshPreview() {
2746
+ if (this.st.mode !== "overlay-loras") {
2747
+ runInAction(() => {
2748
+ this.previewAnsi = null;
2749
+ this.previewBytes = null;
2750
+ this.previewName = null;
2751
+ this.previewNote = null;
2752
+ });
2753
+ return;
2754
+ }
2755
+ const name = this.selectedName;
2756
+ if (name == null || this._busy) return;
2757
+ this._busy = true;
2758
+ try {
2759
+ const host = this.st.wf.host;
2760
+ if (this.previewMap === void 0 || this.previewMapHostId !== host.data.id) {
2761
+ this.previewMap = await fetchLoraPreviewMap(host);
2762
+ this.previewMapHostId = host.data.id;
2763
+ }
2764
+ const map = this.previewMap;
2765
+ const url = map?.get(loraPreviewKey(name));
2766
+ const note = map == null ? "lora-manager extension not detected" : url == null ? "no preview available" : null;
2767
+ if (url == null) {
2768
+ runInAction(() => {
2769
+ this.previewAnsi = null;
2770
+ this.previewBytes = null;
2771
+ this.previewName = name;
2772
+ this.previewNote = note;
2773
+ });
2774
+ return;
2775
+ }
2776
+ const bytes = await fetchLoraPreviewBytes(host, url);
2777
+ if (bytes == null) throw new Error("no image preview on the server");
2778
+ if (this.st.preview.useNative) {
2779
+ runInAction(() => {
2780
+ this.previewBytes = bytes;
2781
+ this.previewAnsi = null;
2782
+ this.previewName = name;
2783
+ this.previewNote = null;
2784
+ });
2785
+ return;
2786
+ }
2787
+ const ansi = await imageBufferToAnsi(bytes, {
2788
+ width: this.st.preview.width,
2789
+ height: this.st.preview.height
2790
+ });
2791
+ runInAction(() => {
2792
+ this.previewAnsi = ansi;
2793
+ this.previewName = name;
2794
+ this.previewNote = null;
2795
+ });
2796
+ } catch (e) {
2797
+ runInAction(() => {
2798
+ this.previewAnsi = null;
2799
+ this.previewBytes = null;
2800
+ this.previewName = name;
2801
+ this.previewNote = extractErrorMessage(e);
2802
+ });
2803
+ } finally {
2804
+ this._busy = false;
2805
+ if (this.st.mode === "overlay-loras" && this.selectedName !== name) this.refreshPreview();
2806
+ }
2807
+ }
2808
+ };
2809
+ //#endregion
2810
+ //#region src/cli/tui/state/PickerSt.ts
2811
+ /**
2812
+ * choice + size overlays: a windowed option list with a fuzzy type-to-filter.
2813
+ * For sizes the filter doubles as free `WxH` entry.
2814
+ */
2815
+ var PickerSt = class {
2816
+ constructor(st) {
2817
+ this.st = st;
2818
+ this.filter = "";
2819
+ this.ix = 0;
2820
+ this.invalid = false;
2821
+ makeAutoObservable(this, { st: false });
2822
+ }
2823
+ get choiceVar() {
2824
+ const sel = this.st.selected?.[1];
2825
+ return sel?.kind === "choice" ? sel : null;
2826
+ }
2827
+ get sizeVar() {
2828
+ const sel = this.st.selected?.[1];
2829
+ return sel?.kind === "size" ? sel : null;
2830
+ }
2831
+ get options() {
2832
+ const cv = this.choiceVar;
2833
+ if (cv != null) {
2834
+ if (this.filter === "") return [...cv.choices];
2835
+ return cv.choices.filter((c) => fuzzyMatch(this.filter, c));
2836
+ }
2837
+ const sv = this.sizeVar;
2838
+ if (sv != null) {
2839
+ const labels = sv.presets.map((p) => `${p.width}×${p.height} ${p.label}`);
2840
+ if (this.filter === "") return labels;
2841
+ return labels.filter((l) => fuzzyMatch(this.filter, l));
2842
+ }
2843
+ return [];
2844
+ }
2845
+ beginChoice() {
2846
+ const cv = this.choiceVar;
2847
+ if (cv == null) return;
2848
+ this.st.mode = "overlay-choice";
2849
+ this.filter = "";
2850
+ this.invalid = false;
2851
+ this.ix = Math.max(0, cv.choices.indexOf(cv.value));
2852
+ }
2853
+ beginSize() {
2854
+ const sv = this.sizeVar;
2855
+ if (sv == null) return;
2856
+ this.st.mode = "overlay-size";
2857
+ this.filter = "";
2858
+ this.invalid = false;
2859
+ const ix = sv.presets.findIndex((p) => p.width === sv.value.width && p.height === sv.value.height);
2860
+ this.ix = ix === -1 ? 0 : ix;
2861
+ }
2862
+ move(delta) {
2863
+ const len = this.options.length;
2864
+ if (len === 0) return;
2865
+ this.ix = (this.ix + delta + len) % len;
2866
+ }
2867
+ filterInput(chunk) {
2868
+ this.filter += chunk;
2869
+ this.ix = 0;
2870
+ this.invalid = false;
2871
+ }
2872
+ filterBackspace() {
2873
+ this.filter = this.filter.slice(0, -1);
2874
+ this.ix = 0;
2875
+ this.invalid = false;
2876
+ }
2877
+ /** ⌥⌫ / ⌃W: drop the last word of the filter */
2878
+ filterDeleteWord() {
2879
+ this.filter = this.filter.replace(/\s*\S+\s*$/, "");
2880
+ this.ix = 0;
2881
+ this.invalid = false;
2882
+ }
2883
+ commit() {
2884
+ const cv = this.choiceVar;
2885
+ if (cv != null) {
2886
+ const hit = this.options[this.ix];
2887
+ if (hit == null) return;
2888
+ cv.set(hit);
2889
+ this.st.mode = "nav";
2890
+ return;
2891
+ }
2892
+ const sv = this.sizeVar;
2893
+ if (sv == null) return;
2894
+ const hit = this.options[this.ix];
2895
+ if (hit != null) {
2896
+ const m = hit.match(/^(\d+)×(\d+)/);
2897
+ if (m != null) sv.set({
2898
+ width: Number(m[1]),
2899
+ height: Number(m[2])
2900
+ });
2901
+ this.st.mode = "nav";
2902
+ return;
2903
+ }
2904
+ if (sv.parse(this.filter)) this.st.mode = "nav";
2905
+ else this.invalid = true;
2906
+ }
2907
+ };
2908
+ //#endregion
2909
+ //#region src/cli/tui/state/QueueSt.ts
2910
+ /** live server queue length (ws 'status' messages) + queue actions */
2911
+ var QueueSt = class {
2912
+ constructor(st) {
2913
+ this.st = st;
2914
+ this.remaining = 0;
2915
+ this.attached = null;
2916
+ makeAutoObservable(this, { st: false });
2917
+ this.attach(this.st.wf.host);
2918
+ this.st.disposers.push(() => {
2919
+ if (this.attached != null) this.attached.onStatus = null;
2920
+ });
2921
+ }
2922
+ /** follow the CURRENT workflow's host (re-called on workflow switch) */
2923
+ attach(host) {
2924
+ if (this.attached === host) return;
2925
+ if (this.attached != null) this.attached.onStatus = null;
2926
+ this.attached = host;
2927
+ this.remaining = 0;
2928
+ host.onStatus = (p) => {
2929
+ runInAction(() => {
2930
+ this.remaining = p.queueRemaining;
2931
+ });
2932
+ };
2933
+ }
2934
+ async clearPending() {
2935
+ try {
2936
+ await this.st.wf.host.clearQueue();
2937
+ runInAction(() => {
2938
+ this.st.exec.notice = "pending queue cleared";
2939
+ });
2940
+ } catch (e) {
2941
+ runInAction(() => {
2942
+ this.st.exec.error = extractErrorMessage(e);
2943
+ });
2944
+ }
2945
+ }
2946
+ async interrupt() {
2947
+ try {
2948
+ await this.st.wf.host.interrupt();
2949
+ runInAction(() => {
2950
+ this.st.exec.notice = "interrupt requested";
2951
+ });
2952
+ } catch (e) {
2953
+ runInAction(() => {
2954
+ this.st.exec.error = extractErrorMessage(e);
2955
+ });
2956
+ }
2957
+ }
2958
+ };
2959
+ //#endregion
2960
+ //#region src/cli/tui/state/SettingsSt.ts
2961
+ /** persisted TUI settings at `.comfy-ts/settings.json` (LOCAL state, gitignored) */
2962
+ var SettingsSt = class {
2963
+ constructor(st) {
2964
+ this.st = st;
2965
+ this.previewMode = protocolCapable() ? "native" : "ansi";
2966
+ this.lastDraft = {};
2967
+ this.load();
2968
+ if (this.previewMode === "native" && !protocolCapable()) this.previewMode = "ansi";
2969
+ makeAutoObservable(this, { st: false });
2970
+ this.st.disposers.push(reaction(() => JSON.stringify({
2971
+ previewMode: this.previewMode,
2972
+ lastDraft: this.lastDraft
2973
+ }), (json) => this.write(json), { delay: 300 }));
2974
+ }
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
+ rememberDraft(moduleKey, draft) {
2991
+ this.lastDraft[moduleKey] = draft;
2992
+ }
2993
+ load() {
2994
+ const path = comfyts.settingsPath;
2995
+ if (!existsSync(path)) return;
2996
+ try {
2997
+ const raw = JSON.parse(readFileSync(path, "utf8"));
2998
+ if (raw == null || typeof raw !== "object") return;
2999
+ const o = raw;
3000
+ if (o.previewMode === "native" || o.previewMode === "ansi" || o.previewMode === "off") this.previewMode = o.previewMode;
3001
+ if (o.lastDraft != null && typeof o.lastDraft === "object") this.lastDraft = { ...o.lastDraft };
3002
+ } catch {}
3003
+ }
3004
+ write(json) {
3005
+ const path = comfyts.settingsPath;
3006
+ try {
3007
+ mkdirSync(dirname(path), { recursive: true });
3008
+ writeFileSync(path, json);
3009
+ } catch (e) {
3010
+ runInAction(() => {
3011
+ this.st.exec.notice = `settings save failed: ${String(e)}`;
3012
+ });
3013
+ }
3014
+ }
3015
+ };
3016
+ //#endregion
3017
+ //#region src/cli/tui/state/TreeSt.ts
3018
+ /** the left `(t)ree`: workflows with their drafts nested under them */
3019
+ var TreeSt = class {
3020
+ constructor(st) {
3021
+ this.st = st;
3022
+ this.ix = 0;
3023
+ this.expandedFiles = /* @__PURE__ */ new Set();
3024
+ makeAutoObservable(this, { st: false });
3025
+ }
3026
+ get rows() {
3027
+ this.st.drafts.version;
3028
+ const w = this.st.workflows;
3029
+ const rows = [];
3030
+ for (const file of w.files) {
3031
+ const current = file === w.currentPath;
3032
+ const expanded = this.expandedFiles.has(file);
3033
+ const drafts = listDraftsForFile(file);
3034
+ rows.push({
3035
+ kind: "workflow",
3036
+ file,
3037
+ name: draftKeyForFile(file),
3038
+ expanded,
3039
+ current,
3040
+ hasDrafts: drafts.length > 0
3041
+ });
3042
+ if (!expanded) continue;
3043
+ for (const draft of drafts) rows.push({
3044
+ kind: "draft",
3045
+ file,
3046
+ draft,
3047
+ active: current && draft === this.st.drafts.active
3048
+ });
3049
+ }
3050
+ return rows;
3051
+ }
3052
+ get selected() {
3053
+ return this.rows[this.ix];
3054
+ }
3055
+ /** 't' / ←: focus the tree ON THE ACTIVE DRAFT (where you actually are), workflow row as fallback */
3056
+ focus() {
3057
+ const w = this.st.workflows;
3058
+ if (w.files.length === 0) {
3059
+ this.st.exec.notice = "no workflow tree — start the tui in a folder containing **/*.cflow.ts";
3060
+ return;
3061
+ }
3062
+ if (w.currentPath != null) this.expandedFiles.add(w.currentPath);
3063
+ this.st.mode = "tree";
3064
+ const rows = this.rows;
3065
+ const draftIx = rows.findIndex((r) => r.kind === "draft" && r.active);
3066
+ const ix = draftIx === -1 ? rows.findIndex((r) => r.kind === "workflow" && r.current) : draftIx;
3067
+ this.ix = ix === -1 ? 0 : ix;
3068
+ }
3069
+ /** esc/t inside the tree, → on a draft row, `v` anywhere: back to the vars list */
3070
+ blur() {
3071
+ this.st.mode = "nav";
3072
+ }
3073
+ move(delta) {
3074
+ const len = this.rows.length;
3075
+ if (len === 0) return;
3076
+ this.ix = (this.ix + delta + len) % len;
3077
+ }
3078
+ /** →: unfold the workflow under the cursor; on a draft row there is nothing
3079
+ * left to unfold, so → continues rightwards into the vars panel */
3080
+ unfold() {
3081
+ const row = this.selected;
3082
+ if (row == null) return;
3083
+ if (row.kind === "workflow") this.expandedFiles.add(row.file);
3084
+ else this.blur();
3085
+ }
3086
+ /** ←: fold the workflow under the cursor; on a draft row, jump to (and fold) its parent */
3087
+ fold() {
3088
+ const row = this.selected;
3089
+ if (row == null) return;
3090
+ this.expandedFiles.delete(row.file);
3091
+ if (row.kind === "draft") {
3092
+ const ix = this.rows.findIndex((r) => r.kind === "workflow" && r.file === row.file);
3093
+ if (ix !== -1) this.ix = ix;
3094
+ }
3095
+ }
3096
+ /** ⏎: load the workflow (into 'default'), or the exact draft under the cursor */
3097
+ async commit() {
3098
+ const row = this.selected;
3099
+ if (row == null) return;
3100
+ if (row.kind === "workflow") return this.st.workflows.commit(row.file);
3101
+ return this.st.workflows.commit(row.file, row.draft);
3102
+ }
3103
+ /** n: new draft — current workflow only (a draft snapshots its LIVE var values) */
3104
+ promptNewDraft() {
3105
+ const row = this.selected;
3106
+ if (row != null && row.file !== this.st.workflows.currentPath) {
3107
+ this.st.exec.notice = "load that workflow first (⏎) — a new draft snapshots its live vars";
3108
+ return;
3109
+ }
3110
+ this.st.drafts.promptNew("tree");
3111
+ }
3112
+ /** f2/c/x on a draft row: rename / duplicate / delete (file ops, work on ANY workflow's drafts) */
3113
+ draftOp(op) {
3114
+ const row = this.selected;
3115
+ if (row?.kind !== "draft") {
3116
+ this.st.exec.notice = "select a draft row (unfold a workflow with →)";
3117
+ return;
3118
+ }
3119
+ if (op === "rename") return this.st.drafts.promptRename(row.draft, row.file, "tree");
3120
+ if (op === "duplicate") return this.st.drafts.promptDuplicate(row.draft, row.file, "tree");
3121
+ this.st.drafts.deleteDraft(row.draft, row.file);
3122
+ this.ix = Math.min(this.ix, Math.max(0, this.rows.length - 1));
3123
+ }
3124
+ };
3125
+ //#endregion
3126
+ //#region src/cli/tui/state/WorkflowsSt.ts
3127
+ /** workflow-module data layer: scanned files, module loading, opened-host set (TreeSt is the UI over it) */
3128
+ var WorkflowsSt = class {
3129
+ constructor(st, files, currentPath = null) {
3130
+ this.st = st;
3131
+ this.files = files;
3132
+ this.loading = false;
3133
+ this.loadedHosts = /* @__PURE__ */ new Set();
3134
+ this.currentPath = currentPath;
3135
+ makeAutoObservable(this, { st: false });
3136
+ }
3137
+ disconnectAllHosts() {
3138
+ this.loadedHosts.add(this.st.wf.host);
3139
+ for (const host of this.loadedHosts) host.disconnect();
3140
+ }
3141
+ /** load a workflow module; `draft` null => the remembered draft, else that exact draft */
3142
+ async commit(path, draft = null) {
3143
+ if (path === this.currentPath) {
3144
+ if (this.loading) return;
3145
+ if (draft == null) this.st.drafts.activateRemembered();
3146
+ else this.st.drafts.activate(draft);
3147
+ this.st.mode = "nav";
3148
+ return;
3149
+ }
3150
+ return this.load(path, draft, false);
3151
+ }
3152
+ /** cache-busted re-import of the CURRENT module: defineWorkflow re-executes,
3153
+ * so dynamic var option lists (v.loras over getLoras()…) pick up fresh schema values */
3154
+ async reload(draft) {
3155
+ const path = this.currentPath;
3156
+ if (path == null) return;
3157
+ return this.load(path, draft, true);
3158
+ }
3159
+ async load(path, draft, bustCache) {
3160
+ if (this.loading) return;
3161
+ runInAction(() => {
3162
+ this.loading = true;
3163
+ });
3164
+ try {
3165
+ const wf = findDefinedWorkflow(await import(pathToFileURL(resolve(path)).href + (bustCache ? `?v=${Date.now()}` : "")));
3166
+ if (wf == null) throw new Error(`${path} exports no DefinedWorkflow`);
3167
+ runInAction(() => {
3168
+ this.loadedHosts.add(this.st.wf.host);
3169
+ this.loadedHosts.add(wf.host);
3170
+ this.st.wf = wf;
3171
+ this.st.queue.attach(wf.host);
3172
+ this.currentPath = path;
3173
+ this.st.selIx = 0;
3174
+ this.st.mode = "nav";
3175
+ this.st.exec.resetForWorkflow(`${basename(path)}`);
3176
+ if (draft == null) this.st.drafts.activateRemembered();
3177
+ else this.st.drafts.activate(draft);
3178
+ this.st.preview.reset();
3179
+ });
3180
+ } catch (e) {
3181
+ runInAction(() => {
3182
+ this.st.mode = "nav";
3183
+ this.st.exec.error = extractErrorMessage(e);
3184
+ });
3185
+ } finally {
3186
+ runInAction(() => {
3187
+ this.loading = false;
3188
+ });
3189
+ }
3190
+ }
3191
+ };
3192
+ //#endregion
3193
+ //#region src/cli/tui/state/TuiSt.ts
3194
+ /**
3195
+ * ROOT of the TUI state tree (one instance per run). Children are service
3196
+ * classes with an `st` backref; components are stateless views over this.
3197
+ */
3198
+ var TuiSt = class {
3199
+ constructor(wf, opts = {}) {
3200
+ this.mode = "nav";
3201
+ this.selIx = 0;
3202
+ this.disposers = [];
3203
+ this.onExit = () => {};
3204
+ this.termCols = process.stdout.columns ?? 80;
3205
+ this.termRows = (process.stdout.rows ?? 24) - 1;
3206
+ this.wf = wf;
3207
+ makeAutoObservable(this, {
3208
+ wf: observable.ref,
3209
+ onExit: false,
3210
+ editor: false,
3211
+ picker: false,
3212
+ loras: false,
3213
+ workflows: false,
3214
+ tree: false,
3215
+ drafts: false,
3216
+ exec: false,
3217
+ preview: false,
3218
+ host: false,
3219
+ queue: false,
3220
+ settings: false
3221
+ });
3222
+ this.settings = new SettingsSt(this);
3223
+ this.editor = new EditorSt(this);
3224
+ this.picker = new PickerSt(this);
3225
+ this.loras = new LorasSt(this);
3226
+ this.workflows = new WorkflowsSt(this, opts.workflowFiles ?? [], opts.currentFile ?? null);
3227
+ this.tree = new TreeSt(this);
3228
+ this.drafts = new DraftsSt(this);
3229
+ this.exec = new ExecSt(this);
3230
+ this.preview = new PreviewSt(this);
3231
+ this.host = new HostSt(this);
3232
+ this.queue = new QueueSt(this);
3233
+ this.drafts.activateRemembered();
3234
+ if (opts.currentFile != null) this.tree.expandedFiles.add(opts.currentFile);
3235
+ const onResize = () => {
3236
+ runInAction(() => {
3237
+ this.termCols = process.stdout.columns ?? 80;
3238
+ this.termRows = (process.stdout.rows ?? 24) - 1;
3239
+ });
3240
+ };
3241
+ process.stdout.on?.("resize", onResize);
3242
+ this.disposers.push(() => process.stdout.off?.("resize", onResize));
3243
+ }
3244
+ dispose() {
3245
+ for (const d of this.disposers.splice(0)) d();
3246
+ this.workflows.disconnectAllHosts();
3247
+ }
3248
+ /** rows available inside a modal overlay list */
3249
+ get overlayLines() {
3250
+ return Math.max(8, this.termRows - 12);
3251
+ }
3252
+ /** left tree panel width: longest row (workflow or indented draft), clamped */
3253
+ get treeWidth() {
3254
+ const longest = Math.max(8, ...this.tree.rows.map((r) => r.kind === "workflow" ? r.name.length : r.draft.length + 3));
3255
+ return Math.min(32, longest + 7);
3256
+ }
3257
+ get entries() {
3258
+ return this.wf.entries();
3259
+ }
3260
+ get selected() {
3261
+ return this.entries[this.selIx];
3262
+ }
3263
+ moveSel(delta) {
3264
+ const len = this.entries.length;
3265
+ if (len === 0) return;
3266
+ this.selIx = (this.selIx + delta + len) % len;
3267
+ }
3268
+ /** enter/space on a var: toggle, open an overlay, or inline-edit */
3269
+ activate() {
3270
+ const sel = this.selected?.[1];
3271
+ if (sel == null) return;
3272
+ if (sel.kind === "toggle") sel.toggle();
3273
+ else if (sel.kind === "text") this.editor.beginMultiline();
3274
+ else if (sel.kind === "choice") this.picker.beginChoice();
3275
+ else if (sel.kind === "size") this.picker.beginSize();
3276
+ else if (sel.kind === "loras") this.loras.begin();
3277
+ else this.editor.beginInline();
3278
+ }
3279
+ /** kind-specific nav keys (documented in the keybar): seed `+`/`-`/`=`/`?` mode, `*` reroll */
3280
+ navKey(input) {
3281
+ const sel = this.selected?.[1];
3282
+ if (sel?.kind === "seed") {
3283
+ if (input === "+" || input === "-" || input === "=" || input === "?") {
3284
+ sel.setMode(input);
3285
+ return true;
3286
+ }
3287
+ if (input === "*") {
3288
+ sel.randomize();
3289
+ return true;
3290
+ }
3291
+ }
3292
+ return false;
3293
+ }
3294
+ };
3295
+ //#endregion
3296
+ //#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
+ async function runTui(args) {
3302
+ const target = args.find((a) => !a.startsWith("--")) ?? ".";
3303
+ process.env[COMFY_TS_TUI_ENV] = "1";
3304
+ process.env.COMFY_TS_QUIET = "1";
3305
+ const abs = resolve(target);
3306
+ const isDir = statSync(abs).isDirectory();
3307
+ 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) {
3311
+ console.error(`[comfy-ts tui] no **/*.cflow.ts found under ${abs}`);
3312
+ return 1;
3313
+ }
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(...)`);
3317
+ return 1;
3318
+ }
3319
+ const st = new TuiSt(wf, {
3320
+ workflowFiles,
3321
+ currentFile: first
3322
+ });
3323
+ const altScreen = process.stdout.isTTY === true;
3324
+ if (altScreen) process.stdout.write("\x1B[?1049h\x1B[H\x1B[>4;1m");
3325
+ const uninstallPainter = installProtocolImagePainter(st);
3326
+ try {
3327
+ const app = render(/* @__PURE__ */ jsx(TuiApp, { st }), { kittyKeyboard: { mode: "auto" } });
3328
+ st.onExit = () => st.dispose();
3329
+ await app.waitUntilExit();
3330
+ st.dispose();
3331
+ } finally {
3332
+ uninstallPainter();
3333
+ if (altScreen) process.stdout.write("\x1B[>4;0m\x1B[?1049l");
3334
+ }
3335
+ return 0;
3336
+ }
3337
+ //#endregion
3338
+ export { runTui };
3339
+
3340
+ //# sourceMappingURL=run-tui-Io8Xea0L.js.map