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,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
 
@@ -0,0 +1,118 @@
1
+ // the SHARED export surface of both entries (architecture item 13):
2
+ // everything here must stay web-safe — node-only exports live in index.ts.
3
+
4
+ // global Comfy.* base namespace + per-host sdk registry (side-effectful types)
5
+ export * from 'src/types/comfy-sdk.ts'
6
+
7
+ // entrypoint singleton
8
+ export { ComfyTS } from 'src/state.ts'
9
+
10
+ // host
11
+ export {
12
+ ComfyHost,
13
+ ComfyHostAuthError,
14
+ type ComfyHostData,
15
+ type ComfyHostID,
16
+ type ConnectOptions,
17
+ } from 'src/host/ComfyHost.ts'
18
+ export { type ParsedHostBase, parseHostBase, renderHttpBase, renderWsUrl } from 'src/host/hostUrl.ts'
19
+ export { ComfyManager } from 'src/host/ComfyManager.ts'
20
+ export { ComfyUploader, type ComfyUploadImageResult } from 'src/host/ComfyUploader.ts'
21
+ export { ComfyWorkflowBuilder } from 'src/host/ComfyWorkflowBuilder.ts'
22
+ export type { Requirements, PluginInstallStatus, PluginSuggestion } from 'src/host/Requirements.ts'
23
+ export { ResilientWebSocketClient } from 'src/host/ResilientWebsocket.ts'
24
+
25
+ // runner
26
+ export {
27
+ ComfyWorkflow,
28
+ type ComfyNodeIdMode,
29
+ type ComfyWorkflowData,
30
+ type ComfyWorkflowID,
31
+ type ExecutionSnapshot,
32
+ type ProgressReport,
33
+ type RunSettings,
34
+ } from 'src/runner/ComfyWorkflow.ts'
35
+ export { ComfyExecution, type ComfyExecutionData, type ExecutionProgress } from 'src/runner/ComfyExecution.ts'
36
+ export type { PromptID, WsMsg, PromptRelated_WsMsg } from 'src/runner/ComfyWsApi.ts'
37
+ export { MediaImage, type MediaImageData } from 'src/runner/MediaImage.ts'
38
+ export type { ComfyExecutionStatus } from 'src/runner/ComfyExecutionStatus.ts'
39
+ export { InvalidPromptError } from 'src/errors/InvalidPromptError.ts'
40
+
41
+ // graph (programmatic node graph)
42
+ export { ComfyNode } from 'src/graph/ComfyNode.ts'
43
+ export { ComfyNodeOutput } from 'src/graph/ComfyNodeOutput.ts'
44
+ export type { ComfyNodeMetadata, ComfyNodeId } from 'src/graph/ComfyNodeID.ts'
45
+ export { auto, auto_ } from 'src/graph/autoValue.ts'
46
+
47
+ // sdk generator (schema parsing + per-host codegen)
48
+ export { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
49
+ export { codegenSDK, hostIdToNamespace, type CodegenOptions } from 'src/sdk-generator/comfyui-sdk-codegen.ts'
50
+ export type { ComfyNodeSchemaJSON, ComfySchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'
51
+ export type { ComfyImageName, ComfyUnionValue, QualifiedNodeKey } from 'src/sdk-generator/comfyui-types.ts'
52
+ export type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
53
+
54
+ // litegraph (ComfyUI saved-workflow JSON format)
55
+ export type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
56
+ export { convertFlowToLiteGraphJSON } from 'src/litegraph/convertFlowToLiteGraphJSON.ts'
57
+ export type {
58
+ CanonicalGroup,
59
+ CanonicalInput,
60
+ CanonicalLink,
61
+ CanonicalNode,
62
+ CanonicalOutput,
63
+ CanonicalWidgetValues,
64
+ CanonicalWorkflow,
65
+ NodeMode,
66
+ } from 'src/litegraph/CanonicalWorkflow.ts'
67
+ export { normalizeWorkflow, parseWorkflowJson, WorkflowNormalizeError } from 'src/litegraph/normalizeWorkflow.ts'
68
+ export { convertLiteGraphToPrompt, WorkflowConvertError } from 'src/sdk-generator/litegraphToApiRequestPayload.ts'
69
+
70
+ // vars + re-runnable workflows
71
+ export {
72
+ v,
73
+ ComfyVarBase,
74
+ ComfyVar,
75
+ TextVar,
76
+ PromptVar,
77
+ IntVar,
78
+ FloatVar,
79
+ SeedVar,
80
+ ToggleVar,
81
+ ChoiceVar,
82
+ LorasVar,
83
+ SizeVar,
84
+ ImageVar,
85
+ ImageVarEmptyError,
86
+ DEFAULT_SIZE_PRESETS,
87
+ DEFAULT_IMAGE_EXTENSIONS,
88
+ activeLoras,
89
+ } from 'src/vars/ComfyVars.ts'
90
+ export type {
91
+ AnyVar,
92
+ VarKind,
93
+ VarsSpec,
94
+ VarValues,
95
+ PromptValue,
96
+ ActiveLoraSource,
97
+ LorasHost,
98
+ LoraStrength,
99
+ ActiveLora,
100
+ SizeValue,
101
+ SizePreset,
102
+ ImageVarOpts,
103
+ } from 'src/vars/ComfyVars.ts'
104
+ export { DefinedWorkflow, type DefineWorkflowSpec, type BoundVars, type LoraNameOf } from 'src/vars/DefinedWorkflow.ts'
105
+ export { getLoraKeyword, setLoraKeyword } from 'src/vars/loraKeywords.ts'
106
+ export { loraTag } from 'src/utils/loraTag.ts'
107
+
108
+ // shared types
109
+ export * from 'src/types/index.ts'
110
+
111
+ // the storage seam (custom backends: ComfyTS.create({ storage }))
112
+ export {
113
+ type ComfyStorage,
114
+ createMemoryStorage,
115
+ getComfyStorage,
116
+ setDefaultComfyStorage,
117
+ } from 'src/storage/ComfyStorage.ts'
118
+ export type { WsLike, WsMessageEvent } from 'src/host/ResilientWebsocket.ts'
@@ -1,6 +1,5 @@
1
- import { existsSync, mkdirSync, readFileSync, statSync } from 'node:fs'
1
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
2
2
  import { type } from 'arktype'
3
- import type { MessageEvent } from 'ws'
4
3
  import type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'
5
4
  import type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPluginURL.ts'
6
5
  import type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'
@@ -28,13 +27,12 @@ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
28
27
  import { printArkResultInConsole } from 'src/utils/printArkResultInConsole.ts'
29
28
  import { readableStringify } from 'src/utils/stringifyReadable.ts'
30
29
  import { logError as toastError, logInfo } from 'src/utils/log.ts'
31
- import { writeFileAsync } from 'src/utils/writeFile.ts'
32
30
  import type { ComfyInstallType } from 'src/host/ComfyInstallType.ts'
33
31
  import { ComfyManager } from 'src/host/ComfyManager.ts'
34
32
  import { ComfyUploader } from 'src/host/ComfyUploader.ts'
35
33
  import { type ParsedHostBase, parseHostBase, renderHttpBase, renderWsUrl } from 'src/host/hostUrl.ts'
36
34
  import type { Requirements } from 'src/host/Requirements.ts'
37
- import { ResilientWebSocketClient } from 'src/host/ResilientWebsocket.ts'
35
+ import { ResilientWebSocketClient, type WsMessageEvent } from 'src/host/ResilientWebsocket.ts'
38
36
  import { DefinedWorkflow, type DefineWorkflowSpec } from 'src/vars/DefinedWorkflow.ts'
39
37
  import type { VarsSpec } from 'src/vars/ComfyVars.ts'
40
38
 
@@ -65,7 +63,7 @@ export type ComfyHostData = {
65
63
  installType?: ComfyInstallType
66
64
 
67
65
  // misc
68
- onWsMessageAny?: (e: MessageEvent) => void
66
+ onWsMessageAny?: (e: WsMessageEvent) => void
69
67
  onWsMessageArrayBuffer?: (e: ArrayBuffer) => void
70
68
  onWsMessageJSON?: (e: WsMsg) => void
71
69
  }
@@ -122,10 +120,10 @@ export class ComfyHost<ID extends string = string> {
122
120
  this.cacheFolder = comfyts.resolveFromHosts(this.data.id)
123
121
 
124
122
  // create the folder if it does not exist
125
- const exists = existsSync(this.cacheFolder)
126
- if (!exists) {
123
+ const storage = getComfyStorage()
124
+ if (!storage.exists(this.cacheFolder)) {
127
125
  console.log('🟢 creating folder', this.cacheFolder)
128
- mkdirSync(this.cacheFolder, { recursive: true })
126
+ storage.mkdirp(this.cacheFolder)
129
127
  }
130
128
 
131
129
  this.comfyJSONPath = comfyts.resolve(this.cacheFolder, `object_info.json`)
@@ -435,22 +433,22 @@ export class ComfyHost<ID extends string = string> {
435
433
 
436
434
  private async writeSDKToDisk(): Promise<void> {
437
435
  if (this.data.sdkAutoWrite === false) return
436
+ const storage = getComfyStorage()
438
437
  const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id })
439
438
  // skip the 4MB write when nothing changed (fast re-connects)
440
- if (existsSync(this.sdkDTSPath) && readFileSync(this.sdkDTSPath, 'utf-8') === comfySchemaTs) return
441
- await writeFileAsync(this.sdkDTSPath, comfySchemaTs, 'utf-8')
439
+ if (storage.readTextIfExists(this.sdkDTSPath) === comfySchemaTs) return
440
+ storage.writeText(this.sdkDTSPath, comfySchemaTs)
442
441
  }
443
442
 
444
443
  private shouldUseSchemaCache(): boolean {
445
444
  if (this._schemaStrategy === 'refresh') return false
446
- const exists = existsSync(this.comfyJSONPath)
445
+ const mtimeMs = getComfyStorage().mtimeMs(this.comfyJSONPath)
447
446
  if (this._schemaStrategy === 'cache') {
448
- if (!exists) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`)
447
+ if (mtimeMs == null) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`)
449
448
  return true
450
449
  }
451
- if (!exists) return false
452
- const ageMs = Date.now() - statSync(this.comfyJSONPath).mtimeMs
453
- return ageMs < this._schemaMaxAgeMs
450
+ if (mtimeMs == null) return false
451
+ return Date.now() - mtimeMs < this._schemaMaxAgeMs
454
452
  }
455
453
 
456
454
  // WEBSCKET -----------------------------------------------------------------------------
@@ -501,10 +499,12 @@ export class ComfyHost<ID extends string = string> {
501
499
  await this.waitForSession()
502
500
  this.markReady()
503
501
  },
504
- onMessage: (e: MessageEvent): void => this.onMessage(e),
502
+ onMessage: (e: WsMessageEvent): void => this.onMessage(e),
505
503
  url: () => this.getWSUrl(),
506
- // auth rides the upgrade HEADERS, never the query string
504
+ // auth rides the upgrade headers; headerless transports (browser)
505
+ // remap X-API-Key to ?token= inside the ws client
507
506
  headers: () => this.authHeaders(),
507
+ onTransportDead: (e): void => this.markFailed(e),
508
508
  onClose: (): void => {
509
509
  logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`)
510
510
  },
@@ -531,7 +531,7 @@ export class ComfyHost<ID extends string = string> {
531
531
  * examples must still open in the TUI; run() fetches the real schema through
532
532
  * connect() anyway). Not memoized in that case, so a later gen/connect retries. */
533
533
  loadSchemaFromCache(): Promise<void> {
534
- if (this._schemaFromCache == null && !existsSync(this.comfyJSONPath)) {
534
+ if (this._schemaFromCache == null && !getComfyStorage().exists(this.comfyJSONPath)) {
535
535
  toastError(
536
536
  `no schema cache for host '${this.data.id}' at ${this.comfyJSONPath} — continuing with base types (no node/model unions); run \`comfy-ts gen --id ${this.data.id} --host <url>\` or connect() once to create it`,
537
537
  )
@@ -546,7 +546,7 @@ export class ComfyHost<ID extends string = string> {
546
546
  this.schema.RUN_BASIC_CHECKS()
547
547
 
548
548
  // the on-disk sdk was generated from this same cache — only write when missing
549
- if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk()
549
+ if (!getComfyStorage().exists(this.sdkDTSPath)) await this.writeSDKToDisk()
550
550
  })().catch((e: unknown) => {
551
551
  this._schemaFromCache = null // a missing cache must stay retryable (e.g. after gen:sdk)
552
552
  throw e
@@ -626,7 +626,7 @@ export class ComfyHost<ID extends string = string> {
626
626
  // e.g. lora-manager serves HTML at /embeddings)
627
627
  const object_info_json = await this.fetchJSON_<{ [key: string]: ComfySchemaJSON[string] }>('/object_info')
628
628
  const object_info_str = readableStringify(object_info_json, 4)
629
- void writeFileAsync(this.comfyJSONPath, object_info_str, 'utf-8')
629
+ getComfyStorage().writeText(this.comfyJSONPath, object_info_str)
630
630
  // use ark to check if payload match the type, and display errors if not
631
631
  const res = ComfySchemaJSON_ark(object_info_json)
632
632
  if (res instanceof type.errors) {
@@ -638,7 +638,7 @@ export class ComfyHost<ID extends string = string> {
638
638
  const embeddings_json = await this.fetchJSON_<EmbeddingName[]>('/embeddings').catch(
639
639
  () => [] as EmbeddingName[],
640
640
  )
641
- void writeFileAsync(this.embeddingsPath, JSON.stringify(embeddings_json), 'utf-8')
641
+ getComfyStorage().writeText(this.embeddingsPath, JSON.stringify(embeddings_json))
642
642
 
643
643
  // 3 ------------------------------------
644
644
  // update schema
@@ -657,7 +657,7 @@ export class ComfyHost<ID extends string = string> {
657
657
  console.error(error)
658
658
  console.error('🔴 FAILURE TO GENERATE the typed sdk', extractErrorMessage(error))
659
659
 
660
- const schemaExists = existsSync(this.sdkDTSPath)
660
+ const schemaExists = getComfyStorage().exists(this.sdkDTSPath)
661
661
  if (!schemaExists) await this.writeSDKToDisk()
662
662
  this.markFailed(error)
663
663
  } finally {
@@ -726,7 +726,7 @@ export class ComfyHost<ID extends string = string> {
726
726
  * never revives one) */
727
727
  lastWsMessageAt: number | null = null
728
728
 
729
- onMessage(e: MessageEvent): void {
729
+ onMessage(e: WsMessageEvent): void {
730
730
  this.lastWsMessageAt = Date.now()
731
731
  if (this.data.onWsMessageAny) this.data.onWsMessageAny(e)
732
732
  if (e.data instanceof ArrayBuffer) {
@@ -1,9 +1,51 @@
1
- import WebSocket, { type CloseEvent, type Event, type MessageEvent } from 'ws'
1
+ // transport-agnostic since 2026-07-31 (architecture item 13): node uses the
2
+ // `ws` package (custom upgrade headers work), browsers the native WebSocket.
3
+ // The `ws` import specifier is a VARIABLE so browser bundlers never chase it.
2
4
  import type { Maybe } from 'src/types/index.ts'
3
5
  import { bang } from 'src/utils/bang.ts'
6
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
4
7
  import { logInfo } from 'src/utils/log.ts'
5
8
 
6
- type Message = string | Buffer
9
+ type Message = string | Uint8Array
10
+
11
+ /** structural face of both transports (ws package AND browser WebSocket) */
12
+ export type WsLike = {
13
+ binaryType: string
14
+ onmessage: ((event: WsMessageEvent) => void) | null
15
+ onopen: ((event: unknown) => void) | null
16
+ onclose: ((event: WsCloseEvent) => void) | null
17
+ onerror: ((event: unknown) => void) | null
18
+ send(data: Message): void
19
+ close(): void
20
+ }
21
+
22
+ /** what both transports deliver with binaryType 'arraybuffer': string or ArrayBuffer in `data` */
23
+ export type WsMessageEvent = { data: unknown }
24
+ export type WsCloseEvent = { code: number; reason: string }
25
+
26
+ type WsCtor = new (url: string, opts?: { headers?: Record<string, string> }) => WsLike
27
+
28
+ type WsTransport = { ctor: WsCtor; supportsHeaders: boolean }
29
+
30
+ let transportPromise: Promise<WsTransport> | null = null
31
+
32
+ /** node: the ws package (headers on the upgrade). browser: native WebSocket. */
33
+ function resolveWsTransport(): Promise<WsTransport> {
34
+ transportPromise ??= (async (): Promise<WsTransport> => {
35
+ const specifier = 'ws'
36
+ try {
37
+ // cast: the ws package ctor fits WsCtor structurally; a variable
38
+ // specifier types the import as any, so the shape is stated here
39
+ const mod = (await import(specifier)) as { default: WsCtor }
40
+ return { ctor: mod.default, supportsHeaders: true }
41
+ } catch {
42
+ const native = (globalThis as { WebSocket?: WsCtor }).WebSocket
43
+ if (native != null) return { ctor: native, supportsHeaders: false }
44
+ throw new Error(`no WebSocket transport: neither the 'ws' package nor a global WebSocket is available`)
45
+ }
46
+ })()
47
+ return transportPromise
48
+ }
7
49
 
8
50
  type WsDebugMessage = {
9
51
  type: 'info' | 'error'
@@ -12,9 +54,8 @@ type WsDebugMessage = {
12
54
  }
13
55
 
14
56
  export class ResilientWebSocketClient {
15
- // private protocols?: string | string[]
16
57
  private url: string
17
- private currentWS?: Maybe<WebSocket>
58
+ private currentWS?: Maybe<WsLike>
18
59
  private messageBuffer: Message[] = []
19
60
 
20
61
  isOpen: boolean = false
@@ -32,19 +73,24 @@ export class ResilientWebSocketClient {
32
73
 
33
74
  constructor(
34
75
  public options: {
35
- url: () => string /*protocols?: string | string[]*/
36
- /** upgrade-request headers (auth: X-API-Key & co) — a thunk, re-read on every reconnect */
76
+ url: () => string
77
+ /** upgrade-request headers (auth: X-API-Key & co) — a thunk, re-read on every reconnect.
78
+ * On a headerless transport (browser) X-API-Key rides `?token=` instead
79
+ * (the probed Comfy Cloud contract); other headers throw loud. */
37
80
  headers?: () => Record<string, string>
38
- onMessage: (event: MessageEvent) => void
81
+ onMessage: (event: WsMessageEvent) => void
39
82
  onConnectOrReconnect: () => void
40
83
  onClose: () => void
84
+ /** transport unrecoverable (no ws package AND no global WebSocket, or ctor threw):
85
+ * reported here ONCE, the client goes permanently closed — never a retry storm */
86
+ onTransportDead?: (error: unknown) => void
41
87
  },
42
88
  ) {
43
89
  this.url = options.url()
44
- this.connect()
90
+ void this.connect()
45
91
  }
46
92
 
47
- private reconnectTimeout?: Maybe<NodeJS.Timeout>
93
+ private reconnectTimeout?: Maybe<ReturnType<typeof setTimeout>>
48
94
  private permanentlyClosed: boolean = false
49
95
 
50
96
  /** close and stop reconnecting (lets a script exit cleanly) */
@@ -56,7 +102,21 @@ export class ResilientWebSocketClient {
56
102
  this.isOpen = false
57
103
  }
58
104
 
59
- private connect(): void {
105
+ /** headerless transports carry the api key as ?token= — everything else is refused loud */
106
+ private headerlessUrl(headers: Record<string, string>): string {
107
+ const rest = { ...headers }
108
+ const apiKey = rest['X-API-Key']
109
+ delete rest['X-API-Key']
110
+ const extra = Object.keys(rest)
111
+ if (extra.length > 0)
112
+ throw new Error(
113
+ `custom ws headers (${extra.join(', ')}) need the 'ws' package — a browser WebSocket cannot set upgrade headers`,
114
+ )
115
+ if (apiKey == null) return this.url
116
+ return this.url + (this.url.includes('?') ? '&' : '?') + 'token=' + encodeURIComponent(apiKey)
117
+ }
118
+
119
+ private async connect(): Promise<void> {
60
120
  this.isOpen = false
61
121
  const prevWS = this.currentWS
62
122
 
@@ -68,18 +128,32 @@ export class ResilientWebSocketClient {
68
128
  this.addInfo('Previous WebSocket discarded')
69
129
  prevWS.close()
70
130
  }
71
- const ws = new WebSocket(this.url, { headers: this.options.headers?.() })
131
+
132
+ let ws: WsLike
133
+ try {
134
+ const transport = await resolveWsTransport()
135
+ if (this.permanentlyClosed) return // closed while the transport resolved
136
+ const headers = this.options.headers?.() ?? {}
137
+ ws = transport.supportsHeaders
138
+ ? new transport.ctor(this.url, { headers })
139
+ : new transport.ctor(this.headerlessUrl(headers))
140
+ } catch (e) {
141
+ // connect() runs void'd (ctor + reconnect timer): a rethrow here would be
142
+ // an unhandled rejection, so the failure reports through onTransportDead
143
+ this.addError(`cannot open WebSocket: ${extractErrorMessage(e)}`)
144
+ this.permanentlyClosed = true
145
+ this.options.onTransportDead?.(e)
146
+ return
147
+ }
72
148
  ws.binaryType = 'arraybuffer'
73
149
 
74
150
  this.currentWS = ws
75
151
 
76
- if (this.options.onMessage) {
77
- ws.onmessage = (event: MessageEvent): void => {
78
- this.options.onMessage(event)
79
- }
152
+ ws.onmessage = (event: WsMessageEvent): void => {
153
+ this.options.onMessage(event)
80
154
  }
81
155
 
82
- ws.onopen = (_event: Event): void => {
156
+ ws.onopen = (): void => {
83
157
  if (ws !== this.currentWS) return
84
158
  this.addInfo('✅ WebSocket connected to ' + this.url)
85
159
  this.isOpen = true
@@ -87,17 +161,17 @@ export class ResilientWebSocketClient {
87
161
  this.flushMessageBuffer()
88
162
  }
89
163
 
90
- ws.onclose = (event: CloseEvent): void => {
164
+ ws.onclose = (event: WsCloseEvent): void => {
91
165
  if (ws !== this.currentWS) return
92
166
  this.isOpen = false
93
167
  this.options.onClose()
94
168
  if (this.permanentlyClosed) return
95
169
  this.addError(`WebSocket closed (reason=${JSON.stringify(event.reason)}, code=${event.code})`)
96
170
  this.addInfo('⏱️ reconnecting in 2 seconds...')
97
- this.reconnectTimeout = setTimeout(() => this.connect(), 2000)
171
+ this.reconnectTimeout = setTimeout(() => void this.connect(), 2000)
98
172
  }
99
173
 
100
- ws.onerror = (event: Event): void => {
174
+ ws.onerror = (event: unknown): void => {
101
175
  if (ws !== this.currentWS) return
102
176
  this.addError(`WebSocket ERROR` + JSON.stringify(event))
103
177
  console.error({ event })
@@ -118,32 +192,4 @@ export class ResilientWebSocketClient {
118
192
  this.currentWS?.send(message)
119
193
  }
120
194
  }
121
-
122
- /** forward WebSocket add event listeners to the current WebSocket instance */
123
- public addEventListener<K extends keyof WebSocketEventMap>(
124
- type: K,
125
- listener:
126
- | ((event: WebSocket.WebSocketEventMap[K]) => void)
127
- | { handleEvent(event: WebSocket.WebSocketEventMap[K]): void },
128
- options?: WebSocket.EventListenerOptions,
129
- ): void {
130
- this.currentWS?.addEventListener(type, listener, options)
131
- }
132
-
133
- /** forward WebSocket remove event listeners to the current WebSocket instance */
134
- public removeEventListener<K extends keyof WebSocketEventMap>(
135
- type: K,
136
- listener:
137
- | ((event: WebSocket.WebSocketEventMap[K]) => void)
138
- | { handleEvent(event: WebSocket.WebSocketEventMap[K]): void },
139
- ): void {
140
- this.currentWS?.removeEventListener(type, listener)
141
- }
142
- }
143
-
144
- type WebSocketEventMap = {
145
- open: Event
146
- close: CloseEvent
147
- error: Event
148
- message: MessageEvent
149
195
  }
@@ -47,7 +47,8 @@ export function renderHttpBase(p: ParsedHostBase): string {
47
47
  return `${p.scheme}://${p.host}${renderPort(p)}${p.basePath}`
48
48
  }
49
49
 
50
- /** ws(s) endpoint; auth NEVER rides the query string (headers own it) */
50
+ /** ws(s) endpoint; auth rides the upgrade headers — EXCEPT headerless
51
+ * transports (browser), where the ws client remaps X-API-Key to ?token= */
51
52
  export function renderWsUrl(p: ParsedHostBase): string {
52
53
  const scheme = p.scheme === 'https' ? 'wss' : 'ws'
53
54
  return `${scheme}://${p.host}${renderPort(p)}${p.basePath}/ws`