api.js 13.3 KB
Newer Older
pythongosssss's avatar
pythongosssss committed
1
class ComfyApi extends EventTarget {
2
3
	#registered = new Set();

pythongosssss's avatar
pythongosssss committed
4
	constructor() {
pythongosssss's avatar
pythongosssss committed
5
		super();
6
7
		this.api_host = location.host;
		this.api_base = location.pathname.split('/').slice(0, -1).join('/');
8
		this.initialClientId = sessionStorage.getItem("clientId");
9
10
11
12
13
14
15
	}

	apiURL(route) {
		return this.api_base + route;
	}

	fetchApi(route, options) {
16
17
18
19
20
21
22
		if (!options) {
			options = {};
		}
		if (!options.headers) {
			options.headers = {};
		}
		options.headers["Comfy-User"] = this.user;
23
		return fetch(this.apiURL(route), options);
pythongosssss's avatar
pythongosssss committed
24
25
	}

26
27
28
29
30
	addEventListener(type, callback, options) {
		super.addEventListener(type, callback, options);
		this.#registered.add(type);
	}

pythongosssss's avatar
pythongosssss committed
31
32
33
	/**
	 * Poll status  for colab and other things that don't support websockets.
	 */
pythongosssss's avatar
pythongosssss committed
34
35
36
	#pollQueue() {
		setInterval(async () => {
			try {
37
				const resp = await this.fetchApi("/prompt");
pythongosssss's avatar
pythongosssss committed
38
39
40
41
42
43
44
45
				const status = await resp.json();
				this.dispatchEvent(new CustomEvent("status", { detail: status }));
			} catch (error) {
				this.dispatchEvent(new CustomEvent("status", { detail: null }));
			}
		}, 1000);
	}

pythongosssss's avatar
pythongosssss committed
46
47
48
49
	/**
	 * Creates and connects a WebSocket for realtime updates
	 * @param {boolean} isReconnect If the socket is connection is a reconnect attempt
	 */
pythongosssss's avatar
pythongosssss committed
50
51
52
53
54
55
	#createSocket(isReconnect) {
		if (this.socket) {
			return;
		}

		let opened = false;
56
		let existingSession = window.name;
57
58
59
60
		if (existingSession) {
			existingSession = "?clientId=" + existingSession;
		}
		this.socket = new WebSocket(
61
			`ws${window.location.protocol === "https:" ? "s" : ""}://${this.api_host}${this.api_base}/ws${existingSession}`
62
		);
space-nuko's avatar
space-nuko committed
63
		this.socket.binaryType = "arraybuffer";
pythongosssss's avatar
pythongosssss committed
64
65
66
67
68
69
70
71
72
73

		this.socket.addEventListener("open", () => {
			opened = true;
			if (isReconnect) {
				this.dispatchEvent(new CustomEvent("reconnected"));
			}
		});

		this.socket.addEventListener("error", () => {
			if (this.socket) this.socket.close();
pythongosssss's avatar
pythongosssss committed
74
			if (!isReconnect && !opened) {
75
76
				this.#pollQueue();
			}
pythongosssss's avatar
pythongosssss committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
		});

		this.socket.addEventListener("close", () => {
			setTimeout(() => {
				this.socket = null;
				this.#createSocket(true);
			}, 300);
			if (opened) {
				this.dispatchEvent(new CustomEvent("status", { detail: null }));
				this.dispatchEvent(new CustomEvent("reconnecting"));
			}
		});

		this.socket.addEventListener("message", (event) => {
			try {
space-nuko's avatar
space-nuko committed
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
				if (event.data instanceof ArrayBuffer) {
					const view = new DataView(event.data);
					const eventType = view.getUint32(0);
					const buffer = event.data.slice(4);
					switch (eventType) {
					case 1:
						const view2 = new DataView(event.data);
						const imageType = view2.getUint32(0)
						let imageMime
						switch (imageType) {
							case 1:
							default:
								imageMime = "image/jpeg";
								break;
							case 2:
								imageMime = "image/png"
pythongosssss's avatar
pythongosssss committed
108
						}
space-nuko's avatar
Fix  
space-nuko committed
109
110
						const imageBlob = new Blob([buffer.slice(4)], { type: imageMime });
						this.dispatchEvent(new CustomEvent("b_preview", { detail: imageBlob }));
111
						break;
pythongosssss's avatar
pythongosssss committed
112
					default:
space-nuko's avatar
space-nuko committed
113
114
115
116
117
118
119
120
121
						throw new Error(`Unknown binary websocket message of type ${eventType}`);
					}
				}
				else {
				    const msg = JSON.parse(event.data);
				    switch (msg.type) {
					    case "status":
						    if (msg.data.sid) {
							    this.clientId = msg.data.sid;
122
123
							    window.name = this.clientId; // use window name so it isnt reused when duplicating tabs
								sessionStorage.setItem("clientId", this.clientId); // store in session storage so duplicate tab can load correct workflow
space-nuko's avatar
space-nuko committed
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
						    }
						    this.dispatchEvent(new CustomEvent("status", { detail: msg.data.status }));
						    break;
					    case "progress":
						    this.dispatchEvent(new CustomEvent("progress", { detail: msg.data }));
						    break;
					    case "executing":
						    this.dispatchEvent(new CustomEvent("executing", { detail: msg.data.node }));
						    break;
					    case "executed":
						    this.dispatchEvent(new CustomEvent("executed", { detail: msg.data }));
						    break;
					    case "execution_start":
						    this.dispatchEvent(new CustomEvent("execution_start", { detail: msg.data }));
						    break;
139
140
141
					    case "execution_success":
						    this.dispatchEvent(new CustomEvent("execution_success", { detail: msg.data }));
						    break;
space-nuko's avatar
space-nuko committed
142
143
144
					    case "execution_error":
						    this.dispatchEvent(new CustomEvent("execution_error", { detail: msg.data }));
						    break;
145
146
147
					    case "execution_cached":
						    this.dispatchEvent(new CustomEvent("execution_cached", { detail: msg.data }));
						    break;
space-nuko's avatar
space-nuko committed
148
149
150
151
152
153
154
					    default:
						    if (this.#registered.has(msg.type)) {
							    this.dispatchEvent(new CustomEvent(msg.type, { detail: msg.data }));
						    } else {
							    throw new Error(`Unknown message type ${msg.type}`);
						    }
				    }
pythongosssss's avatar
pythongosssss committed
155
156
				}
			} catch (error) {
space-nuko's avatar
space-nuko committed
157
				console.warn("Unhandled message:", event.data, error);
pythongosssss's avatar
pythongosssss committed
158
159
160
161
			}
		});
	}

pythongosssss's avatar
pythongosssss committed
162
163
164
	/**
	 * Initialises sockets and realtime updates
	 */
pythongosssss's avatar
pythongosssss committed
165
166
167
	init() {
		this.#createSocket();
	}
pythongosssss's avatar
pythongosssss committed
168

169
170
171
172
173
	/**
	 * Gets a list of extension urls
	 * @returns An array of script urls to import
	 */
	async getExtensions() {
174
		const resp = await this.fetchApi("/extensions", { cache: "no-store" });
175
176
177
		return await resp.json();
	}

178
179
180
181
182
	/**
	 * Gets a list of embedding names
	 * @returns An array of script urls to import
	 */
	async getEmbeddings() {
183
		const resp = await this.fetchApi("/embeddings", { cache: "no-store" });
184
185
186
		return await resp.json();
	}

pythongosssss's avatar
pythongosssss committed
187
188
189
190
	/**
	 * Loads node object definitions for the graph
	 * @returns The node definitions
	 */
pythongosssss's avatar
pythongosssss committed
191
	async getNodeDefs() {
192
		const resp = await this.fetchApi("/object_info", { cache: "no-store" });
pythongosssss's avatar
pythongosssss committed
193
194
195
		return await resp.json();
	}

pythongosssss's avatar
pythongosssss committed
196
197
198
199
200
	/**
	 *
	 * @param {number} number The index at which to queue the prompt, passing -1 will insert the prompt at the front of the queue
	 * @param {object} prompt The prompt data to queue
	 */
pythongosssss's avatar
pythongosssss committed
201
202
203
204
205
206
207
208
209
210
211
212
213
	async queuePrompt(number, { output, workflow }) {
		const body = {
			client_id: this.clientId,
			prompt: output,
			extra_data: { extra_pnginfo: { workflow } },
		};

		if (number === -1) {
			body.front = true;
		} else if (number != 0) {
			body.number = number;
		}

214
		const res = await this.fetchApi("/prompt", {
pythongosssss's avatar
pythongosssss committed
215
216
217
218
219
220
221
222
223
			method: "POST",
			headers: {
				"Content-Type": "application/json",
			},
			body: JSON.stringify(body),
		});

		if (res.status !== 200) {
			throw {
224
				response: await res.json(),
pythongosssss's avatar
pythongosssss committed
225
226
			};
		}
227
228

		return await res.json();
pythongosssss's avatar
pythongosssss committed
229
	}
