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.
@@ -228,9 +228,95 @@ const scopeOf = (input, folder) =>
228
228
  const runsOutside = (toolName, input, folder) =>
229
229
  toolName === "Bash" && typeof input?.cwd === "string" && input.cwd !== "" && scopeOf(input, folder) !== undefined && !staysInFolder(".", input.cwd, folder);
230
230
 
231
+ // ---------------------------------------------------------------------------
232
+ // A FILE TOOL'S REMEMBERED RULE STAYS IN THE FOLDER (#6556)
233
+ //
234
+ // A rule for a file tool is the tool's bare name (`Edit`), so "Always allow in
235
+ // my-app" for one edit must not also wave through an edit of `/etc/hosts`.
236
+ // A remembered rule therefore applies only when every path the call names
237
+ // lands inside the linked folder, links followed (`realPathOf`), a relative
238
+ // path judged from the run's own folder (Claude's file tools resolve it
239
+ // there, not from the shell's `cd`s). A call with no path, a path that cannot
240
+ // be read as text, or one that lands outside or through a link that leads out,
241
+ // is covered by nothing: it asks, and offers no "Always" button, since no
242
+ // saved rule would apply to it. Bash has its own check above and is untouched.
243
+
244
+ const FILE_TOOLS = new Set(["Read", "Write", "Edit", "MultiEdit", "NotebookEdit"]);
245
+ const SEARCH_TOOLS = new Set(["Glob", "Grep"]);
246
+ /** Keys a tool puts a path in. */
247
+ const PATH_KEYS = ["file_path", "notebook_path", "path"];
248
+ const GLOB_CHARS = /[*?[\]{}()!]/;
249
+
250
+ /** The directory a glob starts from: its steps up to the first one that
251
+ * names more than one thing. Null for a pattern that reaches out of its
252
+ * root by itself: `..` steps, or a leading `~`. */
253
+ const globRoot = (pattern) => {
254
+ if (pattern.startsWith("~")) return null;
255
+ const steps = pattern.split(/[\\/]/);
256
+ if (steps.includes("..")) return null;
257
+ const fixed = [];
258
+ for (const step of steps) {
259
+ if (GLOB_CHARS.test(step)) break;
260
+ fixed.push(step);
261
+ }
262
+ return fixed.length === steps.length ? pattern : (fixed.join("/") || (pattern.startsWith("/") ? "/" : "."));
263
+ };
264
+
265
+ /** The paths a call names, as `{path, glob}` entries to judge, or null when
266
+ * the call must ask: a file tool with no path text, or one with a NUL byte. */
267
+ const targetsOf = (toolName, input) => {
268
+ const isText = (value) => typeof value === "string" && value !== "" && !value.includes("\0");
269
+ if (FILE_TOOLS.has(toolName)) {
270
+ const path = input?.file_path ?? input?.notebook_path;
271
+ return isText(path) ? [{ path }] : null;
272
+ }
273
+ if (SEARCH_TOOLS.has(toolName)) {
274
+ // No `path` means the run's own folder.
275
+ const out = [];
276
+ if (input?.path !== undefined && input.path !== null && input.path !== "") {
277
+ if (!isText(input.path)) return null;
278
+ out.push({ path: input.path });
279
+ } else out.push({ path: "." });
280
+ for (const key of toolName === "Glob" ? ["pattern"] : ["glob"]) {
281
+ const value = input?.[key];
282
+ if (value === undefined || value === null || value === "") continue;
283
+ if (!isText(value)) return null;
284
+ // A glob is judged from the search root (an absolute one is judged as written).
285
+ out.push({ path: value, glob: true, from: out[0].path });
286
+ }
287
+ return out;
288
+ }
289
+ // Any other tool that names a path (an engine's own file tool) is held to it too.
290
+ if (toolName === "Bash" || toolName === "Permissions" || String(toolName).startsWith("mcp__")) return [];
291
+ const out = [];
292
+ for (const key of PATH_KEYS) {
293
+ const value = input?.[key];
294
+ if (value === undefined || value === null) continue;
295
+ if (!isText(value)) return null;
296
+ out.push({ path: value });
297
+ }
298
+ return out;
299
+ };
300
+
301
+ /** Whether every path this call names lands inside `folder`, links followed.
302
+ * True for a tool that names no path (nothing to hold it to). */
303
+ export function targetsStayInFolder(toolName, input, folder, base) {
304
+ const targets = targetsOf(toolName, input);
305
+ if (targets === null) return false;
306
+ if (targets.length === 0) return true;
307
+ if (typeof folder !== "string" || folder === "") return false;
308
+ const from = typeof base === "string" && base !== "" ? base : folder;
309
+ return targets.every((target) => {
310
+ if (!target.glob) return staysInFolder(target.path, from, folder);
311
+ const root = globRoot(target.path);
312
+ return root !== null && staysInFolder(root, isAbsolute(root) ? from : resolve(from, target.from), folder);
313
+ });
314
+ }
315
+
231
316
  /** The "Always allow" button for a tool call. A shell command names its
232
317
  * family, or says it saves this command only. */
