comfy-ts 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +363 -0
  3. package/dist/cli.js +764 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/index.cjs +4128 -0
  6. package/dist/index.cjs.map +1 -0
  7. package/dist/index.d.cts +9862 -0
  8. package/dist/index.d.ts +9846 -58
  9. package/dist/index.js +4049 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/log-CdfgILde.js +10 -0
  12. package/dist/log-CdfgILde.js.map +1 -0
  13. package/dist/run-tui-Io8Xea0L.js +3340 -0
  14. package/dist/run-tui-Io8Xea0L.js.map +1 -0
  15. package/package.json +104 -75
  16. package/src/cli/comfy-ts-cli.ts +36 -0
  17. package/src/cli/gen.ts +47 -0
  18. package/src/cli/outline.ts +82 -0
  19. package/src/cli/tui/components/DraftsOverlay.tsx +44 -0
  20. package/src/cli/tui/components/EditField.tsx +27 -0
  21. package/src/cli/tui/components/Header.tsx +51 -0
  22. package/src/cli/tui/components/HostPanel.tsx +37 -0
  23. package/src/cli/tui/components/LorasOverlay.tsx +49 -0
  24. package/src/cli/tui/components/OverlayList.tsx +25 -0
  25. package/src/cli/tui/components/PickerOverlays.tsx +66 -0
  26. package/src/cli/tui/components/PreviewPanel.tsx +33 -0
  27. package/src/cli/tui/components/PromptOverlay.tsx +16 -0
  28. package/src/cli/tui/components/StatusBar.tsx +165 -0
  29. package/src/cli/tui/components/TextOverlay.tsx +72 -0
  30. package/src/cli/tui/components/TreePanel.tsx +51 -0
  31. package/src/cli/tui/components/TuiApp.tsx +223 -0
  32. package/src/cli/tui/components/VarsPanel.tsx +86 -0
  33. package/src/cli/tui/findDefinedWorkflow.ts +16 -0
  34. package/src/cli/tui/keys.ts +20 -0
  35. package/src/cli/tui/protocolImagePainter.ts +59 -0
  36. package/src/cli/tui/run-tui.tsx +73 -0
  37. package/src/cli/tui/state/DraftsSt.ts +273 -0
  38. package/src/cli/tui/state/EditorSt.ts +289 -0
  39. package/src/cli/tui/state/ExecSt.ts +170 -0
  40. package/src/cli/tui/state/HostSt.ts +107 -0
  41. package/src/cli/tui/state/LorasSt.ts +185 -0
  42. package/src/cli/tui/state/PickerSt.ts +112 -0
  43. package/src/cli/tui/state/PreviewSt.ts +138 -0
  44. package/src/cli/tui/state/QueueSt.ts +59 -0
  45. package/src/cli/tui/state/SettingsSt.ts +73 -0
  46. package/src/cli/tui/state/TreeSt.ts +122 -0
  47. package/src/cli/tui/state/TuiSt.ts +169 -0
  48. package/src/cli/tui/state/WorkflowsSt.ts +92 -0
  49. package/src/cli/tui-env.ts +8 -0
  50. package/src/errors/InvalidPromptError.ts +12 -0
  51. package/src/graph/ComfyNode.ts +403 -0
  52. package/src/graph/ComfyNodeID.ts +28 -0
  53. package/src/graph/ComfyNodeOutput.ts +16 -0
  54. package/src/graph/NodeSlotSize.ts +4 -0
  55. package/src/graph/autoValue.ts +17 -0
  56. package/src/host/ComfyHost.ts +646 -0
  57. package/src/host/ComfyInstallType.ts +15 -0
  58. package/src/host/ComfyManager.ts +232 -0
  59. package/src/host/ComfyUploader.ts +110 -0
  60. package/src/host/ComfyWorkflowBuilder.ts +60 -0
  61. package/src/host/Requirements.ts +55 -0
  62. package/src/host/ResilientWebsocket.ts +147 -0
  63. package/src/host/loraManagerApi.ts +98 -0
  64. package/src/image-utils/_getPngMetadata.ts +53 -0
  65. package/src/image-utils/_getWebpMetadata.ts +38 -0
  66. package/src/image-utils/_parseExifData.ts +53 -0
  67. package/src/index.ts +89 -0
  68. package/src/litegraph/LiteGraphGroup.ts +22 -0
  69. package/src/litegraph/LiteGraphJSON.ts +46 -0
  70. package/src/litegraph/LiteGraphLink.ts +23 -0
  71. package/src/litegraph/LiteGraphLinkID.ts +6 -0
  72. package/src/litegraph/LiteGraphNode.ts +69 -0
  73. package/src/litegraph/LiteGraphNodeInput.ts +27 -0
  74. package/src/litegraph/LiteGraphNodeOutput.ts +23 -0
  75. package/src/litegraph/LiteGraphSlotIndex.ts +6 -0
  76. package/src/litegraph/convertFlowToLiteGraphJSON.ts +114 -0
  77. package/src/manager/ComfyRegistry.ts +124 -0
  78. package/src/manager/generated/KnownComfyCustomNodeName.ts +19280 -0
  79. package/src/manager/generated/KnownComfyPluginTitle.ts +5130 -0
  80. package/src/manager/generated/KnownComfyPluginURL.ts +2589 -0
  81. package/src/manager/generated/KnownModel_Base.ts +126 -0
  82. package/src/manager/generated/KnownModel_FileName.ts +2287 -0
  83. package/src/manager/generated/KnownModel_Name.ts +2287 -0
  84. package/src/manager/generated/KnownModel_SavePath.ts +263 -0
  85. package/src/manager/generated/KnownModel_Type.ts +97 -0
  86. package/src/manager/json/alter-list.json +224 -0
  87. package/src/manager/json/custom-node-list.extra.ts +13 -0
  88. package/src/manager/json/custom-node-list.json +21948 -0
  89. package/src/manager/json/extension-node-map.json +31282 -0
  90. package/src/manager/json/github-stats.json +12602 -0
  91. package/src/manager/json/model-list.extra.ts +26 -0
  92. package/src/manager/json/model-list.json +5052 -0
  93. package/src/manager/loaders/step1_downloadComfyManagerJSONs.ts +56 -0
  94. package/src/manager/loaders/step2_custom-node-list-loader.ts +149 -0
  95. package/src/manager/loaders/step3_extension-node-map-loader.ts +189 -0
  96. package/src/manager/loaders/step4_model-list-loader.ts +159 -0
  97. package/src/manager/script-update-manager.bun.ts +18 -0
  98. package/src/manager/types/ComfyManagerAPIFetchPolicy.ts +9 -0
  99. package/src/manager/types/ComfyManagerAPIModelList.ts +10 -0
  100. package/src/manager/types/ComfyManagerAPIPluginList.ts +11 -0
  101. package/src/manager/types/ComfyManagerFileModelInfo.ts +5 -0
  102. package/src/manager/types/ComfyManagerFilePluginContent.ts +13 -0
  103. package/src/manager/types/ComfyManagerFilePluginList.ts +5 -0
  104. package/src/manager/types/ComfyManagerModelInfo.ts +18 -0
  105. package/src/manager/types/ComfyManagerPluginContentMetadata.ts +16 -0
  106. package/src/manager/types/ComfyManagerPluginEnums.ts +8 -0
  107. package/src/manager/types/ComfyManagerPluginInfo.ts +50 -0
  108. package/src/runner/ComfyExecution.ts +301 -0
  109. package/src/runner/ComfyExecutionStatus.ts +2 -0
  110. package/src/runner/ComfyWorkflow.ts +395 -0
  111. package/src/runner/ComfyWorkflowLayout.ts +96 -0
  112. package/src/runner/ComfyWsApi.ts +159 -0
  113. package/src/runner/MediaImage.ts +262 -0
  114. package/src/sdk-generator/ComfyNodeSchema.ts +79 -0
  115. package/src/sdk-generator/ComfySchema.ts +369 -0
  116. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +95 -0
  117. package/src/sdk-generator/Primitives.ts +76 -0
  118. package/src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts +39 -0
  119. package/src/sdk-generator/_pythonModuleToNamespace.ts +27 -0
  120. package/src/sdk-generator/_toQualifiedNodeKey.ts +5 -0
  121. package/src/sdk-generator/comfy-api-json.ts +16 -0
  122. package/src/sdk-generator/comfyui-sdk-codegen.ts +287 -0
  123. package/src/sdk-generator/comfyui-types.ts +56 -0
  124. package/src/sdk-generator/litegraphToApiRequestPayload.ts +157 -0
  125. package/src/ssh-host-manager/ssh-config-manager.ts +89 -0
  126. package/src/ssh-host-manager/ssh-config.windows.md +32 -0
  127. package/src/ssh-host-manager/ssh-manager.ts +129 -0
  128. package/src/state.ts +136 -0
  129. package/src/types/comfy-sdk.ts +106 -0
  130. package/src/types/index.ts +55 -0
  131. package/src/utils/CodeBuffer.ts +61 -0
  132. package/src/utils/ComfyColors.ts +38 -0
  133. package/src/utils/ansi.ts +26 -0
  134. package/src/utils/ansiImage.ts +36 -0
  135. package/src/utils/bang.ts +39 -0
  136. package/src/utils/deepCopyNaive.ts +1 -0
  137. package/src/utils/downloadFile.ts +77 -0
  138. package/src/utils/escapeJSKey.ts +32 -0
  139. package/src/utils/exhaust.ts +4 -0
  140. package/src/utils/extractErrorMessage.ts +11 -0
  141. package/src/utils/fuzzyMatch.ts +8 -0
  142. package/src/utils/githubRegexes.ts +2 -0
  143. package/src/utils/hashArrayBuffer.ts +6 -0
  144. package/src/utils/log.ts +9 -0
  145. package/src/utils/loraTag.ts +10 -0
  146. package/src/utils/printArkResultInConsole.ts +16 -0
  147. package/src/utils/softValidate.ts +8 -0
  148. package/src/utils/stringifyReadable.ts +32 -0
  149. package/src/utils/toposort.ts +59 -0
  150. package/src/utils/tryExtracting.ts +41 -0
  151. package/src/utils/writeFile.ts +16 -0
  152. package/src/vars/ComfyVars.ts +531 -0
  153. package/src/vars/DefinedWorkflow.ts +112 -0
  154. package/src/vars/loraKeywords.ts +56 -0
  155. package/dist/index.d.mts +0 -74
  156. package/dist/index.mjs +0 -3
  157. package/dist/index.mjs.map +0 -1
  158. package/readme.md +0 -40
@@ -0,0 +1,185 @@
1
+ import { makeAutoObservable, reaction, runInAction } from 'mobx'
2
+ import { fetchLoraPreviewBytes, fetchLoraPreviewMap, loraPreviewKey } from 'src/host/loraManagerApi.ts'
3
+ import { imageBufferToAnsi } from 'src/utils/ansiImage.ts'
4
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
5
+ import { fuzzyMatch } from 'src/utils/fuzzyMatch.ts'
6
+ import { LorasVar } from 'src/vars/ComfyVars.ts'
7
+ import { getLoraKeyword, setLoraKeyword } from 'src/vars/loraKeywords.ts'
8
+ import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
9
+
10
+ /** loras overlay: fuzzy filter + tick/untick + strengths + bulk ops + lora-manager preview */
11
+ export class LorasSt {
12
+ constructor(private st: TuiSt) {
13
+ makeAutoObservable<LorasSt, 'st'>(this, { st: false })
14
+ // the selected lora's preview follows the cursor (debounced; renders into the preview panel)
15
+ this.st.disposers.push(
16
+ reaction(
17
+ () => (this.st.mode === 'overlay-loras' ? this.selectedName : null),
18
+ () => void this.refreshPreview(),
19
+ { delay: 120 },
20
+ ),
21
+ )
22
+ }
23
+
24
+ ix: number = 0
25
+ filter: string = ''
26
+
27
+ /** kind-narrowing cast sanctioned (agent/coding.md), `kind` is the tag */
28
+ get selectedVar(): LorasVar<string> | null {
29
+ const sel = this.st.selected?.[1]
30
+ return sel?.kind === 'loras' ? (sel as LorasVar<string>) : null
31
+ }
32
+
33
+ /** options surviving the fuzzy filter (bulk ops apply to exactly these) */
34
+ get filteredNames(): string[] {
35
+ const lv = this.selectedVar
36
+ if (lv == null) return []
37
+ if (this.filter === '') return lv.names
38
+ return lv.names.filter((n) => fuzzyMatch(this.filter, n))
39
+ }
40
+
41
+ begin(): void {
42
+ if (this.selectedVar == null) return
43
+ this.st.mode = 'overlay-loras'
44
+ this.ix = 0
45
+ this.filter = ''
46
+ }
47
+
48
+ move(delta: number): void {
49
+ const len = this.filteredNames.length
50
+ if (len === 0) return
51
+ this.ix = (this.ix + delta + len) % len
52
+ }
53
+
54
+ filterInput(chunk: string): void {
55
+ this.filter += chunk
56
+ this.ix = 0
57
+ }
58
+
59
+ filterBackspace(): void {
60
+ this.filter = this.filter.slice(0, -1)
61
+ this.ix = 0
62
+ }
63
+
64
+ /** ⌥⌫ / ⌃W: drop the last word of the filter */
65
+ filterDeleteWord(): void {
66
+ this.filter = this.filter.replace(/\s*\S+\s*$/, '')
67
+ this.ix = 0
68
+ }
69
+
70
+ toggle(): void {
71
+ const lv = this.selectedVar
72
+ const name = this.filteredNames[this.ix]
73
+ if (lv == null || name == null) return
74
+ lv.toggleItem(name)
75
+ }
76
+
77
+ /** ⌃A / ⌃N: tick / untick every lora surviving the filter */
78
+ setAll(on: boolean): void {
79
+ this.selectedVar?.setAll(on, this.filteredNames)
80
+ }
81
+
82
+ adjust(delta: number): void {
83
+ const lv = this.selectedVar
84
+ const name = this.filteredNames[this.ix]
85
+ if (lv == null || name == null) return
86
+ lv.adjustItem(name, delta)
87
+ }
88
+
89
+ /** ⌃K: assign the selected lora's trigger keyword (PromptVar prefixes actives with it) */
90
+ beginKeyword(): void {
91
+ const name = this.selectedName
92
+ if (name == null) return
93
+ this.st.editor.beginCustom({
94
+ title: `keyword for ${LorasVar.shortName(name)} (empty clears)`,
95
+ initial: getLoraKeyword(name),
96
+ onCommit: (raw) => {
97
+ setLoraKeyword(name, raw)
98
+ return true
99
+ },
100
+ returnMode: 'overlay-loras',
101
+ })
102
+ }
103
+
104
+ // ---- lora-manager previews (optional extension, quiet degrade) ----
105
+ get selectedName(): string | null {
106
+ return this.filteredNames[this.ix] ?? null
107
+ }
108
+
109
+ previewAnsi: string | null = null
110
+ /** protocol mode: raw preview bytes for the overlay painter */
111
+ previewBytes: Uint8Array | null = null
112
+ previewName: string | null = null
113
+ /** placeholder line when no image can be shown (missing extension, no preview, video preview…) */
114
+ previewNote: string | null = null
115
+
116
+ /** undefined = not fetched yet · null = extension absent */
117
+ private previewMap: Map<string, string> | null | undefined = undefined
118
+ private previewMapHostId: string | null = null
119
+ private _busy: boolean = false
120
+
121
+ async refreshPreview(): Promise<void> {
122
+ if (this.st.mode !== 'overlay-loras') {
123
+ runInAction(() => {
124
+ this.previewAnsi = null
125
+ this.previewBytes = null
126
+ this.previewName = null
127
+ this.previewNote = null
128
+ })
129
+ return
130
+ }
131
+ const name = this.selectedName
132
+ if (name == null || this._busy) return
133
+ this._busy = true
134
+ try {
135
+ const host = this.st.wf.host
136
+ if (this.previewMap === undefined || this.previewMapHostId !== host.data.id) {
137
+ this.previewMap = await fetchLoraPreviewMap(host)
138
+ this.previewMapHostId = host.data.id
139
+ }
140
+ const map = this.previewMap
141
+ const url = map?.get(loraPreviewKey(name))
142
+ const note = map == null ? 'lora-manager extension not detected' : url == null ? 'no preview available' : null
143
+ if (url == null) {
144
+ runInAction(() => {
145
+ this.previewAnsi = null
146
+ this.previewBytes = null
147
+ this.previewName = name
148
+ this.previewNote = note
149
+ })
150
+ return
151
+ }
152
+ const bytes = await fetchLoraPreviewBytes(host, url)
153
+ // null covers the SPA index.html fallback (non-image response) too
154
+ if (bytes == null) throw new Error('no image preview on the server')
155
+ if (this.st.preview.useNative) {
156
+ // the overlay painter shows the REAL image — no ansi rendering needed
157
+ runInAction(() => {
158
+ this.previewBytes = bytes
159
+ this.previewAnsi = null
160
+ this.previewName = name
161
+ this.previewNote = null
162
+ })
163
+ return
164
+ }
165
+ const ansi = await imageBufferToAnsi(bytes, { width: this.st.preview.width, height: this.st.preview.height })
166
+ runInAction(() => {
167
+ this.previewAnsi = ansi
168
+ this.previewName = name
169
+ this.previewNote = null
170
+ })
171
+ } catch (e) {
172
+ // e.g. video previews sharp can't decode — placeholder, not an incident
173
+ runInAction(() => {
174
+ this.previewAnsi = null
175
+ this.previewBytes = null
176
+ this.previewName = name
177
+ this.previewNote = extractErrorMessage(e)
178
+ })
179
+ } finally {
180
+ this._busy = false
181
+ // the cursor may have moved while we rendered: catch up once
182
+ if (this.st.mode === 'overlay-loras' && this.selectedName !== name) void this.refreshPreview()
183
+ }
184
+ }
185
+ }
@@ -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,138 @@
1
+ import { makeAutoObservable, runInAction } from 'mobx'
2
+ import sharp from 'sharp'
3
+ import { imageBufferToAnsi } from 'src/utils/ansiImage.ts'
4
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
5
+ import type { PreviewMode } from 'src/cli/tui/state/SettingsSt.ts'
6
+ import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
7
+
8
+ /** OSC 1337 support: the panel can show REAL images instead of half-blocks */
9
+ export function protocolCapable(): boolean {
10
+ if (process.env.COMFY_TS_NO_ITERM_IMAGES === '1') return false
11
+ const term = process.env.TERM_PROGRAM ?? ''
12
+ return term === 'iTerm.app' || term === 'WezTerm' || term === 'vscode' || process.env.LC_TERMINAL === 'iTerm2'
13
+ }
14
+
15
+ /**
16
+ * right-side preview panel. The MODE (native/ansi/off) lives in SettingsSt and
17
+ * is cycled with `p`. 'native' overlay-paints the REAL image over the panel rect
18
+ * (protocolImagePainter.ts); 'ansi' renders truecolor half-blocks; 'off' hides
19
+ * the panel. Sources: live latent while running, last output after, selected
20
+ * lora while the loras overlay is open.
21
+ */
22
+ export class PreviewSt {
23
+ constructor(private st: TuiSt) {
24
+ makeAutoObservable<PreviewSt, 'st'>(this, { st: false })
25
+ }
26
+
27
+ /** ansi half-block render of the last output image */
28
+ outputAnsi: string | null = null
29
+ /** live latent preview during a run (binary ws frames) */
30
+ latentAnsi: string | null = null
31
+ /** native mode: pre-shrunk output bytes / raw latent jpeg for the painter */
32
+ outputBytes: Uint8Array | null = null
33
+ latentBytes: Uint8Array | null = null
34
+ /** last output path, so a mode switch can re-render it */
35
+ private lastOutputPath: string | null = null
36
+
37
+ get mode(): PreviewMode {
38
+ return this.st.settings.previewMode
39
+ }
40
+ get show(): boolean {
41
+ return this.mode !== 'off'
42
+ }
43
+ /** SettingsSt already downgrades native → ansi on incapable terminals */
44
+ get useNative(): boolean {
45
+ return this.mode === 'native'
46
+ }
47
+
48
+ reset(): void {
49
+ this.outputAnsi = null
50
+ this.latentAnsi = null
51
+ this.outputBytes = null
52
+ this.latentBytes = null
53
+ this.lastOutputPath = null
54
+ }
55
+
56
+ /** run boundary: drop the latents so the next run never shows the previous one's */
57
+ clearLatent(): void {
58
+ this.latentAnsi = null
59
+ this.latentBytes = null
60
+ }
61
+
62
+ /** re-render the last output in the newly chosen mode */
63
+ onModeChanged(): void {
64
+ this.outputAnsi = null
65
+ this.outputBytes = null
66
+ if (this.mode !== 'off' && this.lastOutputPath != null) void this.renderOutput(this.lastOutputPath)
67
+ }
68
+
69
+ /** what the painter should show RIGHT NOW (native mode only; mirrors the panel's source) */
70
+ get protocolImage(): Uint8Array | null {
71
+ if (!this.useNative || !this.show) return null
72
+ if (this.st.mode === 'overlay-loras') return this.st.loras.previewBytes
73
+ if (this.st.exec.running && this.latentBytes != null) return this.latentBytes
74
+ return this.outputBytes
75
+ }
76
+
77
+ get width(): number {
78
+ // leave ~64 cols to the vars panel (plus the tree), keep the image between 24 and 80 cells
79
+ return Math.max(24, Math.min(80, this.st.termCols - 68 - this.st.treeWidth))
80
+ }
81
+
82
+ get height(): number {
83
+ // budget: header 3 + borders 2 + progress 1 + outputs box ~3 + keybar 2
84
+ return Math.max(10, this.st.termRows - 12)
85
+ }
86
+
87
+ async renderOutput(path: string): Promise<void> {
88
+ this.lastOutputPath = path
89
+ if (this.mode === 'off') return
90
+ try {
91
+ if (this.useNative) {
92
+ // pre-shrink ONCE: the painter re-uploads on every repaint, so ~100KB beats ~2MB
93
+ const shrunk = await sharp(path)
94
+ .resize(896, 896, { fit: 'inside', withoutEnlargement: true })
95
+ .png()
96
+ .toBuffer()
97
+ runInAction(() => {
98
+ this.outputBytes = new Uint8Array(shrunk)
99
+ })
100
+ return
101
+ }
102
+ const rendered = await imageBufferToAnsi(path, { width: this.width, height: this.height })
103
+ runInAction(() => {
104
+ this.outputAnsi = rendered
105
+ })
106
+ } catch (e) {
107
+ // preview failure must be VISIBLE (outputs list still shows the paths)
108
+ runInAction(() => {
109
+ this.st.exec.notice = `preview: ${extractErrorMessage(e)}`
110
+ })
111
+ }
112
+ }
113
+
114
+ /** skip-while-busy: latent frames arrive faster than sharp renders them */
115
+ private _busy: boolean = false
116
+ async renderLatent(bytes: Uint8Array): Promise<void> {
117
+ if (this.mode === 'off') return
118
+ if (this.useNative) {
119
+ // server jpegs pass through untouched — the terminal scales them
120
+ this.latentBytes = bytes
121
+ return
122
+ }
123
+ if (this._busy) return
124
+ this._busy = true
125
+ try {
126
+ const ansi = await imageBufferToAnsi(bytes, { width: this.width, height: this.height })
127
+ runInAction(() => {
128
+ this.latentAnsi = ansi
129
+ })
130
+ } catch (e) {
131
+ runInAction(() => {
132
+ this.st.exec.notice = `latent preview: ${extractErrorMessage(e)}`
133
+ })
134
+ } finally {
135
+ this._busy = false
136
+ }
137
+ }
138
+ }
@@ -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,73 @@
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 PreviewMode = 'native' | 'ansi' | 'off'
8
+
9
+ /** persisted TUI settings at `.comfy-ts/settings.json` (LOCAL state, gitignored) */
10
+ export class SettingsSt {
11
+ constructor(private st: TuiSt) {
12
+ this.load()
13
+ // a non-protocol terminal can't do native — fall the stored setting back to ansi
14
+ if (this.previewMode === 'native' && !protocolCapable()) this.previewMode = 'ansi'
15
+ makeAutoObservable<SettingsSt, 'st'>(this, { st: false })
16
+ this.st.disposers.push(
17
+ reaction(
18
+ () => JSON.stringify({ previewMode: this.previewMode, lastDraft: this.lastDraft }),
19
+ (json) => this.write(json),
20
+ { delay: 300 },
21
+ ),
22
+ )
23
+ }
24
+
25
+ previewMode: PreviewMode = protocolCapable() ? 'native' : 'ansi'
26
+ /** module basename → the draft that was active last time (reopened on load) */
27
+ lastDraft: Record<string, string> = {}
28
+
29
+ setPreviewMode(mode: PreviewMode): void {
30
+ this.previewMode = mode
31
+ this.st.preview.onModeChanged()
32
+ }
33
+
34
+ /** `p` cycles native → ansi → off (native skipped when the terminal can't do it) */
35
+ cyclePreviewMode(): void {
36
+ const order: PreviewMode[] = protocolCapable() ? ['native', 'ansi', 'off'] : ['ansi', 'off']
37
+ const next = order[(order.indexOf(this.previewMode) + 1) % order.length] ?? 'off'
38
+ this.setPreviewMode(next)
39
+ this.st.exec.notice = `preview: ${next}`
40
+ }
41
+
42
+ rememberDraft(moduleKey: string, draft: string): void {
43
+ this.lastDraft[moduleKey] = draft
44
+ }
45
+
46
+ private load(): void {
47
+ const path = comfyts.settingsPath
48
+ if (!existsSync(path)) return
49
+ try {
50
+ const raw: unknown = JSON.parse(readFileSync(path, 'utf8'))
51
+ if (raw == null || typeof raw !== 'object') return
52
+ const o = raw as { previewMode?: unknown; lastDraft?: unknown }
53
+ if (o.previewMode === 'native' || o.previewMode === 'ansi' || o.previewMode === 'off')
54
+ this.previewMode = o.previewMode
55
+ if (o.lastDraft != null && typeof o.lastDraft === 'object')
56
+ this.lastDraft = { ...(o.lastDraft as Record<string, string>) }
57
+ } catch {
58
+ // corrupt settings must never block the TUI — start from defaults
59
+ }
60
+ }
61
+
62
+ private write(json: string): void {
63
+ const path = comfyts.settingsPath
64
+ try {
65
+ mkdirSync(dirname(path), { recursive: true })
66
+ writeFileSync(path, json)
67
+ } catch (e) {
68
+ runInAction(() => {
69
+ this.st.exec.notice = `settings save failed: ${String(e)}`
70
+ })
71
+ }
72
+ }
73
+ }
@@ -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
+ }