@bigmistqke/workpad 0.18.1 → 0.19.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 (55) hide show
  1. package/bin/workpad.ts +225 -21
  2. package/dist/bin/workpad.js +181 -15
  3. package/dist/plugins/badge/README.md +59 -10
  4. package/dist/plugins/badge/index.js +130 -8
  5. package/dist/plugins/badge/public/style.css +132 -12
  6. package/dist/plugins/chat/index.js +7 -1
  7. package/dist/plugins/claude/README.md +13 -5
  8. package/dist/plugins/claude/channel.js +25 -2
  9. package/dist/plugins/claude/doctor.js +43 -47
  10. package/dist/plugins/claude/index.js +24 -8
  11. package/dist/plugins/claude/session.js +46 -1
  12. package/dist/plugins/opencode/channel.js +42 -7
  13. package/dist/plugins/opencode/index.js +2 -0
  14. package/dist/src/agents.js +6 -1
  15. package/dist/src/events.js +6 -5
  16. package/dist/src/help.js +16 -4
  17. package/dist/src/hub.js +55 -2
  18. package/dist/src/listen.js +36 -4
  19. package/dist/src/listeners.js +14 -4
  20. package/dist/src/pages/board.js +9 -4
  21. package/dist/src/pages/index.js +2 -4
  22. package/dist/src/pages/markdown.js +47 -16
  23. package/dist/src/pages/render.js +1 -1
  24. package/dist/src/server.js +69 -6
  25. package/dist/src/state.js +2 -1
  26. package/dist/src/status.js +11 -2
  27. package/dist/src/turns.js +41 -0
  28. package/package.json +6 -1
  29. package/plugins/badge/README.md +59 -10
  30. package/plugins/badge/index.ts +141 -8
  31. package/plugins/badge/public/style.css +132 -12
  32. package/plugins/chat/index.ts +9 -1
  33. package/plugins/claude/README.md +13 -5
  34. package/plugins/claude/channel.ts +26 -2
  35. package/plugins/claude/doctor.ts +58 -39
  36. package/plugins/claude/index.ts +30 -8
  37. package/plugins/claude/session.ts +32 -0
  38. package/plugins/opencode/channel.ts +42 -7
  39. package/plugins/opencode/index.ts +4 -0
  40. package/skills/workpad/SKILL.md +23 -3
  41. package/src/agents.ts +7 -0
  42. package/src/define.ts +28 -1
  43. package/src/events.ts +23 -2
  44. package/src/help.ts +16 -4
  45. package/src/hub.ts +71 -2
  46. package/src/listen.ts +47 -4
  47. package/src/listeners.ts +22 -1
  48. package/src/pages/board.ts +10 -3
  49. package/src/pages/index.ts +8 -10
  50. package/src/pages/markdown.ts +55 -8
  51. package/src/pages/render.ts +1 -1
  52. package/src/server.ts +84 -6
  53. package/src/state.ts +3 -0
  54. package/src/status.ts +15 -1
  55. package/src/turns.ts +56 -0
@@ -224,6 +224,15 @@ Start on them? :button[Start it]
224
224
  ::::
225
225
  ```
226
226
 
227
+ **Badges:** `:badge[word]` is a status in a word, a grey dot before it.
228
+ `color`, `background` and `border` take a palette name (red orange yellow
229
+ green blue violet pink grey), each off unless set: `{background=red}` is a
230
+ red pill, its text made readable; `live` pulses the dot. The project's
231
+ presets (`workpad docs badge` lists them) give a word its look
232
+ (`:badge[you]`), or a badge names one (`{preset=person}`); built-in words
233
+ like `done` and `blocked` are presets too. The badge's own attributes win
234
+ over its `preset=`, which wins over its word's.
235
+
227
236
  **Nesting containers:** the outer fence needs more colons than anything
228
237
  inside it, `::::grid` around `:::item`. A `:::` closes the first open
229
238
  container whose fence is no longer than its own, so with equal colons the
@@ -446,9 +455,11 @@ ping and then just wait for a pong that may not come.
446
455
  comes. Other agents' messages from before that someone already received
447
456
  are skipped; it says how many, and `workpad listen --wait --page
