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

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

Refusals reach the page on /live, and the page reports its snap-backs with their cause to /precision #468

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/457-refusals-reach-the-page-on-live-and-the → main 2 commits fork 3 threads · 3 unresolved

  • Merged. smith/457-refusals-reach-the-page-on-live-and-the was merged into main as 10e3bc7.

Review

Sign in to review this change.
16 files changed +428 −10
Software/README.md +11 −1
@@ -951,7 +951,17 @@ Every change to how closely the arm follows is judged by one scorecard, measured
951951 dead-man hold or the end of a stream; the headline is snap-backs per 100 releases.
952952 - **Latency by hop**: for now the arm server's own, a Goal_Position write to the first read-back more than 3 ticks
953953 from where the joint was (`bus→move`). The headline is the sum of the measured hops' p95. The hops through the
954 browser and the relay, on aligned clocks, are #458; snap-backs the page sees and refusals shown on the page are #457.
954 browser and the relay, on aligned clocks, are #458; the page's own snap-backs and refusals are below.
955
956 **Refusals and the page's snap-backs (#457).** Every frame the relay or the arm server drops, clamps or refuses (the
957 `clamp` entries of the Machine log: joint limit, too far in one frame, zone, jam, too many frames, not passed on, the
958 speed cap) is pushed to the driver's page over `/live` as `{"type": "refused", "line", "count"}`. The page shows it as
959 one line under the controls (`blocked: joint limit: joint 3, asked 4000, sent 3500 (12 so far)`), as text, and the relay
960 counts them (`refusals_shown`). In the terminal (`$FORGE_APP_SSH`) the driver gets the same line, printed when it
961 changes. `POST /precision/snap-back` with `{"cause", "sizeDeg"}` (the driver only, through the relay; the arm server
962 takes it too) adds a snap-back the page saw to the scorecard; a cause not in the list above, or a size outside
963 0-360, is a 400. The page reports only `reconnect`, the cause only it can see: the arm server counts every other cause
964 itself, and a test fails if the page names one of those.
955965
956966 `GET /precision` answers the session being driven, the last 10 minutes, the last 48 stored sessions and the hourly
957967 roll-up (`?hours=1-720` for more), every row tagged with the deployed commit (`FORGE_APP_COMMIT` or the checkout's
Software/so101/src/lobby.ts +7
@@ -763,6 +763,13 @@ export class Lobby {
763763 for (const s of this.seats) if (s.ws.readyState === WebSocket.OPEN) s.ws.send(text);
764764 }
765765
766 /** Tell the driver's pages alone something; in a local run, where nobody takes turns, every page. */
767 tellDriver(body: unknown): void {
768 const text = JSON.stringify(body);
769 const id = this.turns.driver?.id;
770 for (const s of this.seats) if (s.ws.readyState === WebSocket.OPEN && (this.local || (id !== undefined && s.who?.id === id))) s.ws.send(text);
771 }
772
766773 /** How many pages have the room open. */
767774 get watching(): number {
768775 return this.seats.size;
Software/so101/src/page-feedback.test.ts added +104
@@ -0,0 +1,104 @@
1 /**
2 * The page's side of the precision scorecard (issue #457): what the relay and the arm refuse reaches the driver's page
3 * on /live with its reason, and the snap-backs the page sees are counted on the arm's /precision by cause.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtempSync, rmSync } from "node:fs";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import WebSocket from "ws";
10 import { FeetechBus } from "./bus.ts";
11 import { FakeBus } from "./fake-bus.ts";
12 import { Lobby } from "./lobby.ts";
13 import { CAUSES, parseSnapBack } from "./precision.ts";
14 import { clampLine, refusalBatch } from "./refusals.ts";
15 import { startRelay, type RunningRelay } from "./relay.ts";
16 import { startServer, type RunningServer } from "./server.ts";
17
18 const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
19 let dir: string;
20 let arm: RunningServer;
21 let relay: RunningRelay;
22 let guarded: RunningRelay;
23 let lobby: Lobby;
24 let guardedLobby: Lobby;
25 let direct: string;
26 let base: string;
27
28 beforeAll(async () => {
29 dir = mkdtempSync(join(tmpdir(), "so101-page-feedback-"));
30 arm = await startServer(new FeetechBus(new FakeBus([1, 2, 6])), { host: "127.0.0.1", port: 0, ids: [1, 2, 6], posesFile: join(dir, "poses.json"), watchdogMs: 60 });
31 direct = `http://127.0.0.1:${arm.port}`;
32 lobby = new Lobby({ local: true, adminFile: join(dir, "admin.json") });
33 relay = await startRelay({ port: 0, simulation: direct, lobby });
34 base = `http://127.0.0.1:${relay.port}`;
35 guardedLobby = new Lobby({ identityKey: "k", adminFile: join(dir, "guarded.json") });
36 guarded = await startRelay({ port: 0, simulation: direct, lobby: guardedLobby });
37 });
38 afterAll(async () => {
39 await Promise.race([Promise.all([relay.close(), guarded.close(), arm.close()]), sleep(500)]);
40 lobby.close();
41 guardedLobby.close();
42 rmSync(dir, { recursive: true, force: true });
43 });
44
45 const snap = (url: string, body: unknown) => fetch(`${url}/precision/snap-back`, { method: "POST", body: JSON.stringify(body) });
46 const counts = async () => ((await (await fetch(`${direct}/precision`)).json()) as { window: { snapBacks: { total: number; byCause: Record<string, number> } } }).window.snapBacks;
47
48 describe("a refusal reaches the page", () => {
49 test("a frame the relay does not pass on shows its reason on /live", async () => {
50 const live = new WebSocket(`ws://127.0.0.1:${relay.port}/live`);
51 const lines: Array<{ type: string; line?: string; count?: number }> = [];
52 live.on("message", (d) => lines.push(JSON.parse(String(d))));
53 await new Promise((r) => live.once("open", r));
54 const follow = new WebSocket(`ws://127.0.0.1:${relay.port}/follow`);
55 await new Promise((r) => follow.once("open", r));
56 follow.send(JSON.stringify({ "1": 2000 })); // no seq and no time: dropped, with its reason
57 for (let i = 0; i < 40 && !lines.some((l) => l.type === "refused"); i++) await sleep(25);
58 follow.close();
59 live.close();
60 const refused = lines.find((l) => l.type === "refused");
61 expect(refused?.line).toContain("not passed on");
62 expect(refused?.line).toContain("unstamped");
63 expect(refused?.count).toBeGreaterThanOrEqual(1);
64 });
65
66 test("a clamp entry is one short line of text, whatever it holds", () => {
67 expect(clampLine({ what: "joint limit", detail: { id: 3, asked: 4000, sent: 3500, source: "stream" } })).toBe("joint limit: joint 3, asked 4000, sent 3500");
68 expect(clampLine({ what: "zone", detail: { what: "table", link: "gripper", depthMm: 12 } })).toBe("zone: table 12 mm");
69 expect(clampLine({ what: "x".repeat(300), detail: {} }).length).toBe(140);
70 const entry = (kind: "sent" | "clamp", seq: number) => ({ seq, t: 0, kind, what: "jam", detail: {} });
71 expect(refusalBatch([entry("sent", 1)])).toBeNull();
72 expect(refusalBatch([entry("clamp", 2), entry("sent", 3), entry("clamp", 4)])).toEqual({ type: "refused", line: "jam", count: 2 });
73 });
74 });
75
76 describe("the page's snap-backs are counted by cause", () => {
77 test("each cause on the list is counted with its cause", async () => {
78 const before = await counts();
79 for (const cause of CAUSES) {
80 const answer = await snap(base, { cause, sizeDeg: 7.5 });
81 expect(answer.status).toBe(200);
82 }
83 const after = await counts();
84 expect(after.total - before.total).toBe(CAUSES.length);
85 for (const cause of CAUSES) expect(after.byCause[cause]! - (before.byCause[cause] ?? 0)).toBe(1);
86 });
87
88 test("a cause not on the list, or a size that is not a size, is refused with 400, at the relay and at the arm", async () => {
89 const before = await counts();
90 for (const url of [base, direct]) {
91 for (const body of [{ cause: "gremlins", sizeDeg: 5 }, { sizeDeg: 5 }, { cause: "STOP" }, { cause: "STOP", sizeDeg: -1 }, { cause: "STOP", sizeDeg: 9999 }, { cause: "STOP", sizeDeg: "5" }, { cause: "toString", sizeDeg: 1 }, []]) {
92 expect((await snap(url, body)).status).toBe(400);
93 }
94 }
95 expect((await counts()).total).toBe(before.total);
96 expect(parseSnapBack({ cause: "reconnect", sizeDeg: 3.14159 })).toEqual({ cause: "reconnect", sizeDeg: 3.14 });
97 });
98
99 test("only the driver reports: someone who is not signed in is turned away", async () => {
100 const before = await counts();
101 expect((await snap(`http://127.0.0.1:${guarded.port}`, { cause: "STOP", sizeDeg: 5 })).status).toBe(401);
102 expect((await counts()).total).toBe(before.total);
103 });
104 });
Software/so101/src/precision-history.ts +8 −1
@@ -7,7 +7,7 @@
77 import { Database } from "bun:sqlite";
88 import { existsSync, readFileSync } from "node:fs";
99 import { join } from "node:path";
10 import { emptyRecords, summarize, trim, Tracker, WINDOW_MS, type Card } from "./precision.ts";
10 import { emptyRecords, summarize, trim, Tracker, WINDOW_MS, type Card, type Cause } from "./precision.ts";
1111
1212 /** The deployed commit: the forge's or CI's variable when set, else the checkout's HEAD, else "unknown". Never a shell. */
1313 export function deployedCommit(env: Record<string, string | undefined> = process.env, root = join(import.meta.dir, "../../..")): string {
@@ -80,6 +80,13 @@ export class PrecisionHistory {
8080 return this.#current;
8181 }
8282
83 /** A snap-back the page saw: in the session being driven when there is one, else in the rolling window alone (a reconnect comes after the stream). */
84 pageSnapBack(cause: Cause, sizeDeg: number): void {
85 const at = this.#now();
86 if (this.#current) this.#current.pageSnapBack(cause, sizeDeg, at);
87 else this.#window.snaps.push({ at, cause, id: null, sizeDeg });
88 }
89
8390 /** The session ends: its row and its hour are written. A session that measured nothing is not kept. */
8491 end(tracker: Tracker): Card {
8592 const at = this.#now();
Software/so101/src/precision.ts +17
@@ -32,6 +32,18 @@ export const CAUSES = ["release-park", "hold-expired", "zone", "cap", "stale-dro
3232 export type Cause = (typeof CAUSES)[number];
3333 export const isCause = (value: unknown): value is Cause => typeof value === "string" && (CAUSES as readonly string[]).includes(value);
3434
35 /** The most a page may report as one snap-back: a joint's whole travel and a little over. */
36 export const MAX_SNAP_DEG = 360;
37
38 /** A snap-back as the page reports it, checked: `{cause, sizeDeg}` with a listed cause and a size from 0 to MAX_SNAP_DEG; else why not. */
39 export function parseSnapBack(body: unknown): { cause: Cause; sizeDeg: number } | { error: string } {
40 if (!body || typeof body !== "object" || Array.isArray(body)) return { error: 'send {"cause", "sizeDeg"}' };
41 const { cause, sizeDeg } = body as Record<string, unknown>;
42 if (!isCause(cause)) return { error: `cause is one of ${CAUSES.join(", ")}` };
43 if (typeof sizeDeg !== "number" || !Number.isFinite(sizeDeg) || sizeDeg < 0 || sizeDeg > MAX_SNAP_DEG) return { error: `sizeDeg is a number from 0 to ${MAX_SNAP_DEG}` };
44 return { cause, sizeDeg: Number(sizeDeg.toFixed(2)) };
45 }
46
3547 export type Kind = "error" | "arrive" | "overshoot" | "settle" | "busToMove";
outdated

Typo: Kind ="error" is missing a space. Restore the original formatting.

3648 /** Timestamped samples, by joint and kind: [at, value]. */
3749 export interface Records {
@@ -271,6 +283,11 @@ export class Tracker {
271283 for (const records of [this.records, ...this.#sinks]) records.snaps.push(entry);
272284 }
273285
286 /** A snap-back only the page saw (src/ui/snap-back.js), already checked by `parseSnapBack`. */
287 pageSnapBack(cause: Cause, sizeDeg: number, at: number): void {
288 for (const records of [this.records, ...this.#sinks]) records.snaps.push({ at, cause, id: null, sizeDeg });
289 }
290
274291 /** The driver let go: a dead-man hold, or the end of the stream. */
275292 release(at: number): void {
276293 for (const records of [this.records, ...this.#sinks]) records.releases.push(at);
Software/so101/src/refusals.ts added +32
@@ -0,0 +1,32 @@
1 /**
2 * What the driver is told when a frame is dropped, clamped or refused: one short line per batch of the machine log's
3 * `clamp` entries (the relay's own and the arm server's), pushed to the driver's page on /live and shown there as text.
4 */
5
6 import type { DetailValue, MachineEntry } from "./machine-log.ts";
7
8 const MAX_LINE = 140;
9
10 const word = (value: DetailValue | undefined): string | null => (typeof value === "string" && value ? value : typeof value === "number" ? String(value) : null);
11
12 /** One clamp entry as a short line: the rule, then what it says about it (the reason, the joint, what was asked and what went). */
13 export function clampLine({ what, detail }: Pick<MachineEntry, "what" | "detail">): string {
14 const parts: string[] = [];
15 const why = word(detail.why);
16 if (why) parts.push(why);
17 if (typeof detail.id === "number") parts.push(`joint ${detail.id}`);
18 const link = word(detail.what) ?? word(detail.link);
19 if (link) parts.push(`${link}${typeof detail.depthMm === "number" ? ` ${detail.depthMm} mm` : ""}`);
20 if (typeof detail.asked === "number" && typeof detail.sent === "number") parts.push(`asked ${detail.asked}, sent ${detail.sent}`);
21 else if (typeof detail.asked === "number") parts.push(`asked ${detail.asked}`);
22 if (typeof detail.percent === "number") parts.push(`cap ${detail.percent}%`);
23 const line = parts.length ? `${what}: ${parts.join(", ")}` : what;
24 return line.length > MAX_LINE ? `${line.slice(0, MAX_LINE - 1)}…` : line;
25 }
26
27 /** What goes to the page for a batch of log entries, or null when none of them is a clamp. */
28 export function refusalBatch(entries: readonly MachineEntry[]): { type: "refused"; line: string; count: number } | null {
29 const clamps = entries.filter((e) => e.kind === "clamp");
30 const last = clamps[clamps.length - 1];
31 return last ? { type: "refused", line: clampLine(last), count: clamps.length } : null;
32 }
Software/so101/src/relay.ts +34
@@ -37,6 +37,7 @@
3737 * sets the HttpOnly session cookie and names you: {"you": {"id", "name", "owner"}}
3838 * GET /admin, POST /admin the owner's page: pause, end a turn, take control, the settings, the log
3939 * GET /precision?hours=1-720 owner and moderators: the arm's precision scorecard (src/precision-history.ts); 404 to anyone else
40 * POST /precision/snap-back the driver's page: {cause, sizeDeg} for a snap-back only the page saw (cause from src/precision.ts), 400 for any other
4041 * GET /link {"mode": "live"|"reconnecting"|"offline"|"simulated", "host": "<host:port>"|null, "problem": "…"|null}
4142 * GET /status the arm's own /status, and which arm said it: "source": "live <host:port>", "reconnecting to the arm:
4243 * <why>" (the last known status, with "reconnecting": true and "seenAt"; 503 before
@@ -61,6 +62,8 @@ import WebSocket, { WebSocketServer } from "ws";
6162 import { LiveMetrics } from "./live-metrics.ts";
6263 import { ArmLink, type LinkTimings } from "./arm-link.ts";
6364 import { MachineFeed } from "./machine-feed.ts";
65 import { refusalBatch } from "./refusals.ts";
66 import { parseSnapBack } from "./precision.ts";
6467 import { perServo } from "./machine-log.ts";
6568 import { parseFrame } from "./safety.ts";
6669 import { acceptsGzip, GzipCache, worthCompressing } from "./compress.ts";
@@ -309,6 +312,13 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
309312 });
310313 },
311314 });
315 // Every frame dropped, clamped or refused (the relay's own and the arm server's) goes to the driver's page with its reason, and is counted.
316 machine.log.subscribe((entries) => {
317 const batch = refusalBatch(entries);
318 if (!batch) return;
319 metrics.count("refusals_shown", batch.count);
320 lobby?.tellDriver(batch);
321 });
312322 const source = () => {
313323 const m = mode();
314324 if (m === "live") return `live ${remote!.host}`;
@@ -430,6 +440,28 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
430440 return json(res, 502, { error: `the arm did not answer /precision (${reason(err)})` });
431441 }
432442 };
443 /** POST /precision/snap-back (the driver's page: {cause, sizeDeg}): checked here, then added to the arm's scorecard beside its own. */
444 const snapBack = async (req: IncomingMessage, res: ServerResponse) => {
445 let body: unknown;
446 try {
447 body = JSON.parse((await readBody(req)).toString("utf8"));
448 } catch {
449 return json(res, 400, { error: "send JSON: {\"cause\", \"sizeDeg\"}" });
450 }
451 const snap = parseSnapBack(body);
452 if ("error" in snap) return json(res, 400, { error: snap.error });
453 try {
454 const answer = await fetch(`${remote && onArm() ? remote.http : simulation}/precision/snap-back`, {
455 method: "POST",
456 body: JSON.stringify(snap),
457 cache: "no-store",
458 signal: AbortSignal.timeout(Math.min(readTimeoutMs, 1000)),
459 });
460 return json(res, answer.status, await answer.json());
461 } catch (err) {
462 return json(res, 502, { error: `the arm did not answer /precision/snap-back (${reason(err)})` });
463 }
464 };
433465 const status = async (res: ServerResponse, path: string) => {
434466 const { code, body } = await statusOf(path);
435467 return json(res, code, body);
@@ -636,6 +668,8 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
636668 }
637669 if (req.method === "GET" && url.pathname === "/status") return await status(res, path);
638670
671 if (route === "POST /precision/snap-back") return await snapBack(req, res);
672
639673 const camera = CAMERA.exec(url.pathname);
640674 if (camera) {
641675 if (!reading) return json(res, 405, { error: "cameras are read-only" });
Software/so101/src/server.ts +9 −1
@@ -34,6 +34,7 @@
3434 * GET /precision the precision scorecard (src/precision.ts): tracking error, time to arrive, snap-backs by cause,
3535 * latency by hop, for the session being driven, the last 10 minutes, and the stored sessions and hours;
3636 * ?hours=1-720 hourly rows (48 by default)
37 * POST /precision/snap-back {"cause": one of CAUSES, "sizeDeg"}: a snap-back only the page saw, counted beside the server's own (400 for any other cause)
3738 * GET /model.json the arm model: joints, the model's floor (floorZ) and the enforced table (tableZ), where the URDF is served
3839 * GET /leader-map.js the leader calibration mapping, for the browser (src/leader-map.js)
3940 * GET /model/<file> the URDF and its meshes; GET /vendor/<pkg>/<file> three.js and the URDF loader
@@ -72,7 +73,7 @@ import { ArmModel, gripperTicksToRadians, ticksToRadians, type Violation } from
7273 import { clamp, type Frame } from "./mapping.ts";
7374 import { MachineLog, perServo } from "./machine-log.ts";
7475 import { Metrics } from "./metrics.ts";
75 import { ARRIVE_TICKS, type Cause, type Tracker } from "./precision.ts";
76 import { ARRIVE_TICKS, parseSnapBack, type Cause, type Tracker } from "./precision.ts";
7677 import { PrecisionHistory } from "./precision-history.ts";
7778 import { MotionError, moveToPose, playTrajectory, recordTrajectory, STALL_SPAN_TICKS } from "./motion.ts";
7879 import { assertPoseName, parsePoseFile, serializePoseFile, type PoseFile } from "./poses.ts";
@@ -757,6 +758,13 @@ export async function startServer(bus: FeetechBus, options: ServerOptions = {}):
757758 if (!/^\d{1,3}$/.test(hours) || Number(hours) < 1 || Number(hours) > 720) throw new HttpError(400, "hours must be 1-720");
758759 return json(res, 200, precision.scorecard(Number(hours)));
759760 }
761 case "POST /precision/snap-back": {
762 // What only the page sees (a model or slider moved off the driver's target, a reconnect): counted beside the server's own.
763 const snap = parseSnapBack(await readBody(req));
764 if ("error" in snap) throw new HttpError(400, snap.error);
765 precision.pageSnapBack(snap.cause, snap.sizeDeg);
766 return json(res, 200, { counted: snap.cause });
767 }
760768 case "GET /settings":
761769 return json(res, 200, { ...settings, model: model !== null });
762770 case "PUT /settings": {
Software/so101/src/terminal.test.ts +7
@@ -62,6 +62,13 @@ describe("terminal identity", () => {
6262 });
6363
6464 describe("terminal lines", () => {
65 test("a refusal is one blocked line, as plain text, said once while it stays the same", () => {
66 const room = emptyRoom();
67 expect(hear(room, { type: "refused", line: "joint limit: joint 3\x1b[2J", count: 2 })).toEqual(["blocked: joint limit: joint 3[2J"]);
68 expect(hear(room, { type: "refused", line: "joint limit: joint 3\x1b[2J", count: 1 })).toEqual([]);
69 expect(hear(room, { type: "refused", line: "zone", count: 1 })).toEqual(["blocked: zone"]);
70 });
71
6572 test("room text never reaches the terminal as escapes or control characters", () => {
6673 const room = emptyRoom();
6774 const lines = hear(room, { type: "said", message: { id: 1, at: 0, from: { id: "u-x", name: "x\x1b[31m" }, text: "\x1b[2Jboom\r\nok\x07‮" } });
Software/so101/src/terminal.ts +10 −1
@@ -179,11 +179,13 @@ export interface Room {
179179 seen: Map<string, Someone>;
180180 /** The reports the owner or a moderator was last sent, newest first; null until the first list (the one on join). */
181181 reports: Array<Record<string, unknown>> | null;
182 /** The latest refusal line printed, so a run of the same one is said once. */
183 refused: string | null;
182184 /** The latest presence line, "12 here · 4 signed in · 8 watching"; null until a good frame. */
183185 presence: string | null;
184186 }
185187
186 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, presence: null });
188 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 });
187189
188190 const someone = (x: unknown): Someone | null => {
189191 if (typeof x !== "object" || x === null) return null;
@@ -288,6 +290,13 @@ export function hear(room: Room, frame: Frame): string[] {
288290 case "said":
289291 see(room, someone((frame.message as { from?: unknown } | null)?.from));
290292 return [said(room, frame.message)];
293 case "refused": {
294 // A frame the relay or the arm dropped, clamped or refused (the page shows it as its blocked line): said when it changes.
295 const line = `blocked: ${plain(frame.line)}`;
296 if (line === room.refused) return [];
297 room.refused = line;
298 return [line];
299 }
291300 case "status": {
292301 // Said when it changes, not on every push: a stop made here or on a page reaches every terminal once.
293302 const h = (frame.status as { held?: unknown } | null)?.held as { by?: unknown; at?: unknown } | null | undefined;
Software/so101/src/ui/intent.js +19 −3
@@ -11,6 +11,8 @@ export class Intent {
1111 this.near = options.near ?? 12;
1212 /** @type {Map<number, { ticks: number, down: boolean, since: number }>} */
1313 this.targets = new Map();
14 /** Targets that were let go unreached (they waited out `hold`, or were cleared): the page's snap-backs, until `takeLost`. @type {Array<{ id: number, ticks: number }>} */
15 this.lost = [];
1416 }
1517
1618 /** The pointer is on the joint and wants `ticks`. @param {number} id @param {number} ticks @param {number} now */
@@ -24,8 +26,20 @@ export class Intent {
2426 if (t) { t.down = false; t.since = now; }
2527 }
2628
27 /** Drop everything (stopped, turn over). */
28 clear() { this.targets.clear(); }
29 /** Drop everything (stopped, turn over); a released target the arm had not reached is lost. */
30 clear() {
31 for (const [id, t] of this.targets) if (!t.down) this.#lose(id, t.ticks);
32 this.targets.clear();
33 }
34
35 /** @param {number} id @param {number} ticks */
36 #lose(id, ticks) {
37 this.lost.push({ id, ticks });
38 if (this.lost.length > 50) this.lost.shift();
39 }
40
41 /** The targets lost since last asked, once each. */
42 takeLost() { return this.lost.splice(0); }
2943
3044 /**
3145 * The target to show for a joint, or null when the real pose is the thing to show. Expires released targets the
@@ -35,8 +49,10 @@ export class Intent {
3549 target(id, actual, now) {
3650 const t = this.targets.get(id);
3751 if (!t) return null;
38 if (!t.down && (now - t.since >= this.hold || (Number.isFinite(actual) && Math.abs(/** @type {number} */ (actual) - t.ticks) <= this.near))) {
52 const arrived = Number.isFinite(actual) && Math.abs(/** @type {number} */ (actual) - t.ticks) <= this.near;
53 if (!t.down && (now - t.since >= this.hold || arrived)) {
3954 this.targets.delete(id);
55 if (!arrived) this.#lose(id, t.ticks);
4056 return null;
4157 }
4258 return t.ticks;
Software/so101/src/ui/lobby-panel.js +2 −1
@@ -66,7 +66,7 @@ export const backoff = (attempt) => Math.min(100 * 2 ** Math.max(0, attempt - 1)
6666 const tell = (what) => /** @type {any} */ (globalThis).dispatchEvent?.(new Event(what));
6767
6868 /**
69 * @param {any} page what the page owns: said(lines) for new chat lines, $, el, relayed, tab(), showTab, msg, applyLock, applyStatus, noStatus, words, admin, note
69 * @param {any} page what the page owns: said(lines) for new chat lines, $, el, relayed, tab(), showTab, msg, applyLock, applyStatus, noStatus, words, admin, note, refused
7070 */
7171 export function createRoom(page) {
7272 const { $, el, relayed, msg } = page;
@@ -356,6 +356,7 @@ export function createRoom(page) {
356356 if (m.type === "ping") return say({ type: "pong" });
357357 if (m.type === "presence") { const t = presenceText(m); if (t !== null) { const b = $("presenceLine"); b.textContent = t; b.disabled = false; } return; }
358358 if (m.type === "who") return showWho(m);
359 if (m.type === "refused") return page.refused?.(m);
359360 if (m.type === "status") { tell("pose"); lobby.statusSeen = true; return m.status ? page.applyStatus(m.status) : page.noStatus(); }
360361 if (m.type === "hello") lobby.hello = m;
361362 else if (m.type === "state") { lobby.offset = m.now - Date.now(); lobby.state = m; }
Software/so101/src/ui/refusal.js +13
@@ -21,3 +21,16 @@ export function refusalLine(body) {
2121 const line = `blocked: ${reason}`;
2222 return line.length > MAX ? `${line.slice(0, MAX - 1)}…` : line;
2323 }
24
25 /**
26 * The line for frames the relay or the arm dropped, clamped or refused, as /live pushes them: `{ line, count }`, and how many there have been in all.
27 * @param {unknown} m @param {number} total
28 * @returns {string}
29 */
30 export function clampNote(m, total) {
31 const line = m && typeof m === "object" ? /** @type {{ line?: unknown }} */ (m).line : undefined;
32 // eslint-disable-next-line no-control-regex
33 const text = typeof line === "string" ? line.replace(/[\u0000-\u001f\u007f]+/g, " ").trim() : "";
34 const note = `blocked: ${text || "a frame was dropped"}${total > 1 ? ` (${total} so far)` : ""}`;
35 return note.length > MAX ? `${note.slice(0, MAX - 1)}…` : note;
36 }
Software/so101/src/ui/snap-back.js added +56
@@ -0,0 +1,56 @@
1 // @ts-check
2 /**
3 * The page's side of the precision scorecard: when the model or a slider moves away from the user's target without
4 * the user doing it, say why from what the page knows and report `{cause, sizeDeg}` (causes: src/precision.ts, CAUSES).
5 * Only causes the page can name are reported; the arm server counts its own.
6 */
7
8 const DEGREES_PER_TICK = 360 / 4096;
9
10 /**
11 * Why a target was lost, when only the page can say: the link to the arm was down and the page snapped back to the
12 * arm's pose. Every other cause (zone, jam, STOP, turn-end, ...) is counted by the arm server itself (src/server.ts), so
13 * the page leaves it alone: reporting it too would count one event twice.
14 * @param {{ reconnecting?: unknown }} s
15 * @returns {"reconnect" | null}
16 */
17 export function snapCause(s) {
18 return s.reconnecting ? "reconnect" : null;
19 }
outdated

The server already counts "zone" and "jam" (server.ts tracker.snapBack calls), so reporting them here counts each twice. Return only STOP, reconnect and turn-end.

20
21 /**
22 * The snap-backs for targets lost, each with its cause and size; a joint whose position is unknown or whose cause is unknown is left out.
23 * @param {Array<{ id: number, ticks: number }>} lost
24 * @param {(id: number) => number | null | undefined} actual where the arm is, in ticks
25 * @param {Parameters<typeof snapCause>[0]} state
26 */
27 export function snapBacks(lost, actual, state) {
28 /** @type {Array<{ cause: string, sizeDeg: number }>} */
29 const out = [];
30 for (const { id, ticks } of lost) {
31 const at = actual(id);
32 const cause = snapCause(state);
33 if (cause && typeof at === "number") out.push({ cause, sizeDeg: Number((Math.abs(ticks - at) * DEGREES_PER_TICK).toFixed(2)) });
34 }
35 return out;
36 }
37
38 /**
39 * Send them to the relay, which checks them and adds them to the arm's scorecard; a failure is nobody's to see.
40 * @param {Array<{ cause: string, sizeDeg: number }>} snaps @param {typeof fetch} send
41 */
42 export function reportSnapBacks(snaps, send = fetch) {
43 for (const snap of snaps) send("/precision/snap-back", { method: "POST", body: JSON.stringify(snap), cache: "no-store" }).catch(() => {});
44 }
45
46 /**
47 * The page's whole report: what the intent lost since last asked, against the arm's last status, sent to the relay.
48 * @param {{ takeLost(): Array<{ id: number, ticks: number }> } | undefined} intent
49 * @param {{ joints?: Array<{ id: number, position?: number | null }> } | null | undefined} status the arm's last status
50 * @param {boolean} reconnecting whether the link to the arm is down
51 * @param {typeof fetch} [send]
52 */
53 export function reportLost(intent, status, reconnecting, send = fetch) {
54 const lost = intent?.takeLost?.() ?? [];
55 if (lost.length) reportSnapBacks(snapBacks(lost, (id) => status?.joints?.find((j) => j.id === id)?.position, { reconnecting }), send);
56 }
Software/so101/src/ui/snap-back.test.ts added +86
@@ -0,0 +1,86 @@
1 import { describe, expect, test } from "bun:test";
2 import { Intent } from "./intent.js";
3 import { clampNote } from "./refusal.js";
4 import { readFileSync } from "node:fs";
5 import { reportLost, reportSnapBacks, snapBacks, snapCause } from "./snap-back.js";
6
7 const driving = { turn: true };
8
9 describe("the page names why a target was lost", () => {
10 test("only reconnect is the page's to say", () => {
11 expect(snapCause({ reconnecting: true })).toBe("reconnect");
12 expect(snapCause({})).toBeNull();
13 expect(snapCause({ reconnecting: false })).toBeNull();
14 });
15
16 test("the page never reports a cause the arm server counts itself", () => {
17 const server = readFileSync(new URL("../server.ts", import.meta.url), "utf8");
18 const counted = new Set([...server.matchAll(/snapBack\("([^"]+)"/g)].map((m) => m[1]!));
19 for (const m of server.matchAll(/stopCause\.set\([^)]*?"([^"]+)"(?:[^)]*?"([^"]+)")?/g)) for (const c of m.slice(1)) if (c) counted.add(c);
20 expect(counted.has("jam") && counted.has("zone") && counted.has("STOP") && counted.has("turn-end")).toBe(true); // the scan still finds them
21 for (const state of [{ reconnecting: true }, { reconnecting: false }, {}]) {
22 const cause = snapCause(state);
23 if (cause) expect(counted.has(cause)).toBe(false);
24 }
25 });
26
27 test("a lost target is a snap-back of its distance in degrees", () => {
28 expect(snapBacks([{ id: 1, ticks: 2048 }, { id: 2, ticks: 0 }], (id) => (id === 1 ? 1024 : undefined), { reconnecting: true })).toEqual([{ cause: "reconnect", sizeDeg: 90 }]);
29 });
30
31 test("the intent keeps targets the arm never reached, and not those it did", () => {
32 const intent = new Intent({ hold: 100 });
33 intent.set(1, 2000, 0);
34 intent.release(1, 0);
35 intent.set(2, 3000, 0);
36 intent.release(2, 0);
37 expect(intent.target(2, 3005, 10)).toBeNull(); // arrived
38 expect(intent.target(1, 1500, 200)).toBeNull(); // waited out
39 expect(intent.takeLost()).toEqual([{ id: 1, ticks: 2000 }]);
40 expect(intent.takeLost()).toEqual([]);
41 intent.set(3, 100, 0);
42 intent.release(3, 0);
43 intent.clear(); // the turn ended
44 expect(intent.takeLost()).toEqual([{ id: 3, ticks: 100 }]);
45 });
46
47 test("with nothing to name, nothing is reported", () => {
48 expect(snapBacks([{ id: 1, ticks: 2048 }], () => 1024, {})).toEqual([]);
49 });
50
51 test("reportLost drains the intent against the arm's status and posts only what the page can name", () => {
52 const intent = new Intent({ hold: 100 });
53 for (const id of [1, 2]) (intent.set(id, 2048, 0), intent.release(id, 0));
54 intent.target(1, 0, 500);
55 intent.target(2, 0, 500);
56 const status = { joints: [{ id: 1, position: 1024 }, { id: 2, position: 2048 - 512 }] };
57 const sent: string[] = [];
58 const send = ((_: string, init: { body: string }) => (sent.push(init.body), Promise.resolve(new Response("{}")))) as never;
59 reportLost(intent, status, false, send);
60 expect(sent).toEqual([]); // not reconnecting: the arm server counts it
61 for (const id of [1, 2]) (intent.set(id, 2048, 0), intent.release(id, 0));
62 intent.target(1, 0, 500);
63 intent.target(2, 0, 500);
64 reportLost(intent, status, true, send);
65 expect(sent).toEqual(['{"cause":"reconnect","sizeDeg":90}', '{"cause":"reconnect","sizeDeg":45}']);
66 reportLost(intent, status, true, send);
67 expect(sent.length).toBe(2); // each once
68 });
69
70 test("they are posted to the relay, one each; a failed post is nobody's to see", async () => {
71 const sent: Array<[string, string]> = [];
72 reportSnapBacks([{ cause: "STOP", sizeDeg: 4 }, { cause: "zone", sizeDeg: 9 }], ((url: string, init: { body: string }) => (sent.push([url, init.body]), Promise.reject(new Error("down")))) as never);
73 await Promise.resolve();
74 expect(sent).toEqual([["/precision/snap-back", '{"cause":"STOP","sizeDeg":4}'], ["/precision/snap-back", '{"cause":"zone","sizeDeg":9}']]);
75 });
76 });
77
78 describe("the refusal line on the page", () => {
79 test("is text, counted, and bounded", () => {
80 expect(clampNote({ line: "joint limit: joint 3" }, 1)).toBe("blocked: joint limit: joint 3");
81 expect(clampNote({ line: "jam" }, 12)).toBe("blocked: jam (12 so far)");
82 expect(clampNote({ line: "<b>x</b>\n" }, 1)).toBe("blocked: <b>x</b>");
83 expect(clampNote(null, 1)).toBe("blocked: a frame was dropped");
84 expect(clampNote({ line: "y".repeat(500) }, 1).length).toBe(160);
85 });
86 });
Software/so101/src/viewer.html +13 −2
@@ -507,6 +507,9 @@
507507 // Why a move was refused, until the next accepted one.
508508 const refused = async (body) => { $("refusal").textContent = (await import("/ui/__VERSION__/refusal.js")).refusalLine(body); };
509509 const accepted = () => { $("refusal").textContent = ""; };
510 // A frame the relay or the arm dropped, clamped or refused, as /live pushes it to the driver: one line, counted.
511 let refusedTotal = 0;

Make #refusal an aria-live=polite region (if it is not already) so the blocked line is announced, and confirm it wraps on a 360px phone.

512 const streamRefused = async (m) => { refusedTotal += m.count; $("refusal").textContent = (await import("/ui/__VERSION__/refusal.js")).clampNote(m, refusedTotal); };
510513 const api = async (path, body, method = body === undefined ? "GET" : "POST") => {
511514 const r = await fetch(path, { method, body: body === undefined ? undefined : JSON.stringify(body), cache: "no-store" });
512515 const data = await r.json().catch(() => ({}));
@@ -1343,6 +1346,7 @@
13431346 },
13441347 words(m) { const f = $("wordsForm"); if (document.activeElement !== f.elements.words) f.elements.words.value = m.words.join(", "); if (wordsSent) { wordsSent = false; msg(`Word filter saved: ${m.words.length} word${m.words.length === 1 ? "" : "s"}.`); } },
13451348 admin: (saved) => fillAdmin(saved),
1349 refused: (m) => streamRefused(m),
13461350 });
13471351 const { lobby, mayDrive, isOwner, say, serverNow, lobbyConnect, chatBox, renderTurn, button } = room;
13481352 if (relayed) import("/ui/__VERSION__/health-meter.js").then((m) => m.start(say, stream.frames));
@@ -1353,9 +1357,16 @@
13531357 $("why").textContent = w ?? "";
13541358 return w;
13551359 }
1360 /** Targets the arm was kept from: reported with their cause to the scorecard (src/ui/snap-back.js). */
1361 function reportLost() {
1362 if (!relayed) return;
1363 const d = status, reconnecting = Boolean(d?.reconnecting || linkNow === "reconnecting");
1364 if (!intent.takeLost || !intent.lost?.length) return;
1365 import("/ui/__VERSION__/snap-back.js").then((m) => m.reportLost(intent, d, reconnecting), () => {});
1366 }
13561367 function applyLock() {
13571368 const why = explainLock();
1358 if (why) intent.clear();
1369 if (why) { intent.clear(); reportLost(); }
13591370 const can = mayDrive() && !why, owner = isOwner();
13601371 $("t-controls").hidden = !mayDrive();
13611372 shell.classList.toggle("mayDrive", mayDrive());
@@ -1517,7 +1528,7 @@
15171528 $("record").textContent = d.driving === "record" ? "■ Stop recording" : "● Record";
15181529 for (const id of ["hold", "releaseBtn", "play"]) $(id).disabled = d.driving !== null;
15191530 if (tab === "controls") render(d);
1520 banner(d); applyModel(d);
1531 banner(d); applyModel(d); reportLost();
15211532 $("readout").innerHTML = `<span>lowest part <b>${Number.isFinite(d.lowestMm) ? d.lowestMm : "—"} mm</b> above the table</span><span>zone <b>${d.zone === "enforce" || d.zone === "warn" || d.zone === "off" ? d.zone : "—"}</b></span>`;
15221533 }
15231534 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs