peppa/apps/web/components/cards.tsx
2026-11-15 22:49:13 +05:00

265 lines
14 KiB
TypeScript

// Domain cards shared by pages: agent questions, runners, project list.
import Link from "next/link";
import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square, SquareTerminal } from "lucide-react";
import type { Project, Question, SessionView, StepView } from "@peppa/core";
import { SubscriptionName } from "@/components/SubscriptionName";
import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions";
import { Button } from "@/components/ui/button";
import { AgentBadge } from "@/components/AgentBadge";
import { Input } from "@/components/ui/input";
import { ago, Disclosure, Empty, Key, StatusBadge } from "@/components/common";
import { AgentSteps } from "@/components/AgentSteps";
import { Dictate } from "@/components/Dictate";
import { RunnerTerminal } from "@/components/RunnerTerminal";
import { SessionUsageLine } from "@/components/Accounting";
import { cn } from "@/lib/utils";
import { getT } from "@/lib/i18n";
import { m } from "@peppa/shared/i18n";
const KIND = {
approval: { label: m("Одобрение плана"), icon: FileCheck, border: "border-l-primary" },
question: { label: m("Вопрос"), icon: CircleHelp, border: "border-l-info" },
permission: { label: m("Разрешение"), icon: ShieldQuestion, border: "border-l-warn" },
attention: { label: m("Сообщение от фабрики"), icon: BellRing, border: "border-l-ok" },
} as const;
/** Hidden inputs of a server-action form. */
export function Hidden({ fields }: { fields: Record<string, string | number | null | undefined> }) {
return (
<>
{Object.entries(fields).map(([k, v]) => (v == null ? null : <input key={k} type="hidden" name={k} value={v} />))}
</>
);
}
export async function QuestionCard({ q, taskKey, taskStatus, back, compact = false, plain = false }: { q: Question; taskKey?: string | null; taskStatus?: string | null; back: string; compact?: boolean; /** PEP-120: for a product manager — no question number, a terminal command only under «Подробнее». */ plain?: boolean }) {
const t = await getT();
const review = q.kind === "attention" && taskStatus === "review";
const answered = !!q.answeredAt;
const k = KIND[q.kind];
const Icon = review ? CircleCheck : k.icon;
return (
<article id={`q-${q.id}`} className={cn("flex flex-col gap-2.5 rounded-lg border border-l-2 bg-card p-4", answered ? "border-l-border opacity-70" : k.border)}>
<header className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
<Icon className="size-4 text-muted-foreground" />
<span className="font-medium">{review ? t("Готово к ревью") : t(k.label)}</span>
{taskKey && <Key href={`/t/${taskKey}`}>{taskKey}</Key>}
<span className="ml-auto font-mono text-xs text-muted-foreground">
{!plain && <>#{q.id} · </>}{ago(q.createdAt, t)}
</span>
</header>
{plain && q.kind === "permission" ? (
<>
<p className="m-0 text-sm">{t("Агенту нужно ваше разрешение, чтобы продолжить работу.")}</p>
<details className="text-sm">
<summary className="cursor-pointer text-muted-foreground">{t("Подробнее")}</summary>
<p className="m-0 mt-1 max-h-40 overflow-auto whitespace-pre-wrap">{t.text(q.text)}</p>
</details>
</>
) : (
<p className={cn("m-0 overflow-auto text-sm whitespace-pre-wrap", compact ? "max-h-40" : "max-h-72")}>{t.text(q.text)}</p>
)}
{answered ? (
<p className="m-0 flex items-center gap-1.5 text-sm text-muted-foreground">
{q.answeredVia === "system" ? <Hourglass className="size-3.5" /> : <CircleCheck className="size-3.5 text-ok" />}
{q.answeredVia === "system" ? t.text(q.answer) : t("Ответ ({via}): {answer}", { via: q.answeredVia, answer: q.answer })}
</p>
) : (
<form action={answerQuestion} className="flex flex-col gap-2">
<Hidden fields={{ questionId: q.id, back }} />
<div className="flex flex-wrap gap-2">
{/* i18n-ignore: choice values are answers to the agent */}
{q.kind === "approval" && <Button name="choice" value="ок" variant="default" size="sm">{t("Одобрить")}</Button>}
{q.kind === "permission" && (
<>
<Button name="choice" value="allow" variant="default" size="sm">{t("Разрешить")}</Button>
<Button name="choice" value="always" size="sm">{t("Всегда")}</Button>
<Button name="choice" value="deny" variant="destructive" size="sm">{t("Запретить")}</Button>
</>
)}
{review && <Button name="choice" value="__accept" variant="default" size="sm">{t("Принять")}</Button>}
{/* i18n-ignore: the value is the message to the agent */}
{q.kind === "attention" && !review && <Button name="choice" value="Продолжай." variant="default" size="sm">{t("Продолжай")}</Button>}
{(q.options ?? []).map((o) => (
<Button key={o} name="choice" value={o} size="sm">{t.text(o)}</Button>
))}
</div>
{q.kind !== "permission" && (
<div className="flex gap-2">
<Input id={`answer-${q.id}`} name="answer" data-hotkey-answer placeholder={q.kind === "approval" || review ? t("Замечание — вернёт на доработку") : t("Свой ответ")} aria-label={t("Ответ")} className="h-8" />
<Dictate target={`answer-${q.id}`} compact />
<Button size="sm">{t("Ответить")}</Button>
</div>
)}
</form>
)}
</article>
);
}
/** Message / stop / resume controls of one runner. */
export async function SessionActions({ s, back }: { s: SessionView; back: string }) {
const t = await getT();
const alive = !["done", "failed"].includes(s.status);
return (
<div className="flex flex-wrap gap-2">
{alive && (
<form action={messageSession} className="flex min-w-0 flex-[1_1_16rem] gap-2">
<Hidden fields={{ sessionId: s.id, back }} />
<Input id={`agent-message-${s.id}`} name="text" placeholder={t("Написать агенту")} aria-label={t("Написать агенту")} className="h-8" />
<Dictate target={`agent-message-${s.id}`} compact />
<Button size="sm" aria-label={t("Отправить")} title={t("Отправить")}>
<Send />
<span className="max-sm:hidden">{t("Отправить")}</span>
</Button>
</form>
)}
{alive && (
<form action={stopTaskSession}>
<Hidden fields={{ sessionId: s.id, back }} />
<Button variant="destructive" size="sm">
<Square />
{t("Остановить")}
</Button>
</form>
)}
{(!alive || ["rate_limited", "stalled"].includes(s.status)) && (
<form action={resumeTaskSession}>
<Hidden fields={{ sessionId: s.id, back }} />
<Button size="sm">
{alive ? <RotateCcw /> : <Play />}
{t("Продолжить")}
</Button>
</form>
)}
</div>
);
}
export function AttachCommand({ name }: { name: string }) {
return <code className="block overflow-x-auto rounded-md bg-muted px-2.5 py-1.5 font-mono text-xs whitespace-nowrap text-muted-foreground">tmux attach -t {name}</code>;
}
/** `steps` (PEP-33): the live step feed of the agent, shown with the terminal. */
export async function SessionCard({ s, back, showTitle = false, terminal = false, steps }: { s: SessionView; back: string; showTitle?: boolean; terminal?: boolean; steps?: StepView[] }) {
const t = await getT();
return (
<article className="flex flex-col gap-2.5 rounded-lg border bg-card p-3.5">
<header className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
<StatusBadge status={s.status} kind="session" />
{s.taskKey ? <Key href={`/t/${s.taskKey}`}>{s.taskKey}</Key> : <Key href={`/p/${s.projectKey}`}>{s.projectKey}</Key>}
{s.agentName && <AgentBadge name={s.agentName} />}
{showTitle && (s.taskTitle ?? s.name) && <span className="min-w-0 flex-[1_1_12em] truncate">{s.taskTitle ?? s.name}</span>}
<span className="ml-auto font-mono text-xs text-muted-foreground">
<Link href={`/runners?id=${s.id}`} className="text-muted-foreground hover:text-foreground">#{s.id}</Link> · {s.provider}
<SubscriptionName s={s} prefix=" · " />
{s.host && <> · {s.host.name}</>}
{s.container && <> · {t("в контейнере")}</>}
{s.subscriptionSwitches > 0 && <> · {t("переключений {n}", { n: s.subscriptionSwitches })}</>} · {t("пок. {n}", { n: s.generation })} · {ago(s.lastActivityAt, t)}
</span>
</header>
<SessionUsageLine usage={s.usage} provider={s.provider} />
<AttachCommand name={s.tmuxName} />
<SessionActions s={s} back={back} />
{!terminal && !["done", "failed"].includes(s.status) && (
<Button asChild size="sm" variant="outline" className="self-start">
<Link href={`/runners?id=${s.id}`}>
<SquareTerminal /> {t("Открыть терминал")}
</Link>
</Button>
)}
{steps && <AgentSteps key={`steps-${s.id}`} sessionId={s.id} initial={steps} live={terminal} hooks={s.provider === "claude"} />}
{terminal && <RunnerTerminal key={s.id} sessionId={s.id} live />}
</article>
);
}
/**
* PEP-89: an agent at work, for a product manager — who, on what, in what state. The run's
* number, subscription, terminal command and spend sit under «Подробнее» — in «Инженер» only
* (PEP-123: «Продакт» sees no terminal commands, subscriptions or spend).
*/
export async function AgentAtWork({ s, back, engineer = false }: { s: SessionView; back: string; engineer?: boolean }) {
const alive = !["done", "failed"].includes(s.status);
const t = await getT();
const verb = s.status === "running" || s.status === "starting" ? t("работает над") : s.status === "waiting_input" ? t("спрашивает по") : t("вёл");
return (
<article className="flex flex-col gap-2.5 rounded-lg border bg-card p-3.5" data-agent-at-work={s.id}>
<header className="flex flex-wrap items-center gap-x-2.5 gap-y-1.5">
<AgentBadge name={s.agentName ?? t("без клички")} large />
<StatusBadge status={s.status} kind="session" />
<span className="ml-auto text-xs text-muted-foreground">{ago(s.lastActivityAt, t)}</span>
</header>
<p className="m-0 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-sm">
{s.taskKey ? (
<>
<span className="text-muted-foreground">{verb}</span>
<Key href={`/t/${s.taskKey}`}>{s.taskKey}</Key>
<span className="min-w-0 flex-[1_1_12em] truncate">{s.taskTitle}</span>
</>
) : (
<>
<span className="text-muted-foreground">{engineer ? t("свободный терминал в проекте") : t("помогает в проекте")}</span>
<Key href={`/p/${s.projectKey}`}>{s.projectKey}</Key>
{s.name && <span className="min-w-0 truncate">{s.name}</span>}
</>
)}
</p>
<SessionActions s={s} back={back} />
{engineer && (
<Disclosure summary={t("Подробнее")} className="border-0 bg-transparent [&>summary]:px-0 [&>summary]:py-0 [&>summary]:text-xs [&>summary]:font-normal [&>summary]:text-muted-foreground">
<div className="flex flex-col gap-2 pt-2">
<span className="font-mono text-xs text-muted-foreground">
{t("запуск #{id}", { id: s.id })} · {s.provider}
<SubscriptionName s={s} prefix=" · " />
{s.host && <> · {s.host.name}</>}
{s.container && <> · {t("в контейнере")}</>}
{s.subscriptionSwitches > 0 && <> · {t("переключений {n}", { n: s.subscriptionSwitches })}</>} · {t("пок. {n}", { n: s.generation })}
</span>
<SessionUsageLine usage={s.usage} provider={s.provider} />
<AttachCommand name={s.tmuxName} />
{alive && (
<Button asChild size="sm" variant="outline" className="self-start">
<Link href={`/runners?id=${s.id}`}>
<SquareTerminal /> {t("Открыть терминал")}
</Link>
</Button>
)}
</div>
</Disclosure>
)}
</article>
);
}
/** `engineer` (PEP-123): the address of the code is shown in «Инженер» only. */
export async function ProjectList({ projects, userId, engineer = false }: { projects: Array<Project & { ownerLogin?: string | null }>; userId: number; engineer?: boolean }) {
const t = await getT();
if (!projects.length)
return (
<Empty>
{t("Проектов пока нет.")} <Link href="/projects/new" className="text-primary">{t("Создать первый")}</Link>
</Empty>
);
return (
<ul className="m-0 grid list-none gap-2 p-0 sm:grid-cols-2">
{projects.map((p) => (
<li key={p.id}>
<Link href={`/p/${p.key}`} className="flex h-full flex-col gap-1 rounded-lg border bg-card px-4 py-3 text-foreground transition-colors hover:border-primary/50 hover:no-underline">
<span className="flex items-center gap-2">
<span className="rounded bg-muted px-1.5 font-mono text-xs text-primary">{p.key}</span>
<span className="min-w-0 truncate font-medium">{p.name}</span>
{p.ownerId !== userId && <span className="ml-auto rounded-full border px-2 text-[11px] text-muted-foreground">{p.ownerLogin !== undefined ? (p.ownerLogin ?? t("без владельца")) : t("общий")}</span>}
</span>
{engineer && (
<span className="truncate font-mono text-xs text-muted-foreground">
{p.giteaOwner}/{p.giteaRepo}
</span>
)}
</Link>
</li>
))}
</ul>
);
}