viewable-one 0.12.2 → 0.12.4

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 (61) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +2 -2
  3. package/SPAWN.md +107 -53
  4. package/glytch.mjs +49 -12
  5. package/lib/acp.mjs +110 -148
  6. package/lib/admission.mjs +25 -5
  7. package/lib/agents.mjs +59 -16
  8. package/lib/answerTag.mjs +47 -0
  9. package/lib/atomic.mjs +1 -16
  10. package/lib/auth.mjs +25 -9
  11. package/lib/boardside.mjs +28 -12
  12. package/lib/child.mjs +89 -116
  13. package/lib/claudeModels.mjs +168 -0
  14. package/lib/codex-rpc.mjs +2 -2
  15. package/lib/codex.mjs +43 -63
  16. package/lib/codexApps.mjs +5 -3
  17. package/lib/codexToolInputs.mjs +98 -22
  18. package/lib/codingChecks.mjs +8 -4
  19. package/lib/conversationRules.mjs +46 -6
  20. package/lib/detect.mjs +14 -23
  21. package/lib/devserver.mjs +6 -6
  22. package/lib/doctor.mjs +4 -2
  23. package/lib/folderReads.mjs +96 -0
  24. package/lib/followUps.mjs +170 -0
  25. package/lib/hosted.mjs +13 -4
  26. package/lib/init-connect.mjs +29 -10
  27. package/lib/lateResume.mjs +135 -0
  28. package/lib/logindaemon.mjs +113 -33
  29. package/lib/mcpjson.mjs +35 -2
  30. package/lib/multiwatch.mjs +80 -45
  31. package/lib/pagePictures.mjs +14 -11
  32. package/lib/paths.mjs +0 -1
  33. package/lib/permissionAsk.mjs +341 -58
  34. package/lib/procs.mjs +73 -2
  35. package/lib/refusal.mjs +0 -2
  36. package/lib/restartPass.mjs +52 -11
  37. package/lib/rowsAnswers.mjs +18 -34
  38. package/lib/rowsEvents.mjs +20 -2
  39. package/lib/runner-health.mjs +26 -2
  40. package/lib/runner.mjs +106 -1363
  41. package/lib/runnerAdmission.mjs +33 -12
  42. package/lib/runnerApi.mjs +28 -12
  43. package/lib/runnerBeat.mjs +398 -0
  44. package/lib/runnerCompletion.mjs +5 -2
  45. package/lib/runnerExecute.mjs +227 -0
  46. package/lib/runnerGates.mjs +338 -0
  47. package/lib/runnerLaunch.mjs +351 -0
  48. package/lib/runnerLease.mjs +31 -9
  49. package/lib/runnerOps.mjs +226 -0
  50. package/lib/runnerPace.mjs +10 -6
  51. package/lib/runnerRecovery.mjs +457 -0
  52. package/lib/runnerRegister.mjs +29 -8
  53. package/lib/runnerSettlement.mjs +29 -9
  54. package/lib/selfUninstall.mjs +239 -0
  55. package/lib/spawn.mjs +0 -5
  56. package/lib/sync.mjs +26 -14
  57. package/lib/update.mjs +184 -0
  58. package/lib/viewableFolder.mjs +8 -2
  59. package/lib/worktree.mjs +66 -13
  60. package/lib/writePolicy.mjs +90 -10
  61. package/package.json +1 -1
@@ -38,9 +38,8 @@
38
38
  // gets its sync and its watcher without anything being restarted.
39
39
 
40
40
  import { makeRunnerHealth } from "./runner-health.mjs";
41
- import { watch as fsWatch } from "node:fs";
41
+ import { unwatchFile, watchFile } from "node:fs";
42
42
  import { stat } from "node:fs/promises";
43
- import { basename, dirname } from "node:path";
44
43
  import { makeAgentProbe } from "./detect.mjs";
45
44
  import { platformMark } from "./platform.mjs";
46
45
  import { ensureViewableFolder } from "./viewableFolder.mjs";
@@ -51,16 +50,21 @@ import { makeHeartbeatHub, makeRegistrar, REGISTER_REFRESH_MS } from "./runnerPa
51
50
  import { beatBaseMs, makeRunnerRealtime } from "./runnerRealtime.mjs";
52
51
  import { sweepAll } from "./sweep.mjs";
53
52
  import { syncFolder } from "./sync.mjs";
54
- import { makeUpdateChecker, packageVersion } from "./update.mjs";
53
+ import { makeSelfUpdate, makeUpdateChecker, packageVersion } from "./update.mjs";
54
+ import { liveRuns } from "./restartPass.mjs";
55
+ import { activeRecoveryRunIds } from "./runnerRecovery.mjs";
56
+ import * as runnerApiModule from "./runnerApi.mjs";
55
57
 
56
58
  export const SWEEP_INTERVAL_MS = 86_400_000;
57
- /** How often the registry is re-read when fs.watch tells us nothing. The
58
- * floor, not the mechanism: fs.watch answers in milliseconds when it fires at
59
- * all, and this is what catches the cases where it does not - a network home
60
- * directory, an editor that swaps the file in a way the watch misses, a
61
- * platform that drops the event. A minute is invisible to a person typing
62
- * `viewable init` and then switching to the app. */
59
+ /** How often the registry is re-read when the stat poll below tells us
60
+ * nothing. The floor, not the mechanism: the stat poll answers within
61
+ * REGISTRY_STAT_MS, and this is what catches the cases where it does not - a
62
+ * network home directory, a file system whose stat times do not move. A
63
+ * minute is invisible to a person typing `viewable init` and then switching
64
+ * to the app. */
63
65
  export const REGISTRY_POLL_MS = 60_000;
66
+ /** How often the registry file is stat'ed for a change (fs.watchFile). */
67
+ export const REGISTRY_STAT_MS = 1_000;
64
68
 
65
69
  const isDir = async (path) => {
66
70
  try {
@@ -73,11 +77,13 @@ const isDir = async (path) => {
73
77
  /** Watch every registered folder until `signal` aborts.
74
78
  *
75
79
  * Returns {watched, missing} after signal-driven shutdown and after every
76
- * folder's watch has ended. An empty registry still waits for new folders. */
80
+ * folder's watch has ended. An empty registry still waits for new folders.
81
+ * `restart: true` means the board's Update installed a new version and the
82
+ * caller should exit so the service manager starts it (#4949). */
77
83
  export async function watchRegistered({
78
84
  env = process.env,
79
85
  settings,
80
- signal,
86
+ signal: outerSignal,
81
87
  log = () => {},
82
88
  folders,
83
89
  sweep = sweepAll,
@@ -104,7 +110,14 @@ export async function watchRegistered({
104
110
  // THE PUSH CHANNEL (#813), one per process. Injected for the tests, which
105
111
  // pass a fake, or `() => null` for none (every 10 s, as before).
106
112
  makeRealtime = makeRunnerRealtime,
113
+ // THE BOARD'S UPDATE BUTTON (#4949). Injected for the tests.
114
+ makeSelfUpdater = makeSelfUpdate,
107
115
  } = {}) {
116
+ // An installed update stops every watcher the same way Ctrl-C does: each
117
+ // drains the runs it started (there are none by then) before it ends.
118
+ const restartStop = new AbortController();
119
+ const signal = outerSignal ? AbortSignal.any([outerSignal, restartStop.signal]) : restartStop.signal;
120
+ let restarting = false;
108
121
  // An injected list is the whole list: a caller that says which folders to
109
122
  // watch is not asking the registry anything, so the live re-read below
110
123
  // stands down for it. Nothing in the package passes this; the tests do.
@@ -185,7 +198,43 @@ export async function watchRegistered({
185
198
  // starting a detached dev server - the browser may be on another box
186
199
  // entirely (lib/platform.mjs says why it is not `navigator`).
187
200
  const health = makeRunnerHealth({ env, version: updater.state?.().version ?? packageVersion() });
188
- const markExtra = () => ({ ...platform, ...updater.mark(), ...probe.mark(), ...health.mark() });
201
+ // Every folder a beat has named, so the update can see each folder's
202
+ // recovered runs whose owner is gone but whose child processes are not.
203
+ const projects = new Map();
204
+ const activeRuns = async () => {
205
+ let count = liveRuns.size;
206
+ for (const project of projects.values()) {
207
+ for (const id of await activeRecoveryRunIds(project, settings ?? {}, { log })) if (!liveRuns.has(id)) count += 1;
208
+ }
209
+ return count;
210
+ };
211
+ const updateApi = settings?.runnerApi ?? runnerApiModule;
212
+ let askBeat = () => {};
213
+ const selfUpdater = makeSelfUpdater({
214
+ version: updater.state?.().version ?? packageVersion(),
215
+ activeRuns,
216
+ take: async (op) => {
217
+ const taken = await updateApi.updateTake({ projectId: op.project_id, requestId: op.id }, { env: settings?.env, fetchImpl: settings?.fetchImpl });
218
+ if (!taken?.ok) throw new Error(taken?.error ?? "Could not take the update request.");
219
+ return taken.taken === true;
220
+ },
221
+ onChange: () => askBeat(),
222
+ restart: async () => {
223
+ restarting = true;
224
+ restartStop.abort();
225
+ },
226
+ log,
227
+ });
228
+ const selfUpdate = {
229
+ request: (op) => selfUpdater.request(op),
230
+ seen: (project, ops) => {
231
+ if (project?.id) projects.set(project.id, project);
232
+ selfUpdater.seen(project, ops);
233
+ },
234
+ holdsRuns: () => selfUpdater.holdsRuns(),
235
+ claimStarted: () => selfUpdater.claimStarted(),
236
+ };
237
+ const markExtra = () => ({ ...platform, ...updater.mark(), ...probe.mark(), ...health.mark(), ...selfUpdater.mark() });
189
238
 
190
239
  // ONE REGISTER AND ONE HEARTBEAT FOR THE WHOLE PROCESS (ticket e8,
191
240
  // 2026-10-03; #616, 2026-10-16). Every folder's beat registers the whole
@@ -219,7 +268,7 @@ export async function watchRegistered({
219
268
  // sharing one heartbeat (one `at` for all of them).
220
269
  const beatAsks = new Set();
221
270
  const beatRequests = { subscribe: (fn) => { beatAsks.add(fn); return () => beatAsks.delete(fn); } };
222
- const askBeat = () => {
271
+ askBeat = () => {
223
272
  const at = Date.now();
224
273
  for (const fn of [...beatAsks]) fn(at);
225
274
  };
@@ -264,7 +313,7 @@ export async function watchRegistered({
264
313
  const entry = { controller, done: false, leaving: false };
265
314
  let started;
266
315
  try {
267
- started = watchOne(folder, { ...settings, runnerId, realtime, onHealthy: (path) => health.beat(path), markExtra, registrar, heartbeats, beatRequests, refreshAgents: () => probe.once() }, {
316
+ started = watchOne(folder, { ...settings, runnerId, realtime, onHealthy: (path) => health.beat(path), markExtra, registrar, heartbeats, beatRequests, refreshAgents: () => probe.once(), selfUpdate }, {
268
317
  signal: controller.signal,
269
318
  log: (line) => log(`[${folder}] ${line}`),
270
319
  });
@@ -366,33 +415,25 @@ export async function watchRegistered({
366
415
  }
367
416
  };
368
417
 
369
- // BOTH THE FILE AND ITS DIRECTORY. `folders.json` is written by
370
- // writeFileAtomic, which renames a temp file over it, so the inode a watch
371
- // on the file is holding is not the one the next read opens - the file
372
- // watch sees the first write and then nothing. The directory watch sees the
373
- // rename. Neither is trusted: setInterval below is the floor, and a
374
- // platform where fs.watch does nothing at all still picks a new folder up
375
- // within registryPollMs.
418
+ // A STAT POLL ON THE FILE, NOT fs.watch (#4726). fs.watchFile stats the
419
+ // path, so it sees writeFileAtomic's rename, an edit in place and a file
420
+ // that does not exist yet. A folder fs.watch on macOS starts FSEvents, and
421
+ // closing it waits on fseventsd: a stuck one froze Ctrl-C on `runner watch`
422
+ // forever. setInterval below is still the floor.
376
423
  const regPath = registryPath(env);
377
- const regName = basename(regPath);
378
- const fsWatchers = [];
379
- const attach = (target, onlyRegistry) => {
424
+ const onRegistryStat = (now, before) => {
425
+ if (now.mtimeMs === before.mtimeMs && now.ino === before.ino && now.size === before.size) return;
426
+ void refresh();
427
+ };
428
+ let statWatching = false;
429
+ if (!pinned) {
380
430
  try {
381
- const w = fsWatch(target, (_event, filename) => {
382
- if (onlyRegistry && filename && basename(String(filename)) !== regName) return;
383
- void refresh();
384
- });
385
- w.on("error", () => {}); // a dead watch is not an exit; the poll covers it
386
- w.unref?.();
387
- fsWatchers.push(w);
431
+ // persistent: false - the keepAlive below owns the process lifetime.
432
+ watchFile(regPath, { persistent: false, interval: REGISTRY_STAT_MS }, onRegistryStat);
433
+ statWatching = true;
388
434
  } catch {
389
- // The file may not exist yet, the directory may not be watchable: the
390
- // poll is the answer to both.
435
+ // A path that cannot be stat-watched is not an exit; the poll covers it.
391
436
  }
392
- };
393
- if (!pinned) {
394
- attach(regPath, false);
395
- attach(dirname(regPath), true);
396
437
  }
397
438
  const polling = setInterval(() => void refresh(), registryPollMs);
398
439
  polling.unref?.();
@@ -416,13 +457,7 @@ export async function watchRegistered({
416
457
  signal?.removeEventListener("abort", bump);
417
458
  clearInterval(sweeping);
418
459
  clearInterval(polling);
419
- for (const w of fsWatchers) {
420
- try {
421
- w.close();
422
- } catch {
423
- // closing twice, or after an error, is not a failure worth a line
424
- }
425
- }
460
+ if (statWatching) unwatchFile(regPath, onRegistryStat);
426
461
  }
427
- return { watched, missing };
462
+ return { watched, missing, ...(restarting ? { restart: true } : {}) };
428
463
  }
@@ -22,6 +22,7 @@ import { createServer } from "node:net";
22
22
  import { tmpdir } from "node:os";
23
23
  import { delimiter, join } from "node:path";
24
24
  import { devServerEnv } from "./child.mjs";
25
+ import { OUT_OF_TIME } from "./codingChecks.mjs";
25
26
  import { killTree } from "./kill.mjs";
26
27
  import { pageOf, isScreenFile } from "./pageRoutes.mjs";
27
28
  import { runnableCommand } from "./windows-command.mjs";
@@ -75,7 +76,7 @@ export function findBrowser({ env = process.env, platform = process.platform, ex
75
76
  // ---------- the browser, over its DevTools pipe ----------
76
77
 
77
78
  /** Start the browser headless with a fresh profile it forgets afterwards. */
78
- export async function openBrowser(browser, { platform = process.platform, stopCheck, deadline = Infinity } = {}) {
79
+ export async function openBrowser(browser, { platform = process.platform, stopCheck, onProcess, deadline = Infinity } = {}) {
79
80
  const profile = await mkdtemp(join(tmpdir(), "viewable-browser-"));
80
81
  const args = [
81
82
  ...browser.args, "--headless=new", "--remote-debugging-pipe", `--user-data-dir=${profile}`,
@@ -84,7 +85,8 @@ export async function openBrowser(browser, { platform = process.platform, stopCh
84
85
  `--window-size=${VIEWPORT.width},${VIEWPORT.height}`, "about:blank",
85
86
  ];
86
87
  // The person's own browser, but not the runner's secrets.
87
- const child = spawn(browser.bin, args, { stdio: ["ignore", "ignore", "ignore", "pipe", "pipe"], windowsHide: true, env: devServerEnv(process.env, platform) });
88
+ const child = spawn(browser.bin, args, { stdio: ["ignore", "ignore", "ignore", "pipe", "pipe"], windowsHide: true, detached: Boolean(onProcess) && platform !== "win32", env: devServerEnv(process.env, platform) });
89
+ onProcess?.(child.pid);
88
90
  const waiting = new Map();
89
91
  const listeners = new Set();
90
92
  let nextId = 1;
@@ -254,7 +256,7 @@ async function appScript(dir) {
254
256
  }
255
257
 
256
258
  /** Start the folder's app on a free port and wait until it answers. */
257
- export async function startApp(dir, { env, platform = process.platform, deadline, stopCheck, killGraceMs = 3_000, fetchImpl = fetch }) {
259
+ export async function startApp(dir, { env, platform = process.platform, deadline, stopCheck, killGraceMs = 3_000, onProcess, fetchImpl = fetch }) {
258
260
  const found = await appScript(dir);
259
261
  if (!found.script) return { ok: false, missing: found.missing };
260
262
  const port = await freePort();
@@ -264,6 +266,7 @@ export async function startApp(dir, { env, platform = process.platform, deadline
264
266
  stdio: ["ignore", "pipe", "pipe"],
265
267
  env: { ...devServerEnv(env, platform), ...(port ? { PORT: String(port) } : {}), BROWSER: "none", NO_COLOR: "1", FORCE_COLOR: "0" },
266
268
  });
269
+ onProcess?.(child.pid);
267
270
  let log = "";
268
271
  let exited = false;
269
272
  const take = (chunk) => { log = (log + String(chunk)).slice(-8_000); };
@@ -330,7 +333,7 @@ async function pictureOf(dir, page, browser, options) {
330
333
  * `files` are the paths the run changed. `folder` is where the app is tried
331
334
  * when the copy's does not start: if it does not start there either, the
332
335
  * check is skipped (not the run's doing), never failed. */
333
- export async function checkPage({ cwd, folder, files, env, baseEnv = process.env, platform = process.platform, deadline, stopCheck, killGraceMs, browser: given, fetchImpl }) {
336
+ export async function checkPage({ cwd, folder, files, env, baseEnv = process.env, platform = process.platform, deadline, stopCheck, killGraceMs, onProcess, browser: given, fetchImpl }) {
334
337
  // A page the run deleted has no address left to open.
335
338
  const screens = files.filter((file) => isScreenFile(file) && existsSync(join(cwd, file)));
336
339
  if (screens.length === 0) return null;
@@ -339,11 +342,11 @@ export async function checkPage({ cwd, folder, files, env, baseEnv = process.env
339
342
  const browser = given === undefined ? findBrowser({ env: baseEnv, platform }) : given;
340
343
  if (!browser) return { page, check: check("skipped", "No browser was found on this computer."), note: NO_BROWSER };
341
344
  if (await stopCheck?.()) return { page, browser, stopped: true, check: check("skipped", "Stopped before this check finished.") };
342
- if (Date.now() >= deadline) return { page, browser, check: check("failed", "Ran out of time before this check finished.") };
343
- const options = { env, platform, deadline, stopCheck, killGraceMs, ...(fetchImpl ? { fetchImpl } : {}) };
345
+ if (Date.now() >= deadline) return { page, browser, check: check("skipped", OUT_OF_TIME) };
346
+ const options = { env, platform, deadline, stopCheck, killGraceMs, onProcess, ...(fetchImpl ? { fetchImpl } : {}) };
344
347
  let opened;
345
348
  let stoppedStarting = false;
346
- try { opened = await openBrowser(browser, { platform, stopCheck, deadline }); } catch (error) { opened = null; stoppedStarting = error.stopped === true; }
349
+ try { opened = await openBrowser(browser, { platform, stopCheck, deadline, onProcess }); } catch (error) { opened = null; stoppedStarting = error.stopped === true; }
347
350
  if (stoppedStarting) return { page, browser, stopped: true, check: check("skipped", "Stopped before this check finished.") };
348
351
  if (!opened) return { page, check: check("skipped", "The browser on this computer did not start."), note: NO_BROWSER };
349
352
  try {
@@ -352,7 +355,7 @@ export async function checkPage({ cwd, folder, files, env, baseEnv = process.env
352
355
  if (after.browserGone) return { page, browser, check: check("skipped", "The browser on this computer closed."), note: BROWSER_CLOSED };
353
356
  if (after.missing === "script") return { page, browser, check: check("skipped", "This folder has no app to start."), note: NO_APP_SCRIPT };
354
357
  if (after.missing === "dependencies") return { page, browser, check: check("skipped", "The folder's dependencies are not installed."), note: NO_APP };
355
- if (after.timedOut) return { page, browser, check: check("failed", "Ran out of time before this check finished.") };
358
+ if (after.timedOut) return { page, browser, check: check("skipped", OUT_OF_TIME) };
356
359
  if (!after.started) {
357
360
  const there = folder ? await startApp(folder, options) : { ok: false };
358
361
  if (there.ok) await there.stop();
@@ -377,13 +380,13 @@ export async function checkPage({ cwd, folder, files, env, baseEnv = process.env
377
380
 
378
381
  /** Before, from the folder, and the changed part of After. Pictures that do
379
382
  * not differ mean the wrong page was opened: no pictures at all. */
380
- export async function beforePicture({ folder, page, after, browser, env, platform = process.platform, deadline, stopCheck, killGraceMs, fetchImpl }) {
383
+ export async function beforePicture({ folder, page, after, browser, env, platform = process.platform, deadline, stopCheck, killGraceMs, onProcess, fetchImpl }) {
381
384
  if (!after || !browser) return {};
382
385
  if (!folder || await stopCheck?.() || Date.now() >= deadline) return { after };
383
386
  let opened;
384
- try { opened = await openBrowser(browser, { platform, stopCheck, deadline }); } catch { return { after }; }
387
+ try { opened = await openBrowser(browser, { platform, stopCheck, deadline, onProcess }); } catch { return { after }; }
385
388
  try {
386
- const before = await pictureOf(folder, page, opened, { env, platform, deadline, stopCheck, killGraceMs, ...(fetchImpl ? { fetchImpl } : {}) });
389
+ const before = await pictureOf(folder, page, opened, { env, platform, deadline, stopCheck, killGraceMs, onProcess, ...(fetchImpl ? { fetchImpl } : {}) });
387
390
  if (!before.started || !before.ok || !before.image) return { after };
388
391
  let changed = null;
389
392
  try { changed = await opened.changedArea(before.image, after); } catch { return { before: before.image, after }; }
package/lib/paths.mjs CHANGED
@@ -2,7 +2,6 @@
2
2
  // Historical request files and the repo-map cache still live under SPAWN_DIR.
3
3
 
4
4
  export const BOARD_DIR = ".viewable";
5
- export const INBOX_DIR = `${BOARD_DIR}/inbox`;
6
5
  // Kept on purpose: the sweep reads receipts written by old runners.
7
6
  export const SPAWN_DIR = ".glytch/inbox/spawn";
8
7