// PEP-186: the project's subscription ran out — its owner asks the superadmin for one; «lend» // puts a free subscription of the superadmin into the project's pool for a while, the waiting // agent moves onto it, the time runs out and it goes back; «refuse» tells the owner. import assert from "node:assert/strict"; import { after, before, describe, test } from "node:test"; import { stripAsIs } from "@peppa/shared/i18n"; import { core, db, project, runner, setDefaultOwner, teardown } from "./helpers.ts"; process.env.PEPPA_SECRET = "mock-secret-for-tests"; const { renderQuestion } = await import("@peppa/bot/render"); type User = Awaited>; let admin: User; let platformKey = ""; let seq = 0; const TOKEN = (tag: string) => `sk-ant-oat01-mock${"x".repeat(24)}${tag}`; const claudeSub = (name: string, tag: string, by: number) => runner.addSubscription(db, { provider: "claude", name, method: "token", secret: TOKEN(tag), createdBy: by }); const newUser = (login: string) => core.upsertUserFromGitea(db, { id: 186_000 + ++seq, login }, { access_token: "x" }); before(async () => { admin = await newUser("mock-admin-186"); await core.setSetting(db, "platform.admins", [admin.login]); setDefaultOwner(admin.id); const platform = await project({ turns: [] }); platformKey = platform.key; process.env.PEPPA_PLATFORM_KEY = platform.key; }); after(teardown); /** A project of `owner` whose only subscription is limited for an hour (agents stand). */ async function standingProject(owner: User, tag: string) { setDefaultOwner(owner.id); const p = await project({ turns: [] }); const own = await claudeSub(`Own ${tag}`, `own${tag}`, owner.id); const pool = await core.createPool(db, { name: `Пул ${tag}`, subscriptionIds: [own.id] }); const proj = await core.getProject(db, p.key); await core.setProjectPool(db, proj.id, pool.id); await core.markSubscriptionLimited(db, own.id, new Date(Date.now() + 3 * 3_600_000), "limit"); return { p, proj, pool, own }; } const adminQuestions = async () => (await core.pendingQuestions(db, (await core.getProject(db, platformKey)).id)).filter((q) => q.options?.includes(runner.REQUEST_DENY)); const ownerMessages = async (projectId: number) => (await db.select().from((await import("@peppa/db")).questions)).filter((q) => q.projectId === projectId && q.kind === "attention").map((q) => stripAsIs(q.text)); describe("Попросить подписку у администратора (PEP-186)", () => { test("Лимит → запрос → вопрос с вариантами; «Одолжить до сброса» → заём в наборе, агент переехал, владельцу сообщение; срок вышел → подписка вернулась", async () => { const owner = await newUser("mock-pm-186a"); setDefaultOwner(owner.id); const p = await project({ turns: [[{ limit: { resetInSec: 3600, credential: "ownLim" } }, { say: "Дальше на одолженной." }]] }); const own = await claudeSub("Own Lim", "ownLim", owner.id); const pool = await core.createPool(db, { name: "Пул Lim", subscriptionIds: [own.id] }); const proj = await core.getProject(db, p.key); await core.setProjectPool(db, proj.id, pool.id); const lend = await claudeSub("Admin spare", "adminSpare", admin.id); const sid = await p.start(); await p.waitStatus(sid, "rate_limited"); assert.equal(await runner.subscriptionRequestOffer(db, owner, proj.id), "can"); // The owner's limit question (PEP-150) offers it as an answer — a button in Telegram too. let limitQ: Awaited>[number] | undefined; for (let i = 0; i < 50 && !limitQ; i++) { limitQ = (await core.pendingQuestions(db, proj.id)).find((q) => q.options?.includes(runner.LIMIT_REQUEST)); if (!limitQ) await new Promise((r) => setTimeout(r, 200)); } assert.ok(limitQ, "the limit question offers «Попросить подписку у администратора»"); const tg = renderQuestion(limitQ!, { taskKey: p.taskKey, taskTitle: null, session: await core.getSession(db, sid), webUrl: "http://peppa.test" }); assert.ok(tg.buttons.flat().some((b) => b.text.includes("Попросить подписку")), "a button under the limit message"); assert.equal(await runner.subscriptionRequestOffer(db, admin, proj.id), null, "a superadmin lends himself"); await core.runAsActor({ kind: "user", userId: owner.id, channel: "telegram" }, () => runner.answerAndDeliver(db, limitQ!.id, runner.LIMIT_REQUEST, "telegram")); assert.equal(await runner.subscriptionRequestOffer(db, owner, proj.id), "sent"); const [q] = await adminQuestions(); assert.ok(q, "the superadmin got a question"); assert.match(stripAsIs(q!.text), new RegExp(`${owner.login} просит подписку для проекта «${p.key}»: агенты стоят до \\d\\d:\\d\\d`)); assert.deepEqual(q!.options, [runner.LEND_UNTIL_RESET, runner.LEND_DAY, runner.REQUEST_DENY]); assert.equal(q!.defaultOption, runner.LEND_UNTIL_RESET); assert.equal(q!.msgType, "question"); await runner.answerAndDeliver(db, q!.id, runner.LEND_UNTIL_RESET, "web"); const loan = (await core.listLoans(db)).find((l) => l.poolId === pool.id); assert.equal(loan?.subscriptionId, lend.id, "the superadmin's subscription is lent to the project's pool"); const resumeAt = (await core.getSession(db, sid)).resumeAt; assert.ok(Math.abs(loan!.until.getTime() - (resumeAt?.getTime() ?? Date.now() + 3_600_000)) < 120_000 || loan!.until.getTime() > Date.now() + 50 * 60_000, "until the limit resets"); assert.equal(await runner.subscriptionRequestOffer(db, owner, proj.id), null, "lent — nothing to ask"); await assert.rejects(runner.requestSubscription(db, owner, proj), /уже одолжил подписку/); await p.waitLog("relaunched on the lent subscription", (e) => e.ev === "start" && e.gen === "2"); assert.equal((await core.getSession(db, sid)).subscriptionId, lend.id); const msgs = await ownerMessages(proj.id); assert.ok(msgs.some((t) => /администратор одолжил подписку до \d\d:\d\d — агенты продолжают/.test(t)), msgs.join("\n")); assert.ok(!msgs.some((t) => t.includes("Admin spare")), "the subscription's name is not shown"); await runner.subscriptionRequestTick(db, new Date(loan!.until.getTime() + 1000)); await p.waitLog("back on its own subscription", (e) => e.ev === "start" && e.gen === "3"); assert.equal((await core.getSession(db, sid)).subscriptionId, own.id, "the agent went back to its own subscription"); await runner.stopSession(db, sid); assert.equal((await core.listLoans(db)).some((l) => l.poolId === pool.id), false, "the loan is over"); assert.equal((await core.poolSubscriptions(db, pool.id)).some((s) => s.id === lend.id), false); assert.equal(await runner.subscriptionRequest(db, proj.id), null); assert.ok((await ownerMessages(proj.id)).some((t) => /срок одолженной подписки кончился/.test(t))); }); test("«Отказать» → владельцу сообщение, повторный запрос возможен", async () => { const owner = await newUser("mock-pm-186b"); const { proj } = await standingProject(owner, "deny"); await runner.requestSubscription(db, owner, proj); const q = (await adminQuestions()).at(-1)!; await runner.answerAndDeliver(db, q.id, runner.REQUEST_DENY, "web"); assert.ok((await ownerMessages(proj.id)).some((t) => /администратор отказал в подписке/.test(t))); assert.equal(await runner.subscriptionRequestOffer(db, owner, proj.id), "can"); await runner.requestSubscription(db, owner, proj); const again = (await adminQuestions()).at(-1)!; await runner.answerAndDeliver(db, again.id, "Сегодня нельзя, бюджет кончился", "web"); assert.ok((await ownerMessages(proj.id)).some((t) => t.includes("администратор отказал в подписке: Сегодня нельзя, бюджет кончился"))); }); test("Второй запрос при открытом — отклоняется; не больше 3 запросов в сутки", async () => { const owner = await newUser("mock-pm-186c"); const { proj } = await standingProject(owner, "limit"); await runner.requestSubscription(db, owner, proj); await assert.rejects(runner.requestSubscription(db, owner, proj), /Запрос отправлен — ждём ответа администратора/); for (let i = 0; i < 2; i++) { await runner.answerAndDeliver(db, (await adminQuestions()).at(-1)!.id, runner.REQUEST_DENY, "web"); await runner.requestSubscription(db, owner, proj); } await runner.answerAndDeliver(db, (await adminQuestions()).at(-1)!.id, runner.REQUEST_DENY, "web"); await assert.rejects(runner.requestSubscription(db, owner, proj), /Сегодня вы уже просили подписку 3 раза/); }); test("Свободной подписки нет → в вопросе нет вариантов займа; «Напомнить позже» спрашивает снова через час", async () => { const owner = await newUser("mock-pm-186d"); const { proj } = await standingProject(owner, "none"); const admin2 = await newUser("mock-admin2-186"); await core.setSetting(db, "platform.admins", [admin2.login]); try { await runner.requestSubscription(db, owner, proj); const q = (await adminQuestions()).at(-1)!; assert.match(stripAsIs(q.text), /Свободной подписки сейчас нет/); assert.deepEqual(q.options, [runner.REQUEST_REMIND, runner.REQUEST_DENY]); await runner.answerAndDeliver(db, q.id, runner.REQUEST_REMIND, "web"); assert.equal(await runner.subscriptionRequestOffer(db, owner, proj.id), "sent", "the request stays open"); const before = (await adminQuestions()).length; await runner.subscriptionRequestTick(db, new Date(Date.now() + 1_800_000)); assert.equal((await adminQuestions()).length, before, "not yet"); await runner.subscriptionRequestTick(db, new Date(Date.now() + 3_700_000)); assert.equal((await adminQuestions()).length, before + 1, "asked again"); } finally { await core.setSetting(db, "platform.admins", [admin.login]); } }); test("PEP-206: в «Подписках» — всегда; запрос заранее, пока агенты работают: «Одолжить на сутки» / «Отказать», сам не закрывается", async () => { const owner = await newUser("mock-pm-206"); setDefaultOwner(owner.id); const p = await project({ turns: [] }); const own = await claudeSub("Own ahead", "ownahead", owner.id); const pool = await core.createPool(db, { name: "Пул ahead", subscriptionIds: [own.id] }); const proj = await core.getProject(db, p.key); await core.setProjectPool(db, proj.id, pool.id); await claudeSub("Admin ahead", "adminahead", admin.id); assert.equal(await runner.subscriptionRequestOffer(db, owner, proj.id), null, "agents work: no limit banner"); assert.equal(await runner.subscriptionRequestOffer(db, owner, proj.id, new Date(), { always: true }), "can", "«Подписки» offers it always"); assert.equal(await runner.subscriptionRequestOffer(db, admin, proj.id, new Date(), { always: true }), null, "not to the superadmin"); await assert.rejects(runner.requestSubscription(db, owner, proj), /подписка не нужна/); await runner.requestSubscription(db, owner, proj, new Date(), { ahead: true }); const q = (await adminQuestions()).at(-1)!; assert.match(stripAsIs(q.text), /заранее: агенты пока работают/); assert.deepEqual(q.options, [runner.LEND_DAY, runner.REQUEST_DENY]); await runner.subscriptionRequestTick(db); assert.equal(await runner.subscriptionRequestOffer(db, owner, proj.id, new Date(), { always: true }), "sent", "not closed while the agents work"); assert.equal(await runner.subscriptionRequestOffer(db, owner, proj.id), null, "no «agents stand» banner for it"); await runner.answerAndDeliver(db, q.id, runner.LEND_DAY, "web"); const loans = (await core.listLoans(db)).filter((l) => l.poolId === pool.id); assert.equal(loans.length, 1, "lent into the project's set"); assert.ok(loans[0]!.until.getTime() - Date.now() > 23 * 3_600_000, "for a day"); }); });