comfy-ts 0.2.0 → 0.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 (161) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +363 -0
  3. package/dist/cli.js +764 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/index.cjs +4171 -0
  6. package/dist/index.cjs.map +1 -0
  7. package/dist/index.d.cts +9910 -0
  8. package/dist/index.d.ts +9894 -58
  9. package/dist/index.js +4092 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/log-CdfgILde.js +10 -0
  12. package/dist/log-CdfgILde.js.map +1 -0
  13. package/dist/run-tui-SDSJo1Qf.js +3896 -0
  14. package/dist/run-tui-SDSJo1Qf.js.map +1 -0
  15. package/package.json +103 -75
  16. package/src/cli/comfy-ts-cli.ts +36 -0
  17. package/src/cli/gen.ts +47 -0
  18. package/src/cli/outline.ts +82 -0
  19. package/src/cli/tui/components/DraftsOverlay.tsx +44 -0
  20. package/src/cli/tui/components/EditField.tsx +27 -0
  21. package/src/cli/tui/components/Header.tsx +56 -0
  22. package/src/cli/tui/components/HostPanel.tsx +37 -0
  23. package/src/cli/tui/components/LogsPanel.tsx +23 -0
  24. package/src/cli/tui/components/LorasOverlay.tsx +49 -0
  25. package/src/cli/tui/components/OverlayList.tsx +25 -0
  26. package/src/cli/tui/components/PickerOverlays.tsx +66 -0
  27. package/src/cli/tui/components/PreviewPanel.tsx +78 -0
  28. package/src/cli/tui/components/PromptOverlay.tsx +16 -0
  29. package/src/cli/tui/components/StatusBar.tsx +171 -0
  30. package/src/cli/tui/components/TextOverlay.tsx +72 -0
  31. package/src/cli/tui/components/TreePanel.tsx +51 -0
  32. package/src/cli/tui/components/TuiApp.tsx +246 -0
  33. package/src/cli/tui/components/VarsPanel.tsx +86 -0
  34. package/src/cli/tui/findDefinedWorkflow.ts +16 -0
  35. package/src/cli/tui/keys.ts +20 -0
  36. package/src/cli/tui/protocolImagePainter.ts +95 -0
  37. package/src/cli/tui/run-tui.tsx +76 -0
  38. package/src/cli/tui/state/DraftsSt.ts +273 -0
  39. package/src/cli/tui/state/EditorSt.ts +289 -0
  40. package/src/cli/tui/state/ExecSt.ts +173 -0
  41. package/src/cli/tui/state/HostSt.ts +230 -0
  42. package/src/cli/tui/state/LogsSt.ts +107 -0
  43. package/src/cli/tui/state/LorasSt.ts +185 -0
  44. package/src/cli/tui/state/PickerSt.ts +112 -0
  45. package/src/cli/tui/state/PreviewSt.ts +288 -0
  46. package/src/cli/tui/state/QueueSt.ts +59 -0
  47. package/src/cli/tui/state/SettingsSt.ts +100 -0
  48. package/src/cli/tui/state/TreeSt.ts +122 -0
  49. package/src/cli/tui/state/TuiSt.ts +175 -0
  50. package/src/cli/tui/state/WorkflowsSt.ts +93 -0
  51. package/src/cli/tui-env.ts +8 -0
  52. package/src/errors/InvalidPromptError.ts +12 -0
  53. package/src/graph/ComfyNode.ts +403 -0
  54. package/src/graph/ComfyNodeID.ts +28 -0
  55. package/src/graph/ComfyNodeOutput.ts +16 -0
  56. package/src/graph/NodeSlotSize.ts +4 -0
  57. package/src/graph/autoValue.ts +17 -0
  58. package/src/host/ComfyHost.ts +690 -0
  59. package/src/host/ComfyInstallType.ts +15 -0
  60. package/src/host/ComfyManager.ts +232 -0
  61. package/src/host/ComfyUploader.ts +110 -0
  62. package/src/host/ComfyWorkflowBuilder.ts +60 -0
  63. package/src/host/Requirements.ts +55 -0
  64. package/src/host/ResilientWebsocket.ts +147 -0
  65. package/src/host/loraManagerApi.ts +98 -0
  66. package/src/image-utils/_getPngMetadata.ts +53 -0
  67. package/src/image-utils/_getWebpMetadata.ts +38 -0
  68. package/src/image-utils/_parseExifData.ts +53 -0
  69. package/src/index.ts +89 -0
  70. package/src/litegraph/LiteGraphGroup.ts +22 -0
  71. package/src/litegraph/LiteGraphJSON.ts +46 -0
  72. package/src/litegraph/LiteGraphLink.ts +23 -0
  73. package/src/litegraph/LiteGraphLinkID.ts +6 -0
  74. package/src/litegraph/LiteGraphNode.ts +69 -0
  75. package/src/litegraph/LiteGraphNodeInput.ts +27 -0
  76. package/src/litegraph/LiteGraphNodeOutput.ts +23 -0
  77. package/src/litegraph/LiteGraphSlotIndex.ts +6 -0
  78. package/src/litegraph/convertFlowToLiteGraphJSON.ts +114 -0
  79. package/src/manager/ComfyRegistry.ts +124 -0
  80. package/src/manager/generated/KnownComfyCustomNodeName.ts +19280 -0
  81. package/src/manager/generated/KnownComfyPluginTitle.ts +5130 -0
  82. package/src/manager/generated/KnownComfyPluginURL.ts +2589 -0
  83. package/src/manager/generated/KnownModel_Base.ts +126 -0
  84. package/src/manager/generated/KnownModel_FileName.ts +2287 -0
  85. package/src/manager/generated/KnownModel_Name.ts +2287 -0
  86. package/src/manager/generated/KnownModel_SavePath.ts +263 -0
  87. package/src/manager/generated/KnownModel_Type.ts +97 -0
  88. package/src/manager/json/alter-list.json +224 -0
  89. package/src/manager/json/custom-node-list.extra.ts +13 -0
  90. package/src/manager/json/custom-node-list.json +21948 -0
  91. package/src/manager/json/extension-node-map.json +31282 -0
  92. package/src/manager/json/github-stats.json +12602 -0
  93. package/src/manager/json/model-list.extra.ts +26 -0
  94. package/src/manager/json/model-list.json +5052 -0
  95. package/src/manager/loaders/step1_downloadComfyManagerJSONs.ts +56 -0
  96. package/src/manager/loaders/step2_custom-node-list-loader.ts +149 -0
  97. package/src/manager/loaders/step3_extension-node-map-loader.ts +189 -0
  98. package/src/manager/loaders/step4_model-list-loader.ts +159 -0
  99. package/src/manager/script-update-manager.bun.ts +18 -0
  100. package/src/manager/types/ComfyManagerAPIFetchPolicy.ts +9 -0
  101. package/src/manager/types/ComfyManagerAPIModelList.ts +10 -0
  102. package/src/manager/types/ComfyManagerAPIPluginList.ts +11 -0
  103. package/src/manager/types/ComfyManagerFileModelInfo.ts +5 -0
  104. package/src/manager/types/ComfyManagerFilePluginContent.ts +13 -0
  105. package/src/manager/types/ComfyManagerFilePluginList.ts +5 -0
  106. package/src/manager/types/ComfyManagerModelInfo.ts +18 -0
  107. package/src/manager/types/ComfyManagerPluginContentMetadata.ts +16 -0
  108. package/src/manager/types/ComfyManagerPluginEnums.ts +8 -0
  109. package/src/manager/types/ComfyManagerPluginInfo.ts +50 -0
  110. package/src/runner/ComfyExecution.ts +301 -0
  111. package/src/runner/ComfyExecutionStatus.ts +2 -0
  112. package/src/runner/ComfyWorkflow.ts +395 -0
  113. package/src/runner/ComfyWorkflowLayout.ts +96 -0
  114. package/src/runner/ComfyWsApi.ts +170 -0
  115. package/src/runner/MediaImage.ts +262 -0
  116. package/src/sdk-generator/ComfyNodeSchema.ts +79 -0
  117. package/src/sdk-generator/ComfySchema.ts +369 -0
  118. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +95 -0
  119. package/src/sdk-generator/Primitives.ts +76 -0
  120. package/src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts +39 -0
  121. package/src/sdk-generator/_pythonModuleToNamespace.ts +27 -0
  122. package/src/sdk-generator/_toQualifiedNodeKey.ts +5 -0
  123. package/src/sdk-generator/comfy-api-json.ts +16 -0
  124. package/src/sdk-generator/comfyui-sdk-codegen.ts +287 -0
  125. package/src/sdk-generator/comfyui-types.ts +56 -0
  126. package/src/sdk-generator/litegraphToApiRequestPayload.ts +157 -0
  127. package/src/ssh-host-manager/ssh-config-manager.ts +89 -0
  128. package/src/ssh-host-manager/ssh-config.windows.md +32 -0
  129. package/src/ssh-host-manager/ssh-manager.ts +114 -0
  130. package/src/state.ts +136 -0
  131. package/src/types/comfy-sdk.ts +106 -0
  132. package/src/types/index.ts +55 -0
  133. package/src/utils/CodeBuffer.ts +61 -0
  134. package/src/utils/ComfyColors.ts +38 -0
  135. package/src/utils/ansi.ts +33 -0
  136. package/src/utils/ansiImage.ts +36 -0
  137. package/src/utils/bang.ts +39 -0
  138. package/src/utils/deepCopyNaive.ts +1 -0
  139. package/src/utils/downloadFile.ts +77 -0
  140. package/src/utils/escapeJSKey.ts +32 -0
  141. package/src/utils/exhaust.ts +4 -0
  142. package/src/utils/extractErrorMessage.ts +11 -0
  143. package/src/utils/fuzzyMatch.ts +8 -0
  144. package/src/utils/githubRegexes.ts +2 -0
  145. package/src/utils/hashArrayBuffer.ts +6 -0
  146. package/src/utils/log.ts +9 -0
  147. package/src/utils/loraTag.ts +10 -0
  148. package/src/utils/mojibake.ts +60 -0
  149. package/src/utils/printArkResultInConsole.ts +16 -0
  150. package/src/utils/softValidate.ts +8 -0
  151. package/src/utils/stringifyReadable.ts +32 -0
  152. package/src/utils/toposort.ts +59 -0
  153. package/src/utils/tryExtracting.ts +41 -0
  154. package/src/utils/writeFile.ts +16 -0
  155. package/src/vars/ComfyVars.ts +531 -0
  156. package/src/vars/DefinedWorkflow.ts +112 -0
  157. package/src/vars/loraKeywords.ts +56 -0
  158. package/dist/index.d.mts +0 -74
  159. package/dist/index.mjs +0 -3
  160. package/dist/index.mjs.map +0 -1
  161. package/readme.md +0 -40
