peppa/apps/web/components/RunnerConsole.tsx
Асель 14916079bc PEP-5/43/47/48: usage and limits, story budgets, factory metrics, audit journal
- PEP-5: statusLine hook (cost, context, 5h/7d limit windows), transcript tokens,
  sessions.usage, usage strip over every page, runner usage, bot /status, MCP get_usage
- PEP-43: project/story budgets in settings, watchdog pause (Escape, question to the PM:
  extend x2 / remove limit / stop), start/resume guard, budget on the story card
- PEP-47: project metrics tab (cycle time, first pass, review returns, questions, runner
  hours, PM wait, limits, spend by week/agent/epic), MCP get_metrics
- PEP-48: event authors (actor columns, AsyncLocalStorage context), question_answered,
  /journal for superadmins, project journal tab, authors in the story feed
- Migration 0007_usage_audit; OpenSpec changes archived

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

211 lines
11 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.

// 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 RunnerTaskView, type SessionView, type StepView } from "@peppa/core";
import { RunnerStories } from "@/components/Runners";
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";
import { RunnerTerminal } from "@/components/RunnerTerminal";
import { SessionUsageLine } from "@/components/Accounting";
import type { InboxItem } from "@/lib/queries";
import { SESSION_STATUS, TONE_BG, TONE_TEXT } from "@/lib/status";
import { cn } from "@/lib/utils";
/** «остановлена · продолжит в 03:10» for a runner that hit the usage limit (PEP-56). */
export function LimitNote({ s }: { s: SessionView }) {
if (s.status !== "rate_limited") return null;
if (!s.resumeAt) return <>остановлена · лимит</>;
if (s.resumeAt.getTime() <= Date.now()) return <>остановлена · продолжит сейчас</>;
return (
<>
остановлена · продолжит в <LocalTime iso={s.resumeAt.toISOString()} />
</>
);
}
interface SwitchPayload {
fromName?: string | null;
toName?: string | null;
reason?: "limit" | "threshold";
carried?: "resume" | "fresh";
}
/** «Claude A → Claude B · лимит · разговор продолжен» for a subscription_switched event (PEP-39). */
export function switchText(payload: unknown): string {
const p = (payload ?? {}) as SwitchPayload;
return `${p.fromName ?? "?"} → ${p.toName ?? "?"} · ${p.reason === "threshold" ? "порог использования" : "лимит"} · ${p.carried === "fresh" ? "запуск заново" : "разговор продолжен"}`;
}
/** One line of a session's event log: type + the human part for known types. */
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;
if (e.type === "question_answered") return `ответ на #${(e.payload as { questionId?: number }).questionId}: ${(e.payload as { answer?: string }).answer ?? ""}`;
if (e.type === "budget_paused") return `бюджет исчерпан: ${(e.payload as { summary?: string }).summary ?? ""}`;
return "";
}
/** `selected`: "wide" — picked by default, highlighted only where the side panel is visible. */
export function RunnerRow({ s, href, selected, needsPm }: { s: SessionView; href: string; selected: boolean | "wide"; needsPm: boolean }) {
const limited = s.status === "rate_limited";
const st = SESSION_STATUS[s.status] ?? { label: s.status, tone: "muted" as const };
return (
<li>
<Link
href={href}
scroll={false}
data-hotkey-item
aria-current={selected === true ? "true" : undefined}
className={cn(
"group grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-3 gap-y-0.5 rounded-md border border-transparent px-3 py-2.5 text-sm text-foreground transition-colors hover:bg-accent hover:no-underline",
needsPm && "bg-primary/[0.07] shadow-[inset_2px_0_0_var(--primary)]",
selected === true && "border-border bg-accent",
selected === "wide" && "xl:border-border xl:bg-accent",
)}
>
<span className={cn("row-span-2 size-2 self-start mt-1.5 rounded-full", TONE_BG[st.tone], (s.status === "running" || s.status === "starting") && "animate-pulse")} />
<span className="flex min-w-0 items-baseline gap-2">
<span className="shrink-0 font-mono text-xs text-primary">{s.taskKey ?? s.projectKey}</span>
<span className="truncate">{s.taskTitle ?? s.name ?? "без стори"}</span>
</span>
<span className={cn("text-right font-mono text-xs whitespace-nowrap", TONE_TEXT[st.tone])}>{limited ? (
<>
<span className="sm:hidden">{st.label}</span>
<span className="max-sm:hidden">
<LimitNote s={s} />
</span>
</>
) : (
st.label
)}
</span>
<span className="truncate font-mono text-[11px] text-muted-foreground">
{s.name && s.taskTitle ? `${s.name} · ` : ""}{s.projectKey} · {s.provider}{s.subscriptionName ? ` · ${s.subscriptionName}` : ""}{s.subscriptionSwitches > 0 ? ` (↻${s.subscriptionSwitches})` : ""} · #{s.id} · {s.tmuxName}
</span>
<span className="text-right font-mono text-[11px] whitespace-nowrap text-muted-foreground">{ago(s.lastActivityAt)}</span>
{limited && (
<span className="col-span-2 col-start-2 font-mono text-[11px] text-warn sm:hidden">
<LimitNote s={s} />
</span>
)}
</Link>
</li>
);
}
export function RunnerDetails({ s, questions, events, steps, stories, back, closeHref, chosen }: { s: SessionView; questions: InboxItem[]; events: Array<{ id: number; type: string; payload: unknown; createdAt: Date }>; steps: StepView[]; stories?: { history: RunnerTaskView[]; queue: RunnerTaskView[] }; 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. */}
{chosen && <ScrollIntoViewOnNarrow id={s.id} />}
<header className="flex flex-col gap-2">
<div className="flex items-center gap-2">
<StatusBadge status={s.status} kind="session" />
<span className="font-mono text-xs text-muted-foreground">#{s.id}</span>
<Link href={closeHref} scroll={false} aria-label="Закрыть" title="Закрыть" className="ml-auto rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-foreground">
<X className="size-4" />
</Link>
</div>
<h2 className="m-0 text-base leading-snug font-semibold">
{s.taskKey && <Key href={`/t/${s.taskKey}`} className="mr-1.5">{s.taskKey}</Key>}
{s.taskTitle ?? s.name ?? "без стори"}
</h2>
{s.name && s.taskTitle && <p className="m-0 text-sm text-muted-foreground">{s.name}</p>}
{/* PEP-5: tokens, cost, context of this runner. */}
<SessionUsageLine usage={s.usage} provider={s.provider} />
{s.status === "rate_limited" && (
<p className="m-0 rounded-md border border-warn/40 bg-warn/10 px-3 py-2 text-sm">
<LimitNote s={s} />
<span className="block text-xs text-muted-foreground">
авто-продолжений сегодня: {s.limitResumes} из {MAX_LIMIT_RESUMES_PER_DAY}
</span>
{s.rotateReason === "limit" && <span className="block text-xs">переключается на свободную подписку пула…</span>}
</p>
)}
{s.rotateReason === "threshold" && (
<p className="m-0 rounded-md border border-warn/40 bg-warn/10 px-3 py-2 text-sm">Подписка подходит к лимиту — после этого хода переключится на свободную.</p>
)}
</header>
<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">
<Key href={`/p/${s.projectKey}`}>{s.projectKey}</Key>
</dd>
<dt className="text-muted-foreground">Агент</dt>
<dd className="m-0">{PROVIDER_NAMES[s.provider]} · поколение {s.generation}</dd>
<dt className="text-muted-foreground">Подписка</dt>
<dd className="m-0">
{s.subscriptionName ?? (s.subscriptionId ? `#${s.subscriptionId}` : "вход машины")}
{s.subscriptionSwitches > 0 && <span className="text-muted-foreground"> · переключений {s.subscriptionSwitches}</span>}
</dd>
<dt className="text-muted-foreground">Запущен</dt>
<dd className="m-0">{ago(s.startedAt)}</dd>
<dt className="text-muted-foreground">Активность</dt>
<dd className="m-0">{ago(s.lastActivityAt)}</dd>
</dl>
<AttachCommand name={s.tmuxName} />
<SessionActions s={s} back={back} />
{stories && <RunnerStories s={s} history={stories.history} queue={stories.queue} back={back} />}
{questions.length > 0 && (
<PanelSection title="Ждёт ответа" count={questions.length}>
{questions.map((q) => (
<QuestionCard key={q.id} q={q} taskKey={s.taskKey} taskStatus={q.taskStatus} back={back} compact />
))}
</PanelSection>
)}
<PanelSection title="Что делает агент">
<AgentSteps key={s.id} sessionId={s.id} initial={steps} live={!finished} hooks={s.provider === "claude"} />
</PanelSection>
<PanelSection title="Терминал">
{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" />
Сессия завершена — терминала больше нет.
</div>
) : (
<RunnerTerminal key={s.id} sessionId={s.id} live />
)}
</PanelSection>
{events.some((e) => e.type === "subscription_switched") && (
<PanelSection title="Переключения подписок">
<ol className="m-0 flex list-none flex-col gap-1.5 p-0">
{events
.filter((e) => e.type === "subscription_switched")
.map((e) => (
<li key={e.id} className="text-sm [overflow-wrap:anywhere]">
<span className="font-mono text-xs text-muted-foreground">{ago(e.createdAt)}</span> {switchText(e.payload)}
</li>
))}
</ol>
</PanelSection>
)}
{events.length > 0 && (
<PanelSection title="События">
<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>
);
}