fix(javascript): integrate current provider timeout recovery
Include the main-branch Hopper startup timeout normalization already merged in #1866 so combined CI retains launcher diagnostics when either timer fires. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
This commit is contained in:
co-authored by
factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Kaoru0822
commit
47f8156efe
@@ -1,4 +1,5 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { join, resolve } from "node:path";
|
||||
@@ -770,6 +771,173 @@ describe("export writes in function evaluation contexts", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("retains namespace re-export bindings and provenance through stdio MCP and CLI", async () => {
|
||||
const root = await createTestTempDirectory("rea-namespace-reexports-");
|
||||
const declarations = [
|
||||
{ clause: "* as ns", name: "ns", imported: "*" },
|
||||
{
|
||||
clause: '* as "namespace value"',
|
||||
name: "namespace value",
|
||||
imported: "*",
|
||||
},
|
||||
{ clause: "{ value as forwarded }", name: "forwarded", imported: "value" },
|
||||
{ clause: "*", name: "*", imported: "*" },
|
||||
];
|
||||
const source = declarations
|
||||
.map(({ clause }) => `export ${clause} from "./dependency.mjs";`)
|
||||
.join("\n");
|
||||
const path = join(root, "barrel.mjs");
|
||||
await Promise.all([
|
||||
writeFile(path, source),
|
||||
writeFile(join(root, "dependency.mjs"), "export const value = 42;"),
|
||||
]);
|
||||
// Node executes only this test-owned fixture to establish its actual exports.
|
||||
for (const name of ["ns", "namespace value"])
|
||||
expect(await runtimeExport(path, name)).toEqual({ value: 42 });
|
||||
for (const name of ["forwarded", "value"])
|
||||
expect(await runtimeExport(path, name)).toBe(42);
|
||||
|
||||
const documents = [
|
||||
await analyzeThroughMcp(root),
|
||||
await runCli(["analyze-javascript-application", root, "--json"]),
|
||||
];
|
||||
const digest = createHash("sha256").update(source).digest("hex");
|
||||
for (const document of documents) {
|
||||
const { graph } = applicationEnvelope.parse(document).normalized_result;
|
||||
const sourceModule = graph.nodes.find(({ observations }) =>
|
||||
observations.some(
|
||||
({ properties }) =>
|
||||
properties.semantic_role === "source-module" &&
|
||||
properties.path === "barrel.mjs",
|
||||
),
|
||||
);
|
||||
expect(sourceModule?.observations[0]?.properties).toMatchObject({
|
||||
export_relationships: 4,
|
||||
export_names: ["*", "forwarded", "namespace value", "ns"],
|
||||
omitted_export_names: 0,
|
||||
});
|
||||
for (const [index, { clause, name, imported }] of declarations.entries()) {
|
||||
const exported = graph.nodes.find(({ observations }) =>
|
||||
observations.some(
|
||||
({ properties }) =>
|
||||
properties.semantic_role === "export-binding" &&
|
||||
properties.module_path === "barrel.mjs" &&
|
||||
properties.exported_name === name,
|
||||
),
|
||||
);
|
||||
const observation = exported?.observations[0];
|
||||
expect(observation?.properties).toMatchObject({
|
||||
relationship_kind: "re-export",
|
||||
declared_specifier: "./dependency.mjs",
|
||||
imported_name: imported,
|
||||
local_name: null,
|
||||
});
|
||||
if (imported === "*" && name !== "*")
|
||||
expect(observation?.evidence).toMatchObject({
|
||||
artifact: { available: true, sha256: digest },
|
||||
location: {
|
||||
available: true,
|
||||
value: {
|
||||
kind: "source-range",
|
||||
source: "barrel.mjs",
|
||||
start: { line: index + 1, column: 7 },
|
||||
end: { line: index + 1, column: 7 + clause.length },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
source_node_id: sourceModule?.node_id,
|
||||
target_node_id: exported?.node_id,
|
||||
relation: "exposes",
|
||||
properties: expect.objectContaining({ exported_name: name }),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: observation?.evidence.artifact,
|
||||
location: observation?.evidence.location,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
source_node_id: exported?.node_id,
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: "re-export",
|
||||
imported_name: imported,
|
||||
exported_name: name,
|
||||
resolved_path: "dependency.mjs",
|
||||
resolution_status: "resolved",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
expect(graph.coverage).toMatchObject({
|
||||
status: "complete",
|
||||
omitted_count: 0,
|
||||
truncated: false,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("excludes erased namespace type exports through stdio MCP and CLI", async () => {
|
||||
const root = await createTestTempDirectory("rea-namespace-type-exports-");
|
||||
const path = join(root, "barrel.mts");
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
path,
|
||||
'export type * as Types from "./types.mjs";\nexport * as Values from "./values.mjs";',
|
||||
),
|
||||
writeFile(
|
||||
join(root, "types.mjs"),
|
||||
'throw new Error("Type-only dependency must not execute");',
|
||||
),
|
||||
writeFile(join(root, "values.mjs"), "export const value = 42;"),
|
||||
]);
|
||||
// Node strips the type-only declaration without loading its throwing target.
|
||||
expect(await runtimeExport(path, "Types")).toBeUndefined();
|
||||
expect(await runtimeExport(path, "Values")).toEqual({ value: 42 });
|
||||
|
||||
const documents = [
|
||||
await analyzeThroughMcp(root),
|
||||
await runCli(["analyze-javascript-application", root, "--json"]),
|
||||
];
|
||||
for (const document of documents) {
|
||||
const { graph } = applicationEnvelope.parse(document).normalized_result;
|
||||
const observations = graph.nodes.flatMap(
|
||||
({ observations }) => observations,
|
||||
);
|
||||
expect(
|
||||
observations.find(
|
||||
({ properties }) =>
|
||||
properties.semantic_role === "source-module" &&
|
||||
properties.path === "barrel.mts",
|
||||
)?.properties,
|
||||
).toMatchObject({
|
||||
export_relationships: 1,
|
||||
export_names: ["Values"],
|
||||
omitted_export_names: 0,
|
||||
});
|
||||
expect(
|
||||
observations.filter(
|
||||
({ properties }) =>
|
||||
properties.semantic_role === "export-binding" &&
|
||||
properties.module_path === "barrel.mts" &&
|
||||
properties.exported_name === "Types",
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
graph.edges.filter(
|
||||
({ properties }) => properties.exported_name === "Types",
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(graph.coverage).toMatchObject({
|
||||
status: "complete",
|
||||
omitted_count: 0,
|
||||
truncated: false,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const expectRuntimeExports = async (
|
||||
fixture: Awaited<ReturnType<typeof analyzeVersions>>,
|
||||
expected: (count: number) => unknown,
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { access, copyFile, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { expect, onTestFinished, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js";
|
||||
import { acquireHopperTargetLease } from "../../../src/hopper/HopperTargetLease.js";
|
||||
|
||||
const statusSchema = z.object({ result: z.object({ open: z.boolean() }) });
|
||||
const test = workspaceCliTest.skipIf(process.platform !== "darwin");
|
||||
|
||||
test(
|
||||
"retains a denial-shaped failure when caller arguments can alter the helper's AppleScript",
|
||||
{ timeout: 90_000 },
|
||||
async ({ workspace }) => {
|
||||
for (const source of ["target", "loader"] as const) {
|
||||
const target = workspace.path(
|
||||
source === "target" ? 'quoted"target' : "loader-target",
|
||||
);
|
||||
await copyFile("/usr/bin/true", target);
|
||||
const mode = await workspace.write(
|
||||
`${source}-mode`,
|
||||
"denied-after-handoff",
|
||||
);
|
||||
const receipt = workspace.path(`${source}-bootstrap`);
|
||||
const loaderArgs = [
|
||||
resolve("tests/fixtures/hopperLaunchAdmission.mjs"),
|
||||
mode,
|
||||
receipt,
|
||||
...(source === "loader" ? ['caller"loader'] : []),
|
||||
];
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [resolve("dist/main.js")],
|
||||
stderr: "pipe",
|
||||
env: {
|
||||
...workspace.environment,
|
||||
PATH: process.env.PATH ?? "",
|
||||
REA_ANALYSIS_PROVIDER: "hopper",
|
||||
HOPPER_LAUNCHER_PATH: process.execPath,
|
||||
HOPPER_LOADER_ARGS_JSON: JSON.stringify(loaderArgs),
|
||||
REA_LOG_LEVEL: "silent",
|
||||
},
|
||||
});
|
||||
const mcp = new Client({ name: "hopper-literal-boundary", version: "1" });
|
||||
let runtime: string | undefined;
|
||||
onTestFinished(async () => {
|
||||
// SDK close can return immediately after SIGKILL. Wait for its actual
|
||||
// child-close event before recovering this process's retained lease.
|
||||
let serverExited: Promise<void> | undefined;
|
||||
if (transport.pid !== null) {
|
||||
const onclose = transport.onclose;
|
||||
serverExited = new Promise<void>((resolveExit) => {
|
||||
transport.onclose = () => {
|
||||
onclose?.();
|
||||
resolveExit();
|
||||
};
|
||||
});
|
||||
}
|
||||
await mcp.close();
|
||||
await transport.close();
|
||||
await serverExited;
|
||||
// The fixture created only this marker, never a native GUI document.
|
||||
if (runtime !== undefined)
|
||||
await rm(runtime, { recursive: true, force: true });
|
||||
const acquired = await acquireHopperTargetLease({
|
||||
targetPath: target,
|
||||
targetKind: "executable",
|
||||
loaderArgs,
|
||||
runId: "literal-boundary-test-cleanup",
|
||||
});
|
||||
if (!acquired.acquired) throw new Error("Fixture lease remained live");
|
||||
await acquired.lease.release();
|
||||
});
|
||||
await mcp.connect(transport);
|
||||
const call = (name: string, arguments_: Record<string, string> = {}) =>
|
||||
mcp.callTool({ name, arguments: arguments_ });
|
||||
expect((await call("open_binary", { path: target })).isError).not.toBe(
|
||||
true,
|
||||
);
|
||||
const first = parseMcpToolError(await call("current_document"));
|
||||
runtime = dirname(await readFile(receipt, "utf8"));
|
||||
expect(first.error).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
diagnostics: {
|
||||
primary_error: {
|
||||
code: "provider_unavailable",
|
||||
details: {
|
||||
launcher: {
|
||||
exit_code: 2,
|
||||
stderr: {
|
||||
text: expect.stringContaining(
|
||||
"Not authorized to send Apple events",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
await access(`${receipt}.document-created`);
|
||||
await access(runtime);
|
||||
expect(parseMcpToolError(await call("list_procedures"))).toEqual(first);
|
||||
expect(parseMcpToolError(await call("close_binary")).error.code).toBe(
|
||||
"cleanup_incomplete",
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("recovers a denied Hopper launch through the same stdio MCP session and CLI", async ({
|
||||
workspace,
|
||||
cli,
|
||||
}) => {
|
||||
const target = workspace.path("target");
|
||||
await copyFile("/usr/bin/true", target);
|
||||
const mode = await workspace.write("mode", "denied");
|
||||
const receipt = workspace.path("bootstrap-path");
|
||||
const environment = {
|
||||
...workspace.environment,
|
||||
PATH: process.env.PATH ?? "",
|
||||
REA_ANALYSIS_PROVIDER: "hopper",
|
||||
HOPPER_LAUNCHER_PATH: process.execPath,
|
||||
HOPPER_LOADER_ARGS_JSON: JSON.stringify([
|
||||
resolve("tests/fixtures/hopperLaunchAdmission.mjs"),
|
||||
mode,
|
||||
receipt,
|
||||
]),
|
||||
REA_LOG_LEVEL: "silent",
|
||||
};
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [resolve("dist/main.js")],
|
||||
env: environment,
|
||||
stderr: "pipe",
|
||||
});
|
||||
const mcp = new Client({ name: "hopper-startup-recovery", version: "1" });
|
||||
let stderr = "";
|
||||
transport.stderr?.on("data", (chunk: Buffer) => {
|
||||
stderr += chunk.toString();
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await mcp.close();
|
||||
await transport.close();
|
||||
});
|
||||
await mcp.connect(transport);
|
||||
const call = (name: string, arguments_: Record<string, string> = {}) =>
|
||||
mcp.callTool({ name, arguments: arguments_ }).catch((cause: unknown) => {
|
||||
throw new Error(`${name}: ${stderr}`, { cause });
|
||||
});
|
||||
expect((await call("open_binary", { path: target })).isError).not.toBe(true);
|
||||
for (const operation of ["current_document", "list_procedures"]) {
|
||||
const { error } = parseMcpToolError(await call(operation));
|
||||
expect(error).toMatchObject({
|
||||
code: "provider_unavailable",
|
||||
details: {
|
||||
stage: "launch",
|
||||
launcher: {
|
||||
exit_code: 2,
|
||||
stderr: {
|
||||
text: expect.stringContaining(
|
||||
"Not authorized to send Apple events",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(error.message).toContain("Automation");
|
||||
const bootstrap = await readFile(receipt, "utf8");
|
||||
await expect(access(dirname(bootstrap))).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
}
|
||||
expect((await call("close_binary")).isError).not.toBe(true);
|
||||
const deniedCli = await cli.run({
|
||||
arguments: ["analyze", target, "--provider", "hopper", "--json"],
|
||||
environment,
|
||||
timeoutMs: 15_000,
|
||||
});
|
||||
expect(deniedCli.exitCode).toBe(1);
|
||||
expect(deniedCli.json).toMatchObject({
|
||||
code: "provider_unavailable",
|
||||
details: { launcher: { exit_code: 2 } },
|
||||
});
|
||||
|
||||
await writeFile(mode, "bridge");
|
||||
expect((await call("open_binary", { path: target })).isError).not.toBe(true);
|
||||
expect((await call("current_document")).isError).not.toBe(true);
|
||||
expect((await call("close_binary")).isError).not.toBe(true);
|
||||
expect(
|
||||
statusSchema.parse((await call("binary_session")).structuredContent).result
|
||||
.open,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test(
|
||||
"preserves a timed-out handoff and closes only a late bridge with matching run identity",
|
||||
{ timeout: 60_000 },
|
||||
async ({ workspace }) => {
|
||||
const target = workspace.path("target");
|
||||
await copyFile("/usr/bin/true", target);
|
||||
const mode = await workspace.write("mode", "handoff");
|
||||
const receipt = workspace.path("bootstrap-path");
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [resolve("dist/main.js")],
|
||||
stderr: "pipe",
|
||||
env: {
|
||||
...workspace.environment,
|
||||
PATH: process.env.PATH ?? "",
|
||||
REA_ANALYSIS_PROVIDER: "hopper",
|
||||
HOPPER_LAUNCHER_PATH: process.execPath,
|
||||
HOPPER_LOADER_ARGS_JSON: JSON.stringify([
|
||||
resolve("tests/fixtures/hopperLaunchAdmission.mjs"),
|
||||
mode,
|
||||
receipt,
|
||||
]),
|
||||
REA_HOPPER_STARTUP_TIMEOUT_MS: "2000",
|
||||
REA_LOG_LEVEL: "silent",
|
||||
},
|
||||
});
|
||||
const mcp = new Client({ name: "hopper-late-readiness", version: "1" });
|
||||
const children: ChildProcess[] = [];
|
||||
let runtime: string | undefined;
|
||||
const stop = async (child: ChildProcess) => {
|
||||
if (child.exitCode !== null || child.signalCode !== null) return;
|
||||
const exited = new Promise<void>((resolveExit) =>
|
||||
child.once("exit", () => resolveExit()),
|
||||
);
|
||||
child.kill("SIGKILL");
|
||||
await exited;
|
||||
};
|
||||
onTestFinished(async () => {
|
||||
await Promise.all(children.map(stop));
|
||||
await mcp.close();
|
||||
await transport.close();
|
||||
if (runtime !== undefined)
|
||||
await rm(runtime, { recursive: true, force: true });
|
||||
});
|
||||
await mcp.connect(transport);
|
||||
const call = (name: string, arguments_: Record<string, string> = {}) =>
|
||||
mcp.callTool({ name, arguments: arguments_ });
|
||||
expect((await call("open_binary", { path: target })).isError).not.toBe(
|
||||
true,
|
||||
);
|
||||
const initial = parseMcpToolError(await call("current_document"));
|
||||
expect(initial.error).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
diagnostics: {
|
||||
primary_error: {
|
||||
code: "provider_timeout",
|
||||
details: { timeout_ms: 2000, launcher: { exit_code: 0 } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(parseMcpToolError(await call("list_procedures"))).toEqual(initial);
|
||||
const status = z.object({
|
||||
result: z.object({
|
||||
provider_operation_health: z.object({
|
||||
state: z.literal("not_started"),
|
||||
stage: z.literal("launch"),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
status.parse((await call("binary_session")).structuredContent);
|
||||
expect(parseMcpToolError(await call("close_binary")).error.code).toBe(
|
||||
"cleanup_incomplete",
|
||||
);
|
||||
const bootstrap = await readFile(await readFile(receipt, "utf8"), "utf8");
|
||||
const setting = (name: string): string => {
|
||||
const line = bootstrap
|
||||
.split("\n")
|
||||
.find((value) => value.startsWith(`${name} = `));
|
||||
if (line === undefined)
|
||||
throw new Error(`Missing bootstrap setting ${name}`);
|
||||
return z.string().parse(JSON.parse(line.slice(name.length + 3)));
|
||||
};
|
||||
const socket = setting("REA_SOCKET");
|
||||
const token = setting("REA_TOKEN");
|
||||
const runId = setting("REA_RUN_ID");
|
||||
runtime = dirname(socket);
|
||||
const lateBridge = async (identity: string, credential = token) => {
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
resolve("tests/fixtures/fakeHopper.mjs"),
|
||||
socket,
|
||||
credential,
|
||||
identity,
|
||||
],
|
||||
{ stdio: "ignore" },
|
||||
);
|
||||
children.push(child);
|
||||
await vi.waitFor(() => access(socket));
|
||||
return child;
|
||||
};
|
||||
for (const [identity, credential] of [
|
||||
["different-run", token],
|
||||
[runId, "different-token"],
|
||||
] as const) {
|
||||
const wrong = await lateBridge(identity, credential);
|
||||
expect(parseMcpToolError(await call("close_binary")).error.code).toBe(
|
||||
"cleanup_incomplete",
|
||||
);
|
||||
expect(wrong.exitCode).toBeNull();
|
||||
await access(runtime);
|
||||
await stop(wrong);
|
||||
await rm(socket, { force: true });
|
||||
}
|
||||
const closing = call("close_binary");
|
||||
await delay(150);
|
||||
const owned = await lateBridge(runId);
|
||||
expect((await closing).isError).not.toBe(true);
|
||||
await vi.waitFor(() => expect(owned.exitCode).toBe(0));
|
||||
await expect(access(runtime)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
await writeFile(mode, "bridge");
|
||||
expect((await call("open_binary", { path: target })).isError).not.toBe(
|
||||
true,
|
||||
);
|
||||
expect((await call("current_document")).isError).not.toBe(true);
|
||||
expect((await call("close_binary")).isError).not.toBe(true);
|
||||
},
|
||||
);
|
||||
@@ -1,16 +1,14 @@
|
||||
import { chmod, copyFile, mkdir, readdir, rm, rmdir } from "node:fs/promises";
|
||||
import { createConnection } from "node:net";
|
||||
import { join } from "node:path";
|
||||
import { chmod, copyFile, rm } from "node:fs/promises";
|
||||
|
||||
import { describe, expect, onTestFinished } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js";
|
||||
|
||||
import { HOPPER_TARGET_LEASE_DIRECTORY } from "../../../src/hopper/HopperTargetLease.js";
|
||||
import { acquireHopperTargetLease } from "../../../src/hopper/HopperTargetLease.js";
|
||||
|
||||
const FAILED_LAUNCHER = `#!/bin/sh
|
||||
printf 'Cannot launch Hopper!\\nNot authorized to send Apple events to Hopper Disassembler.\\n' >&2
|
||||
printf 'Cannot launch Hopper!\\nDocument state is unknown.\\n' >&2
|
||||
exit 2
|
||||
`;
|
||||
|
||||
@@ -27,45 +25,11 @@ const RetainedRuntime = z.object({
|
||||
}),
|
||||
});
|
||||
|
||||
const listLeases = async (): Promise<ReadonlySet<string>> =>
|
||||
new Set(await readdir(HOPPER_TARGET_LEASE_DIRECTORY).catch(() => []));
|
||||
|
||||
const refusesConnections = (socketPath: string): Promise<boolean> =>
|
||||
new Promise((resolve) => {
|
||||
const socket = createConnection(socketPath);
|
||||
socket.once("connect", () => {
|
||||
socket.destroy();
|
||||
resolve(false);
|
||||
});
|
||||
socket.once("error", (error: NodeJS.ErrnoException) =>
|
||||
resolve(error.code === "ECONNREFUSED"),
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Remove a lease socket only when its owner has exited, holding the same
|
||||
* recovery reservation as production so a concurrent acquirer is never
|
||||
* unlinked. Live or busy leases are left for their owners.
|
||||
*/
|
||||
const removeStaleLease = async (socketPath: string): Promise<void> => {
|
||||
const recoveryPath = `${socketPath}.recovery`;
|
||||
try {
|
||||
await mkdir(recoveryPath, { mode: 0o700 });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (await refusesConnections(socketPath))
|
||||
await rm(socketPath, { force: true });
|
||||
} finally {
|
||||
await rmdir(recoveryPath);
|
||||
}
|
||||
};
|
||||
|
||||
describe("Hopper launcher failure through the one-shot CLI", () => {
|
||||
// Hopper target leases are acquired only for the macOS launcher route.
|
||||
workspaceCliTest.skipIf(process.platform !== "darwin")(
|
||||
"exits after a retained-cleanup failure and releases the target to a retry",
|
||||
{ timeout: 90_000 },
|
||||
async ({ cli, workspace }) => {
|
||||
const launcherPath = await workspace.write(
|
||||
"failure-helper",
|
||||
@@ -74,11 +38,16 @@ describe("Hopper launcher failure through the one-shot CLI", () => {
|
||||
await chmod(launcherPath, 0o700);
|
||||
const targetPath = workspace.path("probe");
|
||||
await copyFile("/usr/bin/true", targetPath);
|
||||
const leasesBefore = await listLeases();
|
||||
const loaderArgs = ["--probe"];
|
||||
onTestFinished(async () => {
|
||||
for (const name of await listLeases())
|
||||
if (!leasesBefore.has(name) && name.endsWith(".sock"))
|
||||
await removeStaleLease(join(HOPPER_TARGET_LEASE_DIRECTORY, name));
|
||||
const recovered = await acquireHopperTargetLease({
|
||||
targetPath,
|
||||
targetKind: "executable",
|
||||
loaderArgs,
|
||||
runId: "failed-cli-test-cleanup",
|
||||
});
|
||||
expect(recovered.acquired).toBe(true);
|
||||
if (recovered.acquired) await recovered.lease.release();
|
||||
});
|
||||
|
||||
for (const attempt of ["first", "retry"]) {
|
||||
@@ -87,9 +56,10 @@ describe("Hopper launcher failure through the one-shot CLI", () => {
|
||||
environment: {
|
||||
...workspace.environment,
|
||||
HOPPER_LAUNCHER_PATH: launcherPath,
|
||||
HOPPER_LOADER_ARGS_JSON: JSON.stringify(loaderArgs),
|
||||
REA_LOG_LEVEL: "silent",
|
||||
},
|
||||
timeoutMs: 30_000,
|
||||
timeoutMs: 45_000,
|
||||
});
|
||||
const retained = RetainedRuntime.safeParse(result.json);
|
||||
if (retained.success)
|
||||
@@ -113,7 +83,7 @@ describe("Hopper launcher failure through the one-shot CLI", () => {
|
||||
exit_code: 2,
|
||||
stderr: {
|
||||
text: expect.stringContaining(
|
||||
"Not authorized to send Apple events",
|
||||
"Document state is unknown",
|
||||
),
|
||||
},
|
||||
},
|
||||
|
||||
@@ -9,8 +9,17 @@ import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const observe = async (path: string) => {
|
||||
const inventory = await inventoryArtifact(path);
|
||||
const observe = async (
|
||||
path: string,
|
||||
omit: { readonly nodes?: boolean; readonly occurrences?: boolean } = {},
|
||||
) => {
|
||||
const observed = await inventoryArtifact(path);
|
||||
const inventory = {
|
||||
...observed,
|
||||
...(omit.nodes === true ? { nodes: [] } : {}),
|
||||
...(omit.occurrences === true ? { occurrences: [] } : {}),
|
||||
};
|
||||
const partial = omit.nodes === true || omit.occurrences === true;
|
||||
return createEvidence(
|
||||
{
|
||||
path,
|
||||
@@ -22,7 +31,7 @@ const observe = async (path: string) => {
|
||||
operation: "inventory_artifact",
|
||||
parameters: {},
|
||||
result: jsonValueSchema.parse(inventory),
|
||||
confidence: "observed",
|
||||
confidence: partial ? "derived" : "observed",
|
||||
authority: "shipped-artifact",
|
||||
},
|
||||
);
|
||||
@@ -60,4 +69,75 @@ describe("artifact comparison summary", () => {
|
||||
});
|
||||
expect(comparison.changes).toHaveLength(3);
|
||||
});
|
||||
|
||||
const writeChangedFiles = async () => {
|
||||
const root = await createTestTempDirectory("rea-artifact-partial-root-");
|
||||
const leftPath = join(root, "left.txt");
|
||||
const rightPath = join(root, "right.txt");
|
||||
await Promise.all([
|
||||
writeFile(leftPath, "before"),
|
||||
writeFile(rightPath, "after"),
|
||||
]);
|
||||
return { leftPath, rightPath };
|
||||
};
|
||||
|
||||
it("counts a changed root once when partial inventories omit node details", async () => {
|
||||
const { leftPath, rightPath } = await writeChangedFiles();
|
||||
const [left, right] = await Promise.all([
|
||||
observe(leftPath, { nodes: true }),
|
||||
observe(rightPath, { nodes: true }),
|
||||
]);
|
||||
const comparison = compareArtifacts(left, right);
|
||||
|
||||
expect(comparison.status).toBe("truncated");
|
||||
expect(comparison.summary).toMatchObject({ changed: 1, unknown: 0 });
|
||||
expect(comparison.changes).toEqual([
|
||||
expect.objectContaining({
|
||||
logical_path: ".",
|
||||
classification: "changed",
|
||||
dimensions: ["content", "availability"],
|
||||
left_occurrence_id: expect.stringMatching(/^occ_/u),
|
||||
right_occurrence_id: expect.stringMatching(/^occ_/u),
|
||||
evidence_links: [left.evidence_id, right.evidence_id],
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports a root content change when partial inventories omit every member", async () => {
|
||||
const { leftPath, rightPath } = await writeChangedFiles();
|
||||
const [left, right] = await Promise.all([
|
||||
observe(leftPath, { nodes: true, occurrences: true }),
|
||||
observe(rightPath, { nodes: true, occurrences: true }),
|
||||
]);
|
||||
const comparison = compareArtifacts(left, right);
|
||||
|
||||
expect(comparison.status).toBe("truncated");
|
||||
expect(comparison.summary).toMatchObject({ changed: 1 });
|
||||
expect(comparison.changes).toEqual([
|
||||
expect.objectContaining({
|
||||
logical_path: ".",
|
||||
classification: "changed",
|
||||
dimensions: ["content"],
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not infer a content change between identical partial inventories", async () => {
|
||||
const { leftPath } = await writeChangedFiles();
|
||||
const [left, right] = await Promise.all([
|
||||
observe(leftPath, { nodes: true }),
|
||||
observe(leftPath, { nodes: true }),
|
||||
]);
|
||||
const comparison = compareArtifacts(left, right);
|
||||
|
||||
expect(comparison.status).toBe("truncated");
|
||||
expect(comparison.summary).toMatchObject({ changed: 0, unknown: 1 });
|
||||
expect(comparison.changes).toEqual([
|
||||
expect.objectContaining({
|
||||
logical_path: ".",
|
||||
classification: "unknown",
|
||||
dimensions: ["availability"],
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { PrivateRuntimeRoot } from "../../../../src/process/PrivateRuntimeRoot.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"the shipped bridge reauthenticates reconnects and releases its execution thread after expiry",
|
||||
async () => {
|
||||
const runtime = await PrivateRuntimeRoot.create({ parent: "/tmp" });
|
||||
onTestFinished(() => runtime.close());
|
||||
const { stdout } = await execute("python3", [
|
||||
fileURLToPath(
|
||||
new URL(
|
||||
"../../../fixtures/hopperBridgeReconnectProbe.py",
|
||||
import.meta.url,
|
||||
),
|
||||
),
|
||||
fileURLToPath(
|
||||
new URL("../../../../bridge/hopper_bridge.py", import.meta.url),
|
||||
),
|
||||
runtime.path,
|
||||
]);
|
||||
const rows = z
|
||||
.array(
|
||||
z.object({
|
||||
mode: z.string(),
|
||||
requests: z.array(z.string()),
|
||||
listener_removed: z.literal(true),
|
||||
thread_released: z.literal(true),
|
||||
}),
|
||||
)
|
||||
.parse(JSON.parse(stdout));
|
||||
expect(rows).toEqual([
|
||||
{
|
||||
mode: "unauthorized",
|
||||
requests: ["health", "shutdown_document", "shutdown_document"],
|
||||
listener_removed: true,
|
||||
thread_released: true,
|
||||
},
|
||||
...["disconnect", "lost-reply"].map((mode) => ({
|
||||
mode,
|
||||
requests: [
|
||||
"health",
|
||||
"health",
|
||||
"shutdown_document",
|
||||
"shutdown_document",
|
||||
],
|
||||
listener_removed: true,
|
||||
thread_released: true,
|
||||
})),
|
||||
{
|
||||
mode: "expiry",
|
||||
requests: ["health"],
|
||||
listener_removed: true,
|
||||
thread_released: true,
|
||||
},
|
||||
]);
|
||||
},
|
||||
);
|
||||
@@ -82,7 +82,7 @@ const clients: HopperClient[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(clients.splice(0).map((client) => client.close()));
|
||||
});
|
||||
}, 45_000);
|
||||
|
||||
describe("HopperClient cleanup", () => {
|
||||
it("waits for an operation reply without a fixed request deadline", async () => {
|
||||
|
||||
@@ -210,7 +210,15 @@ it("blocks a fresh launch while cleanup remains unverified", async () => {
|
||||
const { client, child } = await failedStartup(launcher);
|
||||
await expect(client.start()).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "HopperProtocolError" },
|
||||
error: {
|
||||
cleanupIncomplete: true,
|
||||
cause: { _tag: "HopperTimeoutError" },
|
||||
diagnostics: { primary_error: { code: "provider_timeout" } },
|
||||
},
|
||||
});
|
||||
expect(client.operationHealth()).toMatchObject({
|
||||
state: "not_started",
|
||||
stage: "launch",
|
||||
});
|
||||
expect(launcher.processes).toEqual([child]);
|
||||
launcher.allowCleanup = true;
|
||||
@@ -309,7 +317,10 @@ it("retries a failed lease release after document, process, and runtime cleanup
|
||||
});
|
||||
await expect(client.start()).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "HopperProtocolError" },
|
||||
error: {
|
||||
cleanupIncomplete: true,
|
||||
diagnostics: { primary_error: { code: "provider_timeout" } },
|
||||
},
|
||||
});
|
||||
releaseAllowed = true;
|
||||
await expect(client.close()).resolves.toEqual({ ok: true, value: null });
|
||||
|
||||
@@ -35,6 +35,7 @@ export class HopperFixtureLauncher implements BridgeLauncher {
|
||||
constructor(
|
||||
readonly tokenOverride?: string,
|
||||
readonly diagnosticMode: "quiet" | "noisy" | "noisy_no_socket" = "quiet",
|
||||
readonly healthMode: "ready" | "gated" = "ready",
|
||||
) {}
|
||||
|
||||
launch(session: BridgeSession) {
|
||||
@@ -51,6 +52,7 @@ export class HopperFixtureLauncher implements BridgeLauncher {
|
||||
session.runId,
|
||||
"acknowledge",
|
||||
this.diagnosticMode,
|
||||
this.healthMode,
|
||||
],
|
||||
{ stdio: ["ignore", "pipe", "pipe", "ipc"] },
|
||||
);
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
import { execFile, spawn, type ChildProcess } from "node:child_process";
|
||||
import { access, rm } from "node:fs/promises";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect, it, onTestFinished, vi } from "vitest";
|
||||
|
||||
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
|
||||
import { ok } from "../../../../src/domain/result.js";
|
||||
import type {
|
||||
BridgeLauncher,
|
||||
BridgeSession,
|
||||
} from "../../../../src/hopper/BridgeLauncher.js";
|
||||
import { HopperClient } from "../../../../src/hopper/HopperClient.js";
|
||||
import { HopperFixtureLauncher } from "./hopperClient.fixture.js";
|
||||
|
||||
const stop = async (child: ChildProcess): Promise<void> => {
|
||||
if (child.exitCode !== null || child.signalCode !== null) return;
|
||||
const exited = new Promise<void>((resolve) =>
|
||||
child.once("exit", () => resolve()),
|
||||
);
|
||||
child.kill("SIGKILL");
|
||||
await exited;
|
||||
};
|
||||
|
||||
// The GUI is a sibling owned by the test, never a descendant owned by REA's helper.
|
||||
class ExternalBridgeLauncher implements BridgeLauncher {
|
||||
readonly fixture: HopperFixtureLauncher;
|
||||
readonly sessions: BridgeSession[] = [];
|
||||
readonly helpers: ChildProcess[] = [];
|
||||
|
||||
constructor(
|
||||
readonly identity: "matching" | "wrong-run" | "wrong-token" = "matching",
|
||||
healthMode: "ready" | "gated" = "ready",
|
||||
) {
|
||||
this.fixture = new HopperFixtureLauncher(
|
||||
identity === "wrong-token" ? "foreign-token" : undefined,
|
||||
"quiet",
|
||||
healthMode,
|
||||
);
|
||||
}
|
||||
|
||||
async launch(session: BridgeSession) {
|
||||
this.sessions.push(session);
|
||||
await this.fixture.launch({
|
||||
...session,
|
||||
runId: this.identity === "wrong-run" ? "foreign-run" : session.runId,
|
||||
});
|
||||
const helper = spawn(process.execPath, ["-e", "process.exit(0)"], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
this.helpers.push(helper);
|
||||
return ok({
|
||||
process: helper,
|
||||
ownsProcessLifetime: false as const,
|
||||
providerLifetime: "external-application" as const,
|
||||
shutdownMode: "bridge-request" as const,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const setup = (
|
||||
identity?: "matching" | "wrong-run" | "wrong-token",
|
||||
healthMode?: "ready" | "gated",
|
||||
) => {
|
||||
const launcher = new ExternalBridgeLauncher(identity, healthMode);
|
||||
const client = new HopperClient({ launcher, startupTimeoutMs: 2_000 });
|
||||
onTestFinished(async () => {
|
||||
await client.close();
|
||||
await Promise.all(
|
||||
[...launcher.helpers, ...launcher.fixture.processes].map(stop),
|
||||
);
|
||||
await Promise.all(
|
||||
launcher.sessions.map(({ directory }) =>
|
||||
rm(directory, { recursive: true, force: true }),
|
||||
),
|
||||
);
|
||||
}, 45_000);
|
||||
return { client, launcher };
|
||||
};
|
||||
|
||||
it.each(["missing", "not-listening"] as const)(
|
||||
"waits for a matching bridge published during close after a %s socket failure",
|
||||
async (socketState) => {
|
||||
const fixture = new HopperFixtureLauncher();
|
||||
let session: BridgeSession | undefined;
|
||||
let helper: ChildProcess | undefined;
|
||||
const client = new HopperClient({
|
||||
startupTimeoutMs: 2_000,
|
||||
launcher: {
|
||||
launch(value) {
|
||||
session = value;
|
||||
helper = spawn(process.execPath, ["-e", "process.exit(0)"], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
process: helper,
|
||||
ownsProcessLifetime: false as const,
|
||||
providerLifetime: "external-application" as const,
|
||||
shutdownMode: "bridge-request" as const,
|
||||
}),
|
||||
);
|
||||
},
|
||||
},
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await Promise.all(
|
||||
[...(helper === undefined ? [] : [helper]), ...fixture.processes].map(
|
||||
stop,
|
||||
),
|
||||
);
|
||||
if (session !== undefined)
|
||||
await rm(session.directory, { recursive: true, force: true });
|
||||
});
|
||||
const started = await client.start();
|
||||
if (started.ok) throw new Error("Expected readiness to time out");
|
||||
expect(projectAnalysisError(started.error)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: { diagnostics: { primary_error: { code: "provider_timeout" } } },
|
||||
});
|
||||
if (session === undefined) throw new Error("Fixture did not launch");
|
||||
if (socketState === "not-listening")
|
||||
await promisify(execFile)(process.execPath, [
|
||||
"-e",
|
||||
'require("node:net").createServer().listen(process.argv[1], () => process.exit(0))',
|
||||
session.socketPath,
|
||||
]);
|
||||
const closing = client.close();
|
||||
// Publish after close has encountered an unavailable endpoint, within its
|
||||
// cleanup window rather than before the caller requests cleanup.
|
||||
await delay(150);
|
||||
await rm(session.socketPath, { force: true });
|
||||
await fixture.launch(session);
|
||||
const closed = await closing;
|
||||
if (!closed.ok) throw closed.error;
|
||||
expect(fixture.requests.map(({ method }) => method)).toEqual([
|
||||
"health",
|
||||
"shutdown_document",
|
||||
]);
|
||||
await vi.waitFor(() => expect(fixture.processes[0]?.exitCode).toBe(0));
|
||||
await expect(access(session.directory)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["wrong-run", "wrong-token"] as const)(
|
||||
"never requests document shutdown after the first handshake rejects %s",
|
||||
async (identity) => {
|
||||
const { client, launcher } = setup(identity);
|
||||
const started = await client.start();
|
||||
if (started.ok) throw new Error("Expected a rejected handshake");
|
||||
expect(projectAnalysisError(started.error)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
});
|
||||
await launcher.fixture.waitForRequest("health");
|
||||
expect(launcher.fixture.requests.map(({ method }) => method)).toEqual([
|
||||
"health",
|
||||
]);
|
||||
expect(client.operationHealth()).toMatchObject({
|
||||
state: "unknown",
|
||||
stage: "launch",
|
||||
});
|
||||
const closed = await client.close();
|
||||
if (closed.ok)
|
||||
throw new Error("Expected retained foreign bridge ownership");
|
||||
expect(projectAnalysisError(closed.error)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
});
|
||||
expect(
|
||||
launcher.fixture.requests.every(({ method }) => method === "health"),
|
||||
).toBe(true);
|
||||
expect(launcher.fixture.processes[0]?.exitCode).toBeNull();
|
||||
const session = launcher.sessions[0];
|
||||
if (session === undefined) throw new Error("Fixture did not launch");
|
||||
await access(session.directory);
|
||||
},
|
||||
);
|
||||
|
||||
it("reconnects for authenticated cleanup after a previously valid bridge transport fails", async () => {
|
||||
const { client, launcher } = setup();
|
||||
const started = await client.start();
|
||||
if (!started.ok) throw started.error;
|
||||
const malformed = await client.callTool("malformed");
|
||||
expect(malformed).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "HopperProtocolError" },
|
||||
});
|
||||
const closed = await client.close();
|
||||
if (!closed.ok) throw closed.error;
|
||||
expect(launcher.fixture.requests.map(({ method }) => method)).toEqual([
|
||||
"health",
|
||||
"malformed",
|
||||
"health",
|
||||
"shutdown_document",
|
||||
]);
|
||||
await vi.waitFor(() =>
|
||||
expect(launcher.fixture.processes[0]?.exitCode).toBe(0),
|
||||
);
|
||||
const session = launcher.sessions[0];
|
||||
if (session === undefined) throw new Error("Fixture did not launch");
|
||||
await expect(access(session.directory)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves launcher diagnostics after a health deadline and reauthenticates for cleanup", async () => {
|
||||
const { client, launcher } = setup("matching", "gated");
|
||||
const starting = client.start();
|
||||
const first = await launcher.fixture.waitForRequest("health");
|
||||
const started = await starting;
|
||||
if (started.ok) throw new Error("Expected a health deadline");
|
||||
expect(projectAnalysisError(started.error)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
diagnostics: {
|
||||
primary_error: {
|
||||
code: "provider_timeout",
|
||||
details: {
|
||||
timeout_ms: 2_000,
|
||||
stage: "startup",
|
||||
launcher: { exit_code: 0, output_closed: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(client.requestActivity()).toBeNull();
|
||||
const closing = client.close();
|
||||
const next = await vi.waitFor(() => {
|
||||
const request = launcher.fixture.requests.find(
|
||||
({ method, id }) => method === "health" && id !== first.id,
|
||||
);
|
||||
if (request === undefined)
|
||||
throw new Error("Waiting for recovery handshake");
|
||||
return request;
|
||||
});
|
||||
await launcher.fixture.release(next);
|
||||
const closed = await closing;
|
||||
if (!closed.ok) throw closed.error;
|
||||
expect(launcher.fixture.requests.map(({ method }) => method)).toEqual([
|
||||
"health",
|
||||
"health",
|
||||
"shutdown_document",
|
||||
]);
|
||||
});
|
||||
@@ -55,7 +55,7 @@ const start = async (owned: boolean) => {
|
||||
onTestFinished(async () => {
|
||||
await client.close();
|
||||
for (const child of launcher.fixture.processes) child.kill();
|
||||
});
|
||||
}, 45_000);
|
||||
expect((await client.start()).ok).toBe(true);
|
||||
return { client, launcher };
|
||||
};
|
||||
|
||||
@@ -35,7 +35,7 @@ it("does not equate an owned native helper exit with an external GUI exit", asyn
|
||||
const client = new HopperClient({ launcher, startupTimeoutMs: 10_000 });
|
||||
onTestFinished(async () => {
|
||||
await client.close();
|
||||
});
|
||||
}, 45_000);
|
||||
const result = await client.start();
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
@@ -87,7 +87,7 @@ it.each(["exit", "signal", "exit75"] as const)(
|
||||
const client = new HopperClient({ launcher, startupTimeoutMs: 10_000 });
|
||||
onTestFinished(async () => {
|
||||
await client.close();
|
||||
});
|
||||
}, 45_000);
|
||||
const result = await client.start();
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
@@ -139,7 +139,7 @@ it.each([0, 1])(
|
||||
const client = new HopperClient({ launcher, startupTimeoutMs: 10_000 });
|
||||
onTestFinished(async () => {
|
||||
await client.close();
|
||||
});
|
||||
}, 45_000);
|
||||
const result = await client.start();
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
@@ -177,7 +177,7 @@ it("preserves a successful helper's diagnostics when bridge readiness is never o
|
||||
const client = new HopperClient({ launcher, startupTimeoutMs: 1500 });
|
||||
onTestFinished(async () => {
|
||||
await client.close();
|
||||
});
|
||||
}, 45_000);
|
||||
const result = await client.start();
|
||||
if (result.ok)
|
||||
throw new Error("Expected missing bridge readiness to time out");
|
||||
|
||||
@@ -128,7 +128,7 @@ const clients: HopperClient[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(clients.splice(0).map((client) => client.close()));
|
||||
});
|
||||
}, 45_000);
|
||||
|
||||
describe("HopperClient startup deadline", () => {
|
||||
it("applies one deadline to launcher, socket, and health startup phases", async () => {
|
||||
|
||||
@@ -311,7 +311,7 @@ describe("managed member comparison of undecoded signatures", () => {
|
||||
it("pairs undecoded signatures by exact declared type, name, and raw bytes", () => {
|
||||
const undecoded = {
|
||||
methodSignature: Buffer.from([0x00, 0x00, 0x7f]),
|
||||
fieldSignature: Buffer.from([0x06, 0x15]),
|
||||
fieldSignature: Buffer.from([0x06, 0x7f]),
|
||||
};
|
||||
const left = inspect(
|
||||
buildManagedPeFixture(undecoded),
|
||||
@@ -346,7 +346,7 @@ describe("managed member comparison of undecoded signatures", () => {
|
||||
const left = inspect(
|
||||
buildManagedPeFixture({
|
||||
methodSignature: Buffer.from([0x00, 0x00, 0x7f]),
|
||||
fieldSignature: Buffer.from([0x06, 0x15]),
|
||||
fieldSignature: Buffer.from([0x06, 0x7f]),
|
||||
}),
|
||||
"/tmp/undecoded-before.dll",
|
||||
);
|
||||
@@ -374,7 +374,7 @@ describe("managed member comparison of undecoded signatures", () => {
|
||||
const right = inspect(
|
||||
buildManagedPeFixture({
|
||||
methodSignature: Buffer.from([0x00, 0x00, 0x7f]),
|
||||
fieldSignature: Buffer.from([0x06, 0x15]),
|
||||
fieldSignature: Buffer.from([0x06, 0x7f]),
|
||||
}),
|
||||
"/tmp/undecoded-after.dll",
|
||||
);
|
||||
|
||||
Vendored
+15
-10
@@ -6,6 +6,7 @@ const [
|
||||
runId,
|
||||
shutdownMode = "acknowledge",
|
||||
diagnosticMode = "quiet",
|
||||
healthMode = "ready",
|
||||
] = process.argv.slice(2);
|
||||
let diagnosticOutputEmitted = false;
|
||||
const heldReplies = new Map();
|
||||
@@ -201,17 +202,21 @@ const server = createServer((socket) => {
|
||||
send({ id: request.id, error: { code: -32001, message: "bad token" } });
|
||||
} else if (request.method === "health") {
|
||||
emitDiagnosticOutput();
|
||||
send(
|
||||
{
|
||||
id: request.id,
|
||||
result: {
|
||||
name: "REA Hopper bridge",
|
||||
version: "1.0.0",
|
||||
run_id: runId,
|
||||
const reply = () =>
|
||||
send(
|
||||
{
|
||||
id: request.id,
|
||||
result: {
|
||||
name: "REA Hopper bridge",
|
||||
version: "1.0.0",
|
||||
run_id: runId,
|
||||
},
|
||||
},
|
||||
},
|
||||
true,
|
||||
);
|
||||
true,
|
||||
);
|
||||
if (healthMode === "gated") heldReplies.set(request.id, reply);
|
||||
else if (healthMode === "ready") reply();
|
||||
else throw new Error(`Unknown health fixture mode: ${healthMode}`);
|
||||
} else if (
|
||||
request.method === "shutdown" ||
|
||||
request.method === "shutdown_document"
|
||||
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
"""Exercise the shipped socket lifecycle with a recording native dispatch port."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
from hopperBridgeFacadeProbe import load_bridge
|
||||
|
||||
|
||||
def probe(path, socket_path, mode):
|
||||
bridge = load_bridge(path)
|
||||
bridge.update(REA_SOCKET=socket_path, REA_TOKEN="owned-token", REA_RUN_ID="owned-run",
|
||||
REA_RECONNECT_TIMEOUT_SECONDS=0.2)
|
||||
requests = []
|
||||
entered = threading.Event()
|
||||
release = threading.Event()
|
||||
health = bridge["_dispatch"]
|
||||
|
||||
def dispatch(method, params):
|
||||
requests.append(method)
|
||||
if method == "health":
|
||||
if mode == "lost-reply" and requests == ["health"]:
|
||||
entered.set()
|
||||
assert release.wait(2), "Probe never released the blocked reply"
|
||||
return health(method, params)
|
||||
assert method == "shutdown_document", method
|
||||
closed = not params.get("unconfirmed", False)
|
||||
return {"shutdown": True, "analysis_stopped": True, "document_closed": closed}
|
||||
|
||||
bridge["_dispatch"] = dispatch
|
||||
failures = []
|
||||
|
||||
def serve():
|
||||
try:
|
||||
bridge["_run"]()
|
||||
except Exception as error:
|
||||
failures.append(repr(error))
|
||||
|
||||
worker = threading.Thread(target=serve, daemon=True)
|
||||
worker.start()
|
||||
deadline = time.monotonic() + 2
|
||||
while not Path(socket_path).exists():
|
||||
assert time.monotonic() < deadline, failures
|
||||
time.sleep(0.005)
|
||||
|
||||
def connect():
|
||||
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
client.settimeout(2)
|
||||
client.connect(socket_path)
|
||||
return client, client.makefile("rwb")
|
||||
|
||||
def send(file, method, token="owned-token", params=None):
|
||||
file.write((json.dumps({"id": 1, "method": method, "token": token, "params": params or {}}) + "\n").encode())
|
||||
file.flush()
|
||||
|
||||
def reply(file):
|
||||
while True:
|
||||
line = file.readline()
|
||||
assert line, "Bridge closed before its reply"
|
||||
value = json.loads(line)
|
||||
if "event" not in value:
|
||||
return value
|
||||
|
||||
client, file = connect()
|
||||
send(file, "health", "foreign-token" if mode == "unauthorized" else "owned-token")
|
||||
if mode == "lost-reply":
|
||||
assert entered.wait(2)
|
||||
elif mode == "unauthorized":
|
||||
assert reply(file)["error"]["type"] == "authorization"
|
||||
else:
|
||||
assert reply(file)["result"]["run_id"] == "owned-run"
|
||||
file.close()
|
||||
client.close()
|
||||
release.set()
|
||||
if mode != "expiry":
|
||||
client, file = connect()
|
||||
send(file, "health")
|
||||
assert reply(file)["result"]["run_id"] == "owned-run"
|
||||
send(file, "shutdown_document", params={"unconfirmed": True})
|
||||
assert reply(file)["result"]["document_closed"] is False
|
||||
send(file, "shutdown_document")
|
||||
assert reply(file)["result"]["document_closed"] is True
|
||||
file.close()
|
||||
client.close()
|
||||
worker.join(2)
|
||||
assert not worker.is_alive(), "Bridge pinned its execution thread"
|
||||
assert not failures, failures
|
||||
assert not Path(socket_path).exists(), "Bridge retained its closed listener"
|
||||
assert requests.count("shutdown_document") == (0 if mode == "expiry" else 2)
|
||||
return {"mode": mode, "requests": requests, "listener_removed": True, "thread_released": True}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(json.dumps([probe(sys.argv[1], str(Path(sys.argv[2]) / (mode + ".sock")), mode)
|
||||
for mode in ("unauthorized", "disconnect", "lost-reply", "expiry")]))
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
|
||||
// Model the native helper's external GUI handoff independently of its lifetime.
|
||||
const [modePath, receiptPath] = process.argv.slice(2, 4);
|
||||
const mode = await readFile(modePath, "utf8");
|
||||
const bootstrapIndex = process.argv.indexOf("-Y") + 1;
|
||||
if (bootstrapIndex === 0) throw new Error("Missing Hopper bootstrap argument");
|
||||
const bootstrapPath = process.argv[bootstrapIndex];
|
||||
await writeFile(receiptPath, bootstrapPath);
|
||||
if (mode === "denied" || mode === "denied-after-handoff") {
|
||||
process.stderr.write(
|
||||
"Cannot launch Hopper!\nNot authorized to send Apple events to Hopper Disassembler.\n",
|
||||
async () => {
|
||||
if (mode === "denied-after-handoff") {
|
||||
// A real native helper can create a document before emitting this same
|
||||
// diagnostic when caller literals alter its AppleScript construction.
|
||||
await writeFile(`${receiptPath}.document-created`, "unconfirmed");
|
||||
}
|
||||
process.exit(2);
|
||||
},
|
||||
);
|
||||
} else if (mode === "handoff") {
|
||||
process.exit(0);
|
||||
} else if (mode === "bridge") {
|
||||
await import("./fakeLauncher.mjs");
|
||||
} else {
|
||||
throw new Error(`Unknown Hopper launch admission fixture mode: ${mode}`);
|
||||
}
|
||||
Reference in New Issue
Block a user