409 lines
22 KiB
TypeScript
409 lines
22 KiB
TypeScript
// 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 { Markdown } from "@/components/Markdown";
|
||
import Link from "next/link";
|
||
import { notFound } from "next/navigation";
|
||
import { Archive, ArchiveRestore, CircleCheck, CircleX, GitPullRequest, Hourglass, Lock, Pencil, Play, X } from "lucide-react";
|
||
import {
|
||
blockersOf,
|
||
dependentsOf,
|
||
actorLabel,
|
||
FINISHED_SESSION_STATUSES,
|
||
getTaskRunnerSettings,
|
||
getTaskAgentSettings,
|
||
getEscalation,
|
||
resolveAgentSettings,
|
||
resolveRunnerSettings,
|
||
getProjectBudget,
|
||
listJournal,
|
||
taskBudgetView,
|
||
getEpic,
|
||
isSuperadmin,
|
||
latestReview,
|
||
listEpics,
|
||
listPools,
|
||
listSubscriptions,
|
||
parseTasks,
|
||
prGate,
|
||
projectPool,
|
||
PROVIDER_NAMES,
|
||
readChange,
|
||
reviewLabel,
|
||
reviewPreview,
|
||
sessionSteps,
|
||
refinePending,
|
||
storyComments,
|
||
getIntakeSettings,
|
||
getIntakeState,
|
||
intakePending,
|
||
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 { TaskRunnerSettings } from "@/components/Runners";
|
||
import { TaskAgentModel } from "@/components/AgentModel";
|
||
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, saveTaskBudgetAction, startTaskSession } from "../../actions";
|
||
import { BudgetPanel } from "@/components/Accounting";
|
||
import { ActivityTab, ArtifactTab, CommentsTab, MergeTab, ProgressBar, SpecsTab, STORY_TABS, TasksTab, TestsTab, type CheckRunRow, type StoryTab } from "./tabs";
|
||
import { archiveTaskAction, setDependenciesAction } from "../../board-actions";
|
||
import { Badge } from "@/components/ui/badge";
|
||
|
||
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, sessions.map((s) => s.workspacePath));
|
||
const progress = change?.tasks ? parseTasks(change.tasks) : null;
|
||
// PEP-10: runner mode/context of this story over the project's.
|
||
const [runnerOwn, runnerProject] = await Promise.all([getTaskRunnerSettings(db, task.id), resolveRunnerSettings(db, project.id)]);
|
||
// PEP-41: the story's agent model over the project's, and its escalation.
|
||
const [agentOwn, agentProject, escalation] = await Promise.all([getTaskAgentSettings(db, task.id), resolveAgentSettings(db, project.id), getEscalation(db, task.id)]);
|
||
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);
|
||
const [blockers, dependents] = await Promise.all([blockersOf(db, ref), dependentsOf(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 commentRefining = tab === "comments" && (await refinePending(db, task));
|
||
// PEP-84: is the story still with «продакт» and «аналитик»?
|
||
const intake = task.status === "backlog" ? await getIntakeState(db, task.id) : null;
|
||
const refining = task.status === "backlog" && intakePending(await getIntakeSettings(db, ref.project.id), task, intake) ? (intake?.stage ?? "product") : null;
|
||
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,
|
||
};
|
||
// PEP-43: spend against the budget; PEP-48: who did each event.
|
||
const budget = await taskBudgetView(db, task);
|
||
const projectBudget = await getProjectBudget(db, project.id);
|
||
const authors = new Map((await listJournal(db, { taskId: task.id, limit: 200 })).map((e) => [e.id, actorLabel(e)]));
|
||
|
||
const aside = (
|
||
<div className="flex flex-col gap-6">
|
||
<ReviewPreview preview={preview} />
|
||
<PanelSection title="Расход и бюджет">
|
||
<BudgetPanel view={budget} taskId={task.id} projectBudget={projectBudget} back={back} action={saveTaskBudgetAction} paused={!!budget.paused} />
|
||
</PanelSection>
|
||
<PanelSection title="Зависимости">
|
||
{blockers.length === 0 && dependents.length === 0 && <p className="m-0 text-sm text-muted-foreground">Стори ни от чего не зависит.</p>}
|
||
{blockers.length > 0 && (
|
||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||
{blockers.map((b) => (
|
||
<li key={b.id} className="flex items-center gap-2">
|
||
{b.open ? <Lock className="size-3.5 text-warn" /> : <CircleCheck className="size-3.5 text-ok" />}
|
||
<Link href={`/t/${b.key}`} className="min-w-0 flex-1 truncate">
|
||
<span className="font-mono text-xs text-primary">{b.key}</span> {b.title}
|
||
</Link>
|
||
<StatusBadge status={b.status} />
|
||
<form action={setDependenciesAction}>
|
||
<Hidden fields={{ taskKey: ref.key, back, remove: b.key }} />
|
||
{blockers.map((x) => <input key={x.id} type="hidden" name="current" value={x.key} />)}
|
||
<button type="submit" title={`Убрать зависимость от ${b.key}`} aria-label={`Убрать зависимость от ${b.key}`} className="rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground">
|
||
<X className="size-3.5" />
|
||
</button>
|
||
</form>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
)}
|
||
{blockers.some((b) => b.open) && <p className="m-0 text-xs text-muted-foreground">Диспетчер не возьмёт стори, пока предшественники не в ревью или готово.</p>}
|
||
<form action={setDependenciesAction} className="flex gap-2">
|
||
<Hidden fields={{ taskKey: ref.key, back }} />
|
||
{blockers.map((x) => <input key={x.id} type="hidden" name="current" value={x.key} />)}
|
||
<Input name="blockedBy" required placeholder={`Ждёт стори: ${project.key}-3`} aria-label="Добавить зависимость" className="h-8" />
|
||
<Button size="sm" variant="outline">Добавить</Button>
|
||
</form>
|
||
{dependents.length > 0 && (
|
||
<p className="m-0 text-sm">
|
||
<span className="text-muted-foreground">Её ждут: </span>
|
||
{dependents.map((d, i) => (
|
||
<span key={d.id}>
|
||
{i > 0 && ", "}
|
||
<Link href={`/t/${d.key}`} className="font-mono text-xs">{d.key}</Link>
|
||
</span>
|
||
))}
|
||
</p>
|
||
)}
|
||
</PanelSection>
|
||
<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)} authors={authors} />
|
||
<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} />
|
||
{task.archivedAt && <Badge variant="muted" className="ml-1.5 align-middle">в архиве</Badge>}
|
||
</>
|
||
}
|
||
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>
|
||
)}
|
||
<form action={archiveTaskAction}>
|
||
<Hidden fields={{ taskKey: ref.key, back, archived: task.archivedAt ? "0" : "1" }} />
|
||
<Button size="sm" variant="ghost" title={task.archivedAt ? "Вернуть стори на доску (в конец)" : "Убрать с доски; агент остановится, история останется"}>
|
||
{task.archivedAt ? <><ArchiveRestore />Вернуть</> : <><Archive />В архив</>}
|
||
</Button>
|
||
</form>
|
||
</>
|
||
}
|
||
>
|
||
<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>
|
||
|
||
{refining && (
|
||
<p role="status" className="mb-4 flex flex-wrap items-center gap-2 rounded-lg border border-info/40 bg-info/10 px-4 py-3 text-sm">
|
||
<span className="font-medium">{refining === "waiting" ? "Аналитик ждёт ваших ответов" : "Продакт и аналитик уточняют задачу"}</span>
|
||
<span className="text-muted-foreground">
|
||
{refining === "waiting" ? "— вопрос во вкладке «Comments». Не ответите — возьмёт варианты по умолчанию и отдаст стори в работу." : "— через минуту здесь появятся критерии приёмки. Агент-разработчик возьмёт стори после этого."}
|
||
</span>
|
||
</p>
|
||
)}
|
||
{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>}>
|
||
{/* PEP-84: the analyst writes the story in Markdown (criteria, out of scope, assumptions). */}
|
||
{task.description && /^## /m.test(task.description) ? (
|
||
<Markdown text={task.description} className="text-sm" />
|
||
) : (
|
||
<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>
|
||
)}
|
||
<TaskRunnerSettings taskKey={ref.key} own={runnerOwn} inherited={runnerProject} back={back} />
|
||
<TaskAgentModel taskKey={ref.key} own={agentOwn} inherited={agentProject} escalation={escalation} back={back} />
|
||
{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} refining={commentRefining} />}
|
||
{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} authors={authors} />}
|
||
</div>
|
||
</Workspace>
|
||
);
|
||
}
|