@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
@@ -231,6 +231,8 @@ function draw() {
231
231
  badge.toggleAttribute('data-unread', unread)
232
232
  badge.title = unread ? 'the agent replied: unread' : lastFromAgent(t) ? 'the agent replied' : 'comment'
233
233
  badge.textContent = String(1 + t.replies.length)
234
+ // the reader's comment or reply no agent received for long: the page counts it and goes here
235
+ if (late(t)) badge.dataset.wpDelivery = 'late'
234
236
  const rect = t.range?.getClientRects()[0]
235
237
  // a passage that is gone from the page: its badge stays where the passage was (at the top, if
236
238
  // nothing of there is left), still open until closed
@@ -307,15 +309,29 @@ function refreshComments() {
307
309
  // messages as markdown, rendered by the server, by their text
308
310
  const rendered = new Map<string, string>()
309
311
 
312
+ /** Does a thread hold a message of the reader's no agent received for long (api.delivery)? */
313
+ const late = (t: Thread) => [t.comment, ...t.replies].some(e => api.delivery().get(e.id)?.state === 'late')
314
+
310
315
  function renderPopover() {
311
316
  const t = threads.find(x => x.id === openThread)
312
317
  if (!t) return
313
318
  const who = (e: WpEvent) => (e.from === 'cli' ? 'agent' : 'you')
319
+ // Where the reader's messages went, said quietly under the one it is about: their latest, while
320
+ // the agent hasn't replied after it (a reply says it all), and any no agent received for long
321
+ const all = [t.comment, ...t.replies]
322
+ const lastAgent = all.findLastIndex(e => e.from === 'cli')
323
+ const lastOwn = all.findLastIndex(e => e.from !== 'cli' && !e.sending)
324
+ const deliveryOf = (e: WpEvent) => {
325
+ const i = all.indexOf(e)
326
+ const d = e.from !== 'cli' && !e.sending ? api.delivery().get(e.id) : undefined
327
+ return d && (d.state === 'late' || (i === lastOwn && i > lastAgent)) ? d : undefined
328
+ }
314
329
  // the quote and every message are text from the reader or the agent: `html` escapes them
315
330
  // a message is markdown: as rendered, once the server has (api.markdown), as plain text till then
316
331
  const message = (e: WpEvent) => {
317
332
  const text = String(e.data.text ?? '')
318
333
  const md = rendered.get(text)
334
+ const d = deliveryOf(e)
319
335
  // shown at once, not yet confirmed by the server
320
336
  return html`<div
321
337
  class="wp-thread-message"
@@ -325,6 +341,7 @@ function renderPopover() {
325
341
  >
326
342
  <span class="wp-thread-who">${who(e)}</span>
327
343
  <div class="wp-thread-text" ${md != null ? raw(' data-md') : ''}>${md != null ? raw(md) : text}</div>
344
+ ${d && html`<span class="wp-thread-delivery" role="status" data-wp-delivery="${d.state}">${d.text}</span>`}
328
345
  </div>`
329
346
  }
330
347
  // the reply being typed: its text, and its focus and caret, which a redraw would take
@@ -714,6 +731,8 @@ const mount: PluginMount = (el: HTMLElement, handle: PageHandle, core: Api) => {
714
731
  })
715
732
 
716
733
  api.events.on(refreshComments)
734
+ // where the reader's messages went: who received them, one turned late
735
+ api.delivery.on(refreshComments)
717
736
  api.onRendered(refreshComments)
718
737
  new ResizeObserver(() => draw()).observe(root)
719
738
  addEventListener('resize', () => draw())
@@ -16,10 +16,16 @@ export default function comments(): Plugin {
16
16
  events: {
17
17
  'comments:new': {
18
18
  handOut: true,
19
+ requires: ['text'],
19
20
  description:
20
21
  "a comment on a passage or lines of code: `{ quote, before, after, block, at?, text }`; its id is the thread's",
21
22
  },
22
- 'comments:reply': { handOut: true, forReader: true, description: 'a reply in a thread: `{ replyTo, text }`' },
23
+ 'comments:reply': {
24
+ handOut: true,
25
+ forReader: true,
26
+ requires: ['replyTo', 'text'],
27
+ description: 'a reply in a thread: `{ replyTo, text }`',
28
+ },
23
29
  'comments:resolve': { description: 'the reader closed a thread: `{ replyTo }`' },
24
30
  },
25
31
  public: builtinPublic('comments'),
@@ -103,6 +103,15 @@
103
103
  .wp-thread-message[data-from='agent'] .wp-thread-who {
104
104
  color: var(--accent, #1d5bbf);
105
105
  }
106
+ /* where the reader's message went (api.delivery), quietly under it; not received for long: the warning colour */
107
+ .wp-thread-delivery {
108
+ font-size: var(--ui-tiny);
109
+ color: var(--muted, #696e76);
110
+ }
111
+ .wp-thread-delivery[data-wp-delivery='late'] {
112
+ color: var(--warn, #6b4fc0);
113
+ font-weight: var(--weight-strong);
114
+ }
106
115
  .wp-thread-text {
107
116
  white-space: pre-wrap;
108
117
  overflow-wrap: anywhere;
@@ -117,7 +117,7 @@ but send nothing.
117
117
  answering it: under every form is a chat (see the chat plugin), named
118
118
  after the form, whose messages are never a submit, so talking about a choice
119
119
  never makes it. Answer there with `workpad append --type chat:message
120
- --data '{"chat":"<form name>","text":"…"}'`, and don't add a free-text field
120
+ --data '{"chat":"<form name>"}' --text-file -` (the text on standard input), and don't add a free-text field
121
121
  for questions to a decision form. A form that asks nothing to talk about (a
122
122
  lone button that starts something) can leave its chat out:
123
123
  `:::form{name=start chat=false}`.
package/plugins/index.ts CHANGED
@@ -23,6 +23,7 @@ import badge from './badge/index.ts'
23
23
  import ansi from './ansi/index.ts'
24
24
  import timeline from './timeline/index.ts'
25
25
  import toc from './toc/index.ts'
26
+ import progress from './progress/index.ts'
26
27
 
27
28
  export function builtins(): Plugin[] {
28
29
  return [
@@ -45,5 +46,6 @@ export function builtins(): Plugin[] {
45
46
  ansi(),
46
47
  timeline(),
47
48
  toc(),
49
+ progress(),
48
50
  ]
49
51
  }
@@ -103,7 +103,8 @@ export async function channel(ctx: CommandContext) {
103
103
  // a page taken on through the channel: what is new, not the past someone already received
104
104
  const since = channelSince(read(ctx.eventsFile).events, agent, page) ?? undefined
105
105
  void ctx
106
- .handOut({ page, exact: true }, push, { mark: false, agent, skipReceivedBefore: since })
106
+ // what it wrote in its session, when WORKPAD_AGENT names it, is its own too
107
+ .handOut({ page, exact: true }, push, { mark: false, agent, aliases: new Set([session]), skipReceivedBefore: since })
107
108
  .catch(err => problem('handing out failed', { page, err: String(err) }))
108
109
  }
109
110
  }
@@ -0,0 +1,41 @@
1
+ How far a long piece of work is, live, where the reader would ask: a
2
+ `:progress{id=…}` inline on a page, moved by the agent doing the work with
3
+ `workpad progress`. Moving it appends an event to the page's log and leaves
4
+ the page as it is, so it never fights another writer, and a job can move a
5
+ progress on a page that isn't its own.
6
+
7
+ ```markdown
8
+ ## The probe
9
+
10
+ Captures 3 and 4 :progress{id=probe}
11
+ ```
12
+
13
+ ```sh
14
+ workpad progress goldens probe 287/1413 "captures 3 and 4" --eta 20m
15
+ workpad progress goldens probe "building the stack" # no count
16
+ workpad progress goldens probe 1413/1413 "all 287 checked" # n = total: done
17
+ workpad progress goldens probe done "all 287 checked"
18
+ workpad progress goldens probe failed "Docker ran out of disk"
19
+ ```
20
+
21
+ On the page it shows a small bar and the count, the note, the time left
22
+ (`--eta`, else from the rate so far) and how long ago it moved; without a
23
+ count a pulsing dot; `done` and `failed` with when; "waiting to start"
24
+ before its first update. The corner has a card for it while it runs, and
25
+ one that stays once it ended until the reader has clicked to it; a click
26
+ goes to the marker. `workpad status` lists the running ones, and the
27
+ shared server's overview shows each page's on its card.
28
+
29
+ Ids are per page, letters, digits, `-` and `_`. Several on a page are one
30
+ per piece of work.
31
+
32
+ **Stale:** a running progress past its ETA, or without an update for 15
33
+ minutes, greys. The server then nudges the agent that last moved it, once,
34
+ and again at most every 15 minutes while it stays stale: a `progress:stale`
35
+ event, handed out like an answer (a channel pushes it, `workpad listen
36
+ --wait` returns with it, the turn-end check mentions it). Moving the
37
+ progress, or marking it done or failed, answers it. So move it while the
38
+ work runs, and end it when the work ends, failed too.
39
+
40
+ The times are the plugin's options, in milliseconds, in the config:
41
+ `progress({ staleAfter, nudgeEvery, checkEvery })`.
@@ -0,0 +1,172 @@
1
+ // The page's side of `:progress` (index.ts): each marker drawn from the log, again as updates come,
2
+ // as the page is patched, and every few seconds for its times; and a quiet toast in the corner per
3
+ // progress, there while it runs whether its marker is in view or not, a click going to the marker.
4
+ // One that ended (done, failed) stays until the reader has clicked to it; which they have is kept
5
+ // per page in localStorage, by the update that ended it.
6
+ import type { Api, PageHandle, PluginMount, Toast, ToastOptions } from '../../src/define.ts'
7
+ import { STALE_AFTER, ago, countText, isStale, leftText, progressOn, span, type Progress } from './state.ts'
8
+
9
+ /** An element with a class, and text when given. */
10
+ function h(tag: string, className: string, text?: string): HTMLElement {
11
+ const el = document.createElement(tag)
12
+ el.className = className
13
+ if (text != null) el.textContent = text
14
+ return el
15
+ }
16
+
17
+ /** `14:12`: when it ended, as the reader's clock says. */
18
+ const clock = (ts: string) =>
19
+ new Date(ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' })
20
+
21
+ /** How far, 0 to 1, or null without a count. */
22
+ const fraction = (p: Progress) => (p.n != null && p.total ? p.n / p.total : null)
23
+
24
+ const WORDS = { running: 'running', done: 'done', failed: 'failed' } as const
25
+
26
+ /** A marker's content for `p` (undefined: no update yet) at `now`. */
27
+ function drawMarker(el: HTMLElement, p: Progress | undefined, now: number, staleAfter: number) {
28
+ const body = el.querySelector<HTMLElement>(':scope > .wp-progress-body')
29
+ if (!body) return
30
+ if (!p) {
31
+ el.dataset.wpProgress = 'waiting'
32
+ el.removeAttribute('data-wp-stale')
33
+ body.replaceChildren(h('span', 'wp-progress-note', 'waiting to start'))
34
+ return
35
+ }
36
+ const stale = isStale(p, now, staleAfter)
37
+ el.dataset.wpProgress = p.state
38
+ el.toggleAttribute('data-wp-stale', stale)
39
+ const parts: HTMLElement[] = []
40
+ const f = fraction(p)
41
+ if (p.state === 'running' && f != null) {
42
+ const bar = h('span', 'wp-progress-bar')
43
+ const fill = h('span', '')
44
+ fill.style.width = `${Math.round(f * 1000) / 10}%`
45
+ bar.append(fill)
46
+ bar.setAttribute('role', 'progressbar')
47
+ bar.setAttribute('aria-valuemin', '0')
48
+ bar.setAttribute('aria-valuemax', String(p.total))
49
+ bar.setAttribute('aria-valuenow', String(p.n))
50
+ parts.push(bar, h('span', 'wp-progress-count', countText(p)))
51
+ } else parts.push(h('span', 'wp-progress-state', WORDS[p.state]))
52
+ if (p.note) parts.push(h('span', 'wp-progress-note', p.note))
53
+ const when: string[] = []
54
+ if (p.state !== 'running') when.push(clock(p.ts))
55
+ else if (stale) when.push(`no update for ${span(now - Date.parse(p.ts))}`)
56
+ else {
57
+ const left = leftText(p, now)
58
+ if (left) when.push(left)
59
+ when.push(ago(now - Date.parse(p.ts)))
60
+ }
61
+ parts.push(h('span', 'wp-progress-when', when.join(' · ')))
62
+ body.replaceChildren(...parts)
63
+ el.title = `${p.id}: ${p.state}${p.by ? `, moved by ${p.by}` : ''}`
64
+ }
65
+
66
+ /** What a progress's toast says, and its time and bar. */
67
+ function toastOf(p: Progress, now: number, staleAfter: number): { text: string } & Pick<ToastOptions, 'meta' | 'bar'> {
68
+ const what = p.state === 'running' ? countText(p) || p.note : p.note || WORDS[p.state]
69
+ const mark = p.state === 'done' ? '✓ ' : p.state === 'failed' ? '✗ ' : ''
70
+ const text = `${mark}${p.id}${what ? ` · ${what}` : ''}`
71
+ if (p.state !== 'running')
72
+ return { text, meta: ago(now - Date.parse(p.ts)), bar: { value: 1, tone: p.state === 'done' ? 'good' : 'bad' } }
73
+ const stale = isStale(p, now, staleAfter)
74
+ return {
75
+ text,
76
+ meta: stale ? `no update ${span(now - Date.parse(p.ts))}` : leftText(p, now) || ago(now - Date.parse(p.ts)),
77
+ bar: { value: fraction(p), tone: 'accent' },
78
+ }
79
+ }
80
+
81
+ const mount: PluginMount = (root: HTMLElement, page: PageHandle, api: Api) => {
82
+ if (!page.live) return
83
+ const staleAfter =
84
+ Number(document.querySelector<HTMLMetaElement>('meta[name=wp-progress]')?.dataset.staleAfter) || STALE_AFTER
85
+ // the ended ones the reader has clicked to, by the update that ended them
86
+ const seenKey = `wp-progress-seen:${location.pathname}`
87
+ let seen = new Set<string>()
88
+ try {
89
+ seen = new Set(JSON.parse(localStorage.getItem(seenKey) ?? '[]') as string[])
90
+ } catch {
91
+ /* storage unavailable */
92
+ }
93
+ const remember = (event: string) => {
94
+ seen.add(event)
95
+ try {
96
+ localStorage.setItem(seenKey, JSON.stringify([...seen].slice(-200)))
97
+ } catch {
98
+ /* storage unavailable */
99
+ }
100
+ }
101
+
102
+ const toasts = new Map<string, Toast>()
103
+ // the progress each toast is of now, read on its click
104
+ const current = new Map<string, Progress>()
105
+ // the marker a click went to last, per id: a progress shown in several places goes to each in turn
106
+ const turn = new Map<string, number>()
107
+
108
+ const markers = (id: string) =>
109
+ [...root.querySelectorAll<HTMLElement>('.wp-progress[data-progress]')].filter(el => el.dataset.progress === id)
110
+
111
+ function jump(id: string) {
112
+ const p = current.get(id)
113
+ if (p && p.state !== 'running') {
114
+ remember(p.event)
115
+ toasts.get(id)?.close()
116
+ toasts.delete(id)
117
+ }
118
+ const list = markers(id)
119
+ if (!list.length) return
120
+ const i = ((turn.get(id) ?? -1) + 1) % list.length
121
+ turn.set(id, i)
122
+ const el = list[i]!
123
+ el.scrollIntoView({ block: 'center', behavior: 'smooth' })
124
+ el.classList.remove('wp-flash')
125
+ void el.offsetWidth
126
+ el.classList.add('wp-flash')
127
+ }
128
+
129
+ function draw() {
130
+ const now = Date.now()
131
+ const list = progressOn(api.events(), api.page)
132
+ const byId = new Map(list.map(p => [p.id, p]))
133
+ for (const el of root.querySelectorAll<HTMLElement>('.wp-progress[data-progress]'))
134
+ drawMarker(el, byId.get(el.dataset.progress!), now, staleAfter)
135
+ for (const p of list) {
136
+ const wanted = p.state === 'running' || !seen.has(p.event)
137
+ let toast = toasts.get(p.id)
138
+ if (!wanted) {
139
+ toast?.close()
140
+ toasts.delete(p.id)
141
+ continue
142
+ }
143
+ current.set(p.id, p)
144
+ const { text, meta, bar } = toastOf(p, now, staleAfter)
145
+ if (!toast) {
146
+ toast = api.toast(text, {
147
+ kind: 'quiet',
148
+ ms: 0,
149
+ name: `progress-${p.id}`,
150
+ order: -3,
151
+ meta,
152
+ bar,
153
+ onClick: () => jump(p.id),
154
+ })
155
+ toasts.set(p.id, toast)
156
+ } else toast.update(text, { meta: meta ?? null, bar: bar ?? null })
157
+ }
158
+ for (const [id, toast] of toasts)
159
+ if (!byId.has(id)) {
160
+ toast.close()
161
+ toasts.delete(id)
162
+ }
163
+ }
164
+
165
+ draw()
166
+ api.events.on(draw)
167
+ // a patched page has its markers back as the server rendered them
168
+ api.onRendered(draw)
169
+ setInterval(draw, 10_000)
170
+ }
171
+
172
+ export default mount
@@ -0,0 +1,166 @@
1
+ // :progress{id=…} — how far a piece of work is, shown live where it is written on a page; the agent
2
+ // doing the work moves it with `workpad progress`, which appends an event and never edits the page.
3
+ // See README.md; where each one stands is read from the log by state.ts, here, on the command line
4
+ // and in the browser alike.
5
+ //
6
+ // The server watches the log for progress gone stale (past its ETA, or without an update for a
7
+ // while) and nudges the agent that last moved it: a `progress:stale` event, handed out like an
8
+ // answer, so a channel pushes it and a `listen --wait` returns with it.
9
+ import fs from 'node:fs'
10
+ import path from 'node:path'
11
+ import { definePlugin, html, anchorTaken, type DirectiveContext, type Plugin } from '@bigmistqke/workpad'
12
+ import { appendEvent, handle, handledIds, read } from '@bigmistqke/workpad/log'
13
+ import { builtinPublic } from '../../src/package.ts'
14
+ import {
15
+ MINUTE,
16
+ NUDGER,
17
+ NUDGE_EVERY,
18
+ STALE,
19
+ STALE_AFTER,
20
+ UPDATE,
21
+ isProgressId,
22
+ keyOf,
23
+ line,
24
+ nudgesDue,
25
+ openNudges,
26
+ parseArgs,
27
+ progressOf,
28
+ } from './state.ts'
29
+
30
+ export interface ProgressOptions {
31
+ /** a running progress without an update this long is stale, in ms (default 15 minutes) */
32
+ staleAfter?: number
33
+ /** a stale progress is nudged again at most this often, in ms (default 15 minutes) */
34
+ nudgeEvery?: number
35
+ /** how often the server looks for stale progress, in ms (default a minute) */
36
+ checkEvery?: number
37
+ /** the time, for tests: ms since the epoch */
38
+ now?: () => number
39
+ }
40
+
41
+ /** `:progress{id=probe}`: the marker, drawn by the page's client from the log; "waiting to start" until then. */
42
+ function render(ctx: DirectiveContext) {
43
+ const id = ctx.attrs.id ?? ''
44
+ if (!id) {
45
+ ctx.problem('`:progress` needs an id, which `workpad progress` moves it by: `:progress{id=probe}`')
46
+ return html``
47
+ }
48
+ if (!isProgressId(id)) ctx.problem(`\`:progress{id=${id}}\`: an id is letters, digits, - and _`)
49
+ const anchor = ctx.anchor('progress', id)
50
+ // the body is the browser's to draw: quiet, so a progress moving never marks the block new
51
+ return html`<span class="wp-progress" data-progress="${id}" ${anchor ? html` id="${anchor}"` : ''}
52
+ >${!anchor ? anchorTaken('progress', id) : ''}<span class="wp-progress-body" data-wp-quiet
53
+ ><span class="wp-progress-note">waiting to start</span></span
54
+ ></span
55
+ >`
56
+ }
57
+
58
+ // one watch per log: a config loaded again sets the plugin up again, and takes over the watch
59
+ const watches = new Map<string, ReturnType<typeof setInterval>>()
60
+
61
+ /** Append the nudges due at `now` to the log in `file`; returns them. */
62
+ export function nudgeStale(file: string, now: number, options: ProgressOptions = {}) {
63
+ const due = nudgesDue(read(file).events, now, {
64
+ staleAfter: options.staleAfter ?? STALE_AFTER,
65
+ every: options.nudgeEvery ?? NUDGE_EVERY,
66
+ })
67
+ return due.map(n => appendEvent(file, n, 'cli', NUDGER))
68
+ }
69
+
70
+ /** Whether page `page` is there to show a progress: a page of `.workpad/pages/`, or a file of the repository. */
71
+ function pageExists(wp: string, dir: string, page: string) {
72
+ if (page.startsWith('-/')) return fs.existsSync(path.join(dir, page.slice(2)))
73
+ const pages = path.join(wp, 'pages')
74
+ return fs.existsSync(path.join(pages, `${page}.md`)) || fs.existsSync(path.join(pages, page, 'index.md'))
75
+ }
76
+
77
+ /** The page's source, when it has one to look in for its marker. */
78
+ function sourceOf(wp: string, page: string): string | null {
79
+ const pages = path.join(wp, 'pages')
80
+ for (const file of [path.join(pages, `${page}.md`), path.join(pages, page, 'index.md')])
81
+ try {
82
+ return fs.readFileSync(file, 'utf8')
83
+ } catch {
84
+ /* not this one */
85
+ }
86
+ return null
87
+ }
88
+
89
+ export default function progress(options: ProgressOptions = {}): Plugin {
90
+ const now = options.now ?? Date.now
91
+ return definePlugin({
92
+ name: 'progress',
93
+ public: builtinPublic('progress'),
94
+ blocks: {
95
+ progress: {
96
+ menu: { group: 'mark', summary: 'how far a long piece of work is, moved live by `workpad progress`' },
97
+ attrs: ['id'],
98
+ style: 'style.css',
99
+ html: ctx => render(ctx as DirectiveContext),
100
+ },
101
+ },
102
+ events: {
103
+ [UPDATE]: {
104
+ description:
105
+ 'a progress moved (`workpad progress`): `{ id, n, total, note, eta, state }`, `n` and `total` null without a count, `eta` seconds from it, `state` running, done or failed',
106
+ },
107
+ [STALE]: {
108
+ handOut: true,
109
+ description:
110
+ 'the server nudges the agent that last moved a progress gone stale: `{ id, to, nudge, since, at }`, `to` that agent, `nudge` what to run. Moving the progress handles it',
111
+ },
112
+ },
113
+ setup(ctx) {
114
+ const file = path.join(ctx.project.wp, 'events.ndjson')
115
+ clearInterval(watches.get(file))
116
+ const timer = setInterval(() => {
117
+ try {
118
+ nudgeStale(file, now(), options)
119
+ } catch (err) {
120
+ console.error('progress: looking for stale progress failed:', err)
121
+ }
122
+ }, options.checkEvery ?? MINUTE)
123
+ timer.unref()
124
+ watches.set(file, timer)
125
+ return {
126
+ client: 'client.js',
127
+ // when it counts as stale, for the page to grey it at the same time
128
+ slots: () =>
129
+ options.staleAfter != null
130
+ ? { head: html`<meta name="wp-progress" data-stale-after="${String(options.staleAfter)}" />` }
131
+ : null,
132
+ }
133
+ },
134
+ commands: {
135
+ '': {
136
+ description:
137
+ 'move a `:progress{id=…}` on a page: how far (`287/1413`), a note, and `--eta`; or `done`, `failed`. Appends an event; the page is left as it is',
138
+ args: '<page|file> <id> [<n>/<total> | done | failed] "<note>"',
139
+ options: { eta: { type: 'string?', value: 'time', description: 'the time left: 20m, 90s, 1h30m' } },
140
+ run(ctx) {
141
+ const [target, id, ...rest] = ctx.positionals
142
+ if (!target || !id || !rest.length)
143
+ throw new Error(
144
+ 'usage: workpad progress <page> <id> <n>/<total> "<note>" [--eta 20m], or <page> <id> "<note>", <page> <id> done|failed "<note>"',
145
+ )
146
+ if (!isProgressId(id)) throw new Error(`progress id ${JSON.stringify(id)}: letters, digits, - and _`)
147
+ const page = ctx.page(target)
148
+ if (!pageExists(ctx.project.wp, ctx.project.dir, page)) throw new Error(`no page ${page}`)
149
+ const data = parseArgs(rest, (ctx.options.eta as string | undefined) ?? null)
150
+ const before = read(ctx.eventsFile).events
151
+ const event = appendEvent(ctx.eventsFile, { page, type: UPDATE, data: { id, ...data } }, 'cli', ctx.agent)
152
+ // moving it answers the nudges about it
153
+ for (const e of openNudges(before, page, id, handledIds(before))) handle(ctx.eventsFile, e, ctx.agent)
154
+ const p = progressOf([...before, event]).get(keyOf(page, id))!
155
+ console.log(`${page}: ${line(p, Date.parse(event.ts))}`)
156
+ const source = sourceOf(ctx.project.wp, page)
157
+ if (source != null && !new RegExp(`:progress\\{[^}]*\\bid=["']?${id}(?![\\w-])`).test(source))
158
+ console.error(
159
+ `workpad: ${page} has no :progress{id=${id}}: put one where it should show (the corner shows it all the same)`,
160
+ )
161
+ },
162
+ },
163
+ },
164
+ docs: () => fs.readFileSync(new URL('./README.md', import.meta.url), 'utf8'),
165
+ })
166
+ }
@@ -0,0 +1,85 @@
1
+ /* A progress, inline where it is written (client.ts draws it): a small bar and the count while it
2
+ runs, or a word with a dot (running without a count, done, failed); the note; and its time, muted.
3
+ Its state is data-wp-progress (waiting, running, done, failed); data-wp-stale greys it. */
4
+ .wp-progress {
5
+ font-size: 0.9em;
6
+ }
7
+ .wp-progress-body {
8
+ display: inline-flex;
9
+ flex-wrap: wrap;
10
+ align-items: center;
11
+ gap: 2px var(--space-md, 8px);
12
+ vertical-align: baseline;
13
+ font-family: var(--sans);
14
+ }
15
+ .wp-progress[data-wp-progress='waiting'] .wp-progress-note {
16
+ color: var(--muted);
17
+ font-style: italic;
18
+ }
19
+ .wp-progress-bar {
20
+ position: relative;
21
+ display: inline-block;
22
+ width: 64px;
23
+ height: 5px;
24
+ border-radius: 3px;
25
+ overflow: hidden;
26
+ background: color-mix(in srgb, var(--muted) 28%, transparent);
27
+ }
28
+ .wp-progress-bar > span {
29
+ position: absolute;
30
+ inset: 0 auto 0 0;
31
+ border-radius: inherit;
32
+ background: var(--accent);
33
+ }
34
+ .wp-progress-count {
35
+ font-variant-numeric: tabular-nums;
36
+ font-weight: var(--weight-strong, 600);
37
+ }
38
+ .wp-progress-when {
39
+ color: var(--muted);
40
+ font-size: 0.92em;
41
+ }
42
+ /* the word, with its dot: blue and pulsing while it runs, green done, red failed */
43
+ .wp-progress-state {
44
+ display: inline-flex;
45
+ align-items: center;
46
+ gap: var(--space-sm, 6px);
47
+ color: var(--muted);
48
+ font: 500 var(--ui-tiny, 0.7rem) / 1 var(--sans);
49
+ }
50
+ .wp-progress-state::before {
51
+ content: '';
52
+ width: 7px;
53
+ height: 7px;
54
+ border-radius: 50%;
55
+ background: var(--wp-progress-dot, var(--muted));
56
+ }
57
+ .wp-progress[data-wp-progress='running'] {
58
+ --wp-progress-dot: var(--accent);
59
+ }
60
+ .wp-progress[data-wp-progress='done'] {
61
+ --wp-progress-dot: var(--ok);
62
+ }
63
+ .wp-progress[data-wp-progress='failed'] {
64
+ --wp-progress-dot: var(--bad);
65
+ }
66
+ @keyframes wp-progress-pulse {
67
+ 50% {
68
+ opacity: 0.35;
69
+ }
70
+ }
71
+ .wp-progress[data-wp-progress='running']:not([data-wp-stale]) .wp-progress-state::before {
72
+ animation: wp-progress-pulse 1.6s ease-in-out infinite;
73
+ }
74
+ @media (prefers-reduced-motion: reduce) {
75
+ .wp-progress-state::before {
76
+ animation: none !important;
77
+ }
78
+ }
79
+ /* stale: greyed, its time saying how long without an update */
80
+ .wp-progress[data-wp-stale] .wp-progress-body {
81
+ opacity: 0.55;
82
+ }
83
+ .wp-progress[data-wp-stale] .wp-progress-bar > span {
84
+ background: var(--muted);
85
+ }