import { notFound } from "next/navigation";
import { ExternalLink, KeyRound, Plus, RefreshCw } from "lucide-react";
import { isSuperadmin, listSubscriptions, OPENCODE_KEY_ENV, PROVIDER_NAMES, poolOverviews, type PoolOverview, type SubscriptionView } from "@peppa/core";
import { pendingLogin, pollCodexLogin, type PendingLogin } from "@peppa/runner";
import { AutoRefresh } from "@/components/AutoRefresh";
import { 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,
returnLoanAction,
reconnectSubscription,
submitLoginCode,
updatePoolAction,
} from "./actions";
export async function generateMetadata() {
const t = await getT();
return { title: t("Подписки — Peppa FACTORY") };
}
// 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 (
);
}
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 (
)}
);
}
/** 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("ни один проект не работает на них")}
(
<>
{s.loan ? (
) : (
)}
>
)}
/>
{addable.length > 0 && (
)}
{/* 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 };
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 } = await searchParams;
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;
return (
{[...logins.values()].some((l) => l.kind === "codex") && }