comfy-ts 1.3.0 → 2.0.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 (115) hide show
  1. package/README.md +106 -6
  2. package/dist/{DefinedWorkflow-gpknV-5f.js → DefinedWorkflow-CqNE_kgR.js} +67 -14
  3. package/dist/DefinedWorkflow-CqNE_kgR.js.map +1 -0
  4. package/dist/{DraftsSt-DmA0jWGl.js → DraftsSt-Da4DZUP7.js} +2 -2
  5. package/dist/{DraftsSt-DmA0jWGl.js.map → DraftsSt-Da4DZUP7.js.map} +1 -1
  6. package/dist/cli.js +3 -3
  7. package/dist/index.cjs +548 -239
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +164 -116
  10. package/dist/index.d.ts +165 -117
  11. package/dist/index.js +540 -230
  12. package/dist/index.js.map +1 -1
  13. package/dist/{run-serve-Bn6yIJB0.js → run-serve-BqeXtf8P.js} +9 -7
  14. package/dist/run-serve-BqeXtf8P.js.map +1 -0
  15. package/dist/{run-tui-BtjaOXRh.js → run-tui-CiB7TbYv.js} +18 -13
  16. package/dist/run-tui-CiB7TbYv.js.map +1 -0
  17. package/dist/{state-DKCPy105.js → state-C1g_B8zR.js} +398 -201
  18. package/dist/state-C1g_B8zR.js.map +1 -0
  19. package/dist/web.d.ts +17335 -0
  20. package/dist/web.js +5715 -0
  21. package/dist/web.js.map +1 -0
  22. package/examples/comfy-cloud/ace-step-t2a.cflow.ts +1 -0
  23. package/examples/comfy-cloud/anima-t2i.cflow.ts +2 -3
  24. package/examples/comfy-cloud/boogu-i2i.cflow.ts +2 -5
  25. package/examples/comfy-cloud/capybara-i2i.cflow.ts +2 -2
  26. package/examples/comfy-cloud/capybara-i2v.cflow.ts +1 -0
  27. package/examples/comfy-cloud/capybara-t2i.cflow.ts +2 -2
  28. package/examples/comfy-cloud/chatterbox-t2a.cflow.ts +1 -0
  29. package/examples/comfy-cloud/chroma-t2i.cflow.ts +2 -5
  30. package/examples/comfy-cloud/ernie-t2i.cflow.ts +2 -3
  31. package/examples/comfy-cloud/firered-i2i.cflow.ts +2 -2
  32. package/examples/comfy-cloud/flux1-i2i.cflow.ts +2 -2
  33. package/examples/comfy-cloud/flux1-t2i.cflow.ts +2 -2
  34. package/examples/comfy-cloud/flux2-i2i.cflow.ts +2 -5
  35. package/examples/comfy-cloud/flux2-t2i.cflow.ts +2 -5
  36. package/examples/comfy-cloud/hidream-i2i.cflow.ts +2 -5
  37. package/examples/comfy-cloud/hidream-t2i.cflow.ts +2 -2
  38. package/examples/comfy-cloud/hunyuan-video-i2v.cflow.ts +1 -0
  39. package/examples/comfy-cloud/hunyuan-video-t2v.cflow.ts +1 -0
  40. package/examples/comfy-cloud/ideogram4-t2i.cflow.ts +2 -3
  41. package/examples/comfy-cloud/kandinsky5-i2v.cflow.ts +1 -0
  42. package/examples/comfy-cloud/kandinsky5-t2i.cflow.ts +2 -2
  43. package/examples/comfy-cloud/kandinsky5-t2v.cflow.ts +1 -0
  44. package/examples/comfy-cloud/krea2-t2i.cflow.ts +2 -3
  45. package/examples/comfy-cloud/lens-t2i.cflow.ts +2 -3
  46. package/examples/comfy-cloud/longcat-i2i.cflow.ts +2 -2
  47. package/examples/comfy-cloud/longcat-t2i.cflow.ts +2 -5
  48. package/examples/comfy-cloud/ltxv-i2v.cflow.ts +1 -0
  49. package/examples/comfy-cloud/ltxv-t2v.cflow.ts +1 -0
  50. package/examples/comfy-cloud/newbie-t2i.cflow.ts +2 -5
  51. package/examples/comfy-cloud/omnigen2-i2i.cflow.ts +2 -5
  52. package/examples/comfy-cloud/omnigen2-t2i.cflow.ts +2 -5
  53. package/examples/comfy-cloud/ovis-t2i.cflow.ts +2 -5
  54. package/examples/comfy-cloud/pixeldit-t2i.cflow.ts +2 -5
  55. package/examples/comfy-cloud/qwen-image-i2i.cflow.ts +2 -2
  56. package/examples/comfy-cloud/qwen-image-t2i.cflow.ts +2 -2
  57. package/examples/comfy-cloud/sd35-t2i.cflow.ts +2 -2
  58. package/examples/comfy-cloud/sdk.d.ts +13251 -11458
  59. package/examples/comfy-cloud/sdxl-t2i.cflow.ts +2 -2
  60. package/examples/comfy-cloud/stable-audio-t2a.cflow.ts +1 -0
  61. package/examples/comfy-cloud/svd-i2v.cflow.ts +1 -0
  62. package/examples/comfy-cloud/wan21-i2v.cflow.ts +1 -0
  63. package/examples/comfy-cloud/wan21-t2v.cflow.ts +1 -0
  64. package/examples/comfy-cloud/wan22-5b-t2v.cflow.ts +1 -0
  65. package/examples/comfy-cloud/wan22-i2v.cflow.ts +1 -0
  66. package/examples/comfy-cloud/wan22-t2v.cflow.ts +1 -0
  67. package/examples/comfy-cloud/z-image-t2i.cflow.ts +2 -5
  68. package/examples/rvion/01-txt2img.cflow.ts +5 -3
  69. package/examples/rvion/02-img2img-upload.cflow.ts +5 -4
  70. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +6 -7
  71. package/examples/rvion/05-comfy-cloud.cflow.ts +4 -2
  72. package/examples/rvion/06-qwen-image-edit.cflow.ts +2 -3
  73. package/examples/web/example.ts +78 -0
  74. package/examples/web/index.html +77 -0
  75. package/examples/web/serve.ts +42 -0
  76. package/examples/web/tsconfig.json +15 -0
  77. package/package.json +8 -2
  78. package/src/cli/serve/ServeApp.ts +9 -6
  79. package/src/cli/tui/state/ExecSt.ts +14 -2
  80. package/src/coreExports.ts +118 -0
  81. package/src/host/ComfyHost.ts +56 -24
  82. package/src/host/ResilientWebsocket.ts +93 -47
  83. package/src/host/hostUrl.ts +2 -1
  84. package/src/host/loraManagerApi.ts +6 -7
  85. package/src/index.ts +8 -107
  86. package/src/manager/loaders/step2_custom-node-list-loader.ts +4 -4
  87. package/src/manager/loaders/step3_extension-node-map-loader.ts +3 -3
  88. package/src/manager/loaders/step4_model-list-loader.ts +7 -7
  89. package/src/manager/loaders/step5_alter-list-loader.ts +2 -2
  90. package/src/manager/loaders/step6_github-stats-loader.ts +2 -2
  91. package/src/runner/ComfyExecution.ts +168 -77
  92. package/src/runner/ComfyWorkflow.ts +25 -3
  93. package/src/runner/ComfyWsApi.ts +6 -0
  94. package/src/runner/MediaImage.ts +73 -38
  95. package/src/runner/ephemeral.ts +21 -0
  96. package/src/runner/outputPath.ts +2 -2
  97. package/src/sdk-generator/ComfySchema.ts +2 -2
  98. package/src/sdk-generator/_pythonModuleToNamespace.ts +3 -0
  99. package/src/state.ts +13 -9
  100. package/src/storage/ComfyStorage.ts +144 -0
  101. package/src/storage/nodeStorage.ts +9 -0
  102. package/src/types/index.ts +6 -2
  103. package/src/utils/downloadFile.ts +11 -69
  104. package/src/utils/hashArrayBuffer.ts +3 -4
  105. package/src/utils/lazySharp.ts +25 -0
  106. package/src/utils/sha1.ts +69 -0
  107. package/src/vars/ComfyVars.ts +5 -6
  108. package/src/vars/DefinedWorkflow.ts +3 -1
  109. package/src/vars/loraKeywords.ts +6 -6
  110. package/src/web.ts +13 -0
  111. package/dist/DefinedWorkflow-gpknV-5f.js.map +0 -1
  112. package/dist/run-serve-Bn6yIJB0.js.map +0 -1
  113. package/dist/run-tui-BtjaOXRh.js.map +0 -1
  114. package/dist/state-DKCPy105.js.map +0 -1
  115. package/src/utils/writeFile.ts +0 -16
@@ -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'
@@ -14,6 +13,7 @@ import {
14
13
  type ComfyStatusData,
15
14
  type LogEntry,
16
15
  type PromptID,
16
+ type PendingWsItem,
17
17
  type PromptRelated_WsMsg,
18
18
  type WsMsg,
19
19
  WsMsg_ark,
@@ -28,13 +28,12 @@ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
28
28
  import { printArkResultInConsole } from 'src/utils/printArkResultInConsole.ts'
29
29
  import { readableStringify } from 'src/utils/stringifyReadable.ts'
30
30
  import { logError as toastError, logInfo } from 'src/utils/log.ts'
31
- import { writeFileAsync } from 'src/utils/writeFile.ts'
32
31
  import type { ComfyInstallType } from 'src/host/ComfyInstallType.ts'
33
32
  import { ComfyManager } from 'src/host/ComfyManager.ts'
34
33
  import { ComfyUploader } from 'src/host/ComfyUploader.ts'
35
34
  import { type ParsedHostBase, parseHostBase, renderHttpBase, renderWsUrl } from 'src/host/hostUrl.ts'
36
35
  import type { Requirements } from 'src/host/Requirements.ts'
37
- import { ResilientWebSocketClient } from 'src/host/ResilientWebsocket.ts'
36
+ import { ResilientWebSocketClient, type WsMessageEvent } from 'src/host/ResilientWebsocket.ts'
38
37
  import { DefinedWorkflow, type DefineWorkflowSpec } from 'src/vars/DefinedWorkflow.ts'
39
38
  import type { VarsSpec } from 'src/vars/ComfyVars.ts'
40
39
 
@@ -65,7 +64,7 @@ export type ComfyHostData = {
65
64
  installType?: ComfyInstallType
66
65
 
67
66
  // misc
68
- onWsMessageAny?: (e: MessageEvent) => void
67
+ onWsMessageAny?: (e: WsMessageEvent) => void
69
68
  onWsMessageArrayBuffer?: (e: ArrayBuffer) => void
70
69
  onWsMessageJSON?: (e: WsMsg) => void
71
70
  }
@@ -122,10 +121,10 @@ export class ComfyHost<ID extends string = string> {
122
121
  this.cacheFolder = comfyts.resolveFromHosts(this.data.id)
123
122
 
124
123
  // create the folder if it does not exist
125
- const exists = existsSync(this.cacheFolder)
126
- if (!exists) {
124
+ const storage = getComfyStorage()
125
+ if (!storage.exists(this.cacheFolder)) {
127
126
  console.log('🟢 creating folder', this.cacheFolder)
128
- mkdirSync(this.cacheFolder, { recursive: true })
127
+ storage.mkdirp(this.cacheFolder)
129
128
  }
130
129
 
131
130
  this.comfyJSONPath = comfyts.resolve(this.cacheFolder, `object_info.json`)
@@ -435,22 +434,22 @@ export class ComfyHost<ID extends string = string> {
435
434
 
436
435
  private async writeSDKToDisk(): Promise<void> {
437
436
  if (this.data.sdkAutoWrite === false) return
437
+ const storage = getComfyStorage()
438
438
  const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id })
439
439
  // 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')
440
+ if (storage.readTextIfExists(this.sdkDTSPath) === comfySchemaTs) return
441
+ storage.writeText(this.sdkDTSPath, comfySchemaTs)
442
442
  }
443
443
 
444
444
  private shouldUseSchemaCache(): boolean {
445
445
  if (this._schemaStrategy === 'refresh') return false
446
- const exists = existsSync(this.comfyJSONPath)
446
+ const mtimeMs = getComfyStorage().mtimeMs(this.comfyJSONPath)
447
447
  if (this._schemaStrategy === 'cache') {
448
- if (!exists) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`)
448
+ if (mtimeMs == null) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`)
449
449
  return true
450
450
  }
451
- if (!exists) return false
452
- const ageMs = Date.now() - statSync(this.comfyJSONPath).mtimeMs
453
- return ageMs < this._schemaMaxAgeMs
451
+ if (mtimeMs == null) return false
452
+ return Date.now() - mtimeMs < this._schemaMaxAgeMs
454
453
  }
455
454
 
456
455
  // WEBSCKET -----------------------------------------------------------------------------
@@ -501,10 +500,12 @@ export class ComfyHost<ID extends string = string> {
501
500
  await this.waitForSession()
502
501
  this.markReady()
503
502
  },
504
- onMessage: (e: MessageEvent): void => this.onMessage(e),
503
+ onMessage: (e: WsMessageEvent): void => this.onMessage(e),
505
504
  url: () => this.getWSUrl(),
506
- // auth rides the upgrade HEADERS, never the query string
505
+ // auth rides the upgrade headers; headerless transports (browser)
506
+ // remap X-API-Key to ?token= inside the ws client
507
507
  headers: () => this.authHeaders(),
508
+ onTransportDead: (e): void => this.markFailed(e),
508
509
  onClose: (): void => {
509
510
  logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`)
510
511
  },
@@ -531,7 +532,7 @@ export class ComfyHost<ID extends string = string> {
531
532
  * examples must still open in the TUI; run() fetches the real schema through
532
533
  * connect() anyway). Not memoized in that case, so a later gen/connect retries. */
533
534
  loadSchemaFromCache(): Promise<void> {
534
- if (this._schemaFromCache == null && !existsSync(this.comfyJSONPath)) {
535
+ if (this._schemaFromCache == null && !getComfyStorage().exists(this.comfyJSONPath)) {
535
536
  toastError(
536
537
  `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
538
  )
@@ -546,7 +547,7 @@ export class ComfyHost<ID extends string = string> {
546
547
  this.schema.RUN_BASIC_CHECKS()
547
548
 
548
549
  // the on-disk sdk was generated from this same cache — only write when missing
549
- if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk()
550
+ if (!getComfyStorage().exists(this.sdkDTSPath)) await this.writeSDKToDisk()
550
551
  })().catch((e: unknown) => {
551
552
  this._schemaFromCache = null // a missing cache must stay retryable (e.g. after gen:sdk)
552
553
  throw e
@@ -574,6 +575,20 @@ export class ComfyHost<ID extends string = string> {
574
575
  return this.postJSON_('/interrupt', {})
575
576
  }
576
577
 
578
+ // HISTORY SCRUB (architecture.md item 14) -------------------------------------------
579
+ // deletes the server-side history ENTRY (workflow JSON, prompts, output
580
+ // filenames) — never files: the ephemeral tier creates none to begin with
581
+
582
+ /** delete ONE prompt's server history entry */
583
+ deleteHistory = (promptId: string): Promise<void> => {
584
+ return this.postJSON_('/history', { delete: [promptId] })
585
+ }
586
+
587
+ /** wipe the server's WHOLE prompt history (every user of that server) */
588
+ clearHistory = (): Promise<void> => {
589
+ return this.postJSON_('/history', { clear: true })
590
+ }
591
+
577
592
  // SERVER LOGS ----------------------------------------------------------------------
578
593
  // /internal routes are served bare (no /api prefix, no custom-node hijacks)
579
594
 
@@ -626,7 +641,7 @@ export class ComfyHost<ID extends string = string> {
626
641
  // e.g. lora-manager serves HTML at /embeddings)
627
642
  const object_info_json = await this.fetchJSON_<{ [key: string]: ComfySchemaJSON[string] }>('/object_info')
628
643
  const object_info_str = readableStringify(object_info_json, 4)
629
- void writeFileAsync(this.comfyJSONPath, object_info_str, 'utf-8')
644
+ getComfyStorage().writeText(this.comfyJSONPath, object_info_str)
630
645
  // use ark to check if payload match the type, and display errors if not
631
646
  const res = ComfySchemaJSON_ark(object_info_json)
632
647
  if (res instanceof type.errors) {
@@ -638,7 +653,7 @@ export class ComfyHost<ID extends string = string> {
638
653
  const embeddings_json = await this.fetchJSON_<EmbeddingName[]>('/embeddings').catch(
639
654
  () => [] as EmbeddingName[],
640
655
  )
641
- void writeFileAsync(this.embeddingsPath, JSON.stringify(embeddings_json), 'utf-8')
656
+ getComfyStorage().writeText(this.embeddingsPath, JSON.stringify(embeddings_json))
642
657
 
643
658
  // 3 ------------------------------------
644
659
  // update schema
@@ -657,7 +672,7 @@ export class ComfyHost<ID extends string = string> {
657
672
  console.error(error)
658
673
  console.error('🔴 FAILURE TO GENERATE the typed sdk', extractErrorMessage(error))
659
674
 
660
- const schemaExists = existsSync(this.sdkDTSPath)
675
+ const schemaExists = getComfyStorage().exists(this.sdkDTSPath)
661
676
  if (!schemaExists) await this.writeSDKToDisk()
662
677
  this.markFailed(error)
663
678
  } finally {
@@ -669,7 +684,7 @@ export class ComfyHost<ID extends string = string> {
669
684
  executions: Map<PromptID, ComfyExecution> = new Map()
670
685
 
671
686
  /** buffer in case we receive packets out of order */
672
- _pendingMsgs = new Map<PromptID, PromptRelated_WsMsg[]>()
687
+ _pendingMsgs = new Map<PromptID, PendingWsItem[]>()
673
688
 
674
689
  /** the active prompt currently running on this host */
675
690
  private activePromptID: PromptID | null = null
@@ -726,12 +741,29 @@ export class ComfyHost<ID extends string = string> {
726
741
  * never revives one) */
727
742
  lastWsMessageAt: number | null = null
728
743
 
729
- onMessage(e: MessageEvent): void {
744
+ onMessage(e: WsMessageEvent): void {
730
745
  this.lastWsMessageAt = Date.now()
731
746
  if (this.data.onWsMessageAny) this.data.onWsMessageAny(e)
732
747
  if (e.data instanceof ArrayBuffer) {
733
748
  const frame = parseBinaryWsFrame(e.data)
734
749
  if (frame.kind === 'preview') {
750
+ // OUTPUT, not preview: while a SaveImageWebsocket node executes,
751
+ // each preview-kind frame IS one output image (frames follow their
752
+ // 'executing' message on the same socket — architecture.md item 14)
753
+ const activeExec = this.activePromptID != null ? this.executions.get(this.activePromptID) : null
754
+ if (activeExec?.wsOutputNodeExecuting) {
755
+ activeExec.onWsImageOutput({ bytes: frame.bytes, mime: frame.mime })
756
+ return
757
+ }
758
+ // pre-registration window (reviewer catch 2026-07-31): ws messages
759
+ // can beat the POST /prompt response, and an ephemeral output frame
760
+ // in that window would be the ONLY copy of the image — buffer it IN
761
+ // ORDER with the json messages; ComfyExecution.onCreate replays the
762
+ // queue and decides output-vs-latent from the state at replay time
763
+ if (this.activePromptID != null) {
764
+ const pending = this._pendingMsgs.get(this.activePromptID)
765
+ if (pending != null) pending.push({ type: 'binary_preview_frame', bytes: frame.bytes, mime: frame.mime })
766
+ }
735
767
  // type 1 AND the cloud's type 4 (preview + metadata) feed the same hook
736
768
  const imageBlob = new Blob([frame.bytes], { type: frame.mime })
737
769
  this.latentPreview = {
@@ -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`
@@ -1,7 +1,6 @@
1
- import { createHash } from 'node:crypto'
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
3
1
  import { type } from 'arktype'
4
- import { dirname } from 'pathe'
2
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
3
+ import { sha1HexOfString } from 'src/utils/sha1.ts'
5
4
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
6
5
  import { logError } from 'src/utils/log.ts'
7
6
 
@@ -80,8 +79,9 @@ export function looksLikeImage(bytes: Uint8Array): boolean {
80
79
  * a non-image content-type OR non-image magic bytes => no preview, not a crash.
81
80
  */
82
81
  export async function fetchLoraPreviewBytes(host: ComfyHost, previewUrl: string): Promise<Uint8Array | null> {
83
- const cachePath = comfyts.resolveFromCache(`lora-previews/${createHash('sha1').update(previewUrl).digest('hex')}`)
84
- if (existsSync(cachePath)) return new Uint8Array(readFileSync(cachePath))
82
+ const storage = getComfyStorage()
83
+ const cachePath = comfyts.resolveFromCache(`lora-previews/${sha1HexOfString(previewUrl)}`)
84
+ if (storage.exists(cachePath)) return storage.readBytes(cachePath)
85
85
  try {
86
86
  // preview_url is already a full server-relative path — no /api probing
87
87
  const res = await host.fetch(previewUrl, {}, { apiPrefix: false })
@@ -90,8 +90,7 @@ export async function fetchLoraPreviewBytes(host: ComfyHost, previewUrl: string)
90
90
  if (ct !== '' && !ct.startsWith('image/')) return null // HTML fallback etc.
91
91
  const bytes = new Uint8Array(await res.arrayBuffer())
92
92
  if (!looksLikeImage(bytes)) return null
93
- mkdirSync(dirname(cachePath), { recursive: true })
94
- writeFileSync(cachePath, bytes)
93
+ storage.writeBytes(cachePath, bytes)
95
94
  return bytes
96
95
  } catch {
97
96
  return null