584 lines
33 KiB
TypeScript
584 lines
33 KiB
TypeScript
import { notFound } from "next/navigation";
|
||
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
|
||
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release } from "@peppa/runner";
|
||
import { listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, memoryStats, readMemory, projectPool, sharedPool, ownPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||
import { PanelSection } from "@/components/ActivityAside";
|
||
import { Board, type Card } from "@/components/Board";
|
||
import { Hidden, SessionCard } from "@/components/cards";
|
||
import { Empty, Flash, Key, Notice, PageHeader, Section } from "@/components/common";
|
||
import { IncidentSettingsPanel, IncidentsSection } from "@/components/Incidents";
|
||
import { AutonomyPanel } from "@/components/Autonomy";
|
||
import { NewRunnerForm, RunnerSettingsPanel } from "@/components/Runners";
|
||
import { AgentModelPanel } from "@/components/AgentModel";
|
||
import { Badge } from "@/components/ui/badge";
|
||
import { Button } from "@/components/ui/button";
|
||
import { Input, NativeSelect, Textarea } from "@/components/ui/input";
|
||
import { SettingsDialog } from "@/components/SettingsDialog";
|
||
import { ProjectSecretsPanel } from "@/components/ProjectSecrets";
|
||
import { Workspace } from "@/components/Workspace";
|
||
import { SubscriptionSetup } from "@/components/SubscriptionSetup";
|
||
import { requireUser } from "@/lib/auth";
|
||
import { cn } from "@/lib/utils";
|
||
import { db } from "@/lib/db";
|
||
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
|
||
import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, saveReviewSettingsAction, saveIntakeSettingsAction, setProjectVisibilityAction, connectOwnSubscriptionAction, chooseSharedSubscriptionAction } from "../../actions";
|
||
import { AgentsMdTab, CodeTab, EpicsPanel, EpicsTab, MemorySection, ProgressBar, PullsTab, SpecsTab } from "./tabs";
|
||
import { setProjectPoolAction } from "../../subscriptions/actions";
|
||
import { JournalFilters, JournalList, MetricsTab, ProjectBudgetPanel } from "@/components/Accounting";
|
||
import { saveProjectBudgetAction } from "../../actions";
|
||
|
||
const RELEASE_STATUS: Record<Release["status"], { label: string; tone: "info" | "ok" | "warn" | "danger" | "muted" }> = {
|
||
deploying: { label: "выкатывается", tone: "info" },
|
||
healthy: { label: "работает", tone: "ok" },
|
||
rolled_back: { label: "откат", tone: "warn" },
|
||
failed: { label: "не поднялся", tone: "danger" },
|
||
removed: { label: "удалён", tone: "muted" },
|
||
};
|
||
|
||
const TABS = [
|
||
{ id: "board", label: "Доска" },
|
||
{ id: "epics", label: "Эпики" },
|
||
{ id: "code", label: "Код" },
|
||
{ id: "specs", label: "Спеки" },
|
||
{ id: "agents", label: "AGENTS.md" },
|
||
{ id: "pulls", label: "PR" },
|
||
{ id: "releases", label: "Релизы" },
|
||
{ id: "bugs", label: "Баги" },
|
||
{ id: "sessions", label: "Сессии" },
|
||
{ id: "metrics", label: "Метрики" },
|
||
{ id: "journal", label: "Журнал" },
|
||
] as const;
|
||
|
||
function EnvLine({ name, r }: { name: string; r: Release | null | undefined }) {
|
||
return (
|
||
<div className="flex min-w-0 flex-1 flex-col gap-0.5 rounded-md border bg-background/40 px-3 py-2">
|
||
<span className="font-mono text-[11px] tracking-wider text-muted-foreground uppercase">{name}</span>
|
||
{r ? (
|
||
<span className="flex min-w-0 flex-wrap items-center gap-x-2 text-sm">
|
||
<span className="font-mono">{r.sha.slice(0, 7)}</span>
|
||
{r.host && (
|
||
<a href={`https://${r.host}`} className="truncate text-primary">
|
||
{r.host}
|
||
</a>
|
||
)}
|
||
</span>
|
||
) : (
|
||
<span className="text-sm text-muted-foreground">нет</span>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string; tab?: string; epic?: string; weeks?: string; actor?: string; channel?: string; edit?: string; saved?: string }> }) {
|
||
const user = await requireUser();
|
||
const { key } = await params;
|
||
const { error, created, tab: tabParam, epic: epicParam, weeks, actor, channel, edit, saved } = await searchParams;
|
||
const tab = TABS.find((t) => t.id === tabParam)?.id ?? "board";
|
||
const p = await projectForUserByKey(user.id, key).catch(() => null);
|
||
if (!p) notFound();
|
||
const [{ tasks }, epics, sessions, team, repo, incidentSettings, sources, incidents, releases, current, reviewer, progress, deps] = await Promise.all([
|
||
board(p.id),
|
||
listEpics(db, p.id),
|
||
projectSessions(p.id),
|
||
listMembers(db, p),
|
||
describeRepo(db, p),
|
||
getIncidentSettings(db, p.id),
|
||
listErrorSources(db, p.id),
|
||
listIncidents(db, p.id),
|
||
listReleases(db, p.id, 15),
|
||
currentReleases(db, p.id),
|
||
getReviewSettings(db, p.id),
|
||
epicProgress(db, p.id),
|
||
blockersMap(db, p.id),
|
||
]);
|
||
// Peppa itself has no staging: its prod candidate is the newest green main (PEP-18).
|
||
const prodCandidate = isPlatform(p) ? ((await platformReleaseOffers(db)) ? await platformReleaseCandidate(db, p) : null) : (current.staging?.sha ?? null);
|
||
const collaborators = new Set((repo.collaborators ?? []).map((l) => l.toLowerCase()));
|
||
// Members who are not repo collaborators (only known when Gitea listed them; owners of the namespace see it anyway).
|
||
const noRepoAccess = (login: string) =>
|
||
repo.collaborators !== null && login.toLowerCase() !== p.giteaOwner.toLowerCase() && !collaborators.has(login.toLowerCase());
|
||
const missingAccess = team.members.some((m) => noRepoAccess(m.login));
|
||
// PEP-67: default subscription pool; only a superadmin changes it.
|
||
const superadmin = await isSuperadmin(db, user);
|
||
// PEP-88: a superadmin manages any project like its owner.
|
||
const isOwner = p.ownerId === user.id || superadmin;
|
||
const [pool, pools, autonomy, shared] = await Promise.all([projectPool(db, p.id), superadmin ? listPools(db) : Promise.resolve([]), getAutonomy(db, p.id), sharedPool(db)]);
|
||
// PEP-10/27: runner settings of the project over the system ones.
|
||
const [runnerOwn, runnerSystem, secrets, runnerHosts] = await Promise.all([getProjectRunnerSettings(db, p.id), getSystemRunnerSettings(db), listProjectSecrets(db, p.id), listHosts(db, { enabled: true })]);
|
||
// PEP-41: agent provider/model of the project over the platform's.
|
||
const [agentOwn, agentSystem] = await Promise.all([getProjectAgentSettings(db, p.id), getSystemAgentSettings(db)]);
|
||
// PEP-31: the project's pool has no working subscription — agents won't start.
|
||
const agentWarning = await projectAgentWarning(db, p.id);
|
||
// PEP-80: the owner's own subscriptions — a ChatGPT device login in progress, and whether a pool exists already.
|
||
const mayChoose = isOwner || superadmin;
|
||
const [ownLogins, hasOwnPool] = await Promise.all([mayChoose && pool ? ownPendingLogins(db, pool.id) : Promise.resolve([]), mayChoose ? ownPool(db, user.id).then((x) => !!x) : Promise.resolve(false)]);
|
||
// Epic filter (PEP-66): only an open epic of this project filters; anything else shows all.
|
||
const epicFilter = epics.find((e) => String(e.id) === epicParam) ?? null;
|
||
const boardHref = (epicId?: number) => (epicId ? `/p/${p.key}?epic=${epicId}` : `/p/${p.key}`);
|
||
const back = tab === "board" ? boardHref(epicFilter?.id) : `/p/${p.key}?tab=${tab}`;
|
||
const epicTitle = new Map(epics.map((e) => [e.id, e.title]));
|
||
const agentNames = await taskAgentNames(db, p.id);
|
||
const [intake, refining] = await Promise.all([getIntakeSettings(db, p.id), intakePendingTasks(db, p.id)]);
|
||
const cards: Card[] = tasks
|
||
.filter((t) => !epicFilter || t.goalId === epicFilter.id)
|
||
.map((t) => {
|
||
const pr = columnOf(t.status) === "in_progress" ? taskProgress(p, t.openspecChange) : null;
|
||
return {
|
||
key: `${p.key}-${t.number}`,
|
||
title: t.title,
|
||
status: t.status,
|
||
column: columnOf(t.status),
|
||
epic: t.goalId ? (epicTitle.get(t.goalId) ?? null) : null,
|
||
// PEP-33: tasks.md progress of stories in work.
|
||
progress: pr && { done: pr.done, total: pr.total, current: pr.current },
|
||
blocked: t.status === "backlog" ? blockedLabel(deps.get(t.id)) : null,
|
||
agent: agentNames.get(t.id) ?? null,
|
||
refining: refining.has(t.id) ? (refining.get(t.id) === "waiting" ? "ждёт ваших ответов" : "уточняется") : null,
|
||
};
|
||
});
|
||
// Gitea and the working copy are read only for the open tab.
|
||
const [code, pulls] = await Promise.all([tab === "code" ? repoOverview(db, p) : null, tab === "pulls" ? openPulls(db, p) : null]);
|
||
const specs = tab === "specs" ? listSpecs(p) : [];
|
||
const agentsMd = tab === "agents" ? await readAgentsMd(db, p) : null;
|
||
const memory = tab === "specs" ? readMemory(p.workspacePath) : "";
|
||
// PEP-47 metrics, PEP-48 journal, PEP-43 default budget.
|
||
const metrics = tab === "metrics" ? await projectMetrics(db, p.id, { weeks: Number(weeks) || 8 }) : null;
|
||
const journal = tab === "journal" ? await listJournal(db, { projectId: p.id, actorKind: (actor || undefined) as ActorKind | undefined, channel: (channel || undefined) as ActorChannel | undefined, limit: 200 }) : [];
|
||
const projectBudget = await getProjectBudget(db, p.id);
|
||
|
||
const aside = (
|
||
<div className="flex flex-col gap-6">
|
||
<PanelSection title="Репозиторий">
|
||
<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 truncate">
|
||
<a href={repo.url} className="text-primary">{repo.fullName}</a>
|
||
</dd>
|
||
<dt className="text-muted-foreground">Пространство</dt>
|
||
<dd className="m-0">
|
||
{p.giteaOwner}
|
||
{repo.ownerKind && ` — ${repo.ownerKind === "org" ? "организация" : "личное"}`}
|
||
</dd>
|
||
<dt className="text-muted-foreground">Видимость</dt>
|
||
<dd className="m-0">{repoVisibilityLabel(repo.private)}</dd>
|
||
<dt className="text-muted-foreground">Кто видит</dt>
|
||
<dd className="m-0">{repoAudience(repo)}</dd>
|
||
<dt className="text-muted-foreground">Рабочая копия</dt>
|
||
<dd className="m-0 font-mono text-xs break-all">{p.workspacePath}</dd>
|
||
</dl>
|
||
<div className="flex flex-wrap gap-2">
|
||
<Button asChild size="sm">
|
||
<a href={repo.url}>
|
||
Открыть в Gitea <ExternalLink />
|
||
</a>
|
||
</Button>
|
||
{isOwner && repo.private !== null && (
|
||
<form action={setProjectVisibilityAction}>
|
||
<Hidden fields={{ projectId: p.id, visibility: repo.private ? "public" : "private", back }} />
|
||
<Button size="sm" variant="outline">{repo.private ? "Сделать публичным" : "Сделать приватным"}</Button>
|
||
</form>
|
||
)}
|
||
</div>
|
||
{isOwner && repo.private !== null && (
|
||
<p className="m-0 text-xs text-muted-foreground">
|
||
{repo.private ? "Публичный репозиторий видят все, у кого есть доступ к Gitea." : "Приватный репозиторий видят только владелец пространства, соавторы и peppa-bot."} Видимость меняется в Gitea сразу.
|
||
</p>
|
||
)}
|
||
</PanelSection>
|
||
|
||
<PanelSection title="Автономность">
|
||
<AutonomyPanel projectId={p.id} settings={autonomy} back={back} />
|
||
</PanelSection>
|
||
|
||
<PanelSection title="Раннеры">
|
||
<RunnerSettingsPanel projectId={p.id} own={runnerOwn} inherited={{ ...DEFAULT_RUNNER_SETTINGS, ...runnerSystem }} back={back} hosts={runnerHosts} />
|
||
</PanelSection>
|
||
|
||
<PanelSection title="Модель агента">
|
||
<AgentModelPanel projectId={p.id} own={agentOwn} inherited={{ ...DEFAULT_AGENT_SETTINGS, ...agentSystem }} back={back} />
|
||
</PanelSection>
|
||
|
||
<PanelSection title="Эпики" count={epics.length}>
|
||
<EpicsPanel projectId={p.id} projectKey={p.key} epics={epics} progress={progress} back={back} />
|
||
</PanelSection>
|
||
|
||
<PanelSection title="Секреты" count={secrets.length}>
|
||
<ProjectSecretsPanel projectId={p.id} secrets={secrets} back={back} />
|
||
</PanelSection>
|
||
|
||
<PanelSection title="Бюджет стори">
|
||
<ProjectBudgetPanel projectId={p.id} budget={projectBudget} back={back} action={saveProjectBudgetAction} />
|
||
</PanelSection>
|
||
|
||
<PanelSection title="Продакт и аналитик">
|
||
<form action={saveIntakeSettingsAction} className="flex flex-col gap-2.5">
|
||
<Hidden fields={{ projectId: p.id, back }} />
|
||
<label className="flex items-center gap-2 text-sm">
|
||
<input type="checkbox" name="enabled" defaultChecked={intake.enabled} className="size-4 accent-primary" />
|
||
Новые стори сначала уточняют продакт и аналитик
|
||
</label>
|
||
<label className="flex items-center gap-2 text-sm">
|
||
Ждать ответа на вопросы, минут
|
||
<Input type="number" name="waitMin" min={0} max={1440} defaultValue={intake.waitMin} aria-label="Сколько минут аналитик ждёт ответа" className="h-8 w-20" />
|
||
</label>
|
||
<Button size="sm" className="self-start">Сохранить</Button>
|
||
</form>
|
||
<p className="m-0 text-xs text-muted-foreground">
|
||
Продакт решает, зачем это и что берём в первую версию; аналитик пишет критерии приёмки и задаёт до трёх вопросов. Не ответили вовремя — идёт по вариантам по умолчанию (ночью ждёт до утра). Стори, созданные
|
||
до включения, не трогает.
|
||
</p>
|
||
</PanelSection>
|
||
|
||
<PanelSection title="Ревьюер">
|
||
<form action={saveReviewSettingsAction} className="flex flex-col gap-2.5">
|
||
<Hidden fields={{ projectId: p.id, back }} />
|
||
<label className="flex items-center gap-2 text-sm">
|
||
<input type="checkbox" name="enabled" defaultChecked={reviewer.enabled} className="size-4 accent-primary" />
|
||
Агент-ревьюер читает дифф до ревью PM
|
||
</label>
|
||
<label className="flex items-center gap-2 text-sm">
|
||
Возвратов агенту не больше
|
||
<Input type="number" name="maxIterations" min={1} max={10} defaultValue={reviewer.maxIterations} aria-label="Лимит итераций ревьюера" className="h-8 w-20" />
|
||
</label>
|
||
<Textarea
|
||
name="rules"
|
||
rows={3}
|
||
defaultValue={reviewer.rules ?? ""}
|
||
aria-label="Дополнительные правила ревьюера"
|
||
placeholder="Дополнительные правила ревьюера: например, «новые эндпоинты — только с проверкой доступа», «без новых зависимостей»"
|
||
/>
|
||
<Button size="sm" className="self-start">Сохранить</Button>
|
||
</form>
|
||
<p className="m-0 text-xs text-muted-foreground">
|
||
Когда проверки PR зелёные и агент отдаёт стори в ревью, короткая сессия Claude (sonnet, на подписке пула проекта) читает дифф по чек-листу. Замечания уходят агенту, «ок» — стори к вам с резюме ревьюера. После лимита возвратов стори приходит к вам с незакрытыми замечаниями.
|
||
</p>
|
||
</PanelSection>
|
||
|
||
<PanelSection title="Баги">
|
||
<IncidentSettingsPanel
|
||
projectId={p.id}
|
||
back={back}
|
||
isOwner={isOwner}
|
||
settings={incidentSettings}
|
||
sources={sources}
|
||
webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null}
|
||
/>
|
||
</PanelSection>
|
||
|
||
<PanelSection title="Участники" count={team.members.length + 1}>
|
||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||
<li className="flex flex-col rounded-md px-2 py-1.5">
|
||
<span className="font-medium">{team.owner?.login ?? "—"}</span>
|
||
<span className="text-xs text-muted-foreground">владелец</span>
|
||
</li>
|
||
{team.members.map((m) => (
|
||
<li key={m.id} className="flex items-center gap-2 rounded-md px-2 py-1.5">
|
||
<span className="flex min-w-0 flex-1 flex-col">
|
||
<span>{m.login}</span>
|
||
<span className="text-xs text-muted-foreground">участник{noRepoAccess(m.login) && " · нет доступа к репозиторию"}</span>
|
||
</span>
|
||
{(isOwner || m.id === user.id) && (
|
||
<form action={removeProjectMember}>
|
||
<Hidden fields={{ projectId: p.id, login: m.login, back }} />
|
||
<Button size="xs" variant="destructive">{m.id === user.id ? "Выйти из проекта" : "Убрать"}</Button>
|
||
</form>
|
||
)}
|
||
</li>
|
||
))}
|
||
{team.invites.map((login) => (
|
||
<li key={login} className="flex items-center gap-2 rounded-md px-2 py-1.5">
|
||
<span className="flex min-w-0 flex-1 flex-col">
|
||
<span>{login}</span>
|
||
<span className="text-xs text-muted-foreground">приглашён · появится после первого входа в Пеппу</span>
|
||
</span>
|
||
{isOwner && (
|
||
<form action={removeProjectMember}>
|
||
<Hidden fields={{ projectId: p.id, login, back }} />
|
||
<Button size="xs" variant="destructive">Отозвать</Button>
|
||
</form>
|
||
)}
|
||
</li>
|
||
))}
|
||
</ul>
|
||
{isOwner && (
|
||
<form action={addProjectMember} className="flex gap-2">
|
||
<Hidden fields={{ projectId: p.id, back }} />
|
||
<Input name="login" required placeholder="Логин в Gitea" aria-label="Логин участника в Gitea" className="h-8" />
|
||
<Button size="sm">Добавить участника</Button>
|
||
</form>
|
||
)}
|
||
{isOwner && missingAccess && (
|
||
<form action={grantRepoAccessToMembers}>
|
||
<Hidden fields={{ projectId: p.id, back }} />
|
||
<Button size="sm">Выдать доступ участникам</Button>
|
||
</form>
|
||
)}
|
||
{isOwner && <p className="m-0 text-xs text-muted-foreground">Участник видит доску и входящие, двигает карточки и отвечает агентам; получает доступ на запись к репозиторию.</p>}
|
||
</PanelSection>
|
||
|
||
<PanelSection title="Подписки">
|
||
<p className="m-0 text-sm" id="subscription">
|
||
{pool ? (
|
||
<>Агенты работают на пуле «{pool.name}»{shared?.id === pool.id ? " — общая подписка Пеппы" : ""}.</>
|
||
) : agentWarning ? (
|
||
<b>Подписка не выбрана — агенты не запустятся.</b>
|
||
) : (
|
||
"Пул не назначен — агенты работают на входе машины."
|
||
)}
|
||
</p>
|
||
{(isOwner || superadmin) && (
|
||
<>
|
||
{shared && shared.id !== pool?.id && (
|
||
<form action={chooseSharedSubscriptionAction}>
|
||
<Hidden fields={{ projectId: p.id, back }} />
|
||
<Button size="sm" variant={pool ? "outline" : "default"}>Общая подписка Пеппы</Button>
|
||
</form>
|
||
)}
|
||
<form action={connectOwnSubscriptionAction} className="flex flex-col gap-2">
|
||
<Hidden fields={{ projectId: p.id, back }} />
|
||
<NativeSelect name="kind" defaultValue="claude_login" aria-label="Что подключить" className="h-8">
|
||
<option value="claude_login">Claude — вход по ссылке</option>
|
||
<option value="codex_login">ChatGPT — вход по ссылке и коду</option>
|
||
<option value="claude">Claude — готовый токен (claude setup-token)</option>
|
||
<option value="codex_key">Codex — ключ OpenAI API</option>
|
||
{hasOwnPool && <option value="existing">Моя уже подключённая подписка</option>}
|
||
</NativeSelect>
|
||
<Input name="secret" type="password" autoComplete="off" placeholder="Токен Claude или ключ OpenAI (для входа по ссылке не нужен)" aria-label="Токен или ключ своей подписки" className="h-8 font-mono" />
|
||
<Button size="sm" variant={pool ? "outline" : "default"} className="self-start">Подключить свою подписку</Button>
|
||
<span className="text-xs text-muted-foreground">
|
||
Вход по ссылке: поле оставьте пустым — на странице проекта появятся шаги. Готовый токен Claude выдаёт <span className="font-mono">claude setup-token</span> на вашем компьютере. Токены и ключи
|
||
хранятся зашифрованными, показать их нельзя.
|
||
</span>
|
||
</form>
|
||
</>
|
||
)}
|
||
{superadmin && (
|
||
<form action={setProjectPoolAction} className="flex gap-2">
|
||
<Hidden fields={{ projectKey: p.key, back }} />
|
||
<NativeSelect name="poolId" defaultValue={pool?.id ?? ""} aria-label="Пул подписок по умолчанию" className="h-8">
|
||
<option value="">Без пула — вход машины</option>
|
||
{pools.map((x) => (
|
||
<option key={x.id} value={x.id}>{x.name}</option>
|
||
))}
|
||
</NativeSelect>
|
||
<Button size="sm">Сохранить</Button>
|
||
</form>
|
||
)}
|
||
<p className="m-0 text-xs text-muted-foreground">Раннеры проекта стартуют на свободной подписке пула. {superadmin ? <a href="/subscriptions#pools" className="text-primary">Пулы и подписки</a> : "Выбирает владелец проекта."}</p>
|
||
</PanelSection>
|
||
</div>
|
||
);
|
||
|
||
const newTask = (
|
||
<form action={addTask} className="flex flex-col gap-2">
|
||
<Hidden fields={{ projectId: p.id, back }} />
|
||
<Input name="title" required placeholder="Что сделать" aria-label="Название стори" />
|
||
<Textarea name="description" rows={5} placeholder="Описание: кому и зачем, критерии готовности" aria-label="Описание стори" />
|
||
<NativeSelect name="epicId" defaultValue={epicFilter ? String(epicFilter.id) : ""} aria-label="Эпик">
|
||
<option value="">Без эпика</option>
|
||
{epics.map((e) => (
|
||
<option key={e.id} value={e.id}>
|
||
{e.title}
|
||
</option>
|
||
))}
|
||
</NativeSelect>
|
||
<Button variant="default" size="sm" className="self-start">Создать стори</Button>
|
||
</form>
|
||
);
|
||
const tabCount: Partial<Record<(typeof TABS)[number]["id"], number>> = { board: tasks.length, epics: epics.length, bugs: incidents.length, sessions: sessions.length };
|
||
|
||
return (
|
||
<Workspace aside={null} wide>
|
||
<LiveRefresh scope={`project:${p.id}`} />
|
||
<Flash error={error} />
|
||
{created && !error && (
|
||
<Notice>
|
||
Репозиторий создан: <a href={repo.url} className="text-primary">{repo.fullName}</a> ({repoVisibilityLabel(repo.private)}).
|
||
<Button asChild size="xs">
|
||
<a href={repo.url}>Открыть в Gitea</a>
|
||
</Button>
|
||
</Notice>
|
||
)}
|
||
<PageHeader
|
||
actions={
|
||
<>
|
||
<SettingsDialog title="Новая стори" trigger={<><Plus />Стори</>}>
|
||
{newTask}
|
||
</SettingsDialog>
|
||
<SettingsDialog title="Настройки проекта">{aside}</SettingsDialog>
|
||
</>
|
||
}
|
||
crumbs={<a href="/projects" className="text-muted-foreground hover:text-foreground">Проекты</a>}
|
||
title={
|
||
<>
|
||
<span className="rounded-md bg-muted px-2 font-mono text-primary">{p.key}</span> {p.name}
|
||
</>
|
||
}
|
||
>
|
||
<a href={repo.url} className="text-primary">{repo.fullName}</a> · {repoVisibilityLabel(repo.private)}
|
||
</PageHeader>
|
||
|
||
{mayChoose && (ownLogins.length > 0 || (!pool && agentWarning)) && <SubscriptionSetup projectId={p.id} back={back} logins={ownLogins} />}
|
||
{agentWarning && !(mayChoose && (ownLogins.length > 0 || !pool)) && (
|
||
<p role="alert" className="mb-4 flex flex-wrap items-center gap-2 rounded-lg border border-warn/40 bg-warn/10 px-4 py-3 text-sm">
|
||
<span className="font-medium">Агенты не запустятся:</span> {agentWarning}.
|
||
{pool ? (superadmin ? <a href="/subscriptions" className="text-primary">Подписки →</a> : <span className="text-muted-foreground">Смените подписку в «⋯ Настройки проекта → Подписки» или попросите суперадмина проверить её.</span>) : null}
|
||
</p>
|
||
)}
|
||
|
||
<nav aria-label="Разделы проекта" className="-mt-2 mb-4 flex gap-1 overflow-x-auto border-b">
|
||
{TABS.map((t) => (
|
||
<a
|
||
key={t.id}
|
||
href={t.id === "board" ? `/p/${p.key}` : `/p/${p.key}?tab=${t.id}`}
|
||
aria-current={tab === t.id ? "page" : undefined}
|
||
className={cn(
|
||
"-mb-px flex items-center gap-1.5 border-b-2 px-3 py-2 text-sm whitespace-nowrap text-muted-foreground hover:text-foreground hover:no-underline",
|
||
tab === t.id ? "border-primary text-foreground" : "border-transparent",
|
||
)}
|
||
>
|
||
{t.label}
|
||
{!!tabCount[t.id] && <span className="rounded-full bg-muted px-1.5 font-mono text-[11px] tabular-nums">{tabCount[t.id]}</span>}
|
||
</a>
|
||
))}
|
||
</nav>
|
||
|
||
{tab === "board" && (
|
||
<>
|
||
{epics.length > 0 && (
|
||
<nav aria-label="Фильтр по эпику" className="mb-3 flex flex-wrap items-center gap-1.5 text-sm">
|
||
<a href={`/p/${p.key}?tab=epics`} className="text-xs text-muted-foreground" title="Эпик — большая цель; карточки на доске — стори, шаги к ней">Эпики:</a>
|
||
{[{ id: 0, title: "все" }, ...epics].map((e) => {
|
||
const active = (epicFilter?.id ?? 0) === e.id;
|
||
return (
|
||
<a
|
||
key={e.id}
|
||
href={boardHref(e.id || undefined)}
|
||
aria-current={active ? "page" : undefined}
|
||
className={cn("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs hover:no-underline", active ? "border-primary bg-primary/12 text-primary" : "text-muted-foreground hover:text-foreground")}
|
||
>
|
||
{e.title}
|
||
{e.id > 0 && (
|
||
<span className="ml-1.5 inline-flex items-center gap-1 font-mono text-[10px] tabular-nums" title={`Готово ${progressLabel(progress.get(e.id))}`}>
|
||
<ProgressBar done={progress.get(e.id)?.done ?? 0} total={progress.get(e.id)?.total ?? 0} className="w-8" />
|
||
{progressLabel(progress.get(e.id))}
|
||
</span>
|
||
)}
|
||
</a>
|
||
);
|
||
})}
|
||
{epicFilter && (
|
||
<a href={`/p/${p.key}/plan/${epicFilter.id}`} className="ml-auto text-xs text-primary">
|
||
Спланировать стори эпика →
|
||
</a>
|
||
)}
|
||
</nav>
|
||
)}
|
||
<Board cards={cards} back={back} />
|
||
</>
|
||
)}
|
||
|
||
{tab === "epics" && (
|
||
<EpicsTab
|
||
projectId={p.id}
|
||
projectKey={p.key}
|
||
epics={epics}
|
||
stories={tasks.map((t) => ({ key: `${p.key}-${t.number}`, title: t.title, status: t.status, goalId: t.goalId }))}
|
||
progress={progress}
|
||
back={back}
|
||
/>
|
||
)}
|
||
|
||
{tab === "code" && code && <CodeTab code={code} />}
|
||
|
||
{tab === "specs" && (
|
||
<>
|
||
<MemorySection text={memory} {...memoryStats(memory)} />
|
||
<SpecsTab specs={specs} />
|
||
</>
|
||
)}
|
||
|
||
{tab === "agents" && agentsMd && <AgentsMdTab projectId={p.id} projectKey={p.key} md={agentsMd} edit={edit === "1"} saved={saved === "1"} />}
|
||
|
||
{tab === "pulls" && pulls && <PullsTab pulls={pulls.pulls} error={pulls.error} repoUrl={repo.url} />}
|
||
|
||
{tab === "releases" && (
|
||
<Section title="Релизы">
|
||
<div className="flex flex-col gap-2 sm:flex-row">
|
||
<EnvLine name="staging" r={current.staging} />
|
||
<EnvLine name="прод" r={current.prod} />
|
||
</div>
|
||
{prodCandidate && prodCandidate !== current.prod?.sha && (
|
||
<form action={deployProdAction}>
|
||
<Hidden fields={{ projectKey: p.key, back }} />
|
||
<Button variant="default" size="sm">
|
||
<Rocket />
|
||
Выкатить в прод {prodCandidate.slice(0, 7)}
|
||
</Button>
|
||
</form>
|
||
)}
|
||
{releases.length === 0 ? (
|
||
<Empty>
|
||
Деплоев ещё не было. Настройка — <span className="font-mono">deploy</span> в .peppa/project.json (см. «Помощь → CI/CD»).
|
||
</Empty>
|
||
) : (
|
||
<div className="overflow-x-auto rounded-lg border">
|
||
<table className="w-full border-collapse text-sm">
|
||
<tbody>
|
||
{releases.map((r) => (
|
||
<tr key={r.id} className="border-b last:border-0">
|
||
<td className="px-3 py-2 whitespace-nowrap">
|
||
{r.env}
|
||
{r.prNumber ? ` #${r.prNumber}` : ""}
|
||
</td>
|
||
<td className="px-3 py-2 font-mono">{r.sha.slice(0, 7)}</td>
|
||
<td className="px-3 py-2">
|
||
<Badge variant={RELEASE_STATUS[r.status].tone}>{RELEASE_STATUS[r.status].label}</Badge>
|
||
{r.reason && <span className="ml-1.5 text-muted-foreground">{r.reason}</span>}
|
||
</td>
|
||
<td className="px-3 py-2">
|
||
{r.tasks.map((t) => (
|
||
<Key key={t} href={`/t/${t}`} className="mr-1.5">{t}</Key>
|
||
))}
|
||
</td>
|
||
<td className="px-3 py-2 text-right whitespace-nowrap text-muted-foreground">
|
||
{r.deployedBy} · {r.createdAt.toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" })}
|
||
</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
)}
|
||
</Section>
|
||
)}
|
||
|
||
{tab === "bugs" && (
|
||
<IncidentsSection projectId={p.id} back={back} settings={incidentSettings} incidents={incidents} taskKeys={new Map(tasks.map((t) => [t.id, `${p.key}-${t.number}`]))} />
|
||
)}
|
||
|
||
{tab === "metrics" && metrics && <MetricsTab m={metrics} projectKey={p.key} />}
|
||
|
||
{tab === "journal" && (
|
||
<Section title="Журнал действий" actions={<JournalFilters action={`/p/${p.key}`} value={{ tab: "journal", actor, channel }} />}>
|
||
<JournalList entries={journal} showProject={false} />
|
||
</Section>
|
||
)}
|
||
|
||
{tab === "sessions" && (
|
||
<Section
|
||
title="Сессии"
|
||
actions={
|
||
<SettingsDialog title="Новый терминал" trigger={<><SquareTerminal />Новый терминал</>}>
|
||
<NewRunnerForm projectId={p.id} back={back} />
|
||
</SettingsDialog>
|
||
}
|
||
>
|
||
{sessions.length === 0 ? <Empty>Сессий ещё не было.</Empty> : sessions.map((s) => <SessionCard key={s.id} s={s} back={back} showTitle />)}
|
||
</Section>
|
||
)}
|
||
</Workspace>
|
||
);
|
||
}
|