@bigmistqke/workpad 0.18.0 → 0.18.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.
package/bin/workpad.ts CHANGED
@@ -735,9 +735,26 @@ switch (cmd) {
735
735
  }
736
736
  if (code) console.log(`confirmed: answers on your pages come to you now, as the pong did.${await covers()}`)
737
737
  else if (body.confirmed) console.log(`answers on your pages come to you already, through this session’s channel.${await covers()}`)
738
- else if (body.sent)
738
+ else if (body.sent && opts.wait) {
739
+ // run in the background: it ends, and so wakes the agent, when the pong it pushed is confirmed,
740
+ // or when none came in time: then nothing brings answers here, and the agent listens instead
741
+ console.log('pinged this session’s channel: a pong comes to you as a message; confirm it with the command it names')
742
+ const limit = Date.now() + (opts.timeout ? Number(opts.timeout) * 1000 : 120_000)
743
+ while (Date.now() < limit) {
744
+ await new Promise(r => setTimeout(r, 1000))
745
+ const channels = (await api('/api/channels')) as { session: string | null; confirmed: boolean }[]
746
+ if (channels.some(c => c.session === me && c.confirmed)) {
747
+ console.log(`confirmed: answers on your pages come to you now.${await covers()}`)
748
+ process.exit(0)
749
+ }
750
+ }
751
+ console.log(
752
+ 'no pong was confirmed in time: nothing brings answers here. Listen for them (`workpad listen --wait --page <file>` in the background), and in Claude Code tell the user what `workpad claude doctor` says is wrong',
753
+ )
754
+ process.exit(1)
755
+ } else if (body.sent)
739
756
  console.log(
740
- 'pinged this session’s channel: a pong comes to you as a message, the way answers will, with the command that confirms it. It may only come once your turn has ended, so start no listen yet; if none has come by your next turn, nothing brings answers here: listen for them then',
757
+ 'pinged this session’s channel: a pong comes to you as a message, the way answers will, with the command that confirms it. It may only come once your turn has ended, so start no listen yet. Run `workpad agent ping --wait` in the background instead, and it ends when you confirmed the pong or when none came: then listen',
741
758
  )
742
759
  else {
743
760
  console.log(
@@ -748,7 +765,7 @@ switch (cmd) {
748
765
  break
749
766
  }
750
767
  throw new Error(
751
- 'usage: workpad agent [name <name> | name --clear | list | unsubscribe <agent> [--page <p>…] | ping [<code>]]',
768
+ 'usage: workpad agent [name <name> | name --clear | list | unsubscribe <agent> [--page <p>…] | ping [<code> | --wait [--timeout <s>]]]',
752
769
  )
753
770
  }
754
771
  case 'show': {
@@ -586,14 +586,26 @@ switch (cmd) {
586
586
  };
587
587
  if (code) console.log(`confirmed: answers on your pages come to you now, as the pong did.${await covers()}`);
588
588
  else if (body.confirmed) console.log(`answers on your pages come to you already, through this session’s channel.${await covers()}`);
589
- else if (body.sent) console.log("pinged this session’s channel: a pong comes to you as a message, the way answers will, with the command that confirms it. It may only come once your turn has ended, so start no listen yet; if none has come by your next turn, nothing brings answers here: listen for them then");
589
+ else if (body.sent && opts.wait) {
590
+ console.log("pinged this session’s channel: a pong comes to you as a message; confirm it with the command it names");
591
+ const limit = Date.now() + (opts.timeout ? Number(opts.timeout) * 1e3 : 12e4);
592
+ while (Date.now() < limit) {
593
+ await new Promise((r) => setTimeout(r, 1e3));
594
+ if ((await api("/api/channels")).some((c) => c.session === me && c.confirmed)) {
595
+ console.log(`confirmed: answers on your pages come to you now.${await covers()}`);
596
+ process.exit(0);
597
+ }
598
+ }
599
+ console.log("no pong was confirmed in time: nothing brings answers here. Listen for them (`workpad listen --wait --page <file>` in the background), and in Claude Code tell the user what `workpad claude doctor` says is wrong");
600
+ process.exit(1);
601
+ } else if (body.sent) console.log("pinged this session’s channel: a pong comes to you as a message, the way answers will, with the command that confirms it. It may only come once your turn has ended, so start no listen yet. Run `workpad agent ping --wait` in the background instead, and it ends when you confirmed the pong or when none came: then listen");
590
602
  else {
591
603
  console.log("nothing brings answers to this session: listen for them (`workpad listen --wait --page <file>` in the background)");
592
604
  process.exit(1);
593
605
  }
594
606
  break;
595
607
  }
596
- throw new Error("usage: workpad agent [name <name> | name --clear | list | unsubscribe <agent> [--page <p>…] | ping [<code>]]");
608
+ throw new Error("usage: workpad agent [name <name> | name --clear | list | unsubscribe <agent> [--page <p>…] | ping [<code> | --wait [--timeout <s>]]]");
597
609
  }
598
610
  case "show": {
599
611
  if (!positionals[0]) throw new Error("usage: workpad show <page|file> [<anchor>]");
@@ -15,7 +15,7 @@ const identity = (session) => process.env.WORKPAD_AGENT || session;
15
15
  /** The one listen for these pages, stopping at the first answer: a --page each. */
16
16
  const waitOn = (pages) => `workpad listen --wait ${pages.map((p) => `--page ${relFile(p.file)}`).join(" ")}`;
17
17
  /** For a page nobody listens on: a channel the session has may bring the answers instead. */
18
- const PING = "run `workpad agent ping` if you haven't this session (answers may come to you); else";
18
+ const PING = "run `workpad agent ping --wait` in the background if you haven't this session (answers may come to you; it ends when you confirmed the pong, or when none came); else";
19
19
  /**
20
20
  * A turn of `session` ends: nothing when its pages have nothing left for it; else what to tell the
21
21
  * agent to do before it ends its turn (`reason`), and what is open in one line, for the reader (`shown`).
@@ -1419,9 +1419,32 @@ function trackBoard() {
1419
1419
  applyBoard(view);
1420
1420
  applySearch();
1421
1421
  });
1422
+ document.addEventListener("toggle", (e) => {
1423
+ const fold = e.target;
1424
+ if (fold.dataset?.wpFiles && fold.open) loadFiles(fold);
1425
+ }, true);
1422
1426
  applyBoard(chosen());
1423
1427
  trackSearch();
1424
1428
  }
1429
+ async function loadFiles(fold) {
1430
+ if (fold.dataset.wpLoaded) return;
1431
+ fold.dataset.wpLoaded = "loading";
1432
+ const count = fold.querySelector("summary .wp-meta");
1433
+ if (count) count.textContent = "…";
1434
+ try {
1435
+ const res = await fetch(`/api/files?base=${encodeURIComponent(fold.dataset.wpFiles)}`);
1436
+ const body = await res.json();
1437
+ if (!res.ok) throw new Error(body.error ?? res.statusText);
1438
+ if (count) count.textContent = String(body.count);
1439
+ fold.insertAdjacentHTML("beforeend", body.count ? body.html : "<p class=\"wp-meta\">No markdown files.</p>");
1440
+ fold.dataset.wpLoaded = "yes";
1441
+ applySearch();
1442
+ } catch (err) {
1443
+ delete fold.dataset.wpLoaded;
1444
+ if (count) count.textContent = "";
1445
+ fold.insertAdjacentHTML("beforeend", `<p class="wp-meta">Couldn't list the files: ${String(err.message)}</p>`);
1446
+ }
1447
+ }
1425
1448
  // src/client/page/sticky.ts
1426
1449
  function place$1(body) {
1427
1450
  const nav = document.querySelector(".wp-nav");
package/dist/src/help.js CHANGED
@@ -18,7 +18,7 @@ const COMMAND_HELP = {
18
18
  details: "Subfolders are fine (task/plan). Whoever runs it (--agent, WORKPAD_AGENT, a plugin's session) is subscribed to the page."
19
19
  },
20
20
  agent: {
21
- usage: "[name <name> | name --clear | list | unsubscribe <agent> [--page <p>…] | ping [<code>]]",
21
+ usage: "[name <name> | name --clear | list | unsubscribe <agent> [--page <p>…] | ping [<code> | --wait [--timeout <s>]]]",
22
22
  summary: "who you are on the boards: your id and name; name yourself, see who else is around, check a channel reaches you",
23
23
  details: `Your id is --agent, else WORKPAD_AGENT, else the session an agent plugin names (claude(),
24
24
  opencode()). Alone, it says your id and your name.
@@ -34,7 +34,9 @@ opencode()). Alone, it says your id and your name.
34
34
  into the session, the way answers will, with the code to confirm with. Once
35
35
  confirmed, the channel listens on your pages, and the answers it brings count
36
36
  as received. No channel (exit 1), or no pong: nothing brings answers here, so
37
- listen for them.`
37
+ listen for them. --wait: run it in the background; it pings and ends when
38
+ the pong is confirmed (exit 0), or after --timeout seconds (120) without one
39
+ (exit 1): then listen.`
38
40
  },
39
41
  show: {
40
42
  usage: "<page|file> [<anchor>]",
package/dist/src/hub.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { filesFold } from "./pages/render.js";
1
2
  import { project } from "./config.js";
2
3
  import { followEntries, machineDir, readMachineConfig, stateDir } from "./entries.js";
3
4
  import { VERSION, compareVersions } from "./package.js";
@@ -213,6 +214,12 @@ function createHub({ dir = machineDir(), state = stateDir(), home, interval, onS
213
214
  return sendJson(res, 200, all.flat());
214
215
  }
215
216
  if (p === "/api/stream") return streamAll(req, res, Object.fromEntries(url.searchParams));
217
+ if (p === "/api/files") {
218
+ const s = [...served.values()].find((x) => x.base === url.searchParams.get("base"));
219
+ if (!s) return sendJson(res, 404, { error: "no such project" });
220
+ if (!await s.server.files().catch(() => false)) return sendJson(res, 403, { error: "its files are not served" });
221
+ return sendJson(res, 200, await filesFold(s.dir, s.base));
222
+ }
216
223
  if (p === "/favicon.ico") {
217
224
  res.writeHead(204);
218
225
  res.end();
@@ -7,7 +7,8 @@ import { ACTIVE_FOR, byProject, byState, total, withoutPages } from "./board.js"
7
7
  import fs from "node:fs";
8
8
  import path from "node:path";
9
9
  import os from "node:os";
10
- import { execFileSync } from "node:child_process";
10
+ import { execFile, execFileSync } from "node:child_process";
11
+ import { promisify } from "node:util";
11
12
  import { fileURLToPath } from "node:url";
12
13
  // src/pages/render.ts
13
14
  const BASE_CSS = new URL("../client/page/base.css", import.meta.url);
@@ -36,12 +37,16 @@ const body = (source) => source.replace(FRONTMATTER, "");
36
37
  /** A page's title: its first heading, else its name. */
37
38
  function titleOf(file, fallback) {
38
39
  try {
39
- const h1 = /^#\s+(.+)$/m.exec(body(fs.readFileSync(file, "utf8")));
40
- return h1 ? h1[1].replace(/[*_`]/g, "") : fallback;
40
+ return headingOf(fs.readFileSync(file, "utf8")) ?? fallback;
41
41
  } catch {
42
42
  return fallback;
43
43
  }
44
44
  }
45
+ /** The first heading of a page's markdown, past its frontmatter; null when it has none. */
46
+ function headingOf(source) {
47
+ const h1 = /^#\s+(.+)$/m.exec(body(source));
48
+ return h1 ? h1[1].replace(/[*_`]/g, "") : null;
49
+ }
45
50
  function crumbs(id, name, base, entry) {
46
51
  const parts = id ? id.split("/") : [];
47
52
  const above = entry ? html`<a href="/">workpad</a> / ` : "";
@@ -140,6 +145,101 @@ function documentsIn(dir, shows = (rel) => fileFilter().shows(rel)) {
140
145
  const depth = (f) => f.split("/").length;
141
146
  return [...new Set(files)].filter(shows).toSorted((a, b) => depth(a) - depth(b) || a.localeCompare(b));
142
147
  }
148
+ function docOf(dir, file) {
149
+ const abs = path.join(dir, file);
150
+ let mtime = 0;
151
+ try {
152
+ mtime = fs.statSync(abs).mtimeMs;
153
+ } catch {}
154
+ return {
155
+ file,
156
+ title: titleOf(abs, path.posix.basename(file)),
157
+ mtime
158
+ };
159
+ }
160
+ /**
161
+ * Whether a project without pages has documents to read, without listing them: a markdown file in
162
+ * its top folder (a README). Cheap, so the overview can ask it of every project on each render;
163
+ * the files themselves are listed only when the reader opens the fold (filesFold).
164
+ */
165
+ function hasTopDocs(dir) {
166
+ try {
167
+ return fs.readdirSync(dir).some((n) => MARKDOWN.test(n));
168
+ } catch {
169
+ return false;
170
+ }
171
+ }
172
+ const run = promisify(execFile);
173
+ /**
174
+ * The files fold of a project without pages, listed when the reader opens it (GET /api/files on the
175
+ * shared server): documentsIn's list, but off the event loop. A checkout holds thousands of
176
+ * markdown files, and listing them on each render froze the shared server for many seconds.
177
+ */
178
+ async function filesFold(dir, base) {
179
+ let files;
180
+ try {
181
+ const { stdout } = await run("git", [
182
+ "ls-files",
183
+ "--cached",
184
+ "--others",
185
+ "--exclude-standard",
186
+ "--",
187
+ ":(icase)*.md",
188
+ ":(icase)*.markdown"
189
+ ], {
190
+ cwd: dir,
191
+ encoding: "utf8",
192
+ maxBuffer: 67108864
193
+ });
194
+ files = stdout.split("\n").filter((f) => f && !f.startsWith(".workpad/"));
195
+ } catch {
196
+ files = [];
197
+ const walk = async (rel) => {
198
+ let entries = [];
199
+ try {
200
+ entries = await fs.promises.readdir(path.join(dir, rel), { withFileTypes: true });
201
+ } catch {
202
+ return;
203
+ }
204
+ for (const e of entries) if (e.isDirectory()) {
205
+ if (!SKIP.has(e.name) && !e.name.startsWith(".")) await walk(path.posix.join(rel, e.name));
206
+ } else if (MARKDOWN.test(e.name)) files.push(path.posix.join(rel, e.name));
207
+ };
208
+ await walk("");
209
+ }
210
+ const shows = fileFilter().shows;
211
+ const depth = (f) => f.split("/").length;
212
+ files = [...new Set(files)].filter((f) => shows(f)).toSorted((a, b) => depth(a) - depth(b) || a.localeCompare(b));
213
+ const docs = [];
214
+ for (let i = 0; i < files.length; i += 32) {
215
+ const batch = await Promise.all(files.slice(i, i + 32).map(async (file) => {
216
+ const abs = path.join(dir, file);
217
+ try {
218
+ const handle = await fs.promises.open(abs, "r");
219
+ try {
220
+ const { mtimeMs } = await handle.stat();
221
+ const buf = Buffer.alloc(8192);
222
+ const { bytesRead } = await handle.read(buf, 0, buf.length, 0);
223
+ const name = path.posix.basename(file);
224
+ return {
225
+ file,
226
+ title: headingOf(buf.toString("utf8", 0, bytesRead)) ?? name,
227
+ mtime: mtimeMs
228
+ };
229
+ } finally {
230
+ await handle.close();
231
+ }
232
+ } catch {
233
+ return null;
234
+ }
235
+ }));
236
+ for (const d of batch) if (d) docs.push(d);
237
+ }
238
+ return {
239
+ count: docs.length,
240
+ html: String(documentFolders(docs, dir, base, () => null))
241
+ };
242
+ }
143
243
  /**
144
244
  * The overview's list of the project's documents: each by its title, linked to its rendered page,
145
245
  * with when its file last changed. The list can be sorted in the browser (sort.ts): by folder (as
@@ -154,13 +254,21 @@ function documentList(ctx) {
154
254
  * documents would otherwise be one long list. A folder holding only one folder is shown as one
155
255
  * (`docs/adr/`), so the tree is no deeper than what tells folders apart.
156
256
  */
157
- function documentTree(files, dir, base, urlFor, open = false) {
257
+ function documentTree(docs, dir, base, urlFor, open = false) {
258
+ return html`<details class="wp-documents wp-folded-documents"${raw(open ? " open" : "")}>
259
+ <summary>Files <span class="wp-meta">${docs.length}</span></summary>
260
+ ${documentFolders(docs, dir, base, urlFor)}
261
+ </details>`;
262
+ }
263
+ /** The inside of a project's files fold: its documents by folder, a fold per folder with how many. */
264
+ function documentFolders(docs, dir, base, urlFor) {
158
265
  const root = {
159
266
  files: [],
160
267
  folders: /* @__PURE__ */ new Map(),
161
268
  count: 0
162
269
  };
163
- for (const f of files) {
270
+ const byFile = new Map(docs.map((d) => [d.file, d]));
271
+ for (const { file: f } of docs) {
164
272
  let at = root;
165
273
  at.count++;
166
274
  const parts = f.split("/");
@@ -178,11 +286,7 @@ function documentTree(files, dir, base, urlFor, open = false) {
178
286
  const row = (f) => {
179
287
  const abs = path.join(dir, f);
180
288
  const name = path.posix.basename(f);
181
- const title = titleOf(abs, name);
182
- let mtime = 0;
183
- try {
184
- mtime = fs.statSync(abs).mtimeMs;
185
- } catch {}
289
+ const { title, mtime } = byFile.get(f);
186
290
  return html`<li>
187
291
  <a href="${urlFor(abs) ?? `${base}/-/${f}`}">${title}</a>
188
292
  <span class="wp-meta">${title !== name && html`<code>${name}</code> · `}edited ${time(mtime)}</span>
@@ -202,32 +306,24 @@ function documentTree(files, dir, base, urlFor, open = false) {
202
306
  const contents = (f) => html`${f.files.length > 0 && html`<ul class="wp-index">
203
307
  ${f.files.map(row)}
204
308
  </ul>`}${[...f.folders].toSorted(([a], [b]) => a.localeCompare(b)).map(([name, sub]) => folder(name, sub))}`;
205
- return html`<details class="wp-documents wp-folded-documents"${raw(open ? " open" : "")}>
206
- <summary>Files <span class="wp-meta">${files.length}</span></summary>
207
- ${contents(root)}
208
- </details>`;
309
+ return contents(root);
209
310
  }
210
311
  /**
211
312
  * A project's documents, as its overview lists them: from its folder, linked where it serves them.
212
313
  * `folded`: in a fold that says how many (the shared server's overview, where each project has them).
213
314
  */
214
315
  function documentsOf(dir, base, urlFor, folded = false, shows, open = false) {
215
- const files = documentsIn(dir, shows);
216
- if (!files.length) return "";
316
+ const docs = documentsIn(dir, shows).map((f) => docOf(dir, f));
317
+ if (!docs.length) return "";
318
+ if (folded) return documentTree(docs, dir, base, urlFor, open);
217
319
  const ctx = {
218
320
  project: { dir },
219
321
  base,
220
322
  urlFor
221
323
  };
222
- const rows = files.map((f, i) => {
324
+ const rows = docs.map(({ file: f, title, mtime }, i) => {
223
325
  const abs = path.join(ctx.project.dir, f);
224
- const name = path.posix.basename(f);
225
- const title = titleOf(abs, name);
226
- const where = title === name ? path.posix.dirname(f) : f;
227
- let mtime = 0;
228
- try {
229
- mtime = fs.statSync(abs).mtimeMs;
230
- } catch {}
326
+ const where = title === path.posix.basename(f) ? path.posix.dirname(f) : f;
231
327
  return html`<li data-order="${i}" data-updated="${mtime}" data-title="${title.toLowerCase()}">
232
328
  <a href="${ctx.urlFor(abs) ?? `${ctx.base ?? ""}/-/${f}`}">${title}</a>
233
329
  <span class="wp-meta"
@@ -235,7 +331,6 @@ function documentsOf(dir, base, urlFor, folded = false, shows, open = false) {
235
331
  >
236
332
  </li>`;
237
333
  });
238
- if (folded) return documentTree(files, dir, base, urlFor, open);
239
334
  return html`<section class="wp-documents">
240
335
  <div class="wp-list-head">
241
336
  <h2>Documents</h2>
@@ -294,10 +389,9 @@ function emptyColumn(projects) {
294
389
  */
295
390
  function board(projects, now) {
296
391
  const states = byState(projects, now);
297
- const docsOf = new Map(withoutPages(projects).map((p) => [p, p.files ? documentsIn(p.dir).length : 0]));
298
392
  const empty = withoutPages(projects);
299
- const withDocs = [...docsOf].filter(([, n]) => n > 0).map(([p]) => p);
300
- const bare = empty.filter((p) => !docsOf.get(p));
393
+ const withDocs = empty.filter((p) => p.files && hasTopDocs(p.dir));
394
+ const bare = empty.filter((p) => !withDocs.includes(p));
301
395
  const hours = ACTIVE_FOR / 36e5;
302
396
  const stateColumn = (key, title, note) => html`<section class="wp-board-column wp-board-${key}${key === "waiting" && states.waiting.length ? " wp-board-waits" : ""}">
303
397
  <header class="wp-board-head">
@@ -320,9 +414,11 @@ function board(projects, now) {
320
414
  const docsColumn = (p) => html`<section class="wp-board-column wp-board-docs">
321
415
  <header class="wp-board-head" title="${p.dir.replace(os.homedir(), "~")}">
322
416
  <h2><a href="${p.base}/">${p.label}</a></h2>
323
- <span class="wp-meta">no pages · ${docsOf.get(p)} file${docsOf.get(p) === 1 ? "" : "s"}</span>
417
+ <span class="wp-meta">no pages</span>
324
418
  </header>
325
- ${documentsOf(p.dir, p.base, () => null, true, void 0, true)}
419
+ <details class="wp-documents wp-folded-documents" data-wp-files="${p.base}">
420
+ <summary>Files <span class="wp-meta"></span></summary>
421
+ </details>
326
422
  </section>`;
327
423
  return html`<div class="wp-board-bar">
328
424
  <div class="wp-board-switch" role="group" aria-label="Columns">
@@ -662,4 +758,4 @@ ${GROUPS.map(([group, title]) => {
662
758
  `;
663
759
  };
664
760
  }
665
- export { createAgentMessageRender, createBlocksRender, createDocs, createMessageRender, createRender, titleOf };
761
+ export { createAgentMessageRender, createBlocksRender, createDocs, createMessageRender, createRender, filesFold, hasTopDocs, titleOf };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bigmistqke/workpad",
3
- "version": "0.18.0",
3
+ "version": "0.18.1",
4
4
  "description": "A workpad for you and your agent: it writes markdown pages you read live in the browser, you answer through forms it waits on",
5
5
  "keywords": [
6
6
  "agent",
@@ -425,11 +425,14 @@ message. Whether it does, only a round trip can tell. Once a session,
425
425
  before you first need answers, run
426
426
 
427
427
  ```sh
428
- workpad agent ping
428
+ workpad agent ping --wait # in the background
429
429
  ```
430
430
 
431
- - It says nothing brings answers to this session (exit 1): listen for
432
- them, below.
431
+ Run it in the background, so its end wakes you whatever happens; never
432
+ ping and then just wait for a pong that may not come.
433
+
434
+ - It says nothing brings answers to this session (exit 1 at once): listen
435
+ for them, below.
433
436
  - It pinged this session's channel: a message `workpad: pong` comes to
434
437
  you the way answers will. It may only come once your turn has ended (in
435
438
  opencode it does), so don't start a `listen` yet: end your turn if you
@@ -442,9 +445,10 @@ workpad agent ping
442
445
  once; the channel brings the user's answers waiting there and what
443
446
  comes. Other agents' messages from before that someone already received
444
447
  are skipped; it says how many, and `workpad listen --wait --page
445
- <file>` hands them to you when you want to catch up. No pong by your
446
- next turn: listen for them, below, and in Claude Code tell the user what
447
- `workpad claude doctor` says is wrong.
448
+ <file>` hands them to you when you want to catch up. Once you confirmed,
449
+ the background ping ends (exit 0). No pong confirmed within two minutes:
450
+ it ends with exit 1, and that wakes you: listen for them, below, and in
451
+ Claude Code tell the user what `workpad claude doctor` says is wrong.
448
452
 
449
453
  The answers come as one line each: the page, what the user did, its id:
450
454
  `plan: form scope: "Smaller" (id mwv…; …)`. Act on each, handle it, then
package/src/agents.ts CHANGED
@@ -25,7 +25,8 @@ export const identity = (session: string | null): string | null => process.env.W
25
25
  const waitOn = (pages: PageStatus[]) => `workpad listen --wait ${pages.map(p => `--page ${relFile(p.file)}`).join(' ')}`
26
26
 
27
27
  /** For a page nobody listens on: a channel the session has may bring the answers instead. */
28
- const PING = 'run `workpad agent ping` if you haven\'t this session (answers may come to you); else'
28
+ const PING =
29
+ 'run `workpad agent ping --wait` in the background if you haven\'t this session (answers may come to you; it ends when you confirmed the pong, or when none came); else'
29
30
 
30
31
 
31
32
  /**
@@ -132,6 +132,35 @@ export function trackBoard() {
132
132
  applyBoard(view)
133
133
  applySearch()
134
134
  })
135
+ // a project's files fold without its files in it: the server lists them once it is opened
136
+ document.addEventListener(
137
+ 'toggle',
138
+ e => {
139
+ const fold = e.target as HTMLDetailsElement
140
+ if (fold.dataset?.wpFiles && fold.open) void loadFiles(fold)
141
+ },
142
+ true,
143
+ )
135
144
  applyBoard(chosen())
136
145
  trackSearch()
137
146
  }
147
+
148
+ async function loadFiles(fold: HTMLDetailsElement) {
149
+ if (fold.dataset.wpLoaded) return
150
+ fold.dataset.wpLoaded = 'loading'
151
+ const count = fold.querySelector('summary .wp-meta')
152
+ if (count) count.textContent = '…'
153
+ try {
154
+ const res = await fetch(`/api/files?base=${encodeURIComponent(fold.dataset.wpFiles!)}`)
155
+ const body = (await res.json()) as { count?: number; html?: string; error?: string }
156
+ if (!res.ok) throw new Error(body.error ?? res.statusText)
157
+ if (count) count.textContent = String(body.count)
158
+ fold.insertAdjacentHTML('beforeend', body.count ? body.html! : '<p class="wp-meta">No markdown files.</p>')
159
+ fold.dataset.wpLoaded = 'yes'
160
+ applySearch()
161
+ } catch (err) {
162
+ delete fold.dataset.wpLoaded
163
+ if (count) count.textContent = ''
164
+ fold.insertAdjacentHTML('beforeend', `<p class="wp-meta">Couldn't list the files: ${String((err as Error).message)}</p>`)
165
+ }
166
+ }
package/src/help.ts CHANGED
@@ -30,7 +30,7 @@ export const COMMAND_HELP: Record<string, CommandHelp> = {
30
30
  },
31
31
 
32
32
  agent: {
33
- usage: '[name <name> | name --clear | list | unsubscribe <agent> [--page <p>…] | ping [<code>]]',
33
+ usage: '[name <name> | name --clear | list | unsubscribe <agent> [--page <p>…] | ping [<code> | --wait [--timeout <s>]]]',
34
34
  summary: 'who you are on the boards: your id and name; name yourself, see who else is around, check a channel reaches you',
35
35
  details: `Your id is --agent, else WORKPAD_AGENT, else the session an agent plugin names (claude(),
36
36
  opencode()). Alone, it says your id and your name.
@@ -46,7 +46,9 @@ opencode()). Alone, it says your id and your name.
46
46
  into the session, the way answers will, with the code to confirm with. Once
47
47
  confirmed, the channel listens on your pages, and the answers it brings count
48
48
  as received. No channel (exit 1), or no pong: nothing brings answers here, so
49
- listen for them.`,
49
+ listen for them. --wait: run it in the background; it pings and ends when
50
+ the pong is confirmed (exit 0), or after --timeout seconds (120) without one
51
+ (exit 1): then listen.`,
50
52
  },
51
53
 
52
54
  show: {
package/src/hub.ts CHANGED
@@ -23,6 +23,7 @@
23
23
  // A project's server is made when the project is found and closed when it goes, so a project
24
24
  // appears and disappears without a restart. Each keeps its own state, config and log, as it would
25
25
  // on a port of its own: the shared server only routes.
26
+ import { filesFold } from './pages/render.ts'
26
27
  import fs from 'node:fs'
27
28
  import path from 'node:path'
28
29
  import type { IncomingMessage, ServerResponse } from 'node:http'
@@ -302,6 +303,14 @@ export function createHub({
302
303
  return sendJson(res, 200, all.flat())
303
304
  }
304
305
  if (p === '/api/stream') return streamAll(req, res, Object.fromEntries(url.searchParams))
306
+ // a project's files, for its fold on the overview: listed when the reader opens it, off the
307
+ // event loop, so the overview's render reads no project's files (src/pages/render.ts)
308
+ if (p === '/api/files') {
309
+ const s = [...served.values()].find(x => x.base === url.searchParams.get('base'))
310
+ if (!s) return sendJson(res, 404, { error: 'no such project' })
311
+ if (!(await s.server.files().catch(() => false))) return sendJson(res, 403, { error: 'its files are not served' })
312
+ return sendJson(res, 200, await filesFold(s.dir, s.base))
313
+ }
305
314
  if (p === '/favicon.ico') {
306
315
  res.writeHead(204)
307
316
  return void res.end()
@@ -8,7 +8,8 @@ import fs from 'node:fs'
8
8
  import os from 'node:os'
9
9
  import path from 'node:path'
10
10
  import { fileURLToPath } from 'node:url'
11
- import { execFileSync } from 'node:child_process'
11
+ import { execFile, execFileSync } from 'node:child_process'
12
+ import { promisify } from 'node:util'
12
13
  import { renderMarkdown, type Island, type MdNode } from './markdown.ts'
13
14
  import { html, raw, type Html } from '../html.ts'
14
15
  import { INBOX_ICON, awaitingLabel } from '../icons.ts'
@@ -62,13 +63,18 @@ const body = (source: string) => source.replace(FRONTMATTER, '')
62
63
  /** A page's title: its first heading, else its name. */
63
64
  export function titleOf(file: string, fallback: string) {
64
65
  try {
65
- const h1 = /^#\s+(.+)$/m.exec(body(fs.readFileSync(file, 'utf8')))
66
- return h1 ? h1[1].replace(/[*_`]/g, '') : fallback
66
+ return headingOf(fs.readFileSync(file, 'utf8')) ?? fallback
67
67
  } catch {
68
68
  return fallback
69
69
  }
70
70
  }
71
71
 
72
+ /** The first heading of a page's markdown, past its frontmatter; null when it has none. */
73
+ function headingOf(source: string): string | null {
74
+ const h1 = /^#\s+(.+)$/m.exec(body(source))
75
+ return h1 ? h1[1].replace(/[*_`]/g, '') : null
76
+ }
77
+
72
78
  function crumbs(id: string, name: string, base: string, entry?: RenderContext['entry']) {
73
79
  const parts = id ? id.split('/') : []
74
80
  // under a shared server, the overview of every project comes first, by its own name
@@ -161,6 +167,100 @@ function documentsIn(dir: string, shows: (rel: string) => boolean = rel => fileF
161
167
  return [...new Set(files)].filter(shows).toSorted((a, b) => depth(a) - depth(b) || a.localeCompare(b))
162
168
  }
163
169
 
170
+ /** A document as the overview lists it: its path in the project, its title, when its file last changed. */
171
+ interface Doc {
172
+ file: string
173
+ title: string
174
+ mtime: number
175
+ }
176
+
177
+ function docOf(dir: string, file: string): Doc {
178
+ const abs = path.join(dir, file)
179
+ let mtime = 0
180
+ try {
181
+ mtime = fs.statSync(abs).mtimeMs
182
+ } catch {
183
+ /* gone meanwhile */
184
+ }
185
+ return { file, title: titleOf(abs, path.posix.basename(file)), mtime }
186
+ }
187
+
188
+ /**
189
+ * Whether a project without pages has documents to read, without listing them: a markdown file in
190
+ * its top folder (a README). Cheap, so the overview can ask it of every project on each render;
191
+ * the files themselves are listed only when the reader opens the fold (filesFold).
192
+ */
193
+ export function hasTopDocs(dir: string): boolean {
194
+ try {
195
+ return fs.readdirSync(dir).some(n => MARKDOWN.test(n))
196
+ } catch {
197
+ return false
198
+ }
199
+ }
200
+
201
+ const run = promisify(execFile)
202
+
203
+ /**
204
+ * The files fold of a project without pages, listed when the reader opens it (GET /api/files on the
205
+ * shared server): documentsIn's list, but off the event loop. A checkout holds thousands of
206
+ * markdown files, and listing them on each render froze the shared server for many seconds.
207
+ */
208
+ export async function filesFold(dir: string, base: string): Promise<{ count: number; html: string }> {
209
+ let files: string[]
210
+ try {
211
+ const { stdout } = await run(
212
+ 'git',
213
+ ['ls-files', '--cached', '--others', '--exclude-standard', '--', ':(icase)*.md', ':(icase)*.markdown'],
214
+ { cwd: dir, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 },
215
+ )
216
+ files = stdout.split('\n').filter(f => f && !f.startsWith('.workpad/'))
217
+ } catch {
218
+ files = []
219
+ const walk = async (rel: string) => {
220
+ let entries: fs.Dirent[] = []
221
+ try {
222
+ entries = await fs.promises.readdir(path.join(dir, rel), { withFileTypes: true })
223
+ } catch {
224
+ return
225
+ }
226
+ for (const e of entries) {
227
+ if (e.isDirectory()) {
228
+ if (!SKIP.has(e.name) && !e.name.startsWith('.')) await walk(path.posix.join(rel, e.name))
229
+ } else if (MARKDOWN.test(e.name)) files.push(path.posix.join(rel, e.name))
230
+ }
231
+ }
232
+ await walk('')
233
+ }
234
+ const shows = fileFilter().shows
235
+ const depth = (f: string) => f.split('/').length
236
+ files = [...new Set(files)].filter(f => shows(f)).toSorted((a, b) => depth(a) - depth(b) || a.localeCompare(b))
237
+ // a title is in a file's first lines: read only those, a few files at a time
238
+ const docs: Doc[] = []
239
+ for (let i = 0; i < files.length; i += 32) {
240
+ const batch = await Promise.all(
241
+ files.slice(i, i + 32).map(async (file): Promise<Doc | null> => {
242
+ const abs = path.join(dir, file)
243
+ try {
244
+ const handle = await fs.promises.open(abs, 'r')
245
+ try {
246
+ const { mtimeMs } = await handle.stat()
247
+ const buf = Buffer.alloc(8192)
248
+ const { bytesRead } = await handle.read(buf, 0, buf.length, 0)
249
+ const name = path.posix.basename(file)
250
+ return { file, title: headingOf(buf.toString('utf8', 0, bytesRead)) ?? name, mtime: mtimeMs }
251
+ } finally {
252
+ await handle.close()
253
+ }
254
+ } catch {
255
+ return null // gone meanwhile (git also lists files deleted and not yet committed)
256
+ }
257
+ }),
258
+ )
259
+ for (const d of batch) if (d) docs.push(d)
260
+ }
261
+ return { count: docs.length, html: String(documentFolders(docs, dir, base, () => null)) }
262
+ }
263
+
164
264
  /**
165
265
  * The overview's list of the project's documents: each by its title, linked to its rendered page,
166
266
  * with when its file last changed. The list can be sorted in the browser (sort.ts): by folder (as
@@ -177,19 +277,28 @@ function documentList(ctx: RenderContext) {
177
277
  * (`docs/adr/`), so the tree is no deeper than what tells folders apart.
178
278
  */
179
279
  function documentTree(
180
- files: string[],
280
+ docs: Doc[],
181
281
  dir: string,
182
282
  base: string,
183
283
  urlFor: (abs: string) => string | null,
184
284
  open = false,
185
285
  ) {
286
+ return html`<details class="wp-documents wp-folded-documents"${raw(open ? ' open' : '')}>
287
+ <summary>Files <span class="wp-meta">${docs.length}</span></summary>
288
+ ${documentFolders(docs, dir, base, urlFor)}
289
+ </details>`
290
+ }
291
+
292
+ /** The inside of a project's files fold: its documents by folder, a fold per folder with how many. */
293
+ function documentFolders(docs: Doc[], dir: string, base: string, urlFor: (abs: string) => string | null): Html {
186
294
  interface Folder {
187
295
  files: string[]
188
296
  folders: Map<string, Folder>
189
297
  count: number
190
298
  }
191
299
  const root: Folder = { files: [], folders: new Map(), count: 0 }
192
- for (const f of files) {
300
+ const byFile = new Map(docs.map(d => [d.file, d]))
301
+ for (const { file: f } of docs) {
193
302
  let at = root
194
303
  at.count++
195
304
  const parts = f.split('/')
@@ -203,13 +312,7 @@ function documentTree(
203
312
  const row = (f: string) => {
204
313
  const abs = path.join(dir, f)
205
314
  const name = path.posix.basename(f)
206
- const title = titleOf(abs, name)
207
- let mtime = 0
208
- try {
209
- mtime = fs.statSync(abs).mtimeMs
210
- } catch {
211
- /* gone meanwhile */
212
- }
315
+ const { title, mtime } = byFile.get(f)!
213
316
  return html`<li>
214
317
  <a href="${urlFor(abs) ?? `${base}/-/${f}`}">${title}</a>
215
318
  <span class="wp-meta">${title !== name && html`<code>${name}</code> · `}edited ${time(mtime)}</span>
@@ -234,10 +337,7 @@ function documentTree(
234
337
  ${f.files.map(row)}
235
338
  </ul>`
236
339
  }${[...f.folders].toSorted(([a], [b]) => a.localeCompare(b)).map(([name, sub]) => folder(name, sub))}`
237
- return html`<details class="wp-documents wp-folded-documents"${raw(open ? ' open' : '')}>
238
- <summary>Files <span class="wp-meta">${files.length}</span></summary>
239
- ${contents(root)}
240
- </details>`
340
+ return contents(root)
241
341
  }
242
342
 
243
343
  /**
@@ -252,21 +352,15 @@ function documentsOf(
252
352
  shows?: (rel: string) => boolean,
253
353
  open = false,
254
354
  ) {
255
- const files = documentsIn(dir, shows)
256
- if (!files.length) return ''
355
+ const docs = documentsIn(dir, shows).map(f => docOf(dir, f))
356
+ if (!docs.length) return ''
357
+ if (folded) return documentTree(docs, dir, base, urlFor, open)
257
358
  const ctx = { project: { dir }, base, urlFor }
258
- const rows = files.map((f, i) => {
359
+ const rows = docs.map(({ file: f, title, mtime }, i) => {
259
360
  const abs = path.join(ctx.project.dir, f)
260
361
  // a file without a heading goes by its name, and the line under it says the folder it is in
261
362
  const name = path.posix.basename(f)
262
- const title = titleOf(abs, name)
263
363
  const where = title === name ? path.posix.dirname(f) : f
264
- let mtime = 0
265
- try {
266
- mtime = fs.statSync(abs).mtimeMs
267
- } catch {
268
- /* gone meanwhile */
269
- }
270
364
  return html`<li data-order="${i}" data-updated="${mtime}" data-title="${title.toLowerCase()}">
271
365
  <a href="${ctx.urlFor(abs) ?? `${ctx.base ?? ''}/-/${f}`}">${title}</a>
272
366
  <span class="wp-meta"
@@ -274,7 +368,6 @@ function documentsOf(
274
368
  >
275
369
  </li>`
276
370
  })
277
- if (folded) return documentTree(files, dir, base, urlFor, open)
278
371
  // in a section, so the heading isn't numbered like the page's own sections
279
372
  return html`<section class="wp-documents">
280
373
  <div class="wp-list-head">
@@ -359,11 +452,12 @@ function emptyColumn(projects: BoardProject[]) {
359
452
  function board(projects: BoardProject[], now: number) {
360
453
  const states = byState(projects, now)
361
454
  // of the projects without pages, those with documents to read get a column of their own in the
362
- // per-project view (a worktree's README and docs), and only the truly empty fold at the end
363
- const docsOf = new Map(withoutPages(projects).map(p => [p, p.files ? documentsIn(p.dir).length : 0]))
455
+ // per-project view (a worktree's README and docs), and only the truly empty fold at the end. Which
456
+ // is which is a look at the top folder: listing a checkout's files (thousands, in a big repository)
457
+ // waits until the reader opens its fold (filesFold), so a render reads no project's files
364
458
  const empty = withoutPages(projects)
365
- const withDocs = [...docsOf].filter(([, n]) => n > 0).map(([p]) => p)
366
- const bare = empty.filter(p => !docsOf.get(p))
459
+ const withDocs = empty.filter(p => p.files && hasTopDocs(p.dir))
460
+ const bare = empty.filter(p => !withDocs.includes(p))
367
461
  const hours = ACTIVE_FOR / 3_600_000
368
462
  const stateColumn = (key: keyof typeof states, title: string, note: string) =>
369
463
  html`<section class="wp-board-column wp-board-${key}${key === 'waiting' && states.waiting.length ? ' wp-board-waits' : ''}">
@@ -384,14 +478,17 @@ function board(projects: BoardProject[], now: number) {
384
478
  ${cards(col.cards, false)} ${p.files && documentsOf(p.dir, p.base, () => null, true)}
385
479
  </section>`
386
480
  }
387
- // a project with documents and no pages: its column holds its files, open
481
+ // a project with documents and no pages: its column holds its files, listed when the fold opens
482
+ // (board.ts in the page asks /api/files for them)
388
483
  const docsColumn = (p: BoardProject) =>
389
484
  html`<section class="wp-board-column wp-board-docs">
390
485
  <header class="wp-board-head" title="${p.dir.replace(os.homedir(), '~')}">
391
486
  <h2><a href="${p.base}/">${p.label}</a></h2>
392
- <span class="wp-meta">no pages · ${docsOf.get(p)} file${docsOf.get(p) === 1 ? '' : 's'}</span>
487
+ <span class="wp-meta">no pages</span>
393
488
  </header>
394
- ${documentsOf(p.dir, p.base, () => null, true, undefined, true)}
489
+ <details class="wp-documents wp-folded-documents" data-wp-files="${p.base}">
490
+ <summary>Files <span class="wp-meta"></span></summary>
491
+ </details>
395
492
  </section>`
396
493
  return html`<div class="wp-board-bar">
397
494
  <div class="wp-board-switch" role="group" aria-label="Columns">