Долгоживущий агент чата (только для managerIds, тестовый менеджер) и тайминг чата (chat_timing, миграция 016); тесты; docs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
134
packages/khbuild_assistant_prep/src/live-runner.test.ts
Normal file
134
packages/khbuild_assistant_prep/src/live-runner.test.ts
Normal file
@@ -0,0 +1,134 @@
|
||||
import { mkdtempSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { ClaudeError } from "./agents/cli-runner.js";
|
||||
import { createLiveRunner, type LiveRunner } from "./agents/live-runner.js";
|
||||
|
||||
/** Фейковый claude: читает JSON-строки со stdin, на каждое сообщение отвечает событием result; DIE - падает, HANG - молчит. */
|
||||
const FAKE = `
|
||||
const rl = require("readline").createInterface({ input: process.stdin });
|
||||
const sid = process.argv[process.argv.indexOf("--session-id") + 1] || process.argv[process.argv.indexOf("--resume") + 1];
|
||||
if (process.env.FAKE_NO_SESSION && process.argv.includes("--resume")) { console.error("No conversation found with session ID " + sid); process.exit(1); }
|
||||
let n = 0;
|
||||
rl.on("line", (line) => {
|
||||
const m = JSON.parse(line); const text = m.message.content; n++;
|
||||
if (text === "HANG") return;
|
||||
if (text === "DIE") process.exit(3);
|
||||
console.log(JSON.stringify({ type: "system", subtype: "init", session_id: sid }));
|
||||
console.log(JSON.stringify({ type: "result", subtype: "success", is_error: text === "ERR", result: "pid=" + process.pid + " n=" + n + " " + text, session_id: sid, total_cost_usd: 0.01 * n, duration_ms: 5 }));
|
||||
});
|
||||
rl.on("close", () => process.exit(0));
|
||||
`;
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "llmtest-live-"));
|
||||
const script = join(dir, "fake-claude.cjs");
|
||||
writeFileSync(script, FAKE);
|
||||
|
||||
const runners: LiveRunner[] = [];
|
||||
const mk = (o: { idleMs?: number; warmupMs?: number; timeoutMs?: number } = {}) => {
|
||||
const events: string[] = [];
|
||||
const r = createLiveRunner({ bin: process.execPath, prefixArgs: [script], idleMs: o.idleMs ?? 60_000, warmupMs: o.warmupMs ?? 0, timeoutMs: o.timeoutMs ?? 5_000, onEvent: (e) => events.push(e.kind) });
|
||||
runners.push(r);
|
||||
return { r, events };
|
||||
};
|
||||
const call = (cwd: string, prompt: string, sessionId = "11111111-1111-4111-8111-111111111111", resume = false) => ({ prompt, cwd, sessionId, resume, tools: "chat" as const });
|
||||
const pid = (t: string) => t.match(/pid=(\d+)/)![1];
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
afterEach(() => { for (const r of runners.splice(0)) r.closeAll(); });
|
||||
|
||||
describe("долгоживущий агент (фейковый claude)", () => {
|
||||
it("один процесс на несколько ходов; стоимость - по ходу, а не накопительно", async () => {
|
||||
const { r, events } = mk();
|
||||
const cwd = join(dir, "m1");
|
||||
const a = await r.run(call(cwd, "привет"));
|
||||
expect(r.isActive(cwd)).toBe(true);
|
||||
const b = await r.run(call(cwd, "ещё"));
|
||||
expect(pid(b.text)).toBe(pid(a.text));
|
||||
expect(b.text).toContain("n=2");
|
||||
expect(a.costUsd).toBeCloseTo(0.01);
|
||||
expect(b.costUsd).toBeCloseTo(0.01); // 0.02 накопительно - 0.01 предыдущего хода
|
||||
expect(events.filter((e) => e === "start")).toHaveLength(1);
|
||||
expect(r.activeCount()).toBe(1);
|
||||
});
|
||||
|
||||
it("закрывается через простой; следующий ход стартует новый процесс", async () => {
|
||||
const { r, events } = mk({ idleMs: 150 });
|
||||
const cwd = join(dir, "m2");
|
||||
const a = await r.run(call(cwd, "раз"));
|
||||
await sleep(500);
|
||||
expect(r.isActive(cwd)).toBe(false);
|
||||
expect(events).toContain("idle_close");
|
||||
const b = await r.run(call(cwd, "два", "11111111-1111-4111-8111-111111111111", true));
|
||||
expect(pid(b.text)).not.toBe(pid(a.text));
|
||||
});
|
||||
|
||||
it("новый ход сбрасывает таймер простоя", async () => {
|
||||
const { r } = mk({ idleMs: 300 });
|
||||
const cwd = join(dir, "m3");
|
||||
await r.run(call(cwd, "раз"));
|
||||
await sleep(200);
|
||||
await r.run(call(cwd, "два"));
|
||||
await sleep(200);
|
||||
expect(r.isActive(cwd)).toBe(true); // с первого хода прошло 400 мс > idleMs, но таймер перезапущен вторым ходом
|
||||
});
|
||||
|
||||
it("после старта процесса ждёт warmup, на следующих ходах - нет", async () => {
|
||||
const { r } = mk({ warmupMs: 400 });
|
||||
const cwd = join(dir, "m4");
|
||||
const t0 = Date.now();
|
||||
await r.run(call(cwd, "раз"));
|
||||
expect(Date.now() - t0).toBeGreaterThanOrEqual(380);
|
||||
const t1 = Date.now();
|
||||
await r.run(call(cwd, "два"));
|
||||
expect(Date.now() - t1).toBeLessThan(300);
|
||||
});
|
||||
|
||||
it("таймаут хода: процесс убит, ошибка timeout, следующий ход работает", async () => {
|
||||
const { r } = mk({ timeoutMs: 300 });
|
||||
const cwd = join(dir, "m5");
|
||||
await expect(r.run(call(cwd, "HANG"))).rejects.toMatchObject({ kind: "timeout" });
|
||||
expect(r.isActive(cwd)).toBe(false);
|
||||
expect((await r.run(call(cwd, "жив"))).text).toContain("жив");
|
||||
});
|
||||
|
||||
it("падение процесса посреди хода: ошибка failed, следующий ход стартует заново", async () => {
|
||||
const { r } = mk();
|
||||
const cwd = join(dir, "m6");
|
||||
await r.run(call(cwd, "раз"));
|
||||
const err = await r.run(call(cwd, "DIE")).catch((e) => e);
|
||||
expect(err).toBeInstanceOf(ClaudeError);
|
||||
expect(err.kind).toBe("failed");
|
||||
expect(r.isActive(cwd)).toBe(false);
|
||||
expect((await r.run(call(cwd, "снова", "11111111-1111-4111-8111-111111111111", true))).text).toContain("снова");
|
||||
});
|
||||
|
||||
it("is_error в результате - ошибка, процесс остаётся жив", async () => {
|
||||
const { r } = mk();
|
||||
const cwd = join(dir, "m7");
|
||||
await expect(r.run(call(cwd, "ERR"))).rejects.toMatchObject({ kind: "failed" });
|
||||
expect(r.isActive(cwd)).toBe(true);
|
||||
});
|
||||
|
||||
it("сессия не найдена при --resume -> no_session", async () => {
|
||||
process.env.FAKE_NO_SESSION = "1";
|
||||
try {
|
||||
const { r } = mk();
|
||||
await expect(r.run(call(join(dir, "m8"), "x", "22222222-2222-4222-8222-222222222222", true))).rejects.toMatchObject({ kind: "no_session" });
|
||||
} finally {
|
||||
delete process.env.FAKE_NO_SESSION;
|
||||
}
|
||||
});
|
||||
|
||||
it("другая сессия в той же папке: старый процесс закрывается, стартует новый; close() закрывает", async () => {
|
||||
const { r } = mk();
|
||||
const cwd = join(dir, "m9");
|
||||
const a = await r.run(call(cwd, "раз"));
|
||||
const b = await r.run(call(cwd, "два", "33333333-3333-4333-8333-333333333333"));
|
||||
expect(pid(b.text)).not.toBe(pid(a.text));
|
||||
expect(r.activeCount()).toBe(1);
|
||||
r.close(cwd);
|
||||
expect(r.isActive(cwd)).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user