comfy-ts 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +61 -8
  2. package/dist/{DefinedWorkflow-BYyu5dK9.js → DefinedWorkflow-gpknV-5f.js} +52 -35
  3. package/dist/DefinedWorkflow-gpknV-5f.js.map +1 -0
  4. package/dist/DraftsSt-DmA0jWGl.js +434 -0
  5. package/dist/DraftsSt-DmA0jWGl.js.map +1 -0
  6. package/dist/cli.js +17 -4555
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +184 -32
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +54 -23
  11. package/dist/index.d.ts +36 -5
  12. package/dist/index.js +184 -32
  13. package/dist/index.js.map +1 -1
  14. package/dist/run-serve-Bn6yIJB0.js +638 -0
  15. package/dist/run-serve-Bn6yIJB0.js.map +1 -0
  16. package/dist/{run-tui-DZ22HDHI.js → run-tui-BtjaOXRh.js} +791 -395
  17. package/dist/run-tui-BtjaOXRh.js.map +1 -0
  18. package/dist/state-DKCPy105.js +4690 -0
  19. package/dist/state-DKCPy105.js.map +1 -0
  20. package/examples/README.md +6 -4
  21. package/examples/{01-txt2img.cflow.ts → rvion/01-txt2img.cflow.ts} +1 -1
  22. package/examples/{02-img2img-upload.cflow.ts → rvion/02-img2img-upload.cflow.ts} +1 -1
  23. package/examples/{03-export-workflow-json.cflow.ts → rvion/03-export-workflow-json.cflow.ts} +1 -1
  24. package/examples/{04-krea2-turbo-t2i.cflow.ts → rvion/04-krea2-turbo-t2i.cflow.ts} +2 -2
  25. package/examples/{05-comfy-cloud.cflow.ts → rvion/05-comfy-cloud.cflow.ts} +2 -2
  26. package/examples/rvion/06-qwen-image-edit.cflow.ts +89 -0
  27. package/package.json +6 -2
  28. package/src/cli/comfy-ts-cli.ts +15 -5
  29. package/src/cli/serve/ServeApp.ts +378 -0
  30. package/src/cli/serve/applyVarPayload.ts +119 -0
  31. package/src/cli/serve/describeVar.ts +74 -0
  32. package/src/cli/serve/run-serve.ts +169 -0
  33. package/src/cli/tui/components/CopyOverlay.tsx +25 -0
  34. package/src/cli/tui/components/Header.tsx +9 -4
  35. package/src/cli/tui/components/HostPanel.tsx +3 -2
  36. package/src/cli/tui/components/HostsOverlay.tsx +33 -0
  37. package/src/cli/tui/components/StatusBar.tsx +29 -9
  38. package/src/cli/tui/components/TreePanel.tsx +33 -9
  39. package/src/cli/tui/components/TuiApp.tsx +54 -7
  40. package/src/cli/tui/components/VarsPanel.tsx +67 -34
  41. package/src/cli/tui/imageClipboard.ts +39 -0
  42. package/src/cli/tui/imagePicker/fsListing.ts +6 -4
  43. package/src/cli/tui/listWindow.ts +36 -0
  44. package/src/cli/tui/run-tui.tsx +47 -7
  45. package/src/cli/tui/state/DraftsSt.ts +3 -2
  46. package/src/cli/tui/state/ExecSt.ts +156 -12
  47. package/src/cli/tui/state/HostSt.ts +94 -10
  48. package/src/cli/tui/state/PickerSt.ts +8 -2
  49. package/src/cli/tui/state/QueueSt.ts +2 -2
  50. package/src/cli/tui/state/SettingsSt.ts +25 -7
  51. package/src/cli/tui/state/TreeSt.ts +164 -36
  52. package/src/cli/tui/state/TuiSt.ts +81 -6
  53. package/src/cli/tui/state/WorkflowsSt.ts +14 -2
  54. package/src/cli/tui/treeRows.ts +165 -0
  55. package/src/host/ComfyHost.ts +7 -0
  56. package/src/litegraph/convertFlowToLiteGraphJSON.ts +11 -7
  57. package/src/runner/ComfyExecution.ts +21 -4
  58. package/src/runner/ComfyWorkflowLayout.ts +6 -4
  59. package/src/runner/outputPath.ts +75 -0
  60. package/src/sdk-generator/inputWidgetKind.ts +50 -11
  61. package/src/sdk-generator/litegraphToApiRequestPayload.ts +14 -7
  62. package/src/state.ts +7 -1
  63. package/src/vars/ComfyVars.ts +33 -4
  64. package/src/vars/DefinedWorkflow.ts +21 -8
  65. package/dist/DefinedWorkflow-BYyu5dK9.js.map +0 -1
  66. package/dist/run-tui-DZ22HDHI.js.map +0 -1
@@ -1,9 +1,11 @@
1
1
  import { Box, Text, useApp, useInput, useStdin } from 'ink'
2
2
  import { observer } from 'mobx-react-lite'
3
3
  import { basename } from 'pathe'
4
+ import { CopyOverlay } from 'src/cli/tui/components/CopyOverlay.tsx'
4
5
  import { DraftsOverlay } from 'src/cli/tui/components/DraftsOverlay.tsx'
5
6
  import { Header } from 'src/cli/tui/components/Header.tsx'
6
7
  import { HostPanel } from 'src/cli/tui/components/HostPanel.tsx'
8
+ import { HostsOverlay } from 'src/cli/tui/components/HostsOverlay.tsx'
7
9
  import { LorasOverlay } from 'src/cli/tui/components/LorasOverlay.tsx'
8
10
  import { ChoiceOverlay, SizeOverlay } from 'src/cli/tui/components/PickerOverlays.tsx'
9
11
  import { PreviewPanel } from 'src/cli/tui/components/PreviewPanel.tsx'
@@ -115,7 +117,21 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
115
117
  }
116
118
  if (s.mode === 'tree') {
117
119
  const tr = s.tree
118
- if (key.escape || input === 't') return tr.blur()
120
+ // the `/` filter owns plain keys while active (letters type into it)
121
+ if (tr.filtering) {
122
+ if (key.escape) return tr.clearFilter()
123
+ if (key.return) return void tr.commit()
124
+ if (key.upArrow) return tr.move(-1)
125
+ if (key.downArrow) return tr.move(1)
126
+ if (key.leftArrow) return tr.fold()
127
+ if (key.rightArrow) return tr.unfold()
128
+ if (key.backspace || key.delete) return tr.filterBackspace()
129
+ if (input && !key.ctrl && !key.meta) return tr.filterInput(input)
130
+ return
131
+ }
132
+ if (key.escape) return tr.filter !== '' ? tr.clearFilter() : tr.blur()
133
+ if (input === 't') return tr.blur()
134
+ if (input === '/') return tr.beginFilter()
119
135
  if (key.return || input === ' ') return void tr.commit()
120
136
  if (key.upArrow) return tr.move(-1)
121
137
  if (key.downArrow) return tr.move(1)
@@ -130,9 +146,11 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
130
146
  if (input === 'r') return void s.exec.run()
131
147
  if (input === 's') return s.exec.randomizeSeedAndRun()
132
148
  if (input === 'd') return s.drafts.begin()
133
- if (input === 'h') return s.host.begin()
149
+ if (input === 'h') return s.host.beginPicker()
150
+ if (input === 'a') return s.host.begin()
134
151
  if (input === 'p') return s.preview.beginMenu()
135
152
  if (input === 'o') return s.exec.openLastOutput()
153
+ if (input === 'i') return void s.exec.copyLastImage()
136
154
  if (input === 'q') {
137
155
  s.onExit()
138
156
  return app.exit()
@@ -141,7 +159,8 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
141
159
  }
142
160
  if (s.mode === 'host') {
143
161
  const h = s.host
144
- if (key.escape || input === 'h' || input === 'v') return h.blur()
162
+ if (key.escape || input === 'a' || input === 'v') return h.blur()
163
+ if (input === 'h') return h.beginPicker()
145
164
  if (key.return || input === ' ') return void h.commit()
146
165
  if (key.upArrow) return h.move(-1)
147
166
  if (key.downArrow) return h.move(1)
@@ -151,6 +170,20 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
151
170
  }
152
171
  return
153
172
  }
