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

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

A chat mute can last 10 min, 1 h, 24 h or for good, and ends on its own - in src/chat.ts #253

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/236-a-chat-mute-can-last-10-min-1-h-24-h-or → main 6 commits fork 5 threads · 5 unresolved

  • Merged. smith/236-a-chat-mute-can-last-10-min-1-h-24-h-or was merged into main as 81fbc14.

Review

Sign in to review this change.
9 files changed +150 −22
Software/README.md +1 −1
@@ -471,7 +471,7 @@ watches. A line you type is said in the chat; commands start with `/`:
471471 `resumed` when it is resumed.
472472 - `/end [name]`, owner: end that turn (no name: whoever drives), or take
473473 them out of the line.
474 - `/mute <name>`, `/unmute <name>`, owner.
474 - `/mute <name> [10m|1h|24h|forever]`, `/unmute <name>`, owner. A mute without a length is for good; a timed one ends on its own and the owner's list says when.
475475 - `/table here`, owner: the page's "Table is here", the same
476476 `POST /settings/table-here`: the table plane goes under the arm's lowest
477477 link now. `/table <mm>`, owner: sets `tableOffsetMm` (-100 to 100) by
Software/so101/src/chat.test.ts +30 −2
@@ -35,7 +35,7 @@ describe("chat", () => {
3535 let clock = 0;
3636 const chat = new Chat({ file, now: () => (clock += 5000) });
3737 for (let i = 0; i < KEEP + 5; i++) chat.post(alice, `line ${i}`);
38 chat.mute("b", "bob", true);
38 chat.mute("b", "bob", null);
3939 expect(chat.messages.length).toBe(KEEP);
4040 const again = new Chat({ file });
4141 expect(again.messages.length).toBe(KEEP);
@@ -47,10 +47,38 @@ describe("chat", () => {
4747 test("a muted person cannot post; a deleted line is gone", () => {
4848 const chat = new Chat();
4949 const line = chat.post(alice, "spam");
50 chat.mute("a", "alice", true);
50 chat.mute("a", "alice", null);
5151 expect(() => chat.post(alice, "more")).toThrow(/muted/);
5252 expect(chat.delete(line.id)).toBe(true);
5353 expect(chat.delete(line.id)).toBe(false);
5454 expect(chat.messages).toEqual([]);
5555 });
56
57 test("a timed mute ends on its own; a permanent one survives a reload; the old file format loads", () => {
58 const min = 60_000;
59 let clock = 0;
60 const file = join(mkdtempSync(join(tmpdir(), "chat-")), "chat.json");
61 const chat = new Chat({ file, now: () => clock });
62 chat.mute("a", "alice", 10 * min);
63 chat.mute("b", "bob", null);
64 clock = 10 * min - 1000;
65 expect(() => chat.post(alice, "hi")).toThrow(/muted/);
66 expect(chat.muted.has("a")).toBe(true);
67 clock = 10 * min + 1000;
68 expect(chat.post(alice, "hi").text).toBe("hi");
69 expect(chat.muted.has("a")).toBe(false);
70 clock = 1000 * min;
71 const again = new Chat({ file, now: () => clock });
72 expect(again.muted.get("b")).toBe("bob");
73 expect(() => again.post(bob, "hi")).toThrow(/muted/);
74 again.unmute("b");
75 expect(again.post(bob, "hi").text).toBe("hi");
76 });
77
78 test("an old-format file loads as a mute for good", async () => {
79 const old = join(mkdtempSync(join(tmpdir(), "chat-")), "chat.json");
80 await Bun.write(old, JSON.stringify({ messages: [], muted: { c: "carol" } }));
81 const chat = new Chat({ file: old, now: () => 1e12 });
82 expect(chat.muted.get("c")).toBe("carol");
83 });
5684 });
Software/so101/src/chat.ts +58 −8
@@ -42,8 +42,11 @@ export function cleanText(text: unknown): string {
4242
4343 export class Chat {
4444 messages: Message[] = [];
45 /** id → name of everyone muted. */
46 readonly muted = new Map<string, string>();
45 /** id → mute; `until` null is for good. */
46 private readonly mutes = new Map<string, { name: string; until: number | null }>();
47 /** id → name of everyone muted; kept in step with `mutes`, expired ones pruned on read. */
48 private readonly names = new Map<string, string>();
49 private readonly expired: string[] = [];
4750 private next = 1;
4851 private readonly lastPost = new Map<string, number>();
4952 private readonly file: string | undefined;
@@ -57,8 +60,21 @@ export class Chat {
5760 if (this.file) this.load(this.file);
5861 }
5962
outdated

This allocates a new Map on every read. Prune expired mutes here, or share one active(mute) helper with post instead of repeating the expiry check.

63 /** id → name of everyone muted right now; a mute that has run out is gone. */
64 get muted(): Map<string, string> {
65 this.prune();
66 return this.names;
67 }
68
69 /** Everyone muted right now, with when it ends (null: for good). */
70 mutedList(): { id: string; name: string; until: number | null }[] {
71 this.prune();
72 return [...this.mutes].map(([id, m]) => ({ id, name: m.name, until: m.until }));
73 }
74
6075 post(who: Person, text: unknown): Message {
61 if (this.muted.has(who.id)) throw new ChatError("you are muted");
76 this.prune();
77 if (this.names.has(who.id)) throw new ChatError("you are muted");
6278 const clean = cleanText(text);
6379 const now = this.now();
6480 const last = this.lastPost.get(who.id);
@@ -88,12 +104,36 @@ export class Chat {
88104 this.save();
89105 }
90106
91 mute(id: string, name: string, on: boolean): void {
92 if (on) this.muted.set(id, name);
93 else this.muted.delete(id);
107 /** Mutes until the time `until` (ms), or for good when null. */
108 mute(id: string, name: string, until: number | null): void {
109 this.mutes.set(id, { name, until });
110 this.names.set(id, name);
94111 this.save();
95112 }
96113
114 unmute(id: string): void {
115 this.mutes.delete(id);
116 this.names.delete(id);
117 this.save();
118 }
119
outdated

Expiry is only noticed lazily on read. Nothing notifies the lobby when a mute ends, so seats keep their stale hello.muted. Return the expired ids from prune, or let the lobby own the timer, so it can re-send hello and the muted list.

120 /** The people whose mute has run out since the last call, for whoever must tell them. */
121 takeExpired(): string[] {
122 this.prune();
123 return this.expired.splice(0);
124 }
125
126 /** Forgets the mutes whose time has come. */
127 private prune(): void {
128 const now = this.now();
129 for (const [id, m] of this.mutes) {
130 if (m.until === null || now < m.until) continue;
131 this.mutes.delete(id);
132 this.names.delete(id);
133 this.expired.push(id);
134 }
135 }
136
97137 private add(from: Message["from"], text: string): Message {
98138 const message = { id: this.next++, at: this.now(), from, text };
99139 this.messages.push(message);
@@ -114,14 +154,24 @@ export class Chat {
114154 .filter((m): m is Message => typeof m?.id === "number" && typeof m.at === "number" && typeof m.text === "string" && (m.from === null || (typeof m.from?.id === "string" && typeof m.from?.name === "string")))
115155 .slice(-KEEP);
116156 }
117 if (stored.muted && typeof stored.muted === "object") for (const [id, name] of Object.entries(stored.muted)) if (typeof name === "string") this.muted.set(id, name);
157 if (stored.muted && typeof stored.muted === "object") {
158 // a name string is the old format: muted for good
159 for (const [id, v] of Object.entries(stored.muted as Record<string, unknown>)) {
160 if (typeof v === "string") this.mutes.set(id, { name: v, until: null });
161 else if (v && typeof v === "object") {
162 const { name, until } = v as { name?: unknown; until?: unknown };
163 if (typeof name === "string" && (until === null || typeof until === "number")) this.mutes.set(id, { name, until });
164 }
165 }
166 }
167 for (const [id, m] of this.mutes) this.names.set(id, m.name);
118168 this.next = Math.max(0, ...this.messages.map((m) => m.id)) + 1;
119169 }
120170
121171 private save(): void {
122172 if (!this.file) return;
123173 mkdirSync(dirname(this.file), { recursive: true });
124 writeFileSync(`${this.file}.tmp`, JSON.stringify({ messages: this.messages, muted: Object.fromEntries(this.muted) }));
174 writeFileSync(`${this.file}.tmp`, JSON.stringify({ messages: this.messages, muted: Object.fromEntries([...this.mutes].map(([id, m]) => [id, m.until === null ? m.name : m])) }));
125175 renameSync(`${this.file}.tmp`, this.file);
126176 }
127177 }
Software/so101/src/lobby.test.ts +23 −1
@@ -272,12 +272,34 @@ describe("lobby", () => {
272272 expect((await anon.next((m) => m.type === "unsaid")).id).toBe(said.message.id);
273273 owner.send({ type: "mute", id: "u-alice", on: true });
274274 expect((await alice.next((m) => m.type === "hello")).muted).toBe(true);
275 expect((await owner.next((m) => m.type === "muted")).muted).toEqual([{ id: "u-alice", name: "alice" }]);
275 expect((await owner.next((m) => m.type === "muted")).muted).toEqual([{ id: "u-alice", name: "alice", until: null }]);
276276
277277 const late = await join(port);
278278 expect((await late.first((m) => m.type === "chat")).messages).toEqual([]);
279279 });
280280
281 test("a 10-minute mute reaches the owner's list with its end, refuses a bad length, and ends on its own", async () => {
282 let clock = 1_000_000;
283 const chat = new Chat({ now: () => clock });
284 lobby = new Lobby({ identityKey: KEY, turns: new Turns(), chat, admin: new Admin(), accounts: new Accounts(), now: () => clock, pingMs: 20 });
285 relay = await startRelay({ port: 0, simulation: `http://127.0.0.1:${simulation.port}`, lobby });
286 const alice = await join(relay.port, ALICE);
287 const owner = await join(relay.port, OWNER);
288 owner.send({ type: "mute", id: "u-alice", on: true, for: "2 weeks" });
289 expect((await owner.next((m) => m.type === "error")).error).toContain("10m, 1h, 24h or forever");
290 owner.send({ type: "mute", id: "u-alice", on: true, for: "10m" });
291 expect((await alice.next((m) => m.type === "hello")).muted).toBe(true);
292 expect((await owner.next((m) => m.type === "muted")).muted).toEqual([{ id: "u-alice", name: "alice", until: 1_600_000 }]);
293 clock = 1_599_000;
294 expect(chat.muted.has("u-alice")).toBe(true);
295 clock = 1_601_000;
296 expect((await alice.next((m) => m.type === "hello")).muted).toBe(false); // told without a reload
297 expect((await owner.next((m) => m.type === "muted")).muted).toEqual([]);
298 expect(chat.muted.has("u-alice")).toBe(false);
299 alice.send({ type: "post", text: "back" });
300 expect((await alice.next((m) => m.type === "said")).message.text).toBe("back");
301 });
302
281303 test("a moderator deletes a chat line and it is logged; a plain user is refused; settings and pause stay the owner's", async () => {
282304 const admin = new Admin();
283305 admin.set({ id: "u-owner", name: "trevato", owner: true }, { moderators: ["bob"] });
Software/so101/src/lobby.ts +24 −3
@@ -12,7 +12,7 @@
1212 * {"type": "post", "text": "…"} say something
1313 * {"type": "end", "id": "<user id>"} owner: end that turn, or take them out of the line
1414 * {"type": "delete", "id": 12} owner or a moderator: delete a chat line
15 * {"type": "mute", "id": "<user id>", "on": true|false} owner
15 * {"type": "mute", "id": "<user id>", "on": true|false, "for": "10m"|"1h"|"24h"|"forever"} owner
1616 * {"type": "pause", "on": true|false} owner: maintenance; nobody new gets a turn
1717 * {"type": "settings", "set": {…}} owner: any of src/admin.ts's settings
1818 * {"type": "crew", "settings": {"enabled", "rules", "maxPerMinute"}} owner: the moderator's settings
@@ -41,7 +41,12 @@ import { WordFilter } from "./word-filter.ts";
4141 import { identify, LOCAL, type Person, type Who } from "./identity.ts";
4242 import { Turns, type TurnEvent } from "./turns.ts";
4343
44 /** How long a mute lasts, by the name the page and the terminal send; null is for good. */
45 export const MUTE_FOR: Record<string, number | null> = { "10m": 600_000, "1h": 3_600_000, "24h": 86_400_000, forever: null };
46
4447 export interface LobbyOptions {
48 /** The clock mutes are timed on; Date.now by default. */
49 now?: () => number;
4550 /** FORGE_APP_IDENTITY_KEY. Without it nobody is signed in, unless `local`. */
4651 identityKey?: string;
4752 /** A forge-less run on one machine: every visitor is the owner and may command the arm (there is no one to sign in as). */
@@ -98,8 +103,10 @@ export class Lobby {
98103 private readonly pinger: ReturnType<typeof setInterval>;
99104 private readonly silentMs: number;
100105 private lastActivityState = 0;
106 private readonly now: () => number;
101107
102108 constructor(options: LobbyOptions = {}) {
109 this.now = options.now ?? Date.now;
103110 this.key = options.identityKey ?? "";
104111 this.local = Boolean(options.local);
105112 this.admin = options.admin ?? new Admin({ file: options.adminFile });
@@ -343,9 +350,12 @@ export class Lobby {
343350 }
344351 case "mute": {
345352 if (typeof m.id !== "string" || !USER_ID.test(m.id) || typeof m.on !== "boolean") return this.send(seat, { type: "error", error: "mute whom?" });
353 if (m.for !== undefined && (typeof m.for !== "string" || !Object.hasOwn(MUTE_FOR, m.for))) return this.send(seat, { type: "error", error: "mute for 10m, 1h, 24h or forever" });
346354 const id = m.id;
347355 const name = [...this.seats].find((s) => s.who?.id === id)?.who?.name ?? [...this.chat.messages].reverse().find((x) => x.from?.id === id)?.from?.name ?? this.chat.muted.get(id) ?? id;
348 this.chat.mute(id, name, m.on);
356 const span = MUTE_FOR[m.for ?? "forever"];
357 if (m.on) this.chat.mute(id, name, span === null ? null : this.now() + span);
358 else this.chat.unmute(id);
349359 for (const s of this.seats) {
350360 if (s.who?.id === id) this.send(s, this.hello(s));
351361 if (s.who?.owner) this.send(s, this.mutedList());
@@ -461,10 +471,11 @@ export class Lobby {
461471 }
462472
463473 private mutedList() {
464 return { type: "muted", muted: [...this.chat.muted].map(([id, name]) => ({ id, name })) };
474 return { type: "muted", muted: this.chat.mutedList() };
465475 }
466476
467477 private ping(): void {
478 this.mutesEnded();
468479 const now = Date.now();
469480 for (const s of this.seats) {
470481 if (now - s.heard > this.silentMs) s.ws.terminate(); // its close handler starts the grace period
@@ -472,6 +483,16 @@ export class Lobby {
472483 }
473484 }
474485
486 /** A mute that ran out is told to the person (their chat box comes back) and to the owners' list. */
487 private mutesEnded(): void {
488 const ended = this.chat.takeExpired();
489 if (!ended.length) return;
490 for (const s of this.seats) {
491 if (s.who && ended.includes(s.who.id)) this.send(s, this.hello(s));
492 if (s.who?.owner) this.send(s, this.mutedList());
493 }
494 }
495
475496 /** Up to `count` lines before the one with id `before` (all of them with no `before`), oldest first, and whether older ones remain. */
476497 private page(before: number | null, count: number) {
477498 const all = this.chat.messages;
Software/so101/src/terminal.test.ts +3 −1
@@ -80,7 +80,9 @@ describe("terminal lines", () => {
8080 expect(typed(room, "/end Bob")).toEqual({ send: { type: "end", id: "u-bob" } });
8181 expect(typed(room, "/mute alice")).toEqual({ send: { type: "mute", id: "u-alice", on: true } });
8282 expect(typed(room, "/unmute u-zed")).toEqual({ send: { type: "mute", id: "u-zed", on: false } });
83 expect(typed(room, "/mute")).toEqual({ print: "usage: /mute <name>" });
83 expect(typed(room, "/unmute alice 1h")).toEqual({ print: "usage: /unmute <name>" });
84 expect(typed(room, "/mute alice 1h")).toEqual({ send: { type: "mute", id: "u-alice", on: true, for: "1h" } });
85 expect(typed(room, "/mute")).toEqual({ print: "usage: /mute <name> [10m|1h|24h|forever]" });
8486 expect(typed(room, "/mute a.b!")).toEqual({ print: "error: who is a.b!?" });
8587 hear(room, { type: "said", message: { id: 7, from: { id: "u-alice", name: "alice" }, text: "hi" } });
8688 expect(typed(room, "/delete Alice")).toEqual({ send: { type: "delete", id: 7 } });
Software/so101/src/terminal.ts +8 −4
@@ -20,7 +20,7 @@
2020 * /stop the driver or an admin: halt the arm and hold it, whatever drives it, until /resume
2121 * /resume the driver or an admin: end the hold; the arm stays put until a new command
2222 * /end [who] owner: end that turn (none: whoever drives), or take them out of the line
23 * /mute <who> /unmute <who> owner
23 * /mute <who> [10m|1h|24h|forever] /unmute <who> owner
2424 * /delete <who|#id> owner or moderator: remove that person's latest chat line, or the line numbered #id (shown to those who may)
2525 * /table here admin: put the table under the arm's lowest link now (POST /settings/table-here)
2626 * /table <mm> admin: set the table offset, -100..100 mm (PUT /settings tableOffsetMm)
@@ -255,7 +255,9 @@ export function typed(room: Room, input: string): Typed {
255255 if (!line) return null;
256256 if (!line.startsWith("/")) return { send: { type: "post", text: line } };
257257 const [verb = "", arg = "", ...rest] = line.slice(1).split(/\s+/);
258 if (rest.length) return { print: `error: one name at a time` };
258 const timed = /^mute$/i.test(verb) && rest.length === 1 && /^(10m|1h|24h|forever)$/i.test(rest[0]!);
259 if (rest.length && !timed && /^unmute$/i.test(verb)) return { print: "usage: /unmute <name>" };
260 if (rest.length && !timed) return { print: `error: one name at a time` };
259261 switch (verb.toLowerCase()) {
260262 case "join":
261263 case "leave":
@@ -269,9 +271,11 @@ export function typed(room: Room, input: string): Typed {
269271 }
270272 case "mute":
271273 case "unmute": {
272 if (!arg) return { print: `usage: /${verb.toLowerCase()} <name>` };
274 const on = verb.toLowerCase() === "mute";
275 const span = timed ? rest[0]!.toLowerCase() : null;
outdated

const who = arg; is a redundant alias; use arg directly.

276 if (!arg) return { print: `usage: /${on ? "mute" : "unmute"} <name>${on ? " [10m|1h|24h|forever]" : ""}` };
273277 const id = target(room, arg);
274 return id ? { send: { type: "mute", id, on: verb.toLowerCase() === "mute" } } : { print: `error: who is ${plain(arg)}?` };
278 return id ? { send: span ? { type: "mute", id, on, for: span } : { type: "mute", id, on } } : { print: `error: who is ${plain(arg)}?` };
275279 }
276280 case "delete": {
277281 if (!arg) return { print: "usage: /delete <name> | /delete #<line number>" };
Software/so101/src/ui/lobby-panel.js +2 −2
@@ -128,7 +128,7 @@ export function createRoom(page) {
128128 $("pauseBtn").className = st.paused ? "go" : "";
129129 $("pauseBtn").onclick = () => say({ type: "pause", on: !st.paused });
130130 }
131 $("mutedLine").replaceChildren(...(me?.owner ? lobby.mutedList.map((m) => el("div", { className: "item" }, el("span", { textContent: `${m.name} is muted` }), button("Unmute", "", () => say({ type: "mute", id: m.id, on: false })))) : []));
131 $("mutedLine").replaceChildren(...(me?.owner ? lobby.mutedList.map((m) => el("div", { className: "item" }, el("span", { textContent: `${m.name} is muted ${m.until ? "until " + new Date(m.until).toLocaleString([], { dateStyle: "short", timeStyle: "short" }) : "for good"}` }), button("Unmute", "", () => say({ type: "mute", id: m.id, on: false })))) : []));
132132 $("bannedLine").replaceChildren(...(me?.owner ? lobby.bannedList.map((b) => el("div", { className: "item" }, el("span", { textContent: `${b.name} is banned` }), button("Unban", "", () => say({ type: "ban", id: b.id, on: false })))) : []));
133133 renderCrew(me);
134134 $("say").hidden = !me || lobby.hello.muted || lobby.hello.banned;
@@ -235,7 +235,7 @@ export function createRoom(page) {
235235 const line = held; held = null; line?.classList.remove("held");
236236 if (!line) return;
237237 if ($("modDlg").returnValue === "delete") say({ type: "delete", id: Number(line.dataset.id) });
238 if ($("modDlg").returnValue === "mute") say({ type: "mute", id: line.dataset.from, on: true });
238 if ($("modDlg").returnValue === "mute") say({ type: "mute", id: line.dataset.from, on: true, for: $("modFor").value });
239239 if ($("modDlg").returnValue === "ban" && confirm(`Ban ${line.dataset.name}? They can still watch, but nobody from their name, browser or address can chat or drive.`)) say({ type: "ban", id: line.dataset.from, on: true });
240240 });
241241 }
Software/so101/src/viewer.html +1
@@ -520,6 +520,7 @@
520520 <form method="dialog">
521521 <h3 id="modTitle">Message</h3>
522522 <p id="modText"></p>
523 <label class="inline">mute for <select id="modFor"><option value="10m">10 min</option><option value="1h">1 hour</option><option value="24h">24 hours</option><option value="forever" selected>for good</option></select></label>

This label stays visible to moderators, who cannot mute. Hide it with modMute in lobby-panel.js (line 224).

523524 <div class="actions"><button value="delete" class="danger">Delete message</button><button value="mute" class="danger" id="modMute">Mute</button><button value="ban" class="danger" id="modBan">Ban</button><button value="cancel">Cancel</button></div>
524525 </form>
525526 </dialog>

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs