Public: anyone can read this; the crew can change it.
Migrated from github.com/Trevato/SO-ARM100
workbenchthis machine
The admin page shows the table height and a 'the arm rests on the table now - set the table here' button #184
smith/arm:smith/163-the-admin-page-shows-the-table-height-an → main 4 commits fork 3 threads · 3 unresolved
7 files
changed +238
−25
Software/README.md +10 −3
| @@ -515,13 +515,20 @@ or from the **Admin** tab that only the owner sees: | ||
| 515 | 515 | checked as `ARM_SERVER` is). The relay follows it at once for every viewer |
| 516 | 516 | (it shows in `/link`; the camera list is the owner's own); empty uses the |
| 517 | 517 | `ARM_SERVER` environment variable, then the simulation. |
| 518 | - **Table**: the owner sets the table height (-100 to 100 mm above the | |
| 519 | model's table) or presses "The arm rests on the table now - set the table | |
| 520 | here", which puts the table under the arm's lowest point. A moderator only | |
| 521 | reads the value. Each action goes to the arm server (or the simulation when | |
| 522 | there is none) and is checked there. In the terminal, `/table` reads it, | |
| 523 | `/table 12` sets it and `/table here` presses the button; they go through the | |
| 524 | app's `/admin/table`, which gates them as the page is (anyone but the owner and the | |
| 525 | moderators gets 404; a moderator can read and gets 403 on a write). The other settings are still | |
| 526 | web-only. | |
| 518 | 527 | - **Moderators**: usernames the owner names on `/admin`. A moderator can open |
| 519 | 528 | `/admin` and read the settings and the log, and change nothing. A moderator |
| 520 | 529 | is matched on the forge-signed identity (the forge username), never on a |
| 521 | 530 | name a guest typed: a guest who picks a moderator's name still gets a 403. |
| 522 | Settings are web-only because this app has no terminal (`forge.json` has no | |
| 523 | `tty`); the `so101` command line drives the arm hardware and does not run | |
| 524 | the relay. | |
| 531 | The `so101` command line drives the arm hardware and does not run the relay. | |
| 525 | 532 | |
| 526 | 533 | The settings take effect at once and survive a restart: they are stored in |
| 527 | 534 | `$FORGE_APP_DATA/so101/admin.json`. Every change and every owner action |
Software/so101/src/admin-page.ts +15 −1
| @@ -53,7 +53,7 @@ time { color: var(--dim); font-variant-numeric: tabular-nums; } | ||
| 53 | 53 | export const ADMIN_CSP = `default-src 'none'; style-src 'sha256-${createHash("sha256").update(STYLE).digest("base64")}'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'`; |
| 54 | 54 | |
| 55 | 55 | /** The fixed lines a redirect back may ask for; nothing from the request is echoed. */ |
| 56 | export const DONE = { saved: "Saved.", paused: "Paused: nobody new gets a turn.", resumed: "Open again: the next in line has control.", ended: "Turn ended.", taken: "You have control." } as const; | |
| 56 | export 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.", table: "The table is set." } as const; | |
| 57 | 57 | export type Done = keyof typeof DONE; |
| 58 | 58 | |
| 59 | 59 | export interface AdminPage { |
| @@ -62,6 +62,10 @@ export interface AdminPage { | ||
| 62 | 62 | canEdit: boolean; |
| 63 | 63 | settings: AdminSettings; |
| 64 | 64 | snapshot: Snapshot; |
| 65 | /** The arm server's table height, mm above the model's; null when it did not say. */ | |
| 66 | tableOffsetMm?: number | null; | |
| 67 | /** Why the arm server's answer is missing, when it did not answer. */ | |
| 68 | tableProblem?: string | null; | |
| 65 | 69 | log: readonly LogEntry[]; |
| 66 | 70 | done?: Done | null; |
| 67 | 71 | error?: string | null; |
| @@ -112,6 +116,15 @@ export function renderAdmin(p: AdminPage): string { | ||
| 112 | 116 | const log = p.log.length |
| 113 | 117 | ? `<ol>${[...p.log].reverse().map((e) => `<li>${time(e.at)}<span><b>${esc(e.by.name)}</b> ${esc(e.what)}</span></li>`).join("")}</ol>` |
| 114 | 118 | : `<p class="empty">Nothing yet.</p>`; |
| 119 | const t = p.tableOffsetMm; | |
| 120 | const table = p.tableProblem | |
| 121 | ? `<p class="flash bad" role="alert">${esc(p.tableProblem)}: the table height is not known.</p>` | |
| 122 | : t === null || t === undefined | |
| 123 | ? `<p class="empty">The arm server did not say where the table is.</p>` | |
| 124 | : p.canEdit | |
| 125 | ? `<form method="post" action="/admin"><input type="hidden" name="action" value="table-set"><div class="grid"><label>Table height<small>mm above the model's table, -100 to 100</small><input name="tableOffsetMm" aria-label="Table height in millimetres above the model's table" type="number" inputmode="numeric" required min="-100" max="100" step="1" value="${t}"></label></div><div class="save actions"><button>Set the table height</button></div></form> | |
| 126 | <div class="save">${action("table-here", "The arm rests on the table now - set the table here", "go")}</div>` | |
| 127 | : `<p>Table height: <b>${t}</b> mm above the model's table.</p>`; | |
| 115 | 128 | return page( |
| 116 | 129 | "Admin · SO-101", |
| 117 | 130 | `<header> |
| @@ -139,6 +152,7 @@ ${field("maxQueue", "Max queue length", "people waiting, 0–100", s.maxQueue, 0 | ||
| 139 | 152 | ${p.canEdit ? `<div class="save"><button class="go">Save settings</button></div>` : ""} |
| 140 | 153 | </form> |
| 141 | 154 | </section> |
| 155 | <section aria-labelledby="table"><h2 id="table">Table</h2>${table}</section> | |
| 142 | 156 | <section aria-labelledby="mods"><h2 id="mods">Moderators</h2>${mods}</section> |
| 143 | 157 | <section aria-labelledby="log"><h2 id="log">Log</h2>${log}</section>`, |
| 144 | 158 | ); |
Software/so101/src/admin-relay.test.ts +39
| @@ -123,3 +123,42 @@ test("/status names who is driving: null, then alice, then the owner after a tak | ||
| 123 | 123 | sim.stop(true); |
| 124 | 124 | } |
| 125 | 125 | }); |
| 126 | ||
| 127 | test("/admin shows the table height to the owner with the buttons that move it, and to a moderator as text only; the owner can set it", async () => { | |
| 128 | const stub = Bun.serve({ | |
| 129 | port: 0, | |
| 130 | fetch: async (r) => { | |
| 131 | const path = new URL(r.url).pathname; | |
| 132 | if (path === "/settings" && r.method === "GET") return Response.json({ tableOffsetMm: table }); | |
| 133 | if (path === "/settings" && r.method === "PUT") return Response.json({ tableOffsetMm: (table = ((await r.json()) as { tableOffsetMm: number }).tableOffsetMm) }); | |
| 134 | if (path === "/settings/table-here") return Response.json({ tableOffsetMm: (table = -12) }); | |
| 135 | return new Response("no", { status: 404 }); | |
| 136 | }, | |
| 137 | }); | |
| 138 | let table = 7; | |
| 139 | try { | |
| 140 | const base = await boot(); | |
| 141 | const owner = as("trevato", "admin"); | |
| 142 | const bob = as("bob", "user"); | |
| 143 | await fetch(`${base}/admin`, form(owner, { action: "save", armServer: `http://127.0.0.1:${stub.port}` })); | |
| 144 | await fetch(`${base}/admin`, form(owner, { action: "mod-add", name: "bob" })); | |
| 145 | const mine = await (await fetch(`${base}/admin`, { headers: owner })).text(); | |
| 146 | expect(mine).toContain('name="tableOffsetMm"'); | |
| 147 | expect(mine).toContain('value="7"'); | |
| 148 | expect(mine).toContain('value="table-here"'); | |
| 149 | const theirs = await (await fetch(`${base}/admin`, { headers: bob })).text(); | |
| 150 | expect(theirs).toContain("Table height: <b>7</b>"); | |
| 151 | expect(theirs).not.toContain('name="tableOffsetMm"'); | |
| 152 | expect(theirs).not.toContain("table-here"); | |
| 153 | expect((await fetch(`${base}/admin`, form(bob, { action: "table-here" }))).status).toBe(403); | |
| 154 | expect((await fetch(`${base}/admin`, form(bob, { action: "table-set", tableOffsetMm: "1" }))).status).toBe(403); | |
| 155 | expect(table).toBe(7); | |
| 156 | expect((await fetch(`${base}/admin`, form(owner, { action: "table-set", tableOffsetMm: "500" }))).status).toBe(400); | |
| 157 | expect((await fetch(`${base}/admin`, form(owner, { action: "table-set", tableOffsetMm: "-3" }))).status).toBe(303); | |
| 158 | expect(table).toBe(-3); | |
| 159 | expect((await fetch(`${base}/admin`, form(owner, { action: "table-here" }))).status).toBe(303); | |
| 160 | expect(await (await fetch(`${base}/admin`, { headers: owner })).text()).toContain('value="-12"'); | |
| 161 | } finally { | |
| 162 | stub.stop(true); | |
| 163 | } | |
| 164 | }); |
Software/so101/src/admin-routes.ts +85 −11
| @@ -5,42 +5,74 @@ import type { Lobby } from "./lobby.ts"; | ||
| 5 | 5 | import { AdminError, changeFromForm } from "./admin.ts"; |
| 6 | 6 | import { ADMIN_CSP, DONE, renderAdmin, renderRefusal, type Done } from "./admin-page.ts"; |
| 7 | 7 | |
| 8 | /** The arm server's table plane, as the owner's page reads and moves it; each throws an AdminError saying why not. */ | |
| 9 | export interface ArmTable { | |
| 10 | /** The table height now, mm, or null when the arm server answered without one; throws when it did not answer. */ | |
| 11 | read: () => Promise<number | null>; | |
| 12 | set: (mm: number) => Promise<void>; | |
| 13 | /** Put the table under the arm's lowest point now. */ | |
| 14 | here: () => Promise<void>; | |
| 15 | } | |
| 16 | ||
| 17 | /** A table height from a person: a whole number of mm, -100 to 100. */ | |
| 18 | export function tableMm(text: unknown): number { | |
| 19 | const mm = typeof text === "number" ? text : typeof text === "string" && /^-?\d{1,3}$/.test(text) ? Number(text) : NaN; | |
| 20 | if (!Number.isInteger(mm) || mm < -100 || mm > 100) throw new AdminError("the table height is a whole number of mm, -100 to 100"); | |
| 21 | return mm; | |
| 22 | } | |
| 23 | ||
| 8 | 24 | /** What a POST needs once the caller is known to be allowed on the page. */ |
| 9 | 25 | export interface AdminSession { |
| 10 | 26 | who: Person; |
| 11 | 27 | canEdit: boolean; |
| 12 | 28 | /** Render the page with this status, and a notice or an error. */ |
| 13 | show: (status: number, done: Done | null, error: string | null) => void; | |
| 29 | show: (status: number, done: Done | null, error: string | null) => Promise<void>; | |
| 14 | 30 | /** Answer with the refusal page. */ |
| 15 | 31 | refuse: (status: number) => void; |
| 16 | 32 | } |
| 17 | 33 | |
| 34 | /** Who may open the owner's page, or the table's door: the owner (who edits) or a verified moderator (who reads); null for anyone else. */ | |
| 35 | export function adminAccess(lobby: Lobby, req: IncomingMessage): { who: Person; canEdit: boolean } | null { | |
| 36 | const who = lobby.who(req); | |
| 37 | const canEdit = Boolean(who?.owner); | |
| 38 | // a moderator is named by forge username and must hold that forge identity: a guest who types the same name is not them | |
| 39 | return who && (canEdit || (lobby.verified(req)?.id === who.id && lobby.admin.isModerator(who.name))) ? { who, canEdit } : null; | |
| 40 | } | |
| 41 | ||
| 18 | 42 | /** |
| 19 | 43 | * Answer 404 to anyone not allowed, and the page itself to GET and HEAD. Returns the session for any other |
| 20 | 44 | * method by an allowed caller, and null when the response has been sent. |
| 21 | 45 | */ |
| 22 | export function serveAdminPage(lobby: Lobby, req: IncomingMessage, res: ServerResponse, url: URL): AdminSession | null { | |
| 46 | export async function serveAdminPage(lobby: Lobby, arm: ArmTable | undefined, req: IncomingMessage, res: ServerResponse, url: URL): Promise<AdminSession | null> { | |
| 23 | 47 | const who = lobby.who(req); |
| 24 | 48 | const html = (status: number, text: string) => { |
| 25 | 49 | res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "content-security-policy": ADMIN_CSP }); |
| 26 | 50 | res.end(text); |
| 27 | 51 | }; |
| 28 | const canEdit = Boolean(who?.owner); | |
| 29 | // a moderator is named by forge username and must hold that forge identity: a guest who types the same name is not them | |
| 30 | if (!who || !(canEdit || (lobby.verified(req)?.id === who.id && lobby.admin.isModerator(who.name)))) { | |
| 52 | const access = adminAccess(lobby, req); | |
| 53 | if (!access) { | |
| 31 | 54 | // the page is no secret to a moderator, but to anyone else it does not exist: the answer is the ordinary not-found one |
| 32 | 55 | res.writeHead(404, { "content-type": "application/json", "cache-control": "no-store" }); |
| 33 | 56 | res.end(JSON.stringify({ error: "no such route" })); |
| 34 | 57 | return null; |
| 35 | 58 | } |
| 36 | const show = (status: number, done: Done | null, error: string | null) => | |
| 37 | html(status, renderAdmin({ who, canEdit, settings: lobby.admin.settings, snapshot: lobby.turns.snapshot(), log: lobby.admin.log, done, error })); | |
| 59 | const { canEdit } = access; | |
| 60 | const show = async (status: number, done: Done | null, error: string | null) => { | |
| 61 | let tableOffsetMm: number | null | undefined; | |
| 62 | let tableProblem: string | null = null; | |
| 63 | try { | |
| 64 | tableOffsetMm = await arm?.read(); | |
| 65 | } catch (err) { | |
| 66 | tableProblem = err instanceof AdminError ? err.message : "the arm server did not answer"; | |
| 67 | } | |
| 68 | html(status, renderAdmin({ who: access.who, canEdit, tableOffsetMm, tableProblem, settings: lobby.admin.settings, snapshot: lobby.turns.snapshot(), log: lobby.admin.log, done, error })); | |
| 69 | }; | |
| 38 | 70 | if (req.method === "GET" || req.method === "HEAD") { |
| 39 | 71 | const done = url.searchParams.get("done"); |
| 40 | show(200, done && Object.hasOwn(DONE, done) ? (done as Done) : null, null); | |
| 72 | await show(200, done && Object.hasOwn(DONE, done) ? (done as Done) : null, null); | |
| 41 | 73 | return null; |
| 42 | 74 | } |
| 43 | return { who, canEdit, show, refuse: (status) => html(status, renderRefusal(who)) }; | |
| 75 | return { who: access.who, canEdit, show, refuse: (status) => html(status, renderRefusal(access.who)) }; | |
| 44 | 76 | } |
| 45 | 77 | |
| 46 | 78 | /** The largest form the page may post. */ |
| @@ -50,8 +82,8 @@ const MAX_FORM = 16_384; | ||
| 50 | 82 | type ReadBody = (req: IncomingMessage, limit?: number) => Promise<Buffer>; |
| 51 | 83 | |
| 52 | 84 | /** The owner's page. Anyone else is told so; a change is a form post, answered with a redirect back. */ |
| 53 | export async function handleAdmin(lobby: Lobby, req: IncomingMessage, res: ServerResponse, url: URL, readBody: ReadBody): Promise<void> { | |
| 54 | const session = serveAdminPage(lobby, req, res, url); | |
| 85 | export async function handleAdmin(lobby: Lobby, arm: ArmTable | undefined, req: IncomingMessage, res: ServerResponse, url: URL, readBody: ReadBody): Promise<void> { | |
| 86 | const session = await serveAdminPage(lobby, arm, req, res, url); | |
| 55 | 87 | if (!session) return; |
| 56 | 88 | const { who, canEdit, show } = session; |
| 57 | 89 | if (req.method !== "POST") { |
| @@ -96,6 +128,16 @@ export async function handleAdmin(lobby: Lobby, req: IncomingMessage, res: Serve | ||
| 96 | 128 | lobby.takeControl(who); |
| 97 | 129 | done = "taken"; |
| 98 | 130 | break; |
| 131 | case "table-here": | |
| 132 | case "table-set": { | |
| 133 | if (!arm) throw new AdminError("there is no arm server to set the table on"); | |
| 134 | if (form.get("action") === "table-here") await arm.here(); | |
| 135 | else { | |
| 136 | await arm.set(tableMm(form.get("tableOffsetMm"))); | |
| 137 | } | |
| 138 | done = "table"; | |
| 139 | break; | |
| 140 | } | |
| 99 | 141 | default: |
| 100 | 142 | throw new AdminError("no such action"); |
| 101 | 143 | } |
| @@ -106,3 +148,35 @@ export async function handleAdmin(lobby: Lobby, req: IncomingMessage, res: Serve | ||
| 106 | 148 | res.writeHead(303, { location: `/admin?done=${done}`, "cache-control": "no-store" }); |
| 107 | 149 | res.end(); |
| 108 | 150 | } |
| 151 | ||
| 152 | /** | |
| 153 | * /admin/table, the terminal's door to the table plane, gated as the page is: GET for the owner and a moderator, | |
| 154 | * POST ({tableOffsetMm} or {here: true}) for the owner only; anyone else gets the ordinary 404. | |
| 155 | */ | |
| 156 | export async function handleTable(lobby: Lobby, arm: ArmTable | undefined, req: IncomingMessage, res: ServerResponse, readBody: ReadBody): Promise<void> { | |
| 157 | const send = (status: number, body: unknown) => { | |
| 158 | res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" }); | |
| 159 | res.end(JSON.stringify(body)); | |
| 160 | }; | |
| 161 | const access = adminAccess(lobby, req); | |
| 162 | if (!access) return send(404, { error: "no such route" }); // as for the page: to anyone else it does not exist | |
| 163 | if (!arm) return send(409, { error: "there is no arm server to ask" }); | |
| 164 | try { | |
| 165 | if (req.method === "GET") return send(200, { tableOffsetMm: await arm.read(), canEdit: access.canEdit }); | |
| 166 | if (req.method !== "POST") return send(405, { error: "GET or POST" }); | |
| 167 | if (!access.canEdit) return send(403, { error: "only the owner can set the table" }); | |
Add the same-origin check here, or earlier in handleTable, and require a JSON content-type. Add a test that a foreign-Origin POST by the owner is refused. |
||
| 168 | let body: Record<string, unknown>; | |
| 169 | try { | |
| 170 | body = JSON.parse((await readBody(req, MAX_FORM)).toString("utf8") || "{}"); | |
| 171 | if (typeof body !== "object" || body === null || Array.isArray(body)) throw new Error(); | |
| 172 | } catch { | |
| 173 | return send(400, { error: "a JSON object, please" }); | |
| 174 | } | |
| 175 | if (body.here === true) await arm.here(); | |
| 176 | else await arm.set(tableMm(body.tableOffsetMm)); | |
| 177 | return send(200, { tableOffsetMm: await arm.read() }); | |
| 178 | } catch (err) { | |
| 179 | if (err instanceof AdminError) return send(400, { error: err.message }); | |
| 180 | throw err; | |
| 181 | } | |
| 182 | } |
Software/so101/src/relay.ts +31 −2
| @@ -64,7 +64,8 @@ import { acceptsGzip, GzipCache, worthCompressing } from "./compress.ts"; | ||
| 64 | 64 | import { AccountError, sessionCookie, visitor } from "./accounts.ts"; |
| 65 | 65 | import { CameraSocket } from "./camera-socket.ts"; |
| 66 | 66 | import { OFFLINE_FRAME } from "./offline-frame.ts"; |
| 67 | import { handleAdmin } from "./admin-routes.ts"; | |
| 67 | import { AdminError } from "./admin.ts"; | |
| 68 | import { handleAdmin, handleTable, type ArmTable } from "./admin-routes.ts"; | |
| 68 | 69 | import { parseFps, type FeedOptions } from "./camera-feed.ts"; |
| 69 | 70 | import { CameraError, CameraHub } from "./cameras.ts"; |
| 70 | 71 | import { LOCAL as LOCAL_PERSON } from "./identity.ts"; |
| @@ -522,6 +523,33 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 522 | 523 | } |
| 523 | 524 | }; |
| 524 | 525 | |
| 526 | /** The table plane on the arm server that is the arm now (the simulation when none is), for the owner's page. */ | |
| 527 | const armTable: ArmTable = { | |
| 528 | read: async () => { | |
| 529 | let r: Response; | |
| 530 | try { | |
| 531 | r = await fetch(`${onArm() ? remote!.http : simulation}/settings`, { signal: AbortSignal.timeout(readTimeoutMs), cache: "no-store" }); | |
| 532 | } catch (err) { | |
| 533 | throw new AdminError(`the arm server did not answer (${reason(err)})`); | |
| 534 | } | |
| 535 | if (!r.ok) throw new AdminError(await whyNot(r, "/settings")); | |
| 536 | const v = ((await r.json().catch(() => ({}))) as { tableOffsetMm?: unknown }).tableOffsetMm; | |
| 537 | return typeof v === "number" && Number.isFinite(v) ? v : null; | |
| 538 | }, | |
| 539 | set: async (mm) => void (await tableCall("/settings", "PUT", { tableOffsetMm: mm })), | |
| 540 | here: async () => void (await tableCall("/settings/table-here", "POST", {})), | |
| 541 | }; | |
| 542 | const tableCall = async (path: string, method: string, body: object) => { | |
| 543 | try { | |
| 544 | const r = await fetch(`${onArm() ? remote!.http : simulation}${path}`, { method, headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(readTimeoutMs), cache: "no-store" }); | |
| 545 | if (!r.ok) throw new AdminError(await whyNot(r, path)); | |
| 546 | await r.body?.cancel(); | |
| 547 | } catch (err) { | |
| 548 | if (err instanceof AdminError) throw err; | |
| 549 | throw new AdminError(`the arm server did not answer (${reason(err)})`); | |
| 550 | } | |
| 551 | }; | |
| 552 | ||
| 525 | 553 | /** Resume once the arm server has: one that is still held would refuse the stream anyway. One too old for /resume (404) has no hold of its own. */ |
| 526 | 554 | const resume = async (res: ServerResponse, by: string) => { |
| 527 | 555 | const real = Boolean(remote && onArm()); |
| @@ -550,7 +578,8 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 550 | 578 | } |
| 551 | 579 | const cameraAdmin = ADMIN_CAMERA.exec(url.pathname); |
| 552 | 580 | if (cameraAdmin) return await administer(req, res, cameraAdmin[1] === undefined ? null : Number(cameraAdmin[1])); |
| 553 | if (lobby && url.pathname === "/admin") return await handleAdmin(lobby, req, res, url, readBody); | |
| 581 | if (lobby && url.pathname === "/admin/table") return await handleTable(lobby, armTable, req, res, readBody); | |
| 582 | if (lobby && url.pathname === "/admin") return await handleAdmin(lobby, armTable, req, res, url, readBody); | |
| 554 | 583 | if (url.pathname === LEADER) return await leaderCalibration(req, res); |
| 555 | 584 | if (url.pathname === "/join") { |
| 556 | 585 | if (req.method === "POST") return await join(req, res); |
Software/so101/src/terminal.test.ts +32
| @@ -344,4 +344,36 @@ describe("terminal door", () => { | ||
| 344 | 344 | await alice.printedLine(/^STOPPED by trevato/); |
| 345 | 345 | await waitFor(() => (alice.printed.filter((l) => /^resumed/.test(l)).length === 2 ? true : undefined), "the owner's resume on alice's terminal"); |
| 346 | 346 | }); |
| 347 | ||
| 348 | test("/table: the owner reads and sets it and the arm server hears it; a moderator reads and is refused a write; a guest sees nothing", async () => { | |
| 349 | const port = await start(); | |
| 350 | lobby!.admin.set({ id: "u-owner", name: "trevato", owner: true }, { moderators: ["bob"] }); | |
| 351 | const owner = await terminal(port, ttyEnv("u-owner", "trevato", "admin")); | |
| 352 | owner.door.input("/table"); | |
| 353 | await owner.printedLine(/^table height: 0 mm/); | |
| 354 | owner.door.input("/table 12"); | |
| 355 | await owner.printedLine(/^table height: 12 mm .*\(set\)/); | |
| 356 | expect(((await (await fetch(`http://127.0.0.1:${simulation.port}/settings`)).json()) as { tableOffsetMm: number }).tableOffsetMm).toBe(12); | |
| 357 | owner.door.input("/table 500"); | |
| 358 | await owner.printedLine(/^usage: \/table/); | |
| 359 | ||
| 360 | const bob = await terminal(port, ttyEnv("u-bob", "bob", "user")); | |
| 361 | bob.door.input("/table"); | |
| 362 | await bob.printedLine(/^table height: 12 mm/); | |
| 363 | bob.door.input("/table 3"); | |
| 364 | await bob.printedLine(/^error: only the owner can set the table/); | |
| 365 | bob.door.input("/table here"); | |
| 366 | await waitFor(() => (bob.printed.filter((l) => /only the owner can set/.test(l)).length === 2 ? true : undefined), "a second refusal"); | |
| 367 | expect(((await (await fetch(`http://127.0.0.1:${simulation.port}/settings`)).json()) as { tableOffsetMm: number }).tableOffsetMm).toBe(12); | |
| 368 | ||
| 369 | const carol = await terminal(port, ttyEnv("u-carol", "carol", "user")); | |
| 370 | carol.door.input("/table"); | |
| 371 | await carol.printedLine(/^error: no such route/); | |
| 372 | const guest = await terminal(port, {}); | |
| 373 | guest.door.input("/table 1"); | |
| 374 | await guest.printedLine(/^error: no such route/); | |
| 375 | expect(typed(emptyRoom(), "/table here")).toEqual({ table: "here" }); | |
| 376 | expect(typed(emptyRoom(), "/table -5")).toEqual({ table: -5 }); | |
| 377 | await fetch(`http://127.0.0.1:${simulation.port}/settings`, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ tableOffsetMm: 0 }) }); | |
| 378 | }); | |
| 347 | 379 | }); |
Software/so101/src/terminal.ts +26 −8
| @@ -21,6 +21,7 @@ | ||
| 21 | 21 | * /resume the driver or an admin: end the hold; the arm stays put until a new command |
| 22 | 22 | * /end [who] owner: end that turn (none: whoever drives), or take them out of the line |
| 23 | 23 | * /mute <who> /unmute <who> owner |
| 24 | * /table [mm|here] owner: set the table height (-100..100 mm), or here: the arm rests on it now; a moderator reads it | |
| 24 | 25 | * /machine [off] the Machine panel (/machine, src/machine-feed.ts): the joints, the link and the server as they are, |
| 25 | 26 | * then every command in and out as it happens, in the page's own words (src/ui/machine.js); off stops it |
| 26 | 27 | * /who /help /quit |
| @@ -66,17 +67,18 @@ function appPort(env: Env): number { | ||
| 66 | 67 | return port; |
| 67 | 68 | } |
| 68 | 69 | |
| 69 | export type Post = (path: "/stop" | "/resume") => Promise<{ status: number; error: string | null }>; | |
| 70 | export type Post = (path: string, body?: object, method?: string) => Promise<{ status: number; error: string | null; body: Record<string, unknown> }>; | |
| 70 | 71 | |
| 71 | 72 | /** POST to the app as the page does, signed afresh for each request (a signature is good for a minute). */ |
| 72 | 73 | export function poster(env: Env, fetcher: typeof fetch = fetch): Post { |
| 73 | return async (path) => { | |
| 74 | return async (path, payload = {}, method = "POST") => { | |
| 74 | 75 | try { |
| 75 | const r = await fetcher(`${appUrl(env)}${path}`, { method: "POST", headers: { "content-type": "application/json", ...terminalHeaders(env) }, body: "{}", signal: AbortSignal.timeout(5000) }); | |
| 76 | const body = (await r.json().catch(() => ({}))) as { error?: unknown }; | |
| 77 | return { status: r.status, error: r.ok ? null : plain(body.error ?? `status ${r.status}`) }; | |
| 76 | const r = await fetcher(`${appUrl(env)}${path}`, { method, headers: { "content-type": "application/json", ...terminalHeaders(env) }, body: method === "GET" ? undefined : JSON.stringify(payload), signal: AbortSignal.timeout(5000) }); | |
| 77 | const parsed = await r.json().catch(() => ({})); | |
| 78 | const body = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : {}; | |
| 79 | return { status: r.status, error: r.ok ? null : plain(body.error ?? `status ${r.status}`), body }; | |
| 78 | 80 | } catch (err) { |
| 79 | return { status: 0, error: plain((err as Error).message) }; | |
| 81 | return { status: 0, error: plain((err as Error).message), body: {} }; | |
| 80 | 82 | } |
| 81 | 83 | }; |
| 82 | 84 | } |
| @@ -126,7 +128,7 @@ const said = (m: unknown): string => { | ||
| 126 | 128 | return from ? `${plain(from.name)}: ${plain(message?.text)}` : `· ${plain(message?.text)}`; |
| 127 | 129 | }; |
| 128 | 130 | |
| 129 | export const HELP = "type to chat · /join /leave /ready /extend · /stop /resume (driver, owner) · /end [who] /mute <who> /unmute <who> (owner) · /machine [off] · /who · /quit"; | |
| 131 | export const HELP = "type to chat · /join /leave /ready /extend · /stop /resume (driver, owner) · /end [who] /mute <who> /unmute <who> (owner) · /table [mm|here] (owner sets, moderator reads) · /machine [off] · /who · /quit"; | |
| 130 | 132 | |
| 131 | 133 | /** The Machine feed's socket beside the lobby's: same app, same port. */ |
| 132 | 134 | export const machineUrl = (live: string): string => live.replace(/\/live$/, "/machine"); |
| @@ -236,7 +238,7 @@ function target(room: Room, word: string): string | null { | ||
| 236 | 238 | return ID.test(word) ? word : null; |
| 237 | 239 | } |
| 238 | 240 | |
| 239 | export type Typed = { send: Frame } | { post: "/stop" | "/resume" } | { print: string } | { machine: boolean } | { quit: true } | null; | |
| 241 | export type Typed = { send: Frame } | { post: "/stop" | "/resume" } | { table: "read" | "here" | number } | { print: string } | { machine: boolean } | { quit: true } | null; | |
| 240 | 242 | |
| 241 | 243 | /** What a typed line asks for. Validation the server repeats anyway; this only saves a round trip on a typo. */ |
| 242 | 244 | export function typed(room: Room, input: string): Typed { |
| @@ -265,6 +267,12 @@ export function typed(room: Room, input: string): Typed { | ||
| 265 | 267 | case "stop": |
| 266 | 268 | case "resume": |
| 267 | 269 | return { post: `/${verb.toLowerCase()}` as "/stop" | "/resume" }; |
| 270 | case "table": { | |
| 271 | if (!arg) return { table: "read" }; | |
| 272 | if (arg.toLowerCase() === "here") return { table: "here" }; | |
| 273 | const mm = /^-?\d{1,3}$/.test(arg) ? Number(arg) : NaN; | |
| 274 | return mm >= -100 && mm <= 100 ? { table: mm } : { print: "usage: /table [mm|here], mm a whole number from -100 to 100" }; | |
| 275 | } | |
| 268 | 276 | case "machine": |
| 269 | 277 | if (arg && arg.toLowerCase() !== "off" && arg.toLowerCase() !== "on") return { print: "usage: /machine [off]" }; |
| 270 | 278 | return { machine: arg.toLowerCase() !== "off" }; |
| @@ -331,6 +339,7 @@ export class Door { | ||
| 331 | 339 | if ("quit" in t) return false; |
| 332 | 340 | if ("print" in t) this.print(t.print); |
| 333 | 341 | else if ("post" in t) void this.ask(t.post); |
| 342 | else if ("table" in t) void this.table(t.table); | |
| 334 | 343 | else if ("machine" in t) this.watchMachine(t.machine); |
| 335 | 344 | else this.send(t.send); |
| 336 | 345 | return true; |
| @@ -345,6 +354,15 @@ export class Door { | ||
| 345 | 354 | else if (path === "/resume" && this.room.held === null) this.print("the arm was not stopped"); |
| 346 | 355 | } |
| 347 | 356 | |
| 357 | /** The table plane through the app's /admin/table, which gates it as the page is; the answer is printed either way. */ | |
| 358 | private async table(what: "read" | "here" | number): Promise<void> { | |
| 359 | if (!this.post) return this.print("error: the table is not available here"); | |
| 360 | const { error, body } = what === "read" ? await this.post("/admin/table", {}, "GET") : await this.post("/admin/table", what === "here" ? { here: true } : { tableOffsetMm: what }); | |
| 361 | if (error) return this.print(`error: ${error}`); | |
| 362 | const mm = body.tableOffsetMm; | |
| 363 | this.print(typeof mm === "number" ? `table height: ${plain(mm)} mm above the model's table${what === "read" ? "" : " (set)"}` : "the arm server did not say where the table is"); | |
| 364 | } | |
| 365 | ||
| 348 | 366 | close(): void { |
| 349 | 367 | this.ws?.close(); |
| 350 | 368 | this.machineWs?.close(); |
new above
offline
.catch(() => null)turns an unreachable arm server into the same text as an arm server that did not report a height. Distinguish the two so the owner knows to act.