viewable-one 0.12.2 → 0.12.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +2 -2
  3. package/SPAWN.md +107 -53
  4. package/glytch.mjs +49 -12
  5. package/lib/acp.mjs +110 -148
  6. package/lib/admission.mjs +25 -5
  7. package/lib/agents.mjs +59 -16
  8. package/lib/answerTag.mjs +47 -0
  9. package/lib/atomic.mjs +1 -16
  10. package/lib/auth.mjs +25 -9
  11. package/lib/boardside.mjs +28 -12
  12. package/lib/child.mjs +89 -116
  13. package/lib/claudeModels.mjs +168 -0
  14. package/lib/codex-rpc.mjs +2 -2
  15. package/lib/codex.mjs +43 -63
  16. package/lib/codexApps.mjs +5 -3
  17. package/lib/codexToolInputs.mjs +98 -22
  18. package/lib/codingChecks.mjs +8 -4
  19. package/lib/conversationRules.mjs +46 -6
  20. package/lib/detect.mjs +14 -23
  21. package/lib/devserver.mjs +6 -6
  22. package/lib/doctor.mjs +4 -2
  23. package/lib/folderReads.mjs +96 -0
  24. package/lib/followUps.mjs +170 -0
  25. package/lib/hosted.mjs +13 -4
  26. package/lib/init-connect.mjs +29 -10
  27. package/lib/lateResume.mjs +135 -0
  28. package/lib/logindaemon.mjs +113 -33
  29. package/lib/mcpjson.mjs +35 -2
  30. package/lib/multiwatch.mjs +80 -45
  31. package/lib/pagePictures.mjs +14 -11
  32. package/lib/paths.mjs +0 -1
  33. package/lib/permissionAsk.mjs +341 -58
  34. package/lib/procs.mjs +73 -2
  35. package/lib/refusal.mjs +0 -2
  36. package/lib/restartPass.mjs +52 -11
  37. package/lib/rowsAnswers.mjs +18 -34
  38. package/lib/rowsEvents.mjs +20 -2
  39. package/lib/runner-health.mjs +26 -2
  40. package/lib/runner.mjs +106 -1363
  41. package/lib/runnerAdmission.mjs +33 -12
  42. package/lib/runnerApi.mjs +28 -12
  43. package/lib/runnerBeat.mjs +398 -0
  44. package/lib/runnerCompletion.mjs +5 -2
  45. package/lib/runnerExecute.mjs +227 -0
  46. package/lib/runnerGates.mjs +338 -0
  47. package/lib/runnerLaunch.mjs +351 -0
  48. package/lib/runnerLease.mjs +31 -9
  49. package/lib/runnerOps.mjs +226 -0
  50. package/lib/runnerPace.mjs +10 -6
  51. package/lib/runnerRecovery.mjs +457 -0
  52. package/lib/runnerRegister.mjs +29 -8
  53. package/lib/runnerSettlement.mjs +29 -9
  54. package/lib/selfUninstall.mjs +239 -0
  55. package/lib/spawn.mjs +0 -5
  56. package/lib/sync.mjs +26 -14
  57. package/lib/update.mjs +184 -0
  58. package/lib/viewableFolder.mjs +8 -2
  59. package/lib/worktree.mjs +66 -13
  60. package/lib/writePolicy.mjs +90 -10
  61. package/package.json +1 -1
@@ -22,13 +22,13 @@ export async function prepareCompletionStore(project, settings) {
22
22
  return dir;
23
23
  }
24
24
 
25
- async function writeReceipt(project, runId, patch, settings) {
25
+ async function writeReceipt(project, runId, patch, settings, events) {
26
26
  const dir = await prepareCompletionStore(project, settings);
27
- const path = join(dir, `${digest(runId)}.json`);
27
+ const path = join(dir, `${digest(runId)}${events ? `-events-${events[0].seq}` : ""}.json`);
28
28
  const temporary = `${path}.${randomUUID()}.tmp`;
29
29
  const handle = await open(temporary, "wx", 0o600);
30
30
  try {
31
- await handle.writeFile(JSON.stringify({ projectId: project.id, runId, patch }));
31
+ await handle.writeFile(JSON.stringify({ projectId: project.id, runId, ...(settings.runGeneration ? { generation: settings.runGeneration } : {}), ...(events ? { events } : { patch }) }));
32
32
  await handle.sync();
33
33
  } finally { await handle.close(); }
34
34
  try { await rename(temporary, path); }
@@ -44,9 +44,12 @@ async function deliver(path, record, settings, log, attempts) {
44
44
  const options = { env: settings.env, fetchImpl: settings.fetchImpl };
45
45
  let last;
46
46
  for (let attempt = 0; attempt < attempts; attempt += 1) {
47
- try { last = await api.update({ runId: record.runId, patch: record.patch }, options); }
47
+ try { last = record.events
48
+ ? await api.events({ runId: record.runId, events: record.events }, options)
49
+ : await api.update({ runId: record.runId, patch: record.patch, ...(record.generation ? { generation: record.generation } : {}) }, options); }
48
50
  catch (error) { last = { ok: false, error: error.message }; }
49
- if (last?.ok) {
51
+ if (last?.ok || last?.error === "runner ownership lost") {
52
+ if (!last.ok) log(`[${record.runId}] discarded receipt from an older lease generation`);
50
53
  await unlink(path).catch(error => { if (error.code !== "ENOENT") log(`[${record.runId}] completion acknowledged; local cleanup will retry: ${error.message}`); });
51
54
  return true;
52
55
  }
@@ -59,9 +62,23 @@ async function deliver(path, record, settings, log, attempts) {
59
62
  try { return await task; } finally { replaying.delete(path); }
60
63
  }
61
64
 
65
+ /** Persist every queued event before attempting network delivery. Event names
66
+ * retain the server's (run, sequence) idempotency key across process restarts. */
67
+ export async function retainRunEvents(project, runId, events, settings) {
68
+ for (const event of events) await writeReceipt(project, runId, undefined, settings, [event]);
69
+ }
70
+
71
+ export async function deliverRunEvents(project, runId, events, settings, log = () => {}) {
72
+ for (const event of events) {
73
+ const path = join(completionDirectory(project, settings), `${digest(runId)}-events-${event.seq}.json`);
74
+ if (!await deliver(path, { projectId: project.id, runId, events: [event] }, settings, log, 1)) return { ok: false };
75
+ }
76
+ return { ok: true };
77
+ }
78
+
62
79
  export async function settleRun(project, runId, patch, settings, log = () => {}, { deferDelivery = false } = {}) {
63
80
  if (!terminal.has(patch.status)) throw new Error("A terminal receipt requires a terminal status.");
64
- const record = { projectId: project.id, runId, patch };
81
+ const record = { projectId: project.id, runId, patch, ...(settings.runGeneration ? { generation: settings.runGeneration } : {}) };
65
82
  const memoryKey = join(completionDirectory(project, settings), digest(runId));
66
83
  memoryReceipts.set(memoryKey, record);
67
84
  let path;
@@ -96,17 +113,20 @@ export async function flushCompletions(project, settings, log = () => {}) {
96
113
  let complete = true;
97
114
  for (const [key, record] of [...memoryReceipts]) {
98
115
  if (key !== join(dir, digest(record.runId))) continue;
99
- const result = await settleRun(project, record.runId, record.patch, settings, log);
116
+ const result = await settleRun(project, record.runId, record.patch, { ...settings, runGeneration: record.generation }, log);
100
117
  if (result.state === "pending-sync") complete = false;
101
118
  }
102
119
  let names;
103
120
  try { names = await readdir(dir); }
104
121
  catch (error) { if (error.code === "ENOENT") return complete; throw error; }
105
- for (const name of names.filter(name => /^[a-f0-9]{64}\.json$/.test(name))) {
122
+ for (const name of names.filter(name => /^[a-f0-9]{64}(?:-events-[1-9][0-9]*)?\.json$/.test(name)).sort((a, b) => a.localeCompare(b, "en", { numeric: true }))) {
106
123
  const path = join(dir, name);
107
124
  try {
108
125
  const record = JSON.parse(await readFile(path, "utf8"));
109
- if (record.projectId !== project.id || typeof record.runId !== "string" || `${digest(record.runId)}.json` !== name || !terminal.has(record.patch?.status)) throw new Error("Invalid saved completion receipt");
126
+ const event = record.events?.[0];
127
+ const validEvents = Array.isArray(record.events) && record.events.length === 1 && Number.isSafeInteger(event?.seq) && event.seq > 0 && ["log", "cut"].includes(event.kind) && typeof event.text === "string";
128
+ const expected = `${digest(record.runId)}${validEvents ? `-events-${event.seq}` : ""}.json`;
129
+ if (record.projectId !== project.id || typeof record.runId !== "string" || expected !== name || !(validEvents || terminal.has(record.patch?.status))) throw new Error("Invalid saved completion receipt");
110
130
  if (!(await deliver(path, record, settings, log, 1))) complete = false;
111
131
  } catch (error) {
112
132
  if (error.code === "ENOENT") continue;
@@ -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/spawn.mjs CHANGED
@@ -19,11 +19,6 @@ import { SIGN_IN_AGENTS } from "./signIn.mjs";
19
19
  // runner's local scratch lives.
20
20
  export const SPAWN_DIR = join(...segmentsOf(SPAWN_PATH));
21
21
 
22
- /** THE SAME PLACE, SPELLED FOR A PERSON. `SPAWN_DIR` above is `join`ed, so
23
- * on Windows it is `.glytch\inbox\spawn`; this is the `/`-spelled form for
24
- * anything that prints the path to a human. */
25
- export const SPAWN_DIR_IN_WORDS = SPAWN_PATH;
26
-
27
22
  // A session left running all night bills all night, so there is a default and
28
23
  // a hard cap, and the cap is what a request may ask for.
29
24
  //
package/lib/sync.mjs CHANGED
@@ -35,13 +35,14 @@ import { join } from "node:path";
35
35
  import { detectAgents, execProbe } from "./detect.mjs";
36
36
  import {
37
37
  DAEMON_LABEL,
38
- RUNNER_BY_HAND,
38
+ launcherNeedsRepair,
39
+ COMPUTER_REPAIR,
39
40
  daemonPackageVersion,
40
41
  viewableScriptPath,
41
42
  loginDaemon,
42
43
  noDaemonInstall,
43
44
  } from "./logindaemon.mjs";
44
- import { BOARD_MCP_URL, DEFAULT_BOARD_MCP_URL, mergeBoardServer } from "./mcpjson.mjs";
45
+ import { BOARD_MCP_URL, mergeBoardServer } from "./mcpjson.mjs";
45
46
  import { addFolder, readRegistry } from "./registry.mjs";
46
47
  import { readAgentSelection, parseAgentSelection } from "./agent-selection.mjs";
47
48
  import { syncProjectMcp } from "./project-mcp.mjs";
@@ -95,12 +96,12 @@ export async function syncMcpJson(root, { write = true, platform = process.platf
95
96
  ".mcp.json",
96
97
  false,
97
98
  "unreadable",
98
- `${path} exists and is not JSON we can extend. It is someone's work, so nothing was written - open it and add {"mcpServers":{"viewable":{"type":"http","url":"${DEFAULT_BOARD_MCP_URL}"}}} by hand.`,
99
+ `${path} could not be read, so nothing was changed. ${COMPUTER_REPAIR}`,
99
100
  );
100
101
  }
101
102
  if (!write) {
102
103
  return merge.kind === "legacy"
103
- ? row("mcp", ".mcp.json", false, "legacy-command", `${path} still names the retired ${merge.moved ? "board address - run viewable init to move it to app.viewable.one" : "local MCP server - run viewable init to switch it to the hosted board URL"}`)
104
+ ? row("mcp", ".mcp.json", false, "legacy-command", `${path} still uses an old connection. ${COMPUTER_REPAIR}`)
104
105
  : row("mcp", ".mcp.json", false, merge.kind, "missing the Viewable server");
105
106
  }
106
107
  await writeFile(path, merge.text, "utf8");
@@ -152,7 +153,7 @@ export async function syncRegistry(root, { env = process.env, write = true } = {
152
153
  false,
153
154
  "could not write",
154
155
  `~/.glytch/folders.json could not be written: ${why}`,
155
- "Check that ~/.glytch is writable by this account (on Windows, a locked-down or OneDrive-redirected profile can refuse it), then rerun viewable init.",
156
+ COMPUTER_REPAIR,
156
157
  );
157
158
  }
158
159
  return row("registry", "folder registered", true, "added", "added to ~/.glytch/folders.json");
@@ -287,7 +288,7 @@ export async function syncLaunchAgent({
287
288
  // Ruling 6C: an older WSL with no `systemctl --user` is told the truth and
288
289
  // given the fallback, rather than sent to `glytch init` for ever.
289
290
  if (result.unavailable) {
290
- return row("plist", label, true, "no systemd here", `wrote ${result.file}; systemctl --user is not available - run: ${RUNNER_BY_HAND}`);
291
+ return row("plist", label, true, "no systemd here", `wrote ${result.file}; the background connection is unavailable. ${COMPUTER_REPAIR}`);
291
292
  }
292
293
  return row(
293
294
  "plist",
@@ -317,6 +318,13 @@ export async function syncLaunchAgent({
317
318
  // unloaded branch is: the running daemon's own multiwatch loop must never
318
319
  // unload itself mid-sync, so it leaves this repair to `init` and `doctor`,
319
320
  // which both pass daemon:false.
321
+ const brokenLauncher = await launcherNeedsRepair(text, { env, impl });
322
+ if (daemon && brokenLauncher && write) {
323
+ const result = await impl.install({ env, ...call, path: mergePaths(captured, path, impl.pathDelimiter),
324
+ nodePath, scriptPath: impl.programScriptPath(text) ?? scriptPath, force: true, load: false });
325
+ if (!skipped && result.reloaded === false) return row("plist", label, false, "launcher not reloaded", result.why);
326
+ return row("plist", label, true, "launcher repaired", "Your computer will reconnect automatically on its next start.");
327
+ }
320
328
  if (!daemon) {
321
329
  const currentScriptPath = scriptPath ?? viewableScriptPath();
322
330
  const mismatch = await scriptMismatch({
@@ -324,7 +332,7 @@ export async function syncLaunchAgent({
324
332
  currentScriptPath,
325
333
  currentVersion: version,
326
334
  });
327
- if (mismatch || restart || replaceLoadedVersion) {
335
+ if (mismatch || restart || replaceLoadedVersion || brokenLauncher) {
328
336
  const change = mismatch ?? { oldPath: impl.programScriptPath(text), newPath: currentScriptPath, oldVersion: health?.version ?? null, newVersion: version };
329
337
  const oldVersionText = change.oldVersion ?? "unknown";
330
338
  if (!write) {
@@ -332,8 +340,8 @@ export async function syncLaunchAgent({
332
340
  "plist",
333
341
  label,
334
342
  false,
335
- "different script",
336
- `${file} runs ${change.oldPath} (${oldVersionText}); this install is ${change.newPath} (${change.newVersion})`,
343
+ brokenLauncher ? "broken launcher" : "different script",
344
+ brokenLauncher ? "The background connection needs repair." : `${file} runs ${change.oldPath} (${oldVersionText}); this install is ${change.newPath} (${change.newVersion})`,
337
345
  );
338
346
  }
339
347
  const merged = mergePaths(captured, path, impl.pathDelimiter);
@@ -348,7 +356,7 @@ export async function syncLaunchAgent({
348
356
  );
349
357
  }
350
358
  if (result.unavailable) {
351
- return row("plist", label, true, "no systemd here", `rewrote ${result.file}; systemctl --user is not available - run: ${RUNNER_BY_HAND}`);
359
+ return row("plist", label, true, "no systemd here", `rewrote ${result.file}; the background connection is unavailable. ${COMPUTER_REPAIR}`);
352
360
  }
353
361
  return row(
354
362
  "plist",
@@ -382,7 +390,7 @@ export async function syncLaunchAgent({
382
390
  return row("plist", label, false, "present, cannot be checked", `${file} is on disk; ${impl.tool} refused: ${state.why}`, state.action);
383
391
  }
384
392
  if (state.unavailable) {
385
- return row("plist", label, true, "no systemd here", `${file} is on disk; systemctl --user is not available - run: ${RUNNER_BY_HAND}`);
393
+ return row("plist", label, true, "no systemd here", `${file} is on disk; the background connection is unavailable. ${COMPUTER_REPAIR}`);
386
394
  }
387
395
  if (!write) {
388
396
  return row(
@@ -390,7 +398,7 @@ export async function syncLaunchAgent({
390
398
  label,
391
399
  false,
392
400
  "present, not loaded",
393
- `${file} is on disk but ${impl.holder} is not holding ${DAEMON_LABEL} - run: viewable init`,
401
+ `${file} is on disk but ${impl.holder} is not holding ${DAEMON_LABEL}. ${COMPUTER_REPAIR}`,
394
402
  );
395
403
  }
396
404
  const result = await impl.install({ env, ...call, path, nodePath, scriptPath, load: true });
@@ -411,12 +419,16 @@ export async function syncLaunchAgent({
411
419
  if (!write) {
412
420
  return row("plist", label, false, "stale PATH", "the captured PATH is missing entries this shell has");
413
421
  }
414
- const result = await impl.install({ env, ...call, path: merged, nodePath, scriptPath, force: true });
422
+ const result = await impl.install({ env, ...call, path: merged, nodePath, scriptPath, force: true, load: !daemon });
415
423
  if (skipped) {
416
424
  return row("plist", label, true, "PATH refreshed, not loaded", `rewrote ${result.file}; ${escape} is set, so ${impl.tool} was not run`);
417
425
  }
418
426
  if (result.unavailable) {
419
- return row("plist", label, true, "no systemd here", `rewrote ${result.file}; systemctl --user is not available - run: ${RUNNER_BY_HAND}`);
427
+ return row("plist", label, true, "no systemd here", `rewrote ${result.file}; the background connection is unavailable. ${COMPUTER_REPAIR}`);
428
+ }
429
+ if (daemon) {
430
+ if (result.reloaded === false) return row("plist", label, false, "PATH not reloaded", result.why);
431
+ return row("plist", label, true, "PATH refreshed on next start", "Your computer will use the updated connection on its next start.");
420
432
  }
421
433
  return row(
422
434
  "plist",
package/lib/update.mjs CHANGED
@@ -300,3 +300,187 @@ export async function runUpdate({
300
300
  log(`Viewable ${latest} is installed. Your computer restarted and has a fresh connection.`);
301
301
  return { ok: true, version: latest };
302
302
  }
303
+
304
+ // ---------------------------------------------------------------------------
305
+ // THE BOARD'S UPDATE BUTTON (#4949). The person presses Update in More; the
306
+ // app files a `runner_update_requests` row; the heartbeat hands this process
307
+ // an `update` op. From then on new runs wait (claims are held), and nothing
308
+ // happens to a run already going. Once no run and no run's child process is
309
+ // left, the request is TAKEN (an atomic delete on the server, so Cancel update
310
+ // and the take cannot both win), the new version installs in place, and this
311
+ // process exits with UPDATE_RESTART_EXIT_CODE. The service the computer
312
+ // already has starts it again on the new code: launchd KeepAlive and systemd
313
+ // Restart=always on any exit, Windows' RestartOnFailure on a nonzero one.
314
+ // Restarting the service from in here would kill the process doing the
315
+ // restart halfway (see multiwatch's `daemon: true`), so this never does.
316
+ //
317
+ // The daily check above stays a notice: nothing installs unless a person
318
+ // pressed Update for this computer.
319
+
320
+ /** Nonzero on purpose: Task Scheduler restarts only a failed task. */
321
+ export const UPDATE_RESTART_EXIT_CODE = 75;
322
+ const UPDATE_POLL_MS = 2_000;
323
+
324
+ const readPackageVersion = async (path) => JSON.parse(readFileSync(path, "utf8")).version;
325
+
326
+ /** Install the latest in place, for the running service to pick up when it
327
+ * restarts. Refuses BEFORE installing when npm's global copy is not the one
328
+ * this process runs (npx, Volta, a second prefix): installing elsewhere would
329
+ * change nothing, and the copy prompt still covers that computer. */
330
+ export async function installUpdate({
331
+ env = process.env, platform = process.platform, exec = execNpm, version = packageVersion(),
332
+ scriptPath = fileURLToPath(new URL("../glytch.mjs", import.meta.url)),
333
+ resolvePath = realpath, readVersion = readPackageVersion, log = () => {},
334
+ } = {}) {
335
+ const failure = (error) => ({ ok: false, error });
336
+ if (noDaemonInstall(env)) return failure("Updates are turned off on this computer.");
337
+ const npm = (args, options) => exec(args, { env, platform, ...options });
338
+ const latest = await latestFromNpm({ exec: npm });
339
+ if (!latest) return failure("Could not reach npm to find the new version.");
340
+ if (compareVersions(latest, version) <= 0) return { ok: true, version, restart: false };
341
+ const root = await npm(["root", "-g"]);
342
+ if (!root?.ok || !root.stdout.trim()) return failure("Could not find where npm installs Viewable.");
343
+ const path = platform === "win32" ? win32 : { join };
344
+ const installedScript = path.join(root.stdout.trim(), PACKAGE_NAME, "glytch.mjs");
345
+ const same = await Promise.all([resolvePath(installedScript), resolvePath(scriptPath)])
346
+ .then(([a, b]) => a === b, () => false);
347
+ if (!same) return failure("This computer runs Viewable from another folder, so it cannot update itself.");
348
+ log(`update: installing Viewable ${latest}…`);
349
+ const installed = await npm(["install", "-g", `${PACKAGE_NAME}@${latest}`, "--force"], { timeoutMs: 180_000 });
350
+ if (!installed?.ok) return failure("Installation failed. Nothing was restarted.");
351
+ const found = await readVersion(path.join(root.stdout.trim(), PACKAGE_NAME, "package.json")).catch(() => null);
352
+ if (found !== latest) return failure(`Installed, but the version reads ${found ?? "nothing"}, not ${latest}. Nothing was restarted.`);
353
+ return { ok: true, version: latest, restart: true };
354
+ }
355
+
356
+ /** One per computer app process: every folder's beat shares it.
357
+ *
358
+ * `activeRuns()` counts this process's runs AND recovery records whose child
359
+ * processes are still alive (runnerRecovery's own journal, not a second run
360
+ * tracker), so the restart comes only after the last child ends. */
361
+ export function makeSelfUpdate({
362
+ version = packageVersion(), activeRuns = async () => 0, take = async () => false,
363
+ install = (options) => installUpdate({ version, ...options }), restart = async () => {},
364
+ onChange = () => {}, log = () => {}, pollMs = UPDATE_POLL_MS,
365
+ after = setTimeout, cancel = clearTimeout,
366
+ } = {}) {
367
+ /** idle | waiting {request, runs, taken} | updating {to} | failed {error} */
368
+ let state = { name: "idle" };
369
+ let timer = null;
370
+ let checking = null;
371
+ // Claims that passed the gate before the update was asked for. Their run
372
+ // may not be counted by `activeRuns()` yet, so nothing installs until each
373
+ // one has settled and its run, if any, is counted (#4949 review).
374
+ let claims = 0;
375
+ // A take whose answer has not come back. The server deleted the request
376
+ // when it took it, so a heartbeat in between no longer lists it; the take's
377
+ // answer decides, not that heartbeat (#4949 review).
378
+ let taking = false;
379
+ // A take that failed with no answer may have won on the server, which
380
+ // deleted the request. If the request is then gone, nobody can tell a
381
+ // lost win from Cancel update, so it fails where the user can see it
382
+ // rather than vanishing; Try again files a new one (#4949 review).
383
+ let takeUnknown = false;
384
+ const lostTake = () => {
385
+ takeUnknown = false;
386
+ log("update: the board stopped answering while the update was taken; nothing was installed");
387
+ set({ name: "failed", error: "The board stopped answering while the update started. Nothing was installed." });
388
+ };
389
+ const holds = () => state.name === "waiting" || state.name === "updating";
390
+ const set = (next) => {
391
+ const before = JSON.stringify(view());
392
+ state = next;
393
+ if (JSON.stringify(view()) !== before) onChange();
394
+ };
395
+ const view = () => {
396
+ if (state.name === "waiting") return { state: "waiting", runs: state.runs ?? 0 };
397
+ if (state.name === "updating") return { state: "updating", ...(state.to ? { to: state.to } : {}) };
398
+ if (state.name === "failed") return { state: "failed", error: state.error };
399
+ return undefined;
400
+ };
401
+ const schedule = () => {
402
+ if (timer || state.name !== "waiting") return;
403
+ timer = after(() => { timer = null; void check(); }, pollMs);
404
+ timer?.unref?.();
405
+ };
406
+ const runOnce = async () => {
407
+ if (state.name !== "waiting") return;
408
+ let runs;
409
+ try { runs = await activeRuns(); }
410
+ catch (error) { log(`update: cannot tell whether runs are going (${error.message}); waiting`); return; }
411
+ if (state.name !== "waiting") return;
412
+ if (runs + claims > 0) { set({ ...state, runs: runs + claims }); return; }
413
+ if (!state.taken) {
414
+ let taken = false;
415
+ taking = true;
416
+ try { taken = await take(state.request); }
417
+ catch (error) { takeUnknown = true; log(`update: could not take the request (${error.message}); trying again`); return; }
418
+ finally { taking = false; }
419
+ if (state.name !== "waiting") return;
420
+ if (!taken && takeUnknown) { lostTake(); return; }
421
+ if (!taken) { log("update: the request was cancelled or already taken"); set({ name: "idle" }); return; }
422
+ takeUnknown = false;
423
+ state = { ...state, taken: true };
424
+ }
425
+ // A claim in flight when the request came may have started a run, or may
426
+ // still be on its way. Read both again right before installing.
427
+ const late = (await activeRuns().catch(() => 1)) + claims;
428
+ if (state.name !== "waiting") return;
429
+ if (late > 0) { set({ ...state, runs: late }); return; }
430
+ set({ name: "updating" });
431
+ let result;
432
+ try { result = await install({ log }); }
433
+ catch (error) { result = { ok: false, error: `Installation failed: ${error.message}` }; }
434
+ if (!result?.ok) {
435
+ log(`update: ${result?.error ?? "failed"}; the old version keeps running`);
436
+ set({ name: "failed", error: result?.error ?? "The update failed." });
437
+ return;
438
+ }
439
+ if (!result.restart) { log(`update: already on ${result.version ?? version}`); set({ name: "idle" }); return; }
440
+ set({ name: "updating", to: result.version });
441
+ log(`update: Viewable ${result.version} installed; restarting on it`);
442
+ await restart();
443
+ };
444
+ const check = () => {
445
+ checking ??= runOnce().finally(() => { checking = null; schedule(); });
446
+ return checking;
447
+ };
448
+ return {
449
+ /** An `update` op off a heartbeat. A second press while waiting is the
450
+ * same request; a press after a failure is Try again. */
451
+ request(op) {
452
+ if (!op?.id) return;
453
+ if (state.name === "waiting" && state.request.id === op.id) return;
454
+ if (state.name === "updating" || (state.name === "waiting" && (state.taken || taking))) return;
455
+ log(`update: asked for from the board`);
456
+ takeUnknown = false;
457
+ set({ name: "waiting", request: op, runs: state.name === "waiting" ? state.runs : 0, taken: false });
458
+ void check();
459
+ },
460
+ /** This folder's heartbeat ops. Its untaken request missing from them is
461
+ * Cancel update. Another folder's beat says nothing about it. */
462
+ seen(project, ops) {
463
+ const projectId = typeof project === "string" ? project : project?.id;
464
+ if (state.name !== "waiting" || state.taken || taking || state.request.project_id !== projectId) return;
465
+ if ((ops ?? []).some((op) => op.kind === "update" && op.id === state.request.id)) return;
466
+ if (timer) { cancel(timer); timer = null; }
467
+ if (takeUnknown) { lostTake(); return; }
468
+ log("update: cancelled from the board");
469
+ set({ name: "idle" });
470
+ },
471
+ /** New runs wait while an update is asked for or installing. */
472
+ holdsRuns: holds,
473
+ /** The claim gate and its count in one step: null while runs are held,
474
+ * else the call that says this claim has settled and its run, if any,
475
+ * is counted by `activeRuns()`. */
476
+ claimStarted() {
477
+ if (holds()) return null;
478
+ claims += 1;
479
+ let ended = false;
480
+ return () => { if (!ended) { ended = true; claims -= 1; } };
481
+ },
482
+ /** Beside `version` in the presence the app reads. */
483
+ mark: () => ({ updateRequests: true, ...(view() ? { update: view() } : {}) }),
484
+ check,
485
+ };
486
+ }