import { useRef, useState } from "react"; import { CalendarClock, ChevronRight, CircleAlert, RefreshCcw, } from "lucide-react"; import type { TFunction } from "i18next"; import { useTranslation } from "react-i18next"; import { AutomationDeleteDialog, AutomationDetailDialog, AutomationEditDialog, } from "@/components/settings/system/AutomationsSettings"; import type { AutomationAction } from "@/components/settings/system/AutomationsSettings"; import { Button } from "@/components/ui/button"; import { formControlFocusClassName } from "@/components/ui/form-control"; import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover"; import { useSessionAutomationJobs } from "@/hooks/useSessionAutomationJobs"; import { currentLocale } from "@/i18n"; import { runAutomationAction, updateAutomation } from "@/lib/api"; import type { WebUIMutationTransport } from "@/lib/api"; import { fmtDateTime } from "@/lib/format"; import type { AutomationUpdatePayload, SessionAutomationJob, } from "@/lib/types"; import { cn } from "@/lib/utils"; const RELATIVE_THRESHOLDS: [number, Intl.RelativeTimeFormatUnit][] = [ [60, "second"], [60, "minute"], [24, "hour"], [7, "day"], [4.345, "week"], [12, "month"], [Number.POSITIVE_INFINITY, "year"], ]; interface SessionInfoPopoverProps { client: WebUIMutationTransport; sessionKey: string; token: string; title: string; } export function SessionInfoPopover({ client, sessionKey, token, title }: SessionInfoPopoverProps) { const { t } = useTranslation("common"); const [open, setOpen] = useState(false); const [inspectedJob, setInspectedJob] = useState(null); const [detailOpen, setDetailOpen] = useState(false); const [actionKey, setActionKey] = useState(null); const [actionError, setActionError] = useState(null); const [pendingEdit, setPendingEdit] = useState(null); const [pendingDelete, setPendingDelete] = useState(null); const triggerRef = useRef(null); const afterDetailClose = useRef<(() => void) | null>(null); const surfacesOpen = open || detailOpen || Boolean(pendingEdit) || Boolean(pendingDelete); const { jobs, loading, loadFailed, now } = useSessionAutomationJobs( surfacesOpen, token, sessionKey, ); const selectedJob = inspectedJob; const inspectJob = (job: SessionAutomationJob) => { setActionError(null); setInspectedJob(job); setOpen(false); setDetailOpen(true); }; const handOffDetail = (next: () => void) => { afterDetailClose.current = next; setDetailOpen(false); }; const updateInspectedJob = (nextJobs: SessionAutomationJob[], id: string) => { const nextJob = nextJobs.find((job) => job.id === id); if (nextJob) setInspectedJob(nextJob); }; const handleAction = async (action: AutomationAction, job: SessionAutomationJob) => { const key = `${action}:${job.id}`; setActionKey(key); setActionError(null); try { const payload = await runAutomationAction(client, action, job.id); if (action === "delete") { setPendingDelete(null); setInspectedJob(null); } else { updateInspectedJob(payload.jobs, job.id); } } catch (error) { setActionError(error instanceof Error ? error.message : String(error)); } finally { setActionKey(null); } }; const handleEdit = async (job: SessionAutomationJob, values: AutomationUpdatePayload) => { const key = `update:${job.id}`; setActionKey(key); setActionError(null); try { const payload = await updateAutomation(client, job.id, values); updateInspectedJob(payload.jobs, job.id); setPendingEdit(null); } catch (error) { setActionError(error instanceof Error ? error.message : String(error)); } finally { setActionKey(null); } }; const automationContent = loading ? (
{t("thread.sessionInfo.loading")}
) : loadFailed ? (
{t("thread.sessionInfo.loadFailed")}
) : jobs.length ? (
{jobs.map((job) => ( ))}
) : (
{t("thread.sessionInfo.empty")}
); return ( <> { if (detailOpen) event.preventDefault(); }} >
{t("thread.sessionInfo.title")}
{title || t("thread.sessionInfo.untitled")}
{t("thread.sessionInfo.automations")} {t("thread.sessionInfo.count", { count: jobs.length })}
{automationContent}
handOffDetail(() => setPendingEdit(job))} onRequestDelete={(job) => handOffDetail(() => setPendingDelete(job))} onCloseAutoFocus={(event) => { event.preventDefault(); if (detailOpen) return; setInspectedJob(null); triggerRef.current?.focus({ preventScroll: true }); const next = afterDetailClose.current; afterDetailClose.current = null; next?.(); }} /> { if (!nextOpen) setPendingEdit(null); }} onCancel={(job) => { setInspectedJob(job); setDetailOpen(true); }} onSave={handleEdit} /> { if (!nextOpen) setPendingDelete(null); }} onConfirm={(job) => handleAction("delete", job)} /> ); } function AutomationRow({ job, now, onSelect, }: { job: SessionAutomationJob; now: number; onSelect: (job: SessionAutomationJob) => void; }) { const { t } = useTranslation("common"); const nextRun = formatNextRun(job, t, now); const needsAttention = job.state.last_status === "error" || Boolean(job.state.last_error); const summary = needsAttention ? t("settings.automations.filters.failed", { defaultValue: "Needs attention" }) : nextRun.label; const statusClass = job.enabled ? needsAttention ? "bg-destructive" : "bg-emerald-500" : "bg-muted-foreground/35"; return ( ); } function formatNextRun(job: SessionAutomationJob, t: TFunction, now: number) { const locale = currentLocale(); if (!job.enabled) { return { label: t("thread.sessionInfo.next.disabled"), title: "" }; } if (job.state.pending) { return { label: t("thread.sessionInfo.next.pending"), title: "" }; } if (isLocalTriggerAutomation(job)) { return { label: t("thread.sessionInfo.next.local"), title: "" }; } const next = job.state.next_run_at_ms; if (!next) { return { label: t("thread.sessionInfo.next.none"), title: "" }; } return { label: t("thread.sessionInfo.next.label", { time: relativeTimeFrom(next, now, locale) }), title: fmtDateTime(next, locale), }; } function isLocalTriggerAutomation(job: SessionAutomationJob): boolean { return job.kind === "local_trigger" || job.payload.kind === "local_trigger" || job.schedule.kind === "local"; } function relativeTimeFrom(value: number, now: number, locale: string): string { let delta = (value - now) / 1000; const formatter = new Intl.RelativeTimeFormat(locale, { numeric: "auto" }); for (const [step, unit] of RELATIVE_THRESHOLDS) { if (Math.abs(delta) < step) { return formatter.format(Math.round(delta), unit); } delta /= step; } return formatter.format(Math.round(delta), "year"); }