PEP-32/33/37: story page tabs, live agent step feed, SSE live updates instead of 5 s polling
- PEP-37: change hub (runner/live.ts) woken by notify() (new 'web' subscriber) and PRAGMA data_version; per-scope fingerprints; GET /api/live SSE (no-transform, ping 15 s); LiveRefresh replaces AutoRefresh with a connection indicator and polling fallback - PEP-33: async PostToolUse/PostToolUseFailure hook -> 'step' events (last 200 per session), AgentSteps live feed on the story page and runner panel, tasks.md progress on board cards and the story header - PEP-32: story page header + tabs Proposal/Design/Specs/Tasks/Comments/Tests/Merge request/Activity, safe Markdown renderer, PM comments visible in get_task, edit title/description/epic, accept-and-merge (acceptStory) - OpenSpec changes archived; specs live-updates, agent-steps, story-page Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
e3ed7bc367
commit
4a80d9dc6b
@ -6,7 +6,7 @@
|
||||
Текущее состояние и порядок работ: `docs/HANDOFF.md`.
|
||||
|
||||
## Структура
|
||||
- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): UI-пульт (PEP-38): Tailwind v4 + компоненты shadcn/ui в `components/ui/*` (исходники в репо), lucide-react, шрифты `geist`, токены темы в `app/app.css` (тёмная по умолчанию, cookie `peppa_theme`); раскладка — `Sidebar` слева (счётчики «ждут тебя» из `navCounts`), страница рисует центр и правую панель через `<Workspace aside>` (по умолчанию `ActivityAside`); демо-данные для проверки UI — `apps/web/scripts/mock-ui-seed.ts` в отдельную БД; вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Подписки (только суперадмин) · Помощь; проект как в GitHub (PEP-66): вкладки Доска (фильтр `?epic=`) · Код (`repoOverview`: README, ветки, коммиты из Gitea, кэш минута) · Спеки (`listSpecs`, `openspec/specs` рабочей копии) · PR (`openPulls` + `taskCiSummary`) · Релизы · Баги · Сессии (`?tab=`), «+ Стори» и «⋯ Настройки проекта» (репозиторий, эпики, настройки багов, участники); стори (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. **Слова**: задачи Пеппы в интерфейсе — «стори» (одна стори = один OpenSpec change; «задачи» — пункты tasks.md), цели — «эпики» (метки стори; хранятся в таблице `goals`, `tasks.goal_id`; MCP `*_epic(s)`/`epic_id`, `*_goal(s)`/`goal_id` — алиасы); имена MCP-инструментов и кода (`create_task`, `tasks`) не меняем. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. До запуска веб — `next dev` из рабочей копии (ниже)
|
||||
- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): UI-пульт (PEP-38): Tailwind v4 + компоненты shadcn/ui в `components/ui/*` (исходники в репо), lucide-react, шрифты `geist`, токены темы в `app/app.css` (тёмная по умолчанию, cookie `peppa_theme`); раскладка — `Sidebar` слева (счётчики «ждут тебя» из `navCounts`), страница рисует центр и правую панель через `<Workspace aside>` (по умолчанию `ActivityAside`); демо-данные для проверки UI — `apps/web/scripts/mock-ui-seed.ts` в отдельную БД; вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Подписки (только суперадмин) · Помощь; проект как в GitHub (PEP-66): вкладки Доска (фильтр `?epic=`) · Код (`repoOverview`: README, ветки, коммиты из Gitea, кэш минута) · Спеки (`listSpecs`, `openspec/specs` рабочей копии) · PR (`openPulls` + `taskCiSummary`) · Релизы · Баги · Сессии (`?tab=`), «+ Стори» и «⋯ Настройки проекта» (репозиторий, эпики, настройки багов, участники); стори (PEP-32): шапка (статус, эпик, прогресс tasks.md, «Изменить» — название/описание/эпик, агент и живая сессия с терминалом и лентой шагов) и вкладки `?tab=` Proposal · Design (свой безопасный рендер `components/Markdown.tsx`) · Specs (дельта-спеки change) · Tasks · Comments (вопросы + комментарии PM: событие `pm_comment`, агент видит в `get_task`, флажок «Отправить агенту сейчас») · Tests · Merge request («Принять и смержить» = `acceptStory` в runner/flow.ts) · Activity (с авторами: `payload.login` / сессия / система); change читает `core/openspec.ts` (`readChange`, `parseTasks`, `taskProgress`, и архивный); новый проект. **Живые страницы (PEP-37)**: `LiveRefresh` (вместо `AutoRefresh`, он остался только у подписок) слушает SSE `GET /api/live?scope=home|runners|project:<id>|task:<id>|steps:<sessionId>` и делает `router.refresh()` (ждёт, пока пользователь печатает), индикатор связи, откат на опрос 5 с; хаб `runner/live.ts` (`globalThis`) будят `notify()` (подписчик `web`, сокет `$PEPPA_HOME/web.events.sock`) и `PRAGMA data_version` + `total_changes()` раз в секунду, отпечаток области — один SQL без `last_activity_at`/шагов; заголовки `no-cache, no-transform`, `X-Accel-Buffering: no`, пинг 15 с **Слова**: задачи Пеппы в интерфейсе — «стори» (одна стори = один OpenSpec change; «задачи» — пункты tasks.md), цели — «эпики» (метки стори; хранятся в таблице `goals`, `tasks.goal_id`; MCP `*_epic(s)`/`epic_id`, `*_goal(s)`/`goal_id` — алиасы); имена MCP-инструментов и кода (`create_task`, `tasks`) не меняем. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. До запуска веб — `next dev` из рабочей копии (ниже)
|
||||
- `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка у каждого пользователя своя: веб «Настройки → Telegram» (или `peppa telegram pair <login>`), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (PEP-2). Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта
|
||||
- `packages/db` — Drizzle-схема и клиент: **SQLite** (`node:sqlite`, WAL) в файле `PEPPA_DB` (по умолчанию `~/.peppa/peppa.db`); каждый процесс открывает файл сам (`busy_timeout` первой командой, `BEGIN IMMEDIATE`). Прослойка `src/client.ts` даёт сессии drizzle `better-sqlite3` API `node:sqlite`. **Транзакции только синхронные** (`db.transaction((tx) => …)` без `await`; async-колбэк драйвер отклоняет). JSON-поля — `json_extract`/`json_each`, не `->>`/`@>`. Миграции — `drizzle-kit generate` (`packages/db/migrations`, база 0000), применение — `peppa db migrate` (PEP-36)
|
||||
- `packages/shared` — env, ключи задач (`PEP-42`)
|
||||
@ -17,6 +17,7 @@
|
||||
- `packages/cli` — CLI `peppa` (project/goal/task/q), пока нет веба
|
||||
- `packages/runner` — запуск claude в tmux (`peppa-<task>-s<id>`), вачдог, `peppa-hook`
|
||||
- Терминал в вебе (PEP-9): `runner/terminal.ts` — `TerminalFeed` опрашивает pane (`capture-pane -e` + `display-message`, 250 мс, один цикл на раннер для всех зрителей, `globalThis`), шлёт изменившиеся строки и ушедшие в историю; `terminalInput` (`send-keys -H` / `paste-buffer -p`; только владелец/участник, живая сессия, ≤1 КБ нажатий / 64 КБ вставки, 40 запросов за 5 с, сброс `auto_nudges`, событие `terminal_input` раз в минуту). Веб: `GET/POST /api/runners/<id>/terminal` (SSE + JSON, пинг 15 с для Cloudflare), `components/RunnerTerminal.tsx` (xterm.js); pane браузер не ресайзит
|
||||
- Шаги агента (PEP-33): хуки `PostToolUse`/`PostToolUseFailure` с `async: true` → `peppa-hook tool-use` → `recordStep` (core/steps.ts: событие `step` `{tool, kind, text, ok}`, последние 200 на сессию, `last_activity_at` без `notify()`); шаги исключены из журнала стори, `get_task` и «Событий» раннера; лента — `components/AgentSteps.tsx` (у живой сессии на странице стори и в панели раннера, новые шаги — событием `step` из `/api/live?scope=steps:<id>`); прогресс tasks.md («7/12» и текущий пункт) — на карточках доски «В работе» и в шапке стори. Codex/OpenCode шагов не шлют
|
||||
- хуки не в репо проекта, а в генерируемом `~/.peppa/runs/s<id>-g<gen>/settings.json` (`claude --settings`)
|
||||
- `PEPPA_SESSION_ID` + `PEPPA_GENERATION`: хук из старого поколения (до resume) игнорируется
|
||||
- PermissionRequest и AskUserQuestion блокируют и ждут ответ PM из БД (`PEPPA_HOOK_WAIT_SEC`, 540с), потом откат на диалог в терминале; `questions.awaiting_hook` не даёт ответу уйти ещё и в tmux
|
||||
|
||||
@ -38,10 +38,13 @@ import {
|
||||
sendWebPush,
|
||||
setNotifyPrefs,
|
||||
userPushSubscriptions,
|
||||
addStoryComment,
|
||||
updateTask,
|
||||
listSessions,
|
||||
} from "@peppa/core";
|
||||
import { bugsinkFromEnv } from "@peppa/bugsink";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner";
|
||||
import { acceptStory, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { requireUser } from "@/lib/auth";
|
||||
@ -123,6 +126,44 @@ export async function editEpic(f: FormData) {
|
||||
});
|
||||
}
|
||||
|
||||
/** Story page (PEP-32): title, description and epic from the web; no agent is started. */
|
||||
export async function editStoryAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
await attempt(f, async () => {
|
||||
const ref = await resolveTask(db, str(f, "taskKey"));
|
||||
await projectForUser(db, user.id, ref.project.id);
|
||||
const title = str(f, "title");
|
||||
if (title.length < 2) throw new PeppaError("Нужно название стори");
|
||||
const epic = str(f, "epicId");
|
||||
await updateTask(db, ref, { title, description: String(f.get("description") ?? "").trim(), goalId: epic ? Number(epic) : null }, undefined, user.login);
|
||||
});
|
||||
}
|
||||
|
||||
/** PM comment on a story (PEP-32): the agent sees it in get_task; optionally typed into the live runner. */
|
||||
export async function commentStoryAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
await attempt(f, async () => {
|
||||
const ref = await resolveTask(db, str(f, "taskKey"));
|
||||
await projectForUser(db, user.id, ref.project.id);
|
||||
const c = await addStoryComment(db, ref, user, String(f.get("text") ?? ""));
|
||||
if (str(f, "toAgent")) {
|
||||
const [live] = await listSessions(db, { active: true, taskId: ref.task.id });
|
||||
if (!live) throw new PeppaError("Комментарий сохранён, но живой сессии нет — агент увидит его в get_task");
|
||||
await sendToSession(db, live.id, `Комментарий PM (${user.login}) к ${ref.key}:\n${c.text}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** «Принять и смержить» on the story's merge request tab (PEP-32): the same gate as «Принять». */
|
||||
export async function acceptStoryAction(f: FormData) {
|
||||
const user = await requireUser();
|
||||
await attempt(f, async () => {
|
||||
const ref = await resolveTask(db, str(f, "taskKey"));
|
||||
await projectForUser(db, user.id, ref.project.id);
|
||||
await acceptStory(db, ref, "web");
|
||||
});
|
||||
}
|
||||
|
||||
export async function startTaskSession(f: FormData) {
|
||||
const user = await requireUser();
|
||||
await attempt(f, async () => {
|
||||
|
||||
@ -8,7 +8,7 @@ const TOOLS: Array<[string, string]> = [
|
||||
["create_project", "новый проект: репозиторий в Gitea (публичный по умолчанию или приватный) + шаблон + OpenSpec, или подключить существующий; отвечает ссылкой на репозиторий и кто его видит"],
|
||||
["list_epics / create_epic / update_epic", "эпики проекта (метки стори): завести, переименовать, описать, завершить или убрать в архив; list_goals / create_goal / update_goal — старые имена, работают так же"],
|
||||
["list_tasks", "доска проекта: Бэклог / В работе / Ревью / Готово"],
|
||||
["get_task", "карточка стори: описание, эпик, статус, OpenSpec, проверки, вопросы, прогресс"],
|
||||
["get_task", "карточка стори: описание, эпик, статус, OpenSpec, проверки, вопросы, комментарии PM, прогресс"],
|
||||
["create_task / update_task", "завести стори (в Бэклог, с эпиком epic_id); поправить название, описание, эпик"],
|
||||
["move_task", "передвинуть карточку; «В работе» запускает агента, «Бэклог»/«Готово» останавливают"],
|
||||
["set_project_visibility", "сделать репозиторий проекта публичным или приватным (только владелец); отвечает новой видимостью и кто видит репозиторий"],
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { ExternalLink, Plus, Rocket } from "lucide-react";
|
||||
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, repoOverview, type Release } from "@peppa/runner";
|
||||
import { getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
||||
import { AutoRefresh } from "@/components/AutoRefresh";
|
||||
import { taskProgress, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { PanelSection } from "@/components/ActivityAside";
|
||||
import { Board, type Card } from "@/components/Board";
|
||||
import { Hidden, SessionCard } from "@/components/cards";
|
||||
@ -98,13 +98,18 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
const epicTitle = new Map(epics.map((e) => [e.id, e.title]));
|
||||
const cards: Card[] = tasks
|
||||
.filter((t) => !epicFilter || t.goalId === epicFilter.id)
|
||||
.map((t) => ({
|
||||
key: `${p.key}-${t.number}`,
|
||||
title: t.title,
|
||||
status: t.status,
|
||||
column: columnOf(t.status),
|
||||
epic: t.goalId ? (epicTitle.get(t.goalId) ?? null) : null,
|
||||
}));
|
||||
.map((t) => {
|
||||
const pr = columnOf(t.status) === "in_progress" ? taskProgress(p, t.openspecChange) : null;
|
||||
return {
|
||||
key: `${p.key}-${t.number}`,
|
||||
title: t.title,
|
||||
status: t.status,
|
||||
column: columnOf(t.status),
|
||||
epic: t.goalId ? (epicTitle.get(t.goalId) ?? null) : null,
|
||||
// PEP-33: tasks.md progress of stories in work.
|
||||
progress: pr && { done: pr.done, total: pr.total, current: pr.current },
|
||||
};
|
||||
});
|
||||
// Gitea and the working copy are read only for the open tab.
|
||||
const [code, pulls] = await Promise.all([tab === "code" ? repoOverview(db, p) : null, tab === "pulls" ? openPulls(db, p) : null]);
|
||||
const specs = tab === "specs" ? listSpecs(p) : [];
|
||||
@ -284,7 +289,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
|
||||
return (
|
||||
<Workspace aside={null} wide>
|
||||
<AutoRefresh />
|
||||
<LiveRefresh scope={`project:${p.id}`} />
|
||||
<Flash error={error} />
|
||||
{created && !error && (
|
||||
<Notice>
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { listUserProjects } from "@peppa/core";
|
||||
import { AutoRefresh } from "@/components/AutoRefresh";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { ActivityAside } from "@/components/ActivityAside";
|
||||
import { ProjectList, QuestionCard, SessionCard } from "@/components/cards";
|
||||
import { Empty, Flash, MoreLink, PageHeader, Section } from "@/components/common";
|
||||
@ -14,7 +14,7 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e
|
||||
const [items, sessions, projects] = await Promise.all([inbox(user.id), activeSessions(user.id), listUserProjects(db, user.id)]);
|
||||
return (
|
||||
<Workspace aside={<ActivityAside questions={false} />}>
|
||||
<AutoRefresh />
|
||||
<LiveRefresh scope="home" />
|
||||
<Flash error={error} />
|
||||
<PageHeader title="Главная">{items.length ? "Агенты ждут твоего решения — ответь здесь, в Telegram или через MCP." : "Всё идёт само: агентам от тебя ничего не нужно."}</PageHeader>
|
||||
<Section title="Вопросы агентов" count={items.length}>
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import Link from "next/link";
|
||||
import { Search } from "lucide-react";
|
||||
import { listUserSessions, RUNNER_FILTERS, type RunnerFilter, type SessionView } from "@peppa/core";
|
||||
import { AutoRefresh } from "@/components/AutoRefresh";
|
||||
import { listUserSessions, RUNNER_FILTERS, sessionSteps, type RunnerFilter, type SessionView } from "@peppa/core";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { Empty, Flash, PageHeader } from "@/components/common";
|
||||
import { RunnerDetails, RunnerRow } from "@/components/RunnerConsole";
|
||||
import { Input } from "@/components/ui/input";
|
||||
@ -52,12 +52,12 @@ export default async function Runners({ searchParams }: { searchParams: Promise<
|
||||
const selected = (id && all.find((s) => s.id === Number(id))) || shown[0];
|
||||
const back = url({ ...base, id: selected?.id });
|
||||
const aside = selected ? (
|
||||
<RunnerDetails s={selected} questions={asking.get(selected.id) ?? []} events={await sessionEvents(selected.id)} back={back} closeHref={url(base)} chosen={!!id} />
|
||||
<RunnerDetails s={selected} questions={asking.get(selected.id) ?? []} events={await sessionEvents(selected.id)} steps={await sessionSteps(db, selected.id)} back={back} closeHref={url(base)} chosen={!!id} />
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<Workspace aside={aside} asideWideOnly={!id}>
|
||||
<AutoRefresh />
|
||||
<LiveRefresh scope="runners" />
|
||||
<Flash error={error} />
|
||||
<PageHeader title="Раннеры">Агенты в tmux по стори твоих и общих проектов: кто ждёт тебя, кто работает, что готово.</PageHeader>
|
||||
<div className="mb-3 flex flex-col gap-3 lg:flex-row lg:items-center">
|
||||
|
||||
@ -1,97 +1,117 @@
|
||||
// Story page (PEP-32): header with the story, the agent and its live session; tabs by the
|
||||
// OpenSpec artifacts and the course of work (?tab=). Live updates — PEP-37, agent steps — PEP-33.
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { CircleCheck, CircleX, GitPullRequest, Hourglass, Play } from "lucide-react";
|
||||
import { FINISHED_SESSION_STATUSES, getEpic, isSuperadmin, latestReview, listPools, listSubscriptions, projectPool, PROVIDER_NAMES, reviewLabel, taskCiSummary } from "@peppa/core";
|
||||
import { AutoRefresh } from "@/components/AutoRefresh";
|
||||
import { CircleCheck, CircleX, GitPullRequest, Hourglass, Pencil, Play } from "lucide-react";
|
||||
import {
|
||||
FINISHED_SESSION_STATUSES,
|
||||
getEpic,
|
||||
isSuperadmin,
|
||||
latestReview,
|
||||
listEpics,
|
||||
listPools,
|
||||
listSubscriptions,
|
||||
parseTasks,
|
||||
prGate,
|
||||
projectPool,
|
||||
PROVIDER_NAMES,
|
||||
readChange,
|
||||
reviewLabel,
|
||||
sessionSteps,
|
||||
storyComments,
|
||||
taskCiSummary,
|
||||
type GateResult,
|
||||
} from "@peppa/core";
|
||||
import { checkRuns } from "@peppa/db";
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
import { PanelSection } from "@/components/ActivityAside";
|
||||
import { Hidden, QuestionCard, SessionCard } from "@/components/cards";
|
||||
import { eventLine } from "@/components/RunnerConsole";
|
||||
import { ago, Disclosure, Empty, Flash, PageHeader, Section, StatusBadge } from "@/components/common";
|
||||
import { Hidden, SessionCard } from "@/components/cards";
|
||||
import { ago, Disclosure, Flash, PageHeader, Section, StatusBadge } from "@/components/common";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input, NativeSelect } from "@/components/ui/input";
|
||||
import { Input, NativeSelect, Textarea } 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";
|
||||
import { taskActivity, taskForUser } from "@/lib/queries";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { editStoryAction, startTaskSession } from "../../actions";
|
||||
import { ActivityTab, ArtifactTab, CommentsTab, MergeTab, ProgressBar, SpecsTab, STORY_TABS, TasksTab, TestsTab, type CheckRunRow, type StoryTab } from "./tabs";
|
||||
|
||||
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 StoryPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string }> }) {
|
||||
/** Gitea behind Cloudflare can hang: the merge tab waits at most this long. */
|
||||
async function gateWithTimeout(ref: Parameters<typeof prGate>[0]): Promise<GateResult | null> {
|
||||
return Promise.race([prGate(ref).catch(() => null), new Promise<null>((r) => setTimeout(() => r(null), 5000))]);
|
||||
}
|
||||
|
||||
export default async function StoryPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; tab?: string; edit?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const { key } = await params;
|
||||
const { error } = await searchParams;
|
||||
const sp = await searchParams;
|
||||
const ref = await taskForUser(user.id, decodeURIComponent(key)).catch(() => null);
|
||||
if (!ref) notFound();
|
||||
const { task, project } = ref;
|
||||
const { questions, sessions, events } = await taskActivity(task.id);
|
||||
const liveId = sessions.find((s) => !FINISHED_SESSION_STATUSES.includes(s.status))?.id;
|
||||
const artifacts = openspecArtifacts(project, task.openspecChange);
|
||||
const live = sessions.find((s) => !FINISHED_SESSION_STATUSES.includes(s.status)) ?? null;
|
||||
const past = sessions.filter((s) => s !== live);
|
||||
const change = readChange(project, task.openspecChange);
|
||||
const progress = change?.tasks ? parseTasks(change.tasks) : null;
|
||||
const ci = await taskCiSummary(db, ref);
|
||||
const review = await latestReview(db, task.id);
|
||||
const epic = task.goalId ? await getEpic(db, project.id, task.goalId).catch(() => null) : null;
|
||||
const back = `/t/${ref.key}`;
|
||||
const epics = await listEpics(db, project.id);
|
||||
const epic = task.goalId ? (epics.find((e) => e.id === task.goalId) ?? (await getEpic(db, project.id, task.goalId).catch(() => null))) : null;
|
||||
const tab: StoryTab = STORY_TABS.find((t) => t.id === sp.tab)?.id ?? (change ? "proposal" : "comments");
|
||||
const tabHref = (id: StoryTab) => `/t/${ref.key}?tab=${id}`;
|
||||
const back = tabHref(tab);
|
||||
// PEP-67: superadmins choose the subscriptions a runner may take; others run on the project's pool.
|
||||
const superadmin = await isSuperadmin(db, user);
|
||||
const pool = await projectPool(db, project.id);
|
||||
const [pools, subs] = superadmin ? await Promise.all([listPools(db), listSubscriptions(db)]) : [[], []];
|
||||
const steps = live ? await sessionSteps(db, live.id) : undefined;
|
||||
|
||||
// Only the open tab reads the rest (Gitea for the merge request).
|
||||
const comments = tab === "comments" ? await storyComments(db, task.id) : [];
|
||||
const runs: CheckRunRow[] =
|
||||
tab === "tests" && ci.sha
|
||||
? (await db.select().from(checkRuns).where(eq(checkRuns.taskId, task.id)).orderBy(desc(checkRuns.updatedAt))).filter((r) => r.sha === ci.sha).sort((a, b) => a.check.localeCompare(b.check))
|
||||
: [];
|
||||
const gate = tab === "merge" && task.prUrl ? await gateWithTimeout(ref) : null;
|
||||
const openQuestions = questions.filter((q) => !q.answeredAt).length;
|
||||
const counts: Partial<Record<StoryTab, number | string>> = {
|
||||
specs: change?.specs.length || undefined,
|
||||
tasks: progress?.total ? `${progress.done}/${progress.total}` : undefined,
|
||||
comments: openQuestions || undefined,
|
||||
};
|
||||
|
||||
const aside = (
|
||||
<div className="flex flex-col gap-6">
|
||||
<PanelSection title="Проверки">
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<Link href={tabHref("tests")} className="flex flex-wrap items-center gap-2 text-sm text-foreground hover:no-underline">
|
||||
{CI_ICON[ci.state as keyof typeof CI_ICON]}
|
||||
{ci.runUrl ? <a href={ci.runUrl} className="text-primary">{ci.label}</a> : ci.label}
|
||||
{ci.label}
|
||||
{ci.sha && <span className="font-mono text-xs text-muted-foreground">{ci.sha.slice(0, 7)}</span>}
|
||||
</div>
|
||||
</Link>
|
||||
{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>
|
||||
{review && (
|
||||
<PanelSection title="Ревьюер">
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||
{review.verdict === "ok" ? <CircleCheck className="size-4 text-ok" /> : review.verdict === "changes" || review.state === "error" ? <CircleX className="size-4 text-destructive" /> : <Hourglass className="size-4 text-warn" />}
|
||||
<span className="[overflow-wrap:anywhere]">{reviewLabel(review)}</span>
|
||||
<span className="font-mono text-xs text-muted-foreground">{review.sha.slice(0, 7)}</span>
|
||||
</div>
|
||||
{review.findings.length > 0 && (
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-xs">
|
||||
{review.findings.map((f, i) => (
|
||||
<li key={i} className="[overflow-wrap:anywhere]">
|
||||
{f.file && <span className="font-mono text-muted-foreground">{f.file}{f.line ? `:${f.line}` : ""} — </span>}
|
||||
{f.text}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<p className="m-0 text-xs text-muted-foreground">{ago(review.updatedAt)}</p>
|
||||
<p className="m-0 text-sm [overflow-wrap:anywhere]">{reviewLabel(review)}</p>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{review.sha.slice(0, 7)} · {ago(review.updatedAt)}
|
||||
</p>
|
||||
</PanelSection>
|
||||
)}
|
||||
<PanelSection title="События">
|
||||
<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>{" "}
|
||||
{eventLine(e)}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
<>
|
||||
<ActivityTab events={events.slice(0, 8)} />
|
||||
<Link href={tabHref("activity")} className="text-xs text-primary">
|
||||
Вся активность →
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</PanelSection>
|
||||
</div>
|
||||
@ -99,8 +119,8 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
|
||||
return (
|
||||
<Workspace aside={aside}>
|
||||
<AutoRefresh />
|
||||
<Flash error={error} />
|
||||
<LiveRefresh scope={`task:${task.id}`} />
|
||||
<Flash error={sp.error} />
|
||||
<PageHeader
|
||||
crumbs={
|
||||
<>
|
||||
@ -121,78 +141,164 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
</>
|
||||
}
|
||||
actions={
|
||||
task.prUrl && (
|
||||
<Button asChild size="sm">
|
||||
<a href={task.prUrl}>
|
||||
<GitPullRequest />
|
||||
PR
|
||||
</a>
|
||||
<>
|
||||
<Button asChild size="sm" variant="outline">
|
||||
<Link href={sp.edit ? back : `${back}&edit=1`} scroll={false}>
|
||||
<Pencil />
|
||||
Изменить
|
||||
</Link>
|
||||
</Button>
|
||||
)
|
||||
{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>
|
||||
>
|
||||
<span className="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
{task.openspecChange ? (
|
||||
<span className="font-mono text-xs">
|
||||
{task.openspecChange}
|
||||
{change?.archived && <span className="ml-1 rounded bg-muted px-1">в архиве</span>}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-xs">change ещё нет</span>
|
||||
)}
|
||||
{progress?.total ? (
|
||||
<span className="w-56 max-w-full">
|
||||
<ProgressBar done={progress.done} total={progress.total} current={null} compact />
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
</PageHeader>
|
||||
|
||||
<Section title="Сессии">
|
||||
<form action={startTaskSession} className="flex flex-wrap gap-2">
|
||||
{sp.edit ? (
|
||||
<form action={editStoryAction} className="flex flex-col gap-2 rounded-lg border bg-card p-4">
|
||||
<Hidden fields={{ taskKey: ref.key, back }} />
|
||||
<NativeSelect name="provider" defaultValue="" aria-label="Агент" className="w-auto">
|
||||
<option value="">{pool || superadmin ? "Любой агент" : "Claude Code"}</option>
|
||||
<option value="claude">Claude Code</option>
|
||||
<option value="codex">Codex</option>
|
||||
<option value="opencode">OpenCode</option>
|
||||
</NativeSelect>
|
||||
{superadmin && (
|
||||
<NativeSelect name="choice" defaultValue="" aria-label="Подписки" className="w-auto">
|
||||
<option value="">{pool ? `Пул проекта: ${pool.name}` : "Без пула (вход машины)"}</option>
|
||||
{pools.filter((p) => p.id !== pool?.id).map((p) => (
|
||||
<option key={p.id} value={`pool:${p.id}`}>Пул: {p.name}</option>
|
||||
<label className="flex flex-col gap-1 text-sm">
|
||||
Название
|
||||
<Input name="title" defaultValue={task.title} required minLength={2} />
|
||||
</label>
|
||||
<label className="flex flex-col gap-1 text-sm">
|
||||
Описание
|
||||
<Textarea name="description" defaultValue={task.description ?? ""} rows={6} />
|
||||
</label>
|
||||
<label className="flex flex-col gap-1 text-sm">
|
||||
Эпик
|
||||
<NativeSelect name="epicId" defaultValue={task.goalId ?? ""} className="w-auto">
|
||||
<option value="">Без эпика</option>
|
||||
{epics.map((e) => (
|
||||
<option key={e.id} value={e.id}>{e.title}</option>
|
||||
))}
|
||||
{subs.length > 0 && <option value="pick">Отмеченные подписки ↓</option>}
|
||||
{epic && !epics.some((e) => e.id === epic.id) && <option value={epic.id}>{epic.title} (в архиве)</option>}
|
||||
</NativeSelect>
|
||||
)}
|
||||
<Input name="prompt" placeholder="Доп. инструкция (необязательно)" aria-label="Доп. инструкция" className="flex-[1_1_14rem]" />
|
||||
<Button variant="default">
|
||||
<Play />
|
||||
Запустить агента
|
||||
</Button>
|
||||
{superadmin && subs.length > 0 && (
|
||||
<details className="basis-full text-sm">
|
||||
<summary className="cursor-pointer text-muted-foreground">Отметить подписки (для «Отмеченные подписки»)</summary>
|
||||
<div className="mt-2 flex flex-col gap-1">
|
||||
{subs.map((s) => (
|
||||
<label key={s.id} className="flex items-center gap-2">
|
||||
<input type="checkbox" name="subscription" value={s.id} className="size-4 accent-primary" />
|
||||
<span className="text-muted-foreground">{PROVIDER_NAMES[s.provider]}</span> {s.name}
|
||||
<span className="text-xs text-muted-foreground">· {s.status === "active" ? "активна" : s.status === "limited" ? "лимит" : s.status === "pending" ? "ожидает входа" : "ошибка входа"} · сессий {s.activeSessions}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm">Сохранить</Button>
|
||||
<Button asChild size="sm" variant="ghost">
|
||||
<Link href={back} scroll={false}>Отмена</Link>
|
||||
</Button>
|
||||
</div>
|
||||
<p className="m-0 text-xs text-muted-foreground">Агент не запускается; изменение попадёт в Activity.</p>
|
||||
</form>
|
||||
{!superadmin && pool && <p className="m-0 text-xs text-muted-foreground">Агент запустится на свободной подписке пула «{pool.name}».</p>}
|
||||
{sessions.map((s) => (
|
||||
// PEP-9: the live terminal of the newest unfinished runner.
|
||||
<SessionCard key={s.id} s={s} back={back} terminal={s.id === liveId} />
|
||||
))}
|
||||
</Section>
|
||||
) : (
|
||||
<Disclosure open={!change} summary={<span className="text-sm font-medium">Описание</span>}>
|
||||
<div className="text-sm whitespace-pre-wrap [overflow-wrap:anywhere]">{task.description || <span className="text-muted-foreground">Без описания</span>}</div>
|
||||
</Disclosure>
|
||||
)}
|
||||
|
||||
<Section title="Вопросы">
|
||||
{questions.length === 0 ? <Empty>Вопросов не было.</Empty> : questions.map((q) => <QuestionCard key={q.id} q={q} taskStatus={task.status} back={back} />)}
|
||||
</Section>
|
||||
|
||||
<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) => (
|
||||
<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>
|
||||
))
|
||||
<Section title="Агент" count={sessions.length || undefined}>
|
||||
{progress?.current && live && (
|
||||
<p className="m-0 text-sm">
|
||||
<span className="text-muted-foreground">Сейчас по tasks.md:</span> {progress.current}
|
||||
</p>
|
||||
)}
|
||||
{live ? (
|
||||
// PEP-9 terminal + PEP-33 step feed of the newest unfinished runner.
|
||||
<SessionCard s={live} back={back} terminal steps={steps} />
|
||||
) : (
|
||||
<Empty>Change ещё не создан.</Empty>
|
||||
<form action={startTaskSession} className="flex flex-wrap gap-2">
|
||||
<Hidden fields={{ taskKey: ref.key, back }} />
|
||||
<NativeSelect name="provider" defaultValue="" aria-label="Агент" className="w-auto">
|
||||
<option value="">{pool || superadmin ? "Любой агент" : "Claude Code"}</option>
|
||||
<option value="claude">Claude Code</option>
|
||||
<option value="codex">Codex</option>
|
||||
<option value="opencode">OpenCode</option>
|
||||
</NativeSelect>
|
||||
{superadmin && (
|
||||
<NativeSelect name="choice" defaultValue="" aria-label="Подписки" className="w-auto">
|
||||
<option value="">{pool ? `Пул проекта: ${pool.name}` : "Без пула (вход машины)"}</option>
|
||||
{pools.filter((p) => p.id !== pool?.id).map((p) => (
|
||||
<option key={p.id} value={`pool:${p.id}`}>Пул: {p.name}</option>
|
||||
))}
|
||||
{subs.length > 0 && <option value="pick">Отмеченные подписки ↓</option>}
|
||||
</NativeSelect>
|
||||
)}
|
||||
<Input name="prompt" placeholder="Доп. инструкция (необязательно)" aria-label="Доп. инструкция" className="flex-[1_1_14rem]" />
|
||||
<Button variant="default">
|
||||
<Play />
|
||||
Запустить агента
|
||||
</Button>
|
||||
{superadmin && subs.length > 0 && (
|
||||
<details className="basis-full text-sm">
|
||||
<summary className="cursor-pointer text-muted-foreground">Отметить подписки (для «Отмеченные подписки»)</summary>
|
||||
<div className="mt-2 flex flex-col gap-1">
|
||||
{subs.map((s) => (
|
||||
<label key={s.id} className="flex items-center gap-2">
|
||||
<input type="checkbox" name="subscription" value={s.id} className="size-4 accent-primary" />
|
||||
<span className="text-muted-foreground">{PROVIDER_NAMES[s.provider]}</span> {s.name}
|
||||
<span className="text-xs text-muted-foreground">· {s.status === "active" ? "активна" : s.status === "limited" ? "лимит" : s.status === "pending" ? "ожидает входа" : "ошибка входа"} · сессий {s.activeSessions}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
{!superadmin && pool && <p className="m-0 basis-full text-xs text-muted-foreground">Агент запустится на свободной подписке пула «{pool.name}».</p>}
|
||||
</form>
|
||||
)}
|
||||
{past.length > 0 && (
|
||||
<Disclosure summary={<span className="text-sm text-muted-foreground">Прошлые сессии: {past.length}</span>}>
|
||||
<div className="flex flex-col gap-2">
|
||||
{past.map((s) => (
|
||||
<SessionCard key={s.id} s={s} back={back} />
|
||||
))}
|
||||
</div>
|
||||
</Disclosure>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<nav aria-label="Разделы стори" className="mt-2 flex gap-1 overflow-x-auto border-b">
|
||||
{STORY_TABS.map((t) => (
|
||||
<Link
|
||||
key={t.id}
|
||||
href={tabHref(t.id)}
|
||||
scroll={false}
|
||||
aria-current={tab === t.id ? "page" : undefined}
|
||||
className={cn(
|
||||
"-mb-px flex items-center gap-1.5 border-b-2 px-3 py-2 text-sm whitespace-nowrap text-muted-foreground hover:text-foreground hover:no-underline",
|
||||
tab === t.id ? "border-primary text-foreground" : "border-transparent",
|
||||
)}
|
||||
>
|
||||
{t.label}
|
||||
{counts[t.id] != null && <span className={cn("rounded-full px-1.5 font-mono text-[11px] tabular-nums", t.id === "comments" ? "bg-primary/15 text-primary" : "bg-muted")}>{counts[t.id]}</span>}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
{tab === "proposal" && <ArtifactTab change={change} changeId={task.openspecChange} file="proposal" />}
|
||||
{tab === "design" && <ArtifactTab change={change} changeId={task.openspecChange} file="design" />}
|
||||
{tab === "specs" && <SpecsTab change={change} changeId={task.openspecChange} />}
|
||||
{tab === "tasks" && <TasksTab change={change} changeId={task.openspecChange} progress={progress} />}
|
||||
{tab === "comments" && <CommentsTab taskKey={ref.key} taskStatus={task.status} questions={[...questions].reverse()} comments={comments} back={back} hasLive={!!live} />}
|
||||
{tab === "tests" && <TestsTab ci={ci} runs={runs} review={review} />}
|
||||
{tab === "merge" && <MergeTab taskKey={ref.key} taskStatus={task.status} prUrl={task.prUrl} pull={gate?.pull ?? null} gate={gate} back={back} />}
|
||||
{tab === "activity" && <ActivityTab events={events} />}
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
|
||||
406
apps/web/app/(app)/t/[key]/tabs.tsx
Normal file
406
apps/web/app/(app)/t/[key]/tabs.tsx
Normal file
@ -0,0 +1,406 @@
|
||||
// Story page tabs (PEP-32): OpenSpec artifacts of the change, comments, checks, the PR and
|
||||
// the activity log. Server components; each tab reads only what it shows.
|
||||
import { CircleCheck, CircleX, ExternalLink, GitMerge, GitPullRequest, Hourglass, MessageSquare, Send } from "lucide-react";
|
||||
import type { ChangeArtifacts, CiSummary, CodeReview, DeltaOp, GiteaPull, Question, StoryComment, TasksProgress } from "@peppa/core";
|
||||
import { reviewLabel } from "@peppa/core";
|
||||
import { Hidden, QuestionCard } from "@/components/cards";
|
||||
import { ago, Disclosure, Empty } from "@/components/common";
|
||||
import { Markdown } from "@/components/Markdown";
|
||||
import { eventLine } from "@/components/RunnerConsole";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Textarea } from "@/components/ui/input";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { acceptStoryAction, commentStoryAction } from "../../actions";
|
||||
|
||||
export const STORY_TABS = [
|
||||
{ id: "proposal", label: "Proposal" },
|
||||
{ id: "design", label: "Design" },
|
||||
{ id: "specs", label: "Specs" },
|
||||
{ id: "tasks", label: "Tasks" },
|
||||
{ id: "comments", label: "Comments" },
|
||||
{ id: "tests", label: "Tests" },
|
||||
{ id: "merge", label: "Merge request" },
|
||||
{ id: "activity", label: "Activity" },
|
||||
] as const;
|
||||
export type StoryTab = (typeof STORY_TABS)[number]["id"];
|
||||
|
||||
const noChange = (change: string | null) => <Empty>{change ? `Change ${change} не найден в рабочей копии.` : "Change ещё не создан — агент заведёт его на этапе proposal."}</Empty>;
|
||||
|
||||
export function ArtifactTab({ change, changeId, file }: { change: ChangeArtifacts | null; changeId: string | null; file: "proposal" | "design" }) {
|
||||
if (!change) return noChange(changeId);
|
||||
const text = change[file];
|
||||
if (!text) return <Empty>{file === "design" ? "design.md в этом change нет — значит, решений сверх proposal не понадобилось." : "proposal.md ещё не написан."}</Empty>;
|
||||
return (
|
||||
<article className="rounded-lg border bg-card p-5">
|
||||
<Markdown text={text} />
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
const OP: Record<DeltaOp, { label: string; variant: "ok" | "info" | "danger" | "outline" }> = {
|
||||
ADDED: { label: "добавлено", variant: "ok" },
|
||||
MODIFIED: { label: "изменено", variant: "info" },
|
||||
REMOVED: { label: "удалено", variant: "danger" },
|
||||
RENAMED: { label: "переименовано", variant: "outline" },
|
||||
};
|
||||
|
||||
export function SpecsTab({ change, changeId }: { change: ChangeArtifacts | null; changeId: string | null }) {
|
||||
if (!change) return noChange(changeId);
|
||||
if (!change.specs.length) return <Empty>В change нет дельта-спецификаций (specs/*/spec.md).</Empty>;
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{change.specs.map((spec) => (
|
||||
<section key={spec.capability} className="flex flex-col gap-3 rounded-lg border bg-card p-4">
|
||||
<h3 className="m-0 font-mono text-sm font-semibold">{spec.capability}</h3>
|
||||
{spec.sections.map((sec, si) => (
|
||||
<div key={si} className="flex flex-col gap-2">
|
||||
{sec.requirements.length === 0 && <p className="m-0 text-xs text-muted-foreground">{OP[sec.op].label}: без требований</p>}
|
||||
{sec.requirements.map((r, ri) => (
|
||||
<Disclosure
|
||||
key={ri}
|
||||
open={change.specs.length === 1 && ri < 3}
|
||||
summary={
|
||||
<span className="flex min-w-0 items-center gap-2">
|
||||
<Badge variant={OP[sec.op].variant}>{OP[sec.op].label}</Badge>
|
||||
<span className="min-w-0 font-medium [overflow-wrap:anywhere]">{r.name}</span>
|
||||
{r.scenarios.length > 0 && <span className="ml-auto shrink-0 font-mono text-[11px] text-muted-foreground">сценариев: {r.scenarios.length}</span>}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-3">
|
||||
{r.body && <Markdown text={r.body} />}
|
||||
{r.scenarios.map((sc, i) => (
|
||||
<div key={i} className="rounded-md border-l-2 border-primary/50 bg-muted/30 py-2 pr-3 pl-3">
|
||||
<p className="m-0 mb-1 text-xs font-semibold">Сценарий: {sc.name}</p>
|
||||
<Markdown text={sc.body} className="text-xs" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Disclosure>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TasksTab({ change, changeId, progress }: { change: ChangeArtifacts | null; changeId: string | null; progress: TasksProgress | null }) {
|
||||
if (!change) return noChange(changeId);
|
||||
if (!progress?.total) return <Empty>tasks.md ещё нет или в нём нет пунктов.</Empty>;
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<ProgressBar done={progress.done} total={progress.total} current={progress.current} />
|
||||
{progress.sections.map((sec, i) => {
|
||||
const done = sec.items.filter((it) => it.done).length;
|
||||
return (
|
||||
<section key={i} className="flex flex-col gap-1.5 rounded-lg border bg-card p-4">
|
||||
<h3 className="m-0 flex items-center gap-2 text-sm font-semibold">
|
||||
{sec.title || "Пункты"}
|
||||
<span className={cn("ml-auto font-mono text-xs tabular-nums", done === sec.items.length ? "text-ok" : "text-muted-foreground")}>
|
||||
{done}/{sec.items.length}
|
||||
</span>
|
||||
</h3>
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0">
|
||||
{sec.items.map((it, j) => (
|
||||
<li key={j} className={cn("flex items-start gap-2 text-sm", it.text === progress.current && !it.done && "rounded bg-info/10 px-1 -mx-1")}>
|
||||
<input type="checkbox" checked={it.done} readOnly disabled aria-label={it.done ? "выполнено" : "не выполнено"} className="mt-1 size-3.5 shrink-0 accent-primary" />
|
||||
<span className={cn("[overflow-wrap:anywhere]", it.done && "text-muted-foreground line-through decoration-muted-foreground/40")}>{it.text}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProgressBar({ done, total, current, compact = false }: { done: number; total: number; current: string | null; compact?: boolean }) {
|
||||
const pct = total ? Math.round((done / total) * 100) : 0;
|
||||
return (
|
||||
<div className="flex min-w-0 flex-col gap-1" title={current ? `Сейчас: ${current}` : undefined}>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className={cn("flex-1 overflow-hidden rounded-full bg-muted", compact ? "h-1" : "h-1.5")}>
|
||||
<div className={cn("h-full rounded-full", done === total ? "bg-ok" : "bg-info")} style={{ width: `${pct}%` }} />
|
||||
</div>
|
||||
<span className="font-mono text-xs text-muted-foreground tabular-nums">
|
||||
{done}/{total}
|
||||
</span>
|
||||
</div>
|
||||
{current && !compact && <span className="truncate text-xs text-muted-foreground">Сейчас: {current}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type Thread = { at: number; kind: "q"; q: Question } | { at: number; kind: "c"; c: StoryComment };
|
||||
|
||||
export function CommentsTab({ taskKey, taskStatus, questions, comments, back, hasLive }: { taskKey: string; taskStatus: string; questions: Question[]; comments: StoryComment[]; back: string; hasLive: boolean }) {
|
||||
const thread: Thread[] = [...questions.map((q) => ({ at: q.createdAt.getTime(), kind: "q" as const, q })), ...comments.map((c) => ({ at: c.createdAt.getTime(), kind: "c" as const, c }))].sort((a, b) => a.at - b.at);
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
{thread.length === 0 && <Empty>Вопросов и комментариев пока нет.</Empty>}
|
||||
{thread.map((t) =>
|
||||
t.kind === "q" ? (
|
||||
<QuestionCard key={`q${t.q.id}`} q={t.q} taskStatus={taskStatus} back={back} />
|
||||
) : (
|
||||
<article key={`c${t.c.id}`} className="flex flex-col gap-1.5 rounded-lg border border-primary/30 bg-primary/[0.04] p-3.5">
|
||||
<header className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<MessageSquare className="size-3.5 text-primary" />
|
||||
<span className="font-medium text-foreground">{t.c.login}</span> комментарий PM · {ago(t.c.createdAt)}
|
||||
</header>
|
||||
<p className="m-0 text-sm whitespace-pre-wrap [overflow-wrap:anywhere]">{t.c.text}</p>
|
||||
</article>
|
||||
),
|
||||
)}
|
||||
<form action={commentStoryAction} className="flex flex-col gap-2 rounded-lg border bg-card p-3.5">
|
||||
<Hidden fields={{ taskKey, back }} />
|
||||
<label htmlFor="story-comment" className="text-sm font-medium">
|
||||
Комментарий для агента
|
||||
</label>
|
||||
<Textarea id="story-comment" name="text" rows={3} required maxLength={8000} placeholder="Что учесть: агент видит комментарии в get_task" />
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<label className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<input type="checkbox" name="toAgent" value="1" defaultChecked={hasLive} disabled={!hasLive} className="size-4 accent-primary" />
|
||||
Отправить агенту сейчас{!hasLive && " (живой сессии нет)"}
|
||||
</label>
|
||||
<Button size="sm" className="ml-auto">
|
||||
<Send />
|
||||
Оставить комментарий
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const STATE_ICON = {
|
||||
success: <CircleCheck className="size-4 text-ok" />,
|
||||
failure: <CircleX className="size-4 text-destructive" />,
|
||||
error: <CircleX className="size-4 text-destructive" />,
|
||||
pending: <Hourglass className="size-4 text-warn" />,
|
||||
};
|
||||
|
||||
export interface CheckRunRow {
|
||||
check: string;
|
||||
state: "pending" | "success" | "failure" | "error";
|
||||
runUrl: string | null;
|
||||
logTail: string | null;
|
||||
durationSec: number | null;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export function TestsTab({ ci, runs, review }: { ci: CiSummary; runs: CheckRunRow[]; review: CodeReview | null }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<section className="flex flex-col gap-3 rounded-lg border bg-card p-4">
|
||||
<h3 className="m-0 flex flex-wrap items-center gap-2 text-sm font-semibold">
|
||||
{STATE_ICON[ci.state as keyof typeof STATE_ICON]}
|
||||
{ci.state === "not_configured" ? "Проверки не настроены" : ci.label}
|
||||
{ci.sha && <span className="font-mono text-xs font-normal text-muted-foreground">коммит {ci.sha.slice(0, 7)}</span>}
|
||||
{ci.runUrl && (
|
||||
<a href={ci.runUrl} className="ml-auto text-xs font-normal text-primary">
|
||||
запуск в Gitea
|
||||
</a>
|
||||
)}
|
||||
</h3>
|
||||
{ci.state === "not_configured" && <p className="m-0 text-sm text-muted-foreground">В `.peppa/project.json` проекта нет `checks` — PR проверяется только человеком.</p>}
|
||||
{ci.state === "none" && <p className="m-0 text-sm text-muted-foreground">Проверки ещё не запускались: появятся после первого пуша ветки стори.</p>}
|
||||
{runs.length > 0 && (
|
||||
<ul className="m-0 flex list-none flex-col gap-1.5 p-0">
|
||||
{runs.map((r) => (
|
||||
<li key={r.check}>
|
||||
{r.logTail && r.state !== "success" ? (
|
||||
<Disclosure open={r.state !== "pending"} summary={<CheckLine r={r} />}>
|
||||
<pre className="m-0 max-h-80 overflow-auto font-mono text-[11px] whitespace-pre-wrap">{r.logTail.split("\n").slice(-80).join("\n")}</pre>
|
||||
</Disclosure>
|
||||
) : (
|
||||
<div className="px-3 py-1.5">
|
||||
<CheckLine r={r} />
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
<section className="flex flex-col gap-2 rounded-lg border bg-card p-4">
|
||||
<h3 className="m-0 text-sm font-semibold">Агент-ревьюер</h3>
|
||||
{review ? (
|
||||
<>
|
||||
<p className="m-0 flex flex-wrap items-center gap-2 text-sm">
|
||||
{review.verdict === "ok" ? STATE_ICON.success : review.verdict === "changes" || review.state === "error" ? STATE_ICON.failure : STATE_ICON.pending}
|
||||
<span className="[overflow-wrap:anywhere]">{reviewLabel(review)}</span>
|
||||
<span className="font-mono text-xs text-muted-foreground">
|
||||
{review.sha.slice(0, 7)} · {ago(review.updatedAt)}
|
||||
</span>
|
||||
</p>
|
||||
{review.summary && <Markdown text={review.summary} className="text-xs" />}
|
||||
{review.findings.length > 0 && (
|
||||
<ul className="m-0 flex list-disc flex-col gap-1 pl-5 text-xs">
|
||||
{review.findings.map((f, i) => (
|
||||
<li key={i} className="[overflow-wrap:anywhere]">
|
||||
{f.file && <span className="font-mono text-muted-foreground">{f.file}{f.line ? `:${f.line}` : ""} — </span>}
|
||||
{f.text}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<p className="m-0 text-sm text-muted-foreground">Ревью не было: ревьюер выключен в настройках проекта или PR ещё не отдан в ревью.</p>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CheckLine({ r }: { r: CheckRunRow }) {
|
||||
return (
|
||||
<span className="flex min-w-0 items-center gap-2 text-sm">
|
||||
{STATE_ICON[r.state]}
|
||||
<span className="font-mono">{r.check}</span>
|
||||
{r.durationSec != null && <span className="font-mono text-xs text-muted-foreground">{r.durationSec} с</span>}
|
||||
<span className="ml-auto font-mono text-xs text-muted-foreground">{ago(r.updatedAt)}</span>
|
||||
{r.runUrl && (
|
||||
<a href={r.runUrl} className="text-xs text-primary">
|
||||
лог
|
||||
</a>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function MergeTab({
|
||||
taskKey,
|
||||
taskStatus,
|
||||
prUrl,
|
||||
pull,
|
||||
gate,
|
||||
back,
|
||||
}: {
|
||||
taskKey: string;
|
||||
taskStatus: string;
|
||||
prUrl: string | null;
|
||||
pull: GiteaPull | null;
|
||||
gate: { ok: boolean; reason?: string } | null;
|
||||
back: string;
|
||||
}) {
|
||||
if (!prUrl) return <Empty>PR ещё нет — агент откроет его, когда закончит работу.</Empty>;
|
||||
return (
|
||||
<section className="flex flex-col gap-3 rounded-lg border bg-card p-4">
|
||||
<h3 className="m-0 flex flex-wrap items-center gap-2 text-sm font-semibold">
|
||||
{pull?.merged ? <GitMerge className="size-4 text-ok" /> : <GitPullRequest className={cn("size-4", pull?.state === "closed" ? "text-destructive" : "text-primary")} />}
|
||||
{pull ? (
|
||||
<>
|
||||
#{pull.number} {pull.title}
|
||||
</>
|
||||
) : (
|
||||
"Pull request"
|
||||
)}
|
||||
<Badge variant={pull?.merged ? "ok" : pull?.state === "closed" ? "danger" : "info"} className="ml-auto">
|
||||
{pull ? (pull.merged ? "смержен" : pull.state === "closed" ? "закрыт" : "открыт") : "Gitea недоступна"}
|
||||
</Badge>
|
||||
</h3>
|
||||
{pull && (
|
||||
<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 font-mono text-xs [overflow-wrap:anywhere]">
|
||||
{pull.head.ref} → {pull.base.ref}
|
||||
</dd>
|
||||
<dt className="text-muted-foreground">Коммит</dt>
|
||||
<dd className="m-0 font-mono text-xs">{pull.head.sha.slice(0, 10)}</dd>
|
||||
{!pull.merged && pull.state === "open" && (
|
||||
<>
|
||||
<dt className="text-muted-foreground">Мерж</dt>
|
||||
<dd className="m-0">{gate?.ok ? <span className="text-ok">можно мержить</span> : <span className="text-warn">{gate?.reason ?? (pull.mergeable ? "без конфликтов" : "есть конфликты")}</span>}</dd>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button asChild variant="outline" size="sm">
|
||||
<a href={prUrl}>
|
||||
<ExternalLink />
|
||||
PR в Gitea
|
||||
</a>
|
||||
</Button>
|
||||
<Button asChild variant="outline" size="sm">
|
||||
<a href={`${prUrl.replace(/\/$/, "")}/files`}>Дифф</a>
|
||||
</Button>
|
||||
{taskStatus === "review" && !pull?.merged && (
|
||||
<form action={acceptStoryAction} className="ml-auto">
|
||||
<Hidden fields={{ taskKey, back }} />
|
||||
<Button size="sm" disabled={gate ? !gate.ok : false} title={gate && !gate.ok ? gate.reason : undefined}>
|
||||
<GitMerge />
|
||||
Принять и смержить
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
{taskStatus !== "review" && !pull?.merged && <p className="m-0 text-xs text-muted-foreground">Мерж — когда стори в ревью: агент отдаёт её туда после зелёных проверок.</p>}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const EVENT_RU: Record<string, string> = {
|
||||
task_updated: "стори изменена",
|
||||
progress: "прогресс",
|
||||
pm_comment: "комментарий",
|
||||
claude_session: "сессия агента",
|
||||
claude_session_end: "конец сессии агента",
|
||||
session_started: "раннер запущен",
|
||||
session_stopped: "раннер остановлен",
|
||||
auto_continue: "автопродолжение",
|
||||
awaiting_review: "ждёт ревьюера",
|
||||
stop_failure: "ход оборвался",
|
||||
notification: "уведомление",
|
||||
terminal_input: "ввод в терминал",
|
||||
subscription_switched: "смена подписки",
|
||||
};
|
||||
|
||||
export interface ActivityEvent {
|
||||
id: number;
|
||||
type: string;
|
||||
payload: unknown;
|
||||
sessionId: number | null;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
/** Who did it: a PM by login, the agent of a session, or Peppa itself. */
|
||||
export function eventAuthor(e: ActivityEvent): { label: string; tone: "pm" | "agent" | "system" } {
|
||||
const login = (e.payload as { login?: unknown } | null)?.login;
|
||||
if (typeof login === "string" && login) return { label: login, tone: "pm" };
|
||||
if (e.sessionId) return { label: `агент · #${e.sessionId}`, tone: "agent" };
|
||||
return { label: "система", tone: "system" };
|
||||
}
|
||||
|
||||
function changeLine(e: ActivityEvent): string {
|
||||
if (e.type !== "task_updated") return eventLine(e);
|
||||
const to = ((e.payload as { to?: Record<string, unknown> } | null)?.to ?? {}) as Record<string, unknown>;
|
||||
const parts = Object.entries(to).map(([k, v]) => {
|
||||
const name = { status: "статус", title: "название", description: "описание", goalId: "эпик", openspecChange: "change", prUrl: "PR" }[k] ?? k;
|
||||
return k === "description" ? name : `${name} → ${v ?? "—"}`;
|
||||
});
|
||||
return parts.join(", ");
|
||||
}
|
||||
|
||||
export function ActivityTab({ events }: { events: ActivityEvent[] }) {
|
||||
if (!events.length) return <Empty>Событий нет.</Empty>;
|
||||
return (
|
||||
<ol className="m-0 flex list-none flex-col gap-0 border-l p-0 pl-4">
|
||||
{events.map((e) => {
|
||||
const a = eventAuthor(e);
|
||||
return (
|
||||
<li key={e.id} className="relative py-1.5 text-sm [overflow-wrap:anywhere]">
|
||||
<span className={cn("absolute top-3 -left-[1.3rem] size-2 rounded-full", a.tone === "pm" ? "bg-primary" : a.tone === "agent" ? "bg-info" : "bg-muted-foreground")} />
|
||||
<span className="font-mono text-xs text-muted-foreground">{ago(e.createdAt)}</span> <span className={cn("text-xs font-medium", a.tone === "pm" ? "text-primary" : a.tone === "agent" ? "text-info" : "text-muted-foreground")}>{a.label}</span>{" "}
|
||||
<span className="font-mono text-xs text-muted-foreground">{EVENT_RU[e.type] ?? e.type}</span> {changeLine(e)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
21
apps/web/app/api/live/route.ts
Normal file
21
apps/web/app/api/live/route.ts
Normal file
@ -0,0 +1,21 @@
|
||||
// Live updates (PEP-37): SSE of `change` (a watched scope changed — refresh) and `step`
|
||||
// (an agent's tool call, PEP-33) events. ?scope=home | runners | project:<id> | task:<id> | steps:<sessionId>, comma-separated.
|
||||
import { LiveError, liveSse, parseScopes } from "@peppa/runner";
|
||||
import { currentUser } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const fail = (status: number, error: string) => Response.json({ error }, { status, headers: { "Cache-Control": "no-store" } });
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const user = await currentUser();
|
||||
if (!user) return fail(401, "Нужен вход");
|
||||
try {
|
||||
return await liveSse(db, user, parseScopes(new URL(req.url).searchParams.get("scope")), req.signal);
|
||||
} catch (e) {
|
||||
if (e instanceof LiveError) return fail(e.status, e.message);
|
||||
console.error("live:", e);
|
||||
return fail(500, "Ошибка потока");
|
||||
}
|
||||
}
|
||||
88
apps/web/components/AgentSteps.tsx
Normal file
88
apps/web/components/AgentSteps.tsx
Normal file
@ -0,0 +1,88 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Bot, FilePen, FileText, FlaskConical, Globe, Plug, Search, SquareTerminal, Wrench, type LucideIcon } from "lucide-react";
|
||||
import type { StepKind, StepView } from "@peppa/core";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const KIND: Record<StepKind, { icon: LucideIcon; label: string }> = {
|
||||
command: { icon: SquareTerminal, label: "команда" },
|
||||
test: { icon: FlaskConical, label: "тест" },
|
||||
edit: { icon: FilePen, label: "правка" },
|
||||
read: { icon: FileText, label: "чтение" },
|
||||
search: { icon: Search, label: "поиск" },
|
||||
web: { icon: Globe, label: "веб" },
|
||||
agent: { icon: Bot, label: "субагент" },
|
||||
mcp: { icon: Plug, label: "MCP" },
|
||||
other: { icon: Wrench, label: "инструмент" },
|
||||
};
|
||||
|
||||
const KEEP = 30;
|
||||
|
||||
function since(iso: string, now: number): string {
|
||||
const s = Math.max(0, Math.round((now - Date.parse(iso)) / 1000));
|
||||
if (s < 60) return `${s} с`;
|
||||
if (s < 3600) return `${Math.floor(s / 60)} мин`;
|
||||
return `${Math.floor(s / 3600)} ч`;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the agent is doing now (PEP-33): its latest tool calls, newest first. Initial steps
|
||||
* come from the server, new ones from the live channel (PEP-37, `steps:<sessionId>`).
|
||||
*/
|
||||
export function AgentSteps({ sessionId, initial, live, hooks = true }: { sessionId: number; initial: StepView[]; live: boolean; hooks?: boolean }) {
|
||||
const [steps, setSteps] = useState(initial);
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
|
||||
useEffect(() => setSteps((cur) => merge(initial, cur)), [initial]);
|
||||
|
||||
useEffect(() => {
|
||||
const t = setInterval(() => setNow(Date.now()), 10_000);
|
||||
if (!live || typeof EventSource === "undefined") return () => clearInterval(t);
|
||||
const es = new EventSource(`/api/live?scope=steps:${sessionId}`);
|
||||
es.addEventListener("step", (e) => {
|
||||
try {
|
||||
const { step } = JSON.parse((e as MessageEvent).data) as { step: StepView };
|
||||
setSteps((cur) => merge([step], cur));
|
||||
setNow(Date.now());
|
||||
} catch {}
|
||||
});
|
||||
return () => {
|
||||
clearInterval(t);
|
||||
es.close();
|
||||
};
|
||||
}, [sessionId, live]);
|
||||
|
||||
if (!steps.length)
|
||||
return (
|
||||
<p className="m-0 rounded-md border border-dashed px-3 py-2 text-xs text-muted-foreground">
|
||||
{hooks ? (live ? "Агент ещё ничего не сделал — шаги появятся здесь." : "Шагов не записано.") : "Этот агент не сообщает шаги (нет хуков) — смотри терминал."}
|
||||
</p>
|
||||
);
|
||||
return (
|
||||
<ol aria-label="Шаги агента" className="m-0 flex max-h-72 list-none flex-col gap-0.5 overflow-auto p-0">
|
||||
{steps.map((s, i) => {
|
||||
const k = KIND[s.kind] ?? KIND.other;
|
||||
const Icon = k.icon;
|
||||
return (
|
||||
<li key={s.id} className={cn("flex items-center gap-2 rounded px-1.5 py-1 text-xs", i === 0 && live && "bg-info/10")}>
|
||||
<Icon className={cn("size-3.5 shrink-0", s.ok ? "text-muted-foreground" : "text-destructive")} aria-label={k.label} />
|
||||
<span className={cn("min-w-0 flex-1 truncate font-mono", !s.ok && "text-destructive")} title={`${s.tool}: ${s.text}`}>
|
||||
{s.text}
|
||||
</span>
|
||||
{!s.ok && <span className="shrink-0 text-[10px] text-destructive">ошибка</span>}
|
||||
<span className="shrink-0 font-mono text-[10px] text-muted-foreground tabular-nums">{since(s.at, now)}</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
|
||||
function merge(add: StepView[], cur: StepView[]): StepView[] {
|
||||
const seen = new Set<number>();
|
||||
return [...add, ...cur]
|
||||
.filter((s) => !seen.has(s.id) && (seen.add(s.id), true))
|
||||
.sort((a, b) => b.id - a.id)
|
||||
.slice(0, KEEP);
|
||||
}
|
||||
@ -15,6 +15,31 @@ export interface Card {
|
||||
column: Column;
|
||||
/** Epic label (PEP-66), if the story has an open epic. */
|
||||
epic?: string | null;
|
||||
/** tasks.md progress of a story in work (PEP-33). */
|
||||
progress?: CardProgress | null;
|
||||
}
|
||||
export interface CardProgress {
|
||||
done: number;
|
||||
total: number;
|
||||
current: string | null;
|
||||
}
|
||||
|
||||
/** «7/12» bar and the item the agent is on (PEP-33). */
|
||||
export function ProgressLine({ p, className }: { p: CardProgress; className?: string }) {
|
||||
const pct = p.total ? Math.round((p.done / p.total) * 100) : 0;
|
||||
return (
|
||||
<div className={cn("flex min-w-0 flex-col gap-1", className)} title={p.current ? `Сейчас: ${p.current}` : "Все пункты tasks.md выполнены"}>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="h-1 flex-1 overflow-hidden rounded-full bg-muted">
|
||||
<div className="h-full rounded-full bg-info" style={{ width: `${pct}%` }} />
|
||||
</div>
|
||||
<span className="font-mono text-[11px] text-muted-foreground tabular-nums">
|
||||
{p.done}/{p.total}
|
||||
</span>
|
||||
</div>
|
||||
{p.current && <span className="truncate text-[11px] text-muted-foreground">{p.current}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const COLUMNS: Array<{ id: Column; title: string; hint: string; dot: string }> = [
|
||||
@ -83,6 +108,7 @@ export function Board({ cards, back }: { cards: Card[]; back: string }) {
|
||||
<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>
|
||||
{card.progress && <ProgressLine p={card.progress} />}
|
||||
{(STATUS[card.status] || NEXT[c.id] || card.epic) && (
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
{card.epic && (
|
||||
|
||||
125
apps/web/components/LiveRefresh.tsx
Normal file
125
apps/web/components/LiveRefresh.tsx
Normal file
@ -0,0 +1,125 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type Mode = "connecting" | "live" | "reconnecting" | "polling";
|
||||
|
||||
const LABEL: Record<Mode, string> = {
|
||||
connecting: "подключение…",
|
||||
live: "в реальном времени",
|
||||
reconnecting: "переподключение…",
|
||||
polling: "опрос раз в 5 с",
|
||||
};
|
||||
const DOT: Record<Mode, string> = {
|
||||
connecting: "bg-muted-foreground",
|
||||
live: "bg-ok",
|
||||
reconnecting: "bg-warn animate-pulse",
|
||||
polling: "bg-warn",
|
||||
};
|
||||
|
||||
/** True while the user is typing or left an unsent draft: a refresh must wait. */
|
||||
function busy(): boolean {
|
||||
const el = document.activeElement;
|
||||
const typing = el instanceof HTMLTextAreaElement || (el instanceof HTMLInputElement && ["text", "search", ""].includes(el.type));
|
||||
const draft = [...document.querySelectorAll<HTMLTextAreaElement | HTMLInputElement>("textarea, input[type=text]")].some((i) => i.value !== i.defaultValue);
|
||||
return typing || draft;
|
||||
}
|
||||
|
||||
/**
|
||||
* Live page (PEP-37): listens to /api/live for its scope and re-renders server data when
|
||||
* something there changed (router.refresh keeps client state and typed text). Falls back to
|
||||
* polling every 5 s when the stream can't be opened; shows the connection state.
|
||||
*/
|
||||
export function LiveRefresh({ scope, pollMs = 5000 }: { scope: string; pollMs?: number }) {
|
||||
const router = useRouter();
|
||||
const [mode, setMode] = useState<Mode>("connecting");
|
||||
const pending = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
let closed = false;
|
||||
let es: EventSource | null = null;
|
||||
let fails = 0;
|
||||
let opened = false;
|
||||
let poll: ReturnType<typeof setInterval> | null = null;
|
||||
let retry: ReturnType<typeof setTimeout> | null = null;
|
||||
let flushTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
// Debounced refresh that waits for the user to finish typing.
|
||||
const flush = () => {
|
||||
flushTimer = null;
|
||||
if (closed || !pending.current) return;
|
||||
if (busy() || document.visibilityState !== "visible") {
|
||||
flushTimer = setTimeout(flush, 2000);
|
||||
return;
|
||||
}
|
||||
pending.current = false;
|
||||
router.refresh();
|
||||
};
|
||||
const request = () => {
|
||||
pending.current = true;
|
||||
if (!flushTimer) flushTimer = setTimeout(flush, 300);
|
||||
};
|
||||
const onVisible = () => document.visibilityState === "visible" && pending.current && request();
|
||||
|
||||
const startPolling = () => {
|
||||
if (poll) return;
|
||||
setMode("polling");
|
||||
poll = setInterval(request, pollMs);
|
||||
// Try the stream again now and then.
|
||||
retry = setTimeout(() => {
|
||||
if (poll) clearInterval(poll);
|
||||
poll = null;
|
||||
fails = 0;
|
||||
connect();
|
||||
}, 30_000);
|
||||
};
|
||||
|
||||
const connect = () => {
|
||||
if (closed) return;
|
||||
if (typeof EventSource === "undefined") return startPolling();
|
||||
es = new EventSource(`/api/live?scope=${encodeURIComponent(scope)}`);
|
||||
es.addEventListener("ready", () => {
|
||||
// Back after a drop: changes may have been missed.
|
||||
if (opened) request();
|
||||
opened = true;
|
||||
fails = 0;
|
||||
setMode("live");
|
||||
});
|
||||
es.addEventListener("change", request);
|
||||
es.onerror = () => {
|
||||
if (closed) return;
|
||||
fails++;
|
||||
if (fails >= 3 || es?.readyState === EventSource.CLOSED) {
|
||||
es?.close();
|
||||
es = null;
|
||||
startPolling();
|
||||
} else setMode("reconnecting");
|
||||
};
|
||||
};
|
||||
|
||||
connect();
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
return () => {
|
||||
closed = true;
|
||||
es?.close();
|
||||
if (poll) clearInterval(poll);
|
||||
if (retry) clearTimeout(retry);
|
||||
if (flushTimer) clearTimeout(flushTimer);
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
};
|
||||
}, [router, scope, pollMs]);
|
||||
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
title={mode === "polling" ? "Канал событий недоступен — страница обновляется по таймеру" : "Страница обновляется сама, когда что-то меняется"}
|
||||
className="pointer-events-none fixed right-3 bottom-3 z-40 flex items-center gap-1.5 rounded-full border bg-background/90 px-2.5 py-1 font-mono text-[11px] text-muted-foreground shadow-sm backdrop-blur"
|
||||
>
|
||||
<span className={cn("size-1.5 rounded-full", DOT[mode])} />
|
||||
{LABEL[mode]}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
172
apps/web/components/Markdown.tsx
Normal file
172
apps/web/components/Markdown.tsx
Normal file
@ -0,0 +1,172 @@
|
||||
// Safe Markdown for OpenSpec artifacts (PEP-32): the subset proposals and designs use —
|
||||
// headings, paragraphs, lists with checkboxes, code blocks, tables, quotes, rules, inline
|
||||
// code/bold/italic/links. Everything becomes React elements; no HTML from the file is
|
||||
// ever injected, and only http(s), mailto and relative links are kept.
|
||||
import { Fragment, type ReactNode } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type Block =
|
||||
| { t: "h"; level: number; text: string }
|
||||
| { t: "p"; text: string }
|
||||
| { t: "code"; lang: string; text: string }
|
||||
| { t: "list"; ordered: boolean; items: Array<{ text: string; checked: boolean | null; depth: number }> }
|
||||
| { t: "quote"; text: string }
|
||||
| { t: "table"; head: string[]; rows: string[][] }
|
||||
| { t: "hr" };
|
||||
|
||||
const LIST_RE = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/;
|
||||
const splitRow = (l: string) => l.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((c) => c.trim());
|
||||
|
||||
export function parseMarkdown(src: string): Block[] {
|
||||
const lines = src.replace(/\r\n?/g, "\n").split("\n");
|
||||
const out: Block[] = [];
|
||||
let i = 0;
|
||||
while (i < lines.length) {
|
||||
const line = lines[i]!;
|
||||
if (!line.trim()) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
const fence = line.match(/^\s*(```|~~~)\s*(\S*)/);
|
||||
if (fence) {
|
||||
const body: string[] = [];
|
||||
i++;
|
||||
while (i < lines.length && !lines[i]!.trim().startsWith(fence[1]!)) body.push(lines[i++]!);
|
||||
i++;
|
||||
out.push({ t: "code", lang: fence[2] ?? "", text: body.join("\n") });
|
||||
continue;
|
||||
}
|
||||
const h = line.match(/^(#{1,6})\s+(.*?)\s*#*\s*$/);
|
||||
if (h) {
|
||||
out.push({ t: "h", level: h[1]!.length, text: h[2]! });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) {
|
||||
out.push({ t: "hr" });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (line.includes("|") && /^\s*\|?\s*:?-{2,}/.test(lines[i + 1] ?? "") && (lines[i + 1] ?? "").includes("-")) {
|
||||
const head = splitRow(line);
|
||||
const rows: string[][] = [];
|
||||
i += 2;
|
||||
while (i < lines.length && lines[i]!.includes("|") && lines[i]!.trim()) rows.push(splitRow(lines[i++]!));
|
||||
out.push({ t: "table", head, rows });
|
||||
continue;
|
||||
}
|
||||
if (/^\s*>/.test(line)) {
|
||||
const body: string[] = [];
|
||||
while (i < lines.length && /^\s*>/.test(lines[i]!)) body.push(lines[i++]!.replace(/^\s*>\s?/, ""));
|
||||
out.push({ t: "quote", text: body.join("\n") });
|
||||
continue;
|
||||
}
|
||||
const li = line.match(LIST_RE);
|
||||
if (li) {
|
||||
const ordered = /\d/.test(li[2]!);
|
||||
const items: Array<{ text: string; checked: boolean | null; depth: number }> = [];
|
||||
while (i < lines.length) {
|
||||
const m = lines[i]!.match(LIST_RE);
|
||||
if (m) {
|
||||
const box = m[3]!.match(/^\[([ xX])\]\s+(.*)$/);
|
||||
items.push({ text: box ? box[2]! : m[3]!, checked: box ? box[1] !== " " : null, depth: Math.min(3, Math.floor(m[1]!.replace(/\t/g, " ").length / 2)) });
|
||||
i++;
|
||||
} else if (lines[i]!.trim() && /^\s{2,}/.test(lines[i]!) && items.length) {
|
||||
items.at(-1)!.text += ` ${lines[i++]!.trim()}`; // continuation line
|
||||
} else break;
|
||||
}
|
||||
out.push({ t: "list", ordered, items });
|
||||
continue;
|
||||
}
|
||||
const para: string[] = [];
|
||||
while (i < lines.length && lines[i]!.trim() && !/^(#{1,6}\s|\s*```|\s*~~~|\s*>)/.test(lines[i]!) && !LIST_RE.test(lines[i]!)) para.push(lines[i++]!.trim());
|
||||
out.push({ t: "p", text: para.join(" ") });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function safeHref(href: string): string | null {
|
||||
const h = href.trim();
|
||||
if (/^(https?:|mailto:)/i.test(h)) return h;
|
||||
if (/^[a-z][a-z0-9+.-]*:/i.test(h) || h.startsWith("//")) return null; // javascript:, data:, protocol-relative…
|
||||
return h;
|
||||
}
|
||||
|
||||
// Inline: `code`, **bold**, *italic* or _italic_, [text](url), bare https links.
|
||||
export function inline(text: string, key = "i"): ReactNode[] {
|
||||
const out: ReactNode[] = [];
|
||||
const re = /(`+)([^`]+?)\1|\*\*([^*]+)\*\*|__([^_]+)__|\[([^\]]+)\]\(([^)\s]+)\)|(?<![\w*])\*([^*\s][^*]*?)\*(?!\w)|(?<![\w_])_([^_\s][^_]*?)_(?!\w)|(https?:\/\/[^\s)<]+)/g;
|
||||
let last = 0;
|
||||
let n = 0;
|
||||
for (const m of text.matchAll(re)) {
|
||||
if (m.index! > last) out.push(text.slice(last, m.index));
|
||||
const k = `${key}-${n++}`;
|
||||
if (m[2] != null) out.push(<code key={k} className="rounded bg-muted px-1 py-0.5 font-mono text-[0.85em]">{m[2]}</code>);
|
||||
else if (m[3] != null || m[4] != null) out.push(<strong key={k}>{inline(m[3] ?? m[4]!, k)}</strong>);
|
||||
else if (m[5] != null) {
|
||||
const href = safeHref(m[6]!);
|
||||
out.push(href ? <a key={k} href={href} className="text-primary" rel="noreferrer">{inline(m[5], k)}</a> : <Fragment key={k}>{m[5]}</Fragment>);
|
||||
} else if (m[7] != null || m[8] != null) out.push(<em key={k}>{inline(m[7] ?? m[8]!, k)}</em>);
|
||||
else if (m[9] != null) out.push(<a key={k} href={m[9]} className="text-primary [overflow-wrap:anywhere]" rel="noreferrer">{m[9]}</a>);
|
||||
last = m.index! + m[0].length;
|
||||
}
|
||||
if (last < text.length) out.push(text.slice(last));
|
||||
return out;
|
||||
}
|
||||
|
||||
const H = ["h2", "h3", "h4", "h5", "h6", "h6"] as const;
|
||||
const H_CLASS = ["text-lg", "text-base", "text-sm", "text-sm", "text-xs", "text-xs"];
|
||||
|
||||
export function Markdown({ text, className }: { text: string; className?: string }) {
|
||||
const blocks = parseMarkdown(text);
|
||||
return (
|
||||
<div className={cn("flex min-w-0 flex-col gap-3 text-sm leading-relaxed [overflow-wrap:anywhere]", className)}>
|
||||
{blocks.map((b, i) => {
|
||||
const k = `b${i}`;
|
||||
switch (b.t) {
|
||||
case "h": {
|
||||
const Tag = H[b.level - 1]!;
|
||||
return <Tag key={k} className={cn("m-0 mt-2 font-semibold first:mt-0", H_CLASS[b.level - 1])}>{inline(b.text, k)}</Tag>;
|
||||
}
|
||||
case "p":
|
||||
return <p key={k} className="m-0">{inline(b.text, k)}</p>;
|
||||
case "code":
|
||||
return <pre key={k} className="m-0 max-h-[32em] overflow-auto rounded-md border bg-muted/50 p-3 font-mono text-xs leading-relaxed whitespace-pre">{b.text}</pre>;
|
||||
case "quote":
|
||||
return <blockquote key={k} className="m-0 border-l-2 pl-3 text-muted-foreground">{inline(b.text, k)}</blockquote>;
|
||||
case "hr":
|
||||
return <hr key={k} className="border-border" />;
|
||||
case "table":
|
||||
return (
|
||||
<div key={k} className="overflow-auto">
|
||||
<table className="w-full border-collapse text-xs">
|
||||
<thead>
|
||||
<tr>{b.head.map((c, j) => <th key={j} className="border px-2 py-1 text-left font-semibold">{inline(c, `${k}h${j}`)}</th>)}</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{b.rows.map((r, ri) => (
|
||||
<tr key={ri}>{r.map((c, j) => <td key={j} className="border px-2 py-1 align-top">{inline(c, `${k}r${ri}c${j}`)}</td>)}</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
case "list": {
|
||||
const Tag = b.ordered ? "ol" : "ul";
|
||||
const checklist = b.items.some((it) => it.checked != null);
|
||||
return (
|
||||
<Tag key={k} className={cn("m-0 flex flex-col gap-1", checklist ? "list-none p-0" : b.ordered ? "list-decimal pl-5" : "list-disc pl-5")}>
|
||||
{b.items.map((it, j) => (
|
||||
<li key={j} style={it.depth ? { marginLeft: `${it.depth * 1.25}rem` } : undefined} className={cn(it.checked != null && "flex items-start gap-2")}>
|
||||
{it.checked != null && <input type="checkbox" checked={it.checked} readOnly disabled className="mt-1 size-3.5 shrink-0 accent-primary" />}
|
||||
<span className={cn(it.checked && "text-muted-foreground")}>{inline(it.text, `${k}l${j}`)}</span>
|
||||
</li>
|
||||
))}
|
||||
</Tag>
|
||||
);
|
||||
}
|
||||
}
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,9 +1,10 @@
|
||||
// Runners console (PEP-38): list rows with status and limit info, and the details panel of the chosen runner.
|
||||
import Link from "next/link";
|
||||
import { SquareTerminal, X } from "lucide-react";
|
||||
import { FINISHED_SESSION_STATUSES, PROVIDER_NAMES, type SessionView } from "@peppa/core";
|
||||
import { FINISHED_SESSION_STATUSES, PROVIDER_NAMES, type SessionView, type StepView } from "@peppa/core";
|
||||
import { MAX_LIMIT_RESUMES_PER_DAY } from "@peppa/runner";
|
||||
import { PanelSection } from "@/components/ActivityAside";
|
||||
import { AgentSteps } from "@/components/AgentSteps";
|
||||
import { AttachCommand, QuestionCard, SessionActions } from "@/components/cards";
|
||||
import { ago, Key, StatusBadge } from "@/components/common";
|
||||
import { LocalTime, ScrollIntoViewOnNarrow } from "@/components/LocalTime";
|
||||
@ -42,6 +43,7 @@ export function eventLine(e: { type: string; payload: unknown }): string {
|
||||
if (e.type === "progress") return (e.payload as { text: string }).text;
|
||||
if (e.type === "subscription_switched") return switchText(e.payload);
|
||||
if (e.type === "task_updated") return JSON.stringify((e.payload as { to: unknown }).to);
|
||||
if (e.type === "pm_comment") return (e.payload as { text: string }).text;
|
||||
return "";
|
||||
}
|
||||
|
||||
@ -92,7 +94,8 @@ export function RunnerRow({ s, href, selected, needsPm }: { s: SessionView; href
|
||||
);
|
||||
}
|
||||
|
||||
export function RunnerDetails({ s, questions, events, back, closeHref, chosen }: { s: SessionView; questions: InboxItem[]; events: Array<{ id: number; type: string; payload: unknown; createdAt: Date }>; back: string; closeHref: string; chosen: boolean }) {
|
||||
export function RunnerDetails({ s, questions, events, steps, back, closeHref, chosen }: { s: SessionView; questions: InboxItem[]; events: Array<{ id: number; type: string; payload: unknown; createdAt: Date }>; steps: StepView[]; back: string; closeHref: string; chosen: boolean }) {
|
||||
const finished = FINISHED_SESSION_STATUSES.includes(s.status);
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
{/* Picked from the list: on narrow screens the panel is under it, scroll there. */}
|
||||
@ -152,8 +155,12 @@ export function RunnerDetails({ s, questions, events, back, closeHref, chosen }:
|
||||
</PanelSection>
|
||||
)}
|
||||
|
||||
<PanelSection title="Что делает агент">
|
||||
<AgentSteps key={s.id} sessionId={s.id} initial={steps} live={!finished} hooks={s.provider === "claude"} />
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Терминал">
|
||||
{FINISHED_SESSION_STATUSES.includes(s.status) ? (
|
||||
{finished ? (
|
||||
<div className="flex min-h-24 flex-col items-center justify-center gap-2 rounded-lg border border-dashed bg-background/60 p-4 text-center font-mono text-xs text-muted-foreground">
|
||||
<SquareTerminal className="size-6" />
|
||||
Сессия завершена — терминала больше нет.
|
||||
|
||||
@ -1,11 +1,12 @@
|
||||
// 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 type { Project, Question, SessionView, StepView } 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 { AgentSteps } from "@/components/AgentSteps";
|
||||
import { RunnerTerminal } from "@/components/RunnerTerminal";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
@ -117,7 +118,8 @@ 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, terminal = false }: { s: SessionView; back: string; showTitle?: boolean; terminal?: boolean }) {
|
||||
/** `steps` (PEP-33): the live step feed of the agent, shown with the terminal. */
|
||||
export function SessionCard({ s, back, showTitle = false, terminal = false, steps }: { s: SessionView; back: string; showTitle?: boolean; terminal?: boolean; steps?: StepView[] }) {
|
||||
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">
|
||||
@ -132,6 +134,7 @@ export function SessionCard({ s, back, showTitle = false, terminal = false }: {
|
||||
</header>
|
||||
<AttachCommand name={s.tmuxName} />
|
||||
<SessionActions s={s} back={back} />
|
||||
{steps && <AgentSteps key={`steps-${s.id}`} sessionId={s.id} initial={steps} live={terminal} hooks={s.provider === "claude"} />}
|
||||
{terminal && <RunnerTerminal key={s.id} sessionId={s.id} live />}
|
||||
</article>
|
||||
);
|
||||
|
||||
@ -1,9 +1,7 @@
|
||||
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { listSessions, PeppaError, projectForUser, resolveTask, userProjectIds, type Project, type TaskRef } from "@peppa/core";
|
||||
import { listSessions, PeppaError, STEP_EVENT, projectForUser, resolveTask, userProjectIds, type Project, type TaskRef } from "@peppa/core";
|
||||
import { events, projects, questions, sessions, tasks } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { and, asc, count, desc, eq, inArray, isNull } from "drizzle-orm";
|
||||
import { and, asc, count, desc, eq, inArray, isNull, ne } from "drizzle-orm";
|
||||
import { db } from "./db";
|
||||
|
||||
export type InboxItem = Awaited<ReturnType<typeof inbox>>[number];
|
||||
@ -53,29 +51,14 @@ export async function taskForUser(userId: number, key: string): Promise<TaskRef>
|
||||
export async function taskActivity(taskId: number) {
|
||||
const qs = await db.select().from(questions).where(eq(questions.taskId, taskId)).orderBy(desc(questions.id));
|
||||
const ss = await listSessions(db, { taskId });
|
||||
const evs = await db.select().from(events).where(eq(events.taskId, taskId)).orderBy(desc(events.id)).limit(40);
|
||||
// Steps of agents (PEP-33) have their own live feed.
|
||||
const evs = await db.select().from(events).where(and(eq(events.taskId, taskId), ne(events.type, STEP_EVENT))).orderBy(desc(events.id)).limit(100);
|
||||
return { questions: qs, sessions: ss, events: evs };
|
||||
}
|
||||
|
||||
export const isActiveSession = (status: string) => !["done", "failed"].includes(status);
|
||||
|
||||
/** OpenSpec artifacts of a change from the working copy (active or archived). */
|
||||
export function openspecArtifacts(p: Project, change: string | null): Array<{ name: string; text: string }> | null {
|
||||
if (!change) return null;
|
||||
const changes = join(p.workspacePath, "openspec", "changes");
|
||||
let dir = join(changes, change);
|
||||
if (!existsSync(dir)) {
|
||||
const archive = join(changes, "archive");
|
||||
const hit = existsSync(archive) ? readdirSync(archive).find((d) => d.endsWith(`-${change}`) || d === change) : undefined;
|
||||
if (!hit) return null;
|
||||
dir = join(archive, hit);
|
||||
}
|
||||
return ["proposal.md", "design.md", "tasks.md"]
|
||||
.filter((f) => existsSync(join(dir, f)))
|
||||
.map((f) => ({ name: f, text: readFileSync(join(dir, f), "utf8") }));
|
||||
}
|
||||
|
||||
|
||||
/** Counters of the side navigation (PEP-38): open PM questions and runners waiting for the PM. */
|
||||
export async function navCounts(userId: number): Promise<{ questions: number; waitingRunners: number }> {
|
||||
const ids = await userProjectIds(db, userId);
|
||||
@ -87,5 +70,5 @@ export async function navCounts(userId: number): Promise<{ questions: number; wa
|
||||
|
||||
/** Latest events of one runner, newest first (runner details panel, PEP-38). */
|
||||
export async function sessionEvents(sessionId: number, limit = 12) {
|
||||
return db.select().from(events).where(eq(events.sessionId, sessionId)).orderBy(desc(events.id)).limit(limit);
|
||||
return db.select().from(events).where(and(eq(events.sessionId, sessionId), ne(events.type, STEP_EVENT))).orderBy(desc(events.id)).limit(limit);
|
||||
}
|
||||
|
||||
@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-14
|
||||
@ -0,0 +1,15 @@
|
||||
## Decisions
|
||||
|
||||
- **Вкладка в адресе** (`?tab=proposal|design|specs|tasks|comments|tests|merge|activity`),
|
||||
серверный рендер одной вкладки; по умолчанию — Proposal, если change есть, иначе Comments.
|
||||
Ссылки вкладок — обычные `<Link>`, без клиентского состояния.
|
||||
- **Комментарий PM = событие `pm_comment` `{userId, login, text}`**: без миграции, попадает в
|
||||
Activity и в `get_task` (раздел «Комментарии PM»). Флажок
|
||||
«Отправить агенту сейчас» вставляет текст в живую сессию (`sendToSession`).
|
||||
- **«Принять и смержить»** (`acceptStory` в runner/flow.ts): есть открытое сообщение «готово к
|
||||
ревью» → `acceptTask` (как кнопка в боте); нет — тот же порядок вручную: `mergeTaskPr`
|
||||
(гейт PEP-57), `done`, `syncWorkspace`. Только для стори в `review`.
|
||||
- **Markdown** рендерится в React-элементы (никакого `dangerouslySetInnerHTML`), ссылки только
|
||||
`http(s)`/относительные.
|
||||
- **Автор события**: `payload.login` (PM), иначе `session_id` → «агент · сессия #N», иначе
|
||||
«система».
|
||||
@ -0,0 +1,36 @@
|
||||
## Why
|
||||
|
||||
Страница стори — одна лента: описание, сессии, вопросы, OpenSpec сырым текстом, события.
|
||||
Дельта-спецификации change не видны вообще, прогресс tasks.md не посчитан, PR и проверки — в
|
||||
боковой панели. PEP-32: вкладки по артефактам OpenSpec и ходу работы.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Шапка над вкладками: ключ, название, статус, эпик, прогресс tasks.md (PEP-33), кнопки
|
||||
(PR, «Изменить» — название, описание, эпик), запуск агента и активная сессия (терминал PEP-9 и
|
||||
лента шагов PEP-33).
|
||||
- Вкладки `?tab=`: **Proposal** · **Design** (Markdown change, рендер), **Specs** (дельта-спеки
|
||||
`specs/*/spec.md`: ADDED/MODIFIED/REMOVED/RENAMED, требования и сценарии), **Tasks** (чек-лист
|
||||
tasks.md с прогрессом x/y по разделам), **Comments** (вопросы агента и ответы PM + комментарии
|
||||
PM: событие `pm_comment`, агент видит их в `get_task`, по флажку текст уходит и в живую
|
||||
сессию), **Tests** (проверки PEP-57 по каждой проверке с логом, ревьюер PEP-26; без `checks` —
|
||||
«проверки не настроены»), **Merge request** (PR: номер, ветка, головной SHA, мерж/конфликты,
|
||||
ссылки на PR и дифф, кнопка «Принять и смержить» в ревью — тот же гейт, что у «Принять»),
|
||||
**Activity** (события стори и сессий с автором: агент сессии #N, PM по логину, система).
|
||||
- Работает и для архивного change (`openspec/changes/archive/<дата>-<id>`).
|
||||
- Свой безопасный рендер Markdown (`components/Markdown.tsx`: заголовки, списки, чекбоксы,
|
||||
код, таблицы, ссылки http(s)) — без HTML из файла и без новых зависимостей.
|
||||
- `core/openspec.ts`: чтение change (артефакты, дельта-спеки, разбор tasks.md) — общий для веба
|
||||
и прогресса PEP-33; `lib/queries.openspecArtifacts` уходит.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
- `story-page`: страница стори с вкладками.
|
||||
|
||||
## Impact
|
||||
|
||||
- `apps/web/app/(app)/t/[key]/page.tsx` (+ компоненты вкладок), `components/Markdown.tsx`,
|
||||
`actions.ts` (`editStoryAction`, `commentStoryAction`, `acceptStoryAction`),
|
||||
`core/openspec.ts`, `core/tasks.ts` (комментарии PM в `TaskDetails`), MCP `format.ts`,
|
||||
`runner/flow.ts` (`acceptStory`). Миграций нет.
|
||||
@ -0,0 +1,52 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Вкладки страницы стори
|
||||
Страница стори SHALL иметь шапку (ключ, название, статус, эпик, прогресс tasks.md, кнопки
|
||||
действий, запуск агента и активная сессия) и вкладки Proposal, Design, Specs, Tasks, Comments,
|
||||
Tests, Merge request, Activity; выбранная вкладка хранится в адресе (`?tab=`). Proposal и
|
||||
Design показывают Markdown change отрендеренным, Specs — дельта-спецификации change
|
||||
(операция, требования, сценарии), Tasks — чек-лист tasks.md с прогрессом x/y. Всё это работает и
|
||||
для архивного change.
|
||||
|
||||
#### Scenario: Спеки архивного change
|
||||
- **GIVEN** change `pay-3-checkout` стори PAY-3 заархивирован с дельтой `specs/checkout/spec.md`
|
||||
- **WHEN** PM открывает `/t/PAY-3?tab=specs`
|
||||
- **THEN** видна спека `checkout` с её требованиями и сценариями
|
||||
|
||||
#### Scenario: Ссылка на вкладку
|
||||
- **WHEN** PM открывает `/t/PAY-3?tab=tasks`
|
||||
- **THEN** открыта вкладка Tasks с прогрессом «7/12»
|
||||
|
||||
#### Scenario: Нет change
|
||||
- **GIVEN** у стори PAY-4 нет OpenSpec change
|
||||
- **WHEN** PM открывает её страницу
|
||||
- **THEN** открыта вкладка Comments, вкладки артефактов говорят «Change ещё не создан»
|
||||
|
||||
### Requirement: Комментарии PM, которые видит агент
|
||||
На вкладке Comments PM SHALL видеть вопросы агента и ответы и оставлять комментарий к стори;
|
||||
комментарий сохраняется с логином автора, показывается в Activity и в `get_task` агента, по
|
||||
флажку «Отправить агенту сейчас» вставляется в живую сессию.
|
||||
|
||||
#### Scenario: Комментарий
|
||||
- **WHEN** PM пишет комментарий «Кнопку сделать зелёной» к PAY-3
|
||||
- **THEN** `get_task PAY-3` содержит раздел «Комментарии PM» с этим текстом и логином PM
|
||||
|
||||
### Requirement: Проверки и merge request стори
|
||||
Вкладка Tests SHALL показывать проверки головного коммита (каждая с состоянием и хвостом лога
|
||||
у упавших) и последнее ревью агента-ревьюера; без настроенных проверок — «проверки не
|
||||
настроены». Вкладка Merge request SHALL показывать PR (номер, ветка, головной SHA, смержен ли,
|
||||
конфликты, ссылки на PR и дифф) и для стори в ревью — кнопку «Принять и смержить» с тем же
|
||||
гейтом, что у «Принять».
|
||||
|
||||
#### Scenario: Мерж из вкладки
|
||||
- **GIVEN** PAY-3 в ревью, проверки PR зелёные
|
||||
- **WHEN** PM жмёт «Принять и смержить»
|
||||
- **THEN** PR смержен, стори `done`, сообщение «готово к ревью» отвечено
|
||||
|
||||
### Requirement: Редактирование стори в вебе
|
||||
PM SHALL менять название, описание и эпик стори из шапки страницы; изменение пишется в
|
||||
журнал (`task_updated`) и не запускает агента.
|
||||
|
||||
#### Scenario: Сменить эпик
|
||||
- **WHEN** PM выбирает для PAY-3 эпик «Оплата»
|
||||
- **THEN** у стори эпик «Оплата», в Activity событие с автором-PM
|
||||
@ -0,0 +1,18 @@
|
||||
## 1. Данные
|
||||
|
||||
- [x] 1.1 `core/openspec.ts`: change (в т.ч. архивный), дельта-спеки, разбор tasks.md
|
||||
- [x] 1.2 Комментарии PM (`pm_comment`) в `TaskDetails` и `get_task`
|
||||
- [x] 1.3 `acceptStory` (runner/flow.ts)
|
||||
|
||||
## 2. Веб
|
||||
|
||||
- [x] 2.1 `Markdown` — безопасный рендер
|
||||
- [x] 2.2 Шапка: статус, эпик, прогресс, кнопки, «Изменить», агент и активная сессия
|
||||
- [x] 2.3 Вкладки Proposal, Design, Specs, Tasks
|
||||
- [x] 2.4 Вкладки Comments, Tests, Merge request, Activity
|
||||
- [x] 2.5 Server actions: редактирование, комментарий, принять и смержить
|
||||
|
||||
## 3. Проверка
|
||||
|
||||
- [x] 3.1 e2e: разбор change/спек/tasks.md (архивный), комментарий в get_task, acceptStory
|
||||
- [x] 3.2 UI на копии базы; AGENTS.md
|
||||
@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-14
|
||||
@ -0,0 +1,15 @@
|
||||
## Decisions
|
||||
|
||||
- **Шаг = строка `events` (`type = 'step'`)**, без новой таблицы: у событий уже есть проект,
|
||||
стори и сессия, индекс по сессии; размер держим удалением всего, что старше 200 последних
|
||||
шагов сессии (на каждой вставке, одним DELETE по id).
|
||||
- **Асинхронный хук.** `PostToolUse` с `async: true`: Claude не ждёт процесс `peppa-hook`, цена —
|
||||
один `node` на вызов инструмента в фоне. Поколение (`PEPPA_GENERATION`) проверяется как у
|
||||
остальных хуков.
|
||||
- **Текст шага** — короткий: команда (первая строка, 200 символов), путь файла относительно
|
||||
рабочей копии, паттерн поиска, URL; для `mcp__peppa__*` — имя инструмента.
|
||||
- **Прогресс из tasks.md рабочей копии**: агент отмечает пункты `- [x]` по ходу работы
|
||||
(правила OpenSpec), отдельного учёта не нужно. Нет change или файла — прогресса нет.
|
||||
- **Лента живёт в браузере**: SSE `steps:<sessionId>` присылает `step` с данными, компонент
|
||||
дописывает их сверху без `router.refresh()`; новые шаги не меняют отпечаток стори, чтобы
|
||||
страница не перерисовывалась на каждый вызов инструмента.
|
||||
@ -0,0 +1,31 @@
|
||||
## Why
|
||||
|
||||
Про работающего агента видно только «работает»: чтобы понять, что он делает, PM открывает
|
||||
терминал. PEP-33: лента последних действий агента (команда, файл, тест), текущий пункт
|
||||
tasks.md и прогресс x/y на карточке, странице стори и доске.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Хук Claude `PostToolUse` / `PostToolUseFailure` (асинхронный, `async: true` — не тормозит
|
||||
агента) → `peppa-hook tool-use` → событие сессии `step` `{tool, kind, text, ok}`: kind —
|
||||
`command` | `test` | `edit` | `read` | `search` | `web` | `agent` | `mcp` | `other`; тест —
|
||||
команда, похожая на запуск тестов. Хранятся последние 200 шагов сессии (старые удаляются),
|
||||
`last_activity_at` обновляется. `AskUserQuestion` и чтение задач Пеппы не пишутся.
|
||||
- Шаги не засоряют журнал: «События»/Activity, `get_task` и отпечатки PEP-37 их пропускают.
|
||||
- `taskProgress(project, change)` (core): пункты tasks.md change из рабочей копии — `done/total`
|
||||
и текущий (первый незакрытый) пункт; на доске (карточки в работе), в шапке стори и у сессии.
|
||||
- Живая лента `components/AgentSteps.tsx` у активной сессии на странице стори и в панели
|
||||
раннера: начальные шаги с сервера, новые — событием `step` канала PEP-37
|
||||
(`/api/live?scope=steps:<sessionId>`), рядом с терминалом PEP-9.
|
||||
- Codex и OpenCode хуков на шаги не имеют — лента у них пустая с пояснением.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
- `agent-steps`: лента шагов агента и прогресс tasks.md.
|
||||
|
||||
## Impact
|
||||
|
||||
- `runner/run-settings.ts`, `runner/hook.ts`, `core/steps.ts` (классификация, хранение,
|
||||
прогресс), `runner/live.ts` (поток шагов), веб: `AgentSteps`, `Board`, страница стори,
|
||||
`RunnerConsole`. Миграций нет (таблица `events`).
|
||||
@ -0,0 +1,38 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Лента шагов агента
|
||||
Раннер SHALL записывать каждый вызов инструмента агента Claude (хук `PostToolUse` /
|
||||
`PostToolUseFailure`, асинхронно) как шаг сессии: вид (команда, тест, правка, чтение, поиск,
|
||||
веб, субагент, MCP), короткий текст и успех. Хранятся последние 200 шагов сессии. Веб SHALL
|
||||
показывать ленту последних шагов у активной сессии на странице стори и в панели раннера и
|
||||
дописывать новые шаги в реальном времени (PEP-37). Шаги не попадают в журнал событий стори и в
|
||||
`get_task`.
|
||||
|
||||
#### Scenario: Агент запустил тесты
|
||||
- **GIVEN** сессия #12 стори PAY-3 работает
|
||||
- **WHEN** агент выполняет `pnpm test`
|
||||
- **THEN** у сессии #12 появляется шаг вида «тест» с текстом `pnpm test`, PM видит его в ленте
|
||||
страницы PAY-3 без перезагрузки
|
||||
|
||||
#### Scenario: Неудачная команда
|
||||
- **WHEN** команда агента падает (`PostToolUseFailure`)
|
||||
- **THEN** шаг отмечен как неудачный
|
||||
|
||||
#### Scenario: Старый хук
|
||||
- **GIVEN** сессию #12 возобновили (поколение 2)
|
||||
- **WHEN** приходит `tool-use` из поколения 1
|
||||
- **THEN** шаг не записывается
|
||||
|
||||
#### Scenario: Предел хранения
|
||||
- **WHEN** у сессии записано больше 200 шагов
|
||||
- **THEN** остаются 200 последних
|
||||
|
||||
### Requirement: Прогресс tasks.md
|
||||
Веб SHALL показывать для стори с OpenSpec change прогресс пунктов tasks.md рабочей копии
|
||||
(«7/12») и текущий (первый незакрытый) пункт: в шапке страницы стори, у активной сессии и на
|
||||
карточках доски в колонке «В работе».
|
||||
|
||||
#### Scenario: Прогресс на доске
|
||||
- **GIVEN** tasks.md change стори PAY-3: 12 пунктов, 7 отмечены, восьмой — «2.3 Кнопка оплаты»
|
||||
- **WHEN** PM открывает доску PAY
|
||||
- **THEN** на карточке PAY-3 «7/12» и «2.3 Кнопка оплаты»
|
||||
@ -0,0 +1,19 @@
|
||||
## 1. Запись шагов
|
||||
|
||||
- [x] 1.1 `core/steps.ts`: классификация вызова, `recordStep` с пределом 200, `sessionSteps`
|
||||
- [x] 1.2 Хуки `PostToolUse`/`PostToolUseFailure` (async) → `peppa-hook tool-use`
|
||||
- [x] 1.3 Шаги исключены из журнала стори, `get_task`, панели раннера
|
||||
|
||||
## 2. Прогресс
|
||||
|
||||
- [x] 2.1 `taskProgress` по tasks.md (done/total, текущий пункт)
|
||||
- [x] 2.2 Доска, шапка стори, сессия
|
||||
|
||||
## 3. Живая лента
|
||||
|
||||
- [x] 3.1 Поток `steps:<sessionId>` в хабе PEP-37
|
||||
- [x] 3.2 `AgentSteps` на странице стори и в панели раннера
|
||||
|
||||
## 4. Проверка
|
||||
|
||||
- [x] 4.1 e2e: хук пишет шаг, классификация, старое поколение, предел 200, прогресс, поток шагов
|
||||
@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-14
|
||||
@ -0,0 +1,26 @@
|
||||
## Context
|
||||
|
||||
`notify()` (PEP-36) пишет строку JSON в unix-сокеты подписчиков из `SUBSCRIBERS`; бот вдобавок
|
||||
смотрит `PRAGMA data_version`. Веб — `next dev`/`next start`, один процесс; терминал PEP-9 уже
|
||||
держит SSE через Cloudflare (пинг 15 с, `no-transform`).
|
||||
|
||||
## Decisions
|
||||
|
||||
- **Будильник, а не данные.** Клиент получает только «в твоей области изменилось» и делает
|
||||
`router.refresh()`: серверные компоненты остаются единственным источником разметки, React
|
||||
сверяет дерево без мигания, состояние клиентских компонентов и введённый текст сохраняются.
|
||||
Точечные данные (лента шагов PEP-33) — отдельные события того же канала.
|
||||
- **Отпечаток области** вместо разбора типов уведомлений: хуки, вачдог и CLI пишут из других
|
||||
процессов и не всегда зовут `notify()`; `data_version` ловит любые записи, а отпечаток
|
||||
отсекает шум (heartbeat, outbox). Отпечатки считаются только для областей, у которых есть
|
||||
зрители, и не чаще раза в 250 мс.
|
||||
- **Сокет `web.events.sock`** слушает хаб в процессе веба; `listenEvents` удаляет старый файл,
|
||||
поэтому второй веб с тем же `PEPPA_HOME` отнимает сокет — тогда первый живёт на
|
||||
`data_version` (секунда задержки). Ошибка привязки сокета не роняет хаб.
|
||||
- **Откат на опрос.** `EventSource` сам переподключается; после 3 ошибок подряд без открытия
|
||||
клиент включает таймер 5 с (поведение `AutoRefresh`) и раз в 30 с пробует SSE снова.
|
||||
|
||||
## Risks
|
||||
|
||||
- Отпечаток `home`/`runners` не фильтруется по пользователю — лишнее обновление у чужого
|
||||
пользователя возможно, данных он не получает.
|
||||
@ -0,0 +1,34 @@
|
||||
## Why
|
||||
|
||||
Страницы веба (Главная, проект, стори, раннеры) перезагружают данные таймером раз в 5 секунд
|
||||
(`AutoRefresh`): лишняя нагрузка, задержка до 5 с и ни одного признака, что связь жива. PEP-37:
|
||||
канал событий сервер → браузер, который будит страницу, только когда в её области что-то
|
||||
поменялось; основа для ленты шагов (PEP-33) и терминала (PEP-9).
|
||||
|
||||
## What Changes
|
||||
|
||||
- Веб-процесс держит один общий «хаб изменений» (`runner/live.ts`, `globalThis`): его будят
|
||||
`notify()` (новый подписчик `web` — сокет `$PEPPA_HOME/web.events.sock`, те же события, что
|
||||
слушает бот) и `PRAGMA data_version` (запасной опрос раз в секунду: хуки и вачдог — другие
|
||||
процессы). На пробуждение хаб считает отпечаток каждой области, на которую есть зрители, и
|
||||
шлёт `change` только тем, у кого отпечаток сменился.
|
||||
- Области: `home` (вопросы, раннеры, стори проектов пользователя), `project:<id>`,
|
||||
`task:<id>`, `runners`. Отпечаток — один SQL на область, без частых полей (`last_activity_at`).
|
||||
- `GET /api/live?scope=…` — SSE (`text/event-stream`, `no-cache, no-transform`,
|
||||
`X-Accel-Buffering: no`, пинг 15 с, `retry: 3000`) для Cloudflare; доступ к проекту/стори
|
||||
проверяется (`projectForUser`).
|
||||
- `components/LiveRefresh.tsx` вместо `AutoRefresh`: `EventSource` → `router.refresh()` с
|
||||
дебаунсом; пока пользователь печатает или оставил черновик — откладывает обновление;
|
||||
индикатор соединения (зелёная точка «в реальном времени» / «переподключение» / «опрос»).
|
||||
Нет SSE (ошибка 3 раза подряд) — откат на прежний опрос 5 с.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
- `live-updates`: живые обновления веба по событиям.
|
||||
|
||||
## Impact
|
||||
|
||||
- `packages/core/src/notify.ts` (подписчик `web`), `packages/runner/src/live.ts` (хаб, SSE),
|
||||
`apps/web/app/api/live/route.ts`, `apps/web/components/LiveRefresh.tsx`, страницы с
|
||||
`AutoRefresh`. Миграций и зависимостей нет.
|
||||
@ -0,0 +1,37 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Канал изменений сервер → браузер
|
||||
Веб SHALL отдавать поток SSE `GET /api/live?scope=<область>` (области `home`, `runners`,
|
||||
`project:<id>`, `task:<id>`), который присылает событие `change`, когда в области поменялись
|
||||
данные (стори, вопросы, сессии, события), по уведомлениям `notify()` и по `PRAGMA data_version`.
|
||||
Поток не буферизуется прокси: `Cache-Control: no-cache, no-transform`, `X-Accel-Buffering: no`,
|
||||
пинг каждые 15 с. Доступ к проекту и стори проверяется как на странице.
|
||||
|
||||
#### Scenario: Вопрос появился
|
||||
- **GIVEN** PM открыл стори PAY-3, браузер подписан на `task:<id PAY-3>`
|
||||
- **WHEN** агент задаёт вопрос по PAY-3
|
||||
- **THEN** в поток приходит `change` в пределах пары секунд
|
||||
|
||||
#### Scenario: Шум не будит страницу
|
||||
- **GIVEN** браузер подписан на `task:<id PAY-3>`
|
||||
- **WHEN** вачдог пишет heartbeat, а другая стори меняет статус
|
||||
- **THEN** `change` для PAY-3 не приходит
|
||||
|
||||
#### Scenario: Чужая стори
|
||||
- **WHEN** пользователь без доступа к проекту PAY подписывается на `task:<id PAY-3>`
|
||||
- **THEN** ответ 404
|
||||
|
||||
### Requirement: Точечное обновление страницы и индикатор связи
|
||||
Страницы Главная, проект, стори и раннеры SHALL обновляться по событиям канала без
|
||||
перезагрузки и без потери введённого текста (обновление откладывается, пока пользователь
|
||||
печатает или оставил черновик), и показывать состояние связи: «в реальном времени»,
|
||||
«переподключение» или «опрос». Если канал недоступен, страница откатывается на опрос раз в 5 с.
|
||||
|
||||
#### Scenario: Черновик ответа
|
||||
- **GIVEN** PM печатает ответ на вопрос на странице стори
|
||||
- **WHEN** приходит `change`
|
||||
- **THEN** текст не теряется, страница обновится, когда поле отправят или очистят
|
||||
|
||||
#### Scenario: Канал недоступен
|
||||
- **WHEN** `/api/live` трижды подряд не открывается
|
||||
- **THEN** индикатор показывает «опрос», страница обновляется раз в 5 с
|
||||
@ -0,0 +1,15 @@
|
||||
## 1. Сервер
|
||||
|
||||
- [x] 1.1 Подписчик `web` в `notify()`
|
||||
- [x] 1.2 Хаб изменений `runner/live.ts`: data_version + сокет, отпечатки областей, подписка
|
||||
- [x] 1.3 SSE `GET /api/live?scope=` с проверкой доступа
|
||||
|
||||
## 2. Клиент
|
||||
|
||||
- [x] 2.1 `LiveRefresh` (EventSource, дебаунс, черновики, индикатор, откат на опрос)
|
||||
- [x] 2.2 Заменить `AutoRefresh` на страницах
|
||||
|
||||
## 3. Проверка
|
||||
|
||||
- [x] 3.1 e2e: отпечатки и `change` по областям, шум не будит, чужая область → 404
|
||||
- [x] 3.2 Документация (AGENTS.md)
|
||||
43
openspec/specs/agent-steps/spec.md
Normal file
43
openspec/specs/agent-steps/spec.md
Normal file
@ -0,0 +1,43 @@
|
||||
# agent-steps Specification
|
||||
|
||||
## Purpose
|
||||
Что агент делает сейчас: лента шагов (вызовов инструментов) раннера и прогресс tasks.md на карточках (PEP-33).
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Лента шагов агента
|
||||
Раннер SHALL записывать каждый вызов инструмента агента Claude (хук `PostToolUse` /
|
||||
`PostToolUseFailure`, асинхронно) как шаг сессии: вид (команда, тест, правка, чтение, поиск,
|
||||
веб, субагент, MCP), короткий текст и успех. Хранятся последние 200 шагов сессии. Веб SHALL
|
||||
показывать ленту последних шагов у активной сессии на странице стори и в панели раннера и
|
||||
дописывать новые шаги в реальном времени (PEP-37). Шаги не попадают в журнал событий стори и в
|
||||
`get_task`.
|
||||
|
||||
#### Scenario: Агент запустил тесты
|
||||
- **GIVEN** сессия #12 стори PAY-3 работает
|
||||
- **WHEN** агент выполняет `pnpm test`
|
||||
- **THEN** у сессии #12 появляется шаг вида «тест» с текстом `pnpm test`, PM видит его в ленте
|
||||
страницы PAY-3 без перезагрузки
|
||||
|
||||
#### Scenario: Неудачная команда
|
||||
- **WHEN** команда агента падает (`PostToolUseFailure`)
|
||||
- **THEN** шаг отмечен как неудачный
|
||||
|
||||
#### Scenario: Старый хук
|
||||
- **GIVEN** сессию #12 возобновили (поколение 2)
|
||||
- **WHEN** приходит `tool-use` из поколения 1
|
||||
- **THEN** шаг не записывается
|
||||
|
||||
#### Scenario: Предел хранения
|
||||
- **WHEN** у сессии записано больше 200 шагов
|
||||
- **THEN** остаются 200 последних
|
||||
|
||||
### Requirement: Прогресс tasks.md
|
||||
Веб SHALL показывать для стори с OpenSpec change прогресс пунктов tasks.md рабочей копии
|
||||
(«7/12») и текущий (первый незакрытый) пункт: в шапке страницы стори, у активной сессии и на
|
||||
карточках доски в колонке «В работе».
|
||||
|
||||
#### Scenario: Прогресс на доске
|
||||
- **GIVEN** tasks.md change стори PAY-3: 12 пунктов, 7 отмечены, восьмой — «2.3 Кнопка оплаты»
|
||||
- **WHEN** PM открывает доску PAY
|
||||
- **THEN** на карточке PAY-3 «7/12» и «2.3 Кнопка оплаты»
|
||||
42
openspec/specs/live-updates/spec.md
Normal file
42
openspec/specs/live-updates/spec.md
Normal file
@ -0,0 +1,42 @@
|
||||
# live-updates Specification
|
||||
|
||||
## Purpose
|
||||
Живые обновления веба: канал SSE сервер → браузер будит страницы, когда в их области меняются данные (PEP-37).
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Канал изменений сервер → браузер
|
||||
Веб SHALL отдавать поток SSE `GET /api/live?scope=<область>` (области `home`, `runners`,
|
||||
`project:<id>`, `task:<id>`), который присылает событие `change`, когда в области поменялись
|
||||
данные (стори, вопросы, сессии, события), по уведомлениям `notify()` и по `PRAGMA data_version`.
|
||||
Поток не буферизуется прокси: `Cache-Control: no-cache, no-transform`, `X-Accel-Buffering: no`,
|
||||
пинг каждые 15 с. Доступ к проекту и стори проверяется как на странице.
|
||||
|
||||
#### Scenario: Вопрос появился
|
||||
- **GIVEN** PM открыл стори PAY-3, браузер подписан на `task:<id PAY-3>`
|
||||
- **WHEN** агент задаёт вопрос по PAY-3
|
||||
- **THEN** в поток приходит `change` в пределах пары секунд
|
||||
|
||||
#### Scenario: Шум не будит страницу
|
||||
- **GIVEN** браузер подписан на `task:<id PAY-3>`
|
||||
- **WHEN** вачдог пишет heartbeat, а другая стори меняет статус
|
||||
- **THEN** `change` для PAY-3 не приходит
|
||||
|
||||
#### Scenario: Чужая стори
|
||||
- **WHEN** пользователь без доступа к проекту PAY подписывается на `task:<id PAY-3>`
|
||||
- **THEN** ответ 404
|
||||
|
||||
### Requirement: Точечное обновление страницы и индикатор связи
|
||||
Страницы Главная, проект, стори и раннеры SHALL обновляться по событиям канала без
|
||||
перезагрузки и без потери введённого текста (обновление откладывается, пока пользователь
|
||||
печатает или оставил черновик), и показывать состояние связи: «в реальном времени»,
|
||||
«переподключение» или «опрос». Если канал недоступен, страница откатывается на опрос раз в 5 с.
|
||||
|
||||
#### Scenario: Черновик ответа
|
||||
- **GIVEN** PM печатает ответ на вопрос на странице стори
|
||||
- **WHEN** приходит `change`
|
||||
- **THEN** текст не теряется, страница обновится, когда поле отправят или очистят
|
||||
|
||||
#### Scenario: Канал недоступен
|
||||
- **WHEN** `/api/live` трижды подряд не открывается
|
||||
- **THEN** индикатор показывает «опрос», страница обновляется раз в 5 с
|
||||
57
openspec/specs/story-page/spec.md
Normal file
57
openspec/specs/story-page/spec.md
Normal file
@ -0,0 +1,57 @@
|
||||
# story-page Specification
|
||||
|
||||
## Purpose
|
||||
Страница стори в вебе: шапка, агент и вкладки по артефактам OpenSpec и ходу работы (PEP-32).
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Вкладки страницы стори
|
||||
Страница стори SHALL иметь шапку (ключ, название, статус, эпик, прогресс tasks.md, кнопки
|
||||
действий, запуск агента и активная сессия) и вкладки Proposal, Design, Specs, Tasks, Comments,
|
||||
Tests, Merge request, Activity; выбранная вкладка хранится в адресе (`?tab=`). Proposal и
|
||||
Design показывают Markdown change отрендеренным, Specs — дельта-спецификации change
|
||||
(операция, требования, сценарии), Tasks — чек-лист tasks.md с прогрессом x/y. Всё это работает и
|
||||
для архивного change.
|
||||
|
||||
#### Scenario: Спеки архивного change
|
||||
- **GIVEN** change `pay-3-checkout` стори PAY-3 заархивирован с дельтой `specs/checkout/spec.md`
|
||||
- **WHEN** PM открывает `/t/PAY-3?tab=specs`
|
||||
- **THEN** видна спека `checkout` с её требованиями и сценариями
|
||||
|
||||
#### Scenario: Ссылка на вкладку
|
||||
- **WHEN** PM открывает `/t/PAY-3?tab=tasks`
|
||||
- **THEN** открыта вкладка Tasks с прогрессом «7/12»
|
||||
|
||||
#### Scenario: Нет change
|
||||
- **GIVEN** у стори PAY-4 нет OpenSpec change
|
||||
- **WHEN** PM открывает её страницу
|
||||
- **THEN** открыта вкладка Comments, вкладки артефактов говорят «Change ещё не создан»
|
||||
|
||||
### Requirement: Комментарии PM, которые видит агент
|
||||
На вкладке Comments PM SHALL видеть вопросы агента и ответы и оставлять комментарий к стори;
|
||||
комментарий сохраняется с логином автора, показывается в Activity и в `get_task` агента, по
|
||||
флажку «Отправить агенту сейчас» вставляется в живую сессию.
|
||||
|
||||
#### Scenario: Комментарий
|
||||
- **WHEN** PM пишет комментарий «Кнопку сделать зелёной» к PAY-3
|
||||
- **THEN** `get_task PAY-3` содержит раздел «Комментарии PM» с этим текстом и логином PM
|
||||
|
||||
### Requirement: Проверки и merge request стори
|
||||
Вкладка Tests SHALL показывать проверки головного коммита (каждая с состоянием и хвостом лога
|
||||
у упавших) и последнее ревью агента-ревьюера; без настроенных проверок — «проверки не
|
||||
настроены». Вкладка Merge request SHALL показывать PR (номер, ветка, головной SHA, смержен ли,
|
||||
конфликты, ссылки на PR и дифф) и для стори в ревью — кнопку «Принять и смержить» с тем же
|
||||
гейтом, что у «Принять».
|
||||
|
||||
#### Scenario: Мерж из вкладки
|
||||
- **GIVEN** PAY-3 в ревью, проверки PR зелёные
|
||||
- **WHEN** PM жмёт «Принять и смержить»
|
||||
- **THEN** PR смержен, стори `done`, сообщение «готово к ревью» отвечено
|
||||
|
||||
### Requirement: Редактирование стори в вебе
|
||||
PM SHALL менять название, описание и эпик стори из шапки страницы; изменение пишется в
|
||||
журнал (`task_updated`) и не запускает агента.
|
||||
|
||||
#### Scenario: Сменить эпик
|
||||
- **WHEN** PM выбирает для PAY-3 эпик «Оплата»
|
||||
- **THEN** у стори эпик «Оплата», в Activity событие с автором-PM
|
||||
@ -26,3 +26,5 @@ export * from "./webpush.ts";
|
||||
export * from "./notifications.ts";
|
||||
export * from "./digest.ts";
|
||||
export * from "./autonomy.ts";
|
||||
export * from "./openspec.ts";
|
||||
export * from "./steps.ts";
|
||||
|
||||
@ -12,8 +12,8 @@ export type PeppaNotification =
|
||||
| { type: "session_updated"; sessionId: number }
|
||||
| { type: "incident"; incidentId: number };
|
||||
|
||||
/** Services that want live updates; each listens on its own unix socket in PEPPA_HOME. */
|
||||
export const SUBSCRIBERS = ["bot"] as const;
|
||||
/** Services that want live updates; each listens on its own unix socket in PEPPA_HOME (web: PEP-37). */
|
||||
export const SUBSCRIBERS = ["bot", "web"] as const;
|
||||
export type Subscriber = (typeof SUBSCRIBERS)[number];
|
||||
|
||||
export const eventsSocket = (service: Subscriber) => join(peppaHome(), `${service}.events.sock`);
|
||||
|
||||
167
packages/core/src/openspec.ts
Normal file
167
packages/core/src/openspec.ts
Normal file
@ -0,0 +1,167 @@
|
||||
// An OpenSpec change of a story as the web shows it (PEP-32) and its tasks.md progress
|
||||
// (PEP-33): read from the project's working copy, active or archived.
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import type { Project } from "./projects.ts";
|
||||
|
||||
export type DeltaOp = "ADDED" | "MODIFIED" | "REMOVED" | "RENAMED";
|
||||
|
||||
export interface SpecScenario {
|
||||
name: string;
|
||||
body: string;
|
||||
}
|
||||
export interface SpecRequirement {
|
||||
name: string;
|
||||
body: string;
|
||||
scenarios: SpecScenario[];
|
||||
}
|
||||
export interface DeltaSpec {
|
||||
/** Capability: the folder under the change's specs/. */
|
||||
capability: string;
|
||||
sections: Array<{ op: DeltaOp; requirements: SpecRequirement[] }>;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface TaskItem {
|
||||
text: string;
|
||||
done: boolean;
|
||||
}
|
||||
export interface TasksProgress {
|
||||
done: number;
|
||||
total: number;
|
||||
/** The first unchecked item — what the agent is on now. */
|
||||
current: string | null;
|
||||
sections: Array<{ title: string; items: TaskItem[] }>;
|
||||
}
|
||||
|
||||
export interface ChangeArtifacts {
|
||||
id: string;
|
||||
dir: string;
|
||||
archived: boolean;
|
||||
proposal: string | null;
|
||||
design: string | null;
|
||||
tasks: string | null;
|
||||
specs: DeltaSpec[];
|
||||
}
|
||||
|
||||
/** openspec/changes/<id>, or openspec/changes/archive/<date>-<id> once archived. */
|
||||
export function findChangeDir(workspacePath: string, change: string): { dir: string; archived: boolean } | null {
|
||||
if (!change || /[/\\]|^\.\.?$/.test(change)) return null;
|
||||
const changes = join(workspacePath, "openspec", "changes");
|
||||
const dir = join(changes, change);
|
||||
if (existsSync(dir)) return { dir, archived: false };
|
||||
const archive = join(changes, "archive");
|
||||
if (!existsSync(archive)) return null;
|
||||
const hit = readdirSync(archive)
|
||||
.filter((d) => d === change || d.endsWith(`-${change}`))
|
||||
.sort()
|
||||
.pop();
|
||||
return hit ? { dir: join(archive, hit), archived: true } : null;
|
||||
}
|
||||
|
||||
const readIf = (path: string) => (existsSync(path) ? readFileSync(path, "utf8") : null);
|
||||
|
||||
export function readChange(project: Pick<Project, "workspacePath">, change: string | null): ChangeArtifacts | null {
|
||||
if (!change) return null;
|
||||
const found = findChangeDir(project.workspacePath, change);
|
||||
if (!found) return null;
|
||||
const specsDir = join(found.dir, "specs");
|
||||
const specs = existsSync(specsDir)
|
||||
? readdirSync(specsDir, { withFileTypes: true })
|
||||
.filter((d) => d.isDirectory() && existsSync(join(specsDir, d.name, "spec.md")))
|
||||
.map((d) => parseDeltaSpec(d.name, readFileSync(join(specsDir, d.name, "spec.md"), "utf8")))
|
||||
.sort((a, b) => a.capability.localeCompare(b.capability))
|
||||
: [];
|
||||
return {
|
||||
id: change,
|
||||
dir: found.dir,
|
||||
archived: found.archived,
|
||||
proposal: readIf(join(found.dir, "proposal.md")),
|
||||
design: readIf(join(found.dir, "design.md")),
|
||||
tasks: readIf(join(found.dir, "tasks.md")),
|
||||
specs,
|
||||
};
|
||||
}
|
||||
|
||||
/** `## ADDED Requirements` → `### Requirement: …` → `#### Scenario: …`. */
|
||||
export function parseDeltaSpec(capability: string, text: string): DeltaSpec {
|
||||
const sections: DeltaSpec["sections"] = [];
|
||||
let req: SpecRequirement | null = null;
|
||||
let scen: SpecScenario | null = null;
|
||||
for (const line of text.split("\n")) {
|
||||
const op = line.match(/^##\s+(ADDED|MODIFIED|REMOVED|RENAMED)\b/i);
|
||||
if (op) {
|
||||
sections.push({ op: op[1]!.toUpperCase() as DeltaOp, requirements: [] });
|
||||
req = scen = null;
|
||||
continue;
|
||||
}
|
||||
const r = line.match(/^###\s+Requirement:\s*(.*)$/);
|
||||
if (r) {
|
||||
if (!sections.length) sections.push({ op: "ADDED", requirements: [] });
|
||||
req = { name: r[1]!.trim(), body: "", scenarios: [] };
|
||||
sections.at(-1)!.requirements.push(req);
|
||||
scen = null;
|
||||
continue;
|
||||
}
|
||||
const s = line.match(/^####\s+Scenario:\s*(.*)$/);
|
||||
if (s && req) {
|
||||
scen = { name: s[1]!.trim(), body: "" };
|
||||
req.scenarios.push(scen);
|
||||
continue;
|
||||
}
|
||||
if (scen) scen.body += `${line}\n`;
|
||||
else if (req) req.body += `${line}\n`;
|
||||
}
|
||||
for (const sec of sections)
|
||||
for (const r of sec.requirements) {
|
||||
r.body = r.body.trim();
|
||||
for (const s of r.scenarios) s.body = s.body.trim();
|
||||
}
|
||||
return { capability, sections, text };
|
||||
}
|
||||
|
||||
/** Checklist of tasks.md: `## 1. Section` headings and `- [ ]` / `- [x]` items. */
|
||||
export function parseTasks(text: string): TasksProgress {
|
||||
const sections: TasksProgress["sections"] = [];
|
||||
for (const line of text.split("\n")) {
|
||||
const h = line.match(/^#{2,3}\s+(.*)$/);
|
||||
if (h) {
|
||||
sections.push({ title: h[1]!.trim(), items: [] });
|
||||
continue;
|
||||
}
|
||||
const item = line.match(/^\s*[-*]\s+\[([ xX])\]\s+(.*)$/);
|
||||
if (!item) continue;
|
||||
if (!sections.length) sections.push({ title: "", items: [] });
|
||||
sections.at(-1)!.items.push({ text: item[2]!.trim(), done: item[1] !== " " });
|
||||
}
|
||||
const items = sections.flatMap((s) => s.items);
|
||||
return {
|
||||
done: items.filter((i) => i.done).length,
|
||||
total: items.length,
|
||||
current: items.find((i) => !i.done)?.text ?? null,
|
||||
sections: sections.filter((s) => s.items.length),
|
||||
};
|
||||
}
|
||||
|
||||
const progressCache = new Map<string, { mtimeMs: number; progress: TasksProgress }>();
|
||||
|
||||
/** tasks.md progress of a story's change (cached by file mtime: the board reads many). */
|
||||
export function taskProgress(project: Pick<Project, "workspacePath">, change: string | null): TasksProgress | null {
|
||||
if (!change) return null;
|
||||
const found = findChangeDir(project.workspacePath, change);
|
||||
if (!found) return null;
|
||||
const path = join(found.dir, "tasks.md");
|
||||
let mtimeMs: number;
|
||||
try {
|
||||
mtimeMs = statSync(path).mtimeMs;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const hit = progressCache.get(path);
|
||||
let progress = hit?.mtimeMs === mtimeMs ? hit.progress : null;
|
||||
if (!progress) {
|
||||
progress = parseTasks(readFileSync(path, "utf8"));
|
||||
progressCache.set(path, { mtimeMs, progress });
|
||||
}
|
||||
return progress.total ? progress : null;
|
||||
}
|
||||
98
packages/core/src/steps.ts
Normal file
98
packages/core/src/steps.ts
Normal file
@ -0,0 +1,98 @@
|
||||
// What the agent is doing now (PEP-33): every tool call of a Claude runner (PostToolUse hook)
|
||||
// becomes a "step" event of its session. Only the last MAX_STEPS per session are kept, and
|
||||
// steps stay out of the story journal (events of other types).
|
||||
import { and, desc, eq, sql } from "drizzle-orm";
|
||||
import { events, sessions, type Db } from "@peppa/db";
|
||||
import { relative, isAbsolute } from "node:path";
|
||||
import type { Session } from "./sessions.ts";
|
||||
|
||||
export const STEP_EVENT = "step";
|
||||
export const MAX_STEPS = 200;
|
||||
|
||||
export type StepKind = "command" | "test" | "edit" | "read" | "search" | "web" | "agent" | "mcp" | "other";
|
||||
|
||||
export interface StepPayload {
|
||||
tool: string;
|
||||
kind: StepKind;
|
||||
text: string;
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
export interface StepView extends StepPayload {
|
||||
id: number;
|
||||
sessionId: number;
|
||||
at: string;
|
||||
}
|
||||
|
||||
/** Tool calls that say nothing about the work (asking the PM, reading the story itself). */
|
||||
const SKIP = new Set(["AskUserQuestion", "TodoWrite", "TodoRead", "ExitPlanMode", "mcp__peppa__get_task", "mcp__peppa__get_rules"]);
|
||||
|
||||
const TEST_RE = /(^|[\s/;&|(])(test|tests|e2e|jest|vitest|pytest|mocha|playwright|rspec|phpunit|ci\.sh|run ci|node --test|go test|cargo test|mix test)(\b|$)/i;
|
||||
|
||||
const oneLine = (s: string, n = 200) => {
|
||||
const first = s.trim().split("\n")[0]!.trim();
|
||||
return first.length > n ? `${first.slice(0, n)}…` : first;
|
||||
};
|
||||
|
||||
function relPath(p: string, cwd?: string): string {
|
||||
if (!cwd || !isAbsolute(p)) return p;
|
||||
const r = relative(cwd, p);
|
||||
return r && !r.startsWith("..") ? r : p;
|
||||
}
|
||||
|
||||
/** Classifies one tool call; null = not worth a step. */
|
||||
export function describeStep(tool: string, input: Record<string, unknown> = {}, cwd?: string): { kind: StepKind; text: string } | null {
|
||||
if (!tool || SKIP.has(tool)) return null;
|
||||
const s = (k: string) => (typeof input[k] === "string" ? (input[k] as string) : "");
|
||||
switch (tool) {
|
||||
case "Bash":
|
||||
case "BashOutput": {
|
||||
const cmd = s("command") || s("description") || tool;
|
||||
return { kind: TEST_RE.test(cmd) ? "test" : "command", text: oneLine(cmd) };
|
||||
}
|
||||
case "Edit":
|
||||
case "MultiEdit":
|
||||
case "Write":
|
||||
case "NotebookEdit":
|
||||
return { kind: "edit", text: relPath(s("file_path") || s("notebook_path"), cwd) || tool };
|
||||
case "Read":
|
||||
return { kind: "read", text: relPath(s("file_path"), cwd) || tool };
|
||||
case "Grep":
|
||||
case "Glob":
|
||||
return { kind: "search", text: oneLine(`${s("pattern")}${s("path") ? ` · ${relPath(s("path"), cwd)}` : ""}`) || tool };
|
||||
case "WebFetch":
|
||||
case "WebSearch":
|
||||
return { kind: "web", text: oneLine(s("url") || s("query")) || tool };
|
||||
case "Task":
|
||||
case "Agent":
|
||||
return { kind: "agent", text: oneLine(s("description") || s("prompt")) || tool };
|
||||
}
|
||||
if (tool.startsWith("mcp__")) return { kind: "mcp", text: tool.replace(/^mcp__/, "").replace("__", " · ") };
|
||||
return { kind: "other", text: tool };
|
||||
}
|
||||
|
||||
/** Stores a step and drops what is older than the last MAX_STEPS of the session. */
|
||||
export async function recordStep(db: Db, s: Pick<Session, "id" | "projectId" | "taskId">, step: StepPayload, now = new Date()) {
|
||||
const [row] = await db.insert(events).values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, type: STEP_EVENT, payload: step, createdAt: now }).returning();
|
||||
// Activity time without notify(): a step is not a status change (the bot needn't wake).
|
||||
await db.update(sessions).set({ lastActivityAt: now }).where(eq(sessions.id, s.id));
|
||||
await db.run(sql`DELETE FROM events WHERE session_id = ${s.id} AND type = ${STEP_EVENT} AND id <= (
|
||||
SELECT id FROM events WHERE session_id = ${s.id} AND type = ${STEP_EVENT} ORDER BY id DESC LIMIT 1 OFFSET ${MAX_STEPS})`);
|
||||
return row!;
|
||||
}
|
||||
|
||||
export function stepView(e: typeof events.$inferSelect): StepView {
|
||||
const p = (e.payload ?? {}) as Partial<StepPayload>;
|
||||
return { id: e.id, sessionId: e.sessionId ?? 0, at: e.createdAt.toISOString(), tool: p.tool ?? "?", kind: p.kind ?? "other", text: p.text ?? "", ok: p.ok !== false };
|
||||
}
|
||||
|
||||
/** Latest steps of a session, newest first. */
|
||||
export async function sessionSteps(db: Db, sessionId: number, limit = 30): Promise<StepView[]> {
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(events)
|
||||
.where(and(eq(events.sessionId, sessionId), eq(events.type, STEP_EVENT)))
|
||||
.orderBy(desc(events.id))
|
||||
.limit(limit);
|
||||
return rows.map(stepView);
|
||||
}
|
||||
@ -1,6 +1,6 @@
|
||||
import { events, goals, projects, questions, taskStatus, tasks, type Db } from "@peppa/db";
|
||||
import { formatTaskKey, parseTaskKey } from "@peppa/shared";
|
||||
import { and, asc, desc, eq, inArray, isNull, sql } from "drizzle-orm";
|
||||
import { and, asc, desc, eq, inArray, isNull, ne, sql } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { notify } from "./notify.ts";
|
||||
import { getGoal, getProject, type Goal, type Project } from "./projects.ts";
|
||||
@ -100,7 +100,8 @@ export interface TaskPatch {
|
||||
prUrl?: string | null;
|
||||
}
|
||||
|
||||
export async function updateTask(db: Db, ref: TaskRef, patch: TaskPatch, sessionId?: number): Promise<Task> {
|
||||
/** `login`: the person who changed it from the web (PEP-32: authors in Activity). */
|
||||
export async function updateTask(db: Db, ref: TaskRef, patch: TaskPatch, sessionId?: number, login?: string): Promise<Task> {
|
||||
if (patch.goalId != null) await getGoal(db, ref.project.id, patch.goalId);
|
||||
const [task] = await db.update(tasks).set(patch).where(eq(tasks.id, ref.task.id)).returning();
|
||||
const changed = Object.fromEntries(
|
||||
@ -112,7 +113,7 @@ export async function updateTask(db: Db, ref: TaskRef, patch: TaskPatch, session
|
||||
taskId: ref.task.id,
|
||||
sessionId,
|
||||
type: "task_updated",
|
||||
payload: { from: pick(ref.task, Object.keys(changed)), to: changed },
|
||||
payload: { from: pick(ref.task, Object.keys(changed)), to: changed, ...(login ? { login } : {}) },
|
||||
});
|
||||
await notify(db, { type: "task_updated", taskId: ref.task.id });
|
||||
}
|
||||
@ -134,6 +135,37 @@ export interface TaskDetails {
|
||||
review: CodeReview | null;
|
||||
/** The project's autonomy settings (PEP-23): agents follow them. */
|
||||
autonomy: AutonomySettings;
|
||||
/** PM comments on the story (PEP-32), oldest first: the agent reads them in get_task. */
|
||||
comments: StoryComment[];
|
||||
}
|
||||
|
||||
export const COMMENT_EVENT = "pm_comment";
|
||||
export interface StoryComment {
|
||||
id: number;
|
||||
login: string;
|
||||
text: string;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
/** A PM comment on a story (PEP-32): an event the agent sees in get_task. */
|
||||
export async function addStoryComment(db: Db, ref: TaskRef, author: { id: number; login: string }, text: string): Promise<StoryComment> {
|
||||
const body = text.trim();
|
||||
if (!body) throw new PeppaError("Пустой комментарий");
|
||||
if (body.length > 8000) throw new PeppaError("Комментарий длиннее 8000 символов");
|
||||
const [row] = await db
|
||||
.insert(events)
|
||||
.values({ projectId: ref.project.id, taskId: ref.task.id, type: COMMENT_EVENT, payload: { userId: author.id, login: author.login, text: body } })
|
||||
.returning();
|
||||
await notify(db, { type: "task_updated", taskId: ref.task.id });
|
||||
return { id: row!.id, login: author.login, text: body, createdAt: row!.createdAt };
|
||||
}
|
||||
|
||||
export async function storyComments(db: Db, taskId: number): Promise<StoryComment[]> {
|
||||
const rows = await db.select().from(events).where(and(eq(events.taskId, taskId), eq(events.type, COMMENT_EVENT))).orderBy(asc(events.id));
|
||||
return rows.map((e) => {
|
||||
const p = (e.payload ?? {}) as { login?: string; text?: string };
|
||||
return { id: e.id, login: p.login ?? "?", text: p.text ?? "", createdAt: e.createdAt };
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTaskDetails(db: Db, ref: TaskRef): Promise<TaskDetails> {
|
||||
@ -142,11 +174,11 @@ export async function getTaskDetails(db: Db, ref: TaskRef): Promise<TaskDetails>
|
||||
const evs = await db
|
||||
.select()
|
||||
.from(events)
|
||||
.where(eq(events.taskId, ref.task.id))
|
||||
.where(and(eq(events.taskId, ref.task.id), ne(events.type, "step")))
|
||||
.orderBy(desc(events.id))
|
||||
.limit(20);
|
||||
const incident = await incidentForTask(db, ref.task.id);
|
||||
return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref), review: await latestReview(db, ref.task.id), autonomy: await getAutonomy(db, ref.project.id) };
|
||||
return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref), review: await latestReview(db, ref.task.id), autonomy: await getAutonomy(db, ref.project.id), comments: await storyComments(db, ref.task.id) };
|
||||
}
|
||||
|
||||
export interface NewQuestion {
|
||||
|
||||
@ -36,6 +36,11 @@ export function formatTask(d: TaskDetails): string {
|
||||
lines.push("", `- [${q.kind} #${q.id}] ${q.text}`, q.answer ? ` - Ответ (${q.answeredVia}): ${q.answer}` : " - _ожидает ответа_");
|
||||
}
|
||||
}
|
||||
// PEP-32: the PM's comments on the story — instructions to take into account.
|
||||
if (d.comments?.length) {
|
||||
lines.push("", "## Комментарии PM");
|
||||
for (const c of d.comments.slice(-10)) lines.push("", `- ${c.createdAt.toISOString().slice(0, 16).replace("T", " ")} ${c.login}: ${c.text.replace(/\n/g, "\n ")}`);
|
||||
}
|
||||
const progress = d.recentEvents.filter((e) => e.type === "progress");
|
||||
if (progress.length) {
|
||||
lines.push("", "## Последний прогресс");
|
||||
|
||||
@ -253,7 +253,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
|
||||
},
|
||||
);
|
||||
|
||||
tool("get_task", "Get a story: description, epic, status, OpenSpec change, PM questions, progress, CI checks.", { task: taskArg }, true, async ({ task }) => {
|
||||
tool("get_task", "Get a story: description, epic, status, OpenSpec change, PM questions and comments, progress, CI checks.", { task: taskArg }, true, async ({ task }) => {
|
||||
const ref = await ownedTask(task);
|
||||
return `${formatTask(await getTaskDetails(db, ref))}\n\nWeb: ${webUrl}/t/${ref.key}`;
|
||||
});
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
// PM-side moves on the task board and review acceptance (web and Telegram use these).
|
||||
import { answerQuestion, getQuestion, listSessions, PeppaError, prGate, resolveTask, updateTask, type Question, type TaskRef } from "@peppa/core";
|
||||
import { answerQuestion, getQuestion, listSessions, PeppaError, pendingQuestions, prGate, resolveTask, updateTask, type Question, type TaskRef } from "@peppa/core";
|
||||
import { tasks, projects, type Db } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { eq } from "drizzle-orm";
|
||||
@ -84,6 +84,20 @@ export async function acceptTask(db: Db, questionId: number, via: NonNullable<Qu
|
||||
return ref;
|
||||
}
|
||||
|
||||
/**
|
||||
* «Принять и смержить» on the story page (PEP-32): the open ready-for-review message is
|
||||
* accepted like in the bot; without one the same steps run by hand (gate, merge, done, sync).
|
||||
*/
|
||||
export async function acceptStory(db: Db, ref: TaskRef, via: NonNullable<Question["answeredVia"]> = "web"): Promise<TaskRef> {
|
||||
if (ref.task.status !== "review") throw new PeppaError(`${ref.key} не в ревью (сейчас ${ref.task.status})`);
|
||||
const [open] = (await pendingQuestions(db, ref.project.id)).filter((q) => q.taskId === ref.task.id && q.kind === "attention").slice(-1);
|
||||
if (open) return acceptTask(db, open.id, via);
|
||||
await mergeTaskPr(ref);
|
||||
await moveTask(db, ref, "done");
|
||||
await syncWorkspace(db, ref).catch(() => {});
|
||||
return ref;
|
||||
}
|
||||
|
||||
/** True when an "attention" question is the ready-for-review message of its task. */
|
||||
export async function isReviewQuestion(db: Db, q: Question): Promise<boolean> {
|
||||
if (q.kind !== "attention" || !q.taskId || q.answeredAt) return false;
|
||||
|
||||
@ -7,7 +7,9 @@ import { appendFileSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
answerQuestion,
|
||||
describeStep,
|
||||
getAutonomy,
|
||||
recordStep,
|
||||
getQuestion,
|
||||
getReviewSettings,
|
||||
latestReview,
|
||||
@ -44,6 +46,7 @@ interface HookInput {
|
||||
last_assistant_message?: string;
|
||||
tool_name?: string;
|
||||
tool_input?: Record<string, unknown>;
|
||||
cwd?: string;
|
||||
permission_suggestions?: unknown[];
|
||||
}
|
||||
|
||||
@ -260,6 +263,13 @@ async function handle(event: string, input: HookInput): Promise<void> {
|
||||
await askQuestion(db, s, input);
|
||||
break;
|
||||
|
||||
case "tool-use": {
|
||||
// PEP-33: one step of the live feed (PostToolUse / PostToolUseFailure, async hook).
|
||||
const d = describeStep(input.tool_name ?? "", input.tool_input, input.cwd);
|
||||
if (d) await recordStep(db, s, { tool: input.tool_name!, ...d, ok: input.hook_event_name !== "PostToolUseFailure" }, now);
|
||||
break;
|
||||
}
|
||||
|
||||
case "notification":
|
||||
await logSessionEvent(db, s, "notification", { type: input.notification_type, message: input.message });
|
||||
break;
|
||||
|
||||
@ -24,3 +24,4 @@ export * from "./reviewer.ts";
|
||||
export * from "./autonomy.ts";
|
||||
export * from "./workspace-sync.ts";
|
||||
export * from "./rotation.ts";
|
||||
export * from "./live.ts";
|
||||
|
||||
298
packages/runner/src/live.ts
Normal file
298
packages/runner/src/live.ts
Normal file
@ -0,0 +1,298 @@
|
||||
// Live web (PEP-37): one change hub per web process. notify() pokes (the `web` subscriber
|
||||
// socket, the same events the bot hears) and PRAGMA data_version (writes from the hooks,
|
||||
// the watchdog, the CLI) wake it; it then computes a fingerprint of every scope somebody
|
||||
// watches and tells only the watchers whose scope changed. Steps of agents (PEP-33) go to
|
||||
// `steps:<sessionId>` watchers as data.
|
||||
import { existsSync, statSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { findChangeDir, listenEvents, projectForUser, STEP_EVENT, stepView, type StepView, type User } from "@peppa/core";
|
||||
import { events, sessions, tasks, type Db } from "@peppa/db";
|
||||
import { and, eq, gt } from "drizzle-orm";
|
||||
|
||||
export type LiveScope = "home" | "runners" | `project:${number}` | `task:${number}` | `steps:${number}`;
|
||||
export type LiveEvent = { type: "change"; scope: LiveScope } | { type: "step"; scope: LiveScope; step: StepView };
|
||||
type Listener = (e: LiveEvent) => void;
|
||||
|
||||
export const LIVE_PING_MS = 15_000;
|
||||
|
||||
/** Refusal of a live stream with its HTTP status. */
|
||||
export class LiveError extends Error {
|
||||
status: number;
|
||||
constructor(message: string, status: number) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
const WAKE_DEBOUNCE_MS = 250;
|
||||
|
||||
/** Parses `?scope=a,b`; unknown parts are refused. */
|
||||
export function parseScopes(raw: string | null): LiveScope[] {
|
||||
const out = new Set<LiveScope>();
|
||||
for (const part of (raw ?? "").split(",").map((s) => s.trim()).filter(Boolean)) {
|
||||
if (part === "home" || part === "runners") out.add(part);
|
||||
else if (/^(project|task|steps):[1-9]\d{0,9}$/.test(part)) out.add(part as LiveScope);
|
||||
else throw new LiveError(`Неизвестная область: ${part}`, 400);
|
||||
}
|
||||
if (!out.size || out.size > 8) throw new LiveError("Нужна область (scope)", 400);
|
||||
return [...out];
|
||||
}
|
||||
|
||||
/** Access: project/story/runner scopes need the project; home/runners only a user. */
|
||||
export async function checkScopeAccess(db: Db, user: User, scope: LiveScope): Promise<void> {
|
||||
const [kind, raw] = scope.split(":") as [string, string?];
|
||||
const id = Number(raw);
|
||||
let projectId: number | undefined;
|
||||
if (kind === "project") projectId = id;
|
||||
else if (kind === "task") projectId = (await db.select({ p: tasks.projectId }).from(tasks).where(eq(tasks.id, id)))[0]?.p;
|
||||
else if (kind === "steps") projectId = (await db.select({ p: sessions.projectId }).from(sessions).where(eq(sessions.id, id)))[0]?.p;
|
||||
else return;
|
||||
if (projectId == null) throw new LiveError("Не найдено", 404);
|
||||
await projectForUser(db, user.id, projectId).catch(() => {
|
||||
throw new LiveError("Не найдено", 404);
|
||||
});
|
||||
}
|
||||
|
||||
const ACTIVE_SESSIONS = `group_concat(CASE WHEN ended_at IS NULL THEN id || ':' || status END)`;
|
||||
|
||||
/** One SQL per scope; frequent fields (last_activity_at, steps, heartbeats) are left out. */
|
||||
function fingerprint(db: Db, scope: LiveScope): string {
|
||||
const c = db.$client;
|
||||
const [kind, raw] = scope.split(":") as [string, string?];
|
||||
const id = Number(raw);
|
||||
if (kind === "task") {
|
||||
const row = c
|
||||
.prepare(
|
||||
`SELECT
|
||||
(SELECT json_array(status, title, coalesce(description,''), coalesce(goal_id,0), coalesce(openspec_change,''), coalesce(pr_url,''), ci_attempts, updated_at) FROM tasks WHERE id = ?1) AS t,
|
||||
(SELECT coalesce(max(id),0) FROM events WHERE task_id = ?1 AND type <> 'step') AS e,
|
||||
(SELECT count(*) || ':' || count(answered_at) FROM questions WHERE task_id = ?1) AS q,
|
||||
(SELECT coalesce(group_concat(id || ':' || status || ':' || coalesce(ended_at,'')),'') FROM sessions WHERE task_id = ?1) AS s,
|
||||
(SELECT coalesce(max(updated_at),0) || ':' || count(*) FROM check_runs WHERE task_id = ?1) AS ci,
|
||||
(SELECT coalesce(max(updated_at),0) || ':' || count(*) FROM code_reviews WHERE task_id = ?1) AS r,
|
||||
(SELECT p.workspace_path FROM tasks t JOIN projects p ON p.id = t.project_id WHERE t.id = ?1) AS ws,
|
||||
(SELECT openspec_change FROM tasks WHERE id = ?1) AS ch`,
|
||||
)
|
||||
.get(id) as Record<string, string | number | null> | undefined;
|
||||
if (!row) return "";
|
||||
// tasks.md of the working copy changes without a database write (agent ticks items).
|
||||
let tasksMtime = 0;
|
||||
if (row.ws && row.ch) {
|
||||
const found = findChangeDir(String(row.ws), String(row.ch));
|
||||
const file = found && join(found.dir, "tasks.md");
|
||||
if (file && existsSync(file)) tasksMtime = statSync(file).mtimeMs;
|
||||
}
|
||||
return [row.t, row.e, row.q, row.s, row.ci, row.r, tasksMtime].join("|");
|
||||
}
|
||||
if (kind === "project") {
|
||||
const row = c
|
||||
.prepare(
|
||||
`SELECT
|
||||
(SELECT coalesce(max(updated_at),0) || ':' || count(*) FROM tasks WHERE project_id = ?1) AS t,
|
||||
(SELECT coalesce(max(id),0) FROM events WHERE project_id = ?1 AND type <> 'step') AS e,
|
||||
(SELECT count(*) || ':' || count(answered_at) FROM questions WHERE project_id = ?1) AS q,
|
||||
(SELECT count(*) || ':' || coalesce(${ACTIVE_SESSIONS},'') FROM sessions WHERE project_id = ?1) AS s,
|
||||
(SELECT coalesce(max(updated_at),0) FROM check_runs WHERE project_id = ?1) AS ci,
|
||||
(SELECT coalesce(max(id),0) || ':' || count(*) FROM releases WHERE project_id = ?1) AS rel,
|
||||
(SELECT coalesce(max(updated_at),0) FROM goals WHERE project_id = ?1) AS g,
|
||||
(SELECT updated_at FROM projects WHERE id = ?1) AS p`,
|
||||
)
|
||||
.get(id) as Record<string, unknown>;
|
||||
return Object.values(row).join("|");
|
||||
}
|
||||
// home / runners: across projects (only wakes the page — data stays behind access checks).
|
||||
const row = c
|
||||
.prepare(
|
||||
`SELECT
|
||||
(SELECT coalesce(max(updated_at),0) || ':' || count(*) FROM tasks) AS t,
|
||||
(SELECT count(*) || ':' || count(answered_at) FROM questions) AS q,
|
||||
(SELECT count(*) || ':' || coalesce(${ACTIVE_SESSIONS},'') FROM sessions) AS s,
|
||||
(SELECT count(*) FROM projects) AS p`,
|
||||
)
|
||||
.get() as Record<string, unknown>;
|
||||
return Object.values(row).join("|");
|
||||
}
|
||||
|
||||
class LiveHub {
|
||||
private listeners = new Map<LiveScope, Set<Listener>>();
|
||||
private prints = new Map<LiveScope, string>();
|
||||
private lastStep = new Map<LiveScope, number>();
|
||||
private timer: ReturnType<typeof setInterval> | null = null;
|
||||
private wakeTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private stopSocket: (() => Promise<void>) | null = null;
|
||||
private seen = "";
|
||||
private db: Db;
|
||||
constructor(db: Db) {
|
||||
this.db = db;
|
||||
}
|
||||
|
||||
subscribe(scopes: LiveScope[], fn: Listener): () => void {
|
||||
for (const s of scopes) {
|
||||
let set = this.listeners.get(s);
|
||||
if (!set) {
|
||||
this.listeners.set(s, (set = new Set()));
|
||||
this.prime(s);
|
||||
}
|
||||
set.add(fn);
|
||||
}
|
||||
this.start();
|
||||
return () => {
|
||||
for (const s of scopes) {
|
||||
const set = this.listeners.get(s);
|
||||
set?.delete(fn);
|
||||
if (set && !set.size) {
|
||||
this.listeners.delete(s);
|
||||
this.prints.delete(s);
|
||||
this.lastStep.delete(s);
|
||||
}
|
||||
}
|
||||
if (!this.listeners.size) this.stop();
|
||||
};
|
||||
}
|
||||
|
||||
/** Remembers the current state, so only later changes are reported. */
|
||||
private prime(s: LiveScope) {
|
||||
try {
|
||||
if (s.startsWith("steps:")) {
|
||||
const row = this.db.$client.prepare(`SELECT coalesce(max(id),0) AS id FROM events WHERE session_id = ? AND type = 'step'`).get(Number(s.slice(6))) as { id: number };
|
||||
this.lastStep.set(s, row.id);
|
||||
} else this.prints.set(s, fingerprint(this.db, s));
|
||||
} catch (e) {
|
||||
console.error("live: prime failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
private start() {
|
||||
if (this.timer) return;
|
||||
this.seen = this.version();
|
||||
// Writes of other processes (hooks, watchdog, bot, CLI) and of this one.
|
||||
this.timer = setInterval(() => {
|
||||
const v = this.version();
|
||||
if (v !== this.seen) {
|
||||
this.seen = v;
|
||||
this.wake();
|
||||
}
|
||||
}, 1000);
|
||||
this.timer.unref?.();
|
||||
listenEvents("web", () => this.wake())
|
||||
.then((stop) => {
|
||||
if (this.timer) this.stopSocket = stop;
|
||||
else void stop();
|
||||
})
|
||||
.catch((e) => console.error("live: web.events.sock unavailable, data_version only:", (e as Error).message));
|
||||
}
|
||||
|
||||
private stop() {
|
||||
if (this.timer) clearInterval(this.timer);
|
||||
this.timer = null;
|
||||
if (this.wakeTimer) clearTimeout(this.wakeTimer);
|
||||
this.wakeTimer = null;
|
||||
void this.stopSocket?.();
|
||||
this.stopSocket = null;
|
||||
}
|
||||
|
||||
private version(): string {
|
||||
try {
|
||||
const c = this.db.$client;
|
||||
const own = c.prepare("SELECT total_changes() AS n").get() as { n: number };
|
||||
return `${c.dataVersion()}:${own.n}`;
|
||||
} catch {
|
||||
return this.seen;
|
||||
}
|
||||
}
|
||||
|
||||
/** Debounced: a burst of writes is one check. */
|
||||
wake() {
|
||||
if (this.wakeTimer || !this.timer) return;
|
||||
this.wakeTimer = setTimeout(() => {
|
||||
this.wakeTimer = null;
|
||||
this.check();
|
||||
}, WAKE_DEBOUNCE_MS);
|
||||
}
|
||||
|
||||
/** Recomputes every watched scope now (tests call it directly). */
|
||||
check() {
|
||||
for (const [scope, set] of this.listeners) {
|
||||
try {
|
||||
if (scope.startsWith("steps:")) {
|
||||
const after = this.lastStep.get(scope) ?? 0;
|
||||
const rows = this.db
|
||||
.select()
|
||||
.from(events)
|
||||
.where(and(eq(events.sessionId, Number(scope.slice(6))), eq(events.type, STEP_EVENT), gt(events.id, after)))
|
||||
.orderBy(events.id)
|
||||
.limit(50)
|
||||
.all();
|
||||
if (!rows.length) continue;
|
||||
this.lastStep.set(scope, rows.at(-1)!.id);
|
||||
for (const r of rows) for (const fn of set) fn({ type: "step", scope, step: stepView(r) });
|
||||
continue;
|
||||
}
|
||||
const fp = fingerprint(this.db, scope);
|
||||
if (fp === this.prints.get(scope)) continue;
|
||||
this.prints.set(scope, fp);
|
||||
for (const fn of set) fn({ type: "change", scope });
|
||||
} catch (e) {
|
||||
console.error(`live: ${scope} check failed`, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
get watched(): LiveScope[] {
|
||||
return [...this.listeners.keys()];
|
||||
}
|
||||
}
|
||||
|
||||
const g = globalThis as { __peppaLiveHub?: LiveHub };
|
||||
/** The process-wide hub (survives Next dev module reloads). */
|
||||
export function liveHub(db: Db): LiveHub {
|
||||
return (g.__peppaLiveHub ??= new LiveHub(db));
|
||||
}
|
||||
|
||||
/** SSE response for /api/live: `change` / `step` events, pings for Cloudflare. */
|
||||
export async function liveSse(db: Db, user: User, scopes: LiveScope[], signal: AbortSignal, opts: { pingMs?: number } = {}): Promise<Response> {
|
||||
for (const s of scopes) await checkScopeAccess(db, user, s);
|
||||
const enc = new TextEncoder();
|
||||
let cleanup = () => {};
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
let closed = false;
|
||||
let unsubscribe = () => {};
|
||||
const send = (chunk: string) => {
|
||||
if (closed) return;
|
||||
try {
|
||||
controller.enqueue(enc.encode(chunk));
|
||||
} catch {
|
||||
close();
|
||||
}
|
||||
};
|
||||
const ping = setInterval(() => send(": ping\n\n"), opts.pingMs ?? LIVE_PING_MS);
|
||||
const close = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
clearInterval(ping);
|
||||
unsubscribe();
|
||||
signal.removeEventListener("abort", close);
|
||||
try {
|
||||
controller.close();
|
||||
} catch {}
|
||||
};
|
||||
cleanup = close;
|
||||
signal.addEventListener("abort", close);
|
||||
send("retry: 3000\n\n");
|
||||
send(`event: ready\ndata: ${JSON.stringify({ scopes })}\n\n`);
|
||||
if (signal.aborted) return close();
|
||||
unsubscribe = liveHub(db).subscribe(scopes, (e) => send(`event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`));
|
||||
},
|
||||
cancel() {
|
||||
cleanup();
|
||||
},
|
||||
});
|
||||
return new Response(body, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream; charset=utf-8",
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
"X-Accel-Buffering": "no",
|
||||
Connection: "keep-alive",
|
||||
},
|
||||
});
|
||||
}
|
||||
@ -32,12 +32,16 @@ export function writeRunRules(sessionId: number, generation: number, text: strin
|
||||
|
||||
export function writeRunSettings(sessionId: number, generation: number): string {
|
||||
const hook = (event: string, timeout = 30) => ({ type: "command", command: `${hookBin()} ${event}`, timeout });
|
||||
// PEP-33: steps of the agent; async — Claude doesn't wait for the hook process.
|
||||
const step = { ...hook("tool-use", 15), async: true };
|
||||
const settings = {
|
||||
hooks: {
|
||||
SessionStart: [{ hooks: [hook("session-start")] }],
|
||||
UserPromptSubmit: [{ hooks: [hook("prompt")] }],
|
||||
PermissionRequest: [{ hooks: [hook("permission-request", HOOK_WAIT_SEC + 30)] }],
|
||||
PreToolUse: [{ matcher: "AskUserQuestion", hooks: [hook("ask-question", HOOK_WAIT_SEC + 30)] }],
|
||||
PostToolUse: [{ hooks: [step] }],
|
||||
PostToolUseFailure: [{ hooks: [step] }],
|
||||
Notification: [{ hooks: [hook("notification")] }],
|
||||
Stop: [{ hooks: [hook("stop")] }],
|
||||
StopFailure: [{ hooks: [hook("stop-failure")] }],
|
||||
|
||||
251
packages/testkit/test/story-live.test.ts
Normal file
251
packages/testkit/test/story-live.test.ts
Normal file
@ -0,0 +1,251 @@
|
||||
// PEP-32/33/37: story page data (OpenSpec change incl. archived, delta specs, tasks.md
|
||||
// progress, PM comments, accept-and-merge), agent steps from the PostToolUse hook, and the
|
||||
// live change hub with its SSE stream.
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { after, describe, test } from "node:test";
|
||||
import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
after(teardown);
|
||||
|
||||
const HOOK = process.env.PEPPA_MOCK_MCP_BIN!.replace("mcp/bin/peppa-mcp", "runner/bin/peppa-hook");
|
||||
let seq = 0;
|
||||
const user = (login: string) => core.upsertUserFromGitea(db, { id: 7000 + seq++, login }, { access_token: "x" });
|
||||
|
||||
const DELTA = `## ADDED Requirements
|
||||
|
||||
### Requirement: Оплата картой
|
||||
Покупатель SHALL оплачивать заказ картой.
|
||||
|
||||
#### Scenario: Успешная оплата
|
||||
- **WHEN** покупатель вводит карту
|
||||
- **THEN** заказ оплачен
|
||||
|
||||
#### Scenario: Отказ банка
|
||||
- **THEN** заказ не оплачен
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Корзина
|
||||
Корзина SHALL хранить товары 7 дней.
|
||||
`;
|
||||
const TASKS = `## 1. Бэкенд
|
||||
|
||||
- [x] 1.1 Модель платежа
|
||||
- [x] 1.2 API
|
||||
|
||||
## 2. Веб
|
||||
|
||||
- [ ] 2.1 Кнопка оплаты
|
||||
- [ ] 2.2 Экран успеха
|
||||
`;
|
||||
|
||||
function writeChange(dir: string, change: string, archived: boolean) {
|
||||
const base = archived ? join(dir, "openspec/changes/archive", `2026-11-01-${change}`) : join(dir, "openspec/changes", change);
|
||||
mkdirSync(join(base, "specs/checkout"), { recursive: true });
|
||||
writeFileSync(join(base, "proposal.md"), "## Why\n\nНужна **оплата**.\n");
|
||||
writeFileSync(join(base, "tasks.md"), TASKS);
|
||||
writeFileSync(join(base, "specs/checkout/spec.md"), DELTA);
|
||||
return base;
|
||||
}
|
||||
|
||||
async function story() {
|
||||
const p = await project({ turns: [] });
|
||||
const ref = await core.resolveTask(db, p.taskKey);
|
||||
return { p, ref, proj: ref.project };
|
||||
}
|
||||
|
||||
describe("OpenSpec change of a story (PEP-32)", () => {
|
||||
test("archived change: artifacts, delta specs with scenarios, tasks.md progress", async () => {
|
||||
const { p, ref } = await story();
|
||||
writeChange(p.dir, "pay-1-checkout", true);
|
||||
await core.updateTask(db, ref, { openspecChange: "pay-1-checkout" });
|
||||
const c = core.readChange(ref.project, "pay-1-checkout")!;
|
||||
assert.ok(c.archived);
|
||||
assert.match(c.proposal!, /оплата/);
|
||||
assert.equal(c.design, null);
|
||||
assert.equal(c.specs.length, 1);
|
||||
const spec = c.specs[0]!;
|
||||
assert.equal(spec.capability, "checkout");
|
||||
assert.deepEqual(spec.sections.map((s) => s.op), ["ADDED", "MODIFIED"]);
|
||||
const req = spec.sections[0]!.requirements[0]!;
|
||||
assert.equal(req.name, "Оплата картой");
|
||||
assert.deepEqual(req.scenarios.map((s) => s.name), ["Успешная оплата", "Отказ банка"]);
|
||||
assert.match(req.scenarios[0]!.body, /заказ оплачен/);
|
||||
|
||||
const pr = core.taskProgress(ref.project, "pay-1-checkout")!;
|
||||
assert.equal(pr.done, 2);
|
||||
assert.equal(pr.total, 4);
|
||||
assert.equal(pr.current, "2.1 Кнопка оплаты");
|
||||
assert.deepEqual(pr.sections.map((s) => s.title), ["1. Бэкенд", "2. Веб"]);
|
||||
});
|
||||
|
||||
test("active change wins over an archived one; unknown or unsafe ids give nothing", async () => {
|
||||
const { p, ref } = await story();
|
||||
writeChange(p.dir, "pay-2", true);
|
||||
writeChange(p.dir, "pay-2", false);
|
||||
assert.equal(core.readChange(ref.project, "pay-2")!.archived, false);
|
||||
assert.equal(core.readChange(ref.project, "nope"), null);
|
||||
assert.equal(core.readChange(ref.project, "../etc"), null);
|
||||
assert.equal(core.taskProgress(ref.project, null), null);
|
||||
});
|
||||
|
||||
test("PM comment: stored with the login, shown to the agent in get_task", async () => {
|
||||
const { ref } = await story();
|
||||
const pm = await user("pm-comment");
|
||||
await assert.rejects(core.addStoryComment(db, ref, pm, " "), /Пустой/);
|
||||
await core.addStoryComment(db, ref, pm, "Кнопку сделать зелёной");
|
||||
const d = await core.getTaskDetails(db, ref);
|
||||
assert.equal(d.comments.length, 1);
|
||||
assert.equal(d.comments[0]!.login, "pm-comment");
|
||||
const { formatTask } = await import("../../mcp/src/format.ts");
|
||||
assert.match(formatTask(d), /## Комментарии PM\n\n- .* pm-comment: Кнопку сделать зелёной/);
|
||||
});
|
||||
|
||||
test("edit from the web is logged with the PM's login", async () => {
|
||||
const { ref } = await story();
|
||||
await core.updateTask(db, ref, { title: "Новое имя" }, undefined, "pm-edit");
|
||||
const [e] = (await core.getTaskDetails(db, await core.resolveTask(db, ref.key))).recentEvents.filter((x) => x.type === "task_updated").slice(-1);
|
||||
assert.equal((e!.payload as { login: string }).login, "pm-edit");
|
||||
});
|
||||
|
||||
test("accept and merge: answers the ready-for-review message, story done", async () => {
|
||||
const { ref } = await story();
|
||||
await core.updateTask(db, ref, { status: "review" });
|
||||
await assert.rejects(runner.acceptStory(db, await core.resolveTask(db, ref.key).then((r) => ({ ...r, task: { ...r.task, status: "in_progress" as const } }))), /не в ревью/);
|
||||
const q = await core.askPm(db, ref, { kind: "attention", text: "✅ готово к ревью" });
|
||||
await runner.acceptStory(db, await core.resolveTask(db, ref.key));
|
||||
assert.equal((await core.resolveTask(db, ref.key)).task.status, "done");
|
||||
assert.ok((await core.getQuestion(db, q.id)).answeredAt);
|
||||
});
|
||||
|
||||
test("accept and merge without a review message (no PR): done", async () => {
|
||||
const { ref } = await story();
|
||||
await core.updateTask(db, ref, { status: "review" });
|
||||
await runner.acceptStory(db, await core.resolveTask(db, ref.key));
|
||||
assert.equal((await core.resolveTask(db, ref.key)).task.status, "done");
|
||||
});
|
||||
});
|
||||
|
||||
describe("agent steps (PEP-33)", () => {
|
||||
test("describeStep classifies tool calls", () => {
|
||||
assert.deepEqual(core.describeStep("Bash", { command: "pnpm test --filter web\nmore" }), { kind: "test", text: "pnpm test --filter web" });
|
||||
assert.deepEqual(core.describeStep("Bash", { command: "git status" }), { kind: "command", text: "git status" });
|
||||
assert.deepEqual(core.describeStep("Edit", { file_path: "/w/src/a.ts" }, "/w"), { kind: "edit", text: "src/a.ts" });
|
||||
assert.deepEqual(core.describeStep("Grep", { pattern: "TODO" }), { kind: "search", text: "TODO" });
|
||||
assert.deepEqual(core.describeStep("mcp__peppa__update_task", {}), { kind: "mcp", text: "peppa · update_task" });
|
||||
assert.equal(core.describeStep("AskUserQuestion", {}), null);
|
||||
assert.equal(core.describeStep("mcp__peppa__get_task", {}), null);
|
||||
});
|
||||
|
||||
test("run settings register the async PostToolUse hooks", () => {
|
||||
const path = runner.writeRunSettings(9999, 0);
|
||||
const s = JSON.parse(execFileSync("cat", [path], { encoding: "utf8" }));
|
||||
for (const ev of ["PostToolUse", "PostToolUseFailure"]) {
|
||||
const h = s.hooks[ev][0].hooks[0];
|
||||
assert.match(h.command, /peppa-hook tool-use$/);
|
||||
assert.equal(h.async, true);
|
||||
}
|
||||
});
|
||||
|
||||
test("hook writes steps; failure is marked; a stale generation is ignored; steps stay out of the journal", async () => {
|
||||
const { p, ref, proj } = await story();
|
||||
const s = await core.createSession(db, { projectId: proj.id, taskId: ref.task.id });
|
||||
const hook = (input: object, gen = 0) =>
|
||||
execFileSync("bash", ["-c", `${HOOK} tool-use`], { input: JSON.stringify(input), env: { ...process.env, PEPPA_SESSION_ID: String(s.id), PEPPA_GENERATION: String(gen) } });
|
||||
hook({ hook_event_name: "PostToolUse", tool_name: "Bash", tool_input: { command: "pnpm run ci" }, cwd: p.dir });
|
||||
hook({ hook_event_name: "PostToolUseFailure", tool_name: "Write", tool_input: { file_path: join(p.dir, "src/x.ts") }, cwd: p.dir });
|
||||
hook({ hook_event_name: "PostToolUse", tool_name: "Read", tool_input: { file_path: "/x" } }, 5);
|
||||
const steps = await core.sessionSteps(db, s.id);
|
||||
assert.deepEqual(
|
||||
steps.map((x) => [x.kind, x.text, x.ok]),
|
||||
[
|
||||
["edit", "src/x.ts", false],
|
||||
["test", "pnpm run ci", true],
|
||||
],
|
||||
);
|
||||
assert.ok((await core.getSession(db, s.id)).lastActivityAt, "activity time updated");
|
||||
const d = await core.getTaskDetails(db, ref);
|
||||
assert.ok(!d.recentEvents.some((e) => e.type === "step"), "get_task has no steps");
|
||||
});
|
||||
|
||||
test("only the last MAX_STEPS steps of a session are kept", async () => {
|
||||
const { ref, proj } = await story();
|
||||
const s = await core.createSession(db, { projectId: proj.id, taskId: ref.task.id });
|
||||
for (let i = 0; i < core.MAX_STEPS + 15; i++) await core.recordStep(db, s, { tool: "Bash", kind: "command", text: `cmd ${i}`, ok: true });
|
||||
const all = await core.sessionSteps(db, s.id, 1000);
|
||||
assert.equal(all.length, core.MAX_STEPS);
|
||||
assert.equal(all[0]!.text, `cmd ${core.MAX_STEPS + 14}`);
|
||||
assert.equal(all.at(-1)!.text, "cmd 15");
|
||||
});
|
||||
});
|
||||
|
||||
describe("live hub and SSE (PEP-37)", () => {
|
||||
test("parseScopes", () => {
|
||||
assert.deepEqual(runner.parseScopes("home, task:3,steps:9"), ["home", "task:3", "steps:9"]);
|
||||
assert.throws(() => runner.parseScopes("task:abc"), runner.LiveError);
|
||||
assert.throws(() => runner.parseScopes(""), runner.LiveError);
|
||||
});
|
||||
|
||||
test("a scope changes on its own writes only; steps arrive as data", async () => {
|
||||
const a = await story();
|
||||
const b = await story();
|
||||
const hub = runner.liveHub(db);
|
||||
const got: import("@peppa/runner").LiveEvent[] = [];
|
||||
const s = await core.createSession(db, { projectId: a.proj.id, taskId: a.ref.task.id });
|
||||
const stop = hub.subscribe([`task:${a.ref.task.id}`, `steps:${s.id}`], (e) => got.push(e));
|
||||
try {
|
||||
// Noise: a heartbeat, another story, a step (not a change of the story).
|
||||
await core.setSetting(db, "heartbeat:test", { at: Date.now() });
|
||||
await core.updateTask(db, b.ref, { status: "in_progress" });
|
||||
await core.recordStep(db, s, { tool: "Bash", kind: "command", text: "ls", ok: true });
|
||||
hub.check();
|
||||
assert.deepEqual(got.map((e) => e.type), ["step"]);
|
||||
assert.equal(got[0]!.type === "step" && got[0]!.step.text, "ls");
|
||||
// A question on the story: change (via the check the notify() poke schedules).
|
||||
await core.askPm(db, a.ref, { kind: "question", text: "Какой цвет?" });
|
||||
await waitFor("change event", async () => got.some((e) => e.type === "change"), 5000);
|
||||
const n = got.length;
|
||||
hub.check();
|
||||
assert.equal(got.length, n, "no repeat without a new write");
|
||||
} finally {
|
||||
stop();
|
||||
}
|
||||
assert.deepEqual(hub.watched, []);
|
||||
});
|
||||
|
||||
test("SSE: headers for Cloudflare, ready + change events, 404 for an outsider", async () => {
|
||||
const owner = await user("live-owner");
|
||||
const outsider = await user("live-outsider");
|
||||
const { ref, proj } = await story();
|
||||
await core.setProjectOwner(db, proj.id, owner.id);
|
||||
await assert.rejects(runner.liveSse(db, outsider, [`task:${ref.task.id}`], new AbortController().signal), (e: unknown) => e instanceof runner.LiveError && e.status === 404);
|
||||
await assert.rejects(runner.liveSse(db, owner, ["task:999999"], new AbortController().signal), (e: unknown) => e instanceof runner.LiveError && e.status === 404);
|
||||
|
||||
const ac = new AbortController();
|
||||
const res = await runner.liveSse(db, owner, [`task:${ref.task.id}`], ac.signal);
|
||||
assert.equal(res.headers.get("content-type"), "text/event-stream; charset=utf-8");
|
||||
assert.match(res.headers.get("cache-control")!, /no-transform/);
|
||||
assert.equal(res.headers.get("x-accel-buffering"), "no");
|
||||
const reader = res.body!.getReader();
|
||||
const dec = new TextDecoder();
|
||||
let buf = "";
|
||||
const until = async (re: RegExp) => {
|
||||
const deadline = Date.now() + 5000;
|
||||
while (!re.test(buf)) {
|
||||
if (Date.now() > deadline) throw new Error(`no ${re} in ${buf}`);
|
||||
const { value, done } = await reader.read();
|
||||
if (done) break;
|
||||
buf += dec.decode(value);
|
||||
}
|
||||
};
|
||||
await until(/event: ready/);
|
||||
await core.updateTask(db, ref, { title: "Переименовано" }, undefined, "live-owner");
|
||||
await until(/event: change\ndata: \{"type":"change","scope":"task:\d+"\}/);
|
||||
ac.abort();
|
||||
await reader.cancel().catch(() => {});
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user