@@ -0,0 +1,112 @@
1
+ import { makeAutoObservable } from 'mobx'
2
+ import { fuzzyMatch } from 'src/utils/fuzzyMatch.ts'
3
+ import type { ChoiceVar, SizeVar } from 'src/vars/ComfyVars.ts'
4
+ import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
5
+
6
+ /**
7
+ * choice + size overlays: a windowed option list with a fuzzy type-to-filter.
8
+ * For sizes the filter doubles as free `WxH` entry.
9
+ */
10
+ export class PickerSt {
11
+ constructor(private st: TuiSt) {
12
+ makeAutoObservable<PickerSt, 'st'>(this, { st: false })
13
+ }
14
+
15
+ filter: string = ''
16
+ ix: number = 0
17
+ /** size overlay only: the filter failed to parse as WxH on commit */
18
+ invalid: boolean = false
19
+
20
+ // kind-narrowing casts sanctioned (agent/coding.md), `kind` is the tag
21
+ private get choiceVar(): ChoiceVar<string> | null {
22
+ const sel = this.st.selected?.[1]
23
+ return sel?.kind === 'choice' ? (sel as ChoiceVar<string>) : null
24
+ }
25
+
26
+ private get sizeVar(): SizeVar | null {
27
+ const sel = this.st.selected?.[1]
28
+ return sel?.kind === 'size' ? (sel as SizeVar) : null
29
+ }
30
+
31
+ get options(): string[] {
32
+ const cv = this.choiceVar
33
+ if (cv != null) {
34
+ if (this.filter === '') return [...cv.choices]
35
+ return cv.choices.filter((c) => fuzzyMatch(this.filter, c))
36
+ }
37
+ const sv = this.sizeVar
38
+ if (sv != null) {
39
+ const labels = sv.presets.map((p) => `${p.width}×${p.height} ${p.label}`)
40
+ if (this.filter === '') return labels
41
+ return labels.filter((l) => fuzzyMatch(this.filter, l))
42
+ }
43
+ return []
44
+ }
45
+
46
+ beginChoice(): void {
47
+ const cv = this.choiceVar
48
+ if (cv == null) return
49
+ this.st.mode = 'overlay-choice'
50
+ this.filter = ''
51
+ this.invalid = false
52
+ this.ix = Math.max(0, cv.choices.indexOf(cv.value))
53
+ }
54
+
55
+ beginSize(): void {
56
+ const sv = this.sizeVar
57
+ if (sv == null) return
58
+ this.st.mode = 'overlay-size'
59
+ this.filter = ''
60
+ this.invalid = false
61
+ const ix = sv.presets.findIndex((p) => p.width === sv.value.width && p.height === sv.value.height)
62
+ this.ix = ix === -1 ? 0 : ix
63
+ }
64
+
65
+ move(delta: number): void {
66
+ const len = this.options.length
67
+ if (len === 0) return
68
+ this.ix = (this.ix + delta + len) % len
69
+ }
70
+
71
+ filterInput(chunk: string): void {
72
+ this.filter += chunk
73
+ this.ix = 0
74
+ this.invalid = false
75
+ }
76
+
77
+ filterBackspace(): void {
78
+ this.filter = this.filter.slice(0, -1)
79
+ this.ix = 0
80
+ this.invalid = false
81
+ }
82
+
83
+ /** ⌥⌫ / ⌃W: drop the last word of the filter */
84
+ filterDeleteWord(): void {
85
+ this.filter = this.filter.replace(/\s*\S+\s*$/, '')
86
+ this.ix = 0
87
+ this.invalid = false
88
+ }
89
+
90
+ commit(): void {
91
+ const cv = this.choiceVar
92
+ if (cv != null) {
93
+ const hit = this.options[this.ix]
94
+ if (hit == null) return
95
+ cv.set(hit)
96
+ this.st.mode = 'nav'
97
+ return
98
+ }
99
+ const sv = this.sizeVar
100
+ if (sv == null) return
101
+ const hit = this.options[this.ix]
102
+ if (hit != null) {
103
+ const m = hit.match(/^(\d+)×(\d+)/)
104
+ if (m != null) sv.set({ width: Number(m[1]), height: Number(m[2]) })
105
+ this.st.mode = 'nav'
106
+ return
107
+ }
108
+ // no preset survives the filter: the filter IS the custom `WxH` entry
109
+ if (sv.parse(this.filter)) this.st.mode = 'nav'
110
+ else this.invalid = true
111
+ }
112
+ }
@@ -0,0 +1,288 @@
1
+ import { makeAutoObservable, runInAction } from 'mobx'
2
+ import sharp from 'sharp'
3
+ import { imageMeta } from 'image-meta'
4
+ import { imageBufferToAnsi } from 'src/utils/ansiImage.ts'
5
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
6
+ import type { PreviewDuringRun, PreviewRenderer } from 'src/cli/tui/state/SettingsSt.ts'
7
+ import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
8
+
9
+ /** OSC 1337 support: the panel can show REAL images instead of half-blocks */
10
+ export function protocolCapable(): boolean {
11
+ if (process.env.COMFY_TS_NO_ITERM_IMAGES === '1') return false
12
+ const term = process.env.TERM_PROGRAM ?? ''
13
+ return term === 'iTerm.app' || term === 'WezTerm' || term === 'vscode' || process.env.LC_TERMINAL === 'iTerm2'
14
+ }
15
+
16
+ type MenuRow = { key: 'panel' | 'renderer' | 'during-run'; label: string; value: string }
17
+
18
+ /** small-latent corner: fraction of the panel each dimension takes */
19
+ const CORNER_FRACTION = 0.38
20
+ /** pixel 'latent small': the sharp-composited thumb takes this fraction of the panel */
21
+ const PIXEL_SMALL_FRACTION = 0.4
22
+
23
+ /**
24
+ * right-side preview panel + its `p` settings menu (mode 'preview').
25
+ * Three independent axes live in SettingsSt: panel on/off, renderer
26
+ * native/pixel, and what to show while running (latent / latent small /
27
+ * last output). Sources: live latent while running, last output after,
28
+ * selected lora while the loras overlay is open.
29
+ */
30
+ export class PreviewSt {
31
+ constructor(private st: TuiSt) {
32
+ makeAutoObservable<PreviewSt, 'st'>(this, { st: false })
33
+ }
34
+
35
+ /** ansi half-block render of the last output image */
36
+ outputAnsi: string | null = null
37
+ /** live latent preview during a run (binary ws frames) */
38
+ latentAnsi: string | null = null
39
+ /** native mode: pre-shrunk output bytes / raw latent jpeg for the painter */
40
+ outputBytes: Uint8Array | null = null
41
+ latentBytes: Uint8Array | null = null
42
+ /** the latent's pixel dimensions (image-meta) — sizes the native corner box */
43
+ latentDims: { width: number; height: number } | null = null
44
+ /** at least one latent frame arrived this run — false + progress = server sends none */
45
+ latentSeenThisRun: boolean = false
46
+ /** last output path, so a settings change can re-render it */
47
+ private lastOutputPath: string | null = null
48
+
49
+ get show(): boolean {
50
+ return this.st.settings.previewPanel
51
+ }
52
+ get renderer(): PreviewRenderer {
53
+ return this.st.settings.previewRenderer
54
+ }
55
+ get useNative(): boolean {
56
+ return this.renderer === 'native'
57
+ }
58
+ get duringRun(): PreviewDuringRun {
59
+ return this.st.settings.previewDuringRun
60
+ }
61
+ get menuOpen(): boolean {
62
+ return this.st.mode === 'preview'
63
+ }
64
+ /** running + latents wanted + sampling well underway + none arrived = server
65
+ * sends none. The ≥20% gate keeps healthy runs from red-flashing: the first
66
+ * progress tick lands a beat before the first preview frame */
67
+ get latentsMissing(): boolean {
68
+ return (
69
+ this.st.exec.running &&
70
+ this.duringRun !== 'last-output' &&
71
+ (this.st.exec.progress?.percent ?? 0) >= 20 &&
72
+ !this.latentSeenThisRun
73
+ )
74
+ }
75
+
76
+ // ---- `p` settings menu (rendered by PreviewPanel while mode === 'preview') ----
77
+ menuIx: number = 0
78
+
79
+ get menuRows(): MenuRow[] {
80
+ return [
81
+ { key: 'panel', label: 'panel', value: this.show ? 'on' : 'off' },
82
+ {
83
+ key: 'renderer',
84
+ label: 'renderer',
85
+ value: this.renderer + (protocolCapable() ? '' : ' (no protocol support)'),
86
+ },
87
+ {
88
+ key: 'during-run',
89
+ label: 'while running',
90
+ value:
91
+ this.duringRun === 'latent'
92
+ ? 'latent'
93
+ : this.duringRun === 'latent-small'
94
+ ? 'latent small'
95
+ : 'last output',
96
+ },
97
+ ]
98
+ }
99
+
100
+ beginMenu(): void {
101
+ this.st.mode = 'preview'
102
+ this.menuIx = 0
103
+ }
104
+
105
+ blurMenu(): void {
106
+ this.st.mode = 'nav'
107
+ }
108
+
109
+ menuMove(delta: number): void {
110
+ const len = this.menuRows.length
111
+ this.menuIx = (this.menuIx + delta + len) % len
112
+ }
113
+
114
+ /** cycle the selected row's value (settings persist via SettingsSt reaction) */
115
+ menuCycle(delta: number): void {
116
+ const row = this.menuRows[this.menuIx]
117
+ if (row == null) return
118
+ const s = this.st.settings
119
+ if (row.key === 'panel') {
120
+ s.previewPanel = !s.previewPanel
121
+ } else if (row.key === 'renderer') {
122
+ // no protocol support → native is unreachable, pixel is the only value
123
+ if (protocolCapable()) s.previewRenderer = s.previewRenderer === 'native' ? 'pixel' : 'native'
124
+ } else {
125
+ const order: PreviewDuringRun[] = ['latent', 'latent-small', 'last-output']
126
+ const ix = (order.indexOf(s.previewDuringRun) + delta + order.length) % order.length
127
+ s.previewDuringRun = order[ix] ?? 'latent'
128
+ }
129
+ this.onSettingsChanged()
130
+ }
131
+
132
+ reset(): void {
133
+ this.outputAnsi = null
134
+ this.latentAnsi = null
135
+ this.outputBytes = null
136
+ this.latentBytes = null
137
+ this.latentDims = null
138
+ this.latentSeenThisRun = false
139
+ this.lastOutputPath = null
140
+ }
141
+
142
+ /** run boundary: drop the latents so the next run never shows the previous one's */
143
+ clearLatent(): void {
144
+ this.latentAnsi = null
145
+ this.latentBytes = null
146
+ this.latentDims = null
147
+ this.latentSeenThisRun = false
148
+ }
149
+
150
+ /** re-render the last output for the newly chosen settings */
151
+ onSettingsChanged(): void {
152
+ this.outputAnsi = null
153
+ this.outputBytes = null
154
+ if (this.show && this.lastOutputPath != null) void this.renderOutput(this.lastOutputPath)
155
+ }
156
+
157
+ /** what the painter should show RIGHT NOW (native renderer only; mirrors the panel's source) */
158
+ get protocolImage(): Uint8Array | null {
159
+ if (!this.useNative || !this.show || this.menuOpen) return null
160
+ if (this.st.mode === 'overlay-loras') return this.st.loras.previewBytes
161
+ if (this.st.exec.running) {
162
+ if (this.duringRun === 'latent') return this.latentBytes ?? this.outputBytes
163
+ // latent-small keeps the OUTPUT big (corner carries the latent) — last-output too
164
+ return this.outputBytes
165
+ }
166
+ return this.outputBytes
167
+ }
168
+
169
+ /** small latent painted over the panel's top-right corner (native + 'latent small' only) */
170
+ get protocolImageCorner(): Uint8Array | null {
171
+ if (!this.useNative || !this.show || this.menuOpen) return null
172
+ if (this.st.mode === 'overlay-loras') return null
173
+ if (this.st.exec.running && this.duringRun === 'latent-small') return this.latentBytes
174
+ return null
175
+ }
176
+
177
+ /** corner cell box matched to the latent's REAL aspect (a mismatched box
178
+ * letterboxes in iTerm — his repro: "some vertical rectangle"). Cells are
179
+ * ~1:2 (w:h), hence the ×2 when converting image aspect to cells. */
180
+ get cornerBox(): { w: number; h: number } {
181
+ let w = Math.max(8, Math.floor(this.width * CORNER_FRACTION))
182
+ const maxH = Math.max(4, Math.floor(this.height * CORNER_FRACTION))
183
+ const dims = this.latentDims
184
+ if (dims == null || dims.width === 0 || dims.height === 0) return { w, h: maxH }
185
+ const aspect = dims.width / dims.height
186
+ let h = Math.max(2, Math.round(w / aspect / 2))
187
+ if (h > maxH) {
188
+ h = maxH
189
+ w = Math.max(4, Math.round(h * aspect * 2))
190
+ }
191
+ return { w, h }
192
+ }
193
+
194
+ get width(): number {
195
+ // leave ~64 cols to the vars panel (plus the tree), keep the image between 24 and 80 cells
196
+ return Math.max(24, Math.min(80, this.st.termCols - 68 - this.st.treeWidth))
197
+ }
198
+
199
+ get height(): number {
200
+ // budget: header 3 + borders 2 + progress 1 + outputs box ~3 + keybar 2
201
+ return Math.max(10, this.st.termRows - 12)
202
+ }
203
+
204
+ async renderOutput(path: string): Promise<void> {
205
+ this.lastOutputPath = path
206
+ if (!this.show) return
207
+ try {
208
+ if (this.useNative) {
209
+ // pre-shrink ONCE: the painter re-uploads on every repaint, so ~100KB beats ~2MB
210
+ const shrunk = await sharp(path)
211
+ .resize(896, 896, { fit: 'inside', withoutEnlargement: true })
212
+ .png()
213
+ .toBuffer()
214
+ runInAction(() => {
215
+ this.outputBytes = new Uint8Array(shrunk)
216
+ })
217
+ return
218
+ }
219
+ const rendered = await imageBufferToAnsi(path, { width: this.width, height: this.height })
220
+ runInAction(() => {
221
+ this.outputAnsi = rendered
222
+ })
223
+ } catch (e) {
224
+ // preview failure must be VISIBLE (outputs list still shows the paths)
225
+ runInAction(() => {
226
+ this.st.exec.notice = `preview: ${extractErrorMessage(e)}`
227
+ })
228
+ }
229
+ }
230
+
231
+ /** skip-while-busy: latent frames arrive faster than sharp renders them */
232
+ private _busy: boolean = false
233
+ async renderLatent(bytes: Uint8Array): Promise<void> {
234
+ runInAction(() => {
235
+ this.latentSeenThisRun = true
236
+ })
237
+ if (!this.show || this.duringRun === 'last-output') return
238
+ if (this.useNative) {
239
+ // server jpegs pass through untouched — the terminal scales them;
240
+ // dims feed cornerBox so the corner rect matches the image aspect
241
+ const meta = imageMeta(bytes)
242
+ this.latentBytes = bytes
243
+ this.latentDims = meta.width != null && meta.height != null ? { width: meta.width, height: meta.height } : null
244
+ return
245
+ }
246
+ if (this._busy) return
247
+ this._busy = true
248
+ try {
249
+ const ansi =
250
+ this.duringRun === 'latent-small'
251
+ ? await this.renderLatentSmallPixel(bytes)
252
+ : await imageBufferToAnsi(bytes, { width: this.width, height: this.height })
253
+ runInAction(() => {
254
+ this.latentAnsi = ansi
255
+ })
256
+ } catch (e) {
257
+ runInAction(() => {
258
+ this.st.exec.notice = `latent preview: ${extractErrorMessage(e)}`
259
+ })
260
+ } finally {
261
+ this._busy = false
262
+ }
263
+ }
264
+
265
+ /** pixel 'latent small': sharp-composite the latent thumb onto the last
266
+ * output (top-right), then ONE half-block render — a string-level overlay
267
+ * was tried and dropped: its space padding reads as black bars */
268
+ private async renderLatentSmallPixel(bytes: Uint8Array): Promise<string> {
269
+ const pxW = this.width
270
+ const pxH = this.height * 2
271
+ const thumb = await sharp(bytes)
272
+ .resize(
273
+ Math.max(8, Math.floor(pxW * PIXEL_SMALL_FRACTION)),
274
+ Math.max(8, Math.floor(pxH * PIXEL_SMALL_FRACTION)),
275
+ { fit: 'inside' },
276
+ )
277
+ .png()
278
+ .toBuffer()
279
+ const outPath = this.lastOutputPath
280
+ if (outPath == null) return imageBufferToAnsi(thumb, { width: this.width, height: this.height })
281
+ const base = await sharp(outPath).resize(pxW, pxH, { fit: 'inside' }).png().toBuffer()
282
+ const composed = await sharp(base)
283
+ .composite([{ input: thumb, gravity: 'northeast' }])
284
+ .png()
285
+ .toBuffer()
286
+ return imageBufferToAnsi(composed, { width: this.width, height: this.height })
287
+ }
288
+ }
@@ -0,0 +1,59 @@
1
+ import { makeAutoObservable, runInAction } from 'mobx'
2
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
3
+ import type { ComfyHost } from 'src/host/ComfyHost.ts'
4
+ import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
5
+
6
+ /** live server queue length (ws 'status' messages) + queue actions */
7
+ export class QueueSt {
8
+ constructor(private st: TuiSt) {
9
+ makeAutoObservable<QueueSt, 'st'>(this, { st: false })
10
+ this.attach(this.st.wf.host)
11
+ this.st.disposers.push(() => {
12
+ if (this.attached != null) this.attached.onStatus = null
13
+ })
14
+ }
15
+
16
+ /** prompts waiting on the server (excludes the one running) */
17
+ remaining: number = 0
18
+
19
+ private attached: ComfyHost | null = null
20
+
21
+ /** follow the CURRENT workflow's host (re-called on workflow switch) */
22
+ attach(host: ComfyHost): void {
23
+ if (this.attached === host) return
24
+ if (this.attached != null) this.attached.onStatus = null
25
+ this.attached = host
26
+ this.remaining = 0
27
+ host.onStatus = (p) => {
28
+ runInAction(() => {
29
+ this.remaining = p.queueRemaining
30
+ })
31
+ }
32
+ }
33
+
34
+ async clearPending(): Promise<void> {
35
+ try {
36
+ await this.st.wf.host.clearQueue()
37
+ runInAction(() => {
38
+ this.st.exec.notice = 'pending queue cleared'
39
+ })
40
+ } catch (e) {
41
+ runInAction(() => {
42
+ this.st.exec.error = extractErrorMessage(e)
43
+ })
44
+ }
45
+ }
46
+
47
+ async interrupt(): Promise<void> {
48
+ try {
49
+ await this.st.wf.host.interrupt()
50
+ runInAction(() => {
51
+ this.st.exec.notice = 'interrupt requested'
52
+ })
53
+ } catch (e) {
54
+ runInAction(() => {
55
+ this.st.exec.error = extractErrorMessage(e)
56
+ })
57
+ }
58
+ }
59
+ }
@@ -0,0 +1,100 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { makeAutoObservable, reaction, runInAction } from 'mobx'
3
+ import { dirname } from 'pathe'
4
+ import { protocolCapable } from 'src/cli/tui/state/PreviewSt.ts'
5
+ import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
6
+
7
+ export type PreviewRenderer = 'native' | 'pixel'
8
+ export type PreviewDuringRun = 'latent' | 'latent-small' | 'last-output'
9
+
10
+ export type PreviewSettings = {
11
+ previewPanel: boolean
12
+ previewRenderer: PreviewRenderer
13
+ previewDuringRun: PreviewDuringRun
14
+ }
15
+
16
+ /** read stored preview settings, migrating the legacy single `previewMode`
17
+ * (native|ansi|off) into the three independent axes */
18
+ export function migratePreviewSettings(raw: Record<string, unknown>, defaults: PreviewSettings): PreviewSettings {
19
+ const out = { ...defaults }
20
+ const legacy = raw.previewMode
21
+ if (legacy === 'native') out.previewRenderer = 'native'
22
+ if (legacy === 'ansi') out.previewRenderer = 'pixel'
23
+ if (legacy === 'off') out.previewPanel = false
24
+ if (typeof raw.previewPanel === 'boolean') out.previewPanel = raw.previewPanel
25
+ if (raw.previewRenderer === 'native' || raw.previewRenderer === 'pixel') out.previewRenderer = raw.previewRenderer
26
+ if (
27
+ raw.previewDuringRun === 'latent' ||
28
+ raw.previewDuringRun === 'latent-small' ||
29
+ raw.previewDuringRun === 'last-output'
30
+ )
31
+ out.previewDuringRun = raw.previewDuringRun
32
+ return out
33
+ }
34
+
35
+ /** persisted TUI settings at `.comfy-ts/settings.json` (LOCAL state, gitignored) */
36
+ export class SettingsSt {
37
+ constructor(private st: TuiSt) {
38
+ this.load()
39
+ // a non-protocol terminal can't do native — fall the stored setting back to pixel
40
+ if (this.previewRenderer === 'native' && !protocolCapable()) this.previewRenderer = 'pixel'
41
+ makeAutoObservable<SettingsSt, 'st'>(this, { st: false })
42
+ this.st.disposers.push(
43
+ reaction(
44
+ () =>
45
+ JSON.stringify({
46
+ previewPanel: this.previewPanel,
47
+ previewRenderer: this.previewRenderer,
48
+ previewDuringRun: this.previewDuringRun,
49
+ lastDraft: this.lastDraft,
50
+ }),
51
+ (json) => this.write(json),
52
+ { delay: 300 },
53
+ ),
54
+ )
55
+ }
56
+
57
+ previewPanel: boolean = true
58
+ previewRenderer: PreviewRenderer = protocolCapable() ? 'native' : 'pixel'
59
+ previewDuringRun: PreviewDuringRun = 'latent'
60
+ /** module basename → the draft that was active last time (reopened on load) */
61
+ lastDraft: Record<string, string> = {}
62
+
63
+ rememberDraft(moduleKey: string, draft: string): void {
64
+ this.lastDraft[moduleKey] = draft
65
+ }
66
+
67
+ private load(): void {
68
+ const path = comfyts.settingsPath
69
+ if (!existsSync(path)) return
70
+ try {
71
+ const raw: unknown = JSON.parse(readFileSync(path, 'utf8'))
72
+ if (raw == null || typeof raw !== 'object') return
73
+ const o = raw as Record<string, unknown>
74
+ const preview = migratePreviewSettings(o, {
75
+ previewPanel: this.previewPanel,
76
+ previewRenderer: this.previewRenderer,
77
+ previewDuringRun: this.previewDuringRun,
78
+ })
79
+ this.previewPanel = preview.previewPanel
80
+ this.previewRenderer = preview.previewRenderer
81
+ this.previewDuringRun = preview.previewDuringRun
82
+ if (o.lastDraft != null && typeof o.lastDraft === 'object')
83
+ this.lastDraft = { ...(o.lastDraft as Record<string, string>) }
84
+ } catch {
85
+ // corrupt settings must never block the TUI — start from defaults
86
+ }
87
+ }
88
+
89
+ private write(json: string): void {
90
+ const path = comfyts.settingsPath
91
+ try {
92
+ mkdirSync(dirname(path), { recursive: true })
93
+ writeFileSync(path, json)
94
+ } catch (e) {
95
+ runInAction(() => {
96
+ this.st.exec.notice = `settings save failed: ${String(e)}`
97
+ })
98
+ }
99
+ }
100
+ }
@@ -0,0 +1,122 @@
1
+ import { makeAutoObservable } from 'mobx'
2
+ import { draftKeyForFile, listDraftsForFile } from 'src/cli/tui/state/DraftsSt.ts'
3
+ import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
4
+
5
+ export type TreeRow =
6
+ | { kind: 'workflow'; file: string; name: string; expanded: boolean; current: boolean; hasDrafts: boolean }
7
+ | { kind: 'draft'; file: string; draft: string; active: boolean }
8
+
9
+ /** the left `(t)ree`: workflows with their drafts nested under them */
10
+ export class TreeSt {
11
+ constructor(private st: TuiSt) {
12
+ makeAutoObservable<TreeSt, 'st'>(this, { st: false })
13
+ }
14
+
15
+ ix: number = 0
16
+ expandedFiles: Set<string> = new Set()
17
+
18
+ get rows(): TreeRow[] {
19
+ void this.st.drafts.version // fs-derived: recompute when drafts change
20
+ const w = this.st.workflows
21
+ const rows: TreeRow[] = []
22
+ for (const file of w.files) {
23
+ const current = file === w.currentPath
24
+ const expanded = this.expandedFiles.has(file)
25
+ const drafts = listDraftsForFile(file)
26
+ rows.push({
27
+ kind: 'workflow',
28
+ file,
29
+ name: draftKeyForFile(file),
30
+ expanded,
31
+ current,
32
+ hasDrafts: drafts.length > 0,
33
+ })
34
+ if (!expanded) continue
35
+ for (const draft of drafts) {
36
+ rows.push({ kind: 'draft', file, draft, active: current && draft === this.st.drafts.active })
37
+ }
38
+ }
39
+ return rows
40
+ }
41
+
42
+ get selected(): TreeRow | undefined {
43
+ return this.rows[this.ix]
44
+ }
45
+
46
+ /** 't' / ←: focus the tree ON THE ACTIVE DRAFT (where you actually are), workflow row as fallback */
47
+ focus(): void {
48
+ const w = this.st.workflows
49
+ if (w.files.length === 0) {
50
+ this.st.exec.notice = 'no workflow tree — start the tui in a folder containing **/*.cflow.ts'
51
+ return
52
+ }
53
+ if (w.currentPath != null) this.expandedFiles.add(w.currentPath)
54
+ this.st.mode = 'tree'
55
+ const rows = this.rows
56
+ const draftIx = rows.findIndex((r) => r.kind === 'draft' && r.active)
57
+ const ix = draftIx === -1 ? rows.findIndex((r) => r.kind === 'workflow' && r.current) : draftIx
58
+ this.ix = ix === -1 ? 0 : ix
59
+ }
60
+
61
+ /** esc/t inside the tree, → on a draft row, `v` anywhere: back to the vars list */
62
+ blur(): void {
63
+ this.st.mode = 'nav'
64
+ }
65
+
66
+ move(delta: number): void {
67
+ const len = this.rows.length
68
+ if (len === 0) return
69
+ this.ix = (this.ix + delta + len) % len
70
+ }
71
+
72
+ /** →: unfold the workflow under the cursor; on a draft row there is nothing
73
+ * left to unfold, so → continues rightwards into the vars panel */
74
+ unfold(): void {
75
+ const row = this.selected
76
+ if (row == null) return
77
+ if (row.kind === 'workflow') this.expandedFiles.add(row.file)
78
+ else this.blur()
79
+ }
80
+
81
+ /** ←: fold the workflow under the cursor; on a draft row, jump to (and fold) its parent */
82
+ fold(): void {
83
+ const row = this.selected
84
+ if (row == null) return
85
+ this.expandedFiles.delete(row.file)
86
+ if (row.kind === 'draft') {
87
+ const ix = this.rows.findIndex((r) => r.kind === 'workflow' && r.file === row.file)
88
+ if (ix !== -1) this.ix = ix
89
+ }
90
+ }
91
+
92
+ /** ⏎: load the workflow (into 'default'), or the exact draft under the cursor */
93
+ async commit(): Promise<void> {
94
+ const row = this.selected
95
+ if (row == null) return
96
+ if (row.kind === 'workflow') return this.st.workflows.commit(row.file)
97
+ return this.st.workflows.commit(row.file, row.draft)
98
+ }
99
+
100
+ /** n: new draft — current workflow only (a draft snapshots its LIVE var values) */
101
+ promptNewDraft(): void {
102
+ const row = this.selected
103
+ if (row != null && row.file !== this.st.workflows.currentPath) {
104
+ this.st.exec.notice = 'load that workflow first (⏎) — a new draft snapshots its live vars'
105
+ return
106
+ }
107
+ this.st.drafts.promptNew('tree')
108
+ }
109
+
110
+ /** f2/c/x on a draft row: rename / duplicate / delete (file ops, work on ANY workflow's drafts) */
111
+ draftOp(op: 'rename' | 'duplicate' | 'delete'): void {
112
+ const row = this.selected
113
+ if (row?.kind !== 'draft') {
114
+ this.st.exec.notice = 'select a draft row (unfold a workflow with →)'
115
+ return
116
+ }
117
+ if (op === 'rename') return this.st.drafts.promptRename(row.draft, row.file, 'tree')
118
+ if (op === 'duplicate') return this.st.drafts.promptDuplicate(row.draft, row.file, 'tree')
119
+ this.st.drafts.deleteDraft(row.draft, row.file)
120
+ this.ix = Math.min(this.ix, Math.max(0, this.rows.length - 1))
121
+ }
122
+ }