173
+ if (s.mode === 'overlay-hosts') {
174
+ const h = s.host
175
+ if (key.escape || input === 'h') return h.cancelPicker()
176
+ if (key.return || input === ' ') return h.commitPicker()
177
+ if (key.upArrow) return h.pickerMove(-1)
178
+ if (key.downArrow) return h.pickerMove(1)
179
+ return
180
+ }
181
+ if (s.mode === 'overlay-copy') {
182
+ // any close-ish key ends it — a confirmation must never trap
183
+ if (key.escape || key.return || input === ' ' || input === 'c' || input === 'C' || input === 'q')
184
+ return s.exec.closeCopyPopup()
185
+ return
186
+ }
154
187
  if (s.mode === 'preview') {
155
188
  const pv = s.preview
156
189
  // ⏎ CONFIRMS (closes): ←→ already changed the value in place
@@ -163,8 +196,10 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
163
196
  if (input === 'r') return void s.exec.run()
164
197
  if (input === 's') return s.exec.randomizeSeedAndRun()
165
198
  if (input === 'd') return s.drafts.begin()
166
- if (input === 'h') return s.host.begin()
199
+ if (input === 'h') return s.host.beginPicker()
200
+ if (input === 'a') return s.host.begin()
167
201
  if (input === 'o') return s.exec.openLastOutput()
202
+ if (input === 'i') return void s.exec.copyLastImage()
168
203
  if (input === 'q') {
169
204
  s.onExit()
170
205
  return app.exit()
@@ -198,14 +233,20 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
198
233
  if (key.leftArrow) return s.tree.focus()
199
234
  if (key.rightArrow || key.return || input === ' ') return s.activate()
200
235
  if (s.navKey(input)) return
236
+ if (input === '/') {
237
+ s.tree.focus()
238
+ return s.tree.beginFilter()
239
+ }
201
240
  if (input === 'e') return s.drafts.beginRename()
202
241
  if (input === 'r') return void s.exec.run()
203
242
  if (input === 's') return s.exec.randomizeSeedAndRun()
204
243
  if (input === 't' || input === 'w') return s.tree.focus()
205
- if (input === 'h') return s.host.begin()
244
+ if (input === 'h') return s.host.beginPicker()
245
+ if (input === 'a') return s.host.begin()
206
246
  if (input === 'd') return s.drafts.begin()
207
247
  if (input === 'p') return s.preview.beginMenu()
208
248
  if (input === 'o') return s.exec.openLastOutput()
249
+ if (input === 'i') return void s.exec.copyLastImage()
209
250
  if (input === 'c') return void s.exec.copyWorkflowJson()
210
251
  if (input === 'C') return void s.exec.copyApiJson()
211
252
  },
@@ -216,9 +257,11 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
216
257
  )
217
258
 
218
259
  return (
219
- <Box flexDirection="column" minHeight={s.termRows - 1}>
260
+ // FIXED height, not min: content taller than the terminal must window
261
+ // itself (tree) or clip, never grow the frame — his overflow repro
262
+ <Box flexDirection="column" height={s.termRows - 1}>
220
263
  <Header st={s} />
221
- <Box flexDirection="row" flexGrow={1}>
264
+ <Box flexDirection="row" flexGrow={1} flexShrink={1} overflow="hidden">
222
265
  <TreePanel st={s} />
223
266
  <Box flexDirection="column" flexGrow={1}>
224
267
  {/* ink has no z-order: the overlay replaces the vars panel while open */}
@@ -238,6 +281,10 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
238
281
  <ImagePickerOverlay st={s} />
239
282
  ) : s.mode === 'overlay-drafts' ? (
240
283
  <DraftsOverlay st={s} />
284
+ ) : s.mode === 'overlay-hosts' ? (
285
+ <HostsOverlay st={s} />
286
+ ) : s.mode === 'overlay-copy' ? (
287
+ <CopyOverlay st={s} />
241
288
  ) : (
242
289
  <VarsPanel st={s} />
243
290
  )}
