// 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("остановлена · продолжит в")}
>
);
}
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 (
{s.taskKey ?? s.projectKey}
{s.taskTitle ?? s.name ?? t("без стори")}
{limited ? (
<>
{t(st.label)}
>
) : (
t(st.label)
)}
{s.name && s.taskTitle ? `${s.name} · ` : ""}{s.projectKey} · {s.provider}{s.subscriptionSwitches > 0 ? ` (↻${s.subscriptionSwitches})` : ""} · #{s.id} · {s.tmuxName}
{ago(s.lastActivityAt, t)}
{limited && (
)}
);
}
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 (
{/* Picked from the list: on narrow screens the panel is under it, scroll there. */}
{chosen &&
}
#{s.id}
{s.taskKey && {s.taskKey}}
{s.taskTitle ?? s.name ?? t("без стори")}
{s.name && s.taskTitle && {s.name}
}
{/* PEP-5: tokens, cost, context of this runner. */}
{s.status === "rate_limited" && (
{t("авто-продолжений сегодня: {n} из {max}", { n: s.limitResumes, max: MAX_LIMIT_RESUMES_PER_DAY })}
{s.rotateReason === "limit" && {t("переключается на свободную подписку пула…")}}
)}
{s.rotateReason === "threshold" && (
{t("Подписка подходит к лимиту — после этого хода переключится на свободную.")}
)}
- {t("Проект")}
-
{s.projectKey}
- {t("Агент")}
- {PROVIDER_NAMES[s.provider]} · {t("поколение {n}", { n: s.generation })}
- {t("Подписка")}
-
{s.subscriptionSwitches > 0 && · {t("переключений {n}", { n: s.subscriptionSwitches })}}
- {t("Где")}
-
{s.host ? t("хост {name}", { name: s.host.name }) : t("Mac FORGE")}
{s.container ? · {t("контейнер {name}", { name: s.container })} : · {t("без изоляции")}}
- {t("Запущен")}
- {ago(s.startedAt, t)}
- {t("Активность")}
- {ago(s.lastActivityAt, t)}
{stories &&
}
{questions.length > 0 && (
{questions.map((q) => (
))}
)}
{finished ? (
{t("Сессия завершена — терминала больше нет.")}
) : (
)}
{events.some((e) => e.type === "subscription_switched") && (
{events
.filter((e) => e.type === "subscription_switched")
.map((e) => (
-
{ago(e.createdAt, t)} {switchText(e.payload, names, t)}
))}
)}
{events.length > 0 && (
{events.map((e) => (
-
{ago(e.createdAt, t)} {e.type}{" "}
{eventLine(e, t)}
))}
)}
);
}