@gorlitzer-labs/seldon 0.17.1 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -76
- package/bin/seldon.js +152 -36
- package/lib/telegram.mjs +5 -6
- package/lib/workspace.mjs +175 -0
- package/package.json +1 -1
- package/lib/serve.mjs +0 -241
- package/lib/web/index.html +0 -351
package/README.md
CHANGED
|
@@ -9,64 +9,73 @@
|
|
|
9
9
|
╚══════╝╚══════╝╚══════╝╚═════╝ ╚═════╝ ╚═╝ ╚═══╝
|
|
10
10
|
```
|
|
11
11
|
|
|
12
|
-
**
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
`seldon` is the panel. `seldon install` adds the optional add-ons (rooms, voice, secrets, the
|
|
16
|
-
plan), each via its native method (npm for the Node tools, a shell installer for bifrost, a
|
|
17
|
-
venv for demerzel).
|
|
12
|
+
**Every coding agent you run — Claude Code, Codex, opencode — on every project, every machine,
|
|
13
|
+
one screen.** See who needs you. Jump there. Answer. Move on.
|
|
18
14
|
|
|
19
15
|
## Install
|
|
20
16
|
|
|
21
17
|
```bash
|
|
22
|
-
pnpm add -g @gorlitzer-labs/seldon # or
|
|
18
|
+
pnpm add -g @gorlitzer-labs/seldon # or bun / npm
|
|
19
|
+
seldon ws # the workspace
|
|
23
20
|
seldon # the panel
|
|
24
|
-
seldon install #
|
|
21
|
+
seldon install # add-ons: ↑↓ move · space pick · enter
|
|
25
22
|
```
|
|
26
23
|
|
|
27
|
-
|
|
24
|
+
## The workspace — `seldon ws`
|
|
28
25
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
26
|
+
Every agent, on every machine, beside the one you're talking to. One key to switch.
|
|
27
|
+
|
|
28
|
+
```text
|
|
29
|
+
SELDON ⚑ 2 ● 3 │ ── fix-save-crash ──────────────────────────
|
|
30
|
+
│ ❯ fix the save crash on resume
|
|
31
|
+
stranded │ Read src/save/slot.ts
|
|
32
|
+
❯1 ⚑ 🦊 fix-save-crash │ Allow this command? ./gradlew test
|
|
33
|
+
needs you · permission │ 1 Yes 2 Always 3 No
|
|
34
|
+
2 ● 🐙 smoke-harness │
|
|
35
|
+
working · 40m · codex │
|
|
36
|
+
weather │
|
|
37
|
+
3 ⚑ 🦉 add-cache │
|
|
38
|
+
needs you · @mini │
|
|
39
|
+
4 ○ 🐢 docs-pass │
|
|
40
|
+
SELDON Alt-1…9 agent · Alt-n next ⚑ · Alt-s list · Alt-h home · Alt-q leave
|
|
33
41
|
```
|
|
34
42
|
|
|
43
|
+
| key | does |
|
|
44
|
+
|---|---|
|
|
45
|
+
| `Alt-1`…`9` | open that agent |
|
|
46
|
+
| `Alt-n` | next agent that needs you |
|
|
47
|
+
| `Alt-s` | the list (on a phone it's behind this key) |
|
|
48
|
+
| `Alt-h` | home: the full panel on the right |
|
|
49
|
+
| `Alt-q` | leave. Agents keep running |
|
|
50
|
+
|
|
51
|
+
- **Real terminals.** The right side is the agent itself, not a copy.
|
|
52
|
+
- **Switching never stops anything.** Leave, reconnect from anywhere, it's all still there.
|
|
53
|
+
- **Both laptops, one list.** Agents on `seldon machines` open over ssh in the same pane. A sleeping one shows ☾ and waits.
|
|
54
|
+
- **Phone.** `ssh` in, run `seldon ws`. Under 90 columns one pane fills the screen.
|
|
55
|
+
- **Emoji per agent.** Same name, same face, everywhere.
|
|
56
|
+
- **No Alt key?** `Ctrl-g` then the key. macOS: turn on *Option as Meta*.
|
|
57
|
+
- **Your tmux is untouched.** It runs on its own server. `seldon ws stop` closes it.
|
|
58
|
+
|
|
35
59
|
## The panel — `seldon`
|
|
36
60
|
|
|
37
61
|
```text
|
|
38
|
-
SELDON 1 need you · 2 working · 1 idle ● watcher
|
|
62
|
+
SELDON 1 need you · 2 working · 1 idle ● watcher
|
|
39
63
|
|
|
40
64
|
❯ stranded plan 5 · 2 done
|
|
41
|
-
⚑ fix-save-crash claude needs you: permission prompt
|
|
42
|
-
● smoke-harness codex working
|
|
43
|
-
weather plan 2 · 0 done
|
|
44
|
-
● add-cache claude working 12m
|
|
45
|
-
○ docs-pass claude idle 1h
|
|
46
|
-
|
|
47
|
-
↑↓ move · ⏎ open · x stop · R resume · n new lane · p plan · r refresh · q quit
|
|
48
|
-
U start stack · D stop stack · i install
|
|
65
|
+
⚑ fix-save-crash claude needs you: permission prompt 2m
|
|
66
|
+
● smoke-harness codex working 40m
|
|
49
67
|
```
|
|
50
68
|
|
|
51
|
-
Every coding agent on this machine — Claude Code, Codex, opencode — grouped by project (a
|
|
52
|
-
worktree counts for its main repo), most urgent first, refreshed every two seconds. `⏎` on an
|
|
53
|
-
agent opens it; `⏎` on a project runs `go`. Claude agents report their own state via
|
|
54
|
-
`claude agents --json`; Codex and opencode do after `seldon setup` (until then they read
|
|
55
|
-
*running*). Without a terminal
|
|
56
|
-
(a script, a hook, an agent's shell) the same rows are printed as plain text.
|
|
57
|
-
|
|
58
69
|
| key | does |
|
|
59
70
|
|---|---|
|
|
60
|
-
| `n` | new lane:
|
|
61
|
-
| `p` | the
|
|
62
|
-
| `⏎` |
|
|
63
|
-
| `x` `x` | stop
|
|
64
|
-
| `R` | resume what a reboot stopped
|
|
71
|
+
| `n` | new lane: task, then `1` claude · `2` codex · `3` opencode |
|
|
72
|
+
| `p` | the plan (`docs/QUEUE.md`); `⏎` starts a lane on an item |
|
|
73
|
+
| `⏎` | open the agent |
|
|
74
|
+
| `x` `x` | stop it |
|
|
75
|
+
| `R` | resume what a reboot stopped |
|
|
65
76
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
lanes run in tmux (`seldon_<slug>`), in a worktree under `~/.seldon/worktrees/`, and are
|
|
69
|
-
recorded in `~/.seldon/lanes.json`. A plan item shows the lane working on it.
|
|
77
|
+
Each lane gets its own branch and worktree. Claude lanes run under Claude's supervisor
|
|
78
|
+
(`claude --bg -w`); Codex and opencode run in tmux (`seldon_<slug>`).
|
|
70
79
|
|
|
71
80
|
## Lanes from the command line
|
|
72
81
|
|
|
@@ -131,42 +140,7 @@ seldon machines # each one, and whether it an
|
|
|
131
140
|
- **How it reaches them:** the panel runs `ssh <machine> seldon lanes --json` in the background
|
|
132
141
|
every 10 seconds, so a sleeping machine never freezes it, and it acts with
|
|
133
142
|
`ssh <machine> seldon lane <verb> <key>`.
|
|
134
|
-
- **From a phone:** `ssh` to any one machine and run `seldon`.
|
|
135
|
-
one line per lane.
|
|
136
|
-
|
|
137
|
-
## On your phone — `seldon serve`
|
|
138
|
-
|
|
139
|
-
The panel as a web app, for a phone (or any browser). Same lanes, same actions, a touch screen
|
|
140
|
-
instead of a terminal: what needs you first, the agent's screen, quick replies, stop / resume /
|
|
141
|
-
remove, new lanes and the plan, for this machine and every machine in `seldon machines`.
|
|
142
|
-
|
|
143
|
-
```bash
|
|
144
|
-
seldon serve # http://localhost:7930/#t=<token> on this machine only
|
|
145
|
-
seldon serve --tailnet # + HTTPS on your tailnet, for your tailscale login only
|
|
146
|
-
seldon serve --tailnet --owner you@example.com # a different login than this machine's
|
|
147
|
-
seldon serve --allow-reply # let the phone type into agents (off by default)
|
|
148
|
-
```
|
|
149
|
-
|
|
150
|
-
- **Nothing is open by default.** It listens on loopback only. `--tailnet` puts it behind
|
|
151
|
-
`tailscale serve` (HTTPS, tailnet-only, never the internet, on its own port 8443 so it never
|
|
152
|
-
takes `/` from the voice) and lets in exactly one login: `--owner`, or this machine's
|
|
153
|
-
tailscale user. If it can't tell whose it is, it does not go on the tailnet. Undo with
|
|
154
|
-
`tailscale serve --https=8443 off`.
|
|
155
|
-
- **A token on every call.** The first run makes one in `~/.seldon/serve-token` (0600). Every
|
|
156
|
-
API call, reads included, needs it; the phone gets it once from the link `serve` prints,
|
|
157
|
-
keeps it, and takes it out of the address bar. `rm ~/.seldon/serve-token` for a new one —
|
|
158
|
-
every device has to open the new link.
|
|
159
|
-
- **A leftover tailnet mapping reaches nothing.** Started without `--tailnet`, it refuses every
|
|
160
|
-
request that comes in by a `*.ts.net` name.
|
|
161
|
-
- **Replies are off unless `--allow-reply`,** and are a whitelist of keys or literal text. A
|
|
162
|
-
menu key ("1") is sent without Enter.
|
|
163
|
-
- **What it can read:** lanes in tmux (Codex, opencode, and Claude lanes seldon started) show
|
|
164
|
-
their screen and take replies. An interactive Claude session in a plain terminal has no pane
|
|
165
|
-
to read: open it with `claude attach`, or from the Claude app with Remote Control.
|
|
166
|
-
- **It acts with this machine's ssh keys:** a lane on another machine is stopped or started by
|
|
167
|
-
`ssh <machine> seldon lane …`, so whoever gets in reaches those machines' lanes too.
|
|
168
|
-
- **Alerts:** while the page is open, the phone buzzes and notifies when an agent starts
|
|
169
|
-
needing you.
|
|
143
|
+
- **From a phone:** `ssh` to any one machine and run `seldon ws`.
|
|
170
144
|
|
|
171
145
|
## On Telegram — `seldon tell`
|
|
172
146
|
|
|
@@ -190,8 +164,7 @@ piped log over a few lines folds away — tap it to open.
|
|
|
190
164
|
|
|
191
165
|
Every message is a card that reads at a glance: a coloured dot for what kind of news it is,
|
|
192
166
|
then where it comes from (the repo, branch and machine it was sent from), then what happened.
|
|
193
|
-
The watcher's cards also name the agent, what it is waiting for
|
|
194
|
-
to the phone app when `seldon serve --tailnet` is on.
|
|
167
|
+
The watcher's cards also name the agent, what it is waiting for and how long it has run.
|
|
195
168
|
|
|
196
169
|
Images show inline, videos play, GIFs animate, audio plays, anything else is a document; a
|
|
197
170
|
bot can send up to 50 MB per file.
|
package/bin/seldon.js
CHANGED
|
@@ -14,10 +14,10 @@ import { openCommand, stopCommand, transitions, laneForItem, slugify, HARNESSES
|
|
|
14
14
|
import { startLane, stopLane, resumeLane, removeLane, findLane } from "../lib/actions.mjs";
|
|
15
15
|
import { listMachines, addMachine, fetchLanes, remoteGroups, sshArgs, lastJsonLine } from "../lib/machines.mjs";
|
|
16
16
|
import { notify } from "../lib/notify.mjs";
|
|
17
|
-
import { serve, serveToken, ownerFromStatus } from "../lib/serve.mjs";
|
|
18
17
|
import { sendCard, watchCard, KINDS, tokenName, readChat, writeChat, chatFromUpdates, getUpdates, sendText, sendFile, pollUpdates, fileFromMessage, inboxName, freeName, noteLine, downloadFile, react, MAX_DOWNLOAD } from "../lib/telegram.mjs";
|
|
19
18
|
import { reportFromEvent, mergeCodexHooks, removeCodexHooks, opencodePlugin } from "../lib/reports.mjs";
|
|
20
19
|
import { buildRows, headline, ago, laneDetail, unlistedAgents, GLYPH } from "../lib/home.mjs";
|
|
20
|
+
import { WS_SOCKET, WS_SESSION, NARROW, SIDE_WIDTH, assignEmoji, wsRows, nextNeeding, findRow, paneCommand, setupCommands, rowCells, wsHeadline } from "../lib/workspace.mjs";
|
|
21
21
|
import { parseDuration, describe as describeHold, NAME_RE, DEFAULT_FOR_MS } from "../lib/holds.mjs";
|
|
22
22
|
import { tryHold, release as releaseHold, listHolds, findOwner } from "../lib/holds-store.mjs";
|
|
23
23
|
|
|
@@ -1428,13 +1428,13 @@ function help() {
|
|
|
1428
1428
|
${C.bold("seldon")} — the agent factory: your projects, and the stack that runs them.
|
|
1429
1429
|
|
|
1430
1430
|
${C.bold("seldon")} ${C.gold("the panel")} — every agent (claude · codex · opencode) by project; n new lane, p plan
|
|
1431
|
+
${C.bold("seldon ws")} ${C.gold("the workspace")} — the agent list beside the agent's own terminal; Alt-1…9 switches
|
|
1431
1432
|
${C.bold("seldon hold")} <thing> take a turn on a shared resource (emulator, unreal, gpu); waits if someone has it
|
|
1432
1433
|
${C.bold("seldon release")} <thing> give it back · ${C.bold("seldon holds")} who holds what
|
|
1433
1434
|
${C.bold("seldon go")} [name|dir] ${C.gold("get back to work")} — adopt if needed, reopen the room, staff an agent, attach.
|
|
1434
1435
|
Idempotent, and it prints every step it skipped. Run it from inside a repo.
|
|
1435
1436
|
${C.bold("seldon up")} start the stack (voice + supervisor) and print where to go
|
|
1436
1437
|
${C.bold("seldon up --tailnet")} expose the voice over HTTPS (tailscale serve) so the mic works on your phone
|
|
1437
|
-
${C.bold("seldon serve")} [--tailnet] the panel as a phone web app (--allow-reply to answer agents)
|
|
1438
1438
|
${C.bold("seldon tell")} "…" message yourself on Telegram (--file to send one; --setup once)
|
|
1439
1439
|
${C.bold("seldon inbox")} [--dir d] save what you send the bot to a folder here (no agent, no tokens)
|
|
1440
1440
|
${C.bold("seldon up --brain=X")} pick the voice brain: qwen (in-process) | bonsai (local server); remembered
|
|
@@ -1476,22 +1476,12 @@ function tellInBackground(fields) {
|
|
|
1476
1476
|
child.on("error", () => {}); child.unref();
|
|
1477
1477
|
}
|
|
1478
1478
|
|
|
1479
|
-
function phoneAppUrl() {
|
|
1480
|
-
const ts = tailscaleBin(); if (!ts) return null;
|
|
1481
|
-
try {
|
|
1482
|
-
const out = execSync(`${ts} serve status`, { stdio: ["ignore", "pipe", "ignore"], timeout: 10000 }).toString();
|
|
1483
|
-
const m = out.match(new RegExp(`https://\\S+:${SERVE_TAILNET_PORT}`));
|
|
1484
|
-
return m ? m[0] + "/" : null;
|
|
1485
|
-
} catch { return null; }
|
|
1486
|
-
}
|
|
1487
|
-
|
|
1488
1479
|
async function watchCmd(flags) {
|
|
1489
1480
|
ensureSiblingPath();
|
|
1490
1481
|
const every = parseDuration(flags.interval, 5000) || 5000;
|
|
1491
1482
|
let prev = new Map();
|
|
1492
1483
|
const stamp = () => new Date().toTimeString().slice(0, 8);
|
|
1493
1484
|
console.log(`${stamp()} seldon watch — every ${every / 1000}s`);
|
|
1494
|
-
const phone = phoneAppUrl(); // once: the link the phone cards carry
|
|
1495
1485
|
for (;;) {
|
|
1496
1486
|
let lanes = [];
|
|
1497
1487
|
try { lanes = readLanes().flatMap((g) => g.lanes); } catch (e) { console.log(`${stamp()} read failed: ${e.message}`); }
|
|
@@ -1499,7 +1489,7 @@ async function watchCmd(flags) {
|
|
|
1499
1489
|
console.log(`${stamp()} ${e.text}`);
|
|
1500
1490
|
const where = path.basename(e.lane.project || e.lane.cwd || "");
|
|
1501
1491
|
notify(e.to === "needs-you" ? "Seldon · needs you" : "Seldon", `${e.text} — ${where}`);
|
|
1502
|
-
tellInBackground(watchCard(e, { machine: os.hostname().split(".")[0]
|
|
1492
|
+
tellInBackground(watchCard(e, { machine: os.hostname().split(".")[0] }));
|
|
1503
1493
|
}
|
|
1504
1494
|
prev = new Map(lanes.map((l) => [l.key, l.state]));
|
|
1505
1495
|
if (flags.once) return;
|
|
@@ -1553,29 +1543,150 @@ function laneCmd(verb, arg, flags) {
|
|
|
1553
1543
|
console.log(C.green(`✓ ${verb === "stop" ? "stopped" : "resumed"} ${lane.name}`) + (r.fresh ? C.dim(" (new conversation, same task + worktree)") : ""));
|
|
1554
1544
|
}
|
|
1555
1545
|
|
|
1556
|
-
//
|
|
1557
|
-
//
|
|
1558
|
-
//
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1546
|
+
// ---- the workspace: `seldon ws` -------------------------------------------------------
|
|
1547
|
+
// The agent list on the left, the selected agent's own terminal on the right, one key to
|
|
1548
|
+
// switch (lib/workspace.mjs has the rules; this is the tmux and the drawing). It runs on its
|
|
1549
|
+
// own tmux server, so nothing here touches the user's tmux or its config.
|
|
1550
|
+
const WS_ROWS = path.join(SELDON_HOME, "ws.json"); // the list, as the sidebar last drew it
|
|
1551
|
+
const WS_CURRENT = path.join(SELDON_HOME, "ws-current"); // the key of the agent on the right
|
|
1552
|
+
const shq = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
1553
|
+
const wsSelf = () => `${shq(process.execPath)} ${shq(fs.realpathSync(process.argv[1]))}`;
|
|
1554
|
+
// The right-hand pane with no agent open is the full panel; when it exits, it comes back.
|
|
1555
|
+
const wsHome = () => `sh -c ${shq(`while :; do ${wsSelf()}; sleep 0.3; done`)}`;
|
|
1556
|
+
const wsTmux = (args, opts = {}) => spawnSync("tmux", ["-L", WS_SOCKET, "-f", "/dev/null", ...args], { encoding: "utf8", ...opts });
|
|
1557
|
+
const wsOpt = (name) => (wsTmux(["show-options", "-v", "-t", WS_SESSION, name]).stdout || "").trim();
|
|
1558
|
+
const wsReadRows = () => { try { return JSON.parse(fs.readFileSync(WS_ROWS, "utf8")); } catch { return []; } };
|
|
1559
|
+
const wsCurrent = () => { try { return fs.readFileSync(WS_CURRENT, "utf8").trim() || null; } catch { return null; } };
|
|
1560
|
+
function wsSave(file, text) {
|
|
1561
|
+
fs.mkdirSync(SELDON_HOME, { recursive: true });
|
|
1562
|
+
const tmp = `${file}.${process.pid}`;
|
|
1563
|
+
fs.writeFileSync(tmp, text); fs.renameSync(tmp, file); // a reader never sees half a file
|
|
1564
|
+
}
|
|
1565
|
+
// Show `pane`. On a small screen it fills it; on a wide one both panes show.
|
|
1566
|
+
function wsFocus(pane, width = null) {
|
|
1567
|
+
const [w0, zoomed] = (wsTmux(["display-message", "-p", "-t", `${WS_SESSION}:0`, "#{window_width} #{window_zoomed_flag}"]).stdout || "").trim().split(" ");
|
|
1568
|
+
const narrow = (width ?? Number(w0)) < NARROW; // `width`: the screen about to attach
|
|
1569
|
+
if (!pane && narrow && !wsCurrent()) pane = wsOpt("@side"); // a phone with no agent open starts on the list
|
|
1570
|
+
if (pane) wsTmux(["select-pane", ...(narrow ? ["-Z"] : []), "-t", pane]);
|
|
1571
|
+
if (narrow !== (zoomed === "1")) wsTmux(["resize-pane", "-Z", "-t", `${WS_SESSION}:0`]);
|
|
1572
|
+
if (!narrow) wsTmux(["resize-pane", "-t", wsOpt("@side"), "-x", String(SIDE_WIDTH)]); // a resize stretches it otherwise
|
|
1573
|
+
}
|
|
1574
|
+
function wsOpen(row) {
|
|
1575
|
+
const main = wsOpt("@main");
|
|
1576
|
+
wsTmux(["respawn-pane", "-k", "-t", main, row.cmd]);
|
|
1577
|
+
wsSave(WS_CURRENT, row.off ? "" : row.key);
|
|
1578
|
+
wsFocus(main);
|
|
1579
|
+
}
|
|
1580
|
+
function wsGoHome() {
|
|
1581
|
+
const main = wsOpt("@main");
|
|
1582
|
+
wsTmux(["respawn-pane", "-k", "-t", main, wsHome()]);
|
|
1583
|
+
wsSave(WS_CURRENT, "");
|
|
1584
|
+
wsFocus(main);
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
// The left-hand pane: the list. It also writes the list to disk, which is how a key pressed
|
|
1588
|
+
// anywhere in the workspace (`seldon ws pick 3`, run by tmux) knows what "3" is.
|
|
1589
|
+
async function wsSidebar() {
|
|
1590
|
+
ensureSiblingPath();
|
|
1591
|
+
const machines = listMachines();
|
|
1592
|
+
const seen = new Map();
|
|
1593
|
+
const poll = () => {
|
|
1594
|
+
for (const m of machines) {
|
|
1595
|
+
const was = seen.get(m.name) || {};
|
|
1596
|
+
if (was.inflight || (was.at && Date.now() - was.at < 10_000)) continue;
|
|
1597
|
+
seen.set(m.name, { ...was, inflight: true });
|
|
1598
|
+
fetchLanes(m, (r) => { seen.set(m.name, { groups: r.lanes ? remoteGroups(m, r.lanes) : was.groups || [], error: r.error || null, at: Date.now(), inflight: false }); });
|
|
1599
|
+
}
|
|
1600
|
+
};
|
|
1601
|
+
let rows = [], cur = 0, note = "";
|
|
1602
|
+
const home = wsHome();
|
|
1603
|
+
const load = () => {
|
|
1604
|
+
poll();
|
|
1605
|
+
let groups = [];
|
|
1606
|
+
try { groups = [...readLanes(), ...[...seen.values()].flatMap((v) => v.groups || [])]; } catch (e) { note = C.red(e.message); }
|
|
1607
|
+
const down = new Set([...seen].filter(([, v]) => v.error).map(([name]) => name));
|
|
1608
|
+
const prev = rows[cur]?.key;
|
|
1609
|
+
rows = wsRows(groups, down);
|
|
1610
|
+
const keep = rows.findIndex((r) => r.key === prev);
|
|
1611
|
+
cur = keep >= 0 ? keep : Math.min(cur, Math.max(0, rows.length - 1));
|
|
1612
|
+
wsSave(WS_ROWS, JSON.stringify(rows.map((r) => ({ n: r.n, key: r.key, name: r.name, state: r.state, off: r.off, cmd: paneCommand(r, { machines, home }) }))));
|
|
1613
|
+
};
|
|
1614
|
+
const tint = { "needs-you": C.gold, working: C.green, running: C.green, idle: C.dim, failed: C.red, stopped: C.dim, off: C.dim };
|
|
1615
|
+
const draw = () => {
|
|
1616
|
+
const width = process.stdout.columns || 38, height = process.stdout.rows || 40;
|
|
1617
|
+
const open = wsCurrent(), h = wsHeadline(rows);
|
|
1618
|
+
const head = [` ${C.bold("SELDON")} ${h.need ? C.gold(`⚑ ${h.need}`) : C.dim("⚑ 0")} ${C.green(`● ${h.busy}`)}`, ""];
|
|
1619
|
+
const foot = ["", C.dim(" ⏎ open · n next ⚑ · h home"), C.dim(" Alt-1…9 from any pane · q leave"), ...(note ? [" " + note] : [])];
|
|
1620
|
+
const body = []; let curLine = 0, last = null;
|
|
1621
|
+
if (!rows.length) body.push(C.dim(" no agents running"), C.dim(" h, then n starts one"));
|
|
1622
|
+
const faces = assignEmoji(rows.map((r) => r.name));
|
|
1623
|
+
rows.forEach((r, i) => {
|
|
1624
|
+
if (r.project !== last) { if (last !== null) body.push(""); body.push(" " + C.dim(r.project.slice(0, width - 2))); last = r.project; }
|
|
1625
|
+
const c = rowCells(r, width, ago, faces.get(r.name)), color = tint[c.state] || ((x) => x);
|
|
1626
|
+
const mark = i === cur ? C.gold("❯") : r.key === open ? C.cyan("▸") : " ";
|
|
1627
|
+
if (i === cur) curLine = body.length;
|
|
1628
|
+
body.push(`${mark}${C.dim(c.n)} ${color(c.glyph)} ${c.emoji} ${i === cur ? C.bold(c.name) : c.name}`);
|
|
1629
|
+
body.push(` ${color(c.sub)}`);
|
|
1630
|
+
});
|
|
1631
|
+
const room = Math.max(2, height - head.length - foot.length);
|
|
1632
|
+
const from = Math.max(0, Math.min(curLine - Math.floor(room / 2), body.length - room));
|
|
1633
|
+
clearScreen();
|
|
1634
|
+
process.stdout.write([...head, ...body.slice(from, from + room), ...foot].join("\n"));
|
|
1635
|
+
};
|
|
1636
|
+
const openRow = (r) => { if (r) { wsOpen(wsReadRows().find((x) => x.key === r.key) || r); note = ""; } };
|
|
1637
|
+
load();
|
|
1638
|
+
setInterval(() => { load(); draw(); }, 2000);
|
|
1639
|
+
process.stdout.on("resize", draw);
|
|
1640
|
+
await rawSession({
|
|
1641
|
+
draw,
|
|
1642
|
+
onError: (e) => { note = C.red(e.message); },
|
|
1643
|
+
onKey: (str, key, api) => {
|
|
1644
|
+
if (key?.name === "up" || str === "k") cur = Math.max(0, cur - 1);
|
|
1645
|
+
else if (key?.name === "down" || str === "j") cur = Math.min(rows.length - 1, cur + 1);
|
|
1646
|
+
else if (key?.name === "return") openRow(rows[cur]);
|
|
1647
|
+
else if (/^[1-9]$/.test(str || "")) openRow(findRow(rows, str));
|
|
1648
|
+
else if (str === "n") { const r = nextNeeding(rows, wsCurrent()); if (r) openRow(r); else note = C.dim("nobody is waiting on you"); }
|
|
1649
|
+
else if (str === "h") wsGoHome();
|
|
1650
|
+
else if (str === "r") load();
|
|
1651
|
+
else if (str === "q" || (key?.ctrl && key.name === "c")) wsTmux(["detach-client"]);
|
|
1652
|
+
api.draw();
|
|
1653
|
+
},
|
|
1654
|
+
});
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
function wsCmd(sub, arg) {
|
|
1658
|
+
const fail = (msg) => { console.log(C.red(msg)); process.exitCode = 1; };
|
|
1659
|
+
if (!has("tmux")) return fail("the workspace needs tmux — install it (brew install tmux / apt install tmux), then: seldon ws");
|
|
1660
|
+
if (sub === "sidebar") return wsSidebar();
|
|
1661
|
+
if (sub === "fit") return wsFocus(null);
|
|
1662
|
+
if (sub === "list") return wsFocus(wsOpt("@side"));
|
|
1663
|
+
if (sub === "home") return wsGoHome();
|
|
1664
|
+
if (sub === "pick" || sub === "next") {
|
|
1665
|
+
const rows = wsReadRows();
|
|
1666
|
+
const row = sub === "pick" ? findRow(rows, arg) : nextNeeding(rows, wsCurrent());
|
|
1667
|
+
if (row) wsOpen(row);
|
|
1668
|
+
else wsTmux(["display-message", sub === "pick" ? `no agent ${arg ?? ""}` : "nobody is waiting on you"]);
|
|
1669
|
+
return;
|
|
1570
1670
|
}
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1671
|
+
if (sub === "stop") {
|
|
1672
|
+
wsTmux(["kill-server"]);
|
|
1673
|
+
return console.log(C.green("✓ workspace closed") + C.dim(" — your agents keep running"));
|
|
1674
|
+
}
|
|
1675
|
+
if (sub) return fail("usage: seldon ws (open the workspace) · seldon ws stop (close it; agents keep running)");
|
|
1676
|
+
if (process.env.SELDON_WS) return console.log(C.dim("you are already in the workspace — Alt-s for the list, Alt-q to leave"));
|
|
1677
|
+
if (wsTmux(["has-session", "-t", WS_SESSION]).status !== 0) {
|
|
1678
|
+
const cmds = setupCommands({ self: wsSelf(), home: wsHome(), cols: process.stdout.columns || 200, rows: process.stdout.rows || 50 });
|
|
1679
|
+
const made = wsTmux(cmds.flatMap((c, i) => (i ? [";", ...c] : c)));
|
|
1680
|
+
if (made.status !== 0) return fail(`could not start the workspace: ${(made.stderr || "").trim() || "tmux failed"} (it needs tmux 3.2 or newer)`);
|
|
1681
|
+
const panes = (wsTmux(["list-panes", "-t", `${WS_SESSION}:0`, "-F", "#{pane_left} #{pane_id}"]).stdout || "").trim().split("\n")
|
|
1682
|
+
.map((l) => l.split(" ")).sort((a, b) => Number(a[0]) - Number(b[0]));
|
|
1683
|
+
wsTmux(["set-option", "-t", WS_SESSION, "@side", panes[0][1]]);
|
|
1684
|
+
wsTmux(["set-option", "-t", WS_SESSION, "@main", panes[panes.length - 1][1]]);
|
|
1685
|
+
wsSave(WS_CURRENT, "");
|
|
1686
|
+
}
|
|
1687
|
+
wsFocus(null, process.stdout.columns || null); // fit this screen before it shows
|
|
1688
|
+
const env = { ...process.env }; delete env.TMUX;
|
|
1689
|
+
process.exitCode = spawnSync("tmux", ["-L", WS_SOCKET, "attach", "-t", WS_SESSION], { stdio: "inherit", env }).status ?? 1;
|
|
1579
1690
|
}
|
|
1580
1691
|
|
|
1581
1692
|
// `seldon tell "…"` — message the operator on Telegram, from any agent. The token comes from
|
|
@@ -1838,6 +1949,11 @@ function parseArgv(raw) {
|
|
|
1838
1949
|
return { flags, positional };
|
|
1839
1950
|
}
|
|
1840
1951
|
|
|
1952
|
+
// Inside the workspace $TMUX points at the workspace's own tmux server. Lanes live on the
|
|
1953
|
+
// default one, so every tmux call seldon makes from here (listing panes, attaching) must not
|
|
1954
|
+
// follow it; the workspace's own calls name their server explicitly.
|
|
1955
|
+
if (process.env.SELDON_WS) delete process.env.TMUX;
|
|
1956
|
+
|
|
1841
1957
|
const rawArgv = process.argv.slice(2);
|
|
1842
1958
|
// Everything after a bare `--` is a command to run (`seldon hold emulator -- ./gradlew test`),
|
|
1843
1959
|
// never seldon's own flags.
|
|
@@ -1877,7 +1993,7 @@ const ids = tokens.filter((id) => byId[id]); // only the valid module
|
|
|
1877
1993
|
if (cmd === "lanes") return lanesCmd(flags);
|
|
1878
1994
|
if (cmd === "machines") return machinesCmd(tokens[0], tokens[1], tokens[2]);
|
|
1879
1995
|
if (cmd === "lane") return laneCmd(tokens[0], tokens[1], flags);
|
|
1880
|
-
if (cmd === "
|
|
1996
|
+
if (cmd === "ws" || cmd === "workspace") return wsCmd(tokens[0], tokens[1]);
|
|
1881
1997
|
if (cmd === "tell") return tellCmd(tokens, flags);
|
|
1882
1998
|
if (cmd === "inbox") return inboxCmd(flags);
|
|
1883
1999
|
if (cmd === "setup") return setupCmd(tokens[0], flags);
|
package/lib/telegram.mjs
CHANGED
|
@@ -144,7 +144,7 @@ export const htmlToPlain = (html) => String(html)
|
|
|
144
144
|
|
|
145
145
|
// Every part is optional but the kind. `log` is shown as code (its tail: the end of a log is
|
|
146
146
|
// what matters). `max` keeps the whole card under Telegram's limit — 1024 for a caption.
|
|
147
|
-
export function card({ kind = "info", text, log, project, branch, lane, harness, detail, age, machine,
|
|
147
|
+
export function card({ kind = "info", text, log, project, branch, lane, harness, detail, age, machine, max = MAX } = {}) {
|
|
148
148
|
const k = KINDS[kind] || KINDS.info;
|
|
149
149
|
const e = escHtml;
|
|
150
150
|
const meta = [age && `⏱ ${e(age)}`, machine && `💻 ${e(machine)}`].filter(Boolean).join(" · ");
|
|
@@ -153,7 +153,7 @@ export function card({ kind = "info", text, log, project, branch, lane, harness,
|
|
|
153
153
|
lane && `▸ <b>${e(lane)}</b>${harness ? ` · ${e(harness)}` : ""}`,
|
|
154
154
|
detail && `⏳ ${e(detail)}`,
|
|
155
155
|
].filter(Boolean);
|
|
156
|
-
const bottom = [meta && `<i>${meta}</i
|
|
156
|
+
const bottom = [meta && `<i>${meta}</i>`].filter(Boolean);
|
|
157
157
|
// The free text gets whatever room the frame leaves (escaping can grow it, hence the margin).
|
|
158
158
|
const room = Math.max(0, max - [...top, ...bottom].join("\n").length - 60);
|
|
159
159
|
const words = text && mdToHtml(clip(String(text).trim(), Math.floor(room * (log ? 0.4 : 1) / 1.2)));
|
|
@@ -236,18 +236,17 @@ export async function downloadFile(token, fileId, dest) {
|
|
|
236
236
|
export const react = (token, chatId, messageId, emoji) =>
|
|
237
237
|
call(token, "setMessageReaction", { chat_id: chatId, message_id: messageId, reaction: [{ type: "emoji", emoji }] }).catch(() => {});
|
|
238
238
|
|
|
239
|
-
// The watcher's news as a card: which agent, on what, what it is waiting for, for how long
|
|
240
|
-
// and — when the phone app is on the tailnet — a link straight to it.
|
|
239
|
+
// The watcher's news as a card: which agent, on what, what it is waiting for, for how long.
|
|
241
240
|
const WATCH_KIND = { "needs-you": "need", failed: "fail", idle: "done" };
|
|
242
241
|
const WATCH_DETAIL = { failed: "ended with an error", idle: "finished its turn — ready for the next task" };
|
|
243
|
-
export function watchCard(e, { machine = null,
|
|
242
|
+
export function watchCard(e, { machine = null, now = Date.now() } = {}) {
|
|
244
243
|
return {
|
|
245
244
|
kind: WATCH_KIND[e.to] || "info",
|
|
246
245
|
project: basename(e.lane.project || e.lane.cwd || "") || null,
|
|
247
246
|
lane: e.lane.name || e.lane.id, harness: e.lane.harness,
|
|
248
247
|
detail: e.to === "needs-you" ? (e.lane.waitingFor || "waiting for you") : WATCH_DETAIL[e.to] || e.to,
|
|
249
248
|
age: e.lane.startedAt ? `running ${ago(e.lane.startedAt, now)}` : null,
|
|
250
|
-
machine,
|
|
249
|
+
machine,
|
|
251
250
|
};
|
|
252
251
|
}
|
|
253
252
|
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// The workspace: every agent in a list on the left, the selected agent's own terminal on the
|
|
2
|
+
// right, one key to switch. It is a tmux session on its own server (`tmux -L seldon-ws`), so
|
|
3
|
+
// its keys and options never touch the tmux you already use, and an agent that itself lives in
|
|
4
|
+
// tmux is simply attached inside the right-hand pane.
|
|
5
|
+
//
|
|
6
|
+
// Switching never stops an agent: the right-hand pane only holds a client (`claude attach`,
|
|
7
|
+
// `tmux attach`, or ssh to another machine's `seldon lane open`). Replacing the pane ends the
|
|
8
|
+
// client, not the agent.
|
|
9
|
+
//
|
|
10
|
+
// Everything here is pure: bin/seldon.js runs tmux and reads the lanes, and passes them in.
|
|
11
|
+
import { openCommand } from "./lanes.mjs";
|
|
12
|
+
import { sshArgs } from "./machines.mjs";
|
|
13
|
+
|
|
14
|
+
export const WS_SOCKET = "seldon-ws";
|
|
15
|
+
export const WS_SESSION = "ws";
|
|
16
|
+
export const SIDE_WIDTH = 38;
|
|
17
|
+
export const NARROW = 90; // below this many columns one pane fills the screen (a phone)
|
|
18
|
+
|
|
19
|
+
// ---- a face for every agent --------------------------------------------------------
|
|
20
|
+
// The same name always gets the same emoji (apiary does this for its agents), so an agent is
|
|
21
|
+
// recognisable in the list, in its pane title and across machines without reading its name.
|
|
22
|
+
export const AGENT_POOL = [
|
|
23
|
+
"🦊", "🐙", "🦉", "🐢", "🦁", "🐧", "🦄", "🐳", "🦖", "🐝", "🦋", "🐺", "🦜", "🐸", "🦔", "🐼",
|
|
24
|
+
"🦀", "🐬", "🦩", "🐿️", "🦥", "🦦", "🐨", "🦈", "🐊", "🦚", "🐌", "🦇", "🐗", "🦬", "🦭", "🪼",
|
|
25
|
+
];
|
|
26
|
+
const hash = (s) => { let h = 7; for (const c of String(s)) h = (h * 31 + c.codePointAt(0)) >>> 0; return h; };
|
|
27
|
+
export const emojiFor = (name, pool = AGENT_POOL) => pool[hash(name) % pool.length];
|
|
28
|
+
|
|
29
|
+
// One emoji each for the agents on screen together. Each takes its own (hashed) one; when two
|
|
30
|
+
// would share, the later name alphabetically moves to the next free one, so the answer does
|
|
31
|
+
// not depend on the order the agents are listed in.
|
|
32
|
+
export function assignEmoji(names, pool = AGENT_POOL) {
|
|
33
|
+
const out = new Map(), used = new Set();
|
|
34
|
+
for (const name of [...new Set(names)].sort()) {
|
|
35
|
+
let i = hash(name) % pool.length;
|
|
36
|
+
for (let n = 0; used.has(pool[i]) && n < pool.length; n++) i = (i + 1) % pool.length;
|
|
37
|
+
used.add(pool[i]); out.set(name, pool[i]);
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// ---- the list ----------------------------------------------------------------------
|
|
43
|
+
// One numbered row per agent, in the order the panel shows them (the ones waiting first).
|
|
44
|
+
// `down` is the set of machines that did not answer: their agents stay listed, marked off.
|
|
45
|
+
export function wsRows(groups, down = new Set()) {
|
|
46
|
+
const rows = [];
|
|
47
|
+
for (const g of groups) {
|
|
48
|
+
for (const lane of g.lanes) {
|
|
49
|
+
rows.push({
|
|
50
|
+
n: rows.length + 1,
|
|
51
|
+
key: lane.key,
|
|
52
|
+
name: lane.name || lane.id || lane.key,
|
|
53
|
+
project: g.name,
|
|
54
|
+
harness: lane.harness,
|
|
55
|
+
state: lane.state,
|
|
56
|
+
waitingFor: lane.waitingFor || null,
|
|
57
|
+
startedAt: lane.startedAt || null,
|
|
58
|
+
machine: lane.machine || null,
|
|
59
|
+
off: !!lane.machine && down.has(lane.machine),
|
|
60
|
+
lane,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return rows;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// The next agent waiting on you after `currentKey`, wrapping round. null when nobody is.
|
|
68
|
+
export function nextNeeding(rows, currentKey) {
|
|
69
|
+
const live = rows.filter((r) => !r.off);
|
|
70
|
+
const at = live.findIndex((r) => r.key === currentKey);
|
|
71
|
+
for (let k = 1; k <= live.length; k++) {
|
|
72
|
+
const r = live[(at + k) % live.length];
|
|
73
|
+
if (r.state === "needs-you") return r;
|
|
74
|
+
}
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// A row by its number ("3") or its key.
|
|
79
|
+
export const findRow = (rows, ref) => rows.find((r) => String(r.n) === String(ref) || r.key === ref) || null;
|
|
80
|
+
|
|
81
|
+
// ---- what the right-hand pane runs ---------------------------------------------------
|
|
82
|
+
const sq = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
83
|
+
const shJoin = (argv) => argv.map(sq).join(" ");
|
|
84
|
+
|
|
85
|
+
// The shell line that opens one agent. When its client exits (you detached, the agent ended,
|
|
86
|
+
// the machine dropped) the pane falls back to `home`, the full panel, instead of dying.
|
|
87
|
+
// A failure stays on screen long enough to read.
|
|
88
|
+
export function paneCommand(row, { machines = [], home }) {
|
|
89
|
+
const lane = row.lane;
|
|
90
|
+
let open;
|
|
91
|
+
if (row.off) return `printf '\\n %s is paused: %s is not reachable. It carries on when that machine is back.\\n' ${sq(row.name)} ${sq(row.machine)}; sleep 6; exec ${home}`;
|
|
92
|
+
if (lane.machine) {
|
|
93
|
+
const m = machines.find((x) => x.name === lane.machine);
|
|
94
|
+
if (!m) return `printf '\\n seldon does not know the machine %s\\n' ${sq(lane.machine)}; sleep 6; exec ${home}`;
|
|
95
|
+
open = shJoin(["ssh", ...sshArgs(m, ["seldon", "lane", "open", lane.remoteKey || lane.key], { tty: true })]);
|
|
96
|
+
} else {
|
|
97
|
+
const how = openCommand(lane);
|
|
98
|
+
if (how.why) return `printf '\\n cannot open %s here: %s\\n' ${sq(row.name)} ${sq(how.why)}; sleep 6; exec ${home}`;
|
|
99
|
+
// The lane's tmux lives on the default server; this pane's $TMUX points at the workspace's.
|
|
100
|
+
const argv = how.bin === "tmux" ? ["env", "-u", "TMUX", "tmux", ...how.args] : [how.bin, ...how.args];
|
|
101
|
+
open = (how.cwd ? `cd ${sq(how.cwd)} && ` : "") + shJoin(argv);
|
|
102
|
+
}
|
|
103
|
+
return `${open} || { printf '\\n seldon: %s closed with an error\\n' ${sq(row.name)}; sleep 5; }; exec ${home}`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// ---- the tmux session ----------------------------------------------------------------
|
|
107
|
+
// `self` is the absolute `node seldon.js`, shell-quoted (tmux runs commands with its server's
|
|
108
|
+
// PATH, not yours); `home` is what the right-hand pane shows when no agent is open. Returned
|
|
109
|
+
// as argv lists, in order, for one `tmux -L seldon-ws` call.
|
|
110
|
+
export function setupCommands({ self, home = self, cols = 200, rows = 50 }) {
|
|
111
|
+
const argv = (...a) => ["run-shell", "-b", `${self} ws ${a.join(" ")}`];
|
|
112
|
+
const line = (...a) => `run-shell -b ${sq(`${self} ws ${a.join(" ")}`)}`; // a hook takes one string
|
|
113
|
+
const cmds = [
|
|
114
|
+
["start-server"],
|
|
115
|
+
["set", "-g", "default-terminal", "screen-256color"], ["set", "-as", "terminal-features", ",*:RGB"],
|
|
116
|
+
["set", "-g", "extended-keys", "on"], ["set", "-g", "history-limit", "20000"],
|
|
117
|
+
// No prefix key: every key goes to the agent, except the ones bound below.
|
|
118
|
+
["set", "-g", "prefix", "None"], ["set", "-g", "prefix2", "None"],
|
|
119
|
+
["set", "-g", "mouse", "on"], ["set", "-g", "escape-time", "10"], ["set", "-g", "focus-events", "on"],
|
|
120
|
+
["set", "-g", "status", "on"], ["set", "-g", "status-style", "bg=default,fg=colour244"],
|
|
121
|
+
["set", "-g", "status-left", "#[bold,fg=colour223] SELDON #[default]"], ["set", "-g", "status-left-length", "12"],
|
|
122
|
+
["set", "-g", "status-right", "Alt-1…9 agent · Alt-n next ⚑ · Alt-s list · Alt-h home · Alt-q leave "],
|
|
123
|
+
["set", "-g", "status-right-length", "90"], ["set", "-g", "window-status-format", ""], ["set", "-g", "window-status-current-format", ""],
|
|
124
|
+
["set", "-g", "pane-border-style", "fg=colour238"], ["set", "-g", "pane-active-border-style", "fg=colour238"],
|
|
125
|
+
["set-environment", "-g", "SELDON_WS", "1"],
|
|
126
|
+
// One pane fills a small screen; both show on a wide one. Re-checked whenever a screen attaches or resizes.
|
|
127
|
+
["set-hook", "-g", "client-attached", line("fit")], ["set-hook", "-g", "client-resized", line("fit")],
|
|
128
|
+
// Alt-<key> directly, and Ctrl-g then <key> for terminals that do not send Alt (macOS
|
|
129
|
+
// Terminal and iTerm2 need "Option as Meta" turned on).
|
|
130
|
+
["bind", "-n", "C-g", "switch-client", "-T", "seldon"],
|
|
131
|
+
];
|
|
132
|
+
const keys = { n: ["next"], s: ["list"], h: ["home"] };
|
|
133
|
+
for (let i = 1; i <= 9; i++) keys[i] = ["pick", i];
|
|
134
|
+
for (const [k, a] of Object.entries(keys)) {
|
|
135
|
+
cmds.push(["bind", "-n", `M-${k}`, ...argv(...a)], ["bind", "-T", "seldon", String(k), ...argv(...a)]);
|
|
136
|
+
}
|
|
137
|
+
cmds.push(["bind", "-n", "M-q", "detach-client"], ["bind", "-T", "seldon", "q", "detach-client"]);
|
|
138
|
+
// The session last, so both panes start with every option above already in force.
|
|
139
|
+
cmds.push(
|
|
140
|
+
["new-session", "-d", "-s", WS_SESSION, "-x", String(cols), "-y", String(rows), "-n", "seldon", "-e", "SELDON_WS=1", home],
|
|
141
|
+
["split-window", "-hb", "-t", `${WS_SESSION}:0`, "-l", String(SIDE_WIDTH), "-e", "SELDON_WS=1", `${self} ws sidebar`],
|
|
142
|
+
);
|
|
143
|
+
return cmds;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// ---- drawing the list ------------------------------------------------------------------
|
|
147
|
+
const GLYPH = { "needs-you": "⚑", working: "●", running: "●", idle: "○", failed: "✗", stopped: "·" };
|
|
148
|
+
const WORDS = { "needs-you": "needs you", working: "working", running: "running", idle: "idle", failed: "failed", stopped: "stopped" };
|
|
149
|
+
const cut = (s, w) => (s.length > w ? s.slice(0, Math.max(0, w - 1)) + "…" : s);
|
|
150
|
+
|
|
151
|
+
// The two lines of one agent, as plain cells the caller colours:
|
|
152
|
+
// { n, glyph, emoji, name, sub } — name and sub already cut to fit `width` columns.
|
|
153
|
+
// `emoji` comes from assignEmoji when several agents are drawn together.
|
|
154
|
+
export function rowCells(row, width = SIDE_WIDTH, ago = () => "", emoji = emojiFor(row.name)) {
|
|
155
|
+
const state = row.off ? "off" : row.state;
|
|
156
|
+
const where = row.machine ? ` @${row.machine}` : "";
|
|
157
|
+
const what = row.off ? `paused · ${row.machine} unreachable`
|
|
158
|
+
: row.state === "needs-you" ? `needs you · ${row.waitingFor || "input"}`
|
|
159
|
+
: [WORDS[row.state] || row.state, ago(row.startedAt)].filter(Boolean).join(" · ");
|
|
160
|
+
return {
|
|
161
|
+
n: row.n <= 9 ? String(row.n) : " ",
|
|
162
|
+
glyph: row.off ? "☾" : GLYPH[row.state] || "?",
|
|
163
|
+
emoji,
|
|
164
|
+
state,
|
|
165
|
+
name: cut(row.name, Math.max(6, width - 11)),
|
|
166
|
+
sub: cut(`${what} · ${row.harness}${where}`, Math.max(6, width - 8)),
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function wsHeadline(rows) {
|
|
171
|
+
const live = rows.filter((r) => !r.off);
|
|
172
|
+
const need = live.filter((r) => r.state === "needs-you").length;
|
|
173
|
+
const busy = live.filter((r) => r.state === "working" || r.state === "running").length;
|
|
174
|
+
return { need, busy, total: rows.length };
|
|
175
|
+
}
|
package/package.json
CHANGED
package/lib/serve.mjs
DELETED
|
@@ -1,241 +0,0 @@
|
|
|
1
|
-
// `seldon serve` — the panel as a phone app. Same lanes, same actions, a touch screen instead of
|
|
2
|
-
// a terminal. It owns nothing: it reads what the panel reads (readLanes, bifrost's machines) and
|
|
3
|
-
// acts through the same functions `seldon lane …` uses, locally or over `ssh <machine> seldon …`.
|
|
4
|
-
//
|
|
5
|
-
// Reach it from a phone with `tailscale serve`: HTTPS, the tailnet's identity on every request,
|
|
6
|
-
// no port on the internet. On its own it listens on loopback only.
|
|
7
|
-
//
|
|
8
|
-
// Pure rules first (tested without a server), then the I/O.
|
|
9
|
-
import { createServer } from "node:http";
|
|
10
|
-
import { readFileSync, writeFileSync, mkdirSync, chmodSync } from "node:fs";
|
|
11
|
-
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
12
|
-
import { execFile } from "node:child_process";
|
|
13
|
-
import { join, dirname } from "node:path";
|
|
14
|
-
import { fileURLToPath } from "node:url";
|
|
15
|
-
import { readLanes, readPlan, addToPlan, projectRoot, SELDON_HOME } from "./agents.mjs";
|
|
16
|
-
import { startLane, stopLane, resumeLane, removeLane, findLane, allLanes } from "./actions.mjs";
|
|
17
|
-
import { listMachines, fetchLanes, remoteGroups, sshArgs } from "./machines.mjs";
|
|
18
|
-
import { listHolds } from "./holds-store.mjs";
|
|
19
|
-
import { headline } from "./home.mjs";
|
|
20
|
-
import { HARNESSES, laneForItem, stopCommand, resumeCommands } from "./lanes.mjs";
|
|
21
|
-
|
|
22
|
-
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
23
|
-
|
|
24
|
-
// ---- pure ---------------------------------------------------------------------------
|
|
25
|
-
// "mini/claude:ab12" → { machine: "mini", key: "claude:ab12" }; local keys have no slash.
|
|
26
|
-
export function splitKey(key) {
|
|
27
|
-
const s = String(key || "");
|
|
28
|
-
const i = s.indexOf("/");
|
|
29
|
-
return i > 0 && !s.slice(0, i).includes(":") ? { machine: s.slice(0, i), key: s.slice(i + 1) } : { machine: null, key: s };
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
// Who may talk to it:
|
|
33
|
-
// - the Host is loopback or a tailnet name (a DNS-rebinding page can pose as neither), and a
|
|
34
|
-
// tailnet name only when it was started with --tailnet (`tailnet`): a `tailscale serve`
|
|
35
|
-
// mapping left over from an earlier run reaches nothing;
|
|
36
|
-
// - on the tailnet, the login tailscale serve stamps on the request must be the owner;
|
|
37
|
-
// - every /api call, reads too, carries the token. That also stops cross-site pages: they
|
|
38
|
-
// can't read it, and can't set a custom header without a CORS preflight nobody answers.
|
|
39
|
-
// The page itself (/) is static and holds no data, so it loads without one.
|
|
40
|
-
export function guard({ path, host, headers }, { token, owner = null, tailnet = false } = {}) {
|
|
41
|
-
const h = String(host || "").replace(/:\d+$/, "").toLowerCase();
|
|
42
|
-
const local = h === "localhost" || h === "127.0.0.1" || h === "[::1]";
|
|
43
|
-
if (!local && !h.endsWith(".ts.net")) return "host not allowed";
|
|
44
|
-
if (!local && !tailnet) return "not served on the tailnet (start with: seldon serve --tailnet)";
|
|
45
|
-
if (!local && (!owner || headers["tailscale-user-login"] !== owner)) return "not the owner";
|
|
46
|
-
if (String(path).startsWith("/api/") && !tokenOk(headers["x-seldon-token"], token)) return "bad or missing token";
|
|
47
|
-
return null;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export function tokenOk(given, token) {
|
|
51
|
-
if (!token || typeof given !== "string") return false;
|
|
52
|
-
const a = Buffer.from(given), b = Buffer.from(token);
|
|
53
|
-
return a.length === b.length && timingSafeEqual(a, b);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
// The tailnet login of this machine's user: who --tailnet lets in when --owner is not given.
|
|
57
|
-
export function ownerFromStatus(status) {
|
|
58
|
-
const id = status?.Self?.UserID;
|
|
59
|
-
return (id != null && status?.User?.[String(id)]?.LoginName) || null;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
// Keys a phone may press into an agent. A whitelist, so a reply can't smuggle tmux syntax.
|
|
63
|
-
export const REPLY_KEYS = { enter: "Enter", esc: "Escape", up: "Up", down: "Down", tab: "Tab", "ctrl-c": "C-c" };
|
|
64
|
-
// `submit: false` types without Enter: a menu key ("1") already chooses, and an Enter after it
|
|
65
|
-
// would answer whatever the agent asks next.
|
|
66
|
-
export function replyArgs(session, { key, text, submit = true } = {}) {
|
|
67
|
-
if (!session) return null;
|
|
68
|
-
if (key && REPLY_KEYS[key]) return [["send-keys", "-t", session, REPLY_KEYS[key]]];
|
|
69
|
-
if (typeof text === "string" && text.length && text.length <= 2000)
|
|
70
|
-
return [["send-keys", "-t", session, "-l", text], ...(submit ? [["send-keys", "-t", session, "Enter"]] : [])];
|
|
71
|
-
return null;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
// What a phone can do with a lane, so the UI never offers a button the server will refuse.
|
|
75
|
-
export function laneCaps(lane) {
|
|
76
|
-
const live = !["stopped", "failed"].includes(lane.state);
|
|
77
|
-
return {
|
|
78
|
-
peek: !!lane.tmuxSession && live,
|
|
79
|
-
reply: !!lane.tmuxSession && live,
|
|
80
|
-
stop: live && !stopCommand(lane).why,
|
|
81
|
-
resume: !live && !resumeCommands(lane).why,
|
|
82
|
-
rm: !live,
|
|
83
|
-
// Claude background lanes live under Claude's own supervisor: no tmux pane to read.
|
|
84
|
-
// Claude's Remote Control (claude.ai/code, the Claude app) is the way in for those.
|
|
85
|
-
hint: !lane.tmuxSession && lane.harness === "claude" && live
|
|
86
|
-
? (lane.id ? `claude attach ${lane.id}` : "open it in its terminal, or with Claude Remote Control") : null,
|
|
87
|
-
};
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
// ---- I/O ----------------------------------------------------------------------------
|
|
91
|
-
const sh = (bin, args, timeout = 10_000) => new Promise((res) =>
|
|
92
|
-
execFile(bin, args, { timeout, encoding: "utf8", maxBuffer: 4 << 20 }, (err, stdout, stderr) =>
|
|
93
|
-
res({ ok: !err, out: stdout || "", error: err ? (String(stderr).trim().split("\n").pop() || err.message) : null })));
|
|
94
|
-
|
|
95
|
-
// Machines are asked in the background, like the panel does, so a sleeping one never stalls a
|
|
96
|
-
// request. The cache is what the API answers from.
|
|
97
|
-
function remoteCache(intervalMs = 10_000) {
|
|
98
|
-
const state = new Map(); // name → { machine, lanes, error, at }
|
|
99
|
-
const poll = () => {
|
|
100
|
-
for (const m of listMachines()) fetchLanes(m, (r) => state.set(m.name, { machine: m, ...r, at: Date.now() }));
|
|
101
|
-
};
|
|
102
|
-
poll();
|
|
103
|
-
const t = setInterval(poll, intervalMs); t.unref();
|
|
104
|
-
return {
|
|
105
|
-
groups: () => [...state.values()].filter((s) => s.lanes).flatMap((s) => remoteGroups({ ...s.machine }, s.lanes)),
|
|
106
|
-
machines: () => listMachines().map((m) => {
|
|
107
|
-
const s = state.get(m.name);
|
|
108
|
-
return { name: m.name, host: m.host, ok: !!s?.lanes, error: s?.error || (s ? null : "asking…"), count: s?.lanes?.length ?? 0, at: s?.at ?? null };
|
|
109
|
-
}),
|
|
110
|
-
get: (name) => state.get(name),
|
|
111
|
-
refresh: poll,
|
|
112
|
-
};
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
function snapshot(remote) {
|
|
116
|
-
const local = readLanes().map((g) => ({ ...g, machine: null }));
|
|
117
|
-
const groups = [...local, ...remote.groups()];
|
|
118
|
-
for (const g of groups) for (const l of g.lanes) l.caps = laneCaps(l);
|
|
119
|
-
return { headline: headline(groups), groups, machines: remote.machines(), holds: listHolds(), at: Date.now() };
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
function laneByKey(remote, fullKey) {
|
|
123
|
-
const { machine, key } = splitKey(fullKey);
|
|
124
|
-
if (!machine) { const lane = findLane(key); return lane ? { lane, machine: null } : null; }
|
|
125
|
-
const s = remote.get(machine);
|
|
126
|
-
const lane = s?.lanes?.find((l) => l.key === key);
|
|
127
|
-
return lane ? { lane, machine: s.machine } : null;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
// One verb, wherever the lane lives.
|
|
131
|
-
async function act(remote, verb, fullKey, opts = {}) {
|
|
132
|
-
const found = laneByKey(remote, fullKey);
|
|
133
|
-
if (!found) return { ok: false, error: "no such lane (it may have just ended)" };
|
|
134
|
-
const { lane, machine } = found;
|
|
135
|
-
if (machine) {
|
|
136
|
-
const r = await sh("ssh", sshArgs(machine, ["seldon", "lane", verb, lane.key, ...(opts.force ? ["--force"] : [])]), 30_000);
|
|
137
|
-
remote.refresh();
|
|
138
|
-
return r.ok ? { ok: true } : { ok: false, error: r.error };
|
|
139
|
-
}
|
|
140
|
-
const r = verb === "stop" ? stopLane(lane) : verb === "resume" ? resumeLane(lane) : removeLane(lane, { force: !!opts.force });
|
|
141
|
-
return r.why ? { ok: false, error: r.why } : r;
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
async function tmuxOn(machine, args) {
|
|
145
|
-
return machine ? sh("ssh", sshArgs(machine, ["tmux", ...args])) : sh("tmux", args);
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
async function peek(remote, fullKey, lines = 60) {
|
|
149
|
-
const found = laneByKey(remote, fullKey);
|
|
150
|
-
if (!found?.lane.tmuxSession) return { ok: false, error: "no screen to read for this lane" };
|
|
151
|
-
const r = await tmuxOn(found.machine, ["capture-pane", "-p", "-J", "-t", found.lane.tmuxSession, "-S", `-${Math.min(400, lines)}`]);
|
|
152
|
-
return r.ok ? { ok: true, screen: r.out.replace(/\s+$/, "") } : r;
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
async function reply(remote, fullKey, body) {
|
|
156
|
-
const found = laneByKey(remote, fullKey);
|
|
157
|
-
const steps = replyArgs(found?.lane.tmuxSession, body);
|
|
158
|
-
if (!steps) return { ok: false, error: "nothing to send, or no pane to send it to" };
|
|
159
|
-
for (const args of steps) { const r = await tmuxOn(found.machine, args); if (!r.ok) return r; }
|
|
160
|
-
return { ok: true };
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
async function start(remote, { root, machine, task, agent = "claude" }) {
|
|
164
|
-
if (!HARNESSES.includes(agent)) return { ok: false, error: `unknown agent ${agent}` };
|
|
165
|
-
if (machine) {
|
|
166
|
-
const m = remote.get(machine)?.machine;
|
|
167
|
-
if (!m) return { ok: false, error: `unknown machine ${machine}` };
|
|
168
|
-
const r = await sh("ssh", sshArgs(m, ["seldon", "lane", "start", root, "--task", task, "--agent", agent]), 30_000);
|
|
169
|
-
remote.refresh();
|
|
170
|
-
return r.ok ? { ok: true } : { ok: false, error: r.error };
|
|
171
|
-
}
|
|
172
|
-
const dir = projectRoot(root) || root;
|
|
173
|
-
return startLane({ root: dir, name: dir.split("/").pop(), task, harness: agent });
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
// The open plan, each item with the lane already on it (the panel's own matching rule).
|
|
177
|
-
async function plan(remote, { root, machine }) {
|
|
178
|
-
const withLanes = (items, lanes) => items && items.map((it) => ({ ...it, lane: laneForItem(it, lanes)?.name ?? null }));
|
|
179
|
-
if (!machine) return { ok: true, items: withLanes(readPlan(root), allLanes()) };
|
|
180
|
-
const s = remote.get(machine);
|
|
181
|
-
if (!s) return { ok: false, error: `unknown machine ${machine}` };
|
|
182
|
-
const r = await sh("ssh", sshArgs(s.machine, ["foundation", "queue", "--list", "--json", "--dir", root]));
|
|
183
|
-
const line = r.out.split("\n").reverse().find((l) => l.trim().startsWith("["));
|
|
184
|
-
try { return { ok: true, items: withLanes(line ? JSON.parse(line) : null, s.lanes || []) }; } catch { return { ok: true, items: null }; }
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
const readBody = (req) => new Promise((res) => {
|
|
188
|
-
let raw = ""; req.on("data", (c) => { raw += c; if (raw.length > 64_000) req.destroy(); });
|
|
189
|
-
req.on("end", () => { try { res(JSON.parse(raw || "{}")); } catch { res({}); } });
|
|
190
|
-
});
|
|
191
|
-
|
|
192
|
-
// The token, made once and kept owner-only (0600). Delete the file to change it.
|
|
193
|
-
export function serveToken(home = SELDON_HOME) {
|
|
194
|
-
const file = join(home, "serve-token");
|
|
195
|
-
try { const t = readFileSync(file, "utf8").trim(); if (t.length >= 32) return t; } catch { /* first run */ }
|
|
196
|
-
const t = randomBytes(24).toString("base64url");
|
|
197
|
-
mkdirSync(home, { recursive: true });
|
|
198
|
-
writeFileSync(file, t + "\n", { mode: 0o600 }); chmodSync(file, 0o600);
|
|
199
|
-
return t;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
export function serve({ port = 7930, token, owner = null, tailnet = false, allowReply = false } = {}) {
|
|
203
|
-
if (!token) throw new Error("seldon serve needs a token");
|
|
204
|
-
if (tailnet && !owner) throw new Error("seldon serve --tailnet needs an owner");
|
|
205
|
-
const remote = remoteCache();
|
|
206
|
-
const page = () => readFileSync(join(HERE, "web", "index.html"), "utf8"); // re-read: edit + reload
|
|
207
|
-
const send = (res, code, body, type = "application/json") => {
|
|
208
|
-
res.writeHead(code, { "content-type": type, "cache-control": "no-store", "x-content-type-options": "nosniff",
|
|
209
|
-
"referrer-policy": "no-referrer", "x-frame-options": "DENY" });
|
|
210
|
-
res.end(type === "application/json" ? JSON.stringify(body) : body);
|
|
211
|
-
};
|
|
212
|
-
const server = createServer(async (req, res) => {
|
|
213
|
-
const url = new URL(req.url, "http://x");
|
|
214
|
-
const denied = guard({ path: url.pathname, host: req.headers.host, headers: req.headers }, { token, owner, tailnet });
|
|
215
|
-
if (denied) return send(res, 403, { ok: false, error: denied });
|
|
216
|
-
try {
|
|
217
|
-
if (req.method === "GET" && url.pathname === "/") return send(res, 200, page(), "text/html; charset=utf-8");
|
|
218
|
-
if (req.method === "GET" && url.pathname === "/manifest.webmanifest")
|
|
219
|
-
return send(res, 200, JSON.stringify({ name: "seldon", short_name: "seldon", display: "standalone", start_url: "/", background_color: "#0e0f0c", theme_color: "#0e0f0c" }), "application/manifest+json");
|
|
220
|
-
if (req.method === "GET" && url.pathname === "/api/state") return send(res, 200, { ...snapshot(remote), allowReply });
|
|
221
|
-
if (req.method === "GET" && url.pathname === "/api/peek") return send(res, 200, await peek(remote, url.searchParams.get("key")));
|
|
222
|
-
if (req.method === "GET" && url.pathname === "/api/plan")
|
|
223
|
-
return send(res, 200, await plan(remote, { root: url.searchParams.get("root"), machine: url.searchParams.get("machine") || null }));
|
|
224
|
-
if (req.method === "POST") {
|
|
225
|
-
const body = await readBody(req);
|
|
226
|
-
const m = url.pathname.match(/^\/api\/lane\/(stop|resume|rm)$/);
|
|
227
|
-
if (m) return send(res, 200, await act(remote, m[1], body.key, body));
|
|
228
|
-
if (url.pathname === "/api/lane/start") return send(res, 200, await start(remote, body));
|
|
229
|
-
if (url.pathname === "/api/lane/reply") {
|
|
230
|
-
if (!allowReply) return send(res, 403, { ok: false, error: "replies are off — start with: seldon serve --allow-reply" });
|
|
231
|
-
return send(res, 200, await reply(remote, body.lane, body));
|
|
232
|
-
}
|
|
233
|
-
if (url.pathname === "/api/plan/add" && !body.machine && body.root && body.text)
|
|
234
|
-
return send(res, 200, addToPlan(body.root, String(body.text).slice(0, 500), body.priority || "P2"));
|
|
235
|
-
}
|
|
236
|
-
send(res, 404, { ok: false, error: "not found" });
|
|
237
|
-
} catch (e) { send(res, 500, { ok: false, error: e.message }); }
|
|
238
|
-
});
|
|
239
|
-
server.listen(port, "127.0.0.1");
|
|
240
|
-
return server;
|
|
241
|
-
}
|
package/lib/web/index.html
DELETED
|
@@ -1,351 +0,0 @@
|
|
|
1
|
-
<!doctype html>
|
|
2
|
-
<html lang="en">
|
|
3
|
-
<head>
|
|
4
|
-
<meta charset="utf-8">
|
|
5
|
-
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
|
6
|
-
<meta name="theme-color" content="#0e0f0c">
|
|
7
|
-
<meta name="apple-mobile-web-app-capable" content="yes">
|
|
8
|
-
<link rel="manifest" href="/manifest.webmanifest">
|
|
9
|
-
<title>seldon</title>
|
|
10
|
-
<style>
|
|
11
|
-
:root {
|
|
12
|
-
--bg: #f4f2ec; --card: #fffdf8; --ink: #1b1c18; --mute: #6d6c64; --line: #e2dfd5;
|
|
13
|
-
--need: #c2410c; --need-bg: #fdecdf; --work: #2f7d4f; --idle: #8b8a80; --fail: #b42318; --accent: #1b1c18;
|
|
14
|
-
--mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;
|
|
15
|
-
--sans: -apple-system, system-ui, "Segoe UI", Roboto, sans-serif;
|
|
16
|
-
--r: 14px; --safe-b: env(safe-area-inset-bottom, 0px);
|
|
17
|
-
}
|
|
18
|
-
@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) {
|
|
19
|
-
--bg: #0e0f0c; --card: #171814; --ink: #ecebe4; --mute: #8f8e85; --line: #2a2b25;
|
|
20
|
-
--need: #fb923c; --need-bg: #2a1a0e; --work: #5fbf86; --idle: #77766d; --fail: #f87171; --accent: #ecebe4;
|
|
21
|
-
} }
|
|
22
|
-
:root[data-theme="dark"] {
|
|
23
|
-
--bg: #0e0f0c; --card: #171814; --ink: #ecebe4; --mute: #8f8e85; --line: #2a2b25;
|
|
24
|
-
--need: #fb923c; --need-bg: #2a1a0e; --work: #5fbf86; --idle: #77766d; --fail: #f87171; --accent: #ecebe4;
|
|
25
|
-
}
|
|
26
|
-
* { box-sizing: border-box; }
|
|
27
|
-
html, body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.4 var(--sans); -webkit-text-size-adjust: 100%; }
|
|
28
|
-
button, input, textarea, select { font: inherit; color: inherit; }
|
|
29
|
-
button { cursor: pointer; }
|
|
30
|
-
.wrap { max-width: 640px; margin: 0 auto; padding: 0 16px calc(96px + var(--safe-b)); }
|
|
31
|
-
|
|
32
|
-
/* top */
|
|
33
|
-
header { position: sticky; top: 0; z-index: 5; background: color-mix(in srgb, var(--bg) 92%, transparent); backdrop-filter: blur(10px);
|
|
34
|
-
padding: calc(10px + env(safe-area-inset-top, 0px)) 0 10px; border-bottom: 1px solid var(--line); }
|
|
35
|
-
.top { display: flex; align-items: baseline; gap: 10px; }
|
|
36
|
-
.mark { font: 700 13px/1 var(--mono); letter-spacing: .28em; }
|
|
37
|
-
.head { flex: 1; min-width: 0; color: var(--mute); font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
38
|
-
.live { width: 8px; height: 8px; border-radius: 50%; background: var(--work); align-self: center; transition: opacity .3s; }
|
|
39
|
-
.live.stale { background: var(--fail); }
|
|
40
|
-
.chips { display: flex; gap: 8px; overflow-x: auto; margin-top: 10px; scrollbar-width: none; }
|
|
41
|
-
.chips::-webkit-scrollbar { display: none; }
|
|
42
|
-
.chip { flex: none; min-height: 44px; padding: 0 14px; border-radius: 999px; border: 1px solid var(--line); background: var(--card);
|
|
43
|
-
display: inline-flex; align-items: center; gap: 6px; font-size: 13px; }
|
|
44
|
-
.chip[aria-pressed="true"] { background: var(--accent); color: var(--bg); border-color: var(--accent); }
|
|
45
|
-
.chip .n { font: 600 12px var(--mono); }
|
|
46
|
-
.chip.need .n { color: var(--need); }
|
|
47
|
-
.chip[aria-pressed="true"].need .n { color: inherit; }
|
|
48
|
-
.chip .dot { width: 7px; height: 7px; }
|
|
49
|
-
|
|
50
|
-
.holds { margin: 12px 0 0; font: 12px var(--mono); color: var(--mute); }
|
|
51
|
-
.holds b { color: var(--ink); font-weight: 600; }
|
|
52
|
-
|
|
53
|
-
/* projects + lanes */
|
|
54
|
-
section.proj { margin-top: 18px; }
|
|
55
|
-
.ph { display: flex; align-items: center; gap: 8px; min-height: 44px; }
|
|
56
|
-
.ph h2 { margin: 0; font-size: 15px; font-weight: 650; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
57
|
-
.ph .at { font: 12px var(--mono); color: var(--mute); flex: none; }
|
|
58
|
-
.ph .sp { flex: 1; }
|
|
59
|
-
.ghost { min-height: 44px; min-width: 44px; padding: 0 12px; border: 0; background: none; color: var(--mute); font-size: 13px; border-radius: 10px; }
|
|
60
|
-
.ghost:active { background: var(--line); }
|
|
61
|
-
.card { background: var(--card); border: 1px solid var(--line); border-radius: var(--r); overflow: hidden; }
|
|
62
|
-
.lane { display: grid; grid-template-columns: 22px 1fr auto; gap: 2px 10px; align-items: center; width: 100%; text-align: left;
|
|
63
|
-
padding: 12px 14px; min-height: 60px; border: 0; background: none; border-top: 1px solid var(--line); }
|
|
64
|
-
.lane:first-child { border-top: 0; }
|
|
65
|
-
.lane:active { background: var(--line); }
|
|
66
|
-
.lane.needs-you { background: var(--need-bg); }
|
|
67
|
-
.lane .g { grid-row: span 2; display: grid; place-items: center; }
|
|
68
|
-
.lane .nm { min-width: 0; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
69
|
-
.lane .ag { font: 12px var(--mono); color: var(--mute); }
|
|
70
|
-
.lane .dt { grid-column: 2 / 4; min-width: 0; font-size: 13px; color: var(--mute); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
71
|
-
.lane.needs-you .dt { color: var(--need); font-weight: 600; }
|
|
72
|
-
.dot { width: 10px; height: 10px; border-radius: 50%; background: var(--idle); display: inline-block; flex: none; }
|
|
73
|
-
.dot.needs-you { background: var(--need); box-shadow: 0 0 0 4px color-mix(in srgb, var(--need) 25%, transparent); animation: pulse 1.6s infinite; }
|
|
74
|
-
.dot.working, .dot.running { background: var(--work); }
|
|
75
|
-
.dot.failed { background: var(--fail); }
|
|
76
|
-
.dot.stopped { background: transparent; border: 2px solid var(--idle); }
|
|
77
|
-
@keyframes pulse { 50% { box-shadow: 0 0 0 7px transparent; } }
|
|
78
|
-
@media (prefers-reduced-motion: reduce) { .dot.needs-you { animation: none; } }
|
|
79
|
-
.empty { padding: 40px 8px; text-align: center; color: var(--mute); }
|
|
80
|
-
.empty p { margin: 6px 0; }
|
|
81
|
-
|
|
82
|
-
/* fab */
|
|
83
|
-
.fab { position: fixed; right: max(16px, calc(50% - 304px)); bottom: calc(18px + var(--safe-b)); z-index: 6; min-height: 52px; padding: 0 20px;
|
|
84
|
-
border-radius: 999px; border: 0; background: var(--accent); color: var(--bg); font-weight: 650; box-shadow: 0 6px 24px rgb(0 0 0 / .25); }
|
|
85
|
-
|
|
86
|
-
/* sheet */
|
|
87
|
-
.scrim { position: fixed; inset: 0; background: rgb(0 0 0 / .45); z-index: 10; opacity: 0; pointer-events: none; transition: opacity .2s; }
|
|
88
|
-
.scrim.on { opacity: 1; pointer-events: auto; }
|
|
89
|
-
.sheet { position: fixed; left: 0; right: 0; bottom: 0; z-index: 11; max-width: 640px; margin: 0 auto; max-height: 92dvh; overflow-y: auto;
|
|
90
|
-
background: var(--card); border-radius: 18px 18px 0 0; padding: 8px 16px calc(20px + var(--safe-b)); transform: translateY(105%); transition: transform .22s ease-out; }
|
|
91
|
-
.sheet.on { transform: none; }
|
|
92
|
-
.grab { width: 40px; height: 5px; border-radius: 3px; background: var(--line); margin: 4px auto 12px; }
|
|
93
|
-
.sheet h3 { margin: 0; font-size: 18px; overflow-wrap: anywhere; }
|
|
94
|
-
.meta { display: flex; flex-wrap: wrap; gap: 6px 12px; margin: 6px 0 14px; font: 12px var(--mono); color: var(--mute); }
|
|
95
|
-
.meta .st { display: inline-flex; gap: 6px; align-items: center; color: var(--ink); }
|
|
96
|
-
.screen { background: #0b0c0a; color: #d8d6cc; font: 11.5px/1.45 var(--mono); border-radius: 10px; padding: 10px 12px; max-height: 42dvh;
|
|
97
|
-
overflow: auto; white-space: pre; margin: 0 0 12px; }
|
|
98
|
-
.note { font-size: 13px; color: var(--mute); background: var(--bg); border-radius: 10px; padding: 10px 12px; margin: 0 0 12px; }
|
|
99
|
-
.note code { font: 12px var(--mono); color: var(--ink); overflow-wrap: anywhere; }
|
|
100
|
-
.keys { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin-bottom: 8px; }
|
|
101
|
-
.k { min-height: 44px; border-radius: 10px; border: 1px solid var(--line); background: var(--bg); font: 600 14px var(--mono); }
|
|
102
|
-
.k:active { background: var(--line); }
|
|
103
|
-
.row { display: flex; gap: 8px; }
|
|
104
|
-
.row > * { min-width: 0; }
|
|
105
|
-
.in { flex: 1; min-height: 44px; border-radius: 10px; border: 1px solid var(--line); background: var(--bg); padding: 10px 12px; }
|
|
106
|
-
textarea.in { min-height: 96px; resize: vertical; width: 100%; }
|
|
107
|
-
select.in { width: 100%; }
|
|
108
|
-
.btn { min-height: 44px; padding: 0 16px; border-radius: 10px; border: 1px solid var(--line); background: var(--bg); font-weight: 600; }
|
|
109
|
-
.btn.primary { background: var(--accent); color: var(--bg); border-color: var(--accent); }
|
|
110
|
-
.btn.danger { color: var(--fail); }
|
|
111
|
-
.btn.danger.armed { background: var(--fail); color: #fff; border-color: var(--fail); }
|
|
112
|
-
.btn:disabled { opacity: .5; }
|
|
113
|
-
.actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 14px; }
|
|
114
|
-
.actions .btn { flex: 1 1 30%; }
|
|
115
|
-
label.f { display: block; font-size: 12px; color: var(--mute); margin: 12px 0 6px; font-weight: 600; letter-spacing: .02em; }
|
|
116
|
-
.seg { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; }
|
|
117
|
-
.seg button { min-height: 44px; border-radius: 10px; border: 1px solid var(--line); background: var(--bg); font: 13px var(--mono); }
|
|
118
|
-
.seg button[aria-pressed="true"] { background: var(--accent); color: var(--bg); border-color: var(--accent); }
|
|
119
|
-
.plan { list-style: none; margin: 0; padding: 0; }
|
|
120
|
-
.plan li { display: flex; gap: 10px; align-items: center; padding: 10px 0; border-top: 1px solid var(--line); }
|
|
121
|
-
.plan li:first-child { border-top: 0; }
|
|
122
|
-
.plan .pr { font: 600 11px var(--mono); color: var(--mute); flex: none; width: 22px; }
|
|
123
|
-
.plan .tx { flex: 1; min-width: 0; font-size: 14px; }
|
|
124
|
-
.plan .on { font: 11px var(--mono); color: var(--work); }
|
|
125
|
-
.toast { position: fixed; left: 16px; right: 16px; bottom: calc(84px + var(--safe-b)); z-index: 20; max-width: 560px; margin: 0 auto;
|
|
126
|
-
background: var(--ink); color: var(--bg); padding: 12px 14px; border-radius: 12px; font-size: 14px; opacity: 0; transform: translateY(8px);
|
|
127
|
-
transition: .2s; pointer-events: none; }
|
|
128
|
-
.toast.on { opacity: 1; transform: none; }
|
|
129
|
-
.toast.err { background: var(--fail); color: #fff; }
|
|
130
|
-
</style>
|
|
131
|
-
</head>
|
|
132
|
-
<body>
|
|
133
|
-
<header><div class="wrap" style="padding-bottom:0">
|
|
134
|
-
<div class="top"><span class="mark">SELDON</span><span class="head" id="head">…</span><span class="live" id="live" title="live"></span></div>
|
|
135
|
-
<div class="chips" id="chips" role="toolbar" aria-label="filter"></div>
|
|
136
|
-
<div class="holds" id="holds"></div>
|
|
137
|
-
</div></header>
|
|
138
|
-
<main class="wrap" id="main"></main>
|
|
139
|
-
<button class="fab" data-act="new">+ lane</button>
|
|
140
|
-
<div class="scrim" id="scrim" data-act="close"></div>
|
|
141
|
-
<div class="sheet" id="sheet" role="dialog" aria-modal="true"><div class="grab"></div><div id="sheetBody"></div></div>
|
|
142
|
-
<div class="toast" id="toast" role="status"></div>
|
|
143
|
-
<script>
|
|
144
|
-
"use strict";
|
|
145
|
-
const $ = (id) => document.getElementById(id);
|
|
146
|
-
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
|
147
|
-
const ago = (ms) => { if (!ms) return ""; const s = Math.max(0, (Date.now() - ms) / 1000 | 0);
|
|
148
|
-
return s < 60 ? s + "s" : s < 3600 ? (s / 60 | 0) + "m" : s < 86400 ? (s / 3600 | 0) + "h" : (s / 86400 | 0) + "d"; };
|
|
149
|
-
const detail = (l) => l.state === "needs-you" ? "needs you: " + (l.waitingFor || "input") : l.state === "running" ? "running (no state reported)" : l.state;
|
|
150
|
-
|
|
151
|
-
let S = null, filter = "all", sheet = null, peekTimer = null, lastNeed = -1;
|
|
152
|
-
// The token arrives once in the link seldon serve prints (#t=…), is kept on this device, and
|
|
153
|
-
// is taken out of the address bar so it never ends up in a screenshot or a shared URL.
|
|
154
|
-
const TOKEN = (() => {
|
|
155
|
-
const m = location.hash.match(/[#&]t=([A-Za-z0-9_-]+)/);
|
|
156
|
-
try { if (m) localStorage.setItem("seldon-token", m[1]); } catch {}
|
|
157
|
-
if (m) history.replaceState(null, "", location.pathname);
|
|
158
|
-
try { return m?.[1] || localStorage.getItem("seldon-token") || ""; } catch { return m?.[1] || ""; }
|
|
159
|
-
})();
|
|
160
|
-
const api = async (path, body) => {
|
|
161
|
-
const headers = { "x-seldon-token": TOKEN, ...(body ? { "content-type": "application/json" } : {}) };
|
|
162
|
-
const r = await fetch(path, body ? { method: "POST", headers, body: JSON.stringify(body) } : { headers });
|
|
163
|
-
const j = await r.json().catch(() => ({ ok: false, error: "bad reply (" + r.status + ")" }));
|
|
164
|
-
if (r.status === 403) locked(j.error);
|
|
165
|
-
return j;
|
|
166
|
-
};
|
|
167
|
-
function locked(why) {
|
|
168
|
-
$("head").textContent = "locked";
|
|
169
|
-
$("main").innerHTML = `<div class="empty"><p><b>This device isn't let in.</b></p><p>${esc(why)}</p>
|
|
170
|
-
<p>Open the link <code>seldon serve</code> printed in your terminal (it carries the token).</p></div>`;
|
|
171
|
-
throw new Error(why);
|
|
172
|
-
}
|
|
173
|
-
const toast = (msg, err) => { const t = $("toast"); t.textContent = msg; t.className = "toast on" + (err ? " err" : ""); clearTimeout(toast.t); toast.t = setTimeout(() => t.className = "toast", 2600); };
|
|
174
|
-
const allLanes = () => S ? S.groups.flatMap((g) => g.lanes.map((l) => ({ ...l, group: g }))) : [];
|
|
175
|
-
const laneBy = (key) => allLanes().find((l) => l.key === key);
|
|
176
|
-
|
|
177
|
-
// ---- poll -------------------------------------------------------------------------
|
|
178
|
-
async function refresh() {
|
|
179
|
-
try {
|
|
180
|
-
S = await api("/api/state");
|
|
181
|
-
$("live").classList.remove("stale");
|
|
182
|
-
render();
|
|
183
|
-
const need = allLanes().filter((l) => l.state === "needs-you").length;
|
|
184
|
-
if (lastNeed >= 0 && need > lastNeed) alertNeed(need);
|
|
185
|
-
lastNeed = need;
|
|
186
|
-
document.title = need ? `(${need}) seldon` : "seldon";
|
|
187
|
-
if (sheet?.type === "lane") renderLaneSheet(false);
|
|
188
|
-
} catch { $("live").classList.add("stale"); }
|
|
189
|
-
}
|
|
190
|
-
function alertNeed(n) {
|
|
191
|
-
navigator.vibrate?.(120);
|
|
192
|
-
if (document.hidden && "Notification" in window && Notification.permission === "granted")
|
|
193
|
-
new Notification("seldon", { body: n === 1 ? "an agent needs you" : n + " agents need you", tag: "seldon-need" });
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
// ---- render -----------------------------------------------------------------------
|
|
197
|
-
function render() {
|
|
198
|
-
$("head").textContent = S.headline;
|
|
199
|
-
const lanes = allLanes(), need = lanes.filter((l) => l.state === "needs-you").length;
|
|
200
|
-
const chips = [["all", "All", lanes.length, ""], ["need", "Needs you", need, "need"], ["here", "this mac", S.groups.filter((g) => !g.machine).reduce((a, g) => a + g.lanes.length, 0), ""],
|
|
201
|
-
...S.machines.map((m) => ["m:" + m.name, m.name, m.ok ? m.count : "—", m.ok ? "" : "off"])];
|
|
202
|
-
$("chips").innerHTML = chips.map(([id, label, n, cls]) =>
|
|
203
|
-
`<button class="chip ${cls}" data-act="filter" data-id="${esc(id)}" aria-pressed="${filter === id}">${cls === "off" ? '<span class="dot failed"></span>' : ""}${esc(label)} <span class="n">${esc(n)}</span></button>`).join("");
|
|
204
|
-
$("holds").innerHTML = S.holds?.length ? "held: " + S.holds.map((h) => `<b>${esc(h.name)}</b> → ${esc(h.who)}`).join(" · ") : "";
|
|
205
|
-
|
|
206
|
-
const groups = S.groups.map((g) => ({ ...g, lanes: g.lanes.filter((l) =>
|
|
207
|
-
filter === "need" ? l.state === "needs-you" : filter === "here" ? !g.machine : filter.startsWith("m:") ? g.machine === filter.slice(2) : true) }))
|
|
208
|
-
.filter((g) => g.lanes.length);
|
|
209
|
-
$("main").innerHTML = groups.length ? groups.map((g) => `
|
|
210
|
-
<section class="proj">
|
|
211
|
-
<div class="ph"><h2>${esc(g.lanes[0].projectName || g.name.replace(/ @.*/, ""))}</h2>${g.machine ? `<span class="at">@${esc(g.machine)}</span>` : ""}<span class="sp"></span>
|
|
212
|
-
<button class="ghost" data-act="plan" data-root="${esc(g.remoteRoot || g.root)}" data-machine="${esc(g.machine || "")}">plan</button>
|
|
213
|
-
<button class="ghost" data-act="new" data-root="${esc(g.remoteRoot || g.root)}" data-machine="${esc(g.machine || "")}" aria-label="new lane here">+</button></div>
|
|
214
|
-
<div class="card">${g.lanes.map((l) => `
|
|
215
|
-
<button class="lane ${esc(l.state)}" data-act="lane" data-key="${esc(l.key)}">
|
|
216
|
-
<span class="g"><span class="dot ${esc(l.state)}"></span></span>
|
|
217
|
-
<span class="nm">${esc(l.name || l.id || "?")}</span><span class="ag">${esc(l.harness)} ${esc(ago(l.startedAt))}</span>
|
|
218
|
-
<span class="dt">${esc(detail(l))}</span>
|
|
219
|
-
</button>`).join("")}</div>
|
|
220
|
-
</section>`).join("")
|
|
221
|
-
: `<div class="empty"><p><b>${filter === "need" ? "Nobody needs you." : "No agents here."}</b></p><p>${filter === "need" ? "You'll get a buzz when one does." : "Start one with + lane."}</p></div>`;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
// ---- sheets -----------------------------------------------------------------------
|
|
225
|
-
function open(type, data) { sheet = { type, ...data }; $("scrim").classList.add("on"); $("sheet").classList.add("on"); }
|
|
226
|
-
function close() { sheet = null; clearInterval(peekTimer); $("scrim").classList.remove("on"); $("sheet").classList.remove("on"); }
|
|
227
|
-
|
|
228
|
-
function renderLaneSheet(full = true) {
|
|
229
|
-
const l = laneBy(sheet.key);
|
|
230
|
-
if (!l) { $("sheetBody").innerHTML = `<h3>Lane ended</h3><p class="note">It is no longer listed.</p>`; return; }
|
|
231
|
-
const c = l.caps || {};
|
|
232
|
-
const head = `<h3>${esc(l.name || l.id)}</h3>
|
|
233
|
-
<div class="meta"><span class="st"><span class="dot ${esc(l.state)}"></span>${esc(detail(l))}</span><span>${esc(l.harness)}</span>
|
|
234
|
-
<span>${esc(l.group.lanes[0].projectName || l.group.name)}${l.group.machine ? " @" + esc(l.group.machine) : ""}</span><span>${esc(ago(l.startedAt))}</span></div>`;
|
|
235
|
-
if (!full) { $("sheetBody").querySelector(".lanehead").innerHTML = head; return; }
|
|
236
|
-
$("sheetBody").innerHTML = `<div class="lanehead">${head}</div>
|
|
237
|
-
${c.peek ? `<pre class="screen" id="screen">reading the screen…</pre>` : ""}
|
|
238
|
-
${c.hint ? `<p class="note">No terminal pane to read for this lane. Open it with <code>${esc(c.hint)}</code>, or from the Claude app via Remote Control.</p>` : ""}
|
|
239
|
-
${c.reply && S.allowReply ? `
|
|
240
|
-
<div class="keys">${["1", "2", "3", "y"].map((k) => `<button class="k" data-act="text" data-v="${k}">${k}</button>`).join("")}
|
|
241
|
-
${[["enter", "⏎"], ["esc", "esc"], ["up", "↑"], ["down", "↓"]].map(([k, v]) => `<button class="k" data-act="key" data-v="${k}">${v}</button>`).join("")}</div>
|
|
242
|
-
<form class="row" data-form="reply"><input class="in" name="t" placeholder="reply to the agent…" autocomplete="off" enterkeyhint="send"><button class="btn primary">Send</button></form>`
|
|
243
|
-
: c.reply ? `<p class="note">Read-only. To answer from here, start it with <code>seldon serve --allow-reply</code>.</p>` : ""}
|
|
244
|
-
<div class="actions">
|
|
245
|
-
${c.stop ? `<button class="btn danger" data-act="stop">Stop</button>` : ""}
|
|
246
|
-
${c.resume ? `<button class="btn primary" data-act="resume">Resume</button>` : ""}
|
|
247
|
-
${c.rm ? `<button class="btn danger" data-act="rm">Remove</button>` : ""}
|
|
248
|
-
<button class="btn" data-act="close">Close</button>
|
|
249
|
-
</div>`;
|
|
250
|
-
clearInterval(peekTimer);
|
|
251
|
-
if (c.peek) { peek(); peekTimer = setInterval(peek, 2000); }
|
|
252
|
-
}
|
|
253
|
-
async function peek() {
|
|
254
|
-
const el = $("screen"); if (!el || !sheet) return;
|
|
255
|
-
const r = await api("/api/peek?key=" + encodeURIComponent(sheet.key));
|
|
256
|
-
const atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 8;
|
|
257
|
-
el.textContent = r.ok ? (r.screen || "(empty)") : r.error;
|
|
258
|
-
if (atBottom) el.scrollTop = el.scrollHeight;
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
function projects() {
|
|
262
|
-
return S.groups.map((g) => ({ root: g.remoteRoot || g.root, machine: g.machine || "", label: (g.lanes[0]?.projectName || g.name.replace(/ @.*/, "")) + (g.machine ? " @" + g.machine : "") }));
|
|
263
|
-
}
|
|
264
|
-
function renderNew(d) {
|
|
265
|
-
const ps = projects(); const pick = ps.find((p) => p.root === d.root && p.machine === (d.machine || "")) || ps[0];
|
|
266
|
-
sheet.agent = sheet.agent || "claude";
|
|
267
|
-
$("sheetBody").innerHTML = `<h3>New lane</h3>
|
|
268
|
-
<form data-form="start">
|
|
269
|
-
<label class="f">Project</label>
|
|
270
|
-
<select class="in" name="p">${ps.map((p, i) => `<option value="${i}" ${p === pick ? "selected" : ""}>${esc(p.label)}</option>`).join("")}</select>
|
|
271
|
-
<label class="f">Task</label>
|
|
272
|
-
<textarea class="in" name="task" placeholder="fix the save crash">${esc(d.task || "")}</textarea>
|
|
273
|
-
<label class="f">Agent</label>
|
|
274
|
-
<div class="seg">${["claude", "codex", "opencode"].map((a) => `<button type="button" data-act="agent" data-v="${a}" aria-pressed="${sheet.agent === a}">${a}</button>`).join("")}</div>
|
|
275
|
-
<div class="actions"><button class="btn primary">Start lane</button><button type="button" class="btn" data-act="close">Cancel</button></div>
|
|
276
|
-
</form>`;
|
|
277
|
-
sheet.projects = ps;
|
|
278
|
-
}
|
|
279
|
-
async function renderPlan() {
|
|
280
|
-
$("sheetBody").innerHTML = `<h3>Plan</h3><p class="note">reading docs/QUEUE.md…</p>`;
|
|
281
|
-
const r = await api(`/api/plan?root=${encodeURIComponent(sheet.root)}&machine=${encodeURIComponent(sheet.machine || "")}`);
|
|
282
|
-
if (sheet?.type !== "plan") return;
|
|
283
|
-
const items = r.items;
|
|
284
|
-
$("sheetBody").innerHTML = `<h3>Plan</h3><div class="meta"><span>${esc(sheet.root)}${sheet.machine ? " @" + esc(sheet.machine) : ""}</span></div>
|
|
285
|
-
${!r.ok ? `<p class="note">${esc(r.error)}</p>` : items == null ? `<p class="note">No plan here (foundation not installed, or no docs/QUEUE.md).</p>`
|
|
286
|
-
: !items.length ? `<p class="note">The plan is empty.</p>`
|
|
287
|
-
: `<ul class="plan">${items.map((it, i) => `<li><span class="pr">${esc(it.priority || "")}</span><span class="tx">${esc(it.text)}</span>
|
|
288
|
-
${it.lane ? `<span class="on">● ${esc(it.lane)}</span>` : `<button class="btn" data-act="item" data-i="${i}">Start</button>`}</li>`).join("")}</ul>`}
|
|
289
|
-
${!sheet.machine && items ? `<form class="row" data-form="add" style="margin-top:12px"><input class="in" name="t" placeholder="add to the plan…" autocomplete="off"><button class="btn">Add</button></form>` : ""}
|
|
290
|
-
<div class="actions"><button class="btn" data-act="close">Close</button></div>`;
|
|
291
|
-
sheet.items = items;
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
// ---- one listener for everything ----------------------------------------------------
|
|
295
|
-
async function doLane(verb, btn) {
|
|
296
|
-
if (verb !== "resume" && !btn.classList.contains("armed")) { btn.classList.add("armed"); btn.textContent = "Tap again to " + verb.replace("rm", "remove"); setTimeout(() => { btn.classList.remove("armed"); btn.textContent = verb === "rm" ? "Remove" : "Stop"; }, 3000); return; }
|
|
297
|
-
btn.disabled = true;
|
|
298
|
-
const r = await api("/api/lane/" + verb, { key: sheet.key });
|
|
299
|
-
toast(r.ok ? ({ stop: "Stopped", resume: "Resumed", rm: "Removed" }[verb]) : r.error, !r.ok);
|
|
300
|
-
if (r.ok && verb !== "resume") close();
|
|
301
|
-
refresh();
|
|
302
|
-
}
|
|
303
|
-
document.addEventListener("click", async (e) => {
|
|
304
|
-
const b = e.target.closest("[data-act]"); if (!b) return;
|
|
305
|
-
const a = b.dataset.act;
|
|
306
|
-
if (a === "filter") { filter = b.dataset.id; render(); }
|
|
307
|
-
else if (a === "lane") { open("lane", { key: b.dataset.key }); renderLaneSheet(); maybeAskNotify(); }
|
|
308
|
-
else if (a === "new") { open("new", {}); renderNew({ root: b.dataset.root, machine: b.dataset.machine }); }
|
|
309
|
-
else if (a === "plan") { open("plan", { root: b.dataset.root, machine: b.dataset.machine }); renderPlan(); }
|
|
310
|
-
else if (a === "close") close();
|
|
311
|
-
else if (a === "agent") { sheet.agent = b.dataset.v; b.parentElement.querySelectorAll("button").forEach((x) => x.setAttribute("aria-pressed", x === b)); }
|
|
312
|
-
else if (["stop", "resume", "rm"].includes(a)) doLane(a, b);
|
|
313
|
-
else if (a === "key") reply({ key: b.dataset.v });
|
|
314
|
-
else if (a === "text") reply({ text: b.dataset.v, submit: false });
|
|
315
|
-
else if (a === "item") { const it = sheet.items[b.dataset.i]; const { root, machine } = sheet; open("new", {}); renderNew({ root, machine, task: it.text }); }
|
|
316
|
-
});
|
|
317
|
-
async function reply(what) {
|
|
318
|
-
const r = await api("/api/lane/reply", { lane: sheet.key, ...what });
|
|
319
|
-
if (!r.ok) toast(r.error, true); else { navigator.vibrate?.(15); setTimeout(peek, 250); }
|
|
320
|
-
}
|
|
321
|
-
document.addEventListener("submit", async (e) => {
|
|
322
|
-
const f = e.target.closest("[data-form]"); if (!f) return;
|
|
323
|
-
e.preventDefault();
|
|
324
|
-
const kind = f.dataset.form, btn = f.querySelector("button:not([type=button])");
|
|
325
|
-
if (kind === "reply") { const t = f.t.value; if (!t) return; f.t.value = ""; return reply({ text: t }); }
|
|
326
|
-
if (kind === "add") {
|
|
327
|
-
const t = f.t.value.trim(); if (!t) return;
|
|
328
|
-
const r = await api("/api/plan/add", { root: sheet.root, text: t });
|
|
329
|
-
toast(r.ok ? "Added to the plan" : r.error, !r.ok); if (r.ok) renderPlan(); return;
|
|
330
|
-
}
|
|
331
|
-
if (kind === "start") {
|
|
332
|
-
const p = sheet.projects[f.p.value], task = f.task.value.trim();
|
|
333
|
-
if (!p || !task) return toast("pick a project and write a task", true);
|
|
334
|
-
btn.disabled = true; btn.textContent = "Starting…";
|
|
335
|
-
const r = await api("/api/lane/start", { root: p.root, machine: p.machine || null, task, agent: sheet.agent });
|
|
336
|
-
toast(r.ok ? "Started " + (r.slug || "lane") : r.error, !r.ok);
|
|
337
|
-
if (r.ok) close(); else { btn.disabled = false; btn.textContent = "Start lane"; }
|
|
338
|
-
refresh();
|
|
339
|
-
}
|
|
340
|
-
});
|
|
341
|
-
// Notifications need a secure context (tailscale serve gives one) and a tap to ask.
|
|
342
|
-
function maybeAskNotify() {
|
|
343
|
-
if ("Notification" in window && Notification.permission === "default" && window.isSecureContext) Notification.requestPermission();
|
|
344
|
-
}
|
|
345
|
-
document.addEventListener("keydown", (e) => { if (e.key === "Escape" && sheet) close(); });
|
|
346
|
-
document.addEventListener("visibilitychange", () => { if (!document.hidden) refresh(); });
|
|
347
|
-
refresh();
|
|
348
|
-
setInterval(refresh, 3000);
|
|
349
|
-
</script>
|
|
350
|
-
</body>
|
|
351
|
-
</html>
|