Files
UHD_Media_Tool/apps/web/app/components/schedules/schedule-board.tsx
T
rootandClaude Opus 5.5 baf2d6ea04 feat(web): split plan page from tasks (FE-6)
- Nav overview group: 首页 / 任务 / 计划 / Agent 会话; tasks page drops the plan tab
- /console/tasks?tab=plan[&job=] redirects to /console/schedules[?job=]
- Plan page: 自动任务 compact grouped list (switch, interval preset/custom, last result,
  countdown, failure reason, run now/skip/run records) and Agent 巡检 cards (goal,
  allowlist, budget, upstream/model, trigger, cost per run, recent sessions); split stats
- Home plan band: two counts linking to #auto / #checks
- Docs: console-ia §7.4a, glossary, schedules runbook; smoke routes

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-29 17:13:54 +08:00

244 lines
9.7 KiB
TypeScript

import { useQueryClient } from "@tanstack/react-query";
import { SCHEDULE_CHANGED_EVENT, type ScheduledJob } from "@umt/contracts";
import { AlertTriangle, Bot, CalendarClock, CircleCheck, Coins, LoaderCircle, Plus, XCircle } from "lucide-react";
import { type ReactNode, useEffect, useRef, useState } from "react";
import { useLocation } from "react-router";
import { groupRunsBySchedule, useScheduleAgentRuns } from "~/api/agent.ts";
import { usePiUpstreams } from "~/api/pi.ts";
import { useScheduleBoard } from "~/api/schedules.ts";
import { EmptyState, ErrorState, LoadingState } from "~/components/console/empty-state.tsx";
import { StatTile } from "~/components/console/stat-tile.tsx";
import { Button } from "~/components/ui/button.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 { formatUsd } from "./labels.ts";
import { RunsSheet } from "./runs-sheet.tsx";
// 计划页(FE-6,/console/schedules):「自动任务」= 程序按固定周期执行的定时任务(紧凑列表);
// 「Agent 巡检」= 到点发起 Agent 会话的定时任务(卡片)。自动任务的运行记录跳任务页按该定时任务筛选。
/** 每秒一跳的当前时间(倒计时用) */
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();
}
const WEEK_MS = 7 * 24 * 3600_000;
/** 两节的计数:自动任务 启用/失败/运行中;巡检 启用/失败/近 7 天费用 */
export function planStats(items: ScheduledJob[], checkCosts: { at: string; cost: number | undefined }[], now: number) {
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,
});
const recent = checkCosts.filter((c) => now - new Date(c.at).getTime() <= WEEK_MS);
return {
auto: count(auto),
checks: {
...count(checks),
weekRuns: recent.length,
weekCost: recent.reduce((s, c) => s + (c.cost ?? 0), 0),
},
};
}
function SectionHead({ id, title, hint, actions }: { id: string; title: string; hint: string; 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 agentRuns = useScheduleAgentRuns();
const upstreams = usePiUpstreams();
const now = useNow();
const { hash } = useLocation();
const [editing, setEditing] = useState<{ job: ScheduledJob | null; key: number } | null>(null);
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 runsByJob = groupRunsBySchedule(agentRuns.data ?? []);
const def = upstreams.data?.items.find((u) => u.isDefault);
const upstream: DefaultUpstream = def ? { name: def.name, model: def.defaultModel ?? null } : null;
const s = planStats(
items,
(agentRuns.data ?? []).map((r) => ({ at: r.createdAt, cost: r.usage.costUsd })),
now,
);
const val = (n: number) => (board.isPending ? "…" : board.isError ? "—" : n);
// 首页计数链到 #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]);
const jump = (id: string) => document.getElementById(id)?.scrollIntoView({ block: "start", behavior: "smooth" });
return (
<>
<div className="mb-4 grid gap-3 lg:grid-cols-2">
<div className="grid gap-1.5">
<p className="px-1 text-meta font-medium text-muted-foreground">自动任务</p>
<div className="grid grid-cols-3 gap-2">
<StatTile
label="已启用"
icon={CircleCheck}
value={val(s.auto.enabled)}
hint={board.isPending ? undefined : `共 ${s.auto.total} 项`}
onClick={() => jump("auto")}
/>
<StatTile
label="上次失败"
icon={XCircle}
tone={s.auto.failed > 0 ? "destructive" : "neutral"}
value={val(s.auto.failed)}
onClick={() => jump("auto")}
/>
<StatTile label="运行中" icon={LoaderCircle} value={val(s.auto.running)} onClick={() => jump("auto")} />
</div>
</div>
<div className="grid gap-1.5">
<p className="px-1 text-meta font-medium text-muted-foreground">Agent 巡检</p>
<div className="grid grid-cols-3 gap-2">
<StatTile
label="已启用"
icon={Bot}
value={val(s.checks.enabled)}
hint={board.isPending ? undefined : `共 ${s.checks.total} 项`}
onClick={() => jump("checks")}
/>
<StatTile
label="上次失败"
icon={XCircle}
tone={s.checks.failed > 0 ? "destructive" : "neutral"}
value={val(s.checks.failed)}
onClick={() => jump("checks")}
/>
<StatTile
label="近 7 天费用"
icon={Coins}
value={agentRuns.isPending ? "…" : agentRuns.isError ? "—" : formatUsd(s.checks.weekCost)}
hint={agentRuns.data ? `${s.checks.weekRuns} 次会话` : undefined}
onClick={() => jump("checks")}
/>
</div>
</div>
</div>
{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="auto">
<SectionHead
id="auto"
title="自动任务"
hint="程序按固定周期执行,不调用模型。间隔可直接改,改过的可恢复默认。"
/>
{autoJobs.length === 0 ? (
<EmptyState icon={CalendarClock} title="还没有自动任务" description="worker 启动后自动登记。" />
) : (
<AutoTaskList jobs={autoJobs} now={now} highlightJob={highlightJob} />
)}
</section>
<section aria-labelledby="checks">
<SectionHead
id="checks"
title="Agent 巡检"
hint="到点按目标发起一次 Agent 会话,只在能力白名单和预算内执行;触发条件不满足时跳过,不调用模型。"
actions={
<Button size="sm" onClick={() => setEditing({ job: null, key: Date.now() })}>
<Plus />
新建巡检
</Button>
}
/>
{checks.length === 0 ? (
<EmptyState icon={Bot} title="还没有巡检" description="新建一个巡检,到点由 Agent 按目标检查并汇报。" />
) : (
<div className="grid items-start gap-4 md:grid-cols-2 2xl:grid-cols-3">
{checks.map((j) => (
<AgentCheckCard
key={j.id}
job={j}
now={now}
runs={runsByJob.get(j.id) ?? []}
upstream={upstream}
highlight={highlightJob === j.id}
onEdit={(job) => setEditing({ job, key: Date.now() })}
onHistory={setHistory}
/>
))}
</div>
)}
</section>
</div>
)}
{editing ? (
<AgentCheckDialog key={editing.key} open job={editing.job} onOpenChange={(o) => !o && setEditing(null)} />
) : null}
<RunsSheet job={history} onClose={() => setHistory(null)} />
</>
);
}