feat(web): unified task stream with plan tab, task detail drawer and audit links (FE-1)

Tasks page merges engine runs (with W9-I business fields) into one stream:
all / active / failed / plan tabs, filters for source, business kind, status
and time; detail drawer with business summary, timeline, collapsed engine
steps, cancel/retry and related audit links. The schedule board moves into
the plan tab; card history jumps to the stream filtered by schedule key.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
rootandClaude Opus 5.5 committed 2026-09-28 16:10:29 +08:00
1 parent f8362a3f4c
commit d8b9bd9662
10 files changed
+1189 -30

No files matched your search

@@ -328,7 +328,7 @@ export function TaskSummary({ t }: { t: Task }) {
{
label: "引擎运行",
value: t.engineRunId ? (
<Link to={consolePath("engine", t.engineRunId)} className="font-mono underline underline-offset-4">
<Link to={consolePath("tasks", t.engineRunId)} className="font-mono underline underline-offset-4">
{t.engineRunId.slice(0, 12)}
</Link>
) : null,
@@ -0,0 +1,145 @@
import { useQueryClient } from "@tanstack/react-query";
import { SCHEDULE_CHANGED_EVENT, type ScheduledJob, type ScheduleGroup } from "@umt/contracts";
import { AlertTriangle, CalendarClock, CircleCheck, LoaderCircle, Plus, XCircle } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router";
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 { AgentCheckDialog } from "./agent-check-dialog.tsx";
import { GROUP_LABEL, GROUP_ORDER } from "./labels.ts";
import { ScheduleCard } from "./schedule-card.tsx";
// 定时任务看板(W7-C),IA-3 起是任务页的"计划"页签。卡片"运行记录"跳到任务流按该定时任务筛选。
/** 每秒一跳的当前时间(倒计时用) */
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();
}
/** 任务流里某个定时任务的筛选地址 */
export const scheduleStreamPath = (id: string) => `/console/tasks?tab=all&kind=schedule&ref=${encodeURIComponent(id)}`;
export function ScheduleBoard({ highlightJob }: { highlightJob?: string }) {
const _qc = useQueryClient();
const navigate = useNavigate();
const board = useLiveSchedules();
const now = useNow();
const [editing, setEditing] = useState<{ job: ScheduledJob | null; key: number } | null>(null);
const data = board.data;
const items = data?.items ?? [];
const byGroup = new Map<ScheduleGroup, ScheduledJob[]>();
for (const g of GROUP_ORDER) byGroup.set(g, []);
for (const j of items) byGroup.get(j.group)?.push(j);
const stats = data?.stats;
const val = (n: number | undefined) => (board.isPending ? "…" : board.isError ? "—" : (n ?? 0));
return (
<>
<div className="mb-3 flex flex-wrap items-center gap-2">
<p className="text-caption text-muted-foreground">周期任务与 Agent 巡检的开关、间隔和下次运行。</p>
<div className="ml-auto flex items-center gap-2">
<Button size="sm" onClick={() => setEditing({ job: null, key: Date.now() })}>
<Plus />
新建巡检
</Button>
</div>
</div>
<div className="mb-3 grid grid-cols-2 gap-2 lg:grid-cols-4">
<StatTile label="已启用" icon={CircleCheck} value={val(stats?.enabled)} />
<StatTile
label="上次失败"
icon={XCircle}
tone={(stats?.failed ?? 0) > 0 ? "destructive" : "neutral"}
value={val(stats?.failed)}
/>
<StatTile label="运行中" icon={LoaderCircle} value={val(stats?.running)} />
<StatTile label="全部" icon={CalendarClock} value={val(stats?.total)} />
</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>
) : (
<div className="mb-4" />
)}
{board.isPending ? (
<LoadingState rows={6} />
) : board.isError ? (
<ErrorState error={board.error} onRetry={() => board.refetch()} />
) : items.length === 0 ? (
<EmptyState icon={CalendarClock} title="还没有定时任务" description="worker 启动后自动登记。" />
) : (
<div className="grid items-start gap-4 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-5">
{GROUP_ORDER.map((g) => {
const jobs = byGroup.get(g) ?? [];
return (
<section key={g} aria-label={GROUP_LABEL[g]} className="grid min-w-0 gap-2.5">
<h2 className="flex items-baseline justify-between px-1 text-caption font-medium text-muted-foreground">
<span>{GROUP_LABEL[g]}</span>
<span className="tabular-nums">{jobs.length}</span>
</h2>
{jobs.length === 0 ? (
<p className="rounded-xl border border-dashed border-border/70 px-4 py-6 text-center text-meta text-muted-foreground">
{g === "agent" ? "还没有巡检。" : "还没有定时任务。"}
</p>
) : (
jobs.map((j) => (
<ScheduleCard
key={j.id}
job={j}
now={now}
highlight={highlightJob === j.id}
onHistory={(job) => navigate(scheduleStreamPath(job.id))}
onEdit={(job) => setEditing({ job, key: Date.now() })}
/>
))
)}
</section>
);
})}
</div>
)}
{editing ? (
<AgentCheckDialog key={editing.key} open job={editing.job} onOpenChange={(o) => !o && setEditing(null)} />
) : null}
</>
);
}
@@ -1,5 +1,6 @@
import type { AgentCheckConfig, ScheduledJob, ScheduleSpecInput } from "@umt/contracts";
import { History, LoaderCircle, Pencil, Play, RotateCcw, SkipForward, Trash2 } from "lucide-react";
import { useEffect, useRef } from "react";
import { toast } from "sonner";
import { useDeleteSchedule, useRunScheduleNow, useSkipSchedule, useUpdateSchedule } from "~/api/schedules.ts";
import { ConfirmDialog } from "~/components/console/confirm-dialog.tsx";
@@ -8,6 +9,7 @@ import { Button } from "~/components/ui/button.tsx";
import { Switch } from "~/components/ui/switch.tsx";
import { errorMessage } from "~/lib/api.ts";
import { formatRelative } from "~/lib/labels.ts";
import { cn } from "~/lib/utils.ts";
import { IntervalEditor } from "./interval-editor.tsx";
import { CHECK_TRIGGER_LABEL, countdown, formatMs, RUN_STATUS } from "./labels.ts";
@@ -54,16 +56,23 @@ export function ScheduleCard({
now,
onHistory,
onEdit,
highlight = false,
}: {
job: ScheduledJob;
now: number;
onHistory: (job: ScheduledJob) => void;
onEdit: (job: ScheduledJob) => void;
/** 从任务流跳来时高亮并滚到可见 */
highlight?: boolean;
}) {
const update = useUpdateSchedule();
const runNow = useRunScheduleNow();
const skip = useSkipSchedule();
const del = useDeleteSchedule();
const ref = useRef<HTMLElement>(null);
useEffect(() => {
if (highlight) ref.current?.scrollIntoView({ block: "center" });
}, [highlight]);
const busy = !!job.runningSince || !!job.runRequestedAt;
const last = job.lastStatus ? RUN_STATUS[job.lastStatus] : null;
@@ -74,7 +83,15 @@ export function ScheduleCard({
);
return (
<article className="pg-slab grid min-w-0 gap-3 rounded-xl px-4 py-3.5" aria-label={job.name}>
<article
id={`job-${job.id}`}
ref={ref}
className={cn(
"pg-slab grid min-w-0 scroll-mt-20 gap-3 rounded-xl px-4 py-3.5",
highlight && "ring-2 ring-ring/50",
)}
aria-label={job.name}
>
<header className="flex items-start justify-between gap-3">
<div className="min-w-0">
<h3 className="truncate text-lead font-medium text-foreground" title={job.name}>
+111
View File
@@ -0,0 +1,111 @@
import type { EngineBusinessKind, EngineRun, EngineTriggeredBy } from "@umt/contracts";
import { consolePath } from "~/components/console/nav.ts";
import type { StatusTone } from "~/components/console/status-badge.tsx";
// 统一任务流的标签:引擎 run + business(W9-I)。一条 run = 一条任务。
export const BUSINESS_KIND_LABEL: Record<EngineBusinessKind, string> = {
subscription: "订阅",
download: "下载",
organization: "整理",
agent: "Agent",
schedule: "定时任务",
feed: "Feed",
site: "站点",
decision: "待处理事项",
media: "作品",
};
export const BUSINESS_KINDS = Object.keys(BUSINESS_KIND_LABEL) as EngineBusinessKind[];
/** 来源:四类(定时/事件/手动/Agent);API Key 调用算手动 */
export type TaskSource = "schedule" | "event" | "manual" | "agent";
export const SOURCE_LABEL: Record<TaskSource, string> = {
schedule: "定时",
event: "事件",
manual: "手动",
agent: "Agent",
};
export function sourceOf(t: EngineTriggeredBy | null | undefined): TaskSource | null {
if (!t) return null;
if (t === "user" || t === "api_key") return "manual";
return t;
}
/** 引擎工作流名 → 做什么 */
export const WORKFLOW_LABEL: Record<string, string> = {
ingestFeed: "抓取 Feed",
resolveObservation: "识别资源",
evaluateAcquisition: "评估候选",
submitDownload: "提交下载",
verifyAndImport: "核验入库",
refreshMetadata: "刷新元数据",
reconcileLibrary: "资产对账",
cleanupDownloadCache: "清理缓存",
resolveDecision: "处理待处理事项",
runAgent: "Agent 会话",
snapshotSite: "站点快照",
refreshSiteAccount: "刷新站点账号",
searchSubscription: "订阅搜索",
purgeTrash: "清理回收站",
refreshPiTokens: "刷新上游登录",
};
export const workflowLabel = (name: string) => WORKFLOW_LABEL[name] ?? name;
/** 引擎状态 → 任务状态 */
const RUN_STATUS: Record<string, { label: string; tone: StatusTone }> = {
pending: { label: "排队", tone: "neutral" },
running: { label: "进行中", tone: "neutral" },
sleeping: { label: "等待", tone: "neutral" },
completed: { label: "完成", tone: "success" },
succeeded: { label: "完成", tone: "success" },
failed: { label: "失败", tone: "destructive" },
canceled: { label: "已取消", tone: "warning" },
};
export const runStatus = (s: string) => RUN_STATUS[s] ?? { label: s, tone: "neutral" as StatusTone };
export const RUN_STATUS_OPTIONS = ["pending", "running", "completed", "failed", "canceled"].map((value) => ({
value,
label: runStatus(value).label,
}));
/** 行标题:业务对象名 > 业务类型 + 短 id > 工作流做什么 */
export function runTitle(r: Pick<EngineRun, "business" | "workflowName">): string {
const b = r.business;
if (b?.title) return b.title;
if (b) return `${BUSINESS_KIND_LABEL[b.kind]} ${b.refId.length > 12 ? b.refId.slice(0, 8) : b.refId}`;
return workflowLabel(r.workflowName);
}
/** 业务对象的"家"页面 */
export function businessLink(b: EngineRun["business"], input?: unknown): { to: string; label: string } | null {
if (!b) return null;
const id = encodeURIComponent(b.refId);
switch (b.kind) {
case "subscription":
return { to: consolePath("subscriptions"), label: "订阅" };
case "download": {
// 计划还没提交时 refId 是下载计划
const i = (input ?? {}) as { downloadTaskId?: unknown; acquisitionPlanId?: unknown };
if (!i.downloadTaskId && i.acquisitionPlanId === b.refId)
return { to: consolePath("downloads", "plans"), label: "下载计划" };
return { to: `/console/downloads/${id}`, label: "下载任务" };
}
case "organization":
return { to: `/console/organize/${id}`, label: "整理记录" };
case "agent":
return { to: `/console/agent/${id}`, label: "Agent 会话" };
case "schedule":
return { to: `/console/tasks?tab=plan&job=${id}`, label: "定时任务" };
case "feed":
return { to: consolePath("sources"), label: "Feed" };
case "site":
return { to: `/console/sites/${id}`, label: "站点" };
case "decision":
return { to: consolePath("inbox"), label: "待处理" };
case "media":
return { to: `/console/library/${id}`, label: "作品" };
default:
return null;
}
}
export const ENGINE_ACTIVE = new Set(["pending", "running", "sleeping"]);
@@ -0,0 +1,351 @@
import type { EngineRunDetail, EngineStepAttempt } from "@umt/contracts";
import { Ban, ChevronDown, ExternalLink, Repeat, ScrollText } from "lucide-react";
import { type ReactNode, useState } from "react";
import { Link } from "react-router";
import { toast } from "sonner";
import { ENGINE_TERMINAL, useCancelEngineRun, useEngineRun, useRetryEngineRun } from "~/api/engine.ts";
import { ConfirmDialog } from "~/components/console/confirm-dialog.tsx";
import { DetailSection } from "~/components/console/detail-sheet.tsx";
import { EmptyState, ErrorState, LoadingState } from "~/components/console/empty-state.tsx";
import { JsonView } from "~/components/console/json-view.tsx";
import { KvList } from "~/components/console/kv-list.tsx";
import { StatusBadge } from "~/components/console/status-badge.tsx";
import { Timeline, type TimelineItem } from "~/components/console/timeline.tsx";
import { Button } from "~/components/ui/button.tsx";
import { errorMessage } from "~/lib/api.ts";
import { formatDuration, formatRelative, spanSec } from "~/lib/labels.ts";
import { cn, formatDateTime } from "~/lib/utils.ts";
import { BUSINESS_KIND_LABEL, businessLink, runStatus, SOURCE_LABEL, sourceOf, workflowLabel } from "./labels.ts";
// 任务详情:业务摘要 → 时间线 → 引擎步骤(折叠)→ 操作。任务页抽屉与 /tasks/:id 共用。
const KIND_LABEL: Record<string, string> = {
function: "函数",
sleep: "休眠",
workflow: "子工作流",
"signal-send": "发送信号",
"signal-wait": "等待信号",
};
function stepTone(s: string) {
if (s === "completed" || s === "succeeded") return "success" as const;
if (s === "failed") return "destructive" as const;
return "neutral" as const;
}
/** 错误对象里的一句话 */
export function errorText(e: unknown): string | null {
if (e === null || e === undefined) return null;
if (typeof e === "string") return e;
const m = (e as { message?: unknown }).message;
return typeof m === "string" ? m : JSON.stringify(e).slice(0, 300);
}
/** 引擎步骤尝试(原引擎面板详情) */
function stepItems(steps: EngineStepAttempt[], onOpenRun?: (id: string) => void): TimelineItem[] {
const seen = new Map<string, number>();
return steps.map((st) => {
const n = (seen.get(st.stepName) ?? 0) + 1;
seen.set(st.stepName, n);
const hasError = st.error !== null && st.error !== undefined;
return {
id: st.id,
at: st.startedAt ?? st.createdAt,
tone: stepTone(st.status),
title: (
<span>
{st.stepName}
<span className="ml-2 text-meta font-normal text-muted-foreground">
{KIND_LABEL[st.kind] ?? st.kind} · {runStatus(st.status).label}
{n > 1 ? ` · 第 ${n} 次` : ""}
</span>
</span>
),
meta: formatDuration(spanSec(st)),
description: (
<>
{st.waitSignal ? (
<p>
等待信号 <code className="font-mono">{st.waitSignal}</code>
{st.timeoutAt ? ` · 超时于 ${formatDateTime(st.timeoutAt)}` : ""}
</p>
) : null}
{st.childWorkflowRunId ? (
<p>
子任务{" "}
<button
type="button"
className="cursor-pointer font-mono underline"
onClick={() => onOpenRun?.(st.childWorkflowRunId ?? "")}
>
{st.childWorkflowRunId}
</button>
</p>
) : null}
<p className="font-mono text-meta">{st.id}</p>
</>
),
children: hasError ? (
<JsonView label="错误" value={st.error} tone="destructive" defaultOpen />
) : st.output !== null && st.output !== undefined ? (
<JsonView label="输出" value={st.output} defaultOpen={false} maxHeight="14rem" />
) : undefined,
};
});
}
/** 业务时间线:创建 → 开始 → 等待 / 失败的步骤 → 结束 */
function businessTimeline(r: EngineRunDetail): TimelineItem[] {
const src = sourceOf(r.business?.triggeredBy);
const items: TimelineItem[] = [
{ id: "created", at: r.createdAt, title: `创建${src ? `(${SOURCE_LABEL[src]}触发)` : ""}`, tone: "neutral" },
];
if (r.startedAt)
items.push({
id: "started",
at: r.startedAt,
title: r.attempts > 1 ? `开始执行 · 第 ${r.attempts} 次尝试` : "开始执行",
tone: "neutral",
});
for (const st of r.stepAttempts) {
if (st.waitSignal && !st.finishedAt)
items.push({ id: `w-${st.id}`, at: st.startedAt ?? st.createdAt, title: `等待:${st.stepName}`, tone: "warning" });
else if (st.status === "failed")
items.push({
id: `f-${st.id}`,
at: st.finishedAt ?? st.startedAt ?? st.createdAt,
title: `步骤失败:${st.stepName}`,
description: errorText(st.error),
tone: "destructive",
});
}
if (r.finishedAt) {
const s = runStatus(r.status);
items.push({
id: "finished",
at: r.finishedAt,
title: s.label,
// 与最后一个失败步骤相同的错误不再重复
description:
r.status === "failed" && !r.stepAttempts.some((st) => errorText(st.error) === errorText(r.error))
? errorText(r.error)
: undefined,
tone: s.tone,
meta: formatDuration(spanSec(r)),
});
} else if (r.startedAt) {
items.push({ id: "now", title: "进行中", tone: "neutral", meta: `已 ${formatDuration(spanSec(r))}` });
}
return items;
}
/** 取消 / 重跑 */
export function RunActions({
r,
onOpenRun,
size = "sm",
}: {
r: EngineRunDetail;
onOpenRun?: (id: string) => void;
size?: "sm" | "xs";
}) {
const cancel = useCancelEngineRun();
const retry = useRetryEngineRun();
if (!ENGINE_TERMINAL.has(r.status))
return (
<ConfirmDialog
trigger={
<Button variant="destructive" size={size}>
<Ban />
取消任务
</Button>
}
title="取消这个任务?"
description="正在执行的步骤会在下一个检查点退出,已完成的步骤不回滚。"
confirmLabel="取消任务"
cancelLabel="不取消"
destructive
onConfirm={async () => {
try {
const res = await cancel.mutateAsync({ id: r.id, reason: "控制台手动取消" });
if (res.canceled) toast.success("已取消");
else toast.warning("任务已结束");
} catch (err) {
toast.error(errorMessage(err, "取消失败"));
throw err;
}
}}
/>
);
return (
<ConfirmDialog
trigger={
<Button variant="outline" size={size} disabled={retry.isPending}>
<Repeat />
重跑
</Button>
}
title="重跑这个任务?"
description="用原始输入新建一条任务,原记录不变。已完成的文件操作不会重复执行。"
confirmLabel="重跑"
cancelLabel="不重跑"
onConfirm={async () => {
try {
const res = await retry.mutateAsync({ id: r.id });
toast.success(`已重新排队(第 ${res.attempt} 次重跑)`);
onOpenRun?.(res.runId);
} catch (err) {
toast.error(errorMessage(err, "重跑失败"));
throw err;
}
}}
/>
);
}
function Collapsible({ title, children }: { title: string; children: ReactNode }) {
const [open, setOpen] = useState(false);
return (
<section>
<button
type="button"
aria-expanded={open}
onClick={() => setOpen((v) => !v)}
className="flex w-full cursor-pointer items-center gap-2 text-label font-semibold tracking-[0.18em] text-muted-foreground uppercase hover:text-foreground"
>
<ChevronDown className={cn("h-3.5 w-3.5 transition-transform", !open && "-rotate-90")} />
{title}
</button>
{open ? <div className="mt-3 space-y-4">{children}</div> : null}
</section>
);
}
/** 详情主体(不含外框);抽屉和独立页都用 */
export function TaskDetailBody({ r, onOpenRun }: { r: EngineRunDetail; onOpenRun?: (id: string) => void }) {
const b = r.business;
const link = businessLink(b, r.input);
const src = sourceOf(b?.triggeredBy);
const hasError = r.error !== null && r.error !== undefined;
const audits = [
{ to: `/console/audit?targetType=engine_run&targetId=${encodeURIComponent(r.id)}`, label: "本任务的操作记录" },
...(b?.kind === "schedule"
? [
{
to: `/console/audit?targetType=scheduled_job&targetId=${encodeURIComponent(b.refId)}`,
label: "定时任务的修改记录",
},
]
: []),
];
return (
<>
<DetailSection title="业务摘要">
<KvList
items={[
{
label: "关联对象",
value: b ? (
link ? (
<Link to={link.to} className="inline-flex items-center gap-1 underline underline-offset-4">
{BUSINESS_KIND_LABEL[b.kind]} · {b.title ?? b.refId}
<ExternalLink className="h-3 w-3" />
</Link>
) : (
`${BUSINESS_KIND_LABEL[b.kind]} · ${b.title ?? b.refId}`
)
) : (
"无"
),
wide: true,
},
{ label: "做什么", value: workflowLabel(r.workflowName) },
{ label: "来源", value: src ? SOURCE_LABEL[src] : "未知" },
{
label: "开始",
value: r.startedAt ? `${formatDateTime(r.startedAt)}(${formatRelative(r.startedAt)})` : "未开始",
},
{ label: "耗时", value: formatDuration(spanSec(r)) },
]}
/>
</DetailSection>
<DetailSection title="时间线">
<Timeline items={businessTimeline(r)} />
</DetailSection>
<DetailSection title="相关审计">
<ul className="flex flex-wrap gap-x-4 gap-y-1 text-caption">
{audits.map((a) => (
<li key={a.to}>
<Link
to={a.to}
className="inline-flex items-center gap-1 text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"
>
<ScrollText className="h-3.5 w-3.5" />
{a.label}
</Link>
</li>
))}
</ul>
</DetailSection>
<Collapsible title={`引擎步骤(${r.stepAttempts.length})`}>
<KvList
items={[
{ label: "工作流", value: `${r.workflowName}${r.version ? ` ${r.version}` : ""}`, mono: true },
{ label: "运行 ID", value: r.id, mono: true },
{ label: "尝试次数", value: r.attempts },
{ label: "Worker", value: r.workerId, mono: true },
{ label: "可执行于", value: formatDateTime(r.availableAt) },
{ label: "截止", value: formatDateTime(r.deadlineAt) },
{ label: "父步骤", value: r.parentStepAttemptId, mono: true },
]}
/>
{r.stepAttempts.length === 0 ? (
<EmptyState plain title="还没有步骤" className="py-6" />
) : (
<Timeline items={stepItems(r.stepAttempts, onOpenRun)} />
)}
{hasError ? <JsonView label="错误" value={r.error} tone="destructive" /> : null}
<JsonView label="输入" value={r.input} defaultOpen={false} />
{!hasError ? <JsonView label="输出" value={r.output} defaultOpen={false} /> : null}
{r.signals.length ? (
<div className="space-y-2">
<p className="text-meta text-muted-foreground">信号({r.signals.length})</p>
{r.signals.map((sg) => (
<div key={sg.id} className="min-w-0">
<p className="text-sm">
<code className="font-mono">{sg.signal}</code>
<span className="ml-2 text-meta text-muted-foreground">{formatDateTime(sg.createdAt)}</span>
</p>
<JsonView value={sg.data} maxHeight="10rem" className="mt-1" />
</div>
))}
</div>
) : null}
</Collapsible>
</>
);
}
/** 头部一行:状态 + 业务类型 */
export function TaskStatusLine({ r }: { r: EngineRunDetail }) {
const s = runStatus(r.status);
return (
<span className="flex flex-wrap items-center gap-2">
<StatusBadge tone={s.tone}>{s.label}</StatusBadge>
<span>{workflowLabel(r.workflowName)}</span>
{r.business ? <span>· {BUSINESS_KIND_LABEL[r.business.kind]}</span> : null}
</span>
);
}
/** 按 id 取数并渲染(抽屉用) */
export function TaskDetail({ runId, onOpenRun }: { runId: string; onOpenRun?: (id: string) => void }) {
const q = useEngineRun(runId);
if (q.isPending) return <LoadingState rows={6} />;
if (q.isError) return <ErrorState plain error={q.error} onRetry={() => q.refetch()} />;
return <TaskDetailBody r={q.data} onOpenRun={onOpenRun} />;
}
@@ -0,0 +1,300 @@
import { useQueryClient } from "@tanstack/react-query";
import type { EngineBusinessKind, EngineRun, ScheduledJob } from "@umt/contracts";
import { CalendarClock, ExternalLink, History, ListTodo, X } from "lucide-react";
import { useMemo, useRef, useState } from "react";
import { Link } from "react-router";
import { useEngineRuns, useEngineRunsPage } from "~/api/engine.ts";
import { useScheduleBoard } from "~/api/schedules.ts";
import { DataTable } from "~/components/console/data-table.tsx";
import { FilterBar, FilterSelect } from "~/components/console/filter-bar.tsx";
import { StatusBadge } from "~/components/console/status-badge.tsx";
import { RunsSheet } from "~/components/schedules/runs-sheet.tsx";
import { Button } from "~/components/ui/button.tsx";
import { formatDuration, formatRelative, spanSec } from "~/lib/labels.ts";
import { qk } from "~/lib/query-keys.ts";
import { useSse } from "~/lib/sse.ts";
import {
BUSINESS_KIND_LABEL,
BUSINESS_KINDS,
businessLink,
ENGINE_ACTIVE,
RUN_STATUS_OPTIONS,
runStatus,
runTitle,
SOURCE_LABEL,
sourceOf,
type TaskSource,
workflowLabel,
} from "./labels.ts";
export type StreamTab = "all" | "active" | "failed";
/** 引擎本身不发事件;业务事件足以代表任务在动,2 秒节流刷新 */
const TASK_EVENTS = [
"task.created",
"task.status_changed",
"download.status_changed",
"organization.changed",
"agent.run_status",
"schedule.changed",
];
export function useLiveTasks() {
const qc = useQueryClient();
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
useSse(TASK_EVENTS, () => {
if (timer.current) return;
timer.current = setTimeout(() => {
timer.current = null;
qc.invalidateQueries({ queryKey: qk.all("engine") });
}, 2000);
});
}
const SINCE: { value: string; label: string; ms: number }[] = [
{ value: "1h", label: "1 小时内", ms: 3600_000 },
{ value: "24h", label: "24 小时内", ms: 86400_000 },
{ value: "7d", label: "7 天内", ms: 7 * 86400_000 },
{ value: "30d", label: "30 天内", ms: 30 * 86400_000 },
];
export type StreamFilters = {
status: string;
kind: string;
ref: string;
source: string;
since: string;
workflow: string;
};
function SourceBadge({ r }: { r: EngineRun }) {
const s = sourceOf(r.business?.triggeredBy);
return s ? <span className="text-caption">{SOURCE_LABEL[s]}</span> : <span className="text-muted-foreground">—</span>;
}
/** 定时任务筛选时,页头给出定时任务自己的运行记录(含跳过的,引擎里没有) */
function ScheduleBanner({ jobId, onClear }: { jobId: string; onClear: () => void }) {
const board = useScheduleBoard();
const job = board.data?.items.find((j) => j.id === jobId) ?? null;
const [open, setOpen] = useState<ScheduledJob | null>(null);
return (
<div className="mb-3 flex flex-wrap items-center gap-2 rounded-xl border border-border/70 px-3 py-2 text-caption">
<CalendarClock className="h-4 w-4 text-muted-foreground" />
<span className="min-w-0 truncate">
定时任务 <span className="font-medium text-foreground">{job?.name ?? jobId}</span> 触发的任务
</span>
<span className="ml-auto flex items-center gap-1">
<Button variant="ghost" size="xs" disabled={!job} onClick={() => setOpen(job)}>
<History />
运行记录
</Button>
<Button asChild variant="ghost" size="xs">
<Link to={`/console/tasks?tab=plan&job=${encodeURIComponent(jobId)}`}>
<ExternalLink />
计划
</Link>
</Button>
<Button variant="ghost" size="icon-xs" aria-label="清除定时任务筛选" onClick={onClear}>
<X />
</Button>
</span>
<RunsSheet job={open} onClose={() => setOpen(null)} />
</div>
);
}
export function TaskStream({
tab,
filters,
setFilter,
resetFilters,
onOpen,
selectedId,
}: {
tab: StreamTab;
filters: StreamFilters;
setFilter: (k: keyof StreamFilters, v: string) => void;
resetFilters: () => void;
onOpen: (id: string) => void;
selectedId: string | null;
}) {
useLiveTasks();
// 时间下界按分钟取整,查询 key 稳定
const from = useMemo(() => {
const ms = SINCE.find((s) => s.value === filters.since)?.ms;
return ms ? new Date(Math.floor((Date.now() - ms) / 60_000) * 60_000).toISOString() : undefined;
}, [filters.since]);
const base = {
businessKind: (filters.kind || undefined) as EngineBusinessKind | undefined,
businessRefId: filters.ref || undefined,
workflowName: filters.workflow || undefined,
from,
};
const list = useEngineRuns(
{
...base,
status: tab === "failed" ? "failed" : filters.status || undefined,
},
tab !== "active",
);
// 进行中 = 进行中 + 排队(两次取第一页合并)
const running = useEngineRunsPage({ ...base, status: "running" }, 100, 10_000, tab === "active");
const pending = useEngineRunsPage({ ...base, status: "pending" }, 100, 10_000, tab === "active");
const active = tab === "active";
const loaded = active
? running.data && pending.data
? [...running.data.items, ...pending.data.items]
: undefined
: list.data?.pages.flatMap((p) => p.items);
const rows = filters.source ? loaded?.filter((r) => sourceOf(r.business?.triggeredBy) === filters.source) : loaded;
const filtered = Object.values(filters).some(Boolean);
return (
<>
{filters.kind === "schedule" && filters.ref ? (
<ScheduleBanner
jobId={filters.ref}
onClear={() => {
setFilter("ref", "");
setFilter("kind", "");
}}
/>
) : filters.ref ? (
<div className="mb-3 flex items-center gap-2 text-caption text-muted-foreground">
只看对象 <code className="font-mono text-foreground">{filters.ref}</code>
<Button variant="ghost" size="icon-xs" aria-label="清除对象筛选" onClick={() => setFilter("ref", "")}>
<X />
</Button>
</div>
) : null}
<FilterBar onReset={filtered ? resetFilters : undefined}>
<FilterSelect
label="来源"
value={filters.source}
onChange={(v) => setFilter("source", v)}
options={(Object.keys(SOURCE_LABEL) as TaskSource[]).map((value) => ({ value, label: SOURCE_LABEL[value] }))}
/>
<FilterSelect
label="业务"
value={filters.kind}
onChange={(v) => setFilter("kind", v)}
options={BUSINESS_KINDS.map((value) => ({ value, label: BUSINESS_KIND_LABEL[value] }))}
/>
{tab === "all" ? (
<FilterSelect
label="状态"
value={filters.status}
onChange={(v) => setFilter("status", v)}
options={RUN_STATUS_OPTIONS}
/>
) : null}
<FilterSelect
label="时间"
value={filters.since}
onChange={(v) => setFilter("since", v)}
options={SINCE}
allLabel="不限"
/>
{filters.workflow ? (
<Button variant="outline" size="sm" onClick={() => setFilter("workflow", "")}>
{workflowLabel(filters.workflow)}
<X />
</Button>
) : null}
</FilterBar>
<DataTable<EngineRun>
rows={rows}
rowKey={(r) => r.id}
loading={active ? running.isPending || pending.isPending : list.isPending}
error={active ? (running.error ?? pending.error) : list.error}
onRetry={() => {
if (active) {
void running.refetch();
void pending.refetch();
} else void list.refetch();
}}
onRowClick={(r) => onOpen(r.id)}
selectedKey={selectedId}
hasMore={!active && !!list.hasNextPage}
onLoadMore={() => list.fetchNextPage()}
loadingMore={list.isFetchingNextPage}
empty={{
icon: ListTodo,
title: filtered
? "没有符合条件的任务"
: tab === "active"
? "没有进行中的任务"
: tab === "failed"
? "没有失败的任务"
: "还没有任务",
description: filters.source && loaded?.length ? "来源筛选只作用于已加载的记录,可加载更多再看。" : undefined,
}}
columns={[
{
key: "title",
header: "任务",
cell: (r) => (
<div className="min-w-0 max-w-[15rem] sm:max-w-sm">
<p className="truncate font-medium text-foreground">{runTitle(r)}</p>
<p className="truncate text-meta text-muted-foreground">
{r.business
? `${workflowLabel(r.workflowName)} · ${BUSINESS_KIND_LABEL[r.business.kind]}`
: `未关联业务对象 · ${r.id.slice(0, 8)}`}
</p>
</div>
),
},
{ key: "source", header: "来源", hideBelow: "md", cell: (r) => <SourceBadge r={r} /> },
{
key: "status",
header: "状态",
cell: (r) => {
const s = runStatus(r.status);
return <StatusBadge tone={s.tone}>{s.label}</StatusBadge>;
},
},
{
key: "time",
header: "开始 / 耗时",
hideBelow: "sm",
cell: (r) => (
<div className="whitespace-nowrap">
<p className="text-muted-foreground" title={r.startedAt ?? r.createdAt}>
{r.startedAt
? formatRelative(r.startedAt)
: ENGINE_ACTIVE.has(r.status)
? `排队 ${formatRelative(r.createdAt)}`
: `未开始 · ${formatRelative(r.createdAt)}`}
</p>
<p className="text-meta text-muted-foreground tabular-nums">{formatDuration(spanSec(r))}</p>
</div>
),
},
{
key: "link",
header: "关联",
hideBelow: "lg",
cell: (r) => {
const l = businessLink(r.business);
return l ? (
<Link
to={l.to}
onClick={(e) => e.stopPropagation()}
className="inline-flex items-center gap-1 text-caption text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"
>
{l.label}
<ExternalLink className="h-3 w-3" />
</Link>
) : (
<span className="text-muted-foreground">—</span>
);
},
},
]}
/>
</>
);
}