comfy-ts 1.2.0 → 1.4.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 (72) hide show
  1. package/README.md +66 -0
  2. package/dist/DefinedWorkflow-C_QAxKr3.js +737 -0
  3. package/dist/DefinedWorkflow-C_QAxKr3.js.map +1 -0
  4. package/dist/DraftsSt-DcOTn0QR.js +434 -0
  5. package/dist/DraftsSt-DcOTn0QR.js.map +1 -0
  6. package/dist/cli.js +15 -5
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +476 -202
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +98 -40
  11. package/dist/index.d.ts +117 -59
  12. package/dist/index.js +468 -193
  13. package/dist/index.js.map +1 -1
  14. package/dist/run-serve-CN0DhrsA.js +638 -0
  15. package/dist/run-serve-CN0DhrsA.js.map +1 -0
  16. package/dist/{run-tui-BAdizWsO.js → run-tui-bN2hSD5i.js} +250 -447
  17. package/dist/run-tui-bN2hSD5i.js.map +1 -0
  18. package/dist/state-COlKYipO.js +4743 -0
  19. package/dist/state-COlKYipO.js.map +1 -0
  20. package/dist/web.d.ts +17340 -0
  21. package/dist/{state-BYbxDgfr.js → web.js} +1903 -1592
  22. package/dist/web.js.map +1 -0
  23. package/examples/web/example.ts +71 -0
  24. package/examples/web/index.html +77 -0
  25. package/examples/web/serve.ts +42 -0
  26. package/examples/web/tsconfig.json +15 -0
  27. package/package.json +10 -3
  28. package/src/cli/comfy-ts-cli.ts +15 -5
  29. package/src/cli/serve/ServeApp.ts +378 -0
  30. package/src/cli/serve/applyVarPayload.ts +119 -0
  31. package/src/cli/serve/describeVar.ts +74 -0
  32. package/src/cli/serve/run-serve.ts +169 -0
  33. package/src/cli/tui/components/StatusBar.tsx +1 -0
  34. package/src/cli/tui/components/TreePanel.tsx +17 -3
  35. package/src/cli/tui/components/TuiApp.tsx +7 -2
  36. package/src/cli/tui/components/VarsPanel.tsx +67 -34
  37. package/src/cli/tui/imageClipboard.ts +39 -0
  38. package/src/cli/tui/listWindow.ts +36 -0
  39. package/src/cli/tui/state/ExecSt.ts +48 -0
  40. package/src/cli/tui/state/TreeSt.ts +25 -0
  41. package/src/cli/tui/state/TuiSt.ts +34 -0
  42. package/src/coreExports.ts +118 -0
  43. package/src/host/ComfyHost.ts +23 -23
  44. package/src/host/ResilientWebsocket.ts +93 -47
  45. package/src/host/hostUrl.ts +2 -1
  46. package/src/host/loraManagerApi.ts +6 -7
  47. package/src/index.ts +8 -107
  48. package/src/litegraph/convertFlowToLiteGraphJSON.ts +11 -7
  49. package/src/manager/loaders/step2_custom-node-list-loader.ts +4 -4
  50. package/src/manager/loaders/step3_extension-node-map-loader.ts +3 -3
  51. package/src/manager/loaders/step4_model-list-loader.ts +7 -7
  52. package/src/manager/loaders/step5_alter-list-loader.ts +2 -2
  53. package/src/manager/loaders/step6_github-stats-loader.ts +2 -2
  54. package/src/runner/ComfyExecution.ts +32 -12
  55. package/src/runner/MediaImage.ts +18 -30
  56. package/src/runner/outputPath.ts +75 -0
  57. package/src/sdk-generator/ComfySchema.ts +2 -2
  58. package/src/sdk-generator/inputWidgetKind.ts +50 -11
  59. package/src/sdk-generator/litegraphToApiRequestPayload.ts +14 -7
  60. package/src/state.ts +13 -9
  61. package/src/storage/ComfyStorage.ts +144 -0
  62. package/src/storage/nodeStorage.ts +9 -0
  63. package/src/utils/downloadFile.ts +11 -69
  64. package/src/utils/hashArrayBuffer.ts +3 -4
  65. package/src/utils/lazySharp.ts +25 -0
  66. package/src/utils/sha1.ts +69 -0
  67. package/src/vars/ComfyVars.ts +13 -6
  68. package/src/vars/loraKeywords.ts +6 -6
  69. package/src/web.ts +13 -0
  70. package/dist/run-tui-BAdizWsO.js.map +0 -1
  71. package/dist/state-BYbxDgfr.js.map +0 -1
  72. package/src/utils/writeFile.ts +0 -16
@@ -1,52 +1,22 @@
1
- import { a as PromptVar, f as logError, i as LorasVar, l as extractErrorMessage, n as settingsPathFor, o as getLoraKeyword, r as DefinedWorkflow, s as setLoraKeyword, u as stripAnsi } from "./state-BYbxDgfr.js";
1
+ import { i as stripAnsi, n as settingsPathFor, o as sha1HexOfString } from "./state-COlKYipO.js";
2
+ import { c as PromptVar, g as getComfyStorage, h as extractErrorMessage, m as setLoraKeyword, p as getLoraKeyword, s as LorasVar, y as logError } from "./DefinedWorkflow-C_QAxKr3.js";
3
+ import { a as assignFamilyColors, c as findDefinedWorkflow, i as listDraftsForFile, l as mergeWorkflowSources, o as buildFileRows, s as familyOf, t as DraftsSt, u as scanCflowFiles } from "./DraftsSt-DcOTn0QR.js";
2
4
  import { spawn } from "node:child_process";
3
5
  import { fileURLToPath, pathToFileURL } from "node:url";
4
- import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
6
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
5
7
  import { basename, dirname, join, resolve } from "pathe";
6
- import { createHash } from "node:crypto";
7
8
  import { type } from "arktype";
8
- import sharp from "sharp";
9
9
  import { imageMeta } from "image-meta";
10
- import { homedir } from "node:os";
11
10
  import { makeAutoObservable, observable, reaction, runInAction } from "mobx";
