- 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>
420 lines
21 KiB
TypeScript
420 lines
21 KiB
TypeScript
// Accounting blocks (PEP-5/43/47/48): the usage strip on top, story budget, project metrics, journal.
|
||
import Link from "next/link";
|
||
import type { ReactNode } from "react";
|
||
import { Gauge } from "lucide-react";
|
||
import {
|
||
accountPeak,
|
||
actorLabel,
|
||
ACTOR_CHANNEL_NAMES,
|
||
ACTOR_KIND_NAMES,
|
||
BUDGET_KINDS,
|
||
BUDGET_LABELS,
|
||
describeUsage,
|
||
fmtCost,
|
||
fmtHours,
|
||
fmtPct,
|
||
fmtTokens,
|
||
formatBudgetValue,
|
||
PROVIDER_NAMES,
|
||
usageTotals,
|
||
type AccountUsage,
|
||
type Budget,
|
||
type JournalEntry,
|
||
type MetricsBucket,
|
||
type ProjectMetrics,
|
||
type SessionUsage,
|
||
type TaskBudgetView,
|
||
type WindowView,
|
||
} from "@peppa/core";
|
||
import { Hidden } from "@/components/cards";
|
||
import { eventLine } from "@/components/RunnerConsole";
|
||
import { LocalTime } from "@/components/LocalTime";
|
||
import { ago, Empty } from "@/components/common";
|
||
import { Badge } from "@/components/ui/badge";
|
||
import { Button } from "@/components/ui/button";
|
||
import { Input } from "@/components/ui/input";
|
||
import { cn } from "@/lib/utils";
|
||
|
||
const tone = (pct: number) => (pct >= 90 ? "bg-destructive" : pct >= 70 ? "bg-warn" : "bg-primary");
|
||
|
||
function Meter({ pct, className }: { pct: number; className?: string }) {
|
||
return (
|
||
<span className={cn("relative inline-block h-1.5 w-16 overflow-hidden rounded-full bg-muted align-middle", className)} aria-hidden>
|
||
<span className={cn("absolute inset-y-0 left-0 rounded-full", tone(pct))} style={{ width: `${Math.max(2, Math.min(100, pct))}%` }} />
|
||
</span>
|
||
);
|
||
}
|
||
|
||
function WindowCell({ label, w }: { label: string; w: WindowView | null }) {
|
||
if (!w) return null;
|
||
return (
|
||
<span className="flex items-center gap-1.5 whitespace-nowrap">
|
||
<span className="text-muted-foreground">{label}</span>
|
||
{w.reset ? (
|
||
<span className="text-muted-foreground">сброшено</span>
|
||
) : (
|
||
<>
|
||
<Meter pct={w.pct!} />
|
||
<span className="font-mono tabular-nums">{Math.round(w.pct!)}%</span>
|
||
{w.resetsAt && (
|
||
<span className="text-muted-foreground">
|
||
сброс <LocalTime iso={w.resetsAt.toISOString()} />
|
||
</span>
|
||
)}
|
||
</>
|
||
)}
|
||
</span>
|
||
);
|
||
}
|
||
|
||
function accountTitle(a: AccountUsage): string {
|
||
const w = (l: string, v: WindowView | null) => (!v ? `${l}: нет данных` : v.reset ? `${l}: сброшено` : `${l}: ${Math.round(v.pct!)}%`);
|
||
return `${a.name} — ${w("5 ч", a.fiveHour)}, ${w("7 д", a.sevenDay)}${a.limitedUntil ? ", в лимите" : ""}${a.at ? `, обновлено ${a.at.toLocaleString("ru-RU")}` : ""}`;
|
||
}
|
||
|
||
/** PEP-5: thin bar above every page — the most loaded limit window of the user's accounts. */
|
||
export function UsageStrip({ accounts, admin }: { accounts: AccountUsage[]; admin: boolean }) {
|
||
const withData = accounts.filter((a) => a.fiveHour || a.sevenDay || a.limitedUntil);
|
||
const top = withData[0];
|
||
const limited = accounts.filter((a) => a.limitedUntil);
|
||
return (
|
||
<div
|
||
role="status"
|
||
aria-label="Лимиты подписок"
|
||
title={accounts.map(accountTitle).join("\n") || undefined}
|
||
className="flex min-h-8 flex-wrap items-center gap-x-4 gap-y-1 border-b bg-sidebar/40 px-4 py-1 text-xs md:px-8"
|
||
>
|
||
<span className="flex items-center gap-1.5 text-muted-foreground">
|
||
<Gauge className="size-3.5" />
|
||
Лимиты
|
||
</span>
|
||
{!top ? (
|
||
<span className="text-muted-foreground">нет данных о лимитах</span>
|
||
) : (
|
||
<>
|
||
{withData.length > 1 && <span className="font-medium">{top.name}</span>}
|
||
<WindowCell label="5 ч" w={top.fiveHour} />
|
||
<WindowCell label="7 д" w={top.sevenDay} />
|
||
{top.stale && top.at && <span className="text-warn">устарело ({ago(top.at)})</span>}
|
||
</>
|
||
)}
|
||
{limited.map((a) => (
|
||
<span key={a.key} className="whitespace-nowrap text-destructive">
|
||
{a.name}: лимит до <LocalTime iso={a.limitedUntil!.toISOString()} />
|
||
</span>
|
||
))}
|
||
{withData.length > 1 && (
|
||
<span className="text-muted-foreground">
|
||
+{withData.length - 1} {admin ? <Link href="/subscriptions" className="text-muted-foreground underline-offset-2 hover:text-foreground">подписки</Link> : "аккаунт"}
|
||
</span>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export const usagePeakSort = (a: AccountUsage[]) => [...a].sort((x, y) => accountPeak(y) - accountPeak(x));
|
||
|
||
/** PEP-5: one line under a runner card. */
|
||
export function SessionUsageLine({ usage, provider }: { usage: SessionUsage | null; provider: string }) {
|
||
const t = usageTotals(usage);
|
||
if (!t.hasData) return <p className="m-0 text-xs text-muted-foreground">Расход: нет данных{provider !== "claude" ? ` (${provider} не сообщает)` : ""}</p>;
|
||
return (
|
||
<p className="m-0 flex flex-wrap items-center gap-x-3 text-xs text-muted-foreground">
|
||
<span>Расход: {describeUsage(usage)}</span>
|
||
{t.context && (
|
||
<span className="flex items-center gap-1.5">
|
||
контекст <Meter pct={t.context.pct} className="w-12" /> {fmtTokens(t.context.used)} / {fmtTokens(t.context.size)}
|
||
</span>
|
||
)}
|
||
</p>
|
||
);
|
||
}
|
||
|
||
// ── PEP-43: budget ────────────────────────────────────────────────────────────────
|
||
const spentOf = (v: TaskBudgetView, k: (typeof BUDGET_KINDS)[number]) => (k === "costUsd" ? (v.spend.costUsd ?? 0) : v.spend[k]);
|
||
const spentText = (v: TaskBudgetView, k: (typeof BUDGET_KINDS)[number]) => (k === "costUsd" ? fmtCost(v.spend.usage) : formatBudgetValue(k, v.spend[k]));
|
||
|
||
export function BudgetFields({ budget, placeholder }: { budget: Budget; placeholder?: Budget }) {
|
||
const field = (k: (typeof BUDGET_KINDS)[number], label: string, step = "1") => (
|
||
<label className="flex flex-col gap-1 text-xs text-muted-foreground">
|
||
{label}
|
||
<Input
|
||
type="number"
|
||
name={k}
|
||
min={0}
|
||
step={step}
|
||
defaultValue={budget[k] ?? ""}
|
||
placeholder={placeholder?.[k] != null ? String(placeholder[k]) : "∞"}
|
||
aria-label={label}
|
||
className="h-8 w-full"
|
||
/>
|
||
</label>
|
||
);
|
||
return (
|
||
<div className="grid grid-cols-2 gap-2">
|
||
{field("minutes", "Минуты раннеров")}
|
||
{field("tokens", "Токены")}
|
||
{field("restarts", "Перезапуски")}
|
||
{field("costUsd", "Стоимость, $", "0.01")}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export function BudgetPanel({ view, taskId, projectBudget, back, action, paused }: { view: TaskBudgetView; taskId: number; projectBudget: Budget; back: string; action: (f: FormData) => Promise<void>; paused: boolean }) {
|
||
return (
|
||
<div className="flex flex-col gap-2.5">
|
||
{paused && <p className="m-0 rounded-md border border-destructive/40 bg-destructive/10 px-2.5 py-1.5 text-xs text-destructive">Бюджет исчерпан — агент на паузе до вашего решения (вопрос во «Входящих» или новый бюджет ниже).</p>}
|
||
<ul className="m-0 flex list-none flex-col gap-1.5 p-0 text-sm">
|
||
{BUDGET_KINDS.map((k) => {
|
||
const limit = view.budget[k];
|
||
const pct = limit ? (spentOf(view, k) / limit) * 100 : null;
|
||
return (
|
||
<li key={k} className="flex items-center gap-2">
|
||
<span className="w-24 shrink-0 text-xs text-muted-foreground">{BUDGET_LABELS[k]}</span>
|
||
<span className="font-mono text-xs tabular-nums">{spentText(view, k)}</span>
|
||
<span className="text-xs text-muted-foreground">из {formatBudgetValue(k, limit)}</span>
|
||
{pct != null && <Meter pct={pct} className="ml-auto w-14" />}
|
||
</li>
|
||
);
|
||
})}
|
||
</ul>
|
||
<p className="m-0 text-xs text-muted-foreground">
|
||
{view.source === "task" ? "Свой бюджет стори." : view.source === "project" ? "Бюджет проекта по умолчанию." : "Без бюджета."} Сессий {view.spend.sessions}
|
||
{view.spend.costEstimated && " · ≈ — оценка по прайсу API"}.
|
||
</p>
|
||
<details className="text-sm">
|
||
<summary className="cursor-pointer text-xs text-muted-foreground">Изменить бюджет стори</summary>
|
||
<form action={action} className="mt-2 flex flex-col gap-2">
|
||
<Hidden fields={{ taskId, back }} />
|
||
<BudgetFields budget={view.source === "task" ? view.budget : {}} placeholder={projectBudget} />
|
||
<div className="flex flex-wrap gap-2">
|
||
<Button size="sm" name="mode" value="set">Сохранить</Button>
|
||
<Button size="sm" variant="outline" name="mode" value="unlimited">Без лимита</Button>
|
||
{view.source === "task" && (
|
||
<Button size="sm" variant="ghost" name="mode" value="inherit">Как в проекте</Button>
|
||
)}
|
||
</div>
|
||
</form>
|
||
</details>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export function ProjectBudgetPanel({ projectId, budget, back, action }: { projectId: number; budget: Budget; back: string; action: (f: FormData) => Promise<void> }) {
|
||
return (
|
||
<form action={action} className="flex flex-col gap-2">
|
||
<Hidden fields={{ projectId, back }} />
|
||
<BudgetFields budget={budget} />
|
||
<Button size="sm" className="self-start">Сохранить</Button>
|
||
<p className="m-0 text-xs text-muted-foreground">
|
||
Бюджет по умолчанию для каждой стори; пусто — без предела. Превышение ставит стори на паузу (ход прерывается, разговор сохраняется) и присылает вопрос: продлить, снять лимит или остановить.
|
||
</p>
|
||
</form>
|
||
);
|
||
}
|
||
|
||
// ── PEP-47: metrics ───────────────────────────────────────────────────────────────
|
||
function Stat({ label, value, hint }: { label: string; value: ReactNode; hint?: string }) {
|
||
return (
|
||
<div className="flex flex-col gap-0.5 rounded-lg border bg-card px-3 py-2.5" title={hint}>
|
||
<span className="text-xs text-muted-foreground">{label}</span>
|
||
<span className="font-mono text-lg font-semibold tabular-nums">{value}</span>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
const day = (d: Date) => d.toLocaleDateString("ru-RU", { day: "2-digit", month: "2-digit" });
|
||
|
||
function Bar({ value, max }: { value: number; max: number }) {
|
||
return (
|
||
<span className="relative inline-block h-1.5 w-full min-w-10 overflow-hidden rounded-full bg-muted align-middle" aria-hidden>
|
||
<span className="absolute inset-y-0 left-0 rounded-full bg-primary/70" style={{ width: `${max > 0 ? Math.max(value > 0 ? 3 : 0, (value / max) * 100) : 0}%` }} />
|
||
</span>
|
||
);
|
||
}
|
||
|
||
export function MetricsTab({ m, projectKey }: { m: ProjectMetrics; projectKey: string }) {
|
||
const s = m.summary;
|
||
const maxDone = Math.max(...m.weekly.map((w) => w.done), 0);
|
||
const maxHours = Math.max(...m.weekly.map((w) => w.runnerHours), 0);
|
||
const cols: Array<[string, (b: MetricsBucket) => ReactNode]> = [
|
||
["Цикл", (b) => fmtHours(b.cycleHoursMedian)],
|
||
["1-й проход", (b) => fmtPct(b.firstPassRate)],
|
||
["Возвраты", (b) => fmtPct(b.reviewReturnRate)],
|
||
["Вопр./стори", (b) => (b.questionsPerStory == null ? "—" : b.questionsPerStory.toFixed(1))],
|
||
["Ждали PM", (b) => fmtHours(b.pmWaitHours)],
|
||
["Лимиты", (b) => b.limitHits],
|
||
["Токены", (b) => fmtTokens(b.spend.tokens)],
|
||
["Стоимость", (b) => fmtCost(b.spend.usage)],
|
||
];
|
||
return (
|
||
<div className="flex flex-col gap-8">
|
||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||
<span className="text-muted-foreground">Период:</span>
|
||
{[4, 8, 12].map((w) => (
|
||
<Link key={w} href={`/p/${projectKey}?tab=metrics&weeks=${w}`} aria-current={m.weeks === w ? "page" : undefined} className={cn("rounded-md border px-2 py-0.5 text-xs", m.weeks === w ? "border-primary text-foreground" : "text-muted-foreground")}>
|
||
{w} нед.
|
||
</Link>
|
||
))}
|
||
</div>
|
||
<div className="grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-5">
|
||
<Stat label="Готово стори" value={s.done} />
|
||
<Stat label="Время цикла (медиана)" value={fmtHours(s.cycleHoursMedian)} hint="От «В работу» до «Готово»" />
|
||
<Stat label="Приняты с первого раза" value={fmtPct(s.firstPassRate)} hint="Без возврата из ревью и без замечаний ревьюера" />
|
||
<Stat label="Возвраты с ревью" value={fmtPct(s.reviewReturnRate)} />
|
||
<Stat label="Вопросов PM на стори" value={s.questionsPerStory == null ? "—" : s.questionsPerStory.toFixed(1)} hint="Вопросы, разрешения и одобрения; уведомления не считаются" />
|
||
<Stat label="Часы раннеров" value={fmtHours(s.runnerHours)} />
|
||
<Stat label="Агенты ждали PM" value={fmtHours(s.pmWaitHours)} hint="Сумма времени от вопроса агента до ответа человека" />
|
||
<Stat label="Упоры в лимит" value={s.limitHits} />
|
||
<Stat label="Токены" value={fmtTokens(s.spend.tokens)} />
|
||
<Stat label="Стоимость" value={fmtCost(s.spend.usage)} hint="≈ — оценка по прайсу API, если агент не сообщил стоимость" />
|
||
</div>
|
||
|
||
<section className="flex flex-col gap-2">
|
||
<h2 className="m-0 text-[15px] font-semibold">По неделям</h2>
|
||
<div className="overflow-x-auto rounded-lg border">
|
||
<table className="w-full min-w-[760px] border-collapse text-sm">
|
||
<thead className="bg-muted/40 text-xs text-muted-foreground">
|
||
<tr>
|
||
<th className="px-3 py-2 text-left font-medium">Неделя</th>
|
||
<th className="px-3 py-2 text-left font-medium">Готово</th>
|
||
<th className="px-3 py-2 text-left font-medium">Раннеры</th>
|
||
{cols.map(([h]) => (
|
||
<th key={h} className="px-3 py-2 text-right font-medium whitespace-nowrap">{h}</th>
|
||
))}
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{[...m.weekly].reverse().map((w) => (
|
||
<tr key={w.from.toISOString()} className="border-t">
|
||
<td className="px-3 py-1.5 font-mono text-xs whitespace-nowrap">{day(w.from)}</td>
|
||
<td className="px-3 py-1.5">
|
||
<span className="flex items-center gap-2"><span className="w-5 font-mono tabular-nums">{w.done}</span><Bar value={w.done} max={maxDone} /></span>
|
||
</td>
|
||
<td className="px-3 py-1.5">
|
||
<span className="flex items-center gap-2"><span className="w-16 shrink-0 font-mono text-xs whitespace-nowrap tabular-nums">{fmtHours(w.runnerHours)}</span><Bar value={w.runnerHours} max={maxHours} /></span>
|
||
</td>
|
||
{cols.map(([h, f]) => (
|
||
<td key={h} className="px-3 py-1.5 text-right font-mono text-xs tabular-nums whitespace-nowrap">{f(w)}</td>
|
||
))}
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
</section>
|
||
|
||
<div className="grid gap-8 lg:grid-cols-2">
|
||
<section className="flex flex-col gap-2">
|
||
<h2 className="m-0 text-[15px] font-semibold">По агентам</h2>
|
||
{m.byProvider.length === 0 ? (
|
||
<Empty>Сессий за период не было.</Empty>
|
||
) : (
|
||
<SimpleTable
|
||
head={["Агент", "Сессий", "Стори", "Часы", "Токены", "Стоимость"]}
|
||
rows={m.byProvider.map((p) => [PROVIDER_NAMES[p.provider as keyof typeof PROVIDER_NAMES] ?? p.provider, p.sessions, p.stories, fmtHours(p.hours), fmtTokens(p.spend.tokens), fmtCost(p.spend.usage)])}
|
||
/>
|
||
)}
|
||
</section>
|
||
<section className="flex flex-col gap-2">
|
||
<h2 className="m-0 text-[15px] font-semibold">По эпикам (всё время)</h2>
|
||
{m.byEpic.length === 0 ? (
|
||
<Empty>Стори нет.</Empty>
|
||
) : (
|
||
<SimpleTable
|
||
head={["Эпик", "Стори", "Готово", "Время", "Токены", "Стоимость"]}
|
||
rows={m.byEpic.map((e) => [
|
||
e.goalId ? <Link key="t" href={`/p/${projectKey}?epic=${e.goalId}`}>{e.title}</Link> : e.title,
|
||
e.stories,
|
||
e.done,
|
||
fmtHours(e.spend.minutes / 60),
|
||
fmtTokens(e.spend.tokens),
|
||
fmtCost(e.spend.usage),
|
||
])}
|
||
/>
|
||
)}
|
||
</section>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function SimpleTable({ head, rows }: { head: string[]; rows: ReactNode[][] }) {
|
||
return (
|
||
<div className="overflow-x-auto rounded-lg border">
|
||
<table className="w-full border-collapse text-sm">
|
||
<thead className="bg-muted/40 text-xs text-muted-foreground">
|
||
<tr>
|
||
{head.map((h, i) => (
|
||
<th key={h} className={cn("px-3 py-2 font-medium", i === 0 ? "text-left" : "text-right")}>{h}</th>
|
||
))}
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{rows.map((r, i) => (
|
||
<tr key={i} className="border-t">
|
||
{r.map((c, j) => (
|
||
<td key={j} className={cn("px-3 py-1.5", j === 0 ? "text-left" : "text-right font-mono text-xs tabular-nums")}>{c}</td>
|
||
))}
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// ── PEP-48: journal ───────────────────────────────────────────────────────────────
|
||
const KIND_TONE = { user: "info", agent: "ok", system: "muted" } as const;
|
||
|
||
export function JournalList({ entries, showProject = true }: { entries: JournalEntry[]; showProject?: boolean }) {
|
||
if (!entries.length) return <Empty>Действий нет.</Empty>;
|
||
return (
|
||
<ol className="m-0 flex list-none flex-col divide-y rounded-lg border p-0">
|
||
{entries.map((e) => {
|
||
const who = actorLabel(e);
|
||
const line = eventLine(e);
|
||
return (
|
||
<li key={e.id} className="flex flex-wrap items-baseline gap-x-2.5 gap-y-1 px-3 py-2 text-sm">
|
||
<span className="w-14 shrink-0 font-mono text-xs text-muted-foreground">{ago(e.createdAt)}</span>
|
||
{e.actorKind ? <Badge variant={KIND_TONE[e.actorKind]}>{who}</Badge> : <Badge variant="muted">автор не записан</Badge>}
|
||
<span className="font-mono text-xs text-primary">{e.type}</span>
|
||
{showProject && !e.taskKey && <Link href={`/p/${e.projectKey}`} className="font-mono text-xs">{e.projectKey}</Link>}
|
||
{e.taskKey && <Link href={`/t/${e.taskKey}`} className="font-mono text-xs">{e.taskKey}</Link>}
|
||
{line && <span className="min-w-0 flex-[1_1_16rem] text-xs text-muted-foreground [overflow-wrap:anywhere]">{line.length > 300 ? `${line.slice(0, 300)}…` : line}</span>}
|
||
</li>
|
||
);
|
||
})}
|
||
</ol>
|
||
);
|
||
}
|
||
|
||
export function JournalFilters({ action, projects, value }: { action: string; projects?: Array<{ key: string; name: string }>; value: { project?: string; actor?: string; channel?: string; tab?: string } }) {
|
||
return (
|
||
<form action={action} method="get" className="flex flex-wrap items-center gap-2 text-sm">
|
||
{value.tab && <input type="hidden" name="tab" value={value.tab} />}
|
||
{projects && (
|
||
<select name="project" defaultValue={value.project ?? ""} aria-label="Проект" className="h-8 rounded-md border bg-background px-2 text-sm">
|
||
<option value="">Все проекты</option>
|
||
{projects.map((p) => (
|
||
<option key={p.key} value={p.key}>{p.key} — {p.name}</option>
|
||
))}
|
||
</select>
|
||
)}
|
||
<select name="actor" defaultValue={value.actor ?? ""} aria-label="Кто" className="h-8 rounded-md border bg-background px-2 text-sm">
|
||
<option value="">Все авторы</option>
|
||
{Object.entries(ACTOR_KIND_NAMES).map(([k, v]) => (
|
||
<option key={k} value={k}>{v}</option>
|
||
))}
|
||
</select>
|
||
<select name="channel" defaultValue={value.channel ?? ""} aria-label="Канал" className="h-8 rounded-md border bg-background px-2 text-sm">
|
||
<option value="">Все каналы</option>
|
||
{Object.entries(ACTOR_CHANNEL_NAMES).map(([k, v]) => (
|
||
<option key={k} value={k}>{v}</option>
|
||
))}
|
||
</select>
|
||
<Button size="sm" variant="outline">Показать</Button>
|
||
</form>
|
||
);
|
||
}
|