peppa/apps/web/app/(app)/t/[key]/page.tsx
Асель c7283063c9 PEP-39: rotate a limited session to a free subscription of the pool at the turn boundary
Limit marks the subscription «лимит до …»; the watchdog relaunches the session on another
usable subscription of the same provider (Claude/OpenCode resume the conversation, Codex
starts afresh), threshold banner switches after the turn, max 3 switches/hour, simple
fairness between projects, subscription_switched events + Telegram message, web shows
subscription and switch history. Migration 0004 (sessions.rotate_reason).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 05:31:22 +05:00

199 lines
10 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.

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 { 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 { Button } from "@/components/ui/button";
import { Input, NativeSelect } from "@/components/ui/input";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { openspecArtifacts, taskActivity, taskForUser } from "@/lib/queries";
import { startTaskSession } from "../../actions";
const CI_ICON = { success: <CircleCheck className="size-4 text-ok" />, failure: <CircleX className="size-4 text-destructive" />, pending: <Hourglass className="size-4 text-warn" /> };
export default async function StoryPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
const { key } = await params;
const { error } = 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 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}`;
// 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 aside = (
<div className="flex flex-col gap-6">
<PanelSection title="Проверки">
<div className="flex flex-wrap items-center gap-2 text-sm">
{CI_ICON[ci.state as keyof typeof CI_ICON]}
{ci.runUrl ? <a href={ci.runUrl} className="text-primary">{ci.label}</a> : ci.label}
{ci.sha && <span className="font-mono text-xs text-muted-foreground">{ci.sha.slice(0, 7)}</span>}
</div>
{task.ciAttempts > 0 && <p className="m-0 text-xs text-muted-foreground">красных подряд: {task.ciAttempts}</p>}
{ci.failed.map((f) => (
<Disclosure
key={f.check}
summary={
<span className="flex items-center gap-1.5">
<CircleX className="size-3.5 text-destructive" />
<span className="font-mono">{f.check}</span>
{f.runUrl && <a href={f.runUrl} className="text-xs text-primary">лог</a>}
</span>
}
>
{f.logTail && <pre className="m-0 max-h-80 overflow-auto font-mono text-[11px] whitespace-pre-wrap">{f.logTail.split("\n").slice(-60).join("\n")}</pre>}
</Disclosure>
))}
</PanelSection>
{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>
</PanelSection>
)}
<PanelSection title="События">
{events.length === 0 ? (
<p className="m-0 text-sm text-muted-foreground">Событий нет.</p>
) : (
<ol className="m-0 flex list-none flex-col gap-1.5 border-l p-0 pl-3">
{events.map((e) => (
<li key={e.id} className="text-xs [overflow-wrap:anywhere]">
<span className="font-mono text-muted-foreground">{ago(e.createdAt)}</span> <span className="font-mono text-primary">{e.type}</span>{" "}
{eventLine(e)}
</li>
))}
</ol>
)}
</PanelSection>
</div>
);
return (
<Workspace aside={aside}>
<AutoRefresh />
<Flash error={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={
task.prUrl && (
<Button asChild size="sm">
<a href={task.prUrl}>
<GitPullRequest />
PR
</a>
</Button>
)
}
/>
<div className="rounded-lg border bg-card p-4 text-sm whitespace-pre-wrap">{task.description || <span className="text-muted-foreground">Без описания</span>}</div>
<Section title="Сессии">
<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>
)}
</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>
<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>
))
) : (
<Empty>Change ещё не создан.</Empty>
)}
</Section>
</Workspace>
);
}