Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix(setup): gate prewarm to applied registrations and supervise the r…
…unner tree

Address review findings on the prewarm step:

- Gate the prewarm on at least one applied client registration
  (configured_<client>), so an empty plan or a skill-only run never
  installs into the package-runner cache; the step now only follows
  registrations the user approved in this transaction.
- Replace execFileOutput with a supervised spawn: on timeout the whole
  runner tree stops through cleanupWindowsProcessTree on Windows and a
  process-group kill on POSIX, because killing only the direct child
  leaves npm holding the inherited output pipes past the deadline.
- Emit started and completed progress events around the prewarm so an
  interactive cold install no longer looks like a frozen setup.
  • Loading branch information
wxj006007 committed Oct 24, 2026
commit 88dd2c111ac5ee4254f01e74f8cf77f16d0cae51
29 changes: 25 additions & 4 deletions src/application/Setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { setupCleanupError, setupCleanupReason } from "./SetupCleanupOwner.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import type { SetupSkillInstallError } from "./SetupSkill.js";
import type { SetupHopperInstallFailure } from "./SetupInstallFailure.js";
import type { SetupRegistrationPrewarm } from "./SetupRegistrationPrewarm.js";

/** Discover, approve, and apply setup actions idempotently. */
export const runSetup = async (
Expand Down Expand Up @@ -378,14 +379,34 @@ const runSetupWorkflow = async (
return withHopperFailure(await failSkill(skillFailure));
}
}
const prewarm = await host.prewarmRegistrationRunner?.();
if (prewarm?.status === "failed")
// The prewarm only follows client registrations the user approved; an empty
// plan or a skill-only run must not install anything.
const prewarmEligible = appliedActions.some((id) =>
id.startsWith("configured_"),
);
let prewarm: SetupRegistrationPrewarm | undefined;
if (prewarmEligible && host.prewarmRegistrationRunner !== undefined) {
emitProgress(options, {
actionId: "prewarm_registration_runner",
label: "REA package-runner cache",
state: "warning",
detail: prewarm.reason,
state: "started",
detail: "Preparing the pinned package entry",
});
prewarm = await host.prewarmRegistrationRunner();
if (prewarm.status === "failed")
emitProgress(options, {
actionId: "prewarm_registration_runner",
label: "REA package-runner cache",
state: "warning",
detail: prewarm.reason,
});
else if (prewarm.status === "warmed")
emitProgress(options, {
actionId: "prewarm_registration_runner",
label: "REA package-runner cache",
state: "completed",
});
}
const doctor = summarizeDoctor(await host.doctor(readinessScope));
const remediation = combineRemediation(
hopperFailure?.remediation ??
Expand Down
102 changes: 77 additions & 25 deletions src/application/SetupRegistrationPrewarm.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,26 @@ import { describe, expect, it } from "vitest";

import { PRODUCT_IDENTITY } from "../identity.js";
import {
launchRegistrationRunnerCommand,
materializeRegistrationRunnerCache,
registrationPrewarmCommand,
type RegistrationRunnerSpawn,
type RegistrationRunnerLaunch,
type RegistrationRunnerLauncher,
} from "./SetupRegistrationPrewarm.js";

const specifier = PRODUCT_IDENTITY.registrationPackageSpecifier;

const launch = (
overrides: Partial<RegistrationRunnerLaunch> = {},
): RegistrationRunnerLaunch => ({
exitCode: 0,
signal: null,
stdout: "",
stderr: "",
timedOut: false,
...overrides,
});

describe("registrationPrewarmCommand", () => {
it("replaces the server subcommand of an npx registration", () => {
expect(registrationPrewarmCommand(["npx", "-y", specifier, "mcp"])).toEqual(
Expand Down Expand Up @@ -48,52 +61,48 @@ describe("registrationPrewarmCommand", () => {
});

describe("materializeRegistrationRunnerCache", () => {
it("skips direct launchers without spawning", async () => {
let spawned = 0;
const spawn: RegistrationRunnerSpawn = async () => {
spawned += 1;
it("skips direct launchers without launching", async () => {
let launched = 0;
const launcher: RegistrationRunnerLauncher = async () => {
launched += 1;
return launch();
};
const result = await materializeRegistrationRunnerCache(
["/opt/rea/rea", "mcp"],
{},
spawn,
launcher,
);
expect(result).toEqual({ status: "skipped", reason: "direct_launcher" });
expect(spawned).toBe(0);
expect(launched).toBe(0);
});

it("materializes the pinned spec once and reports warmed", async () => {
const launches: (readonly string[])[] = [];
const spawn: RegistrationRunnerSpawn = async (
const commands: (readonly string[])[] = [];
const launcher: RegistrationRunnerLauncher = async (
command,
arguments_,
options,
) => {
launches.push([command, ...arguments_]);
expect(options.timeout).toBeGreaterThan(0);
commands.push([command, ...arguments_]);
expect(options.timeoutMs).toBeGreaterThan(0);
expect(options.env.REA_PREWARM_PROBE).toBe("1");
expect(options.cwd.length).toBeGreaterThan(0);
return launch({ stdout: "6.7.0\n" });
};
const result = await materializeRegistrationRunnerCache(
["npx", "-y", specifier, "mcp"],
{ REA_PREWARM_PROBE: "1" },
spawn,
launcher,
);
expect(result).toEqual({ status: "warmed" });
expect(launches).toEqual([["npx", "-y", specifier, "--version"]]);
expect(commands).toEqual([["npx", "-y", specifier, "--version"]]);
});

it("reports a bounded failure reason with command output facts", async () => {
const failure = Object.assign(
new Error("Command failed: npx -y rea-agents@0.0.0 --version"),
{ stdout: "", stderr: "spawn EPERM\n", code: 1 },
);
it("reports a bounded failure reason for a non-zero exit", async () => {
const result = await materializeRegistrationRunnerCache(
["npx", "-y", specifier, "mcp"],
{},
async () => {
throw failure;
},
async () => launch({ exitCode: 1, stderr: "spawn EPERM\n" }),
);
expect(result.status).toBe("failed");
if (result.status !== "failed") return;
Expand All @@ -107,12 +116,55 @@ describe("materializeRegistrationRunnerCache", () => {
const result = await materializeRegistrationRunnerCache(
["npx", "-y", specifier, "mcp"],
{},
async () => {
throw new Error("Command timed out after 180000 ms: npx");
},
async () => launch({ exitCode: null, timedOut: true }),
);
expect(result.status).toBe("failed");
if (result.status !== "failed") return;
expect(result.reason).toContain("timed out");
});

it("reports a spawn failure", async () => {
const result = await materializeRegistrationRunnerCache(
["npx", "-y", specifier, "mcp"],
{},
async () => launch({ exitCode: null, spawnError: "spawn npx ENOENT" }),
);
expect(result.status).toBe("failed");
if (result.status !== "failed") return;
expect(result.reason).toContain("timed out after 180000 ms");
expect(result.reason).toContain("spawn npx ENOENT");
});
});

describe("launchRegistrationRunnerCommand", () => {
it("captures a successful command exit", async () => {
const result = await launchRegistrationRunnerCommand(
process.execPath,
["--version"],
{
env: process.env,
cwd: process.cwd(),
timeoutMs: 30_000,
platform: process.platform,
},
);
expect(result.exitCode).toBe(0);
expect(result.timedOut).toBe(false);
expect(result.stdout.trim().length).toBeGreaterThan(0);
});

it("stops the runner tree at the deadline and reports the timeout", async () => {
const startedAt = Date.now();
const result = await launchRegistrationRunnerCommand(
process.execPath,
["-e", "setInterval(() => {}, 1000)"],
{
env: process.env,
cwd: process.cwd(),
timeoutMs: 300,
platform: process.platform,
},
);
expect(result.timedOut).toBe(true);
expect(Date.now() - startedAt).toBeLessThan(10_000);
});
});
141 changes: 109 additions & 32 deletions src/application/SetupRegistrationPrewarm.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { spawn, type ChildProcess } from "node:child_process";
import { tmpdir } from "node:os";

import {
execFileOutput,
execFileOutputFailure,
} from "../process/ExecFileOutput.js";
import { cleanupWindowsProcessTree } from "../process/ProcessOwnership.js";
import { inspectClientRegistrationCommand } from "./ClientRegistrationIdentity.js";

/**
Expand All @@ -18,23 +16,32 @@ export type SetupRegistrationPrewarm =

/** One cold package install at setup time; client startup deadlines stay untouched. */
const PREWARM_TIMEOUT_MS = 180_000;
const PREWARM_MAX_OUTPUT_BYTES = 64 * 1024;
const PREWARM_CAPTURE_LIMIT = 64 * 1024;
const PREWARM_REASON_LIMIT = 300;

/** Spawn shape shared with execFileOutput so tests can observe the launch. */
export type RegistrationRunnerSpawn = (
/** Facts of one supervised package-runner launch. */
export interface RegistrationRunnerLaunch {
readonly exitCode: string | number | null;
readonly signal: string | null;
readonly stdout: string;
readonly stderr: string;
readonly timedOut: boolean;
readonly spawnError?: string;
}

/** Launch shape shared with the supervised spawn so tests can observe it. */
export type RegistrationRunnerLauncher = (
command: string,
arguments_: readonly string[],
options: {
readonly timeout: number;
readonly stopSignal: NodeJS.Signals;
readonly maxBuffer: number;
readonly env: Readonly<NodeJS.ProcessEnv>;
/** Neutral directory; inside a REA source checkout the package runner
* would resolve the local project instead of the published entry. */
readonly cwd: string;
readonly timeoutMs: number;
readonly platform: NodeJS.Platform;
},
) => Promise<unknown>;
) => Promise<RegistrationRunnerLaunch>;

/**
* Resolve the cache-materializing variant of a registration command. The
Expand All @@ -58,35 +65,105 @@ export const registrationPrewarmCommand = (
export const materializeRegistrationRunnerCache = async (
command: readonly string[],
environment: Readonly<NodeJS.ProcessEnv>,
spawnCommand: RegistrationRunnerSpawn = execFileOutput,
launchCommand: RegistrationRunnerLauncher = launchRegistrationRunnerCommand,
): Promise<SetupRegistrationPrewarm> => {
const prewarm = registrationPrewarmCommand(command);
if (prewarm === undefined)
return { status: "skipped", reason: "direct_launcher" };
try {
await spawnCommand(prewarm[0] ?? "", prewarm.slice(1), {
timeout: PREWARM_TIMEOUT_MS,
stopSignal: "SIGTERM",
maxBuffer: PREWARM_MAX_OUTPUT_BYTES,
env: environment,
cwd: tmpdir(),
const launch = await launchCommand(prewarm[0] ?? "", prewarm.slice(1), {
env: environment,
cwd: tmpdir(),
timeoutMs: PREWARM_TIMEOUT_MS,
platform: process.platform,
});
return launch.timedOut ||
launch.spawnError !== undefined ||
launch.exitCode !== 0
? { status: "failed", reason: prewarmFailureReason(launch) }
: { status: "warmed" };
};

/**
* Stop the whole runner tree: killing only the direct child leaves npm, which
* inherited the output pipes, holding them open past the deadline.
*/
const stopRunnerTree = (
child: ChildProcess,
platform: NodeJS.Platform,
): Promise<void> => {
const pid = child.pid;
if (pid === undefined) return Promise.resolve();
if (platform === "win32")
return cleanupWindowsProcessTree(pid).then(() => undefined);
return new Promise((resolve) => {
try {
process.kill(-pid, "SIGKILL");
} catch {
// The process group may already be gone.
}
resolve();
});
};

export const launchRegistrationRunnerCommand: RegistrationRunnerLauncher = (
command,
arguments_,
options,
) =>
new Promise((resolve) => {
const child = spawn(command, [...arguments_], {
env: options.env,
cwd: options.cwd,
stdio: ["ignore", "pipe", "pipe"],
// POSIX runs the runner in its own group so one signal stops the tree.
...(options.platform === "win32" ? {} : { detached: true }),
Comment thread
wxj006007 marked this conversation as resolved.
Resolved
});
const stdout = boundedStream(child.stdout);
const stderr = boundedStream(child.stderr);
let timedOut = false;
let spawnError: string | undefined;
const timer = setTimeout(() => {
timedOut = true;
void stopRunnerTree(child, options.platform).finally(() => {
child.kill("SIGKILL");
});
}, options.timeoutMs);
child.on("error", (error: NodeJS.ErrnoException) => {
spawnError = error.message;
});
return { status: "warmed" };
} catch (cause: unknown) {
return { status: "failed", reason: prewarmFailureReason(cause) };
}
child.on("close", (code, signal) => {
clearTimeout(timer);
resolve({
exitCode: code ?? signal,
signal: signal ?? null,
stdout: stdout(),
stderr: stderr(),
timedOut,
...(spawnError === undefined ? {} : { spawnError }),
});
});
});

const boundedStream = (
stream: NodeJS.ReadableStream | null,
): (() => string) => {
let captured = "";
stream?.on("data", (chunk: Buffer) => {
if (captured.length < PREWARM_CAPTURE_LIMIT)
captured += chunk.toString("utf8").slice(0, PREWARM_CAPTURE_LIMIT);
});
return () => captured;
};

const prewarmFailureReason = (cause: unknown): string => {
const failure = execFileOutputFailure(cause);
const prewarmFailureReason = (launch: RegistrationRunnerLaunch): string => {
const observed =
failure === undefined
? cause instanceof Error
? cause.message
: String(cause)
: `exit ${failure.code === null ? "unknown" : String(failure.code)}${
failure.stderr.trim() === "" ? "" : `: ${failure.stderr.trim()}`
}`;
launch.spawnError !== undefined
? launch.spawnError
: launch.timedOut
? `the package runner timed out after the bounded prewarm window`
: `exit ${launch.exitCode === null ? "unknown" : String(launch.exitCode)}${
launch.stderr.trim() === "" ? "" : `: ${launch.stderr.trim()}`
}`;
const normalized = observed
.replace(/\u001b(?:\[[0-9;?]*[ -/]*[@-~]|\([0-9A-Za-z]|[@-Z\\^_])/gu, "")
.replace(/[\u0000-\u001f\u007f]+/gu, " ")
Expand Down
Loading