peppa/apps/web/app/(app)/platform/page.tsx

159 lines
9.5 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 { Megaphone, RefreshCw, Send } from "lucide-react";
import { AGENT_CLIS, buildPlatformDigest, getAgentVersions, getPlatformBuild, pinnedAgentVersions, versionDrifts, getPlatformChannel, isSuperadmin, platformDigestEmpty, PLATFORM_CHANNEL_EVENT_NAMES, PLATFORM_CHANNEL_EVENTS, renderPlatformDigest } from "@peppa/core";
import { ago, Flash, 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 } 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 { checkChannelAction, saveChannelAction, saveChannelSettingsAction, sendDigestNowAction } from "./actions";
export async function generateMetadata() {
const t = await getT();
return { title: t("Платформа — FORGE") };
}
/** Telegram HTML of the digest → plain text for the preview. */
const plain = (html: string) => html.replace(/<[^>]+>/g, "").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
export default async function Platform({ searchParams }: { searchParams: Promise<{ error?: string; sent?: string }> }) {
const user = await requireUser();
const t = await getT();
if (!(await isSuperadmin(db, user))) notFound();
const { error, sent } = await searchParams;
const [c, build, versions] = await Promise.all([getPlatformChannel(db), getPlatformBuild(db), getAgentVersions(db)]);
// PEP-267: pinned agent CLI versions against what runs (the watchdog checks once an hour).
const pinned = pinnedAgentVersions();
const drifts = versions ? versionDrifts(versions) : [];
const digest = await buildPlatformDigest(db, { since: new Date(Date.now() - 24 * 3600_000) });
return (
<Workspace>
<div className="max-w-3xl">
<Flash error={error} />
{sent && <p className="mb-4 rounded-lg border px-4 py-3 text-sm">{sent === "empty" ? t("Дайджест пуст — нечего отправлять.") : t("Дайджест отправлен: {to}", { to: sent.replace("channel", t("в канал")).replace(",users:", " · " + t("пользователям:") + " ") })}</p>}
<PageHeader title={<><Megaphone className="mr-1 inline size-5 text-primary" />{t("Платформа")}</>}>
{t("Telegram-канал FORGE: новые версии, падения и перезапуски сервисов и ежедневный дайджест — что нового в FORGE и что происходит сейчас. Раздел видят только суперадмины.")}
{build && <> {t("Сейчас: v{version}", { version: build.version })} · <span className="font-mono">{build.commit.slice(0, 7)}</span>.</>}
</PageHeader>
<Section title={t("Канал")}>
<Card className="gap-3">
<div className="flex flex-wrap items-center gap-2">
{c.chatId == null ? (
<Badge variant="secondary">{t("канал не задан")}</Badge>
) : !c.check ? (
<Badge variant="info">{t("не проверен")}</Badge>
) : c.check.ok ? (
<Badge variant="ok">{t("канал подключён")}</Badge>
) : (
<Badge variant="danger">{t("не работает")}</Badge>
)}
{c.check?.ok && c.title && <span className="font-semibold">{c.title}</span>}
{c.check && <span className="ml-auto text-xs text-muted-foreground">{t("проверен {ago}", { ago: ago(new Date(c.check.at), t) })}</span>}
</div>
{c.check && !c.check.ok && <p className="m-0 text-sm text-destructive">{t.text(c.check.error)}</p>}
<form action={saveChannelAction} className="flex flex-wrap items-end gap-2">
<Label className="min-w-56 flex-1">
{t("Chat ID канала")}
<Input name="chatId" placeholder={t("-100… или @имя")} defaultValue={c.chatId == null ? "" : String(c.chatId)} className="h-8 font-mono" />
</Label>
<Button size="sm">{t("Сохранить и проверить")}</Button>
</form>
{c.chatId != null && (
<form action={checkChannelAction}>
<Button size="sm" variant="outline"><RefreshCw />{t("Проверить ещё раз")}</Button>
</form>
)}
<p className="m-0 text-xs text-muted-foreground">
{t("Добавьте бота FORGE в канал администратором с правом «Публикация сообщений». Пока проверка не прошла, FORGE перепроверяет канал раз в час и ничего туда не пишет. Ответы в канале бот не читает.")}
</p>
</Card>
</Section>
<Section title={t("Что присылать")}>
<Card>
<form action={saveChannelSettingsAction} className="flex flex-col gap-3">
{PLATFORM_CHANNEL_EVENTS.map((e) => (
<label key={e} className="flex items-center gap-2 text-sm">
<input type="checkbox" name={`event.${e}`} defaultChecked={c.events[e]} className="size-4 accent-primary" />
{t("{event} — в канал", { event: t(PLATFORM_CHANNEL_EVENT_NAMES[e]) })}
</label>
))}
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="users" defaultChecked={c.digest.users} className="size-4 accent-primary" />
{t("Дайджест ещё и в личные чаты всем, кто привязал Telegram (отписка — «Настройки → Уведомления»)")}
</label>
<div className="grid gap-2 sm:grid-cols-2">
<Label>
{t("Время дайджеста")}
<Input name="time" type="time" required defaultValue={c.digest.time} className="h-8" />
</Label>
<Label>
{t("Таймзона")}
<Input name="timezone" required defaultValue={c.digest.timezone} className="h-8 font-mono" />
</Label>
</div>
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
</form>
</Card>
</Section>
<Section title={t("Версии программ агентов")}>
<Card className="gap-3">
<table className="w-full text-sm">
<thead className="text-left text-xs text-muted-foreground">
<tr>
<th className="font-normal">{t("Программа")}</th>
<th className="font-normal">{t("Закреплена")}</th>
<th className="font-normal">{t("В сервисе FORGE")}</th>
<th className="font-normal">{t("В образе агентов")}</th>
</tr>
</thead>
<tbody className="font-mono">
{AGENT_CLIS.map(({ cli, name }) => {
const cell = (place: "service" | "runner", v: string | undefined) => {
const bad = drifts.some((d) => d.cli === cli && d.place === place);
return <td className={bad ? "text-destructive" : undefined}>{v ?? "—"}{bad && <> <Badge variant="danger">{t("не та версия")}</Badge></>}</td>;
};
return (
<tr key={cli}>
<td className="font-sans">{name}</td>
<td>{pinned[cli] ?? "—"}</td>
{cell("service", versions?.service[cli])}
{cell("runner", versions?.runner?.[cli])}
</tr>
);
})}
</tbody>
</table>
<p className="m-0 text-xs text-muted-foreground">
{versions ? t("Проверено {ago}.", { ago: ago(new Date(versions.at), t) }) : t("Ещё не проверялось.")}{" "}
{/* glossary-ignore: раздел видят только суперадмины — имя скрипта, не слово для продакта */}
{t("Программы сами не обновляются. Новая версия — scripts/runner-image.sh --try <программа> <версия> (сначала проверка), вернуть прежний образ агентов — scripts/runner-image.sh --rollback.")}
</p>
</Card>
</Section>
<Section
title={t("Дайджест за сутки")}
actions={
<form action={sendDigestNowAction}>
<Button size="sm" variant="outline"><Send />{t("Отправить сейчас")}</Button>
</form>
}
>
{platformDigestEmpty(digest) ? (
<p className="m-0 text-sm text-muted-foreground">{t("За сутки ничего нового и ничего не происходит — дайджест не уйдёт.")}</p>
) : (
<pre className="m-0 overflow-x-auto rounded-md bg-muted p-3 text-xs whitespace-pre-wrap">{plain(renderPlatformDigest(digest))}</pre>
)}
</Section>
</div>
</Workspace>
);
}