import { useEffect, useRef, useState } from "react"; import { CalendarClock, ChevronRight, CircleAlert, } 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 { SkeletonStatus } from "@/components/settings/shared/SkeletonStatus"; import { formControlFocusClassName } from "@/components/ui/form-control"; import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover"; import { currentLocale } from "@/i18n"; import { fmtDateTime } from "@/lib/format-time"; 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"], ]; export function SessionInfoPopoverView({ title, jobs, loading, loadFailed, now, onAction, onEdit, onSurfacesOpenChange, calendarHref, onOpenCalendar }: { title: string; jobs: SessionAutomationJob[]; loading: boolean; loadFailed: boolean; now: number; onAction: (action: AutomationAction, job: SessionAutomationJob) => Promise; onEdit: (job: SessionAutomationJob, values: AutomationUpdatePayload) => Promise; onSurfacesOpenChange?: (open: boolean) => void; calendarHref?: string; onOpenCalendar?: () => void; }) { 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); useEffect(() => { onSurfacesOpenChange?.(surfacesOpen); }, [onSurfacesOpenChange, surfacesOpen]); 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 nextJobs = await onAction(action, job); if (action === "delete") { setPendingDelete(null); setInspectedJob(null); } else { updateInspectedJob(nextJobs, 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 nextJobs = await onEdit(job, values); updateInspectedJob(nextJobs, job.id); setPendingEdit(null); } catch (error) { setActionError(error instanceof Error ? error.message : String(error)); } finally { setActionKey(null); } }; const automationContent = loading && jobs.length === 0 ? ( {[0, 1, 2].map((index) =>
)} ) : loadFailed && jobs.length === 0 ? (
{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")} {loading && jobs.length === 0 ? "—" : 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"); }