Public: anyone can read this; the crew can change it.
Migrated from github.com/Trevato/SO-ARM100
workbenchthis machine
Terminal door: tty gating test for mute, end-turn and chat, and tty writes reaching web viewers live #47
Check · Review · Land done · Live — Landed; nothing deploys from this branch, so this is the end of its path.
quill/arm:quill/37-terminal-door-tty-gating-test-for-mute-e → main 1 commit fork
8 files
changed +542
−3
Software/README.md +25
| @@ -315,6 +315,31 @@ its live pose and the cameras. Driving needs a name and a turn. | ||
| 315 | 315 | agent is kept with each ban to read, not to block on: too many people |
| 316 | 316 | share one browser for it to tell them apart. |
| 317 | 317 | |
| 318 | **The terminal.** The room also has a terminal door (`src/tty.ts`, the | |
| 319 | `tty` in `forge.json`). Connect with the exact command the forge gives in | |
| 320 | `FORGE_APP_SSH`; when the forge has | |
| 321 | not set it for an environment, that environment's terminal is off. Your | |
| 322 | SSH key says who you are: a forge account that may write this repository | |
| 323 | is the owner, any other account is a signed-in person, and an unknown key | |
| 324 | watches. A line you type is said in the chat; commands start with `/`: | |
| 325 | ||
| 326 | - `/join`, `/leave`: ask to drive (the owner takes over at once), hand back. | |
| 327 | - `/end [name]`, owner: end that turn (no name: whoever drives), or take | |
| 328 | them out of the line. | |
| 329 | - `/mute <name>`, `/unmute <name>`, owner. | |
| 330 | - `/who` (who drives, who waits), `/help`, `/quit`. | |
| 331 | ||
| 332 | The terminal is a client of the running server, like the page: it opens | |
| 333 | the same `/live` socket on `127.0.0.1:$PORT`, as the forge's identity for | |
| 334 | the person at the keyboard (`FORGE_APP_USER*`, signed with | |
| 335 | `FORGE_APP_IDENTITY_KEY`). The server applies the same rules to both, so a | |
| 336 | muted person is muted at the terminal too, only the owner may end turns or | |
| 337 | mute, and every line, join and hand-back from the terminal reaches every | |
| 338 | web viewer as it happens. Text from the room is shown with control | |
| 339 | characters removed, so a chat line cannot drive your terminal. Locally, | |
| 340 | `PORT=8102 bun run Software/so101/src/tty.ts` beside `fake-serve.ts` | |
| 341 | reaches it as the owner. | |
| 342 | ||
| 318 | 343 | **Admin.** The owner runs the room from `/admin` (plain forms, no script), |
| 319 | 344 | or from the **Admin** tab that only the owner sees: |
| 320 | 345 |
Software/so101/src/chat.ts +1 −1
| @@ -30,7 +30,7 @@ export interface ChatOptions { | ||
| 30 | 30 | } |
| 31 | 31 | |
| 32 | 32 | /** Control characters and the bidi overrides that could turn a line around on screen. */ |
| 33 | const UNPRINTABLE = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g; | |
| 33 | export const UNPRINTABLE = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g; | |
| 34 | 34 | |
| 35 | 35 | export function cleanText(text: unknown): string { |
| 36 | 36 | if (typeof text !== "string") throw new ChatError("a message is text"); |
Software/so101/src/identity.ts +2 −2
| @@ -25,8 +25,8 @@ export type Who = Person | null; | ||
| 25 | 25 | /** Everyone at the keyboard of a local, forge-less run: there is nobody to sign in with, and nobody else. */ |
| 26 | 26 | export const LOCAL: Person = { id: "local", name: "local", owner: true }; |
| 27 | 27 | |
| 28 | const NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/; | |
| 29 | const ID = /^[A-Za-z0-9_-]{1,64}$/; | |
| 28 | export const NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/; | |
| 29 | export const ID = /^[A-Za-z0-9_-]{1,64}$/; | |
| 30 | 30 | |
| 31 | 31 | /** The signature the forge computes. Exported so a test can be the forge. */ |
| 32 | 32 | export const sign = (identity: string, key: string): string => createHmac("sha256", key).update(identity).digest("base64url"); |
Software/so101/src/manifest.test.ts +6
| @@ -20,3 +20,9 @@ test("egress covers the arm and the first camera the relay derives from one host | ||
| 20 | 20 | for (const target of needed) expect(egress).toContain(target); |
| 21 | 21 | expect(egress.every((e) => e.startsWith(`${host}:`))).toBe(true); |
| 22 | 22 | }); |
| 23 | ||
| 24 | test("the terminal the forge opens on ssh is this package's tty, run from the repository root", async () => { | |
| 25 | const command: string = manifest.app.tty; | |
| 26 | expect(command).toMatch(/^bun run [\w./-]+\.ts$/); | |
| 27 | expect(await Bun.file(new URL(`../../../${command.slice("bun run ".length)}`, import.meta.url)).exists()).toBe(true); | |
| 28 | }); |
Software/so101/src/terminal.test.ts added +223
| @@ -0,0 +1,223 @@ | ||
| 1 | import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test"; | |
| 2 | import { mkdtempSync } from "node:fs"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import WebSocket from "ws"; | |
| 6 | import { Accounts } from "./accounts.ts"; | |
| 7 | import { Admin } from "./admin.ts"; | |
| 8 | import { FeetechBus } from "./bus.ts"; | |
| 9 | import { Chat } from "./chat.ts"; | |
| 10 | import { FakeBus } from "./fake-bus.ts"; | |
| 11 | import { identify, sign } from "./identity.ts"; | |
| 12 | import { Lobby } from "./lobby.ts"; | |
| 13 | import { startRelay, type RunningRelay } from "./relay.ts"; | |
| 14 | import { startServer, type RunningServer } from "./server.ts"; | |
| 15 | import { Door, emptyRoom, hear, liveUrl, plain, terminalHeaders, typed } from "./terminal.ts"; | |
| 16 | import { Turns } from "./turns.ts"; | |
| 17 | ||
| 18 | const KEY = "test-identity-key"; | |
| 19 | const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); | |
| 20 | const shut = (s: { close(): Promise<void> } | undefined) => (s ? Promise.race([s.close(), sleep(500)]) : undefined); | |
| 21 | /** The environment the forge hands the `tty` program for this person. */ | |
| 22 | const ttyEnv = (id: string, name: string, role: string) => ({ FORGE_APP_IDENTITY_KEY: KEY, FORGE_APP_USER_ID: id, FORGE_APP_USER: name, FORGE_APP_USER_ROLE: role }); | |
| 23 | /** What the forge's proxy puts on a browser's request. */ | |
| 24 | const web = (id: string, name: string, role = "user") => { | |
| 25 | const identity = `${id}|${name}|${role}|${Date.now() + 3_600_000}`; | |
| 26 | return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) }; | |
| 27 | }; | |
| 28 | ||
| 29 | type Msg = Record<string, any>; | |
| 30 | const waitFor = async <T>(probe: () => T | undefined, what: string, ms = 2000): Promise<T> => { | |
| 31 | for (const until = Date.now() + ms; Date.now() < until; await sleep(10)) { | |
| 32 | const found = probe(); | |
| 33 | if (found !== undefined) return found; | |
| 34 | } | |
| 35 | throw new Error(`no ${what} in ${ms} ms`); | |
| 36 | }; | |
| 37 | ||
| 38 | describe("terminal identity", () => { | |
| 39 | test("the forge's terminal user is signed so the lobby knows them; a guest or a missing key is nobody", () => { | |
| 40 | const user = terminalHeaders(ttyEnv("u-alice", "alice", "user")); | |
| 41 | expect(identify(user, KEY)).toEqual({ id: "u-alice", name: "alice", owner: false }); | |
| 42 | expect(identify(terminalHeaders(ttyEnv("u-o", "trevato", "admin")), KEY)).toEqual({ id: "u-o", name: "trevato", owner: true }); | |
| 43 | expect(terminalHeaders({ ...ttyEnv("", "", ""), FORGE_APP_USER_ROLE: "" })).toEqual({}); | |
| 44 | expect(terminalHeaders({ ...ttyEnv("u-alice", "alice", "user"), FORGE_APP_IDENTITY_KEY: "" })).toEqual({}); | |
| 45 | expect(terminalHeaders(ttyEnv("u-alice", "alice", "root"))).toEqual({}); | |
| 46 | expect(terminalHeaders(ttyEnv("u-alice", "al|ice|admin", "user"))).toEqual({}); | |
| 47 | }); | |
| 48 | ||
| 49 | test("the signature is short-lived: the handshake reads it, nothing replays it later", () => { | |
| 50 | const h = terminalHeaders(ttyEnv("u-alice", "alice", "user"), 1000); | |
| 51 | expect(identify(h, KEY, 1000)).not.toBeNull(); | |
| 52 | expect(identify(h, KEY, 1000 + 61_000)).toBeNull(); | |
| 53 | }); | |
| 54 | ||
| 55 | test("the lobby is on loopback at PORT", () => { | |
| 56 | expect(liveUrl({ PORT: "4123" })).toBe("ws://127.0.0.1:4123/live"); | |
| 57 | expect(liveUrl({})).toBe("ws://127.0.0.1:8102/live"); | |
| 58 | expect(() => liveUrl({ PORT: "0" })).toThrow(); | |
| 59 | expect(() => liveUrl({ PORT: "80; rm -rf" })).toThrow(); | |
| 60 | }); | |
| 61 | }); | |
| 62 | ||
| 63 | describe("terminal lines", () => { | |
| 64 | test("room text never reaches the terminal as escapes or control characters", () => { | |
| 65 | const room = emptyRoom(); | |
| 66 | 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" } }); | |
| 67 | expect(lines).toEqual(["x[31m: [2Jboom ok"]); | |
| 68 | expect(lines.join("")).not.toMatch(/[\x00-\x1f\x7f-\x9f]/); | |
| 69 | expect(plain("a\tb")).toBe("a b"); | |
| 70 | }); | |
| 71 | ||
| 72 | test("typed lines become lobby frames; names the door has seen become ids", () => { | |
| 73 | const room = emptyRoom(); | |
| 74 | hear(room, { type: "state", driver: { id: "u-alice", name: "alice" }, queue: [{ id: "u-bob", name: "bob" }], paused: false }); | |
| 75 | expect(typed(room, "hello <b>there</b>")).toEqual({ send: { type: "post", text: "hello <b>there</b>" } }); | |
| 76 | expect(typed(room, "/end")).toEqual({ send: { type: "end", id: "u-alice" } }); | |
| 77 | expect(typed(room, "/end Bob")).toEqual({ send: { type: "end", id: "u-bob" } }); | |
| 78 | expect(typed(room, "/mute alice")).toEqual({ send: { type: "mute", id: "u-alice", on: true } }); | |
| 79 | expect(typed(room, "/unmute u-zed")).toEqual({ send: { type: "mute", id: "u-zed", on: false } }); | |
| 80 | expect(typed(room, "/mute")).toEqual({ print: "usage: /mute <name>" }); | |
| 81 | expect(typed(room, "/mute a.b!")).toEqual({ print: "error: who is a.b!?" }); | |
| 82 | expect(typed(room, "/who")).toEqual({ print: "alice has control · 1. bob" }); | |
| 83 | expect(typed(room, "/quit")).toEqual({ quit: true }); | |
| 84 | expect(typed(room, " ")).toBeNull(); | |
| 85 | expect(typed(emptyRoom(), "/end")).toEqual({ print: "nobody has control" }); | |
| 86 | }); | |
| 87 | }); | |
| 88 | ||
| 89 | /** Both doors on one room: the page's WebSocket and the terminal's, gated by the same server. */ | |
| 90 | describe("terminal door", () => { | |
| 91 | let simulation: RunningServer; | |
| 92 | let relay: RunningRelay | undefined; | |
| 93 | let lobby: Lobby | undefined; | |
| 94 | const open: Array<{ close(): void }> = []; | |
| 95 | beforeAll(async () => { | |
| 96 | simulation = await startServer(new FeetechBus(new FakeBus([1, 2, 6])), { host: "127.0.0.1", port: 0, ids: [1, 2, 6], posesFile: join(mkdtempSync(join(tmpdir(), "so101-tty-")), "poses.json") }); | |
| 97 | }); | |
| 98 | afterAll(() => shut(simulation)); | |
| 99 | afterEach(async () => { | |
| 100 | for (const o of open.splice(0)) o.close(); | |
| 101 | await shut(relay); | |
| 102 | lobby?.close(); | |
| 103 | relay = lobby = undefined; | |
| 104 | }); | |
| 105 | ||
| 106 | const start = async () => { | |
| 107 | lobby = new Lobby({ identityKey: KEY, turns: new Turns(), chat: new Chat({ rateMs: 0 }), admin: new Admin(), accounts: new Accounts() }); | |
| 108 | relay = await startRelay({ port: 0, simulation: `http://127.0.0.1:${simulation.port}`, lobby }); | |
| 109 | return relay.port; | |
| 110 | }; | |
| 111 | /** A terminal as the forge would start it for this person. */ | |
| 112 | const terminal = async (port: number, env: Record<string, string>) => { | |
| 113 | const printed: string[] = []; | |
| 114 | const door = new Door(liveUrl({ ...env, PORT: String(port) }), terminalHeaders(env), (line) => printed.push(line)); | |
| 115 | await door.open(); | |
| 116 | open.push(door); | |
| 117 | const printedLine = (match: RegExp) => waitFor(() => printed.find((l) => match.test(l)), `line matching ${match}; printed ${JSON.stringify(printed)}`); | |
| 118 | // Seated once the server said hello and the room's state. | |
| 119 | await waitFor(() => (door.room.you !== null || printed.length > 0 ? true : undefined), "hello"); | |
| 120 | return { door, printed, printedLine }; | |
| 121 | }; | |
| 122 | /** A browser on the page. */ | |
| 123 | const viewer = async (port: number, headers: Record<string, string> = {}) => { | |
| 124 | const ws = new WebSocket(`ws://127.0.0.1:${port}/live`, { headers }); | |
| 125 | const heard: Msg[] = []; | |
| 126 | ws.on("message", (d) => heard.push(JSON.parse(String(d)))); | |
| 127 | await new Promise((r, j) => (ws.once("open", r), ws.once("error", j))); | |
| 128 | open.push({ close: () => ws.terminate() }); | |
| 129 | const heardOne = (match: (m: Msg) => boolean, what: string) => waitFor(() => heard.find(match), `${what}; heard ${JSON.stringify(heard.slice(-4))}`); | |
| 130 | return { ws, heard, heardOne, send: (m: Msg) => ws.send(JSON.stringify(m)) }; | |
| 131 | }; | |
| 132 | ||
| 133 | test("a terminal line reaches every web viewer live, as text, and the web's lines reach the terminal", async () => { | |
| 134 | const port = await start(); | |
| 135 | const page = await viewer(port); | |
| 136 | const alice = await terminal(port, ttyEnv("u-alice", "alice", "user")); | |
| 137 | expect(alice.door.room.you).toEqual({ id: "u-alice", name: "alice", owner: false }); | |
| 138 | alice.door.input("hi from ssh <b>bold</b>"); | |
| 139 | const m = await page.heardOne((m) => m.type === "said" && m.message.from?.id === "u-alice", "terminal line on the page"); | |
| 140 | expect(m.message).toMatchObject({ from: { id: "u-alice", name: "alice" }, text: "hi from ssh <b>bold</b>" }); | |
| 141 | const bob = await viewer(port, web("u-bob", "bob")); | |
| 142 | bob.send({ type: "post", text: "hello terminal" }); | |
| 143 | await alice.printedLine(/^bob: hello terminal$/); | |
| 144 | }); | |
| 145 | ||
| 146 | test("a guest at the terminal watches and is refused chat and the line", async () => { | |
| 147 | const port = await start(); | |
| 148 | const page = await viewer(port); | |
| 149 | const guest = await terminal(port, ttyEnv("", "", "")); | |
| 150 | await guest.printedLine(/you are watching/); | |
| 151 | guest.door.input("let me in"); | |
| 152 | await guest.printedLine(/^error: join to take part$/); | |
| 153 | guest.door.input("/join"); | |
| 154 | await sleep(100); | |
| 155 | expect(guest.printed.filter((l) => l === "error: join to take part")).toHaveLength(2); | |
| 156 | expect(page.heard.some((m) => m.type === "said" && m.message.from)).toBe(false); | |
| 157 | expect(lobby!.turns.driver).toBeNull(); | |
| 158 | }); | |
| 159 | ||
| 160 | test("a terminal join and hand-back show on the page", async () => { | |
| 161 | const port = await start(); | |
| 162 | const page = await viewer(port); | |
| 163 | const alice = await terminal(port, ttyEnv("u-alice", "alice", "user")); | |
| 164 | alice.door.input("/join"); | |
| 165 | await page.heardOne((m) => m.type === "state" && m.driver?.id === "u-alice", "alice driving on the page"); | |
| 166 | alice.door.input("/leave"); | |
| 167 | await page.heardOne((m) => m.type === "said" && /alice's turn ended \(handed back\)/.test(m.message.text), "the hand-back on the page"); | |
| 168 | }); | |
| 169 | ||
| 170 | test("mute: only the owner's terminal may; the muted person's page hears it, and their terminal cannot chat", async () => { | |
| 171 | const port = await start(); | |
| 172 | const alicePage = await viewer(port, web("u-alice", "alice")); | |
| 173 | alicePage.send({ type: "post", text: "first" }); | |
| 174 | const bob = await terminal(port, ttyEnv("u-bob", "bob", "user")); | |
| 175 | await bob.printedLine(/^alice: first$/); | |
| 176 | bob.door.input("/mute alice"); | |
| 177 | await bob.printedLine(/^error: only the owner can do that$/); | |
| 178 | expect(lobby!.chat.muted.has("u-alice")).toBe(false); | |
| 179 | ||
| 180 | const owner = await terminal(port, ttyEnv("u-owner", "trevato", "admin")); | |
| 181 | expect(owner.door.room.you?.owner).toBe(true); | |
| 182 | owner.door.input("/mute alice"); | |
| 183 | await alicePage.heardOne((m) => m.type === "hello" && m.muted === true, "the mute on alice's page"); | |
| 184 | alicePage.send({ type: "post", text: "still here?" }); | |
| 185 | await alicePage.heardOne((m) => m.type === "error" && m.error === "you are muted", "a refused post"); | |
| 186 | ||
| 187 | // Alice at a terminal is the same person, and just as muted. | |
| 188 | const aliceTty = await terminal(port, ttyEnv("u-alice", "alice", "user")); | |
| 189 | await aliceTty.printedLine(/^you are muted$/); | |
| 190 | aliceTty.door.input("from ssh then"); | |
| 191 | await aliceTty.printedLine(/^error: you are muted$/); | |
| 192 | expect(lobby!.chat.messages.some((m) => m.text === "from ssh then" || m.text === "still here?")).toBe(false); | |
| 193 | ||
| 194 | owner.door.input("/unmute alice"); | |
| 195 | await aliceTty.printedLine(/^you may chat again$/); | |
| 196 | aliceTty.door.input("thanks"); | |
| 197 | await alicePage.heardOne((m) => m.type === "said" && m.message.text === "thanks", "alice's line once unmuted"); | |
| 198 | }); | |
| 199 | ||
| 200 | test("end-turn: only the owner's terminal may; the page sees the turn pass on", async () => { | |
| 201 | const port = await start(); | |
| 202 | const alicePage = await viewer(port, web("u-alice", "alice")); | |
| 203 | const bobPage = await viewer(port, web("u-bob", "bob")); | |
| 204 | alicePage.send({ type: "join" }); | |
| 205 | await alicePage.heardOne((m) => m.type === "state" && m.driver?.id === "u-alice", "alice driving"); | |
| 206 | bobPage.send({ type: "join" }); | |
| 207 | await bobPage.heardOne((m) => m.type === "state" && m.queue?.[0]?.id === "u-bob", "bob in line"); | |
| 208 | ||
| 209 | const carol = await terminal(port, ttyEnv("u-carol", "carol", "user")); | |
| 210 | carol.door.input("/end"); | |
| 211 | await carol.printedLine(/^error: only the owner can do that$/); | |
| 212 | carol.door.input("/end bob"); | |
| 213 | await waitFor(() => (carol.printed.filter((l) => /only the owner/.test(l)).length === 2 ? true : undefined), "a second refusal"); | |
| 214 | expect(lobby!.turns.driver?.id).toBe("u-alice"); | |
| 215 | expect(lobby!.turns.queue.map((p) => p.id)).toEqual(["u-bob"]); | |
| 216 | ||
| 217 | const owner = await terminal(port, ttyEnv("u-owner", "trevato", "admin")); | |
| 218 | owner.door.input("/end"); | |
| 219 | await bobPage.heardOne((m) => m.type === "state" && m.driver?.id === "u-bob", "bob driving after the owner ended alice's turn"); | |
| 220 | await owner.printedLine(/alice's turn ended .*bob has control/); | |
| 221 | expect(lobby!.admin.log.some((e) => /ended alice's turn/.test(JSON.stringify(e)))).toBe(true); | |
| 222 | }); | |
| 223 | }); |
Software/so101/src/terminal.ts added +238
| @@ -0,0 +1,238 @@ | ||
| 1 | /** | |
| 2 | * The room's terminal door: chat, the line and the owner's mute and end-turn, typed instead of tapped. | |
| 3 | * | |
| 4 | * The forge runs forge.json's `tty` on a pty when someone `ssh`es to the app (FORGE_APP_SSH says how). That program | |
| 5 | * is handed the app's own environment — PORT, FORGE_APP_IDENTITY_KEY — plus who is at the keyboard: | |
| 6 | * FORGE_APP_USER, FORGE_APP_USER_ID and FORGE_APP_USER_ROLE (`user`, `admin` for whoever may write the repository, | |
| 7 | * empty for a guest). Its cell may reach the running app on http://127.0.0.1:$PORT, so the door is simply another | |
| 8 | * client of /live: it signs that identity the way the forge signs a browser's (src/identity.ts) and the Lobby gates | |
| 9 | * it exactly as it gates the page. Nothing here decides who may do what; the server does, and says why not. | |
| 10 | * | |
| 11 | * Typed lines: | |
| 12 | * <text> say it | |
| 13 | * /join /leave ask to drive (the owner takes over), or hand back / leave the line | |
| 14 | * /end [who] owner: end that turn (none: whoever drives), or take them out of the line | |
| 15 | * /mute <who> /unmute <who> owner | |
| 16 | * /who /help /quit | |
| 17 | * <who> is a name the door has seen (driving, in line, in the chat) or a user id. | |
| 18 | */ | |
| 19 | ||
| 20 | import WebSocket from "ws"; | |
| 21 | import { UNPRINTABLE } from "./chat.ts"; | |
| 22 | import { ID, NAME, sign } from "./identity.ts"; | |
| 23 | ||
| 24 | export type Env = Record<string, string | undefined>; | |
| 25 | ||
| 26 | /** How long the signed identity is good for: only the handshake reads it. */ | |
| 27 | const SIGNED_FOR_MS = 60_000; | |
| 28 | const MAX_LINE = 600; | |
| 29 | ||
| 30 | /** The forge's headers for whoever is at this terminal, signed here; none for a guest or with no key. */ | |
| 31 | export function terminalHeaders(env: Env, now = Date.now()): Record<string, string> { | |
| 32 | const key = env.FORGE_APP_IDENTITY_KEY ?? ""; | |
| 33 | const id = env.FORGE_APP_USER_ID ?? ""; | |
| 34 | const name = env.FORGE_APP_USER ?? ""; | |
| 35 | const role = env.FORGE_APP_USER_ROLE ?? ""; | |
| 36 | if (!key || (role !== "user" && role !== "admin") || !ID.test(id) || !NAME.test(name)) return {}; | |
| 37 | const identity = `${id}|${name}|${role}|${now + SIGNED_FOR_MS}`; | |
| 38 | return { "x-forge-identity": identity, "x-forge-signature": sign(identity, key) }; | |
| 39 | } | |
| 40 | ||
| 41 | /** The running app's lobby, beside the terminal: PORT as the forge sets it, 8102 as bench/fake-serve.ts defaults. */ | |
| 42 | export function liveUrl(env: Env): string { | |
| 43 | const raw = env.PORT ?? "8102"; | |
| 44 | const port = /^\d{1,5}$/.test(raw) ? Number(raw) : NaN; | |
| 45 | if (!(port >= 1 && port <= 65535)) throw new Error(`PORT is not a port: ${JSON.stringify(raw.slice(0, 20))}`); | |
| 46 | return `ws://127.0.0.1:${port}/live`; | |
| 47 | } | |
| 48 | ||
| 49 | /** Text from the room, safe to write to a terminal: no escapes, no control characters, no line breaks. */ | |
| 50 | export const plain = (text: unknown): string => String(text ?? "").replace(/\r\n?|\n|\t/g, " ").replace(UNPRINTABLE, ""); | |
| 51 | ||
| 52 | type Frame = Record<string, unknown>; | |
| 53 | interface Someone { | |
| 54 | id: string; | |
| 55 | name: string; | |
| 56 | } | |
| 57 | ||
| 58 | /** What the door knows of the room, from what the server told it. */ | |
| 59 | export interface Room { | |
| 60 | you: (Someone & { owner: boolean }) | null; | |
| 61 | muted: boolean; | |
| 62 | banned: boolean; | |
| 63 | driver: Someone | null; | |
| 64 | queue: Someone[]; | |
| 65 | paused: boolean; | |
| 66 | /** Everyone seen by name, most recent last: to turn a typed name into an id. */ | |
| 67 | seen: Map<string, Someone>; | |
| 68 | } | |
| 69 | ||
| 70 | export const emptyRoom = (): Room => ({ you: null, muted: false, banned: false, driver: null, queue: [], paused: false, seen: new Map() }); | |
| 71 | ||
| 72 | const someone = (x: unknown): Someone | null => { | |
| 73 | if (typeof x !== "object" || x === null) return null; | |
| 74 | const { id, name } = x as Record<string, unknown>; | |
| 75 | return typeof id === "string" && typeof name === "string" ? { id, name } : null; | |
| 76 | }; | |
| 77 | ||
| 78 | function see(room: Room, who: Someone | null): void { | |
| 79 | if (!who) return; | |
| 80 | room.seen.delete(who.name.toLowerCase()); | |
| 81 | room.seen.set(who.name.toLowerCase(), who); | |
| 82 | } | |
| 83 | ||
| 84 | const said = (m: unknown): string => { | |
| 85 | const message = m as { from?: unknown; text?: unknown } | null; | |
| 86 | const from = someone(message?.from); | |
| 87 | return from ? `${plain(from.name)}: ${plain(message?.text)}` : `· ${plain(message?.text)}`; | |
| 88 | }; | |
| 89 | ||
| 90 | export const HELP = "type to chat · /join /leave · /end [who] /mute <who> /unmute <who> (owner) · /who · /quit"; | |
| 91 | ||
| 92 | /** Fold one server frame into the room; what to print for it, if anything. */ | |
| 93 | export function hear(room: Room, frame: Frame): string[] { | |
| 94 | switch (frame.type) { | |
| 95 | case "hello": { | |
| 96 | const you = someone(frame.you); | |
| 97 | const was = { you: room.you, muted: room.muted, banned: room.banned }; | |
| 98 | room.you = you ? { ...you, owner: (frame.you as { owner?: unknown }).owner === true } : null; | |
| 99 | room.muted = frame.muted === true; | |
| 100 | room.banned = frame.banned === true; | |
| 101 | see(room, you); | |
| 102 | const out: string[] = []; | |
| 103 | if (!was.you && room.you) out.push(`you are ${plain(room.you.name)}${room.you.owner ? " (owner)" : ""}`); | |
| 104 | if (!room.you && frame.signin === true) out.push("you are watching: connect with a key your forge account knows to chat and drive"); | |
| 105 | if (room.muted !== was.muted && (room.muted || was.you)) out.push(room.muted ? "you are muted" : "you may chat again"); | |
| 106 | if (room.banned && !was.banned) out.push("you are banned: you can still watch"); | |
| 107 | return out; | |
| 108 | } | |
| 109 | case "state": { | |
| 110 | room.driver = someone(frame.driver); | |
| 111 | room.queue = Array.isArray(frame.queue) ? frame.queue.map(someone).filter((p): p is Someone => p !== null) : []; | |
| 112 | room.paused = frame.paused === true; | |
| 113 | see(room, room.driver); | |
| 114 | for (const p of room.queue) see(room, p); | |
| 115 | return []; | |
| 116 | } | |
| 117 | case "chat": { | |
| 118 | const messages = Array.isArray(frame.messages) ? frame.messages : []; | |
| 119 | for (const m of messages) see(room, someone((m as { from?: unknown } | null)?.from)); | |
| 120 | return messages.slice(-10).map(said); | |
| 121 | } | |
| 122 | case "said": | |
| 123 | see(room, someone((frame.message as { from?: unknown } | null)?.from)); | |
| 124 | return [said(frame.message)]; | |
| 125 | case "unsaid": | |
| 126 | return ["· a line was removed"]; | |
| 127 | case "error": | |
| 128 | return [`error: ${plain(frame.error)}`]; | |
| 129 | default: | |
| 130 | return []; | |
| 131 | } | |
| 132 | } | |
| 133 | ||
| 134 | export function who(room: Room): string { | |
| 135 | const line = room.queue.length ? room.queue.map((p, i) => `${i + 1}. ${plain(p.name)}`).join(" ") : "nobody waiting"; | |
| 136 | return `${room.paused ? "paused · " : ""}${room.driver ? `${plain(room.driver.name)} has control` : "nobody has control"} · ${line}`; | |
| 137 | } | |
| 138 | ||
| 139 | /** A typed <who>: a name the door has seen, else taken as an id. */ | |
| 140 | function target(room: Room, word: string): string | null { | |
| 141 | const known = room.seen.get(word.toLowerCase()); | |
| 142 | if (known) return known.id; | |
| 143 | return ID.test(word) ? word : null; | |
| 144 | } | |
| 145 | ||
| 146 | export type Typed = { send: Frame } | { print: string } | { quit: true } | null; | |
| 147 | ||
| 148 | /** What a typed line asks for. Validation the server repeats anyway; this only saves a round trip on a typo. */ | |
| 149 | export function typed(room: Room, input: string): Typed { | |
| 150 | const line = input.slice(0, MAX_LINE).trim(); | |
| 151 | if (!line) return null; | |
| 152 | if (!line.startsWith("/")) return { send: { type: "post", text: line } }; | |
| 153 | const [verb = "", arg = "", ...rest] = line.slice(1).split(/\s+/); | |
| 154 | if (rest.length) return { print: `error: one name at a time` }; | |
| 155 | switch (verb.toLowerCase()) { | |
| 156 | case "join": | |
| 157 | case "leave": | |
| 158 | return { send: { type: verb.toLowerCase() } }; | |
| 159 | case "end": { | |
| 160 | if (!arg && !room.driver) return { print: "nobody has control" }; | |
| 161 | const id = arg ? target(room, arg) : room.driver!.id; | |
| 162 | return id ? { send: { type: "end", id } } : { print: `error: who is ${plain(arg)}?` }; | |
| 163 | } | |
| 164 | case "mute": | |
| 165 | case "unmute": { | |
| 166 | if (!arg) return { print: `usage: /${verb.toLowerCase()} <name>` }; | |
| 167 | const id = target(room, arg); | |
| 168 | return id ? { send: { type: "mute", id, on: verb.toLowerCase() === "mute" } } : { print: `error: who is ${plain(arg)}?` }; | |
| 169 | } | |
| 170 | case "who": | |
| 171 | return { print: who(room) }; | |
| 172 | case "help": | |
| 173 | return { print: HELP }; | |
| 174 | case "quit": | |
| 175 | case "exit": | |
| 176 | return { quit: true }; | |
| 177 | default: | |
| 178 | return { print: `unknown command /${plain(verb)} · ${HELP}` }; | |
| 179 | } | |
| 180 | } | |
| 181 | ||
| 182 | /** One terminal's seat in the room: lines in, lines out. */ | |
| 183 | export class Door { | |
| 184 | readonly room = emptyRoom(); | |
| 185 | private ws: WebSocket | null = null; | |
| 186 | private readonly url: string; | |
| 187 | private readonly headers: Record<string, string>; | |
| 188 | private readonly print: (line: string) => void; | |
| 189 | ||
| 190 | constructor(url: string, headers: Record<string, string>, print: (line: string) => void) { | |
| 191 | this.url = url; | |
| 192 | this.headers = headers; | |
| 193 | this.print = print; | |
| 194 | } | |
| 195 | ||
| 196 | /** Connect; resolves once seated, rejects when the app does not answer. `onClose` hears the app going away. */ | |
| 197 | open(onClose: () => void = () => {}): Promise<void> { | |
| 198 | const ws = new WebSocket(this.url, { headers: this.headers, maxPayload: 1 << 20 }); | |
| 199 | this.ws = ws; | |
| 200 | ws.on("message", (data, binary) => { | |
| 201 | if (binary) return; | |
| 202 | let frame: unknown; | |
| 203 | try { | |
| 204 | frame = JSON.parse(String(data)); | |
| 205 | } catch { | |
| 206 | return; | |
| 207 | } | |
| 208 | if (typeof frame !== "object" || frame === null || Array.isArray(frame)) return; | |
| 209 | if ((frame as Frame).type === "ping") return this.send({ type: "pong" }); | |
| 210 | for (const line of hear(this.room, frame as Frame)) this.print(line); | |
| 211 | }); | |
| 212 | return new Promise((resolve, reject) => { | |
| 213 | ws.once("open", () => { | |
| 214 | ws.on("close", onClose); | |
| 215 | resolve(); | |
| 216 | }); | |
| 217 | ws.once("error", reject); | |
| 218 | }); | |
| 219 | } | |
| 220 | ||
| 221 | /** A typed line. False when it asks to quit. */ | |
| 222 | input(line: string): boolean { | |
| 223 | const t = typed(this.room, line); | |
| 224 | if (!t) return true; | |
| 225 | if ("quit" in t) return false; | |
| 226 | if ("print" in t) this.print(t.print); | |
| 227 | else this.send(t.send); | |
| 228 | return true; | |
| 229 | } | |
| 230 | ||
| 231 | close(): void { | |
| 232 | this.ws?.close(); | |
| 233 | } | |
| 234 | ||
| 235 | private send(frame: Frame): void { | |
| 236 | if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify(frame)); | |
| 237 | } | |
| 238 | } |
Software/so101/src/tty.ts added +46
| @@ -0,0 +1,46 @@ | ||
| 1 | /** | |
| 2 | * forge.json's `tty`: the room on a terminal (src/terminal.ts). The forge starts this on a pty for each `ssh` to | |
| 3 | * the app, beside the running server; locally, `bun run src/tty.ts` reaches bench/fake-serve.ts on PORT (8102). | |
| 4 | */ | |
| 5 | ||
| 6 | import { createInterface, type Interface } from "node:readline"; | |
| 7 | import { Door, HELP, liveUrl, terminalHeaders } from "./terminal.ts"; | |
| 8 | ||
| 9 | const env = process.env; | |
| 10 | const where = env.FORGE_APP_ENV === "preview" ? `preview of #${env.FORGE_APP_PULL ?? "?"}` : (env.FORGE_APP_ENV ?? "local"); | |
| 11 | let rl: Interface | null = null; | |
| 12 | let leaving = false; | |
| 13 | ||
| 14 | /** A line from the room, written above whatever is being typed. */ | |
| 15 | const print = (line: string) => { | |
| 16 | process.stdout.write("\r\x1b[2K" + line + "\r\n"); | |
| 17 | rl?.prompt(true); | |
| 18 | }; | |
| 19 | ||
| 20 | const door = new Door(liveUrl(env), terminalHeaders(env), print); | |
| 21 | print(`\x1b[1mSO-101 arm\x1b[0m · ${where} · ${HELP}`); | |
| 22 | try { | |
| 23 | await door.open(() => { | |
| 24 | if (leaving) return; | |
| 25 | print("the arm's server went away"); | |
| 26 | process.exit(1); | |
| 27 | }); | |
| 28 | } catch (err) { | |
| 29 | print(`the arm's server is not answering (${(err as Error).message})`); | |
| 30 | process.exit(1); | |
| 31 | } | |
| 32 | ||
| 33 | // Read only once seated, so nothing typed meanwhile is lost. | |
| 34 | rl = createInterface({ input: process.stdin, output: process.stdout, prompt: "> " }); | |
| 35 | const leave = () => { | |
| 36 | leaving = true; | |
| 37 | door.close(); | |
| 38 | process.exit(0); | |
| 39 | }; | |
| 40 | rl.on("line", (line) => { | |
| 41 | if (!door.input(line)) rl!.close(); | |
| 42 | else rl!.prompt(); | |
| 43 | }); | |
| 44 | // The end of input (a pipe, ^D) leaves a moment for the room's answer to the last line. | |
| 45 | rl.on("close", () => setTimeout(leave, 300)); | |
| 46 | rl.prompt(); |
forge.json +1
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | "app": { |
| 3 | 3 | "install": "bun install --cwd Software/so101 --frozen-lockfile", |
| 4 | 4 | "run": "bun run Software/so101/bench/fake-serve.ts", |
| 5 | "tty": "bun run Software/so101/src/tty.ts", | |
| 5 | 6 | "test": "bun --cwd Software/so101 test", |
| 6 | 7 | "health": "/status" |
| 7 | 8 | }, |
new above
offline