@bigmistqke/whiteboard 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +31 -12
  2. package/bin/whiteboard.ts +74 -17
  3. package/dist/bin/whiteboard.js +93 -22
  4. package/dist/client/runtime.js +164 -11
  5. package/dist/plugins/chat/README.md +2 -1
  6. package/dist/plugins/chat/client.js +2 -2
  7. package/dist/plugins/chat/index.js +1 -0
  8. package/dist/plugins/chat/style.css +7 -0
  9. package/dist/plugins/code/diff.js +1 -0
  10. package/dist/plugins/comments/client.js +6 -6
  11. package/dist/plugins/comments/index.js +4 -1
  12. package/dist/plugins/comments/style.css +8 -0
  13. package/dist/plugins/forge/README.md +12 -0
  14. package/dist/plugins/forge/index.js +83 -0
  15. package/dist/plugins/gallery/client.js +1 -1
  16. package/dist/plugins/iframe/README.md +18 -0
  17. package/dist/plugins/iframe/client.js +1 -0
  18. package/dist/plugins/iframe/index.js +40 -0
  19. package/dist/plugins/iframe/style.css +29 -0
  20. package/dist/plugins/index.js +4 -0
  21. package/dist/plugins/mermaid/index.js +1 -0
  22. package/dist/solid/index.js +2 -1
  23. package/dist/src/client/page/base.css +33 -12
  24. package/dist/src/client/page/main.js +246 -22
  25. package/dist/src/events.js +24 -3
  26. package/dist/src/icons.js +6 -0
  27. package/dist/src/loader.js +12 -6
  28. package/dist/src/pages/blocks.js +1 -0
  29. package/dist/src/pages/index.js +3 -2
  30. package/dist/src/pages/markdown.js +107 -4
  31. package/dist/src/pages/render.js +63 -9
  32. package/dist/src/server.js +37 -12
  33. package/dist/src/status.js +38 -10
  34. package/package.json +1 -1
  35. package/plugins/chat/README.md +2 -1
  36. package/plugins/chat/client.tsx +15 -3
  37. package/plugins/chat/index.ts +1 -1
  38. package/plugins/chat/style.css +7 -0
  39. package/plugins/code/diff.ts +7 -1
  40. package/plugins/comments/client.ts +50 -6
  41. package/plugins/comments/index.ts +4 -2
  42. package/plugins/comments/style.css +8 -0
  43. package/plugins/forge/README.md +12 -0
  44. package/plugins/forge/index.ts +71 -0
  45. package/plugins/iframe/README.md +18 -0
  46. package/plugins/iframe/client.ts +46 -0
  47. package/plugins/iframe/index.ts +54 -0
  48. package/plugins/iframe/style.css +29 -0
  49. package/plugins/index.ts +3 -1
  50. package/plugins/mermaid/index.ts +1 -0
  51. package/skills/whiteboard/SKILL.md +17 -7
  52. package/solid/index.tsx +3 -0
  53. package/src/client/forms.ts +5 -6
  54. package/src/client/markdown.ts +36 -0
  55. package/src/client/page/base.css +33 -12
  56. package/src/client/page/elsewhere.ts +70 -0
  57. package/src/client/page/live.ts +30 -0
  58. package/src/client/page/main.ts +25 -2
  59. package/src/client/page/sort.ts +38 -0
  60. package/src/client/page/waiting.ts +102 -29
  61. package/src/client/read.ts +73 -0
  62. package/src/client/runtime.ts +13 -0
  63. package/src/client/toast.ts +25 -0
  64. package/src/define.ts +79 -13
  65. package/src/events.ts +27 -3
  66. package/src/icons.ts +8 -0
  67. package/src/loader.ts +7 -4
  68. package/src/pages/blocks.ts +3 -0
  69. package/src/pages/index.ts +8 -2
  70. package/src/pages/markdown.ts +92 -4
  71. package/src/pages/render.ts +49 -12
  72. package/src/server.ts +35 -12
  73. package/src/status.ts +64 -20
package/README.md CHANGED
@@ -271,7 +271,7 @@ upward with a `.whiteboard/` folder.
271
271
  | `whiteboard url <page\|file>` | the same |
272
272
  | `whiteboard docs [name]` | print how to write pages in this project: the blocks, then each plugin's docs; with a name, only that plugin's |
273
273
  | `whiteboard events [filters] [--follow]` | print recorded events; with `--follow`, then each new one as it comes, marking nothing |
