// 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 { queuePositions } from "@peppa/core"; import { Markdown } from "@/components/Markdown"; import Link from "next/link"; import { notFound } from "next/navigation"; import { Archive, ArchiveRestore, ChevronDown, ChevronRight, 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, getPendingAccept, PENDING_ACCEPT_LABEL, PLATFORM_DELAY_LABEL, taskDelayed, taskDelayLine, projectPool, PROVIDER_NAMES, readChange, reviewLabel, reviewPreview, storyProductView, sessionSteps, refinePending, storyComments, getIntakeSettings, getIntakeState, intakePending, taskCiSummary, type GateResult, productUrls, questionType, } from "@peppa/core"; import { checkRuns } from "@peppa/db"; import { desc, eq } from "drizzle-orm"; import { getDecisions, getTeamMatch, matchLine } from "@peppa/core"; 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, uiMode } from "@/lib/auth"; import { StoryProduct } from "@/components/StoryProduct"; import { TaskDecisions } from "@/components/TaskDecisions"; import { db } from "@/lib/db"; import { taskActivity, taskForUser } from "@/lib/queries"; import { cn } from "@/lib/utils"; import { getT } from "@/lib/i18n"; 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: , failure: , pending: }; /** Gitea behind Cloudflare can hang: the merge tab waits at most this long. */ async function gateWithTimeout(ref: Parameters[0]): Promise { return Promise.race([prGate(ref).catch(() => null), new Promise((r) => setTimeout(() => r(null), 5000))]); } export default async function StoryPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; tab?: string; edit?: string; more?: string }> }) { const user = await requireUser(); const t = await getT(); 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((x) => x.id === sp.tab)?.id ?? (change ? "proposal" : "comments"); const tabHref = (id: StoryTab) => `/t/${ref.key}?tab=${id}`; // PEP-120: «Продакт» sees one plain card; the rest of the page opens by «Подробнее» (?more=1, a tab or the edit form). const engineer = (await uiMode()) === "engineer"; // PEP-183: was the story given to a specialist of the team (engineer only). const teamMatchText = engineer ? matchLine(await getTeamMatch(db, task.id)) : null; const detailsOpen = engineer || !!(sp.more || sp.tab || sp.edit); const back = engineer || sp.tab ? tabHref(tab) : detailsOpen ? `/t/${ref.key}?more=1` : `/t/${ref.key}`; 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 / PEP-198: is the story still with the analyst? 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 ?? "analyst") : 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 pendingAccept = await getPendingAccept(db, task.id); // PEP-150: a delay on the platform's side — one line instead of a message to the owner. // Not while a question waits for the owner: «от вас ничего не нужно» would not be true. const delayed = !task.archivedAt && task.status !== "done" && !questions.some((q) => !q.answeredAt) && (await taskDelayed(db, task.id)); // PEP-209: when the next attempt comes, or that the administrator is told — never the terminal's text. const delayLine = delayed ? await taskDelayLine(db, task.id) : null; const gate = tab === "merge" && task.prUrl ? await gateWithTimeout(ref) : null; const openQuestions = questions.filter((q) => !q.answeredAt).length; const counts: Partial> = { 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 = (
{blockers.length === 0 && dependents.length === 0 &&

{t("Стори ни от чего не зависит.")}

} {blockers.length > 0 && (
    {blockers.map((b) => (
  • {b.open ? : } {b.key} {b.title}
    {blockers.map((x) => )}
  • ))}
)} {blockers.some((b) => b.open) &&

{t("Диспетчер не возьмёт стори, пока предшественники не в ревью или готово.")}

}
{blockers.map((x) => )} {dependents.length > 0 && (

{t("Её ждут:")} {dependents.map((d, i) => ( {i > 0 && ", "} {d.key} ))}

)}
{CI_ICON[ci.state as keyof typeof CI_ICON]} {t.text(ci.label)} {ci.sha && {ci.sha.slice(0, 7)}} {task.ciAttempts > 0 &&

{t("красных подряд: {n}", { n: task.ciAttempts })}

}
{review && (

{t.text(reviewLabel(review))}

{review.sha.slice(0, 7)} · {ago(review.updatedAt, t)}

)} {events.length === 0 ? (

{t("Событий нет.")}

) : ( <> {t("Вся активность →")} )}
); const headerActions = ( <> {task.prUrl && ( )}
); // What a product manager reads first: open questions (the «готово к ревью» message is the card's own buttons). // PEP-149: only messages of type `question`; failures and other factory messages stay under «Подробнее». const productQuestions = questions.filter((q) => !q.answeredAt && questionType(q, task.status) === "question").reverse(); const productView = storyProductView({ status: task.status, archived: !!task.archivedAt, progress, agentWorking: !!live, agentName: live?.agentName, openQuestions: productQuestions.length, refining, waitsFor: blockers.filter((b) => b.open).map((b) => b.title), accepted: !!pendingAccept, delayed, delayLine, // PEP-182: no agent yet because all are busy — the place in the queue. queued: live ? null : ((await queuePositions(db, task.projectId)).get(task.id) ?? null), }); const body = ( <> {refining && (

{refining === "waiting" ? t("Аналитик ждёт ваших ответов") : t("Аналитик уточняет задачу")} {refining === "waiting" ? t("— вопрос во вкладке «Comments». Не ответите — возьмёт варианты по умолчанию и отдаст стори в работу.") : t("— через минуту здесь появятся критерии приёмки. Агент-разработчик возьмёт стори после этого.")}

)} {sp.edit ? (