// 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, Hourglass, Play } 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 AgentsLine, 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 ( ); } function WindowCell({ label, w }: { label: string; w: WindowView | null }) { if (!w) return null; return ( {label} {w.reset ? ( сброшено ) : ( <> {Math.round(w.pct!)}% {w.resetsAt && ( сброс )} )} ); } 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 (
Лимиты {!top ? ( нет данных о лимитах ) : ( <> {withData.length > 1 && {top.name}} {top.stale && top.at && устарело ({ago(top.at)})} )} {limited.map((a) => ( {a.name}: лимит до ))} {withData.length > 1 && ( +{withData.length - 1} {admin ? подписки : "аккаунт"} )}
); } /** PEP-121: the same bar for a product manager — one line, no shares, windows or account names. */ export function AgentsStrip({ line }: { line: AgentsLine }) { return (
{line.state === "working" ? ( <> Агенты работают ) : ( <> Агенты продолжат в )}
); } 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

Расход: нет данных{provider !== "claude" ? ` (${provider} не сообщает)` : ""}

; return (

Расход: {describeUsage(usage)} {t.context && ( контекст {fmtTokens(t.context.used)} / {fmtTokens(t.context.size)} )}

); } // ── 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") => ( ); return (
{field("minutes", "Минуты раннеров")} {field("tokens", "Токены")} {field("restarts", "Перезапуски")} {field("costUsd", "Стоимость, $", "0.01")}
); } export function BudgetPanel({ view, taskId, projectBudget, back, action, paused }: { view: TaskBudgetView; taskId: number; projectBudget: Budget; back: string; action: (f: FormData) => Promise; paused: boolean }) { return (
{paused &&

Бюджет исчерпан — агент на паузе до вашего решения (вопрос во «Входящих» или новый бюджет ниже).

}
    {BUDGET_KINDS.map((k) => { const limit = view.budget[k]; const pct = limit ? (spentOf(view, k) / limit) * 100 : null; return (
  • {BUDGET_LABELS[k]} {spentText(view, k)} из {formatBudgetValue(k, limit)} {pct != null && }
  • ); })}

{view.source === "task" ? "Свой бюджет стори." : view.source === "project" ? "Бюджет проекта по умолчанию." : "Без бюджета."} Сессий {view.spend.sessions} {view.spend.costEstimated && " · ≈ — оценка по прайсу API"}.

Изменить бюджет стори
{view.source === "task" && ( )}
); } export function ProjectBudgetPanel({ projectId, budget, back, action }: { projectId: number; budget: Budget; back: string; action: (f: FormData) => Promise }) { return (

Бюджет по умолчанию для каждой стори; пусто — без предела. Превышение ставит стори на паузу (ход прерывается, разговор сохраняется) и присылает вопрос: продлить, снять лимит или остановить.

); } // ── PEP-47: metrics ─────────────────────────────────────────────────────────────── function Stat({ label, value, hint }: { label: string; value: ReactNode; hint?: string }) { return (
{label} {value}
); } const day = (d: Date) => d.toLocaleDateString("ru-RU", { day: "2-digit", month: "2-digit" }); function Bar({ value, max }: { value: number; max: number }) { return ( 0 ? Math.max(value > 0 ? 3 : 0, (value / max) * 100) : 0}%` }} /> ); } 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 (
Период: {[4, 8, 12].map((w) => ( {w} нед. ))}

По неделям

{cols.map(([h]) => ( ))} {[...m.weekly].reverse().map((w) => ( {cols.map(([h, f]) => ( ))} ))}
Неделя Готово Раннеры{h}
{day(w.from)} {w.done} {fmtHours(w.runnerHours)} {f(w)}

По агентам

{m.byProvider.length === 0 ? ( Сессий за период не было. ) : ( [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)])} /> )}

По эпикам (всё время)

{m.byEpic.length === 0 ? ( Стори нет. ) : ( [ e.goalId ? {e.title} : e.title, e.stories, e.done, fmtHours(e.spend.minutes / 60), fmtTokens(e.spend.tokens), fmtCost(e.spend.usage), ])} /> )}
); } function SimpleTable({ head, rows }: { head: string[]; rows: ReactNode[][] }) { return (
{head.map((h, i) => ( ))} {rows.map((r, i) => ( {r.map((c, j) => ( ))} ))}
{h}
{c}
); } // ── 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 Действий нет.; return (
    {entries.map((e) => { const who = actorLabel(e); const line = eventLine(e); return (
  1. {ago(e.createdAt)} {e.actorKind ? {who} : автор не записан} {e.type} {showProject && !e.taskKey && {e.projectKey}} {e.taskKey && {e.taskKey}} {line && {line.length > 300 ? `${line.slice(0, 300)}…` : line}}
  2. ); })}
); } export function JournalFilters({ action, projects, value }: { action: string; projects?: Array<{ key: string; name: string }>; value: { project?: string; actor?: string; channel?: string; tab?: string } }) { return (
{value.tab && } {projects && ( )}
); }