comfy-ts 0.4.0 → 1.1.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/README.md +385 -255
  2. package/dist/DefinedWorkflow-BYyu5dK9.js +669 -0
  3. package/dist/DefinedWorkflow-BYyu5dK9.js.map +1 -0
  4. package/dist/cli.js +4106 -152
  5. package/dist/cli.js.map +1 -1
  6. package/dist/index.cjs +1560 -333
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +7826 -467
  9. package/dist/index.d.ts +7808 -449
  10. package/dist/index.js +1550 -333
  11. package/dist/index.js.map +1 -1
  12. package/dist/{run-tui-SDSJo1Qf.js → run-tui-DZ22HDHI.js} +631 -657
  13. package/dist/run-tui-DZ22HDHI.js.map +1 -0
  14. package/examples/01-txt2img.cflow.ts +50 -0
  15. package/examples/02-img2img-upload.cflow.ts +55 -0
  16. package/examples/03-export-workflow-json.cflow.ts +56 -0
  17. package/examples/04-krea2-turbo-t2i.cflow.ts +125 -0
  18. package/examples/05-comfy-cloud.cflow.ts +51 -0
  19. package/examples/README.md +30 -0
  20. package/examples/comfy-cloud/ace-step-t2a.cflow.ts +79 -0
  21. package/examples/comfy-cloud/anima-t2i.cflow.ts +57 -0
  22. package/examples/comfy-cloud/boogu-i2i.cflow.ts +76 -0
  23. package/examples/comfy-cloud/capybara-i2i.cflow.ts +85 -0
  24. package/examples/comfy-cloud/capybara-i2v.cflow.ts +90 -0
  25. package/examples/comfy-cloud/capybara-t2i.cflow.ts +67 -0
  26. package/examples/comfy-cloud/chatterbox-t2a.cflow.ts +79 -0
  27. package/examples/comfy-cloud/chroma-t2i.cflow.ts +62 -0
  28. package/examples/comfy-cloud/cloudHost.ts +41 -0
  29. package/examples/comfy-cloud/ernie-t2i.cflow.ts +59 -0
  30. package/examples/comfy-cloud/firered-i2i.cflow.ts +74 -0
  31. package/examples/comfy-cloud/flux1-i2i.cflow.ts +76 -0
  32. package/examples/comfy-cloud/flux1-t2i.cflow.ts +63 -0
  33. package/examples/comfy-cloud/flux2-i2i.cflow.ts +80 -0
  34. package/examples/comfy-cloud/flux2-t2i.cflow.ts +57 -0
  35. package/examples/comfy-cloud/hidream-i2i.cflow.ts +89 -0
  36. package/examples/comfy-cloud/hidream-t2i.cflow.ts +65 -0
  37. package/examples/comfy-cloud/hunyuan-video-i2v.cflow.ts +93 -0
  38. package/examples/comfy-cloud/hunyuan-video-t2v.cflow.ts +74 -0
  39. package/examples/comfy-cloud/ideogram4-t2i.cflow.ts +80 -0
  40. package/examples/comfy-cloud/kandinsky5-i2v.cflow.ts +95 -0
  41. package/examples/comfy-cloud/kandinsky5-t2i.cflow.ts +60 -0
  42. package/examples/comfy-cloud/kandinsky5-t2v.cflow.ts +78 -0
  43. package/examples/comfy-cloud/krea2-t2i.cflow.ts +59 -0
  44. package/examples/comfy-cloud/lens-t2i.cflow.ts +62 -0
  45. package/examples/comfy-cloud/longcat-i2i.cflow.ts +74 -0
  46. package/examples/comfy-cloud/longcat-t2i.cflow.ts +65 -0
  47. package/examples/comfy-cloud/ltxv-i2v.cflow.ts +92 -0
  48. package/examples/comfy-cloud/ltxv-t2v.cflow.ts +78 -0
  49. package/examples/comfy-cloud/newbie-t2i.cflow.ts +67 -0
  50. package/examples/comfy-cloud/omnigen2-i2i.cflow.ts +86 -0
  51. package/examples/comfy-cloud/omnigen2-t2i.cflow.ts +62 -0
  52. package/examples/comfy-cloud/ovis-t2i.cflow.ts +56 -0
  53. package/examples/comfy-cloud/pixeldit-t2i.cflow.ts +63 -0
  54. package/examples/comfy-cloud/qwen-image-i2i.cflow.ts +69 -0
  55. package/examples/comfy-cloud/qwen-image-t2i.cflow.ts +55 -0
  56. package/examples/comfy-cloud/sd35-t2i.cflow.ts +48 -0
  57. package/examples/comfy-cloud/sdk.d.ts +123062 -0
  58. package/examples/comfy-cloud/sdxl-t2i.cflow.ts +69 -0
  59. package/examples/comfy-cloud/stable-audio-t2a.cflow.ts +53 -0
  60. package/examples/comfy-cloud/svd-i2v.cflow.ts +75 -0
  61. package/examples/comfy-cloud/wan21-i2v.cflow.ts +83 -0
  62. package/examples/comfy-cloud/wan21-t2v.cflow.ts +64 -0
  63. package/examples/comfy-cloud/wan22-5b-t2v.cflow.ts +69 -0
  64. package/examples/comfy-cloud/wan22-i2v.cflow.ts +107 -0
  65. package/examples/comfy-cloud/wan22-t2v.cflow.ts +98 -0
  66. package/examples/comfy-cloud/z-image-t2i.cflow.ts +62 -0
  67. package/examples/images/README.md +18 -0
  68. package/examples/images/bear_1024x1024.jpg +0 -0
  69. package/examples/images/deer_768x1344.jpg +0 -0
  70. package/examples/images/dog_512x512.jpg +0 -0
  71. package/examples/images/lioness_768x768.jpg +0 -0
  72. package/examples/images/pug_200x300.jpg +0 -0
  73. package/examples/images/walrus_1344x768.jpg +0 -0
  74. package/guide-for-agents.md +172 -0
  75. package/package.json +20 -4
  76. package/src/cli/comfy-ts-cli.ts +19 -2
  77. package/src/cli/gen.ts +21 -12
  78. package/src/cli/tui/components/PreviewPanel.tsx +9 -8
  79. package/src/cli/tui/components/StatusBar.tsx +11 -0
  80. package/src/cli/tui/components/TreePanel.tsx +15 -2
  81. package/src/cli/tui/components/TuiApp.tsx +18 -0
  82. package/src/cli/tui/discoverWorkflows.ts +45 -0
  83. package/src/cli/tui/imagePicker/ImagePickerOverlay.tsx +72 -0
  84. package/src/cli/tui/imagePicker/ImagePickerSt.ts +288 -0
  85. package/src/cli/tui/imagePicker/fsListing.ts +46 -0
  86. package/src/cli/tui/imagePicker/pickerPrefs.ts +78 -0
  87. package/src/cli/tui/run-tui.tsx +52 -23
  88. package/src/cli/tui/state/HostSt.ts +2 -3
  89. package/src/cli/tui/state/LorasSt.ts +14 -36
  90. package/src/cli/tui/state/PreviewSt.ts +28 -2
  91. package/src/cli/tui/state/TreeSt.ts +30 -6
  92. package/src/cli/tui/state/TuiSt.ts +27 -3
  93. package/src/cli/tui/state/WorkflowsSt.ts +15 -1
  94. package/src/exampleAssets.ts +56 -0
  95. package/src/graph/ComfyNode.ts +4 -1
  96. package/src/host/ComfyHost.ts +203 -77
  97. package/src/host/ComfyManager.ts +10 -9
  98. package/src/host/ComfyUploader.ts +1 -2
  99. package/src/host/ResilientWebsocket.ts +3 -1
  100. package/src/host/hostUrl.ts +59 -0
  101. package/src/host/loraManagerApi.ts +5 -4
  102. package/src/index.ts +27 -1
  103. package/src/litegraph/CanonicalWorkflow.ts +77 -0
  104. package/src/litegraph/LiteGraphGroup.ts +9 -7
  105. package/src/litegraph/LiteGraphJSON.ts +34 -13
  106. package/src/litegraph/LiteGraphLink.ts +32 -2
  107. package/src/litegraph/LiteGraphNode.ts +18 -33
  108. package/src/litegraph/LiteGraphNodeInput.ts +10 -8
  109. package/src/litegraph/LiteGraphNodeOutput.ts +2 -3
  110. package/src/litegraph/LiteGraphSubgraphDef.ts +74 -0
  111. package/src/litegraph/convertFlowToLiteGraphJSON.ts +4 -4
  112. package/src/litegraph/expandSubgraphs.ts +352 -0
  113. package/src/litegraph/normalizeWorkflow.ts +141 -0
  114. package/src/manager/ComfyRegistry.ts +37 -9
  115. package/src/manager/generated/KnownComfyCustomNodeName.ts +23852 -1926
  116. package/src/manager/generated/KnownComfyPluginTitle.ts +6854 -236
  117. package/src/manager/generated/KnownComfyPluginURL.ts +3425 -111
  118. package/src/manager/generated/KnownModel_Base.ts +23 -7
  119. package/src/manager/generated/KnownModel_FileName.ts +421 -0
  120. package/src/manager/generated/KnownModel_Name.ts +421 -0
  121. package/src/manager/generated/KnownModel_SavePath.ts +34 -8
  122. package/src/manager/generated/KnownModel_Type.ts +18 -14
  123. package/src/manager/json/alter-list.json +221 -221
  124. package/src/manager/json/custom-node-list.json +61020 -21946
  125. package/src/manager/json/extension-node-map.json +81077 -31176
  126. package/src/manager/json/github-stats.json +29321 -12601
  127. package/src/manager/json/model-list.json +5935 -4997
  128. package/src/manager/loaders/parseReport.ts +55 -0
  129. package/src/manager/loaders/step1_downloadComfyManagerJSONs.ts +15 -49
  130. package/src/manager/loaders/step2_custom-node-list-loader.ts +38 -83
  131. package/src/manager/loaders/step3_extension-node-map-loader.ts +36 -142
  132. package/src/manager/loaders/step4_model-list-loader.ts +25 -36
  133. package/src/manager/loaders/step5_alter-list-loader.ts +29 -0
  134. package/src/manager/loaders/step6_github-stats-loader.ts +23 -0
  135. package/src/manager/script-update-manager.bun.ts +9 -1
  136. package/src/manager/types/ComfyManagerAlterInfo.ts +13 -0
  137. package/src/manager/types/ComfyManagerFileModelInfo.ts +7 -3
  138. package/src/manager/types/ComfyManagerFilePluginContent.ts +6 -9
  139. package/src/manager/types/ComfyManagerFilePluginList.ts +3 -3
  140. package/src/manager/types/ComfyManagerGithubStats.ts +9 -0
  141. package/src/manager/types/ComfyManagerPluginContentMetadata.ts +2 -3
  142. package/src/manager/types/ComfyManagerPluginInfo.ts +48 -34
  143. package/src/runner/ComfyExecution.ts +4 -5
  144. package/src/runner/ComfyWorkflow.ts +2 -2
  145. package/src/runner/wsBinaryFrame.ts +48 -0
  146. package/src/sdk-generator/ComfySchema.ts +14 -1
  147. package/src/sdk-generator/Primitives.ts +6 -24
  148. package/src/sdk-generator/comfy-api-json.ts +3 -1
  149. package/src/sdk-generator/comfyui-sdk-codegen.ts +15 -0
  150. package/src/sdk-generator/inputWidgetKind.ts +196 -0
  151. package/src/sdk-generator/litegraphToApiRequestPayload.ts +372 -96
  152. package/src/state.ts +13 -2
  153. package/src/vars/ComfyVars.ts +82 -2
  154. package/src/vars/DefinedWorkflow.ts +7 -2
  155. package/dist/log-CdfgILde.js +0 -10
  156. package/dist/log-CdfgILde.js.map +0 -1
  157. package/dist/run-tui-SDSJo1Qf.js.map +0 -1
  158. package/src/utils/tryExtracting.ts +0 -41
@@ -0,0 +1,72 @@
1
+ import { Box, Text } from 'ink'
2
+ import { observer } from 'mobx-react-lite'
3
+ import { OverlayList } from 'src/cli/tui/components/OverlayList.tsx'
4
+ import { PICKER_PANES } from 'src/cli/tui/imagePicker/ImagePickerSt.ts'
5
+ import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
6
+
7
+ /** modal image browser: three panes (tab), dirs enter, ⏎ picks, ★ = favorite folder */
8
+ export const ImagePickerOverlay = observer((p: { st: TuiSt }) => {
9
+ const s = p.st
10
+ const ip = s.imagePicker
11
+ const iv = ip.selectedVar
12
+ if (iv == null) return null
13
+ const rows = ip.rows
14
+ return (
15
+ <OverlayList
16
+ title={
17
+ <>
18
+ {s.selected?.[1].label ?? s.selected?.[0]} <Text color="gray">{iv.display()}</Text>
19
+ </>
20
+ }
21
+ extraHeader={
22
+ <Box flexDirection="column">
23
+ <Text>
24
+ {PICKER_PANES.map((pane, ix) => (
25
+ <Text key={pane}>
26
+ {ix > 0 ? <Text color="gray"> · </Text> : null}
27
+ <Text
28
+ color={pane === ip.pane ? 'cyan' : 'gray'}
29
+ bold={pane === ip.pane}
30
+ underline={pane === ip.pane}
31
+ >
32
+ {pane}
33
+ </Text>
34
+ </Text>
35
+ ))}
36
+ {ip.pane === 'browse' ? <Text color="gray"> {ip.folderDisplay}</Text> : null}
37
+ </Text>
38
+ <Text color="yellow">filter: {ip.filter}▌</Text>
39
+ </Box>
40
+ }
41
+ selectedIx={ip.ix}
42
+ lines={s.overlayLines}
43
+ rows={rows.map((row, ix) => {
44
+ const sel = ix === ip.ix
45
+ const fav = row.kind === 'dir' && ip.isFavorite(row.path)
46
+ const missing = row.kind === 'image' && row.missing
47
+ return {
48
+ key: `${row.kind}:${row.path}`,
49
+ node: (
50
+ <Text
51
+ key={`${row.kind}:${row.path}`}
52
+ inverse={sel}
53
+ color={row.kind === 'dir' ? 'blue' : missing ? 'gray' : undefined}
54
+ dimColor={missing}
55
+ >
56
+ {sel ? '▸ ' : ' '}
57
+ {fav ? '★ ' : ' '}
58
+ {row.name}
59
+ {row.kind === 'dir' ? '/' : ''}
60
+ {missing ? ' (missing)' : ''}
61
+ </Text>
62
+ ),
63
+ }
64
+ })}
65
+ footer={
66
+ rows.length === 0 ? (
67
+ <Text color="red">{ip.listingError ?? (ip.filter !== '' ? 'no match' : 'no images here')}</Text>
68
+ ) : undefined
69
+ }
70
+ />
71
+ )
72
+ })
@@ -0,0 +1,288 @@
1
+ import { existsSync, readFileSync, statSync } from 'node:fs'
2
+ import { homedir } from 'node:os'
3
+ import { makeAutoObservable, reaction } from 'mobx'
4
+ import { basename, dirname, resolve } from 'pathe'
5
+ import { listImageDir, parentDir } from 'src/cli/tui/imagePicker/fsListing.ts'
6
+ import { pickerPrefs } from 'src/cli/tui/imagePicker/pickerPrefs.ts'
7
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
8
+ import { fuzzyMatch } from 'src/utils/fuzzyMatch.ts'
9
+ import { imageBufferToAnsi } from 'src/utils/ansiImage.ts'
10
+ import type { ImageVar } from 'src/vars/ComfyVars.ts'
11
+ import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
12
+
13
+ export type PickerPane = 'browse' | 'favorites' | 'recents'
14
+ export const PICKER_PANES: readonly PickerPane[] = ['browse', 'favorites', 'recents']
15
+
16
+ export type PickerRow =
17
+ | { kind: 'dir'; name: string; path: string }
18
+ | { kind: 'image'; name: string; path: string; missing: boolean }
19
+
20
+ /** `~`-contract $HOME for display (ImageVar.display's convention) */
21
+ export function contractHome(path: string): string {
22
+ const home = homedir()
23
+ return path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path
24
+ }
25
+
26
+ /**
27
+ * image-picker overlay (mode 'overlay-image'): browse the disk for an image
28
+ * var, three panes (browse / favorites / recents), filter-as-you-type, the
29
+ * highlighted image previews into the panel via PreviewSt's overlay slot.
30
+ */
31
+ export class ImagePickerSt {
32
+ constructor(private st: TuiSt) {
33
+ makeAutoObservable<ImagePickerSt, 'st'>(this, { st: false })
34
+ // the highlighted image's preview follows the cursor (debounced so
35
+ // arrowing fast never thrashes sharp; renders into the preview panel)
36
+ this.st.disposers.push(
37
+ reaction(
38
+ () => (this.st.mode === 'overlay-image' ? this.highlightedImage : null),
39
+ () => void this.refreshPreview(),
40
+ { delay: 120 },
41
+ ),
42
+ )
43
+ }
44
+
45
+ pane: PickerPane = 'browse'
46
+ /** current browse folder, absolute */
47
+ folder: string = process.cwd()
48
+ ix: number = 0
49
+ filter: string = ''
50
+
51
+ /** kind-narrowing cast sanctioned (agent/coding.md), `kind` is the tag */
52
+ get selectedVar(): ImageVar | null {
53
+ const sel = this.st.selected?.[1]
54
+ return sel?.kind === 'image' ? (sel as ImageVar) : null
55
+ }
56
+
57
+ get folderDisplay(): string {
58
+ return contractHome(this.folder)
59
+ }
60
+
61
+ /** begin() open order: dirname(value) → persisted lastFolder → opts.folder → cwd */
62
+ private initialFolder(iv: ImageVar): string {
63
+ const candidates: (string | null)[] = [
64
+ iv.isSet() ? dirname(iv.absPath()) : null,
65
+ pickerPrefs().lastFolder,
66
+ iv.opts.folder != null ? resolve(iv.opts.folder) : null,
67
+ ]
68
+ for (const c of candidates) {
69
+ try {
70
+ if (c != null && statSync(c).isDirectory()) return c
71
+ } catch {
72
+ // vanished candidate: fall through to the next one
73
+ }
74
+ }
75
+ return process.cwd()
76
+ }
77
+
78
+ begin(): void {
79
+ const iv = this.selectedVar
80
+ if (iv == null) return
81
+ this.st.mode = 'overlay-image'
82
+ this.pane = 'browse'
83
+ this.filter = ''
84
+ this.ix = 0
85
+ this.folder = this.initialFolder(iv)
86
+ // fresh overlay starts on the placeholder, never a stale slot image
87
+ this.st.preview.clearOverlayImage()
88
+ }
89
+
90
+ cancel(): void {
91
+ this.st.mode = 'nav'
92
+ }
93
+
94
+ // ---- listing ----
95
+ /** every row of the active pane BEFORE the filter, plus the browse-pane
96
+ * read error (unreadable folder: shown IN the overlay, browsing elsewhere
97
+ * stays possible). Computed with NO side effects — mobx forbids them. */
98
+ private get paneListing(): { rows: PickerRow[]; error: string | null } {
99
+ if (this.pane === 'favorites')
100
+ return {
101
+ rows: pickerPrefs().favorites.map((dir) => ({ kind: 'dir', name: contractHome(dir), path: dir })),
102
+ error: null,
103
+ }
104
+ if (this.pane === 'recents')
105
+ return {
106
+ rows: pickerPrefs().recents.map((img) => ({
107
+ kind: 'image',
108
+ name: contractHome(img),
109
+ path: img,
110
+ missing: !existsSync(img),
111
+ })),
112
+ error: null,
113
+ }
114
+ const iv = this.selectedVar
115
+ if (iv == null) return { rows: [], error: null }
116
+ try {
117
+ const listing = listImageDir(this.folder, iv.extensions)
118
+ return {
119
+ rows: [
120
+ ...listing.dirs.map((d): PickerRow => ({ kind: 'dir', name: d, path: resolve(this.folder, d) })),
121
+ ...listing.images.map(
122
+ (f): PickerRow => ({ kind: 'image', name: f, path: resolve(this.folder, f), missing: false }),
123
+ ),
124
+ ],
125
+ error: null,
126
+ }
127
+ } catch (e) {
128
+ return { rows: [], error: extractErrorMessage(e) }
129
+ }
130
+ }
131
+
132
+ get listingError(): string | null {
133
+ return this.paneListing.error
134
+ }
135
+
136
+ /** what the overlay renders: pane rows surviving the filter */
137
+ get rows(): PickerRow[] {
138
+ const all = this.paneListing.rows
139
+ if (this.filter === '') return all
140
+ return all.filter((r) => fuzzyMatch(this.filter, r.name))
141
+ }
142
+
143
+ get current(): PickerRow | null {
144
+ return this.rows[this.ix] ?? null
145
+ }
146
+
147
+ /** feeds the preview reaction: only a real, present image highlights */
148
+ get highlightedImage(): string | null {
149
+ const row = this.current
150
+ return row?.kind === 'image' && !row.missing ? row.path : null
151
+ }
152
+
153
+ // ---- navigation ----
154
+ move(delta: number): void {
155
+ const len = this.rows.length
156
+ if (len === 0) return
157
+ this.ix = (this.ix + delta + len) % len
158
+ }
159
+
160
+ cyclePane(): void {
161
+ const ix = PICKER_PANES.indexOf(this.pane)
162
+ this.pane = PICKER_PANES[(ix + 1) % PICKER_PANES.length] ?? 'browse'
163
+ this.ix = 0
164
+ this.filter = ''
165
+ }
166
+
167
+ private goto(dir: string): void {
168
+ this.pane = 'browse'
169
+ this.folder = dir
170
+ this.ix = 0
171
+ this.filter = ''
172
+ }
173
+
174
+ /** `→`: enter the highlighted dir (browse pane; images select via ⏎ only) */
175
+ enter(): void {
176
+ const row = this.current
177
+ if (this.pane === 'browse' && row?.kind === 'dir') this.goto(row.path)
178
+ }
179
+
180
+ /** `←`: parent dir (browse pane; the fs root is its own parent) */
181
+ goParent(): void {
182
+ if (this.pane !== 'browse') return
183
+ const parent = parentDir(this.folder)
184
+ if (parent !== this.folder) this.goto(parent)
185
+ }
186
+
187
+ /** ⏎: enter a dir (a favorite jumps browse into it), select an image */
188
+ commit(): void {
189
+ const row = this.current
190
+ if (row == null) return
191
+ if (row.kind === 'dir') return this.goto(row.path)
192
+ if (row.missing) return // vanished recent: dim row, never a broken value
193
+ this.select(row.path)
194
+ }
195
+
196
+ /** the pick: absolute path into the var, recents + lastFolder recorded */
197
+ private select(absPath: string): void {
198
+ const iv = this.selectedVar
199
+ if (iv == null) return
200
+ iv.set(absPath)
201
+ pickerPrefs().recordPick(absPath)
202
+ this.st.mode = 'nav'
203
+ }
204
+
205
+ /** ⌃F: favorite FOLDERS only — a dir row favorites it, an image row favorites the current folder */
206
+ toggleFavorite(): void {
207
+ const row = this.current
208
+ const dir =
209
+ row == null
210
+ ? this.pane === 'browse'
211
+ ? this.folder
212
+ : null
213
+ : row.kind === 'dir'
214
+ ? row.path
215
+ : this.pane === 'browse'
216
+ ? this.folder
217
+ : dirname(row.path)
218
+ if (dir == null) return
219
+ pickerPrefs().toggleFavorite(dir)
220
+ // favorites pane: the row may vanish under the cursor — clamp
221
+ this.ix = Math.max(0, Math.min(this.ix, this.rows.length - 1))
222
+ }
223
+
224
+ isFavorite(dir: string): boolean {
225
+ return pickerPrefs().isFavorite(dir)
226
+ }
227
+
228
+ // ---- filter (plain chars ALWAYS filter, LorasSt precedent) ----
229
+ filterInput(chunk: string): void {
230
+ this.filter += chunk
231
+ this.ix = 0
232
+ }
233
+
234
+ filterBackspace(): void {
235
+ this.filter = this.filter.slice(0, -1)
236
+ this.ix = 0
237
+ }
238
+
239
+ /** ⌥⌫ / ⌃W: drop the last word of the filter */
240
+ filterDeleteWord(): void {
241
+ this.filter = this.filter.replace(/\s*\S+\s*$/, '')
242
+ this.ix = 0
243
+ }
244
+
245
+ // ---- preview into the shared overlay slot (debounced reaction above) ----
246
+ private _busy: boolean = false
247
+
248
+ async refreshPreview(): Promise<void> {
249
+ if (this.st.mode !== 'overlay-image') {
250
+ // debounced close: another overlay may ALREADY own the slot — never wipe its image
251
+ if (!this.st.preview.overlayActive) this.st.preview.clearOverlayImage()
252
+ return
253
+ }
254
+ const path = this.highlightedImage
255
+ if (path == null) {
256
+ // dir row / empty pane: clear so a stale image never lingers
257
+ this.st.preview.clearOverlayImage()
258
+ return
259
+ }
260
+ if (this._busy) return
261
+ this._busy = true
262
+ try {
263
+ // local file: bytes read directly, no host round-trip
264
+ const bytes = new Uint8Array(readFileSync(path))
265
+ if (this.st.preview.useNative) {
266
+ this.st.preview.setOverlayImage({ bytes, ansi: null, name: basename(path), note: null })
267
+ } else {
268
+ const ansi = await imageBufferToAnsi(bytes, {
269
+ width: this.st.preview.width,
270
+ height: this.st.preview.height,
271
+ })
272
+ this.st.preview.setOverlayImage({ bytes: null, ansi, name: basename(path), note: null })
273
+ }
274
+ } catch (e) {
275
+ // e.g. a file sharp can't decode — placeholder note, never a crash
276
+ this.st.preview.setOverlayImage({
277
+ bytes: null,
278
+ ansi: null,
279
+ name: basename(path),
280
+ note: extractErrorMessage(e),
281
+ })
282
+ } finally {
283
+ this._busy = false
284
+ // the cursor may have moved while we rendered: catch up once
285
+ if (this.st.mode === 'overlay-image' && this.highlightedImage !== path) void this.refreshPreview()
286
+ }
287
+ }
288
+ }
@@ -0,0 +1,46 @@
1
+ import { readdirSync, statSync } from 'node:fs'
2
+ import { dirname, join } from 'pathe'
3
+
4
+ export type DirListing = { dirs: string[]; images: string[] }
5
+
6
+ /** `name.PNG` matches extensions `['png']` — extensions are lowercase, no dots */
7
+ export function hasImageExtension(name: string, extensions: readonly string[]): boolean {
8
+ const dot = name.lastIndexOf('.')
9
+ if (dot <= 0) return false
10
+ return extensions.includes(name.slice(dot + 1).toLowerCase())
11
+ }
12
+
13
+ /**
14
+ * ONE folder for the picker: dirs first then images, both alphabetical,
15
+ * dotfiles skipped, images filtered by extension. Symlinks are followed
16
+ * (a dangling one is skipped). Pure over fs — an unreadable dir THROWS,
17
+ * the caller surfaces it (never a silent empty listing).
18
+ */
19
+ export function listImageDir(dir: string, extensions: readonly string[]): DirListing {
20
+ const dirs: string[] = []
21
+ const images: string[] = []
22
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
23
+ if (entry.name.startsWith('.')) continue
24
+ let isDir = entry.isDirectory()
25
+ let isFile = entry.isFile()
26
+ if (entry.isSymbolicLink()) {
27
+ try {
28
+ const target = statSync(join(dir, entry.name))
29
+ isDir = target.isDirectory()
30
+ isFile = target.isFile()
31
+ } catch {
32
+ continue // dangling symlink: neither dir nor image
33
+ }
34
+ }
35
+ if (isDir) dirs.push(entry.name)
36
+ else if (isFile && hasImageExtension(entry.name, extensions)) images.push(entry.name)
37
+ }
38
+ dirs.sort((a, b) => a.localeCompare(b))
39
+ images.sort((a, b) => a.localeCompare(b))
40
+ return { dirs, images }
41
+ }
42
+
43
+ /** parent for `←` navigation — the fs root is its own parent (never ascends past it) */
44
+ export function parentDir(dir: string): string {
45
+ return dirname(dir)
46
+ }
@@ -0,0 +1,78 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { makeAutoObservable } from 'mobx'
3
+ import { dirname, join } from 'pathe'
4
+ import { logError } from 'src/utils/log.ts'
5
+
6
+ export const RECENTS_CAP = 20
7
+
8
+ /**
9
+ * image-picker favorites + recents + lastFolder — loraKeywords pattern:
10
+ * observable, loaded once, written through on every mutation. Human-editable
11
+ * json at `.comfy-ts/image-picker.json` (hand-tuned data, NOT under cache/ —
12
+ * survives a cache wipe):
13
+ * { "favorites": ["/abs/dir"], "recents": ["/abs/img.png"], "lastFolder": "/abs/dir" }
14
+ * A corrupt file logs loud and starts fresh, never blocks the TUI. The class
15
+ * takes its file path explicitly so tests round-trip it headless; the TUI
16
+ * uses the ONE lazy module singleton below.
17
+ */
18
+ export class PickerPrefs {
19
+ /** favorite FOLDERS, absolute — recents cover files */
20
+ favorites: string[] = []
21
+ /** picked images, absolute, newest first, deduped, capped */
22
+ recents: string[] = []
23
+ lastFolder: string | null = null
24
+
25
+ constructor(public readonly path: string) {
26
+ this.load()
27
+ makeAutoObservable(this)
28
+ }
29
+
30
+ private load(): void {
31
+ if (!existsSync(this.path)) return
32
+ try {
33
+ const raw: unknown = JSON.parse(readFileSync(this.path, 'utf8'))
34
+ if (raw == null || typeof raw !== 'object') throw new Error('not a json object')
35
+ const o = raw as Record<string, unknown>
36
+ if (Array.isArray(o.favorites)) this.favorites = o.favorites.filter((f): f is string => typeof f === 'string')
37
+ if (Array.isArray(o.recents))
38
+ this.recents = o.recents.filter((r): r is string => typeof r === 'string').slice(0, RECENTS_CAP)
39
+ if (typeof o.lastFolder === 'string') this.lastFolder = o.lastFolder
40
+ } catch (e) {
41
+ logError(`[imagePicker] unreadable ${this.path} — starting fresh: ${String(e)}`)
42
+ }
43
+ }
44
+
45
+ private write(): void {
46
+ try {
47
+ mkdirSync(dirname(this.path), { recursive: true })
48
+ const json = { favorites: this.favorites, recents: this.recents, lastFolder: this.lastFolder }
49
+ writeFileSync(this.path, `${JSON.stringify(json, null, 2)}\n`)
50
+ } catch (e) {
51
+ logError(`[imagePicker] write failed ${this.path}: ${String(e)}`)
52
+ }
53
+ }
54
+
55
+ isFavorite(dir: string): boolean {
56
+ return this.favorites.includes(dir)
57
+ }
58
+
59
+ toggleFavorite(dir: string): void {
60
+ this.favorites = this.favorites.includes(dir) ? this.favorites.filter((f) => f !== dir) : [...this.favorites, dir]
61
+ this.write()
62
+ }
63
+
64
+ /** a pick records the image (newest first, deduped, capped) AND remembers its folder */
65
+ recordPick(imagePath: string): void {
66
+ this.recents = [imagePath, ...this.recents.filter((r) => r !== imagePath)].slice(0, RECENTS_CAP)
67
+ this.lastFolder = dirname(imagePath)
68
+ this.write()
69
+ }
70
+ }
71
+
72
+ let _prefs: PickerPrefs | null = null
73
+
74
+ /** the TUI's store, bound lazily to `.comfy-ts/image-picker.json` (gitignored) */
75
+ export function pickerPrefs(): PickerPrefs {
76
+ if (_prefs == null) _prefs = new PickerPrefs(join(comfyts.baseFolder, 'image-picker.json'))
77
+ return _prefs
78
+ }
@@ -1,50 +1,79 @@
1
- import { readdirSync, statSync } from 'node:fs'
1
+ import { realpathSync, statSync } from 'node:fs'
2
2
  import { pathToFileURL } from 'node:url'
3
3
  import { render } from 'ink'
4
- import { dirname, join, resolve } from 'pathe'
4
+ import { dirname, resolve } from 'pathe'
5
5
  import { COMFY_TS_TUI_ENV } from 'src/cli/tui-env.ts'
6
+ import { mergeWorkflowSources, scanCflowFiles } from 'src/cli/tui/discoverWorkflows.ts'
7
+ import { bundledExamplesDir } from 'src/exampleAssets.ts'
6
8
  import { findDefinedWorkflow } from 'src/cli/tui/findDefinedWorkflow.ts'
7
9
  import { installProtocolImagePainter } from 'src/cli/tui/protocolImagePainter.ts'
8
10
  import { TuiApp } from 'src/cli/tui/components/TuiApp.tsx'
9
11
  import { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
10
-
11
- /** recursive scan for the workflow-module naming convention */
12
- function scanCflowFiles(dir: string): string[] {
13
- const hits = readdirSync(dir, { recursive: true })
14
- .map((f) => join(dir, String(f)))
15
- .filter((f) => f.endsWith('.cflow.ts') || f.endsWith('.cflow.tsx'))
16
- return hits.sort()
17
- }
12
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
13
+ import { logError } from 'src/utils/log.ts'
14
+ import type { DefinedWorkflow } from 'src/vars/DefinedWorkflow.ts'
18
15
 
19
16
  export async function runTui(args: string[]): Promise<number> {
20
- // no arg = scan cwd; a file arg ALSO scans its folder (file preselected)
21
- const target = args.find((a) => !a.startsWith('--')) ?? '.'
17
+ // no arg = cwd scan MERGED with the examples packaged with comfy-ts; an
18
+ // explicit dir/file arg keeps that scope only (a file arg is preselected)
19
+ const target = args.find((a) => !a.startsWith('--'))
22
20
 
23
21
  // the module contract: files check `import.meta.main` (false here) so their
24
22
  // standalone run block is skipped; this env var covers in-run tweaks
25
23
  process.env[COMFY_TS_TUI_ENV] = '1'
26
24
  process.env.COMFY_TS_QUIET = '1' // info chatter off; the TUI owns the screen
27
25
 
28
- const abs = resolve(target)
26
+ // realpath both sides: scanned paths derive from cwd, bundled ones from
27
+ // import.meta — a symlinked cwd must not defeat the dedupe
28
+ const abs = realpathSync(resolve(target ?? '.'))
29
29
  const isDir = statSync(abs).isDirectory()
30
30
  const scanned = scanCflowFiles(isDir ? abs : dirname(abs))
31
- const workflowFiles = isDir || scanned.includes(abs) ? scanned : [abs, ...scanned]
32
- const first = isDir ? workflowFiles[0] : abs
33
- if (first == null) {
31
+ const scannedPlusArg = isDir || scanned.includes(abs) ? scanned : [abs, ...scanned]
32
+ // no bun = no bundled examples: node refuses to import TypeScript under
33
+ // node_modules (the cli re-execs into bun when it can, comfy-ts-cli.ts)
34
+ const canImportBundled = process.versions.bun != null
35
+ const examplesDir = canImportBundled ? bundledExamplesDir() : null
36
+ if (!canImportBundled && target == null)
37
+ logError('packaged examples skipped: importing .cflow.ts from node_modules needs bun (bunx --bun comfy-ts tui)')
38
+ const discovery = mergeWorkflowSources({
39
+ explicitTarget: target != null,
40
+ scanned: scannedPlusArg,
41
+ bundledFiles: examplesDir == null ? [] : scanCflowFiles(realpathSync(examplesDir)),
42
+ })
43
+ const workflowFiles = discovery.files
44
+ if (workflowFiles.length === 0) {
34
45
  console.error(`[comfy-ts tui] no **/*.cflow.ts found under ${abs}`)
35
46
  return 1
36
47
  }
37
48
 
38
- const mod: Record<string, unknown> = await import(pathToFileURL(first).href)
39
- const wf = findDefinedWorkflow(mod)
40
- if (wf == null) {
41
- console.error(
42
- `[comfy-ts tui] ${first} exports no DefinedWorkflow — export the result of host.defineWorkflow(...)`,
43
- )
49
+ // initial module = the file arg, else the first candidate that LOADS: a
50
+ // module whose import throws (missing schema cache, bad code) or that
51
+ // exports no DefinedWorkflow becomes a red row in the tree, never a crash
52
+ const candidates =
53
+ !isDir && workflowFiles.includes(abs) ? [abs, ...workflowFiles.filter((f) => f !== abs)] : workflowFiles
54
+ const loadErrors = new Map<string, string>()
55
+ let first: string | null = null
56
+ let wf: DefinedWorkflow | null = null
57
+ for (const file of candidates) {
58
+ try {
59
+ const mod: Record<string, unknown> = await import(pathToFileURL(file).href)
60
+ const found = findDefinedWorkflow(mod)
61
+ if (found == null)
62
+ throw new Error(`${file} exports no DefinedWorkflow — export the result of host.defineWorkflow(...)`)
63
+ first = file
64
+ wf = found
65
+ break
66
+ } catch (e) {
67
+ loadErrors.set(file, extractErrorMessage(e))
68
+ }
69
+ }
70
+ if (first == null || wf == null) {
71
+ console.error(`[comfy-ts tui] no loadable workflow module among ${candidates.length} file(s):`)
72
+ for (const [file, err] of loadErrors) console.error(` ${file}: ${err}`)
44
73
  return 1
45
74
  }
46
75
 
47
- const st = new TuiSt(wf, { workflowFiles, currentFile: first })
76
+ const st = new TuiSt(wf, { workflowFiles, currentFile: first, bundledFiles: discovery.bundled, loadErrors })
48
77
  // ALT SCREEN (TTY only): deterministic absolute coordinates for the protocol
49
78
  // image painter + no scrollback pollution / clipped first row.
50
79
  // modifyOtherKeys mode 1 rides along: vscode/xterm.js then ENCODES modified ⏎
@@ -104,9 +104,8 @@ export class HostSt {
104
104
  this.spinTimer = spin
105
105
  let ok = false
106
106
  try {
107
- const res = await fetch(`${host.getServerHostHTTP()}/api/prompt`, {
108
- signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
109
- })
107
+ // host.fetch: /api preferred + auth header, so cloud hosts probe up too
108
+ const res = await host.fetch('/prompt', { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) })
110
109
  void res.body?.cancel()
111
110
  ok = res.ok
112
111
  } catch {