12
- import { Box, Text, render, useApp, useInput, useStdin } from "ink";
11
+ import { Box, Text, measureElement, render, useApp, useInput, useStdin } from "ink";
12
+ import sharp from "sharp";
13
13
  import { observer } from "mobx-react-lite";
14
14
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
15
+ import { homedir } from "node:os";
16
+ import { useEffect, useRef } from "react";
15
17
  //#region src/cli/tui-env.ts
16
18
  const COMFY_TS_TUI_ENV = "COMFY_TS_TUI";
17
19
  //#endregion
18
- //#region src/cli/tui/discoverWorkflows.ts
19
- /**
20
- * recursive scan for the workflow-module naming convention. Entries BELOW a
21
- * node_modules segment are skipped: packaged examples arrive via
22
- * bundledExamplesDir (src/exampleAssets.ts — symlinked layouts like pnpm would
23
- * otherwise list them twice, un-deduped, as the user's own files), and
24
- * third-party packages shipping *.cflow.ts are not this project's workflows. A
25
- * scan root that is ITSELF inside node_modules still works (the filter is
26
- * relative to the root).
27
- */
28
- function scanCflowFiles(dir) {
29
- return readdirSync(dir, { recursive: true }).map((f) => String(f)).filter((f) => !f.split("/").includes("node_modules")).map((f) => join(dir, f)).filter((f) => f.endsWith(".cflow.ts") || f.endsWith(".cflow.tsx")).sort();
30
- }
31
- /**
32
- * PURE merge of the scan with the packaged examples (headless-tested). An
33
- * explicit target keeps its scope only. Bundled files ALWAYS group under the
34
- * bundled section, also when the scan already found them (repo dev: ./examples
35
- * is under cwd) — dedupe relies on the caller passing realpath-normalized
36
- * strings on both sides.
37
- */
38
- function mergeWorkflowSources(p) {
39
- if (p.explicitTarget) return {
40
- files: p.scanned,
41
- bundled: /* @__PURE__ */ new Set()
42
- };
43
- const bundled = new Set(p.bundledFiles);
44
- return {
45
- files: [...p.scanned.filter((f) => !bundled.has(f)), ...p.bundledFiles],
46
- bundled
47
- };
48
- }
49
- //#endregion
50
20
  //#region src/exampleAssets.ts
51
21
  /**
52
22
  * the examples/ folder shipped in the npm tarball, resolved from THIS module's
@@ -79,16 +49,6 @@ function bundledExamplesDir(moduleUrl = import.meta.url) {
79
49
  throw new Error(`[comfy-ts] no package.json found walking up from ${fileURLToPath(moduleUrl)}`);
80
50
  }
81
51
  //#endregion
82
- //#region src/cli/tui/findDefinedWorkflow.ts
83
- /**
84
- * instanceof first; duck-type fallback covers a second copy of the library in
85
- * the module graph (linked dev setups, npm dedupe misses)
86
- */
87
- function findDefinedWorkflow(mod) {
88
- const isDefined = (x) => x instanceof DefinedWorkflow || typeof x === "object" && x != null && "spec" in x && typeof x.run === "function" && typeof x.entries === "function";
89
- return [mod.default, ...Object.values(mod)].find(isDefined) ?? null;
90
- }
91
- //#endregion
92
52
  //#region src/utils/ansiImage.ts