@@ -1,5 +1,7 @@
1
- import { Box, Text } from 'ink'
1
+ import { Box, measureElement, Text } from 'ink'
2
2
  import { observer } from 'mobx-react-lite'
3
+ import { useEffect, useRef } from 'react'
4
+ import type { DOMElement } from 'ink'
3
5
  import { EditField } from 'src/cli/tui/components/EditField.tsx'
4
6
  import { type AnyVar, PromptVar } from 'src/vars/ComfyVars.ts'
5
7
  import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
@@ -32,55 +34,86 @@ const PromptCell = observer((p: { varDef: PromptVar; value: string }) => {
32
34
  )
33
35
  })
34
36
 
35
- const VarRow = observer((p: { name: string; varDef: AnyVar; selected: boolean; labelW: number; st: TuiSt }) => {
36
- // a custom prompt session (draft naming) renders as PromptOverlay, not here
37
- const editing = p.selected && p.st.mode === 'edit' && !p.st.editor.isCustom
38
- const label = p.varDef.label ?? p.name
39
- const raw = p.varDef.display()
40
- const value = raw.length > VALUE_CAP ? `${raw.slice(0, VALUE_CAP)}…` : raw
41
- return (
42
- <Box flexDirection="row">
43
- {/* fixed columns keep wrapped value lines aligned under the value column */}
44
- <Box width={p.labelW} flexShrink={0}>
45
- <Text inverse={p.selected}>
46
- {p.selected ? '▸ ' : ' '}
47
- {label}
48
- </Text>
49
- </Box>
50
- <Box width={9} flexShrink={0}>
51
- <Text color="gray">[{p.varDef.kind}]</Text>
52
- </Box>
53
- <Box flexGrow={1}>
54
- {editing ? (
55
- <EditField st={p.st} />
56
- ) : p.varDef instanceof PromptVar ? (
57
- <PromptCell varDef={p.varDef} value={value} />
58
- ) : (
59
- <Text color="cyan" wrap="wrap">
60
- {value}
37
+ const VarRow = observer(
38
+ (p: { name: string; varDef: AnyVar; selected: boolean; labelW: number; st: TuiSt; compact: boolean }) => {
39
+ // a custom prompt session (draft naming) renders as PromptOverlay, not here
40
+ const editing = p.selected && p.st.mode === 'edit' && !p.st.editor.isCustom
41
+ const label = p.varDef.label ?? p.name
42
+ const raw = p.varDef.display()
43
+ const value = raw.length > VALUE_CAP ? `${raw.slice(0, VALUE_CAP)}…` : raw
44
+ // compact (small terminal, list overflows): NON-selected rows cost ONE
45
+ // line — tall wrapped values above the selection cannot push it off
46
+ const oneLine = p.compact && !p.selected
47
+ return (
48
+ <Box flexDirection="row">
49
+ {/* fixed columns keep wrapped value lines aligned under the value column */}
50
+ <Box width={p.labelW} flexShrink={0}>
51
+ <Text inverse={p.selected}>
52
+ {p.selected ? '▸ ' : ' '}
53
+ {label}
61
54
  </Text>
62
- )}
55
+ </Box>
56
+ <Box width={9} flexShrink={0}>
57
+ <Text color="gray">[{p.varDef.kind}]</Text>
58
+ </Box>
59
+ <Box flexGrow={1}>
60
+ {editing ? (
61
+ <EditField st={p.st} />
62
+ ) : oneLine ? (
63
+ <Text color="cyan" wrap="truncate">
64
+ {value.replaceAll('\n', ' ')}
65
+ </Text>
66
+ ) : p.varDef instanceof PromptVar ? (
67
+ <PromptCell varDef={p.varDef} value={value} />
68
+ ) : (
69
+ <Text color="cyan" wrap="wrap">
70
+ {value}
71
+ </Text>
72
+ )}
73
+ </Box>
63
74
  </Box>
64
- </Box>
65
- )
66
- })
75
+ )
76
+ },
77
+ )
67
78
 
