修改
This commit is contained in:
+1459
-11
File diff suppressed because it is too large
Load Diff
@@ -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",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,16 +1,18 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import type { ExportedMessageRepository } from "@assistant-ui/core";
|
import type { ExportedMessageRepository } from "@assistant-ui/core";
|
||||||
import { AssistantRuntimeProvider } from "@assistant-ui/react";
|
import { AssistantRuntimeProvider, useAuiState } from "@assistant-ui/react";
|
||||||
import {
|
import {
|
||||||
AssistantChatTransport,
|
AssistantChatTransport,
|
||||||
useChatRuntime,
|
useChatRuntime,
|
||||||
} from "@assistant-ui/react-ai-sdk";
|
} from "@assistant-ui/react-ai-sdk";
|
||||||
import type { UIMessage } from "ai";
|
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 {
|
import {
|
||||||
ActivityPanel,
|
ActivityPanel,
|
||||||
ActivityProvider,
|
ActivityProvider,
|
||||||
|
useActivityPanel,
|
||||||
} from "@/components/assistant-ui/activity-panel";
|
} from "@/components/assistant-ui/activity-panel";
|
||||||
import { Thread } from "@/components/assistant-ui/thread";
|
import { Thread } from "@/components/assistant-ui/thread";
|
||||||
import {
|
import {
|
||||||
@@ -18,18 +20,26 @@ import {
|
|||||||
toReplayRepository,
|
toReplayRepository,
|
||||||
} from "@/components/assistant-ui/thread-list";
|
} from "@/components/assistant-ui/thread-list";
|
||||||
import { ThreadListSidebar } from "@/components/assistant-ui/threadlist-sidebar";
|
import { ThreadListSidebar } from "@/components/assistant-ui/threadlist-sidebar";
|
||||||
|
import { TrainingPipelinePanel } from "@/components/training/training-pipeline-panel";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
SidebarInset,
|
SidebarInset,
|
||||||
SidebarProvider,
|
SidebarProvider,
|
||||||
SidebarTrigger,
|
SidebarTrigger,
|
||||||
} from "@/components/ui/sidebar";
|
} from "@/components/ui/sidebar";
|
||||||
import {
|
import {
|
||||||
|
ACTIVE_SESSION_CHANGED_EVENT,
|
||||||
readActiveSessionId,
|
readActiveSessionId,
|
||||||
readPendingWorkspaceSessionId,
|
readPendingWorkspaceSessionId,
|
||||||
writeActiveSessionId,
|
writeActiveSessionId,
|
||||||
} from "@/lib/claw-active-session";
|
} from "@/lib/claw-active-session";
|
||||||
import { ClawSessionReplayProvider } from "@/lib/claw-session-replay";
|
import { ClawSessionReplayProvider } from "@/lib/claw-session-replay";
|
||||||
import { pushSessionUrl } from "@/lib/claw-session-url";
|
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";
|
import { ClawAccountGate, useClawAccount } from "./claw-account-gate";
|
||||||
|
|
||||||
type AssistantProps = {
|
type AssistantProps = {
|
||||||
@@ -153,12 +163,7 @@ export const Assistant = ({ initialSessionId }: AssistantProps = {}) => {
|
|||||||
onLogout={() => setAccount(null)}
|
onLogout={() => setAccount(null)}
|
||||||
/>
|
/>
|
||||||
<SidebarInset>
|
<SidebarInset>
|
||||||
<div className="flex min-h-0 flex-1 overflow-hidden">
|
<AssistantWorkspace />
|
||||||
<div className="min-w-0 flex-1 overflow-hidden">
|
|
||||||
<Thread />
|
|
||||||
</div>
|
|
||||||
<ActivityPanel />
|
|
||||||
</div>
|
|
||||||
</SidebarInset>
|
</SidebarInset>
|
||||||
</div>
|
</div>
|
||||||
</SidebarProvider>
|
</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[]) {
|
function getLastSessionId(messages: UIMessage[]) {
|
||||||
for (const message of [...messages].reverse()) {
|
for (const message of [...messages].reverse()) {
|
||||||
if (message.role !== "assistant") continue;
|
if (message.role !== "assistant") continue;
|
||||||
|
|||||||
@@ -51,6 +51,86 @@
|
|||||||
background-position: -100% 0;
|
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 {
|
.doc-page-v2 {
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ import {
|
|||||||
CollapsibleContent,
|
CollapsibleContent,
|
||||||
CollapsibleTrigger,
|
CollapsibleTrigger,
|
||||||
} from "@/components/ui/collapsible";
|
} from "@/components/ui/collapsible";
|
||||||
|
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";
|
||||||
import {
|
import {
|
||||||
ACTIVE_SESSION_CHANGED_EVENT,
|
ACTIVE_SESSION_CHANGED_EVENT,
|
||||||
readActiveSessionId,
|
readActiveSessionId,
|
||||||
@@ -140,7 +141,7 @@ type ActivityItem = {
|
|||||||
|
|
||||||
type LiveRunEvent = NonNullable<ClawRunStatus["events"]>[number];
|
type LiveRunEvent = NonNullable<ClawRunStatus["events"]>[number];
|
||||||
|
|
||||||
export function ActivityPanel() {
|
export function ActivityPanel({ asDrawer = false }: { asDrawer?: boolean } = {}) {
|
||||||
const {
|
const {
|
||||||
open,
|
open,
|
||||||
mode,
|
mode,
|
||||||
@@ -221,20 +222,12 @@ export function ActivityPanel() {
|
|||||||
prevLatestIdRef.current = latestId;
|
prevLatestIdRef.current = latestId;
|
||||||
}, [items, mode, openActivity, selectedId]);
|
}, [items, mode, openActivity, selectedId]);
|
||||||
|
|
||||||
if (!open) return null;
|
if (!asDrawer && !open) return null;
|
||||||
|
|
||||||
if (mode === "files") {
|
const isFilesMode = mode === "files";
|
||||||
return (
|
|
||||||
<SessionFilesPanel
|
|
||||||
key={`${sessionId ?? "active"}:${filesRefreshToken}`}
|
|
||||||
sessionId={sessionId}
|
|
||||||
onClose={close}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
const activityBody = (
|
||||||
<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">
|
<>
|
||||||
<header className="flex h-16 shrink-0 items-center justify-between border-b px-4">
|
<header className="flex h-16 shrink-0 items-center justify-between border-b px-4">
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<h2 className="font-semibold text-base">活动</h2>
|
<h2 className="font-semibold text-base">活动</h2>
|
||||||
@@ -244,16 +237,18 @@ export function ActivityPanel() {
|
|||||||
: "暂无链路"}
|
: "暂无链路"}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Button
|
{!asDrawer ? (
|
||||||
type="button"
|
<Button
|
||||||
variant="ghost"
|
type="button"
|
||||||
size="icon"
|
variant="ghost"
|
||||||
className="size-8"
|
size="icon"
|
||||||
onClick={close}
|
className="size-8"
|
||||||
aria-label="关闭活动面板"
|
onClick={close}
|
||||||
>
|
aria-label="关闭活动面板"
|
||||||
<PanelRightCloseIcon className="size-4" />
|
>
|
||||||
</Button>
|
<PanelRightCloseIcon className="size-4" />
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
</header>
|
</header>
|
||||||
<div className="min-h-0 flex-1 overflow-y-auto px-4 py-4">
|
<div className="min-h-0 flex-1 overflow-y-auto px-4 py-4">
|
||||||
{visibleItems.length === 0 ? (
|
{visibleItems.length === 0 ? (
|
||||||
@@ -280,6 +275,52 @@ export function ActivityPanel() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</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>
|
</aside>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -308,9 +349,11 @@ type SessionFilesPayload = {
|
|||||||
function SessionFilesPanel({
|
function SessionFilesPanel({
|
||||||
sessionId,
|
sessionId,
|
||||||
onClose,
|
onClose,
|
||||||
|
embedded = false,
|
||||||
}: {
|
}: {
|
||||||
sessionId: string | null;
|
sessionId: string | null;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
|
embedded?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const [payload, setPayload] = useState<SessionFilesPayload | null>(null);
|
const [payload, setPayload] = useState<SessionFilesPayload | null>(null);
|
||||||
const [status, setStatus] = useState("正在读取聊天中的文件...");
|
const [status, setStatus] = useState("正在读取聊天中的文件...");
|
||||||
@@ -377,8 +420,8 @@ function SessionFilesPanel({
|
|||||||
const outputFiles = payload?.output ?? [];
|
const outputFiles = payload?.output ?? [];
|
||||||
const total = inputFiles.length + outputFiles.length;
|
const total = inputFiles.length + outputFiles.length;
|
||||||
|
|
||||||
return (
|
const body = (
|
||||||
<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">
|
<>
|
||||||
<header className="flex h-16 shrink-0 items-center justify-between border-b px-4">
|
<header className="flex h-16 shrink-0 items-center justify-between border-b px-4">
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<h2 className="font-semibold text-base">聊天中的文件</h2>
|
<h2 className="font-semibold text-base">聊天中的文件</h2>
|
||||||
@@ -386,16 +429,18 @@ function SessionFilesPanel({
|
|||||||
{status || `${total} 个文件`}
|
{status || `${total} 个文件`}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Button
|
{!embedded ? (
|
||||||
type="button"
|
<Button
|
||||||
variant="ghost"
|
type="button"
|
||||||
size="icon"
|
variant="ghost"
|
||||||
className="size-8"
|
size="icon"
|
||||||
onClick={onClose}
|
className="size-8"
|
||||||
aria-label="关闭文件面板"
|
onClick={onClose}
|
||||||
>
|
aria-label="关闭文件面板"
|
||||||
<PanelRightCloseIcon className="size-4" />
|
>
|
||||||
</Button>
|
<PanelRightCloseIcon className="size-4" />
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
</header>
|
</header>
|
||||||
<div className="min-h-0 flex-1 overflow-y-auto px-4 py-4">
|
<div className="min-h-0 flex-1 overflow-y-auto px-4 py-4">
|
||||||
{!status && total === 0 ? (
|
{!status && total === 0 ? (
|
||||||
@@ -406,6 +451,16 @@ function SessionFilesPanel({
|
|||||||
<FileSection title="输入" files={inputFiles} />
|
<FileSection title="输入" files={inputFiles} />
|
||||||
<FileSection title="输出" files={outputFiles} />
|
<FileSection title="输出" files={outputFiles} />
|
||||||
</div>
|
</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>
|
</aside>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -425,17 +425,16 @@ async function cancelLatestRun(sessionId: string, runId?: string | null) {
|
|||||||
const ChatTopActions: FC = () => {
|
const ChatTopActions: FC = () => {
|
||||||
const { openFiles } = useActivityPanel();
|
const { openFiles } = useActivityPanel();
|
||||||
const [workspaceOpen, setWorkspaceOpen] = useState(false);
|
const [workspaceOpen, setWorkspaceOpen] = useState(false);
|
||||||
const actionSessionId = useCurrentThreadSessionId({
|
// "切换工作区" dialog 与 indicator 必须用同一个 sessionId,否则会出现
|
||||||
includePending: true,
|
// "绑给 A、查的是 B" 的错位(agent 的 bash 路由也是用 active session id,
|
||||||
// 工作区切换必须绑定当前可见会话;空白新会话不能回退到上一个
|
// 错位时表面 indicator 显示已连接,实际 agent 跑在本地)。
|
||||||
// activeSessionId,否则会把 Jupyter 工作区切到旧会话上。
|
// 新建空会话场景由 thread-list.tsx 的 clearActiveSessionId() 兜底,
|
||||||
includeActive: false,
|
// 此处不再需要刻意排除 activeSessionId。
|
||||||
});
|
const sessionId = useCurrentThreadSessionId({
|
||||||
const displaySessionId = useCurrentThreadSessionId({
|
|
||||||
includePending: true,
|
includePending: true,
|
||||||
includeActive: true,
|
includeActive: true,
|
||||||
});
|
});
|
||||||
const workspaceStatus = useJupyterWorkspaceStatus(displaySessionId);
|
const workspaceStatus = useJupyterWorkspaceStatus(sessionId);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="pointer-events-none sticky top-3 z-20 mr-4 flex justify-end">
|
<div className="pointer-events-none sticky top-3 z-20 mr-4 flex justify-end">
|
||||||
@@ -462,7 +461,7 @@ const ChatTopActions: FC = () => {
|
|||||||
type="button"
|
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"
|
className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-sm transition-colors hover:bg-muted"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
openFiles(displaySessionId);
|
openFiles(sessionId);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<FileTextIcon className="size-4 text-muted-foreground" />
|
<FileTextIcon className="size-4 text-muted-foreground" />
|
||||||
@@ -482,7 +481,7 @@ const ChatTopActions: FC = () => {
|
|||||||
<WorkspaceSwitchDialog
|
<WorkspaceSwitchDialog
|
||||||
open={workspaceOpen}
|
open={workspaceOpen}
|
||||||
onOpenChange={setWorkspaceOpen}
|
onOpenChange={setWorkspaceOpen}
|
||||||
sessionId={actionSessionId}
|
sessionId={sessionId}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -72,6 +72,7 @@ type ClawSessionSummary = {
|
|||||||
preview?: string;
|
preview?: string;
|
||||||
model?: string;
|
model?: string;
|
||||||
usage?: UsageSummary;
|
usage?: UsageSummary;
|
||||||
|
is_training?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
type UsageSummary = {
|
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"
|
className="flex w-full flex-col rounded-lg px-2 py-2 text-left transition-colors hover:bg-muted"
|
||||||
onClick={onClick}
|
onClick={onClick}
|
||||||
>
|
>
|
||||||
<span className="truncate font-medium text-sm">
|
<span className="flex items-center gap-1.5">
|
||||||
{loading ? "回放中..." : session.preview || session.session_id}
|
<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>
|
||||||
<span className="mt-0.5 text-muted-foreground text-xs">
|
<span className="mt-0.5 text-muted-foreground text-xs">
|
||||||
{session.turns ?? 0} 轮 · {session.tool_calls ?? 0} 次工具
|
{session.turns ?? 0} 轮 · {session.tool_calls ?? 0} 次工具
|
||||||
@@ -382,17 +390,23 @@ function useSidebarSessions(open: boolean) {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return;
|
if (!open) return;
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
fetch("/api/claw/sessions", { cache: "no-store" })
|
const reload = () => {
|
||||||
.then((res) => (res.ok ? res.json() : []))
|
fetch("/api/claw/sessions", { cache: "no-store" })
|
||||||
.then((payload) => {
|
.then((res) => (res.ok ? res.json() : []))
|
||||||
if (cancelled || !Array.isArray(payload)) return;
|
.then((payload) => {
|
||||||
setSessions(dedupeSidebarSessions(payload));
|
if (cancelled || !Array.isArray(payload)) return;
|
||||||
})
|
setSessions(dedupeSidebarSessions(payload));
|
||||||
.catch(() => {
|
})
|
||||||
if (!cancelled) setSessions([]);
|
.catch(() => {
|
||||||
});
|
if (!cancelled) setSessions([]);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
reload();
|
||||||
|
const handleUpdate = () => reload();
|
||||||
|
window.addEventListener("claw-session-updated", handleUpdate);
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
|
window.removeEventListener("claw-session-updated", handleUpdate);
|
||||||
};
|
};
|
||||||
}, [open]);
|
}, [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];
|
||||||
|
}
|
||||||
@@ -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 };
|
||||||
|
}
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
# Skill: model-iteration
|
|
||||||
|
|
||||||
本目录是小爱中控模型迭代 skill,用于评测、错误分析、数据增强、SFT 训练和 CML workflow 追踪。
|
|
||||||
|
|
||||||
## 目录结构
|
|
||||||
|
|
||||||
```
|
|
||||||
model-iteration/
|
|
||||||
├── config.yaml # 评估阈值 + CML 工作流配置
|
|
||||||
├── knowledge/ # 分流知识库
|
|
||||||
│ ├── navigation_routing_rules.md # 地图导航 Agent/ComplexTask 分流
|
|
||||||
│ ├── travel_routing_rules.md # 旅游 Agent/ComplexTask 分流
|
|
||||||
│ └── multi_command_rules.md # 多指令 vs ComplexTask 判定
|
|
||||||
├── scripts/
|
|
||||||
│ ├── prepare_and_train_sft.py # 数据组装 + 本地训练
|
|
||||||
│ ├── submit_sft_via_cml.sh # CML 云端训练提交(R29 起统一用此)
|
|
||||||
│ └── sft_train_job.yaml.tpl # CML 训练 job YAML 模板
|
|
||||||
├── SKILL.md # 完整迭代协议(触发规则、Step 0-6、数据增强/清洗规范)
|
|
||||||
└── README.md # 本文件
|
|
||||||
```
|
|
||||||
|
|
||||||
## 快速上手
|
|
||||||
|
|
||||||
### 1. 评测当前模型
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cml workflow run \
|
|
||||||
--workflow_id f-20260408161444-wu3pz --version v28 \
|
|
||||||
--global_inputs runDic=<N> \
|
|
||||||
--global_inputs model_path_new=<新模型路径> \
|
|
||||||
--global_inputs model_path_old=<基线模型路径>
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2. SFT 训练(CML 云端)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
AUTORESEARCH_ROOT=/mnt/wangsenhao/autoresearch-zk \
|
|
||||||
./scripts/submit_sft_via_cml.sh <RUNDIC> [PREV_RUNDIC]
|
|
||||||
```
|
|
||||||
|
|
||||||
训练完成后自动起评测 workflow。
|
|
||||||
|
|
||||||
### 3. SFT 训练(本地)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
AUTORESEARCH_ROOT=/mnt/wangsenhao/autoresearch-zk \
|
|
||||||
python scripts/prepare_and_train_sft.py prepare --output_dir ./sft_data
|
|
||||||
|
|
||||||
AUTORESEARCH_ROOT=/mnt/wangsenhao/autoresearch-zk \
|
|
||||||
python scripts/prepare_and_train_sft.py train \
|
|
||||||
--data_dir ./sft_data \
|
|
||||||
--model_path /mnt/wangsenhao/verl_zk/Qwen3-4B-Instruct-2507 \
|
|
||||||
--model_type qwen3 \
|
|
||||||
--train_output ./sft_output \
|
|
||||||
--epochs 3 --lr 1e-5
|
|
||||||
```
|
|
||||||
|
|
||||||
## 关键规则
|
|
||||||
|
|
||||||
- **达标标准**:需求集合 ≥ 95%,大盘车载降幅 ≤ 0.3%,specific test 降幅 ≤ 1%
|
|
||||||
- **数据清洗**:case 驱动、禁止批量、必须备份、只改 output 不动 instruction
|
|
||||||
- **训练环境**:FSDP2 + torch 2.6 需要 accelerate==1.7.0,不要改训练代码去适配
|
|
||||||
|
|
||||||
## 完整协议
|
|
||||||
|
|
||||||
详见 [SKILL.md](SKILL.md)
|
|
||||||
+293
-1294
File diff suppressed because it is too large
Load Diff
@@ -9,5 +9,5 @@ thresholds:
|
|||||||
# CML 评测工作流配置
|
# CML 评测工作流配置
|
||||||
cml_eval:
|
cml_eval:
|
||||||
workflow_id: f-20260408161444-wu3pz
|
workflow_id: f-20260408161444-wu3pz
|
||||||
version: v28
|
version: v32
|
||||||
|
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
# 多轮对话连贯性 —— ComplexTask 继承规则
|
||||||
|
|
||||||
|
## 核心判定
|
||||||
|
|
||||||
|
| 场景 | 输出 | 示例 |
|
||||||
|
|------|------|------|
|
||||||
|
| 上轮是 ComplexTask + 当前 query 和上轮**相关**(延续/细化/替换/挑选/追加) | 当前仍 `ComplexTask(tag="...")` | 上轮 CT 导航多目的地,当前"第二家导航过去" → CT |
|
||||||
|
| 上轮是 Agent + 当前 query 是独立新任务 | 按当前 query 独立分类 | 上轮 Agent 导航,当前"播放周杰伦" → Agent(音乐播放) |
|
||||||
|
| 上轮是 ComplexTask + 当前 query 是**无关**新任务 | 按当前独立分类 | 上轮 CT 旅游,当前"今天天气怎么样" → QA/WeatherQA |
|
||||||
|
|
||||||
|
## 判定要点
|
||||||
|
|
||||||
|
- **"相关"的定义**:当前 query 是对上轮任务的**延续、细化、替换、挑选、追加**中的任一类:
|
||||||
|
- 延续:用户在上轮的同一任务线上继续操作("继续导航"/"换一条不堵的")
|
||||||
|
- 细化:对上轮结果加筛选条件("人少一点的"/"评分最高的"/"最近的那个")
|
||||||
|
- 替换:换掉上轮的某个要素,同领域保持("不要 A 换成 B")
|
||||||
|
- 挑选:从上轮推荐的候选中选择("第一个"/"第二家"/"刚给的那个")
|
||||||
|
- 追加:在上轮任务基础上加步骤("路上再加个加油站"/"顺便找个 ATM")
|
||||||
|
|
||||||
|
- **prev 侧"隐式 CT 信号"(R17777 补充)**:prev 即使只是一轮用户独白,只要含以下任一信号也视作 CT 场景:
|
||||||
|
- **单轮内自我修正/替换**:"导航到 A 哦不对 B"、"去 X 啊不 Y"、"到 A 嗯就是 B" —— 用户在说的过程中换目的地,系统需处理替换逻辑
|
||||||
|
- **候选选择犹豫**:"是 A 还是 B"、"哪个近就哪个"、"算了不去 A 了"
|
||||||
|
- **多 POI 枚举/对比**:"A 和 B 哪个近"、"先说 A 再说 B"
|
||||||
|
|
||||||
|
> 注:单 POI + 多重形容词筛选("最便宜的有车位的充电站")**不算** CT 信号,按 R1 归 Agent。
|
||||||
|
|
||||||
|
- **继承的是 `complex` 维度,不是 tag 内容**:tag 仍可能是 Agent 标签,但 complex=true,因为复合任务语境未结束
|
||||||
|
|
||||||
|
## 反例(不适用继承)
|
||||||
|
|
||||||
|
- 当前 query 明显切换意图:上轮 CT 导航 → 当前"打开空调"(tag=车载控制,无关)→ 独立分类
|
||||||
|
- 当前 query 是独立的闲聊 / 时间 / 天气问答:上轮 CT → 当前"现在几点" → 独立分类
|
||||||
|
- 上轮是 CT 但失败/取消("算了不要了"):后续 query 不再继承
|
||||||
|
|
||||||
|
## 为什么需要这条规则(经验来源)
|
||||||
|
|
||||||
|
R17775 迭代中,我们修改了训练集 47 条"纯路线偏好"样本 complex=true → false,对齐 0511 专项 gold(60% → 76.67%)。但这产生副作用:
|
||||||
|
|
||||||
|
- `复杂导航线上真实_rag` -3.30pp(11 条 gold=true 被过度修正为 false)
|
||||||
|
- 如 "我要重新选一个路线"、"嗯经过凤雏路去江北虹悦城"
|
||||||
|
- `0511 专项` 新引入 6 条错全是**多轮延续 POI/挑选**类
|
||||||
|
- 如 "评分最高的那个导航过去"、"第二家导航过去"、"人少一点的"
|
||||||
|
|
||||||
|
根因:单看 query 这些表达像"纯偏好",但在多轮上下文中是**对上轮 ComplexTask 的挑选/细化**,应继承 CT。SFT 模型在只看当前 query 时判错。
|
||||||
|
|
||||||
|
## 应用场景
|
||||||
|
|
||||||
|
- **数据增强**:生成带 prev_session 的训练样本时,如果 prev 是 `ComplexTask(...)`,当前 query 与之相关 → ground_truth 必须是 ComplexTask(不能矛盾)
|
||||||
|
- **训练集清洗**:不要把"多轮延续同任务"类样本的 complex=true 改为 false(R17774 的 47 条改动里,L10752 / L10943 / L10954 等 multi_turn_deixis 已保留未改,正确)
|
||||||
|
- **Badcase 分析**:错例 query 如果语境是对上轮 CT 的延续,SFT 模型判错不能靠修改训练集同 pattern 样本的 label 来解,需要补"带 prev_session 的延续 CT"仿写增强模型学到上下文信号
|
||||||
|
- **Reward 函数**:对违反此规则的预测(prev=CT + 相关继续 但 pred complex=false)应被惩罚
|
||||||
|
|
||||||
|
## 反模式
|
||||||
|
|
||||||
|
- ❌ 只看当前 query 文本判 complex,忽略 prev_session
|
||||||
|
- ❌ 训练集批改 complex=true→false 时未检查 prev_session,导致多轮延续样本被误改
|
||||||
|
- ❌ 生成仿写时当前 query 与 prev_session 矛盾(prev CT 但 current 标 complex=false)
|
||||||
+2
-2
@@ -4,8 +4,8 @@
|
|||||||
|
|
||||||
| 场景 | 输出 | 示例 |
|
| 场景 | 输出 | 示例 |
|
||||||
|------|------|------|
|
|------|------|------|
|
||||||
| 规划路线,无筛选条件 | `Agent(tag="旅游出行")` | 规划一个从北京到上海的路线 |
|
| 规划路线,无筛选条件 | `Agent(tag="旅游")` | 规划一个从北京到上海的路线 |
|
||||||
| 规划路线,有筛选条件 | `ComplexTask(tag="旅游出行")` | 规划一个从北京到上海的路线,人少风景好、三天两夜、3000预算 |
|
| 规划路线,有筛选条件 | `ComplexTask(tag="旅游")` | 规划一个从北京到上海的路线,人少风景好、三天两夜、3000预算 |
|
||||||
|
|
||||||
## 判定要点
|
## 判定要点
|
||||||
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -4,11 +4,9 @@
|
|||||||
|
|
||||||
用法:
|
用法:
|
||||||
# 仅组装数据
|
# 仅组装数据
|
||||||
AUTORESEARCH_ROOT=/mnt/wangsenhao/autoresearch-zk \
|
python prepare_and_train_sft.py prepare --output_dir /mnt/wangsenhao/autoresearch-zk/sft_data
|
||||||
python prepare_and_train_sft.py prepare --output_dir /mnt/wangsenhao/autoresearch-zk/sft_data
|
|
||||||
|
|
||||||
# 启动训练(需先 prepare)
|
# 启动训练(需先 prepare)
|
||||||
AUTORESEARCH_ROOT=/mnt/wangsenhao/autoresearch-zk \
|
|
||||||
python prepare_and_train_sft.py train \
|
python prepare_and_train_sft.py train \
|
||||||
--data_dir /mnt/wangsenhao/autoresearch-zk/sft_data \
|
--data_dir /mnt/wangsenhao/autoresearch-zk/sft_data \
|
||||||
--model_path /mnt/wangsenhao/verl_zk/Qwen3-4B-Instruct-2507 \
|
--model_path /mnt/wangsenhao/verl_zk/Qwen3-4B-Instruct-2507 \
|
||||||
@@ -28,14 +26,7 @@ from pathlib import Path
|
|||||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
AI_PLANNING = Path(__file__).resolve().parent / "ai-planning"
|
||||||
def _path_from_env(name: str, fallback: Path) -> Path:
|
|
||||||
return Path(os.environ.get(name, str(fallback))).expanduser().resolve()
|
|
||||||
|
|
||||||
|
|
||||||
AUTORESEARCH_ROOT = _path_from_env("AUTORESEARCH_ROOT", Path("/mnt/wangsenhao/autoresearch-zk"))
|
|
||||||
AI_PLANNING = _path_from_env("AI_PLANNING_DIR", AUTORESEARCH_ROOT / "ai-planning")
|
|
||||||
ZK_TRAINER_DIR = _path_from_env("ZK_TRAINER_DIR", AUTORESEARCH_ROOT / "zk_trainer")
|
|
||||||
TRAIN_SET_DIR = AI_PLANNING / "data" / "train_set"
|
TRAIN_SET_DIR = AI_PLANNING / "data" / "train_set"
|
||||||
DATA_TRAIN_DIR = AI_PLANNING / "data_train"
|
DATA_TRAIN_DIR = AI_PLANNING / "data_train"
|
||||||
GENERATE_TRAIN_SCRIPT = DATA_TRAIN_DIR / "generate_train.py"
|
GENERATE_TRAIN_SCRIPT = DATA_TRAIN_DIR / "generate_train.py"
|
||||||
@@ -157,7 +148,7 @@ def run_sft_training(data_dir: str, model_path: str, model_type: str, train_outp
|
|||||||
epochs: int = 3, lr: float = 1e-5, max_seq_length: int = 1024,
|
epochs: int = 3, lr: float = 1e-5, max_seq_length: int = 1024,
|
||||||
per_device_batch: int = 1, grad_accum: int = 1):
|
per_device_batch: int = 1, grad_accum: int = 1):
|
||||||
"""基于 zk_trainer 的 accelerate launch 方式启动 SFT 训练。"""
|
"""基于 zk_trainer 的 accelerate launch 方式启动 SFT 训练。"""
|
||||||
zk_trainer_dir = str(ZK_TRAINER_DIR)
|
zk_trainer_dir = str(Path(__file__).resolve().parent / "zk_trainer")
|
||||||
if not os.path.isdir(zk_trainer_dir):
|
if not os.path.isdir(zk_trainer_dir):
|
||||||
log.error(f"zk_trainer 目录不存在: {zk_trainer_dir}")
|
log.error(f"zk_trainer 目录不存在: {zk_trainer_dir}")
|
||||||
return None
|
return None
|
||||||
|
|||||||
@@ -1,117 +0,0 @@
|
|||||||
jobName: "sft-train-r{RUNDIC}"
|
|
||||||
description: "AutoResearch R{RUNDIC} SFT training (40k+ samples, qwen3-4B base, 3 epochs FSDP2)"
|
|
||||||
accessType: PUBLIC
|
|
||||||
|
|
||||||
imageConfig:
|
|
||||||
imageUrl: micr.cloud.mioffice.cn/vllm-image/ai-arch-llm-prod:vllm-v0.12.0-f098b188
|
|
||||||
imageCommand: |-
|
|
||||||
set -ex
|
|
||||||
cd {AUTORESEARCH_ROOT}
|
|
||||||
|
|
||||||
# 0a. 验环境 + 装缺的包(vllm 镜像 py3.12 + torch 已含)
|
|
||||||
python3 --version
|
|
||||||
python3 -c "import torch; print(f'torch={torch.__version__}')"
|
|
||||||
pip install -q --no-deps "accelerate==1.7.0" 2>&1 | tail -3
|
|
||||||
pip install -q --ignore-installed blinker 2>&1 | tail -2
|
|
||||||
pip install -q peft 2>&1 | tail -3
|
|
||||||
pip install -q wandb bitsandbytes 2>&1 | tail -3
|
|
||||||
pip install -q luigi mlflow scikit-learn openpyxl pyyaml sentencepiece tiktoken protobuf pynvml datasets 2>&1 | tail -3
|
|
||||||
pip install -q "transformers>=4.45" 2>&1 | tail -3
|
|
||||||
python3 -c 'import torch, accelerate, transformers, peft; print(torch.__version__, accelerate.__version__, transformers.__version__, peft.__version__)'
|
|
||||||
|
|
||||||
# 0c. 把 HF cache 重定向到容器本地大盘(默认在 ~/.cache 可能是 juicefs,mmap 易 SIGBUS)
|
|
||||||
export HF_HOME=/tmp/hf_cache
|
|
||||||
export HF_DATASETS_CACHE=/tmp/hf_cache/datasets
|
|
||||||
export TRANSFORMERS_CACHE=/tmp/hf_cache/transformers
|
|
||||||
mkdir -p /tmp/hf_cache/datasets /tmp/hf_cache/transformers
|
|
||||||
df -h /tmp /dev/shm 2>/dev/null || true
|
|
||||||
|
|
||||||
# 强制 datasets 加载进内存而不是 arrow mmap(避免 /dev/shm 溢出 SIGBUS)
|
|
||||||
export HF_DATASETS_IN_MEMORY_MAX_SIZE=20000000000
|
|
||||||
export HF_DATASETS_NUM_PROC=1
|
|
||||||
export TOKENIZERS_PARALLELISM=false
|
|
||||||
export OMP_NUM_THREADS=1
|
|
||||||
export MKL_NUM_THREADS=1
|
|
||||||
# 关闭 NCCL 用 shm 通信(改 socket 通道)
|
|
||||||
export NCCL_SHM_DISABLE=1
|
|
||||||
export NCCL_P2P_DISABLE=0
|
|
||||||
export NCCL_DEBUG=WARN
|
|
||||||
|
|
||||||
# 0b. 把上一轮产出搬走(cml job 内幂等,本地搬过就跳过)
|
|
||||||
if [ -d sft_output ] && [ ! -d sft_output_r{PREV_RUNDIC} ]; then
|
|
||||||
mv sft_output sft_output_r{PREV_RUNDIC}
|
|
||||||
fi
|
|
||||||
rm -rf sft_output
|
|
||||||
|
|
||||||
# 1. 组装数据
|
|
||||||
python3 {AUTORESEARCH_ROOT}/prepare_and_train_sft.py prepare \
|
|
||||||
--output_dir {AUTORESEARCH_ROOT}/sft_data
|
|
||||||
|
|
||||||
# 2. 启动训练(绝对路径,避免相对路径在容器内找不到 zk_trainer)
|
|
||||||
python3 {AUTORESEARCH_ROOT}/prepare_and_train_sft.py train \
|
|
||||||
--data_dir {AUTORESEARCH_ROOT}/sft_data \
|
|
||||||
--model_path /mnt/wangsenhao/verl_zk/Qwen3-4B-Instruct-2507 \
|
|
||||||
--model_type qwen3 \
|
|
||||||
--train_output {AUTORESEARCH_ROOT}/sft_output \
|
|
||||||
--epochs 3 --lr 1e-5
|
|
||||||
|
|
||||||
# 3. 训练成功标记(被 watcher 检测)
|
|
||||||
[ -f {AUTORESEARCH_ROOT}/sft_output/config.json ] && \
|
|
||||||
touch {AUTORESEARCH_ROOT}/sft_output/_SUCCESS
|
|
||||||
|
|
||||||
# 挂载 wangsenhao + xiaoai-zk-model-train-tj5 + verl_zk 所在卷
|
|
||||||
juiceFsMountConfigs:
|
|
||||||
- volume: wangsenhao
|
|
||||||
juiceFsCluster: tj5-common
|
|
||||||
subPath: /
|
|
||||||
mountPath: /mnt/wangsenhao
|
|
||||||
readOnly: false
|
|
||||||
- volume: xiaoai-zk-model-train-tj5
|
|
||||||
juiceFsCluster: tj5-common
|
|
||||||
subPath: /
|
|
||||||
mountPath: /mnt/xiaoai-zk-model-train-tj5
|
|
||||||
readOnly: false
|
|
||||||
|
|
||||||
envConfigs:
|
|
||||||
- key: PYTHONPATH
|
|
||||||
value: {AUTORESEARCH_ROOT}/zk_trainer
|
|
||||||
- key: WANDB_DISABLED
|
|
||||||
value: "true"
|
|
||||||
- key: WANDB_MODE
|
|
||||||
value: offline
|
|
||||||
- key: VOLUME_PREFIX
|
|
||||||
value: /mnt/xiaoai-zk-model-train-tj5
|
|
||||||
- key: HF_HOME
|
|
||||||
value: /mnt/wangsenhao/.hf_cache
|
|
||||||
|
|
||||||
# h20-96g 8 卡 FSDP2
|
|
||||||
queueId: "6052"
|
|
||||||
priority: 5
|
|
||||||
preemptible: false
|
|
||||||
framework: pytorch
|
|
||||||
resourceConfigs:
|
|
||||||
- nodeRole: worker
|
|
||||||
nodeNumber: 1
|
|
||||||
perNodeResourceSpec:
|
|
||||||
resourcePriority: GUARANTEED
|
|
||||||
resourceName: cloudml.ng2h20-8-8.20-199
|
|
||||||
resourceNumber: 8
|
|
||||||
|
|
||||||
# 故障自动重试(节点级失败)
|
|
||||||
retryConfig:
|
|
||||||
enableRetry: true
|
|
||||||
maxRetryTimes: 2
|
|
||||||
policySets:
|
|
||||||
- NodeFailure
|
|
||||||
|
|
||||||
# 失败/完成飞书告警
|
|
||||||
alertConfig:
|
|
||||||
enableAlert: true
|
|
||||||
alertItems:
|
|
||||||
- alertConditions:
|
|
||||||
- FAILED
|
|
||||||
- SUCCEED
|
|
||||||
alertLevel: P2
|
|
||||||
alertReceivers:
|
|
||||||
persons:
|
|
||||||
- wangsenhao
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
# 用 cml custom_train submit 提交 SFT 训练,训练完成后自动起 cml workflow run 评测
|
|
||||||
# 用法: ./submit_sft_via_cml.sh <RUNDIC>
|
|
||||||
# 例: ./submit_sft_via_cml.sh 17756
|
|
||||||
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
RUNDIC=${1:?usage: $0 <RUNDIC>}
|
|
||||||
PREV_RUNDIC=${2:-$((RUNDIC-1))}
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
||||||
ROOT=${AUTORESEARCH_ROOT:-/mnt/wangsenhao/autoresearch-zk}
|
|
||||||
MODEL_OLD=${MODEL_OLD:-/mnt/wangsenhao/verl_zk/qwen4b_cispo_wokl_add_bvt_2/global_step_5/actor/huggingface}
|
|
||||||
TPL=${SFT_TRAIN_JOB_TEMPLATE:-$SCRIPT_DIR/sft_train_job.yaml.tpl}
|
|
||||||
YAML=/tmp/sft_train_job_r${RUNDIC}.yaml
|
|
||||||
|
|
||||||
if [ -f ~/.cloudml-cli/.profile ]; then
|
|
||||||
source ~/.cloudml-cli/.profile
|
|
||||||
else
|
|
||||||
echo "[cml-sft] ❌ 未找到 ~/.cloudml-cli/.profile,请先安装并初始化 cml" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 1. 渲染 yaml 模板
|
|
||||||
sed \
|
|
||||||
-e "s|{RUNDIC}|${RUNDIC}|g" \
|
|
||||||
-e "s|{PREV_RUNDIC}|${PREV_RUNDIC}|g" \
|
|
||||||
-e "s|{AUTORESEARCH_ROOT}|${ROOT}|g" \
|
|
||||||
"$TPL" > "$YAML"
|
|
||||||
echo "[cml-sft] yaml: $YAML"
|
|
||||||
|
|
||||||
# 2. 提交训练任务
|
|
||||||
SUBMIT_OUT=$(cml custom_train submit --filename "$YAML" 2>&1)
|
|
||||||
echo "$SUBMIT_OUT"
|
|
||||||
JOB_ID=$(echo "$SUBMIT_OUT" | grep -oE 't-[0-9]+-[a-z0-9]+' | head -1)
|
|
||||||
if [ -z "$JOB_ID" ]; then
|
|
||||||
echo "[cml-sft] ❌ 提交失败" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "[cml-sft] ✅ JobID: $JOB_ID"
|
|
||||||
|
|
||||||
# 3. 后台 watcher:等训练成功 → 自动起评测
|
|
||||||
WATCHER_LOG=/tmp/r${RUNDIC}_logs/cml_watcher.log
|
|
||||||
mkdir -p "$(dirname "$WATCHER_LOG")"
|
|
||||||
|
|
||||||
nohup bash -c '
|
|
||||||
JOB_ID='"$JOB_ID"'
|
|
||||||
RUNDIC='"$RUNDIC"'
|
|
||||||
LOG='"$WATCHER_LOG"'
|
|
||||||
ROOT='"$ROOT"'
|
|
||||||
MODEL_NEW="$ROOT/sft_output"
|
|
||||||
MODEL_OLD='"$MODEL_OLD"'
|
|
||||||
EVAL_WORKFLOW_ID=f-20260408161444-wu3pz
|
|
||||||
EVAL_VERSION=v28
|
|
||||||
|
|
||||||
source ~/.cloudml-cli/.profile
|
|
||||||
|
|
||||||
echo "[$(date)] 等待 cml job $JOB_ID 完成..." >> "$LOG"
|
|
||||||
while true; do
|
|
||||||
STATE=$(cml custom_train describe "$JOB_ID" 2>/dev/null | grep -o "\"state\": \"[a-z]*\"" | head -1 | sed "s/.*: \"//;s/\"//")
|
|
||||||
case "$STATE" in
|
|
||||||
succeed)
|
|
||||||
echo "[$(date)] 训练成功" >> "$LOG"
|
|
||||||
break ;;
|
|
||||||
failed|killed)
|
|
||||||
echo "[$(date)] ❌ 训练 $STATE" >> "$LOG"
|
|
||||||
exit 1 ;;
|
|
||||||
*)
|
|
||||||
sleep 60 ;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
# 验证产出
|
|
||||||
[ ! -f "$MODEL_NEW/_SUCCESS" ] && [ ! -f "$MODEL_NEW/config.json" ] && {
|
|
||||||
echo "[$(date)] ❌ 产出缺失" >> "$LOG"; exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
# 起评测
|
|
||||||
echo "[$(date)] 启动 CML 评测 runDic=$RUNDIC" >> "$LOG"
|
|
||||||
cml workflow run \
|
|
||||||
--workflow_id $EVAL_WORKFLOW_ID --version $EVAL_VERSION \
|
|
||||||
--global_inputs runDic=$RUNDIC \
|
|
||||||
--global_inputs model_path_new=$MODEL_NEW \
|
|
||||||
--global_inputs model_path_old=$MODEL_OLD >> "$LOG" 2>&1
|
|
||||||
echo "[$(date)] cml workflow run 提交完成" >> "$LOG"
|
|
||||||
' > /tmp/r${RUNDIC}_logs/watcher_runner.log 2>&1 &
|
|
||||||
|
|
||||||
WATCHER_PID=$!
|
|
||||||
echo "[cml-sft] watcher PID: $WATCHER_PID(log: $WATCHER_LOG)"
|
|
||||||
|
|
||||||
# 4. 立即输出可查看命令
|
|
||||||
cat <<EOF
|
|
||||||
|
|
||||||
[cml-sft] 任务提交完成,关键命令:
|
|
||||||
查看任务状态: cml custom_train describe $JOB_ID
|
|
||||||
查看实时日志: cml custom_train logs $JOB_ID --follow
|
|
||||||
停止任务: cml custom_train kill $JOB_ID
|
|
||||||
watcher log: tail -f $WATCHER_LOG
|
|
||||||
|
|
||||||
训练完成后,evaluation workflow 会自动启动;评测产物在
|
|
||||||
/mnt/xiaoai-zk-model-train-tj5/workflow5/workflow${RUNDIC}/
|
|
||||||
|
|
||||||
JobID: $JOB_ID
|
|
||||||
RUNDIC: $RUNDIC
|
|
||||||
EOF
|
|
||||||
+1
-1
@@ -158,7 +158,7 @@ class AgentRuntimeConfig:
|
|||||||
cwd: Path
|
cwd: Path
|
||||||
max_turns: int = DEFAULT_MAX_TURNS
|
max_turns: int = DEFAULT_MAX_TURNS
|
||||||
command_timeout_seconds: float = 30.0
|
command_timeout_seconds: float = 30.0
|
||||||
max_output_chars: int = 12000
|
max_output_chars: int = 50000 # ≈ 20k token (Chinese/code mix ≈ 2.5 chars/token)
|
||||||
stream_model_responses: bool = False
|
stream_model_responses: bool = False
|
||||||
auto_snip_threshold_tokens: int | None = None
|
auto_snip_threshold_tokens: int | None = None
|
||||||
auto_compact_threshold_tokens: int | None = None
|
auto_compact_threshold_tokens: int | None = None
|
||||||
|
|||||||
@@ -774,6 +774,20 @@ print(f"{'appended' if MODE == 'a' else 'wrote'} {target} ({len(content)} chars)
|
|||||||
|
|
||||||
def resolve_workspace_path(self, raw_path: str) -> str:
|
def resolve_workspace_path(self, raw_path: str) -> str:
|
||||||
value = raw_path.strip() or '.'
|
value = raw_path.strip() or '.'
|
||||||
|
|
||||||
|
# 系统提示里给的"当前会话目录"通常是本地后端的绝对/相对路径,例如
|
||||||
|
# `.port_sessions/accounts/<acc>/sessions/<sid>/input` 或
|
||||||
|
# `/home/mi/.../.port_sessions/accounts/<acc>/sessions/<sid>/output/foo.csv`。
|
||||||
|
# 远端 Jupyter 没这套目录结构。识别这种 pattern 后,把 input/output/
|
||||||
|
# scratchpad bucket 映射到远端 workspace 的同名目录。
|
||||||
|
bucket_match = self._match_local_session_bucket(value)
|
||||||
|
if bucket_match is not None:
|
||||||
|
bucket, rest = bucket_match
|
||||||
|
tail = f'/{rest}' if rest else ''
|
||||||
|
return normalize_posix_path(
|
||||||
|
f'{self.binding.workspace_cwd}/{bucket}{tail}'
|
||||||
|
)
|
||||||
|
|
||||||
if value.startswith('/'):
|
if value.startswith('/'):
|
||||||
return normalize_posix_path(value)
|
return normalize_posix_path(value)
|
||||||
path = PurePosixPath(value)
|
path = PurePosixPath(value)
|
||||||
@@ -787,8 +801,34 @@ print(f"{'appended' if MODE == 'a' else 'wrote'} {target} ({len(content)} chars)
|
|||||||
if path.parts and path.parts[0] in {'scratchpad', 'scratch'}:
|
if path.parts and path.parts[0] in {'scratchpad', 'scratch'}:
|
||||||
tail = PurePosixPath(*path.parts[1:]) if len(path.parts) > 1 else PurePosixPath()
|
tail = PurePosixPath(*path.parts[1:]) if len(path.parts) > 1 else PurePosixPath()
|
||||||
return normalize_posix_path(f'{self.binding.workspace_cwd}/scratchpad/{tail}')
|
return normalize_posix_path(f'{self.binding.workspace_cwd}/scratchpad/{tail}')
|
||||||
|
if path.parts and path.parts[0] in {'input', 'inputs'}:
|
||||||
|
tail = PurePosixPath(*path.parts[1:]) if len(path.parts) > 1 else PurePosixPath()
|
||||||
|
return normalize_posix_path(f'{self.binding.workspace_cwd}/input/{tail}')
|
||||||
return normalize_posix_path(f'{self.binding.workspace_cwd}/{value}')
|
return normalize_posix_path(f'{self.binding.workspace_cwd}/{value}')
|
||||||
|
|
||||||
|
_LOCAL_SESSION_BUCKET_RE = re.compile(
|
||||||
|
r'(?:^|/)\.port_sessions/accounts/[^/]+/sessions/[^/]+/'
|
||||||
|
r'(?P<bucket>input|inputs|output|outputs|scratchpad|scratch)'
|
||||||
|
r'(?:/(?P<rest>.*))?$'
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _match_local_session_bucket(cls, raw: str) -> tuple[str, str] | None:
|
||||||
|
m = cls._LOCAL_SESSION_BUCKET_RE.search(raw)
|
||||||
|
if not m:
|
||||||
|
return None
|
||||||
|
bucket = m.group('bucket')
|
||||||
|
normalized = {
|
||||||
|
'input': 'input',
|
||||||
|
'inputs': 'input',
|
||||||
|
'output': 'output',
|
||||||
|
'outputs': 'output',
|
||||||
|
'scratchpad': 'scratchpad',
|
||||||
|
'scratch': 'scratchpad',
|
||||||
|
}[bucket]
|
||||||
|
rest = m.group('rest') or ''
|
||||||
|
return normalized, rest
|
||||||
|
|
||||||
def _remote_env_prefix(self) -> str:
|
def _remote_env_prefix(self) -> str:
|
||||||
exports = {
|
exports = {
|
||||||
'ZK_AGENT_WORKSPACE': self.binding.workspace_cwd,
|
'ZK_AGENT_WORKSPACE': self.binding.workspace_cwd,
|
||||||
|
|||||||
+23
-21
@@ -15,28 +15,28 @@ from .agent_types import (
|
|||||||
OutputSchemaConfig,
|
OutputSchemaConfig,
|
||||||
UsageStats,
|
UsageStats,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class StoredSession:
|
class StoredSession:
|
||||||
session_id: str
|
session_id: str
|
||||||
messages: tuple[str, ...]
|
messages: tuple[str, ...]
|
||||||
input_tokens: int
|
input_tokens: int
|
||||||
output_tokens: int
|
output_tokens: int
|
||||||
|
|
||||||
|
|
||||||
DEFAULT_SESSION_DIR = Path('.port_sessions')
|
DEFAULT_SESSION_DIR = Path('.port_sessions')
|
||||||
DEFAULT_AGENT_SESSION_DIR = DEFAULT_SESSION_DIR / 'agent'
|
DEFAULT_AGENT_SESSION_DIR = DEFAULT_SESSION_DIR / 'agent'
|
||||||
|
|
||||||
|
|
||||||
def save_session(session: StoredSession, directory: Path | None = None) -> Path:
|
def save_session(session: StoredSession, directory: Path | None = None) -> Path:
|
||||||
target_dir = directory or DEFAULT_SESSION_DIR
|
target_dir = directory or DEFAULT_SESSION_DIR
|
||||||
target_dir.mkdir(parents=True, exist_ok=True)
|
target_dir.mkdir(parents=True, exist_ok=True)
|
||||||
path = target_dir / f'{session.session_id}.json'
|
path = target_dir / f'{session.session_id}.json'
|
||||||
path.write_text(json.dumps(asdict(session), indent=2))
|
path.write_text(json.dumps(asdict(session), indent=2))
|
||||||
return path
|
return path
|
||||||
|
|
||||||
|
|
||||||
def load_session(session_id: str, directory: Path | None = None) -> StoredSession:
|
def load_session(session_id: str, directory: Path | None = None) -> StoredSession:
|
||||||
target_dir = directory or DEFAULT_SESSION_DIR
|
target_dir = directory or DEFAULT_SESSION_DIR
|
||||||
data = json.loads((target_dir / f'{session_id}.json').read_text())
|
data = json.loads((target_dir / f'{session_id}.json').read_text())
|
||||||
@@ -68,6 +68,7 @@ class StoredAgentSession:
|
|||||||
budget_state: JSONDict
|
budget_state: JSONDict
|
||||||
plugin_state: JSONDict
|
plugin_state: JSONDict
|
||||||
scratchpad_directory: str | None = None
|
scratchpad_directory: str | None = None
|
||||||
|
is_training: bool = False
|
||||||
|
|
||||||
|
|
||||||
def save_agent_session(session: StoredAgentSession, directory: Path | None = None) -> Path:
|
def save_agent_session(session: StoredAgentSession, directory: Path | None = None) -> Path:
|
||||||
@@ -118,6 +119,7 @@ def load_agent_session(session_id: str, directory: Path | None = None) -> Stored
|
|||||||
if isinstance(data.get('scratchpad_directory'), str)
|
if isinstance(data.get('scratchpad_directory'), str)
|
||||||
else None
|
else None
|
||||||
),
|
),
|
||||||
|
is_training=bool(data.get('is_training', False)),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -222,7 +224,7 @@ def deserialize_runtime_config(payload: JSONDict) -> AgentRuntimeConfig:
|
|||||||
cwd=Path(str(payload['cwd'])).resolve(),
|
cwd=Path(str(payload['cwd'])).resolve(),
|
||||||
max_turns=int(payload.get('max_turns', DEFAULT_MAX_TURNS)),
|
max_turns=int(payload.get('max_turns', DEFAULT_MAX_TURNS)),
|
||||||
command_timeout_seconds=float(payload.get('command_timeout_seconds', 30.0)),
|
command_timeout_seconds=float(payload.get('command_timeout_seconds', 30.0)),
|
||||||
max_output_chars=int(payload.get('max_output_chars', 12000)),
|
max_output_chars=int(payload.get('max_output_chars', 50000)),
|
||||||
stream_model_responses=bool(payload.get('stream_model_responses', False)),
|
stream_model_responses=bool(payload.get('stream_model_responses', False)),
|
||||||
auto_snip_threshold_tokens=_optional_int(payload.get('auto_snip_threshold_tokens')),
|
auto_snip_threshold_tokens=_optional_int(payload.get('auto_snip_threshold_tokens')),
|
||||||
auto_compact_threshold_tokens=_optional_int(payload.get('auto_compact_threshold_tokens')),
|
auto_compact_threshold_tokens=_optional_int(payload.get('auto_compact_threshold_tokens')),
|
||||||
|
|||||||
Reference in New Issue
Block a user