// A full episode of the math / AgentGym records.
// Thread: the lead's conversation as a channel, each teammate as a thread opened in a side pane (as in Slack).
// GameReview: the environment actions as a move list beside the current state, with the score below (as in lichess).
import { useEffect, useMemo, useRef, useState } from "react";
import { LineChart } from "./Charts";
import { normMsg, type RecAgent, type RecEpisode } from "./records";
import type { Message } from "./types";
const initial = (a: RecAgent) => (a.role === "lead" ? "L" : (a.label || a.id)[0].toUpperCase());
const parse = (s: string) => { try { return JSON.parse(s); } catch { return null; } };
const one = (s: string) => (s || "").trim().split("\n", 1)[0];
function Clamp({ text, lines, className }: { text: string; lines: number; className: string }) {
const [open, setOpen] = useState(false);
const long = text.split("\n").length > lines || text.length > lines * 110;
return (
<>
{text}
{long && setOpen(!open)}>{open ? "收起" : "展开"} }
>
);
}
function ToolCall({ name, args, result }: { name: string; args: string; result?: Message }) {
const [open, setOpen] = useState(false);
const a = parse(args);
const cmd = name === "bash" ? String(a?.command ?? args) : a && typeof a === "object"
? Object.entries(a).map(([k, v]) => `${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`).join("\n") : args;
return (
setOpen(!open)}>
{name} {one(cmd)}
{result && {open ? "收起" : "看输出"} }
{open && <>
{cmd.includes("\n") &&
{cmd} }
{result &&
{result.content || "(无输出)"} }
>}
);
}
function MessageView({ m, agent, results, threads, onThread, openThread, firstUser }: {
m: Message; agent: RecAgent; firstUser: boolean; results: Map; threads: RecAgent[]; onThread: (id: string) => void; openThread: string | null;
}) {
if (m.role === "tool") return null;
if (m.role === "system" || m.role === "user") return (
{m.role === "system" ? "S" : "任"}
{m.role === "system" ? "系统提示" : firstUser ? "任务" : "运行环境插入的消息"}
);
return (
{initial(agent)}
{agent.label || agent.id}
{m.reasoning &&
}
{m.content &&
}
{m.tool_calls.map((tc) =>
)}
{threads.map((t) => (
onThread(t.id)}>
{initial(t)}
{t.label || t.id} {t.messages.filter((x) => x.role === "assistant").length} 条回复
{openThread === t.id ? "正在看" : "查看话题 ›"}
))}
);
}
function Conversation({ agent, all, openThread, onThread }: { agent: RecAgent; all: RecAgent[]; openThread: string | null; onThread: (id: string) => void }) {
const msgs = useMemo(() => agent.messages.map((m) => normMsg(m)), [agent]);
const results = useMemo(() => new Map(msgs.filter((m) => m.role === "tool" && m.tool_call_id).map((m) => [m.tool_call_id, m])), [msgs]);
const threadsAt = (i: number) => agent.spawns.filter((s) => s.message === i).map((s) => all.find((a) => a.id === s.agent)).filter((a): a is RecAgent => !!a);
const firstUser = msgs.findIndex((m) => m.role === "user");
return <>{msgs.map((m, i) => )}>;
}
export default function Thread({ ep }: { ep: RecEpisode }) {
const lead = ep.agents.find((a) => a.role === "lead") ?? ep.agents[0];
const [open, setOpen] = useState(null);
const mate = ep.agents.find((a) => a.id === open);
const orphan = ep.agents.filter((a) => a !== lead && !lead.spawns.some((s) => s.agent === a.id));
useEffect(() => setOpen(null), [ep]);
return (
# lead {lead.messages.length} 条消息{ep.agents.length > 1 ? ` · ${ep.agents.length - 1} 个队友,点「查看话题」看队友那边` : ""}
setOpen(open === id ? null : id)} />
{orphan.length > 0 && (
+
没对上派出时间的队友
{orphan.map((t) =>
setOpen(t.id)}>{initial(t)} {t.label || t.id} 查看话题 › )}
)}
{mate && (
话题 · {mate.label || mate.id} {mate.reward != null ? `得分 ${mate.reward}` : ""}
setOpen(null)}>✕
{}} />
)}
);
}
// ---------- game review ----------
export function GameReview({ ep }: { ep: RecEpisode }) {
const steps = ep.env_steps;
const [k, setK] = useState(0);
const list = useRef(null);
useEffect(() => setK(0), [ep]);
useEffect(() => {
const f = (e: KeyboardEvent) => {
if ((e.target as HTMLElement)?.tagName === "INPUT" || (e.target as HTMLElement)?.tagName === "SELECT") return;
if (e.key === "ArrowRight" || e.key === "ArrowDown") { setK((x) => Math.min(steps.length - 1, x + 1)); e.preventDefault(); }
if (e.key === "ArrowLeft" || e.key === "ArrowUp") { setK((x) => Math.max(0, x - 1)); e.preventDefault(); }
if (e.key === "Home") setK(0);
if (e.key === "End") setK(steps.length - 1);
};
addEventListener("keydown", f); return () => removeEventListener("keydown", f);
}, [steps.length]);
useEffect(() => { list.current?.querySelector(`[data-k="${k}"]`)?.scrollIntoView({ block: "nearest" }); }, [k]);
// carry the last known score forward, so the bar and the curve exist at every move
const scores = useMemo(() => { let last: number | null = null; return steps.map((s) => (s.score != null ? (last = s.score) : last)); }, [steps]);
const cur = steps[k];
const sc = scores[k];
const label = (a: string) => ep.agents.find((x) => x.id === a)?.label || a;
const tgt = (t: string) => (t === "main" ? "主局" : t.replace(/^copy-?/, "副本 "));
const maxScore = Math.max(1, ...scores.filter((x): x is number => x != null));
return (
环境 第 {k + 1} / {steps.length} 步 · ← → 逐步
{sc == null ? "–" : sc.toFixed(2)}
{cur && <>
{tgt(cur.target)} {label(cur.agent)}
{cur.action}
环境返回
{cur.observation || "(无)"}
>}
任务原文 {ep.instruction}
动作 主局是正式的一局,副本是试走用的拷贝
setK(0)}>⏮ setK(Math.max(0, k - 1))}>‹
setK(Math.min(steps.length - 1, k + 1))}>› setK(steps.length - 1)}>⏭
{steps.map((s, i) => {
const d = scores[i] != null && (i === 0 ? scores[i]! : scores[i]! - (scores[i - 1] ?? 0));
return (
setK(i)}>
{i + 1}
{tgt(s.target)}
{s.action}
{typeof d === "number" && d !== 0 && 0 ? "up" : "down")}>{d > 0 ? "+" : ""}{d.toFixed(2)} }
);
})}
得分随步数 点曲线上的一步跳过去
{}}>
i + 1)} series={[{ name: "得分", color: "var(--orch)", values: new Map(scores.map((v, i) => [i + 1, v])) }]}
fmt={(v) => v.toFixed(2)} height={170} hover={k + 1} onHover={(x) => { if (x != null) setK(x - 1); }} />
);
}