import { notFound } from "next/navigation"; import { ExternalLink, KeyRound, Plus, RefreshCw } from "lucide-react"; import { getQuestion, isSuperadmin, listSubscriptions, OPENCODE_KEY_ENV, PROVIDER_NAMES, poolOverviews, type PoolOverview, type SubscriptionView } from "@peppa/core"; import { pendingLogin, pollCodexLogin, type PendingLogin, backfillCodexAccounts, openSubscriptionRequests } from "@peppa/runner"; import { answerQuestion } from "@/app/(app)/actions"; import { LocalTime } from "@/components/LocalTime"; import { LiveRefresh } from "@/components/LiveRefresh"; import { PoolCapacity, PoolSubscriptions, PoolSummary, PoolSwitches } from "@/components/PoolSubscriptions"; import { Hidden } from "@/components/cards"; import { ago, Disclosure, Empty, Flash, Notice, PageHeader, Section } from "@/components/common"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { Input, Label, NativeSelect } from "@/components/ui/input"; import { Workspace } from "@/components/Workspace"; import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; import { getT } from "@/lib/i18n"; import type { Translator } from "@peppa/shared/i18n"; import { addSubscriptionAction, cancelLoginAction, checkSubscriptionAction, createPoolAction, deletePoolAction, deleteSubscriptionAction, addPoolSubscriptionAction, switchAgentsAction, returnLoanAction, setPoolCapacityAction, reconnectSubscription, submitLoginCode, renameSubscription, updatePoolAction, } from "./actions"; // PEP-216: the backfill reads auth files — once per process is enough, not on every visit. let backfilled = false; async function backfillOnce(d: typeof db) { if (backfilled) return; backfilled = true; await backfillCodexAccounts(d).catch(() => {}); } export async function generateMetadata() { const t = await getT(); return { title: t("Подписки — FORGE") }; } // PEP-170: one simple picture — a subscription runs out, agents move to the next free one. // Problems first, then one card per set of subscriptions (whose they are, which projects run on // them), rows with one status each, the latest switches. No pool editor, no lending form. function LoginSteps({ s, login, t }: { s: SubscriptionView; login: PendingLogin; t: Translator }) { return (
{login.kind === "claude" ? ( <>

{t("1. Откройте ссылку на любом устройстве и войдите в аккаунт Claude с подпиской:")}

{t("2. Claude покажет код — вставьте его сюда:")}

) : ( <>

{t("1. Откройте ссылку на любом устройстве и войдите в ChatGPT:")}

{t("2. Введите одноразовый код:")} {login.code}

{t("Страница обновится сама, когда Codex подтвердит вход.")}

)}
); } function AddForm({ provider, children, t }: { provider: string; children: React.ReactNode; t: Translator }) { return (
{children} ); } const PENDING_STALE_MS = 3_600_000; /** Rows that need a person: a broken sign-in, a sign-in started and left. */ function Problem({ s, login, t }: { s: SubscriptionView; login: PendingLogin | null; t: Translator }) { return (
{s.name} {s.ownerName && !s.name.includes(s.ownerName) && · {s.ownerName}} {PROVIDER_NAMES[s.provider]} {s.status === "auth_error" ? {t("ошибка входа")} : {t("вход не закончен · {ago}", { ago: ago(s.createdAt, t) })}}
{s.lastError && s.status === "auth_error" &&

{s.lastError}

} {login && } {!login && (
{(s.provider === "claude" || (s.provider === "codex" && s.authKind === "device")) && (
)}
)}
); } /** A set of subscriptions: its projects, the rows, what happens on a limit, the latest switches. */ function SetCard({ o, subs, t }: { o: PoolOverview; subs: SubscriptionView[]; t: Translator }) { const ids = o.subscriptions.map((s) => s.id); const addable = subs.filter((s) => !ids.includes(s.id) && s.status !== "auth_error"); return (
{o.pool.name} {o.projects.length ? t("работают: {keys}", { keys: o.projects.map((x) => x.key).join(", ") }) : t("ни один проект не работает на них")}
( <> {/* PEP-176: move this subscription's agents by hand — to one of the pool's working subscriptions or to any free one. */} {s.activeSessions > 0 && (
{o.subscriptions .filter((x) => x.id !== s.id && x.usable) .map((x) => ( ))} )} {/* PEP-178: name and account of the subscription — which login it is. */}
{t("Изменить")}
{s.loan ? (
) : (
{ids.filter((x) => x !== s.id).map((x) => )} )} )} /> } /> {addable.length > 0 && (
{ids.map((x) => )} {addable.map((s) => ( ))} )} {/* PEP-164: one more subscription straight into this set — the sign-in starts right away. */}
{!o.projects.length && !ids.length && (
)}
); } type Params = { error?: string; login?: string; added?: string; switched?: string; left?: string }; export default async function Subscriptions({ searchParams }: { searchParams: Promise }) { const user = await requireUser(); const t = await getT(); if (!(await isSuperadmin(db, user))) notFound(); const { error, added, switched, left } = await searchParams; // PEP-178: ChatGPT logins carry their account — fill in the ones signed in before it was kept. await backfillOnce(db); let subs = await listSubscriptions(db); // Codex device sign-ins finish on the user's device: look whether they are done. let polled = false; for (const s of subs) if (s.provider === "codex" && s.status === "pending") polled = (await pollCodexLogin(db, s.id)) !== "pending" || polled; if (polled) subs = await listSubscriptions(db); const logins = new Map(); for (const s of subs) { const l = await pendingLogin(db, s.id); if (l) logins.set(s.id, l); } const now = Date.now(); const problems = subs.filter((s) => s.status === "auth_error" || (s.status === "pending" && (logins.has(s.id) || now - s.createdAt.getTime() > PENDING_STALE_MS))); // Sets: the ones projects run on and the troubled first. const sets = (await poolOverviews(db)).sort((a, b) => Number(!a.projects.length) - Number(!b.projects.length) || a.usableCount - b.usableCount || b.waiting - a.waiting); const thin = sets.filter((o) => o.projects.length && o.usableCount <= 1); const inSet = new Set(sets.flatMap((o) => o.subscriptions.map((s) => s.id))); const loose = subs.filter((s) => !inSet.has(s.id) && s.status !== "auth_error" && s.status !== "pending"); const addedSub = added ? subs.find((s) => s.id === Number(added)) : undefined; // PEP-186: owners asking for a subscription — answered right here, same buttons as on Home. const requests = await Promise.all( (await openSubscriptionRequests(db)).map(async (r) => ({ ...r, question: r.questionId ? await getQuestion(db, r.questionId).catch(() => null) : null })), ); return ( {[...logins.entries()].filter(([, l]) => l.kind === "codex").map(([id]) => )}
{t("Подписки")}}> {t("Аккаунты Claude и ChatGPT, на которых работают агенты. Кончилась одна — агенты переходят на следующую свободную, а когда лимит сбросится, она снова в строю. Раздел видят только суперадмины.")} {switched !== undefined && ( {Number(left) > 0 ? t("Переведено агентов: {n}. Ещё {m} — некуда: свободной рабочей подписки нет.", { n: Number(switched), m: Number(left) }) : t("Переведено агентов: {n}. Они продолжают на новой подписке.", { n: Number(switched) })} )} {addedSub && {addedSub.status === "active" ? t("Подписка «{name}» добавлена и активна", { name: addedSub.name }) : t("Подписка «{name}» добавлена", { name: addedSub.name })}} {(problems.length > 0 || thin.length > 0 || requests.length > 0) && (
{requests.map((r) => (
{r.question && !r.question.answeredAt ? t.text(r.question.text) : t("{login} просит подписку для проекта «{project}»", { login: r.login, project: r.name })} {r.question && !r.question.answeredAt ? (
{(r.question.options ?? []).map((o, i) => (
))}
) : r.remindAt ? ( {t("Напомню в")} ) : null}
))} {problems.map((s) => ( ))} {thin.map((o) => ( {o.usableCount === 0 ? t("{keys}: все подписки кончились — агенты ждут сброса лимита", { keys: o.projects.map((x) => x.key).join(", ") }) : t("{keys}: запасной подписки нет", { keys: o.projects.map((x) => x.key).join(", ") })} ))}
)}
{sets.length === 0 && {t("Подписок пока нет — подключите первую ниже.")}} {sets.map((o) => ( ))} {loose.length > 0 && ( {t("Ни к чему не подключены")}
    {loose.map((s) => (
  • {s.name} {s.ownerName && !s.name.includes(s.ownerName) && · {s.ownerName}} {PROVIDER_NAMES[s.provider]}
  • ))}
)}
Claude}> ChatGPT}> OpenCode}> {Object.keys(OPENCODE_KEY_ENV).map((k) => ( ))}
{t("Новый набор подписок")}}>
{t("Проекту набор выбирается в «⋯ Настройки проекта → Подписки».")}
); }