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
Check · Review · Land · Live done — Landed and live in production.
scout/tempo:scout/12-a-card-someone-moves-appears-for-everyon → main 5 commits fork 3 threads · 3 unresolved
README.md +23 −7
| @@ -50,10 +50,22 @@ FORGE_APP_DATA=./data bun run src/tty.ts # the terminal interface | ||
| 50 | 50 | - **Undo**: reverses the last change to the board — a create, edit, |
| 51 | 51 | move, or delete of a card or column. It is a shared, board-wide undo |
| 52 | 52 | (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"). | |
| 57 | 69 | - **Agents**: `POST /mcp` speaks MCP over plain JSON-RPC 2.0 |
| 58 | 70 | (`initialize`, `tools/list`, `tools/call`) with four tools — |
| 59 | 71 | `list_boards`, `list_cards`, `add_card`, `move_card` — under the same |
| @@ -83,6 +95,9 @@ background, reverting if it fails. | ||
| 83 | 95 | the server, so it can't be used to go discover a board by guessing. |
| 84 | 96 | - Undo is board-wide, not per-visitor, and unaffected by who's signed |
| 85 | 97 | 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. | |
| 86 | 101 | - The terminal (`src/tty.ts` draws it and reads keys, `src/keys.ts` |
| 87 | 102 | decides what each key does, `src/session.ts` decides who is asking) |
| 88 | 103 | mirrors the board actions with a letter-key scheme (`j/k/h/l` move, |
| @@ -157,9 +172,10 @@ same as an anonymous browser's. | ||
| 157 | 172 | ## Dependencies |
| 158 | 173 | |
| 159 | 174 | 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, | |
| 163 | 179 | pointerdown/pointermove/pointerup, and `localStorage` calls run against |
| 164 | 180 | the real thing — hand-rolling that much of the DOM to test a few dozen |
| 165 | 181 | 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-")); | ||
| 19 | 19 | process.env.PORT = "0"; |
| 20 | 20 | process.env.FORGE_APP_IDENTITY_KEY = "test-key"; |
| 21 | 21 | const { server } = await import("./server.ts"); |
| 22 | const { boardCreationBucket } = await import("./limits.ts"); | |
| 22 | 23 | const base = `http://${server.hostname}:${server.port}`; |
| 23 | 24 | |
| 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 | ||
| 24 | 30 | const post = (path: string, body: Record<string, string> = {}) => |
| 25 | 31 | fetch(base + path, { method: "POST", body: new URLSearchParams(body) }); |
| 26 | 32 |
src/limits.ts +17
| @@ -24,6 +24,11 @@ export const MAX_BOARDS_CREATED_PER_MINUTE = 30; | ||
| 24 | 24 | // giant upload can't be used to exhaust memory parsing it. |
| 25 | 25 | export const MAX_REQUEST_BODY_BYTES = 64 * 1024; |
| 26 | 26 | |
| 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 | ||
| 27 | 32 | /** |
| 28 | 33 | * A token bucket: `capacityPerMinute` tokens to start, refilled at |
| 29 | 34 | * `capacityPerMinute` per minute, never exceeding that capacity. It is a |
| @@ -66,6 +71,18 @@ export class TokenBucket { | ||
| 66 | 71 | if (missing <= 0) return 0; |
| 67 | 72 | return Math.max(1, Math.ceil((missing / this.capacityPerMinute) * 60)); |
| 68 | 73 | } |
| 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 | } | |
| 69 | 86 | } |
| 70 | 87 | |
| 71 | 88 | // 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 @@ | ||
| 1 | 1 | /** |
| 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. | |
| 7 | 6 | * |
| 8 | 7 | * happy-dom has no EventSource or DOMParser of its own recent enough for |
| 9 | 8 | * 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-")); | ||
| 20 | 19 | process.env.PORT = "0"; |
| 21 | 20 | process.env.FORGE_APP_IDENTITY_KEY = "test-key"; |
| 22 | 21 | const { server } = await import("./server.ts"); |
| 22 | const { boardCreationBucket } = await import("./limits.ts"); | |
| 23 | 23 | const base = `http://${server.hostname}:${server.port}`; |
| 24 | 24 | |
| 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 | ||
| 25 | 30 | 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) }); | |
| 27 | 32 | |
| 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]; | |
| 40 | 36 | } |
| 41 | 37 | |
| 42 | /** Long enough that a refresh would have landed, for asserting one has not. */ | |
| 43 | const settle = () => new Promise((resolve) => setTimeout(resolve, 100)); | |
| 44 | ||
| 45 | 38 | let restoreEventSource: (() => void) | undefined; |
| 46 | 39 | let restoreDOMParser: (() => void) | undefined; |
| 47 | 40 | beforeEach(() => { |
| @@ -61,13 +54,14 @@ afterEach(() => { | ||
| 61 | 54 | |
| 62 | 55 | class FakeEventSource { |
| 63 | 56 | onmessage: ((message: { data: string }) => void) | null = null; |
| 57 | onopen: (() => void) | null = null; | |
| 64 | 58 | constructor(_url: string) { |
| 65 | 59 | latestSource = this; |
| 66 | 60 | } |
| 67 | 61 | } |
| 68 | 62 | let latestSource: FakeEventSource | undefined; |
| 69 | 63 | |
| 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 }> { | |
| 71 | 65 | const html = await (await fetch(`${base}/b/${boardId}`)).text(); |
| 72 | 66 | const [, scriptSrc] = html.match(/<script src="(\/static\/board[^"]+)"/)!; |
| 73 | 67 | const script = await (await fetch(base + scriptSrc)).text(); |
| @@ -83,7 +77,10 @@ async function run(boardId: string): Promise<{ window: Window; document: Documen | ||
| 83 | 77 | |
| 84 | 78 | new Function("document", "fetch", "location", "history", "CSS", script)( |
| 85 | 79 | 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 | }, | |
| 87 | 84 | window.location, |
| 88 | 85 | window.history, |
| 89 | 86 | window.CSS, |
| @@ -91,38 +88,32 @@ async function run(boardId: string): Promise<{ window: Window; document: Documen | ||
| 91 | 88 | return { window, document }; |
| 92 | 89 | } |
| 93 | 90 | |
| 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(); | |
| 97 | 97 | const { window, document } = await run(boardId); |
| 98 | const columnId = document.querySelector("[data-column-id]")!.getAttribute("data-column-id")!; | |
| 98 | 99 | |
| 99 | 100 | const addInput = document.querySelector(".add-card input") as unknown as HTMLInputElement; |
| 100 | 101 | addInput.focus(); |
| 101 | 102 | addInput.value = "half-typed"; |
| 102 | 103 | |
| 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)); | |
| 111 | 108 | |
| 112 | 109 | 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(); | |
| 119 | 111 | |
| 120 | 112 | await window.close(); |
| 121 | 113 | }); |
| 122 | 114 | |
| 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(); | |
| 126 | 117 | const columnId = (await (await fetch(`${base}/b/${boardId}`)).text()).match(/data-column-id="([a-z0-9]{12})"/)![1]; |
| 127 | 118 | await post(`/b/${boardId}/columns/${columnId}/cards`, { title: "Keep focused" }); |
| 128 | 119 | const { window, document } = await run(boardId); |
| @@ -131,16 +122,96 @@ test("a live refresh restores focus to a keyboard-focused card instead of deferr | ||
| 131 | 122 | card.focus(); |
| 132 | 123 | const cardId = card.dataset.cardId; |
| 133 | 124 | |
| 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)); | |
| 140 | 129 | |
| 141 | 130 | 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); | |
| 144 | 215 | |
| 145 | 216 | await window.close(); |
| 146 | 217 | }); |
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 @@ | ||
| 8 | 8 | * take a board id directly, exactly like the page and the JSON forms do. |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | import * as bus from "./bus.ts"; | |
| 11 | 12 | import * as db from "./db.ts"; |
| 12 | import { touch } from "./live.ts"; | |
| 13 | 13 | import { MAX_CARDS_PER_BOARD } from "./limits.ts"; |
| 14 | 14 | import type { Who } from "./who.ts"; |
| 15 | 15 | |
| 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 | ||
| 16 | 21 | const BOARD_ID = /^[a-z0-9]{8}$/; |
| 17 | 22 | const ENTITY_ID = /^[a-z0-9]{12}$/; |
| 18 | 23 | |
| @@ -57,7 +62,7 @@ export const tools: readonly Tool[] = [ | ||
| 57 | 62 | properties: { board_id: { type: "string" }, column_id: { type: "string" }, title: { type: "string", maxLength: 200 } }, |
| 58 | 63 | required: ["board_id", "column_id", "title"], |
| 59 | 64 | }, |
| 60 | run: (_who, args) => { | |
| 65 | run: (who, args) => { | |
| 61 | 66 | const board = boardOf(args); |
| 62 | 67 | if (!board) return fail("not_found", "no such board"); |
| 63 | 68 | const columnId = String(args.column_id ?? ""); |
| @@ -67,7 +72,7 @@ export const tools: readonly Tool[] = [ | ||
| 67 | 72 | const card = db.createCard(board.id, columnId, title); |
| 68 | 73 | if (card === "not_found") return fail("not_found", "no such column"); |
| 69 | 74 | 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 }); | |
| 71 | 76 | return ok(card); |
| 72 | 77 | }, |
| 73 | 78 | }, |
| @@ -84,7 +89,7 @@ export const tools: readonly Tool[] = [ | ||
| 84 | 89 | }, |
| 85 | 90 | required: ["board_id", "card_id", "column_id"], |
| 86 | 91 | }, |
| 87 | run: (_who, args) => { | |
| 92 | run: (who, args) => { | |
| 88 | 93 | const board = boardOf(args); |
| 89 | 94 | if (!board) return fail("not_found", "no such board"); |
| 90 | 95 | const cardId = String(args.card_id ?? ""); |
| @@ -94,7 +99,7 @@ export const tools: readonly Tool[] = [ | ||
| 94 | 99 | if (!Number.isFinite(index) || index < 0) return fail("invalid", "index must be a non-negative number"); |
| 95 | 100 | const moved = db.moveCard(board.id, cardId, columnId, Math.floor(index)); |
| 96 | 101 | 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 }); | |
| 98 | 103 | return ok({ id: cardId }); |
| 99 | 104 | }, |
| 100 | 105 | }, |
src/pages/board.ts +1 −1
| @@ -278,6 +278,6 @@ const boardShortcuts: [string, string][] = [ | ||
| 278 | 278 | |
| 279 | 279 | // Named by content — a change to static/board.js gets a new hash here, |
| 280 | 280 | // 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"; | |
| 282 | 282 | export const THEME_JS = "theme.1025564933.js"; |
| 283 | 283 | export const BOARDS_JS = "boards.608180649.js"; |
src/routes.ts +95 −20
| @@ -4,9 +4,10 @@ | ||
| 4 | 4 | * not own, so server.ts can fall through to static files and 404. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import * as bus from "./bus.ts"; | |
| 8 | import type { EventKind } from "./bus.ts"; | |
| 7 | 9 | 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"; | |
| 10 | 11 | import { rpc } from "./mcp.ts"; |
| 11 | 12 | import { boardPage, landingPage } from "./pages/board.ts"; |
| 12 | 13 | import type { Who } from "./who.ts"; |
| @@ -14,12 +15,23 @@ import type { Who } from "./who.ts"; | ||
| 14 | 15 | const BOARD_ID = /^[a-z0-9]{8}$/; |
| 15 | 16 | const ENTITY_ID = /^[a-z0-9]{12}$/; |
| 16 | 17 | |
| 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 | |
| 18 | 19 | // 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. | |
| 20 | 21 | 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 | } | |
| 23 | 35 | |
| 24 | 36 | // Pages carry a visitor's name and sign-out link once they're signed in, so |
| 25 | 37 | // 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 | ||
| 59 | 71 | return ok ? Response.redirect(`/b/${boardId}`, 303) : new Response("not found", { status: 404 }); |
| 60 | 72 | } |
| 61 | 73 | // 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); | |
| 64 | 84 | return done(request, boardId, ok, extra); |
| 65 | 85 | } |
| 66 | 86 | |
| @@ -100,6 +120,51 @@ async function form(request: Request): Promise<FormData> { | ||
| 100 | 120 | return request.formData(); |
| 101 | 121 | } |
| 102 | 122 | |
| 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) { | |
| 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 | ||
| 103 | 168 | export async function route(request: Request, url: URL, env: string, who: Who): Promise<Response | undefined> { |
| 104 | 169 | try { |
| 105 | 170 | return await dispatch(request, url, env, who); |
| @@ -170,7 +235,7 @@ async function dispatch(request: Request, url: URL, env: string, who: Who): Prom | ||
| 170 | 235 | |
| 171 | 236 | if (method === "GET" && parts.length === 3 && parts[2] === "events") { |
| 172 | 237 | if (!db.getBoard(boardId)) return new Response("board not found", { status: 404 }); |
| 173 | return live.events(boardId, request); | |
| 238 | return eventStream(boardId, request); | |
| 174 | 239 | } |
| 175 | 240 | |
| 176 | 241 | 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 | ||
| 179 | 244 | if (who.role === "anon") return new Response("sign in to keep a board", { status: 401 }); |
| 180 | 245 | const result = db.claimBoard(boardId, { id: who.id, name: who.name }); |
| 181 | 246 | if (result === "owned_by_other") return new Response("already kept by someone else", { status: 403 }); |
| 182 | if (result === "claimed") touch(boardId, request); | |
| 183 | 247 | return done(request, boardId, true); |
| 184 | 248 | } |
| 185 | 249 | |
| @@ -188,11 +252,11 @@ async function dispatch(request: Request, url: URL, env: string, who: Who): Prom | ||
| 188 | 252 | const name = cleanText(data.get("name"), 100); |
| 189 | 253 | if (!name) return boardBad(request, who, boardId, "a board needs a name"); |
| 190 | 254 | db.renameBoard(boardId, name); |
| 191 | return doneTouch(request, boardId, true); | |
| 255 | return donePublish(request, who, boardId, true, "board.renamed"); | |
| 192 | 256 | } |
| 193 | 257 | |
| 194 | 258 | 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"); | |
| 196 | 260 | } |
| 197 | 261 | |
| 198 | 262 | 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 | ||
| 201 | 265 | if (!name) return boardBad(request, who, boardId, "a column needs a name"); |
| 202 | 266 | const column = db.createColumn(boardId, name); |
| 203 | 267 | 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 }); | |
| 205 | 269 | } |
| 206 | 270 | |
| 207 | 271 | if (parts.length >= 4 && parts[2] === "columns") { |
| @@ -212,18 +276,18 @@ async function dispatch(request: Request, url: URL, env: string, who: Who): Prom | ||
| 212 | 276 | const data = await form(request); |
| 213 | 277 | const name = cleanText(data.get("name"), 60); |
| 214 | 278 | 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 }); | |
| 216 | 280 | } |
| 217 | 281 | |
| 218 | 282 | if (method === "POST" && parts.length === 5 && parts[4] === "move") { |
| 219 | 283 | const data = await form(request); |
| 220 | 284 | const direction = data.get("direction"); |
| 221 | 285 | 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 }); | |
| 223 | 287 | } |
| 224 | 288 | |
| 225 | 289 | 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 }); | |
| 227 | 291 | } |
| 228 | 292 | |
| 229 | 293 | 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 | ||
| 232 | 296 | if (!title) return boardBad(request, who, boardId, "a card needs a title"); |
| 233 | 297 | const card = db.createCard(boardId, columnId, title); |
| 234 | 298 | 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 | ); | |
| 236 | 308 | } |
| 237 | 309 | } |
| 238 | 310 | |
| @@ -244,7 +316,7 @@ async function dispatch(request: Request, url: URL, env: string, who: Who): Prom | ||
| 244 | 316 | const data = await form(request); |
| 245 | 317 | const title = cleanText(data.get("title"), 200); |
| 246 | 318 | 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 }); | |
| 248 | 320 | } |
| 249 | 321 | |
| 250 | 322 | 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 | ||
| 253 | 325 | const index = Number(data.get("index")); |
| 254 | 326 | if (!ENTITY_ID.test(columnId)) return boardBad(request, who, boardId, "column_id is required"); |
| 255 | 327 | 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 | }); | |
| 257 | 332 | } |
| 258 | 333 | |
| 259 | 334 | 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 }); | |
| 261 | 336 | } |
| 262 | 337 | } |
| 263 | 338 |
src/server.test.ts +148 −13
| @@ -2,14 +2,19 @@ import { expect, test } from "bun:test"; | ||
| 2 | 2 | import { mkdtempSync } from "node:fs"; |
| 3 | 3 | import { tmpdir } from "node:os"; |
| 4 | 4 | import { join } from "node:path"; |
| 5 | import { subscriberCount } from "./bus.ts"; | |
| 5 | 6 | |
| 6 | 7 | process.env.FORGE_APP_DATA = mkdtempSync(join(tmpdir(), "app-")); |
| 7 | 8 | process.env.PORT = "0"; |
| 8 | 9 | process.env.FORGE_APP_IDENTITY_KEY = "test-key"; |
| 9 | 10 | const { server } = await import("./server.ts"); |
| 10 | 11 | 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"); | |
| 12 | 13 | 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(); | |
| 13 | 18 | const KEY = "test-key"; |
| 14 | 19 | const identityHeaders = (id: string, name: string, role: "user" | "admin" = "user") => { |
| 15 | 20 | 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 | ||
| 325 | 330 | expect(await (await fetch(base + boardUrl)).text()).toContain("Bob added this"); |
| 326 | 331 | }); |
| 327 | 332 | |
| 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 () => { | |
| 329 | 339 | const id = await newBoard(); |
| 330 | 340 | const boardUrl = `/b/${id}`; |
| 331 | 341 | 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 | ||
| 335 | 345 | |
| 336 | 346 | const stream = await fetch(base + `${boardUrl}/events`); |
| 337 | 347 | 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"); | |
| 338 | 350 | const reader = stream.body!.getReader(); |
| 339 | 351 | const decoder = new TextDecoder(); |
| 340 | 352 | let buffer = ""; |
| 341 | async function nextChunk(): Promise<string> { | |
| 353 | async function nextFrame(): Promise<string> { | |
| 342 | 354 | while (!buffer.includes("\n\n")) { |
| 343 | 355 | const { value, done } = await reader.read(); |
| 344 | 356 | if (done) throw new Error("stream ended"); |
| 345 | 357 | buffer += decoder.decode(value, { stream: true }); |
| 346 | 358 | } |
| 347 | 359 | const at = buffer.indexOf("\n\n"); |
| 348 | const chunk = buffer.slice(0, at); | |
| 360 | const frame = buffer.slice(0, at); | |
| 349 | 361 | buffer = buffer.slice(at + 2); |
| 350 | return chunk; | |
| 362 | return frame; | |
| 351 | 363 | } |
| 352 | 364 | |
| 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 | ||
| 358 | 365 | 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); | |
| 362 | 497 | await reader.cancel(); |
| 363 | 498 | }); |
| 364 | 499 |
src/server.ts +9 −1
| @@ -49,7 +49,7 @@ export const server = Bun.serve({ | ||
| 49 | 49 | port: Number(process.env.PORT ?? 8080), |
| 50 | 50 | hostname: process.env.HOST ?? "127.0.0.1", |
| 51 | 51 | // 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. | |
| 53 | 53 | idleTimeout: 60, |
| 54 | 54 | // Never Bun's source-listing error page, in production or in a preview. |
| 55 | 55 | development: false, |
| @@ -87,6 +87,14 @@ export const server = Bun.serve({ | ||
| 87 | 87 | } |
| 88 | 88 | |
| 89 | 89 | 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.
No forge identity on the wire. The rest of the round is right too. 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 One small thing, not worth another round: 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 |
||
| 95 | response.body?.cancel(); | |
| 96 | return new Response(null, { status: response.status, headers: response.headers }); | |
| 97 | } | |
| 90 | 98 | const body = await response.arrayBuffer(); |
| 91 | 99 | const headers = new Headers(response.headers); |
| 92 | 100 | 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-")); | ||
| 14 | 14 | process.env.PORT = "0"; |
| 15 | 15 | process.env.FORGE_APP_IDENTITY_KEY = "test-key"; |
| 16 | 16 | const { server } = await import("./server.ts"); |
| 17 | const { boardCreationBucket } = await import("./limits.ts"); | |
| 17 | 18 | const base = `http://${server.hostname}:${server.port}`; |
| 18 | 19 | |
| 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 | ||
| 19 | 25 | test("the stylesheet follows the system theme and lets an explicit choice override it", async () => { |
| 20 | 26 | const page = await (await fetch(base + "/")).text(); |
| 21 | 27 | expect(page).toContain("prefers-color-scheme: dark"); |
static/board.7793265334.js → static/board.109353762.js renamed +209 −41
| @@ -18,8 +18,11 @@ | ||
| 18 | 18 | } |
| 19 | 19 | |
| 20 | 20 | // 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(); | |
| 23 | 26 | function post(path, data) { |
| 24 | 27 | return fetch(path, { |
| 25 | 28 | method: "POST", |
| @@ -35,9 +38,12 @@ | ||
| 35 | 38 | const cardsOf = (columnEl) => Array.from(columnEl.querySelectorAll(".card")); |
| 36 | 39 | const indexOf = (cardEl) => cardsOf(cardEl.closest(".column")).indexOf(cardEl); |
| 37 | 40 | 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)}"]`); | |
| 38 | 43 | |
| 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; | |
| 41 | 47 | const all = col.querySelectorAll(".card").length; |
| 42 | 48 | const visible = col.querySelectorAll(".card:not([hidden])").length; |
| 43 | 49 | col.querySelector(".count").textContent = `${visible}/${all}`; |
| @@ -117,20 +123,18 @@ | ||
| 117 | 123 | if (!dragging) return; |
| 118 | 124 | e.preventDefault(); |
| 119 | 125 | }); |
| 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 | }); | |
| 132 | 136 | } |
| 133 | attachDropListeners(); | |
| 137 | for (const list of root.querySelectorAll(".cards")) attachDropListenersTo(list); | |
| 134 | 138 | |
| 135 | 139 | // ---- touch: a long press (no real drag events on a phone) picks a card |
| 136 | 140 | // up, pointermove carries it, and pointerup drops it through the same |
| @@ -391,39 +395,203 @@ | ||
| 391 | 395 | // Guarded so this file still runs where EventSource doesn't exist (the |
| 392 | 396 | // drag test's synthetic environment); a real browser always has it. |
| 393 | 397 | 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() { | |
| 401 | 425 | 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 | } | |
| 404 | 460 | return; |
| 405 | 461 | } |
| 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"); | |
| 412 | 477 | const current = root.querySelector(".board"); |
| 413 | 478 | 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 | } | |
| 417 | 579 | } |
| 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()); | |
| 421 | 580 | |
| 422 | 581 | const source = new EventSource(`/b/${boardId}/events`); |
| 423 | 582 | 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; | |
| 427 | 595 | }; |
| 428 | 596 | } |
| 429 | 597 | })(); |
Round two, and nothing from the last review was addressed: between
661ffd7and this head the only changes to this pull's own files are the merge ofmainplus nine lines ofstatic/board.jsand four ofsrc/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 fromPOST /mcp tools/calleach arrived on an open/eventsstream within a second, correctly scoped, with the security floor andcache-control: no-store;/events404s an unknown board; the per-board unsubscribe is clean.src/bus.tsis the right shape and no board content crosses the bus.1 (high, fix first, unchanged from last round):
HEAD /b/<id>/eventsnever answers, and each one holds a subscriber slot. On the preview at this head, a minute ago:And run against this branch locally, with
subscriberCountimported: while one HEAD is open the fetch promise has not settled andsubscriberCount(boardId)is1; it drops back to0only when the client goes away. The cause issrc/server.ts:89-93— a HEAD is routed as a GET and thenawait response.arrayBuffer(), which for an endless stream never settles. So 100 unauthenticated one-line HEADs held open makeeventStreamanswer503to 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.tsbefore 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 returnnew Response(null, { status: response.status, headers })instead of buffering it. Cover it with a test thatHEAD /b/<id>/eventsanswers promptly and leavessubscriberCount(boardId)at0. 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, thepublishhelper insrc/routes.ts:26and the one insrc/mcp.ts:16putby: { id, name }on the wire for every event;static/board.409682029.jsonly ever readsevent.clientandevent.kind/event.ids—byappears nowhere in it. The page names exactly one person, the owner. So today anyone holding a board link can sit on/eventsand harvest the forge id and display name of every signed-in person who touches that board. Keep the field inBoardEventif you want it for later, but do not serialize the id to subscribers: one line ineventStream'ssend, sending{ name }at most, and ideally nothing until the page shows it.3 (medium, new):
MAX_BOARDS_CREATED_PER_MINUTEwas 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 newlive-refresh.test.tscases anddrag.test.ts— not with a clear message but withTypeError: null is not an object, because the 429 page has nodata-column-idin 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: restore30(and the README line) and give the tests their own bucket — export a reset onboardCreationBucket, or build it from an injected clock the tests advance.4 (medium, new): two new behaviours have no test.
MAX_SUBSCRIBERS_PER_BOARD/ the503is new and nothing covers it, though the issue named the cap as a risk; andsrc/mcp.tsnow publishes, which is the direction's headline ("two people and one agent"), yet deleting bothpublish(...)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_cardoverPOST /mcpproduces acard.addedframe on an open stream.5 (low, new): events apply concurrently, so a burst can land a card in the wrong place.
apply()callsapplyNow(event)without awaiting, andpending.splice(0).forEach(applyNow)does the same, while every non-delete event does its own fullfreshBoard()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.tsstill 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);pendinggrows unbounded while an input stays focused;column.added/column.deleteddo not update the per-card "Move to column" options althoughcolumn.renameddoes;column.renamed'sfreshColumn.querySelector("header form.rename input").valueis not null-guarded like its siblings; and the droppedclaimevent 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.