peppa/apps/web/components/AgentSteps.tsx

110 lines
4.9 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.

"use client";
import { useEffect, useState } from "react";
import { Bot, FilePen, FileText, FlaskConical, Globe, Plug, Search, SquareTerminal, Wrench, type LucideIcon } from "lucide-react";
import type { StepKind, StepView } from "@peppa/core";
import { cn } from "@/lib/utils";
import { useLive } from "@/lib/live";
import { useT } from "@/components/I18n";
import { m, type Translator } from "@peppa/shared/i18n";
const KIND: Record<StepKind, { icon: LucideIcon; label: string }> = {
command: { icon: SquareTerminal, label: m("команда") },
test: { icon: FlaskConical, label: m("тест") },
edit: { icon: FilePen, label: m("правка") },
read: { icon: FileText, label: m("чтение") },
search: { icon: Search, label: m("поиск") },
web: { icon: Globe, label: m("веб") },
agent: { icon: Bot, label: m("субагент") },
mcp: { icon: Plug, label: "MCP" },
other: { icon: Wrench, label: m("инструмент") },
};
// PEP-154: a step for the «Продакт» view — what the agent does, in words: no command, file name or path.
const STEP_PLAIN: Record<StepKind, string> = {
command: m("Выполняет действие в проекте"),
test: m("Запускает проверки"),
edit: m("Вносит изменения"),
read: m("Изучает проект"),
search: m("Ищет нужное в проекте"),
web: m("Смотрит в интернете"),
agent: m("Поручил часть работы помощнику"),
mcp: m("Сверяется с задачей"),
other: m("Работает над задачей"),
};
const KEEP = 30;
function since(iso: string, now: number, t: Translator): string {
const s = Math.max(0, Math.round((now - Date.parse(iso)) / 1000));
if (s < 60) return t("{n} с", { n: s });
if (s < 3600) return t("{n} мин", { n: Math.floor(s / 60) });
return t("{n} ч", { n: Math.floor(s / 3600) });
}
/**
* What the agent is doing now (PEP-33): its latest tool calls, newest first. Initial steps
* come from the server, new ones from the live channel (PEP-37, `steps:<sessionId>`).
*/
export function AgentSteps({ sessionId, initial, live, hooks = true, plain = false }: { sessionId: number; initial: StepView[]; live: boolean; hooks?: boolean; /** PEP-154: «Продакт» — what the agent does in words, no commands, file names or paths. */ plain?: boolean }) {
const [steps, setSteps] = useState(initial);
const [now, setNow] = useState(() => Date.now());
const t = useT();
useEffect(() => setSteps((cur) => merge(initial, cur)), [initial]);
// The «N с назад» clock only (no data is fetched on it).
useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), 10_000);
return () => clearInterval(timer);
}, []);
// PEP-225: new steps over the tab's live channel; a hidden tab drops them and catches up on return.
useLive(
live ? `steps:${sessionId}` : null,
(e) => {
if (e.type !== "step") return;
setSteps((cur) => merge([e.step as unknown as StepView], cur));
setNow(Date.now());
},
{ heavy: true },
);
if (!steps.length)
return (
<p className="m-0 rounded-md border border-dashed px-3 py-2 text-xs text-muted-foreground">
{hooks ? (live ? t("Агент ещё ничего не сделал — шаги появятся здесь.") : t("Шагов не записано.")) : plain ? t("Этот агент не сообщает о шагах.") : t("Этот агент не сообщает шаги (нет хуков) — смотри терминал.")}
</p>
);
return (
<ol aria-label={t("Шаги агента")} className="m-0 flex max-h-72 list-none flex-col gap-0.5 overflow-auto p-0">
{steps.map((s, i) => {
const k = KIND[s.kind] ?? KIND.other;
const Icon = k.icon;
return (
<li key={s.id} className={cn("flex items-center gap-2 rounded px-1.5 py-1 text-xs", i === 0 && live && "bg-info/10")}>
<Icon className={cn("size-3.5 shrink-0", s.ok ? "text-muted-foreground" : "text-destructive")} aria-label={t(k.label)} />
{plain ? (
<span className={cn("min-w-0 flex-1 truncate", !s.ok && "text-destructive")}>{t(STEP_PLAIN[s.kind] ?? STEP_PLAIN.other)}</span>
) : (
<span className={cn("min-w-0 flex-1 truncate font-mono", !s.ok && "text-destructive")} title={`${s.tool}: ${s.text}`}>
{s.text}
</span>
)}
{!s.ok && <span className="shrink-0 text-[10px] text-destructive">{t("ошибка")}</span>}
<span className="shrink-0 font-mono text-[10px] text-muted-foreground tabular-nums">{since(s.at, now, t)}</span>
</li>
);
})}
</ol>
);
}
function merge(add: StepView[], cur: StepView[]): StepView[] {
const seen = new Set<number>();
return [...add, ...cur]
.filter((s) => !seen.has(s.id) && (seen.add(s.id), true))
.sort((a, b) => b.id - a.id)
.slice(0, KEEP);
}