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

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

Page control for tableOffsetMm and a table-here button in the settings panel #181

Merged opened this

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

Merged

smith/arm:smith/178-page-control-for-tableoffsetmm-and-a-tab → main 4 commits fork 5 threads · 5 unresolved

  • Merged. smith/178-page-control-for-tableoffsetmm-and-a-tab was merged into main as 48b63e8.

Review

Sign in to review this change.
6 files changed +239 −12
Software/README.md +8 −3
@@ -449,6 +449,10 @@ watches. A line you type is said in the chat; commands start with `/`:
449449 - `/end [name]`, owner: end that turn (no name: whoever drives), or take
450450 them out of the line.
451451 - `/mute <name>`, `/unmute <name>`, owner.
452 - `/table here`, owner: the page's "Table is here", the same
453 `POST /settings/table-here`: the table plane goes under the arm's lowest
454 link now. `/table <mm>`, owner: sets `tableOffsetMm` (-100 to 100) by
455 `PUT /settings`. Both print the offset the server now holds, or its refusal.
452456 - `/machine`: the Machine panel, the same rows the page's Machine tab shows
453457 (one line per joint, then the link and the server), followed by every
454458 command in and out and every clamp, line by line as it happens. `/machine`
@@ -461,9 +465,10 @@ the same `/live` socket on `127.0.0.1:$PORT`, as the forge's identity for
461465 the person at the keyboard (`FORGE_APP_USER*`, signed with
462466 `FORGE_APP_IDENTITY_KEY`). The server applies the same rules to both, so a
463467 muted person is muted at the terminal too, only the owner may end turns or
464 mute, only the driver or an owner may stop or resume (over HTTP to the same
465 app, signed afresh for each request), and every line, join and hand-back from the terminal reaches every
466 web viewer as it happens. Text from the room is shown with control
468 mute, only an owner may set the table (`/table`), and only the driver or an
outdated

This sentence now runs on as one 150-character line and puts the clause in the middle of the existing list. Move "only an owner may set the table (/table)" to its own short line or break it across lines like the surrounding text.