pythongosssss's avatar
pythongosssss committed
230

pythongosssss's avatar
pythongosssss committed
231
232
233
234
235
	/**
	 * Loads a list of items (queue or history)
	 * @param {string} type The type of items to load, queue or history
	 * @returns The items of the specified type grouped by their status
	 */
pythongosssss's avatar
pythongosssss committed
236
237
238
239
240
241
242
	async getItems(type) {
		if (type === "queue") {
			return this.getQueue();
		}
		return this.getHistory();
	}

pythongosssss's avatar
pythongosssss committed
243
244
245
246
	/**
	 * Gets the current state of the queue
	 * @returns The currently running and queued items
	 */
pythongosssss's avatar
pythongosssss committed
247
248
	async getQueue() {
		try {
249
			const res = await this.fetchApi("/queue");
pythongosssss's avatar
pythongosssss committed
250
251
252
			const data = await res.json();
			return {
				// Running action uses a different endpoint for cancelling
pythongosssss's avatar
pythongosssss committed
253
254
255
256
				Running: data.queue_running.map((prompt) => ({
					prompt,
					remove: { name: "Cancel", cb: () => api.interrupt() },
				})),
pythongosssss's avatar
pythongosssss committed
257
258
259
260
261
262
263
264
				Pending: data.queue_pending.map((prompt) => ({ prompt })),
			};
		} catch (error) {
			console.error(error);
			return { Running: [], Pending: [] };
		}
	}

pythongosssss's avatar
pythongosssss committed
265
266
267
268
	/**
	 * Gets the prompt execution history
	 * @returns Prompt history including node outputs
	 */
269
	async getHistory(max_items=200) {
pythongosssss's avatar
pythongosssss committed
270
		try {
271
			const res = await this.fetchApi(`/history?max_items=${max_items}`);
pythongosssss's avatar
pythongosssss committed
272
273
274
275
276
277
278
			return { History: Object.values(await res.json()) };
		} catch (error) {
			console.error(error);
			return { History: [] };
		}
	}

pythongosssss's avatar
pythongosssss committed
279
280
281
282
283
284
285
286
287
	/**
	 * Gets system & device stats
	 * @returns System stats such as python version, OS, per device info
	 */
	async getSystemStats() {
		const res = await this.fetchApi("/system_stats");
		return await res.json();
	}

pythongosssss's avatar
pythongosssss committed
288
289
290
291
292
	/**
	 * Sends a POST request to the API
	 * @param {*} type The endpoint to post to
	 * @param {*} body Optional POST data
	 */
pythongosssss's avatar
pythongosssss committed
293
294
	async #postItem(type, body) {
		try {
295
			await this.fetchApi("/" + type, {
pythongosssss's avatar
pythongosssss committed
296
297
298
299
300
301
302
303
304
305
306
				method: "POST",
				headers: {
					"Content-Type": "application/json",
				},
				body: body ? JSON.stringify(body) : undefined,
			});
		} catch (error) {
			console.error(error);
		}
	}

pythongosssss's avatar
pythongosssss committed
307
308
309
310
311
	/**
	 * Deletes an item from the specified list
	 * @param {string} type The type of item to delete, queue or history
	 * @param {number} id The id of the item to delete
	 */
pythongosssss's avatar
pythongosssss committed
312
313
314
315
	async deleteItem(type, id) {
		await this.#postItem(type, { delete: [id] });
	}

pythongosssss's avatar
pythongosssss committed
316
317
318
319
	/**
	 * Clears the specified list
	 * @param {string} type The type of list to clear, queue or history
	 */
pythongosssss's avatar
pythongosssss committed
320
321
322
323
	async clearItems(type) {
		await this.#postItem(type, { clear: true });
	}

pythongosssss's avatar
pythongosssss committed
324
325
326
	/**
	 * Interrupts the execution of the running prompt
	 */
pythongosssss's avatar
pythongosssss committed
327
328
329
	async interrupt() {
		await this.#postItem("interrupt", null);
	}
