diff --git a/.changeset/reinstall-standalone-homebrew.md b/.changeset/reinstall-standalone-homebrew.md new file mode 100644 index 00000000..1e8c8fc0 --- /dev/null +++ b/.changeset/reinstall-standalone-homebrew.md @@ -0,0 +1,10 @@ +--- +"sessionpipe": patch +--- + +Recognize official standalone (`install.sh`) and Homebrew launchers in `sessionpipe doctor` and `sessionpipe reinstall`: + +- Read standalone (`~/.local/bin/sessionpipe`) and Homebrew (`/opt/homebrew/bin/sessionpipe`) launchers safely on `PATH` (bounded plain-file check, never executed) instead of treating them as unknown files blocking npm. +- Keep healthy standalone and Homebrew installs untouched during `sessionpipe reinstall` while removing leftover global npm copies and dangling links (including when npm is not installed or a newer release is out, with an update note). +- Report deleted or broken standalone and Homebrew installs with their native repair commands (`curl -fsSL https://sessionpipe.org/install.sh | sh` or `brew reinstall `) rather than suggesting `mv` and `npx`. +- Note leftover npm copies in `install.sh` when replacing an existing npm global symlink. diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 750ca892..585f03dc 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -1564,17 +1564,33 @@ async function checkup(deep: boolean): Promise<{ report: Record const around = process.platform === "win32" ? null : copies({ npmPrefix: npmrcPrefix(), service: look }); // An npx cache entry nothing uses is a cache, not a second copy (plan.ts `idle`). const installs = (around?.copies ?? []).filter((c) => c.slot && !idle(c)); + const typedManaged = around?.copies.find((c) => c.dir === around.typed && c.managed !== null) ?? null; + const managedBroken = !!typedManaged?.wrong; + const managedFormula = + typedManaged?.managed === "homebrew" + ? (homebrewFormula(path.join(typedManaged.dir, "dist")) ?? "sessionpipe") + : null; const dangling = around?.dangling ?? []; - const collide = installs.length > 1 || dangling.length > 0 || installs.some((c) => c.wrong); + const collide = + installs.length > 1 || + dangling.length > 0 || + installs.some((c) => c.wrong) || + (!!typedManaged && (installs.length > 0 || managedBroken)); // What typing `sessionpipe` starts, where that is known to be no installed copy a shell // finds: a finding with nothing to type, said as `reinstall` says it, so the two never // disagree about which computer is all good. const astray = around ? typing(around, shown) : null; - report.copies = installs.map((c) => ({ dir: c.dir, version: c.version, whole: !c.wrong, uses: c.uses })); - const named = (c: (typeof installs)[number], where: string): string => - `${c.aside ? "a leftover" : c.version} in ${where}`; - // What is typed is not a copy npm installed (a checkout, Volta's copy): nothing to fix, - // and said as what is so. It counts for nothing in the verdict. + const listed = [...(typedManaged ? [typedManaged] : []), ...installs]; + report.copies = listed.map((c) => ({ dir: c.dir, version: c.version, whole: !c.wrong, uses: c.uses })); + const named = (c: (typeof listed)[number], where: string): string => + `${c.aside ? "a leftover" : (c.version ?? "broken")} in ${where}`; + const describeCopy = (c: (typeof listed)[number]): string => + `${named(c, c.where)} (${[ + ...(c.managed ? [c.managed === "standalone" ? "standalone" : "Homebrew"] : []), + c.wrong ?? usedBy(c), + ].join("; ")})`; + // What is typed is not a copy npm installed (a standalone/Homebrew install, a checkout, + // Volta's copy): nothing to fix by itself, and said as what is so. const own = around ? typedAs(around, shown) : null; // But not where what is typed is a folder in npm's own place that is no whole install // (an install that was cut off): `sessionpipe` may not run at all there, and the repair @@ -1592,13 +1608,10 @@ async function checkup(deep: boolean): Promise<{ report: Record label: "copies", value: [ ...(collide - ? [ - ...installs.map((c) => `${named(c, c.where)} (${c.wrong ?? usedBy(c)})`), - ...dangling.map((f) => `${shown(f)}, a link to one that is gone`), - ] + ? [...listed.map(describeCopy), ...dangling.map((f) => `${shown(f)}, a link to one that is gone`)] : []), ...(astray ? [astray] : []), - ...(own ? [own.slice(0, -1)] : []), + ...(own && !typedManaged ? [own.slice(0, -1)] : []), ].join("; "), }); // Nothing to type for it, and still not all good: it is said among what is to fix. @@ -1610,15 +1623,25 @@ async function checkup(deep: boolean): Promise<{ report: Record if (collide) warnings.push( `${ - installs.length > 1 - ? `${installs.length} copies of sessionpipe are on this computer (${installs.map((c) => named(c, c.dir)).join("; ")})` - : `the copy of sessionpipe on this computer is not whole (${[ - ...installs.filter((c) => c.wrong).map((c) => `${named(c, c.dir)}: ${c.wrong}`), - ...dangling.map((f) => `${f} is a link to one that is gone`), - ].join("; ")})` - }; \`sessionpipe reinstall\` leaves one clean copy`, + listed.length > 1 + ? `${listed.length} copies of sessionpipe are on this computer (${listed.map((c) => named(c, c.dir)).join("; ")})` + : managedBroken && typedManaged + ? `the ${typedManaged.managed === "standalone" ? "standalone" : "Homebrew"} copy of sessionpipe on this computer is not whole (${named(typedManaged, typedManaged.dir)}: ${typedManaged.wrong})` + : typedManaged + ? `a leftover link to a sessionpipe copy that is gone is on this computer (${dangling.map((f) => `${f} is a link to one that is gone`).join("; ")})` + : `the copy of sessionpipe on this computer is not whole (${[ + ...installs.filter((c) => c.wrong).map((c) => `${named(c, c.dir)}: ${c.wrong}`), + ...dangling.map((f) => `${f} is a link to one that is gone`), + ].join("; ")})` + }; ${ + managedBroken && typedManaged + ? typedManaged.managed === "standalone" + ? "re-run the standalone installer to repair it" + : `\`brew reinstall ${managedFormula}\` repairs it` + : "`sessionpipe reinstall` leaves one clean copy" + }`, ); - const blocked = !!own && !cut && (collide || two); + const blocked = !!own && !cut && !typedManaged && (collide || two); if (down || apart.length || collide || two || cut) todo.push({ order: 1, @@ -1628,9 +1651,15 @@ async function checkup(deep: boolean): Promise<{ report: Record down ? "The background service isn't running, so no message reaches this computer. " : "" }${two ? "A daemon someone started by hand holds the socket the background service needs. " : ""}${ collide - ? installs.length > 1 - ? `${installs.length} copies of sessionpipe are on this computer, and one is enough. ` - : "The copy of sessionpipe on this computer is not whole. " + ? managedBroken && typedManaged + ? `The ${typedManaged.managed === "standalone" ? "standalone" : "Homebrew"} copy of sessionpipe on this computer is not whole. ` + : typedManaged + ? installs.length > 0 + ? `${installs.length === 1 ? "A leftover npm copy" : `${installs.length} leftover npm copies`} of sessionpipe ${installs.length === 1 ? "is" : "are"} on this computer beside your ${typedManaged.managed === "standalone" ? "standalone" : "Homebrew"} install. ` + : "A link to a sessionpipe copy that is gone is left on this computer. " + : installs.length > 1 + ? `${installs.length} copies of sessionpipe are on this computer, and one is enough. ` + : "The copy of sessionpipe on this computer is not whole. " : apart.length ? `This command is sessionpipe ${VERSION}, and ${apart.join(", and ")}. ` : "" @@ -1641,15 +1670,21 @@ async function checkup(deep: boolean): Promise<{ report: Record ? "What you type is not a copy npm installed, so `sessionpipe reinstall` leaves it alone and can't put this right from here." : "One command puts it right:" }`, - // Where what is typed is not whole, `sessionpipe` may not run: the repair goes through npx. + // Where what is typed is not whole, `sessionpipe` may not run: the repair goes through npx + // (or the standalone installer / Homebrew for managed installs). ...(blocked ? {} : { - run: cut - ? "npx -y sessionpipe@latest reinstall" - : collide || two - ? "sessionpipe reinstall" - : "sessionpipe update", + run: + managedBroken && typedManaged + ? typedManaged.managed === "standalone" + ? "curl -fsSL https://sessionpipe.org/install.sh | sh" + : `brew reinstall ${managedFormula}` + : cut + ? "npx -y sessionpipe@latest reinstall" + : collide || two + ? "sessionpipe reinstall" + : "sessionpipe update", }), }); const w = report.hook_wall_ms as { p50: number; p95: number; n: number } | null; @@ -2680,8 +2715,8 @@ async function reinstall(): Promise { if (a !== "" && a !== "y" && a !== "yes") return out(" Nothing was changed."); say(""); } - const home = (p.home as NonNullable).prefix; - const slot = slotIn(home); + const home = p.home?.prefix ?? null; + const slot = home ? slotIn(home) : (p.managed as NonNullable).dir; const dist = path.join(slot, "dist"); const sock = socketPath(state); // The copy in the home is never removed, by whatever name it is asked for. @@ -2769,13 +2804,18 @@ async function reinstall(): Promise { } }; const files = [served?.file, ...facts.hookFiles].filter((x): x is string => !!x); + const launcher = home ? null : (now.onPath.find((e) => e.dir !== null && same(e.dir, slot))?.file ?? null); return { - // The copy in the home runs, through the link npm made for it: a shell can start - // the file that link leads to (node, asked next, reads one of any mode). - runs: - leads(path.join(home, "bin", "sessionpipe"), slot) && startable(path.join(dist, "cli.js")) - ? versionRun(path.join(dist, "cli.js")) - : null, + // The copy in the home runs, through the link npm made for it (or through the + // standalone/Homebrew launcher): a shell can start the file that link/launcher + // leads to (node, asked next, reads one of any mode). + runs: ( + home + ? leads(path.join(home, "bin", "sessionpipe"), slot) && startable(path.join(dist, "cli.js")) + : launcher !== null && startable(launcher) && existsSync(path.join(dist, "cli.js")) + ) + ? versionRun(path.join(dist, "cli.js")) + : null, typed: now.typed !== null && same(now.typed, slot), onPath: now.onPath.map((e) => e.file), named: files.flatMap((file) => removed.filter((r) => text(file).includes(r)).map((r) => ({ file, path: r }))), diff --git a/packages/cli/src/reinstall/find.ts b/packages/cli/src/reinstall/find.ts index 17dc46aa..c125f47e 100644 --- a/packages/cli/src/reinstall/find.ts +++ b/packages/cli/src/reinstall/find.ts @@ -12,6 +12,7 @@ import { accessSync, constants, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs"; import path from "node:path"; import { parseVersion } from "@sessionpipe/core/version"; +import { homebrewFormula, standaloneRoot } from "../update.js"; import { ASIDE, binsOf, @@ -26,6 +27,7 @@ import { } from "./ours.js"; export type Use = "typed" | "service" | "hooks" | "this"; +export type Managed = "standalone" | "homebrew"; export interface Copy { /** The package folder. */ @@ -37,6 +39,8 @@ export interface Copy { prefix: string | null; /** Ours to remove, and in which kind of slot; null where it is not, with why in `not`. */ slot: Slot | null; + /** Managed by our standalone installer (`install.sh`) or Homebrew; null otherwise. */ + managed: Managed | null; not: string | null; /** A folder left behind: npm's own from an install that was cut off, this command's * from a run that was, or an empty folder of the name (what is left of a copy that @@ -252,6 +256,54 @@ const packageOf = (cli: string | null): string | null => ? path.dirname(path.dirname(cli)) : null; +/** Max launcher script size read from disk; anything larger is no official launcher. */ +const LAUNCHER_MAX = 4096; +const STANDALONE_BANNER = /^# sessionpipe \S+ launcher, written by https:\/\/sessionpipe\.org\/install\.sh$/m; +const STANDALONE_EXEC = /^exec\s+(?:"[^"\n]+"|[^\s"]+)\s+"\$DATA_DIR\/app\/dist\/cli\.js"\s+"\$@"$/m; +const BREW_EXEC = /^exec\s+"[^"]+"\s+"([^"]+\/libexec\/dist\/cli\.js)"\s+"\$@"$/m; + +const hasNodeModules = (p: string): boolean => path.resolve(p).split(/[\\/]/).includes("node_modules"); + +/** Parse a `DATA_DIR=...` line from an `install.sh` launcher (POSIX single-quoted or safe unquoted). */ +function parseDataDir(text: string): string | null { + const raw = /^DATA_DIR=(.+)$/m.exec(text)?.[1]?.trim(); + if (!raw) return null; + if (raw.startsWith("'")) return /^'(?:[^']|'\\'')*'$/.test(raw) ? raw.slice(1, -1).replaceAll("'\\''", "'") : null; + return /[\s"'`$\\]/.test(raw) ? null : raw; +} + +function readLauncher(file: string, allowed: (p: string) => boolean): { kind: Managed; dir: string } | null { + try { + const real = realpathSync(file); + if (!allowed(real)) return null; + const st = statSync(real); + if (!st.isFile() || st.size > LAUNCHER_MAX) return null; + const text = readFileSync(real, "utf8"); + if (!text.startsWith("#!/bin/sh\n") || text.includes("\r")) return null; + if (STANDALONE_BANNER.test(text) && STANDALONE_EXEC.test(text)) { + const dataDir = parseDataDir(text); + if (!dataDir || !path.isAbsolute(dataDir)) return null; + const appDir = path.join(dataDir, "app"); + if (hasNodeModules(appDir) || hasNodeModules(spelled(appDir))) return null; + return allowed(appDir) ? { kind: "standalone", dir: appDir } : null; + } + const brew = BREW_EXEC.exec(text); + if (brew) { + const dist = path.dirname(brew[1] as string); + const libexec = path.dirname(dist); + return allowed(libexec) && homebrewFormula(dist) && isThere(libexec) ? { kind: "homebrew", dir: libexec } : null; + } + return null; + } catch { + return null; + } +} + +/** Package folder started by a standalone (`install.sh`) or Homebrew launcher script, + * read as a bounded plain file and never executed; null for anything else. */ +export const launcherTarget = (file: string, allowed: (p: string) => boolean = () => true): string | null => + readLauncher(file, allowed)?.dir ?? null; + export function look(o: Looking): Inventory { // One spelling for one folder, for the whole look: the plan compares the paths of an // inventory as they are, so a folder reached by two names (another case on a disk that @@ -319,6 +371,7 @@ export function look(o: Looking): Inventory { if (inReach(dir)) dirs.add(dir); }; const onPath: Inventory["onPath"] = []; + const standaloneLaunchers = new Set(); const dangling: string[] = []; const strangers: Inventory["strangers"] = []; for (const dir of pathDirs) { @@ -343,13 +396,18 @@ export function look(o: Looking): Inventory { continue; } // A link of someone's own to a `…/dist/cli.js`: the folder it starts is known without - // running it (a checkout, a build). Any other file says nothing of what it starts. + // running it (a checkout, a build). Official standalone (`install.sh`) and Homebrew + // launchers are also read (bounded plain files, never executed). Any other file says + // nothing of what it starts. let folder: string | null = null; try { folder = linked ? packageOf(realpathSync(file)) : null; } catch {} - onPath.push({ file, dir: folder && one(folder) }); - if (folder) add(one(folder)); + const hit = folder ? null : readLauncher(file, (p) => inReach(one(p))); + const resolved = folder ? one(folder) : hit ? one(hit.dir) : null; + if (hit?.kind === "standalone" && resolved) standaloneLaunchers.add(resolved); + onPath.push({ file, dir: resolved }); + if (resolved) add(resolved); else strangers.push({ file, why: linked ? "a link to no install of sessionpipe" : "a file npm didn't put there" }); } for (const p of prefixes) { @@ -374,8 +432,9 @@ export function look(o: Looking): Inventory { // --- what typing starts --------------------------------------------------------------- // The first on PATH that starts something: a link to a copy that is gone starts nothing, - // and a shell goes on to the next. - const first = onPath.find((e) => !e.dir || isThere(e.dir)) ?? null; + // and a shell goes on to the next. A standalone launcher file itself is still on disk + // and starts even when its app folder was deleted. + const first = onPath.find((e) => !e.dir || isThere(e.dir) || standaloneLaunchers.has(e.dir)) ?? null; // An entry that is no absolute folder, ahead of it on PATH: what typing starts then // depends on the folder a person is in, and what was read is only what it may be. const firstAt = first @@ -414,22 +473,31 @@ export function look(o: Looking): Inventory { }; if (j.name === "sessionpipe" && typeof j.version === "string" && parseVersion(j.version)) version = j.version; } catch {} - const cli = path.join(dir, "dist", "cli.js"); + const dist = path.join(dir, "dist"); + const cli = path.join(dist, "cli.js"); // Left behind: by its name, or ours with no release to name (the proof takes such a // folder only when it is empty). const aside = ASIDE.test(path.basename(dir)) || (slot !== null && version === null); const prefix = slot === "global" ? prefixOfSlot(dir) : null; const kept = same(prefixOfSlot(dir), volta(o)); + const brew = slot === null ? homebrewFormula(dist) : null; + const hasStandaloneRoot = slot === null && !brew && standaloneRoot(dist) !== null; + const standalone = hasStandaloneRoot || (slot === null && !brew && standaloneLaunchers.has(dir)); + const managed: Managed | null = standalone ? "standalone" : brew ? "homebrew" : null; const bins = binsOf(dir, proving); + const exists = isThere(dir); let whole = false; try { whole = statSync(cli).isFile(); } catch {} - // Whole, and a shell can start it: npm's link leads to the cli.js itself. - const starts = whole && startable(cli); + const launcher = managed ? (onPath.find((e) => e.dir === dir)?.file ?? null) : null; + // Whole, and a shell can start it: npm's link leads to the cli.js itself; standalone + // and Homebrew launchers invoke node on dist/cli.js, so the launcher must be executable. + const starts = whole && (managed ? !launcher || startable(launcher) : startable(cli)); // The one copy that is asked whether it runs: what typing starts, where that is a - // folder the proof accepts and not the copy running now. - const ran = starts && slot && !kept && dir === typed && dir !== mine && o.runs ? { said: o.runs(cli) } : null; + // folder the proof accepts (or a standalone/Homebrew install) and not the copy running now. + const ran = + starts && (slot || managed) && !kept && dir === typed && dir !== mine && o.runs ? { said: o.runs(cli) } : null; return { dir, // An npx cache entry by its own folder (`~/.npm/_npx/` says what it is); what is @@ -437,33 +505,52 @@ export function look(o: Looking): Inventory { where: o.tilde(slot === "npx" ? path.dirname(path.dirname(dir)) : slot === "global" ? prefixOfSlot(dir) : dir), prefix, slot: kept ? null : slot, - not: kept ? "Volta keeps it" : proof.is === "not" ? proof.why : null, + managed, + not: kept + ? "Volta keeps it" + : brew + ? "Homebrew keeps it" + : standalone + ? "installed by the standalone installer" + : proof.is === "not" + ? proof.why + : null, aside, version, wrong: aside ? "left behind by an install that was cut off" - : !whole - ? "its dist/cli.js is missing (an install that was cut off?)" - : !starts - ? "its dist/cli.js is not executable, so a shell can't start it" - : ran && ran.said === null - ? "it doesn't run: `--version` printed nothing" - : ran && ran.said !== version - ? `it says it is ${ran.said}, and its package.json says ${version}` - : // Whole, and nothing can start it: npm's link to it was taken away or written - // over. (An npx cache entry is started by npx, by its path.) - slot === "global" && !bins.length - ? "npm's link to it is gone" - : null, + : standalone && !exists + ? "its app folder is missing" + : !whole + ? "its dist/cli.js is missing (an install that was cut off?)" + : !starts + ? managed + ? "its launcher is not executable, so a shell can't start it" + : "its dist/cli.js is not executable, so a shell can't start it" + : managed && version === null + ? "its package.json names no release of sessionpipe" + : standalone && !hasStandaloneRoot + ? "its .standalone marker is missing" + : ran && ran.said === null + ? "it doesn't run: `--version` printed nothing" + : ran && ran.said !== version + ? `it says it is ${ran.said}, and its package.json says ${version}` + : // Whole, and nothing can start it: npm's link to it was taken away or written + // over. (An npx cache entry is started by npx, by its path.) + slot === "global" && !bins.length + ? "npm's link to it is gone" + : null, bins, uses: [ ...(dir === typed ? (["typed"] as const) : []), ...(dir === serving ? (["service"] as const) : []), ...(dir === mine ? (["this"] as const) : []), ], - onPath: slot === "global" && pathDirs.includes(one(path.join(prefixOfSlot(dir), "bin"))), + onPath: + (slot === "global" && pathDirs.includes(one(path.join(prefixOfSlot(dir), "bin")))) || + (managed !== null && onPath.some((e) => e.dir === dir)), writable: canWrite(path.dirname(dir)), - keeper: kept ? "volta uninstall sessionpipe" : null, + keeper: kept ? "volta uninstall sessionpipe" : brew ? `brew uninstall ${brew}` : null, }; }); // The hooks run files of their own, written by one release: the copy of that release diff --git a/packages/cli/src/reinstall/page.ts b/packages/cli/src/reinstall/page.ts index 384a4b94..2eda705f 100644 --- a/packages/cli/src/reinstall/page.ts +++ b/packages/cli/src/reinstall/page.ts @@ -20,8 +20,8 @@ export const usedBy = (c: Copy): string => .map((u) => USED[u]) .join(", ") || "nothing uses it"; -/** A copy the proof accepts names its release; a folder left behind may not. */ -const version = (c: Copy): string => (c.aside ? "left over" : (c.version as string)); +/** A copy the proof accepts names its release; a folder left behind or broken copy may not. */ +const version = (c: Copy): string => (c.aside ? "left over" : (c.version ?? "broken")); /** A folder set after `first`, and one longer than the line broken after a `/` or `\`, * each further line starting under the folder's first character: a path has no spaces @@ -57,9 +57,16 @@ function wrap(ui: Ui, first: string, body: string): string[] { * release, a reason with a file's name in it) is cleaned of what a terminal acts on * before it is set in a line: it can't start a line of its own or carry a colour. */ export function found(ui: Ui, inv: Inventory, f: Facts, show: (p: string) => string = (p) => p): string[] { - const copies = inv.copies.filter((c) => c.slot); + const copies = inv.copies.filter((c) => c.slot || c.managed); const n = copies.length; - const about = (c: Copy): string => clean([usedBy(c), ...(c.wrong ? [c.wrong] : [])].join(" · ")); + const about = (c: Copy): string => + clean( + [ + usedBy(c), + ...(c.managed ? [c.managed === "standalone" ? "standalone" : "Homebrew"] : []), + ...(c.wrong ? [c.wrong] : []), + ].join(" · "), + ); const sign = (c: Copy): string => mark(ui, c.wrong ? "bad" : "info"); // One line a copy while the folders are short; a folder too long for that (an fnm or // asdf one) gets the line to itself, and the rest goes under it. diff --git a/packages/cli/src/reinstall/plan.ts b/packages/cli/src/reinstall/plan.ts index 4ad9b7ab..1830aa82 100644 --- a/packages/cli/src/reinstall/plan.ts +++ b/packages/cli/src/reinstall/plan.ts @@ -11,7 +11,8 @@ import path from "node:path"; import { isNewer } from "@sessionpipe/core/version"; import { shq } from "../shell.js"; -import type { Copy, Home, Inventory } from "./find.js"; +import { homebrewFormula } from "../update.js"; +import type { Copy, Home, Inventory, Managed } from "./find.js"; /** What was found beside the copies. */ export interface Facts { @@ -85,8 +86,13 @@ export interface Plan { /** The release the one copy is, and where it lives. */ target: string | null; home: Home | null; + /** A managed copy (standalone or Homebrew) that typing starts and this plan keeps in + * place while cleaning up leftover npm copies or refreshing hooks/service. Null when + * `home` (an npm prefix) is the one copy, or when the plan refuses / does nothing. */ + managed: { via: Managed; dir: string; shown: string } | null; /** The home's copy is not installed again: it is whole and the newest, where this user - * may not write. The words of its row. Null: it is installed fresh. */ + * may not write (or a healthy standalone/Homebrew install). The words of its row. Null: + * it is installed fresh. */ stays: string | null; steps: Step[]; /** What keeps a run safe, under the rows: a line each. */ @@ -142,17 +148,22 @@ export function typing(inv: Inventory, show: (p: string) => string = (p) => p): } /** What typing `sessionpipe` starts, where that is something other than a copy npm - * installed: a contributor's checkout, a linked folder, the copy Volta keeps. Nothing is - * wrong with that, and it is not this command's to change: it is said as what is so. */ + * installed: a standalone install, Homebrew's copy, a contributor's checkout, a linked + * folder, the copy Volta keeps. Nothing is wrong with that, and it is not this command's + * to replace: it is said as what is so. */ export function typedAs(inv: Inventory, show: (p: string) => string = (p) => p): string | null { const typed = inv.copies.find((c) => c.dir === inv.typed); if (!inv.typed || typed?.slot === "global") return null; const where = typed?.where ?? show(inv.typed); - return typed?.keeper - ? `Typing \`sessionpipe\` starts the copy Volta keeps, in ${where}.` - : cutOff(inv) - ? `Typing \`sessionpipe\` starts ${where}, which is no whole install of it.` - : `Typing \`sessionpipe\` starts ${where}, which npm did not install (a checkout, a linked folder).`; + return typed?.managed === "standalone" + ? `Typing \`sessionpipe\` starts the standalone install, in ${where}.` + : typed?.managed === "homebrew" + ? `Typing \`sessionpipe\` starts the copy Homebrew keeps, in ${where}.` + : typed?.keeper + ? `Typing \`sessionpipe\` starts the copy Volta keeps, in ${where}.` + : cutOff(inv) + ? `Typing \`sessionpipe\` starts ${where}, which is no whole install of it.` + : `Typing \`sessionpipe\` starts ${where}, which npm did not install (a checkout, a linked folder).`; } /** What is typed is a folder where npm keeps the package, and not provably an install of @@ -175,6 +186,7 @@ export function plan(inv: Inventory, f: Facts, show: (p: string) => string = (p) refuse: null, target: null, home: null, + managed: null, stays: null, steps: [], safety: [], @@ -188,9 +200,11 @@ export function plan(inv: Inventory, f: Facts, show: (p: string) => string = (p) return stop(`${f.apart.said}, so it leaves this computer's copies alone. Nothing was changed`, f.apart.line); const home = inv.home; const ours = inv.copies.filter((c) => c.slot); + const typed = inv.copies.find((c) => c.dir === inv.typed); + const managed = typed?.managed ? typed : null; const left: Left[] = [ ...inv.copies - .filter((c) => !c.slot) + .filter((c) => !c.slot && c.dir !== managed?.dir) .map((c) => ({ where: c.where, path: c.dir, @@ -222,7 +236,6 @@ export function plan(inv: Inventory, f: Facts, show: (p: string) => string = (p) // What can't be known, said beside a computer that is otherwise fine. It is no finding: // a file first on PATH that npm did not make may well be the shim that starts this copy. const own = typedAs(inv, show); - const typed = inv.copies.find((c) => c.dir === inv.typed); const inSlot = cutOff(inv); // What typing starts was not read: taken from how this command was started (a file // first on PATH that npm did not make), or from a PATH with an entry that is no absolute @@ -232,7 +245,7 @@ export function plan(inv: Inventory, f: Facts, show: (p: string) => string = (p) ? `Typing \`sessionpipe\` starts ${show(inv.inferred)}, which is no link of npm's: which copy it starts is not known` : `\`${inv.loose}\` on your PATH is not an absolute folder: what typing \`sessionpipe\` starts depends on where you stand`; const unknown = [ - ...(own ? [own] : []), + ...(own && !managed ? [own] : []), ...(inv.loose !== null ? [`${unread}.`] : []), ...(inv.unsure ? [ @@ -247,7 +260,8 @@ export function plan(inv: Inventory, f: Facts, show: (p: string) => string = (p) const live = ours.filter((c) => !idle(c)); const one = live.length === 1 ? (live[0] as Copy) : null; const known = "version" in f.latest ? f.latest.version : null; - const target = known ?? one?.version ?? null; + const sole = managed ? (live.length === 0 ? managed : null) : one?.slot === "global" ? one : null; + const target = managed ? managed.version : (known ?? one?.version ?? null); const hooksFine = !f.harnesses.length || (f.hooks.version === target && !f.hooks.wrong.length); const serviceFine = idleService || @@ -255,25 +269,21 @@ export function plan(inv: Inventory, f: Facts, show: (p: string) => string = (p) ? f.wanted && f.service.loaded && f.service.nodeOk && - !!one?.uses.includes("service") && + !!(managed ?? one)?.uses.includes("service") && f.daemon?.version === target && !twins(f.service, f.daemon) : !f.daemon || f.daemon.version === target); + const soleCurrent = managed + ? sole?.version !== null && (!known || !isNewer(known, sole?.version as string)) + : sole?.version === target; // (Not where what is typed is a folder in npm's own place that is no install: typing // `sessionpipe` then starts that, whatever whole copy is elsewhere.) - if ( - one?.slot === "global" && - !inSlot && - !one.wrong && - one.version === target && - !inv.dangling.length && - hooksFine && - serviceFine - ) { + if (sole && !inSlot && !sole.wrong && soleCurrent && !inv.dangling.length && hooksFine && serviceFine) { if (!known) unknown.push( - `npm couldn't be asked whether ${one.version} is the newest release: ${(f.latest as { error: string }).error}.`, + `npm couldn't be asked whether ${sole.version} is the newest release: ${(f.latest as { error: string }).error}.`, ); + const newest = known !== null && sole.version === known; return { ...none, target, @@ -294,8 +304,8 @@ export function plan(inv: Inventory, f: Facts, show: (p: string) => string = (p) // "Nothing to repair" wherever nothing was found that is not as it should be: the // same computers `doctor` calls all good. What can't be known is said beside it. nothing: notes.length - ? `One sessionpipe on this computer: ${one.version}${known ? ", the newest release" : ""}.` - : `Nothing to repair: one sessionpipe, ${one.version}${known ? ", the newest release" : ""}.`, + ? `One sessionpipe on this computer: ${sole.version}${newest ? ", the newest release" : ""}.` + : `Nothing to repair: one sessionpipe, ${sole.version}${newest ? ", the newest release" : ""}.`, }; } @@ -303,7 +313,7 @@ export function plan(inv: Inventory, f: Facts, show: (p: string) => string = (p) // installed is here: nothing is this command's to repair, and `doctor` says the same. // (Not where what is typed sits where npm keeps the package: that is what an install // that was cut off left, and it is in the way. Nor with two daemons to sort out.) - if (own && !inSlot && !live.length && !inv.dangling.length && !twins(f.service, f.daemon)) + if (own && !managed && !inSlot && !live.length && !inv.dangling.length && !twins(f.service, f.daemon)) return { ...none, target, @@ -314,112 +324,165 @@ export function plan(inv: Inventory, f: Facts, show: (p: string) => string = (p) }; // --- something to repair: what must hold before anything is touched ---------------------- - if (!known) - return stop( - `npm couldn't be asked for the newest release (${(f.latest as { error: string }).error}), and a fresh copy comes from npm. Nothing was changed`, - "sessionpipe reinstall", - ); - if (!f.npm) - return stop( - "npm is not beside this Node nor on PATH, and a fresh copy comes from npm. Nothing was changed. Install npm, then run this again", - "sessionpipe reinstall", - ); - // What npx fetched to run this is not what this computer runs: a newer runner - // (`npx sessionpipe@next reinstall`) moves nothing back, and goes with the rest. - const ahead = [...live.map((c) => c.version), f.hooks.version, f.daemon?.version ?? null].find( - (v) => v && isNewer(v, known, true), - ); - if (ahead) - return stop( - `sessionpipe ${ahead} is on this computer, newer than npm's newest release (${known}): a reinstall would move it back. Nothing was changed`, - "sessionpipe doctor", - ); - // What typing starts must end up the one clean copy, or nothing is changed. A file first - // on PATH that is no link of npm's (a version manager's shim, a wrapper) starts a copy - // this command can't name unless it was started through it. - if (inv.unsure) - return stop( - `${show(inv.unsure)} is the first \`sessionpipe\` on your PATH and no link of npm's: this command can't tell which copy that file starts, so it can't tell where the one clean copy goes. Nothing was changed. If the file is yours, point it at one copy or take it off your PATH (\`which -a sessionpipe\` shows what your PATH finds), then run this again`, - // No command leads out by itself (installing another copy leads back here): none is named. - "", - ); - /** The line that moves something out of the way, and writes over nothing. Once it has - * run, `sessionpipe` may be nowhere to type: the repair goes on through npx, in the - * same line. */ - const aside = (file: string): string => - `mv -n ${shq(file, "linux")} ${shq(inv.spare[file] ?? `${file}.old`, "linux")} && ${NPX}`; - const ASIDE = "The line moves it aside and runs the repair again, through npx"; - if (inv.typed && typed?.slot !== "global") - return stop( - `${(own as string).slice(0, -1)}${ - typed?.not && !typed.keeper ? `: ${typed.not}` : "" - }. This command leaves it alone, so it can't put one clean copy in its place. Nothing was changed${ - inSlot ? `. ${ASIDE}` : "" - }`, - // A folder where npm keeps the package (what an install that was cut off left, a - // build) is in the way of the one copy, and the person's to move: the line moves it, - // and deletes nothing. For anything else there is nothing of sessionpipe's to run: - // what the person's own PATH finds, in its order. - inSlot ? aside(inv.typed) : "which -a sessionpipe", - ); - if (!home && inv.taken) - return stop( - `${show(inv.taken.dir)} is not provably sessionpipe's (${inv.taken.why}), and it is where the one copy goes. Nothing was changed. ${ASIDE}`, - aside(inv.taken.dir), - ); - if (!home) - return stop( - "no folder on this computer can hold the one copy of sessionpipe. Nothing was changed", - // Not `doctor`, which would name this command: what the PATH finds, in its order. - "which -a sessionpipe", - ); - const at = slotIn(home.prefix); - // npm refuses to put its link over a file it didn't make (EEXIST: it installs nothing), - // and what is not provably ours is never moved by this command. - if (home.blocked) - return stop( - `${show(home.blocked)} is not sessionpipe's, and it is where the fresh copy's link goes: npm won't write over it. Nothing was changed. ${ASIDE}`, - aside(home.blocked), - ); - if (!inv.typed && !home.onPath) - return stop( - `${show(home.bin)} is not on your PATH, so \`sessionpipe\` would not be found when you type it. Nothing was changed. Add it, then run this again`, - `export PATH=${shq(home.bin, "linux")}:"$PATH"`, + let targetVer: string; + let at: string; + let stays: string | null; + let there: Copy | undefined; + let needUse = true; + let managedNote: string | null = null; + if (managed) { + const formula = homebrewFormula(path.join(managed.dir, "dist")) ?? "sessionpipe"; + const label = managed.managed === "standalone" ? "the standalone install" : "the copy Homebrew keeps"; + if (managed.wrong) + return stop( + `${label} in ${managed.where} is not whole (${managed.wrong}). Nothing was changed. ${ + managed.managed === "standalone" ? "Re-run the installer to repair it" : "Reinstall it with Homebrew" + }`, + managed.managed === "standalone" + ? "curl -fsSL https://sessionpipe.org/install.sh | sh" + : `brew reinstall ${formula}`, + ); + const ver = managed.version as string; + const repairWork = live.length > 0 || inv.dangling.length > 0 || !hooksFine || !serviceFine; + const outdated = known !== null && isNewer(known, ver); + if (outdated && !repairWork) + return stop( + `${label} in ${managed.where} is ${ver}, and ${known} is out. Nothing was changed. ${ + managed.managed === "standalone" ? "Update it" : "Upgrade it with Homebrew" + }, then run this again`, + managed.managed === "standalone" + ? "curl -fsSL https://sessionpipe.org/install.sh | sh" + : `brew upgrade ${formula}`, + ); + const ahead = [...live.map((c) => c.version), f.hooks.version, f.daemon?.version ?? null].find( + (v) => v && isNewer(v, ver, true), ); - // A home this user may not write is never answered with a second copy somewhere else. - // Its copy stays where it is whole and the newest; where it is not, the one line that - // updates it in place comes first, and this command finishes the job after it. - // The copy that is there now; a folder left behind in its place is no copy. - const there = ours.find((c) => c.dir === at && !c.aside); - const sound = !!there && !there.wrong && there.version === known; - if (!home.writable && !sound) - return stop( - `${home.shown} ${ - there - ? `holds ${inv.typed ? "the copy you type" : "the copy that is to stay"} (${there.version})` - : `is where \`sessionpipe\` goes (${home.why})` - }, and you may not write there. Nothing was changed. ${there ? "Update" : "Install"} it there, then run this again`, - `sudo npm install -g --prefix ${shq(home.prefix, "linux")} sessionpipe@${known}`, + if (ahead) + return stop( + `sessionpipe ${ahead} is on this computer, newer than ${label} (${ver}): a reinstall would move it back. Nothing was changed`, + "sessionpipe doctor", + ); + if (outdated) + managedNote = `${known} is out: update with \`${ + managed.managed === "standalone" + ? "curl -fsSL https://sessionpipe.org/install.sh | sh" + : `brew upgrade ${formula}` + }\`.`; + targetVer = ver; + at = managed.dir; + stays = `${ver} in ${managed.where} (${managed.managed === "standalone" ? "standalone install" : "Homebrew"})`; + needUse = !hooksFine || !serviceFine; + } else { + if (!known) + return stop( + `npm couldn't be asked for the newest release (${(f.latest as { error: string }).error}), and a fresh copy comes from npm. Nothing was changed`, + "sessionpipe reinstall", + ); + if (!f.npm) + return stop( + "npm is not beside this Node nor on PATH, and a fresh copy comes from npm. Nothing was changed. Install npm, then run this again", + "sessionpipe reinstall", + ); + // What npx fetched to run this is not what this computer runs: a newer runner + // (`npx sessionpipe@next reinstall`) moves nothing back, and goes with the rest. + const ahead = [...live.map((c) => c.version), f.hooks.version, f.daemon?.version ?? null].find( + (v) => v && isNewer(v, known, true), ); - const stays = home.writable ? null : `${known} in ${home.shown} as it is: whole, the newest, and not yours to write`; + if (ahead) + return stop( + `sessionpipe ${ahead} is on this computer, newer than npm's newest release (${known}): a reinstall would move it back. Nothing was changed`, + "sessionpipe doctor", + ); + // What typing starts must end up the one clean copy, or nothing is changed. A file first + // on PATH that is no link of npm's (a version manager's shim, a wrapper) starts a copy + // this command can't name unless it was started through it. + if (inv.unsure) + return stop( + `${show(inv.unsure)} is the first \`sessionpipe\` on your PATH and no link of npm's: this command can't tell which copy that file starts, so it can't tell where the one clean copy goes. Nothing was changed. If the file is yours, point it at one copy or take it off your PATH (\`which -a sessionpipe\` shows what your PATH finds), then run this again`, + // No command leads out by itself (installing another copy leads back here): none is named. + "", + ); + /** The line that moves something out of the way, and writes over nothing. Once it has + * run, `sessionpipe` may be nowhere to type: the repair goes on through npx, in the + * same line. */ + const aside = (file: string): string => + `mv -n ${shq(file, "linux")} ${shq(inv.spare[file] ?? `${file}.old`, "linux")} && ${NPX}`; + const ASIDE = "The line moves it aside and runs the repair again, through npx"; + if (inv.typed && typed?.slot !== "global") + return stop( + `${(own as string).slice(0, -1)}${ + typed?.not && !typed.keeper ? `: ${typed.not}` : "" + }. This command leaves it alone, so it can't put one clean copy in its place. Nothing was changed${ + inSlot ? `. ${ASIDE}` : "" + }`, + // A folder where npm keeps the package (what an install that was cut off left, a + // build) is in the way of the one copy, and the person's to move: the line moves it, + // and deletes nothing. For anything else there is nothing of sessionpipe's to run: + // what the person's own PATH finds, in its order. + inSlot ? aside(inv.typed) : "which -a sessionpipe", + ); + if (!home && inv.taken) + return stop( + `${show(inv.taken.dir)} is not provably sessionpipe's (${inv.taken.why}), and it is where the one copy goes. Nothing was changed. ${ASIDE}`, + aside(inv.taken.dir), + ); + if (!home) + return stop( + "no folder on this computer can hold the one copy of sessionpipe. Nothing was changed", + // Not `doctor`, which would name this command: what the PATH finds, in its order. + "which -a sessionpipe", + ); + at = slotIn(home.prefix); + // npm refuses to put its link over a file it didn't make (EEXIST: it installs nothing), + // and what is not provably ours is never moved by this command. + if (home.blocked) + return stop( + `${show(home.blocked)} is not sessionpipe's, and it is where the fresh copy's link goes: npm won't write over it. Nothing was changed. ${ASIDE}`, + aside(home.blocked), + ); + if (!inv.typed && !home.onPath) + return stop( + `${show(home.bin)} is not on your PATH, so \`sessionpipe\` would not be found when you type it. Nothing was changed. Add it, then run this again`, + `export PATH=${shq(home.bin, "linux")}:"$PATH"`, + ); + // A home this user may not write is never answered with a second copy somewhere else. + // Its copy stays where it is whole and the newest; where it is not, the one line that + // updates it in place comes first, and this command finishes the job after it. + // The copy that is there now; a folder left behind in its place is no copy. + there = ours.find((c) => c.dir === at && !c.aside); + const sound = !!there && !there.wrong && there.version === known; + if (!home.writable && !sound) + return stop( + `${home.shown} ${ + there + ? `holds ${inv.typed ? "the copy you type" : "the copy that is to stay"} (${there.version})` + : `is where \`sessionpipe\` goes (${home.why})` + }, and you may not write there. Nothing was changed. ${there ? "Update" : "Install"} it there, then run this again`, + `sudo npm install -g --prefix ${shq(home.prefix, "linux")} sessionpipe@${known}`, + ); + targetVer = known; + stays = home.writable ? null : `${known} in ${home.shown} as it is: whole, the newest, and not yours to write`; + } // --- the steps, in the order they are taken ------------------------------------------------ const steps: Step[] = []; - if (!stays) + if (!stays) { + const h = home as Home; steps.push( - { do: "fetch", version: known, touches: [] }, + { do: "fetch", version: targetVer, touches: [] }, { do: "install", - version: known, - prefix: home.prefix, + version: targetVer, + prefix: h.prefix, dir: at, replaces: !!there, - touches: [at, path.join(home.bin, "sessionpipe")], + touches: [at, path.join(h.bin, "sessionpipe")], // Why this folder: the table's row for it says what uses the copy that is there; // where none is, the reason is said here. - say: `${known}, the newest release, fresh in ${home.shown} (${there ? `replaces ${there.version}` : home.why})`, + say: `${targetVer}, the newest release, fresh in ${h.shown} (${there ? `replaces ${there.version}` : h.why})`, }, ); + } // Two daemons: the one someone started by hand is stopped, and the service takes over. if (f.daemon && twins(f.service, f.daemon)) steps.push({ @@ -433,19 +496,20 @@ export function plan(inv: Inventory, f: Facts, show: (p: string) => string = (p) ...(f.harnesses.length ? ["the hooks"] : []), ...(serve ? ["the background service"] : f.daemon ? ["the daemon that runs here"] : []), ]; - steps.push({ - do: "use", - serve: serve || !!f.daemon, - touches: [ - ...(f.harnesses.length ? f.hookFiles : []), - ...(serve ? [(f.service as NonNullable).file] : []), - ], - // What moves onto the copy: the hooks where an agent is hooked, and what runs in the - // background where something does. - say: moved.length ? `${moved.join(" and ")} to it` : null, - }); + if (needUse) + steps.push({ + do: "use", + serve: serve || !!f.daemon, + touches: [ + ...(f.harnesses.length ? f.hookFiles : []), + ...(serve ? [(f.service as NonNullable).file] : []), + ], + // What moves onto the copy: the hooks where an agent is hooked, and what runs in the + // background where something does. + say: moved.length ? `${moved.join(" and ")} to it` : null, + }); // The home's own link is written again by the install; any other that leads nowhere goes. - for (const file of inv.dangling.filter((f) => path.dirname(f) !== home.bin)) + for (const file of inv.dangling.filter((f) => path.dirname(f) !== home?.bin)) steps.push({ do: "remove", path: file, @@ -490,17 +554,18 @@ export function plan(inv: Inventory, f: Facts, show: (p: string) => string = (p) steps.push({ do: "prove", touches: [] }); return { ...none, - target: known, + target: targetVer, home, + managed: managed ? { via: managed.managed as Managed, dir: managed.dir, shown: managed.where } : null, stays, steps, // npm installs beside the copy that is there and the fresh one is seen to run before // the two change places: a download or an install that fails has touched nothing. safety: [ - ...(stays ? [] : [`Nothing is touched until ${known} has been downloaded and seen to run.`]), - ...(serve + ...(stays ? [] : [`Nothing is touched until ${targetVer} has been downloaded and seen to run.`]), + ...(needUse && serve ? ["The service keeps its environment and restarts once it holds nothing."] - : f.daemon + : needUse && f.daemon ? ["The daemon restarts once it holds nothing."] : []), ], @@ -513,6 +578,12 @@ export function plan(inv: Inventory, f: Facts, show: (p: string) => string = (p) notes: [ ...notes.filter((n) => n !== astray), ...(taken !== null ? [`${unread}${kept ? ", so no other installed copy is removed" : ""}.`] : []), + ...(managed && !known + ? [ + `npm couldn't be asked whether ${targetVer} is the newest release: ${(f.latest as { error: string }).error}.`, + ] + : []), + ...(managedNote ? [managedNote] : []), ], }; } diff --git a/packages/cli/src/reinstall/run.ts b/packages/cli/src/reinstall/run.ts index 2dc61736..a13dd1df 100644 --- a/packages/cli/src/reinstall/run.ts +++ b/packages/cli/src/reinstall/run.ts @@ -151,7 +151,12 @@ async function fresh(s: Extract, d: Doing): Promise<{ e export async function carryOut(p: Plan, d: Doing): Promise { const target = p.target as string; - const home = (p.home as NonNullable).shown; + const home = (p.home ?? (p.managed as NonNullable)).shown; + const recover = p.managed + ? p.managed.via === "standalone" + ? "curl -fsSL https://sessionpipe.org/install.sh | sh" + : "sessionpipe doctor" + : NPX; const removed: string[] = []; const stayed: { what: string; why: string }[] = []; const warn: string[] = []; @@ -229,7 +234,7 @@ export async function carryOut(p: Plan, d: Doing): Promise { // the home runs through its own link, and typing `sessionpipe` starts it. if (!proven) { const proof = await d.prove([]); - if (proof.runs !== target) return failed(`${unfit(proof)}: no other copy was removed`, NPX); + if (proof.runs !== target) return failed(`${unfit(proof)}: no other copy was removed`, recover); // (Where what typing starts was never read, it is not asked of the proof either.) if (!p.inferred && !proof.typed) return failed(`${untyped(proof)}: no other copy was removed`, "sessionpipe doctor"); @@ -246,7 +251,7 @@ export async function carryOut(p: Plan, d: Doing): Promise { } } else if (!waiting) { const proof = await d.prove(removed); - if (proof.runs !== target) return failed(unfit(proof), NPX); + if (proof.runs !== target) return failed(unfit(proof), recover); d.say({ mark: "ok", text: `the copy in ${home} runs: \`--version\` says ${target}` }); // What a person types is what a shell finds first. What is behind it on PATH is what // was left alone, and starts nothing typed. @@ -301,11 +306,16 @@ export async function carryOut(p: Plan, d: Doing): Promise { .filter(Boolean) .join(" && ") || "sessionpipe reinstall", }; + const tag = p.managed + ? p.managed.via === "standalone" + ? " (standalone install)" + : " (Homebrew)" + : p.stays + ? " (not installed again: it is whole, the newest, and not yours to write)" + : ""; return { state: "one", - said: `${p.kept ? `sessionpipe ${target} is installed in ${home} and in use` : `This computer has one sessionpipe: ${target}, in ${home}`}${ - p.stays ? " (not installed again: it is whole, the newest, and not yours to write)" : "" - }. Pairings and settings are as they were.`, + said: `${p.kept ? `sessionpipe ${target} is installed in ${home} and in use` : `This computer has one sessionpipe: ${target}, in ${home}`}${tag}. Pairings and settings are as they were.`, warn, }; } diff --git a/packages/cli/test/cli-reinstall-agree.test.ts b/packages/cli/test/cli-reinstall-agree.test.ts index 3f17b467..e1b84669 100644 --- a/packages/cli/test/cli-reinstall-agree.test.ts +++ b/packages/cli/test/cli-reinstall-agree.test.ts @@ -698,6 +698,7 @@ describe.skipIf(process.platform === "win32")("doctor and reinstall, of the same where: prefix.replace(home, "~"), prefix, slot: "global", + managed: null, not: null, aside: false, version: NEWEST, @@ -754,6 +755,7 @@ describe.skipIf(process.platform === "win32")("doctor and reinstall, of the same where: "~/.local/lib/node_modules/sessionpipe", prefix: null, slot: null, + managed: null, not: "it has no package.json that can be read (an install that was cut off?)", aside: false, version: null, @@ -770,6 +772,7 @@ describe.skipIf(process.platform === "win32")("doctor and reinstall, of the same where: "~/.nvm/versions/node/v22.1.0", prefix: nvm, slot: "global", + managed: null, not: null, version: NEWEST, bins: [bin(nvm)], @@ -1132,4 +1135,189 @@ describe.skipIf(process.platform === "win32")("doctor and reinstall, at real fol expect(started.filter((s) => /\b(npm|npx|launchctl|systemctl|loginctl)\b/.test(s))).toEqual([]); expect(started.some((s) => s.includes("hook.js"))).toBe(true); }); + + it("standalone & Homebrew installs: doctor and reinstall agree across healthy, leftover npm copies, dangling links, and broken installs", async () => { + const local = path.join(home, ".local"); + const dataDir = path.join(local, "share", "sessionpipe"); + const appDir = path.join(dataDir, "app"); + const binFile = path.join(local, "bin", "sessionpipe"); + const put = (file: string, body: string | object, mode?: number) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, typeof body === "string" ? body : JSON.stringify(body), mode ? { mode } : undefined); + }; + const mkStandalone = (version: string, withCli = true) => { + put(path.join(appDir, "package.json"), { name: "sessionpipe", version }); + put(path.join(appDir, ".standalone"), '{"installer":"curl"}\n'); + if (withCli) put(path.join(appDir, "dist", "cli.js"), "#!/usr/bin/env node\n", 0o755); + put( + binFile, + `#!/bin/sh\n# sessionpipe ${version} launcher, written by https://sessionpipe.org/install.sh\nDATA_DIR='${dataDir}'\nexec node "$DATA_DIR/app/dist/cli.js" "$@"\n`, + 0o755, + ); + }; + const install = (prefix: string, version: string, link = true) => { + const dir = path.join(prefix, "lib", "node_modules", "sessionpipe"); + put(path.join(dir, "package.json"), { name: "sessionpipe", version }); + put(path.join(dir, "dist", "cli.js"), "#!/usr/bin/env node\n", 0o755); + if (link) { + mkdirSync(path.join(prefix, "bin"), { recursive: true }); + symlinkSync( + path.join("..", "lib", "node_modules", "sessionpipe", "dist", "cli.js"), + path.join(prefix, "bin", "sessionpipe"), + ); + } + return dir; + }; + vi.mocked(spawnSync).mockImplementation(((_cmd: string, argv: string[]) => ({ + status: argv.some((a) => a.endsWith("hook.js")) || argv[1] === "--version" ? 0 : 1, + stdout: argv[1] === "--version" ? `${NEWEST}\n` : "", + stderr: "", + })) as never); + + mkStandalone(NEWEST); + const alone = await both(null); + expect(alone.verdict).toBe("✓ All good"); + expect(alone.row).toBe(false); + expect(alone.warnings).toEqual([]); + expect(alone.info).toBe("Typing `sessionpipe` starts the standalone install, in ~/.local/share/sessionpipe/app"); + expect(alone.plan.nothing).toBe(NOTHING); + expect(alone.plan.steps).toEqual([]); + expect(alone.refused).toEqual([]); + + const oldLocal = install(local, "0.18.6", false); + const misha = await both(null); + expect(misha.verdict).toBe("! 1 thing needs attention"); + expect(misha.row).toBe(true); + expect(misha.warnings[0]).toContain("2 copies of sessionpipe are on this computer"); + expect(misha.warnings[0]).not.toContain("not whole"); + const docPage = (await run("doctor")).text; + expect(docPage).toContain(NEWEST); + expect(docPage).toContain("A leftover npm copy of sessionpipe is on this computer beside your standalone install."); + expect(docPage).toContain("sessionpipe reinstall"); + expect(misha.refused).toEqual([]); + expect(misha.plan.managed).toEqual({ via: "standalone", dir: appDir, shown: "~/.local/share/sessionpipe/app" }); + expect(misha.plan.steps.map((s) => s.do)).toEqual(["remove", "prove"]); + + const nvmPrefix = path.join(home, ".nvm", "versions", "node", "v22.1.0"); + const oldNvm = install(nvmPrefix, "0.18.5", true); + const twoLeft = (await run("doctor")).text; + expect(twoLeft).toContain( + "2 leftover npm copies of sessionpipe are on this computer beside your standalone install.", + ); + rmSync(oldLocal, { recursive: true, force: true }); + rmSync(oldNvm, { recursive: true, force: true }); + + const dang = await both(null); + expect(dang.verdict).toBe("! 1 thing needs attention"); + expect(dang.warnings[0]).toContain("a leftover link to a sessionpipe copy that is gone"); + const dangDoc = (await run("doctor")).text; + expect(dangDoc).toContain("A link to a sessionpipe copy that is gone is left on this computer."); + expect(dangDoc).toContain("sessionpipe reinstall"); + rmSync(path.join(nvmPrefix, "bin", "sessionpipe"), { force: true }); + + rmSync(path.join(appDir, "dist", "cli.js")); + const brokenSt = await both(null); + expect(brokenSt.verdict).toBe("! 1 thing needs attention"); + expect(brokenSt.warnings[0]).toContain("the standalone copy of sessionpipe on this computer is not whole"); + expect((await run("doctor")).text).toContain("curl -fsSL https://sessionpipe.org/install.sh | sh"); + expect(brokenSt.refused[0]).toContain("curl -fsSL https://sessionpipe.org/install.sh | sh"); + + const brewRoot = path.join(home, "homebrew"); + const cellar = path.join(brewRoot, "Cellar", "sessionpipe", NEWEST); + const libexec = path.join(cellar, "libexec"); + put(path.join(libexec, "dist", "cli.js"), "#!/usr/bin/env node\n", 0o755); + put( + path.join(cellar, "bin", "sessionpipe"), + `#!/bin/sh\nexec "${brewRoot}/opt/node/bin/node" "${cellar}/libexec/dist/cli.js" "$@"\n`, + 0o755, + ); + mkdirSync(path.join(brewRoot, "bin"), { recursive: true }); + symlinkSync(path.join(cellar, "bin", "sessionpipe"), path.join(brewRoot, "bin", "sessionpipe")); + vi.stubEnv("PATH", path.join(brewRoot, "bin")); + const brokenBrew = await both(null); + expect(brokenBrew.verdict).toBe("! 1 thing needs attention"); + expect(brokenBrew.warnings[0]).toContain("the Homebrew copy of sessionpipe on this computer is not whole"); + expect(brokenBrew.warnings[0]).toContain("`brew reinstall sessionpipe` repairs it"); + expect((await run("doctor")).text).toContain("brew reinstall sessionpipe"); + expect(brokenBrew.refused[0]).toContain("brew reinstall sessionpipe"); + + // Healthy Homebrew + leftover npm copy -> doctor names Homebrew install + reinstall + put(path.join(libexec, "package.json"), { name: "sessionpipe", version: NEWEST }); + install(local, "0.18.6", false); + const brewDoc = (await run("doctor")).text; + expect(brewDoc).toContain("beside your Homebrew install"); + expect(brewDoc).toContain("Homebrew; you type this"); + + // Outdated Homebrew (1.9.0, latest 2.0.0) + leftover npm 0.18.6 -> doctor says reinstall, reinstall agrees and cleans up with update note + put(path.join(libexec, "package.json"), { name: "sessionpipe", version: "1.9.0" }); + vi.mocked(spawnSync).mockImplementation(((_cmd: string, argv: string[]) => ({ + status: argv.some((a) => a.endsWith("hook.js")) || argv[1] === "--version" ? 0 : 1, + stdout: argv[1] === "--version" ? "1.9.0\n" : "", + stderr: "", + })) as never); + const outdatedBrew = await both(null); + expect(outdatedBrew.verdict).toBe("! 1 thing needs attention"); + expect((await run("doctor")).text).toContain("sessionpipe reinstall"); + expect(outdatedBrew.refused).toEqual([]); + expect(outdatedBrew.plan.steps.map((s) => s.do)).toEqual(["remove", "prove"]); + expect(outdatedBrew.plan.notes).toContain(`${NEWEST} is out: update with \`brew upgrade sessionpipe\`.`); + + // Outdated standalone (1.9.0, latest 2.0.0) + leftover npm 0.18.6 -> doctor and reinstall agree + mkStandalone("1.9.0"); + vi.stubEnv("PATH", path.join(local, "bin")); + const outdatedSt = await both(null); + expect(outdatedSt.verdict).toBe("! 1 thing needs attention"); + expect((await run("doctor")).text).toContain("sessionpipe reinstall"); + expect(outdatedSt.refused).toEqual([]); + expect(outdatedSt.plan.steps.map((s) => s.do)).toEqual(["remove", "prove"]); + expect(outdatedSt.plan.notes).toContain( + `${NEWEST} is out: update with \`curl -fsSL https://sessionpipe.org/install.sh | sh\`.`, + ); + + // Deleted standalone app/ directory beside leftover npm 0.18.6 -> both point to install.sh, never `mv` + rmSync(appDir, { recursive: true, force: true }); + const deletedApp = await both(null); + expect(deletedApp.verdict).toBe("! 1 thing needs attention"); + expect((await run("doctor")).text).toContain("curl -fsSL https://sessionpipe.org/install.sh | sh"); + expect(deletedApp.refused[0]).toContain("its app folder is missing"); + expect(deletedApp.refused[0]).toContain("curl -fsSL https://sessionpipe.org/install.sh | sh"); + expect(deletedApp.refused[0]).not.toContain("mv -n"); + + // Synthetic managed Homebrew with non-Cellar path (tests formula fallback in doctor) + const fakeBrewInv: Inventory = { + reach: true, + copies: [ + { + dir: "/custom/libexec", + where: "/custom/libexec", + prefix: null, + slot: null, + managed: "homebrew", + not: "Homebrew keeps it", + aside: false, + version: null, + wrong: "its dist/cli.js is missing", + bins: [], + uses: ["typed"], + onPath: true, + writable: true, + keeper: "brew uninstall sessionpipe", + }, + ], + dangling: [], + strangers: [], + onPath: [{ file: "/custom/bin/sessionpipe", dir: "/custom/libexec" }], + typed: "/custom/libexec", + unsure: null, + inferred: null, + loose: null, + spare: {}, + home: null, + taken: null, + prefixes: [], + npx: path.join(home, ".npm", "_npx"), + }; + const fakeBrew = await both(fakeBrewInv); + expect(fakeBrew.warnings[0]).toContain("`brew reinstall sessionpipe` repairs it"); + }); }); diff --git a/packages/cli/test/cli-reinstall.test.ts b/packages/cli/test/cli-reinstall.test.ts index 73f13b60..c8d1206e 100644 --- a/packages/cli/test/cli-reinstall.test.ts +++ b/packages/cli/test/cli-reinstall.test.ts @@ -267,6 +267,7 @@ const copy = (prefix: string, o: Partial = {}): Copy => ({ where: shown(prefix), prefix, slot: "global", + managed: null, not: null, aside: false, version: NEWEST, @@ -4957,4 +4958,57 @@ describe.skipIf(process.platform === "win32")("sessionpipe reinstall on real fol expect(versionOf(slotOf(LOCAL()))).toBe(NEWEST); expect(beside(LOCAL())).toEqual(["sessionpipe"]); }); + + it("Misha's exact bug on disk: standalone install in ~/.local/bin + leftover npm 0.18.6 in ~/.local removes the npm copy, keeps the standalone install, and proves it runs", async () => { + const w = onDisk(); + installed(LOCAL(), "0.18.6"); + rmSync(binOf(LOCAL())); + const dataDir = path.join(LOCAL(), "share", "sessionpipe"); + const appDir = path.join(dataDir, "app"); + put(path.join(appDir, "package.json"), { name: "sessionpipe", version: NEWEST }); + put(path.join(appDir, ".standalone"), '{"installer":"curl"}\n'); + put(path.join(appDir, "dist", "cli.js"), "#!/usr/bin/env node\n"); + const launcherBody = `#!/bin/sh\n# sessionpipe ${NEWEST} launcher, written by https://sessionpipe.org/install.sh\nDATA_DIR='${dataDir}'\nexec node "$DATA_DIR/app/dist/cli.js" "$@"\n`; + put(binOf(LOCAL()), launcherBody); + chmodSync(binOf(LOCAL()), 0o755); + onPath(path.join(LOCAL(), "bin")); + + // Run reinstall --yes: keeps standalone, removes leftover npm 0.18.6, never calls npmDo/installInto! + const r = await w.run({}, "reinstall", "--yes"); + expect(r.err).not.toHaveBeenCalled(); + expect(r.exit).not.toHaveBeenCalled(); + expect(w.m.npmDo).not.toHaveBeenCalled(); + expect(w.m.installInto).not.toHaveBeenCalled(); + expect(r.text).toContain(`= keep ${NEWEST} in ~/.local/share/sessionpipe/app (standalone install)`); + expect(r.text).toContain("- remove 0.18.6 in ~/.local"); + expect(r.text).toContain( + `This computer has one sessionpipe: ${NEWEST}, in ~/.local/share/sessionpipe/app (standalone install)`, + ); + expect(existsSync(slotOf(LOCAL()))).toBe(false); + expect(existsSync(appDir)).toBe(true); + expect(existsSync(binOf(LOCAL()))).toBe(true); + + // Running again reports Nothing to repair! + const again = await w.run({}, "reinstall", "--dry-run"); + expect(again.err).not.toHaveBeenCalled(); + expect(again.text).toContain(`Nothing to repair: one sessionpipe, ${NEWEST}, the newest release.`); + + // If the standalone launcher disappears before prove(), prove reports runs: null and refuses without removing anything + rmSync(binOf(LOCAL())); + installed(LOCAL(), "0.18.6"); + rmSync(binOf(LOCAL())); + put(binOf(LOCAL()), launcherBody); + chmodSync(binOf(LOCAL()), 0o755); + const prevSpawn = w.m.spawnSync.getMockImplementation(); + vi.mocked(w.m.spawnSync).mockImplementationOnce((() => { + rmSync(binOf(LOCAL()), { force: true }); + return { status: 0, stdout: `${NEWEST}\n`, stderr: "" }; + }) as never); + const broken = await w.run({}, "reinstall", "--yes"); + expect(broken.err).toHaveBeenCalledWith( + expect.stringContaining("Next: curl -fsSL https://sessionpipe.org/install.sh | sh"), + ); + expect(existsSync(slotOf(LOCAL()))).toBe(true); + if (prevSpawn) w.m.spawnSync.mockImplementation(prevSpawn); + }); }); diff --git a/packages/cli/test/helpers/reinstall-worlds.ts b/packages/cli/test/helpers/reinstall-worlds.ts index 34f7f5f6..a6ff4b97 100644 --- a/packages/cli/test/helpers/reinstall-worlds.ts +++ b/packages/cli/test/helpers/reinstall-worlds.ts @@ -429,6 +429,7 @@ function seen(m: Model): Inventory { ), prefix: f.prefix, slot: f.kept ? null : f.slot, + managed: null, not: f.kept ? "Volta keeps it" : f.not, aside, version: f.version, diff --git a/packages/cli/test/reinstall-find.test.ts b/packages/cli/test/reinstall-find.test.ts index 4cd04ba2..09fcb803 100644 --- a/packages/cli/test/reinstall-find.test.ts +++ b/packages/cli/test/reinstall-find.test.ts @@ -38,6 +38,7 @@ import { type Home, type Inventory, type Looking, + launcherTarget, look, prefixesOf, spelled, @@ -217,6 +218,7 @@ const row = (prefix: string, o: Partial = {}): Copy => ({ where: tilde(prefix), prefix, slot: "global", + managed: null, not: null, aside: false, version: "0.15.0", @@ -239,6 +241,7 @@ const stray = (dir: string, o: Partial = {}): Copy => ({ where: tilde(dir), prefix: null, slot: null, + managed: null, not: NO_SLOT, aside: false, version: "0.15.0", @@ -291,6 +294,7 @@ const cachedRow = (e: { entry: string; bin: string; dir: string }, o: Partial [c.version, c.slot])).toEqual(Object.values(written).map((v) => [v, "global"])); }); }); + +describe.skipIf(win32)("standalone (`install.sh`) and Homebrew launchers", () => { + const standaloneApp = (dataDir: string, version = "0.21.0", o: { cli?: boolean; marker?: boolean } = {}): string => { + const appDir = path.join(dataDir, "app"); + pkg(appDir, { version, cli: o.cli ?? true }); + if (o.marker !== false) writeFileSync(path.join(appDir, ".standalone"), '{"installer":"curl"}\n'); + return appDir; + }; + const writeStandaloneLauncher = (file: string, dataDir: string, version = "0.21.0", quoted = true): void => { + mkdirSync(path.dirname(file), { recursive: true }); + const rhs = quoted ? `'${dataDir.replaceAll("'", "'\\''")}'` : dataDir; + writeFileSync( + file, + `#!/bin/sh\n# sessionpipe ${version} launcher, written by https://sessionpipe.org/install.sh\nDATA_DIR=${rhs}\nexec node "$DATA_DIR/app/dist/cli.js" "$@"\n`, + { mode: 0o755 }, + ); + }; + const homebrewInstall = ( + brewRoot: string, + formula = "sessionpipe", + version = "0.21.0", + o: { cli?: boolean; pkg?: boolean } = {}, + ) => { + const cellar = path.join(brewRoot, "Cellar", formula, version); + const libexec = path.join(cellar, "libexec"); + if (o.pkg === false) { + mkdirSync(path.join(libexec, "dist"), { recursive: true }); + if (o.cli !== false) + writeFileSync(path.join(libexec, "dist", "cli.js"), "#!/usr/bin/env node\n", { mode: 0o755 }); + } else { + pkg(libexec, { version, cli: o.cli ?? true }); + } + mkdirSync(path.join(brewRoot, "opt"), { recursive: true }); + const optFormula = path.join(brewRoot, "opt", formula); + symlinkSync(cellar, optFormula); + const cellarBin = path.join(cellar, "bin", "sessionpipe"); + mkdirSync(path.dirname(cellarBin), { recursive: true }); + writeFileSync( + cellarBin, + `#!/bin/sh\nexec "${brewRoot}/opt/node/bin/node" "${optFormula}/libexec/dist/cli.js" "$@"\n`, + { mode: 0o755 }, + ); + const binFile = path.join(brewRoot, "bin", "sessionpipe"); + mkdirSync(path.dirname(binFile), { recursive: true }); + symlinkSync(cellarBin, binFile); + return { cellar, libexec, optFormula, cellarBin, binFile }; + }; + + it("launcherTarget parses valid standalone and Homebrew launchers and rejects unsafe, oversized, or malformed files", () => { + // POSIX single-quoted with escaped apostrophe + const oddData = path.join(home, "o'neil", "data"); + const oddApp = standaloneApp(oddData); + const oddBin = path.join(home, "bin-odd", "sessionpipe"); + writeStandaloneLauncher(oddBin, oddData, "0.21.0", true); + expect(launcherTarget(oddBin)).toBe(oddApp); + + // Unquoted DATA_DIR + const plainData = path.join(home, "plain-data"); + const plainApp = standaloneApp(plainData); + const plainBin = path.join(home, "bin-plain", "sessionpipe"); + writeStandaloneLauncher(plainBin, plainData, "0.21.0", false); + expect(launcherTarget(plainBin)).toBe(plainApp); + + // Rejected shapes: missing DATA_DIR, unterminated single quote, unquoted with spaces, + // relative DATA_DIR, missing .standalone, non-sh, >4KiB, directory, nonexistent, outside reach + const badDir = path.join(home, "bad-launchers"); + mkdirSync(badDir, { recursive: true }); + const put = (name: string, body: string) => { + const f = path.join(badDir, name); + writeFileSync(f, body, { mode: 0o755 }); + return f; + }; + const banner = "#!/bin/sh\n# sessionpipe 0.21.0 launcher, written by https://sessionpipe.org/install.sh\n"; + const execLine = 'exec "$n" "$DATA_DIR/app/dist/cli.js" "$@"\n'; + expect(launcherTarget(put("no-data", `${banner}${execLine}`))).toBeNull(); + expect(launcherTarget(put("no-exec", `${banner}DATA_DIR='${plainData}'\n`))).toBeNull(); + expect(launcherTarget(put("bad-quote", `${banner}DATA_DIR='/unclosed\n${execLine}`))).toBeNull(); + expect(launcherTarget(put("spaces", `${banner}DATA_DIR=/a/b c\n${execLine}`))).toBeNull(); + expect(launcherTarget(put("cmd-sub", `${banner}DATA_DIR=/a/$(id)\n${execLine}`))).toBeNull(); + expect(launcherTarget(put("double-quote", `${banner}DATA_DIR="/a/$(id)"\n${execLine}`))).toBeNull(); + expect(launcherTarget(put("backtick", `${banner}DATA_DIR=/a/\`id\`\n${execLine}`))).toBeNull(); + expect( + launcherTarget( + put( + "crlf", + `#!/bin/sh\r\n# sessionpipe 0.21.0 launcher, written by https://sessionpipe.org/install.sh\r\nDATA_DIR='${plainData}'\r\n${execLine}`, + ), + ), + ).toBeNull(); + expect(launcherTarget(put("crlf-body", `${banner}DATA_DIR='${plainData}'\r\n${execLine}`))).toBeNull(); + expect(launcherTarget(put("relative", `${banner}DATA_DIR=relative/dir\n${execLine}`))).toBeNull(); + const nmData = path.join(home, "proj", "node_modules", "sessionpipe"); + expect(launcherTarget(put("node-modules", `${banner}DATA_DIR='${nmData}'\n${execLine}`))).toBeNull(); + mkdirSync(nmData, { recursive: true }); + const nmLink = path.join(home, "alias-nm"); + symlinkSync(nmData, nmLink); + expect(launcherTarget(put("node-modules-link", `${banner}DATA_DIR='${nmLink}'\n${execLine}`))).toBeNull(); + // Authentic launcher whose app/ folder was deleted or lacks .standalone still resolves so doctor/reinstall report it broken + const missingData = path.join(home, "deleted-data"); + expect(launcherTarget(put("deleted-app", `${banner}DATA_DIR='${missingData}'\n${execLine}`))).toBe( + path.join(missingData, "app"), + ); + expect(launcherTarget(put("non-sh", "#!/usr/bin/env bash\necho hi\n"))).toBeNull(); + expect( + launcherTarget(put("huge", `${banner}DATA_DIR='${plainData}'\n${execLine}#${"x".repeat(5000)}\n`)), + ).toBeNull(); + expect(launcherTarget(put("other-sh", '#!/bin/sh\nexec /usr/bin/node /tmp/other.js "$@"\n'))).toBeNull(); + expect(launcherTarget(badDir)).toBeNull(); + expect(launcherTarget(path.join(badDir, "missing"))).toBeNull(); + expect(launcherTarget(plainBin, () => false)).toBeNull(); + expect(launcherTarget(plainBin, (p) => p === plainBin)).toBeNull(); + + // Homebrew launcher (opt symlink + missing libexec + outside reach) + const brewRoot = path.join(home, "homebrew"); + const brew = homebrewInstall(brewRoot, "sessionpipe@0.21", "0.21.0"); + expect(launcherTarget(brew.binFile)).toBe(path.join(brew.optFormula, "libexec")); + expect(launcherTarget(brew.binFile, (p) => p === brew.cellarBin)).toBeNull(); + const badBrew = put( + "bad-brew", + `#!/bin/sh\nexec "/opt/homebrew/opt/node/bin/node" "${brewRoot}/opt/sessionpipe/libexec/dist/cli.js" "$@"\n`, + ); + expect(launcherTarget(badBrew)).toBeNull(); + }); + + it("recognizes standalone launcher in ~/.local/bin beside a leftover npm copy in ~/.local without flagging it as a stranger or inWay", () => { + const local = path.join(home, ".local"); + // Old npm 0.18.6 install in ~/.local whose symlink was replaced by install.sh + pkg(slot(local), { version: "0.18.6" }); + const dataDir = path.join(local, "share", "sessionpipe"); + const appDir = standaloneApp(dataDir, "0.21.0"); + const binFile = path.join(local, "bin", "sessionpipe"); + writeStandaloneLauncher(binFile, dataDir, "0.21.0"); + + const { asked, runs } = runner({ [path.join(appDir, "dist", "cli.js")]: "0.21.0" }); + const inv = look(looking({ env: { PATH: path.join(local, "bin") }, runs })); + expect(inv.strangers).toEqual([]); + expect(inv.typed).toBe(appDir); + expect(inv.unsure).toBeNull(); + expect(inv.home).toBeNull(); + expect(inv.onPath).toEqual([{ file: binFile, dir: appDir }]); + expect(asked).toEqual([path.join(appDir, "dist", "cli.js")]); + const st = inv.copies.find((c) => c.dir === appDir); + expect(st).toMatchObject({ + slot: null, + managed: "standalone", + not: "installed by the standalone installer", + keeper: null, + version: "0.21.0", + wrong: null, + uses: ["typed"], + onPath: true, + }); + const old = inv.copies.find((c) => c.dir === slot(local)); + expect(old).toMatchObject({ + slot: "global", + managed: null, + version: "0.18.6", + wrong: "npm's link to it is gone", + uses: [], + }); + }); + + it("detects broken standalone installs (missing dist/cli.js, non-executable launcher, and standalone run off PATH)", () => { + const local = path.join(home, ".local"); + const dataDir = path.join(local, "share", "sessionpipe"); + const appDir = standaloneApp(dataDir, "0.21.0", { cli: false }); + const binFile = path.join(local, "bin", "sessionpipe"); + writeStandaloneLauncher(binFile, dataDir, "0.21.0"); + const missingCli = look(looking({ env: { PATH: path.join(local, "bin") } })); + expect(missingCli.copies.find((c) => c.dir === appDir)?.wrong).toBe( + "its dist/cli.js is missing (an install that was cut off?)", + ); + + // Non-executable launcher with non-executable cli.js + mkdirSync(path.join(appDir, "dist"), { recursive: true }); + writeFileSync(path.join(appDir, "dist", "cli.js"), "#!/usr/bin/env node\n", { mode: 0o644 }); + chmodSync(binFile, 0o644); + const noExec = look(looking({ env: { PATH: path.join(local, "bin") } })); + expect(noExec.copies.find((c) => c.dir === appDir)?.wrong).toBe( + "its launcher is not executable, so a shell can't start it", + ); + + // Executable launcher with non-executable cli.js is healthy (launcher invokes node on cli.js) + chmodSync(binFile, 0o755); + const okExec = look(looking({ env: { PATH: path.join(local, "bin") } })); + expect(okExec.copies.find((c) => c.dir === appDir)?.wrong).toBeNull(); + + // Standalone discovered as `mine` when not on PATH + const offPath = look(looking({ env: { PATH: "" }, distDir: path.join(appDir, "dist") })); + expect(offPath.copies.find((c) => c.dir === appDir)).toMatchObject({ + managed: "standalone", + wrong: null, + onPath: false, + uses: ["this"], + }); + + // Missing .standalone marker while app/package.json and dist/cli.js exist + rmSync(path.join(appDir, ".standalone")); + const noMarker = look(looking({ env: { PATH: path.join(local, "bin") } })); + expect(noMarker.strangers).toEqual([]); + expect(noMarker.typed).toBe(appDir); + expect(noMarker.copies.find((c) => c.dir === appDir)).toMatchObject({ + managed: "standalone", + version: "0.21.0", + wrong: "its .standalone marker is missing", + }); + + // Missing package.json inside standalone app/ + rmSync(path.join(appDir, "package.json")); + const noPkg = look(looking({ env: { PATH: path.join(local, "bin") } })); + expect(noPkg.copies.find((c) => c.dir === appDir)).toMatchObject({ + managed: "standalone", + version: null, + wrong: "its package.json names no release of sessionpipe", + }); + + // Deleted standalone app/ folder beside a leftover npm copy in ~/.local: never treated as stranger or inWay + pkg(slot(local), { version: "0.18.6" }); + rmSync(appDir, { recursive: true, force: true }); + const goneApp = look(looking({ env: { PATH: path.join(local, "bin") } })); + expect(goneApp.strangers).toEqual([]); + expect(goneApp.typed).toBe(appDir); + expect(goneApp.home).toBeNull(); + expect(goneApp.copies.find((c) => c.dir === appDir)).toMatchObject({ + managed: "standalone", + version: null, + wrong: "its app folder is missing", + uses: ["typed"], + }); + }); + + it("recognizes Homebrew launcher and Cellar copy (healthy and broken without package.json)", () => { + const brewRoot = path.join(home, "homebrew"); + const brew = homebrewInstall(brewRoot, "sessionpipe", "0.21.0"); + const inv = look(looking({ env: { PATH: path.join(brewRoot, "bin") } })); + expect(inv.strangers).toEqual([]); + expect(inv.typed).toBe(brew.libexec); + expect(inv.home).toBeNull(); + expect(inv.copies.find((c) => c.dir === brew.libexec)).toMatchObject({ + slot: null, + managed: "homebrew", + not: "Homebrew keeps it", + keeper: "brew uninstall sessionpipe", + version: "0.21.0", + wrong: null, + uses: ["typed"], + onPath: true, + }); + + // Broken Homebrew copy with missing package.json + const brokenRoot = path.join(home, "homebrew-broken"); + const broken = homebrewInstall(brokenRoot, "sessionpipe", "0.21.0", { pkg: false }); + const invBroken = look(looking({ env: { PATH: path.join(brokenRoot, "bin") } })); + expect(invBroken.typed).toBe(broken.libexec); + expect(invBroken.copies.find((c) => c.dir === broken.libexec)).toMatchObject({ + managed: "homebrew", + version: null, + wrong: "its package.json names no release of sessionpipe", + }); + }); +}); diff --git a/packages/cli/test/reinstall-ours.test.ts b/packages/cli/test/reinstall-ours.test.ts index 4423ea62..193de13f 100644 --- a/packages/cli/test/reinstall-ours.test.ts +++ b/packages/cli/test/reinstall-ours.test.ts @@ -2124,8 +2124,8 @@ describe("the guard: one file deletes, in one function, and nothing is npm's or /** The line plan.ts prints for a person to paste where they may not write: it is shown, * never run (plan.ts runs nothing: see `inModule`). */ const SUDO_LINE = q('line: `sudo rm -r @{[c.dir, ...c.bins].map((x) => shq(x, "linux")).join(" ")}`,'); - /** Volta's own command for its own copy, shown to a person the same way. */ - const VOLTA_LINE = 'keeper: kept ? "volta uninstall sessionpipe" : null,'; + /** Volta's and Homebrew's own commands for their own copies, shown to a person the same way. */ + const VOLTA_LINE = 'keeper: kept ? "volta uninstall sessionpipe" : brew ? `brew uninstall ${brew}` : null,'; /** A bracket after a name or a closing bracket: a member by a computed name, an item of * a list, an array type; and what is between the brackets. */ @@ -2415,7 +2415,7 @@ describe("the guard: one file deletes, in one function, and nothing is npm's or // The two lines that are only shown are there, once each, as this guard knows them. expect(code(source("find.ts")).split(VOLTA_LINE)).toHaveLength(2); expect(code(source("plan.ts")).split(SUDO_LINE)).toHaveLength(2); - expect(source("find.ts").match(/uninstall/gi)).toHaveLength(1); + expect(source("find.ts").match(/uninstall/gi)).toHaveLength(2); // The comments say why npm is not asked; the code never names its uninstall. for (const name of files) expect(code(source(name)), name).not.toMatch(/npm uninstall|"uninstall"/); }, 60_000); @@ -2718,7 +2718,9 @@ describe("the guard: one file deletes, in one function, and nothing is npm's or "install: async (stage, v) => {\n made.push(stage);\n const r = await installInto(stage, v, {", ); expect(code(body).match(/\bmade\b/g)).toHaveLength(3); - expect(body).toContain("const home = (p.home as NonNullable).prefix;\n const slot = slotIn(home);"); + expect(body).toContain( + "const home = p.home?.prefix ?? null;\n const slot = home ? slotIn(home) : (p.managed as NonNullable).dir;", + ); expect(body.match(/\bproving\b/g)).toHaveLength(2); // What it writes with node:fs: the renames of the swap, and one link, npm's own, made // (with the folder it goes in) where it is not there. Nothing else, by any name. diff --git a/packages/cli/test/reinstall-page.test.ts b/packages/cli/test/reinstall-page.test.ts index 4e5ebc27..f3d13415 100644 --- a/packages/cli/test/reinstall-page.test.ts +++ b/packages/cli/test/reinstall-page.test.ts @@ -34,6 +34,7 @@ const copy = (where: string, over: Partial = {}): Copy => { where, prefix, slot: "global", + managed: null, not: null, aside: false, version: "1.2.0", @@ -110,6 +111,7 @@ const aPlan = (over: Partial = {}): Plan => ({ refuse: null, target: "1.2.0", home: null, + managed: null, stays: null, steps: [FETCH, PROVE], safety: [SAFE], @@ -1822,3 +1824,46 @@ describe("the screen of a home this user may not write, from the plan itself", ( } }); }); + +describe("standalone and Homebrew copies on the found screen", () => { + it("lists standalone, Homebrew, and broken Homebrew copies alongside npm copies", () => { + const standalone = copy("~/.local/share/sessionpipe/app", { + dir: folder("~/.local/share/sessionpipe/app"), + prefix: null, + slot: null, + managed: "standalone", + not: "installed by the standalone installer", + version: "0.21.0", + uses: ["typed"], + }); + const brew = copy("/opt/homebrew/Cellar/sessionpipe/0.21.0/libexec", { + dir: "/opt/homebrew/Cellar/sessionpipe/0.21.0/libexec", + prefix: null, + slot: null, + managed: "homebrew", + not: "Homebrew keeps it", + keeper: "brew uninstall sessionpipe", + version: "0.21.0", + uses: [], + }); + const brokenBrew = copy("/opt/homebrew/Cellar/sessionpipe/0.20.0/libexec", { + dir: "/opt/homebrew/Cellar/sessionpipe/0.20.0/libexec", + prefix: null, + slot: null, + managed: "homebrew", + not: "Homebrew keeps it", + keeper: "brew uninstall sessionpipe", + version: null, + wrong: "its package.json names no release of sessionpipe", + uses: [], + }); + const npmOld = copy("~/.local", { version: "0.18.6", wrong: "npm's link to it is gone" }); + const lines = found(PLAIN, inv([standalone, brew, brokenBrew, npmOld]), facts()); + expect(lines.join("\n")).toContain("0.21.0 · you type this · standalone"); + expect(lines.join("\n")).toContain("0.21.0 · nothing uses it · Homebrew"); + expect(lines.join("\n")).toContain( + "broken · nothing uses it · Homebrew · its package.json names no release of sessionpipe", + ); + expect(lines.join("\n")).toContain("0.18.6 · nothing uses it · npm's link to it is gone"); + }); +}); diff --git a/packages/cli/test/reinstall-plan.test.ts b/packages/cli/test/reinstall-plan.test.ts index b80a98a9..011177ff 100644 --- a/packages/cli/test/reinstall-plan.test.ts +++ b/packages/cli/test/reinstall-plan.test.ts @@ -62,11 +62,15 @@ function broken(p: Plan): string[] { const fresh = p.steps.filter((s) => s.do === "fetch" || s.do === "install").map((s) => s.do); if (p.steps.length && fresh.join() !== (p.stays === null ? "fetch,install" : "")) no.push(`it ${p.stays === null ? "installs" : "keeps the copy"}, and downloads and installs: ${fresh.join()}`); - if (p.stays !== null && p.home?.writable !== false) no.push("a copy stays that could be installed again"); + if (p.stays !== null && !p.managed && p.home?.writable !== false) + no.push("a copy stays that could be installed again"); const first = `Nothing is touched until ${p.target} has been downloaded and seen to run.`; if (p.safety.filter((s) => s.startsWith("Nothing is touched")).join() !== (fresh.length ? first : "")) no.push(`its safety line is ${JSON.stringify(p.safety)}`); - const said = JSON.stringify({ ...p, left: p.left.map((l) => (l.line === KEEPER ? { ...l, line: null } : l)) }); + const said = JSON.stringify({ + ...p, + left: p.left.map((l) => (l.line === KEEPER || l.line?.startsWith("brew uninstall ") ? { ...l, line: null } : l)), + }); if (/uninstall/i.test(said)) no.push("it names an uninstall"); return no; } @@ -105,6 +109,7 @@ const copy = (prefix: string, over: Partial = {}): Copy => ({ where: prefix, prefix, slot: "global", + managed: null, not: null, aside: false, version: NEW, @@ -226,6 +231,7 @@ const REFUSED = { nothing: null, target: null, home: null, + managed: null, stays: null, steps: [], safety: [], @@ -309,6 +315,7 @@ describe("nothing to repair", () => { refuse: null, target: NEW, home: home(), + managed: null, stays: null, steps: [], safety: [], @@ -608,6 +615,7 @@ describe("nothing to repair", () => { refuse: null, target: NEW, home: home(), + managed: null, stays: null, steps: [], safety: [], @@ -1062,6 +1070,7 @@ describe("M3: the one copy stays where it is typed, whoever may write there", () refuse: null, target: NEW, home: sysHome(), + managed: null, stays: null, steps: [], safety: [], @@ -1164,6 +1173,7 @@ describe("M3: the one copy stays where it is typed, whoever may write there", () refuse: null, target: NEW, home: sysHome(), + managed: null, stays: "1.2.0 in /usr/local as it is: whole, the newest, and not yours to write", steps: [ { do: "use", serve: true, touches: [...HOOKS, FILE], say: SERVED }, @@ -1748,6 +1758,7 @@ describe("the steps, in the order they are taken", () => { refuse: null, target: NEW, home: home(), + managed: null, stays: null, steps: [ FETCH, @@ -3919,7 +3930,7 @@ describe("over computers made up from a seed (helpers/reinstall-worlds.ts): what lines++; } else if (l.line !== null) { // The one other line a row may have: someone else's tool, for its own copy. - expect(l.line).toBe(KEEPER); + expect(l.line).toMatch(/^(?:volta|brew) uninstall sessionpipe(?:@\S+)?$/); kept++; } } @@ -3934,3 +3945,324 @@ describe("over computers made up from a seed (helpers/reinstall-worlds.ts): what expect(kept).toBeGreaterThan(20); }); }); + +describe("standalone (`install.sh`) and Homebrew installs", () => { + const APP = "/w/home/.local/share/sessionpipe/app"; + const BREW_CELLAR = "/opt/homebrew/Cellar/sessionpipe/1.2.0/libexec"; + const BREW_ALT = "/opt/homebrew/Cellar/sessionpipe@0.21/1.2.0/libexec"; + + const standalone = (over: Partial = {}): Copy => + copy(LOCAL, { + dir: APP, + where: "~/.local/share/sessionpipe/app", + prefix: null, + slot: null, + managed: "standalone", + not: "installed by the standalone installer", + keeper: null, + version: NEW, + bins: [], + uses: ["typed", "service", "hooks", "this"], + onPath: true, + ...over, + }); + + const homebrew = (over: Partial = {}): Copy => + copy(BREW, { + dir: BREW_CELLAR, + where: BREW_CELLAR, + prefix: null, + slot: null, + managed: "homebrew", + not: "Homebrew keeps it", + keeper: "brew uninstall sessionpipe", + version: NEW, + bins: [], + uses: ["typed", "service", "hooks", "this"], + onPath: true, + ...over, + }); + + it("typedAs distinguishes standalone and Homebrew installs from Volta and checkouts", () => { + const stInv = inv({ + copies: [standalone()], + onPath: [{ file: bin(LOCAL), dir: APP }], + typed: APP, + home: null, + }); + expect(typedAs(stInv)).toBe( + "Typing `sessionpipe` starts the standalone install, in ~/.local/share/sessionpipe/app.", + ); + + const brInv = inv({ + copies: [homebrew()], + onPath: [{ file: bin(BREW), dir: BREW_CELLAR }], + typed: BREW_CELLAR, + home: null, + }); + expect(typedAs(brInv)).toBe(`Typing \`sessionpipe\` starts the copy Homebrew keeps, in ${BREW_CELLAR}.`); + }); + + it("Scenario 2: healthy standalone or Homebrew install alone is Nothing to repair (including offline, pre-release, and idle npx cache)", () => { + const stInv = inv({ + copies: [standalone(), cached({ uses: ["this"] })], + onPath: [{ file: bin(LOCAL), dir: APP }], + typed: APP, + home: null, + }); + const p1 = plan(stInv, facts({ npm: false })); + expect(p1.nothing).toBe(NOTHING); + expect(p1.steps).toEqual([]); + expect(p1.notes).toEqual([]); + expect(p1.left).toHaveLength(1); + expect(p1.left[0]?.why).toBe("npm's cache of what npx ran"); + + const pOffline = plan( + inv({ copies: [standalone()], onPath: [{ file: bin(LOCAL), dir: APP }], typed: APP, home: null }), + facts({ latest: { error: OFFLINE }, npm: false }), + ); + expect(pOffline.nothing).toBe(NOTHING_UNASKED(NEW)); + expect(pOffline.notes).toEqual([`npm couldn't be asked whether ${NEW} is the newest release: ${OFFLINE}.`]); + + const pre = "1.3.0-rc.1"; + const pPre = plan( + inv({ + copies: [standalone({ version: pre })], + onPath: [{ file: bin(LOCAL), dir: APP }], + typed: APP, + home: null, + }), + facts({ hooks: { version: pre, wrong: [] }, daemon: { pid: 100, version: pre, byHand: false } }), + ); + expect(pPre.nothing).toBe(`Nothing to repair: one sessionpipe, ${pre}.`); + + const pBrew = plan( + inv({ + copies: [homebrew()], + onPath: [{ file: bin(BREW), dir: BREW_CELLAR }], + typed: BREW_CELLAR, + home: null, + }), + facts({ npm: false }), + ); + expect(pBrew.nothing).toBe(NOTHING); + expect(pBrew.steps).toEqual([]); + expect(pBrew.notes).toEqual([]); + }); + + it("Scenario 1: healthy standalone or Homebrew install with leftover npm copies keeps the managed install and removes leftovers without needing npm", () => { + const oldLocal = copy(LOCAL, { + where: "~/.local", + version: OLD, + bins: [], + wrong: "npm's link to it is gone", + uses: [], + }); + const oldNvm = copy(NVM, { where: "~/.nvm/versions/node/v22.1.0", version: OLD, uses: [] }); + const stInv = inv({ + copies: [standalone(), oldLocal, oldNvm], + dangling: [bin(BREW)], + onPath: [ + { file: bin(LOCAL), dir: APP }, + { file: bin(NVM), dir: oldNvm.dir }, + ], + typed: APP, + home: null, + }); + const p = plan(stInv, facts({ npm: false })); + expect(p.refuse).toBeNull(); + expect(p.nothing).toBeNull(); + expect(p.home).toBeNull(); + expect(p.managed).toEqual({ via: "standalone", dir: APP, shown: "~/.local/share/sessionpipe/app" }); + expect(p.stays).toBe(`${NEW} in ~/.local/share/sessionpipe/app (standalone install)`); + expect(does(p)).toEqual([`remove ${bin(BREW)}`, `remove ${oldLocal.dir}`, `remove ${oldNvm.dir}`, "prove"]); + expect(p.left).toEqual([]); + expect(p.safety).toEqual([]); + + const pOffline = plan(stInv, facts({ latest: { error: OFFLINE }, npm: false })); + expect(pOffline.refuse).toBeNull(); + expect(pOffline.notes).toContain(`npm couldn't be asked whether ${NEW} is the newest release: ${OFFLINE}.`); + + const pUse = plan( + inv({ + copies: [standalone({ uses: ["typed"] }), oldLocal], + onPath: [{ file: bin(LOCAL), dir: APP }], + typed: APP, + home: null, + }), + facts({ + npm: false, + hooks: { version: OLD, wrong: [] }, + service: null, + wanted: false, + daemon: { pid: 99, version: OLD, byHand: true }, + }), + ); + expect(does(pUse)).toEqual(["use", `remove ${oldLocal.dir}`, "prove"]); + expect(pUse.safety).toEqual(["The daemon restarts once it holds nothing."]); + + const pBrew = plan( + inv({ + copies: [homebrew({ uses: ["typed"] }), oldLocal], + onPath: [{ file: bin(BREW), dir: BREW_CELLAR }], + typed: BREW_CELLAR, + home: null, + }), + facts({ npm: false, hooks: { version: OLD, wrong: [] } }), + ); + expect(pBrew.managed).toEqual({ via: "homebrew", dir: BREW_CELLAR, shown: BREW_CELLAR }); + expect(pBrew.stays).toBe(`${NEW} in ${BREW_CELLAR} (Homebrew)`); + expect(does(pBrew)).toEqual(["use", `remove ${oldLocal.dir}`, "prove"]); + expect(pBrew.safety).toEqual([SERVICE_RESTARTS]); + + const pBehind = plan( + inv({ + copies: [one({ version: OLD }), homebrew({ uses: [] })], + onPath: [ + { file: bin(LOCAL), dir: slotIn(LOCAL) }, + { file: bin(BREW), dir: BREW_CELLAR }, + ], + typed: slotIn(LOCAL), + }), + facts(), + ); + expect(pBehind.left).toContainEqual({ + where: BREW_CELLAR, + path: BREW_CELLAR, + version: NEW, + why: "Homebrew keeps it", + line: "brew uninstall sessionpipe", + ours: false, + }); + }); + + it("Scenario 3: broken, outdated, or behind standalone/Homebrew installs refuse with the exact native repair command", () => { + const pBrokenSt = plan( + inv({ + copies: [standalone({ wrong: "its dist/cli.js is missing (an install that was cut off?)" })], + onPath: [{ file: bin(LOCAL), dir: APP }], + typed: APP, + home: null, + }), + facts({ npm: false }), + ); + expect(refused(pBrokenSt)).toEqual({ + error: + "the standalone install in ~/.local/share/sessionpipe/app is not whole (its dist/cli.js is missing (an install that was cut off?)). Nothing was changed. Re-run the installer to repair it", + next: "curl -fsSL https://sessionpipe.org/install.sh | sh", + }); + + const pOldSt = plan( + inv({ + copies: [standalone({ version: OLD })], + onPath: [{ file: bin(LOCAL), dir: APP }], + typed: APP, + home: null, + }), + facts({ npm: false, hooks: { version: OLD, wrong: [] }, daemon: { pid: 100, version: OLD, byHand: false } }), + ); + expect(refused(pOldSt)).toEqual({ + error: `the standalone install in ~/.local/share/sessionpipe/app is ${OLD}, and ${NEW} is out. Nothing was changed. Update it, then run this again`, + next: "curl -fsSL https://sessionpipe.org/install.sh | sh", + }); + + // Outdated standalone or Homebrew WITH leftover npm copies still cleans up the leftovers and adds an update note + const oldLeftover = copy(LOCAL, { + where: "~/.local", + version: "1.0.0", + bins: [], + wrong: "npm's link to it is gone", + uses: [], + }); + const pOldStCleanup = plan( + inv({ + copies: [standalone({ version: OLD }), oldLeftover], + onPath: [{ file: bin(LOCAL), dir: APP }], + typed: APP, + home: null, + }), + facts({ npm: false, hooks: { version: OLD, wrong: [] }, daemon: { pid: 100, version: OLD, byHand: false } }), + ); + expect(pOldStCleanup.refuse).toBeNull(); + expect(pOldStCleanup.stays).toBe(`${OLD} in ~/.local/share/sessionpipe/app (standalone install)`); + expect(does(pOldStCleanup)).toEqual([`remove ${oldLeftover.dir}`, "prove"]); + expect(pOldStCleanup.notes).toEqual([ + `${NEW} is out: update with \`curl -fsSL https://sessionpipe.org/install.sh | sh\`.`, + ]); + + const pOldBrewCleanup = plan( + inv({ + copies: [homebrew({ version: OLD }), oldLeftover], + onPath: [{ file: bin(BREW), dir: BREW_CELLAR }], + typed: BREW_CELLAR, + home: null, + }), + facts({ npm: false, hooks: { version: OLD, wrong: [] }, daemon: { pid: 100, version: OLD, byHand: false } }), + ); + expect(pOldBrewCleanup.refuse).toBeNull(); + expect(pOldBrewCleanup.stays).toBe(`${OLD} in ${BREW_CELLAR} (Homebrew)`); + expect(does(pOldBrewCleanup)).toEqual([`remove ${oldLeftover.dir}`, "prove"]); + expect(pOldBrewCleanup.notes).toEqual([`${NEW} is out: update with \`brew upgrade sessionpipe\`.`]); + + const pBrokenBrew = plan( + inv({ + copies: [ + homebrew({ + dir: BREW_ALT, + where: BREW_ALT, + keeper: "brew uninstall sessionpipe@0.21", + wrong: "its package.json names no release of sessionpipe", + version: null, + }), + ], + onPath: [{ file: bin(BREW), dir: BREW_ALT }], + typed: BREW_ALT, + home: null, + }), + facts({ npm: false }), + ); + expect(refused(pBrokenBrew)).toEqual({ + error: `the copy Homebrew keeps in ${BREW_ALT} is not whole (its package.json names no release of sessionpipe). Nothing was changed. Reinstall it with Homebrew`, + next: "brew reinstall sessionpipe@0.21", + }); + + const pFallbackBrew = plan( + inv({ + copies: [homebrew({ dir: "/custom/libexec", where: "/custom/libexec", wrong: "broken" })], + onPath: [{ file: "/custom/bin/sessionpipe", dir: "/custom/libexec" }], + typed: "/custom/libexec", + home: null, + }), + facts({ npm: false }), + ); + expect(refused(pFallbackBrew)?.next).toBe("brew reinstall sessionpipe"); + + const pOldBrew = plan( + inv({ + copies: [homebrew({ version: OLD })], + onPath: [{ file: bin(BREW), dir: BREW_CELLAR }], + typed: BREW_CELLAR, + home: null, + }), + facts({ npm: false, hooks: { version: OLD, wrong: [] }, daemon: { pid: 100, version: OLD, byHand: false } }), + ); + expect(refused(pOldBrew)).toEqual({ + error: `the copy Homebrew keeps in ${BREW_CELLAR} is ${OLD}, and ${NEW} is out. Nothing was changed. Upgrade it with Homebrew, then run this again`, + next: "brew upgrade sessionpipe", + }); + + const pAhead = plan( + inv({ + copies: [standalone({ version: NEW })], + onPath: [{ file: bin(LOCAL), dir: APP }], + typed: APP, + home: null, + }), + facts({ npm: false, daemon: { pid: 100, version: AHEAD, byHand: false } }), + ); + expect(refused(pAhead)).toEqual({ + error: `sessionpipe ${AHEAD} is on this computer, newer than the standalone install (${NEW}): a reinstall would move it back. Nothing was changed`, + next: "sessionpipe doctor", + }); + }); +}); diff --git a/packages/cli/test/reinstall-run.test.ts b/packages/cli/test/reinstall-run.test.ts index d09fce9a..eb19ac45 100644 --- a/packages/cli/test/reinstall-run.test.ts +++ b/packages/cli/test/reinstall-run.test.ts @@ -103,6 +103,7 @@ const plan = (steps: Step[], o: Partial = {}): Plan => ({ blocked: null, writable: true, }, + managed: null, stays: null, steps, // The plan's screen says it; the run has nothing to do with it. @@ -2088,3 +2089,67 @@ describe.skipIf(process.platform === "win32" || path.sep !== "/")( }); }, ); + +describe("carryOut for kept managed (standalone and Homebrew) plans", () => { + const managedPlan = (via: "standalone" | "homebrew", shown: string, dir: string): Plan => + plan( + [ + { + do: "remove", + path: slotOf("/w/home/.local"), + touches: [slotOf("/w/home/.local")], + say: "0.18.6 in ~/.local", + }, + { do: "prove", touches: [] }, + ], + { + home: null, + managed: { via, dir, shown }, + stays: `2.0.0 in ${shown} (${via === "standalone" ? "standalone install" : "Homebrew"})`, + safety: [], + }, + ); + + it("finishes cleanly for standalone and Homebrew plans with their install tag", async () => { + for (const [via, shown, dir, tag] of [ + ["standalone", "~/.local/share/sessionpipe/app", "/w/home/.local/share/sessionpipe/app", "(standalone install)"], + [ + "homebrew", + "/opt/homebrew/Cellar/sessionpipe/2.0.0/libexec", + "/opt/homebrew/Cellar/sessionpipe/2.0.0/libexec", + "(Homebrew)", + ], + ] as const) { + const { d } = start({ there: [slotOf("/w/home/.local")] }); + const done = await carryOut(managedPlan(via, shown, dir), d); + expect(done).toEqual({ + state: "one", + said: `This computer has one sessionpipe: 2.0.0, in ${shown} ${tag}. Pairings and settings are as they were.`, + warn: [], + }); + } + }); + + it("names the standalone installer or doctor (not npx) when prove fails on a managed copy", async () => { + const st = start({ proof: { runs: null, typed: true, onPath: [], named: [] } }); + expect(await carryOut(managedPlan("standalone", "~/.local/share/sessionpipe/app", "/w/app"), st.d)).toEqual({ + state: "failed", + error: + "the copy in ~/.local/share/sessionpipe/app doesn't run as it should (`--version` printed nothing): no other copy was removed", + next: "curl -fsSL https://sessionpipe.org/install.sh | sh", + }); + + const br = start({ proof: { runs: null, typed: true, onPath: [], named: [] } }); + expect( + await carryOut( + managedPlan("homebrew", "/opt/homebrew/Cellar/sessionpipe/2.0.0/libexec", "/opt/homebrew/libexec"), + br.d, + ), + ).toEqual({ + state: "failed", + error: + "the copy in /opt/homebrew/Cellar/sessionpipe/2.0.0/libexec doesn't run as it should (`--version` printed nothing): no other copy was removed", + next: "sessionpipe doctor", + }); + }); +}); diff --git a/scripts/install-script.test.ts b/scripts/install-script.test.ts index 058bacfb..84dff785 100644 --- a/scripts/install-script.test.ts +++ b/scripts/install-script.test.ts @@ -390,4 +390,34 @@ exec "${process.execPath}" -e 'const fs=require("node:fs");fetch(process.argv[1] expect(badOpt.stderr).toContain("unknown option: --bogus"); chmodSync(installScript, 0o755); }); + + it("prints a cleanup note pointing to `sessionpipe reinstall` when replacing an existing npm global symlink", async () => { + const local = path.join(tmp, "local"); + const binDir = path.join(local, "bin"); + const npmPkg = path.join(local, "lib", "node_modules", "sessionpipe"); + const dataDir = path.join(tmp, "data"); + mkdirSync(path.join(npmPkg, "dist"), { recursive: true }); + mkdirSync(binDir, { recursive: true }); + writeFileSync(path.join(npmPkg, "package.json"), JSON.stringify({ name: "sessionpipe", version: "0.18.5" })); + writeFileSync(path.join(npmPkg, "dist", "cli.js"), "#!/usr/bin/env node\n", { mode: 0o755 }); + const { symlinkSync } = await import("node:fs"); + symlinkSync( + path.join("..", "lib", "node_modules", "sessionpipe", "dist", "cli.js"), + path.join(binDir, "sessionpipe"), + ); + + const { stdout } = await execFileAsync("/bin/sh", [installScript], { + env: { + ...process.env, + HOME: tmp, + SESSIONPIPE_REGISTRY: registryUrl, + SESSIONPIPE_DATA: dataDir, + SESSIONPIPE_BIN_DIR: binDir, + }, + }); + expect(stdout).toContain(`Installed sessionpipe ${pkgNew.version}`); + expect(stdout).toContain("an older npm copy remains in"); + expect(stdout).toContain("sessionpipe reinstall"); + expect((await execFileAsync(path.join(binDir, "sessionpipe"), ["--version"])).stdout.trim()).toBe(pkgNew.version); + }); }); diff --git a/website/public/install.sh b/website/public/install.sh index 874752a3..4ab2879a 100755 --- a/website/public/install.sh +++ b/website/public/install.sh @@ -298,6 +298,10 @@ rm -rf "$APP_EXTRACT" "$APP_BACKUP" BIN_FILE="$BIN_DIR/sessionpipe" BIN_TMP="$BIN_DIR/.sessionpipe.$$.tmp" +REPLACED_NPM=0 +if [ -L "$BIN_FILE" ] && [ -f "$BIN_DIR/../lib/node_modules/sessionpipe/package.json" ]; then + REPLACED_NPM=1 +fi cat > "$BIN_TMP" <