viewable-one 0.12.2 → 0.12.3

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 (59) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +2 -2
  3. package/SPAWN.md +107 -53
  4. package/glytch.mjs +41 -10
  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 +25 -38
  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 +39 -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 +6 -12
  42. package/lib/runnerApi.mjs +20 -11
  43. package/lib/runnerBeat.mjs +384 -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 +217 -0
  50. package/lib/runnerPace.mjs +10 -6
  51. package/lib/runnerRecovery.mjs +457 -0
  52. package/lib/runnerRegister.mjs +28 -7
  53. package/lib/runnerSettlement.mjs +29 -9
  54. package/lib/spawn.mjs +0 -5
  55. package/lib/sync.mjs +26 -14
  56. package/lib/viewableFolder.mjs +8 -2
  57. package/lib/worktree.mjs +66 -13
  58. package/lib/writePolicy.mjs +90 -10
  59. package/package.json +1 -1
@@ -0,0 +1,135 @@
1
+ // Finished-session messages use the existing permission ask and resume doors
2
+ // (#5101, #5103). No child runs while an answer waits, and no message is acked
3
+ // until declined or durably filed. Permission memory stays per linked folder.
4
+ import { acquireAdmission } from "./admission.mjs";
5
+ import { basename, join } from "node:path";
6
+ import { mkdir, readFile } from "node:fs/promises";
7
+ import { askUserOnBoard } from "./boardside.mjs";
8
+ import { ALLOW, NOT_THIS, alwaysLabel, readAnswer, readRules, rememberRule, verdictFor } from "./permissionAsk.mjs";
9
+ import { writeFileAtomic } from "./atomic.mjs";
10
+ import { viewableHome } from "./registry.mjs";
11
+ import { callRunnerTool } from "./hosted.mjs";
12
+ import * as runnerApi from "./runnerApi.mjs";
13
+ import { promoteLateRows } from "./rowsAnswers.mjs";
14
+
15
+ /** One nonblocking look at a permission. The receipt survives watcher restarts;
16
+ * the account/project scope prevents a different sign-in inheriting a grant. */
17
+ export async function allowLateResume(root, run, promotionId, settings, log = () => {}) {
18
+ const env = settings.env;
19
+ const key = `Continue(${run.user_id}:${run.project_id})`;
20
+ const directory = join(viewableHome(env), "resume-asks");
21
+ const path = join(directory, `${promotionId}.json`);
22
+ let saved;
23
+ try { saved = JSON.parse(await readFile(path, "utf8")); }
24
+ catch (error) { if (error.code !== "ENOENT") throw error; }
25
+ const callTool = (name, args, options) => (settings.hostedCallTool ?? callRunnerTool)(name, args, { ...options, sessionBoardId: run.board_id });
26
+ const options = { sessionKey: run.session_key ?? run.id, env };
27
+ const folderName = basename(root) || root;
28
+ // A prior explicit refusal stays refused even if another ask saves Always.
29
+ if (saved?.decision) return saved.decision;
30
+ if (!saved && (await readRules(env, root)).includes(key)) return "allow";
31
+ if (!saved) {
32
+ // Keyed on the promotion id: a lost reply or a receipt that did not save
33
+ // gets the same question back on the next beat, never a second one (#5106).
34
+ const filed = await askUserOnBoard({ key: options.sessionKey }, "Allow the agent to continue with the new answer?", {
35
+ fromId: run.from_id, purpose: "permission", askKey: promotionId,
36
+ why: "The agent finished before this answer arrived. Allow continues its session. Always allow lets later answers continue agents in this folder without asking.",
37
+ options: [ALLOW, NOT_THIS, alwaysLabel(folderName)],
38
+ recommendation: { answer: ALLOW, why: "Let the agent use the answer to continue its work." },
39
+ }, { callTool, env });
40
+ if (!filed.ok || !filed.questionId) {
41
+ // A refused ask (its idea deleted, the run stopped) never succeeds on
42
+ // a later beat; a transport failure may, so only that one retries.
43
+ throw Object.assign(new Error(filed.detail ?? "Could not ask to continue."), { refused: filed.refused === true });
44
+ }
45
+ saved = { questionId: filed.questionId };
46
+ await mkdir(directory, { recursive: true, mode: 0o700 });
47
+ await writeFileAtomic(path, JSON.stringify(saved));
48
+ }
49
+ const result = await callTool("check_answer", { question_id: saved.questionId, wait_s: 0 }, options);
50
+ if (result.isError && readAnswer(result.text).state !== "gone") throw new Error(result.text);
51
+ const answer = readAnswer(result.text);
52
+ // ALWAYS ALLOW RELEASES ASKS ALREADY WAITING (#5106). An open ask on this
53
+ // run lets go once another run's ask saved Always for the folder. An answer
54
+ // given on this ask itself is read first, so its own "Not this" still wins.
55
+ const released = answer.state === "open" && (await readRules(env, root)).includes(key);
56
+ if (answer.state === "open" && !released) return "waiting";
57
+ const verdict = released ? { behavior: "allow" } : verdictFor(answer, folderName);
58
+ if (verdict.remember) await rememberRule(env, root, key);
59
+ saved.decision = verdict.behavior;
60
+ await writeFileAtomic(path, JSON.stringify(saved));
61
+ log(`[${run.id}] continuation ${saved.decision}`);
62
+ return saved.decision;
63
+ }
64
+
65
+ /** The statuses board-runner's resume accepts; the heartbeat covers each. */
66
+ const FINISHED = ["done", "error", "stopped"];
67
+
68
+ /** Whether resume could carry this run on at all, by the same conversation
69
+ * id board-runner's resume reads. The server re-checks. */
70
+ const continuable = run => run.approved === true && !run.stop_requested_at
71
+ && Boolean(run.request?.agent === "codex" ? run.sidecar?.codexThreadId : run.sidecar?.claudeSessionId);
72
+
73
+ /** Mark a message on the run's sidecar before it is acknowledged, so the app
74
+ * shows "did not reach the session" with Try again. Throws if the mark could
75
+ * not be saved, so the message stays unacknowledged and the next beat retries. */
76
+ async function markUndelivered(api, run, message, options) {
77
+ if (!message) return;
78
+ const list = Array.isArray(run.sidecar?.undelivered) ? run.sidecar.undelivered : [];
79
+ if (list.some(m => m.from === message.from && m.text === message.text)) return;
80
+ const sidecar = { ...(run.sidecar ?? {}), undelivered: [...list, { from: message.from, text: message.text }] };
81
+ const out = await api.update({ runId: run.id, patch: { sidecar } }, options);
82
+ if (!out.ok) throw new Error(out.error);
83
+ run.sidecar = out.run?.sidecar ?? sidecar;
84
+ }
85
+
86
+ /** The heartbeat revisits undelivered messages, including reviews decided long
87
+ * after exit. The server lists this account's finished app runs in every
88
+ * status resume accepts. A run that can continue asks first; a message that
89
+ * cannot be asked about or carried on is declined and marked undelivered,
90
+ * never left unread. Returns how many runs the server listed. */
91
+ export async function resumeLateMessages(project, settings, log = () => {}) {
92
+ if (settings.enabled !== true) return 0;
93
+ const held = await acquireAdmission(project.path, { directory: join(viewableHome(settings.env), "resume-asks") });
94
+ if (!held.ok) return 0;
95
+ try {
96
+ const api = settings.runnerApi ?? runnerApi;
97
+ const options = { env: settings.env, fetchImpl: settings.fetchImpl };
98
+ const listed = await api.runs({ projectIds: [project.id], lateMessages: true }, options);
99
+ if (!listed.ok) throw new Error(listed.error);
100
+ const waiting = listed.runs ?? [];
101
+ for (const run of waiting) {
102
+ if (!FINISHED.includes(run.status) || (!run.from_id && !run.request?.roomId)) continue;
103
+ try {
104
+ const callTool = (name, args, opts) => (settings.hostedCallTool ?? callRunnerTool)(name, args, { ...opts, sessionBoardId: run.board_id });
105
+ await promoteLateRows(project.path, run.id, {
106
+ poller: { since: () => 0, hasDelivered: () => true }, // question answers belong to their existing consumer
107
+ callTool, sessionKey: run.session_key ?? run.id, env: settings.env,
108
+ messageLimit: 1,
109
+ promote: async (root, id, reply, logger, promotionId) => {
110
+ const decline = async why => {
111
+ await markUndelivered(api, run, reply.message, options);
112
+ logger(`[${id}] late message not carried on: ${why}`);
113
+ return { declined: true };
114
+ };
115
+ if (!continuable(run)) return decline("this session cannot be continued");
116
+ let decision;
117
+ try { decision = await allowLateResume(root, run, promotionId, settings, logger); }
118
+ catch (error) { if (error?.refused) return decline(error.message); throw error; }
119
+ if (decision === "waiting") return { waiting: true };
120
+ if (decision === "deny") return decline("not allowed");
121
+ const out = await api.resume({ runId: id, message: reply.text, images: reply.images, promotionId }, options);
122
+ if (!out.ok && out.refused && !out.retry) return decline(out.error);
123
+ if (!out.ok) throw new Error(out.error);
124
+ return out.run?.id ?? out.id ?? null;
125
+ },
126
+ }, log);
127
+ } catch (error) {
128
+ log(`[${run.id}] late message continuation failed: ${error?.message ?? error}`);
129
+ }
130
+ }
131
+ // How many runs still had messages waiting: the heartbeat looks again
132
+ // soon while any do, and rarely while none do (runnerBeat.mjs).
133
+ return waiting.length;
134
+ } finally { await held.release(); }
135
+ }
@@ -232,6 +232,85 @@ async function ensureLogDir(env) {
232
232
  await mkdir(logDir(env), { recursive: true });
233
233
  }
234
234
 
235
+ /** Stable entry point: the OS can start this even after Node's versioned
236
+ * directory disappears. The existing installer still owns installation. */
237
+ export const posixLauncherPath = (env = process.env) => join(viewableHome(env), "runner-launcher.sh");
238
+ const shQuote = (value) => "'" + String(value).replace(/'/g, "'\\''") + "'";
239
+
240
+ export function renderPosixLauncher({ nodePath = process.execPath, env = process.env, shellTimeoutSeconds = 5 } = {}) {
241
+ return `#!/bin/sh
242
+ # Viewable launcher v1
243
+ SHELL=${shQuote(env.SHELL || "/bin/sh")}
244
+ export SHELL
245
+ node_bin=
246
+ # Read the current profile, including nvm/fnm configuration. Ignore banners.
247
+ for mode in -lc -ilc; do
248
+ # Redirect to a file so a profile's descendants cannot hold a substitution
249
+ # pipe open after the shell itself times out. No external timeout on macOS.
250
+ lookup_dir=$(/usr/bin/mktemp -d "\${TMPDIR:-/tmp}/viewable-node.XXXXXX") || continue
251
+ "$SHELL" "$mode" 'command -v node' >"$lookup_dir/path" 2>/dev/null &
252
+ lookup_pid=$!
253
+ (
254
+ trap 'kill "$sleeper" 2>/dev/null; exit' TERM INT
255
+ /bin/sleep ${shQuote(shellTimeoutSeconds)} &
256
+ sleeper=$!
257
+ wait "$sleeper"
258
+ kill -KILL "$lookup_pid" 2>/dev/null
259
+ ) >/dev/null 2>&1 &
260
+ watchdog=$!
261
+ wait "$lookup_pid" 2>/dev/null
262
+ kill "$watchdog" 2>/dev/null
263
+ wait "$watchdog" 2>/dev/null
264
+ found=$(/bin/cat "$lookup_dir/path")
265
+ /bin/rm -rf "$lookup_dir"
266
+ while IFS= read -r candidate; do
267
+ case "$candidate" in /*)
268
+ if [ -x "$candidate" ] && "$candidate" -e 'process.exit(+process.versions.node.split(".")[0]>=22?0:1)' 2>/dev/null; then node_bin=$candidate; fi
269
+ ;; esac
270
+ done <<EOF
271
+ $found
272
+ EOF
273
+ [ -z "$node_bin" ] || break
274
+ done
275
+ if [ -z "$node_bin" ]; then
276
+ for candidate in ${shQuote(nodePath)} \
277
+ "$HOME/.local/share/fnm/aliases/default/bin/node" \
278
+ "$HOME/Library/Application Support/fnm/aliases/default/bin/node" \
279
+ "\${FNM_DIR:-$HOME/.local/share/fnm}"/node-versions/*/installation/bin/node \
280
+ "\${NVM_DIR:-$HOME/.nvm}"/versions/node/*/bin/node \
281
+ /opt/homebrew/bin/node /usr/local/bin/node /usr/bin/node; do
282
+ if [ -x "$candidate" ] && "$candidate" -e 'process.exit(+process.versions.node.split(".")[0]>=22?0:1)' 2>/dev/null; then node_bin=$candidate; break; fi
283
+ done
284
+ fi
285
+ if [ -z "$node_bin" ]; then
286
+ echo "Your computer could not reconnect. Open Claude Code or Codex and ask it to repair the computer connection." >&2
287
+ exit 1
288
+ fi
289
+ PATH="\${node_bin%/*}:$PATH"
290
+ export PATH
291
+ script=$1
292
+ shift
293
+ if [ ! -f "$script" ]; then
294
+ script="\${node_bin%/*}/../lib/node_modules/viewable-one/glytch.mjs"
295
+ fi
296
+ exec "$node_bin" "$script" "$@"
297
+ `;
298
+ }
299
+
300
+ /** Report legacy or broken service launchers through the same sync doctor uses. */
301
+ export async function launcherNeedsRepair(text, { env = process.env, impl } = {}) {
302
+ if (impl.kind === "schtasks" || !impl.programScriptPath(text)) return false;
303
+ const launcher = posixLauncherPath(env);
304
+ const expected = impl.kind === "launchd" ? xml(launcher) : launcher;
305
+ if (!text.includes(expected)) return true;
306
+ const content = await readFile(launcher, "utf8").catch(() => "");
307
+ return !content.startsWith("#!/bin/sh\n# Viewable launcher v1\n");
308
+ }
309
+
310
+ async function writePosixLauncher(env, nodePath, force) {
311
+ await writeIfAbsent(posixLauncherPath(env), renderPosixLauncher({ env, nodePath }), force);
312
+ }
313
+
235
314
  // ---------------------------------------------------------------- launchd --
236
315
 
237
316
  const xml = (text) =>
@@ -240,6 +319,8 @@ const xml = (text) =>
240
319
  .replace(/</g, "&lt;")
241
320
  .replace(/>/g, "&gt;");
242
321
 
322
+ const unxml = (text) => String(text).replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
323
+
243
324
  /** Where the plist goes. ~/Library/LaunchAgents on a real machine; under
244
325
  * GLYTCH_HOME when it is set, which is what keeps the suite off this Mac. */
245
326
  export const plistPath = (env = process.env) =>
@@ -255,6 +336,7 @@ export function renderPlist({
255
336
  path = process.env.PATH ?? "",
256
337
  out = logPath(),
257
338
  home,
339
+ launcher,
258
340
  } = {}) {
259
341
  const env = [
260
342
  // The switch. A daemon is still not consent by itself: this is the same
@@ -273,8 +355,8 @@ export function renderPlist({
273
355
  <string>${xml(DAEMON_LABEL)}</string>
274
356
  <key>ProgramArguments</key>
275
357
  <array>
276
- <string>${xml(nodePath)}</string>
277
- <string>${xml(scriptPath)}</string>
358
+ <string>${xml(launcher ? "/bin/sh" : nodePath)}</string>
359
+ ${launcher ? ` <string>${xml(launcher)}</string>\n` : ""} <string>${xml(scriptPath)}</string>
278
360
  <string>runner</string>
279
361
  <string>watch</string>
280
362
  </array>
@@ -300,7 +382,7 @@ ${env.map(([k, v]) => ` <key>${xml(k)}</key>\n <string>${xml(v)}</string>`
300
382
  * installed is a daemon that cannot find the engine the app is offering. */
301
383
  export function capturedPlistPath(text) {
302
384
  const match = /<key>PATH<\/key>\s*<string>([^<]*)<\/string>/.exec(String(text ?? ""));
303
- return match ? match[1] : null;
385
+ return match ? unxml(match[1]) : null;
304
386
  }
305
387
 
306
388
  /** The script path a plist's ProgramArguments carries - the SECOND
@@ -313,8 +395,8 @@ export function capturedPlistPath(text) {
313
395
  export function scriptPathFromPlist(text) {
314
396
  const args = /<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(String(text ?? ""));
315
397
  if (!args) return null;
316
- const strings = [...args[1].matchAll(/<string>([^<]*)<\/string>/g)].map((m) => m[1]);
317
- return strings[1] ?? null;
398
+ const strings = [...args[1].matchAll(/<string>([^<]*)<\/string>/g)].map((m) => unxml(m[1]));
399
+ return strings[strings[0] === "/bin/sh" ? 2 : 1] ?? null;
318
400
  }
319
401
 
320
402
  const launchd = {
@@ -356,9 +438,11 @@ const launchd = {
356
438
  return exec(args, env);
357
439
  };
358
440
  await ensureLogDir(env);
441
+ await writePosixLauncher(env, nodePath, force);
359
442
  const wrote = await writeIfAbsent(
360
443
  file,
361
444
  renderPlist({
445
+ launcher: posixLauncherPath(env),
362
446
  nodePath,
363
447
  scriptPath,
364
448
  path,
@@ -395,7 +479,10 @@ const launchd = {
395
479
  }
396
480
  calls.push(["unload", "-w", file]);
397
481
  const result = await exec(["unload", "-w", file], env);
398
- if (removeFile) await rm(file, { force: true }).catch(() => {});
482
+ if (removeFile) {
483
+ await rm(file, { force: true }).catch(() => {});
484
+ await rm(posixLauncherPath(env), { force: true }).catch(() => {});
485
+ }
399
486
  return {
400
487
  file,
401
488
  unloaded: result.ok === true,
@@ -590,26 +677,15 @@ async function writeTaskXml(file, text) {
590
677
 
591
678
  /** Is this Task Scheduler refusing US, rather than a task that is not there?
592
679
  * Told apart because the two need opposite answers: a missing task is
593
- * installed, and a refused one is a person opening an elevated terminal. */
680
+ * installed, and a refused one needs help repairing the connection. */
594
681
  export const schtasksDenied = (result) =>
595
682
  /access is denied|do(es)? not have permission|requires elevation/i.test(
596
683
  `${result?.stderr ?? ""} ${result?.stdout ?? ""}`,
597
684
  );
598
685
 
599
- /** What to type on Windows when the daemon cannot be registered.
600
- * POWERSHELL'S SPELLING, because that is the shell VS Code and Windows
601
- * Terminal open - `PM_SPAWN_RUNNER=on viewable runner watch` is POSIX syntax
602
- * that neither PowerShell nor cmd.exe has, so RUNNER_BY_HAND pasted there is
603
- * an error rather than a runner. cmd.exe's own is `set PM_SPAWN_RUNNER=on &&
604
- * viewable runner watch`; the README carries both. */
605
- export const RUNNER_BY_HAND_WINDOWS = '$env:PM_SPAWN_RUNNER="on"; viewable runner watch';
606
-
607
- /** The one next step a denied registration leaves. It travels on the row as
608
- * `action`, so doctor prints THIS under "Next steps" instead of its default
609
- * "run viewable init", which is the advice that looped. */
610
- export const ELEVATED_INIT =
611
- 'Task Scheduler refused the registration. Open a terminal with "Run as administrator" and run viewable init once from this project folder' +
612
- ` - or skip the daemon and run the runner by hand: ${RUNNER_BY_HAND_WINDOWS}`;
686
+ /** One repair instruction for service registration and startup failures. */
687
+ export const COMPUTER_REPAIR = "Open Claude Code or Codex and ask it to install or repair the computer connection.";
688
+ export const ELEVATED_INIT = `Your computer could not connect in the background. ${COMPUTER_REPAIR}`;
613
689
 
614
690
  const schtasks = {
615
691
  kind: "schtasks",
@@ -780,6 +856,7 @@ export const unitPath = (env = process.env) =>
780
856
  * Environment on whitespace otherwise, and a home directory with a space in
781
857
  * it is ordinary. */
782
858
  export function renderUnit({
859
+ launcher,
783
860
  nodePath = process.execPath,
784
861
  scriptPath = viewableScriptPath(),
785
862
  path = process.env.PATH ?? "",
@@ -794,7 +871,7 @@ After=default.target
794
871
 
795
872
  [Service]
796
873
  Type=simple
797
- ExecStart="${q(nodePath)}" "${q(scriptPath)}" runner watch
874
+ ExecStart="${q(launcher ? "/bin/sh" : nodePath)}" ${launcher ? `"${q(launcher)}" ` : ""}"${q(scriptPath)}" runner watch
798
875
  Environment="PM_SPAWN_RUNNER=on"
799
876
  Environment="PATH=${q(path)}"
800
877
  ${home ? `Environment="VIEWABLE_HOME=${q(home)}"\n` : ""}# KeepAlive, in systemd's words. The mac's plist asks for the same thing.
@@ -811,14 +888,14 @@ WantedBy=default.target
811
888
  /** The PATH the unit carries, or null. */
812
889
  export function capturedUnitPath(text) {
813
890
  const match = /^Environment="PATH=(.*)"$/m.exec(String(text ?? ""));
814
- return match ? match[1] : null;
891
+ return match ? match[1].replace(/\\"/g, '"') : null;
815
892
  }
816
893
 
817
894
  /** The script path a systemd unit's ExecStart runs - the second quoted
818
895
  * argument, after the node binary - or null. The Linux/WSL half of the same
819
896
  * daemon-version check (brief 31, Move 5). */
820
897
  export function scriptPathFromUnit(text) {
821
- const match = /^ExecStart="[^"]*"\s+"([^"]*)"\s+runner watch\b/m.exec(String(text ?? ""));
898
+ const match = /^ExecStart="[^"]*"\s+(?:"[^"]*runner-launcher\.sh"\s+)?"([^"]*)"\s+runner watch\b/m.exec(String(text ?? ""));
822
899
  return match ? match[1] : null;
823
900
  }
824
901
 
@@ -832,9 +909,6 @@ export const systemctlUnavailable = (result) =>
832
909
  `${result?.stderr ?? ""}`,
833
910
  ) || result?.code === "ENOENT";
834
911
 
835
- /** What to type when there is no systemd to install into. */
836
- export const RUNNER_BY_HAND = "PM_SPAWN_RUNNER=on viewable runner watch";
837
-
838
912
  const systemd = {
839
913
  kind: "systemd",
840
914
  platforms: ["wsl", "linux"],
@@ -866,9 +940,11 @@ const systemd = {
866
940
  return exec(args, env);
867
941
  };
868
942
  await ensureLogDir(env);
943
+ await writePosixLauncher(env, nodePath, force);
869
944
  const wrote = await writeIfAbsent(
870
945
  file,
871
946
  renderUnit({
947
+ launcher: posixLauncherPath(env),
872
948
  nodePath,
873
949
  scriptPath,
874
950
  path,
@@ -877,7 +953,7 @@ const systemd = {
877
953
  }),
878
954
  force,
879
955
  );
880
- if (!load) return { file, wrote, loaded: false, why: "not asked to load", calls };
956
+ if (!load && !wrote) return { file, wrote, loaded: false, why: "not asked to load", calls };
881
957
  // DAEMON-RELOAD FIRST, ALWAYS. systemd caches unit files, so a rewritten
882
958
  // unit that is never re-read keeps running the OLD one - the same failure
883
959
  // the plist's unload-then-load prevents. `enable --now` then both
@@ -886,9 +962,10 @@ const systemd = {
886
962
  const reloaded = await run(["--user", "daemon-reload"]);
887
963
  if (!reloaded.ok) {
888
964
  const unavailable = systemctlUnavailable(reloaded);
889
- return { file, wrote, loaded: false, unavailable,
890
- why: unavailable ? `systemctl --user is not available on your computer: run ${RUNNER_BY_HAND}` : reloaded.stderr?.trim() || "systemctl daemon-reload failed", calls };
965
+ return { file, wrote, loaded: false, reloaded: false, unavailable,
966
+ why: unavailable ? `Your computer cannot connect in the background yet. ${COMPUTER_REPAIR}` : reloaded.stderr?.trim() || "systemctl daemon-reload failed", calls };
891
967
  }
968
+ if (!load) return { file, wrote, loaded: false, reloaded: true, why: "not asked to load", calls };
892
969
  let enabled = await run(["--user", "enable", "--now", UNIT_NAME]);
893
970
  // enable --now leaves an already-running process alone, even after the
894
971
  // file at ExecStart was replaced. Explicit repair/update must reload it.
@@ -902,7 +979,7 @@ const systemd = {
902
979
  why: enabled.ok === true
903
980
  ? ""
904
981
  : unavailable
905
- ? `systemctl --user is not available on your computer: run ${RUNNER_BY_HAND}`
982
+ ? `Your computer cannot connect in the background yet. ${COMPUTER_REPAIR}`
906
983
  : enabled.stderr.trim() || `systemctl --user enable exited ${enabled.code}`,
907
984
  calls,
908
985
  };
@@ -917,7 +994,10 @@ const systemd = {
917
994
  }
918
995
  calls.push(["--user", "disable", "--now", UNIT_NAME]);
919
996
  const result = await exec(["--user", "disable", "--now", UNIT_NAME], env);
920
- if (removeFile) await rm(file, { force: true }).catch(() => {});
997
+ if (removeFile) {
998
+ await rm(file, { force: true }).catch(() => {});
999
+ await rm(posixLauncherPath(env), { force: true }).catch(() => {});
1000
+ }
921
1001
  return {
922
1002
  file,
923
1003
  unloaded: result.ok === true,
@@ -936,7 +1016,7 @@ const systemd = {
936
1016
  loaded: false,
937
1017
  unavailable,
938
1018
  why: unavailable
939
- ? `systemctl --user is not available on your computer: run ${RUNNER_BY_HAND}`
1019
+ ? `Your computer cannot connect in the background yet. ${COMPUTER_REPAIR}`
940
1020
  : result.stderr?.trim() ?? "",
941
1021
  };
942
1022
  },
package/lib/mcpjson.mjs CHANGED
@@ -71,14 +71,47 @@ export const DEFAULT_BOARD_MCP_URL = "https://app.viewable.one/mcp";
71
71
  * other bridge file imports it from here. */
72
72
  export const RETIRED_BOARD_MCP_URL = `${RETIRED_APP_URL}/mcp`;
73
73
  export const RETIRED_BOARD_MCP_URLS = RETIRED_APP_URLS.map(origin => `${origin}/mcp`);
74
+ /** Is this address the board endpoint on a retired host? Compared by parsed
75
+ * origin, not by string (#3736): scheme is ignored (http or https), the host
76
+ * is case-insensitive and may end in a dot, a default port is dropped, and the path must be /mcp in
77
+ * any case (repeated and trailing slashes allowed) with any query or fragment. */
78
+ export function isRetiredBoardUrl(value) {
79
+ if (typeof value !== "string") return false;
80
+ let url;
81
+ try { url = new URL(value.trim()); } catch { return false; }
82
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
83
+ // The path is /mcp in any case, with repeated or trailing slashes ("//mcp",
84
+ // "/MCP/"); the host may end in a dot ("app.glytch.ai.").
85
+ if (url.pathname.toLowerCase().replace(/\/{2,}/g, "/").replace(/\/+$/, "") !== "/mcp") return false;
86
+ // `new URL` lowercases the host and drops the scheme's default port; the
87
+ // other scheme's default (http on 443, https on 80) is dropped here.
88
+ const port = url.port === "" || url.port === "80" || url.port === "443" ? "" : `:${url.port}`;
89
+ const hostname = url.hostname.replace(/\.+$/, "");
90
+ return RETIRED_APP_URLS.some(origin => new URL(origin).host === `${hostname}${port}`);
91
+ }
74
92
  export const BOARD_MCP_URL = (env = process.env) => {
75
93
  const value = (env?.VIEWABLE_BOARD_URL ?? env?.GLYTCH_BOARD_URL);
76
94
  return typeof value === "string" && value.trim() !== "" ? value.trim() : DEFAULT_BOARD_MCP_URL;
77
95
  };
78
96
  /** Run children already have a bearer, so use the runner's direct function
79
97
  * host for the production MCP endpoint. Keep discovered/custom endpoints.
80
- * The hosted project address stays owned by runnerApiUrlFrom (#813). */
81
- export function runnerMcpUrlFrom({ appUrl, mcpUrl }, env = process.env) {
98
+ * The hosted project address stays owned by runnerApiUrlFrom (#813).
99
+ *
100
+ * A developer's `GLYTCH_BOARD_URL` / `VIEWABLE_BOARD_URL` wins over the
101
+ * app-derived address (#3705). Without it a runner on the local stack posted
102
+ * its collect and report calls to `<stack>/mcp`, which is not the board
103
+ * function (the stack answers 406 "Client must accept both application/json
104
+ * and text/event-stream"), so a finished run never wrote its summary.
105
+ *
106
+ * An override at a RETIRED host is not followed (#3717). Those hosts answer
107
+ * with a redirect, and a cross-origin redirect drops the Authorization
108
+ * header, so the runner would lose its sign-in. It is treated as unset (the
109
+ * derived function host is used) and `warn`, when given, is told why. */
110
+ export function runnerMcpUrlFrom({ appUrl, mcpUrl }, env = process.env, warn) {
111
+ const override = BOARD_MCP_URL(env);
112
+ if (isRetiredBoardUrl(override)) {
113
+ warn?.(`The board address ${override} is retired and redirects without the sign-in header; using the board function instead. Unset VIEWABLE_BOARD_URL or set it to ${DEFAULT_BOARD_MCP_URL}.`);
114
+ } else if (override !== DEFAULT_BOARD_MCP_URL) return override;
82
115
  if (appUrl !== DEFAULT_APP_URL || mcpUrl !== DEFAULT_BOARD_MCP_URL) return mcpUrl;
83
116
  const runnerUrl = new URL(runnerApiUrlFrom(appUrl, env));
84
117
  // A trailing slash still names the runner endpoint, not a directory.
@@ -38,9 +38,8 @@
38
38
  // gets its sync and its watcher without anything being restarted.
39
39
 
40
40
  import { makeRunnerHealth } from "./runner-health.mjs";
41
- import { watch as fsWatch } from "node:fs";
41
+ import { unwatchFile, watchFile } from "node:fs";
42
42
  import { stat } from "node:fs/promises";
43
- import { basename, dirname } from "node:path";
44
43
  import { makeAgentProbe } from "./detect.mjs";
45
44
  import { platformMark } from "./platform.mjs";
46
45
  import { ensureViewableFolder } from "./viewableFolder.mjs";
@@ -54,13 +53,15 @@ import { syncFolder } from "./sync.mjs";
54
53
  import { makeUpdateChecker, packageVersion } from "./update.mjs";
55
54
 
56
55
  export const SWEEP_INTERVAL_MS = 86_400_000;
57
- /** How often the registry is re-read when fs.watch tells us nothing. The
58
- * floor, not the mechanism: fs.watch answers in milliseconds when it fires at
59
- * all, and this is what catches the cases where it does not - a network home
60
- * directory, an editor that swaps the file in a way the watch misses, a
61
- * platform that drops the event. A minute is invisible to a person typing
62
- * `viewable init` and then switching to the app. */
56
+ /** How often the registry is re-read when the stat poll below tells us
57
+ * nothing. The floor, not the mechanism: the stat poll answers within
58
+ * REGISTRY_STAT_MS, and this is what catches the cases where it does not - a
59
+ * network home directory, a file system whose stat times do not move. A
60
+ * minute is invisible to a person typing `viewable init` and then switching
61
+ * to the app. */
63
62
  export const REGISTRY_POLL_MS = 60_000;
63
+ /** How often the registry file is stat'ed for a change (fs.watchFile). */
64
+ export const REGISTRY_STAT_MS = 1_000;
64
65
 
65
66
  const isDir = async (path) => {
66
67
  try {
@@ -366,33 +367,25 @@ export async function watchRegistered({
366
367
  }
367
368
  };
368
369
 
369
- // BOTH THE FILE AND ITS DIRECTORY. `folders.json` is written by
370
- // writeFileAtomic, which renames a temp file over it, so the inode a watch
371
- // on the file is holding is not the one the next read opens - the file
372
- // watch sees the first write and then nothing. The directory watch sees the
373
- // rename. Neither is trusted: setInterval below is the floor, and a
374
- // platform where fs.watch does nothing at all still picks a new folder up
375
- // within registryPollMs.
370
+ // A STAT POLL ON THE FILE, NOT fs.watch (#4726). fs.watchFile stats the
371
+ // path, so it sees writeFileAtomic's rename, an edit in place and a file
372
+ // that does not exist yet. A folder fs.watch on macOS starts FSEvents, and
373
+ // closing it waits on fseventsd: a stuck one froze Ctrl-C on `runner watch`
374
+ // forever. setInterval below is still the floor.
376
375
  const regPath = registryPath(env);
377
- const regName = basename(regPath);
378
- const fsWatchers = [];
379
- const attach = (target, onlyRegistry) => {
376
+ const onRegistryStat = (now, before) => {
377
+ if (now.mtimeMs === before.mtimeMs && now.ino === before.ino && now.size === before.size) return;
378
+ void refresh();
379
+ };
380
+ let statWatching = false;
381
+ if (!pinned) {
380
382
  try {
381
- const w = fsWatch(target, (_event, filename) => {
382
- if (onlyRegistry && filename && basename(String(filename)) !== regName) return;
383
- void refresh();
384
- });
385
- w.on("error", () => {}); // a dead watch is not an exit; the poll covers it
386
- w.unref?.();
387
- fsWatchers.push(w);
383
+ // persistent: false - the keepAlive below owns the process lifetime.
384
+ watchFile(regPath, { persistent: false, interval: REGISTRY_STAT_MS }, onRegistryStat);
385
+ statWatching = true;
388
386
  } catch {
389
- // The file may not exist yet, the directory may not be watchable: the
390
- // poll is the answer to both.
387
+ // A path that cannot be stat-watched is not an exit; the poll covers it.
391
388
  }
392
- };
393
- if (!pinned) {
394
- attach(regPath, false);
395
- attach(dirname(regPath), true);
396
389
  }
397
390
  const polling = setInterval(() => void refresh(), registryPollMs);
398
391
  polling.unref?.();
@@ -416,13 +409,7 @@ export async function watchRegistered({
416
409
  signal?.removeEventListener("abort", bump);
417
410
  clearInterval(sweeping);
418
411
  clearInterval(polling);
419
- for (const w of fsWatchers) {
420
- try {
421
- w.close();
422
- } catch {
423
- // closing twice, or after an error, is not a failure worth a line
424
- }
425
- }
412
+ if (statWatching) unwatchFile(regPath, onRegistryStat);
426
413
  }
427
414
  return { watched, missing };
428
415
  }