68
79
  export const VarsPanel = observer((p: { st: TuiSt }) => {
69
80
  const s = p.st
70
81
  // label column = longest label + marker, so [kind] and values line up
71
82
  const labelW = Math.max(6, ...s.entries.map(([name, v]) => (v.label ?? name).length)) + 3
72
83
  const focused = s.mode === 'nav' || s.mode === 'edit'
84
+ const boxRef = useRef<DOMElement>(null)
85
+ useEffect(() => {
86
+ if (boxRef.current != null) s.setVarsViewH(measureElement(boxRef.current).height)
87
+ })
88
+ const w = s.varsWindow
73
89
  return (
74
- <Box borderStyle="round" borderColor={focused ? 'cyan' : 'gray'} paddingX={1} flexDirection="column">
90
+ <Box
91
+ ref={boxRef}
92
+ borderStyle="round"
93
+ borderColor={focused ? 'cyan' : 'gray'}
94
+ paddingX={1}
95
+ flexDirection="column"
96
+ overflow="hidden"
97
+ >
75
98
  {/* marginTop -1 lifts the label onto the border line: the panel key IS its title */}
76
99
  <Box marginTop={-1}>
77
100
  <Text color={focused ? 'cyan' : 'gray'} bold={focused}>
78
101
  (v)ars
79
102
  </Text>
80
103
  </Box>
81
- {s.entries.map(([name, varDef], ix) => (
82
- <VarRow key={name} name={name} varDef={varDef} selected={ix === s.selIx} labelW={labelW} st={s} />
104
+ {w.moreAbove && <Text color="gray">…</Text>}
105
+ {s.entries.slice(w.start, w.end).map(([name, varDef], sliceIx) => (
106
+ <VarRow
107
+ key={name}
108
+ name={name}
109
+ varDef={varDef}
110
+ selected={w.start + sliceIx === s.selIx}
111
+ labelW={labelW}
112
+ st={s}
113
+ compact={s.varsCompact}
114
+ />
83
115
  ))}
116
+ {w.moreBelow && <Text color="gray">…</Text>}
84
117
  </Box>
85
118
  )
86
119
  })
@@ -0,0 +1,39 @@
1
+ /** platform command that puts an image file's PIXELS on the clipboard
2
+ * (pbcopy/clip/xclip only do text — images need per-OS tools) */
3
+ export type ImageClipboardCommand = { cmd: string; args: string[] }
4
+
5
+ const extOf = (path: string): string => {
6
+ const dot = path.lastIndexOf('.')
7
+ return dot === -1 ? '' : path.slice(dot + 1).toLowerCase()
8
+ }
9
+
10
+ export const imageClipboardCommand = (platform: NodeJS.Platform, path: string): ImageClipboardCommand | null => {
11
+ const ext = extOf(path)
12
+ if (platform === 'darwin') {
13
+ // osascript TAGS bytes with the class, it never transcodes: PNGf on a
14
+ // webp would paste garbage under a green popup — only png/jpeg pass;
15
+ // the caller transcodes anything else to png first (reviewer catch)
16
+ if (ext !== 'png' && ext !== 'jpg' && ext !== 'jpeg') return null
17
+ const cls = ext === 'png' ? '«class PNGf»' : 'JPEG picture'
18
+ return {
19
+ cmd: 'osascript',
20
+ args: ['-e', `set the clipboard to (read (POSIX file ${JSON.stringify(path)}) as ${cls})`],
21
+ }
22
+ }
23
+ if (platform === 'win32') {
24
+ // single-quoted PS string, inner quotes doubled: a double-quoted string
25
+ // would interpolate $ and ` from user-controlled paths (reviewer catch)
26
+ const psQuoted = `'${path.replaceAll("'", "''")}'`
27
+ return {
28
+ cmd: 'powershell',
29
+ args: [
30
+ '-NoProfile',
31
+ '-Sta',
32
+ '-Command',
33
+ `Add-Type -AssemblyName System.Windows.Forms,System.Drawing; $img=[System.Drawing.Image]::FromFile(${psQuoted}); [System.Windows.Forms.Clipboard]::SetImage($img); $img.Dispose()`,
34
+ ],
35
+ }
36
+ }
37
+ const mime = ext === 'jpg' || ext === 'jpeg' ? 'image/jpeg' : ext === 'webp' ? 'image/webp' : 'image/png'
38
+ return { cmd: 'xclip', args: ['-selection', 'clipboard', '-t', mime, '-i', path] }
39
+ }
@@ -12,15 +12,15 @@ export function hasImageExtension(name: string, extensions: readonly string[]):
12
12
 
13
13
  /**
14
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).
15
+ * images filtered by extension. Dot FILES are junk (.DS_Store) and skipped;
16
+ * dot DIRS are listed — .comfy-ts/outputs must be browsable. Symlinks are
17
+ * followed (a dangling one is skipped). Pure over fs — an unreadable dir
18
+ * THROWS, the caller surfaces it (never a silent empty listing).
18
19
  */
19
20
  export function listImageDir(dir: string, extensions: readonly string[]): DirListing {
20
21
  const dirs: string[] = []
21
22
  const images: string[] = []
22
23
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
23
- if (entry.name.startsWith('.')) continue
24
24
  let isDir = entry.isDirectory()
25
25
  let isFile = entry.isFile()
26
26
  if (entry.isSymbolicLink()) {
@@ -32,6 +32,8 @@ export function listImageDir(dir: string, extensions: readonly string[]): DirLis
32
32
  continue // dangling symlink: neither dir nor image
33
33
  }
34
34
  }
35
+ // after symlink resolution, so a dot-named link to a real dir stays listed
36
+ if (entry.name.startsWith('.') && !isDir) continue
35
37
  if (isDir) dirs.push(entry.name)
36
38
  else if (isFile && hasImageExtension(entry.name, extensions)) images.push(entry.name)
37
39
  }
@@ -0,0 +1,36 @@
1
+ /** a scroll window over a list, `…` markers INCLUDED in the line budget
2
+ * (OverlayList's markers ride on modal slack instead — different contract) */
3
+ export type ListWindow = {
4
+ start: number
5
+ end: number
6
+ moreAbove: boolean
7
+ moreBelow: boolean
8
+ }
9
+
10
+ /**
11
+ * window a list around the selection so that
12
+ * (moreAbove ? 1 : 0) + (end - start) + (moreBelow ? 1 : 0) <= budget,
13
+ * with the selection always inside [start, end). Degenerate budgets (<= 2)
14
+ * drop the markers and show a bare slice at the selection.
15
+ */
16
+ export const listWindow = (p: { count: number; selected: number; budget: number }): ListWindow => {
17
+ if (p.count === 0 || p.budget <= 0) {
18
+ const at = Math.max(0, Math.min(p.selected, p.count))
19
+ return { start: at, end: at, moreAbove: false, moreBelow: false }
20
+ }
21
+ if (p.count <= p.budget) return { start: 0, end: p.count, moreAbove: false, moreBelow: false }
22
+ const sel = Math.max(0, Math.min(p.selected, p.count - 1))
23
+ if (p.budget <= 2) {
24
+ const start = Math.min(sel, p.count - p.budget)
25
+ return { start, end: start + p.budget, moreAbove: false, moreBelow: false }
26
+ }
27
+ // top region: the window starts at 0, only the below marker eats a line
28
+ if (sel < p.budget - 1) return { start: 0, end: p.budget - 1, moreAbove: false, moreBelow: true }
29
+ // bottom region: the window ends at count, only the above marker eats a line
30
+ if (sel >= p.count - (p.budget - 1))
31
+ return { start: p.count - (p.budget - 1), end: p.count, moreAbove: true, moreBelow: false }
32
+ // middle: both markers eat, the rest centers on the selection
33
+ const visible = p.budget - 2
34
+ const start = Math.max(1, Math.min(sel - Math.floor(visible / 2), p.count - visible - 1))
35
+ return { start, end: start + visible, moreAbove: true, moreBelow: true }
36
+ }
@@ -1,8 +1,9 @@
1
- import { realpathSync, statSync } from 'node:fs'
1
+ import { readFileSync, realpathSync, statSync } from 'node:fs'
2
2
  import { pathToFileURL } from 'node:url'
3
3
  import { render } from 'ink'
4
4
  import { dirname, resolve } from 'pathe'
5
5
  import { COMFY_TS_TUI_ENV } from 'src/cli/tui-env.ts'
6
+ import { settingsPathFor } from 'src/state.ts'
6
7
  import { mergeWorkflowSources, scanCflowFiles } from 'src/cli/tui/discoverWorkflows.ts'
7
8
  import { bundledExamplesDir } from 'src/exampleAssets.ts'
8
9
  import { findDefinedWorkflow } from 'src/cli/tui/findDefinedWorkflow.ts'
@@ -13,6 +14,22 @@ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
13
14
  import { logError } from 'src/utils/log.ts'
14
15
  import type { DefinedWorkflow } from 'src/vars/DefinedWorkflow.ts'
15
16
 
17
+ /** the module the last session was on, IF it is still in this run's tree
18
+ * (settings write: SettingsSt; exported for the headless test) */
19
+ export function rememberedWorkflow(
20
+ workflowFiles: string[],
21
+ settingsPath = settingsPathFor(process.cwd()),
22
+ ): string | null {
23
+ try {
24
+ const raw: unknown = JSON.parse(readFileSync(settingsPath, 'utf8'))
25
+ if (raw == null || typeof raw !== 'object') return null
26
+ const last = (raw as Record<string, unknown>).lastWorkflow
27
+ return typeof last === 'string' && workflowFiles.includes(last) ? last : null
28
+ } catch {
29
+ return null // no settings yet, or unreadable json — the default pick is fine
30
+ }
31
+ }
32
+
16
33
  export async function runTui(args: string[]): Promise<number> {
17
34
  // no arg = cwd scan MERGED with the examples packaged with comfy-ts; an
18
35
  // explicit dir/file arg keeps that scope only (a file arg is preselected)
@@ -35,10 +52,20 @@ export async function runTui(args: string[]): Promise<number> {
35
52
  const examplesDir = canImportBundled ? bundledExamplesDir() : null
36
53
  if (!canImportBundled && target == null)
37
54
  logError('packaged examples skipped: importing .cflow.ts from node_modules needs bun (bunx --bun comfy-ts tui)')
55
+ // rvion/ (the numbered didactic sequence) ahead of the zoo: with no file
56
+ // arg the FIRST LOADABLE bundled module is the opening workflow, and that
57
+ // must stay 01-txt2img, not the zoo's alphabetical head (the tree itself
58
+ // stays alphabetical — this only orders the load candidates)
59
+ const bundledFiles =
60
+ examplesDir == null
61
+ ? []
62
+ : scanCflowFiles(realpathSync(examplesDir)).sort(
63
+ (a, b) => Number(!a.includes('/rvion/')) - Number(!b.includes('/rvion/')) || a.localeCompare(b),
64
+ )
38
65
  const discovery = mergeWorkflowSources({
39
66
  explicitTarget: target != null,
40
67
  scanned: scannedPlusArg,
41
- bundledFiles: examplesDir == null ? [] : scanCflowFiles(realpathSync(examplesDir)),
68
+ bundledFiles,
42
69
  })
43
70
  const workflowFiles = discovery.files
44
71
  if (workflowFiles.length === 0) {
@@ -46,11 +73,14 @@ export async function runTui(args: string[]): Promise<number> {
46
73
  return 1
47
74
  }
48
75
 
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
76
+ // initial module = the file arg, else the workflow the LAST session was on
77
+ // (settings read straight from disk: the comfyts global only exists once a
78
+ // module imports), else the first candidate that LOADS: a module whose
79
+ // import throws (missing schema cache, bad code) or that exports no
80
+ // DefinedWorkflow becomes a red row in the tree, never a crash
81
+ const preferred =
82
+ !isDir && workflowFiles.includes(abs) ? abs : target == null ? rememberedWorkflow(workflowFiles) : null
83
+ const candidates = preferred != null ? [preferred, ...workflowFiles.filter((f) => f !== preferred)] : workflowFiles
54
84
  const loadErrors = new Map<string, string>()
55
85
  let first: string | null = null
56
86
  let wf: DefinedWorkflow | null = null
@@ -83,10 +113,18 @@ export async function runTui(args: string[]): Promise<number> {
83
113
  // editor keys); unsupporting terminals ignore it.
84
114
  const altScreen = process.stdout.isTTY === true
85
115
  if (altScreen) process.stdout.write('\u001b[?1049h\u001b[H\u001b[>4;1m')
116
+ // RAW MODE BEFORE RENDER: ink's kittyKeyboard auto-detect sends its `CSI ? u`
117
+ // query from the Ink constructor, but raw mode only turns on later when
118
+ // useInput mounts. In that window the terminal's `CSI ? 0 u` reply is echoed
119
+ // by termios (ECHOCTL) as literal `^[[?0u` into the first frame (his repro).
120
+ // Raw mode off = echo on, so flip it ourselves first (inside the try so the
121
+ // finally always restores); ink owns it afterwards and restores cooked mode
122
+ // on exit.
86
123
  // REAL images over the preview panel rect on OSC-1337 terminals (repaints
87
124
  // after every stdout flush + on image change — NOT a React effect)
88
125
  const uninstallPainter = installProtocolImagePainter(st)
89
126
  try {
127
+ if (process.stdin.isTTY === true) process.stdin.setRawMode(true)
90
128
  // kittyKeyboard auto: ink queries `CSI ? u` and enables CSI-u encoding
91
129
  // where supported (iTerm2 3.5+/WezTerm/kitty/ghostty) — ⇧⏎ parsed natively
92
130
  const app = render(<TuiApp st={st} />, { kittyKeyboard: { mode: 'auto' } })
@@ -95,6 +133,8 @@ export async function runTui(args: string[]): Promise<number> {
95
133
  await app.waitUntilExit()
96
134
  st.dispose()
97
135
  } finally {
136
+ // ink restores cooked mode on clean exit; this covers a throw before mount
137
+ if (process.stdin.isTTY === true) process.stdin.setRawMode(false)
98
138
  uninstallPainter()
99
139
  // reset colors + erase WHILE STILL in the alt screen: ED deletes iTerm
100
140
  // inline images too — without this the last protocol image and stray
@@ -9,13 +9,14 @@ import {
9
9
  writeFileSync,
10
10
  } from 'node:fs'
11
11
  import { makeAutoObservable, reaction } from 'mobx'
12
- import { basename, dirname, join } from 'pathe'
12
+ import { dirname, join } from 'pathe'
13
+ import { moduleName } from 'src/cli/tui/treeRows.ts'
13
14
  import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
14
15
  import type { TuiMode, TuiSt } from 'src/cli/tui/state/TuiSt.ts'
15
16
 
16
17
  /** module basename (`01-txt2img`) keys the draft folder — knowable for EVERY tree file without importing it */
17
18
  export function draftKeyForFile(file: string): string {
18
- return basename(file).replace(/\.cflow\.tsx?$/, '')
19
+ return moduleName(file)
19
20
  }
20
21
 
21
22
  export function draftsDirForFile(file: string): string {