@leonidstern/labit 0.6.3-main.16 → 0.6.3-main.17

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/CHANGELOG.md CHANGED
@@ -4,6 +4,22 @@ Versions follow [semver](https://semver.org). Before 1.0, a minor version can ch
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ - The listening badge has three looks: a plain green rabbit while an agent is connected and listening, green with twitching ears while it works on pins, and black only when nobody listens. Black used to mean listening, grey nobody. A dropped connection (a phone waking, the laptop sleeping) keeps the last look, faded, with "reconnecting", instead of going to nobody.
8
+ - Labs & pages: ⌘K (Control-K off a Mac), or "labs & pages" in the ⋯ menu, opens a box listing every lab running on this computer and its pages, with open comments and who's listening. Type to filter, ↵ goes, ⌘↵ opens a new tab. Each lab can be **archived**: Claude's wait on it ends with "stopped from the page" (it doesn't wait again until asked) and the lab stops. With nobody listening, **get Claude listening** copies a line to paste to your agent. The ⋯ menu now opens with the lab's name and port. On a phone the box is a sheet that holds still when the keyboard comes up. A wifi guest sees this lab's pages and the other labs open to the wifi: tapping one of their pages goes through `/_lab/hop`, where this lab asks that one for a one-time link for the same name, so the phone needs no new invite. New routes: `GET /_lab/labs`, `POST /_lab/labs` (this computer, with the lab's key).
9
+ - Labs & pages, in words and about pages: each lab is a heading (its folder, which goes to its home; its port, who listens, its totals, when it was made and how long it has run are on hover), and each page reads "Title /path 5m ago": its last activity, a comment, reply or close or someone opening it, and labs and pages are ordered by it, newest first; when it was last opened (kept in `.lab/opened.json`), who commented, replies and the file's time are on hover. A guest's box lists only the keys that work for a guest, and this computer opened through its wifi address is told to use localhost for every lab and the lab keys. On a phone it is one of the widget's sheets, the comment and chat drawer: the handle, the swipe down, the dimmed page, the keyboard fit and back closing are theirs; on a computer the page dims with the widget's own `.scrim`. A phone also names the labs it can't open (not on the wifi, or on an older labit) under "on the computer only".
10
+ - A lab's home (its list of pages) speaks to a phone in phone words: hold a spot to comment, ⋯ then "labs & pages" for another lab, instead of keys. On a computer it adds ⌘K.
11
+ - CI reuse check (`npm run reuse`, `ci/reuse.mjs`): fails on a second drawer, dimmed page, swipe or keyboard fit, a new animation, a new widget module, or a long style copied into a second rule. Something genuinely new is listed in `ci/parts.json`, on purpose, in the same pull request.
12
+ - A lab no longer starts on a port another lab holds. A lab on the wifi listens on every address, and macOS still let a second lab take 127.0.0.1 on the same port, so localhost reached one lab or the other; ports in `~/.labit/servers` are skipped now.
13
+ - `labit publish <page.html | folder> [--name "topic"]` shows a page the way an Artifact is shown: it goes into your one pages lab (`pagesFolder`), which starts if it isn't running, and prints the page's link. Publishing again updates it at the same link. The skill uses it for every page that isn't part of a project's site.
14
+ - One lab per project, not one per topic: the skill has agents check `labit list` and reuse the running lab, and put pages that belong to no project (tries, demos, options) in one pages lab, a folder per topic, instead of a new folder and lab each time. Its folder is the new personal setting `pagesFolder` (default `~/lab-pages`).
15
+ - Labs & pages is one list of pages from every lab, last active first, with no lab headings: each row names its lab (its topic, or its folder) in grey beside the time. A lab is only the folder a page lives in. ⇧⌥A archives the chosen page's whole lab (press it twice); the heading buttons are gone. Opening "archived" keeps the list where it was and chooses its first row. Search also matches the grey lab label and the lab's folder; a long lab label gives way to the page title; a search with no results says "nothing matches" on a phone too.
16
+ - Labs & pages can archive a page: ⌥A on the chosen one folds it away under "archived" at the bottom, with its lab's name; ↵ still opens it and ⌥A there brings it back. The file stays; the list is the lab's `.lab/archived.json`. A whole lab still archives with its button. New `POST /_lab/labs` actions: `archive-page`, `unarchive-page` (with `page`).
17
+ - A lab can be named for its topic: `labit --name "Lab navigation"`. Labs & pages (⌘K) and the ⋯ menu show the name instead of the folder (the folder is on hover); it's kept in `.lab/name`, so later starts keep it. The skill asks agents to name the labs they start.
18
+ - ⌥W goes to the next new comment from the widget's text boxes too, where W types a letter (Shift-⌥W: the one before). Control-D still does.
19
+ - Labs & pages, archiving and dates: a lab can be **archived** (it stops and folds away under "archived · N" at the bottom; ↵ starts it again, same folder and port). Each lab is headed by its folder (~/projects/site), its port on hover. Parking was tried and taken out: a lab parked by an earlier build shows under archived too. One order: last active first (sorting was tried and taken out). Each page reads its last activity (a comment, reply or close, or someone opening it). ⌥A archives the chosen row's lab (asks twice); a separate stop listening was tried and folded into archive. The footer is one short line. On a phone: the sheet fills the space above the keyboard, a swipe down from the top of the list closes it, and it opens scrolled to the page you're on.
20
+ - Listening, per page: the lab tells pages which of them a wait hears (`heard` in the state). A page that no wait covers (another session listens with `--page` on a different one) says "no agent on this page" instead of "talking to Claude", and its comment box says "no agent listening yet". Hovering the pill says what to tell the agent to listen there. A wait that runs out keeps the pages saying listening for 45 s (`LAB_BETWEEN_MS`), so the agent's next wait doesn't flash "no agent" in between; a cancelled wait still shows it at once.
21
+ - Two sessions on one lab: when one gets its pins, the lab stays "listening" while the other's wait is open, and the ten-minute timer after a hand-over no longer turns every page away while a wait is still open. Before, one session working on its pins turned the other's pages to "no agent listening".
22
+ - `reply <id> --wait --page /x` listens on /x, as `wait --page /x` does. It used to drop the page and listen on every page instead, so a session answering on one page stopped hearing it.
7
23
  - A pin between two blocks whose block above is gone (the section was deleted) no longer crashes the widget: it sits at the end of the box instead. Before, one such pin stopped the bar from drawing on its page.
8
24
  - License: from the next release labit is under [PolyForm Perimeter 1.0.0](LICENSE) instead of MIT. Use and change it freely, except to build a competing product. Versions already on npm (0.6.2 and earlier) keep MIT.
9
25
  - Phone links with two labs on one computer: each lab keeps its own pass (`lab_guest_<port>`), so joining a try lab no longer logs the phone out of the other, and a used link again takes that phone to its page instead of "used up".
@@ -21,6 +37,7 @@ Versions follow [semver](https://semver.org). Before 1.0, a minor version can ch
21
37
  - Comments API: a write can't undo a change made meanwhile.
22
38
 
23
39
  - Releases publish themselves: a version bump merged to main goes to npm as `latest` (tagged `vX.Y.Z`), and every merge to main goes out as `next` (0.6.3-main.41…). `npx @leonidstern/labit@latest` is the newest release; `@next` is main as it is now, for whoever wants each merge in their labs. From GitHub Actions with npm trusted publishing, no token.
40
+ - Labs & pages: no hand pointer on its links, rows or buttons; they show the arrow.
24
41
 
25
42
  ## 0.6.2 · 2026-11-17
26
43
 
@@ -39,7 +39,8 @@ var labCall = (server, pathname, body, session, signal) => new Promise((resolve,
39
39
  var WAIT_SAID = {
40
40
  204: "No new comments yet. Run wait again to keep listening.",
41
41
  409: "Another session is listening now; this one stopped.",
42
- 410: "The page was closed, so this stopped listening. Wait again only when the person asks or opens the page."
42
+ 410: "The page was closed, so this stopped listening. Wait again only when the person asks or opens the page.",
43
+ 423: "The person stopped listening from the page (labs & pages). Don't wait again until they ask you to."
43
44
  };
44
45
 
45
46
  export {
@@ -61,6 +61,14 @@ var runningLabs = () => (fs.existsSync(REGISTRY) ? fs.readdirSync(REGISTRY) : []
61
61
  return [];
62
62
  }
63
63
  }).sort((a, b) => a.root.localeCompare(b.root));
64
+ var PARKED = path.join(path.dirname(REGISTRY), "parked");
65
+ var parkedLabs = () => (fs.existsSync(PARKED) ? fs.readdirSync(PARKED) : []).filter((n) => n.endsWith(".json")).flatMap((n) => {
66
+ try {
67
+ return [JSON.parse(fs.readFileSync(path.join(PARKED, n), "utf8"))];
68
+ } catch {
69
+ return [];
70
+ }
71
+ }).sort((a, b) => a.name.localeCompare(b.name));
64
72
 
65
73
  export {
66
74
  listenPages,
@@ -71,5 +79,7 @@ export {
71
79
  parseArgs,
72
80
  REGISTRY,
73
81
  keyFor,
74
- runningLabs
82
+ runningLabs,
83
+ PARKED,
84
+ parkedLabs
75
85
  };
@@ -5,18 +5,20 @@ import {
5
5
  replyIntent,
6
6
  runningLabs,
7
7
  waitSeconds
8
- } from "./chunk-B5QP5NGM.mjs";
8
+ } from "./chunk-ZL5RPOIP.mjs";
9
9
  import {
10
10
  WAIT_SAID,
11
11
  findLab,
12
12
  labCall
13
- } from "./chunk-QTMKKULT.mjs";
13
+ } from "./chunk-FVO4473A.mjs";
14
14
  import {
15
15
  mySession
16
16
  } from "./chunk-X4RYDWNI.mjs";
17
17
 
18
18
  // lib/commands.ts
19
+ import { spawn } from "node:child_process";
19
20
  import fs from "node:fs";
21
+ import os from "node:os";
20
22
  import path from "node:path";
21
23
  async function runCommand({ pos, opts, HERE, CMD, ME, die }) {
22
24
  if (pos[0] === "preview") {
@@ -46,6 +48,37 @@ ${JSON.stringify(entry(), null, 2)}`);
46
48
  process.exit(0);
47
49
  }
48
50
  const forHere = (lab) => lab.root === HERE || lab.root.startsWith(HERE + path.sep) || HERE.startsWith(lab.root + path.sep);
51
+ if (pos[0] === "publish") {
52
+ const src = pos[1] && path.resolve(pos[1]);
53
+ if (!src || !fs.existsSync(src)) die(`Usage: ${CMD} publish <page.html | folder> [--name "topic"]`);
54
+ const { loadSettings } = await import("./settings-OTB7HBCL.mjs");
55
+ const home = String(loadSettings(HERE, {}).values.pagesFolder || "~/lab-pages").replace(/^~(?=$|\/)/, os.homedir());
56
+ fs.mkdirSync(home, { recursive: true });
57
+ const root = fs.realpathSync(home);
58
+ const dir = fs.statSync(src).isDirectory();
59
+ const topic = typeof opts.name === "string" ? opts.name : path.basename(src).replace(/\.html?$/i, "");
60
+ const slug = topic.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "page";
61
+ if (!dir && !/\.html?$/i.test(src)) die(`${src}: give an .html file, or a folder of pages`);
62
+ const dest = path.join(root, dir ? slug : `${slug}.html`);
63
+ if (path.resolve(src) !== dest) {
64
+ fs.rmSync(dest, { recursive: true, force: true });
65
+ fs.cpSync(src, dest, { recursive: true });
66
+ }
67
+ let lab = runningLabs().find((l) => l.root === root);
68
+ if (!lab) {
69
+ spawn(process.execPath, [ME, root, "--no-open", "--name", "Pages"], { cwd: root, detached: true, stdio: "ignore" }).unref();
70
+ for (let i = 0; i < 100 && !lab; i++) {
71
+ await new Promise((r) => setTimeout(r, 100));
72
+ lab = runningLabs().find((l) => l.root === root);
73
+ }
74
+ if (!lab) die(`The pages lab didn't start. Run it yourself: ${CMD} ${root}`);
75
+ }
76
+ const key = keyFor(path.relative(root, dir ? path.join(dest, "index.html") : dest));
77
+ console.log(`http://localhost:${lab.port}${key.replace(/\/index$/, "/")}`);
78
+ console.log(`In the pages lab (${root.replace(os.homedir(), "~")}). Publish again to update it, same link.`);
79
+ console.log(`Listen for its pins: cd ${root} && ${CMD} wait --bg --pages ${key}`);
80
+ process.exit(0);
81
+ }
49
82
  if (pos[0] === "list") {
50
83
  const labs = runningLabs();
51
84
  if (!labs.length) console.log("No labs running.");
@@ -119,7 +152,7 @@ The device that opens it is ${name} in this lab.`);
119
152
  `
120
153
  That wait was held to ${FOREGROUND_CAP} seconds. Run it in the background (your app's own way of doing that) and add --bg for the full wait: in the foreground this command holds your turn open, and the person cannot say anything to you until it ends.`
121
154
  );
122
- process.exit(out.status < 300 || out.status === 409 || out.status === 410 ? 0 : 1);
155
+ process.exit(out.status < 300 || out.status === 409 || out.status === 410 || out.status === 423 ? 0 : 1);
123
156
  }
124
157
  if (cmd === "pin") {
125
158
  const selector = (ref || "").trim();
@@ -213,7 +246,7 @@ That wait was held to ${FOREGROUND_CAP} seconds. Run it in the background (your
213
246
  console.log(`${cmd === "reply" ? opts.resolve ? "Replied and resolved" : "Replied" : "Resolved"} on ${hit.page}.`);
214
247
  if (opts.wait) {
215
248
  const { seconds, capped } = waitSeconds(opts, process.stdout.isTTY === true);
216
- const out = await call("/_lab/wait", { timeout: seconds, pages: listenPages(opts) });
249
+ const out = await call("/_lab/wait", { timeout: seconds, pages: listenPages(opts, true) });
217
250
  console.log(WAIT_SAID[out.status] ?? out.text);
218
251
  if (capped && out.status === 204)
219
252
  console.log(`
package/dist/local.mjs CHANGED
@@ -6,12 +6,14 @@ import {
6
6
  upgrade
7
7
  } from "./chunk-Q4IDYYZO.mjs";
8
8
  import {
9
+ PARKED,
9
10
  REGISTRY,
10
11
  WRITE_SHORT,
11
12
  keyFor,
13
+ parkedLabs,
12
14
  parseArgs,
13
15
  runningLabs
14
- } from "./chunk-B5QP5NGM.mjs";
16
+ } from "./chunk-ZL5RPOIP.mjs";
15
17
  import {
16
18
  AGENTS,
17
19
  agentKind,
@@ -215,7 +217,7 @@ var VERSION2 = JSON.parse(fs3.readFileSync(path3.join(REPO, "package.json"), "ut
215
217
  var HELP = `labit ${VERSION2}: comment on local pages, your agent (Claude, Codex, Cursor\u2026) answers on the pins.
216
218
  Run it as npx @leonidstern/labit \u2026, or node local.mjs \u2026 from a clone.
217
219
 
218
- labit [--proxy [port]] [--port 4400] [--wifi] [--no-open] [folder]
220
+ labit [--name "topic"] [--proxy [port]] [--port 4400] [--wifi] [--no-open] [folder]
219
221
  Run it in your project. If the project has a dev server (Astro, Next, Vite\u2026) running, comments go on top
220
222
  of it: it finds the server run from this folder, even with other projects' servers running. Give
221
223
  --proxy <port> to pick one yourself. A folder of HTML files is served as it is at http://localhost:4400
@@ -223,6 +225,11 @@ Run it as npx @leonidstern/labit \u2026, or node local.mjs \u2026 from a clone.
223
225
  --wifi lets phones and laptops on the same wifi comment too (as guests). Each one needs a one-time link
224
226
  (labit invite), so finding the port isn't enough. The pages still travel in the clear over the wifi.
225
227
  A folder that a running lab already serves opens in that lab; --new starts a separate one anyway.
228
+ --name gives the lab its topic ("Lab navigation"), shown in labs & pages (\u2318K) instead of the folder; it's
229
+ kept in .lab/name, so later starts keep it.
230
+ labit publish <page.html | folder> [--name "topic"]
231
+ Show a page the way an Artifact is shown: it goes into your one pages lab (pagesFolder, ~/lab-pages), which
232
+ starts if it isn't running, and the page's link is printed. Publish it again to update it, at the same link.
226
233
  labit list
227
234
  Every lab running on this computer: its address, folder, pages and open comments. Check it before starting one.
228
235
  labit pages [--all]
@@ -273,8 +280,8 @@ var die = (msg) => {
273
280
  };
274
281
  if (unknownFlags.length) die(`Unknown option ${unknownFlags[0]}. See: ${CMD} --help`);
275
282
  var HERE = fs3.realpathSync(path3.resolve(opts.dir || "."));
276
- var COMMANDS = ["preview", "list", "pages", "wait", "reply", "resolve", "pin", "invite", "mcp", "settings"];
277
- var { loadSettings, changedShortcuts, savePersonal, saveFlag } = await import("./settings-T6OQSQH4.mjs");
283
+ var COMMANDS = ["publish", "preview", "list", "pages", "wait", "reply", "resolve", "pin", "invite", "mcp", "settings"];
284
+ var { loadSettings, changedShortcuts, savePersonal, saveFlag } = await import("./settings-OTB7HBCL.mjs");
278
285
  var { FLAGS, flagsOn } = await import("./flags-PGKWZHJC.mjs");
279
286
  var SETTINGS = loadSettings(HERE, {
280
287
  port: opts.port !== void 0 && opts.port !== true ? Number(opts.port) : void 0,
@@ -311,12 +318,12 @@ Yours: ${home(SETTINGS.files.personal)}${fs3.existsSync(SETTINGS.files.persona
311
318
  A flag or variable wins over labit.json, which wins over your file. See docs/settings.md.`);
312
319
  process.exit(SETTINGS.problems.length ? 1 : 0);
313
320
  }
314
- if (["preview", "list", "pages", "wait", "reply", "resolve", "pin", "invite"].includes(pos[0])) {
315
- const { runCommand } = await import("./commands-PNRTBJ3G.mjs");
321
+ if (["publish", "preview", "list", "pages", "wait", "reply", "resolve", "pin", "invite"].includes(pos[0])) {
322
+ const { runCommand } = await import("./commands-ITXC5TEQ.mjs");
316
323
  await runCommand({ pos, opts, HERE, CMD, ME, die });
317
324
  }
318
325
  if (pos[0] === "mcp") {
319
- const { runMcp } = await import("./mcp-OXSR36ME.mjs");
326
+ const { runMcp } = await import("./mcp-VC7FJ3PY.mjs");
320
327
  await runMcp({ HERE, ME, CMD, VERSION: VERSION2, WRITE_SHORT, AGENTS, agentKind, agentNow });
321
328
  }
322
329
  if (pos[0] && !fs3.existsSync(pos[0])) die(`No folder ${pos[0]}. Run ${CMD} in your project, or name a folder (see --help)`);
@@ -400,6 +407,16 @@ var ARCHIVE = path3.join(LAB, "archive");
400
407
  var SERVER = path3.join(LAB, "server.json");
401
408
  var SEEN = path3.join(LAB, "seen");
402
409
  fs3.mkdirSync(LAB, { recursive: true });
410
+ var NAME_FILE = path3.join(LAB, "name");
411
+ var SERVES = !COMMANDS.includes(pos[0]);
412
+ if (SERVES && typeof opts.name === "string" && opts.name.trim()) fs3.writeFileSync(NAME_FILE, opts.name.trim().slice(0, 80) + "\n");
413
+ var LAB_NAME = (() => {
414
+ try {
415
+ return fs3.readFileSync(NAME_FILE, "utf8").trim() || path3.basename(ROOT);
416
+ } catch {
417
+ return path3.basename(ROOT);
418
+ }
419
+ })();
403
420
  var alreadyHere = (running) => {
404
421
  if (process.env.PORT && !opts.port && Number(process.env.PORT) !== running.port)
405
422
  die(`[lab] already running for this folder at http://localhost:${running.port}. Stop that one (Ctrl+C) to open it here.`);
@@ -934,19 +951,25 @@ var rulesSent = /* @__PURE__ */ new Map();
934
951
  var toldAt = /* @__PURE__ */ new Map();
935
952
  var mode = "away";
936
953
  var awayTimer;
954
+ var BETWEEN_MS = Number(process.env.LAB_BETWEEN_MS ?? 45e3);
955
+ var betweenTimer;
956
+ var recent = [];
937
957
  var setMode = (m) => {
938
958
  mode = m;
939
959
  clearTimeout(awayTimer);
940
- if (m === "working") awayTimer = setTimeout(() => setMode("away"), 6e5);
960
+ clearTimeout(betweenTimer);
961
+ if (m === "away") recent = [];
962
+ if (m === "working") awayTimer = setTimeout(() => setMode(waiters.length ? "listening" : "away"), 6e5);
941
963
  saveServer();
942
964
  broadcast();
943
965
  };
944
966
  var PORT = Number(opts.port || process.env.PORT || 4400);
967
+ var STARTED = (/* @__PURE__ */ new Date()).toISOString();
945
968
  var registryFile = () => path3.join(REGISTRY, `${PORT}.json`);
946
969
  var register = () => {
947
970
  try {
948
971
  fs3.mkdirSync(REGISTRY, { recursive: true });
949
- writeAtomic(registryFile(), JSON.stringify({ port: PORT, pid: process.pid, root: ROOT, name: path3.basename(ROOT), proxy: PROXY?.origin || null, startedAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2));
972
+ writeAtomic(registryFile(), JSON.stringify({ port: PORT, pid: process.pid, root: ROOT, name: LAB_NAME, proxy: PROXY?.origin || null, startedAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2));
950
973
  } catch {
951
974
  }
952
975
  };
@@ -956,6 +979,38 @@ setInterval(() => {
956
979
  for (const c of clients) c.res.write("event: beat\ndata: 1\n\n");
957
980
  }, 15e3).unref();
958
981
  var READS = path3.join(LAB, "reads.json");
982
+ var OPENED = path3.join(LAB, "opened.json");
983
+ var opened = (() => {
984
+ try {
985
+ return new Map(Object.entries(JSON.parse(fs3.readFileSync(OPENED, "utf8"))));
986
+ } catch {
987
+ return /* @__PURE__ */ new Map();
988
+ }
989
+ })();
990
+ var openedTimer = null;
991
+ var markOpened = (page) => {
992
+ opened.set(page, (/* @__PURE__ */ new Date()).toISOString());
993
+ openedTimer ??= setTimeout(() => {
994
+ openedTimer = null;
995
+ try {
996
+ writeAtomic(OPENED, JSON.stringify(Object.fromEntries(opened)));
997
+ } catch {
998
+ }
999
+ }, 3e3);
1000
+ };
1001
+ var ARCHIVED = path3.join(LAB, "archived.json");
1002
+ var archivedPages = (() => {
1003
+ try {
1004
+ return new Map(Object.entries(JSON.parse(fs3.readFileSync(ARCHIVED, "utf8"))));
1005
+ } catch {
1006
+ return /* @__PURE__ */ new Map();
1007
+ }
1008
+ })();
1009
+ var archivePage = (page, on) => {
1010
+ if (on) archivedPages.set(page, (/* @__PURE__ */ new Date()).toISOString());
1011
+ else archivedPages.delete(page);
1012
+ writeAtomic(ARCHIVED, JSON.stringify(Object.fromEntries(archivedPages)));
1013
+ };
959
1014
  var bare = (o) => Object.assign(/* @__PURE__ */ Object.create(null), o);
960
1015
  var readSide = (file2, what) => {
961
1016
  let text;
@@ -1002,7 +1057,7 @@ var saveHanded = saver(HANDED2, () => {
1002
1057
  }, "hand-off marks");
1003
1058
  if (Object.keys(handoff).length) saveHanded();
1004
1059
  for (const [id, mark] of Object.entries(readSide(HANDED2, "handed.json") || {})) if (Array.isArray(mark)) handoff[id] = mark;
1005
- var state = (local) => JSON.stringify({ ...version, reads: readsRev, mode, session: session && (local ? session : { name: session.name, agent: session.agent, model: session.model }) });
1060
+ var state = (local) => JSON.stringify({ ...version, reads: readsRev, mode, heard: heard(), session: session && (local ? session : { name: session.name, agent: session.agent, model: session.model }) });
1006
1061
  var broadcast = () => {
1007
1062
  for (const c of clients) c.res.write(`data: ${state(c.local)}
1008
1063
 
@@ -1070,6 +1125,15 @@ var claimed = () => {
1070
1125
  return new Set([...claims].filter(([, at]) => now - at < CLAIM_MS).map(([p]) => p));
1071
1126
  };
1072
1127
  var scopeOf = (w) => w.pages ? pages().filter((p) => w.pages.includes(p)) : pages().filter((p) => !claimed().has(p));
1128
+ var heard = () => {
1129
+ const open = [...waiters, ...recent];
1130
+ const named = new Set(open.flatMap((w) => w.pages || []));
1131
+ const all = open.some((w) => !w.pages);
1132
+ return { all, pages: [...named], except: all ? [...claimed()].filter((p) => !named.has(p)) : [] };
1133
+ };
1134
+ var remember = (w) => {
1135
+ recent = [...recent.filter((r) => r.key !== w.key), { key: w.key, pages: w.pages }];
1136
+ };
1073
1137
  var CLOSE_GRACE = Number(process.env.LAB_CLOSE_GRACE || 3600) * 1e3;
1074
1138
  var TAB_TTL = Number(process.env.LAB_TAB_TTL || 90) * 1e3;
1075
1139
  var tabs = /* @__PURE__ */ new Map();
@@ -1184,7 +1248,7 @@ function deliver(res, got, who = "") {
1184
1248
  saveHanded();
1185
1249
  for (const page of new Set(got.handed.map(([page2]) => page2))) persist(page).catch(() => {
1186
1250
  });
1187
- setMode("working");
1251
+ setMode(waiters.length ? "listening" : "working");
1188
1252
  }
1189
1253
  var SETTLE_MS = Number(process.env.LAB_SETTLE_MS ?? 2e3);
1190
1254
  var REMIND_MS = Number(process.env.LAB_REMIND_MS ?? 18e4);
@@ -1202,6 +1266,7 @@ async function wakeNow() {
1202
1266
  waiters = waiters.filter((x) => x !== w);
1203
1267
  waitEnded = Date.now();
1204
1268
  clearTimeout(w.timer);
1269
+ remember(w);
1205
1270
  deliver(w.res, got, w.who);
1206
1271
  }
1207
1272
  }
@@ -1222,8 +1287,11 @@ var flagsAttr = () => {
1222
1287
  return ` data-flags='${json.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/'/g, "&#39;")}'`;
1223
1288
  };
1224
1289
  var LABIT_ATTR = ` data-labit="${`labit ${VERSION2}${process.env.LABIT_EDGE ? ` \xB7 edge: ${process.env.LABIT_EDGE}` : ""}`.replace(/[<>&'"]/g, "")}"`;
1225
- var widget = (page, admin, me = "") => `<script src="/_lab/comments.js" data-live="/_lab/live" data-on="1" data-page="${page}" data-version="${version.files}" data-lab="${version.lab}" data-widget="${version.widget}"${me ? ` data-me="${me.replace(/[<>&'"]/g, "")}"` : ""}${KEYS_ATTR}${flagsAttr()}${LABIT_ATTR}${admin ? ` data-admin="${TOKEN}"` : ""} defer></script>
1290
+ var widget = (page, admin, me = "") => {
1291
+ markOpened(page);
1292
+ return `<script src="/_lab/comments.js" data-live="/_lab/live" data-on="1" data-page="${page}" data-version="${version.files}" data-lab="${version.lab}" data-widget="${version.widget}"${me ? ` data-me="${me.replace(/[<>&'"]/g, "")}"` : ""}${KEYS_ATTR}${flagsAttr()}${LABIT_ATTR} data-lab-name="${LAB_NAME.replace(/[<>&'"]/g, "")}"${admin ? ` data-admin="${TOKEN}"` : ""} defer></script>
1226
1293
  `;
1294
+ };
1227
1295
  var inject = (html, tag) => {
1228
1296
  html = html.replace(/<script\b[^>]*\bsrc=["'][^"']*\/_lab\/comments\.js["'][^>]*>\s*<\/script>\s*/gi, "");
1229
1297
  const lower = html.toLowerCase();
@@ -1307,12 +1375,81 @@ var listing = (res, dir, urlPath) => {
1307
1375
  res.end(
1308
1376
  labPage(
1309
1377
  `labit \xB7 ${esc(path3.basename(dir))}`,
1310
- `<header><h1>${esc(path3.basename(dir))}</h1><p class="lede">${pages2.length} page${pages2.length === 1 ? "" : "s"}${open ? ` \xB7 ${open} open comment${open === 1 ? "" : "s"}` : ""} \xB7 newest first</p></header>` + (many ? `<input class="lab-filter" type="search" placeholder="Filter pages" aria-label="Filter pages" autocomplete="off">` : "") + `<ul class="lab-box lab-rows lab-pages">${li || '<li class="lab-muted" style="padding:8px 10px">No HTML pages here. Running a dev server? Start it, then run labit again.</li>'}</ul><p class="lab-muted lab-hint">On a page, press <kbd>${SET.shortcuts.toggle}</kbd> to show comments, or hold <kbd>\u2325</kbd> and click.</p>` + (many ? `<script>const f=document.querySelector('.lab-filter'),r=[...document.querySelectorAll('.lab-pages li')];f.addEventListener('input',()=>{const q=f.value.trim().toLowerCase();for(const l of r)l.hidden=!!q&&!l.textContent.toLowerCase().includes(q)});addEventListener('keydown',e=>{if(e.key==='/'&&document.activeElement!==f){e.preventDefault();f.focus()}})</script>` : "")
1378
+ `<header><h1>${esc(path3.basename(dir))}</h1><p class="lede">${pages2.length} page${pages2.length === 1 ? "" : "s"}${open ? ` \xB7 ${open} open comment${open === 1 ? "" : "s"}` : ""} \xB7 newest first</p></header>` + (many ? `<input class="lab-filter" type="search" placeholder="Filter pages" aria-label="Filter pages" autocomplete="off">` : "") + `<ul class="lab-box lab-rows lab-pages">${li || '<li class="lab-muted" style="padding:8px 10px">No HTML pages here. Running a dev server? Start it, then run labit again.</li>'}</ul><p class="lab-muted lab-hint lab-keys">On a page, press <kbd>${SET.shortcuts.toggle}</kbd> to show comments, or hold <kbd>\u2325</kbd> and click. <kbd>\u2318K</kbd> goes to another lab.</p><p class="lab-muted lab-hint lab-touch">On a page, hold a spot to comment. \u22EF then "labs &amp; pages" goes to another lab.</p><style>.lab-touch{display:none}@media (pointer:coarse){.lab-keys{display:none}.lab-touch{display:block}}</style>` + (many ? `<script>const f=document.querySelector('.lab-filter'),r=[...document.querySelectorAll('.lab-pages li')];f.addEventListener('input',()=>{const q=f.value.trim().toLowerCase();for(const l of r)l.hidden=!!q&&!l.textContent.toLowerCase().includes(q)});addEventListener('keydown',e=>{if(e.key==='/'&&document.activeElement!==f){e.preventDefault();f.focus()}})</script>` : "")
1311
1379
  )
1312
1380
  );
1313
1381
  };
1314
1382
  var sent = async (req) => JSON.parse(await new Response(req).text() || "{}");
1315
1383
  var answer = (res, data) => res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify(data));
1384
+ var oneEach = (names) => names.filter((n, i) => names.findIndex((m) => m.toLowerCase() === n.toLowerCase()) === i);
1385
+ var created = () => {
1386
+ try {
1387
+ const t = fs3.statSync(LAB).birthtimeMs;
1388
+ if (t > 0) return new Date(t).toISOString();
1389
+ } catch {
1390
+ }
1391
+ const first = pages().flatMap((k) => commentsOf(k).map((c) => c.createdAt)).sort()[0];
1392
+ return first || null;
1393
+ };
1394
+ var labInfo = () => {
1395
+ const tally = (key) => {
1396
+ const all = commentsOf(key);
1397
+ const roots = all.filter((c) => !c.parent);
1398
+ const last = all.flatMap((c) => [c.createdAt, c.resolvedAt]).filter(Boolean).sort().pop() || null;
1399
+ const replies = all.filter((c) => c.parent);
1400
+ return {
1401
+ open: roots.filter((c) => !c.resolved).length,
1402
+ done: roots.filter((c) => c.resolved).length,
1403
+ last,
1404
+ first: roots[0]?.createdAt || null,
1405
+ replies: replies.length,
1406
+ agent: replies.filter((c) => c.session).length,
1407
+ people: oneEach(all.filter((c) => !c.session && c.name).map((c) => String(c.name).trim())).slice(0, 8)
1408
+ };
1409
+ };
1410
+ const edited = (file2) => {
1411
+ try {
1412
+ return file2 ? new Date(fs3.statSync(path3.join(ROOT, file2)).mtimeMs).toISOString() : null;
1413
+ } catch {
1414
+ return null;
1415
+ }
1416
+ };
1417
+ const list = (PROXY ? [] : pagesUnder(ROOT)).map((rel) => ({ url: origin + urlOf(rel), title: titleOf(path3.join(ROOT, rel)), file: rel, key: keyFor(rel) }));
1418
+ if (PROXY) list.push({ url: origin + "/", title: "", file: "", key: "/" });
1419
+ if (PROXY) {
1420
+ for (const key of pages()) if (!list.some((p) => p.key === key)) list.push({ url: origin + key, title: "", file: fileFor(key) || "", key });
1421
+ }
1422
+ return {
1423
+ name: LAB_NAME,
1424
+ root: ROOT,
1425
+ port: PORT,
1426
+ wifi: WIFI,
1427
+ proxy: PROXY?.origin || null,
1428
+ mode: session ? mode : "away",
1429
+ listening: session?.name || null,
1430
+ heard: heard(),
1431
+ started: STARTED,
1432
+ created: created(),
1433
+ pages: list.map(({ key, ...p }) => ({ ...p, path: key, ...tally(key), edited: edited(p.file), opened: opened.get(key) || null, archived: archivedPages.get(key) || null }))
1434
+ };
1435
+ };
1436
+ var keyOk = (req) => {
1437
+ const got = Buffer.from(String(req.headers["x-lab-admin"] || ""));
1438
+ const key = Buffer.from(TOKEN);
1439
+ return got.length === key.length && timingSafeEqual(got, key);
1440
+ };
1441
+ var stopListening = () => {
1442
+ const all = waiters;
1443
+ waiters = [];
1444
+ waitEnded = Date.now();
1445
+ for (const w of all) {
1446
+ clearTimeout(w.timer);
1447
+ w.res.writeHead(423).end("stopped from the page");
1448
+ }
1449
+ recent = [];
1450
+ console.log("[lab] listening stopped from the page");
1451
+ setMode("away");
1452
+ };
1316
1453
  var handler = async (req, res) => {
1317
1454
  try {
1318
1455
  const url = new URL(req.url, origin);
@@ -1428,13 +1565,21 @@ var handler = async (req, res) => {
1428
1565
  const w = { res, pages: want, key, who: whoOf(session) };
1429
1566
  claim(want);
1430
1567
  const got = await unseen(scopeOf(w), w.who);
1431
- if (got?.text) return deliver(res, got, w.who);
1568
+ recent = recent.filter((r) => r.key !== key);
1569
+ if (got?.text) {
1570
+ remember(w);
1571
+ return deliver(res, got, w.who);
1572
+ }
1432
1573
  w.timer = setTimeout(() => {
1433
1574
  if (!waiters.includes(w)) return;
1434
1575
  waiters = waiters.filter((x) => x !== w);
1435
1576
  waitEnded = Date.now();
1436
1577
  res.writeHead(204).end();
1437
- if (!waiters.length) setMode("away");
1578
+ if (waiters.length) return broadcast();
1579
+ remember(w);
1580
+ clearTimeout(betweenTimer);
1581
+ betweenTimer = setTimeout(() => !waiters.length && mode === "listening" && setMode("away"), BETWEEN_MS);
1582
+ broadcast();
1438
1583
  }, Math.min(Number(timeout) || 1500, 7e3) * 1e3);
1439
1584
  if (!openTabs() && Date.now() - waitEnded > 12e4) closedSince = Date.now();
1440
1585
  waiters.push(w);
@@ -1447,24 +1592,117 @@ var handler = async (req, res) => {
1447
1592
  waitEnded = Date.now();
1448
1593
  clearTimeout(w.timer);
1449
1594
  if (!waiters.length) setMode("away");
1595
+ else broadcast();
1450
1596
  });
1451
1597
  return;
1452
1598
  }
1599
+ if (pathname === "/_lab/labs" && req.method === "GET") {
1600
+ const here = isLoopback(req);
1601
+ const mine = { ...labInfo(), here: true };
1602
+ const others = await Promise.all(
1603
+ runningLabs().filter((l) => l.port !== PORT).map(async (l) => {
1604
+ try {
1605
+ const r = await fetch(`http://localhost:${l.port}/_lab/pages`, { signal: AbortSignal.timeout(1500) });
1606
+ return { ...await r.json(), port: l.port, here: false };
1607
+ } catch {
1608
+ return { name: l.name, root: l.root, port: l.port, here: false, pages: [], mode: "away", unreachable: true };
1609
+ }
1610
+ })
1611
+ );
1612
+ others.sort((a, b) => a.name.localeCompare(b.name));
1613
+ if (here) return answer(res, { labs: [mine, ...others], parked: parkedLabs().filter((p) => !runningLabs().some((l) => l.port === p.port)), guest: false });
1614
+ const forGuest = (lab2, hop) => ({
1615
+ name: lab2.name,
1616
+ port: lab2.port,
1617
+ here: lab2.here,
1618
+ mode: lab2.mode,
1619
+ listening: lab2.listening,
1620
+ created: lab2.created,
1621
+ started: lab2.started,
1622
+ pages: lab2.pages.map(({ url: url2, root: _root, file: _file, ...p }) => ({ ...p, url: hop ? `/_lab/hop?port=${lab2.port}&to=${encodeURIComponent(p.path)}` : new URL(url2).pathname }))
1623
+ });
1624
+ const local = others.filter((l) => !l.wifi || l.unreachable).map((l) => ({ name: l.name, port: l.port }));
1625
+ const self = wifiAddrs().includes(String(req.socket.remoteAddress || "").replace(/^::ffff:/, "")) ? `http://localhost:${PORT}${url.searchParams.get("page") || "/"}` : null;
1626
+ return answer(res, { labs: [forGuest(mine, false), ...others.filter((l) => l.wifi && !l.unreachable).map((l) => forGuest(l, true))], parked: [], guest: true, local, self });
1627
+ }
1628
+ if (pathname === "/_lab/hop" && req.method === "GET") {
1629
+ const n = Number(url.searchParams.get("port"));
1630
+ const lab2 = runningLabs().find((l) => l.port === n && n !== PORT);
1631
+ if (!lab2) return res.writeHead(404, { "content-type": "text/plain" }).end("no such lab running");
1632
+ try {
1633
+ const srv = JSON.parse(fs3.readFileSync(path3.join(lab2.root, ".lab/server.json"), "utf8"));
1634
+ const r = await fetch(`http://localhost:${n}/_lab/invite`, {
1635
+ method: "POST",
1636
+ signal: AbortSignal.timeout(3e3),
1637
+ headers: { "content-type": "application/json", "x-lab-admin": srv.agent || srv.token, "x-lab-agent": "1", origin: `http://localhost:${n}` },
1638
+ body: JSON.stringify({ name: nameFor(req) || "", page: url.searchParams.get("to") || "/" })
1639
+ });
1640
+ if (!r.ok) return res.writeHead(r.status, { "content-type": "text/plain" }).end(await r.text());
1641
+ const { links } = await r.json();
1642
+ const host = String(req.headers.host || "").replace(/:\d+$/, "");
1643
+ const go = links.find((l) => new URL(l).hostname === host) || links[0];
1644
+ return res.writeHead(302, { location: go, "cache-control": "no-store" }).end();
1645
+ } catch {
1646
+ return res.writeHead(502, { "content-type": "text/plain" }).end("that lab did not answer");
1647
+ }
1648
+ }
1649
+ if (pathname === "/_lab/labs" && req.method === "POST") {
1650
+ if (!isLoopback(req) || !keyOk(req)) return res.writeHead(403).end("forbidden");
1651
+ const { action, port, page } = await sent(req);
1652
+ const n = Number(port);
1653
+ if (action === "archive-page" || action === "unarchive-page") {
1654
+ if (typeof page !== "string" || !page.startsWith("/")) return res.writeHead(400).end("page: /path");
1655
+ if (n === PORT) {
1656
+ archivePage(page, action === "archive-page");
1657
+ return answer(res, { ok: true });
1658
+ }
1659
+ }
1660
+ if (action === "start") {
1661
+ const p = parkedLabs().find((x) => x.port === n);
1662
+ if (!p) return res.writeHead(404).end("not parked");
1663
+ if (runningLabs().some((l) => l.port === n)) return res.writeHead(409).end("already running");
1664
+ const env = { ...process.env, ...p.edge ? { LABIT_EDGE: p.edge } : {} };
1665
+ spawn(process.execPath, [...p.execArgv, ...p.argv.filter((a) => a !== "--no-open"), "--no-open"], { cwd: p.root, env, detached: true, stdio: "ignore" }).unref();
1666
+ fs3.rmSync(path3.join(PARKED, `${n}.json`), { force: true });
1667
+ console.log(`[lab] started ${p.name} again on ${n}`);
1668
+ return answer(res, { ok: true });
1669
+ }
1670
+ const parkedFile = path3.join(PARKED, `${n}.json`);
1671
+ if ((action === "archive" || action === "unarchive") && !runningLabs().some((l) => l.port === n)) {
1672
+ const p = parkedLabs().find((x) => x.port === n);
1673
+ if (!p) return res.writeHead(404).end("not parked");
1674
+ writeAtomic(parkedFile, JSON.stringify({ ...p, archived: action === "archive", at: (/* @__PURE__ */ new Date()).toISOString() }, null, 2));
1675
+ return answer(res, { ok: true });
1676
+ }
1677
+ if (action === "unarchive") return res.writeHead(409).end("running, not archived");
1678
+ if (!["stop", "park", "archive", "archive-page", "unarchive-page"].includes(action)) return res.writeHead(400).end("action: stop, park, archive, unarchive, start, archive-page or unarchive-page");
1679
+ if (n !== PORT) {
1680
+ const lab2 = runningLabs().find((l) => l.port === n);
1681
+ if (!lab2) return res.writeHead(404).end("no lab on that port");
1682
+ try {
1683
+ const key = JSON.parse(fs3.readFileSync(path3.join(lab2.root, ".lab/server.json"), "utf8")).token;
1684
+ const r = await fetch(`http://localhost:${n}/_lab/labs`, { method: "POST", headers: { "content-type": "application/json", "x-lab-admin": key }, body: JSON.stringify({ action, port: n, page }), signal: AbortSignal.timeout(3e3) });
1685
+ return res.writeHead(r.status, { "content-type": "application/json" }).end(await r.text());
1686
+ } catch {
1687
+ return res.writeHead(502).end("that lab did not answer");
1688
+ }
1689
+ }
1690
+ stopListening();
1691
+ if (action === "stop") return answer(res, { ok: true });
1692
+ try {
1693
+ fs3.mkdirSync(PARKED, { recursive: true });
1694
+ const edge = process.env.LABIT_EDGE;
1695
+ writeAtomic(path3.join(PARKED, `${PORT}.json`), JSON.stringify({ port: PORT, root: ROOT, name: LAB_NAME, argv: process.argv.slice(1), execArgv: process.execArgv, ...edge ? { edge } : {}, ...action === "archive" ? { archived: true } : {}, at: (/* @__PURE__ */ new Date()).toISOString() }, null, 2));
1696
+ } catch {
1697
+ }
1698
+ console.log("[lab] parked from the page: start it again from the switcher (\u2318K) in another lab, or run labit here");
1699
+ answer(res, { ok: true });
1700
+ setTimeout(bye, 200);
1701
+ return;
1702
+ }
1453
1703
  if (pathname === "/_lab/pages") {
1454
1704
  if (!isLoopback(req)) return res.writeHead(403, { "content-type": "text/plain" }).end("forbidden");
1455
- const openOn = (key) => commentsOf(key).filter((c) => !c.parent && !c.resolved).length;
1456
- const list = (PROXY ? [] : pagesUnder(ROOT)).map((rel) => ({ url: origin + urlOf(rel), title: titleOf(path3.join(ROOT, rel)), file: rel, key: keyFor(rel) }));
1457
- if (PROXY) list.push({ url: origin + "/", title: "", file: "", key: "/" });
1458
- for (const key of pages()) if (!list.some((p) => p.key === key)) list.push({ url: origin + key, title: "", file: fileFor(key) || "", key });
1459
- return answer(res, {
1460
- name: path3.basename(ROOT),
1461
- root: ROOT,
1462
- port: PORT,
1463
- proxy: PROXY?.origin || null,
1464
- mode,
1465
- listening: session?.name || null,
1466
- pages: list.map(({ key, ...p }) => ({ ...p, path: key, open: openOn(key) }))
1467
- });
1705
+ return answer(res, labInfo());
1468
1706
  }
1469
1707
  if (pathname.startsWith("/_lab/agent/")) {
1470
1708
  res.writeHead(200, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" });
@@ -1602,8 +1840,15 @@ server.on("error", (e) => {
1602
1840
  /** @type {NodeJS.ErrnoException} */
1603
1841
  e.code !== "EADDRINUSE" || fixed || PORT >= Number(opts.port || 4400) + 20
1604
1842
  ) die(`[lab] could not start: ${e.message}`);
1605
- server.listen(++PORT, WIFI ? void 0 : "127.0.0.1");
1843
+ PORT = skipLabs(PORT + 1);
1844
+ server.listen(PORT, WIFI ? void 0 : "127.0.0.1");
1606
1845
  });
1846
+ function skipLabs(port) {
1847
+ if (!opts.port && process.env.PORT) return port;
1848
+ const held = new Set(runningLabs().filter((l) => l.pid !== process.pid).map((l) => l.port));
1849
+ while (held.has(port)) port++;
1850
+ return port;
1851
+ }
1607
1852
  async function newerVersion() {
1608
1853
  if (process.env.LABIT_NO_UPDATE_CHECK || process.env.CI) return null;
1609
1854
  const file2 = path3.join(path3.dirname(REGISTRY), "latest.json");
@@ -1658,4 +1903,5 @@ var bye = () => {
1658
1903
  process.on("SIGINT", bye);
1659
1904
  process.on("SIGTERM", bye);
1660
1905
  process.on("SIGHUP", bye);
1906
+ PORT = skipLabs(PORT);
1661
1907
  server.listen(PORT, WIFI ? void 0 : "127.0.0.1");
@@ -2,7 +2,7 @@ import {
2
2
  WAIT_SAID,
3
3
  findLab,
4
4
  labCall
5
- } from "./chunk-QTMKKULT.mjs";
5
+ } from "./chunk-FVO4473A.mjs";
6
6
  import {
7
7
  mySession
8
8
  } from "./chunk-X4RYDWNI.mjs";
@@ -21,6 +21,9 @@ var SPEC = {
21
21
  updateCheck: { type: "boolean", def: true },
22
22
  name: { type: "string", def: "", only: "personal" },
23
23
  model: { type: "string", def: "", only: "personal" },
24
+ // The one lab for pages that belong to no project (tries, demos, options): agents add pages there, a folder per
25
+ // topic, instead of starting a lab of their own (Leo 18 Nov: "def reuse it, why we have so much").
26
+ pagesFolder: { type: "string", def: "~/lab-pages", only: "personal" },
24
27
  shortcuts: { type: "shortcuts", def: SHORTCUTS },
25
28
  // What is being tried here (lib/flags.ts). Off unless a file or the ⋯ menu turns one on.
26
29
  flags: { type: "flags", def: flagDefaults() }