feat(setup): make installation explicit and safe

This commit is contained in:
morluto
2026-07-13 15:13:59 +08:00
parent 1d1fe7b212
commit 3793889ce8
12 changed files with 793 additions and 497 deletions
+60 -101
View File
@@ -24,90 +24,54 @@ afterEach(async () => {
});
describe("curl installer scenarios", () => {
it("installs a pinned release with closed stdin and cleans temporary files", async () => {
it("installs only a pinned REA CLI with closed stdin", async () => {
const fixture = await createFixture();
const result = await runInstaller(fixture, { REA_VERSION: "0.3.0" });
expect(result.stdout).toContain("REA 0.3.0 is installed and ready");
const result = await runInstaller(fixture, ["--version", "0.3.0"]);
expect(result.stdout).toContain("REA 0.3.0 is installed");
expect(result.stdout).toContain("Run ");
expect(await readFile(fixture.npmLog, "utf8")).toContain(
"rea-agents@0.3.0",
"install --global --prefix",
);
expect(await readFile(fixture.reaLog, "utf8")).toBe("--version\n");
expect(await readdir(fixture.temporary)).toEqual([]);
});
it("resolves and validates the latest rea-agents release tag", async () => {
it("accepts Node 25 without installing or replacing it", async () => {
const fixture = await createFixture();
const result = await runInstaller(fixture, ["--version", "0.3.0"], {
FAKE_NODE_VERSION: "25.1.0",
});
expect(result.stdout).toContain("Runtime: Node.js 25.1.0");
});
it("resolves and validates the latest REA release tag", async () => {
const fixture = await createFixture();
const result = await runInstaller(fixture);
expect(result.stdout).toContain("Installing rea-agents@0.3.0");
expect(result.stdout).toContain("Version: 0.3.0");
});
it("bootstraps checksum-verified Node 24 into the user prefix", async () => {
it("prints a dry run without invoking npm", async () => {
const fixture = await createFixture();
const result = await runInstaller(fixture, {
REA_VERSION: "0.3.0",
FAKE_OLD_NODE: "1",
FAKE_NODE_ARCHIVE: fixture.nodeArchive,
FAKE_NODE_SUMS: fixture.nodeSums,
const result = await runInstaller(fixture, [
"--version",
"0.3.0",
"--dry-run",
]);
expect(result.stdout).toContain("no changes made");
await expect(readFile(fixture.npmLog, "utf8")).rejects.toMatchObject({
code: "ENOENT",
});
expect(result.stdout).toContain("REA 0.3.0 is installed and ready");
expect(
await readFile(
join(fixture.home, ".local/share/rea/node/bin/node"),
"utf8",
),
).toContain("24.18.0");
});
it("reports fresh Hopper activation as partial success", async () => {
const fixture = await createFixture();
const result = await runInstaller(fixture, {
REA_VERSION: "0.3.0",
FAKE_SETUP_ACTIONS: '["installed_hopper"]',
});
expect(result.stdout).toContain("One user action remains");
expect(result.stdout).toContain("open Hopper");
});
it.each([
[
"injected version",
{ REA_VERSION: "0.3.0;touch /tmp/pwned" },
"exact semantic version",
],
[
"npm failure",
{ REA_VERSION: "0.3.0", FAKE_NPM_FAIL: "1" },
"npm package installation failed",
],
[
"version mismatch",
{ REA_VERSION: "0.3.0", FAKE_REA_VERSION: "9.9.9" },
"does not match",
],
[
"malformed setup",
{ REA_VERSION: "0.3.0", FAKE_SETUP_JSON: "not-json" },
"malformed output",
],
[
"unhealthy doctor",
{ REA_VERSION: "0.3.0", FAKE_DOCTOR_HEALTHY: "false" },
"unhealthy required component",
],
["unsupported Node", { FAKE_NODE_VERSION: "20.0.0" }, "unsupported"],
["npm failure", { FAKE_NPM_FAIL: "1" }, "npm package installation failed"],
["version mismatch", { FAKE_REA_VERSION: "9.9.9" }, "does not match"],
] as const)("fails closed on %s", async (_name, overrides, message) => {
const fixture = await createFixture();
await expect(runInstaller(fixture, overrides)).rejects.toMatchObject({
stderr: expect.stringContaining(message),
});
});
it("is safe to rerun", async () => {
const fixture = await createFixture();
await runInstaller(fixture, { REA_VERSION: "0.3.0" });
await runInstaller(fixture, { REA_VERSION: "0.3.0" });
expect(
(await readFile(fixture.npmLog, "utf8")).trim().split("\n"),
).toHaveLength(2);
expect(await readdir(fixture.temporary)).toEqual([]);
await expect(
runInstaller(fixture, ["--version", "0.3.0"], overrides),
).rejects.toMatchObject({ stderr: expect.stringContaining(message) });
});
});
@@ -116,8 +80,7 @@ interface InstallerFixture {
readonly bin: string;
readonly temporary: string;
readonly npmLog: string;
readonly nodeArchive: string;
readonly nodeSums: string;
readonly reaLog: string;
}
const createFixture = async (): Promise<InstallerFixture> => {
@@ -127,52 +90,45 @@ const createFixture = async (): Promise<InstallerFixture> => {
const bin = join(root, "bin");
const temporary = join(root, "tmp");
const npmLog = join(root, "npm.log");
const nodeFixture = join(root, "node-v24.18.0-linux-x64");
const nodeArchive = `${nodeFixture}.tar.xz`;
const nodeSums = join(root, "SHASUMS256.txt");
const reaLog = join(root, "rea.log");
await Promise.all([mkdir(home), mkdir(bin), mkdir(temporary)]);
const realNode = process.execPath;
await mkdir(join(nodeFixture, "bin"), { recursive: true });
await executable(
join(nodeFixture, "bin/node"),
`#!/bin/sh\nif [ "$1" = "-p" ]; then echo 24.18.0; else exec ${shellQuote(realNode)} "$@"; fi\n`,
);
await executable(
join(nodeFixture, "bin/npm"),
'#!/bin/sh\nif [ "$1" = "--version" ]; then echo 11.16.0; exit 0; fi\nprintf "%s\\n" "$*" >> "$FAKE_NPM_LOG"\nexit 0\n',
);
await execFileAsync("tar", [
"-cJf",
nodeArchive,
"-C",
root,
"node-v24.18.0-linux-x64",
]);
const checksum = (
await execFileAsync("sha256sum", [nodeArchive])
).stdout.split(" ")[0];
await writeFile(nodeSums, `${checksum} node-v24.18.0-linux-x64.tar.xz\n`);
await executable(
join(bin, "uname"),
'#!/bin/sh\n[ "$1" = "-m" ] && echo x86_64 || echo Linux\n',
);
await executable(
join(bin, "node"),
`#!/bin/sh\nif [ "$1" = "-p" ]; then [ "\${FAKE_OLD_NODE:-}" = "1" ] && echo 20.0.0 || echo 24.18.0; else exec ${shellQuote(realNode)} "$@"; fi\n`,
`#!/bin/sh
if [ "$1" = "-p" ]; then printf '%s\n' "\${FAKE_NODE_VERSION:-24.18.0}"; else exec ${shellQuote(process.execPath)} "$@"; fi
`,
);
await executable(
join(bin, "npm"),
'#!/bin/sh\nif [ "$1" = "--version" ]; then echo 11.16.0; exit 0; fi\nprintf "%s\\n" "$*" >> "$FAKE_NPM_LOG"\n[ "${FAKE_NPM_FAIL:-}" = "1" ] && exit 1\nexit 0\n',
`#!/bin/sh
printf '%s\n' "$*" >> "$FAKE_NPM_LOG"
[ "\${FAKE_NPM_FAIL:-}" = "1" ] && exit 1
prefix="$HOME/.local"
while [ "$#" -gt 0 ]; do
if [ "$1" = "--prefix" ]; then shift; prefix="$1"; fi
shift
done
mkdir -p "$prefix/bin"
cp "$FAKE_REA_SOURCE" "$prefix/bin/rea"
chmod +x "$prefix/bin/rea"
`,
);
await executable(
join(bin, "curl"),
'#!/bin/sh\nout=""\nurl=""\nwhile [ "$#" -gt 0 ]; do\n if [ "$1" = "-o" ]; then shift; out="$1"; else url="$1"; fi\n shift\ndone\ncase "$url" in\n *node-v24.18.0-linux-x64.tar.xz) cp "$FAKE_NODE_ARCHIVE" "$out" ;;\n *SHASUMS256.txt) cp "$FAKE_NODE_SUMS" "$out" ;;\n *) printf \'{"tag_name":"rea-agents-0.3.0"}\' ;;\nesac\n',
'#!/bin/sh\nprintf \'{"tag_name":"rea-agents-0.3.0"}\'\n',
);
await executable(
join(bin, "rea"),
'#!/bin/sh\ncase "$1" in\n--version) printf "%s\\n" "${FAKE_REA_VERSION:-0.3.0}" ;;\nsetup) if [ -n "${FAKE_SETUP_JSON:-}" ]; then printf "%s\\n" "$FAKE_SETUP_JSON"; else printf \'{"status":"ready","actions":%s}\\n\' "${FAKE_SETUP_ACTIONS:-[]}"; fi ;;\ndoctor) printf \'{"healthy":%s,"checks":[]}\\n\' "${FAKE_DOCTOR_HEALTHY:-true}" ;;\nesac\n',
join(bin, "rea-source"),
`#!/bin/sh
printf '%s\n' "$*" >> "$FAKE_REA_LOG"
[ "$1" = "--version" ] && printf '%s\n' "\${FAKE_REA_VERSION:-0.3.0}"
`,
);
return { home, bin, temporary, npmLog, nodeArchive, nodeSums };
return { home, bin, temporary, npmLog, reaLog };
};
const executable = async (path: string, source: string): Promise<void> => {
@@ -182,15 +138,18 @@ const executable = async (path: string, source: string): Promise<void> => {
const runInstaller = async (
fixture: InstallerFixture,
args: readonly string[] = [],
overrides: Readonly<Record<string, string>> = {},
): Promise<{ readonly stdout: string; readonly stderr: string }> =>
execFileAsync("/bin/bash", [join(process.cwd(), "install.sh")], {
execFileAsync("/bin/bash", [join(process.cwd(), "install.sh"), ...args], {
env: {
...process.env,
HOME: fixture.home,
TMPDIR: fixture.temporary,
PATH: `${fixture.bin}:${process.env.PATH ?? ""}`,
PATH: `${fixture.bin}:/usr/bin:/bin`,
FAKE_NPM_LOG: fixture.npmLog,
FAKE_REA_LOG: fixture.reaLog,
FAKE_REA_SOURCE: join(fixture.bin, "rea-source"),
...overrides,
},
});
+110
View File
@@ -0,0 +1,110 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import {
installMacHopper,
type MacHopperInstallHost,
} from "../src/application/MacHopper.js";
class FakeMacHopperHost implements MacHopperInstallHost {
readonly archive = new TextEncoder().encode("hopper-dmg");
archiveOk = true;
valid = true;
existing = false;
mountSucceeds = true;
copySucceeds = true;
launcherSucceeds = true;
badHash = false;
unmounts = 0;
cleanups = 0;
opens = 0;
download = (url: string) =>
Promise.resolve(
url.includes("files-api")
? {
ok: true,
bytes: new TextEncoder().encode(
JSON.stringify({
"OS X": {
filename:
"https://www.hopperapp.com:443/downloader/public/Hopper-demo.dmg",
file_length: String(this.archive.byteLength),
file_hash: this.badHash
? "0".repeat(40)
: createHash("sha1").update(this.archive).digest("hex"),
},
}),
),
}
: { ok: this.archiveOk, bytes: this.archive },
);
createTemporaryDirectory = () => Promise.resolve("/tmp/rea-hopper-test");
createMountDirectory = () => Promise.resolve();
writePackage = () => Promise.resolve();
mount = () => Promise.resolve(this.mountSucceeds);
unmount = () => {
this.unmounts += 1;
return Promise.resolve();
};
appBundle = () => Promise.resolve("/mounted/Hopper Disassembler.app");
validBundle = () => Promise.resolve(this.valid);
destinationExists = () => Promise.resolve(this.existing);
installBundle = () => Promise.resolve(this.copySucceeds);
launcherReady = () => Promise.resolve(this.launcherSucceeds);
openApplication = () => {
this.opens += 1;
return Promise.resolve();
};
cleanup = () => {
this.cleanups += 1;
return Promise.resolve();
};
destination = () => "/home/user/Applications/Hopper Disassembler.app";
}
describe("macOS Hopper installation", () => {
it("installs, verifies, opens, and cleans the official package", async () => {
const host = new FakeMacHopperHost();
await expect(installMacHopper(host)).resolves.toEqual({
status: "installed",
launcherPath:
"/home/user/Applications/Hopper Disassembler.app/Contents/MacOS/hopper",
});
expect(host.opens).toBe(1);
expect(host.unmounts).toBe(1);
expect(host.cleanups).toBe(1);
});
it("rejects an integrity mismatch before mounting", async () => {
const host = new FakeMacHopperHost();
host.badHash = true;
await expect(installMacHopper(host)).resolves.toEqual({
status: "failed",
reason: "integrity",
});
expect(host.unmounts).toBe(0);
expect(host.cleanups).toBe(0);
});
it("refuses to overwrite an existing application", async () => {
const host = new FakeMacHopperHost();
host.existing = true;
await expect(installMacHopper(host)).resolves.toEqual({
status: "failed",
reason: "destination_exists",
});
});
it("cleans and detaches after bundle validation fails", async () => {
const host = new FakeMacHopperHost();
host.valid = false;
await expect(installMacHopper(host)).resolves.toEqual({
status: "failed",
reason: "bundle",
});
expect(host.unmounts).toBe(1);
expect(host.cleanups).toBe(1);
});
});
+92 -134
View File
@@ -5,26 +5,23 @@ import {
type ClientConfigurationResult,
type SetupClient,
type SetupHost,
type SetupOptions,
} from "../src/application/Setup.js";
import type { DoctorCheck } from "../src/application/Doctor.js";
import type { LinuxDistribution } from "../src/application/LinuxHopper.js";
class FakeSetupHost implements SetupHost {
readonly platform: NodeJS.Platform;
readonly nodeVersion = "24.18.0";
readonly nodeVersion = "25.1.0";
version: string | undefined = "14.5";
brew = false;
distribution: LinuxDistribution | undefined;
hopper: string | undefined;
homebrewInstallSucceeds = true;
hopperInstallSucceeds = true;
skill: "installed" | "unchanged" | "failed" = "installed";
clients: readonly SetupClient[] = [];
clientResults = new Map<string, ClientConfigurationResult>();
homebrewInstalls = 0;
hopperInstalls = 0;
configurations = 0;
configuredHopperPaths: string[] = [];
distribution: LinuxDistribution | undefined;
constructor(platform: NodeJS.Platform = "darwin") {
this.platform = platform;
@@ -34,31 +31,20 @@ class FakeSetupHost implements SetupHost {
Promise.resolve(this.version);
linuxDistribution = (): Promise<LinuxDistribution | undefined> =>
Promise.resolve(this.distribution);
hasHomebrew = (): Promise<boolean> => Promise.resolve(this.brew);
installHomebrew = (): Promise<boolean> => {
this.homebrewInstalls += 1;
if (this.homebrewInstallSucceeds) this.brew = true;
return Promise.resolve(this.homebrewInstallSucceeds);
};
hopperPath = (): Promise<string | undefined> => Promise.resolve(this.hopper);
installHopper = (): Promise<boolean> => {
installHopper = (): Promise<string | undefined> => {
this.hopperInstalls += 1;
if (this.hopperInstallSucceeds) this.hopper = "/manual/Hopper";
return Promise.resolve(this.hopperInstallSucceeds);
return Promise.resolve(this.hopper);
};
detectedClients = (): Promise<readonly SetupClient[]> =>
Promise.resolve(this.clients);
configureClient = (
client: SetupClient,
hopperPath: string,
): Promise<ClientConfigurationResult> => {
this.configurations += 1;
this.configuredHopperPaths.push(hopperPath);
return Promise.resolve(
this.clientResults.get(client.name) ?? {
status: "configured",
backupPath: `${client.configPath}.backup`,
},
this.clientResults.get(client.name) ?? { status: "configured" },
);
};
installSkill = (): Promise<"installed" | "unchanged" | "failed"> =>
@@ -69,40 +55,107 @@ class FakeSetupHost implements SetupHost {
checks: readonly DoctorCheck[];
}> =>
Promise.resolve({
healthy:
(this.platform === "linux" || this.brew) && this.hopper !== undefined,
healthy: this.hopper !== undefined,
...(this.hopper === undefined ? {} : { hopperPath: this.hopper }),
checks: [],
});
}
const options = (approved: boolean, installHopper = false): SetupOptions => ({
approved,
installHopper,
structured: true,
});
describe("setup workflow", () => {
it("installs Homebrew and Hopper on a clean approved machine", async () => {
it("returns a complete plan without mutation", async () => {
const host = new FakeSetupHost();
const result = await runSetup(true, host);
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
const result = await runSetup(options(false), host);
expect(result.status).toBe("needs_confirmation");
expect(result.plannedActions.map(({ kind }) => kind)).toEqual([
"install_hopper",
"configure_client",
"install_skill",
]);
expect(host.hopperInstalls).toBe(0);
expect(host.configurations).toBe(0);
});
it("applies an accepted interactive plan including Hopper", async () => {
const host = new FakeSetupHost();
const result = await runSetup(
{ ...options(false), structured: false },
host,
() => Promise.resolve(true),
);
expect(result.status).toBe("needs_human");
expect(result.actions).toEqual([
"installed_homebrew",
expect(result.appliedActions).toEqual([
"installed_hopper",
"installed_skill",
]);
expect(host.hopperInstalls).toBe(1);
});
it("installs Hopper without Homebrew on supported Linux", async () => {
const host = new FakeSetupHost("linux");
host.distribution = {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
};
const result = await runSetup(true, host);
it("declines an interactive plan without mutation", async () => {
const host = new FakeSetupHost();
const result = await runSetup(
{ ...options(false), structured: false },
host,
() => Promise.resolve(false),
);
expect(result.status).toBe("planned");
expect(result.appliedActions).toEqual([]);
expect(host.hopperInstalls).toBe(0);
});
it("requires the Hopper flag for unattended setup", async () => {
const host = new FakeSetupHost();
const result = await runSetup(options(true), host);
expect(result.status).toBe("needs_human");
expect(result.actions).toEqual(["installed_hopper", "installed_skill"]);
expect(host.homebrewInstalls).toBe(0);
expect(host.hopperInstalls).toBe(0);
expect(result.appliedActions).toEqual(["installed_skill"]);
expect(result.remediation).toContain("--install-hopper");
});
it("rejects unsupported Linux before mutation", async () => {
it("installs Hopper when unattended authorization is explicit", async () => {
const host = new FakeSetupHost();
const result = await runSetup(options(true, true), host);
expect(result.appliedActions).toEqual([
"installed_hopper",
"installed_skill",
]);
expect(host.hopperInstalls).toBe(1);
});
it("reuses existing Hopper and configures detected clients", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.clients = [
{ name: "claude", configPath: "/claude.json" },
{ name: "cursor", configPath: "/cursor.json" },
];
const result = await runSetup(options(true), host);
expect(result.status).toBe("ready");
expect(result.appliedActions).toEqual([
"configured_claude",
"configured_cursor",
"installed_skill",
]);
expect(host.hopperInstalls).toBe(0);
});
it("reports a failed Hopper installation without configuring clients", async () => {
const host = new FakeSetupHost();
host.hopperInstallSucceeds = false;
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
const result = await runSetup(options(true, true), host);
expect(result.status).toBe("needs_human");
expect(result.remediation).toContain("failed");
expect(host.configurations).toBe(0);
});
it("rejects unsupported hosts before mutation", async () => {
const host = new FakeSetupHost("linux");
host.distribution = {
id: "debian",
@@ -110,103 +163,8 @@ describe("setup workflow", () => {
packageFamily: "deb",
supported: false,
};
const result = await runSetup(true, host);
const result = await runSetup(options(true, true), host);
expect(result.status).toBe("needs_human");
expect(host.hopperInstalls).toBe(0);
expect(host.configurations).toBe(0);
});
it("requires --yes before installing Homebrew", async () => {
const host = new FakeSetupHost();
const result = await runSetup(false, host);
expect(result.status).toBe("needs_human");
expect(host.homebrewInstalls).toBe(0);
expect(result.remediation).toContain("--yes");
});
it("requires --yes before installing Hopper", async () => {
const host = new FakeSetupHost();
host.brew = true;
const result = await runSetup(false, host);
expect(result.status).toBe("needs_human");
expect(host.hopperInstalls).toBe(0);
expect(result.remediation).toContain("--yes");
});
it("accepts existing Homebrew and manually installed Hopper", async () => {
const host = new FakeSetupHost();
host.brew = true;
host.hopper = "/Applications/Manual Hopper";
expect((await runSetup(true, host)).actions).toEqual(["installed_skill"]);
expect(host.hopperInstalls).toBe(0);
expect(host.configuredHopperPaths).toEqual([]);
});
it.each(["homebrew", "hopper"] as const)(
"returns needs_human when %s installation is interrupted",
async (stage) => {
const host = new FakeSetupHost();
if (stage === "homebrew") host.homebrewInstallSucceeds = false;
else {
host.brew = true;
host.hopperInstallSucceeds = false;
}
const result = await runSetup(true, host);
expect(result.status).toBe("needs_human");
expect(result.remediation).toContain("interrupted");
},
);
it("configures every detected client and reports backup paths", async () => {
const host = new FakeSetupHost();
host.brew = true;
host.hopper = "/Hopper";
host.clients = [
{ name: "claude", configPath: "/claude.json" },
{ name: "cursor", configPath: "/cursor.json" },
];
const result = await runSetup(true, host);
expect(Object.keys(result.clients)).toEqual(["claude", "cursor"]);
expect(host.configurations).toBe(2);
expect(host.configuredHopperPaths).toEqual(["/Hopper", "/Hopper"]);
});
it.each(["backup", "write", "readback"] as const)(
"stops with precise remediation after a %s failure",
async (reason) => {
const host = new FakeSetupHost();
host.brew = true;
host.hopper = "/Hopper";
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
host.clientResults.set("cursor", { status: "failed", reason });
const result = await runSetup(true, host);
expect(result.status).toBe("needs_human");
expect(result.remediation).toContain(reason);
},
);
it("is idempotent on repeated setup", async () => {
const host = new FakeSetupHost();
host.brew = true;
host.hopper = "/Hopper";
host.skill = "unchanged";
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
host.clientResults.set("cursor", { status: "unchanged" });
const first = await runSetup(true, host);
const second = await runSetup(true, host);
expect(first.actions).toEqual([]);
expect(second.actions).toEqual([]);
expect(host.homebrewInstalls).toBe(0);
expect(host.hopperInstalls).toBe(0);
});
it.each(["11.7", undefined])(
"rejects unsupported macOS %s before mutation",
async (version) => {
const host = new FakeSetupHost();
host.version = version;
expect((await runSetup(true, host)).status).toBe("needs_human");
expect(host.homebrewInstalls).toBe(0);
},
);
});