214 lines
14 KiB
TypeScript
214 lines
14 KiB
TypeScript
// PEP-107: development doesn't stop on a limit — a runner moves to another provider's
|
||
// subscription (Claude ↔ Codex) when its pool has no free one of the same provider; the pool
|
||
// is visible; a project down to one subscription is warned before the limit; a superadmin
|
||
// lends a spare subscription for a while.
|
||
import assert from "node:assert/strict";
|
||
import { after, before, describe, test } from "node:test";
|
||
import { events, settings } from "@peppa/db";
|
||
import { core, db, project, runner, setDefaultOwner, teardown, tick } from "./helpers.ts";
|
||
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
|
||
type User = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
let pm: User;
|
||
let admin: User;
|
||
const CHAT = 5550107;
|
||
before(async () => {
|
||
pm = await core.upsertUserFromGitea(db, { id: 107, login: "mock-pm-107" }, { access_token: "x" });
|
||
admin = await core.upsertUserFromGitea(db, { id: 1107, login: "mock-admin-107" }, { access_token: "x" });
|
||
await core.setSetting(db, "platform.admins", [admin.login]);
|
||
db.$client.prepare("UPDATE users SET telegram_chat_id = ?, telegram_user_id = ? WHERE id = ?").run(CHAT, CHAT, pm.id);
|
||
setDefaultOwner(pm.id);
|
||
});
|
||
after(teardown);
|
||
|
||
const TOKEN = (tag: string) => `sk-ant-oat01-mock${"x".repeat(24)}${tag}`;
|
||
const claudeSub = (name: string, tag: string) => runner.addSubscription(db, { provider: "claude", name, method: "token", secret: TOKEN(tag), createdBy: pm.id });
|
||
const codexSub = (name: string, key: string) => runner.addSubscription(db, { provider: "codex", name, method: "api_key", secret: key, createdBy: pm.id });
|
||
const sess = (id: number) => core.getSession(db, id);
|
||
let seq = 0;
|
||
const poolFor = async (key: string, ids: number[]) => {
|
||
const pool = await core.createPool(db, { name: `Пул F${++seq}`, subscriptionIds: ids });
|
||
await core.setProjectPool(db, (await core.getProject(db, key)).id, pool.id);
|
||
return pool;
|
||
};
|
||
const outboxTexts = async (prefix: string) =>
|
||
db.$client
|
||
.prepare("SELECT params FROM telegram_outbox WHERE dedupe_key LIKE ?")
|
||
.all(`${prefix}%`)
|
||
.map((r) => String((JSON.parse(String((r as { params: string }).params)) as { text: string }).text));
|
||
const typeEvents = async (type: string) => (await db.select().from(events)).filter((e) => e.type === type);
|
||
|
||
describe("Переезд на подписку другого провайдера", () => {
|
||
test("Claude упёрся в лимит, в пуле есть ChatGPT: новый запуск Codex без resume, PM получает «переехал»", async () => {
|
||
const a = await claudeSub("Cross A", "xlimA");
|
||
const c = await codexSub("Cross C", "mock-openai-key-crossC");
|
||
const p = await project({ turns: [[{ limit: { resetInSec: 3600, credential: "xlimA" } }, { say: "Дальше на ChatGPT." }]] });
|
||
await poolFor(p.key, [a.id, c.id]);
|
||
const sid = await p.start();
|
||
assert.equal((await sess(sid)).provider, "claude");
|
||
await p.waitStatus(sid, "rate_limited");
|
||
assert.equal((await sess(sid)).rotateReason, "limit");
|
||
await tick();
|
||
const start = await p.waitLog("relaunched on Codex", (e) => e.ev === "start" && e.gen === "2");
|
||
assert.equal(start.resume, null, "a conversation doesn't move between CLIs");
|
||
assert.equal(start.codexHome, runner.codexHome(c.id));
|
||
assert.match(String((start.argv as string[]).at(-1)), /Восстанови контекст/);
|
||
const s = await sess(sid);
|
||
assert.equal(s.provider, "codex");
|
||
assert.equal(s.subscriptionId, c.id);
|
||
assert.equal(s.conversationId, null);
|
||
const ev = (await typeEvents(runner.SWITCH_EVENT)).find((e) => e.sessionId === sid)!.payload as Record<string, unknown>;
|
||
assert.deepEqual({ from: ev.fromProvider, to: ev.toProvider, carried: ev.carried }, { from: "claude", to: "codex", carried: "fresh" });
|
||
const [msg] = await outboxTexts(`rot:${sid}:g2:`);
|
||
assert.match(msg!, /переехал на другую подписку \(.*ChatGPT \(Codex\) — начал заново с контекстом из стори/);
|
||
await runner.stopSession(db, sid);
|
||
});
|
||
|
||
test("Подписка того же провайдера в приоритете перед другим", async () => {
|
||
const [a, b] = [await claudeSub("Pref A", "prefA"), await claudeSub("Pref B", "prefB")];
|
||
const c = await codexSub("Pref C", "mock-openai-key-prefC");
|
||
const p = await project({ turns: [] });
|
||
await poolFor(p.key, [a.id, c.id, b.id]);
|
||
assert.equal((await core.rotationCandidate(db, { projectId: (await core.getProject(db, p.key)).id, provider: "claude", subscriptionId: a.id }))?.id, b.id);
|
||
});
|
||
|
||
test("Переезд между провайдерами выключен (PEPPA_ROTATE_CROSS=off): ждёт сброса", async () => {
|
||
const a = await claudeSub("NoCross A", "nocrossA");
|
||
const c = await codexSub("NoCross C", "mock-openai-key-nocross");
|
||
const p = await project({ turns: [] });
|
||
await poolFor(p.key, [a.id, c.id]);
|
||
const projectId = (await core.getProject(db, p.key)).id;
|
||
process.env.PEPPA_ROTATE_CROSS = "off";
|
||
try {
|
||
assert.equal(await core.rotationCandidate(db, { projectId, provider: "claude", subscriptionId: a.id }), null);
|
||
} finally {
|
||
delete process.env.PEPPA_ROTATE_CROSS;
|
||
}
|
||
assert.equal((await core.rotationCandidate(db, { projectId, provider: "claude", subscriptionId: a.id }))?.id, c.id);
|
||
});
|
||
|
||
test("Лимит без замены: сообщение подсказывает добавить подписку", async () => {
|
||
const a = await claudeSub("Hint A", "hintlimA");
|
||
const p = await project({ turns: [[{ limit: { resetInSec: 600, credential: "hintlimA" } }]] });
|
||
await poolFor(p.key, [a.id]);
|
||
const sid = await p.start();
|
||
await p.waitStatus(sid, "rate_limited");
|
||
assert.match((await p.waitQuestion(sid, "attention")).text, /продолжит в \d\d:\d\d сам\.\nЧтобы агенты не ждали — добавьте ещё одну подписку/);
|
||
await runner.stopSession(db, sid);
|
||
});
|
||
});
|
||
|
||
describe("Подписки пула на виду", () => {
|
||
test("Состояние каждой подписки: в работе, свободна, лимит до, использование окна", async () => {
|
||
const [a, b, l] = [await claudeSub("View A", "viewA"), await claudeSub("View B", "viewB"), await claudeSub("View L", "viewL")];
|
||
const p = await project({ turns: [] });
|
||
const pool = await poolFor(p.key, [a.id, b.id, l.id]);
|
||
const projectId = (await core.getProject(db, p.key)).id;
|
||
const s = await core.createSession(db, { projectId, subscriptionId: a.id });
|
||
await core.updateSession(db, s.id, { status: "running" });
|
||
await core.markSubscriptionLimited(db, l.id, new Date(Date.now() + 3600_000));
|
||
const resetsAt = Date.now() + 2 * 3600_000;
|
||
await core.setSetting(db, core.accountKey(b.id), { fiveHour: { pct: 42, resetsAt }, at: Date.now() });
|
||
const o = (await core.poolOverview(db, pool.id))!;
|
||
const by = (id: number) => o.subscriptions.find((x) => x.id === id)!;
|
||
assert.equal(by(a.id).label, "в работе: 1 агент");
|
||
assert.equal(by(b.id).label, "свободна");
|
||
assert.equal(by(b.id).usage?.pct, 42);
|
||
assert.match(by(l.id).label, /^лимит до \d\d:\d\d$/);
|
||
assert.equal(o.usableCount, 2);
|
||
assert.deepEqual(o.projects.map((x) => x.key), [p.key]);
|
||
await core.updateSession(db, s.id, { status: "done" });
|
||
});
|
||
|
||
test("Владелец добавляет вторую подписку ChatGPT в свой пул", async () => {
|
||
const p = await project({ turns: [] });
|
||
const proj = await core.getProject(db, p.key);
|
||
await runner.connectOwnSubscription(db, pm, proj, "claude", TOKEN("own1"));
|
||
const before = (await core.projectPool(db, proj.id))!;
|
||
const { subscriptionId } = await runner.connectOwnSubscription(db, pm, proj, "codex_key", "mock-openai-key-own2");
|
||
const pool = (await core.projectPool(db, proj.id))!;
|
||
assert.equal(pool.id, before.id, "the same personal pool");
|
||
const subs = await core.poolSubscriptions(db, pool.id);
|
||
assert.deepEqual(subs.map((x) => x.provider).sort(), ["claude", "codex"]);
|
||
assert.ok(subs.some((x) => x.id === subscriptionId));
|
||
});
|
||
|
||
test("Свою подписку нельзя убрать, пока на ней работают агенты; свободную — можно", async () => {
|
||
const p = await project({ turns: [] });
|
||
const proj = await core.getProject(db, p.key);
|
||
const { subscriptionId: one } = await runner.connectOwnSubscription(db, pm, proj, "claude", TOKEN("rm1"));
|
||
const { subscriptionId: two } = await runner.connectOwnSubscription(db, pm, proj, "claude", TOKEN("rm2"));
|
||
const s = await core.createSession(db, { projectId: proj.id, subscriptionId: one });
|
||
await core.updateSession(db, s.id, { status: "running" });
|
||
await assert.rejects(runner.removeOwnSubscription(db, pm, proj, one!), /Сначала остановите агентов или добавьте другую подписку/);
|
||
await runner.removeOwnSubscription(db, pm, proj, two!);
|
||
const left = (await core.poolSubscriptions(db, (await core.projectPool(db, proj.id))!.id)).map((x) => x.id);
|
||
assert.ok(left.includes(one!) && !left.includes(two!));
|
||
await core.updateSession(db, s.id, { status: "done" });
|
||
});
|
||
});
|
||
|
||
describe("Предупреждение до лимита", () => {
|
||
test("Одна подписка на 90%: одно предупреждение с временем сброса; есть запасная — молчим", async () => {
|
||
const a = await claudeSub("Warn1 A", "w1A");
|
||
const p = await project({ turns: [] });
|
||
const pool = await poolFor(p.key, [a.id]);
|
||
const resetsAt = Date.now() + 3600_000;
|
||
await core.setSetting(db, core.accountKey(a.id), { fiveHour: { pct: 90, resetsAt }, at: Date.now() });
|
||
assert.equal(await core.subscriptionWarnTick(db), 1);
|
||
assert.equal(await core.subscriptionWarnTick(db), 0, "once per window");
|
||
const [text] = await outboxTexts(`subwarn:${a.id}:`);
|
||
assert.match(text!, /Осталась одна рабочая подписка, использовано 90% \(окно 5 ч, сброс в \d\d:\d\d\).*Добавьте ещё одну подписку/);
|
||
assert.equal((await typeEvents("subscription_last_warning")).filter((e) => (e.payload as { subscriptionId: number }).subscriptionId === a.id).length, 1);
|
||
|
||
// A new window crosses the threshold again → a new warning.
|
||
await core.setSetting(db, core.accountKey(a.id), { fiveHour: { pct: 95, resetsAt: resetsAt + 5 * 3600_000 }, at: Date.now() });
|
||
assert.equal(await core.subscriptionWarnTick(db), 1);
|
||
|
||
// With a spare subscription — nothing.
|
||
const b = await claudeSub("Warn1 B", "w1B");
|
||
await core.updatePool(db, pool.id, { subscriptionIds: [a.id, b.id] });
|
||
await core.setSetting(db, core.accountKey(a.id), { fiveHour: { pct: 97, resetsAt: resetsAt + 10 * 3600_000 }, at: Date.now() });
|
||
assert.equal(await core.subscriptionWarnTick(db), 0);
|
||
});
|
||
|
||
test("Баннер CLI без замены (Codex): то же предупреждение, не чаще раза в 5 часов", async () => {
|
||
const c = await codexSub("Warn2 C", "mock-openai-key-w2");
|
||
const p = await project({ turns: [] });
|
||
await poolFor(p.key, [c.id]);
|
||
const now = new Date();
|
||
assert.equal(await core.warnLastSubscription(db, c.id, now), true);
|
||
assert.equal(await core.warnLastSubscription(db, c.id, new Date(now.getTime() + 3600_000)), false);
|
||
assert.equal(await core.warnLastSubscription(db, c.id, new Date(now.getTime() + 6 * 3600_000)), true);
|
||
});
|
||
});
|
||
|
||
describe("Суперадмин одалживает подписку", () => {
|
||
test("Заём попадает в пул, по сроку возвращается сам; повторный заём в тот же пул отклоняется", async () => {
|
||
const own = await claudeSub("Loan own", "loanOwn");
|
||
const spare = await runner.addSubscription(db, { provider: "claude", name: "Loan spare", method: "token", secret: TOKEN("loanSpare"), createdBy: admin.id });
|
||
const p = await project({ turns: [] });
|
||
const pool = await poolFor(p.key, [own.id]);
|
||
await assert.rejects(core.lendSubscription(db, pm, { subscriptionId: spare.id, poolId: pool.id, hours: 2 }), /Не найдено/);
|
||
await assert.rejects(core.lendSubscription(db, admin, { subscriptionId: spare.id, poolId: pool.id, hours: 0 }), /от 1 до 168/);
|
||
const now = new Date();
|
||
const loan = await core.lendSubscription(db, admin, { subscriptionId: spare.id, poolId: pool.id, hours: 2, now });
|
||
assert.equal(loan.until.getTime(), now.getTime() + 2 * 3600_000);
|
||
assert.ok((await core.poolSubscriptions(db, pool.id)).some((x) => x.id === spare.id));
|
||
await assert.rejects(core.lendSubscription(db, admin, { subscriptionId: spare.id, poolId: pool.id, hours: 2 }), /Подписка уже в этом пуле/);
|
||
const o = (await core.poolOverview(db, pool.id))!;
|
||
assert.ok(o.subscriptions.find((x) => x.id === spare.id)!.loan);
|
||
assert.match((await outboxTexts(`loan:${pool.id}:${spare.id}:`))[0]!, /запасная подписка — до \d\d:\d\d/);
|
||
// The owner can't remove a lent subscription.
|
||
await assert.rejects(runner.removeOwnSubscription(db, admin, await core.getProject(db, p.key), spare.id), /вернётся сама по сроку/);
|
||
|
||
assert.equal(await core.expireLoans(db, new Date(now.getTime() + 3600_000)), 0, "not yet");
|
||
await tick();
|
||
assert.equal(await core.expireLoans(db, new Date(now.getTime() + 2 * 3600_000 + 1000)), 1);
|
||
assert.deepEqual((await core.poolSubscriptions(db, pool.id)).map((x) => x.id), [own.id]);
|
||
assert.match((await outboxTexts(`loanback:${pool.id}:${spare.id}:`))[0]!, /вернулась владельцу — срок займа кончился/);
|
||
assert.equal((await db.select().from(settings)).filter((r) => r.key.startsWith("subscription.loan:")).length, 0);
|
||
});
|
||
});
|