93
53
  /**
94
54
  * render an image as truecolor half-block ANSI: each char cell is 1px wide and
@@ -646,6 +606,7 @@ const KeyBar = observer((p) => {
646
606
  ...s.mode === "nav" ? [["e", "rename draft"]] : [],
647
607
  ...s.preview.show || s.mode === "preview" ? [] : [["p", "preview (off)"]],
648
608
  ["o", "open image"],
609
+ ["i", "copy image"],
649
610
  ...s.mode === "tree" || s.mode === "preview" ? [] : [["c/C", "copy wf/api"]],
650
611
  ["q", "quit"]
651
612
  ] : [["⌃R", "run"], ["esc", "back"]];
@@ -1737,18 +1698,27 @@ const TextOverlay = observer((p) => {
1737
1698
  //#endregion
1738
1699
  //#region src/cli/tui/components/TreePanel.tsx
1739
1700
  /** persistent left panel: directory hierarchy + workflows with their drafts
1740
- * nested; `t` (or ← from vars) focuses it, `/` filters it */
1701
+ * nested; `t` (or ← from vars) focuses it, `/` filters it. The Box is
1702
+ * measured (keybar wraps, chrome height is width-dependent — arithmetic
1703
+ * lies) and the row list windows to the measured budget; overflow hidden
1704
+ * is the backstop for the one pre-measure frame. */
1741
1705
  const TreePanel = observer((p) => {
1742
1706
  const s = p.st;
1743
1707
  const tree = s.tree;
1744
1708
  const focused = s.mode === "tree";
1709
+ const boxRef = useRef(null);
1710
+ useEffect(() => {
1711
+ if (boxRef.current != null) tree.setViewH(measureElement(boxRef.current).height);
1712
+ });
1745
1713
  return /* @__PURE__ */ jsxs(Box, {
1714
+ ref: boxRef,
1746
1715
  borderStyle: "round",
1747
1716
  borderColor: focused ? "cyan" : "gray",
1748
1717
  flexDirection: "column",
1749
1718
  flexShrink: 0,
1750
1719
  width: s.treeWidth,
1751
1720
  paddingX: 1,
1721
+ overflow: "hidden",
1752
1722
  children: [
1753
1723
  /* @__PURE__ */ jsx(Box, {
1754
1724
  marginTop: -1,
@@ -1767,7 +1737,12 @@ const TreePanel = observer((p) => {
1767
1737
  tree.filtering ? "▌" : ""
1768
1738
  ]
1769
1739
  }),
1770
- tree.rows.map((row, ix) => {
1740
+ tree.window.moreAbove && /* @__PURE__ */ jsx(Text, {
1741
+ color: "gray",
1742
+ children: "…"
1743
+ }),
1744
+ tree.rows.slice(tree.window.start, tree.window.end).map((row, sliceIx) => {
1745
+ const ix = tree.window.start + sliceIx;
1771
1746
  const sel = focused && ix === tree.ix;
1772
1747
  const indent = " ".repeat(row.depth * 2);
1773
1748
  if (row.kind === "dir") return /* @__PURE__ */ jsxs(Text, {
@@ -1812,6 +1787,10 @@ const TreePanel = observer((p) => {
1812
1787
  ]
1813
1788
  }, `${row.file}·${row.draft}`);
1814
1789
  }),
1790
+ tree.window.moreBelow && /* @__PURE__ */ jsx(Text, {
1791
+ color: "gray",
1792
+ children: "…"
1793
+ }),
1815
1794
  s.workflows.loading ? /* @__PURE__ */ jsx(Text, {
1816
1795
  color: "yellow",
1817
1796
  children: "loading…"
@@ -1849,6 +1828,7 @@ const VarRow = observer((p) => {
1849
1828
  const label = p.varDef.label ?? p.name;
1850
1829
  const raw = p.varDef.display();
1851
1830
  const value = raw.length > VALUE_CAP ? `${raw.slice(0, VALUE_CAP)}…` : raw;
1831
+ const oneLine = p.compact && !p.selected;
1852
1832
  return /* @__PURE__ */ jsxs(Box, {
1853
1833
  flexDirection: "row",
1854
1834
  children: [
@@ -1874,7 +1854,11 @@ const VarRow = observer((p) => {
1874
1854
  }),
1875
1855
  /* @__PURE__ */ jsx(Box, {
1876
1856
  flexGrow: 1,
1877
- children: editing ? /* @__PURE__ */ jsx(EditField, { st: p.st }) : p.varDef instanceof PromptVar ? /* @__PURE__ */ jsx(PromptCell, {
1857
+ children: editing ? /* @__PURE__ */ jsx(EditField, { st: p.st }) : oneLine ? /* @__PURE__ */ jsx(Text, {
1858
+ color: "cyan",
1859
+ wrap: "truncate",
1860
+ children: value.replaceAll("\n", " ")
1861
+ }) : p.varDef instanceof PromptVar ? /* @__PURE__ */ jsx(PromptCell, {
1878
1862
  varDef: p.varDef,
1879
1863
  value
1880
1864
  }) : /* @__PURE__ */ jsx(Text, {
@@ -1890,25 +1874,44 @@ const VarsPanel = observer((p) => {
1890
1874
  const s = p.st;
1891
1875
  const labelW = Math.max(6, ...s.entries.map(([name, v]) => (v.label ?? name).length)) + 3;
1892
1876
  const focused = s.mode === "nav" || s.mode === "edit";
1877
+ const boxRef = useRef(null);
1878
+ useEffect(() => {
1879
+ if (boxRef.current != null) s.setVarsViewH(measureElement(boxRef.current).height);
1880
+ });
1881
+ const w = s.varsWindow;
1893
1882
  return /* @__PURE__ */ jsxs(Box, {
1883
+ ref: boxRef,
1894
1884
  borderStyle: "round",
1895
1885
  borderColor: focused ? "cyan" : "gray",
1896
1886
  paddingX: 1,
1897
1887
  flexDirection: "column",
1898
- children: [/* @__PURE__ */ jsx(Box, {
1899
- marginTop: -1,
1900
- children: /* @__PURE__ */ jsx(Text, {
1901
- color: focused ? "cyan" : "gray",
1902
- bold: focused,
1903
- children: "(v)ars"
1888
+ overflow: "hidden",
1889
+ children: [
1890
+ /* @__PURE__ */ jsx(Box, {
1891
+ marginTop: -1,
1892
+ children: /* @__PURE__ */ jsx(Text, {
1893
+ color: focused ? "cyan" : "gray",
1894
+ bold: focused,
1895
+ children: "(v)ars"
1896
+ })
1897
+ }),
1898
+ w.moreAbove && /* @__PURE__ */ jsx(Text, {
1899
+ color: "gray",
1900
+ children: "…"
1901
+ }),
1902
+ s.entries.slice(w.start, w.end).map(([name, varDef], sliceIx) => /* @__PURE__ */ jsx(VarRow, {
1903
+ name,
1904
+ varDef,
1905
+ selected: w.start + sliceIx === s.selIx,
1906
+ labelW,
1907
+ st: s,
1908
+ compact: s.varsCompact
1909
+ }, name)),
1910
+ w.moreBelow && /* @__PURE__ */ jsx(Text, {
1911
+ color: "gray",
1912
+ children: "…"
1904
1913
  })
1905
- }), s.entries.map(([name, varDef], ix) => /* @__PURE__ */ jsx(VarRow, {
1906
- name,
1907
- varDef,
1908
- selected: ix === s.selIx,
1909
- labelW,
1910
- st: s
1911
- }, name))]
1914
+ ]
1912
1915
  });
1913
1916
  });
1914
1917
  //#endregion
@@ -2053,6 +2056,7 @@ const TuiApp = observer((p) => {
2053
2056
  if (input === "a") return s.host.begin();
2054
2057
  if (input === "p") return s.preview.beginMenu();
2055
2058
  if (input === "o") return s.exec.openLastOutput();
2059
+ if (input === "i") return void s.exec.copyLastImage();
2056
2060
  if (input === "q") {
2057
2061
  s.onExit();
2058
2062
  return app.exit();
@@ -2097,6 +2101,7 @@ const TuiApp = observer((p) => {
2097
2101
  if (input === "h") return s.host.beginPicker();
2098
2102
  if (input === "a") return s.host.begin();
2099
2103
  if (input === "o") return s.exec.openLastOutput();
2104
+ if (input === "i") return void s.exec.copyLastImage();
2100
2105
  if (input === "q") {
2101
2106
  s.onExit();
2102
2107
  return app.exit();
@@ -2140,17 +2145,20 @@ const TuiApp = observer((p) => {
2140
2145
  if (input === "d") return s.drafts.begin();
2141
2146
  if (input === "p") return s.preview.beginMenu();
2142
2147
  if (input === "o") return s.exec.openLastOutput();
2148
+ if (input === "i") return void s.exec.copyLastImage();
2143
2149
  if (input === "c") return void s.exec.copyWorkflowJson();
2144
2150
  if (input === "C") return void s.exec.copyApiJson();
2145
2151
  }, { isActive: useStdin().isRawModeSupported === true });
2146
2152
  return /* @__PURE__ */ jsxs(Box, {
2147
2153
  flexDirection: "column",
2148
- minHeight: s.termRows - 1,
2154
+ height: s.termRows - 1,
2149
2155
  children: [
2150
2156
  /* @__PURE__ */ jsx(Header, { st: s }),
2151
2157
  /* @__PURE__ */ jsxs(Box, {
2152
2158
  flexDirection: "row",
2153
2159
  flexGrow: 1,
2160
+ flexShrink: 1,
2161
+ overflow: "hidden",
2154
2162
  children: [
2155
2163
  /* @__PURE__ */ jsx(TreePanel, { st: s }),
2156
2164
  /* @__PURE__ */ jsxs(Box, {
@@ -2190,389 +2198,59 @@ const TuiApp = observer((p) => {
2190
2198
  });
2191
2199
  });
2192
2200
  //#endregion
2193
- //#region src/cli/tui/treeRows.ts
2194
- /** module display name — also the drafts folder key (DraftsSt delegates here) */
2195
- function moduleName(file) {
2196
- return basename(file).replace(/\.cflow\.tsx?$/, "");
2197
- }
2198
- /** the color word: everything before the first `-` (`flux1-i2i` → `flux1`) */
2199
- function familyOf(name) {
2200
- const dash = name.indexOf("-");
2201
- return dash === -1 ? name : name.slice(0, dash);
2202
- }
2203
- /** hue-spread so CONSECUTIVE families land on clearly distinct colors */
2204
- const FAMILY_PALETTE = [
2205
- "#61afef",
2206
- "#e5c07b",
2207
- "#c678dd",
2208
- "#98c379",
2209
- "#e06c75",
2210
- "#56b6c2",
2211
- "#d19a66",
2212
- "#a5b4fc",
2213
- "#a5e075",
2214
- "#f28fad"
2215
- ];
2216
- /** family → color, palette cycled in first-appearance order over the FULL
2217
- * (unfiltered) file list — stable while filtering/folding */
2218
- function assignFamilyColors(files) {
2219
- const colors = /* @__PURE__ */ new Map();
2220
- for (const file of files) {
2221
- const family = familyOf(moduleName(file));
2222
- if (colors.has(family)) continue;
2223
- colors.set(family, FAMILY_PALETTE[colors.size % FAMILY_PALETTE.length] ?? "#61afef");
2224
- }
2225
- return colors;
2226
- }
2227
- function commonDir(files) {
2228
- const first = files[0];
2229
- if (first == null) return "";
2230
- let prefix = dirname(first).split("/");
2231
- for (const f of files.slice(1)) {
2232
- const segs = dirname(f).split("/");
2233
- let i = 0;
2234
- while (i < prefix.length && i < segs.length && prefix[i] === segs[i]) i++;
2235
- prefix = prefix.slice(0, i);
2236
- }
2237
- return prefix.join("/");
2238
- }
2239
- function insert(root, rootDir, file) {
2240
- const rel = dirname(file).slice(rootDir.length).replace(/^\//, "");
2241
- const segs = rel === "" ? [] : rel.split("/");
2242
- let node = root;
2243
- for (const seg of segs) {
2244
- let child = node.dirs.get(seg);
2245
- if (child == null) {
2246
- child = {
2247
- path: `${node.path}/${seg}`,
2248
- label: seg,
2249
- files: [],
2250
- dirs: /* @__PURE__ */ new Map()
2251
- };
2252
- node.dirs.set(seg, child);
2253
- }
2254
- node = child;
2255
- }
2256
- node.files.push(file);
2257
- }
2258
- /** a dir holding NOTHING but one subdir shows as one `a/b` row */
2259
- function mergeChains(node) {
2260
- const entries = [...node.dirs];
2261
- for (const [key, child] of entries) {
2262
- mergeChains(child);
2263
- if (child.files.length === 0 && child.dirs.size === 1) {
2264
- const only = [...child.dirs.values()][0];
2265
- const label = `${child.label}/${only.label}`;
2266
- node.dirs.delete(key);
2267
- node.dirs.set(label, {
2268
- ...only,
2269
- label
2270
- });
2271
- }
2272
- }
2273
- }
2274
- function matches(file, rootDir, filter) {
2275
- if (filter === "") return true;
2276
- return `${dirname(file).slice(rootDir.length)}/${moduleName(file)}`.toLowerCase().includes(filter.toLowerCase());
2277
- }
2278
- function emit(p) {
2279
- for (const file of p.node.files) {
2280
- if (!matches(file, p.rootDir, p.filter)) continue;
2281
- p.out.push({
2282
- kind: "file",
2283
- file,
2284
- name: moduleName(file),
2285
- depth: p.depth
2286
- });
2287
- }
2288
- for (const dir of [...p.node.dirs.values()].sort((a, b) => a.label.localeCompare(b.label))) {
2289
- const kept = [];
2290
- const expanded = p.filter !== "" || !p.collapsedDirs.has(dir.path);
2291
- emit({
2292
- ...p,
2293
- node: dir,
2294
- depth: p.depth + 1,
2295
- out: kept
2296
- });
2297
- if (p.filter !== "" && kept.length === 0) continue;
2298
- p.out.push({
2299
- kind: "dir",
2300
- path: dir.path,
2301
- label: dir.label,
2302
- depth: p.depth,
2303
- expanded
2304
- });
2305
- if (expanded) p.out.push(...kept);
2306
- }
2307
- }
2201
+ //#region src/cli/tui/listWindow.ts
2308
2202
  /**
2309
- * hierarchy rows over the discovered files: user files under their common
2310
- * root, packaged examples LAST under one foldable 'comfy-ts examples' node.
2203
+ * window a list around the selection so that
2204
+ * (moreAbove ? 1 : 0) + (end - start) + (moreBelow ? 1 : 0) <= budget,
2205
+ * with the selection always inside [start, end). Degenerate budgets (<= 2)
2206
+ * drop the markers and show a bare slice at the selection.
2311
2207
  */
2312
- function buildFileRows(p) {
2313
- const out = [];
2314
- if (p.userFiles.length > 0) {
2315
- const rootDir = commonDir(p.userFiles);
2316
- const root = {
2317
- path: rootDir,
2318
- label: "",
2319
- files: [],
2320
- dirs: /* @__PURE__ */ new Map()
2208
+ const listWindow = (p) => {
2209
+ if (p.count === 0 || p.budget <= 0) {
2210
+ const at = Math.max(0, Math.min(p.selected, p.count));
2211
+ return {
2212
+ start: at,
2213
+ end: at,
2214
+ moreAbove: false,
2215
+ moreBelow: false
2321
2216
  };
2322
- for (const f of p.userFiles) insert(root, rootDir, f);
2323
- mergeChains(root);
2324
- emit({
2325
- node: root,
2326
- depth: 0,
2327
- rootDir,
2328
- collapsedDirs: p.collapsedDirs,
2329
- filter: p.filter,
2330
- out
2331
- });
2332
2217
  }
2333
- if (p.bundledFiles.length > 0) {
2334
- const rootDir = commonDir(p.bundledFiles);
2335
- const root = {
2336
- path: rootDir,
2337
- label: "comfy-ts examples",
2338
- files: [],
2339
- dirs: /* @__PURE__ */ new Map()
2218
+ if (p.count <= p.budget) return {
2219
+ start: 0,
2220
+ end: p.count,
2221
+ moreAbove: false,
2222
+ moreBelow: false
2223
+ };
2224
+ const sel = Math.max(0, Math.min(p.selected, p.count - 1));
2225
+ if (p.budget <= 2) {
2226
+ const start = Math.min(sel, p.count - p.budget);
2227
+ return {
2228
+ start,
2229
+ end: start + p.budget,
2230
+ moreAbove: false,
2231
+ moreBelow: false
2340
2232
  };
2341
- for (const f of p.bundledFiles) insert(root, rootDir, f);
2342
- mergeChains(root);
2343
- const kept = [];
2344
- const expanded = p.filter !== "" || !p.collapsedDirs.has(rootDir);
2345
- emit({
2346
- node: root,
2347
- depth: 1,
2348
- rootDir,
2349
- collapsedDirs: p.collapsedDirs,
2350
- filter: p.filter,
2351
- out: kept
2352
- });
2353
- if (p.filter !== "" && kept.length === 0) return out;
2354
- out.push({
2355
- kind: "dir",
2356
- path: rootDir,
2357
- label: root.label,
2358
- depth: 0,
2359
- expanded
2360
- });
2361
- if (expanded) out.push(...kept);
2362
- }
2363
- return out;
2364
- }
2365
- //#endregion
2366
- //#region src/cli/tui/state/DraftsSt.ts
2367
- /** module basename (`01-txt2img`) keys the draft folder — knowable for EVERY tree file without importing it */
2368
- function draftKeyForFile(file) {
2369
- return moduleName(file);
2370
- }
2371
- function draftsDirForFile(file) {
2372
- return comfyts.resolveFromDrafts(draftKeyForFile(file));
2373
- }
2374
- function listDraftsInDir(dir) {
2375
- if (!existsSync(dir)) return [];
2376
- return readdirSync(dir).filter((f) => f.endsWith(".json")).map((f) => f.slice(0, -5)).sort();
2377
- }
2378
- /** draft names stored for a workflow module (fs read — pair with DraftsSt.version for reactivity) */
2379
- function listDraftsForFile(file) {
2380
- return listDraftsInDir(draftsDirForFile(file));
2381
- }
2382
- /**
2383
- * named var-value snapshots at `.comfy-ts/drafts/<module-basename>/<name>.json`
2384
- * (LOCAL state, gitignored). The active draft autosaves debounced; the TUI is
2385
- * ALWAYS in a draft (`default` unless another one is activated).
2386
- */
2387
- var DraftsSt = class {
2388
- constructor(st) {
2389
- this.st = st;
2390
- this.active = null;
2391
- this.list = [];
2392
- this.ix = 0;
2393
- this.version = 0;
2394
- makeAutoObservable(this, { st: false });
2395
- this.st.disposers.push(reaction(() => this.active == null ? null : JSON.stringify(this.snapshot()), (json) => {
2396
- if (json != null && this.active != null) this.write(this.active, json);
2397
- }, { delay: 300 }));
2398
- }
2399
- get dir() {
2400
- const cur = this.st.workflows.currentPath;
2401
- return cur != null ? draftsDirForFile(cur) : comfyts.resolveFromDrafts(this.st.wf.spec.id ?? "workflow");
2402
- }
2403
- snapshot() {
2404
- return Object.fromEntries(this.st.entries.map(([k, varDef]) => [k, varDef.toJSON()]));
2405
- }
2406
- write(name, json) {
2407
- const path = join(this.dir, `${name}.json`);
2408
- mkdirSync(dirname(path), { recursive: true });
2409
- writeFileSync(path, json);
2410
- this.version++;
2411
- }
2412
- /** module key of the currently loaded workflow (settings.lastDraft is keyed by it) */
2413
- get moduleKey() {
2414
- const cur = this.st.workflows.currentPath;
2415
- return cur != null ? draftKeyForFile(cur) : this.st.wf.spec.id ?? "workflow";
2416
- }
2417
- /** switch to a draft: load its stored values when the file exists, else it starts from current values */
2418
- activate(name) {
2419
- this.active = null;
2420
- const path = join(this.dir, `${name}.json`);
2421
- if (existsSync(path)) try {
2422
- const values = JSON.parse(readFileSync(path, "utf8"));
2423
- for (const [k, varDef] of this.st.entries) if (k in values) varDef.loadJSON(values[k]);
2424
- } catch (e) {
2425
- this.st.exec.error = extractErrorMessage(e);
2426
- }
2427
- this.active = name;
2428
- this.st.settings.rememberDraft(this.moduleKey, name);
2429
- }
2430
- /** open the draft this workflow was last in (settings), else 'default' */
2431
- activateRemembered() {
2432
- const remembered = this.st.settings.lastDraft[this.moduleKey];
2433
- if (remembered != null && remembered !== "default" && existsSync(join(this.dir, `${remembered}.json`))) this.activate(remembered);
2434
- else this.activate("default");
2435
- }
2436
- /** every workflow starts in a draft; kept for callers that want 'default' explicitly */
2437
- activateDefault() {
2438
- this.activate("default");
2439
- }
2440
- dirFor(file) {
2441
- return file != null ? draftsDirForFile(file) : this.dir;
2442
- }
2443
- /** true when ops on `file` touch the ACTIVE draft bookkeeping */
2444
- isCurrent(file) {
2445
- return file == null || file === this.st.workflows.currentPath;
2446
- }
2447
- validName(rawName) {
2448
- const name = rawName.trim();
2449
- if (/^[\w][\w .-]*$/.test(name)) return name;
2450
- this.st.exec.notice = `invalid draft name: '${rawName}'`;
2451
- return null;
2452
- }
2453
- /** create a NEW draft from the current var values (current workflow only) */
2454
- createNamed(rawName) {
2455
- const name = this.validName(rawName);
2456
- if (name == null) return false;
2457
- if (existsSync(join(this.dir, `${name}.json`))) {
2458
- this.st.exec.notice = `draft '${name}' already exists`;
2459
- return false;
2460
- }
2461
- this.write(name, JSON.stringify(this.snapshot(), null, 2));
2462
- this.active = name;
2463
- this.st.settings.rememberDraft(this.moduleKey, name);
2464
- this.st.exec.notice = `new draft: ${name} (autosaves)`;
2465
- return true;
2466
- }
2467
- rename(oldName, rawName, file) {
2468
- const newName = this.validName(rawName);
2469
- if (newName == null) return false;
2470
- if (newName === oldName) return true;
2471
- const dir = this.dirFor(file);
2472
- const to = join(dir, `${newName}.json`);
2473
- if (existsSync(to)) {
2474
- this.st.exec.notice = `draft '${newName}' already exists`;
2475
- return false;
2476
- }
2477
- const from = join(dir, `${oldName}.json`);
2478
- if (existsSync(from)) renameSync(from, to);
2479
- else if (this.isCurrent(file)) this.write(newName, JSON.stringify(this.snapshot(), null, 2));
2480
- if (this.isCurrent(file) && this.active === oldName) {
2481
- this.active = newName;
2482
- this.st.settings.rememberDraft(this.moduleKey, newName);
2483
- }
2484
- this.version++;
2485
- this.st.exec.notice = `draft renamed: ${oldName} → ${newName}`;
2486
- return true;
2487
- }
2488
- duplicate(name, rawName, file) {
2489
- const newName = this.validName(rawName);
2490
- if (newName == null) return false;
2491
- const dir = this.dirFor(file);
2492
- const from = join(dir, `${name}.json`);
2493
- const to = join(dir, `${newName}.json`);
2494
- if (!existsSync(from)) {
2495
- this.st.exec.notice = `draft '${name}' has no file yet (edit a var first)`;
2496
- return false;
2497
- }
2498
- if (existsSync(to)) {
2499
- this.st.exec.notice = `draft '${newName}' already exists`;
2500
- return false;
2501
- }
2502
- copyFileSync(from, to);
2503
- this.version++;
2504
- this.st.exec.notice = `draft duplicated: ${name} → ${newName}`;
2505
- return true;
2506
- }
2507
- deleteDraft(name, file) {
2508
- const path = join(this.dirFor(file), `${name}.json`);
2509
- if (existsSync(path)) rmSync(path);
2510
- this.version++;
2511
- if (this.isCurrent(file) && this.active === name) this.activateDefault();
2512
- this.st.exec.notice = `draft deleted: ${name}`;
2513
- }
2514
- promptNew(returnMode = "nav") {
2515
- this.st.editor.beginCustom({
2516
- title: "new draft (from current values)",
2517
- initial: "",
2518
- onCommit: (raw) => {
2519
- const ok = this.createNamed(raw);
2520
- if (ok && returnMode === "overlay-drafts") this.begin();
2521
- return ok;
2522
- },
2523
- returnMode
2524
- });
2525
- }
2526
- promptRename(name, file, returnMode = "nav") {
2527
- this.st.editor.beginCustom({
2528
- title: `rename draft '${name}'`,
2529
- initial: name,
2530
- onCommit: (raw) => {
2531
- const ok = this.rename(name, raw, file);
2532
- if (ok && returnMode === "overlay-drafts") this.begin();
2533
- return ok;
2534
- },
2535
- returnMode
2536
- });
2537
- }
2538
- promptDuplicate(name, file, returnMode = "nav") {
2539
- this.st.editor.beginCustom({
2540
- title: `duplicate draft '${name}'`,
2541
- initial: `${name}-copy`,
2542
- onCommit: (raw) => {
2543
- const ok = this.duplicate(name, raw, file);
2544
- if (ok && returnMode === "overlay-drafts") this.begin();
2545
- return ok;
2546
- },
2547
- returnMode
2548
- });
2549
- }
2550
- /** f2 in nav: rename the ACTIVE draft */
2551
- beginRename() {
2552
- this.promptRename(this.active ?? "default");
2553
- }
2554
- begin() {
2555
- this.list = listDraftsInDir(this.dir);
2556
- this.st.mode = "overlay-drafts";
2557
- const ix = this.active == null ? -1 : this.list.indexOf(this.active);
2558
- this.ix = ix === -1 ? 0 : ix + 1;
2559
- }
2560
- move(delta) {
2561
- const len = this.list.length + 1;
2562
- this.ix = (this.ix + delta + len) % len;
2563
- }
2564
- /** draft name under the overlay cursor (row 0 is 'new') */
2565
- get selectedName() {
2566
- return this.ix === 0 ? null : this.list[this.ix - 1] ?? null;
2567
- }
2568
- commit() {
2569
- if (this.ix === 0) return this.promptNew("overlay-drafts");
2570
- const name = this.selectedName;
2571
- if (name == null) return;
2572
- this.activate(name);
2573
- this.st.exec.notice = `draft: ${name} (autosaves)`;
2574
- this.st.mode = "nav";
2575
2233
  }
2234
+ if (sel < p.budget - 1) return {
2235
+ start: 0,
2236
+ end: p.budget - 1,
2237
+ moreAbove: false,
2238
+ moreBelow: true
2239
+ };
2240
+ if (sel >= p.count - (p.budget - 1)) return {
2241
+ start: p.count - (p.budget - 1),
2242
+ end: p.count,
2243
+ moreAbove: true,
2244
+ moreBelow: false
2245
+ };
2246
+ const visible = p.budget - 2;
2247
+ const start = Math.max(1, Math.min(sel - Math.floor(visible / 2), p.count - visible - 1));
2248
+ return {
2249
+ start,
2250
+ end: start + visible,
2251
+ moreAbove: true,
2252
+ moreBelow: true
2253
+ };
2576
2254
  };
2577
2255
  //#endregion
2578
2256
  //#region src/cli/tui/state/EditorSt.ts
@@ -2829,6 +2507,43 @@ var EditorSt = class EditorSt {
2829
2507
  }
2830
2508
  };
2831
2509
  //#endregion
2510
+ //#region src/cli/tui/imageClipboard.ts
2511
+ const extOf = (path) => {
2512
+ const dot = path.lastIndexOf(".");
2513
+ return dot === -1 ? "" : path.slice(dot + 1).toLowerCase();
2514
+ };
2515
+ const imageClipboardCommand = (platform, path) => {
2516
+ const ext = extOf(path);
2517
+ if (platform === "darwin") {
2518
+ if (ext !== "png" && ext !== "jpg" && ext !== "jpeg") return null;
2519
+ const cls = ext === "png" ? "«class PNGf»" : "JPEG picture";
2520
+ return {
2521
+ cmd: "osascript",
2522
+ args: ["-e", `set the clipboard to (read (POSIX file ${JSON.stringify(path)}) as ${cls})`]
2523
+ };
2524
+ }
2525
+ if (platform === "win32") return {
2526
+ cmd: "powershell",
2527
+ args: [
2528
+ "-NoProfile",
2529
+ "-Sta",
2530
+ "-Command",
2531
+ `Add-Type -AssemblyName System.Windows.Forms,System.Drawing; $img=[System.Drawing.Image]::FromFile(${`'${path.replaceAll("'", "''")}'`}); [System.Windows.Forms.Clipboard]::SetImage($img); $img.Dispose()`
2532
+ ]
2533
+ };
2534
+ return {
2535
+ cmd: "xclip",
2536
+ args: [
2537
+ "-selection",
2538
+ "clipboard",
2539
+ "-t",
2540
+ ext === "jpg" || ext === "jpeg" ? "image/jpeg" : ext === "webp" ? "image/webp" : "image/png",
2541
+ "-i",
2542
+ path
2543
+ ]
2544
+ };
2545
+ };
2546
+ //#endregion
2832
2547
  //#region src/cli/tui/state/ExecSt.ts
2833
2548
  /** popup body: summary + the head of the copied json (proof of WHAT is in the clipboard) */
2834
2549
  function jsonHead(text, maxLines) {
@@ -2961,6 +2676,44 @@ var ExecSt = class {
2961
2676
  };
2962
2677
  this.st.mode = "overlay-copy";
2963
2678
  }
2679
+ /** 'i': the LAST generated image's pixels → clipboard (paste anywhere) */
2680
+ async copyLastImage() {
2681
+ const last = this.outputs[this.outputs.length - 1];
2682
+ if (last == null) {
2683
+ this.showCopyPopup("image → clipboard", false, ["no output image yet — r runs the workflow first"]);
2684
+ return;
2685
+ }
2686
+ let file = last;
2687
+ let command = imageClipboardCommand(process.platform, file);
2688
+ if (command == null && process.platform === "darwin") try {
2689
+ const { default: sharp } = await import("sharp");
2690
+ const { tmpdir } = await import("node:os");
2691
+ const { join } = await import("pathe");
2692
+ file = join(tmpdir(), `comfy-ts-clip-${Date.now()}.png`);
2693
+ await sharp(last).png().toFile(file);
2694
+ command = imageClipboardCommand(process.platform, file);
2695
+ } catch (e) {
2696
+ this.showCopyPopup("image → clipboard", false, [`COPY FAILED for ${basename(last)}`, `png transcode failed: ${extractErrorMessage(e)}`]);
2697
+ return;
2698
+ }
2699
+ if (command == null) {
2700
+ this.showCopyPopup("image → clipboard", false, [`no clipboard image tool for ${process.platform}`]);
2701
+ return;
2702
+ }
2703
+ const cmd = command;
2704
+ const ok = await new Promise((resolve) => {
2705
+ const proc = spawn(cmd.cmd, cmd.args, { stdio: "ignore" });
2706
+ proc.on("error", () => resolve(false));
2707
+ proc.on("close", (code) => resolve(code === 0));
2708
+ });
2709
+ runInAction(() => {
2710
+ this.showCopyPopup("image → clipboard", ok, ok ? [
2711
+ `${basename(last)} — paste the pixels anywhere`,
2712
+ "",
2713
+ last
2714
+ ] : [`COPY FAILED for ${basename(last)}`, `could not run ${cmd.cmd} — is it installed and allowed ?`]);
2715
+ });
2716
+ }
2964
2717
  toClipboard(text) {
2965
2718
  const [cmd, ...args] = process.platform === "darwin" ? ["pbcopy"] : process.platform === "win32" ? ["clip"] : [
2966
2719
  "xclip",
@@ -3571,8 +3324,9 @@ function looksLikeImage(bytes) {
3571
3324
  * a non-image content-type OR non-image magic bytes => no preview, not a crash.
3572
3325
  */
3573
3326
  async function fetchLoraPreviewBytes(host, previewUrl) {
3574
- const cachePath = comfyts.resolveFromCache(`lora-previews/${createHash("sha1").update(previewUrl).digest("hex")}`);
3575
- if (existsSync(cachePath)) return new Uint8Array(readFileSync(cachePath));
3327
+ const storage = getComfyStorage();
3328
+ const cachePath = comfyts.resolveFromCache(`lora-previews/${sha1HexOfString(previewUrl)}`);
3329
+ if (storage.exists(cachePath)) return storage.readBytes(cachePath);
3576
3330
  try {
3577
3331
  const res = await host.fetch(previewUrl, {}, { apiPrefix: false });
3578
3332
  if (!res.ok) return null;
@@ -3580,8 +3334,7 @@ async function fetchLoraPreviewBytes(host, previewUrl) {
3580
3334
  if (ct !== "" && !ct.startsWith("image/")) return null;
3581
3335
  const bytes = new Uint8Array(await res.arrayBuffer());
3582
3336
  if (!looksLikeImage(bytes)) return null;
3583
- mkdirSync(dirname(cachePath), { recursive: true });
3584
- writeFileSync(cachePath, bytes);
3337
+ storage.writeBytes(cachePath, bytes);
3585
3338
  return bytes;
3586
3339
  } catch {
3587
3340
  return null;
@@ -3975,6 +3728,7 @@ var TreeSt = class {
3975
3728
  this.expandedFiles = /* @__PURE__ */ new Set();
3976
3729
  this.filter = "";
3977
3730
  this.filtering = false;
3731
+ this.viewH = 0;
3978
3732
  this.collapsedDirs = new Set(st.settings.collapsedDirs);
3979
3733
  makeAutoObservable(this, { st: false });
3980
3734
  }
@@ -4053,6 +3807,27 @@ var TreeSt = class {
4053
3807
  const ix = draftIx === -1 ? rows.findIndex((r) => r.kind === "workflow" && r.current) : draftIx;
4054
3808
  this.ix = ix === -1 ? 0 : ix;
4055
3809
  }
3810
+ setViewH(h) {
3811
+ this.viewH = h;
3812
+ }
3813
+ /** rows available for tree content: measured panel height minus the panel's
3814
+ * own chrome (2 border rows, the filter line when visible, the loading
3815
+ * line). Pre-measure fallback: termRows minus the header+keybar estimate —
3816
+ * one frame only, the measurement replaces it. */
3817
+ get viewBudget() {
3818
+ const h = this.viewH > 0 ? this.viewH : Math.max(5, this.st.termRows - 5);
3819
+ const filterLine = this.filtering || this.filter !== "" ? 1 : 0;
3820
+ const loadingLine = this.st.workflows.loading ? 1 : 0;
3821
+ return Math.max(1, h - 2 - filterLine - loadingLine);
3822
+ }
3823
+ /** the visible slice, selection always inside, markers within the budget */
3824
+ get window() {
3825
+ return listWindow({
3826
+ count: this.rows.length,
3827
+ selected: this.ix,
3828
+ budget: this.viewBudget
3829
+ });
3830
+ }
4056
3831
  /** esc/t inside the tree, → on a draft row, `v` anywhere: back to the vars list */
4057
3832
  blur() {
4058
3833
  this.filtering = false;
@@ -4279,6 +4054,7 @@ var TuiSt = class {
4279
4054
  this.onExit = () => {};
4280
4055
  this.termCols = process.stdout.columns ?? 80;
4281
4056
  this.termRows = (process.stdout.rows ?? 24) - 1;
4057
+ this.varsViewH = 0;
4282
4058
  this.wf = wf;
4283
4059
  makeAutoObservable(this, {
4284
4060
  wf: observable.ref,
@@ -4351,6 +4127,33 @@ var TuiSt = class {
4351
4127
  if (len === 0) return;
4352
4128
  this.selIx = (this.selIx + delta + len) % len;
4353
4129
  }
4130
+ setVarsViewH(h) {
4131
+ this.varsViewH = h;
4132
+ }
4133
+ /** row budget: measured height minus the 2 border rows; pre-measure fallback estimate */
4134
+ get varsBudget() {
4135
+ const h = this.varsViewH > 0 ? this.varsViewH : Math.max(5, this.termRows - 5);
4136
+ return Math.max(1, h - 2);
4137
+ }
4138
+ get varsWindow() {
4139
+ return listWindow({
4140
+ count: this.entries.length,
4141
+ selected: this.selIx,
4142
+ budget: this.varsBudget
4143
+ });
4144
+ }
4145
+ /**
4146
+ * while the list cannot fit, NON-selected rows collapse to one truncated
4147
+ * line (prompt values wrap tall) — rows above the selection then cost one
4148
+ * line each, so the selection can never be pushed off-screen. Reads only
4149
+ * entry count + measured height, never its own rendering: no oscillation.
4150
+ */
4151
+ get varsCompact() {
4152
+ const w = this.varsWindow;
4153
+ if (w.moreAbove || w.moreBelow) return true;
4154
+ const h = this.varsViewH > 0 ? this.varsViewH : Math.max(5, this.termRows - 5);
4155
+ return this.entries.length + 2 > h;
4156
+ }
4354
4157
  /** enter/space on a var: toggle, open an overlay, or inline-edit */
4355
4158
  activate() {
4356
4159
  const sel = this.selected?.[1];
@@ -4459,4 +4262,4 @@ async function runTui(args) {
4459
4262
  //#endregion
4460
4263
  export { runTui };
4461
4264
 
4462
- //# sourceMappingURL=run-tui-BAdizWsO.js.map
4265
+ //# sourceMappingURL=run-tui-bN2hSD5i.js.map