peppa/apps/web/components/cards.tsx
Асель 43e1319c5f PEP-156: кто говорит — события от имени Peppa FACTORY, агент под кличкой, роли на «вы»
Проекция событий в чаты подписывает то, что сделала фабрика или агент, «Peppa FACTORY»;
логин — только под словами человека. Слова агента — с кличкой (чат, карточка вопроса,
Telegram «🤖 Шустрик: …»), роли — «Аналитик» и «Продакт-агент». «Агент <кличка> взял
задачу в работу» ждёт запуска агента. Промпты ролей требуют «вы» (ADDRESS_RULE),
informalAddress проверяет ответы моков. Change pep-156-who-speaks в архиве, спека
project-chats, тест who-speaks.test.ts.

Rebased on main (one commit on top of 1074d276).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 18:30:48 +05:00

359 lines
23 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 { pausedProjectIds, messageDetails, questionAuthor, 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 } from "lucide-react";
import { DeleteProjectControl, mayDeleteProject, RestoreProjectButton } from "@/components/ProjectDelete";
import type { AnalystLink } from "@peppa/core";
import { SubscriptionName } from "@/components/SubscriptionName";
import { PausedBadge } from "@/components/ProjectPause";
import { answerQuestion, fixStoryAction, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions";
import { Textarea } from "@/components/ui/input";
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 { cleanText } from "@/lib/chat-text";
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, clean = false, signed = 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; /** PEP-207: chats for a non-superadmin — no terminal output or paths in the main text. */ clean?: boolean; /** PEP-156: the author is already shown above the card (a chat line). */ signed?: boolean }) {
const t = await getT();
const review = q.kind === "attention" && taskStatus === "review";
// PEP-207: a «готово» message stays one after the story moved on — its outcome is shown, not a form.
const reviewCard = q.kind === "attention" && (q.msgType === "done" || (review && q.msgType == null));
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 raw = t.text(questionText(q));
const shown = q.kind === "permission" ? { main: raw, more: details } : splitForDisplay(clean ? cleanText(raw, false, (process.env.GITEA_URL ?? "").replace(/\/+$/, "")) : raw, details ? t.text(details) : null);
// PEP-156: an agent's own words carry its nickname; the rest is said by the factory.
const author = await questionAuthor(db, q).catch(() => null);
const fromAgent = author?.kind === "agent";
// 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("Готово к ревью") : q.kind === "attention" && fromAgent ? t("Сообщение агента") : t(k.label)}</span>
{taskKey && <Key href={`/t/${taskKey}`}>{taskKey}</Key>}
{!signed && author?.kind === "agent" && author.name && <AgentBadge name={author.name} />}
<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 && reviewCard ? (
// PEP-207: the «готово» message after a press shows what came of it; no buttons are left.
<p data-review-outcome 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" && taskStatus === "done"
? t("Принято, {time}", { time: hhmm(q.answeredAt!) })
: q.answeredVia === "system"
? t("Уже не актуально")
: /^✅/.test(q.answer ?? "")
? t("Вы приняли, {time}", { time: hhmm(q.answeredAt!) })
: t("Вы попросили поправить, {time}: {text}", { time: hhmm(q.answeredAt!), text: q.answer ?? "" })}
</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>
) : review && taskKey ? (
// PEP-207: everything about the result right in the message — the same actions as on the task page.
<div data-review-actions className="flex flex-col gap-2">
<form action={answerQuestion} className="flex flex-wrap items-center gap-2">
<Hidden fields={{ questionId: q.id, back }} />
<Button asChild size="sm" variant="outline">
<Link href={`/t/${taskKey}`}>{t("Посмотреть результат")}</Link>
</Button>
<Button name="choice" value="__accept" variant="default" size="sm">{t("Принять")}</Button>
</form>
<details className="group/fix">
<summary className="inline-flex cursor-pointer list-none items-center rounded-md border px-3 py-1.5 text-sm hover:bg-accent [&::-webkit-details-marker]:hidden">{t("Поправить")}</summary>
<form action={fixStoryAction} className="mt-2 flex flex-col gap-2">
<Hidden fields={{ taskKey, back }} />
<Textarea id={`fix-${q.id}`} name="text" rows={3} required placeholder={t("Что поправить — агент доработает и пришлёт снова")} aria-label={t("Что поправить")} />
<div className="flex gap-2">
<Dictate target={`fix-${q.id}`} compact />
<Button size="sm" className="ml-auto">{t("Отправить агенту")}</Button>
</div>
</form>
</details>
</div>
) : 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. */}
{mayDeleteProject(p, userId, superadmin) && <DeleteProjectControl project={p} back="/projects" compact />}
{p.deletedAt && superadmin && <RestoreProjectButton projectId={p.id} back="/projects#deleted" />}
</div>
</li>
);
})}
</ul>
);
}
const hhmm = (d: Date) => new Date(d).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });