peppa/apps/web/components/RunnerConsole.tsx

228 lines
12 KiB
TypeScript

// 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 { SubscriptionName } from "@/components/SubscriptionName";
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";
import { getT } from "@/lib/i18n";
import { translator, type Translator } from "@peppa/shared/i18n";
/** «остановлена · продолжит в 03:10» for a runner that hit the usage limit (PEP-56). */
export async function LimitNote({ s }: { s: SessionView }) {
if (s.status !== "rate_limited") return null;
const t = await getT();
if (!s.resumeAt) return <>{t("остановлена · лимит")}</>;
if (s.resumeAt.getTime() <= Date.now()) return <>{t("остановлена · продолжит сейчас")}</>;
return (
<>
{t("остановлена · продолжит в")} <LocalTime iso={s.resumeAt.toISOString()} />
</>
);
}
interface SwitchPayload {
fromName?: string | null;
toName?: string | null;
reason?: "limit" | "threshold" | "manual";
carried?: "resume" | "fresh";
}
/**
* «Claude A → Claude B · лимит · разговор продолжен» for a subscription_switched event (PEP-39).
* PEP-121: the names only with `names` (a superadmin) — others read «другая подписка».
*/
export function switchText(payload: unknown, names = false, t: Translator = translator("ru")): string {
const p = (payload ?? {}) as SwitchPayload;
const reason = p.reason === "threshold" ? t("порог использования") : p.reason === "manual" ? t("переключил администратор") : t("лимит");
const carried = p.carried === "fresh" ? t("запуск заново") : t("разговор продолжен");
const from = names ? `${p.fromName ?? "?"} → ${p.toName ?? "?"}` : t("другая подписка");
return `${from} · ${reason} · ${carried}`;
}
/** One line of a session's event log: type + the human part for known types. `t` defaults to Russian. */
export function eventLine(e: { type: string; payload: unknown }, t: Translator = translator("ru")): string {
if (e.type === "progress") return (e.payload as { text: string }).text;
if (e.type === "subscription_switched") return switchText(e.payload, false, t);
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 t("ответ на #{id}: {answer}", { id: (e.payload as { questionId?: number }).questionId, answer: (e.payload as { answer?: string }).answer ?? "" });
if (e.type === "budget_paused") return t("бюджет исчерпан: {summary}", { summary: (e.payload as { summary?: string }).summary ?? "" });
return "";
}
/** `selected`: "wide" — picked by default, highlighted only where the side panel is visible. */
export async function RunnerRow({ s, href, selected, needsPm }: { s: SessionView; href: string; selected: boolean | "wide"; needsPm: boolean }) {
const t = await getT();
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 ?? t("без стори")}</span>
</span>
<span className={cn("text-right font-mono text-xs whitespace-nowrap", TONE_TEXT[st.tone])}>{limited ? (
<>
<span className="sm:hidden">{t(st.label)}</span>
<span className="max-sm:hidden">
<LimitNote s={s} />
</span>
</>
) : (
t(st.label)
)}
</span>
<span className="truncate font-mono text-[11px] text-muted-foreground">
{s.name && s.taskTitle ? `${s.name} · ` : ""}{s.projectKey} · {s.provider}<SubscriptionName s={s} prefix=" · " />{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, t)}</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 async function RunnerDetails({ s, questions, events, steps, stories, back, closeHref, chosen, names = false }: { names?: boolean; 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 t = await getT();
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={t("Закрыть")} title={t("Закрыть")} 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 ?? t("без стори")}
</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">
{t("авто-продолжений сегодня: {n} из {max}", { n: s.limitResumes, max: MAX_LIMIT_RESUMES_PER_DAY })}
</span>
{s.rotateReason === "limit" && <span className="block text-xs">{t("переключается на свободную подписку пула…")}</span>}
</p>
)}
{s.rotateReason === "threshold" && (
<p className="m-0 rounded-md border border-warn/40 bg-warn/10 px-3 py-2 text-sm">{t("Подписка подходит к лимиту — после этого хода переключится на свободную.")}</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">{t("Проект")}</dt>
<dd className="m-0">
<Key href={`/p/${s.projectKey}`}>{s.projectKey}</Key>
</dd>
<dt className="text-muted-foreground">{t("Агент")}</dt>
<dd className="m-0">{PROVIDER_NAMES[s.provider]} · {t("поколение {n}", { n: s.generation })}</dd>
<dt className="text-muted-foreground">{t("Подписка")}</dt>
<dd className="m-0">
<SubscriptionName s={s} fallback={t("подключена")} />
{s.subscriptionSwitches > 0 && <span className="text-muted-foreground"> · {t("переключений {n}", { n: s.subscriptionSwitches })}</span>}
</dd>
<dt className="text-muted-foreground">{t("Где")}</dt>
<dd className="m-0">
{s.host ? t("хост {name}", { name: s.host.name }) : t("Mac Peppa FACTORY")}
{s.container ? <span className="text-muted-foreground"> · {t("контейнер {name}", { name: s.container })}</span> : <span className="text-muted-foreground"> · {t("без изоляции")}</span>}
</dd>
<dt className="text-muted-foreground">{t("Запущен")}</dt>
<dd className="m-0">{ago(s.startedAt, t)}</dd>
<dt className="text-muted-foreground">{t("Активность")}</dt>
<dd className="m-0">{ago(s.lastActivityAt, t)}</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={t("Ждёт ответа")} count={questions.length}>
{questions.map((q) => (
<QuestionCard key={q.id} q={q} taskKey={s.taskKey} taskStatus={q.taskStatus} back={back} compact />
))}
</PanelSection>
)}
<PanelSection title={t("Что делает агент")}>
<AgentSteps key={s.id} sessionId={s.id} initial={steps} live={!finished} hooks={s.provider === "claude"} />
</PanelSection>
<PanelSection title={t("Терминал")}>
{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" />
{t("Сессия завершена — терминала больше нет.")}
</div>
) : (
<RunnerTerminal key={s.id} sessionId={s.id} live />
)}
</PanelSection>
{events.some((e) => e.type === "subscription_switched") && (
<PanelSection title={t("Переключения подписок")}>
<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, t)}</span> {switchText(e.payload, names, t)}
</li>
))}
</ol>
</PanelSection>
)}
{events.length > 0 && (
<PanelSection title={t("События")}>
<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, t)}</span> <span className="font-mono text-primary">{e.type}</span>{" "}
{eventLine(e, t)}
</li>
))}
</ol>
</PanelSection>
)}
</div>
);
}