viewable-one 0.12.3 → 0.12.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,239 @@
1
+ // THE COMPUTER UNINSTALLS ITSELF (#4951, rulings #2885, #4977, #4978).
2
+ //
3
+ // Two ways in, and both end in the same `viewable uninstall --yes`:
4
+ //
5
+ // 1. Remove on an online computer. The app marks the computer's rows
6
+ // (`runner_computer_uninstall_request`) and board-runner hands this daemon
7
+ // an `uninstall` op on its next heartbeat. The board asked, over this
8
+ // computer's own signed-in channel, so it runs.
9
+ //
10
+ // 2. A computer removed while it was off ("Remove it from the board only")
11
+ // comes back and finds its board key refused. A refusal alone proves
12
+ // nothing: an expired token, a refresh that failed for a moment, a key
13
+ // revoked in Access tokens or a banned account all look the same from
14
+ // here. So it asks the board one question, `POST /oauth/removed`, about
15
+ // each key it holds, and runs only when every one of them gets a plain
16
+ // 200 `{removed: true}`. The board says yes only for a key that Remove
17
+ // took away (#4978). Anything else (a network failure, a 5xx, a 404 from
18
+ // an older board, odd JSON, `removed: false`) for any key leaves the
19
+ // computer exactly as it is.
20
+ //
21
+ // Every key, not the first yes: a sign-in with a personal key keeps the
22
+ // older OAuth pair beside it (auth.mjs login). If that older pair was
23
+ // taken away by an earlier Remove and the new personal key is later
24
+ // refused for another reason, the pair's yes alone would uninstall a
25
+ // computer nobody removed. Asking only about the refused key is not
26
+ // enough either: once the personal key is marked dead the daemon falls
27
+ // back to the old pair and sends its access token, and a refused refresh
28
+ // sends no key at all.
29
+ //
30
+ // `viewable uninstall` stops the background app, revokes the key and deletes
31
+ // ~/.glytch. It never touches the Viewable folder or its files: the folder
32
+ // steps only take out the config entries `viewable init` wrote.
33
+ //
34
+ // The uninstall runs outside this daemon, because stopping the background app
35
+ // is the second thing it does and that kills this daemon. A detached process
36
+ // group is enough on a Mac (launchctl unload ends the one process). It is not
37
+ // on Linux and WSL: systemd stops every process left in the service's cgroup,
38
+ // a detached child included, so the uninstall starts in its own transient
39
+ // unit (`systemd-run --user --collect`). Nor on Windows: Task Scheduler ends
40
+ // a task's whole job (`schtasks /end`), and Node never asks to break away from
41
+ // a job, so it starts through WMI (Win32_Process.Create), whose processes
42
+ // belong to no task. Either launcher falls back to the plain detached child
43
+ // when it is missing or refuses: on a machine where the daemon is not under
44
+ // systemd or Task Scheduler, that child survives anyway.
45
+
46
+ import { spawn } from "node:child_process";
47
+ import { createHash } from "node:crypto";
48
+ import { writeFileSync } from "node:fs";
49
+ import { tmpdir } from "node:os";
50
+ import { dirname, join, sep } from "node:path";
51
+ import { fileURLToPath } from "node:url";
52
+
53
+ import { appUrlFrom, readAuthFile } from "./auth.mjs";
54
+
55
+ const CLI_PATH = join(dirname(fileURLToPath(import.meta.url)), "..", "glytch.mjs");
56
+ /** How often a refused computer may ask the board whether it was removed. */
57
+ export const REMOVED_CHECK_EVERY_MS = 5 * 60_000;
58
+ const REMOVED_CHECK_TIMEOUT_MS = 15_000;
59
+
60
+ let started = false;
61
+ let lastCheckAt = -Infinity;
62
+
63
+ /** Test seam: forget this process's one-shot state. */
64
+ export function resetSelfUninstall() {
65
+ started = false;
66
+ lastCheckAt = -Infinity;
67
+ launch = Promise.resolve(null);
68
+ }
69
+
70
+ /** The board keys this computer holds: the stored pair or personal key, and
71
+ * the script key from the environment. */
72
+ export function heldCredentials(stored, env = process.env) {
73
+ const fromEnv = (env.VIEWABLE_BOARD_TOKEN ?? env.GLYTCH_BOARD_TOKEN)?.trim();
74
+ const tokens = [stored?.refreshToken, stored?.accessToken, stored?.oauthAccessToken, fromEnv];
75
+ return [...new Set(tokens.filter((token) => typeof token === "string" && token !== ""))];
76
+ }
77
+
78
+ const fingerprint = (tokens) => createHash("sha256").update(tokens.join("\n")).digest("hex");
79
+
80
+ /** Does the board say Remove took this computer's keys away? Only a plain
81
+ * `200 {removed: true}` for every key it holds counts. */
82
+ export async function credentialRemoved({ env = process.env, fetchImpl = fetch, stored } = {}) {
83
+ const auth = stored === undefined ? await readAuthFile(env) : stored;
84
+ const tokens = heldCredentials(auth, env);
85
+ if (tokens.length === 0) return { removed: false, reason: "no key on this computer" };
86
+ const appUrl = auth?.appUrl || appUrlFrom(undefined, env);
87
+ for (const token of tokens) {
88
+ let response;
89
+ try {
90
+ response = await fetchImpl(`${appUrl}/oauth/removed`, {
91
+ method: "POST",
92
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
93
+ body: new URLSearchParams({ token }),
94
+ signal: AbortSignal.timeout(REMOVED_CHECK_TIMEOUT_MS),
95
+ });
96
+ } catch {
97
+ return { removed: false, reason: "the board could not be reached" };
98
+ }
99
+ if (response?.status !== 200) {
100
+ if (response?.status === 404) return { removed: false, reason: "this board cannot say yet" };
101
+ return { removed: false, reason: `the board answered ${response?.status ?? "nothing"}` };
102
+ }
103
+ let body;
104
+ try { body = JSON.parse(await response.text()); } catch { return { removed: false, reason: "the board's answer was unreadable" }; }
105
+ if (body === null || typeof body !== "object" || body.removed !== true) return { removed: false, reason: "a key was not removed" };
106
+ }
107
+ return { removed: true, tokens };
108
+ }
109
+
110
+ /** Where the global npm package lives when this copy came from one. */
111
+ function globalPackageDir(cliPath) {
112
+ const marker = `${sep}node_modules${sep}viewable-one${sep}`;
113
+ return cliPath.includes(marker) ? cliPath.slice(0, cliPath.indexOf(marker) + marker.length - 1) : null;
114
+ }
115
+
116
+ /** What the uninstall needs from this daemon's environment. A launcher
117
+ * outside this process (a systemd unit, WMI) starts it with the user's
118
+ * default environment instead, so the script carries these itself. Keys and
119
+ * tokens stay out: the uninstall reads the stored sign-in from the home. */
120
+ export function carriedEnv(env = process.env) {
121
+ const keep = /^(HOME|PATH|USERPROFILE|APPDATA|LOCALAPPDATA|TMPDIR|TEMP|TMP|XDG_[A-Z_]+|(VIEWABLE|GLYTCH)_[A-Z0-9_]+)$/;
122
+ const secret = /TOKEN|SECRET|KEY|PASSWORD/i;
123
+ return Object.fromEntries(Object.entries(env).filter(([name, value]) => typeof value === "string" && keep.test(name) && !secret.test(name)));
124
+ }
125
+
126
+ /** The detached command: `viewable uninstall --yes`, then, only when it
127
+ * finished and this copy is the global npm package, `npm uninstall -g`. */
128
+ export function selfUninstallCommand({ execPath = process.execPath, cliPath = CLI_PATH, env = process.env } = {}) {
129
+ const npm = globalPackageDir(cliPath) ? join(dirname(execPath), process.platform === "win32" ? "npm.cmd" : "npm") : null;
130
+ const script = [
131
+ 'const { spawnSync } = require("node:child_process");',
132
+ `const env = { ...process.env, ...${JSON.stringify(carriedEnv(env))} };`,
133
+ `const done = spawnSync(process.execPath, [${JSON.stringify(cliPath)}, "uninstall", "--yes"], { stdio: "ignore", env });`,
134
+ npm ? `if (done.status === 0) spawnSync(${JSON.stringify(npm)}, ["uninstall", "-g", "viewable-one"], { stdio: "ignore", env, shell: process.platform === "win32" });` : "",
135
+ ].join("\n");
136
+ return { command: execPath, args: ["-e", script], script };
137
+ }
138
+
139
+ /** The launcher that starts `command` outside this daemon's service, or null
140
+ * where a detached child already outlives it (macOS). */
141
+ export function outsideServiceLauncher(command, { platform = process.platform, dir = tmpdir(), writeFile = writeFileSync } = {}) {
142
+ if (platform === "linux") {
143
+ return { command: "systemd-run", args: ["--user", "--collect", "--quiet", "--", command.command, ...command.args] };
144
+ }
145
+ if (platform === "win32") {
146
+ // WMI takes one command line; a script file keeps it free of quoting.
147
+ const file = join(dir, `viewable-uninstall-${process.pid}.cjs`);
148
+ writeFile(file, command.script ?? "");
149
+ const quoted = (value) => `"${value}"`;
150
+ const line = `${quoted(command.command)} ${quoted(file)}`.replaceAll("'", "''");
151
+ return {
152
+ command: "powershell.exe",
153
+ args: ["-NoProfile", "-NonInteractive", "-Command",
154
+ `$r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = '${line}'; CurrentDirectory = '${dir.replaceAll("'", "''")}' }; exit $r.ReturnValue`],
155
+ };
156
+ }
157
+ return null;
158
+ }
159
+
160
+ const LAUNCH_TIMEOUT_MS = 20_000;
161
+
162
+ /** Run a launcher and wait for it to say it started the uninstall. */
163
+ function launched(launcher, { env, spawnFn, timeoutMs = LAUNCH_TIMEOUT_MS }) {
164
+ return new Promise((resolve) => {
165
+ let child;
166
+ try {
167
+ child = spawnFn(launcher.command, launcher.args, { env, cwd: tmpdir(), stdio: "ignore", windowsHide: true });
168
+ } catch { resolve(false); return; }
169
+ if (!child?.once) { resolve(false); return; }
170
+ const timer = setTimeout(() => { child.kill?.(); resolve(false); }, timeoutMs);
171
+ timer.unref?.();
172
+ child.once("error", () => { clearTimeout(timer); resolve(false); });
173
+ child.once("exit", (code) => { clearTimeout(timer); resolve(code === 0); });
174
+ });
175
+ }
176
+
177
+ /** The plain detached child. Throws when it cannot start. */
178
+ function spawnDetached(command, { env, spawnFn }) {
179
+ const child = spawnFn(command.command, command.args, { env, cwd: tmpdir(), detached: true, stdio: "ignore", windowsHide: true });
180
+ child?.unref?.();
181
+ }
182
+
183
+ /** Start the uninstall once per process. Returns whether this call started
184
+ * it; on Linux, WSL and Windows the launch finishes in the background
185
+ * (`selfUninstallLaunch()` resolves to how it started). */
186
+ let launch = Promise.resolve(null);
187
+ export const selfUninstallLaunch = () => launch;
188
+
189
+ export function startSelfUninstall({ env = process.env, spawnFn = spawn, log = () => {}, why, platform = process.platform, command = selfUninstallCommand({ env }), launcher } = {}) {
190
+ if (started) return false;
191
+ started = true;
192
+ log(`uninstall: ${why} - uninstalling Viewable from this computer. Your Viewable folder and its files stay.`);
193
+ const failed = (error) => {
194
+ started = false;
195
+ log(`uninstall: could not start: ${error instanceof Error ? error.message : String(error)}`);
196
+ };
197
+ let outside = null;
198
+ try { outside = launcher === undefined ? outsideServiceLauncher(command, { platform }) : launcher; }
199
+ catch (error) { log(`uninstall: ${error instanceof Error ? error.message : String(error)}; starting it here`); }
200
+ if (outside === null) {
201
+ try { spawnDetached(command, { env, spawnFn }); launch = Promise.resolve("detached"); return true; }
202
+ catch (error) { failed(error); launch = Promise.resolve(null); return false; }
203
+ }
204
+ launch = launched(outside, { env, spawnFn }).then((ok) => {
205
+ if (ok) return outside.command;
206
+ log(`uninstall: ${outside.command} did not start it; starting it here`);
207
+ try { spawnDetached(command, { env, spawnFn }); return "detached"; }
208
+ catch (error) { failed(error); return null; }
209
+ });
210
+ return true;
211
+ }
212
+
213
+ /** An `uninstall` op on this beat: the board's Remove on an online computer. */
214
+ export function serviceUninstallOps(ops, settings = {}, log = () => {}) {
215
+ if (!(ops ?? []).some((op) => op?.kind === "uninstall")) return false;
216
+ if (started) return true;
217
+ return startSelfUninstall({ env: settings.env ?? process.env, spawnFn: settings.spawnFn, platform: settings.platform, log, why: "the board asked (Remove in Settings)" });
218
+ }
219
+
220
+ /** After the board refused this computer's key: ask whether Remove took its
221
+ * keys away, at most once every few minutes, and uninstall only on a yes
222
+ * for every key that is still on file. */
223
+ export async function uninstallIfRemoved(settings = {}, log = () => {}, { now = Date.now } = {}) {
224
+ if (started) return { started: false, reason: "already uninstalling" };
225
+ const at = now();
226
+ if (at - lastCheckAt < REMOVED_CHECK_EVERY_MS) return { started: false, reason: "asked a moment ago" };
227
+ lastCheckAt = at;
228
+ const env = settings.env ?? process.env;
229
+ const fetchImpl = settings.fetchImpl ?? fetch;
230
+ const stored = await readAuthFile(env);
231
+ const answer = await credentialRemoved({ env, fetchImpl, stored });
232
+ if (!answer.removed) return { started: false, reason: answer.reason };
233
+ // A new sign-in while the question was out wins: never uninstall a computer
234
+ // that has just been connected again.
235
+ const current = heldCredentials(await readAuthFile(env), env);
236
+ if (current.length === 0 || fingerprint(current) !== fingerprint(answer.tokens)) return { started: false, reason: "the key changed while asking" };
237
+ const ok = startSelfUninstall({ env, spawnFn: settings.spawnFn, platform: settings.platform, log, why: "this computer was removed from the board while it was away" });
238
+ return { started: ok, reason: ok ? "removed" : "could not start" };
239
+ }
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."); }
@@ -300,3 +366,187 @@ export async function runUpdate({
300
366
  log(`Viewable ${latest} is installed. Your computer restarted and has a fresh connection.`);
301
367
  return { ok: true, version: latest };
302
368
  }
369
+
370
+ // ---------------------------------------------------------------------------
371
+ // THE BOARD'S UPDATE BUTTON (#4949). The person presses Update in More; the
372
+ // app files a `runner_update_requests` row; the heartbeat hands this process
373
+ // an `update` op. From then on new runs wait (claims are held), and nothing
374
+ // happens to a run already going. Once no run and no run's child process is
375
+ // left, the request is TAKEN (an atomic delete on the server, so Cancel update
376
+ // and the take cannot both win), the new version installs in place, and this
377
+ // process exits with UPDATE_RESTART_EXIT_CODE. The service the computer
378
+ // already has starts it again on the new code: launchd KeepAlive and systemd
379
+ // Restart=always on any exit, Windows' RestartOnFailure on a nonzero one.
380
+ // Restarting the service from in here would kill the process doing the
381
+ // restart halfway (see multiwatch's `daemon: true`), so this never does.
382
+ //
383
+ // The daily check above stays a notice: nothing installs unless a person
384
+ // pressed Update for this computer.
385
+
386
+ /** Nonzero on purpose: Task Scheduler restarts only a failed task. */
387
+ export const UPDATE_RESTART_EXIT_CODE = 75;
388
+ const UPDATE_POLL_MS = 2_000;
389
+
390
+ const readPackageVersion = async (path) => JSON.parse(readFileSync(path, "utf8")).version;
391
+
392
+ /** Install the latest in place, for the running service to pick up when it
393
+ * restarts. Refuses BEFORE installing when npm's global copy is not the one
394
+ * this process runs (npx, Volta, a second prefix): installing elsewhere would
395
+ * change nothing, and the copy prompt still covers that computer. */
396
+ export async function installUpdate({
397
+ env = process.env, platform = process.platform, exec = execNpm, version = packageVersion(),
398
+ scriptPath = fileURLToPath(new URL("../glytch.mjs", import.meta.url)),
399
+ resolvePath = realpath, readVersion = readPackageVersion, log = () => {},
400
+ } = {}) {
401
+ const failure = (error) => ({ ok: false, error });
402
+ if (noDaemonInstall(env)) return failure("Updates are turned off on this computer.");
403
+ const npm = (args, options) => exec(args, { env, platform, ...options });
404
+ const latest = await latestFromNpm({ exec: npm });
405
+ if (!latest) return failure("Could not reach npm to find the new version.");
406
+ if (compareVersions(latest, version) <= 0) return { ok: true, version, restart: false };
407
+ const root = await npm(["root", "-g"]);
408
+ if (!root?.ok || !root.stdout.trim()) return failure("Could not find where npm installs Viewable.");
409
+ const path = platform === "win32" ? win32 : { join };
410
+ const installedScript = path.join(root.stdout.trim(), PACKAGE_NAME, "glytch.mjs");
411
+ const same = await Promise.all([resolvePath(installedScript), resolvePath(scriptPath)])
412
+ .then(([a, b]) => a === b, () => false);
413
+ if (!same) return failure("This computer runs Viewable from another folder, so it cannot update itself.");
414
+ log(`update: installing Viewable ${latest}…`);
415
+ const installed = await npm(["install", "-g", `${PACKAGE_NAME}@${latest}`, "--force"], { timeoutMs: 180_000 });
416
+ if (!installed?.ok) return failure(`Installation failed. ${installFailureReason(installed, root.stdout.trim())} Nothing was restarted.`);
417
+ const found = await readVersion(path.join(root.stdout.trim(), PACKAGE_NAME, "package.json")).catch(() => null);
418
+ if (found !== latest) return failure(`Installed, but the version reads ${found ?? "nothing"}, not ${latest}. Nothing was restarted.`);
419
+ return { ok: true, version: latest, restart: true };
420
+ }
421
+
422
+ /** One per computer app process: every folder's beat shares it.
423
+ *
424
+ * `activeRuns()` counts this process's runs AND recovery records whose child
425
+ * processes are still alive (runnerRecovery's own journal, not a second run
426
+ * tracker), so the restart comes only after the last child ends. */
427
+ export function makeSelfUpdate({
428
+ version = packageVersion(), activeRuns = async () => 0, take = async () => false,
429
+ install = (options) => installUpdate({ version, ...options }), restart = async () => {},
430
+ onChange = () => {}, log = () => {}, pollMs = UPDATE_POLL_MS,
431
+ after = setTimeout, cancel = clearTimeout,
432
+ } = {}) {
433
+ /** idle | waiting {request, runs, taken} | updating {to} | failed {error} */
434
+ let state = { name: "idle" };
435
+ let timer = null;
436
+ let checking = null;
437
+ // Claims that passed the gate before the update was asked for. Their run
438
+ // may not be counted by `activeRuns()` yet, so nothing installs until each
439
+ // one has settled and its run, if any, is counted (#4949 review).
440
+ let claims = 0;
441
+ // A take whose answer has not come back. The server deleted the request
442
+ // when it took it, so a heartbeat in between no longer lists it; the take's
443
+ // answer decides, not that heartbeat (#4949 review).
444
+ let taking = false;
445
+ // A take that failed with no answer may have won on the server, which
446
+ // deleted the request. If the request is then gone, nobody can tell a
447
+ // lost win from Cancel update, so it fails where the user can see it
448
+ // rather than vanishing; Try again files a new one (#4949 review).
449
+ let takeUnknown = false;
450
+ const lostTake = () => {
451
+ takeUnknown = false;
452
+ log("update: the board stopped answering while the update was taken; nothing was installed");
453
+ set({ name: "failed", error: "The board stopped answering while the update started. Nothing was installed." });
454
+ };
455
+ const holds = () => state.name === "waiting" || state.name === "updating";
456
+ const set = (next) => {
457
+ const before = JSON.stringify(view());
458
+ state = next;
459
+ if (JSON.stringify(view()) !== before) onChange();
460
+ };
461
+ const view = () => {
462
+ if (state.name === "waiting") return { state: "waiting", runs: state.runs ?? 0 };
463
+ if (state.name === "updating") return { state: "updating", ...(state.to ? { to: state.to } : {}) };
464
+ if (state.name === "failed") return { state: "failed", error: state.error };
465
+ return undefined;
466
+ };
467
+ const schedule = () => {
468
+ if (timer || state.name !== "waiting") return;
469
+ timer = after(() => { timer = null; void check(); }, pollMs);
470
+ timer?.unref?.();
471
+ };
472
+ const runOnce = async () => {
473
+ if (state.name !== "waiting") return;
474
+ let runs;
475
+ try { runs = await activeRuns(); }
476
+ catch (error) { log(`update: cannot tell whether runs are going (${error.message}); waiting`); return; }
477
+ if (state.name !== "waiting") return;
478
+ if (runs + claims > 0) { set({ ...state, runs: runs + claims }); return; }
479
+ if (!state.taken) {
480
+ let taken = false;
481
+ taking = true;
482
+ try { taken = await take(state.request); }
483
+ catch (error) { takeUnknown = true; log(`update: could not take the request (${error.message}); trying again`); return; }
484
+ finally { taking = false; }
485
+ if (state.name !== "waiting") return;
486
+ if (!taken && takeUnknown) { lostTake(); return; }
487
+ if (!taken) { log("update: the request was cancelled or already taken"); set({ name: "idle" }); return; }
488
+ takeUnknown = false;
489
+ state = { ...state, taken: true };
490
+ }
491
+ // A claim in flight when the request came may have started a run, or may
492
+ // still be on its way. Read both again right before installing.
493
+ const late = (await activeRuns().catch(() => 1)) + claims;
494
+ if (state.name !== "waiting") return;
495
+ if (late > 0) { set({ ...state, runs: late }); return; }
496
+ set({ name: "updating" });
497
+ let result;
498
+ try { result = await install({ log }); }
499
+ catch (error) { result = { ok: false, error: `Installation failed: ${error.message}` }; }
500
+ if (!result?.ok) {
501
+ log(`update: ${result?.error ?? "failed"}; the old version keeps running`);
502
+ set({ name: "failed", error: result?.error ?? "The update failed." });
503
+ return;
504
+ }
505
+ if (!result.restart) { log(`update: already on ${result.version ?? version}`); set({ name: "idle" }); return; }
506
+ set({ name: "updating", to: result.version });
507
+ log(`update: Viewable ${result.version} installed; restarting on it`);
508
+ await restart();
509
+ };
510
+ const check = () => {
511
+ checking ??= runOnce().finally(() => { checking = null; schedule(); });
512
+ return checking;
513
+ };
514
+ return {
515
+ /** An `update` op off a heartbeat. A second press while waiting is the
516
+ * same request; a press after a failure is Try again. */
517
+ request(op) {
518
+ if (!op?.id) return;
519
+ if (state.name === "waiting" && state.request.id === op.id) return;
520
+ if (state.name === "updating" || (state.name === "waiting" && (state.taken || taking))) return;
521
+ log(`update: asked for from the board`);
522
+ takeUnknown = false;
523
+ set({ name: "waiting", request: op, runs: state.name === "waiting" ? state.runs : 0, taken: false });
524
+ void check();
525
+ },
526
+ /** This folder's heartbeat ops. Its untaken request missing from them is
527
+ * Cancel update. Another folder's beat says nothing about it. */
528
+ seen(project, ops) {
529
+ const projectId = typeof project === "string" ? project : project?.id;
530
+ if (state.name !== "waiting" || state.taken || taking || state.request.project_id !== projectId) return;
531
+ if ((ops ?? []).some((op) => op.kind === "update" && op.id === state.request.id)) return;
532
+ if (timer) { cancel(timer); timer = null; }
533
+ if (takeUnknown) { lostTake(); return; }
534
+ log("update: cancelled from the board");
535
+ set({ name: "idle" });
536
+ },
537
+ /** New runs wait while an update is asked for or installing. */
538
+ holdsRuns: holds,
539
+ /** The claim gate and its count in one step: null while runs are held,
540
+ * else the call that says this claim has settled and its run, if any,
541
+ * is counted by `activeRuns()`. */
542
+ claimStarted() {
543
+ if (holds()) return null;
544
+ claims += 1;
545
+ let ended = false;
546
+ return () => { if (!ended) { ended = true; claims -= 1; } };
547
+ },
548
+ /** Beside `version` in the presence the app reads. */
549
+ mark: () => ({ updateRequests: true, ...(view() ? { update: view() } : {}) }),
550
+ check,
551
+ };
552
+ }