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

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

TOP: a restart never costs you control - reconnect in a second, keep your turn and queue place, and the arm holds still meanwhile #217

Parked opened this in answer to
Closed without merging

vesper/arm:vesper/202-top-a-restart-never-costs-you-control-re → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
19 files changed +658 −25
Software/README.md +10
@@ -408,6 +408,16 @@ its live pose and the cameras. Driving needs a name and a turn.
408408 - Chat: everyone reads. Everyone who joined posts one message every 2 s, up to
409409 500 characters. The last 200 messages are kept in
410410 `$FORGE_APP_DATA/so101/chat.json`. Driver changes appear as grey lines.
411 - A restart (a deploy, the forge rolling) costs nobody their turn. The turn
412 and the queue are written to `$FORGE_APP_DATA/so101/turns.json` on every
413 change and STOP's hold to `relay-held.json`; both are restored on start.
414 The page reconnects by itself (0.25, 0.5, 1, then every 2 s) and shows
415 "reconnecting…", with driving off, until the server says where the turn
416 stands. The same cookie is the same person: the driver drives again until
417 their turn's own end, and the queue keeps its order. Everyone gets the usual
418 10 s grace to come back. While the app is away nothing reaches the arm, and
419 the Pi's dead-man holds it still. `GET /deploy-ok` answers 200 while nobody
420 drives and 409 while someone does, so the forge can hold batched deploys.
411421 - The crew moderator (`src/moderator.ts`): each posted line is checked in the
412422 background, never delaying the chat, by an OpenAI-compatible chat endpoint
413423 named by `FORGE_MODEL_URL` (plus `FORGE_MODEL_KEY`, `FORGE_MODEL_NAME`);
Software/so101/bench/fake-serve.ts +4 −2
@@ -10,7 +10,8 @@
1010 * Anyone may watch; only the person whose turn it is may drive (src/lobby.ts). People join with a name picked here
1111 * (src/accounts.ts, kept in accounts.sqlite); the forge signs who its own signed-in people are with FORGE_APP_IDENTITY_KEY.
1212 * Run on one's own machine, away from the forge and with no key, every visitor is the owner.
13 * The owner's settings (pause, turn length, speed cap, announcement) and their log live beside the chat (src/admin.ts).
13 * The owner's settings (pause, turn length, speed cap, announcement) and their log live beside the chat (src/admin.ts),
14 * as do the turn and the line (turns.json) and STOP's hold (relay-held.json): a restart costs nobody their turn.
1415 */
1516 import { mkdirSync, mkdtempSync } from "node:fs";
1617 import { tmpdir } from "node:os";
@@ -52,6 +53,7 @@ const lobby = new Lobby({
5253 local,
5354 chatFile: join(dir, "chat.json"),
5455 adminFile: join(dir, "admin.json"),
56 turnsFile: join(dir, "turns.json"),
5557 wordsFile: join(dir, "words.json"),
5658 accounts: new Accounts({ file: join(dir, "accounts.sqlite") }),
5759 moderator: new Moderator({ file: join(dir, "crew.json"), model: modelFromEnv(process.env) }),
@@ -59,6 +61,6 @@ const lobby = new Lobby({
5961 const cameras = new CameraHub({ file: join(dir, "cameras.json"), seed: remote ? [{ name: "Camera 1", source: remote.cameras[0]! }] : [] });
6062
6163 const leaders = new LeaderCalibrations({ file: join(dir, "leader-calibrations.json") });
62 const relay = await startRelay({ host, port, simulation: `http://127.0.0.1:${simulation.port}`, remote, problem, lobby, cameras, leaders });
64 const relay = await startRelay({ host, port, simulation: `http://127.0.0.1:${simulation.port}`, remote, problem, lobby, cameras, leaders, heldFile: join(dir, "relay-held.json") });
6365 const { mode, host: armHost } = relay.link();
6466 console.log(`arm on http://${host}:${relay.port} (${mode === "simulated" ? "simulated" : `arm ${armHost}: ${mode}`}; data in ${dir}${local ? "; local: every visitor drives as the owner" : ""})`);
Software/so101/src/held-store.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * STOP's hold on disk (src/command-gate.ts): an arm stopped before a restart is still stopped after it, until someone
3 * resumes. Written when the gate shuts, removed when it opens. A file that is there but cannot be read still holds,
4 * as the E-stop's does: when in doubt, the arm stays put.
5 */
6
7 import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
8 import { dirname } from "node:path";
9 import type { Held } from "./command-gate.ts";
10
11 const UNREADABLE = "an unreadable record";
12
13 export function loadHeld(file: string, now = Date.now()): Held | null {
14 let text: string;
15 try {
16 text = readFileSync(file, "utf8");
17 } catch (err) {
18 return (err as NodeJS.ErrnoException).code === "ENOENT" ? null : { by: UNREADABLE, at: new Date(now).toISOString() };
19 }
20 try {
21 const h = JSON.parse(text) as Partial<Held>;
22 if (typeof h.by === "string" && h.by.length <= 64 && typeof h.at === "string" && !Number.isNaN(Date.parse(h.at))) return { by: h.by, at: h.at };
23 } catch {
24 /* held all the same, below */
25 }
26 return { by: UNREADABLE, at: new Date(now).toISOString() };
27 }
28
29 /** Keep the hold as it now stands: written while held, gone once resumed. */
30 export function saveHeld(file: string, held: Held | null): void {
31 try {
32 if (!held) return void unlinkSync(file);
33 mkdirSync(dirname(file), { recursive: true });
34 writeFileSync(`${file}.tmp`, JSON.stringify(held));
35 renameSync(`${file}.tmp`, file);
36 } catch (err) {
37 if ((err as NodeJS.ErrnoException).code !== "ENOENT") console.error(`hold: ${file} not written: ${(err as Error).message}`);
38 }
39 }
Software/so101/src/lean-page.test.ts added +24
@@ -0,0 +1,24 @@
1 import { describe, expect, test } from "bun:test";
2 import { readFileSync } from "node:fs";
3 import { join } from "node:path";
4 import { leanPage } from "./lean-page.ts";
5
6 const script = (html: string) => html.slice(html.indexOf('<script type="module">') + 22, html.indexOf("</script>", html.indexOf('<script type="module">')));
7 const compiled = (js: string) => new Bun.Transpiler({ loader: "js", minifyWhitespace: true }).transformSync(js);
8
9 describe("leanPage", () => {
10 test("drops the comment-only lines of the module script and nothing it runs: the page compiles to the same code", () => {
11 const page = readFileSync(join(import.meta.dir, "viewer.html"), "utf8");
12 const lean = leanPage(page);
13 expect(lean.length).toBeLessThan(page.length);
14 expect(script(lean)).not.toMatch(/^\s*\/\/ /m);
15 expect(compiled(script(lean))).toBe(compiled(script(page)));
16 expect(lean.slice(0, lean.indexOf('<script type="module">'))).toBe(page.slice(0, page.indexOf('<script type="module">')));
17 });
18
19 test("leaves a // inside a string or after code, and everything outside the module script", () => {
20 const html = '<style>/* a */</style>\n// not script\n<script type="module">\n // gone\n const u = "https://x";\n f(); // kept\n</script>\n// after';
21 expect(leanPage(html)).toBe('<style>/* a */</style>\n// not script\n<script type="module">\n const u = "https://x";\n f(); // kept\n</script>\n// after');
22 expect(leanPage("<p>no script</p>")).toBe("<p>no script</p>");
23 });
24 });
Software/so101/src/lean-page.ts added +19
@@ -0,0 +1,19 @@
1 /**
2 * The page as sent: viewer.html keeps its comments for whoever reads the source, the browser gets the module script
3 * without the lines that are only a `//` comment. Nothing else changes (src/lean-page.test.ts checks the script
4 * compiles to the same thing either way), and the first visit is a few kilobytes lighter.
5 */
6
7 const START = '<script type="module">';
8
9 export function leanPage(html: string): string {
10 const at = html.indexOf(START);
11 if (at < 0) return html;
12 const end = html.indexOf("</script>", at);
13 const script = html.slice(at, end < 0 ? html.length : end);
14 const lean = script
15 .split("\n")
16 .filter((line) => !/^\s*\/\/ /.test(line))
17 .join("\n");
18 return html.slice(0, at) + lean + (end < 0 ? "" : html.slice(end));
19 }
Software/so101/src/lobby.ts +10
@@ -39,6 +39,7 @@ import { Chat, ChatError } from "./chat.ts";
3939 import { Moderator } from "./moderator.ts";
4040 import { WordFilter } from "./word-filter.ts";
4141 import { identify, LOCAL, type Person, type Who } from "./identity.ts";
42 import { loadTurns, saveTurns } from "./turn-store.ts";
4243 import { Turns, type TurnEvent } from "./turns.ts";
4344
4445 export interface LobbyOptions {
@@ -54,6 +55,8 @@ export interface LobbyOptions {
5455 wordsFile?: string;
5556 /** The admin settings' file; none keeps them in memory. */
5657 adminFile?: string;
58 /** The turn and the line (src/turn-store.ts), restored on start and written on every change; none keeps them in memory. */
59 turnsFile?: string;
5760 /** Given turns keep their own limits until the owner changes one; made here, they start from the admin settings. */
5861 turns?: Turns;
5962 chat?: Chat;
@@ -104,6 +107,13 @@ export class Lobby {
104107 const a = this.admin.settings;
105108 this.turns = options.turns ?? new Turns({ turnMs: a.turnSeconds * 1000, idleMs: a.idleSeconds * 1000, maxQueue: a.maxQueue });
106109 this.turns.setPaused(a.paused);
110 const turnsFile = options.turnsFile;
111 if (turnsFile) {
112 const saved = loadTurns(turnsFile);
113 if (saved) this.turns.restore(saved);
114 saveTurns(turnsFile, this.turns.saved());
115 this.turns.on(() => saveTurns(turnsFile, this.turns.saved()));
116 }
107117 this.chat = options.chat ?? new Chat({ file: options.chatFile });
108118 this.accounts = options.accounts ?? new Accounts();
109119 this.filter = new WordFilter(options.wordsFile);
Software/so101/src/relay.ts +17 −2
@@ -36,6 +36,9 @@
3636 * POST /join {"name": "…"}: become someone here, no forge account needed (src/accounts.ts); the answer
3737 * sets the HttpOnly session cookie and names you: {"you": {"id", "name", "owner"}}
3838 * GET /admin, POST /admin the owner's page: pause, end a turn, take control, the settings, the log
39 * GET /deploy-ok 200 {"ok": true} while nobody drives, 409 {"ok": false, "driving": true} while someone does: a
40 * restart is safe either way (the turn and the line are kept, src/turn-store.ts), but
41 * the forge's batched deploys wait for the 200 so nobody's hands are on the arm
3942 * GET /link {"mode": "live"|"reconnecting"|"offline"|"simulated", "host": "<host:port>"|null, "problem": "…"|null}
4043 * GET /status the arm's own /status, and which arm said it: "source": "live <host:port>", "reconnecting to the arm:
4144 * <why>" (the last known status, with "reconnecting": true and "seenAt"; 503 before
@@ -74,6 +77,7 @@ import { CalibrationError } from "./leader-map.js";
7477 import type { Lobby } from "./lobby.ts";
7578 import { capBody, FrameCap } from "./speed-cap.ts";
7679 import { Clock, CommandGate, HELD_CLOSE } from "./command-gate.ts";
80 import { loadHeld, saveHeld } from "./held-store.ts";
7781 import { FLOOD_CLOSE, FrameRate, frameBytes, MAX_FRAME_BYTES, TOO_BIG_CLOSE } from "./frame-limit.ts";
7882
7983 export interface Remote {
@@ -122,6 +126,8 @@ export interface RelayOptions {
122126 leaders?: LeaderCalibrations;
123127 /** How often the arm's status is read for the pages on /live (and sent to them when it changed). */
124128 statusEveryMs?: number;
129 /** Where STOP's hold is kept across a restart (src/held-store.ts); none keeps it in memory. */
130 heldFile?: string;
125131 /** Where HTTP_PROXY and NO_PROXY are read from; process.env by default. */
126132 env?: Record<string, string | undefined>;
127133 }
@@ -359,6 +365,8 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
359365
360366 /** STOP's hold, for every stream through here, and each driver's clock (their stamps, seen from here). */
361367 const gate = new CommandGate();
368 if (options.heldFile) gate.held = loadHeld(options.heldFile); // a STOP outlives a restart
369 const keepHeld = () => options.heldFile && saveHeld(options.heldFile, gate.held);
362370 const clocks = new Map<string, Clock>();
363371 /**
364372 * The arm's /status, saying which arm it is: from the link while it is live, the last one it had while reconnecting,
@@ -533,7 +541,9 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
533541 } catch (err) {
534542 return json(res, 502, { error: `the arm server did not answer (${reason(err)})` });
535543 }
536 return json(res, 200, { resumed: gate.resume(), held: null });
544 const resumed = gate.resume();
545 if (resumed) keepHeld();
546 return json(res, 200, { resumed, held: null });
537547 };
538548
539549 const http = createServer(async (req, res) => {
@@ -572,6 +582,11 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
572582 by = who!.name;
573583 }
574584 if (req.method === "GET" && url.pathname === "/link") return json(res, 200, link());
585 if (req.method === "GET" && url.pathname === "/deploy-ok") {
586 // For the forge's batched deploys: a restart now would cost nobody a turn's worth of driving.
587 const driving = Boolean(lobby?.turns.driver);
588 return json(res, driving ? 409 : 200, { ok: !driving, driving });
589 }
575590 if (req.method === "GET" && url.pathname === "/status") return await status(res, path);
576591
577592 const camera = CAMERA.exec(url.pathname);
@@ -600,7 +615,7 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
600615 const answered = (status: number) => logged && machine.note("received", route, { status });
601616 if (route === "POST /stop") {
602617 // Shut before anything is asked of an arm: a frame already on its way finds the gate closed.
603 gate.hold(by);
618 if (gate.hold(by)) keepHeld();
604619 for (const browser of streams.keys()) browser.close(HELD_CLOSE, `stopped by ${by}`);
605620 }
606621 if (route === "POST /resume") return await resume(res, by);
Software/so101/src/restart.test.ts added +159
@@ -0,0 +1,159 @@
1 /**
2 * The app killed and started again mid-turn on the same data dir (a deploy, the forge rolling): the driver comes back
3 * driving, the line comes back in order, STOP still holds, and the arm does not move while the app is away.
4 */
5 import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";
6 import { mkdtempSync, rmSync } from "node:fs";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import WebSocket from "ws";
10 import { FeetechBus } from "./bus.ts";
11 import { FakeBus } from "./fake-bus.ts";
12 import { sign } from "./identity.ts";
13 import { Lobby } from "./lobby.ts";
14 import { startRelay, type RunningRelay } from "./relay.ts";
15 import { startServer, type RunningServer } from "./server.ts";
16
17 const KEY = "test-identity-key";
18 const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
19 const shut = (s: { close(): Promise<void> } | undefined) => (s ? Promise.race([s.close(), sleep(500)]) : undefined);
20 const as = (id: string, name: string) => {
21 const identity = `${id}|${name}|user|${Date.now() + 3_600_000}`;
22 return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
23 };
24 const ALICE = as("u-alice", "alice");
25 const BOB = as("u-bob", "bob");
26 const CAROL = as("u-carol", "carol");
27
28 type Msg = Record<string, any>;
29 const sockets: WebSocket[] = [];
30 /** A /live client: what it heard, and a wait for the next thing that matches. */
31 async function client(port: number, headers: Record<string, string>) {
32 const ws = new WebSocket(`ws://127.0.0.1:${port}/live`, { headers });
33 sockets.push(ws);
34 const heard: Msg[] = [];
35 const waiters: Array<{ match: (m: Msg) => boolean; resolve: (m: Msg) => void }> = [];
36 ws.on("message", (data) => {
37 const m = JSON.parse(String(data)) as Msg;
38 heard.push(m);
39 for (const w of [...waiters]) if (w.match(m)) waiters.splice(waiters.indexOf(w), 1), w.resolve(m);
40 });
41 await new Promise((r, j) => (ws.once("open", r), ws.once("error", j)));
42 const next = (match: (m: Msg) => boolean, ms = 2000) =>
43 new Promise<Msg>((resolve, reject) => {
44 const found = heard.find(match);
45 if (found) return resolve(found);
46 waiters.push({ match, resolve });
47 setTimeout(() => reject(new Error(`nothing matched in ${ms} ms; heard ${JSON.stringify(heard.slice(-5))}`)), ms);
48 });
49 return { ws, heard, next, send: (m: Msg) => ws.send(JSON.stringify(m)) };
50 }
51 /** Whether a /follow stream opens for these headers, or the reason it is refused. */
52 const follow = (port: number, headers: Record<string, string>) =>
53 new Promise<string>((resolve) => {
54 const ws = new WebSocket(`ws://127.0.0.1:${port}/follow`, { headers });
55 sockets.push(ws);
56 const timer = setTimeout(() => resolve("open"), 150);
57 ws.once("close", (code, why) => (clearTimeout(timer), resolve(`${code} ${why}`)));
58 ws.once("error", () => (clearTimeout(timer), resolve("error")));
59 });
60
61 let simulation: RunningServer;
62 let dir = "";
63 beforeAll(async () => {
64 dir = mkdtempSync(join(tmpdir(), "so101-restart-"));
65 simulation = await startServer(new FeetechBus(new FakeBus([1, 2, 6])), { host: "127.0.0.1", port: 0, ids: [1, 2, 6], posesFile: join(dir, "poses.json"), watchdogMs: 60 });
66 });
67 afterAll(async () => {
68 await shut(simulation);
69 rmSync(dir, { recursive: true, force: true });
70 });
71
72 let relay: RunningRelay | undefined;
73 let lobby: Lobby | undefined;
74 afterEach(async () => {
75 for (const s of sockets.splice(0)) s.terminate();
76 await shut(relay);
77 lobby?.close();
78 relay = lobby = undefined;
79 });
80
81 /** The app as fake-serve starts it: the lobby's files and STOP's hold all in one data dir. */
82 async function boot(data: string) {
83 lobby = new Lobby({ identityKey: KEY, chatFile: join(data, "chat.json"), adminFile: join(data, "admin.json"), turnsFile: join(data, "turns.json") });
84 relay = await startRelay({ port: 0, simulation: `http://127.0.0.1:${simulation.port}`, lobby, heldFile: join(data, "relay-held.json") });
85 return relay.port;
86 }
87 /** The app killed: every socket drops at once, nothing is said on the way out. */
88 async function kill() {
89 for (const s of sockets.splice(0)) s.terminate();
90 await shut(relay);
91 lobby?.close();
92 relay = lobby = undefined;
93 }
94 const joints = async () => ((await (await fetch(`http://127.0.0.1:${simulation.port}/status`)).json()) as { joints: Array<{ id: number; position: number | null }> }).joints.map((j) => [j.id, j.position]);
95
96 test("killed mid-turn: the driver keeps control after reconnecting, the line keeps its order, and the arm holds still", async () => {
97 const data = mkdtempSync(join(dir, "app-"));
98 let port = await boot(data);
99 const alice = await client(port, ALICE);
100 const bob = await client(port, BOB);
101 const carol = await client(port, CAROL);
102 alice.send({ type: "join" });
103 await alice.next((m) => m.type === "state" && m.driver?.name === "alice");
104 bob.send({ type: "join" });
105 await bob.next((m) => m.type === "state" && m.queue.length === 1);
106 carol.send({ type: "join" });
107 const before = await carol.next((m) => m.type === "state" && m.queue.length === 2);
108 expect(await follow(port, ALICE)).toBe("open");
109 expect((await fetch(`http://127.0.0.1:${port}/deploy-ok`)).status).toBe(409);
110
111 await kill();
112 const still = await joints();
113 await sleep(300); // the app away: no relay, so nothing reaches the arm, and the server's dead-man holds it
114 expect(await joints()).toEqual(still);
115
116 port = await boot(data);
117 const back = await client(port, ALICE);
118 const hello = await back.next((m) => m.type === "hello");
119 expect(hello.you).toMatchObject({ name: "alice" });
120 const state = await back.next((m) => m.type === "state");
121 expect(state.driver).toMatchObject({ name: "alice", endsAt: before.driver.endsAt });
122 expect(state.queue.map((q: Msg) => q.name)).toEqual(["bob", "carol"]);
123 expect(await follow(port, ALICE)).toBe("open");
124 expect(await follow(port, BOB)).toStartWith("4403");
125 expect(await (await fetch(`http://127.0.0.1:${port}/deploy-ok`)).json()).toEqual({ ok: false, driving: true });
126
127 back.send({ type: "leave" });
128 await back.next((m) => m.type === "state" && m.driver?.name === "bob");
129 });
130
131 test("nobody driving: /deploy-ok answers 200", async () => {
132 const port = await boot(mkdtempSync(join(dir, "app-")));
133 const r = await fetch(`http://127.0.0.1:${port}/deploy-ok`);
134 expect(r.status).toBe(200);
135 expect(await r.json()).toEqual({ ok: true, driving: false });
136 expect(r.headers.get("x-content-type-options")).toBe("nosniff");
137 });
138
139 test("a STOP outlives the restart: the arm stays held until someone resumes", async () => {
140 const data = mkdtempSync(join(dir, "app-"));
141 let port = await boot(data);
142 const alice = await client(port, ALICE);
143 alice.send({ type: "join" });
144 await alice.next((m) => m.type === "state" && m.driver?.name === "alice");
145 expect((await fetch(`http://127.0.0.1:${port}/stop`, { method: "POST", headers: ALICE })).status).toBe(200);
146 await kill();
147
148 port = await boot(data);
149 const back = await client(port, ALICE);
150 await back.next((m) => m.type === "state" && m.driver?.name === "alice");
151 expect(await follow(port, ALICE)).toStartWith("4409");
152 expect((await fetch(`http://127.0.0.1:${port}/resume`, { method: "POST", headers: ALICE })).status).toBe(200);
153 await kill();
154
155 port = await boot(data);
156 const again = await client(port, ALICE);
157 await again.next((m) => m.type === "state" && m.driver?.name === "alice");
158 expect(await follow(port, ALICE)).toBe("open");
159 });
Software/so101/src/server.test.ts +14
@@ -979,6 +979,20 @@ describe("the safety envelope", () => {
979979 expect((await call("/move", { targets: { "1": 2200 } })).status).toBe(200);
980980 });
981981
982 test("STOP's hold survives a restart, and resuming clears it from disk", async () => {
983 expect((await call("/stop", { by: "ann" })).status).toBe(200);
984 expect(existsSync(join(dir, "held.json"))).toBe(true);
985 await Promise.race([srv.close(), sleep(500)]);
986 srv = await start();
987 url = `http://127.0.0.1:${srv.port}`;
988 expect(((await (await fetch(`${url}/status`)).json()) as { held: { by: string } | null }).held?.by).toBe("ann");
989 expect((await call("/move", { targets: { "1": 2200 } })).status).toBe(423);
990 expect(await closed(new WebSocket(`ws://127.0.0.1:${srv.port}/follow`))).toBe(4409);
991 expect(((await (await call("/resume", { by: "ann" })).json()) as { resumed: boolean }).resumed).toBe(true);
992 expect(existsSync(join(dir, "held.json"))).toBe(false);
993 expect((await call("/move", { targets: { "1": 2200 } })).status).toBe(200);
994 });
995
982996 test("the name an E-stop is credited to stays one line of plain data, markup and all, in /status and /metrics", async () => {
983997 const name = '<img src=x onerror="alert(1)">';
984998 await call("/estop", { by: ` ${name}\n\u0000\u202eadmin ` });
Software/so101/src/server.ts +13 −3
@@ -61,6 +61,8 @@ import { fileURLToPath } from "node:url";
6161 import { WebSocketServer, type WebSocket } from "ws";
6262 import { browserModule } from "./browser-modules.ts";
6363 import { Clock, CommandGate, HELD_CLOSE } from "./command-gate.ts";
64 import { loadHeld, saveHeld } from "./held-store.ts";
65 import { leanPage } from "./lean-page.ts";
6466 import { FLOOD_CLOSE, FrameRate, frameBytes, MAX_FRAME_BYTES, TOO_BIG_CLOSE } from "./frame-limit.ts";
6567 import type { FeetechBus } from "./bus.ts";
6668 import { ArmModel, gripperTicksToRadians, ticksToRadians, type Violation } from "./kinematics.ts";
@@ -311,6 +313,8 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
311313 }
312314 /** STOP's hold: every frame is dropped and every move refused until /resume (src/command-gate.ts). */
313315 const gate = new CommandGate();
316 const heldFile = join(dataDir, "held.json");
317 gate.held = loadHeld(heldFile); // a STOP outlives a restart
314318 const holding = (h: { by: string; at: string }) => `stopped (${h.by}, ${h.at.slice(0, 19).replace("T", " ")} UTC): the arm holds until someone resumes`;
315319 const stopped = (e: EStop) => `emergency stop (${e.by}, ${e.at.slice(0, 19).replace("T", " ")} UTC): the arm holds until an admin clears it`;
316320 /** Torque on, goal where each joint is: the arm stays put and resists. */
@@ -722,7 +726,7 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
722726 case "GET /":
723727 case "GET /index.html":
724728 res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
725 return res.end(readFileSync(viewerPath, "utf8").replaceAll("/ui/__VERSION__/", `/ui/${uiVersion()}/`)); // read per request: a viewer change deploys with rsync alone
729 return res.end(leanPage(readFileSync(viewerPath, "utf8")).replaceAll("/ui/__VERSION__/", `/ui/${uiVersion()}/`)); // read per request: a viewer change deploys with rsync alone
726730 case "GET /leader-map.js":
727731 return file(res, join(here, "leader-map.js"), "no-cache");
728732 case "GET /status":
@@ -862,7 +866,10 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
862866 case "POST /stop": {
863867 const body = await readBody(req);
864868 // Held first, before anything awaits: a frame already on its way finds the gate shut.
865 if (body.hold !== false && gate.hold(actor(body))) metrics.event("hold", { by: actor(body) });
869 if (body.hold !== false && gate.hold(actor(body))) {
870 saveHeld(heldFile, gate.held);
871 metrics.event("hold", { by: actor(body) });
872 }
866873 const was = driver;
867874 if (was === "stream") for (const client of wss.clients) end(client, 1000, "stopped from the viewer"); // its close handler holds the arm
868875 else if (was === "record") {
@@ -874,7 +881,10 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
874881 case "POST /resume": {
875882 const by = actor(await readBody(req));
876883 const resumed = gate.resume();
877 if (resumed) metrics.event("resume", { by });
884 if (resumed) {
885 saveHeld(heldFile, null);
886 metrics.event("resume", { by });
887 }
878888 return json(res, 200, { resumed, held: null });
879889 }
880890 case "POST /estop": {
Software/so101/src/turn-store.test.ts added +65
@@ -0,0 +1,65 @@
1 import { afterAll, describe, expect, test } from "bun:test";
2 import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { loadHeld, saveHeld } from "./held-store.ts";
6 import { loadTurns, parseTurns, saveTurns } from "./turn-store.ts";
7
8 const dir = mkdtempSync(join(tmpdir(), "so101-turn-store-"));
9 afterAll(() => rmSync(dir, { recursive: true, force: true }));
10
11 const alice = { id: "u-alice", name: "alice", owner: false };
12 const bob = { id: "u-bob", name: "bob", owner: false };
13 const turn = { ...alice, startedAt: 1, endsAt: 180_001, lastActive: 5, readyBy: null, bonusMs: 0 };
14
15 describe("the turn and the line on disk", () => {
16 test("what is saved is what is loaded, and nothing is there before the first save", () => {
17 const file = join(dir, "a", "turns.json");
18 expect(loadTurns(file)).toBeNull();
19 saveTurns(file, { driver: turn, queue: [bob] });
20 expect(loadTurns(file)).toEqual({ driver: turn, queue: [bob] });
21 saveTurns(file, { driver: null, queue: [] });
22 expect(loadTurns(file)).toEqual({ driver: null, queue: [] });
23 });
24
25 test("a malformed file restores nobody, never half a line", () => {
26 for (const bad of [
27 "not json",
28 "null",
29 "[]",
30 JSON.stringify({ driver: null }),
31 JSON.stringify({ driver: { ...turn, endsAt: "soon" }, queue: [] }),
32 JSON.stringify({ driver: { ...turn, id: "<script>" }, queue: [] }),
33 JSON.stringify({ driver: null, queue: [bob, { id: "x", name: "", owner: false }] }),
34 JSON.stringify({ driver: null, queue: [{ ...bob, owner: "yes" }] }),
35 JSON.stringify({ driver: null, queue: Array.from({ length: 1001 }, (_, i) => ({ id: `u${i}`, name: "n", owner: false })) }),
36 ])
37 expect(parseTurns(bad)).toBeNull();
38 });
39
40 test("only the fields it knows come back, and someone twice in the line keeps their first place", () => {
41 const text = JSON.stringify({ driver: { ...turn, extra: 1 }, queue: [{ ...bob, admin: true }, alice, bob] });
42 expect(parseTurns(text)).toEqual({ driver: turn, queue: [bob, alice] });
43 });
44 });
45
46 describe("STOP's hold on disk", () => {
47 test("written while held, gone once resumed", () => {
48 const file = join(dir, "b", "held.json");
49 expect(loadHeld(file)).toBeNull();
50 const held = { by: "alice", at: "2026-10-21T02:00:00.000Z" };
51 saveHeld(file, held);
52 expect(loadHeld(file)).toEqual(held);
53 saveHeld(file, null);
54 expect(loadHeld(file)).toBeNull();
55 saveHeld(file, null); // resuming twice is harmless
56 });
57
58 test("a file that is there but cannot be made sense of still holds: when in doubt the arm stays put", () => {
59 const file = join(dir, "held-bad.json");
60 writeFileSync(file, "{ torn");
61 expect(loadHeld(file, 0)).toEqual({ by: "an unreadable record", at: new Date(0).toISOString() });
62 writeFileSync(file, JSON.stringify({ by: 3, at: "never" }));
63 expect(loadHeld(file)?.by).toBe("an unreadable record");
64 });
65 });
Software/so101/src/turn-store.ts added +71
@@ -0,0 +1,71 @@
1 /**
2 * The turn and the line on disk, so a restart (a deploy, the forge rolling) costs nobody their turn or their place.
3 * One small JSON file beside the chat, rewritten whole and atomically on every change of turn or line. What is read
4 * back is checked field by field: a file that is missing, unreadable or malformed restores nobody, never half a line.
5 */
6
7 import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
8 import { dirname } from "node:path";
9 import type { Person } from "./identity.ts";
10 import type { SavedTurns, Turn } from "./turns.ts";
11
12 const ID = /^[A-Za-z0-9_|:.@-]{1,128}$/;
13 const MAX_LINE = 1000;
14
15 const time = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v) && v >= 0;
16
17 function person(v: unknown): Person | null {
18 if (typeof v !== "object" || v === null) return null;
19 const p = v as Record<string, unknown>;
20 if (typeof p.id !== "string" || !ID.test(p.id) || typeof p.name !== "string" || !p.name || p.name.length > 64 || typeof p.owner !== "boolean") return null;
21 return { id: p.id, name: p.name, owner: p.owner };
22 }
23
24 function turn(v: unknown): Turn | null {
25 const p = person(v);
26 if (!p) return null;
27 const t = v as Record<string, unknown>;
28 if (!time(t.startedAt) || !time(t.endsAt) || !time(t.lastActive) || !time(t.bonusMs) || !(t.readyBy === null || time(t.readyBy))) return null;
29 return { ...p, startedAt: t.startedAt, endsAt: t.endsAt, lastActive: t.lastActive, readyBy: t.readyBy, bonusMs: t.bonusMs };
30 }
31
32 /** What a saved file holds, checked; null when there is nothing usable in it. */
33 export function parseTurns(text: string): SavedTurns | null {
34 let raw: unknown;
35 try {
36 raw = JSON.parse(text);
37 } catch {
38 return null;
39 }
40 if (typeof raw !== "object" || raw === null) return null;
41 const r = raw as Record<string, unknown>;
42 if (!Array.isArray(r.queue) || r.queue.length > MAX_LINE) return null;
43 const driver = r.driver === null ? null : turn(r.driver);
44 if (r.driver !== null && !driver) return null;
45 const queue: Person[] = [];
46 for (const entry of r.queue) {
47 const p = person(entry);
48 if (!p) return null;
49 if (!queue.some((q) => q.id === p.id)) queue.push(p);
50 }
51 return { driver, queue };
52 }
53
54 export function loadTurns(file: string): SavedTurns | null {
55 try {
56 return parseTurns(readFileSync(file, "utf8"));
57 } catch (err) {
58 if ((err as NodeJS.ErrnoException).code !== "ENOENT") console.error(`turns: ${file} not read: ${(err as Error).message}`);
59 return null;
60 }
61 }
62
63 export function saveTurns(file: string, saved: SavedTurns): void {
64 try {
65 mkdirSync(dirname(file), { recursive: true });
66 writeFileSync(`${file}.tmp`, JSON.stringify(saved));
67 renameSync(`${file}.tmp`, file);
68 } catch (err) {
69 console.error(`turns: ${file} not written: ${(err as Error).message}`);
70 }
71 }
Software/so101/src/turns.test.ts +78 −2
@@ -8,8 +8,8 @@ const owner = { id: "o", name: "trevato", owner: true };
88
99 let clock = 1_000_000;
1010 let turns: Turns;
11 const make = () => {
12 clock = 1_000_000;
11 const make = (start = 1_000_000) => {
12 clock = start;
1313 turns = new Turns({ turnMs: 180_000, idleMs: 30_000, graceMs: 10_000, now: () => clock });
1414 const events: TurnEvent[] = [];
1515 turns.on((e) => events.push(e));
@@ -239,3 +239,79 @@ describe("ready check and extra time", () => {
239239 expect(turns.driver!.endsAt - turns.driver!.startedAt).toBe(360_000);
240240 });
241241 });
242
243 describe("a restart", () => {
244 /** A new Turns, as after a restart at the time it is now, given what the old one saved. */
245 const restarted = (saved: ReturnType<Turns["saved"]>) => {
246 const events = make(clock);
247 turns.restore(saved);
248 return events;
249 };
250
251 test("the driver keeps their turn to its own end and the line its order, and nothing is announced", () => {
252 make();
253 turns.join(alice);
254 turns.join(bob);
255 turns.join(carol);
256 for (let i = 0; i < 3; i++) {
257 advance(20_000);
258 turns.activity("a");
259 }
260 const saved = JSON.parse(JSON.stringify(turns.saved()));
261 turns.dispose();
262 const at = clock;
263 const events = restarted(saved);
264 clock = at + 2000; // two seconds down
265 turns.connect("a");
266 turns.check();
267 expect(events).toEqual([]);
268 const s = turns.snapshot();
269 expect(s.driver?.id).toBe("a");
270 expect(s.driver?.endsAt).toBe(1_000_000 + 180_000);
271 expect(s.queue.map((p) => p.id)).toEqual(["b", "c"]);
272 });
273
274 test("the time the app was down never counts as idle, and a pending Ready gets its full time again", () => {
275 make();
276 turns.join(alice);
277 turns.join(bob);
278 turns.leave("a"); // bob is called from the line and must confirm
279 expect(turns.driver?.readyBy).toBe(clock + 15_000);
280 const saved = turns.saved();
281 turns.dispose();
282 restarted(saved);
283 clock += 25_000; // longer down than the idle allowance would leave: still bob's, measured from the restore
284 turns.connect("b");
285 turns.restore({ ...saved }); // an idempotent second restore is harmless
286 expect(turns.driver?.id).toBe("b");
287 expect(turns.driver?.readyBy).toBe(clock + 15_000);
288 expect(turns.driver?.lastActive).toBe(clock);
289 });
290
291 test("whoever does not come back within the grace loses their turn or place", () => {
292 make();
293 turns.join(alice);
294 turns.join(bob);
295 turns.join(carol);
296 const saved = turns.saved();
297 turns.dispose();
298 restarted(saved);
299 turns.connect("b");
300 advance(10_001);
301 expect(turns.driver?.id).toBe("b"); // alice never came back: bob, who did, drives
302 expect(turns.queue.map((p) => p.id)).toEqual([]); // carol never came back either
303 });
304
305 test("a turn that ran out while the app was down is over, and the head of the line is called", () => {
306 make();
307 turns.join(alice);
308 turns.join(bob);
309 const saved = turns.saved();
310 turns.dispose();
311 clock += 200_000; // down past alice's three minutes
312 const events = restarted(saved);
313 expect(turns.driver?.id).toBe("b");
314 expect(turns.queue).toEqual([]);
315 expect(events).toEqual([{ kind: "turn", ended: null, started: bob }]);
316 });
317 });
Software/so101/src/turns.ts +27
@@ -35,6 +35,12 @@ export interface Snapshot {
3535 queue: Array<{ id: string; name: string; place: number; waitMs: number }>;
3636 }
3737
38 /** What outlives a restart: the turn under way and the line, plain data (src/turn-store.ts keeps it on disk). */
39 export interface SavedTurns {
40 driver: Turn | null;
41 queue: Person[];
42 }
43
3844 export interface TurnsOptions {
3945 turnMs?: number;
4046 idleMs?: number;
@@ -196,6 +202,27 @@ export class Turns {
196202 this.schedule();
197203 }
198204
205 /** The turn and the line as they stand, for keeping across a restart. */
206 saved(): SavedTurns {
207 return { driver: this.driver ? { ...this.driver } : null, queue: this.queue.map((p) => ({ ...p })) };
208 }
209
210 /**
211 * Back after a restart: the same driver until their turn's own end, the same line in the same order. Nobody could
212 * act while the app was down, so the idle clock (and a pending Ready) starts over now; and nobody has a connection
213 * yet, so everyone restored gets the usual grace to come back before their turn or place is let go. A turn that ran out while it was
214 * down is over, and the head of the line is called as usual.
215 */
216 restore(saved: SavedTurns): void {
217 const now = this.now();
218 const d = saved.driver;
219 this.driver = d && now < d.endsAt ? { ...d, lastActive: now, readyBy: d.readyBy === null ? null : now + this.readyMs } : null;
220 this.queue.splice(0, this.queue.length, ...saved.queue.filter((p) => p.id !== this.driver?.id).map((p) => ({ ...p })));
221 for (const p of [this.driver, ...this.queue]) if (p && !this.connections.has(p.id)) this.gone.set(p.id, now);
222 if (!this.driver && !this.paused && this.queue.length) this.handOver(null);
223 this.schedule();
224 }
225
199226 snapshot(): Snapshot {
200227 const now = this.now();
201228 const d = this.driver;
Software/so101/src/ui/intent.js +3 −1
@@ -48,9 +48,11 @@ export class Intent {
4848
4949 /**
5050 * In words, why the controls are off; null when they are on.
51 * @param {{ queued?: boolean, turn: boolean, estop?: unknown, held?: unknown, reconnecting?: unknown }} s
51 * @param {{ queued?: boolean, turn: boolean, estop?: unknown, held?: unknown, reconnecting?: unknown, app?: unknown }} s
52 * `app`: the app itself is not answering (a restart); what the page last heard of the arm may be stale, so it comes first
5253 */
5354 export function whyNot(s) {
55 if (s.app) return "Reconnecting… the arm holds still meanwhile";
5456 if (s.estop) return "Stopped - an admin must clear the emergency stop";
5557 if (s.held) return "Stopped - resume first";
5658 if (s.reconnecting) return "Arm offline - reconnecting";
Software/so101/src/ui/intent.test.ts +5
@@ -38,6 +38,11 @@ describe("whyNot", () => {
3838 expect(whyNot({ turn: true, reconnecting: true })).toBe("Arm offline - reconnecting");
3939 });
4040 test("your turn drives", () => expect(whyNot({ turn: true })).toBeNull());
41 test("the app away (a restart) says reconnecting before anything it last heard of the arm", () => {
42 expect(whyNot({ turn: true, app: true })).toBe("Reconnecting… the arm holds still meanwhile");
43 expect(whyNot({ turn: true, app: true, held: {}, estop: {} })).toMatch(/^Reconnecting/);
44 expect(whyNot({ turn: true, app: true })).not.toMatch(/simulat/i);
45 });
4146 });
4247
4348 describe("marks", () => {
Software/so101/src/ui/lobby-panel.js +26 −7
@@ -12,6 +12,11 @@ export const ordinal = (n) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : ["t
1212 /** @param {number} ms @returns {number} whole minutes to wait, at least one */
1313 export const waitMinutes = (ms) => Math.max(1, Math.ceil(ms / 60000));
1414
15 /** The room's socket comes back by itself: first after RETRY_FIRST ms, then twice as long each time, never over RETRY_MOST. */
16 export const RETRY_FIRST = 250, RETRY_MOST = 2000;
17 /** @param {number} ms @returns {number} the wait after this one */
18 export const nextRetry = (ms) => Math.min(Math.max(ms, RETRY_FIRST) * 2, RETRY_MOST);
19
1520 /**
1621 * One line of the queue. The name goes in as text, so a name can never be markup.
1722 * @param {(tag: string, props?: Record<string, unknown>, ...children: any[]) => any} el
@@ -23,12 +28,13 @@ export function queueEntry(el, x, mine) {
2328 }
2429
2530 /**
26 * @param {any} page what the page owns: $, el, relayed, tab(), showTab, msg, applyLock, applyStatus, noStatus, words, admin
31 * @param {any} page what the page owns: $, el, relayed, tab(), showTab, msg, applyLock, applyStatus, noStatus, words, admin,
32 * and away(on), told when the app itself stops answering (a restart) and when it is back
2733 */
2834 export function createRoom(page) {
2935 const { $, el, relayed, msg } = page;
3036 const doc = /** @type {any} */ (globalThis).document, nav = /** @type {any} */ (globalThis).navigator;
31 const lobby = { ws: null, hello: null, state: null, offset: 0, retry: 500, mutedList: [], bannedList: [], admin: null, statusSeen: false };
37 const lobby = { ws: null, hello: null, state: null, offset: 0, retry: RETRY_FIRST, down: false, mutedList: [], bannedList: [], admin: null, statusSeen: false };
3238 function mayDrive() { return !relayed || (lobby.hello !== null && (!lobby.hello.signin || (lobby.hello.you !== null && lobby.state?.driver?.id === lobby.hello.you.id))); }
3339 function isOwner() { return !relayed || Boolean(lobby.hello?.you?.owner); }
3440 const say = (m) => { if (lobby.ws?.readyState === 1) lobby.ws.send(JSON.stringify(m)); };
@@ -226,10 +232,22 @@ export function createRoom(page) {
226232 if ($("modDlg").returnValue === "ban" && confirm(`Ban ${line.dataset.name}? They can still watch, but nobody from their name, browser or address can chat or drive.`)) say({ type: "ban", id: line.dataset.from, on: true });
227233 });
228234 }
235 /**
236 * The app away (a restart: a deploy, the forge rolling) or back. Away, the page keeps who you are, the turn and the
237 * line as they last stood, so nothing on screen jumps; it only says "reconnecting…" and drives nothing. Back, the
238 * server's hello and state replace them: the same cookie is the same person, in the same place.
239 */
240 function away(on) {
241 if (lobby.down === on) return;
242 lobby.down = on;
243 $("away").hidden = !on;
244 page.away?.(on);
245 page.applyLock();
246 }
229247 function lobbyConnect() {
230248 const ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/live`);
231249 lobby.ws = ws;
232 ws.onopen = () => { lobby.retry = 500; };
250 ws.onopen = () => { lobby.retry = RETRY_FIRST; };
233251 ws.onmessage = (e) => {
234252 const m = JSON.parse(e.data);
235253 if (m.type === "ping") return say({ type: "pong" });
@@ -246,15 +264,16 @@ export function createRoom(page) {
246264 else if (m.type === "admin") { const saved = lobby.admin !== null; lobby.admin = m; page.admin(saved); }
247265 else if (m.type === "crew") lobby.crew = m;
248266 else if (m.type === "error") return msg(m.error, true);
267 // Back once the server has said who you are and where the turn stands (hello comes first, then state).
268 if (m.type === "state") away(false);
249269 renderTurn();
250270 };
251271 ws.onclose = () => {
252272 if (lobby.ws !== ws) return;
253 lobby.ws = null; lobby.hello = null; lobby.statusSeen = false; // polling takes over until it is back
254 page.applyLock();
255 $("driverLine").className = "none"; $("driverLine").textContent = "Reconnecting…";
273 lobby.ws = null; lobby.statusSeen = false; // polling takes over until it is back
274 away(true);
256275 setTimeout(lobbyConnect, lobby.retry);
257 lobby.retry = Math.min(lobby.retry * 2, 8000);
276 lobby.retry = nextRetry(lobby.retry);
258277 };
259278 }
260279 $("say").onsubmit = (e) => {
Software/so101/src/ui/lobby-panel.test.ts +63 −1
@@ -1,5 +1,5 @@
11 import { describe, expect, test } from "bun:test";
2 import { createRoom, minutes, ordinal, queueEntry, waitMinutes } from "./lobby-panel.js";
2 import { createRoom, minutes, nextRetry, ordinal, queueEntry, RETRY_FIRST, RETRY_MOST, waitMinutes } from "./lobby-panel.js";
33
44 /** A stand-in for the page's el(): elements as plain trees, so the test needs no DOM. */
55 const el = (tag: string, props: Record<string, unknown> = {}, ...children: unknown[]) => ({ tag, ...props, children });
@@ -63,4 +63,66 @@ describe("the room over /live", () => {
6363 expect(room.lobby.hello).not.toBeNull();
6464 } finally { Object.assign(g, saved); }
6565 });
66
67 test("a dropped socket comes back by itself within a second, 0.25 s then doubling to 2 s, and resumes the same seat", () => {
68 expect(RETRY_FIRST).toBe(250);
69 const waits = [RETRY_FIRST];
70 for (let i = 0; i < 5; i++) waits.push(nextRetry(waits.at(-1)!));
71 expect(waits).toEqual([250, 500, 1000, 2000, 2000, 2000]);
72 expect(RETRY_MOST).toBe(2000);
73 expect(waits.slice(0, 3).reduce((a, b) => a + b, 0)).toBeLessThan(2000);
74
75 const sockets: any[] = [], timers: Array<[() => void, number]> = [];
76 const g = globalThis as any, saved = { WebSocket: g.WebSocket, setInterval: g.setInterval, setTimeout: g.setTimeout, location: g.location };
77 g.WebSocket = class { readyState = 1; sent: string[] = []; constructor() { sockets.push(this); } send(m: string) { this.sent.push(m); } };
78 g.setInterval = () => 0;
79 g.setTimeout = (f: () => void, ms: number) => (timers.push([f, ms]), 0);
80 g.location = { protocol: "http:", host: "x", pathname: "/", search: "" };
81 try {
82 const nodes = new Map<string, any>(), awayCalls: boolean[] = [];
83 let locks = 0;
84 const page = {
85 $: (id: string) => nodes.get(id) ?? (nodes.set(id, node()), nodes.get(id)),
86 el: (tag: string, props: object = {}) => Object.assign(node(), { tag }, props),
87 relayed: true, tab: () => "chat", showTab() {}, applyLock: () => void locks++, applyStatus() {}, noStatus() {}, words() {}, admin() {}, msg() {},
88 away: (on: boolean) => void awayCalls.push(on),
89 };
90 const room = createRoom(page);
91 room.lobbyConnect();
92 const me = { id: "u-ann", name: "ann", owner: false };
93 const state = { type: "state", now: Date.now(), turnMs: 180_000, idleMs: 30_000, paused: false, maxQueue: -1, driver: { ...me, endsAt: Date.now() + 60_000, idleEndsAt: Date.now() + 30_000, readyBy: null }, queue: [] };
94 sockets[0].onopen();
95 sockets[0].onmessage({ data: JSON.stringify({ type: "hello", signin: true, you: me }) });
96 sockets[0].onmessage({ data: JSON.stringify(state) });
97 expect(room.mayDrive()).toBe(true);
98 expect(page.$("away").hidden).not.toBe(false);
99
100 // The app restarts: the page keeps your seat on screen, says reconnecting, and tries again in 0.25 s.
101 sockets[0].onclose();
102 expect(room.lobby.down).toBe(true);
103 expect(page.$("away").hidden).toBe(false);
104 expect(awayCalls).toEqual([true]);
105 expect((room.lobby.hello as any)?.you).toEqual(me);
106 expect(room.mayDrive()).toBe(true); // the tab stays put; the page's lock says reconnecting and sends nothing
107 expect(locks).toBeGreaterThan(0);
108 expect(timers.at(-1)![1]).toBe(250);
109
110 // Still down: the next try waits 0.5 s.
111 timers.at(-1)![0]();
112 sockets[1].onclose();
113 expect(timers.at(-1)![1]).toBe(500);
114
115 // Back: hello and state from the server, and the chip goes; the waits start over at 0.25 s.
116 timers.at(-1)![0]();
117 sockets[2].onopen();
118 sockets[2].onmessage({ data: JSON.stringify({ type: "hello", signin: true, you: me }) });
119 expect(room.lobby.down).toBe(true); // not until the server has said where the turn stands
120 sockets[2].onmessage({ data: JSON.stringify(state) });
121 expect(room.lobby.down).toBe(false);
122 expect(page.$("away").hidden).toBe(true);
123 expect(awayCalls).toEqual([true, false]);
124 expect(room.mayDrive()).toBe(true);
125 expect(room.lobby.retry).toBe(250);
126 } finally { Object.assign(g, saved); }
127 });
66128 });
Software/so101/src/viewer.html +11 −7
@@ -103,6 +103,7 @@
103103 #strip.ready { box-shadow: inset 0 0 0 2px var(--blue); } #turnActions .ready { min-height: 48px; padding: 0 20px; font-weight: 800; }
104104 @media (prefers-reduced-motion: no-preference) { #turnActions .ready { animation: pulse 1s ease-in-out infinite; } @keyframes pulse { 50% { opacity: .65; } } }
105105 #driverTag { position: absolute; z-index: 2; left: calc(10px + var(--safe-l)); bottom: 10px; max-width: 70%; padding: 4px 10px; border-radius: 999px; background: rgba(0,0,0,.6); color: #fff; font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; pointer-events: none; } #driverTag:empty { display: none; }
106 #away { position: absolute; z-index: 3; top: 10px; left: 50%; transform: translateX(-50%); padding: 4px 12px; border-radius: 999px; background: var(--warn); color: #000; font-size: 13px; font-weight: 650; pointer-events: none; } #away[hidden] { display: none; }
106107
107108 /* the sheet: one panel at a time, the tabs under the thumb */
108109 #sheet { grid-area: sheet; min-height: 0; display: flex; flex-direction: column; background: var(--surface); }
@@ -310,6 +311,7 @@
310311 <button id="fs" title="F">Fullscreen</button>
311312 </div>
312313 <div id="driverTag" aria-hidden="true"></div>
314 <div id="away" role="status" hidden>reconnecting…</div>
313315 <div id="banner" role="alert"></div>
314316 <div id="msg" role="status"></div>
315317 <div id="refusal" role="status"></div>
@@ -604,6 +606,8 @@
604606 // A real arm that drops is "reconnecting": the same arm, its last pose kept, driving paused. Only after a minute down
605607 // does the relay hand the page the simulation, and then it says OFFLINE in red.
606608 let linkMode = null, linkNow = null;
609 // The app itself not answering (a restart): the page drives nothing until /live is back, and says "reconnecting…".
610 let appAway = false;
607611 const realArm = (mode) => mode === "live" || mode === "reconnecting";
608612 async function pollLink() {
609613 const l = await api("/link").catch(() => null);
@@ -833,7 +837,7 @@
833837 ws?.close();
834838 },
835839 open() {
836 if (!mayDrive()) return; // the server would refuse it: only the person whose turn it is streams
840 if (!mayDrive() || appAway) return; // the server would refuse it: only the person whose turn it is streams (and the app must be there)
837841 clearTimeout(this.closeTimer);
838842 if (this.ws && this.ws.readyState <= 1) return;
839843 if (this.halted) return; // the server ended this hold (Stop, or the arm is busy): nothing more until the next press
@@ -1090,7 +1094,7 @@
10901094 leader = l;
10911095 teleop ??= new tele.Teleop({
10921096 connect: () => new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/follow`),
1093 mayDrive, visible: () => document.visibilityState === "visible", onChange: teleopChanged,
1097 mayDrive, visible: () => document.visibilityState === "visible" && !appAway, onChange: teleopChanged,
10941098 });
10951099 teleop.setLeader(true);
10961100 renderLeaderButtons();
@@ -1405,7 +1409,7 @@
14051409 flush: (f) => stream.flush(f),
14061410 end: () => stream.end(),
14071411 begin: () => {
1408 if (!canDrive({ mayDrive: mayDrive(), estop: status?.estop, held: status?.held, reconnecting: status?.reconnecting, limits })) return false;
1412 if (!canDrive({ mayDrive: mayDrive(), estop: status?.estop, held: status?.held, reconnecting: status?.reconnecting || appAway, limits })) return false;
14091413 stream.open();
14101414 return true;
14111415 },
@@ -1597,13 +1601,13 @@
15971601 const room = createRoom({
15981602 $, el, relayed, msg, tab: () => tab, showTab, applyLock: () => applyLock(), applyStatus: (s) => applyStatus(s), noStatus: () => noStatus(),
15991603 words(m) { const f = $("wordsForm"); if (document.activeElement !== f.elements.words) f.elements.words.value = m.words.join(", "); if (wordsSent) { wordsSent = false; msg(`Word filter saved: ${m.words.length} word${m.words.length === 1 ? "" : "s"}.`); } },
1600 admin: (saved) => fillAdmin(saved),
1604 admin: (saved) => fillAdmin(saved), away: (on) => { appAway = on; },
16011605 });
16021606 const { lobby, mayDrive, isOwner, say, serverNow, lobbyConnect, chatBox, renderTurn, button } = room;
16031607 let drove = false;
16041608 function explainLock() {
16051609 const me = lobby.hello?.you, down = linkNow === "offline", st = typeof status?.source === "string" && status.source.startsWith("simulated");
1606 const w = whyNot({ turn: mayDrive(), queued: Boolean(me && lobby.state?.queue?.some((x) => x.id === me.id)), estop: status?.estop, held: status?.held, reconnecting: status?.reconnecting || linkNow === "reconnecting" || (relayed && (down || (st && realArm(linkMode)))) });
1610 const w = whyNot({ turn: mayDrive(), queued: Boolean(me && lobby.state?.queue?.some((x) => x.id === me.id)), estop: status?.estop, held: status?.held, app: appAway, reconnecting: status?.reconnecting || linkNow === "reconnecting" || (relayed && (down || (st && realArm(linkMode)))) });
16071611 $("why").textContent = w ?? "";
16081612 return w;
16091613 }
@@ -1757,7 +1761,7 @@
17571761 driver.seed(d.joints.filter((j) => j.position != null).map((j) => [j.id, j.position]));
17581762 if ((explainLock() ?? "") !== was) applyLock();
17591763 // Stopped, reconnecting or no longer this person's turn: a held thumb lets go, and its zero goes out now.
1760 if (!canDrive({ mayDrive: mayDrive(), estop: d.estop, held: d.held, reconnecting: d.reconnecting, limits })) driver.releaseAll();
1764 if (!canDrive({ mayDrive: mayDrive(), estop: d.estop, held: d.held, reconnecting: d.reconnecting || appAway, limits })) driver.releaseAll();
17611765 // The round trip to the arm, which every command also makes: shown once it is long enough to feel.
17621766 const lag = [...rtts].sort((a, b) => a - b)[rtts.length >> 1] ?? 0;
17631767 $("lag").hidden = rtts.length < 3 || lag <= 250; $("lag").textContent = `· ${Math.round(lag)} ms lag`;
@@ -1777,7 +1781,7 @@
17771781 }
17781782 }
17791783 function noStatus() {
1780 const reconnecting = linkNow === "reconnecting";
1784 const reconnecting = appAway || linkNow === "reconnecting";
17811785 $("dot").className = reconnecting ? "dot warn" : "dot"; $("state").textContent = reconnecting ? "reconnecting…" : "no arm";
17821786 }
17831787 async function poll() {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs