peppa/apps/web/app/(app)/p/[key]/page.tsx
peppa-bot 43d78dd060
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 47с
peppa/build build: success за 34с
peppa/test test: success за 1378с
peppa-ci / ci (pull_request) Successful in 25m18s
PEP-275: «Попросить подписку у администратора» на странице проекта
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 16:02:15 +00:00

808 lines
51 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.

import Link from "next/link";
import { Fragment } from "react";
import { ProductCard } from "@/components/ProductCard";
import { PublishPanel } from "@/components/PublishPanel";
import { notFound } from "next/navigation";
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
import { columnOf, currentReleases, peekRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release, sharedRequest, subscriptionRequestOffer } from "@peppa/runner";
import { getProjectPause, getPublishMode, poolSubscriptions, PRODUCT_PROJECT_TABS, userProjectIds, projectProduct, discussionUnread, ensureProjectChat, listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, agentSecretsEnabled, secretsAgentReport, secretNameHints, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, taskHoldReasons, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { productNeeds, lastProductReview } 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 { AttachField } from "@/components/AttachField";
import { Dictate } from "@/components/Dictate";
import { Empty, Flash, Key, Notice, PageHeader, Section } from "@/components/common";
import { IncidentSettingsPanel, IncidentsSection } from "@/components/Incidents";
import { ProjectErrors, type ErrorSearch } from "@/components/ProjectErrors";
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 { PauseBanner, PauseControl } from "@/components/ProjectPause";
import { ProjectSecretsPanel } from "@/components/ProjectSecrets";
import { Workspace } from "@/components/Workspace";
import { SubscriptionSetup } from "@/components/SubscriptionSetup";
import { SubscriptionRequestButton } from "@/components/SubscriptionRequest";
import { PoolSubscriptions, PoolSummary, PoolSwitches } from "@/components/PoolSubscriptions";
import { requireUser, words } from "@/lib/auth";
import { cn } from "@/lib/utils";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
import { intlLocale, m, type Translator } from "@peppa/shared/i18n";
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, saveReviewSettingsAction, saveIntakeSettingsAction, setProjectVisibilityAction, connectOwnSubscriptionAction, chooseSharedSubscriptionAction, removeOwnSubscriptionAction } 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";
// PEP-127: on its own line — the long @peppa/core import above is edited by every story.
import { delayedTaskIds, taskDelayLine, pendingQuestions, listPendingAccepts, PENDING_ACCEPT_LABEL, PLATFORM_DELAY_LABEL } from "@peppa/core";
import { trashDaysLeft } from "@peppa/core";
import { queuePositions, workLine } from "@peppa/core";
import { WorkLine } from "@/components/WorkLine";
import { deleteProjectAction } from "../../actions";
import { DeleteProjectControl, mayDeleteProject, RestoreProjectButton } from "@/components/ProjectDelete";
const RELEASE_STATUS: Record<Release["status"], { label: string; tone: "info" | "ok" | "warn" | "danger" | "muted" }> = {
deploying: { label: m("выкатывается"), tone: "info" },
healthy: { label: m("работает"), tone: "ok" },
rolled_back: { label: m("откат"), tone: "warn" },
failed: { label: m("не поднялся"), tone: "danger" },
removed: { label: m("удалён"), tone: "muted" },
};
const TABS = [
{ id: "board", label: m("Доска") },
{ id: "epics", label: m("Эпики") },
{ id: "code", label: m("Код") },
{ id: "specs", label: m("Спеки") },
{ id: "agents", label: "AGENTS.md" },
{ id: "pulls", label: "PR" },
{ id: "releases", label: m("Релизы") },
{ id: "bugs", label: m("Баги") },
{ id: "sessions", label: m("Сессии") },
{ id: "metrics", label: m("Метрики") },
{ id: "journal", label: m("Журнал") },
] as const;
function EnvLine({ name, r, t }: { name: string; r: Release | null | undefined; t: Translator }) {
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">{t("нет")}</span>
)}
</div>
);
}
export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string; checked?: string; tab?: string; epic?: string; weeks?: string; actor?: string; channel?: string; edit?: string; saved?: string } & ErrorSearch> }) {
const user = await requireUser();
const { key } = await params;
const sp = await searchParams;
const { error, created, checked, tab: tabParam, epic: epicParam, weeks, actor, channel, edit, saved } = sp;
const t = await getT();
// PEP-119: «Продакт» sees the board, epics and bugs; the developer's tabs belong to «Инженер».
const w = await words();
const engineer = w.engineer;
const visibleTabs = engineer ? TABS : TABS.filter((x) => (PRODUCT_PROJECT_TABS as readonly string[]).includes(x.id));
const tab = visibleTabs.find((x) => x.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),
Promise.resolve(peekRepo(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-253: where secrets go and which of them are keys of catalog services.
const [agentSecrets, secretReport] = await Promise.all([agentSecretsEnabled(db, p.id), secretsAgentReport(db, { projectIds: [p.id] })]);
// 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-174: the project on pause — a plaque on top, «Продолжить» instead of «Поставить на паузу».
const pause = await getProjectPause(db, p.id);
// PEP-107: each subscription of the pool — at work, free, limited until…, usage of its window.
const poolView = pool ? await poolOverview(db, pool.id, new Date(), { admin: superadmin, userId: user.id }) : null;
// PEP-80: the owner's own subscriptions — a ChatGPT device login in progress, and whether a pool exists already.
const mayChoose = isOwner || superadmin;
// PEP-128: a pool whose every sign-in failed or is unfinished is as good as no subscription —
// the owner gets the connection wizard again, with what went wrong.
const poolSubs = pool ? await poolSubscriptions(db, pool.id) : [];
const connected = poolSubs.some((s) => s.status === "active" || s.status === "limited");
const failedLogins = poolSubs.filter((s) => s.status === "auth_error").map((s) => ({ provider: s.provider, timedOut: /timed out/i.test(s.lastError ?? "") }));
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 accepted = await listPendingAccepts(db);
// PEP-150: the delay line — not on a story whose question waits for the owner.
// PEP-209: the acceptance page — every story in review on one screen.
const toAccept = tasks.filter((x) => x.status === "review" && !x.archivedAt).length;
const delayed = await delayedTaskIds(db);
if (delayed.size) for (const q of await pendingQuestions(db, p.id)) if (q.taskId != null) delayed.delete(q.taskId);
// PEP-209: the card says when the next attempt comes (or that the administrator is told).
const delayLines = new Map<number, string>();
for (const id of delayed) {
const line = await taskDelayLine(db, id);
if (line) delayLines.set(id, line);
}
// PEP-182: stories waiting for a free agent, and «Делается · В очереди» above the board.
const [queued, work] = tab === "board" ? await Promise.all([queuePositions(db, p.id), workLine(db, [p.id])]) : [new Map<number, number>(), null];
const [intake, refining] = await Promise.all([getIntakeSettings(db, p.id), intakePendingTasks(db, p.id)]);
// PEP-247: in work without an agent for a lawful reason (pause, no subscription, budget) — the card says why.
const holds = tab === "board" ? await taskHoldReasons(db, p.id, tasks.filter((x) => x.status === "in_progress" && !agentNames.has(x.id) && !delayed.has(x.id) && !queued.has(x.id)).map((x) => x.id)) : new Map();
const cards: Card[] = tasks
.filter((x) => !epicFilter || x.goalId === epicFilter.id)
.map((x) => {
const pr = columnOf(x.status) === "in_progress" ? taskProgress(p, x.openspecChange) : null;
return {
key: `${p.key}-${x.number}`,
id: x.id,
title: x.title,
status: x.status,
column: columnOf(x.status),
epic: x.goalId ? (epicTitle.get(x.goalId) ?? null) : null,
// PEP-33: tasks.md progress of stories in work.
progress: pr && { done: pr.done, total: pr.total, current: pr.current },
blocked: x.status === "backlog" ? blockedLabel(deps.get(x.id)) : null,
agent: agentNames.get(x.id) ?? null,
accepted: accepted.has(x.id) ? t.text(PENDING_ACCEPT_LABEL) : null,
delayed: delayed.has(x.id) && x.status !== "done" ? t.text(delayLines.get(x.id) ?? PLATFORM_DELAY_LABEL) : null,
queued: queued.get(x.id) ?? null,
hold: holds.has(x.id) ? t.text(holds.get(x.id)!.text) : null,
proposed: x.proposed,
severity: (x.severity as Card["severity"]) ?? null,
agentMade: x.origin !== "human",
refining: refining.has(x.id) ? (refining.get(x.id) === "waiting" ? t("ждёт ваших ответов") : t("уточняется")) : 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 product = await projectProduct(db, p.id);
const publish = await getPublishMode(db, p.id);
const [productNeedList, productReview] = await Promise.all([productNeeds(db, p.id), lastProductReview(db, p.id)]);
// The chat belongs to the project's people; a superadmin looking at someone else's project has none.
const canChat = (await userProjectIds(db, user.id)).includes(p.id);
const sharedReq = await sharedRequest(db, p.id);
// PEP-186: agents stand on a limit or a broken sign-in — ask the superadmin for a subscription.
const askOffer = await subscriptionRequestOffer(db, user, p.id).catch(() => null);
// PEP-206: «Подписки» offers the request always (ahead of a limit, too).
const askAhead = askOffer ? null : await subscriptionRequestOffer(db, user, p.id, new Date(), { always: true }).catch(() => null);
const discussionNew = (await discussionUnread(db, user.id)).get((await ensureProjectChat(db, p.id)).id) ?? 0;
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={t("Пауза")}>
<p className="m-0 mb-2 text-xs text-muted-foreground">
{pause ? t("Проект на паузе: агенты не работают, уведомлений нет.") : t("На паузе агенты не работают, а вы не получаете уведомлений по проекту.")}
</p>
<PauseControl projectId={p.id} back={back} paused={!!pause} />
</PanelSection>
{engineer && (
<PanelSection title={t("Репозиторий")}>
<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 truncate">
<a href={repo.url} className="text-primary">{repo.fullName}</a>
</dd>
<dt className="text-muted-foreground">{t("Пространство")}</dt>
<dd className="m-0">
{p.giteaOwner}
{repo.ownerKind && <> — {repo.ownerKind === "org" ? t("организация") : t("личное")}</>}
</dd>
<dt className="text-muted-foreground">{t("Видимость")}</dt>
<dd className="m-0">{t.text(repoVisibilityLabel(repo.private))}</dd>
<dt className="text-muted-foreground">{t("Кто видит")}</dt>
<dd className="m-0">{t.text(repoAudience(repo))}</dd>
<dt className="text-muted-foreground">{t("Рабочая копия")}</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}>
{t("Открыть в 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 ? t("Сделать публичным") : t("Сделать приватным")}</Button>
</form>
)}
</div>
{isOwner && repo.private !== null && (
<p className="m-0 text-xs text-muted-foreground">
{repo.private ? t("Публичный репозиторий видят все, у кого есть доступ к Gitea.") : t("Приватный репозиторий видят только владелец пространства, соавторы и peppa-bot.")} {t("Видимость меняется в Gitea сразу.")}
</p>
)}
</PanelSection>
)}
<PanelSection title={t("Автономность")}>
<AutonomyPanel projectId={p.id} settings={autonomy} back={back} engineer={engineer} />
</PanelSection>
<PanelSection title={t("Показывать всем")}>
<PublishPanel projectId={p.id} mode={publish} back={back} />
</PanelSection>
{engineer && (
<PanelSection title={t("Раннеры")}>
<RunnerSettingsPanel projectId={p.id} own={runnerOwn} inherited={{ ...DEFAULT_RUNNER_SETTINGS, ...runnerSystem }} back={back} hosts={runnerHosts} />
</PanelSection>
)}
{/* glossary-ignore: раздел виден только в виде «Инженер» */}
{engineer && (
<PanelSection title={t("Модель агента")}>
<AgentModelPanel projectId={p.id} own={agentOwn} inherited={{ ...DEFAULT_AGENT_SETTINGS, ...agentSystem }} back={back} />
</PanelSection>
)}
<PanelSection title={t("Эпики")} count={epics.length}>
<EpicsPanel w={w} projectId={p.id} projectKey={p.key} epics={epics} progress={progress} back={back} />
</PanelSection>
<PanelSection title={t("Секреты")} count={secrets.length}>
<ProjectSecretsPanel
projectId={p.id}
secrets={secrets}
back={back}
agentsEnabled={agentSecrets}
services={new Map(secretReport.map((r) => [r.name, { serviceName: r.serviceName, connectionName: r.connectionName }]))}
hints={secretNameHints()}
engineer={engineer}
/>
</PanelSection>
{engineer && (
<PanelSection title={t("Бюджет стори")}>
<ProjectBudgetPanel projectId={p.id} budget={projectBudget} back={back} action={saveProjectBudgetAction} />
</PanelSection>
)}
<PanelSection title={t("Аналитик на входе задачи")}>
<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" />
{t("Новые {tasks} сначала разбирает аналитик", { tasks: w.task("accPl") })}
</label>
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
</form>
<p className="m-0 text-xs text-muted-foreground">
{t("Аналитик решает, зачем это и что берём в первую версию, делит большое (не больше четырёх частей) и пишет критерии приёмки. Вопросов не задаёт: развилки решает сам и показывает решения на странице задачи — «Фабрика решила за вас». {Tasks}, созданные до включения, не трогает.", { Tasks: w.Task("pl") })}
</p>
</PanelSection>
{engineer && (
<PanelSection title={t("Ревьюер")}>
<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" />
{t("Агент-ревьюер читает дифф до ревью PM")}
</label>
<label className="flex items-center gap-2 text-sm">
{t("Возвратов агенту не больше")}
<Input type="number" name="maxIterations" min={1} max={10} defaultValue={reviewer.maxIterations} aria-label={t("Лимит итераций ревьюера")} className="h-8 w-20" />
</label>
<Textarea
name="rules"
rows={3}
defaultValue={reviewer.rules ?? ""}
aria-label={t("Дополнительные правила ревьюера")}
placeholder={t("Дополнительные правила ревьюера: например, «новые эндпоинты — только с проверкой доступа», «без новых зависимостей»")}
/>
<Button size="sm" className="self-start">{t("Сохранить")}</Button>
</form>
<p className="m-0 text-xs text-muted-foreground">
{t("Когда проверки PR зелёные и агент отдаёт стори в ревью, короткая сессия Claude (sonnet, на подписке пула проекта) читает дифф по чек-листу. Замечания уходят агенту, «ок» — стори к вам с резюме ревьюера. После лимита возвратов стори приходит к вам с незакрытыми замечаниями.")}
</p>
</PanelSection>
)}
<PanelSection title={t("Баги")}>
<IncidentSettingsPanel
w={w}
projectId={p.id}
back={back}
isOwner={isOwner}
settings={incidentSettings}
sources={sources}
webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null}
/>
</PanelSection>
<PanelSection title={t("Участники")} 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">{t("владелец")}</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">{t("участник")}{engineer && noRepoAccess(m.login) && " · " + t("нет доступа к репозиторию")}</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 ? t("Выйти из проекта") : t("Убрать")}</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">{t("приглашён · появится после первого входа в FORGE")}</span>
</span>
{isOwner && (
<form action={removeProjectMember}>
<Hidden fields={{ projectId: p.id, login, back }} />
<Button size="xs" variant="destructive">{t("Отозвать")}</Button>
</form>
)}
</li>
))}
</ul>
{isOwner && (
<form action={addProjectMember} className="flex gap-2">
<Hidden fields={{ projectId: p.id, back }} />
<Input name="login" required placeholder={engineer ? t("Логин в Gitea") : t("Логин участника")} aria-label={engineer ? t("Логин участника в Gitea") : t("Логин участника")} className="h-8" />
<Button size="sm">{t("Добавить участника")}</Button>
</form>
)}
{engineer && isOwner && missingAccess && (
<form action={grantRepoAccessToMembers}>
<Hidden fields={{ projectId: p.id, back }} />
<Button size="sm">{t("Выдать доступ участникам")}</Button>
</form>
)}
{isOwner && <p className="m-0 text-xs text-muted-foreground">{engineer ? t("Участник видит доску и входящие, двигает карточки и отвечает агентам; получает доступ на запись к репозиторию.") : t("Участник видит доску и входящие, двигает карточки и отвечает агентам.")}</p>}
</PanelSection>
<PanelSection title={t("Подписки")}>
<p className="m-0 text-sm" id="subscription">
{pool ? (
shared?.id === pool.id ? (
<>
{t("Агенты работают на")} <b>{t("подписке FORGE")}</b> {t("— общей для пользователей фабрики. Свою подписку можно подключить в любой момент ниже.")}
</>
) : (
<>{superadmin ? t("Агенты работают на подписке проекта — пул «{name}».", { name: pool.name }) : t("Агенты работают на подписке проекта.")}</>
)
) : agentWarning ? (
<b>{t("Подписка не выбрана — агенты не запустятся.")}</b>
) : (
engineer ? t("Пул не назначен — агенты работают на входе машины.") : t("Своя подписка не подключена — агенты работают на общей.")
)}
</p>
{askOffer && (
<div className="flex flex-wrap items-center gap-2 text-sm">
<span>{t("Агенты стоят — администратор может одолжить свою подписку на время.")}</span>
<SubscriptionRequestButton projectId={p.id} offer={askOffer} back={`${back}#subscription`} />
</div>
)}
{askAhead && (
<div className="flex flex-wrap items-center gap-2 text-sm" data-subscription-ahead>
<span>{t("Нужна ещё подписка? Администратор может одолжить свою на время.")}</span>
<SubscriptionRequestButton projectId={p.id} offer={askAhead} back={`${back}#subscription`} ahead />
</div>
)}
{/* PEP-116: on the factory's subscription a user sees its state, not the accounts behind it. */}
{poolView && (superadmin || poolView.pool.id !== shared?.id) && (
<>
<PoolSubscriptions
o={poolView}
action={(s) =>
mayChoose && !s.loan && (s.createdBy === user.id || superadmin) && poolView.pool.id !== shared?.id ? (
<form action={removeOwnSubscriptionAction}>
<Hidden fields={{ projectId: p.id, subscriptionId: s.id, back }} />
<Button size="xs" variant="ghost" className="text-muted-foreground">{t("Убрать")}</Button>
</form>
) : null
}
/>
<PoolSummary o={poolView} />
<PoolSwitches o={poolView} />
</>
)}
{superadmin && pool && pool.id === shared?.id && (
// PEP-164: the factory's pool is filled on «Подписки» — straight to this pool's card.
<a href={`/subscriptions#pool-${pool.id}`} className="self-start text-sm font-medium text-primary">{t("Добавить ещё одну подписку")} →</a>
)}
{mayChoose && pool && pool.id !== shared?.id && (
<div className="flex flex-wrap gap-2" aria-label={t("Добавить подписку")}>
<form action={connectOwnSubscriptionAction}>
<Hidden fields={{ projectId: p.id, kind: "claude_login", back }} />
<Button size="sm" variant="outline">{t("Добавить ещё Claude")}</Button>
</form>
<form action={connectOwnSubscriptionAction}>
<Hidden fields={{ projectId: p.id, kind: "codex_login", back }} />
<Button size="sm" variant="outline">{t("Добавить ещё ChatGPT")}</Button>
</form>
<span className="basis-full text-xs text-muted-foreground">{t("Две и больше подписок — агенты не ждут лимита: упёрлась одна — продолжают на другой, в том числе Claude ↔ ChatGPT.")}</span>
</div>
)}
{(isOwner || superadmin) && (
<>
{shared && shared.id !== pool?.id && (
<form action={chooseSharedSubscriptionAction}>
<Hidden fields={{ projectId: p.id, back }} />
<Button size="sm" variant={pool ? "outline" : "default"} disabled={!!sharedReq && !superadmin}>
{superadmin ? t("Перейти на подписку FORGE") : sharedReq ? t("Запрос на подписку FORGE отправлен") : t("Попросить подписку FORGE")}
</Button>
{!superadmin && <span className="text-xs text-muted-foreground">{sharedReq ? t("Ждём подтверждения администратора фабрики — придёт сообщение.") : t("Нужно подтверждение администратора фабрики.")}</span>}
</form>
)}
{engineer ? (
<form action={connectOwnSubscriptionAction} className="flex flex-col gap-2">
<Hidden fields={{ projectId: p.id, back }} />
<NativeSelect name="kind" defaultValue="claude_login" aria-label={t("Что подключить")} className="h-8">
<option value="claude_login">{t("Claude — вход по ссылке")}</option>
<option value="codex_login">{t("ChatGPT — вход по ссылке и коду")}</option>
<option value="claude">{t("Claude — готовый токен (claude setup-token)")}</option>
<option value="codex_key">{t("Codex — ключ OpenAI API")}</option>
{hasOwnPool && <option value="existing">{t("Моя уже подключённая подписка")}</option>}
</NativeSelect>
<Input name="secret" type="password" autoComplete="off" placeholder={t("Токен Claude или ключ OpenAI (для входа по ссылке не нужен)")} aria-label={t("Токен или ключ своей подписки")} className="h-8 font-mono" />
<Button size="sm" variant={pool ? "outline" : "default"} className="self-start">{t("Подключить свою подписку")}</Button>
<span className="text-xs text-muted-foreground">
{t("Вход по ссылке: поле оставьте пустым — на странице проекта появятся шаги. Готовый токен Claude выдаёт")} <span className="font-mono">claude setup-token</span>{" "}
{t("на вашем компьютере. Токены и ключи хранятся зашифрованными, показать их нельзя.")}
</span>
</form>
) : (
!pool || pool.id === shared?.id ? (
<div className="flex flex-wrap gap-2" aria-label={t("Подключить свою подписку")}>
<form action={connectOwnSubscriptionAction}>
<Hidden fields={{ projectId: p.id, kind: "claude_login", back }} />
<Button size="sm" variant={pool ? "outline" : "default"}>{t("Подключить Claude")}</Button>
</form>
<form action={connectOwnSubscriptionAction}>
<Hidden fields={{ projectId: p.id, kind: "codex_login", back }} />
<Button size="sm" variant="outline">{t("Подключить ChatGPT")}</Button>
</form>
<span className="basis-full text-xs text-muted-foreground">{t("Подойдёт обычная платная подписка. После нажатия на странице проекта появятся шаги — это одна минута.")}</span>
</div>
) : null
)}
</>
)}
{superadmin && (
<form action={setProjectPoolAction} className="flex gap-2">
<Hidden fields={{ projectKey: p.key, back }} />
<NativeSelect name="poolId" defaultValue={pool?.id ?? ""} aria-label={t("Пул подписок по умолчанию")} className="h-8">
<option value="">{t("Без пула — вход машины")}</option>
{pools.map((x) => (
<option key={x.id} value={x.id}>{x.name}</option>
))}
</NativeSelect>
<Button size="sm">{t("Сохранить")}</Button>
</form>
)}
{engineer && <p className="m-0 text-xs text-muted-foreground">{t("Раннеры проекта стартуют на свободной подписке пула.")} {superadmin ? <a href="/subscriptions#pools" className="text-primary">{t("Пулы и подписки")}</a> : t("Выбирает владелец проекта.")}</p>}
</PanelSection>
{mayDeleteProject(p, user.id, superadmin) && (
<PanelSection title={t("Удалить проект")}>
<p className="m-0 text-xs text-muted-foreground">{t("Проект пропадёт из вашего списка, а агенты остановятся. Ещё неделю он хранится у администратора FORGE — если передумаете, попросите вернуть его. Потом проект удаляется насовсем.")}</p>
<form action={deleteProjectAction} className="flex flex-col gap-2">
<Hidden fields={{ projectId: p.id, back }} />
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="confirm" value="yes" required />
{t("Да, удалить проект {name}", { name: p.name })}
</label>
<Button size="sm" variant="destructive" className="self-start">{t("Удалить проект")}</Button>
</form>
</PanelSection>
)}
{!engineer && <p className="m-0 text-xs text-muted-foreground">{t("Настройки для разработчиков — код проекта, настройки и расход агентов — открываются в виде «Инженер»:")} <a href="/settings#mode" className="text-primary">{t("Настройки → Вид FORGE")}</a>.</p>}
</div>
);
const newTask = (
<form action={addTask} className="flex flex-col gap-2">
<Hidden fields={{ projectId: p.id, back }} />
<Input name="title" required placeholder={t("Что сделать")} aria-label={t("Название {task}", { task: w.task("gen") })} />
<Textarea id="new-story-description" name="description" rows={5} placeholder={t("Описание: кому и зачем, критерии готовности")} aria-label={t("Описание {task}", { task: w.task("gen") })} />
<Dictate target="new-story-description" className="self-start" />
<AttachField projectId={p.id} target="new-story-description" />
<NativeSelect name="epicId" defaultValue={epicFilter ? String(epicFilter.id) : ""} aria-label={t("Эпик")}>
<option value="">{t("Без эпика")}</option>
{epics.map((e) => (
<option key={e.id} value={e.id}>
{e.title}
</option>
))}
</NativeSelect>
<Button variant="default" size="sm" className="self-start">{t("Создать {task}", { task: w.task("acc") })}</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} />
{p.deletedAt && (
<div className="flex flex-wrap items-center gap-3 rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm">
<span>{t("Проект удалён. Он хранится ещё {days} дн., потом исчезнет насовсем.", { days: trashDaysLeft(p) })}</span>
{superadmin && <RestoreProjectButton projectId={p.id} back={back} />}
</div>
)}
{created && !error && !engineer && <Notice>{t("Проект создан. Напишите первую задачу — кнопка «Задача» справа вверху.")}</Notice>}
{created && !error && engineer && (
<Notice>
{t("Репозиторий создан:")} <a href={repo.url} className="text-primary">{repo.fullName}</a> ({t.text(repoVisibilityLabel(repo.private))}).
<Button asChild size="xs">
<a href={repo.url}>{t("Открыть в Gitea")}</a>
</Button>
</Notice>
)}
<PageHeader
actions={
<>
{toAccept > 0 && (
<Link href={`/p/${p.key}/accept`} className="inline-flex h-9 items-center gap-1 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground hover:bg-primary/90" data-accept-link>
{t("Принять работу · {n}", { n: toAccept })}
</Link>
)}
<SettingsDialog title={t("Новая {task}", { task: w.task() })} trigger={<><Plus />{w.Task()}</>}>
{newTask}
</SettingsDialog>
{!pause && <PauseControl projectId={p.id} back={back} paused={false} popover />}
{mayDeleteProject(p, user.id, superadmin) && <DeleteProjectControl project={p} back={back} popover />}
<SettingsDialog title={t("Настройки проекта")}>{aside}</SettingsDialog>
</>
}
crumbs={<a href="/projects" className="text-muted-foreground hover:text-foreground">{t("Проекты")}</a>}
title={
<>
<span className="rounded-md bg-muted px-2 font-mono text-primary">{p.key}</span> {p.name}
</>
}
>
{engineer && <><a href={repo.url} className="text-primary">{repo.fullName}</a> · {t.text(repoVisibilityLabel(repo.private))}</>}
</PageHeader>
{pause && <PauseBanner projectId={p.id} back={back} since={pause.since} />}
{mayChoose && (ownLogins.length > 0 || (agentWarning && !connected)) && (
<SubscriptionSetup projectId={p.id} back={back} logins={ownLogins} checked={checked === "1"} extra={!agentWarning} shared={!!shared} requested={!!sharedReq} direct={superadmin} failed={failedLogins} />
)}
{agentWarning && !(mayChoose && (ownLogins.length > 0 || !pool || !connected)) && (
<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">{t("Агенты не запустятся:")}</span> {t.text(agentWarning)}.
{pool ? (superadmin ? <a href={`/subscriptions#pool-${pool.id}`} className="text-primary">{t("Добавить ещё одну подписку")} →</a> : <span className="text-muted-foreground">{t("Смените подписку в «⋯ Настройки проекта → Подписки» или попросите суперадмина проверить её.")}</span>) : null}
{askOffer && <SubscriptionRequestButton projectId={p.id} offer={askOffer} back={back} />}
</p>
)}
{/* Кнопка «Попросить подписку у администратора» видна на странице проекта всегда, не только в «⋯ Настройки проекта». */}
{askAhead && (
<div className="mb-4 flex flex-wrap items-center gap-2 text-sm text-muted-foreground" data-subscription-request-page>
<span>{t("Нужна ещё подписка? Администратор может одолжить свою на время.")}</span>
<SubscriptionRequestButton projectId={p.id} offer={askAhead} back={back} ahead />
</div>
)}
{tab === "board" && <ProductCard product={product} projectKey={p.key} chat={canChat} engineer={engineer} projectId={p.id} needs={productNeedList} review={productReview} back={back} publish={publish} />}
<nav aria-label={t("Разделы проекта")} className="-mt-2 mb-4 flex gap-1 overflow-x-auto border-b">
{visibleTabs.map((x) => (
<Fragment key={x.id}>
<a
href={x.id === "board" ? `/p/${p.key}` : `/p/${p.key}?tab=${x.id}`}
aria-current={tab === x.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 === x.id ? "border-primary text-foreground" : "border-transparent",
)}
>
{t(x.label)}
{!!tabCount[x.id] && <span className="rounded-full bg-muted px-1.5 font-mono text-[11px] tabular-nums">{tabCount[x.id]}</span>}
</a>
{/* PEP-106: the people's chat of the project lives in «Чаты»; the link sits right after the board. */}
{x.id === "board" && canChat && (
<a href={`/chats/${p.key}`} className="-mb-px flex items-center gap-1.5 border-b-2 border-transparent px-3 py-2 text-sm whitespace-nowrap text-muted-foreground hover:text-foreground hover:no-underline">
{t("Чат с аналитиком")}
{discussionNew > 0 && <span className="rounded-full bg-info px-1.5 font-mono text-[11px] text-background tabular-nums">{discussionNew}</span>}
</a>
)}
</Fragment>
))}
</nav>
{tab === "board" && (
<>
{epics.length > 0 && (
<nav aria-label={t("Фильтр по эпику")} 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={t("Эпик — большая цель; карточки на доске — {tasks}, шаги к ней", { tasks: w.task("pl") })}>{t("Эпики:")}</a>
{[{ id: 0, title: t("все") }, ...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={t("Готово {progress}", { progress: 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">
{t("Спланировать {tasks} эпика", { tasks: w.task("accPl") })} →
</a>
)}
</nav>
)}
{work && <WorkLine line={work} className="mb-2" />}
<Board cards={cards} back={back} />
</>
)}
{tab === "epics" && (
<EpicsTab
w={w}
projectId={p.id}
projectKey={p.key}
epics={epics}
stories={tasks.map((x) => ({ key: `${p.key}-${x.number}`, title: x.title, status: x.status, goalId: x.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={t("Релизы")}>
<div className="flex flex-col gap-2 sm:flex-row">
<EnvLine name="staging" r={current.staging} t={t} />
<EnvLine name={t("прод")} r={current.prod} t={t} />
</div>
{prodCandidate && prodCandidate !== current.prod?.sha && (
<form action={deployProdAction}>
<Hidden fields={{ projectKey: p.key, back }} />
<Button variant="default" size="sm">
<Rocket />
{t("Выкатить в прод {sha}", { sha: prodCandidate.slice(0, 7) })}
</Button>
</form>
)}
{releases.length === 0 ? (
<Empty>
{t("Деплоев ещё не было. Настройка —")} <span className="font-mono">deploy</span> {t("в .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}>{t(RELEASE_STATUS[r.status].label)}</Badge>
{r.reason && <span className="ml-1.5 text-muted-foreground">{t.text(r.reason)}</span>}
</td>
<td className="px-3 py-2">
{r.tasks.map((k) => (
<Key key={k} href={`/t/${k}`} className="mr-1.5">{k}</Key>
))}
</td>
<td className="px-3 py-2 text-right whitespace-nowrap text-muted-foreground">
{r.deployedBy} · {r.createdAt.toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short" })}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</Section>
)}
{tab === "bugs" && (
<>
<IncidentsSection w={w} projectId={p.id} back={back} settings={incidentSettings} incidents={incidents} taskKeys={new Map(tasks.map((t) => [t.id, `${p.key}-${t.number}`]))} />
{sources.length ? <ProjectErrors projectId={p.id} projectKey={p.key} sp={sp} /> : null}
</>
)}
{tab === "metrics" && metrics && <MetricsTab m={metrics} projectKey={p.key} />}
{tab === "journal" && (
<Section title={t("Журнал действий")} actions={<JournalFilters action={`/p/${p.key}`} value={{ tab: "journal", actor, channel }} />}>
<JournalList entries={journal} showProject={false} />
</Section>
)}
{tab === "sessions" && (
<Section
title={t("Сессии")}
actions={
<SettingsDialog title={t("Новый терминал")} trigger={<><SquareTerminal />{t("Новый терминал")}</>}>
<NewRunnerForm projectId={p.id} back={back} />
</SettingsDialog>
}
>
{sessions.length === 0 ? <Empty>{t("Сессий ещё не было.")}</Empty> : sessions.map((s) => <SessionCard key={s.id} s={s} back={back} showTitle />)}
</Section>
)}
</Workspace>
);
}