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

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

Admin: the owner is the app's admin, can name moderators, and every setting lives on one admin page #46

Closed opened this in answer to
Closed without merging

smith/arm:smith/12-admin-the-owner-is-the-app-s-admin-can-n → main 11 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +228 −17
.gitignore +14
@@ -5,3 +5,17 @@ node_modules/
55 poses.json
66 outputs/
77 __pycache__/
8
9 # sandbox home-directory placeholders: never part of the app
10 /.bash_profile
11 /.bashrc
12 /.zshrc
13 /.zprofile
14 /.profile
15 /.gitconfig
16 /.gitmodules
17 /.mcp.json
18 /.ripgreprc
19 /.idea
20 /.vscode
21 /.claude/
Software/README.md +11
@@ -342,6 +342,17 @@ or from the **Admin** tab that only the owner sees:
342342 full. The owner is never turned away.
343343 - **Announcement**: up to 280 characters, shown to everyone at the top of
344344 the panel. Leave it empty to remove it.
345 - **Arm server**: where the arm and its cameras are (`http://host:port`,
346 checked as `ARM_SERVER` is). The relay follows it at once for every viewer
347 (it shows in `/link`; the camera list is the owner's own); empty uses the
348 `ARM_SERVER` environment variable, then the simulation.
349 - **Moderators**: usernames the owner names on `/admin`. A moderator can open
350 `/admin` and read the settings and the log, and change nothing. A moderator
351 is matched on the forge-signed identity (the forge username), never on a
352 name a guest typed: a guest who picks a moderator's name still gets a 403.
353 Settings are web-only because this app has no terminal (`forge.json` has no
354 `tty`); the `so101` command line drives the arm hardware and does not run
355 the relay.
345356
346357 The settings take effect at once and survive a restart: they are stored in
347358 `$FORGE_APP_DATA/so101/admin.json`. Every change and every owner action
Software/so101/src/admin-page.ts +19 −11
@@ -43,8 +43,9 @@ textarea { min-height: 5.5rem; resize: vertical; }
4343 .wide { grid-column: 1 / -1; }
4444 .save { margin-top: 1.25rem; }
4545 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); }
46 ol li { display: grid; grid-template-columns: 7.5rem 1fr; overflow-wrap: anywhere; gap: 1rem; padding-bottom: .5rem; border-bottom: 1px solid var(--line); }
4747 time { color: var(--dim); font-variant-numeric: tabular-nums; }
48 .inline { display: inline; margin: 0; }
4849 .empty { color: var(--dim); }
4950 @media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
5051 `;
@@ -57,6 +58,8 @@ export type Done = keyof typeof DONE;
5758
5859 export interface AdminPage {
5960 who: Who;
61 /** The owner may change things; a moderator only looks. */
62 canEdit: boolean;
6063 settings: AdminSettings;
6164 snapshot: Snapshot;
6265 log: readonly LogEntry[];
@@ -94,8 +97,8 @@ const time = (at: number) => {
9497 return `<time datetime="${iso}">${iso.slice(5, 10)} ${iso.slice(11, 16)}</time>`;
9598 };
9699
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>`;
100 const field = (name: keyof AdminSettings, label: string, hint: string, value: number, min: number, max: number, off: string) =>
101 `<label>${label}<small>${hint}</small><input name="${name}" type="number" inputmode="numeric" required min="${min}" max="${max}" step="1" value="${value}"${off}></label>`;
99102
100103 const action = (name: string, text: string, cls = "", disabled = false) =>
101104 `<form method="post" action="/admin"><input type="hidden" name="action" value="${name}"><button class="${cls}"${disabled ? " disabled" : ""}>${text}</button></form>`;
@@ -104,6 +107,9 @@ export function renderAdmin(p: AdminPage): string {
104107 const s = p.settings;
105108 const d = p.snapshot.driver;
106109 const mine = d && p.who && d.id === p.who.id;
110 const off = p.canEdit ? "" : " disabled";
111 const mods = `<ul>${s.moderators.map((m) => `<li>${esc(m)}${p.canEdit ? ` <form method="post" action="/admin" class="inline"><input type="hidden" name="action" value="mod-remove"><input type="hidden" name="name" value="${esc(m)}"><button aria-label="Remove moderator ${esc(m)}">Remove</button></form>` : ""}</li>`).join("") || "<li class=\"empty\">none</li>"}</ul>` +
112 (p.canEdit ? `<form method="post" action="/admin"><input type="hidden" name="action" value="mod-add"><label>Add a moderator<small>a username; moderators can look at this page and change nothing</small><input name="name" required maxlength="64"></label><div class="save"><button>Add</button></div></form>` : "");
107113 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>` : "";
108114 const log = p.log.length
109115 ? `<ol>${[...p.log].reverse().map((e) => `<li>${time(e.at)}<span><b>${esc(e.by.name)}</b> ${esc(e.what)}</span></li>`).join("")}</ol>`
@@ -117,23 +123,25 @@ export function renderAdmin(p: AdminPage): string {
117123 ${flash}
118124 <section aria-labelledby="now"><h2 id="now">Right now</h2>
119125 <div class="actions">
120 ${s.paused ? action("resume", "Resume the queue", "go") : action("pause", "Pause the queue")}
126 ${p.canEdit ? `${s.paused ? action("resume", "Resume the queue", "go") : action("pause", "Pause the queue")}
121127 ${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))}
128 ${action("take", mine ? "You have control" : "Take control now", "go", Boolean(mine))}` : `<p class="empty">${esc(p.who?.name ?? "")} is a moderator: this page is read-only.</p>`}
123129 </div>
124130 </section>
125131 <section aria-labelledby="set"><h2 id="set">Settings</h2>
126132 <form method="post" action="/admin"><input type="hidden" name="action" value="save">
127133 <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>
134 ${field("turnSeconds", "Turn length", "seconds, 30–3600", s.turnSeconds, 30, 3600, off)}
135 ${field("idleSeconds", "Idle timeout", "seconds without a command, 10–600", s.idleSeconds, 10, 600, off)}
136 ${field("maxSpeedPercent", "Max speed", "percent of full, on top of the safety limits", s.maxSpeedPercent, 5, 100, off)}
137 ${field("maxQueue", "Max queue length", "people waiting, 0–100", s.maxQueue, 0, 100, off)}
138 <label class="wide">Announcement<small>shown to everyone above the queue; empty for none</small><textarea name="announcement" maxlength="${ANNOUNCEMENT_CHARS}"${off}>${esc(s.announcement)}</textarea></label>
139 <label class="wide">Arm server<small>where the arm and its cameras are, http://host:port; empty uses ARM_SERVER from the environment, else the simulation; takes effect at once</small><input name="armServer" maxlength="200" value="${esc(s.armServer)}"${off}></label>
133140 </div>
134 <div class="save"><button class="go">Save settings</button></div>
141 ${p.canEdit ? `<div class="save"><button class="go">Save settings</button></div>` : ""}
135142 </form>
136143 </section>
144 <section aria-labelledby="mods"><h2 id="mods">Moderators</h2>${mods}</section>
137145 <section aria-labelledby="log"><h2 id="log">Log</h2>${log}</section>`,
138146 );
139147 }
Software/so101/src/admin-relay.test.ts added +103
@@ -0,0 +1,103 @@
1 import { afterEach, expect, test } from "bun:test";
2 import { mkdtempSync, rmSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { validateChange } from "./admin.ts";
6 import { sign } from "./identity.ts";
7 import { Lobby } from "./lobby.ts";
8 import { startRelay, type RunningRelay } from "./relay.ts";
9
10 const KEY = "k".repeat(64);
11 const later = Date.now() + 600_000;
12 const as = (name: string, role: "user" | "admin") => {
13 const identity = `id-${name}|${name}|${role}|${later}`;
14 return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
15 };
16 const form = (headers: Record<string, string>, body: Record<string, string>) => ({ method: "POST", headers: { ...headers, "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(body), redirect: "manual" as const });
17
18 let dir = "";
19 let relay: RunningRelay | undefined;
20 let lobby: Lobby | undefined;
21 afterEach(async () => {
22 await relay?.close();
23 lobby?.close();
24 if (dir) rmSync(dir, { recursive: true, force: true });
25 dir = "";
26 relay = lobby = undefined;
27 });
28
29 async function boot() {
30 dir ||= mkdtempSync(join(tmpdir(), "so101-admin-relay-"));
31 lobby = new Lobby({ identityKey: KEY, adminFile: join(dir, "admin.json") });
32 relay = await startRelay({ port: 0, simulation: "http://127.0.0.1:1", lobby });
33 return `http://127.0.0.1:${relay.port}`;
34 }
35
36 test("the new settings are checked", () => {
37 expect(validateChange({ armServer: " http://127.0.0.1:9 " })).toEqual({ armServer: "http://127.0.0.1:9" });
38 expect(validateChange({ armServer: "" })).toEqual({ armServer: "" });
39 expect(() => validateChange({ armServer: "ftp://x" })).toThrow();
40 expect(validateChange({ moderators: ["Bob", "bob", "eve"] })).toEqual({ moderators: ["bob", "eve"] });
41 expect(() => validateChange({ moderators: ["a b"] })).toThrow();
42 expect(() => validateChange({ moderators: "bob" })).toThrow();
43 });
44
45 test("a moderator looks at /admin and changes nothing; the owner names and removes moderators; it persists", async () => {
46 dir = mkdtempSync(join(tmpdir(), "so101-admin-relay-"));
47 let base = await boot();
48 const owner = as("trevato", "admin");
49 const bob = as("bob", "user");
50 expect((await fetch(`${base}/admin`, { headers: bob })).status).toBe(403);
51 expect((await fetch(`${base}/admin`, form(owner, { action: "mod-add", name: "Bob" }))).status).toBe(303);
52 const seen = await fetch(`${base}/admin`, { headers: bob });
53 expect(seen.status).toBe(200);
54 expect(await seen.text()).toContain("read-only");
55 expect((await fetch(`${base}/admin`, form(bob, { action: "pause" }))).status).toBe(403);
56 expect((await fetch(`${base}/admin`, form(bob, { action: "mod-add", name: "eve" }))).status).toBe(403);
57 expect((await fetch(`${base}/admin`, { headers: as("eve", "user") })).status).toBe(403);
58
59 await relay!.close();
60 lobby!.close();
61 base = await boot();
62 expect((await fetch(`${base}/admin`, { headers: bob })).status).toBe(200);
63 const html = await (await fetch(`${base}/admin`, { headers: owner })).text();
64 expect(html).toContain("moderators → bob");
65 await fetch(`${base}/admin`, form(owner, { action: "mod-remove", name: "bob" }));
66 expect((await fetch(`${base}/admin`, { headers: bob })).status).toBe(403);
67 });
68
69 test("the arm server set on /admin is the one the relay uses, at once; a bad one is refused", async () => {
70 dir = mkdtempSync(join(tmpdir(), "so101-admin-relay-"));
71 const base = await boot();
72 const owner = as("trevato", "admin");
73 expect(relay!.link().host).toBeNull();
74 const bad = await fetch(`${base}/admin`, form(owner, { action: "save", armServer: "<script>x</script>" }));
75 expect(bad.status).toBe(400);
76 expect(await bad.text()).not.toContain("<script>x");
77 await fetch(`${base}/admin`, form(owner, { action: "save", armServer: "http://127.0.0.1:1" }));
78 expect(relay!.link().host).toBe("127.0.0.1:1");
79 expect(relay!.link().mode).toBe("simulated");
80 await fetch(`${base}/admin`, form(owner, { action: "save", armServer: "" }));
81 expect(relay!.link().host).toBeNull();
82 });
83
84 test("a guest who types a moderator's name is not that moderator; the Remove buttons say whom they remove", async () => {
85 const base = await boot();
86 const owner = as("trevato", "admin");
87 await fetch(`${base}/admin`, form(owner, { action: "mod-add", name: "bob" }));
88 const joined = await fetch(`${base}/join`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: "bob" }) });
89 expect(joined.status).toBe(200);
90 const cookie = joined.headers.get("set-cookie")!.split(";")[0]!;
91 expect((await fetch(`${base}/admin`, { headers: { cookie } })).status).toBe(403);
92 expect((await fetch(`${base}/admin`, { headers: as("bob", "user") })).status).toBe(200);
93 expect(await (await fetch(`${base}/admin`, { headers: owner })).text()).toContain('aria-label="Remove moderator bob"');
94 });
95
96 test("reading /link never changes anything; the arm server switches when the setting does", async () => {
97 const base = await boot();
98 const owner = as("trevato", "admin");
99 await fetch(`${base}/admin`, form(owner, { action: "save", armServer: "http://127.0.0.1:1" }));
100 const after = await (await fetch(`${base}/link`)).json();
101 expect(after.host).toBe("127.0.0.1:1");
102 expect(await (await fetch(`${base}/link`)).json()).toEqual(after);
103 });
Software/so101/src/admin.ts +35 −2
@@ -8,6 +8,7 @@ import { appendFileSync, mkdirSync, readFileSync, renameSync, writeFileSync } fr
88 import { dirname } from "node:path";
99 import { cleanText } from "./chat.ts";
1010 import type { Person } from "./identity.ts";
11 import { parseRemote } from "./relay.ts";
1112
1213 export interface AdminSettings {
1314 /** Maintenance: nobody new gets a turn; the owner still may. */
@@ -20,9 +21,16 @@ export interface AdminSettings {
2021 maxQueue: number;
2122 /** Shown to everyone above the queue; empty for none. */
2223 announcement: string;
24 /** Where the arm and its cameras are (http://host:port); empty uses ARM_SERVER from the environment, else the simulation. */
25 armServer: string;
26 /** Usernames (lowercase) who may see /admin but change nothing. */
27 moderators: string[];
2328 }
2429
25 export const DEFAULT_ADMIN: AdminSettings = { paused: false, turnSeconds: 180, idleSeconds: 30, maxSpeedPercent: 100, maxQueue: 20, announcement: "" };
30 export const DEFAULT_ADMIN: AdminSettings = { paused: false, turnSeconds: 180, idleSeconds: 30, maxSpeedPercent: 100, maxQueue: 20, announcement: "", armServer: "", moderators: [] };
31
32 const NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
33 export const MAX_MODERATORS = 50;
2634
2735 export const ANNOUNCEMENT_CHARS = 280;
2836 const RANGES = {
@@ -38,6 +46,8 @@ const LABELS: Record<keyof AdminSettings, string> = {
3846 maxSpeedPercent: "max speed (%)",
3947 maxQueue: "max queue length",
4048 announcement: "announcement",
49 armServer: "arm server",
50 moderators: "moderators",
4151 };
4252 const KEEP_LOG = 50;
4353
@@ -67,6 +77,22 @@ export function validateChange(input: unknown): Partial<AdminSettings> {
6777 /* nothing printable: no announcement */
6878 }
6979 out.announcement = text;
80 } else if (key === "armServer") {
81 if (typeof value !== "string") throw new AdminError("the arm server is an address");
82 const text = value.trim();
83 if (text) {
84 try {
85 parseRemote({ ARM_SERVER: text });
86 } catch (err) {
87 throw new AdminError((err as Error).message);
88 }
89 }
90 out.armServer = text;
91 } else if (key === "moderators") {
92 if (!Array.isArray(value) || !value.every((m) => typeof m === "string" && NAME.test(m.trim()))) throw new AdminError("a username is letters, digits, _ . -");
93 const names = [...new Set(value.map((m: string) => m.trim().toLowerCase()))];
94 if (names.length > MAX_MODERATORS) throw new AdminError(`at most ${MAX_MODERATORS} moderators`);
95 out.moderators = names;
7096 } else if (Object.hasOwn(RANGES, key)) {
7197 const k = key as keyof typeof RANGES;
7298 const [min, max] = RANGES[k];
@@ -88,6 +114,8 @@ export function changeFromForm(form: URLSearchParams): Partial<AdminSettings> {
88114 }
89115 const announcement = form.get("announcement");
90116 if (announcement !== null) raw.announcement = announcement;
117 const armServer = form.get("armServer");
118 if (armServer !== null) raw.armServer = armServer;
91119 return validateChange(raw);
92120 }
93121
@@ -115,7 +143,7 @@ export class Admin {
115143 /** Apply a change as `who`; returns the fields that changed (nothing is written when none did). */
116144 set(who: Person, input: unknown): Array<keyof AdminSettings> {
117145 const change = validateChange(input);
118 const changed = (Object.keys(change) as Array<keyof AdminSettings>).filter((k) => change[k] !== this.settings[k]);
146 const changed = (Object.keys(change) as Array<keyof AdminSettings>).filter((k) => JSON.stringify(change[k]) !== JSON.stringify(this.settings[k]));
119147 if (!changed.length) return [];
120148 this.settings = { ...this.settings, ...change };
121149 this.save();
@@ -123,6 +151,11 @@ export class Admin {
123151 return changed;
124152 }
125153
154 /** Whether this person may look at the admin page without changing anything. */
155 isModerator(name: string): boolean {
156 return this.settings.moderators.includes(name.toLowerCase());
157 }
158
126159 /** Note an owner action (ending a turn, taking control) in the log. */
127160 record(who: Person, what: string): void {
128161 const entry: LogEntry = { at: this.now(), by: { id: who.id, name: who.name }, what };
Software/so101/src/lobby.ts +13
@@ -80,6 +80,7 @@ export class Lobby {
8080 private readonly key: string;
8181 private readonly wss = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME });
8282 private readonly seats = new Set<Seat>();
83 private readonly changeListeners = new Set<() => void>();
8384 private readonly endListeners = new Set<(who: Person) => void>();
8485 private readonly pinger: ReturnType<typeof setInterval>;
8586 private readonly silentMs: number;
@@ -124,6 +125,11 @@ export class Lobby {
124125 return this.accounts.byToken(from.token, from);
125126 }
126127
128 /** The forge-signed identity behind this request, or null: a guest's chosen name proves nothing, so it never counts here. */
129 verified(req: IncomingMessage): Person | null {
130 return this.local ? LOCAL : identify(req.headers, this.key);
131 }
132
127133 /** Whether this person, or anyone where they are, is banned. The owner never is. */
128134 barred(who: Person, from: Visitor | null): boolean {
129135 return !who.owner && !this.local && this.accounts.banned(who.id, who.name, from?.ip ?? null);
@@ -171,6 +177,7 @@ export class Lobby {
171177 }
172178 this.broadcastState();
173179 this.broadcastAdmin();
180 if (changed.length) for (const listener of this.changeListeners) listener();
174181 }
175182
176183 /** The owner ends whoever drives now. */
@@ -193,6 +200,12 @@ export class Lobby {
193200 return this.turns.join(who);
194201 }
195202
203 /** Told once each time the owner's settings change. */
204 onSettingsChange(listener: () => void): () => void {
205 this.changeListeners.add(listener);
206 return () => this.changeListeners.delete(listener);
207 }
208
196209 /** Called with whoever's turn just ended, for whatever reason: their streams and moves must stop. */
197210 onTurnEnd(listener: (who: Person) => void): () => void {
198211 this.endListeners.add(listener);
Software/so101/src/relay.ts +33 −4
@@ -183,7 +183,10 @@ const reason = (err: unknown) => {
183183 };
184184
185185 export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
186 const remote = options.remote ?? null;
186 /** The arm server in use: the admin's setting when it names one, else the one the environment gave. */
187 let remote = options.remote ?? null;
188 const environment = remote;
189 let named = "";
187190 const simulation = options.simulation.replace(/\/+$/, "");
188191 const simulationWs = simulation.replace(/^http/, "ws");
189192 const probeTimeoutMs = options.probeTimeoutMs ?? 1500;
@@ -226,6 +229,18 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
226229 probing = null;
227230 }
228231 })());
232 /** Follow the admin's arm server setting: a change cuts what is in flight and probes the new address at once. */
233 const follow = () => {
234 if (!lobby) return;
235 const address = lobby.admin.settings.armServer;
236 if (address === named) return;
237 named = address;
238 remote = address ? parseRemote({ ARM_SERVER: address }) : environment;
239 live = false;
240 problem = null;
241 for (const c of inFlight) c.abort(new Error("the arm server was changed"));
242 if (remote) void probe();
243 };
229244 const link = (): Link => ({ mode: live ? "live" : "simulated", host: remote?.host ?? null, problem });
230245 const source = () => (live && remote ? `live ${remote.host}` : `simulated: ${problem ?? "ARM_SERVER is not set"}`);
231246
@@ -351,14 +366,17 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
351366 res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "content-security-policy": ADMIN_CSP });
352367 res.end(text);
353368 };
354 if (!who?.owner) return html(who ? 403 : 401, renderRefusal(who));
369 const canEdit = Boolean(who?.owner);
370 // a moderator is named by forge username and must hold that forge identity: a guest who types the same name is not them
371 if (!who || !(canEdit || (lobby.verified(req)?.id === who.id && lobby.admin.isModerator(who.name)))) return html(who ? 403 : 401, renderRefusal(who));
355372 const show = (status: number, done: Done | null, error: string | null) =>
356 html(status, renderAdmin({ who, settings: lobby.admin.settings, snapshot: lobby.turns.snapshot(), log: lobby.admin.log, done, error }));
373 html(status, renderAdmin({ who, canEdit, settings: lobby.admin.settings, snapshot: lobby.turns.snapshot(), log: lobby.admin.log, done, error }));
357374 if (req.method === "GET" || req.method === "HEAD") {
358375 const done = url.searchParams.get("done");
359376 return show(200, done && Object.hasOwn(DONE, done) ? (done as Done) : null, null);
360377 }
361378 if (req.method !== "POST") return json(res, 405, { error: "GET or POST" });
379 if (!canEdit) return html(403, renderRefusal(who));
362380 let body: Buffer;
363381 try {
364382 body = await readBody(req, MAX_FORM);
@@ -374,6 +392,14 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
374392 lobby.configure(who, changeFromForm(form));
375393 done = "saved";
376394 break;
395 case "mod-add":
396 case "mod-remove": {
397 const name = (form.get("name") ?? "").trim().toLowerCase();
398 const now = lobby.admin.settings.moderators;
399 lobby.configure(who, { moderators: form.get("action") === "mod-add" ? [...now, name] : now.filter((m) => m !== name) });
400 done = "saved";
401 break;
402 }
377403 case "pause":
378404 case "resume":
379405 lobby.configure(who, { paused: form.get("action") === "pause" });
@@ -645,6 +671,7 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
645671
646672 // ------------------------------------------------------------------ a turn that ends
647673 // Its streams close (the arm server holds the arm when a stream ends) and a move, playback or recording stops.
674 const settingsChanged = lobby?.onSettingsChange(follow);
648675 const turnEnded = lobby?.onTurnEnd((who) => {
649676 for (const [browser, id] of streams) if (id === who.id) browser.close(1000, "your turn ended");
650677 const base = remote && live ? remote.http : simulation;
@@ -655,8 +682,9 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
655682 });
656683
657684 // ------------------------------------------------------------------ start
685 follow();
658686 if (remote) await probe(); // bounded by the probe timeout: the first page already knows which arm it has
659 const timer = remote ? setInterval(() => void probe(), probeEveryMs) : undefined;
687 const timer = remote || lobby ? setInterval(() => (follow(), remote && void probe()), probeEveryMs) : undefined;
660688 timer?.unref?.();
661689 await new Promise<void>((resolve) => http.listen(options.port ?? 8102, options.host ?? "127.0.0.1", resolve));
662690 const address = http.address();
@@ -666,6 +694,7 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
666694 close: () =>
667695 new Promise<void>((resolve) => {
668696 clearInterval(timer);
697 settingsChanged?.();
669698 turnEnded?.();
670699 if (!options.cameras) cameras.close();
671700 for (const c of inFlight) c.abort();

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs