修改
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
import { loginByEmail } from "@/lib/claw-auth";
|
||||
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
const payload = (await req.json()) as {
|
||||
email?: string;
|
||||
password?: string;
|
||||
};
|
||||
const account = await loginByEmail(
|
||||
payload.email ?? "",
|
||||
payload.password ?? "",
|
||||
);
|
||||
return Response.json({ account });
|
||||
} catch (err) {
|
||||
return Response.json(
|
||||
{ error: err instanceof Error ? err.message : "登录失败" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { registerByEmail } from "@/lib/claw-auth";
|
||||
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
const payload = (await req.json()) as {
|
||||
email?: string;
|
||||
password?: string;
|
||||
};
|
||||
const account = await registerByEmail(
|
||||
payload.email ?? "",
|
||||
payload.password ?? "",
|
||||
);
|
||||
return Response.json({ account });
|
||||
} catch (err) {
|
||||
return Response.json(
|
||||
{ error: err instanceof Error ? err.message : "注册失败" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { getCurrentAccount } from "@/lib/claw-auth";
|
||||
|
||||
const CLAW_API_URL = process.env.CLAW_API_URL ?? "http://127.0.0.1:8765";
|
||||
|
||||
type BindBody = {
|
||||
session_id?: string;
|
||||
};
|
||||
|
||||
export async function POST(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ workspaceId: string }> },
|
||||
) {
|
||||
const account = await getCurrentAccount();
|
||||
if (!account)
|
||||
return Response.json({ error: "请先登录账号" }, { status: 401 });
|
||||
|
||||
const { workspaceId } = await params;
|
||||
const payload = (await req.json()) as BindBody;
|
||||
try {
|
||||
const target = `${CLAW_API_URL}/api/jupyter/workspaces/${encodeURIComponent(workspaceId)}/bind`;
|
||||
const response = await fetch(target, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
session_id: payload.session_id,
|
||||
account_id: account.id,
|
||||
}),
|
||||
cache: "no-store",
|
||||
});
|
||||
const body = await response.text();
|
||||
return new Response(body, {
|
||||
status: response.status,
|
||||
headers: {
|
||||
"content-type":
|
||||
response.headers.get("content-type") ?? "application/json",
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
return Response.json(
|
||||
{
|
||||
error:
|
||||
err instanceof Error
|
||||
? `Unable to reach Claw backend: ${err.message}`
|
||||
: "Unable to reach Claw backend",
|
||||
},
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { getCurrentAccount } from "@/lib/claw-auth";
|
||||
|
||||
const CLAW_API_URL = process.env.CLAW_API_URL ?? "http://127.0.0.1:8765";
|
||||
|
||||
export async function DELETE(
|
||||
_req: Request,
|
||||
{ params }: { params: Promise<{ workspaceId: string }> },
|
||||
) {
|
||||
const account = await getCurrentAccount();
|
||||
if (!account)
|
||||
return Response.json({ error: "请先登录账号" }, { status: 401 });
|
||||
|
||||
const { workspaceId } = await params;
|
||||
try {
|
||||
const target = new URL(
|
||||
`${CLAW_API_URL}/api/jupyter/workspaces/${encodeURIComponent(workspaceId)}`,
|
||||
);
|
||||
target.searchParams.set("account_id", account.id);
|
||||
const response = await fetch(target, {
|
||||
method: "DELETE",
|
||||
cache: "no-store",
|
||||
});
|
||||
const body = await response.text();
|
||||
return new Response(body, {
|
||||
status: response.status,
|
||||
headers: {
|
||||
"content-type":
|
||||
response.headers.get("content-type") ?? "application/json",
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
return Response.json(
|
||||
{
|
||||
error:
|
||||
err instanceof Error
|
||||
? `Unable to reach Claw backend: ${err.message}`
|
||||
: "Unable to reach Claw backend",
|
||||
},
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
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() {
|
||||
const account = await getCurrentAccount();
|
||||
if (!account)
|
||||
return Response.json({ error: "请先登录账号" }, { status: 401 });
|
||||
|
||||
try {
|
||||
const target = new URL(`${CLAW_API_URL}/api/jupyter/workspaces`);
|
||||
target.searchParams.set("account_id", account.id);
|
||||
const response = await fetch(target, { cache: "no-store" });
|
||||
const body = await response.text();
|
||||
return new Response(body, {
|
||||
status: response.status,
|
||||
headers: {
|
||||
"content-type":
|
||||
response.headers.get("content-type") ?? "application/json",
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
return Response.json(
|
||||
{
|
||||
error:
|
||||
err instanceof Error
|
||||
? `Unable to reach Claw backend: ${err.message}`
|
||||
: "Unable to reach Claw backend",
|
||||
},
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -182,6 +182,8 @@ const APPLY_INTENT_PATTERNS: RegExp[] = [
|
||||
/(?:进行|开始|启动|开启|执行|发起|做)\s*(?:模型)?\s*训练/i,
|
||||
// 训练 + 目标集合
|
||||
/训练[\s\S]{0,60}?(?:目标集合|需求集合|specific[\s_-]?test|集合)/i,
|
||||
// 「(模型)训练,目标是 X」「训练,基模 X」「训练 ... csv」之类自然表达
|
||||
/(?:^|[\s,,。.!?])(?:模型)?训练[\s,,][\s\S]{0,80}?(?:目标|基模|specific[\s_-]?test|\.csv)/i,
|
||||
// 跟着 program.md 的旧表达保留
|
||||
/(?:应用|加载|载入|启用|装载|使用|跑|按照?|根据|用)\s*\S*program\.?md/i,
|
||||
/program\.?md[\s\S]{0,120}?(?:训练|应用|启用|跑起来|跑一下)/i,
|
||||
@@ -204,6 +206,42 @@ function AssistantWorkspace() {
|
||||
const showPipeline = skill.enabled && applied;
|
||||
const messages = useAuiState((s) => s.thread.messages);
|
||||
const lastProcessedUserMsgId = useRef<string | null>(null);
|
||||
const pipelineContainerRef = useRef<HTMLDivElement>(null);
|
||||
const lastPipelineYRef = useRef<number | null>(null);
|
||||
const [exitButtonVisible, setExitButtonVisible] = useState(false);
|
||||
|
||||
const handlePipelineMouseMove = useCallback(
|
||||
(event: React.MouseEvent<HTMLDivElement>) => {
|
||||
const node = pipelineContainerRef.current;
|
||||
if (!node) return;
|
||||
const rect = node.getBoundingClientRect();
|
||||
const relativeY = event.clientY - rect.top;
|
||||
const inTopThird = relativeY >= 0 && relativeY <= rect.height / 3;
|
||||
const lastY = lastPipelineYRef.current;
|
||||
const movingUp = lastY !== null && event.clientY < lastY;
|
||||
const movingDown = lastY !== null && event.clientY > lastY;
|
||||
lastPipelineYRef.current = event.clientY;
|
||||
setExitButtonVisible((prev) => {
|
||||
if (!inTopThird) return false;
|
||||
if (movingUp) return true;
|
||||
if (movingDown) return false;
|
||||
return prev;
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handlePipelineMouseLeave = useCallback(() => {
|
||||
lastPipelineYRef.current = null;
|
||||
setExitButtonVisible(false);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!showPipeline) {
|
||||
lastPipelineYRef.current = null;
|
||||
setExitButtonVisible(false);
|
||||
}
|
||||
}, [showPipeline]);
|
||||
|
||||
useEffect(() => {
|
||||
const update = () => setActiveSessionId(readActiveSessionId());
|
||||
@@ -235,31 +273,52 @@ function AssistantWorkspace() {
|
||||
// 自动应用:skill 启用 + 当前 session 后端的 pipeline 已经有进展(任何
|
||||
// 卡 running 或 complete)→ applied=true。这样关 tab 重开 / 刷新 / 切回
|
||||
// 已在跑的会话都能自动恢复 monitor 面板,不依赖触发词。
|
||||
// 30 秒轮询一次,覆盖「页面打开时 pipeline 还没起、之后才被外部脚本启动」
|
||||
// 这类情形——一次性 fetch 容易错过。
|
||||
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) => {
|
||||
const tick = async () => {
|
||||
try {
|
||||
const res = await fetch(url, { cache: "no-store" });
|
||||
if (!res.ok) return;
|
||||
const payload = await res.json();
|
||||
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",
|
||||
),
|
||||
const items = Array.isArray(payload.items) ? payload.items : [];
|
||||
const hasItemProgress = items.some(
|
||||
(it: {
|
||||
type?: string;
|
||||
status?: string;
|
||||
cards?: Array<{ status?: string }>;
|
||||
}) => {
|
||||
if (it.type === "gate") {
|
||||
return it.status === "running" || it.status === "complete";
|
||||
}
|
||||
return (
|
||||
Array.isArray(it.cards) &&
|
||||
it.cards.some(
|
||||
(c) =>
|
||||
c.status === "running" || c.status === "complete",
|
||||
)
|
||||
);
|
||||
},
|
||||
);
|
||||
if (hasProgress) setApplied(true);
|
||||
})
|
||||
.catch(() => {
|
||||
// items[] 走 phase-complete-only 过滤;R0 只有一张卡在跑时
|
||||
// items 是空的,进展信号在 in_flight 字段里——也算进展。
|
||||
const hasInFlight = Boolean(payload.in_flight);
|
||||
if (hasItemProgress || hasInFlight) setApplied(true);
|
||||
} catch {
|
||||
/* ignore */
|
||||
});
|
||||
}
|
||||
};
|
||||
tick();
|
||||
const id = window.setInterval(tick, 30000);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.clearInterval(id);
|
||||
};
|
||||
}, [skill.enabled, applied, activeSessionId, setApplied]);
|
||||
|
||||
@@ -293,15 +352,24 @@ function AssistantWorkspace() {
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 overflow-hidden">
|
||||
{showPipeline ? (
|
||||
<div className="relative flex min-w-0 flex-1 flex-col">
|
||||
<div
|
||||
ref={pipelineContainerRef}
|
||||
onMouseMove={handlePipelineMouseMove}
|
||||
onMouseLeave={handlePipelineMouseLeave}
|
||||
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"
|
||||
className={cn(
|
||||
"-translate-x-1/2 absolute top-0 left-1/2 z-20 inline-flex items-center gap-1 rounded-b-md border-x border-b border-border bg-background px-3 py-1 text-muted-foreground text-xs shadow-md ring-offset-background transition-transform duration-200 hover:bg-muted hover:text-foreground focus:outline-hidden focus:ring-2 focus:ring-ring focus:ring-offset-2",
|
||||
exitButtonVisible ? "translate-y-0" : "-translate-y-full",
|
||||
)}
|
||||
>
|
||||
<XIcon className="size-3.5" />
|
||||
<span>退出训练模式</span>
|
||||
</button>
|
||||
<TrainingPipelinePanel sessionId={activeSessionId} />
|
||||
</div>
|
||||
@@ -309,9 +377,7 @@ function AssistantWorkspace() {
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col overflow-hidden",
|
||||
showPipeline
|
||||
? "w-[28rem] shrink-0 border-l"
|
||||
: "min-w-0 flex-1",
|
||||
showPipeline ? "w-[28rem] shrink-0 border-l" : "min-w-0 flex-1",
|
||||
)}
|
||||
>
|
||||
<div className="min-h-0 flex-1 overflow-hidden">
|
||||
|
||||
@@ -36,36 +36,59 @@ export function useClawAccount() {
|
||||
return { account, isLoading, refresh, setAccount };
|
||||
}
|
||||
|
||||
const XIAOMI_EMAIL_RE = /^[\w.-]+@xiaomi\.com$/i;
|
||||
|
||||
export function ClawAccountGate({
|
||||
onAccount,
|
||||
}: {
|
||||
onAccount: (account: ClawAccount) => void;
|
||||
}) {
|
||||
const [mode, setMode] = useState<"login" | "register">("login");
|
||||
const [username, setUsername] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
async function submit() {
|
||||
setError("");
|
||||
const trimmed = email.trim();
|
||||
if (!XIAOMI_EMAIL_RE.test(trimmed)) {
|
||||
setError("请使用小米邮箱(@xiaomi.com)登录");
|
||||
return;
|
||||
}
|
||||
if (password.length < 6) {
|
||||
setError("密码至少 6 位");
|
||||
return;
|
||||
}
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const response = await fetch(`/api/claw/auth/${mode}`, {
|
||||
const endpoint =
|
||||
mode === "register"
|
||||
? "/api/claw/auth/email-register"
|
||||
: "/api/claw/auth/email-login";
|
||||
const response = await fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ username, password }),
|
||||
body: JSON.stringify({ email: trimmed, password }),
|
||||
});
|
||||
const payload = (await response.json()) as {
|
||||
account?: ClawAccount;
|
||||
error?: string;
|
||||
};
|
||||
if (!response.ok || !payload.account) {
|
||||
throw new Error(payload.error ?? "账号操作失败");
|
||||
throw new Error(
|
||||
payload.error ?? (mode === "register" ? "注册失败" : "登录失败"),
|
||||
);
|
||||
}
|
||||
onAccount(payload.account);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "账号操作失败");
|
||||
setError(
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: mode === "register"
|
||||
? "注册失败"
|
||||
: "登录失败",
|
||||
);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
@@ -77,22 +100,25 @@ export function ClawAccountGate({
|
||||
<div className="mb-6">
|
||||
<h1 className="font-semibold text-xl">ZK Data Agent</h1>
|
||||
<p className="mt-1 text-muted-foreground text-sm">
|
||||
中控数据开发平台会按账号隔离会话、上传文件和生成产物。
|
||||
{mode === "register"
|
||||
? "创建账号:使用小米邮箱注册,前缀作为 autoresearch 工作根目录。"
|
||||
: "使用小米邮箱登录。会话/上传/产物按邮箱前缀和 chat 二级隔离。"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid gap-3">
|
||||
<Input
|
||||
autoFocus
|
||||
placeholder="账号"
|
||||
value={username}
|
||||
onChange={(event) => setUsername(event.target.value)}
|
||||
type="email"
|
||||
placeholder="your_name@xiaomi.com"
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") submit();
|
||||
}}
|
||||
/>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="密码"
|
||||
placeholder={mode === "register" ? "设置密码(≥6 位)" : "密码"}
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
@@ -101,7 +127,7 @@ export function ClawAccountGate({
|
||||
/>
|
||||
{error ? <p className="text-destructive text-sm">{error}</p> : null}
|
||||
<Button onClick={submit} disabled={isSubmitting}>
|
||||
{isSubmitting ? "处理中..." : mode === "login" ? "登录" : "注册"}
|
||||
{isSubmitting ? "处理中..." : mode === "register" ? "注册" : "登录"}
|
||||
</Button>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -100,15 +100,15 @@
|
||||
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);
|
||||
0 0 0 1px rgb(56 189 248 / 0.3),
|
||||
0 0 0 0 rgb(56 189 248 / 0);
|
||||
border-color: rgb(56 189 248 / 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);
|
||||
0 0 0 1px rgb(56 189 248 / 0.7),
|
||||
0 0 10px 2px rgb(56 189 248 / 0.35);
|
||||
border-color: rgb(56 189 248 / 0.85);
|
||||
}
|
||||
}
|
||||
--animate-pipeline-dot-ping: pipeline-dot-ping 1400ms ease-out infinite;
|
||||
|
||||
@@ -212,6 +212,7 @@ export function ActivityPanel({ asDrawer = false }: { asDrawer?: boolean } = {})
|
||||
useEffect(() => {
|
||||
const latestId = items.at(-1)?.id ?? null;
|
||||
if (
|
||||
!asDrawer &&
|
||||
mode === "activity" &&
|
||||
!selectedId &&
|
||||
latestId &&
|
||||
@@ -220,7 +221,7 @@ export function ActivityPanel({ asDrawer = false }: { asDrawer?: boolean } = {})
|
||||
openActivity();
|
||||
}
|
||||
prevLatestIdRef.current = latestId;
|
||||
}, [items, mode, openActivity, selectedId]);
|
||||
}, [asDrawer, items, mode, openActivity, selectedId]);
|
||||
|
||||
if (!asDrawer && !open) return null;
|
||||
|
||||
@@ -269,6 +270,7 @@ export function ActivityPanel({ asDrawer = false }: { asDrawer?: boolean } = {})
|
||||
open={selectedId === item.id}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (nextOpen) openItem(item.id);
|
||||
else if (selectedId === item.id) openActivity();
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -6,10 +6,13 @@ import {
|
||||
import { ThreadListPrimitive } from "@assistant-ui/react";
|
||||
import type { UIMessage } from "ai";
|
||||
import {
|
||||
Loader2Icon,
|
||||
MoreHorizontalIcon,
|
||||
PencilIcon,
|
||||
PlusIcon,
|
||||
ServerIcon,
|
||||
Trash2Icon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
type FC,
|
||||
@@ -23,6 +26,7 @@ import {
|
||||
clearActiveSessionId,
|
||||
readActiveSessionId,
|
||||
writeActiveSessionId,
|
||||
writePendingWorkspaceSessionId,
|
||||
} from "@/lib/claw-active-session";
|
||||
import { useClawSessionReplay } from "@/lib/claw-session-replay";
|
||||
import { pushHomeUrl, pushSessionUrl } from "@/lib/claw-session-url";
|
||||
@@ -112,6 +116,7 @@ export const ThreadList: FC = () => {
|
||||
return (
|
||||
<ThreadListPrimitive.Root className="aui-root aui-thread-list-root flex min-h-0 flex-1 flex-col gap-1">
|
||||
<ThreadListNew />
|
||||
<JupyterWorkspaceList />
|
||||
<ClawSessionList />
|
||||
</ThreadListPrimitive.Root>
|
||||
);
|
||||
@@ -139,6 +144,177 @@ const ThreadListNew: FC = () => {
|
||||
);
|
||||
};
|
||||
|
||||
type JupyterWorkspaceEntry = {
|
||||
id: string;
|
||||
label?: string;
|
||||
base_url?: string;
|
||||
workspace_root?: string;
|
||||
created_at?: number;
|
||||
last_used_at?: number;
|
||||
};
|
||||
|
||||
function ensureSidebarWorkspaceSessionId(): {
|
||||
sessionId: string;
|
||||
created: boolean;
|
||||
} {
|
||||
const existing = readActiveSessionId();
|
||||
if (existing) return { sessionId: existing, created: false };
|
||||
const generated =
|
||||
typeof crypto !== "undefined" && "randomUUID" in crypto
|
||||
? `__LOCALID_${crypto.randomUUID().replace(/-/g, "").slice(0, 8)}`
|
||||
: `__LOCALID_${Math.random().toString(36).slice(2, 10)}`;
|
||||
writeActiveSessionId(generated);
|
||||
return { sessionId: generated, created: true };
|
||||
}
|
||||
|
||||
function workspaceDisplayLabel(entry: JupyterWorkspaceEntry): string {
|
||||
if (entry.label && entry.label.trim()) return entry.label.trim();
|
||||
if (entry.base_url) {
|
||||
try {
|
||||
return new URL(entry.base_url).host;
|
||||
} catch {
|
||||
return entry.base_url;
|
||||
}
|
||||
}
|
||||
return entry.id;
|
||||
}
|
||||
|
||||
const JupyterWorkspaceList: FC = () => {
|
||||
const [entries, setEntries] = useState<JupyterWorkspaceEntry[]>([]);
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [bindingId, setBindingId] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const refresh = () => {
|
||||
fetch("/api/claw/jupyter/workspaces", { cache: "no-store" })
|
||||
.then((res) => (res.ok ? res.json() : []))
|
||||
.then((payload) => {
|
||||
if (cancelled) return;
|
||||
if (Array.isArray(payload)) {
|
||||
setEntries(payload as JupyterWorkspaceEntry[]);
|
||||
} else {
|
||||
setEntries([]);
|
||||
}
|
||||
setLoaded(true);
|
||||
})
|
||||
.catch(() => {
|
||||
if (cancelled) return;
|
||||
setEntries([]);
|
||||
setLoaded(true);
|
||||
});
|
||||
};
|
||||
refresh();
|
||||
const onChanged = () => refresh();
|
||||
window.addEventListener("claw-workspaces-changed", onChanged);
|
||||
window.addEventListener("focus", refresh);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.removeEventListener("claw-workspaces-changed", onChanged);
|
||||
window.removeEventListener("focus", refresh);
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (!loaded || entries.length === 0) return null;
|
||||
|
||||
const bind = async (entry: JupyterWorkspaceEntry) => {
|
||||
setError(null);
|
||||
setBindingId(entry.id);
|
||||
const { sessionId, created } = ensureSidebarWorkspaceSessionId();
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/claw/jupyter/workspaces/${encodeURIComponent(entry.id)}/bind`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ session_id: sessionId }),
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
const payload = (await response.json().catch(() => ({}))) as {
|
||||
detail?: string;
|
||||
error?: string;
|
||||
};
|
||||
setError(payload.detail ?? payload.error ?? "切换工作区失败");
|
||||
return;
|
||||
}
|
||||
if (created) writePendingWorkspaceSessionId(sessionId);
|
||||
window.dispatchEvent(new Event("claw-sessions-changed"));
|
||||
window.dispatchEvent(new Event("claw-workspaces-changed"));
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof Error ? err.message : "切换工作区时网络异常",
|
||||
);
|
||||
} finally {
|
||||
setBindingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (entry: JupyterWorkspaceEntry) => {
|
||||
if (!window.confirm(`移除工作区「${workspaceDisplayLabel(entry)}」?`)) return;
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/claw/jupyter/workspaces/${encodeURIComponent(entry.id)}`,
|
||||
{ method: "DELETE" },
|
||||
);
|
||||
if (!response.ok) return;
|
||||
setEntries((current) => current.filter((e) => e.id !== entry.id));
|
||||
} catch {
|
||||
// best effort; next refresh will reconcile
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mt-1 flex flex-col gap-1 border-y border-dashed py-2">
|
||||
<div className="flex items-center gap-1.5 px-2 text-muted-foreground text-xs uppercase tracking-wide">
|
||||
<ServerIcon className="size-3" />
|
||||
<span>工作区</span>
|
||||
</div>
|
||||
<div className="flex flex-col gap-0.5">
|
||||
{entries.map((entry) => {
|
||||
const label = workspaceDisplayLabel(entry);
|
||||
const subtitle = entry.workspace_root ?? "";
|
||||
const isBinding = bindingId === entry.id;
|
||||
return (
|
||||
<div
|
||||
key={entry.id}
|
||||
className="group relative flex h-9 items-center gap-1 rounded-lg transition-colors hover:bg-muted"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
disabled={isBinding}
|
||||
onClick={() => void bind(entry)}
|
||||
className="flex h-full min-w-0 flex-1 items-center gap-2 rounded-lg px-3 text-left text-sm disabled:cursor-wait"
|
||||
title={`${entry.base_url ?? ""}${subtitle ? ` · ${subtitle}` : ""}`}
|
||||
>
|
||||
{isBinding ? (
|
||||
<Loader2Icon className="size-3.5 shrink-0 animate-spin" />
|
||||
) : (
|
||||
<ServerIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate">{label}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="移除工作区"
|
||||
title="移除工作区"
|
||||
onClick={() => void remove(entry)}
|
||||
className="mr-1 hidden size-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-background hover:text-foreground group-hover:flex"
|
||||
>
|
||||
<XIcon className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{error ? (
|
||||
<div className="px-2 text-destructive text-xs">{error}</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const ClawSessionList: FC = () => {
|
||||
const { replaySession } = useClawSessionReplay();
|
||||
const [sessions, setSessions] = useState<ClawSession[]>([]);
|
||||
|
||||
@@ -273,7 +273,25 @@ function useRefreshCurrentRun() {
|
||||
const runStatus = await fetchLatestRunStatus(sessionId);
|
||||
if (cancelled) return;
|
||||
if (runStatus?.status === "queued" || runStatus?.status === "running") {
|
||||
activeRunRef.current = runStatus.run_id ?? "active";
|
||||
const runKey = runStatus.run_id ?? "active";
|
||||
const previousRunKey = activeRunRef.current;
|
||||
activeRunRef.current = runKey;
|
||||
// Watcher auto-resume: backend started a new run via _maybe_auto_resume
|
||||
// without a local SSE stream driving the UI. We need to replay once so
|
||||
// the active-run placeholder (pending prompt + 思考中 bubble) appears.
|
||||
// useRefreshReplayedRun will take over polling once replayedRun.active
|
||||
// becomes true.
|
||||
if (!runtimeRunning && previousRunKey !== runKey) {
|
||||
const response = await fetch(`/api/claw/sessions/${sessionId}`, {
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!response.ok || cancelled) return;
|
||||
const payload = await response.json();
|
||||
replaySession(
|
||||
sessionId,
|
||||
toReplayRepository(payload, sessionId, runStatus),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!runtimeRunning && !activeRunRef.current) return;
|
||||
@@ -632,6 +650,7 @@ function WorkspaceSwitchDialog({
|
||||
if (needsFirstMessageSession) {
|
||||
writePendingWorkspaceSessionId(sessionIdForRequest);
|
||||
}
|
||||
window.dispatchEvent(new Event("claw-workspaces-changed"));
|
||||
setStatus(payload as JupyterWorkspaceStatus);
|
||||
setProgress({ percent: 100, label: "切换完成" });
|
||||
setMessage("工作区切换成功,后续工具会在远端 Jupyter 工作区执行。");
|
||||
@@ -1186,6 +1205,7 @@ function ModelPickerButton({
|
||||
};
|
||||
}) {
|
||||
const [query, setQuery] = useState("");
|
||||
const [open, setOpen] = useState(false);
|
||||
const normalizedQuery = query.trim().toLowerCase();
|
||||
const filteredModels = useMemo(() => {
|
||||
if (!normalizedQuery) return status.models;
|
||||
@@ -1199,7 +1219,7 @@ function ModelPickerButton({
|
||||
}, [normalizedQuery, status.models]);
|
||||
|
||||
return (
|
||||
<PopoverPrimitive.Root>
|
||||
<PopoverPrimitive.Root open={open} onOpenChange={setOpen}>
|
||||
<PopoverPrimitive.Trigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
@@ -1240,7 +1260,10 @@ function ModelPickerButton({
|
||||
key={model.id}
|
||||
type="button"
|
||||
className="flex h-8 w-full items-center justify-between gap-2 rounded-lg px-2 text-left text-sm hover:bg-muted"
|
||||
onClick={() => status.setModel(model.id)}
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
void status.setModel(model.id);
|
||||
}}
|
||||
>
|
||||
<span className="min-w-0 flex-1 truncate">{model.id}</span>
|
||||
<span className="shrink-0 text-muted-foreground text-xs">
|
||||
|
||||
@@ -1,18 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import { ExternalLinkIcon, FileIcon, RefreshCwIcon } from "lucide-react";
|
||||
import {
|
||||
ExternalLinkIcon,
|
||||
FileIcon,
|
||||
RefreshCwIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";
|
||||
import {
|
||||
Sheet,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type TableSection = {
|
||||
title: string;
|
||||
source_path: string;
|
||||
kind: "csv" | "jsonl" | "text" | "markdown" | "missing" | "error";
|
||||
columns: string[];
|
||||
rows: string[][];
|
||||
total_rows: number;
|
||||
shown_rows: number;
|
||||
error?: string;
|
||||
body?: string;
|
||||
};
|
||||
|
||||
type StepDetail = {
|
||||
step: string;
|
||||
run_dic: number | null;
|
||||
format: "markdown" | "jsonl" | "json" | "csv" | "text" | "empty";
|
||||
content: string;
|
||||
format:
|
||||
| "markdown"
|
||||
| "jsonl"
|
||||
| "json"
|
||||
| "csv"
|
||||
| "text"
|
||||
| "empty"
|
||||
| "tables";
|
||||
content?: string;
|
||||
sections?: TableSection[];
|
||||
source_path: string | null;
|
||||
fetched_at_ms: number;
|
||||
error?: string;
|
||||
@@ -65,6 +95,7 @@ export function StepDetailSheet({
|
||||
<Sheet open={open} onOpenChange={onOpenChange}>
|
||||
<SheetContent
|
||||
side="right"
|
||||
hideClose
|
||||
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">
|
||||
@@ -87,17 +118,25 @@ export function StepDetailSheet({
|
||||
</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>
|
||||
<div className="mt-0.5 flex shrink-0 items-center gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-7"
|
||||
onClick={() => setReloadCount((c) => c + 1)}
|
||||
title="刷新"
|
||||
aria-label="刷新"
|
||||
>
|
||||
<RefreshCwIcon className="size-3.5" />
|
||||
</Button>
|
||||
<SheetClose
|
||||
className="inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus:outline-hidden focus:ring-2 focus:ring-ring focus:ring-offset-2"
|
||||
aria-label="关闭"
|
||||
>
|
||||
<XIcon className="size-3.5" />
|
||||
</SheetClose>
|
||||
</div>
|
||||
</header>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-5 py-4 text-sm">
|
||||
{loading ? (
|
||||
@@ -106,14 +145,16 @@ export function StepDetailSheet({
|
||||
<p className="text-muted-foreground text-xs">无法获取详情</p>
|
||||
) : detail.format === "empty" ? (
|
||||
<EmptyView detail={detail} />
|
||||
) : detail.format === "tables" ? (
|
||||
<TablesView sections={detail.sections ?? []} />
|
||||
) : detail.format === "markdown" ? (
|
||||
<MarkdownView text={detail.content} />
|
||||
<MarkdownView text={detail.content ?? ""} />
|
||||
) : detail.format === "json" ? (
|
||||
<JsonView text={detail.content} />
|
||||
<JsonView text={detail.content ?? ""} />
|
||||
) : detail.format === "jsonl" ? (
|
||||
<JsonLinesView text={detail.content} />
|
||||
<JsonLinesView text={detail.content ?? ""} />
|
||||
) : (
|
||||
<RawView text={detail.content} />
|
||||
<RawView text={detail.content ?? ""} />
|
||||
)}
|
||||
</div>
|
||||
{detail?.source_path && !loading ? (
|
||||
@@ -939,6 +980,153 @@ function MarkdownView({ text }: { text: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
function TablesView({ sections }: { sections: TableSection[] }) {
|
||||
if (sections.length === 0) {
|
||||
return <p className="text-muted-foreground text-xs">空内容。</p>;
|
||||
}
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{sections.map((section, idx) => (
|
||||
<TableSectionCard
|
||||
key={`${section.title}-${idx}`}
|
||||
section={section}
|
||||
defaultOpen={idx <= 1}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TableSectionCard({
|
||||
section,
|
||||
defaultOpen,
|
||||
}: {
|
||||
section: TableSection;
|
||||
defaultOpen: boolean;
|
||||
}) {
|
||||
const isMissing = section.kind === "missing" || section.kind === "error";
|
||||
const isMarkdown = section.kind === "markdown";
|
||||
const truncated =
|
||||
section.shown_rows > 0 && section.shown_rows < section.total_rows;
|
||||
const noteParts: string[] = [];
|
||||
if (section.total_rows > 0) {
|
||||
noteParts.push(`共 ${section.total_rows} 行`);
|
||||
if (truncated) {
|
||||
noteParts.push(`仅显示前 ${section.shown_rows} 行`);
|
||||
}
|
||||
}
|
||||
if (section.kind === "csv") noteParts.push("CSV");
|
||||
else if (section.kind === "jsonl") noteParts.push("JSONL");
|
||||
else if (section.kind === "text") noteParts.push("TEXT");
|
||||
else if (section.kind === "markdown") noteParts.push("MARKDOWN");
|
||||
|
||||
return (
|
||||
<details
|
||||
open={defaultOpen && !isMissing}
|
||||
className="group rounded-lg border bg-card shadow-sm"
|
||||
>
|
||||
<summary className="flex cursor-pointer items-center gap-2 border-b px-4 py-2.5 hover:bg-muted/30">
|
||||
<span className="font-semibold text-foreground text-sm">
|
||||
{section.title}
|
||||
</span>
|
||||
{noteParts.length > 0 ? (
|
||||
<span className="rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">
|
||||
{noteParts.join(" · ")}
|
||||
</span>
|
||||
) : null}
|
||||
<span className="ml-auto text-[10px] text-muted-foreground transition-transform group-open:rotate-180">
|
||||
▾
|
||||
</span>
|
||||
</summary>
|
||||
<div className="space-y-2 px-4 py-3">
|
||||
<div className="flex items-center gap-1 truncate font-mono text-[11px] text-muted-foreground">
|
||||
<FileIcon className="size-3 shrink-0" />
|
||||
<span className="truncate">{section.source_path}</span>
|
||||
</div>
|
||||
{isMissing ? (
|
||||
<p className="rounded-md border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-muted-foreground text-xs">
|
||||
{section.error ?? "产物文件不存在或读取失败"}
|
||||
</p>
|
||||
) : isMarkdown ? (
|
||||
<MarkdownView text={section.body ?? ""} />
|
||||
) : section.rows.length === 0 ? (
|
||||
<p className="text-muted-foreground text-xs">空表。</p>
|
||||
) : (
|
||||
<DataTable columns={section.columns} rows={section.rows} />
|
||||
)}
|
||||
</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
function DataTable({
|
||||
columns,
|
||||
rows,
|
||||
}: {
|
||||
columns: string[];
|
||||
rows: string[][];
|
||||
}) {
|
||||
return (
|
||||
<div className="max-h-[60vh] overflow-auto rounded-md border">
|
||||
<table className="w-full border-collapse text-[12px]">
|
||||
<thead className="sticky top-0 z-10 bg-muted/80 backdrop-blur supports-[backdrop-filter]:bg-muted/60">
|
||||
<tr>
|
||||
<th className="border-b border-r px-2 py-1 text-left font-medium text-[10px] text-muted-foreground tracking-wider w-10">
|
||||
#
|
||||
</th>
|
||||
{columns.map((c) => (
|
||||
<th
|
||||
key={c}
|
||||
className="border-b border-r last:border-r-0 px-2 py-1 text-left font-medium whitespace-nowrap"
|
||||
>
|
||||
{c}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row, rIdx) => (
|
||||
<tr
|
||||
key={rIdx}
|
||||
className="border-b last:border-b-0 hover:bg-muted/20"
|
||||
>
|
||||
<td className="border-r px-2 py-1 align-top font-mono text-[10px] text-muted-foreground tabular-nums">
|
||||
{rIdx + 1}
|
||||
</td>
|
||||
{columns.map((c, cIdx) => {
|
||||
const cell = row[cIdx] ?? "";
|
||||
return (
|
||||
<td
|
||||
key={c}
|
||||
className="border-r last:border-r-0 px-2 py-1 align-top font-mono text-[11px]"
|
||||
>
|
||||
{cell === "" ? (
|
||||
<span className="text-muted-foreground">—</span>
|
||||
) : (
|
||||
<TableCell text={cell} />
|
||||
)}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TableCell({ text }: { text: string }) {
|
||||
if (text.includes("\n")) {
|
||||
return (
|
||||
<pre className="whitespace-pre-wrap break-words font-mono text-[11px] leading-snug">
|
||||
{text}
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
return <span className="break-words whitespace-pre-wrap">{text}</span>;
|
||||
}
|
||||
|
||||
function RawView({ text }: { text: string }) {
|
||||
return (
|
||||
<pre className="overflow-x-auto whitespace-pre-wrap break-all font-mono text-[11px] leading-relaxed">
|
||||
|
||||
@@ -1,34 +1,43 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
AlertTriangleIcon,
|
||||
BarChart3Icon,
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
ChevronRightIcon,
|
||||
ClipboardListIcon,
|
||||
ClockIcon,
|
||||
DnaIcon,
|
||||
ExternalLinkIcon,
|
||||
FileTextIcon,
|
||||
FlaskConicalIcon,
|
||||
GitBranchIcon,
|
||||
GraduationCapIcon,
|
||||
HourglassIcon,
|
||||
Loader2Icon,
|
||||
MicroscopeIcon,
|
||||
type LucideIcon,
|
||||
MicroscopeIcon,
|
||||
RefreshCwIcon,
|
||||
ShieldCheckIcon,
|
||||
TrendingUpIcon,
|
||||
UserCheckIcon,
|
||||
} 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 CardStatus =
|
||||
| "pending"
|
||||
| "running"
|
||||
| "waiting"
|
||||
| "complete"
|
||||
| "failed"
|
||||
| "cancelled";
|
||||
type SectionType = "baseline" | "train" | "analysis";
|
||||
type GateKind = "human-check" | "human-review";
|
||||
|
||||
type PipelineCard = {
|
||||
key: string;
|
||||
step: string;
|
||||
icon?: string;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
@@ -36,10 +45,37 @@ type PipelineCard = {
|
||||
progress?: number;
|
||||
};
|
||||
|
||||
type PipelinePhase = {
|
||||
key: string;
|
||||
type RoundItem = {
|
||||
type: "round";
|
||||
index: number;
|
||||
run_id: string;
|
||||
run_index: number;
|
||||
section_type: SectionType;
|
||||
label: string;
|
||||
tone: PhaseTone;
|
||||
description: string;
|
||||
status: CardStatus;
|
||||
cards: PipelineCard[];
|
||||
};
|
||||
|
||||
type GateItem = {
|
||||
type: "gate";
|
||||
index: number;
|
||||
key: string;
|
||||
run_id: string;
|
||||
run_index: number;
|
||||
gate_kind: GateKind;
|
||||
title: string;
|
||||
description: string;
|
||||
status: CardStatus;
|
||||
reason?: string | null;
|
||||
};
|
||||
|
||||
type PipelineItem = RoundItem | GateItem;
|
||||
|
||||
type InFlight = {
|
||||
run_id: string;
|
||||
section_type: SectionType;
|
||||
section_label: string;
|
||||
cards: PipelineCard[];
|
||||
};
|
||||
|
||||
@@ -58,19 +94,21 @@ type LogLine = {
|
||||
type PipelinePayload = {
|
||||
session_id: string;
|
||||
generated_at_ms: number;
|
||||
available?: boolean;
|
||||
status: { mode: string; state: CardStatus };
|
||||
kpis: Kpi[];
|
||||
phases: PipelinePhase[];
|
||||
items: PipelineItem[];
|
||||
in_flight?: InFlight | null;
|
||||
logs: LogLine[];
|
||||
};
|
||||
|
||||
const ICON_MAP: Record<string, LucideIcon> = {
|
||||
"alert-triangle": AlertTriangleIcon,
|
||||
"bar-chart": BarChart3Icon,
|
||||
microscope: MicroscopeIcon,
|
||||
"trending-up": TrendingUpIcon,
|
||||
"file-text": FileTextIcon,
|
||||
dna: DnaIcon,
|
||||
"git-branch": GitBranchIcon,
|
||||
flask: FlaskConicalIcon,
|
||||
shield: ShieldCheckIcon,
|
||||
"graduation-cap": GraduationCapIcon,
|
||||
@@ -78,6 +116,19 @@ const ICON_MAP: Record<string, LucideIcon> = {
|
||||
"refresh-cw": RefreshCwIcon,
|
||||
clock: ClockIcon,
|
||||
hourglass: HourglassIcon,
|
||||
"user-check": UserCheckIcon,
|
||||
};
|
||||
|
||||
const SECTION_PHASE_TONE: Record<SectionType, string> = {
|
||||
baseline: "from-violet-500/15 to-sky-500/10 border-violet-400/40",
|
||||
train: "from-emerald-500/15 to-amber-500/10 border-emerald-400/40",
|
||||
analysis: "from-sky-500/15 to-violet-500/10 border-sky-400/40",
|
||||
};
|
||||
|
||||
const SECTION_BADGE_TONE: Record<SectionType, string> = {
|
||||
baseline: "bg-violet-500/10 text-violet-700 dark:text-violet-300",
|
||||
train: "bg-emerald-500/10 text-emerald-700 dark:text-emerald-300",
|
||||
analysis: "bg-sky-500/10 text-sky-700 dark:text-sky-300",
|
||||
};
|
||||
|
||||
export function TrainingPipelinePanel({
|
||||
@@ -102,7 +153,6 @@ export function TrainingPipelinePanel({
|
||||
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 {
|
||||
@@ -114,7 +164,6 @@ export function TrainingPipelinePanel({
|
||||
}
|
||||
};
|
||||
es.onerror = () => {
|
||||
// EventSource auto-reconnects; just stop showing the loading state.
|
||||
setLoading(false);
|
||||
};
|
||||
return () => {
|
||||
@@ -122,33 +171,83 @@ export function TrainingPipelinePanel({
|
||||
};
|
||||
}, [sessionId]);
|
||||
|
||||
const stripNamespace = (key: string): string => {
|
||||
// "R1:cml" → "cml" — backend uses round-namespaced keys, but the
|
||||
// step-detail endpoint is keyed only by step name.
|
||||
const idx = key.indexOf(":");
|
||||
return idx >= 0 ? key.slice(idx + 1) : key;
|
||||
};
|
||||
|
||||
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 className="mt-5 space-y-3">
|
||||
{(() => {
|
||||
if (!data) {
|
||||
return (
|
||||
<div className="rounded-md border border-dashed p-8 text-center text-muted-foreground text-xs">
|
||||
暂无 pipeline 数据
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const items = data.items ?? [];
|
||||
if (items.length === 0) {
|
||||
const isRunning = data.status?.state === "running";
|
||||
return (
|
||||
<div className="rounded-md border border-dashed p-8 text-center text-muted-foreground text-xs">
|
||||
{isRunning
|
||||
? "首个阶段进行中,卡片即将出现……"
|
||||
: "等待 agent 进入第一个步骤……"}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{items.map((item, idx) => {
|
||||
const showConnector = idx < items.length - 1;
|
||||
if (item.type === "round") {
|
||||
return (
|
||||
<div
|
||||
key={`round-${item.run_id}-${item.section_type}`}
|
||||
>
|
||||
<RoundSection
|
||||
item={item}
|
||||
onCardClick={(card) =>
|
||||
setOpenCard({
|
||||
key: stripNamespace(card.key),
|
||||
title: card.title,
|
||||
status: card.status,
|
||||
})
|
||||
}
|
||||
/>
|
||||
{showConnector ? <ItemConnector /> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div key={`gate-${item.key}`}>
|
||||
<GateCard
|
||||
item={item}
|
||||
onClick={() =>
|
||||
setOpenCard({
|
||||
key: stripNamespace(item.key),
|
||||
title: item.title,
|
||||
status: item.status,
|
||||
})
|
||||
}
|
||||
/>
|
||||
{showConnector ? <ItemConnector /> : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
</div>
|
||||
<LegendBar />
|
||||
<LogStream logs={data?.logs ?? []} />
|
||||
<StepDetailSheet
|
||||
sessionId={sessionId}
|
||||
@@ -177,6 +276,10 @@ function HeaderRow({
|
||||
? `${status.mode} · ${statusText(status.state)}`
|
||||
: "暂无运行";
|
||||
const isRunning = status?.state === "running";
|
||||
const isWaiting = status?.state === "waiting";
|
||||
const isFailed = status?.state === "failed";
|
||||
const isCancelled = status?.state === "cancelled";
|
||||
const isErrored = isFailed || isCancelled;
|
||||
return (
|
||||
<header className="flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -187,27 +290,33 @@ function HeaderRow({
|
||||
</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",
|
||||
"flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs",
|
||||
isErrored
|
||||
? "border-rose-500/50 bg-rose-500/10 text-rose-700 dark:text-rose-300"
|
||||
: isWaiting
|
||||
? "border-amber-500/50 bg-amber-500/10 text-amber-700 dark:text-amber-300"
|
||||
: isRunning
|
||||
? "animate-pipeline-pill-glow border-sky-400 bg-sky-500/10 text-sky-700 dark:text-sky-300"
|
||||
: "border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300",
|
||||
)}
|
||||
>
|
||||
<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",
|
||||
isErrored
|
||||
? "bg-rose-500"
|
||||
: isWaiting
|
||||
? "bg-amber-500"
|
||||
: isRunning
|
||||
? "bg-sky-500"
|
||||
: status?.state === "complete"
|
||||
? "bg-emerald-500"
|
||||
: "bg-muted-foreground",
|
||||
)}
|
||||
/>
|
||||
{isRunning ? (
|
||||
<span className="pointer-events-none absolute inset-0 animate-pipeline-dot-ping rounded-full bg-emerald-400" />
|
||||
{isRunning && !isErrored ? (
|
||||
<span className="pointer-events-none absolute inset-0 animate-pipeline-dot-ping rounded-full bg-sky-400" />
|
||||
) : null}
|
||||
</span>
|
||||
<span className="font-medium">{statusLabel}</span>
|
||||
@@ -245,80 +354,204 @@ function KpiRow({ kpis }: { kpis: Kpi[] }) {
|
||||
);
|
||||
}
|
||||
|
||||
function PhaseSection({
|
||||
phase,
|
||||
function ItemConnector() {
|
||||
return (
|
||||
<div className="flex justify-center py-1">
|
||||
<div className="h-5 w-0.5 bg-gradient-to-b from-border to-muted-foreground/30" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StatusPill({ status }: { status: CardStatus }) {
|
||||
const map: Record<
|
||||
CardStatus,
|
||||
{ label: string; cls: string; icon: LucideIcon | null }
|
||||
> = {
|
||||
complete: {
|
||||
label: "COMPLETED",
|
||||
cls: "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300 border-emerald-500/30",
|
||||
icon: CheckIcon,
|
||||
},
|
||||
running: {
|
||||
label: "IN PROGRESS",
|
||||
cls: "bg-sky-500/15 text-sky-700 dark:text-sky-300 border-sky-500/30",
|
||||
icon: Loader2Icon,
|
||||
},
|
||||
waiting: {
|
||||
label: "WAITING FOR YOU",
|
||||
cls: "bg-amber-500/15 text-amber-700 dark:text-amber-300 border-amber-500/40",
|
||||
icon: HourglassIcon,
|
||||
},
|
||||
pending: {
|
||||
label: "PENDING",
|
||||
cls: "bg-muted text-muted-foreground border-border",
|
||||
icon: null,
|
||||
},
|
||||
failed: {
|
||||
label: "FAILED",
|
||||
cls: "bg-rose-500/15 text-rose-700 dark:text-rose-300 border-rose-500/30",
|
||||
icon: AlertTriangleIcon,
|
||||
},
|
||||
cancelled: {
|
||||
label: "CANCELLED",
|
||||
cls: "bg-muted text-muted-foreground border-border",
|
||||
icon: null,
|
||||
},
|
||||
};
|
||||
const { label, cls, icon: Icon } = map[status];
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-[10px] font-semibold tracking-wider",
|
||||
cls,
|
||||
)}
|
||||
>
|
||||
{Icon ? (
|
||||
<Icon
|
||||
className={cn(
|
||||
"size-3",
|
||||
status === "running" ? "animate-spin" : "",
|
||||
)}
|
||||
/>
|
||||
) : null}
|
||||
{label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function RoundSection({
|
||||
item,
|
||||
onCardClick,
|
||||
}: {
|
||||
phase: PipelinePhase;
|
||||
item: RoundItem;
|
||||
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";
|
||||
const numLabel = item.index.toString().padStart(2, "0");
|
||||
const phaseTone = SECTION_PHASE_TONE[item.section_type];
|
||||
const badgeTone = SECTION_BADGE_TONE[item.section_type];
|
||||
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}
|
||||
<section
|
||||
className={cn(
|
||||
"rounded-2xl border bg-gradient-to-br p-4 shadow-sm",
|
||||
phaseTone,
|
||||
"bg-background/80",
|
||||
)}
|
||||
>
|
||||
<div className="mb-3 flex items-start justify-between gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<span
|
||||
className={cn(
|
||||
"flex size-9 shrink-0 items-center justify-center rounded-full font-mono text-sm font-semibold",
|
||||
badgeTone,
|
||||
)}
|
||||
>
|
||||
{numLabel}
|
||||
</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 className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-semibold text-foreground text-sm">
|
||||
{item.label}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-0.5 text-[11px] text-muted-foreground">
|
||||
{item.description}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<StatusPill status={item.status} />
|
||||
</div>
|
||||
{item.cards.length > 0 ? (
|
||||
<div className="flex flex-wrap items-stretch justify-center gap-2">
|
||||
{item.cards.map((card, idx) => (
|
||||
<div key={card.key} className="flex items-stretch gap-2">
|
||||
<PipelineCardView
|
||||
card={card}
|
||||
onClick={onCardClick ? () => onCardClick(card) : undefined}
|
||||
/>
|
||||
{idx < item.cards.length - 1 ? <CardArrow /> : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function PhaseArrow({ complete }: { complete: boolean }) {
|
||||
function CardArrow() {
|
||||
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 className="flex items-center px-1 text-muted-foreground/50">
|
||||
<ChevronRightIcon className="size-5" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function GateCard({
|
||||
item,
|
||||
onClick,
|
||||
}: {
|
||||
item: GateItem;
|
||||
onClick?: () => void;
|
||||
}) {
|
||||
const numLabel = item.index.toString().padStart(2, "0");
|
||||
const isWaiting = item.status === "waiting";
|
||||
const isComplete = item.status === "complete";
|
||||
const Tag = onClick ? "button" : "div";
|
||||
const hint =
|
||||
item.gate_kind === "human-review"
|
||||
? "在右侧对话里给出 OK / 调整后的指令,agent 才会继续。"
|
||||
: "在右侧对话里回 OK / 修改建议,确认后进入下一轮训练。";
|
||||
return (
|
||||
<Tag
|
||||
type={onClick ? "button" : undefined}
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
"flex w-full items-center justify-between gap-3 rounded-2xl border-2 border-dashed bg-amber-500/5 p-4 text-left transition-colors",
|
||||
isWaiting
|
||||
? "border-amber-400 bg-amber-500/10 ring-2 ring-amber-300/40 dark:ring-amber-500/30 animate-pipeline-pill-glow"
|
||||
: isComplete
|
||||
? "border-emerald-400/60 bg-emerald-500/5"
|
||||
: "border-amber-400/40",
|
||||
onClick &&
|
||||
"cursor-pointer hover:bg-amber-500/15 focus:outline-none focus-visible:ring-2 focus-visible:ring-amber-400",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<span className="flex size-9 shrink-0 items-center justify-center rounded-full bg-amber-500/15 font-mono text-amber-700 text-sm font-semibold dark:text-amber-300">
|
||||
{numLabel}
|
||||
</span>
|
||||
<div className="flex size-10 shrink-0 items-center justify-center rounded-full bg-amber-500/20 text-amber-700 dark:text-amber-300">
|
||||
<UserCheckIcon className="size-5" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="font-semibold text-foreground text-sm">
|
||||
{item.title}
|
||||
</span>
|
||||
<span className="rounded bg-amber-500/15 px-1.5 py-0.5 font-mono text-[10px] text-amber-700 dark:text-amber-300">
|
||||
{item.run_id}
|
||||
</span>
|
||||
</div>
|
||||
{item.reason ? (
|
||||
<p className="mt-1 text-[12px] text-foreground/80 leading-snug line-clamp-3">
|
||||
{item.reason}
|
||||
</p>
|
||||
) : (
|
||||
<p className="mt-1 text-[11px] text-muted-foreground leading-snug">
|
||||
{item.description}
|
||||
</p>
|
||||
)}
|
||||
{isWaiting ? (
|
||||
<p className="mt-1 text-[10px] uppercase tracking-wide text-amber-700/80 dark:text-amber-400/80">
|
||||
{hint}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<StatusPill status={item.status} />
|
||||
</Tag>
|
||||
);
|
||||
}
|
||||
|
||||
function PipelineCardView({
|
||||
card,
|
||||
onClick,
|
||||
@@ -357,7 +590,7 @@ function PipelineCardView({
|
||||
<CheckIcon className="size-3" strokeWidth={3} />
|
||||
</div>
|
||||
) : (
|
||||
<StatusBadge status={card.status} />
|
||||
<MiniStatus status={card.status} />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
@@ -390,7 +623,7 @@ function PipelineCardView({
|
||||
);
|
||||
}
|
||||
|
||||
function StatusBadge({ status }: { status: CardStatus }) {
|
||||
function MiniStatus({ status }: { status: CardStatus }) {
|
||||
const map: Record<CardStatus, { label: string; cls: string }> = {
|
||||
complete: {
|
||||
label: "DONE",
|
||||
@@ -400,6 +633,10 @@ function StatusBadge({ status }: { status: CardStatus }) {
|
||||
label: "RUNNING",
|
||||
cls: "bg-sky-500/20 text-sky-700 dark:text-sky-200",
|
||||
},
|
||||
waiting: {
|
||||
label: "WAITING",
|
||||
cls: "bg-amber-500/20 text-amber-700 dark:text-amber-200",
|
||||
},
|
||||
pending: {
|
||||
label: "PENDING",
|
||||
cls: "bg-muted text-muted-foreground",
|
||||
@@ -429,6 +666,61 @@ function StatusBadge({ status }: { status: CardStatus }) {
|
||||
);
|
||||
}
|
||||
|
||||
function LegendBar() {
|
||||
const items = [
|
||||
{
|
||||
icon: BarChart3Icon,
|
||||
label: "Measure",
|
||||
sub: "Quantify performance",
|
||||
color:
|
||||
"bg-sky-500/10 text-sky-700 dark:text-sky-300 border-sky-500/30",
|
||||
},
|
||||
{
|
||||
icon: DnaIcon,
|
||||
label: "Improve",
|
||||
sub: "Data, training, quality",
|
||||
color:
|
||||
"bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border-emerald-500/30",
|
||||
},
|
||||
{
|
||||
icon: MicroscopeIcon,
|
||||
label: "Understand",
|
||||
sub: "Analyze & diagnose",
|
||||
color:
|
||||
"bg-violet-500/10 text-violet-700 dark:text-violet-300 border-violet-500/30",
|
||||
},
|
||||
{
|
||||
icon: RefreshCwIcon,
|
||||
label: "Iterate",
|
||||
sub: "Repeat & grow",
|
||||
color:
|
||||
"bg-amber-500/10 text-amber-700 dark:text-amber-300 border-amber-500/30",
|
||||
},
|
||||
];
|
||||
return (
|
||||
<div className="flex shrink-0 items-center gap-4 border-t bg-background/80 px-6 py-2.5 overflow-x-auto">
|
||||
{items.map(({ icon: Icon, label, sub, color }) => (
|
||||
<div key={label} className="flex items-center gap-2 shrink-0">
|
||||
<span
|
||||
className={cn(
|
||||
"flex size-7 items-center justify-center rounded-full border",
|
||||
color,
|
||||
)}
|
||||
>
|
||||
<Icon className="size-3.5" />
|
||||
</span>
|
||||
<div className="leading-tight">
|
||||
<div className="text-[11px] font-semibold text-foreground">
|
||||
{label}
|
||||
</div>
|
||||
<div className="text-[10px] text-muted-foreground">{sub}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LogStream({ logs }: { logs: LogLine[] }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
@@ -471,6 +763,7 @@ function LogStream({ logs }: { logs: LogLine[] }) {
|
||||
function statusText(state: CardStatus) {
|
||||
const map: Record<CardStatus, string> = {
|
||||
running: "Running",
|
||||
waiting: "等待人工确认",
|
||||
complete: "Complete",
|
||||
failed: "Failed",
|
||||
pending: "Idle",
|
||||
|
||||
@@ -48,9 +48,11 @@ function SheetContent({
|
||||
className,
|
||||
children,
|
||||
side = "right",
|
||||
hideClose = false,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
|
||||
side?: "top" | "right" | "bottom" | "left";
|
||||
hideClose?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<SheetPortal>
|
||||
@@ -72,10 +74,12 @@ function SheetContent({
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SheetPrimitive.Close className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-hidden focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
|
||||
<XIcon className="size-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</SheetPrimitive.Close>
|
||||
{hideClose ? null : (
|
||||
<SheetPrimitive.Close className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-hidden focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
|
||||
<XIcon className="size-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</SheetPrimitive.Close>
|
||||
)}
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPortal>
|
||||
);
|
||||
|
||||
@@ -69,6 +69,58 @@ export async function loginAccount(username: string, password: string) {
|
||||
return createSession(account);
|
||||
}
|
||||
|
||||
const XIAOMI_EMAIL_RE = /^([\w.-]+)@xiaomi\.com$/i;
|
||||
|
||||
export function accountIdFromEmail(email: string): string {
|
||||
const match = XIAOMI_EMAIL_RE.exec((email ?? "").trim());
|
||||
if (!match) {
|
||||
throw new Error("请使用小米邮箱(@xiaomi.com)登录");
|
||||
}
|
||||
const prefix = match[1].toLowerCase();
|
||||
if (!/^[a-z0-9._-]{2,40}$/.test(prefix)) {
|
||||
throw new Error(
|
||||
"邮箱前缀只能包含小写字母、数字、点、下划线或中划线,长度 2-40",
|
||||
);
|
||||
}
|
||||
return prefix;
|
||||
}
|
||||
|
||||
export async function registerByEmail(email: string, password: string) {
|
||||
const accountId = accountIdFromEmail(email);
|
||||
validatePassword(password);
|
||||
const usersFile = await readUsers();
|
||||
if (usersFile.users.some((user) => user.id === accountId)) {
|
||||
throw new Error("该邮箱已注册,请直接登录");
|
||||
}
|
||||
const account: UserRecord = {
|
||||
id: accountId,
|
||||
username: accountId,
|
||||
passwordHash: hashPassword(password),
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
usersFile.users.push(account);
|
||||
await writeUsers(usersFile);
|
||||
await createAccountDirectories(account.id);
|
||||
return createSession(account);
|
||||
}
|
||||
|
||||
export async function loginByEmail(email: string, password: string) {
|
||||
const accountId = accountIdFromEmail(email);
|
||||
const usersFile = await readUsers();
|
||||
const account = usersFile.users.find((user) => user.id === accountId);
|
||||
if (!account) {
|
||||
throw new Error("账号不存在,请先注册");
|
||||
}
|
||||
if (!account.passwordHash) {
|
||||
throw new Error("该账号尚未设置密码,请联系管理员重置");
|
||||
}
|
||||
if (!verifyPassword(password, account.passwordHash)) {
|
||||
throw new Error("邮箱或密码错误");
|
||||
}
|
||||
await createAccountDirectories(account.id);
|
||||
return createSession(account);
|
||||
}
|
||||
|
||||
export async function logoutAccount() {
|
||||
const cookieStore = await cookies();
|
||||
const token = cookieStore.get(COOKIE_NAME)?.value;
|
||||
|
||||
Reference in New Issue
Block a user