Public: anyone can read this; the crew can change it.
Migrated from github.com/Trevato/SO-ARM100
workbenchthis machine
Open / Closed: the owner can close the arm, and a resting card tells visitors why (and when it is back) #568
Check · Review · Land done · Live — Landed; nothing deploys from this branch, so this is the end of its path.
vesper/arm:vesper/563-open-closed-the-owner-can-close-the-arm → main 3 commits fork
17 files
changed +986
−22
Software/so101/README.md +10
| @@ -2,6 +2,16 @@ | ||
| 2 | 2 | |
| 3 | 3 | `bench/fake-serve.ts` is the hosted app (the page, the room, the relay); `so101 serve` is the arm server on the Pi. |
| 4 | 4 | |
| 5 | ## Open / Closed | |
| 6 | ||
| 7 | The owner can close the whole app when the shop is dark: on `/admin`, **Open / Closed** has **Close the arm** with an optional note for visitors ("Back Saturday 10am CT", at most 140 characters) and an optional "back around" time (the owner's local time); **Open the arm** undoes it. In the terminal: `/close [note]` and `/open`. Over `/live`, the owner sends `{"type": "open", "open": false, "note": "…", "reopenAt": "2026-10-31T10:00-05:00"}`. Every change is in the admin log; the switch is kept in `so101/open.json` under `FORGE_APP_DATA` (src/opening.ts). | |
| 8 | ||
| 9 | Closed means: every turn ends (the owner's too) and the line is emptied, nobody can join, the cameras are refused and every open camera and `/follow` stream is closed, and nothing reaches the arm but a STOP (anything else is 503). `/` is then a calm card, **The arm is resting**, with the note, when it should be back and when it was last open, a "Get notified when it's back" button (the browser's own notification, while that tab stays open), and links to the story (`/story`) and the code (src/resting-page.ts). A page that was open when it closed reloads into the card, and the card reloads into the arm when it opens. The reopen time is only shown: the arm never reopens by itself. | |
| 10 | ||
| 11 | The arm closes itself too: a real arm (ARM_SERVER) that has not answered for more than 2 minutes shows the same card worded **The arm is offline right now**, until the arm answers again. If the owner presses **Open anyway** after it went, the page shows the simulation instead, as before. | |
| 12 | ||
| 13 | `GET /status` says so for everyone: `{"open": false, "reason": "closed"|"offline", "note": "…"|null, "reopenAt": ISO|null, "lastOpenAt": ISO|null, "driver": null, "source": "The arm is resting"}`, answered without asking the arm; while open, the arm's status as before with `"open": true`. | |
| 14 | ||
| 5 | 15 | ## The story page: /story |
| 6 | 16 | |
| 7 | 17 | `/story` on the hosted app is the arm explained for anyone: the hook, how it works (with a diagram of browser → forge → Pi → servos, and what latency, the queue, STOP and the safety zone mean), how to build your own (the [](https://huggingface.co/docs/lerobot/so101), this repository, `bun so101 setup`) and what the crew built. Anyone may read it; it is linked from the Chat tab's footer (hidden while you drive) and the Queue tab. |
Software/so101/bench/fake-serve.ts +1
| @@ -54,6 +54,7 @@ const lobby = new Lobby({ | ||
| 54 | 54 | local, |
| 55 | 55 | chatFile: join(dir, "chat.json"), |
| 56 | 56 | adminFile: join(dir, "admin.json"), |
| 57 | openFile: join(dir, "open.json"), | |
| 57 | 58 | countsFile: join(dir, "visitors.json"), |
| 58 | 59 | turnsFile: join(dir, "turns.json"), |
| 59 | 60 | wordsFile: join(dir, "words.json"), |
Software/so101/src/admin-page.ts +38 −3
| @@ -16,6 +16,7 @@ import { precisionSection, type PrecisionPanel } from "./precision-panel.ts"; | ||
| 16 | 16 | import { ALIGNED_DEG, REFERENCES, alignment } from "./joint-reference.ts"; |
| 17 | 17 | import { servosSection, type ServoPanel } from "./servo-panel.ts"; |
| 18 | 18 | import { videoSection, type VideoCard } from "./video-panel.ts"; |
| 19 | import { NOTE_CHARS, OFFLINE_AFTER_MS, type OpenState, type Resting } from "./opening.ts"; | |
| 19 | 20 | |
| 20 | 21 | export const esc = (text: string): string => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`); |
| 21 | 22 | |
| @@ -174,7 +175,16 @@ const ALIGN_SCRIPT = ` | ||
| 174 | 175 | `; |
| 175 | 176 | |
| 176 | 177 | /** The page's one script: the Health refresh, and for the owner the table height saver and the joint aligner. */ |
| 177 | const scriptFor = (canEdit: boolean): string => (canEdit ? HEALTH_SCRIPT + TABLE_SCRIPT + ALIGN_SCRIPT : HEALTH_SCRIPT); | |
| 178 | /** The Close form's reopen time is the owner's local time: its zone, for that date, goes with it. */ | |
| 179 | const ZONE_SCRIPT = ` | |
| 180 | const closing = document.getElementById("close-form"); | |
| 181 | if (closing) closing.addEventListener("submit", () => { | |
| 182 | const at = closing.elements.reopenAt.value; | |
| 183 | closing.elements.zone.value = String(-(at ? new Date(at) : new Date()).getTimezoneOffset()); | |
| 184 | }); | |
| 185 | `; | |
| 186 | ||
| 187 | const scriptFor = (canEdit: boolean): string => (canEdit ? HEALTH_SCRIPT + TABLE_SCRIPT + ALIGN_SCRIPT + ZONE_SCRIPT : HEALTH_SCRIPT); | |
| 178 | 188 | |
| 179 | 189 | const sha = (text: string) => createHash("sha256").update(text).digest("base64"); |
| 180 | 190 | |
| @@ -183,7 +193,7 @@ export const adminCsp = (canEdit: boolean): string => | ||
| 183 | 193 | `default-src 'none'; style-src 'sha256-${sha(STYLE)}'; script-src 'sha256-${sha(scriptFor(canEdit))}'; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'`; |
| 184 | 194 | |
| 185 | 195 | /** The fixed lines a redirect back may ask for; nothing from the request is echoed. */ |
| 186 | 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.", restored: "Line restored.", lifted: "Lifted.", reportRemoved: "Line removed; report closed.", reportMuted: "Author muted; report closed.", reportDismissed: "Report dismissed.", tuning: "The P experiment is running on the arm: reload to follow it." } as const; | |
| 196 | export const DONE = { opened: "Open: people can take turns again.", closed: "Closed: visitors see the resting card.", 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.", restored: "Line restored.", lifted: "Lifted.", reportRemoved: "Line removed; report closed.", reportMuted: "Author muted; report closed.", reportDismissed: "Report dismissed.", tuning: "The P experiment is running on the arm: reload to follow it." } as const; | |
| 187 | 197 | export type Done = keyof typeof DONE; |
| 188 | 198 | |
| 189 | 199 | export interface Target { id: string; name: string } |
| @@ -194,6 +204,9 @@ export interface AdminPage { | ||
| 194 | 204 | canEdit: boolean; |
| 195 | 205 | settings: AdminSettings; |
| 196 | 206 | snapshot: Snapshot; |
| 207 | /** The owner's open/closed switch, and whether the room rests now (closed, or the arm offline); absent reads as open. */ | |
| 208 | opening?: OpenState; | |
| 209 | resting?: Resting | null; | |
| 197 | 210 | /** What each open page last reported about its link. */ |
| 198 | 211 | health?: readonly ViewerRow[]; |
| 199 | 212 | log: readonly LogEntry[]; |
| @@ -298,6 +311,27 @@ const alignSection = (): string => { | ||
| 298 | 311 | return `<section aria-labelledby="align"><h2 id="align">Align joints</h2><p class="empty">Put a joint at its reference by hand, then press Record: the model reads that angle from then on. Done is within ${ALIGNED_DEG}°.</p><div class="scroll"><table aria-label="Align joints"><thead><tr><th scope="col">Joint</th><th scope="col">Reference</th><th scope="col">Offset</th><th scope="col">Record</th><th scope="col">Check</th></tr></thead><tbody>${rows}</tbody></table></div></section>`; |
| 299 | 312 | }; |
| 300 | 313 | |
| 314 | /** Open / Closed: the switch, what visitors see now, and the note and reopen time for closing. */ | |
| 315 | function openSection(p: AdminPage): string { | |
| 316 | const s = p.opening ?? { open: true, note: "", reopenAt: null, changedAt: 0 }; | |
| 317 | const r = p.resting ?? null; | |
| 318 | const at = (ms: number) => new Date(ms).toISOString().slice(0, 16).replace("T", " ") + " UTC"; | |
| 319 | const now = !s.open | |
| 320 | ? `<p>Closed${s.changedAt ? ` since ${at(s.changedAt)}` : ""}. Visitors see <b>The arm is resting.</b>${s.note ? ` with your note: “${esc(s.note)}”` : ""}${r?.reopenAt ? `, back around ${at(r.reopenAt)}` : ""}. No turns, no line, no cameras, and nothing but a STOP reaches the arm.</p>` | |
| 321 | : r?.reason === "offline" | |
| 322 | ? `<p>The arm has not answered for over ${OFFLINE_AFTER_MS / 60_000} minutes, so visitors see <b>The arm is offline right now</b>. It opens again by itself when the arm answers; Open anyway shows the simulation instead.</p>` | |
| 323 | : `<p>Open: people can watch, queue and drive.</p>`; | |
| 324 | if (!p.canEdit) return `<section aria-labelledby="open"><h2 id="open">Open / Closed</h2>${now}</section>`; | |
| 325 | const open = action("open", r?.reason === "offline" ? "Open anyway" : "Open the arm", "go"); | |
| 326 | const close = `<form method="post" action="/admin" id="close-form"><input type="hidden" name="action" value="close"><input type="hidden" name="zone" value=""> | |
| 327 | <div class="grid"> | |
| 328 | <label class="wide">Note for visitors<small>optional, at most ${NOTE_CHARS} characters, e.g. Back Saturday 10am CT</small><input name="note" maxlength="${NOTE_CHARS}" value="${esc(s.open ? "" : s.note)}"></label> | |
| 329 | <label>Back around<small>optional; your local time; shown, it does not reopen by itself</small><input name="reopenAt" type="datetime-local"></label> | |
| 330 | </div> | |
| 331 | <div class="save"><button class="${s.open ? "danger" : ""}">${s.open ? "Close the arm" : "Update the note"}</button></div></form>`; | |
| 332 | return `<section aria-labelledby="open"><h2 id="open">Open / Closed</h2>${now}${!s.open || r ? `<div class="actions">${open}</div>` : ""}${close}</section>`; | |
| 333 | } | |
| 334 | ||
| 301 | 335 | /** The two commits side by side; a mismatch says so, with what the last attempt to fix it came to. */ |
| 302 | 336 | function versionsSection(v: Versions): string { |
| 303 | 337 | const same = v.pi === v.app; |
| @@ -321,9 +355,10 @@ export function renderAdmin(p: AdminPage): string { | ||
| 321 | 355 | "Admin · SO-101", |
| 322 | 356 | `<header> |
| 323 | 357 | <h1>Admin</h1> |
| 324 | <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="/admin/data">Data</a><a href="/admin/camera-list">Cameras</a><a href="/">Back to the arm</a></div> | |
| 358 | <div class="state"><span class="pill${s.paused || p.resting ? " paused" : ""}">${p.resting ? (p.resting.reason === "offline" ? "Offline" : "Closed") : 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="/admin/data">Data</a><a href="/admin/camera-list">Cameras</a><a href="/">Back to the arm</a></div> | |
| 325 | 359 | </header> |
| 326 | 360 | ${flash} |
| 361 | ${openSection(p)} | |
| 327 | 362 | <section aria-labelledby="now"><h2 id="now">Right now</h2> |
| 328 | 363 | <div class="actions"> |
| 329 | 364 | ${p.canEdit ? `${s.paused ? action("resume", "Resume the queue", "go") : action("pause", "Pause the queue")} |
Software/so101/src/admin-routes.ts +7 −1
| @@ -3,6 +3,7 @@ import type { IncomingMessage, ServerResponse } from "node:http"; | ||
| 3 | 3 | import type { Person } from "./identity.ts"; |
| 4 | 4 | import type { Lobby } from "./lobby.ts"; |
| 5 | 5 | import { AdminError, changeFromForm } from "./admin.ts"; |
| 6 | import { openChangeFromForm } from "./opening.ts"; | |
| 6 | 7 | import { sameOrigin } from "./relay.ts"; |
| 7 | 8 | import { adminCsp, DONE, renderAdmin, renderRefusal, type Done } from "./admin-page.ts"; |
| 8 | 9 | import type { Versions } from "./pi-deploy.ts"; |
| @@ -62,7 +63,7 @@ export async function serveAdminPage(lobby: Lobby, req: IncomingMessage, res: Se | ||
| 62 | 63 | const servos = canEdit && (req.method === "GET" || req.method === "HEAD") && askServos ? await askServos() : undefined; |
| 63 | 64 | const video = askVideo?.(); |
| 64 | 65 | const show = (status: number, done: Done | null, error: string | null) => |
| 65 | html(status, renderAdmin({ precision, servos, video, versions: versions?.(), who, canEdit, settings: lobby.admin.settings, snapshot: lobby.turns.snapshot(), log: lobby.admin.log, removed: lobby.chat.removed, muted: lobby.chat.mutedList(), banned: lobby.accounts.bans(), health: lobby.reports.rows(), reports: lobby.lineReports.list(), visitors: canEdit ? { peak: lobby.visitors.peakToday(), hours: lobby.visitors.joinsPerHour() } : undefined, done, error }), canEdit); | |
| 66 | html(status, renderAdmin({ precision, servos, video, versions: versions?.(), who, canEdit, settings: lobby.admin.settings, opening: lobby.opening.state, resting: lobby.resting(), snapshot: lobby.turns.snapshot(), log: lobby.admin.log, removed: lobby.chat.removed, muted: lobby.chat.mutedList(), banned: lobby.accounts.bans(), health: lobby.reports.rows(), reports: lobby.lineReports.list(), visitors: canEdit ? { peak: lobby.visitors.peakToday(), hours: lobby.visitors.joinsPerHour() } : undefined, done, error }), canEdit); | |
| 66 | 67 | if (req.method === "GET" || req.method === "HEAD") { |
| 67 | 68 | const done = url.searchParams.get("done"); |
| 68 | 69 | show(200, done && Object.hasOwn(DONE, done) ? (done as Done) : null, null); |
| @@ -121,6 +122,11 @@ export async function handleAdmin(lobby: Lobby, req: IncomingMessage, res: Serve | ||
| 121 | 122 | lobby.configure(who, { paused: form.get("action") === "pause" }); |
| 122 | 123 | done = form.get("action") === "pause" ? "paused" : "resumed"; |
| 123 | 124 | break; |
| 125 | case "open": | |
| 126 | case "close": | |
| 127 | lobby.setOpen(who, openChangeFromForm(form, act === "open", Date.now())); | |
| 128 | done = act === "open" ? "opened" : "closed"; | |
| 129 | break; | |
| 124 | 130 | case "end": |
| 125 | 131 | lobby.endTurn(who); |
| 126 | 132 | done = "ended"; |
Software/so101/src/camera-feed.ts +7
| @@ -140,6 +140,13 @@ export class CameraFeed { | ||
| 140 | 140 | } else if (this._state === "idle") this.connect(); |
| 141 | 141 | } |
| 142 | 142 | |
| 143 | /** End every viewer's response; with nobody watching, the source is let go after the usual linger. */ | |
| 144 | endViewers(): void { | |
| 145 | for (const v of this.viewers) v.res.end(); | |
| 146 | this.viewers.clear(); | |
| 147 | this.idleCheck(); | |
| 148 | } | |
| 149 | ||
| 143 | 150 | close(): void { |
| 144 | 151 | this.closed = true; |
| 145 | 152 | this.stop(); |
Software/so101/src/cameras.ts +5
| @@ -128,6 +128,11 @@ export class CameraHub { | ||
| 128 | 128 | return this.specs.find((c) => c.id === id)?.source ?? null; |
| 129 | 129 | } |
| 130 | 130 | |
| 131 | /** End every viewer's stream (the arm is resting); each feed lets go of its source once nobody watches, and may open again. */ | |
| 132 | endViewers(): void { | |
| 133 | for (const feed of this.feeds.values()) feed.endViewers(); | |
| 134 | } | |
| 135 | ||
| 131 | 136 | close(): void { |
| 132 | 137 | for (const feed of this.feeds.values()) feed.close(); |
| 133 | 138 | this.feeds.clear(); |
Software/so101/src/lobby.ts +74 −4
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | * {"type": "mute", "id": "<user id>", "on": true|false, "for": "10m"|"1h"|"24h"|"forever"} owner or a moderator (never the owner or a moderator) |
| 16 | 16 | * {"type": "pause", "on": true|false} owner: maintenance; nobody new gets a turn |
| 17 | 17 | * {"type": "settings", "set": {…}} owner: any of src/admin.ts's settings |
| 18 | * {"type": "open", "open": true|false, "note"?, "reopenAt"?} owner: open the room, or close it (src/opening.ts) | |
| 18 | 19 | * {"type": "crew", "settings": {"enabled", "rules", "maxPerMinute"}} owner: the moderator's settings |
| 19 | 20 | * {"type": "removed"} owner: the latest removed lines, answered with {"type": "removed", "lines": [...]} |
| 20 | 21 | * {"type": "visitors"} owner: today's peak and joins per hour, answered with {"type": "visitors", "peak", "hours": [24 numbers, oldest first]} |
| @@ -31,7 +32,7 @@ | ||
| 31 | 32 | * {"type": "clock", "offsetMs", "readBack"} the page's offset to the relay and the read-back hops it saw (src/page-clock.ts) |
| 32 | 33 | * {"type": "pong"} the answer to {"type": "ping"} |
| 33 | 34 | * {"type": "history", "before": 12} anyone: up to HISTORY_PAGE lines older than that one |
| 34 | * Server → client: hello (who you are, and whether you may moderate: delete a line), you (an anonymous socket only: its guest name and colour, once), state (the turn, the line, pause, the announcement and the speed cap), | |
| 35 | * Server → client: hello (who you are, and whether you may moderate: delete a line), you (an anonymous socket only: its guest name and colour, once), state (the turn, the line, pause, the announcement, the speed cap, and `resting`: null, or why the arm rests), | |
| 35 | 36 | * chat (the last CHAT_FIRST lines of the log, and whether there are more), history (an older page, the same way), |
| 36 | 37 | * said, unsaid, muted, admin (owners only: the settings and the admin log), crew (owners only: |
| 37 | 38 | * settings, hidden lines, mute suggestions), banned (owners and moderators), words (owners only), reports (the owner and verified moderators: the |
| @@ -61,6 +62,7 @@ import { Turns, type TurnEvent } from "./turns.ts"; | ||
| 61 | 62 | import { parseReport, ViewerReports } from "./viewer-reports.ts"; |
| 62 | 63 | import { wallMs } from "./clock.ts"; |
| 63 | 64 | import { parseClock } from "./page-clock.ts"; |
| 65 | import { Opening, parseOpenChange, resting, restingWords, type ArmSeen, type Resting } from "./opening.ts"; | |
| 64 | 66 | |
| 65 | 67 | /** How long a mute lasts, by the name the page and the terminal send; null is for good. */ |
| 66 | 68 | export const MUTE_FOR: Record<string, number | null> = { "10m": 600_000, "1h": 3_600_000, "24h": 86_400_000, forever: null }; |
| @@ -86,6 +88,10 @@ export interface LobbyOptions { | ||
| 86 | 88 | countsFile?: string; |
| 87 | 89 | /** The admin settings' file; none keeps them in memory. */ |
| 88 | 90 | adminFile?: string; |
| 91 | /** The open/closed switch's file (src/opening.ts); none keeps it in memory. */ | |
| 92 | openFile?: string; | |
| 93 | /** The arm gone this long rests the room as offline (src/opening.ts, two minutes). */ | |
| 94 | offlineAfterMs?: number; | |
| 89 | 95 | /** The line and the current turn's file; none keeps them in memory. */ |
| 90 | 96 | turnsFile?: string; |
| 91 | 97 | /** Given turns keep their own limits until the owner changes one; made here, they start from the admin settings. */ |
| @@ -130,6 +136,8 @@ export class Lobby { | ||
| 130 | 136 | readonly chat: Chat; |
| 131 | 137 | readonly accounts: Accounts; |
| 132 | 138 | readonly admin: Admin; |
| 139 | /** The owner's open/closed switch. */ | |
| 140 | readonly opening: Opening; | |
| 133 | 141 | readonly filter: WordFilter; |
| 134 | 142 | readonly rules: ChatRules; |
| 135 | 143 | /** What each open page last reported about its own link. */ |
| @@ -151,6 +159,10 @@ export class Lobby { | ||
| 151 | 159 | private readonly chatListeners = new Set<(who: Person) => void>(); |
| 152 | 160 | private readonly readBackListeners = new Set<(ms: number[]) => void>(); |
| 153 | 161 | private readonly arriveListeners = new Set<(tell: (text: string) => void) => void>(); |
| 162 | private readonly restingListeners = new Set<(r: Resting | null) => void>(); | |
| 163 | private arm: ArmSeen = { downSince: null, lastSeenAt: 0 }; | |
| 164 | private rest: Resting | null = null; | |
| 165 | private readonly offlineAfterMs: number | undefined; | |
| 154 | 166 | private readonly pinger: ReturnType<typeof setInterval>; |
| 155 | 167 | private readonly silentMs: number; |
| 156 | 168 | private lastActivityState = 0; |
| @@ -171,6 +183,10 @@ export class Lobby { | ||
| 171 | 183 | const a = this.admin.settings; |
| 172 | 184 | this.turns = options.turns ?? new Turns({ turnMs: a.turnSeconds * 1000, idleMs: a.idleSeconds * 1000, maxQueue: a.maxQueue, file: options.turnsFile }); |
| 173 | 185 | this.turns.setPaused(a.paused); |
| 186 | this.opening = new Opening({ file: options.openFile, now: this.now }); | |
| 187 | this.offlineAfterMs = options.offlineAfterMs; | |
| 188 | this.rest = resting(this.opening.state, this.arm, this.now(), this.offlineAfterMs); | |
| 189 | this.turns.setClosed(this.rest !== null); | |
| 174 | 190 | this.chat = options.chat ?? new Chat({ file: options.chatFile }); |
| 175 | 191 | this.accounts = options.accounts ?? new Accounts(); |
| 176 | 192 | this.filter = new WordFilter(options.wordsFile); |
| @@ -237,6 +253,7 @@ export class Lobby { | ||
| 237 | 253 | |
| 238 | 254 | /** Why this person may not command the arm right now, or null when they may (and then it counts as activity). */ |
| 239 | 255 | refusal(who: Who, req?: IncomingMessage): { status: number; error: string } | null { |
| 256 | if (this.rest) return { status: 503, error: restingWords(this.rest) }; | |
| 240 | 257 | if (this.local) return null; |
| 241 | 258 | if (!who) return { status: 401, error: "join to take control" }; |
| 242 | 259 | if (this.barred(who, req ? visitor(req) : null)) return { status: 403, error: "you are banned: you can still watch" }; |
| @@ -284,6 +301,48 @@ export class Lobby { | ||
| 284 | 301 | if (changed.length) for (const listener of this.changeListeners) listener(); |
| 285 | 302 | } |
| 286 | 303 | |
| 304 | /** Why the arm rests right now, or null while it is open. */ | |
| 305 | resting(): Resting | null { | |
| 306 | return this.rest; | |
| 307 | } | |
| 308 | ||
| 309 | /** The owner opens or closes the room (persisted, logged). Throws AdminError for anyone else or a bad value. */ | |
| 310 | setOpen(who: Who, input: unknown): void { | |
| 311 | if (!who?.owner) throw new AdminError("only the owner can do that"); | |
| 312 | const change = parseOpenChange(input, this.now()); | |
| 313 | if (!this.opening.set(change)) return; | |
| 314 | const s = this.opening.state; | |
| 315 | this.admin.record(who, s.open ? "opened the arm" : `closed the arm${s.note ? `: ${JSON.stringify(s.note)}` : ""}${s.reopenAt ? ` (back ${new Date(s.reopenAt).toISOString().slice(0, 16)}Z)` : ""}`); | |
| 316 | this.broadcastAdmin(); | |
| 317 | this.reconsider(); | |
| 318 | } | |
| 319 | ||
| 320 | /** What the relay knows of the arm, each second and on every change of the link: it may rest the room as offline, or wake it. */ | |
| 321 | armSeen(arm: ArmSeen): void { | |
| 322 | this.arm = arm; | |
| 323 | this.reconsider(); | |
| 324 | } | |
| 325 | ||
| 326 | /** Told each time the room starts or stops resting, with why (null: open again). */ | |
| 327 | onResting(listener: (r: Resting | null) => void): () => void { | |
| 328 | this.restingListeners.add(listener); | |
| 329 | return () => this.restingListeners.delete(listener); | |
| 330 | } | |
| 331 | ||
| 332 | /** Work out resting again; a change ends the turns or lets them start, and everyone hears it. */ | |
| 333 | private reconsider(): void { | |
| 334 | const next = resting(this.opening.state, this.arm, this.now(), this.offlineAfterMs); | |
| 335 | if (JSON.stringify(next) === JSON.stringify(this.rest)) return; | |
| 336 | const was = this.rest; | |
| 337 | this.rest = next; | |
| 338 | if (Boolean(was) !== Boolean(next) || was?.reason !== next?.reason) { | |
| 339 | this.broadcast({ type: "said", message: this.chat.system(next ? restingWords(next) : "The arm is open again") }); | |
| 340 | } | |
| 341 | this.turns.setClosed(next !== null); | |
| 342 | this.broadcastState(); | |
| 343 | for (const listener of this.restingListeners) listener(next); | |
| 344 | } | |
| 345 | ||
| 287 | 346 | /** The owner ends whoever drives now. */ |
| 288 | 347 | endTurn(who: Who): void { |
| 289 | 348 | if (!who?.owner) throw new AdminError("only the owner can do that"); |
| @@ -295,7 +354,8 @@ export class Lobby { | ||
| 295 | 354 | } |
| 296 | 355 | |
| 297 | 356 | /** Ask to drive; for the owner that is taking control now, and it is logged. */ |
| 298 | takeControl(who: Person): "driving" | "queued" | "full" { | |
| 357 | takeControl(who: Person): "driving" | "queued" | "full" | "closed" { | |
| 358 | if (this.rest) return "closed"; | |
| 299 | 359 | if (who.owner && !this.turns.isDriver(who.id)) { |
| 300 | 360 | const d = this.turns.driver; |
| 301 | 361 | this.admin.record(who, d ? `took control from ${d.name}` : "took control"); |
| @@ -479,7 +539,12 @@ export class Lobby { | ||
| 479 | 539 | if (this.barred(who, seat.from)) return this.send(seat, { type: "error", error: "you are banned: you can still watch" }); |
| 480 | 540 | switch (m.type) { |
| 481 | 541 | case "join": |
| 482 | if (this.takeControl(who) === "full") this.send(seat, { type: "error", error: `the line is full (${this.turns.maxQueue}); try again in a little while` }); | |
| 542 | switch (this.takeControl(who)) { | |
| 543 | case "full": | |
| 544 | return this.send(seat, { type: "error", error: `the line is full (${this.turns.maxQueue}); try again in a little while` }); | |
| 545 | case "closed": | |
| 546 | return this.send(seat, { type: "error", error: restingWords(this.rest!) }); | |
| 547 | } | |
| 483 | 548 | return; |
| 484 | 549 | case "ready": |
| 485 | 550 | this.turns.ready(who.id); |
| @@ -526,6 +591,10 @@ export class Lobby { | ||
| 526 | 591 | case "pause": |
| 527 | 592 | if (typeof m.on !== "boolean") return this.send(seat, { type: "error", error: "pause on or off?" }); |
| 528 | 593 | return this.configure(who, { paused: m.on }); |
| 594 | case "open": { | |
| 595 | const { type: _, ...change } = m; | |
| 596 | return this.setOpen(who, change); | |
| 597 | } | |
| 529 | 598 | case "settings": |
| 530 | 599 | return this.configure(who, m.set); |
| 531 | 600 | case "delete": |
| @@ -720,7 +789,7 @@ export class Lobby { | ||
| 720 | 789 | } |
| 721 | 790 | |
| 722 | 791 | private state() { |
| 723 | return { type: "state", ...this.turns.snapshot(), announcement: this.admin.settings.announcement, maxSpeedPercent: this.admin.settings.maxSpeedPercent }; | |
| 792 | return { type: "state", ...this.turns.snapshot(), announcement: this.admin.settings.announcement, maxSpeedPercent: this.admin.settings.maxSpeedPercent, resting: this.rest }; | |
| 724 | 793 | } |
| 725 | 794 | |
| 726 | 795 | private broadcastState(): void { |
| @@ -893,3 +962,4 @@ export class Lobby { | ||
| 893 | 962 | for (const s of this.seats) if (s.ws.readyState === WebSocket.OPEN) s.ws.send(text); |
| 894 | 963 | } |
| 895 | 964 | } |
| 965 |
Software/so101/src/opening.test.ts added +181
| @@ -0,0 +1,181 @@ | ||
| 1 | import { afterEach, describe, 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 { Lobby } from "./lobby.ts"; | |
| 6 | import { DEFAULT_OPEN, NOTE_CHARS, OFFLINE_AFTER_MS, Opening, openChangeFromForm, parseOpenChange, resting, statusFields, type OpenState } from "./opening.ts"; | |
| 7 | import { Turns } from "./turns.ts"; | |
| 8 | ||
| 9 | const T = Date.parse("2026-10-25T18:00:00Z"); | |
| 10 | const live = { downSince: null, lastSeenAt: T - 1000 }; | |
| 11 | const closed = (more: Partial<OpenState> = {}): OpenState => ({ open: false, note: "Back Saturday 10am CT", reopenAt: null, changedAt: T - 60_000, ...more }); | |
| 12 | ||
| 13 | describe("whether the arm rests", () => { | |
| 14 | test("open with the arm live is open; closed is resting, with the note and when it was last open", () => { | |
| 15 | expect(resting(DEFAULT_OPEN, live, T)).toBeNull(); | |
| 16 | expect(resting(closed(), live, T)).toEqual({ reason: "closed", note: "Back Saturday 10am CT", reopenAt: null, lastOpenAt: T - 60_000 }); | |
| 17 | }); | |
| 18 | ||
| 19 | test("a reopen time is said while it is ahead, dropped once it has passed; it never opens the arm by itself", () => { | |
| 20 | expect(resting(closed({ reopenAt: T + 3_600_000 }), live, T)?.reopenAt).toBe(T + 3_600_000); | |
| 21 | const after = resting(closed({ reopenAt: T + 3_600_000 }), live, T + 3_600_001); | |
| 22 | expect(after?.reason).toBe("closed"); | |
| 23 | expect(after?.reopenAt).toBeNull(); | |
| 24 | }); | |
| 25 | ||
| 26 | test("a real arm gone more than two minutes rests the room as offline; two minutes exactly does not", () => { | |
| 27 | const gone = { downSince: T - OFFLINE_AFTER_MS, lastSeenAt: T - OFFLINE_AFTER_MS - 500 }; | |
| 28 | expect(resting(DEFAULT_OPEN, gone, T)).toBeNull(); | |
| 29 | expect(resting(DEFAULT_OPEN, gone, T + 1)).toEqual({ reason: "offline", note: "", reopenAt: null, lastOpenAt: T - OFFLINE_AFTER_MS - 500 }); | |
| 30 | expect(resting(DEFAULT_OPEN, { downSince: T - 200_000, lastSeenAt: 0 }, T)?.lastOpenAt).toBeNull(); | |
| 31 | }); | |
| 32 | ||
| 33 | test("the owner marking it open after the arm went keeps it open (the simulation, on purpose); an older open does not", () => { | |
| 34 | const gone = { downSince: T - 300_000, lastSeenAt: T - 300_000 }; | |
| 35 | expect(resting({ ...DEFAULT_OPEN, changedAt: T - 100_000 }, gone, T)).toBeNull(); | |
| 36 | expect(resting({ ...DEFAULT_OPEN, changedAt: T - 400_000 }, gone, T)?.reason).toBe("offline"); | |
| 37 | }); | |
| 38 | ||
| 39 | test("the owner's closed wins over offline: the card says resting", () => { | |
| 40 | expect(resting(closed(), { downSince: T - 300_000, lastSeenAt: 1 }, T)?.reason).toBe("closed"); | |
| 41 | }); | |
| 42 | ||
| 43 | test("GET /status's fields: open, or why not with ISO times", () => { | |
| 44 | expect(statusFields(null)).toEqual({ open: true }); | |
| 45 | expect(statusFields({ reason: "closed", note: "Back Saturday", reopenAt: T, lastOpenAt: null })).toEqual({ open: false, reason: "closed", note: "Back Saturday", reopenAt: "2026-10-25T18:00:00.000Z", lastOpenAt: null }); | |
| 46 | expect(statusFields({ reason: "offline", note: "", reopenAt: null, lastOpenAt: T })).toMatchObject({ open: false, reason: "offline", note: null }); | |
| 47 | }); | |
| 48 | }); | |
| 49 | ||
| 50 | describe("a change of the switch is checked", () => { | |
| 51 | test("open, a note and a reopen time with its zone", () => { | |
| 52 | expect(parseOpenChange({ open: false, note: " Back\nSaturday ", reopenAt: "2026-10-31T10:00-05:00" }, T)).toEqual({ open: false, note: "Back Saturday", reopenAt: Date.parse("2026-10-31T15:00:00Z") }); | |
| 53 | expect(parseOpenChange({ open: true, note: "kept?", reopenAt: T + 1000 }, T)).toEqual({ open: true, note: "", reopenAt: null }); | |
| 54 | expect(parseOpenChange({ open: false }, T)).toEqual({ open: false, note: "", reopenAt: null }); | |
| 55 | }); | |
| 56 | ||
| 57 | test("anything else is refused, naming what is wrong", () => { | |
| 58 | expect(() => parseOpenChange(null, T)).toThrow(/open/); | |
| 59 | expect(() => parseOpenChange({ open: "no" }, T)).toThrow(/true or false/); | |
| 60 | expect(() => parseOpenChange({ open: false, note: "x".repeat(NOTE_CHARS + 1) }, T)).toThrow(/at most/); | |
| 61 | expect(() => parseOpenChange({ open: false, note: 5 }, T)).toThrow(/text/); | |
| 62 | expect(() => parseOpenChange({ open: false, reopenAt: "2026-10-31T10:00" }, T)).toThrow(/zone/); | |
| 63 | expect(() => parseOpenChange({ open: false, reopenAt: "2026-10-01T10:00Z" }, T)).toThrow(/past/); | |
| 64 | expect(() => parseOpenChange({ open: false, reopenAt: T + 400 * 86_400_000 }, T)).toThrow(/year/); | |
| 65 | expect(() => parseOpenChange({ open: false, admin: true }, T)).toThrow(/no field/); | |
| 66 | }); | |
| 67 | ||
| 68 | test("the /admin form: a local date and time with the page's zone, or UTC without one", () => { | |
| 69 | const form = new URLSearchParams({ note: "Back soon", reopenAt: "2026-10-31T10:00", zone: "-300" }); | |
| 70 | expect(openChangeFromForm(form, false, T)).toEqual({ open: false, note: "Back soon", reopenAt: Date.parse("2026-10-31T15:00:00Z") }); | |
| 71 | expect(openChangeFromForm(new URLSearchParams({ reopenAt: "2026-10-31T10:00" }), false, T).reopenAt).toBe(Date.parse("2026-10-31T10:00:00Z")); | |
| 72 | expect(() => openChangeFromForm(new URLSearchParams({ reopenAt: "soon" }), false, T)).toThrow(/date/); | |
| 73 | expect(() => openChangeFromForm(new URLSearchParams({ reopenAt: "2026-10-31T10:00", zone: "9999" }), false, T)).toThrow(/zone/); | |
| 74 | }); | |
| 75 | }); | |
| 76 | ||
| 77 | describe("the switch is kept", () => { | |
| 78 | let dir = ""; | |
| 79 | afterEach(() => dir && rmSync(dir, { recursive: true, force: true })); | |
| 80 | ||
| 81 | test("closing stamps when it was last open, a new note keeps it, opening stamps it again; all of it survives a restart", () => { | |
| 82 | dir = mkdtempSync(join(tmpdir(), "so101-open-")); | |
| 83 | let now = T; | |
| 84 | const file = join(dir, "open.json"); | |
| 85 | const opening = new Opening({ file, now: () => now }); | |
| 86 | expect(opening.set({ open: false, note: "Out", reopenAt: null })).toBe(true); | |
| 87 | expect(opening.state.changedAt).toBe(T); | |
| 88 | now += 1000; | |
| 89 | expect(opening.set({ open: false, note: "Out", reopenAt: null })).toBe(false); | |
| 90 | expect(opening.set({ open: false, note: "Back Monday", reopenAt: null })).toBe(true); | |
| 91 | expect(opening.state.changedAt).toBe(T); | |
| 92 | expect(new Opening({ file }).state).toEqual({ open: false, note: "Back Monday", reopenAt: null, changedAt: T }); | |
| 93 | now += 1000; | |
| 94 | expect(opening.set({ open: true, note: "", reopenAt: null })).toBe(true); | |
| 95 | now += 1000; | |
| 96 | expect(opening.set({ open: true, note: "", reopenAt: null })).toBe(true); // marked open again, on purpose | |
| 97 | expect(new Opening({ file }).state).toEqual({ open: true, note: "", reopenAt: null, changedAt: T + 3000 }); | |
| 98 | }); | |
| 99 | }); | |
| 100 | ||
| 101 | describe("closed turns", () => { | |
| 102 | test("closing ends anyone's turn, the owner's too, and empties the line; nobody may join until it opens", () => { | |
| 103 | const turns = new Turns(); | |
| 104 | const owner = { id: "o", name: "owner", owner: true }; | |
| 105 | const ann = { id: "a", name: "ann", owner: false }; | |
| 106 | turns.join(owner); | |
| 107 | turns.join(ann); | |
| 108 | const ended: string[] = []; | |
| 109 | turns.on((e) => e.kind === "turn" && e.ended && ended.push(`${e.ended.who.name}: ${e.ended.reason}`)); | |
| 110 | turns.setClosed(true); | |
| 111 | expect(ended).toEqual(["owner: the arm is resting"]); | |
| 112 | expect(turns.snapshot()).toMatchObject({ closed: true, driver: null, queue: [] }); | |
| 113 | expect(turns.join(owner)).toBe("closed"); | |
| 114 | expect(turns.join(ann)).toBe("closed"); | |
| 115 | turns.setClosed(false); | |
| 116 | expect(turns.join(ann)).toBe("driving"); | |
| 117 | turns.dispose(); | |
| 118 | }); | |
| 119 | }); | |
| 120 | ||
| 121 | describe("the lobby's switch", () => { | |
| 122 | const owner = { id: "o", name: "owner", owner: true }; | |
| 123 | const ann = { id: "a", name: "ann", owner: false }; | |
| 124 | ||
| 125 | test("only the owner closes it; closed, no turn starts and every command is refused, the owner's too", () => { | |
| 126 | const lobby = new Lobby(); | |
| 127 | try { | |
| 128 | lobby.takeControl(ann); | |
| 129 | expect(lobby.refusal(ann)).toBeNull(); | |
| 130 | expect(() => lobby.setOpen(ann, { open: false })).toThrow(/owner/); | |
| 131 | const told: unknown[] = []; | |
| 132 | lobby.onResting((r) => told.push(r?.reason ?? null)); | |
| 133 | lobby.setOpen(owner, { open: false, note: "Lights off in the shop" }); | |
| 134 | expect(told).toEqual(["closed"]); | |
| 135 | expect(lobby.resting()).toMatchObject({ reason: "closed", note: "Lights off in the shop" }); | |
| 136 | expect(lobby.turns.driver).toBeNull(); | |
| 137 | expect(lobby.takeControl(ann)).toBe("closed"); | |
| 138 | expect(lobby.takeControl(owner)).toBe("closed"); | |
| 139 | expect(lobby.refusal(ann)).toEqual({ status: 503, error: "The arm is resting" }); | |
| 140 | expect(lobby.refusal(owner)?.status).toBe(503); | |
| 141 | expect(lobby.admin.log.at(-1)?.what).toBe('closed the arm: "Lights off in the shop"'); | |
| 142 | lobby.setOpen(owner, { open: true }); | |
| 143 | expect(told).toEqual(["closed", null]); | |
| 144 | expect(lobby.takeControl(ann)).toBe("driving"); | |
| 145 | } finally { | |
| 146 | lobby.close(); | |
| 147 | } | |
| 148 | }); | |
| 149 | ||
| 150 | test("an arm unheard for over two minutes rests it as offline, and it wakes when the arm answers", () => { | |
| 151 | let now = T; | |
| 152 | const lobby = new Lobby({ now: () => now }); | |
| 153 | try { | |
| 154 | lobby.armSeen({ downSince: T, lastSeenAt: T - 10 }); | |
| 155 | expect(lobby.resting()).toBeNull(); | |
| 156 | now = T + OFFLINE_AFTER_MS + 1; | |
| 157 | lobby.armSeen({ downSince: T, lastSeenAt: T - 10 }); | |
| 158 | expect(lobby.resting()).toEqual({ reason: "offline", note: "", reopenAt: null, lastOpenAt: T - 10 }); | |
| 159 | expect(lobby.refusal(ann)?.error).toBe("The arm is offline right now"); | |
| 160 | lobby.armSeen({ downSince: null, lastSeenAt: now }); | |
| 161 | expect(lobby.resting()).toBeNull(); | |
| 162 | } finally { | |
| 163 | lobby.close(); | |
| 164 | } | |
| 165 | }); | |
| 166 | ||
| 167 | test("the switch is restored on a restart: a closed room starts closed", () => { | |
| 168 | const dir = mkdtempSync(join(tmpdir(), "so101-open-")); | |
| 169 | try { | |
| 170 | const first = new Lobby({ openFile: join(dir, "open.json") }); | |
| 171 | first.setOpen(owner, { open: false, note: "Back Saturday" }); | |
| 172 | first.close(); | |
| 173 | const again = new Lobby({ openFile: join(dir, "open.json") }); | |
| 174 | expect(again.resting()?.note).toBe("Back Saturday"); | |
| 175 | expect(again.takeControl(ann)).toBe("closed"); | |
| 176 | again.close(); | |
| 177 | } finally { | |
| 178 | rmSync(dir, { recursive: true, force: true }); | |
| 179 | } | |
| 180 | }); | |
| 181 | }); |
Software/so101/src/opening.ts added +168
| @@ -0,0 +1,168 @@ | ||
| 1 | /** | |
| 2 | * Open or closed: the owner's switch for the whole room, and the rule for when the arm is resting. | |
| 3 | * | |
| 4 | * Closed (the owner's choice) means no turns and no line, the cameras stop and nothing but a STOP goes to the arm; the | |
| 5 | * page is the resting card (src/resting-page.ts). The owner may leave a note ("Back Saturday 10am CT") and a time it | |
| 6 | * should be back; the time is shown, it never reopens by itself. | |
| 7 | * | |
| 8 | * Offline (nobody's choice): a real arm the relay has not heard from for more than OFFLINE_AFTER_MS rests the room the | |
| 9 | * same way, worded "offline", unless the owner switched it open after the arm went (to show the simulation on purpose). | |
| 10 | * Kept in one JSON file beside the admin settings; plain data in, plain data out. | |
| 11 | */ | |
| 12 | ||
| 13 | import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; | |
| 14 | import { dirname } from "node:path"; | |
| 15 | import { AdminError } from "./admin.ts"; | |
| 16 | import { cleanText } from "./chat.ts"; | |
| 17 | ||
| 18 | /** The arm gone this long, and not marked open since, rests the room as offline. */ | |
| 19 | export const OFFLINE_AFTER_MS = 120_000; | |
| 20 | export const NOTE_CHARS = 140; | |
| 21 | /** A reopen time further out than this is a typo. */ | |
| 22 | const MAX_AHEAD_MS = 366 * 86_400_000; | |
| 23 | ||
| 24 | export interface OpenState { | |
| 25 | open: boolean; | |
| 26 | /** The owner's words for visitors while closed; empty for none. */ | |
| 27 | note: string; | |
| 28 | /** When the owner expects it back, ms since the epoch; null for unsaid. */ | |
| 29 | reopenAt: number | null; | |
| 30 | /** When the switch last moved (0: never): closing says when it was last open, opening says it was on purpose. */ | |
| 31 | changedAt: number; | |
| 32 | } | |
| 33 | ||
| 34 | export const DEFAULT_OPEN: OpenState = { open: true, note: "", reopenAt: null, changedAt: 0 }; | |
| 35 | ||
| 36 | /** What a resting room says, to the page, /status and the terminal. */ | |
| 37 | export interface Resting { | |
| 38 | reason: "closed" | "offline"; | |
| 39 | note: string; | |
| 40 | /** Only while still ahead. */ | |
| 41 | reopenAt: number | null; | |
| 42 | /** When it was last open: the owner closing it, or the arm's last word; null when unknown. */ | |
| 43 | lastOpenAt: number | null; | |
| 44 | } | |
| 45 | ||
| 46 | /** What the relay knows of the arm: since when it is gone (null while live, or with no real arm), and when it last spoke (0: never). */ | |
| 47 | export interface ArmSeen { | |
| 48 | downSince: number | null; | |
| 49 | lastSeenAt: number; | |
| 50 | } | |
| 51 | ||
| 52 | /** Whether the room rests now, and why; null when it is open. */ | |
| 53 | export function resting(state: OpenState, arm: ArmSeen, now: number, offlineAfterMs = OFFLINE_AFTER_MS): Resting | null { | |
| 54 | const reopenAt = state.reopenAt !== null && state.reopenAt > now ? state.reopenAt : null; | |
| 55 | if (!state.open) return { reason: "closed", note: state.note, reopenAt, lastOpenAt: state.changedAt || null }; | |
| 56 | const gone = arm.downSince !== null && now - arm.downSince > offlineAfterMs; | |
| 57 | if (gone && state.changedAt <= arm.downSince!) return { reason: "offline", note: "", reopenAt: null, lastOpenAt: arm.lastSeenAt || null }; | |
| 58 | return null; | |
| 59 | } | |
| 60 | ||
| 61 | /** The one sentence for a resting room: the card's heading, the chat's system line and every refusal. */ | |
| 62 | export function restingWords(r: Resting): string { | |
| 63 | return r.reason === "offline" ? "The arm is offline right now" : "The arm is resting"; | |
| 64 | } | |
| 65 | ||
| 66 | /** GET /status's words on it, for everyone: {"open", "reason"?, "note"?, "reopenAt"?, "lastOpenAt"?}, times as ISO text. */ | |
| 67 | export function statusFields(r: Resting | null): Record<string, unknown> { | |
| 68 | if (!r) return { open: true }; | |
| 69 | const iso = (ms: number | null) => (ms === null ? null : new Date(ms).toISOString()); | |
| 70 | return { open: false, reason: r.reason, note: r.note || null, reopenAt: iso(r.reopenAt), lastOpenAt: iso(r.lastOpenAt) }; | |
| 71 | } | |
| 72 | ||
| 73 | /** Check a change of the switch: {"open": bool, "note"?: text, "reopenAt"?: ISO text with a zone, ms, or null}. Throws AdminError. */ | |
| 74 | export function parseOpenChange(input: unknown, now: number): Omit<OpenState, "changedAt"> { | |
| 75 | if (typeof input !== "object" || input === null || Array.isArray(input)) throw new AdminError("send {\"open\": true|false, \"note\"?, \"reopenAt\"?}"); | |
| 76 | const { open, note = "", reopenAt = null, ...rest } = input as Record<string, unknown>; | |
| 77 | const extra = Object.keys(rest)[0]; | |
| 78 | if (extra !== undefined) throw new AdminError(`no field "${extra.slice(0, 40)}"`); | |
| 79 | if (typeof open !== "boolean") throw new AdminError("open is true or false"); | |
| 80 | if (typeof note !== "string") throw new AdminError("the note is text"); | |
| 81 | if ([...note].length > NOTE_CHARS) throw new AdminError(`the note is at most ${NOTE_CHARS} characters`); | |
| 82 | let text = ""; | |
| 83 | try { | |
| 84 | text = cleanText(note); | |
| 85 | } catch { | |
| 86 | /* nothing printable: no note */ | |
| 87 | } | |
| 88 | let at: number | null = null; | |
| 89 | if (reopenAt !== null && reopenAt !== "") { | |
| 90 | at = typeof reopenAt === "number" ? reopenAt : typeof reopenAt === "string" && /(Z|[+-]\d\d:\d\d)$/.test(reopenAt) ? Date.parse(reopenAt) : NaN; | |
| 91 | if (!Number.isSafeInteger(at)) throw new AdminError("the reopen time is a date and time with its zone, like 2026-10-31T10:00-05:00"); | |
| 92 | if (at <= now) throw new AdminError("the reopen time is in the past"); | |
| 93 | if (at > now + MAX_AHEAD_MS) throw new AdminError("the reopen time is more than a year away"); | |
| 94 | } | |
| 95 | // Open again: the note and the time were for while it was closed. | |
| 96 | return open ? { open, note: "", reopenAt: null } : { open, note: text, reopenAt: at }; | |
| 97 | } | |
| 98 | ||
| 99 | /** | |
| 100 | * The /admin form: action open or close, `note`, and `reopenAt` from a datetime-local input (no zone) with `zone`, the | |
| 101 | * page's minutes east of UTC; without a zone the time is read as UTC. Throws AdminError. | |
| 102 | */ | |
| 103 | export function openChangeFromForm(form: URLSearchParams, open: boolean, now: number): Omit<OpenState, "changedAt"> { | |
| 104 | const local = (form.get("reopenAt") ?? "").trim(); | |
| 105 | let reopenAt: string | null = null; | |
| 106 | if (local) { | |
| 107 | if (!/^\d{4}-\d\d-\d\dT\d\d:\d\d$/.test(local)) throw new AdminError("the reopen time is a date and a time"); | |
| 108 | const zone = (form.get("zone") ?? "").trim(); | |
| 109 | if (zone && !(/^-?\d{1,3}$/.test(zone) && Math.abs(Number(zone)) <= 14 * 60)) throw new AdminError("that time zone is not one"); | |
| 110 | const minutes = zone ? Number(zone) : 0; | |
| 111 | const sign = minutes < 0 ? "-" : "+"; | |
| 112 | const abs = Math.abs(minutes); | |
| 113 | reopenAt = `${local}${sign}${String(Math.floor(abs / 60)).padStart(2, "0")}:${String(abs % 60).padStart(2, "0")}`; | |
| 114 | } | |
| 115 | return parseOpenChange({ open, note: form.get("note") ?? "", reopenAt }, now); | |
| 116 | } | |
| 117 | ||
| 118 | export interface OpeningOptions { | |
| 119 | /** Where the switch is kept; none keeps it in memory. */ | |
| 120 | file?: string; | |
| 121 | now?: () => number; | |
| 122 | } | |
| 123 | ||
| 124 | export class Opening { | |
| 125 | state: OpenState = { ...DEFAULT_OPEN }; | |
| 126 | private readonly file: string | undefined; | |
| 127 | private readonly now: () => number; | |
| 128 | ||
| 129 | constructor(options: OpeningOptions = {}) { | |
| 130 | this.file = options.file; | |
| 131 | this.now = options.now ?? Date.now; | |
| 132 | if (this.file) this.load(); | |
| 133 | } | |
| 134 | ||
| 135 | /** Apply a checked change; returns whether anything changed (the note alone counts). Opening always counts: it is marked open now. */ | |
| 136 | set(change: Omit<OpenState, "changedAt">): boolean { | |
| 137 | const s = this.state; | |
| 138 | if (!change.open && !s.open && s.note === change.note && s.reopenAt === change.reopenAt) return false; | |
| 139 | if (change.open && s.open) { | |
| 140 | this.state = { ...s, changedAt: this.now() }; | |
| 141 | this.save(); | |
| 142 | return true; | |
| 143 | } | |
| 144 | this.state = { ...change, changedAt: s.open === change.open ? s.changedAt : this.now() }; | |
| 145 | this.save(); | |
| 146 | return true; | |
| 147 | } | |
| 148 | ||
| 149 | private load(): void { | |
| 150 | try { | |
| 151 | const raw = JSON.parse(readFileSync(this.file!, "utf8")) as Record<string, unknown>; | |
| 152 | const open = raw.open !== false; | |
| 153 | const reopenAt = typeof raw.reopenAt === "number" && Number.isSafeInteger(raw.reopenAt) ? raw.reopenAt : null; | |
| 154 | const note = typeof raw.note === "string" ? raw.note.slice(0, NOTE_CHARS * 2) : ""; | |
| 155 | const changedAt = typeof raw.changedAt === "number" && Number.isSafeInteger(raw.changedAt) ? raw.changedAt : 0; | |
| 156 | this.state = { open, note: open ? "" : note, reopenAt: open ? null : reopenAt, changedAt }; | |
| 157 | } catch { | |
| 158 | /* none yet, or unreadable: open */ | |
| 159 | } | |
| 160 | } | |
| 161 | ||
| 162 | private save(): void { | |
| 163 | if (!this.file) return; | |
| 164 | mkdirSync(dirname(this.file), { recursive: true }); | |
| 165 | writeFileSync(`${this.file}.tmp`, JSON.stringify(this.state)); | |
| 166 | renameSync(`${this.file}.tmp`, this.file); | |
| 167 | } | |
| 168 | } |
Software/so101/src/relay.ts +42 −3
| @@ -53,6 +53,11 @@ | ||
| 53 | 53 | * GET /story, /story/arm.webp the story of the arm for anyone, docs/story.md with the camera and the week's scorecard; its preview photo (src/story.ts) |
| 54 | 54 | * GET /admin/camera-list the owner's page for the camera list |
| 55 | 55 | * POST /admin/cameras {"name", "source"}, DELETE /admin/cameras/<id> the owner changes the list; viewers see it within seconds |
| 56 | * Resting (the owner closed it, or a real arm unheard for two minutes; src/opening.ts): / is the resting card | |
| 57 | * (src/resting-page.ts), /status answers {"open": false, "reason", "note", "reopenAt", "lastOpenAt"} without asking the | |
| 58 | * arm, every turn has ended, the cameras and /follow are refused (and those open are closed), and nothing goes to the arm | |
| 59 | * but a STOP: anything else is 503. Open, /status carries "open": true. | |
| 60 | * | |
| 56 | 61 | * GET|PUT|DELETE /leader/calibration the signed-in person's own leader calibration (src/leader-map.js), any time, |
| 57 | 62 | * turn or no turn: GET answers it or null, PUT {"joints": {...}} stores it |
| 58 | 63 | */ |
| @@ -101,6 +106,8 @@ import type { Lobby } from "./lobby.ts"; | ||
| 101 | 106 | import { capBody, FrameCap } from "./speed-cap.ts"; |
| 102 | 107 | import { Clock, CommandGate, HELD_CLOSE, isRelease, parseCommand } from "./command-gate.ts"; |
| 103 | 108 | import { FLOOD_CLOSE, FrameRate, frameBytes, MAX_FRAME_BYTES, TOO_BIG_CLOSE } from "./frame-limit.ts"; |
| 109 | import { restingWords, statusFields, type Resting } from "./opening.ts"; | |
| 110 | import { RESTING_CSP, renderResting } from "./resting-page.ts"; | |
| 104 | 111 | |
| 105 | 112 | export interface Remote { |
| 106 | 113 | /** The arm server's HTTP base, no trailing slash. */ |
| @@ -460,16 +467,25 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 460 | 467 | /** STOP's hold, for every stream through here, and each driver's clock (their stamps, seen from here). */ |
| 461 | 468 | const gate = new CommandGate(options.holdFile); |
| 462 | 469 | const clocks = new Map<string, Clock>(); |
| 470 | /** Why the arm rests right now (src/opening.ts), or null while it is open; never resting without a lobby. */ | |
| 471 | const restingNow = (): Resting | null => lobby?.resting() ?? null; | |
| 472 | /** The resting card, in place of the page. */ | |
| 473 | const restingPage = (res: ServerResponse, rest: Resting) => { | |
| 474 | res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "content-security-policy": RESTING_CSP }); | |
| 475 | res.end(renderResting(rest)); | |
| 476 | }; | |
| 463 | 477 | /** |
| 464 | 478 | * The arm's /status, saying which arm it is: from the link while it is live, the last one it had while reconnecting, |
| 465 | 479 | * and from the simulation otherwise. It also adds `driver`, {id, name, owner} of whoever holds the turn (the owner |
| 466 | 480 | * after a take-over) or null, to every answer that has a status; the 503 has none. /status and the /live push share it. |
| 467 | 481 | */ |
| 468 | 482 | const statusOf = async (path = "/status"): Promise<{ code: number; body: Record<string, unknown> }> => { |
| 483 | const rest = restingNow(); | |
| 484 | if (rest) return { code: 200, body: { ...statusFields(rest), driver: null, source: restingWords(rest) } }; | |
| 469 | 485 | const answer = await ownStatus(path); |
| 470 | 486 | const d = lobby?.turns.snapshot().driver; |
| 471 | 487 | if (answer.code === 200) answer.body.driver = d ? { id: d.id, name: d.name, owner: d.owner } : null; |
| 472 | return answer; | |
| 488 | return { code: answer.code, body: { ...answer.body, ...statusFields(null) } }; | |
| 473 | 489 | }; |
| 474 | 490 | /** The arm's status alone, with no word of the turn. */ |
| 475 | 491 | const ownStatus = async (path: string): Promise<{ code: number; body: Record<string, unknown> }> => { |
| @@ -617,9 +633,11 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 617 | 633 | if (lobby.watching === 0) return void (pushed = ""); // the next page to open the room hears it at once |
| 618 | 634 | pushing = true; |
| 619 | 635 | let text: string; |
| 636 | const rest = restingNow(); | |
| 620 | 637 | try { |
| 621 | 638 | const { code, body } = await statusOf(); |
| 622 | text = JSON.stringify(code === 200 ? { type: "status", status: body } : { type: "status", status: null, error: body.error ?? `status ${code}` }); | |
| 639 | // A resting room has no pose: no status, and why (the state frame before it carries the rest, and the page reloads on it). | |
| 640 | text = JSON.stringify(rest ? { type: "status", status: null, error: restingWords(rest), open: false } : code === 200 ? { type: "status", status: body } : { type: "status", status: null, error: body.error ?? `status ${code}` }); | |
| 623 | 641 | } catch (err) { |
| 624 | 642 | text = JSON.stringify({ type: "status", status: null, error: reason(err) }); |
| 625 | 643 | } finally { |
| @@ -785,7 +803,7 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 785 | 803 | if (cameraAdmin) return await administer(req, res, cameraAdmin[1] === undefined ? null : Number(cameraAdmin[1])); |
| 786 | 804 | if (lobby && url.pathname === "/admin/lift") return await handleLift(lobby, req, res, readBody); |
| 787 | 805 | if (lobby && (url.pathname === "/admin" || url.pathname === "/admin/health")) return await handleAdmin(lobby, req, res, url, readBody, askPrecision, askServos, videoCards, options.piSync ? () => options.piSync!.versions() : undefined, tuneP); |
| 788 | if (serveStory(req, res, url.pathname, { cameras: () => cameras.list(), numbers: storyNumbers })) return; | |
| 806 | if (serveStory(req, res, url.pathname, { cameras: () => (restingNow() ? [] : cameras.list()), numbers: storyNumbers })) return; | |
| 789 | 807 | if (url.pathname === "/admin/versions") return versionsRead(req, res); |
| 790 | 808 | if (lobby && url.pathname === "/admin/data") return serveDataPage(lobby, req, res); |
| 791 | 809 | if (url.pathname === "/data") return serveData(facts ?? undefined, lobby ?? undefined, req, res, url); |
| @@ -834,9 +852,11 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 834 | 852 | |
| 835 | 853 | if (route === "POST /precision/snap-back") return await snapBack(req, res); |
| 836 | 854 | |
| 855 | const rest = restingNow(); | |
| 837 | 856 | const camera = CAMERA.exec(url.pathname); |
| 838 | 857 | if (camera) { |
| 839 | 858 | if (!reading) return json(res, 405, { error: "cameras are read-only" }); |
| 859 | if (rest) return json(res, 503, { error: `${restingWords(rest)}: the cameras are off`, open: false }); | |
| 840 | 860 | const id = Number(camera[1]); |
| 841 | 861 | const source = cameras.source(id); |
| 842 | 862 | if (source === null) return json(res, 404, { error: "no such camera" }); |
| @@ -850,8 +870,11 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 850 | 870 | } |
| 851 | 871 | } |
| 852 | 872 | |
| 873 | if (req.method === "GET" && PAGE.test(url.pathname) && rest) return restingPage(res, rest); | |
| 853 | 874 | if (req.method === "GET" && PAGE.test(url.pathname)) return await page(req, res, await ask(simulation + path, req, undefined, null, false)); |
| 854 | 875 | if (req.method === "GET" && STATIC.test(url.pathname) && acceptsGzip(req.headers)) return await packed(res, await ask(simulation + path, req, undefined, null, false), path); |
| 876 | // Resting, nothing reaches an arm but a STOP: not a command, not a read. | |
| 877 | if (rest && !LOCAL.test(url.pathname) && !STOPS.has(route)) return json(res, 503, { error: `${restingWords(rest)}: nothing goes to it now`, open: false }); | |
| 855 | 878 | if (route === "POST /stop" || route === "POST /estop") facts?.event("STOP", lobby ? lobby.who(req)?.id : null); |
| 856 | 879 | if (route === "POST /stop") { |
| 857 | 880 | // Shut before anything is asked of an arm: a frame already on its way finds the gate closed. |
| @@ -1074,6 +1097,8 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 1074 | 1097 | const url = new URL(req.url ?? "/", "http://x"); |
| 1075 | 1098 | const video = VIDEO.exec(url.pathname); |
| 1076 | 1099 | const cameraWs = CAMERA_WS.exec(url.pathname); |
| 1100 | // Resting, the cameras are off; a /follow is closed with the lobby's reason below (4503), which a page can read. | |
| 1101 | if ((cameraWs || video) && restingNow()) return refuse(socket, "503 Service Unavailable"); | |
| 1077 | 1102 | if (cameraWs) { |
| 1078 | 1103 | if (!sameOrigin(req)) return refuse(socket, "403 Forbidden"); |
| 1079 | 1104 | const id = Number(cameraWs[1]); |
| @@ -1131,6 +1156,15 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 1131 | 1156 | // ------------------------------------------------------------------ a turn that ends |
| 1132 | 1157 | // Its streams close (the arm server holds the arm when a stream ends) and a move, playback or recording stops. |
| 1133 | 1158 | const settingsChanged = lobby?.onSettingsChange(follow); |
| 1159 | // Resting: every stream through here (/follow, the cameras over WebSocket and H.264) and every MJPEG viewer is ended. | |
| 1160 | const restingChanged = lobby?.onResting((rest) => { | |
| 1161 | pushed = ""; | |
| 1162 | if (!rest) return; | |
| 1163 | for (const client of wss.clients) client.close(1000, restingWords(rest)); | |
| 1164 | cameras.endViewers(); | |
| 1165 | }); | |
| 1166 | /** What the lobby is told of the arm, for the offline rule: since when a real arm is gone, and when it last spoke. */ | |
| 1167 | const armSeen = () => lobby?.armSeen({ downSince: remote && armLink && armLink.state !== "live" ? armLink.downSince : null, lastSeenAt: armLink?.lastAt ?? 0 }); | |
| 1134 | 1168 | const arrived = lobby?.onArrive((tell) => (pushed ? tell(pushed) : void push())); |
| 1135 | 1169 | // The read-back→browser hops a page measured go to the arm server's scorecard beside the relay's own. |
| 1136 | 1170 | const readBacks = lobby?.onReadBack((ms) => { |
| @@ -1192,6 +1226,9 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 1192 | 1226 | await (armLink as ArmLink | null)?.ready; // bounded by the first attempt's timeout: the first page already knows which arm it has |
| 1193 | 1227 | const timer = lobby ? setInterval(follow, followEveryMs) : undefined; |
| 1194 | 1228 | timer?.unref?.(); |
| 1229 | armSeen(); | |
| 1230 | const seenTimer = lobby ? setInterval(armSeen, 1000) : undefined; | |
| 1231 | seenTimer?.unref?.(); | |
| 1195 | 1232 | const piTimer = options.piSync ? setInterval(() => void options.piSync!.check(), options.piEveryMs ?? 60_000) : undefined; |
| 1196 | 1233 | piTimer?.unref?.(); |
| 1197 | 1234 | if (options.piSync) setTimeout(() => void options.piSync!.check(), 3000).unref?.(); |
| @@ -1208,6 +1245,8 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 1208 | 1245 | close: () => |
| 1209 | 1246 | new Promise<void>((resolve) => { |
| 1210 | 1247 | clearInterval(timer); |
| 1248 | clearInterval(seenTimer); | |
| 1249 | restingChanged?.(); | |
| 1211 | 1250 | clearInterval(pusher); |
| 1212 | 1251 | clearInterval(piTimer); |
| 1213 | 1252 | clearInterval(summary); |
Software/so101/src/resting-page.ts added +123
| @@ -0,0 +1,123 @@ | ||
| 1 | /** | |
| 2 | * The page a visitor gets at / while the arm rests (src/opening.ts): one calm card where the camera would be, saying | |
| 3 | * why (the owner closed it, or the arm is offline), the owner's note, when it should be back and when it was last | |
| 4 | * open, with a way to be told when it is back, the story and the code. No camera, no controls, no error banner. | |
| 5 | * | |
| 6 | * Server-rendered from plain data, every value escaped; times go out as UTC text and the script rewrites them in the | |
| 7 | * visitor's own zone. The script asks GET /status every 20 s: when it says open, it shows the notification the visitor | |
| 8 | * asked for (the browser's own, while this tab stays open) and reloads into the arm. Style and script are inline, each | |
| 9 | * pinned by its hash in the page's Content-Security-Policy, which allows nothing else. | |
| 10 | */ | |
| 11 | ||
| 12 | import { createHash } from "node:crypto"; | |
| 13 | import { esc } from "./admin-page.ts"; | |
| 14 | import { restingWords, type Resting } from "./opening.ts"; | |
| 15 | ||
| 16 | /** The public repository, for "the code". */ | |
| 17 | export const REPO_URL = "https://forge.open-platform.sh/trevato/arm"; | |
| 18 | /** The story page (#565). */ | |
| 19 | export const STORY_PATH = "/story"; | |
| 20 | ||
| 21 | export const RESTING_STYLE = ` | |
| 22 | :root { color-scheme: dark light; --bg: #0b0d10; --card: #11161d; --fg: #e8eaed; --dim: #9aa4ae; --line: #2a313a; --accent: #58a6ff; --calm: #7d8fa3; } | |
| 23 | @media (prefers-color-scheme: light) { :root { --bg: #f6f7f9; --card: #fff; --fg: #1f2328; --dim: #59636e; --line: #d8dee4; --accent: #0969da; --calm: #6e7f91; } } | |
| 24 | * { box-sizing: border-box; } | |
| 25 | html, body { margin: 0; min-height: 100%; } | |
| 26 | body { background: var(--bg); color: var(--fg); font: 16px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; } | |
| 27 | main { min-height: 100vh; min-height: 100dvh; display: grid; align-content: center; padding: max(1rem, env(safe-area-inset-top)) max(1rem, env(safe-area-inset-right)) max(1rem, env(safe-area-inset-bottom)) max(1rem, env(safe-area-inset-left)); } | |
| 28 | .card { width: 100%; margin: 0 auto; background: var(--card); border: 1px solid var(--line); border-radius: 16px; padding: 1.5rem 1.25rem; display: grid; gap: 1rem; } | |
| 29 | .mark { width: 2.75rem; height: 2.75rem; border-radius: 50%; border: 2px solid var(--calm); display: grid; place-items: center; color: var(--calm); font-size: 1.25rem; } | |
| 30 | h1 { margin: 0; font-size: 1.75rem; line-height: 1.2; letter-spacing: -.01em; } | |
| 31 | p { margin: 0; } | |
| 32 | .note { font-size: 1.15rem; overflow-wrap: anywhere; } | |
| 33 | .when { display: grid; gap: .25rem; color: var(--dim); font-variant-numeric: tabular-nums; } | |
| 34 | .when b { color: var(--fg); font-weight: 600; } | |
| 35 | .notify { display: grid; gap: .4rem; justify-items: start; } | |
| 36 | button { font: inherit; font-weight: 600; min-height: 44px; padding: .55rem 1.1rem; border-radius: 10px; border: 1px solid var(--accent); background: var(--accent); color: #fff; cursor: pointer; } | |
| 37 | button:disabled { opacity: .6; cursor: default; } | |
| 38 | button:focus-visible, a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } | |
| 39 | .said { color: var(--dim); font-size: .9rem; min-height: 1.35em; } | |
| 40 | nav { display: flex; flex-wrap: wrap; gap: .5rem 1.25rem; border-top: 1px solid var(--line); padding-top: 1rem; } | |
| 41 | a { color: var(--accent); display: inline-flex; align-items: center; min-height: 44px; } | |
| 42 | @media (min-width: 720px) { | |
| 43 | main { padding: 3rem 2rem; } | |
| 44 | .card { max-width: 40rem; padding: 2.5rem 2.75rem; gap: 1.25rem; } | |
| 45 | h1 { font-size: 2.25rem; } | |
| 46 | } | |
| 47 | `; | |
| 48 | ||
| 49 | export const RESTING_SCRIPT = ` | |
| 50 | const zone = { weekday: "short", month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }; | |
| 51 | for (const t of document.querySelectorAll("time[datetime]")) t.textContent = new Date(t.dateTime).toLocaleString([], zone); | |
| 52 | const button = document.getElementById("notify"); | |
| 53 | const said = document.getElementById("said"); | |
| 54 | let wanted = false; | |
| 55 | if ("Notification" in window) { | |
| 56 | button.hidden = false; | |
| 57 | button.onclick = async () => { | |
| 58 | const answer = Notification.permission === "granted" ? "granted" : await Notification.requestPermission(); | |
| 59 | wanted = answer === "granted"; | |
| 60 | said.textContent = wanted ? "You'll get a notification here when it's back. Keep this tab open." : "Notifications are off for this site; this page still refreshes itself when the arm is back."; | |
| 61 | button.disabled = wanted; | |
| 62 | }; | |
| 63 | } else said.textContent = "This page refreshes itself when the arm is back."; | |
| 64 | async function ask() { | |
| 65 | try { | |
| 66 | const r = await fetch("/status", { cache: "no-store" }); | |
| 67 | const s = await r.json(); | |
| 68 | if (s && s.open === true) { | |
| 69 | if (wanted) new Notification("The arm is back", { body: "Come and drive it." }); | |
| 70 | return location.reload(); | |
| 71 | } | |
| 72 | } catch {} | |
| 73 | setTimeout(ask, 20000); | |
| 74 | } | |
| 75 | setTimeout(ask, 20000); | |
| 76 | `; | |
| 77 | ||
| 78 | const sha = (text: string) => createHash("sha256").update(text).digest("base64"); | |
| 79 | /** The page's Content-Security-Policy: its style and its script, each pinned by hash; it may only ask /status. */ | |
| 80 | export const RESTING_CSP = `default-src 'none'; style-src 'sha256-${sha(RESTING_STYLE)}'; script-src 'sha256-${sha(RESTING_SCRIPT)}'; connect-src 'self'; img-src 'self'; form-action 'none'; frame-ancestors 'none'; base-uri 'none'`; | |
| 81 | ||
| 82 | const time = (ms: number) => { | |
| 83 | const iso = new Date(ms).toISOString(); | |
| 84 | return `<time datetime="${iso}">${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC</time>`; | |
| 85 | }; | |
| 86 | ||
| 87 | /** The resting card as a whole page. */ | |
| 88 | export function renderResting(r: Resting): string { | |
| 89 | const title = restingWords(r); | |
| 90 | const description = r.note || (r.reason === "offline" ? "The arm can't be reached from here just now; it comes back by itself." : "The owner has closed the arm for now."); | |
| 91 | const when = [ | |
| 92 | r.reopenAt !== null ? `<p>Back around <b>${time(r.reopenAt)}</b></p>` : "", | |
| 93 | r.lastOpenAt !== null ? `<p>Last open ${time(r.lastOpenAt)}</p>` : "", | |
| 94 | ].join(""); | |
| 95 | return `<!doctype html> | |
| 96 | <html lang="en"> | |
| 97 | <head> | |
| 98 | <meta charset="utf-8"> | |
| 99 | <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"> | |
| 100 | <meta name="color-scheme" content="dark light"> | |
| 101 | <title>${esc(title)} · SO-101</title> | |
| 102 | <meta name="description" content="${esc(description)}"> | |
| 103 | <meta property="og:title" content="${esc(title)} · SO-101"> | |
| 104 | <meta property="og:description" content="${esc(description)}"> | |
| 105 | <meta property="og:type" content="website"> | |
| 106 | <style>${RESTING_STYLE}</style> | |
| 107 | </head> | |
| 108 | <body> | |
| 109 | <main> | |
| 110 | <section class="card" aria-labelledby="resting"> | |
| 111 | <div class="mark" aria-hidden="true">☾</div> | |
| 112 | <h1 id="resting">${esc(title)}</h1> | |
| 113 | ${r.note ? `<p class="note">${esc(r.note)}</p>` : `<p class="note">${esc(description)}</p>`} | |
| 114 | ${when ? `<div class="when">${when}</div>` : ""} | |
| 115 | <div class="notify"><button type="button" id="notify" hidden>Get notified when it's back</button><p class="said" id="said" role="status"></p></div> | |
| 116 | <nav aria-label="While you wait"><a href="${STORY_PATH}">Read the story of the arm</a><a href="${REPO_URL}">See the code</a></nav> | |
| 117 | </section> | |
| 118 | </main> | |
| 119 | <script>${RESTING_SCRIPT}</script> | |
| 120 | </body> | |
| 121 | </html> | |
| 122 | `; | |
| 123 | } |
Software/so101/src/resting.test.ts added +238
| @@ -0,0 +1,238 @@ | ||
| 1 | import { afterEach, describe, 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 WebSocket from "ws"; | |
| 6 | import { FeetechBus } from "./bus.ts"; | |
| 7 | import { FakeBus } from "./fake-bus.ts"; | |
| 8 | import { sign } from "./identity.ts"; | |
| 9 | import { Lobby } from "./lobby.ts"; | |
| 10 | import { parseRemote, startRelay, type RunningRelay } from "./relay.ts"; | |
| 11 | import { REPO_URL, RESTING_CSP, RESTING_STYLE, STORY_PATH, renderResting } from "./resting-page.ts"; | |
| 12 | import { startServer, type RunningServer } from "./server.ts"; | |
| 13 | ||
| 14 | const KEY = "k".repeat(64); | |
| 15 | const later = Date.now() + 600_000; | |
| 16 | const as = (name: string, role: "user" | "admin") => { | |
| 17 | const identity = `id-${name}|${name}|${role}|${later}`; | |
| 18 | return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) }; | |
| 19 | }; | |
| 20 | const owner = as("trevato", "admin"); | |
| 21 | const form = (body: Record<string, string>) => ({ method: "POST", headers: { ...owner, "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(body), redirect: "manual" as const }); | |
| 22 | const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); | |
| 23 | const shut = (s: { close(): Promise<void> } | undefined) => (s ? Promise.race([s.close(), sleep(500)]) : undefined); | |
| 24 | ||
| 25 | let dir = ""; | |
| 26 | let relay: RunningRelay | undefined; | |
| 27 | let lobby: Lobby | undefined; | |
| 28 | let sim: RunningServer | undefined; | |
| 29 | afterEach(async () => { | |
| 30 | await shut(relay); | |
| 31 | await shut(sim); | |
| 32 | lobby?.close(); | |
| 33 | if (dir) rmSync(dir, { recursive: true, force: true }); | |
| 34 | dir = ""; | |
| 35 | relay = lobby = sim = undefined; | |
| 36 | }); | |
| 37 | ||
| 38 | async function boot(options: { offlineAfterMs?: number; deadArm?: boolean } = {}) { | |
| 39 | dir = mkdtempSync(join(tmpdir(), "so101-resting-")); | |
| 40 | sim = await startServer(new FeetechBus(new FakeBus([1, 2, 3, 4, 5, 6])), { host: "127.0.0.1", port: 0, posesFile: join(dir, "poses.json") }); | |
| 41 | lobby = new Lobby({ identityKey: KEY, adminFile: join(dir, "admin.json"), openFile: join(dir, "open.json"), offlineAfterMs: options.offlineAfterMs }); | |
| 42 | const remote = options.deadArm ? parseRemote({ ARM_SERVER: "ws://127.0.0.1:1" }) : null; | |
| 43 | relay = await startRelay({ port: 0, simulation: `http://127.0.0.1:${sim.port}`, remote, lobby, link: { backoffMs: [20], connectTimeoutMs: 50, offlineAfterMs: 60_000 } }); | |
| 44 | return `http://127.0.0.1:${relay.port}`; | |
| 45 | } | |
| 46 | ||
| 47 | describe("closed by the owner", () => { | |
| 48 | test("the owner closes it on /admin: /status says so for everyone, / is the resting card, a command and the cameras are refused", async () => { | |
| 49 | const base = await boot(); | |
| 50 | const open = await (await fetch(`${base}/status`)).json() as any; | |
| 51 | expect(open.open).toBe(true); | |
| 52 | expect(Array.isArray(open.joints)).toBe(true); | |
| 53 | expect(await (await fetch(`${base}/admin`, { headers: owner })).text()).toContain("Open / Closed"); | |
| 54 | ||
| 55 | const back = new Date(Math.floor(Date.now() / 60_000) * 60_000 + 30 * 86_400_000); | |
| 56 | const local = back.toISOString().slice(0, 16); // read with zone -300: five hours later in UTC | |
| 57 | const closing = await fetch(`${base}/admin`, form({ action: "close", note: "Back Saturday <b>10am</b> CT", reopenAt: local, zone: "-300" })); | |
| 58 | expect(closing.status).toBe(303); | |
| 59 | expect(closing.headers.get("location")).toBe("/admin?done=closed"); | |
| 60 | ||
| 61 | const status = await (await fetch(`${base}/status`)).json() as any; | |
| 62 | expect(status).toMatchObject({ open: false, reason: "closed", note: "Back Saturday <b>10am</b> CT", reopenAt: new Date(back.getTime() + 5 * 3_600_000).toISOString(), driver: null }); | |
| 63 | expect(typeof status.lastOpenAt).toBe("string"); | |
| 64 | expect(status.joints).toBeUndefined(); // the arm was not asked | |
| 65 | ||
| 66 | const page = await fetch(`${base}/`); | |
| 67 | expect(page.status).toBe(200); | |
| 68 | expect(page.headers.get("content-security-policy")).toBe(RESTING_CSP); | |
| 69 | expect(page.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 70 | const html = await page.text(); | |
| 71 | expect(html).toContain("The arm is resting"); | |
| 72 | expect(html).toContain("Back Saturday <b>10am</b> CT"); | |
| 73 | expect(html).not.toContain("<b>10am"); | |
| 74 | expect(html).toContain("Get notified when it's back"); | |
| 75 | expect(html).not.toContain("urdf-viewer"); | |
| 76 | ||
| 77 | for (const route of ["/move", "/torque", "/pose/go", "/resume"]) { | |
| 78 | const refused = await fetch(`${base}${route}`, { method: "POST", headers: { ...owner, "content-type": "application/json" }, body: "{}" }); | |
| 79 | expect([route, refused.status]).toEqual([route, 503]); | |
| 80 | expect((await refused.json() as any).error).toMatch(/The arm is resting/); | |
| 81 | } | |
| 82 | expect((await fetch(`${base}/stop`, { method: "POST", headers: owner })).status).toBe(200); // a STOP is never refused | |
| 83 | expect((await fetch(`${base}/camera/1/stream`)).status).toBe(503); | |
| 84 | expect((await fetch(`${base}/camera/1/snapshot`)).status).toBe(503); | |
| 85 | ||
| 86 | const story = await fetch(`${base}/story`); | |
| 87 | expect(story.status).toBe(200); // the card links to it: it stays up, with no camera to break | |
| 88 | expect(await story.text()).toContain("The camera is not connected right now"); | |
| 89 | ||
| 90 | const follow = new WebSocket(`ws://127.0.0.1:${relay!.port}/follow`, { headers: owner }); | |
| 91 | const refused = await new Promise<string>((resolve) => follow.on("close", (code, why) => resolve(`${code} ${why}`))); | |
| 92 | expect(refused).toBe("4503 The arm is resting"); | |
| 93 | ||
| 94 | expect(lobby!.takeControl({ id: "id-trevato", name: "trevato", owner: true })).toBe("closed"); | |
| 95 | const admin = await (await fetch(`${base}/admin`, { headers: owner })).text(); | |
| 96 | expect(admin).toContain("Closed"); | |
| 97 | expect(admin).toContain("Open the arm"); | |
| 98 | ||
| 99 | expect((await fetch(`${base}/admin`, form({ action: "open" }))).headers.get("location")).toBe("/admin?done=opened"); | |
| 100 | expect((await (await fetch(`${base}/status`)).json() as any).open).toBe(true); | |
| 101 | expect(await (await fetch(`${base}/`)).text()).toContain("urdf-viewer"); | |
| 102 | }); | |
| 103 | ||
| 104 | test("a resting room still answers /live: the state says why, and the status push has no pose", async () => { | |
| 105 | const base = await boot(); | |
| 106 | await fetch(`${base}/admin`, form({ action: "close", note: "Lights off" })); | |
| 107 | const live = new WebSocket(`ws://127.0.0.1:${relay!.port}/live`); | |
| 108 | const seen: Array<Record<string, any>> = []; | |
| 109 | await new Promise<void>((resolve, reject) => { | |
| 110 | const timer = setTimeout(() => reject(new Error(`no status in 2 s: ${JSON.stringify(seen.map((m) => m.type))}`)), 2000); | |
| 111 | live.on("message", (data) => { | |
| 112 | const m = JSON.parse(String(data)); | |
| 113 | seen.push(m); | |
| 114 | if (m.type === "status") (clearTimeout(timer), resolve()); | |
| 115 | }); | |
| 116 | }); | |
| 117 | live.close(); | |
| 118 | expect(seen.find((m) => m.type === "state")?.resting).toMatchObject({ reason: "closed", note: "Lights off" }); | |
| 119 | expect(seen.find((m) => m.type === "status")).toEqual({ type: "status", status: null, error: "The arm is resting", open: false }); | |
| 120 | }); | |
| 121 | ||
| 122 | test("closing ends the driver's open stream and turn at once", async () => { | |
| 123 | const base = await boot(); | |
| 124 | lobby!.takeControl({ id: "id-trevato", name: "trevato", owner: true }); | |
| 125 | const follow = new WebSocket(`ws://127.0.0.1:${relay!.port}/follow`, { headers: owner }); | |
| 126 | await new Promise((resolve, reject) => follow.on("open", resolve).on("error", reject)); | |
| 127 | const closed = new Promise<string>((resolve) => follow.on("close", (_code, why) => resolve(why.toString()))); | |
| 128 | await fetch(`${base}/admin`, form({ action: "close" })); | |
| 129 | expect(await closed).toMatch(/^(your turn ended|The arm is resting)$/); | |
| 130 | expect(lobby!.turns.driver).toBeNull(); | |
| 131 | }); | |
| 132 | ||
| 133 | test("the owner's /live open frame and the terminal's /close do the same; anyone else is told no", async () => { | |
| 134 | await boot(); | |
| 135 | expect(() => lobby!.setOpen({ id: "id-bob", name: "bob", owner: false }, { open: false })).toThrow(/owner/); | |
| 136 | lobby!.setOpen({ id: "id-trevato", name: "trevato", owner: true }, { open: false, note: "Lights off" }); | |
| 137 | expect(lobby!.resting()?.note).toBe("Lights off"); | |
| 138 | }); | |
| 139 | }); | |
| 140 | ||
| 141 | describe("offline by itself", () => { | |
| 142 | test("a real arm unreachable past the limit shows the offline card, never a broken camera; the owner may open it anyway", async () => { | |
| 143 | const base = await boot({ deadArm: true, offlineAfterMs: 300 }); | |
| 144 | let status: Record<string, unknown> = {}; | |
| 145 | for (let i = 0; i < 40 && status.open !== false; i++) { | |
| 146 | await sleep(100); | |
| 147 | status = await (await fetch(`${base}/status`)).json() as any; | |
| 148 | } | |
| 149 | expect(status).toMatchObject({ open: false, reason: "offline", note: null, lastOpenAt: null }); | |
| 150 | const html = await (await fetch(`${base}/`)).text(); | |
| 151 | expect(html).toContain("The arm is offline right now"); | |
| 152 | expect(html).not.toContain("urdf-viewer"); | |
| 153 | expect((await fetch(`${base}/move`, { method: "POST", headers: { ...owner, "content-type": "application/json" }, body: "{}" })).status).toBe(503); | |
| 154 | expect(await (await fetch(`${base}/admin`, { headers: owner })).text()).toContain("Open anyway"); | |
| 155 | ||
| 156 | await fetch(`${base}/admin`, form({ action: "open" })); | |
| 157 | expect((await (await fetch(`${base}/status`)).json() as any).open).toBe(true); | |
| 158 | }); | |
| 159 | }); | |
| 160 | ||
| 161 | // Read, not rendered: the card's CSS resolved at the two screens the issue names, the way a browser picks its @media blocks. | |
| 162 | type Rule = { selector: string; body: string }; | |
| 163 | function rulesAt(w: number, h: number): Rule[] { | |
| 164 | const holds = (query: string) => | |
| 165 | query.split(/\s+and\s+/).every((part) => { | |
| 166 | const [name, value] = part.trim().replace(/^\(|\)$/g, "").split(":").map((s) => s.trim()); | |
| 167 | if (name === "min-width") return w >= parseFloat(value!); | |
| 168 | if (name === "prefers-color-scheme") return value === "dark"; | |
| 169 | throw new Error(`unread media feature ${part}`); | |
| 170 | }); | |
| 171 | const out: Rule[] = []; | |
| 172 | const walk = (src: string) => { | |
| 173 | let i = 0; | |
| 174 | while (i < src.length) { | |
| 175 | const open = src.indexOf("{", i); | |
| 176 | if (open < 0) break; | |
| 177 | let depth = 1; | |
| 178 | let j = open + 1; | |
| 179 | for (; j < src.length && depth; j++) depth += src[j] === "{" ? 1 : src[j] === "}" ? -1 : 0; | |
| 180 | const head = src.slice(i, open).trim(); | |
| 181 | const body = src.slice(open + 1, j - 1); | |
| 182 | if (head.startsWith("@media")) { | |
| 183 | if (holds(head.slice(6).trim())) walk(body); | |
| 184 | } else for (const s of head.split(",")) out.push({ selector: s.trim(), body }); | |
| 185 | i = j; | |
| 186 | } | |
| 187 | }; | |
| 188 | walk(RESTING_STYLE.replace(/\/\*[\s\S]*?\*\//g, "")); | |
| 189 | void h; | |
| 190 | return out; | |
| 191 | } | |
| 192 | const prop = (rules: Rule[], selector: string, name: string) => { | |
| 193 | let found: string | undefined; | |
| 194 | for (const r of rules) { | |
| 195 | if (r.selector !== selector) continue; | |
| 196 | for (const decl of r.body.split(";")) { | |
| 197 | const [k, ...v] = decl.split(":"); | |
| 198 | if (k?.trim() === name) found = v.join(":").trim(); | |
| 199 | } | |
| 200 | } | |
| 201 | return found; | |
| 202 | }; | |
| 203 | ||
| 204 | describe("the resting card", () => { | |
| 205 | const rest = { reason: "closed" as const, note: "Back Saturday 10am CT", reopenAt: Date.parse("2026-10-31T15:00:00Z"), lastOpenAt: Date.parse("2026-10-25T02:00:00Z") }; | |
| 206 | ||
| 207 | test("it says why, the note, when it is back and when it was last open, and points to the story and the code", () => { | |
| 208 | const html = renderResting(rest); | |
| 209 | expect(html).toContain("<h1 id=\"resting\">The arm is resting</h1>"); | |
| 210 | expect(html).toContain("Back Saturday 10am CT"); | |
| 211 | expect(html).toContain('Back around <b><time datetime="2026-10-31T15:00:00.000Z">'); | |
| 212 | expect(html).toContain('Last open <time datetime="2026-10-25T02:00:00.000Z">'); | |
| 213 | expect(html).toContain(`href="${STORY_PATH}"`); | |
| 214 | expect(html).toContain(`href="${REPO_URL}"`); | |
| 215 | expect(html).toContain('<meta property="og:description" content="Back Saturday 10am CT">'); | |
| 216 | expect(html).not.toMatch(/reconnect|error|spinner/i); | |
| 217 | expect(renderResting({ reason: "offline", note: "", reopenAt: null, lastOpenAt: null })).toContain("The arm is offline right now"); | |
| 218 | }); | |
| 219 | ||
| 220 | test("at 390×844 the card fills the width with room to breathe; nothing in it is wider than the phone", () => { | |
| 221 | const rules = rulesAt(390, 844); | |
| 222 | expect(prop(rules, ".card", "width")).toBe("100%"); | |
| 223 | expect(prop(rules, ".card", "max-width")).toBeUndefined(); | |
| 224 | expect(prop(rules, "main", "padding")).toContain("max(1rem"); | |
| 225 | expect(prop(rules, ".note", "overflow-wrap")).toBe("anywhere"); | |
| 226 | expect(prop(rules, "nav", "flex-wrap")).toBe("wrap"); | |
| 227 | expect(prop(rules, "button", "min-height")).toBe("44px"); | |
| 228 | expect(RESTING_STYLE.replace(/@media[^{]*/g, "")).not.toMatch(/\b(?:[4-9]\d\d|\d{4,})px/); // no fixed size past a phone's | |
| 229 | }); | |
| 230 | ||
| 231 | test("at 1440×900 the card is a calm column in the middle of the screen", () => { | |
| 232 | const rules = rulesAt(1440, 900); | |
| 233 | expect(prop(rules, ".card", "max-width")).toBe("40rem"); | |
| 234 | expect(prop(rules, ".card", "margin")).toBe("0 auto"); | |
| 235 | expect(prop(rules, "main", "align-content")).toBe("center"); | |
| 236 | expect(prop(rules, "h1", "font-size")).toBe("2.25rem"); | |
| 237 | }); | |
| 238 | }); |
Software/so101/src/terminal.test.ts +22 −1
| @@ -12,7 +12,7 @@ import { identify, sign } from "./identity.ts"; | ||
| 12 | 12 | import { Lobby } from "./lobby.ts"; |
| 13 | 13 | import { startRelay, type RunningRelay } from "./relay.ts"; |
| 14 | 14 | import { startServer, type RunningServer } from "./server.ts"; |
| 15 | import { traceLines, traceReader, alignReader, cardReader, Door, tuningReader, servosLines, servosReader, emptyRoom, hear, precisionLines, liveUrl, machineEntry, machineLines, machineUrl, healthLines, plain, poster, reader, terminalHeaders, typed } from "./terminal.ts"; | |
| 15 | import { traceLines, traceReader, alignReader, cardReader, Door, tuningReader, servosLines, servosReader, emptyRoom, hear, precisionLines, liveUrl, machineEntry, machineLines, machineUrl, healthLines, plain, poster, reader, terminalHeaders, typed, who } from "./terminal.ts"; | |
| 16 | 16 | import { jointRows } from "./ui/machine.js"; |
| 17 | 17 | import { Turns } from "./turns.ts"; |
| 18 | 18 | |
| @@ -776,3 +776,24 @@ describe("/trace", () => { | ||
| 776 | 776 | expect(printed.join("\n")).toContain("not available here"); |
| 777 | 777 | }); |
| 778 | 778 | }); |
| 779 | ||
| 780 | describe("open and closed in the terminal", () => { | |
| 781 | test("/close takes the rest of the line as the note, /open takes nothing; the server checks who may", () => { | |
| 782 | const room = emptyRoom(); | |
| 783 | expect(typed(room, "/close Back Saturday 10am CT")).toEqual({ send: { type: "open", open: false, note: "Back Saturday 10am CT" } }); | |
| 784 | expect(typed(room, "/close")).toEqual({ send: { type: "open", open: false, note: "" } }); | |
| 785 | expect(typed(room, "/open")).toEqual({ send: { type: "open", open: true } }); | |
| 786 | expect(typed(room, "/open now")).toEqual({ print: "usage: /open" }); | |
| 787 | }); | |
| 788 | ||
| 789 | test("the room says once when it starts resting, with the note, and once when it opens again; /who leads with it", () => { | |
| 790 | const room = emptyRoom(); | |
| 791 | const state = (resting: unknown) => hear(room, { type: "state", driver: null, queue: [], paused: false, resting }); | |
| 792 | expect(state(null)).toEqual([]); | |
| 793 | expect(state({ reason: "closed", note: "Lights\noff", reopenAt: Date.parse("2026-10-31T15:00:00Z"), lastOpenAt: null })).toEqual(["The arm is resting: Lights off (back around 2026-10-31 15:00 UTC)"]); | |
| 794 | expect(who(room)).toStartWith("The arm is resting: Lights off"); | |
| 795 | expect(state({ reason: "closed", note: "Lights\noff", reopenAt: Date.parse("2026-10-31T15:00:00Z"), lastOpenAt: null })).toEqual([]); | |
| 796 | expect(state({ reason: "offline", note: "", reopenAt: null, lastOpenAt: null })).toEqual(["The arm is offline right now"]); | |
| 797 | expect(state(null)).toEqual(["the arm is open again"]); | |
| 798 | }); | |
| 799 | }); |
Software/so101/src/terminal.ts +21 −4
| @@ -336,6 +336,8 @@ export interface Room { | ||
| 336 | 336 | driver: Someone | null; |
| 337 | 337 | queue: Someone[]; |
| 338 | 338 | paused: boolean; |
| 339 | /** Why the arm rests, as a line ("The arm is resting: back Saturday"); null while it is open. */ | |
| 340 | resting: string | null; | |
| 339 | 341 | /** The arm's STOP: who and when, as a line; null while it may move, undefined until the first status. */ |
| 340 | 342 | held: string | null | undefined; |
| 341 | 343 | /** Whether the call to confirm, and the "you are next" cue, were already printed (each is said once). */ |
| @@ -352,7 +354,7 @@ export interface Room { | ||
| 352 | 354 | presence: string | null; |
| 353 | 355 | } |
| 354 | 356 | |
| 355 | export const emptyRoom = (): Room => ({ you: null, muted: false, banned: false, driver: null, queue: [], paused: false, held: undefined, told: { called: false, next: false }, seen: new Map(), latest: new Map(), reports: null, refused: null, presence: null }); | |
| 357 | export const emptyRoom = (): Room => ({ you: null, muted: false, banned: false, driver: null, queue: [], paused: false, resting: null, held: undefined, told: { called: false, next: false }, seen: new Map(), latest: new Map(), reports: null, refused: null, presence: null }); | |
| 356 | 358 | |
| 357 | 359 | const someone = (x: unknown): Someone | null => { |
| 358 | 360 | if (typeof x !== "object" || x === null) return null; |
| @@ -379,7 +381,7 @@ const said = (room: Room, m: unknown): string => { | ||
| 379 | 381 | const TUNE_USAGE = "usage: /tune <joint, e.g. shoulder_pan or 1> <P, 1 to 64>, or /tune alone for the run so far"; |
| 380 | 382 | const ZERO_USAGE = "usage: /zero <joint, e.g. shoulder_pan> [degrees the model should read, default 0]"; |
| 381 | 383 | const DATA_USAGE = "usage: /data [hour|day|week|all] or /data #<turn>"; |
| 382 | export const HELP = "type to chat · /join /leave /ready /extend · /stop /resume (driver, owner) · /end [who] /table here|touch 1|2|3|<mm> /zero <joint> [deg] /align [joint] (owner) · /mute <who> /unmute <who> (owner, moderator) · /delete <who|#id> (owner, moderator) · /report <who|#id> · /reports /dismiss #<id> (owner, moderator) · /removed /restore #<id> /visitors (owner) · /health /precision /trace <session> /data [hour|day|week|all|#<turn>] /versions (owner, moderator) · /servos /tune [<joint> <P>] (owner) · /machine [off] · /who · /quit"; | |
| 384 | export const HELP = "type to chat · /join /leave /ready /extend · /stop /resume (driver, owner) · /end [who] /table here|touch 1|2|3|<mm> /zero <joint> [deg] /align [joint] (owner) · /mute <who> /unmute <who> (owner, moderator) · /delete <who|#id> (owner, moderator) · /report <who|#id> · /reports /dismiss #<id> (owner, moderator) · /removed /restore #<id> /visitors (owner) · /close [note] /open (owner) · /health /precision /trace <session> /data [hour|day|week|all|#<turn>] /versions (owner, moderator) · /servos /tune [<joint> <P>] (owner) · /machine [off] · /who · /quit"; | |
| 383 | 385 | |
| 384 | 386 | /** The Machine feed's socket beside the lobby's: same app, same port. */ |
| 385 | 387 | export const machineUrl = (live: string): string => live.replace(/\/live$/, "/machine"); |
| @@ -450,7 +452,10 @@ export function hear(room: Room, frame: Frame): string[] { | ||
| 450 | 452 | room.paused = frame.paused === true; |
| 451 | 453 | see(room, room.driver); |
| 452 | 454 | for (const p of room.queue) see(room, p); |
| 453 | return cues(room, frame.driver); | |
| 455 | const was = room.resting; | |
| 456 | room.resting = restingLine(frame.resting); | |
| 457 | const told = room.resting !== was ? [room.resting ?? "the arm is open again"] : []; | |
| 458 | return [...told, ...cues(room, frame.driver)]; | |
| 454 | 459 | } |
| 455 | 460 | case "chat": { |
| 456 | 461 | const messages = Array.isArray(frame.messages) ? frame.messages : []; |
| @@ -507,12 +512,21 @@ export function hear(room: Room, frame: Frame): string[] { | ||
| 507 | 512 | } |
| 508 | 513 | } |
| 509 | 514 | |
| 515 | /** A state frame's `resting` as one line: why, and the owner's note; null when it is open. */ | |
| 516 | function restingLine(x: unknown): string | null { | |
| 517 | if (typeof x !== "object" || x === null) return null; | |
| 518 | const { reason, note, reopenAt } = x as Record<string, unknown>; | |
| 519 | const why = reason === "offline" ? "The arm is offline right now" : "The arm is resting"; | |
| 520 | const back = typeof reopenAt === "number" ? ` (back around ${new Date(reopenAt).toISOString().slice(0, 16).replace("T", " ")} UTC)` : ""; | |
| 521 | return `${why}${typeof note === "string" && note ? `: ${plain(note)}` : ""}${back}`; | |
| 522 | } | |
| 523 | ||
| 510 | 524 | /** One report as a line: the line's number, its author, the words, and who reported it. */ |
| 511 | 525 | const reportLine = (x: Record<string, unknown>): string => `report #${plain(x.id)} ${plain(x.author)}: ${plain(x.text)} (by ${plain(x.reporter)})`; |
| 512 | 526 | |
| 513 | 527 | export function who(room: Room): string { |
| 514 | 528 | const line = room.queue.length ? room.queue.map((p, i) => `${i + 1}. ${plain(p.name)}`).join(" ") : "nobody waiting"; |
| 515 | return `${room.paused ? "paused · " : ""}${room.driver ? `${plain(room.driver.name)} has control` : "nobody has control"} · ${line}${room.presence ? ` · ${room.presence}` : ""}`; | |
| 529 | return `${room.resting ? `${room.resting} · ` : room.paused ? "paused · " : ""}${room.driver ? `${plain(room.driver.name)} has control` : "nobody has control"} · ${line}${room.presence ? ` · ${room.presence}` : ""}`; | |
| 516 | 530 | } |
| 517 | 531 | |
| 518 | 532 | /** A typed <who>: a name the door has seen, else taken as an id. */ |
| @@ -546,6 +560,9 @@ export function typed(room: Room, input: string): Typed { | ||
| 546 | 560 | return { tune: { joint: Number(joint), p: Number(rest[0]) } }; |
| 547 | 561 | } |
| 548 | 562 | if (/^data$/i.test(verb) && rest.length) return { print: DATA_USAGE }; |
| 563 | // The owner's switch (src/opening.ts): the note is the rest of the line, spaces and all; the server checks it. | |
| 564 | if (/^close$/i.test(verb)) return { send: { type: "open", open: false, note: line.slice(1 + verb.length).trim() } }; | |
| 565 | if (/^open$/i.test(verb)) return arg ? { print: "usage: /open" } : { send: { type: "open", open: true } }; | |
| 549 | 566 | const timed = /^mute$/i.test(verb) && rest.length === 1 && /^(10m|1h|24h|forever)$/i.test(rest[0]!); |
| 550 | 567 | if (rest.length && !timed && /^unmute$/i.test(verb)) return { print: "usage: /unmute <name>" }; |
| 551 | 568 | const touching = /^table$/i.test(verb) && /^touch$/i.test(arg) && rest.length === 1; |
Software/so101/src/turns.ts +22 −5
| @@ -5,7 +5,8 @@ | ||
| 5 | 5 | * connection for `graceMs`; someone waiting in line who loses their connection for `graceMs` leaves the line. |
| 6 | 6 | * The owner jumps the line: asking to drive ends whoever drives now. The owner can also end anyone's turn. |
| 7 | 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. | |
| 8 | * the line holds at most `maxQueue`. Closed (src/opening.ts), nobody drives, not even the owner, and there is no line. | |
| 9 | * Turn length and idle allowance change live, the current turn included. | |
| 9 | 10 | * Plain state and deadlines; one timer, set to the nearest deadline, runs `check()`. |
| 10 | 11 | */ |
| 11 | 12 | |
| @@ -23,7 +24,7 @@ export interface Turn extends Person { | ||
| 23 | 24 | bonusMs: number; |
| 24 | 25 | } |
| 25 | 26 | |
| 26 | export type EndReason = "handed back" | "time is up" | "idle" | "not ready" | "disconnected" | "ended by the owner" | "taken over by the owner" | "paused for maintenance"; | |
| 27 | export type EndReason = "handed back" | "time is up" | "idle" | "not ready" | "disconnected" | "ended by the owner" | "taken over by the owner" | "paused for maintenance" | "the arm is resting"; | |
| 27 | 28 | |
| 28 | 29 | export type TurnEvent = { kind: "turn"; ended: { who: Person; reason: EndReason } | null; started: Person | null } | { kind: "queue" }; |
| 29 | 30 | |
| @@ -32,6 +33,8 @@ export interface Snapshot { | ||
| 32 | 33 | turnMs: number; |
| 33 | 34 | idleMs: number; |
| 34 | 35 | paused: boolean; |
| 36 | /** Resting: no turns and no line at all. */ | |
| 37 | closed: boolean; | |
| 35 | 38 | maxQueue: number; |
| 36 | 39 | driver: { id: string; name: string; owner: boolean; endsAt: number; idleEndsAt: number; readyBy: number | null } | null; |
| 37 | 40 | queue: Array<{ id: string; name: string; place: number; waitMs: number }>; |
| @@ -57,6 +60,7 @@ export class Turns { | ||
| 57 | 60 | readyMs: number; |
| 58 | 61 | maxQueue: number; |
| 59 | 62 | paused: boolean; |
| 63 | closed = false; | |
| 60 | 64 | private readonly now: () => number; |
| 61 | 65 | private readonly file: string | undefined; |
| 62 | 66 | driver: Turn | null = null; |
| @@ -89,7 +93,8 @@ export class Turns { | ||
| 89 | 93 | } |
| 90 | 94 | |
| 91 | 95 | /** Ask to drive: drive now when nobody does, the owner takes over, everyone else gets in line (unless it is full). */ |
| 92 | join(who: Person): "driving" | "queued" | "full" { | |
| 96 | join(who: Person): "driving" | "queued" | "full" | "closed" { | |
| 97 | if (this.closed) return "closed"; | |
| 93 | 98 | if (this.isDriver(who.id)) return "driving"; |
| 94 | 99 | if (who.owner) { |
| 95 | 100 | this.remove(who.id); |
| @@ -121,6 +126,17 @@ export class Turns { | ||
| 121 | 126 | else this.emit({ kind: "queue" }); |
| 122 | 127 | } |
| 123 | 128 | |
| 129 | /** Resting or open. Closing ends anyone's turn, the owner's too, and empties the line; opening starts with nobody. */ | |
| 130 | setClosed(on: boolean): void { | |
| 131 | if (this.closed === on) return; | |
| 132 | this.closed = on; | |
| 133 | if (!on) return this.emit({ kind: "queue" }); | |
| 134 | this.queue.splice(0); | |
| 135 | this.gone.clear(); | |
| 136 | if (this.driver) this.handOver("the arm is resting"); | |
| 137 | else this.emit({ kind: "queue" }); | |
| 138 | } | |
| 139 | ||
| 124 | 140 | /** New limits, live: the current turn is measured against them at once. Someone already in a longer line keeps their place. */ |
| 125 | 141 | configure(limits: { turnMs?: number; idleMs?: number; maxQueue?: number }): void { |
| 126 | 142 | if (limits.turnMs !== undefined) this.turnMs = limits.turnMs; |
| @@ -212,6 +228,7 @@ export class Turns { | ||
| 212 | 228 | turnMs: this.turnMs, |
| 213 | 229 | idleMs: this.idleMs, |
| 214 | 230 | paused: this.paused, |
| 231 | closed: this.closed, | |
| 215 | 232 | maxQueue: Number.isFinite(this.maxQueue) ? this.maxQueue : -1, |
| 216 | 233 | driver: d ? { id: d.id, name: d.name, owner: d.owner, endsAt: d.endsAt, idleEndsAt: Math.min(d.endsAt, d.lastActive + this.idleMs), readyBy: d.readyBy } : null, |
| 217 | 234 | // At most: a turn can end early, never late. |
| @@ -236,8 +253,8 @@ export class Turns { | ||
| 236 | 253 | const ended = this.driver && reason ? { who: { id: this.driver.id, name: this.driver.name, owner: this.driver.owner }, reason } : null; |
| 237 | 254 | if (reason) this.driver = null; |
| 238 | 255 | if (this.driver) return; |
| 239 | const called = next ? undefined : this.paused ? undefined : this.queue.shift(); | |
| 240 | const who = next ?? called; | |
| 256 | const called = next || this.closed ? undefined : this.paused ? undefined : this.queue.shift(); | |
| 257 | const who = this.closed ? undefined : next ?? called; | |
| 241 | 258 | const now = this.now(); |
| 242 | 259 | // Only someone called out of the line has to confirm; a person who asked for an idle arm is looking at it. |
| 243 | 260 | this.driver = who ? { ...who, startedAt: now, endsAt: now + this.turnMs, lastActive: now, readyBy: called && confirm ? now + this.readyMs : null, bonusMs: 0 } : null; |
Software/so101/src/ui/lobby-panel.js +4 −1
| @@ -360,7 +360,10 @@ export function createRoom(page) { | ||
| 360 | 360 | if (m.type === "refused") return page.refused?.(m); |
| 361 | 361 | if (m.type === "status") { tell("pose"); if (m.status?.readAt !== undefined) tell("clock-status", m.status.readAt); lobby.statusSeen = true; return m.status ? page.applyStatus(m.status) : page.noStatus(); } |
| 362 | 362 | if (m.type === "hello") lobby.hello = m; |
| 363 | else if (m.type === "state") { lobby.offset = m.now - Date.now(); lobby.state = m; } | |
| 363 | else if (m.type === "state") { | |
| 364 | if (m.resting) return location.reload(); // the room rests: the server answers / with the resting card, no dead camera or controls | |
| 365 | lobby.offset = m.now - Date.now(); lobby.state = m; | |
| 366 | } | |
| 364 | 367 | else if (m.type === "chat") return addChat(m.messages, true), showEarlier(m.more); |
| 365 | 368 | else if (m.type === "history") return addOlder(m.messages, m.more); |
| 366 | 369 | else if (m.type === "said") return addChat([m.message]); |
Software/so101/src/ui/lobby-panel.test.ts +23
| @@ -87,6 +87,29 @@ describe("the room over /live", () => { | ||
| 87 | 87 | } finally { Object.assign(g, saved); } |
| 88 | 88 | }); |
| 89 | 89 | |
| 90 | test("a state that says the arm rests reloads the page into the resting card; an open one does not", () => { | |
| 91 | const sockets: any[] = [], reloads: number[] = []; | |
| 92 | const g = globalThis as any, saved = { WebSocket: g.WebSocket, setInterval: g.setInterval, location: g.location }; | |
| 93 | g.WebSocket = class { readyState = 1; sent: string[] = []; constructor() { sockets.push(this); } send(m: string) { this.sent.push(m); } }; | |
| 94 | g.setInterval = () => 0; | |
| 95 | g.location = { protocol: "http:", host: "x", pathname: "/", search: "", reload: () => reloads.push(1) }; | |
| 96 | try { | |
| 97 | const nodes = new Map<string, any>(); | |
| 98 | const page = { | |
| 99 | $: (id: string) => nodes.get(id) ?? (nodes.set(id, node()), nodes.get(id)), | |
| 100 | el: (tag: string, props: object = {}) => Object.assign(node(), { tag }, props), | |
| 101 | relayed: true, tab: () => "chat", showTab() {}, applyLock() {}, applyStatus() {}, noStatus() {}, words() {}, admin() {}, note() {}, msg() {}, | |
| 102 | }; | |
| 103 | createRoom(page).lobbyConnect(); | |
| 104 | const state = { type: "state", now: Date.now(), driver: null, queue: [], paused: false, closed: false, maxQueue: 20, turnMs: 180000, idleMs: 30000 }; | |
| 105 | sockets[0].onmessage({ data: JSON.stringify({ type: "hello", signin: false, you: null }) }); | |
| 106 | sockets[0].onmessage({ data: JSON.stringify({ ...state, resting: null }) }); | |
| 107 | expect(reloads).toEqual([]); | |
| 108 | sockets[0].onmessage({ data: JSON.stringify({ ...state, closed: true, resting: { reason: "closed", note: "", reopenAt: null, lastOpenAt: null } }) }); | |
| 109 | expect(reloads).toEqual([1]); | |
| 110 | } finally { Object.assign(g, saved); } | |
| 111 | }); | |
| 112 | ||
| 90 | 113 | test("when /live closes: backoff 0.1 to 2 s, a chip until the first message, no motion, no reload", () => { |
| 91 | 114 | const sockets: any[] = [], delays: number[] = [], timers: (() => void)[] = []; |
| 92 | 115 | const g = globalThis as any, saved = { WebSocket: g.WebSocket, setInterval: g.setInterval, setTimeout: g.setTimeout, location: g.location }; |
new above
offline