viewable-one 0.12.3 → 0.12.5

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
@@ -13,6 +13,91 @@ package.
13
13
 
14
14
  ## [Unreleased]
15
15
 
16
+ ## [0.12.5] - 2026-11-10
17
+
18
+ ### Fixed
19
+
20
+ - `viewable update` and the Update button in More install with the npm next
21
+ to the Node running Viewable, not the first `npm` on the PATH (#5305). On a
22
+ Mac with a system Node and nvm the first one wrote to a folder you cannot
23
+ write to and the message blamed your connection. A failed install now says
24
+ what failed, for example "No permission to write /usr/local/lib/node_modules".
25
+
26
+ - A removed default folder stays removed across restarts (#5290). The
27
+ daemon made and registered the default folder (`~/Glytch`, `~/Viewable` or
28
+ `Documents/Viewable`) on every start, so Remove held only until the next
29
+ restart. `removeFolder` now leaves a marker beside the restore markers,
30
+ `ensureViewableFolder` skips a folder with one, and `addFolder` (init, sync)
31
+ clears it. `ensureViewableFolder` checks and registers under the lock a
32
+ removal takes, so a Remove that lands while the start makes the folder is
33
+ not undone; `viewable forget` takes the lock too, and startup registration
34
+ is one step in the registry (#5310). Nothing is deleted.
35
+ - A Codex run whose app list read ran out of time no longer stops with words
36
+ that blame the person's apps (#5271). A timeout gets its own message ("Codex
37
+ was slow") and one retry at twice the time, in `prepareCodexApps`, the one
38
+ path every caller uses.
39
+
40
+ ### Added
41
+
42
+ - The computer app says goodbye when it is stopped (ruling #4979, #5216).
43
+ On SIGTERM, SIGHUP, SIGBREAK (Windows) or Ctrl+C it writes one last
44
+ presence with `goodbye` set to the signal (`lib/goodbye.mjs`), through the
45
+ shared heartbeat's new `farewell`, which closes the hub so no later beat
46
+ overwrites it, and waits (at most 3 s) for every beat and register already
47
+ on its way, so none lands after it; the shared registrar is tied to the hub
48
+ for this. An OS signal says it at once with a 3 s timeout and exits within
49
+ 7 s; Ctrl+C drains the running sessions first, still beating. The
50
+ next normal beat leaves the field out and so clears it. `viewable update`
51
+ and `viewable stop` leave a `quiet-stop.json` note first, so their SIGTERM
52
+ says nothing; the board's Update restarts in process and never signals.
53
+ Two edge cases (#5308): a register that outlasts that 3 s wait no longer
54
+ erases the goodbye, because the farewell sends it again each time such a
55
+ register lands, until the exit deadline less 0.5 s, and it covers a folder that register named; and Ctrl+C during the first
56
+ registration, before any folder has beaten, still says goodbye, because the
57
+ hub keeps every folder that beats once a stop is asked, even one whose
58
+ watcher then ends (`keepIds`). A stop asked before any beat waits (up to
59
+ that deadline) for the first registration, which names its folders and how
60
+ to write their presence, and says goodbye for them.
61
+ - Sign in to Claude Code from the board (#5216, rulings #4151 and #4200).
62
+ `SIGN_IN_AGENTS` is now `codex` and `claude`; the Claude sign-in runs
63
+ `claude auth login --claudeai` (the Claude plan, never the API console).
64
+ Presence reports `signInAgents`, so the board can tell a computer that can
65
+ start it from an older one. `codexLogin` is replaced by `agentLogin`,
66
+ which finds the binary the way a run does (`resolveAgentBinary`: the
67
+ daemon's PATH, the usual install folders, a login shell) and says "not
68
+ installed" only when none has it, for Codex too.
69
+
70
+ ## [0.12.4] - 2026-11-09
71
+
72
+ ### Added
73
+
74
+ - The computer app updates itself from the board's More menu (#4949). The
75
+ board's Update request reaches it on its heartbeat; it waits for running
76
+ runs, then installs. While an update waits or installs, no run starts,
77
+ including a recovered run in the restart pass (`runGate` in
78
+ `runnerAdmission.mjs`, used by `claimOne` and `restartPass`); the record
79
+ stays so a later pass or the restarted app carries it on.
80
+ - A take that failed with no answer may have won on the server, which
81
+ deletes the request. If the request is then gone, the update fails where
82
+ the user sees it ("Nothing was installed") instead of idling; Try again
83
+ files a new request. A failed read of update requests is reported in the
84
+ heartbeat (`updatesUnread`) and the computer keeps the request it holds
85
+ instead of reading the missing op as Cancel update.
86
+ - Remove uninstalls the computer app (#4951, #4978). It uninstalls only when
87
+ every key the computer holds reads removed for good, and never deletes the
88
+ Viewable folder. Removal evidence lives in `computer_removed_keys`, which
89
+ the OAuth cleanup does not delete, so a computer away past the 30-day
90
+ cleanup still hears it. A folder added again after an uninstall is not
91
+ uninstalled again.
92
+ - The uninstall request arrives within seconds: a database trigger sends an
93
+ `op` hint on the owner's live runner topics, and the bridge beats at once.
94
+ - On Linux and WSL the uninstall starts in its own `systemd-run --user
95
+ --collect` unit; on Windows it starts through WMI so Task Scheduler's end
96
+ of the job does not kill it. Both fall back to a plain detached child. The
97
+ launched script carries a curated environment with no tokens or keys.
98
+ - An online computer that does not take uninstall requests (older apps) keeps
99
+ the copy-a-prompt way, with the board-only Remove.
100
+
16
101
  ## [0.12.3] - 2026-11-09
17
102
 
18
103
  ### Fixed
@@ -60,6 +145,7 @@ package.
60
145
  `--model`, because Claude Code refuses the OpenRouter id. Other ids pass
61
146
  through unchanged (#3869). The fix reaches people with the next bridge
62
147
  release.
148
+
63
149
  ## [0.12.2] - 2026-10-30
64
150
 
65
151
  ### Changed
package/glytch.mjs CHANGED
@@ -46,15 +46,16 @@ import { allGreen, doctorRows } from "./lib/doctor.mjs";
46
46
  import { loginDaemon, noDaemonInstall } from "./lib/logindaemon.mjs";
47
47
  import { makeFileLogger } from "./lib/logs.mjs";
48
48
  import { watchRegistered } from "./lib/multiwatch.mjs";
49
- import { readRegistry, registryPath, removeFolder, touchRegistry } from "./lib/registry.mjs";
49
+ import { readRegistry, registryPath, removeFolder, touchRegistry, withRegistryLock } from "./lib/registry.mjs";
50
50
  import { settingsFromEnv, newRunnerId, registerAndFindProject } from "./lib/runner.mjs";
51
51
  import { syncFolder, syncRegistry } from "./lib/sync.mjs";
52
52
  import { SETUP_HEALTH_SLOW_MS, SETUP_HEALTH_WAIT_MS, hasFreshBeat, waitForRunnerHealth, writeRunnerHealth } from "./lib/runner-health.mjs";
53
- import { initServiceScript, packageVersion, runUpdate } from "./lib/update.mjs";
53
+ import { initServiceScript, packageVersion, runUpdate, UPDATE_RESTART_EXIT_CODE } from "./lib/update.mjs";
54
54
  import { initOptions, chooseAgents, readAgentSelection, saveAgentSelection } from "./lib/agent-selection.mjs";
55
55
  import { projectMcpServerKey } from "./lib/project-mcp.mjs";
56
56
  import { AGENT_CONNECT_HINT, agentLoginStep, personalBoardToken, signInStep } from "./lib/init-connect.mjs";
57
57
  import { runUninstall, uninstallOptions } from "./lib/uninstall.mjs";
58
+ import { markQuietStop, onStopSignals } from "./lib/goodbye.mjs";
58
59
 
59
60
  // THE SAME SENTENCE `SETUP_READY` NAMES (src/folder/runnerSetup.ts). Nothing
60
61
  // under bridge/ may import from src/ (nor the reverse - see CLAUDE.md), so
@@ -399,7 +400,9 @@ async function forget() {
399
400
  const color = colorEnabled();
400
401
  const root = resolve(process.cwd());
401
402
  say(heading("Viewable · Forget project", { color }));
402
- const { removed } = await removeFolder(root);
403
+ // Under the registry lock the daemon's start takes before it registers the
404
+ // default folder, so a forget cannot land in the middle of that (#5290).
405
+ const { removed } = await withRegistryLock(() => removeFolder(root));
403
406
  say(
404
407
  removed
405
408
  ? ok(`Forgot ${root}. Your computer keeps watching the ${(await readRegistry()).length} folder(s) left in ${registryPath()}.`, { color })
@@ -416,6 +419,8 @@ async function stop() {
416
419
  const color = colorEnabled();
417
420
  const daemon = loginDaemon();
418
421
  say(heading("Viewable · Stop runner", { color }));
422
+ // A Stop is not a goodbye (ruling #4979): the app it stops reads this.
423
+ await markQuietStop({ why: "stop" });
419
424
  const result = await daemon.stop();
420
425
  if (result.unloaded) {
421
426
  say(ok(`Unloaded the ${daemon.rowLabel} (${result.file}).`, { color }));
@@ -471,12 +476,20 @@ async function runner(args) {
471
476
  }
472
477
  const log = makeFileLogger();
473
478
  const controller = new AbortController();
474
- process.on("SIGINT", () => {
475
- log("stopping. Any session already running keeps going; it is a separate process.");
476
- controller.abort();
477
- });
478
- await watchRegistered({ settings, signal: controller.signal, log });
479
- return null;
479
+ // Ctrl+C, and the OS stopping this app at shutdown, restart or sign out:
480
+ // each stops the watch, and each but an update's or Stop's says goodbye
481
+ // to the board first (ruling #4979, lib/goodbye.mjs).
482
+ const { goodbye, stoppedBy } = onStopSignals({ stop: controller, log });
483
+ const watched = await watchRegistered({ settings, signal: controller.signal, log, goodbye });
484
+ // The board's Update installed a new version (#4949): exit nonzero so
485
+ // launchd, systemd and Task Scheduler each start the new code.
486
+ if (watched?.restart) {
487
+ log(`restarting on the new version`);
488
+ return UPDATE_RESTART_EXIT_CODE;
489
+ }
490
+ // Stopped by a signal: exit now, rather than wait on whatever handle is
491
+ // still open, which is what the signal's own default used to do.
492
+ return stoppedBy() ? 0 : null;
480
493
  }
481
494
 
482
495
  async function main() {
package/lib/codexApps.mjs CHANGED
@@ -5,6 +5,8 @@ import { killTree } from "./kill.mjs";
5
5
  import { secretLike } from "./codexToolInputs.mjs";
6
6
 
7
7
  const unreadable = () => new Error("Couldn't read the apps set up in Codex, so this run did not start. Check your apps in Codex, then try again.");
8
+ // Codex did not answer in time (slow under load, #5271). Not the person's apps.
9
+ const slow = () => Object.assign(new Error("Codex was slow to answer, so this run did not start. Try again."), { slow: true });
8
10
  const unsupported = () => new Error("Codex couldn't check approval for every app on this computer, so this run did not start. Check your apps in Codex, then try again.");
9
11
  const offSources = ["-c", "features.plugins=false", "-c", "features.apps=false"];
10
12
  const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
@@ -43,7 +45,7 @@ export async function listCodexServers({ bin = "codex", args, cwd, env = process
43
45
  try {
44
46
  const list = await new Promise((resolve, reject) => {
45
47
  let out = "";
46
- timer = setTimeout(() => reject(unreadable()), timeoutMs);
48
+ timer = setTimeout(() => reject(slow()), timeoutMs);
47
49
  child.stdout.setEncoding("utf8");
48
50
  child.stdout.on("data", (chunk) => { out += chunk; if (out.length > 2_000_000) reject(unreadable()); });
49
51
  child.once("error", () => reject(unreadable()));
@@ -96,7 +98,7 @@ async function readCodexApps({ bin = "codex", args, cwd, env = process.env, time
96
98
  try {
97
99
  await rpc.initialize();
98
100
  return { config: await readAppsConfig(rpc, cwd), inventory: inventory ? await readInventory(rpc) : [] };
99
- } catch { throw unreadable(); } finally { rpc.close(); await stopPreflight(child, gone, killGraceMs); }
101
+ } catch (error) { throw /timed out/.test(error?.message ?? "") ? slow() : unreadable(); } finally { rpc.close(); await stopPreflight(child, gone, killGraceMs); }
100
102
  }
101
103
 
102
104
  // -c splits dotted paths literally, including quote characters (0.162.1).
@@ -154,14 +156,24 @@ function sourceIsOff(config, source) {
154
156
  return plugin?.enabled === false || plugin?.mcp_servers?.[source.name]?.enabled === false;
155
157
  }
156
158
 
159
+ // A read that ran out of time is tried once more with twice the time: a busy
160
+ // computer answers late, it does not have broken apps (#5271). Any other
161
+ // refusal is final. Every caller (a run, the Look) reaches the reads here.
162
+ async function retrySlow(read, opts) {
163
+ try { return await read(opts); } catch (error) {
164
+ if (!error?.slow) throw error;
165
+ return read({ ...opts, timeoutMs: (opts.timeoutMs ?? 15_000) * 2 });
166
+ }
167
+ }
168
+
157
169
  export async function prepareCodexApps(opts, { on, isDraft }) {
158
170
  const allowed = on && !isDraft;
159
171
  const sourceArgs = allowed ? [] : offSources;
160
172
  const restricted = { ...opts, args: [...(opts.args ?? ["app-server"]), ...sourceArgs] };
161
173
  // ON gets plugin identities from the effective app-server inventory and
162
174
  // config. A separate CLI listing would start an unnecessary third process.
163
- const listed = allowed ? [] : await listCodexServers(restricted);
164
- const { config, inventory } = await readCodexApps(restricted, allowed);
175
+ const listed = allowed ? [] : await retrySlow(listCodexServers, restricted);
176
+ const { config, inventory } = await retrySlow((o) => readCodexApps(o, allowed), restricted);
165
177
  const servers = config.mcp_servers;
166
178
  if (!allowed && (config.features?.plugins !== false || config.features?.apps !== false)) throw unreadable();
167
179
  if (listed.some((entry) => entry.enabled !== false && !Object.hasOwn(servers, entry.name))) throw unsupported();
@@ -0,0 +1,120 @@
1
+ // THE COMPUTER APP SAYS GOODBYE (ruling #4979, #5216).
2
+ //
3
+ // When the computer shuts down, restarts or signs out, the OS stops this
4
+ // process with a signal: SIGTERM from launchd and systemd, SIGHUP when the
5
+ // terminal or session goes, Ctrl+C (SIGINT) by hand, SIGBREAK on Windows.
6
+ // Before it exits it writes one last presence with `goodbye` set, so the
7
+ // board's offline card says the computer was turned off rather than asleep
8
+ // (src/runs/projects.ts `saidGoodbye`). The next normal beat leaves the
9
+ // field out, and since a beat replaces the presence, that clears it.
10
+ //
11
+ // Best effort, with a short wait: a power cut, a crash or Wi-Fi already gone
12
+ // says nothing, and the card keeps its asleep line.
13
+ //
14
+ // NOT FOR AN UPDATE OR STOP. The board's Update restarts in process and
15
+ // never signals. `viewable update` and `viewable stop` stop the service with
16
+ // the same SIGTERM a shutdown sends, so each leaves a note first
17
+ // (`markQuietStop`) and the stopping process reads it (`takeQuietStop`).
18
+ import { readFile, rm } from "node:fs/promises";
19
+ import { join } from "node:path";
20
+
21
+ import { writeFileAtomic } from "./atomic.mjs";
22
+ import { viewableHome } from "./registry.mjs";
23
+
24
+ /** How long the goodbye beat may take. launchd allows a stopping agent 20 s
25
+ * by default; a shutdown should not wait on a board that cannot be reached. */
26
+ export const GOODBYE_WAIT_MS = 3_000;
27
+ /** After an OS stop signal the process exits by this time, goodbye or not:
28
+ * up to GOODBYE_WAIT_MS for a beat or register already on its way (so the
29
+ * goodbye lands after it rather than being overwritten by it), then up to
30
+ * GOODBYE_WAIT_MS for the goodbye itself. A register that outlasts the
31
+ * first wait gets the goodbye again each time one lands (#5308), until
32
+ * this deadline less a margin (runnerPace.mjs reads it from here). */
33
+ export const GOODBYE_EXIT_MS = 2 * GOODBYE_WAIT_MS + 1_000;
34
+ /** A note older than this is from a stop that never came. */
35
+ export const QUIET_STOP_MS = 2 * 60_000;
36
+
37
+ /** The signals that stop the computer app, per platform. Node never raises
38
+ * SIGTERM on Windows, and SIGBREAK only exists there. */
39
+ export const stopSignals = (platform = process.platform) =>
40
+ platform === "win32" ? ["SIGINT", "SIGTERM", "SIGHUP", "SIGBREAK"] : ["SIGINT", "SIGTERM", "SIGHUP"];
41
+
42
+ /** Ctrl+C is a person at the terminal: the app finishes the sessions it runs
43
+ * first, beating while it does, and says goodbye at the end. Every other
44
+ * stop signal is the OS, which will not wait: goodbye at once. */
45
+ export const signalWaitsForSessions = (name) => name === "SIGINT";
46
+
47
+ export const quietStopPath = (env = process.env) => join(viewableHome(env), "quiet-stop.json");
48
+
49
+ /** `viewable update` or `viewable stop` is about to stop the service: the
50
+ * stop that follows is not a goodbye. Never throws. */
51
+ export async function markQuietStop({ env = process.env, now = Date.now, why = "stop" } = {}) {
52
+ try { await writeFileAtomic(quietStopPath(env), `${JSON.stringify({ at: now(), why })}\n`); }
53
+ catch { /* No note means a goodbye, which the next beat clears. */ }
54
+ }
55
+
56
+ /** Whether this stop was asked for by `markQuietStop` a moment ago. Reads
57
+ * the note once and removes it, so one note quiets one stop. */
58
+ export async function takeQuietStop({ env = process.env, now = Date.now } = {}) {
59
+ const path = quietStopPath(env);
60
+ let at;
61
+ try { at = JSON.parse(await readFile(path, "utf8"))?.at; }
62
+ catch { return false; }
63
+ await rm(path, { force: true }).catch(() => {});
64
+ return typeof at === "number" && now() - at >= 0 && now() - at <= QUIET_STOP_MS;
65
+ }
66
+
67
+ /** What a stop asks of the watch (lib/multiwatch.mjs): whether to say
68
+ * goodbye (`value`, what `presence.goodbye` carries) and whether at once
69
+ * (`now`) or once the sessions running here have finished. Asked again,
70
+ * `now` can only turn on: Ctrl+C and then a shutdown says it at once. */
71
+ export function makeGoodbye() {
72
+ let value = null;
73
+ let now = false;
74
+ const listeners = new Set();
75
+ return {
76
+ get value() { return value; },
77
+ get now() { return now; },
78
+ ask(said, { now: at = false } = {}) {
79
+ value ??= said;
80
+ now ||= at;
81
+ for (const fn of [...listeners]) fn();
82
+ },
83
+ subscribe(fn) {
84
+ listeners.add(fn);
85
+ return () => listeners.delete(fn);
86
+ },
87
+ };
88
+ }
89
+
90
+ /** Wire the stop signals for `viewable runner watch`. Each stops the watch
91
+ * (`stop`); each but an update's or Stop's asks for a goodbye; an OS signal
92
+ * also arms the exit, so a stuck goodbye or a long session never holds a
93
+ * shutdown up. Returns the goodbye to pass to `watchRegistered`, and
94
+ * `stoppedBy()`, the first signal seen. */
95
+ export function onStopSignals({
96
+ stop, log = () => {}, env = process.env, platform = process.platform,
97
+ processRef = process, exit = (code) => processRef.exit(code), quiet = takeQuietStop,
98
+ } = {}) {
99
+ const goodbye = makeGoodbye();
100
+ let first = null;
101
+ let exitArmed = false;
102
+ const handle = async (name) => {
103
+ first ??= name;
104
+ const waits = signalWaitsForSessions(name);
105
+ if (!waits && !exitArmed) {
106
+ exitArmed = true;
107
+ const timer = setTimeout(() => exit(0), GOODBYE_EXIT_MS);
108
+ timer.unref?.();
109
+ }
110
+ const asked = !waits && (await quiet({ env }));
111
+ if (asked) log(`${name}: stopping for an update or Stop, so no goodbye.`);
112
+ else goodbye.ask(name, { now: !waits });
113
+ if (!stop.signal.aborted) {
114
+ log("stopping. Any session already running keeps going; it is a separate process.");
115
+ stop.abort();
116
+ }
117
+ };
118
+ for (const name of stopSignals(platform)) processRef.on(name, () => void handle(name));
119
+ return { goodbye, stoppedBy: () => first };
120
+ }
@@ -50,7 +50,11 @@ import { makeHeartbeatHub, makeRegistrar, REGISTER_REFRESH_MS } from "./runnerPa
50
50
  import { beatBaseMs, makeRunnerRealtime } from "./runnerRealtime.mjs";
51
51
  import { sweepAll } from "./sweep.mjs";
52
52
  import { syncFolder } from "./sync.mjs";
53
- 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 { GOODBYE_WAIT_MS } from "./goodbye.mjs";
57
+ import * as runnerApiModule from "./runnerApi.mjs";
54
58
 
55
59
  export const SWEEP_INTERVAL_MS = 86_400_000;
56
60
  /** How often the registry is re-read when the stat poll below tells us
@@ -74,11 +78,17 @@ const isDir = async (path) => {
74
78
  /** Watch every registered folder until `signal` aborts.
75
79
  *
76
80
  * Returns {watched, missing} after signal-driven shutdown and after every
77
- * folder's watch has ended. An empty registry still waits for new folders. */
81
+ * folder's watch has ended. An empty registry still waits for new folders.
82
+ * `restart: true` means the board's Update installed a new version and the
83
+ * caller should exit so the service manager starts it (#4949).
84
+ *
85
+ * `goodbye` (lib/goodbye.mjs `makeGoodbye`) is how a stop signal asks for the
86
+ * last beat (ruling #4979): at once when it says `now`, otherwise once every
87
+ * watcher has finished its sessions. An update's restart never asks. */
78
88
  export async function watchRegistered({
79
89
  env = process.env,
80
90
  settings,
81
- signal,
91
+ signal: outerSignal,
82
92
  log = () => {},
83
93
  folders,
84
94
  sweep = sweepAll,
@@ -105,7 +115,15 @@ export async function watchRegistered({
105
115
  // THE PUSH CHANNEL (#813), one per process. Injected for the tests, which
106
116
  // pass a fake, or `() => null` for none (every 10 s, as before).
107
117
  makeRealtime = makeRunnerRealtime,
118
+ // THE BOARD'S UPDATE BUTTON (#4949). Injected for the tests.
119
+ makeSelfUpdater = makeSelfUpdate,
120
+ goodbye,
108
121
  } = {}) {
122
+ // An installed update stops every watcher the same way Ctrl-C does: each
123
+ // drains the runs it started (there are none by then) before it ends.
124
+ const restartStop = new AbortController();
125
+ const signal = outerSignal ? AbortSignal.any([outerSignal, restartStop.signal]) : restartStop.signal;
126
+ let restarting = false;
109
127
  // An injected list is the whole list: a caller that says which folders to
110
128
  // watch is not asking the registry anything, so the live re-read below
111
129
  // stands down for it. Nothing in the package passes this; the tests do.
@@ -186,7 +204,43 @@ export async function watchRegistered({
186
204
  // starting a detached dev server - the browser may be on another box
187
205
  // entirely (lib/platform.mjs says why it is not `navigator`).
188
206
  const health = makeRunnerHealth({ env, version: updater.state?.().version ?? packageVersion() });
189
- const markExtra = () => ({ ...platform, ...updater.mark(), ...probe.mark(), ...health.mark() });
207
+ // Every folder a beat has named, so the update can see each folder's
208
+ // recovered runs whose owner is gone but whose child processes are not.
209
+ const projects = new Map();
210
+ const activeRuns = async () => {
211
+ let count = liveRuns.size;
212
+ for (const project of projects.values()) {
213
+ for (const id of await activeRecoveryRunIds(project, settings ?? {}, { log })) if (!liveRuns.has(id)) count += 1;
214
+ }
215
+ return count;
216
+ };
217
+ const updateApi = settings?.runnerApi ?? runnerApiModule;
218
+ let askBeat = () => {};
219
+ const selfUpdater = makeSelfUpdater({
220
+ version: updater.state?.().version ?? packageVersion(),
221
+ activeRuns,
222
+ take: async (op) => {
223
+ const taken = await updateApi.updateTake({ projectId: op.project_id, requestId: op.id }, { env: settings?.env, fetchImpl: settings?.fetchImpl });
224
+ if (!taken?.ok) throw new Error(taken?.error ?? "Could not take the update request.");
225
+ return taken.taken === true;
226
+ },
227
+ onChange: () => askBeat(),
228
+ restart: async () => {
229
+ restarting = true;
230
+ restartStop.abort();
231
+ },
232
+ log,
233
+ });
234
+ const selfUpdate = {
235
+ request: (op) => selfUpdater.request(op),
236
+ seen: (project, ops) => {
237
+ if (project?.id) projects.set(project.id, project);
238
+ selfUpdater.seen(project, ops);
239
+ },
240
+ holdsRuns: () => selfUpdater.holdsRuns(),
241
+ claimStarted: () => selfUpdater.claimStarted(),
242
+ };
243
+ const markExtra = () => ({ ...platform, ...updater.mark(), ...probe.mark(), ...health.mark(), ...selfUpdater.mark() });
190
244
 
191
245
  // ONE REGISTER AND ONE HEARTBEAT FOR THE WHOLE PROCESS (ticket e8,
192
246
  // 2026-10-03; #616, 2026-10-16). Every folder's beat registers the whole
@@ -196,7 +250,6 @@ export async function watchRegistered({
196
250
  // repeats an unchanged list every 5 minutes, and one heartbeat hub, which
197
251
  // sends one heartbeat for all of them per beat (lib/runnerPace.mjs).
198
252
  const beatMs = settings?.beatMs ?? RUNNER_BEAT_MS;
199
- const registrar = makeRegistrar({ ttlMs: REGISTER_REFRESH_MS, failureTtlMs: 0.9 * beatMs });
200
253
  const runnerId = settings?.runnerId ?? newRunnerId();
201
254
  // PUSH (#813): joined, every folder beats every 5 minutes and the hub's
202
255
  // shared answer lives as long, so the folders still share one heartbeat.
@@ -212,15 +265,31 @@ export async function watchRegistered({
212
265
  ttlMs: () => 0.9 * beatBaseMs(realtime, beatMs, settings?.pushBeatMs),
213
266
  failureTtlMs: 0.9 * beatMs,
214
267
  });
268
+ // Tied to the hub, so the goodbye waits for a register on its way (#5216).
269
+ const registrar = makeRegistrar({ ttlMs: REGISTER_REFRESH_MS, failureTtlMs: 0.9 * beatMs, heartbeats });
215
270
  realtime?.start();
216
271
  // A BEAT ON REQUEST (#813 review). `glytch init` in a folder this daemon
217
272
  // already watches leaves it running and waits for a beat that came after
218
273
  // it started (runner-health.mjs); joined, the next one could be 5 minutes
219
274
  // away. init rewrites the registry instead, and every watcher beats once,
220
275
  // sharing one heartbeat (one `at` for all of them).
276
+ // THE GOODBYE (ruling #4979). The hub keeps the folders from the moment a
277
+ // stop is asked, and any that beat after it (a first registration still
278
+ // running when Ctrl+C came), since a watcher that ends leaves the hub
279
+ // before the last one does (#5308).
280
+ let saidGoodbye = null;
281
+ const sayGoodbye = () => {
282
+ saidGoodbye ??= heartbeats.farewell(heartbeats.ids(), { goodbye: goodbye.value, timeoutMs: GOODBYE_WAIT_MS })
283
+ .then((answer) => log(answer?.ok ? "said goodbye to the board" : `could not say goodbye to the board: ${answer?.error ?? "no answer"}`));
284
+ return saidGoodbye;
285
+ };
286
+ const unsubscribeGoodbye = goodbye?.subscribe(() => {
287
+ heartbeats.keepIds();
288
+ if (goodbye.now && !restarting) void sayGoodbye();
289
+ });
221
290
  const beatAsks = new Set();
222
291
  const beatRequests = { subscribe: (fn) => { beatAsks.add(fn); return () => beatAsks.delete(fn); } };
223
- const askBeat = () => {
292
+ askBeat = () => {
224
293
  const at = Date.now();
225
294
  for (const fn of [...beatAsks]) fn(at);
226
295
  };
@@ -265,7 +334,7 @@ export async function watchRegistered({
265
334
  const entry = { controller, done: false, leaving: false };
266
335
  let started;
267
336
  try {
268
- started = watchOne(folder, { ...settings, runnerId, realtime, onHealthy: (path) => health.beat(path), markExtra, registrar, heartbeats, beatRequests, refreshAgents: () => probe.once() }, {
337
+ started = watchOne(folder, { ...settings, runnerId, realtime, onHealthy: (path) => health.beat(path), markExtra, registrar, heartbeats, beatRequests, refreshAgents: () => probe.once(), selfUpdate }, {
269
338
  signal: controller.signal,
270
339
  log: (line) => log(`[${folder}] ${line}`),
271
340
  });
@@ -405,11 +474,13 @@ export async function watchRegistered({
405
474
  } finally {
406
475
  clearInterval(keepAlive);
407
476
  for (const entry of running.values()) clearTimeout(entry.retry);
477
+ unsubscribeGoodbye?.();
478
+ if (goodbye?.value && !restarting) await sayGoodbye();
408
479
  await realtime?.close();
409
480
  signal?.removeEventListener("abort", bump);
410
481
  clearInterval(sweeping);
411
482
  clearInterval(polling);
412
483
  if (statWatching) unwatchFile(regPath, onRegistryStat);
413
484
  }
414
- return { watched, missing };
485
+ return { watched, missing, ...(restarting ? { restart: true } : {}) };
415
486
  }
package/lib/registry.mjs CHANGED
@@ -55,6 +55,18 @@ export async function markFolderRestore(folder, env = process.env) {
55
55
  await writeFileAtomic(restorePath(folder, env), randomUUID());
56
56
  }
57
57
 
58
+ // A REMOVED FOLDER STAYS REMOVED (#5290). Every start makes and registers the
59
+ // default folder (viewableFolder.mjs), so without a record a person's Remove
60
+ // held only until the next restart: the daemon watched the folder again for a
61
+ // few seconds, until the board's forget came round once more. removeFolder
62
+ // leaves this marker, only an explicit add clears it, and
63
+ // automatic registration checks this marker under the registry lock.
64
+ const removedPath = (folder, env) => join(viewableHome(env), "registry", `${createHash("sha256").update(resolve(folder)).digest("hex")}.removed`);
65
+
66
+ export async function folderWasRemoved(folder, env = process.env) {
67
+ return existsSync(removedPath(folder, env));
68
+ }
69
+
58
70
  // TEMPORARY FOLDERS ARE NEVER REGISTERED (QA 2026-10-01, ticket e7). An agent
59
71
  // once started a runner from its scratchpad, and "proof-project
60
72
  // (/private/tmp/claude-501/...)" sat in Settings > Connection for days. A
@@ -154,12 +166,25 @@ export async function addFolder(folder, env = process.env) {
154
166
  const path = resolve(folder);
155
167
  if (isScratchFolder(path, env)) throw new Error(`${path} is a temporary folder, and those are never registered. Run viewable init in the project folder itself.`);
156
168
  const folders = await readRegistry(env);
169
+ // Adding is the person asking for the folder back (init, sync): the record
170
+ // of its removal ends here, even when it is already listed.
171
+ await rm(removedPath(path, env), { force: true }).catch(() => {});
157
172
  if (folders.includes(path)) return { folders, added: false };
158
173
  const next = [...folders, path];
159
174
  await writeRegistry(next, env);
160
175
  return { folders: next, added: true };
161
176
  }
162
177
 
178
+ /** Automatic registration must not undo a Remove during startup. Return null
179
+ * for a removed folder; otherwise return addFolder's result. Explicit adds
180
+ * still restore removed folders. The check and add share the removal lock. */
181
+ export async function addFolderUnlessRemoved(folder, env = process.env) {
182
+ return withRegistryLock(async () => {
183
+ if (await folderWasRemoved(folder, env)) return null;
184
+ return addFolder(folder, env);
185
+ }, env);
186
+ }
187
+
163
188
  /** Write the folder list back unchanged. The running daemon reads a rewrite
164
189
  * as a request for one beat from every folder it watches (multiwatch.mjs),
165
190
  * which is how `viewable init` in a folder already watched gets the fresh beat
@@ -177,6 +202,9 @@ export async function touchRegistry(env = process.env) {
177
202
  export async function removeFolder(folder, env = process.env) {
178
203
  const path = resolve(folder);
179
204
  const folders = await readRegistry(env);
205
+ // Recorded even when it was not listed: the person asked for it gone.
206
+ await mkdir(dirname(removedPath(path, env)), { recursive: true });
207
+ await writeFileAtomic(removedPath(path, env), `${new Date().toISOString()}\n`);
180
208
  if (!folders.includes(path)) return { folders, removed: false };
181
209
  const next = folders.filter((f) => f !== path);
182
210
  await writeRegistry(next, env);
@@ -10,6 +10,7 @@
10
10
  // local dead-owner evidence and transfer the original row through recovery.
11
11
 
12
12
  import { hasRecoveryRecord, recoverLocalRun } from "./runnerRecovery.mjs";
13
+ import { runGate } from "./runnerAdmission.mjs";
13
14
  import { randomUUID } from "node:crypto";
14
15
  import { stat } from "node:fs/promises";
15
16
  import * as runnerApiModule from "./runnerApi.mjs";
@@ -91,12 +92,24 @@ export async function restartPass(project, settings, { log = () => {}, now = Dat
91
92
  return done;
92
93
  }
93
94
 
94
- if (startRun) for (const row of rows.filter(row => row.lease_generation && !liveRuns.has(row.id))) {
95
- try {
96
- const recovered = await recoverLocalRun(project, row, settings, api, opts, log);
97
- if (recovered) { startRun(recovered); done.resumed.push(row.id); }
98
- } catch (error) { log(`[${row.id}] local recovery failed: ${error.message}`); }
95
+ // A recovered run is a run start like a claim: it waits while an update
96
+ // waits or installs (#4949 review). Its record stays, so a later pass, or
97
+ // the restarted computer app, carries it on; the loop below never ends a
98
+ // fenced row that still has its record.
99
+ const recoverable = startRun ? rows.filter(row => row.lease_generation && !liveRuns.has(row.id)) : [];
100
+ const endStart = recoverable.length ? runGate(settings.selfUpdate) : null;
101
+ if (recoverable.length && !endStart) {
102
+ log("restart pass: an update is waiting; recovered sessions start after it");
103
+ done.skipped.push(...recoverable.map((row) => row.id));
99
104
  }
105
+ if (endStart) try {
106
+ for (const row of recoverable) {
107
+ try {
108
+ const recovered = await recoverLocalRun(project, row, settings, api, opts, log);
109
+ if (recovered) { startRun(recovered); done.resumed.push(row.id); }
110
+ } catch (error) { log(`[${row.id}] local recovery failed: ${error.message}`); }
111
+ }
112
+ } finally { setImmediate(endStart); }
100
113
  // A fenced row whose record is still here belongs to a live owner or to a
101
114
  // recovery that will try again; only a row nobody here can carry on ends.
102
115
  const ours = (row) => !row.lease_generation || (!done.resumed.includes(row.id) && !hasRecoveryRecord(project, row.id, settings));
package/lib/runner.mjs CHANGED
@@ -238,7 +238,7 @@ export async function watch(root, settings, { signal, log = () => {}, startPrevi
238
238
  // A failed answer is kept only as long as a 10 s beat would, never the
239
239
  // 5 minutes a joined success lives, so a retry really asks (#813 review).
240
240
  const heartbeats = settings.heartbeats ??= makeHeartbeatHub({ ttlMs: () => 0.9 * beatBase(), failureTtlMs: 0.9 * beatMs });
241
- settings.registrar ??= makeRegistrar({ ttlMs: REGISTER_REFRESH_MS, failureTtlMs: 0.9 * beatMs });
241
+ settings.registrar ??= makeRegistrar({ ttlMs: REGISTER_REFRESH_MS, failureTtlMs: 0.9 * beatMs, heartbeats });
242
242
  // The claim loop's no-call wait, and its timed wait: a waiting run pushed
243
243
  // to this folder ends both (#813).
244
244
  const nudge = makeLatch();
@@ -7,8 +7,35 @@ import * as runnerApiModule from "./runnerApi.mjs";
7
7
 
8
8
  const retryHint = (out) => (Number.isFinite(out.retryAfterMs) ? { retryAfterMs: out.retryAfterMs } : {});
9
9
 
10
+ /** The update gate every run start passes, a claim or a recovered run (#4949).
11
+ * null while an update waits or installs, so no run starts under it; else
12
+ * the call that says this start has settled. Until then the update counts
13
+ * it, so a request that comes while the start is on its way never installs
14
+ * under it. Call the returned function with setImmediate, after the run is
15
+ * in `liveRuns`. */
16
+ export function runGate(update) {
17
+ if (!update) return () => {};
18
+ if (update.claimStarted) return update.claimStarted();
19
+ return update.holdsRuns() ? null : () => {};
20
+ }
21
+
10
22
  export async function claimOne(root, project, settings, { activeRunIds = [], log } = {}) {
11
23
  const runnerApi = settings.runnerApi ?? runnerApiModule;
24
+ // An update waits for the runs going to end, so no new one starts (#4949).
25
+ const endClaim = runGate(settings.selfUpdate);
26
+ if (!endClaim) return { claimed: false, idle: true, detail: "An update is waiting for runs to finish." };
27
+ try {
28
+ return await claimAdmitted(root, project, settings, runnerApi, { activeRunIds, log });
29
+ } finally {
30
+ // Both callers start the run (runRequest adds it to `liveRuns` before its
31
+ // first await) in the continuation right after this settles. Microtasks
32
+ // run before setImmediate, so the update counts the run before it stops
33
+ // counting the claim.
34
+ setImmediate(endClaim);
35
+ }
36
+ }
37
+
38
+ async function claimAdmitted(root, project, settings, runnerApi, { activeRunIds, log }) {
12
39
  const rowsOpts = { env: settings.env, fetchImpl: settings.fetchImpl };
13
40
  const admission = await acquireAdmission(root);
14
41
  if (!admission.ok) return { claimed: false, transient: true, detail: admission.detail };