// PEP-265: an agent that made no action since its start while its CLI waits on a question of its own // (trust, model, sign-in) is a failure of the platform: the delay `hang`, the superadmin hears at once, // the story's automatic restarts are not spent. import assert from "node:assert/strict"; import { after, afterEach, describe, test } from "node:test"; import { and, eq } from "drizzle-orm"; process.env.PEPPA_SECRET ??= "mock-secret-for-tests"; import { core, db, project, runner, superadmin, teardown, waitFor } from "./helpers.ts"; const { events } = await import("@peppa/db"); const { startQuestion } = await import("../../runner/src/start-screen.ts"); after(teardown); afterEach(() => runner.setWatchdogSettings(db, ["reset"])); const MIN = 60_000; const sess = (id: number) => core.getSession(db, id); const tickAt = (now: Date) => runner.tick(db, { intervalMs: 0, stallMs: 3_600_000, now }); const eventsOf = async (sid: number, type: string) => db.select().from(events).where(and(eq(events.sessionId, sid), eq(events.type, type))); const TRUST = "Do you trust the files in this folder?\n\n❯ 1. Yes, proceed\n 2. No, exit"; async function storyAtWork(scenario: Parameters[0]) { const p = await project(scenario); const ref = await core.resolveTask(db, p.taskKey); await core.updateTask(db, ref, { status: "in_progress" }); return { p, scope: { projectId: ref.project.id, taskId: ref.task.id } }; } describe("Вопросы CLI на старте узнаются", () => { test("Claude: доверие, модель, вход, настройка", () => { assert.equal(startQuestion("claude", `✻ Claude Code\n\n${TRUST}\n\n\n`), "trust"); assert.equal(startQuestion("claude", "Fable 5.2 now uses usage credits\n 1. Continue\n 2. Exit"), "model"); assert.equal(startQuestion("claude", "Select login method:\n ❯ 1. Claude account with subscription"), "login"); assert.equal(startQuestion("claude", "Invalid API key · Please run /login"), "login"); assert.equal(startQuestion("claude", "WARNING: Claude Code running in Bypass Permissions mode\n ❯ 1. No, exit\n 2. Yes, I accept"), "setup"); }); test("Codex: доверие, меню модели, вход", () => { assert.equal(startQuestion("codex", "> You are in /w/s1\n\n Do you trust the contents of this directory?\n\n› 1. Yes, continue\n 2. No, quit"), "trust"); assert.equal(startQuestion("codex", "Switch to gpt-5-mini for lower credit usage?\n› 1. Switch\n 2. Keep current model\n\n Press enter select"), "model"); assert.equal(startQuestion("codex", "Welcome to Codex\n\n› 1. Sign in with ChatGPT\n 2. Provide your own API key"), "login"); }); test("Работа агента — не вопрос", () => { assert.equal(startQuestion("claude", "⏺ Bash(pnpm test)\n ⎿ ok 12 tests\n> "), null); assert.equal(startQuestion("codex", "• Running pnpm install\n"), null); assert.equal(startQuestion("opencode", TRUST), null, "OpenCode is not checked"); }); }); describe("Зависание на старте — сбой платформы", () => { test("Вопрос о доверии: задержка и сообщение суперадмину, попытки задачи не тронуты", async () => { const sent = await superadmin(); const { p, scope } = await storyAtWork({ startQuestion: TRUST, turns: [[{ say: "Работаю." }]] }); const sid = await p.start(); await p.waitLog("question shown", (e) => e.ev === "start_question"); const launched = (await sess(sid)).watchState?.launchedAt; assert.ok(launched, "launch time saved"); // Not yet: under 90 s. await tickAt(new Date(launched + 30_000)); assert.equal(await core.getPlatformDelay(db, scope, "hang"), null); await tickAt(new Date(launched + 100_000)); const d = await core.getPlatformDelay(db, scope, "hang"); assert.ok(d, "the delay is on the story"); assert.equal(d.exhausted, false); const texts = await waitFor("superadmin told", async () => ((await sent()).length ? await sent() : null)); assert.equal(texts.length, 1); assert.match(texts[0]!, /завис на старте — ждёт ответа на экране \(доверие к папке\)/); const s = await sess(sid); assert.equal(s.status, "failed"); assert.deepEqual(s.watchState?.restarts ?? [], [], "no automatic restart spent"); assert.equal(s.watchState?.restartFree, true); assert.equal(s.watchState?.hangs, 1); assert.equal((await p.pending(sid)).length, 0, "nothing for the owner"); assert.equal((await eventsOf(sid, "start_hang")).length, 1); await runner.stopSession(db, sid).catch(() => {}); }); test("Третье зависание подряд — агент остановлен, карточка исчерпана", async () => { const sent = await superadmin(); const { p, scope } = await storyAtWork({ startQuestion: TRUST, turns: [[{ say: "Работаю." }]] }); const sid = await p.start(); let t = Date.now(); for (let n = 1; n <= 3; n++) { const gen = await waitFor(`gen ${n} launched`, async () => { const s = await sess(sid); return s.watchState?.launchedGen === s.generation && s.status === "running" ? s : null; }); await waitFor(`question ${n} shown`, async () => p.log().filter((e) => e.ev === "start_question").length >= n || null); t = Math.max(t, gen.watchState!.launchedAt!) + 100_000; await tickAt(new Date(t)); assert.equal((await sess(sid)).watchState?.hangs, n); // The planned restart (5, then 15 min) — not counted as an automatic restart. if (n < 3) { t += (n === 1 ? 5 : 15) * MIN + 1000; await tickAt(new Date(t)); } } const s = await sess(sid); assert.equal(s.status, "failed"); assert.equal(s.watchState?.restartAt, undefined, "no more restarts"); assert.deepEqual(s.watchState?.restarts ?? [], []); assert.equal((await core.getPlatformDelay(db, scope, "hang"))?.exhausted, true); assert.equal((await eventsOf(sid, "start_hang_retried")).length, 2); assert.ok((await sent()).some((x) => /зависает на старте 3 раза подряд/.test(x))); }); test("Агент уже действует — текст про доверие на экране не зависание", async () => { const sent = await superadmin(); const { p, scope } = await storyAtWork({ turns: [[{ say: TRUST }]] }); const sid = await p.start(); await p.waitLog("turn 0", (e) => e.ev === "turn_end"); const s = await waitFor("acted", async () => { const x = await sess(sid); return x.watchState?.actedGen === x.generation ? x : null; }); await tickAt(new Date(s.watchState!.launchedAt! + 100_000)); assert.equal(await core.getPlatformDelay(db, scope, "hang"), null); assert.deepEqual(await sent(), []); await runner.stopSession(db, sid); }); test("Порог 0 — проверка выключена", async () => { await runner.setWatchdogSettings(db, ["startHangSec=0"]); const { p, scope } = await storyAtWork({ startQuestion: TRUST, turns: [] }); const sid = await p.start(); await p.waitLog("question shown", (e) => e.ev === "start_question"); await tickAt(new Date((await sess(sid)).watchState!.launchedAt! + 10 * MIN)); assert.equal(await core.getPlatformDelay(db, scope, "hang"), null); await runner.stopSession(db, sid); }); });