233
- export function alwaysOptionFor(toolName, input, folderName, folder) {
318
+ export function alwaysOptionFor(toolName, input, folderName, folder, base) {
319
+ if (!targetsStayInFolder(toolName, input, folder, base)) return "";
234
320
  if (toolName !== "Bash") return alwaysLabel(folderName);
235
321
  if (runsOutside(toolName, input, folder)) return "";
236
322
  const family = safeFamilyOf(input?.command, scopeOf(input, folder));
@@ -418,7 +504,8 @@ export function questionFor({ toolName, input, folder, base }) {
418
504
  const mcp = /^mcp__(.+?)__(.+)$/.exec(String(toolName));
419
505
  if (mcp) {
420
506
  const [, provider, name] = mcp;
421
- const risk = writeRisk(provider.toLowerCase(), name, input) ?? "open-ended";
507
+ // A computer app has no catalog row: its risk is read from the call alone (#5442).
508
+ const risk = writeRisk(null, name, input) ?? "open-ended";
422
509
  return { question: `Use ${name.replaceAll("_", " ")} in ${provider}?`,
423
510
  // A tool that only flags itself destructive has no reason line (#4571).
424
511
  why: `On your computer, ${provider}\n${riskReason(risk) ? `${riskReason(risk)}\n` : ""}${appInputsText(provider, input, name)}`,
@@ -457,7 +544,7 @@ export function questionFor({ toolName, input, folder, base }) {
457
544
  return {
458
545
  question: bash ? bash.question : `Can I ${action}?`,
459
546
  why,
460
- options: [ALLOW, toolName === "Bash" ? ALLOW_RUN : "", NOT_THIS, alwaysOptionFor(toolName, input, folderName, folder)].filter(Boolean),
547
+ options: [ALLOW, toolName === "Bash" ? ALLOW_RUN : "", NOT_THIS, alwaysOptionFor(toolName, input, folderName, folder, base)].filter(Boolean),
461
548
  recommendation: { answer: ALLOW, why: "It lets this run carry on with what you asked." },
462
549
  };
463
550
  }
@@ -497,8 +584,10 @@ export async function rememberRule(env, folder, key) {
497
584
  * saved before #3726 still matches its family when it names one (`Bash(ls:*)`,
498
585
  * cat, pwd, head, tail, wc), and only then; any other (`Bash(npm:*)`,
499
586
  * `Bash(rm:*)`) matches no key any more. */
500
- export function ruleCovers(rules, toolName, input, folder) {
587
+ export function ruleCovers(rules, toolName, input, folder, base) {
501
588
  if (!rememberable(toolName, input)) return false;
589
+ // A file tool's rule is its bare name, so the paths it names are checked here (#6556).
590
+ if (!targetsStayInFolder(toolName, input, folder, base)) return false;
502
591
  // A command run from outside the linked folder is never covered, not even by
503
592
  // a rule saved for those exact bytes (#3759): the bytes mean something else there.
504
593
  if (runsOutside(toolName, input, folder)) return false;
@@ -629,7 +718,7 @@ export function createPermissionAsker({
629
718
  // write the folder's remembered permission rules.
630
719
  const remembered = question ? [] : await readRules(env, folder);
631
720
  if (signal?.aborted) return null;
632
- if (!question && ruleCovers(remembered, toolName, input, folder)) {
721
+ if (!question && ruleCovers(remembered, toolName, input, folder, cwd)) {
633
722
  log(`permission: ${ruleKeyFor(toolName, input, folder)} is allowed in ${folderName} (remembered), no question filed`);
634
723
  return allow();
635
724
  }
@@ -683,6 +772,7 @@ export function createPermissionAsker({
683
772
  const verdict = verdictFor(answer, folderName, q.options.find((o) => o.startsWith("Always allow")) ?? null, { runOffered: q.options.includes(ALLOW_RUN) });
684
773
  if (verdict.forRun) runAllowed.abort();
685
774
  if (verdict.remember && !rememberable(toolName, input)) log("permission: this grant names no scope, so it is allowed once and not remembered");
775
+ else if (verdict.remember && !targetsStayInFolder(toolName, input, folder, cwd)) log("permission: this call names a path outside the folder, so it is allowed once and not remembered (#6556)");
686
776
  else if (verdict.remember) {
687
777
  try { await rememberRule(env, folder, ruleKeyFor(toolName, input, folder)); }
688
778
  catch (error) { log(`permission: could not save the rule (${error?.message ?? error}); allowing this once`); }
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
@@ -46,7 +46,11 @@ async function claimAdmitted(root, project, settings, runnerApi, { activeRunIds,
46
46
  if (!(await flushCompletions(project, settings))) return { claimed: false, transient: true, detail: "Saved completions are waiting to sync." };
47
47
  const room = await runningRoom(project, settings, runnerApi, { activeRunIds, log });
48
48
  if (!room.ok) return { claimed: false, ...room };
49
- const claimed = await runnerApi.claim({ projectIds: [project.id], runnerInstanceId: settings.runnerInstanceId ??= randomUUID(), fencing: true }, rowsOpts);
49
+ const claimed = await runnerApi.claim({
50
+ projectIds: [project.id], runnerInstanceId: settings.runnerInstanceId ??= randomUUID(), fencing: true,
51
+ // The database holds the same cap across this computer's folders (#5732).
52
+ ...(Number.isFinite(settings.maxConcurrent) ? { maxConcurrent: settings.maxConcurrent } : {}),
53
+ }, rowsOpts);
50
54
  if (!claimed.ok) return { claimed: false, transient: claimed.transient === true, ...retryHint(claimed), detail: claimed.error };
51
55
  if (!claimed.run) return { claimed: false, idle: true, detail: "nothing pending" };
52
56
  return { claimed: true, run: claimed.run };
package/lib/runnerApi.mjs CHANGED
@@ -193,8 +193,13 @@ export function heartbeat({ projectIds, presence, runnerInstanceId, activeRunIds
193
193
  * `listRequests`/`claimRequest`'s exclusive-create-on-disk race. `run.request`
194
194
  * is the SpawnRequest a file used to carry; `run.project_id` names which
195
195
  * registered project (and therefore which root) it belongs to. */
196
- export function claim({ projectIds, runnerInstanceId, fencing }, options = {}) {
197
- return call("claim", { projectIds, ...(runnerInstanceId !== undefined ? { runnerInstanceId } : {}), ...(fencing === true ? { fencing } : {}) }, options);
196
+ /** `maxConcurrent` is PM_SPAWN_MAX_CONCURRENT when set: the database holds it
197
+ * per computer across folders (#5732). Absent (the default) is no cap. */
198
+ export function claim({ projectIds, runnerInstanceId, fencing, maxConcurrent }, options = {}) {
199
+ return call("claim", {
200
+ projectIds, ...(runnerInstanceId !== undefined ? { runnerInstanceId } : {}), ...(fencing === true ? { fencing } : {}),
201
+ ...(Number.isSafeInteger(maxConcurrent) && maxConcurrent >= 1 ? { maxConcurrent } : {}),
202
+ }, options);
198
203
  }
199
204
 
200
205
  /** `update {runId, patch}` -> ok, or `{ok:false, error:"result already
@@ -12,7 +12,8 @@
12
12
  // not in four separate writes racing whatever else might be reading the row.
13
13
  import { cleanWorktree, isGitCheckout, worktreeSummary } from "./worktree.mjs";
14
14
  import { readWorktreeRecord } from "./devserver.mjs";
15
- import { reportOutcomeOnBoard, formatVerdict } from "./boardside.mjs";
15
+ import { reportOutcomeOnBoard, formatVerdict, closingTextOf, finishedCleanly } from "./boardside.mjs";
16
+ import { asksForComputerApps } from "./conversationRules.mjs";
16
17
  import { promoteLateRows } from "./rowsAnswers.mjs";
17
18
  import { housekeeping } from "./runnerMaintenance.mjs";
18
19
  import { classifyExit } from "./exitClass.mjs";
@@ -238,6 +239,13 @@ export async function completeRequest(context, services = defaultServices) {
238
239
  // its exit happened to read as ok - "you stopped it" is worth keeping
239
240
  // separate from "it finished" even when the two exits look alike.
240
241
  const status = wasStopped ? "stopped" : outcome.ok === true ? "done" : "error";
242
+ // A RUN THAT FINISHED BUT COULD NOT DO ITS JOB (#6552): it had no way to
243
+ // the person's apps and its closing words ask for them. The row stays
244
+ // `done` (the session did end well); `unable` names why, so a scheduled
245
+ // run's automation counts a failure (runs_habit_completion) instead of
246
+ // "Ran". A run that had the apps never sets it.
247
+ const unable = status === "done" && request?.computerApps !== true
248
+ && finishedCleanly(outcome) && asksForComputerApps(closingTextOf(outcome)) ? "computer-apps" : undefined;
241
249
  const patch = {
242
250
  status,
243
251
  result: `${outcome.ok === true ? "OK" : "ERROR"}\n\n${detail}\n`,
@@ -247,7 +255,7 @@ export async function completeRequest(context, services = defaultServices) {
247
255
  // final sidecar and may retain their early workspace receipt instead.
248
256
  // The pictures ride on the closing reply only: two of them on every run
249
257
  // row would weigh down each list of runs (#2194).
250
- sidecar: { ...(sidecar ?? {}), resultLanded, ...(outcome.result ? { result: withoutPictures(outcome.result) } : {}), ...(status === "error" ? agentErrorOf(outcome) : {}) },
258
+ sidecar: { ...(sidecar ?? {}), resultLanded, ...(unable ? { unable } : {}), ...(outcome.result ? { result: withoutPictures(outcome.result) } : {}), ...(status === "error" ? agentErrorOf(outcome) : {}) },
251
259
  ...(server ? { server } : {}),
252
260
  };
253
261
 
@@ -9,6 +9,7 @@ import { createRowsAnswerPoll } from "./rowsAnswers.mjs";
9
9
  import { createPermissionAsker } from "./permissionAsk.mjs";
10
10
  import { makeRowEventStreamer } from "./rowsEvents.mjs";
11
11
  import { AGENTS, agentFor, prepareWorkspace, runnerFor } from "./agents.mjs";
12
+ import { readWorktreeRecord } from "./devserver.mjs";
12
13
  import { classifyExit } from "./exitClass.mjs";
13
14
  import { DEFAULTS, childEnv } from "./child.mjs";
14
15
  import { BOARD_DIR } from "./paths.mjs";
@@ -129,7 +130,14 @@ export async function startRun(ctx, state, { timing, receipt, preparation, finis
129
130
 
130
131
  const makeRunOpts = runOptionsFor(ctx, state, { imageSuffix, onChunk, childEnvObj, stopCheck, answerPoll, askPermission, receipt });
131
132
  const runOpts = makeRunOpts(plan);
132
- const runFn = runnerFor(agent, useStreaming);
133
+ // A child that left something running in its group after Stop keeps the
134
+ // recovery record, so the next pass can still find and end it (#6557).
135
+ const runner = runnerFor(agent, useStreaming);
136
+ const runFn = async (options) => {
137
+ const outcome = await runner(options);
138
+ if (outcome?.descendantsRemain) await settings.recoveryTracker?.retain(outcome.descendantsRemain);
139
+ return outcome;
140
+ };
133
141
 
134
142
  if (settings.stopped?.has(id)) return await finish({ status: "stopped", result: settings.leaseLost?.has(id) ? "STOPPED\n\nRunner connection expired before the process was started.\n" : "STOPPED\n\nStopped by user request before the process was started.\n", finished_at: new Date().toISOString() });
135
143
  preparation.complete();
@@ -208,6 +216,8 @@ function runOptionsFor({ id, request, runnerApi, rowsOpts, settings, log }, { ag
208
216
  onChunk,
209
217
  requireResume: request.recovery === true && Boolean(request.resumeSessionId),
210
218
  recoveryGroup: Boolean(settings.recoveryTracker),
219
+ // The server the session recorded survives Stop (ruling A, 2026-09-06).
220
+ keepPids: async () => { const record = await readWorktreeRecord(made.cwd); return record ? [Number(record.pid)] : []; },
211
221
  onProcess: settings.recoveryTracker ? (pid) => settings.recoveryTracker.onProcess(pid, { group: platform !== "win32" }) : undefined,
212
222
  onSession: async (threadId) => {
213
223
  receipt.sidecar = { ...receipt.sidecar, [agentFor(agent) === "codex" ? "codexThreadId" : "claudeSessionId"]: threadId, resumeSessionId: threadId, restartable: true };
@@ -60,6 +60,28 @@ async function retainGroups(record, snapshot, identity, gone, onChange = () => {
60
60
  if (retained.length !== (record.groups ?? []).length) { record.groups = retained; onChange(); }
61
61
  }
62
62
 
63
+ /** A retained record is only a reminder that something may still be running.
64
+ * Once every survivor has exited (or its pid belongs to another process now),
65
+ * delete it, so the run stops holding a slot. Only the record this call kept
66
+ * is removed: a newer run with the same id has a different token. */
67
+ function watchSurvivors(path, token, survivors, { readIdentity, isAlive }) {
68
+ const timer = setInterval(async () => {
69
+ try {
70
+ for (const member of survivors) {
71
+ if (!isAlive(member.pid)) continue;
72
+ const current = await readIdentity(member.pid);
73
+ if (current?.command?.includes("<defunct>")) continue;
74
+ if (sameProcessIdentity(member, current) !== false) return; // still running, or cannot tell
75
+ }
76
+ clearInterval(timer);
77
+ try {
78
+ if (JSON.parse(readFileSync(path, "utf8")).retainedToken === token) unlinkSync(path);
79
+ } catch { /* already replaced or removed */ }
80
+ } catch { /* look again next tick */ }
81
+ }, 2000);
82
+ timer.unref?.();
83
+ }
84
+
63
85
  export async function trackRun(project, run, settings, receipt, { readIdentity = readProcessIdentity, readTable = processTable, readGroups = processGroups, isAlive = alive, now = () => performance.now(), after = setTimeout, cancel = clearTimeout } = {}) {
64
86
  if (!run.lease_generation) return null; // Installed server without fencing.
65
87
  const path = recoveryPath(project, run.id, settings);
@@ -74,6 +96,10 @@ export async function trackRun(project, run, settings, receipt, { readIdentity =
74
96
  host: hostname(), pid: process.pid, ownerStartedAt: owner?.startedAt, ownerCommand: owner?.command, budgetMs: wallClockFor(run.request), workingMs: 0, sidecar: receipt.sidecar,
75
97
  ...(preparedResume ? { launching: true, preparedResume: true } : {}) };
76
98
  let closed = false;
99
+ // Set when a stopped child left a running process behind (#6557): the record
100
+ // is then the only thing that can still end it, so close() must not delete it.
101
+ let retained = false;
102
+ let survivors = [];
77
103
  const write = () => {
78
104
  record.workingMs = Math.ceil(performance.now() - started);
79
105
  record.savedAt = Date.now(); // Recovery charges a surviving agent from here.
@@ -180,12 +206,31 @@ export async function trackRun(project, run, settings, receipt, { readIdentity =
180
206
  registering.add(registration);
181
207
  try { persist(); void output(); } catch { (settings.stopped ??= new Set()).add(run.id); }
182
208
  },
183
- async close({ keep = false } = {}) {
209
+ /** A stopped child left these pids running. Save their identities now, so
210
+ * a restart can anchor and end them (stopOrphan), and let close() keep the
211
+ * record until they are gone. */
212
+ async retain(pids = []) {
213
+ retained = true;
214
+ const found = [];
215
+ for (const pid of pids) {
216
+ const identity = await readIdentity(pid);
217
+ if (identity) found.push({ pid, ...identity });
218
+ }
219
+ survivors = found;
220
+ if (found.length) {
221
+ const seen = new Set(found.map(member => member.pid));
222
+ record.processes = [...found, ...(record.processes ?? []).filter(member => !seen.has(member.pid))];
223
+ }
224
+ record.retainedToken = randomUUID();
225
+ try { write(); } catch { /* the previous save still stands */ }
226
+ },
227
+ async close({ keep = retained } = {}) {
184
228
  closed = true; clearInterval(timer);
185
229
  if (outputTimer) { cancel(outputTimer); outputTimer = null; }
186
230
  resolveOutput?.(); resolveOutput = null; pendingOutput = null;
187
231
  try {
188
232
  if (!keep) { try { unlinkSync(path); } catch (error) { if (error.code !== "ENOENT") throw error; } }
233
+ else if (retained && survivors.length) watchSurvivors(path, record.retainedToken, survivors, { readIdentity, isAlive });
189
234
  } finally { await lock.release(); }
190
235
  },
191
236
  };
@@ -95,6 +95,14 @@ export async function prepareRequestWorkspace(context, services = defaultService
95
95
  const isOwnTree = wantedRecordedTree && typeof ownTreePath === "string" && ownTreePath !== "";
96
96
  if (wantedRecordedTree && !isOwnTree) log(`[${id}] the named worktree ${request.worktreePath} is not this idea's own; not reused`);
97
97
  const reusedTree = isOwnTree ? await reuseWorktree(root, ownTreePath, log, lifecycle) : null;
98
+ // THE REPO LOCK COULD NOT BE HELD (#6558): spawn nothing. The tree is not
99
+ // gone and a fallback would put the session in the checkout the holder is
100
+ // changing, so neither "the copy is gone" nor an unisolated run is true.
101
+ const lockRefusal = (detail) => {
102
+ log(`[${id}] refused: ${detail}`);
103
+ return { ok: false, patch: { status: "error", result: `ERROR\n\nNOTHING WAS SPAWNED AND NOTHING WAS BILLED.\n\n${detail}\n\nRun again once the other repository change has finished.\n`, finished_at: new Date().toISOString() } };
104
+ };
105
+ if (reusedTree?.lockRefused) return lockRefusal(reusedTree.detail);
98
106
  if ((request.recovery === true || (request.continues && isResume)) && wantedRecordedTree && !reusedTree) {
99
107
  return { ok: false, patch: { status: "error", result: "ERROR\n\nThis session cannot continue because its separate copy is gone. Run again to start a new session.\n", finished_at: new Date().toISOString(), sidecar: { ...(request.recovery === true ? { recoveryFailed: true } : {}) } } };
100
108
  }
@@ -118,6 +126,7 @@ export async function prepareRequestWorkspace(context, services = defaultService
118
126
  ? { cwd: root, isolated: false, detail: `Ran in the linked folder per idea setting (worktree off).` }
119
127
  : await makeWorktree(root, id, log, title(request), lifecycle);
120
128
  preparation?.check();
129
+ if (made.lockRefused) return lockRefusal(made.detail);
121
130
 
122
131
  const wantedIsolation = !isChat && !request.cwd && request.useWorktree !== false;
123
132
  if (wantedIsolation && !made.isolated) {
@@ -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,31 +108,37 @@ 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
119
114
  * tokens stay out: the uninstall reads the stored sign-in from the home. */
120
- export function carriedEnv(env = process.env) {
115
+ export function carriedEnv(env = process.env, platform = process.platform) {
116
+ // Windows environment names are case-insensitive; retain the supplied Path spelling.
121
117
  const keep = /^(HOME|PATH|USERPROFILE|APPDATA|LOCALAPPDATA|TMPDIR|TEMP|TMP|XDG_[A-Z_]+|(VIEWABLE|GLYTCH)_[A-Z0-9_]+)$/;
122
118
  const secret = /TOKEN|SECRET|KEY|PASSWORD/i;
123
- return Object.fromEntries(Object.entries(env).filter(([name, value]) => typeof value === "string" && keep.test(name) && !secret.test(name)));
119
+ return Object.fromEntries(Object.entries(env).filter(([name, value]) => typeof value === "string" && (keep.test(name) || (platform === "win32" && /^PATH$/i.test(name))) && !secret.test(name)));
124
120
  }
125
121
 
126
122
  /** The detached command: `viewable uninstall --yes`, then, only when it
127
123
  * 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;
124
+ export function selfUninstallCommand({ execPath = process.execPath, cliPath = CLI_PATH, env = process.env, ...options } = {}) {
125
+ const target = { ...options, nodePath: execPath, cliPath, env };
126
+ const npm = globalPackageDir(cliPath, target) ? npmCommand(["uninstall", "-g", "viewable-one"], target) : null;
130
127
  const script = [
131
128
  'const { spawnSync } = require("node:child_process");',
132
- `const env = { ...process.env, ...${JSON.stringify(carriedEnv(env))} };`,
129
+ // The launcher may spell Path differently from the daemon. Collapse aliases
130
+ // before either spawn so Node cannot discard the carried search path.
131
+ 'const mergeEnv = (base, carried) => {',
132
+ ' const merged = { ...base, ...carried };',
133
+ ' if (process.platform === "win32") {',
134
+ ' const key = Object.keys(carried).find((name) => /^path$/i.test(name)) ?? Object.keys(base).find((name) => /^path$/i.test(name));',
135
+ ' for (const name of Object.keys(merged)) if (/^path$/i.test(name) && name !== key) delete merged[name];',
136
+ ' }',
137
+ ' return merged;',
138
+ '};',
139
+ `const env = mergeEnv(process.env, ${JSON.stringify(carriedEnv(env, options.platform))});`,
133
140
  `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" });` : "",
141
+ npm ? `if (done.status === 0) spawnSync(${JSON.stringify(npm.file)}, ${JSON.stringify(npm.args)}, { stdio: "ignore", env: mergeEnv(env, ${JSON.stringify(carriedEnv(npm.env, options.platform))}), shell: false });` : "",
135
142
  ].join("\n");
136
143
  return { command: execPath, args: ["-e", script], script };
137
144
  }
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
package/lib/uninstall.mjs CHANGED
@@ -36,7 +36,7 @@ import { join } from "node:path";
36
36
  import { bold, bullets, colorEnabled, heading, hint, renderRow, row, step, summary, warn, warnRow } from "./cli-output.mjs";
37
37
  import { appUrlFrom, logout as hostedLogout, readAuthFile } from "./auth.mjs";
38
38
  import { detectAgents, execProbe } from "./detect.mjs";
39
- import { viewableHome, readRegistry } from "./registry.mjs";
39
+ import { viewableDisplayPath, viewableHome, readRegistry } from "./registry.mjs";
40
40
  import { loginDaemon } from "./logindaemon.mjs";
41
41
  import { uninstallProject } from "./uninstall-project.mjs";
42
42
 
@@ -99,7 +99,7 @@ export function readlineAsk(input = process.stdin, output = process.stdout) {
99
99
 
100
100
  /** The bulleted plan printed before the question is ever asked - "print what
101
101
  * will happen" first, so "Type yes to continue" means something. */
102
- export function uninstallPlan(options, { folderCount = 0 } = {}) {
102
+ export function uninstallPlan(options, { folderCount = 0, env = process.env } = {}) {
103
103
  const lines = [];
104
104
  if (options.project) {
105
105
  lines.push(
@@ -119,8 +119,8 @@ export function uninstallPlan(options, { folderCount = 0 } = {}) {
119
119
  );
120
120
  lines.push(
121
121
  options.keepLogin
122
- ? "Leave ~/.glytch in place: the sign-in credential lives there (--keep-login)."
123
- : "Delete ~/.glytch entirely.",
122
+ ? `Leave ${viewableDisplayPath(env)} in place: the sign-in credential lives there (--keep-login).`
123
+ : `Delete ${viewableDisplayPath(env)} entirely.`,
124
124
  );
125
125
  }
126
126
  lines.push("Print the two steps left to finish by hand: uninstalling the npm package, and unlinking the folder in the app.");
@@ -313,13 +313,13 @@ export async function revokeRow({ stored, env, fetchImpl, dryRun, keepLogin, log
313
313
  export async function deleteHomeRow({ env, dryRun, keepLogin }) {
314
314
  const home = viewableHome(env);
315
315
  if (keepLogin) {
316
- return warnRow("home", "Delete ~/.glytch", "kept", `kept - the sign-in credential lives at ${join(home, "auth.json")} (--keep-login)`);
316
+ return warnRow("home", `Delete ${viewableDisplayPath(env)}`, "kept", `kept - the sign-in credential lives at ${join(home, "auth.json")} (--keep-login)`);
317
317
  }
318
318
  if (dryRun) {
319
- return row("home", "Delete ~/.glytch", true, "would delete", home);
319
+ return row("home", `Delete ${viewableDisplayPath(env)}`, true, "would delete", home);
320
320
  }
321
321
  await rm(home, { recursive: true, force: true });
322
- return row("home", "Delete ~/.glytch", true, "deleted", home);
322
+ return row("home", `Delete ${viewableDisplayPath(env)}`, true, "deleted", home);
323
323
  }
324
324
 
325
325
  /** The two steps this command cannot do for you, as hints under step 3.
@@ -356,7 +356,7 @@ export async function runUninstall({
356
356
  } = {}) {
357
357
  const paint = { color };
358
358
  const roots = options.project ? [root] : await readRegistry(env);
359
- const plan = uninstallPlan(options, { folderCount: roots.length });
359
+ const plan = uninstallPlan(options, { folderCount: roots.length, env });
360
360
  const proceed = await confirmUninstall({ options, plan, isTTY, ask, log, color });
361
361
  if (!proceed) return 1;
362
362
 
@@ -438,16 +438,16 @@ export async function runUninstall({
438
438
  const home = !projectsOk
439
439
  ? warnRow(
440
440
  "home",
441
- "Delete ~/.glytch",
441
+ `Delete ${viewableDisplayPath(env)}`,
442
442
  "left in place",
443
- "a project step failed - ~/.glytch was left in place so `viewable uninstall` can retry",
443
+ `a project step failed - ${viewableDisplayPath(env)} was left in place so \`viewable uninstall\` can retry`,
444
444
  )
445
445
  : revoke.keptCredential
446
446
  ? warnRow(
447
447
  "home",
448
- "Delete ~/.glytch",
448
+ `Delete ${viewableDisplayPath(env)}`,
449
449
  "kept",
450
- "the board sign-in could not be revoked and its credential was kept so a retry can revoke it; ~/.glytch was not deleted",
450
+ `the board sign-in could not be revoked and its credential was kept so a retry can revoke it; ${viewableDisplayPath(env)} was not deleted`,
451
451
  )
452
452
  : await deleteHomeRow({ env, dryRun: options.dryRun, keepLogin: options.keepLogin });
453
453
  for (const line of printedRows([home], paint)) log(line);