peppa/apps/web/app/(app)/t/[key]/page.tsx
Асель 6ab17456af PEP-44, PEP-46: review preview with screenshots; Gitea issues, PR comments, manual merge
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 06:06:57 +05:00

309 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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, Pencil, Play } from "lucide-react";
import {
FINISHED_SESSION_STATUSES,
getEpic,
isSuperadmin,
latestReview,
listEpics,
listPools,
listSubscriptions,
parseTasks,
prGate,
projectPool,
PROVIDER_NAMES,
readChange,
reviewLabel,
reviewPreview,
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, 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, Textarea } from "@/components/ui/input";
import { Workspace } from "@/components/Workspace";
import { ReviewPreview } from "@/components/ReviewPreview";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
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" /> };
/** 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 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 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 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);
const preview = await reviewPreview(db, ref);
// 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">
<ReviewPreview preview={preview} />
<PanelSection title="Проверки">
<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.label}
{ci.sha && <span className="font-mono text-xs text-muted-foreground">{ci.sha.slice(0, 7)}</span>}
</Link>
{task.ciAttempts > 0 && <p className="m-0 text-xs text-muted-foreground">красных подряд: {task.ciAttempts}</p>}
</PanelSection>
{review && (
<PanelSection title="Ревьюер">
<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="Последнее">
{events.length === 0 ? (
<p className="m-0 text-sm text-muted-foreground">Событий нет.</p>
) : (
<>
<ActivityTab events={events.slice(0, 8)} />
<Link href={tabHref("activity")} className="text-xs text-primary">
Вся активность →
</Link>
</>
)}
</PanelSection>
</div>
);
return (
<Workspace aside={aside}>
<LiveRefresh scope={`task:${task.id}`} />
<Flash error={sp.error} />
<PageHeader
crumbs={
<>
<Link href={`/p/${project.key}`} className="text-muted-foreground hover:text-foreground">{project.name}</Link>
{epic && (
<>
<span className="text-muted-foreground">/</span>
<Link href={`/p/${project.key}?epic=${epic.id}`} title="Эпик" className="text-muted-foreground hover:text-foreground">
эпик «{epic.title}»
</Link>
</>
)}
</>
}
title={
<>
<span className="font-mono text-primary">{ref.key}</span> {task.title} <StatusBadge status={task.status} />
</>
}
actions={
<>
<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>
)}
</>
}
>
<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>
{sp.edit ? (
<form action={editStoryAction} className="flex flex-col gap-2 rounded-lg border bg-card p-4">
<Hidden fields={{ taskKey: ref.key, back }} />
<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>
))}
{epic && !epics.some((e) => e.id === epic.id) && <option value={epic.id}>{epic.title} (в архиве)</option>}
</NativeSelect>
</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>
) : (
<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="Агент" 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} />
) : (
<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>
);
}