peppa/apps/web/app/(app)/t/[key]/tabs.tsx
Асель ee4a313074 PEP-84: «продакт» and «аналитик» refine a story before any developer agent takes it
Also: a subscription the owner connected once is assigned to their new projects; claudePrint never
falls back to the machine login for a self-registered owner.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 22:39:07 +05:00

412 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.

// 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 { reviewLabel } from "@peppa/core";
import { Hidden, QuestionCard } from "@/components/cards";
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 { cn } from "@/lib/utils";
import { acceptStoryAction, commentStoryAction } from "../../actions";
export const STORY_TABS = [
{ id: "proposal", label: "Proposal" },
{ id: "design", label: "Design" },
{ id: "specs", label: "Specs" },
{ id: "tasks", label: "Tasks" },
{ id: "comments", label: "Comments" },
{ id: "tests", label: "Tests" },
{ id: "merge", label: "Merge request" },
{ id: "activity", label: "Activity" },
] as const;
export type StoryTab = (typeof STORY_TABS)[number]["id"];
const noChange = (change: string | null) => <Empty>{change ? `Change ${change} не найден в рабочей копии.` : "Change ещё не создан — агент заведёт его на этапе proposal."}</Empty>;
export function ArtifactTab({ change, changeId, file }: { change: ChangeArtifacts | null; changeId: string | null; file: "proposal" | "design" }) {
if (!change) return noChange(changeId);
const text = change[file];
if (!text) return <Empty>{file === "design" ? "design.md в этом change нет — значит, решений сверх proposal не понадобилось." : "proposal.md ещё не написан."}</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: "добавлено", variant: "ok" },
MODIFIED: { label: "изменено", variant: "info" },
REMOVED: { label: "удалено", variant: "danger" },
RENAMED: { label: "переименовано", variant: "outline" },
};
export function SpecsTab({ change, changeId }: { change: ChangeArtifacts | null; changeId: string | null }) {
if (!change) return noChange(changeId);
if (!change.specs.length) return <Empty>В 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">{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}>{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">сценариев: {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">Сценарий: {sc.name}</p>
<Markdown text={sc.body} className="text-xs" />
</div>
))}
</div>
</Disclosure>
))}
</div>
))}
</section>
))}
</div>
);
}
export function TasksTab({ change, changeId, progress }: { change: ChangeArtifacts | null; changeId: string | null; progress: TasksProgress | null }) {
if (!change) return noChange(changeId);
if (!progress?.total) return <Empty>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 || "Пункты"}
<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 ? "выполнено" : "не выполнено"} 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 function ProgressBar({ done, total, current, compact = false }: { done: number; total: number; current: string | null; compact?: boolean }) {
const pct = total ? Math.round((done / total) * 100) : 0;
return (
<div className="flex min-w-0 flex-col gap-1" title={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">Сейчас: {current}</span>}
</div>
);
}
type Thread = { at: number; kind: "q"; q: Question } | { at: number; kind: "c"; c: StoryComment };
export function CommentsTab({ taskKey, taskStatus, questions, comments, back, hasLive }: { taskKey: string; taskStatus: string; questions: Question[]; comments: StoryComment[]; back: string; hasLive: boolean }) {
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">
{thread.length === 0 && <Empty>Вопросов и комментариев пока нет.</Empty>}
{thread.map((t) =>
t.kind === "q" ? (
<QuestionCard key={`q${t.q.id}`} q={t.q} taskStatus={taskStatus} back={back} />
) : (
<article key={`c${t.c.id}`} data-role={t.c.role} className={cn("flex flex-col gap-1.5 rounded-lg border p-3.5", t.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">
{t.c.role ? <AgentBadge name={t.c.login} className="font-medium text-foreground" /> : <MessageSquare className="size-3.5 text-primary" />}
{t.c.role ? (t.c.role === "product" ? "зачем и что берём" : "что должно получиться") : <><span className="font-medium text-foreground">{t.c.login}</span> комментарий PM</>} · {ago(t.c.createdAt)}
</header>
<p className="m-0 text-sm whitespace-pre-wrap [overflow-wrap:anywhere]">{t.c.text}</p>
</article>
),
)}
<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">
Комментарий для агента
</label>
<Textarea id="story-comment" name="text" rows={3} required maxLength={8000} placeholder="Что учесть: агент видит комментарии в get_task" />
<div className="flex flex-wrap items-center gap-3">
<label className="flex items-center gap-2 text-sm text-muted-foreground">
<input type="checkbox" name="toAgent" value="1" defaultChecked={hasLive} disabled={!hasLive} className="size-4 accent-primary" />
Отправить агенту сейчас{!hasLive && " (живой сессии нет)"}
</label>
<Button size="sm" className="ml-auto">
<Send />
Оставить комментарий
</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 function TestsTab({ ci, runs, review }: { ci: CiSummary; runs: CheckRunRow[]; review: CodeReview | null }) {
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" ? "Проверки не настроены" : ci.label}
{ci.sha && <span className="font-mono text-xs font-normal text-muted-foreground">коммит {ci.sha.slice(0, 7)}</span>}
{ci.runUrl && (
<a href={ci.runUrl} className="ml-auto text-xs font-normal text-primary">
запуск в Gitea
</a>
)}
</h3>
{ci.state === "not_configured" && <p className="m-0 text-sm text-muted-foreground">В `.peppa/project.json` проекта нет `checks` — PR проверяется только человеком.</p>}
{ci.state === "none" && <p className="m-0 text-sm text-muted-foreground">Проверки ещё не запускались: появятся после первого пуша ветки стори.</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">Агент-ревьюер</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]">{reviewLabel(review)}</span>
<span className="font-mono text-xs text-muted-foreground">
{review.sha.slice(0, 7)} · {ago(review.updatedAt)}
</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">Ревью не было: ревьюер выключен в настройках проекта или PR ещё не отдан в ревью.</p>
)}
</section>
</div>
);
}
function CheckLine({ r }: { r: CheckRunRow }) {
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">{r.durationSec} с</span>}
<span className="ml-auto font-mono text-xs text-muted-foreground">{ago(r.updatedAt)}</span>
{r.runUrl && (
<a href={r.runUrl} className="text-xs text-primary">
лог
</a>
)}
</span>
);
}
export function MergeTab({
taskKey,
taskStatus,
prUrl,
pull,
gate,
back,
}: {
taskKey: string;
taskStatus: string;
prUrl: string | null;
pull: GiteaPull | null;
gate: { ok: boolean; reason?: string } | null;
back: string;
}) {
if (!prUrl) return <Empty>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 ? "смержен" : pull.state === "closed" ? "закрыт" : "открыт") : "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">Ветка</dt>
<dd className="m-0 font-mono text-xs [overflow-wrap:anywhere]">
{pull.head.ref} → {pull.base.ref}
</dd>
<dt className="text-muted-foreground">Коммит</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">Мерж</dt>
<dd className="m-0">{gate?.ok ? <span className="text-ok">можно мержить</span> : <span className="text-warn">{gate?.reason ?? (pull.mergeable ? "без конфликтов" : "есть конфликты")}</span>}</dd>
</>
)}
</dl>
)}
<div className="flex flex-wrap items-center gap-2">
<Button asChild variant="outline" size="sm">
<a href={prUrl}>
<ExternalLink />
PR в Gitea
</a>
</Button>
<Button asChild variant="outline" size="sm">
<a href={`${prUrl.replace(/\/$/, "")}/files`}>Дифф</a>
</Button>
{taskStatus === "review" && !pull?.merged && (
<form action={acceptStoryAction} className="ml-auto">
<Hidden fields={{ taskKey, back }} />
<Button size="sm" disabled={gate ? !gate.ok : false} title={gate && !gate.ok ? gate.reason : undefined}>
<GitMerge />
Принять и смержить
</Button>
</form>
)}
</div>
{taskStatus !== "review" && !pull?.merged && <p className="m-0 text-xs text-muted-foreground">Мерж — когда стори в ревью: агент отдаёт её туда после зелёных проверок.</p>}
</section>
);
}
const EVENT_RU: Record<string, string> = {
task_updated: "стори изменена",
progress: "прогресс",
pm_comment: "комментарий",
claude_session: "сессия агента",
claude_session_end: "конец сессии агента",
session_started: "раннер запущен",
session_stopped: "раннер остановлен",
auto_continue: "автопродолжение",
awaiting_review: "ждёт ревьюера",
stop_failure: "ход оборвался",
notification: "уведомление",
terminal_input: "ввод в терминал",
subscription_switched: "смена подписки",
};
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>): { 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: 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: `агент · #${e.sessionId}`, tone: "agent" };
return { label: "система", tone: "system" };
}
function changeLine(e: ActivityEvent): string {
if (e.type !== "task_updated") return eventLine(e);
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 = { status: "статус", title: "название", description: "описание", goalId: "эпик", openspecChange: "change", prUrl: "PR" }[k] ?? k;
return k === "description" ? name : `${name} → ${v ?? "—"}`;
});
return parts.join(", ");
}
export function ActivityTab({ events, authors }: { events: ActivityEvent[]; authors?: Map<number, string | null> }) {
if (!events.length) return <Empty>Событий нет.</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);
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)}</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] ?? e.type}</span> {changeLine(e)}
</li>
);
})}
</ol>
);
}