@zmskco/dsh-notebook 0.1.0 → 0.2.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/LICENSE +23 -23
- package/README.md +238 -96
- package/assets/material-icons/LICENSE.txt +8 -0
- package/assets/material-icons/NOTICE.md +13 -0
- package/cordis.patch.yml +4 -2
- package/icon.png +0 -0
- package/lib/client.js +5359 -245
- package/lib/http/api.js +64 -13
- package/lib/index.js +19 -8
- package/lib/story/bootstrap.js +4 -9
- package/lib/story/project.js +175 -5
- package/lib/story/readme.js +9 -9
- package/lib/story/root.js +12 -9
- package/lib/story/sandbox.js +33 -106
- package/lib/story/workspace.js +1 -15
- package/locale/en.json +6 -6
- package/locale/zh.json +6 -6
- package/package.json +93 -89
- package/icon.svg +0 -9
- package/lib/config.js +0 -43
- package/lib/http/media.js +0 -187
- package/lib/render/backend.js +0 -247
- package/lib/render/jobs.js +0 -267
- package/lib/render/png.js +0 -125
- package/lib/tools.js +0 -341
package/lib/http/media.js
DELETED
|
@@ -1,187 +0,0 @@
|
|
|
1
|
-
import { NotebookError, asNotebookError } from '../errors.js';
|
|
2
|
-
import { assertRelativePath, assertStoryName } from '../story/paths.js';
|
|
3
|
-
import { statusFor } from './status.js';
|
|
4
|
-
/** Mount point of this plugin's media route. */
|
|
5
|
-
export const MEDIA_PREFIX = '/notebook/media';
|
|
6
|
-
/** Byte ranges above this size are streamed in chunks instead of buffered. */
|
|
7
|
-
const STREAM_THRESHOLD = 4 * 1024 * 1024;
|
|
8
|
-
const CHUNK_SIZE = 1024 * 1024;
|
|
9
|
-
/** Hard cap for one un-ranged response; larger files must be ranged. */
|
|
10
|
-
const MAX_BUFFERED = 64 * 1024 * 1024;
|
|
11
|
-
const CONTENT_TYPES = {
|
|
12
|
-
'.png': 'image/png',
|
|
13
|
-
'.jpg': 'image/jpeg',
|
|
14
|
-
'.jpeg': 'image/jpeg',
|
|
15
|
-
'.webp': 'image/webp',
|
|
16
|
-
'.gif': 'image/gif',
|
|
17
|
-
'.mp4': 'video/mp4',
|
|
18
|
-
'.webm': 'video/webm',
|
|
19
|
-
'.json': 'application/json; charset=utf-8',
|
|
20
|
-
'.md': 'text/markdown; charset=utf-8',
|
|
21
|
-
'.txt': 'text/plain; charset=utf-8',
|
|
22
|
-
};
|
|
23
|
-
function contentTypeFor(path) {
|
|
24
|
-
const dot = path.lastIndexOf('.');
|
|
25
|
-
const extension = dot < 0 ? '' : path.slice(dot).toLowerCase();
|
|
26
|
-
return CONTENT_TYPES[extension] ?? 'application/octet-stream';
|
|
27
|
-
}
|
|
28
|
-
function sendJson(res, status, body) {
|
|
29
|
-
const text = JSON.stringify(body);
|
|
30
|
-
res.statusCode = status;
|
|
31
|
-
res.setHeader('content-type', 'application/json; charset=utf-8');
|
|
32
|
-
res.setHeader('content-length', Buffer.byteLength(text));
|
|
33
|
-
res.end(text);
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Parse a single-range `Range` header.
|
|
37
|
-
* @param header - the raw header value.
|
|
38
|
-
* @param size - the resource size.
|
|
39
|
-
* @returns the range, or `null` when the header is unsatisfiable.
|
|
40
|
-
*/
|
|
41
|
-
function parseRange(header, size) {
|
|
42
|
-
const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
|
|
43
|
-
if (match === null)
|
|
44
|
-
return null;
|
|
45
|
-
const rawStart = match[1] ?? '';
|
|
46
|
-
const rawEnd = match[2] ?? '';
|
|
47
|
-
if (rawStart.length === 0 && rawEnd.length === 0)
|
|
48
|
-
return null;
|
|
49
|
-
if (rawStart.length === 0) {
|
|
50
|
-
// Suffix form: the last N bytes.
|
|
51
|
-
const length = Number(rawEnd);
|
|
52
|
-
if (!Number.isFinite(length) || length <= 0 || size === 0)
|
|
53
|
-
return null;
|
|
54
|
-
return { start: Math.max(0, size - length), end: size - 1 };
|
|
55
|
-
}
|
|
56
|
-
const start = Number(rawStart);
|
|
57
|
-
if (!Number.isFinite(start) || start >= size)
|
|
58
|
-
return null;
|
|
59
|
-
const end = rawEnd.length === 0 ? size - 1 : Math.min(Number(rawEnd), size - 1);
|
|
60
|
-
if (!Number.isFinite(end) || end < start)
|
|
61
|
-
return null;
|
|
62
|
-
return { start, end };
|
|
63
|
-
}
|
|
64
|
-
/** Write one buffer, waiting for drain when the socket is saturated. */
|
|
65
|
-
async function writeChunk(res, chunk) {
|
|
66
|
-
if (res.write(chunk))
|
|
67
|
-
return;
|
|
68
|
-
await new Promise((resolve, reject) => {
|
|
69
|
-
const cleanup = () => {
|
|
70
|
-
res.off('drain', onDrain);
|
|
71
|
-
res.off('close', onClose);
|
|
72
|
-
};
|
|
73
|
-
function onDrain() { cleanup(); resolve(); }
|
|
74
|
-
function onClose() { cleanup(); reject(new NotebookError('internal', 'client closed the connection')); }
|
|
75
|
-
res.on('drain', onDrain);
|
|
76
|
-
res.on('close', onClose);
|
|
77
|
-
});
|
|
78
|
-
}
|
|
79
|
-
/**
|
|
80
|
-
* Register the media route on the HTTP carrier.
|
|
81
|
-
* @param deps - carrier, filesystem, trust fence, store and logger.
|
|
82
|
-
* @returns the route disposer.
|
|
83
|
-
*/
|
|
84
|
-
export function registerMediaRoute(deps) {
|
|
85
|
-
const { webServer, fs, connection, roots, log } = deps;
|
|
86
|
-
const handle = async (req, res) => {
|
|
87
|
-
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
88
|
-
res.setHeader('allow', 'GET, HEAD');
|
|
89
|
-
res.statusCode = 405;
|
|
90
|
-
res.end();
|
|
91
|
-
return;
|
|
92
|
-
}
|
|
93
|
-
const url = new URL(String(req.url), 'http://localhost');
|
|
94
|
-
const pathname = url.pathname;
|
|
95
|
-
const rest = decodeURIComponent(pathname.slice(MEDIA_PREFIX.length).replace(/^\//, ''));
|
|
96
|
-
const segments = rest.split('/');
|
|
97
|
-
const rawProject = segments[0];
|
|
98
|
-
const rawFile = segments.slice(1);
|
|
99
|
-
if (rawProject === undefined || rawFile.length === 0) {
|
|
100
|
-
sendJson(res, 400, { code: 'bad-request', message: `expected ${MEDIA_PREFIX}/<project>/<path>` });
|
|
101
|
-
return;
|
|
102
|
-
}
|
|
103
|
-
const projectId = assertStoryName(rawProject);
|
|
104
|
-
const rel = assertRelativePath(rawFile.join('/'));
|
|
105
|
-
// The image URL carries the Session whose workspace holds this project, for
|
|
106
|
-
// the same reason every other route does: the story root is per workspace.
|
|
107
|
-
const { store } = roots(url.searchParams.get('session') ?? undefined);
|
|
108
|
-
const project = await store.open(projectId);
|
|
109
|
-
const target = await store.resolveInside(project, rel);
|
|
110
|
-
const info = await fs.stat(target);
|
|
111
|
-
if (info === undefined || info.type !== 'file') {
|
|
112
|
-
sendJson(res, 404, { code: 'not-found', message: `${rel} does not exist in project ${projectId}` });
|
|
113
|
-
return;
|
|
114
|
-
}
|
|
115
|
-
const size = info.size ?? 0;
|
|
116
|
-
res.setHeader('content-type', contentTypeFor(rel));
|
|
117
|
-
res.setHeader('accept-ranges', 'bytes');
|
|
118
|
-
res.setHeader('cache-control', 'no-cache');
|
|
119
|
-
res.setHeader('etag', `"${info.version}"`);
|
|
120
|
-
if (req.headers['if-none-match'] === `"${info.version}"`) {
|
|
121
|
-
res.statusCode = 304;
|
|
122
|
-
res.end();
|
|
123
|
-
return;
|
|
124
|
-
}
|
|
125
|
-
const rangeHeader = req.headers.range;
|
|
126
|
-
const hasRange = typeof rangeHeader === 'string' && rangeHeader.length > 0;
|
|
127
|
-
const range = hasRange ? parseRange(rangeHeader, size) : null;
|
|
128
|
-
if (hasRange && range === null) {
|
|
129
|
-
res.statusCode = 416;
|
|
130
|
-
res.setHeader('content-range', `bytes */${String(size)}`);
|
|
131
|
-
res.end();
|
|
132
|
-
return;
|
|
133
|
-
}
|
|
134
|
-
const start = range?.start ?? 0;
|
|
135
|
-
const end = range?.end ?? size - 1;
|
|
136
|
-
const length = Math.max(0, end - start + 1);
|
|
137
|
-
if (range !== null) {
|
|
138
|
-
res.statusCode = 206;
|
|
139
|
-
res.setHeader('content-range', `bytes ${String(start)}-${String(end)}/${String(size)}`);
|
|
140
|
-
}
|
|
141
|
-
else if (length > MAX_BUFFERED) {
|
|
142
|
-
// Refuse rather than exhaust memory; a well-behaved client ranges.
|
|
143
|
-
sendJson(res, 413, { code: 'bad-request', message: `${rel} is ${String(size)} bytes; request a byte range` });
|
|
144
|
-
return;
|
|
145
|
-
}
|
|
146
|
-
else {
|
|
147
|
-
res.statusCode = 200;
|
|
148
|
-
}
|
|
149
|
-
res.setHeader('content-length', String(length));
|
|
150
|
-
if (req.method === 'HEAD' || length === 0) {
|
|
151
|
-
res.end();
|
|
152
|
-
return;
|
|
153
|
-
}
|
|
154
|
-
if (length <= STREAM_THRESHOLD) {
|
|
155
|
-
res.end(Buffer.from(await fs.readByteRange(target, { offset: start, length })));
|
|
156
|
-
return;
|
|
157
|
-
}
|
|
158
|
-
for (let offset = start; offset <= end; offset += CHUNK_SIZE) {
|
|
159
|
-
const take = Math.min(CHUNK_SIZE, end - offset + 1);
|
|
160
|
-
await writeChunk(res, await fs.readByteRange(target, { offset, length: take }));
|
|
161
|
-
}
|
|
162
|
-
res.end();
|
|
163
|
-
};
|
|
164
|
-
return webServer.register({
|
|
165
|
-
kind: 'prefix',
|
|
166
|
-
path: MEDIA_PREFIX,
|
|
167
|
-
handler: (req, res) => {
|
|
168
|
-
const rejection = connection.requestRejection({ headers: req.headers });
|
|
169
|
-
if (rejection !== undefined) {
|
|
170
|
-
res.statusCode = rejection;
|
|
171
|
-
res.end();
|
|
172
|
-
return;
|
|
173
|
-
}
|
|
174
|
-
void handle(req, res).catch((error) => {
|
|
175
|
-
const failure = asNotebookError(error);
|
|
176
|
-
log.warn('notebook: media request failed', failure);
|
|
177
|
-
if (res.headersSent)
|
|
178
|
-
res.end();
|
|
179
|
-
else
|
|
180
|
-
sendJson(res, statusFor(failure.code), {
|
|
181
|
-
code: failure.code,
|
|
182
|
-
message: failure.message,
|
|
183
|
-
});
|
|
184
|
-
});
|
|
185
|
-
},
|
|
186
|
-
});
|
|
187
|
-
}
|
package/lib/render/backend.js
DELETED
|
@@ -1,247 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The image backend seam.
|
|
3
|
-
*
|
|
4
|
-
* Novel-to-comic needs pixels, but where they come from is a deployment
|
|
5
|
-
* decision — and during plugin development there is usually no image stack on
|
|
6
|
-
* the machine at all. So the renderer talks to this interface, and the profile
|
|
7
|
-
* picks an implementation: `stub` (deterministic placeholders, no service
|
|
8
|
-
* required) or `comfy` (a ComfyUI HTTP API). Everything above the seam —
|
|
9
|
-
* prompt assembly, jobs, progress, panel files, the media route, previews — is
|
|
10
|
-
* identical for both, which is what makes the stub a real test rather than a
|
|
11
|
-
* mock.
|
|
12
|
-
*
|
|
13
|
-
* ComfyUI is addressed over HTTP with a configurable base URL, so it may be a
|
|
14
|
-
* process on this machine or one on the LAN; the code path is the same and the
|
|
15
|
-
* failure modes are surfaced as text rather than assumed away.
|
|
16
|
-
*/
|
|
17
|
-
import { readFile } from 'node:fs/promises';
|
|
18
|
-
import { NotebookError, asNotebookError } from '../errors.js';
|
|
19
|
-
import { encodePlaceholderPng } from './png.js';
|
|
20
|
-
const COMFY_CLIENT_ID = 'dsh-notebook';
|
|
21
|
-
function delay(ms, signal) {
|
|
22
|
-
return new Promise((resolve, reject) => {
|
|
23
|
-
if (signal.aborted) {
|
|
24
|
-
reject(new NotebookError('internal', 'cancelled'));
|
|
25
|
-
return;
|
|
26
|
-
}
|
|
27
|
-
const timer = setTimeout(() => {
|
|
28
|
-
signal.removeEventListener('abort', onAbort);
|
|
29
|
-
resolve();
|
|
30
|
-
}, ms);
|
|
31
|
-
const onAbort = () => {
|
|
32
|
-
clearTimeout(timer);
|
|
33
|
-
reject(new NotebookError('internal', 'cancelled'));
|
|
34
|
-
};
|
|
35
|
-
signal.addEventListener('abort', onAbort, { once: true });
|
|
36
|
-
});
|
|
37
|
-
}
|
|
38
|
-
/** The development backend: real PNG bytes, no image service. */
|
|
39
|
-
export class StubBackend {
|
|
40
|
-
id = 'stub';
|
|
41
|
-
label = 'Placeholder renderer';
|
|
42
|
-
async probe() {
|
|
43
|
-
return {
|
|
44
|
-
ready: true,
|
|
45
|
-
detail: 'Renders deterministic placeholder panels. Configure imageBackend "comfy" to use a real model.',
|
|
46
|
-
};
|
|
47
|
-
}
|
|
48
|
-
async generate(request, signal) {
|
|
49
|
-
// A short pause and an abort check keep the job pipeline honest: progress,
|
|
50
|
-
// cancellation and partial-batch behaviour are exercised, not skipped.
|
|
51
|
-
await delay(120, signal);
|
|
52
|
-
return encodePlaceholderPng(request.prompt, request.seed, request.width, request.height);
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
/**
|
|
56
|
-
* Write one `"<nodeId>.<inputName>"` mapping into a workflow graph.
|
|
57
|
-
* @returns `true` when the node and input both existed.
|
|
58
|
-
*/
|
|
59
|
-
function applyNodeInput(graph, mapping, value) {
|
|
60
|
-
if (mapping === undefined)
|
|
61
|
-
return false;
|
|
62
|
-
const separator = mapping.lastIndexOf('.');
|
|
63
|
-
if (separator <= 0)
|
|
64
|
-
return false;
|
|
65
|
-
const node = graph[mapping.slice(0, separator)];
|
|
66
|
-
if (node === undefined)
|
|
67
|
-
return false;
|
|
68
|
-
const inputs = node.inputs ?? (node.inputs = {});
|
|
69
|
-
inputs[mapping.slice(separator + 1)] = value;
|
|
70
|
-
return true;
|
|
71
|
-
}
|
|
72
|
-
/** Extract the first produced image descriptor from a `/history` entry. */
|
|
73
|
-
function firstImage(outputs) {
|
|
74
|
-
if (typeof outputs !== 'object' || outputs === null)
|
|
75
|
-
return undefined;
|
|
76
|
-
for (const node of Object.values(outputs)) {
|
|
77
|
-
const images = node.images;
|
|
78
|
-
if (!Array.isArray(images))
|
|
79
|
-
continue;
|
|
80
|
-
for (const image of images) {
|
|
81
|
-
const candidate = image;
|
|
82
|
-
if (typeof candidate.filename !== 'string')
|
|
83
|
-
continue;
|
|
84
|
-
return {
|
|
85
|
-
filename: candidate.filename,
|
|
86
|
-
subfolder: typeof candidate.subfolder === 'string' ? candidate.subfolder : '',
|
|
87
|
-
type: typeof candidate.type === 'string' ? candidate.type : 'output',
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
return undefined;
|
|
92
|
-
}
|
|
93
|
-
/** The ComfyUI HTTP backend. */
|
|
94
|
-
export class ComfyUiBackend {
|
|
95
|
-
baseUrl;
|
|
96
|
-
workflowPath;
|
|
97
|
-
nodes;
|
|
98
|
-
timeoutMs;
|
|
99
|
-
log;
|
|
100
|
-
id = 'comfy';
|
|
101
|
-
label = 'ComfyUI';
|
|
102
|
-
constructor(baseUrl, workflowPath, nodes, timeoutMs, log) {
|
|
103
|
-
this.baseUrl = baseUrl;
|
|
104
|
-
this.workflowPath = workflowPath;
|
|
105
|
-
this.nodes = nodes;
|
|
106
|
-
this.timeoutMs = timeoutMs;
|
|
107
|
-
this.log = log;
|
|
108
|
-
}
|
|
109
|
-
async fetchWithTimeout(path, init, signal) {
|
|
110
|
-
const timeout = AbortSignal.timeout(this.timeoutMs);
|
|
111
|
-
const combined = AbortSignal.any([signal, timeout]);
|
|
112
|
-
try {
|
|
113
|
-
return await fetch(`${this.baseUrl}${path}`, { ...init, signal: combined });
|
|
114
|
-
}
|
|
115
|
-
catch (error) {
|
|
116
|
-
if (signal.aborted)
|
|
117
|
-
throw new NotebookError('internal', 'cancelled');
|
|
118
|
-
if (timeout.aborted) {
|
|
119
|
-
throw new NotebookError('backend-unavailable', `${this.baseUrl}${path} timed out after ${String(this.timeoutMs)} ms`);
|
|
120
|
-
}
|
|
121
|
-
throw new NotebookError('backend-unavailable', `cannot reach ComfyUI at ${this.baseUrl}${path}: ${asNotebookError(error).message}`);
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
async probe(signal) {
|
|
125
|
-
if (this.workflowPath === null) {
|
|
126
|
-
return { ready: false, detail: 'comfyWorkflow is unset; export a workflow with "Save (API Format)" and point the config at it.' };
|
|
127
|
-
}
|
|
128
|
-
if (this.nodes.prompt === undefined) {
|
|
129
|
-
return { ready: false, detail: 'comfyNodes.prompt is unset; map it to the positive-prompt input, for example "6.text".' };
|
|
130
|
-
}
|
|
131
|
-
try {
|
|
132
|
-
const response = await this.fetchWithTimeout('/system_stats', { method: 'GET' }, signal);
|
|
133
|
-
if (!response.ok) {
|
|
134
|
-
return { ready: false, detail: `ComfyUI answered ${String(response.status)} for /system_stats` };
|
|
135
|
-
}
|
|
136
|
-
return { ready: true, detail: `ComfyUI reachable at ${this.baseUrl}; workflow ${this.workflowPath}` };
|
|
137
|
-
}
|
|
138
|
-
catch (error) {
|
|
139
|
-
return { ready: false, detail: asNotebookError(error).message };
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
async loadGraph() {
|
|
143
|
-
if (this.workflowPath === null) {
|
|
144
|
-
throw new NotebookError('bad-request', 'comfyWorkflow is unset');
|
|
145
|
-
}
|
|
146
|
-
let text;
|
|
147
|
-
try {
|
|
148
|
-
text = await readFile(this.workflowPath, 'utf8');
|
|
149
|
-
}
|
|
150
|
-
catch (error) {
|
|
151
|
-
throw new NotebookError('bad-request', `cannot read the ComfyUI workflow at ${this.workflowPath}: ${asNotebookError(error).message}`);
|
|
152
|
-
}
|
|
153
|
-
let parsed;
|
|
154
|
-
try {
|
|
155
|
-
parsed = JSON.parse(text);
|
|
156
|
-
}
|
|
157
|
-
catch (error) {
|
|
158
|
-
throw new NotebookError('bad-request', `${this.workflowPath} is not valid JSON: ${asNotebookError(error).message}`);
|
|
159
|
-
}
|
|
160
|
-
// "Save (API Format)" emits either the bare map or a wrapper carrying it.
|
|
161
|
-
const graph = parsed.prompt ?? parsed;
|
|
162
|
-
if (typeof graph !== 'object' || graph === null || Array.isArray(graph)) {
|
|
163
|
-
throw new NotebookError('bad-request', `${this.workflowPath} is not a ComfyUI API-format graph (expected an object of nodes)`);
|
|
164
|
-
}
|
|
165
|
-
return structuredClone(graph);
|
|
166
|
-
}
|
|
167
|
-
async generate(request, signal) {
|
|
168
|
-
const graph = await this.loadGraph();
|
|
169
|
-
const missing = [];
|
|
170
|
-
const set = (mapping, value, name) => {
|
|
171
|
-
if (!applyNodeInput(graph, mapping, value))
|
|
172
|
-
missing.push(name);
|
|
173
|
-
};
|
|
174
|
-
set(this.nodes.prompt, request.prompt, 'prompt');
|
|
175
|
-
if (request.negativePrompt !== undefined)
|
|
176
|
-
set(this.nodes.negativePrompt, request.negativePrompt, 'negativePrompt');
|
|
177
|
-
set(this.nodes.seed, request.seed, 'seed');
|
|
178
|
-
set(this.nodes.width, request.width, 'width');
|
|
179
|
-
set(this.nodes.height, request.height, 'height');
|
|
180
|
-
if (request.checkpoint !== undefined)
|
|
181
|
-
set(this.nodes.checkpoint, request.checkpoint, 'checkpoint');
|
|
182
|
-
if (missing.length > 0) {
|
|
183
|
-
throw new NotebookError('bad-request', `the workflow has no node matching ${missing.join(', ')}; check comfyNodes against the exported graph`);
|
|
184
|
-
}
|
|
185
|
-
const submitted = await this.fetchWithTimeout('/prompt', {
|
|
186
|
-
method: 'POST',
|
|
187
|
-
headers: { 'content-type': 'application/json' },
|
|
188
|
-
body: JSON.stringify({ prompt: graph, client_id: COMFY_CLIENT_ID }),
|
|
189
|
-
}, signal);
|
|
190
|
-
if (!submitted.ok) {
|
|
191
|
-
const detail = await submitted.text().catch(() => '');
|
|
192
|
-
throw new NotebookError('backend-failed', `ComfyUI rejected the prompt (${String(submitted.status)}): ${detail.slice(0, 500)}`);
|
|
193
|
-
}
|
|
194
|
-
const queued = await submitted.json();
|
|
195
|
-
if (typeof queued.prompt_id !== 'string') {
|
|
196
|
-
throw new NotebookError('backend-failed', 'ComfyUI accepted the request but returned no prompt_id');
|
|
197
|
-
}
|
|
198
|
-
const promptId = queued.prompt_id;
|
|
199
|
-
const deadline = Date.now() + this.timeoutMs;
|
|
200
|
-
for (;;) {
|
|
201
|
-
if (signal.aborted)
|
|
202
|
-
throw new NotebookError('internal', 'cancelled');
|
|
203
|
-
if (Date.now() > deadline) {
|
|
204
|
-
throw new NotebookError('backend-unavailable', `ComfyUI did not finish ${promptId} within ${String(this.timeoutMs)} ms`);
|
|
205
|
-
}
|
|
206
|
-
await delay(700, signal);
|
|
207
|
-
const historyResponse = await this.fetchWithTimeout(`/history/${encodeURIComponent(promptId)}`, { method: 'GET' }, signal);
|
|
208
|
-
if (!historyResponse.ok)
|
|
209
|
-
continue;
|
|
210
|
-
const history = await historyResponse.json();
|
|
211
|
-
const record = history[promptId];
|
|
212
|
-
if (record === undefined)
|
|
213
|
-
continue;
|
|
214
|
-
const status = record.status?.status_str;
|
|
215
|
-
if (status === 'error') {
|
|
216
|
-
const messages = JSON.stringify(record.status?.messages ?? []).slice(0, 500);
|
|
217
|
-
throw new NotebookError('backend-failed', `ComfyUI reported an error for ${promptId}: ${messages}`);
|
|
218
|
-
}
|
|
219
|
-
const image = firstImage(record.outputs);
|
|
220
|
-
if (image === undefined) {
|
|
221
|
-
// Completed without an image node output: nothing to fetch.
|
|
222
|
-
if (status === 'success') {
|
|
223
|
-
throw new NotebookError('backend-failed', `ComfyUI finished ${promptId} without producing an image; check the workflow's output node`);
|
|
224
|
-
}
|
|
225
|
-
continue;
|
|
226
|
-
}
|
|
227
|
-
const query = new URLSearchParams({ filename: image.filename, subfolder: image.subfolder, type: image.type });
|
|
228
|
-
const imageResponse = await this.fetchWithTimeout(`/view?${query.toString()}`, { method: 'GET' }, signal);
|
|
229
|
-
if (!imageResponse.ok) {
|
|
230
|
-
throw new NotebookError('backend-failed', `ComfyUI could not serve ${image.filename} (${String(imageResponse.status)})`);
|
|
231
|
-
}
|
|
232
|
-
return new Uint8Array(await imageResponse.arrayBuffer());
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
/**
|
|
237
|
-
* Build the backend the configuration selects.
|
|
238
|
-
* @param config - resolved plugin configuration.
|
|
239
|
-
* @param log - plugin logger, used for backend warnings.
|
|
240
|
-
* @returns the backend instance.
|
|
241
|
-
*/
|
|
242
|
-
export function createBackend(config, log) {
|
|
243
|
-
if (config.imageBackend === 'comfy') {
|
|
244
|
-
return new ComfyUiBackend(config.comfyUrl, config.comfyWorkflow, config.comfyNodes, config.requestTimeoutMs, log);
|
|
245
|
-
}
|
|
246
|
-
return new StubBackend();
|
|
247
|
-
}
|