comfy-ts 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +66 -0
  2. package/dist/DefinedWorkflow-C_QAxKr3.js +737 -0
  3. package/dist/DefinedWorkflow-C_QAxKr3.js.map +1 -0
  4. package/dist/DraftsSt-DcOTn0QR.js +434 -0
  5. package/dist/DraftsSt-DcOTn0QR.js.map +1 -0
  6. package/dist/cli.js +15 -5
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +476 -202
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +98 -40
  11. package/dist/index.d.ts +117 -59
  12. package/dist/index.js +468 -193
  13. package/dist/index.js.map +1 -1
  14. package/dist/run-serve-CN0DhrsA.js +638 -0
  15. package/dist/run-serve-CN0DhrsA.js.map +1 -0
  16. package/dist/{run-tui-BAdizWsO.js → run-tui-bN2hSD5i.js} +250 -447
  17. package/dist/run-tui-bN2hSD5i.js.map +1 -0
  18. package/dist/state-COlKYipO.js +4743 -0
  19. package/dist/state-COlKYipO.js.map +1 -0
  20. package/dist/web.d.ts +17340 -0
  21. package/dist/{state-BYbxDgfr.js → web.js} +1903 -1592
  22. package/dist/web.js.map +1 -0
  23. package/examples/web/example.ts +71 -0
  24. package/examples/web/index.html +77 -0
  25. package/examples/web/serve.ts +42 -0
  26. package/examples/web/tsconfig.json +15 -0
  27. package/package.json +10 -3
  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/StatusBar.tsx +1 -0
  34. package/src/cli/tui/components/TreePanel.tsx +17 -3
  35. package/src/cli/tui/components/TuiApp.tsx +7 -2
  36. package/src/cli/tui/components/VarsPanel.tsx +67 -34
  37. package/src/cli/tui/imageClipboard.ts +39 -0
  38. package/src/cli/tui/listWindow.ts +36 -0
  39. package/src/cli/tui/state/ExecSt.ts +48 -0
  40. package/src/cli/tui/state/TreeSt.ts +25 -0
  41. package/src/cli/tui/state/TuiSt.ts +34 -0
  42. package/src/coreExports.ts +118 -0
  43. package/src/host/ComfyHost.ts +23 -23
  44. package/src/host/ResilientWebsocket.ts +93 -47
  45. package/src/host/hostUrl.ts +2 -1
  46. package/src/host/loraManagerApi.ts +6 -7
  47. package/src/index.ts +8 -107
  48. package/src/litegraph/convertFlowToLiteGraphJSON.ts +11 -7
  49. package/src/manager/loaders/step2_custom-node-list-loader.ts +4 -4
  50. package/src/manager/loaders/step3_extension-node-map-loader.ts +3 -3
  51. package/src/manager/loaders/step4_model-list-loader.ts +7 -7
  52. package/src/manager/loaders/step5_alter-list-loader.ts +2 -2
  53. package/src/manager/loaders/step6_github-stats-loader.ts +2 -2
  54. package/src/runner/ComfyExecution.ts +32 -12
  55. package/src/runner/MediaImage.ts +18 -30
  56. package/src/runner/outputPath.ts +75 -0
  57. package/src/sdk-generator/ComfySchema.ts +2 -2
  58. package/src/sdk-generator/inputWidgetKind.ts +50 -11
  59. package/src/sdk-generator/litegraphToApiRequestPayload.ts +14 -7
  60. package/src/state.ts +13 -9
  61. package/src/storage/ComfyStorage.ts +144 -0
  62. package/src/storage/nodeStorage.ts +9 -0
  63. package/src/utils/downloadFile.ts +11 -69
  64. package/src/utils/hashArrayBuffer.ts +3 -4
  65. package/src/utils/lazySharp.ts +25 -0
  66. package/src/utils/sha1.ts +69 -0
  67. package/src/vars/ComfyVars.ts +13 -6
  68. package/src/vars/loraKeywords.ts +6 -6
  69. package/src/web.ts +13 -0
  70. package/dist/run-tui-BAdizWsO.js.map +0 -1
  71. package/dist/state-BYbxDgfr.js.map +0 -1
  72. package/src/utils/writeFile.ts +0 -16
@@ -0,0 +1,119 @@
1
+ // PURE payload → var application: one POST body value onto one var, per kind.
2
+ // Returns an error message (nothing applied) or null. No fs here — ImageVar
3
+ // url download + existence checks are ServeApp's job.
4
+ import {
5
+ type AnyVar,
6
+ ChoiceVar,
7
+ FloatVar,
8
+ ImageVar,
9
+ IntVar,
10
+ type LoraStrength,
11
+ LorasVar,
12
+ PromptVar,
13
+ SeedVar,
14
+ SizeVar,
15
+ TextVar,
16
+ ToggleVar,
17
+ } from 'src/vars/ComfyVars.ts'
18
+
19
+ function isFiniteNumber(x: unknown): x is number {
20
+ return typeof x === 'number' && Number.isFinite(x)
21
+ }
22
+
23
+ function isLoraStrength(x: unknown): x is LoraStrength {
24
+ if (typeof x === 'boolean') return true
25
+ if (isFiniteNumber(x)) return true
26
+ return Array.isArray(x) && x.length === 2 && isFiniteNumber(x[0]) && isFiniteNumber(x[1])
27
+ }
28
+
29
+ /** cap long option lists in error messages */
30
+ function listSome(items: readonly string[], cap: number = 20): string {
31
+ if (items.length <= cap) return items.join(', ')
32
+ return `${items.slice(0, cap).join(', ')} … +${items.length - cap} more`
33
+ }
34
+
35
+ export function applyVarPayload(varDef: AnyVar, raw: unknown): string | null {
36
+ const name = varDef.name ?? varDef.label ?? varDef.kind
37
+
38
+ if (varDef instanceof TextVar || varDef instanceof PromptVar) {
39
+ if (typeof raw !== 'string') return `var '${name}' expects a string`
40
+ varDef.set(raw)
41
+ return null
42
+ }
43
+
44
+ if (varDef instanceof IntVar || varDef instanceof FloatVar) {
45
+ if (isFiniteNumber(raw)) {
46
+ varDef.set(raw) // set() clamps to min/max
47
+ return null
48
+ }
49
+ if (typeof raw === 'string' && varDef.parse(raw)) return null
50
+ const o = varDef.opts
51
+ const range = o.min == null && o.max == null ? '' : ` (${o.min ?? '-∞'}..${o.max ?? '∞'})`
52
+ return `var '${name}' expects a number${range}`
53
+ }
54
+
55
+ if (varDef instanceof SeedVar) {
56
+ if (isFiniteNumber(raw)) {
57
+ // an explicit payload seed is FIXED for this request
58
+ varDef.setMode('=')
59
+ varDef.set(raw)
60
+ return null
61
+ }
62
+ if (raw != null && typeof raw === 'object' && !Array.isArray(raw)) {
63
+ const o = raw as { mode?: unknown; value?: unknown }
64
+ const mode = o.mode === '=' || o.mode === '+' || o.mode === '-' || o.mode === '?' ? o.mode : null
65
+ if (o.mode !== undefined && mode == null) return `var '${name}': mode must be one of = + - ?`
66
+ if (o.value !== undefined && !isFiniteNumber(o.value)) return `var '${name}': value must be a number`
67
+ if (mode == null && o.value === undefined) return `var '${name}': give "mode" and/or "value"`
68
+ if (mode != null) varDef.setMode(mode)
69
+ if (isFiniteNumber(o.value)) varDef.set(o.value)
70
+ return null
71
+ }
72
+ return `var '${name}' expects a number or {"mode":"=|+|-|?","value":number}`
73
+ }
74
+
75
+ if (varDef instanceof ToggleVar) {
76
+ if (typeof raw !== 'boolean') return `var '${name}' expects true or false`
77
+ varDef.set(raw)
78
+ return null
79
+ }
80
+
81
+ if (varDef instanceof ChoiceVar) {
82
+ if (typeof raw === 'string' && varDef.parse(raw)) return null
83
+ return `var '${name}' expects one of: ${listSome(varDef.choices)}`
84
+ }
85
+
86
+ if (varDef instanceof LorasVar) {
87
+ if (raw == null || typeof raw !== 'object' || Array.isArray(raw))
88
+ return `var '${name}' expects {"<lora name>": false | true | strength | [model, clip]}`
89
+ const record = raw as Record<string, unknown>
90
+ const known = new Set<string>(varDef.options)
91
+ const unknownNames = Object.keys(record).filter((k) => !known.has(k))
92
+ if (unknownNames.length > 0)
93
+ return `var '${name}': unknown lora(s) ${unknownNames.join(', ')} — available: ${listSome(varDef.options)}`
94
+ for (const [k, s] of Object.entries(record))
95
+ if (!isLoraStrength(s)) return `var '${name}': '${k}' must be false | true | number | [model, clip]`
96
+ varDef.set(record as Partial<Record<string, LoraStrength>>) // every entry validated just above
97
+ return null
98
+ }
99
+
100
+ if (varDef instanceof SizeVar) {
101
+ if (typeof raw === 'string' && varDef.parse(raw)) return null
102
+ if (raw != null && typeof raw === 'object' && !Array.isArray(raw)) {
103
+ const o = raw as { width?: unknown; height?: unknown }
104
+ if (isFiniteNumber(o.width) && isFiniteNumber(o.height)) {
105
+ varDef.set({ width: o.width, height: o.height })
106
+ return null
107
+ }
108
+ }
109
+ return `var '${name}' expects {"width":W,"height":H}, "WxH", or a preset label`
110
+ }
111
+
112
+ if (varDef instanceof ImageVar) {
113
+ if (typeof raw !== 'string') return `var '${name}' expects a file path or http(s) url string`
114
+ varDef.set(raw)
115
+ return null
116
+ }
117
+
118
+ return `var '${name}' has unsupported kind '${varDef.kind}'`
119
+ }
@@ -0,0 +1,74 @@
1
+ // PURE var → descriptor: ONE introspection pass feeds GET /drafts (json) AND
2
+ // the startup print (renderDescriptorLine)
3
+ import {
4
+ type AnyVar,
5
+ ChoiceVar,
6
+ FloatVar,
7
+ ImageVar,
8
+ IntVar,
9
+ LorasVar,
10
+ PromptVar,
11
+ SeedVar,
12
+ SizeVar,
13
+ type SizePreset,
14
+ type VarKind,
15
+ } from 'src/vars/ComfyVars.ts'
16
+
17
+ export type VarDescriptor = {
18
+ kind: VarKind
19
+ label?: string
20
+ /** what a POST payload accepts for this var, human-readable */
21
+ payload: string
22
+ default: unknown
23
+ choices?: readonly string[]
24
+ /** loras: the resolved option list */
25
+ options?: readonly string[]
26
+ min?: number
27
+ max?: number
28
+ presets?: SizePreset[]
29
+ extensions?: readonly string[]
30
+ }
31
+
32
+ function rangeText(opts: { min?: number; max?: number }): string {
33
+ if (opts.min == null && opts.max == null) return ''
34
+ return ` (${opts.min ?? '-∞'}..${opts.max ?? '∞'})`
35
+ }
36
+
37
+ export function describeVar(varDef: AnyVar): VarDescriptor {
38
+ const base = { kind: varDef.kind, label: varDef.label, default: varDef.defaultValue }
39
+ if (varDef instanceof PromptVar) return { ...base, payload: 'string ("//" lines = comments, "- " lines = negative)' }
40
+ if (varDef instanceof IntVar)
41
+ return { ...base, payload: `integer${rangeText(varDef.opts)}`, min: varDef.opts.min, max: varDef.opts.max }
42
+ if (varDef instanceof FloatVar)
43
+ return { ...base, payload: `number${rangeText(varDef.opts)}`, min: varDef.opts.min, max: varDef.opts.max }
44
+ if (varDef instanceof SeedVar)
45
+ return {
46
+ ...base,
47
+ default: { mode: varDef.mode, value: varDef.defaultValue },
48
+ payload: 'number (fixed) or {"mode":"=|+|-|?","value":number}',
49
+ }
50
+ if (varDef.kind === 'toggle') return { ...base, payload: 'true or false' }
51
+ if (varDef instanceof ChoiceVar)
52
+ return { ...base, payload: `one of: ${varDef.choices.join(' | ')}`, choices: varDef.choices }
53
+ if (varDef instanceof LorasVar)
54
+ return {
55
+ ...base,
56
+ payload: '{"<lora name>": false | true | strength | [model, clip]}',
57
+ options: varDef.options,
58
+ }
59
+ if (varDef instanceof SizeVar)
60
+ return { ...base, payload: '{"width":W,"height":H} or "WxH" or a preset label', presets: varDef.presets }
61
+ if (varDef instanceof ImageVar)
62
+ return { ...base, payload: 'local file path or http(s) url', extensions: varDef.extensions }
63
+ return { ...base, payload: 'string' } // TextVar and future plain kinds
64
+ }
65
+
66
+ /** one aligned console line per var (startup print) */
67
+ export function renderDescriptorLine(name: string, d: VarDescriptor, nameWidth: number): string {
68
+ const def = typeof d.default === 'string' ? JSON.stringify(truncate(d.default, 40)) : JSON.stringify(d.default)
69
+ return ` ${name.padEnd(nameWidth)} ${d.kind.padEnd(6)} ${d.payload} · default: ${truncate(def ?? 'null', 60)}`
70
+ }
71
+
72
+ function truncate(s: string, n: number): string {
73
+ return s.length <= n ? s : s.slice(0, n - 1) + '…'
74
+ }
@@ -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
+ }