330
331
332

	/**
	 * Gets user configuration data and where data should be stored
333
	 * @returns { Promise<{ storage: "server" | "browser", users?: Promise<string, unknown>, migrated?: boolean }> }
334
335
336
337
338
339
340
	 */
	async getUserConfig() {
		return (await this.fetchApi("/users")).json();
	}

	/**
	 * Creates a new user
341
	 * @param { string } username
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
	 * @returns The fetch response
	 */
	createUser(username) {
		return this.fetchApi("/users", {
			method: "POST",
			headers: {
				"Content-Type": "application/json",
			},
			body: JSON.stringify({ username }),
		});
	}

	/**
	 * Gets all setting values for the current user
	 * @returns { Promise<string, unknown> } A dictionary of id -> value
	 */
	async getSettings() {
		return (await this.fetchApi("/settings")).json();
	}

	/**
	 * Gets a setting for the current user
	 * @param { string } id The id of the setting to fetch
	 * @returns { Promise<unknown> } The setting value
	 */
	async getSetting(id) {
		return (await this.fetchApi(`/settings/${encodeURIComponent(id)}`)).json();
	}

	/**
	 * Stores a dictionary of settings for the current user
	 * @param { Record<string, unknown> } settings Dictionary of setting id -> value to save
	 * @returns { Promise<void> }
	 */
	async storeSettings(settings) {
		return this.fetchApi(`/settings`, {
			method: "POST",
			body: JSON.stringify(settings)
		});
	}

	/**
	 * Stores a setting for the current user
	 * @param { string } id The id of the setting to update
	 * @param { unknown } value The value of the setting
	 * @returns { Promise<void> }
	 */
	async storeSetting(id, value) {
		return this.fetchApi(`/settings/${encodeURIComponent(id)}`, {
			method: "POST",
			body: JSON.stringify(value)
		});
	}

	/**
	 * Gets a user data file for the current user
	 * @param { string } file The name of the userdata file to load
	 * @param { RequestInit } [options]
400
	 * @returns { Promise<Response> } The fetch response object
401
402
403
404
405
406
407
408
409
	 */
	async getUserData(file, options) {
		return this.fetchApi(`/userdata/${encodeURIComponent(file)}`, options);
	}

	/**
	 * Stores a user data file for the current user
	 * @param { string } file The name of the userdata file to save
	 * @param { unknown } data The data to save to the file
410
411
	 * @param { RequestInit & { overwrite?: boolean, stringify?: boolean, throwOnError?: boolean } } [options]
	 * @returns { Promise<Response> }
412
	 */
413
414
	async storeUserData(file, data, options = { overwrite: true, stringify: true, throwOnError: true }) {
		const resp = await this.fetchApi(`/userdata/${encodeURIComponent(file)}?overwrite=${options?.overwrite}`, {
415
416
417
			method: "POST",
			body: options?.stringify ? JSON.stringify(data) : data,
			...options,
418
419
		});
		if (resp.status !== 200 && options?.throwOnError !== false) {
420
421
			throw new Error(`Error storing user data file '${file}': ${resp.status} ${(await resp).statusText}`);
		}
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
		return resp;
	}

	/**
	 * Deletes a user data file for the current user
	 * @param { string } file The name of the userdata file to delete
	 */
	async deleteUserData(file) {
		const resp = await this.fetchApi(`/userdata/${encodeURIComponent(file)}`, {
			method: "DELETE",
		});
		if (resp.status !== 204) {
			throw new Error(`Error removing user data file '${file}': ${resp.status} ${(resp).statusText}`);
		}
	}

	/**
	 * Move a user data file for the current user
	 * @param { string } source The userdata file to move
	 * @param { string } dest The destination for the file
	 */
	async moveUserData(source, dest, options = { overwrite: false }) {
		const resp = await this.fetchApi(`/userdata/${encodeURIComponent(source)}/move/${encodeURIComponent(dest)}?overwrite=${options?.overwrite}`, {
			method: "POST",
		});
		return resp;
	}

	/**
	 * @overload
	 * Lists user data files for the current user
	 * @param { string } dir The directory in which to list files
	 * @param { boolean } [recurse] If the listing should be recursive
	 * @param { true } [split] If the paths should be split based on the os path separator
	 * @returns { Promise<string[][]>> } The list of split file paths in the format [fullPath, ...splitPath]
	 */
	/**
	 * @overload
	 * Lists user data files for the current user
	 * @param { string } dir The directory in which to list files
	 * @param { boolean } [recurse] If the listing should be recursive
	 * @param { false | undefined } [split] If the paths should be split based on the os path separator
	 * @returns { Promise<string[]>> } The list of files
	 */
	async listUserData(dir, recurse, split) {
		const resp = await this.fetchApi(
			`/userdata?${new URLSearchParams({
				recurse,
				dir,
				split,
			})}`
		);
		if (resp.status === 404) return [];
		if (resp.status !== 200) {
			throw new Error(`Error getting user data list '${dir}': ${resp.status} ${resp.statusText}`);
		}
		return resp.json();
479
	}
pythongosssss's avatar
pythongosssss committed
480
481
482
}

export const api = new ComfyApi();