tabherd 0.0.1 → 0.6.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 (68) hide show
  1. package/CHANGELOG.md +166 -0
  2. package/LICENSE +674 -0
  3. package/README.md +538 -2
  4. package/launcher/npm.js +9 -0
  5. package/lib/agents.js +324 -0
  6. package/lib/codex-client.js +306 -0
  7. package/lib/codex-rollout.js +251 -0
  8. package/lib/codex.js +424 -0
  9. package/lib/comfy.js +479 -0
  10. package/lib/completed.js +55 -0
  11. package/lib/copilot.js +359 -0
  12. package/lib/cursor.js +516 -0
  13. package/lib/dismissed.js +30 -0
  14. package/lib/filters.js +120 -0
  15. package/lib/groups.js +144 -0
  16. package/lib/history.js +253 -0
  17. package/lib/llamacpp.js +159 -0
  18. package/lib/lmstudio.js +134 -0
  19. package/lib/localai.js +291 -0
  20. package/lib/memory.js +55 -0
  21. package/lib/ollama.js +124 -0
  22. package/lib/open-dashboard.js +39 -0
  23. package/lib/opencode.js +371 -0
  24. package/lib/repos.js +81 -0
  25. package/lib/saved.js +33 -0
  26. package/lib/secrets.js +196 -0
  27. package/lib/session-id.js +9 -0
  28. package/lib/settings.js +231 -0
  29. package/lib/store.js +44 -0
  30. package/lib/terminals/index.js +62 -0
  31. package/lib/terminals/kitty.js +126 -0
  32. package/lib/terminals/linux.js +310 -0
  33. package/lib/terminals/macos.js +468 -0
  34. package/lib/terminals/tmux.js +89 -0
  35. package/lib/terminals/unix-driver.js +172 -0
  36. package/lib/terminals/unix.js +204 -0
  37. package/lib/terminals/unsupported.js +22 -0
  38. package/lib/terminals/wezterm.js +103 -0
  39. package/lib/terminals/windows-close.ps1 +125 -0
  40. package/lib/terminals/windows-focus.ps1 +235 -0
  41. package/lib/terminals/windows-pick-folder.ps1 +57 -0
  42. package/lib/terminals/windows-titles.js +124 -0
  43. package/lib/terminals/windows-titles.ps1 +95 -0
  44. package/lib/terminals/windows.js +166 -0
  45. package/lib/ticket-refs.js +184 -0
  46. package/lib/tickets.js +437 -0
  47. package/lib/todos.js +166 -0
  48. package/lib/trackers.js +541 -0
  49. package/lib/transcript.js +314 -0
  50. package/lib/updates.js +186 -0
  51. package/package.json +35 -7
  52. package/public/app.js +4077 -0
  53. package/public/favicon.svg +1 -0
  54. package/public/icons/tabherd-128.png +0 -0
  55. package/public/icons/tabherd-16.png +0 -0
  56. package/public/icons/tabherd-20.png +0 -0
  57. package/public/icons/tabherd-24.png +0 -0
  58. package/public/icons/tabherd-256.png +0 -0
  59. package/public/icons/tabherd-32.png +0 -0
  60. package/public/icons/tabherd-40.png +0 -0
  61. package/public/icons/tabherd-48.png +0 -0
  62. package/public/icons/tabherd-512.png +0 -0
  63. package/public/icons/tabherd-64.png +0 -0
  64. package/public/index.html +655 -0
  65. package/public/lang/es.js +742 -0
  66. package/public/style.css +1443 -0
  67. package/server.js +814 -0
  68. package/placeholder.js +0 -3
package/lib/comfy.js ADDED
@@ -0,0 +1,479 @@
1
+ 'use strict';
2
+
3
+ // ComfyUI's jobs as cards: the running and queued ones, and for a few minutes
4
+ // after, the ones just finished, with their first output. Also the models
5
+ // it has loaded, for the Memory and models card. Comfy Desktop
6
+ // records each ComfyUI it runs in comfy-procs/<installation>.json, with its
7
+ // port; a ComfyUI started some other way is looked for on its usual port.
8
+ // ComfyUI has no login, and it answers requests that carry no Origin, as a
9
+ // server's own requests don't.
10
+ //
11
+ // ComfyUI only sends a job's progress to the page that queued it. Comfy
12
+ // Desktop shows that progress in its window's title, so on Windows the
13
+ // percentage comes from there.
14
+
15
+ const fs = require('fs');
16
+ const os = require('os');
17
+ const path = require('path');
18
+ const terminals = require('./terminals');
19
+
20
+ const IS_WIN = process.platform === 'win32';
21
+ // Where Comfy Desktop keeps its records, by system.
22
+ const DESKTOP_DIRS = IS_WIN
23
+ ? [path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'Comfy Desktop')]
24
+ : process.platform === 'darwin'
25
+ ? [path.join(os.homedir(), 'Library', 'Application Support', 'Comfy Desktop')]
26
+ : [path.join(os.homedir(), '.local', 'state', 'comfyui-desktop-2'), path.join(os.homedir(), '.config', 'comfyui-desktop-2')];
27
+ // Where to look for a ComfyUI that Comfy Desktop didn't start: Settings'
28
+ // ComfyUI address, or its usual one.
29
+ const USUAL_URL = 'http://127.0.0.1:8188';
30
+ let otherUrl = USUAL_URL;
31
+
32
+ function configure({ url } = {}) {
33
+ otherUrl = (url || USUAL_URL).replace(/\/+$/, '');
34
+ }
35
+ const REFRESH_MS = 1500;
36
+ const REQUEST_MS = 2000;
37
+ // A finished job leaves the dashboard at once; for this long after, its
38
+ // outcome and output are there for the ding and the notification list. A
39
+ // failed one keeps its card until it's cleared, from up to a day ago.
40
+ const FINISHED_SHOWN_MS = 5 * 60 * 1000;
41
+ const FAILED_SHOWN_MS = 24 * 60 * 60 * 1000;
42
+ // How long an output image stays available, for the notification list.
43
+ const PREVIEW_KEPT_MS = 24 * 60 * 60 * 1000;
44
+ const NAMES_REFRESH_MS = 60 * 1000;
45
+
46
+ function isRunning(pid) {
47
+ try {
48
+ process.kill(pid, 0);
49
+ return true;
50
+ } catch (err) {
51
+ return err.code === 'EPERM';
52
+ }
53
+ }
54
+
55
+ function readJson(file) {
56
+ try {
57
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+
63
+ // The ComfyUIs running now: [{ id, name, url, desktopPid, installPath }].
64
+ // A record left by a ComfyUI that crashed has a process that's gone.
65
+ function instances(dirs = DESKTOP_DIRS, other = otherUrl) {
66
+ const found = [];
67
+ for (const dir of dirs) {
68
+ let names;
69
+ try {
70
+ names = fs.readdirSync(path.join(dir, 'comfy-procs'));
71
+ } catch {
72
+ continue;
73
+ }
74
+ const installs = readJson(path.join(dir, 'installations.json')) || [];
75
+ for (const n of names) {
76
+ const r = n.endsWith('.json') ? readJson(path.join(dir, 'comfy-procs', n)) : null;
77
+ if (!r || !Number.isInteger(r.port) || r.childExitedAt || (r.childPid && !isRunning(r.childPid))) continue;
78
+ const inst = Array.isArray(installs) ? installs.find((i) => i.id === r.installationId) : null;
79
+ found.push({
80
+ id: String(r.installationId || r.port),
81
+ name: inst?.name || 'ComfyUI',
82
+ url: `http://127.0.0.1:${r.port}`,
83
+ desktopPid: Number.isInteger(r.desktopPid) && isRunning(r.desktopPid) ? r.desktopPid : null,
84
+ installPath: r.installPath || inst?.installPath || null,
85
+ });
86
+ }
87
+ }
88
+ if (other && !found.some((f) => f.url === other)) found.push({ id: 'comfyui', name: 'ComfyUI', url: other, desktopPid: null, installPath: null });
89
+ return found;
90
+ }
91
+
92
+ async function get(base, route) {
93
+ const res = await fetch(base + route, { signal: AbortSignal.timeout(REQUEST_MS) });
94
+ if (!res.ok) throw new Error(`ComfyUI answered ${res.status}`);
95
+ return res.json();
96
+ }
97
+
98
+ async function post(base, route, body) {
99
+ const res = await fetch(base + route, {
100
+ method: 'POST',
101
+ headers: { 'Content-Type': 'application/json' },
102
+ body: JSON.stringify(body || {}),
103
+ signal: AbortSignal.timeout(REQUEST_MS),
104
+ });
105
+ if (!res.ok) throw new Error(`ComfyUI answered ${res.status}`);
106
+ return res.json().catch(() => ({}));
107
+ }
108
+
109
+ // ---- workflow names ------------------------------------------------------------
110
+
111
+ // A job only carries its workflow's ID. Saved workflows are files whose
112
+ // contents have that ID, so each is read once (again if it changes) to map ID
113
+ // to name. An unsaved workflow has no file, and so no name here.
114
+ const workflowFiles = new Map();
115
+ const namesAt = new Map();
116
+
117
+ async function refreshNames(inst, wanted) {
118
+ if (!wanted.length || Date.now() - (namesAt.get(inst.id) || 0) < NAMES_REFRESH_MS) return;
119
+ namesAt.set(inst.id, Date.now());
120
+ const files = workflowFiles.get(inst.id) || new Map();
121
+ workflowFiles.set(inst.id, files);
122
+ const list = await get(inst.url, '/api/userdata?dir=workflows&recurse=true&full_info=true').catch(() => []);
123
+ for (const f of Array.isArray(list) ? list.slice(0, 500) : []) {
124
+ if (typeof f?.path !== 'string' || !f.path.endsWith('.json')) continue;
125
+ const known = files.get(f.path);
126
+ if (known && known.modified === f.modified) continue;
127
+ const wf = await get(inst.url, `/api/userdata/${encodeURIComponent(`workflows/${f.path}`)}`).catch(() => null);
128
+ files.set(f.path, { modified: f.modified, id: wf?.id || null });
129
+ }
130
+ }
131
+
132
+ function workflowName(instId, workflowId) {
133
+ for (const [file, f] of workflowFiles.get(instId) || []) {
134
+ if (workflowId && f.id === workflowId) return path.basename(file, '.json');
135
+ }
136
+ return null;
137
+ }
138
+
139
+ // What Comfy Desktop's window title says:
140
+ // "<installation> · [39%] *<workflow> - ComfyUI · Comfy Desktop v1.2.1", or
141
+ // "… · [39%][12%] <node> · …" while one node runs. The first percentage is
142
+ // the running job's.
143
+ function parseTitle(title) {
144
+ if (!title) return null;
145
+ const parts = String(title).split(' · ');
146
+ const page = parts.length >= 3 ? parts.slice(1, -1).join(' · ') : String(title);
147
+ const m = page.match(/^\s*(?:\[(\d{1,3})%\])?(?:\[(\d{1,3})%\])?(?:\[\d+ nodes running\])?\s*\*?\s*(.*?)\s*$/);
148
+ if (!m) return null;
149
+ const rest = m[3].replace(/ - ComfyUI$/, '');
150
+ return {
151
+ percent: m[1] ? Math.min(100, Number(m[1])) : null,
152
+ // The workflow's name, when the title shows it rather than a node's.
153
+ workflow: m[2] || !/ - ComfyUI$/.test(m[3]) ? null : rest || null,
154
+ };
155
+ }
156
+
157
+ // ---- jobs as cards ------------------------------------------------------------------
158
+
159
+ // The outputs the dashboard may show, so the image proxy serves only those.
160
+ // Each with when it stops being served.
161
+ const previews = new Map();
162
+ const previewKey = (instId, p) => [instId, p.type || 'output', p.subfolder || '', p.filename].join('\u0000');
163
+
164
+ function previewFor(inst, job) {
165
+ const p = job.preview_output;
166
+ if (!p?.filename || p.mediaType !== 'images') return null;
167
+ previews.set(previewKey(inst.id, p), Date.now() + PREVIEW_KEPT_MS);
168
+ const q = new URLSearchParams({ i: inst.id, filename: p.filename, subfolder: p.subfolder || '', type: p.type || 'output' });
169
+ return `/api/comfy/view?${q}`;
170
+ }
171
+
172
+ function took(ms) {
173
+ if (!Number.isFinite(ms) || ms < 0) return null;
174
+ const s = Math.round(ms / 1000);
175
+ return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${s % 60}s`;
176
+ }
177
+
178
+ // One installation's jobs: cards for those running, queued or failed, and
179
+ // what became of those that finished in the last few minutes.
180
+ function itemsFor(inst, active, recent, { now = Date.now(), title = null } = {}) {
181
+ const shown = parseTitle(title);
182
+ const running = active.filter((j) => j.status === 'in_progress');
183
+ const pending = active.filter((j) => j.status === 'pending').sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0) || a.create_time - b.create_time);
184
+ const card = (job, fields) => {
185
+ const name = workflowName(inst.id, job.workflow_id);
186
+ return {
187
+ app: 'comfy',
188
+ kind: 'job',
189
+ id: `comfy:${inst.id}:${job.id}`,
190
+ jobId: job.id,
191
+ instance: inst.id,
192
+ name: name || 'Unsaved workflow',
193
+ title: name,
194
+ host: inst.name,
195
+ cwd: inst.installPath,
196
+ pid: inst.desktopPid,
197
+ startedAt: job.create_time || null,
198
+ outputs: job.outputs_count || 0,
199
+ ...fields,
200
+ };
201
+ };
202
+ const items = [];
203
+ for (const job of running) {
204
+ // The title's percentage is the running job's, when there's just one.
205
+ const percent = running.length === 1 && shown?.percent !== null ? shown?.percent : null;
206
+ items.push(
207
+ card(job, {
208
+ status: 'busy',
209
+ statusSince: job.execution_start_time || job.create_time,
210
+ progress: Number.isFinite(percent) ? { value: percent, max: 100 } : null,
211
+ facts: [],
212
+ // It leaves once it's done, which counts as finishing.
213
+ leavesWhenDone: true,
214
+ actions: ['focus', 'stop'],
215
+ }),
216
+ );
217
+ }
218
+ pending.forEach((job, i) =>
219
+ items.push(
220
+ card(job, {
221
+ status: 'queued',
222
+ statusSince: job.create_time,
223
+ facts: [['Queue', `${i + 1} of ${pending.length}`]],
224
+ leavesWhenDone: true,
225
+ actions: ['focus', 'cancel'],
226
+ }),
227
+ ),
228
+ );
229
+ const finished = [];
230
+ for (const job of recent) {
231
+ const ended = job.execution_end_time || job.create_time;
232
+ if (!ended) continue;
233
+ if (job.status === 'failed') {
234
+ if (now - ended > FAILED_SHOWN_MS) continue;
235
+ const error = job.execution_error?.exception_message || job.execution_error?.message || null;
236
+ items.push(
237
+ card(job, {
238
+ status: 'waiting',
239
+ statusLabel: 'Failed',
240
+ waitingFor: error ? `Failed: ${String(error).slice(0, 200)}` : 'Failed',
241
+ statusSince: ended,
242
+ facts: [],
243
+ actions: ['focus', 'dismiss'],
244
+ }),
245
+ );
246
+ } else if (now - ended <= FINISHED_SHOWN_MS) {
247
+ finished.push({
248
+ id: `comfy:${inst.id}:${job.id}`,
249
+ label: job.status === 'cancelled' ? 'Cancelled' : 'Finished',
250
+ preview: job.status === 'cancelled' ? null : previewFor(inst, job),
251
+ took: took((job.execution_end_time || 0) - (job.execution_start_time || 0)),
252
+ at: ended,
253
+ });
254
+ }
255
+ }
256
+ return { items, finished };
257
+ }
258
+
259
+ // ---- loaded models ---------------------------------------------------------------
260
+
261
+ // ComfyUI doesn't list the models it has loaded, but a job's loader nodes name
262
+ // them, and ComfyUI keeps what its last job loaded in memory for the next one,
263
+ // until it needs the room or is told to free it. So the models shown are the
264
+ // ones the latest job to run loaded, until Unload frees them. That frees them
265
+ // all, as ComfyUI can't free just one.
266
+ const MODEL_FILE = /\.(safetensors|sft|ckpt|pt|pth|bin|gguf|onnx)$/i;
267
+ // What the loader's input says a model is.
268
+ const MODEL_TYPES = [
269
+ [/^ckpt_name$/, 'Checkpoint'],
270
+ [/^unet_name$/, 'Diffusion model'],
271
+ [/^clip_name\d*$/, 'Text encoder'],
272
+ [/^vae_name$/, 'VAE'],
273
+ [/^lora_name/, 'LoRA'],
274
+ [/^control_net_name$/, 'ControlNet'],
275
+ [/^clip_vision_name$/, 'CLIP vision'],
276
+ ];
277
+
278
+ // The model files a job's workflow names, once each: [{ file, type }].
279
+ function modelsIn(prompt) {
280
+ const found = new Map();
281
+ for (const node of Object.values(prompt || {})) {
282
+ for (const [key, value] of Object.entries(node?.inputs || {})) {
283
+ if (typeof value !== 'string' || !MODEL_FILE.test(value) || found.has(value)) continue;
284
+ found.set(value, { file: value, type: MODEL_TYPES.find(([re]) => re.test(key))?.[1] || null });
285
+ }
286
+ }
287
+ return [...found.values()];
288
+ }
289
+
290
+ // The job whose models are loaded: the one running, else the last to start.
291
+ function latestRun(active, recent) {
292
+ return (
293
+ active.find((j) => j.status === 'in_progress') ||
294
+ recent.filter((j) => j.execution_start_time).sort((a, b) => b.execution_start_time - a.execution_start_time)[0] ||
295
+ null
296
+ );
297
+ }
298
+
299
+ // Each installation's latest job's models, read once per job:
300
+ // { jobId, workflowId, models }.
301
+ const loaded = new Map();
302
+ // The job whose models Unload freed, by installation. They show again once
303
+ // another job runs.
304
+ const freed = new Map();
305
+
306
+ async function refreshModels(inst, job) {
307
+ if (!job) {
308
+ loaded.delete(inst.id);
309
+ return;
310
+ }
311
+ if (loaded.get(inst.id)?.jobId === job.id) return;
312
+ // A running job's workflow is in the queue, as [number, id, prompt, …]; a
313
+ // finished one's is in its record.
314
+ const prompt =
315
+ job.status === 'in_progress'
316
+ ? (await get(inst.url, '/queue')).queue_running?.find((q) => q[1] === job.id)?.[2]
317
+ : (await get(inst.url, `/api/jobs/${encodeURIComponent(job.id)}`)).workflow?.prompt;
318
+ // Finished between the two requests: read it again next time.
319
+ if (!prompt) return;
320
+ loaded.set(inst.id, { jobId: job.id, workflowId: job.workflow_id || null, models: await withSizes(inst, modelsIn(prompt)) });
321
+ }
322
+
323
+ // The folder each type of model is kept in, looked in first, as another
324
+ // folder can have a file of the same name.
325
+ const TYPE_FOLDERS = {
326
+ Checkpoint: 'checkpoints',
327
+ 'Diffusion model': 'diffusion_models',
328
+ 'Text encoder': 'text_encoders',
329
+ VAE: 'vae',
330
+ LoRA: 'loras',
331
+ ControlNet: 'controlnet',
332
+ 'CLIP vision': 'clip_vision',
333
+ };
334
+
335
+ // The models with the size of each one's file, from ComfyUI's lists of its
336
+ // model folders: about what each takes in memory, as ComfyUI doesn't say.
337
+ // A ComfyUI too old to list them gives none.
338
+ async function withSizes(inst, models) {
339
+ let lists;
340
+ try {
341
+ const folders = await get(inst.url, '/experiment/models');
342
+ lists = await Promise.all(
343
+ folders.map(async (f) => [f.name, await get(inst.url, `/experiment/models/${encodeURIComponent(f.name)}`).catch(() => [])]),
344
+ );
345
+ } catch {
346
+ return models;
347
+ }
348
+ // A model in a subfolder is named with the system's slash.
349
+ const slashed = (name) => String(name).replace(/\\/g, '/');
350
+ const sizes = new Map(lists.map(([folder, files]) => [folder, new Map((Array.isArray(files) ? files : []).map((f) => [slashed(f.name), f.size]))]));
351
+ return models.map((m) => {
352
+ const file = slashed(m.file);
353
+ const size = [sizes.get(TYPE_FOLDERS[m.type]), ...sizes.values()].map((s) => s?.get(file)).find((n) => n > 0);
354
+ return size ? { ...m, size } : m;
355
+ });
356
+ }
357
+
358
+ const bytes = (n) => (n >= 1e9 ? `${(n / 1e9).toFixed(1)} GB` : n >= 1e6 ? `${Math.round(n / 1e6)} MB` : null);
359
+
360
+ function modelItems(inst, l) {
361
+ if (!l || freed.get(inst.id) === l.jobId) return [];
362
+ const workflow = workflowName(inst.id, l.workflowId);
363
+ return l.models.map((m) => ({
364
+ app: 'comfy',
365
+ kind: 'model',
366
+ id: `comfy:${inst.id}:model:${m.file}`,
367
+ instance: inst.id,
368
+ name: m.file.split(/[\\/]/).pop(),
369
+ host: inst.name,
370
+ // A model in a subfolder, such as "flux\model.safetensors".
371
+ where: /[\\/]/.test(m.file) ? m.file : null,
372
+ status: 'loaded',
373
+ facts: [
374
+ ['Type', m.type],
375
+ ['Size', bytes(m.size)],
376
+ ['Loaded by', workflow],
377
+ ].filter(([, v]) => v),
378
+ memory: m.size ? { used: m.size, about: true } : null,
379
+ actions: ['unload'],
380
+ }));
381
+ }
382
+
383
+ // ---- polling ---------------------------------------------------------------------
384
+
385
+ let state = [];
386
+ let refreshing = null;
387
+ let refreshedAt = 0;
388
+
389
+ async function refresh() {
390
+ const next = [];
391
+ await Promise.all(
392
+ instances().map(async (inst) => {
393
+ try {
394
+ const [active, recent] = await Promise.all([
395
+ get(inst.url, '/api/jobs?status=in_progress,pending&limit=100'),
396
+ get(inst.url, '/api/jobs?status=completed,failed,cancelled&limit=10&sort_by=created_at&sort_order=desc'),
397
+ ]);
398
+ const jobs = { active: active.jobs || [], recent: recent.jobs || [] };
399
+ next.push({ inst, ...jobs });
400
+ const ids = [...jobs.active, ...jobs.recent].map((j) => j.workflow_id).filter((id) => id && !workflowName(inst.id, id));
401
+ await Promise.all([refreshNames(inst, ids), refreshModels(inst, latestRun(jobs.active, jobs.recent)).catch(() => {})]);
402
+ } catch {
403
+ // Not running, or not answering this time.
404
+ }
405
+ }),
406
+ );
407
+ state = next;
408
+ }
409
+
410
+ function poll() {
411
+ if (!refreshing && Date.now() - refreshedAt > REFRESH_MS) {
412
+ refreshing = refresh()
413
+ .catch(() => {})
414
+ .finally(() => {
415
+ refreshing = null;
416
+ refreshedAt = Date.now();
417
+ });
418
+ }
419
+ }
420
+
421
+ // The jobs as cards and the loaded models as rows, from the last check, and
422
+ // the Comfy Desktop windows whose titles the next snapshot needs. Checks
423
+ // again in the background.
424
+ function snapshot() {
425
+ poll();
426
+ const now = Date.now();
427
+ for (const [key, until] of previews) if (until < now) previews.delete(key);
428
+ const items = [];
429
+ const finished = [];
430
+ for (const s of state) {
431
+ const out = itemsFor(s.inst, s.active, s.recent, { now, title: s.inst.desktopPid ? terminals.titleFor(s.inst.desktopPid) : null });
432
+ items.push(...out.items, ...modelItems(s.inst, loaded.get(s.inst.id)));
433
+ finished.push(...out.finished);
434
+ }
435
+ return { items, finished, windowPids: state.map((s) => s.inst.desktopPid).filter(Boolean) };
436
+ }
437
+
438
+ // ---- actions -------------------------------------------------------------------
439
+
440
+ // Stops a running job, or takes a queued one out of the queue.
441
+ async function cancel(item) {
442
+ const s = state.find((x) => x.inst.id === item.instance);
443
+ if (!s) return { ok: false, error: "That ComfyUI isn't answering." };
444
+ try {
445
+ const r = await post(s.inst.url, `/api/jobs/${encodeURIComponent(item.jobId)}/cancel`);
446
+ return r.cancelled === false ? { ok: false, error: 'It had already finished.' } : { ok: true };
447
+ } catch (err) {
448
+ return { ok: false, error: `Couldn't cancel it: ${err.message}` };
449
+ }
450
+ }
451
+
452
+ // Frees every model the installation has loaded: ComfyUI can't free just one.
453
+ // They go from the card at once, and come back when another job runs.
454
+ async function unload(item) {
455
+ const s = state.find((x) => x.inst.id === item.instance);
456
+ if (!s) return { ok: false, error: "That ComfyUI isn't answering." };
457
+ try {
458
+ await post(s.inst.url, '/free', { unload_models: true, free_memory: true });
459
+ const l = loaded.get(s.inst.id);
460
+ if (l) freed.set(s.inst.id, l.jobId);
461
+ const n = l?.models.length || 0;
462
+ return { ok: true, done: n > 1 ? `Unloaded ${s.inst.name}'s ${n} models` : `Unloaded ${item.name}` };
463
+ } catch (err) {
464
+ return { ok: false, error: `Couldn't unload them: ${err.message}` };
465
+ }
466
+ }
467
+
468
+ // An output image of a job, fetched from its ComfyUI. Only outputs of jobs
469
+ // the dashboard has reported, in the last day, are served.
470
+ async function view({ i, filename, subfolder = '', type = 'output' }) {
471
+ const s = state.find((x) => x.inst.id === i);
472
+ if (!s || !previews.has(previewKey(i, { filename, subfolder, type }))) return null;
473
+ const q = new URLSearchParams({ filename, subfolder, type, preview: 'webp;80' });
474
+ const res = await fetch(`${s.inst.url}/view?${q}`, { signal: AbortSignal.timeout(10000) });
475
+ if (!res.ok) return null;
476
+ return { type: res.headers.get('content-type') || 'image/webp', body: Buffer.from(await res.arrayBuffer()) };
477
+ }
478
+
479
+ module.exports = { snapshot, configure, cancel, unload, view, instances, itemsFor, parseTitle, modelsIn, latestRun, modelItems, withSizes };
@@ -0,0 +1,55 @@
1
+ 'use strict';
2
+
3
+ const store = require('./store');
4
+ const { isSessionId } = require('./session-id');
5
+
6
+ // Sessions marked complete, by session ID, so History can tell work that's
7
+ // done from work that was only closed. Saved as completed.json. Each keeps
8
+ // when it was marked and how many prompts the session had then: one resumed
9
+ // and asked more is no longer complete. The latest 2000 are kept, more than
10
+ // History holds.
11
+
12
+ const MAX = 2000;
13
+
14
+ function load() {
15
+ const saved = store.read('completed', null);
16
+ const list = Array.isArray(saved?.sessions) ? saved.sessions.filter((s) => isSessionId(s?.id) && Number.isFinite(s.at)) : [];
17
+ return new Map(list.map((s) => [s.id, { at: s.at, prompts: Number(s.prompts) || 0 }]));
18
+ }
19
+
20
+ let marks = load();
21
+
22
+ // Writes first and only then keeps the change, so a failed write changes nothing.
23
+ function commit(next) {
24
+ const kept = [...next].sort((a, b) => b[1].at - a[1].at).slice(0, MAX);
25
+ store.write('completed', { sessions: kept.map(([id, m]) => ({ id, ...m })) });
26
+ marks = new Map(kept);
27
+ }
28
+
29
+ function add(id, prompts, now = Date.now()) {
30
+ if (!isSessionId(id)) return;
31
+ commit(new Map(marks).set(id, { at: now, prompts: prompts || 0 }));
32
+ }
33
+
34
+ function remove(id) {
35
+ if (!marks.has(id)) return;
36
+ const next = new Map(marks);
37
+ next.delete(id);
38
+ commit(next);
39
+ }
40
+
41
+ // When the session was marked complete, or null.
42
+ const at = (id) => marks.get(id)?.at ?? null;
43
+
44
+ // Called with each snapshot: a complete session that's running again and has
45
+ // been asked more since is no longer complete.
46
+ function observe(agents) {
47
+ let next = null;
48
+ for (const a of agents) {
49
+ const m = marks.get(a.id);
50
+ if (m && (a.prompts || 0) > m.prompts) (next ||= new Map(marks)).delete(a.id);
51
+ }
52
+ if (next) commit(next);
53
+ }
54
+
55
+ module.exports = { add, remove, at, observe };