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

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

The page reconnects /live by itself within 1 s (backoff 0.25 to 2 s) behind a small 'reconnecting…' chip, never reloading #255

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/234-the-page-reconnects-live-by-itself-withi → main 2 commits fork 1 thread · 1 unresolved

  • Merged. smith/234-the-page-reconnects-live-by-itself-withi was merged into main as 48952b2.

Review

Sign in to review this change.
3 files changed +103 −7
Software/so101/src/ui/lobby-panel.js +17 −5
@@ -22,6 +22,9 @@ export function queueEntry(el, x, mine) {
2222 return el("li", { className: mine ? "me" : "" }, el("span", { className: "place", textContent: `${x.place}.` }), el("span", { textContent: mine ? `${x.name} (you)` : x.name }), el("span", { className: "wait", textContent: `≤ ${waitMinutes(x.waitMs)} min` }));
2323 }
2424
25 /** @param {number} attempt 1 for the first retry @returns {number} ms to wait: 250, 500, 1000, then 2000 at most */
26 export const backoff = (attempt) => Math.min(250 * 2 ** Math.max(0, attempt - 1), 2000);
27
2528 /**
2629 * @param {any} page what the page owns: $, el, relayed, tab(), showTab, msg, applyLock, applyStatus, noStatus, words, admin
2730 */
@@ -30,7 +33,7 @@ export function createRoom(page) {
3033 // the type check has no DOM (as ./machine-panel.js)
3134 const win = /** @type {any} */ (globalThis), doc = win.document, nav = win.navigator, location = win.location;
3235 /** @type {{ ws: WebSocket | null, hello: any, state: any, mutedList: any[], bannedList: any[], crew?: any, [k: string]: any }} */
33 const lobby = { ws: null, hello: null, state: null, offset: 0, retry: 500, mutedList: [], bannedList: [], admin: null, statusSeen: false };
36 const lobby = { ws: null, hello: null, state: null, offset: 0, retry: 0, attempt: 0, reopening: false, mutedList: [], bannedList: [], admin: null, statusSeen: false };
3437 function mayDrive() { return !relayed || (lobby.hello !== null && (!lobby.hello.signin || (lobby.hello.you !== null && lobby.state?.driver?.id === lobby.hello.you.id))); }
3538 function isOwner() { return !relayed || Boolean(lobby.hello?.you?.owner); }
3639 const say = (/** @type {Record<string, unknown>} */ m) => { if (lobby.ws?.readyState === 1) lobby.ws.send(JSON.stringify(m)); };
@@ -162,7 +165,7 @@ export function createRoom(page) {
162165 const r = await fetch("/join", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: $("joinName").value.trim() }) });
163166 const body = /** @type {any} */ (await r.json().catch(() => ({})));
164167 err.textContent = r.ok || (r.status === 409 && body.you) ? "" : body.error ?? `could not join (${r.status})`;
165 if (!err.textContent) { $("joinName").value = ""; lobby.ws?.close(); }
168 if (!err.textContent) { $("joinName").value = ""; lobby.reopening = true; lobby.ws?.close(); }

Set lobby.reopening only if lobby.ws exists; otherwise the flag lingers and swallows the next genuine outage (no chip, no backoff for one cycle).

