fix(plugins): resolve review findings and integrate main

This commit is contained in:
morluto
2026-10-14 07:51:46 +08:00
565 changed files with 101110 additions and 46071 deletions
@@ -0,0 +1,323 @@
import { chmod, mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, vi } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
processTest,
type TestProcesses,
} from "../../support/process/processFixture.js";
const script = `
import { PlaywrightElectronActiveProvider } from "./dist/browser/PlaywrightElectronActiveProvider.js";
import { electronActiveObservationInputSchema } from "./dist/domain/javascript/electronActiveObservation.js";
const [scenario, executable, root] = JSON.parse(process.argv[1]);
let observedRejections = 0;
if (scenario === "oneFailureWithManySuccesses" || scenario === "externalListenerSeesUnrelatedOnce")
process.on("unhandledRejection", () => { observedRejections += 1; });
const orphanStack = (message, file) =>
message + "\\n at waitForLine (/app/node_modules/playwright-core/lib/server/" + file + ":247:21)";
const playwrightError = (message, file = "electron/electron.js") => {
const error = new Error(message);
error.stack = "Error: " + orphanStack(message, file);
return error;
};
const rejectLater = (error, ms) => setTimeout(() => void Promise.reject(error), ms);
const fakeApplication = { process: () => ({ pid: undefined }), close: async () => undefined };
const launchFailure = (message) =>
new Error("electron.launch: " + message + "\\nCall log:\\n - <launching>");
const after = (ms, action) => new Promise((resolve, reject) => setTimeout(() => {
try { resolve(action()); } catch (error) { reject(error); }
}, ms));
const orphans = (message) => {
for (let index = 0; index < 3; index += 1) void Promise.reject(playwrightError(message));
};
let during = -1;
const launches = {
realLaunch: undefined,
realWithUnrelatedPlaywrightRejection: async (options) => {
void Promise.reject(playwrightError("unrelated playwright failure", "page.js"));
return (await import("playwright-core"))._electron.launch(options);
},
failureWithOrphans: async () => {
during = process.listenerCount("unhandledRejection");
orphans("Process failed to launch!");
await after(10, () => { throw launchFailure("Process failed to launch!"); });
},
failureInOneTick: async () => {
orphans("Process failed to launch!");
throw launchFailure("Process failed to launch!");
},
failureWithUnrelatedPlaywrightRejection: async () => {
orphans("Process failed to launch!");
void Promise.reject(playwrightError("Target page, context or browser has been closed", "page.js"));
await after(10, () => { throw launchFailure("Process failed to launch!"); });
},
externalListenerSeesUnrelatedOnce: async () => {
void Promise.reject(playwrightError("unrelated playwright failure", "page.js"));
await after(10, () => { throw launchFailure("Process failed to launch!"); });
},
pendingWithUnrelatedRejection: () => {
setInterval(() => {}, 1000);
rejectLater(new Error("unrelated application failure"), 20);
return new Promise(() => {});
},
success: async () => {
during = process.listenerCount("unhandledRejection");
return fakeApplication;
},
successWithPlaywrightRejection: async () => {
void Promise.reject(playwrightError("stray playwright failure", "page.js"));
await after(10, () => fakeApplication);
return fakeApplication;
},
};
const input = (executablePath) => ({
...electronActiveObservationInputSchema.parse({
executable_path: executablePath,
application_path: root,
}),
application_root: root,
});
const capture = (launch, executablePath = executable) =>
new PlaywrightElectronActiveProvider({}, launch).capture(input(executablePath));
const before = process.listenerCount("unhandledRejection");
let results;
if (scenario === "concurrentFailures" || scenario === "failureThenSuccess" || scenario === "successThenFailure" || scenario === "oneFailureWithManySuccesses") {
const failing = (message, orphanAt, settleAt) => async () => {
during = Math.max(during, process.listenerCount("unhandledRejection"));
await after(orphanAt, () => orphans(message));
await after(settleAt - orphanAt, () => { throw launchFailure(message); });
};
const succeeding = (settleAt) => () => {
during = Math.max(during, process.listenerCount("unhandledRejection"));
return after(settleAt, () => fakeApplication);
};
const pair = {
concurrentFailures: [failing("alpha failed", 10, 30), failing("beta failed", 20, 50)],
failureThenSuccess: [failing("alpha failed", 10, 20), succeeding(40)],
successThenFailure: [failing("alpha failed", 20, 40), succeeding(30)],
oneFailureWithManySuccesses: [failing("alpha failed", 10, 80), ...[20, 30, 40, 50].map(succeeding)],
}[scenario];
results = await Promise.all(pair.map((launch) => capture(launch)));
} else {
results = [await capture(launches[scenario] ?? undefined)];
}
await new Promise((resolve) => setTimeout(resolve, 50));
console.log(JSON.stringify({
before,
during,
after: process.listenerCount("unhandledRejection"),
observedRejections,
reasons: results.map((result) => result.ok ? null : result.error.reason ?? null),
ok: results.map((result) => result.ok),
causeReasons: results.map((result) => result.ok ? null : result.error.cause?.reason ?? null),
cleanupResources: results.map((result) => result.ok ? null : result.error.cleanupResources ?? null),
causes: results.map((result) => result.ok ? null : String(result.error.cause?.message).split("\\n")[0]),
}));
`;
// A cold macOS Swift toolchain may spend up to 120 seconds building the
// ownership reader before any child launch reaches its assertion.
vi.setConfig({ testTimeout: 180_000 });
type Outcome = {
readonly before: number;
readonly during: number;
readonly after: number;
readonly ok: readonly boolean[];
readonly causes: readonly (string | null)[];
readonly observedRejections: number;
readonly reasons: readonly (string | null)[];
readonly causeReasons: readonly (string | null)[];
readonly cleanupResources: readonly (readonly string[] | null)[];
};
const run = async (
processes: TestProcesses,
scenario: string,
executable = "/not/launched",
root = "/",
) =>
processes.run(
process.execPath,
[
"--input-type=module",
"--eval",
script,
JSON.stringify([scenario, executable, root]),
],
{ timeoutMs: 150_000 },
);
const outcome = (result: { readonly stdout: string }): Outcome =>
JSON.parse(result.stdout.trim().split("\n").at(-1) ?? "") as Outcome;
const earlyExit = async () => {
const root = await createTestTempDirectory("rea-launch-rejections-");
const executable = join(root, "exits-immediately");
await mkdir(join(root, "app"));
await writeFile(executable, "#!/bin/sh\nexit 0\n");
await chmod(executable, 0o755);
return { executable, root: join(root, "app") };
};
processTest(
"absorbs the orphaned rejections of a failed launch and removes its listener",
async ({ processes }) => {
const result = await run(processes, "failureWithOrphans");
expect(result.exitCode, result.stderr).toBe(0);
expect(outcome(result)).toMatchObject({
during: outcome(result).before + 1,
after: outcome(result).before,
ok: [false],
causes: ["electron.launch: Process failed to launch!"],
});
},
);
processTest(
"absorbs orphans raised in the same tick as the launch failure",
async ({ processes }) => {
const result = await run(processes, "failureInOneTick");
expect(result.exitCode, result.stderr).toBe(0);
expect(outcome(result)).toMatchObject({ ok: [false] });
},
);
processTest.skipIf(process.platform === "win32")(
"absorbs the orphans of a real Playwright launch that exits at once",
async ({ processes }) => {
const { executable, root } = await earlyExit();
const result = await run(processes, "realLaunch", executable, root);
expect(result.exitCode, result.stderr).toBe(0);
expect(outcome(result)).toMatchObject({
ok: [false],
causes: ["electron.launch: Process failed to launch!"],
});
expect(outcome(result).after).toBe(outcome(result).before);
},
);
processTest.skipIf(process.platform === "win32")(
"still fails on an unrelated Playwright rejection during a real failing launch",
async ({ processes }) => {
const { executable, root } = await earlyExit();
const result = await run(
processes,
"realWithUnrelatedPlaywrightRejection",
executable,
root,
);
expect(result.exitCode, result.stderr).toBe(1);
expect(result.stderr).toContain("unrelated playwright failure");
expect(result.stdout).toBe("");
},
);
processTest(
"does not replay an unrelated orphan to a listener that already received it",
async ({ processes }) => {
const result = await run(processes, "externalListenerSeesUnrelatedOnce");
expect(result.exitCode, result.stderr).toBe(0);
expect(outcome(result)).toMatchObject({
observedRejections: 1,
ok: [false],
causes: ["electron.launch: Process failed to launch!"],
});
},
);
processTest(
"still fails on an unrelated Playwright rejection beside a failing launch's own orphans",
async ({ processes }) => {
const result = await run(
processes,
"failureWithUnrelatedPlaywrightRejection",
);
expect(result.exitCode, result.stderr).toBe(1);
expect(result.stderr).toContain(
"Target page, context or browser has been closed",
);
expect(result.stdout).toBe("");
},
);
processTest(
"still fails at once on an unrelated rejection while a launch is pending",
async ({ processes }) => {
const result = await run(processes, "pendingWithUnrelatedRejection");
expect(result.exitCode, result.stderr).toBe(1);
expect(result.stderr).toContain("unrelated application failure");
expect(result.stdout).toBe("");
},
);
processTest(
"removes its listener after a successful launch",
async ({ processes }) => {
const result = await run(processes, "success");
expect(result.exitCode, result.stderr).toBe(0);
expect(outcome(result)).toMatchObject({
during: outcome(result).before + 1,
after: outcome(result).before,
});
},
);
processTest(
"re-raises a Playwright rejection when the launch succeeds",
async ({ processes }) => {
const result = await run(processes, "successWithPlaywrightRejection");
expect(result.exitCode, result.stderr).toBe(1);
expect(result.stderr).toContain("stray playwright failure");
expect(result.stdout).toBe("");
},
);
processTest.for([
"concurrentFailures",
"failureThenSuccess",
"successThenFailure",
])(
"keeps overlapping launches from re-raising each other's orphans (%s)",
async (scenario, { processes }) => {
const result = await run(processes, scenario);
expect(result.exitCode, result.stderr).toBe(0);
expect(outcome(result).after).toBe(outcome(result).before);
},
);
processTest(
"holds each orphan once across many overlapping successful launches",
async ({ processes }) => {
const result = await run(processes, "oneFailureWithManySuccesses");
expect(result.exitCode, result.stderr).toBe(0);
const observed = outcome(result);
expect(observed.during).toBe(observed.before + 1);
expect(observed.after).toBe(observed.before);
expect(observed.observedRejections).toBe(3);
expect(observed.ok).toEqual([false, false, false, false, false]);
expect(observed.causes[0]).toBe("electron.launch: alpha failed");
expect(observed.reasons).toEqual([
null,
"cleanup_failed",
"cleanup_failed",
"cleanup_failed",
"cleanup_failed",
]);
expect(observed.causeReasons).toEqual([
null,
...Array.from({ length: 4 }, () => "process_ownership_unavailable"),
]);
expect(observed.cleanupResources).toEqual([
[],
...Array.from({ length: 4 }, () => ["owned_process_group"]),
]);
},
);
+125 -1
View File
@@ -12,7 +12,10 @@ import {
cleanupOwnedProcessGroup,
type ProcessCleanupResult,
} from "../../../src/process/ProcessOwnership.js";
import { prepareProcessOwnershipInspection } from "../../../src/process/ProcessOwnershipObservation.js";
import {
prepareProcessOwnershipInspection,
systemProcessOwnershipHost,
} from "../../../src/process/ProcessOwnershipObservation.js";
import { waitForProviderProcessReady } from "../../fixtures/providerProcess.js";
const command = (script: string) => ({
@@ -152,6 +155,127 @@ it("fails an accepted nonzero command when an output stream errors and cleans it
expect(cleanup).toHaveBeenCalledOnce();
});
it("marks an output collection error when the process itself exits zero", async () => {
const stdout = new PassThrough();
const stderr = new PassThrough();
class FakeProcess extends EventEmitter {
readonly stdout = stdout;
readonly stderr = stderr;
exitCode: number | null = null;
signalCode: NodeJS.Signals | null = null;
readonly pid = 41235;
kill(): boolean {
return true;
}
}
const child = new FakeProcess();
const request = command("unused fake launcher command");
const failure = runOwnedCommand(
request,
{ timeoutMs: 2_000, diagnosticBytes: 1024, acceptNonZeroExit: true },
{
launcher: async () => {
setImmediate(() => {
stdout.write("partial output");
stdout.destroy(new Error("fixture read failure"));
stderr.end();
child.exitCode = 0;
child.emit("exit", 0, null);
child.emit("close", 0, null);
});
return {
process: child,
ownership: {
runId: request.runId,
leaderPid: child.pid,
processGroupId: child.pid,
},
cleanup: async () => ({ cleaned: true, signaled: false }),
};
},
},
);
await expect(failure).rejects.toMatchObject({
reason: "process",
collectionFailure: true,
message: "stdout stream failed: fixture read failure",
snapshot: { stdout: { text: "partial output" }, exitCode: 0 },
});
});
it.skipIf(process.platform === "win32")(
"sweeps detached run-token descendants and preserves a pre-existing unrelated process",
async () => {
const runId = `rea-owned-descendant-test-${randomUUID()}`;
const unrelated = await spawnOwnedProviderProcess({
command: process.execPath,
arguments: ["-e", "setInterval(() => undefined, 1000)"],
runId: `${runId}-unrelated`,
hostEnvironment: process.env,
});
let descendantPid: number | undefined;
try {
const result = await runOwnedCommand(
{
...command(`
const { spawn } = require("node:child_process");
const child = spawn(process.execPath, ["-e", "setInterval(() => undefined, 1000)"], {
detached: true,
stdio: "ignore",
});
child.unref();
process.stdout.write(String(child.pid));
`),
runId,
sweepTokenOwnedProcesses: true,
},
{ timeoutMs: 5_000, diagnosticBytes: 1024 },
);
descendantPid = Number(result.stdout.text);
expect(Number.isSafeInteger(descendantPid)).toBe(true);
let remainsLive = true;
const deadline = Date.now() + 2_000;
while (remainsLive && Date.now() < deadline) {
remainsLive = (await systemProcessOwnershipHost.listProcesses()).some(
({ pid }) => pid === descendantPid,
);
if (remainsLive) await delay(25);
}
expect(remainsLive).toBe(false);
expect(() => process.kill(unrelated.process.pid!, 0)).not.toThrow();
} finally {
if (descendantPid !== undefined) {
try {
process.kill(descendantPid, "SIGKILL");
} catch {
// The run-token sweep may already have removed it.
}
}
await cleanupOwnedProcessGroup(unrelated.ownership);
}
},
);
it.skipIf(process.platform === "win32")(
"fails before provider spawn when a requested ownership baseline cannot be captured",
async () => {
const baseline = vi
.spyOn(systemProcessOwnershipHost, "captureBaseline")
.mockRejectedValue(new Error("baseline unavailable"));
try {
await expect(
runOwnedCommand(
{ ...command("process.exit(0)"), sweepTokenOwnedProcesses: true },
{ timeoutMs: 2_000, diagnosticBytes: 1024 },
),
).rejects.toThrow("baseline unavailable");
} finally {
baseline.mockRestore();
}
},
);
it("cancels a real acquired process and independently releases it", async () => {
const controller = new AbortController();
let pid: number | undefined;
File diff suppressed because it is too large Load Diff
@@ -1,5 +1,5 @@
import { spawn } from "node:child_process";
import { lstat, mkdir, readFile, writeFile } from "node:fs/promises";
import { copyFile, lstat, mkdir, readFile, writeFile } from "node:fs/promises";
import { delimiter, join } from "node:path";
import { fileURLToPath } from "node:url";
import { expect, it, onTestFinished } from "vitest";
@@ -10,8 +10,8 @@ const launcher = fileURLToPath(
new URL("../../../scripts/plugin-mcp-launcher.mjs", import.meta.url),
);
const start = (path: string, version = "6.4.0-rc.1") => {
const child = spawn(process.execPath, [launcher, version], {
const start = (path: string, version = "6.4.0-rc.1", entry = launcher) => {
const child = spawn(process.execPath, [entry, version], {
env: {
...process.env,
PATH: `${path}${delimiter}${process.env.PATH ?? ""}`,
@@ -170,3 +170,68 @@ it("rejects a shell expression instead of treating it as the pinned package", as
stderr: "REA plugin requires one exact rea-agents@VERSION pin.\n",
});
});
const pluginFixture = async () => {
const root = await createTestTempDirectory("rea-plugin-release-origin-");
await mkdir(join(root, "scripts"));
await mkdir(join(root, "dist/mcp"), { recursive: true });
const entry = join(root, "scripts/plugin-mcp-launcher.mjs");
await copyFile(launcher, entry);
await writeFile(
join(root, "package.json"),
JSON.stringify({
name: "rea-agents",
version: "6.4.0",
type: "module",
}),
);
await writeFile(join(root, "dist/mcp/main.js"), "");
await writeFile(
join(root, "scripts/rea.mjs"),
'process.stdout.write("bundled-runtime");',
);
return { root, entry };
};
it
.skipIf(process.platform === "win32")
.each(["directory", "worktree file", "exported source"])(
"uses the registry pin even when a %s checkout has same-version dist",
async (kind) => {
const { root, entry } = await pluginFixture();
await mkdir(join(root, "src/application"), { recursive: true });
await copyFile(
fileURLToPath(
new URL(
"../../../src/application/PackageRunnerCommand.mjs",
import.meta.url,
),
),
join(root, "src/application/PackageRunnerCommand.mjs"),
);
if (kind === "directory") await mkdir(join(root, ".git"));
else if (kind === "worktree file")
await writeFile(join(root, ".git"), "gitdir: /fixture/worktree");
const bin = await fakeRunner(
"process.stdout.write(JSON.stringify(process.argv.slice(2)));",
);
const { child, closed } = start(bin, "6.4.0", entry);
child.stdin.end();
expect(await closed).toMatchObject({
code: 0,
stdout: '["-y","rea-agents@6.4.0","mcp"]',
stderr: "",
});
},
);
it("uses the matching installed runtime without another package-runner install", async () => {
const { root, entry } = await pluginFixture();
const { child, closed } = start(root, "6.4.0", entry);
child.stdin.end();
expect(await closed).toMatchObject({
code: 0,
stdout: "bundled-runtime",
stderr: "",
});
});
@@ -188,6 +188,40 @@ describe("provider process runtime and wait primitives", () => {
});
describe("provider process output and cleanup primitives", () => {
it("marks retained provider output that cannot be represented as UTF-8", async () => {
const child = spawnProviderProcessFixture("invalid-utf8");
const supervisor = new ProviderProcessSupervisor({
process: child,
ownsProcessLifetime: true,
});
await expect(supervisor.waitForOutputClose(2_000)).resolves.toBe(true);
expect(supervisor.snapshot()).toMatchObject({
stdout: { text: "a�b", invalidUtf8: true },
stderr: { text: "c�d", invalidUtf8: true },
});
await expect(supervisor.stop()).resolves.toMatchObject({
status: "already-exited",
});
});
it("marks a retained byte prefix that cuts a valid multibyte UTF-8 character", async () => {
const child = spawnProviderProcessFixture("valid-multibyte");
const supervisor = new ProviderProcessSupervisor(
{ process: child, ownsProcessLifetime: true },
{ maxDiagnosticBytes: 2 },
);
await expect(supervisor.waitForOutputClose(2_000)).resolves.toBe(true);
expect(supervisor.snapshot()).toMatchObject({
stdout: { text: "�", bytes: 2, observedBytes: 3, invalidUtf8: true },
diagnosticTruncated: true,
});
await expect(supervisor.stop()).resolves.toMatchObject({
status: "already-exited",
});
});
it("retains complete stdout and stderr beyond the former fixed ceiling", async () => {
const outputBytes = 70_000;
const child = spawnProviderProcessFixture("burst", outputBytes);
@@ -1,4 +1,7 @@
import { expect, it } from "vitest";
import { expect, it, vi } from "vitest";
import type { Socket } from "node:net";
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import {
ProviderProcessSupervisor,
type ProviderProcessDiagnostic,
@@ -8,6 +11,26 @@ import {
stopProviderProcessFixture,
} from "../../fixtures/providerProcess.js";
it("unreferences inherited output streams without closing them", async () => {
const child = spawnProviderProcessFixture("stubborn");
const supervisor = new ProviderProcessSupervisor({
process: child,
ownsProcessLifetime: true,
});
const stdoutUnref = vi.spyOn(child.stdout as Socket, "unref");
const stderrUnref = vi.spyOn(child.stderr as Socket, "unref");
try {
supervisor.unrefOutputStreams();
expect(stdoutUnref).toHaveBeenCalledOnce();
expect(stderrUnref).toHaveBeenCalledOnce();
expect(child.stdout!.destroyed).toBe(false);
expect(child.stderr!.destroyed).toBe(false);
} finally {
await supervisor.stop();
await stopProviderProcessFixture(child);
}
});
it("bounds capture before diagnostic callbacks while draining both output streams", async () => {
const child = spawnProviderProcessFixture("burst", 70_000);
const diagnostics: ProviderProcessDiagnostic[] = [];
@@ -46,3 +69,30 @@ it("bounds capture before diagnostic callbacks while draining both output stream
await stopProviderProcessFixture(child);
}
});
it("bounds additional late output while retaining observed byte counts", () => {
const child = Object.assign(new EventEmitter(), {
stdout: new PassThrough(),
stderr: new PassThrough(),
exitCode: null as number | null,
signalCode: null as NodeJS.Signals | null,
kill: vi.fn(() => true),
});
const supervisor = new ProviderProcessSupervisor({
process: child,
ownsProcessLifetime: true,
});
supervisor.limitAdditionalOutputBytes(5);
child.stdout.write("abc");
supervisor.limitAdditionalOutputBytes(5);
child.stdout.write("defgh");
child.stderr.write("ijkl");
const snapshot = supervisor.snapshot();
expect(snapshot.stdout.text + snapshot.stderr.text).toHaveLength(5);
expect(snapshot.stdout.observedBytes).toBe(8);
expect(snapshot.stderr.observedBytes).toBe(4);
expect(snapshot.diagnosticTruncated).toBe(true);
supervisor.dispose();
});