viewable-one 0.12.4 → 0.12.6

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,82 @@ package.
13
13
 
14
14
  ## [Unreleased]
15
15
 
16
+ ## [0.12.6] - 2026-11-10
17
+
18
+ ### Fixed
19
+
20
+ - `viewable update`, the Update button in More and Remove act on the copy of
21
+ Viewable that is really installed (#5305). When a login shell starts an
22
+ nvm-installed Viewable with a system Node, the install went to the wrong
23
+ folder. The shared npm resolver in `lib/npm-command.mjs` now pins `--prefix`
24
+ to the installed package's prefix and uses that prefix's own Node and npm
25
+ when present; self-uninstall uses the same resolver. A custom prefix keeps
26
+ its destination, Volta keeps its manager path, and local and npx copies
27
+ update as before. Windows runs `npm-cli.js` without a command shell. A
28
+ permission error keeps its real cause and drops the old running-Node advice.
29
+ - A project folder named `lib` is no longer taken for a global install (#5403).
30
+ `globalPackageDir` called any `<x>/lib/node_modules/viewable-one` global, so
31
+ Update could install into that project and Remove could `npm uninstall -g`
32
+ its copy. On posix a copy is now global only when `<prefix>/bin/viewable`
33
+ exists and resolves to this very file, the shim npm writes on a global
34
+ install. Windows rules are unchanged.
35
+ - Login, logout, doctor, init and uninstall messages show the actual credential
36
+ and registry paths when the computer home is overridden (#5398).
37
+
38
+ ## [0.12.5] - 2026-11-10
39
+
40
+ ### Fixed
41
+
42
+ - `viewable update` and the Update button in More install with the npm next
43
+ to the Node running Viewable, not the first `npm` on the PATH (#5305). On a
44
+ Mac with a system Node and nvm the first one wrote to a folder you cannot
45
+ write to and the message blamed your connection. A failed install now says
46
+ what failed, for example "No permission to write /usr/local/lib/node_modules".
47
+
48
+ - A removed default folder stays removed across restarts (#5290). The
49
+ daemon made and registered the default folder (`~/Glytch`, `~/Viewable` or
50
+ `Documents/Viewable`) on every start, so Remove held only until the next
51
+ restart. `removeFolder` now leaves a marker beside the restore markers,
52
+ `ensureViewableFolder` skips a folder with one, and `addFolder` (init, sync)
53
+ clears it. `ensureViewableFolder` checks and registers under the lock a
54
+ removal takes, so a Remove that lands while the start makes the folder is
55
+ not undone; `viewable forget` takes the lock too, and startup registration
56
+ is one step in the registry (#5310). Nothing is deleted.
57
+ - A Codex run whose app list read ran out of time no longer stops with words
58
+ that blame the person's apps (#5271). A timeout gets its own message ("Codex
59
+ was slow") and one retry at twice the time, in `prepareCodexApps`, the one
60
+ path every caller uses.
61
+
62
+ ### Added
63
+
64
+ - The computer app says goodbye when it is stopped (ruling #4979, #5216).
65
+ On SIGTERM, SIGHUP, SIGBREAK (Windows) or Ctrl+C it writes one last
66
+ presence with `goodbye` set to the signal (`lib/goodbye.mjs`), through the
67
+ shared heartbeat's new `farewell`, which closes the hub so no later beat
68
+ overwrites it, and waits (at most 3 s) for every beat and register already
69
+ on its way, so none lands after it; the shared registrar is tied to the hub
70
+ for this. An OS signal says it at once with a 3 s timeout and exits within
71
+ 7 s; Ctrl+C drains the running sessions first, still beating. The
72
+ next normal beat leaves the field out and so clears it. `viewable update`
73
+ and `viewable stop` leave a `quiet-stop.json` note first, so their SIGTERM
74
+ says nothing; the board's Update restarts in process and never signals.
75
+ Two edge cases (#5308): a register that outlasts that 3 s wait no longer
76
+ erases the goodbye, because the farewell sends it again each time such a
77
+ register lands, until the exit deadline less 0.5 s, and it covers a folder that register named; and Ctrl+C during the first
78
+ registration, before any folder has beaten, still says goodbye, because the
79
+ hub keeps every folder that beats once a stop is asked, even one whose
80
+ watcher then ends (`keepIds`). A stop asked before any beat waits (up to
81
+ that deadline) for the first registration, which names its folders and how
82
+ to write their presence, and says goodbye for them.
83
+ - Sign in to Claude Code from the board (#5216, rulings #4151 and #4200).
84
+ `SIGN_IN_AGENTS` is now `codex` and `claude`; the Claude sign-in runs
85
+ `claude auth login --claudeai` (the Claude plan, never the API console).
86
+ Presence reports `signInAgents`, so the board can tell a computer that can
87
+ start it from an older one. `codexLogin` is replaced by `agentLogin`,
88
+ which finds the binary the way a run does (`resolveAgentBinary`: the
89
+ daemon's PATH, the usual install folders, a login shell) and says "not
90
+ installed" only when none has it, for Codex too.
91
+
16
92
  ## [0.12.4] - 2026-11-09
17
93
 
18
94
  ### Added
package/glytch.mjs CHANGED
@@ -40,13 +40,13 @@ import { resolve } from "node:path";
40
40
  import { homedir } from "node:os";
41
41
  import { heading, checkSections, summary, homeNotice, wrap, bold, colorEnabled, dim, fail, hint, ok, step, warn, warnRow } from "./lib/cli-output.mjs";
42
42
 
43
- import { login as hostedLogin, logout as hostedLogout } from "./lib/auth.mjs";
43
+ import { authDisplayPath, login as hostedLogin, logout as hostedLogout } from "./lib/auth.mjs";
44
44
  import { detectAgents, detectionLines, execProbe } from "./lib/detect.mjs";
45
45
  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";
@@ -55,6 +55,7 @@ import { initOptions, chooseAgents, readAgentSelection, saveAgentSelection } fro
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
@@ -383,7 +384,7 @@ async function login() {
383
384
  say("");
384
385
  say(ok(`Signed in to ${stored.appUrl}.`, { color }));
385
386
  say(`Board tools on your computer now reach ${stored.mcpUrl}: no app tab, no token to paste.`);
386
- say(`Saved to ~/.glytch/auth.json (mode 0600), or GLYTCH_HOME when that is set.`);
387
+ say(`Saved to ${authDisplayPath()} (mode 0600).`);
387
388
  return 0;
388
389
  }
389
390
 
@@ -391,7 +392,7 @@ async function logout() {
391
392
  const color = colorEnabled();
392
393
  say(heading("Viewable · Sign out", { color }));
393
394
  const removed = await hostedLogout();
394
- say(removed ? ok("Signed out. ~/.glytch/auth.json removed.", { color }) : warn("Not signed in, nothing to remove.", { color }));
395
+ say(removed ? ok(`Signed out. ${authDisplayPath()} removed.`, { color }) : warn("Not signed in, nothing to remove.", { color }));
395
396
  return 0;
396
397
  }
397
398
 
@@ -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,18 +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
- const watched = await watchRegistered({ settings, signal: controller.signal, log });
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 });
479
484
  // The board's Update installed a new version (#4949): exit nonzero so
480
485
  // launchd, systemd and Task Scheduler each start the new code.
481
486
  if (watched?.restart) {
482
487
  log(`restarting on the new version`);
483
488
  return UPDATE_RESTART_EXIT_CODE;
484
489
  }
485
- return null;
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;
486
493
  }
487
494
 
488
495
  async function main() {
package/lib/auth.mjs CHANGED
@@ -49,7 +49,7 @@ import { createServer } from "node:http";
49
49
  import { spawn } from "node:child_process";
50
50
  import { join } from "node:path";
51
51
 
52
- import { viewableHome } from "./registry.mjs";
52
+ import { viewableHome, viewableDisplayPath } from "./registry.mjs";
53
53
  import { writeFileAtomic } from "./atomic.mjs";
54
54
  import { movedAuth } from "./retired-address.mjs";
55
55
 
@@ -94,6 +94,11 @@ const EXCHANGE_TIMEOUT_MS = 60_000;
94
94
 
95
95
  const authFilePath = (env = process.env) => join(viewableHome(env), "auth.json");
96
96
 
97
+ /** Match the storage resolver, preserving the familiar default-home spelling. */
98
+ export function authDisplayPath(env = process.env) {
99
+ return viewableDisplayPath(env, "auth.json");
100
+ }
101
+
97
102
  const trimTrailingSlash = (s) => String(s).replace(/\/+$/, "");
98
103
 
99
104
  /** The app origin this run should use: the explicit argument, then
@@ -1329,9 +1334,9 @@ export async function login({
1329
1334
  await writeAuthFile(result, env);
1330
1335
  log(
1331
1336
  keepsOAuth
1332
- ? "VIEWABLE_BOARD_TOKEN is set - saved it to ~/.glytch/auth.json as a personal access token, keeping the " +
1337
+ ? `VIEWABLE_BOARD_TOKEN is set - saved it to ${authDisplayPath(env)} as a personal access token, keeping the ` +
1333
1338
  "OAuth sign-in already there beside it. No browser needed."
1334
- : "VIEWABLE_BOARD_TOKEN is set - saved it to ~/.glytch/auth.json as a personal access token. No browser needed.",
1339
+ : `VIEWABLE_BOARD_TOKEN is set - saved it to ${authDisplayPath(env)} as a personal access token. No browser needed.`,
1335
1340
  );
1336
1341
  return result;
1337
1342
  }
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();
package/lib/doctor.mjs CHANGED
@@ -46,7 +46,7 @@ import { projectMcpServerKey } from "./project-mcp.mjs";
46
46
  import { syncFolder } from "./sync.mjs";
47
47
  import { readAgentSelection } from "./agent-selection.mjs";
48
48
  import { compareVersions, latestFromNpm, packageVersion, verifyInstalledCli } from "./update.mjs";
49
- import { PERSONAL_TOKEN_REJECTED_HINT, REAUTH_REQUIRED_HINT, hostedStatus } from "./auth.mjs";
49
+ import { authDisplayPath, PERSONAL_TOKEN_REJECTED_HINT, REAUTH_REQUIRED_HINT, hostedStatus } from "./auth.mjs";
50
50
  import { presence as hostedPresence } from "./runnerApi.mjs";
51
51
 
52
52
  // `row` is imported from cli-output.mjs (brief 31 review, 2026-09-12 - it
@@ -377,7 +377,7 @@ export async function doctorRows(
377
377
  "board sign-in",
378
378
  false,
379
379
  "rejected",
380
- `the personal token in ~/.glytch/auth.json was rejected by the board${boardAuth.deadSince ? ` (since ${boardAuth.deadSince})` : ""}`,
380
+ `the personal token in ${authDisplayPath(env)} was rejected by the board${boardAuth.deadSince ? ` (since ${boardAuth.deadSince})` : ""}`,
381
381
  PERSONAL_TOKEN_REJECTED_HINT,
382
382
  )
383
383
  : row(
@@ -385,7 +385,7 @@ export async function doctorRows(
385
385
  "board sign-in",
386
386
  false,
387
387
  "expired",
388
- `the credential in ~/.glytch/auth.json was refused by the board${boardAuth.deadSince ? ` (since ${boardAuth.deadSince})` : ""} and cannot be renewed`,
388
+ `the credential in ${authDisplayPath(env)} was refused by the board${boardAuth.deadSince ? ` (since ${boardAuth.deadSince})` : ""} and cannot be renewed`,
389
389
  REAUTH_REQUIRED_HINT,
390
390
  )
391
391
  : boardAuth.signedIn
@@ -410,8 +410,8 @@ export async function doctorRows(
410
410
  (boardAuth.via === "VIEWABLE_BOARD_TOKEN"
411
411
  ? "VIEWABLE_BOARD_TOKEN is set"
412
412
  : boardAuth.via === "personal token"
413
- ? "a personal access token is stored in ~/.glytch/auth.json"
414
- : "~/.glytch/auth.json is there"),
413
+ ? `a personal access token is stored in ${authDisplayPath(env)}`
414
+ : `${authDisplayPath(env)} is there`),
415
415
  )
416
416
  : row(
417
417
  "boardAuth",
@@ -419,7 +419,7 @@ export async function doctorRows(
419
419
  false,
420
420
  "not signed in",
421
421
  "run `viewable login`, or set VIEWABLE_BOARD_TOKEN to a personal access token for a script",
422
- "Run `viewable login`. It opens a browser to sign in and approve, and the credential lands in ~/.glytch/auth.json. Re-running `viewable init` does not do this step.",
422
+ `Run \`viewable login\`. It opens a browser to sign in and approve, and the credential lands in ${authDisplayPath(env)}. Re-running \`viewable init\` does not do this step.`,
423
423
  ),
424
424
  );
425
425
 
@@ -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
+ }
@@ -34,7 +34,7 @@
34
34
  // are seams, every test asserts the argv sequence, and NOTHING in the suite
35
35
  // runs claude, codex, opencode or a browser on the machine running it.
36
36
 
37
- import { hostedStatus, login as hostedLogin, readAuthFile } from "./auth.mjs";
37
+ import { authDisplayPath, hostedStatus, login as hostedLogin, readAuthFile } from "./auth.mjs";
38
38
  import { projectMcpServerKey } from "./project-mcp.mjs";
39
39
  import { execProbe, runInteractive } from "./detect.mjs";
40
40
  import { compareVersions } from "./update.mjs";
@@ -209,7 +209,7 @@ export async function signInStep({
209
209
  }
210
210
  try {
211
211
  const stored = await login({ env, log: (line) => log(hint(line, options)) });
212
- return settle("ok", `VIEWABLE_BOARD_TOKEN saved to ~/.glytch/auth.json (${stored.appUrl})`);
212
+ return settle("ok", `VIEWABLE_BOARD_TOKEN saved to ${authDisplayPath(env)} (${stored.appUrl})`);
213
213
  } catch (error) {
214
214
  return settle("fail", error instanceof Error ? error.message : String(error));
215
215
  }
@@ -53,6 +53,7 @@ import { syncFolder } from "./sync.mjs";
53
53
  import { makeSelfUpdate, makeUpdateChecker, packageVersion } from "./update.mjs";
54
54
  import { liveRuns } from "./restartPass.mjs";
55
55
  import { activeRecoveryRunIds } from "./runnerRecovery.mjs";
56
+ import { GOODBYE_WAIT_MS } from "./goodbye.mjs";
56
57
  import * as runnerApiModule from "./runnerApi.mjs";
57
58
 
58
59
  export const SWEEP_INTERVAL_MS = 86_400_000;
@@ -79,7 +80,11 @@ const isDir = async (path) => {
79
80
  * Returns {watched, missing} after signal-driven shutdown and after every
80
81
  * folder's watch has ended. An empty registry still waits for new folders.
81
82
  * `restart: true` means the board's Update installed a new version and the
82
- * caller should exit so the service manager starts it (#4949). */
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. */
83
88
  export async function watchRegistered({
84
89
  env = process.env,
85
90
  settings,
@@ -112,6 +117,7 @@ export async function watchRegistered({
112
117
  makeRealtime = makeRunnerRealtime,
113
118
  // THE BOARD'S UPDATE BUTTON (#4949). Injected for the tests.
114
119
  makeSelfUpdater = makeSelfUpdate,
120
+ goodbye,
115
121
  } = {}) {
116
122
  // An installed update stops every watcher the same way Ctrl-C does: each
117
123
  // drains the runs it started (there are none by then) before it ends.
@@ -244,7 +250,6 @@ export async function watchRegistered({
244
250
  // repeats an unchanged list every 5 minutes, and one heartbeat hub, which
245
251
  // sends one heartbeat for all of them per beat (lib/runnerPace.mjs).
246
252
  const beatMs = settings?.beatMs ?? RUNNER_BEAT_MS;
247
- const registrar = makeRegistrar({ ttlMs: REGISTER_REFRESH_MS, failureTtlMs: 0.9 * beatMs });
248
253
  const runnerId = settings?.runnerId ?? newRunnerId();
249
254
  // PUSH (#813): joined, every folder beats every 5 minutes and the hub's
250
255
  // shared answer lives as long, so the folders still share one heartbeat.
@@ -260,12 +265,28 @@ export async function watchRegistered({
260
265
  ttlMs: () => 0.9 * beatBaseMs(realtime, beatMs, settings?.pushBeatMs),
261
266
  failureTtlMs: 0.9 * beatMs,
262
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 });
263
270
  realtime?.start();
264
271
  // A BEAT ON REQUEST (#813 review). `glytch init` in a folder this daemon
265
272
  // already watches leaves it running and waits for a beat that came after
266
273
  // it started (runner-health.mjs); joined, the next one could be 5 minutes
267
274
  // away. init rewrites the registry instead, and every watcher beats once,
268
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
+ });
269
290
  const beatAsks = new Set();
270
291
  const beatRequests = { subscribe: (fn) => { beatAsks.add(fn); return () => beatAsks.delete(fn); } };
271
292
  askBeat = () => {
@@ -453,6 +474,8 @@ export async function watchRegistered({
453
474
  } finally {
454
475
  clearInterval(keepAlive);
455
476
  for (const entry of running.values()) clearTimeout(entry.retry);
477
+ unsubscribeGoodbye?.();
478
+ if (goodbye?.value && !restarting) await sayGoodbye();
456
479
  await realtime?.close();
457
480
  signal?.removeEventListener("abort", bump);
458
481
  clearInterval(sweeping);
@@ -0,0 +1,68 @@
1
+ // Shared npm targeting for updates and removal. The installed package owns
2
+ // the prefix; env node may have started it with an unrelated Node (#5305).
3
+ import { existsSync, realpathSync } from "node:fs";
4
+ import { posix, win32 } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { runnableCommand } from "./windows-command.mjs";
7
+
8
+ const CLI_PATH = fileURLToPath(new URL("../glytch.mjs", import.meta.url));
9
+
10
+ /** A POSIX prefix owns this copy only when its own bin/viewable shim resolves
11
+ * to this very file. A folder shaped like `<prefix>/lib/node_modules` proves
12
+ * nothing: a project directory named `lib` has the same shape (#5403). */
13
+ function ownsShim(path, prefix, cliPath, { exists, resolvePath }) {
14
+ const shim = path.join(prefix, "bin", "viewable");
15
+ try { return exists(shim) && resolvePath(shim) === cliPath; } catch { return false; }
16
+ }
17
+
18
+ /** Extract the global package directory (formerly in selfUninstall). Never
19
+ * treat a checkout, local dependency or npx cache as a global installation. */
20
+ export function globalPackageDir(cliPath, { platform = process.platform, env = process.env, nodePath = process.execPath, exists = existsSync, resolvePath = realpathSync } = {}) {
21
+ const path = platform === "win32" ? win32 : posix;
22
+ try { cliPath = resolvePath(cliPath); } catch { return null; }
23
+ const dir = path.dirname(cliPath);
24
+ if (path.basename(dir) !== "viewable-one" || path.basename(path.dirname(dir)) !== "node_modules") return null;
25
+ if (/[\\/]_npx[\\/]/.test(dir)) return null;
26
+ const parent = path.dirname(path.dirname(dir));
27
+ if (platform !== "win32") return path.basename(parent) === "lib" && ownsShim(path, path.dirname(parent), cliPath, { exists, resolvePath }) ? dir : null;
28
+ // Windows global packages have command shims in their prefix. Local
29
+ // dependencies put those shims in node_modules/.bin instead.
30
+ const appData = env.APPDATA ? path.join(env.APPDATA, "npm") : "";
31
+ return parent.toLowerCase() === appData.toLowerCase() || parent.toLowerCase() === path.dirname(nodePath).toLowerCase()
32
+ || exists(path.join(parent, "viewable.cmd")) ? dir : null;
33
+ }
34
+
35
+ export function npmPathFor({ platform = process.platform, env = process.env, nodePath = process.execPath, exists = existsSync } = {}) {
36
+ const path = platform === "win32" ? win32 : posix;
37
+ const nodeDir = path.dirname(nodePath);
38
+ const voltaHome = String(env?.VOLTA_HOME ?? "");
39
+ if (/[\\/]tools[\\/]image[\\/]node[\\/]/.test(nodePath) || (voltaHome && nodePath.startsWith(voltaHome))) return env;
40
+ if (!exists(path.join(nodeDir, platform === "win32" ? "npm.cmd" : "npm"))) return env;
41
+ const key = Object.keys(env ?? {}).find((k) => (platform === "win32" ? k.toUpperCase() === "PATH" : k === "PATH")) ?? "PATH";
42
+ const rest = String(env?.[key] ?? "").split(path.delimiter).filter((dir) => dir && dir !== nodeDir);
43
+ return { ...env, [key]: [nodeDir, ...rest].join(path.delimiter) };
44
+ }
45
+
46
+ /** Resolve once before spawning, including before self-uninstall deletes us.
47
+ * Volta owns its package image, so its shim must retain control of the prefix.
48
+ * Custom global prefixes may have no Node; pin the destination regardless. */
49
+ export function npmCommand(args, { platform = process.platform, env = process.env, nodePath = process.execPath, cliPath = CLI_PATH, exists = existsSync, resolvePath = realpathSync, readFile } = {}) {
50
+ const path = platform === "win32" ? win32 : posix;
51
+ const packageDir = globalPackageDir(cliPath, { platform, env, nodePath, exists, resolvePath });
52
+ const volta = packageDir && /[\\/]tools[\\/]image[\\/]packages[\\/]/.test(packageDir);
53
+ const prefix = packageDir && !volta ? path.resolve(packageDir, platform === "win32" ? "../.." : "../../..") : null;
54
+ if (prefix) {
55
+ const bin = platform === "win32" ? prefix : path.join(prefix, "bin");
56
+ const owningNode = path.join(bin, platform === "win32" ? "node.exe" : "node");
57
+ const npm = platform === "win32" ? path.join(bin, "node_modules/npm/bin/npm-cli.js") : path.join(bin, "npm");
58
+ if (exists(owningNode) && exists(npm)) nodePath = owningNode;
59
+ args = [...args, "--prefix", prefix];
60
+ }
61
+ const npmEnv = volta ? env : npmPathFor({ platform, env, nodePath, exists });
62
+ const cli = path.join(path.dirname(nodePath), "node_modules/npm/bin/npm-cli.js");
63
+ // Node's npm.cmd uses variables that the generic shim parser refuses.
64
+ const command = !volta && platform === "win32" && exists(cli)
65
+ ? { file: nodePath, args: [cli, ...args], shell: false }
66
+ : runnableCommand("npm", args, { platform, env: npmEnv, nodePath, exists, ...(readFile ? { readFile } : {}) });
67
+ return { ...command, env: npmEnv, packageDir };
68
+ }