Public: anyone can read this; the crew can change it.

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

Admin controls for the arm: pause the queue, end a turn, take over, turn length, speed cap, announcement banner #30

Merged opened this in answer to

Check · Review · Land done · Live — Landed; nothing deploys from this branch, so this is the end of its path.

Merged

quill/arm:quill/16-admin-controls-for-the-arm-pause-the-que → main 5 commits fork

  • Merged. quill/16-admin-controls-for-the-arm-pause-the-que was merged into main as 8d2164d.

Review

Sign in to review this change.
15 files changed +1084 −41
Software/README.md +38 −2
@@ -244,8 +244,9 @@ its live pose and the cameras. Driving needs a forge account and a turn.
244244
245245 - **Take control** (after **Sign in to take control**) joins the queue in
246246 the panel beside the arm. When nobody is driving, you drive at once.
247 - A turn lasts 3 minutes, with a countdown. It ends early when you press
248 **Hand back**, after 30 s with no command, or 10 s after your connection
247 - A turn lasts 3 minutes (the owner can change it), with a countdown. It ends
248 early when you press **Hand back**, after 30 s with no command (also the
249 owner's to change), or 10 s after your connection
249250 drops. The next person in the queue then drives. Someone in the queue
250251 whose connection drops for 10 s leaves it.
251252 - Everyone sees the queue live: who drives, who is next, each place, and
@@ -271,6 +272,41 @@ its live pose and the cameras. Driving needs a forge account and a turn.
271272 the queue, delete messages and mute people. The owner can also press
272273 **Stop** during anyone's turn.
273274
275 **Admin.** The owner runs the room from `/admin` (plain forms, no script),
276 or from the compact **Admin** bar that only the owner sees beside the queue:
277
278 - **Pause the queue** for maintenance. The driver's turn ends (unless it is
279 the owner's), nobody new gets a turn, and everyone sees "Paused for
280 maintenance". People can still join the queue, and it keeps its order.
281 **Resume** gives the arm to whoever is first. The owner can drive while
282 the queue is paused.
283 - **End current turn** gives the arm to the next person in the queue.
284 **Take control now** skips the queue.
285 - **Turn length** (30–3600 s) and **idle timeout** (10–600 s) apply at once,
286 including to the turn in progress.
287 - **Max speed** (5–100 % of full) is a cap added on top of the safety
288 limits. The relay applies it before anything reaches the arm, to exactly
289 these: the `speed` of `/move` and `/pose/go` (the arm's full 1500 ticks/s
290 times the percentage), the `speed` the gripper closes at on `/grip` (the
291 same cap; the grip never goes faster than its own 300 ticks/s), the `rate`
292 of `/play` (2× times the percentage), and how far each joint of a `/follow`
293 stream may travel per second. A stream starts from where the arm reports
294 its joints (`/status`), so its first frame is capped too; under a cap, a
295 joint whose position is not known yet is left out of the frames until it
296 is. `/torque`, `/stop` and recording do not move the arm and are not
297 touched. At 100 % nothing changes.
298 - **Max queue length** (0–100) turns new people away once the queue is
299 full. The owner is never turned away.
300 - **Announcement**: up to 280 characters, shown to everyone at the top of
301 the panel. Leave it empty to remove it.
302
303 The settings take effect at once and survive a restart: they are stored in
304 `$FORGE_APP_DATA/so101/admin.json`. Every change and every owner action
305 (ending a turn, taking control, removing someone from the queue) is
306 appended to `admin.log.jsonl` next to it, with who did it. `/admin` shows
307 the latest entries. Changes are accepted only from the owner, and only from
308 the app's own page.
309
274310 The queue, the countdown and the chat all come over one WebSocket (`/live`):
275311 no polling. The forge says who someone is with a signed `x-forge-identity`
276312 header. The app checks that signature with `FORGE_APP_IDENTITY_KEY` and
Software/so101/bench/fake-serve.ts +2 −1
@@ -7,6 +7,7 @@
77 * sends the arm API, /follow and the cameras there while it answers, and to the simulation when it does not.
88 * Anyone may watch; only the signed-in person whose turn it is may drive (src/lobby.ts). The forge signs who that is
99 * with FORGE_APP_IDENTITY_KEY. Run on one's own machine, away from the forge and with no key, every visitor is the owner.
10 * The owner's settings (pause, turn length, speed cap, announcement) and their log live beside the chat (src/admin.ts).
1011 */
1112 import { mkdirSync, mkdtempSync } from "node:fs";
1213 import { tmpdir } from "node:os";
@@ -41,7 +42,7 @@ try {
4142 }
4243 const identityKey = process.env.FORGE_APP_IDENTITY_KEY ?? "";
4344 const local = !identityKey && !process.env.FORGE_APP_ENV;
44 const lobby = new Lobby({ identityKey, local, chatFile: join(dir, "chat.json"), moderator: new Moderator({ file: join(dir, "crew.json"), model: modelFromEnv(process.env) }) });
45 const lobby = new Lobby({ identityKey, local, chatFile: join(dir, "chat.json"), adminFile: join(dir, "admin.json"), moderator: new Moderator({ file: join(dir, "crew.json"), model: modelFromEnv(process.env) }) });
4546 const leaders = new LeaderCalibrations({ file: join(dir, "leader-calibrations.json") });
4647 const relay = await startRelay({ host, port, simulation: `http://127.0.0.1:${simulation.port}`, remote, problem, lobby, leaders });
4748 const { mode, host: armHost } = relay.link();
Software/so101/src/admin-page.ts added +139
@@ -0,0 +1,139 @@
1 /**
2 * The owner's page, /admin: plain HTML forms that post back to /admin, no script. Rendered from plain data; every
3 * value that came from a person (names, the announcement, the log) is escaped. The style is inline and pinned by
4 * its hash in the page's Content-Security-Policy, which allows nothing else.
5 */
6
7 import { createHash } from "node:crypto";
8 import { ANNOUNCEMENT_CHARS, type AdminSettings, type LogEntry } from "./admin.ts";
9 import type { Who } from "./identity.ts";
10 import type { Snapshot } from "./turns.ts";
11
12 export const esc = (text: string): string => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
13
14 const STYLE = `
15 :root { color-scheme: dark; --bg: #0b0d10; --panel: #0d1117; --fg: #e8eaed; --dim: #9aa4ae; --line: #30363d; --blue: #388bfd; --bad: #f85149; --warn: #d29922; --ok: #3fb950; }
16 * { box-sizing: border-box; }
17 body { margin: 0; background: var(--bg); color: var(--fg); font: 16px/1.5 ui-sans-serif, system-ui, -apple-system, sans-serif; }
18 main { max-width: 44rem; margin: 0 auto; padding: clamp(1.5rem, 5vw, 3.5rem) 1.25rem 4rem; display: grid; gap: 2.5rem; }
19 header { display: grid; gap: .5rem; }
20 h1 { font-size: clamp(1.75rem, 4vw, 2.25rem); line-height: 1.15; margin: 0; letter-spacing: -.01em; }
21 h2 { font-size: .8rem; text-transform: uppercase; letter-spacing: .08em; color: var(--dim); margin: 0 0 1rem; font-weight: 600; }
22 a { color: #58a6ff; }
23 .state { display: flex; flex-wrap: wrap; gap: .5rem 1.25rem; color: var(--dim); font-size: .95rem; }
24 .state b { color: var(--fg); font-weight: 600; }
25 .pill { display: inline-block; padding: .1rem .6rem; border-radius: 999px; border: 1px solid var(--ok); color: var(--ok); font-size: .85rem; font-weight: 600; }
26 .pill.paused { border-color: var(--warn); color: #f2cc60; }
27 .flash { padding: .75rem 1rem; border-radius: 8px; border: 1px solid var(--ok); background: rgba(63,185,80,.08); }
28 .flash.bad { border-color: var(--bad); background: rgba(248,81,73,.08); color: #ffb3ad; }
29 .actions { display: flex; flex-wrap: wrap; gap: .75rem; }
30 .actions form { margin: 0; }
31 button { font: inherit; font-weight: 600; padding: .6rem 1.1rem; min-height: 44px; border-radius: 8px; border: 1px solid var(--line); background: #21262d; color: var(--fg); cursor: pointer; }
32 button:hover { border-color: var(--dim); }
33 button:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px solid var(--blue); outline-offset: 2px; }
34 button.go { background: var(--blue); border-color: var(--blue); color: #fff; }
35 button.danger { border-color: var(--bad); color: #ffb3ad; }
36 button:disabled { opacity: .45; cursor: not-allowed; }
37 .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr)); gap: 1.25rem; }
38 label { display: grid; gap: .35rem; font-weight: 600; font-size: .95rem; }
39 label small { color: var(--dim); font-weight: 400; font-size: .85rem; }
40 input, textarea { font: inherit; padding: .55rem .75rem; border-radius: 8px; border: 1px solid var(--line); background: var(--panel); color: var(--fg); width: 100%; }
41 input { font-variant-numeric: tabular-nums; }
42 textarea { min-height: 5.5rem; resize: vertical; }
43 .wide { grid-column: 1 / -1; }
44 .save { margin-top: 1.25rem; }
45 ol { list-style: none; margin: 0; padding: 0; display: grid; gap: .5rem; font-size: .95rem; }
46 ol li { display: grid; grid-template-columns: 7.5rem 1fr; gap: 1rem; padding-bottom: .5rem; border-bottom: 1px solid var(--line); }
47 time { color: var(--dim); font-variant-numeric: tabular-nums; }
48 .empty { color: var(--dim); }
49 @media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
50 `;
51
52 export const ADMIN_CSP = `default-src 'none'; style-src 'sha256-${createHash("sha256").update(STYLE).digest("base64")}'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'`;
53
54 /** The fixed lines a redirect back may ask for; nothing from the request is echoed. */
55 export const DONE = { saved: "Saved.", paused: "Paused: nobody new gets a turn.", resumed: "Open again: the next in line has control.", ended: "Turn ended.", taken: "You have control." } as const;
56 export type Done = keyof typeof DONE;
57
58 export interface AdminPage {
59 who: Who;
60 settings: AdminSettings;
61 snapshot: Snapshot;
62 log: readonly LogEntry[];
63 done?: Done | null;
64 error?: string | null;
65 }
66
67 const page = (title: string, body: string) => `<!doctype html>
68 <html lang="en">
69 <head>
70 <meta charset="utf-8">
71 <meta name="viewport" content="width=device-width, initial-scale=1">
72 <meta name="robots" content="noindex">
73 <title>${esc(title)}</title>
74 <style>${STYLE}</style>
75 </head>
76 <body>
77 <main>
78 ${body}
79 </main>
80 </body>
81 </html>
82 `;
83
84 /** For anyone who is not the owner. */
85 export function renderRefusal(who: Who): string {
86 const what = who
87 ? `<p>Signed in as ${esc(who.name)}. Only the owner can change how the arm is shared.</p>`
88 : `<p>Only the owner can change how the arm is shared.</p><p><a href="/__forge/signin?to=%2Fadmin">Sign in</a></p>`;
89 return page("Admin · SO-101", `<header><h1>Admin</h1></header><section>${what}<p><a href="/">Back to the arm</a></p></section>`);
90 }
91
92 const time = (at: number) => {
93 const iso = new Date(at).toISOString();
94 return `<time datetime="${iso}">${iso.slice(5, 10)} ${iso.slice(11, 16)}</time>`;
95 };
96
97 const field = (name: keyof AdminSettings, label: string, hint: string, value: number, min: number, max: number) =>
98 `<label>${label}<small>${hint}</small><input name="${name}" type="number" inputmode="numeric" required min="${min}" max="${max}" step="1" value="${value}"></label>`;
99
100 const action = (name: string, text: string, cls = "", disabled = false) =>
101 `<form method="post" action="/admin"><input type="hidden" name="action" value="${name}"><button class="${cls}"${disabled ? " disabled" : ""}>${text}</button></form>`;
102
103 export function renderAdmin(p: AdminPage): string {
104 const s = p.settings;
105 const d = p.snapshot.driver;
106 const mine = d && p.who && d.id === p.who.id;
107 const flash = p.error ? `<p class="flash bad" role="alert">${esc(p.error)}</p>` : p.done ? `<p class="flash" role="status">${DONE[p.done]}</p>` : "";
108 const log = p.log.length
109 ? `<ol>${[...p.log].reverse().map((e) => `<li>${time(e.at)}<span><b>${esc(e.by.name)}</b> ${esc(e.what)}</span></li>`).join("")}</ol>`
110 : `<p class="empty">Nothing yet.</p>`;
111 return page(
112 "Admin · SO-101",
113 `<header>
114 <h1>Admin</h1>
115 <div class="state"><span class="pill${s.paused ? " paused" : ""}">${s.paused ? "Paused" : "Open"}</span><span>${d ? `<b>${esc(d.name)}</b> has control` : "Nobody has control"}</span><span><b>${p.snapshot.queue.length}</b> waiting</span><a href="/">Back to the arm</a></div>
116 </header>
117 ${flash}
118 <section aria-labelledby="now"><h2 id="now">Right now</h2>
119 <div class="actions">
120 ${s.paused ? action("resume", "Resume the queue", "go") : action("pause", "Pause the queue")}
121 ${action("end", d ? `End ${esc(d.name)}'s turn` : "End current turn", "danger", !d)}
122 ${action("take", mine ? "You have control" : "Take control now", "go", Boolean(mine))}
123 </div>
124 </section>
125 <section aria-labelledby="set"><h2 id="set">Settings</h2>
126 <form method="post" action="/admin"><input type="hidden" name="action" value="save">
127 <div class="grid">
128 ${field("turnSeconds", "Turn length", "seconds, 30–3600", s.turnSeconds, 30, 3600)}
129 ${field("idleSeconds", "Idle timeout", "seconds without a command, 10–600", s.idleSeconds, 10, 600)}
130 ${field("maxSpeedPercent", "Max speed", "percent of full, on top of the safety limits", s.maxSpeedPercent, 5, 100)}
131 ${field("maxQueue", "Max queue length", "people waiting, 0–100", s.maxQueue, 0, 100)}
132 <label class="wide">Announcement<small>shown to everyone above the queue; empty for none</small><textarea name="announcement" maxlength="${ANNOUNCEMENT_CHARS}">${esc(s.announcement)}</textarea></label>
133 </div>
134 <div class="save"><button class="go">Save settings</button></div>
135 </form>
136 </section>
137 <section aria-labelledby="log"><h2 id="log">Log</h2>${log}</section>`,
138 );
139 }
Software/so101/src/admin.test.ts added +51
@@ -0,0 +1,51 @@
1 import { describe, expect, test } from "bun:test";
2 import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { Admin, AdminError, changeFromForm, DEFAULT_ADMIN, validateChange } from "./admin.ts";
6
7 const owner = { id: "o", name: "trevato", owner: true };
8 const dir = () => mkdtempSync(join(tmpdir(), "so101-admin-"));
9
10 describe("admin settings", () => {
11 test("every field is checked; unknown ones are refused", () => {
12 expect(validateChange({ turnSeconds: 60, paused: true, announcement: " back at 5 " })).toEqual({ turnSeconds: 60, paused: true, announcement: "back at 5" });
13 expect(() => validateChange({ turnSeconds: 5 })).toThrow("turn length (s) must be a whole number from 30 to 3600");
14 expect(() => validateChange({ maxSpeedPercent: 50.5 })).toThrow(AdminError);
15 expect(() => validateChange({ maxQueue: "3" })).toThrow(AdminError);
16 expect(() => validateChange({ paused: "yes" })).toThrow("paused is true or false");
17 expect(() => validateChange({ announcement: "x".repeat(281) })).toThrow("at most 280");
18 expect(() => validateChange({ isOwner: true })).toThrow('no setting "isOwner"');
19 expect(() => validateChange([])).toThrow(AdminError);
20 expect(validateChange({ announcement: "‮\u0007" })).toEqual({ announcement: "" });
21 });
22
23 test("a form's numbers arrive as text and are read strictly", () => {
24 expect(changeFromForm(new URLSearchParams("turnSeconds=90&idleSeconds=20&maxSpeedPercent=40&maxQueue=5&announcement=hi"))).toEqual({ turnSeconds: 90, idleSeconds: 20, maxSpeedPercent: 40, maxQueue: 5, announcement: "hi" });
25 expect(() => changeFromForm(new URLSearchParams("turnSeconds=1e3"))).toThrow("must be a whole number");
26 expect(() => changeFromForm(new URLSearchParams("maxQueue=-1"))).toThrow(AdminError);
27 });
28
29 test("settings persist, and every change is logged with who made it", () => {
30 const file = join(dir(), "admin.json");
31 const a = new Admin({ file, now: () => 1000 });
32 expect(a.settings).toEqual(DEFAULT_ADMIN);
33 expect(a.set(owner, { paused: true, maxSpeedPercent: 40, turnSeconds: 180 })).toEqual(["paused", "maxSpeedPercent"]);
34 a.record(owner, "ended alice's turn");
35 expect(a.set(owner, { paused: true })).toEqual([]); // no change, nothing logged
36 const b = new Admin({ file });
37 expect(b.settings).toMatchObject({ paused: true, maxSpeedPercent: 40, turnSeconds: 180 });
38 expect(b.log.map((e) => e.what)).toEqual(["paused → true, max speed (%) → 40", "ended alice's turn"]);
39 expect(b.log[0]).toMatchObject({ at: 1000, by: { id: "o", name: "trevato" } });
40 expect(existsSync(file.replace(".json", ".log.jsonl"))).toBe(true);
41 });
42
43 test("a bad stored value costs only that value", () => {
44 const file = join(dir(), "admin.json");
45 writeFileSync(file, JSON.stringify({ turnSeconds: 1, maxQueue: 3, nonsense: 1 }));
46 expect(new Admin({ file }).settings).toMatchObject({ turnSeconds: 180, maxQueue: 3 });
47 writeFileSync(file, "{not json");
48 expect(new Admin({ file }).settings).toEqual(DEFAULT_ADMIN);
49 expect(readFileSync(file, "utf8")).toBe("{not json"); // left for the owner to look at
50 });
51 });
Software/so101/src/admin.ts added +176
@@ -0,0 +1,176 @@
1 /**
2 * The owner's knobs for the room: pause the queue, how long a turn and its idle allowance last, a speed cap on top
3 * of the safety limits, how long the line may grow, and an announcement everyone sees. Validated here, kept in one
4 * JSON file beside the arm's data, and every change (and every owner action) appended to a log with who did it.
5 */
6
7 import { appendFileSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
8 import { dirname } from "node:path";
9 import { cleanText } from "./chat.ts";
10 import type { Person } from "./identity.ts";
11
12 export interface AdminSettings {
13 /** Maintenance: nobody new gets a turn; the owner still may. */
14 paused: boolean;
15 turnSeconds: number;
16 idleSeconds: number;
17 /** A cap on every move, playback and stream, in percent of the arm's full speed. 100 is no extra cap. */
18 maxSpeedPercent: number;
19 /** How many may wait in line. */
20 maxQueue: number;
21 /** Shown to everyone above the queue; empty for none. */
22 announcement: string;
23 }
24
25 export const DEFAULT_ADMIN: AdminSettings = { paused: false, turnSeconds: 180, idleSeconds: 30, maxSpeedPercent: 100, maxQueue: 20, announcement: "" };
26
27 export const ANNOUNCEMENT_CHARS = 280;
28 const RANGES = {
29 turnSeconds: [30, 3600],
30 idleSeconds: [10, 600],
31 maxSpeedPercent: [5, 100],
32 maxQueue: [0, 100],
33 } as const satisfies Partial<Record<keyof AdminSettings, readonly [number, number]>>;
34 const LABELS: Record<keyof AdminSettings, string> = {
35 paused: "paused",
36 turnSeconds: "turn length (s)",
37 idleSeconds: "idle timeout (s)",
38 maxSpeedPercent: "max speed (%)",
39 maxQueue: "max queue length",
40 announcement: "announcement",
41 };
42 const KEEP_LOG = 50;
43
44 export class AdminError extends Error {}
45
46 export interface LogEntry {
47 at: number;
48 by: { id: string; name: string };
49 what: string;
50 }
51
52 /** Check a partial change; throws AdminError naming the first bad field. Unknown fields are refused, not ignored. */
53 export function validateChange(input: unknown): Partial<AdminSettings> {
54 if (typeof input !== "object" || input === null || Array.isArray(input)) throw new AdminError("settings are an object");
55 const out: Partial<AdminSettings> = {};
56 for (const [key, value] of Object.entries(input)) {
57 if (key === "paused") {
58 if (typeof value !== "boolean") throw new AdminError("paused is true or false");
59 out.paused = value;
60 } else if (key === "announcement") {
61 if (typeof value !== "string") throw new AdminError("the announcement is text");
62 if ([...value].length > ANNOUNCEMENT_CHARS) throw new AdminError(`the announcement is at most ${ANNOUNCEMENT_CHARS} characters`);
63 let text = "";
64 try {
65 text = cleanText(value);
66 } catch {
67 /* nothing printable: no announcement */
68 }
69 out.announcement = text;
70 } else if (Object.hasOwn(RANGES, key)) {
71 const k = key as keyof typeof RANGES;
72 const [min, max] = RANGES[k];
73 if (!Number.isInteger(value) || (value as number) < min || (value as number) > max) throw new AdminError(`${LABELS[k]} must be a whole number from ${min} to ${max}`);
74 out[k] = value as number;
75 } else throw new AdminError(`no setting "${key.slice(0, 40)}"`);
76 }
77 return out;
78 }
79
80 /** A change from an HTML form: numbers arrive as text. Only the fields the form has are read. */
81 export function changeFromForm(form: URLSearchParams): Partial<AdminSettings> {
82 const raw: Record<string, unknown> = {};
83 for (const key of Object.keys(RANGES)) {
84 const value = form.get(key);
85 if (value === null) continue;
86 if (!/^\s*\d{1,6}\s*$/.test(value)) throw new AdminError(`${LABELS[key as keyof AdminSettings]} must be a whole number`);
87 raw[key] = Number(value);
88 }
89 const announcement = form.get("announcement");
90 if (announcement !== null) raw.announcement = announcement;
91 return validateChange(raw);
92 }
93
94 export interface AdminOptions {
95 /** Where the settings live; none keeps them in memory. The log goes beside it, as <name>.log.jsonl. */
96 file?: string;
97 now?: () => number;
98 }
99
100 export class Admin {
101 settings: AdminSettings = { ...DEFAULT_ADMIN };
102 /** The most recent entries, oldest first. */
103 readonly log: LogEntry[] = [];
104 private readonly file: string | undefined;
105 private readonly logFile: string | undefined;
106 private readonly now: () => number;
107
108 constructor(options: AdminOptions = {}) {
109 this.file = options.file;
110 this.logFile = options.file?.replace(/(\.json)?$/, ".log.jsonl");
111 this.now = options.now ?? Date.now;
112 if (this.file) this.load();
113 }
114
115 /** Apply a change as `who`; returns the fields that changed (nothing is written when none did). */
116 set(who: Person, input: unknown): Array<keyof AdminSettings> {
117 const change = validateChange(input);
118 const changed = (Object.keys(change) as Array<keyof AdminSettings>).filter((k) => change[k] !== this.settings[k]);
119 if (!changed.length) return [];
120 this.settings = { ...this.settings, ...change };
121 this.save();
122 this.record(who, changed.map((k) => `${LABELS[k]} → ${k === "announcement" ? JSON.stringify(this.settings[k]) : String(this.settings[k])}`).join(", "));
123 return changed;
124 }
125
126 /** Note an owner action (ending a turn, taking control) in the log. */
127 record(who: Person, what: string): void {
128 const entry: LogEntry = { at: this.now(), by: { id: who.id, name: who.name }, what };
129 this.log.push(entry);
130 if (this.log.length > KEEP_LOG) this.log.splice(0, this.log.length - KEEP_LOG);
131 console.log(`admin: ${who.name}: ${what}`);
132 if (!this.logFile) return;
133 try {
134 mkdirSync(dirname(this.logFile), { recursive: true });
135 appendFileSync(this.logFile, `${JSON.stringify(entry)}\n`);
136 } catch (err) {
137 console.error(`admin: could not log to ${this.logFile}: ${err instanceof Error ? err.message : String(err)}`);
138 }
139 }
140
141 private load(): void {
142 try {
143 const stored = JSON.parse(readFileSync(this.file!, "utf8")) as Record<string, unknown>;
144 // Field by field: one bad value must not throw away the rest.
145 for (const [key, value] of Object.entries(stored)) {
146 try {
147 this.settings = { ...this.settings, ...validateChange({ [key]: value }) };
148 } catch (err) {
149 console.error(`admin: ignoring ${key} in ${this.file}: ${(err as Error).message}`);
150 }
151 }
152 } catch {
153 /* none yet, or unreadable: the defaults */
154 }
155 try {
156 const lines = readFileSync(this.logFile!, "utf8").trimEnd().split("\n").slice(-KEEP_LOG);
157 for (const line of lines) {
158 try {
159 const e = JSON.parse(line) as LogEntry;
160 if (typeof e.at === "number" && typeof e.what === "string" && typeof e.by?.id === "string" && typeof e.by?.name === "string") this.log.push(e);
161 } catch {
162 /* skip a torn line */
163 }
164 }
165 } catch {
166 /* no log yet */
167 }
168 }
169
170 private save(): void {
171 if (!this.file) return;
172 mkdirSync(dirname(this.file), { recursive: true });
173 writeFileSync(`${this.file}.tmp`, JSON.stringify(this.settings, null, 1));
174 renameSync(`${this.file}.tmp`, this.file);
175 }
176 }
Software/so101/src/lobby.test.ts +147 −4
@@ -1,8 +1,10 @@
11 import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test";
22 import { mkdtempSync } from "node:fs";
3 import { createServer, type Server } from "node:http";
34 import { tmpdir } from "node:os";
45 import { join } from "node:path";
5 import WebSocket from "ws";
6 import WebSocket, { WebSocketServer } from "ws";
7 import { Admin } from "./admin.ts";
68 import { FeetechBus } from "./bus.ts";
79 import { Chat } from "./chat.ts";
810 import { FakeBus } from "./fake-bus.ts";
@@ -64,9 +66,9 @@ describe("lobby", () => {
6466 lobby?.close();
6567 relay = lobby = undefined;
6668 });
67 const start = async (turns: Turns = new Turns(), chat = new Chat()) => {
68 lobby = new Lobby({ identityKey: KEY, turns, chat });
69 relay = await startRelay({ port: 0, simulation: `http://127.0.0.1:${simulation.port}`, lobby });
69 const start = async (turns?: Turns, chat = new Chat(), admin = new Admin(), upstream = `http://127.0.0.1:${simulation.port}`) => {
70 lobby = new Lobby({ identityKey: KEY, turns: turns ?? new Turns(), chat, admin });
71 relay = await startRelay({ port: 0, simulation: upstream, lobby });
7072 return relay.port;
7173 };
7274 const join = async (port: number, headers: Record<string, string> = {}) => {
@@ -230,4 +232,145 @@ describe("lobby", () => {
230232 const late = await join(port);
231233 expect((await late.first((m) => m.type === "chat")).messages).toEqual([]);
232234 });
235
236 const form = (port: number, fields: Record<string, string>, headers: Record<string, string> = {}) =>
237 fetch(`http://127.0.0.1:${port}/admin`, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded", "sec-fetch-site": "same-origin", ...headers }, body: new URLSearchParams(fields).toString() });
238
239 test("pause stops new turns and everyone sees it; the announcement reaches every watcher", async () => {
240 const port = await start();
241 const anon = await join(port);
242 const alice = await join(port, ALICE);
243 const owner = await join(port, OWNER);
244 expect((await owner.first((m) => m.type === "admin")).settings).toMatchObject({ paused: false, maxSpeedPercent: 100 });
245 alice.send({ type: "join" });
246 await anon.next(drivingIs("alice"));
247 alice.send({ type: "pause", on: true });
248 expect((await alice.next((m) => m.type === "error")).error).toContain("only the owner");
249
250 owner.send({ type: "pause", on: true });
251 const paused = await anon.next((m) => m.type === "state" && m.paused === true && m.driver === null);
252 expect(paused.queue).toEqual([]);
253 expect(anon.heard.some((m) => m.type === "said" && m.message.text === "The arm is paused for maintenance")).toBe(true);
254 expect(anon.heard.some((m) => m.type === "said" && /alice's turn ended \(paused for maintenance\)/.test(m.message.text))).toBe(true);
255 expect((await torque(port, ALICE)).status).toBe(403);
256 alice.send({ type: "join" });
257 expect((await anon.next((m) => m.type === "state" && m.queue.length === 1)).driver).toBeNull();
258
259 owner.send({ type: "settings", set: { announcement: "Back at <b>5</b>", maxSpeedPercent: 50 } });
260 expect(await anon.next((m) => m.type === "state" && m.announcement !== "")).toMatchObject({ announcement: "Back at <b>5</b>", maxSpeedPercent: 50, paused: true });
261 owner.send({ type: "settings", set: { turnSeconds: 1 } });
262 expect((await owner.next((m) => m.type === "error")).error).toContain("from 30 to 3600");
263
264 owner.send({ type: "pause", on: false });
265 await anon.next(drivingIs("alice"));
266 expect((await owner.next((m) => m.type === "admin")).log.map((e: Msg) => e.what)).toEqual(["paused → true", 'announcement → "Back at <b>5</b>", max speed (%) → 50', "paused → false"]);
267 });
268
269 test("/admin is the owner's: end a turn hands to the next, settings persist, every value is escaped", async () => {
270 const file = `${mkdtempSync(`${tmpdir()}/so101-admin-`)}/admin.json`;
271 const port = await start(undefined, new Chat(), new Admin({ file }));
272 const page = (headers: Record<string, string> = {}) => fetch(`http://127.0.0.1:${port}/admin`, { headers });
273 const anonPage = await page();
274 expect(anonPage.status).toBe(401);
275 expect(await anonPage.text()).toContain("/__forge/signin?to=%2Fadmin");
276 expect((await page(ALICE)).status).toBe(403);
277 expect((await form(port, { action: "pause" }, ALICE)).status).toBe(403);
278 expect((await form(port, { action: "pause" }, { ...OWNER, "sec-fetch-site": "cross-site" })).status).toBe(403);
279
280 const alice = await join(port, ALICE);
281 const bob = await join(port, BOB);
282 alice.send({ type: "join" });
283 await bob.next(drivingIs("alice"));
284 bob.send({ type: "join" });
285 await alice.next((m) => m.type === "state" && m.queue.length === 1);
286 const ended = await form(port, { action: "end" }, OWNER);
287 expect(ended.status).toBe(303);
288 expect(ended.headers.get("location")).toBe("/admin?done=ended");
289 await alice.next(drivingIs("bob"));
290
291 const saved = await form(port, { action: "save", turnSeconds: "90", idleSeconds: "20", maxSpeedPercent: "40", maxQueue: "3", announcement: '<script>alert("x")</script>' }, OWNER);
292 expect(saved.status).toBe(303);
293 const bad = await form(port, { action: "save", maxQueue: "lots" }, OWNER);
294 expect(bad.status).toBe(400);
295 expect(await bad.text()).toContain("max queue length must be a whole number");
296 const huge = await form(port, { action: "save", maxQueue: "1", announcement: "x".repeat(20_000) }, OWNER);
297 expect(huge.status).toBe(413); // refused by the bytes read, before any of it is parsed
298 expect(await huge.text()).toContain("that form is too large");
299
300 const ok = await page(OWNER);
301 expect(ok.status).toBe(200);
302 expect(ok.headers.get("content-security-policy")).toMatch(/^default-src 'none'; style-src 'sha256-[A-Za-z0-9+/=]+'/);
303 const html = await ok.text();
304 expect(html).not.toContain("<script");
305 expect(html).toContain("&#60;script&#62;alert(&#34;x&#34;)&#60;/script&#62;");
306 expect(html).toContain('name="maxSpeedPercent" type="number" inputmode="numeric" required min="5" max="100" step="1" value="40"');
307 expect(html).toContain("<b>trevato</b> ended alice&#39;s turn");
308 expect(lobby!.turns.snapshot()).toMatchObject({ turnMs: 90_000, idleMs: 20_000, maxQueue: 3 });
309 expect(new Admin({ file }).settings).toMatchObject({ turnSeconds: 90, idleSeconds: 20, maxSpeedPercent: 40, maxQueue: 3, paused: false });
310 expect((await form(port, { action: "pause" }, OWNER)).status).toBe(303);
311 const restarted = new Lobby({ identityKey: KEY, adminFile: file }); // a restart: the settings come back, the pause included
312 expect(restarted.turns.snapshot()).toMatchObject({ paused: true, turnMs: 90_000, idleMs: 20_000, maxQueue: 3 });
313 expect(restarted.maxSpeedPercent).toBe(40);
314 restarted.close();
315 });
316
317 test("the speed cap clamps commands before they reach the arm", async () => {
318 // An arm that only writes down what it was asked.
319 const bodies: Record<string, any>[] = [];
320 const frames: Record<string, number>[] = [];
321 const arm: Server = createServer((req, res) => {
322 let data = "";
323 req.on("data", (c) => (data += c));
324 req.on("end", () => {
325 if (req.method === "POST") bodies.push({ path: req.url, ...JSON.parse(data || "{}") });
326 res.writeHead(200, { "content-type": "application/json" });
327 // where the arm says its joints are: the stream's cap starts from here
328 res.end(req.url === "/status" ? JSON.stringify({ joints: [{ id: 1, position: 2000 }, { id: 2, position: null }] }) : "{}");
329 });
330 });
331 const armWs = new WebSocketServer({ server: arm, path: "/follow" });
332 armWs.on("connection", (ws) => ws.on("message", (d) => frames.push(JSON.parse(String(d)))));
333 await new Promise<void>((r) => arm.listen(0, "127.0.0.1", r));
334 try {
335 const port = await start(undefined, new Chat(), new Admin(), `http://127.0.0.1:${(arm.address() as { port: number }).port}`);
336 const owner = { id: "u-owner", name: "trevato", owner: true };
337 lobby!.takeControl(owner);
338 lobby!.configure(owner, { maxSpeedPercent: 10 });
339 const post = (path: string, body: unknown) => fetch(`http://127.0.0.1:${port}${path}`, { method: "POST", headers: { "content-type": "application/json", ...OWNER }, body: JSON.stringify(body) });
340 await post("/move", { targets: { 1: 3000 }, speed: 1500 });
341 await post("/pose/go", { name: "home" });
342 await post("/play", { name: "wave", rate: 2 });
343 await post("/grip", { position: 2100, torque: 30 });
344 await post("/torque", { on: true });
345 expect(bodies).toEqual([
346 { path: "/move", targets: { 1: 3000 }, speed: 150 },
347 { path: "/pose/go", name: "home", speed: 150 },
348 { path: "/play", name: "wave", rate: 0.2 },
349 { path: "/grip", position: 2100, torque: 30, speed: 150 },
350 { path: "/torque", on: true },
351 ]);
352
353 const stream = new WebSocket(`ws://127.0.0.1:${port}/follow`, { headers: OWNER });
354 sockets.push(stream);
355 await new Promise((r) => stream.once("open", r));
356 // The leader starts far from where the arm is (2000), and joint 2's position is not known at all.
357 const started = Date.now();
358 for (let i = 0; i < 6; i++) {
359 stream.send('{"1":3900,"2":100}');
360 await sleep(30);
361 }
362 for (let i = 0; i < 50 && frames.length < 3; i++) await sleep(10);
363 const elapsed = (Date.now() - started) / 1000;
364 expect(frames.length).toBeGreaterThan(0);
365 // 10 % of full speed is 150 ticks/s, from the arm's own pose: the first frame is not let through at full speed
366 expect(frames[0]!["1"]!).toBeGreaterThan(2000);
367 expect(frames[0]!["1"]!).toBeLessThanOrEqual(2015);
368 for (const f of frames) expect(f["1"]! - 2000).toBeLessThanOrEqual(15 + 150 * elapsed);
369 expect(frames.every((f) => !("2" in f))).toBe(true); // held back, not sent uncapped
370 } finally {
371 armWs.close();
372 arm.closeAllConnections();
373 arm.close();
374 }
375 });
233376 });
Software/so101/src/lobby.ts +83 −8
@@ -10,17 +10,21 @@
1010 * {"type": "end", "id": "<user id>"} owner: end that turn, or take them out of the line
1111 * {"type": "delete", "id": 12} owner: delete a chat line
1212 * {"type": "mute", "id": "<user id>", "on": true|false} owner
13 * {"type": "pause", "on": true|false} owner: maintenance; nobody new gets a turn
14 * {"type": "settings", "set": {…}} owner: any of src/admin.ts's settings
1315 * {"type": "crew", "settings": {"enabled", "rules", "maxPerMinute"}} owner: the moderator's settings
1416 * {"type": "restore", "id": 12} owner: put back a line the crew hid
1517 * {"type": "dismiss", "id": 12} owner: dismiss a mute suggestion
1618 * {"type": "pong"} the answer to {"type": "ping"}
17 * Server → client: hello (who you are), state (the turn and the line), chat (the log), said, unsaid, muted
18 * (owners only), crew (owners only: settings, hidden lines, mute suggestions), ping, error.
19 * Server → client: hello (who you are), state (the turn, the line, pause, the announcement and the speed cap),
20 * chat (the log), said, unsaid, muted, admin (owners only: the settings and the admin log), crew (owners only:
21 * settings, hidden lines, mute suggestions), ping, error.
1922 */
2023
2124 import type { IncomingMessage } from "node:http";
2225 import type { Duplex } from "node:stream";
2326 import WebSocket, { WebSocketServer } from "ws";
27 import { Admin, AdminError } from "./admin.ts";
2428 import { Chat, ChatError } from "./chat.ts";
2529 import { Moderator } from "./moderator.ts";
2630 import { identify, LOCAL, type Person, type Who } from "./identity.ts";
@@ -33,8 +37,12 @@ export interface LobbyOptions {
3337 local?: boolean;
3438 /** The chat's file; none keeps it in memory. */
3539 chatFile?: string;
40 /** The admin settings' file; none keeps them in memory. */
41 adminFile?: string;
42 /** Given turns keep their own limits until the owner changes one; made here, they start from the admin settings. */
3643 turns?: Turns;
3744 chat?: Chat;
45 admin?: Admin;
3846 /** Checks each posted line in the background; none leaves the chat unchecked. */
3947 moderator?: Moderator;
4048 /** How often each socket is pinged, and how long it may stay silent before it counts as dropped. */
@@ -54,6 +62,7 @@ const USER_ID = /^[A-Za-z0-9_-]{1,64}$/;
5462 export class Lobby {
5563 readonly turns: Turns;
5664 readonly chat: Chat;
65 readonly admin: Admin;
5766 readonly local: boolean;
5867 readonly moderator: Moderator | undefined;
5968 private readonly key: string;
@@ -67,7 +76,10 @@ export class Lobby {
6776 constructor(options: LobbyOptions = {}) {
6877 this.key = options.identityKey ?? "";
6978 this.local = Boolean(options.local);
70 this.turns = options.turns ?? new Turns();
79 this.admin = options.admin ?? new Admin({ file: options.adminFile });
80 const a = this.admin.settings;
81 this.turns = options.turns ?? new Turns({ turnMs: a.turnSeconds * 1000, idleMs: a.idleSeconds * 1000, maxQueue: a.maxQueue });
82 this.turns.setPaused(a.paused);
7183 this.chat = options.chat ?? new Chat({ file: options.chatFile });
7284 this.silentMs = options.silentMs ?? 15_000;
7385 this.moderator = options.moderator;
@@ -114,6 +126,47 @@ export class Lobby {
114126 }
115127 }
116128
129 /** The owner's cap on every move, playback and stream, percent of full speed. */
130 get maxSpeedPercent(): number {
131 return this.admin.settings.maxSpeedPercent;
132 }
133
134 /** The owner changes settings (live, persisted, logged). Throws AdminError for anyone else or a bad value. */
135 configure(who: Who, input: unknown): void {
136 if (!who?.owner) throw new AdminError("only the owner can do that");
137 const changed = this.admin.set(who, input);
138 const s = this.admin.settings;
139 if (changed.some((k) => k === "turnSeconds" || k === "idleSeconds" || k === "maxQueue")) {
140 this.turns.configure({ turnMs: s.turnSeconds * 1000, idleMs: s.idleSeconds * 1000, maxQueue: s.maxQueue });
141 }
142 if (changed.includes("paused")) {
143 this.broadcast({ type: "said", message: this.chat.system(s.paused ? "The arm is paused for maintenance" : "The arm is open again") });
144 this.turns.setPaused(s.paused);
145 }
146 this.broadcastState();
147 this.broadcastAdmin();
148 }
149
150 /** The owner ends whoever drives now. */
151 endTurn(who: Who): void {
152 if (!who?.owner) throw new AdminError("only the owner can do that");
153 const d = this.turns.driver;
154 if (!d) return;
155 this.admin.record(who, `ended ${d.name}'s turn`);
156 this.turns.endCurrent();
157 this.broadcastAdmin();
158 }
159
160 /** Ask to drive; for the owner that is taking control now, and it is logged. */
161 takeControl(who: Person): "driving" | "queued" | "full" {
162 if (who.owner && !this.turns.isDriver(who.id)) {
163 const d = this.turns.driver;
164 this.admin.record(who, d ? `took control from ${d.name}` : "took control");
165 this.broadcastAdmin();
166 }
167 return this.turns.join(who);
168 }
169
117170 /** Called with whoever's turn just ended, for whatever reason: their streams and moves must stop. */
118171 onTurnEnd(listener: (who: Person) => void): () => void {
119172 this.endListeners.add(listener);
@@ -138,10 +191,11 @@ export class Lobby {
138191 this.seats.add(seat);
139192 if (who) this.turns.connect(who.id);
140193 this.send(seat, { type: "hello", you: who, signin: !this.local, muted: who ? this.chat.muted.has(who.id) : false });
141 this.send(seat, { type: "state", ...this.turns.snapshot() });
194 this.send(seat, this.state());
142195 this.send(seat, { type: "chat", messages: this.chat.messages });
143196 if (who?.owner) {
144197 this.send(seat, this.mutedList());
198 this.send(seat, this.adminState());
145199 this.send(seat, this.crewState());
146200 }
147201 ws.on("message", (data, binary) => {
@@ -156,8 +210,9 @@ export class Lobby {
156210 try {
157211 this.handle(seat, message);
158212 } catch (err) {
159 this.send(seat, { type: "error", error: err instanceof ChatError ? err.message : "that did not work" });
160 if (!(err instanceof ChatError)) console.error(`lobby: ${err instanceof Error ? err.message : String(err)}`);
213 const told = err instanceof ChatError || err instanceof AdminError;
214 this.send(seat, { type: "error", error: told ? err.message : "that did not work" });
215 if (!told) console.error(`lobby: ${err instanceof Error ? err.message : String(err)}`);
161216 }
162217 });
163218 ws.on("close", () => {
@@ -175,7 +230,7 @@ export class Lobby {
175230 if (!who) return this.send(seat, { type: "error", error: "sign in to take part" });
176231 switch (m.type) {
177232 case "join":
178 this.turns.join(who);
233 if (this.takeControl(who) === "full") this.send(seat, { type: "error", error: `the line is full (${this.turns.maxQueue}); try again in a little while` });
179234 return;
180235 case "leave":
181236 this.turns.leave(who.id);
@@ -191,8 +246,15 @@ export class Lobby {
191246 switch (m.type) {
192247 case "end":
193248 if (typeof m.id !== "string" || !USER_ID.test(m.id)) return this.send(seat, { type: "error", error: "end whom?" });
249 if (this.turns.isDriver(m.id)) return this.endTurn(who);
250 if (this.turns.queue.some((p) => p.id === m.id)) this.admin.record(who, `took ${this.turns.queue.find((p) => p.id === m.id)!.name} out of the line`);
194251 this.turns.end(m.id);
195252 return;
253 case "pause":
254 if (typeof m.on !== "boolean") return this.send(seat, { type: "error", error: "pause on or off?" });
255 return this.configure(who, { paused: m.on });
256 case "settings":
257 return this.configure(who, m.set);
196258 case "delete":
197259 if (!Number.isSafeInteger(m.id)) return this.send(seat, { type: "error", error: "delete which line?" });
198260 if (this.chat.delete(m.id as number)) this.broadcast({ type: "unsaid", id: m.id });
@@ -241,8 +303,21 @@ export class Lobby {
241303 this.broadcastState();
242304 }
243305
306 private state() {
307 return { type: "state", ...this.turns.snapshot(), announcement: this.admin.settings.announcement, maxSpeedPercent: this.admin.settings.maxSpeedPercent };
308 }
309
244310 private broadcastState(): void {
245 this.broadcast({ type: "state", ...this.turns.snapshot() });
311 this.broadcast(this.state());
312 }
313
314 private adminState() {
315 return { type: "admin", settings: this.admin.settings, log: this.admin.log.slice(-20) };
316 }
317
318 private broadcastAdmin(): void {
319 const text = JSON.stringify(this.adminState());
320 for (const s of this.seats) if (s.who?.owner && s.ws.readyState === WebSocket.OPEN) s.ws.send(text);
246321 }
247322
248323 /** What the crew did, for the owners: its settings, the lines it hid, and who it suggests muting. */
Software/so101/src/relay.ts +109 −9
@@ -10,7 +10,10 @@
1010 * request that is not a read, and the /follow stream, is refused for anyone else before it reaches an arm. When a
1111 * turn ends, that person's streams are closed and whatever they started is stopped.
1212 *
13 * The owner's speed cap (src/speed-cap.ts) is applied here too, to moves, poses, grips, playbacks and every stream frame.
14 *
1315 * WS /live the lobby: the turn, the queue, the chat
16 * GET /admin, POST /admin the owner's page: pause, end a turn, take control, the settings, the log
1417 * GET /link {"mode": "live"|"simulated", "host": "<host:port>"|null, "problem": "…"|null}
1518 * GET /camera/<1|2>/stream the arm machine's camera, one upstream connection shared by every viewer
1619 * (src/camera-feed.ts); the "camera offline" picture when there is none or it is down
@@ -24,11 +27,14 @@ import type { Duplex } from "node:stream";
2427 import { Readable } from "node:stream";
2528 import { pipeline } from "node:stream/promises";
2629 import WebSocket, { WebSocketServer } from "ws";
30 import { AdminError, changeFromForm } from "./admin.ts";
31 import { ADMIN_CSP, DONE, renderAdmin, renderRefusal, type Done } from "./admin-page.ts";
2732 import { CameraFeed, type FeedOptions } from "./camera-feed.ts";
2833 import { LOCAL as LOCAL_PERSON } from "./identity.ts";
2934 import { LeaderCalibrations } from "./leader-calibrations.ts";
3035 import { CalibrationError } from "./leader-map.js";
3136 import type { Lobby } from "./lobby.ts";
37 import { capBody, FrameCap } from "./speed-cap.ts";
3238
3339 export interface Remote {
3440 /** The arm server's HTTP base, no trailing slash. */
@@ -79,6 +85,7 @@ export interface RunningRelay {
7985
8086 const SCHEMES: Record<string, "http:" | "https:"> = { "http:": "http:", "https:": "https:", "ws:": "http:", "wss:": "https:" };
8187 const MAX_BODY = 1_000_000;
88 const MAX_FORM = 16_384;
8289 /** Served from this process whichever arm is live: they describe the app, not the arm. */
8390 const LOCAL = /^\/(?:index\.html|leader-map\.js)?$|^\/(?:model|vendor|printables|app)(?:\/|$)/;
8491 const LEADER = "/leader/calibration";
@@ -191,16 +198,20 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
191198 res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
192199 res.end(JSON.stringify(body));
193200 };
194 const readBody = (req: IncomingMessage) =>
201 /**
202 * A request's body, refused once more than `limit` bytes have come in. Nothing past the limit is kept: the rest is
203 * read and dropped, so the refusal can still be answered, and the answer closes the connection.
204 */
205 const readBody = (req: IncomingMessage, limit = MAX_BODY) =>
195206 new Promise<Buffer>((resolve, reject) => {
196207 const chunks: Buffer[] = [];
197208 let size = 0;
198209 req.on("data", (c: Buffer) => {
199210 size += c.length;
200 if (size > MAX_BODY) {
201 req.destroy();
202 reject(new Error("body too large"));
203 } else chunks.push(c);
211 if (size <= limit) return void chunks.push(c);
212 req.removeAllListeners("data");
213 req.resume();
214 reject(new Error("body too large"));
204215 });
205216 req.on("end", () => resolve(Buffer.concat(chunks)));
206217 req.on("error", reject);
@@ -241,6 +252,60 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
241252 }
242253 };
243254
255 /** The owner's page. Anyone else is told so; a change is a form post, answered with a redirect back. */
256 const admin = async (lobby: Lobby, req: IncomingMessage, res: ServerResponse, url: URL) => {
257 const who = lobby.who(req);
258 const html = (status: number, text: string) => {
259 res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "content-security-policy": ADMIN_CSP });
260 res.end(text);
261 };
262 if (!who?.owner) return html(who ? 403 : 401, renderRefusal(who));
263 const show = (status: number, done: Done | null, error: string | null) =>
264 html(status, renderAdmin({ who, settings: lobby.admin.settings, snapshot: lobby.turns.snapshot(), log: lobby.admin.log, done, error }));
265 if (req.method === "GET" || req.method === "HEAD") {
266 const done = url.searchParams.get("done");
267 return show(200, done && Object.hasOwn(DONE, done) ? (done as Done) : null, null);
268 }
269 if (req.method !== "POST") return json(res, 405, { error: "GET or POST" });
270 let body: Buffer;
271 try {
272 body = await readBody(req, MAX_FORM);
273 } catch {
274 res.setHeader("connection", "close");
275 return show(413, null, "that form is too large");
276 }
277 const form = new URLSearchParams(body.toString("utf8"));
278 let done: Done;
279 try {
280 switch (form.get("action")) {
281 case "save":
282 lobby.configure(who, changeFromForm(form));
283 done = "saved";
284 break;
285 case "pause":
286 case "resume":
287 lobby.configure(who, { paused: form.get("action") === "pause" });
288 done = form.get("action") === "pause" ? "paused" : "resumed";
289 break;
290 case "end":
291 lobby.endTurn(who);
292 done = "ended";
293 break;
294 case "take":
295 lobby.takeControl(who);
296 done = "taken";
297 break;
298 default:
299 throw new AdminError("no such action");
300 }
301 } catch (err) {
302 if (err instanceof AdminError) return show(400, null, err.message);
303 throw err;
304 }
305 res.writeHead(303, { location: `/admin?done=${done}`, "cache-control": "no-store" });
306 res.end();
307 };
308
244309 /** A person's own calibration: signed in is enough, it never touches the arm. */
245310 const leaderCalibration = async (req: IncomingMessage, res: ServerResponse) => {
246311 const who = lobby ? lobby.who(req) : LOCAL_PERSON;
@@ -276,6 +341,7 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
276341 const path = url.pathname + url.search;
277342 const reading = req.method === "GET" || req.method === "HEAD";
278343 if (!reading && !sameOrigin(req)) return json(res, 403, { error: "only this page may change the arm" });
344 if (lobby && url.pathname === "/admin") return await admin(lobby, req, res, url);
279345 if (url.pathname === LEADER) return await leaderCalibration(req, res);
280346 if (!reading && lobby) {
281347 const who = lobby.who(req);
@@ -299,7 +365,8 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
299365 }
300366 }
301367
302 const body = reading ? undefined : await readBody(req);
368 const raw = reading ? undefined : await readBody(req);
369 const body = raw && lobby ? capBody(url.pathname, raw, lobby.maxSpeedPercent) : raw;
303370 if (LOCAL.test(url.pathname) || !live || !remote) return await pass(res, await ask(simulation + path, req, body, null, false));
304371 try {
305372 // A read must answer fast or fall back; a move or a playback answers when the arm arrives, and is only cut when the link is.
@@ -337,19 +404,49 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
337404 const sendable = (code: number) => (code >= 1000 && code <= 1003) || (code >= 1007 && code <= 1014) || (code >= 3000 && code <= 4999);
338405 /** Each open /follow stream and whose it is, so a turn that ends can close it. */
339406 const streams = new Map<WebSocket, string>();
340 const bridge = (browser: WebSocket, arm: WebSocket, driver: string | null) => {
407 /** `base` is the arm server's HTTP side, asked where the joints are so the speed cap starts from there. */
408 const bridge = (browser: WebSocket, arm: WebSocket, base: string, driver: string | null) => {
341409 if (driver !== null) {
342410 streams.set(browser, driver);
343411 browser.on("close", () => streams.delete(browser));
344412 }
345413 arm.on("message", (data, binary) => browser.readyState === WebSocket.OPEN && browser.send(data, { binary }));
414 const cap = new FrameCap();
415 let seeded = false;
416 let asking = false;
417 let askedAt = 0;
418 /** Where the arm is, once at the start and again (at most once a second) while a cap holds a joint back for want of it. */
419 const seed = () => {
420 if (!lobby || seeded || asking || Date.now() - askedAt < 1000) return;
421 asking = true;
422 askedAt = Date.now();
423 fetch(`${base}/status`, { signal: AbortSignal.timeout(readTimeoutMs), cache: "no-store" })
424 .then((r) => r.json() as Promise<{ joints?: Array<{ id?: unknown; position?: unknown }> }>)
425 .then(({ joints }) => {
426 const known = (joints ?? []).filter((j) => Number.isInteger(j.id) && typeof j.position === "number");
427 cap.seed(known.map((j) => [String(j.id), j.position as number] as const));
428 seeded = known.length > 0;
429 })
430 .catch(() => {})
431 .finally(() => (asking = false));
432 };
433 seed();
346434 browser.on("message", (data, binary) => {
347435 if (driver !== null) {
348436 // The turn may have ended while this frame was on its way, before the close reaches the page: it is not passed on.
349437 if (lobby && !lobby.turns.isDriver(driver) && !lobby.local) return;
350438 lobby?.activity(driver);
351439 }
352 if (arm.readyState === WebSocket.OPEN) arm.send(data, { binary });
440 if (arm.readyState !== WebSocket.OPEN) return;
441 const percent = lobby?.maxSpeedPercent ?? 100;
442 if (percent >= 100) {
443 if (lobby) cap.cap(String(data), percent); // keeps each joint's last target, so a cap set mid-stream starts from there
444 arm.send(data, { binary });
445 return;
446 }
447 if (!seeded) seed();
448 const capped = cap.cap(String(data), percent);
449 if (capped !== null) arm.send(capped);
353450 });
354451 arm.on("close", (code, why) => browser.close(sendable(code) ? code : 1011, why.length ? why.toString() : "the arm server went away"));
355452 browser.on("close", () => arm.close());
@@ -375,19 +472,22 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
375472 }
376473 void (async () => {
377474 let arm: WebSocket;
475 let base: string;
378476 try {
379477 if (!remote || !live) throw null;
380478 arm = await open(`${remote.ws}/follow`, readTimeoutMs);
479 base = remote.http;
381480 } catch (err) {
382481 if (err) down(reason(err));
383482 try {
384483 arm = await open(`${simulationWs}/follow`, readTimeoutMs);
484 base = simulation;
385485 } catch {
386486 return refuse(socket, "502 Bad Gateway");
387487 }
388488 }
389489 if (socket.destroyed) return arm.close();
390 wss.handleUpgrade(req, socket, head, (browser) => bridge(browser, arm, driver));
490 wss.handleUpgrade(req, socket, head, (browser) => bridge(browser, arm, base, driver));
391491 })();
392492 });
393493
Software/so101/src/server.test.ts +6
@@ -131,6 +131,12 @@ describe("moves over HTTP", () => {
131131 const memory = fake.servos.get(6)!;
132132 expect(memory[48]! + memory[49]! * 256).toBe(300); // Torque_Limit 30 %
133133 expect(memory[40]).toBe(1); // Torque_Enable
134 expect(memory[46]! + memory[47]! * 256).toBe(300); // Goal_Velocity: the default
135 await post("/grip", { position: 2000, speed: 150 });
136 expect(memory[46]! + memory[47]! * 256).toBe(150); // slower when asked (the owner's speed cap asks)
137 await post("/grip", { position: 2000, speed: 1500 });
138 expect(memory[46]! + memory[47]! * 256).toBe(300); // never faster than it always was
139 expect((await post("/grip", { position: 2000, speed: "fast" })).status).toBe(400);
134140 });
135141
136142 test("/stop with nothing running is harmless", async () => {
Software/so101/src/server.ts +3 −2
@@ -10,7 +10,7 @@
1010 * POST /pose/delete {"name": "he1"}
1111 * POST /pose/go {"name": "home", "speed"?: 300, "torque"?: 70, "release"?: false}
1212 * POST /move {"targets": {"3": 2048}, "speed"?, "torque"?, "release"?} supervised, any joints
13 * POST /grip {"position": 2000, "torque": 30} close the gripper toward a position at a low torque cap and hold
13 * POST /grip {"position": 2000, "torque": 30, "speed"?: 300} close the gripper toward a position at a low torque cap and hold
1414 * POST /torque {"on": true|false}
1515 * POST /stop end whatever drives the arm: a move, a playback, a recording, or a stream; the arm holds
1616 * GET /recordings the saved recordings with their length
@@ -592,13 +592,14 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
592592 if (!Number.isInteger(body.position)) throw new HttpError(400, "position must be an integer");
593593 const position = clamp(body.position as number, lim.min + margin, lim.max - margin);
594594 const torque = number(body.torque, 30, 10, 60, "torque");
595 const speed = Math.round(number(body.speed, 300, 20, 300, "speed"));
595596 claim("move");
596597 try {
597598 const present = await bus.syncRead([id], STS3215.Present_Position);
598599 if (!present.has(id)) throw new HttpError(409, "no response from the gripper");
599600 await bus.syncWrite(STS3215.Goal_Position, [[id, present.get(id)!]]);
600601 await bus.syncWrite(STS3215.Torque_Limit, [[id, Math.round(torque * 10)]]); // stays low while it holds; the next supervised gripper move puts the ceiling back
601 await bus.syncWrite(STS3215.Goal_Velocity, [[id, 300]]);
602 await bus.syncWrite(STS3215.Goal_Velocity, [[id, speed]]);
602603 await bus.syncWrite(STS3215.Torque_Enable, [[id, 1]]);
603604 await bus.syncWrite(STS3215.Goal_Position, [[id, position]]);
604605 } finally {
Software/so101/src/speed-cap.test.ts added +58
@@ -0,0 +1,58 @@
1 import { describe, expect, test } from "bun:test";
2 import { capBody, FrameCap } from "./speed-cap.ts";
3
4 const body = (o: unknown) => Buffer.from(JSON.stringify(o));
5 const read = (b: Buffer) => JSON.parse(b.toString());
6
7 describe("speed cap", () => {
8 test("a move's speed and a playback's rate are brought under the cap", () => {
9 expect(read(capBody("/move", body({ targets: { 1: 2048 }, speed: 1500 }), 20))).toEqual({ targets: { 1: 2048 }, speed: 300 });
10 expect(read(capBody("/pose/go", body({ name: "home" }), 10))).toEqual({ name: "home", speed: 150 }); // the default 300 is capped too
11 expect(read(capBody("/move", body({ targets: {}, speed: 100 }), 50))).toMatchObject({ speed: 100 }); // already slower
12 expect(read(capBody("/play", body({ name: "wave", rate: 2 }), 25))).toEqual({ name: "wave", rate: 0.5 });
13 expect(read(capBody("/play", body({ name: "wave" }), 5))).toEqual({ name: "wave", rate: 0.1 });
14 expect(read(capBody("/grip", body({ position: 2000, torque: 30 }), 10))).toEqual({ position: 2000, torque: 30, speed: 150 });
15 expect(read(capBody("/grip", body({ position: 2000 }), 50))).toEqual({ position: 2000, speed: 300 }); // its own 300 is under the cap
16 });
17
18 test("at 100 %, on other routes, or for a body it cannot read, nothing changes", () => {
19 const fast = body({ targets: { 1: 2048 }, speed: 1500 });
20 expect(capBody("/move", fast, 100)).toBe(fast);
21 const torque = body({ on: true });
22 expect(capBody("/torque", torque, 10)).toBe(torque);
23 const odd = Buffer.from("{nope");
24 expect(capBody("/move", odd, 10)).toBe(odd);
25 const typed = body({ speed: "fast" });
26 expect(capBody("/move", typed, 10)).toBe(typed);
27 });
28
29 test("a stream's joints travel at most the capped speed between frames, from where the arm is", () => {
30 const cap = new FrameCap();
31 cap.seed([["1", 2000], ["2", 1000]]);
32 // the first frame, however far from the arm: the first step is counted as 100 ms, 10 % of 1500 ticks/s is 15 ticks
33 expect(JSON.parse(cap.cap('{"1":3900,"2":100}', 10, 1000)!)).toEqual({ "1": 2015, "2": 985 });
34 // 50 ms: 7.5 ticks
35 expect(JSON.parse(cap.cap('{"1":2400,"2":990}', 10, 1050)!)).toEqual({ "1": 2022, "2": 990 });
36 // a long gap counts as 100 ms, never more: no jump after a pause
37 expect(JSON.parse(cap.cap('{"1":2400}', 10, 6000)!)).toEqual({ "1": 2037 });
38 expect(cap.cap("not json", 10, 6100)).toBe("not json");
39 });
40
41 test("under a cap, a joint the arm has not reported is held back, not sent at full speed", () => {
42 const cap = new FrameCap();
43 expect(cap.cap('{"1":3900}', 10, 0)).toBeNull();
44 cap.seed([["1", 2000]]);
45 expect(cap.knows("1")).toBe(true);
46 expect(cap.knows("2")).toBe(false);
47 expect(JSON.parse(cap.cap('{"1":3900,"2":100}', 10, 100)!)).toEqual({ "1": 2015 });
48 // a seed never pulls back a joint the stream has already moved
49 cap.seed([["1", 0]]);
50 expect(JSON.parse(cap.cap('{"1":3900}', 10, 200)!)).toEqual({ "1": 2030 });
51 });
52
53 test("at 100 % frames pass untouched", () => {
54 const cap = new FrameCap();
55 cap.cap('{"1":2000}', 100, 0);
56 expect(cap.cap('{"1":3000}', 100, 30)).toBe('{"1":3000}');
57 });
58 });
Software/so101/src/speed-cap.ts added +96
@@ -0,0 +1,96 @@
1 /**
2 * The owner's speed cap, applied in the relay before anything reaches an arm, on top of the arm server's own limits.
3 * One percent scales everything that moves the arm: a supervised move's or a pose's speed, the gripper's closing speed,
4 * a playback's rate, and how far each joint of a /follow stream may travel per second. At 100 nothing is touched.
5 */
6
7 /** The arm server's fastest supervised move, ticks/s (src/server.ts clamps `speed` to this). */
8 export const FULL_SPEED = 1500;
9 /** Its default move speed, when a request names none. */
10 export const DEFAULT_SPEED = 300;
11 /** Its fastest playback rate. */
12 export const FULL_RATE = 2;
13
14 /** The routes with a `speed` in ticks/s. /grip never closes faster than DEFAULT_SPEED, so it shares the default. */
15 const MOVES = new Set(["/move", "/pose/go", "/grip"]);
16
17 /** A request body with its speed (or rate) brought under the cap; anything it cannot read passes as is, for the arm server to refuse. */
18 export function capBody(pathname: string, body: Buffer, percent: number): Buffer {
19 if (percent >= 100 || (!MOVES.has(pathname) && pathname !== "/play")) return body;
20 let parsed: unknown;
21 try {
22 parsed = JSON.parse(body.toString("utf8") || "{}");
23 } catch {
24 return body;
25 }
26 if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return body;
27 const b = parsed as Record<string, unknown>;
28 if (MOVES.has(pathname)) {
29 if (b.speed !== undefined && typeof b.speed !== "number") return body;
30 b.speed = Math.min((b.speed as number | undefined) ?? DEFAULT_SPEED, Math.max(20, Math.round((FULL_SPEED * percent) / 100)));
31 } else {
32 if (b.rate !== undefined && typeof b.rate !== "number") return body;
33 b.rate = Math.min((b.rate as number | undefined) ?? 1, Math.max(0.1, (FULL_RATE * percent) / 100));
34 }
35 return Buffer.from(JSON.stringify(b));
36 }
37
38 /**
39 * Per stream: each joint's target may move at most the capped speed times the time since the last frame (counted
40 * between 5 and 100 ms, so a pause in the frames never buys a jump). It starts from where the arm says it is
41 * (`seed`); under a cap, a joint whose position is not known yet is held back from the frame rather than sent at
42 * full speed. At 100 frames pass as they are, and are remembered, so a cap set mid-stream starts from there.
43 */
44 export class FrameCap {
45 private readonly last = new Map<string, number>();
46 private lastAt = 0;
47
48 /** Where the arm reports its joints; a joint the stream has already moved keeps its own last target. */
49 seed(positions: Iterable<readonly [string, number]>): void {
50 for (const [id, p] of positions) if (Number.isFinite(p) && !this.last.has(id)) this.last.set(id, Math.round(p));
51 }
52
53 /** Whether a joint's position is known, from the arm or from an earlier frame. */
54 knows(id: string): boolean {
55 return this.last.has(id);
56 }
57
58 /**
59 * The frame to send on, as text, or null when every joint it names is held back. A frame that is not a JSON
60 * object passes unchanged, for the arm server to refuse.
61 */
62 cap(text: string, percent: number, now = Date.now()): string | null {
63 let frame: unknown;
64 try {
65 frame = JSON.parse(text);
66 } catch {
67 return text;
68 }
69 if (typeof frame !== "object" || frame === null || Array.isArray(frame)) return text;
70 const dt = Math.min(0.1, Math.max(0.005, (now - this.lastAt) / 1000));
71 this.lastAt = now;
72 const step = Math.max(1, (FULL_SPEED * percent * dt) / 100);
73 const out: Record<string, unknown> = {};
74 let held = 0;
75 for (const [id, value] of Object.entries(frame)) {
76 if (typeof value !== "number" || !Number.isFinite(value)) {
77 out[id] = value;
78 continue;
79 }
80 const previous = this.last.get(id);
81 let next = Math.round(value);
82 if (percent < 100) {
83 if (previous === undefined) {
84 held++;
85 continue;
86 }
87 const d = Math.max(-step, Math.min(step, value - previous));
88 next = previous + Math.sign(d) * Math.floor(Math.abs(d)); // never past the cap
89 }
90 out[id] = next;
91 this.last.set(id, next);
92 }
93 if (percent >= 100) return text;
94 return held && !Object.keys(out).length ? null : JSON.stringify(out);
95 }
96 }
Software/so101/src/turns.test.ts +67
@@ -122,4 +122,71 @@ describe("turns", () => {
122122 turns.end("b"); // out of the line
123123 expect(turns.queue).toEqual([]);
124124 });
125
126 test("paused: nobody new gets a turn and the line keeps its order; resuming hands over to the head", () => {
127 const events = make();
128 turns.join(alice);
129 turns.join(bob);
130 turns.setPaused(true);
131 expect(turns.driver).toBeNull();
132 expect(events.at(-1)).toEqual({ kind: "turn", ended: { who: alice, reason: "paused for maintenance" }, started: null });
133 expect(turns.join(carol)).toBe("queued");
134 advance(200_000);
135 expect(turns.driver).toBeNull();
136 expect(turns.snapshot()).toMatchObject({ paused: true, queue: [{ id: "b" }, { id: "c" }] });
137 expect(turns.join(owner)).toBe("driving"); // maintenance is the owner's
138 turns.leave("o");
139 expect(turns.driver).toBeNull();
140 turns.setPaused(false);
141 expect(turns.driver?.id).toBe("b");
142 expect(turns.queue.map((p) => p.id)).toEqual(["c"]);
143 });
144
145 test("pausing keeps the owner's own turn", () => {
146 make();
147 turns.join(owner);
148 turns.setPaused(true);
149 expect(turns.driver?.id).toBe("o");
150 });
151
152 test("ending the current turn hands the arm to the next in line", () => {
153 const events = make();
154 expect(turns.endCurrent()).toBe(false);
155 turns.join(alice);
156 turns.join(bob);
157 expect(turns.endCurrent()).toBe(true);
158 expect(turns.driver?.id).toBe("b");
159 expect(events.at(-1)).toEqual({ kind: "turn", ended: { who: alice, reason: "ended by the owner" }, started: bob });
160 });
161
162 test("a full line turns people away, never the owner; a shorter limit keeps who is already in", () => {
163 make();
164 turns.configure({ maxQueue: 1 });
165 turns.join(alice);
166 expect(turns.join(bob)).toBe("queued");
167 expect(turns.join(carol)).toBe("full");
168 expect(turns.join(bob)).toBe("queued");
169 turns.configure({ maxQueue: 0 });
170 expect(turns.queue.map((p) => p.id)).toEqual(["b"]);
171 expect(turns.join(owner)).toBe("driving");
172 });
173
174 test("a new turn length and idle timeout apply to the turn under way", () => {
175 make();
176 turns.join(alice);
177 turns.join(bob);
178 for (const ms of [20_000, 20_000, 10_000]) {
179 advance(ms);
180 turns.activity("a");
181 }
182 turns.configure({ turnMs: 60_000, idleMs: 5_000 });
183 expect(turns.snapshot()).toMatchObject({ turnMs: 60_000, idleMs: 5_000, driver: { id: "a", endsAt: 1_060_000 } });
184 advance(5_000);
185 expect(turns.driver).toMatchObject({ id: "b", endsAt: 1_055_000 + 60_000 });
186 turns.configure({ turnMs: 30_000 });
187 expect(turns.driver?.endsAt).toBe(1_055_000 + 30_000);
188 clock += 2_000;
189 turns.configure({ turnMs: 1_000 }); // already past it: over at once
190 expect(turns.driver).toBeNull();
191 });
125192 });
Software/so101/src/turns.ts +51 −10
@@ -4,6 +4,8 @@
44 * A turn lasts `turnMs`. It ends early when the driver hands back, sends nothing for `idleMs`, or has had no
55 * connection for `graceMs`; someone waiting in line who loses their connection for `graceMs` leaves the line.
66 * The owner jumps the line: asking to drive ends whoever drives now. The owner can also end anyone's turn.
7 * Paused (maintenance), nobody new gets a turn but the owner, and the line keeps its order for when it resumes;
8 * the line holds at most `maxQueue`. Turn length and idle allowance change live, the current turn included.
79 * Plain state and deadlines; one timer, set to the nearest deadline, runs `check()`.
810 */
911
@@ -15,7 +17,7 @@ export interface Turn extends Person {
1517 lastActive: number;
1618 }
1719
18 export type EndReason = "handed back" | "time is up" | "idle" | "disconnected" | "ended by the owner" | "taken over by the owner";
20 export type EndReason = "handed back" | "time is up" | "idle" | "disconnected" | "ended by the owner" | "taken over by the owner" | "paused for maintenance";
1921
2022 export type TurnEvent = { kind: "turn"; ended: { who: Person; reason: EndReason } | null; started: Person | null } | { kind: "queue" };
2123
@@ -23,6 +25,8 @@ export interface Snapshot {
2325 now: number;
2426 turnMs: number;
2527 idleMs: number;
28 paused: boolean;
29 maxQueue: number;
2630 driver: { id: string; name: string; owner: boolean; endsAt: number; idleEndsAt: number } | null;
2731 queue: Array<{ id: string; name: string; place: number; waitMs: number }>;
2832 }
@@ -31,13 +35,17 @@ export interface TurnsOptions {
3135 turnMs?: number;
3236 idleMs?: number;
3337 graceMs?: number;
38 maxQueue?: number;
39 paused?: boolean;
3440 now?: () => number;
3541 }
3642
3743 export class Turns {
38 readonly turnMs: number;
39 readonly idleMs: number;
44 turnMs: number;
45 idleMs: number;
4046 readonly graceMs: number;
47 maxQueue: number;
48 paused: boolean;
4149 private readonly now: () => number;
4250 driver: Turn | null = null;
4351 readonly queue: Person[] = [];
@@ -51,6 +59,8 @@ export class Turns {
5159 this.turnMs = options.turnMs ?? 180_000;
5260 this.idleMs = options.idleMs ?? 30_000;
5361 this.graceMs = options.graceMs ?? 10_000;
62 this.maxQueue = options.maxQueue ?? Infinity;
63 this.paused = options.paused ?? false;
5464 this.now = options.now ?? Date.now;
5565 }
5666
@@ -63,20 +73,49 @@ export class Turns {
6373 return this.driver?.id === id;
6474 }
6575
66 /** Ask to drive: drive now when nobody does, the owner takes over, everyone else gets in line. */
67 join(who: Person): "driving" | "queued" {
76 /** Ask to drive: drive now when nobody does, the owner takes over, everyone else gets in line (unless it is full). */
77 join(who: Person): "driving" | "queued" | "full" {
6878 if (this.isDriver(who.id)) return "driving";
69 if (who.owner && this.driver) {
79 if (who.owner) {
7080 this.remove(who.id);
71 this.handOver("taken over by the owner", who);
81 this.handOver(this.driver ? "taken over by the owner" : null, who);
7282 return "driving";
7383 }
74 if (!this.queue.some((p) => p.id === who.id)) this.queue.push({ ...who });
75 if (!this.driver) this.handOver(null);
84 if (!this.queue.some((p) => p.id === who.id)) {
85 if ((this.driver || this.paused) && this.queue.length >= this.maxQueue) return "full";
86 this.queue.push({ ...who });
87 }
88 if (!this.driver && !this.paused) this.handOver(null);
7689 else this.emit({ kind: "queue" });
7790 return this.isDriver(who.id) ? "driving" : "queued";
7891 }
7992
93 /** The owner ends whoever drives now. */
94 endCurrent(): boolean {
95 if (!this.driver) return false;
96 this.handOver("ended by the owner");
97 return true;
98 }
99
100 /** Maintenance on or off. Pausing ends anyone's turn but the owner's; resuming hands the arm to the head of the line. */
101 setPaused(on: boolean): void {
102 if (this.paused === on) return;
103 this.paused = on;
104 if (on && this.driver && !this.driver.owner) this.handOver("paused for maintenance");
105 else if (!on && !this.driver) this.handOver(null);
106 else this.emit({ kind: "queue" });
107 }
108
109 /** New limits, live: the current turn is measured against them at once. Someone already in a longer line keeps their place. */
110 configure(limits: { turnMs?: number; idleMs?: number; maxQueue?: number }): void {
111 if (limits.turnMs !== undefined) this.turnMs = limits.turnMs;
112 if (limits.idleMs !== undefined) this.idleMs = limits.idleMs;
113 if (limits.maxQueue !== undefined) this.maxQueue = limits.maxQueue;
114 if (this.driver) this.driver.endsAt = this.driver.startedAt + this.turnMs;
115 this.check();
116 this.emit({ kind: "queue" });
117 }
118
80119 /** Hand back the turn, or leave the line. */
81120 leave(id: string): void {
82121 if (this.isDriver(id)) return this.handOver("handed back");
@@ -133,6 +172,8 @@ export class Turns {
133172 now,
134173 turnMs: this.turnMs,
135174 idleMs: this.idleMs,
175 paused: this.paused,
176 maxQueue: Number.isFinite(this.maxQueue) ? this.maxQueue : -1,
136177 driver: d ? { id: d.id, name: d.name, owner: d.owner, endsAt: d.endsAt, idleEndsAt: Math.min(d.endsAt, d.lastActive + this.idleMs) } : null,
137178 // At most: a turn can end early, never late.
138179 queue: this.queue.map((p, i) => ({ id: p.id, name: p.name, place: i + 1, waitMs: left + i * this.turnMs })),
@@ -156,7 +197,7 @@ export class Turns {
156197 const ended = this.driver && reason ? { who: { id: this.driver.id, name: this.driver.name, owner: this.driver.owner }, reason } : null;
157198 if (reason) this.driver = null;
158199 if (this.driver) return;
159 const who = next ?? this.queue.shift();
200 const who = next ?? (this.paused ? undefined : this.queue.shift());
160201 const now = this.now();
161202 this.driver = who ? { ...who, startedAt: now, endsAt: now + this.turnMs, lastActive: now } : null;
162203 this.emit({ kind: "turn", ended, started: who ?? null });
Software/so101/src/viewer.html +58 −5
@@ -102,6 +102,18 @@
102102 #say { display: flex; gap: 6px; padding: 8px 12px calc(8px + env(safe-area-inset-bottom)); border-top: 1px solid var(--line); }
103103 #say input { flex: 1; min-width: 0; font: inherit; padding: 6px 10px; border-radius: 6px; border: 1px solid var(--line); background: var(--bg); color: var(--fg); }
104104 #sayNote { color: var(--dim); font-size: 12px; padding: 0 12px 8px; } #sayNote:empty { display: none; }
105 #notice { padding: 10px 12px 10px 10px; border-bottom: 1px solid var(--line); border-left: 3px solid var(--blue); background: rgba(56,139,253,.1); font-size: 13px; line-height: 1.45; overflow-wrap: anywhere; }
106 #notice[hidden], #adminBar[hidden] { display: none; }
107 #driverLine.paused { color: #f2cc60; font-weight: 600; }
108 #capLine { color: var(--dim); font-size: 12px; } #capLine:empty { display: none; }
109 #adminBar { border: 1px solid var(--line); border-radius: 8px; padding: 6px 8px; display: grid; gap: 8px; font-size: 13px; }
110 #adminBar .head { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; } #adminBar .head b { color: var(--dim); font-size: 11px; text-transform: uppercase; letter-spacing: .06em; margin-right: auto; }
111 #adminBar details summary { cursor: pointer; color: var(--dim); }
112 #adminForm { display: grid; grid-template-columns: 1fr 1fr; gap: 6px 8px; margin-top: 6px; }
113 #adminForm label { display: grid; gap: 2px; color: var(--dim); font-size: 12px; }
114 #adminForm input { font: inherit; padding: 4px 8px; border-radius: 6px; border: 1px solid var(--line); background: var(--bg); color: var(--fg); min-width: 0; font-variant-numeric: tabular-nums; }
115 #adminForm .wide { grid-column: 1 / -1; }
116 #adminForm .row { grid-column: 1 / -1; display: flex; gap: 8px; align-items: center; }
105117 /* the leader calibration: a card over the stage, so the 3D model can show the pose to copy */
106118 #leaderDlg { position: absolute; left: 12px; top: 12px; margin: 0; z-index: 8; width: min(400px, calc(100% - 24px)); max-height: calc(100% - 24px); overflow: auto; }
107119 #lcRead { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px 10px; margin: 10px 0; font-size: 12px; color: var(--dim); font-variant-numeric: tabular-nums; }
@@ -249,10 +261,25 @@
249261 </dialog>
250262 </div>
251263 <aside id="side" hidden aria-label="Control and chat">
264 <div id="notice" role="status" hidden></div>
252265 <section id="turn" aria-live="polite">
253266 <div id="driverLine" class="none">Connecting…</div>
254267 <div id="clock"></div>
268 <div id="capLine"></div>
255269 <div class="row" id="turnActions"></div>
270 <div id="adminBar" hidden aria-label="Admin">
271 <div class="head"><b>Admin</b><button id="pauseBtn"></button><a href="/admin">Admin page</a></div>
272 <details><summary>Settings</summary>
273 <form id="adminForm">
274 <label>Turn length, s<input name="turnSeconds" type="number" inputmode="numeric" min="30" max="3600" step="1" required></label>
275 <label>Idle timeout, s<input name="idleSeconds" type="number" inputmode="numeric" min="10" max="600" step="1" required></label>
276 <label>Max speed, %<input name="maxSpeedPercent" type="number" inputmode="numeric" min="5" max="100" step="1" required></label>
277 <label>Max queue<input name="maxQueue" type="number" inputmode="numeric" min="0" max="100" step="1" required></label>
278 <label class="wide">Announcement<input name="announcement" maxlength="280" autocomplete="off" placeholder="none"></label>
279 <div class="row"><button class="go">Save</button></div>
280 </form>
281 </details>
282 </div>
256283 <ol id="queue" aria-label="Queue"></ol>
257284 <div id="mutedLine"></div>
258285 <div id="crewLine" aria-live="polite"></div>
@@ -765,7 +792,7 @@
765792 // ---------------------------------------------------------------- the room: the turn, the queue and the chat over /live
766793 // Behind the hosted app's relay only the person whose turn it is may drive, and the server refuses everyone else.
767794 // The page follows suit: the controls are inert until it is your turn. Everything here arrives on one socket.
768 const lobby = { ws: null, hello: null, state: null, offset: 0, retry: 500, mutedList: [] };
795 const lobby = { ws: null, hello: null, state: null, offset: 0, retry: 500, mutedList: [], admin: null };
769796 function mayDrive() { return !relayed || (lobby.hello !== null && (!lobby.hello.signin || (lobby.hello.you !== null && lobby.state?.driver?.id === lobby.hello.you.id))); }
770797 function isOwner() { return !relayed || Boolean(lobby.hello?.you?.owner); }
771798 const say = (m) => { if (lobby.ws?.readyState === 1) lobby.ws.send(JSON.stringify(m)); };
@@ -782,7 +809,7 @@
782809 function tickClock() {
783810 const d = lobby.state?.driver, c = $("clock");
784811 if (!lobby.state || !lobby.hello?.signin) return void (c.textContent = lobby.hello && !lobby.hello.signin ? "Local: no sign-in, every visitor drives." : "");
785 if (!d) { c.className = ""; c.textContent = "Free: take control to drive."; return; }
812 if (!d) { c.className = ""; c.textContent = lobby.state.paused ? "No new turns until the owner resumes; you can still join the queue." : "Free: take control to drive."; return; }
786813 const now = serverNow(), idle = d.idleEndsAt - now;
787814 const idleSoon = idle < 15000 && d.idleEndsAt < d.endsAt;
788815 c.className = idleSoon ? "idle" : "";
@@ -793,8 +820,11 @@
793820 const st = lobby.state, me = lobby.hello?.you ?? null;
794821 if (!st || !lobby.hello) return;
795822 const d = st.driver;
796 $("driverLine").className = d ? "" : "none";
797 $("driverLine").textContent = d ? (me && d.id === me.id ? "You have control" : `${d.name} has control`) : "Nobody has control";
823 $("driverLine").className = st.paused ? "paused" : d ? "" : "none";
824 $("driverLine").textContent = (st.paused ? "Paused for maintenance" + (d ? " · " : "") : "") + (d ? (me && d.id === me.id ? "You have control" : `${d.name} has control`) : st.paused ? "" : "Nobody has control");
825 $("notice").hidden = !st.announcement;
826 $("notice").textContent = st.announcement ?? "";
827 $("capLine").textContent = st.maxSpeedPercent < 100 ? `Speed limited to ${st.maxSpeedPercent}% of full` : "";
798828 const button = (textContent, className, onclick) => el("button", { textContent, className, onclick });
799829 const queued = me && st.queue.some((q) => q.id === me.id);
800830 const actions = [];
@@ -802,7 +832,7 @@
802832 else if (!me) actions.push(el("a", { className: "btn", href: `/__forge/signin?to=${encodeURIComponent(location.pathname + location.search)}`, textContent: "Sign in to take control" }));
803833 else if (d?.id === me.id) actions.push(button("Hand back", "", () => say({ type: "leave" })));
804834 else if (queued) actions.push(button("Leave the queue", "", () => say({ type: "leave" })));
805 else if (me) actions.push(button(me.owner && d ? "Take control now" : "Take control", "go", () => say({ type: "join" })));
835 else if (me) actions.push(button(me.owner && d ? "Take control now" : st.paused && !me.owner ? "Join the queue" : "Take control", "go", () => say({ type: "join" })));
806836 if (me?.owner && d && d.id !== me.id) actions.push(button(`End ${d.name}'s turn`, "danger", () => say({ type: "end", id: d.id })));
807837 $("turnActions").replaceChildren(...actions);
808838 $("queue").replaceChildren(...st.queue.map((q) => {
@@ -812,6 +842,12 @@
812842 return li;
813843 }));
814844 $("mutedLine").replaceChildren(...(me?.owner && lobby.mutedList.length ? ["Muted: ", ...lobby.mutedList.flatMap((m) => [el("span", { textContent: `${m.name} ` }), button("unmute", "x", () => say({ type: "mute", id: m.id, on: false }))])] : []));
845 $("adminBar").hidden = !me?.owner;
846 if (me?.owner) {
847 $("pauseBtn").textContent = st.paused ? "Resume the queue" : "Pause the queue";
848 $("pauseBtn").className = st.paused ? "go" : "";
849 $("pauseBtn").onclick = () => say({ type: "pause", on: !st.paused });
850 }
815851 renderCrew(me);
816852 $("say").hidden = !me || lobby.hello.muted;
817853 $("sayNote").textContent = !lobby.hello.signin ? "" : !me ? "Sign in to chat." : lobby.hello.muted ? "The owner has muted you." : "";
@@ -866,6 +902,7 @@
866902 else if (m.type === "said") return addChat([m.message]);
867903 else if (m.type === "unsaid") return chatBox.querySelector(`[data-id="${Number(m.id)}"]`)?.remove();
868904 else if (m.type === "muted") lobby.mutedList = m.muted;
905 else if (m.type === "admin") { const saved = lobby.admin !== null; lobby.admin = m; fillAdmin(saved); }
869906 else if (m.type === "crew") lobby.crew = m;
870907 else if (m.type === "error") return msg(m.error, true);
871908 renderTurn();
@@ -879,6 +916,22 @@
879916 lobby.retry = Math.min(lobby.retry * 2, 8000);
880917 };
881918 }
919 // The owner's settings: filled from the server whenever they change, unless the owner is typing in the form.
920 function fillAdmin(saved) {
921 const form = $("adminForm");
922 if (!lobby.admin || form.contains(document.activeElement)) return;
923 for (const [k, v] of Object.entries(lobby.admin.settings)) if (form.elements[k]) form.elements[k].value = v;
924 if (saved && form.dataset.sent) { delete form.dataset.sent; msg("settings saved"); }
925 }
926 $("adminForm").onsubmit = (e) => {
927 e.preventDefault();
928 const f = $("adminForm").elements;
929 const set = { announcement: f.announcement.value };
930 for (const k of ["turnSeconds", "idleSeconds", "maxSpeedPercent", "maxQueue"]) set[k] = Number(f[k].value);
931 $("adminForm").dataset.sent = "1";
932 document.activeElement?.blur();
933 say({ type: "settings", set });
934 };
882935 $("say").onsubmit = (e) => {
883936 e.preventDefault();
884937 const text = $("sayText").value.trim();

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs