@bigmistqke/workpad 0.18.1 → 0.20.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 (109) hide show
  1. package/README.md +18 -9
  2. package/bin/workpad.ts +412 -58
  3. package/dist/bin/workpad.js +336 -46
  4. package/dist/client/runtime.js +141 -18
  5. package/dist/plugins/badge/README.md +59 -10
  6. package/dist/plugins/badge/index.js +130 -8
  7. package/dist/plugins/badge/public/style.css +132 -12
  8. package/dist/plugins/chat/README.md +7 -3
  9. package/dist/plugins/chat/index.js +8 -1
  10. package/dist/plugins/chat/public/client.js +2 -2
  11. package/dist/plugins/chat/public/style.css +10 -0
  12. package/dist/plugins/claude/README.md +13 -5
  13. package/dist/plugins/claude/channel.js +47 -6
  14. package/dist/plugins/claude/doctor.js +43 -47
  15. package/dist/plugins/claude/index.js +24 -8
  16. package/dist/plugins/claude/session.js +46 -1
  17. package/dist/plugins/comments/README.md +2 -1
  18. package/dist/plugins/comments/index.js +2 -0
  19. package/dist/plugins/comments/public/client.js +6 -5
  20. package/dist/plugins/comments/public/style.css +9 -0
  21. package/dist/plugins/form/README.md +1 -1
  22. package/dist/plugins/index.js +3 -1
  23. package/dist/plugins/opencode/channel.js +43 -7
  24. package/dist/plugins/opencode/index.js +2 -0
  25. package/dist/plugins/progress/README.md +41 -0
  26. package/dist/plugins/progress/index.js +117 -0
  27. package/dist/plugins/progress/public/client.js +1 -0
  28. package/dist/plugins/progress/public/style.css +85 -0
  29. package/dist/plugins/progress/state.js +210 -0
  30. package/dist/solid/index.js +3 -1
  31. package/dist/src/agents.js +13 -4
  32. package/dist/src/anchors.js +25 -1
  33. package/dist/src/build.js +1 -1
  34. package/dist/src/client/page/base.css +48 -2
  35. package/dist/src/client/page/main.js +58 -30
  36. package/dist/src/document.js +6 -4
  37. package/dist/src/events.js +22 -11
  38. package/dist/src/help.js +59 -12
  39. package/dist/src/hub.js +69 -3
  40. package/dist/src/listen.js +36 -4
  41. package/dist/src/listeners.js +14 -4
  42. package/dist/src/loader.js +7 -2
  43. package/dist/src/migrate.js +1 -1
  44. package/dist/src/pages/board.js +9 -4
  45. package/dist/src/pages/index.js +2 -4
  46. package/dist/src/pages/markdown.js +50 -19
  47. package/dist/src/pages/render.js +17 -1
  48. package/dist/src/server.js +94 -18
  49. package/dist/src/set.js +99 -0
  50. package/dist/src/state.js +2 -1
  51. package/dist/src/status.js +57 -9
  52. package/dist/src/turns.js +41 -0
  53. package/package.json +11 -1
  54. package/plugins/README.md +3 -1
  55. package/plugins/badge/README.md +59 -10
  56. package/plugins/badge/index.ts +141 -8
  57. package/plugins/badge/public/style.css +132 -12
  58. package/plugins/chat/README.md +7 -3
  59. package/plugins/chat/client.tsx +20 -3
  60. package/plugins/chat/index.ts +10 -1
  61. package/plugins/chat/public/style.css +10 -0
  62. package/plugins/claude/README.md +13 -5
  63. package/plugins/claude/channel.ts +45 -7
  64. package/plugins/claude/doctor.ts +58 -39
  65. package/plugins/claude/index.ts +30 -8
  66. package/plugins/claude/session.ts +32 -0
  67. package/plugins/comments/README.md +2 -1
  68. package/plugins/comments/client.ts +19 -0
  69. package/plugins/comments/index.ts +7 -1
  70. package/plugins/comments/public/style.css +9 -0
  71. package/plugins/form/README.md +1 -1
  72. package/plugins/index.ts +2 -0
  73. package/plugins/opencode/channel.ts +44 -8
  74. package/plugins/opencode/index.ts +4 -0
  75. package/plugins/progress/README.md +41 -0
  76. package/plugins/progress/client.ts +172 -0
  77. package/plugins/progress/index.ts +166 -0
  78. package/plugins/progress/public/style.css +85 -0
  79. package/plugins/progress/state.ts +278 -0
  80. package/skills/workpad/SKILL.md +149 -18
  81. package/solid/index.tsx +6 -2
  82. package/src/agents.ts +24 -2
  83. package/src/anchors.ts +32 -0
  84. package/src/build.ts +1 -1
  85. package/src/client/delivery.ts +49 -0
  86. package/src/client/forms.ts +18 -11
  87. package/src/client/page/base.css +48 -2
  88. package/src/client/page/waiting.ts +45 -25
  89. package/src/client/read.ts +9 -5
  90. package/src/client/runtime.ts +7 -3
  91. package/src/client/toast.ts +27 -3
  92. package/src/define.ts +120 -9
  93. package/src/document.ts +19 -5
  94. package/src/events.ts +47 -6
  95. package/src/help.ts +58 -11
  96. package/src/hub.ts +80 -2
  97. package/src/listen.ts +47 -4
  98. package/src/listeners.ts +22 -1
  99. package/src/loader.ts +14 -4
  100. package/src/migrate.ts +1 -1
  101. package/src/pages/board.ts +12 -3
  102. package/src/pages/index.ts +8 -10
  103. package/src/pages/markdown.ts +59 -12
  104. package/src/pages/render.ts +20 -2
  105. package/src/server.ts +127 -19
  106. package/src/set.ts +118 -0
  107. package/src/state.ts +3 -0
  108. package/src/status.ts +115 -14
  109. package/src/turns.ts +56 -0
@@ -23,8 +23,8 @@ import fs from 'node:fs'
23
23
  import path from 'node:path'
24
24
  import readline from 'node:readline'
25
25
  import type { CommandContext, WpEvent } from '../../src/define.ts'
26
- import { ANSWERS_NOTE, answerLine, identity, pong } from '../../src/agents.ts'
27
- import { channelSince, read } from '../../src/events.ts'
26
+ import { ANSWERS_NOTE, answerLine, identity, pong, unfollowedLine } from '../../src/agents.ts'
27
+ import { channelSince, read, takesUnfollowed } from '../../src/events.ts'
28
28
  import { claudeProcess, recordedSession } from './session.ts'
29
29
 
30
30
  const INSTRUCTIONS = [
@@ -45,9 +45,14 @@ export async function channel(ctx: CommandContext) {
45
45
  const claude = claudeProcess()
46
46
  const started = process.env.CLAUDE_CODE_SESSION_ID || null
47
47
  let session: string | null = null
48
+ // every id the process's conversation went by: the sessions before a resume or a clear, and the
49
+ // session beside WORKPAD_AGENT. What any of them wrote is the agent's own, never pushed to it
50
+ const selves = new Set<string>()
48
51
  /** The conversation now, and a line in the log when it changed after start (a resume). */
49
52
  const current = () => {
50
- const now = identity(recordedSession(ctx.dataDir, claude) ?? started)
53
+ const raw = recordedSession(ctx.dataDir, claude) ?? started
54
+ const now = identity(raw)
55
+ for (const id of [raw, now]) if (id) selves.add(id)
51
56
  if (now !== session) {
52
57
  if (!now) problem('no CLAUDE_CODE_SESSION_ID: no pages to follow')
53
58
  else if (now !== started || session) problem('following another session than at start', { started, now })
@@ -80,23 +85,56 @@ export async function channel(ctx: CommandContext) {
80
85
  })
81
86
  }
82
87
 
83
- // Each page followed on its own, so another session's answers are never handed out here.
88
+ // Each page followed on its own, so another session's answers are never handed out here; as the
89
+ // session it is followed for, until that moves on (a resume, a clear): then its pages are let go,
90
+ // and the new session's followed as its own
84
91
  const followed = new Set<string>()
92
+ let followedFor: { session: string; stop: AbortController } | null = null
93
+ // the pages no one follows, when the session took them on (`workpad listen --unfollowed --channel`)
94
+ let unfollowed: { session: string; stop: AbortController } | null = null
95
+ const takeUnfollowed = (session: string) => {
96
+ const wanted = takesUnfollowed(read(ctx.eventsFile).events, session)
97
+ if (unfollowed && (!wanted || unfollowed.session !== session)) {
98
+ unfollowed.stop.abort()
99
+ unfollowed = null
100
+ }
101
+ if (!wanted || unfollowed) return
102
+ unfollowed = { session, stop: new AbortController() }
103
+ void ctx
104
+ .unfollowed(
105
+ (e, again, from) =>
106
+ notify(unfollowedLine(e, again, from), {
107
+ page: e.page,
108
+ id: e.id,
109
+ type: e.type,
110
+ ...(from && { project: from.project }),
111
+ }),
112
+ { agent: session, signal: unfollowed.stop.signal },
113
+ )
114
+ .catch(err => problem('taking the unfollowed pages failed', String(err)))
115
+ }
85
116
  const follow = async () => {
86
117
  const session = current()
87
118
  hold(session)
88
119
  if (!confirmed || !session) return
120
+ takeUnfollowed(session)
121
+ if (followedFor?.session !== session) {
122
+ followedFor?.stop.abort()
123
+ followed.clear()
124
+ followedFor = { session, stop: new AbortController() }
125
+ }
126
+ const { signal } = followedFor.stop
89
127
  const pages = (await ctx.status()).filter(p => p.subscribers.includes(session)).map(p => p.page)
90
128
  for (const page of pages) {
91
- if (followed.has(page)) continue
129
+ if (followed.has(page) || signal.aborted) continue
92
130
  followed.add(page)
93
- await ctx.listen(page, { agent: session })
131
+ await ctx.listen(page, { agent: session, signal })
94
132
  // received as it is sent: the agent confirmed that what this sends reaches it
95
133
  const push = (e: WpEvent, again: boolean) => notify(answerLine(e, again), { page: e.page, id: e.id, type: e.type })
96
134
  // a page taken on through the channel: what is new, not the past someone already received
97
135
  const since = channelSince(read(ctx.eventsFile).events, session, page) ?? undefined
98
136
  void ctx
99
- .handOut({ page, exact: true }, push, { agent: session, skipReceivedBefore: since })
137
+ .handOut({ page, exact: true }, push, { agent: session, aliases: selves, skipReceivedBefore: since, signal })
100
138
  .catch(err => problem('handing out failed', { page, err: String(err) }))
101
139
  }
102
140
  }
@@ -1,19 +1,23 @@
1
1
  // `workpad claude doctor`: everything the channel needs to push the reader's answers into this
2
2
  // session, checked one by one, with what to do about each that fails. Each of these broke a channel
3
3
  // without a word once: Claude Code drops a server's messages when the session wasn't started with the
4
- // channels flag, a session started from another folder never sees the project's .mcp.json, and an Esc
5
- // on "New MCP server found" disables the server in a settings file `/mcp` then doesn't list at all
6
- // (in a git worktree without its own settings.local.json, in the main checkout's).
4
+ // channels flag, a session reads .mcp.json from the folder it runs in only, and an Esc on "New MCP
5
+ // server found" disables the server in a settings file `/mcp` then doesn't list at all (in a git
6
+ // worktree without its own settings.local.json, in the main checkout's).
7
+ //
8
+ // The folder Claude Code runs in is not always the pages' project: a wrapper can hand a session in
9
+ // one folder (a git worktree) the pages of another (a job's folder). .mcp.json and the approval are
10
+ // read from Claude's folder (claudeFolder), and both are named when they differ.
7
11
  //
8
12
  // It reads, and changes nothing: the files, the claude process it runs under (its command line and
9
13
  // folder, with ps and lsof), and what the project's server says (never started for it). The
10
- // channel's command is started once, asked to initialize, and stopped.
14
+ // channel's command is started once, in Claude's folder, asked to initialize, and stopped.
11
15
  import fs from 'node:fs'
12
16
  import os from 'node:os'
13
17
  import path from 'node:path'
14
18
  import { spawn, spawnSync } from 'node:child_process'
15
19
  import type { CommandContext } from '../../src/define.ts'
16
- import { claudePid, claudeProcess, recordedSession } from './session.ts'
20
+ import { claudeFolder, claudePid, claudeProcess, real, recordedSession } from './session.ts'
17
21
 
18
22
  const SERVER = 'workpad'
19
23
  const FLAG = '--dangerously-load-development-channels'
@@ -136,62 +140,85 @@ export function approvals(dir: string, home = os.homedir()): Line[] {
136
140
  return lines
137
141
  }
138
142
 
139
- /** The claude process's command line and folder. */
140
- function claudeLaunch(pid: number): { args: string | null; cwd: string | null } {
143
+ /** The claude process's command line. */
144
+ function claudeArgs(pid: number): string | null {
141
145
  const ps = spawnSync('ps', ['-o', 'args=', '-p', String(pid)], { encoding: 'utf8' })
142
- const lsof = spawnSync('lsof', ['-a', '-p', String(pid), '-d', 'cwd', '-Fn'], { encoding: 'utf8' })
143
- const cwd = lsof.status === 0 ? (lsof.stdout.split('\n').find(l => l.startsWith('n'))?.slice(1) ?? null) : null
144
- return { args: ps.status === 0 ? ps.stdout.trim() : null, cwd }
145
- }
146
-
147
- /** The workpad version a project pins (its package.json), and the one installed there, when it has them. */
148
- function pinned(dir: string): { pin: string | null; installed: string | null } {
149
- const pkg = readJson(path.join(dir, 'package.json'))?.value
150
- const pin = pkg?.dependencies?.['@bigmistqke/workpad'] ?? pkg?.devDependencies?.['@bigmistqke/workpad'] ?? null
151
- const installed = readJson(path.join(dir, 'node_modules', '@bigmistqke', 'workpad', 'package.json'))?.value?.version ?? null
152
- return { pin, installed }
146
+ return ps.status === 0 ? ps.stdout.trim() : null
153
147
  }
154
148
 
155
- export async function doctor(ctx: CommandContext) {
156
- const dir = ctx.project.dir
149
+ /**
150
+ * The checks of what Claude Code reads where it runs (`claude`, see claudeFolder): which folder
151
+ * that is, beside the pages' project (`pages`), when the two differ; the channel in its .mcp.json,
152
+ * and that its command answers, started there as Claude Code starts it; and the server approved and
153
+ * disabled nowhere in its settings. Each fix points at the folder it is for.
154
+ */
155
+ export async function channelChecks(
156
+ pages: string,
157
+ claude: { dir: string; from: string | null },
158
+ home = os.homedir(),
159
+ ): Promise<Line[]> {
160
+ const dir = claude.dir
161
+ const apart = real(pages) !== dir
157
162
  const lines: Line[] = []
163
+ if (apart)
164
+ lines.push({
165
+ mark: 'skip',
166
+ text: `pages: ${pages}; Claude's project: ${dir} (${claude.from ?? 'no Claude Code session found'}). The channel and its approval are read from Claude's`,
167
+ })
168
+ else if (claude.from)
169
+ lines.push({ mark: 'ok', text: `Claude Code runs in the project's folder (${dir})` })
170
+ const install = apart ? `workpad claude install --claude-dir ${dir}` : 'workpad claude install'
158
171
 
159
- // 1. the channel in .mcp.json, and its command starts
172
+ // the channel in .mcp.json, and its command starts
160
173
  const mcpFile = path.join(dir, '.mcp.json')
161
174
  const mcp = readJson(mcpFile)
162
175
  const entry = mcp?.value?.mcpServers?.[SERVER]
163
- if (!mcp) lines.push({ mark: 'fail', text: `no ${mcpFile}`, fix: 'workpad claude install' })
176
+ if (!mcp) lines.push({ mark: 'fail', text: `no ${mcpFile}`, fix: install })
164
177
  else if (mcp.value === undefined) lines.push({ mark: 'fail', text: `${mcpFile}: ${mcp.why}`, fix: 'fix the file' })
165
- else if (!entry?.command)
166
- lines.push({ mark: 'fail', text: `${mcpFile} has no "${SERVER}" server`, fix: 'workpad claude install' })
178
+ else if (!entry?.command) lines.push({ mark: 'fail', text: `${mcpFile} has no "${SERVER}" server`, fix: install })
167
179
  else {
168
- const env = { ...process.env, CLAUDE_PROJECT_DIR: process.env.CLAUDE_PROJECT_DIR ?? dir, ...(entry.env ?? {}) }
180
+ const env = { ...process.env, CLAUDE_PROJECT_DIR: dir, ...(entry.env ?? {}) }
169
181
  const command = expand(entry.command, env)
170
182
  const args = ((entry.args ?? []) as string[]).map(a => expand(a, env))
171
183
  const why = await probe(command, args, dir, env)
172
184
  const shown = [entry.command, ...(entry.args ?? [])].join(' ')
173
185
  lines.push(
174
186
  why
175
- ? { mark: 'fail', text: `the channel's command in ${mcpFile} doesn't answer: ${why}`, fix: `run it by hand to see why: ${shown}` }
187
+ ? { mark: 'fail', text: `the channel's command in ${mcpFile} doesn't answer: ${why}`, fix: `run it by hand in ${dir} to see why: ${shown}` }
176
188
  : { mark: 'ok', text: `${mcpFile} has the channel, and its command answers (${shown})` },
177
189
  )
178
190
  }
179
191
 
180
- // 2. enabled, and disabled in no settings scope
181
- lines.push(...approvals(dir))
192
+ // enabled, and disabled in no settings scope
193
+ lines.push(...approvals(dir, home))
194
+ return lines
195
+ }
182
196
 
183
- // 3. the session: started with the flag, from the project's folder
197
+ /** The workpad version a project pins (its package.json), and the one installed there, when it has them. */
198
+ function pinned(dir: string): { pin: string | null; installed: string | null } {
199
+ const pkg = readJson(path.join(dir, 'package.json'))?.value
200
+ const pin = pkg?.dependencies?.['@bigmistqke/workpad'] ?? pkg?.devDependencies?.['@bigmistqke/workpad'] ?? null
201
+ const installed = readJson(path.join(dir, 'node_modules', '@bigmistqke', 'workpad', 'package.json'))?.value?.version ?? null
202
+ return { pin, installed }
203
+ }
204
+
205
+ export async function doctor(ctx: CommandContext) {
206
+ const dir = ctx.project.dir
207
+ // 1. where Claude Code runs; the channel in its .mcp.json; 2. approved, and disabled in no settings scope
208
+ const lines = await channelChecks(dir, claudeFolder(dir))
209
+
210
+ // 3. the session: started with the flag
184
211
  const pid = claudePid()
185
212
  const envSession = process.env.CLAUDE_CODE_SESSION_ID || null
186
213
  if (!pid)
187
214
  lines.push({
188
215
  mark: 'skip',
189
216
  text: envSession
190
- ? "couldn't find the claude process (is ps permitted here?): its launch flag and folder are not checked"
217
+ ? "couldn't find the claude process (is ps permitted here?): its launch flag is not checked"
191
218
  : 'not run from a Claude Code session: its launch and channel are not checked',
192
219
  })
193
220
  else {
194
- const { args, cwd } = claudeLaunch(pid)
221
+ const args = claudeArgs(pid)
195
222
  if (args == null) lines.push({ mark: 'skip', text: `couldn't read the command line of claude (pid ${pid})` })
196
223
  else if (new RegExp(`${FLAG}(=|\\s+)\\S*server:${SERVER}\\b`).test(args))
197
224
  lines.push({ mark: 'ok', text: `the session was started with ${FLAG} server:${SERVER}` })
@@ -201,14 +228,6 @@ export async function doctor(ctx: CommandContext) {
201
228
  text: `the session was started without ${FLAG} server:${SERVER}: Claude Code drops what the channel sends`,
202
229
  fix: `restart it with: claude ${FLAG} server:${SERVER} (a resume or a restore keeps no flag it wasn't given)`,
203
230
  })
204
- if (cwd == null) lines.push({ mark: 'skip', text: `couldn't read the folder claude (pid ${pid}) runs in` })
205
- else if (path.resolve(cwd) === dir) lines.push({ mark: 'ok', text: `the session runs in the project's folder` })
206
- else
207
- lines.push({
208
- mark: 'fail',
209
- text: `the session runs in ${cwd}, not the project's folder: it doesn't see ${mcpFile}`,
210
- fix: `start claude in ${dir}`,
211
- })
212
231
  }
213
232
 
214
233
  // 4. the server, its version, and a channel for this session; 5. its ping confirmed
@@ -28,6 +28,7 @@ import { read, receivedBy } from '../../src/events.ts'
28
28
  import { channel } from './channel.ts'
29
29
  import { doctor } from './doctor.ts'
30
30
  import { recordSession } from './session.ts'
31
+ import { recordTurn } from '../../src/turns.ts'
31
32
 
32
33
  type Mode = 'session' | 'stop'
33
34
 
@@ -71,27 +72,44 @@ export default function claude(): Plugin {
71
72
  },
72
73
  doctor: {
73
74
  description:
74
- "check what the channel needs, a line each with what to do: the .mcp.json entry and its command, the server approved and disabled in no settings file, the session started with the channels flag in the project's folder, the server up at the project's version, a channel for this session, its ping confirmed",
75
+ "check what the channel needs, a line each with what to do: the .mcp.json entry and its command, the server approved and disabled in no settings file (both where Claude Code runs, named beside the pages' project when it is another folder), the session started with the channels flag, the server up at the project's version, a channel for this session, its ping confirmed",
75
76
  run: doctor,
76
77
  },
77
78
  install: {
78
- description: "add the channel to this project's .mcp.json and its hooks to .claude/settings.json",
79
+ description:
80
+ "add the channel to the .mcp.json and its hooks to the .claude/settings.json of the folder Claude Code runs in: this project's, or --claude-dir",
81
+ options: { 'claude-dir': CLAUDE_DIR },
79
82
  run: ctx => {
80
- installChannel(ctx.project.dir)
81
- installHooks(ctx.project.dir)
83
+ const dir = claudeDir(ctx)
84
+ installChannel(dir)
85
+ installHooks(dir)
82
86
  },
83
87
  },
84
88
  uninstall: {
85
- description: "take the channel and its hooks out of this project's settings again; other hooks, servers and settings stay",
89
+ description:
90
+ "take the channel and its hooks out of the settings again (this project's, or --claude-dir's); other hooks, servers and settings stay",
91
+ options: { 'claude-dir': CLAUDE_DIR },
86
92
  run: ctx => {
87
- uninstallChannel(ctx.project.dir)
88
- uninstallHooks(ctx.project.dir)
93
+ const dir = claudeDir(ctx)
94
+ uninstallChannel(dir)
95
+ uninstallHooks(dir)
89
96
  },
90
97
  },
91
98
  },
92
99
  }
93
100
  }
94
101
 
102
+ /**
103
+ * The folder Claude Code runs in, when it isn't the pages' project: a session a wrapper hands
104
+ * another folder's pages reads .mcp.json and its settings from its own folder.
105
+ */
106
+ const CLAUDE_DIR = {
107
+ type: 'string?',
108
+ value: 'folder',
109
+ description: "the folder Claude Code runs in, when not this project's (`workpad claude doctor` names it)",
110
+ } as const
111
+ const claudeDir = (ctx: CommandContext) => path.resolve((ctx.options['claude-dir'] as string | undefined) ?? ctx.project.dir)
112
+
95
113
  /** The JSON Claude Code passes a hook on its standard input, or nothing. */
96
114
  function hookInput(): { session_id?: string; stop_hook_active?: boolean; transcript_path?: string } {
97
115
  if (process.stdin.isTTY) return {}
@@ -106,12 +124,16 @@ async function hook(ctx: CommandContext, mode: Mode) {
106
124
  const input = hookInput()
107
125
  // the channel's environment can hold an id the conversation left (a resume): tell it the current one
108
126
  if (input.session_id) recordSession(ctx.dataDir, input.session_id)
109
- if (mode === 'session') return
127
+ // `workpad agent ping --wait` counts from a turn's end (turns.ts): from here on they are recorded
128
+ if (mode === 'session')
129
+ return recordTurn(ctx.project.wp, identity(input.session_id ?? process.env.CLAUDE_CODE_SESSION_ID ?? null), false)
110
130
  // A turn ends with something on the session's pages left: its turn goes on once, with that as the
111
131
  // reason; Claude Code marks a turn a hook continued (stop_hook_active), and that one ends, with
112
132
  // what is open shown to the reader instead.
113
133
  const agent = identity(input.session_id ?? process.env.CLAUDE_CODE_SESSION_ID ?? null)
114
134
  const left = await stopReminder(ctx, agent, inFlight(ctx, agent, input.transcript_path))
135
+ // the turn ends, unless the reminder below sends it on: then its next end is the one (turns.ts)
136
+ if (!left || input.stop_hook_active) recordTurn(ctx.project.wp, agent, true)
115
137
  if (!left) return
116
138
  if (input.stop_hook_active) return void console.log(JSON.stringify({ systemMessage: left.shown }))
117
139
  // As context for the turn, not a block: the turn goes on all the same (with the same guard,
@@ -37,6 +37,38 @@ export function claudeProcess(): string {
37
37
  return Number.isNaN(at) ? String(pid) : `${pid}-${at / 1000}`
38
38
  }
39
39
 
40
+ /** The folder a process runs in (with lsof), or null when it can't be read. */
41
+ function processCwd(pid: number): string | null {
42
+ const lsof = spawnSync('lsof', ['-a', '-p', String(pid), '-d', 'cwd', '-Fn'], { encoding: 'utf8' })
43
+ if (lsof.status !== 0) return null
44
+ return lsof.stdout.split('\n').find(l => l.startsWith('n'))?.slice(1) || null
45
+ }
46
+
47
+ /** A folder as the file system names it, symbolic links resolved (as given when it isn't there). */
48
+ export function real(dir: string): string {
49
+ try {
50
+ return fs.realpathSync(dir)
51
+ } catch {
52
+ return path.resolve(dir)
53
+ }
54
+ }
55
+
56
+ /**
57
+ * The folder Claude Code runs in, where it reads .mcp.json and its project settings: not always the
58
+ * pages' project (a wrapper can hand a session another folder's pages). CLAUDE_PROJECT_DIR when set
59
+ * (Claude Code gives it to hooks and MCP servers, not to an agent's commands); else the folder of
60
+ * the claude process this one runs under (found with ps, else by the CLAUDE_PID Claude Code gives an
61
+ * agent's commands); else, outside a session, `fallback`. With how it was found, for the doctor
62
+ * (null: no session was found, and it is `fallback`).
63
+ */
64
+ export function claudeFolder(fallback: string, env: NodeJS.ProcessEnv = process.env): { dir: string; from: string | null } {
65
+ if (env.CLAUDE_PROJECT_DIR) return { dir: real(env.CLAUDE_PROJECT_DIR), from: 'CLAUDE_PROJECT_DIR' }
66
+ const pid = claudePid() ?? (Number(env.CLAUDE_PID) || null)
67
+ const cwd = pid ? processCwd(pid) : null
68
+ if (cwd) return { dir: real(cwd), from: `the folder claude (pid ${pid}) runs in` }
69
+ return { dir: real(fallback), from: null }
70
+ }
71
+
40
72
  const sessionsDir = (dataDir: string) => path.join(dataDir, 'sessions')
41
73
 
42
74
  /** The conversation a hook says this claude process is on; records of processes that ended go. */
@@ -21,7 +21,8 @@ page until the reader closes it. Answer a comment the way it asks:
21
21
  - **It asks for a change:** edit the page. The thread stays, so say what you
22
22
  changed in a reply if it is not obvious.
23
23
  - **It asks a question:** reply in the thread:
24
- `workpad append --page <file> --type comments:reply --data '{"replyTo":"<comment id>","text":"…"}'`
24
+ `workpad append --page <file> --type comments:reply --data '{"replyTo":"<comment id>"}' --text-file -`,
25
+ the reply's markdown on standard input
25
26
 
26
27
  Your replies show as the agent's, and your own `listen` skips what you
27
28
  append, so you don't hear your own replies. Comments and replies are
@@ -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
  }
@@ -23,8 +23,10 @@ import fs from 'node:fs'
23
23
  import path from 'node:path'
24
24
  import readline from 'node:readline'
25
25
  import type { CommandContext, WpEvent } from '../../src/define.ts'
26
- import { channelSince, read, receive, receivedBy } from '../../src/events.ts'
27
- import { answerLine, identity, pong } from '../../src/agents.ts'
26
+ import { channelSince, read, receive, receivedBy, takesUnfollowed } from '../../src/events.ts'
27
+ import { answerLine, identity, pong, unfollowedLine } from '../../src/agents.ts'
28
+ import { project as projectAt } from '../../src/config.ts'
29
+ import { recordTurn } from '../../src/turns.ts'
28
30
 
29
31
  export async function channel(ctx: CommandContext) {
30
32
  const problem = (what: string, data?: unknown) => {
@@ -40,6 +42,8 @@ export async function channel(ctx: CommandContext) {
40
42
  const sessions = new Map<string, boolean>()
41
43
  const hold = (session: string) => {
42
44
  sessions.set(session, false)
45
+ // its turn ends are recorded from now on (`hook stop`), for `workpad agent ping --wait` (turns.ts)
46
+ recordTurn(ctx.project.wp, identity(session), false)
43
47
  ctx.channel(identity(session)!, {
44
48
  onPing: code => say({ session, pong: true, text: pong(code) }),
45
49
  onConfirmed: () => {
@@ -50,11 +54,37 @@ export async function channel(ctx: CommandContext) {
50
54
  }
51
55
  // each page followed on its own, so another session's answers are never handed out here
52
56
  const followed = new Set<string>()
57
+ // the sessions that took the pages no one follows on (`workpad listen --unfollowed --channel`),
58
+ // and the log each answer they were given from another project is in, to mark it received there
59
+ const unfollowed = new Map<string, AbortController>()
60
+ const logOf = new Map<string, string>()
61
+ const takeUnfollowed = (agent: string, session: string) => {
62
+ const wanted = takesUnfollowed(read(ctx.eventsFile).events, agent)
63
+ if (!wanted) {
64
+ unfollowed.get(session)?.abort()
65
+ unfollowed.delete(session)
66
+ return
67
+ }
68
+ if (unfollowed.has(session)) return
69
+ const stop = new AbortController()
70
+ unfollowed.set(session, stop)
71
+ void ctx
72
+ .unfollowed(
73
+ (e, again, from) => {
74
+ const log = from ? projectAt(from.project)?.eventsFile : null
75
+ if (log) logOf.set(e.id, log)
76
+ say({ session, id: e.id, page: e.page, type: e.type, text: unfollowedLine(e, again, from) })
77
+ },
78
+ { agent, mark: false, signal: stop.signal },
79
+ )
80
+ .catch(err => problem('taking the unfollowed pages failed', String(err)))
81
+ }
53
82
  const follow = async () => {
54
83
  // who each confirmed session is on the boards, and the session to bring its pages' answers to
55
84
  const who = new Map<string, string>()
56
85
  for (const [session, confirmed] of sessions) if (confirmed) who.set(identity(session)!, session)
57
86
  if (!who.size) return
87
+ for (const [agent, session] of who) takeUnfollowed(agent, session)
58
88
  for (const p of await ctx.status()) {
59
89
  const agent = p.subscribers.find(s => who.has(s))
60
90
  if (!agent || followed.has(p.page)) continue
@@ -73,7 +103,8 @@ export async function channel(ctx: CommandContext) {
73
103
  // a page taken on through the channel: what is new, not the past someone already received
74
104
  const since = channelSince(read(ctx.eventsFile).events, agent, page) ?? undefined
75
105
  void ctx
76
- .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 })
77
108
  .catch(err => problem('handing out failed', { page, err: String(err) }))
78
109
  }
79
110
  }
@@ -81,11 +112,16 @@ export async function channel(ctx: CommandContext) {
81
112
  /** The plugin brought these answers into their session. */
82
113
  const received = (ids: string[], session: string) => {
83
114
  const agent = identity(session)
84
- const { events } = read(ctx.eventsFile)
85
- const had = receivedBy(events, agent)
86
- for (const id of ids) {
87
- const e = events.find(x => x.id === id)
88
- if (e && !had.has(id)) receive(ctx.eventsFile, e, agent)
115
+ // by log: this project's, or another's an unfollowed page is in
116
+ for (const log of new Set(ids.map(id => logOf.get(id) ?? ctx.eventsFile))) {
117
+ const { events } = read(log)
118
+ const had = receivedBy(events, agent)
119
+ for (const id of ids) {
120
+ if ((logOf.get(id) ?? ctx.eventsFile) !== log) continue
121
+ const e = events.find(x => x.id === id)
122
+ if (e && !had.has(id)) receive(log, e, agent)
123
+ logOf.delete(id)
124
+ }
89
125
  }
90
126
  }
91
127
 
@@ -19,6 +19,7 @@ import fs from 'node:fs'
19
19
  import path from 'node:path'
20
20
  import type { Plugin } from '../../src/define.ts'
21
21
  import { identity, stopReminder, workpadCommand } from '../../src/agents.ts'
22
+ import { recordTurn } from '../../src/turns.ts'
22
23
  import { channel } from './channel.ts'
23
24
  import { shimSource } from './shim.ts'
24
25
 
@@ -37,6 +38,9 @@ export default function opencode(): Plugin {
37
38
  if (ctx.positionals[0] !== 'stop') throw new Error('usage: workpad opencode hook stop')
38
39
  // a hook that fails must not get in the way of the session it runs in: say why, and exit cleanly
39
40
  try {
41
+ // the turn ended, for `workpad agent ping --wait` (turns.ts); one the plugin then sends on
42
+ // with what is left counts as ended a little early, since this can't tell
43
+ recordTurn(ctx.project.wp, identity(session()), true)
40
44
  const left = await stopReminder(ctx, identity(session()))
41
45
  if (left) console.log(JSON.stringify(left))
42
46
  } catch (err) {
@@ -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 })`.