peppa/apps/web/app/(app)/t/[key]/tabs.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

462 lines
24 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.

// Story page tabs (PEP-32): OpenSpec artifacts of the change, comments, checks, the PR and
// the activity log. Server components; each tab reads only what it shows.
import { AgentBadge } from "@/components/AgentBadge";
import { CircleCheck, CircleX, ExternalLink, GitMerge, GitPullRequest, Hourglass, MessageSquare, Send } from "lucide-react";
import type { ChangeArtifacts, CiSummary, CodeReview, DeltaOp, GiteaPull, Question, StoryComment, TasksProgress } from "@peppa/core";
import { attachmentsByEvent, PENDING_ACCEPT_LABEL, reviewLabel, storyOwnAttachments } from "@peppa/core";
import { db } from "@/lib/db";
import { AttachField } from "@/components/AttachField";
import { Attachments } from "@/components/Attachments";
import { Hidden, QuestionCard } from "@/components/cards";
import { Dictate } from "@/components/Dictate";
import { ago, Disclosure, Empty } from "@/components/common";
import { Markdown } from "@/components/Markdown";
import { eventLine } from "@/components/RunnerConsole";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/input";
import { commentHint } from "@/lib/comment-hint";
import { cn } from "@/lib/utils";
import { getT } from "@/lib/i18n";
import { m, translator, type Translator } from "@peppa/shared/i18n";
import { acceptStoryAction, commentStoryAction } from "../../actions";
export const STORY_TABS = [
// PEP-94: names a product manager understands (ids stay — links keep working).
{ id: "proposal", label: m("План") },
{ id: "design", label: m("Как устроено") },
{ id: "specs", label: m("Требования") },
{ id: "tasks", label: m("Шаги") },
{ id: "comments", label: m("Обсуждение") },
{ id: "tests", label: m("Проверки") },
{ id: "merge", label: m("Результат") },
{ id: "activity", label: m("История") },
] as const;
export type StoryTab = (typeof STORY_TABS)[number]["id"];
// glossary-ignore: имя OpenSpec change — техническое, как в main
const noChange = (t: Translator, change: string | null) => <Empty>{change ? t("Change {change} не найден в рабочей копии.", { change }) : t("План ещё не написан — агент составит его, когда возьмёт стори.")}</Empty>;
export async function ArtifactTab({ change, changeId, file }: { change: ChangeArtifacts | null; changeId: string | null; file: "proposal" | "design" }) {
const t = await getT();
if (!change) return noChange(t, changeId);
const text = change[file];
if (!text) return <Empty>{file === "design" ? t("Отдельных решений об устройстве не понадобилось — всё есть в плане.") : t("План ещё не написан.")}</Empty>;
return (
<article className="rounded-lg border bg-card p-5">
<Markdown text={text} />
</article>
);
}
const OP: Record<DeltaOp, { label: string; variant: "ok" | "info" | "danger" | "outline" }> = {
ADDED: { label: m("добавлено"), variant: "ok" },
MODIFIED: { label: m("изменено"), variant: "info" },
REMOVED: { label: m("удалено"), variant: "danger" },
RENAMED: { label: m("переименовано"), variant: "outline" },
};
export async function SpecsTab({ change, changeId }: { change: ChangeArtifacts | null; changeId: string | null }) {
const t = await getT();
if (!change) return noChange(t, changeId);
if (!change.specs.length) return <Empty>{t("В change нет дельта-спецификаций (specs/*/spec.md).")}</Empty>;
return (
<div className="flex flex-col gap-4">
{change.specs.map((spec) => (
<section key={spec.capability} className="flex flex-col gap-3 rounded-lg border bg-card p-4">
<h3 className="m-0 font-mono text-sm font-semibold">{spec.capability}</h3>
{spec.sections.map((sec, si) => (
<div key={si} className="flex flex-col gap-2">
{sec.requirements.length === 0 && <p className="m-0 text-xs text-muted-foreground">{t("{op}: без требований", { op: t(OP[sec.op].label) })}</p>}
{sec.requirements.map((r, ri) => (
<Disclosure
key={ri}
open={change.specs.length === 1 && ri < 3}
summary={
<span className="flex min-w-0 items-center gap-2">
<Badge variant={OP[sec.op].variant}>{t(OP[sec.op].label)}</Badge>
<span className="min-w-0 font-medium [overflow-wrap:anywhere]">{r.name}</span>
{r.scenarios.length > 0 && <span className="ml-auto shrink-0 font-mono text-[11px] text-muted-foreground">{t("сценариев: {n}", { n: r.scenarios.length })}</span>}
</span>
}
>
<div className="flex flex-col gap-3">
{r.body && <Markdown text={r.body} />}
{r.scenarios.map((sc, i) => (
<div key={i} className="rounded-md border-l-2 border-primary/50 bg-muted/30 py-2 pr-3 pl-3">
<p className="m-0 mb-1 text-xs font-semibold">{t("Сценарий: {name}", { name: sc.name })}</p>
<Markdown text={sc.body} className="text-xs" />
</div>
))}
</div>
</Disclosure>
))}
</div>
))}
</section>
))}
</div>
);
}
export async function TasksTab({ change, changeId, progress }: { change: ChangeArtifacts | null; changeId: string | null; progress: TasksProgress | null }) {
const t = await getT();
if (!change) return noChange(t, changeId);
if (!progress?.total) return <Empty>{t("tasks.md ещё нет или в нём нет пунктов.")}</Empty>;
return (
<div className="flex flex-col gap-4">
<ProgressBar done={progress.done} total={progress.total} current={progress.current} />
{progress.sections.map((sec, i) => {
const done = sec.items.filter((it) => it.done).length;
return (
<section key={i} className="flex flex-col gap-1.5 rounded-lg border bg-card p-4">
<h3 className="m-0 flex items-center gap-2 text-sm font-semibold">
{sec.title || t("Пункты")}
<span className={cn("ml-auto font-mono text-xs tabular-nums", done === sec.items.length ? "text-ok" : "text-muted-foreground")}>
{done}/{sec.items.length}
</span>
</h3>
<ul className="m-0 flex list-none flex-col gap-1 p-0">
{sec.items.map((it, j) => (
<li key={j} className={cn("flex items-start gap-2 text-sm", it.text === progress.current && !it.done && "rounded bg-info/10 px-1 -mx-1")}>
<input type="checkbox" checked={it.done} readOnly disabled aria-label={it.done ? t("выполнено") : t("не выполнено")} className="mt-1 size-3.5 shrink-0 accent-primary" />
<span className={cn("[overflow-wrap:anywhere]", it.done && "text-muted-foreground line-through decoration-muted-foreground/40")}>{it.text}</span>
</li>
))}
</ul>
</section>
);
})}
</div>
);
}
export async function ProgressBar({ done, total, current, compact = false }: { done: number; total: number; current: string | null; compact?: boolean }) {
const t = await getT();
const pct = total ? Math.round((done / total) * 100) : 0;
return (
<div className="flex min-w-0 flex-col gap-1" title={current ? t("Сейчас: {current}", { current }) : undefined}>
<div className="flex items-center gap-2">
<div className={cn("flex-1 overflow-hidden rounded-full bg-muted", compact ? "h-1" : "h-1.5")}>
<div className={cn("h-full rounded-full", done === total ? "bg-ok" : "bg-info")} style={{ width: `${pct}%` }} />
</div>
<span className="font-mono text-xs text-muted-foreground tabular-nums">
{done}/{total}
</span>
</div>
{current && !compact && <span className="truncate text-xs text-muted-foreground">{t("Сейчас: {current}", { current })}</span>}
</div>
);
}
type Thread = { at: number; kind: "q"; q: Question } | { at: number; kind: "c"; c: StoryComment };
export async function CommentsTab({ taskId, projectId, taskKey, taskStatus, questions, comments, back, hasLive, refining = false }: { taskId: number; projectId: number; taskKey: string; taskStatus: string; questions: Question[]; comments: StoryComment[]; back: string; hasLive: boolean; refining?: boolean }) {
const t = await getT();
// PEP-159: the files of every comment and the story's own.
const files = await attachmentsByEvent(db, comments.map((c) => c.id));
const own = await storyOwnAttachments(db, taskId);
const thread: Thread[] = [...questions.map((q) => ({ at: q.createdAt.getTime(), kind: "q" as const, q })), ...comments.map((c) => ({ at: c.createdAt.getTime(), kind: "c" as const, c }))].sort((a, b) => a.at - b.at);
return (
<div className="flex flex-col gap-3">
{own.length > 0 && (
<section className="flex flex-col gap-1.5 rounded-lg border bg-card p-3.5" aria-label={t("Файлы задачи")}>
<h3 className="m-0 text-xs font-medium text-muted-foreground">{t("Файлы задачи")}</h3>
<Attachments files={own} />
</section>
)}
{thread.length === 0 && own.length === 0 && <Empty>{t("Вопросов и комментариев пока нет.")}</Empty>}
{thread.map((x) =>
x.kind === "q" ? (
<QuestionCard key={`q${x.q.id}`} q={x.q} taskStatus={taskStatus} back={back} />
) : (
<article key={`c${x.c.id}`} data-role={x.c.role} className={cn("flex flex-col gap-1.5 rounded-lg border p-3.5", x.c.role ? "border-info/40 bg-info/[0.06]" : "border-primary/30 bg-primary/[0.04]")}>
<header className="flex items-center gap-2 text-xs text-muted-foreground">
{x.c.role ? <AgentBadge name={x.c.login} role className="font-medium text-foreground" /> : <MessageSquare className="size-3.5 text-primary" />}
{x.c.role ? (x.c.role === "product" ? t("зачем и что берём") : t("что должно получиться")) : <><span className="font-medium text-foreground">{x.c.login}</span> {t("комментарий PM")}</>} · {ago(x.c.createdAt, t)}
</header>
<p className="m-0 text-sm whitespace-pre-wrap [overflow-wrap:anywhere]">{x.c.text}</p>
<Attachments files={files.get(x.c.id)} />
</article>
),
)}
{refining && (
<p data-refining className="m-0 flex items-center gap-2 text-sm text-muted-foreground">
<Hourglass className="size-3.5" />
{t("Аналитик уточняет постановку…")}
</p>
)}
<form action={commentStoryAction} className="flex flex-col gap-2 rounded-lg border bg-card p-3.5">
<Hidden fields={{ taskKey, back }} />
<label htmlFor="story-comment" className="text-sm font-medium">
{t("Комментарий к стори")}
</label>
<Textarea id="story-comment" name="text" rows={3} maxLength={60000} placeholder={t("Что учесть или изменить в задаче")} aria-describedby="story-comment-hint" />
<AttachField projectId={projectId} target="story-comment" />
<div className="flex flex-wrap items-center gap-3">
<Dictate target="story-comment" />
<p id="story-comment-hint" className="m-0 text-sm text-muted-foreground">
{t(commentHint(taskStatus, hasLive))}
</p>
{hasLive && (
<label className="flex items-center gap-2 text-sm text-muted-foreground">
<input type="checkbox" name="toAgent" value="1" defaultChecked className="size-4 accent-primary" />
{t("Отправить агенту сейчас")}
</label>
)}
<Button size="sm" className="ml-auto">
<Send />
{t("Оставить комментарий")}
</Button>
</div>
</form>
</div>
);
}
const STATE_ICON = {
success: <CircleCheck className="size-4 text-ok" />,
failure: <CircleX className="size-4 text-destructive" />,
error: <CircleX className="size-4 text-destructive" />,
pending: <Hourglass className="size-4 text-warn" />,
};
export interface CheckRunRow {
check: string;
state: "pending" | "success" | "failure" | "error";
runUrl: string | null;
logTail: string | null;
durationSec: number | null;
updatedAt: Date;
}
export async function TestsTab({ ci, runs, review }: { ci: CiSummary; runs: CheckRunRow[]; review: CodeReview | null }) {
const t = await getT();
return (
<div className="flex flex-col gap-4">
<section className="flex flex-col gap-3 rounded-lg border bg-card p-4">
<h3 className="m-0 flex flex-wrap items-center gap-2 text-sm font-semibold">
{STATE_ICON[ci.state as keyof typeof STATE_ICON]}
{ci.state === "not_configured" ? t("Проверки не настроены") : t.text(ci.label)}
{ci.sha && <span className="font-mono text-xs font-normal text-muted-foreground">{t("коммит {sha}", { sha: ci.sha.slice(0, 7) })}</span>}
{ci.runUrl && (
<a href={ci.runUrl} className="ml-auto text-xs font-normal text-primary">
{t("запуск в Gitea")}
</a>
)}
</h3>
{ci.state === "not_configured" && <p className="m-0 text-sm text-muted-foreground">{t("В `.peppa/project.json` проекта нет `checks` — PR проверяется только человеком.")}</p>}
{ci.state === "none" && <p className="m-0 text-sm text-muted-foreground">{t("Проверки ещё не запускались: появятся после первого пуша ветки стори.")}</p>}
{runs.length > 0 && (
<ul className="m-0 flex list-none flex-col gap-1.5 p-0">
{runs.map((r) => (
<li key={r.check}>
{r.logTail && r.state !== "success" ? (
<Disclosure open={r.state !== "pending"} summary={<CheckLine r={r} />}>
<pre className="m-0 max-h-80 overflow-auto font-mono text-[11px] whitespace-pre-wrap">{r.logTail.split("\n").slice(-80).join("\n")}</pre>
</Disclosure>
) : (
<div className="px-3 py-1.5">
<CheckLine r={r} />
</div>
)}
</li>
))}
</ul>
)}
</section>
<section className="flex flex-col gap-2 rounded-lg border bg-card p-4">
<h3 className="m-0 text-sm font-semibold">{t("Агент-ревьюер")}</h3>
{review ? (
<>
<p className="m-0 flex flex-wrap items-center gap-2 text-sm">
{review.verdict === "ok" ? STATE_ICON.success : review.verdict === "changes" || review.state === "error" ? STATE_ICON.failure : STATE_ICON.pending}
<span className="[overflow-wrap:anywhere]">{t.text(reviewLabel(review))}</span>
<span className="font-mono text-xs text-muted-foreground">
{review.sha.slice(0, 7)} · {ago(review.updatedAt, t)}
</span>
</p>
{review.summary && <Markdown text={review.summary} className="text-xs" />}
{review.findings.length > 0 && (
<ul className="m-0 flex list-disc flex-col gap-1 pl-5 text-xs">
{review.findings.map((f, i) => (
<li key={i} className="[overflow-wrap:anywhere]">
{f.file && <span className="font-mono text-muted-foreground">{f.file}{f.line ? `:${f.line}` : ""} — </span>}
{f.text}
</li>
))}
</ul>
)}
</>
) : (
<p className="m-0 text-sm text-muted-foreground">{t("Ревью не было: ревьюер выключен в настройках проекта или PR ещё не отдан в ревью.")}</p>
)}
</section>
</div>
);
}
async function CheckLine({ r }: { r: CheckRunRow }) {
const t = await getT();
return (
<span className="flex min-w-0 items-center gap-2 text-sm">
{STATE_ICON[r.state]}
<span className="font-mono">{r.check}</span>
{r.durationSec != null && <span className="font-mono text-xs text-muted-foreground">{t("{n} с", { n: r.durationSec })}</span>}
<span className="ml-auto font-mono text-xs text-muted-foreground">{ago(r.updatedAt, t)}</span>
{r.runUrl && (
<a href={r.runUrl} className="text-xs text-primary">
{t("лог")}
</a>
)}
</span>
);
}
export async function MergeTab({
taskKey,
taskStatus,
prUrl,
pull,
gate,
back,
accepted,
}: {
taskKey: string;
taskStatus: string;
prUrl: string | null;
pull: GiteaPull | null;
gate: { ok: boolean; reason?: string } | null;
back: string;
/** PEP-127: «Принять» is remembered — the agent updates the changes, Peppa closes the story itself. */
accepted?: boolean;
}) {
const t = await getT();
// PEP-127: an open PR that can't be merged yet does not block «Принять» — it is remembered and carried through.
const carried = pull?.state === "open" && !!gate && !gate.ok;
const checksFailed = !!gate?.reason?.startsWith("проверки не пройдены"); // i18n-ignore: the Russian reason from core (prGate)
if (!prUrl) return <Empty>{t("PR ещё нет — агент откроет его, когда закончит работу.")}</Empty>;
return (
<section className="flex flex-col gap-3 rounded-lg border bg-card p-4">
<h3 className="m-0 flex flex-wrap items-center gap-2 text-sm font-semibold">
{pull?.merged ? <GitMerge className="size-4 text-ok" /> : <GitPullRequest className={cn("size-4", pull?.state === "closed" ? "text-destructive" : "text-primary")} />}
{pull ? (
<>
#{pull.number} {pull.title}
</>
) : (
"Pull request"
)}
<Badge variant={pull?.merged ? "ok" : pull?.state === "closed" ? "danger" : "info"} className="ml-auto">
{pull ? (pull.merged ? t("смержен") : pull.state === "closed" ? t("закрыт") : t("открыт")) : t("Gitea недоступна")}
</Badge>
</h3>
{pull && (
<dl className="m-0 grid grid-cols-[max-content_minmax(0,1fr)] gap-x-3 gap-y-1.5 text-sm">
<dt className="text-muted-foreground">{t("Ветка")}</dt>
<dd className="m-0 font-mono text-xs [overflow-wrap:anywhere]">
{pull.head.ref} → {pull.base.ref}
</dd>
<dt className="text-muted-foreground">{t("Коммит")}</dt>
<dd className="m-0 font-mono text-xs">{pull.head.sha.slice(0, 10)}</dd>
{!pull.merged && pull.state === "open" && (
<>
<dt className="text-muted-foreground">{t("Мерж")}</dt>
<dd className="m-0">{gate?.ok ? <span className="text-ok">{t("можно мержить")}</span> : <span className="text-warn">{gate?.reason ? t.text(gate.reason) : pull.mergeable ? t("без конфликтов") : t("есть конфликты")}</span>}</dd>
</>
)}
</dl>
)}
<div className="flex flex-wrap items-center gap-2">
<Button asChild variant="outline" size="sm">
<a href={prUrl}>
<ExternalLink />
{t("PR в Gitea")}
</a>
</Button>
<Button asChild variant="outline" size="sm">
<a href={`${prUrl.replace(/\/$/, "")}/files`}>{t("Дифф")}</a>
</Button>
{taskStatus === "review" && !pull?.merged && !accepted && (
<form action={acceptStoryAction} className="ml-auto">
<Hidden fields={{ taskKey, back }} />
<Button size="sm" disabled={!!gate && !gate.ok && (!carried || checksFailed)} title={checksFailed && gate?.reason ? t.text(gate.reason) : carried ? t("Сначала изменения обновятся и пройдут проверки, затем задача закроется сама") : undefined}>
<GitMerge />
{t("Принять и смержить")}
</Button>
</form>
)}
</div>
{accepted && !pull?.merged && <p className="m-0 text-sm text-ok">{t("{label}. Нажимать ещё раз не нужно — мы сообщим, когда задача закроется.", { label: t.text(PENDING_ACCEPT_LABEL) })}</p>}
{!accepted && taskStatus !== "review" && !pull?.merged && <p className="m-0 text-xs text-muted-foreground">{t("Мерж — когда стори в ревью: агент отдаёт её туда после зелёных проверок.")}</p>}
</section>
);
}
const EVENT_RU: Record<string, string> = {
task_updated: m("стори изменена"),
progress: m("прогресс"),
pm_comment: m("комментарий"),
claude_session: m("сессия агента"),
claude_session_end: m("конец сессии агента"),
session_started: m("раннер запущен"),
session_stopped: m("раннер остановлен"),
auto_continue: m("автопродолжение"),
awaiting_review: m("ждёт ревьюера"),
stop_failure: m("ход оборвался"),
notification: m("уведомление"),
terminal_input: m("ввод в терминал"),
subscription_switched: m("смена подписки"),
};
export interface ActivityEvent {
id: number;
type: string;
payload: unknown;
sessionId: number | null;
createdAt: Date;
}
/** Who did it: a PM by login, the agent of a session, or Peppa itself. */
export function eventAuthor(e: ActivityEvent, authors?: Map<number, string | null>, t: Translator = translator("ru")): { label: string; tone: "pm" | "agent" | "system" } {
// PEP-48: the recorded author (person + channel, agent, Peppa) when the event has one.
const kind = (e as { actorKind?: string | null }).actorKind;
const recorded = authors?.get(e.id);
if (kind && recorded) return { label: t.text(recorded), tone: kind === "user" ? "pm" : kind === "agent" ? "agent" : "system" };
const login = (e.payload as { login?: unknown } | null)?.login;
if (typeof login === "string" && login) return { label: login, tone: "pm" };
if (e.sessionId) return { label: t("агент · #{id}", { id: e.sessionId }), tone: "agent" };
return { label: t("система"), tone: "system" };
}
const CHANGE_FIELD: Record<string, string> = { status: m("статус"), title: m("название"), description: m("описание"), goalId: m("эпик"), openspecChange: "change", prUrl: "PR" };
function changeLine(e: ActivityEvent, t: Translator): string {
if (e.type !== "task_updated") return eventLine(e, t);
const to = ((e.payload as { to?: Record<string, unknown> } | null)?.to ?? {}) as Record<string, unknown>;
const parts = Object.entries(to).map(([k, v]) => {
const name = t(CHANGE_FIELD[k] ?? k);
return k === "description" ? name : `${name} → ${v ?? "—"}`;
});
return parts.join(", ");
}
export async function ActivityTab({ events, authors }: { events: ActivityEvent[]; authors?: Map<number, string | null> }) {
const t = await getT();
if (!events.length) return <Empty>{t("Событий нет.")}</Empty>;
return (
<ol className="m-0 flex list-none flex-col gap-0 border-l p-0 pl-4">
{events.map((e) => {
const a = eventAuthor(e, authors, t);
return (
<li key={e.id} className="relative py-1.5 text-sm [overflow-wrap:anywhere]">
<span className={cn("absolute top-3 -left-[1.3rem] size-2 rounded-full", a.tone === "pm" ? "bg-primary" : a.tone === "agent" ? "bg-info" : "bg-muted-foreground")} />
<span className="font-mono text-xs text-muted-foreground">{ago(e.createdAt, t)}</span> <span className={cn("text-xs font-medium", a.tone === "pm" ? "text-primary" : a.tone === "agent" ? "text-info" : "text-muted-foreground")}>{a.label}</span>{" "}
<span className="font-mono text-xs text-muted-foreground">{EVENT_RU[e.type] ? t(EVENT_RU[e.type]) : e.type}</span> {changeLine(e, t)}
</li>
);
})}
</ol>
);
}