Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,19 @@ host mount and the rest of `/tmp` remain unchanged; this fallback never invokes
`sudo`. `rea doctor --provider hopper --json` reports the selected
strategy and both host and effective mount facts.

The supported Linux demo forwards additional launches into its existing
application, even across private displays. REA therefore reserves one Linux
Hopper application per user across cooperating REA processes. A competing
CLI or MCP session receives the owning session ID before Hopper is launched,
for both the same target and a different target. Switch targets through that
MCP session, or close it before starting another session. Closing the owner
releases the reservation. This does not attach to or claim ownership of
manually opened Hopper applications.

Stale lease recovery is serialized. If an interrupted recovery leaves its
reservation directory, the diagnostic identifies that exact path. Stop REA
sessions before removing that recovery directory and retrying.

### Launcher paths and troubleshooting

On macOS, REA uses
Expand Down
7 changes: 6 additions & 1 deletion docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,12 @@ subsequent wire recovery and clean shutdown. Caller timeout does not interrupt
Hopper's synchronous native operation. Socket boundary tests deterministically
cover active and queued expiry, late replies and timer cleanup.

The Linux demo lane remains a separate `verify:hopper:linux` command.
The Linux demo lane remains a separate `verify:hopper:linux` command. Its
lifecycle checks attempt competing CLI launches for the active target and a
different target, requiring rejection before either can change the owning
MCP session's documents or procedures. Lease boundary tests also preserve
unresponsive or malformed live endpoints while allowing confirmed stale
sockets to recover.

`verify:hopper:fat` is a separate macOS lane requiring installed Hopper and the
existing Xcode clang/lipo toolchain. It compiles arm64/x86-64 thin executables and
Expand Down
12 changes: 12 additions & 0 deletions scripts/lib/real-hopper-boundaries.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import Ajv from "ajv/dist/2020.js";
import addFormats from "ajv-formats";
import { mcpTextValue, requireMcpResult } from "./mcp-verifier-results.mjs";
import { verifyHopperCliSelectors } from "./real-hopper-cli-selectors.mjs";
import { verifyLinuxHopperLaunchIsolation } from "./real-hopper-session-isolation.mjs";
import { verifyHopperNavigationAndText } from "./real-hopper-navigation.mjs";
import { verifyHopperWorkflows } from "./real-hopper-workflows.mjs";
import {
Expand Down Expand Up @@ -327,6 +328,16 @@ export async function verifyHopperLifecycleAndCli(client, options, targets) {
procedure: entry.value,
});
const firstDocument = await call("current_document");
const linuxApplicationIsolation =
process.platform === "linux"
? await verifyLinuxHopperLaunchIsolation({
call,
runCli,
dispatcher: new URL("../rea.mjs", import.meta.url).pathname,
primary,
secondary,
})
: null;
await call("open_binary", { path: secondary });
const secondDocument = await call("current_document");
assert.notEqual(firstDocument, secondDocument);
Expand Down Expand Up @@ -464,6 +475,7 @@ export async function verifyHopperLifecycleAndCli(client, options, targets) {
cliNamedSelectorParity,
callerCancellationRecovered: true,
closedDocumentAbsent: true,
linuxApplicationIsolation,
};
} finally {
await call("close_binary");
Expand Down
53 changes: 53 additions & 0 deletions scripts/lib/real-hopper-session-isolation.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import assert from "node:assert/strict";

/** Prove competing Linux launches cannot forward documents into the active MCP owner. */
export async function verifyLinuxHopperLaunchIsolation({
call,
runCli,
dispatcher,
primary,
secondary,
}) {
const documents = await call("list_documents");
const current = await call("current_document");
const procedures = await call("list_procedures");
for (const target of [primary, secondary]) {
let failure;
try {
await runCli([
dispatcher,
"inspect",
target,
"--provider",
"hopper",
"--format",
"json",
]);
} catch (error) {
assert.equal(error.code, 1);
failure = JSON.parse(error.stdout);
}
assert.ok(
failure,
"A competing CLI launch was allowed to reach Linux Hopper",
);
assert.equal(failure.code, "provider_unavailable");
assert.match(
failure.message,
/Linux Hopper is already active in REA session/u,
);
assert.ok(failure.message.includes(target));
assert.deepEqual(
await call("list_documents"),
documents,
"A rejected CLI launch changed the owning session's documents",
);
assert.equal(await call("current_document"), current);
assert.deepEqual(await call("list_procedures"), procedures);
}
return {
sameTargetRejected: true,
differentTargetRejected: true,
ownerDocumentsPreserved: true,
};
}
50 changes: 33 additions & 17 deletions src/hopper/BridgeLauncher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ import {
type HopperMachOImage,
} from "./HopperMachOImage.js";

import { acquireHopperTargetLease } from "./HopperTargetLease.js";
import {
acquireHopperTargetLease,
acquireLinuxHopperApplicationLease,
} from "./HopperTargetLease.js";
import type { HopperTargetLease } from "./HopperTargetLease.js";

const execFileAsync = promisify(execFile);
Expand Down Expand Up @@ -96,6 +99,7 @@ export type HopperApplicationLauncherOptions =
export interface HopperApplicationLauncherDependencies {
readonly platform?: NodeJS.Platform;
readonly acquireTargetLease?: typeof acquireHopperTargetLease;
readonly acquireApplicationLease?: typeof acquireLinuxHopperApplicationLease;
readonly selectPrivateDisplay?: (options: {
readonly helperPath: string;
readonly signal?: AbortSignal;
Expand Down Expand Up @@ -131,7 +135,7 @@ export class HopperApplicationLauncher implements BridgeLauncher {
HopperStartError | HopperCancelledError | HopperProcessError
>
> {
const leaseResult = await this.#acquireTargetLease(session.runId);
const leaseResult = await this.#acquireLaunchLease(session.runId);
if (!leaseResult.ok) return leaseResult;
const lease = leaseResult.value;
let leaseTransferred = false;
Expand Down Expand Up @@ -267,32 +271,44 @@ export class HopperApplicationLauncher implements BridgeLauncher {
}
}

async #acquireTargetLease(
async #acquireLaunchLease(
runId: string,
): Promise<Result<HopperTargetLease | undefined, HopperStartError>> {
if ((this.dependencies.platform ?? process.platform) !== "darwin")
return ok(undefined);
const platform = this.dependencies.platform ?? process.platform;
const applicationLease =
platform === "linux" && usesLinuxDemo(this.options);
if (!applicationLease && platform !== "darwin") return ok(undefined);
try {
const acquisition = await (
this.dependencies.acquireTargetLease ?? acquireHopperTargetLease
)({
targetPath: this.options.targetPath,
targetKind: this.options.targetKind,
loaderArgs: this.options.loaderArgs,
runId,
});
const acquisition = applicationLease
? await (
this.dependencies.acquireApplicationLease ??
acquireLinuxHopperApplicationLease
)({ runId })
: await (
this.dependencies.acquireTargetLease ?? acquireHopperTargetLease
)({
targetPath: this.options.targetPath,
targetKind: this.options.targetKind,
loaderArgs: this.options.loaderArgs,
runId,
});
if (!acquisition.acquired)
return err(
new HopperStartError({
ownerRunId: acquisition.owner.runId,
userMessage:
`This Hopper target is already open in REA session ${acquisition.owner.runId}. ` +
"Use that REA session or close it before opening this target again.",
userMessage: applicationLease
? `Linux Hopper is already active in REA session ${acquisition.owner.runId}; it cannot open ${this.options.targetPath} in another session. This build forwards new launches to the existing application. Use the owning REA session to switch targets, or close it before retrying.`
: `This Hopper target is already open in REA session ${acquisition.owner.runId}. ` +
"Use that REA session or close it before opening this target again.",
}),
);
return ok(acquisition.lease);
} catch (cause: unknown) {
return err(new HopperStartError({ cause }));
return err(
cause instanceof HopperStartError
? cause
: new HopperStartError({ cause }),
);
}
}

Expand Down
150 changes: 148 additions & 2 deletions src/hopper/HopperTargetLease.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import { mkdtemp, rm } from "node:fs/promises";
import { execFile } from "node:child_process";
import { once } from "node:events";
import { lstat, mkdir, mkdtemp, readdir, rm, rmdir } from "node:fs/promises";
import { createServer, type Socket } from "node:net";
import { join } from "node:path";
import { promisify } from "node:util";

import { afterEach, describe, expect, it } from "vitest";

import { acquireHopperTargetLease } from "./HopperTargetLease.js";
import {
acquireHopperTargetLease,
acquireLinuxHopperApplicationLease,
} from "./HopperTargetLease.js";

const directories: string[] = [];

Expand Down Expand Up @@ -66,6 +73,145 @@ describe("Hopper target leases", () => {
});
});

describe("Linux Hopper application leases", () => {
it("reserves the shared application until its owner releases it", async () => {
const directory = await temporaryDirectory();
const first = await acquireLinuxHopperApplicationLease({
directory,
runId: "first",
});
expect(first.acquired).toBe(true);
if (!first.acquired) return;
try {
expect(
await acquireLinuxHopperApplicationLease({
directory,
runId: "second",
}),
).toMatchObject({
acquired: false,
owner: { runId: "first", processId: process.pid },
});
} finally {
await first.lease.release();
}
const reopened = await acquireLinuxHopperApplicationLease({
directory,
runId: "third",
});
expect(reopened.acquired).toBe(true);
if (reopened.acquired) await reopened.lease.release();
});

it.each(["silent", "malformed", "invalid-pid", "closed"] as const)(
"keeps a live endpoint when its owner response is %s",
async (behavior) => {
const directory = await temporaryDirectory();
const socketPath = await releasedApplicationSocket(directory);
let responsive = false;
const sockets = new Set<Socket>();
const owner = { runId: "existing-owner", processId: process.pid };
const server = createServer((socket) => {
sockets.add(socket);
socket.on("close", () => sockets.delete(socket));
socket.on("error", () => undefined);
if (responsive) socket.end(`${JSON.stringify(owner)}\n`);
else if (behavior === "malformed") socket.end("not JSON\n");
else if (behavior === "invalid-pid")
socket.end('{"runId":"existing-owner","processId":-1}\n');
else if (behavior === "closed") socket.end();
});
server.listen(socketPath);
await once(server, "listening");
try {
await expect(
acquireLinuxHopperApplicationLease({ directory, runId: "new-owner" }),
).rejects.toMatchObject({
_tag: "HopperStartError",
userMessage: expect.stringContaining("left unchanged"),
});
expect((await lstat(socketPath)).isSocket()).toBe(true);
responsive = true;
expect(
await acquireLinuxHopperApplicationLease({
directory,
runId: "retry",
}),
).toEqual({
acquired: false,
owner,
});
} finally {
for (const socket of sockets) socket.destroy();
server.close();
await once(server, "close");
}
},
);

it("recovers a socket left by a process that exited without releasing it", async () => {
const directory = await temporaryDirectory();
const socketPath = await releasedApplicationSocket(directory);
await leaveStaleSocket(socketPath);
expect((await lstat(socketPath)).isSocket()).toBe(true);
const recovered = await acquireLinuxHopperApplicationLease({
directory,
runId: "recovered",
});
expect(recovered.acquired).toBe(true);
if (recovered.acquired) await recovered.lease.release();
});
});

it("leaves a stale socket unchanged while another process reserves its recovery", async () => {
const directory = await temporaryDirectory();
const socketPath = await releasedApplicationSocket(directory);
await leaveStaleSocket(socketPath);
const recoveryPath = `${socketPath}.recovery`;
await mkdir(recoveryPath, { mode: 0o700 });
const stale = await lstat(socketPath);
await expect(
acquireLinuxHopperApplicationLease({ directory, runId: "competing" }),
).rejects.toMatchObject({
_tag: "HopperStartError",
userMessage: expect.stringContaining(recoveryPath),
});
expect((await lstat(socketPath)).ino).toBe(stale.ino);
await rmdir(recoveryPath);
const recovered = await acquireLinuxHopperApplicationLease({
directory,
runId: "after-recovery",
});
expect(recovered.acquired).toBe(true);
if (recovered.acquired) await recovered.lease.release();
expect(await readdir(directory)).toEqual([]);
});

const leaveStaleSocket = async (socketPath: string): Promise<void> => {
await promisify(execFile)(process.execPath, [
"--input-type=module",
"-e",
'import {createServer} from "node:net"; createServer().listen(process.argv[1],()=>process.exit(0));',
socketPath,
]);
};

const releasedApplicationSocket = async (
directory: string,
): Promise<string> => {
const initial = await acquireLinuxHopperApplicationLease({
directory,
runId: "initial",
});
if (!initial.acquired)
throw new Error("Initial application lease was unavailable");
const [name] = await readdir(directory);
await initial.lease.release();
if (name === undefined)
throw new Error("Application lease did not create a socket");
return join(directory, name);
};

const leaseInput = {
targetPath: "/tmp/sample-binary",
targetKind: "executable" as const,
Expand Down
Loading
Loading