feat(schedules): per-check cost and model summary on GET /schedules (INT-3)

agent_check items carry agentRuns (last 100 sessions: last/avg cost, 7-day count and cost,
models, recent 3); plan page and home plan band use it instead of fetching agent runs.
Migration 0052 indexes agent_run(created_by, created_at).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
rootandClaude Opus 5.5 committed 2026-09-29 17:55:47 +08:00
1 parent 82df5662f0
commit e681fcedf6
9 files changed
+200 -78

No files matched your search

-28
View File
@@ -413,31 +413,3 @@ export function useRunInvocationAudit(runId: string, enabled: boolean, version =
},
});
}
/**
* 巡检触发的最近会话(trigger=schedule,createdBy = schedule:<定时任务 id>):
* 计划页的巡检卡片、首页计划带按定时任务分组取费用、模型与最近结果。一次取最近 100 条。
*/
export function useScheduleAgentRuns() {
return useQuery({
queryKey: [...agentKeys.runs(undefined, "schedule"), "plan"],
queryFn: ({ signal }) =>
apiParsed(RunPage, AGENT_BASE, { params: cleanParams({ trigger: "schedule", limit: 100 }), signal }),
select: (page) => page.items,
staleTime: 30 * TTL_SECOND,
refetchInterval: 60 * TTL_SECOND,
});
}
/** 按定时任务 id 分组(新 → 旧,保持接口顺序) */
export function groupRunsBySchedule(runs: AgentRun[]): Map<string, AgentRun[]> {
const out = new Map<string, AgentRun[]>();
for (const r of runs) {
const id = r.createdBy?.startsWith("schedule:") ? r.createdBy.slice("schedule:".length) : null;
if (!id) continue;
const list = out.get(id);
if (list) list.push(r);
else out.set(id, [r]);
}
return out;
}
@@ -1,10 +1,4 @@
import {
type AgentCheckConfig,
type AgentRun,
CAPABILITY_CATALOG,
type KnownCapabilityId,
type ScheduledJob,
} from "@umt/contracts";
import { type AgentCheckConfig, CAPABILITY_CATALOG, type KnownCapabilityId, type ScheduledJob } from "@umt/contracts";
import { History, LoaderCircle, Pencil, Play, RotateCcw, SkipForward, Trash2 } from "lucide-react";
import { type ReactNode, useEffect, useRef } from "react";
import { Link } from "react-router";
@@ -39,6 +33,9 @@ const capTitle = (id: string) => CAPABILITY_CATALOG[id as KnownCapabilityId]?.ti
/** 默认上游(巡检没有单独的上游设置,跟随 Agent 设置里的默认上游) */
export type DefaultUpstream = { name: string; model: string | null } | null;
const modelsTitle = (models: { provider: string | null; model: string; count: number }[]) =>
models.map((m) => `${m.provider ? `${m.provider} · ` : ""}${m.model}:${m.count} 次`).join("\n");
function Field({ label, children }: { label: string; children: ReactNode }) {
return (
<>
@@ -51,7 +48,6 @@ function Field({ label, children }: { label: string; children: ReactNode }) {
export function AgentCheckCard({
job,
now,
runs,
upstream,
highlight,
onEdit,
@@ -59,8 +55,6 @@ export function AgentCheckCard({
}: {
job: ScheduledJob;
now: number;
/** 该巡检最近的会话(新 → 旧) */
runs: AgentRun[];
upstream: DefaultUpstream;
highlight: boolean;
onEdit: (job: ScheduledJob) => void;
@@ -77,9 +71,9 @@ export function AgentCheckCard({
const budget = c.budget ?? {};
const allow = c.capabilityAllowlist ?? [];
const last = job.lastStatus ? RUN_STATUS[job.lastStatus] : null;
const latest = runs[0] ?? null;
const costs = runs.map((r) => r.usage.costUsd).filter((v): v is number => typeof v === "number");
const avg = costs.length ? costs.reduce((s, v) => s + v, 0) / costs.length : null;
// 费用 / 模型由后端按最近 100 次会话汇总(GET /schedules 的 agentRuns)
const stats = job.agentRuns;
const runs = stats?.recent ?? [];
const budgetParts = [
budget.maxToolCalls ? `${budget.maxToolCalls} 次调用` : null,
budget.maxDurationSec ? `${budget.maxDurationSec} 秒` : null,
@@ -149,10 +143,13 @@ export function AgentCheckCard({
</Field>
<Field label="预算">{budgetParts.length ? budgetParts.join(" · ") : "默认"}</Field>
<Field label="上游">
{latest?.model ? (
<span className="break-words">
{latest.provider ? `${latest.provider} · ` : ""}
{latest.model}
{stats?.lastModel ? (
<span className="break-words" title={modelsTitle(stats.models)}>
{stats.lastProvider ? `${stats.lastProvider} · ` : ""}
{stats.lastModel}
{stats.models.length > 1 ? (
<span className="text-muted-foreground"> 等 {stats.models.length} 个模型</span>
) : null}
</span>
) : upstream ? (
<span className="break-words">
@@ -182,12 +179,12 @@ export function AgentCheckCard({
</span>
</Field>
<Field label="每次费用">
{costs.length ? (
{stats?.count ? (
<span className="tabular-nums">
上次 {formatUsd(costs[0])}
上次 {formatUsd(stats.lastCostUsd)}
<span className="text-muted-foreground">
{" "}
· 近 {costs.length} 次平均 {formatUsd(avg)}
· 近 {stats.count} 次平均 {formatUsd(stats.avgCostUsd)}
</span>
</span>
) : (
@@ -225,7 +222,7 @@ export function AgentCheckCard({
<span className="min-w-0 flex-1 truncate" title={r.summary ?? undefined}>
{plainSummary(r.summary ?? r.goal)}
</span>
<span className="shrink-0 tabular-nums">{formatUsd(r.usage.costUsd)}</span>
<span className="shrink-0 tabular-nums">{formatUsd(r.costUsd)}</span>
<span className="shrink-0" title={r.createdAt}>
{formatRelative(r.finishedAt ?? r.createdAt)}
</span>
@@ -3,7 +3,6 @@ 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";
@@ -50,10 +49,8 @@ export function useLiveSchedules() {
return useScheduleBoard();
}
const WEEK_MS = 7 * 24 * 3600_000;
/** 两节的计数:自动任务 启用/失败/运行中;巡检 启用/失败/近 7 天费用 */
export function planStats(items: ScheduledJob[], checkCosts: { at: string; cost: number | undefined }[], now: number) {
/** 两节的计数:自动任务 启用/失败/运行中;巡检 启用/失败/近 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[]) => ({
@@ -62,13 +59,12 @@ export function planStats(items: ScheduledJob[], checkCosts: { at: string; cost:
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),
weekRuns: checks.reduce((s, j) => s + (j.agentRuns?.weekCount ?? 0), 0),
weekCost: checks.reduce((s, j) => s + (j.agentRuns?.weekCostUsd ?? 0), 0),
},
};
}
@@ -89,7 +85,6 @@ function SectionHead({ id, title, hint, actions }: { id: string; title: string;
export function PlanBoard({ highlightJob }: { highlightJob?: string }) {
const board = useLiveSchedules();
const agentRuns = useScheduleAgentRuns();
const upstreams = usePiUpstreams();
const now = useNow();
const { hash } = useLocation();
@@ -100,14 +95,9 @@ export function PlanBoard({ highlightJob }: { highlightJob?: string }) {
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 s = planStats(items);
const val = (n: number) => (board.isPending ? "…" : board.isError ? "—" : n);
// 首页计数链到 #auto / #checks:数据到了再滚过去
@@ -163,8 +153,8 @@ export function PlanBoard({ highlightJob }: { highlightJob?: string }) {
<StatTile
label="近 7 天费用"
icon={Coins}
value={agentRuns.isPending ? "…" : agentRuns.isError ? "—" : formatUsd(s.checks.weekCost)}
hint={agentRuns.data ? `${s.checks.weekRuns} 次会话` : undefined}
value={data ? formatUsd(s.checks.weekCost) : "…"}
hint={data ? `${s.checks.weekRuns} 次会话` : undefined}
onClick={() => jump("checks")}
/>
</div>
@@ -221,7 +211,6 @@ export function PlanBoard({ highlightJob }: { highlightJob?: string }) {
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() })}
+3 -10
View File
@@ -22,7 +22,6 @@ import type { ReactNode } from "react";
import { useRef } from "react";
import { Link } from "react-router";
import { toast } from "sonner";
import { useScheduleAgentRuns } from "~/api/agent.ts";
import { useDashboard, useSitesWithAccounts } from "~/api/dashboard.ts";
import { useDecisions } from "~/api/decisions.ts";
import { useEngineRunsPage, useEngineStats } from "~/api/engine.ts";
@@ -36,7 +35,7 @@ import { StatTile } from "~/components/console/stat-tile.tsx";
import { StatusBadge, type StatusTone } from "~/components/console/status-badge.tsx";
import { useVolumeLabel } from "~/components/downloads/cache-volumes.tsx";
import { formatUsd, planPath } from "~/components/schedules/labels.ts";
import { planStats, useLiveSchedules, useNow } from "~/components/schedules/schedule-board.tsx";
import { planStats, useLiveSchedules } from "~/components/schedules/schedule-board.tsx";
import { engineRunStatus, runTitle, workflowLabel } from "~/components/tasks/labels.ts";
import { useLiveTasks } from "~/components/tasks/task-stream.tsx";
import { Button } from "~/components/ui/button.tsx";
@@ -353,13 +352,7 @@ function Num({ children, tone }: { children: ReactNode; tone?: "destructive" })
function PlanStrip() {
const board = useLiveSchedules();
const runs = useScheduleAgentRuns();
const now = useNow(60_000);
const s = planStats(
board.data?.items ?? [],
(runs.data ?? []).map((r) => ({ at: r.createdAt, cost: r.usage.costUsd })),
now,
);
const s = planStats(board.data?.items ?? []);
return (
<Section
title="计划"
@@ -388,7 +381,7 @@ function PlanStrip() {
启用 <Num>{s.checks.enabled}</Num> / {s.checks.total}
</span>
<span title="近 7 天巡检会话费用合计">
近 7 天 <Num>{runs.isPending ? "…" : runs.isError ? "—" : formatUsd(s.checks.weekCost)}</Num>
近 7 天 <Num>{formatUsd(s.checks.weekCost)}</Num>
</span>
</PlanCount>
</div>