comfy-ts 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +61 -8
  2. package/dist/{DefinedWorkflow-BYyu5dK9.js → DefinedWorkflow-gpknV-5f.js} +52 -35
  3. package/dist/DefinedWorkflow-gpknV-5f.js.map +1 -0
  4. package/dist/DraftsSt-DmA0jWGl.js +434 -0
  5. package/dist/DraftsSt-DmA0jWGl.js.map +1 -0
  6. package/dist/cli.js +17 -4555
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +184 -32
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +54 -23
  11. package/dist/index.d.ts +36 -5
  12. package/dist/index.js +184 -32
  13. package/dist/index.js.map +1 -1
  14. package/dist/run-serve-Bn6yIJB0.js +638 -0
  15. package/dist/run-serve-Bn6yIJB0.js.map +1 -0
  16. package/dist/{run-tui-DZ22HDHI.js → run-tui-BtjaOXRh.js} +791 -395
  17. package/dist/run-tui-BtjaOXRh.js.map +1 -0
  18. package/dist/state-DKCPy105.js +4690 -0
  19. package/dist/state-DKCPy105.js.map +1 -0
  20. package/examples/README.md +6 -4
  21. package/examples/{01-txt2img.cflow.ts → rvion/01-txt2img.cflow.ts} +1 -1
  22. package/examples/{02-img2img-upload.cflow.ts → rvion/02-img2img-upload.cflow.ts} +1 -1
  23. package/examples/{03-export-workflow-json.cflow.ts → rvion/03-export-workflow-json.cflow.ts} +1 -1
  24. package/examples/{04-krea2-turbo-t2i.cflow.ts → rvion/04-krea2-turbo-t2i.cflow.ts} +2 -2
  25. package/examples/{05-comfy-cloud.cflow.ts → rvion/05-comfy-cloud.cflow.ts} +2 -2
  26. package/examples/rvion/06-qwen-image-edit.cflow.ts +89 -0
  27. package/package.json +6 -2
  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/CopyOverlay.tsx +25 -0
  34. package/src/cli/tui/components/Header.tsx +9 -4
  35. package/src/cli/tui/components/HostPanel.tsx +3 -2
  36. package/src/cli/tui/components/HostsOverlay.tsx +33 -0
  37. package/src/cli/tui/components/StatusBar.tsx +29 -9
  38. package/src/cli/tui/components/TreePanel.tsx +33 -9
  39. package/src/cli/tui/components/TuiApp.tsx +54 -7
  40. package/src/cli/tui/components/VarsPanel.tsx +67 -34
  41. package/src/cli/tui/imageClipboard.ts +39 -0
  42. package/src/cli/tui/imagePicker/fsListing.ts +6 -4
  43. package/src/cli/tui/listWindow.ts +36 -0
  44. package/src/cli/tui/run-tui.tsx +47 -7
  45. package/src/cli/tui/state/DraftsSt.ts +3 -2
  46. package/src/cli/tui/state/ExecSt.ts +156 -12
  47. package/src/cli/tui/state/HostSt.ts +94 -10
  48. package/src/cli/tui/state/PickerSt.ts +8 -2
  49. package/src/cli/tui/state/QueueSt.ts +2 -2
  50. package/src/cli/tui/state/SettingsSt.ts +25 -7
  51. package/src/cli/tui/state/TreeSt.ts +164 -36
  52. package/src/cli/tui/state/TuiSt.ts +81 -6
  53. package/src/cli/tui/state/WorkflowsSt.ts +14 -2
  54. package/src/cli/tui/treeRows.ts +165 -0
  55. package/src/host/ComfyHost.ts +7 -0
  56. package/src/litegraph/convertFlowToLiteGraphJSON.ts +11 -7
  57. package/src/runner/ComfyExecution.ts +21 -4
  58. package/src/runner/ComfyWorkflowLayout.ts +6 -4
  59. package/src/runner/outputPath.ts +75 -0
  60. package/src/sdk-generator/inputWidgetKind.ts +50 -11
  61. package/src/sdk-generator/litegraphToApiRequestPayload.ts +14 -7
  62. package/src/state.ts +7 -1
  63. package/src/vars/ComfyVars.ts +33 -4
  64. package/src/vars/DefinedWorkflow.ts +21 -8
  65. package/dist/DefinedWorkflow-BYyu5dK9.js.map +0 -1
  66. package/dist/run-tui-DZ22HDHI.js.map +0 -1
@@ -1,7 +1,9 @@
1
- import { a as setLoraKeyword, c as stripAnsi, i as getLoraKeyword, n as LorasVar, o as extractErrorMessage, r as PromptVar, t as DefinedWorkflow, u as logError } from "./DefinedWorkflow-BYyu5dK9.js";
1
+ import { i as stripAnsi, n as settingsPathFor } from "./state-DKCPy105.js";
2
+ import { _ as logError, c as PromptVar, h as extractErrorMessage, m as setLoraKeyword, p as getLoraKeyword, s as LorasVar } from "./DefinedWorkflow-gpknV-5f.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-DmA0jWGl.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
8
  import { createHash } from "node:crypto";
7
9
  import { type } from "arktype";
@@ -9,44 +11,13 @@ import sharp from "sharp";
9
11
  import { imageMeta } from "image-meta";
10
12
  import { homedir } from "node:os";
11
13
  import { makeAutoObservable, observable, reaction, runInAction } from "mobx";
12
- import { Box, Text, render, useApp, useInput, useStdin } from "ink";
14
+ import { Box, Text, measureElement, render, useApp, useInput, useStdin } from "ink";
13
15
  import { observer } from "mobx-react-lite";
14
16
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
17
+ import { useEffect, useRef } from "react";
15
18
  //#region src/cli/tui-env.ts
16
19
  const COMFY_TS_TUI_ENV = "COMFY_TS_TUI";
17
20
  //#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
21
  //#region src/exampleAssets.ts
51
22
  /**
52
23
  * the examples/ folder shipped in the npm tarball, resolved from THIS module's
@@ -79,16 +50,6 @@ function bundledExamplesDir(moduleUrl = import.meta.url) {
79
50
  throw new Error(`[comfy-ts] no package.json found walking up from ${fileURLToPath(moduleUrl)}`);
80
51
  }
81
52
  //#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
53
  //#region src/utils/ansiImage.ts
93
54
  /**
94
55
  * render an image as truecolor half-block ANSI: each char cell is 1px wide and
@@ -450,35 +411,6 @@ function installProtocolImagePainter(st) {
450
411
  };
451
412
  }
452
413
  //#endregion
453
- //#region src/cli/tui/components/OverlayList.tsx
454
- /** generic modal list: title + rows windowed around the selected index */
455
- const OverlayList = (p) => {
456
- const winStart = Math.max(0, Math.min(p.selectedIx - Math.floor(p.lines / 2), p.rows.length - p.lines));
457
- const visible = p.rows.slice(winStart, winStart + p.lines);
458
- return /* @__PURE__ */ jsxs(Box, {
459
- borderStyle: "double",
460
- paddingX: 1,
461
- flexDirection: "column",
462
- children: [
463
- /* @__PURE__ */ jsx(Text, {
464
- bold: true,
465
- children: p.title
466
- }),
467
- p.extraHeader,
468
- winStart > 0 && /* @__PURE__ */ jsx(Text, {
469
- color: "gray",
470
- children: "…"
471
- }),
472
- visible.map((r) => r.node),
473
- winStart + p.lines < p.rows.length && /* @__PURE__ */ jsx(Text, {
474
- color: "gray",
475
- children: "…"
476
- }),
477
- p.footer
478
- ]
479
- });
480
- };
481
- //#endregion
482
414
  //#region src/cli/tui/components/StatusBar.tsx
483
415
  /** keys cyan, labels gray — shared by the keybar and overlay footers */
484
416
  const KeyHints = (p) => /* @__PURE__ */ jsx(Text, {
@@ -627,18 +559,26 @@ const MODE_KEYS = {
627
559
  ["↑↓", "move"],
628
560
  ["esc", "cancel"]
629
561
  ],
562
+ "overlay-hosts": [
563
+ ["⏎", "pick run host"],
564
+ ["↑↓", "move"],
565
+ ["esc", "cancel"]
566
+ ],
567
+ "overlay-copy": [["⏎/esc", "close"]],
630
568
  tree: [
631
569
  ["⏎", "load"],
632
570
  ["↑↓", "move"],
633
571
  ["←", "fold"],
634
572
  ["→", "unfold / vars"],
573
+ ["/", "filter"],
635
574
  ...DRAFT_OP_HINTS,
636
575
  ["t/esc", "back"]
637
576
  ],
638
577
  host: [
639
578
  ["⏎", "run action"],
640
579
  ["↑↓", "move"],
641
- ["h/esc", "back"]
580
+ ["h", "change host"],
581
+ ["a/esc", "back"]
642
582
  ],
643
583
  preview: [
644
584
  ["←→", "change"],
@@ -650,17 +590,24 @@ const MODE_KEYS = {
650
590
  const KeyBar = observer((p) => {
651
591
  const s = p.st;
652
592
  const kind = s.selected?.[1].kind;
653
- const modeHints = MODE_KEYS[s.mode] ?? [
593
+ const treeFiltering = s.mode === "tree" && s.tree.filtering;
594
+ const modeHints = treeFiltering ? [
595
+ ["type", "filter"],
596
+ ["⏎", "load"],
597
+ ["↑↓", "move"],
598
+ ["esc", "clear"]
599
+ ] : MODE_KEYS[s.mode] ?? [
654
600
  ["↑↓", "select"],
655
601
  ["←", "tree"],
656
602
  ...kind ? KIND_KEYS[kind] ?? [] : []
657
603
  ];
658
- const globalHints = s.mode === "nav" || s.mode === "tree" || s.mode === "host" || s.mode === "preview" ? [
604
+ const globalHints = !treeFiltering && (s.mode === "nav" || s.mode === "tree" || s.mode === "host" || s.mode === "preview") ? [
659
605
  ["r", "run"],
660
606
  ["s", "reroll+run"],
661
607
  ...s.mode === "nav" ? [["e", "rename draft"]] : [],
662
608
  ...s.preview.show || s.mode === "preview" ? [] : [["p", "preview (off)"]],
663
609
  ["o", "open image"],
610
+ ["i", "copy image"],
664
611
  ...s.mode === "tree" || s.mode === "preview" ? [] : [["c/C", "copy wf/api"]],
665
612
  ["q", "quit"]
666
613
  ] : [["⌃R", "run"], ["esc", "back"]];
@@ -671,6 +618,62 @@ const KeyBar = observer((p) => {
671
618
  });
672
619
  });
673
620
  //#endregion
621
+ //#region src/cli/tui/components/CopyOverlay.tsx
622
+ /** `c`/`C` confirmation popup: WHAT landed in the clipboard (or the loud
623
+ * failure) — a copy is never silent again. ⏎/esc closes. */
624
+ const CopyOverlay = observer((p) => {
625
+ const popup = p.st.exec.copyPopup;
626
+ if (popup == null) return null;
627
+ return /* @__PURE__ */ jsxs(Box, {
628
+ borderStyle: "double",
629
+ borderColor: popup.ok ? "green" : "red",
630
+ paddingX: 1,
631
+ flexDirection: "column",
632
+ children: [
633
+ /* @__PURE__ */ jsxs(Text, {
634
+ bold: true,
635
+ color: popup.ok ? "green" : "red",
636
+ children: [popup.ok ? "✓ " : "✗ ", popup.title]
637
+ }),
638
+ popup.lines.slice(0, p.st.overlayLines).map((line, ix) => /* @__PURE__ */ jsx(Text, {
639
+ color: popup.ok ? void 0 : "red",
640
+ wrap: "truncate",
641
+ children: line
642
+ }, `${ix}·${line.slice(0, 12)}`)),
643
+ /* @__PURE__ */ jsx(KeyHints, { hints: [["⏎/esc", "close"]] })
644
+ ]
645
+ });
646
+ });
647
+ //#endregion
648
+ //#region src/cli/tui/components/OverlayList.tsx
649
+ /** generic modal list: title + rows windowed around the selected index */
650
+ const OverlayList = (p) => {
651
+ const winStart = Math.max(0, Math.min(p.selectedIx - Math.floor(p.lines / 2), p.rows.length - p.lines));
652
+ const visible = p.rows.slice(winStart, winStart + p.lines);
653
+ return /* @__PURE__ */ jsxs(Box, {
654
+ borderStyle: "double",
655
+ paddingX: 1,
656
+ flexDirection: "column",
657
+ children: [
658
+ /* @__PURE__ */ jsx(Text, {
659
+ bold: true,
660
+ children: p.title
661
+ }),
662
+ p.extraHeader,
663
+ winStart > 0 && /* @__PURE__ */ jsx(Text, {
664
+ color: "gray",
665
+ children: "…"
666
+ }),
667
+ visible.map((r) => r.node),
668
+ winStart + p.lines < p.rows.length && /* @__PURE__ */ jsx(Text, {
669
+ color: "gray",
670
+ children: "…"
671
+ }),
672
+ p.footer
673
+ ]
674
+ });
675
+ };
676
+ //#endregion
674
677
  //#region src/cli/tui/components/DraftsOverlay.tsx
675
678
  /** modal draft picker: row 0 creates a new draft, the rest load existing ones */
676
679
  const DraftsOverlay = observer((p) => {
@@ -720,9 +723,10 @@ const HeaderBox = (p) => /* @__PURE__ */ jsxs(Box, {
720
723
  })
721
724
  }), /* @__PURE__ */ jsx(Box, { children: p.children })]
722
725
  });
723
- /** labeled header boxes: brand · (w)orkflow · (d)raft · (h)ost — the keys open each surface */
726
+ /** labeled header boxes: brand · (w)orkflow · (d)raft · (h)ost·(a)ctions — the keys open each surface */
724
727
  const Header = observer((p) => {
725
728
  const s = p.st;
729
+ const runHost = s.runHost;
726
730
  return /* @__PURE__ */ jsxs(Box, {
727
731
  flexDirection: "row",
728
732
  children: [
@@ -748,7 +752,7 @@ const Header = observer((p) => {
748
752
  })
749
753
  }),
750
754
  /* @__PURE__ */ jsx(HeaderBox, {
751
- title: "(h)ost",
755
+ title: "(h)ost · (a)ctions",
752
756
  children: /* @__PURE__ */ jsxs(Text, { children: [
753
757
  /* @__PURE__ */ jsx(Text, {
754
758
  color: s.host.status === "up" ? "green" : s.host.status === "down" ? "red" : "gray",
@@ -757,19 +761,23 @@ const Header = observer((p) => {
757
761
  /* @__PURE__ */ jsx(Text, {
758
762
  bold: true,
759
763
  color: "green",
760
- children: s.wf.host.data.id
764
+ children: runHost.data.id
761
765
  }),
762
766
  /* @__PURE__ */ jsxs(Text, {
763
767
  color: "gray",
764
768
  children: [
765
769
  " ",
766
770
  "(",
767
- s.wf.host.data.host,
771
+ runHost.base.host,
768
772
  ":",
769
- s.wf.host.data.port,
773
+ runHost.base.port,
770
774
  ")"
771
775
  ]
772
776
  }),
777
+ s.hostOverride != null && s.hostOverride !== s.wf.host && /* @__PURE__ */ jsxs(Text, {
778
+ color: "yellow",
779
+ children: [" ⇄ overrides ", s.wf.host.data.id]
780
+ }),
773
781
  s.host.status === "down" && /* @__PURE__ */ jsxs(Text, {
774
782
  color: "red",
775
783
  children: [" ", s.host.probing ? s.host.spinner : `↻ ${s.host.retryInS}s`]
@@ -783,7 +791,8 @@ const Header = observer((p) => {
783
791
  //#region src/cli/tui/components/HostPanel.tsx
784
792
  /** host stats + maintenance actions (mode 'host', key `h`) */
785
793
  const HostPanel = observer((p) => {
786
- const h = p.st.host;
794
+ const s = p.st;
795
+ const h = s.host;
787
796
  return /* @__PURE__ */ jsxs(Box, {
788
797
  borderStyle: "double",
789
798
  paddingX: 1,
@@ -792,7 +801,7 @@ const HostPanel = observer((p) => {
792
801
  /* @__PURE__ */ jsxs(Text, {
793
802
  bold: true,
794
803
  children: [
795
- "host · ",
804
+ "host actions · ",
796
805
  /* @__PURE__ */ jsx(Text, {
797
806
  color: "green",
798
807
  children: h.host.data.id
@@ -802,11 +811,15 @@ const HostPanel = observer((p) => {
802
811
  color: "gray",
803
812
  children: [
804
813
  "(",
805
- h.host.data.host,
814
+ h.host.base.host,
806
815
  ":",
807
- h.host.data.port,
816
+ h.host.base.port,
808
817
  ")"
809
818
  ]
819
+ }),
820
+ s.hostOverride != null && /* @__PURE__ */ jsx(Text, {
821
+ color: "yellow",
822
+ children: " ⇄ override"
810
823
  })
811
824
  ]
812
825
  }),
@@ -832,6 +845,34 @@ const HostPanel = observer((p) => {
832
845
  });
833
846
  });
834
847
  //#endregion
848
+ //#region src/cli/tui/components/HostsOverlay.tsx
849
+ /** modal host picker (`h`): row 0 restores the workflow's own host, the rest
850
+ * override where runs are built and sent (every registered host is listed) */
851
+ const HostsOverlay = observer((p) => {
852
+ const s = p.st;
853
+ const h = s.host;
854
+ const rows = h.pickerRows.map((row, ix) => ({
855
+ key: row.host?.data.id ?? "·default·",
856
+ node: /* @__PURE__ */ jsxs(Text, {
857
+ inverse: ix === h.pickerIx,
858
+ children: [
859
+ ix === h.pickerIx ? "▸ " : " ",
860
+ row.active ? "● " : " ",
861
+ row.label
862
+ ]
863
+ }, row.host?.data.id ?? "·default·")
864
+ }));
865
+ return /* @__PURE__ */ jsx(OverlayList, {
866
+ title: /* @__PURE__ */ jsxs(Fragment, { children: ["run host ", /* @__PURE__ */ jsx(Text, {
867
+ color: "gray",
868
+ children: "· overrides the workflow's configured host"
869
+ })] }),
870
+ selectedIx: h.pickerIx,
871
+ lines: s.overlayLines,
872
+ rows
873
+ });
874
+ });
875
+ //#endregion
835
876
  //#region src/cli/tui/components/LorasOverlay.tsx
836
877
  /** modal multi-select: tick/untick loras, filter, bulk ops, step strengths */
837
878
  const LorasOverlay = observer((p) => {
@@ -1115,15 +1156,15 @@ function hasImageExtension(name, extensions) {
1115
1156
  }
1116
1157
  /**
1117
1158
  * ONE folder for the picker: dirs first then images, both alphabetical,
1118
- * dotfiles skipped, images filtered by extension. Symlinks are followed
1119
- * (a dangling one is skipped). Pure over fs — an unreadable dir THROWS,
1120
- * the caller surfaces it (never a silent empty listing).
1159
+ * images filtered by extension. Dot FILES are junk (.DS_Store) and skipped;
1160
+ * dot DIRS are listed — .comfy-ts/outputs must be browsable. Symlinks are
1161
+ * followed (a dangling one is skipped). Pure over fs — an unreadable dir
1162
+ * THROWS, the caller surfaces it (never a silent empty listing).
1121
1163
  */
1122
1164
  function listImageDir(dir, extensions) {
1123
1165
  const dirs = [];
1124
1166
  const images = [];
1125
1167
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
1126
- if (entry.name.startsWith(".")) continue;
1127
1168
  let isDir = entry.isDirectory();
1128
1169
  let isFile = entry.isFile();
1129
1170
  if (entry.isSymbolicLink()) try {
@@ -1133,6 +1174,7 @@ function listImageDir(dir, extensions) {
1133
1174
  } catch {
1134
1175
  continue;
1135
1176
  }
1177
+ if (entry.name.startsWith(".") && !isDir) continue;
1136
1178
  if (isDir) dirs.push(entry.name);
1137
1179
  else if (isFile && hasImageExtension(entry.name, extensions)) images.push(entry.name);
1138
1180
  }
@@ -1656,18 +1698,28 @@ const TextOverlay = observer((p) => {
1656
1698
  });
1657
1699
  //#endregion
1658
1700
  //#region src/cli/tui/components/TreePanel.tsx
1659
- /** persistent left panel: workflows with their drafts nested; `t` (or ← from vars) focuses it */
1701
+ /** persistent left panel: directory hierarchy + workflows with their drafts
1702
+ * nested; `t` (or ← from vars) focuses it, `/` filters it. The Box is
1703
+ * measured (keybar wraps, chrome height is width-dependent — arithmetic
1704
+ * lies) and the row list windows to the measured budget; overflow hidden
1705
+ * is the backstop for the one pre-measure frame. */
1660
1706
  const TreePanel = observer((p) => {
1661
1707
  const s = p.st;
1662
1708
  const tree = s.tree;
1663
1709
  const focused = s.mode === "tree";
1710
+ const boxRef = useRef(null);
1711
+ useEffect(() => {
1712
+ if (boxRef.current != null) tree.setViewH(measureElement(boxRef.current).height);
1713
+ });
1664
1714
  return /* @__PURE__ */ jsxs(Box, {
1715
+ ref: boxRef,
1665
1716
  borderStyle: "round",
1666
1717
  borderColor: focused ? "cyan" : "gray",
1667
1718
  flexDirection: "column",
1668
1719
  flexShrink: 0,
1669
1720
  width: s.treeWidth,
1670
1721
  paddingX: 1,
1722
+ overflow: "hidden",
1671
1723
  children: [
1672
1724
  /* @__PURE__ */ jsx(Box, {
1673
1725
  marginTop: -1,
@@ -1677,22 +1729,45 @@ const TreePanel = observer((p) => {
1677
1729
  children: "(t)ree"
1678
1730
  })
1679
1731
  }),
1680
- tree.rows.map((row, ix) => {
1732
+ (tree.filtering || tree.filter !== "") && /* @__PURE__ */ jsxs(Text, {
1733
+ color: "yellow",
1734
+ wrap: "truncate",
1735
+ children: [
1736
+ "/",
1737
+ tree.filter,
1738
+ tree.filtering ? "▌" : ""
1739
+ ]
1740
+ }),
1741
+ tree.window.moreAbove && /* @__PURE__ */ jsx(Text, {
1742
+ color: "gray",
1743
+ children: "…"
1744
+ }),
1745
+ tree.rows.slice(tree.window.start, tree.window.end).map((row, sliceIx) => {
1746
+ const ix = tree.window.start + sliceIx;
1681
1747
  const sel = focused && ix === tree.ix;
1682
- if (row.kind === "section") return /* @__PURE__ */ jsxs(Text, {
1748
+ const indent = " ".repeat(row.depth * 2);
1749
+ if (row.kind === "dir") return /* @__PURE__ */ jsxs(Text, {
1750
+ inverse: sel,
1683
1751
  color: "gray",
1684
- dimColor: true,
1752
+ bold: true,
1685
1753
  wrap: "truncate",
1686
- children: ["─ ", row.label]
1687
- }, `section·${row.label}`);
1754
+ children: [
1755
+ indent,
1756
+ row.expanded ? "▾" : "▸",
1757
+ " ",
1758
+ row.label
1759
+ ]
1760
+ }, `dir·${row.path}`);
1688
1761
  if (row.kind === "workflow") {
1689
1762
  const arrow = row.hasDrafts ? row.expanded ? "▾" : "▸" : " ";
1690
1763
  const marker = row.error != null ? "✗" : row.current ? "●" : " ";
1691
1764
  return /* @__PURE__ */ jsxs(Text, {
1692
1765
  inverse: sel,
1693
- color: row.error != null ? "red" : row.current ? "green" : void 0,
1766
+ bold: row.current,
1767
+ color: row.error != null ? "red" : row.color,
1694
1768
  wrap: "truncate",
1695
1769
  children: [
1770
+ indent,
1696
1771
  arrow,
1697
1772
  marker,
1698
1773
  " ",
@@ -1705,13 +1780,18 @@ const TreePanel = observer((p) => {
1705
1780
  color: row.active ? "cyan" : "gray",
1706
1781
  wrap: "truncate",
1707
1782
  children: [
1708
- " ",
1783
+ indent,
1784
+ " ",
1709
1785
  row.active ? "●" : "·",
1710
1786
  " ",
1711
1787
  row.draft
1712
1788
  ]
1713
1789
  }, `${row.file}·${row.draft}`);
1714
1790
  }),
1791
+ tree.window.moreBelow && /* @__PURE__ */ jsx(Text, {
1792
+ color: "gray",
1793
+ children: "…"
1794
+ }),
1715
1795
  s.workflows.loading ? /* @__PURE__ */ jsx(Text, {
1716
1796
  color: "yellow",
1717
1797
  children: "loading…"
@@ -1749,6 +1829,7 @@ const VarRow = observer((p) => {
1749
1829
  const label = p.varDef.label ?? p.name;
1750
1830
  const raw = p.varDef.display();
1751
1831
  const value = raw.length > VALUE_CAP ? `${raw.slice(0, VALUE_CAP)}…` : raw;
1832
+ const oneLine = p.compact && !p.selected;
1752
1833
  return /* @__PURE__ */ jsxs(Box, {
1753
1834
  flexDirection: "row",
1754
1835
  children: [
@@ -1774,7 +1855,11 @@ const VarRow = observer((p) => {
1774
1855
  }),
1775
1856
  /* @__PURE__ */ jsx(Box, {
1776
1857
  flexGrow: 1,
1777
- children: editing ? /* @__PURE__ */ jsx(EditField, { st: p.st }) : p.varDef instanceof PromptVar ? /* @__PURE__ */ jsx(PromptCell, {
1858
+ children: editing ? /* @__PURE__ */ jsx(EditField, { st: p.st }) : oneLine ? /* @__PURE__ */ jsx(Text, {
1859
+ color: "cyan",
1860
+ wrap: "truncate",
1861
+ children: value.replaceAll("\n", " ")
1862
+ }) : p.varDef instanceof PromptVar ? /* @__PURE__ */ jsx(PromptCell, {
1778
1863
  varDef: p.varDef,
1779
1864
  value
1780
1865
  }) : /* @__PURE__ */ jsx(Text, {
@@ -1790,25 +1875,44 @@ const VarsPanel = observer((p) => {
1790
1875
  const s = p.st;
1791
1876
  const labelW = Math.max(6, ...s.entries.map(([name, v]) => (v.label ?? name).length)) + 3;
1792
1877
  const focused = s.mode === "nav" || s.mode === "edit";
1878
+ const boxRef = useRef(null);
1879
+ useEffect(() => {
1880
+ if (boxRef.current != null) s.setVarsViewH(measureElement(boxRef.current).height);
1881
+ });
1882
+ const w = s.varsWindow;
1793
1883
  return /* @__PURE__ */ jsxs(Box, {
1884
+ ref: boxRef,
1794
1885
  borderStyle: "round",
1795
1886
  borderColor: focused ? "cyan" : "gray",
1796
1887
  paddingX: 1,
1797
1888
  flexDirection: "column",
1798
- children: [/* @__PURE__ */ jsx(Box, {
1799
- marginTop: -1,
1800
- children: /* @__PURE__ */ jsx(Text, {
1801
- color: focused ? "cyan" : "gray",
1802
- bold: focused,
1803
- children: "(v)ars"
1889
+ overflow: "hidden",
1890
+ children: [
1891
+ /* @__PURE__ */ jsx(Box, {
1892
+ marginTop: -1,
1893
+ children: /* @__PURE__ */ jsx(Text, {
1894
+ color: focused ? "cyan" : "gray",
1895
+ bold: focused,
1896
+ children: "(v)ars"
1897
+ })
1898
+ }),
1899
+ w.moreAbove && /* @__PURE__ */ jsx(Text, {
1900
+ color: "gray",
1901
+ children: "…"
1902
+ }),
1903
+ s.entries.slice(w.start, w.end).map(([name, varDef], sliceIx) => /* @__PURE__ */ jsx(VarRow, {
1904
+ name,
1905
+ varDef,
1906
+ selected: w.start + sliceIx === s.selIx,
1907
+ labelW,
1908
+ st: s,
1909
+ compact: s.varsCompact
1910
+ }, name)),
1911
+ w.moreBelow && /* @__PURE__ */ jsx(Text, {
1912
+ color: "gray",
1913
+ children: "…"
1804
1914
  })
1805
- }), s.entries.map(([name, varDef], ix) => /* @__PURE__ */ jsx(VarRow, {
1806
- name,
1807
- varDef,
1808
- selected: ix === s.selIx,
1809
- labelW,
1810
- st: s
1811
- }, name))]
1915
+ ]
1812
1916
  });
1813
1917
  });
1814
1918
  //#endregion
@@ -1922,7 +2026,20 @@ const TuiApp = observer((p) => {
1922
2026
  }
1923
2027
  if (s.mode === "tree") {
1924
2028
  const tr = s.tree;
1925
- if (key.escape || input === "t") return tr.blur();
2029
+ if (tr.filtering) {
2030
+ if (key.escape) return tr.clearFilter();
2031
+ if (key.return) return void tr.commit();
2032
+ if (key.upArrow) return tr.move(-1);
2033
+ if (key.downArrow) return tr.move(1);
2034
+ if (key.leftArrow) return tr.fold();
2035
+ if (key.rightArrow) return tr.unfold();
2036
+ if (key.backspace || key.delete) return tr.filterBackspace();
2037
+ if (input && !key.ctrl && !key.meta) return tr.filterInput(input);
2038
+ return;
2039
+ }
2040
+ if (key.escape) return tr.filter !== "" ? tr.clearFilter() : tr.blur();
2041
+ if (input === "t") return tr.blur();
2042
+ if (input === "/") return tr.beginFilter();
1926
2043
  if (key.return || input === " ") return void tr.commit();
1927
2044
  if (key.upArrow) return tr.move(-1);
1928
2045
  if (key.downArrow) return tr.move(1);
@@ -1936,9 +2053,11 @@ const TuiApp = observer((p) => {
1936
2053
  if (input === "r") return void s.exec.run();
1937
2054
  if (input === "s") return s.exec.randomizeSeedAndRun();
1938
2055
  if (input === "d") return s.drafts.begin();
1939
- if (input === "h") return s.host.begin();
2056
+ if (input === "h") return s.host.beginPicker();
2057
+ if (input === "a") return s.host.begin();
1940
2058
  if (input === "p") return s.preview.beginMenu();
1941
2059
  if (input === "o") return s.exec.openLastOutput();
2060
+ if (input === "i") return void s.exec.copyLastImage();
1942
2061
  if (input === "q") {
1943
2062
  s.onExit();
1944
2063
  return app.exit();
@@ -1947,7 +2066,8 @@ const TuiApp = observer((p) => {
1947
2066
  }
1948
2067
  if (s.mode === "host") {
1949
2068
  const h = s.host;
1950
- if (key.escape || input === "h" || input === "v") return h.blur();
2069
+ if (key.escape || input === "a" || input === "v") return h.blur();
2070
+ if (input === "h") return h.beginPicker();
1951
2071
  if (key.return || input === " ") return void h.commit();
1952
2072
  if (key.upArrow) return h.move(-1);
1953
2073
  if (key.downArrow) return h.move(1);
@@ -1957,6 +2077,18 @@ const TuiApp = observer((p) => {
1957
2077
  }
1958
2078
  return;
1959
2079
  }
2080
+ if (s.mode === "overlay-hosts") {
2081
+ const h = s.host;
2082
+ if (key.escape || input === "h") return h.cancelPicker();
2083
+ if (key.return || input === " ") return h.commitPicker();
2084
+ if (key.upArrow) return h.pickerMove(-1);
2085
+ if (key.downArrow) return h.pickerMove(1);
2086
+ return;
2087
+ }
2088
+ if (s.mode === "overlay-copy") {
2089
+ if (key.escape || key.return || input === " " || input === "c" || input === "C" || input === "q") return s.exec.closeCopyPopup();
2090
+ return;
2091
+ }
1960
2092
  if (s.mode === "preview") {
1961
2093
  const pv = s.preview;
1962
2094
  if (key.escape || key.return || input === "p" || input === "v") return pv.blurMenu();
@@ -1967,8 +2099,10 @@ const TuiApp = observer((p) => {
1967
2099
  if (input === "r") return void s.exec.run();
1968
2100
  if (input === "s") return s.exec.randomizeSeedAndRun();
1969
2101
  if (input === "d") return s.drafts.begin();
1970
- if (input === "h") return s.host.begin();
2102
+ if (input === "h") return s.host.beginPicker();
2103
+ if (input === "a") return s.host.begin();
1971
2104
  if (input === "o") return s.exec.openLastOutput();
2105
+ if (input === "i") return void s.exec.copyLastImage();
1972
2106
  if (input === "q") {
1973
2107
  s.onExit();
1974
2108
  return app.exit();
@@ -1999,32 +2133,40 @@ const TuiApp = observer((p) => {
1999
2133
  if (key.leftArrow) return s.tree.focus();
2000
2134
  if (key.rightArrow || key.return || input === " ") return s.activate();
2001
2135
  if (s.navKey(input)) return;
2136
+ if (input === "/") {
2137
+ s.tree.focus();
2138
+ return s.tree.beginFilter();
2139
+ }
2002
2140
  if (input === "e") return s.drafts.beginRename();
2003
2141
  if (input === "r") return void s.exec.run();
2004
2142
  if (input === "s") return s.exec.randomizeSeedAndRun();
2005
2143
  if (input === "t" || input === "w") return s.tree.focus();
2006
- if (input === "h") return s.host.begin();
2144
+ if (input === "h") return s.host.beginPicker();
2145
+ if (input === "a") return s.host.begin();
2007
2146
  if (input === "d") return s.drafts.begin();
2008
2147
  if (input === "p") return s.preview.beginMenu();
2009
2148
  if (input === "o") return s.exec.openLastOutput();
2149
+ if (input === "i") return void s.exec.copyLastImage();
2010
2150
  if (input === "c") return void s.exec.copyWorkflowJson();
2011
2151
  if (input === "C") return void s.exec.copyApiJson();
2012
2152
  }, { isActive: useStdin().isRawModeSupported === true });
2013
2153
  return /* @__PURE__ */ jsxs(Box, {
2014
2154
  flexDirection: "column",
2015
- minHeight: s.termRows - 1,
2155
+ height: s.termRows - 1,
2016
2156
  children: [
2017
2157
  /* @__PURE__ */ jsx(Header, { st: s }),
2018
2158
  /* @__PURE__ */ jsxs(Box, {
2019
2159
  flexDirection: "row",
2020
2160
  flexGrow: 1,
2161
+ flexShrink: 1,
2162
+ overflow: "hidden",
2021
2163
  children: [
2022
2164
  /* @__PURE__ */ jsx(TreePanel, { st: s }),
2023
2165
  /* @__PURE__ */ jsxs(Box, {
2024
2166
  flexDirection: "column",
2025
2167
  flexGrow: 1,
2026
2168
  children: [
2027
- s.mode === "edit" && s.editor.isCustom ? /* @__PURE__ */ jsx(PromptOverlay, { st: s }) : s.mode === "host" ? /* @__PURE__ */ jsx(HostPanel, { st: s }) : s.mode === "overlay-text" ? /* @__PURE__ */ jsx(TextOverlay, { st: s }) : s.mode === "overlay-choice" ? /* @__PURE__ */ jsx(ChoiceOverlay, { st: s }) : s.mode === "overlay-size" ? /* @__PURE__ */ jsx(SizeOverlay, { st: s }) : s.mode === "overlay-loras" ? /* @__PURE__ */ jsx(LorasOverlay, { st: s }) : s.mode === "overlay-image" ? /* @__PURE__ */ jsx(ImagePickerOverlay, { st: s }) : s.mode === "overlay-drafts" ? /* @__PURE__ */ jsx(DraftsOverlay, { st: s }) : /* @__PURE__ */ jsx(VarsPanel, { st: s }),
2169
+ s.mode === "edit" && s.editor.isCustom ? /* @__PURE__ */ jsx(PromptOverlay, { st: s }) : s.mode === "host" ? /* @__PURE__ */ jsx(HostPanel, { st: s }) : s.mode === "overlay-text" ? /* @__PURE__ */ jsx(TextOverlay, { st: s }) : s.mode === "overlay-choice" ? /* @__PURE__ */ jsx(ChoiceOverlay, { st: s }) : s.mode === "overlay-size" ? /* @__PURE__ */ jsx(SizeOverlay, { st: s }) : s.mode === "overlay-loras" ? /* @__PURE__ */ jsx(LorasOverlay, { st: s }) : s.mode === "overlay-image" ? /* @__PURE__ */ jsx(ImagePickerOverlay, { st: s }) : s.mode === "overlay-drafts" ? /* @__PURE__ */ jsx(DraftsOverlay, { st: s }) : s.mode === "overlay-hosts" ? /* @__PURE__ */ jsx(HostsOverlay, { st: s }) : s.mode === "overlay-copy" ? /* @__PURE__ */ jsx(CopyOverlay, { st: s }) : /* @__PURE__ */ jsx(VarsPanel, { st: s }),
2028
2170
  /* @__PURE__ */ jsx(Box, {
2029
2171
  paddingX: 1,
2030
2172
  children: /* @__PURE__ */ jsx(ProgressLine, { st: s })
@@ -2057,216 +2199,59 @@ const TuiApp = observer((p) => {
2057
2199
  });
2058
2200
  });
2059
2201
  //#endregion
2060
- //#region src/cli/tui/state/DraftsSt.ts
2061
- /** module basename (`01-txt2img`) keys the draft folder — knowable for EVERY tree file without importing it */
2062
- function draftKeyForFile(file) {
2063
- return basename(file).replace(/\.cflow\.tsx?$/, "");
2064
- }
2065
- function draftsDirForFile(file) {
2066
- return comfyts.resolveFromDrafts(draftKeyForFile(file));
2067
- }
2068
- function listDraftsInDir(dir) {
2069
- if (!existsSync(dir)) return [];
2070
- return readdirSync(dir).filter((f) => f.endsWith(".json")).map((f) => f.slice(0, -5)).sort();
2071
- }
2072
- /** draft names stored for a workflow module (fs read — pair with DraftsSt.version for reactivity) */
2073
- function listDraftsForFile(file) {
2074
- return listDraftsInDir(draftsDirForFile(file));
2075
- }
2202
+ //#region src/cli/tui/listWindow.ts
2076
2203
  /**
2077
- * named var-value snapshots at `.comfy-ts/drafts/<module-basename>/<name>.json`
2078
- * (LOCAL state, gitignored). The active draft autosaves debounced; the TUI is
2079
- * ALWAYS in a draft (`default` unless another one is activated).
2204
+ * window a list around the selection so that
2205
+ * (moreAbove ? 1 : 0) + (end - start) + (moreBelow ? 1 : 0) <= budget,
2206
+ * with the selection always inside [start, end). Degenerate budgets (<= 2)
2207
+ * drop the markers and show a bare slice at the selection.
2080
2208
  */
2081
- var DraftsSt = class {
2082
- constructor(st) {
2083
- this.st = st;
2084
- this.active = null;
2085
- this.list = [];
2086
- this.ix = 0;
2087
- this.version = 0;
2088
- makeAutoObservable(this, { st: false });
2089
- this.st.disposers.push(reaction(() => this.active == null ? null : JSON.stringify(this.snapshot()), (json) => {
2090
- if (json != null && this.active != null) this.write(this.active, json);
2091
- }, { delay: 300 }));
2092
- }
2093
- get dir() {
2094
- const cur = this.st.workflows.currentPath;
2095
- return cur != null ? draftsDirForFile(cur) : comfyts.resolveFromDrafts(this.st.wf.spec.id ?? "workflow");
2096
- }
2097
- snapshot() {
2098
- return Object.fromEntries(this.st.entries.map(([k, varDef]) => [k, varDef.toJSON()]));
2099
- }
2100
- write(name, json) {
2101
- const path = join(this.dir, `${name}.json`);
2102
- mkdirSync(dirname(path), { recursive: true });
2103
- writeFileSync(path, json);
2104
- this.version++;
2105
- }
2106
- /** module key of the currently loaded workflow (settings.lastDraft is keyed by it) */
2107
- get moduleKey() {
2108
- const cur = this.st.workflows.currentPath;
2109
- return cur != null ? draftKeyForFile(cur) : this.st.wf.spec.id ?? "workflow";
2110
- }
2111
- /** switch to a draft: load its stored values when the file exists, else it starts from current values */
2112
- activate(name) {
2113
- this.active = null;
2114
- const path = join(this.dir, `${name}.json`);
2115
- if (existsSync(path)) try {
2116
- const values = JSON.parse(readFileSync(path, "utf8"));
2117
- for (const [k, varDef] of this.st.entries) if (k in values) varDef.loadJSON(values[k]);
2118
- } catch (e) {
2119
- this.st.exec.error = extractErrorMessage(e);
2120
- }
2121
- this.active = name;
2122
- this.st.settings.rememberDraft(this.moduleKey, name);
2123
- }
2124
- /** open the draft this workflow was last in (settings), else 'default' */
2125
- activateRemembered() {
2126
- const remembered = this.st.settings.lastDraft[this.moduleKey];
2127
- if (remembered != null && remembered !== "default" && existsSync(join(this.dir, `${remembered}.json`))) this.activate(remembered);
2128
- else this.activate("default");
2129
- }
2130
- /** every workflow starts in a draft; kept for callers that want 'default' explicitly */
2131
- activateDefault() {
2132
- this.activate("default");
2133
- }
2134
- dirFor(file) {
2135
- return file != null ? draftsDirForFile(file) : this.dir;
2136
- }
2137
- /** true when ops on `file` touch the ACTIVE draft bookkeeping */
2138
- isCurrent(file) {
2139
- return file == null || file === this.st.workflows.currentPath;
2140
- }
2141
- validName(rawName) {
2142
- const name = rawName.trim();
2143
- if (/^[\w][\w .-]*$/.test(name)) return name;
2144
- this.st.exec.notice = `invalid draft name: '${rawName}'`;
2145
- return null;
2146
- }
2147
- /** create a NEW draft from the current var values (current workflow only) */
2148
- createNamed(rawName) {
2149
- const name = this.validName(rawName);
2150
- if (name == null) return false;
2151
- if (existsSync(join(this.dir, `${name}.json`))) {
2152
- this.st.exec.notice = `draft '${name}' already exists`;
2153
- return false;
2154
- }
2155
- this.write(name, JSON.stringify(this.snapshot(), null, 2));
2156
- this.active = name;
2157
- this.st.settings.rememberDraft(this.moduleKey, name);
2158
- this.st.exec.notice = `new draft: ${name} (autosaves)`;
2159
- return true;
2160
- }
2161
- rename(oldName, rawName, file) {
2162
- const newName = this.validName(rawName);
2163
- if (newName == null) return false;
2164
- if (newName === oldName) return true;
2165
- const dir = this.dirFor(file);
2166
- const to = join(dir, `${newName}.json`);
2167
- if (existsSync(to)) {
2168
- this.st.exec.notice = `draft '${newName}' already exists`;
2169
- return false;
2170
- }
2171
- const from = join(dir, `${oldName}.json`);
2172
- if (existsSync(from)) renameSync(from, to);
2173
- else if (this.isCurrent(file)) this.write(newName, JSON.stringify(this.snapshot(), null, 2));
2174
- if (this.isCurrent(file) && this.active === oldName) {
2175
- this.active = newName;
2176
- this.st.settings.rememberDraft(this.moduleKey, newName);
2177
- }
2178
- this.version++;
2179
- this.st.exec.notice = `draft renamed: ${oldName} → ${newName}`;
2180
- return true;
2181
- }
2182
- duplicate(name, rawName, file) {
2183
- const newName = this.validName(rawName);
2184
- if (newName == null) return false;
2185
- const dir = this.dirFor(file);
2186
- const from = join(dir, `${name}.json`);
2187
- const to = join(dir, `${newName}.json`);
2188
- if (!existsSync(from)) {
2189
- this.st.exec.notice = `draft '${name}' has no file yet (edit a var first)`;
2190
- return false;
2191
- }
2192
- if (existsSync(to)) {
2193
- this.st.exec.notice = `draft '${newName}' already exists`;
2194
- return false;
2195
- }
2196
- copyFileSync(from, to);
2197
- this.version++;
2198
- this.st.exec.notice = `draft duplicated: ${name} → ${newName}`;
2199
- return true;
2200
- }
2201
- deleteDraft(name, file) {
2202
- const path = join(this.dirFor(file), `${name}.json`);
2203
- if (existsSync(path)) rmSync(path);
2204
- this.version++;
2205
- if (this.isCurrent(file) && this.active === name) this.activateDefault();
2206
- this.st.exec.notice = `draft deleted: ${name}`;
2207
- }
2208
- promptNew(returnMode = "nav") {
2209
- this.st.editor.beginCustom({
2210
- title: "new draft (from current values)",
2211
- initial: "",
2212
- onCommit: (raw) => {
2213
- const ok = this.createNamed(raw);
2214
- if (ok && returnMode === "overlay-drafts") this.begin();
2215
- return ok;
2216
- },
2217
- returnMode
2218
- });
2219
- }
2220
- promptRename(name, file, returnMode = "nav") {
2221
- this.st.editor.beginCustom({
2222
- title: `rename draft '${name}'`,
2223
- initial: name,
2224
- onCommit: (raw) => {
2225
- const ok = this.rename(name, raw, file);
2226
- if (ok && returnMode === "overlay-drafts") this.begin();
2227
- return ok;
2228
- },
2229
- returnMode
2230
- });
2231
- }
2232
- promptDuplicate(name, file, returnMode = "nav") {
2233
- this.st.editor.beginCustom({
2234
- title: `duplicate draft '${name}'`,
2235
- initial: `${name}-copy`,
2236
- onCommit: (raw) => {
2237
- const ok = this.duplicate(name, raw, file);
2238
- if (ok && returnMode === "overlay-drafts") this.begin();
2239
- return ok;
2240
- },
2241
- returnMode
2242
- });
2243
- }
2244
- /** f2 in nav: rename the ACTIVE draft */
2245
- beginRename() {
2246
- this.promptRename(this.active ?? "default");
2247
- }
2248
- begin() {
2249
- this.list = listDraftsInDir(this.dir);
2250
- this.st.mode = "overlay-drafts";
2251
- const ix = this.active == null ? -1 : this.list.indexOf(this.active);
2252
- this.ix = ix === -1 ? 0 : ix + 1;
2253
- }
2254
- move(delta) {
2255
- const len = this.list.length + 1;
2256
- this.ix = (this.ix + delta + len) % len;
2257
- }
2258
- /** draft name under the overlay cursor (row 0 is 'new') */
2259
- get selectedName() {
2260
- return this.ix === 0 ? null : this.list[this.ix - 1] ?? null;
2209
+ const listWindow = (p) => {
2210
+ if (p.count === 0 || p.budget <= 0) {
2211
+ const at = Math.max(0, Math.min(p.selected, p.count));
2212
+ return {
2213
+ start: at,
2214
+ end: at,
2215
+ moreAbove: false,
2216
+ moreBelow: false
2217
+ };
2261
2218
  }
2262
- commit() {
2263
- if (this.ix === 0) return this.promptNew("overlay-drafts");
2264
- const name = this.selectedName;
2265
- if (name == null) return;
2266
- this.activate(name);
2267
- this.st.exec.notice = `draft: ${name} (autosaves)`;
2268
- this.st.mode = "nav";
2219
+ if (p.count <= p.budget) return {
2220
+ start: 0,
2221
+ end: p.count,
2222
+ moreAbove: false,
2223
+ moreBelow: false
2224
+ };
2225
+ const sel = Math.max(0, Math.min(p.selected, p.count - 1));
2226
+ if (p.budget <= 2) {
2227
+ const start = Math.min(sel, p.count - p.budget);
2228
+ return {
2229
+ start,
2230
+ end: start + p.budget,
2231
+ moreAbove: false,
2232
+ moreBelow: false
2233
+ };
2269
2234
  }
2235
+ if (sel < p.budget - 1) return {
2236
+ start: 0,
2237
+ end: p.budget - 1,
2238
+ moreAbove: false,
2239
+ moreBelow: true
2240
+ };
2241
+ if (sel >= p.count - (p.budget - 1)) return {
2242
+ start: p.count - (p.budget - 1),
2243
+ end: p.count,
2244
+ moreAbove: true,
2245
+ moreBelow: false
2246
+ };
2247
+ const visible = p.budget - 2;
2248
+ const start = Math.max(1, Math.min(sel - Math.floor(visible / 2), p.count - visible - 1));
2249
+ return {
2250
+ start,
2251
+ end: start + visible,
2252
+ moreAbove: true,
2253
+ moreBelow: true
2254
+ };
2270
2255
  };
2271
2256
  //#endregion
2272
2257
  //#region src/cli/tui/state/EditorSt.ts
@@ -2523,7 +2508,51 @@ var EditorSt = class EditorSt {
2523
2508
  }
2524
2509
  };
2525
2510
  //#endregion
2511
+ //#region src/cli/tui/imageClipboard.ts
2512
+ const extOf = (path) => {
2513
+ const dot = path.lastIndexOf(".");
2514
+ return dot === -1 ? "" : path.slice(dot + 1).toLowerCase();
2515
+ };
2516
+ const imageClipboardCommand = (platform, path) => {
2517
+ const ext = extOf(path);
2518
+ if (platform === "darwin") {
2519
+ if (ext !== "png" && ext !== "jpg" && ext !== "jpeg") return null;
2520
+ const cls = ext === "png" ? "«class PNGf»" : "JPEG picture";
2521
+ return {
2522
+ cmd: "osascript",
2523
+ args: ["-e", `set the clipboard to (read (POSIX file ${JSON.stringify(path)}) as ${cls})`]
2524
+ };
2525
+ }
2526
+ if (platform === "win32") return {
2527
+ cmd: "powershell",
2528
+ args: [
2529
+ "-NoProfile",
2530
+ "-Sta",
2531
+ "-Command",
2532
+ `Add-Type -AssemblyName System.Windows.Forms,System.Drawing; $img=[System.Drawing.Image]::FromFile(${`'${path.replaceAll("'", "''")}'`}); [System.Windows.Forms.Clipboard]::SetImage($img); $img.Dispose()`
2533
+ ]
2534
+ };
2535
+ return {
2536
+ cmd: "xclip",
2537
+ args: [
2538
+ "-selection",
2539
+ "clipboard",
2540
+ "-t",
2541
+ ext === "jpg" || ext === "jpeg" ? "image/jpeg" : ext === "webp" ? "image/webp" : "image/png",
2542
+ "-i",
2543
+ path
2544
+ ]
2545
+ };
2546
+ };
2547
+ //#endregion
2526
2548
  //#region src/cli/tui/state/ExecSt.ts
2549
+ /** popup body: summary + the head of the copied json (proof of WHAT is in the clipboard) */
2550
+ function jsonHead(text, maxLines) {
2551
+ const lines = text.split("\n");
2552
+ const head = lines.slice(0, maxLines).map((l) => l.length > 76 ? `${l.slice(0, 75)}…` : l);
2553
+ if (lines.length > maxLines) head.push("…");
2554
+ return head;
2555
+ }
2527
2556
  /** run lifecycle + outputs + status line + clipboard/open actions */
2528
2557
  var ExecSt = class {
2529
2558
  constructor(st) {
@@ -2536,6 +2565,9 @@ var ExecSt = class {
2536
2565
  this.error = null;
2537
2566
  this.notice = null;
2538
2567
  this.currentPromptId = null;
2568
+ this.latentHosts = /* @__PURE__ */ new Set();
2569
+ this.copyPopup = null;
2570
+ this.copying = false;
2539
2571
  makeAutoObservable(this, { st: false });
2540
2572
  }
2541
2573
  get running() {
@@ -2552,7 +2584,7 @@ var ExecSt = class {
2552
2584
  /** every run takes THIS path, queued ones included: same progress, outputs, previews */
2553
2585
  async run() {
2554
2586
  const queued = this.running;
2555
- const host = this.st.wf.host;
2587
+ const host = this.st.runHost;
2556
2588
  runInAction(() => {
2557
2589
  this.inFlight++;
2558
2590
  this.error = null;
@@ -2562,11 +2594,15 @@ var ExecSt = class {
2562
2594
  this.notice = null;
2563
2595
  this.currentPromptId = null;
2564
2596
  this.st.preview.clearLatent();
2565
- host.onLatentPreview = (p) => void this.st.preview.renderLatent(p.bytes);
2566
2597
  }
2598
+ host.onLatentPreview = (p) => void this.st.preview.renderLatent(p.bytes);
2599
+ this.latentHosts.add(host);
2567
2600
  });
2568
2601
  try {
2569
- const execution = await this.st.wf.run({ onProgress: (p) => runInAction(() => this.onProgress(p)) });
2602
+ const execution = await this.st.wf.run({
2603
+ host: this.st.hostOverride ?? void 0,
2604
+ onProgress: (p) => runInAction(() => this.onProgress(p))
2605
+ });
2570
2606
  runInAction(() => {
2571
2607
  this.outputs = execution.images.map((i) => i.absPath);
2572
2608
  this.lastStatus = execution.status;
@@ -2584,7 +2620,10 @@ var ExecSt = class {
2584
2620
  this.progress = null;
2585
2621
  this.currentPromptId = null;
2586
2622
  this.st.preview.clearLatent();
2587
- if (this.inFlight === 0) host.onLatentPreview = null;
2623
+ if (this.inFlight === 0) {
2624
+ for (const h of this.latentHosts) h.onLatentPreview = null;
2625
+ this.latentHosts.clear();
2626
+ }
2588
2627
  });
2589
2628
  }
2590
2629
  }
@@ -2621,6 +2660,61 @@ var ExecSt = class {
2621
2660
  proc.unref();
2622
2661
  this.notice = `opened ${basename(last)}`;
2623
2662
  }
2663
+ closeCopyPopup() {
2664
+ this.copyPopup = null;
2665
+ this.st.mode = "nav";
2666
+ }
2667
+ showCopyPopup(title, ok, lines) {
2668
+ const m = this.st.mode;
2669
+ if (m === "edit" || m.startsWith("overlay-")) {
2670
+ this.notice = `${ok ? "✓" : "✗"} ${title}`;
2671
+ return;
2672
+ }
2673
+ this.copyPopup = {
2674
+ title,
2675
+ ok,
2676
+ lines
2677
+ };
2678
+ this.st.mode = "overlay-copy";
2679
+ }
2680
+ /** 'i': the LAST generated image's pixels → clipboard (paste anywhere) */
2681
+ async copyLastImage() {
2682
+ const last = this.outputs[this.outputs.length - 1];
2683
+ if (last == null) {
2684
+ this.showCopyPopup("image → clipboard", false, ["no output image yet — r runs the workflow first"]);
2685
+ return;
2686
+ }
2687
+ let file = last;
2688
+ let command = imageClipboardCommand(process.platform, file);
2689
+ if (command == null && process.platform === "darwin") try {
2690
+ const { default: sharp } = await import("sharp");
2691
+ const { tmpdir } = await import("node:os");
2692
+ const { join } = await import("pathe");
2693
+ file = join(tmpdir(), `comfy-ts-clip-${Date.now()}.png`);
2694
+ await sharp(last).png().toFile(file);
2695
+ command = imageClipboardCommand(process.platform, file);
2696
+ } catch (e) {
2697
+ this.showCopyPopup("image → clipboard", false, [`COPY FAILED for ${basename(last)}`, `png transcode failed: ${extractErrorMessage(e)}`]);
2698
+ return;
2699
+ }
2700
+ if (command == null) {
2701
+ this.showCopyPopup("image → clipboard", false, [`no clipboard image tool for ${process.platform}`]);
2702
+ return;
2703
+ }
2704
+ const cmd = command;
2705
+ const ok = await new Promise((resolve) => {
2706
+ const proc = spawn(cmd.cmd, cmd.args, { stdio: "ignore" });
2707
+ proc.on("error", () => resolve(false));
2708
+ proc.on("close", (code) => resolve(code === 0));
2709
+ });
2710
+ runInAction(() => {
2711
+ this.showCopyPopup("image → clipboard", ok, ok ? [
2712
+ `${basename(last)} — paste the pixels anywhere`,
2713
+ "",
2714
+ last
2715
+ ] : [`COPY FAILED for ${basename(last)}`, `could not run ${cmd.cmd} — is it installed and allowed ?`]);
2716
+ });
2717
+ }
2624
2718
  toClipboard(text) {
2625
2719
  const [cmd, ...args] = process.platform === "darwin" ? ["pbcopy"] : process.platform === "win32" ? ["clip"] : [
2626
2720
  "xclip",
@@ -2641,29 +2735,67 @@ var ExecSt = class {
2641
2735
  }
2642
2736
  /** 'c': copy workflow.json (litegraph, drag into the ComfyUI editor) */
2643
2737
  async copyWorkflowJson() {
2738
+ if (this.copying) return;
2739
+ runInAction(() => {
2740
+ this.copying = true;
2741
+ this.notice = "building for copy… (i2i workflows upload their input image first)";
2742
+ });
2644
2743
  try {
2645
- const json = await (await this.st.wf.build()).toWorkflowJson();
2646
- const ok = await this.toClipboard(JSON.stringify(json, null, 2));
2744
+ const json = await (await this.st.wf.build({ host: this.st.hostOverride ?? void 0 })).toWorkflowJson();
2745
+ const text = JSON.stringify(json, null, 2);
2746
+ const ok = await this.toClipboard(text);
2647
2747
  runInAction(() => {
2648
- this.notice = ok ? `workflow.json copied (${json.nodes.length} nodes)` : "clipboard copy failed";
2748
+ this.showCopyPopup("workflow.json → clipboard", ok, ok ? [
2749
+ `${json.nodes.length} nodes · ${text.length} chars — paste into the ComfyUI editor`,
2750
+ "",
2751
+ ...jsonHead(text, 10)
2752
+ ] : ["CLIPBOARD COPY FAILED — is a clipboard tool available (pbcopy/clip/xclip) ?"]);
2649
2753
  });
2650
2754
  } catch (e) {
2651
2755
  runInAction(() => {
2652
- this.notice = `${extractErrorMessage(e)}`;
2756
+ this.showCopyPopup("workflow.json copy FAILED", false, [
2757
+ extractErrorMessage(e),
2758
+ "",
2759
+ "nothing was copied. i2i/i2v builds upload their input image first —",
2760
+ "an unreachable host fails the build itself, not just the run."
2761
+ ]);
2762
+ });
2763
+ } finally {
2764
+ runInAction(() => {
2765
+ this.copying = false;
2653
2766
  });
2654
2767
  }
2655
2768
  }
2656
2769
  /** 'C': copy api.json (the POST /prompt payload) */
2657
2770
  async copyApiJson() {
2771
+ if (this.copying) return;
2772
+ runInAction(() => {
2773
+ this.copying = true;
2774
+ this.notice = "building for copy… (i2i workflows upload their input image first)";
2775
+ });
2658
2776
  try {
2659
- const json = (await this.st.wf.build()).toApiJson("use_stringified_numbers_only");
2660
- const ok = await this.toClipboard(JSON.stringify(json, null, 2));
2777
+ const json = (await this.st.wf.build({ host: this.st.hostOverride ?? void 0 })).toApiJson("use_stringified_numbers_only");
2778
+ const text = JSON.stringify(json, null, 2);
2779
+ const ok = await this.toClipboard(text);
2661
2780
  runInAction(() => {
2662
- this.notice = ok ? `api.json copied (${Object.keys(json).length} nodes)` : "clipboard copy failed";
2781
+ this.showCopyPopup("api.json → clipboard", ok, ok ? [
2782
+ `${Object.keys(json).length} nodes · ${text.length} chars — the POST /prompt payload`,
2783
+ "",
2784
+ ...jsonHead(text, 10)
2785
+ ] : ["CLIPBOARD COPY FAILED — is a clipboard tool available (pbcopy/clip/xclip) ?"]);
2663
2786
  });
2664
2787
  } catch (e) {
2665
2788
  runInAction(() => {
2666
- this.notice = `${extractErrorMessage(e)}`;
2789
+ this.showCopyPopup("api.json copy FAILED", false, [
2790
+ extractErrorMessage(e),
2791
+ "",
2792
+ "nothing was copied. i2i/i2v builds upload their input image first —",
2793
+ "an unreachable host fails the build itself, not just the run."
2794
+ ]);
2795
+ });
2796
+ } finally {
2797
+ runInAction(() => {
2798
+ this.copying = false;
2667
2799
  });
2668
2800
  }
2669
2801
  }
@@ -2684,12 +2816,35 @@ const SPIN_FRAMES = [
2684
2816
  "⠇",
2685
2817
  "⠏"
2686
2818
  ];
2819
+ /**
2820
+ * PURE probe verdict (headless-tested). http ok is proof enough; on http
2821
+ * failure a RECENTLY TALKING open ws still means up — ComfyUI is
2822
+ * single-threaded and stalls new connects mid-generation while established
2823
+ * sockets stream (his repro 2026-07-30: 'windows-1 offline' in the header
2824
+ * while the browser tab generated fine). A half-open socket receives
2825
+ * nothing, so the recency window never revives one.
2826
+ */
2827
+ function probeVerdict(p) {
2828
+ if (p.httpOk) return {
2829
+ status: "up",
2830
+ via: p.wsOpen ? "ws" : "http"
2831
+ };
2832
+ if (p.wsOpen && p.lastWsMessageAt != null && p.now - p.lastWsMessageAt < 1e4) return {
2833
+ status: "up",
2834
+ via: "ws"
2835
+ };
2836
+ return {
2837
+ status: "down",
2838
+ via: null
2839
+ };
2840
+ }
2687
2841
  /** host panel (`h`): stats about the connected host + maintenance actions */
2688
2842
  var HostSt = class {
2689
2843
  constructor(st) {
2690
2844
  this.st = st;
2691
2845
  this.status = "unknown";
2692
2846
  this.statusVia = null;
2847
+ this.lastProbeError = null;
2693
2848
  this.probing = false;
2694
2849
  this.retryInS = 0;
2695
2850
  this.spinFrame = 0;
@@ -2718,6 +2873,7 @@ var HostSt = class {
2718
2873
  label: "interrupt current run"
2719
2874
  }
2720
2875
  ];
2876
+ this.pickerIx = 0;
2721
2877
  makeAutoObservable(this, { st: false });
2722
2878
  this.probeLoop();
2723
2879
  this.st.disposers.push(() => {
@@ -2726,10 +2882,11 @@ var HostSt = class {
2726
2882
  if (this.spinTimer != null) clearInterval(this.spinTimer);
2727
2883
  if (this.countdownTimer != null) clearInterval(this.countdownTimer);
2728
2884
  });
2729
- this.st.disposers.push(reaction(() => this.st.wf, () => {
2885
+ this.st.disposers.push(reaction(() => this.st.runHost, () => {
2730
2886
  runInAction(() => {
2731
2887
  this.status = "unknown";
2732
2888
  this.statusVia = null;
2889
+ this.lastProbeError = null;
2733
2890
  });
2734
2891
  this.probeGen++;
2735
2892
  if (this.loopTimer != null) clearTimeout(this.loopTimer);
@@ -2762,8 +2919,9 @@ var HostSt = class {
2762
2919
  }, PROBE_EVERY_MS);
2763
2920
  this.loopTimer.unref?.();
2764
2921
  }
2765
- /** http is the ground truth: a half-open ws keeps isOpen=true forever, and
2766
- * trusting it would re-create the exact silent-death this dot exists to expose */
2922
+ /** http first — a half-open ws keeps isOpen=true forever, so isOpen alone
2923
+ * is never trusted. RECENT MESSAGES are: probeVerdict lets a talking ws
2924
+ * beat a stalled http probe (busy single-threaded server) */
2767
2925
  async probe() {
2768
2926
  const host = this.host;
2769
2927
  runInAction(() => {
@@ -2777,12 +2935,15 @@ var HostSt = class {
2777
2935
  spin.unref?.();
2778
2936
  this.spinTimer = spin;
2779
2937
  let ok = false;
2938
+ let probeError = null;
2780
2939
  try {
2781
2940
  const res = await host.fetch("/prompt", { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
2782
2941
  res.body?.cancel();
2783
2942
  ok = res.ok;
2784
- } catch {
2943
+ if (!ok) probeError = `http ${res.status}`;
2944
+ } catch (e) {
2785
2945
  ok = false;
2946
+ probeError = extractErrorMessage(e);
2786
2947
  } finally {
2787
2948
  clearInterval(spin);
2788
2949
  if (this.spinTimer === spin) {
@@ -2793,13 +2954,20 @@ var HostSt = class {
2793
2954
  }
2794
2955
  }
2795
2956
  if (this.host !== host) return;
2957
+ const verdict = probeVerdict({
2958
+ httpOk: ok,
2959
+ wsOpen: host.isConnected,
2960
+ lastWsMessageAt: host.lastWsMessageAt,
2961
+ now: Date.now()
2962
+ });
2796
2963
  runInAction(() => {
2797
- this.status = ok ? "up" : "down";
2798
- this.statusVia = ok ? host.isConnected ? "ws" : "http" : null;
2964
+ this.status = verdict.status;
2965
+ this.statusVia = verdict.via;
2966
+ this.lastProbeError = probeError;
2799
2967
  });
2800
2968
  }
2801
2969
  get host() {
2802
- return this.st.wf.host;
2970
+ return this.st.runHost;
2803
2971
  }
2804
2972
  get stats() {
2805
2973
  const schema = this.host.schema;
@@ -2808,6 +2976,10 @@ var HostSt = class {
2808
2976
  label: "status",
2809
2977
  value: this.status === "down" ? `down · ${this.probing ? `${this.spinner} probing…` : `retry in ${this.retryInS}s`}` : this.status + (this.statusVia != null ? ` (${this.statusVia})` : "")
2810
2978
  },
2979
+ ...this.lastProbeError != null ? [{
2980
+ label: "http probe",
2981
+ value: this.lastProbeError
2982
+ }] : [],
2811
2983
  {
2812
2984
  label: "node types",
2813
2985
  value: String(schema.nodes.length)
@@ -2837,6 +3009,39 @@ var HostSt = class {
2837
3009
  blur() {
2838
3010
  this.st.mode = "nav";
2839
3011
  }
3012
+ get pickerRows() {
3013
+ const rows = [{
3014
+ host: null,
3015
+ label: `workflow default (${this.st.wf.host.data.id})`,
3016
+ active: this.st.hostOverride == null
3017
+ }];
3018
+ for (const host of comfyts.hosts.values()) rows.push({
3019
+ host,
3020
+ label: `${host.data.id} (${host.base.host}:${host.base.port})`,
3021
+ active: this.st.hostOverride === host
3022
+ });
3023
+ return rows;
3024
+ }
3025
+ beginPicker() {
3026
+ this.st.mode = "overlay-hosts";
3027
+ const active = this.pickerRows.findIndex((r) => r.active);
3028
+ this.pickerIx = active === -1 ? 0 : active;
3029
+ }
3030
+ cancelPicker() {
3031
+ this.st.mode = "nav";
3032
+ }
3033
+ pickerMove(delta) {
3034
+ const len = this.pickerRows.length;
3035
+ if (len === 0) return;
3036
+ this.pickerIx = (this.pickerIx + delta + len) % len;
3037
+ }
3038
+ commitPicker() {
3039
+ const row = this.pickerRows[this.pickerIx];
3040
+ if (row == null) return;
3041
+ this.st.setHostOverride(row.host);
3042
+ this.st.mode = "nav";
3043
+ this.st.exec.notice = row.host == null ? `host override cleared — runs target the workflow's own host (${this.st.wf.host.data.id})` : `runs now target ${row.host.data.id} (overrides ${this.st.wf.host.data.id})`;
3044
+ }
2840
3045
  move(delta) {
2841
3046
  const len = this.actions.length;
2842
3047
  this.ix = (this.ix + delta + len) % len;
@@ -3293,6 +3498,7 @@ var PickerSt = class {
3293
3498
  this.filter = "";
3294
3499
  this.ix = 0;
3295
3500
  this.invalid = false;
3501
+ this.imageSizeRow = null;
3296
3502
  makeAutoObservable(this, { st: false });
3297
3503
  }
3298
3504
  get choiceVar() {
@@ -3312,6 +3518,7 @@ var PickerSt = class {
3312
3518
  const sv = this.sizeVar;
3313
3519
  if (sv != null) {
3314
3520
  const labels = sv.presets.map((p) => `${p.width}×${p.height} ${p.label}`);
3521
+ if (this.imageSizeRow != null) labels.unshift(this.imageSizeRow);
3315
3522
  if (this.filter === "") return labels;
3316
3523
  return labels.filter((l) => fuzzyMatch(this.filter, l));
3317
3524
  }
@@ -3331,8 +3538,10 @@ var PickerSt = class {
3331
3538
  this.st.mode = "overlay-size";
3332
3539
  this.filter = "";
3333
3540
  this.invalid = false;
3334
- const ix = sv.presets.findIndex((p) => p.width === sv.value.width && p.height === sv.value.height);
3335
- this.ix = ix === -1 ? 0 : ix;
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);
3336
3545
  }
3337
3546
  move(delta) {
3338
3547
  const len = this.options.length;
@@ -3408,7 +3617,7 @@ var QueueSt = class {
3408
3617
  }
3409
3618
  async clearPending() {
3410
3619
  try {
3411
- await this.st.wf.host.clearQueue();
3620
+ await this.st.runHost.clearQueue();
3412
3621
  runInAction(() => {
3413
3622
  this.st.exec.notice = "pending queue cleared";
3414
3623
  });
@@ -3420,7 +3629,7 @@ var QueueSt = class {
3420
3629
  }
3421
3630
  async interrupt() {
3422
3631
  try {
3423
- await this.st.wf.host.interrupt();
3632
+ await this.st.runHost.interrupt();
3424
3633
  runInAction(() => {
3425
3634
  this.st.exec.notice = "interrupt requested";
3426
3635
  });
@@ -3454,15 +3663,25 @@ var SettingsSt = class {
3454
3663
  this.previewRenderer = protocolCapable() ? "native" : "pixel";
3455
3664
  this.previewDuringRun = "latent";
3456
3665
  this.lastDraft = {};
3666
+ this.lastWorkflow = null;
3667
+ this.hostOverrideId = null;
3668
+ this.collapsedDirs = [];
3457
3669
  this.load();
3458
3670
  if (this.previewRenderer === "native" && !protocolCapable()) this.previewRenderer = "pixel";
3459
3671
  makeAutoObservable(this, { st: false });
3460
- this.st.disposers.push(reaction(() => JSON.stringify({
3672
+ this.st.disposers.push(reaction(() => this.snapshotJson(), (json) => this.write(json), { delay: 300 }));
3673
+ this.st.disposers.push(() => this.write(this.snapshotJson()));
3674
+ }
3675
+ snapshotJson() {
3676
+ return JSON.stringify({
3461
3677
  previewPanel: this.previewPanel,
3462
3678
  previewRenderer: this.previewRenderer,
3463
3679
  previewDuringRun: this.previewDuringRun,
3464
- lastDraft: this.lastDraft
3465
- }), (json) => this.write(json), { delay: 300 }));
3680
+ lastDraft: this.lastDraft,
3681
+ lastWorkflow: this.lastWorkflow,
3682
+ hostOverrideId: this.hostOverrideId,
3683
+ collapsedDirs: this.collapsedDirs
3684
+ });
3466
3685
  }
3467
3686
  rememberDraft(moduleKey, draft) {
3468
3687
  this.lastDraft[moduleKey] = draft;
@@ -3483,6 +3702,9 @@ var SettingsSt = class {
3483
3702
  this.previewRenderer = preview.previewRenderer;
3484
3703
  this.previewDuringRun = preview.previewDuringRun;
3485
3704
  if (o.lastDraft != null && typeof o.lastDraft === "object") this.lastDraft = { ...o.lastDraft };
3705
+ if (typeof o.lastWorkflow === "string") this.lastWorkflow = o.lastWorkflow;
3706
+ if (typeof o.hostOverrideId === "string") this.hostOverrideId = o.hostOverrideId;
3707
+ if (Array.isArray(o.collapsedDirs)) this.collapsedDirs = o.collapsedDirs.filter((d) => typeof d === "string");
3486
3708
  } catch {}
3487
3709
  }
3488
3710
  write(json) {
@@ -3499,45 +3721,63 @@ var SettingsSt = class {
3499
3721
  };
3500
3722
  //#endregion
3501
3723
  //#region src/cli/tui/state/TreeSt.ts
3502
- /** the left `(t)ree`: workflows with their drafts nested under them */
3724
+ /** the left `(t)ree`: directory hierarchy + workflows with their drafts nested */
3503
3725
  var TreeSt = class {
3504
3726
  constructor(st) {
3505
3727
  this.st = st;
3506
3728
  this.ix = 0;
3507
3729
  this.expandedFiles = /* @__PURE__ */ new Set();
3730
+ this.filter = "";
3731
+ this.filtering = false;
3732
+ this.viewH = 0;
3733
+ this.collapsedDirs = new Set(st.settings.collapsedDirs);
3508
3734
  makeAutoObservable(this, { st: false });
3509
3735
  }
3736
+ /** fold state is hand-tuned: mirror every change into the settings file */
3737
+ persistFolds() {
3738
+ this.st.settings.collapsedDirs = [...this.collapsedDirs];
3739
+ }
3740
+ /** family → color over the FULL file list (stable under filter/fold) */
3741
+ get familyColors() {
3742
+ return assignFamilyColors(this.st.workflows.files);
3743
+ }
3510
3744
  get rows() {
3511
3745
  this.st.drafts.version;
3512
3746
  const w = this.st.workflows;
3747
+ const fileRows = buildFileRows({
3748
+ userFiles: w.files.filter((f) => !w.bundled.has(f)),
3749
+ bundledFiles: w.files.filter((f) => w.bundled.has(f)),
3750
+ collapsedDirs: this.collapsedDirs,
3751
+ filter: this.filter
3752
+ });
3753
+ const colors = this.familyColors;
3513
3754
  const rows = [];
3514
- let sectionPushed = false;
3515
- for (const file of w.files) {
3516
- if (!sectionPushed && w.bundled.has(file)) {
3517
- rows.push({
3518
- kind: "section",
3519
- label: "comfy-ts examples"
3520
- });
3521
- sectionPushed = true;
3755
+ for (const row of fileRows) {
3756
+ if (row.kind === "dir") {
3757
+ rows.push(row);
3758
+ continue;
3522
3759
  }
3523
- const current = file === w.currentPath;
3524
- const expanded = this.expandedFiles.has(file);
3525
- const drafts = listDraftsForFile(file);
3760
+ const current = row.file === w.currentPath;
3761
+ const expanded = this.expandedFiles.has(row.file);
3762
+ const drafts = listDraftsForFile(row.file);
3526
3763
  rows.push({
3527
3764
  kind: "workflow",
3528
- file,
3529
- name: draftKeyForFile(file),
3765
+ file: row.file,
3766
+ name: row.name,
3767
+ depth: row.depth,
3530
3768
  expanded,
3531
3769
  current,
3532
3770
  hasDrafts: drafts.length > 0,
3533
- error: w.loadErrors.get(file) ?? null
3771
+ error: w.loadErrors.get(row.file) ?? null,
3772
+ color: w.specColors.get(row.file) ?? colors.get(familyOf(row.name)) ?? "white"
3534
3773
  });
3535
3774
  if (!expanded) continue;
3536
3775
  for (const draft of drafts) rows.push({
3537
3776
  kind: "draft",
3538
- file,
3777
+ file: row.file,
3539
3778
  draft,
3540
- active: current && draft === this.st.drafts.active
3779
+ active: current && draft === this.st.drafts.active,
3780
+ depth: row.depth + 1
3541
3781
  });
3542
3782
  }
3543
3783
  return rows;
@@ -3552,57 +3792,137 @@ var TreeSt = class {
3552
3792
  this.st.exec.notice = "no workflow tree — start the tui in a folder containing **/*.cflow.ts";
3553
3793
  return;
3554
3794
  }
3555
- if (w.currentPath != null) this.expandedFiles.add(w.currentPath);
3795
+ if (w.currentPath != null) {
3796
+ this.expandedFiles.add(w.currentPath);
3797
+ let changed = false;
3798
+ const collapsed = [...this.collapsedDirs];
3799
+ for (const dir of collapsed) if (w.currentPath.startsWith(`${dir}/`)) {
3800
+ this.collapsedDirs.delete(dir);
3801
+ changed = true;
3802
+ }
3803
+ if (changed) this.persistFolds();
3804
+ }
3556
3805
  this.st.mode = "tree";
3557
3806
  const rows = this.rows;
3558
3807
  const draftIx = rows.findIndex((r) => r.kind === "draft" && r.active);
3559
3808
  const ix = draftIx === -1 ? rows.findIndex((r) => r.kind === "workflow" && r.current) : draftIx;
3560
3809
  this.ix = ix === -1 ? 0 : ix;
3561
3810
  }
3811
+ setViewH(h) {
3812
+ this.viewH = h;
3813
+ }
3814
+ /** rows available for tree content: measured panel height minus the panel's
3815
+ * own chrome (2 border rows, the filter line when visible, the loading
3816
+ * line). Pre-measure fallback: termRows minus the header+keybar estimate —
3817
+ * one frame only, the measurement replaces it. */
3818
+ get viewBudget() {
3819
+ const h = this.viewH > 0 ? this.viewH : Math.max(5, this.st.termRows - 5);
3820
+ const filterLine = this.filtering || this.filter !== "" ? 1 : 0;
3821
+ const loadingLine = this.st.workflows.loading ? 1 : 0;
3822
+ return Math.max(1, h - 2 - filterLine - loadingLine);
3823
+ }
3824
+ /** the visible slice, selection always inside, markers within the budget */
3825
+ get window() {
3826
+ return listWindow({
3827
+ count: this.rows.length,
3828
+ selected: this.ix,
3829
+ budget: this.viewBudget
3830
+ });
3831
+ }
3562
3832
  /** esc/t inside the tree, → on a draft row, `v` anywhere: back to the vars list */
3563
3833
  blur() {
3834
+ this.filtering = false;
3564
3835
  this.st.mode = "nav";
3565
3836
  }
3566
3837
  move(delta) {
3567
- const rows = this.rows;
3568
- const len = rows.length;
3838
+ const len = this.rows.length;
3569
3839
  if (len === 0) return;
3570
- let ix = this.ix;
3571
- for (let step = 0; step < len; step++) {
3572
- ix = (ix + delta + len) % len;
3573
- if (rows[ix]?.kind !== "section") break;
3840
+ this.ix = (this.ix + delta + len) % len;
3841
+ }
3842
+ beginFilter() {
3843
+ this.filtering = true;
3844
+ }
3845
+ filterInput(ch) {
3846
+ this.filter += ch;
3847
+ this.clampToSelectable();
3848
+ }
3849
+ filterBackspace() {
3850
+ this.filter = this.filter.slice(0, -1);
3851
+ this.clampToSelectable();
3852
+ }
3853
+ /** esc while the filter owns the keys: drop it, stay in the tree */
3854
+ clearFilter() {
3855
+ this.filter = "";
3856
+ this.filtering = false;
3857
+ this.clampToSelectable();
3858
+ }
3859
+ /** filter edits reshape rows: keep the cursor on a workflow row when one exists */
3860
+ clampToSelectable() {
3861
+ const rows = this.rows;
3862
+ this.ix = Math.min(this.ix, Math.max(0, rows.length - 1));
3863
+ if (rows[this.ix]?.kind !== "workflow") {
3864
+ const first = rows.findIndex((r) => r.kind === "workflow");
3865
+ if (first !== -1) this.ix = first;
3574
3866
  }
3575
- this.ix = ix;
3576
3867
  }
3577
- /** →: unfold the workflow under the cursor; on a draft row there is nothing
3578
- * left to unfold, so → continues rightwards into the vars panel */
3868
+ /** →: unfold the dir/workflow under the cursor; on a draft row there is
3869
+ * nothing left to unfold, so → continues rightwards into the vars panel */
3579
3870
  unfold() {
3580
3871
  const row = this.selected;
3581
- if (row == null || row.kind === "section") return;
3582
- if (row.kind === "workflow") this.expandedFiles.add(row.file);
3872
+ if (row == null) return;
3873
+ if (row.kind === "dir") {
3874
+ this.collapsedDirs.delete(row.path);
3875
+ this.persistFolds();
3876
+ } else if (row.kind === "workflow") this.expandedFiles.add(row.file);
3583
3877
  else this.blur();
3584
3878
  }
3585
- /** ←: fold the workflow under the cursor; on a draft row, jump to (and fold) its parent */
3879
+ /** ←: fold under the cursor; on an already-folded row, jump to the parent */
3586
3880
  fold() {
3587
3881
  const row = this.selected;
3588
- if (row == null || row.kind === "section") return;
3589
- this.expandedFiles.delete(row.file);
3882
+ if (row == null) return;
3883
+ if (row.kind === "dir") {
3884
+ this.collapsedDirs.add(row.path);
3885
+ this.persistFolds();
3886
+ return;
3887
+ }
3590
3888
  if (row.kind === "draft") {
3591
3889
  const ix = this.rows.findIndex((r) => r.kind === "workflow" && r.file === row.file);
3592
3890
  if (ix !== -1) this.ix = ix;
3891
+ this.expandedFiles.delete(row.file);
3892
+ return;
3893
+ }
3894
+ if (row.expanded) {
3895
+ this.expandedFiles.delete(row.file);
3896
+ return;
3897
+ }
3898
+ for (let ix = this.ix - 1; ix >= 0; ix--) {
3899
+ const r = this.rows[ix];
3900
+ if (r?.kind === "dir" && r.depth < row.depth) {
3901
+ this.ix = ix;
3902
+ return;
3903
+ }
3593
3904
  }
3594
3905
  }
3595
- /** ⏎: load the workflow (into 'default'), or the exact draft under the cursor */
3906
+ /** ⏎: toggle a dir, load the workflow (into 'default'), or load the exact draft */
3596
3907
  async commit() {
3597
3908
  const row = this.selected;
3598
- if (row == null || row.kind === "section") return;
3909
+ if (row == null) return;
3910
+ if (row.kind === "dir") {
3911
+ if (this.filter !== "") return;
3912
+ if (row.expanded) this.collapsedDirs.add(row.path);
3913
+ else this.collapsedDirs.delete(row.path);
3914
+ this.persistFolds();
3915
+ return;
3916
+ }
3917
+ this.filter = "";
3918
+ this.filtering = false;
3599
3919
  if (row.kind === "workflow") return this.st.workflows.commit(row.file);
3600
3920
  return this.st.workflows.commit(row.file, row.draft);
3601
3921
  }
3602
3922
  /** n: new draft — current workflow only (a draft snapshots its LIVE var values) */
3603
3923
  promptNewDraft() {
3604
3924
  const row = this.selected;
3605
- if (row?.kind === "section") return;
3925
+ if (row?.kind === "dir") return;
3606
3926
  if (row != null && row.file !== this.st.workflows.currentPath) {
3607
3927
  this.st.exec.notice = "load that workflow first (⏎) — a new draft snapshots its live vars";
3608
3928
  return;
@@ -3630,12 +3950,16 @@ var WorkflowsSt = class {
3630
3950
  this.st = st;
3631
3951
  this.files = files;
3632
3952
  this.loading = false;
3953
+ this.specColors = /* @__PURE__ */ new Map();
3633
3954
  this.loadedHosts = /* @__PURE__ */ new Set();
3634
3955
  this.currentPath = currentPath;
3635
3956
  this.bundled = bundled;
3636
3957
  this.loadErrors = loadErrors;
3637
3958
  makeAutoObservable(this, { st: false });
3638
3959
  }
3960
+ recordSpecColor(path, wf) {
3961
+ if (wf.spec.color != null) this.specColors.set(path, wf.spec.color);
3962
+ }
3639
3963
  disconnectAllHosts() {
3640
3964
  this.loadedHosts.add(this.st.wf.host);
3641
3965
  for (const host of this.loadedHosts) host.disconnect();
@@ -3670,10 +3994,13 @@ var WorkflowsSt = class {
3670
3994
  this.loadErrors.delete(path);
3671
3995
  this.loadedHosts.add(this.st.wf.host);
3672
3996
  this.loadedHosts.add(wf.host);
3997
+ this.recordSpecColor(path, wf);
3673
3998
  this.st.wf = wf;
3674
- this.st.queue.attach(wf.host);
3675
- this.st.logs.attach(wf.host);
3999
+ this.st.applyPersistedHostOverride();
4000
+ this.st.queue.attach(this.st.runHost);
4001
+ this.st.logs.attach(this.st.runHost);
3676
4002
  this.currentPath = path;
4003
+ this.st.settings.lastWorkflow = path;
3677
4004
  this.st.selIx = 0;
3678
4005
  this.st.mode = "nav";
3679
4006
  this.st.exec.resetForWorkflow(`${basename(path)}`);
@@ -3702,16 +4029,37 @@ var WorkflowsSt = class {
3702
4029
  * classes with an `st` backref; components are stateless views over this.
3703
4030
  */
3704
4031
  var TuiSt = class {
4032
+ /** the host runs actually target right now */
4033
+ get runHost() {
4034
+ return this.hostOverride ?? this.wf.host;
4035
+ }
4036
+ setHostOverride(host) {
4037
+ this.hostOverride = host;
4038
+ if (host != null) this.workflows.loadedHosts.add(host);
4039
+ this.queue.attach(this.runHost);
4040
+ this.logs.attach(this.runHost);
4041
+ this.settings.hostOverrideId = host?.data.id ?? null;
4042
+ }
4043
+ /** re-resolve a persisted override id — hosts register as modules import */
4044
+ applyPersistedHostOverride() {
4045
+ const id = this.settings.hostOverrideId;
4046
+ if (id == null || this.hostOverride != null) return;
4047
+ const host = comfyts.hosts.get(id);
4048
+ if (host != null) this.setHostOverride(host);
4049
+ }
3705
4050
  constructor(wf, opts = {}) {
3706
4051
  this.mode = "nav";
3707
4052
  this.selIx = 0;
4053
+ this.hostOverride = null;
3708
4054
  this.disposers = [];
3709
4055
  this.onExit = () => {};
3710
4056
  this.termCols = process.stdout.columns ?? 80;
3711
4057
  this.termRows = (process.stdout.rows ?? 24) - 1;
4058
+ this.varsViewH = 0;
3712
4059
  this.wf = wf;
3713
4060
  makeAutoObservable(this, {
3714
4061
  wf: observable.ref,
4062
+ hostOverride: observable.ref,
3715
4063
  onExit: false,
3716
4064
  editor: false,
3717
4065
  picker: false,
@@ -3740,8 +4088,13 @@ var TuiSt = class {
3740
4088
  this.host = new HostSt(this);
3741
4089
  this.queue = new QueueSt(this);
3742
4090
  this.logs = new LogsSt(this);
4091
+ this.applyPersistedHostOverride();
3743
4092
  this.drafts.activateRemembered();
3744
- if (opts.currentFile != null) this.tree.expandedFiles.add(opts.currentFile);
4093
+ if (opts.currentFile != null) {
4094
+ this.tree.expandedFiles.add(opts.currentFile);
4095
+ this.workflows.recordSpecColor(opts.currentFile, wf);
4096
+ this.settings.lastWorkflow = opts.currentFile;
4097
+ }
3745
4098
  const onResize = () => {
3746
4099
  runInAction(() => {
3747
4100
  this.termCols = process.stdout.columns ?? 80;
@@ -3759,10 +4112,10 @@ var TuiSt = class {
3759
4112
  get overlayLines() {
3760
4113
  return Math.max(8, this.termRows - 12);
3761
4114
  }
3762
- /** left tree panel width: longest row (workflow or indented draft), clamped */
4115
+ /** left tree panel width: longest row (depth-indented), clamped */
3763
4116
  get treeWidth() {
3764
- const longest = Math.max(8, ...this.tree.rows.map((r) => r.kind === "workflow" ? r.name.length : r.kind === "draft" ? r.draft.length + 3 : r.label.length));
3765
- return Math.min(32, longest + 7);
4117
+ const longest = Math.max(8, ...this.tree.rows.map((r) => r.depth * 2 + (r.kind === "workflow" ? r.name.length : r.kind === "draft" ? r.draft.length + 3 : r.label.length + 2)));
4118
+ return Math.min(34, longest + 7);
3766
4119
  }
3767
4120
  get entries() {
3768
4121
  return this.wf.entries();
@@ -3775,6 +4128,33 @@ var TuiSt = class {
3775
4128
  if (len === 0) return;
3776
4129
  this.selIx = (this.selIx + delta + len) % len;
3777
4130
  }
4131
+ setVarsViewH(h) {
4132
+ this.varsViewH = h;
4133
+ }
4134
+ /** row budget: measured height minus the 2 border rows; pre-measure fallback estimate */
4135
+ get varsBudget() {
4136
+ const h = this.varsViewH > 0 ? this.varsViewH : Math.max(5, this.termRows - 5);
4137
+ return Math.max(1, h - 2);
4138
+ }
4139
+ get varsWindow() {
4140
+ return listWindow({
4141
+ count: this.entries.length,
4142
+ selected: this.selIx,
4143
+ budget: this.varsBudget
4144
+ });
4145
+ }
4146
+ /**
4147
+ * while the list cannot fit, NON-selected rows collapse to one truncated
4148
+ * line (prompt values wrap tall) — rows above the selection then cost one
4149
+ * line each, so the selection can never be pushed off-screen. Reads only
4150
+ * entry count + measured height, never its own rendering: no oscillation.
4151
+ */
4152
+ get varsCompact() {
4153
+ const w = this.varsWindow;
4154
+ if (w.moreAbove || w.moreBelow) return true;
4155
+ const h = this.varsViewH > 0 ? this.varsViewH : Math.max(5, this.termRows - 5);
4156
+ return this.entries.length + 2 > h;
4157
+ }
3778
4158
  /** enter/space on a var: toggle, open an overlay, or inline-edit */
3779
4159
  activate() {
3780
4160
  const sel = this.selected?.[1];
@@ -3805,6 +4185,18 @@ var TuiSt = class {
3805
4185
  };
3806
4186
  //#endregion
3807
4187
  //#region src/cli/tui/run-tui.tsx
4188
+ /** the module the last session was on, IF it is still in this run's tree
4189
+ * (settings write: SettingsSt; exported for the headless test) */
4190
+ function rememberedWorkflow(workflowFiles, settingsPath = settingsPathFor(process.cwd())) {
4191
+ try {
4192
+ const raw = JSON.parse(readFileSync(settingsPath, "utf8"));
4193
+ if (raw == null || typeof raw !== "object") return null;
4194
+ const last = raw.lastWorkflow;
4195
+ return typeof last === "string" && workflowFiles.includes(last) ? last : null;
4196
+ } catch {
4197
+ return null;
4198
+ }
4199
+ }
3808
4200
  async function runTui(args) {
3809
4201
  const target = args.find((a) => !a.startsWith("--"));
3810
4202
  process.env[COMFY_TS_TUI_ENV] = "1";
@@ -3816,17 +4208,19 @@ async function runTui(args) {
3816
4208
  const canImportBundled = process.versions.bun != null;
3817
4209
  const examplesDir = canImportBundled ? bundledExamplesDir() : null;
3818
4210
  if (!canImportBundled && target == null) logError("packaged examples skipped: importing .cflow.ts from node_modules needs bun (bunx --bun comfy-ts tui)");
4211
+ const bundledFiles = examplesDir == null ? [] : scanCflowFiles(realpathSync(examplesDir)).sort((a, b) => Number(!a.includes("/rvion/")) - Number(!b.includes("/rvion/")) || a.localeCompare(b));
3819
4212
  const discovery = mergeWorkflowSources({
3820
4213
  explicitTarget: target != null,
3821
4214
  scanned: scannedPlusArg,
3822
- bundledFiles: examplesDir == null ? [] : scanCflowFiles(realpathSync(examplesDir))
4215
+ bundledFiles
3823
4216
  });
3824
4217
  const workflowFiles = discovery.files;
3825
4218
  if (workflowFiles.length === 0) {
3826
4219
  console.error(`[comfy-ts tui] no **/*.cflow.ts found under ${abs}`);
3827
4220
  return 1;
3828
4221
  }
3829
- const candidates = !isDir && workflowFiles.includes(abs) ? [abs, ...workflowFiles.filter((f) => f !== abs)] : workflowFiles;
4222
+ const preferred = !isDir && workflowFiles.includes(abs) ? abs : target == null ? rememberedWorkflow(workflowFiles) : null;
4223
+ const candidates = preferred != null ? [preferred, ...workflowFiles.filter((f) => f !== preferred)] : workflowFiles;
3830
4224
  const loadErrors = /* @__PURE__ */ new Map();
3831
4225
  let first = null;
3832
4226
  let wf = null;
@@ -3854,11 +4248,13 @@ async function runTui(args) {
3854
4248
  if (altScreen) process.stdout.write("\x1B[?1049h\x1B[H\x1B[>4;1m");
3855
4249
  const uninstallPainter = installProtocolImagePainter(st);
3856
4250
  try {
4251
+ if (process.stdin.isTTY === true) process.stdin.setRawMode(true);
3857
4252
  const app = render(/* @__PURE__ */ jsx(TuiApp, { st }), { kittyKeyboard: { mode: "auto" } });
3858
4253
  st.onExit = () => st.dispose();
3859
4254
  await app.waitUntilExit();
3860
4255
  st.dispose();
3861
4256
  } finally {
4257
+ if (process.stdin.isTTY === true) process.stdin.setRawMode(false);
3862
4258
  uninstallPainter();
3863
4259
  if (altScreen) process.stdout.write("\x1B[0m\x1B[2J\x1B[H\x1B[>4;0m\x1B[?1049l");
3864
4260
  }
@@ -3867,4 +4263,4 @@ async function runTui(args) {
3867
4263
  //#endregion
3868
4264
  export { runTui };
3869
4265
 
3870
- //# sourceMappingURL=run-tui-DZ22HDHI.js.map
4266
+ //# sourceMappingURL=run-tui-BtjaOXRh.js.map