319 lines
18 KiB
TypeScript
319 lines
18 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 {
|
||
addSubscriptionAction,
|
||
cancelLoginAction,
|
||
checkSubscriptionAction,
|
||
createPoolAction,
|
||
deletePoolAction,
|
||
deleteSubscriptionAction,
|
||
lendSubscriptionAction,
|
||
returnLoanAction,
|
||
reconnectSubscription,
|
||
submitLoginCode,
|
||
updatePoolAction,
|
||
} from "./actions";
|
||
|
||
export const metadata = { title: "Подписки — Peppa FACTORY" };
|
||
|
||
const hhmm = (d: Date) => d.toLocaleString("ru-RU", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" });
|
||
|
||
function StatusOf({ s }: { s: SubscriptionView }) {
|
||
if (s.status === "pending") return <Badge variant="info">ожидает входа</Badge>;
|
||
if (s.status === "auth_error") return <Badge variant="danger">ошибка входа</Badge>;
|
||
if (s.status === "limited" && !isUsable(s)) return <Badge variant="warn">лимит до {s.limitedUntil ? hhmm(s.limitedUntil) : "?"}</Badge>;
|
||
return <Badge variant="ok">активна</Badge>;
|
||
}
|
||
|
||
function LoginSteps({ s, login }: { s: SubscriptionView; login: PendingLogin }) {
|
||
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">1. Откройте ссылку на любом устройстве и войдите в аккаунт Claude с подпиской:</p>
|
||
<Button asChild variant="default" size="sm" className="self-start">
|
||
<a href={login.url} target="_blank" rel="noreferrer">
|
||
Войти в Claude <ExternalLink />
|
||
</a>
|
||
</Button>
|
||
<p className="m-0 text-sm">2. Claude покажет код — вставьте его сюда:</p>
|
||
<form action={submitLoginCode} className="flex gap-2">
|
||
<Hidden fields={{ id: s.id }} />
|
||
<Input name="code" placeholder="Код из Claude" aria-label="Код из Claude" autoComplete="off" required className="font-mono" />
|
||
<Button variant="default">Подключить</Button>
|
||
</form>
|
||
</>
|
||
) : (
|
||
<>
|
||
<p className="m-0 text-sm">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">
|
||
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">Страница обновится сама, когда Codex подтвердит вход.</p>
|
||
</>
|
||
)}
|
||
<form action={cancelLoginAction}>
|
||
<Hidden fields={{ id: s.id }} />
|
||
<Button variant="link" size="sm" className="px-0 text-muted-foreground">Отменить вход</Button>
|
||
</form>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function SubscriptionCard({ s, login, pools }: { s: SubscriptionView; login: PendingLogin | null; pools: Map<number, string> }) {
|
||
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} />
|
||
<span className="ml-auto text-xs text-muted-foreground">
|
||
сессий сейчас: <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">
|
||
{s.authKind === "api_key" ? `API-ключ${s.keyProvider ? ` ${s.keyProvider}` : ""}` : s.authKind === "device" ? "вход ChatGPT" : "токен Claude"}
|
||
{" · "}добавил {s.createdByLogin ?? "—"} {ago(s.createdAt)}
|
||
{s.checkedAt && <> · проверена {ago(s.checkedAt)}</>}
|
||
{s.poolIds.length > 0 && <> · пулы: {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} />}
|
||
{!login && (
|
||
<div className="flex flex-wrap gap-2">
|
||
{s.status !== "pending" && (
|
||
<form action={checkSubscriptionAction}>
|
||
<Hidden fields={{ id: s.id }} />
|
||
<Button size="sm">
|
||
<RefreshCw />
|
||
Проверить
|
||
</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" ? "Войти" : "Переподключить"}</Button>
|
||
</form>
|
||
)}
|
||
<form action={deleteSubscriptionAction}>
|
||
<Hidden fields={{ id: s.id }} />
|
||
<Button size="sm" variant="destructive" title="Удалить подписку">
|
||
<Trash2 />
|
||
Удалить
|
||
</Button>
|
||
</form>
|
||
</div>
|
||
)}
|
||
</Card>
|
||
);
|
||
}
|
||
|
||
function SubscriptionChecks({ subs, checked }: { subs: SubscriptionView[]; checked: number[] }) {
|
||
return subs.length === 0 ? (
|
||
<p className="m-0 text-sm text-muted-foreground">Сначала добавьте подписки.</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 }: { provider: string; children: React.ReactNode }) {
|
||
return (
|
||
<form action={addSubscriptionAction} className="flex flex-col gap-3">
|
||
<Hidden fields={{ provider }} />
|
||
<Label>
|
||
Название
|
||
<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();
|
||
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" />Подписки</>}>
|
||
Аккаунты, на которых работают агенты, и пулы для ротации. Раннер берёт свободную активную подписку из пула проекта или из выбранных при запуске, а при лимите переключается на другую свободную подписку пула — того же агента, а если такой нет, другого (Claude ↔ ChatGPT). Раздел видят только суперадмины.
|
||
</PageHeader>
|
||
{addedSub && <Notice>Подписка «{addedSub.name}» добавлена{addedSub.status === "active" ? " и активна" : ""}</Notice>}
|
||
|
||
<Section title="Картина по пулам" count={overviews.length} id="overview">
|
||
{overviews.length === 0 && <Empty>Пулов пока нет.</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(", ") : "не назначен проектам"}</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">Вернуть сейчас</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" />Одолжить подписку</span>}>
|
||
<form action={lendSubscriptionAction} className="flex flex-col gap-3">
|
||
<Label>
|
||
Подписка
|
||
<NativeSelect name="subscriptionId" required>
|
||
{lendable.map((s) => (
|
||
<option key={s.id} value={s.id}>{s.name} ({PROVIDER_NAMES[s.provider]})</option>
|
||
))}
|
||
</NativeSelect>
|
||
</Label>
|
||
<Label>
|
||
В пул
|
||
<NativeSelect name="poolId" required>
|
||
{overviews.map((o) => (
|
||
<option key={o.pool.id} value={o.pool.id}>{o.pool.name}{o.usableCount <= 1 ? " — запасной нет" : ""}</option>
|
||
))}
|
||
</NativeSelect>
|
||
</Label>
|
||
<Label>
|
||
На сколько часов (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">Одолжить</Button>
|
||
<span className="text-xs text-muted-foreground">Подписка сразу попадает в пул, по сроку возвращается сама; агенты, которые уже на ней, доработают текущий запуск. Участники проектов пула получают сообщение.</span>
|
||
</form>
|
||
</Disclosure>
|
||
)}
|
||
</Section>
|
||
|
||
<Section title="Подписки" count={subs.length}>
|
||
{subs.length === 0 ? <Empty>Подписок пока нет — добавьте первую ниже.</Empty> : subs.map((s) => <SubscriptionCard key={s.id} s={s} login={logins.get(s.id) ?? null} pools={poolNames} />)}
|
||
<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">
|
||
<NativeSelect name="method" defaultValue="login" aria-label="Способ входа">
|
||
<option value="login">Войти по ссылке (claude setup-token)</option>
|
||
<option value="token">Вставить готовый токен</option>
|
||
</NativeSelect>
|
||
<Input name="secret" type="password" placeholder="sk-ant-oat… (только для готового токена)" autoComplete="off" aria-label="Токен" />
|
||
<Button variant="default" className="self-start">Добавить</Button>
|
||
</AddForm>
|
||
</Disclosure>
|
||
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />Codex</span>}>
|
||
<AddForm provider="codex">
|
||
<NativeSelect name="method" defaultValue="device" aria-label="Способ входа">
|
||
<option value="device">Подписка ChatGPT (ссылка + код)</option>
|
||
<option value="api_key">API-ключ OpenAI</option>
|
||
</NativeSelect>
|
||
<Input name="secret" type="password" placeholder="sk-… (только для API-ключа)" autoComplete="off" aria-label="API-ключ" />
|
||
<Button variant="default" className="self-start">Добавить</Button>
|
||
</AddForm>
|
||
</Disclosure>
|
||
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />OpenCode</span>}>
|
||
<AddForm provider="opencode">
|
||
<input type="hidden" name="method" value="api_key" />
|
||
<NativeSelect name="keyProvider" defaultValue="anthropic" aria-label="Провайдер ключа">
|
||
{Object.keys(OPENCODE_KEY_ENV).map((k) => (
|
||
<option key={k} value={k}>{k}</option>
|
||
))}
|
||
</NativeSelect>
|
||
<Input name="secret" type="password" required placeholder="Ключ провайдера" autoComplete="off" aria-label="Ключ" />
|
||
<Button variant="default" className="self-start">Добавить</Button>
|
||
</AddForm>
|
||
</Disclosure>
|
||
</div>
|
||
</Section>
|
||
|
||
<Section title="Пулы" count={pools.length} id="pools">
|
||
{pools.length === 0 && <Empty>Пулов нет. Пул — набор подписок, который назначается проекту по умолчанию.</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="Название пула" className="max-w-xs font-medium" />
|
||
<span className="text-xs text-muted-foreground">
|
||
{p.projectKeys.length ? `по умолчанию у ${p.projectKeys.join(", ")}` : "не назначен проектам"}
|
||
</span>
|
||
</div>
|
||
<SubscriptionChecks subs={subs} checked={p.subscriptionIds} />
|
||
<Button size="sm" className="self-start">Сохранить</Button>
|
||
</form>
|
||
<form action={deletePoolAction}>
|
||
<Hidden fields={{ id: p.id }} />
|
||
<Button size="sm" variant="link" className="px-0 text-destructive">Удалить пул</Button>
|
||
</form>
|
||
</Card>
|
||
))}
|
||
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />Новый пул</span>}>
|
||
<form action={createPoolAction} className="flex flex-col gap-3">
|
||
<Label>
|
||
Название
|
||
<Input name="name" required placeholder="Основной" />
|
||
</Label>
|
||
<SubscriptionChecks subs={subs} checked={[]} />
|
||
<Button variant="default" className="self-start">Создать пул</Button>
|
||
</form>
|
||
</Disclosure>
|
||
<p className="m-0 text-xs text-muted-foreground">Пул проекта по умолчанию выбирается в «⋯ Настройки проекта».</p>
|
||
</Section>
|
||
</div>
|
||
</Workspace>
|
||
);
|
||
}
|