peppa/apps/web/app/(app)/subscriptions/page.tsx
peppa-bot f3d10a4c25 PEP-243: платформа называется FORGE — название во всех текстах для людей и подсказках агентам, адрес forge.telecom.quest
«Peppa FACTORY» → «FORGE» в экранах, сообщениях, словарях en/kk, шаблоне и тестах; «Пеппа» → «FORGE» в подсказках
агентам и правилах; логотип, значок, версия кэша service worker; в словаре старые названия — в «Нельзя».
Внутренние имена (CLI peppa, PEPPA_*, MCP-сервер peppa, ключи PEP-N) не меняются. Второй адрес — в mac-route.sh.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 11:18:49 +05:00

424 lines
24 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 (
<div className="flex flex-col gap-2 rounded-md border bg-background/40 p-3">
{login.kind === "claude" ? (
<>
<p className="m-0 text-sm">{t("1. Откройте ссылку на любом устройстве и войдите в аккаунт Claude с подпиской:")}</p>
<Button asChild variant="default" size="sm" className="self-start">
<a href={login.url} target="_blank" rel="noreferrer">
{t("Войти в Claude")} <ExternalLink />
</a>
</Button>
<p className="m-0 text-sm">{t("2. Claude покажет код — вставьте его сюда:")}</p>
<form action={submitLoginCode} className="flex gap-2">
<Hidden fields={{ id: s.id }} />
<Input name="code" placeholder={t("Код из Claude")} aria-label={t("Код из Claude")} autoComplete="off" required className="font-mono" />
<Input name="account" type="email" autoComplete="email" placeholder={t("Почта аккаунта Claude — по желанию")} aria-label={t("Почта аккаунта Claude")} />
<Button variant="default">{t("Подключить")}</Button>
</form>
</>
) : (
<>
<p className="m-0 text-sm">{t("1. Откройте ссылку на любом устройстве и войдите в ChatGPT:")}</p>
<Button asChild variant="default" size="sm" className="self-start">
<a href={login.url} target="_blank" rel="noreferrer">
{login.url} <ExternalLink />
</a>
</Button>
<p className="m-0 text-sm">
{t("2. Введите одноразовый код:")} <span className="rounded bg-muted px-2 py-0.5 font-mono text-base font-semibold tracking-wider">{login.code}</span>
</p>
<p className="m-0 text-xs text-muted-foreground">{t("Страница обновится сама, когда Codex подтвердит вход.")}</p>
</>
)}
<form action={cancelLoginAction}>
<Hidden fields={{ id: s.id }} />
<Button variant="link" size="sm" className="px-0 text-muted-foreground">{t("Отменить вход")}</Button>
</form>
</div>
);
}
function AddForm({ provider, children, t }: { provider: string; children: React.ReactNode; t: Translator }) {
return (
<form action={addSubscriptionAction} className="flex flex-col gap-3">
<Hidden fields={{ provider }} />
<Label>
{t("Название")}
<Input name="name" required placeholder={provider === "claude" ? "Claude Max — asel" : provider === "codex" ? "ChatGPT Pro — asel" : "OpenCode — Anthropic"} />
</Label>
{children}
</form>
);
}
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 (
<Card id={`s-${s.id}`} className="gap-2">
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-medium">{s.name}</span>
{s.ownerName && !s.name.includes(s.ownerName) && <span className="text-xs text-muted-foreground">· {s.ownerName}</span>}
<span className="text-xs text-muted-foreground">{PROVIDER_NAMES[s.provider]}</span>
{s.status === "auth_error" ? <Badge variant="danger">{t("ошибка входа")}</Badge> : <Badge variant="muted">{t("вход не закончен · {ago}", { ago: ago(s.createdAt, t) })}</Badge>}
</div>
{s.lastError && s.status === "auth_error" && <p className="m-0 font-mono text-xs [overflow-wrap:anywhere] text-destructive">{s.lastError}</p>}
{login && <LoginSteps s={s} login={login} t={t} />}
{!login && (
<div className="flex flex-wrap gap-2">
{(s.provider === "claude" || (s.provider === "codex" && s.authKind === "device")) && (
<form action={reconnectSubscription}>
<Hidden fields={{ id: s.id, provider: s.provider }} />
<Button size="sm" variant="default">{t("Подключить заново")}</Button>
</form>
)}
<form action={deleteSubscriptionAction}>
<Hidden fields={{ id: s.id }} />
<Button size="sm" variant="ghost" className="text-muted-foreground">{t("Удалить")}</Button>
</form>
</div>
)}
</Card>
);
}
/** 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 (
<Card className="gap-3" id={`pool-${o.pool.id}`} data-pool-overview={o.pool.id}>
<div className="flex flex-wrap items-baseline gap-2">
<span className="font-medium">{o.pool.name}</span>
<span className="text-xs text-muted-foreground">{o.projects.length ? t("работают: {keys}", { keys: o.projects.map((x) => x.key).join(", ") }) : t("ни один проект не работает на них")}</span>
</div>
<PoolSubscriptions
o={o}
capacity
action={(s) => (
<>
{/* 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 && (
<form action={switchAgentsAction} className="flex items-center gap-1" data-switch-agents={s.id}>
<Hidden fields={{ fromId: s.id }} />
<NativeSelect name="toId" aria-label={t("Куда перевести агентов")} className="h-7 text-xs">
<option value="">{t("на любую свободную")}</option>
{o.subscriptions
.filter((x) => x.id !== s.id && x.usable)
.map((x) => (
<option key={x.id} value={x.id}>
{x.name}
{x.accountEmail ? ` · ${x.accountEmail}` : x.ownerName && !x.name.includes(x.ownerName) ? ` · ${x.ownerName}` : ""}
</option>
))}
</NativeSelect>
<Button size="xs" variant="outline" title={t("Агенты сразу продолжат на выбранной подписке")}>
{t("Перевести агентов")}
</Button>
</form>
)}
{/* PEP-178: name and account of the subscription — which login it is. */}
<details className="relative" data-edit-subscription={s.id}>
<summary className="cursor-pointer list-none rounded px-2 py-1 text-xs text-muted-foreground hover:text-foreground">{t("Изменить")}</summary>
<form action={renameSubscription} className="absolute right-0 z-20 mt-1 flex w-72 flex-col gap-2 rounded-lg border bg-card p-3 shadow-lg">
<Hidden fields={{ id: s.id, back: `/subscriptions#pool-${o.pool.id}` }} />
<Label>
{t("Название")}
<Input name="name" required defaultValue={s.name} className="h-8" />
</Label>
<Label>
{t("Почта аккаунта")}
<Input name="account" type="email" defaultValue={s.accountEmail ?? ""} placeholder="name@example.com" className="h-8" />
</Label>
<Button size="sm" variant="default" className="self-start">{t("Сохранить")}</Button>
</form>
</details>
<form action={checkSubscriptionAction}>
<Hidden fields={{ id: s.id }} />
<Button size="xs" variant="ghost" title={t("Проверить")} aria-label={t("Проверить")} className="text-muted-foreground">
<RefreshCw />
</Button>
</form>
{s.loan ? (
<form action={returnLoanAction}>
<Hidden fields={{ poolId: o.pool.id, subscriptionId: s.id }} />
<Button size="xs" variant="ghost" className="text-muted-foreground">{t("Вернуть")}</Button>
</form>
) : (
<form action={updatePoolAction}>
<Hidden fields={{ id: o.pool.id }} />
{ids.filter((x) => x !== s.id).map((x) => <input key={x} type="hidden" name="subscription" value={x} />)}
<Button size="xs" variant="ghost" className="text-muted-foreground">{t("Убрать")}</Button>
</form>
)}
</>
)}
/>
<PoolSummary o={o} />
<PoolCapacity
o={o}
form={
<form action={setPoolCapacityAction} className="ml-auto flex items-center gap-1.5">
<Hidden fields={{ poolId: o.pool.id }} />
<Label className="flex-row items-center gap-1.5 text-xs font-normal">
{t("Агентов на подписку")}
<Input name="capacity" type="number" min={1} max={20} required defaultValue={o.capacity} className="h-7 w-16 text-sm" />
</Label>
<Button size="xs" variant="outline">{t("Сохранить")}</Button>
</form>
}
/>
{addable.length > 0 && (
<form action={updatePoolAction} className="flex flex-wrap items-center gap-2">
<Hidden fields={{ id: o.pool.id }} />
{ids.map((x) => <input key={x} type="hidden" name="subscription" value={x} />)}
<NativeSelect name="subscription" aria-label={t("Добавить подписку")} className="h-8 max-w-xs text-sm" required defaultValue="">
<option value="" disabled>{t("Добавить подписку…")}</option>
{addable.map((s) => (
<option key={s.id} value={s.id}>{s.name}{s.ownerName && !s.name.includes(s.ownerName) ? ` · ${s.ownerName}` : ""} ({PROVIDER_NAMES[s.provider]})</option>
))}
</NativeSelect>
<Button size="sm">{t("Добавить")}</Button>
</form>
)}
{/* PEP-164: one more subscription straight into this set — the sign-in starts right away. */}
<div className="flex flex-wrap gap-2" data-add-to-pool={o.pool.id}>
<form action={addPoolSubscriptionAction}>
<Hidden fields={{ poolId: o.pool.id, provider: "claude" }} />
<Button size="sm" variant={o.usableCount <= 1 ? "default" : "outline"}>
<Plus /> {t("Добавить ещё Claude")}
</Button>
</form>
<form action={addPoolSubscriptionAction}>
<Hidden fields={{ poolId: o.pool.id, provider: "codex" }} />
<Button size="sm" variant="outline">
<Plus /> {t("Добавить ещё ChatGPT")}
</Button>
</form>
</div>
{!o.projects.length && !ids.length && (
<form action={deletePoolAction}>
<Hidden fields={{ id: o.pool.id }} />
<Button size="xs" variant="ghost" className="px-0 text-muted-foreground">{t("Удалить пустой набор")}</Button>
</form>
)}
<PoolSwitches o={o} />
</Card>
);
}
type Params = { error?: string; login?: string; added?: string; switched?: string; left?: string };
export default async function Subscriptions({ searchParams }: { searchParams: Promise<Params> }) {
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<number, PendingLogin>();
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 (
<Workspace>
<LiveRefresh scope="subs" />
{[...logins.entries()].filter(([, l]) => l.kind === "codex").map(([id]) => <LiveRefresh key={id} scope={`login:${id}`} indicator={false} />)}
<div className="max-w-3xl">
<Flash error={error} />
<PageHeader title={<><KeyRound className="mr-1 inline size-5 text-primary" />{t("Подписки")}</>}>
{t("Аккаунты Claude и ChatGPT, на которых работают агенты. Кончилась одна — агенты переходят на следующую свободную, а когда лимит сбросится, она снова в строю. Раздел видят только суперадмины.")}
</PageHeader>
{switched !== undefined && (
<Notice>
{Number(left) > 0
? t("Переведено агентов: {n}. Ещё {m} — некуда: свободной рабочей подписки нет.", { n: Number(switched), m: Number(left) })
: t("Переведено агентов: {n}. Они продолжают на новой подписке.", { n: Number(switched) })}
</Notice>
)}
{addedSub && <Notice>{addedSub.status === "active" ? t("Подписка «{name}» добавлена и активна", { name: addedSub.name }) : t("Подписка «{name}» добавлена", { name: addedSub.name })}</Notice>}
{(problems.length > 0 || thin.length > 0 || requests.length > 0) && (
<Section title={t("Нужно ваше внимание")} count={problems.length + thin.length + requests.length}>
{requests.map((r) => (
<div key={r.projectId} data-subscription-request={r.key} className="flex flex-col gap-2 rounded-md border border-warn/40 px-3 py-2 text-sm">
<span>{r.question && !r.question.answeredAt ? t.text(r.question.text) : t("{login} просит подписку для проекта «{project}»", { login: r.login, project: r.name })}</span>
{r.question && !r.question.answeredAt ? (
<div className="flex flex-wrap gap-2">
{(r.question.options ?? []).map((o, i) => (
<form key={o} action={answerQuestion}>
<Hidden fields={{ questionId: r.question!.id, choice: o, back: "/subscriptions" }} />
<Button size="xs" variant={i === 0 ? "default" : "outline"}>{t.text(o)}</Button>
</form>
))}
</div>
) : r.remindAt ? (
<span className="text-xs text-muted-foreground">
{t("Напомню в")} <LocalTime iso={r.remindAt.toISOString()} />
</span>
) : null}
</div>
))}
{problems.map((s) => (
<Problem key={s.id} s={s} login={logins.get(s.id) ?? null} t={t} />
))}
{thin.map((o) => (
<a key={o.pool.id} href={`#pool-${o.pool.id}`} className="block rounded-md border border-warn/40 px-3 py-2 text-sm text-warn hover:no-underline">
{o.usableCount === 0
? t("{keys}: все подписки кончились — агенты ждут сброса лимита", { keys: o.projects.map((x) => x.key).join(", ") })
: t("{keys}: запасной подписки нет", { keys: o.projects.map((x) => x.key).join(", ") })}
</a>
))}
</Section>
)}
<Section title={t("Кто на чём работает")} count={sets.length} id="pools">
{sets.length === 0 && <Empty>{t("Подписок пока нет — подключите первую ниже.")}</Empty>}
{sets.map((o) => (
<SetCard key={o.pool.id} o={o} subs={subs} t={t} />
))}
{loose.length > 0 && (
<Card className="gap-2">
<span className="font-medium">{t("Ни к чему не подключены")}</span>
<ul className="m-0 flex list-none flex-col divide-y divide-border p-0">
{loose.map((s) => (
<li key={s.id} className="flex flex-wrap items-center gap-2 py-2 text-sm first:pt-0 last:pb-0">
<span className="font-medium">{s.name}</span>
{s.ownerName && !s.name.includes(s.ownerName) && <span className="text-xs text-muted-foreground">· {s.ownerName}</span>}
<span className="text-xs text-muted-foreground">{PROVIDER_NAMES[s.provider]}</span>
<form action={deleteSubscriptionAction} className="ml-auto">
<Hidden fields={{ id: s.id }} />
<Button size="xs" variant="ghost" className="text-muted-foreground">{t("Удалить")}</Button>
</form>
</li>
))}
</ul>
</Card>
)}
</Section>
<Section title={t("Подключить подписку")}>
<div className="grid gap-2 md:grid-cols-3">
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />Claude</span>}>
<AddForm provider="claude" t={t}>
<NativeSelect name="method" defaultValue="login" aria-label={t("Способ входа")}>
<option value="login">{t("Войти по ссылке (claude setup-token)")}</option>
<option value="token">{t("Вставить готовый токен")}</option>
</NativeSelect>
<Input name="secret" type="password" placeholder={t("sk-ant-oat… (только для готового токена)")} autoComplete="off" aria-label={t("Токен")} />
<Button variant="default" className="self-start">{t("Добавить")}</Button>
</AddForm>
</Disclosure>
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />ChatGPT</span>}>
<AddForm provider="codex" t={t}>
<NativeSelect name="method" defaultValue="device" aria-label={t("Способ входа")}>
<option value="device">{t("Подписка ChatGPT (ссылка + код)")}</option>
<option value="api_key">{t("API-ключ OpenAI")}</option>
</NativeSelect>
<Input name="secret" type="password" placeholder={t("sk-… (только для API-ключа)")} autoComplete="off" aria-label={t("API-ключ")} />
<Button variant="default" className="self-start">{t("Добавить")}</Button>
</AddForm>
</Disclosure>
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />OpenCode</span>}>
<AddForm provider="opencode" t={t}>
<input type="hidden" name="method" value="api_key" />
<NativeSelect name="keyProvider" defaultValue="anthropic" aria-label={t("Провайдер ключа")}>
{Object.keys(OPENCODE_KEY_ENV).map((k) => (
<option key={k} value={k}>{k}</option>
))}
</NativeSelect>
<Input name="secret" type="password" required placeholder={t("Ключ провайдера")} autoComplete="off" aria-label={t("Ключ")} />
<Button variant="default" className="self-start">{t("Добавить")}</Button>
</AddForm>
</Disclosure>
</div>
<Disclosure summary={<span className="flex items-center gap-1.5 text-sm text-muted-foreground"><Plus className="size-4" />{t("Новый набор подписок")}</span>}>
<form action={createPoolAction} className="flex flex-col gap-3">
<Label>
{t("Название")}
<Input name="name" required placeholder={t("Основной")} />
</Label>
<Button variant="default" className="self-start">{t("Создать")}</Button>
<span className="text-xs text-muted-foreground">{t("Проекту набор выбирается в «⋯ Настройки проекта → Подписки».")}</span>
</form>
</Disclosure>
</Section>
</div>
</Workspace>
);
}