Public: anyone can read this; the crew can change it.
Migrated from github.com/Trevato/SO-ARM100
workbenchthis machine
Who is here: a live count of users and anonymous watchers, with a tasteful generated name for each anonymous viewer #185
smith/arm:smith/148-who-is-here-a-live-count-of-users-and-an → main 6 commits fork 4 threads · 4 unresolved
10 files
changed +306
−8
Software/so101/src/lobby.test.ts +43 −1
| @@ -573,7 +573,7 @@ describe("lobby", () => { | ||
| 573 | 573 | const ended = await form(port, { action: "end" }, OWNER); |
| 574 | 574 | expect(ended.status).toBe(303); |
| 575 | 575 | expect(ended.headers.get("location")).toBe("/admin?done=ended"); |
| 576 | await alice.next(drivingIs("bob")); | |
| 576 | await alice.first(drivingIs("bob")); | |
| 577 | 577 | |
| 578 | 578 | const saved = await form(port, { action: "save", turnSeconds: "90", idleSeconds: "20", maxSpeedPercent: "40", maxQueue: "3", announcement: '<script>alert("x")</script>' }, OWNER); |
| 579 | 579 | expect(saved.status).toBe(303); |
| @@ -662,6 +662,48 @@ describe("lobby", () => { | ||
| 662 | 662 | } |
| 663 | 663 | }); |
| 664 | 664 | |
| 665 | test("presence: two anonymous sockets get different curated names, counts follow connect and disconnect", async () => { | |
| 666 | const port = await start(); | |
| 667 | const browser = (n: number) => ({ cookie: `arm_here=browser-number-${n}-padding` }); | |
| 668 | const a = await join(port, browser(1)); | |
| 669 | const b = await join(port, browser(2)); | |
| 670 | const seen = await b.first((m) => m.type === "presence" && m.anon === 2); | |
| 671 | expect(seen).toMatchObject({ here: 2, signedIn: 0, anon: 2 }); | |
| 672 | const [one, two] = seen.people.map((p: Msg) => p.name as string); | |
| 673 | expect(one).not.toBe(two); | |
| 674 | for (const name of [one, two]) expect(name).toMatch(/^[A-Z][a-z]+ [A-Z][a-z]+$/); | |
| 675 | expect(seen.people.every((p: Msg) => /^#[0-9a-f]{6}$/.test(p.color) && p.role === "watching")).toBe(true); | |
| 676 | expect(JSON.stringify(seen)).not.toContain("127.0.0.1"); | |
| 677 | const alice = await join(port, ALICE); | |
| 678 | expect(await alice.first((m) => m.type === "presence" && m.here === 3)).toMatchObject({ signedIn: 1, anon: 2 }); | |
| 679 | alice.send({ type: "join" }); | |
| 680 | const driving = await b.next((m) => m.type === "presence" && m.people[0]?.role === "driving"); | |
| 681 | expect(driving.people[0]).toMatchObject({ name: "alice", anon: false, color: null }); | |
| 682 | a.ws.close(); | |
| 683 | expect(await b.next((m) => m.type === "presence" && m.anon === 1)).toMatchObject({ here: 2 }); | |
| 684 | }); | |
| 685 | ||
| 686 | test("presence: the same browser keeps its name across reconnects", async () => { | |
| 687 | const port = await start(); | |
| 688 | const first = await join(port, { cookie: "arm_here=browser-number-1-padding" }); | |
| 689 | const other = await join(port, { cookie: "arm_here=browser-number-2-padding" }); | |
| 690 | await other.first((m) => m.type === "presence" && m.anon === 2); | |
| 691 | const cookie = (await fetch(`http://127.0.0.1:${port}/`)).headers.get("set-cookie")?.split(";")[0] ?? ""; | |
| 692 | expect(cookie).toMatch(/^arm_here=/); | |
| 693 | const name = async () => { | |
| 694 | const c = await join(port, { cookie }); | |
| 695 | const m = await c.first((x) => x.type === "presence" && x.people.length > 0); | |
| 696 | return m; | |
| 697 | }; | |
| 698 | const a = await name(); | |
| 699 | const mine = (m: Msg) => m.people.map((p: Msg) => p.name).sort().join(); | |
| 700 | const before = mine(a); | |
| 701 | const b = await name(); | |
| 702 | expect(b.here).toBe(a.here); // the same cookie is the same person: not counted twice | |
| 703 | expect(mine(b)).toBe(before); | |
| 704 | expect(first.ws.readyState).toBe(WebSocket.OPEN); | |
| 705 | }); | |
| 706 | ||
| 665 | 707 | describe("/live frame size", () => { |
| 666 | 708 | /** A JSON object of exactly `bytes` bytes, its padding made of `ch` (of `width` bytes each). */ |
| 667 | 709 | const padded = (bytes: number, ch = "a", width = 1) => { |
Software/so101/src/lobby.ts +22 −3
| @@ -26,11 +26,13 @@ | ||
| 26 | 26 | * chat (the last CHAT_FIRST lines of the log, and whether there are more), history (an older page, the same way), |
| 27 | 27 | * said, unsaid, muted, admin (owners only: the settings and the admin log), crew (owners only: |
| 28 | 28 | * settings, hidden lines, mute suggestions), banned and words (owners only), ping, error; and whatever the relay |
| 29 | * `presence` (everyone: the counts and who is here, src/presence.ts), and whatever the relay | |
| 29 | 30 | * `publish`es to everyone: the arm's status, so a page needs this one socket for the pose, the chat and the queue. |
| 30 | 31 | */ |
| 31 | 32 | |
| 32 | 33 | import type { IncomingMessage } from "node:http"; |
| 33 | 34 | import type { Duplex } from "node:stream"; |
| 35 | import { createHash } from "node:crypto"; | |
| 34 | 36 | import WebSocket, { WebSocketServer } from "ws"; |
| 35 | 37 | import { Accounts, visitor, type Visitor } from "./accounts.ts"; |
| 36 | 38 | import { Admin, AdminError } from "./admin.ts"; |
| @@ -39,6 +41,7 @@ import { Chat, ChatError } from "./chat.ts"; | ||
| 39 | 41 | import { Moderator } from "./moderator.ts"; |
| 40 | 42 | import { WordFilter } from "./word-filter.ts"; |
| 41 | 43 | import { identify, LOCAL, type Person, type Who } from "./identity.ts"; |
| 44 | import { hereToken, Presence } from "./presence.ts"; | |
| 42 | 45 | import { Turns, type TurnEvent } from "./turns.ts"; |
| 43 | 46 | |
| 44 | 47 | export interface LobbyOptions { |
| @@ -70,6 +73,8 @@ interface Seat { | ||
| 70 | 73 | who: Who; |
| 71 | 74 | from: Visitor; |
| 72 | 75 | heard: number; |
| 76 | /** Who the room counts this socket as: the account id, or the anonymous cookie. */ | |
| 77 | key: string; | |
| 73 | 78 | } |
| 74 | 79 | |
| 75 | 80 | const MAX_FRAME = 4096; |
| @@ -86,6 +91,7 @@ export class Lobby { | ||
| 86 | 91 | readonly admin: Admin; |
| 87 | 92 | readonly filter: WordFilter; |
| 88 | 93 | readonly local: boolean; |
| 94 | readonly presence = new Presence(); | |
| 89 | 95 | readonly moderator: Moderator | undefined; |
| 90 | 96 | private readonly key: string; |
| 91 | 97 | private readonly wss = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME }); |
| @@ -232,7 +238,9 @@ export class Lobby { | ||
| 232 | 238 | upgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void { |
| 233 | 239 | const who = this.who(req); |
| 234 | 240 | const from = visitor(req); |
| 235 | this.wss.handleUpgrade(req, socket, head, (ws) => this.seat(ws, who, from)); | |
| 241 | // The page sets the cookie; a socket without one counts as its address and browser together, hashed and never shown. | |
| 242 | const token = hereToken(req) ?? createHash("sha256").update(`${from.ip}|${from.ua}`).digest("base64url"); | |
| 243 | this.wss.handleUpgrade(req, socket, head, (ws) => this.seat(ws, who, from, token)); | |
| 236 | 244 | } |
| 237 | 245 | |
| 238 | 246 | close(): void { |
| @@ -244,9 +252,10 @@ export class Lobby { | ||
| 244 | 252 | } |
| 245 | 253 | |
| 246 | 254 | // ------------------------------------------------------------------ sockets |
| 247 | private seat(ws: WebSocket, who: Who, from: Visitor): void { | |
| 248 | const seat: Seat = { ws, who, from, heard: Date.now() }; | |
| 255 | private seat(ws: WebSocket, who: Who, from: Visitor, token: string): void { | |
| 256 | const seat: Seat = { ws, who, from, heard: Date.now(), key: who ? `u:${who.id}` : `a:${token}` }; | |
| 249 | 257 | this.seats.add(seat); |
| 258 | this.presence.enter(seat.key, who); | |
| 250 | 259 | if (who) this.turns.connect(who.id); |
| 251 | 260 | this.send(seat, this.hello(seat)); |
| 252 | 261 | this.send(seat, this.state()); |
| @@ -258,6 +267,7 @@ export class Lobby { | ||
| 258 | 267 | this.send(seat, this.adminState()); |
| 259 | 268 | this.send(seat, this.crewState()); |
| 260 | 269 | } |
| 270 | this.broadcastPresence(); | |
| 261 | 271 | for (const listener of this.arriveListeners) listener((text) => seat.ws.readyState === WebSocket.OPEN && seat.ws.send(text)); |
| 262 | 272 | ws.on("message", (data, binary) => { |
| 263 | 273 | seat.heard = Date.now(); |
| @@ -279,6 +289,8 @@ export class Lobby { | ||
| 279 | 289 | }); |
| 280 | 290 | ws.on("close", () => { |
| 281 | 291 | this.seats.delete(seat); |
| 292 | this.presence.leave(seat.key); | |
| 293 | this.broadcastPresence(); | |
| 282 | 294 | if (who) this.turns.disconnect(who.id); |
| 283 | 295 | }); |
| 284 | 296 | ws.on("error", () => ws.terminate()); |
| @@ -406,6 +418,13 @@ export class Lobby { | ||
| 406 | 418 | if (parts.length) this.broadcast({ type: "said", message: this.chat.system(parts.join("; ")) }); |
| 407 | 419 | } |
| 408 | 420 | this.broadcastState(); |
| 421 | this.broadcastPresence(); | |
| 422 | } | |
| 423 | ||
| 424 | /** The count and the list, to every page. */ | |
| 425 | private broadcastPresence(): void { | |
| 426 | const { driver, queue } = this.turns; | |
| 427 | this.broadcast({ type: "presence", ...this.presence.counts(), people: this.presence.list(driver?.id ?? null, queue.map((p) => p.id)) }); | |
| 409 | 428 | } |
| 410 | 429 | |
| 411 | 430 | private state() { |
Software/so101/src/presence.test.ts added +37
| @@ -0,0 +1,37 @@ | ||
| 1 | import { describe, expect, test } from "bun:test"; | |
| 2 | import { COLORS, NOUNS, Presence } from "./presence.ts"; | |
| 3 | ||
| 4 | const curated = (name: string) => { | |
| 5 | const [color, noun, ...rest] = name.split(" "); | |
| 6 | return rest.length === 0 && color! in COLORS && NOUNS.includes(noun!); | |
| 7 | }; | |
| 8 | ||
| 9 | describe("presence", () => { | |
| 10 | test("anonymous names come only from the lists, are stable, and are never shared at once", () => { | |
| 11 | const p = new Presence(); | |
| 12 | for (let i = 0; i < 300; i++) p.enter(`token-number-${i}-padding`, null); | |
| 13 | const names = p.list(null, []).map((h) => h.name); | |
| 14 | expect(new Set(names).size).toBe(300); | |
| 15 | expect(names.every(curated)).toBe(true); | |
| 16 | const again = (token: string) => { | |
| 17 | const q = new Presence(); | |
| 18 | q.enter(token, null); | |
| 19 | return q.list(null, [])[0]!.name; | |
| 20 | }; | |
| 21 | expect(again("token-number-7-padding")).toBe(again("token-number-7-padding")); | |
| 22 | }); | |
| 23 | ||
| 24 | test("two tabs are one person; counts follow enter and leave; roles and order", () => { | |
| 25 | const p = new Presence(); | |
| 26 | p.enter("a:one-token-xxxxxxxx", null); | |
| 27 | p.enter("a:one-token-xxxxxxxx", null); | |
| 28 | p.enter("u:1", { id: "1", name: "alice" }); | |
| 29 | p.enter("u:2", { id: "2", name: "bob" }); | |
| 30 | expect(p.counts()).toEqual({ here: 3, signedIn: 2, anon: 1 }); | |
| 31 | expect(p.list("2", ["1"]).map((h) => [h.name, h.role]).slice(0, 2)).toEqual([["bob", "driving"], ["alice", "queued"]]); | |
| 32 | p.leave("a:one-token-xxxxxxxx"); | |
| 33 | expect(p.counts().anon).toBe(1); | |
| 34 | p.leave("a:one-token-xxxxxxxx"); | |
| 35 | expect(p.counts()).toEqual({ here: 2, signedIn: 2, anon: 0 }); | |
| 36 | }); | |
| 37 | }); |
Software/so101/src/presence.ts added +107
| @@ -0,0 +1,107 @@ | ||
| 1 | /** | |
| 2 | * Who is here. Everyone with the room open is counted once however many tabs they hold: signed-in people by their | |
| 3 | * account, anonymous viewers by a random cookie (`arm_here`, set when the page loads). Each anonymous viewer is | |
| 4 | * given a colour and a nature noun from the curated lists below ("Teal Heron"), picked from a hash of the cookie so it | |
| 5 | * stays the same for that browser, and moved along to the next free pair when someone present already has it: two | |
| 6 | * people never share a name at once. Names come from the lists only. Nothing here keeps or shows an address. | |
| 7 | * */ | |
| 8 | ||
| 9 | import { createHash, randomBytes } from "node:crypto"; | |
| 10 | import type { IncomingMessage } from "node:http"; | |
| 11 | ||
| 12 | export const HERE_COOKIE = "arm_here"; | |
| 13 | const TOKEN = /^[A-Za-z0-9_-]{16,64}$/; | |
| 14 | ||
| 15 | /** Colour name → its dot. Muted, readable on a dark page. */ | |
| 16 | export const COLORS: Readonly<Record<string, string>> = { | |
| 17 | Amber: "#e0a030", Azure: "#4a90d9", Coral: "#e8735a", Crimson: "#c0445a", Ivory: "#d8d2bc", Jade: "#3fae8a", | |
| 18 | Lilac: "#a98bd4", Moss: "#7a9a4a", Olive: "#9a9a3e", Plum: "#8e4f8a", Rust: "#b5572f", Sage: "#8fae8a", | |
| 19 | Sand: "#cdb88a", Slate: "#6f7f92", Teal: "#2a9d9d", Violet: "#7a62d0", | |
| 20 | }; | |
| 21 | export const NOUNS: readonly string[] = [ | |
| 22 | "Badger", "Crane", "Dragonfly", "Falcon", "Finch", "Fox", "Gecko", "Heron", "Ibis", "Kestrel", "Lynx", "Marten", | |
| 23 | "Moth", "Newt", "Otter", "Owl", "Pika", "Plover", "Robin", "Sparrow", "Swift", "Tern", "Wren", "Wolf", | |
| 24 | ]; | |
| 25 | const COLOR_NAMES = Object.keys(COLORS); | |
| 26 | ||
| 27 | export type Role = "driving" | "queued" | "watching"; | |
| 28 | export interface Here { | |
| 29 | name: string; | |
| 30 | /** Hex dot for an anonymous viewer, null for a signed-in person. */ | |
| 31 | color: string | null; | |
| 32 | anon: boolean; | |
| 33 | role: Role; | |
| 34 | } | |
| 35 | export interface Counts { | |
| 36 | here: number; | |
| 37 | signedIn: number; | |
| 38 | anon: number; | |
| 39 | } | |
| 40 | ||
| 41 | interface Entry { | |
| 42 | name: string; | |
| 43 | color: string | null; | |
| 44 | anon: boolean; | |
| 45 | /** Signed-in id, used to look up the turn; never sent out. */ | |
| 46 | id: string | null; | |
| 47 | sockets: number; | |
| 48 | } | |
| 49 | ||
| 50 | /** The anonymous token in the handshake's cookies, if it is shaped like one. */ | |
| 51 | export function hereToken(req: IncomingMessage): string | null { | |
| 52 | for (const part of (req.headers.cookie ?? "").split(";")) { | |
| 53 | const [k, v] = part.trim().split("=", 2); | |
| 54 | if (k === HERE_COOKIE && v && TOKEN.test(v)) return v; | |
| 55 | } | |
| 56 | return null; | |
| 57 | } | |
| 58 | export const newHereToken = (): string => randomBytes(18).toString("base64url"); | |
| 59 | export const hereCookie = (token: string): string => `${HERE_COOKIE}=${token}; Path=/; Max-Age=${365 * 24 * 3600}; HttpOnly; Secure; SameSite=Lax`; | |
| 60 | ||
| 61 | const pick = (token: string, taken: ReadonlySet<string>): { name: string; color: string } => { | |
| 62 | const total = COLOR_NAMES.length * NOUNS.length; | |
| 63 | const start = createHash("sha256").update(token).digest().readUInt32BE(0) % total; | |
| 64 | for (let i = 0; i < total; i++) { | |
| 65 | const n = (start + i) % total; | |
| 66 | const color = COLOR_NAMES[n % COLOR_NAMES.length]!; | |
| 67 | const name = `${color} ${NOUNS[Math.floor(n / COLOR_NAMES.length)]}`; | |
| 68 | if (!taken.has(name)) return { name, color: COLORS[color]! }; | |
| 69 | } | |
| 70 | return { name: "Grey Visitor", color: "#888888" }; // every pair taken: more than 380 people at once | |
| 71 | }; | |
| 72 | ||
| 73 | export class Presence { | |
| 74 | private readonly entries = new Map<string, Entry>(); | |
| 75 | ||
| 76 | /** A socket opened. `key` is the account id or the anonymous token; `name` is the account's name, none for an anonymous viewer. */ | |
| 77 | enter(key: string, who: { id: string; name: string } | null): void { | |
| 78 | const have = this.entries.get(key); | |
| 79 | if (have) return void have.sockets++; | |
| 80 | const taken = new Set([...this.entries.values()].map((e) => e.name)); | |
| 81 | const entry: Entry = who | |
| 82 | ? { name: who.name, color: null, anon: false, id: who.id, sockets: 1 } | |
| 83 | : { ...pick(key, taken), anon: true, id: null, sockets: 1 }; | |
| 84 | this.entries.set(key, entry); | |
| 85 | } | |
| 86 | ||
| 87 | /** A socket closed. */ | |
| 88 | leave(key: string): void { | |
| 89 | const e = this.entries.get(key); | |
| 90 | if (e && --e.sockets <= 0) this.entries.delete(key); | |
| 91 | } | |
| 92 | ||
| 93 | /** Everyone here, the driver first, then the queue in order, then the rest by name. */ | |
| 94 | list(driver: string | null, queue: readonly string[]): Here[] { | |
| 95 | const rank = (e: Entry) => (e.id !== null && e.id === driver ? -1 : e.id !== null && queue.includes(e.id) ? queue.indexOf(e.id) : Infinity); | |
| 96 | return [...this.entries.values()] | |
| 97 | .map((e): Here & { r: number } => ({ name: e.name, color: e.color, anon: e.anon, role: e.id !== null && e.id === driver ? "driving" : e.id !== null && queue.includes(e.id) ? "queued" : "watching", r: rank(e) })) | |
| 98 | .sort((a, b) => (a.r === b.r ? a.name.localeCompare(b.name) : a.r < b.r ? -1 : 1)) | |
| 99 | .map(({ r: _r, ...h }) => h); | |
| 100 | } | |
| 101 | ||
| 102 | counts(): Counts { | |
| 103 | let anon = 0; | |
| 104 | for (const e of this.entries.values()) if (e.anon) anon++; | |
| 105 | return { here: this.entries.size, signedIn: this.entries.size - anon, anon }; | |
| 106 | } | |
| 107 | } |
Software/so101/src/relay.ts +2
| @@ -68,6 +68,7 @@ import { handleAdmin } from "./admin-routes.ts"; | ||
| 68 | 68 | import { parseFps, type FeedOptions } from "./camera-feed.ts"; |
| 69 | 69 | import { CameraError, CameraHub } from "./cameras.ts"; |
| 70 | 70 | import { LOCAL as LOCAL_PERSON } from "./identity.ts"; |
| 71 | import { hereCookie, hereToken, newHereToken } from "./presence.ts"; | |
| 71 | 72 | import { LeaderCalibrations } from "./leader-calibrations.ts"; |
| 72 | 73 | import { proxyFor, whyNot } from "./egress.ts"; |
| 73 | 74 | import { CalibrationError } from "./leader-map.js"; |
| @@ -439,6 +440,7 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 439 | 440 | const boot = JSON.stringify({ link: link(), cameras: cameras.list().map(({ id, name, online }) => ({ id, name, online })) }).replace(/</g, "\\u003c"); |
| 440 | 441 | const body = Buffer.from(response.status === 200 ? html.replace("</head>", `<script type="application/json" id="boot">${boot}</script>\n</head>`) : html); |
| 441 | 442 | const headers: Record<string, string> = { "content-type": response.headers.get("content-type") ?? "text/html; charset=utf-8", "cache-control": "no-store", vary: "accept-encoding" }; |
| 443 | if (!hereToken(req)) headers["set-cookie"] = hereCookie(newHereToken()); // how the room tells one anonymous browser from another (src/presence.ts) | |
| 442 | 444 | if (!acceptsGzip(req.headers)) { |
| 443 | 445 | res.writeHead(response.status, headers); |
| 444 | 446 | return res.end(body); |
Software/so101/src/terminal.test.ts +7
| @@ -70,6 +70,13 @@ describe("terminal lines", () => { | ||
| 70 | 70 | expect(plain("a\tb")).toBe("a b"); |
| 71 | 71 | }); |
| 72 | 72 | |
| 73 | test("/here prints the page's count and list, names as plain text", () => { | |
| 74 | const room = emptyRoom(); | |
| 75 | expect(typed(room, "/here")).toEqual({ print: "no word yet on who is here" }); | |
| 76 | hear(room, { type: "presence", here: 3, signedIn: 1, anon: 2, people: [{ name: "alice", role: "driving" }, { name: "Teal Heron", role: "watching" }, { name: "Amber\x1b[31mFox", role: "queued" }] }); | |
| 77 | expect(typed(room, "/here")).toEqual({ print: "3 here · 1 signed in · 2 watching: alice (driving), Teal Heron, Amber[31mFox (in the queue)" }); | |
| 78 | }); | |
| 79 | ||
| 73 | 80 | test("typed lines become lobby frames; names the door has seen become ids", () => { |
| 74 | 81 | const room = emptyRoom(); |
| 75 | 82 | hear(room, { type: "state", driver: { id: "u-alice", name: "alice" }, queue: [{ id: "u-bob", name: "bob" }], paused: false }); |
Software/so101/src/terminal.ts +22 −3
| @@ -23,7 +23,8 @@ | ||
| 23 | 23 | * /mute <who> /unmute <who> owner |
| 24 | 24 | * /machine [off] the Machine panel (/machine, src/machine-feed.ts): the joints, the link and the server as they are, |
| 25 | 25 | * then every command in and out as it happens, in the page's own words (src/ui/machine.js); off stops it |
| 26 | * /who /help /quit | |
| 26 | * /who /here the line; everyone here, by name, with what each is doing (the page's count and list) | |
| 27 | * /help /quit | |
| 27 | 28 | * <who> is a name the door has seen (driving, in line, in the chat) or a user id. |
| 28 | 29 | */ |
| 29 | 30 | |
| @@ -98,6 +99,8 @@ export interface Room { | ||
| 98 | 99 | driver: Someone | null; |
| 99 | 100 | queue: Someone[]; |
| 100 | 101 | paused: boolean; |
| 102 | /** Who is here: the last "presence" frame, null until one comes. */ | |
| 103 | here: { here: number; signedIn: number; anon: number; people: Array<{ name: string; role: string }> } | null; | |
| 101 | 104 | /** The arm's STOP: who and when, as a line; null while it may move, undefined until the first status. */ |
| 102 | 105 | held: string | null | undefined; |
| 103 | 106 | /** Whether the call to confirm, and the "you are next" cue, were already printed (each is said once). */ |
| @@ -106,7 +109,7 @@ export interface Room { | ||
| 106 | 109 | seen: Map<string, Someone>; |
| 107 | 110 | } |
| 108 | 111 | |
| 109 | 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() }); | |
| 112 | export const emptyRoom = (): Room => ({ you: null, muted: false, banned: false, driver: null, queue: [], paused: false, here: null, held: undefined, told: { called: false, next: false }, seen: new Map() }); | |
| 110 | 113 | |
| 111 | 114 | const someone = (x: unknown): Someone | null => { |
| 112 | 115 | if (typeof x !== "object" || x === null) return null; |
| @@ -126,7 +129,7 @@ const said = (m: unknown): string => { | ||
| 126 | 129 | return from ? `${plain(from.name)}: ${plain(message?.text)}` : `· ${plain(message?.text)}`; |
| 127 | 130 | }; |
| 128 | 131 | |
| 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"; | |
| 132 | export const HELP = "type to chat · /join /leave /ready /extend · /stop /resume (driver, owner) · /end [who] /mute <who> /unmute <who> (owner) · /machine [off] · /who /here · /quit"; | |
| 130 | 133 | |
| 131 | 134 | /** The Machine feed's socket beside the lobby's: same app, same port. */ |
| 132 | 135 | export const machineUrl = (live: string): string => live.replace(/\/live$/, "/machine"); |
| @@ -215,6 +218,12 @@ export function hear(room: Room, frame: Frame): string[] { | ||
| 215 | 218 | if (now === was || (was === undefined && now === null)) return []; |
| 216 | 219 | return [now ?? "resumed: the arm may move again, from a new command"]; |
| 217 | 220 | } |
| 221 | case "presence": { | |
| 222 | const n = (k: string) => (typeof frame[k] === "number" ? (frame[k] as number) : 0); | |
| 223 | const people = Array.isArray(frame.people) ? frame.people.map((p) => ({ name: plain((p as { name?: unknown }).name), role: plain((p as { role?: unknown }).role) })) : []; | |
| 224 | room.here = { here: n("here"), signedIn: n("signedIn"), anon: n("anon"), people }; | |
| 225 | return []; | |
| 226 | } | |
| 218 | 227 | case "unsaid": |
| 219 | 228 | return ["· a line was removed"]; |
| 220 | 229 | case "error": |
| @@ -229,6 +238,14 @@ export function who(room: Room): string { | ||
| 229 | 238 | return `${room.paused ? "paused · " : ""}${room.driver ? `${plain(room.driver.name)} has control` : "nobody has control"} · ${line}`; |
| 230 | 239 | } |
| 231 | 240 | |
| 241 | /** Everyone here, as the page's list shows them: the count, then each name with what they are doing. */ | |
| 242 | export function here(room: Room): string { | |
| 243 | const h = room.here; | |
| 244 | if (!h) return "no word yet on who is here"; | |
| 245 | const names = h.people.map((p) => (p.role === "watching" ? p.name : `${p.name} (${p.role === "queued" ? "in the queue" : p.role})`)).join(", "); | |
| 246 | return `${h.here} here · ${h.signedIn} signed in · ${h.anon} watching${names ? `: ${names}` : ""}`; | |
| 247 | } | |
| 248 | ||
| 232 | 249 | /** A typed <who>: a name the door has seen, else taken as an id. */ |
| 233 | 250 | function target(room: Room, word: string): string | null { |
| 234 | 251 | const known = room.seen.get(word.toLowerCase()); |
| @@ -270,6 +287,8 @@ export function typed(room: Room, input: string): Typed { | ||
| 270 | 287 | return { machine: arg.toLowerCase() !== "off" }; |
| 271 | 288 | case "who": |
| 272 | 289 | return { print: who(room) }; |
| 290 | case "here": | |
| 291 | return { print: here(room) }; | |
| 273 | 292 | case "help": |
| 274 | 293 | return { print: HELP }; |
| 275 | 294 | case "quit": |
Software/so101/src/ui/here.js added +52
| @@ -0,0 +1,52 @@ | ||
| 1 | // @ts-check | |
| 2 | /** | |
| 3 | * The "who is here" panel: names as text, a dot in the viewer's curated colour, the role beside each name. Loaded the | |
| 4 | * first time the count is tapped, so a first visit never pays for it. A dialog: focus moves in on open and back to | |
| 5 | * the count on Close. | |
| 6 | */ | |
| 7 | ||
| 8 | /** The page's document: this module only runs there (the type check has no DOM, as for ./machine-panel.js). @type {any} */ | |
| 9 | const doc = /** @type {any} */ (globalThis).document; | |
| 10 | ||
| 11 | /** @param {any} opener the count button, where focus returns */ | |
| 12 | export function openHere(opener) { | |
| 13 | const panel = doc.createElement("div"); | |
| 14 | panel.className = "panel"; | |
| 15 | panel.id = "herePanel"; | |
| 16 | panel.setAttribute("role", "dialog"); | |
| 17 | panel.setAttribute("aria-label", "Who is here"); | |
| 18 | panel.tabIndex = -1; | |
| 19 | panel.hidden = true; | |
| 20 | const close = doc.createElement("button"); | |
| 21 | close.className = "close"; | |
| 22 | close.textContent = "Close"; | |
| 23 | close.onclick = () => { panel.hidden = true; opener.focus(); }; | |
| 24 | const title = doc.createElement("h2"); | |
| 25 | title.textContent = "Who is here"; | |
| 26 | const list = doc.createElement("ul"); | |
| 27 | list.id = "hereList"; | |
| 28 | const article = doc.createElement("article"); | |
| 29 | article.append(title, list); | |
| 30 | panel.append(close, article); | |
| 31 | doc.body.append(panel); | |
| 32 | ||
| 33 | return { | |
| 34 | /** @param {any} presence the last "presence" frame @param {boolean} [quiet] refresh the list but do not open the panel */ | |
| 35 | show(presence, quiet) { | |
| 36 | list.textContent = ""; | |
| 37 | for (const h of presence?.people ?? []) { | |
| 38 | const li = doc.createElement("li"), dot = doc.createElement("span"), role = doc.createElement("span"); | |
| 39 | li.className = h.role; | |
| 40 | dot.className = "dot"; | |
| 41 | if (/^#[0-9a-f]{6}$/i.test(h.color ?? "")) dot.style.background = h.color; | |
| 42 | role.className = "r"; | |
| 43 | role.textContent = h.role === "queued" ? "in the queue" : h.role; | |
| 44 | li.append(dot, h.name, role); | |
| 45 | list.append(li); | |
| 46 | } | |
| 47 | if (quiet) return; | |
| 48 | panel.hidden = false; | |
| 49 | panel.focus(); | |
| 50 | }, | |
| 51 | }; | |
| 52 | } |
Software/so101/src/ui/lobby-panel.js +2 −1
| @@ -245,12 +245,13 @@ export function createRoom(page) { | ||
| 245 | 245 | else if (m.type === "words") page.words(m); |
| 246 | 246 | else if (m.type === "admin") { const saved = lobby.admin !== null; lobby.admin = m; page.admin(saved); } |
| 247 | 247 | else if (m.type === "crew") lobby.crew = m; |
| 248 | else if (m.type === "presence") return page.presence(m); | |
| 248 | 249 | else if (m.type === "error") return msg(m.error, true); |
| 249 | 250 | renderTurn(); |
| 250 | 251 | }; |
| 251 | 252 | ws.onclose = () => { |
| 252 | 253 | if (lobby.ws !== ws) return; |
| 253 | lobby.ws = null; lobby.hello = null; lobby.statusSeen = false; // polling takes over until it is back | |
| 254 | lobby.ws = null; lobby.hello = null; lobby.statusSeen = false; page.presence(null); // polling takes over until it is back | |
| 254 | 255 | page.applyLock(); |
| 255 | 256 | $("driverLine").className = "none"; $("driverLine").textContent = "Reconnecting…"; |
| 256 | 257 | setTimeout(lobbyConnect, lobby.retry); |
Software/so101/src/viewer.html +12
| @@ -215,6 +215,7 @@ | ||
| 215 | 215 | #mutedLine .item { display: flex; align-items: center; gap: 8px; } #mutedLine .item span { flex: 1; } |
| 216 | 216 | |
| 217 | 217 | /* full-screen panels and dialogs */ |
| 218 | #hereList { list-style: none; padding: 0 ; } #hereList li { display: flex; gap: 8px; align-items: center; padding: 6px 0; } #hereList .driving { font-weight: 700; } #hereList .dot { width: 10px; height: 10px; border-radius: 50%; background: var(); } #hereList .r { margin-left: auto; color: var(); } | |
| 218 | 219 | .panel { position: fixed; inset: 0; z-index: 20; overflow: auto; background: var(); color: var(); padding: calc(16px + env(safe-area-inset-top, 0px)) calc(18px + var()) calc(40px + var()) calc(18px + var()); } |
| 219 | 220 | .panel article { max-width: 760px; margin: 0 auto; } |
| 220 | 221 | .panel h2 { margin: 0 80px 12px 0; font-size: 20px; } .panel h3 { margin: 18px 0 6px; font-size: 15px; } |
| @@ -304,6 +305,7 @@ | ||
| 304 | 305 | <div id="top"> |
| 305 | 306 | <span class="seg" role="group" aria-label="Views"><button id="v3" aria-pressed="false">3D</button></span> |
outdated
|
||
| 306 | 307 | <span class="info"><span id="link" hidden></span><span id="live" class="label"></span><span class="dot" id="dot"></span><span id="state">…</span><span id="lag" hidden></span></span> |
| 308 | <button id="here" type="button" hidden aria-live="polite"></button> | |
| 307 | 309 | <button id="quality" type="button" hidden title="Video quality: Auto follows the connection, Saver sends 2 frames a second, Full every frame">Auto</button> |
| 308 | 310 | <button id="fs" title="F">Fullscreen</button> |
| 309 | 311 | </div> |
| @@ -1586,7 +1588,17 @@ | ||
| 1586 | 1588 | $, el, relayed, msg, tab: () => tab, showTab, applyLock: () => applyLock(), applyStatus: (s) => applyStatus(s), noStatus: () => noStatus(), |
| 1587 | 1589 | 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"}.`); } }, |
| 1588 | 1590 | admin: (saved) => fillAdmin(saved), |
| 1591 | presence: (m) => hereUpdate(m), | |
| 1589 | 1592 | }); |
| 1593 | // Who is here: ./ui/here.js builds the list on the first tap. | |
| 1594 | let here, hereNow; | |
| 1595 | function hereUpdate(m) { | |
| 1596 | hereNow = m; | |
| 1597 | $("here").hidden = !m; | |
| 1598 | if (m) $("here").textContent = `${m.here} here · ${m.signedIn} signed in · ${m.anon} watching`; | |
| 1599 | here?.show(m, true); | |
| 1600 | } | |
| 1601 | $("here").onclick = async () => { here ??= (await import("/ui/__VERSION__/here.js")).openHere($("here")); here.show(hereNow); }; | |
| 1590 | 1602 | const { lobby, mayDrive, isOwner, say, serverNow, lobbyConnect, chatBox, renderTurn, button } = room; |
| 1591 | 1603 | let drove = false; |
| 1592 | 1604 | function explainLock() { |
new above
offline
The panel needs
role="dialog", an accessible name, focus moved in on open and returned to the button on Close. It is also inline-styled; the repo's pattern is classes in the page CSS.