comfy-ts 0.3.0 → 1.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.
- package/README.md +349 -255
- package/dist/DefinedWorkflow-O3ynII3Y.js +598 -0
- package/dist/DefinedWorkflow-O3ynII3Y.js.map +1 -0
- package/dist/cli.js +3969 -128
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +1208 -170
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +449 -115
- package/dist/index.d.ts +449 -115
- package/dist/index.js +1200 -171
- package/dist/index.js.map +1 -1
- package/dist/{run-tui-Io8Xea0L.js → run-tui-BFhba_oG.js} +744 -665
- package/dist/run-tui-BFhba_oG.js.map +1 -0
- package/examples/01-txt2img.cflow.ts +50 -0
- package/examples/02-img2img-upload.cflow.ts +66 -0
- package/examples/03-export-workflow-json.cflow.ts +56 -0
- package/examples/04-krea2-turbo-t2i.cflow.ts +125 -0
- package/examples/05-comfy-cloud.cflow.ts +67 -0
- package/examples/comfy-cloud/sdk.d.ts +122674 -0
- package/guide-for-agents.md +166 -0
- package/package.json +7 -3
- package/src/cli/comfy-ts-cli.ts +19 -2
- package/src/cli/gen.ts +21 -12
- package/src/cli/tui/components/Header.tsx +5 -0
- package/src/cli/tui/components/LogsPanel.tsx +23 -0
- package/src/cli/tui/components/PreviewPanel.tsx +52 -7
- package/src/cli/tui/components/StatusBar.tsx +10 -4
- package/src/cli/tui/components/TreePanel.tsx +15 -2
- package/src/cli/tui/components/TuiApp.tsx +26 -3
- package/src/cli/tui/discoverWorkflows.ts +79 -0
- package/src/cli/tui/protocolImagePainter.ts +54 -18
- package/src/cli/tui/run-tui.tsx +55 -24
- package/src/cli/tui/state/ExecSt.ts +4 -1
- package/src/cli/tui/state/HostSt.ts +123 -1
- package/src/cli/tui/state/LogsSt.ts +107 -0
- package/src/cli/tui/state/PreviewSt.ts +173 -23
- package/src/cli/tui/state/SettingsSt.ts +48 -21
- package/src/cli/tui/state/TreeSt.ts +30 -6
- package/src/cli/tui/state/TuiSt.ts +27 -3
- package/src/cli/tui/state/WorkflowsSt.ts +16 -1
- package/src/host/ComfyHost.ts +241 -71
- package/src/host/ComfyManager.ts +10 -9
- package/src/host/ComfyUploader.ts +1 -2
- package/src/host/ResilientWebsocket.ts +3 -1
- package/src/host/hostUrl.ts +59 -0
- package/src/host/loraManagerApi.ts +5 -4
- package/src/index.ts +20 -1
- package/src/litegraph/CanonicalWorkflow.ts +77 -0
- package/src/litegraph/LiteGraphGroup.ts +9 -7
- package/src/litegraph/LiteGraphJSON.ts +34 -13
- package/src/litegraph/LiteGraphLink.ts +32 -2
- package/src/litegraph/LiteGraphNode.ts +18 -33
- package/src/litegraph/LiteGraphNodeInput.ts +10 -8
- package/src/litegraph/LiteGraphNodeOutput.ts +2 -3
- package/src/litegraph/LiteGraphSubgraphDef.ts +74 -0
- package/src/litegraph/convertFlowToLiteGraphJSON.ts +4 -4
- package/src/litegraph/expandSubgraphs.ts +352 -0
- package/src/litegraph/normalizeWorkflow.ts +141 -0
- package/src/runner/ComfyExecution.ts +4 -5
- package/src/runner/ComfyWorkflow.ts +2 -2
- package/src/runner/ComfyWsApi.ts +12 -1
- package/src/runner/wsBinaryFrame.ts +48 -0
- package/src/sdk-generator/Primitives.ts +6 -24
- package/src/sdk-generator/comfy-api-json.ts +3 -1
- package/src/sdk-generator/inputWidgetKind.ts +179 -0
- package/src/sdk-generator/litegraphToApiRequestPayload.ts +372 -96
- package/src/ssh-host-manager/ssh-manager.ts +0 -15
- package/src/state.ts +13 -2
- package/src/utils/ansi.ts +7 -0
- package/src/utils/mojibake.ts +60 -0
- package/dist/log-CdfgILde.js +0 -10
- package/dist/log-CdfgILde.js.map +0 -1
- package/dist/run-tui-Io8Xea0L.js.map +0 -1
package/src/host/ComfyHost.ts
CHANGED
|
@@ -6,15 +6,18 @@ import type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPlugin
|
|
|
6
6
|
import type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'
|
|
7
7
|
import type { ComfyExecution } from 'src/runner/ComfyExecution.ts'
|
|
8
8
|
import type { ComfyApiJson } from 'src/sdk-generator/comfy-api-json.ts'
|
|
9
|
-
import
|
|
9
|
+
import { parseWorkflowJson } from 'src/litegraph/normalizeWorkflow.ts'
|
|
10
|
+
import { parseBinaryWsFrame } from 'src/runner/wsBinaryFrame.ts'
|
|
10
11
|
import { convertLiteGraphToPrompt } from 'src/sdk-generator/litegraphToApiRequestPayload.ts'
|
|
11
12
|
import { asComfyWorkflowID, ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'
|
|
12
13
|
import {
|
|
13
14
|
type ComfyStatusData,
|
|
15
|
+
type LogEntry,
|
|
14
16
|
type PromptID,
|
|
15
17
|
type PromptRelated_WsMsg,
|
|
16
18
|
type WsMsg,
|
|
17
19
|
WsMsg_ark,
|
|
20
|
+
WsMsgLogsData_ark,
|
|
18
21
|
} from 'src/runner/ComfyWsApi.ts'
|
|
19
22
|
import { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
|
|
20
23
|
import { type ComfySchemaJSON, ComfySchemaJSON_ark } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'
|
|
@@ -29,6 +32,7 @@ import { writeFileAsync } from 'src/utils/writeFile.ts'
|
|
|
29
32
|
import type { ComfyInstallType } from 'src/host/ComfyInstallType.ts'
|
|
30
33
|
import { ComfyManager } from 'src/host/ComfyManager.ts'
|
|
31
34
|
import { ComfyUploader } from 'src/host/ComfyUploader.ts'
|
|
35
|
+
import { type ParsedHostBase, parseHostBase, renderHttpBase, renderWsUrl } from 'src/host/hostUrl.ts'
|
|
32
36
|
import type { Requirements } from 'src/host/Requirements.ts'
|
|
33
37
|
import { ResilientWebSocketClient } from 'src/host/ResilientWebsocket.ts'
|
|
34
38
|
import { DefinedWorkflow, type DefineWorkflowSpec } from 'src/vars/DefinedWorkflow.ts'
|
|
@@ -37,10 +41,26 @@ import type { VarsSpec } from 'src/vars/ComfyVars.ts'
|
|
|
37
41
|
export type ComfyHostID = Tagged<string, { HostID: true }>
|
|
38
42
|
export type ComfyHostData = {
|
|
39
43
|
id: string
|
|
40
|
-
|
|
41
|
-
|
|
44
|
+
|
|
45
|
+
/** full base url as pasted from a provider (https://cloud.comfy.org,
|
|
46
|
+
* https://xxx.modal.run, http://192.168.1.5:8188/comfy).
|
|
47
|
+
* Exactly ONE of url OR the legacy host+port (+https?) spelling. */
|
|
48
|
+
url?: string
|
|
49
|
+
host?: string
|
|
50
|
+
port?: number
|
|
42
51
|
https?: boolean
|
|
43
52
|
|
|
53
|
+
/** sent as X-API-Key on every request AND the ws upgrade.
|
|
54
|
+
* NEVER persist the value: read it from an env var (e.g. COMFY_CLOUD_API_KEY) */
|
|
55
|
+
apiKey?: string
|
|
56
|
+
/** default true. false = never write sdk.d.ts to .comfy-ts/hosts/<id>/ —
|
|
57
|
+
* schema updates stay in-memory. The comfy-cloud example sets false: its sdk
|
|
58
|
+
* home is the COMMITTED examples/comfy-cloud/sdk.d.ts (gen:sdk:cloud), and a
|
|
59
|
+
* second copy under .comfy-ts/hosts/ would double-declare the globals. */
|
|
60
|
+
sdkAutoWrite?: boolean
|
|
61
|
+
/** extra headers merged into every request + the ws upgrade (Modal-style auth pairs) */
|
|
62
|
+
headers?: Record<string, string>
|
|
63
|
+
|
|
44
64
|
// for extra features using path manipulation
|
|
45
65
|
installType?: ComfyInstallType
|
|
46
66
|
|
|
@@ -66,6 +86,20 @@ type ServerLog = {
|
|
|
66
86
|
id: number
|
|
67
87
|
}
|
|
68
88
|
|
|
89
|
+
/** auth failure with a SPECIFIC meaning (per the Comfy Cloud error table):
|
|
90
|
+
* 401 invalid/missing key · 402 insufficient credits · 429 subscription inactive
|
|
91
|
+
* (or plain rate limiting on non-cloud hosts). The key value never appears here. */
|
|
92
|
+
export class ComfyHostAuthError extends Error {
|
|
93
|
+
constructor(
|
|
94
|
+
public code: 401 | 402 | 429,
|
|
95
|
+
public hostId: string,
|
|
96
|
+
message: string,
|
|
97
|
+
) {
|
|
98
|
+
super(message)
|
|
99
|
+
this.name = 'ComfyHostAuthError'
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
69
103
|
export class ComfyHost<ID extends string = string> {
|
|
70
104
|
// ----- misc paths where we'll store host-related files -----
|
|
71
105
|
cacheFolder: AbsolutePath
|
|
@@ -78,7 +112,12 @@ export class ComfyHost<ID extends string = string> {
|
|
|
78
112
|
schema: ComfySchema
|
|
79
113
|
uploader = new ComfyUploader(this)
|
|
80
114
|
|
|
115
|
+
/** parsed ONCE from data (url-first or legacy host/port/https) — the url ground truth */
|
|
116
|
+
readonly base: ParsedHostBase
|
|
117
|
+
|
|
81
118
|
constructor(public data: ComfyHostData & { id: ID }) {
|
|
119
|
+
this.base = parseHostBase(this.data)
|
|
120
|
+
|
|
82
121
|
/** folder where file related to the host config will be cached */
|
|
83
122
|
this.cacheFolder = comfyts.resolveFromHosts(this.data.id)
|
|
84
123
|
|
|
@@ -196,17 +235,106 @@ export class ComfyHost<ID extends string = string> {
|
|
|
196
235
|
|
|
197
236
|
// URLS -----------------------------------------------------------------------------
|
|
198
237
|
getServerHostHTTP(): string {
|
|
199
|
-
|
|
200
|
-
const host = this.data.host
|
|
201
|
-
const port = this.data.port
|
|
202
|
-
return `${method}://${host}:${port}`
|
|
238
|
+
return renderHttpBase(this.base)
|
|
203
239
|
}
|
|
204
240
|
|
|
205
241
|
getWSUrl = (): string => {
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
242
|
+
return renderWsUrl(this.base)
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// HTTP -----------------------------------------------------------------------------
|
|
246
|
+
/** extra headers + X-API-Key, for every http request AND the ws upgrade */
|
|
247
|
+
private authHeaders(): Record<string, string> {
|
|
248
|
+
const out: Record<string, string> = {}
|
|
249
|
+
if (this.data.headers != null) Object.assign(out, this.data.headers)
|
|
250
|
+
if (this.data.apiKey != null) out['X-API-Key'] = this.data.apiKey
|
|
251
|
+
return out
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** remembered /api-prefix verdict for this host; null until first probed */
|
|
255
|
+
private _apiPrefix: boolean | null = null
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* the ONE http path to this host: joins basePath, injects X-API-Key + extra
|
|
259
|
+
* headers, prefers `/api<route>` (required by Comfy Cloud, canonical since
|
|
260
|
+
* custom nodes hijack bare routes) with a bare-route fallback on 404/405 for
|
|
261
|
+
* old local servers (winner memoized; the other spelling is still retried
|
|
262
|
+
* when the memo misses — mixed servers exist, e.g. /internal is bare-only).
|
|
263
|
+
* Auth failures throw a typed ComfyHostAuthError instead of generic noise.
|
|
264
|
+
* `p.apiPrefix: false` opts a route out of the prefix game entirely.
|
|
265
|
+
*/
|
|
266
|
+
fetch = async (route: string, init: RequestInit = {}, p: { apiPrefix?: boolean } = {}): Promise<Response> => {
|
|
267
|
+
const base = this.getServerHostHTTP()
|
|
268
|
+
const headers = new Headers(init.headers)
|
|
269
|
+
for (const [k, v] of Object.entries(this.authHeaders())) headers.set(k, v)
|
|
270
|
+
const send = (prefixed: boolean): Promise<Response> =>
|
|
271
|
+
fetch(`${base}${prefixed ? '/api' : ''}${route}`, { ...init, headers })
|
|
272
|
+
const missed = (res: Response): boolean => res.status === 404 || res.status === 405
|
|
273
|
+
|
|
274
|
+
let res: Response
|
|
275
|
+
if (p.apiPrefix === false) {
|
|
276
|
+
res = await send(false)
|
|
277
|
+
} else if (this._apiPrefix != null) {
|
|
278
|
+
res = await send(this._apiPrefix)
|
|
279
|
+
if (missed(res)) {
|
|
280
|
+
const alt = await send(!this._apiPrefix)
|
|
281
|
+
if (!missed(alt)) res = alt
|
|
282
|
+
}
|
|
283
|
+
} else {
|
|
284
|
+
res = await send(true)
|
|
285
|
+
if (missed(res)) {
|
|
286
|
+
const bare = await send(false)
|
|
287
|
+
if (!missed(bare)) {
|
|
288
|
+
this._apiPrefix = false
|
|
289
|
+
res = bare
|
|
290
|
+
}
|
|
291
|
+
} else {
|
|
292
|
+
this._apiPrefix = true
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
this.throwOnAuthError(res, route)
|
|
296
|
+
return res
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* binary download path: Comfy Cloud answers `/api/view` with a 302 to a
|
|
301
|
+
* temporary signed URL. fetch only auto-strips Authorization/cookies on
|
|
302
|
+
* cross-origin redirects — a custom X-API-Key WOULD be forwarded to the
|
|
303
|
+
* storage host — so we follow the Location manually with a CLEAN fetch.
|
|
304
|
+
*/
|
|
305
|
+
fetchFile = async (route: string): Promise<Response> => {
|
|
306
|
+
const res = await this.fetch(route, { redirect: 'manual' })
|
|
307
|
+
if (res.status >= 300 && res.status < 400) {
|
|
308
|
+
const location = res.headers.get('location')
|
|
309
|
+
if (location == null)
|
|
310
|
+
throw new Error(`GET ${route} on host '${this.data.id}' redirected (${res.status}) without a Location`)
|
|
311
|
+
void res.body?.cancel()
|
|
312
|
+
return fetch(new URL(location, this.getServerHostHTTP()))
|
|
313
|
+
}
|
|
314
|
+
return res
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
private throwOnAuthError(res: Response, route: string): void {
|
|
318
|
+
if (res.status === 401)
|
|
319
|
+
throw new ComfyHostAuthError(
|
|
320
|
+
401,
|
|
321
|
+
this.data.id,
|
|
322
|
+
this.data.apiKey != null
|
|
323
|
+
? `host '${this.data.id}': 401 on ${route} — API key invalid or expired`
|
|
324
|
+
: `host '${this.data.id}': 401 on ${route} — host requires authentication, no apiKey configured`,
|
|
325
|
+
)
|
|
326
|
+
if (res.status === 402)
|
|
327
|
+
throw new ComfyHostAuthError(
|
|
328
|
+
402,
|
|
329
|
+
this.data.id,
|
|
330
|
+
`host '${this.data.id}': 402 on ${route} — insufficient credits`,
|
|
331
|
+
)
|
|
332
|
+
if (res.status === 429)
|
|
333
|
+
throw new ComfyHostAuthError(
|
|
334
|
+
429,
|
|
335
|
+
this.data.id,
|
|
336
|
+
`host '${this.data.id}': 429 on ${route} — subscription inactive or rate limited`,
|
|
337
|
+
)
|
|
210
338
|
}
|
|
211
339
|
|
|
212
340
|
// LOGS -----------------------------------------------------------------------------
|
|
@@ -237,9 +365,14 @@ export class ComfyHost<ID extends string = string> {
|
|
|
237
365
|
return new DefinedWorkflow(this, spec)
|
|
238
366
|
}
|
|
239
367
|
|
|
240
|
-
/**
|
|
241
|
-
|
|
242
|
-
|
|
368
|
+
/**
|
|
369
|
+
* import a workflow.json (litegraph format) as a live, editable workflow.
|
|
370
|
+
* Accepts unknown: the JSON is ark-validated + normalized (parseWorkflowJson)
|
|
371
|
+
* before conversion — invalid documents throw WorkflowNormalizeError.
|
|
372
|
+
*/
|
|
373
|
+
importWorkflowJson = (json: unknown, p: { id?: string } = {}): ComfyWorkflow<ID> => {
|
|
374
|
+
const canonical = parseWorkflowJson(json)
|
|
375
|
+
const apiJson = convertLiteGraphToPrompt(this.schema, canonical)
|
|
243
376
|
return this.importApiJson(apiJson, p)
|
|
244
377
|
}
|
|
245
378
|
|
|
@@ -301,6 +434,7 @@ export class ComfyHost<ID extends string = string> {
|
|
|
301
434
|
}
|
|
302
435
|
|
|
303
436
|
private async writeSDKToDisk(): Promise<void> {
|
|
437
|
+
if (this.data.sdkAutoWrite === false) return
|
|
304
438
|
const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id })
|
|
305
439
|
// skip the 4MB write when nothing changed (fast re-connects)
|
|
306
440
|
if (existsSync(this.sdkDTSPath) && readFileSync(this.sdkDTSPath, 'utf-8') === comfySchemaTs) return
|
|
@@ -369,6 +503,8 @@ export class ComfyHost<ID extends string = string> {
|
|
|
369
503
|
},
|
|
370
504
|
onMessage: (e: MessageEvent): void => this.onMessage(e),
|
|
371
505
|
url: () => this.getWSUrl(),
|
|
506
|
+
// auth rides the upgrade HEADERS, never the query string
|
|
507
|
+
headers: () => this.authHeaders(),
|
|
372
508
|
onClose: (): void => {
|
|
373
509
|
logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`)
|
|
374
510
|
},
|
|
@@ -389,8 +525,18 @@ export class ComfyHost<ID extends string = string> {
|
|
|
389
525
|
private _schemaFromCache: Promise<void> | null = null
|
|
390
526
|
|
|
391
527
|
/** load the schema from .comfy-ts/hosts/<id>/ without connecting (offline workflows, fast starts).
|
|
392
|
-
* idempotent like connect(): N co-imported modules parse the ~4MB cache once
|
|
528
|
+
* idempotent like connect(): N co-imported modules parse the ~4MB cache once.
|
|
529
|
+
* A MISSING cache degrades LOUDLY to the base types instead of failing the
|
|
530
|
+
* module import (a fresh consumer project has no cache yet — the bundled
|
|
531
|
+
* examples must still open in the TUI; run() fetches the real schema through
|
|
532
|
+
* connect() anyway). Not memoized in that case, so a later gen/connect retries. */
|
|
393
533
|
loadSchemaFromCache(): Promise<void> {
|
|
534
|
+
if (this._schemaFromCache == null && !existsSync(this.comfyJSONPath)) {
|
|
535
|
+
toastError(
|
|
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
|
+
)
|
|
538
|
+
return Promise.resolve()
|
|
539
|
+
}
|
|
394
540
|
this._schemaFromCache ??= (async (): Promise<void> => {
|
|
395
541
|
const object_info_json = comfyts.readJSON_<ComfySchemaJSON>(this.comfyJSONPath)
|
|
396
542
|
const embeddings_json = comfyts.readJSON_<string[]>(this.embeddingsPath, [])
|
|
@@ -408,18 +554,14 @@ export class ComfyHost<ID extends string = string> {
|
|
|
408
554
|
return this._schemaFromCache
|
|
409
555
|
}
|
|
410
556
|
|
|
411
|
-
/** POST a JSON route
|
|
557
|
+
/** POST a JSON route through host.fetch (/api preferred, bare fallback) */
|
|
412
558
|
private postJSON_ = async (route: string, body: unknown): Promise<void> => {
|
|
413
|
-
const
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
})
|
|
420
|
-
if (res.ok) return
|
|
421
|
-
}
|
|
422
|
-
throw new Error(`POST ${route} failed on ${base} (tried /api${route} and ${route})`)
|
|
559
|
+
const res = await this.fetch(route, {
|
|
560
|
+
method: 'POST',
|
|
561
|
+
headers: { 'Content-Type': 'application/json' },
|
|
562
|
+
body: JSON.stringify(body),
|
|
563
|
+
})
|
|
564
|
+
if (!res.ok) throw new Error(`POST ${route} failed on ${this.getServerHostHTTP()}: ${res.status}`)
|
|
423
565
|
}
|
|
424
566
|
|
|
425
567
|
/** drop every PENDING prompt from the server queue (the running one keeps going) */
|
|
@@ -432,16 +574,47 @@ export class ComfyHost<ID extends string = string> {
|
|
|
432
574
|
return this.postJSON_('/interrupt', {})
|
|
433
575
|
}
|
|
434
576
|
|
|
435
|
-
|
|
577
|
+
// SERVER LOGS ----------------------------------------------------------------------
|
|
578
|
+
// /internal routes are served bare (no /api prefix, no custom-node hijacks)
|
|
579
|
+
|
|
580
|
+
/** the server's recent console buffer (entries are write CHUNKS, not lines) */
|
|
581
|
+
fetchRawLogs = async (): Promise<{ entries: LogEntry[] }> => {
|
|
582
|
+
const res = await this.fetch('/internal/logs/raw', {}, { apiPrefix: false })
|
|
583
|
+
if (!res.ok) throw new Error(`GET /internal/logs/raw failed: ${res.status}`)
|
|
584
|
+
const json: unknown = await res.json()
|
|
585
|
+
// wire tolerance (agent/coding.md cast #4): soft-validate, log, still cast
|
|
586
|
+
const checked = WsMsgLogsData_ark(json)
|
|
587
|
+
if (checked instanceof type.errors) {
|
|
588
|
+
console.log(`[🔴] /!\\ /internal/logs/raw payload does not match schema.`)
|
|
589
|
+
printArkResultInConsole(checked)
|
|
590
|
+
}
|
|
591
|
+
return json as { entries: LogEntry[] }
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/** (un)subscribe THIS session to ws 'logs' messages — per-sid server state,
|
|
595
|
+
* must be re-sent after every reconnect (see onSession) */
|
|
596
|
+
subscribeLogs = async (p: { enabled: boolean; clientId: string }): Promise<void> => {
|
|
597
|
+
const res = await this.fetch(
|
|
598
|
+
'/internal/logs/subscribe',
|
|
599
|
+
{
|
|
600
|
+
method: 'PATCH',
|
|
601
|
+
headers: { 'Content-Type': 'application/json' },
|
|
602
|
+
body: JSON.stringify({ enabled: p.enabled, clientId: p.clientId }),
|
|
603
|
+
},
|
|
604
|
+
{ apiPrefix: false },
|
|
605
|
+
)
|
|
606
|
+
if (!res.ok) throw new Error(`PATCH /internal/logs/subscribe failed: ${res.status}`)
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/** GET a JSON route through host.fetch (/api preferred, bare fallback) */
|
|
436
610
|
private fetchJSON_ = async <T>(route: string): Promise<T> => {
|
|
437
611
|
const base = this.getServerHostHTTP()
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
throw new Error(`GET ${route} failed on ${base} (tried /api${route} and ${route})`)
|
|
612
|
+
const res = await this.fetch(route)
|
|
613
|
+
if (!res.ok) throw new Error(`GET ${route} failed on ${base}: ${res.status}`)
|
|
614
|
+
const contentType = res.headers.get('content-type') ?? ''
|
|
615
|
+
if (!contentType.includes('json'))
|
|
616
|
+
throw new Error(`GET ${route} on ${base} answered '${contentType || 'no content-type'}' instead of json`)
|
|
617
|
+
return (await res.json()) as T
|
|
445
618
|
}
|
|
446
619
|
|
|
447
620
|
/** retrieve the comfy spec from the schema*/
|
|
@@ -531,54 +704,44 @@ export class ComfyHost<ID extends string = string> {
|
|
|
531
704
|
/** fires on every ws 'status' message (queue length lives there) */
|
|
532
705
|
onStatus: Maybe<(p: { queueRemaining: number }) => void> = null
|
|
533
706
|
|
|
707
|
+
/** fires when the server assigns a NEW session id (first connect AND every
|
|
708
|
+
* reconnect — per-sid server state like log subscriptions must be redone) */
|
|
709
|
+
onSession: Maybe<(sid: string) => void> = null
|
|
710
|
+
|
|
711
|
+
/** fires on ws 'logs' messages (server console stream, see subscribeLogs) */
|
|
712
|
+
onLogs: Maybe<(p: { entries: LogEntry[] }) => void> = null
|
|
713
|
+
|
|
534
714
|
/** the session assigned to us by the server */
|
|
535
715
|
comfySessionId: string = 'temp' /** send by ComfyUI server */
|
|
536
716
|
|
|
717
|
+
/** binary frame types we already complained about (one log per type, no spam) */
|
|
718
|
+
private _unknownBinaryFrameTypes = new Set<number>()
|
|
719
|
+
|
|
537
720
|
/** handy to keep around */
|
|
538
721
|
status: ComfyStatusData['status'] | null = null
|
|
539
722
|
|
|
540
723
|
onMessage(e: MessageEvent): void {
|
|
541
724
|
if (this.data.onWsMessageAny) this.data.onWsMessageAny(e)
|
|
542
725
|
if (e.data instanceof ArrayBuffer) {
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
switch (imageType) {
|
|
553
|
-
case 1:
|
|
554
|
-
imageMime = 'image/jpeg'
|
|
555
|
-
break
|
|
556
|
-
case 2:
|
|
557
|
-
imageMime = 'image/png'
|
|
558
|
-
break
|
|
559
|
-
default:
|
|
560
|
-
imageMime = 'image/jpeg'
|
|
561
|
-
break
|
|
562
|
-
}
|
|
563
|
-
const imageBytes = buffer.slice(4)
|
|
564
|
-
const imageBlob = new Blob([imageBytes], { type: imageMime })
|
|
565
|
-
const imagePreview = URL.createObjectURL(imageBlob)
|
|
566
|
-
this.latentPreview = {
|
|
567
|
-
blob: imageBlob,
|
|
568
|
-
url: imagePreview,
|
|
569
|
-
receivedAt: Date.now() as number_Timestamp,
|
|
570
|
-
promptID: this.activePromptID,
|
|
571
|
-
}
|
|
572
|
-
this.onLatentPreview?.({
|
|
573
|
-
bytes: new Uint8Array(imageBytes),
|
|
574
|
-
mime: imageMime,
|
|
575
|
-
promptID: this.activePromptID,
|
|
576
|
-
})
|
|
577
|
-
break
|
|
726
|
+
const frame = parseBinaryWsFrame(e.data)
|
|
727
|
+
if (frame.kind === 'preview') {
|
|
728
|
+
// type 1 AND the cloud's type 4 (preview + metadata) feed the same hook
|
|
729
|
+
const imageBlob = new Blob([frame.bytes], { type: frame.mime })
|
|
730
|
+
this.latentPreview = {
|
|
731
|
+
blob: imageBlob,
|
|
732
|
+
url: URL.createObjectURL(imageBlob),
|
|
733
|
+
receivedAt: Date.now() as number_Timestamp,
|
|
734
|
+
promptID: this.activePromptID,
|
|
578
735
|
}
|
|
579
|
-
|
|
580
|
-
|
|
736
|
+
this.onLatentPreview?.({ bytes: frame.bytes, mime: frame.mime, promptID: this.activePromptID })
|
|
737
|
+
} else if (frame.kind === 'unknown' && !this._unknownBinaryFrameTypes.has(frame.eventType)) {
|
|
738
|
+
// wire tolerance: log once per type, never throw (a throw per sampling
|
|
739
|
+
// step is what the first live cloud run did on type 4)
|
|
740
|
+
this._unknownBinaryFrameTypes.add(frame.eventType)
|
|
741
|
+
console.error(`🔴 unknown binary ws frame type ${frame.eventType} from host ${this.data.id} — ignored`)
|
|
581
742
|
}
|
|
743
|
+
// frame.kind === 'text' (node progress text) is dropped: the json
|
|
744
|
+
// 'progress' messages already carry everything we surface
|
|
582
745
|
return
|
|
583
746
|
}
|
|
584
747
|
|
|
@@ -601,9 +764,11 @@ export class ComfyHost<ID extends string = string> {
|
|
|
601
764
|
|
|
602
765
|
if (msg.type === 'status') {
|
|
603
766
|
if (msg.data.sid) {
|
|
767
|
+
const sidChanged = msg.data.sid !== this.comfySessionId
|
|
604
768
|
this.comfySessionId = msg.data.sid
|
|
605
769
|
this._sessionResolve?.()
|
|
606
770
|
this._sessionResolve = null
|
|
771
|
+
if (sidChanged) this.onSession?.(msg.data.sid)
|
|
607
772
|
}
|
|
608
773
|
this.status = msg.data.status
|
|
609
774
|
this.onStatus?.({ queueRemaining: msg.data.status?.exec_info?.queue_remaining ?? 0 })
|
|
@@ -637,6 +802,11 @@ export class ComfyHost<ID extends string = string> {
|
|
|
637
802
|
this.addLog(msg.data.data)
|
|
638
803
|
return
|
|
639
804
|
}
|
|
805
|
+
|
|
806
|
+
if (msg.type === 'logs') {
|
|
807
|
+
this.onLogs?.(msg.data)
|
|
808
|
+
return
|
|
809
|
+
}
|
|
640
810
|
exhaust(msg)
|
|
641
811
|
console.log('❌', 'Unknown message:', msg)
|
|
642
812
|
|
package/src/host/ComfyManager.ts
CHANGED
|
@@ -21,7 +21,12 @@ import { softValidate } from 'src/utils/softValidate.ts'
|
|
|
21
21
|
import type { PluginInstallStatus } from 'src/host/Requirements.ts'
|
|
22
22
|
|
|
23
23
|
export class ComfyManager {
|
|
24
|
-
constructor(
|
|
24
|
+
constructor(
|
|
25
|
+
public host: {
|
|
26
|
+
getServerHostHTTP: () => string
|
|
27
|
+
fetch: (route: string, init?: RequestInit, p?: { apiPrefix?: boolean }) => Promise<Response>
|
|
28
|
+
},
|
|
29
|
+
) {
|
|
25
30
|
// void this.updateHostPluginsAndModels()
|
|
26
31
|
}
|
|
27
32
|
|
|
@@ -58,11 +63,10 @@ export class ComfyManager {
|
|
|
58
63
|
no()
|
|
59
64
|
}
|
|
60
65
|
if (abortCtrl) abortCtrl.abort()
|
|
61
|
-
const url = this.host.getServerHostHTTP()
|
|
62
66
|
abortCtrl = new AbortController()
|
|
63
67
|
try {
|
|
64
68
|
console.log(` - trying...`)
|
|
65
|
-
await fetch(
|
|
69
|
+
await this.host.fetch('/', { signal: abortCtrl.signal }, { apiPrefix: false })
|
|
66
70
|
clearInterval(interval)
|
|
67
71
|
yes(true)
|
|
68
72
|
} catch {
|
|
@@ -200,8 +204,7 @@ export class ComfyManager {
|
|
|
200
204
|
|
|
201
205
|
// --------------------------------------------------------------
|
|
202
206
|
private fetchPost = async <IN, OUT = unknown>(endpoint: string, body: IN, validator?: Type<OUT>): Promise<OUT> => {
|
|
203
|
-
const
|
|
204
|
-
const response = await fetch(url, {
|
|
207
|
+
const response = await this.host.fetch(endpoint, {
|
|
205
208
|
method: 'POST',
|
|
206
209
|
headers: { 'Content-Type': 'application/json' },
|
|
207
210
|
body: JSON.stringify(body),
|
|
@@ -214,8 +217,7 @@ export class ComfyManager {
|
|
|
214
217
|
}
|
|
215
218
|
|
|
216
219
|
private fetchGetJSON = async <OUT = unknown>(endpoint: string, validator?: Type<OUT>): Promise<OUT> => {
|
|
217
|
-
const
|
|
218
|
-
const response = await fetch(url)
|
|
220
|
+
const response = await this.host.fetch(endpoint)
|
|
219
221
|
if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`)
|
|
220
222
|
const jsonResult = await response.json()
|
|
221
223
|
if (validator) return softValidate(validator, jsonResult)
|
|
@@ -224,8 +226,7 @@ export class ComfyManager {
|
|
|
224
226
|
}
|
|
225
227
|
|
|
226
228
|
private fetchGetText = async (endopint: string): Promise<string> => {
|
|
227
|
-
const
|
|
228
|
-
const response = await fetch(url)
|
|
229
|
+
const response = await this.host.fetch(endopint)
|
|
229
230
|
const status = await response.text()
|
|
230
231
|
return status
|
|
231
232
|
}
|
|
@@ -50,8 +50,7 @@ export class ComfyUploader {
|
|
|
50
50
|
if (p.override ?? true) form.set('override', 'true')
|
|
51
51
|
// const subfolder = p.subfolder ?? 'comfyts-upload'
|
|
52
52
|
if (p.subfolder) form.set('subfolder', p.subfolder)
|
|
53
|
-
const
|
|
54
|
-
const resp = await fetch(uploadURL, { method: 'POST', body: form })
|
|
53
|
+
const resp = await this.host.fetch('/upload/image', { method: 'POST', body: form })
|
|
55
54
|
const result: ComfyUploadImageResult = softValidate(ComfyUploadImageResult_ark, await resp.json())
|
|
56
55
|
|
|
57
56
|
// 4. check upload is successfull
|
|
@@ -33,6 +33,8 @@ export class ResilientWebSocketClient {
|
|
|
33
33
|
constructor(
|
|
34
34
|
public options: {
|
|
35
35
|
url: () => string /*protocols?: string | string[]*/
|
|
36
|
+
/** upgrade-request headers (auth: X-API-Key & co) — a thunk, re-read on every reconnect */
|
|
37
|
+
headers?: () => Record<string, string>
|
|
36
38
|
onMessage: (event: MessageEvent) => void
|
|
37
39
|
onConnectOrReconnect: () => void
|
|
38
40
|
onClose: () => void
|
|
@@ -66,7 +68,7 @@ export class ResilientWebSocketClient {
|
|
|
66
68
|
this.addInfo('Previous WebSocket discarded')
|
|
67
69
|
prevWS.close()
|
|
68
70
|
}
|
|
69
|
-
const ws = new WebSocket(this.url)
|
|
71
|
+
const ws = new WebSocket(this.url, { headers: this.options.headers?.() })
|
|
70
72
|
ws.binaryType = 'arraybuffer'
|
|
71
73
|
|
|
72
74
|
this.currentWS = ws
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/** pure url layer for ComfyHost: parse once, render everywhere. No comfyts global. */
|
|
2
|
+
|
|
3
|
+
export type ParsedHostBase = {
|
|
4
|
+
scheme: 'http' | 'https'
|
|
5
|
+
host: string
|
|
6
|
+
/** always concrete (defaults 80/443 from the scheme when the url omits it) */
|
|
7
|
+
port: number
|
|
8
|
+
/** '' or '/segment…' with no trailing slash */
|
|
9
|
+
basePath: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** exactly ONE of `url` or the legacy `host`+`port` (+`https?`) spelling */
|
|
13
|
+
export function parseHostBase(p: {
|
|
14
|
+
id: string
|
|
15
|
+
url?: string
|
|
16
|
+
host?: string
|
|
17
|
+
port?: number
|
|
18
|
+
https?: boolean
|
|
19
|
+
}): ParsedHostBase {
|
|
20
|
+
const hasLegacy = p.host != null || p.port != null || p.https != null
|
|
21
|
+
if (p.url != null && hasLegacy)
|
|
22
|
+
throw new Error(`host '${p.id}': give either url OR host/port/https, not both spellings at once`)
|
|
23
|
+
if (p.url == null) {
|
|
24
|
+
if (p.host == null || p.port == null)
|
|
25
|
+
throw new Error(`host '${p.id}': needs either url, or host AND port (got host=${p.host}, port=${p.port})`)
|
|
26
|
+
return { scheme: p.https ? 'https' : 'http', host: p.host, port: p.port, basePath: '' }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
let parsed: URL
|
|
30
|
+
try {
|
|
31
|
+
parsed = new URL(p.url)
|
|
32
|
+
} catch {
|
|
33
|
+
throw new Error(`host '${p.id}': unparseable url '${p.url}'`)
|
|
34
|
+
}
|
|
35
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
|
|
36
|
+
throw new Error(`host '${p.id}': url scheme must be http or https, got '${parsed.protocol}' in '${p.url}'`)
|
|
37
|
+
if (parsed.search !== '' || parsed.hash !== '')
|
|
38
|
+
throw new Error(`host '${p.id}': url must be a plain base (no ?query or #hash), got '${p.url}'`)
|
|
39
|
+
const scheme = parsed.protocol === 'https:' ? 'https' : 'http'
|
|
40
|
+
const port = parsed.port !== '' ? Number(parsed.port) : scheme === 'https' ? 443 : 80
|
|
41
|
+
const basePath = parsed.pathname.replace(/\/+$/, '')
|
|
42
|
+
return { scheme, host: parsed.hostname, port, basePath }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** http(s) base, port omitted when it is the scheme default */
|
|
46
|
+
export function renderHttpBase(p: ParsedHostBase): string {
|
|
47
|
+
return `${p.scheme}://${p.host}${renderPort(p)}${p.basePath}`
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** ws(s) endpoint; auth NEVER rides the query string (headers own it) */
|
|
51
|
+
export function renderWsUrl(p: ParsedHostBase): string {
|
|
52
|
+
const scheme = p.scheme === 'https' ? 'wss' : 'ws'
|
|
53
|
+
return `${scheme}://${p.host}${renderPort(p)}${p.basePath}/ws`
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function renderPort(p: ParsedHostBase): string {
|
|
57
|
+
const schemeDefault = p.scheme === 'https' ? 443 : 80
|
|
58
|
+
return p.port === schemeDefault ? '' : `:${p.port}`
|
|
59
|
+
}
|
|
@@ -33,15 +33,15 @@ export function loraPreviewKey(name: string): string {
|
|
|
33
33
|
* (server-relative). Returns null when the extension is absent (404/network).
|
|
34
34
|
*/
|
|
35
35
|
export async function fetchLoraPreviewMap(host: ComfyHost): Promise<Map<string, string> | null> {
|
|
36
|
-
const base = host.getServerHostHTTP()
|
|
37
36
|
const map = new Map<string, string>()
|
|
38
37
|
const pageSize = 500
|
|
39
38
|
for (let page = 1; page <= 20; page++) {
|
|
40
39
|
let res: Response
|
|
41
40
|
try {
|
|
42
|
-
|
|
41
|
+
// the extension registers under /api — already prefixed, skip the probe
|
|
42
|
+
res = await host.fetch(`/api/lm/loras/list?page=${page}&page_size=${pageSize}`, {}, { apiPrefix: false })
|
|
43
43
|
} catch {
|
|
44
|
-
return null // host unreachable: previews off, not an error
|
|
44
|
+
return null // host unreachable (or auth-refused): previews off, not an error
|
|
45
45
|
}
|
|
46
46
|
if (!res.ok) return page === 1 ? null : map // 404 on page 1 = extension absent
|
|
47
47
|
const json: unknown = await res.json()
|
|
@@ -83,7 +83,8 @@ export async function fetchLoraPreviewBytes(host: ComfyHost, previewUrl: string)
|
|
|
83
83
|
const cachePath = comfyts.resolveFromCache(`lora-previews/${createHash('sha1').update(previewUrl).digest('hex')}`)
|
|
84
84
|
if (existsSync(cachePath)) return new Uint8Array(readFileSync(cachePath))
|
|
85
85
|
try {
|
|
86
|
-
|
|
86
|
+
// preview_url is already a full server-relative path — no /api probing
|
|
87
|
+
const res = await host.fetch(previewUrl, {}, { apiPrefix: false })
|
|
87
88
|
if (!res.ok) return null
|
|
88
89
|
const ct = res.headers.get('content-type') ?? ''
|
|
89
90
|
if (ct !== '' && !ct.startsWith('image/')) return null // HTML fallback etc.
|
package/src/index.ts
CHANGED
|
@@ -10,7 +10,14 @@ export * from 'src/types/comfy-sdk.ts'
|
|
|
10
10
|
export { ComfyTS } from 'src/state.ts'
|
|
11
11
|
|
|
12
12
|
// host
|
|
13
|
-
export {
|
|
13
|
+
export {
|
|
14
|
+
ComfyHost,
|
|
15
|
+
ComfyHostAuthError,
|
|
16
|
+
type ComfyHostData,
|
|
17
|
+
type ComfyHostID,
|
|
18
|
+
type ConnectOptions,
|
|
19
|
+
} from 'src/host/ComfyHost.ts'
|
|
20
|
+
export { type ParsedHostBase, parseHostBase, renderHttpBase, renderWsUrl } from 'src/host/hostUrl.ts'
|
|
14
21
|
export { ComfyManager } from 'src/host/ComfyManager.ts'
|
|
15
22
|
export { ComfyUploader, type ComfyUploadImageResult } from 'src/host/ComfyUploader.ts'
|
|
16
23
|
export { ComfyWorkflowBuilder } from 'src/host/ComfyWorkflowBuilder.ts'
|
|
@@ -49,6 +56,18 @@ export type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api
|
|
|
49
56
|
// litegraph (ComfyUI saved-workflow JSON format)
|
|
50
57
|
export type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
|
|
51
58
|
export { convertFlowToLiteGraphJSON } from 'src/litegraph/convertFlowToLiteGraphJSON.ts'
|
|
59
|
+
export type {
|
|
60
|
+
CanonicalGroup,
|
|
61
|
+
CanonicalInput,
|
|
62
|
+
CanonicalLink,
|
|
63
|
+
CanonicalNode,
|
|
64
|
+
CanonicalOutput,
|
|
65
|
+
CanonicalWidgetValues,
|
|
66
|
+
CanonicalWorkflow,
|
|
67
|
+
NodeMode,
|
|
68
|
+
} from 'src/litegraph/CanonicalWorkflow.ts'
|
|
69
|
+
export { normalizeWorkflow, parseWorkflowJson, WorkflowNormalizeError } from 'src/litegraph/normalizeWorkflow.ts'
|
|
70
|
+
export { convertLiteGraphToPrompt, WorkflowConvertError } from 'src/sdk-generator/litegraphToApiRequestPayload.ts'
|
|
52
71
|
|
|
53
72
|
// vars + re-runnable workflows
|
|
54
73
|
export {
|