comfy-ts 1.2.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 (42) hide show
  1. package/README.md +40 -0
  2. package/dist/DefinedWorkflow-gpknV-5f.js +686 -0
  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 +15 -5
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +132 -21
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +5 -0
  11. package/dist/index.d.ts +23 -18
  12. package/dist/index.js +132 -21
  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-BAdizWsO.js → run-tui-BtjaOXRh.js} +244 -440
  17. package/dist/run-tui-BtjaOXRh.js.map +1 -0
  18. package/dist/{state-BYbxDgfr.js → state-DKCPy105.js} +130 -698
  19. package/dist/state-DKCPy105.js.map +1 -0
  20. package/package.json +3 -2
  21. package/src/cli/comfy-ts-cli.ts +15 -5
  22. package/src/cli/serve/ServeApp.ts +378 -0
  23. package/src/cli/serve/applyVarPayload.ts +119 -0
  24. package/src/cli/serve/describeVar.ts +74 -0
  25. package/src/cli/serve/run-serve.ts +169 -0
  26. package/src/cli/tui/components/StatusBar.tsx +1 -0
  27. package/src/cli/tui/components/TreePanel.tsx +17 -3
  28. package/src/cli/tui/components/TuiApp.tsx +7 -2
  29. package/src/cli/tui/components/VarsPanel.tsx +67 -34
  30. package/src/cli/tui/imageClipboard.ts +39 -0
  31. package/src/cli/tui/listWindow.ts +36 -0
  32. package/src/cli/tui/state/ExecSt.ts +48 -0
  33. package/src/cli/tui/state/TreeSt.ts +25 -0
  34. package/src/cli/tui/state/TuiSt.ts +34 -0
  35. package/src/litegraph/convertFlowToLiteGraphJSON.ts +11 -7
  36. package/src/runner/ComfyExecution.ts +21 -4
  37. package/src/runner/outputPath.ts +75 -0
  38. package/src/sdk-generator/inputWidgetKind.ts +50 -11
  39. package/src/sdk-generator/litegraphToApiRequestPayload.ts +14 -7
  40. package/src/vars/ComfyVars.ts +8 -0
  41. package/dist/run-tui-BAdizWsO.js.map +0 -1
  42. package/dist/state-BYbxDgfr.js.map +0 -1
@@ -0,0 +1,169 @@
1
+ // `comfy-ts serve [dir | module.cflow.ts] [--port N] [--bind ADDR]`
2
+ // drafts as a local HTTP generation API — agent/architecture.md item 12
3
+ import { statSync } from 'node:fs'
4
+ import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
5
+ import { pathToFileURL } from 'node:url'
6
+ import { resolve } from 'pathe'
7
+ import { scanCflowFiles } from 'src/cli/tui/discoverWorkflows.ts'
8
+ import { findDefinedWorkflow } from 'src/cli/tui/findDefinedWorkflow.ts'
9
+ import { draftKeyForFile } from 'src/cli/tui/state/DraftsSt.ts'
10
+ import { describeVar, renderDescriptorLine } from 'src/cli/serve/describeVar.ts'
11
+ import { ServeApp, type ServeModule } from 'src/cli/serve/ServeApp.ts'
12
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
13
+
14
+ const DEFAULT_PORT = 8288
15
+ const BODY_CAP = 10_000_000
16
+
17
+ function parseArgs(args: string[]): { target?: string; port: number; bind: string } | { error: string } {
18
+ let target: string | undefined
19
+ let port = DEFAULT_PORT
20
+ let bind = '127.0.0.1'
21
+ for (let i = 0; i < args.length; i++) {
22
+ const a = args[i]
23
+ if (a === '--port') {
24
+ const n = Number(args[++i])
25
+ if (!Number.isInteger(n) || n <= 0 || n > 65535) return { error: `--port expects 1..65535, got '${args[i]}'` }
26
+ port = n
27
+ } else if (a === '--bind') {
28
+ const b = args[++i]
29
+ if (b == null) return { error: '--bind expects an address' }
30
+ bind = b
31
+ } else if (a != null && a.startsWith('--')) return { error: `unknown flag '${a}'` }
32
+ else if (a != null) {
33
+ if (target != null) return { error: `one target only (got '${target}' and '${a}')` }
34
+ target = a
35
+ }
36
+ }
37
+ return { target, port, bind }
38
+ }
39
+
40
+ /** node:http glue around ServeApp.handle — exported so tests can drive a real socket */
41
+ export function makeRequestListener(app: ServeApp): (req: IncomingMessage, res: ServerResponse) => void {
42
+ return (req, res) => {
43
+ // local bridge, no auth by design: open CORS so browser frontends can call it
44
+ const cors = {
45
+ 'access-control-allow-origin': '*',
46
+ 'access-control-allow-methods': 'GET, POST, OPTIONS',
47
+ 'access-control-allow-headers': 'content-type, accept',
48
+ }
49
+ const chunks: Buffer[] = []
50
+ let size = 0
51
+ let overflow = false
52
+ req.on('error', (e) => console.error(`[serve] request stream error: ${extractErrorMessage(e)}`))
53
+ req.on('data', (c: Buffer) => {
54
+ if (overflow) return
55
+ size += c.length
56
+ if (size > BODY_CAP) {
57
+ // answer NOW: a destroyed request never emits 'end'
58
+ overflow = true
59
+ res.writeHead(413, { 'content-type': 'application/json', ...cors })
60
+ res.end(JSON.stringify({ error: 'payload too large' }), () => req.destroy())
61
+ } else chunks.push(c)
62
+ })
63
+ req.on('end', () => {
64
+ if (overflow) return
65
+ if (req.method === 'OPTIONS') {
66
+ res.writeHead(204, cors)
67
+ res.end()
68
+ return
69
+ }
70
+ app.handle({
71
+ method: req.method ?? 'GET',
72
+ url: req.url ?? '/',
73
+ accept: req.headers.accept,
74
+ body: Buffer.concat(chunks).toString('utf8'),
75
+ })
76
+ .then((reply) => {
77
+ res.writeHead(reply.status, { 'content-type': reply.contentType, ...cors })
78
+ res.end(reply.body)
79
+ })
80
+ .catch((e: unknown) => {
81
+ // handle() catches internally; this guards the response write itself
82
+ console.error(`[serve] response write failed: ${extractErrorMessage(e)}`)
83
+ res.destroy()
84
+ })
85
+ })
86
+ }
87
+ }
88
+
89
+ export async function runServe(args: string[]): Promise<number> {
90
+ const parsed = parseArgs(args)
91
+ if ('error' in parsed) {
92
+ console.error(`[comfy-ts serve] ${parsed.error}`)
93
+ return 1
94
+ }
95
+
96
+ // discovery: explicit file → that module only; dir/no-arg → scan, WITHOUT
97
+ // the bundled examples (serve is for the user's tuned drafts)
98
+ const target = resolve(parsed.target ?? '.')
99
+ let files: string[]
100
+ try {
101
+ files = statSync(target).isDirectory() ? scanCflowFiles(target) : [target]
102
+ } catch {
103
+ console.error(`[comfy-ts serve] no such file or directory: ${target}`)
104
+ return 1
105
+ }
106
+ if (files.length === 0) {
107
+ console.error(`[comfy-ts serve] no *.cflow.ts modules under ${target}`)
108
+ return 1
109
+ }
110
+
111
+ const modules: ServeModule[] = []
112
+ const loadErrors: Record<string, string> = {}
113
+ for (const file of files) {
114
+ try {
115
+ const mod: Record<string, unknown> = await import(pathToFileURL(file).href)
116
+ const dw = findDefinedWorkflow(mod)
117
+ if (dw == null) throw new Error('exports no DefinedWorkflow')
118
+ const key = draftKeyForFile(file)
119
+ const clash = modules.find((m) => m.key === key)
120
+ if (clash != null) throw new Error(`module key '${key}' already taken by ${clash.file}`)
121
+ modules.push({ key, file, dw })
122
+ } catch (e) {
123
+ loadErrors[file] = extractErrorMessage(e)
124
+ console.error(`[comfy-ts serve] ✗ ${file}: ${loadErrors[file]}`)
125
+ }
126
+ }
127
+ if (modules.length === 0) {
128
+ console.error('[comfy-ts serve] every module failed to load — nothing to serve')
129
+ return 1
130
+ }
131
+
132
+ const app = new ServeApp(modules, { loadErrors })
133
+ printStartup(app, parsed.bind, parsed.port)
134
+
135
+ const server = createServer(makeRequestListener(app))
136
+
137
+ server.on('error', (e) => {
138
+ console.error(`[comfy-ts serve] server error: ${extractErrorMessage(e)}`)
139
+ process.exitCode = 1
140
+ server.close()
141
+ })
142
+ server.listen(parsed.port, parsed.bind)
143
+
144
+ // stays up until the process is interrupted or the server dies
145
+ return new Promise<number>((resolveExit) => {
146
+ server.on('close', () => resolveExit(typeof process.exitCode === 'number' ? process.exitCode : 0))
147
+ })
148
+ }
149
+
150
+ function printStartup(app: ServeApp, bind: string, port: number): void {
151
+ const base = `http://${bind}:${port}`
152
+ console.log(`comfy-ts serve · ${app.modules.length} workflow(s) · ${base}/`)
153
+ if (bind !== '127.0.0.1' && bind !== 'localhost')
154
+ console.log(`⚠️ bound to ${bind} — this API has NO AUTH and runs workflows on your ComfyUI host`)
155
+ for (const mod of app.modules) {
156
+ console.log(`\n${mod.key} (host: ${mod.dw.host.data.id})`)
157
+ for (const draft of app.draftsFor(mod))
158
+ console.log(` POST ${base}/generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(draft)}`)
159
+ const entries = mod.dw.entries()
160
+ const nameWidth = Math.max(...entries.map(([n]) => n.length), 4)
161
+ for (const [name, varDef] of entries) console.log(renderDescriptorLine(name, describeVar(varDef), nameWidth))
162
+ }
163
+ const firstMod = app.modules[0]
164
+ if (firstMod != null)
165
+ console.log(
166
+ `\ntry: curl -X POST ${base}/generate/${encodeURIComponent(firstMod.key)}/default -H 'content-type: application/json' -d '{}'`,
167
+ )
168
+ console.log(`docs: GET ${base}/drafts (json index of everything above)`)
169
+ }
@@ -182,6 +182,7 @@ export const KeyBar = observer((p: { st: TuiSt }) => {
182
182
  // the preview panel carries `p` in its title — unless it is hidden
183
183
  ...(s.preview.show || s.mode === 'preview' ? [] : ([['p', 'preview (off)']] as Hint[])),
184
184
  ['o', 'open image'],
185
+ ['i', 'copy image'],
185
186
  // c is duplicate inside the tree — don't advertise the copy pair
186
187
  // there; the preview menu doesn't forward it either
187
188
  ...(s.mode === 'tree' || s.mode === 'preview' ? [] : ([['c/C', 'copy wf/api']] as Hint[])),
@@ -1,21 +1,32 @@
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 type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
4
6
 
5
7
  /** persistent left panel: directory hierarchy + workflows with their drafts
6
- * nested; `t` (or ← from vars) focuses it, `/` filters it */
8
+ * nested; `t` (or ← from vars) focuses it, `/` filters it. The Box is
9
+ * measured (keybar wraps, chrome height is width-dependent — arithmetic
10
+ * lies) and the row list windows to the measured budget; overflow hidden
11
+ * is the backstop for the one pre-measure frame. */
7
12
  export const TreePanel = observer((p: { st: TuiSt }) => {
8
13
  const s = p.st
9
14
  const tree = s.tree
10
15
  const focused = s.mode === 'tree'
16
+ const boxRef = useRef<DOMElement>(null)
17
+ useEffect(() => {
18
+ if (boxRef.current != null) tree.setViewH(measureElement(boxRef.current).height)
19
+ })
11
20
  return (
12
21
  <Box
22
+ ref={boxRef}
13
23
  borderStyle="round"
14
24
  borderColor={focused ? 'cyan' : 'gray'}
15
25
  flexDirection="column"
16
26
  flexShrink={0}
17
27
  width={s.treeWidth}
18
28
  paddingX={1}
29
+ overflow="hidden"
19
30
  >
20
31
  {/* marginTop -1 lifts the label onto the border line: the panel key IS its title */}
21
32
  <Box marginTop={-1}>
@@ -29,7 +40,9 @@ export const TreePanel = observer((p: { st: TuiSt }) => {
29
40
  {tree.filtering ? '▌' : ''}
30
41
  </Text>
31
42
  )}
32
- {tree.rows.map((row, ix) => {
43
+ {tree.window.moreAbove && <Text color="gray">…</Text>}
44
+ {tree.rows.slice(tree.window.start, tree.window.end).map((row, sliceIx) => {
45
+ const ix = tree.window.start + sliceIx
33
46
  const sel = focused && ix === tree.ix
34
47
  const indent = ' '.repeat(row.depth * 2)
35
48
  if (row.kind === 'dir') {
@@ -68,6 +81,7 @@ export const TreePanel = observer((p: { st: TuiSt }) => {
68
81
  </Text>
69
82
  )
70
83
  })}
84
+ {tree.window.moreBelow && <Text color="gray">…</Text>}
71
85
  {s.workflows.loading ? <Text color="yellow">loading…</Text> : null}
72
86
  </Box>
73
87
  )
@@ -150,6 +150,7 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
150
150
  if (input === 'a') return s.host.begin()
151
151
  if (input === 'p') return s.preview.beginMenu()
152
152
  if (input === 'o') return s.exec.openLastOutput()
153
+ if (input === 'i') return void s.exec.copyLastImage()
153
154
  if (input === 'q') {
154
155
  s.onExit()
155
156
  return app.exit()
@@ -198,6 +199,7 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
198
199
  if (input === 'h') return s.host.beginPicker()
199
200
  if (input === 'a') return s.host.begin()
200
201
  if (input === 'o') return s.exec.openLastOutput()
202
+ if (input === 'i') return void s.exec.copyLastImage()
201
203
  if (input === 'q') {
202
204
  s.onExit()
203
205
  return app.exit()
@@ -244,6 +246,7 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
244
246
  if (input === 'd') return s.drafts.begin()
245
247
  if (input === 'p') return s.preview.beginMenu()
246
248
  if (input === 'o') return s.exec.openLastOutput()
249
+ if (input === 'i') return void s.exec.copyLastImage()
247
250
  if (input === 'c') return void s.exec.copyWorkflowJson()
248
251
  if (input === 'C') return void s.exec.copyApiJson()
249
252
  },
@@ -254,9 +257,11 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
254
257
  )
255
258
 
256
259
  return (
257
- <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}>
258
263
  <Header st={s} />
259
- <Box flexDirection="row" flexGrow={1}>
264
+ <Box flexDirection="row" flexGrow={1} flexShrink={1} overflow="hidden">
260
265
  <TreePanel st={s} />
261
266
  <Box flexDirection="column" flexGrow={1}>
262
267
  {/* ink has no z-order: the overlay replaces the vars panel while open */}
@@ -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
+ }
@@ -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
+ }
@@ -3,6 +3,7 @@ import { makeAutoObservable, runInAction } from 'mobx'
3
3
  import { basename } from 'pathe'
4
4
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
5
5
  import type { ExecutionProgress } from 'src/runner/ComfyExecution.ts'
6
+ import { imageClipboardCommand } from 'src/cli/tui/imageClipboard.ts'
6
7
  import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
7
8
  import type { SeedVar } from 'src/vars/ComfyVars.ts'
8
9
  import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
@@ -168,6 +169,53 @@ export class ExecSt {
168
169
  this.copyPopup = { title, ok, lines }
169
170
  this.st.mode = 'overlay-copy'
170
171
  }
172
+ /** 'i': the LAST generated image's pixels → clipboard (paste anywhere) */
173
+ async copyLastImage(): Promise<void> {
174
+ const last = this.outputs[this.outputs.length - 1]
175
+ if (last == null) {
176
+ this.showCopyPopup('image → clipboard', false, ['no output image yet — r runs the workflow first'])
177
+ return
178
+ }
179
+ let file = last
180
+ let command = imageClipboardCommand(process.platform, file)
181
+ if (command == null && process.platform === 'darwin') {
182
+ // osascript only tags bytes — webp/etc must become real png first
183
+ try {
184
+ const { default: sharp } = await import('sharp')
185
+ const { tmpdir } = await import('node:os')
186
+ const { join } = await import('pathe')
187
+ file = join(tmpdir(), `comfy-ts-clip-${Date.now()}.png`)
188
+ await sharp(last).png().toFile(file)
189
+ command = imageClipboardCommand(process.platform, file)
190
+ } catch (e) {
191
+ this.showCopyPopup('image → clipboard', false, [
192
+ `COPY FAILED for ${basename(last)}`,
193
+ `png transcode failed: ${extractErrorMessage(e)}`,
194
+ ])
195
+ return
196
+ }
197
+ }
198
+ if (command == null) {
199
+ this.showCopyPopup('image → clipboard', false, [`no clipboard image tool for ${process.platform}`])
200
+ return
201
+ }
202
+ const cmd = command
203
+ const ok = await new Promise<boolean>((resolve) => {
204
+ const proc = spawn(cmd.cmd, cmd.args, { stdio: 'ignore' })
205
+ proc.on('error', () => resolve(false))
206
+ proc.on('close', (code) => resolve(code === 0))
207
+ })
208
+ runInAction(() => {
209
+ this.showCopyPopup(
210
+ 'image → clipboard',
211
+ ok,
212
+ ok
213
+ ? [`${basename(last)} — paste the pixels anywhere`, '', last]
214
+ : [`COPY FAILED for ${basename(last)}`, `could not run ${cmd.cmd} — is it installed and allowed ?`],
215
+ )
216
+ })
217
+ }
218
+
171
219
  private toClipboard(text: string): Promise<boolean> {
172
220
  const [cmd, ...args] =
173
221
  process.platform === 'darwin'
@@ -1,5 +1,6 @@
1
1
  import { makeAutoObservable } from 'mobx'
2
2
  import { listDraftsForFile } from 'src/cli/tui/state/DraftsSt.ts'
3
+ import { listWindow, type ListWindow } from 'src/cli/tui/listWindow.ts'
3
4
  import { assignFamilyColors, buildFileRows, familyOf } from 'src/cli/tui/treeRows.ts'
4
5
  import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
5
6
 
@@ -119,6 +120,30 @@ export class TreeSt {
119
120
  this.ix = ix === -1 ? 0 : ix
120
121
  }
121
122
 
123
+ // ---- viewport (his small-terminal overflow repro 2026-07-31) ----
124
+
125
+ /** measured height of the tree panel Box (TreePanel measureElement); 0 = not measured yet */
126
+ viewH: number = 0
127
+ setViewH(h: number): void {
128
+ this.viewH = h
129
+ }
130
+
131
+ /** rows available for tree content: measured panel height minus the panel's
132
+ * own chrome (2 border rows, the filter line when visible, the loading
133
+ * line). Pre-measure fallback: termRows minus the header+keybar estimate —
134
+ * one frame only, the measurement replaces it. */
135
+ get viewBudget(): number {
136
+ const h = this.viewH > 0 ? this.viewH : Math.max(5, this.st.termRows - 5)
137
+ const filterLine = this.filtering || this.filter !== '' ? 1 : 0
138
+ const loadingLine = this.st.workflows.loading ? 1 : 0
139
+ return Math.max(1, h - 2 - filterLine - loadingLine)
140
+ }
141
+
142
+ /** the visible slice, selection always inside, markers within the budget */
143
+ get window(): ListWindow {
144
+ return listWindow({ count: this.rows.length, selected: this.ix, budget: this.viewBudget })
145
+ }
146
+
122
147
  /** esc/t inside the tree, → on a draft row, `v` anywhere: back to the vars list */
123
148
  blur(): void {
124
149
  this.filtering = false
@@ -1,4 +1,5 @@
1
1
  import { makeAutoObservable, observable, runInAction } from 'mobx'
2
+ import { listWindow, type ListWindow } from 'src/cli/tui/listWindow.ts'
2
3
  import type { SeedVar, ToggleVar, AnyVar } from 'src/vars/ComfyVars.ts'
3
4
  import { ImagePickerSt } from 'src/cli/tui/imagePicker/ImagePickerSt.ts'
4
5
  import { DraftsSt } from 'src/cli/tui/state/DraftsSt.ts'
@@ -206,6 +207,39 @@ export class TuiSt {
206
207
  this.selIx = (this.selIx + delta + len) % len
207
208
  }
208
209
 
210
+ // ---- vars viewport (reviewer follow-up 2026-07-31: the fixed-height
211
+ // frame clips instead of overflowing, so the vars list must window like
212
+ // the tree — measured height, never chrome arithmetic) ----
213
+
214
+ /** measured height of the vars panel Box (VarsPanel measureElement); 0 = not measured yet */
215
+ varsViewH: number = 0
216
+ setVarsViewH(h: number): void {
217
+ this.varsViewH = h
218
+ }
219
+
220
+ /** row budget: measured height minus the 2 border rows; pre-measure fallback estimate */
221
+ get varsBudget(): number {
222
+ const h = this.varsViewH > 0 ? this.varsViewH : Math.max(5, this.termRows - 5)
223
+ return Math.max(1, h - 2)
224
+ }
225
+
226
+ get varsWindow(): ListWindow {
227
+ return listWindow({ count: this.entries.length, selected: this.selIx, budget: this.varsBudget })
228
+ }
229
+
230
+ /**
231
+ * while the list cannot fit, NON-selected rows collapse to one truncated
232
+ * line (prompt values wrap tall) — rows above the selection then cost one
233
+ * line each, so the selection can never be pushed off-screen. Reads only
234
+ * entry count + measured height, never its own rendering: no oscillation.
235
+ */
236
+ get varsCompact(): boolean {
237
+ const w = this.varsWindow
238
+ if (w.moreAbove || w.moreBelow) return true
239
+ const h = this.varsViewH > 0 ? this.varsViewH : Math.max(5, this.termRows - 5)
240
+ return this.entries.length + 2 > h
241
+ }
242
+
209
243
  // kind-discriminated narrowing casts below are sanctioned (agent/coding.md):
210
244
  // ComfyVar<T> value-invariance blocks a clean union, `kind` is the tag.
211
245
 
@@ -1,7 +1,7 @@
1
1
  import type { ComfyNode } from 'src/graph/ComfyNode.ts'
2
2
  import type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'
3
3
  import { bang } from 'src/utils/bang.ts'
4
- import { howManyWidgetValuesForThisSchemaType } from 'src/sdk-generator/inputWidgetKind.ts'
4
+ import { classifySchemaInput } from 'src/sdk-generator/inputWidgetKind.ts'
5
5
  import type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
6
6
  import type { LiteGraphLinkTuple } from 'src/litegraph/LiteGraphLink.ts'
7
7
  import { asLiteGraphLinkID, type LiteGraphLinkID } from 'src/litegraph/LiteGraphLinkID.ts'
@@ -42,7 +42,7 @@ const convertNodeToLiteGraphNode = (ctx: LiteGraphCtx, node: ComfyNode<any>): Li
42
42
  const widgets_values: unknown[] = []
43
43
  for (const ipt of node.$schema.inputs) {
44
44
  const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy])
45
- const isWidget = howManyWidgetValuesForThisSchemaType(ipt) > 0
45
+ const kind = classifySchemaInput(ipt)
46
46
  if (_isLink(raw)) {
47
47
  const nodeUidNumber = bang(
48
48
  ctx.graph.nodes.find((n) => n.uid === raw[0])?.uidNumber,
@@ -61,11 +61,15 @@ const convertNodeToLiteGraphNode = (ctx: LiteGraphCtx, node: ComfyNode<any>): Li
61
61
  ipt.typeName,
62
62
  ),
63
63
  })
64
- } else if (isWidget) {
65
- widgets_values.push(raw)
66
- // ComfyUI stores a phantom control_after_generate value after seeds
67
- const isSeed = ipt.typeName === 'INT' && (ipt.nameInComfy === 'seed' || ipt.nameInComfy === 'noise_seed')
68
- if (isSeed) widgets_values.push(false)
64
+ } else if (kind.kind === 'widget') {
65
+ // frontend button-widget values ride BEFORE the real value (LOAD_3D)
66
+ widgets_values.push(...kind.prefixValues, raw)
67
+ // control_after_generate phantom AFTER the value: the classifier's
68
+ // consumes covers prefix + value + control, config-driven (the 2024
69
+ // INT-named-seed heuristic lives inside controlConsumes), so export
70
+ // and import can never disagree on the run length
71
+ const phantoms = kind.consumes - 1 - kind.prefixValues.length
72
+ for (let i = 0; i < phantoms; i++) widgets_values.push(false)
69
73
  } else {
70
74
  // unconnected link-kind input: a litegraph slot with no link —
71
75
  // NEVER a widget value (that would misalign the round-trip import)