Main's new wording (PEP-123 «Продакт» words) kept and wrapped in t()/m();
wording(mode, locale) gives English words for {task}/{runner} placeholders;
glossary check (pnpm lint) passes; English for all new keys (en/merge-*.ts).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
327 lines
19 KiB
TypeScript
327 lines
19 KiB
TypeScript
import { notFound } from "next/navigation";
|
||
import { ExternalLink, KeyRound, Plus, RefreshCw, Trash2 } from "lucide-react";
|
||
import { isSuperadmin, isUsable, listPools, poolOverviews, listSubscriptions, OPENCODE_KEY_ENV, PROVIDER_NAMES, type SubscriptionView } from "@peppa/core";
|
||
import { pendingLogin, pollCodexLogin, type PendingLogin } from "@peppa/runner";
|
||
import { AutoRefresh } from "@/components/AutoRefresh";
|
||
import { PoolSubscriptions, PoolSummary } 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 { intlLocale, type Translator } from "@peppa/shared/i18n";
|
||
import {
|
||
addSubscriptionAction,
|
||
cancelLoginAction,
|
||
checkSubscriptionAction,
|
||
createPoolAction,
|
||
deletePoolAction,
|
||
deleteSubscriptionAction,
|
||
lendSubscriptionAction,
|
||
returnLoanAction,
|
||
reconnectSubscription,
|
||
submitLoginCode,
|
||
updatePoolAction,
|
||
} from "./actions";
|
||
|
||
export async function generateMetadata() {
|
||
const t = await getT();
|
||
return { title: t("Подписки — Peppa FACTORY") };
|
||
}
|
||
|
||
const hhmm = (d: Date, t: Translator) => d.toLocaleString(intlLocale(t.locale), { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" });
|
||
|
||
function StatusOf({ s, t }: { s: SubscriptionView; t: Translator }) {
|
||
if (s.status === "pending") return <Badge variant="info">{t("ожидает входа")}</Badge>;
|
||
if (s.status === "auth_error") return <Badge variant="danger">{t("ошибка входа")}</Badge>;
|
||
if (s.status === "limited" && !isUsable(s)) return <Badge variant="warn">{t("лимит до {time}", { time: s.limitedUntil ? hhmm(s.limitedUntil, t) : "?" })}</Badge>;
|
||
return <Badge variant="ok">{t("активна")}</Badge>;
|
||
}
|
||
|
||
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" />
|
||
<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 SubscriptionCard({ s, login, pools, t }: { s: SubscriptionView; login: PendingLogin | null; pools: Map<number, string>; t: Translator }) {
|
||
return (
|
||
<Card id={`s-${s.id}`} className="gap-2">
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<Badge variant="outline">{PROVIDER_NAMES[s.provider]}</Badge>
|
||
<span className="font-medium">{s.name}</span>
|
||
<StatusOf s={s} t={t} />
|
||
<span className="ml-auto text-xs text-muted-foreground">
|
||
{t("сессий сейчас:")} <span className="font-mono text-foreground tabular-nums">{s.activeSessions}</span>
|
||
{s.projectSessions.length > 0 && <> ({s.projectSessions.map((p) => `${p.key}${p.n > 1 ? ` ×${p.n}` : ""}`).join(", ")})</>}
|
||
</span>
|
||
</div>
|
||
<div className="text-xs text-muted-foreground">
|
||
{/* glossary-ignore: раздел «Подписки» видит только суперадмин */}
|
||
{s.authKind === "api_key" ? (s.keyProvider ? t("API-ключ {provider}", { provider: s.keyProvider }) : t("API-ключ")) : s.authKind === "device" ? t("вход ChatGPT") : t("токен Claude")}
|
||
{" · "}
|
||
{t("добавил {login} {ago}", { login: s.createdByLogin ?? "—", ago: ago(s.createdAt, t) })}
|
||
{s.checkedAt && <> · {t("проверена {ago}", { ago: ago(s.checkedAt, t) })}</>}
|
||
{s.poolIds.length > 0 && <> · {t("пулы: {names}", { names: s.poolIds.map((id) => pools.get(id)).filter(Boolean).join(", ") })}</>}
|
||
</div>
|
||
{s.lastError && s.status !== "active" && <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.status !== "pending" && (
|
||
<form action={checkSubscriptionAction}>
|
||
<Hidden fields={{ id: s.id }} />
|
||
<Button size="sm">
|
||
<RefreshCw />
|
||
{t("Проверить")}
|
||
</Button>
|
||
</form>
|
||
)}
|
||
{(s.provider === "claude" || (s.provider === "codex" && s.authKind === "device")) && (
|
||
<form action={reconnectSubscription}>
|
||
<Hidden fields={{ id: s.id, provider: s.provider }} />
|
||
<Button size="sm" variant="outline">{s.status === "pending" ? t("Войти") : t("Переподключить")}</Button>
|
||
</form>
|
||
)}
|
||
<form action={deleteSubscriptionAction}>
|
||
<Hidden fields={{ id: s.id }} />
|
||
<Button size="sm" variant="destructive" title={t("Удалить подписку")}>
|
||
<Trash2 />
|
||
{t("Удалить")}
|
||
</Button>
|
||
</form>
|
||
</div>
|
||
)}
|
||
</Card>
|
||
);
|
||
}
|
||
|
||
function SubscriptionChecks({ subs, checked, t }: { subs: SubscriptionView[]; checked: number[]; t: Translator }) {
|
||
return subs.length === 0 ? (
|
||
<p className="m-0 text-sm text-muted-foreground">{t("Сначала добавьте подписки.")}</p>
|
||
) : (
|
||
<div className="flex flex-col gap-1">
|
||
{subs.map((s) => (
|
||
<label key={s.id} className="flex items-center gap-2 text-sm">
|
||
<input type="checkbox" name="subscription" value={s.id} defaultChecked={checked.includes(s.id)} className="size-4 accent-primary" />
|
||
<span className="text-muted-foreground">{PROVIDER_NAMES[s.provider]}</span> {s.name}
|
||
</label>
|
||
))}
|
||
</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>
|
||
);
|
||
}
|
||
|
||
type Params = { error?: string; login?: string; added?: 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 } = 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<number, PendingLogin>();
|
||
for (const s of subs) {
|
||
const l = await pendingLogin(db, s.id);
|
||
if (l) logins.set(s.id, l);
|
||
}
|
||
const pools = await listPools(db);
|
||
const poolNames = new Map(pools.map((p) => [p.id, p.name]));
|
||
// PEP-107: every pool at a glance — busy, free, limited, spare or not, runners waiting.
|
||
const overviews = (await poolOverviews(db)).sort((a, b) => a.usableCount - b.usableCount || b.waiting - a.waiting);
|
||
const lendable = subs.filter((s) => s.status === "active" || s.status === "limited");
|
||
const addedSub = added ? subs.find((s) => s.id === Number(added)) : undefined;
|
||
|
||
return (
|
||
<Workspace>
|
||
{[...logins.values()].some((l) => l.kind === "codex") && <AutoRefresh everyMs={3000} />}
|
||
<div className="max-w-3xl">
|
||
<Flash error={error} />
|
||
<PageHeader title={<><KeyRound className="mr-1 inline size-5 text-primary" />{t("Подписки")}</>}>
|
||
{t("Аккаунты, на которых работают агенты, и пулы для ротации. Раннер берёт свободную активную подписку из пула проекта или из выбранных при запуске, а при лимите переключается на другую свободную подписку пула — того же агента, а если такой нет, другого (Claude ↔ ChatGPT). Раздел видят только суперадмины.")}
|
||
</PageHeader>
|
||
{addedSub && <Notice>{addedSub.status === "active" ? t("Подписка «{name}» добавлена и активна", { name: addedSub.name }) : t("Подписка «{name}» добавлена", { name: addedSub.name })}</Notice>}
|
||
|
||
<Section title={t("Картина по пулам")} count={overviews.length} id="overview">
|
||
{overviews.length === 0 && <Empty>{t("Пулов пока нет.")}</Empty>}
|
||
{overviews.map((o) => (
|
||
<Card key={o.pool.id} className="gap-2" 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 ? o.projects.map((x) => x.key).join(", ") : t("не назначен проектам")}</span>
|
||
</div>
|
||
<PoolSubscriptions
|
||
o={o}
|
||
action={(s) =>
|
||
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>
|
||
) : null
|
||
}
|
||
/>
|
||
<PoolSummary o={o} />
|
||
</Card>
|
||
))}
|
||
{overviews.length > 0 && lendable.length > 0 && (
|
||
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />{t("Одолжить подписку")}</span>}>
|
||
<form action={lendSubscriptionAction} className="flex flex-col gap-3">
|
||
<Label>
|
||
{t("Подписка")}
|
||
<NativeSelect name="subscriptionId" required>
|
||
{lendable.map((s) => (
|
||
<option key={s.id} value={s.id}>{s.name} ({PROVIDER_NAMES[s.provider]})</option>
|
||
))}
|
||
</NativeSelect>
|
||
</Label>
|
||
<Label>
|
||
{t("В пул")}
|
||
<NativeSelect name="poolId" required>
|
||
{overviews.map((o) => (
|
||
<option key={o.pool.id} value={o.pool.id}>{o.pool.name}{o.usableCount <= 1 ? t(" — запасной нет") : ""}</option>
|
||
))}
|
||
</NativeSelect>
|
||
</Label>
|
||
<Label>
|
||
{t("На сколько часов (1–168)")}
|
||
<Input name="hours" type="number" min={1} max={168} defaultValue={4} required className="max-w-32" />
|
||
</Label>
|
||
<Button variant="default" className="self-start">{t("Одолжить")}</Button>
|
||
<span className="text-xs text-muted-foreground">{t("Подписка сразу попадает в пул, по сроку возвращается сама; агенты, которые уже на ней, доработают текущий запуск. Участники проектов пула получают сообщение.")}</span>
|
||
</form>
|
||
</Disclosure>
|
||
)}
|
||
</Section>
|
||
|
||
<Section title={t("Подписки")} count={subs.length}>
|
||
{subs.length === 0 ? <Empty>{t("Подписок пока нет — добавьте первую ниже.")}</Empty> : subs.map((s) => <SubscriptionCard key={s.id} s={s} login={logins.get(s.id) ?? null} pools={poolNames} t={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 Code</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" />Codex</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>
|
||
</Section>
|
||
|
||
<Section title={t("Пулы")} count={pools.length} id="pools">
|
||
{pools.length === 0 && <Empty>{t("Пулов нет. Пул — набор подписок, который назначается проекту по умолчанию.")}</Empty>}
|
||
{pools.map((p) => (
|
||
<Card key={p.id} className="gap-3">
|
||
<form action={updatePoolAction} className="flex flex-col gap-3">
|
||
<Hidden fields={{ id: p.id }} />
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<Input name="name" defaultValue={p.name} aria-label={t("Название пула")} className="max-w-xs font-medium" />
|
||
<span className="text-xs text-muted-foreground">
|
||
{p.projectKeys.length ? t("по умолчанию у {keys}", { keys: p.projectKeys.join(", ") }) : t("не назначен проектам")}
|
||
</span>
|
||
</div>
|
||
<SubscriptionChecks subs={subs} checked={p.subscriptionIds} t={t} />
|
||
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
|
||
</form>
|
||
<form action={deletePoolAction}>
|
||
<Hidden fields={{ id: p.id }} />
|
||
<Button size="sm" variant="link" className="px-0 text-destructive">{t("Удалить пул")}</Button>
|
||
</form>
|
||
</Card>
|
||
))}
|
||
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />{t("Новый пул")}</span>}>
|
||
<form action={createPoolAction} className="flex flex-col gap-3">
|
||
<Label>
|
||
{t("Название")}
|
||
<Input name="name" required placeholder={t("Основной")} />
|
||
</Label>
|
||
<SubscriptionChecks subs={subs} checked={[]} t={t} />
|
||
<Button variant="default" className="self-start">{t("Создать пул")}</Button>
|
||
</form>
|
||
</Disclosure>
|
||
<p className="m-0 text-xs text-muted-foreground">{t("Пул проекта по умолчанию выбирается в «⋯ Настройки проекта».")}</p>
|
||
</Section>
|
||
</div>
|
||
</Workspace>
|
||
);
|
||
}
|