Files
UHD_Media_Tool/apps/web/app/components/schedules/schedule-board.tsx
T

234 lines
9.4 KiB
TypeScript

import { useQueryClient } from "@tanstack/react-query";
import { SCHEDULE_CHANGED_EVENT, type ScheduledJob } from "@umt/contracts";
import { AlertTriangle, Bot, CalendarClock, Plus, Sparkles } from "lucide-react";
import { type ReactNode, useEffect, useRef, useState } from "react";
import { useLocation } from "react-router";
import { usePiUpstreamModels, usePiUpstreams } from "~/api/pi.ts";
import { useScheduleBoard } from "~/api/schedules.ts";
import { EmptyState, ErrorState, LoadingState } from "~/components/console/empty-state.tsx";
import { useListPagination } from "~/components/console/use-list-pagination.ts";
import { Button } from "~/components/ui/button.tsx";
import { Pagination } from "~/components/ui/pagination.tsx";
import { qk } from "~/lib/query-keys.ts";
import { useSse } from "~/lib/sse.ts";
import { AgentCheckCard, type DefaultUpstream } from "./agent-check-card.tsx";
import { AgentCheckDialog } from "./agent-check-dialog.tsx";
import { AutoTaskList } from "./auto-task-list.tsx";
import { DraftCheckDialog } from "./draft-check-dialog.tsx";
import { formatUsd } from "./labels.ts";
import { RunsSheet } from "./runs-sheet.tsx";
// 定时任务(FE-6 的计划页;界面第二轮并入日志页「定时任务」页签,/console/logs?tab=schedules):「智能体巡检」= 到点发起智能体会话的定时任务(卡片,放最上面:
// 数量少、由用户自己建、会花钱,是这页最需要看的);「自动任务」= 程序按固定周期执行的定时任务
// (按分类折叠的紧凑列表,维护类合成「数据清理」)。自动任务的运行记录跳日志页按该定时任务筛选。
/** 每秒一跳的当前时间(倒计时用) */
export function useNow(ms = 1000) {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const t = setInterval(() => setNow(Date.now()), ms);
return () => clearInterval(t);
}, [ms]);
return now;
}
/** SSE:调度器每次开始/结束一次运行都会发 schedule.changed;1 秒节流 */
export function useLiveSchedules() {
const qc = useQueryClient();
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
useSse([SCHEDULE_CHANGED_EVENT], () => {
if (timer.current) return;
timer.current = setTimeout(() => {
timer.current = null;
qc.invalidateQueries({ queryKey: qk.all("schedules") });
}, 1000);
});
useEffect(
() => () => {
if (timer.current) clearTimeout(timer.current);
},
[],
);
return useScheduleBoard();
}
/** 两节的计数:自动任务 启用/失败/运行中;巡检 启用/失败/近 7 天费用(后端按巡检汇总的 agentRuns) */
export function planStats(items: ScheduledJob[]) {
const auto = items.filter((j) => j.kind === "task");
const checks = items.filter((j) => j.kind === "agent_check");
const count = (list: ScheduledJob[]) => ({
total: list.length,
enabled: list.filter((j) => j.enabled && j.available).length,
failed: list.filter((j) => j.lastStatus === "failed").length,
running: list.filter((j) => !!j.runningSince).length,
});
return {
auto: count(auto),
checks: {
...count(checks),
weekRuns: checks.reduce((s, j) => s + (j.agentRuns?.weekCount ?? 0), 0),
weekCost: checks.reduce((s, j) => s + (j.agentRuns?.weekCostUsd ?? 0), 0),
},
};
}
function SectionHead({
id,
title,
hint,
actions,
}: {
id: string;
title: string;
hint: ReactNode;
actions?: ReactNode;
}) {
return (
<div className="mb-3 flex flex-wrap items-end gap-x-3 gap-y-2">
<div className="min-w-0">
<h2 id={id} className="scroll-mt-20 text-title-sm font-semibold text-foreground">
{title}
</h2>
<p className="mt-0.5 text-caption text-muted-foreground">{hint}</p>
</div>
{actions ? <div className="ml-auto flex items-center gap-2">{actions}</div> : null}
</div>
);
}
export function PlanBoard({ highlightJob }: { highlightJob?: string }) {
const board = useLiveSchedules();
const upstreams = usePiUpstreams();
const now = useNow();
const { hash } = useLocation();
const [editing, setEditing] = useState<{ job: ScheduledJob | null; key: number } | null>(null);
const [drafting, setDrafting] = useState(false);
const [history, setHistory] = useState<ScheduledJob | null>(null);
const data = board.data;
const items = data?.items ?? [];
const autoJobs = items.filter((j) => j.kind === "task");
const checks = items.filter((j) => j.kind === "agent_check");
const pagedChecks = useListPagination(checks, { resetKey: "agent-checks" });
const highlightedIndex = checks.findIndex((job) => job.id === highlightJob);
// biome-ignore lint/correctness/useExhaustiveDependencies: 仅在深链目标或每页数量变化时定位所在页
useEffect(() => {
if (highlightedIndex >= 0)
pagedChecks.pagination.onPageChange(Math.floor(highlightedIndex / pagedChecks.pagination.pageSize) + 1);
}, [highlightJob, highlightedIndex, pagedChecks.pagination.pageSize]);
const def = upstreams.data?.items.find((u) => u.isDefault);
// 上游没填默认模型时,运行时用模型目录的第一个(packages/agent pi/upstream.ts pickModel),这里同样取目录首个
const catalog = usePiUpstreamModels(def && !def.defaultModel ? def.id : null);
const catalogModel = catalog.data?.models[0]?.id ?? null;
const upstream: DefaultUpstream = def
? {
name: def.name,
model: def.defaultModel ?? catalogModel,
modelFromCatalog: !def.defaultModel && !!catalogModel,
}
: null;
const s = planStats(items);
// 首页计数链到 #auto / #checks:数据到了再滚过去
const loaded = !!data;
useEffect(() => {
if (!loaded || highlightJob) return;
const id = hash.replace(/^#/, "");
if (id === "auto" || id === "checks") document.getElementById(id)?.scrollIntoView({ block: "start" });
}, [loaded, hash, highlightJob]);
return (
<>
{data && !data.schedulerOnline ? (
<p
role="status"
className="mb-4 flex items-center gap-2 rounded-tight border border-warning/30 bg-warning/10 px-3 py-2 text-caption text-warning"
>
<AlertTriangle className="h-4 w-4 shrink-0" />
调度器未在线,定时任务不会按时运行。
</p>
) : null}
{board.isPending ? (
<LoadingState rows={8} />
) : board.isError ? (
<ErrorState error={board.error} onRetry={() => board.refetch()} />
) : (
<div className="grid gap-8">
<section aria-labelledby="checks">
<SectionHead
id="checks"
title="智能体巡检"
hint={
s.checks.total
? [
`${s.checks.enabled} 个启用`,
s.checks.failed ? `${s.checks.failed} 个上次失败` : null,
s.checks.weekRuns ? `近 7 天 ${s.checks.weekRuns} 次,${formatUsd(s.checks.weekCost)}` : null,
]
.filter(Boolean)
.join(" · ")
: "到点让智能体按目标检查并汇报。"
}
actions={
<>
<Button size="sm" variant="outline" onClick={() => setDrafting(true)}>
<Sparkles />
用对话起草
</Button>
<Button size="sm" onClick={() => setEditing({ job: null, key: Date.now() })}>
<Plus />
新建巡检
</Button>
</>
}
/>
{checks.length === 0 ? (
<EmptyState icon={Bot} title="还没有巡检" description="新建一个巡检,到点由智能体按目标检查并汇报。" />
) : (
<div className="grid auto-rows-fr gap-4 md:grid-cols-2 2xl:grid-cols-3">
{pagedChecks.items?.map((j) => (
<AgentCheckCard
key={j.id}
job={j}
now={now}
upstream={upstream}
highlight={highlightJob === j.id}
onEdit={(job) => setEditing({ job, key: Date.now() })}
onHistory={setHistory}
/>
))}
</div>
)}
{checks.length > 0 ? <Pagination {...pagedChecks.pagination} /> : null}
</section>
<section aria-labelledby="auto">
<SectionHead
id="auto"
title="自动任务"
hint={[
`${s.auto.enabled} 个启用`,
s.auto.running ? `${s.auto.running} 个运行中` : null,
s.auto.failed ? `${s.auto.failed} 个上次失败` : null,
]
.filter(Boolean)
.join(" · ")}
/>
{autoJobs.length === 0 ? (
<EmptyState icon={CalendarClock} title="还没有自动任务" description="worker 启动后自动登记。" />
) : (
<AutoTaskList jobs={autoJobs} now={now} highlightJob={highlightJob} />
)}
</section>
</div>
)}
{editing ? (
<AgentCheckDialog key={editing.key} open job={editing.job} onOpenChange={(o) => !o && setEditing(null)} />
) : null}
{drafting ? <DraftCheckDialog open onOpenChange={setDrafting} /> : null}
<RunsSheet job={history} onClose={() => setHistory(null)} />
</>
);
}