viewable-one 0.12.4 → 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,60 @@ 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
+
16
70
  ## [0.12.4] - 2026-11-09
17
71
 
18
72
  ### Added
package/glytch.mjs CHANGED
@@ -46,7 +46,7 @@ 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
@@ -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/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
+ }
@@ -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);
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);
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();
@@ -158,7 +158,12 @@ export function makeBeatLoop(w) {
158
158
  const runnerApi = settings.runnerApi ?? runnerApiModule;
159
159
  const seen = w.hintSeq;
160
160
  await refreshProjectPaths(root, settings);
161
- const beat = await heartbeats.beat(w.project.id, (projectIds) => runnerApi.heartbeat({ projectIds, presence: presenceBody(settings) }, { env: settings.env, fetchImpl: settings.fetchImpl }));
161
+ // The hub's goodbye (ruling #4979) sends through this same writer, with
162
+ // `goodbye` and a short `timeoutMs` (lib/goodbye.mjs).
163
+ const beat = await heartbeats.beat(w.project.id, (projectIds, { goodbye, timeoutMs } = {}) => runnerApi.heartbeat(
164
+ { projectIds, presence: presenceBody(settings, { goodbye }) },
165
+ { env: settings.env, fetchImpl: settings.fetchImpl, ...(timeoutMs ? { timeoutMs } : {}) },
166
+ ));
162
167
  if (!beat.ok) {
163
168
  clearRefusedProject(beat);
164
169
  log(`heartbeat failed: ${beat.error}`);
@@ -365,7 +370,7 @@ async function refreshRegistration(root, settings, runnerApi) {
365
370
  const refreshSettings = {
366
371
  ...settings,
367
372
  registrar: {
368
- register: (key, send) => settings.registrar.register(key, async () => {
373
+ register: (key, send, writer) => settings.registrar.register(key, async () => {
369
374
  // Row ops may have awaited a slow merge after the beat snapshot.
370
375
  // Bypass the heartbeat cache, only when register is actually due.
371
376
  // The remaining read/write gap is closed server-side by
@@ -389,7 +394,7 @@ async function refreshRegistration(root, settings, runnerApi) {
389
394
  return { ok: false, error: "Registration deferred: a folder removal is pending." };
390
395
  }
391
396
  return send();
392
- }),
397
+ }, writer),
393
398
  },
394
399
  };
395
400
  const reg = await registerAndFindProject(root, refreshSettings);
@@ -13,7 +13,7 @@ import { AGENTS, agentFor, isCodingCli } from "./agents.mjs";
13
13
  import { resolveAgentBinary } from "./detect.mjs";
14
14
  import { imageAttachments } from "./imageAttachments.mjs";
15
15
  import { checkRequest, isChatTurn, isSignIn, titleFor } from "./spawn.mjs";
16
- import { codexLogin } from "./signIn.mjs";
16
+ import { agentLogin } from "./signIn.mjs";
17
17
  import { fromIdOf } from "./boardside.mjs";
18
18
  import { chatBoardOf, makeBoardCwd } from "./viewableFolder.mjs";
19
19
  import { defaultBranchOf, git, makeChatWorktree, resolveChatCwd, worktreeBranch, worktreePath, worktreeSummary } from "./worktree.mjs";
@@ -124,13 +124,14 @@ export async function admitRequest({ project, root, id, request, isChat, runnerA
124
124
  return { patch: { status: "error", result: `ERROR\n\nRefused: ${problems.join("\n")}\n`, finished_at: new Date().toISOString() } };
125
125
  }
126
126
 
127
- // SIGN IN TO CODEX (#482, lib/signIn.mjs): `codex login` opens the sign-in
128
- // page in this computer's browser. Then the agents are probed again, so the
129
- // app's sign-in box goes as soon as Codex says it is signed in rather than
130
- // on the probe's own five-minute clock.
127
+ // SIGN IN TO AN AGENT (#482, #5216, lib/signIn.mjs): `codex login` or
128
+ // `claude auth login` opens the sign-in page in this computer's browser.
129
+ // Then the agents are probed again, so the app's sign-in box goes as soon
130
+ // as the agent says it is signed in rather than on the probe's own
131
+ // five-minute clock.
131
132
  if (isSignIn(request)) {
132
133
  log(`[${id}] signing in to ${request.agent}`);
133
- const signedIn = await (settings.codexLogin ?? codexLogin)({ env: settings.baseEnv ?? process.env });
134
+ const signedIn = await (settings.agentLogin ?? agentLogin)(request.agent, { env: settings.baseEnv ?? process.env });
134
135
  await settings.refreshAgents?.();
135
136
  return { patch: { status: signedIn.ok ? "done" : "error", result: `${signedIn.ok ? "OK" : "ERROR"}\n\n${signedIn.detail}\n`, finished_at: new Date().toISOString() } };
136
137
  }
@@ -40,6 +40,8 @@
40
40
  // full runs-at-once count, a local lock) keeps the base interval, because none of
41
41
  // those get better by calling less often and none of them load the server.
42
42
 
43
+ import { GOODBYE_EXIT_MS } from "./goodbye.mjs";
44
+
43
45
  /** The wait after `failures` server errors in a row: base * 2^(n-1), capped,
44
46
  * then jittered down by up to 20% so many runners do not retry in step. Never
45
47
  * shorter than the base interval. */
@@ -148,18 +150,40 @@ function shareAnswer(send, { at, ttlMs, failureTtlMs }) {
148
150
  }
149
151
  const fresh = (entry, at) => entry.pending || at < entry.expiresAt;
150
152
 
153
+ /** How long before the exit a late goodbye is no longer started (#5308). */
154
+ const EXIT_MARGIN_MS = 500;
155
+
156
+ /** What a beat or register answers once the computer said goodbye. */
157
+ const SAID_GOODBYE = Object.freeze({ ok: false, transient: true, error: "This computer said goodbye." });
158
+
151
159
  /** Coalesce `register` across the folders of one process (ticket e8 item 3).
152
160
  * Every folder's beat registers the whole folder list, so the second and third
153
161
  * folder beating inside the same window would send exactly the same call
154
162
  * again. Within `ttlMs` of the last register for the same list, or while it is
155
163
  * still in flight, callers share its answer; a failure for `failureTtlMs`. */
156
- export function makeRegistrar({ ttlMs, failureTtlMs = ttlMs, now = Date.now }) {
164
+ export function makeRegistrar({ ttlMs, failureTtlMs = ttlMs, now = Date.now, heartbeats = null }) {
157
165
  let last = null;
158
166
  return {
159
- register(key, send) {
167
+ /** A register writes presence too, without the goodbye. With the
168
+ * process's `heartbeats` hub, each one is held in the hub's in-flight
169
+ * set, so the goodbye waits for it, and none starts after the goodbye
170
+ * (ruling #4979). `writer(projectIds, {goodbye, timeoutMs})` is how to
171
+ * write a presence for the folders it registers: a stop during the first
172
+ * register, before any beat, still says goodbye through it (#5308). */
173
+ register(key, send, writer = null) {
174
+ if (heartbeats?.saidGoodbye) return Promise.resolve(SAID_GOODBYE);
160
175
  const at = now();
161
176
  if (last && last.key === key && fresh(last, at)) return last.promise;
162
- last = Object.assign(shareAnswer(send, { at, ttlMs, failureTtlMs }), { key });
177
+ const learning = writer && heartbeats?.learn
178
+ ? async () => {
179
+ const answer = await send();
180
+ if (answer?.ok === true) heartbeats.learn((answer.projects ?? []).map((project) => project?.id).filter(Boolean), writer);
181
+ return answer;
182
+ }
183
+ : send;
184
+ last = Object.assign(shareAnswer(learning, { at, ttlMs, failureTtlMs }), { key });
185
+ // Held from now, not from when shareAnswer calls `send` a microtask later.
186
+ heartbeats?.hold(last.promise);
163
187
  return last.promise;
164
188
  },
165
189
  // A login to another account makes every cached project id obsolete.
@@ -206,7 +230,20 @@ export function makeRegistrar({ ttlMs, failureTtlMs = ttlMs, now = Date.now }) {
206
230
  * call and not the cached failure. A newer `invalidate(at)` makes existing answers
207
231
  * stale, including one started in the same millisecond, so the next beat really
208
232
  * asks: a join, a dropped socket or an op event. Every folder hearing the same event passes the same `at`, so they
209
- * still share the one call that follows. */
233
+ * still share the one call that follows.
234
+ *
235
+ * GOODBYE (ruling #4979, lib/goodbye.mjs). `farewell(projectIds, extra)` is
236
+ * the last beat: it closes the hub, so no beat or register starts after it,
237
+ * waits for every beat and register already on its way (`hold`, at most
238
+ * `extra.timeoutMs`), so none lands after it and replaces the presence, then
239
+ * sends once for every folder through the last `send` a folder gave, with
240
+ * `extra` (`{goodbye, timeoutMs}`) as its second argument. A write that is
241
+ * still on its way after that wait cannot be cancelled, so each time one
242
+ * settles the goodbye is sent again and lands last, until the process exit
243
+ * (`exitMs`, GOODBYE_EXIT_MS) less a margin (#5308). `ids()` lists the
244
+ * folders that have beaten and not left;
245
+ * `keepIds()` starts keeping every folder that beats from then on, leavers
246
+ * too, which the farewell adds to the ones it is given. */
210
247
  export function makeHeartbeatHub({ ttlMs, memberTtlMs, failureTtlMs, now = Date.now }) {
211
248
  const ttl = () => (typeof ttlMs === "function" ? ttlMs() : ttlMs);
212
249
  const failureTtl = () => Math.min(typeof failureTtlMs === "function" ? failureTtlMs() : failureTtlMs ?? Infinity, ttl());
@@ -218,8 +255,23 @@ export function makeHeartbeatHub({ ttlMs, memberTtlMs, failureTtlMs, now = Date.
218
255
  let generation = 0;
219
256
  let batching = true;
220
257
  const covered = (answer, ids) => (answer && typeof answer === "object" ? { ...answer, coveredProjectIds: ids } : answer);
258
+ const beaten = new Set(); // every folder that beat and has not left, for the goodbye
259
+ let kept = null; // once a stop is asked: every folder that beat since, even one that then left (#5308)
260
+ const inFlight = new Set();
261
+ let lastSend = null;
262
+ // Folders a register named and the way to write their presence, for a
263
+ // goodbye asked before any of them beat (#5308).
264
+ const registered = new Set();
265
+ let registerSend = null;
266
+ let farewell = null;
267
+ const track = (sending) => {
268
+ const settled = Promise.resolve(sending).catch(() => {}).finally(() => inFlight.delete(settled));
269
+ inFlight.add(settled);
270
+ return sending;
271
+ };
221
272
  const single = async (projectId, send) => {
222
- const answer = await send([projectId]);
273
+ if (farewell) return covered(SAID_GOODBYE, [projectId]);
274
+ const answer = await track(send([projectId]));
223
275
  if (batching) {
224
276
  if (answer?.ok === false && answer.transient !== true) alone.add(projectId);
225
277
  else if (answer?.ok === true) alone.delete(projectId);
@@ -231,6 +283,10 @@ export function makeHeartbeatHub({ ttlMs, memberTtlMs, failureTtlMs, now = Date.
231
283
  return batching;
232
284
  },
233
285
  async beat(projectId, send) {
286
+ if (farewell) return covered(SAID_GOODBYE, [projectId]);
287
+ beaten.add(projectId);
288
+ kept?.add(projectId);
289
+ lastSend = send;
234
290
  if (!batching || alone.has(projectId)) return single(projectId, send);
235
291
  const at = now();
236
292
  members.set(projectId, at);
@@ -241,6 +297,9 @@ export function makeHeartbeatHub({ ttlMs, memberTtlMs, failureTtlMs, now = Date.
241
297
  const ids = [...members.keys()].sort();
242
298
  const ttlNow = ttl();
243
299
  entry = Object.assign(shareAnswer(() => send(ids), { at, ttlMs: ttlNow, failureTtlMs: failureTtl() }), { ids, generation });
300
+ // In flight from now: shareAnswer calls `send` a microtask later, and
301
+ // a goodbye asked in between must still wait for this beat.
302
+ track(entry.promise);
244
303
  last = entry;
245
304
  }
246
305
  const answer = await entry.promise;
@@ -258,10 +317,80 @@ export function makeHeartbeatHub({ ttlMs, memberTtlMs, failureTtlMs, now = Date.
258
317
  return covered(answer, entry.ids);
259
318
  },
260
319
  leave(projectId) {
320
+ beaten.delete(projectId);
321
+ registered.delete(projectId);
261
322
  members.delete(projectId);
262
323
  alone.delete(projectId);
263
324
  if (last?.ids.includes(projectId)) last = null;
264
325
  },
326
+ ids() {
327
+ return [...beaten].sort();
328
+ },
329
+ /** A stop was asked: from now on, remember every folder that beats, and
330
+ * keep the ones that leave, so the goodbye covers a folder whose first
331
+ * beat comes only while the process shuts down and whose watcher ends
332
+ * before the goodbye is sent (#5308). Folders beaten so far are kept. */
333
+ keepIds() {
334
+ kept ??= new Set(beaten);
335
+ },
336
+ get saidGoodbye() {
337
+ return farewell !== null;
338
+ },
339
+ /** Hold a presence write that is not a beat (a register) in flight. */
340
+ hold(sending) {
341
+ return track(sending);
342
+ },
343
+ /** A register that answered names its folders, so a goodbye still has
344
+ * them when that register was the only thing on its way. */
345
+ learn(projectIds, send) {
346
+ for (const id of projectIds) registered.add(id);
347
+ registerSend = send;
348
+ },
349
+ farewell(projectIds, extra, { waitMs = extra?.timeoutMs ?? 3_000, exitMs = GOODBYE_EXIT_MS } = {}) {
350
+ farewell ??= (async () => {
351
+ const started = now();
352
+ const deadline = started + exitMs - EXIT_MARGIN_MS;
353
+ // Read at each goodbye: a registration that lands late names folders
354
+ // too (#5308).
355
+ const idsNow = () => [...new Set([...projectIds, ...(kept ?? []), ...registered])].sort();
356
+ const ready = () => (lastSend ?? registerSend) && idsNow().length > 0;
357
+ const waitFor = async (pending) => {
358
+ const timer = new AbortController();
359
+ await Promise.race([...pending, sleep(deadline - now(), timer.signal)]);
360
+ timer.abort();
361
+ };
362
+ if (inFlight.size > 0) await Promise.race([Promise.all([...inFlight]), sleep(waitMs)]);
363
+ // No folder is known yet: a first registration still on its way will
364
+ // name them, so wait for it up to the exit deadline before giving up.
365
+ while (!ready() && inFlight.size > 0 && deadline - now() > 0) await waitFor([...inFlight]);
366
+ if (!ready()) return { ok: false, error: "No folder had beaten yet." };
367
+ // A write that outlasted the wait cannot be called back, and it may
368
+ // land after the goodbye and replace it. Fence it: each time one
369
+ // settles, say goodbye again, until the exit deadline (#5308).
370
+ const stragglers = [...inFlight];
371
+ const say = async () => {
372
+ try { return await (lastSend ?? registerSend)(idsNow(), extra); }
373
+ catch (error) { return { ok: false, error: error instanceof Error ? error.message : String(error) }; }
374
+ };
375
+ let result = await say();
376
+ const answered = new Set();
377
+ for (;;) {
378
+ const landed = stragglers.filter((late) => !inFlight.has(late) && !answered.has(late));
379
+ if (landed.length > 0) {
380
+ for (const late of landed) answered.add(late);
381
+ // The corrective send is the last word, ok or not: the board may
382
+ // read the late write's presence, so an earlier ok is not true.
383
+ result = await say();
384
+ continue;
385
+ }
386
+ const open = stragglers.filter((late) => inFlight.has(late));
387
+ if (open.length === 0 || deadline - now() <= 0) break;
388
+ await waitFor(open);
389
+ }
390
+ return result;
391
+ })();
392
+ return farewell;
393
+ },
265
394
  invalidate(at = now()) {
266
395
  if (at > notBefore) {
267
396
  notBefore = at;
@@ -9,6 +9,7 @@ import { basename } from "node:path";
9
9
  import * as runnerApiModule from "./runnerApi.mjs";
10
10
  import { addFolder, foldersWithoutGit, isScratchFolder, markFolderRestore, readRegistry, readRegistryChecked, withRegistryLock } from "./registry.mjs";
11
11
  import { platformMark } from "./platform.mjs";
12
+ import { SIGN_IN_AGENTS } from "./signIn.mjs";
12
13
 
13
14
  /** `register` every folder this machine knows about, plus `root` itself as
14
15
  * a fallback for a single-folder invocation (PM_BOARD_ROOT) that was never
@@ -31,8 +32,16 @@ import { platformMark } from "./platform.mjs";
31
32
  * anyone who queries it at the wrong moment.
32
33
  *
33
34
  * Two writers of one body is how that happened, so there is one now.
35
+ *
36
+ * `signInAgents` names the agents whose sign-in the board can start here
37
+ * (lib/signIn.mjs); a computer on an older version leaves it out, and the
38
+ * board keeps its paste fallback for those (#5216, #5291).
39
+ *
40
+ * `goodbye` is the last beat of a computer that is being turned off,
41
+ * restarted or signed out of (ruling #4979, lib/goodbye.mjs). The next beat
42
+ * leaves it out, and since a beat replaces the presence, that clears it.
34
43
  */
35
- export const presenceBody = (settings) => {
44
+ export const presenceBody = (settings, { goodbye } = {}) => {
36
45
  const { platform: _platform, ...rest } = settings.markExtra?.() ?? {};
37
46
  // A scratch folder is never registered, so it is never reported either:
38
47
  // the app would otherwise show an old one still on disk again (#3644).
@@ -41,7 +50,7 @@ export const presenceBody = (settings) => {
41
50
  try { return statSync(path).isDirectory(); }
42
51
  catch (error) { return error.code !== "ENOENT" && error.code !== "ENOTDIR"; }
43
52
  });
44
- return { ...rest, ...(availableFolders ? { availableFolders } : {}), planApproval: true, computerAppsLook: true, folderReads: true, uninstallRequests: true, ...(settings.noGit?.length ? { noGit: settings.noGit } : {}) };
53
+ return { ...rest, ...(availableFolders ? { availableFolders } : {}), planApproval: true, computerAppsLook: true, folderReads: true, uninstallRequests: true, signInAgents: SIGN_IN_AGENTS, ...(settings.noGit?.length ? { noGit: settings.noGit } : {}), ...(goodbye ? { goodbye } : {}) };
45
54
  };
46
55
 
47
56
  /** Re-read the machine's folder list into `settings.projectPaths` before a
@@ -110,7 +119,12 @@ async function registerProject(root, settings, { readd = false, onlyRoot = false
110
119
  // ONE REGISTER PER PROCESS PER BEAT (ticket e8). multiwatch hands every
111
120
  // folder the same `registrar`, so the folders that beat inside one window
112
121
  // share one call for the same folder list instead of each sending it.
113
- const out = settings.registrar ? await settings.registrar.register(JSON.stringify(list), send) : await send();
122
+ // `writer` lets a goodbye reach these folders when no beat has yet (#5309).
123
+ const writer = (projectIds, { goodbye, timeoutMs } = {}) => runnerApi.heartbeat(
124
+ { projectIds, presence: presenceBody(settings, { goodbye }) },
125
+ { env, fetchImpl: settings.fetchImpl, ...(timeoutMs ? { timeoutMs } : {}) },
126
+ );
127
+ const out = settings.registrar ? await settings.registrar.register(JSON.stringify(list), send, writer) : await send();
114
128
  if (!out.ok) return { ok: false, error: out.error, ...(readd ? { readdRequired: Boolean(readdForgottenAt) } : {}), ...(out.transient ? { transient: true } : {}), ...(out.unauthorized ? { unauthorized: true } : {}), ...(Number.isFinite(out.retryAfterMs) ? { retryAfterMs: out.retryAfterMs } : {}) };
115
129
  const mine = (out.projects ?? []).find((p) => p.path === root);
116
130
  return { ok: true, projects: out.projects ?? [], myProjectId: mine?.id, runnerId };
package/lib/signIn.mjs CHANGED
@@ -1,27 +1,52 @@
1
- // SIGN IN TO CODEX FROM THE BOARD (#482, ruling #470: "the Codex sign-in
2
- // page opened for you"). The app files a run row whose request is
3
- // `{kind: "sign-in", agent: "codex"}`; the runner answers it here by
4
- // starting `codex login` on this computer. Codex opens the ChatGPT sign-in
5
- // page in this computer's browser and exits once the sign-in lands, so no
6
- // one types in a terminal. The runner then probes the agents again, and the
7
- // app's box goes once the probe says Codex is signed in.
1
+ // SIGN IN TO AN AGENT FROM THE BOARD (#482, ruling #470: "the Codex sign-in
2
+ // page opened for you"; Claude Code since #5216, rulings #4151 and #4200).
3
+ // The app files a run row whose request is `{kind: "sign-in", agent}`; the
4
+ // runner answers it here by starting the agent's own sign-in on this
5
+ // computer. Each opens its sign-in page in this computer's browser and exits
6
+ // once the sign-in lands, so no one types in a terminal. The runner then
7
+ // probes the agents again, and the app's box goes once the probe says the
8
+ // agent is signed in.
8
9
  //
9
- // Nothing is billed: `codex login` starts no model turn.
10
+ // Nothing is billed: neither sign-in starts a model turn.
10
11
  import { spawn } from "node:child_process";
11
12
  import { runnableCommand } from "./windows-command.mjs";
12
13
 
13
14
  /** How long a person has to finish signing in on the page that opened. */
14
15
  export const SIGN_IN_WAIT_MS = 10 * 60_000;
15
16
 
16
- /** The engines a sign-in request may name. Claude Code signs in from its
17
- * own first run; opencode's sign-in cannot be checked (detect.mjs). */
18
- export const SIGN_IN_AGENTS = ["codex"];
17
+ /** How each agent signs in. Claude Code signs in with the person's Claude
18
+ * plan (`--claudeai`), never the API console, which bills per use (#4200).
19
+ * opencode's sign-in cannot be checked (detect.mjs), so it has none. */
20
+ const LOGINS = {
21
+ codex: { label: "Codex", binEnv: "PM_CODEX_BIN", bin: "codex", args: ["login"] },
22
+ claude: { label: "Claude Code", binEnv: "PM_CLAUDE_BIN", bin: "claude", args: ["auth", "login", "--claudeai"] },
23
+ };
19
24
 
20
- /** Start `codex login` and wait for it to end. Resolves `{ok, detail}`,
21
- * never throws: a missing binary or a sign-in left open is an answer. */
22
- export function codexLogin({ env = process.env, timeoutMs = SIGN_IN_WAIT_MS, platform = process.platform } = {}) {
23
- const bin = env.PM_CODEX_BIN?.trim() || "codex";
24
- const command = runnableCommand(bin, ["login"], { platform, env });
25
+ /** The engines a sign-in request may name. */
26
+ export const SIGN_IN_AGENTS = Object.keys(LOGINS);
27
+
28
+ /** Start `agent`'s sign-in and wait for it to end. Resolves `{ok, detail}`,
29
+ * never throws: a missing binary or a sign-in left open is an answer.
30
+ *
31
+ * The binary is found the way a run finds it (`resolveAgentBinary`,
32
+ * runnerGates.mjs): the daemon runs with its service's PATH, which often
33
+ * lacks `~/.local/bin` or Homebrew, so the daemon's PATH, the usual install
34
+ * folders and a login shell are all tried before it says "not installed". */
35
+ export async function agentLogin(agent, {
36
+ env = process.env, timeoutMs = SIGN_IN_WAIT_MS, platform = process.platform, resolve: resolveBin,
37
+ } = {}) {
38
+ const login = LOGINS[agent];
39
+ if (!login) return { ok: false, detail: `There is no sign-in for ${agent} on this computer.` };
40
+ const notInstalled = { ok: false, detail: `${login.label} is not installed on this computer.` };
41
+ const wanted = env[login.binEnv]?.trim() || login.bin;
42
+ let found;
43
+ // Loaded here: presence (runnerRegister.mjs) imports this file, and
44
+ // detect.mjs reaches back to the runner's constants, a cycle at load.
45
+ try { found = await (resolveBin ?? (await import("./detect.mjs")).resolveAgentBinary)(wanted, { env, platform }); }
46
+ catch { found = { found: false }; }
47
+ if (!found?.found) return notInstalled;
48
+ const command = runnableCommand(found.path, login.args, { platform, env });
49
+ const said = [login.bin, ...login.args.filter((arg) => !arg.startsWith("-"))].join(" ");
25
50
  return new Promise((resolve) => {
26
51
  let child;
27
52
  try {
@@ -37,11 +62,11 @@ export function codexLogin({ env = process.env, timeoutMs = SIGN_IN_WAIT_MS, pla
37
62
  timer.unref?.();
38
63
  child.on("error", (error) => {
39
64
  clearTimeout(timer);
40
- resolve({ ok: false, detail: error.code === "ENOENT" ? "Codex is not installed on this computer." : error.message });
65
+ resolve(error.code === "ENOENT" ? notInstalled : { ok: false, detail: error.message });
41
66
  });
42
67
  child.on("exit", (code) => {
43
68
  clearTimeout(timer);
44
- resolve(code === 0 ? { ok: true, detail: "Codex is signed in." } : { ok: false, detail: `codex login ended with code ${code}.` });
69
+ resolve(code === 0 ? { ok: true, detail: `${login.label} is signed in.` } : { ok: false, detail: `${said} ended with code ${code}.` });
45
70
  });
46
71
  });
47
72
  }
package/lib/update.mjs CHANGED
@@ -16,11 +16,12 @@
16
16
 
17
17
  import { createRequire } from "node:module";
18
18
  import { execFile } from "node:child_process";
19
- import { readFileSync } from "node:fs";
19
+ import { existsSync, readFileSync } from "node:fs";
20
20
  import { realpath } from "node:fs/promises";
21
21
  import { basename, join, posix, win32 } from "node:path";
22
22
  import { readRunnerHealth, waitForRunnerHealth } from "./runner-health.mjs";
23
23
  import { noDaemonInstall } from "./logindaemon.mjs";
24
+ import { markQuietStop } from "./goodbye.mjs";
24
25
  import { fileURLToPath } from "node:url";
25
26
 
26
27
  import { runnableCommand } from "./windows-command.mjs";
@@ -60,27 +61,87 @@ export function compareVersions(a, b) {
60
61
  return 0;
61
62
  }
62
63
 
63
- /** Ask npm. Returns the version string, or null for offline / not published /
64
- * anything else. `exec` is injected so the tests never touch the network.
64
+ /** Run npm. `exec` is injected so the tests never touch the network.
65
65
  *
66
66
  * npm installs as `npm.cmd` on Windows, so this goes through the same
67
67
  * `runnableCommand` resolution as every other binary this package looks for -
68
68
  * otherwise the version row lies and says "offline" on a machine with a
69
- * perfectly good connection. */
70
- export const execNpm = (args, { timeoutMs = NPM_TIMEOUT_MS, platform = process.platform, env = process.env, exists, readFile, execImpl = execFile } = {}) =>
69
+ * perfectly good connection.
70
+ *
71
+ * WHICH npm (#5305). The first `npm` on the PATH is not necessarily the one
72
+ * whose prefix holds this Viewable: a Mac with a system Node and nvm has
73
+ * `/usr/local/bin/npm` first while Viewable lives under nvm, and installing
74
+ * with the wrong one writes to a folder the person cannot write to. So the
75
+ * npm that sits next to the Node running this process goes first on the
76
+ * child's PATH (npm's own `#!/usr/bin/env node` then finds that Node too).
77
+ * When no npm sits beside this Node (npx), or the Node is one of Volta's
78
+ * images, the PATH decides as before: Volta's own npm shim installs into the
79
+ * package image that #707's verification expects, and the image's bundled npm
80
+ * would not.
81
+ * Every npm call in this file goes through `execNpm`, so `viewable update`,
82
+ * the no-paste Update, and the version checks all agree. This returns the env
83
+ * to run npm with. */
84
+ export function npmPathFor({ platform = process.platform, env = process.env, nodePath = process.execPath, exists = existsSync } = {}) {
85
+ const path = platform === "win32" ? win32 : posix;
86
+ const nodeDir = path.dirname(nodePath);
87
+ const voltaHome = String(env?.VOLTA_HOME ?? "");
88
+ if (/[\\/]tools[\\/]image[\\/]node[\\/]/.test(nodePath) || (voltaHome && nodePath.startsWith(voltaHome))) return env;
89
+ if (!exists(path.join(nodeDir, platform === "win32" ? "npm.cmd" : "npm"))) return env;
90
+ const key = Object.keys(env ?? {}).find((k) => (platform === "win32" ? k.toUpperCase() === "PATH" : k === "PATH")) ?? "PATH";
91
+ const rest = String(env?.[key] ?? "").split(path.delimiter).filter((dir) => dir && dir !== nodeDir);
92
+ return { ...env, [key]: [nodeDir, ...rest].join(path.delimiter) };
93
+ }
94
+
95
+ /** Resolves `{ ok, stdout, stderr, timedOut }`; `stderr` is what
96
+ * `installFailureReason` reads. */
97
+ /** Node's own Windows install ships `npm.cmd` as a launcher that starts
98
+ * through variables ("%NODE_EXE%" "%NPM_CLI_JS%" %*), which `runnableCommand`
99
+ * rightly refuses. Beside that Node the entry script is always at the same
100
+ * place, so run it with that Node instead of the shim. */
101
+ function nodeBesideNpm({ platform, nodePath, exists = existsSync }) {
102
+ if (platform !== "win32") return null;
103
+ const cli = win32.join(win32.dirname(nodePath), "node_modules", "npm", "bin", "npm-cli.js");
104
+ return exists(cli) ? { file: nodePath, args: [cli], shell: false } : null;
105
+ }
106
+
107
+ export const execNpm = (args, { timeoutMs = NPM_TIMEOUT_MS, platform = process.platform, env = process.env, exists, readFile, execImpl = execFile, nodePath = process.execPath } = {}) =>
71
108
  new Promise((resolve) => {
72
109
  let resolved;
110
+ const npmEnv = npmPathFor({ platform, env, nodePath, ...(exists ? { exists } : {}) });
111
+ const beside = nodeBesideNpm({ platform, nodePath, ...(exists ? { exists } : {}) });
73
112
  try {
74
- resolved = runnableCommand("npm", args, { platform, env, ...(exists ? { exists } : {}), ...(readFile ? { readFile } : {}) });
113
+ resolved = beside ? { ...beside, args: [...beside.args, ...args] } : runnableCommand("npm", args, { platform, env: npmEnv, nodePath, ...(exists ? { exists } : {}), ...(readFile ? { readFile } : {}) });
75
114
  } catch {
76
- resolve({ ok: false, stdout: "" });
115
+ resolve({ ok: false, stdout: "", stderr: "" });
77
116
  return;
78
117
  }
79
- execImpl(resolved.file, resolved.args, { timeout: timeoutMs, windowsHide: true, env, shell: resolved.shell }, (error, stdout) =>
80
- resolve({ ok: !error, stdout: String(stdout ?? "") }),
118
+ execImpl(resolved.file, resolved.args, { timeout: timeoutMs, windowsHide: true, env: npmEnv, shell: resolved.shell }, (error, stdout, stderr) =>
119
+ resolve({ ok: !error, stdout: String(stdout ?? ""), stderr: String(stderr ?? ""), ...(error?.killed ? { timedOut: true } : {}) }),
81
120
  );
82
121
  });
83
122
 
123
+ /** Say what an install failure was, in plain words, from npm's own error
124
+ * text. `where` is the folder npm was installing into, used when npm does not
125
+ * name the path. Never says "Check your connection" unless the network is
126
+ * what failed. */
127
+ export function installFailureReason(result, where = "") {
128
+ const text = String(result?.stderr ?? "");
129
+ if (result?.timedOut) return "npm took too long to install it.";
130
+ if (/\b(?:EACCES|EPERM)\b|rejected by your operating system|permission denied/i.test(text)) {
131
+ // npm prints the path quoted after a colon, or bare ("npm error path /x/.npm/_cacache").
132
+ const named = /^(?:npm (?:error|ERR!)\s+)?path:?\s+'?([^'\r\n]+?)'?\s*$/im.exec(text)?.[1] ?? /'((?:\/|[A-Za-z]:\\)[^']+)'/.exec(text)?.[1] ?? where;
133
+ if (/[\\/]_cacache\b/.test(named)) return `No permission to write npm's cache folder ${named}. Fix the folder's owner; never run sudo.`;
134
+ return `No permission to write ${named || "the npm folder"}. Never run sudo; use the npm that came with the Node running Viewable, or fix the folder's owner.`;
135
+ }
136
+ if (/\bENOSPC\b|no space left/i.test(text)) return "The disk is full.";
137
+ if (/\b(?:ENOTFOUND|EAI_AGAIN|ECONNRESET|ECONNREFUSED|ETIMEDOUT|ENETUNREACH|EPROTO)\b|network/i.test(text)) return "Could not reach npm. Check your connection.";
138
+ // npm ends a failed run with a pointer to its log; that is not the cause.
139
+ const line = text.split(/\r?\n/).filter((l) => !/^npm notice\b/i.test(l.trim()))
140
+ .map((l) => l.replace(/^npm (?:error|ERR!)\s*/i, "").trim())
141
+ .filter((l) => l && !/^a complete log of this run can be found/i.test(l)).at(-1);
142
+ return line ? `npm said: ${line.slice(0, 200)}` : "npm did not say why.";
143
+ }
144
+
84
145
  export async function latestFromNpm({ exec = execNpm, name = PACKAGE_NAME, timeoutMs = NPM_TIMEOUT_MS } = {}) {
85
146
  const result = await exec(["view", name, "version"], { timeoutMs });
86
147
  if (!result?.ok) return null;
@@ -283,12 +344,17 @@ export async function runUpdate({
283
344
  const scriptPath = (platform === "win32" ? win32 : { join }).join(root.stdout.trim(), PACKAGE_NAME, "glytch.mjs");
284
345
  log(`Installing Viewable ${latest}…`);
285
346
  const installed = await npm(["install", "-g", `${PACKAGE_NAME}@${latest}`, "--force"], { timeoutMs: 180_000 });
286
- if (!installed?.ok) return failure("Installation failed. Check your connection and npm directory permissions; never run sudo. The service was left alone. Retry viewable update after fixing the install.");
347
+ if (!installed?.ok) return failure(`Installation failed. ${installFailureReason(installed, root.stdout.trim())} The service was left alone. Retry viewable update after fixing the install.`);
287
348
  const checked = await verify({ env, platform, expectedVersion: latest, scriptPath, allowVoltaPackage: true, log });
288
349
  if (!checked.ok) return failure(`The package was installed, but ${checked.error}`);
289
350
  const before = readHealth();
290
351
  const after = now();
291
- const restart = sync ?? (await import("./sync.mjs")).syncLaunchAgent;
352
+ // An update's restart is not a goodbye (ruling #4979): the app it stops
353
+ // reads this note (lib/goodbye.mjs).
354
+ const restart = sync ?? (async (options) => {
355
+ await markQuietStop({ env, why: "update" });
356
+ return (await import("./sync.mjs")).syncLaunchAgent(options);
357
+ });
292
358
  let result;
293
359
  try { result = await restart({ env, platform, scriptPath: checked.scriptPath, version: latest, restart: true }); }
294
360
  catch { return failure("The package was installed, but restarting failed. Folders and sign-in were kept. Run viewable doctor, then retry viewable update."); }
@@ -347,7 +413,7 @@ export async function installUpdate({
347
413
  if (!same) return failure("This computer runs Viewable from another folder, so it cannot update itself.");
348
414
  log(`update: installing Viewable ${latest}…`);
349
415
  const installed = await npm(["install", "-g", `${PACKAGE_NAME}@${latest}`, "--force"], { timeoutMs: 180_000 });
350
- if (!installed?.ok) return failure("Installation failed. Nothing was restarted.");
416
+ if (!installed?.ok) return failure(`Installation failed. ${installFailureReason(installed, root.stdout.trim())} Nothing was restarted.`);
351
417
  const found = await readVersion(path.join(root.stdout.trim(), PACKAGE_NAME, "package.json")).catch(() => null);
352
418
  if (found !== latest) return failure(`Installed, but the version reads ${found ?? "nothing"}, not ${latest}. Nothing was restarted.`);
353
419
  return { ok: true, version: latest, restart: true };
@@ -7,12 +7,13 @@
7
7
  // No existing folder is moved or rewritten by the rename (#2329).
8
8
  //
9
9
  // Made when the daemon starts watching, and kept: nothing here removes it.
10
+ // Unless the person removed it from the board: then it is left alone (#5290).
10
11
 
11
12
  import { existsSync } from "node:fs";
12
13
  import { lstat, mkdir, realpath, writeFile } from "node:fs/promises";
13
14
  import { homedir } from "node:os";
14
15
  import { basename, dirname, join, resolve } from "node:path";
15
- import { addFolder } from "./registry.mjs";
16
+ import { addFolderUnlessRemoved, folderWasRemoved } from "./registry.mjs";
16
17
  import { git, isChatWorktreePath, resolveChatCwd } from "./worktree.mjs";
17
18
 
18
19
  /** Where the default working folder lives, or null when there is none to make.
@@ -52,6 +53,9 @@ const COMMITTER = ["-c", "user.name=Viewable", "-c", "user.email=viewable@localh
52
53
  export async function ensureViewableFolder(env = process.env, log = () => {}) {
53
54
  const path = viewableFolderPath(env);
54
55
  if (path === null) return null;
56
+ // A folder the person removed from the board is not made or watched again
57
+ // on the next start (#5290). Adding it by hand (init) clears the record.
58
+ if (await folderWasRemoved(path, env)) return null;
55
59
  try {
56
60
  await mkdir(path, { recursive: true });
57
61
  // Its own repository, not one it happens to sit inside: a home folder
@@ -77,8 +81,7 @@ export async function ensureViewableFolder(env = process.env, log = () => {}) {
77
81
  if (!commit.ok) throw new Error(`first commit failed: ${commit.stderr?.trim() || "no detail"}`);
78
82
  log(`made the Viewable folder at ${path}`);
79
83
  }
80
- await addFolder(path, env);
81
- return path;
84
+ return await addFolderUnlessRemoved(path, env) === null ? null : path;
82
85
  } catch (error) {
83
86
  log(`could not make the Viewable folder at ${path}: ${error instanceof Error ? error.message : String(error)}`);
84
87
  return null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "viewable-one",
3
- "version": "0.12.4",
3
+ "version": "0.12.5",
4
4
  "description": "Run coding agents from the Viewable board. Connects your machine to app.viewable.one, launches a session in its own worktree when you press Run, and streams what it does back to the canvas.",
5
5
  "keywords": [
6
6
  "mcp",