Ёмкость подписки (core/capacity.ts, по умолчанию 9, суперадмин меняет на набор 1–20); pickSubscription, ротация и ручной перевод агентов уважают ёмкость; без места задача ждёт в очереди и запускается сама по порядку доски (capacityQueueTick); команда растёт только в пределах ёмкости; экраны «Подписки», Главная, доска, страница задачи; ru/kk/en; тест subscription-capacity.test.ts; OpenSpec change archived. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
102 lines
6.4 KiB
TypeScript
102 lines
6.4 KiB
TypeScript
import type { ReactNode } from "react";
|
||
import Link from "next/link";
|
||
import type { PoolOverview, PoolSubscriptionState } from "@peppa/core";
|
||
import { intlLocale, type Locale } from "@peppa/shared/i18n";
|
||
import { Badge } from "@/components/ui/badge";
|
||
import { getT } from "@/lib/i18n";
|
||
|
||
const hhmm = (d: Date, locale: Locale) => d.toLocaleTimeString(intlLocale(locale), { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||
const KIND: Record<PoolSubscriptionState["provider"], string> = { claude: "Claude", codex: "ChatGPT", opencode: "OpenCode" };
|
||
|
||
function tone(s: PoolSubscriptionState): "ok" | "warn" | "danger" | "muted" | "primary" {
|
||
if (s.status === "auth_error") return "danger";
|
||
if (s.status === "pending") return "muted";
|
||
if (s.limitedUntil) return "warn";
|
||
return s.activeSessions ? "primary" : "ok";
|
||
}
|
||
|
||
/**
|
||
* PEP-107/170: the subscriptions of a set as people see them — one status per row (at work,
|
||
* free, limit until, sign-in error) and «следующая» on the one agents move to when theirs runs
|
||
* out; `action` adds buttons per row.
|
||
*/
|
||
export async function PoolSubscriptions({ o, action, capacity }: { o: PoolOverview; action?: (s: PoolSubscriptionState) => ReactNode; capacity?: boolean }) {
|
||
const t = await getT();
|
||
if (!o.subscriptions.length) return <p className="m-0 text-sm text-muted-foreground">{t("Подписок пока нет.")}</p>;
|
||
return (
|
||
<ul className="m-0 flex list-none flex-col divide-y divide-border p-0" aria-label={t("Подписки проекта")}>
|
||
{o.subscriptions.map((s) => (
|
||
<li key={s.id} className="flex flex-wrap items-center gap-x-2 gap-y-1 py-2 text-sm first:pt-0 last:pb-0" data-pool-subscription={s.id}>
|
||
<span className="font-medium">{s.name}</span>
|
||
{s.ownerName && !s.name.includes(s.ownerName) && <span className="text-xs text-muted-foreground" data-subscription-owner>· {s.ownerName}</span>}
|
||
{s.accountEmail && <span className="font-mono text-xs text-muted-foreground" data-subscription-account title={t("Аккаунт, под которым подключена подписка")}>· {s.accountEmail}</span>}
|
||
{!s.name.includes(KIND[s.provider]) && <span className="text-xs text-muted-foreground">{KIND[s.provider]}</span>}
|
||
<Badge variant={tone(s)}>{t.text(s.label)}</Badge>
|
||
{s.next && <Badge variant="info">{t("следующая")}</Badge>}
|
||
{/* PEP-182: live runners against the set's capacity — the superadmin's «Подписки» only. */}
|
||
{capacity && (
|
||
<span className={`text-xs ${s.activeSessions >= s.capacity ? "text-warn" : "text-muted-foreground"}`} data-subscription-load={s.id}>
|
||
{t("агентов: {n} из {max}", { n: s.activeSessions, max: s.capacity })}
|
||
</span>
|
||
)}
|
||
{s.usage && !s.limitedUntil && s.usage.pct! >= 50 && (
|
||
<span className={`text-xs ${s.usage.pct! >= 85 ? "text-warn" : "text-muted-foreground"}`}>
|
||
{s.usage.resetsAt
|
||
? t("израсходовано {pct}%, сброс в {time}", { pct: Math.round(s.usage.pct!), time: hhmm(s.usage.resetsAt, t.locale) })
|
||
: t("израсходовано {pct}%", { pct: Math.round(s.usage.pct!) })}
|
||
</span>
|
||
)}
|
||
{s.loan && <span className="text-xs text-muted-foreground">{t("временно, до {time}", { time: hhmm(s.loan.until, t.locale) })}</span>}
|
||
{action && <span className="ml-auto flex items-center gap-1">{action(s)}</span>}
|
||
</li>
|
||
))}
|
||
</ul>
|
||
);
|
||
}
|
||
|
||
/** One line under the list: what happens when the subscription at work runs out. */
|
||
export async function PoolSummary({ o }: { o: PoolOverview }) {
|
||
const t = await getT();
|
||
const resets = o.subscriptions.map((s) => s.limitedUntil).filter((d): d is Date => !!d).sort((a, b) => a.getTime() - b.getTime())[0];
|
||
let text: string;
|
||
if (!o.subscriptions.length) text = t("Добавьте подписку — без неё агенты не запустятся.");
|
||
else if (o.usableCount === 0) text = resets ? t("Все подписки кончились — агенты продолжат в {time}, когда сбросится лимит.", { time: hhmm(resets, t.locale) }) : t("Рабочих подписок нет — агенты стоят.");
|
||
else if (o.usableCount === 1) text = t("Запасной подписки нет: когда эта кончится, агенты подождут сброса лимита. Добавьте ещё одну.");
|
||
else text = t("Кончится одна — агенты перейдут на следующую.");
|
||
return <p className={`m-0 text-xs ${o.usableCount <= 1 ? "text-warn" : "text-muted-foreground"}`}>{text}</p>;
|
||
}
|
||
|
||
/** PEP-170: the latest switches — who moved, from which subscription to which, when. */
|
||
export async function PoolSwitches({ o }: { o: PoolOverview }) {
|
||
const t = await getT();
|
||
if (!o.switches.length) return null;
|
||
return (
|
||
<div className="flex flex-col gap-0.5 border-t border-border pt-2 text-xs text-muted-foreground">
|
||
<span className="font-medium text-foreground">{t("Переключения")}</span>
|
||
{o.switches.map((x, i) => (
|
||
<span key={i}>
|
||
{x.at.toLocaleString(intlLocale(t.locale), { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined })}
|
||
{" · "}
|
||
{x.taskKey ? <Link href={`/t/${x.taskKey}`}>{x.taskKey}</Link> : t("агент №{id}", { id: x.sessionId ?? "?" })}
|
||
{": "}
|
||
{x.fromName} → {x.toName}
|
||
{" "}
|
||
<span>({x.reason === "threshold" ? t("почти кончилась") : x.reason === "manual" ? t("переключил администратор") : t("кончилась")})</span>
|
||
</span>
|
||
))}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** PEP-182: the set's load and queue, and the capacity per subscription (superadmin). */
|
||
export async function PoolCapacity({ o, form }: { o: PoolOverview; form?: ReactNode }) {
|
||
const t = await getT();
|
||
return (
|
||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground" data-pool-capacity={o.pool.id}>
|
||
<span className={o.total && o.live >= o.total ? "text-warn" : undefined}>{t("Загрузка: {live} из {total}", { live: o.live, total: o.total })}</span>
|
||
<span className={o.queued ? "text-warn" : undefined}>{t("В очереди: {n}", { n: o.queued })}</span>
|
||
{form}
|
||
</div>
|
||
);
|
||
}
|