469 owner may stop or resume (over HTTP to the same app, signed afresh for each
470 request). Every line, join and hand-back from the terminal reaches every web
471 viewer as it happens. Text from the room is shown with control
467472 characters removed, so a chat line cannot drive your terminal. Locally,
468473 `PORT=8102 bun run Software/so101/src/tty.ts` beside `fake-serve.ts`
469474 reaches it as the owner.
Software/so101/src/terminal.test.ts +47
@@ -105,6 +105,53 @@ describe("terminal lines", () => {
105105 });
106106 });
107107
108 describe("terminal table", () => {
109 test("/table here and /table <mm> are asked for; anything else is a usage line", () => {
110 const room = emptyRoom();
111 expect(typed(room, "/table here")).toEqual({ table: "here" });
112 expect(typed(room, "/table -12")).toEqual({ table: -12 });
113 expect(typed(room, "/table 0")).toEqual({ table: 0 });
114 for (const bad of ["/table", "/table 101", "/table -101", "/table 1.5", "/table abc", "/table 1e2"]) expect(typed(room, bad)).toEqual({ print: "usage: /table here | /table <mm, -100 to 100>" });
115 });
116
117 test("the poster sends table-here as a POST and the offset as a PUT /settings, signed; a refusal comes back as its error", async () => {
118 const calls: Array<{ url: string; method: string; body: string; signed: boolean }> = [];
119 const answer = (status: number, body: unknown) => async (url: unknown, init: RequestInit = {}) => {
120 calls.push({ url: String(url), method: String(init.method), body: String(init.body), signed: Boolean((init.headers as Record<string, string>)["x-forge-signature"]) });
121 return new Response(JSON.stringify(body), { status });
122 };
123 const env = { PORT: "9", FORGE_APP_IDENTITY_KEY: "k".repeat(32), FORGE_APP_USER_ID: "u-owner", FORGE_APP_USER: "owner", FORGE_APP_USER_ROLE: "admin" };
124 const ok = await poster(env, answer(200, { tableOffsetMm: -7 }) as never)("/settings/table-here");
125 expect(ok).toEqual({ status: 200, error: null, tableOffsetMm: -7 });
126 const put = await poster(env, answer(200, { tableOffsetMm: 20 }) as never)("/settings", { tableOffsetMm: 20 });
127 expect(put.tableOffsetMm).toBe(20);
128 expect(calls.map((c) => [c.url, c.method, c.body, c.signed])).toEqual([
129 ["http://127.0.0.1:9/settings/table-here", "POST", "{}", true],
130 ["http://127.0.0.1:9/settings", "PUT", '{"tableOffsetMm":20}', true],
131 ]);
132 const refused = await poster(env, answer(403, { error: "admins only" }) as never)("/settings/table-here");
133 expect(refused).toEqual({ status: 403, error: "admins only" });
134 });
135
136 test("the door prints the offset the server holds, or its refusal", async () => {
137 const printed: string[] = [];
138 const asked: unknown[] = [];
139 const door = new Door("ws://127.0.0.1:1/live", {}, (l) => printed.push(l), async (path, body) => {
140 asked.push([path, body]);
141 return path === "/settings" ? { status: 403, error: "admins only" } : { status: 200, error: null, tableOffsetMm: 4 };
142 });
143 door.input("/table here");
144 door.input("/table 9");
145 await Bun.sleep(50);
146 expect(printed).toEqual(["table offset is 4 mm", "error: admins only"]);
147 expect(asked).toEqual([["/settings/table-here", undefined], ["/settings", { tableOffsetMm: 9 }]]);
148 const bare = new Door("ws://127.0.0.1:1/live", {}, (l) => printed.push(l));
149 bare.input("/table here");
150 await Bun.sleep(50);
151 expect(printed[2]).toBe("error: the table is not available here");
152 });
153 });
154
108155 /** Both doors on one room: the page's WebSocket and the terminal's, gated by the same server. */
109156 describe("terminal STOP", () => {
110157 test("/stop and /resume are the app's own routes; the status says STOPPED and resumed once each, not on every push", () => {
Software/so101/src/terminal.ts +26 −8
@@ -19,6 +19,8 @@
1919 * /resume the driver or an admin: end the hold; the arm stays put until a new command
2020 * /end [who] owner: end that turn (none: whoever drives), or take them out of the line
2121 * /mute <who> /unmute <who> owner
22 * /table here admin: put the table under the arm's lowest link now (POST /settings/table-here)
23 * /table <mm> admin: set the table offset, -100..100 mm (PUT /settings tableOffsetMm)
2224 * /machine [off] the Machine panel (/machine, src/machine-feed.ts): the joints, the link and the server as they are,
2325 * then every command in and out as it happens, in the page's own words (src/ui/machine.js); off stops it
2426 * /who /help /quit
@@ -64,15 +66,17 @@ function appPort(env: Env): number {
6466 return port;
6567 }
6668
67 export type Post = (path: "/stop" | "/resume") => Promise<{ status: number; error: string | null }>;
69 export type Path = "/stop" | "/resume" | "/settings/table-here" | "/settings";
70 /** `tableOffsetMm` is the offset the server holds after a settings call, when it said. */
71 export type Post = (path: Path, body?: Record<string, unknown>) => Promise<{ status: number; error: string | null; tableOffsetMm?: number }>;
6872
69 /** POST to the app as the page does, signed afresh for each request (a signature is good for a minute). */
73 /** POST to the app as the page does (PUT for /settings), signed afresh for each request (a signature is good for a minute). */
7074 export function poster(env: Env, fetcher: typeof fetch = fetch): Post {
71 return async (path) => {
75 return async (path, payload = {}) => {
7276 try {
73 const r = await fetcher(`${appUrl(env)}${path}`, { method: "POST", headers: { "content-type": "application/json", ...terminalHeaders(env) }, body: "{}", signal: AbortSignal.timeout(5000) });
74 const body = (await r.json().catch(() => ({}))) as { error?: unknown };
75 return { status: r.status, error: r.ok ? null : plain(body.error ?? `status ${r.status}`) };
77 const r = await fetcher(`${appUrl(env)}${path}`, { method: path === "/settings" ? "PUT" : "POST", headers: { "content-type": "application/json", ...terminalHeaders(env) }, body: JSON.stringify(payload), signal: AbortSignal.timeout(5000) });
78 const body = (await r.json().catch(() => ({}))) as { error?: unknown; tableOffsetMm?: unknown };
79 return { status: r.status, error: r.ok ? null : plain(body.error ?? `status ${r.status}`), ...(typeof body.tableOffsetMm === "number" ? { tableOffsetMm: body.tableOffsetMm } : {}) };
7680 } catch (err) {
7781 return { status: 0, error: plain((err as Error).message) };
7882 }
@@ -124,7 +128,7 @@ const said = (m: unknown): string => {
124128 return from ? `${plain(from.name)}: ${plain(message?.text)}` : `· ${plain(message?.text)}`;
125129 };
126130
127 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> /table here|<mm> (owner) · /machine [off] · /who · /quit";
128132
129133 /** The Machine feed's socket beside the lobby's: same app, same port. */
130134 export const machineUrl = (live: string): string => live.replace(/\/live$/, "/machine");
@@ -234,7 +238,7 @@ function target(room: Room, word: string): string | null {
234238 return ID.test(word) ? word : null;
235239 }
236240
237 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: "here" | number } | { print: string } | { machine: boolean } | { quit: true } | null;
238242
239243 /** What a typed line asks for. Validation the server repeats anyway; this only saves a round trip on a typo. */
240244 export function typed(room: Room, input: string): Typed {
@@ -263,6 +267,11 @@ export function typed(room: Room, input: string): Typed {
263267 case "stop":
264268 case "resume":
265269 return { post: `/${verb.toLowerCase()}` as "/stop" | "/resume" };
270 case "table": {
271 if (arg.toLowerCase() === "here") return { table: "here" };
272 if (/^-?\d{1,3}$/.test(arg) && Math.abs(Number(arg)) <= 100) return { table: Number(arg) };
273 return { print: "usage: /table here | /table <mm, -100 to 100>" };
274 }
266275 case "machine":
267276 if (arg && arg.toLowerCase() !== "off" && arg.toLowerCase() !== "on") return { print: "usage: /machine [off]" };
268277 return { machine: arg.toLowerCase() !== "off" };
@@ -329,6 +338,7 @@ export class Door {
329338 if ("quit" in t) return false;
330339 if ("print" in t) this.print(t.print);
331340 else if ("post" in t) void this.ask(t.post);
341 else if ("table" in t) void this.table(t.table);
332342 else if ("machine" in t) this.watchMachine(t.machine);
333343 else this.send(t.send);
334344 return true;
@@ -343,6 +353,14 @@ export class Door {
343353 else if (path === "/resume" && this.room.held === null) this.print("the arm was not stopped");
344354 }
345355
356 /** The server decides who may; a refusal is printed, success says the offset the server now holds. */
357 private async table(what: "here" | number): Promise<void> {
358 if (!this.post) return this.print("error: the table is not available here");
359 const r = await (what === "here" ? this.post("/settings/table-here") : this.post("/settings", { tableOffsetMm: what }));
360 if (r.error) this.print(`error: ${r.error}`);
361 else this.print(r.tableOffsetMm === undefined ? "table set" : `table offset is ${r.tableOffsetMm} mm`);
362 }
363
346364 close(): void {
347365 this.ws?.close();
348366 this.machineWs?.close();
Software/so101/src/ui/table-control.js added +50
@@ -0,0 +1,50 @@
1 /**
2 * The Admin tab's table plane: the offset field and the "Table is here" button. Plain ESM, served to the page at /ui/
3 * and imported by the tests. The page hands in the elements it found and its own api, msg and reload, so what a click
4 * does is testable without a browser.
5 */
6
7 export const TABLE_RANGE_MM = /** @type {const} */ ([-100, 100]);
8 const FAILED = "could not set the table";
9
10 /**
11 * The line under the row: where the table plane is now.
12 * @param {{ tableOffsetMm?: number } | null | undefined} settings
13 */
14 export const tableNote = (settings) =>
15 `The table plane is ${settings?.tableOffsetMm ?? 0} mm from the model's floor. "Table is here" sets it from the arm's lowest point now.`;
16
17 /**
18 * Wire the field and the button. `api(path, body?, method?)` resolves to the body with `ok`; `msg(text, bad?)` shows a
19 * line; `reload()` re-reads the settings. Each click of the button rewrites the table from the arm's pose, so while one
20 * is in flight the button is disabled and a second click does nothing.
21 * @param {{ input: any, button: any, api: Function, msg: Function, reload: Function }} p
22 */
23 export function bindTableControl({ input, button, api, msg, reload }) {
24 input.onchange = async () => {
25 const mm = Number(input.value);
26 const [lo, hi] = TABLE_RANGE_MM;
27 if (input.value.trim() === "" || !Number.isInteger(mm) || mm < lo || mm > hi || input.checkValidity?.() === false) {
28 return msg(`table offset must be a whole number of mm from ${lo} to ${hi}`, true);
29 }
30 const r = await api("/settings", { tableOffsetMm: mm }, "PUT");
31 if (!r.ok) return msg(r.error ?? FAILED, true);
32 msg("settings saved");
33 await reload();
34 };
35 let busy = false;
36 button.onclick = async () => {
37 if (busy) return;
38 busy = true;
39 button.disabled = true;
40 try {
41 const r = await api("/settings/table-here", {});
42 if (!r.ok) return msg(r.error ?? FAILED, true);
43 msg("table set at the arm's lowest point");
44 await reload();
45 } finally {
46 busy = false;
47 button.disabled = false;
48 }
49 };
50 }
Software/so101/src/ui/table-control.test.ts added +95
@@ -0,0 +1,95 @@
1 import { describe, expect, test } from "bun:test";
2 import { bindTableControl, tableNote } from "./table-control.js";
3
4 const setup = (answer: (path: string, body?: unknown, method?: string) => unknown) => {
5 const calls: unknown[][] = [];
6 const shown: Array<[string, boolean]> = [];
7 let reloads = 0;
8 const input: any = { value: "5", checkValidity: () => true };
9 const button: any = { disabled: false };
10 bindTableControl({
11 input,
12 button,
13 api: async (path: string, body?: unknown, method?: string) => (calls.push([path, body, method]), answer(path, body, method)),
14 msg: (text: string, bad = false) => shown.push([text, bad]),
15 reload: async () => void reloads++,
16 });
17 return { input, button, calls, shown, reloads: () => reloads };
18 };
19
20 describe("Table is here", () => {
21 test("a click posts {} to /settings/table-here and reloads the settings", async () => {
22 const t = setup(() => ({ ok: true }));
23 await t.button.onclick();
24 expect(t.calls).toEqual([["/settings/table-here", {}, undefined]]);
25 expect(t.reloads()).toBe(1);
26 expect(t.shown).toEqual([["table set at the arm's lowest point", false]]);
27 });
28
29 test("the server's error is shown as it is, long 409 text included, and nothing reloads", async () => {
30 const long = "the table would be 140 mm from the model's, past ±100: lowest point 155 mm above the model floor (wrist); put the arm near the table first";
31 const t = setup(() => ({ ok: false, status: 409, error: long }));
32 await t.button.onclick();
33 expect(t.shown).toEqual([[long, true]]);
34 expect(t.reloads()).toBe(0);
35 expect(t.button.disabled).toBe(false);
36 });
37
38 test("an error without text still says something", async () => {
39 const t = setup(() => ({ ok: false }));
40 await t.button.onclick();
41 expect(t.shown).toEqual([["could not set the table", true]]);
42 });
43
44 test("a second click while one is in flight does nothing; the button is disabled meanwhile and free after", async () => {
45 let release: (v: unknown) => void = () => {};
46 const t = setup(() => new Promise((r) => (release = r)));
47 const first = t.button.onclick();
48 expect(t.button.disabled).toBe(true);
49 await t.button.onclick();
50 expect(t.calls.length).toBe(1);
51 release({ ok: true });
52 await first;
53 expect(t.button.disabled).toBe(false);
54 t.calls.length = 0;
55 release = () => {};
56 await Promise.race([t.button.onclick(), Bun.sleep(5)]);
57 expect(t.calls.length).toBe(1);
58 });
59 });
60
61 describe("table offset field", () => {
62 test("a whole number in range is saved with PUT /settings", async () => {
63 const t = setup(() => ({ ok: true }));
64 t.input.value = "-20";
65 await t.input.onchange();
66 expect(t.calls).toEqual([["/settings", { tableOffsetMm: -20 }, "PUT"]]);
67 expect(t.reloads()).toBe(1);
68 });
69
70 test("out of range, fractional, empty, non-numeric or invalid values are not saved", async () => {
71 const t = setup(() => ({ ok: true }));
72 for (const v of ["101", "-101", "1.5", "", "abc"]) {
73 t.input.value = v;
74 await t.input.onchange();
75 }
76 t.input.value = "5";
77 t.input.checkValidity = () => false;
78 await t.input.onchange();
79 expect(t.calls).toEqual([]);
80 expect(t.shown.length).toBe(6);
81 expect(t.shown.every(([, bad]) => bad)).toBe(true);
82 });
83
84 test("a refusal from the server is shown and nothing reloads", async () => {
85 const t = setup(() => ({ ok: false, error: "tableOffsetMm: out of range" }));
86 await t.input.onchange();
87 expect(t.shown).toEqual([["tableOffsetMm: out of range", true]]);
88 expect(t.reloads()).toBe(0);
89 });
90 });
91
92 test("the note names the offset, 0 when the server did not say", () => {
93 expect(tableNote({ tableOffsetMm: -12 })).toContain("-12 mm");
94 expect(tableNote({})).toContain("0 mm");
95 });
Software/so101/src/viewer.html +13 −1
@@ -49,6 +49,8 @@
4949 select, input[type=number], input[type=text] { background: var(--btn); color: var(--fg); border: 1px solid var(--line); border-radius: 10px; padding: 0 10px; min-height: var(--tap); font-size: 16px; }
5050 input[type=number] { width: 88px; }
5151 label.inline { display: inline-flex; gap: 8px; align-items: center; color: var(--dim); font-size: 13px; }
52 #tableNote { min-height: 3em; }
53 #msg { overflow-wrap: anywhere; }
5254 .row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
5355 [hidden] { display: none !important; }
5456 [inert] { opacity: .5; }
@@ -418,7 +420,10 @@
418420 <label class="inline">mode <select id="zone"><option value="enforce">enforce</option><option value="warn">warn</option><option value="off">off</option></select></label>
419421 <label class="inline">table margin <input type="number" id="floorMargin" min="0" max="100" step="1" inputmode="numeric"> mm</label>
420422 <label class="inline">base margin <input type="number" id="baseMargin" min="0" max="100" step="1" inputmode="numeric"> mm</label>
423 <label class="inline">table offset <input type="number" id="tableOffset" min="-100" max="100" step="1" inputmode="numeric"> mm</label>
424 <button id="tableHere" type="button">Table is here</button>
421425 </div>
outdated

This paragraph is empty at first paint and filled by JS, so the content below it moves. Reserve its height (min-height) or server-render the text.

426 <p id="tableNote"></p>
422427 <p id="zoneNote"></p>
423428 </div>
424429 <div class="card">
@@ -1489,9 +1494,17 @@
14891494 addEventListener("keydown", (e) => { if (e.key === "Escape") for (const p of document.querySelectorAll(".panel:not([hidden])")) p.hidden = true; });
14901495
14911496 // ---------------------------------------------------------------- settings: the safe zone and the trims, in the Admin tab
1497 let tableControl = null, tableBound = false;
14921498 async function loadSettings() {
14931499 settings = await api("/settings");
14941500 $("zone").value = settings.zone; $("floorMargin").value = settings.floorMarginMm; $("baseMargin").value = settings.baseMarginMm;
1501 $("tableOffset").value = settings.tableOffsetMm ?? 0;
1502 // src/ui/table-control.js, fetched the first time the Admin tab loads.
1503 try {
1504 tableControl ??= await import("/ui/__VERSION__/table-control.js");
1505 if (!tableBound) { tableBound = true; tableControl.bindTableControl({ input: $("tableOffset"), button: $("tableHere"), api, msg, reload: loadSettings }); }
1506 $("tableNote").textContent = tableControl.tableNote(settings);
1507 } catch { msg("the table control did not load", true); }
14951508 const trims = $("trims"); trims.innerHTML = "";
14961509 for (const [id, name] of Object.entries(NAMES)) {
14971510 const input = el("input", { type: "number", min: -30, max: 30, step: 0.5, value: settings.jointOffsetsDeg[name] ?? 0, id: `trim-${id}`, inputMode: "decimal" });
@@ -1526,7 +1539,6 @@
15261539 $("zone").onchange = () => saveSettings({ zone: $("zone").value });
15271540 $("floorMargin").onchange = () => saveSettings({ floorMarginMm: Number($("floorMargin").value) });
15281541 $("baseMargin").onchange = () => saveSettings({ baseMarginMm: Number($("baseMargin").value) });
1529
15301542 // ---------------------------------------------------------------- metrics
15311543 // src/ui/metrics-panel.js, fetched the first time the panel opens.
15321544 async function showMetrics() {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs