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 = { 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 (
{name} {r ? ( {r.sha.slice(0, 7)} {r.host && ( {r.host} )} ) : ( {t("нет")} )}
); } 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(); 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(), 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 = (

{pause ? t("Проект на паузе: агенты не работают, уведомлений нет.") : t("На паузе агенты не работают, а вы не получаете уведомлений по проекту.")}

{engineer && (
{t("Где")}
{repo.fullName}
{t("Пространство")}
{p.giteaOwner} {repo.ownerKind && <> — {repo.ownerKind === "org" ? t("организация") : t("личное")}}
{t("Видимость")}
{t.text(repoVisibilityLabel(repo.private))}
{t("Кто видит")}
{t.text(repoAudience(repo))}
{t("Рабочая копия")}
{p.workspacePath}
{isOwner && repo.private !== null && (
)}
{isOwner && repo.private !== null && (

{repo.private ? t("Публичный репозиторий видят все, у кого есть доступ к Gitea.") : t("Приватный репозиторий видят только владелец пространства, соавторы и peppa-bot.")} {t("Видимость меняется в Gitea сразу.")}

)}
)} {engineer && ( )} {/* glossary-ignore: раздел виден только в виде «Инженер» */} {engineer && ( )} [r.name, { serviceName: r.serviceName, connectionName: r.connectionName }]))} hints={secretNameHints()} engineer={engineer} /> {engineer && ( )}

{t("Аналитик решает, зачем это и что берём в первую версию, делит большое (не больше четырёх частей) и пишет критерии приёмки. Вопросов не задаёт: развилки решает сам и показывает решения на странице задачи — «Фабрика решила за вас». {Tasks}, созданные до включения, не трогает.", { Tasks: w.Task("pl") })}

{engineer && (