viewable-one 0.12.5 → 0.12.7

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.
@@ -22,6 +22,9 @@
22
22
  // breaks read as spaces, and any punctuation or symbol shows (a colon, an
23
23
  // ampersand, a bracket, an arrow, a percent sign), except = { } and a backslash, which
24
24
  // carry form, JSON and escaped data. A year (1900 to 2099) is not a code.
25
+ // A title or a name (NAME_FIELDS, also the title found inside a nested item)
26
+ // shows up to 6 digits in all ("Invoice 4521"; a phone number does not) unless it holds the word
27
+ // "code", a credential word, or nothing but a number (#5436).
25
28
  // Every other test is the same: a credential word, a labelled or token-shaped
26
29
  // value, an opaque run or a long run of digits still hides.
27
30
  // Booleans and null show as themselves; a number shows when it has at most
@@ -87,6 +90,13 @@ const DIGIT_RUN = /\d{4,}/;
87
90
  const YEAR = /(?<!\d)(?:19|20)\d{2}(?!\d)/g;
88
91
  // The fields that hold what a person wrote to be read (#4363).
89
92
  const PROSE_FIELDS = new Set(["title", "description", "subject", "body", "content", "markdown", "reason"]);
93
+ // A title or a name is a label a person types to read back ("Invoice 4521",
94
+ // "Room 1204", #5436): a number of up to 6 digits in all shows there when the text has
95
+ // words and no credential word. A longer run, a number alone, "code" or any
96
+ // credential word still hides. Other fields keep the 4-digit rule.
97
+ const NAME_FIELDS = new Set(["title", "name", "subject", "summary", "heading"]);
98
+ const digitCount = (text) => (text.match(/\d/g) ?? []).length;
99
+ const CODE_WORD = /(?<![A-Za-z])codes?(?![A-Za-z])/i;
90
100
 
91
101
  const MAX_INPUTS = 12;
92
102
  const MAX_VALUE = 80;
@@ -103,29 +113,39 @@ const count = (n, one, many) => `${n} ${n === 1 ? one : many}`;
103
113
  // code, and its markdown marks and line breaks read as plain words.
104
114
  const proseWords = (text) => text.replace(/[*`]+/g, "").replace(/\s+/g, " ").trim();
105
115
  // Length is checked first, so the patterns only ever scan 80 characters.
106
- const plainText = (text, prose = false) => text.length <= MAX_VALUE && (prose ? PROSE_CHARS : PLAIN_CHARS).test(text)
107
- && !DIGIT_RUN.test(prose ? text.replace(YEAR, "") : text) && !valueMentionsSecret(text)
116
+ // "code" as a word, camelCase split first ("loginCode 4521").
117
+ const codeWord = (text) => CODE_WORD.test(text.replace(/([a-z])([A-Z])/g, "$1 $2"));
118
+ const digitsHide = (text, prose, label) => {
119
+ const rest = prose ? text.replace(YEAR, "") : text;
120
+ if (!label) return DIGIT_RUN.test(rest);
121
+ // "each": every title of a list was checked alone (madeRows), so the digits of one never add to another's.
122
+ if (label === "each") return false;
123
+ // Every digit counts, a year too: "2026 123456" is ten digits.
124
+ return digitCount(text) > 6 || (DIGIT_RUN.test(rest) && (codeWord(rest) || !/\p{L}/u.test(rest)));
125
+ };
126
+ const plainText = (text, prose = false, label = false) => text.length <= MAX_VALUE && (prose ? PROSE_CHARS : PLAIN_CHARS).test(text)
127
+ && !digitsHide(text, prose, label) && !valueMentionsSecret(text)
108
128
  && !secretLike(text) && !opaque(text);
109
129
 
110
130
  // The text to show, or null when it must be hidden. A long text shows its
111
131
  // start, cut at a word, and only that start is tested, so the patterns scan
112
132
  // at most 81 characters whatever the size. No word break in the first 80
113
133
  // characters (one long run) stays hidden.
114
- function plainStart(text, prose = false) {
115
- if (text.length <= MAX_VALUE) return plainText(text, prose) ? text.trim() : null;
134
+ function plainStart(text, prose = false, label = false) {
135
+ if (text.length <= MAX_VALUE) return plainText(text, prose, label) ? text.trim() : null;
116
136
  const head = text.slice(0, MAX_VALUE + 1);
117
137
  const cut = head.lastIndexOf(" ");
118
138
  const start = cut > 0 ? head.slice(0, cut).trim() : "";
119
- return start && plainText(start, prose) ? `${start}…` : null;
139
+ return start && plainText(start, prose, label) ? `${start}…` : null;
120
140
  }
121
141
 
122
- function valueText(value, prose = false) {
142
+ function valueText(value, prose = false, label = false) {
123
143
  if (value === null || typeof value === "boolean") return String(value);
124
144
  // At most 3 digits before the point: 49.99 shows, a 4-digit PIN does not.
125
145
  if (typeof value === "number") return Number.isFinite(value) && Math.abs(value) < 1000 ? String(value) : HIDDEN;
126
146
  if (typeof value === "string") {
127
147
  if (value.trim() === "") return "(empty)";
128
- const start = prose ? plainStart(proseWords(value), true) : plainStart(value);
148
+ const start = prose ? plainStart(proseWords(value), true, label) : plainStart(value, false, label);
129
149
  return start ?? `${HIDDEN}, ${count(value.length, "character", "characters")}`;
130
150
  }
131
151
  // Nested values are summarised by size, never opened: a secret one level
@@ -189,9 +209,95 @@ function shownValue(name, value, names) {
189
209
  const named = Object.hasOwn(names ?? {}, name) && typeof names[name] === "string" ? plainStart(proseWords(names[name]), true) : null;
190
210
  if (named) return named;
191
211
  if (typeof value === "string" && UUID.test(value)) return value;
192
- return valueText(value, PROSE_FIELDS.has(name));
212
+ return valueText(value, PROSE_FIELDS.has(name), NAME_FIELDS.has(nameLetters(name)));
193
213
  }
194
214
 
215
+ // WHAT A NESTED ARGUMENT WILL MAKE (#5401). A page batch ("pages": [{
216
+ // properties: { title }, content }]) read "pages: 1 item": it named no page
217
+ // and never said what the page holds. The words a person reads are found by
218
+ // the fields' names, never by the app (#4419): the title and the start of the
219
+ // text of the items inside, at most three levels down, through the same
220
+ // filter as any text. A field named like a credential is never opened.
221
+ const TITLE_KEYS = new Set(["title", "name", "subject", "summary", "heading"]);
222
+ const TEXT_KEYS = new Set(["content", "markdown", "body", "text", "description"]);
223
+ // Deep enough for a title kept as rich text (Notion's API: properties.title
224
+ // [0].text.content); the walk opens at most WALK_NODES values in all.
225
+ const NESTED_DEPTH = 4;
226
+ const WALK_NODES = 200;
227
+ function firstText(value, keys, depth = 0, budget = { left: WALK_NODES }) {
228
+ if (depth > NESTED_DEPTH || value === null || typeof value !== "object" || --budget.left < 0) return undefined;
229
+ const entries = Array.isArray(value) ? value.slice(0, MAX_INPUTS).map((inner) => ["", inner]) : Object.entries(value).slice(0, MAX_INPUTS);
230
+ // The text of an item is never its title's own rich text.
231
+ const open = entries.filter(([key]) => !mentionsSecret(key) && !(keys === TEXT_KEYS && TITLE_KEYS.has(nameLetters(key))));
232
+ for (const [key, inner] of open) {
233
+ if (!keys.has(nameLetters(key))) continue;
234
+ if (typeof inner === "string" && inner.trim()) return inner;
235
+ const rich = richText(inner, depth + 1, budget);
236
+ if (rich !== undefined) return rich;
237
+ }
238
+ for (const [, inner] of open) {
239
+ const found = firstText(inner, keys, depth + 1, budget);
240
+ if (found !== undefined) return found;
241
+ }
242
+ return undefined;
243
+ }
244
+
245
+ /** Every text fragment of a rich text, joined before it is cut: a title kept
246
+ * as ["Launch ", "notes"] reads "Launch notes", never "Launch". Stops once
247
+ * there is more than the card shows. */
248
+ function richText(value, depth, budget, parts = []) {
249
+ if (depth > NESTED_DEPTH || value === null || typeof value !== "object" || --budget.left < 0) return undefined;
250
+ const entries = Array.isArray(value) ? value.slice(0, MAX_INPUTS).map((inner) => ["", inner]) : Object.entries(value).slice(0, MAX_INPUTS);
251
+ for (const [key, inner] of entries) {
252
+ if (parts.join("").length > MAX_VALUE) break;
253
+ if (mentionsSecret(key)) continue;
254
+ if (typeof inner === "string") { if (TEXT_KEYS.has(nameLetters(key))) parts.push(inner); }
255
+ else richText(inner, depth + 1, budget, parts);
256
+ }
257
+ const text = parts.join("");
258
+ return text.trim() ? text : undefined;
259
+ }
260
+
261
+ /** Title and Adds rows for an argument holding the items a write makes, or
262
+ * [] when nothing in it reads as one. Several items name their titles. */
263
+ function madeRows(value) {
264
+ const items = (Array.isArray(value) ? value : [value]).filter(record);
265
+ if (!items.length) return [];
266
+ const titles = items.map((item) => firstText(item, TITLE_KEYS)).filter((title) => title !== undefined);
267
+ const text = items.length === 1 ? firstText(items[0], TEXT_KEYS) : undefined;
268
+ const rows = [];
269
+ // Items with no title of their own still count: two pages, one titled, never read as one.
270
+ const rest = items.length - titles.length;
271
+ const more = titles.length && rest > 0 ? ` and ${rest} more` : "";
272
+ if (titles.length === 1) rows.push({ line: `Title: ${valueText(titles[0], true, true)}${more}` });
273
+ else if (titles.length > 1) {
274
+ // Each title is judged alone for its digits: "123456" next to "Meeting"
275
+ // stays hidden, "Part 123" next to "Part 456" stays readable. A hidden one
276
+ // is counted, never written as a word a real title could also be.
277
+ const visible = titles.map(proseWords).filter((title) => plainStart(title, true, true) !== null);
278
+ const hiddenCount = titles.length - visible.length;
279
+ const joined = visible.join(", ");
280
+ const shown = visible.length ? valueText(joined, true, "each") : HIDDEN;
281
+ // A list cut short or hidden says how many there are in all.
282
+ const cut = shown !== joined;
283
+ const hiddenNote = visible.length && hiddenCount ? `, ${hiddenCount} hidden` : "";
284
+ rows.push({ line: `Titles: ${shown}${hiddenNote}${cut ? ` (${items.length} in all)` : more}` });
285
+ }
286
+ if (text !== undefined) rows.push({ line: `Adds: ${valueText(text, true)}` });
287
+ return rows;
288
+ }
289
+
290
+ // "page_ids" reads "Pages", "parentPages" reads "Parent pages". The same
291
+ // words as plainLabel in src/integrations/writeResults.ts, which src cannot
292
+ // import from here: keep the two together.
293
+ const spoken = (name) => {
294
+ const text = name.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[_.-]+/g, " ").trim().toLowerCase().replace(/ ids$/, "s");
295
+ return text.charAt(0).toUpperCase() + text.slice(1);
296
+ };
297
+ // A flag the model sets to say the person agreed ("user_confirmed"). A bare
298
+ // "confirm" is left alone: on Stripe it is the app's own "charge now".
299
+ const CONFIRM_FLAG = /^userconfirm(?:ed|ation)?$/;
300
+
195
301
  /** Approval-card rows, using the same secret filter as the computer asker.
196
302
  * `tool` is the app's tool name; a Stripe amount reads "Refund" only on a
197
303
  * refund tool (or when the tool is not known). `names` maps an argument to the
@@ -200,16 +306,31 @@ function shownValue(name, value, names) {
200
306
  * instead of "hidden, 36 characters". */
201
307
  export function appInputsText(provider, inputs = {}, tool = "refund", names = {}) {
202
308
  if (!record(inputs)) return toolInputsText({ _meta: { tool_params: inputs } });
203
- const labels = { team: "Team", title: "Title", description: "Description", priority: "Priority", page_id: "Page", page: "Page", parent: "Page", content: "Adds", markdown: "Adds", body: "Comment", owner: "Owner", repo: "Repository", issue_number: "Issue", pullNumber: "Pull request", customer: "Customer", payment_intent: "Payment", charge: "Payment", reason: "Reason", currency: "Currency", to: "To", subject: "Subject" };
309
+ const labels = { team: "Team", title: "Title", description: "Description", priority: "Priority", page_id: "Page", page: "Page", parent: "Page", content: "Adds", markdown: "Adds", body: "Comment", owner: "Owner", repo: "Repository", issue_number: "Issue", pullNumber: "Pull request", customer: "Customer", payment_intent: "Payment", charge: "Payment", reason: "Reason", currency: "Currency", to: "To", subject: "Subject", id: "Item" };
310
+ let named = Object.entries(inputs).some(([name, value]) => (labels[name] === "Title" || labels[name] === "Adds") && !placeholder(value));
204
311
  const money = (name, value) => provider === "stripe" && name === "amount" && Number.isSafeInteger(value) && value >= 0 && value <= 99999999;
205
312
  const rows = Object.entries(inputs).slice(0, MAX_INPUTS).flatMap(([name, value]) => {
206
313
  // An empty value tells the person nothing; a field with content always shows, as a count if nested (#4363).
207
314
  if (placeholder(value)) return [];
315
+ // "User confirmed: true" is a developer flag: Allow is the person's confirmation (#6453).
316
+ if (typeof value === "boolean" && CONFIRM_FLAG.test(nameLetters(name))) return [];
208
317
  if (money(name, value)) return [{ line: `${/refund/i.test(tool) ? "Refund" : "Amount"}: ${moneyText(value, inputs.currency)}` }];
209
318
  // The currency is already in the amount.
210
319
  if (provider === "stripe" && name === "currency" && money("amount", inputs.amount) && /^[a-z]{3}$/i.test(String(value))) return [];
320
+ // A list or object the caller found names for (the pages a delete acts on)
321
+ // reads as the item the call acts on: a capital label keeps it on the line
322
+ // under the question instead of under Details (#6453).
323
+ const label = Object.hasOwn(labels, name) ? labels[name]
324
+ : typeof value === "object" && Object.hasOwn(names ?? {}, name) && plainName(name) ? spoken(name) : undefined;
325
+ // Items under a name the card has no word for say what they make
326
+ // instead of how many there are (#5401): once per call, and never over a
327
+ // title or text the call already gives.
328
+ const made = !named && label === undefined && !mentionsSecret(name) && typeof value === "object" ? madeRows(value) : [];
329
+ if (made.length) { named = true; return made; }
211
330
  const display = mentionsSecret(name) || codeValue(name, value) ? HIDDEN : shownValue(name, value, names);
212
- return [{ line: `${(Object.hasOwn(labels, name) ? labels[name] : undefined) ?? (plainName(name) ? name : "hidden name")}: ${display}`, id: RAW_ID.test(display) }];
331
+ // A name with no label is sent as the app wrote it; the card keeps it
332
+ // under Details in plain words, off the line under the question (#5401).
333
+ return [{ line: `${label ?? (plainName(name) ? name : "hidden name")}: ${display}`, id: RAW_ID.test(display) }];
213
334
  });
214
335
  return "Details:\n" + [...rows.filter((row) => !row.id), ...rows.filter((row) => row.id)].map((row) => row.line).join("\n");
215
336
  }
@@ -38,8 +38,10 @@ export function conversationRules(spec, ask) {
38
38
  "says where the answer is.\n\n" +
39
39
  "When you change something a person can see, attach a screenshot of it to " +
40
40
  "an addComment (it takes `images`, up to 6 data URLs of PNG, JPEG, GIF or " +
41
- `WebP). When you are choosing between looks, ask with ${ask} and pass ` +
42
- "`images` so the person can see each one, and name them in the options.\n\n" +
41
+ `WebP). When you ask about something you saw (a screenshot, a page) or ` +
42
+ `are choosing between looks, ask with ${ask} and pass the pictures in ` +
43
+ "`images`, each as {image, caption} with one plain line saying what it " +
44
+ "shows, so the person can answer from Needs you without opening your work.\n\n" +
43
45
  "When you change a page of an app, write `.viewable-page.json` in the root " +
44
46
  "of the folder you work in, naming that page's address and what a person " +
45
47
  "calls it, like `{\"path\": \"/settings\", \"name\": \"settings page\"}`. " +
@@ -74,6 +76,15 @@ export function otherAppsRule() {
74
76
  // closing message, in these words: the app finds the sentence and offers
75
77
  // Open Manage agent under it.
76
78
  export const APPS_OFF_SENTENCE = "Turn on **Use my computer's apps** in Manage agent and I will try again.";
79
+ /** Closing words that ask for Use my computer's apps (#6552): the sentence
80
+ * above, bold, quoted or plain, as a model writes it back. The app's own
81
+ * reader is src/nodes/sessionWords.ts `offersComputerApps`. A run whose
82
+ * closing asks for the apps could not do its job; runnerCompletion.mjs says
83
+ * so on the row (`sidecar.unable`), and an automation counts it as failed. */
84
+ export function asksForComputerApps(text) {
85
+ return /Turn on [*'"\u2018\u201c]*Use my computer['\u2019]s apps[*'"\u2019\u201d]* in Manage agent/i.test(String(text ?? ""));
86
+ }
87
+
77
88
  export function computerAppsOffRule() {
78
89
  return (
79
90
  "You cannot reach the person's own apps from this run (their email, " +
package/lib/detect.mjs CHANGED
@@ -176,7 +176,8 @@ function ownPathDirs({ env = process.env } = {}) {
176
176
  * with `existsSync`, so a caller gets back a concrete path instead of a
177
177
  * boolean), the well-known install directories (`knownBinDirs`, also no
178
178
  * process spawned), and last a login shell's `command -v` (`loginShellWhich`
179
- * - slowest, memoized, asked only when the first two came up empty).
179
+ * - slowest, asked only when the first two came up empty; `detectAgents`
180
+ * remembers its answer, see `resolveMemo`).
180
181
  *
181
182
  * On POSIX a `bin` that already names a place (it contains a separator) is
182
183
  * `PM_<AGENT>_BIN` set to an explicit path, handed back unchanged and
@@ -476,6 +477,12 @@ export async function probeClaudeEffort(bin, { exec = execProbe, env = process.e
476
477
  return models;
477
478
  }
478
479
 
480
+ /** What `detectAgents` learned from `resolveAgentBinary`, per tool name, PATH and
481
+ * shell: a found path stays until it stops answering, a miss for this long. A
482
+ * tool installed after a miss shows up within one window. */
483
+ export const RESOLVE_MISS_MS = 30 * 60 * 1000;
484
+ const resolveMemo = new Map();
485
+
479
486
  /** Probe every engine. Returns the `agents` block stage 2 writes into the
480
487
  * mark file:
481
488
  *
@@ -493,11 +500,44 @@ export async function detectAgents({
493
500
  fileExists,
494
501
  timeoutMs = PROBE_TIMEOUT_MS,
495
502
  codexDiscover = exec === execProbe ? discoverCodex : null,
503
+ // The way a real run finds a tool (`resolveAgentBinary`: PATH, the usual
504
+ // install folders, then a login shell). Only the real probe uses it; a test's
505
+ // fake exec answers for the names it is given and nothing else.
506
+ resolve = exec === execProbe ? resolveAgentBinary : null,
507
+ memo,
508
+ now = Date.now,
496
509
  } = {}) {
510
+ const cache = memo ?? (resolve === resolveAgentBinary ? resolveMemo : new Map());
497
511
  const agents = {};
512
+ const probedBin = {};
498
513
  for (const spec of bins) {
499
514
  const bin = env[`PM_${spec.key.toUpperCase()}_BIN`]?.trim() || spec.bin;
500
- const result = await exec(bin, ["--version"], { timeoutMs, env });
515
+ let result = await exec(bin, ["--version"], { timeoutMs, env });
516
+ probedBin[spec.key] = bin;
517
+ // A watcher started by hand or by a service has a short PATH. "Not on this
518
+ // PATH" is not "not installed": a run would find the tool through
519
+ // `resolveAgentBinary`, so the mark must too, or the board reads Claude Code
520
+ // as missing and sends the run to another tool (#6646).
521
+ if (result?.ok !== true && resolve) {
522
+ // The lookup can spawn login shells, and this probe runs every five
523
+ // minutes before the first beat: remember a path, and a miss for a while.
524
+ const key = `${bin}\0${env.PATH ?? ""}\0${env.SHELL ?? ""}\0${env.HOME ?? ""}`;
525
+ const seen = cache.get(key);
526
+ try {
527
+ let path;
528
+ if (seen && (seen.path !== null || now() - seen.at < RESOLVE_MISS_MS)) path = seen.path;
529
+ else {
530
+ const resolved = await resolve(bin, { env, platform });
531
+ path = resolved?.found && resolved.path !== bin ? resolved.path : null;
532
+ cache.set(key, { path, at: now() });
533
+ }
534
+ if (path !== null) {
535
+ const retry = await exec(path, ["--version"], { timeoutMs, env });
536
+ if (retry?.ok === true) { result = retry; probedBin[spec.key] = path; }
537
+ else cache.delete(key);
538
+ }
539
+ } catch { /* an unresolvable tool stays not found */ }
540
+ }
501
541
  const found = result?.ok === true;
502
542
  const version = found ? versionFrom(result.stdout || result.stderr) : undefined;
503
543
  agents[spec.key] = { found, ...(version ? { version } : {}) };
@@ -506,14 +546,14 @@ export async function detectAgents({
506
546
  // elsewhere; Codex is queried through app-server below.
507
547
  if (agents.claude) {
508
548
  if (agents.claude.found) {
509
- const effortModels = await probeClaudeEffort(env.PM_CLAUDE_BIN?.trim() || bins.find((b) => b.key === "claude")?.bin || "claude", { exec, env, timeoutMs });
549
+ const effortModels = await probeClaudeEffort(probedBin.claude, { exec, env, timeoutMs });
510
550
  if (Object.keys(effortModels).length) agents.claude.effortModels = effortModels;
511
551
  }
512
552
  agents.claude.loggedIn = await claudeLoggedIn({ exec, env, platform, credentialsPath, fileExists });
513
553
  }
514
554
  if (agents.codex?.found && codexDiscover) {
515
555
  try {
516
- Object.assign(agents.codex, await codexDiscover({ bin: env.PM_CODEX_BIN?.trim() || "codex", env, timeoutMs }));
556
+ Object.assign(agents.codex, await codexDiscover({ bin: probedBin.codex, env, timeoutMs }));
517
557
  } catch { /* version detection remains valid when model discovery fails */ }
518
558
  }
519
559
  return agents;
package/lib/doctor.mjs CHANGED
@@ -46,7 +46,7 @@ import { projectMcpServerKey } from "./project-mcp.mjs";
46
46
  import { syncFolder } from "./sync.mjs";
47
47
  import { readAgentSelection } from "./agent-selection.mjs";
48
48
  import { compareVersions, latestFromNpm, packageVersion, verifyInstalledCli } from "./update.mjs";
49
- import { PERSONAL_TOKEN_REJECTED_HINT, REAUTH_REQUIRED_HINT, hostedStatus } from "./auth.mjs";
49
+ import { authDisplayPath, PERSONAL_TOKEN_REJECTED_HINT, REAUTH_REQUIRED_HINT, hostedStatus } from "./auth.mjs";
50
50
  import { presence as hostedPresence } from "./runnerApi.mjs";
51
51
 
52
52
  // `row` is imported from cli-output.mjs (brief 31 review, 2026-09-12 - it
@@ -377,7 +377,7 @@ export async function doctorRows(
377
377
  "board sign-in",
378
378
  false,
379
379
  "rejected",
380
- `the personal token in ~/.glytch/auth.json was rejected by the board${boardAuth.deadSince ? ` (since ${boardAuth.deadSince})` : ""}`,
380
+ `the personal token in ${authDisplayPath(env)} was rejected by the board${boardAuth.deadSince ? ` (since ${boardAuth.deadSince})` : ""}`,
381
381
  PERSONAL_TOKEN_REJECTED_HINT,
382
382
  )
383
383
  : row(
@@ -385,7 +385,7 @@ export async function doctorRows(
385
385
  "board sign-in",
386
386
  false,
387
387
  "expired",
388
- `the credential in ~/.glytch/auth.json was refused by the board${boardAuth.deadSince ? ` (since ${boardAuth.deadSince})` : ""} and cannot be renewed`,
388
+ `the credential in ${authDisplayPath(env)} was refused by the board${boardAuth.deadSince ? ` (since ${boardAuth.deadSince})` : ""} and cannot be renewed`,
389
389
  REAUTH_REQUIRED_HINT,
390
390
  )
391
391
  : boardAuth.signedIn
@@ -410,8 +410,8 @@ export async function doctorRows(
410
410
  (boardAuth.via === "VIEWABLE_BOARD_TOKEN"
411
411
  ? "VIEWABLE_BOARD_TOKEN is set"
412
412
  : boardAuth.via === "personal token"
413
- ? "a personal access token is stored in ~/.glytch/auth.json"
414
- : "~/.glytch/auth.json is there"),
413
+ ? `a personal access token is stored in ${authDisplayPath(env)}`
414
+ : `${authDisplayPath(env)} is there`),
415
415
  )
416
416
  : row(
417
417
  "boardAuth",
@@ -419,7 +419,7 @@ export async function doctorRows(
419
419
  false,
420
420
  "not signed in",
421
421
  "run `viewable login`, or set VIEWABLE_BOARD_TOKEN to a personal access token for a script",
422
- "Run `viewable login`. It opens a browser to sign in and approve, and the credential lands in ~/.glytch/auth.json. Re-running `viewable init` does not do this step.",
422
+ `Run \`viewable login\`. It opens a browser to sign in and approve, and the credential lands in ${authDisplayPath(env)}. Re-running \`viewable init\` does not do this step.`,
423
423
  ),
424
424
  );
425
425
 
@@ -447,7 +447,9 @@ export async function doctorRows(
447
447
  ? row("version", "version", true, "unknown", `${version} installed; npm did not answer (offline?)`)
448
448
  : compareVersions(newestPublished, version) > 0
449
449
  ? row("version", "version", true, "update available", `${version} installed, ${newestPublished} on npm: npm i -g viewable-one@latest --force`)
450
- : row("version", "version", true, "current", `${version} is the latest`),
450
+ : row("version", "version", true, "current", compareVersions(version, newestPublished) > 0
451
+ ? `${version} is newer than the published ${newestPublished}`
452
+ : `${version} is the latest`),
451
453
  );
452
454
 
453
455
  return rows;
@@ -0,0 +1,81 @@
1
+ // Ending what an agent left running in its own process group (#6557).
2
+ //
3
+ // A recovery-tracked agent leads a private group, so everything it started
4
+ // without `setsid` shares that group. Stop, the wall clock and the stall
5
+ // watchdog end the group, EXCEPT the preview server the session recorded in
6
+ // `.viewable-server.json` (ruling A, 2026-09-06). That server is not always in
7
+ // a group of its own: on macOS the instruction is `nohup <cmd> & disown`,
8
+ // which keeps the agent's group. So the server is spared by pid (and what it
9
+ // started), not by group. With no recorded server the whole group is signalled
10
+ // at once, which leaves no window for a fork to slip through.
11
+ import { processSnapshot, descendantPids } from "./procs.mjs";
12
+
13
+ const nap = (ms) => new Promise((done) => setTimeout(done, ms));
14
+
15
+ /** Is anything still alive in the group `pgid` leads? A member we may not
16
+ * signal (EPERM) is still a member. A group cannot be recycled while it has
17
+ * members, so a true answer here is about OUR group. */
18
+ function groupAlive(pgid) {
19
+ try { process.kill(-pgid, 0); return true; } catch (error) { return error.code === "EPERM"; }
20
+ }
21
+
22
+ async function spared(keep) {
23
+ try {
24
+ const pids = await keep?.();
25
+ return new Set([...(pids ?? [])].map(Number).filter((pid) => Number.isInteger(pid) && pid > 1));
26
+ } catch { return new Set(); }
27
+ }
28
+
29
+ /** The members of `pgid` that may be ended: all of them minus the spared
30
+ * servers and their descendants. null means the process list was unreadable. */
31
+ async function members(pgid, spare, snapshot) {
32
+ const table = await snapshot();
33
+ if (!table) return null;
34
+ const keep = new Set();
35
+ for (const pid of spare) {
36
+ if (!table.has(pid)) continue;
37
+ keep.add(pid);
38
+ for (const child of descendantPids(pid, table)) keep.add(child);
39
+ }
40
+ const found = [];
41
+ for (const [pid, row] of table) {
42
+ if (pid > 1 && row.pgid === pgid && !keep.has(pid) && !row.command?.includes("<defunct>")) found.push(pid);
43
+ }
44
+ return found;
45
+ }
46
+
47
+ /** Send `sig` to everything in the group that is not a spared server.
48
+ * `verified` signals only pids the process table shows in this group right
49
+ * now, never a bare group number (the late SIGKILL pass: a group that emptied
50
+ * during the grace must not be signalled blind). */
51
+ export async function signalGroup(pgid, sig, { keep, verified = false, snapshot = () => processSnapshot(), kill = (pid, s) => process.kill(pid, s) } = {}) {
52
+ const spare = await spared(keep);
53
+ if (!spare.size && !verified) {
54
+ try { kill(-pgid, sig); } catch { /* the group is already empty */ }
55
+ return;
56
+ }
57
+ // Signal members one by one. If the list is unreadable, end only the agent
58
+ // itself, as before #6557 (and nothing at all on a verified pass).
59
+ const found = (await members(pgid, spare, snapshot)) ?? (verified ? [] : [pgid]);
60
+ for (const pid of found) {
61
+ try { kill(pid, sig); } catch { /* gone already */ }
62
+ }
63
+ }
64
+
65
+ /** AFTER A KILL, WAIT UNTIL THE GROUP HAS NOTHING LEFT TO END. What the agent
66
+ * started gets until `deadline` (the kill grace) to follow SIGTERM, then
67
+ * SIGKILL, then a bounded wait for the kernel to reap them. Returns the pids
68
+ * that survived (empty: done), so the caller can keep recovery evidence for
69
+ * exactly those. POSIX only, like the group itself. */
70
+ export async function reapGroup(pgid, deadline, { keep, snapshot = () => processSnapshot(), alive = groupAlive, kill, wait = nap, now = Date.now, finalWaitMs = 2_000 } = {}) {
71
+ if (!Number.isInteger(pgid) || pgid <= 1) return [];
72
+ const spare = await spared(keep);
73
+ const step = spare.size ? 100 : 25;
74
+ const left = async () => spare.size ? ((await members(pgid, spare, snapshot))?.length ?? 1) > 0 : alive(pgid);
75
+ while (await left() && now() < deadline) await wait(step);
76
+ if (!await left()) return [];
77
+ await signalGroup(pgid, "SIGKILL", { keep, verified: true, snapshot, ...(kill ? { kill } : {}) });
78
+ for (let waited = 0; waited < finalWaitMs && await left(); waited += step) await wait(step);
79
+ if (!await left()) return [];
80
+ return (await members(pgid, spare, snapshot)) ?? [pgid];
81
+ }
@@ -34,7 +34,7 @@
34
34
  // are seams, every test asserts the argv sequence, and NOTHING in the suite
35
35
  // runs claude, codex, opencode or a browser on the machine running it.
36
36
 
37
- import { hostedStatus, login as hostedLogin, readAuthFile } from "./auth.mjs";
37
+ import { authDisplayPath, hostedStatus, login as hostedLogin, readAuthFile } from "./auth.mjs";
38
38
  import { projectMcpServerKey } from "./project-mcp.mjs";
39
39
  import { execProbe, runInteractive } from "./detect.mjs";
40
40
  import { compareVersions } from "./update.mjs";
@@ -209,7 +209,7 @@ export async function signInStep({
209
209
  }
210
210
  try {
211
211
  const stored = await login({ env, log: (line) => log(hint(line, options)) });
212
- return settle("ok", `VIEWABLE_BOARD_TOKEN saved to ~/.glytch/auth.json (${stored.appUrl})`);
212
+ return settle("ok", `VIEWABLE_BOARD_TOKEN saved to ${authDisplayPath(env)} (${stored.appUrl})`);
213
213
  } catch (error) {
214
214
  return settle("fail", error instanceof Error ? error.message : String(error));
215
215
  }
@@ -0,0 +1,68 @@
1
+ // Shared npm targeting for updates and removal. The installed package owns
2
+ // the prefix; env node may have started it with an unrelated Node (#5305).
3
+ import { existsSync, realpathSync } from "node:fs";
4
+ import { posix, win32 } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { runnableCommand } from "./windows-command.mjs";
7
+
8
+ const CLI_PATH = fileURLToPath(new URL("../glytch.mjs", import.meta.url));
9
+
10
+ /** A POSIX prefix owns this copy only when its own bin/viewable shim resolves
11
+ * to this very file. A folder shaped like `<prefix>/lib/node_modules` proves
12
+ * nothing: a project directory named `lib` has the same shape (#5403). */
13
+ function ownsShim(path, prefix, cliPath, { exists, resolvePath }) {
14
+ const shim = path.join(prefix, "bin", "viewable");
15
+ try { return exists(shim) && resolvePath(shim) === cliPath; } catch { return false; }
16
+ }
17
+
18
+ /** Extract the global package directory (formerly in selfUninstall). Never
19
+ * treat a checkout, local dependency or npx cache as a global installation. */
20
+ export function globalPackageDir(cliPath, { platform = process.platform, env = process.env, nodePath = process.execPath, exists = existsSync, resolvePath = realpathSync } = {}) {
21
+ const path = platform === "win32" ? win32 : posix;
22
+ try { cliPath = resolvePath(cliPath); } catch { return null; }
23
+ const dir = path.dirname(cliPath);
24
+ if (path.basename(dir) !== "viewable-one" || path.basename(path.dirname(dir)) !== "node_modules") return null;
25
+ if (/[\\/]_npx[\\/]/.test(dir)) return null;
26
+ const parent = path.dirname(path.dirname(dir));
27
+ if (platform !== "win32") return path.basename(parent) === "lib" && ownsShim(path, path.dirname(parent), cliPath, { exists, resolvePath }) ? dir : null;
28
+ // Windows global packages have command shims in their prefix. Local
29
+ // dependencies put those shims in node_modules/.bin instead.
30
+ const appData = env.APPDATA ? path.join(env.APPDATA, "npm") : "";
31
+ return parent.toLowerCase() === appData.toLowerCase() || parent.toLowerCase() === path.dirname(nodePath).toLowerCase()
32
+ || exists(path.join(parent, "viewable.cmd")) ? dir : null;
33
+ }
34
+
35
+ export function npmPathFor({ platform = process.platform, env = process.env, nodePath = process.execPath, exists = existsSync } = {}) {
36
+ const path = platform === "win32" ? win32 : posix;
37
+ const nodeDir = path.dirname(nodePath);
38
+ const voltaHome = String(env?.VOLTA_HOME ?? "");
39
+ if (/[\\/]tools[\\/]image[\\/]node[\\/]/.test(nodePath) || (voltaHome && nodePath.startsWith(voltaHome))) return env;
40
+ if (!exists(path.join(nodeDir, platform === "win32" ? "npm.cmd" : "npm"))) return env;
41
+ const key = Object.keys(env ?? {}).find((k) => (platform === "win32" ? k.toUpperCase() === "PATH" : k === "PATH")) ?? "PATH";
42
+ const rest = String(env?.[key] ?? "").split(path.delimiter).filter((dir) => dir && dir !== nodeDir);
43
+ return { ...env, [key]: [nodeDir, ...rest].join(path.delimiter) };
44
+ }
45
+
46
+ /** Resolve once before spawning, including before self-uninstall deletes us.
47
+ * Volta owns its package image, so its shim must retain control of the prefix.
48
+ * Custom global prefixes may have no Node; pin the destination regardless. */
49
+ export function npmCommand(args, { platform = process.platform, env = process.env, nodePath = process.execPath, cliPath = CLI_PATH, exists = existsSync, resolvePath = realpathSync, readFile } = {}) {
50
+ const path = platform === "win32" ? win32 : posix;
51
+ const packageDir = globalPackageDir(cliPath, { platform, env, nodePath, exists, resolvePath });
52
+ const volta = packageDir && /[\\/]tools[\\/]image[\\/]packages[\\/]/.test(packageDir);
53
+ const prefix = packageDir && !volta ? path.resolve(packageDir, platform === "win32" ? "../.." : "../../..") : null;
54
+ if (prefix) {
55
+ const bin = platform === "win32" ? prefix : path.join(prefix, "bin");
56
+ const owningNode = path.join(bin, platform === "win32" ? "node.exe" : "node");
57
+ const npm = platform === "win32" ? path.join(bin, "node_modules/npm/bin/npm-cli.js") : path.join(bin, "npm");
58
+ if (exists(owningNode) && exists(npm)) nodePath = owningNode;
59
+ args = [...args, "--prefix", prefix];
60
+ }
61
+ const npmEnv = volta ? env : npmPathFor({ platform, env, nodePath, exists });
62
+ const cli = path.join(path.dirname(nodePath), "node_modules/npm/bin/npm-cli.js");
63
+ // Node's npm.cmd uses variables that the generic shim parser refuses.
64
+ const command = !volta && platform === "win32" && exists(cli)
65
+ ? { file: nodePath, args: [cli, ...args], shell: false }
66
+ : runnableCommand("npm", args, { platform, env: npmEnv, nodePath, exists, ...(readFile ? { readFile } : {}) });
67
+ return { ...command, env: npmEnv, packageDir };
68
+ }