Files
crosscode-platform/apps/agent/tests/loop.test.ts
T
joshuaandClaude Opus 5.5 43189c599a Release agent@1.1.1: stats during jobs, its real version
Stats go every minute on their own timer, also while a job runs (before,
a 30-minute install made the Hub alert that the server was down). The
version constant said 1.0.1 in 1.1.0; a test keeps it equal to
package.json now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 19:03:19 +02:00

157 lines
7.6 KiB
TypeScript

import fs from "node:fs";
import path from "node:path";
import { agent } from "@crosscode/contracts";
import { decryptExport } from "@crosscode/contracts/signing";
import { HubRequestError, type HubClient } from "../src/hub";
import { Agent } from "../src/loop";
import type { RunResult } from "../src/runner";
import { SeenJobs } from "../src/verify";
import { config, job, NOW, serverKeys, tempState } from "./helpers";
const state = tempState();
function fakeHub(jobs: unknown[]) {
const posts: { path: string; body: unknown }[] = [];
const puts: { path: string; body: Uint8Array }[] = [];
let down = false;
const hub: HubClient = {
async post(p, body) {
if (down) throw new HubRequestError("down", 0, "HUB_UNREACHABLE");
posts.push({ path: p, body });
if (p === "/api/agent/v1/poll") return { jobs: jobs.splice(0), pollSeconds: 30 };
return null;
},
async put(p, body) {
puts.push({ path: p, body });
return null;
},
};
return { hub, posts, puts, setDown: (v: boolean) => { down = v; } };
}
const ok = (over: Partial<RunResult> = {}): RunResult => ({ status: "succeeded", steps: [{ name: "x", startedAt: NOW.toISOString(), finishedAt: NOW.toISOString(), outcome: "ok" }], result: {}, log: ["==> done"], startedAt: NOW.toISOString(), finishedAt: NOW.toISOString(), ...over });
type Run = (args: string[], job: agent.AgentJob) => Promise<RunResult>;
function make(jobs: unknown[], run: jest.Mock<ReturnType<Run>, Parameters<Run>> = jest.fn<ReturnType<Run>, Parameters<Run>>(async () => ok())) {
const h = fakeHub(jobs);
const a = new Agent({ config, keys: { ed25519Pem: serverKeys.ed25519.privateKeyPem, x25519Pem: serverKeys.x25519.privateKeyPem }, hub: h.hub, seen: new SeenJobs(path.join(state, `seen-${Math.random()}.json`)), run, now: () => NOW });
return { a, run, ...h };
}
const reports = (posts: { path: string; body: unknown }[]) => posts.filter((p) => p.path === "/api/agent/v1/report").map((p) => p.body as agent.AgentReport);
describe("the agent loop", () => {
it("keeps sending stats while a long job runs, so the Hub doesn't think it's down", async () => {
jest.useFakeTimers();
try {
let finish!: () => void;
const longRun = jest.fn<ReturnType<Run>, Parameters<Run>>(() => new Promise<RunResult>((resolve) => { finish = () => resolve(ok()); }));
const h = fakeHub([job()]);
const a = new Agent({ config, keys: { ed25519Pem: serverKeys.ed25519.privateKeyPem, x25519Pem: serverKeys.x25519.privateKeyPem }, hub: h.hub, seen: new SeenJobs(path.join(state, `seen-${Math.random()}.json`)), run: longRun, now: () => NOW, stats: async () => ({}) as agent.AgentStats });
const running = a.start();
await jest.advanceTimersByTimeAsync(10);
expect(longRun).toHaveBeenCalledTimes(1);
// 20 minutes of a job: a stats post every minute all the way through.
await jest.advanceTimersByTimeAsync(20 * 60 * 1000);
const stats = h.posts.filter((p) => p.path === "/api/agent/v1/stats").length;
expect(stats).toBeGreaterThanOrEqual(20);
expect(reports(h.posts)).toHaveLength(0);
finish();
await jest.advanceTimersByTimeAsync(10);
expect(reports(h.posts)).toHaveLength(1);
a.stop();
await jest.advanceTimersByTimeAsync(60 * 1000);
await running;
} finally {
jest.useRealTimers();
}
});
it("runs a valid job once and reports it", async () => {
const j = job();
const { a, run, posts } = make([j, j]);
await a.pollOnce();
expect(run).toHaveBeenCalledTimes(1);
expect(run.mock.calls[0]).toEqual([["deploy", "hope", "events", "--version", "events@2.4.1"], expect.objectContaining({ id: j.id })]);
// The second copy is a replay: refused quietly (the first one's report already went).
const rs = reports(posts);
expect(rs.map((r) => [r.jobId, r.status])).toEqual([[j.id, "succeeded"]]);
expect(agent.agentReportSchema.safeParse(rs[0]).success).toBe(true);
});
it("reports refused and expired jobs without running them", async () => {
const forged = { ...job(), signature: "A".repeat(86) };
const late = job({ expiresAt: "2026-11-20T12:01:00.000Z", notBefore: "2026-11-20T11:00:00.000Z" });
const { a, run, posts } = make([forged, late]);
await a.pollOnce();
expect(run).not.toHaveBeenCalled();
expect(reports(posts).map((r) => r.status)).toEqual(["refused", "expired"]);
});
it("keeps a report it can't send and sends it on the next poll", async () => {
const j = job();
let setDownLater: (v: boolean) => void = () => {};
const { a, posts, setDown } = make([j], jest.fn<ReturnType<Run>, Parameters<Run>>(async () => { setDownLater(true); return ok(); }));
setDownLater = setDown;
await a.pollOnce();
expect(reports(posts)).toEqual([]);
expect(fs.readdirSync(path.join(state, "outbox"))).toContain(`${j.id}.json`);
setDown(false);
await a.pollOnce();
expect(reports(posts).map((r) => r.jobId)).toEqual([j.id]);
expect(fs.readdirSync(path.join(state, "outbox"))).toEqual([]);
});
it("backs off while the Hub is unreachable", async () => {
const { a, setDown } = make([]);
setDown(true);
expect(await a.pollOnce()).toBe(60);
expect(await a.pollOnce()).toBe(120);
setDown(false);
expect(await a.pollOnce()).toBe(30);
});
it("export: encrypts the ZIP, uploads it, and only the report carries the key", async () => {
const j = job({ type: "export", args: { church: "hope", exportId: "exp_abcdefgh" } });
const run = jest.fn<ReturnType<Run>, Parameters<Run>>(async (args: string[]) => {
fs.writeFileSync(args[3]!, "PK zip bytes");
return ok({ result: { file: args[3], bytes: 12 } });
});
const { a, puts, posts } = make([j], run);
await a.pollOnce();
expect(puts).toHaveLength(1);
expect(puts[0]!.path).toBe("/api/agent/v1/exports/exp_abcdefgh");
const r = reports(posts)[0]!;
expect(r.status).toBe("succeeded");
const key = r.result.key as string;
expect(decryptExport(puts[0]!.body, key).toString()).toBe("PK zip bytes");
expect(Buffer.from(puts[0]!.body).includes(Buffer.from("PK zip"))).toBe(false);
expect(fs.readdirSync(path.join(state, "exports"))).toEqual([]);
});
it("status on the central server: its own stats, without crosscode (which isn't installed there)", async () => {
const h = fakeHub([job({ type: "status", args: {} })]);
const run = jest.fn<ReturnType<Run>, Parameters<Run>>(async () => ok());
const stats = { schema: "crosscode.agent-stats/1", central: { proxyBindAddr: "127.0.0.1", allowPorts: null, frpsRunning: true } } as unknown as agent.AgentStats;
const a = new Agent({ config: { ...config, mode: "central" }, keys: { ed25519Pem: serverKeys.ed25519.privateKeyPem, x25519Pem: serverKeys.x25519.privateKeyPem }, hub: h.hub, seen: new SeenJobs(path.join(state, `seen-${Math.random()}.json`)), run, stats: async () => stats, now: () => NOW });
await a.pollOnce();
expect(run).not.toHaveBeenCalled();
const r = reports(h.posts)[0]!;
expect(r).toMatchObject({ type: "status", status: "succeeded", result: { stats } });
expect(agent.agentReportSchema.safeParse(r).success).toBe(true);
});
it("status on a church server runs crosscode status", async () => {
const { a, run } = make([job({ type: "status", args: {} })]);
await a.pollOnce();
expect(run.mock.calls[0]![0]).toEqual(["status", "--no-fetch"]);
});
it("a job that throws is reported as failed", async () => {
const { a, posts } = make([job()], jest.fn<ReturnType<Run>, Parameters<Run>>(async () => { throw new Error("boom"); }));
await a.pollOnce();
expect(reports(posts)[0]).toMatchObject({ status: "failed", message: "boom" });
});
});