peppa/apps/web/components/PoolSubscriptions.tsx

84 lines
5.3 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 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 }: { o: PoolOverview; action?: (s: PoolSubscriptionState) => ReactNode }) {
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>}
{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("почти кончилась") : t("кончилась")})</span>
</span>
))}
</div>
);
}