403 lines
27 KiB
TypeScript
403 lines
27 KiB
TypeScript
// PEP-67: agent subscriptions (Claude Code / Codex / OpenCode), pools and the subscription a
|
||
// runner starts on. Sign-in and trial runs go through the mock CLIs (mock-claude, mock-codex,
|
||
// mock-opencode) with the real contracts: setup-token, device auth, --with-api-key, -p/exec/run.
|
||
import { stripAsIs } from "@peppa/shared/i18n";
|
||
import assert from "node:assert/strict";
|
||
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
||
import { join, resolve } from "node:path";
|
||
import { fileURLToPath } from "node:url";
|
||
import { after, before, describe, test } from "node:test";
|
||
import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
|
||
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||
|
||
type User = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
let asel: User;
|
||
let dana: User;
|
||
before(async () => {
|
||
asel = await core.upsertUserFromGitea(db, { id: 41, login: "asel" }, { access_token: "x" });
|
||
dana = await core.upsertUserFromGitea(db, { id: 42, login: "mock-dana" }, { access_token: "x" });
|
||
await core.setPlatformAdmins(db, ["asel", "admin"]);
|
||
});
|
||
after(teardown);
|
||
|
||
const TOKEN = (tag: string) => `sk-ant-oat01-mock${"x".repeat(24)}${tag.replace(/[^A-Za-z0-9]/g, "")}`;
|
||
const claudeSub = (name: string, tag = name) =>
|
||
runner.addSubscription(db, { provider: "claude", name, method: "token", secret: TOKEN(tag), createdBy: asel.id });
|
||
const sub = (id: number) => core.getSubscription(db, id);
|
||
|
||
describe("Раздел «Подписки» только для суперадмина", () => {
|
||
test("суперадмин — логин из platform.admins, остальным раздела нет", async () => {
|
||
assert.equal(await core.isSuperadmin(db, asel), true);
|
||
assert.equal(await core.isSuperadmin(db, { login: "ADMIN" }), true);
|
||
assert.equal(await core.isSuperadmin(db, dana), false);
|
||
assert.equal(await core.isSuperadmin(db, null), false);
|
||
await assert.rejects(core.requireSuperadmin(db, dana), /Не найдено/);
|
||
await core.requireSuperadmin(db, asel);
|
||
});
|
||
});
|
||
|
||
describe("Подписка агента", () => {
|
||
test("суперадмин добавляет подписку Claude: ссылка → код → активна, токен зашифрован", async () => {
|
||
const s = await runner.addSubscription(db, { provider: "claude", name: "Claude Max — asel", method: "login", createdBy: asel.id });
|
||
assert.equal(s.status, "pending");
|
||
const login = await runner.pendingLogin(db, s.id);
|
||
assert.match(login!.url, /^https:\/\/claude\.com\/cai\/oauth\/authorize\?/);
|
||
await runner.finishClaudeLogin(db, s.id, "mock-good-1");
|
||
const got = await sub(s.id);
|
||
assert.equal(got.status, "active");
|
||
assert.ok(got.secretEnc && !got.secretEnc.includes("sk-ant"), "stored encrypted");
|
||
assert.match(core.decrypt(got.secretEnc), /^sk-ant-oat01-mock/);
|
||
assert.equal(await runner.pendingLogin(db, s.id), null);
|
||
const listed = (await core.listSubscriptions(db)).find((x) => x.id === s.id)!;
|
||
assert.equal(listed.createdByLogin, "asel");
|
||
assert.equal(listed.activeSessions, 0);
|
||
});
|
||
|
||
test("неверный код Claude: ошибка, подписка не активна; отмена удаляет новую подписку", async () => {
|
||
const s = await runner.addSubscription(db, { provider: "claude", name: "Claude bad", method: "login", createdBy: asel.id });
|
||
await assert.rejects(runner.finishClaudeLogin(db, s.id, "mock-bad-code"), /не принял код/);
|
||
assert.equal((await sub(s.id)).status, "pending");
|
||
assert.equal((await sub(s.id)).secretEnc, null);
|
||
await assert.rejects(runner.finishClaudeLogin(db, s.id, "mock-good-1"), /не начат/);
|
||
await runner.cancelLogin(db, s.id);
|
||
await assert.rejects(sub(s.id), /не найдена/);
|
||
});
|
||
|
||
test("Codex через ChatGPT: ссылка и одноразовый код, вход в собственном CODEX_HOME", async () => {
|
||
const s = await runner.addSubscription(db, { provider: "codex", name: "ChatGPT Pro", method: "device", createdBy: asel.id });
|
||
const login = (await runner.pendingLogin(db, s.id))!;
|
||
assert.equal(login.url, "https://auth.openai.com/codex/device");
|
||
assert.match(login.code!, /^MOCK-[A-Z0-9]{4}$/);
|
||
assert.equal(await runner.pollCodexLogin(db, s.id), "pending");
|
||
writeFileSync(join(runner.codexHome(s.id), "mock-device-approved"), "");
|
||
await waitFor("codex login done", async () => (await runner.pollCodexLogin(db, s.id)) === "active");
|
||
assert.equal((await sub(s.id)).status, "active");
|
||
assert.ok(existsSync(join(runner.codexHome(s.id), "auth.json")));
|
||
assert.ok(runner.codexHome(s.id).startsWith(process.env.PEPPA_HOME!));
|
||
});
|
||
|
||
test("Codex: отказ на устройстве → ошибка входа", async () => {
|
||
const s = await runner.addSubscription(db, { provider: "codex", name: "ChatGPT denied", method: "device", createdBy: asel.id });
|
||
writeFileSync(join(runner.codexHome(s.id), "mock-device-denied"), "");
|
||
await waitFor("codex login failed", async () => (await runner.pollCodexLogin(db, s.id)) === "failed");
|
||
const got = await sub(s.id);
|
||
assert.equal(got.status, "auth_error");
|
||
assert.match(got.lastError!, /denied/);
|
||
});
|
||
|
||
test("Codex по API-ключу: неверный ключ отклонён, верный — активна, ключа нет в БД", async () => {
|
||
await assert.rejects(
|
||
runner.addSubscription(db, { provider: "codex", name: "Codex bad key", method: "api_key", secret: "mock-bad-key-123", createdBy: asel.id }),
|
||
/не принял ключ/,
|
||
);
|
||
assert.equal((await core.listSubscriptions(db)).some((x) => x.name === "Codex bad key"), false);
|
||
const s = await runner.addSubscription(db, { provider: "codex", name: "Codex key", method: "api_key", secret: "mock-openai-key-123", createdBy: asel.id });
|
||
assert.equal(s.status, "active");
|
||
assert.equal(s.secretEnc, null);
|
||
assert.match(readFileSync(join(runner.codexHome(s.id), "auth.json"), "utf8"), /mock-openai-key-123/);
|
||
});
|
||
|
||
test("OpenCode по ключу провайдера: активна, ключ зашифрован", async () => {
|
||
await assert.rejects(runner.addSubscription(db, { provider: "opencode", name: "OC", method: "api_key", secret: "k", keyProvider: "nope", createdBy: asel.id }), /провайдера/);
|
||
const s = await runner.addSubscription(db, { provider: "opencode", name: "OpenCode Anthropic", method: "api_key", secret: "mock-anthropic-key-1", keyProvider: "anthropic", createdBy: asel.id });
|
||
assert.equal(s.status, "active");
|
||
assert.equal(core.subscriptionSecret(s), "mock-anthropic-key-1");
|
||
assert.ok(!s.secretEnc!.includes("mock-anthropic"));
|
||
});
|
||
});
|
||
|
||
describe("Проверка подписки", () => {
|
||
test("лимит → «лимит до …», отозванный вход → «ошибка входа» без секрета, рабочая → активна", async () => {
|
||
const now = new Date("2026-11-14T10:00:00");
|
||
const limited = await claudeSub("Claude limited", "limit");
|
||
const r1 = await runner.checkSubscription(db, limited.id, now);
|
||
assert.equal(r1.status, "limited");
|
||
const l = await sub(limited.id);
|
||
assert.equal(l.status, "limited");
|
||
assert.equal(l.limitedUntil!.getHours(), 17, "reset time from the banner (5pm)");
|
||
|
||
const bad = await claudeSub("Claude revoked", "bad");
|
||
assert.equal((await runner.checkSubscription(db, bad.id, now)).status, "auth_error");
|
||
const b = await sub(bad.id);
|
||
assert.match(b.lastError!, /Invalid API key/);
|
||
assert.ok(!b.lastError!.includes(TOKEN("bad")));
|
||
|
||
const ok = await claudeSub("Claude ok", "fine");
|
||
assert.equal((await runner.checkSubscription(db, ok.id, now)).status, "active");
|
||
|
||
const codexLimited = await runner.addSubscription(db, { provider: "codex", name: "Codex limited", method: "api_key", secret: "mock-limit-key-1", createdBy: asel.id });
|
||
assert.equal((await runner.checkSubscription(db, codexLimited.id, now)).status, "limited");
|
||
const oc = await runner.addSubscription(db, { provider: "opencode", name: "OC bad", method: "api_key", secret: "mock-bad-oc-key", keyProvider: "openai", createdBy: asel.id });
|
||
assert.equal((await runner.checkSubscription(db, oc.id, now)).status, "auth_error");
|
||
});
|
||
});
|
||
|
||
describe("Пулы и подписка сессии", () => {
|
||
test("пул для ротации: раннеры проекта стартуют на свободной подписке пула", async () => {
|
||
const a = await claudeSub("Claude A");
|
||
const b = await claudeSub("Claude B");
|
||
const c = await runner.addSubscription(db, { provider: "codex", name: "Codex C", method: "api_key", secret: "mock-openai-key-c", createdBy: asel.id });
|
||
const pool = await core.createPool(db, { name: "Основной", subscriptionIds: [a.id, b.id, c.id], createdBy: asel.id });
|
||
assert.deepEqual((await core.listPools(db)).find((p) => p.id === pool.id)!.subscriptionIds, [a.id, b.id, c.id]);
|
||
|
||
const p1 = await project({ turns: [[{ say: "ok" }]] });
|
||
const p2 = await project({ turns: [[{ say: "ok" }]] });
|
||
for (const p of [p1, p2]) await core.setProjectPool(db, (await core.getProject(db, p.key)).id, pool.id);
|
||
|
||
const s1 = await p1.start();
|
||
assert.equal((await p1.session(s1)).subscriptionId, a.id);
|
||
assert.equal((await p1.session(s1)).subscriptionName, "Claude A");
|
||
assert.equal((await p1.waitLog("started", (e) => e.ev === "start")).oauthToken, `…${TOKEN("Claude A").slice(-4)}`);
|
||
const s2 = await p2.start();
|
||
assert.equal((await p2.session(s2)).subscriptionId, b.id, "A is busy → B");
|
||
assert.equal((await core.listSubscriptions(db)).find((x) => x.id === a.id)!.activeSessions, 1);
|
||
|
||
// Provider asked explicitly: only the pool's Codex subscription, with its CODEX_HOME.
|
||
const p3 = await project({ turns: [[{ say: "ok" }]] });
|
||
await core.setProjectPool(db, (await core.getProject(db, p3.key)).id, pool.id);
|
||
const s3 = await p3.start({ provider: "codex" });
|
||
assert.equal((await p3.session(s3)).provider, "codex");
|
||
assert.equal((await p3.waitLog("started", (e) => e.ev === "start")).codexHome, runner.codexHome(c.id));
|
||
|
||
// Resume stays on the session's subscription.
|
||
await runner.stopSession(db, s1);
|
||
await runner.resumeSession(db, s1);
|
||
await waitFor("resumed run", async () => p1.log().filter((e) => e.ev === "start").length === 2);
|
||
assert.equal(p1.log().filter((e) => e.ev === "start")[1]!.oauthToken, `…${TOKEN("Claude A").slice(-4)}`);
|
||
for (const id of [s1, s2, s3]) await runner.stopSession(db, id);
|
||
});
|
||
|
||
test("выбор при запуске: раннер стартует на одной из отмеченных подписок", async () => {
|
||
const [x, y] = [await claudeSub("Pick X"), await claudeSub("Pick Y")];
|
||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||
const s = await p.start({ subscriptionIds: [y.id, x.id] });
|
||
assert.equal((await p.session(s)).subscriptionId, x.id, "first free by id among the ticked");
|
||
await runner.stopSession(db, s);
|
||
});
|
||
|
||
test("нет активных подписок → запуск отклонён; без пула — вход машины", async () => {
|
||
const bad = await claudeSub("Only bad", "bad");
|
||
await runner.checkSubscription(db, bad.id);
|
||
const pool = await core.createPool(db, { name: "Сломанный", subscriptionIds: [bad.id] });
|
||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||
await core.setProjectPool(db, (await core.getProject(db, p.key)).id, pool.id);
|
||
await assert.rejects(p.start(), /Нет активных подписок/);
|
||
await assert.rejects(p.start({ subscriptionIds: [bad.id] }), /Нет активных подписок/);
|
||
await assert.rejects(core.createPool(db, { name: "Сломанный", subscriptionIds: [] }), /уже есть/);
|
||
|
||
const free = await project({ turns: [[{ say: "ok" }]] });
|
||
const s = await free.start();
|
||
assert.equal((await free.session(s)).subscriptionId, null);
|
||
assert.equal((await free.waitLog("started", (e) => e.ev === "start")).oauthToken, null);
|
||
await runner.stopSession(db, s);
|
||
});
|
||
|
||
test("OpenCode: сессия в tmux с правилами из opencode.json и ключом подписки", async () => {
|
||
const oc = await runner.addSubscription(db, { provider: "opencode", name: "OC session", method: "api_key", secret: "mock-or-key-777", keyProvider: "openrouter", createdBy: asel.id });
|
||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||
const s = await p.start({ subscriptionIds: [oc.id] });
|
||
const start = await p.waitLog("started", (e) => e.ev === "start");
|
||
assert.equal(start.provider, "opencode");
|
||
assert.equal(start.apiKey, "…-777");
|
||
assert.ok((start.rulesChars as number) > 100, "rules from opencode.json instructions");
|
||
assert.equal((await p.session(s)).provider, "opencode");
|
||
await runner.stopSession(db, s);
|
||
});
|
||
|
||
test("удаление подписки и пула: сессии и проекты их забывают, каталог входа удалён", async () => {
|
||
const c = await runner.addSubscription(db, { provider: "codex", name: "To delete", method: "api_key", secret: "mock-openai-del", createdBy: asel.id });
|
||
const pool = await core.createPool(db, { name: "Временный", subscriptionIds: [c.id] });
|
||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||
const pid = (await core.getProject(db, p.key)).id;
|
||
await core.setProjectPool(db, pid, pool.id);
|
||
const s = await p.start();
|
||
assert.equal((await core.projectPool(db, pid))?.name, "Временный");
|
||
await runner.removeSubscription(db, c.id);
|
||
assert.equal((await p.session(s)).subscriptionId, null);
|
||
assert.ok(!existsSync(runner.subscriptionDir(c.id)));
|
||
assert.deepEqual((await core.listPools(db)).find((x) => x.id === pool.id)!.subscriptionIds, []);
|
||
await core.deletePool(db, pool.id);
|
||
assert.equal(await core.projectPool(db, pid), null);
|
||
await runner.stopSession(db, s);
|
||
});
|
||
});
|
||
|
||
describe("Перенос токена Claude из настроек", () => {
|
||
test("миграция: подписка «Claude — <login>» с тем же токеном, пул у проектов владельца", async () => {
|
||
const legacy = TOKEN("legacy");
|
||
const u = await core.upsertUserFromGitea(db, { id: 43, login: "mock-legacy" }, { access_token: "x" });
|
||
db.$client.prepare("UPDATE users SET claude_token_enc = ?, claude_token_set_at = ? WHERE id = ?").run(core.encrypt(legacy), Date.now(), u.id);
|
||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||
const pid = (await core.getProject(db, p.key)).id;
|
||
await core.setProjectOwner(db, pid, u.id);
|
||
|
||
// Re-run the data part of migration 0003 on this database.
|
||
const sql = readFileSync(join(ROOT, "packages/db/migrations/0003_subscriptions.sql"), "utf8");
|
||
const data = sql.split("--> statement-breakpoint").map((x) => x.trim()).filter((x) => /^(--.*\n)*\s*(INSERT|UPDATE)/.test(x));
|
||
assert.equal(data.length, 5);
|
||
for (const stmt of data) db.$client.exec(stmt);
|
||
|
||
const s = (await core.listSubscriptions(db)).find((x) => x.name === "Claude — mock-legacy")!;
|
||
assert.equal(s.status, "active");
|
||
assert.equal(s.provider, "claude");
|
||
assert.equal(core.subscriptionSecret(s), legacy);
|
||
assert.equal((await core.projectPool(db, pid))?.name, "Claude — mock-legacy");
|
||
assert.equal((await core.getUser(db, u.id))!.claudeTokenEnc, null);
|
||
assert.equal(await core.claudeTokenForProject(db, { id: pid }), legacy);
|
||
|
||
const sid = await p.start();
|
||
assert.equal((await p.waitLog("started", (e) => e.ev === "start")).oauthToken, `…${legacy.slice(-4)}`);
|
||
await runner.stopSession(db, sid);
|
||
});
|
||
});
|
||
|
||
describe("PEP-76: владелец выбирает подписку проекта", () => {
|
||
test("Scenario: общая подписка или своя; без выбора агенты самозарегистрированного не запускаются", async () => {
|
||
const admin = await core.upsertUserFromGitea(db, { id: 7601, login: "mock-p76-admin" }, { access_token: "x" });
|
||
const owner = await core.registerEgovUser(db, { iin: "850505400008", name: "ВЫБОРОВ ТЕСТ" });
|
||
const stranger = await core.registerEgovUser(db, { iin: "850505400018", name: "ЧУЖОЙ ТЕСТ" });
|
||
const p = await core.createProject(db, { slug: "mock-p76", key: "MPSUB", name: "P76", giteaOwner: "x", workspacePath: "/tmp/mock-p76", ownerId: owner.id });
|
||
assert.match((await core.projectAgentWarning(db, p.id))!, /подписка не подключена/);
|
||
|
||
// No shared pool yet → only the own one is possible.
|
||
await assert.rejects(runner.chooseSharedSubscription(db, owner, p), /не предлагается — подключите свою/);
|
||
const sub = await runner.addSubscription(db, { provider: "claude", name: "mock-p76 общая", method: "token", secret: "sk-ant-oat01-" + "a".repeat(40), createdBy: admin.id });
|
||
const pool = await core.createPool(db, { name: "mock-p76 общий", subscriptionIds: [sub.id], createdBy: admin.id });
|
||
await core.setSharedPool(db, pool.id);
|
||
// PEP-116: the factory's subscription is the superadmin's — an owner asks, the superadmin confirms.
|
||
const boss = await core.upsertUserFromGitea(db, { id: 7602, login: "mock-p116-boss" }, { access_token: "x" });
|
||
await core.setSetting(db, "platform.admins", ["mock-p116-boss"]);
|
||
const platform = await core.createProject(db, { slug: "mock-p116-platform", key: "MPLT", name: "Platform", giteaOwner: "x", workspacePath: "/tmp/mock-p116-platform", ownerId: boss.id });
|
||
process.env.PEPPA_PLATFORM_KEY = platform.key;
|
||
try {
|
||
await assert.rejects(runner.chooseSharedSubscription(db, stranger, p), /владелец/);
|
||
assert.equal(await runner.chooseSharedSubscription(db, owner, p), "requested");
|
||
assert.equal(await core.projectPool(db, p.id), null, "not switched before the superadmin says yes");
|
||
assert.equal(await runner.chooseSharedSubscription(db, owner, p), "requested", "asking again changes nothing");
|
||
const asks = (await core.pendingQuestions(db, platform.id)).filter((q) => q.text.includes("просит подписку Peppa FACTORY"));
|
||
assert.equal(asks.length, 1, "one request, to the superadmin (platform project → Home and Telegram)");
|
||
assert.match(stripAsIs(asks[0]!.text), new RegExp(`${owner.login} просит подписку Peppa FACTORY для проекта «P76» \\(MPSUB\\)`));
|
||
assert.deepEqual(asks[0]!.options, [runner.SHARED_APPROVE, runner.SHARED_DENY]);
|
||
assert.equal((await runner.sharedRequest(db, p.id))!.login, owner.login);
|
||
|
||
// Refused: the project stays as it was, the owner is told to connect their own.
|
||
await runner.answerAndDeliver(db, asks[0]!.id, runner.SHARED_DENY, "telegram");
|
||
assert.equal(await core.projectPool(db, p.id), null);
|
||
assert.equal(await runner.sharedRequest(db, p.id), null);
|
||
assert.ok((await core.pendingQuestions(db, p.id)).some((q) => /не разрешили\. Подключите свою подписку/.test(q.text)));
|
||
|
||
// Asked again and approved: the project runs on the factory's subscription, the owner is told.
|
||
assert.equal(await runner.chooseSharedSubscription(db, owner, p), "requested");
|
||
const [again] = (await core.pendingQuestions(db, platform.id)).filter((q) => q.text.includes("просит подписку Peppa FACTORY"));
|
||
await runner.answerAndDeliver(db, again!.id, runner.SHARED_APPROVE, "web");
|
||
assert.equal((await core.projectPool(db, p.id))!.id, pool.id);
|
||
assert.equal(await core.projectAgentWarning(db, p.id), null);
|
||
assert.ok((await core.pendingQuestions(db, p.id)).some((q) => /подписка Peppa FACTORY разрешена/.test(q.text)));
|
||
|
||
await assert.rejects(runner.connectOwnSubscription(db, owner, p, "claude", ""), /Вставьте ключ подписки/);
|
||
await assert.rejects(runner.connectOwnSubscription(db, owner, p, "claude", "не токен"), /не похоже на ключ подписки/);
|
||
assert.equal((await core.listSubscriptions(db)).filter((s) => s.createdBy === owner.id).length, 0, "a bad token leaves nothing behind");
|
||
await assert.rejects(runner.connectOwnSubscription(db, owner, p, "existing"), /ещё нет/);
|
||
await runner.connectOwnSubscription(db, owner, p, "claude", "sk-ant-oat01-" + "b".repeat(40));
|
||
const own = (await core.ownPool(db, owner.id))!;
|
||
assert.equal((await core.projectPool(db, p.id))!.id, own.id);
|
||
assert.equal(own.name, `Подписки — ${owner.login}`);
|
||
const mine = (await core.listSubscriptions(db)).filter((s) => s.createdBy === owner.id);
|
||
assert.equal(mine.length, 1);
|
||
assert.equal(core.subscriptionSecret(mine[0]!), "sk-ant-oat01-" + "b".repeat(40));
|
||
|
||
// A superadmin switches at once, without a request; back to own without a token: the existing pool is reused.
|
||
assert.equal(await runner.chooseSharedSubscription(db, boss, p), "switched");
|
||
assert.equal((await core.projectPool(db, p.id))!.id, pool.id);
|
||
await runner.connectOwnSubscription(db, owner, p, "existing");
|
||
assert.equal((await core.projectPool(db, p.id))!.id, own.id);
|
||
assert.equal((await core.listSubscriptions(db)).filter((s) => s.createdBy === owner.id).length, 1);
|
||
|
||
// PEP-80: ChatGPT by the Codex device login — the subscription waits, the page gets the link and the code.
|
||
const { subscriptionId } = await runner.connectOwnSubscription(db, owner, p, "codex_login");
|
||
const logins = await runner.ownPendingLogins(db, own.id);
|
||
assert.equal(logins.length, 1);
|
||
assert.equal(logins[0]!.subscriptionId, subscriptionId);
|
||
assert.match(logins[0]!.url, /^https:\/\//);
|
||
assert.ok(logins[0]!.code);
|
||
await runner.cancelLogin(db, subscriptionId!);
|
||
} finally {
|
||
await core.setSharedPool(db, null);
|
||
delete process.env.PEPPA_PLATFORM_KEY;
|
||
await core.deleteSetting(db, "platform.admins");
|
||
}
|
||
});
|
||
|
||
test("PEP-128: a failed sign-in is dropped by the next attempt; the project is told it has no working subscription", async () => {
|
||
const owner = await core.registerEgovUser(db, { iin: "850505400128", name: "ПОВТОРОВ ВХОД" });
|
||
const p = await core.createProject(db, { slug: "mock-p128", key: "MPRT", name: "P128", giteaOwner: "x", workspacePath: "/tmp/mock-p128", ownerId: owner.id });
|
||
const first = await runner.connectOwnSubscription(db, owner, p, "codex_login");
|
||
// The sign-in was never finished: after 15 minutes the watchdog marks it failed.
|
||
await core.updateSubscription(db, first.subscriptionId!, { status: "auth_error", lastError: "Error logging in: device auth timed out after 15 minutes" });
|
||
const pool = (await core.ownPool(db, owner.id))!;
|
||
assert.deepEqual((await core.poolSubscriptions(db, pool.id)).map((x) => x.status), ["auth_error"]);
|
||
assert.match((await core.projectAgentWarning(db, p.id))!, /нет рабочей подписки/, "the page shows the wizard again");
|
||
const second = await runner.connectOwnSubscription(db, owner, p, "codex_login");
|
||
const subs = await core.poolSubscriptions(db, pool.id);
|
||
assert.deepEqual(subs.map((x) => [x.id, x.status]), [[second.subscriptionId, "pending"]], "the dead entry is gone, the new attempt waits");
|
||
await runner.cancelLogin(db, second.subscriptionId!).catch(() => {});
|
||
});
|
||
|
||
test("PEP-82: вход в Claude по ссылке и коду на странице проекта, без терминала", async () => {
|
||
const owner = await core.registerEgovUser(db, { iin: "850505400038", name: "ССЫЛКИН ВХОД" });
|
||
const stranger = await core.registerEgovUser(db, { iin: "850505400048", name: "ПОСТОРОННИЙ ВХОД" });
|
||
const p = await core.createProject(db, { slug: "mock-p82", key: "MPLNK", name: "P82", giteaOwner: "x", workspacePath: "/tmp/mock-p82", ownerId: owner.id });
|
||
const { subscriptionId } = await runner.connectOwnSubscription(db, owner, p, "claude_login");
|
||
const pool = (await core.projectPool(db, p.id))!;
|
||
const [l] = await runner.ownPendingLogins(db, pool.id);
|
||
assert.equal(l!.subscriptionId, subscriptionId);
|
||
assert.equal(l!.provider, "claude");
|
||
assert.match(l!.url, /^https:\/\//);
|
||
assert.match((await core.projectAgentWarning(db, p.id))!, /не подключена/, "pending is not working yet");
|
||
|
||
await assert.rejects(runner.finishOwnClaudeLogin(db, stranger, p, subscriptionId!, "mock-good-1"), /владелец/);
|
||
await runner.finishOwnClaudeLogin(db, owner, p, subscriptionId!, "mock-good-1");
|
||
assert.equal((await core.getSubscription(db, subscriptionId!)).status, "active");
|
||
assert.equal(await core.projectAgentWarning(db, p.id), null);
|
||
assert.deepEqual(await runner.ownPendingLogins(db, pool.id), []);
|
||
await assert.rejects(runner.cancelOwnLogin(db, owner, p, subscriptionId!), /уже подключена/);
|
||
|
||
// «Отменить и начать заново»: a pending sign-in goes away; with nothing left the project is unassigned.
|
||
const p2 = await core.createProject(db, { slug: "mock-p82b", key: "MPLNB", name: "P82b", giteaOwner: "x", workspacePath: "/tmp/mock-p82b", ownerId: stranger.id });
|
||
const second = await runner.connectOwnSubscription(db, stranger, p2, "claude_login");
|
||
await runner.cancelOwnLogin(db, stranger, p2, second.subscriptionId!);
|
||
assert.equal(await core.projectPool(db, p2.id), null);
|
||
assert.equal((await core.listSubscriptions(db)).some((s) => s.id === second.subscriptionId), false);
|
||
});
|
||
|
||
test("PEP-79/94: новый проект — «Автомат», диспетчер молчит, пока подписка не подключена", async () => {
|
||
assert.equal(core.autonomyLevel(core.NEW_PROJECT_AUTONOMY), "auto");
|
||
assert.equal(core.NEW_PROJECT_AUTONOMY.pick, "auto");
|
||
assert.equal(core.NEW_PROJECT_AUTONOMY.merge, "auto");
|
||
const owner = await core.registerEgovUser(db, { iin: "850505400028", name: "САМОВ БЕРЁТ" });
|
||
const p = await core.createProject(db, { slug: "mock-p79", key: "MPSLF", name: "P79", giteaOwner: "x", workspacePath: "/tmp/mock-p79", ownerId: owner.id });
|
||
await core.setAutonomy(db, p.id, core.NEW_PROJECT_AUTONOMY);
|
||
const t = await core.createTask(db, { projectId: p.id, title: "первая" });
|
||
await runner.autonomyTick(db, { log: () => {} });
|
||
assert.equal((await core.resolveTask(db, t.key)).task.status, "backlog", "not started without a subscription");
|
||
assert.equal((await core.pendingQuestions(db, p.id)).length, 0, "and nobody is pinged about it");
|
||
});
|
||
});
|
||
|
||
describe("PEP-164: ещё одна подписка прямо в пул", () => {
|
||
test("суперадмин добавляет Claude в пул одной кнопкой: подписка в пуле и ждёт входа по ссылке", async () => {
|
||
const first = await claudeSub("Claude — пул ротации", "pep164a");
|
||
const pool = await core.createPool(db, { name: "Пул ротации PEP-164", subscriptionIds: [first.id] });
|
||
const added = await runner.addPoolSubscription(db, { poolId: pool.id, provider: "claude", createdBy: asel.id });
|
||
assert.equal(added.status, "pending", "waits for the sign-in");
|
||
assert.match(added.name, /^Claude 2 — Пул ротации PEP-164$/);
|
||
const members = (await core.poolSubscriptions(db, pool.id)).map((s) => s.id);
|
||
assert.deepEqual(members, [first.id, added.id], "already a member of the pool, the first one stays");
|
||
const login = await runner.pendingLogin(db, added.id);
|
||
assert.ok(login?.url, "the sign-in link is ready");
|
||
await runner.cancelLogin(db, added.id);
|
||
});
|
||
});
|