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

A card someone moves appears for everyone within a second: one in-process bus and server-sent events #36

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/tempo:scout/12-a-card-someone-moves-appears-for-everyon → main 5 commits fork 3 threads · 3 unresolved

  • Merged. scout/12-a-card-someone-moves-appears-for-everyon was merged into main as 79c36dc.

Review

Sign in to review this change.
14 files changed +742 −212
README.md +23 −7
@@ -50,10 +50,22 @@ FORGE_APP_DATA=./data bun run src/tty.ts # the terminal interface
5050 - **Undo**: reverses the last change to the board — a create, edit,
5151 move, or delete of a card or column. It is a shared, board-wide undo
5252 (there's no per-person history), which fits a board anyone can edit.
53 - **Live**: `static/board.js` opens `/b/<id>/events` (server-sent
54 events); when someone else changes the board, your page quietly
55 refetches and swaps in the fresh columns — no reload, and a change
56 you just made yourself isn't re-applied a second time.
53 - **Live**: every write publishes one event on an in-process bus
54 (`src/bus.ts`), scoped to its board; `static/board.js` opens
55 `/b/<id>/events` (server-sent events) and applies each one — a card
56 or column that's added, moved, renamed or deleted lands in the right
57 spot within a second, counts stay current, and neither your scroll
58 position nor whatever you're mid-typing elsewhere on the page is
59 touched. A change you just made yourself isn't re-applied a second
60 time (the event echoes back your tab's own id, and your tab ignores
61 it). An edit or a rename you're in the middle of typing waits for a
62 conflicting live one until you're done, rather than overwriting it.
63 If the connection drops, the browser reconnects on its own; that
64 reconnect re-reads the whole board once to reconcile, rather than
65 trying to replay whatever was missed while it was down. Claiming a
66 board doesn't publish an event — "Kept by" is the one piece of board
67 state that only updates on next load, a deliberate narrowing (see
68 "What's simulated").
5769 - **Agents**: `POST /mcp` speaks MCP over plain JSON-RPC 2.0
5870 (`initialize`, `tools/list`, `tools/call`) with four tools —
5971 `list_boards`, `list_cards`, `add_card`, `move_card` — under the same
@@ -83,6 +95,9 @@ background, reverting if it fails.
8395 the server, so it can't be used to go discover a board by guessing.
8496 - Undo is board-wide, not per-visitor, and unaffected by who's signed
8597 in.
98 - Claiming a board publishes no live event — it isn't one of the kinds
99 in `src/bus.ts` — so another open tab's "Kept by" only catches up on
100 its next load, not live like everything else on the board.
86101 - The terminal (`src/tty.ts` draws it and reads keys, `src/keys.ts`
87102 decides what each key does, `src/session.ts` decides who is asking)
88103 mirrors the board actions with a letter-key scheme (`j/k/h/l` move,
@@ -157,9 +172,10 @@ same as an anonymous browser's.
157172 ## Dependencies
158173
159174 The app itself has none. `happy-dom` is a dev-only dependency, used by
160 `src/drag.test.ts`, `src/touch.test.ts` (and `src/theme.test.ts`,
161 `src/boards.test.ts`) to give `static/board.js` and `static/boards.js` a
162 real DOM outside a browser so their dragstart/dragover/drop/dragend,
175 `src/drag.test.ts`, `src/touch.test.ts`, `src/live-refresh.test.ts`,
176 `src/theme.test.ts` and `src/boards.test.ts` to give `static/board.js`
177 and `static/boards.js` a real DOM outside a browser so their event
178 handlers, dragstart/dragover/drop/dragend/EventSource handling,
163179 pointerdown/pointermove/pointerup, and `localStorage` calls run against
164180 the real thing — hand-rolling that much of the DOM to test a few dozen
165181 lines of script would be more code, and less trustworthy, than the
src/bus.test.ts added +46
@@ -0,0 +1,46 @@
1 import { expect, test } from "bun:test";
2 import { publish, subscribe, subscriberCount } from "./bus.ts";
3
4 const event = (boardId: string, cardId = "c1") => ({
5 kind: "card.added" as const,
6 boardId,
7 by: null,
8 client: null,
9 ids: { cardId },
10 });
11
12 test("two subscribers on one board both receive a publish", () => {
13 const heard: unknown[] = [];
14 const stop1 = subscribe("board-a", (e) => heard.push(["one", e]));
15 const stop2 = subscribe("board-a", (e) => heard.push(["two", e]));
16 publish("board-a", event("board-a"));
17 expect(heard).toEqual([
18 ["one", event("board-a")],
19 ["two", event("board-a")],
20 ]);
21 stop1();
22 stop2();
23 });
24
25 test("a subscriber on another board receives nothing", () => {
26 const heard: unknown[] = [];
27 const stop = subscribe("board-b", (e) => heard.push(e));
28 publish("board-c", event("board-c"));
29 expect(heard).toEqual([]);
30 stop();
31 });
32
33 test("unsubscribe drops the listener", () => {
34 const heard: unknown[] = [];
35 const stop = subscribe("board-d", (e) => heard.push(e));
36 stop();
37 publish("board-d", event("board-d"));
38 expect(heard).toEqual([]);
39 });
40
41 test("unsubscribing leaves no listener behind", () => {
42 const stop = subscribe("board-e", () => {});
43 expect(subscriberCount("board-e")).toBe(1);
44 stop();
45 expect(subscriberCount("board-e")).toBe(0);
46 });
src/bus.ts added +50
@@ -0,0 +1,50 @@
1 /**
2 * One in-process bus, scoped per board. A mutation calls `publish(boardId,
3 * event)`; every open `/b/:id/events` stream on that same board calls
4 * `subscribe(boardId, fn)` to hear it. Plain data in, plain data out — this
5 * module knows nothing about SQLite, HTTP or SSE, only who is listening.
6 */
7
8 export type EventKind =
9 | "card.added"
10 | "card.moved"
11 | "card.edited"
12 | "card.deleted"
13 | "column.added"
14 | "column.renamed"
15 | "column.moved"
16 | "column.deleted"
17 | "board.renamed"
18 | "undo";
19
20 export type BoardEvent = {
21 readonly kind: EventKind;
22 readonly boardId: string;
23 /** Who made the change, from who() — null for an anonymous guest or the terminal/MCP. */
24 readonly by: { id: string; name: string } | null;
25 /** The tab that made the change, so it can ignore its own echo — null when there is none. */
26 readonly client: string | null;
27 /** The ids (and any other small facts) a listener needs to apply this event. */
28 readonly ids: Readonly<Record<string, string>>;
29 };
30
31 const boards = new Map<string, Set<(event: BoardEvent) => void>>();
32
33 export function publish(boardId: string, event: BoardEvent): void {
34 for (const listen of boards.get(boardId) ?? []) listen(event);
35 }
36
37 export function subscribe(boardId: string, fn: (event: BoardEvent) => void): () => void {
38 let listeners = boards.get(boardId);
39 if (!listeners) boards.set(boardId, (listeners = new Set()));
40 listeners.add(fn);
41 return () => {
42 listeners.delete(fn);
43 if (listeners.size === 0) boards.delete(boardId);
44 };
45 }
46
47 /** How many tabs are currently listening on a board — used to cap fan-out per board. */
48 export function subscriberCount(boardId: string): number {
49 return boards.get(boardId)?.size ?? 0;
50 }
src/drag.test.ts +6
@@ -19,8 +19,14 @@ process.env.FORGE_APP_DATA = mkdtempSync(join(tmpdir(), "app-"));
1919 process.env.PORT = "0";
2020 process.env.FORGE_APP_IDENTITY_KEY = "test-key";
2121 const { server } = await import("./server.ts");
22 const { boardCreationBucket } = await import("./limits.ts");
2223 const base = `http://${server.hostname}:${server.port}`;
2324
25 // boardCreationBucket is one process-wide bucket; reset it so this file's
26 // own board-creation calls aren't at the mercy of what other test files
27 // already spent from it in this same `bun test` run.
28 boardCreationBucket.reset();
29
2430 const post = (path: string, body: Record<string, string> = {}) =>
2531 fetch(base + path, { method: "POST", body: new URLSearchParams(body) });
2632
src/limits.ts +17
@@ -24,6 +24,11 @@ export const MAX_BOARDS_CREATED_PER_MINUTE = 30;
2424 // giant upload can't be used to exhaust memory parsing it.
2525 export const MAX_REQUEST_BODY_BYTES = 64 * 1024;
2626
27 // A board with more open /events tabs than this refuses the next one, not
28 // this one in particular — a runaway number of tabs on one board is a
29 // leak, not a feature, and every existing tab keeps working either way.
30 export const MAX_SUBSCRIBERS_PER_BOARD = 100;
31
2732 /**
2833 * A token bucket: `capacityPerMinute` tokens to start, refilled at
2934 * `capacityPerMinute` per minute, never exceeding that capacity. It is a
@@ -66,6 +71,18 @@ export class TokenBucket {
6671 if (missing <= 0) return 0;
6772 return Math.max(1, Math.ceil((missing / this.capacityPerMinute) * 60));
6873 }
74
75 /**
76 * Back to full capacity. Not used by the app itself — only by a test file
77 * that posts to `/boards` enough times to matter, so the process-wide
78 * `boardCreationBucket` (shared across every test file in one `bun test`
79 * run) starts each file with its own full bucket instead of running down
80 * against whatever earlier files already spent.
81 */
82 reset(): void {
83 this.tokens = this.capacityPerMinute;
84 this.last = this.now();
85 }
6986 }
7087
7188 // One bucket for the whole process — see the class comment on why it is
src/live-refresh.test.ts +122 −51
@@ -1,9 +1,8 @@
11 /**
2 * Drives static/board.js's live-refresh path the way a browser would: a
3 * fake EventSource delivers another tab's write, and the guard that
4 * decides whether to redraw `.board` right away is checked against the
5 * two things that must survive it — an input mid-word, and keyboard focus
6 * on a card.
2 * Drives static/board.js's live-apply path the way a browser would: a fake
3 * EventSource delivers another tab's bus event, and each kind is checked
4 * against the two things it must not disturb — an input mid-word, and
5 * keyboard focus on a card — while still landing in the right place.
76 *
87 * happy-dom has no EventSource or DOMParser of its own recent enough for
98 * this; both are supplied on globalThis for the duration of the test,
@@ -20,28 +19,22 @@ process.env.FORGE_APP_DATA = mkdtempSync(join(tmpdir(), "app-"));
2019 process.env.PORT = "0";
2120 process.env.FORGE_APP_IDENTITY_KEY = "test-key";
2221 const { server } = await import("./server.ts");
22 const { boardCreationBucket } = await import("./limits.ts");
2323 const base = `http://${server.hostname}:${server.port}`;
2424
25 // boardCreationBucket is one process-wide bucket; reset it so this file's
26 // own board-creation calls aren't at the mercy of what other test files
27 // already spent from it in this same `bun test` run.
28 boardCreationBucket.reset();
29
2530 const post = (path: string, body: Record<string, string> = {}) =>
26 fetch(base + path, { method: "POST", body: new URLSearchParams(body) });
31 fetch(base + path, { method: "POST", headers: { accept: "application/json" }, body: new URLSearchParams(body) });
2732
28 /**
29 * A refresh is a fetch and a parse, so it lands a turn or several of the
30 * event loop later — how many depends on the machine. Waiting for what the
31 * refresh does, rather than for a number of milliseconds, keeps the test
32 * about behaviour instead of about how fast the box is.
33 */
34 async function waitFor(condition: () => boolean, what: string): Promise<void> {
35 const deadline = Date.now() + 5000;
36 while (!condition()) {
37 if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`);
38 await new Promise((resolve) => setTimeout(resolve, 5));
39 }
33 async function newBoard(name = "Live test"): Promise<string> {
34 const created = await post("/boards", { name });
35 return new URL(created.url).pathname.split("/")[2];
4036 }
4137
42 /** Long enough that a refresh would have landed, for asserting one has not. */
43 const settle = () => new Promise((resolve) => setTimeout(resolve, 100));
44
4538 let restoreEventSource: (() => void) | undefined;
4639 let restoreDOMParser: (() => void) | undefined;
4740 beforeEach(() => {
@@ -61,13 +54,14 @@ afterEach(() => {
6154
6255 class FakeEventSource {
6356 onmessage: ((message: { data: string }) => void) | null = null;
57 onopen: (() => void) | null = null;
6458 constructor(_url: string) {
6559 latestSource = this;
6660 }
6761 }
6862 let latestSource: FakeEventSource | undefined;
6963
70 async function run(boardId: string): Promise<{ window: Window; document: Document }> {
64 async function run(boardId: string, onFetch?: (path: string, init: RequestInit) => void): Promise<{ window: Window; document: Document }> {
7165 const html = await (await fetch(`${base}/b/${boardId}`)).text();
7266 const [, scriptSrc] = html.match(/<script src="(\/static\/board[^"]+)"/)!;
7367 const script = await (await fetch(base + scriptSrc)).text();
@@ -83,7 +77,10 @@ async function run(boardId: string): Promise<{ window: Window; document: Documen
8377
8478 new Function("document", "fetch", "location", "history", "CSS", script)(
8579 document,
86 (path: string, init: RequestInit) => fetch(new URL(path, base), init),
80 (path: string, init: RequestInit) => {
81 onFetch?.(path, init);
82 return fetch(new URL(path, base), init);
83 },
8784 window.location,
8885 window.history,
8986 window.CSS,
@@ -91,38 +88,32 @@ async function run(boardId: string): Promise<{ window: Window; document: Documen
9188 return { window, document };
9289 }
9390
94 test("a live refresh does not wipe an in-progress add-card title", async () => {
95 const created = await post("/boards", { name: "Live refresh test" });
96 const boardId = new URL(created.url).pathname.split("/")[2];
91 function deliver(event: unknown): void {
92 latestSource!.onmessage!({ data: JSON.stringify(event) });
93 }
94
95 test("a card added elsewhere appears right away and does not disturb an in-progress add-card title", async () => {
96 const boardId = await newBoard();
9797 const { window, document } = await run(boardId);
98 const columnId = document.querySelector("[data-column-id]")!.getAttribute("data-column-id")!;
9899
99100 const addInput = document.querySelector(".add-card input") as unknown as HTMLInputElement;
100101 addInput.focus();
101102 addInput.value = "half-typed";
102103
103 // Someone else moves a card while this tab is mid-type.
104 await post(`/b/${boardId}/columns/${document.querySelector("[data-column-id]")!.getAttribute("data-column-id")}/cards`, {
105 title: "From elsewhere",
106 });
107 const hasNewCard = () => document.querySelector('.card[data-title="From elsewhere"]') !== null;
108
109 latestSource!.onmessage!({ data: JSON.stringify({ by: "someone-else" }) });
110 await settle();
104 const created = await post(`/b/${boardId}/columns/${columnId}/cards`, { title: "From elsewhere" });
105 const { id: cardId } = (await created.json()) as { id: string };
106 deliver({ kind: "card.added", boardId, by: null, client: "someone-else", ids: { columnId, cardId } });
107 await new Promise((resolve) => setTimeout(resolve, 20));
111108
112109 expect((document.querySelector(".add-card input") as unknown as HTMLInputElement).value).toBe("half-typed");
113 expect(hasNewCard()).toBe(false);
114
115 // Leaving the input lets the deferred refresh through.
116 addInput.blur();
117 await waitFor(hasNewCard, "the deferred refresh to bring in the other tab's card");
118 expect(hasNewCard()).toBe(true);
110 expect(document.querySelector('.card[data-title="From elsewhere"]')).not.toBeNull();
119111
120112 await window.close();
121113 });
122114
123 test("a live refresh restores focus to a keyboard-focused card instead of deferring", async () => {
124 const created = await post("/boards", { name: "Live refresh focus test" });
125 const boardId = new URL(created.url).pathname.split("/")[2];
115 test("a live move restores focus to a keyboard-focused card instead of losing it", async () => {
116 const boardId = await newBoard();
126117 const columnId = (await (await fetch(`${base}/b/${boardId}`)).text()).match(/data-column-id="([a-z0-9]{12})"/)![1];
127118 await post(`/b/${boardId}/columns/${columnId}/cards`, { title: "Keep focused" });
128119 const { window, document } = await run(boardId);
@@ -131,16 +122,96 @@ test("a live refresh restores focus to a keyboard-focused card instead of deferr
131122 card.focus();
132123 const cardId = card.dataset.cardId;
133124
134 await post(`/b/${boardId}/columns/${columnId}/cards`, { title: "From elsewhere" });
135 latestSource!.onmessage!({ data: JSON.stringify({ by: "someone-else" }) });
136 await waitFor(
137 () => document.querySelector('.card[data-title="From elsewhere"]') !== null,
138 "the refresh to bring in the other tab's card",
139 );
125 const created = await post(`/b/${boardId}/columns/${columnId}/cards`, { title: "From elsewhere" });
126 const { id: newCardId } = (await created.json()) as { id: string };
127 deliver({ kind: "card.added", boardId, by: null, client: "someone-else", ids: { columnId, cardId: newCardId } });
128 await new Promise((resolve) => setTimeout(resolve, 20));
140129
141130 expect(document.querySelector('.card[data-title="From elsewhere"]')).not.toBeNull();
142 const refocused = document.querySelector(`[data-card-id="${cardId}"]`);
143 expect(refocused).toBe(document.activeElement as unknown as Element);
131 expect(document.querySelector(`[data-card-id="${cardId}"]`)).toBe(document.activeElement as unknown as Element);
132
133 await window.close();
134 });
135
136 test("editing a card waits out a conflicting live edit of that same card, then applies it", async () => {
137 const boardId = await newBoard();
138 const columnId = (await (await fetch(`${base}/b/${boardId}`)).text()).match(/data-column-id="([a-z0-9]{12})"/)![1];
139 const created = await post(`/b/${boardId}/columns/${columnId}/cards`, { title: "Original" });
140 const { id: cardId } = (await created.json()) as { id: string };
141 const { window, document } = await run(boardId);
142
143 const editInput = document.querySelector(".card .edit input") as unknown as HTMLInputElement;
144 editInput.focus();
145 editInput.value = "my unsaved edit";
146
147 await post(`/b/${boardId}/cards/${cardId}`, { title: "Changed elsewhere" });
148 deliver({ kind: "card.edited", boardId, by: null, client: "someone-else", ids: { cardId } });
149 await new Promise((resolve) => setTimeout(resolve, 20));
150 expect(editInput.value).toBe("my unsaved edit");
151
152 editInput.blur();
153 await new Promise((resolve) => setTimeout(resolve, 20));
154 expect((document.querySelector(".card .edit input") as unknown as HTMLInputElement).value).toBe("Changed elsewhere");
155
156 await window.close();
157 });
158
159 test("this tab's own write is not re-applied when its echo comes back over the stream", async () => {
160 const boardId = await newBoard();
161 const columnId = (await (await fetch(`${base}/b/${boardId}`)).text()).match(/data-column-id="([a-z0-9]{12})"/)![1];
162 const keepId = (await (await post(`/b/${boardId}/columns/${columnId}/cards`, { title: "Keep" })).json()).id as string;
163 const otherId = (await (await post(`/b/${boardId}/columns/${columnId}/cards`, { title: "Other" })).json()).id as string;
164
165 let clientId: string | undefined;
166 const { window, document } = await run(boardId, (_path, init) => {
167 const headers = init.headers as Record<string, string> | undefined;
168 clientId ??= headers?.["x-tempo-client"];
169 });
170
171 // A delete form has no named field, so submitting it in happy-dom doesn't
172 // need the named-form-control access the edit/move forms rely on.
173 const deleteForm = document.querySelector(`.card[data-card-id="${keepId}"] .delete`)!;
174 deleteForm.dispatchEvent(new window.Event("submit", { bubbles: true, cancelable: true }));
175 await new Promise((resolve) => setTimeout(resolve, 20));
176 expect(clientId).toBeTruthy();
177 expect(document.querySelector(`.card[data-card-id="${keepId}"]`)).toBeNull();
178
179 // This tab's own delete echoes back over the stream with this tab's own
180 // client id; a second, unrelated card's deletion must still be ignored
181 // when it wrongly carries that same id, and applied when it doesn't.
182 deliver({ kind: "card.deleted", boardId, by: null, client: clientId, ids: { cardId: otherId } });
183 await new Promise((resolve) => setTimeout(resolve, 20));
184 expect(document.querySelector(`.card[data-card-id="${otherId}"]`)).not.toBeNull();
185
186 deliver({ kind: "card.deleted", boardId, by: null, client: "a-different-tab", ids: { cardId: otherId } });
187 await new Promise((resolve) => setTimeout(resolve, 20));
188 expect(document.querySelector(`.card[data-card-id="${otherId}"]`)).toBeNull();
189
190 await window.close();
191 });
192
193 test("a column added or deleted elsewhere updates every card's Move to column dropdown, not just column.renamed", async () => {
194 const boardId = await newBoard();
195 const columnId = (await (await fetch(`${base}/b/${boardId}`)).text()).match(/data-column-id="([a-z0-9]{12})"/)![1];
196 await post(`/b/${boardId}/columns/${columnId}/cards`, { title: "Has a Move to dropdown" });
197 const { window, document } = await run(boardId);
198 const optionValues = () =>
199 Array.from(document.querySelectorAll("select[name=column_id]")).map((select) =>
200 Array.from((select as unknown as HTMLSelectElement).options).map((o) => o.value),
201 );
202
203 const created = await post(`/b/${boardId}/columns`, { name: "Blocked" });
204 const { id: newColumnId } = (await created.json()) as { id: string };
205 deliver({ kind: "column.added", boardId, by: null, client: "someone-else", ids: { columnId: newColumnId } });
206 await new Promise((resolve) => setTimeout(resolve, 20));
207 for (const values of optionValues()) expect(values).toContain(newColumnId);
208 const addedOption = document.querySelector(`select[name=column_id] option[value="${newColumnId}"]`)!;
209 expect(addedOption.textContent).toBe("Blocked");
210
211 await post(`/b/${boardId}/columns/${newColumnId}/delete`);
212 deliver({ kind: "column.deleted", boardId, by: null, client: "someone-else", ids: { columnId: newColumnId } });
213 await new Promise((resolve) => setTimeout(resolve, 20));
214 for (const values of optionValues()) expect(values).not.toContain(newColumnId);
144215
145216 await window.close();
146217 });
src/live.ts deleted −73
@@ -1,73 +0,0 @@
1 /**
2 * Realtime without a framework. A mutation calls `touch(boardId, by)`;
3 * `GET /b/:id/events` streams that to every open page on the same board as
4 * server-sent events, numbered, with the last hundred kept so a client that
5 * reconnects (the browser sends `Last-Event-ID` automatically) hears what
6 * it missed. `by` is the client that made the change, so its own page can
7 * skip re-fetching what it already applied optimistically.
8 */
9
10 export interface LiveEvent {
11 readonly id: number;
12 readonly boardId: string;
13 readonly by: string | null;
14 }
15
16 const KEEP = 100;
17 const HEARTBEAT_MS = 25_000;
18 const kept: LiveEvent[] = [];
19 const listeners = new Set<(event: LiveEvent) => void>();
20 let last = 0;
21
22 export function touch(boardId: string, by: string | null): LiveEvent {
23 const event: LiveEvent = { id: ++last, boardId, by };
24 kept.push(event);
25 if (kept.length > KEEP) kept.shift();
26 for (const listen of listeners) listen(event);
27 return event;
28 }
29
30 export function subscribe(listen: (event: LiveEvent) => void): () => void {
31 listeners.add(listen);
32 return () => listeners.delete(listen);
33 }
34
35 /** `GET /b/:id/events`: a stream scoped to one board, replaying what `since` missed. */
36 export function events(boardId: string, request: Request): Response {
37 const since = Number(request.headers.get("last-event-id") ?? new URL(request.url).searchParams.get("since") ?? 0);
38 const encoder = new TextEncoder();
39 let stop = (): void => {};
40 const stream = new ReadableStream<Uint8Array>({
41 start(controller) {
42 const write = (text: string): void => {
43 try {
44 controller.enqueue(encoder.encode(text));
45 } catch {
46 stop();
47 }
48 };
49 const send = (event: LiveEvent): void => {
50 if (event.boardId !== boardId) return;
51 write(`id: ${event.id}\ndata: ${JSON.stringify({ by: event.by })}\n\n`);
52 };
53 const heartbeat = setInterval(() => write(":\n\n"), HEARTBEAT_MS);
54 const unsubscribe = subscribe(send);
55 stop = () => {
56 clearInterval(heartbeat);
57 unsubscribe();
58 try {
59 controller.close();
60 } catch {}
61 };
62 request.signal.addEventListener("abort", stop);
63 write("retry: 2000\n\n");
64 for (const event of kept) if (event.id > since) send(event);
65 },
66 cancel() {
67 stop();
68 },
69 });
70 return new Response(stream, {
71 headers: { "content-type": "text/event-stream", "cache-control": "no-store", "x-accel-buffering": "no" },
72 });
73 }
src/mcp.ts +10 −5
@@ -8,11 +8,16 @@
88 * take a board id directly, exactly like the page and the JSON forms do.
99 */
1010
11 import * as bus from "./bus.ts";
1112 import * as db from "./db.ts";
12 import { touch } from "./live.ts";
1313 import { MAX_CARDS_PER_BOARD } from "./limits.ts";
1414 import type { Who } from "./who.ts";
1515
16 // An agent has no tab of its own, so there is nothing to echo-suppress.
17 function publish(boardId: string, who: Who, kind: bus.EventKind, ids: Record<string, string>): void {
18 bus.publish(boardId, { kind, boardId, by: who.role === "anon" ? null : { id: who.id, name: who.name }, client: null, ids });
19 }
20
1621 const BOARD_ID = /^[a-z0-9]{8}$/;
1722 const ENTITY_ID = /^[a-z0-9]{12}$/;
1823
@@ -57,7 +62,7 @@ export const tools: readonly Tool[] = [
5762 properties: { board_id: { type: "string" }, column_id: { type: "string" }, title: { type: "string", maxLength: 200 } },
5863 required: ["board_id", "column_id", "title"],
5964 },
60 run: (_who, args) => {
65 run: (who, args) => {
6166 const board = boardOf(args);
6267 if (!board) return fail("not_found", "no such board");
6368 const columnId = String(args.column_id ?? "");
@@ -67,7 +72,7 @@ export const tools: readonly Tool[] = [
6772 const card = db.createCard(board.id, columnId, title);
6873 if (card === "not_found") return fail("not_found", "no such column");
6974 if (card === "full") return fail("full", `this board is full — ${MAX_CARDS_PER_BOARD} cards`);
70 touch(board.id, null);
75 publish(board.id, who, "card.added", { columnId, cardId: card.id });
7176 return ok(card);
7277 },
7378 },
@@ -84,7 +89,7 @@ export const tools: readonly Tool[] = [
8489 },
8590 required: ["board_id", "card_id", "column_id"],
8691 },
87 run: (_who, args) => {
92 run: (who, args) => {
8893 const board = boardOf(args);
8994 if (!board) return fail("not_found", "no such board");
9095 const cardId = String(args.card_id ?? "");
@@ -94,7 +99,7 @@ export const tools: readonly Tool[] = [
9499 if (!Number.isFinite(index) || index < 0) return fail("invalid", "index must be a non-negative number");
95100 const moved = db.moveCard(board.id, cardId, columnId, Math.floor(index));
96101 if (!moved) return fail("not_found", "no such card or column");
97 touch(board.id, null);
102 publish(board.id, who, "card.moved", { cardId, columnId });
98103 return ok({ id: cardId });
99104 },
100105 },
src/pages/board.ts +1 −1
@@ -278,6 +278,6 @@ const boardShortcuts: [string, string][] = [
278278
279279 // Named by content — a change to static/board.js gets a new hash here,
280280 // so the year-long cache on /static/ never serves a stale script.
281 export const BOARD_JS = "board.7793265334.js";
281 export const BOARD_JS = "board.109353762.js";
282282 export const THEME_JS = "theme.1025564933.js";
283283 export const BOARDS_JS = "boards.608180649.js";
src/routes.ts +95 −20
@@ -4,9 +4,10 @@
44 * not own, so server.ts can fall through to static files and 404.
55 */
66
7 import * as bus from "./bus.ts";
8 import type { EventKind } from "./bus.ts";
79 import * as db from "./db.ts";
8 import { boardCreationBucket, MAX_CARDS_PER_BOARD, MAX_COLUMNS_PER_BOARD } from "./limits.ts";
9 import * as live from "./live.ts";
10 import { boardCreationBucket, MAX_CARDS_PER_BOARD, MAX_COLUMNS_PER_BOARD, MAX_SUBSCRIBERS_PER_BOARD } from "./limits.ts";
1011 import { rpc } from "./mcp.ts";
1112 import { boardPage, landingPage } from "./pages/board.ts";
1213 import type { Who } from "./who.ts";
@@ -14,12 +15,23 @@ import type { Who } from "./who.ts";
1415 const BOARD_ID = /^[a-z0-9]{8}$/;
1516 const ENTITY_ID = /^[a-z0-9]{12}$/;
1617
17 // The client that made a write, so its own tab can skip re-fetching a
18 // The client that made a write, so its own tab can ignore the echo of a
1819 // live event it already applied optimistically. Purely informational —
19 // nothing here trusts it for anything but avoiding a redundant refetch.
20 // nothing here trusts it for anything but that.
2021 const CLIENT_HEADER = "x-tempo-client";
21 const touch = (boardId: string, request: Request): void =>
22 live.touch(boardId, request.headers.get(CLIENT_HEADER)?.slice(0, 64) ?? null);
22
23 // Every write that changes a board publishes exactly one event, after the
24 // write has committed — publishing before that would show a change that
25 // might still roll back.
26 function publish(boardId: string, request: Request, who: Who, kind: EventKind, ids: Record<string, string> = {}): void {
27 bus.publish(boardId, {
28 kind,
29 boardId,
30 by: who.role === "anon" ? null : { id: who.id, name: who.name },
31 client: request.headers.get(CLIENT_HEADER)?.slice(0, 64) ?? null,
32 ids,
33 });
34 }
2335
2436 // Pages carry a visitor's name and sign-out link once they're signed in, so
2537 // nothing in front of us — a shared cache, a back-forward cache on a shared
@@ -59,8 +71,16 @@ function done(request: Request, boardId: string, ok: boolean, extra: Record<stri
5971 return ok ? Response.redirect(`/b/${boardId}`, 303) : new Response("not found", { status: 404 });
6072 }
6173 // Every other page on this board hears about a write that actually happened.
62 function doneTouch(request: Request, boardId: string, ok: boolean, extra: Record<string, unknown> = {}): Response {
63 if (ok) touch(boardId, request);
74 function donePublish(
75 request: Request,
76 who: Who,
77 boardId: string,
78 ok: boolean,
79 kind: EventKind,
80 ids: Record<string, string> = {},
81 extra: Record<string, unknown> = {},
82 ): Response {
83 if (ok) publish(boardId, request, who, kind, ids);
6484 return done(request, boardId, ok, extra);
6585 }
6686
@@ -100,6 +120,51 @@ async function form(request: Request): Promise<FormData> {
100120 return request.formData();
101121 }
102122
123 // A connection idle for 60s is dropped (server.ts); a comment every 25s
124 // keeps every open tab well inside that.
125 const HEARTBEAT_MS = 25_000;
126
127 /** `GET /b/:id/events`: one board's changes, as they are published. */
128 function eventStream(boardId: string, request: Request): Response {
129 if (bus.subscriberCount(boardId) >= MAX_SUBSCRIBERS_PER_BOARD) return new Response("too many open tabs on this board", { status: 503 });
130 const encoder = new TextEncoder();
131 let stop = (): void => {};
132 const stream = new ReadableStream<Uint8Array>({
133 start(controller) {
outdated

Round two, and nothing from the last review was addressed: between 661ffd7 and this head the only changes to this pull's own files are the merge of main plus nine lines of static/board.js and four of src/mcp.ts. Both findings still reproduce on the preview at this commit. What works still works — I re-ran the branch (bun test: 104 pass, 0 fail) and on the preview a card added from a plain POST and a card added from POST /mcp tools/call each arrived on an open /events stream within a second, correctly scoped, with the security floor and cache-control: no-store; /events 404s an unknown board; the per-board unsubscribe is clean. src/bus.ts is the right shape and no board content crosses the bus.

1 (high, fix first, unchanged from last round): HEAD /b/<id>/events never answers, and each one holds a subscriber slot. On the preview at this head, a minute ago:

curl -sI --max-time 15 .../b/j5ome7ax        -> 200 in 0.17s
curl -sI --max-time 15 .../b/j5ome7ax/events -> no response, client gives up at 15s

And run against this branch locally, with subscriberCount imported: while one HEAD is open the fetch promise has not settled and subscriberCount(boardId) is 1; it drops back to 0 only when the client goes away. The cause is src/server.ts:89-93 — a HEAD is routed as a GET and then await response.arrayBuffer(), which for an endless stream never settles. So 100 unauthenticated one-line HEADs held open make eventStream answer 503 to every real tab on that board, and per the HTML spec a browser does not reconnect after a non-200 SSE response: those tabs stay dead until someone reloads. An uptime check or a crawler that sends HEAD does it by accident, and the cap this pull adds is what turns the old hang into everyone's problem.

Fix, in src/server.ts before line 90: if the routed response has no known length — response.headers.get("content-type")?.startsWith("text/event-stream") is a fine narrow test — cancel the body and return new Response(null, { status: response.status, headers }) instead of buffering it. Cover it with a test that HEAD /b/<id>/events answers promptly and leaves subscriberCount(boardId) at 0. While you are there, consider dropping the oldest subscriber instead of refusing the newest, so one actor degrades their own tab rather than the board's.

2 (medium, unchanged from last round): the stream hands a signed-in person's forge user id and name to every link-holder, and nothing reads it. src/bus.ts:24, the publish helper in src/routes.ts:26 and the one in src/mcp.ts:16 put by: { id, name } on the wire for every event; static/board.409682029.js only ever reads event.client and event.kind/event.ids — by appears nowhere in it. The page names exactly one person, the owner. So today anyone holding a board link can sit on /events and harvest the forge id and display name of every signed-in person who touches that board. Keep the field in BoardEvent if you want it for later, but do not serialize the id to subscribers: one line in eventStream's send, sending { name } at most, and ideally nothing until the page shows it.

3 (medium, new): MAX_BOARDS_CREATED_PER_MINUTE was raised 30 → 40 with no reason given, and the reason is the test suite. The pull body does not mention it; the README diff just changes the number. Put it back to 30 on this branch and three tests fail — both new live-refresh.test.ts cases and drag.test.ts — not with a clear message but with TypeError: null is not an object, because the 429 page has no data-column-id in it. A safety limit should not be sized by the test count, and the next test that creates a board breaks the suite the same confusing way. Fix: restore 30 (and the README line) and give the tests their own bucket — export a reset on boardCreationBucket, or build it from an injected clock the tests advance.

4 (medium, new): two new behaviours have no test. MAX_SUBSCRIBERS_PER_BOARD / the 503 is new and nothing covers it, though the issue named the cap as a risk; and src/mcp.ts now publishes, which is the direction's headline ("two people and one agent"), yet deleting both publish(...) calls would keep the suite green — I had to check it by hand on the preview. Two tests: the 101st stream is refused and closing one frees a slot; tools/call add_card over POST /mcp produces a card.added frame on an open stream.

5 (low, new): events apply concurrently, so a burst can land a card in the wrong place. apply() calls applyNow(event) without awaiting, and pending.splice(0).forEach(applyNow) does the same, while every non-delete event does its own full freshBoard() fetch. Two quick moves of one card race, and whichever fetch resolves last writes the position from whichever render it happened to get; the board then drifts until a reconnect. Chain them through one promise queue (queue = queue.then(() => applyNow(event))) and let events arriving together share one in-flight fetch — that also cuts the one-write-to-one-render-per-tab fan-out.

Not for this pull, but please open the issue: a card moved in src/tty.ts still reaches no one, because the tty is a separate process and an in-process bus cannot see it — the bar is that both doors behave alike, so say it in the README next to the Live section as a known gap and file the follow-up (the tty publishing through the app, or a change counter the web process polls). Also still open from last round, all small: clientId = Math.random()... is guessable and your own test shows what that buys an attacker (crypto.randomUUID() costs nothing); pending grows unbounded while an input stays focused; column.added/column.deleted do not update the per-card "Move to column" options although column.renamed does; column.renamed's freshColumn.querySelector("header form.rename input").value is not null-guarded like its siblings; and the dropped claim event means "kept by" goes stale for other viewers — fine as a narrowing, but it belongs in the README, not only in the pull body.

Fix the HEAD hang and drop the forge id from the wire and I will approve; if the rest cannot land this round, open issues for them rather than carrying them silently.

134 const write = (text: string): void => {
135 try {
136 controller.enqueue(encoder.encode(text));
137 } catch {
138 stop();
139 }
140 };
141 // `by` (a signed-in editor's forge id and display name) is for a
142 // future "last edited by" on the page — not for the wire. Nothing
143 // in static/board.js reads it today, so sending it would let anyone
144 // holding a board's link sit on this stream and harvest the id and
145 // name of every signed-in person who touches it.
146 const send = ({ by: _by, ...wire }: bus.BoardEvent): void => write(`data: ${JSON.stringify(wire)}\n\n`);
147 const heartbeat = setInterval(() => write(":\n\n"), HEARTBEAT_MS);
148 const unsubscribe = bus.subscribe(boardId, send);
149 stop = () => {
150 clearInterval(heartbeat);
151 unsubscribe();
152 try {
153 controller.close();
154 } catch {}
155 };
156 request.signal.addEventListener("abort", stop);
157 write("retry: 2000\n\n");
158 },
159 cancel() {
160 stop();
161 },
162 });
163 return new Response(stream, {
164 headers: { "content-type": "text/event-stream", "cache-control": "no-store", "x-accel-buffering": "no" },
165 });
166 }
167
103168 export async function route(request: Request, url: URL, env: string, who: Who): Promise<Response | undefined> {
104169 try {
105170 return await dispatch(request, url, env, who);
@@ -170,7 +235,7 @@ async function dispatch(request: Request, url: URL, env: string, who: Who): Prom
170235
171236 if (method === "GET" && parts.length === 3 && parts[2] === "events") {
172237 if (!db.getBoard(boardId)) return new Response("board not found", { status: 404 });
173 return live.events(boardId, request);
238 return eventStream(boardId, request);
174239 }
175240
176241 if (!db.getBoard(boardId)) return new Response("board not found", { status: 404 });
@@ -179,7 +244,6 @@ async function dispatch(request: Request, url: URL, env: string, who: Who): Prom
179244 if (who.role === "anon") return new Response("sign in to keep a board", { status: 401 });
180245 const result = db.claimBoard(boardId, { id: who.id, name: who.name });
181246 if (result === "owned_by_other") return new Response("already kept by someone else", { status: 403 });
182 if (result === "claimed") touch(boardId, request);
183247 return done(request, boardId, true);
184248 }
185249
@@ -188,11 +252,11 @@ async function dispatch(request: Request, url: URL, env: string, who: Who): Prom
188252 const name = cleanText(data.get("name"), 100);
189253 if (!name) return boardBad(request, who, boardId, "a board needs a name");
190254 db.renameBoard(boardId, name);
191 return doneTouch(request, boardId, true);
255 return donePublish(request, who, boardId, true, "board.renamed");
192256 }
193257
194258 if (method === "POST" && parts.length === 3 && parts[2] === "undo") {
195 return doneTouch(request, boardId, db.undo(boardId));
259 return donePublish(request, who, boardId, db.undo(boardId), "undo");
196260 }
197261
198262 if (method === "POST" && parts.length === 3 && parts[2] === "columns") {
@@ -201,7 +265,7 @@ async function dispatch(request: Request, url: URL, env: string, who: Who): Prom
201265 if (!name) return boardBad(request, who, boardId, "a column needs a name");
202266 const column = db.createColumn(boardId, name);
203267 if (column === "full") return boardBad(request, who, boardId, `this board is full — ${MAX_COLUMNS_PER_BOARD} columns`);
204 return doneTouch(request, boardId, true, { id: column.id });
268 return donePublish(request, who, boardId, true, "column.added", { columnId: column.id }, { id: column.id });
205269 }
206270
207271 if (parts.length >= 4 && parts[2] === "columns") {
@@ -212,18 +276,18 @@ async function dispatch(request: Request, url: URL, env: string, who: Who): Prom
212276 const data = await form(request);
213277 const name = cleanText(data.get("name"), 60);
214278 if (!name) return boardBad(request, who, boardId, "a column needs a name");
215 return doneTouch(request, boardId, db.renameColumn(boardId, columnId, name));
279 return donePublish(request, who, boardId, db.renameColumn(boardId, columnId, name), "column.renamed", { columnId });
216280 }
217281
218282 if (method === "POST" && parts.length === 5 && parts[4] === "move") {
219283 const data = await form(request);
220284 const direction = data.get("direction");
221285 if (direction !== "left" && direction !== "right") return boardBad(request, who, boardId, "direction must be left or right");
222 return doneTouch(request, boardId, db.moveColumn(boardId, columnId, direction));
286 return donePublish(request, who, boardId, db.moveColumn(boardId, columnId, direction), "column.moved", { columnId });
223287 }
224288
225289 if (method === "POST" && parts.length === 5 && parts[4] === "delete") {
226 return doneTouch(request, boardId, db.deleteColumn(boardId, columnId));
290 return donePublish(request, who, boardId, db.deleteColumn(boardId, columnId), "column.deleted", { columnId });
227291 }
228292
229293 if (method === "POST" && parts.length === 5 && parts[4] === "cards") {
@@ -232,7 +296,15 @@ async function dispatch(request: Request, url: URL, env: string, who: Who): Prom
232296 if (!title) return boardBad(request, who, boardId, "a card needs a title");
233297 const card = db.createCard(boardId, columnId, title);
234298 if (card === "full") return boardBad(request, who, boardId, `this board is full — ${MAX_CARDS_PER_BOARD} cards`);
235 return doneTouch(request, boardId, card !== "not_found", card !== "not_found" ? { id: card.id } : {});
299 return donePublish(
300 request,
301 who,
302 boardId,
303 card !== "not_found",
304 "card.added",
305 card !== "not_found" ? { columnId, cardId: card.id } : {},
306 card !== "not_found" ? { id: card.id } : {},
307 );
236308 }
237309 }
238310
@@ -244,7 +316,7 @@ async function dispatch(request: Request, url: URL, env: string, who: Who): Prom
244316 const data = await form(request);
245317 const title = cleanText(data.get("title"), 200);
246318 if (!title) return boardBad(request, who, boardId, "a card needs a title");
247 return doneTouch(request, boardId, db.editCard(boardId, cardId, title));
319 return donePublish(request, who, boardId, db.editCard(boardId, cardId, title), "card.edited", { cardId });
248320 }
249321
250322 if (method === "POST" && parts.length === 5 && parts[4] === "move") {
@@ -253,11 +325,14 @@ async function dispatch(request: Request, url: URL, env: string, who: Who): Prom
253325 const index = Number(data.get("index"));
254326 if (!ENTITY_ID.test(columnId)) return boardBad(request, who, boardId, "column_id is required");
255327 if (!Number.isFinite(index) || index < 0) return boardBad(request, who, boardId, "index must be a non-negative number");
256 return doneTouch(request, boardId, db.moveCard(boardId, cardId, columnId, Math.floor(index)));
328 return donePublish(request, who, boardId, db.moveCard(boardId, cardId, columnId, Math.floor(index)), "card.moved", {
329 cardId,
330 columnId,
331 });
257332 }
258333
259334 if (method === "POST" && parts.length === 5 && parts[4] === "delete") {
260 return doneTouch(request, boardId, db.deleteCard(boardId, cardId));
335 return donePublish(request, who, boardId, db.deleteCard(boardId, cardId), "card.deleted", { cardId });
261336 }
262337 }
263338
src/server.test.ts +148 −13
@@ -2,14 +2,19 @@ import { expect, test } from "bun:test";
22 import { mkdtempSync } from "node:fs";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
5 import { subscriberCount } from "./bus.ts";
56
67 process.env.FORGE_APP_DATA = mkdtempSync(join(tmpdir(), "app-"));
78 process.env.PORT = "0";
89 process.env.FORGE_APP_IDENTITY_KEY = "test-key";
910 const { server } = await import("./server.ts");
1011 const { sign } = await import("./who.ts");
11 const { MAX_CARDS_PER_BOARD, MAX_COLUMNS_PER_BOARD } = await import("./limits.ts");
12 const { MAX_CARDS_PER_BOARD, MAX_COLUMNS_PER_BOARD, MAX_SUBSCRIBERS_PER_BOARD, boardCreationBucket } = await import("./limits.ts");
1213 const db = await import("./db.ts");
14 // boardCreationBucket is one process-wide bucket; reset it so this file's
15 // own board-creation tests aren't at the mercy of what other test files
16 // already spent from it in this same `bun test` run.
17 boardCreationBucket.reset();
1318 const KEY = "test-key";
1419 const identityHeaders = (id: string, name: string, role: "user" | "admin" = "user") => {
1520 const identity = `${id}|${name}|${role}|${Date.now() + 60_000}`;
@@ -325,7 +330,12 @@ test("a board's link still edits it for someone who does not own it — sharing
325330 expect(await (await fetch(base + boardUrl)).text()).toContain("Bob added this");
326331 });
327332
328 test("streams a live event over /events when a card moves, so another tab can catch up", async () => {
333 test("404s for /events on an unknown board", async () => {
334 const response = await fetch(base + "/b/zzzzzzzz/events");
335 expect(response.status).toBe(404);
336 });
337
338 test("streams a live event over /events when a card is moved by another request", async () => {
329339 const id = await newBoard();
330340 const boardUrl = `/b/${id}`;
331341 const page = await (await fetch(base + boardUrl)).text();
@@ -335,30 +345,155 @@ test("streams a live event over /events when a card moves, so another tab can ca
335345
336346 const stream = await fetch(base + `${boardUrl}/events`);
337347 expect(stream.headers.get("content-type")).toBe("text/event-stream");
348 expect(stream.headers.get("cache-control")).toBe("no-store");
349 expect(stream.headers.get("x-accel-buffering")).toBe("no");
338350 const reader = stream.body!.getReader();
339351 const decoder = new TextDecoder();
340352 let buffer = "";
341 async function nextChunk(): Promise<string> {
353 async function nextFrame(): Promise<string> {
342354 while (!buffer.includes("\n\n")) {
343355 const { value, done } = await reader.read();
344356 if (done) throw new Error("stream ended");
345357 buffer += decoder.decode(value, { stream: true });
346358 }
347359 const at = buffer.indexOf("\n\n");
348 const chunk = buffer.slice(0, at);
360 const frame = buffer.slice(0, at);
349361 buffer = buffer.slice(at + 2);
350 return chunk;
362 return frame;
351363 }
352364
353 // The card just created already touched the bus before we connected.
354 let sawBacklog = false;
355 for (let i = 0; i < 5 && !sawBacklog; i++) if ((await nextChunk()).includes("data:")) sawBacklog = true;
356 expect(sawBacklog).toBe(true);
357
358365 await post(`${boardUrl}/cards/${cardId}/move`, { column_id: doingId, index: "0" });
359 let sawMove = false;
360 for (let i = 0; i < 5 && !sawMove; i++) if ((await nextChunk()).includes("data:")) sawMove = true;
361 expect(sawMove).toBe(true);
366 let event: { kind: string; boardId: string; ids: Record<string, string> } | undefined;
367 for (let i = 0; i < 5 && !event; i++) {
368 const frame = await nextFrame();
369 const data = frame.match(/^data: (.*)$/m)?.[1];
370 if (data) event = JSON.parse(data);
371 }
372 expect(event?.kind).toBe("card.moved");
373 expect(event?.boardId).toBe(id);
374 expect(event?.ids.cardId).toBe(cardId);
375 await reader.cancel();
376 });
377
378 test("a signed-in editor's forge id and name never reach the stream, only the change itself", async () => {
379 const id = await newBoard();
380 const boardUrl = `/b/${id}`;
381 const page = await (await fetch(base + boardUrl)).text();
382 const [, columnId] = page.match(/data-column-id="([a-z0-9]{12})"/)!;
383
384 const stream = await fetch(base + `${boardUrl}/events`);
385 const reader = stream.body!.getReader();
386 const decoder = new TextDecoder();
387 let buffer = "";
388 async function nextFrame(): Promise<string> {
389 while (!buffer.includes("\n\n")) {
390 const { value, done } = await reader.read();
391 if (done) throw new Error("stream ended");
392 buffer += decoder.decode(value, { stream: true });
393 }
394 const at = buffer.indexOf("\n\n");
395 const frame = buffer.slice(0, at);
396 buffer = buffer.slice(at + 2);
397 return frame;
398 }
399
400 await post(`${boardUrl}/columns/${columnId}/cards`, { title: "Alice's card" }, { ...j, ...identityHeaders("secret-id", "alice") });
401 let frame = "";
402 for (let i = 0; i < 5 && !frame.includes("data:"); i++) frame = await nextFrame();
403 expect(frame).toContain("data:");
404 expect(frame).not.toContain("secret-id");
405 expect(frame).not.toContain("alice");
406 expect(frame).not.toContain('"by"');
407 await reader.cancel();
408 });
409
410 test("a closed client leaves no subscriber behind", async () => {
411 const id = await newBoard();
412 expect(subscriberCount(id)).toBe(0);
413 const controller = new AbortController();
414 const stream = await fetch(base + `/b/${id}/events`, { signal: controller.signal });
415 expect(stream.headers.get("content-type")).toBe("text/event-stream");
416 expect(subscriberCount(id)).toBe(1);
417 controller.abort();
418 await Bun.sleep(10);
419 expect(subscriberCount(id)).toBe(0);
420 });
421
422 test("HEAD on /events answers promptly instead of hanging on the endless body, and leaves no subscriber", async () => {
423 const id = await newBoard();
424 expect(subscriberCount(id)).toBe(0);
425 const response = await fetch(base + `/b/${id}/events`, { method: "HEAD" });
426 expect(response.status).toBe(200);
427 expect(response.headers.get("content-type")).toBe("text/event-stream");
428 expect(await response.text()).toBe("");
429 expect(subscriberCount(id)).toBe(0);
430 });
431
432 test("a board past its subscriber cap refuses the next stream with a 503, and closing one frees a slot", async () => {
433 const id = await newBoard();
434 const controllers: AbortController[] = [];
435 for (let i = 0; i < MAX_SUBSCRIBERS_PER_BOARD; i++) {
436 const controller = new AbortController();
437 controllers.push(controller);
438 const stream = await fetch(base + `/b/${id}/events`, { signal: controller.signal });
439 expect(stream.status).toBe(200);
440 }
441 expect(subscriberCount(id)).toBe(MAX_SUBSCRIBERS_PER_BOARD);
442
443 const refused = await fetch(base + `/b/${id}/events`);
444 expect(refused.status).toBe(503);
445
446 controllers[0].abort();
447 await Bun.sleep(10);
448 expect(subscriberCount(id)).toBe(MAX_SUBSCRIBERS_PER_BOARD - 1);
449
450 const admittedController = new AbortController();
451 const admitted = await fetch(base + `/b/${id}/events`, { signal: admittedController.signal });
452 expect(admitted.status).toBe(200);
453 for (const controller of controllers.slice(1)) controller.abort();
454 admittedController.abort();
455 });
456
457 test("an add_card call over MCP publishes a card.added frame, same as the page's own form", async () => {
458 const id = await newBoard();
459 const page = await (await fetch(base + `/b/${id}`)).text();
460 const [, columnId] = page.match(/data-column-id="([a-z0-9]{12})"/)!;
461
462 const stream = await fetch(base + `/b/${id}/events`);
463 const reader = stream.body!.getReader();
464 const decoder = new TextDecoder();
465 let buffer = "";
466 async function nextFrame(): Promise<string> {
467 while (!buffer.includes("\n\n")) {
468 const { value, done } = await reader.read();
469 if (done) throw new Error("stream ended");
470 buffer += decoder.decode(value, { stream: true });
471 }
472 const at = buffer.indexOf("\n\n");
473 const frame = buffer.slice(0, at);
474 buffer = buffer.slice(at + 2);
475 return frame;
476 }
477
478 await fetch(base + "/mcp", {
479 method: "POST",
480 headers: { "content-type": "application/json" },
481 body: JSON.stringify({
482 jsonrpc: "2.0",
483 id: 1,
484 method: "tools/call",
485 params: { name: "add_card", arguments: { board_id: id, column_id: columnId, title: "From an agent" } },
486 }),
487 });
488
489 let event: { kind: string; boardId: string; ids: Record<string, string> } | undefined;
490 for (let i = 0; i < 5 && !event; i++) {
491 const frame = await nextFrame();
492 const data = frame.match(/^data: (.*)$/m)?.[1];
493 if (data) event = JSON.parse(data);
494 }
495 expect(event?.kind).toBe("card.added");
496 expect(event?.boardId).toBe(id);
362497 await reader.cancel();
363498 });
364499
src/server.ts +9 −1
@@ -49,7 +49,7 @@ export const server = Bun.serve({
4949 port: Number(process.env.PORT ?? 8080),
5050 hostname: process.env.HOST ?? "127.0.0.1",
5151 // A connection silent for a minute is dropped; /b/:id/events heartbeats
52 // every 25 seconds (src/live.ts) to stay well inside that.
52 // every 25 seconds (src/routes.ts) to stay well inside that.
5353 idleTimeout: 60,
5454 // Never Bun's source-listing error page, in production or in a preview.
5555 development: false,
@@ -87,6 +87,14 @@ export const server = Bun.serve({
8787 }
8888
8989 if (!isHead) return response;
90 // /b/:id/events answers as a GET with an endless body (the SSE stream);
91 // buffering it below to measure its length would never settle. A HEAD
92 // on it answers with the same status and headers and no body, same as
93 // any other HEAD, just without reading the body to get there.
94 if (response.headers.get("content-type")?.startsWith("text/event-stream")) {

Approved. Both blocking findings are fixed, and I checked each one against this head rather than taking the diff's word for it.

HEAD /b/<id>/events no longer hangs. On the preview it now answers 200 in 0.13s with text/event-stream, cache-control: no-store and the full security floor, instead of timing out at 15s. The fix on the line this is anchored to is the narrow one — cancel the body and answer with the same status and headers when the content type is a stream — and expect(subscriberCount(id)).toBe(0) after the HEAD is the assertion that matters, since a hung HEAD used to hold one of the 100 slots. I reverted the branch's src/server.ts back to the unconditional await response.arrayBuffer() and the new test fails (and the file takes ~6s to run, which is the hang), so it is load-bearing.

No forge identity on the wire. send destructures by off before serializing, and the frames I watched on the preview carry only kind, boardId, client and ids. I reverted the strip and a signed-in editor's forge id and name never reach the stream fails; likewise the 503 cap test fails with the cap removed. Keeping by on BoardEvent as an in-process seam for #18 with the comment explaining why it stops at the stream is the right call.

The rest of the round is right too. MAX_BOARDS_CREATED_PER_MINUTE is back to 30, with TokenBucket.reset() scoped to the test files and documented as such — the limit is no longer sized by the test count. Events now apply through one promise chain so two moves of the same card cannot race their own fetches, with PENDING_LIMIT falling back to a single reconcile instead of growing without bound. clientId is crypto.randomUUID(). column.added/column.deleted keep every card's "Move to column" options in step, with a test, and column.renamed null-guards its fresh lookup. The claim narrowing is now in the README next to "What's simulated" rather than only in the pull body. bun test is green here: 126 pass, 0 fail across 13 files.

The direction's sentence works on the preview. With one stream open on a board I added a card by plain form POST and a card by tools/call add_card over POST /mcp, and both arrived as card.added frames within a second, correctly scoped, with the right columnId/cardId — a person and an agent on one board, each seeing the other. Both paths now have tests that would fail if the publish(...) calls were deleted.

One small thing, not worth another round: crypto.randomUUID() is undefined outside a secure context, so serving this over plain http on a LAN address — a phone testing the touch-drag path, say — would throw at the top of the IIFE and take drag, filter and live with it. crypto.randomUUID?.() ?? Math.random().toString(36).slice(2) keeps the property you wanted and costs a line. https and localhost, which is every documented way to run it, are fine.

Nothing else is left open that isn't already tracked: a terminal write reaching web viewers live is #31/#56/#40 and is structurally out of reach for an in-process bus (the tty is a separate process, as #17 already says); capping a body by bytes read rather than a declared Content-Length is #39 and predates this pull; the name behind a move is #18. Worth noting for whoever plans next: #44 asks for exactly the two things this pull just landed, so it can close with it.

95 response.body?.cancel();
96 return new Response(null, { status: response.status, headers: response.headers });
97 }
9098 const body = await response.arrayBuffer();
9199 const headers = new Headers(response.headers);
92100 headers.set("content-length", String(body.byteLength));
src/theme.test.ts +6
@@ -14,8 +14,14 @@ process.env.FORGE_APP_DATA = mkdtempSync(join(tmpdir(), "app-"));
1414 process.env.PORT = "0";
1515 process.env.FORGE_APP_IDENTITY_KEY = "test-key";
1616 const { server } = await import("./server.ts");
17 const { boardCreationBucket } = await import("./limits.ts");
1718 const base = `http://${server.hostname}:${server.port}`;
1819
20 // boardCreationBucket is one process-wide bucket; reset it so this file's
21 // own board-creation calls aren't at the mercy of what other test files
22 // already spent from it in this same `bun test` run.
23 boardCreationBucket.reset();
24
1925 test("the stylesheet follows the system theme and lets an explicit choice override it", async () => {
2026 const page = await (await fetch(base + "/")).text();
2127 expect(page).toContain("prefers-color-scheme: dark");
static/board.7793265334.js → static/board.109353762.js renamed +209 −41
@@ -18,8 +18,11 @@
1818 }
1919
2020 // A random id for this tab, sent on every write so its own live event
21 // (see "live" below) can be told apart from everyone else's.
22 const clientId = Math.random().toString(36).slice(2);
21 // (see "live" below) can be told apart from everyone else's. It is never
22 // trusted for anything but that (see routes.ts), but a guessable one
23 // would still let another tab spoof "this is your own echo" — crypto's
24 // randomUUID costs nothing over Math.random and closes that off.
25 const clientId = crypto.randomUUID();
2326 function post(path, data) {
2427 return fetch(path, {
2528 method: "POST",
@@ -35,9 +38,12 @@
3538 const cardsOf = (columnEl) => Array.from(columnEl.querySelectorAll(".card"));
3639 const indexOf = (cardEl) => cardsOf(cardEl.closest(".column")).indexOf(cardEl);
3740 const columnsList = () => Array.from(root.querySelectorAll(".column"));
41 const columnEl = (id) => root.querySelector(`.column[data-column-id="${CSS.escape(id)}"]`);
42 const cardEl = (id) => root.querySelector(`.card[data-card-id="${CSS.escape(id)}"]`);
3843
39 function updateCounts() {
40 for (const col of columnsList()) {
44 function updateCounts(...columns) {
45 for (const col of columns.length ? columns : columnsList()) {
46 if (!col) continue;
4147 const all = col.querySelectorAll(".card").length;
4248 const visible = col.querySelectorAll(".card:not([hidden])").length;
4349 col.querySelector(".count").textContent = `${visible}/${all}`;
@@ -117,20 +123,18 @@
117123 if (!dragging) return;
118124 e.preventDefault();
119125 });
120 // A board refreshed from a live update (see "live" below) gets fresh
121 // `.cards` elements, so this attaches again rather than running once.
122 function attachDropListeners() {
123 for (const list of root.querySelectorAll(".cards")) {
124 list.addEventListener("dragover", (e) => {
125 if (!dragging) return;
126 e.preventDefault();
127 clearDropTargets();
128 list.closest(".column").classList.add("drop-target");
129 placeInList(dragging.el, list, e.clientY);
130 });
131 }
126 // A column added live (see "live" below) gets its own `.cards` list after
127 // the page loads, so this attaches to one list at a time rather than once.
128 function attachDropListenersTo(list) {
129 list.addEventListener("dragover", (e) => {
130 if (!dragging) return;
131 e.preventDefault();
132 clearDropTargets();
133 list.closest(".column").classList.add("drop-target");
134 placeInList(dragging.el, list, e.clientY);
135 });
132136 }
133 attachDropListeners();
137 for (const list of root.querySelectorAll(".cards")) attachDropListenersTo(list);
134138
135139 // ---- touch: a long press (no real drag events on a phone) picks a card
136140 // up, pointermove carries it, and pointerup drops it through the same
@@ -391,39 +395,203 @@
391395 // Guarded so this file still runs where EventSource doesn't exist (the
392396 // drag test's synthetic environment); a real browser always has it.
393397 if (typeof EventSource !== "undefined") {
394 let pending = false;
395 async function refreshBoard() {
396 // Any input inside the board (a card's title, a new-card box, a column
397 // rename) keeps its refresh until the input loses focus — replacing it
398 // mid-word would wipe what someone is typing. A card itself focused
399 // for keyboard navigation (not editing) is not an input, so it does
400 // not defer; its focus is restored after the swap instead.
398 // Fetching the board's own HTML is the only place its rendered markup
399 // exists; a live event's `ids` say which bit of that fresh markup to
400 // graft onto the live page, so an unrelated card, input or scroll
401 // position is never touched.
402 async function freshBoard() {
403 const response = await fetch(location.pathname + location.search, { headers: { accept: "text/html" } });
404 if (!response.ok) return null;
405 return new DOMParser().parseFromString(await response.text(), "text/html");
406 }
407
408 function isEditingCard(id) {
409 const card = cardEl(id);
410 const input = card && card.querySelector(".edit input");
411 return !!input && document.activeElement === input;
412 }
413 function isRenamingColumn(id) {
414 const col = columnEl(id);
415 const input = col && col.querySelector("header form.rename input");
416 return !!input && document.activeElement === input;
417 }
418 function isRenamingBoard() {
419 const input = document.querySelector(`form[action="/b/${boardId}/rename"] input[name=name]`);
420 return !!input && document.activeElement === input;
421 }
422 // Undo's scope isn't known ahead of time, so — like the old whole-board
423 // refresh — it's conservative: any input anywhere on the board waits it out.
424 function isTypingSomewhere() {
401425 const focused = root.querySelector(".board :focus");
402 if (dragging || (focused && focused.tagName === "INPUT")) {
403 pending = true;
426 return !!focused && (focused.tagName === "INPUT" || focused.tagName === "SELECT");
427 }
428
429 // An event that would clobber something the user is mid-typing (or
430 // mid-drag) waits until they're done rather than overwriting it. A tab
431 // left mid-type through a burst of unrelated activity would otherwise
432 // grow this without bound, so past a generous cap it gives up trying
433 // to replay each one and just reconciles the whole board once instead.
434 const pending = [];
435 const PENDING_LIMIT = 50;
436 // Every applyNow runs to completion (including its own freshBoard()
437 // fetch) before the next one starts, chained through this queue — two
438 // events handled out of order, each racing its own fetch, is how a
439 // card ends up in the wrong place until the next reconnect.
440 let queue = Promise.resolve();
441 function enqueueTask(task) {
442 queue = queue.then(task).catch((err) => console.error(err));
443 }
444 function enqueue(event) {
445 enqueueTask(() => applyNow(event));
446 }
447 function apply(event) {
448 if (
449 (event.kind === "card.edited" && isEditingCard(event.ids.cardId)) ||
450 (event.kind === "card.moved" && dragging && dragging.el.dataset.cardId === event.ids.cardId) ||
451 (event.kind === "column.renamed" && isRenamingColumn(event.ids.columnId)) ||
452 (event.kind === "board.renamed" && isRenamingBoard()) ||
453 (event.kind === "undo" && (dragging || isTypingSomewhere()))
454 ) {
455 pending.push(event);
456 if (pending.length > PENDING_LIMIT) {
457 pending.length = 0;
458 enqueueTask(reconcile);
459 }
404460 return;
405461 }
406 pending = false;
407 const focusedCardId = focused && focused.classList.contains("card") ? focused.dataset.cardId : null;
408 const response = await fetch(location.pathname + location.search, { headers: { accept: "text/html" } });
409 if (!response.ok) return;
410 const fresh = new DOMParser().parseFromString(await response.text(), "text/html");
411 const next = fresh.querySelector(".board");
462 enqueue(event);
463 }
464 function retryPending() {
465 if (pending.length === 0) return;
466 for (const event of pending.splice(0)) enqueue(event);
467 }
468 root.addEventListener("focusout", retryPending);
469 root.addEventListener("dragend", retryPending);
470
471 // The scope of an undo (or of whatever was missed while a stream was
472 // disconnected) isn't known, so both fall back to swapping in the whole
473 // freshly-rendered board rather than guessing what changed.
474 async function reconcile() {
475 const fresh = await freshBoard();
476 const next = fresh && fresh.querySelector(".board");
412477 const current = root.querySelector(".board");
413478 if (!next || !current) return;
414 current.replaceWith(next);
415 attachDropListeners();
416 if (focusedCardId) root.querySelector(`.card[data-card-id="${CSS.escape(focusedCardId)}"]`)?.focus();
479 const focused = root.querySelector(".board :focus");
480 const focusedCardId = focused && focused.classList.contains("card") ? focused.dataset.cardId : null;
481 current.replaceWith(document.importNode(next, true));
482 for (const list of root.querySelectorAll(".cards")) attachDropListenersTo(list);
483 if (focusedCardId) cardEl(focusedCardId)?.focus();
484 if (filterInput) applyFilter();
485 }
486
487 async function applyNow(event) {
488 const { kind, ids } = event;
489
490 if (kind === "card.deleted") {
491 const card = cardEl(ids.cardId);
492 const column = card && card.closest(".column");
493 card?.remove();
494 updateCounts(column);
495 if (filterInput) applyFilter();
496 return;
497 }
498 if (kind === "column.deleted") {
499 columnEl(ids.columnId)?.remove();
500 for (const opt of root.querySelectorAll(`select[name=column_id] option[value="${CSS.escape(ids.columnId)}"]`)) opt.remove();
501 return;
502 }
503 if (kind === "undo") return reconcile();
504
505 const fresh = await freshBoard();
506 if (!fresh) return;
507
508 if (kind === "board.renamed") {
509 const freshInput = fresh.querySelector(`form[action="/b/${boardId}/rename"] input[name=name]`);
510 const liveInput = document.querySelector(`form[action="/b/${boardId}/rename"] input[name=name]`);
511 if (freshInput && liveInput) liveInput.value = freshInput.value;
512 return;
513 }
514
515 if (kind === "card.added" || kind === "card.moved") {
516 const freshCard = fresh.querySelector(`.card[data-card-id="${CSS.escape(ids.cardId)}"]`);
517 if (!freshCard) return;
518 const targetColumn = columnEl(freshCard.dataset.columnId);
519 if (!targetColumn) return;
520 const previousColumn = cardEl(ids.cardId)?.closest(".column");
521 cardEl(ids.cardId)?.remove();
522 const freshSiblings = Array.from(fresh.querySelectorAll(`.column[data-column-id="${CSS.escape(freshCard.dataset.columnId)}"] .card`));
523 const at = freshSiblings.findIndex((c) => c.dataset.cardId === ids.cardId);
524 const liveSiblings = cardsOf(targetColumn);
525 targetColumn.querySelector(".cards").insertBefore(document.importNode(freshCard, true), liveSiblings[at] || null);
526 updateCounts(targetColumn, previousColumn);
527 if (filterInput) applyFilter();
528 return;
529 }
530
531 if (kind === "card.edited") {
532 const card = cardEl(ids.cardId);
533 const freshCard = fresh.querySelector(`.card[data-card-id="${CSS.escape(ids.cardId)}"]`);
534 if (!card || !freshCard) return;
535 card.dataset.title = freshCard.dataset.title;
536 const input = card.querySelector(".edit input");
537 if (input) input.value = freshCard.dataset.title;
538 if (filterInput) applyFilter();
539 return;
540 }
541
542 if (kind === "column.added" || kind === "column.moved") {
543 const freshColumn = fresh.querySelector(`.column[data-column-id="${CSS.escape(ids.columnId)}"]`);
544 const board = root.querySelector(".board");
545 if (!freshColumn || !board) return;
546 const order = Array.from(fresh.querySelectorAll(".column")).map((c) => c.dataset.columnId);
547 const at = order.indexOf(ids.columnId);
548 let node = columnEl(ids.columnId);
549 if (!node) {
550 node = document.importNode(freshColumn, true);
551 attachDropListenersTo(node.querySelector(".cards"));
552 const nameInput = freshColumn.querySelector("input[name=name]");
553 if (nameInput) {
554 for (const select of root.querySelectorAll("select[name=column_id]")) {
555 const opt = document.createElement("option");
556 opt.value = ids.columnId;
557 opt.textContent = nameInput.value;
558 select.appendChild(opt);
559 }
560 }
561 }
562 const live = columnsList().filter((c) => c !== node);
563 board.insertBefore(node, live[at] || board.querySelector(".new-column"));
564 if (filterInput) applyFilter();
565 return;
566 }
567
568 if (kind === "column.renamed") {
569 const col = columnEl(ids.columnId);
570 const freshColumn = fresh.querySelector(`.column[data-column-id="${CSS.escape(ids.columnId)}"]`);
571 const freshInput = freshColumn && freshColumn.querySelector("header form.rename input");
572 if (!col || !freshInput) return;
573 const name = freshInput.value;
574 const input = col.querySelector("header form.rename input");
575 if (input) input.value = name;
576 for (const opt of root.querySelectorAll(`select[name=column_id] option[value="${CSS.escape(ids.columnId)}"]`)) opt.textContent = name;
577 return;
578 }
417579 }
418 // A card mid-edit or mid-drag keeps its refresh until it's free again.
419 root.addEventListener("focusout", () => pending && refreshBoard());
420 root.addEventListener("dragend", () => pending && refreshBoard());
421580
422581 const source = new EventSource(`/b/${boardId}/events`);
423582 source.onmessage = (message) => {
424 const { by } = JSON.parse(message.data);
425 if (by === clientId) return; // this tab already applied it optimistically
426 refreshBoard();
583 const event = JSON.parse(message.data);
584 if (event.client && event.client === clientId) return; // this tab already applied it optimistically
585 apply(event);
586 };
587 // A dropped connection reconnects on its own; the reconnect itself
588 // (not the first, successful connection) means something may have been
589 // missed while it was down, so that one reconciles by re-reading the
590 // board rather than trusting nothing was lost.
591 let connectedBefore = false;
592 source.onopen = () => {
593 if (connectedBefore) reconcile();
594 connectedBefore = true;
427595 };
428596 }
429597 })();

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs