viewable-one 0.12.4 → 0.12.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/registry.mjs CHANGED
@@ -25,6 +25,14 @@ import { acquireAdmission } from "./admission.mjs";
25
25
  export const viewableHome = (env = process.env) =>
26
26
  (env.VIEWABLE_HOME ?? env.GLYTCH_HOME)?.trim() || join(homedir(), ".glytch");
27
27
 
28
+ /** Display only: resolve through the storage helper, abbreviating the default home. */
29
+ export function viewableDisplayPath(env = process.env, ...parts) {
30
+ const home = viewableHome(env);
31
+ return home === viewableHome({})
32
+ ? ["~", ".glytch", ...parts].join("/")
33
+ : join(home, ...parts);
34
+ }
35
+
28
36
  export const registryPath = (env = process.env) => join(viewableHome(env), "folders.json");
29
37
 
30
38
  // Restore and Remove run in different processes. Reuse admission's exclusive
@@ -55,6 +63,18 @@ export async function markFolderRestore(folder, env = process.env) {
55
63
  await writeFileAtomic(restorePath(folder, env), randomUUID());
56
64
  }
57
65
 
66
+ // A REMOVED FOLDER STAYS REMOVED (#5290). Every start makes and registers the
67
+ // default folder (viewableFolder.mjs), so without a record a person's Remove
68
+ // held only until the next restart: the daemon watched the folder again for a
69
+ // few seconds, until the board's forget came round once more. removeFolder
70
+ // leaves this marker, only an explicit add clears it, and
71
+ // automatic registration checks this marker under the registry lock.
72
+ const removedPath = (folder, env) => join(viewableHome(env), "registry", `${createHash("sha256").update(resolve(folder)).digest("hex")}.removed`);
73
+
74
+ export async function folderWasRemoved(folder, env = process.env) {
75
+ return existsSync(removedPath(folder, env));
76
+ }
77
+
58
78
  // TEMPORARY FOLDERS ARE NEVER REGISTERED (QA 2026-10-01, ticket e7). An agent
59
79
  // once started a runner from its scratchpad, and "proof-project
60
80
  // (/private/tmp/claude-501/...)" sat in Settings > Connection for days. A
@@ -154,12 +174,25 @@ export async function addFolder(folder, env = process.env) {
154
174
  const path = resolve(folder);
155
175
  if (isScratchFolder(path, env)) throw new Error(`${path} is a temporary folder, and those are never registered. Run viewable init in the project folder itself.`);
156
176
  const folders = await readRegistry(env);
177
+ // Adding is the person asking for the folder back (init, sync): the record
178
+ // of its removal ends here, even when it is already listed.
179
+ await rm(removedPath(path, env), { force: true }).catch(() => {});
157
180
  if (folders.includes(path)) return { folders, added: false };
158
181
  const next = [...folders, path];
159
182
  await writeRegistry(next, env);
160
183
  return { folders: next, added: true };
161
184
  }
162
185
 
186
+ /** Automatic registration must not undo a Remove during startup. Return null
187
+ * for a removed folder; otherwise return addFolder's result. Explicit adds
188
+ * still restore removed folders. The check and add share the removal lock. */
189
+ export async function addFolderUnlessRemoved(folder, env = process.env) {
190
+ return withRegistryLock(async () => {
191
+ if (await folderWasRemoved(folder, env)) return null;
192
+ return addFolder(folder, env);
193
+ }, env);
194
+ }
195
+
163
196
  /** Write the folder list back unchanged. The running daemon reads a rewrite
164
197
  * as a request for one beat from every folder it watches (multiwatch.mjs),
165
198
  * which is how `viewable init` in a folder already watched gets the fresh beat
@@ -177,6 +210,9 @@ export async function touchRegistry(env = process.env) {
177
210
  export async function removeFolder(folder, env = process.env) {
178
211
  const path = resolve(folder);
179
212
  const folders = await readRegistry(env);
213
+ // Recorded even when it was not listed: the person asked for it gone.
214
+ await mkdir(dirname(removedPath(path, env)), { recursive: true });
215
+ await writeFileAtomic(removedPath(path, env), `${new Date().toISOString()}\n`);
180
216
  if (!folders.includes(path)) return { folders, removed: false };
181
217
  const next = folders.filter((f) => f !== path);
182
218
  await writeRegistry(next, env);
package/lib/runner.mjs CHANGED
@@ -238,7 +238,7 @@ export async function watch(root, settings, { signal, log = () => {}, startPrevi
238
238
  // A failed answer is kept only as long as a 10 s beat would, never the
239
239
  // 5 minutes a joined success lives, so a retry really asks (#813 review).
240
240
  const heartbeats = settings.heartbeats ??= makeHeartbeatHub({ ttlMs: () => 0.9 * beatBase(), failureTtlMs: 0.9 * beatMs });
241
- settings.registrar ??= makeRegistrar({ ttlMs: REGISTER_REFRESH_MS, failureTtlMs: 0.9 * beatMs });
241
+ settings.registrar ??= makeRegistrar({ ttlMs: REGISTER_REFRESH_MS, failureTtlMs: 0.9 * beatMs, heartbeats });
242
242
  // The claim loop's no-call wait, and its timed wait: a waiting run pushed
243
243
  // to this folder ends both (#813).
244
244
  const nudge = makeLatch();
@@ -158,7 +158,12 @@ export function makeBeatLoop(w) {
158
158
  const runnerApi = settings.runnerApi ?? runnerApiModule;
159
159
  const seen = w.hintSeq;
160
160
  await refreshProjectPaths(root, settings);
161
- const beat = await heartbeats.beat(w.project.id, (projectIds) => runnerApi.heartbeat({ projectIds, presence: presenceBody(settings) }, { env: settings.env, fetchImpl: settings.fetchImpl }));
161
+ // The hub's goodbye (ruling #4979) sends through this same writer, with
162
+ // `goodbye` and a short `timeoutMs` (lib/goodbye.mjs).
163
+ const beat = await heartbeats.beat(w.project.id, (projectIds, { goodbye, timeoutMs } = {}) => runnerApi.heartbeat(
164
+ { projectIds, presence: presenceBody(settings, { goodbye }) },
165
+ { env: settings.env, fetchImpl: settings.fetchImpl, ...(timeoutMs ? { timeoutMs } : {}) },
166
+ ));
162
167
  if (!beat.ok) {
163
168
  clearRefusedProject(beat);
164
169
  log(`heartbeat failed: ${beat.error}`);
@@ -365,7 +370,7 @@ async function refreshRegistration(root, settings, runnerApi) {
365
370
  const refreshSettings = {
366
371
  ...settings,
367
372
  registrar: {
368
- register: (key, send) => settings.registrar.register(key, async () => {
373
+ register: (key, send, writer) => settings.registrar.register(key, async () => {
369
374
  // Row ops may have awaited a slow merge after the beat snapshot.
370
375
  // Bypass the heartbeat cache, only when register is actually due.
371
376
  // The remaining read/write gap is closed server-side by
@@ -389,7 +394,7 @@ async function refreshRegistration(root, settings, runnerApi) {
389
394
  return { ok: false, error: "Registration deferred: a folder removal is pending." };
390
395
  }
391
396
  return send();
392
- }),
397
+ }, writer),
393
398
  },
394
399
  };
395
400
  const reg = await registerAndFindProject(root, refreshSettings);
@@ -13,7 +13,7 @@ import { AGENTS, agentFor, isCodingCli } from "./agents.mjs";
13
13
  import { resolveAgentBinary } from "./detect.mjs";
14
14
  import { imageAttachments } from "./imageAttachments.mjs";
15
15
  import { checkRequest, isChatTurn, isSignIn, titleFor } from "./spawn.mjs";
16
- import { codexLogin } from "./signIn.mjs";
16
+ import { agentLogin } from "./signIn.mjs";
17
17
  import { fromIdOf } from "./boardside.mjs";
18
18
  import { chatBoardOf, makeBoardCwd } from "./viewableFolder.mjs";
19
19
  import { defaultBranchOf, git, makeChatWorktree, resolveChatCwd, worktreeBranch, worktreePath, worktreeSummary } from "./worktree.mjs";
@@ -124,13 +124,14 @@ export async function admitRequest({ project, root, id, request, isChat, runnerA
124
124
  return { patch: { status: "error", result: `ERROR\n\nRefused: ${problems.join("\n")}\n`, finished_at: new Date().toISOString() } };
125
125
  }
126
126
 
127
- // SIGN IN TO CODEX (#482, lib/signIn.mjs): `codex login` opens the sign-in
128
- // page in this computer's browser. Then the agents are probed again, so the
129
- // app's sign-in box goes as soon as Codex says it is signed in rather than
130
- // on the probe's own five-minute clock.
127
+ // SIGN IN TO AN AGENT (#482, #5216, lib/signIn.mjs): `codex login` or
128
+ // `claude auth login` opens the sign-in page in this computer's browser.
129
+ // Then the agents are probed again, so the app's sign-in box goes as soon
130
+ // as the agent says it is signed in rather than on the probe's own
131
+ // five-minute clock.
131
132
  if (isSignIn(request)) {
132
133
  log(`[${id}] signing in to ${request.agent}`);
133
- const signedIn = await (settings.codexLogin ?? codexLogin)({ env: settings.baseEnv ?? process.env });
134
+ const signedIn = await (settings.agentLogin ?? agentLogin)(request.agent, { env: settings.baseEnv ?? process.env });
134
135
  await settings.refreshAgents?.();
135
136
  return { patch: { status: signedIn.ok ? "done" : "error", result: `${signedIn.ok ? "OK" : "ERROR"}\n\n${signedIn.detail}\n`, finished_at: new Date().toISOString() } };
136
137
  }
@@ -40,6 +40,8 @@
40
40
  // full runs-at-once count, a local lock) keeps the base interval, because none of
41
41
  // those get better by calling less often and none of them load the server.
42
42
 
43
+ import { GOODBYE_EXIT_MS } from "./goodbye.mjs";
44
+
43
45
  /** The wait after `failures` server errors in a row: base * 2^(n-1), capped,
44
46
  * then jittered down by up to 20% so many runners do not retry in step. Never
45
47
  * shorter than the base interval. */
@@ -148,18 +150,40 @@ function shareAnswer(send, { at, ttlMs, failureTtlMs }) {
148
150
  }
149
151
  const fresh = (entry, at) => entry.pending || at < entry.expiresAt;
150
152
 
153
+ /** How long before the exit a late goodbye is no longer started (#5308). */
154
+ const EXIT_MARGIN_MS = 500;
155
+
156
+ /** What a beat or register answers once the computer said goodbye. */
157
+ const SAID_GOODBYE = Object.freeze({ ok: false, transient: true, error: "This computer said goodbye." });
158
+
151
159
  /** Coalesce `register` across the folders of one process (ticket e8 item 3).
152
160
  * Every folder's beat registers the whole folder list, so the second and third
153
161
  * folder beating inside the same window would send exactly the same call
154
162
  * again. Within `ttlMs` of the last register for the same list, or while it is
155
163
  * still in flight, callers share its answer; a failure for `failureTtlMs`. */
156
- export function makeRegistrar({ ttlMs, failureTtlMs = ttlMs, now = Date.now }) {
164
+ export function makeRegistrar({ ttlMs, failureTtlMs = ttlMs, now = Date.now, heartbeats = null }) {
157
165
  let last = null;
158
166
  return {
159
- register(key, send) {
167
+ /** A register writes presence too, without the goodbye. With the
168
+ * process's `heartbeats` hub, each one is held in the hub's in-flight
169
+ * set, so the goodbye waits for it, and none starts after the goodbye
170
+ * (ruling #4979). `writer(projectIds, {goodbye, timeoutMs})` is how to
171
+ * write a presence for the folders it registers: a stop during the first
172
+ * register, before any beat, still says goodbye through it (#5308). */
173
+ register(key, send, writer = null) {
174
+ if (heartbeats?.saidGoodbye) return Promise.resolve(SAID_GOODBYE);
160
175
  const at = now();
161
176
  if (last && last.key === key && fresh(last, at)) return last.promise;
162
- last = Object.assign(shareAnswer(send, { at, ttlMs, failureTtlMs }), { key });
177
+ const learning = writer && heartbeats?.learn
178
+ ? async () => {
179
+ const answer = await send();
180
+ if (answer?.ok === true) heartbeats.learn((answer.projects ?? []).map((project) => project?.id).filter(Boolean), writer);
181
+ return answer;
182
+ }
183
+ : send;
184
+ last = Object.assign(shareAnswer(learning, { at, ttlMs, failureTtlMs }), { key });
185
+ // Held from now, not from when shareAnswer calls `send` a microtask later.
186
+ heartbeats?.hold(last.promise);
163
187
  return last.promise;
164
188
  },
165
189
  // A login to another account makes every cached project id obsolete.
@@ -206,7 +230,20 @@ export function makeRegistrar({ ttlMs, failureTtlMs = ttlMs, now = Date.now }) {
206
230
  * call and not the cached failure. A newer `invalidate(at)` makes existing answers
207
231
  * stale, including one started in the same millisecond, so the next beat really
208
232
  * asks: a join, a dropped socket or an op event. Every folder hearing the same event passes the same `at`, so they
209
- * still share the one call that follows. */
233
+ * still share the one call that follows.
234
+ *
235
+ * GOODBYE (ruling #4979, lib/goodbye.mjs). `farewell(projectIds, extra)` is
236
+ * the last beat: it closes the hub, so no beat or register starts after it,
237
+ * waits for every beat and register already on its way (`hold`, at most
238
+ * `extra.timeoutMs`), so none lands after it and replaces the presence, then
239
+ * sends once for every folder through the last `send` a folder gave, with
240
+ * `extra` (`{goodbye, timeoutMs}`) as its second argument. A write that is
241
+ * still on its way after that wait cannot be cancelled, so each time one
242
+ * settles the goodbye is sent again and lands last, until the process exit
243
+ * (`exitMs`, GOODBYE_EXIT_MS) less a margin (#5308). `ids()` lists the
244
+ * folders that have beaten and not left;
245
+ * `keepIds()` starts keeping every folder that beats from then on, leavers
246
+ * too, which the farewell adds to the ones it is given. */
210
247
  export function makeHeartbeatHub({ ttlMs, memberTtlMs, failureTtlMs, now = Date.now }) {
211
248
  const ttl = () => (typeof ttlMs === "function" ? ttlMs() : ttlMs);
212
249
  const failureTtl = () => Math.min(typeof failureTtlMs === "function" ? failureTtlMs() : failureTtlMs ?? Infinity, ttl());
@@ -218,8 +255,23 @@ export function makeHeartbeatHub({ ttlMs, memberTtlMs, failureTtlMs, now = Date.
218
255
  let generation = 0;
219
256
  let batching = true;
220
257
  const covered = (answer, ids) => (answer && typeof answer === "object" ? { ...answer, coveredProjectIds: ids } : answer);
258
+ const beaten = new Set(); // every folder that beat and has not left, for the goodbye
259
+ let kept = null; // once a stop is asked: every folder that beat since, even one that then left (#5308)
260
+ const inFlight = new Set();
261
+ let lastSend = null;
262
+ // Folders a register named and the way to write their presence, for a
263
+ // goodbye asked before any of them beat (#5308).
264
+ const registered = new Set();
265
+ let registerSend = null;
266
+ let farewell = null;
267
+ const track = (sending) => {
268
+ const settled = Promise.resolve(sending).catch(() => {}).finally(() => inFlight.delete(settled));
269
+ inFlight.add(settled);
270
+ return sending;
271
+ };
221
272
  const single = async (projectId, send) => {
222
- const answer = await send([projectId]);
273
+ if (farewell) return covered(SAID_GOODBYE, [projectId]);
274
+ const answer = await track(send([projectId]));
223
275
  if (batching) {
224
276
  if (answer?.ok === false && answer.transient !== true) alone.add(projectId);
225
277
  else if (answer?.ok === true) alone.delete(projectId);
@@ -231,6 +283,10 @@ export function makeHeartbeatHub({ ttlMs, memberTtlMs, failureTtlMs, now = Date.
231
283
  return batching;
232
284
  },
233
285
  async beat(projectId, send) {
286
+ if (farewell) return covered(SAID_GOODBYE, [projectId]);
287
+ beaten.add(projectId);
288
+ kept?.add(projectId);
289
+ lastSend = send;
234
290
  if (!batching || alone.has(projectId)) return single(projectId, send);
235
291
  const at = now();
236
292
  members.set(projectId, at);
@@ -241,6 +297,9 @@ export function makeHeartbeatHub({ ttlMs, memberTtlMs, failureTtlMs, now = Date.
241
297
  const ids = [...members.keys()].sort();
242
298
  const ttlNow = ttl();
243
299
  entry = Object.assign(shareAnswer(() => send(ids), { at, ttlMs: ttlNow, failureTtlMs: failureTtl() }), { ids, generation });
300
+ // In flight from now: shareAnswer calls `send` a microtask later, and
301
+ // a goodbye asked in between must still wait for this beat.
302
+ track(entry.promise);
244
303
  last = entry;
245
304
  }
246
305
  const answer = await entry.promise;
@@ -258,10 +317,80 @@ export function makeHeartbeatHub({ ttlMs, memberTtlMs, failureTtlMs, now = Date.
258
317
  return covered(answer, entry.ids);
259
318
  },
260
319
  leave(projectId) {
320
+ beaten.delete(projectId);
321
+ registered.delete(projectId);
261
322
  members.delete(projectId);
262
323
  alone.delete(projectId);
263
324
  if (last?.ids.includes(projectId)) last = null;
264
325
  },
326
+ ids() {
327
+ return [...beaten].sort();
328
+ },
329
+ /** A stop was asked: from now on, remember every folder that beats, and
330
+ * keep the ones that leave, so the goodbye covers a folder whose first
331
+ * beat comes only while the process shuts down and whose watcher ends
332
+ * before the goodbye is sent (#5308). Folders beaten so far are kept. */
333
+ keepIds() {
334
+ kept ??= new Set(beaten);
335
+ },
336
+ get saidGoodbye() {
337
+ return farewell !== null;
338
+ },
339
+ /** Hold a presence write that is not a beat (a register) in flight. */
340
+ hold(sending) {
341
+ return track(sending);
342
+ },
343
+ /** A register that answered names its folders, so a goodbye still has
344
+ * them when that register was the only thing on its way. */
345
+ learn(projectIds, send) {
346
+ for (const id of projectIds) registered.add(id);
347
+ registerSend = send;
348
+ },
349
+ farewell(projectIds, extra, { waitMs = extra?.timeoutMs ?? 3_000, exitMs = GOODBYE_EXIT_MS } = {}) {
350
+ farewell ??= (async () => {
351
+ const started = now();
352
+ const deadline = started + exitMs - EXIT_MARGIN_MS;
353
+ // Read at each goodbye: a registration that lands late names folders
354
+ // too (#5308).
355
+ const idsNow = () => [...new Set([...projectIds, ...(kept ?? []), ...registered])].sort();
356
+ const ready = () => (lastSend ?? registerSend) && idsNow().length > 0;
357
+ const waitFor = async (pending) => {
358
+ const timer = new AbortController();
359
+ await Promise.race([...pending, sleep(deadline - now(), timer.signal)]);
360
+ timer.abort();
361
+ };
362
+ if (inFlight.size > 0) await Promise.race([Promise.all([...inFlight]), sleep(waitMs)]);
363
+ // No folder is known yet: a first registration still on its way will
364
+ // name them, so wait for it up to the exit deadline before giving up.
365
+ while (!ready() && inFlight.size > 0 && deadline - now() > 0) await waitFor([...inFlight]);
366
+ if (!ready()) return { ok: false, error: "No folder had beaten yet." };
367
+ // A write that outlasted the wait cannot be called back, and it may
368
+ // land after the goodbye and replace it. Fence it: each time one
369
+ // settles, say goodbye again, until the exit deadline (#5308).
370
+ const stragglers = [...inFlight];
371
+ const say = async () => {
372
+ try { return await (lastSend ?? registerSend)(idsNow(), extra); }
373
+ catch (error) { return { ok: false, error: error instanceof Error ? error.message : String(error) }; }
374
+ };
375
+ let result = await say();
376
+ const answered = new Set();
377
+ for (;;) {
378
+ const landed = stragglers.filter((late) => !inFlight.has(late) && !answered.has(late));
379
+ if (landed.length > 0) {
380
+ for (const late of landed) answered.add(late);
381
+ // The corrective send is the last word, ok or not: the board may
382
+ // read the late write's presence, so an earlier ok is not true.
383
+ result = await say();
384
+ continue;
385
+ }
386
+ const open = stragglers.filter((late) => inFlight.has(late));
387
+ if (open.length === 0 || deadline - now() <= 0) break;
388
+ await waitFor(open);
389
+ }
390
+ return result;
391
+ })();
392
+ return farewell;
393
+ },
265
394
  invalidate(at = now()) {
266
395
  if (at > notBefore) {
267
396
  notBefore = at;
@@ -9,6 +9,7 @@ import { basename } from "node:path";
9
9
  import * as runnerApiModule from "./runnerApi.mjs";
10
10
  import { addFolder, foldersWithoutGit, isScratchFolder, markFolderRestore, readRegistry, readRegistryChecked, withRegistryLock } from "./registry.mjs";
11
11
  import { platformMark } from "./platform.mjs";
12
+ import { SIGN_IN_AGENTS } from "./signIn.mjs";
12
13
 
13
14
  /** `register` every folder this machine knows about, plus `root` itself as
14
15
  * a fallback for a single-folder invocation (PM_BOARD_ROOT) that was never
@@ -31,8 +32,16 @@ import { platformMark } from "./platform.mjs";
31
32
  * anyone who queries it at the wrong moment.
32
33
  *
33
34
  * Two writers of one body is how that happened, so there is one now.
35
+ *
36
+ * `signInAgents` names the agents whose sign-in the board can start here
37
+ * (lib/signIn.mjs); a computer on an older version leaves it out, and the
38
+ * board keeps its paste fallback for those (#5216, #5291).
39
+ *
40
+ * `goodbye` is the last beat of a computer that is being turned off,
41
+ * restarted or signed out of (ruling #4979, lib/goodbye.mjs). The next beat
42
+ * leaves it out, and since a beat replaces the presence, that clears it.
34
43
  */
35
- export const presenceBody = (settings) => {
44
+ export const presenceBody = (settings, { goodbye } = {}) => {
36
45
  const { platform: _platform, ...rest } = settings.markExtra?.() ?? {};
37
46
  // A scratch folder is never registered, so it is never reported either:
38
47
  // the app would otherwise show an old one still on disk again (#3644).
@@ -41,7 +50,7 @@ export const presenceBody = (settings) => {
41
50
  try { return statSync(path).isDirectory(); }
42
51
  catch (error) { return error.code !== "ENOENT" && error.code !== "ENOTDIR"; }
43
52
  });
44
- return { ...rest, ...(availableFolders ? { availableFolders } : {}), planApproval: true, computerAppsLook: true, folderReads: true, uninstallRequests: true, ...(settings.noGit?.length ? { noGit: settings.noGit } : {}) };
53
+ return { ...rest, ...(availableFolders ? { availableFolders } : {}), planApproval: true, computerAppsLook: true, folderReads: true, uninstallRequests: true, signInAgents: SIGN_IN_AGENTS, ...(settings.noGit?.length ? { noGit: settings.noGit } : {}), ...(goodbye ? { goodbye } : {}) };
45
54
  };
46
55
 
47
56
  /** Re-read the machine's folder list into `settings.projectPaths` before a
@@ -110,7 +119,12 @@ async function registerProject(root, settings, { readd = false, onlyRoot = false
110
119
  // ONE REGISTER PER PROCESS PER BEAT (ticket e8). multiwatch hands every
111
120
  // folder the same `registrar`, so the folders that beat inside one window
112
121
  // share one call for the same folder list instead of each sending it.
113
- const out = settings.registrar ? await settings.registrar.register(JSON.stringify(list), send) : await send();
122
+ // `writer` lets a goodbye reach these folders when no beat has yet (#5309).
123
+ const writer = (projectIds, { goodbye, timeoutMs } = {}) => runnerApi.heartbeat(
124
+ { projectIds, presence: presenceBody(settings, { goodbye }) },
125
+ { env, fetchImpl: settings.fetchImpl, ...(timeoutMs ? { timeoutMs } : {}) },
126
+ );
127
+ const out = settings.registrar ? await settings.registrar.register(JSON.stringify(list), send, writer) : await send();
114
128
  if (!out.ok) return { ok: false, error: out.error, ...(readd ? { readdRequired: Boolean(readdForgottenAt) } : {}), ...(out.transient ? { transient: true } : {}), ...(out.unauthorized ? { unauthorized: true } : {}), ...(Number.isFinite(out.retryAfterMs) ? { retryAfterMs: out.retryAfterMs } : {}) };
115
129
  const mine = (out.projects ?? []).find((p) => p.path === root);
116
130
  return { ok: true, projects: out.projects ?? [], myProjectId: mine?.id, runnerId };
@@ -47,9 +47,10 @@ import { spawn } from "node:child_process";
47
47
  import { createHash } from "node:crypto";
48
48
  import { writeFileSync } from "node:fs";
49
49
  import { tmpdir } from "node:os";
50
- import { dirname, join, sep } from "node:path";
50
+ import { dirname, join } from "node:path";
51
51
  import { fileURLToPath } from "node:url";
52
52
 
53
+ import { globalPackageDir, npmCommand } from "./npm-command.mjs";
53
54
  import { appUrlFrom, readAuthFile } from "./auth.mjs";
54
55
 
55
56
  const CLI_PATH = join(dirname(fileURLToPath(import.meta.url)), "..", "glytch.mjs");
@@ -107,12 +108,6 @@ export async function credentialRemoved({ env = process.env, fetchImpl = fetch,
107
108
  return { removed: true, tokens };
108
109
  }
109
110
 
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
111
  /** What the uninstall needs from this daemon's environment. A launcher
117
112
  * outside this process (a systemd unit, WMI) starts it with the user's
118
113
  * default environment instead, so the script carries these itself. Keys and
@@ -125,13 +120,14 @@ export function carriedEnv(env = process.env) {
125
120
 
126
121
  /** The detached command: `viewable uninstall --yes`, then, only when it
127
122
  * 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;
123
+ export function selfUninstallCommand({ execPath = process.execPath, cliPath = CLI_PATH, env = process.env, ...options } = {}) {
124
+ const target = { ...options, nodePath: execPath, cliPath, env };
125
+ const npm = globalPackageDir(cliPath, target) ? npmCommand(["uninstall", "-g", "viewable-one"], target) : null;
130
126
  const script = [
131
127
  'const { spawnSync } = require("node:child_process");',
132
128
  `const env = { ...process.env, ...${JSON.stringify(carriedEnv(env))} };`,
133
129
  `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" });` : "",
130
+ npm ? `if (done.status === 0) spawnSync(${JSON.stringify(npm.file)}, ${JSON.stringify(npm.args)}, { stdio: "ignore", env: { ...env, ...${JSON.stringify(carriedEnv(npm.env))} }, shell: false });` : "",
135
131
  ].join("\n");
136
132
  return { command: execPath, args: ["-e", script], script };
137
133
  }
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/sync.mjs CHANGED
@@ -43,7 +43,7 @@ import {
43
43
  noDaemonInstall,
44
44
  } from "./logindaemon.mjs";
45
45
  import { BOARD_MCP_URL, mergeBoardServer } from "./mcpjson.mjs";
46
- import { addFolder, readRegistry } from "./registry.mjs";
46
+ import { viewableDisplayPath, addFolder, readRegistry } from "./registry.mjs";
47
47
  import { readAgentSelection, parseAgentSelection } from "./agent-selection.mjs";
48
48
  import { syncProjectMcp } from "./project-mcp.mjs";
49
49
  import { packageVersion } from "./update.mjs";
@@ -142,7 +142,7 @@ export async function syncOpencode(root, { exec = execProbe, found, write = true
142
142
  export async function syncRegistry(root, { env = process.env, write = true } = {}) {
143
143
  const folders = await readRegistry(env);
144
144
  if (folders.includes(root)) return row("registry", "folder registered", true, "present", "your computer watches this folder");
145
- if (!write) return row("registry", "folder registered", false, "missing", "this folder is not in ~/.glytch/folders.json");
145
+ if (!write) return row("registry", "folder registered", false, "missing", `this folder is not in ${viewableDisplayPath(env, "folders.json")}`);
146
146
  try {
147
147
  await addFolder(root, env);
148
148
  } catch (error) {
@@ -152,11 +152,11 @@ export async function syncRegistry(root, { env = process.env, write = true } = {
152
152
  "folder registered",
153
153
  false,
154
154
  "could not write",
155
- `~/.glytch/folders.json could not be written: ${why}`,
155
+ `${viewableDisplayPath(env, "folders.json")} could not be written: ${why}`,
156
156
  COMPUTER_REPAIR,
157
157
  );
158
158
  }
159
- return row("registry", "folder registered", true, "added", "added to ~/.glytch/folders.json");
159
+ return row("registry", "folder registered", true, "added", `added to ${viewableDisplayPath(env, "folders.json")}`);
160
160
  }
161
161
 
162
162
  /** The entries of a PATH, in order, without the empties.
@@ -34,7 +34,7 @@ import { boardEntryIsOurs as codexBoardEntryIsOurs, opencodeBoardEntryIsOurs, pr
34
34
  import { detectAgents, execProbe } from "./detect.mjs";
35
35
  import { SERVER_KEY, lastStderrLine } from "./init-connect.mjs";
36
36
  import { writeFileAtomic } from "./atomic.mjs";
37
- import { readRegistry, removeFolder } from "./registry.mjs";
37
+ import { viewableDisplayPath, readRegistry, removeFolder } from "./registry.mjs";
38
38
  import { row, warnRow } from "./cli-output.mjs";
39
39
 
40
40
  /** `code: message`, or just the message when there is no `.code` (a plain
@@ -527,17 +527,17 @@ async function registryRow(root, { env, dryRun, log, allOk = true }) {
527
527
  "left registered",
528
528
  "an earlier step in this project failed - left registered so `viewable uninstall` can retry",
529
529
  )
530
- : row("registry", "folder registered", true, "not present", "this folder is not in ~/.glytch/folders.json");
530
+ : row("registry", "folder registered", true, "not present", `this folder is not in ${viewableDisplayPath(env, "folders.json")}`);
531
531
  } else if (dryRun) {
532
532
  const folders = await readRegistry(env);
533
533
  r = folders.includes(target)
534
- ? row("registry", "folder registered", true, "would unregister", "would remove this folder from ~/.glytch/folders.json")
535
- : row("registry", "folder registered", true, "not present", "this folder is not in ~/.glytch/folders.json");
534
+ ? row("registry", "folder registered", true, "would unregister", `would remove this folder from ${viewableDisplayPath(env, "folders.json")}`)
535
+ : row("registry", "folder registered", true, "not present", `this folder is not in ${viewableDisplayPath(env, "folders.json")}`);
536
536
  } else {
537
537
  const result = await removeFolder(root, env);
538
538
  r = result.removed
539
- ? row("registry", "folder registered", true, "unregistered", "removed from ~/.glytch/folders.json")
540
- : row("registry", "folder registered", true, "not present", "this folder was not in ~/.glytch/folders.json");
539
+ ? row("registry", "folder registered", true, "unregistered", `removed from ${viewableDisplayPath(env, "folders.json")}`)
540
+ : row("registry", "folder registered", true, "not present", `this folder was not in ${viewableDisplayPath(env, "folders.json")}`);
541
541
  }
542
542
  } catch (error) {
543
543
  // U4: this should be rare (the registry file is JSON we control), but a