mirror of
https://github.com/morluto/rea.git
synced 2026-11-09 16:26:36 +00:00
* fix(reconstruction): dedupe residual unknown ids with uniqueSorted Current main calls uniqueBy, which is not defined, so typecheck fails. Residual unknown ids are strings, and the adjacent lists already use uniqueSorted. Co-authored-by: morluto <morluto@users.noreply.github.com> * feat(config): make the bridge request ceiling configurable REA_BRIDGE_MAX_REQUEST_BYTES replaces the hard-coded 16 MiB Hopper and Cutter request payload ceiling. The default stays 16777216 bytes. Values outside 7464 to 268435456 bytes are configuration_invalid. Part of #6176. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): keep cleanup ownership when a sent command's reply is oversized An authenticated command may already have changed the Cutter document when its reply exceeds the frame ceiling. Return the existing unknown execution, with the ceiling diagnostic in the message, so receipt cleanup still waits. A frame that overflows before the command is sent remains a resource constraint. Co-authored-by: morluto <morluto@users.noreply.github.com> * style: format the bridge request ceiling sources oxfmt --check failed on the five files that set and test REA_BRIDGE_MAX_REQUEST_BYTES. Formatting only; an oversized Cutter reply still stays an unknown execution. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): exclude the LF from the response frame budget REA_BRIDGE_MAX_REQUEST_BYTES counts payload bytes. The Cutter response reader and authenticated encoder were reserving one byte for the terminating LF, so an exact-limit response was rejected. A reply that exceeds the ceiling after the command was sent still stays an unknown execution. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(bridge): measure escaped JSON before allocating the request A command of U+0001 characters can expand sixfold. JSON.stringify of that expansion can throw past Node's string ceiling before the payload check. Count the escaped size within REA_BRIDGE_MAX_REQUEST_BYTES first and refuse it as a resource constraint. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(config): derive the bridge request maximum from JSON expansion A 256 MiB ceiling still lets a shorter U+0001 command expand past Node's 536870888-character string limit. The maximum is now floor((536870888 - 296) / 7) = 76695798, the longest such command whose authenticated frame fits in one string. Requests are still measured before JSON.stringify. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(bridge): size the Cutter frame deadline and send the measured Hopper payload The authenticated Cutter command is encoded after the challenge, so a one-second read rejected an in-budget frame. That read now allows one second per mebibyte of the ceiling and never waits longer than 25 seconds. Hello stays at one second. Hopper writes the payload it already measured instead of serializing the same request again. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(config): bound the bridge request maximum by the serialized string The ceiling already measures escaped JSON, so dividing Node's string limit by the seven-byte expansion rejected encoded payloads that still fit. The maximum is 536870887, one byte under that string ceiling, leaving room for the framing LF. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(hopper): serialize a bridge request when it reaches the wire The queue kept each encoded frame, plus the caller's params, until Hopper finished the active request. A raised ceiling made a few waiting calls enough to exhaust the heap. The FIFO now keeps the params, and the frame is encoded only for the request being written. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): hash the bridge proof prefix and payload separately An exact-limit Cutter frame plus the HMAC prefix exceeds Node's single-string ceiling, so the client threw before sending an admitted command. The prefix and payload are now separate HMAC updates, including the response proof. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): keep recovery fields when a status path exceeds the frame A long current_file made the status reply miss the ceiling, and the fallback then dropped session_id and the completion receipts. The status now omits the path and version and still returns the session, connection proof, and up to 64 receipts. That required recovery frame is smaller than the 7464 floor. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): report an unknown path when status identity does not fit A bounded status kept the new document generation and omitted the path, so the client filled in the descriptor's older path. The observed path is sent when it fits. When it does not, current_file is null and is not replaced with that stale path. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): count structured replies by their encoded JSON size The response guard charged 16 bytes per primitive and two bytes per list slot, so a dense array under the configured ceiling was replaced with output_truncated. Numbers, booleans, null, and container punctuation now use their JSON lengths. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): stream authenticated responses in bounded chunks A fitting reply was signed from retained raw bytes, escaped bytes, and a joined frame, so a ceiling near 512 MiB could exhaust Cutter before send. Measure and sign JSON pieces, then write the same frame in 64 KiB chunks. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(bridge): keep Cutter admission from stalling or hiding sessions Read an unauthenticated frame off the accept loop. A command reply that does not fit keeps completion and generation and reports an oversized path as null. Discovery reports a ceiling mismatch instead of an absent session. The maximum HMAC proof is opt-in, and both bridges reject non-ASCII digits. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): bound frame scans and client response copies Search only newly read bytes for the framing LF. Unescape each socket chunk into one response string, check the proof, and then parse it. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): keep completion, admission, and dense replies bounded Report completed_connection only through connections that have terminated. Cap connection threads and keep the listener up if one fails to start. Batch scalar JSON and fail discovery when any ceiling mismatches. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): hash requests in parts and scan escapes once Update the client-proof prefix and request separately. Stop the response decoder at the first quote or backslash instead of rescanning the tail. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(cutter): confirm live ceiling mismatches and omitted output A stale descriptor from a previous ceiling is not a discovery mismatch until its hello proves a live authenticated bridge. A response discarded for the frame ceiling after dispatch reports output_truncated. Co-authored-by: morluto <morluto@users.noreply.github.com> * test(cutter): close the unauthenticated ceiling-mismatch fixture The listener that fails the hello proof is destroyed after its challenge so discovery cleanup does not wait on that socket. Co-authored-by: morluto <morluto@users.noreply.github.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: morluto <morluto@users.noreply.github.com>
392 lines
13 KiB
TypeScript
392 lines
13 KiB
TypeScript
import { spawn, type ChildProcess } from "node:child_process";
|
|
import { access } from "node:fs/promises";
|
|
import { createServer, type Server } from "node:net";
|
|
|
|
import { afterEach, describe, expect, it } from "vitest";
|
|
|
|
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
|
|
import type { HopperStartupDiagnostic } from "../../../../src/domain/hopperStartupFailure.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 { LINUX_PRIVATE_DISPLAY_DIAGNOSTIC_PREFIX } from "../../../../src/hopper/LinuxPrivateDisplayDiagnostic.js";
|
|
|
|
import { HopperFixtureLauncher as FixtureLauncher } from "./hopperClient.fixture.js";
|
|
|
|
class SilentLauncher implements BridgeLauncher {
|
|
launch() {
|
|
return Promise.resolve(
|
|
ok({
|
|
process: spawn(
|
|
process.execPath,
|
|
["-e", "setInterval(() => {}, 1000)"],
|
|
{
|
|
stdio: ["ignore", "ignore", "pipe"],
|
|
},
|
|
),
|
|
ownsProcessLifetime: true as const,
|
|
providerLifetime: "launcher-process" as const,
|
|
shutdownMode: "bridge-request" as const,
|
|
}),
|
|
);
|
|
}
|
|
}
|
|
|
|
class CancelThenFixtureLauncher implements BridgeLauncher {
|
|
#launches = 0;
|
|
#firstLaunchReady: ((process: ChildProcess) => void) | undefined;
|
|
readonly firstLaunch = new Promise<ChildProcess>((resolve) => {
|
|
this.#firstLaunchReady = resolve;
|
|
});
|
|
retriedProcess: ChildProcess | undefined;
|
|
|
|
async launch(session: BridgeSession) {
|
|
this.#launches += 1;
|
|
const launched = await (this.#launches === 1
|
|
? new SilentLauncher().launch()
|
|
: new FixtureLauncher().launch(session));
|
|
if (this.#launches === 1 && launched.ok)
|
|
this.#firstLaunchReady?.(launched.value.process);
|
|
else if (launched.ok) this.retriedProcess = launched.value.process;
|
|
return launched;
|
|
}
|
|
}
|
|
|
|
class ExitingLauncher implements BridgeLauncher {
|
|
constructor(readonly code: number) {}
|
|
|
|
launch() {
|
|
return Promise.resolve(
|
|
ok({
|
|
process: spawn(process.execPath, ["-e", `process.exit(${this.code})`], {
|
|
stdio: ["ignore", "ignore", "pipe"],
|
|
}),
|
|
ownsProcessLifetime: true as const,
|
|
providerLifetime: "launcher-process" as const,
|
|
shutdownMode: "bridge-request" as const,
|
|
}),
|
|
);
|
|
}
|
|
}
|
|
|
|
class DiagnosticExitingLauncher implements BridgeLauncher {
|
|
launch() {
|
|
const diagnostic: HopperStartupDiagnostic = {
|
|
component: "hopper_private_display",
|
|
operation: "launch",
|
|
status: "error",
|
|
failure_code: "x11_socket_directory_unusable",
|
|
reason: "socket_directory_read_only",
|
|
socket_directory: "/tmp/.X11-unix",
|
|
socket_directory_mode: "0777",
|
|
mount_read_only: true,
|
|
effective_socket_directory_mode: "0777",
|
|
effective_mount_read_only: true,
|
|
wsl: true,
|
|
strategy: "direct",
|
|
fallback_reason: null,
|
|
xvfb_stderr_bytes: 100,
|
|
};
|
|
const line = `${LINUX_PRIVATE_DISPLAY_DIAGNOSTIC_PREFIX}${JSON.stringify(diagnostic)}\n`;
|
|
return Promise.resolve(
|
|
ok({
|
|
process: spawn(
|
|
process.execPath,
|
|
[
|
|
"-e",
|
|
`process.stderr.write(${JSON.stringify(line)}, () => process.exit(80))`,
|
|
],
|
|
{ stdio: ["ignore", "ignore", "pipe"] },
|
|
),
|
|
ownsProcessLifetime: true as const,
|
|
providerLifetime: "launcher-process" as const,
|
|
shutdownMode: "bridge-request" as const,
|
|
}),
|
|
);
|
|
}
|
|
}
|
|
|
|
class LateSilentLauncher implements BridgeLauncher {
|
|
readonly directories: string[] = [];
|
|
readonly processes: ChildProcess[] = [];
|
|
|
|
async launch(session: BridgeSession) {
|
|
this.directories.push(session.directory);
|
|
const launched = await new SilentLauncher().launch();
|
|
if (launched.ok) this.processes.push(launched.value.process);
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
return launched;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Bridge fixture whose health handshake returns an invalid payload, so
|
|
* parseHopperServerInfo rejects it with HopperProtocolError.
|
|
* Note: assumes the client's first bridge request is `health`; any
|
|
* auth/preamble request added before it would hit the -32601 branch.
|
|
*/
|
|
class BadHealthLauncher implements BridgeLauncher {
|
|
#server: Server | undefined;
|
|
#process: ChildProcess | undefined;
|
|
|
|
async launch(session: BridgeSession) {
|
|
const server = createServer((socket) => {
|
|
let buffer = "";
|
|
socket.setEncoding("utf8");
|
|
socket.on("data", (chunk: string) => {
|
|
buffer += chunk;
|
|
let newline = buffer.indexOf("\n");
|
|
while (newline >= 0) {
|
|
const line = buffer.slice(0, newline);
|
|
buffer = buffer.slice(newline + 1);
|
|
try {
|
|
const request = JSON.parse(line) as {
|
|
id: number;
|
|
method: string;
|
|
};
|
|
if (request.method === "health") {
|
|
socket.write(
|
|
`${JSON.stringify({ id: request.id, result: { bogus: true } })}\n`,
|
|
);
|
|
} else {
|
|
socket.write(
|
|
`${JSON.stringify({
|
|
id: request.id,
|
|
error: { code: -32601, message: "unknown method" },
|
|
})}\n`,
|
|
);
|
|
}
|
|
} catch {
|
|
// Ignore malformed input; the client only sends NDJSON.
|
|
}
|
|
newline = buffer.indexOf("\n");
|
|
}
|
|
});
|
|
});
|
|
await new Promise<void>((resolve, reject) => {
|
|
server.once("error", reject);
|
|
server.listen(session.socketPath, () => {
|
|
server.off("error", reject);
|
|
resolve();
|
|
});
|
|
});
|
|
this.#server = server;
|
|
const child = spawn(
|
|
process.execPath,
|
|
["-e", "setInterval(() => {}, 1000)"],
|
|
{
|
|
stdio: "ignore",
|
|
},
|
|
);
|
|
this.#process = child;
|
|
return ok({
|
|
process: child,
|
|
ownsProcessLifetime: true as const,
|
|
providerLifetime: "launcher-process" as const,
|
|
shutdownMode: "process-cleanup" as const,
|
|
cleanup: async () => {
|
|
child.kill("SIGTERM");
|
|
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
return { cleaned: true as const, signaled: true };
|
|
},
|
|
});
|
|
}
|
|
}
|
|
|
|
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 () => {
|
|
const launcher = new LateSilentLauncher();
|
|
const client = new HopperClient({ launcher, startupTimeoutMs: 500 });
|
|
clients.push(client);
|
|
|
|
const result = await client.start();
|
|
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "HopperTimeoutError", timeoutMs: 500 },
|
|
});
|
|
expect(client.operationHealth()).toMatchObject({
|
|
state: "not_started",
|
|
stage: "launch",
|
|
retryAction: "retry",
|
|
exitCode: null,
|
|
});
|
|
if (!result.ok)
|
|
expect(projectAnalysisError(result.error).details).toMatchObject({
|
|
stage: "startup",
|
|
});
|
|
expect(launcher.directories).toHaveLength(1);
|
|
await expect(access(launcher.directories[0] ?? "")).rejects.toMatchObject({
|
|
code: "ENOENT",
|
|
});
|
|
const process = launcher.processes[0];
|
|
expect(
|
|
process !== undefined &&
|
|
(process.exitCode !== null || process.signalCode !== null),
|
|
).toBe(true);
|
|
});
|
|
});
|
|
|
|
describe("HopperClient startup failures", () => {
|
|
it("cancels bridge startup without waiting for the startup timeout", async () => {
|
|
const launcher = new CancelThenFixtureLauncher();
|
|
const client = new HopperClient({
|
|
launcher,
|
|
// Keep the retry proof independent from scheduler pressure when the
|
|
// complete boundary project is starting several child-process fixtures.
|
|
startupTimeoutMs: 30_000,
|
|
});
|
|
clients.push(client);
|
|
const controller = new AbortController();
|
|
const pending = client.callTool("echo", {}, { signal: controller.signal });
|
|
// Cancel after launch: a timer can fire during runtime-directory creation,
|
|
// leaving the silent first launch to be consumed by the retry instead.
|
|
const firstProcess = await launcher.firstLaunch;
|
|
controller.abort();
|
|
const result = await pending;
|
|
expect(result.ok).toBe(false);
|
|
if (!result.ok) expect(result.error._tag).toBe("HopperCancelledError");
|
|
expect(
|
|
firstProcess.exitCode !== null || firstProcess.signalCode !== null,
|
|
).toBe(true);
|
|
const restarted = await client.start();
|
|
const retriedProcess = launcher.retriedProcess;
|
|
expect(retriedProcess).toBeDefined();
|
|
expect(retriedProcess).not.toBe(firstProcess);
|
|
expect(restarted).toEqual({
|
|
ok: true,
|
|
value: {
|
|
name: "REA Hopper bridge",
|
|
version: "1.0.0",
|
|
processId: retriedProcess?.pid,
|
|
maxRequestBytes: 16 * 1024 * 1024,
|
|
},
|
|
});
|
|
await expect(
|
|
client.callTool("echo", { value: "retried" }),
|
|
).resolves.toEqual({
|
|
ok: true,
|
|
value: { value: "retried" },
|
|
});
|
|
});
|
|
|
|
it("retries after cancellation before the launcher starts", async () => {
|
|
const launcher = new FixtureLauncher();
|
|
const client = new HopperClient({ launcher, startupTimeoutMs: 30_000 });
|
|
clients.push(client);
|
|
const controller = new AbortController();
|
|
|
|
const pending = client.callTool("echo", {}, { signal: controller.signal });
|
|
controller.abort();
|
|
|
|
await expect(pending).resolves.toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "HopperCancelledError" },
|
|
});
|
|
expect(launcher.processes).toHaveLength(0);
|
|
const started = await client.start();
|
|
expect(launcher.processes).toHaveLength(1);
|
|
expect(started).toEqual({
|
|
ok: true,
|
|
value: {
|
|
name: "REA Hopper bridge",
|
|
version: "1.0.0",
|
|
processId: launcher.processes[0]?.pid,
|
|
maxRequestBytes: 16 * 1024 * 1024,
|
|
},
|
|
});
|
|
await expect(
|
|
client.callTool("echo", { value: "retried" }),
|
|
).resolves.toEqual({
|
|
ok: true,
|
|
value: { value: "retried" },
|
|
});
|
|
});
|
|
|
|
it("records unknown when the health handshake is invalid", async () => {
|
|
const launcher = new BadHealthLauncher();
|
|
const client = new HopperClient({ launcher, startupTimeoutMs: 30_000 });
|
|
clients.push(client);
|
|
|
|
const result = await client.start();
|
|
|
|
expect(result.ok).toBe(false);
|
|
if (!result.ok) expect(result.error._tag).toBe("HopperProtocolError");
|
|
// parseHopperServerInfo failures were never recorded, so operationHealth()
|
|
// reported idle and the fast path kept a client whose next start stays
|
|
// blocked by retained resources.
|
|
expect(client.operationHealth()).toMatchObject({ state: "unknown" });
|
|
});
|
|
|
|
it.each([70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80])(
|
|
"reports Linux adapter exit %i during bridge startup",
|
|
async (exitCode) => {
|
|
const client = new HopperClient({
|
|
launcher: new ExitingLauncher(exitCode),
|
|
startupTimeoutMs: 10_000,
|
|
});
|
|
clients.push(client);
|
|
const result = await client.start();
|
|
expect(result.ok).toBe(false);
|
|
if (!result.ok)
|
|
expect(result.error).toMatchObject({
|
|
_tag: "HopperProcessError",
|
|
exitCode,
|
|
});
|
|
},
|
|
);
|
|
|
|
it("projects actionable CI remediation for Hopper UI, license, and lifecycle failures", async () => {
|
|
const client = new HopperClient({
|
|
launcher: new ExitingLauncher(75),
|
|
startupTimeoutMs: 10_000,
|
|
});
|
|
clients.push(client);
|
|
const result = await client.start();
|
|
expect(result.ok).toBe(false);
|
|
if (result.ok) return;
|
|
|
|
const projected = projectAnalysisError(result.error);
|
|
expect(projected.message).toContain("rea doctor --provider hopper --json");
|
|
expect(projected.message).toContain("UI or license prompt");
|
|
expect(projected.message).toContain("close stale Hopper sessions");
|
|
expect(projected.details).toMatchObject({
|
|
failure_code: "hopper_exited_during_startup",
|
|
exit_code: 75,
|
|
});
|
|
});
|
|
|
|
it("preserves the private-display diagnostic from an adapter exit", async () => {
|
|
const client = new HopperClient({
|
|
launcher: new DiagnosticExitingLauncher(),
|
|
startupTimeoutMs: 10_000,
|
|
});
|
|
clients.push(client);
|
|
const result = await client.start();
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
_tag: "HopperProcessError",
|
|
exitCode: 80,
|
|
failureCode: "x11_socket_directory_unusable",
|
|
diagnostic: {
|
|
socket_directory: "/tmp/.X11-unix",
|
|
socket_directory_mode: "0777",
|
|
mount_read_only: true,
|
|
wsl: true,
|
|
strategy: "direct",
|
|
},
|
|
},
|
|
});
|
|
});
|
|
});
|