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,26 @@
import { getCurrentAccount } from "@/lib/claw-auth";
const CLAW_API_URL = process.env.CLAW_API_URL ?? "http://127.0.0.1:8765";
export async function GET(request: Request) {
const account = await getCurrentAccount();
if (!account) return Response.json({ error: "unauthorized" }, { status: 401 });
const incoming = new URL(request.url);
const sessionId = incoming.searchParams.get("session_id") ?? "";
const url = new URL(`${CLAW_API_URL}/api/training/pipeline`);
url.searchParams.set("account_id", account.id);
if (sessionId) url.searchParams.set("session_id", sessionId);
const response = await fetch(url, { cache: "no-store" });
const payload = await response.text();
return new Response(payload, {
status: response.status,
headers: {
"content-type":
response.headers.get("content-type") ?? "application/json",
"cache-control": "no-store",
},
});
}
@@ -0,0 +1,38 @@
import { getCurrentAccount } from "@/lib/claw-auth";
const CLAW_API_URL = process.env.CLAW_API_URL ?? "http://127.0.0.1:8765";
export const dynamic = "force-dynamic";
export async function GET(request: Request) {
const account = await getCurrentAccount();
if (!account) {
return new Response("unauthorized", { status: 401 });
}
const incoming = new URL(request.url);
const sessionId = incoming.searchParams.get("session_id") ?? "";
const url = new URL(`${CLAW_API_URL}/api/training/pipeline/stream`);
url.searchParams.set("account_id", account.id);
if (sessionId) url.searchParams.set("session_id", sessionId);
const upstream = await fetch(url, {
cache: "no-store",
signal: request.signal,
});
if (!upstream.body) {
return new Response("upstream has no body", { status: 502 });
}
return new Response(upstream.body, {
status: upstream.status,
headers: {
"content-type": "text/event-stream",
"cache-control": "no-store",
connection: "keep-alive",
"x-accel-buffering": "no",
},
});
}
@@ -0,0 +1,34 @@
import { getCurrentAccount } from "@/lib/claw-auth";
const CLAW_API_URL = process.env.CLAW_API_URL ?? "http://127.0.0.1:8765";
export async function GET(request: Request) {
const account = await getCurrentAccount();
if (!account) return Response.json({ error: "unauthorized" }, { status: 401 });
const incoming = new URL(request.url);
const sessionId = incoming.searchParams.get("session_id") ?? "";
const step = incoming.searchParams.get("step") ?? "";
if (!sessionId || !step) {
return Response.json(
{ error: "session_id and step are required" },
{ status: 400 },
);
}
const url = new URL(`${CLAW_API_URL}/api/training/step-detail`);
url.searchParams.set("account_id", account.id);
url.searchParams.set("session_id", sessionId);
url.searchParams.set("step", step);
const response = await fetch(url, { cache: "no-store" });
const payload = await response.text();
return new Response(payload, {
status: response.status,
headers: {
"content-type":
response.headers.get("content-type") ?? "application/json",
"cache-control": "no-store",
},
});
}
+197 -8
View File
@@ -1,16 +1,18 @@
"use client";
import type { ExportedMessageRepository } from "@assistant-ui/core";
import { AssistantRuntimeProvider } from "@assistant-ui/react";
import { AssistantRuntimeProvider, useAuiState } from "@assistant-ui/react";
import {
AssistantChatTransport,
useChatRuntime,
} from "@assistant-ui/react-ai-sdk";
import type { UIMessage } from "ai";
import { useCallback, useEffect, useMemo, useRef } from "react";
import { PanelRightOpenIcon, XIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ActivityPanel,
ActivityProvider,
useActivityPanel,
} from "@/components/assistant-ui/activity-panel";
import { Thread } from "@/components/assistant-ui/thread";
import {
@@ -18,18 +20,26 @@ import {
toReplayRepository,
} from "@/components/assistant-ui/thread-list";
import { ThreadListSidebar } from "@/components/assistant-ui/threadlist-sidebar";
import { TrainingPipelinePanel } from "@/components/training/training-pipeline-panel";
import { Button } from "@/components/ui/button";
import {
SidebarInset,
SidebarProvider,
SidebarTrigger,
} from "@/components/ui/sidebar";
import {
ACTIVE_SESSION_CHANGED_EVENT,
readActiveSessionId,
readPendingWorkspaceSessionId,
writeActiveSessionId,
} from "@/lib/claw-active-session";
import { ClawSessionReplayProvider } from "@/lib/claw-session-replay";
import { pushSessionUrl } from "@/lib/claw-session-url";
import { cn } from "@/lib/utils";
import {
useAppliedTraining,
useModelIterationEnabled,
} from "@/lib/use-training-mode";
import { ClawAccountGate, useClawAccount } from "./claw-account-gate";
type AssistantProps = {
@@ -153,12 +163,7 @@ export const Assistant = ({ initialSessionId }: AssistantProps = {}) => {
onLogout={() => setAccount(null)}
/>
<SidebarInset>
<div className="flex min-h-0 flex-1 overflow-hidden">
<div className="min-w-0 flex-1 overflow-hidden">
<Thread />
</div>
<ActivityPanel />
</div>
<AssistantWorkspace />
</SidebarInset>
</div>
</SidebarProvider>
@@ -168,6 +173,190 @@ export const Assistant = ({ initialSessionId }: AssistantProps = {}) => {
);
};
// 用户在对话里表达「我要开始/进行模型训练(这一轮迭代)」时命中的关键短语。
// 要求动词或专属触发词必须存在;避免 "什么是模型训练" 之类无意义匹配。
const APPLY_INTENT_PATTERNS: RegExp[] = [
// 触发短语:开始,xxx / 开始, xxx
/(?:^|\s|[,。.!?])开始\s*[,]\s*\S+/,
// 单纯训练动作:进行/开始/启动/开启/执行/发起/做 + (模型) + 训练
/(?:进行|开始|启动|开启|执行|发起|做)\s*(?:模型)?\s*训练/i,
// 训练 + 目标集合
/训练[\s\S]{0,60}?(?:目标集合|需求集合|specific[\s_-]?test|集合)/i,
// 跟着 program.md 的旧表达保留
/(?:应用|加载|载入|启用|装载|使用|跑|按照?|根据|用)\s*\S*program\.?md/i,
/program\.?md[\s\S]{0,120}?(?:训练|应用|启用|跑起来|跑一下)/i,
/apply\s+program(?:\.md)?/i,
/load\s+program(?:\.md)?/i,
/(?:start|begin|run)\s+(?:the\s+)?training/i,
];
function detectApplyIntent(text: string): boolean {
return APPLY_INTENT_PATTERNS.some((re) => re.test(text));
}
function AssistantWorkspace() {
const [activeSessionId, setActiveSessionId] = useState<string | null>(() =>
readActiveSessionId(),
);
const skill = useModelIterationEnabled();
const { applied, setApplied } = useAppliedTraining(activeSessionId);
const { close: closeActivityPanel } = useActivityPanel();
const showPipeline = skill.enabled && applied;
const messages = useAuiState((s) => s.thread.messages);
const lastProcessedUserMsgId = useRef<string | null>(null);
useEffect(() => {
const update = () => setActiveSessionId(readActiveSessionId());
const handleChanged = (event: Event) => {
const detail = (event as CustomEvent<{ sessionId?: string | null }>)
.detail;
setActiveSessionId(detail?.sessionId ?? readActiveSessionId());
};
window.addEventListener(ACTIVE_SESSION_CHANGED_EVENT, handleChanged);
window.addEventListener("focus", update);
update();
return () => {
window.removeEventListener(ACTIVE_SESSION_CHANGED_EVENT, handleChanged);
window.removeEventListener("focus", update);
};
}, []);
useEffect(() => {
closeActivityPanel();
}, [showPipeline, closeActivityPanel]);
// Skill 关掉时撤销 applied,避免重新启用就立刻弹开。
useEffect(() => {
if (!skill.enabled && applied) {
setApplied(false);
}
}, [skill.enabled, applied, setApplied]);
// 自动应用:skill 启用 + 当前 session 后端的 pipeline 已经有进展(任何
// 卡 running 或 complete)→ applied=true。这样关 tab 重开 / 刷新 / 切回
// 已在跑的会话都能自动恢复 monitor 面板,不依赖触发词。
useEffect(() => {
if (!skill.enabled) return;
if (applied) return;
if (!activeSessionId) return;
let cancelled = false;
const url = `/api/claw/training/pipeline?session_id=${encodeURIComponent(activeSessionId)}`;
fetch(url, { cache: "no-store" })
.then((res) => (res.ok ? res.json() : null))
.then((payload) => {
if (cancelled || !payload) return;
const phases = Array.isArray(payload.phases) ? payload.phases : [];
const hasProgress = phases.some(
(ph: { cards?: Array<{ status?: string }> }) =>
Array.isArray(ph.cards) &&
ph.cards.some(
(c) => c.status === "running" || c.status === "complete",
),
);
if (hasProgress) setApplied(true);
})
.catch(() => {
/* ignore */
});
return () => {
cancelled = true;
};
}, [skill.enabled, applied, activeSessionId, setApplied]);
// 监听用户消息:skill 启用 + 检测到训练触发短语 → applied = true。
useEffect(() => {
if (!skill.enabled) return;
if (applied) return;
if (!Array.isArray(messages) || messages.length === 0) return;
// 找最新一条 user 消息
let latestUser: (typeof messages)[number] | null = null;
for (let i = messages.length - 1; i >= 0; i -= 1) {
const m = messages[i];
if (m.role === "user") {
latestUser = m;
break;
}
}
if (!latestUser) return;
if (lastProcessedUserMsgId.current === latestUser.id) return;
lastProcessedUserMsgId.current = latestUser.id;
const text = collectUserMessageText(latestUser);
if (text && detectApplyIntent(text)) {
setApplied(true);
}
}, [messages, skill.enabled, applied, setApplied]);
// 注意:用同一棵树 + 条件渲染,保证 <Thread /> 和 <ActivityPanel /> 在
// pipeline 切换前后都保持挂载,否则它们会 remount,
// useJupyterWorkspaceStatus 的内部 state 会被清空,UI 上 Jupyter 工作区
// indicator 会闪一下变成"切换工作区"。
return (
<div className="flex min-h-0 flex-1 overflow-hidden">
{showPipeline ? (
<div className="relative flex min-w-0 flex-1 flex-col">
<button
type="button"
onClick={() => setApplied(false)}
title="退出训练模式"
aria-label="退出训练模式"
className="absolute top-3 left-3 z-20 inline-flex size-7 items-center justify-center rounded-full border bg-background/90 text-muted-foreground shadow-sm backdrop-blur transition-colors hover:bg-muted"
>
<XIcon className="size-3.5" />
</button>
<TrainingPipelinePanel sessionId={activeSessionId} />
</div>
) : null}
<div
className={cn(
"flex flex-col overflow-hidden",
showPipeline
? "w-[28rem] shrink-0 border-l"
: "min-w-0 flex-1",
)}
>
<div className="min-h-0 flex-1 overflow-hidden">
<Thread />
</div>
</div>
<ActivityPanel asDrawer={showPipeline} />
{showPipeline ? <ActivityDrawerTrigger /> : null}
</div>
);
}
function collectUserMessageText(message: { content?: unknown }): string {
const content = message.content;
if (typeof content === "string") return content;
if (!Array.isArray(content)) return "";
const parts: string[] = [];
for (const part of content) {
if (typeof part === "string") {
parts.push(part);
} else if (part && typeof part === "object") {
const text = (part as { text?: unknown }).text;
if (typeof text === "string") parts.push(text);
}
}
return parts.join("\n");
}
function ActivityDrawerTrigger() {
const { open, openActivity } = useActivityPanel();
if (open) return null;
return (
<Button
type="button"
variant="outline"
size="icon"
onClick={openActivity}
className="fixed top-3 right-3 z-30 size-9 rounded-lg bg-background/90 shadow-sm backdrop-blur"
aria-label="打开活动面板"
>
<PanelRightOpenIcon className="size-4" />
</Button>
);
}
function getLastSessionId(messages: UIMessage[]) {
for (const message of [...messages].reverse()) {
if (message.role !== "assistant") continue;
+80
View File
@@ -51,6 +51,86 @@
background-position: -100% 0;
}
}
--animate-pipeline-running: pipeline-running-glow 1800ms ease-in-out infinite;
@keyframes pipeline-running-glow {
0%,
100% {
box-shadow:
0 0 0 1px rgb(52 211 153 / 0.45),
0 0 0 0 rgb(52 211 153 / 0);
border-color: rgb(52 211 153 / 0.6);
}
50% {
box-shadow:
0 0 0 1px rgb(52 211 153 / 0.95),
0 0 18px 2px rgb(52 211 153 / 0.4);
border-color: rgb(52 211 153 / 1);
}
}
--animate-pipeline-running-blue: pipeline-running-glow-blue 1800ms ease-in-out
infinite;
@keyframes pipeline-running-glow-blue {
0%,
100% {
box-shadow:
0 0 0 1px rgb(56 189 248 / 0.45),
0 0 0 0 rgb(56 189 248 / 0);
border-color: rgb(56 189 248 / 0.7);
}
50% {
box-shadow:
0 0 0 1px rgb(56 189 248 / 0.95),
0 0 18px 2px rgb(56 189 248 / 0.45);
border-color: rgb(56 189 248 / 1);
}
}
--animate-pipeline-progress-shimmer: pipeline-progress-shimmer 1400ms linear
infinite;
@keyframes pipeline-progress-shimmer {
from {
transform: translateX(-100%);
}
to {
transform: translateX(250%);
}
}
--animate-pipeline-pill-glow: pipeline-pill-glow 1800ms ease-in-out infinite;
@keyframes pipeline-pill-glow {
0%,
100% {
box-shadow:
0 0 0 1px rgb(52 211 153 / 0.3),
0 0 0 0 rgb(52 211 153 / 0);
border-color: rgb(52 211 153 / 0.45);
}
50% {
box-shadow:
0 0 0 1px rgb(52 211 153 / 0.7),
0 0 10px 2px rgb(52 211 153 / 0.35);
border-color: rgb(52 211 153 / 0.85);
}
}
--animate-pipeline-dot-ping: pipeline-dot-ping 1400ms ease-out infinite;
@keyframes pipeline-dot-ping {
0% {
transform: scale(0.6);
opacity: 0.9;
}
80%,
100% {
transform: scale(2.2);
opacity: 0;
}
}
--animate-icon-spin: icon-spin 3200ms linear infinite;
@keyframes icon-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
}
.doc-page-v2 {
@@ -41,6 +41,7 @@ import {
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";
import {
ACTIVE_SESSION_CHANGED_EVENT,
readActiveSessionId,
@@ -140,7 +141,7 @@ type ActivityItem = {
type LiveRunEvent = NonNullable<ClawRunStatus["events"]>[number];
export function ActivityPanel() {
export function ActivityPanel({ asDrawer = false }: { asDrawer?: boolean } = {}) {
const {
open,
mode,
@@ -221,20 +222,12 @@ export function ActivityPanel() {
prevLatestIdRef.current = latestId;
}, [items, mode, openActivity, selectedId]);
if (!open) return null;
if (!asDrawer && !open) return null;
if (mode === "files") {
return (
<SessionFilesPanel
key={`${sessionId ?? "active"}:${filesRefreshToken}`}
sessionId={sessionId}
onClose={close}
/>
);
}
const isFilesMode = mode === "files";
return (
<aside className="fixed inset-y-0 right-0 z-30 flex w-[min(23rem,calc(100vw-1rem))] flex-col border-l bg-background shadow-xl lg:static lg:z-auto lg:h-full lg:w-92 lg:shrink-0 lg:shadow-none">
const activityBody = (
<>
<header className="flex h-16 shrink-0 items-center justify-between border-b px-4">
<div className="min-w-0">
<h2 className="font-semibold text-base"></h2>
@@ -244,16 +237,18 @@ export function ActivityPanel() {
: "暂无链路"}
</p>
</div>
<Button
type="button"
variant="ghost"
size="icon"
className="size-8"
onClick={close}
aria-label="关闭活动面板"
>
<PanelRightCloseIcon className="size-4" />
</Button>
{!asDrawer ? (
<Button
type="button"
variant="ghost"
size="icon"
className="size-8"
onClick={close}
aria-label="关闭活动面板"
>
<PanelRightCloseIcon className="size-4" />
</Button>
) : null}
</header>
<div className="min-h-0 flex-1 overflow-y-auto px-4 py-4">
{visibleItems.length === 0 ? (
@@ -280,6 +275,52 @@ export function ActivityPanel() {
</div>
)}
</div>
</>
);
if (asDrawer) {
return (
<Sheet
open={open}
onOpenChange={(next) => {
if (!next) close();
}}
>
<SheetContent
side="right"
className="flex w-[min(25rem,calc(100vw-1rem))] flex-col gap-0 p-0 sm:max-w-md"
>
<SheetTitle className="sr-only">
{isFilesMode ? "聊天中的文件" : "活动"}
</SheetTitle>
{isFilesMode ? (
<SessionFilesPanel
key={`drawer:${sessionId ?? "active"}:${filesRefreshToken}`}
sessionId={sessionId}
onClose={close}
embedded
/>
) : (
activityBody
)}
</SheetContent>
</Sheet>
);
}
if (isFilesMode) {
return (
<SessionFilesPanel
key={`${sessionId ?? "active"}:${filesRefreshToken}`}
sessionId={sessionId}
onClose={close}
/>
);
}
return (
<aside className="fixed inset-y-0 right-0 z-30 flex w-[min(23rem,calc(100vw-1rem))] flex-col border-l bg-background shadow-xl lg:static lg:z-auto lg:h-full lg:w-92 lg:shrink-0 lg:shadow-none">
{activityBody}
</aside>
);
}
@@ -308,9 +349,11 @@ type SessionFilesPayload = {
function SessionFilesPanel({
sessionId,
onClose,
embedded = false,
}: {
sessionId: string | null;
onClose: () => void;
embedded?: boolean;
}) {
const [payload, setPayload] = useState<SessionFilesPayload | null>(null);
const [status, setStatus] = useState("正在读取聊天中的文件...");
@@ -377,8 +420,8 @@ function SessionFilesPanel({
const outputFiles = payload?.output ?? [];
const total = inputFiles.length + outputFiles.length;
return (
<aside className="fixed inset-y-0 right-0 z-30 flex w-[min(25rem,calc(100vw-1rem))] flex-col border-l bg-background shadow-xl lg:static lg:z-auto lg:h-full lg:w-96 lg:shrink-0 lg:shadow-none">
const body = (
<>
<header className="flex h-16 shrink-0 items-center justify-between border-b px-4">
<div className="min-w-0">
<h2 className="font-semibold text-base"></h2>
@@ -386,16 +429,18 @@ function SessionFilesPanel({
{status || `${total} 个文件`}
</p>
</div>
<Button
type="button"
variant="ghost"
size="icon"
className="size-8"
onClick={onClose}
aria-label="关闭文件面板"
>
<PanelRightCloseIcon className="size-4" />
</Button>
{!embedded ? (
<Button
type="button"
variant="ghost"
size="icon"
className="size-8"
onClick={onClose}
aria-label="关闭文件面板"
>
<PanelRightCloseIcon className="size-4" />
</Button>
) : null}
</header>
<div className="min-h-0 flex-1 overflow-y-auto px-4 py-4">
{!status && total === 0 ? (
@@ -406,6 +451,16 @@ function SessionFilesPanel({
<FileSection title="输入" files={inputFiles} />
<FileSection title="输出" files={outputFiles} />
</div>
</>
);
if (embedded) {
return <div className="flex min-h-0 flex-1 flex-col">{body}</div>;
}
return (
<aside className="fixed inset-y-0 right-0 z-30 flex w-[min(25rem,calc(100vw-1rem))] flex-col border-l bg-background shadow-xl lg:static lg:z-auto lg:h-full lg:w-96 lg:shrink-0 lg:shadow-none">
{body}
</aside>
);
}
@@ -425,17 +425,16 @@ async function cancelLatestRun(sessionId: string, runId?: string | null) {
const ChatTopActions: FC = () => {
const { openFiles } = useActivityPanel();
const [workspaceOpen, setWorkspaceOpen] = useState(false);
const actionSessionId = useCurrentThreadSessionId({
includePending: true,
// 工作区切换必须绑定当前可见会话;空白新会话不能回退到上一个
// activeSessionId,否则会把 Jupyter 工作区切到旧会话上。
includeActive: false,
});
const displaySessionId = useCurrentThreadSessionId({
// "切换工作区" dialog 与 indicator 必须用同一个 sessionId,否则会出现
// "绑给 A、查的是 B" 的错位(agent 的 bash 路由也是用 active session id
// 错位时表面 indicator 显示已连接,实际 agent 跑在本地)。
// 新建空会话场景由 thread-list.tsx 的 clearActiveSessionId() 兜底,
// 此处不再需要刻意排除 activeSessionId。
const sessionId = useCurrentThreadSessionId({
includePending: true,
includeActive: true,
});
const workspaceStatus = useJupyterWorkspaceStatus(displaySessionId);
const workspaceStatus = useJupyterWorkspaceStatus(sessionId);
return (
<div className="pointer-events-none sticky top-3 z-20 mr-4 flex justify-end">
@@ -462,7 +461,7 @@ const ChatTopActions: FC = () => {
type="button"
className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-sm transition-colors hover:bg-muted"
onClick={() => {
openFiles(displaySessionId);
openFiles(sessionId);
}}
>
<FileTextIcon className="size-4 text-muted-foreground" />
@@ -482,7 +481,7 @@ const ChatTopActions: FC = () => {
<WorkspaceSwitchDialog
open={workspaceOpen}
onOpenChange={setWorkspaceOpen}
sessionId={actionSessionId}
sessionId={sessionId}
/>
</div>
);
@@ -72,6 +72,7 @@ type ClawSessionSummary = {
preview?: string;
model?: string;
usage?: UsageSummary;
is_training?: boolean;
};
type UsageSummary = {
@@ -365,8 +366,15 @@ function SessionResultButton({
className="flex w-full flex-col rounded-lg px-2 py-2 text-left transition-colors hover:bg-muted"
onClick={onClick}
>
<span className="truncate font-medium text-sm">
{loading ? "回放中..." : session.preview || session.session_id}
<span className="flex items-center gap-1.5">
<span className="truncate font-medium text-sm">
{loading ? "回放中..." : session.preview || session.session_id}
</span>
{session.is_training ? (
<span className="shrink-0 rounded bg-amber-100 px-1.5 text-[10px] text-amber-800">
</span>
) : null}
</span>
<span className="mt-0.5 text-muted-foreground text-xs">
{session.turns ?? 0} · {session.tool_calls ?? 0}
@@ -382,17 +390,23 @@ function useSidebarSessions(open: boolean) {
useEffect(() => {
if (!open) return;
let cancelled = false;
fetch("/api/claw/sessions", { cache: "no-store" })
.then((res) => (res.ok ? res.json() : []))
.then((payload) => {
if (cancelled || !Array.isArray(payload)) return;
setSessions(dedupeSidebarSessions(payload));
})
.catch(() => {
if (!cancelled) setSessions([]);
});
const reload = () => {
fetch("/api/claw/sessions", { cache: "no-store" })
.then((res) => (res.ok ? res.json() : []))
.then((payload) => {
if (cancelled || !Array.isArray(payload)) return;
setSessions(dedupeSidebarSessions(payload));
})
.catch(() => {
if (!cancelled) setSessions([]);
});
};
reload();
const handleUpdate = () => reload();
window.addEventListener("claw-session-updated", handleUpdate);
return () => {
cancelled = true;
window.removeEventListener("claw-session-updated", handleUpdate);
};
}, [open]);
@@ -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];
}
+228
View File
@@ -0,0 +1,228 @@
"use client";
import { useCallback, useEffect, useState } from "react";
export const SESSION_UPDATED_EVENT = "claw-session-updated";
const APPLIED_STORAGE_PREFIX = "claw.training.applied:";
const MODEL_ITERATION_SKILL_NAMES = new Set(["model-iteration"]);
const SKILL_POLL_MS = 8000;
export function useModelIterationEnabled(): {
enabled: boolean;
loading: boolean;
} {
const [enabled, setEnabled] = useState(false);
const [loading, setLoading] = useState(true);
useEffect(() => {
let cancelled = false;
const tick = async () => {
try {
const res = await fetch("/api/claw/skills", { cache: "no-store" });
if (!res.ok) {
if (!cancelled) {
setEnabled(false);
setLoading(false);
}
return;
}
const skills = await res.json();
if (!Array.isArray(skills)) {
if (!cancelled) {
setEnabled(false);
setLoading(false);
}
return;
}
const isOn = skills.some(
(s: { name?: string; enabled?: boolean }) =>
MODEL_ITERATION_SKILL_NAMES.has(String(s?.name ?? "")) &&
s?.enabled !== false,
);
if (!cancelled) {
setEnabled(isOn);
setLoading(false);
}
} catch {
if (!cancelled) {
setEnabled(false);
setLoading(false);
}
}
};
tick();
const id = window.setInterval(tick, SKILL_POLL_MS);
const onFocus = () => tick();
window.addEventListener("focus", onFocus);
return () => {
cancelled = true;
window.clearInterval(id);
window.removeEventListener("focus", onFocus);
};
}, []);
return { enabled, loading };
}
// applied 状态用 localStorage(按 session id)持久化:
// - 关 tab / 浏览器重启都不丢
// - 刷新页面也保持
// 不走后端 PATCH 是为了避开 __LOCALID_* 临时 session id 导致 404
export function useAppliedTraining(sessionId: string | null) {
const [applied, setApplied] = useState(false);
useEffect(() => {
if (!sessionId || typeof window === "undefined") {
setApplied(false);
return;
}
const stored =
window.localStorage.getItem(APPLIED_STORAGE_PREFIX + sessionId) === "1";
setApplied(stored);
}, [sessionId]);
const setAppliedPersist = useCallback(
(next: boolean) => {
setApplied(next);
if (typeof window === "undefined") return;
if (!sessionId) return;
const key = APPLIED_STORAGE_PREFIX + sessionId;
if (next) {
window.localStorage.setItem(key, "1");
} else {
window.localStorage.removeItem(key);
}
},
[sessionId],
);
return { applied, setApplied: setAppliedPersist };
}
export type ProgramStatus = {
available: boolean;
path?: string;
last_modified_ms?: number | null;
error?: string;
};
const PROGRAM_STATUS_POLL_MS = 5000;
export function useProgramStatus(): ProgramStatus & { loading: boolean } {
const [status, setStatus] = useState<ProgramStatus>({ available: false });
const [loading, setLoading] = useState(true);
useEffect(() => {
let cancelled = false;
const tick = async () => {
try {
const res = await fetch("/api/claw/training/program-status", {
cache: "no-store",
});
if (!res.ok) {
if (!cancelled) {
setStatus({ available: false });
setLoading(false);
}
return;
}
const payload = (await res.json()) as ProgramStatus;
if (!cancelled) {
setStatus(payload);
setLoading(false);
}
} catch {
if (!cancelled) {
setStatus({ available: false });
setLoading(false);
}
}
};
tick();
const id = window.setInterval(tick, PROGRAM_STATUS_POLL_MS);
const onFocus = () => tick();
window.addEventListener("focus", onFocus);
return () => {
cancelled = true;
window.clearInterval(id);
window.removeEventListener("focus", onFocus);
};
}, []);
return { ...status, loading };
}
type SessionUpdatedDetail = {
sessionId: string;
is_training?: boolean;
};
export function dispatchSessionUpdated(detail: SessionUpdatedDetail) {
if (typeof window === "undefined") return;
window.dispatchEvent(
new CustomEvent<SessionUpdatedDetail>(SESSION_UPDATED_EVENT, { detail }),
);
}
export function useTrainingMode(sessionId: string | null) {
const [isTraining, setIsTraining] = useState(false);
const [loaded, setLoaded] = useState(false);
useEffect(() => {
setLoaded(false);
if (!sessionId) {
setIsTraining(false);
return;
}
let cancelled = false;
fetch(`/api/claw/sessions/${encodeURIComponent(sessionId)}`, {
cache: "no-store",
})
.then(async (res) => {
if (!res.ok) return null;
return res.json();
})
.then((payload) => {
if (cancelled) return;
const next = Boolean(payload?.is_training);
setIsTraining(next);
setLoaded(true);
})
.catch(() => {
if (!cancelled) setLoaded(true);
});
return () => {
cancelled = true;
};
}, [sessionId]);
const setTraining = useCallback(
async (next: boolean) => {
if (!sessionId) return;
const previous = isTraining;
setIsTraining(next);
try {
const res = await fetch(
`/api/claw/sessions/${encodeURIComponent(sessionId)}`,
{
method: "PATCH",
headers: { "content-type": "application/json" },
body: JSON.stringify({ is_training: next }),
},
);
if (!res.ok) {
setIsTraining(previous);
return;
}
dispatchSessionUpdated({ sessionId, is_training: next });
} catch {
setIsTraining(previous);
}
},
[sessionId, isTraining],
);
return { isTraining, setTraining, loaded };
}