@bigmistqke/workpad 0.19.0 → 0.20.1

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 (89) hide show
  1. package/README.md +29 -16
  2. package/bin/workpad.ts +193 -37
  3. package/dist/bin/workpad.js +161 -32
  4. package/dist/client/runtime.js +141 -18
  5. package/dist/plugins/chat/README.md +7 -3
  6. package/dist/plugins/chat/index.js +1 -0
  7. package/dist/plugins/chat/public/client.js +2 -2
  8. package/dist/plugins/chat/public/style.css +10 -0
  9. package/dist/plugins/claude/channel.js +22 -4
  10. package/dist/plugins/claude/doctor.js +15 -5
  11. package/dist/plugins/comments/README.md +2 -1
  12. package/dist/plugins/comments/index.js +2 -0
  13. package/dist/plugins/comments/public/client.js +6 -5
  14. package/dist/plugins/comments/public/style.css +9 -0
  15. package/dist/plugins/form/README.md +1 -1
  16. package/dist/plugins/index.js +3 -1
  17. package/dist/plugins/opencode/channel.js +1 -0
  18. package/dist/plugins/progress/README.md +41 -0
  19. package/dist/plugins/progress/index.js +117 -0
  20. package/dist/plugins/progress/public/client.js +1 -0
  21. package/dist/plugins/progress/public/style.css +85 -0
  22. package/dist/plugins/progress/state.js +210 -0
  23. package/dist/solid/index.js +3 -1
  24. package/dist/src/agents.js +7 -3
  25. package/dist/src/anchors.js +25 -1
  26. package/dist/src/build.js +1 -1
  27. package/dist/src/client/page/base.css +48 -2
  28. package/dist/src/client/page/main.js +58 -30
  29. package/dist/src/document.js +6 -4
  30. package/dist/src/entries.js +6 -2
  31. package/dist/src/events.js +19 -9
  32. package/dist/src/files.js +26 -3
  33. package/dist/src/help.js +43 -8
  34. package/dist/src/hub.js +20 -4
  35. package/dist/src/loader.js +11 -6
  36. package/dist/src/migrate.js +1 -1
  37. package/dist/src/pages/board.js +1 -1
  38. package/dist/src/pages/markdown.js +3 -3
  39. package/dist/src/pages/render.js +16 -0
  40. package/dist/src/server.js +70 -32
  41. package/dist/src/set.js +99 -0
  42. package/dist/src/status.js +47 -8
  43. package/package.json +6 -1
  44. package/plugins/README.md +3 -1
  45. package/plugins/chat/README.md +7 -3
  46. package/plugins/chat/client.tsx +20 -3
  47. package/plugins/chat/index.ts +1 -0
  48. package/plugins/chat/public/style.css +10 -0
  49. package/plugins/claude/channel.ts +19 -5
  50. package/plugins/claude/doctor.ts +11 -3
  51. package/plugins/comments/README.md +2 -1
  52. package/plugins/comments/client.ts +19 -0
  53. package/plugins/comments/index.ts +7 -1
  54. package/plugins/comments/public/style.css +9 -0
  55. package/plugins/form/README.md +1 -1
  56. package/plugins/index.ts +2 -0
  57. package/plugins/opencode/channel.ts +2 -1
  58. package/plugins/progress/README.md +41 -0
  59. package/plugins/progress/client.ts +172 -0
  60. package/plugins/progress/index.ts +166 -0
  61. package/plugins/progress/public/style.css +85 -0
  62. package/plugins/progress/state.ts +278 -0
  63. package/skills/workpad/SKILL.md +126 -15
  64. package/solid/index.tsx +6 -2
  65. package/src/agents.ts +17 -2
  66. package/src/anchors.ts +32 -0
  67. package/src/build.ts +1 -1
  68. package/src/client/delivery.ts +49 -0
  69. package/src/client/forms.ts +18 -11
  70. package/src/client/page/base.css +48 -2
  71. package/src/client/page/waiting.ts +45 -25
  72. package/src/client/read.ts +9 -5
  73. package/src/client/runtime.ts +7 -3
  74. package/src/client/toast.ts +27 -3
  75. package/src/define.ts +92 -8
  76. package/src/document.ts +19 -5
  77. package/src/entries.ts +18 -7
  78. package/src/events.ts +26 -6
  79. package/src/files.ts +28 -2
  80. package/src/help.ts +42 -7
  81. package/src/hub.ts +25 -8
  82. package/src/loader.ts +20 -10
  83. package/src/migrate.ts +1 -1
  84. package/src/pages/board.ts +3 -1
  85. package/src/pages/markdown.ts +4 -4
  86. package/src/pages/render.ts +19 -1
  87. package/src/server.ts +114 -42
  88. package/src/set.ts +118 -0
  89. package/src/status.ts +100 -13
package/src/server.ts CHANGED
@@ -32,7 +32,6 @@ import {
32
32
  follow,
33
33
  handle as handleEvent,
34
34
  matches,
35
- receivedIds,
36
35
  handledIds,
37
36
  forAgent,
38
37
  namesOf,
@@ -63,9 +62,29 @@ import { describeRoutes, dispatch, pluginCommands, mountRoutes, usage } from './
63
62
  import { createAuth, sameSite } from './auth.ts'
64
63
  import { accept, refuse } from './ws.ts'
65
64
  import { FROM_SOURCE, PACKAGE_DIR, VERSION } from './package.ts'
66
- import { SCROLL, agentMessagesIn, awaiting, isAgentMessage, projectStatus, type ProjectStatus } from './status.ts'
65
+ import {
66
+ SCROLL,
67
+ agentLabel,
68
+ agentMessagesIn,
69
+ awaiting,
70
+ isAgentMessage,
71
+ projectStatus,
72
+ receivers,
73
+ refusal,
74
+ type ProjectStatus,
75
+ } from './status.ts'
67
76
  import { formsIn, messageForms } from './pages/markdown.ts'
68
- import { fileFilter, type FileFilter } from './files.ts'
77
+ import { fileFilter, type FileFilter, type FilesConfig } from './files.ts'
78
+
79
+ /**
80
+ * Watch a project's files folder by folder (each that can hold something shown, at any depth), not
81
+ * a recursive watch per top-level folder: where a recursive watch costs a watch per folder below
82
+ * it, whatever it holds (Linux's inotify). `$WORKPAD_WATCH`: `folders` or `recursive`, else by
83
+ * platform. See setFiles.
84
+ */
85
+ const WATCH_BY_FOLDER = process.env.WORKPAD_WATCH
86
+ ? process.env.WORKPAD_WATCH === 'folders'
87
+ : process.platform !== 'darwin' && process.platform !== 'win32'
69
88
  import { titleOf } from './pages/render.ts'
70
89
  import { createRegistry, follows, holdStream, listenerOf } from './listeners.ts'
71
90
  import { inPublic } from './public.ts'
@@ -106,6 +125,9 @@ const MIME: Record<string, string> = {
106
125
  '.csv': 'text/csv; charset=utf-8',
107
126
  '.html': 'text/html; charset=utf-8',
108
127
  }
128
+ /** How many of the browser's latest events the server knows by id, to answer a retried send with the first. */
129
+ const APPENDED_KEPT = 1000
130
+
109
131
  // files in .workpad/ that are the server's own bookkeeping, not content
110
132
  const OWN_FILES = new Set(['events.ndjson', 'server.json', 'server.log', 'server.lock', 'token'])
111
133
 
@@ -177,8 +199,10 @@ export interface ServerOptions {
177
199
  name?: string
178
200
  /** serve and watch the project's files, over the config's `files` */
179
201
  files?: boolean
180
- /** serve and watch the project's files when its config doesn't say (its entry's `files`); default true */
181
- filesDefault?: boolean
202
+ /** which of the project's files are served and watched when its config doesn't say (its entry's `files`); default true */
203
+ filesDefault?: boolean | FilesConfig
204
+ /** watch the project's files folder by folder, not recursively (default: by platform, WATCH_BY_FOLDER) */
205
+ watchByFolder?: boolean
182
206
  /** the overview at / lists these instead of the project's pages (the shared server's own project) */
183
207
  overview?: () => Promise<Pick<PagesSource, 'projects' | 'note'>>
184
208
  /** a page of the project changed, or its log grew: the shared server's overview follows it */
@@ -196,6 +220,7 @@ export function createServer(
196
220
  name,
197
221
  files: filesOption,
198
222
  filesDefault,
223
+ watchByFolder = WATCH_BY_FOLDER,
199
224
  overview,
200
225
  onChange,
201
226
  origins = () => [],
@@ -263,7 +288,8 @@ export function createServer(
263
288
  const notices = [...rendered.notices]
264
289
  const parts = await pluginParts(await pluginHooks(), req, {
265
290
  asset,
266
- messages: [...(await config()).forReader],
291
+ messages: Object.fromEntries((await config()).forReader),
292
+ handedOut: [...(await config()).handedOut],
267
293
  failed: message => {
268
294
  console.error(message)
269
295
  notices.push(message)
@@ -466,7 +492,7 @@ export function createServer(
466
492
  events,
467
493
  listeners: listenersFor,
468
494
  forAgent: forAgent(handedOut),
469
- forReader: type => forReader.has(type),
495
+ forReader,
470
496
  })
471
497
  }
472
498
 
@@ -799,8 +825,17 @@ export function createServer(
799
825
  }
800
826
 
801
827
  const clients = new Set<WatchClient>()
802
- /** what the browser appended lately, by id: a send it retries is answered with what it got */
803
- const appended = new Map<string, WpEvent>()
828
+ /**
829
+ * what the browser appended lately, by id: a send it retries is answered with what it got. From
830
+ * the log at the start, so a retry that comes after a restart (the first try got in, its answer
831
+ * didn't get out) is no second answer either.
832
+ */
833
+ const appended = new Map<string, WpEvent>(
834
+ readEvents(project.eventsFile)
835
+ .filter(e => !e.from)
836
+ .slice(-APPENDED_KEPT)
837
+ .map(e => [e.id, e]),
838
+ )
804
839
  function notify(client: WatchClient, kind: string) {
805
840
  client.pending ??= new Set()
806
841
  if (client.pending.size === 0)
@@ -863,65 +898,94 @@ export function createServer(
863
898
  // With files on, the whole project folder is watched (repository views stay live); with files off,
864
899
  // only .workpad/, so a project in a large folder such as the home folder stays cheap. A folder
865
900
  // that holds nothing shown (node_modules, .git, what the config's `files` leaves out: src/files.ts)
866
- // is never watched: an install or a checkout changes thousands of files there that nothing shows,
867
- // and on Linux a recursive watch holds a watch for every folder below it. So the project folder
868
- // itself is watched without recursing, and each folder in it that can hold something shown
869
- // recursively, one made later too. One left out deeper down (a package's own node_modules) is
870
- // watched, its changes passed over (fileChanged).
901
+ // is never watched: an install or a checkout changes thousands of files there that nothing shows.
902
+ // How, by platform (watchByFolder): on Linux a recursive watch is one inotify watch per folder
903
+ // below it, node_modules and nested checkouts' dependencies too (10 checkouts: 113,899 watches,
904
+ // the first request blocked for minutes while they were set up), so each folder that can hold
905
+ // something shown is watched on its own, at any depth, found without blocking, and one made later
906
+ // too. On macOS a recursive watch is a single FSEvents stream, cheap however deep, and a watch
907
+ // per folder would rebuild it at every one added: the project folder is watched without
908
+ // recursing, each folder in it that can hold something shown recursively, and what is left out
909
+ // deeper down (a package's own node_modules) is passed over (fileChanged), cheaply.
871
910
  let FILES: boolean | null = null
872
911
  // which of the project's files are shown (the config's `files`, src/files.ts)
873
912
  let FILTER: FileFilter = fileFilter()
913
+ // a watcher per folder watched, by its path in the project folder ('' the project folder itself)
874
914
  let projectWatchers = new Map<string, fs.FSWatcher>()
915
+ // counts each setFiles: a walk still finding folders for an earlier one stops
916
+ let watchRound = 0
875
917
  function setFiles(files: boolean, filter: FileFilter = fileFilter()) {
876
918
  if (files === FILES && filter.key === FILTER.key) return
877
919
  FILES = files
878
920
  FILTER = filter
921
+ const round = ++watchRound
879
922
  for (const w of projectWatchers.values()) {
880
923
  w.close()
881
924
  watchers.delete(w)
882
925
  }
883
926
  projectWatchers = new Map()
927
+ const drop = (key: string) => {
928
+ for (const [k, w] of projectWatchers)
929
+ if (k === key || k.startsWith(key + '/')) {
930
+ w.close()
931
+ watchers.delete(w)
932
+ projectWatchers.delete(k)
933
+ }
934
+ }
884
935
  const add = (key: string, dir: string, recursive: boolean, prefix: string) => {
885
936
  try {
886
937
  const w = fs.watch(dir, { recursive }, (evt, filename) => {
887
938
  if (!filename) return
888
939
  const name = filename.toString().replace(/\\/g, '/')
889
940
  fileChanged(prefix + name)
890
- // a folder made, removed or made again in the project folder: watched afresh, if it is there
941
+ // a folder made, removed or made again in a folder watched on its own: watched afresh, if it is there
891
942
  if (!recursive && evt === 'rename') {
892
- const old = projectWatchers.get(name)
893
- if (old) {
894
- old.close()
895
- watchers.delete(old)
896
- projectWatchers.delete(name)
897
- }
898
- watchFolder(name)
943
+ const child = prefix + name
944
+ drop(child)
945
+ watchFolder(child)
899
946
  }
900
947
  })
901
948
  // a folder that goes: its watcher with it
902
- w.on('error', () => {
903
- w.close()
904
- watchers.delete(w)
905
- projectWatchers.delete(key)
906
- })
949
+ w.on('error', () => drop(key))
907
950
  projectWatchers.set(key, w)
908
951
  watchers.add(w)
909
952
  } catch {
910
953
  /* gone meanwhile */
911
954
  }
912
955
  }
913
- const watchFolder = (name: string) => {
914
- // .workpad always; of the rest, a folder that can hold something shown
915
- if (projectWatchers.has(name) || name.includes('/') || (name !== '.workpad' && !FILTER.mayHold(name))) return
916
- const dir = path.join(project.dir, name)
917
- let isDir = false
956
+ const isDir = (dir: string) => {
957
+ try {
958
+ return fs.statSync(dir).isDirectory()
959
+ } catch {
960
+ return false
961
+ }
962
+ }
963
+ // a folder in the project folder (`src`, `src/lib` by folder): watched, if it can hold something shown
964
+ const watchFolder = (rel: string) => {
965
+ if (round !== watchRound || projectWatchers.has(rel)) return
966
+ if (rel !== '.workpad' && !FILTER.mayHold(rel)) return
967
+ const top = !rel.includes('/')
968
+ if (!top && !watchByFolder) return
969
+ const dir = path.join(project.dir, rel)
970
+ if (!isDir(dir)) return
971
+ // .workpad recursively, everywhere: it is small, and its pages' folders come and go
972
+ if (rel === '.workpad' || !watchByFolder) return add(rel, dir, true, rel + '/')
973
+ add(rel, dir, false, rel + '/')
974
+ void walk(rel)
975
+ }
976
+ // the folders in a folder watched on its own, each watched in turn; read off the event loop
977
+ const walk = async (rel: string) => {
978
+ let ents: fs.Dirent[]
918
979
  try {
919
- isDir = fs.statSync(dir).isDirectory()
920
- } catch {}
921
- if (isDir) add(name, dir, true, name + '/')
980
+ ents = await fs.promises.readdir(path.join(project.dir, rel), { withFileTypes: true })
981
+ } catch {
982
+ return
983
+ }
984
+ for (const ent of ents) if (ent.isDirectory()) watchFolder(rel ? `${rel}/${ent.name}` : ent.name)
922
985
  }
923
986
  if (!files) return add('.workpad', project.wp, true, '.workpad/')
924
987
  add('', project.dir, false, '')
988
+ // the folders in the project folder at once, as it starts; deeper ones as they are found
925
989
  for (const ent of fs.readdirSync(project.dir, { withFileTypes: true })) if (ent.isDirectory()) watchFolder(ent.name)
926
990
  }
927
991
 
@@ -1134,9 +1198,12 @@ export function createServer(
1134
1198
  // the browser sends it again when it heard nothing back: appended once, the same answer twice
1135
1199
  const again = isEventId(body.id) ? appended.get(body.id) : undefined
1136
1200
  if (again) return sendJson(res, 200, again)
1201
+ // an event without the data its type requires shows nowhere (a chat message with no text)
1202
+ const refused = refusal(body.type, body.data, (await config()).requires)
1203
+ if (refused) return sendJson(res, 400, { error: refused })
1137
1204
  const event = appendEvent(project.eventsFile, body)
1138
1205
  appended.set(event.id, event)
1139
- if (appended.size > 1000) appended.delete(appended.keys().next().value!)
1206
+ if (appended.size > APPENDED_KEPT) appended.delete(appended.keys().next().value!)
1140
1207
  return sendJson(res, 200, event)
1141
1208
  }
1142
1209
  // an agent shows the reader a place on a page: every tab with it open scrolls there
@@ -1264,7 +1331,7 @@ export function createServer(
1264
1331
  if (p === '/api/events') {
1265
1332
  const all = after(readEvents(project.eventsFile), q.since)
1266
1333
  // what became of each: received by a wait, handled by the agent (status.ts)
1267
- const received = receivedIds(all)
1334
+ const received = receivers(all)
1268
1335
  const handled = handledIds(all)
1269
1336
  return sendJson(
1270
1337
  res,
@@ -1272,11 +1339,16 @@ export function createServer(
1272
1339
  all
1273
1340
  // `type` and `kind` may be several, comma-separated (state.ts); `page` and `exact` as ever
1274
1341
  .filter(e => matches(e, { ...q, type: null }) && matchesQuery(e, q))
1275
- .map(e => ({
1276
- ...e,
1277
- ...(received.has(e.id) && { received: true }),
1278
- ...(handled.has(e.id) && { handled: true }),
1279
- })),
1342
+ .map(e => {
1343
+ const by = received.get(e.id)
1344
+ return {
1345
+ ...e,
1346
+ ...(received.has(e.id) && { received: true }),
1347
+ // who, as the page says it ("received by …")
1348
+ ...(by && { receivedBy: agentLabel(by, names) }),
1349
+ ...(handled.has(e.id) && { handled: true }),
1350
+ }
1351
+ }),
1280
1352
  )
1281
1353
  }
1282
1354
  if (p === '/api/docs') return sendJson(res, 200, await docs())
package/src/set.ts ADDED
@@ -0,0 +1,118 @@
1
+ // `workpad set`: a block of a page replaced by its name, not by matching its text. The page is
2
+ // parsed (so a form shown as an example in a code fence is never touched), and each block it can
3
+ // replace is found by the anchor a link would use: a heading's slug for its section (up to the next
4
+ // heading of the same or a higher level), `<type>:<name>` for a named block (`form:logger`,
5
+ // `chat:notes`, `details:why`, `item:parser`). Everything outside the block stays as it was, byte
6
+ // for byte.
7
+ import { toString } from 'mdast-util-to-string'
8
+ import { parseMarkdown, slug, titleWords, type MdNode } from './pages/markdown.ts'
9
+ import { slugText, hashOf } from './anchors.ts'
10
+ import { edit } from './migrate.ts'
11
+
12
+ /** A block `set` can replace: its anchor, what it is, and where it is in the source. */
13
+ export interface SourceBlock {
14
+ /** the anchor that names it, without `#`: `form:logger`, `open-questions` */
15
+ id: string
16
+ /** `heading` for a section, else the directive's type (`form`, `chat`, `details`, `item`) */
17
+ kind: string
18
+ from: number
19
+ to: number
20
+ }
21
+
22
+ const start = (n: MdNode): number => n.position.start.offset
23
+ const end = (n: MdNode): number => n.position.end.offset
24
+
25
+ /** Directives that are named even without a name: a form or chat without one is `form`, `chat`. */
26
+ const NAMED_BY_TYPE = new Set(['form', 'chat'])
27
+
28
+ /**
29
+ * The blocks of a page's source, in source order, named as the page's anchors name them: headings
30
+ * (numbered on a repeat, as the page does), and container or leaf directives with a name (its
31
+ * `name` or `id`), a label (its slug), or of a type named by itself (a form or chat without a name).
32
+ * A repeat of a directive's id is numbered (`details:why-1`), as a details' is on the page.
33
+ */
34
+ export function blocksOf(source: string): SourceBlock[] {
35
+ const tree = parseMarkdown(source)
36
+ const out: SourceBlock[] = []
37
+ const headings = new Map<string, number>()
38
+ const taken = new Map<string, number>()
39
+ const walk = (parent: MdNode) => {
40
+ const kids = parent.children ?? []
41
+ kids.forEach((node, i) => {
42
+ if (node.type === 'heading' && node.position) {
43
+ // the badges and `:when`s in it aren't its words (titleWords), so they're never its slug
44
+ const id = slug(
45
+ titleWords(node.children ?? [], () => true),
46
+ headings,
47
+ )
48
+ // the section: the heading and what follows it up to the next of the same or a higher level
49
+ let last = node
50
+ for (const next of kids.slice(i + 1)) {
51
+ if (next.type === 'heading' && next.depth <= node.depth) break
52
+ last = next
53
+ }
54
+ if (id && !id.startsWith('wp-')) out.push({ id, kind: 'heading', from: start(node), to: end(last) })
55
+ } else if ((node.type === 'containerDirective' || node.type === 'leafDirective') && node.position) {
56
+ const attrs = (node.attributes ?? {}) as Record<string, string | null | undefined>
57
+ const label =
58
+ node.type === 'containerDirective' && node.children?.[0]?.data?.directiveLabel ? node.children[0] : null
59
+ const labelText = label
60
+ ? slugText(node.name === 'details' ? toString(label as any) : titleWords(label.children ?? [], () => true))
61
+ : ''
62
+ const name = attrs.name || attrs.id || (NAMED_BY_TYPE.has(node.name) ? node.name : labelText)
63
+ if (name) {
64
+ const base = `${node.name}:${name}`
65
+ let id = base
66
+ if (taken.has(base)) {
67
+ let n = taken.get(base)!
68
+ do id = `${base}-${++n}`
69
+ while (taken.has(id))
70
+ taken.set(base, n)
71
+ }
72
+ taken.set(id, 0)
73
+ out.push({ id, kind: node.name, from: start(node), to: end(node) })
74
+ }
75
+ }
76
+ walk(node)
77
+ })
78
+ }
79
+ walk(tree)
80
+ return out
81
+ }
82
+
83
+ /** `name` as a link writes it, or as typed: `#form:logger`, `form:logger`, `form%3Alogger`. */
84
+ function normalize(name: string): string {
85
+ let id = name.trim().replace(/^#/, '')
86
+ try {
87
+ id = decodeURIComponent(id)
88
+ } catch {
89
+ /* as written */
90
+ }
91
+ return id
92
+ }
93
+
94
+ /**
95
+ * The block `name` names: its anchor (`form:logger`, `open-questions`), or a block's bare name
96
+ * (`logger` for `form:logger`) when only one block has it. Throws, listing the page's blocks, when
97
+ * none does, or when the bare name fits several.
98
+ */
99
+ export function findBlock(source: string, name: string): SourceBlock {
100
+ const blocks = blocksOf(source)
101
+ const id = normalize(name)
102
+ // `#logger` is the anchor as a link writes it: that heading, never the form of that name
103
+ const exact = name.trim().startsWith('#')
104
+ const fits = blocks.filter(b => b.id === id || (!exact && b.id === `${b.kind}:${id}`))
105
+ if (fits.length === 1) return fits[0]
106
+ const list = (bs: SourceBlock[]) => bs.map(b => ` ${hashOf(b.id)} ${b.kind}`).join('\n')
107
+ if (fits.length > 1)
108
+ throw new Error(`${id} fits ${fits.length} blocks; name one by its anchor, with its #:\n${list(fits)}`)
109
+ throw new Error(
110
+ `no block ${hashOf(id)} on the page${blocks.length ? `; it has:\n${list(blocks)}` : ', nor any other with a name'}`,
111
+ )
112
+ }
113
+
114
+ /** `source` with the block `name` names replaced by `markdown` (its trailing blank lines left off). */
115
+ export function setBlock(source: string, name: string, markdown: string): string {
116
+ const block = findBlock(source, name)
117
+ return edit(source, [{ from: block.from, to: block.to, text: markdown.replace(/\s+$/, '') }])
118
+ }
package/src/status.ts CHANGED
@@ -29,9 +29,10 @@
29
29
  // A message is an agent's event of a type a plugin declares `forReader` (a reply in a comment
30
30
  // thread, a chat message). It is unread until a `workpad:read` event from the reader names it,
31
31
  // which the page appends once the message has been in view; one the agent replaced (`replaces`)
32
- // no longer counts, nor one in a chat no longer on the page (its form or block taken off): the page
32
+ // no longer counts, nor one without the data its type requires (a chat message with no chat or
33
+ // no text: nothing shows it), nor one in a chat no longer on the page (its form or block taken off): the page
33
34
  // keeps those folded after its content, as a record, not as something to read.
34
- import type { FormState, Listener, Marks, PageStatus, WpEvent } from './define.ts'
35
+ import type { Delivery, FormState, Listener, Marks, PageStatus, WpEvent } from './define.ts'
35
36
 
36
37
  /**
37
38
  * Can this be a question's name, the type of its answers? Not with a colon: types with one belong
@@ -129,6 +130,44 @@ export function questionState(
129
130
  export const heard = (name: string, listeners: Listener[]): boolean =>
130
131
  listeners.some(l => l.type === null || l.type === name)
131
132
 
133
+ /**
134
+ * After how long an answer no agent received is late, in ms: the page flags it ("not received after
135
+ * 10 min") and counts it, as something went wrong on the agent's side (a session gone, a channel
136
+ * down, a server under load).
137
+ */
138
+ export const NOT_RECEIVED_AFTER = 10 * 60_000
139
+
140
+ /**
141
+ * Where one of the reader's events for an agent went (Delivery), at time `now` (ms): from its marks
142
+ * (received, handled; `receivedBy`), whether it is still on its way (`sending`), and who listens on
143
+ * its page (`listeners`, those covering it). Someone takes it when a listener hears its type
144
+ * (heard): a listen on the page, a confirmed channel, also a coordinator's listen on the unfollowed
145
+ * pages, which follows the page for no one but does receive what is sent there.
146
+ */
147
+ export function deliveryOf(
148
+ e: WpEvent,
149
+ listeners: Listener[],
150
+ now: number,
151
+ after: number = NOT_RECEIVED_AFTER,
152
+ ): Delivery {
153
+ if (e.sending) return { state: 'sending', text: 'sending…' }
154
+ if (e.handled) return { state: 'handled', text: 'handled' }
155
+ if (e.received)
156
+ return e.receivedBy
157
+ ? { state: 'received', text: `received by ${e.receivedBy}`, by: e.receivedBy }
158
+ : { state: 'received', text: 'received' }
159
+ const nobody = !heard(e.type, listeners)
160
+ if (now - Date.parse(e.ts) >= after)
161
+ return {
162
+ state: 'late',
163
+ text: `not received after ${Math.round(after / 60_000)} min${nobody ? ' · no one follows this page' : ''}`,
164
+ nobody,
165
+ }
166
+ return nobody
167
+ ? { state: 'unfollowed', text: 'no one follows this page — it waits until an agent listens' }
168
+ : { state: 'waiting', text: 'waiting for an agent to receive it' }
169
+ }
170
+
132
171
  /** The type of the event the page appends once messages were in view: `{ ids }`. */
133
172
  export const READ = 'workpad:read'
134
173
 
@@ -140,14 +179,42 @@ export const READ = 'workpad:read'
140
179
  export const SCROLL = 'workpad:scroll'
141
180
 
142
181
  /**
143
- * The agent's messages on a page the reader hasn't read: events from the agent of a type
144
- * `isMessage` says is for the reader, not named by a `workpad:read` from the reader, not
145
- * replaced by a later one (`replaces`), and, given the page's `chats`, not in a chat (`data.chat`)
146
- * that is no longer among them.
182
+ * The fields of an event's `data` its type requires (EventSpec.requires) that it lacks: each must
183
+ * be a non-empty string.
184
+ */
185
+ export const missingData = (data: Record<string, unknown> | null | undefined, requires: readonly string[]): string[] =>
186
+ requires.filter(field => {
187
+ const value = data?.[field]
188
+ return typeof value !== 'string' || !value.trim()
189
+ })
190
+
191
+ /**
192
+ * Why an event of `type` with this `data` can't go in the log, given the types that require data
193
+ * fields: what it lacks, and the shape it needs; null when nothing is missing.
194
+ */
195
+ export function refusal(
196
+ type: string,
197
+ data: Record<string, unknown> | null | undefined,
198
+ requires: ReadonlyMap<string, readonly string[]>,
199
+ ): string | null {
200
+ const fields = requires.get(type) ?? []
201
+ const missing = missingData(data, fields)
202
+ if (!missing.length) return null
203
+ const list = (names: readonly string[]) => names.join(names.length > 2 ? ', ' : ' and ').replace(/, (?=[^,]*$)/, ' and ')
204
+ const shape = JSON.stringify(Object.fromEntries(fields.map(f => [f, '…'])))
205
+ return `a ${type} needs ${list(fields)} in its data, each a non-empty string; ${list(missing)} ${missing.length > 1 ? 'are' : 'is'} missing or empty. Its data: ${shape}`
206
+ }
207
+
208
+ /**
209
+ * The agent's messages on a page the reader hasn't read: events from the agent of a type in
210
+ * `messages` (the types for the reader, each with the `data` fields it requires), not named by a
211
+ * `workpad:read` from the reader, not replaced by a later one (`replaces`), with the data their
212
+ * type requires (one without it shows nowhere on the page, so it waits for nobody), and, given the
213
+ * page's `chats`, not in a chat (`data.chat`) that is no longer among them.
147
214
  */
148
215
  export function unreadMessages(
149
216
  events: WpEvent[],
150
- isMessage: (type: string) => boolean,
217
+ messages: ReadonlyMap<string, readonly string[]>,
151
218
  chats?: ReadonlySet<string> | null,
152
219
  ): WpEvent[] {
153
220
  const read = new Set<string>()
@@ -157,10 +224,12 @@ export function unreadMessages(
157
224
  for (const id of (e.data?.ids as unknown[] | undefined) ?? []) read.add(String(id))
158
225
  if (e.data?.replaces) replaced.add(String(e.data.replaces))
159
226
  }
227
+ const shown = (e: WpEvent) => {
228
+ const requires = messages.get(e.type)
229
+ return !!requires && !missingData(e.data, requires).length
230
+ }
160
231
  const offPage = (e: WpEvent) => !!chats && typeof e.data?.chat === 'string' && !chats.has(e.data.chat)
161
- return events.filter(
162
- e => !fromReader(e) && isMessage(e.type) && !read.has(e.id) && !replaced.has(e.id) && !offPage(e),
163
- )
232
+ return events.filter(e => !fromReader(e) && shown(e) && !read.has(e.id) && !replaced.has(e.id) && !offPage(e))
164
233
  }
165
234
 
166
235
  /** How many things on a page wait for the reader: its open questions and unread messages. */
@@ -236,6 +305,24 @@ export function namesOf(events: WpEvent[]): Map<string, string> {
236
305
  return names
237
306
  }
238
307
 
308
+ /**
309
+ * Who received each answer first, by its id: the `by` of the first RECEIVED naming it (null when
310
+ * the command line knew no one). Only the command line's marks count.
311
+ */
312
+ export function receivers(events: WpEvent[]): Map<string, string | null> {
313
+ const by = new Map<string, string | null>()
314
+ for (const e of events)
315
+ if (e.type === RECEIVED && !fromReader(e)) {
316
+ const id = String(e.data?.event)
317
+ if (!by.has(id)) by.set(id, e.by ?? null)
318
+ }
319
+ return by
320
+ }
321
+
322
+ /** An agent as a page names it: the name it gave itself (`names`), else its id, a long one (a session's) cut short. */
323
+ export const agentLabel = (id: string, names: Map<string, string> = new Map()): string =>
324
+ names.get(id) ?? (id.length > 16 ? id.slice(0, 8) : id)
325
+
239
326
  /** The ids of the answers a wait or watch printed. Only the command line's marks count. */
240
327
  export function receivedIds(events: WpEvent[]): Set<string> {
241
328
  return new Set(events.filter(e => e.type === RECEIVED && !fromReader(e)).map(e => String(e.data?.event)))
@@ -334,8 +421,8 @@ export interface StatusInput {
334
421
  listeners: (page: string) => Listener[]
335
422
  /** the event types handed to an agent (a form's answers; plugins' events declared handOut) */
336
423
  forAgent: (type: string) => boolean
337
- /** the event types that are messages for the reader (declared forReader) */
338
- forReader: (type: string) => boolean
424
+ /** the event types that are messages for the reader (declared forReader), each with the `data` fields it requires */
425
+ forReader: ReadonlyMap<string, readonly string[]>
339
426
  }
340
427
 
341
428
  /** A project's status at one moment: what `workpad status`, the page lists and the log's marks take. */
@@ -454,7 +541,7 @@ export function statusLines(p: PageStatus, file: string, { waiting = true } = {}
454
541
  */
455
542
  export const whose = (p: PageStatus, me: string | null, names: Map<string, string> = new Map()): string =>
456
543
  p.subscribers.length
457
- ? p.subscribers.map(s => (s === me ? 'you' : (names.get(s) ?? (s.length > 16 ? s.slice(0, 8) : s)))).join(', ')
544
+ ? p.subscribers.map(s => (s === me ? 'you' : agentLabel(s, names))).join(', ')
458
545
  : 'no one subscribed'
459
546
 
460
547
  /** The type of a chat message: `{ chat, text }` (the chat plugin's; the core shows the agent's as small pages). */