peppa/apps/web/components/cards.tsx

331 lines
20 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.

// 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 { pausedProjectIds, messageDetails, questionDetails, questionIsFreeText, questionState, questionText, questionType, splitForDisplay, trashDaysLeft, type Project, type Question, type SessionView, type StepView } from "@peppa/core";
import { db } from "@/lib/db";
import { MessagesSquare, Trash2, Undo2 } from "lucide-react";
import type { AnalystLink } from "@peppa/core";
import { SubscriptionName } from "@/components/SubscriptionName";
import { PausedBadge } from "@/components/ProjectPause";
import { answerQuestion, deleteProjectAction, messageSession, restoreProjectAction, 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, linkify, 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 { subscriptionNamesVisible, uiMode } from "@/lib/auth";
import { asIs, 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 notice = questionType(q, taskStatus) === null && q.taskId == null && q.sessionId == null;
// PEP-149: a factory message with answers to choose from is a question for the person.
const k = KIND[q.kind === "attention" && !review && q.options?.length ? "question" : q.kind];
const Icon = review ? CircleCheck : k.icon;
// PEP-151: the same state came again — one message with the time it was last refreshed.
const state = await questionState(db, q.id).catch(() => null);
const updatedAt = state?.updatedAt ? new Date(state.updatedAt) : null;
// PEP-152: the main text — at most five lines; the rest and the technical details open under «Подробнее».
const details = (await messageDetails(db, [q.id]).catch(() => null))?.get(q.id) ?? null;
// A permission request keeps its command whole: that is what the person allows.
const shown = q.kind === "permission" ? { main: t.text(questionText(q)), more: details } : splitForDisplay(t.text(questionText(q)), details ? t.text(details) : null);
// PEP-154: what the filter removed (command output, paths) — for «Инженер» and a superadmin only.
const original = (await uiMode()) === "engineer" || (await subscriptionNamesVisible()) ? await questionDetails(db, q.id).catch(() => null) : null;
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} · </>}{updatedAt ? t("обновлено {ago}", { ago: ago(updatedAt, t) }) : 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(questionText(q))}</p>
{!!state?.repeats && <p className="m-0 mt-1 text-xs text-muted-foreground">{t("Повторов: {n} · первое сообщение {ago}", { n: state.repeats, ago: ago(q.createdAt, t) })}</p>}
</details>
</>
) : (
<p data-message-main className="m-0 overflow-auto text-sm whitespace-pre-wrap break-words">{linkify(shown.main)}</p>
)}
{(shown.more || !!state?.repeats) && !(plain && q.kind === "permission") && (
<details data-message-details className="text-xs text-muted-foreground">
<summary className="cursor-pointer">{t("Подробнее")}</summary>
{shown.more && <p className={cn("m-0 mt-1 overflow-auto whitespace-pre-wrap break-words", compact ? "max-h-40" : "max-h-72")}>{shown.more}</p>}
{!!state?.repeats && <p className="m-0 mt-1">{t("Повторов: {n} · первое сообщение {ago}", { n: state.repeats, ago: ago(q.createdAt, t) })}</p>}
</details>
)}
{original && (
<details className="text-xs text-muted-foreground" data-question-original={q.id}>
<summary className="cursor-pointer">{t("Подробнее: исходный текст")}</summary>
<pre className="m-0 mt-1 max-h-72 overflow-auto font-mono whitespace-pre-wrap">{original}</pre>
</details>
)}
{/* PEP-149: a notice about the product as a whole (released, backlog is empty) asks nothing — no answer form. */}
{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>
) : notice ? null : (
<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>}
{/* PEP-149: no «continue» button — a message either has answers to choose from or needs none. */}
{(q.options ?? []).map((o) => (
<Button key={o} name="choice" value={o} size="sm" variant={o === q.defaultOption ? "default" : undefined} data-default-option={o === q.defaultOption ? "" : undefined}>{t.text(questionIsFreeText(q) ? asIs(o) : o)}</Button>
))}
</div>
{q.defaultOption && <p className="m-0 text-xs text-muted-foreground">{t("Если не ответите, агент продолжит по варианту «{option}».", { option: t.text(q.defaultOption) })}</p>}
{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, plainSteps = false }: { s: SessionView; back: string; showTitle?: boolean; terminal?: boolean; steps?: StepView[]; /** PEP-154: «Продакт» — steps in words. */ plainSteps?: boolean }) {
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"} plain={plainSteps} />}
{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, analyst, superadmin = false }: { projects: Array<Project & { ownerLogin?: string | null }>; userId: number; engineer?: boolean; /** PEP-161: projectId → the chat with the analyst; no entry — no link. */ analyst?: Map<number, AnalystLink>; /** PEP-181: may delete and bring back any project. */ superadmin?: boolean }) {
const t = await getT();
if (!projects.length)
return (
<Empty>
{t("Проектов пока нет.")} <Link href="/projects/new" className="text-primary">{t("Создать первый")}</Link>
</Empty>
);
// PEP-174: projects on pause carry a mark.
const paused = await pausedProjectIds(db);
return (
<ul className="m-0 grid list-none gap-2 p-0 sm:grid-cols-2">
{projects.map((p) => {
const chat = analyst?.get(p.id);
return (
<li key={p.id}>
{/* The project link is stretched over the whole card; the analyst link lies on top of it — no nested links. */}
<div className="relative flex h-full flex-col gap-1 rounded-lg border bg-card px-4 py-3 transition-colors hover:border-primary/50">
<Link href={`/p/${p.key}`} className="flex items-center gap-2 text-foreground after:absolute after:inset-0 after:rounded-lg hover:no-underline">
<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>
{paused.has(p.id) && <PausedBadge />}
{p.deletedAt && <span className="ml-auto rounded-full border border-destructive/60 px-2 text-[11px] text-destructive">{t("удалён, ещё {days} дн.", { days: trashDaysLeft(p) })}</span>}
{!p.deletedAt && 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>}
</Link>
{engineer && (
<span className="truncate font-mono text-xs text-muted-foreground">
{p.giteaOwner}/{p.giteaRepo}
</span>
)}
{chat && (
<Link href={chat.href} className="relative z-10 mt-1 inline-flex items-center gap-1.5 self-start py-1 text-sm font-medium text-primary">
<MessagesSquare className="size-4" /> {t("Написать аналитику")}
{chat.unread > 0 && <span className="rounded-full bg-info px-2 text-xs font-semibold text-background" title={t("новые сообщения")}>{t("{n} нов.", { n: chat.unread })}</span>}
</Link>
)}
{/* PEP-181: delete right on the card (owner or superadmin), with a confirmation; bring back a deleted one. */}
{!p.deletedAt && p.key !== (process.env.PEPPA_PLATFORM_KEY || "PEP") && (p.ownerId === userId || superadmin) && (
<details className="relative z-10 self-start" data-delete-project={p.key}>
<summary className="inline-flex cursor-pointer list-none items-center gap-1.5 py-1 text-sm text-muted-foreground hover:text-destructive">
<Trash2 className="size-4" /> {t("Удалить")}
</summary>
<form action={deleteProjectAction} className="mt-1 flex flex-col gap-2 rounded-md border border-destructive/40 bg-destructive/5 p-3 text-sm">
<Hidden fields={{ projectId: p.id, confirm: "yes", back: "/projects" }} />
<span>{t("Удалить проект «{name}»? Агенты остановятся. 7 дней его можно вернуть, потом он исчезнет насовсем.", { name: p.name })}</span>
<Button size="sm" variant="destructive" className="self-start">{t("Да, удалить")}</Button>
</form>
</details>
)}
{p.deletedAt && superadmin && (
<form action={restoreProjectAction} className="relative z-10 self-start">
<Hidden fields={{ projectId: p.id, back: "/projects" }} />
<Button size="sm" variant="outline" className="mt-1">
<Undo2 /> {t("Вернуть проект")}
</Button>
</form>
)}
</div>
</li>
);
})}
</ul>
);
}