Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(setup): own Hopper replacement staging and committed outcomes

morluto8c0e431895b7
diff --git a/src/application/MacHopper.test.ts b/src/application/MacHopper.test.ts
index 7896208c5..b2547d9b1 100644
--- a/src/application/MacHopper.test.ts
+++ b/src/application/MacHopper.test.ts
@@ -4,7 +4,9 @@ import { describe, expect, it } from "vitest";
import {
installMacHopper,
+ installMacHopperBundle,
type MacHopperBundleVerification,
+ type MacHopperBundleInstallResult,
type MacHopperInstallHost,
} from "./MacHopper.js";
@@ -15,7 +17,8 @@ class FakeMacHopperHost implements MacHopperInstallHost {
existing = false;
mountSucceeds = true;
copySucceeds = true;
- launcherSucceeds = true;
+ mountFailure: Error | undefined;
+ verificationFailure: Error | undefined;
badHash = false;
unmounts = 0;
cleanups = 0;
@@ -46,25 +49,37 @@ class FakeMacHopperHost implements MacHopperInstallHost {
createTemporaryDirectory = () => Promise.resolve("/tmp/rea-hopper-test");
createMountDirectory = () => Promise.resolve();
writePackage = () => Promise.resolve();
- mount = () => Promise.resolve(this.mountSucceeds);
+ mount = () =>
+ this.mountFailure === undefined
+ ? Promise.resolve(this.mountSucceeds)
+ : Promise.reject(this.mountFailure);
unmount = () => {
this.unmounts += 1;
return Promise.resolve();
};
appBundle = () => Promise.resolve("/mounted/Hopper Disassembler.app");
- validBundle = () => Promise.resolve(this.verification);
+ validBundle = () =>
+ this.verificationFailure === undefined
+ ? Promise.resolve(this.verification)
+ : Promise.reject(this.verificationFailure);
destinationExists = () => Promise.resolve(this.existing);
installBundle = (
_source: string,
_destination: string,
- _stage: string,
replaceExisting: boolean,
) => {
this.installs += 1;
this.replaces = replaceExisting;
- return Promise.resolve(this.copySucceeds);
+ return Promise.resolve<MacHopperBundleInstallResult>(
+ this.copySucceeds
+ ? { status: "installed" }
+ : {
+ status: "failed",
+ reason: "copy",
+ diagnostic: "ditto: destination is read-only",
+ },
+ );
};
- launcherReady = () => Promise.resolve(this.launcherSucceeds);
openApplication = () => {
this.opens += 1;
return Promise.resolve();
@@ -89,6 +104,22 @@ describe("macOS Hopper installation", () => {
expect(host.cleanups).toBe(1);
});
+ it("preserves installation when macOS cannot open the installed app", async () => {
+ const host = new FakeMacHopperHost();
+ host.openApplication = () =>
+ Promise.reject(new Error("LaunchServices refused"));
+
+ await expect(installMacHopper({}, host)).resolves.toEqual({
+ status: "installed",
+ launcherPath:
+ "/home/user/Applications/Hopper Disassembler.app/Contents/MacOS/hopper",
+ openFailure: "LaunchServices refused",
+ });
+ expect(host.installs).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;
@@ -130,6 +161,33 @@ describe("macOS Hopper installation", () => {
expect(host.cleanups).toBe(1);
});
+ it("preserves a thrown mount-stage diagnostic and cleans the temporary image", async () => {
+ const host = new FakeMacHopperHost();
+ host.mountFailure = new Error("hdiutil attach: resource busy");
+
+ await expect(installMacHopper({}, host)).resolves.toMatchObject({
+ status: "failed",
+ reason: "mount",
+ diagnostic: "hdiutil attach: resource busy",
+ });
+ expect(host.unmounts).toBe(0);
+ expect(host.cleanups).toBe(1);
+ });
+
+ it("preserves the copy diagnostic from the owned install operation", async () => {
+ const host = new FakeMacHopperHost();
+ host.copySucceeds = false;
+
+ await expect(installMacHopper({}, host)).resolves.toMatchObject({
+ status: "failed",
+ reason: "copy",
+ diagnostic: "ditto: destination is read-only",
+ });
+ expect(host.installs).toBe(1);
+ expect(host.unmounts).toBe(1);
+ expect(host.cleanups).toBe(1);
+ });
+
it("reports a publisher mismatch without copying or launching the bundle", async () => {
const host = new FakeMacHopperHost();
host.verification = "unverified_publisher";
@@ -142,4 +200,18 @@ describe("macOS Hopper installation", () => {
expect(host.unmounts).toBe(1);
expect(host.cleanups).toBe(1);
});
+
+ it("preserves a thrown signature-check diagnostic as a bundle failure", async () => {
+ const host = new FakeMacHopperHost();
+ host.verificationFailure = new Error("codesign: helper unavailable");
+
+ await expect(installMacHopper({}, host)).resolves.toMatchObject({
+ status: "failed",
+ reason: "bundle",
+ diagnostic: "codesign: helper unavailable",
+ });
+ expect(host.installs).toBe(0);
+ expect(host.unmounts).toBe(1);
+ expect(host.cleanups).toBe(1);
+ });
});
diff --git a/src/application/MacHopper.ts b/src/application/MacHopper.ts
index f6b60c71b..ef13af419 100644
--- a/src/application/MacHopper.ts
+++ b/src/application/MacHopper.ts
@@ -10,7 +10,7 @@ import {
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
import { promisify } from "node:util";
import { z } from "zod";
@@ -22,6 +22,7 @@ import {
downloadHopperPackage,
HOPPER_DOWNLOAD_BYTES,
} from "./HopperDownload.js";
+import type { HopperInstallFailureReason } from "./SetupInstallFailure.js";
const execFileAsync = promisify(execFile);
const RELEASES_URL =
@@ -38,6 +39,38 @@ export type MacHopperBundleVerification =
| "invalid_signature"
| "unverified_publisher";
+type MacHopperInstallFailureReason = Extract<
+ HopperInstallFailureReason,
+ | "release_metadata"
+ | "download"
+ | "integrity"
+ | "launcher_missing"
+ | "destination_exists"
+ | "mount"
+ | "bundle"
+ | "publisher_verification_failed"
+ | "copy"
+>;
+
+export type MacHopperBundleInstallResult =
+ | { readonly status: "installed"; readonly cleanupFailure?: string }
+ | {
+ readonly status: "failed";
+ readonly reason: "copy" | "launcher_missing";
+ readonly diagnostic: string;
+ readonly cleanupFailure?: string;
+ };
+
+/** Filesystem effects for one installer-owned bundle replacement transaction. */
+export interface MacHopperBundleInstallOperations {
+ createStagingRoot(parent: string): Promise<string>;
+ copyBundle(source: string, stage: string): Promise<void>;
+ requireLauncher(path: string): Promise<void>;
+ pathExists(path: string): Promise<boolean>;
+ rename(source: string, destination: string): Promise<void>;
+ removeStagingRoot(path: string): Promise<void>;
+}
+
/** Stable network and command effects disclosed before macOS Hopper setup. */
export const macHopperInstallDisclosure = {
networkOrigins: [RELEASES_URL, DOWNLOAD_PREFIX] as const,
@@ -56,19 +89,12 @@ export type MacHopperInstallResult =
readonly status: "installed";
readonly launcherPath: string;
readonly cleanupFailure?: string;
+ readonly openFailure?: string;
}
| {
readonly status: "failed";
- readonly reason:
- | "release_metadata"
- | "download"
- | "integrity"
- | "mount"
- | "bundle"
- | "publisher_verification_failed"
- | "destination_exists"
- | "copy"
- | "launcher_missing";
+ readonly reason: MacHopperInstallFailureReason;
+ readonly diagnostic?: string;
readonly cleanupFailure?: string;
};
@@ -88,10 +114,8 @@ export interface MacHopperInstallHost {
installBundle(
source: string,
destination: string,
- stage: string,
replaceExisting: boolean,
- ): Promise<boolean>;
- launcherReady(path: string): Promise<boolean>;
+ ): Promise<MacHopperBundleInstallResult>;
openApplication(path: string): Promise<void>;
cleanup(path: string): Promise<void>;
/** Retain the cleanup capability until the owning setup host retries it. */
@@ -109,6 +133,8 @@ export const installMacHopper = async (
): Promise<MacHopperInstallResult> => {
let temporary: string | undefined;
let mounted = false;
+ let bundleCleanupFailure: string | undefined;
+ let installStage: MacHopperInstallFailureReason = "release_metadata";
let result: MacHopperInstallResult;
try {
result = await (async (): Promise<MacHopperInstallResult> => {
@@ -120,15 +146,19 @@ export const installMacHopper = async (
const release = parsed.data["OS X"];
if (!release.filename.startsWith(DOWNLOAD_PREFIX))
return { status: "failed", reason: "release_metadata" };
+ installStage = "download";
const archive = await host.download(release.filename);
if (!archive.ok) return { status: "failed", reason: "download" };
+ installStage = "integrity";
if (!integrityMatches(archive.bytes, release))
return { status: "failed", reason: "integrity" };
+ installStage = "destination_exists";
const destination = host.destination();
const destinationExists = await host.destinationExists(destination);
if (destinationExists && options.replaceExisting !== true)
return { status: "failed", reason: "destination_exists" };
+ installStage = "mount";
temporary = await host.createTemporaryDirectory();
const packagePath = join(temporary, "hopper.dmg");
const mountPath = join(temporary, "mounted");
@@ -137,6 +167,7 @@ export const installMacHopper = async (
if (!(await host.mount(packagePath, mountPath)))
return { status: "failed", reason: "mount" };
mounted = true;
+ installStage = "bundle";
const source = await host.appBundle(mountPath);
if (source === undefined) return { status: "failed", reason: "bundle" };
const verification = await host.validBundle(source);
@@ -144,26 +175,41 @@ export const installMacHopper = async (
return { status: "failed", reason: "bundle" };
if (verification === "unverified_publisher")
return { status: "failed", reason: "publisher_verification_failed" };
- const stage = `${destination}.rea-stage`;
- if (
- !(await host.installBundle(
- source,
- destination,
- stage,
- destinationExists,
- ))
- )
- return { status: "failed", reason: "copy" };
+ installStage = "copy";
+ const installation = await host.installBundle(
+ source,
+ destination,
+ destinationExists,
+ );
+ if (installation.status === "failed")
+ return {
+ status: "failed",
+ reason: installation.reason,
+ diagnostic: installation.diagnostic,
+ ...(installation.cleanupFailure === undefined
+ ? {}
+ : { cleanupFailure: installation.cleanupFailure }),
+ };
+ bundleCleanupFailure = installation.cleanupFailure;
const launcherPath = join(destination, "Contents/MacOS/hopper");
- if (!(await host.launcherReady(launcherPath)))
- return { status: "failed", reason: "launcher_missing" };
- await host.openApplication(destination);
- return { status: "installed", launcherPath };
+ let openFailure: string | undefined;
+ try {
+ await host.openApplication(destination);
+ } catch (cause: unknown) {
+ openFailure = failureMessage(cause);
+ }
+ return {
+ status: "installed",
+ launcherPath,
+ ...(openFailure === undefined ? {} : { openFailure }),
+ };
})();
} catch (cause: unknown) {
- // Install-stage failures share the download reason; the stage is cleaned below.
- void cause;
- result = { status: "failed", reason: "download" };
+ result = {
+ status: "failed",
+ reason: installStage,
+ diagnostic: failureMessage(cause),
+ };
}
let cleanupFailure: string | undefined;
@@ -185,7 +231,106 @@ export const installMacHopper = async (
}
}
- return cleanupFailure === undefined ? result : { ...result, cleanupFailure };
+ const retainedCleanupFailure = [
+ bundleCleanupFailure,
+ cleanupFailure,
+ result.cleanupFailure,
+ ]
+ .filter((failure): failure is string => failure !== undefined)
+ .join(" ");
+ return retainedCleanupFailure === ""
+ ? result
+ : { ...result, cleanupFailure: retainedCleanupFailure };
+};
+
+/** Replace a bundle through a fresh same-volume root owned by this transaction. */
+export const installMacHopperBundle = async (
+ source: string,
+ destination: string,
+ replaceExisting: boolean,
+ operations: MacHopperBundleInstallOperations,
+ retainCleanup: (cleanup: () => Promise<void>) => void,
+): Promise<MacHopperBundleInstallResult> => {
+ const stagingRoot = await operations.createStagingRoot(dirname(destination));
+ const stagedBundle = join(stagingRoot, "new.app");
+ const previousBundle = join(stagingRoot, "previous.app");
+ let originalBackedUp = false;
+ let newCommitted = false;
+ let failureReason: "copy" | "launcher_missing" = "copy";
+
+ try {
+ await operations.copyBundle(source, stagedBundle);
+ failureReason = "launcher_missing";
+ await operations.requireLauncher(
+ join(stagedBundle, "Contents/MacOS/hopper"),
+ );
+ failureReason = "copy";
+ if (replaceExisting) {
+ await operations.rename(destination, previousBundle);
+ originalBackedUp = true;
+ }
+ await operations.rename(stagedBundle, destination);
+ newCommitted = true;
+ } catch (cause: unknown) {
+ const diagnostics = [failureMessage(cause)];
+ if (originalBackedUp && !newCommitted) {
+ try {
+ if (await operations.pathExists(destination))
+ throw new Error(
+ "destination now contains another installation; preserving the previous bundle in its owned staging root",
+ );
+ await operations.rename(previousBundle, destination);
+ originalBackedUp = false;
+ } catch (rollbackCause: unknown) {
+ diagnostics.push(`rollback failed: ${failureMessage(rollbackCause)}`);
+ const cleanupFailure = `The previous Hopper bundle remains owned at ${previousBundle}; cleanup will retry restoration only if the destination is empty.`;
+ retainCleanup(async () => {
+ if (originalBackedUp) {
+ if (await operations.pathExists(destination))
+ throw new Error(
+ `Hopper destination is occupied; preserving owned backup ${previousBundle}`,
+ );
+ await operations.rename(previousBundle, destination);
+ originalBackedUp = false;
+ }
+ await operations.removeStagingRoot(stagingRoot);
+ });
+ return {
+ status: "failed",
+ reason: failureReason,
+ diagnostic: diagnostics.join("; "),
+ cleanupFailure,
+ };
+ }
+ }
+ try {
+ await operations.removeStagingRoot(stagingRoot);
+ } catch (cleanupCause: unknown) {
+ const cleanupFailure = `Hopper staging root cleanup failed: ${failureMessage(cleanupCause)}`;
+ retainCleanup(() => operations.removeStagingRoot(stagingRoot));
+ diagnostics.push(cleanupFailure);
+ return {
+ status: "failed",
+ reason: failureReason,
+ diagnostic: diagnostics.join("; "),
+ cleanupFailure,
+ };
+ }
+ return {
+ status: "failed",
+ reason: failureReason,
+ diagnostic: diagnostics.join("; "),
+ };
+ }
+
+ try {
+ await operations.removeStagingRoot(stagingRoot);
+ return { status: "installed" };
+ } catch (cause: unknown) {
+ const cleanupFailure = `Hopper staging root cleanup failed after installation committed: ${failureMessage(cause)}`;
+ retainCleanup(() => operations.removeStagingRoot(stagingRoot));
+ return { status: "installed", cleanupFailure };
+ }
};
/** Compose installer paths and subprocesses from one selected caller context. */
@@ -200,7 +345,7 @@ export const systemMacHopperInstallHost = (
createMountDirectory: (path) => mkdir(path),
writePackage: (path, bytes) => writeFile(path, bytes, { mode: 0o600 }),
async mount(packagePath, mountPath) {
- return commandSucceeds(
+ await execFileAsync(
"hdiutil",
[
"attach",
@@ -210,20 +355,14 @@ export const systemMacHopperInstallHost = (
mountPath,
packagePath,
],
- environment,
+ { env: environment },
);
+ return true;
},
async unmount(mountPath) {
- if (
- !(await commandSucceeds(
- "hdiutil",
- ["detach", mountPath, "-force"],
- environment,
- ))
- )
- throw new Error(
- `hdiutil detach failed for ${JSON.stringify(mountPath)}`,
- );
+ await execFileAsync("hdiutil", ["detach", mountPath, "-force"], {
+ env: environment,
+ });
},
async appBundle(mountPath) {
const entries = await readdir(mountPath, { withFileTypes: true });
@@ -261,49 +400,32 @@ export const systemMacHopperInstallHost = (
await access(path);
return true;
} catch (cause: unknown) {
- // best-effort cleanup: optional existence probing; absence means missing.
- void cause;
- return false;
- }
- },
- async installBundle(source, destination, stage, replaceExisting) {
- const previous = `${stage}-previous`;
- try {
- await mkdir(join(homeDirectory, "Applications"), { recursive: true });
- await rm(stage, { recursive: true, force: true });
- await rm(previous, { recursive: true, force: true });
- await execFileAsync("ditto", [source, stage], { env: environment });
- await access(join(stage, "Contents/MacOS/hopper"));
- if (replaceExisting) await rename(destination, previous);
- await rename(stage, destination);
- if (replaceExisting)
- await rm(previous, { recursive: true, force: true });
- return true;
- } catch (cause: unknown) {
- // Install failure rolls back below; the false return reports it.
- void cause;
- await rm(stage, { recursive: true, force: true });
- if (replaceExisting) {
- try {
- await rename(previous, destination);
- } catch (rollbackCause: unknown) {
- // The original destination was not moved, or rollback is impossible.
- void rollbackCause;
- }
- }
- return false;
- }
- },
- async launcherReady(path) {
- try {
- await access(path);
- return true;
- } catch (cause: unknown) {
- // best-effort cleanup: optional launcher probing; absence means not ready.
- void cause;
- return false;
+ if (isMissingPath(cause)) return false;
+ throw cause;
}
},
+ installBundle: (source, destination, replaceExisting) =>
+ installMacHopperBundle(
+ source,
+ destination,
+ replaceExisting,
+ {
+ async createStagingRoot(parent) {
+ await mkdir(parent, { recursive: true });
+ return mkdtemp(join(parent, ".rea-hopper-stage-"));
+ },
+ copyBundle: async (bundle, staged) => {
+ await execFileAsync("ditto", [bundle, staged], {
+ env: environment,
+ });
+ },
+ requireLauncher: (path) => access(path).then(() => undefined),
+ pathExists,
+ rename,
+ removeStagingRoot: (path) => rm(path, { recursive: true }),
+ },
+ (cleanup) => pendingCleanup.add(cleanup),
+ ),
async openApplication(path) {
await execFileAsync("open", [path], { env: environment });
},
@@ -316,7 +438,7 @@ export const systemMacHopperInstallHost = (
await cleanup();
pendingCleanup.delete(cleanup);
} catch (cause: unknown) {
- failure ??= `Hopper DMG cleanup remains incomplete: ${failureMessage(cause)}`;
+ failure ??= `Hopper installer cleanup remains incomplete: ${failureMessage(cause)}`;
}
}
return failure;
@@ -343,13 +465,41 @@ const commandSucceeds = async (
await execFileAsync(command, args, { env: environment });
return true;
} catch (cause: unknown) {
- // best-effort cleanup: optional command probing; failure means unavailable.
- void cause;
- return false;
+ if (
+ typeof cause === "object" &&
+ cause !== null &&
+ "code" in cause &&
+ typeof cause.code === "number"
+ )
+ return false;
+ throw cause;
}
};
const failureMessage = (cause: unknown): string =>
- cause instanceof Error ? cause.message : String(cause);
+ cause instanceof Error
+ ? [
+ cause.message,
+ "stderr" in cause && typeof cause.stderr === "string"
+ ? cause.stderr.trim()
+ : "",
+ ]
+ .filter((value) => value !== "")
+ .join(": ")
+ : String(cause);
+const isMissingPath = (cause: unknown): boolean =>
+ typeof cause === "object" &&
+ cause !== null &&
+ "code" in cause &&
+ cause.code === "ENOENT";
+const pathExists = async (path: string): Promise<boolean> => {
+ try {
+ await access(path);
+ return true;
+ } catch (cause: unknown) {
+ if (isMissingPath(cause)) return false;
+ throw cause;
+ }
+};
const releaseSchema = z.object({
filename: z.string().url(),
file_length: z.string().regex(/^\d+$/u),
diff --git a/src/application/Setup.planning.test.ts b/src/application/Setup.planning.test.ts
index b0ae6479a..b7137b9b8 100644
--- a/src/application/Setup.planning.test.ts
+++ b/src/application/Setup.planning.test.ts
@@ -311,6 +311,25 @@ describe("setup plan application", () => {
expect(result.remediation).toBeUndefined();
});
+ it("records an installed Hopper when opening the app needs manual recovery", async () => {
+ const host = new FakeSetupHost("darwin");
+ host.installHopper = () =>
+ Promise.resolve({
+ status: "installed",
+ launcherPath: "/Applications/Hopper.app/Contents/MacOS/hopper",
+ warning:
+ "Hopper was installed, but macOS could not open it. Open it manually.",
+ });
+
+ const result = await runSetup(options(true, true), host);
+
+ expect(result).toMatchObject({
+ status: "needs_human",
+ appliedActions: ["installed_hopper"],
+ remediation: expect.stringContaining("Open it manually"),
+ });
+ });
+
it("reuses existing Hopper without selecting every detected client", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
diff --git a/src/application/Setup.ts b/src/application/Setup.ts
index a2a245988..2faaa4c5f 100644
--- a/src/application/Setup.ts
+++ b/src/application/Setup.ts
@@ -306,6 +306,7 @@ const runSetupWorkflow = async (
}
let selectedClients: readonly SetupClient[] =
planSelection.clientsToConfigure;
+ let hopperWarning: string | undefined;
if (
planSelection.installHopper &&
(interactiveApproval || options.installHopper)
@@ -322,7 +323,12 @@ const runSetupWorkflow = async (
clientStates,
});
if ("failure" in install) return install.failure;
- ({ hopperPath, providerEnvironment, selectedClients } = install);
+ ({
+ hopperPath,
+ providerEnvironment,
+ selectedClients,
+ warning: hopperWarning,
+ } = install);
}
const clientFailure = await configureDetectedClients({
host,
@@ -355,6 +361,7 @@ const runSetupWorkflow = async (
doctor.healthy,
hopperPath,
),
+ hopperWarning,
manualRemediation,
);
return {
@@ -407,14 +414,17 @@ const installHopperAction = async (input: {
};
}
input.appliedActions.push("installed_hopper");
+ const warning = [installed.warning, installed.cleanupFailure]
+ .filter((value): value is string => value !== undefined)
+ .join(" ");
emitProgress(input.options, {
actionId: "install_hopper",
label,
- state: installed.cleanupFailure === undefined ? "completed" : "warning",
+ state: warning === "" ? "completed" : "warning",
detail:
- installed.cleanupFailure === undefined
+ warning === ""
? installed.launcherPath
- : `${installed.launcherPath}; ${installed.cleanupFailure}`,
+ : `${installed.launcherPath}; ${warning}`,
});
const providerEnvironment = {
...input.providerEnvironment,
@@ -423,6 +433,7 @@ const installHopperAction = async (input: {
return {
hopperPath: installed.launcherPath,
providerEnvironment,
+ ...(warning === "" ? {} : { warning }),
selectedClients: await filterClientsNeedingConfigure(
input.host,
input.selectedClients,
diff --git a/src/application/SetupHost.ts b/src/application/SetupHost.ts
index 520380eab..f6f69a91f 100644
--- a/src/application/SetupHost.ts
+++ b/src/application/SetupHost.ts
@@ -203,18 +203,29 @@ export const systemSetupHost = (
return {
status: "installed",
launcherPath: result.launcherPath,
+ ...(result.openFailure === undefined
+ ? {}
+ : {
+ warning: `Hopper was installed, but macOS could not open it: ${result.openFailure}. Open ${result.launcherPath} manually to complete first-run setup.`,
+ }),
...(result.cleanupFailure === undefined
? {}
: { cleanupFailure: result.cleanupFailure }),
};
const failure = setupInstallFailure(result.reason);
- if (result.cleanupFailure === undefined) return failure;
- return failure.status === "failed"
- ? {
- ...failure,
- remediation: `${failure.remediation} ${result.cleanupFailure}`,
- }
- : failure;
+ const diagnostic = setupInstallerDiagnostic(result.diagnostic);
+ return {
+ ...failure,
+ remediation: [
+ failure.remediation,
+ ...(diagnostic === undefined
+ ? []
+ : [`Installer detail: ${diagnostic}`]),
+ ...(result.cleanupFailure === undefined
+ ? []
+ : [result.cleanupFailure]),
+ ].join(" "),
+ };
},
detectedClients: () => detectClients(homeDirectory, platform, environment),
supportedClients: () =>
@@ -248,6 +259,21 @@ export const systemSetupHost = (
};
};
+const setupInstallerDiagnostic = (
+ value: string | undefined,
+): string | undefined => {
+ if (value === undefined) return undefined;
+ const normalized = value
+ .replace(/\u001b(?:\[[0-9;?]*[ -/]*[@-~]|\([0-9A-Za-z]|[@-Z\\^_])/gu, "")
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/gu, "")
+ .replace(/\s+/gu, " ")
+ .trim();
+ if (normalized === "") return undefined;
+ return normalized.length <= 400
+ ? normalized
+ : `${normalized.slice(0, 397).trimEnd()}...`;
+};
+
const clientConfigurationOperations = (resources: ArtifactResourceScope) => ({
configureClient: (
client: SetupClient,
diff --git a/src/application/SetupInstallFailure.ts b/src/application/SetupInstallFailure.ts
index 25f020e86..635918ca1 100644
--- a/src/application/SetupInstallFailure.ts
+++ b/src/application/SetupInstallFailure.ts
@@ -23,6 +23,7 @@ export type SetupHopperInstallResult =
readonly status: "installed";
readonly launcherPath: string;
readonly cleanupFailure?: string;
+ readonly warning?: string;
}
| {
readonly status: "failed";
@@ -30,6 +31,11 @@ export type SetupHopperInstallResult =
readonly remediation: string;
};
+export type SetupHopperInstallFailure = Extract<
+ SetupHopperInstallResult,
+ { readonly status: "failed" }
+>;
+
export type HopperInstallFailureReason =
| "unsupported_host"
| "release_metadata"
@@ -93,7 +99,7 @@ const packageManagerRemediation = (
export const setupInstallFailure = (
reason: HopperInstallFailureReason,
packageFailure?: LinuxPackageInstallFailure,
-): SetupHopperInstallResult => {
+): SetupHopperInstallFailure => {
switch (reason) {
case "unsupported_host":
return {
diff --git a/src/setupEnvironment.test.ts b/src/setupEnvironment.test.ts
index d40533656..a4a777c85 100644
--- a/src/setupEnvironment.test.ts
+++ b/src/setupEnvironment.test.ts
@@ -5,6 +5,7 @@ import { join } from "node:path";
import { afterEach, expect, it, vi } from "vitest";
import { createDoctorHostFixture } from "./application/Doctor.fixture.js";
+import * as macHopperInstaller from "./application/MacHopper.js";
import { runSetup } from "./application/Setup.js";
import { options } from "./application/Setup.fixture.js";
import { systemSetupHost } from "./application/SetupHost.js";
@@ -92,6 +93,35 @@ it("composes provider diagnostics from selected configuration rather than ambien
expect(JSON.stringify(inspections)).not.toContain("/ambient/");
});
+it("includes the macOS Hopper installer diagnostic in setup remediation", async () => {
+ const install = vi
+ .spyOn(macHopperInstaller, "installMacHopper")
+ .mockResolvedValue({
+ status: "failed",
+ reason: "mount",
+ diagnostic: "hdiutil attach exited 1:\n\u001b[31mresource busy\u001b[0m",
+ });
+ const host = systemSetupHost(
+ createDoctorHostFixture({ platform: "darwin" }),
+ { HOME: "/fixture/home", USERPROFILE: "/fixture/home" },
+ );
+ try {
+ const result = await host.installHopper(false);
+ expect(result).toMatchObject({
+ status: "failed",
+ code: "mount_failed",
+ remediation: expect.stringContaining(
+ "Installer detail: hdiutil attach exited 1: resource busy",
+ ),
+ });
+ if (result.status !== "failed") throw new Error("expected setup failure");
+ expect(result.remediation).not.toContain("\u001b");
+ } finally {
+ await host.close?.();
+ install.mockRestore();
+ }
+});
+
it("preserves a validated selected JEB endpoint in setup registrations without claiming live readiness", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-jeb-setup-"));
const endpoint = "http://127.0.0.1:8425/mcp/";
diff --git a/tests/boundary/filesystem/macHopperInstallOwnership.test.ts b/tests/boundary/filesystem/macHopperInstallOwnership.test.ts
new file mode 100644
index 000000000..04b47c2fc
--- /dev/null
+++ b/tests/boundary/filesystem/macHopperInstallOwnership.test.ts
@@ -0,0 +1,275 @@
+import {
+ access,
+ mkdir,
+ mkdtemp,
+ readFile,
+ rename,
+ rm,
+ stat,
+ writeFile,
+} from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { afterEach, describe, expect, it } from "vitest";
+
+import {
+ installMacHopperBundle,
+ type MacHopperBundleInstallOperations,
+} from "../../../src/application/MacHopper.js";
+
+const roots: string[] = [];
+
+afterEach(async () => {
+ await Promise.all(
+ roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
+ );
+});
+
+const temporaryRoot = async (): Promise<string> => {
+ const root = await mkdtemp(join(tmpdir(), "rea-hopper-owned-stage-test-"));
+ roots.push(root);
+ return root;
+};
+
+const bundleFiles = (
+ overrides: Partial<MacHopperBundleInstallOperations> = {},
+ captureRoot?: (root: string, mode: number) => void,
+): MacHopperBundleInstallOperations => ({
+ async createStagingRoot(parent) {
+ await mkdir(parent, { recursive: true });
+ const root = await mkdtemp(join(parent, ".rea-hopper-stage-"));
+ captureRoot?.(root, (await stat(root)).mode & 0o777);
+ return root;
+ },
+ async copyBundle(source, stage) {
+ const executable = join(stage, "Contents/MacOS/hopper");
+ await mkdir(join(stage, "Contents/MacOS"), { recursive: true });
+ await writeFile(executable, source);
+ },
+ requireLauncher: async (path) => access(path).then(() => undefined),
+ async pathExists(path) {
+ try {
+ await access(path);
+ return true;
+ } catch (cause: unknown) {
+ if (
+ typeof cause === "object" &&
+ cause !== null &&
+ "code" in cause &&
+ cause.code === "ENOENT"
+ )
+ return false;
+ throw cause;
+ }
+ },
+ rename,
+ removeStagingRoot: (path) => rm(path, { recursive: true }),
+ ...overrides,
+});
+
+const writeBundle = async (path: string, content: string): Promise<void> => {
+ await mkdir(join(path, "Contents/MacOS"), { recursive: true });
+ await writeFile(join(path, "Contents/MacOS/hopper"), content);
+};
+
+describe("macOS Hopper staging isolation", () => {
+ it("rejects a staged bundle without its launcher before moving the original", async () => {
+ const root = await temporaryRoot();
+ const destination = join(root, "Applications/Hopper Disassembler.app");
+ await writeBundle(destination, "original installation");
+ let stagingRoot = "";
+
+ const result = await installMacHopperBundle(
+ "replacement without launcher",
+ destination,
+ true,
+ bundleFiles(
+ {
+ async copyBundle(_source, stage) {
+ await mkdir(join(stage, "Contents/MacOS"), { recursive: true });
+ },
+ },
+ (path) => (stagingRoot = path),
+ ),
+ () => undefined,
+ );
+
+ expect(result).toMatchObject({
+ status: "failed",
+ reason: "launcher_missing",
+ diagnostic: expect.stringContaining("hopper"),
+ });
+ expect(
+ await readFile(join(destination, "Contents/MacOS/hopper"), "utf8"),
+ ).toBe("original installation");
+ await expect(
+ access(join(stagingRoot, "previous.app")),
+ ).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+ await expect(access(stagingRoot)).rejects.toMatchObject({ code: "ENOENT" });
+ });
+
+ it("leaves pre-existing staging-looking sibling directories untouched", async () => {
+ const root = await temporaryRoot();
+ const applications = join(root, "Applications");
+ const destination = join(applications, "Hopper Disassembler.app");
+ const oldStage = `${destination}.rea-stage`;
+ const oldPrevious = `${oldStage}-previous`;
+ await Promise.all([
+ writeBundle(oldStage, "user stage sentinel"),
+ writeBundle(oldPrevious, "user backup sentinel"),
+ ]);
+ let stagingRoot = "";
+ let stagingMode = 0;
+
+ await expect(
+ installMacHopperBundle(
+ "new bundle",
+ destination,
+ false,
+ bundleFiles({}, (path, mode) => {
+ stagingRoot = path;
+ stagingMode = mode;
+ }),
+ () => undefined,
+ ),
+ ).resolves.toEqual({ status: "installed" });
+
+ expect(
+ await readFile(join(oldStage, "Contents/MacOS/hopper"), "utf8"),
+ ).toBe("user stage sentinel");
+ expect(
+ await readFile(join(oldPrevious, "Contents/MacOS/hopper"), "utf8"),
+ ).toBe("user backup sentinel");
+ expect(
+ await readFile(join(destination, "Contents/MacOS/hopper"), "utf8"),
+ ).toBe("new bundle");
+ expect(stagingMode).toBe(0o700);
+ await expect(access(stagingRoot)).rejects.toMatchObject({ code: "ENOENT" });
+ });
+});
+
+describe("macOS Hopper replacement ownership", () => {
+ it("keeps the committed replacement when owned-root cleanup fails", async () => {
+ const root = await temporaryRoot();
+ const destination = join(root, "Applications/Hopper Disassembler.app");
+ await writeBundle(destination, "previous installation");
+ let stagingRoot = "";
+ let failedCleanup = false;
+ const retained: (() => Promise<void>)[] = [];
+
+ const result = await installMacHopperBundle(
+ "new installation",
+ destination,
+ true,
+ bundleFiles(
+ {
+ removeStagingRoot: async (path) => {
+ if (!failedCleanup) {
+ failedCleanup = true;
+ throw new Error("simulated cleanup denial");
+ }
+ await rm(path, { recursive: true });
+ },
+ },
+ (path) => (stagingRoot = path),
+ ),
+ (cleanup) => retained.push(cleanup),
+ );
+
+ expect(result).toMatchObject({
+ status: "installed",
+ cleanupFailure: expect.stringContaining("simulated cleanup denial"),
+ });
+ expect(
+ await readFile(join(destination, "Contents/MacOS/hopper"), "utf8"),
+ ).toBe("new installation");
+ expect(
+ await readFile(
+ join(stagingRoot, "previous.app/Contents/MacOS/hopper"),
+ "utf8",
+ ),
+ ).toBe("previous installation");
+ expect(retained).toHaveLength(1);
+
+ await retained[0]!();
+ expect(
+ await readFile(join(destination, "Contents/MacOS/hopper"), "utf8"),
+ ).toBe("new installation");
+ await expect(access(stagingRoot)).rejects.toMatchObject({ code: "ENOENT" });
+ });
+
+ it("retains a moved backup and never overwrites a later destination on rollback", async () => {
+ const root = await temporaryRoot();
+ const destination = join(root, "Applications/Hopper Disassembler.app");
+ await writeBundle(destination, "original installation");
+ let stagingRoot = "";
+ let backupMoved = false;
+ let concurrentInstallCreated = false;
+ const rollbackRetained: (() => Promise<void>)[] = [];
+ const realRename = rename;
+
+ const result = await installMacHopperBundle(
+ "replacement installation",
+ destination,
+ true,
+ bundleFiles(
+ {
+ rename: async (source, target) => {
+ if (source === destination && target.endsWith("/previous.app")) {
+ await realRename(source, target);
+ backupMoved = true;
+ return;
+ }
+ if (source.endsWith("/new.app") && target === destination) {
+ await writeBundle(destination, "later installation");
+ concurrentInstallCreated = true;
+ throw new Error("simulated competing install");
+ }
+ await realRename(source, target);
+ },
+ },
+ (path) => (stagingRoot = path),
+ ),
+ (cleanup) => rollbackRetained.push(cleanup),
+ );
+
+ expect(result).toMatchObject({
+ status: "failed",
+ diagnostic: expect.stringContaining("simulated competing install"),
+ cleanupFailure: expect.stringContaining(
+ "previous Hopper bundle remains owned",
+ ),
+ });
+ expect(backupMoved).toBe(true);
+ expect(concurrentInstallCreated).toBe(true);
+ expect(
+ await readFile(join(destination, "Contents/MacOS/hopper"), "utf8"),
+ ).toBe("later installation");
+ expect(
+ await readFile(
+ join(stagingRoot, "previous.app/Contents/MacOS/hopper"),
+ "utf8",
+ ),
+ ).toBe("original installation");
+ expect(rollbackRetained).toHaveLength(1);
+
+ await expect(rollbackRetained[0]!()).rejects.toThrow(
+ "destination is occupied",
+ );
+ expect(
+ await readFile(
+ join(stagingRoot, "previous.app/Contents/MacOS/hopper"),
+ "utf8",
+ ),
+ ).toBe("original installation");
+ await rm(destination, { recursive: true });
+ await rollbackRetained[0]!();
+ expect(
+ await readFile(join(destination, "Contents/MacOS/hopper"), "utf8"),
+ ).toBe("original installation");
+ await expect(access(stagingRoot)).rejects.toMatchObject({ code: "ENOENT" });
+ });
+});