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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions sea-trial/vendor/pi-rpc-readers.vendor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { afterEach, describe, expect, test, vi } from "vitest";
import { createPiRuntime, type SessionOptions } from "../../packages/oar/src/index.js";
import { asRecord, parseJson } from "../../packages/oar/src/shared/json.js";
import { killGraceMs } from "../../packages/oar/src/shared/executable/index.js";
import { holdFixtureDeadline } from "../../tests/fixtures/fixture-deadline.js";
import { eventually, gone } from "../../tests/fixtures/process-tree.js";

const identityModule = new URL("../../tests/fixtures/process-tree.ts", import.meta.url).href;
Expand Down Expand Up @@ -99,19 +100,21 @@ describe.skipIf(process.env.OAR_TEST !== "pi-rpc-aimock")("native Pi RPC readers
const f = await fixture();
const pidFile = path.join(f.root, "stalled.json"), script = path.join(f.root, "stalled-pi.mjs");
const { PI_AI_VERSION } = await import("@earendil-works/pi-ai");
await writeFile(script, `import { writeFileSync } from "node:fs";
await writeFile(script, `import { renameSync, writeFileSync } from "node:fs";
import { captureProcess } from ${JSON.stringify(identityModule)};
if (process.argv.includes("--version") && ${JSON.stringify(stage)} !== "version") { console.log(${JSON.stringify(PI_AI_VERSION)}); }
else { writeFileSync(${JSON.stringify(pidFile)}, JSON.stringify({ ...captureProcess(process.pid), directory: process.env.OAR_PI_RPC_DIRECTORY })); setInterval(() => {}, 1000); }`);
else { const file = ${JSON.stringify(pidFile)}; writeFileSync(file + ".tmp", JSON.stringify({ ...captureProcess(process.pid), directory: process.env.OAR_PI_RPC_DIRECTORY })); renameSync(file + ".tmp", file); setInterval(() => {}, 1000); }`);
const runtime = createPiRuntime({ execution: "subprocess", command: process.execPath, args: guardedFixtureArgs("--import", import.meta.resolve("tsx"), script) });
try {
const options = { cwd: f.cwd, env: f.env, timeoutMs: 8000 };
if (reader === "models") {
await expect(runtime.listModels(installed, options)).rejects.toThrow("Pi RPC model listing timed out");
} else {
const result = await runtime.commands(installed, options);
expect(result).toMatchObject({ kind: "unavailable", code: "timeout" });
}
const waitForFixture = holdFixtureDeadline();
const outcome = reader === "models"
? expect(runtime.listModels(installed, options)).rejects.toThrow("Pi RPC model listing timed out")
: expect(runtime.commands(installed, options)).resolves.toMatchObject({ kind: "unavailable", code: "timeout" });
await waitForFixture(outcome, async () => {
expect(await eventually(() => existsSync(pidFile), 15_000), stage).toBe(true);
});
await outcome;
const child = children(pidFile)[0];
assert.ok(child !== undefined);
// Timeout begins the same bounded native shutdown as a session dispose.
Expand Down
33 changes: 19 additions & 14 deletions tests/account-query-deadlines.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* oxlint-disable import/max-dependencies -- One real-process regression exercises each affected account entry point. */
import { readFileSync } from "node:fs";
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, expect, test, vi } from "vitest";
Expand All @@ -15,7 +15,8 @@ import { readCodexAuthStatus } from "../packages/oar/src/runtimes/codex/login.js
import { codebuddyAuthStatus } from "../packages/oar/src/runtimes/codebuddy/auth-status.js";
import { factoryAuthStatus } from "../packages/oar/src/runtimes/factory/account.js";
import { kimiAuthStatus, queryKimiAuth } from "../packages/oar/src/runtimes/kimi/auth-status.js";
import { fakeAgentBinary, gone, withTreeProbe } from "./fixtures/process-tree.js";
import { holdFixtureDeadline } from "./fixtures/fixture-deadline.js";
import { eventually, fakeAgentBinary, gone, withTreeProbe } from "./fixtures/process-tree.js";

const script = fileURLToPath(new URL("fixtures/stalled-account-query.mjs", import.meta.url));
const TIMEOUT = 4000;
Expand Down Expand Up @@ -51,16 +52,18 @@ test.each(cases)("$name settles at its deadline while owned cleanup continues",
...probe.env, HOME: probe.dir, CODEX_HOME: probe.dir, CODEBUDDY_API_KEY: null, WINDSURF_API_KEY: null,
OAR_QUERY_STAGE: stage, OAR_QUERY_REQUESTS: requests,
} }).then((value) => ({ value, error: null }), (error: unknown) => ({ value: null, error }));
const tree = await probe.tree();
// Wait until the fixture reaches the target stage before firing the deadline timer.
await vi.waitFor(() => {
expect(readFileSync(requests, "utf8").trim().split("\n")).toContain(stage);
}, { timeout: 10_000, interval: 10 });
const deadlineAt = performance.now();
vi.advanceTimersByTime(TIMEOUT);
vi.useRealTimers();
let deadlineAt = 0;
const [tree, ready] = await Promise.all([
probe.tree(),
eventually(() => existsSync(requests) && readFileSync(requests, "utf8").trim().split("\n").includes(stage), 10_000),
]).finally(() => {
deadlineAt = performance.now();
vi.advanceTimersByTime(TIMEOUT);
vi.useRealTimers();
});
const outcome = await result;
const settleMs = performance.now() - deadlineAt;
expect(ready, stage).toBe(true);
if (name.endsWith("status")) {
expect(outcome.value).toMatchObject({ kind: "unknown" });
expect(outcome.value).toHaveProperty("detail", expect.stringContaining("timed out"));
Expand Down Expand Up @@ -90,11 +93,12 @@ test.skipIf(process.platform === "win32")("login/logout's internal status reader
vi.stubEnv("OAR_KILL_GRACE_MS", String(GRACE));
await withTreeProbe({ ignoreSigterm: true }, async (probe) => {
const command = fakeAgentBinary(probe.dir, [script]);
const started = performance.now();
const waitForFixture = holdFixtureDeadline();
const result = readCodexAuthStatus({ kind: "available", via: "executable", command }, {
timeoutMs: 1000, env: { ...probe.env, OAR_QUERY_REQUESTS: path.join(probe.dir, "requests") },
});
const tree = await probe.tree();
const tree = await waitForFixture(result, async () => probe.tree());
const started = performance.now();
expect(await result).toMatchObject({ kind: "unknown" });
expect(performance.now() - started).toBeGreaterThanOrEqual(1000 + GRACE - 50);
expect(await gone(tree.agent, 0)).toBe(true);
Expand All @@ -106,10 +110,11 @@ test.skipIf(process.platform === "win32").each(["authenticate", "logout"] as con
vi.stubEnv("OAR_KILL_GRACE_MS", String(GRACE));
await withTreeProbe({ ignoreSigterm: true, detachTool: true }, async probe => {
const command = fakeAgentBinary(probe.dir, [script]);
const started = performance.now();
const waitForFixture = holdFixtureDeadline();
const result = queryKimiAuth(command, method, { timeoutMs: 1000, joinCleanup: method === "authenticate",
env: { ...probe.env, OAR_QUERY_STAGE: method, OAR_QUERY_REQUESTS: path.join(probe.dir, "requests") } });
const tree = await probe.tree();
const tree = await waitForFixture(result, async () => probe.tree());
const started = performance.now();
expect(await result).toBe("timed_out");
expect(performance.now() - started).toBeGreaterThanOrEqual(1000 + GRACE - 50);
expect(await gone(tree.agent, 0)).toBe(true);
Expand Down
20 changes: 12 additions & 8 deletions tests/antigravity/antigravity-plan.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ import {
readAntigravityTokenEmail,
} from "../../packages/oar/src/runtimes/antigravity/token-email.js";
import { asRecord, parseJson, type JsonRecord } from "../../packages/oar/src/shared/json.js";
import { fakeAgentBinary, gone, reportedProcess } from "../fixtures/process-tree.js";
import { holdFixtureDeadline } from "../fixtures/fixture-deadline.js";
import { eventually, fakeAgentBinary, gone, reportedProcess } from "../fixtures/process-tree.js";

// Recorded agy 1.5.13 ACP initialize and authenticate replies (2026-11-20), identifiers removed.
const authFixtureText = readFileSync(path.join(import.meta.dirname, "agy-1.5.13-authenticate.json"), "utf8");
Expand Down Expand Up @@ -55,8 +56,8 @@ function writeFakeState(dir: string, options: FakeAccountOptions): void {

function fakeAgyScript(config: Record<string, unknown>): string {
return [
`import { captureProcess } from ${JSON.stringify(new URL("../fixtures/process-tree.ts", import.meta.url).href)};`,
'import { appendFileSync, writeFileSync } from "node:fs";',
`import { writeProcessReport } from ${JSON.stringify(new URL("../fixtures/process-tree.ts", import.meta.url).href)};`,
'import { appendFileSync } from "node:fs";',
'import { createInterface } from "node:readline";',
`const cfg = ${JSON.stringify(config)};`,
String.raw`const log = (entry) => appendFileSync(cfg.traceFile, JSON.stringify(entry) + "\n");`,
Expand All @@ -65,13 +66,12 @@ function fakeAgyScript(config: Record<string, unknown>): string {
'if (args[0] === "models") { if (!cfg.loggedIn) { console.error("Please sign in to view available models"); process.exit(1); } console.log("gemini-3.8-flash"); process.exit(0); }',
'if (args[0] === "-p" && args[1] === "/usage") { process.stdout.write(JSON.stringify(cfg.usageReply)); process.exit(0); }',
'if (args[0] === "acp") {',
' writeFileSync(cfg.pidFile, JSON.stringify(captureProcess(process.pid)));',
' createInterface({ input: process.stdin }).on("line", (line) => {',
' const req = JSON.parse(line);',
' log({ kind: "rpc", method: req.method, params: req.params });',
String.raw` if (req.method === "initialize") { process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: req.id, result: cfg.initReply }) + "\n"); return; }`,
' if (req.method === "authenticate") {',
' if (cfg.authMode === "stall") { setInterval(() => {}, 1000); return; }',
' if (cfg.authMode === "stall") { writeProcessReport(cfg.pidFile, process.pid); setInterval(() => {}, 1000); return; }',
String.raw` if (cfg.authMode === "no_browser") { process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: req.id, error: { code: -32603, message: "No browser is available here (this is a remote (SSH) session)." } }) + "\n"); return; }`,
String.raw` process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: req.id, result: cfg.authReply }) + "\n");`,
' }',
Expand Down Expand Up @@ -102,7 +102,7 @@ function fakeAccountAgy(options: FakeAccountOptions = {}) {
const env = { HOME: dir, USERPROFILE: dir, DISPLAY: ":99", WAYLAND_DISPLAY: "wayland-0", DBUS_SESSION_BUS_ADDRESS: null, XDG_RUNTIME_DIR: dir };
return {
installation: { kind: "available", via: "executable", command: fakeAgentBinary(dir, guardedFixtureArgs(script)), version: "1.5.13" } as const,
env, dir, trace: () => readTrace(traceFile), acpPid: () => reportedProcess(JSON.parse(readFileSync(pidFile, "utf8"))),
env, dir, ready: () => existsSync(pidFile), trace: () => readTrace(traceFile), acpPid: () => reportedProcess(JSON.parse(readFileSync(pidFile, "utf8"))),
};
}

Expand Down Expand Up @@ -212,9 +212,13 @@ test("omits plan when initialize does not advertise tier or authenticate refuses

test("kills a stalled ACP tier probe at its short deadline and omits plan", async () => {
const stalled = fakeAccountAgy({ persistedMethod: "oauth-personal", authMode: "stall" });
const waitForFixture = holdFixtureDeadline();
const plan = readAntigravityPlan(stalled.installation.command, { HOME: stalled.dir, USERPROFILE: stalled.dir }, { timeoutMs: 400 });
await waitForFixture(plan, async () => {
expect(await eventually(stalled.ready, 10_000), "authenticate published its process identity").toBe(true);
});
const started = performance.now();
const plan = await readAntigravityPlan(stalled.installation.command, { HOME: stalled.dir, USERPROFILE: stalled.dir }, { timeoutMs: 400 });
expect(plan).toBeUndefined();
expect(await plan).toBeUndefined();
expect(performance.now() - started).toBeLessThan(2000);
expect(await gone(stalled.acpPid())).toBe(true);
});
32 changes: 26 additions & 6 deletions tests/ci-runtime-scripts.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,33 @@
import { spawnSync } from "node:child_process";
import { globSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { runExecutable } from "../packages/oar/src/shared/executable/run.js";
import { asRecord, parseJson } from "../packages/oar/src/shared/json.js";
import path from "node:path";
import { expect, test } from "vitest";
import { acceptedPiVersions, checkPiManifestConsistency, satisfiesPublishedRange } from "./fixtures/clean-install-pins.js";

test("CI candidate scripts preserve failures and install only the frozen local fixture", () => {
const result = spawnSync(process.execPath,
["--test", "--test-reporter=tap", ".github/scripts/runtime-ci.test.mjs"], { encoding: "utf8", timeout: 90_000, maxBuffer: 2 * 1024 * 1024 });
expect(result.status, result.stdout + result.stderr).toBe(0);
expect(result.stdout).toMatch(/# fail 0/u);
function fixtureEnvironment(directory: string): NodeJS.ProcessEnv {
const inherited = Object.entries(process.env).filter(([key]) => !/^(?:temp|tmp|tmpdir|runner_temp|npm_config_cache)$/iu.test(key));
return { ...Object.fromEntries(inherited), TEMP: directory, TMP: directory, TMPDIR: directory, RUNNER_TEMP: directory,
npm_config_cache: path.join(directory, "cache") };
}

test("CI candidate scripts preserve failures and install only the frozen local fixture", async () => {
const directory = mkdtempSync(path.join(tmpdir(), "oar-ci-"));
try {
const result = await runExecutable(process.execPath, ["--test", "--test-reporter=tap", ".github/scripts/runtime-ci.test.mjs"], {
timeoutMs: 90_000, env: fixtureEnvironment(directory),
});
if (!result.ok) {
const reports = globSync("oar-runtime install-test-*/reports/*.json", { cwd: directory });
const stages = reports.map(file => {
const raw = readFileSync(path.join(directory, file), "utf8");
return asRecord(parseJson(raw))?.stage;
});
throw new Error(`CI candidate scripts failed: ${JSON.stringify(result.diagnostics)}, active installer stages ${JSON.stringify(stages)}\n${result.stdout}\n${result.stderr}`);
}
expect(result.stdout).toMatch(/# fail 0/u);
} finally { rmSync(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); }
}, 100_000);

test("the gate derives Pi and undici pins from the actual accepted workspace graph", () => {
Expand Down
12 changes: 9 additions & 3 deletions tests/executable-probe-pipes.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { holdFixtureDeadline } from "./fixtures/fixture-deadline.js";
import { setTimeout as delay } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { afterEach, expect, test, vi } from "vitest";
Expand Down Expand Up @@ -31,14 +32,18 @@ test.skipIf(process.platform === "win32").each(["exited", "running", "cancelled"
vi.stubEnv("OAR_KILL_GRACE_MS", "100");
// oxlint-disable-next-line max-statements -- Keep timeout evidence and descendant cleanup in the same real-process observation.
await withTreeProbe({ ignoreSigterm: false }, async (probe) => {
const waitForFixture = holdFixtureDeadline(mode !== "cancelled");
const controller = new AbortController();
const result = runExecutable(process.execPath, [fixture], {
env: { ...process.env, ...probe.env, OAR_FIXTURE_EARLY_EXIT: mode === "running" ? "0" : "1" },
timeoutMs: mode === "cancelled" ? 60_000 : 2000,
signal: controller.signal,
});
const tree = await probe.tree();
if (mode !== "running") { expect(await gone(tree.agent)).toBe(true); }
const tree = await waitForFixture(result, async () => {
const observed = await probe.tree();
if (mode !== "running") { expect(await gone(observed.agent)).toBe(true); }
return observed;
}, controller);
if (mode === "cancelled") { controller.abort(); }
const bounded = await Promise.race([result, delay(5000).then(() => null)]);
expect(bounded).toMatchObject({ ok: false, exitCode: null, diagnostics: mode === "cancelled"
Expand All @@ -56,13 +61,14 @@ test.skipIf(process.platform === "win32").each(["timeout", "cancelled"])(
async (mode) => {
vi.stubEnv("OAR_KILL_GRACE_MS", "100");
await withTreeProbe({ ignoreSigterm: false }, async (probe) => {
const waitForFixture = holdFixtureDeadline(mode !== "cancelled");
const controller = new AbortController();
const result = runExecutable(process.execPath, [fixture], {
env: { ...process.env, ...probe.env, OAR_FIXTURE_CLOSED_PIPES: "1" },
timeoutMs: mode === "cancelled" ? 60_000 : 2000,
signal: controller.signal,
});
const tree = await probe.tree();
const tree = await waitForFixture(result, async () => probe.tree(), controller);
if (mode === "cancelled") { controller.abort(); }
expect(await result).toMatchObject({ ok: false, exitCode: null });
expect(await gone(tree.agent)).toBe(true);
Expand Down
29 changes: 29 additions & 0 deletions tests/fixture-deadline.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { expect, test, vi } from "vitest";
import { runExecutable, type ExecutableResult } from "../packages/oar/src/shared/executable/run.js";
import { holdFixtureDeadline } from "./fixtures/fixture-deadline.js";
import { gone, withTreeProbe } from "./fixtures/process-tree.js";

const fixture = fileURLToPath(new URL("fixtures/probe-background-child.mjs", import.meta.url));

test.each(["deadline", "abort"])("a missing readiness file joins the probe on %s before propagating ENOENT", async mode => {
await withTreeProbe({ ignoreSigterm: false }, async probe => {
const controller = new AbortController();
const waitForFixture = holdFixtureDeadline();
const settled = vi.fn((result: ExecutableResult) => result);
const pending = runExecutable(process.execPath, [fixture], {
env: { ...process.env, ...probe.env, OAR_FIXTURE_CLOSED_PIPES: "1" }, timeoutMs: mode === "abort" ? 60_000 : 200, signal: controller.signal,
}).then(settled);
await expect(waitForFixture(pending, async () => {
await probe.tree();
await readFile(join(probe.dir, "missing-ready"));
}, mode === "abort" ? controller : undefined)).rejects.toMatchObject({ code: "ENOENT" });
expect(settled.mock.calls).toMatchObject([[{ ok: false, diagnostics: mode === "abort" ? { error: { code: "ABORT_ERR" } } : { timeoutMs: 200 } }]]);
vi.useRealTimers();
const tree = await probe.tree();
expect(await gone(tree.agent)).toBe(true);
expect(await gone(tree.grandchild)).toBe(true);
});
});
3 changes: 2 additions & 1 deletion tests/fixtures/fake-installer.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,15 @@
// failed), "prompt" asks on stdin and installs nothing without an answer,
// "hang" starts a worker that holds the output pipes and never finishes.
import { captureProcess } from "./process-tree.ts";
import saveLoginState from "./login-state.mjs";
import { spawn } from "node:child_process";
import { chmodSync, readFileSync, writeFileSync } from "node:fs";

const [stateFile] = process.argv.slice(2);
const state = JSON.parse(readFileSync(stateFile, "utf8"));

function save(changes) {
writeFileSync(stateFile, JSON.stringify({ ...state, ...changes }));
saveLoginState(stateFile, { ...state, ...changes });
}

function installRuntime() {
Expand Down
Loading
Loading