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
@@ -1,5 +1,10 @@
1
- import { mkdirSync, writeFileSync } from 'node:fs'
2
- import { dirname, join } from 'pathe'
1
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
2
+ import { dirname } from 'pathe'
3
+ import { localOutputPath, runTimestamp, uniquifyOutputPath } from 'src/runner/outputPath.ts'
4
+
5
+ /** paths claimed by in-flight retrievals: two same-second runs on a
6
+ * counter-resetting cloud host compute the same name before either writes */
7
+ const CLAIMED_OUTPUT_PATHS = new Set<string>()
3
8
  import sharp, { type FormatEnum } from 'sharp'
4
9
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
5
10
  import { getPngMetadataFromUint8Array } from 'src/image-utils/_getPngMetadata.ts'
@@ -204,15 +209,27 @@ export class ComfyExecution {
204
209
  // image route on the host (cloud answers a 302 signed url — fetchFile follows it unauthed)
205
210
  const imgRoute = '/view?' + new URLSearchParams(comfyImageInfo).toString()
206
211
 
207
- // target path on disk
212
+ // target path on disk: OUR naming, never the raw server filename — a
213
+ // cloud host resets its _00001_ counter per run, so the server name
214
+ // overwrote the same local file on every run (his repro 2026-07-31)
208
215
  const sf = this.saveFormat
216
+ const promptPrefix = promptNode.inputs['filename_prefix']
209
217
  let absPath: string = comfyts.resolveFromOutput(
210
- join(sf?.prefix ?? comfyImageInfo.subfolder, comfyImageInfo.filename),
218
+ localOutputPath({
219
+ localDir: sf?.prefix,
220
+ filenamePrefix: typeof promptPrefix === 'string' ? promptPrefix : undefined,
221
+ subfolder: comfyImageInfo.subfolder,
222
+ filename: comfyImageInfo.filename,
223
+ timestamp: runTimestamp(new Date(this.startedAt)),
224
+ }),
211
225
  )
212
226
  if (sf?.format && sf.format !== 'raw') {
213
227
  const extension = sf.format.split('/')[1]
214
228
  absPath += '.' + extension
215
229
  }
230
+ // last-resort uniquifier: bump past files on disk AND paths claimed by
231
+ // still-downloading retrievals — never overwrite
232
+ absPath = uniquifyOutputPath({ path: absPath, exists: existsSync, claimed: CLAIMED_OUTPUT_PATHS })
216
233
  const dir = dirname(absPath)
217
234
  mkdirSync(dir, { recursive: true })
218
235
 
@@ -0,0 +1,75 @@
1
+ /**
2
+ * local output naming, relative to `.comfy-ts/outputs/` (his repro
3
+ * 2026-07-31): the server filename is NOT unique — cloud hosts reset the
4
+ * `_00001_` counter every run, so trusting it overwrote the same file — and
5
+ * a `foo/krea/` prefix means the DIRECTORY foo/krea/, not a `krea_` name
6
+ * prefix. Local names are ours: dir from the prompt's own filename_prefix
7
+ * (or an explicit saveFormat.prefix override), then
8
+ * `<stem>_<timestamp>_<counter><ext>` so every run sorts chronologically
9
+ * per stem and nothing ever collides.
10
+ */
11
+ export const localOutputPath = (p: {
12
+ /** explicit local dir override (ImageSaveFormat.prefix) — wins when set */
13
+ localDir?: string
14
+ /** the SaveImage node's own filename_prefix as sent in the prompt */
15
+ filenamePrefix?: string
16
+ /** server-reported subfolder (fallback when no prefix is known) */
17
+ subfolder: string
18
+ /** server-reported filename, e.g. krea_00001_.png */
19
+ filename: string
20
+ /** run timestamp, YYYYMMDD-HHmmss */
21
+ timestamp: string
22
+ }): string => {
23
+ // server name → stem / counter / extension: `krea_00001_.png`
24
+ const dot = p.filename.lastIndexOf('.')
25
+ const ext = dot === -1 ? '' : p.filename.slice(dot)
26
+ const base = dot === -1 ? p.filename : p.filename.slice(0, dot)
27
+ const counterMatch = /_(\d+)_$/.exec(base)
28
+ const counter = counterMatch?.[1]
29
+ const serverStem = counterMatch != null ? base.slice(0, base.length - counterMatch[0].length) : base
30
+
31
+ // directory + stem intent: explicit local dir > prompt prefix > server
32
+ // layout. The stem SURVIVES a localDir override — identity keeps sorting
33
+ let dir: string
34
+ let stem: string
35
+ if (p.filenamePrefix != null && p.filenamePrefix !== '') {
36
+ const slash = p.filenamePrefix.lastIndexOf('/')
37
+ dir = slash === -1 ? '' : p.filenamePrefix.slice(0, slash)
38
+ stem = slash === -1 ? p.filenamePrefix : p.filenamePrefix.slice(slash + 1)
39
+ } else {
40
+ dir = p.subfolder
41
+ stem = serverStem
42
+ }
43
+ if (p.localDir != null) dir = p.localDir
44
+
45
+ const name = [stem === '' ? null : stem, p.timestamp, counter].filter((x) => x != null).join('_') + ext
46
+ return dir === '' ? name : `${dir}/${name}`
47
+ }
48
+
49
+ /**
50
+ * never-overwrite guard: bump `-2`, `-3`, … while the path exists on disk OR
51
+ * was already CLAIMED by a still-downloading retrieval (two same-second runs
52
+ * on a counter-resetting cloud host compute the same name — reviewer catch).
53
+ * The chosen path is claimed before returning.
54
+ */
55
+ export const uniquifyOutputPath = (p: {
56
+ path: string
57
+ exists: (path: string) => boolean
58
+ claimed: Set<string>
59
+ }): string => {
60
+ let out = p.path
61
+ if (p.exists(out) || p.claimed.has(out)) {
62
+ const dot = out.lastIndexOf('.')
63
+ const stem = dot === -1 ? out : out.slice(0, dot)
64
+ const ext = dot === -1 ? '' : out.slice(dot)
65
+ for (let n = 2; p.exists(out) || p.claimed.has(out); n++) out = `${stem}-${n}${ext}`
66
+ }
67
+ p.claimed.add(out)
68
+ return out
69
+ }
70
+
71
+ /** YYYYMMDD-HHmmss, local time — sortable, text-encodable, no colons for filesystems */
72
+ export const runTimestamp = (d: Date): string => {
73
+ const pad = (n: number): string => String(n).padStart(2, '0')
74
+ return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`
75
+ }
@@ -11,7 +11,20 @@ import { ComfyPrimitiveMapping } from 'src/sdk-generator/Primitives.ts'
11
11
  */
12
12
  export type InputWidgetKind =
13
13
  | { kind: 'slot' }
14
- | { kind: 'widget'; consumes: 1 | 2; strictValues: boolean }
14
+ | {
15
+ kind: 'widget'
16
+ /** total widgets_values entries this input's run occupies: prefix buttons + value + control phantom */
17
+ consumes: number
18
+ strictValues: boolean
19
+ /**
20
+ * serialized values the frontend addWidget()s BEFORE the real value
21
+ * (button widgets, creation order). Import reads the value at
22
+ * `offset + prefixValues.length`; export writes these literals first
23
+ * so a round-trip through the ComfyUI editor keeps positional
24
+ * alignment. Empty for every config-signalled widget.
25
+ */
26
+ prefixValues: readonly unknown[]
27
+ }
15
28
  | { kind: 'dynamic-combo'; options: DynamicComboOption[]; defaultKey: string }
16
29
  | { kind: 'dynamic-container'; instanceNames: string[]; requiredCount: number }
17
30
 
@@ -110,6 +123,24 @@ export const containerInstanceSlotType = (opts: unknown): string | null => {
110
123
  return first.type
111
124
  }
112
125
 
126
+ /**
127
+ * frontend-registered widgets whose object_info opts carry NO config signal —
128
+ * the one exception to config-only classification (architecture.md rule 8).
129
+ * Every entry must quote the frontend widget-creation source.
130
+ *
131
+ * LOAD_3D (ComfyUI_frontend src/extensions/core/load3d.ts, verified
132
+ * 2026-07-31): the LOAD_3D custom widget handler runs
133
+ * node.addWidget('button', 'upload 3d model', 'upload3dmodel', …)
134
+ * node.addWidget('button', 'upload extra resources', 'uploadExtraResources', …)
135
+ * node.addWidget('button', 'clear', 'clear', …)
136
+ * THEN creates the scene widget, so the serialized run is
137
+ * [btn, btn, btn, value] with the real value LAST. Lax domain: '' in saved
138
+ * files, an {image, mask, normal, camera_info, …} dict at queue time.
139
+ */
140
+ const EMPTY_CONFIG_FRONTEND_WIDGETS: Record<string, { prefixValues: readonly unknown[] }> = {
141
+ LOAD_3D: { prefixValues: ['upload3dmodel', 'uploadExtraResources', 'clear'] },
142
+ }
143
+
113
144
  export const classifyWidgetInput = (p: {
114
145
  name: string
115
146
  type: string | readonly unknown[]
@@ -123,14 +154,19 @@ export const classifyWidgetInput = (p: {
123
154
  // 2. enum arrays / parsed E_ unions are combo widgets
124
155
  if (Array.isArray(p.type) || p.isEnumUnion === true) {
125
156
  const tn = typeof p.type === 'string' ? p.type : 'COMBO'
126
- return { kind: 'widget', consumes: controlConsumes(o, tn, p.name), strictValues: true }
157
+ return { kind: 'widget', consumes: controlConsumes(o, tn, p.name), strictValues: true, prefixValues: [] }
127
158
  }
128
159
  if (typeof p.type !== 'string') return { kind: 'slot' }
129
160
  // 3. widgetType names the widget for multi-type unions (frontend: widgets.get(widgetType ?? type))
130
161
  const widgetTypeName = typeof o?.['widgetType'] === 'string' ? o['widgetType'] : p.type
131
162
  // 4. primitives
132
163
  if (ComfyPrimitiveMapping[widgetTypeName] != null)
133
- return { kind: 'widget', consumes: controlConsumes(o, widgetTypeName, p.name), strictValues: true }
164
+ return {
165
+ kind: 'widget',
166
+ consumes: controlConsumes(o, widgetTypeName, p.name),
167
+ strictValues: true,
168
+ prefixValues: [],
169
+ }
134
170
  // 5. options array: dynamic {key, inputs} family, else plain combo
135
171
  const options = o?.['options']
136
172
  if (Array.isArray(options)) {
@@ -141,7 +177,7 @@ export const classifyWidgetInput = (p: {
141
177
  const defaultKey = typeof o?.['default'] === 'string' ? o['default'] : first.key
142
178
  return { kind: 'dynamic-combo', options: dynOptions, defaultKey }
143
179
  }
144
- return { kind: 'widget', consumes: controlConsumes(o, p.type, p.name), strictValues: true }
180
+ return { kind: 'widget', consumes: controlConsumes(o, p.type, p.name), strictValues: true, prefixValues: [] }
145
181
  }
146
182
  // 6. template WITH nested input = autogrow container; WITHOUT = matchtype slot typing
147
183
  const template = o?.['template']
@@ -150,7 +186,16 @@ export const classifyWidgetInput = (p: {
150
186
  return { kind: 'slot' }
151
187
  }
152
188
  // 7. socketless: a widget that never has a socket (IMAGECOMPARE, COLOR); value domain unknown
153
- if (o?.['socketless'] === true) return { kind: 'widget', consumes: 1, strictValues: false }
189
+ if (o?.['socketless'] === true) return { kind: 'widget', consumes: 1, strictValues: false, prefixValues: [] }
190
+ // 8. known empty-config frontend widgets (LOAD_3D), the one non-config exception
191
+ const emptyConfigEntry = EMPTY_CONFIG_FRONTEND_WIDGETS[widgetTypeName]
192
+ if (emptyConfigEntry != null)
193
+ return {
194
+ kind: 'widget',
195
+ consumes: emptyConfigEntry.prefixValues.length + 1,
196
+ strictValues: false,
197
+ prefixValues: emptyConfigEntry.prefixValues,
198
+ }
154
199
  return { kind: 'slot' }
155
200
  }
156
201
 
@@ -162,12 +207,6 @@ export const classifySchemaInput = (input: NodeInputExt): InputWidgetKind =>
162
207
  isEnumUnion: input.isEnum,
163
208
  })
164
209
 
165
- /** how many widgets_values entries this schema input consumes (export path + positional walks) */
166
- export const howManyWidgetValuesForThisSchemaType = (input: NodeInputExt): number => {
167
- const kind = classifySchemaInput(input)
168
- return kind.kind === 'widget' ? kind.consumes : 0
169
- }
170
-
171
210
  /**
172
211
  * what ComfyUI's frontend gives a widget created with no serialized value
173
212
  * (`getWidgetDefaultValue` semantics), used when a positional array is
@@ -145,15 +145,19 @@ export const convertLiteGraphToPrompt = (
145
145
  )
146
146
  }
147
147
 
148
- /** named wins, then positional cursor; filled=true when both miss (caller falls back to the schema default) */
149
- const resolveWidgetValue = (p: { promptName: string; consumes: number }): { value: unknown; filled: boolean } => {
148
+ /** named wins, then positional cursor (+prefixLen skips leading button values, LOAD_3D); filled=true when both miss (caller falls back to the schema default) */
149
+ const resolveWidgetValue = (p: {
150
+ promptName: string
151
+ consumes: number
152
+ prefixLen: number
153
+ }): { value: unknown; filled: boolean } => {
150
154
  let value: unknown
151
155
  let has = false
152
156
  if (Object.hasOwn(named, p.promptName)) {
153
157
  value = named[p.promptName]
154
158
  has = true
155
- } else if (offset < positional.length) {
156
- value = positional[offset]
159
+ } else if (offset + p.prefixLen < positional.length) {
160
+ value = positional[offset + p.prefixLen]
157
161
  has = true
158
162
  }
159
163
  if (positional.length > 0) offset += p.consumes // named-shadow still advances (promotion case)
@@ -165,11 +169,12 @@ export const convertLiteGraphToPrompt = (
165
169
  typeName: string
166
170
  opts: unknown
167
171
  consumes: number
172
+ prefixLen: number
168
173
  strict: boolean
169
174
  enumValues?: readonly (string | boolean | number)[]
170
175
  linkedInput: CanonicalInput | undefined
171
176
  }): void => {
172
- const r = resolveWidgetValue({ promptName: p.promptName, consumes: p.consumes })
177
+ const r = resolveWidgetValue({ promptName: p.promptName, consumes: p.consumes, prefixLen: p.prefixLen })
173
178
  const raw = r.filled
174
179
  ? defaultValueForWidget({
175
180
  type: p.typeName,
@@ -185,7 +190,7 @@ export const convertLiteGraphToPrompt = (
185
190
 
186
191
  /** key consumed first, then the SELECTED branch inline, recursively (backend get_finalized_class_inputs) */
187
192
  const consumeDynamicCombo = (p: { path: string; options: DynamicComboOption[]; defaultKey: string }): void => {
188
- const r = resolveWidgetValue({ promptName: p.path, consumes: 1 })
193
+ const r = resolveWidgetValue({ promptName: p.path, consumes: 1, prefixLen: 0 })
189
194
  const key = r.filled ? p.defaultKey : r.value
190
195
  if (typeof key !== 'string')
191
196
  throw new WorkflowConvertError(
@@ -224,6 +229,7 @@ export const convertLiteGraphToPrompt = (
224
229
  typeName: typeof sub.type === 'string' ? sub.type : 'COMBO',
225
230
  opts: sub.opts,
226
231
  consumes: kind.consumes,
232
+ prefixLen: kind.prefixValues.length,
227
233
  strict: kind.strictValues,
228
234
  enumValues: inlineEnum,
229
235
  linkedInput: inputsInNodeJSON.find((i) => i.name === subPath),
@@ -238,7 +244,7 @@ export const convertLiteGraphToPrompt = (
238
244
  // proves a widget value was written, so consume per the file's era
239
245
  if (kind.kind === 'slot' && input?.widgetName != null) {
240
246
  const legacyConsumes = howManyWidgetValuesForThisInputType(input.type, field.nameInComfy)
241
- kind = { kind: 'widget', consumes: legacyConsumes === 2 ? 2 : 1, strictValues: true }
247
+ kind = { kind: 'widget', consumes: legacyConsumes === 2 ? 2 : 1, strictValues: true, prefixValues: [] }
242
248
  }
243
249
 
244
250
  if (kind.kind === 'widget') {
@@ -247,6 +253,7 @@ export const convertLiteGraphToPrompt = (
247
253
  typeName: field.typeName,
248
254
  opts: field.opts,
249
255
  consumes: kind.consumes,
256
+ prefixLen: kind.prefixValues.length,
250
257
  strict: kind.strictValues,
251
258
  linkedInput: input,
252
259
  })
@@ -228,6 +228,12 @@ export class SeedVar extends ComfyVar<number> {
228
228
  override afterRun(): void {
229
229
  this.advance()
230
230
  }
231
+ /** mode is part of the seed's state: a reset must not keep a caller's `?`/`+` alive
232
+ * ('=' is the construction default; drafts restore their own mode via loadJSON) */
233
+ override reset(): this {
234
+ this.setMode('=')
235
+ return super.reset()
236
+ }
231
237
  /** parse `+` `- 12` `= 5` `?` or a bare number (=> fixed). Keeps the current number when none given */
232
238
  parse(raw: string): boolean {
233
239
  const m = raw.trim().match(/^([+\-=?])?\s*(\d+)?$/)
@@ -603,11 +609,13 @@ export const v = {
603
609
  export type AnyVar = {
604
610
  readonly kind: VarKind
605
611
  readonly value: unknown
612
+ readonly defaultValue: unknown
606
613
  readonly label?: string
607
614
  /** the vars-spec key — DefinedWorkflow writes it at define time */
608
615
  name?: string
609
616
  parse(raw: string): boolean
610
617
  loadJSON(value: unknown): unknown
618
+ reset(): unknown
611
619
  toJSON(): unknown
612
620
  outValue(): unknown
613
621
  display(): string