PEP-38: all pages on the console components, globals.css removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-13 16:21:24 +05:00
parent 28fbde4add
commit c03b679a1d
23 changed files with 1104 additions and 918 deletions

View File

@ -1,6 +1,7 @@
import Link from "next/link";
import { publicOrigin } from "@/lib/auth";
import { Workspace } from "@/components/Workspace";
import { PageHeader, Section } from "@/components/common";
const TOOLS: Array<[string, string]> = [
["list_projects", "мои проекты, ссылка на репозиторий в Gitea и сколько задач в каждой колонке"],
@ -39,13 +40,13 @@ export default async function Help() {
const mcp = `${await publicOrigin()}/mcp`;
return (
<Workspace>
<section className="narrow help">
<h1>Помощь</h1>
<div className="max-w-3xl text-sm leading-relaxed [&_a]:text-primary [&_code]:font-mono [&_code]:text-[0.92em] [&_li]:my-1 [&_ul]:m-0 [&_ul]:list-disc [&_ul]:pl-5">
<PageHeader title="Помощь">Понятия Пеппы, подключение MCP-клиентов и что можно попросить.</PageHeader>
<h2>Как устроена Пеппа</h2>
<Section title="Как устроена Пеппа">
<ul>
<li><b>Проект</b> — репозиторий в Gitea с ключом задач (например, PEP). Создаётся из веба или через MCP.</li>
<li><b>Где репозиторий</b> — в выбранном при создании пространстве Gitea: личном (<span className="mono">&lt;ваш логин&gt;/&lt;slug&gt;</span>) или организации. По умолчанию он приватный: его видят владелец пространства (в организации — её участники с доступом), <span className="mono">peppa-bot</span> и участники проекта. Ссылка «Открыть в Gitea», видимость и кто видит — в блоке «Репозиторий» на странице проекта.</li>
<li><b>Где репозиторий</b> — в выбранном при создании пространстве Gitea: личном (<span className="font-mono">&lt;ваш логин&gt;/&lt;slug&gt;</span>) или организации. По умолчанию он приватный: его видят владелец пространства (в организации — её участники с доступом), <span className="font-mono">peppa-bot</span> и участники проекта. Ссылка «Открыть в Gitea», видимость и кто видит — в блоке «Репозиторий» на странице проекта.</li>
<li><b>Цель</b> — верхнеуровневый результат («Мультипользовательская платформа»). Группирует задачи и даёт агенту контекст «зачем».</li>
<li><b>Задача</b> (PEP-12) — один результат с описанием и условиями готовности.</li>
<li><b>Доска</b> — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента.</li>
@ -54,65 +55,73 @@ export default async function Help() {
<li><b>Раннер</b> — агент, запущенный по задаче в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе <Link href="/runners">Раннеры</Link>: статус, задача, команда <code>tmux attach</code>, сообщение, остановка и resume; фильтры «ждут тебя / работают / остановлены (упали) / завершены».</li>
<li><b>Главная</b> — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе <Link href="/projects">Проекты</Link>.</li>
</ul>
</Section>
<h2>Подключить MCP</h2>
<p>Адрес сервера:</p>
<code className="mcp-url">{mcp}</code>
<Section title="Подключить MCP">
<p className="m-0">Адрес сервера:</p>
<code className="block overflow-x-auto rounded-md border bg-muted px-3 py-2 text-sm">{mcp}</code>
<ul>
<li><b>ChatGPT</b>: Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется Пеппа — войдите через Gitea и нажмите «Разрешить». В чате включите коннектор Peppa.</li>
<li><b>Codex, Claude и другие MCP-клиенты</b>: добавьте удалённый MCP-сервер по этому URL с OAuth — клиент зарегистрируется сам, вход и согласие на экране Пеппы.</li>
<li>Если клиент не видит новых инструментов — обновите или переподключите коннектор. Доступ отзывается в <Link href="/settings">Настройках</Link>.</li>
<li>Чтобы агенты работали на вашей подписке, подключите Claude в <Link href="/settings">Настройках</Link>.</li>
</ul>
</Section>
<h2>Сценарии</h2>
<Section title="Сценарии">
{CASES.map((c) => (
<article key={c.title} className="card">
<article key={c.title} className="flex flex-col gap-1 rounded-lg border bg-card px-4 py-3">
<b>{c.title}</b>
<p className="say">«{c.say}»</p>
<p className="muted">{c.how}</p>
<p className="m-0 italic">«{c.say}»</p>
<p className="m-0 text-muted-foreground">{c.how}</p>
</article>
))}
</Section>
<h2>Инструменты MCP</h2>
<table className="tools">
<Section title="Инструменты MCP">
<div className="overflow-x-auto rounded-lg border">
<table className="w-full border-collapse">
<tbody>
{TOOLS.map(([name, what]) => (
<tr key={name}>
<td className="mono">{name}</td>
<td>{what}</td>
<tr key={name} className="border-b align-top last:border-0">
<td className="px-3 py-2 font-mono text-xs [overflow-wrap:anywhere] sm:whitespace-nowrap">{name}</td>
<td className="px-3 py-2">{what}</td>
</tr>
))}
</tbody>
</table>
</div>
</Section>
<h2>CI/CD</h2>
<p className="muted">
Каждый PR агента проверяет Gitea Actions: <span className="mono">install</span>, <span className="mono">lint</span>,{" "}
<span className="mono">typecheck</span>, <span className="mono">test</span>, <span className="mono">build</span>. Команды —
в <span className="mono">.peppa/project.json → checks</span> (заполняет агент на первой задаче), workflow приходит из
шаблона; в старый проект — командой <span className="mono">peppa ci connect KEY</span> (PR от Пеппы). Результат виден в
<Section title="CI/CD">
<p className="m-0 text-muted-foreground">
Каждый PR агента проверяет Gitea Actions: <span className="font-mono">install</span>, <span className="font-mono">lint</span>,{" "}
<span className="font-mono">typecheck</span>, <span className="font-mono">test</span>, <span className="font-mono">build</span>. Команды —
в <span className="font-mono">.peppa/project.json → checks</span> (заполняет агент на первой задаче), workflow приходит из
шаблона; в старый проект — командой <span className="font-mono">peppa ci connect KEY</span> (PR от Пеппы). Результат виден в
карточке задачи («Проверки: 4 из 4 пройдены»). Красная проверка уходит агенту с хвостом лога, после 3 красных
прогонов подряд Пеппа спросит вас. В ревью задача попадает и «Принять» мержит PR только с зелёными проверками и без
конфликтов. PR, меняющий конвейер (<span className="mono">.gitea/</span>, <span className="mono">checks</span>,{" "}
<span className="mono">deploy</span>), сам не мержится никогда.
конфликтов. PR, меняющий конвейер (<span className="font-mono">.gitea/</span>, <span className="font-mono">checks</span>,{" "}
<span className="font-mono">deploy</span>), сам не мержится никогда.
</p>
<p className="muted">
Деплой — <span className="mono">deploy</span> в project.json и <span className="mono">Dockerfile</span> (заготовки в{" "}
<span className="mono">deploy/</span>): PR получает preview <span className="mono">slug-prN.telecom.quest</span> (удаляется при
закрытии), мерж выкатывает staging <span className="mono">slug-staging.telecom.quest</span>, прод{" "}
<span className="mono">slug-prod.telecom.quest</span> — по кнопке «Выкатить в прод» (страница проекта, Telegram, MCP{" "}
<span className="mono">deploy</span>). После каждого деплоя — проверка <span className="mono">/healthz</span> до 2 минут; не
<p className="m-0 text-muted-foreground">
Деплой — <span className="font-mono">deploy</span> в project.json и <span className="font-mono">Dockerfile</span> (заготовки в{" "}
<span className="font-mono">deploy/</span>): PR получает preview <span className="font-mono">slug-prN.telecom.quest</span> (удаляется при
закрытии), мерж выкатывает staging <span className="font-mono">slug-staging.telecom.quest</span>, прод{" "}
<span className="font-mono">slug-prod.telecom.quest</span> — по кнопке «Выкатить в прод» (страница проекта, Telegram, MCP{" "}
<span className="font-mono">deploy</span>). После каждого деплоя — проверка <span className="font-mono">/healthz</span> до 2 минут; не
прошла — откат на предыдущий образ и сообщение вам. Релизы — на странице проекта.
</p>
</Section>
<h2>Telegram</h2>
<p className="muted">
<Section title="Telegram">
<p className="m-0 text-muted-foreground">
Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с
кнопками; ответ реплаем уходит прямо в сессию агента. Новые ошибки из прода приходят туда же — по политике
проекта: сообщением, задачей или с кнопками «В бэклог / В работу / Игнорировать».
</p>
</section>
</Section>
</div>
</Workspace>
);
}

View File

@ -1,25 +1,50 @@
import { notFound } from "next/navigation";
import { AutoRefresh } from "@/components/AutoRefresh";
import { Flash, Notice, SessionCard } from "@/components/ui";
import { Board, type Card } from "@/components/Board";
import { columnOf, currentReleases, describeRepo, listReleases, type Release } from "@peppa/runner";
import { requireUser } from "@/lib/auth";
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
import { ExternalLink, Plus, Rocket, Target } from "lucide-react";
import { columnOf, currentReleases, describeRepo, listReleases, bugsinkWebhookBase, type Release } from "@peppa/runner";
import { getIncidentSettings, listErrorSources, listIncidents, listMembers, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { bugsinkWebhookBase } from "@peppa/runner";
import { AutoRefresh } from "@/components/AutoRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Board, type Card } from "@/components/Board";
import { Hidden, SessionCard } from "@/components/cards";
import { Disclosure, Empty, Flash, Key, Notice, PageHeader, Section } from "@/components/common";
import { IncidentsSection } from "@/components/Incidents";
import { db } from "@/lib/db";
import { addGoal, addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember } from "../../actions";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input, Textarea } from "@/components/ui/input";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
import { addGoal, addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember } from "../../actions";
const RELEASE_STATUS: Record<Release["status"], string> = {
deploying: "⏳ выкатывается",
healthy: "✅ работает",
rolled_back: "↩️ откат",
failed: "❌ не поднялся",
removed: "🗑 удалён",
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" },
};
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 }> }) {
const user = await requireUser();
const { key } = await params;
@ -53,83 +78,197 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
column: columnOf(t.status),
goal: t.goalId ? (goalTitle.get(t.goalId) ?? null) : null,
}));
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>
<Button asChild size="sm" className="self-start">
<a href={repo.url}>
Открыть в Gitea <ExternalLink />
</a>
</Button>
</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">владелец · агенты работают на его подписке Claude</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>
</div>
);
return (
<Workspace>
<Workspace aside={aside}>
<AutoRefresh />
<Flash error={error} />
{created && !error && (
<Notice>
Репозиторий создан: <a href={repo.url}>{repo.fullName}</a> ({repoVisibilityLabel(repo.private)}).{" "}
<a href={repo.url} className="button small">Открыть в Gitea</a>
Репозиторий создан: <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>
)}
<h1>
<span className="mono">{p.key}</span> {p.name}
</h1>
<p className="muted">
<a href={repo.url}>{repo.fullName}</a> · {repoVisibilityLabel(repo.private)}
</p>
<PageHeader
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>
<Board cards={cards} back={back} />
{groups.map(({ goal }) => (
<details key={goal?.id ?? "none"} className="add">
<summary>+ Задача{goal ? ` · 🎯 ${goal.title}` : " без цели"}</summary>
<form action={addTask} className="stack">
<input type="hidden" name="projectId" value={p.id} />
<input type="hidden" name="back" value={back} />
{goal && <input type="hidden" name="goalId" value={goal.id} />}
<input type="text" name="title" required placeholder="Что сделать" aria-label="Название задачи" />
<textarea name="description" rows={3} placeholder="Описание: контекст, критерии готовности" aria-label="Описание задачи" />
<button className="primary">Создать задачу</button>
<div className="mt-3 grid gap-2 md:grid-cols-2">
{groups.map(({ goal }) => (
<Disclosure
key={goal?.id ?? "none"}
summary={
<span className="flex min-w-0 items-center gap-1.5">
<Plus className="size-3.5 text-primary" />
Задача
<span className="truncate text-muted-foreground">{goal ? `· ◎ ${goal.title}` : "без цели"}</span>
</span>
}
>
<form action={addTask} className="flex flex-col gap-2">
<Hidden fields={{ projectId: p.id, back, goalId: goal?.id }} />
<Input name="title" required placeholder="Что сделать" aria-label="Название задачи" />
<Textarea name="description" rows={3} placeholder="Описание: контекст, критерии готовности" aria-label="Описание задачи" />
<Button variant="default" size="sm" className="self-start">Создать задачу</Button>
</form>
</Disclosure>
))}
<Disclosure
summary={
<span className="flex items-center gap-1.5">
<Target className="size-3.5 text-primary" />
Цель
</span>
}
>
<form action={addGoal} className="flex flex-col gap-2">
<Hidden fields={{ projectId: p.id, back }} />
<Input name="title" required placeholder="Верхнеуровневая цель" aria-label="Название цели" />
<Textarea name="description" rows={3} placeholder="Зачем и какой результат" aria-label="Описание цели" />
<Button variant="default" size="sm" className="self-start">Создать цель</Button>
</form>
</details>
))}
</Disclosure>
</div>
<section>
<details>
<summary>+ Цель</summary>
<form action={addGoal} className="stack">
<input type="hidden" name="projectId" value={p.id} />
<input type="hidden" name="back" value={back} />
<input type="text" name="title" required placeholder="Верхнеуровневая цель" aria-label="Название цели" />
<textarea name="description" rows={3} placeholder="Зачем и какой результат" aria-label="Описание цели" />
<button className="primary">Создать цель</button>
</form>
</details>
</section>
<section>
<h2>Релизы</h2>
<p>
Staging: {current.staging ? <><span className="mono">{current.staging.sha.slice(0, 7)}</span>{current.staging.host && <> · <a href={`https://${current.staging.host}`}>{current.staging.host}</a></>}</> : <span className="muted">нет</span>}
{" · "}Прод: {current.prod ? <><span className="mono">{current.prod.sha.slice(0, 7)}</span>{current.prod.host && <> · <a href={`https://${current.prod.host}`}>{current.prod.host}</a></>}</> : <span className="muted">нет</span>}
</p>
<Section title="Релизы">
<div className="flex flex-col gap-2 sm:flex-row">
<EnvLine name="staging" r={current.staging} />
<EnvLine name="прод" r={current.prod} />
</div>
{current.staging && current.staging.sha !== current.prod?.sha && (
<form action={deployProdAction} className="row">
<input type="hidden" name="projectKey" value={p.key} />
<input type="hidden" name="back" value={back} />
<button className="primary">🚀 Выкатить в прод {current.staging.sha.slice(0, 7)}</button>
<form action={deployProdAction}>
<Hidden fields={{ projectKey: p.key, back }} />
<Button variant="default" size="sm">
<Rocket />
Выкатить в прод {current.staging.sha.slice(0, 7)}
</Button>
</form>
)}
{releases.length === 0 ? (
<p className="empty">Деплоев ещё не было. Настройка — <span className="mono">deploy</span> в .peppa/project.json (см. «Помощь → CI/CD»).</p>
<Empty>
Деплоев ещё не было. Настройка — <span className="font-mono">deploy</span> в .peppa/project.json (см. «Помощь → CI/CD»).
</Empty>
) : (
<table className="releases">
<tbody>
{releases.map((r) => (
<tr key={r.id}>
<td>{r.env}{r.prNumber ? ` #${r.prNumber}` : ""}</td>
<td className="mono">{r.sha.slice(0, 7)}</td>
<td>{RELEASE_STATUS[r.status]}{r.reason ? <span className="muted"> — {r.reason}</span> : null}</td>
<td>{r.tasks.join(", ")}</td>
<td className="muted">{r.deployedBy} · {r.createdAt.toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" })}</td>
</tr>
))}
</tbody>
</table>
<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>
</Section>
<IncidentsSection
projectId={p.id}
@ -143,89 +282,9 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null}
/>
<section>
<h2>Участники</h2>
<ul className="members">
<li>
<span><b>{team.owner?.login ?? "—"}</b> <span className="muted">владелец · агенты работают на его подписке Claude</span></span>
</li>
{team.members.map((m) => (
<li key={m.id}>
<span>
{m.login} <span className="muted">участник</span>
{noRepoAccess(m.login) && <span className="muted"> · нет доступа к репозиторию</span>}
</span>
{(isOwner || m.id === user.id) && (
<form action={removeProjectMember}>
<input type="hidden" name="projectId" value={p.id} />
<input type="hidden" name="login" value={m.login} />
<input type="hidden" name="back" value={back} />
<button className="small danger">{m.id === user.id ? "Выйти из проекта" : "Убрать"}</button>
</form>
)}
</li>
))}
{team.invites.map((login) => (
<li key={login}>
<span>{login} <span className="muted">приглашён · появится после первого входа в Пеппу</span></span>
{isOwner && (
<form action={removeProjectMember}>
<input type="hidden" name="projectId" value={p.id} />
<input type="hidden" name="login" value={login} />
<input type="hidden" name="back" value={back} />
<button className="small danger">Отозвать</button>
</form>
)}
</li>
))}
</ul>
{isOwner && (
<form action={addProjectMember} className="row">
<input type="hidden" name="projectId" value={p.id} />
<input type="hidden" name="back" value={back} />
<input type="text" name="login" required placeholder="Логин в Gitea" aria-label="Логин участника в Gitea" />
<button>Добавить участника</button>
</form>
)}
{isOwner && missingAccess && (
<form action={grantRepoAccessToMembers}>
<input type="hidden" name="projectId" value={p.id} />
<input type="hidden" name="back" value={back} />
<button>Выдать доступ участникам</button>
</form>
)}
{isOwner && (
<p className="muted">
Участник видит доску и входящие, двигает карточки и отвечает агентам; получает доступ на запись к репозиторию.
</p>
)}
</section>
<section>
<h2>Репозиторий</h2>
<dl className="repo">
<dt>Где</dt>
<dd>
<a href={repo.url}>{repo.fullName}</a> · <a href={repo.url}>Открыть в Gitea</a>
</dd>
<dt>Пространство</dt>
<dd>
{p.giteaOwner}
{repo.ownerKind && ` — ${repo.ownerKind === "org" ? "организация" : "личное"}`}
</dd>
<dt>Видимость</dt>
<dd>{repoVisibilityLabel(repo.private)}</dd>
<dt>Кто видит</dt>
<dd>{repoAudience(repo)}</dd>
<dt>Рабочая копия</dt>
<dd className="mono">{p.workspacePath}</dd>
</dl>
</section>
<section>
<h2>Сессии</h2>
{sessions.length === 0 ? <p className="empty">Сессий ещё не было.</p> : sessions.map((s) => <SessionCard key={s.id} s={s} back={back} />)}
</section>
<Section title="Сессии">
{sessions.length === 0 ? <Empty>Сессий ещё не было.</Empty> : sessions.map((s) => <SessionCard key={s.id} s={s} back={back} showTitle />)}
</Section>
</Workspace>
);
}

View File

@ -1,12 +1,12 @@
import Link from "next/link";
import { listUserProjects } from "@peppa/core";
import { AutoRefresh } from "@/components/AutoRefresh";
import { Flash, ProjectList, QuestionCard, SessionCard } from "@/components/ui";
import { ActivityAside } from "@/components/ActivityAside";
import { ProjectList, QuestionCard, SessionCard } from "@/components/cards";
import { Empty, Flash, MoreLink, PageHeader, Section } from "@/components/common";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { activeSessions, inbox } from "@/lib/queries";
import { Workspace } from "@/components/Workspace";
import { ActivityAside } from "@/components/ActivityAside";
export default async function Home({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
@ -16,23 +16,16 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e
<Workspace aside={<ActivityAside questions={false} />}>
<AutoRefresh />
<Flash error={error} />
<h1>Главная</h1>
<section>
<h2>Вопросы агентов {items.length > 0 && <span className="count">{items.length}</span>}</h2>
{items.length === 0 ? <p className="empty">Агентам от тебя ничего не нужно.</p> : items.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/" />)}
</section>
<section>
<h2>
Активные раннеры <Link href="/runners" className="more">все раннеры →</Link>
</h2>
{sessions.length === 0 ? <p className="empty">Сейчас ничего не запущено.</p> : sessions.map((s) => <SessionCard key={s.id} s={s} back="/" />)}
</section>
<section>
<h2>
Мои проекты <Link href="/projects" className="more">все проекты →</Link>
</h2>
<PageHeader title="Главная">{items.length ? "Агенты ждут твоего решения — ответь здесь, в Telegram или через MCP." : "Всё идёт само: агентам от тебя ничего не нужно."}</PageHeader>
<Section title="Вопросы агентов" count={items.length}>
{items.length === 0 ? <Empty>Агентам от тебя ничего не нужно.</Empty> : items.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/" />)}
</Section>
<Section title="Активные раннеры" actions={<MoreLink href="/runners">все раннеры</MoreLink>}>
{sessions.length === 0 ? <Empty>Сейчас ничего не запущено.</Empty> : sessions.map((s) => <SessionCard key={s.id} s={s} back="/" showTitle />)}
</Section>
<Section title="Мои проекты" actions={<MoreLink href="/projects">все проекты</MoreLink>}>
<ProjectList projects={projects} userId={user.id} />
</section>
</Section>
</Workspace>
);
}

View File

@ -1,10 +1,22 @@
import { giteaForUser, type GiteaOrg } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { Flash } from "@/components/ui";
import { Flash, PageHeader } from "@/components/common";
import { Hidden } from "@/components/cards";
import { Button } from "@/components/ui/button";
import { Input, Label, NativeSelect } from "@/components/ui/input";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { createProjectAction } from "../../actions";
import { Workspace } from "@/components/Workspace";
function Choice({ name, value, checked, children }: { name: string; value: string; checked?: boolean; children: React.ReactNode }) {
return (
<label className="flex cursor-pointer items-start gap-2.5 rounded-md border bg-background/40 px-3 py-2 text-sm has-checked:border-primary/60 has-checked:bg-primary/5">
<input type="radio" name={name} value={value} defaultChecked={checked} className="mt-1 accent-primary" />
<span>{children}</span>
</label>
);
}
export default async function NewProject({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
@ -19,64 +31,56 @@ export default async function NewProject({ searchParams }: { searchParams: Promi
}
return (
<Workspace>
<section className="narrow">
<h1>Новый проект</h1>
<Flash error={error ?? giteaError} />
<form action={createProjectAction} className="stack">
<input type="hidden" name="back" value="/projects/new" />
<label>
Название
<input type="text" name="name" required placeholder="Платёжный сервис" />
</label>
<div className="row">
<label className="grow">
Репозиторий (slug)
<input type="text" name="slug" required pattern="[a-z0-9][a-z0-9-]*" placeholder="payments" />
</label>
<label>
Ключ задач
<input type="text" name="key" required pattern="[A-Za-z][A-Za-z0-9]{1,9}" placeholder="PAY" className="short" />
</label>
</div>
<label>
Пространство в Gitea
<select name="owner" defaultValue={user.login}>
<option value={user.login}>{user.login} — личное</option>
{orgs.map((o) => (
<option key={o.id} value={o.username}>{o.username} — организация</option>
))}
</select>
</label>
<p className="muted">
Репозиторий будет <span className="mono">{giteaUrl}/&lt;пространство&gt;/&lt;slug&gt;</span>. В личном пространстве приватный репозиторий видите
только вы, <span className="mono">peppa-bot</span> и участники проекта; в организации — ещё её участники с доступом к репозиториям.
{orgs.length === 0 && " Организаций, где вы можете создавать репозитории, нет."}
</p>
<fieldset>
<legend>Видимость</legend>
<label className="inline">
<input type="radio" name="visibility" value="private" defaultChecked /> Приватный — только те, кому выдан доступ
</label>
<label className="inline">
<input type="radio" name="visibility" value="public" /> Публичный — все, у кого есть доступ к Gitea
</label>
</fieldset>
<fieldset>
<legend>Репозиторий</legend>
<label className="inline">
<input type="radio" name="mode" value="new" defaultChecked /> Создать новый
</label>
<label className="inline">
<input type="radio" name="mode" value="existing" /> Подключить существующий (нужны права админа; видимость не меняется)
</label>
</fieldset>
<p className="muted">
Пеппа добавит <span className="mono">peppa-bot</span> соавтором, положит AGENTS.md, .mcp.json и .peppa/project.json из шаблона и запустит
openspec init. Занимает до ~15 секунд.
</p>
<button className="primary">Создать проект</button>
</form>
</section>
<div className="max-w-xl">
<PageHeader title="Новый проект" />
<Flash error={error ?? giteaError} />
<form action={createProjectAction} className="flex flex-col gap-4">
<Hidden fields={{ back: "/projects/new" }} />
<Label>
Название
<Input name="name" required placeholder="Платёжный сервис" />
</Label>
<div className="flex gap-3">
<Label className="flex-1">
Репозиторий (slug)
<Input name="slug" required pattern="[a-z0-9][a-z0-9-]*" placeholder="payments" className="font-mono" />
</Label>
<Label className="w-32">
Ключ задач
<Input name="key" required pattern="[A-Za-z][A-Za-z0-9]{1,9}" placeholder="PAY" className="font-mono uppercase" />
</Label>
</div>
<Label>
Пространство в Gitea
<NativeSelect name="owner" defaultValue={user.login}>
<option value={user.login}>{user.login} — личное</option>
{orgs.map((o) => (
<option key={o.id} value={o.username}>{o.username} — организация</option>
))}
</NativeSelect>
</Label>
<p className="m-0 text-sm text-muted-foreground">
Репозиторий будет <span className="font-mono">{giteaUrl}/&lt;пространство&gt;/&lt;slug&gt;</span>. В личном пространстве приватный репозиторий видите
только вы, <span className="font-mono">peppa-bot</span> и участники проекта; в организации — ещё её участники с доступом к репозиториям.
{orgs.length === 0 && " Организаций, где вы можете создавать репозитории, нет."}
</p>
<fieldset className="m-0 flex flex-col gap-2 border-0 p-0">
<legend className="mb-2 text-sm font-medium">Видимость</legend>
<Choice name="visibility" value="private" checked>Приватный — только те, кому выдан доступ</Choice>
<Choice name="visibility" value="public">Публичный — все, у кого есть доступ к Gitea</Choice>
</fieldset>
<fieldset className="m-0 flex flex-col gap-2 border-0 p-0">
<legend className="mb-2 text-sm font-medium">Репозиторий</legend>
<Choice name="mode" value="new" checked>Создать новый</Choice>
<Choice name="mode" value="existing">Подключить существующий (нужны права админа; видимость не меняется)</Choice>
</fieldset>
<p className="m-0 text-sm text-muted-foreground">
Пеппа добавит <span className="font-mono">peppa-bot</span> соавтором, положит AGENTS.md, .mcp.json и .peppa/project.json из шаблона и запустит
openspec init. Занимает до ~15 секунд.
</p>
<Button variant="default" className="self-start">Создать проект</Button>
</form>
</div>
</Workspace>
);
}

View File

@ -1,9 +1,12 @@
import Link from "next/link";
import { Plus } from "lucide-react";
import { listUserProjects } from "@peppa/core";
import { Flash, ProjectList } from "@/components/ui";
import { ProjectList } from "@/components/cards";
import { Flash, PageHeader } from "@/components/common";
import { Button } from "@/components/ui/button";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { Workspace } from "@/components/Workspace";
export default async function Projects({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
@ -12,12 +15,19 @@ export default async function Projects({ searchParams }: { searchParams: Promise
return (
<Workspace>
<Flash error={error} />
<h1>
Проекты{" "}
<Link href="/projects/new" className="button primary small">
Новый проект
</Link>
</h1>
<PageHeader
title="Проекты"
actions={
<Button asChild variant="default" size="sm">
<Link href="/projects/new">
<Plus />
Новый проект
</Link>
</Button>
}
>
Свои и общие проекты: доска задач, релизы, ошибки из прода, участники.
</PageHeader>
<ProjectList projects={projects} userId={user.id} />
</Workspace>
);

View File

@ -1,10 +1,12 @@
import Link from "next/link";
import { listUserSessions, RUNNER_FILTERS, type RunnerFilter } from "@peppa/core";
import { AutoRefresh } from "@/components/AutoRefresh";
import { Flash, SessionCard } from "@/components/ui";
import { SessionCard } from "@/components/cards";
import { Empty, Flash, PageHeader } from "@/components/common";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { Workspace } from "@/components/Workspace";
import { cn } from "@/lib/utils";
const FILTERS: Array<{ key: RunnerFilter | undefined; label: string }> = [
{ key: undefined, label: "Все" },
@ -26,16 +28,22 @@ export default async function Runners({ searchParams }: { searchParams: Promise<
<Workspace>
<AutoRefresh />
<Flash error={error} />
<h1>Раннеры</h1>
<p className="muted">Агенты в tmux по задачам твоих и общих проектов. Подключиться к раннеру — команда tmux attach на машине Пеппы.</p>
<nav className="filters" aria-label="Фильтр раннеров">
<PageHeader title="Раннеры">Агенты в tmux по задачам твоих и общих проектов. Подключиться к раннеру — команда tmux attach на машине Пеппы.</PageHeader>
<nav className="mb-4 flex flex-wrap gap-1.5" aria-label="Фильтр раннеров">
{FILTERS.map((x) => (
<Link key={x.label} href={x.key ? `/runners?f=${x.key}` : "/runners"} className={x.key === filter ? "active" : undefined} aria-current={x.key === filter ? "page" : undefined}>
{x.label} <span className="muted">{count(x.key)}</span>
<Link
key={x.label}
href={x.key ? `/runners?f=${x.key}` : "/runners"}
aria-current={x.key === filter ? "page" : undefined}
className={cn("rounded-full border px-3 py-1 text-sm text-foreground hover:border-muted-foreground hover:no-underline", x.key === filter && "border-primary bg-primary/10")}
>
{x.label} <span className="font-mono text-xs text-muted-foreground">{count(x.key)}</span>
</Link>
))}
</nav>
{shown.length === 0 ? <p className="empty">{filter ? "Таких раннеров нет." : "Раннеров пока не было: перенеси задачу в «В работе» на доске проекта."}</p> : shown.map((s) => <SessionCard key={s.id} s={s} back={back} showTitle />)}
<div className="flex flex-col gap-2.5">
{shown.length === 0 ? <Empty>{filter ? "Таких раннеров нет." : "Раннеров пока не было: перенеси задачу в «В работе» на доске проекта."}</Empty> : shown.map((s) => <SessionCard key={s.id} s={s} back={back} showTitle />)}
</div>
</Workspace>
);
}

View File

@ -1,10 +1,30 @@
import { ExternalLink } from "lucide-react";
import { connectedApps } from "@peppa/core";
import { ago, Flash } from "@/components/ui";
import { pendingClaudeSetup } from "@peppa/runner";
import { Hidden } from "@/components/cards";
import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Workspace } from "@/components/Workspace";
import { publicOrigin, requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { pendingClaudeSetup } from "@peppa/runner";
import { cancelClaude, connectClaude, disconnectClaude, pairTelegram, revokeConnectedApp, submitClaudeCode, unpairTelegramAction } from "../actions";
import { Workspace } from "@/components/Workspace";
const back = { back: "/settings" };
/** A connected thing: title + details on the left, actions on the right. */
function Row({ title, children, actions }: { title: React.ReactNode; children?: React.ReactNode; actions?: React.ReactNode }) {
return (
<Card className="flex-row flex-wrap items-center gap-3">
<div className="min-w-0 flex-[1_1_16rem]">
<div className="font-medium">{title}</div>
{children && <div className="text-sm text-muted-foreground">{children}</div>}
</div>
{actions && <div className="flex gap-2">{actions}</div>}
</Card>
);
}
export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; claude?: string }> }) {
const user = await requireUser();
@ -14,106 +34,118 @@ export default async function Settings({ searchParams }: { searchParams: Promise
const origin = await publicOrigin();
return (
<Workspace>
<section className="narrow">
<Flash error={error} />
<h1>Настройки</h1>
<h2>Claude</h2>
{claude === "connected" && <p className="ok">Claude подключён ✅</p>}
{setup ? (
<div className="card stack">
<p>
1. Откройте ссылку на любом устройстве и войдите в аккаунт Claude (нужна подписка):
</p>
<a className="button primary" href={setup.url} target="_blank" rel="noreferrer">Войти в Claude ↗</a>
<p>2. Claude покажет код — вставьте его сюда:</p>
<form action={submitClaudeCode} className="row">
<input type="hidden" name="back" value="/settings" />
<input type="text" name="code" placeholder="Код из Claude" aria-label="Код из Claude" autoComplete="off" required />
<button className="primary">Подключить</button>
</form>
<form action={cancelClaude}>
<input type="hidden" name="back" value="/settings" />
<button className="link">Отменить</button>
</form>
</div>
) : user.claudeTokenEnc ? (
<article className="card row">
<div className="grow">
<b>Claude подключён</b>
<div className="muted">
<div className="max-w-2xl">
<Flash error={error} />
<PageHeader title="Настройки" />
<Section title="Claude">
{claude === "connected" && <Notice>Claude подключён</Notice>}
{setup ? (
<Card>
<p className="m-0 text-sm">1. Откройте ссылку на любом устройстве и войдите в аккаунт Claude (нужна подписка):</p>
<Button asChild variant="default" className="self-start">
<a href={setup.url} target="_blank" rel="noreferrer">
Войти в Claude <ExternalLink />
</a>
</Button>
<p className="m-0 text-sm">2. Claude покажет код — вставьте его сюда:</p>
<form action={submitClaudeCode} className="flex gap-2">
<Hidden fields={back} />
<Input name="code" placeholder="Код из Claude" aria-label="Код из Claude" autoComplete="off" required className="font-mono" />
<Button variant="default">Подключить</Button>
</form>
<form action={cancelClaude}>
<Hidden fields={back} />
<Button variant="link" className="text-muted-foreground">Отменить</Button>
</form>
</Card>
) : user.claudeTokenEnc ? (
<Row
title="Claude подключён"
actions={
<>
<form action={connectClaude}>
<Hidden fields={back} />
<Button size="sm">Переподключить</Button>
</form>
<form action={disconnectClaude}>
<Hidden fields={back} />
<Button size="sm" variant="destructive">Отключить</Button>
</form>
</>
}
>
с {user.claudeTokenSetAt?.toLocaleDateString("ru-RU")} · сессии ваших проектов работают на вашей подписке
</div>
</div>
<form action={connectClaude}>
<input type="hidden" name="back" value="/settings" />
<button>Переподключить</button>
</form>
<form action={disconnectClaude}>
<input type="hidden" name="back" value="/settings" />
<button className="danger">Отключить</button>
</form>
</article>
) : (
<div className="stack">
<p className="muted">
Агенты ваших проектов запускаются как Claude Code. Подключите свой аккаунт Claude — Пеппа получит годовой
токен через <span className="mono">claude setup-token</span>, вход делаете вы сами по ссылке.
</Row>
) : (
<Row
title="Claude не подключён"
actions={
<form action={connectClaude}>
<Hidden fields={back} />
<Button variant="default" size="sm">Подключить Claude</Button>
</form>
}
>
Агенты ваших проектов запускаются как Claude Code. Подключите свой аккаунт Claude — Пеппа получит годовой токен через{" "}
<span className="font-mono">claude setup-token</span>, вход делаете вы сами по ссылке.
</Row>
)}
</Section>
<Section title="Telegram">
{user.telegramChatId ? (
<Row
title={`Telegram привязан${user.telegramUsername ? ` (@${user.telegramUsername})` : ""}`}
actions={
<form action={unpairTelegramAction}>
<Hidden fields={back} />
<Button size="sm" variant="destructive">Отвязать</Button>
</form>
}
>
Вопросы агентов из ваших и общих проектов приходят в этот чат.
</Row>
) : (
<Row
title="Telegram не привязан"
actions={
<form action={pairTelegram}>
<Hidden fields={back} />
<Button variant="default" size="sm">Привязать Telegram</Button>
</form>
}
>
Бот присылает вопросы агентов и «готово к ревью» с кнопками. Нажмите кнопку — откроется бот, в нём нажмите Start.
</Row>
)}
</Section>
<Section title="MCP для ChatGPT и других клиентов">
<p className="m-0 text-sm">Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент зарегистрируется сам, вы подтвердите доступ на экране Пеппы.</p>
<code className="block overflow-x-auto rounded-md border bg-muted px-3 py-2 font-mono text-sm">{origin}/mcp</code>
<p className="m-0 text-sm text-muted-foreground">
Как подключить и что спрашивать — в <a href="/help" className="text-primary">Помощи</a>.
</p>
<form action={connectClaude}>
<input type="hidden" name="back" value="/settings" />
<button className="primary">Подключить Claude</button>
</form>
</div>
)}
<h2>Telegram</h2>
{user.telegramChatId ? (
<article className="card row">
<div className="grow">
<b>Telegram привязан{user.telegramUsername ? ` (@${user.telegramUsername})` : ""}</b>
<div className="muted">Вопросы агентов из ваших и общих проектов приходят в этот чат.</div>
</div>
<form action={unpairTelegramAction}>
<input type="hidden" name="back" value="/settings" />
<button className="danger">Отвязать</button>
</form>
</article>
) : (
<div className="stack">
<p className="muted">
Бот присылает вопросы агентов и «готово к ревью» с кнопками. Нажмите кнопку — откроется бот, в нём нажмите Start.
</p>
<form action={pairTelegram}>
<input type="hidden" name="back" value="/settings" />
<button className="primary">Привязать Telegram</button>
</form>
</div>
)}
<h2>MCP для ChatGPT и других клиентов</h2>
<p>
Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент
зарегистрируется сам, вы подтвердите доступ на экране Пеппы.
</p>
<code className="mcp-url">{origin}/mcp</code>
<p className="muted">Как подключить и что спрашивать — в <a href="/help">Помощи</a>.</p>
<h2>Подключённые приложения</h2>
{apps.length === 0 ? (
<p className="empty">Нет подключённых приложений.</p>
) : (
apps.map((a) => (
<article key={a.clientId} className="card row">
<div className="grow">
<b>{a.name}</b>
<div className="muted">с {a.since.toLocaleDateString("ru-RU")} · последний запрос {ago(a.lastUsedAt)}</div>
</div>
<form action={revokeConnectedApp}>
<input type="hidden" name="clientId" value={a.clientId} />
<input type="hidden" name="back" value="/settings" />
<button className="danger">Отозвать</button>
</form>
</article>
))
)}
</section>
</Section>
<Section title="Подключённые приложения">
{apps.length === 0 ? (
<Empty>Нет подключённых приложений.</Empty>
) : (
apps.map((a) => (
<Row
key={a.clientId}
title={a.name}
actions={
<form action={revokeConnectedApp}>
<Hidden fields={{ clientId: a.clientId, ...back }} />
<Button size="sm" variant="destructive">Отозвать</Button>
</form>
}
>
с {a.since.toLocaleDateString("ru-RU")} · последний запрос {ago(a.lastUsedAt)}
</Row>
))
)}
</Section>
</div>
</Workspace>
);
}

View File

@ -1,15 +1,22 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { AutoRefresh } from "@/components/AutoRefresh";
import { ago, Badge, Flash, QuestionCard, SessionCard } from "@/components/ui";
import { requireUser } from "@/lib/auth";
import { openspecArtifacts, taskActivity, taskForUser } from "@/lib/queries";
import { db } from "@/lib/db";
import { eq } from "drizzle-orm";
import { CircleCheck, CircleX, GitPullRequest, Hourglass, Play } from "lucide-react";
import { goals } from "@peppa/db";
import { taskCiSummary } from "@peppa/core";
import { eq } from "drizzle-orm";
import { startTaskSession } from "../../actions";
import { AutoRefresh } from "@/components/AutoRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Hidden, QuestionCard, SessionCard } from "@/components/cards";
import { ago, Disclosure, Empty, Flash, PageHeader, Section, StatusBadge } from "@/components/common";
import { Button } from "@/components/ui/button";
import { Input, NativeSelect } from "@/components/ui/input";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { openspecArtifacts, taskActivity, taskForUser } from "@/lib/queries";
import { startTaskSession } from "../../actions";
const CI_ICON = { success: <CircleCheck className="size-4 text-ok" />, failure: <CircleX className="size-4 text-destructive" />, pending: <Hourglass className="size-4 text-warn" /> };
export default async function TaskPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
@ -23,82 +30,108 @@ export default async function TaskPage({ params, searchParams }: { params: Promi
const artifacts = openspecArtifacts(project, task.openspecChange);
const ci = await taskCiSummary(db, ref);
const back = `/t/${ref.key}`;
const aside = (
<div className="flex flex-col gap-6">
<PanelSection title="Проверки">
<div className="flex flex-wrap items-center gap-2 text-sm">
{CI_ICON[ci.state as keyof typeof CI_ICON]}
{ci.runUrl ? <a href={ci.runUrl} className="text-primary">{ci.label}</a> : ci.label}
{ci.sha && <span className="font-mono text-xs text-muted-foreground">{ci.sha.slice(0, 7)}</span>}
</div>
{task.ciAttempts > 0 && <p className="m-0 text-xs text-muted-foreground">красных подряд: {task.ciAttempts}</p>}
{ci.failed.map((f) => (
<Disclosure
key={f.check}
summary={
<span className="flex items-center gap-1.5">
<CircleX className="size-3.5 text-destructive" />
<span className="font-mono">{f.check}</span>
{f.runUrl && <a href={f.runUrl} className="text-xs text-primary">лог</a>}
</span>
}
>
{f.logTail && <pre className="m-0 max-h-80 overflow-auto font-mono text-[11px] whitespace-pre-wrap">{f.logTail.split("\n").slice(-60).join("\n")}</pre>}
</Disclosure>
))}
</PanelSection>
<PanelSection title="События">
{events.length === 0 ? (
<p className="m-0 text-sm text-muted-foreground">Событий нет.</p>
) : (
<ol className="m-0 flex list-none flex-col gap-1.5 border-l p-0 pl-3">
{events.map((e) => (
<li key={e.id} className="text-xs [overflow-wrap:anywhere]">
<span className="font-mono text-muted-foreground">{ago(e.createdAt)}</span> <span className="font-mono text-primary">{e.type}</span>{" "}
{e.type === "progress" ? (e.payload as { text: string }).text : e.type === "task_updated" ? JSON.stringify((e.payload as { to: unknown }).to) : ""}
</li>
))}
</ol>
)}
</PanelSection>
</div>
);
return (
<Workspace>
<Workspace aside={aside}>
<AutoRefresh />
<Flash error={error} />
<p className="crumbs">
<Link href={`/p/${project.key}`}>{project.name}</Link>
{goal && <> · 🎯 {goal.title}</>}
</p>
<h1>
<span className="mono">{ref.key}</span> {task.title} <Badge status={task.status} />
</h1>
{task.prUrl && <p><a href={task.prUrl}>PR</a></p>}
<section className="checks">
<h2>Проверки</h2>
<p>
{ci.state === "success" ? "✅ " : ci.state === "failure" ? "❌ " : ci.state === "pending" ? "⏳ " : ""}
{ci.runUrl ? <a href={ci.runUrl}>{ci.label}</a> : ci.label}
{ci.sha && <span className="mono muted"> · {ci.sha.slice(0, 7)}</span>}
{task.ciAttempts > 0 && <span className="muted"> · красных подряд: {task.ciAttempts}</span>}
</p>
{ci.failed.map((f) => (
<details key={f.check}>
<summary>
❌ <span className="mono">{f.check}</span> {f.runUrl && <a href={f.runUrl}>лог</a>}
</summary>
{f.logTail && <pre className="md">{f.logTail.split("\n").slice(-60).join("\n")}</pre>}
</details>
))}
</section>
<p className="desc">{task.description || <span className="muted">Без описания</span>}</p>
<PageHeader
crumbs={
<>
<Link href={`/p/${project.key}`} className="text-muted-foreground hover:text-foreground">{project.name}</Link>
{goal && <span>· ◎ {goal.title}</span>}
</>
}
title={
<>
<span className="font-mono text-primary">{ref.key}</span> {task.title} <StatusBadge status={task.status} />
</>
}
actions={
task.prUrl && (
<Button asChild size="sm">
<a href={task.prUrl}>
<GitPullRequest />
PR
</a>
</Button>
)
}
/>
<div className="rounded-lg border bg-card p-4 text-sm whitespace-pre-wrap">{task.description || <span className="text-muted-foreground">Без описания</span>}</div>
<section>
<h2>Сессии</h2>
<form action={startTaskSession} className="row wrap">
<input type="hidden" name="taskKey" value={ref.key} />
<input type="hidden" name="back" value={back} />
<select name="provider" defaultValue="claude" aria-label="Агент">
<Section title="Сессии">
<form action={startTaskSession} className="flex flex-wrap gap-2">
<Hidden fields={{ taskKey: ref.key, back }} />
<NativeSelect name="provider" defaultValue="claude" aria-label="Агент" className="w-auto">
<option value="claude">Claude Code</option>
<option value="codex">Codex</option>
</select>
<input type="text" name="prompt" placeholder="Доп. инструкция (необязательно)" aria-label="Доп. инструкция" className="grow" />
<button className="primary">Запустить агента</button>
</NativeSelect>
<Input name="prompt" placeholder="Доп. инструкция (необязательно)" aria-label="Доп. инструкция" className="flex-[1_1_14rem]" />
<Button variant="default">
<Play />
Запустить агента
</Button>
</form>
{sessions.map((s) => <SessionCard key={s.id} s={s} back={back} />)}
</section>
</Section>
<section>
<h2>Вопросы</h2>
{questions.length === 0 ? <p className="empty">Вопросов не было.</p> : questions.map((q) => <QuestionCard key={q.id} q={q} taskStatus={task.status} back={back} />)}
</section>
<Section title="Вопросы">
{questions.length === 0 ? <Empty>Вопросов не было.</Empty> : questions.map((q) => <QuestionCard key={q.id} q={q} taskStatus={task.status} back={back} />)}
</Section>
<section>
<h2>OpenSpec {task.openspecChange && <span className="mono muted">{task.openspecChange}</span>}</h2>
<Section title={<>OpenSpec {task.openspecChange && <span className="ml-1 font-mono text-xs font-normal text-muted-foreground">{task.openspecChange}</span>}</>}>
{artifacts?.length ? (
artifacts.map((a) => (
<details key={a.name} open={a.name === "proposal.md"}>
<summary className="mono">{a.name}</summary>
<pre className="md">{a.text}</pre>
</details>
<Disclosure key={a.name} open={a.name === "proposal.md"} summary={<span className="font-mono">{a.name}</span>}>
<pre className="m-0 max-h-[32em] overflow-auto font-mono text-xs leading-relaxed whitespace-pre-wrap">{a.text}</pre>
</Disclosure>
))
) : (
<p className="empty">Change ещё не создан.</p>
<Empty>Change ещё не создан.</Empty>
)}
</section>
<section>
<h2>События</h2>
<ul className="events">
{events.map((e) => (
<li key={e.id}>
<span className="muted">{ago(e.createdAt)}</span> <span className="mono">{e.type}</span>{" "}
{e.type === "progress" ? (e.payload as { text: string }).text : e.type === "task_updated" ? JSON.stringify((e.payload as { to: unknown }).to) : ""}
</li>
))}
</ul>
</section>
</Section>
</Workspace>
);
}

View File

@ -1,5 +1,4 @@
@import "tailwindcss";
@import "./legacy.css" layer(base);
/* Theme tokens (shadcn/ui naming): light in :root, dark — the default — in .dark (PEP-38). */
@custom-variant dark (&:where(.dark, .dark *));

View File

@ -1,132 +0,0 @@
/* Pre-PEP-38 page styles, imported into the `base` layer so Tailwind utilities win. Removed page by page in stage 2. */
a { color: var(--primary); text-decoration: none; }
a:hover { text-decoration: underline; }
h1 { font-size: 1.5rem; margin: 0 0 12px; display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
h2 { font-size: 1.1rem; margin: 28px 0 10px; }
.mono, code, pre { font-family: var(--font-mono); font-size: 0.9em; }
.muted { color: var(--muted-foreground); }
.empty { color: var(--muted-foreground); padding: 12px 0; }
h2 .more { font-size: 0.85rem; font-weight: 400; margin-left: 8px; }
.filters { display: flex; flex-wrap: wrap; gap: 6px; margin: 12px 0 4px; }
.filters a { padding: 4px 12px; border: 1px solid var(--border); border-radius: 999px; color: var(--foreground); background: var(--card); }
.filters a:hover { text-decoration: none; border-color: var(--muted-foreground); }
.filters a.active { border-color: var(--primary); box-shadow: inset 0 0 0 1px var(--primary); }
.session header.row { flex-wrap: wrap; row-gap: 2px; }
.session header .mono { white-space: nowrap; }
.session .title { flex: 1 1 12em; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.narrow { max-width: 560px; }
.crumbs { margin: 0 0 4px; color: var(--muted-foreground); }
.desc { white-space: pre-wrap; }
.card {
background: var(--card); border: 1px solid var(--border); border-radius: var(--radius);
padding: 14px 16px; margin: 10px 0;
}
.q { border-left: 4px solid var(--info); }
.q-approval { border-left-color: var(--primary); }
.q-permission { border-left-color: var(--warn); }
.q-attention { border-left-color: var(--ok); }
.q.answered { opacity: 0.7; border-left-color: var(--border); }
.kind { font-weight: 600; }
.qtext { white-space: pre-wrap; margin: 8px 0; max-height: 18em; overflow: auto; }
.attach { display: block; color: var(--muted-foreground); margin: 6px 0; overflow-x: auto; }
.count { background: var(--primary); color: var(--primary-foreground); border-radius: 999px; font-size: 0.8rem; padding: 1px 9px; }
.row { display: flex; gap: 8px; align-items: center; }
.row.wrap { flex-wrap: wrap; }
.grow { flex: 1; min-width: 0; }
.row > input[type=text] { flex: 1; min-width: 0; }
.stack { display: flex; flex-direction: column; gap: 12px; margin: 10px 0; }
label { display: flex; flex-direction: column; gap: 4px; font-weight: 500; }
label.inline { flex-direction: row; align-items: center; font-weight: 400; }
fieldset { border: 1px solid var(--border); border-radius: var(--radius); padding: 8px 12px; }
.answer { display: flex; flex-direction: column; gap: 8px; margin-top: 8px; }
input[type=text], textarea, select {
font: inherit; color: var(--foreground); background: var(--background);
border: 1px solid var(--border); border-radius: 8px; padding: 7px 10px; width: 100%;
}
input.short { width: 8em; }
textarea { resize: vertical; }
input:focus, textarea:focus, select:focus, button:focus-visible { outline: 2px solid var(--primary); outline-offset: 1px; }
button, .button {
font: inherit; cursor: pointer; border-radius: 8px; padding: 7px 14px;
border: 1px solid var(--border); background: var(--card); color: var(--foreground); white-space: nowrap;
display: inline-block;
}
button:hover, .button:hover { border-color: var(--muted-foreground); text-decoration: none; }
.primary { background: var(--primary); color: var(--primary-foreground); border-color: var(--primary); }
.danger { color: var(--danger); }
button.link { border: 0; background: none; padding: 0; color: var(--muted-foreground); }
.badge {
font-size: 0.75rem; font-weight: 600; border-radius: 999px; padding: 2px 9px;
background: var(--muted); color: var(--muted-foreground); white-space: nowrap;
}
.s-in_progress, .s-running { color: var(--info); }
.s-awaiting_approval, .s-waiting_input, .s-proposing { color: var(--primary); }
.s-review, .s-done { color: var(--ok); }
.s-blocked, .s-failed, .s-stalled, .s-rate_limited { color: var(--danger); }
.notice { background: color-mix(in srgb, var(--ok) 12%, var(--card)); border: 1px solid var(--ok); border-radius: var(--radius); padding: 10px 14px; }
.flash { background: color-mix(in srgb, var(--danger) 12%, var(--card)); border: 1px solid var(--danger); border-radius: var(--radius); padding: 10px 14px; }
ul.tasks, ul.projects, ul.events { list-style: none; padding: 0; margin: 0; }
ul.tasks li, ul.projects li {
display: flex; gap: 10px; align-items: center; justify-content: space-between;
padding: 8px 12px; background: var(--card); border: 1px solid var(--border); border-radius: 8px; margin: 6px 0;
}
ul.tasks li a, ul.projects li a { color: var(--foreground); min-width: 0; overflow: hidden; text-overflow: ellipsis; }
ul.events li { padding: 3px 0; border-bottom: 1px dashed var(--border); overflow-wrap: anywhere; }
details { margin: 8px 0; }
summary { cursor: pointer; color: var(--primary); }
pre.md {
white-space: pre-wrap; background: var(--muted); border-radius: 8px; padding: 12px;
max-height: 32em; overflow: auto;
}
.board { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; margin: 16px 0; }
.board.busy { opacity: 0.6; pointer-events: none; }
.col { background: color-mix(in srgb, var(--border) 35%, var(--background)); border-radius: var(--radius); padding: 8px; min-height: 120px; }
.col.over { outline: 2px dashed var(--primary); }
.col h3 { font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.04em; margin: 4px 4px 8px; color: var(--muted-foreground); }
.hint { font-size: 0.75rem; margin: -4px 4px 8px; }
.tcard { background: var(--card); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; margin: 6px 0; cursor: grab; display: flex; flex-direction: column; gap: 6px; }
.tcard a { color: var(--foreground); }
.tcard .goal { font-size: 0.75rem; flex-basis: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.small { font-size: 0.78rem; padding: 3px 8px; }
details.add { margin: 4px 0; }
.login { max-width: 420px; margin: 18vh auto; text-align: center; display: flex; flex-direction: column; gap: 14px; align-items: center; }
.login h1 { font-size: 2rem; justify-content: center; }
@media (max-width: 640px) {
.session form.grow { flex-basis: 100%; }
ul.tasks li { flex-direction: column; align-items: flex-start; }
.board { grid-template-columns: 1fr; }
}
.consent { text-align: left; align-items: stretch; }
.consent h1 { justify-content: flex-start; }
.scopes { margin: 0; padding-left: 20px; }
.mcp-url { display: block; padding: 10px 12px; background: var(--muted); border-radius: 8px; overflow-x: auto; }
.ok { background: color-mix(in srgb, var(--ok) 12%, var(--card)); border: 1px solid var(--ok); border-radius: var(--radius); padding: 10px 14px; }
.help ul { padding-left: 20px; }
.help li { margin: 4px 0; }
.say { margin: 6px 0; font-style: italic; }
table.tools { width: 100%; border-collapse: collapse; }
table.tools td { border-top: 1px solid var(--border); padding: 6px 8px; vertical-align: top; }
table.tools td.mono { white-space: nowrap; }
@media (max-width: 640px) { table.tools td.mono { white-space: normal; overflow-wrap: anywhere; } }
ul.members { list-style: none; padding: 0; margin: 0 0 10px; }
ul.members li { display: flex; gap: 10px; align-items: center; justify-content: space-between; padding: 6px 0; border-bottom: 1px dashed var(--border); }
dl.repo { display: grid; grid-template-columns: max-content 1fr; gap: 4px 14px; margin: 0 0 10px; }
dl.repo dt { color: var(--muted-foreground); }
dl.repo dd { margin: 0; }

View File

@ -1,7 +1,9 @@
import { redirect } from "next/navigation";
import { currentUser, safeNext } from "@/lib/auth";
import { Flash } from "@/components/ui";
import { Brand } from "@/components/Brand";
import { Flash } from "@/components/common";
import { Footer } from "@/components/Footer";
import { Button } from "@/components/ui/button";
export const dynamic = "force-dynamic";
@ -9,12 +11,16 @@ export default async function Login({ searchParams }: { searchParams: Promise<{
const { error, next } = await searchParams;
if (await currentUser()) redirect(safeNext(next));
return (
<main className="login">
<h1>🐷 Peppa</h1>
<p className="muted">Софтвейр-фабрика: проекты в Gitea, задачи по OpenSpec, агенты Claude Code и Codex.</p>
<Flash error={error} />
<a className="button primary" href={`/auth/start?next=${encodeURIComponent(safeNext(next))}`}>Войти через Gitea</a>
<Footer />
<main className="grid min-h-dvh place-items-center px-4">
<div className="flex w-full max-w-sm flex-col items-center gap-5 text-center">
<Brand large />
<p className="m-0 text-sm text-muted-foreground">Софтвейр-фабрика: проекты в Gitea, задачи по OpenSpec, агенты Claude Code и Codex.</p>
<Flash error={error} />
<Button asChild variant="default" size="lg" className="w-full">
<a href={`/auth/start?next=${encodeURIComponent(safeNext(next))}`}>Войти через Gitea</a>
</Button>
<Footer />
</div>
</main>
);
}

View File

@ -3,6 +3,9 @@ import { redirect } from "next/navigation";
import { currentUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { approve, deny } from "./actions";
import { Brand } from "@/components/Brand";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
export const dynamic = "force-dynamic";
@ -29,33 +32,35 @@ export default async function Authorize({ searchParams }: { searchParams: Promis
}
const host = p.redirect_uri ? new URL(p.redirect_uri).host : "";
return (
<main className="login consent">
<h1>🐷 Peppa</h1>
{error || !client ? (
<p className="flash">Запрос авторизации некорректен: {error}</p>
) : (
<>
<p>
<b>{client.name}</b> <span className="muted">({host})</span> просит доступ к Пеппе от имени <b>{user.login}</b>.
</p>
<ul className="scopes">
<li>видеть ваши проекты, цели, задачи и вопросы агентов;</li>
<li>создавать задачи и двигать карточки — перенос в «В работе» запускает агента;</li>
<li>отвечать на вопросы агентов и принимать ревью.</li>
</ul>
<p className="muted">Отозвать доступ можно в «Настройки → Подключённые приложения».</p>
<div className="row">
<form action={approve}>
<Hidden p={p} />
<button className="primary">Разрешить</button>
</form>
<form action={deny}>
<Hidden p={p} />
<button>Отклонить</button>
</form>
</div>
</>
)}
<main className="grid min-h-dvh place-items-center px-4">
<Card className="w-full max-w-md gap-4 p-6">
<Brand />
{error || !client ? (
<p role="alert" className="m-0 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm">Запрос авторизации некорректен: {error}</p>
) : (
<>
<p className="m-0 text-sm">
<b>{client.name}</b> <span className="text-muted-foreground">({host})</span> просит доступ к Пеппе от имени <b>{user.login}</b>.
</p>
<ul className="m-0 flex list-disc flex-col gap-1 pl-5 text-sm">
<li>видеть ваши проекты, цели, задачи и вопросы агентов;</li>
<li>создавать задачи и двигать карточки — перенос в «В работе» запускает агента;</li>
<li>отвечать на вопросы агентов и принимать ревью.</li>
</ul>
<p className="m-0 text-xs text-muted-foreground">Отозвать доступ можно в «Настройки → Подключённые приложения».</p>
<div className="flex gap-2">
<form action={approve}>
<Hidden p={p} />
<Button variant="default">Разрешить</Button>
</form>
<form action={deny}>
<Hidden p={p} />
<Button>Отклонить</Button>
</form>
</div>
</>
)}
</Card>
</main>
);
}

View File

@ -1,5 +1,5 @@
import Link from "next/link";
import { ago } from "@/components/ui";
import { ago } from "@/components/common";
import { requireUser } from "@/lib/auth";
import { activeSessions, inbox } from "@/lib/queries";
import { SESSION_STATUS, TONE_BG } from "@/lib/status";

View File

@ -3,6 +3,9 @@
import Link from "next/link";
import { useState, useTransition } from "react";
import { moveTaskCard } from "@/app/(app)/actions";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
export type Column = "backlog" | "in_progress" | "review" | "done";
export interface Card {
@ -13,13 +16,18 @@ export interface Card {
goal: string | null;
}
const COLUMNS: Array<{ id: Column; title: string; hint: string }> = [
{ id: "backlog", title: "Бэклог", hint: "" },
{ id: "in_progress", title: "В работе", hint: "сюда — запустить агента" },
{ id: "review", title: "Ревью", hint: "" },
{ id: "done", title: "Готово", hint: "" },
const COLUMNS: Array<{ id: Column; title: string; hint: string; dot: string }> = [
{ id: "backlog", title: "Бэклог", hint: "", dot: "bg-muted-foreground" },
{ id: "in_progress", title: "В работе", hint: "сюда — запустить агента", dot: "bg-info" },
{ id: "review", title: "Ревью", hint: "", dot: "bg-ok" },
{ id: "done", title: "Готово", hint: "", dot: "bg-ok" },
];
const STATUS: Record<string, string> = { proposing: "proposal", awaiting_approval: "ждёт PM", blocked: "блок", in_progress: "агент" };
const STATUS: Record<string, { label: string; tone: "primary" | "danger" | "info" }> = {
proposing: { label: "proposal", tone: "primary" },
awaiting_approval: { label: "ждёт PM", tone: "primary" },
blocked: { label: "блок", tone: "danger" },
in_progress: { label: "агент", tone: "info" },
};
const NEXT: Partial<Record<Column, { to: Column; label: string }>> = {
backlog: { to: "in_progress", label: "В работу →" },
review: { to: "done", label: "Принять ✓" },
@ -37,48 +45,59 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
start(() => moveTaskCard(f));
};
return (
<div className={`board${pending ? " busy" : ""}`}>
{COLUMNS.map((c) => (
<section
key={c.id}
className={`col${over === c.id ? " over" : ""}`}
onDragOver={(e) => {
e.preventDefault();
setOver(c.id);
}}
onDragLeave={() => setOver(null)}
onDrop={(e) => {
e.preventDefault();
setOver(null);
const key = e.dataTransfer.getData("text/plain");
const card = cards.find((x) => x.key === key);
if (card && card.column !== c.id) move(key, c.id);
}}
>
<h3>
{c.title} <span className="muted">{cards.filter((x) => x.column === c.id).length}</span>
</h3>
{c.hint && <p className="hint muted">{c.hint}</p>}
{cards
.filter((x) => x.column === c.id)
.map((card) => (
<article key={card.key} className="tcard" draggable onDragStart={(e) => e.dataTransfer.setData("text/plain", card.key)}>
<Link href={`/t/${card.key}`}>
<span className="mono">{card.key}</span> {card.title}
<div className={cn("grid gap-3 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-2 min-[1600px]:grid-cols-4", pending && "pointer-events-none opacity-60")}>
{COLUMNS.map((c) => {
const list = cards.filter((x) => x.column === c.id);
return (
<section
key={c.id}
aria-label={c.title}
className={cn("flex min-h-32 flex-col gap-2 rounded-lg border bg-muted/40 p-2", over === c.id && "border-dashed border-primary bg-primary/5")}
onDragOver={(e) => {
e.preventDefault();
setOver(c.id);
}}
onDragLeave={() => setOver(null)}
onDrop={(e) => {
e.preventDefault();
setOver(null);
const key = e.dataTransfer.getData("text/plain");
const card = cards.find((x) => x.key === key);
if (card && card.column !== c.id) move(key, c.id);
}}
>
<h3 className="m-0 flex items-center gap-2 px-1.5 pt-1 font-mono text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
<span className={cn("size-1.5 rounded-full", c.dot)} />
{c.title}
<span className="ml-auto tabular-nums">{list.length}</span>
</h3>
{c.hint && <p className="m-0 px-1.5 text-[11px] text-muted-foreground">{c.hint}</p>}
{list.map((card) => (
<article
key={card.key}
draggable
onDragStart={(e) => e.dataTransfer.setData("text/plain", card.key)}
className="flex cursor-grab flex-col gap-2 rounded-md border bg-card p-2.5 text-sm shadow-xs transition-colors hover:border-primary/40 active:cursor-grabbing"
>
<Link href={`/t/${card.key}`} className="text-foreground hover:no-underline">
<span className="font-mono text-xs text-primary">{card.key}</span> {card.title}
</Link>
<div className="row wrap">
{card.goal && <span className="goal muted">🎯 {card.goal}</span>}
{STATUS[card.status] && <span className={`badge s-${card.status}`}>{STATUS[card.status]}</span>}
{NEXT[c.id] && (
<button className="small" disabled={pending} onClick={() => move(card.key, NEXT[c.id]!.to)}>
{NEXT[c.id]!.label}
</button>
)}
</div>
{(card.goal || STATUS[card.status] || NEXT[c.id]) && (
<div className="flex flex-wrap items-center gap-1.5">
{card.goal && <span className="min-w-0 basis-full truncate text-xs text-muted-foreground">◎ {card.goal}</span>}
{STATUS[card.status] && <Badge variant={STATUS[card.status]!.tone}>{STATUS[card.status]!.label}</Badge>}
{NEXT[c.id] && (
<Button size="xs" className="ml-auto" disabled={pending} onClick={() => move(card.key, NEXT[c.id]!.to)}>
{NEXT[c.id]!.label}
</Button>
)}
</div>
)}
</article>
))}
</section>
))}
</section>
);
})}
</div>
);
}

View File

@ -0,0 +1,11 @@
/** Peppa mark: pink tile with a glow + mono word. */
export function Brand({ large = false }: { large?: boolean }) {
return (
<span className="flex items-center gap-2.5">
<span className={large ? "grid size-10 place-items-center rounded-lg bg-primary font-mono text-lg font-bold text-primary-foreground shadow-[0_0_28px_-4px_var(--primary)]" : "grid size-7 place-items-center rounded-md bg-primary font-mono text-sm font-bold text-primary-foreground shadow-[0_0_18px_-4px_var(--primary)]"}>
P
</span>
<span className={large ? "font-mono text-2xl font-semibold tracking-tight" : "font-mono text-[15px] font-semibold tracking-tight"}>peppa</span>
</span>
);
}

View File

@ -13,7 +13,7 @@ export function Footer() {
{commit && (
<>
{" · "}
<a href={`${loadEnv().GITEA_URL}/peppa-bot/peppa/commit/${full}`} className="mono">
<a href={`${loadEnv().GITEA_URL}/peppa-bot/peppa/commit/${full}`} className="font-mono text-primary">
{commit}
</a>
{dirty && <span title="Собрано с незакоммиченными изменениями"> +изменения</span>}

View File

@ -1,14 +1,18 @@
// Project page section «Ошибки» (PEP-58): connect Bugsink, incident policy, incidents list.
import { Bug, CircleCheck, EyeOff, Inbox, MapPin, Play } from "lucide-react";
import { INCIDENT_STATUS_RU, incidentPolicies, POLICY_RU, type ErrorSource, type Incident, type IncidentSettings } from "@peppa/core";
import { connectErrorTrackingAction, decideIncidentAction, resolveIncidentAction, saveIncidentSettings } from "@/app/(app)/actions";
import { ago } from "./ui";
import { Hidden } from "@/components/cards";
import { ago, Disclosure, Empty, Key, Section } from "@/components/common";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input, Label, NativeSelect, Textarea } from "@/components/ui/input";
const Hidden = ({ projectId, back }: { projectId: number; back: string }) => (
<>
<input type="hidden" name="projectId" value={projectId} />
<input type="hidden" name="back" value={back} />
</>
);
const STATUS_TONE: Record<Incident["status"], "danger" | "warn" | "info" | "ok" | "muted"> = { new: "danger", open: "warn", pending: "warn", task: "info", ignored: "muted", resolved: "ok", regressed: "danger" };
function Code({ children }: { children: React.ReactNode }) {
return <code className="block overflow-x-auto rounded-md bg-muted px-2.5 py-1.5 font-mono text-xs">{children}</code>;
}
export function IncidentsSection(props: {
projectId: number;
@ -24,138 +28,143 @@ export function IncidentsSection(props: {
const { projectId, back, settings: s } = props;
if (!s) {
return (
<section>
<h2>Ошибки</h2>
<p className="muted">Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят сюда и становятся задачами по политике проекта.</p>
<Section title="Ошибки">
<p className="m-0 text-sm text-muted-foreground">Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят сюда и становятся задачами по политике проекта.</p>
{props.isOwner ? (
<form action={connectErrorTrackingAction}>
<Hidden projectId={projectId} back={back} />
<button className="primary">Подключить отслеживание ошибок</button>
<Hidden fields={{ projectId, back }} />
<Button variant="default" size="sm">
<Bug />
Подключить отслеживание ошибок
</Button>
</form>
) : (
<p className="empty">Не подключено — подключает владелец проекта.</p>
<Empty>Не подключено — подключает владелец проекта.</Empty>
)}
</section>
</Section>
);
}
const active = props.incidents.filter((i) => !["ignored", "resolved"].includes(i.status));
const rest = props.incidents.filter((i) => ["ignored", "resolved"].includes(i.status));
return (
<section>
<h2>
Ошибки <span className="muted small">политика: {POLICY_RU[s.policy]}</span>
</h2>
{active.length === 0 ? <p className="empty">Открытых ошибок нет.</p> : active.map((i) => <IncidentCard key={i.id} i={i} {...props} />)}
<Section title="Ошибки" count={active.length} actions={<span className="text-xs text-muted-foreground">политика: {POLICY_RU[s.policy]}</span>}>
{active.length === 0 ? <Empty>Открытых ошибок нет.</Empty> : active.map((i) => <IncidentCard key={i.id} i={i} {...props} />)}
{rest.length > 0 && (
<details>
<summary>Исправленные и игнорируемые ({rest.length})</summary>
{rest.map((i) => (
<IncidentCard key={i.id} i={i} {...props} />
))}
</details>
<Disclosure summary={`Исправленные и игнорируемые (${rest.length})`}>
<div className="flex flex-col gap-2">
{rest.map((i) => (
<IncidentCard key={i.id} i={i} {...props} />
))}
</div>
</Disclosure>
)}
<details>
<summary>Настройки ошибок</summary>
<div className="stack">
<Disclosure summary="Настройки ошибок">
<div className="flex flex-col gap-3 text-sm">
{props.sources.map((src) => (
<div key={src.id}>
<b>DSN {src.kind === "web" ? "фронта (web)" : "бэка (api)"}</b>
<code className="mcp-url">{src.dsn}</code>
<div key={src.id} className="flex flex-col gap-1">
<span className="font-medium">DSN {src.kind === "web" ? "фронта (web)" : "бэка (api)"}</span>
<Code>{src.dsn}</Code>
</div>
))}
<p className="muted">
В коде: <code>{"NEXT_PUBLIC_SENTRY_DSN"}</code> / <code>SENTRY_DSN</code> из окружения, <code>release</code> = SHA деплоя, <code>environment</code> = prod, <code>sendDefaultPii: false</code>.
<p className="m-0 text-muted-foreground">
В коде: <code className="font-mono">NEXT_PUBLIC_SENTRY_DSN</code> / <code className="font-mono">SENTRY_DSN</code> из окружения, <code className="font-mono">release</code> = SHA деплоя,{" "}
<code className="font-mono">environment</code> = prod, <code className="font-mono">sendDefaultPii: false</code>.
</p>
{!s.webhookAuto && props.webhookUrl && (
<div>
<b>Вебхук не настроен автоматически.</b> В Bugsink: проект → Alerts → Custom webhook:
<code className="mcp-url">{props.webhookUrl}</code>
<span className="muted">Пока его нет, Пеппа опрашивает Bugsink раз в 2 минуты.</span>
<div className="flex flex-col gap-1">
<span><b>Вебхук не настроен автоматически.</b> В Bugsink: проект → Alerts → Custom webhook:</span>
<Code>{props.webhookUrl}</Code>
<span className="text-muted-foreground">Пока его нет, Пеппа опрашивает Bugsink раз в 2 минуты.</span>
</div>
)}
<form action={saveIncidentSettings} className="stack">
<Hidden projectId={projectId} back={back} />
<label>
Политика инцидентов{" "}
<select name="policy" defaultValue={s.policy} aria-label="Политика инцидентов">
<form action={saveIncidentSettings} className="flex flex-col gap-2.5">
<Hidden fields={{ projectId, back }} />
<Label>
Политика инцидентов
<NativeSelect name="policy" defaultValue={s.policy} aria-label="Политика инцидентов">
{incidentPolicies.map((p) => (
<option key={p} value={p}>
{p} — {POLICY_RU[p]}
</option>
))}
</select>
</label>
<textarea
</NativeSelect>
</Label>
<Textarea
name="triagePrompt"
rows={3}
defaultValue={s.triagePrompt ?? ""}
aria-label="Как принимать решение (для триажёра)"
placeholder="Как принимать решение (для политики triage): например, «падения оплаты — сразу в работу, косметику фронта — в бэклог, остальное спроси»"
/>
<div className="row">
<input type="text" name="environments" defaultValue={s.environments.join(", ")} aria-label="Окружения" placeholder="Окружения: prod, production" />
<input type="number" name="dailyLimit" min={0} defaultValue={s.dailyLimit} aria-label="Задач в сутки" style={{ width: "6em" }} />
<div className="flex gap-2">
<Input name="environments" defaultValue={s.environments.join(", ")} aria-label="Окружения" placeholder="Окружения: prod, production" />
<Input type="number" name="dailyLimit" min={0} defaultValue={s.dailyLimit} aria-label="Задач в сутки" className="w-24" />
</div>
<input type="text" name="ignorePattern" defaultValue={s.ignorePattern ?? ""} aria-label="Игнорировать по названию" placeholder="Игнорировать по названию (регэксп), например ResizeObserver loop" />
<button>Сохранить</button>
<Input name="ignorePattern" defaultValue={s.ignorePattern ?? ""} aria-label="Игнорировать по названию" placeholder="Игнорировать по названию (регэксп), например ResizeObserver loop" />
<Button size="sm" className="self-start">Сохранить</Button>
</form>
</div>
</details>
</section>
</Disclosure>
</Section>
);
}
function IncidentCard({ i, back, projectId, taskKeys }: { i: Incident; back: string; projectId: number; taskKeys: Map<number, string> }) {
const taskKey = i.taskId ? taskKeys.get(i.taskId) : null;
const decide = (action: string, label: string) => (
const decide = (action: string, label: string, icon: React.ReactNode) => (
<form action={decideIncidentAction}>
<Hidden projectId={projectId} back={back} />
<input type="hidden" name="incidentId" value={i.id} />
<input type="hidden" name="action" value={action} />
<button className="small">{label}</button>
<Hidden fields={{ projectId, back, incidentId: i.id, action }} />
<Button size="xs">
{icon}
{label}
</Button>
</form>
);
return (
<div className="card">
<div className="row">
<span className="badge">{INCIDENT_STATUS_RU[i.status]}</span>
<b className="grow">{i.title}</b>
<span className="muted small">{ago(i.lastSeen)}</span>
<article className="flex flex-col gap-1.5 rounded-lg border bg-card p-3.5 text-sm">
<div className="flex items-start gap-2">
<Badge variant={STATUS_TONE[i.status]}>{INCIDENT_STATUS_RU[i.status]}</Badge>
<b className="min-w-0 flex-1 font-mono text-[13px] font-medium [overflow-wrap:anywhere]">{i.title}</b>
<span className="shrink-0 font-mono text-xs text-muted-foreground">{ago(i.lastSeen)}</span>
</div>
<div className="muted small">
<div className="flex flex-wrap items-center gap-x-1.5 text-xs text-muted-foreground">
{i.source} · {i.environment ?? "—"} · релиз {i.lastRelease ?? "—"} · событий {i.events}
{i.culprit && <> · 📍 {i.culprit}</>}
{i.culprit && (
<span className="inline-flex items-center gap-1">
· <MapPin className="size-3" /> {i.culprit}
</span>
)}
{i.url && (
<>
{" · "}
<a href={i.url}>Bugsink</a>
· <a href={i.url} className="text-primary">Bugsink</a>
</>
)}
{taskKey && (
<>
{" · "}
<a href={`/t/${taskKey}`}>{taskKey}</a>
· <Key href={`/t/${taskKey}`}>{taskKey}</Key>
</>
)}
</div>
{i.decisionReason && <div className="muted small">{i.decidedBy === "triage" ? "🤖 " : ""}{i.decisionReason}</div>}
<div className="row">
{i.decisionReason && <div className="text-xs text-muted-foreground">{i.decidedBy === "triage" ? "🤖 " : ""}{i.decisionReason}</div>}
<div className="flex flex-wrap gap-1.5">
{!i.taskId && i.status !== "resolved" && (
<>
{decide("backlog", "📥 В бэклог")}
{decide("start", "▶️ В работу")}
{i.status !== "ignored" && decide("ignore", "🙈 Игнорировать")}
{decide("backlog", "В бэклог", <Inbox />)}
{decide("start", "В работу", <Play />)}
{i.status !== "ignored" && decide("ignore", "Игнорировать", <EyeOff />)}
</>
)}
{i.status !== "resolved" && i.status !== "ignored" && (
<form action={resolveIncidentAction} className="row">
<Hidden projectId={projectId} back={back} />
<input type="hidden" name="incidentId" value={i.id} />
<button className="small">✅ Исправлено</button>
<form action={resolveIncidentAction}>
<Hidden fields={{ projectId, back, incidentId: i.id }} />
<Button size="xs">
<CircleCheck />
Исправлено
</Button>
</form>
)}
</div>
</div>
</article>
);
}

View File

@ -3,6 +3,7 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Bot, FolderKanban, House, LifeBuoy, LogOut, Settings, type LucideIcon } from "lucide-react";
import { Brand } from "@/components/Brand";
import { ThemeToggle } from "@/components/ThemeToggle";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
@ -30,8 +31,7 @@ export function Sidebar({ login, avatarUrl, counts }: { login: string; avatarUrl
return (
<header className="sticky top-0 z-30 flex h-14 items-center gap-2 border-b bg-sidebar px-3 md:h-dvh md:flex-col md:items-stretch md:gap-1 md:border-r md:border-b-0 md:px-3 md:py-4">
<Link href="/" className="flex shrink-0 items-center gap-2 rounded-md px-1 text-foreground hover:no-underline md:mb-4 md:px-2">
<span className="grid size-7 place-items-center rounded-md bg-primary font-mono text-sm font-bold text-primary-foreground shadow-[0_0_18px_-4px_var(--primary)]">P</span>
<span className="font-mono text-[15px] font-semibold tracking-tight">peppa</span>
<Brand />
<span className="hidden font-mono text-[11px] text-muted-foreground md:inline">фабрика</span>
</Link>
<nav

View File

@ -0,0 +1,161 @@
// Domain cards shared by pages: agent questions, runners, project list.
import Link from "next/link";
import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square } from "lucide-react";
import type { Project, Question, SessionView } from "@peppa/core";
import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ago, Empty, Key, StatusBadge } from "@/components/common";
import { cn } from "@/lib/utils";
const KIND = {
approval: { label: "Одобрение proposal", icon: FileCheck, border: "border-l-primary" },
question: { label: "Вопрос", icon: CircleHelp, border: "border-l-info" },
permission: { label: "Разрешение", icon: ShieldQuestion, border: "border-l-warn" },
attention: { label: "Сессия ждёт тебя", icon: BellRing, border: "border-l-ok" },
} as const;
/** Hidden inputs of a server-action form. */
export function Hidden({ fields }: { fields: Record<string, string | number | null | undefined> }) {
return (
<>
{Object.entries(fields).map(([k, v]) => (v == null ? null : <input key={k} type="hidden" name={k} value={v} />))}
</>
);
}
export function QuestionCard({ q, taskKey, taskStatus, back, compact = false }: { q: Question; taskKey?: string | null; taskStatus?: string | null; back: string; compact?: boolean }) {
const review = q.kind === "attention" && taskStatus === "review";
const answered = !!q.answeredAt;
const k = KIND[q.kind];
const Icon = review ? CircleCheck : k.icon;
return (
<article id={`q-${q.id}`} className={cn("flex flex-col gap-2.5 rounded-lg border border-l-2 bg-card p-4", answered ? "border-l-border opacity-70" : k.border)}>
<header className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
<Icon className="size-4 text-muted-foreground" />
<span className="font-medium">{review ? "Готово к ревью" : k.label}</span>
{taskKey && <Key href={`/t/${taskKey}`}>{taskKey}</Key>}
<span className="ml-auto font-mono text-xs text-muted-foreground">
#{q.id} · {ago(q.createdAt)}
</span>
</header>
<p className={cn("m-0 overflow-auto text-sm whitespace-pre-wrap", compact ? "max-h-40" : "max-h-72")}>{q.text}</p>
{answered ? (
<p className="m-0 flex items-center gap-1.5 text-sm text-muted-foreground">
{q.answeredVia === "system" ? <Hourglass className="size-3.5" /> : <CircleCheck className="size-3.5 text-ok" />}
{q.answeredVia === "system" ? q.answer : `Ответ (${q.answeredVia}): ${q.answer}`}
</p>
) : (
<form action={answerQuestion} className="flex flex-col gap-2">
<Hidden fields={{ questionId: q.id, back }} />
<div className="flex flex-wrap gap-2">
{q.kind === "approval" && <Button name="choice" value="ок" variant="default" size="sm">Одобрить</Button>}
{q.kind === "permission" && (
<>
<Button name="choice" value="allow" variant="default" size="sm">Разрешить</Button>
<Button name="choice" value="always" size="sm">Всегда</Button>
<Button name="choice" value="deny" variant="destructive" size="sm">Запретить</Button>
</>
)}
{review && <Button name="choice" value="__accept" variant="default" size="sm">Принять</Button>}
{q.kind === "attention" && !review && <Button name="choice" value="Продолжай." variant="default" size="sm">Продолжай</Button>}
{(q.options ?? []).map((o) => (
<Button key={o} name="choice" value={o} size="sm">{o}</Button>
))}
</div>
{q.kind !== "permission" && (
<div className="flex gap-2">
<Input name="answer" placeholder={q.kind === "approval" || review ? "Замечание — вернёт на доработку" : "Свой ответ"} aria-label="Ответ" className="h-8" />
<Button size="sm">Ответить</Button>
</div>
)}
</form>
)}
</article>
);
}
/** Message / stop / resume controls of one runner. */
export function SessionActions({ s, back }: { s: SessionView; back: string }) {
const alive = !["done", "failed"].includes(s.status);
return (
<div className="flex flex-wrap gap-2">
{alive && (
<form action={messageSession} className="flex min-w-0 flex-[1_1_16rem] gap-2">
<Hidden fields={{ sessionId: s.id, back }} />
<Input name="text" placeholder="Сообщение в сессию" aria-label="Сообщение в сессию" className="h-8" />
<Button size="sm" aria-label="Отправить" title="Отправить">
<Send />
<span className="max-sm:hidden">Отправить</span>
</Button>
</form>
)}
{alive && (
<form action={stopTaskSession}>
<Hidden fields={{ sessionId: s.id, back }} />
<Button variant="destructive" size="sm">
<Square />
Остановить
</Button>
</form>
)}
{(!alive || ["rate_limited", "stalled"].includes(s.status)) && (
<form action={resumeTaskSession}>
<Hidden fields={{ sessionId: s.id, back }} />
<Button size="sm">
{alive ? <RotateCcw /> : <Play />}
Resume
</Button>
</form>
)}
</div>
);
}
export function AttachCommand({ name }: { name: string }) {
return <code className="block overflow-x-auto rounded-md bg-muted px-2.5 py-1.5 font-mono text-xs whitespace-nowrap text-muted-foreground">tmux attach -t {name}</code>;
}
export function SessionCard({ s, back, showTitle = false }: { s: SessionView; back: string; showTitle?: boolean }) {
return (
<article className="flex flex-col gap-2.5 rounded-lg border bg-card p-3.5">
<header className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
<StatusBadge status={s.status} kind="session" />
{s.taskKey ? <Key href={`/t/${s.taskKey}`}>{s.taskKey}</Key> : <Key href={`/p/${s.projectKey}`}>{s.projectKey}</Key>}
{showTitle && s.taskTitle && <span className="min-w-0 flex-[1_1_12em] truncate">{s.taskTitle}</span>}
<span className="ml-auto font-mono text-xs text-muted-foreground">
<Link href={`/runners?id=${s.id}`} className="text-muted-foreground hover:text-foreground">#{s.id}</Link> · {s.provider} · пок. {s.generation} · {ago(s.lastActivityAt)}
</span>
</header>
<AttachCommand name={s.tmuxName} />
<SessionActions s={s} back={back} />
</article>
);
}
export function ProjectList({ projects, userId }: { projects: Project[]; userId: number }) {
if (!projects.length)
return (
<Empty>
Проектов пока нет. <Link href="/projects/new" className="text-primary">Создать первый</Link>
</Empty>
);
return (
<ul className="m-0 grid list-none gap-2 p-0 sm:grid-cols-2">
{projects.map((p) => (
<li key={p.id}>
<Link href={`/p/${p.key}`} className="flex h-full flex-col gap-1 rounded-lg border bg-card px-4 py-3 text-foreground transition-colors hover:border-primary/50 hover:no-underline">
<span className="flex items-center gap-2">
<span className="rounded bg-muted px-1.5 font-mono text-xs text-primary">{p.key}</span>
<span className="min-w-0 truncate font-medium">{p.name}</span>
{p.ownerId !== userId && <span className="ml-auto rounded-full border px-2 text-[11px] text-muted-foreground">общий</span>}
</span>
<span className="truncate font-mono text-xs text-muted-foreground">
{p.giteaOwner}/{p.giteaRepo}
</span>
</Link>
</li>
))}
</ul>
);
}

View File

@ -0,0 +1,101 @@
// Page building blocks of the console (PEP-38): header, sections, empty states, status badges, alerts.
import Link from "next/link";
import type { ReactNode } from "react";
import { CircleAlert, CircleCheck } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { SESSION_STATUS, TASK_STATUS, TONE_BG } from "@/lib/status";
import { cn } from "@/lib/utils";
export function PageHeader({ title, crumbs, actions, children }: { title: ReactNode; crumbs?: ReactNode; actions?: ReactNode; children?: ReactNode }) {
return (
<header className="mb-6 flex flex-col gap-1.5">
{crumbs && <div className="flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">{crumbs}</div>}
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
<h1 className="m-0 flex min-w-0 flex-wrap items-center gap-2 text-xl font-semibold tracking-tight md:text-2xl">{title}</h1>
{actions && <div className="ml-auto flex flex-wrap items-center gap-2">{actions}</div>}
</div>
{children && <div className="text-sm text-muted-foreground">{children}</div>}
</header>
);
}
export function Section({ title, count, actions, children, className, id }: { title: ReactNode; count?: number; actions?: ReactNode; children: ReactNode; className?: string; id?: string }) {
return (
<section id={id} className={cn("mt-8 flex flex-col gap-3 first:mt-0", className)}>
<div className="flex flex-wrap items-center gap-2">
<h2 className="m-0 text-[15px] font-semibold">{title}</h2>
{count != null && count > 0 && <span className="rounded-full bg-primary px-2 font-mono text-[11px] leading-5 font-semibold text-primary-foreground tabular-nums">{count}</span>}
{actions && <div className="ml-auto flex items-center gap-2 text-sm">{actions}</div>}
</div>
{children}
</section>
);
}
export function MoreLink({ href, children }: { href: string; children: ReactNode }) {
return (
<Link href={href} className="text-xs text-muted-foreground hover:text-foreground">
{children} →
</Link>
);
}
export function Empty({ children }: { children: ReactNode }) {
return <p className="m-0 rounded-lg border border-dashed px-4 py-5 text-center text-sm text-muted-foreground">{children}</p>;
}
/** Monospace task/project key, optionally a link. */
export function Key({ children, href, className }: { children: ReactNode; href?: string; className?: string }) {
const cls = cn("font-mono text-[0.9em] whitespace-nowrap", href ? "text-primary hover:underline" : "text-muted-foreground", className);
return href ? <Link href={href} className={cls}>{children}</Link> : <span className={cls}>{children}</span>;
}
export function StatusBadge({ status, kind = "task" }: { status: string; kind?: "task" | "session" }) {
const s = (kind === "task" ? TASK_STATUS : SESSION_STATUS)[status] ?? { label: status, tone: "muted" as const };
return (
<Badge variant={s.tone}>
{kind === "session" && <span className={cn("size-1.5 rounded-full", TONE_BG[s.tone], status === "running" && "animate-pulse")} />}
{s.label}
</Badge>
);
}
export function Flash({ error }: { error?: string }) {
return error ? (
<p role="alert" className="mb-4 flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-foreground">
<CircleAlert className="mt-0.5 size-4 shrink-0 text-destructive" />
<span>{error}</span>
</p>
) : null;
}
export function Notice({ children }: { children: ReactNode }) {
return (
<div role="status" className="mb-4 flex flex-wrap items-center gap-2 rounded-lg border border-ok/40 bg-ok/10 px-4 py-3 text-sm">
<CircleCheck className="size-4 shrink-0 text-ok" />
{children}
</div>
);
}
/** Collapsible block styled as a card (native <details>: no client JS). */
export function Disclosure({ summary, children, open, className }: { summary: ReactNode; children: ReactNode; open?: boolean; className?: string }) {
return (
<details open={open} className={cn("group rounded-lg border bg-card", className)}>
<summary className="flex cursor-pointer list-none items-center gap-2 px-4 py-2.5 text-sm font-medium select-none [&::-webkit-details-marker]:hidden">
<span className="text-muted-foreground transition-transform group-open:rotate-90">›</span>
{summary}
</summary>
<div className="border-t px-4 py-3">{children}</div>
</details>
);
}
export function ago(d: Date | null | undefined): string {
if (!d) return "—";
const s = Math.round((Date.now() - d.getTime()) / 1000);
if (s < 60) return `${s} с назад`;
if (s < 3600) return `${Math.round(s / 60)} мин назад`;
if (s < 86400) return `${Math.round(s / 3600)} ч назад`;
return d.toLocaleDateString("ru-RU");
}

View File

@ -1,160 +0,0 @@
import Link from "next/link";
import type { ReactNode } from "react";
import type { Project, Question, SessionView } from "@peppa/core";
import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions";
const TASK_STATUS: Record<string, string> = {
backlog: "Бэклог",
proposing: "Proposal",
awaiting_approval: "Ждёт одобрения",
in_progress: "В работе",
review: "Ревью",
done: "Готово",
blocked: "Блок",
};
const SESSION_STATUS: Record<string, string> = {
starting: "запуск",
running: "работает",
waiting_input: "ждёт тебя",
idle: "простаивает",
stalled: "зависла?",
rate_limited: "лимит",
done: "завершена",
failed: "упала",
};
const KIND: Record<string, string> = { approval: "Одобрение proposal", question: "Вопрос", permission: "Разрешение", attention: "Сессия ждёт тебя" };
export function Badge({ status, kind = "task" }: { status: string; kind?: "task" | "session" }) {
const label = (kind === "task" ? TASK_STATUS : SESSION_STATUS)[status] ?? status;
return <span className={`badge s-${status}`}>{label}</span>;
}
export function Flash({ error }: { error?: string }) {
return error ? <p className="flash" role="alert">{error}</p> : null;
}
export function Notice({ children }: { children: ReactNode }) {
return <p className="notice" role="status">{children}</p>;
}
export function ago(d: Date | null | undefined): string {
if (!d) return "—";
const s = Math.round((Date.now() - d.getTime()) / 1000);
if (s < 60) return `${s} с назад`;
if (s < 3600) return `${Math.round(s / 60)} мин назад`;
if (s < 86400) return `${Math.round(s / 3600)} ч назад`;
return d.toLocaleDateString("ru-RU");
}
export function QuestionCard({ q, taskKey, taskStatus, back }: { q: Question; taskKey?: string | null; taskStatus?: string | null; back: string }) {
const review = q.kind === "attention" && taskStatus === "review";
const answered = !!q.answeredAt;
return (
<article className={`card q q-${q.kind}${answered ? " answered" : ""}`}>
<header className="row">
<span className="kind">{review ? "Готово к ревью" : KIND[q.kind]}</span>
{taskKey && (
<Link href={`/t/${taskKey}`} className="mono">
{taskKey}
</Link>
)}
<span className="muted">#{q.id} · {ago(q.createdAt)}</span>
</header>
<p className="qtext">{q.text}</p>
{answered ? (
<p className="muted">
{q.answeredVia === "system" ? "⌛ " : "✅ "}
{q.answeredVia === "system" ? q.answer : `Ответ (${q.answeredVia}): ${q.answer}`}
</p>
) : (
<form action={answerQuestion} className="answer">
<input type="hidden" name="questionId" value={q.id} />
<input type="hidden" name="back" value={back} />
<div className="row wrap">
{q.kind === "approval" && <button name="choice" value="ок" className="primary">Одобрить</button>}
{q.kind === "permission" && (
<>
<button name="choice" value="allow" className="primary">Разрешить</button>
<button name="choice" value="always">Всегда</button>
<button name="choice" value="deny" className="danger">Запретить</button>
</>
)}
{review && <button name="choice" value="__accept" className="primary">Принять</button>}
{q.kind === "attention" && !review && <button name="choice" value="Продолжай." className="primary">Продолжай</button>}
{(q.options ?? []).map((o) => (
<button key={o} name="choice" value={o}>{o}</button>
))}
</div>
{q.kind !== "permission" && (
<div className="row">
<input type="text" name="answer" placeholder={q.kind === "approval" || review ? "Замечание — вернёт на доработку" : "Свой ответ"} aria-label="Ответ" />
<button>Ответить</button>
</div>
)}
</form>
)}
</article>
);
}
export function SessionCard({ s, back, showTitle = false }: { s: SessionView; back: string; showTitle?: boolean }) {
const alive = !["done", "failed"].includes(s.status);
return (
<article className="card session">
<header className="row">
<Badge status={s.status} kind="session" />
{s.taskKey ? <Link href={`/t/${s.taskKey}`} className="mono">{s.taskKey}</Link> : <Link href={`/p/${s.projectKey}`} className="mono">{s.projectKey}</Link>}
{showTitle && s.taskTitle && <span className="title">{s.taskTitle}</span>}
<span className="muted">#{s.id} · {s.provider} · поколение {s.generation} · {ago(s.lastActivityAt)}</span>
</header>
<code className="attach">tmux attach -t {s.tmuxName}</code>
<div className="row wrap">
{alive && (
<form action={messageSession} className="row grow">
<input type="hidden" name="sessionId" value={s.id} />
<input type="hidden" name="back" value={back} />
<input type="text" name="text" placeholder="Сообщение в сессию" aria-label="Сообщение в сессию" />
<button>Отправить</button>
</form>
)}
{alive ? (
<form action={stopTaskSession}>
<input type="hidden" name="sessionId" value={s.id} />
<input type="hidden" name="back" value={back} />
<button className="danger">Остановить</button>
</form>
) : null}
{(!alive || ["rate_limited", "stalled"].includes(s.status)) && (
<form action={resumeTaskSession}>
<input type="hidden" name="sessionId" value={s.id} />
<input type="hidden" name="back" value={back} />
<button>Resume</button>
</form>
)}
</div>
</article>
);
}
export function ProjectList({ projects, userId }: { projects: Project[]; userId: number }) {
if (!projects.length)
return (
<p className="empty">
Проектов пока нет. <Link href="/projects/new">Создать первый</Link>
</p>
);
return (
<ul className="projects">
{projects.map((p) => (
<li key={p.id}>
<Link href={`/p/${p.key}`}>
<span className="mono">{p.key}</span> {p.name}
</Link>
<span className="muted">
{p.ownerId !== userId && <span className="badge">общий</span>} {p.giteaOwner}/{p.giteaRepo}
</span>
</li>
))}
</ul>
);
}

View File

@ -2,10 +2,10 @@
// column, runners in every status (one hit the usage limit and resumes later), open questions, releases.
// Only for a throwaway database — refuses the production one:
// DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa_ui tsx apps/web/scripts/mock-ui-seed.ts [login]
import { mkdirSync } from "node:fs";
import { mkdirSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createDb, events, goals, projects, questions, releases, sessions, tasks, users } from "@peppa/db";
import { checkRuns, createDb, errorSources, events, goals, incidents, incidentSettings, projects, questions, releases, sessions, tasks, users } from "@peppa/db";
import { eq } from "drizzle-orm";
const url = process.env.DATABASE_URL ?? "";
@ -19,7 +19,9 @@ const ws = join(tmpdir(), "peppa-mock-ui");
const [user] = await db.insert(users).values({ giteaId: -900001, login }).onConflictDoUpdate({ target: users.login, set: { login } }).returning();
async function project(key: string, name: string, slug: string) {
mkdirSync(join(ws, slug), { recursive: true });
mkdirSync(join(ws, slug, ".peppa"), { recursive: true });
const checks = { typecheck: "pnpm typecheck", test: "pnpm test", build: "pnpm build" };
writeFileSync(join(ws, slug, ".peppa", "project.json"), JSON.stringify({ key, slug, checks }));
const [p] = await db
.insert(projects)
.values({ key, name, slug, giteaOwner: login, giteaRepo: slug, workspacePath: join(ws, slug), ownerId: user!.id })
@ -108,5 +110,22 @@ await db.insert(releases).values([
{ projectId: pay.id, env: "staging", sha: "a1b2c3d4e5f6", status: "healthy", host: "mock-payments-staging.telecom.quest", tasks: ["PAY-6"], deployedBy: "ci" },
{ projectId: pay.id, env: "prod", sha: "9f8e7d6c5b4a", status: "healthy", host: "mock-payments-prod.telecom.quest", tasks: ["PAY-5"], deployedBy: login },
]);
// CI of PAY-1 (one red check with a log tail) and PAY-4 (green), PEP-57.
await db.insert(checkRuns).values([
...["typecheck", "build"].map((check) => ({ projectId: pay.id, taskId: pt[0]!.id, sha: "c0ffee1234", check, state: "success" as const })),
{ projectId: pay.id, taskId: pt[0]!.id, sha: "c0ffee1234", check: "test", state: "failure" as const, logTail: "FAIL src/webhook.test.ts\n ✕ marks the payment paid (12 ms)\n expected 'paid', got 'pending'" },
...["typecheck", "test", "build"].map((check) => ({ projectId: pay.id, taskId: pt[3]!.id, sha: "beef5678", check, state: "success" as const })),
]);
// Error tracking (PEP-58): settings, DSNs, an open incident, one with a task, one ignored.
await db.insert(incidentSettings).values({ projectId: pay.id, hookSecret: "mock-hook-secret", policy: "ask", webhookAuto: false });
await db.insert(errorSources).values([
{ projectId: pay.id, kind: "web", bugsinkProjectId: 9001, dsn: "https://mock-key@bugsink.example/9001" },
{ projectId: pay.id, kind: "api", bugsinkProjectId: 9002, dsn: "https://mock-key@bugsink.example/9002" },
]);
await db.insert(incidents).values([
{ projectId: pay.id, source: "web", bugsinkIssueId: "mock-1", title: "TypeError: Cannot read properties of undefined (reading 'amount')", culprit: "PaymentForm.tsx in submit", environment: "prod", lastRelease: "9f8e7d6", events: 14, firstSeen: ago(300), lastSeen: ago(6), status: "pending", decidedBy: "triage", decisionReason: "Падает оплата у части пользователей — нужен PM" },
{ projectId: pay.id, source: "api", bugsinkIssueId: "mock-2", title: "TimeoutError: YooKassa did not answer in 10s", environment: "prod", events: 3, firstSeen: ago(900), lastSeen: ago(90), status: "task", taskId: pt[4]!.id },
{ projectId: pay.id, source: "web", bugsinkIssueId: "mock-3", title: "ResizeObserver loop limit exceeded", environment: "prod", events: 120, firstSeen: ago(5000), lastSeen: ago(30), status: "ignored" },
]);
console.log(`seeded: user ${login}, projects PAY and SHOP, ${made.length} runners`);
process.exit(0);

View File

@ -8,12 +8,12 @@
- [x] 1.5 Старый CSS в слое `base`, все маршруты открываются; проверка в браузере (desktop + 390 px)
## 2. Перенос страниц (PR 2)
- [ ] 2.1 Общие: QuestionCard, SessionCard, Badge, Flash/Notice, ProjectList, Footer
- [ ] 2.2 Главная, Проекты, Новый проект
- [ ] 2.3 Проект: доска, задачи/цели, релизы (PEP-57), ошибки (PEP-58), участники, репозиторий
- [ ] 2.4 Задача: проверки (PEP-57), сессии, вопросы, OpenSpec, события
- [ ] 2.5 Настройки, Помощь, вход, согласие OAuth
- [ ] 2.6 Удалить `globals.css`/`legacy.css`; проверка всех страниц в браузере
- [x] 2.1 Общие: QuestionCard, SessionCard, Badge, Flash/Notice, ProjectList, Footer
- [x] 2.2 Главная, Проекты, Новый проект
- [x] 2.3 Проект: доска, задачи/цели, релизы (PEP-57), ошибки (PEP-58), участники, репозиторий
- [x] 2.4 Задача: проверки (PEP-57), сессии, вопросы, OpenSpec, события
- [x] 2.5 Настройки, Помощь, вход, согласие OAuth
- [x] 2.6 Удалить `globals.css`/`legacy.css`; проверка всех страниц в браузере
## 3. Пульт раннеров (PR 3)
- [ ] 3.1 Фильтры-счётчики, поиск `?q=`, строки со статусом и подсветкой