comfy-ts 2.4.2 → 2.6.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 (62) hide show
  1. package/README.md +12 -1
  2. package/dist/{DefinedWorkflow-CnzmQrBh.js → DefinedWorkflow-BJgt5t0x.js} +14 -3
  3. package/dist/DefinedWorkflow-BJgt5t0x.js.map +1 -0
  4. package/dist/{DraftsSt-C1MbWnEp.js → DraftsSt-dizp3VcC.js} +2 -2
  5. package/dist/{DraftsSt-C1MbWnEp.js.map → DraftsSt-dizp3VcC.js.map} +1 -1
  6. package/dist/cli.js +4 -4
  7. package/dist/index.cjs +3 -2
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +3 -0
  10. package/dist/index.d.ts +3 -0
  11. package/dist/index.js +3 -2
  12. package/dist/index.js.map +1 -1
  13. package/dist/{run-serve-D47Zas-a.js → run-serve-CVu39RNd.js} +330 -16
  14. package/dist/run-serve-CVu39RNd.js.map +1 -0
  15. package/dist/{run-tui-BqNO9Ck0.js → run-tui-idFhdO4f.js} +707 -527
  16. package/dist/run-tui-idFhdO4f.js.map +1 -0
  17. package/dist/serve-web.js +280 -0
  18. package/dist/{state-D9w1aJow.js → state-C90kdjtB.js} +3 -13
  19. package/dist/state-C90kdjtB.js.map +1 -0
  20. package/dist/web.d.ts +3 -0
  21. package/dist/web.js +3 -2
  22. package/dist/web.js.map +1 -1
  23. package/package.json +9 -7
  24. package/src/cli/serve/ServeApp.ts +314 -13
  25. package/src/cli/serve/describeVar.ts +6 -1
  26. package/src/cli/serve/run-serve.ts +4 -2
  27. package/src/cli/serve/web/api.ts +105 -0
  28. package/src/cli/serve/web/clipboard.ts +25 -0
  29. package/src/cli/serve/web/components/App.tsx +53 -0
  30. package/src/cli/serve/web/components/Gallery.tsx +186 -0
  31. package/src/cli/serve/web/components/PromptEnhancer.tsx +210 -0
  32. package/src/cli/serve/web/components/Sidebar.tsx +42 -0
  33. package/src/cli/serve/web/components/VarsForm.tsx +173 -0
  34. package/src/cli/serve/web/components/controls/BasicControls.tsx +95 -0
  35. package/src/cli/serve/web/components/controls/ImageControl.tsx +71 -0
  36. package/src/cli/serve/web/components/controls/LorasControl.tsx +340 -0
  37. package/src/cli/serve/web/components/controls/SeedControl.tsx +43 -0
  38. package/src/cli/serve/web/components/controls/SizeControl.tsx +49 -0
  39. package/src/cli/serve/web/main.tsx +18 -0
  40. package/src/cli/serve/web/openrouter.ts +142 -0
  41. package/src/cli/serve/web/state/EnhancerSt.ts +370 -0
  42. package/src/cli/serve/web/state/FormSt.ts +177 -0
  43. package/src/cli/serve/web/state/RunSt.ts +136 -0
  44. package/src/cli/serve/web/state/WebSt.ts +210 -0
  45. package/src/cli/serve/web/state/payload.ts +110 -0
  46. package/src/cli/serve/web/styles.ts +259 -0
  47. package/src/cli/serve/web/tsconfig.json +15 -0
  48. package/src/cli/serve/webBundle.ts +66 -0
  49. package/src/cli/tui/imageEscapes.ts +105 -0
  50. package/src/cli/tui/imagePicker/ImagePickerSt.ts +21 -8
  51. package/src/cli/tui/protocolImage.ts +39 -0
  52. package/src/cli/tui/protocolImagePainter.ts +56 -23
  53. package/src/cli/tui/run-tui.tsx +3 -2
  54. package/src/cli/tui/state/LorasSt.ts +22 -9
  55. package/src/cli/tui/state/PreviewSt.ts +31 -13
  56. package/src/cli/tui/state/SettingsSt.ts +1 -1
  57. package/src/cli/tui/state/TuiSt.ts +4 -4
  58. package/src/vars/ComfyVars.ts +4 -1
  59. package/dist/DefinedWorkflow-CnzmQrBh.js.map +0 -1
  60. package/dist/run-serve-D47Zas-a.js.map +0 -1
  61. package/dist/run-tui-BqNO9Ck0.js.map +0 -1
  62. package/dist/state-D9w1aJow.js.map +0 -1
@@ -1,12 +1,12 @@
1
- import { C as extractErrorMessage, D as logError, S as loraPreviewMapFrom, _ as fetchLoraPreviewBytes, a as getLoraKeyword, b as loraBasename, c as setLoraKeyword, d as getLoraPreviewUrl, f as loraMatchesFilter, g as fetchLoraList, i as clearLoraKeywordOverride, m as refreshLoraInfoCacheIfChanged, n as LorasVar, o as isLoraKeywordFromMirror, r as PromptVar, s as loraKeywordFromMirror, u as getLoraDisplayName, x as loraKey } from "./DefinedWorkflow-CnzmQrBh.js";
2
- import { a as importSharp, i as stripAnsi, n as settingsPathFor } from "./state-D9w1aJow.js";
3
- import { a as assignFamilyColors, c as findDefinedWorkflow, i as listDraftsForFile, l as mergeWorkflowSources, n as draftKeyForFile, o as buildFileRows, s as familyOf, t as DraftsSt, u as scanCflowFiles } from "./DraftsSt-C1MbWnEp.js";
1
+ import { C as loraPreviewMapFrom, S as loraKey, _ as fetchLoraList, a as getLoraKeyword, c as setLoraKeyword, d as getLoraPreviewUrl, h as refreshLoraInfoCacheIfChanged, i as clearLoraKeywordOverride, k as logError, n as LorasVar, o as isLoraKeywordFromMirror, p as loraMatchesFilter, r as PromptVar, s as loraKeywordFromMirror, u as getLoraDisplayName, v as fetchLoraPreviewBytes, w as extractErrorMessage, x as loraBasename } from "./DefinedWorkflow-BJgt5t0x.js";
2
+ import { a as importSharp, i as stripAnsi, n as settingsPathFor } from "./state-C90kdjtB.js";
3
+ import { a as assignFamilyColors, c as findDefinedWorkflow, i as listDraftsForFile, l as mergeWorkflowSources, n as draftKeyForFile, o as buildFileRows, s as familyOf, t as DraftsSt, u as scanCflowFiles } from "./DraftsSt-dizp3VcC.js";
4
4
  import { spawn } from "node:child_process";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
6
6
  import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
7
7
  import { basename, dirname, join, resolve } from "pathe";
8
8
  import { imageMeta } from "image-meta";
9
- import { makeAutoObservable, observable, reaction, runInAction } from "mobx";
9
+ import { makeAutoObservable, observableRef, reaction, runInAction } from "mobx";
10
10
  import { Box, Text, measureElement, render, useApp, useInput, useStdin } from "ink";
11
11
  import sharp from "sharp";
12
12
  import { observer } from "mobx-react-lite";
@@ -48,335 +48,205 @@ function bundledExamplesDir(moduleUrl = import.meta.url) {
48
48
  throw new Error(`[comfy-ts] no package.json found walking up from ${fileURLToPath(moduleUrl)}`);
49
49
  }
50
50
  //#endregion
51
- //#region src/utils/ansiImage.ts
52
- /**
53
- * render an image as truecolor half-block ANSI: each char cell is 1px wide and
54
- * 2px tall (bg color = top pixel, fg '▄' = bottom pixel). Works in any
55
- * truecolor terminal and — unlike protocol images (iTerm/kitty/sixel) —
56
- * survives ink's layout engine. width/height are CHAR CELLS.
57
- */
58
- async function imageBufferToAnsi(input, p) {
59
- const { data, info } = await sharp(input).flatten({ background: p.background ?? "#1e1e1e" }).resize(p.width, p.height * 2, { fit: "inside" }).raw().toBuffer({ resolveWithObject: true });
60
- const w = info.width;
61
- const h = info.height;
62
- const c = info.channels;
63
- const px = (x, y) => {
64
- const i = (y * w + x) * c;
65
- return [
66
- data[i] ?? 0,
67
- data[i + 1] ?? 0,
68
- data[i + 2] ?? 0
69
- ];
51
+ //#region src/cli/tui/imageEscapes.ts
52
+ const ESC = "\x1B";
53
+ /** APC terminator: ESC backslash */
54
+ const ST = "\x1B\\";
55
+ /** one OSC 1337 paint: cursor save → CUP → image sized in CELLS → cursor restore */
56
+ function itermImageEscape(bytes, row, col, w, h) {
57
+ const b64 = Buffer.from(bytes).toString("base64");
58
+ return `${ESC}7${ESC}[${row};${col}H${ESC}]1337;File=inline=1;size=${bytes.byteLength};width=${w};height=${h};preserveAspectRatio=1:${b64}\u0007${ESC}8`;
59
+ }
60
+ /** kitty stretches to the given cell box (no preserveAspectRatio key): fit the
61
+ * box to the image aspect first. Cells are ~1:2 (w:h), same as cornerBox. */
62
+ function fitCellBox(p) {
63
+ if (p.imgW <= 0 || p.imgH <= 0) return {
64
+ w: p.w,
65
+ h: p.h
70
66
  };
71
- const rows = [];
72
- for (let y = 0; y < h; y += 2) {
73
- let row = "";
74
- for (let x = 0; x < w; x++) {
75
- const [tr, tg, tb] = px(x, y);
76
- const [br, bg, bb] = y + 1 < h ? px(x, y + 1) : px(x, y);
77
- row += `\x1b[48;2;${tr};${tg};${tb}m\x1b[38;2;${br};${bg};${bb}m▄`;
78
- }
79
- rows.push(row + "\x1B[0m");
67
+ const aspect = p.imgW / p.imgH;
68
+ let w = p.w;
69
+ let h = Math.max(1, Math.round(w / aspect / 2));
70
+ if (h > p.h) {
71
+ h = p.h;
72
+ w = Math.max(1, Math.min(p.w, Math.round(h * aspect * 2)));
80
73
  }
81
- return rows.join("\n");
74
+ return {
75
+ w,
76
+ h
77
+ };
82
78
  }
83
- //#endregion
84
- //#region src/cli/tui/state/PreviewSt.ts
85
- /** OSC 1337 support: the panel can show REAL images instead of half-blocks */
86
- function protocolCapable() {
87
- if (process.env.COMFY_TS_NO_ITERM_IMAGES === "1") return false;
88
- const term = process.env.TERM_PROGRAM ?? "";
89
- return term === "iTerm.app" || term === "WezTerm" || term === "vscode" || process.env.LC_TERMINAL === "iTerm2";
79
+ const dimsCache = /* @__PURE__ */ new WeakMap();
80
+ /** header-only parse, cached per bytes object (the painter runs on every flush) */
81
+ function imageDims(bytes) {
82
+ const hit = dimsCache.get(bytes);
83
+ if (hit != null) return hit;
84
+ let dims = {
85
+ w: 0,
86
+ h: 0
87
+ };
88
+ try {
89
+ const meta = imageMeta(bytes);
90
+ if (meta.width != null && meta.height != null) dims = {
91
+ w: meta.width,
92
+ h: meta.height
93
+ };
94
+ } catch {}
95
+ dimsCache.set(bytes, dims);
96
+ return dims;
90
97
  }
91
- /** small-latent corner: fraction of the panel each dimension takes */
92
- const CORNER_FRACTION = .38;
93
- /** pixel 'latent small': the sharp-composited thumb takes this fraction of the panel */
94
- const PIXEL_SMALL_FRACTION = .4;
98
+ /** spec cap for one APC payload; continuation chunks carry only the m key */
99
+ const KITTY_CHUNK = 4096;
100
+ /** transmit png data under a fixed image id WITHOUT displaying it (a=t),
101
+ * base64 chunked with m=1/0 continuation */
102
+ function kittyTransmitEscape(bytes, id) {
103
+ const b64 = Buffer.from(bytes).toString("base64");
104
+ let out = "";
105
+ for (let i = 0; i < b64.length; i += KITTY_CHUNK) {
106
+ const last = i + KITTY_CHUNK >= b64.length;
107
+ const ctrl = i === 0 ? `a=t,f=100,t=d,i=${id},q=2,m=${last ? 0 : 1}` : `m=${last ? 0 : 1}`;
108
+ out += `${ESC}_G${ctrl};${b64.slice(i, i + KITTY_CHUNK)}${ST}`;
109
+ }
110
+ return out;
111
+ }
112
+ /** display a transmitted id at the cursor: same i,p replaces the previous
113
+ * placement, so repaints never accumulate; C=1 keeps the cursor put; z pins
114
+ * stacking (same-z overlaps draw newest-on-top, recency is not a contract) */
115
+ function kittyPlaceEscape(id, row, col, w, h, z) {
116
+ const zKey = z == null ? "" : `,z=${z}`;
117
+ return `${ESC}7${ESC}[${row};${col}H${ESC}_Ga=p,i=${id},p=1,c=${w},r=${h},C=1,q=2${zKey}${ST}${ESC}8`;
118
+ }
119
+ /** delete this id's placements AND free its data (uppercase I) */
120
+ function kittyDeleteEscape(id) {
121
+ return `${ESC}_Ga=d,d=I,i=${id},q=2${ST}`;
122
+ }
123
+ /** free every image + placement — the quit path: ED does not clear kitty images */
124
+ const KITTY_DELETE_ALL = `${ESC}_Ga=d,d=A,q=2${ST}`;
95
125
  /**
96
- * right-side preview panel + its `p` settings menu (mode 'preview').
97
- * Three independent axes live in SettingsSt: panel on/off, renderer
98
- * native/pixel, and what to show while running (latent / latent small /
99
- * last output). Sources: live latent while running, last output after,
100
- * selected lora while the loras overlay is open.
126
+ * per-id transmit-once bookkeeping: data uploads when the bytes OBJECT changes
127
+ * (delete-before-retransmit sidesteps the spec's underspecified reuse of a live
128
+ * id), a cheap placement re-paints every flush, drop deletes exactly once.
101
129
  */
102
- var PreviewSt = class {
103
- constructor(st) {
104
- this.st = st;
105
- this.outputAnsi = null;
106
- this.latentAnsi = null;
107
- this.outputBytes = null;
108
- this.latentBytes = null;
109
- this.latentDims = null;
110
- this.latentSeenThisRun = false;
111
- this.lastOutput = null;
112
- this.overlay = null;
113
- this.menuIx = 0;
114
- this._busy = false;
115
- makeAutoObservable(this, { st: false });
116
- }
117
- get show() {
118
- return this.st.settings.previewPanel;
119
- }
120
- get renderer() {
121
- return this.st.settings.previewRenderer;
122
- }
123
- get useNative() {
124
- return this.renderer === "native";
125
- }
126
- get duringRun() {
127
- return this.st.settings.previewDuringRun;
128
- }
129
- get menuOpen() {
130
- return this.st.mode === "preview";
131
- }
132
- get overlayActive() {
133
- return this.st.mode === "overlay-loras" || this.st.mode === "overlay-image";
134
- }
135
- setOverlayImage(p) {
136
- this.overlay = p;
137
- }
138
- clearOverlayImage() {
139
- this.overlay = null;
140
- }
141
- /** running + latents wanted + sampling well underway + none arrived = server
142
- * sends none. The ≥20% gate keeps healthy runs from red-flashing: the first
143
- * progress tick lands a beat before the first preview frame */
144
- get latentsMissing() {
145
- return this.st.exec.running && this.duringRun !== "last-output" && (this.st.exec.progress?.percent ?? 0) >= 20 && !this.latentSeenThisRun;
146
- }
147
- get menuRows() {
148
- return [
149
- {
150
- key: "panel",
151
- label: "panel",
152
- value: this.show ? "on" : "off"
153
- },
154
- {
155
- key: "renderer",
156
- label: "renderer",
157
- value: this.renderer + (protocolCapable() ? "" : " (no protocol support)")
158
- },
159
- {
160
- key: "during-run",
161
- label: "while running",
162
- value: this.duringRun === "latent" ? "latent" : this.duringRun === "latent-small" ? "latent small" : "last output"
163
- }
164
- ];
165
- }
166
- beginMenu() {
167
- this.st.mode = "preview";
168
- this.menuIx = 0;
169
- }
170
- blurMenu() {
171
- this.st.mode = "nav";
130
+ var KittyImageSlot = class {
131
+ constructor(id) {
132
+ this.id = id;
133
+ this.transmitted = null;
172
134
  }
173
- menuMove(delta) {
174
- const len = this.menuRows.length;
175
- this.menuIx = (this.menuIx + delta + len) % len;
176
- }
177
- /** cycle the selected row's value (settings persist via SettingsSt reaction) */
178
- menuCycle(delta) {
179
- const row = this.menuRows[this.menuIx];
180
- if (row == null) return;
181
- const s = this.st.settings;
182
- if (row.key === "panel") s.previewPanel = !s.previewPanel;
183
- else if (row.key === "renderer") {
184
- if (protocolCapable()) s.previewRenderer = s.previewRenderer === "native" ? "pixel" : "native";
185
- } else {
186
- const order = [
187
- "latent",
188
- "latent-small",
189
- "last-output"
190
- ];
191
- s.previewDuringRun = order[(order.indexOf(s.previewDuringRun) + delta + order.length) % order.length] ?? "latent";
192
- }
193
- this.onSettingsChanged();
194
- }
195
- reset() {
196
- this.outputAnsi = null;
197
- this.latentAnsi = null;
198
- this.outputBytes = null;
199
- this.latentBytes = null;
200
- this.latentDims = null;
201
- this.latentSeenThisRun = false;
202
- this.lastOutput = null;
203
- }
204
- /** run boundary: drop the latents so the next run never shows the previous one's */
205
- clearLatent() {
206
- this.latentAnsi = null;
207
- this.latentBytes = null;
208
- this.latentDims = null;
209
- this.latentSeenThisRun = false;
210
- }
211
- /** re-render the last output for the newly chosen settings */
212
- onSettingsChanged() {
213
- this.outputAnsi = null;
214
- this.outputBytes = null;
215
- if (this.show && this.lastOutput != null) this.renderOutput(this.lastOutput);
216
- }
217
- /** what the painter should show RIGHT NOW (native renderer only; mirrors the panel's source) */
218
- get protocolImage() {
219
- if (!this.useNative || !this.show || this.menuOpen) return null;
220
- if (this.overlayActive) return this.overlay?.bytes ?? null;
221
- if (this.st.exec.running) {
222
- if (this.duringRun === "latent") return this.latentBytes ?? this.outputBytes;
223
- return this.outputBytes;
224
- }
225
- return this.outputBytes;
226
- }
227
- /** small latent painted over the panel's top-right corner (native + 'latent small' only) */
228
- get protocolImageCorner() {
229
- if (!this.useNative || !this.show || this.menuOpen) return null;
230
- if (this.overlayActive) return null;
231
- if (this.st.exec.running && this.duringRun === "latent-small") return this.latentBytes;
232
- return null;
233
- }
234
- /** corner cell box matched to the latent's REAL aspect (a mismatched box
235
- * letterboxes in iTerm, showing a tall rectangle). Cells are
236
- * ~1:2 (w:h), hence the ×2 when converting image aspect to cells. */
237
- get cornerBox() {
238
- let w = Math.max(8, Math.floor(this.width * CORNER_FRACTION));
239
- const maxH = Math.max(4, Math.floor(this.height * CORNER_FRACTION));
240
- const dims = this.latentDims;
241
- if (dims == null || dims.width === 0 || dims.height === 0) return {
242
- w,
243
- h: maxH
244
- };
245
- const aspect = dims.width / dims.height;
246
- let h = Math.max(2, Math.round(w / aspect / 2));
247
- if (h > maxH) {
248
- h = maxH;
249
- w = Math.max(4, Math.round(h * aspect * 2));
250
- }
251
- return {
252
- w,
253
- h
254
- };
255
- }
256
- get width() {
257
- return Math.max(24, Math.min(80, this.st.termCols - 68 - this.st.treeWidth));
258
- }
259
- get height() {
260
- return Math.max(10, this.st.termRows - 12);
261
- }
262
- async renderOutput(src) {
263
- this.lastOutput = src;
264
- if (!this.show) return;
265
- try {
266
- if (this.useNative) {
267
- const shrunk = await sharp(src).resize(896, 896, {
268
- fit: "inside",
269
- withoutEnlargement: true
270
- }).png().toBuffer();
271
- runInAction(() => {
272
- this.outputBytes = new Uint8Array(shrunk);
273
- });
274
- return;
275
- }
276
- const rendered = await imageBufferToAnsi(src, {
277
- width: this.width,
278
- height: this.height
279
- });
280
- runInAction(() => {
281
- this.outputAnsi = rendered;
282
- });
283
- } catch (e) {
284
- runInAction(() => {
285
- this.st.exec.notice = `preview: ${extractErrorMessage(e)}`;
286
- });
287
- }
288
- }
289
- async renderLatent(bytes) {
290
- runInAction(() => {
291
- this.latentSeenThisRun = true;
292
- });
293
- if (!this.show || this.duringRun === "last-output") return;
294
- if (this.useNative) {
295
- const meta = imageMeta(bytes);
296
- this.latentBytes = bytes;
297
- this.latentDims = meta.width != null && meta.height != null ? {
298
- width: meta.width,
299
- height: meta.height
300
- } : null;
301
- return;
302
- }
303
- if (this._busy) return;
304
- this._busy = true;
305
- try {
306
- const ansi = this.duringRun === "latent-small" ? await this.renderLatentSmallPixel(bytes) : await imageBufferToAnsi(bytes, {
307
- width: this.width,
308
- height: this.height
309
- });
310
- runInAction(() => {
311
- this.latentAnsi = ansi;
312
- });
313
- } catch (e) {
314
- runInAction(() => {
315
- this.st.exec.notice = `latent preview: ${extractErrorMessage(e)}`;
316
- });
317
- } finally {
318
- this._busy = false;
135
+ show(bytes, row, col, w, h, z) {
136
+ let out = "";
137
+ if (this.transmitted !== bytes) {
138
+ out += kittyDeleteEscape(this.id) + kittyTransmitEscape(bytes, this.id);
139
+ this.transmitted = bytes;
319
140
  }
141
+ return out + kittyPlaceEscape(this.id, row, col, w, h, z);
320
142
  }
321
- /** pixel 'latent small': sharp-composite the latent thumb onto the last
322
- * output (top-right), then ONE half-block render — a string-level overlay
323
- * was tried and dropped: its space padding reads as black bars */
324
- async renderLatentSmallPixel(bytes) {
325
- const pxW = this.width;
326
- const pxH = this.height * 2;
327
- const thumb = await sharp(bytes).resize(Math.max(8, Math.floor(pxW * PIXEL_SMALL_FRACTION)), Math.max(8, Math.floor(pxH * PIXEL_SMALL_FRACTION)), { fit: "inside" }).png().toBuffer();
328
- const out = this.lastOutput;
329
- if (out == null) return imageBufferToAnsi(thumb, {
330
- width: this.width,
331
- height: this.height
332
- });
333
- return imageBufferToAnsi(await sharp(await sharp(out).resize(pxW, pxH, { fit: "inside" }).png().toBuffer()).composite([{
334
- input: thumb,
335
- gravity: "northeast"
336
- }]).png().toBuffer(), {
337
- width: this.width,
338
- height: this.height
339
- });
143
+ drop() {
144
+ if (this.transmitted == null) return "";
145
+ this.transmitted = null;
146
+ return kittyDeleteEscape(this.id);
340
147
  }
341
148
  };
342
149
  //#endregion
150
+ //#region src/cli/tui/protocolImage.ts
151
+ function imageProtocol() {
152
+ if (process.env.COMFY_TS_NO_ITERM_IMAGES === "1") return null;
153
+ const term = process.env.TERM ?? "";
154
+ const program = process.env.TERM_PROGRAM ?? "";
155
+ if (term.includes("kitty") || term.includes("ghostty") || process.env.KITTY_WINDOW_ID != null || process.env.GHOSTTY_RESOURCES_DIR != null) return "kitty";
156
+ return program === "iTerm.app" || program === "WezTerm" || program === "vscode" || process.env.LC_TERMINAL === "iTerm2" ? "iterm" : null;
157
+ }
158
+ function protocolCapable() {
159
+ return imageProtocol() != null;
160
+ }
161
+ const PNG_MAGIC = [
162
+ 137,
163
+ 80,
164
+ 78,
165
+ 71,
166
+ 13,
167
+ 10,
168
+ 26,
169
+ 10
170
+ ];
171
+ function isPng(bytes) {
172
+ return PNG_MAGIC.every((byte, ix) => bytes[ix] === byte);
173
+ }
174
+ /** kitty only draws png (f=100), never jpeg/webp; iterm takes any format.
175
+ * Pass every native-renderer byte source that is not sharp-produced png through here. */
176
+ async function protocolReadyBytes(bytes) {
177
+ if (imageProtocol() !== "kitty" || isPng(bytes)) return bytes;
178
+ return new Uint8Array(await sharp(bytes).png().toBuffer());
179
+ }
180
+ //#endregion
343
181
  //#region src/cli/tui/protocolImagePainter.ts
344
182
  const SYNC_BEGIN = "\x1B[?2026h";
345
183
  const SYNC_END = "\x1B[?2026l";
346
184
  /** below this a write is a terminal query/reply, not a frame — no cells damaged */
347
185
  const MIN_FRAME_BYTES = 64;
186
+ /** kitty image ids: fixed, transmit-once bookkeeping keys */
187
+ const MAIN_ID = 1;
188
+ const CORNER_ID = 2;
189
+ /** corner placement z: pins the small latent ABOVE the main image (same-z
190
+ * stacking is recency, and a fresh output recreates MAIN after the corner) */
191
+ const CORNER_Z = 1;
348
192
  /**
349
- * paints the REAL image (OSC 1337) over the preview panel's cell rect.
350
- * Protocol images cannot go THROUGH ink (layout shreds the escape) and every
351
- * ink frame write ERASES the image's cells — so this hooks stdout.write and
352
- * re-paints SYNCHRONOUSLY within the same flush, the whole batch wrapped in
353
- * DEC 2026 synchronized-update markers: the terminal never presents the
354
- * erased-frame intermediate state. (The previous deferred setImmediate
355
- * repaint WAS the native-mode flicker.) A mobx reaction covers
193
+ * paints the REAL image (iTerm OSC 1337 / kitty APC _G) over the preview
194
+ * panel's cell rect. Protocol images cannot go THROUGH ink (layout shreds the
195
+ * escape) and every ink frame write ERASES the image's cells — so this hooks
196
+ * stdout.write and re-paints SYNCHRONOUSLY within the same flush, the whole
197
+ * batch wrapped in DEC 2026 synchronized-update markers: the terminal never
198
+ * presents the erased-frame intermediate state. (The previous deferred
199
+ * setImmediate repaint WAS the native-mode flicker.) A mobx reaction covers
356
200
  * byte-only changes (fresh latent/output/lora bytes with no frame write).
357
201
  * NOT React: effects only fire for the component that re-rendered, which is
358
202
  * why a useEffect painter missed frames (reported: the image waited for input).
203
+ * Kitty differs from iterm in three ways the code below encodes: data uploads
204
+ * ONCE per bytes object then a tiny placement re-paints per flush (same i,p
205
+ * replaces); kitty draws images OVER later text, so a gone image needs an
206
+ * explicit delete or it covers the menu; the cell box stretches, so it is
207
+ * fitted to the image aspect first.
359
208
  */
360
209
  function installProtocolImagePainter(st) {
361
- if (!protocolCapable() || process.stdout.isTTY !== true) return () => {};
210
+ const proto = imageProtocol();
211
+ if (proto == null || process.stdout.isTTY !== true) return () => {};
362
212
  const original = process.stdout.write.bind(process.stdout);
363
- const imageEscape = (bytes, row, col, w, h) => {
364
- const b64 = Buffer.from(bytes).toString("base64");
365
- return `\u001b7\u001b[${row};${col}H\u001b]1337;File=inline=1;size=${bytes.byteLength};width=${w};height=${h};preserveAspectRatio=1:${b64}\u0007\u001b8`;
366
- };
367
213
  const CONTENT_ROW = 6;
368
- /** both images as ONE escape string ('' when nothing to paint) */
214
+ const kittyMain = new KittyImageSlot(MAIN_ID);
215
+ const kittyCorner = new KittyImageSlot(CORNER_ID);
216
+ /** both images as ONE escape string ('' when nothing to paint or delete) */
369
217
  const imageEscapes = () => {
370
218
  const pv = st.preview;
371
219
  const main = pv.protocolImage;
372
220
  const corner = pv.protocolImageCorner;
373
- if (main == null && corner == null) return "";
374
221
  const col = Math.max(1, st.termCols - (pv.width + 4) + 3);
222
+ if (proto === "iterm") {
223
+ if (main == null && corner == null) return "";
224
+ let out = "";
225
+ if (main != null) out += itermImageEscape(main, CONTENT_ROW, col, pv.width, pv.height);
226
+ if (corner != null) {
227
+ const box = pv.cornerBox;
228
+ out += itermImageEscape(corner, CONTENT_ROW, col + pv.width - box.w, box.w, box.h);
229
+ }
230
+ return out;
231
+ }
375
232
  let out = "";
376
- if (main != null) out += imageEscape(main, CONTENT_ROW, col, pv.width, pv.height);
377
- if (corner != null) {
233
+ if (main == null) out += kittyMain.drop();
234
+ else {
235
+ const dims = imageDims(main);
236
+ const box = fitCellBox({
237
+ imgW: dims.w,
238
+ imgH: dims.h,
239
+ w: pv.width,
240
+ h: pv.height
241
+ });
242
+ const row = CONTENT_ROW + Math.max(0, Math.floor((pv.height - box.h) / 2));
243
+ const c = col + Math.max(0, Math.floor((pv.width - box.w) / 2));
244
+ out += kittyMain.show(main, row, c, box.w, box.h);
245
+ }
246
+ if (corner == null) out += kittyCorner.drop();
247
+ else {
378
248
  const box = pv.cornerBox;
379
- out += imageEscape(corner, CONTENT_ROW, col + pv.width - box.w, box.w, box.h);
249
+ out += kittyCorner.show(corner, CONTENT_ROW, col + pv.width - box.w, box.w, box.h, CORNER_Z);
380
250
  }
381
251
  return out;
382
252
  };
@@ -404,6 +274,7 @@ function installProtocolImagePainter(st) {
404
274
  const disposeReaction = reaction(() => [st.preview.protocolImage, st.preview.protocolImageCorner], schedule);
405
275
  return () => {
406
276
  disposed = true;
277
+ if (proto === "kitty") original(KITTY_DELETE_ALL);
407
278
  process.stdout.write = original;
408
279
  disposeReaction();
409
280
  };
@@ -1274,6 +1145,39 @@ function fuzzyMatch(needle, hay) {
1274
1145
  return i >= n.length;
1275
1146
  }
1276
1147
  //#endregion
1148
+ //#region src/utils/ansiImage.ts
1149
+ /**
1150
+ * render an image as truecolor half-block ANSI: each char cell is 1px wide and
1151
+ * 2px tall (bg color = top pixel, fg '▄' = bottom pixel). Works in any
1152
+ * truecolor terminal and — unlike protocol images (iTerm/kitty/sixel) —
1153
+ * survives ink's layout engine. width/height are CHAR CELLS.
1154
+ */
1155
+ async function imageBufferToAnsi(input, p) {
1156
+ const { data, info } = await sharp(input).flatten({ background: p.background ?? "#1e1e1e" }).resize(p.width, p.height * 2, { fit: "inside" }).raw().toBuffer({ resolveWithObject: true });
1157
+ const w = info.width;
1158
+ const h = info.height;
1159
+ const c = info.channels;
1160
+ const px = (x, y) => {
1161
+ const i = (y * w + x) * c;
1162
+ return [
1163
+ data[i] ?? 0,
1164
+ data[i + 1] ?? 0,
1165
+ data[i + 2] ?? 0
1166
+ ];
1167
+ };
1168
+ const rows = [];
1169
+ for (let y = 0; y < h; y += 2) {
1170
+ let row = "";
1171
+ for (let x = 0; x < w; x++) {
1172
+ const [tr, tg, tb] = px(x, y);
1173
+ const [br, bg, bb] = y + 1 < h ? px(x, y + 1) : px(x, y);
1174
+ row += `\x1b[48;2;${tr};${tg};${tb}m\x1b[38;2;${br};${bg};${bb}m▄`;
1175
+ }
1176
+ rows.push(row + "\x1B[0m");
1177
+ }
1178
+ return rows.join("\n");
1179
+ }
1180
+ //#endregion
1277
1181
  //#region src/cli/tui/imagePicker/ImagePickerSt.ts
1278
1182
  const PICKER_PANES = [
1279
1183
  "browse",
@@ -1482,11 +1386,11 @@ var ImagePickerSt = class {
1482
1386
  try {
1483
1387
  const bytes = new Uint8Array(readFileSync(path));
1484
1388
  if (this.st.preview.useNative) this.st.preview.setOverlayImage({
1485
- bytes,
1389
+ bytes: await protocolReadyBytes(bytes),
1486
1390
  ansi: null,
1487
1391
  name: basename(path),
1488
1392
  note: null
1489
- });
1393
+ }, "overlay-image");
1490
1394
  else {
1491
1395
  const ansi = await imageBufferToAnsi(bytes, {
1492
1396
  width: this.st.preview.width,
@@ -1497,7 +1401,7 @@ var ImagePickerSt = class {
1497
1401
  ansi,
1498
1402
  name: basename(path),
1499
1403
  note: null
1500
- });
1404
+ }, "overlay-image");
1501
1405
  }
1502
1406
  } catch (e) {
1503
1407
  this.st.preview.setOverlayImage({
@@ -1505,7 +1409,7 @@ var ImagePickerSt = class {
1505
1409
  ansi: null,
1506
1410
  name: basename(path),
1507
1411
  note: extractErrorMessage(e)
1508
- });
1412
+ }, "overlay-image");
1509
1413
  } finally {
1510
1414
  this._busy = false;
1511
1415
  if (this.st.mode === "overlay-image" && this.highlightedImage !== path) this.refreshPreview();
@@ -3421,268 +3325,544 @@ var LorasSt = class {
3421
3325
  /** kind-narrowing cast sanctioned (agent/coding.md), `kind` is the tag */
3422
3326
  get selectedVar() {
3423
3327
  const sel = this.st.selected?.[1];
3424
- return sel?.kind === "loras" ? sel : null;
3328
+ return sel?.kind === "loras" ? sel : null;
3329
+ }
3330
+ /**
3331
+ * the host a run will actually target, which is what the metadata must
3332
+ * describe. NOT `wf.host`: pressing `h` overrides the run host, and reading
3333
+ * the defining host's mirror then showed one host's model names while the
3334
+ * generation went to another. `bindHost` also stamped the defining host onto
3335
+ * the var at define time, so the injected keywords are re-pointed with it.
3336
+ */
3337
+ get hostId() {
3338
+ return this.st.runHost.data.id;
3339
+ }
3340
+ /**
3341
+ * options surviving the filter (bulk ops apply to exactly these).
3342
+ * The filter matches the file name OR anything the lora-manager mirror knows:
3343
+ * model name, tags, base model, trigger words.
3344
+ */
3345
+ get filteredNames() {
3346
+ const lv = this.selectedVar;
3347
+ if (lv == null) return [];
3348
+ if (this.filter === "") return lv.names;
3349
+ return lv.names.filter((n) => loraMatchesFilter(n, this.filter, this.hostId));
3350
+ }
3351
+ begin() {
3352
+ if (this.selectedVar == null) return;
3353
+ refreshLoraInfoCacheIfChanged();
3354
+ const lv = this.selectedVar;
3355
+ if (lv != null) lv.hostId = this.hostId;
3356
+ this.st.mode = "overlay-loras";
3357
+ this.ix = 0;
3358
+ this.filter = "";
3359
+ this.st.preview.clearOverlayImage();
3360
+ }
3361
+ move(delta) {
3362
+ const len = this.filteredNames.length;
3363
+ if (len === 0) return;
3364
+ this.ix = (this.ix + delta + len) % len;
3365
+ }
3366
+ filterInput(chunk) {
3367
+ this.filter += chunk;
3368
+ this.ix = 0;
3369
+ }
3370
+ filterBackspace() {
3371
+ this.filter = this.filter.slice(0, -1);
3372
+ this.ix = 0;
3373
+ }
3374
+ /** ⌥⌫ / ⌃W: drop the last word of the filter */
3375
+ filterDeleteWord() {
3376
+ this.filter = this.filter.replace(/\s*\S+\s*$/, "");
3377
+ this.ix = 0;
3378
+ }
3379
+ toggle() {
3380
+ const lv = this.selectedVar;
3381
+ const name = this.filteredNames[this.ix];
3382
+ if (lv == null || name == null) return;
3383
+ lv.toggleItem(name);
3384
+ }
3385
+ /** ⌃A / ⌃N: tick / untick every lora surviving the filter */
3386
+ setAll(on) {
3387
+ this.selectedVar?.setAll(on, this.filteredNames);
3388
+ }
3389
+ adjust(delta) {
3390
+ const lv = this.selectedVar;
3391
+ const name = this.filteredNames[this.ix];
3392
+ if (lv == null || name == null) return;
3393
+ lv.adjustItem(name, delta);
3394
+ }
3395
+ /** ⌃K: assign the selected lora's trigger keyword (PromptVar prefixes actives with it) */
3396
+ beginKeyword() {
3397
+ const name = this.selectedName;
3398
+ if (name == null) return;
3399
+ const fromMirror = loraKeywordFromMirror(name, this.hostId);
3400
+ const hint = fromMirror === "" ? "empty clears" : isLoraKeywordFromMirror(name, this.hostId) ? "from lora-manager · empty = inject nothing" : `overrides lora-manager · esc then ⌃D restores "${fromMirror}"`;
3401
+ this.st.editor.beginCustom({
3402
+ title: `keyword for ${LorasVar.shortName(name)} (${hint})`,
3403
+ initial: getLoraKeyword(name, this.hostId),
3404
+ onCommit: (raw) => {
3405
+ setLoraKeyword(name, raw, this.hostId);
3406
+ return true;
3407
+ },
3408
+ returnMode: "overlay-loras"
3409
+ });
3410
+ }
3411
+ /** ⌃D: drop the hand keyword, so this lora falls back to lora-manager's trigger words */
3412
+ resetKeyword() {
3413
+ const name = this.selectedName;
3414
+ if (name == null) return;
3415
+ clearLoraKeywordOverride(name);
3416
+ }
3417
+ get selectedName() {
3418
+ return this.filteredNames[this.ix] ?? null;
3419
+ }
3420
+ /** preview goes through PreviewSt's shared overlay slot (one code path with the image picker) */
3421
+ async refreshPreview() {
3422
+ if (this.st.mode !== "overlay-loras") {
3423
+ if (!this.st.preview.overlayActive) this.st.preview.clearOverlayImage();
3424
+ return;
3425
+ }
3426
+ const name = this.selectedName;
3427
+ if (name == null || this._busy) return;
3428
+ this._busy = true;
3429
+ try {
3430
+ const host = this.st.runHost;
3431
+ let url = getLoraPreviewUrl(name, host.data.id);
3432
+ let miss = "no preview available";
3433
+ if (url == null) {
3434
+ if (this.previewMap === void 0 || this.previewMapHostId !== host.data.id) {
3435
+ const sweep = await fetchLoraList(host);
3436
+ this.previewMap = sweep.status === "absent" || sweep.status === "unreachable" ? null : loraPreviewMapFrom(sweep.items);
3437
+ this.previewSweepStatus = sweep.status;
3438
+ this.previewMapHostId = host.data.id;
3439
+ }
3440
+ url = this.previewMap?.get(loraKey(name)) ?? null;
3441
+ if (this.previewSweepStatus === "absent") miss = "lora-manager extension not detected";
3442
+ else if (this.previewSweepStatus === "unreachable") miss = "host unreachable";
3443
+ else if (this.previewSweepStatus === "partial") miss = "lora-manager answered only part of its list";
3444
+ }
3445
+ const note = url != null ? null : miss;
3446
+ if (url == null) {
3447
+ this.st.preview.setOverlayImage({
3448
+ bytes: null,
3449
+ ansi: null,
3450
+ name: `lora ${name}`,
3451
+ note
3452
+ }, "overlay-loras");
3453
+ return;
3454
+ }
3455
+ const bytes = await fetchLoraPreviewBytes(host, url);
3456
+ if (bytes == null) throw new Error("no image preview on the server");
3457
+ if (this.st.preview.useNative) {
3458
+ this.st.preview.setOverlayImage({
3459
+ bytes: await protocolReadyBytes(bytes),
3460
+ ansi: null,
3461
+ name: `lora ${name}`,
3462
+ note: null
3463
+ }, "overlay-loras");
3464
+ return;
3465
+ }
3466
+ const ansi = await imageBufferToAnsi(bytes, {
3467
+ width: this.st.preview.width,
3468
+ height: this.st.preview.height
3469
+ });
3470
+ this.st.preview.setOverlayImage({
3471
+ bytes: null,
3472
+ ansi,
3473
+ name: `lora ${name}`,
3474
+ note: null
3475
+ }, "overlay-loras");
3476
+ } catch (e) {
3477
+ this.st.preview.setOverlayImage({
3478
+ bytes: null,
3479
+ ansi: null,
3480
+ name: `lora ${name}`,
3481
+ note: extractErrorMessage(e)
3482
+ }, "overlay-loras");
3483
+ } finally {
3484
+ this._busy = false;
3485
+ if (this.st.mode === "overlay-loras" && this.selectedName !== name) this.refreshPreview();
3486
+ }
3487
+ }
3488
+ };
3489
+ //#endregion
3490
+ //#region src/cli/tui/state/PickerSt.ts
3491
+ /**
3492
+ * choice + size overlays: a windowed option list with a fuzzy type-to-filter.
3493
+ * For sizes the filter doubles as free `WxH` entry.
3494
+ */
3495
+ var PickerSt = class {
3496
+ constructor(st) {
3497
+ this.st = st;
3498
+ this.filter = "";
3499
+ this.ix = 0;
3500
+ this.invalid = false;
3501
+ this.imageSizeRow = null;
3502
+ makeAutoObservable(this, { st: false });
3503
+ }
3504
+ get choiceVar() {
3505
+ const sel = this.st.selected?.[1];
3506
+ return sel?.kind === "choice" ? sel : null;
3507
+ }
3508
+ get sizeVar() {
3509
+ const sel = this.st.selected?.[1];
3510
+ return sel?.kind === "size" ? sel : null;
3425
3511
  }
3426
- /**
3427
- * the host a run will actually target, which is what the metadata must
3428
- * describe. NOT `wf.host`: pressing `h` overrides the run host, and reading
3429
- * the defining host's mirror then showed one host's model names while the
3430
- * generation went to another. `bindHost` also stamped the defining host onto
3431
- * the var at define time, so the injected keywords are re-pointed with it.
3432
- */
3433
- get hostId() {
3434
- return this.st.runHost.data.id;
3512
+ get options() {
3513
+ const cv = this.choiceVar;
3514
+ if (cv != null) {
3515
+ if (this.filter === "") return [...cv.choices];
3516
+ return cv.choices.filter((c) => fuzzyMatch(this.filter, c));
3517
+ }
3518
+ const sv = this.sizeVar;
3519
+ if (sv != null) {
3520
+ const labels = sv.presets.map((p) => `${p.width}×${p.height} ${p.label}`);
3521
+ if (this.imageSizeRow != null) labels.unshift(this.imageSizeRow);
3522
+ if (this.filter === "") return labels;
3523
+ return labels.filter((l) => fuzzyMatch(this.filter, l));
3524
+ }
3525
+ return [];
3435
3526
  }
3436
- /**
3437
- * options surviving the filter (bulk ops apply to exactly these).
3438
- * The filter matches the file name OR anything the lora-manager mirror knows:
3439
- * model name, tags, base model, trigger words.
3440
- */
3441
- get filteredNames() {
3442
- const lv = this.selectedVar;
3443
- if (lv == null) return [];
3444
- if (this.filter === "") return lv.names;
3445
- return lv.names.filter((n) => loraMatchesFilter(n, this.filter, this.hostId));
3527
+ beginChoice() {
3528
+ const cv = this.choiceVar;
3529
+ if (cv == null) return;
3530
+ this.st.mode = "overlay-choice";
3531
+ this.filter = "";
3532
+ this.invalid = false;
3533
+ this.ix = Math.max(0, cv.choices.indexOf(cv.value));
3446
3534
  }
3447
- begin() {
3448
- if (this.selectedVar == null) return;
3449
- refreshLoraInfoCacheIfChanged();
3450
- const lv = this.selectedVar;
3451
- if (lv != null) lv.hostId = this.hostId;
3452
- this.st.mode = "overlay-loras";
3453
- this.ix = 0;
3535
+ beginSize() {
3536
+ const sv = this.sizeVar;
3537
+ if (sv == null) return;
3538
+ this.st.mode = "overlay-size";
3454
3539
  this.filter = "";
3455
- this.st.preview.clearOverlayImage();
3540
+ this.invalid = false;
3541
+ const img = sv.imageSize();
3542
+ this.imageSizeRow = img == null ? null : `${img.width}×${img.height} size of image '${img.name}'`;
3543
+ const presetIx = sv.presets.findIndex((p) => p.width === sv.value.width && p.height === sv.value.height);
3544
+ this.ix = presetIx === -1 ? 0 : presetIx + (this.imageSizeRow != null ? 1 : 0);
3456
3545
  }
3457
3546
  move(delta) {
3458
- const len = this.filteredNames.length;
3547
+ const len = this.options.length;
3459
3548
  if (len === 0) return;
3460
3549
  this.ix = (this.ix + delta + len) % len;
3461
3550
  }
3462
3551
  filterInput(chunk) {
3463
3552
  this.filter += chunk;
3464
3553
  this.ix = 0;
3554
+ this.invalid = false;
3465
3555
  }
3466
3556
  filterBackspace() {
3467
3557
  this.filter = this.filter.slice(0, -1);
3468
3558
  this.ix = 0;
3559
+ this.invalid = false;
3469
3560
  }
3470
3561
  /** ⌥⌫ / ⌃W: drop the last word of the filter */
3471
3562
  filterDeleteWord() {
3472
3563
  this.filter = this.filter.replace(/\s*\S+\s*$/, "");
3473
3564
  this.ix = 0;
3565
+ this.invalid = false;
3474
3566
  }
3475
- toggle() {
3476
- const lv = this.selectedVar;
3477
- const name = this.filteredNames[this.ix];
3478
- if (lv == null || name == null) return;
3479
- lv.toggleItem(name);
3567
+ commit() {
3568
+ const cv = this.choiceVar;
3569
+ if (cv != null) {
3570
+ const hit = this.options[this.ix];
3571
+ if (hit == null) return;
3572
+ cv.set(hit);
3573
+ this.st.mode = "nav";
3574
+ return;
3575
+ }
3576
+ const sv = this.sizeVar;
3577
+ if (sv == null) return;
3578
+ const hit = this.options[this.ix];
3579
+ if (hit != null) {
3580
+ const m = hit.match(/^(\d+)×(\d+)/);
3581
+ if (m != null) sv.set({
3582
+ width: Number(m[1]),
3583
+ height: Number(m[2])
3584
+ });
3585
+ this.st.mode = "nav";
3586
+ return;
3587
+ }
3588
+ if (sv.parse(this.filter)) this.st.mode = "nav";
3589
+ else this.invalid = true;
3480
3590
  }
3481
- /** ⌃A / ⌃N: tick / untick every lora surviving the filter */
3482
- setAll(on) {
3483
- this.selectedVar?.setAll(on, this.filteredNames);
3591
+ };
3592
+ //#endregion
3593
+ //#region src/cli/tui/state/PreviewSt.ts
3594
+ /** small-latent corner: fraction of the panel each dimension takes */
3595
+ const CORNER_FRACTION = .38;
3596
+ /** pixel 'latent small': the sharp-composited thumb takes this fraction of the panel */
3597
+ const PIXEL_SMALL_FRACTION = .4;
3598
+ /**
3599
+ * right-side preview panel + its `p` settings menu (mode 'preview').
3600
+ * Three independent axes live in SettingsSt: panel on/off, renderer
3601
+ * native/pixel, and what to show while running (latent / latent small /
3602
+ * last output). Sources: live latent while running, last output after,
3603
+ * selected lora while the loras overlay is open.
3604
+ */
3605
+ var PreviewSt = class {
3606
+ constructor(st) {
3607
+ this.st = st;
3608
+ this.outputAnsi = null;
3609
+ this.latentAnsi = null;
3610
+ this.outputBytes = null;
3611
+ this.latentBytes = null;
3612
+ this.latentDims = null;
3613
+ this.latentSeenThisRun = false;
3614
+ this.lastOutput = null;
3615
+ this.overlay = null;
3616
+ this.menuIx = 0;
3617
+ this._busy = false;
3618
+ makeAutoObservable(this, { st: false });
3484
3619
  }
3485
- adjust(delta) {
3486
- const lv = this.selectedVar;
3487
- const name = this.filteredNames[this.ix];
3488
- if (lv == null || name == null) return;
3489
- lv.adjustItem(name, delta);
3620
+ get show() {
3621
+ return this.st.settings.previewPanel;
3490
3622
  }
3491
- /** ⌃K: assign the selected lora's trigger keyword (PromptVar prefixes actives with it) */
3492
- beginKeyword() {
3493
- const name = this.selectedName;
3494
- if (name == null) return;
3495
- const fromMirror = loraKeywordFromMirror(name, this.hostId);
3496
- const hint = fromMirror === "" ? "empty clears" : isLoraKeywordFromMirror(name, this.hostId) ? "from lora-manager · empty = inject nothing" : `overrides lora-manager · esc then ⌃D restores "${fromMirror}"`;
3497
- this.st.editor.beginCustom({
3498
- title: `keyword for ${LorasVar.shortName(name)} (${hint})`,
3499
- initial: getLoraKeyword(name, this.hostId),
3500
- onCommit: (raw) => {
3501
- setLoraKeyword(name, raw, this.hostId);
3502
- return true;
3623
+ get renderer() {
3624
+ return this.st.settings.previewRenderer;
3625
+ }
3626
+ get useNative() {
3627
+ return this.renderer === "native";
3628
+ }
3629
+ get duringRun() {
3630
+ return this.st.settings.previewDuringRun;
3631
+ }
3632
+ get menuOpen() {
3633
+ return this.st.mode === "preview";
3634
+ }
3635
+ get overlayActive() {
3636
+ return this.st.mode === "overlay-loras" || this.st.mode === "overlay-image";
3637
+ }
3638
+ /** owner = the overlay mode the render was FOR: every writer awaits (file
3639
+ * read, fetch, transcode) before landing here, and by then another overlay
3640
+ * can own the slot — a stale write would overwrite its image */
3641
+ setOverlayImage(p, owner) {
3642
+ if (this.st.mode !== owner) return;
3643
+ this.overlay = p;
3644
+ }
3645
+ clearOverlayImage() {
3646
+ this.overlay = null;
3647
+ }
3648
+ /** running + latents wanted + sampling well underway + none arrived = server
3649
+ * sends none. The ≥20% gate keeps healthy runs from red-flashing: the first
3650
+ * progress tick lands a beat before the first preview frame */
3651
+ get latentsMissing() {
3652
+ return this.st.exec.running && this.duringRun !== "last-output" && (this.st.exec.progress?.percent ?? 0) >= 20 && !this.latentSeenThisRun;
3653
+ }
3654
+ get menuRows() {
3655
+ return [
3656
+ {
3657
+ key: "panel",
3658
+ label: "panel",
3659
+ value: this.show ? "on" : "off"
3503
3660
  },
3504
- returnMode: "overlay-loras"
3505
- });
3661
+ {
3662
+ key: "renderer",
3663
+ label: "renderer",
3664
+ value: this.renderer + (protocolCapable() ? "" : " (this terminal cannot show real images)")
3665
+ },
3666
+ {
3667
+ key: "during-run",
3668
+ label: "while running",
3669
+ value: this.duringRun === "latent" ? "latent" : this.duringRun === "latent-small" ? "latent small" : "last output"
3670
+ }
3671
+ ];
3672
+ }
3673
+ beginMenu() {
3674
+ this.st.mode = "preview";
3675
+ this.menuIx = 0;
3676
+ }
3677
+ blurMenu() {
3678
+ this.st.mode = "nav";
3679
+ }
3680
+ menuMove(delta) {
3681
+ const len = this.menuRows.length;
3682
+ this.menuIx = (this.menuIx + delta + len) % len;
3683
+ }
3684
+ /** cycle the selected row's value (settings persist via SettingsSt reaction) */
3685
+ menuCycle(delta) {
3686
+ const row = this.menuRows[this.menuIx];
3687
+ if (row == null) return;
3688
+ const s = this.st.settings;
3689
+ if (row.key === "panel") s.previewPanel = !s.previewPanel;
3690
+ else if (row.key === "renderer") {
3691
+ if (protocolCapable()) s.previewRenderer = s.previewRenderer === "native" ? "pixel" : "native";
3692
+ } else {
3693
+ const order = [
3694
+ "latent",
3695
+ "latent-small",
3696
+ "last-output"
3697
+ ];
3698
+ s.previewDuringRun = order[(order.indexOf(s.previewDuringRun) + delta + order.length) % order.length] ?? "latent";
3699
+ }
3700
+ this.onSettingsChanged();
3701
+ }
3702
+ reset() {
3703
+ this.outputAnsi = null;
3704
+ this.latentAnsi = null;
3705
+ this.outputBytes = null;
3706
+ this.latentBytes = null;
3707
+ this.latentDims = null;
3708
+ this.latentSeenThisRun = false;
3709
+ this.lastOutput = null;
3710
+ }
3711
+ /** run boundary: drop the latents so the next run never shows the previous one's */
3712
+ clearLatent() {
3713
+ this.latentAnsi = null;
3714
+ this.latentBytes = null;
3715
+ this.latentDims = null;
3716
+ this.latentSeenThisRun = false;
3717
+ }
3718
+ /** re-render the last output for the newly chosen settings */
3719
+ onSettingsChanged() {
3720
+ this.outputAnsi = null;
3721
+ this.outputBytes = null;
3722
+ if (this.show && this.lastOutput != null) this.renderOutput(this.lastOutput);
3723
+ }
3724
+ /** what the painter should show RIGHT NOW (native renderer only; mirrors the panel's source) */
3725
+ get protocolImage() {
3726
+ if (!this.useNative || !this.show || this.menuOpen) return null;
3727
+ if (this.overlayActive) return this.overlay?.bytes ?? null;
3728
+ if (this.st.exec.running) {
3729
+ if (this.duringRun === "latent") return this.latentBytes ?? this.outputBytes;
3730
+ return this.outputBytes;
3731
+ }
3732
+ return this.outputBytes;
3733
+ }
3734
+ /** small latent painted over the panel's top-right corner (native + 'latent small' only) */
3735
+ get protocolImageCorner() {
3736
+ if (!this.useNative || !this.show || this.menuOpen) return null;
3737
+ if (this.overlayActive) return null;
3738
+ if (this.st.exec.running && this.duringRun === "latent-small") return this.latentBytes;
3739
+ return null;
3740
+ }
3741
+ /** corner cell box matched to the latent's REAL aspect (a mismatched box
3742
+ * letterboxes in iTerm, showing a tall rectangle). Cells are
3743
+ * ~1:2 (w:h), hence the ×2 when converting image aspect to cells. */
3744
+ get cornerBox() {
3745
+ let w = Math.max(8, Math.floor(this.width * CORNER_FRACTION));
3746
+ const maxH = Math.max(4, Math.floor(this.height * CORNER_FRACTION));
3747
+ const dims = this.latentDims;
3748
+ if (dims == null || dims.width === 0 || dims.height === 0) return {
3749
+ w,
3750
+ h: maxH
3751
+ };
3752
+ const aspect = dims.width / dims.height;
3753
+ let h = Math.max(2, Math.round(w / aspect / 2));
3754
+ if (h > maxH) {
3755
+ h = maxH;
3756
+ w = Math.max(4, Math.round(h * aspect * 2));
3757
+ }
3758
+ return {
3759
+ w,
3760
+ h
3761
+ };
3506
3762
  }
3507
- /** ⌃D: drop the hand keyword, so this lora falls back to lora-manager's trigger words */
3508
- resetKeyword() {
3509
- const name = this.selectedName;
3510
- if (name == null) return;
3511
- clearLoraKeywordOverride(name);
3763
+ get width() {
3764
+ return Math.max(24, Math.min(80, this.st.termCols - 68 - this.st.treeWidth));
3512
3765
  }
3513
- get selectedName() {
3514
- return this.filteredNames[this.ix] ?? null;
3766
+ get height() {
3767
+ return Math.max(10, this.st.termRows - 12);
3515
3768
  }
3516
- /** preview goes through PreviewSt's shared overlay slot (one code path with the image picker) */
3517
- async refreshPreview() {
3518
- if (this.st.mode !== "overlay-loras") {
3519
- if (!this.st.preview.overlayActive) this.st.preview.clearOverlayImage();
3520
- return;
3521
- }
3522
- const name = this.selectedName;
3523
- if (name == null || this._busy) return;
3524
- this._busy = true;
3769
+ async renderOutput(src) {
3770
+ this.lastOutput = src;
3771
+ if (!this.show) return;
3525
3772
  try {
3526
- const host = this.st.runHost;
3527
- let url = getLoraPreviewUrl(name, host.data.id);
3528
- let miss = "no preview available";
3529
- if (url == null) {
3530
- if (this.previewMap === void 0 || this.previewMapHostId !== host.data.id) {
3531
- const sweep = await fetchLoraList(host);
3532
- this.previewMap = sweep.status === "absent" || sweep.status === "unreachable" ? null : loraPreviewMapFrom(sweep.items);
3533
- this.previewSweepStatus = sweep.status;
3534
- this.previewMapHostId = host.data.id;
3535
- }
3536
- url = this.previewMap?.get(loraKey(name)) ?? null;
3537
- if (this.previewSweepStatus === "absent") miss = "lora-manager extension not detected";
3538
- else if (this.previewSweepStatus === "unreachable") miss = "host unreachable";
3539
- else if (this.previewSweepStatus === "partial") miss = "lora-manager answered only part of its list";
3540
- }
3541
- const note = url != null ? null : miss;
3542
- if (url == null) {
3543
- this.st.preview.setOverlayImage({
3544
- bytes: null,
3545
- ansi: null,
3546
- name: `lora ${name}`,
3547
- note
3548
- });
3549
- return;
3550
- }
3551
- const bytes = await fetchLoraPreviewBytes(host, url);
3552
- if (bytes == null) throw new Error("no image preview on the server");
3553
- if (this.st.preview.useNative) {
3554
- this.st.preview.setOverlayImage({
3555
- bytes,
3556
- ansi: null,
3557
- name: `lora ${name}`,
3558
- note: null
3773
+ if (this.useNative) {
3774
+ const shrunk = await sharp(src).resize(896, 896, {
3775
+ fit: "inside",
3776
+ withoutEnlargement: true
3777
+ }).png().toBuffer();
3778
+ runInAction(() => {
3779
+ this.outputBytes = new Uint8Array(shrunk);
3559
3780
  });
3560
3781
  return;
3561
3782
  }
3562
- const ansi = await imageBufferToAnsi(bytes, {
3563
- width: this.st.preview.width,
3564
- height: this.st.preview.height
3783
+ const rendered = await imageBufferToAnsi(src, {
3784
+ width: this.width,
3785
+ height: this.height
3565
3786
  });
3566
- this.st.preview.setOverlayImage({
3567
- bytes: null,
3568
- ansi,
3569
- name: `lora ${name}`,
3570
- note: null
3787
+ runInAction(() => {
3788
+ this.outputAnsi = rendered;
3571
3789
  });
3572
3790
  } catch (e) {
3573
- this.st.preview.setOverlayImage({
3574
- bytes: null,
3575
- ansi: null,
3576
- name: `lora ${name}`,
3577
- note: extractErrorMessage(e)
3791
+ runInAction(() => {
3792
+ this.st.exec.notice = `preview: ${extractErrorMessage(e)}`;
3578
3793
  });
3579
- } finally {
3580
- this._busy = false;
3581
- if (this.st.mode === "overlay-loras" && this.selectedName !== name) this.refreshPreview();
3582
- }
3583
- }
3584
- };
3585
- //#endregion
3586
- //#region src/cli/tui/state/PickerSt.ts
3587
- /**
3588
- * choice + size overlays: a windowed option list with a fuzzy type-to-filter.
3589
- * For sizes the filter doubles as free `WxH` entry.
3590
- */
3591
- var PickerSt = class {
3592
- constructor(st) {
3593
- this.st = st;
3594
- this.filter = "";
3595
- this.ix = 0;
3596
- this.invalid = false;
3597
- this.imageSizeRow = null;
3598
- makeAutoObservable(this, { st: false });
3599
- }
3600
- get choiceVar() {
3601
- const sel = this.st.selected?.[1];
3602
- return sel?.kind === "choice" ? sel : null;
3603
- }
3604
- get sizeVar() {
3605
- const sel = this.st.selected?.[1];
3606
- return sel?.kind === "size" ? sel : null;
3607
- }
3608
- get options() {
3609
- const cv = this.choiceVar;
3610
- if (cv != null) {
3611
- if (this.filter === "") return [...cv.choices];
3612
- return cv.choices.filter((c) => fuzzyMatch(this.filter, c));
3613
3794
  }
3614
- const sv = this.sizeVar;
3615
- if (sv != null) {
3616
- const labels = sv.presets.map((p) => `${p.width}×${p.height} ${p.label}`);
3617
- if (this.imageSizeRow != null) labels.unshift(this.imageSizeRow);
3618
- if (this.filter === "") return labels;
3619
- return labels.filter((l) => fuzzyMatch(this.filter, l));
3620
- }
3621
- return [];
3622
- }
3623
- beginChoice() {
3624
- const cv = this.choiceVar;
3625
- if (cv == null) return;
3626
- this.st.mode = "overlay-choice";
3627
- this.filter = "";
3628
- this.invalid = false;
3629
- this.ix = Math.max(0, cv.choices.indexOf(cv.value));
3630
- }
3631
- beginSize() {
3632
- const sv = this.sizeVar;
3633
- if (sv == null) return;
3634
- this.st.mode = "overlay-size";
3635
- this.filter = "";
3636
- this.invalid = false;
3637
- const img = sv.imageSize();
3638
- this.imageSizeRow = img == null ? null : `${img.width}×${img.height} size of image '${img.name}'`;
3639
- const presetIx = sv.presets.findIndex((p) => p.width === sv.value.width && p.height === sv.value.height);
3640
- this.ix = presetIx === -1 ? 0 : presetIx + (this.imageSizeRow != null ? 1 : 0);
3641
- }
3642
- move(delta) {
3643
- const len = this.options.length;
3644
- if (len === 0) return;
3645
- this.ix = (this.ix + delta + len) % len;
3646
- }
3647
- filterInput(chunk) {
3648
- this.filter += chunk;
3649
- this.ix = 0;
3650
- this.invalid = false;
3651
- }
3652
- filterBackspace() {
3653
- this.filter = this.filter.slice(0, -1);
3654
- this.ix = 0;
3655
- this.invalid = false;
3656
- }
3657
- /** ⌥⌫ / ⌃W: drop the last word of the filter */
3658
- filterDeleteWord() {
3659
- this.filter = this.filter.replace(/\s*\S+\s*$/, "");
3660
- this.ix = 0;
3661
- this.invalid = false;
3662
3795
  }
3663
- commit() {
3664
- const cv = this.choiceVar;
3665
- if (cv != null) {
3666
- const hit = this.options[this.ix];
3667
- if (hit == null) return;
3668
- cv.set(hit);
3669
- this.st.mode = "nav";
3796
+ async renderLatent(bytes) {
3797
+ runInAction(() => {
3798
+ this.latentSeenThisRun = true;
3799
+ });
3800
+ if (!this.show || this.duringRun === "last-output") return;
3801
+ if (this.useNative) {
3802
+ const meta = imageMeta(bytes);
3803
+ const dims = meta.width != null && meta.height != null ? {
3804
+ width: meta.width,
3805
+ height: meta.height
3806
+ } : null;
3807
+ if (imageProtocol() !== "kitty") {
3808
+ this.latentBytes = bytes;
3809
+ this.latentDims = dims;
3810
+ return;
3811
+ }
3812
+ if (this._busy) return;
3813
+ this._busy = true;
3814
+ try {
3815
+ const png = await protocolReadyBytes(bytes);
3816
+ runInAction(() => {
3817
+ this.latentBytes = png;
3818
+ this.latentDims = dims;
3819
+ });
3820
+ } catch (e) {
3821
+ runInAction(() => {
3822
+ this.st.exec.notice = `latent preview: ${extractErrorMessage(e)}`;
3823
+ });
3824
+ } finally {
3825
+ this._busy = false;
3826
+ }
3670
3827
  return;
3671
3828
  }
3672
- const sv = this.sizeVar;
3673
- if (sv == null) return;
3674
- const hit = this.options[this.ix];
3675
- if (hit != null) {
3676
- const m = hit.match(/^(\d+)×(\d+)/);
3677
- if (m != null) sv.set({
3678
- width: Number(m[1]),
3679
- height: Number(m[2])
3829
+ if (this._busy) return;
3830
+ this._busy = true;
3831
+ try {
3832
+ const ansi = this.duringRun === "latent-small" ? await this.renderLatentSmallPixel(bytes) : await imageBufferToAnsi(bytes, {
3833
+ width: this.width,
3834
+ height: this.height
3680
3835
  });
3681
- this.st.mode = "nav";
3682
- return;
3836
+ runInAction(() => {
3837
+ this.latentAnsi = ansi;
3838
+ });
3839
+ } catch (e) {
3840
+ runInAction(() => {
3841
+ this.st.exec.notice = `latent preview: ${extractErrorMessage(e)}`;
3842
+ });
3843
+ } finally {
3844
+ this._busy = false;
3683
3845
  }
3684
- if (sv.parse(this.filter)) this.st.mode = "nav";
3685
- else this.invalid = true;
3846
+ }
3847
+ /** pixel 'latent small': sharp-composite the latent thumb onto the last
3848
+ * output (top-right), then ONE half-block render — a string-level overlay
3849
+ * was tried and dropped: its space padding reads as black bars */
3850
+ async renderLatentSmallPixel(bytes) {
3851
+ const pxW = this.width;
3852
+ const pxH = this.height * 2;
3853
+ const thumb = await sharp(bytes).resize(Math.max(8, Math.floor(pxW * PIXEL_SMALL_FRACTION)), Math.max(8, Math.floor(pxH * PIXEL_SMALL_FRACTION)), { fit: "inside" }).png().toBuffer();
3854
+ const out = this.lastOutput;
3855
+ if (out == null) return imageBufferToAnsi(thumb, {
3856
+ width: this.width,
3857
+ height: this.height
3858
+ });
3859
+ return imageBufferToAnsi(await sharp(await sharp(out).resize(pxW, pxH, { fit: "inside" }).png().toBuffer()).composite([{
3860
+ input: thumb,
3861
+ gravity: "northeast"
3862
+ }]).png().toBuffer(), {
3863
+ width: this.width,
3864
+ height: this.height
3865
+ });
3686
3866
  }
3687
3867
  };
3688
3868
  //#endregion
@@ -4160,8 +4340,8 @@ var TuiSt = class {
4160
4340
  this.varsViewH = 0;
4161
4341
  this.wf = wf;
4162
4342
  makeAutoObservable(this, {
4163
- wf: observable.ref,
4164
- hostOverride: observable.ref,
4343
+ wf: observableRef,
4344
+ hostOverride: observableRef,
4165
4345
  onExit: false,
4166
4346
  editor: false,
4167
4347
  picker: false,
@@ -4411,4 +4591,4 @@ async function runTui(args) {
4411
4591
  //#endregion
4412
4592
  export { runTui };
4413
4593
 
4414
- //# sourceMappingURL=run-tui-BqNO9Ck0.js.map
4594
+ //# sourceMappingURL=run-tui-idFhdO4f.js.map