This commit is contained in:
hupenglong1
2026-05-20 15:04:19 +08:00
parent c4b935692c
commit 1a94cec822
27 changed files with 4831 additions and 1693 deletions
@@ -0,0 +1,247 @@
"use client";
import { ExternalLinkIcon, FileIcon, RefreshCwIcon } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { MarkdownText } from "@/components/assistant-ui/markdown-text";
import { Button } from "@/components/ui/button";
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";
import { cn } from "@/lib/utils";
type StepDetail = {
step: string;
run_dic: number | null;
format: "markdown" | "jsonl" | "json" | "csv" | "text" | "empty";
content: string;
source_path: string | null;
fetched_at_ms: number;
error?: string;
tried_paths?: string[];
};
type Props = {
sessionId: string | null;
stepKey: string | null;
stepTitle?: string;
stepStatus?: string;
open: boolean;
onOpenChange: (open: boolean) => void;
};
export function StepDetailSheet({
sessionId,
stepKey,
stepTitle,
stepStatus,
open,
onOpenChange,
}: Props) {
const [detail, setDetail] = useState<StepDetail | null>(null);
const [loading, setLoading] = useState(false);
const [reloadCount, setReloadCount] = useState(0);
useEffect(() => {
if (!open || !sessionId || !stepKey) return;
let cancelled = false;
setLoading(true);
setDetail(null);
const url = `/api/claw/training/step-detail?session_id=${encodeURIComponent(sessionId)}&step=${encodeURIComponent(stepKey)}`;
fetch(url, { cache: "no-store" })
.then((res) => (res.ok ? res.json() : null))
.then((payload) => {
if (cancelled) return;
setDetail(payload);
setLoading(false);
})
.catch(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [open, sessionId, stepKey, reloadCount]);
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent
side="right"
className="flex w-[min(50rem,calc(100vw-2rem))] flex-col gap-0 p-0 sm:max-w-2xl"
>
<header className="flex shrink-0 items-start justify-between gap-3 border-b px-5 py-3">
<div className="min-w-0">
<div className="flex items-center gap-2">
<SheetTitle className="font-semibold text-base text-foreground">
{stepTitle ?? stepKey ?? "—"}
</SheetTitle>
{stepStatus ? <StatusPill status={stepStatus} /> : null}
{detail?.run_dic ? (
<span className="rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">
runDic={detail.run_dic}
</span>
) : null}
</div>
{detail?.source_path ? (
<div className="mt-1 flex items-center gap-1 truncate font-mono text-[11px] text-muted-foreground">
<FileIcon className="size-3 shrink-0" />
<span className="truncate">{detail.source_path}</span>
</div>
) : null}
</div>
<Button
type="button"
variant="ghost"
size="icon"
className="mt-0.5 size-7 shrink-0"
onClick={() => setReloadCount((c) => c + 1)}
title="刷新"
aria-label="刷新"
>
<RefreshCwIcon className="size-3.5" />
</Button>
</header>
<div className="min-h-0 flex-1 overflow-y-auto px-5 py-4 text-sm">
{loading ? (
<p className="text-muted-foreground text-xs">...</p>
) : !detail ? (
<p className="text-muted-foreground text-xs"></p>
) : detail.format === "empty" ? (
<EmptyView detail={detail} />
) : detail.format === "markdown" ? (
<MarkdownText text={detail.content} />
) : detail.format === "json" ? (
<JsonView text={detail.content} />
) : detail.format === "jsonl" ? (
<JsonLinesView text={detail.content} />
) : (
<RawView text={detail.content} />
)}
</div>
{detail?.source_path && !loading ? (
<footer className="flex shrink-0 items-center justify-between border-t bg-muted/30 px-5 py-2 text-[11px] text-muted-foreground">
<span>
{detail.format} ·{" "}
{detail.fetched_at_ms
? new Date(detail.fetched_at_ms).toLocaleTimeString()
: ""}
</span>
<button
type="button"
className="inline-flex items-center gap-1 hover:text-foreground"
onClick={() => {
if (detail.content) {
navigator.clipboard?.writeText(detail.content);
}
}}
>
<ExternalLinkIcon className="size-3" />
</button>
</footer>
) : null}
</SheetContent>
</Sheet>
);
}
function EmptyView({ detail }: { detail: StepDetail }) {
return (
<div className="space-y-3">
<p className="rounded-md border border-dashed border-muted-foreground/30 bg-muted/30 p-3 text-muted-foreground text-xs">
{detail.error ?? "暂无产物。"}
</p>
{detail.tried_paths && detail.tried_paths.length > 0 ? (
<div>
<div className="mb-1 text-[10px] font-medium tracking-wider text-muted-foreground uppercase">
</div>
<ul className="space-y-1 font-mono text-[11px]">
{detail.tried_paths.map((p) => (
<li key={p} className="text-muted-foreground">
{p}
</li>
))}
</ul>
</div>
) : null}
</div>
);
}
function JsonView({ text }: { text: string }) {
const pretty = useMemo(() => {
try {
return JSON.stringify(JSON.parse(text), null, 2);
} catch {
return text;
}
}, [text]);
return (
<pre className="overflow-x-auto rounded-md border bg-muted/30 p-3 font-mono text-[11px] leading-relaxed">
{pretty}
</pre>
);
}
function JsonLinesView({ text }: { text: string }) {
const lines = useMemo(
() =>
text
.split("\n")
.map((l) => l.trim())
.filter(Boolean)
.map((l) => {
try {
return JSON.stringify(JSON.parse(l), null, 2);
} catch {
return l;
}
}),
[text],
);
return (
<div className="space-y-2">
<div className="text-[10px] text-muted-foreground">{lines.length} </div>
{lines.map((l, idx) => (
<details
key={idx}
open={idx === 0}
className="rounded-md border bg-muted/20"
>
<summary className="cursor-pointer px-3 py-1.5 font-mono text-[11px] text-muted-foreground hover:bg-muted/40">
#{idx + 1}
</summary>
<pre className="overflow-x-auto px-3 pt-0 pb-2 font-mono text-[11px] leading-relaxed">
{l}
</pre>
</details>
))}
</div>
);
}
function RawView({ text }: { text: string }) {
return (
<pre className="overflow-x-auto whitespace-pre-wrap break-all font-mono text-[11px] leading-relaxed">
{text}
</pre>
);
}
function StatusPill({ status }: { status: string }) {
const map: Record<string, string> = {
complete: "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300",
running: "bg-sky-500/20 text-sky-700 dark:text-sky-200",
pending: "bg-muted text-muted-foreground",
failed: "bg-rose-500/15 text-rose-700 dark:text-rose-300",
cancelled: "bg-muted text-muted-foreground",
};
return (
<span
className={cn(
"rounded-full px-2 py-0.5 text-[10px] font-medium tracking-wider",
map[status] ?? "bg-muted text-muted-foreground",
)}
>
{status.toUpperCase()}
</span>
);
}
@@ -0,0 +1,60 @@
"use client";
import { GitBranchIcon } from "lucide-react";
import { cn } from "@/lib/utils";
type Props = {
sessionId: string | null;
isTraining: boolean;
onChange: (next: boolean) => void;
disabled?: boolean;
lockedReason?: string;
};
export function TrainingModeToggle({
sessionId,
isTraining,
onChange,
disabled,
lockedReason,
}: Props) {
const isDisabled = disabled || !sessionId;
const tooltip = !sessionId
? "发送首条消息后开启"
: lockedReason
? lockedReason
: "切换训练模式";
return (
<button
type="button"
disabled={isDisabled}
onClick={() => onChange(!isTraining)}
title={tooltip}
aria-pressed={isTraining}
className={cn(
"inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs transition-colors",
"disabled:cursor-not-allowed disabled:opacity-50",
isTraining
? "border-amber-300 bg-amber-50 text-amber-800 hover:bg-amber-100"
: "border-border bg-background text-foreground hover:bg-muted",
)}
>
<GitBranchIcon className="size-3.5" />
<span></span>
<span
className={cn(
"ml-1 inline-flex h-3.5 w-7 shrink-0 items-center rounded-full transition-colors",
isTraining ? "bg-amber-400" : "bg-muted",
)}
>
<span
className={cn(
"inline-block size-3 rounded-full bg-background shadow-sm transition-transform",
isTraining ? "translate-x-3.5" : "translate-x-0.5",
)}
/>
</span>
</button>
);
}
@@ -0,0 +1,480 @@
"use client";
import {
BarChart3Icon,
CheckIcon,
ChevronDownIcon,
ClipboardListIcon,
ClockIcon,
DnaIcon,
ExternalLinkIcon,
FileTextIcon,
FlaskConicalIcon,
GitBranchIcon,
GraduationCapIcon,
HourglassIcon,
Loader2Icon,
MicroscopeIcon,
type LucideIcon,
RefreshCwIcon,
ShieldCheckIcon,
TrendingUpIcon,
} from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { StepDetailSheet } from "@/components/training/step-detail-sheet";
import { cn } from "@/lib/utils";
type CardStatus = "pending" | "running" | "complete" | "failed" | "cancelled";
type PhaseTone = "complete" | "running" | "pending";
type PipelineCard = {
key: string;
icon?: string;
title: string;
subtitle: string;
status: CardStatus;
progress?: number;
};
type PipelinePhase = {
key: string;
label: string;
tone: PhaseTone;
cards: PipelineCard[];
};
type Kpi = {
label: string;
value: string;
icon?: string;
};
type LogLine = {
ts: string;
iter: string | number;
text: string;
};
type PipelinePayload = {
session_id: string;
generated_at_ms: number;
status: { mode: string; state: CardStatus };
kpis: Kpi[];
phases: PipelinePhase[];
logs: LogLine[];
};
const ICON_MAP: Record<string, LucideIcon> = {
"bar-chart": BarChart3Icon,
microscope: MicroscopeIcon,
"trending-up": TrendingUpIcon,
"file-text": FileTextIcon,
dna: DnaIcon,
"git-branch": GitBranchIcon,
flask: FlaskConicalIcon,
shield: ShieldCheckIcon,
"graduation-cap": GraduationCapIcon,
"clipboard-list": ClipboardListIcon,
"refresh-cw": RefreshCwIcon,
clock: ClockIcon,
hourglass: HourglassIcon,
};
export function TrainingPipelinePanel({
sessionId,
}: {
sessionId: string | null;
}) {
const [data, setData] = useState<PipelinePayload | null>(null);
const [loading, setLoading] = useState(false);
const [openCard, setOpenCard] = useState<{
key: string;
title: string;
status: string;
} | null>(null);
useEffect(() => {
setLoading(true);
const url = sessionId
? `/api/claw/training/pipeline/stream?session_id=${encodeURIComponent(sessionId)}`
: "/api/claw/training/pipeline/stream";
const es = new EventSource(url);
es.onmessage = (ev) => {
try {
const payload = JSON.parse(ev.data);
// program.md missing → backend pushes {available: false}; clear panel.
if (payload && payload.available === false) {
setData(null);
} else {
setData(payload);
}
setLoading(false);
} catch {
/* ignore malformed events */
}
};
es.onerror = () => {
// EventSource auto-reconnects; just stop showing the loading state.
setLoading(false);
};
return () => {
es.close();
};
}, [sessionId]);
return (
<div className="flex min-w-0 flex-1 flex-col overflow-hidden border-r bg-muted/20">
<div className="min-h-0 flex-1 overflow-y-auto px-6 py-5">
<HeaderRow status={data?.status ?? null} loading={loading} />
<KpiRow kpis={data?.kpis ?? []} />
<div className="mt-5 space-y-4">
{!data ? (
<div className="rounded-md border border-dashed p-8 text-center text-muted-foreground text-xs">
pipeline
</div>
) : (
data.phases.map((phase) => (
<PhaseSection
key={phase.key}
phase={phase}
onCardClick={(card) =>
setOpenCard({
key: card.key,
title: card.title,
status: card.status,
})
}
/>
))
)}
</div>
</div>
<LogStream logs={data?.logs ?? []} />
<StepDetailSheet
sessionId={sessionId}
stepKey={openCard?.key ?? null}
stepTitle={openCard?.title}
stepStatus={openCard?.status}
open={openCard !== null}
onOpenChange={(next) => {
if (!next) setOpenCard(null);
}}
/>
</div>
);
}
function HeaderRow({
status,
loading,
}: {
status: PipelinePayload["status"] | null;
loading: boolean;
}) {
const statusLabel = loading
? "加载中"
: status
? `${status.mode} · ${statusText(status.state)}`
: "暂无运行";
const isRunning = status?.state === "running";
return (
<header className="flex items-center justify-between gap-3">
<div className="flex items-center gap-2">
<MicroscopeIcon className="size-5 text-muted-foreground" />
<h2 className="font-semibold text-sm uppercase tracking-[0.2em] text-foreground/90">
Training Pipeline Monitor
</h2>
</div>
<div
className={cn(
"flex items-center gap-1.5 rounded-full border bg-emerald-500/10 px-3 py-1 text-emerald-700 text-xs dark:text-emerald-300",
isRunning
? "animate-pipeline-pill-glow border-emerald-400"
: "border-emerald-500/40",
)}
>
<span className="relative inline-flex size-2 items-center justify-center">
<span
className={cn(
"size-2 rounded-full",
isRunning
? "bg-emerald-500"
: status?.state === "complete"
? "bg-emerald-500"
: status?.state === "failed"
? "bg-rose-500"
: "bg-muted-foreground",
)}
/>
{isRunning ? (
<span className="pointer-events-none absolute inset-0 animate-pipeline-dot-ping rounded-full bg-emerald-400" />
) : null}
</span>
<span className="font-medium">{statusLabel}</span>
</div>
</header>
);
}
function KpiRow({ kpis }: { kpis: Kpi[] }) {
if (!kpis.length) {
return null;
}
return (
<div className="mt-4 grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-7">
{kpis.map((kpi) => {
const Icon = kpi.icon ? ICON_MAP[kpi.icon] : null;
return (
<div
key={kpi.label}
className="rounded-lg border bg-background px-3 py-2 min-h-[58px]"
>
<div className="text-[10px] font-medium tracking-wider text-muted-foreground truncate">
{kpi.label}
</div>
<div className="mt-0.5 flex items-start gap-1.5 font-mono text-sm leading-tight text-foreground">
<span className="break-all line-clamp-2">{kpi.value}</span>
{Icon ? (
<Icon className="size-3.5 shrink-0 text-muted-foreground mt-0.5" />
) : null}
</div>
</div>
);
})}
</div>
);
}
function PhaseSection({
phase,
onCardClick,
}: {
phase: PipelinePhase;
onCardClick?: (card: PipelineCard) => void;
}) {
const dotCls =
phase.tone === "complete"
? "bg-emerald-500"
: phase.tone === "running"
? "bg-sky-500"
: "bg-violet-500";
const arrowComplete = phase.tone === "complete";
return (
<section className="rounded-xl border bg-background/60 p-4">
<div className="mb-3 flex items-center justify-between">
<div className="flex items-center gap-2">
<span className={cn("size-2 rounded-full", dotCls)} />
<span className="font-medium text-foreground text-sm">
{phase.label}
</span>
</div>
<ChevronDownIcon className="size-4 text-muted-foreground/60" />
</div>
<div className="flex flex-wrap items-stretch gap-2">
{phase.cards.map((card, idx) => (
<div key={card.key} className="flex items-stretch gap-2">
<PipelineCardView
card={card}
onClick={onCardClick ? () => onCardClick(card) : undefined}
/>
{idx < phase.cards.length - 1 ? (
<PhaseArrow complete={arrowComplete} />
) : null}
</div>
))}
</div>
</section>
);
}
function PhaseArrow({ complete }: { complete: boolean }) {
return (
<div className="flex items-center px-1">
<svg
width="32"
height="14"
viewBox="0 0 32 14"
fill="none"
className={cn(
complete ? "text-emerald-500" : "text-muted-foreground/40",
)}
aria-hidden
>
<line
x1="0"
y1="7"
x2="22"
y2="7"
stroke="currentColor"
strokeWidth="1.5"
strokeDasharray={complete ? "3 3" : "0"}
/>
<path
d="M22 2 L30 7 L22 12 Z"
fill="currentColor"
stroke="none"
/>
</svg>
</div>
);
}
function PipelineCardView({
card,
onClick,
}: {
card: PipelineCard;
onClick?: () => void;
}) {
const isRunning = card.status === "running";
const isComplete = card.status === "complete";
const Icon = card.icon ? ICON_MAP[card.icon] : null;
const tone = isComplete
? "border-emerald-500/40 bg-emerald-50/40 dark:bg-emerald-950/20"
: isRunning
? "border-sky-400 bg-sky-50/60 dark:bg-sky-950/30 ring-2 ring-sky-300/50 dark:ring-sky-500/30 animate-pipeline-running-blue"
: card.status === "failed"
? "border-rose-500/40 bg-rose-50/40 dark:bg-rose-950/20"
: "border-border bg-background";
const Tag = onClick ? "button" : "div";
return (
<Tag
type={onClick ? "button" : undefined}
onClick={onClick}
className={cn(
"relative flex w-48 flex-col rounded-xl border px-3 pt-3 pb-2.5 text-left transition-colors",
tone,
onClick &&
"cursor-pointer hover:brightness-105 hover:shadow-sm focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-400",
)}
>
<div className="mb-2 flex items-start">
{isComplete ? (
<div className="flex size-5 items-center justify-center rounded-full bg-emerald-500 text-white">
<CheckIcon className="size-3" strokeWidth={3} />
</div>
) : (
<StatusBadge status={card.status} />
)}
</div>
<div className="flex items-center gap-1.5">
{Icon ? (
<Icon
className={cn(
"size-4 shrink-0",
isComplete
? "text-emerald-600 dark:text-emerald-400"
: isRunning
? "text-sky-600 dark:text-sky-400"
: "text-muted-foreground",
)}
/>
) : null}
<span
className={cn(
"font-medium text-sm leading-tight",
isRunning ? "text-foreground" : "",
card.status === "pending" ? "text-muted-foreground" : "",
)}
>
{card.title}
</span>
</div>
<span className="mt-0.5 truncate font-mono text-[11px] text-muted-foreground">
{card.subtitle}
</span>
</Tag>
);
}
function StatusBadge({ status }: { status: CardStatus }) {
const map: Record<CardStatus, { label: string; cls: string }> = {
complete: {
label: "DONE",
cls: "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300",
},
running: {
label: "RUNNING",
cls: "bg-sky-500/20 text-sky-700 dark:text-sky-200",
},
pending: {
label: "PENDING",
cls: "bg-muted text-muted-foreground",
},
failed: {
label: "FAILED",
cls: "bg-rose-500/15 text-rose-700 dark:text-rose-300",
},
cancelled: {
label: "CANCELLED",
cls: "bg-muted text-muted-foreground",
},
};
const { label, cls } = map[status];
return (
<span
className={cn(
"inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[9px] font-semibold tracking-wider",
cls,
)}
>
{status === "running" ? (
<Loader2Icon className="size-2.5 animate-spin" />
) : null}
{label}
</span>
);
}
function LogStream({ logs }: { logs: LogLine[] }) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (ref.current) ref.current.scrollTop = ref.current.scrollHeight;
}, [logs]);
return (
<div className="flex h-72 shrink-0 flex-col border-t bg-zinc-950 px-5 py-3">
<div className="mb-2 flex shrink-0 items-center justify-between">
<span className="font-semibold text-xs uppercase tracking-[0.18em] text-zinc-300">
Live Log
</span>
<button
type="button"
className="inline-flex items-center gap-1 text-[11px] text-zinc-400 transition-colors hover:text-zinc-200"
>
<ExternalLinkIcon className="size-3" />
</button>
</div>
<div
ref={ref}
className="min-h-0 flex-1 overflow-y-auto font-mono text-[12px] leading-6 text-zinc-100"
>
{logs.length === 0 ? (
<div className="text-zinc-500"></div>
) : (
logs.map((line, idx) => (
<div key={idx} className="flex gap-3">
<span className="text-zinc-500">{line.ts}</span>
<span className="text-emerald-400">[iter={line.iter}]</span>
<span>{line.text}</span>
</div>
))
)}
</div>
</div>
);
}
function statusText(state: CardStatus) {
const map: Record<CardStatus, string> = {
running: "Running",
complete: "Complete",
failed: "Failed",
pending: "Idle",
cancelled: "Cancelled",
};
return map[state];
}