comfy-ts 2.0.0 → 2.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.
package/dist/web.js CHANGED
@@ -101,7 +101,7 @@ function getComfyStorage() {
101
101
  }
102
102
  //#endregion
103
103
  //#region package.json
104
- var version = "2.0.0";
104
+ var version = "2.1.0";
105
105
  //#endregion
106
106
  //#region src/litegraph/LiteGraphLinkID.ts
107
107
  const asLiteGraphLinkID = (id) => id;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "comfy-ts",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "The complete TypeScript toolkit for ComfyUI and generative AI. Fully type-safe SDK with autocomplete on every node, companion CLI, TUI, agentic docs, and 50+ examples. Design, run and deploy creative pipelines for image, video, audio, 3d and text on any ComfyUI, local, cloud or hosted.",
5
5
  "keywords": [
6
6
  "comfyui",
@@ -1,6 +1,5 @@
1
1
  import { Box, Text, useApp, useInput, useStdin } from 'ink'
2
2
  import { observer } from 'mobx-react-lite'
3
- import { basename } from 'pathe'
4
3
  import { CopyOverlay } from 'src/cli/tui/components/CopyOverlay.tsx'
5
4
  import { DraftsOverlay } from 'src/cli/tui/components/DraftsOverlay.tsx'
6
5
  import { Header } from 'src/cli/tui/components/Header.tsx'
@@ -291,11 +290,11 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
291
290
  <Box paddingX={1}>
292
291
  <ProgressLine st={s} />
293
292
  </Box>
294
- {s.exec.outputs.length > 0 && (
293
+ {s.exec.outputLabels.length > 0 && (
295
294
  <Box borderStyle="round" paddingX={1} flexDirection="column">
296
- {s.exec.outputs.map((o) => (
297
- <Text key={o} color="green" wrap="truncate">
298
- {basename(o)} <Text color="gray">{o}</Text>
295
+ {s.exec.outputLabels.map((o, ix) => (
296
+ <Text key={`${ix}-${o.name}`} color={o.memory ? 'yellow' : 'green'} wrap="truncate">
297
+ {o.name} <Text color="gray">{o.detail}</Text>
299
298
  </Text>
300
299
  ))}
301
300
  </Box>
@@ -79,7 +79,8 @@ const VarRow = observer(
79
79
  export const VarsPanel = observer((p: { st: TuiSt }) => {
80
80
  const s = p.st
81
81
  // label column = longest label + marker, so [kind] and values line up
82
- const labelW = Math.max(6, ...s.entries.map(([name, v]) => (v.label ?? name).length)) + 3
82
+ // ('save to disk'.length covers the TUI-owned last row)
83
+ const labelW = Math.max(12, ...s.entries.map(([name, v]) => (v.label ?? name).length)) + 3
83
84
  const focused = s.mode === 'nav' || s.mode === 'edit'
84
85
  const boxRef = useRef<DOMElement>(null)
85
86
  useEffect(() => {
@@ -102,7 +103,7 @@ export const VarsPanel = observer((p: { st: TuiSt }) => {
102
103
  </Text>
103
104
  </Box>
104
105
  {w.moreAbove && <Text color="gray">…</Text>}
105
- {s.entries.slice(w.start, w.end).map(([name, varDef], sliceIx) => (
106
+ {s.entries.slice(w.start, Math.min(w.end, s.entries.length)).map(([name, varDef], sliceIx) => (
106
107
  <VarRow
107
108
  key={name}
108
109
  name={name}
@@ -113,6 +114,43 @@ export const VarsPanel = observer((p: { st: TuiSt }) => {
113
114
  compact={s.varsCompact}
114
115
  />
115
116
  ))}
117
+ {/* the TUI-owned save rows ride the vars list as its last rows (item 14) */}
118
+ {w.end > s.entries.length && (
119
+ <Box flexDirection="row">
120
+ <Box width={labelW} flexShrink={0}>
121
+ <Text inverse={s.onSaveRow}>
122
+ {s.onSaveRow ? '▸ ' : ' '}
123
+ save to disk
124
+ </Text>
125
+ </Box>
126
+ <Box width={9} flexShrink={0}>
127
+ <Text color="gray">[tui]</Text>
128
+ </Box>
129
+ <Box flexGrow={1}>
130
+ <Text color={s.settings.saveToDisk ? 'cyan' : 'yellow'} wrap="truncate">
131
+ {s.settings.saveToDisk ? 'on' : 'off — outputs stay in memory'}
132
+ </Text>
133
+ </Box>
134
+ </Box>
135
+ )}
136
+ {s.settings.saveToDisk && w.end > s.entries.length + 1 && (
137
+ <Box flexDirection="row">
138
+ <Box width={labelW} flexShrink={0}>
139
+ <Text inverse={s.onPrefixRow}>
140
+ {s.onPrefixRow ? '▸ ' : ' '}
141
+ save prefix
142
+ </Text>
143
+ </Box>
144
+ <Box width={9} flexShrink={0}>
145
+ <Text color="gray">[tui]</Text>
146
+ </Box>
147
+ <Box flexGrow={1}>
148
+ <Text color="cyan" wrap="truncate">
149
+ .comfy-ts/outputs/{s.savePrefix}/
150
+ </Text>
151
+ </Box>
152
+ </Box>
153
+ )}
116
154
  {w.moreBelow && <Text color="gray">…</Text>}
117
155
  </Box>
118
156
  )
@@ -7,6 +7,46 @@ const extOf = (path: string): string => {
7
7
  return dot === -1 ? '' : path.slice(dot + 1).toLowerCase()
8
8
  }
9
9
 
10
+ /** platform command that puts PNG bytes on the clipboard from STDIN — no
11
+ * file ever touches disk (his ask 2026-07-31). The caller pipes `stdin`
12
+ * into the spawned process and closes it. */
13
+ export type ImageClipboardStdinCommand = { cmd: string; args: string[]; stdin: Uint8Array }
14
+
15
+ export const imageClipboardStdinCommand = (
16
+ platform: NodeJS.Platform,
17
+ pngBytes: Uint8Array,
18
+ ): ImageClipboardStdinCommand => {
19
+ if (platform === 'darwin') {
20
+ // osascript reads the SCRIPT itself from stdin (`-`): a «data PNGf<hex>»
21
+ // literal carries the pixels inside the script — hex doubles the size,
22
+ // so multi-MB images take a beat; the caller falls back to the file
23
+ // command when this exits non-zero
24
+ const hex = Buffer.from(pngBytes).toString('hex').toUpperCase()
25
+ return {
26
+ cmd: 'osascript',
27
+ args: ['-'],
28
+ stdin: new TextEncoder().encode(`set the clipboard to «data PNGf${hex}»`),
29
+ }
30
+ }
31
+ if (platform === 'win32') {
32
+ // base64 rides stdin; PS rebuilds the image from a MemoryStream — no
33
+ // user-controlled string ever lands in the script (quoting stays trivial)
34
+ const script =
35
+ '$b=[Convert]::FromBase64String([Console]::In.ReadToEnd()); ' +
36
+ '$ms=New-Object System.IO.MemoryStream(,$b); ' +
37
+ 'Add-Type -AssemblyName System.Windows.Forms,System.Drawing; ' +
38
+ '$img=[System.Drawing.Image]::FromStream($ms); ' +
39
+ '[System.Windows.Forms.Clipboard]::SetImage($img); $img.Dispose()'
40
+ return {
41
+ cmd: 'powershell',
42
+ args: ['-NoProfile', '-Sta', '-Command', script],
43
+ stdin: new TextEncoder().encode(Buffer.from(pngBytes).toString('base64')),
44
+ }
45
+ }
46
+ // xclip reads the image bytes from stdin natively
47
+ return { cmd: 'xclip', args: ['-selection', 'clipboard', '-t', 'image/png'], stdin: pngBytes }
48
+ }
49
+
10
50
  export const imageClipboardCommand = (platform: NodeJS.Platform, path: string): ImageClipboardCommand | null => {
11
51
  const ext = extOf(path)
12
52
  if (platform === 'darwin') {
@@ -82,8 +82,7 @@ export class DraftsSt {
82
82
 
83
83
  /** module key of the currently loaded workflow (settings.lastDraft is keyed by it) */
84
84
  private get moduleKey(): string {
85
- const cur = this.st.workflows.currentPath
86
- return cur != null ? draftKeyForFile(cur) : (this.st.wf.spec.id ?? 'workflow')
85
+ return this.st.moduleKey
87
86
  }
88
87
 
89
88
  /** switch to a draft: load its stored values when the file exists, else it starts from current values */
@@ -1,14 +1,15 @@
1
1
  import { spawn } from 'node:child_process'
2
+ import { existsSync, writeFileSync } from 'node:fs'
3
+ import { tmpdir } from 'node:os'
2
4
  import { makeAutoObservable, runInAction } from 'mobx'
3
- import { basename } from 'pathe'
5
+ import { basename, join } from 'pathe'
4
6
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
5
7
  import type { ExecutionProgress } from 'src/runner/ComfyExecution.ts'
6
- import { imageClipboardCommand } from 'src/cli/tui/imageClipboard.ts'
8
+ import { imageClipboardCommand, imageClipboardStdinCommand } from 'src/cli/tui/imageClipboard.ts'
7
9
  import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
8
10
  import type { SeedVar } from 'src/vars/ComfyVars.ts'
9
11
  import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
10
- import { draftKeyForFile } from 'src/cli/tui/state/DraftsSt.ts'
11
- import type { AbsolutePath } from 'src/types/index.ts'
12
+ import type { MediaImage } from 'src/runner/MediaImage.ts'
12
13
 
13
14
  /** popup body: summary + the head of the copied json (proof of WHAT is in the clipboard) */
14
15
  export function jsonHead(text: string, maxLines: number): string[] {
@@ -27,7 +28,8 @@ export class ExecSt {
27
28
  /** runs we launched that have not finished (the server executes them FIFO) */
28
29
  inFlight: number = 0
29
30
  progress: ExecutionProgress | null = null
30
- outputs: string[] = []
31
+ /** last run's outputs — MediaImages, so memory-only runs (save toggle off) stay first-class */
32
+ outputImages: MediaImage[] = []
31
33
  runCount: number = 0
32
34
  lastStatus: string | null = null
33
35
  error: string | null = null
@@ -45,21 +47,35 @@ export class ExecSt {
45
47
  return this.inFlight > 0
46
48
  }
47
49
 
48
- /** local save dir for this module's outputs (same key the drafts use) */
49
- private get saveDirPrefix(): string {
50
- const cur = this.st.workflows.currentPath
51
- return cur != null ? draftKeyForFile(cur) : (this.st.wf.spec.id ?? 'workflow')
52
- }
53
-
54
50
  /** workflow switch: wipe run artifacts, keep a hello notice */
55
51
  resetForWorkflow(notice: string): void {
56
- this.outputs = []
52
+ this.outputImages = []
57
53
  this.error = null
58
54
  this.notice = notice
59
55
  this.runCount = 0
60
56
  this.lastStatus = null
61
57
  }
62
58
 
59
+ /** outputs box rows: path when saved, honest memory label otherwise */
60
+ get outputLabels(): { name: string; detail: string; memory: boolean }[] {
61
+ return this.outputImages.map((img) => {
62
+ if (img.absPath != null) return { name: basename(img.absPath), detail: img.absPath, memory: false }
63
+ const dims = img.width != null && img.height != null ? `${img.width}x${img.height}, ` : ''
64
+ return { name: img.filename, detail: `(${dims}in memory — i copies, o opens)`, memory: true }
65
+ })
66
+ }
67
+
68
+ /** a file path for viewer/clipboard: the saved file, or the bytes
69
+ * materialized into os tmpdir (deliberate user action, never a silent
70
+ * save — architecture item 14). The path derives from the content hash,
71
+ * so re-materializing is a cheap existsSync, no retention needed. */
72
+ private materialize(img: MediaImage): string {
73
+ if (img.absPath != null) return img.absPath
74
+ const path = join(tmpdir(), `comfy-ts-mem-${img.hash.slice(0, 8)}${img.extension}`)
75
+ if (!existsSync(path)) writeFileSync(path, img.buffer)
76
+ return path
77
+ }
78
+
63
79
  /** every run takes THIS path, queued ones included: same progress, outputs, previews */
64
80
  async run(): Promise<void> {
65
81
  const queued = this.running
@@ -87,19 +103,18 @@ export class ExecSt {
87
103
  try {
88
104
  const execution = await this.st.wf.run({
89
105
  host: this.st.hostOverride ?? undefined,
90
- // the TUI OPTS INTO local saving (library default is memory-only,
91
- // item 14): the outputs list and `o` open-in-viewer need files.
92
- // Outputs group per module under .comfy-ts/outputs/<module>/
93
- save: { prefix: this.saveDirPrefix },
106
+ // the save rows (vars panel, item 14): on = files under
107
+ // .comfy-ts/outputs/<savePrefix>/, off = outputs stay in memory
108
+ save: this.st.settings.saveToDisk ? { prefix: this.st.savePrefix } : false,
94
109
  onProgress: (p) => runInAction(() => this.onProgress(p)),
95
110
  })
96
111
  runInAction(() => {
97
- this.outputs = execution.images.map((i) => i.absPath).filter((p): p is AbsolutePath => p != null)
112
+ this.outputImages = execution.images.slice()
98
113
  this.lastStatus = execution.status
99
114
  this.runCount++
100
115
  })
101
116
  const lastImage = execution.images[execution.images.length - 1]
102
- if (lastImage?.absPath != null) void this.st.preview.renderOutput(lastImage.absPath)
117
+ if (lastImage != null) void this.st.preview.renderOutput(lastImage.absPath ?? lastImage.buffer)
103
118
  } catch (e) {
104
119
  runInAction(() => {
105
120
  this.error = extractErrorMessage(e)
@@ -140,11 +155,18 @@ export class ExecSt {
140
155
 
141
156
  /** 'o': real pixels in the OS viewer — the in-terminal ceiling is half-blocks */
142
157
  openLastOutput(): void {
143
- const last = this.outputs[this.outputs.length - 1]
144
- if (last == null) {
158
+ const lastImg = this.outputImages[this.outputImages.length - 1]
159
+ if (lastImg == null) {
145
160
  this.notice = 'no output image yet'
146
161
  return
147
162
  }
163
+ let last: string
164
+ try {
165
+ last = this.materialize(lastImg)
166
+ } catch (e) {
167
+ this.notice = `open failed: ${extractErrorMessage(e)}`
168
+ return
169
+ }
148
170
  const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open'
149
171
  const proc = spawn(cmd, [last], { stdio: 'ignore', detached: true })
150
172
  proc.on('error', () => {
@@ -153,7 +175,7 @@ export class ExecSt {
153
175
  })
154
176
  })
155
177
  proc.unref()
156
- this.notice = `opened ${basename(last)}`
178
+ this.notice = `opened ${basename(last)}${lastImg.absPath == null ? ` (memory image via ${last})` : ''}`
157
179
  }
158
180
 
159
181
  // ---- clipboard ----
@@ -181,53 +203,84 @@ export class ExecSt {
181
203
  this.copyPopup = { title, ok, lines }
182
204
  this.st.mode = 'overlay-copy'
183
205
  }
184
- /** 'i': the LAST generated image's pixels → clipboard (paste anywhere) */
206
+ /** 'i': the LAST generated image's pixels → clipboard (paste anywhere).
207
+ * The primary route pipes png bytes over stdin — no disk write at all
208
+ * (his ask 2026-07-31); only when that tool fails does it fall back to
209
+ * the materialized-file command, and the popup says which route ran. */
185
210
  async copyLastImage(): Promise<void> {
186
- const last = this.outputs[this.outputs.length - 1]
187
- if (last == null) {
211
+ const lastImg = this.outputImages[this.outputImages.length - 1]
212
+ if (lastImg == null) {
188
213
  this.showCopyPopup('image → clipboard', false, ['no output image yet — r runs the workflow first'])
189
214
  return
190
215
  }
191
- let file = last
192
- let command = imageClipboardCommand(process.platform, file)
193
- if (command == null && process.platform === 'darwin') {
194
- // osascript only tags bytes — webp/etc must become real png first
195
- try {
196
- const { default: sharp } = await import('sharp')
197
- const { tmpdir } = await import('node:os')
198
- const { join } = await import('pathe')
199
- file = join(tmpdir(), `comfy-ts-clip-${Date.now()}.png`)
200
- await sharp(last).png().toFile(file)
201
- command = imageClipboardCommand(process.platform, file)
202
- } catch (e) {
203
- this.showCopyPopup('image → clipboard', false, [
204
- `COPY FAILED for ${basename(last)}`,
205
- `png transcode failed: ${extractErrorMessage(e)}`,
206
- ])
207
- return
208
- }
216
+ // normalize to png IN MEMORY: osascript/PS tag bytes, they never transcode
217
+ let pngBytes: Uint8Array
218
+ try {
219
+ pngBytes = lastImg.metadata.type === 'png' ? lastImg.buffer : await this.toPngBytes(lastImg.buffer)
220
+ } catch (e) {
221
+ this.showCopyPopup('image → clipboard', false, [
222
+ `COPY FAILED for ${lastImg.filename}`,
223
+ `png transcode failed: ${extractErrorMessage(e)}`,
224
+ ])
225
+ return
209
226
  }
210
- if (command == null) {
211
- this.showCopyPopup('image → clipboard', false, [`no clipboard image tool for ${process.platform}`])
227
+ const piped = imageClipboardStdinCommand(process.platform, pngBytes)
228
+ const pipedOk = await this.runWithStdin(piped)
229
+ if (pipedOk) {
230
+ this.showCopyPopup('image → clipboard', true, [
231
+ `${lastImg.filename} — paste the pixels anywhere`,
232
+ '',
233
+ 'nothing written to disk',
234
+ ])
212
235
  return
213
236
  }
214
- const cmd = command
215
- const ok = await new Promise<boolean>((resolve) => {
216
- const proc = spawn(cmd.cmd, cmd.args, { stdio: 'ignore' })
217
- proc.on('error', () => resolve(false))
218
- proc.on('close', (code) => resolve(code === 0))
219
- })
237
+ // fallback: the piped tool failed (missing/blocked) — try the file route
238
+ let file: string
239
+ try {
240
+ file = this.materialize(lastImg)
241
+ } catch (e) {
242
+ this.showCopyPopup('image → clipboard', false, [
243
+ `COPY FAILED for ${lastImg.filename}`,
244
+ `piped ${piped.cmd} failed, and the tmp-file fallback could not write: ${extractErrorMessage(e)}`,
245
+ ])
246
+ return
247
+ }
248
+ const command = imageClipboardCommand(process.platform, file)
249
+ const ok =
250
+ command != null &&
251
+ (await new Promise<boolean>((resolve) => {
252
+ const proc = spawn(command.cmd, command.args, { stdio: 'ignore' })
253
+ proc.on('error', () => resolve(false))
254
+ proc.on('close', (code) => resolve(code === 0))
255
+ }))
220
256
  runInAction(() => {
221
257
  this.showCopyPopup(
222
258
  'image → clipboard',
223
259
  ok,
224
260
  ok
225
- ? [`${basename(last)} — paste the pixels anywhere`, '', last]
226
- : [`COPY FAILED for ${basename(last)}`, `could not run ${cmd.cmd} — is it installed and allowed ?`],
261
+ ? [`${basename(file)} — paste the pixels anywhere`, '', `via fallback file ${file}`]
262
+ : [`COPY FAILED for ${lastImg.filename}`, `could not run ${piped.cmd} — is it installed and allowed ?`],
227
263
  )
228
264
  })
229
265
  }
230
266
 
267
+ private async toPngBytes(bytes: Uint8Array): Promise<Uint8Array> {
268
+ const { default: sharp } = await import('sharp')
269
+ return new Uint8Array(await sharp(bytes).png().toBuffer())
270
+ }
271
+
272
+ private runWithStdin(p: { cmd: string; args: string[]; stdin: Uint8Array }): Promise<boolean> {
273
+ return new Promise((resolve) => {
274
+ const proc = spawn(p.cmd, p.args, { stdio: ['pipe', 'ignore', 'ignore'] })
275
+ proc.on('error', () => resolve(false))
276
+ proc.on('close', (code) => resolve(code === 0))
277
+ // EPIPE when the tool is missing/dies early: the close handler decides
278
+ proc.stdin.on('error', () => {})
279
+ proc.stdin.write(p.stdin)
280
+ proc.stdin.end()
281
+ })
282
+ }
283
+
231
284
  private toClipboard(text: string): Promise<boolean> {
232
285
  const [cmd, ...args] =
233
286
  process.platform === 'darwin'
@@ -52,8 +52,9 @@ export class PreviewSt {
52
52
  latentDims: { width: number; height: number } | null = null
53
53
  /** at least one latent frame arrived this run — false + progress = server sends none */
54
54
  latentSeenThisRun: boolean = false
55
- /** last output path, so a settings change can re-render it */
56
- private lastOutputPath: string | null = null
55
+ /** last output, kept so a settings change can re-render it: a path when
56
+ * the run saved, raw bytes for memory-only runs (item 14) */
57
+ private lastOutput: string | Uint8Array | null = null
57
58
 
58
59
  get show(): boolean {
59
60
  return this.st.settings.previewPanel
@@ -162,7 +163,7 @@ export class PreviewSt {
162
163
  this.latentBytes = null
163
164
  this.latentDims = null
164
165
  this.latentSeenThisRun = false
165
- this.lastOutputPath = null
166
+ this.lastOutput = null
166
167
  }
167
168
 
168
169
  /** run boundary: drop the latents so the next run never shows the previous one's */
@@ -177,7 +178,7 @@ export class PreviewSt {
177
178
  onSettingsChanged(): void {
178
179
  this.outputAnsi = null
179
180
  this.outputBytes = null
180
- if (this.show && this.lastOutputPath != null) void this.renderOutput(this.lastOutputPath)
181
+ if (this.show && this.lastOutput != null) void this.renderOutput(this.lastOutput)
181
182
  }
182
183
 
183
184
  /** what the painter should show RIGHT NOW (native renderer only; mirrors the panel's source) */
@@ -227,13 +228,13 @@ export class PreviewSt {
227
228
  return Math.max(10, this.st.termRows - 12)
228
229
  }
229
230
 
230
- async renderOutput(path: string): Promise<void> {
231
- this.lastOutputPath = path
231
+ async renderOutput(src: string | Uint8Array): Promise<void> {
232
+ this.lastOutput = src
232
233
  if (!this.show) return
233
234
  try {
234
235
  if (this.useNative) {
235
236
  // pre-shrink ONCE: the painter re-uploads on every repaint, so ~100KB beats ~2MB
236
- const shrunk = await sharp(path)
237
+ const shrunk = await sharp(src)
237
238
  .resize(896, 896, { fit: 'inside', withoutEnlargement: true })
238
239
  .png()
239
240
  .toBuffer()
@@ -242,7 +243,7 @@ export class PreviewSt {
242
243
  })
243
244
  return
244
245
  }
245
- const rendered = await imageBufferToAnsi(path, { width: this.width, height: this.height })
246
+ const rendered = await imageBufferToAnsi(src, { width: this.width, height: this.height })
246
247
  runInAction(() => {
247
248
  this.outputAnsi = rendered
248
249
  })
@@ -302,9 +303,9 @@ export class PreviewSt {
302
303
  )
303
304
  .png()
304
305
  .toBuffer()
305
- const outPath = this.lastOutputPath
306
- if (outPath == null) return imageBufferToAnsi(thumb, { width: this.width, height: this.height })
307
- const base = await sharp(outPath).resize(pxW, pxH, { fit: 'inside' }).png().toBuffer()
306
+ const out = this.lastOutput
307
+ if (out == null) return imageBufferToAnsi(thumb, { width: this.width, height: this.height })
308
+ const base = await sharp(out).resize(pxW, pxH, { fit: 'inside' }).png().toBuffer()
308
309
  const composed = await sharp(base)
309
310
  .composite([{ input: thumb, gravity: 'northeast' }])
310
311
  .png()
@@ -60,6 +60,8 @@ export class SettingsSt {
60
60
  lastWorkflow: this.lastWorkflow,
61
61
  hostOverrideId: this.hostOverrideId,
62
62
  collapsedDirs: this.collapsedDirs,
63
+ saveToDisk: this.saveToDisk,
64
+ savePrefix: this.savePrefix,
63
65
  })
64
66
  }
65
67
 
@@ -74,6 +76,10 @@ export class SettingsSt {
74
76
  hostOverrideId: string | null = null
75
77
  /** folded tree dirs (hand-tuned state persists, like every other surface) */
76
78
  collapsedDirs: string[] = []
79
+ /** the vars-panel save toggle (architecture item 14): off = outputs stay in memory */
80
+ saveToDisk: boolean = true
81
+ /** per-module override of the local save dir under .comfy-ts/outputs/ (item 14) */
82
+ savePrefix: Record<string, string> = {}
77
83
 
78
84
  rememberDraft(moduleKey: string, draft: string): void {
79
85
  this.lastDraft[moduleKey] = draft
@@ -99,6 +105,13 @@ export class SettingsSt {
99
105
  if (typeof o.lastWorkflow === 'string') this.lastWorkflow = o.lastWorkflow
100
106
  if (typeof o.hostOverrideId === 'string') this.hostOverrideId = o.hostOverrideId
101
107
  if (Array.isArray(o.collapsedDirs)) this.collapsedDirs = o.collapsedDirs.filter((d) => typeof d === 'string')
108
+ if (typeof o.saveToDisk === 'boolean') this.saveToDisk = o.saveToDisk
109
+ if (o.savePrefix != null && typeof o.savePrefix === 'object')
110
+ this.savePrefix = Object.fromEntries(
111
+ Object.entries(o.savePrefix as Record<string, unknown>).filter(
112
+ (kv): kv is [string, string] => typeof kv[1] === 'string',
113
+ ),
114
+ )
102
115
  } catch {
103
116
  // corrupt settings must never block the TUI — start from defaults
104
117
  }
@@ -2,7 +2,7 @@ import { makeAutoObservable, observable, runInAction } from 'mobx'
2
2
  import { listWindow, type ListWindow } from 'src/cli/tui/listWindow.ts'
3
3
  import type { SeedVar, ToggleVar, AnyVar } from 'src/vars/ComfyVars.ts'
4
4
  import { ImagePickerSt } from 'src/cli/tui/imagePicker/ImagePickerSt.ts'
5
- import { DraftsSt } from 'src/cli/tui/state/DraftsSt.ts'
5
+ import { DraftsSt, draftKeyForFile } from 'src/cli/tui/state/DraftsSt.ts'
6
6
  import { EditorSt } from 'src/cli/tui/state/EditorSt.ts'
7
7
  import { ExecSt } from 'src/cli/tui/state/ExecSt.ts'
8
8
  import { HostSt } from 'src/cli/tui/state/HostSt.ts'
@@ -201,9 +201,43 @@ export class TuiSt {
201
201
  return this.entries[this.selIx]
202
202
  }
203
203
 
204
+ /** module key of the loaded workflow (drafts + savePrefix are keyed by it) */
205
+ get moduleKey(): string {
206
+ const cur = this.workflows.currentPath
207
+ return cur != null ? draftKeyForFile(cur) : (this.wf.spec.id ?? 'workflow')
208
+ }
209
+
210
+ /** the local save dir under .comfy-ts/outputs/ — per-module override, else the module key */
211
+ get savePrefix(): string {
212
+ return this.settings.savePrefix[this.moduleKey] ?? this.moduleKey
213
+ }
214
+
215
+ /** empty input resets to the module-key default */
216
+ setSavePrefix(raw: string): void {
217
+ const trimmed = raw.trim().replace(/^\/+|\/+$/g, '')
218
+ if (trimmed === '' || trimmed === this.moduleKey) delete this.settings.savePrefix[this.moduleKey]
219
+ else this.settings.savePrefix[this.moduleKey] = trimmed
220
+ }
221
+
222
+ /** the vars list carries the TUI-owned rows after the workflow vars: the
223
+ * save-to-disk toggle, plus the save-prefix row while saving is on
224
+ * (architecture item 14) */
225
+ get varRowCount(): number {
226
+ return this.entries.length + (this.settings.saveToDisk ? 2 : 1)
227
+ }
228
+
229
+ /** true while the selection sits on the save-to-disk pseudo-row */
230
+ get onSaveRow(): boolean {
231
+ return this.selIx === this.entries.length
232
+ }
233
+
234
+ /** true while the selection sits on the save-prefix pseudo-row */
235
+ get onPrefixRow(): boolean {
236
+ return this.settings.saveToDisk && this.selIx === this.entries.length + 1
237
+ }
238
+
204
239
  moveSel(delta: number): void {
205
- const len = this.entries.length
206
- if (len === 0) return
240
+ const len = this.varRowCount
207
241
  this.selIx = (this.selIx + delta + len) % len
208
242
  }
209
243
 
@@ -224,7 +258,7 @@ export class TuiSt {
224
258
  }
225
259
 
226
260
  get varsWindow(): ListWindow {
227
- return listWindow({ count: this.entries.length, selected: this.selIx, budget: this.varsBudget })
261
+ return listWindow({ count: this.varRowCount, selected: this.selIx, budget: this.varsBudget })
228
262
  }
229
263
 
230
264
  /**
@@ -237,7 +271,7 @@ export class TuiSt {
237
271
  const w = this.varsWindow
238
272
  if (w.moreAbove || w.moreBelow) return true
239
273
  const h = this.varsViewH > 0 ? this.varsViewH : Math.max(5, this.termRows - 5)
240
- return this.entries.length + 2 > h
274
+ return this.varRowCount + 2 > h
241
275
  }
242
276
 
243
277
  // kind-discriminated narrowing casts below are sanctioned (agent/coding.md):
@@ -245,6 +279,21 @@ export class TuiSt {
245
279
 
246
280
  /** enter/space on a var: toggle, open an overlay, or inline-edit */
247
281
  activate(): void {
282
+ if (this.onSaveRow) {
283
+ this.settings.saveToDisk = !this.settings.saveToDisk
284
+ return
285
+ }
286
+ if (this.onPrefixRow) {
287
+ this.editor.beginCustom({
288
+ title: `save prefix — dir under .comfy-ts/outputs/ (empty = ${this.moduleKey})`,
289
+ initial: this.savePrefix,
290
+ onCommit: (raw) => {
291
+ this.setSavePrefix(raw)
292
+ return true
293
+ },
294
+ })
295
+ return
296
+ }
248
297
  const sel = this.selected?.[1]
249
298
  if (sel == null) return
250
299
  if (sel.kind === 'toggle') (sel as ToggleVar).toggle()