166169 } catch { err.textContent = "could not reach the app; try again"; }
167170 button.disabled = false;
168171 };
@@ -240,8 +243,9 @@ export function createRoom(page) {
240243 function lobbyConnect() {
241244 const ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/live`);
242245 lobby.ws = ws;
243 ws.onopen = () => { lobby.retry = 500; };
244246 ws.onmessage = (e) => {
247 lobby.attempt = 0;
248 if (lobby.retry) { lobby.retry = 0; $("reconnect").classList.remove("on"); } // the first message: it is back
245249 const m = JSON.parse(e.data);
246250 if (m.type === "ping") return say({ type: "pong" });
247251 if (m.type === "status") { lobby.statusSeen = true; return m.status ? page.applyStatus(m.status) : page.noStatus(); }
@@ -262,10 +266,18 @@ export function createRoom(page) {
262266 ws.onclose = () => {
263267 if (lobby.ws !== ws) return;
264268 lobby.ws = null; lobby.hello = null; lobby.statusSeen = false; // polling takes over until it is back
265 page.applyLock();
269 if (lobby.reopening) { // closed on purpose to hear who you are now: not an outage, so no chip
270 lobby.reopening = false;
271 page.applyLock();
272 return lobbyConnect();
273 }
274 lobby.attempt++;
275 $("reconnect").classList.add("on");
276 page.noStatus(); // never the last "simulated" while waiting
277 page.applyLock(); // no hello, so no turn: the drive controls are inert and no motion is sent
266278 $("driverLine").className = "none"; $("driverLine").textContent = "Reconnecting…";
279 lobby.retry = backoff(lobby.attempt);
267280 setTimeout(lobbyConnect, lobby.retry);
268 lobby.retry = Math.min(lobby.retry * 2, 8000);
269281 };
270282 }
271283 $("say").onsubmit = (/** @type {any} */ e) => {
Software/so101/src/ui/lobby-panel.test.ts +84 −1
@@ -1,5 +1,5 @@
11 import { describe, expect, test } from "bun:test";
2 import { createRoom, minutes, ordinal, queueEntry, waitMinutes } from "./lobby-panel.js";
2 import { backoff, createRoom, minutes, ordinal, queueEntry, waitMinutes } from "./lobby-panel.js";
33
44 /** A stand-in for the page's el(): elements as plain trees, so the test needs no DOM. */
55 const el = (tag: string, props: Record<string, unknown> = {}, ...children: unknown[]) => ({ tag, ...props, children });
@@ -63,4 +63,87 @@ describe("the room over /live", () => {
6363 expect(room.lobby.hello).not.toBeNull();
6464 } finally { Object.assign(g, saved); }
6565 });
66
67 test("when /live closes: backoff 0.25 to 2 s, a chip until the first message, no motion, no reload", () => {
68 const sockets: any[] = [], delays: number[] = [], timers: (() => void)[] = [];
69 const g = globalThis as any, saved = { WebSocket: g.WebSocket, setInterval: g.setInterval, setTimeout: g.setTimeout, location: g.location };
70 g.WebSocket = class { readyState = 1; sent: string[] = []; constructor() { sockets.push(this); } send(m: string) { this.sent.push(m); } };
71 g.setInterval = () => 0;
72 g.setTimeout = (f: () => void, ms: number) => (delays.push(ms), timers.push(f), 0);
73 const reloads: number[] = [];
74 g.location = { protocol: "http:", host: "x", pathname: "/", search: "", reload: () => reloads.push(1) };
75 try {
76 const nodes = new Map<string, any>(), calls: string[] = [];
77 const chipOn = () => nodes.get("reconnect").classList.contains("on");
78 const classList = () => { const on = new Set<string>(); return { toggle() {}, add: (c: string) => on.add(c), remove: (c: string) => on.delete(c), contains: (c: string) => on.has(c) }; };
79 const page = {
80 $: (id: string) => nodes.get(id) ?? (nodes.set(id, Object.assign(node(), { classList: classList() })), nodes.get(id)),
81 el: (tag: string, props: object = {}) => Object.assign(node(), { tag }, props),
82 relayed: true, tab: () => "chat", showTab() {}, applyLock: () => calls.push("lock"), applyStatus() {}, noStatus: () => calls.push("noStatus"), words() {}, admin() {},
83 msg() {},
84 };
85 const room = createRoom(page);
86 room.lobbyConnect();
87 sockets[0].onmessage({ data: JSON.stringify({ type: "hello", signin: false, you: null }) });
88 expect(room.mayDrive()).toBe(true);
89 page.$("reconnect");
90 for (let i = 0; i < 6; i++) {
91 const ws = sockets.at(-1);
92 ws.readyState = 3;
93 ws.onclose();
94 expect(chipOn()).toBe(true);
95 expect(room.mayDrive()).toBe(false); // the controls lock
96 room.say({ type: "post", text: "x" });
97 expect(ws.sent).toEqual([]); // nothing goes while disconnected
98 timers.pop()!();
99 }
100 expect(delays).toEqual([250, 500, 1000, 2000, 2000, 2000]);
101 expect(sockets.length).toBe(7);
102 expect(chipOn()).toBe(true); // still waiting: no message yet
103 sockets.at(-1).onmessage({ data: JSON.stringify({ type: "hello", signin: false, you: null }) });
104 expect(chipOn()).toBe(false);
105 sockets.at(-1).readyState = 3; sockets.at(-1).onclose();
106 expect(delays.at(-1)).toBe(250); // a message resets the backoff
107 expect(calls).toContain("noStatus");
108 expect(reloads).toEqual([]);
109 } finally { Object.assign(g, saved); }
110 });
111 });
112
113 describe("a deliberate reopen", () => {
114 test("closing /live on purpose (join) reconnects at once with no chip and no noStatus", async () => {
115 const sockets: any[] = [], delays: number[] = [];
116 const g = globalThis as any, saved = { WebSocket: g.WebSocket, setInterval: g.setInterval, setTimeout: g.setTimeout, location: g.location };
117 g.WebSocket = class { onclose: any; readyState = 1; constructor() { sockets.push(this); } send() {} close() { this.readyState = 3; this.onclose(); } };
118 g.setInterval = () => 0;
119 g.setTimeout = (_f: () => void, ms: number) => (delays.push(ms), 0);
120 g.location = { protocol: "http:", host: "x", pathname: "/", search: "" };
121 try {
122 const nodes = new Map<string, any>(), calls: string[] = [];
123 const on = new Set<string>();
124 const n = (): any => new Proxy({ children: [], classList: { toggle() {}, add: (c: string) => on.add(c), remove: (c: string) => on.delete(c), contains: (c: string) => on.has(c) }, style: { setProperty() {} }, dataset: {} }, {
125 get: (t: any, k) => (k in t ? t[k] : (() => n())), set: (t: any, k, v) => ((t[k] = v), true),
126 });
127 const page = {
128 $: (id: string) => nodes.get(id) ?? (nodes.set(id, n()), nodes.get(id)),
129 el: (tag: string, props: object = {}) => Object.assign(n(), { tag }, props),
130 relayed: true, tab: () => "chat", showTab() {}, applyLock() {}, applyStatus() {}, noStatus: () => calls.push("noStatus"), words() {}, admin() {}, msg() {},
131 };
132 const room = createRoom(page);
133 room.lobbyConnect();
134 page.$("joinName").value = " ann ";
135 const joinForm = nodes.get("joinForm");
136 expect(typeof joinForm.onsubmit).toBe("function");
137 (globalThis as any).fetch = async () => ({ ok: true, status: 200, json: async () => ({}) });
138 await joinForm.onsubmit({ preventDefault() {} });
139 expect(sockets.length).toBe(2); // reopened at once
140 expect(delays).toEqual([]);
141 expect(on.has("on")).toBe(false);
142 expect(calls).toEqual([]);
143 } finally { Object.assign(g, saved); }
144 });
145 });
146
147 test("the retry delays", () => {
148 expect([1, 2, 3, 4, 5, 50].map(backoff)).toEqual([250, 500, 1000, 2000, 2000, 2000]);
66149 });
Software/so101/src/viewer.html +2 −1
@@ -91,6 +91,7 @@
9191 #clock { color: var(--dim); font-size: 13px; font-variant-numeric: tabular-nums; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } #clock.idle { color: var(--warn); }
9292 #capLine { color: var(--dim); font-size: 12px; } #capLine:empty { display: none; }
9393 #armLine { display: none; gap: 6px; align-items: center; color: var(--dim); font-size: 12px; white-space: nowrap; } #armText { min-width: 0; overflow: hidden; text-overflow: ellipsis; } /* shown on a phone held upright (ui/mobile.css) */
94 #reconnect { align-self: flex-start; padding: 0 8px; border-radius: 9px; font-size: 11px; line-height: 16px; background: var(--warn); color: #000; visibility: hidden; } #reconnect.on { visibility: visible; }
9495 #driverLine.paused { color: var(--warn); }
9596 #turnActions { display: flex; gap: 6px; } #turnActions:empty { display: none; }
9697 .estop { flex: none; min-width: 72px; min-height: 56px; border: 0; border-radius: 12px; background: #d1242f; color: #fff; font-weight: 800; letter-spacing: .08em; text-transform: uppercase; box-shadow: 0 0 0 3px rgba(209,36,47,.25), 0 2px 8px rgba(0,0,0,.35); }
@@ -325,7 +326,7 @@
325326
326327 <section id="strip" aria-label="Who drives" aria-live="polite">
327328 <div id="ring" hidden aria-hidden="true"><span id="ringN"></span></div>
328 <div class="who"><div id="driverLine" class="none">Connecting…</div><div id="clock" aria-live="off"></div><div id="capLine"></div><div id="armLine" aria-live="off"><span class="dot" id="armDot"></span><span id="armText"></span></div></div>
329 <div class="who"><div id="driverLine" class="none">Connecting…</div><span id="reconnect" role="status">reconnecting…</span><div id="clock" aria-live="off"></div><div id="capLine"></div><div id="armLine" aria-live="off"><span class="dot" id="armDot"></span><span id="armText"></span></div></div>
329330 <div id="turnActions"></div>
330331 <button id="sheetToggle" hidden aria-controls="sheet" aria-expanded="true">Hide</button>
331332 <button id="stop" class="estop" data-stop title="Stop (space or Esc): halt everything, hold with torque, until someone resumes" aria-label="Stop the arm">Stop</button>

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs