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/server.js ADDED
@@ -0,0 +1,814 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const http = require('http');
5
+ const fs = require('fs');
6
+ const os = require('os');
7
+ const path = require('path');
8
+ const crypto = require('crypto');
9
+ const { snapshot, findAgent, sessionFile } = require('./lib/agents');
10
+ const terminals = require('./lib/terminals');
11
+ const { openDashboard } = require('./lib/open-dashboard');
12
+ const { scanRepos, resolveRepo, SOURCE_DIR } = require('./lib/repos');
13
+ const settings = require('./lib/settings');
14
+ const history = require('./lib/history');
15
+ const todos = require('./lib/todos');
16
+ const groups = require('./lib/groups');
17
+ const filters = require('./lib/filters');
18
+ const codex = require('./lib/codex');
19
+ const copilot = require('./lib/copilot');
20
+ const opencode = require('./lib/opencode');
21
+ const cursor = require('./lib/cursor');
22
+ const comfy = require('./lib/comfy');
23
+ const localai = require('./lib/localai');
24
+ const ollama = require('./lib/ollama');
25
+ const lmstudio = require('./lib/lmstudio');
26
+ const llamacpp = require('./lib/llamacpp');
27
+ const saved = require('./lib/saved');
28
+ const dismissed = require('./lib/dismissed');
29
+ const completed = require('./lib/completed');
30
+ const secrets = require('./lib/secrets');
31
+ const trackers = require('./lib/trackers');
32
+ const tickets = require('./lib/tickets');
33
+ const updates = require('./lib/updates');
34
+
35
+ const PORT = Number(process.env.PORT) || 4317;
36
+ const HOST = '127.0.0.1';
37
+ const PUBLIC_DIR = path.join(__dirname, 'public');
38
+ // Fixed here rather than sent by the page, so the API can't type arbitrary
39
+ // commands into agents.
40
+ const CATCH_UP_PROMPT = (
41
+ process.env.CATCH_UP_PROMPT ||
42
+ "Catch me up: where do things stand? Briefly cover what's done, what's in progress, and anything you need from me."
43
+ ).replace(/\s+/g, ' ');
44
+ // What new tabs run: plain `claude` or `codex`, so it asks before acting,
45
+ // unless Settings says to skip permission prompts. With `resume`, they carry
46
+ // on that session.
47
+ const claudeCommand = () => (settings.get().skipPermissions ? 'claude --dangerously-skip-permissions' : 'claude');
48
+ function sessionCommand(app, resume = null) {
49
+ if (app === 'codex') return codex.command({ skipPermissions: settings.get().skipPermissions, resume });
50
+ if (app === 'copilot') return copilot.command({ skipPermissions: settings.get().skipPermissions, resume });
51
+ if (app === 'opencode') return opencode.command({ skipPermissions: settings.get().skipPermissions, resume });
52
+ if (app === 'cursor') return cursor.command({ skipPermissions: settings.get().skipPermissions, resume });
53
+ return resume ? `${claudeCommand()} --resume ${resume}` : claudeCommand();
54
+ }
55
+ // The app new sessions start in, from Settings: Claude unless Codex is chosen
56
+ // and installed.
57
+ function newSessionApp() {
58
+ const app = settings.get().newSessionApp;
59
+ if (app === 'codex' && codex.installed()) return 'codex';
60
+ if (app === 'copilot' && copilot.installed()) return 'copilot';
61
+ return 'claude';
62
+ }
63
+ // Where a to-do with no folder of its own starts: the Start in folder from
64
+ // Settings, else the repos folder. Claude can make a new project there.
65
+ const todoStartsIn = () => settings.get().todoStartFolder || SOURCE_DIR;
66
+ const SNAPSHOT_TTL_MS = 1000;
67
+ // With --exit-when-idle (as the desktop launcher starts it), the server stops
68
+ // once no dashboard has been open for this long.
69
+ const IDLE_EXIT_MS = 10 * 60 * 1000;
70
+ let lastRequestAt = Date.now();
71
+ // Required on every action, so other web pages cannot drive this server.
72
+ const TOKEN = crypto.randomBytes(24).toString('hex');
73
+ const ALLOWED_HOSTS = new Set([`127.0.0.1:${PORT}`, `localhost:${PORT}`]);
74
+ const STATIC = {
75
+ '/': ['index.html', 'text/html; charset=utf-8'],
76
+ '/app.js': ['app.js', 'text/javascript; charset=utf-8'],
77
+ '/style.css': ['style.css', 'text/css; charset=utf-8'],
78
+ // Each language's words, other than English.
79
+ '/lang/es.js': ['lang/es.js', 'text/javascript; charset=utf-8'],
80
+ // The launchers check for a running server by asking for this one.
81
+ '/favicon.svg': ['favicon.svg', 'image/svg+xml'],
82
+ '/icons/tabherd-32.png': ['icons/tabherd-32.png', 'image/png'],
83
+ '/icons/tabherd-64.png': ['icons/tabherd-64.png', 'image/png'],
84
+ };
85
+
86
+ let cached = null;
87
+ let cachedAt = 0;
88
+ let inflight = null;
89
+
90
+ function currentSnapshot() {
91
+ if (cached && Date.now() - cachedAt < SNAPSHOT_TTL_MS) return Promise.resolve(cached);
92
+ if (!inflight) {
93
+ inflight = snapshot()
94
+ .then((snap) => {
95
+ // Failed jobs, chats and downloads that were cleared.
96
+ snap.agents = snap.agents.filter((a) => !dismissed.has(a.id));
97
+ // To-dos first: a to-do goes on its session's card, and from there
98
+ // into the history when the session closes.
99
+ todos.observe(snap.agents, snap.now);
100
+ snap.todos = todos.pending(snap.now);
101
+ snap.todoStartsIn = todoStartsIn();
102
+ // Each card's group, worked out here so every browser agrees. A to-do
103
+ // with no folder is in the group of the folder it will start in.
104
+ snap.groups = groups.list();
105
+ for (const a of snap.agents) Object.assign(a, groups.groupOf(a));
106
+ for (const t of snap.todos) Object.assign(t, groups.groupOf({ id: t.id, cwd: t.cwd || snap.todoStartsIn }));
107
+ // The filter tabs after All, the same in every browser.
108
+ snap.filters = filters.list();
109
+ // Whether this computer has a terminal the dashboard can drive, for
110
+ // Go to window, Catch up, Start, Resume and the repo menu.
111
+ snap.terminals = terminals.terminals().some((t) => t.available);
112
+ // Whether Codex can be chosen for new sessions, and which app they start in.
113
+ snap.codexInstalled = codex.installed();
114
+ // Whether Codex's open sessions are known yet, so the first-run tour
115
+ // waits for them.
116
+ snap.settled = codex.settled();
117
+ snap.copilotInstalled = copilot.installed();
118
+ snap.newSessionApp = newSessionApp();
119
+ // Each session's and to-do's tickets, before the history takes the
120
+ // sessions that closed.
121
+ tickets.observe(snap.agents, snap.now);
122
+ for (const t of snap.todos) t.tickets = tickets.forTodo(t, snap.now);
123
+ // Whether there are trackers, so cards offer + Ticket.
124
+ snap.trackerCount = (settings.get().trackers || []).length;
125
+ history.observe(snap.agents, snap.now);
126
+ // Sessions marked complete, which a session asked more once resumed
127
+ // no longer is.
128
+ completed.observe(snap.agents);
129
+ for (const a of snap.agents) {
130
+ const at = completed.at(a.id);
131
+ if (at) a.completedAt = at;
132
+ }
133
+ // Sessions Save and close or Complete is waiting on: each closes once
134
+ // it's done.
135
+ closeFinished(snap.agents);
136
+ snap.closing = [...closing.keys()];
137
+ const last = saved.get();
138
+ snap.saved = last ? { savedAt: last.savedAt, count: last.sessions.length } : null;
139
+ // This version, whether to check for a newer one, and any found.
140
+ snap.updates = updateSummary();
141
+ cached = snap;
142
+ cachedAt = Date.now();
143
+ return snap;
144
+ })
145
+ .finally(() => {
146
+ inflight = null;
147
+ });
148
+ }
149
+ return inflight;
150
+ }
151
+
152
+ // Open dashboards get each snapshot pushed to them. A browser slows timers in
153
+ // hidden or covered windows to as little as once a minute, but a pushed message
154
+ // is handled at once, so the page can ding the moment an agent needs you.
155
+ const STREAM_MS = 2000;
156
+ const streams = new Set();
157
+ let streamTimer = null;
158
+
159
+ function pushSnapshot() {
160
+ currentSnapshot()
161
+ .then((snap) => {
162
+ const message = `data: ${JSON.stringify(snap)}\n\n`;
163
+ for (const res of streams) res.write(message);
164
+ })
165
+ .catch(() => {});
166
+ }
167
+
168
+ function openStream(req, res) {
169
+ res.writeHead(200, {
170
+ 'Content-Type': 'text/event-stream; charset=utf-8',
171
+ 'Cache-Control': 'no-store',
172
+ 'X-Content-Type-Options': 'nosniff',
173
+ });
174
+ res.write('retry: 2000\n\n');
175
+ streams.add(res);
176
+ pushSnapshot();
177
+ if (!streamTimer) streamTimer = setInterval(pushSnapshot, STREAM_MS);
178
+ req.on('close', () => {
179
+ streams.delete(res);
180
+ lastRequestAt = Date.now();
181
+ if (!streams.size) {
182
+ clearInterval(streamTimer);
183
+ streamTimer = null;
184
+ }
185
+ });
186
+ }
187
+
188
+ function send(res, status, body, type = 'application/json; charset=utf-8') {
189
+ res.writeHead(status, {
190
+ 'Content-Type': type,
191
+ 'Cache-Control': 'no-store',
192
+ 'X-Content-Type-Options': 'nosniff',
193
+ 'Content-Security-Policy': "default-src 'self'; style-src 'self'; img-src 'self' data:",
194
+ });
195
+ res.end(typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body));
196
+ }
197
+
198
+ // The settings as the page sees them: a key only says whether one is set, and
199
+ // the trackers come from their own routes.
200
+ const forPage = (s) => ({
201
+ ...s,
202
+ localaiKey: '',
203
+ localaiKeySet: Boolean(s.localaiKey),
204
+ lmstudioKey: '',
205
+ lmstudioKeySet: Boolean(s.lmstudioKey),
206
+ trackers: undefined,
207
+ });
208
+
209
+ // Settings → Tickets: the trackers without their tokens, and how secrets are
210
+ // kept on this computer.
211
+ const trackersForPage = () => ({
212
+ ok: true,
213
+ trackers: trackers.forPage(settings.get().trackers),
214
+ // Each tracker's last failed lookup, if it hasn't answered since.
215
+ problems: tickets.problems(),
216
+ secrets: { ...secrets.status(), unreadable: settings.unreadableKeys() },
217
+ });
218
+
219
+ async function trackerAction(res, name, body) {
220
+ const list = settings.get().trackers;
221
+ if (name === 'list') return send(res, 200, trackersForPage());
222
+ if (name === 'test') {
223
+ const t = list.find((x) => x.id === body.id);
224
+ if (!t) return send(res, 404, { ok: false, error: 'That tracker is gone.' });
225
+ return send(res, 200, await trackers.test(t));
226
+ }
227
+ const result = name === 'save' ? trackers.save(list, body.tracker) : { ok: true, list: trackers.remove(list, body.id) };
228
+ if (!result.ok) return send(res, 400, result);
229
+ const saved = settings.update({ trackers: result.list }, { internal: true });
230
+ if (!saved.ok) return send(res, 500, saved);
231
+ // What was read with its old sign-in, or from it, goes.
232
+ tickets.forget(name === 'save' ? result.tracker.id : body.id);
233
+ cached = null;
234
+ return send(res, 200, { ...trackersForPage(), id: result.tracker?.id });
235
+ }
236
+
237
+ // Other apps' addresses and keys, from Settings.
238
+ function configureApps() {
239
+ const s = settings.get();
240
+ comfy.configure({ url: s.comfyUrl });
241
+ localai.configure({ url: s.localaiUrl, key: s.localaiKey });
242
+ ollama.configure({ url: s.ollamaUrl });
243
+ lmstudio.configure({ url: s.lmstudioUrl, key: s.lmstudioKey });
244
+ llamacpp.configure({ url: s.llamacppUrl });
245
+ }
246
+ configureApps();
247
+
248
+ const updateSummary = () => updates.summary(settings.get().updateCheck, settings.get().updatePrereleases);
249
+
250
+ // Checks GitHub for a newer Tabherd, if Settings says to and it's been a day,
251
+ // or at once for Check now, and tells open dashboards what it found.
252
+ async function checkForUpdates({ force = false } = {}) {
253
+ const result = await updates.check({ enabled: settings.get().updateCheck === true, force });
254
+ cached = null;
255
+ if (streams.size) pushSnapshot();
256
+ return result;
257
+ }
258
+
259
+ // Opens a tab running `command` in `dir`, in the terminal chosen in Settings.
260
+ // The command is always built here, never sent by the page.
261
+ const openTab = (dir, command) => terminals.open(dir, command, { terminal: settings.get().terminal });
262
+
263
+ function readJson(req) {
264
+ return new Promise((resolve) => {
265
+ let body = '';
266
+ req.setEncoding('utf8');
267
+ req.on('data', (chunk) => {
268
+ body += chunk;
269
+ // Room for every group's folders, at their most.
270
+ if (body.length > 262144) req.destroy();
271
+ });
272
+ req.on('end', () => {
273
+ try {
274
+ resolve(JSON.parse(body || '{}'));
275
+ } catch {
276
+ resolve({});
277
+ }
278
+ });
279
+ req.on('error', () => resolve({}));
280
+ });
281
+ }
282
+
283
+ async function action(res, sessionId, name) {
284
+ const agent = await findAgent(sessionId);
285
+ if (!agent) return send(res, 404, { ok: false, error: 'That session is no longer running.' });
286
+ cached = null;
287
+ if (name === 'open-folder') {
288
+ if (!agent.cwd || !fs.existsSync(agent.cwd)) return send(res, 400, { ok: false, error: 'Folder not found.' });
289
+ terminals.openFolder(agent.cwd);
290
+ return send(res, 200, { ok: true });
291
+ }
292
+ // A failed job, chat or download, cleared from the dashboard.
293
+ if (name === 'dismiss') {
294
+ if (!(agent.actions || []).includes('dismiss')) return send(res, 400, { ok: false, error: "That can't be cleared: it's still going." });
295
+ dismissed.add(agent.id);
296
+ pushSnapshot();
297
+ return send(res, 200, { ok: true });
298
+ }
299
+ // A session marked complete, then closed as Save and close closes it: a
300
+ // working one once its turn ends. One that can't be closed isn't marked.
301
+ if (name === 'complete') {
302
+ if (!closable(agent)) return send(res, 400, { ok: false, error: "That session can't be closed from here." });
303
+ completed.add(agent.id, agent.prompts);
304
+ if (working(agent)) {
305
+ closing.set(agent.id, agent.name);
306
+ pushSnapshot();
307
+ return send(res, 200, { ok: true, waiting: true });
308
+ }
309
+ const result = await closeSession(agent).catch((err) => ({ ok: false, error: err.message }));
310
+ if (!result.ok) completed.remove(agent.id);
311
+ pushSnapshot();
312
+ return send(res, result.ok ? 200 : 500, result);
313
+ }
314
+ // LocalAI: Unload a model, Stop a chat's turn, Cancel a download or agent
315
+ // job. Ollama, LM Studio and llama.cpp: Unload a model.
316
+ const service = { localai, ollama, lmstudio, llamacpp }[agent.app];
317
+ if (service && ['stop', 'cancel', 'unload'].includes(name)) {
318
+ const result = await service.act(agent, name);
319
+ return send(res, result.ok ? 200 : 500, result);
320
+ }
321
+ // A ComfyUI job: Stop and Cancel go to its ComfyUI, which ends a running
322
+ // job or takes a queued one out of the queue. A model's Unload frees all of
323
+ // its ComfyUI's models.
324
+ if (agent.app === 'comfy' && ['stop', 'cancel', 'unload'].includes(name)) {
325
+ const result = name === 'unload' ? await comfy.unload(agent) : await comfy.cancel(agent);
326
+ return send(res, result.ok ? 200 : 500, result);
327
+ }
328
+ // A VS Code Copilot session runs in VS Code's agent host, with every other
329
+ // VS Code session: its window can be brought up, and that's all.
330
+ if (agent.app === 'copilot' && agent.entrypoint === 'vscode' && name !== 'focus' && name !== 'open-folder') {
331
+ return send(res, 400, { ok: false, error: 'Use VS Code for that: this session runs inside it.' });
332
+ }
333
+ // A Codex session's window is only known once its tab's title names it.
334
+ if (name === 'focus' && !agent.pid) {
335
+ return send(res, 409, { ok: false, error: `Couldn't tell which window ${agent.title || agent.name} is in.` });
336
+ }
337
+ if (name === 'catch-up' && agent.status === 'waiting') {
338
+ const label = agent.terminalTitle || agent.title || agent.name;
339
+ return send(res, 409, { ok: false, error: `${label} is waiting on a prompt or dialog. Use Go to window and answer it first.` });
340
+ }
341
+ // Codex and OpenCode take Catch up's prompt through their services, so
342
+ // nothing is typed into the window, which comes forward if it's known. Stop
343
+ // interrupts the turn it's running, then ends the app in its window.
344
+ const sessions = { codex, opencode }[agent.app];
345
+ if (sessions && name === 'catch-up') {
346
+ const queued = await sessions.queuePrompt(agent.id, CATCH_UP_PROMPT);
347
+ if (!queued.ok) return send(res, 500, queued);
348
+ const shown = agent.pid ? await terminals.focus(agent.pid) : null;
349
+ return send(res, 200, { ok: true, queued: true, raised: Boolean(shown?.raised), window: shown?.window || null });
350
+ }
351
+ if (sessions && name === 'stop') {
352
+ const stopped = await sessions.interrupt(agent.id);
353
+ if (!stopped.ok) return send(res, 500, stopped);
354
+ if (!agent.pid) return send(res, 200, { ok: true, interrupted: stopped.interrupted, windowLeft: true });
355
+ const result = await terminals.stop(agent.pid);
356
+ return send(res, result.ok ? 200 : 500, { ...result, interrupted: stopped.interrupted });
357
+ }
358
+ if (name === 'focus' || name === 'catch-up') {
359
+ const prompt = name === 'catch-up' ? CATCH_UP_PROMPT : null;
360
+ // Claude's registry file is checked again just before typing; other apps
361
+ // were checked above.
362
+ const result = await terminals.focus(agent.pid, { send: prompt, statusFile: agent.app === 'claude' ? sessionFile(agent.pid) : '' });
363
+ return send(res, result.ok ? 200 : 500, result);
364
+ }
365
+ if (name === 'stop') {
366
+ const result = await terminals.stop(agent.pid);
367
+ return send(res, result.ok ? 200 : 500, result);
368
+ }
369
+ return send(res, 404, { ok: false, error: 'Unknown action.' });
370
+ }
371
+
372
+ // ---- Save and close, and Resume last session ----------------------------------
373
+
374
+ // The sessions Save and close takes: Claude's, Codex's, OpenCode's and
375
+ // Cursor's in a terminal. Not background runs, which have no tab, nor
376
+ // sessions in a VS Code panel, which has no shell to close.
377
+ const closable = (a) =>
378
+ (a.app === 'claude' && !a.background && (!a.kind || a.kind === 'interactive') && (!a.entrypoint || a.entrypoint === 'cli')) ||
379
+ a.app === 'codex' ||
380
+ a.app === 'opencode' ||
381
+ a.app === 'cursor' ||
382
+ (a.app === 'copilot' && a.entrypoint === 'cli');
383
+ const working = (a) => a.status === 'busy' || a.status === 'shell';
384
+ // Waiting to close once they're done: session ID -> its name.
385
+ const closing = new Map();
386
+
387
+ // Ends a session and its tab. A Codex or OpenCode session's turn is
388
+ // interrupted first, and one whose window isn't known can't be closed from here.
389
+ async function closeSession(a) {
390
+ if (a.app === 'codex' || a.app === 'opencode') {
391
+ await { codex, opencode }[a.app].interrupt(a.id);
392
+ if (!a.pid) return { ok: false, error: "its window isn't known" };
393
+ }
394
+ return terminals.close(a.pid);
395
+ }
396
+
397
+ function closeFinished(agents) {
398
+ for (const [id] of closing) {
399
+ const a = agents.find((x) => x.id === id);
400
+ if (!a) closing.delete(id);
401
+ else if (!working(a)) {
402
+ closing.delete(id);
403
+ closeSession(a).catch(() => {});
404
+ }
405
+ }
406
+ }
407
+
408
+ // Saves every open session, replacing the last saved set, then closes them.
409
+ // Working ones close now, or with `wait` once they finish their turn. A
410
+ // session that was never asked anything has nothing to resume, and one
411
+ // marked complete is done, so they're closed but not saved.
412
+ async function saveAndClose(res, body) {
413
+ cached = null;
414
+ const snap = await currentSnapshot();
415
+ const open = snap.agents.filter(closable);
416
+ const set = saved.save(
417
+ open.filter((a) => a.prompts > 0 && !a.completedAt).map((a) => ({ app: a.app, id: a.id, cwd: a.cwd, name: a.terminalTitle || a.title || a.name })),
418
+ snap.now,
419
+ );
420
+ const failed = [];
421
+ let closed = 0;
422
+ for (const a of open) {
423
+ if (body.wait && working(a)) {
424
+ closing.set(a.id, a.name);
425
+ continue;
426
+ }
427
+ const result = await closeSession(a).catch((err) => ({ ok: false, error: err.message }));
428
+ if (result.ok) closed++;
429
+ else failed.push({ name: a.terminalTitle || a.title || a.name, error: result.error });
430
+ }
431
+ cached = null;
432
+ pushSnapshot();
433
+ return send(res, 200, { ok: true, saved: set.sessions.length, closed, waiting: closing.size, failed });
434
+ }
435
+
436
+ // Opens each session in the saved set in a terminal tab, carrying on its
437
+ // conversation. Ones that are open already, or whose folder has gone, are
438
+ // skipped.
439
+ async function resumeLast(res) {
440
+ const set = saved.get();
441
+ if (!set?.sessions.length) return send(res, 404, { ok: false, error: 'There is no saved session to resume.' });
442
+ cached = null;
443
+ const snap = await currentSnapshot();
444
+ const open = new Set(snap.agents.map((a) => a.id));
445
+ const skipped = [];
446
+ let opened = 0;
447
+ for (const s of set.sessions) {
448
+ if (open.has(s.id)) skipped.push({ name: s.name, why: 'already open' });
449
+ else if (!fs.existsSync(s.cwd)) skipped.push({ name: s.name, why: 'its folder is gone' });
450
+ else {
451
+ // The ID comes from the saved set, which only holds session IDs, each
452
+ // safe in a command line (session-id.js).
453
+ const result = await openTab(s.cwd, sessionCommand(s.app, s.id));
454
+ if (result.ok) opened++;
455
+ else skipped.push({ name: s.name, why: result.error });
456
+ // One at a time, so each tab opens before the next.
457
+ await new Promise((resolve) => setTimeout(resolve, 600));
458
+ }
459
+ }
460
+ return send(res, 200, { ok: true, opened, skipped });
461
+ }
462
+
463
+ // Everything about a to-do's folder and session is decided here: the folder
464
+ // comes from the repo scan or the folder picker, never from the page, and the
465
+ // session ID is made here.
466
+ async function todoAction(res, id, name, body) {
467
+ const todo = todos.find(id);
468
+ if (!todo) return send(res, 404, { ok: false, error: 'That to-do no longer exists.' });
469
+ let result;
470
+ if (name === 'edit') result = todos.edit(id, body);
471
+ else if (name === 'delete') result = todos.remove(id);
472
+ else if (name === 'folder') {
473
+ let dir;
474
+ if (body.pick) {
475
+ const start = todo.cwd || todoStartsIn();
476
+ const picked = await terminals.pickFolder(start, `Choose a folder for “${todo.title}”`);
477
+ if (!picked.ok || picked.cancelled) return send(res, picked.ok ? 200 : 500, picked);
478
+ dir = typeof picked.path === 'string' ? picked.path : '';
479
+ // Virtual folders, such as This PC, have no path.
480
+ if (!dir || !fs.statSync(dir, { throwIfNoEntry: false })?.isDirectory()) {
481
+ return send(res, 400, { ok: false, error: "That isn't a folder Claude can start in. Choose one on a drive." });
482
+ }
483
+ } else {
484
+ dir = resolveRepo(body.repo);
485
+ if (!dir) return send(res, 404, { ok: false, error: 'That repo is not in the list. Rescan and try again.' });
486
+ }
487
+ result = todos.setFolder(id, dir);
488
+ if (result.ok) result.cwd = dir;
489
+ } else if (name === 'start') {
490
+ if (todos.isLive(id)) return send(res, 409, { ok: false, error: 'Its session is already running.' });
491
+ const cwd = todo.cwd || todoStartsIn();
492
+ if (!fs.existsSync(cwd)) {
493
+ const which = todo.cwd ? 'Its folder' : 'The folder to-dos start in';
494
+ return send(res, 400, { ok: false, error: `${which} doesn't exist: ${cwd}` });
495
+ }
496
+ const app = todo.app || newSessionApp();
497
+ if (app === 'copilot') {
498
+ if (!copilot.installed()) return send(res, 400, { ok: false, error: "The Copilot CLI isn't installed on this computer." });
499
+ // Like Claude: the server makes the session's ID, so it knows which
500
+ // session the to-do became, and Copilot names the session after it.
501
+ const sessionId = crypto.randomUUID();
502
+ const name = terminals.quote(todo.title.replace(/"/g, '”'));
503
+ const opened = await openTab(cwd, copilot.command({ skipPermissions: settings.get().skipPermissions, sessionId, name }));
504
+ if (!opened.ok) return send(res, 500, opened);
505
+ groups.carry(id, sessionId);
506
+ result = todos.started(id, sessionId);
507
+ } else if (app === 'codex') {
508
+ if (!codex.installed()) return send(res, 400, { ok: false, error: "Codex isn't installed on this computer." });
509
+ const opened = await openTab(cwd, sessionCommand('codex'));
510
+ if (!opened.ok) return send(res, 500, opened);
511
+ // Codex picks its session's ID itself, so the to-do is linked to the
512
+ // session once it starts, and the session is named after the to-do then.
513
+ codex.expect(cwd, (threadId) => {
514
+ todos.linked(id, threadId);
515
+ groups.carry(id, threadId);
516
+ codex.rename(threadId, todo.title);
517
+ });
518
+ result = todos.started(id, null);
519
+ } else {
520
+ const sessionId = crypto.randomUUID();
521
+ // Named after the to-do, which Claude shows in its tab's title and its
522
+ // session list. Straight double quotes become curly ones: Windows
523
+ // PowerShell 5.1 mangles them in a program's arguments.
524
+ const name = terminals.quote(todo.title.replace(/"/g, '”'));
525
+ const opened = await openTab(cwd, `${claudeCommand()} --session-id ${sessionId} --name ${name}`);
526
+ if (!opened.ok) return send(res, 500, opened);
527
+ groups.carry(id, sessionId);
528
+ result = todos.started(id, sessionId);
529
+ }
530
+ }
531
+ if (result.ok) {
532
+ cached = null;
533
+ pushSnapshot();
534
+ }
535
+ return send(res, result.ok ? 200 : 400, result);
536
+ }
537
+
538
+ const server = http.createServer(async (req, res) => {
539
+ try {
540
+ // Rejecting other Host headers blocks DNS-rebinding pages from reading prompts.
541
+ if (!ALLOWED_HOSTS.has(req.headers.host)) return send(res, 403, { error: 'Forbidden host' });
542
+ lastRequestAt = Date.now();
543
+ const url = new URL(req.url, `http://${req.headers.host}`);
544
+
545
+ if (req.method === 'GET' && url.pathname === '/api/agents') {
546
+ return send(res, 200, await currentSnapshot());
547
+ }
548
+
549
+ if (req.method === 'GET' && url.pathname === '/api/stream') return openStream(req, res);
550
+
551
+ if (req.method === 'GET' && url.pathname === '/api/repos') {
552
+ const { root, tree, all, count, excludedFolders } = scanRepos(url.searchParams.has('refresh'));
553
+ const app = newSessionApp();
554
+ return send(res, 200, { root, home: os.homedir(), tree, all, count, excluded: excludedFolders.length, app, command: sessionCommand(app) });
555
+ }
556
+
557
+ if (url.pathname === '/api/settings') {
558
+ // With the terminals this computer has, for the Terminal setting.
559
+ if (req.method === 'GET') return send(res, 200, { ok: true, settings: forPage(settings.get()), terminals: terminals.terminals() });
560
+ if (req.method !== 'POST') return send(res, 405, { error: 'Use GET or POST' });
561
+ if (req.headers['x-agents-token'] !== TOKEN) return send(res, 403, { error: 'Missing or bad token' });
562
+ const body = await readJson(req);
563
+ const result = settings.update(body);
564
+ if (result.ok) configureApps();
565
+ // Every dashboard hears the answer to checking for updates, and a yes
566
+ // checks now. Prereleases on or off needs no new check.
567
+ if (result.ok && ('updateCheck' in body || 'updatePrereleases' in body)) {
568
+ cached = null;
569
+ pushSnapshot();
570
+ if (body.updateCheck) checkForUpdates().catch(() => {});
571
+ }
572
+ return send(res, result.ok ? 200 : 400, result.ok ? { ...result, settings: forPage(result.settings) } : result);
573
+ }
574
+
575
+ // Settings → Tickets: list, save, remove or test a tracker. Even listing
576
+ // needs the token, as it has the trackers' addresses and emails.
577
+ const trackerRoute = url.pathname.match(/^\/api\/tickets\/trackers\/(list|save|remove|test)$/);
578
+ if (trackerRoute) {
579
+ if (req.method !== 'POST') return send(res, 405, { error: 'Use POST' });
580
+ if (req.headers['x-agents-token'] !== TOKEN) return send(res, 403, { error: 'Missing or bad token' });
581
+ return await trackerAction(res, trackerRoute[1], await readJson(req));
582
+ }
583
+
584
+ // A newer Tabherd's notes, and how to update this copy, for the update dialog.
585
+ if (req.method === 'GET' && url.pathname === '/api/updates') {
586
+ return send(res, 200, { ok: true, ...updates.details(settings.get().updatePrereleases) });
587
+ }
588
+
589
+ // Check now: asks GitHub at once, whatever Settings says, as someone asked.
590
+ if (url.pathname === '/api/updates/check') {
591
+ if (req.method !== 'POST') return send(res, 405, { error: 'Use POST' });
592
+ if (req.headers['x-agents-token'] !== TOKEN) return send(res, 403, { error: 'Missing or bad token' });
593
+ const result = await checkForUpdates({ force: true });
594
+ if (result.failedAt > result.checkedAt) return send(res, 502, { ok: false, error: `Couldn't reach GitHub: ${result.error}` });
595
+ return send(res, 200, { ok: true, ...updateSummary() });
596
+ }
597
+
598
+ if (url.pathname === '/api/repos/open') {
599
+ if (req.method !== 'POST') return send(res, 405, { error: 'Use POST' });
600
+ if (req.headers['x-agents-token'] !== TOKEN) return send(res, 403, { error: 'Missing or bad token' });
601
+ const dir = resolveRepo((await readJson(req)).path);
602
+ if (!dir) return send(res, 404, { ok: false, error: 'That repo is not in the list. Rescan and try again.' });
603
+ const result = await openTab(dir, sessionCommand(newSessionApp()));
604
+ return send(res, result.ok ? 200 : 500, result);
605
+ }
606
+
607
+ if (req.method === 'GET' && url.pathname === '/api/history') {
608
+ // A fresh snapshot first, so running sessions aren't mistaken for closed ones.
609
+ await currentSnapshot();
610
+ await history.backfill();
611
+ return send(res, 200, {
612
+ ok: true,
613
+ sessions: history.list().map((s) => ({ ...s, ...groups.groupOf(s), completedAt: completed.at(s.id) })),
614
+ groups: groups.list(),
615
+ });
616
+ }
617
+
618
+ const resume = url.pathname.match(/^\/api\/history\/([0-9a-f-]{36})\/resume$/i);
619
+ if (resume) {
620
+ if (req.method !== 'POST') return send(res, 405, { error: 'Use POST' });
621
+ if (req.headers['x-agents-token'] !== TOKEN) return send(res, 403, { error: 'Missing or bad token' });
622
+ const past = history.find(resume[1]);
623
+ if (!past) return send(res, 404, { ok: false, error: 'That session is not in the history.' });
624
+ if (history.isLive(past.id)) return send(res, 409, { ok: false, error: 'That session is already running.' });
625
+ if (!fs.existsSync(past.cwd)) return send(res, 400, { ok: false, error: `Its folder no longer exists: ${past.cwd}` });
626
+ // The ID comes from the history's own records, which only hold UUIDs.
627
+ const result = await openTab(past.cwd, sessionCommand(past.app || 'claude', past.id));
628
+ return send(res, result.ok ? 200 : 500, result);
629
+ }
630
+
631
+ // Save and close every open session, stop waiting on one, or resume the
632
+ // last saved set.
633
+ const sessionsAction = url.pathname.match(/^\/api\/sessions\/(save-close|keep-open|resume-last)$/);
634
+ if (sessionsAction) {
635
+ if (req.method !== 'POST') return send(res, 405, { error: 'Use POST' });
636
+ if (req.headers['x-agents-token'] !== TOKEN) return send(res, 403, { error: 'Missing or bad token' });
637
+ const body = await readJson(req);
638
+ if (sessionsAction[1] === 'save-close') return await saveAndClose(res, body);
639
+ if (sessionsAction[1] === 'resume-last') return await resumeLast(res);
640
+ // Kept open, it's not complete either.
641
+ closing.delete(String(body.id));
642
+ completed.remove(String(body.id));
643
+ cached = null;
644
+ pushSnapshot();
645
+ return send(res, 200, { ok: true });
646
+ }
647
+
648
+ // Every group at once, from the Settings editor; or one session or to-do
649
+ // put in a group by hand.
650
+ if (url.pathname === '/api/groups' || url.pathname === '/api/groups/place') {
651
+ if (req.method !== 'POST') return send(res, 405, { error: 'Use POST' });
652
+ if (req.headers['x-agents-token'] !== TOKEN) return send(res, 403, { error: 'Missing or bad token' });
653
+ const body = await readJson(req);
654
+ const result = url.pathname === '/api/groups' ? groups.setGroups(body.groups) : groups.place(body.id, body.group === undefined ? 'auto' : body.group);
655
+ if (result.ok) {
656
+ cached = null;
657
+ pushSnapshot();
658
+ }
659
+ return send(res, result.ok ? 200 : 400, result);
660
+ }
661
+
662
+ // Every filter at once, in order, as the page edits them; or the usual
663
+ // ones back.
664
+ if (url.pathname === '/api/filters') {
665
+ if (req.method !== 'POST') return send(res, 405, { error: 'Use POST' });
666
+ if (req.headers['x-agents-token'] !== TOKEN) return send(res, 403, { error: 'Missing or bad token' });
667
+ const body = await readJson(req);
668
+ const result = filters.setFilters(body.reset === true ? filters.DEFAULTS : body.filters);
669
+ if (result.ok) {
670
+ cached = null;
671
+ pushSnapshot();
672
+ }
673
+ return send(res, result.ok ? 200 : 400, result);
674
+ }
675
+
676
+ // A ticket's link or key pasted as a new to-do's title: its title and
677
+ // description, to fill in the to-do.
678
+ if (url.pathname === '/api/tickets/describe') {
679
+ if (req.method !== 'POST') return send(res, 405, { error: 'Use POST' });
680
+ if (req.headers['x-agents-token'] !== TOKEN) return send(res, 403, { error: 'Missing or bad token' });
681
+ const answer = await tickets.describe((await readJson(req))?.text);
682
+ return send(res, answer.ok ? 200 : 400, answer);
683
+ }
684
+
685
+ // A card's + Ticket, a ticket's ✕, and the Complete dialog's options and
686
+ // what it posts to the tickets. The session must be on the dashboard now,
687
+ // and only the tickets on its card are written to.
688
+ const ticketRoute = url.pathname.match(/^\/api\/tickets\/(add|remove|done-options|write)$/);
689
+ if (ticketRoute) {
690
+ if (req.method !== 'POST') return send(res, 405, { error: 'Use POST' });
691
+ if (req.headers['x-agents-token'] !== TOKEN) return send(res, 403, { error: 'Missing or bad token' });
692
+ const body = await readJson(req);
693
+ const agent = (await currentSnapshot()).agents.find((a) => a.id === body?.id);
694
+ if (!agent) return send(res, 404, { ok: false, error: 'That session is no longer running.' });
695
+ const run = {
696
+ add: () => tickets.add(agent, body.text),
697
+ remove: () => tickets.remove(agent.id, body.chip),
698
+ 'done-options': () => tickets.doneOptions(agent),
699
+ write: () => tickets.writeBack(agent, body.writes),
700
+ }[ticketRoute[1]];
701
+ const answer = await run();
702
+ cached = null;
703
+ pushSnapshot();
704
+ return send(res, answer.ok ? 200 : 400, answer);
705
+ }
706
+
707
+ if (url.pathname === '/api/todos') {
708
+ if (req.method !== 'POST') return send(res, 405, { error: 'Use POST' });
709
+ if (req.headers['x-agents-token'] !== TOKEN) return send(res, 403, { error: 'Missing or bad token' });
710
+ const result = todos.create(await readJson(req));
711
+ if (result.ok) {
712
+ cached = null;
713
+ pushSnapshot();
714
+ }
715
+ return send(res, result.ok ? 200 : 400, result);
716
+ }
717
+
718
+ const t = url.pathname.match(/^\/api\/todos\/([0-9a-f-]{36})(?:\/(delete|folder|start))?$/i);
719
+ if (t) {
720
+ if (req.method !== 'POST') return send(res, 405, { error: 'Use POST' });
721
+ if (req.headers['x-agents-token'] !== TOKEN) return send(res, 403, { error: 'Missing or bad token' });
722
+ return await todoAction(res, t[1], t[2] || 'edit', await readJson(req));
723
+ }
724
+
725
+ // Sessions have UUIDs, or OpenCode's ses_ IDs; jobs and models have IDs
726
+ // such as comfy:<install>:<job>.
727
+ // Either way it must be on the dashboard now.
728
+ const m = url.pathname.match(/^\/api\/agents\/([^/]{1,300})\/(focus|catch-up|open-folder|stop|complete|cancel|unload|dismiss)$/i);
729
+ if (m) {
730
+ if (req.method !== 'POST') return send(res, 405, { error: 'Use POST' });
731
+ if (req.headers['x-agents-token'] !== TOKEN) return send(res, 403, { error: 'Missing or bad token' });
732
+ let id;
733
+ try {
734
+ id = decodeURIComponent(m[1]);
735
+ } catch {
736
+ return send(res, 400, { error: 'Bad ID' });
737
+ }
738
+ return await action(res, id, m[2]);
739
+ }
740
+
741
+ // A ComfyUI job's output, for its card. Only outputs on cards are served.
742
+ if (req.method === 'GET' && url.pathname === '/api/comfy/view') {
743
+ const p = Object.fromEntries(url.searchParams);
744
+ const image = typeof p.i === 'string' && typeof p.filename === 'string' ? await comfy.view(p).catch(() => null) : null;
745
+ if (!image) return send(res, 404, { error: 'Not found' });
746
+ res.writeHead(200, { 'Content-Type': image.type, 'Cache-Control': 'private, max-age=600', 'X-Content-Type-Options': 'nosniff' });
747
+ return res.end(image.body);
748
+ }
749
+
750
+ const file = req.method === 'GET' && STATIC[url.pathname];
751
+ if (file) {
752
+ let body = fs.readFileSync(path.join(PUBLIC_DIR, file[0]));
753
+ if (file[0] === 'index.html') body = body.toString('utf8').replace('%%TOKEN%%', TOKEN);
754
+ return send(res, 200, body, file[1]);
755
+ }
756
+ send(res, 404, { error: 'Not found' });
757
+ } catch (err) {
758
+ send(res, 500, { error: err.message });
759
+ }
760
+ });
761
+
762
+ // Whether a Tabherd server answers at that address.
763
+ async function isDashboard(url) {
764
+ try {
765
+ const res = await fetch(`${url}/`, { signal: AbortSignal.timeout(2000) });
766
+ return res.ok && (await res.text()).includes('<title>Tabherd</title>');
767
+ } catch {
768
+ return false;
769
+ }
770
+ }
771
+
772
+ async function main() {
773
+ if (process.argv.includes('--once')) {
774
+ const snap = await snapshot();
775
+ for (const a of snap.agents) {
776
+ const doing = a.tools?.length ? `${a.tools[0].name}: ${a.tools[0].detail}` : a.waitingFor || '';
777
+ console.log(`${String(a.pid ?? '-').padEnd(7)} ${a.app.padEnd(7)} ${a.status.padEnd(8)} ${a.name.padEnd(28)} ${doing}`);
778
+ }
779
+ console.log(`${snap.agents.length} running session(s)`);
780
+ return;
781
+ }
782
+ const url = `http://localhost:${PORT}`;
783
+ server.on('error', async (err) => {
784
+ if (err.code === 'EADDRINUSE') {
785
+ // With --open, a dashboard server that's already running is opened
786
+ // instead, so the `tabherd` command works either way.
787
+ if (process.argv.includes('--open') && (await isDashboard(url))) {
788
+ openDashboard(url);
789
+ console.log(`Tabherd is already running: ${url}`);
790
+ process.exit(0);
791
+ }
792
+ console.error(`Port ${PORT} is in use. Is the dashboard already open? Set PORT to use another one.`);
793
+ process.exit(1);
794
+ }
795
+ throw err;
796
+ });
797
+ server.listen(PORT, HOST, () => {
798
+ console.log(`Tabherd dashboard: ${url} (Ctrl+C to stop)`);
799
+ if (process.argv.includes('--open')) openDashboard(url);
800
+ // Fills in sessions that closed while the server wasn't running. After the
801
+ // first snapshot, so sessions that are still running aren't read.
802
+ currentSnapshot()
803
+ .then(() => history.backfill())
804
+ .catch(() => {});
805
+ // Only once Settings says yes, and then once a day.
806
+ checkForUpdates().catch(() => {});
807
+ setInterval(() => checkForUpdates().catch(() => {}), 60 * 60 * 1000).unref();
808
+ if (process.argv.includes('--exit-when-idle')) {
809
+ setInterval(() => !streams.size && Date.now() - lastRequestAt > IDLE_EXIT_MS && process.exit(0), 30000).unref();
810
+ }
811
+ });
812
+ }
813
+
814
+ main();