448
457
  <file>` hands them to you when you want to catch up. Once you confirmed,
449
- the background ping ends (exit 0). No pong confirmed within two minutes:
450
- it ends with exit 1, and that wakes you: listen for them, below, and in
451
- Claude Code tell the user what `workpad claude doctor` says is wrong.
458
+ the background ping ends (exit 0). It keeps waiting while your turn
459
+ runs, so work on as long as you need; no pong confirmed within two
460
+ minutes after your turn ended: it ends with exit 1, and that wakes you:
461
+ listen for them, below, and in Claude Code tell the user what `workpad
462
+ claude doctor` says is wrong.
452
463
 
453
464
  The answers come as one line each: the page, what the user did, its id:
454
465
  `plan: form scope: "Smaller" (id mwv…; …)`. Act on each, handle it, then
@@ -492,6 +503,15 @@ the user that nobody is listening and their answers wait.
492
503
  (its folder) and `url`; act on it in that folder. Use it only when asked
493
504
  to look after the whole board, and with a confirmed channel, take
494
505
  `workpad listen --channel` instead.
506
+ - `workpad listen --unfollowed` is for a coordinator, so no page swallows
507
+ an answer: it takes only the pages no live session follows (its
508
+ session gone, parked, or with a channel never confirmed), across the
509
+ shared server's projects as above, and hands out the user's answers
510
+ there that no other agent received. A page drops out while its own
511
+ session listens again and joins when it goes; new pages join. What you
512
+ get counts as received; act on it in its project, or hand it on. It
513
+ takes `--wait` (re-run it after each) and, with a confirmed channel,
514
+ `--channel`.
495
515
  - `workpad events --page <file> [--type <name>] [--last 1]` lists what was
496
516
  submitted so far, for when you need the history rather than the next
497
517
  answer. With `--follow` it then prints each new event as it comes, without
package/src/agents.ts CHANGED
@@ -129,6 +129,13 @@ export const pong = (code: string) =>
129
129
  export const answerLine = (e: WpEvent, again = false) =>
130
130
  `${e.page}: ${describe(e)}${again ? ' (received before, not handled yet)' : ''} (id ${e.id}; \`workpad thread ${e.id}\` shows it with its question)`
131
131
 
132
+ /**
133
+ * An answer a channel brings from a page no one follows (`workpad listen --unfollowed --channel`):
134
+ * as answerLine, and under the shared server, the project it is in, where its commands run.
135
+ */
136
+ export const unfollowedLine = (e: WpEvent, again: boolean, from: { project: string; url: string } | null) =>
137
+ `${answerLine(e, again)}, on a page no one follows${from ? `, in ${from.project} (${from.url}): run its workpad commands there` : ''}`
138
+
132
139
  /** What to do about answers a channel brought: the same for every agent. */
133
140
  export const ANSWERS_NOTE =
134
141
  'Act on each as on an answer from `workpad listen`. Then handle it with one of: a reply in its chat (`workpad append`), when you have something to say; else `workpad handled <id>`. Nothing more is needed.'
package/src/define.ts CHANGED
@@ -370,6 +370,18 @@ export interface CommandContext {
370
370
  * a page; resolves once the server holds it.
371
371
  */
372
372
  listen(page: string, options?: { agent?: string | null }): Promise<void>
373
+ /**
374
+ * Take the pages no one follows (`workpad listen --unfollowed`), as `agent`, until `signal`
375
+ * aborts: listen on each, and hand the reader's answers there that no other agent received to
376
+ * `onEvent`, as handOut does (received by `agent` unless `mark` is false). A page drops out once someone follows it and
377
+ * joins when its last follower goes; new pages join. Under the shared server they are the pages
378
+ * of every project of this one's entry, and `from` says where each answer is (its project's
379
+ * folder, its page's address); else null. Resolves once the server holds it.
380
+ */
381
+ unfollowed(
382
+ onEvent: (event: WpEvent, again: boolean, from: { project: string; url: string } | null) => void,
383
+ options?: { agent?: string | null; mark?: boolean; signal?: AbortSignal },
384
+ ): Promise<void>
373
385
  /**
374
386
  * Be the channel of agent `session`, a plugin's command that pushes answers into it, for as long
375
387
  * as the command runs. Whether its messages reach the agent only the agent can say: `workpad
@@ -412,6 +424,8 @@ export interface PageStatus {
412
424
  unhandled: WpEvent[]
413
425
  /** the chats on the page whose latest message is the reader's: waiting for the agent's reply */
414
426
  awaitingReply: string[]
427
+ /** when an agent last added to the page's log (a message, a question in a chat), or null */
428
+ updated: string | null
415
429
  /** the running waits and watches that cover the page */
416
430
  listeners: Listener[]
417
431
  }
@@ -484,6 +498,8 @@ export interface IndexPage {
484
498
  url: string
485
499
  /** when its file last changed, in ms */
486
500
  mtime: number
501
+ /** when it last changed for the reader, in ms: its file, or an agent's message or question on it */
502
+ updated: number
487
503
  /** its questions waiting for the reader */
488
504
  open: string[]
489
505
  /** the agent's messages on it the reader hasn't read */
@@ -503,7 +519,7 @@ export interface IndexProject {
503
519
  base: string
504
520
  /** its pages, the latest changed first */
505
521
  pages: IndexPage[]
506
- /** when one of its pages last changed; 0 without pages */
522
+ /** when one of its pages was last updated (IndexPage.updated); 0 without pages */
507
523
  active: number
508
524
  error?: string
509
525
  }
@@ -635,6 +651,11 @@ export interface Listener {
635
651
  agent: string | null
636
652
  /** the name the agent gave itself (`workpad agent name`), when it did: as the server lists it */
637
653
  name?: string
654
+ /**
655
+ * held by `workpad listen --unfollowed` on a page no one else follows: it listens there, but
656
+ * follows nothing, so it never keeps another such listen off the page (listeners.ts, follows)
657
+ */
658
+ unfollowed?: true
638
659
  }
639
660
 
640
661
  /** How a toast looks and acts (Api.toast). */
@@ -931,6 +952,12 @@ interface BaseContext {
931
952
  inline(src: string): Promise<string>
932
953
  /** what a client gets when the block has no props() */
933
954
  defaults(): Promise<Record<string, unknown>>
955
+ /**
956
+ * Report what is wrong with the block as written, for whoever wrote the page, in one sentence (a
957
+ * value it doesn't know): shown above the page and listed by `workpad check` (Rendered.problems).
958
+ * The block still renders as best it can. Nothing in an agent's chat message: nobody there can fix it.
959
+ */
960
+ problem(text: string): void
934
961
  }
935
962
 
936
963
  /** `:::name[label]{attrs}` … `:::`, `::name[label]{attrs}`, `:name[label]{attrs}` */
package/src/events.ts CHANGED
@@ -22,6 +22,7 @@ import {
22
22
  namesOf,
23
23
  receivedIds,
24
24
  subscriptions,
25
+ takesUnfollowed,
25
26
  } from './status.ts'
26
27
 
27
28
  export {
@@ -37,6 +38,7 @@ export {
37
38
  namesOf,
38
39
  receivedIds,
39
40
  subscriptions,
41
+ takesUnfollowed,
40
42
  }
41
43
 
42
44
  /** What is appended: the id and time are added. */
@@ -372,6 +374,16 @@ export interface HandOutOptions {
372
374
  * gets what is new, not other agents' talk from before; `listen --wait` still hands it all out.
373
375
  */
374
376
  skipReceivedBefore?: string
377
+ /**
378
+ * Only the reader's events, no agent's: a listen on the pages no one follows takes the answers
379
+ * waiting there, not what the page's own agents said on them.
380
+ */
381
+ readerOnly?: boolean
382
+ /**
383
+ * Leave out what another agent received: it has it, and is on it (or handed it on). A listen on
384
+ * the pages no one follows takes what reached nobody, not what a session left for between turns.
385
+ */
386
+ notReceivedByOthers?: boolean
375
387
  }
376
388
 
377
389
  /**
@@ -402,6 +414,8 @@ export function handOut(
402
414
  mark = true,
403
415
  agent = null,
404
416
  skipReceivedBefore,
417
+ readerOnly = false,
418
+ notReceivedByOthers = false,
405
419
  } = options
406
420
  return new Promise(resolve => {
407
421
  let got = 0
@@ -412,7 +426,7 @@ export function handOut(
412
426
  resolve(got)
413
427
  }
414
428
  // whose events: the reader's, and another agent's that says who it is
415
- const fromOthers = (e: WpEvent) => fromReader(e) || (!!e.by && e.by !== agent)
429
+ const fromOthers = (e: WpEvent) => fromReader(e) || (!readerOnly && !!e.by && e.by !== agent)
416
430
  // of those, the ones for an agent, unless the filter names a type
417
431
  const wanted = (e: WpEvent) => fromOthers(e) && matches(e, filter) && (!!filter.type || isForAgent(e.type))
418
432
  // what this identity received before, by id: handed out again, it says so
@@ -428,13 +442,20 @@ export function handOut(
428
442
  const { events, end } = read(file)
429
443
  const handled = handledIds(events)
430
444
  before = receivedBy(events, agent)
445
+ const others = notReceivedByOthers
446
+ ? new Set(
447
+ events
448
+ .filter(e => e.type === RECEIVED && !fromReader(e) && (e.by ?? null) !== agent)
449
+ .map(e => String(e.data?.event)),
450
+ )
451
+ : new Set<string>()
431
452
  // the past before a channel's subscription: what someone received, unless it is the reader's
432
453
  let skipping = !!skipReceivedBefore
433
454
  const receivedAny = skipping ? receivedIds(events) : new Set<string>()
434
455
  for (const e of events) {
435
456
  if (skipping && e.id === skipReceivedBefore) skipping = false
436
457
  if (skipping && !fromReader(e) && receivedAny.has(e.id)) continue
437
- if (wanted(e) && !handled.has(e.id) && !hand(e)) return finish()
458
+ if (wanted(e) && !handled.has(e.id) && !others.has(e.id) && !hand(e)) return finish()
438
459
  }
439
460
  // a batch: what there was, if anything; else it goes on for the first to come
440
461
  if (batch && got) return finish()
package/src/help.ts CHANGED
@@ -47,8 +47,10 @@ opencode()). Alone, it says your id and your name.
47
47
  confirmed, the channel listens on your pages, and the answers it brings count
48
48
  as received. No channel (exit 1), or no pong: nothing brings answers here, so
49
49
  listen for them. --wait: run it in the background; it pings and ends when
50
- the pong is confirmed (exit 0), or after --timeout seconds (120) without one
51
- (exit 1): then listen.`,
50
+ the pong is confirmed (exit 0), or --timeout seconds (120) after the
51
+ session's turn ended without one (exit 1): then listen. A pong comes only
52
+ once the turn ends, so it waits while the turn runs, 30 minutes at most;
53
+ where its plugin records no turn ends, it counts from the ping.`,
52
54
  },
53
55
 
54
56
  show: {
@@ -154,7 +156,7 @@ One chat's messages: workpad chat prune <page|file> <chat>.`,
154
156
  --follow then print each new one as it comes`,
155
157
  },
156
158
  listen: {
157
- usage: '[--page <p>…] [--type <t>] [--wait [--timeout <s>] | --channel] [--agent <who>]',
159
+ usage: '[--page <p>… | --unfollowed] [--type <t>] [--wait [--timeout <s>] | --channel] [--agent <who>]',
158
160
  summary:
159
161
  "print what you haven't handled on the pages (the reader's answers, other agents' messages) and each as it comes; --wait stops at the first, --channel hands over to your channel",
160
162
  details: `${FILTERS}
@@ -162,6 +164,7 @@ One chat's messages: workpad chat prune <page|file> <chat>.`,
162
164
  --wait stop once it printed: all there are, or with none, the first to come
163
165
  --timeout <seconds> with --wait: exit 2 when nothing came
164
166
  --channel make the pages yours and exit: your session's channel brings their answers
167
+ --unfollowed the pages no live session follows, for a coordinator: see below
165
168
  --agent <who> who listens (else WORKPAD_AGENT, else the session an agent plugin names)
166
169
 
167
170
  It prints, one line each, everything on the page you haven't handled, also from before it started,
@@ -177,7 +180,16 @@ answers to handle, chats waiting for your reply, questions still unanswered.
177
180
 
178
181
  Any number listen on a page, and each hears everything there but its own events: agents can talk
179
182
  to each other in the same chats. Without --page it listens on every page (in a project of the
180
- machine's entries, every page of the entry).`,
183
+ machine's entries, every page of the entry).
184
+
185
+ --unfollowed is for a coordinator, so no page swallows an answer: it listens on every page no live
186
+ session follows (in a project of the machine's entries, in every project of the entry, each line
187
+ with its \`project\` and \`url\`), and hands out the reader's answers there that no other agent
188
+ received. Following is listening now: a running listen on the page, or a confirmed channel of a
189
+ session it belongs to; a subscriber that is gone, between turns, or whose channel was never
190
+ confirmed follows nothing. A page drops out while someone follows it, and joins when its last
191
+ follower goes, as do new pages. What it hands out counts as received by you. With --channel your
192
+ confirmed channel takes these pages on (none becomes yours) and it exits.`,
181
193
  },
182
194
  append: {
183
195
  usage: '--page <p> --type <t> [--data <json>]',
package/src/hub.ts CHANGED
@@ -19,6 +19,9 @@
19
19
  // a listen over a whole entry, for as long as the connection is open: held on
20
20
  // every page of its projects, also those that appear meanwhile; its stream is
21
21
  // told the entry's projects (listeners.ts). Any number run
22
+ // /api/listen?unfollowed[&entry=<name>][&agent=<who>]
23
+ // a listen on the pages no one follows, across every project (or one entry's):
24
+ // held on each, and told them (`event: pages`) as they change (listeners.ts)
22
25
  //
23
26
  // A project's server is made when the project is found and closed when it goes, so a project
24
27
  // appears and disappears without a restart. Each keeps its own state, config and log, as it would
@@ -89,6 +92,32 @@ export function createHub({
89
92
  tell: () => void
90
93
  }
91
94
  const entryListens = new Set<EntryListen>()
95
+
96
+ // the listens on the pages no one follows (`workpad listen --unfollowed`): each project holds
97
+ // one for it, and says which of its pages those are; its stream is told them all together
98
+ interface UnfollowedListen {
99
+ entry: string | null
100
+ listener: Listener
101
+ held: Map<Served, () => void>
102
+ pages: Map<Served, string[]>
103
+ tell: () => void
104
+ }
105
+ const unfollowedListens = new Set<UnfollowedListen>()
106
+ function takeOn(s: Served, ul: UnfollowedListen) {
107
+ if (ul.held.has(s) || (ul.entry && s.entry !== ul.entry)) return
108
+ ul.held.set(
109
+ s,
110
+ s.server.unfollowed(ul.listener, pages => {
111
+ ul.pages.set(s, pages)
112
+ ul.tell()
113
+ }),
114
+ )
115
+ }
116
+ function letGo(s: Served, ul: UnfollowedListen) {
117
+ ul.held.get(s)?.()
118
+ ul.held.delete(s)
119
+ if (ul.pages.delete(s)) ul.tell()
120
+ }
92
121
  /** An entry listen held on one of its projects, so the project's pages say it listens. */
93
122
  function hold(s: Served, el: EntryListen) {
94
123
  if (!el.held.has(s)) el.held.set(s, s.server.addListener(el.listener))
@@ -124,6 +153,7 @@ export function createHub({
124
153
  for (const [key, s] of served)
125
154
  if (!wanted.has(key)) {
126
155
  for (const el of entryListens) release(s, el)
156
+ for (const ul of unfollowedListens) letGo(s, ul)
127
157
  s.server.close()
128
158
  served.delete(key)
129
159
  console.log(`workpad: ${s.base} is gone (${s.dir})`)
@@ -143,6 +173,7 @@ export function createHub({
143
173
  const s: Served = { ...p, project, server }
144
174
  served.set(key, s)
145
175
  for (const el of entryListens) if (el.entry === p.entry) hold(s, el)
176
+ for (const ul of unfollowedListens) takeOn(s, ul)
146
177
  console.log(`workpad: ${p.base} → ${p.dir}`)
147
178
  }
148
179
  // an entry listen follows its projects coming and going
@@ -231,12 +262,13 @@ export function createHub({
231
262
  title: p.title,
232
263
  url: `${s.base}/${p.page.split('/').map(encodeURIComponent).join('/')}`,
233
264
  mtime: mtimeOf(p.file),
265
+ updated: Math.max(mtimeOf(p.file), p.updated ? Date.parse(p.updated) : 0),
234
266
  open: p.open,
235
267
  unread: p.unread.length,
236
268
  unreceived: p.unreceived.length,
237
269
  }))
238
- .toSorted((a, b) => b.mtime - a.mtime)
239
- return { ...at, pages, active: pages[0]?.mtime ?? 0 }
270
+ .toSorted((a, b) => b.updated - a.updated)
271
+ return { ...at, pages, active: pages[0]?.updated ?? 0 }
240
272
  }
241
273
  const index = () => Promise.all([...served.values()].map(indexOf))
242
274
 
@@ -292,6 +324,7 @@ export function createHub({
292
324
  setImmediate(() => onShutdown?.())
293
325
  return
294
326
  }
327
+ if (p === '/api/listen' && url.searchParams.has('unfollowed')) return listenUnfollowed(req, res, url.searchParams)
295
328
  if (p === '/api/listen' && url.searchParams.has('entry')) return listenEntry(req, res, url.searchParams)
296
329
  // the API across every project: each project's list, put together
297
330
  const what = /^\/api\/(\w+)$/.exec(p)?.[1]
@@ -380,6 +413,42 @@ export function createHub({
380
413
  }
381
414
  const closers = new Set<() => void>()
382
415
 
416
+ /**
417
+ * A listen on the pages no one follows (`workpad listen --unfollowed`), across every project or
418
+ * one entry's: each project holds it on those of its pages (WorkpadServer.unfollowed), and its
419
+ * stream is told them all, once for several changes.
420
+ */
421
+ function listenUnfollowed(req: IncomingMessage, res: ServerResponse, q: URLSearchParams) {
422
+ let telling = false
423
+ const ul: UnfollowedListen = {
424
+ entry: q.get('entry'),
425
+ listener: listenerOf(q),
426
+ held: new Map(),
427
+ pages: new Map(),
428
+ tell: () => {
429
+ if (telling) return
430
+ telling = true
431
+ setImmediate(() => {
432
+ telling = false
433
+ const projects = [...ul.pages]
434
+ .filter(([, pages]) => pages.length)
435
+ .map(([s, pages]) => ({ dir: s.dir, base: s.base, pages }))
436
+ stream.send('pages', { projects })
437
+ })
438
+ },
439
+ }
440
+ const stream = holdStream(req, res, () => {
441
+ closers.delete(stream.end)
442
+ unfollowedListens.delete(ul)
443
+ for (const s of [...ul.held.keys()]) letGo(s, ul)
444
+ })
445
+ closers.add(stream.end)
446
+ unfollowedListens.add(ul)
447
+ for (const s of served.values()) takeOn(s, ul)
448
+ // told at once, also with no project to take on
449
+ ul.tell()
450
+ }
451
+
383
452
  /** /api/stream across every project: as a project's, each event with its project. */
384
453
  function streamAll(req: IncomingMessage, res: ServerResponse, query: Record<string, string>) {
385
454
  res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })
package/src/listen.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  // and the listen hands out from each project's log.
6
6
  import http from 'node:http'
7
7
  import https from 'node:https'
8
- import type { Followed, Snapshot } from './listeners.ts'
8
+ import type { Followed, Snapshot, Unfollowed } from './listeners.ts'
9
9
 
10
10
  /**
11
11
  * A held GET to the server, over http or https as its address says: a server reached at an https
@@ -22,6 +22,10 @@ export interface ListenOptions {
22
22
  query: Record<string, string>
23
23
  /** a listen over a whole entry: the projects it covers, at once and on every change */
24
24
  onSnapshot?: (snapshot: Snapshot) => void
25
+ /** a listen on the unfollowed pages (`unfollowed` in the query): which they are, at once and on every change */
26
+ onPages?: (unfollowed: Unfollowed) => void
27
+ /** let go of the server, and don't connect again */
28
+ signal?: AbortSignal
25
29
  }
26
30
 
27
31
  /**
@@ -29,15 +33,22 @@ export interface ListenOptions {
29
33
  * Resolves once the server holds it; with `orNone`, also after a first try that found no server
30
34
  * running (a listen reads the log all the same, and registers once one appears).
31
35
  */
32
- export function listen({ at, query, onSnapshot }: ListenOptions, { orNone = false } = {}): Promise<void> {
36
+ export function listen(
37
+ { at, query, onSnapshot, onPages, signal }: ListenOptions,
38
+ { orNone = false } = {},
39
+ ): Promise<void> {
33
40
  return new Promise(settled => {
41
+ let current: http.ClientRequest | null = null
42
+ signal?.addEventListener('abort', () => current?.destroy())
34
43
  const connect = async () => {
44
+ if (signal?.aborted) return settled()
35
45
  let base: string | null = null
36
46
  try {
37
47
  base = await at()
38
48
  } catch {
39
49
  /* none runs */
40
50
  }
51
+ if (signal?.aborted) return settled()
41
52
  if (!base) {
42
53
  if (orNone) settled()
43
54
  return setTimeout(connect, 2000).unref()
@@ -49,7 +60,7 @@ export function listen({ at, query, onSnapshot }: ListenOptions, { orNone = fals
49
60
  setTimeout(connect, ms).unref()
50
61
  }
51
62
  }
52
- const req = get(`${base}/api/listen?${new URLSearchParams(query)}`, res => {
63
+ const req = (current = get(`${base}/api/listen?${new URLSearchParams(query)}`, res => {
53
64
  res.setEncoding('utf8')
54
65
  settled()
55
66
  // held: the connection alone does not keep the command running. Not before: until the
@@ -66,10 +77,11 @@ export function listen({ at, query, onSnapshot }: ListenOptions, { orNone = fals
66
77
  const event = /^event: (.*)$/m.exec(block)?.[1]
67
78
  const data = /^data: (.*)$/m.exec(block)?.[1]
68
79
  if (event === 'projects' && data && onSnapshot) onSnapshot(JSON.parse(data) as Snapshot)
80
+ if (event === 'pages' && data && onPages) onPages(JSON.parse(data) as Unfollowed)
69
81
  }
70
82
  })
71
83
  res.on('close', () => retry(1000))
72
- })
84
+ }))
73
85
  req.on('error', () => retry(2000))
74
86
  }
75
87
  void connect()
@@ -98,6 +110,37 @@ export function everyProject(start: (project: Followed, signal: AbortSignal) =>
98
110
  }
99
111
  }
100
112
 
113
+ /** A page of a project a listen on the unfollowed pages takes. */
114
+ export interface PageOf extends Followed {
115
+ page: string
116
+ }
117
+
118
+ /**
119
+ * A listen on the unfollowed pages: `start` is called once for each page as it joins, to hand out
120
+ * from its project's log; a page that drops out (someone follows it now) is stopped (`signal`).
121
+ * @returns what takes each list of pages the server sends
122
+ */
123
+ export function everyPage(start: (page: PageOf, signal: AbortSignal) => void): (unfollowed: Unfollowed) => void {
124
+ const taken = new Map<string, AbortController>()
125
+ return ({ projects }) => {
126
+ const now = new Set<string>()
127
+ for (const p of projects)
128
+ for (const page of p.pages) {
129
+ const key = `${p.dir}\n${page}`
130
+ now.add(key)
131
+ if (taken.has(key)) continue
132
+ const stop = new AbortController()
133
+ taken.set(key, stop)
134
+ start({ dir: p.dir, base: p.base, page }, stop.signal)
135
+ }
136
+ for (const [key, stop] of taken)
137
+ if (!now.has(key)) {
138
+ stop.abort()
139
+ taken.delete(key)
140
+ }
141
+ }
142
+ }
143
+
101
144
  /** What a channel's line does with what the server sends it (`CommandContext.channel`). */
102
145
  export interface ChannelHandlers {
103
146
  /** `workpad agent ping` in the session: push the pong, with this code, into it */
package/src/listeners.ts CHANGED
@@ -26,7 +26,9 @@ export function createRegistry(): Registry {
26
26
  }
27
27
  return {
28
28
  list: (page = null) =>
29
- [...listeners].filter(l => page == null || covers(l, page)).map(({ page, type, agent }) => ({ page, type, agent })),
29
+ [...listeners]
30
+ .filter(l => page == null || covers(l, page))
31
+ .map(({ page, type, agent, unfollowed }) => ({ page, type, agent, ...(unfollowed && { unfollowed }) })),
30
32
  add(l) {
31
33
  listeners.add(l)
32
34
  changed()
@@ -59,8 +61,27 @@ export const listenerOf = (q: URLSearchParams): Listener => ({
59
61
  page: q.get('page') || '',
60
62
  type: q.get('type') || null,
61
63
  agent: q.get('agent') || null,
64
+ ...(q.has('unfollowed') && { unfollowed: true as const }),
62
65
  })
63
66
 
67
+ /**
68
+ * Does `l` follow `page`: is someone there to take whatever comes on it? A listener covering the
69
+ * page, for every type: a running listen on it (or above it, or on every page), and a confirmed
70
+ * channel, which holds one on each page of its session's. A listen for one form only (`--type`)
71
+ * leaves the rest to no one, and a listen on the unfollowed pages follows nothing itself. A
72
+ * subscriber listening nowhere (gone, between turns, or a channel never confirmed) is no listener.
73
+ */
74
+ export const follows = (l: Listener, page: string): boolean => !l.unfollowed && !l.type && covers(l, page)
75
+
76
+ /**
77
+ * What a listen on the unfollowed pages (`workpad listen --unfollowed`) is told (`event: pages`), at
78
+ * once and whenever it changes: per project, the pages no one follows now; a project with none is
79
+ * left out.
80
+ */
81
+ export interface Unfollowed {
82
+ projects: (Followed & { pages: string[] })[]
83
+ }
84
+
64
85
  /**
65
86
  * Hold a /api/listen connection open as an event stream (with a ping, so nothing between closes it
66
87
  * as idle). `send` writes an event on it; `onEnd` runs once, when the agent goes or `end` is called.
@@ -23,6 +23,13 @@ export const waitingOn = (p: IndexPage): Waiting => ({
23
23
 
24
24
  export const total = (w: Waiting): number => w.open + w.unread + w.unreceived
25
25
 
26
+ /**
27
+ * How much a card needs the reader: something waiting on it first, then the newest update (its file,
28
+ * or an agent's message or question on it) first.
29
+ */
30
+ export const byAttention = (a: Card, b: Card): number =>
31
+ Number(total(b.waiting) > 0) - Number(total(a.waiting) > 0) || b.page.updated - a.page.updated
32
+
26
33
  /** A page on the board, with the project it is in. */
27
34
  export interface Card<P extends IndexProject = IndexProject> {
28
35
  page: IndexPage
@@ -48,10 +55,10 @@ export function byState<P extends IndexProject>(
48
55
  for (const project of projects)
49
56
  for (const page of project.pages) {
50
57
  const card = { page, project, waiting: waitingOn(page) }
51
- const column = total(card.waiting) > 0 ? 'waiting' : now - page.mtime <= activeFor ? 'active' : 'quiet'
58
+ const column = total(card.waiting) > 0 ? 'waiting' : now - page.updated <= activeFor ? 'active' : 'quiet'
52
59
  columns[column].push(card)
53
60
  }
54
- for (const cards of [columns.waiting, columns.active, columns.quiet]) cards.sort((a, b) => b.page.mtime - a.page.mtime)
61
+ for (const cards of [columns.waiting, columns.active, columns.quiet]) cards.sort(byAttention)
55
62
  return columns
56
63
  }
57
64
 
@@ -70,7 +77,7 @@ export function byProject<P extends IndexProject>(projects: readonly P[]): Proje
70
77
  .map(project => {
71
78
  const cards = project.pages
72
79
  .map(page => ({ page, project, waiting: waitingOn(page) }))
73
- .sort((a, b) => b.page.mtime - a.page.mtime)
80
+ .sort(byAttention)
74
81
  const waiting = cards.reduce(
75
82
  (sum, c) => ({
76
83
  open: sum.open + c.waiting.open,
@@ -3,7 +3,7 @@
3
3
  // loaded config (see loader.ts); the server renders with it.
4
4
  import { resolveBlocks, type BlockEntry } from './blocks.ts'
5
5
  import { createAgentMessageRender, createBlocksRender, createDocs, createMessageRender, createRender } from './render.ts'
6
- import { chatNames, formDetails, formNames, type FormDetail, type Island } from './markdown.ts'
6
+ import { pageAsks, type Island, type PageAsks } from './markdown.ts'
7
7
  import type { PageSource, RenderContext, Rendered, StoredPage } from '../define.ts'
8
8
  import type { Plugin, TextLink } from '../define.ts'
9
9
 
@@ -28,12 +28,12 @@ export interface Pages {
28
28
  render(page: StoredPage, ctx: RenderContext): Promise<Rendered>
29
29
  /** how pages are written, and which blocks the plugins bring: what `workpad docs` prints first */
30
30
  docs(ctx: RenderContext): string
31
- /** the questions a page asks: its named forms, whose answers are events of their name */
32
- questions(page: PageSource): string[]
33
- /** the chats a page shows: one under every form, and the chat blocks */
34
- chats(page: PageSource): string[]
35
- /** what each of a page's `:::form`s asks: its question, options and buttons */
36
- forms(page: PageSource): FormDetail[]
31
+ /**
32
+ * What a page asks, with what the plugins add at its end: its questions (its named forms, whose
33
+ * answers are events of their name), its chats (one under every form, and the chat blocks) and
34
+ * what each of its `:::form`s asks (its question, options and buttons). One parse for all three.
35
+ */
36
+ asks(page: PageSource): PageAsks
37
37
  /** a message's markdown (a comment, a chat message) as HTML, and the stylesheets it needs */
38
38
  message(text: string, ctx: RenderContext): Promise<{ html: string; styles: string[] }>
39
39
  /**
@@ -72,8 +72,6 @@ export function createPages(options: PagesOptions): Pages {
72
72
  agentMessage: createAgentMessageRender(blocks, options.links ?? [], options.composers),
73
73
  blocks: createBlocksRender(blocks, options.links ?? [], options.composers),
74
74
  docs: createDocs(blocks),
75
- questions: page => formNames(ended(page).body),
76
- chats: page => chatNames(ended(page).body),
77
- forms: page => formDetails(ended(page).body),
75
+ asks: page => pageAsks(ended(page).body),
78
76
  }
79
77
  }