import { useEffect, useState } from "react"; import { Clock, Play, Pause, Lightning, CaretRight, ArrowsClockwise, CheckCircle, XCircle, Timer, Heartbeat, Gear, X, } from "@phosphor-icons/react"; import { fetchCronJobs, fetchCronRuns, fetchSystemCrons, toggleCronJob, runCronJob, type CronJob, type CronRun, type SystemCron, } from "../api"; import { useLocale } from "../hooks/useLocale"; type Tab = "user" | "system"; export function CronManager() { const { t } = useLocale(); const [tab, setTab] = useState("user"); const [jobs, setJobs] = useState([]); const [systemCrons, setSystemCrons] = useState([]); const [loading, setLoading] = useState(true); const [selectedJob, setSelectedJob] = useState(null); const [runs, setRuns] = useState([]); const [runsLoading, setRunsLoading] = useState(false); const [actionLoading, setActionLoading] = useState(null); const [toast, setToast] = useState<{ message: string; type: "ok" | "error" } | null>(null); const showToast = (message: string, type: "ok" | "error" = "ok") => { setToast({ message, type }); setTimeout(() => setToast(null), 3000); }; const loadJobs = async () => { try { const data = await fetchCronJobs(); setJobs(data); } catch (e) { console.error("Failed to load cron jobs:", e); } finally { setLoading(false); } }; const loadSystemCrons = async () => { try { const data = await fetchSystemCrons(); setSystemCrons(data); } catch (e) { console.error("Failed to load system crons:", e); } }; useEffect(() => { loadJobs(); loadSystemCrons(); const interval = setInterval(loadJobs, 30000); return () => clearInterval(interval); }, []); useEffect(() => { if (!selectedJob) { setRuns([]); return; } (async () => { setRunsLoading(true); try { const data = await fetchCronRuns(selectedJob); setRuns(data); } catch (e) { console.error("Failed to load runs:", e); } finally { setRunsLoading(false); } })(); }, [selectedJob]); const handleToggle = async (job: CronJob) => { setActionLoading(job.id); try { await toggleCronJob(job.id, !job.enabled); showToast(`${!job.enabled ? "✅ 已启用" : "⏸ 已禁用"} ${job.name}`); await loadJobs(); } catch (e: any) { showToast(`❌ ${e.message || "操作失败"}`, "error"); } finally { setActionLoading(null); } }; const handleRun = async (job: CronJob) => { setActionLoading(`run-${job.id}`); try { const result = await runCronJob(job.id); if (result.success) { showToast(`⚡ ${job.name} 已触发运行`); setTimeout(loadJobs, 2000); } else { showToast(`❌ ${result.error || "运行失败"}`, "error"); } } catch (e: any) { showToast(`❌ ${e.message || "请求失败"}`, "error"); } finally { setActionLoading(null); } }; const enabledCount = jobs.filter((j) => j.enabled).length; const disabledCount = jobs.length - enabledCount; function formatRelativeTime(iso: string | null): string { if (!iso) return "-"; const date = new Date(iso); const now = new Date(); const diffMs = date.getTime() - now.getTime(); const absDiff = Math.abs(diffMs); const isPast = diffMs < 0; if (absDiff < 60000) return isPast ? t("cron.justNow") : t("cron.soonLabel"); if (absDiff < 3600000) { const mins = Math.floor(absDiff / 60000); return isPast ? `${mins}${t("cron.minAgo")}` : `${mins}${t("cron.minLater")}`; } if (absDiff < 86400000) { const hours = Math.floor(absDiff / 3600000); return isPast ? `${hours}${t("cron.hAgo")}` : `${hours}${t("cron.hLater")}`; } const days = Math.floor(absDiff / 86400000); return isPast ? `${days}${t("cron.dAgo")}` : `${days}${t("cron.dLater")}`; } function statusColor(status: string | null): string { if (!status) return "var(--text-muted)"; if (status === "ok" || status === "completed") return "#22c55e"; if (status === "failed" || status === "error") return "#ef4444"; return "#eab308"; } if (loading) { return (
{t("cron.loading")}
); } return (
{/* Toast */} {toast && (
{toast.message}
)}
{/* Header */}

{t("cron.title")}

{t("cron.subtitle")}

{/* Tabs */}
{tab === "user" && ( <> {/* Stats */}
{jobs.length}
{t("cron.total")}
{enabledCount}
{t("cron.enabled")}
{disabledCount}
{t("cron.disabled")}
{/* Job List */}
{jobs.map((job) => (
{job.name} {job.schedule}
{job.lastRun && ( {formatRelativeTime(job.lastRun)} )} {job.nextRun && job.enabled && ( {formatRelativeTime(job.nextRun)} )} {job.sessionTarget}
{/* Run History */} {selectedJob === job.id && (
{t("cron.runHistory")}
{runsLoading ? (
{t("cron.loading")}
) : runs.length === 0 ? (
{t("cron.noRuns")}
) : (
{runs.map((run, i) => (
{run.status === "completed" || run.status === "ok" ? ( ) : run.status === "failed" || run.status === "error" ? ( ) : ( )} {run.status || "unknown"}
{run.durationMs != null && {(run.durationMs / 1000).toFixed(1)}s} {(() => { const ts = run.runAtMs || run.ts || run.startedAt; if (!ts) return "—"; const d = new Date(typeof ts === "number" ? ts : ts); return isNaN(d.getTime()) ? "—" : d.toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", }); })()}
))}
)}
)}
))}
{jobs.length === 0 && (

{t("cron.empty")}

)} )} {tab === "system" && (
{systemCrons.map((sc) => (
{sc.name} {sc.schedule}
{sc.description}
{sc.enabled ? "运行中" : "禁用"}
{/* Heartbeat agent details */} {sc.type === "heartbeat" && sc.agents && (
{sc.agents.map((agent) => (
{agent.name} ({agent.id}) {agent.heartbeat === "disabled" ? "禁用" : agent.heartbeat}
))}
)}
))} {systemCrons.length === 0 && (

无法读取系统调度信息

)}
)}
); }