391 lines
20 KiB
TypeScript
391 lines
20 KiB
TypeScript
// Project page tabs «Код», «Спеки», «PR» and the epics block of «⋯ Настройки проекта» (PEP-66).
|
||
import type { Words } from "@peppa/shared/wording";
|
||
import { Archive, ExternalLink, GitBranch, GitPullRequest, Pencil } from "lucide-react";
|
||
import type { Epic, SpecSummary } from "@peppa/core";
|
||
import { Markdown } from "@/components/Markdown";
|
||
import type { AgentsMd, OpenPull, RepoOverview } from "@peppa/runner";
|
||
import { addEpic, editEpic, saveAgentsMdAction } from "../../actions";
|
||
import { Hidden } from "@/components/cards";
|
||
import { Disclosure, Empty, Key, Notice, Section, StatusBadge } from "@/components/common";
|
||
import { Badge } from "@/components/ui/badge";
|
||
import { Button } from "@/components/ui/button";
|
||
import { Input, Textarea } from "@/components/ui/input";
|
||
|
||
const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" }) : "—");
|
||
|
||
function plural(n: number, one: string, few: string, many: string) {
|
||
const m10 = n % 10;
|
||
const m100 = n % 100;
|
||
return m10 === 1 && m100 !== 11 ? one : m10 >= 2 && m10 <= 4 && (m100 < 12 || m100 > 14) ? few : many;
|
||
}
|
||
|
||
export function CodeTab({ code }: { code: RepoOverview }) {
|
||
const gitea = (
|
||
<Button asChild size="sm">
|
||
<a href={code.url}>
|
||
Открыть в Gitea <ExternalLink />
|
||
</a>
|
||
</Button>
|
||
);
|
||
if (code.error) {
|
||
return (
|
||
<Section title="Код" actions={gitea}>
|
||
<Empty>{code.error}. Репозиторий: <a href={code.url} className="text-primary">{code.url}</a></Empty>
|
||
</Section>
|
||
);
|
||
}
|
||
return (
|
||
<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_320px]">
|
||
<Section title={<>README {code.readme && <span className="ml-1 font-mono text-xs font-normal text-muted-foreground">{code.readme.path}</span>}</>} actions={gitea}>
|
||
{code.readme ? (
|
||
<pre className="m-0 max-h-[40em] overflow-auto rounded-lg border bg-card p-4 font-mono text-xs leading-relaxed whitespace-pre-wrap">{code.readme.text}</pre>
|
||
) : (
|
||
<Empty>{code.defaultBranch ? `В ветке ${code.defaultBranch} нет README.` : "Репозиторий пуст."}</Empty>
|
||
)}
|
||
</Section>
|
||
<div className="flex flex-col gap-6">
|
||
<Section title="Ветки" count={code.branches.length}>
|
||
{code.branches.length === 0 ? (
|
||
<Empty>Веток нет.</Empty>
|
||
) : (
|
||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||
{code.branches.map((b) => (
|
||
<li key={b.name} className="flex min-w-0 items-center gap-2 rounded-md px-2 py-1">
|
||
<GitBranch className="size-3.5 shrink-0 text-muted-foreground" />
|
||
<a href={`${code.url}/src/branch/${b.name.split("/").map(encodeURIComponent).join("/")}`} className="truncate font-mono text-xs text-primary">
|
||
{b.name}
|
||
</a>
|
||
{b.name === code.defaultBranch && <Badge variant="muted">по умолчанию</Badge>}
|
||
<span className="ml-auto shrink-0 font-mono text-[11px] text-muted-foreground">{b.sha.slice(0, 7)}</span>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
)}
|
||
</Section>
|
||
<Section title={`Коммиты ${code.defaultBranch ?? ""}`}>
|
||
{code.commits.length === 0 ? (
|
||
<Empty>Коммитов нет.</Empty>
|
||
) : (
|
||
<ul className="m-0 flex list-none flex-col gap-2 p-0 text-sm">
|
||
{code.commits.map((c) => (
|
||
<li key={c.sha} className="flex flex-col gap-0.5 rounded-md border bg-card px-3 py-2">
|
||
<span className="[overflow-wrap:anywhere]">{c.message}</span>
|
||
<span className="flex flex-wrap gap-x-2 text-xs text-muted-foreground">
|
||
<a href={c.url} className="font-mono text-primary">{c.sha.slice(0, 7)}</a>
|
||
{c.author} · {when(c.date)}
|
||
</span>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
)}
|
||
</Section>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** PEP-30: the project memory (.peppa/memory.md of the working copy), written by agents. */
|
||
export function MemorySection({ text, chars, max, nearLimit }: { text: string; chars: number; max: number; nearLimit: boolean }) {
|
||
return (
|
||
<Section title="Память проекта" actions={<span className={nearLimit ? "text-warn" : "text-muted-foreground"}>{chars} из {max} символов</span>} className="mb-8">
|
||
<p className="m-0 text-sm text-muted-foreground">Что агенты запомнили для следующих стори: команды, соглашения, грабли, решения (<code>.peppa/memory.md</code>, MCP <code>remember</code>). Раннер подкладывает её агенту при каждом запуске.</p>
|
||
{text.trim() ? (
|
||
<Disclosure summary={<span className="text-sm">Показать память{nearLimit ? " — почти предел, агент ужмёт её" : ""}</span>}>
|
||
<Markdown text={text} />
|
||
</Disclosure>
|
||
) : (
|
||
<Empty>Память пуста — агенты пополнят её в конце стори.</Empty>
|
||
)}
|
||
</Section>
|
||
);
|
||
}
|
||
|
||
export function SpecsTab({ specs }: { specs: SpecSummary[] }) {
|
||
return (
|
||
<Section title="Спеки" count={specs.length}>
|
||
<p className="m-0 text-sm text-muted-foreground">Что система умеет сейчас: требования OpenSpec из рабочей копии (openspec/specs). Обновляются, когда стори архивирует свой change.</p>
|
||
{specs.length === 0 ? (
|
||
<Empty>Спек ещё нет — они появляются после archive первого change.</Empty>
|
||
) : (
|
||
specs.map((s) => (
|
||
<Disclosure
|
||
key={s.name}
|
||
summary={
|
||
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||
<span className="flex items-center gap-2">
|
||
<span className="font-mono">{s.name}</span>
|
||
<Badge variant="muted">
|
||
{s.requirements} {plural(s.requirements, "требование", "требования", "требований")}
|
||
</Badge>
|
||
</span>
|
||
{s.purpose && <span className="text-xs font-normal text-muted-foreground">{s.purpose.split("\n")[0]}</span>}
|
||
</span>
|
||
}
|
||
>
|
||
<pre className="m-0 max-h-[40em] overflow-auto font-mono text-xs leading-relaxed whitespace-pre-wrap">{s.text}</pre>
|
||
</Disclosure>
|
||
))
|
||
)}
|
||
</Section>
|
||
);
|
||
}
|
||
|
||
const CI_TONE = { success: "ok", failure: "danger", pending: "info", none: "muted", not_configured: "muted" } as const;
|
||
|
||
export function PullsTab({ pulls, error, repoUrl }: { pulls: OpenPull[]; error: string | null; repoUrl: string }) {
|
||
return (
|
||
<Section
|
||
title="Открытые PR"
|
||
count={pulls.length}
|
||
actions={
|
||
<Button asChild size="sm">
|
||
<a href={`${repoUrl}/pulls`}>
|
||
Все PR в Gitea <ExternalLink />
|
||
</a>
|
||
</Button>
|
||
}
|
||
>
|
||
{error ? (
|
||
<Empty>{error}.</Empty>
|
||
) : pulls.length === 0 ? (
|
||
<Empty>Открытых PR нет.</Empty>
|
||
) : (
|
||
pulls.map((p) => (
|
||
<article key={p.number} className="flex flex-col gap-1.5 rounded-lg border bg-card p-3.5 text-sm">
|
||
<div className="flex items-start gap-2">
|
||
<GitPullRequest className="mt-0.5 size-4 shrink-0 text-ok" />
|
||
<a href={p.url} className="min-w-0 flex-1 text-foreground [overflow-wrap:anywhere]">
|
||
<span className="font-mono text-xs text-muted-foreground">#{p.number}</span> {p.title}
|
||
</a>
|
||
</div>
|
||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
|
||
<span className="font-mono">{p.branch}</span>
|
||
{p.task ? (
|
||
<>
|
||
· <Key href={`/t/${p.task.key}`}>{p.task.key}</Key>
|
||
<StatusBadge status={p.task.status} />
|
||
<Badge variant={CI_TONE[p.task.ci.state]}>{p.task.ci.label}</Badge>
|
||
</>
|
||
) : (
|
||
<span>· не стори Пеппы</span>
|
||
)}
|
||
</div>
|
||
</article>
|
||
))
|
||
)}
|
||
</Section>
|
||
);
|
||
}
|
||
|
||
/** «⋯ Настройки проекта» → Эпики: labels that group stories (stored as goals). */
|
||
/** PEP-34: done/total of an epic as a thin bar. */
|
||
export function ProgressBar({ done, total, className }: { done: number; total: number; className?: string }) {
|
||
const pct = total ? Math.round((done / total) * 100) : 0;
|
||
return (
|
||
<span role="progressbar" aria-valuemin={0} aria-valuemax={total} aria-valuenow={done} aria-label={`Готово ${done} из ${total}`} className={`inline-block h-1 overflow-hidden rounded-full bg-muted ${className ?? "w-12"}`}>
|
||
<span className="block h-full rounded-full bg-ok" style={{ width: `${pct}%` }} />
|
||
</span>
|
||
);
|
||
}
|
||
|
||
export function EpicsPanel({ projectId, projectKey, epics, progress, back, w }: { w: Words; projectId: number; projectKey: string; epics: Epic[]; progress: Map<number, { done: number; total: number }>; back: string }) {
|
||
return (
|
||
<div className="flex flex-col gap-2 text-sm">
|
||
{epics.length === 0 && <p className="m-0 text-muted-foreground">Эпиков нет. Эпик — большая цель, которая объединяет {w.task("accPl")}; его описание агент получает вместе с {w.task("ins")}.</p>}
|
||
{epics.map((e) => (
|
||
<details key={e.id} className="group rounded-md border bg-card">
|
||
<summary className="flex cursor-pointer list-none items-center gap-2 px-3 py-2 select-none [&::-webkit-details-marker]:hidden">
|
||
<span className="text-muted-foreground transition-transform group-open:rotate-90">›</span>
|
||
<span className="min-w-0 flex-1 truncate">{e.title}</span>
|
||
<ProgressBar done={progress.get(e.id)?.done ?? 0} total={progress.get(e.id)?.total ?? 0} />
|
||
<span className="font-mono text-[11px] text-muted-foreground tabular-nums">{progress.get(e.id)?.done ?? 0}/{progress.get(e.id)?.total ?? 0}</span>
|
||
{w.engineer && <span className="font-mono text-[11px] text-muted-foreground">#{e.id}</span>}
|
||
</summary>
|
||
<div className="flex flex-col gap-2 border-t px-3 py-2.5">
|
||
<form action={editEpic} className="flex flex-col gap-2">
|
||
<Hidden fields={{ projectId, epicId: e.id, back }} />
|
||
<Input name="title" required minLength={2} defaultValue={e.title} aria-label="Название эпика" className="h-8" />
|
||
<Textarea name="description" rows={3} defaultValue={e.description ?? ""} placeholder="Описание для агента: зачем этот эпик" aria-label="Описание эпика" />
|
||
<Button size="xs" className="self-start">Сохранить</Button>
|
||
</form>
|
||
<div className="flex flex-wrap gap-2">
|
||
<Button asChild size="xs" variant="outline">
|
||
<a href={`/p/${projectKey}/plan/${e.id}`}>Спланировать {w.task("accPl")}</a>
|
||
</Button>
|
||
<form action={editEpic}>
|
||
<Hidden fields={{ projectId, epicId: e.id, back, archive: "1" }} />
|
||
<Button size="xs" variant="ghost">
|
||
<Archive />В архив
|
||
</Button>
|
||
</form>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
))}
|
||
<form action={addEpic} className="flex flex-col gap-2">
|
||
<Hidden fields={{ projectId, back }} />
|
||
<div className="flex gap-2">
|
||
<Input name="title" required minLength={2} placeholder="Новый эпик" aria-label="Название нового эпика" className="h-8" />
|
||
<Button size="sm">Добавить</Button>
|
||
</div>
|
||
</form>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** PEP-73: the project's AGENTS.md — prompt and standards every agent follows; read and edit. */
|
||
export function AgentsMdTab({ projectId, projectKey, md, edit, saved }: { projectId: number; projectKey: string; md: AgentsMd; edit: boolean; saved: boolean }) {
|
||
const tabHref = `/p/${projectKey}?tab=agents`;
|
||
const gitea = (
|
||
<Button asChild size="sm">
|
||
<a href={md.url}>
|
||
В Gitea <ExternalLink />
|
||
</a>
|
||
</Button>
|
||
);
|
||
if (md.error) {
|
||
return (
|
||
<Section title="AGENTS.md" actions={gitea}>
|
||
<Empty>{md.error}</Empty>
|
||
</Section>
|
||
);
|
||
}
|
||
if (edit) {
|
||
return (
|
||
<Section title="AGENTS.md — правка" actions={gitea}>
|
||
<form action={saveAgentsMdAction} className="flex flex-col gap-3">
|
||
<Hidden fields={{ projectId: String(projectId), sha: md.sha ?? "", back: `${tabHref}&edit=1` }} />
|
||
<Textarea name="text" defaultValue={md.text || AGENTS_MD_STARTER} rows={28} spellCheck={false} className="font-mono text-xs leading-relaxed" aria-label="Текст AGENTS.md" />
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<Button variant="default">Сохранить в {md.branch}</Button>
|
||
<Button asChild variant="ghost">
|
||
<a href={tabHref}>Отмена</a>
|
||
</Button>
|
||
<span className="text-xs text-muted-foreground">Коммит в ветку {md.branch} от вашего имени. Новые и перезапущенные агенты прочитают его сразу.</span>
|
||
</div>
|
||
</form>
|
||
</Section>
|
||
);
|
||
}
|
||
return (
|
||
<Section
|
||
title="AGENTS.md"
|
||
actions={
|
||
<>
|
||
<Button asChild size="sm" variant="default">
|
||
<a href={`${tabHref}&edit=1`}>
|
||
<Pencil /> Изменить
|
||
</a>
|
||
</Button>
|
||
{gitea}
|
||
</>
|
||
}
|
||
>
|
||
{saved && <Notice>AGENTS.md сохранён в {md.branch}</Notice>}
|
||
<p className="m-0 text-sm text-muted-foreground">
|
||
Промпт и стандарты проекта: стек, команды, соглашения, этапы (например, проверка ИБ перед PR). Его читают все агенты — Claude, Codex и OpenCode; общие правила
|
||
Пеппы добавляются сами.
|
||
</p>
|
||
{md.text.trim() ? (
|
||
<div className="rounded-lg border bg-card p-4">
|
||
<Markdown text={md.text} />
|
||
</div>
|
||
) : (
|
||
<Empty>В репозитории ещё нет AGENTS.md — нажмите «Изменить», чтобы создать его из заготовки.</Empty>
|
||
)}
|
||
</Section>
|
||
);
|
||
}
|
||
|
||
const AGENTS_MD_STARTER = `# AGENTS.md
|
||
|
||
Проект ведётся на **Peppa FACTORY**. Общие правила (OpenSpec, PR, ревью) агент получает от Пеппы;
|
||
здесь — только стандарты этого проекта.
|
||
|
||
## Стек и команды
|
||
<!-- Язык, фреймворки, как собрать и запустить тесты. -->
|
||
|
||
## Соглашения
|
||
<!-- Стиль кода, структура, именование, что запрещено. -->
|
||
|
||
## Перед PR
|
||
- Тесты и линтеры проходят.
|
||
- Безопасность (ИБ): нет секретов в коде и логах; весь ввод проверяется; доступ к данным — только своему пользователю;
|
||
новые зависимости — без известных уязвимостей. Итог проверки — раздел «ИБ» в описании PR.
|
||
`;
|
||
|
||
interface EpicStory {
|
||
key: string;
|
||
title: string;
|
||
status: string;
|
||
goalId: number | null;
|
||
}
|
||
|
||
/** PEP-81: epics in plain sight — each epic (a big goal) with its stories (the steps agents do). */
|
||
export function EpicsTab({ projectId, projectKey, epics, stories, progress, back, w }: { w: Words; projectId: number; projectKey: string; epics: Epic[]; stories: EpicStory[]; progress: Map<number, { done: number; total: number }>; back: string }) {
|
||
const loose = stories.filter((s) => !s.goalId || !epics.some((e) => e.id === s.goalId));
|
||
const list = (items: EpicStory[]) =>
|
||
items.length ? (
|
||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||
{items.map((s) => (
|
||
<li key={s.key} className="flex flex-wrap items-center gap-x-2 gap-y-0.5">
|
||
<Key href={`/t/${s.key}`}>{s.key}</Key>
|
||
<span className="min-w-0 flex-[1_1_12em] truncate">{s.title}</span>
|
||
<StatusBadge status={s.status} />
|
||
</li>
|
||
))}
|
||
</ul>
|
||
) : (
|
||
<p className="m-0 text-sm text-muted-foreground">{w.Task("genPl")} пока нет.</p>
|
||
);
|
||
return (
|
||
<Section title="Эпики" count={epics.length}>
|
||
<p className="m-0 text-sm text-muted-foreground">
|
||
<b className="text-foreground">Эпик</b> — большая цель, например «Оплата» или «Личный кабинет». <b className="text-foreground">{w.Task()}</b> — один конкретный шаг к ней: её делает агент, она — карточка на
|
||
доске. У {w.task("gen")} может быть один эпик; его описание агент получает вместе с {w.task("ins")}.
|
||
</p>
|
||
<form action={addEpic} className="flex flex-wrap items-end gap-2 rounded-lg border bg-card px-4 py-3">
|
||
<Hidden fields={{ projectId, back }} />
|
||
<Input name="title" required minLength={2} placeholder="Новый эпик: большая цель" aria-label="Название нового эпика" className="h-8 min-w-48 flex-1" />
|
||
<Input name="description" placeholder="Зачем он — одной фразой (необязательно)" aria-label="Описание нового эпика" className="h-8 min-w-48 flex-[2]" />
|
||
<Button size="sm" variant="default">Добавить эпик</Button>
|
||
</form>
|
||
{epics.map((e) => {
|
||
const pr = progress.get(e.id) ?? { done: 0, total: 0 };
|
||
return (
|
||
<article key={e.id} id={`epic-${e.id}`} className="flex flex-col gap-2.5 rounded-lg border bg-card px-4 py-3" data-epic={e.id}>
|
||
<header className="flex flex-wrap items-center gap-2">
|
||
<Badge variant="primary">эпик</Badge>
|
||
<h3 className="m-0 min-w-0 flex-1 truncate text-base font-medium">{e.title}</h3>
|
||
<ProgressBar done={pr.done} total={pr.total} className="w-24" />
|
||
<span className="text-xs text-muted-foreground tabular-nums">
|
||
готово {pr.done} из {pr.total}
|
||
</span>
|
||
</header>
|
||
{e.description && <p className="m-0 text-sm text-muted-foreground">{e.description}</p>}
|
||
{list(stories.filter((s) => s.goalId === e.id))}
|
||
<div className="flex flex-wrap gap-2">
|
||
<Button asChild size="xs" variant="outline">
|
||
<a href={`/p/${projectKey}?epic=${e.id}`}>На доске</a>
|
||
</Button>
|
||
<Button asChild size="xs" variant="outline">
|
||
<a href={`/p/${projectKey}/plan/${e.id}`}>Спланировать {w.task("accPl")}</a>
|
||
</Button>
|
||
</div>
|
||
</article>
|
||
);
|
||
})}
|
||
{loose.length > 0 && (
|
||
<article className="flex flex-col gap-2.5 rounded-lg border border-dashed px-4 py-3">
|
||
<header className="flex items-center gap-2">
|
||
<h3 className="m-0 text-base font-medium text-muted-foreground">{w.Task("pl")} без эпика</h3>
|
||
<span className="text-xs text-muted-foreground">{loose.length}</span>
|
||
</header>
|
||
{list(loose)}
|
||
</article>
|
||
)}
|
||
<p className="m-0 text-xs text-muted-foreground">Переименовать эпик, изменить описание или убрать в архив — «Настройки проекта → Эпики». Эпик {w.task("gen")} меняется кнопкой «Изменить» на её странице.</p>
|
||
</Section>
|
||
);
|
||
}
|