274
- | `whiteboard wait [filters]` | print the next matching event not handed out before, waiting for it if needed |
274
+ | `whiteboard wait [filters]` | print the next matching event not handed out before, waiting for it if needed; without `--page`, only what no other wait or watch would take (the fallback, one per project) |
275
275
  | `whiteboard watch [filters]` | like `wait`, but never exits: print each matching event once |
276
276
  | `whiteboard append --page <p> --type <t> [--data <json>]` | add an event to a page's log, such as a reply to a comment |
277
277
  | `whiteboard pick <event id>` | record an event as picked up, as `wait` does when it hands one out |
@@ -307,8 +307,8 @@ export default defineConfig({
307
307
  })
308
308
  ```
309
309
 
310
- The built-in plugins are callout, chat, code, comments, details, form,
311
- gallery, grid, mermaid and quiet: every project has them, and
310
+ The built-in plugins are callout, chat, code, comments, details, forge,
311
+ form, gallery, grid, iframe, mermaid and quiet: every project has them, and
312
312
  `whiteboard docs` shows how to write each. A config's `plugins` add to them,
313
313
  and one with a built-in's name replaces it. The terminal and the Claude Code
314
314
  plugin are opt-in, since they run code or are about one agent.
@@ -451,6 +451,7 @@ export default function mount(root, page, api) {
451
451
  has the block's attributes, label, content as mdast nodes, `toHtml`,
452
452
  `sections` and more), `props(ctx)` (JSON for its client), `client` (a
453
453
  browser module, mounted per block), `style` (linked on pages that use it),
454
+ `fence: true` to also take the code fences of its name (```` ```mermaid ````),
454
455
  and `fence: 'any'` for the block that takes every code fence nobody else
455
456
  claims. Block names are unique across a project's plugins.
456
457
  - **`events`**, by type (`<plugin>:<what>`): a description each, and
@@ -482,8 +483,9 @@ is replaced on a live update; it replaces the server's HTML when it mounts.
482
483
  A page module (`setup`'s `client`) gets `mount(root, page, api)`. Both get
483
484
  the page's `api`: its events and `append` (which comes back through
484
485
  `onEvents`), the listeners, `onRendered` (after a live update, to put back
485
- what it adds), `corner()` for floating buttons, `badge()` for counts in the
486
- tab title, and the theme. Files beside a browser module that are browser
486
+ what it adds), `corner()` for floating buttons, `toast()` for a message
487
+ at the bottom of the window, `badge()` for counts in the tab title, and the
488
+ theme. Files beside a browser module that are browser
487
489
  assets (scripts, styles, images, fonts) are served too.
488
490
 
489
491
  Something that covers the bottom of the window says how much in
@@ -526,14 +528,31 @@ Not started.
526
528
  send it, across live updates and reloads. Sending confirms itself.
527
529
  - **A chat under every form,** to ask about a question without answering
528
530
  it: a message is never a submit. `:::chat{name=…}` puts one anywhere.
529
- - **What waits on whom.** A form is waiting for you (an agent listens for
530
- it), nobody listening, waiting for the agent (answered, not yet picked
531
- up), or decided: then it folds to one line quoting the answer, with its
532
- chat still under it, and a click opens it again. A line above the page
533
- counts them, a button jumps to the next form waiting for you, and the tab
534
- title gets a `(!n)` prefix.
531
+ - **What waits for you.** Your to-do, not whether an agent's process runs:
532
+ a question you haven't answered (or one the agent asks again), and a
533
+ message from the agent you haven't read (a reply to your comment, a chat
534
+ message). A message is read once it has been in view, and that is
535
+ recorded in the log, so it holds in every browser. An answered form waits
536
+ for the agent until it picks the answer up, then it is decided and folds
537
+ to one line quoting the answer, with its chat still under it; a click
538
+ opens it again. A line above the page counts all this, a button goes to
539
+ the next thing waiting for you, unread messages get a toast that stays,
540
+ and the tab title gets a `(!n)` prefix. An answer sent while no agent
541
+ listens says so in a toast; it stays in the log for the next agent that
542
+ checks.
543
+ - **Whether an agent listens.** The dot at the end of the header is green
544
+ while the page is live and an agent takes its answers, grey when nobody
545
+ listens (answers wait in the log), and a ring while the page reconnects.
546
+ - **What waits on other pages.** The header shows an inbox with how much
547
+ waits for you on other pages; it opens a list of those pages, and a page
548
+ in it opens at the first thing. The overview marks the same pages with
549
+ the inbox.
550
+ - **Messages are markdown.** Comments, replies and chat messages, yours
551
+ and the agent's: code, lists, links, `#12`, rendered like a page, but raw
552
+ HTML and blocks show as written.
535
553
  - **Comments.** Select any passage and comment on it; the agent replies in
536
- the thread or edits the page. Passages are found again after edits.
554
+ the thread or edits the page. Passages are found again after edits. A
555
+ thread with a reply you haven't read has a dot on its badge.
537
556
  - **What changed.** A block you haven't seen gets a bar until it has been
538
557
  in view a moment, remembered per page, so coming back shows what changed
539
558
  since. `:::quiet` content never counts as new.
package/bin/whiteboard.ts CHANGED
@@ -13,8 +13,8 @@ import { pluginCommands, parseCommandArgs, usage } from '../src/plugins.ts'
13
13
  import { projectToken } from '../src/auth.ts'
14
14
  import { packagePath } from '../src/package.ts'
15
15
  import { runningServer } from '../src/running.ts'
16
- import { statusLines, whose } from '../src/status.ts'
17
- import type { PageStatus, WbEvent } from '../src/define.ts'
16
+ import { statusLines, takenByOther, whose } from '../src/status.ts'
17
+ import type { Listener, PageStatus, WbEvent } from '../src/define.ts'
18
18
 
19
19
  // a failing command prints its message, not a stack trace
20
20
  const fail = (err: unknown) => {
@@ -44,6 +44,8 @@ const HELP = `whiteboard — markdown pages in the browser, what the reader does
44
44
 
45
45
  filters: --page <page|file> (includes pages below it) --type <type>
46
46
  wait: --timeout <seconds> (exit 2 on timeout) --count <n> (default 1)
47
+ wait, watch without --page: the fallback, taking only what no other wait or watch would, on any
48
+ page, also once they stop; one per project (a second exits 1)
47
49
  events: --since <iso time or event id> --last <n>
48
50
 
49
51
  Every command works on the project of the current folder: the nearest folder upward with a
@@ -135,22 +137,68 @@ async function api(route: string): Promise<any> {
135
137
  * what is waited for. Holds one connection open, the listener; reconnects when the server restarts.
136
138
  * Reading the log does not depend on it, so answers are never missed when the server is away.
137
139
  */
138
- function listen(f: EventFilter, command: 'wait' | 'watch') {
139
- const connect = async () => {
140
- let base
141
- try { base = await ensureServer() } catch { return setTimeout(connect, 2000).unref() }
142
- const q = new URLSearchParams({ command, ...(f.page ? { page: f.page } : {}), ...(f.type ? { type: f.type } : {}) })
140
+ /**
141
+ * Tell the server who is listening, for as long as the command runs (again after a restart). The
142
+ * fallback is refused when another one runs: it exits, saying so. Resolves once the server took it.
143
+ */
144
+ function listen(f: EventFilter, command: 'wait' | 'watch', fallback = false): Promise<void> {
145
+ return new Promise(registered => {
146
+ const connect = async () => {
147
+ let base
148
+ try { base = await ensureServer() } catch { return setTimeout(connect, 2000).unref() }
149
+ const q = new URLSearchParams({ command, ...(f.page ? { page: f.page } : {}), ...(f.type ? { type: f.type } : {}), ...(fallback ? { fallback: '' } : {}) })
150
+ let again = false
151
+ const retry = (ms: number) => { if (!again) { again = true; setTimeout(connect, ms).unref() } }
152
+ const req = http.get(`${base}/api/listen?${q}`, res => {
153
+ if (res.statusCode === 409) {
154
+ console.error('whiteboard: another agent already takes what no other listener does (a wait or watch without --page; one per project). Add --page to wait on a page of your own.')
155
+ process.exit(1)
156
+ }
157
+ res.resume()
158
+ registered()
159
+ res.on('close', () => retry(1000))
160
+ })
161
+ req.on('error', () => retry(2000))
162
+ // the connection alone does not keep the command running
163
+ req.on('socket', socket => socket.unref())
164
+ }
165
+ connect()
166
+ })
167
+ }
168
+
169
+ /**
170
+ * Who else listens, kept current: the fallback leaves to them what they would take. Calls
171
+ * `changed` after each change (the server's live channel says when).
172
+ */
173
+ async function otherListeners(changed: () => void): Promise<() => Listener[]> {
174
+ let list: Listener[] = []
175
+ const load = async () => {
176
+ try { list = await (await fetch(`${await ensureServer()}/api/listeners`)).json() as Listener[] } catch { /* the server restarts */ }
177
+ changed()
178
+ }
179
+ const follow = async () => {
143
180
  let again = false
144
- const retry = (ms: number) => { if (!again) { again = true; setTimeout(connect, ms).unref() } }
145
- const req = http.get(`${base}/api/listen?${q}`, res => {
146
- res.resume()
147
- res.on('close', () => retry(1000))
181
+ const retry = () => { if (!again) { again = true; setTimeout(follow, 1000).unref() } }
182
+ let base
183
+ try { base = await ensureServer() } catch { return retry() }
184
+ const req = http.get(`${base}/api/watch?dir`, res => {
185
+ let buf = ''
186
+ res.setEncoding('utf8')
187
+ res.on('data', (chunk: string) => {
188
+ buf += chunk
189
+ if (buf.includes('event: listeners')) { buf = ''; load() }
190
+ if (buf.length > 4096) buf = buf.slice(-64)
191
+ })
192
+ res.on('close', retry)
193
+ // reconnected after a restart: who listens now
194
+ load()
148
195
  })
149
- req.on('error', () => retry(2000))
150
- // the connection alone does not keep the command running
196
+ req.on('error', retry)
151
197
  req.on('socket', socket => socket.unref())
152
198
  }
153
- connect()
199
+ await load()
200
+ follow()
201
+ return () => list
154
202
  }
155
203
 
156
204
  function init(name: string | undefined) {
@@ -219,6 +267,7 @@ async function status() {
219
267
  currentSession(proj),
220
268
  ])
221
269
  const busy = pages.filter(p => p.unpicked.length || p.open.length)
270
+ if (pages.some(p => p.listeners.some(l => l.fallback))) console.log('a fallback listens: it takes what no other wait or watch would\n')
222
271
  if (!busy.length) { console.log('nothing open: every question is answered, and every answer picked up'); return }
223
272
  for (const p of busy) {
224
273
  console.log(`${p.page} (${whose(p, session)})`)
@@ -345,9 +394,17 @@ switch (cmd) {
345
394
  const proj = needProject()
346
395
  const f = filter()
347
396
  const { handedOut } = await projectConfig(proj)
348
- handOut(proj.eventsFile, f, e => console.log(JSON.stringify(e)), { count: cmd === 'wait' ? Number(opts.count ?? 1) : Infinity, forAgent: forAgent(handedOut) })
349
- .then(() => process.exit(0))
350
- listen(f, cmd)
397
+ // without --page, the fallback: only what no other listener would take, on any page, as it comes
398
+ // and once they stop listening (an answer left in the log, too)
399
+ const fallback = !f.page
400
+ let recheck = () => {}
401
+ const others = fallback ? (await listen(f, cmd, true), await otherListeners(() => recheck())) : null
402
+ handOut(proj.eventsFile, f, e => console.log(JSON.stringify(e)), {
403
+ count: cmd === 'wait' ? Number(opts.count ?? 1) : Infinity,
404
+ forAgent: forAgent(handedOut),
405
+ ...(others && { skip: e => takenByOther(others(), e), recheck: again => { recheck = again } }),
406
+ }).then(() => process.exit(0))
407
+ if (!fallback) listen(f, cmd)
351
408
  if (opts.timeout && cmd === 'wait') setTimeout(() => { console.error('timeout'); process.exit(2) }, Number(opts.timeout) * 1000)
352
409
  break
353
410
  }
@@ -6,7 +6,7 @@ import { parseCommandArgs, pluginCommands, usage } from "../src/plugins.js";
6
6
  import { projectToken } from "../src/auth.js";
7
7
  import { packagePath } from "../src/package.js";
8
8
  import { runningServer } from "../src/running.js";
9
- import { statusLines, whose } from "../src/status.js";
9
+ import { statusLines, takenByOther, whose } from "../src/status.js";
10
10
  import fs from "node:fs";
11
11
  import os from "node:os";
12
12
  import path from "node:path";
@@ -41,6 +41,8 @@ const HELP = `whiteboard — markdown pages in the browser, what the reader does
41
41
 
42
42
  filters: --page <page|file> (includes pages below it) --type <type>
43
43
  wait: --timeout <seconds> (exit 2 on timeout) --count <n> (default 1)
44
+ wait, watch without --page: the fallback, taking only what no other wait or watch would, on any
45
+ page, also once they stop; one per project (a second exits 1)
44
46
  events: --since <iso time or event id> --last <n>
45
47
 
46
48
  Every command works on the project of the current folder: the nearest folder upward with a
@@ -150,34 +152,93 @@ async function api(route) {
150
152
  * what is waited for. Holds one connection open, the listener; reconnects when the server restarts.
151
153
  * Reading the log does not depend on it, so answers are never missed when the server is away.
152
154
  */
153
- function listen(f, command) {
154
- const connect = async () => {
155
- let base;
155
+ /**
156
+ * Tell the server who is listening, for as long as the command runs (again after a restart). The
157
+ * fallback is refused when another one runs: it exits, saying so. Resolves once the server took it.
158
+ */
159
+ function listen(f, command, fallback = false) {
160
+ return new Promise((registered) => {
161
+ const connect = async () => {
162
+ let base;
163
+ try {
164
+ base = await ensureServer();
165
+ } catch {
166
+ return setTimeout(connect, 2e3).unref();
167
+ }
168
+ const q = new URLSearchParams({
169
+ command,
170
+ ...f.page ? { page: f.page } : {},
171
+ ...f.type ? { type: f.type } : {},
172
+ ...fallback ? { fallback: "" } : {}
173
+ });
174
+ let again = false;
175
+ const retry = (ms) => {
176
+ if (!again) {
177
+ again = true;
178
+ setTimeout(connect, ms).unref();
179
+ }
180
+ };
181
+ const req = http.get(`${base}/api/listen?${q}`, (res) => {
182
+ if (res.statusCode === 409) {
183
+ console.error("whiteboard: another agent already takes what no other listener does (a wait or watch without --page; one per project). Add --page to wait on a page of your own.");
184
+ process.exit(1);
185
+ }
186
+ res.resume();
187
+ registered();
188
+ res.on("close", () => retry(1e3));
189
+ });
190
+ req.on("error", () => retry(2e3));
191
+ req.on("socket", (socket) => socket.unref());
192
+ };
193
+ connect();
194
+ });
195
+ }
196
+ /**
197
+ * Who else listens, kept current: the fallback leaves to them what they would take. Calls
198
+ * `changed` after each change (the server's live channel says when).
199
+ */
200
+ async function otherListeners(changed) {
201
+ let list = [];
202
+ const load = async () => {
156
203
  try {
157
- base = await ensureServer();
158
- } catch {
159
- return setTimeout(connect, 2e3).unref();
160
- }
161
- const q = new URLSearchParams({
162
- command,
163
- ...f.page ? { page: f.page } : {},
164
- ...f.type ? { type: f.type } : {}
165
- });
204
+ list = await (await fetch(`${await ensureServer()}/api/listeners`)).json();
205
+ } catch {}
206
+ changed();
207
+ };
208
+ const follow = async () => {
166
209
  let again = false;
167
- const retry = (ms) => {
210
+ const retry = () => {
168
211
  if (!again) {
169
212
  again = true;
170
- setTimeout(connect, ms).unref();
213
+ setTimeout(follow, 1e3).unref();
171
214
  }
172
215
  };
173
- const req = http.get(`${base}/api/listen?${q}`, (res) => {
174
- res.resume();
175
- res.on("close", () => retry(1e3));
216
+ let base;
217
+ try {
218
+ base = await ensureServer();
219
+ } catch {
220
+ return retry();
221
+ }
222
+ const req = http.get(`${base}/api/watch?dir`, (res) => {
223
+ let buf = "";
224
+ res.setEncoding("utf8");
225
+ res.on("data", (chunk) => {
226
+ buf += chunk;
227
+ if (buf.includes("event: listeners")) {
228
+ buf = "";
229
+ load();
230
+ }
231
+ if (buf.length > 4096) buf = buf.slice(-64);
232
+ });
233
+ res.on("close", retry);
234
+ load();
176
235
  });
177
- req.on("error", () => retry(2e3));
236
+ req.on("error", retry);
178
237
  req.on("socket", (socket) => socket.unref());
179
238
  };
180
- connect();
239
+ await load();
240
+ follow();
241
+ return () => list;
181
242
  }
182
243
  function init(name) {
183
244
  const dir = process.cwd();
@@ -234,6 +295,7 @@ async function status() {
234
295
  const proj = needProject();
235
296
  const [pages, session] = await Promise.all([api(`/api/status${opts.page ? `?page=${encodeURIComponent(pageId(proj, opts.page))}` : ""}`), currentSession(proj)]);
236
297
  const busy = pages.filter((p) => p.unpicked.length || p.open.length);
298
+ if (pages.some((p) => p.listeners.some((l) => l.fallback))) console.log("a fallback listens: it takes what no other wait or watch would\n");
237
299
  if (!busy.length) {
238
300
  console.log("nothing open: every question is answered, and every answer picked up");
239
301
  return;
@@ -364,11 +426,20 @@ switch (cmd) {
364
426
  const proj = needProject();
365
427
  const f = filter();
366
428
  const { handedOut } = await projectConfig(proj);
429
+ const fallback = !f.page;
430
+ let recheck = () => {};
431
+ const others = fallback ? (await listen(f, cmd, true), await otherListeners(() => recheck())) : null;
367
432
  handOut(proj.eventsFile, f, (e) => console.log(JSON.stringify(e)), {
368
433
  count: cmd === "wait" ? Number(opts.count ?? 1) : Infinity,
369
- forAgent: forAgent(handedOut)
434
+ forAgent: forAgent(handedOut),
435
+ ...others && {
436
+ skip: (e) => takenByOther(others(), e),
437
+ recheck: (again) => {
438
+ recheck = again;
439
+ }
440
+ }
370
441
  }).then(() => process.exit(0));
371
- listen(f, cmd);
442
+ if (!fallback) listen(f, cmd);
372
443
  if (opts.timeout && cmd === "wait") setTimeout(() => {
373
444
  console.error("timeout");
374
445
  process.exit(2);
@@ -38,8 +38,7 @@ function html(strings, ...values) {
38
38
  const isQuestionName = (name) => !!name && !name.includes(":");
39
39
  /** The states, in the order a reader should see them: what waits on them first. */
40
40
  const STATES = [
41
- "waiting",
42
- "unheard",
41
+ "open",
43
42
  "pending",
44
43
  "decided"
45
44
  ];
@@ -50,18 +49,34 @@ const STATES = [
50
49
  const fromReader = (event) => event.from !== "cli";
51
50
  /**
52
51
  * Where the question `name` stands. `events` are the page's, `listeners` the running waits and
53
- * watches that cover the page, `pickedUp` whether an event was handed to an agent. `last` is its
54
- * latest answer: the reader's latest event of its name.
52
+ * watches that cover the page (only one asking for it by name counts: it asks again),
53
+ * `pickedUp` whether an event was handed to an agent. `last` is its latest answer: the reader's
54
+ * latest event of its name.
55
55
  */
56
56
  function questionState(name, events, listeners, pickedUp) {
57
57
  const last = events.findLast((e) => e.type === name && fromReader(e));
58
- const asked = listeners.some((l) => l.type === name);
59
- const any = listeners.some((l) => l.type === null);
58
+ const askedAgain = listeners.some((l) => !l.fallback && l.type === name);
60
59
  return {
61
- state: asked || any && !last ? "waiting" : !last ? "unheard" : pickedUp(last.id) ? "decided" : "pending",
60
+ state: !last ? "open" : !pickedUp(last.id) ? "pending" : askedAgain ? "open" : "decided",
62
61
  last
63
62
  };
64
63
  }
64
+ /** The type of the event the page appends once messages were in view: `{ ids }`. */
65
+ const READ = "whiteboard:read";
66
+ /**
67
+ * The agent's messages on a page the reader hasn't read: events from the agent of a type
68
+ * `isMessage` says is for the reader, not named by a `whiteboard:read` from the reader, and not
69
+ * replaced by a later one (`replaces`).
70
+ */
71
+ function unreadMessages(events, isMessage) {
72
+ const read = /* @__PURE__ */ new Set();
73
+ const replaced = /* @__PURE__ */ new Set();
74
+ for (const e of events) {
75
+ if (e.type === "whiteboard:read" && fromReader(e)) for (const id of e.data?.ids ?? []) read.add(String(id));
76
+ if (e.data?.replaces) replaced.add(String(e.data.replaces));
77
+ }
78
+ return events.filter((e) => !fromReader(e) && isMessage(e.type) && !read.has(e.id) && !replaced.has(e.id));
79
+ }
65
80
  // src/client/forms.ts
66
81
  let root$1;
67
82
  let api$1;
@@ -159,8 +174,7 @@ async function onSubmit(e) {
159
174
  }
160
175
  }
161
176
  const ATTR = {
162
- waiting: "data-wb-waiting",
163
- unheard: "data-wb-unheard",
177
+ open: "data-wb-open",
164
178
  pending: "data-wb-pending",
165
179
  decided: "data-wb-decided"
166
180
  };
@@ -182,10 +196,10 @@ let current = [];
182
196
  const justSent = /* @__PURE__ */ new WeakMap();
183
197
  /** Mark every form from the log and the listeners, then tell whoever follows. */
184
198
  function mark() {
185
- const waitingFor = api$1.listeners();
199
+ const listening = api$1.listeners();
186
200
  current = forms().map((form) => {
187
201
  const name = form.getAttribute("name");
188
- const { state, last } = questionState(name, api$1.events(), waitingFor, api$1.pickedUp);
202
+ const { state, last } = questionState(name, api$1.events(), listening, api$1.pickedUp);
189
203
  for (const st of STATES) form.toggleAttribute(ATTR[st], st === state);
190
204
  if (state === "decided") form.dataset.wbOutcome = outcome(last.data, last.action);
191
205
  else delete form.dataset.wbOutcome;
@@ -232,6 +246,132 @@ const formsApi = {
232
246
  };
233
247
  }
234
248
  };
249
+ // src/client/toast.ts
250
+ const box = document.createElement("div");
251
+ box.id = "wb-toasts";
252
+ box.setAttribute("role", "status");
253
+ box.setAttribute("aria-live", "polite");
254
+ function toast(text, { kind = "info", ms = 7e3, onClick } = {}) {
255
+ if (!box.isConnected) document.body.append(box);
256
+ const el = document.createElement("div");
257
+ el.className = "wb-toast";
258
+ el.dataset.kind = kind;
259
+ if (onClick) el.dataset.action = "";
260
+ el.textContent = text;
261
+ const close = () => el.remove();
262
+ el.addEventListener("click", () => {
263
+ if (ms) close();
264
+ onClick?.();
265
+ });
266
+ if (ms) setTimeout(close, ms);
267
+ box.append(el);
268
+ return {
269
+ close,
270
+ update: (next) => {
271
+ el.textContent = next;
272
+ }
273
+ };
274
+ }
275
+ // src/client/read.ts
276
+ let isMessage = () => false;
277
+ let getEvents = () => [];
278
+ let send = () => {};
279
+ const sending = /* @__PURE__ */ new Set();
280
+ const unread = () => unreadMessages(getEvents(), isMessage).filter((e) => !sending.has(e.id));
281
+ const queued = /* @__PURE__ */ new Set();
282
+ let timer = 0;
283
+ function markRead(ids) {
284
+ const open = new Set(unread().map((e) => e.id));
285
+ const fresh = ids.filter((id) => open.has(id));
286
+ if (!fresh.length) return;
287
+ for (const id of fresh) {
288
+ sending.add(id);
289
+ queued.add(id);
290
+ }
291
+ clearTimeout(timer);
292
+ timer = window.setTimeout(() => {
293
+ const batch = [...queued];
294
+ queued.clear();
295
+ if (batch.length) send(batch);
296
+ }, 300);
297
+ }
298
+ /** Once the log has the reads, they need no holding. */
299
+ function readsArrived(events) {
300
+ for (const e of events) if (e.type === "whiteboard:read") for (const id of e.data?.ids ?? []) sending.delete(String(id));
301
+ }
302
+ const inView = /* @__PURE__ */ new Set();
303
+ const seen = new IntersectionObserver((entries) => {
304
+ for (const entry of entries) {
305
+ const id = entry.target.dataset.wbMessage;
306
+ if (entry.isIntersecting) inView.add(id);
307
+ else inView.delete(id);
308
+ }
309
+ readVisible();
310
+ }, { threshold: .6 });
311
+ function readVisible() {
312
+ if (document.visibilityState === "visible" && inView.size) markRead([...inView]);
313
+ }
314
+ const observed = /* @__PURE__ */ new WeakSet();
315
+ function observeMessages() {
316
+ const open = new Set(unread().map((e) => e.id));
317
+ for (const el of document.querySelectorAll("[data-wb-message]")) {
318
+ if (observed.has(el) || !open.has(el.dataset.wbMessage)) continue;
319
+ observed.add(el);
320
+ seen.observe(el);
321
+ }
322
+ }
323
+ function trackReading(options) {
324
+ const types = new Set(options.messages);
325
+ isMessage = (type) => types.has(type);
326
+ getEvents = options.events;
327
+ send = options.send;
328
+ new MutationObserver(observeMessages).observe(document.body, {
329
+ childList: true,
330
+ subtree: true
331
+ });
332
+ document.addEventListener("visibilitychange", readVisible);
333
+ observeMessages();
334
+ }
335
+ /** After the events changed: messages that came since may already be on screen. */
336
+ const messagesChanged = () => observeMessages();
337
+ // src/client/markdown.ts
338
+ const cache = /* @__PURE__ */ new Map();
339
+ let queue = [];
340
+ async function flush() {
341
+ const batch = queue;
342
+ queue = [];
343
+ try {
344
+ const res = await fetch("/api/markdown", {
345
+ method: "POST",
346
+ headers: { "content-type": "application/json" },
347
+ body: JSON.stringify({ texts: batch.map((b) => b.text) })
348
+ });
349
+ if (!res.ok) throw new Error(await res.text());
350
+ const { html, styles } = await res.json();
351
+ for (const href of styles) if (![...document.querySelectorAll("link[rel=stylesheet]")].some((l) => new URL(l.href).pathname === new URL(href, location.href).pathname)) document.head.insertAdjacentHTML("beforeend", `<link rel="stylesheet" href="${href.replace(/"/g, "&quot;")}">`);
352
+ batch.forEach((b, i) => b.resolve(html[i] ?? ""));
353
+ } catch (err) {
354
+ for (const b of batch) {
355
+ cache.delete(b.text);
356
+ b.reject(err);
357
+ }
358
+ }
359
+ }
360
+ function markdown(text) {
361
+ let got = cache.get(text);
362
+ if (!got) {
363
+ got = new Promise((resolve, reject) => {
364
+ if (!queue.length) queueMicrotask(flush);
365
+ queue.push({
366
+ text,
367
+ resolve,
368
+ reject
369
+ });
370
+ });
371
+ cache.set(text, got);
372
+ }
373
+ return got;
374
+ }
235
375
  // src/client/runtime.ts
236
376
  const handoff = JSON.parse(document.getElementById("wb-page").textContent);
237
377
  const root = document.getElementById("wb-root");
@@ -241,7 +381,9 @@ let events = [];
241
381
  const eventListeners = /* @__PURE__ */ new Set();
242
382
  function setEvents(next) {
243
383
  events = next;
384
+ readsArrived(events);
244
385
  for (const fn of eventListeners) fn(events);
386
+ messagesChanged();
245
387
  }
246
388
  async function loadEvents() {
247
389
  setEvents((await (await fetch(`/api/events?page=${encodeURIComponent(page)}`)).json()).filter((e) => e.page === page));
@@ -286,6 +428,9 @@ const api = {
286
428
  },
287
429
  last: (type) => events.findLast((e) => e.type === type),
288
430
  pickedUp: (id) => !!events.find((e) => e.id === id)?.pickedUp,
431
+ unread,
432
+ markRead,
433
+ markdown,
289
434
  append,
290
435
  listeners: () => listeners,
291
436
  onListeners(fn) {
@@ -313,6 +458,7 @@ const api = {
313
458
  baseTitle = title;
314
459
  writeTitle();
315
460
  },
461
+ toast,
316
462
  ...formsApi
317
463
  };
318
464
  const changeListeners = /* @__PURE__ */ new Set();
@@ -378,6 +524,13 @@ if (handoff.client) try {
378
524
  root.insertAdjacentHTML("afterbegin", String(html`<pre class="wb-error" role="alert">the page failed to start: ${err.message}</pre>`));
379
525
  }
380
526
  trackForms(root, page, api);
527
+ trackReading({
528
+ messages: handoff.messages ?? [],
529
+ events: () => events,
530
+ send: (ids) => {
531
+ append(READ, { ids }).catch((err) => console.error("marking read:", err));
532
+ }
533
+ });
381
534
  await Promise.all((handoff.plugins ?? []).map(async (ext) => {
382
535
  try {
383
536
  const mount = (await import(ext.client)).default;
@@ -1,6 +1,7 @@
1
1
  A chat between the reader and you: the reader types (Enter sends,
2
2
  Shift+Enter starts a new line), you answer, the reader's messages on one side
3
- and yours on the other. Every form has one under it, for questions about the
3
+ and yours on the other. Messages are markdown (code, lists, links, `#12`);
4
+ raw HTML and blocks show as written. Every form has one under it, for questions about the
4
5
  question; a `chat` block puts one anywhere, for talk that isn't about a form.
5
6
 
6
7
  ```markdown