import { useEffect, useId, useMemo, useRef, useState } from "react"; import type { FormEvent, ReactNode } from "react"; import type { TFunction } from "i18next"; import { Check, Info, CircleAlert, Clipboard, ListFilter, Loader2, } from "lucide-react"; import { useTranslation } from "react-i18next"; import { channelTranslator } from "@/channel-plugins/i18n"; import { channelUiOwner, channelUiPresentation } from "@/channel-plugins/registry"; import { AutomationCalendar } from "@/components/settings/system/AutomationCalendar"; import { AutomationRunAtPicker, parseAutomationRunAt } from "@/components/settings/system/AutomationRunAtPicker"; import { modelPresetOptionsFromSettings, toModelBadgeInfo, } from "@/components/thread/model-preset"; import { ThreadComposer } from "@/components/thread/ThreadComposer"; import { Button } from "@/components/ui/button"; import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; import { DropdownMenu, DropdownMenuContent, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; import { ExpandableText } from "@/components/ui/expandable-text"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { formControlFocusClassName } from "@/components/ui/form-control"; import { Input } from "@/components/ui/input"; import { SegmentedControl } from "@/components/ui/segmented-control"; import { Textarea } from "@/components/ui/textarea"; import { displayTitle } from "@/lib/chat-groups"; import { copyTextToClipboard } from "@/lib/clipboard"; import { fmtDateTime, relativeTime } from "@/lib/format"; import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream"; import type { AutomationsPayload, AutomationUpdatePayload, SessionAutomationJob, SettingsPayload, } from "@/lib/types"; import { cn } from "@/lib/utils"; export type AutomationFilter = "all" | "active" | "paused" | "failed" | "system"; export type AutomationAction = "enable" | "disable" | "delete" | "run"; const EMPTY_TITLE_OVERRIDES: Record = {}; export function AutomationsSettings({ token = "", payload, loading, filter, actionKey, error, titleOverrides = EMPTY_TITLE_OVERRIDES, settingsSnapshot = null, onFilterChange, onAction, onRequestEdit, onRequestDelete, onStartChat, onManageModels, returnToDetailJob = null, onReturnToDetailHandled, }: { token?: string; payload: AutomationsPayload | null; titleOverrides?: Record; settingsSnapshot?: SettingsPayload | null; loading: boolean; filter: AutomationFilter; actionKey: string | null; error: string | null; onFilterChange: (value: AutomationFilter) => void; onAction: (action: AutomationAction, job: SessionAutomationJob) => void | Promise; onRequestEdit: (job: SessionAutomationJob) => void; onRequestDelete: (job: SessionAutomationJob) => void; onStartChat?: ( content: string, images?: SendAttachment[], options?: SendOptions, modelPreset?: string | null, ) => boolean | void | Promise; onManageModels?: () => void; returnToDetailJob?: SessionAutomationJob | null; onReturnToDetailHandled?: () => void; }) { const { t, i18n } = useTranslation(); const tx = (key: string, fallback: string, values?: Record) => t(key, { defaultValue: fallback, ...(values ?? {}) }); const jobs = useMemo(() => (payload?.jobs ?? []).map((job) => { const origin = job.origin; if (origin?.channel !== "websocket") return job; // Resolve UI-only titles from live sidebar state without changing task bindings. const title = displayTitle({ key: origin.session_key ?? "", title: origin.title, preview: origin.preview ?? "", }, titleOverrides, t("chat.newChat")); return title === origin.title ? job : { ...job, origin: { ...origin, title } }; }), [payload, titleOverrides, t]); const locale = i18n.resolvedLanguage || i18n.language; const [inspectedJob, setInspectedJob] = useState(null); const [detailOpen, setDetailOpen] = useState(false); const [localModelPreset, setLocalModelPreset] = useState(null); const [view, setView] = useState<"tasks" | "calendar">("calendar"); const [month, setMonth] = useState(() => { const today = new Date(); return new Date(today.getFullYear(), today.getMonth(), 1); }); const pageTitle = useRef(null); const selectedTrigger = useRef(null); const afterDetailClose = useRef<((job: SessionAutomationJob) => void) | null>(null); const visibleJobs = useMemo(() => jobs.filter((job) => !job.protected), [jobs]); const filtered = useMemo(() => visibleJobs.filter((job) => automationMatchesFilter(job, filter)), [filter, visibleJobs]); // Keep an inspected task open when an action moves it outside the current filter. const liveSelectedJob = jobs.find((job) => job.id === inspectedJob?.id); // Retain the last detail through its exit, even if a one-shot task disappears. const selectedJob = liveSelectedJob ?? inspectedJob; const summaryOptions: Array<{ value: AutomationFilter; label: string; count: number }> = [ { value: "all", label: tx("settings.automations.filters.all", "All"), count: visibleJobs.length }, { value: "active", label: tx("settings.automations.filters.active", "Active"), count: visibleJobs.filter((job) => automationMatchesFilter(job, "active")).length }, { value: "paused", label: tx("settings.automations.filters.paused", "Disabled"), count: visibleJobs.filter((job) => automationMatchesFilter(job, "paused")).length }, { value: "failed", label: tx("settings.automations.filters.failed", "Needs attention"), count: visibleJobs.filter(automationNeedsAttention).length }, ]; const configuredPresetNames = useMemo( () => new Set(settingsSnapshot?.model_presets?.map((preset) => preset.name) ?? []), [settingsSnapshot], ); const activeModelPreset = ( (localModelPreset && (!settingsSnapshot || configuredPresetNames.has(localModelPreset)) ? localModelPreset : null) || settingsSnapshot?.agent.model_preset || "default" ); const modelPresetOptions = useMemo( () => modelPresetOptionsFromSettings(settingsSnapshot), [settingsSnapshot], ); const modelBadge = useMemo( () => toModelBadgeInfo(settingsSnapshot?.agent.model ?? null, settingsSnapshot, activeModelPreset), [activeModelPreset, settingsSnapshot], ); const modelBadgeLabel = modelBadge.needsSetup ? tx("thread.composer.chooseAI", "Choose your AI") : modelBadge.label; useEffect(() => { if (liveSelectedJob) setInspectedJob(liveSelectedJob); else setDetailOpen(false); }, [liveSelectedJob]); useEffect(() => { if (!returnToDetailJob) return; const currentJob = jobs.find((job) => job.id === returnToDetailJob.id) ?? returnToDetailJob; setInspectedJob(currentJob); setDetailOpen(true); onReturnToDetailHandled?.(); }, [jobs, onReturnToDetailHandled, returnToDetailJob]); const inspectJob = (job: SessionAutomationJob, trigger: HTMLElement) => { selectedTrigger.current = trigger; setInspectedJob(job); setDetailOpen(true); }; const handOff = (callback: (job: SessionAutomationJob) => void) => { // Restore the row before opening the next dialog, so it has a mounted // element to return focus to when editing or confirmation finishes. afterDetailClose.current = callback; setDetailOpen(false); }; const startAutomationChat = ( content: string, images?: SendAttachment[], options?: SendOptions, ) => onStartChat?.( tx( "settings.automations.createRequest", "Create an automation for this request:\n\n{{request}}", { request: content.trim() }, ), images, options, activeModelPreset, ); const filterLabel = filter === "all" ? tx("settings.automations.filter", "Filter") : tx("settings.automations.filteredBy", "Filter: {{status}}", { status: summaryOptions.find((option) => option.value === filter)?.label, }); const filters = visibleJobs.length ? ( { const option = summaryOptions.find((item) => item.value === value); if (option) onFilterChange(option.value); }}> {summaryOptions.map((option) => ( {option.label} {option.count} ))} ) : null; return (

{tx("settings.nav.automations", "Automations")}

{onStartChat ? (
) : null} {error ? : null}
{view === "calendar" ? (

{new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" }).format(month)}

) : null} {filters ?
{filters}
: null} {view === "calendar" ? (
) : null}
{loading && !payload ? (
{tx("settings.automations.loading", "Loading automations...")}
) : view === "tasks" ? (
{filtered.length ? (
    {filtered.map((job) => { const status = automationStatusKey(job); const emphasizedStatus = status === "running" || status === "failed" || status === "paused"; return (
  • ); })}
) : (

{visibleJobs.length ? tx("settings.automations.noMatches", "No automations match this view.") : tx("settings.automations.empty", "No automations yet.")}

)}
) : ( tx("settings.automations.calendar.more", "+{{count}} more", { count }), close: tx("common.close", "Close"), system: tx("settings.automations.filters.system", "System"), noEntries: filtered.length ? tx("settings.automations.calendar.noEntries", "No runs in this month.") : visibleJobs.length ? tx("settings.automations.noMatches", "No automations match this view.") : tx("settings.automations.empty", "No automations yet."), completed: tx("settings.automations.status.completed", "Completed"), skipped: tx("settings.automations.skipped", "Skipped"), }} onInspect={inspectJob} /> )}
handOff(onRequestEdit)} onRequestDelete={() => handOff(onRequestDelete)} onCloseAutoFocus={(event) => { event.preventDefault(); if (detailOpen) return; setInspectedJob(null); const target = selectedTrigger.current?.isConnected ? selectedTrigger.current : pageTitle.current; target?.focus({ preventScroll: true }); const next = afterDetailClose.current; afterDetailClose.current = null; if (liveSelectedJob) next?.(liveSelectedJob); }} />
); } export function AutomationDetailDialog({ job, open, locale, actionKey, error, onOpenChange, onAction, onRequestEdit, onRequestDelete, onCloseAutoFocus, }: { job: SessionAutomationJob | null; open: boolean; locale: string; actionKey: string | null; error: string | null; onOpenChange: (open: boolean) => void; onAction: (action: AutomationAction, job: SessionAutomationJob) => void | Promise; onRequestEdit: (job: SessionAutomationJob) => void; onRequestDelete: (job: SessionAutomationJob) => void; onCloseAutoFocus?: (event: Event) => void; }) { return ( {job ? ( ) : null} ); } function AutomationDetailPanel({ job, locale, actionKey, error, onAction, onRequestEdit, onRequestDelete, }: { job: SessionAutomationJob; locale: string; actionKey: string | null; error: string | null; onAction: (action: AutomationAction, job: SessionAutomationJob) => void | Promise; onRequestEdit: (job: SessionAutomationJob) => void; onRequestDelete: (job: SessionAutomationJob) => void; }) { const { t } = useTranslation(); const tx = (key: string, fallback: string, values?: Record) => t(key, { defaultValue: fallback, ...(values ?? {}) }); const originHref = job.origin?.channel === "websocket" && job.origin.session_key ? `#/chat/${encodeURIComponent(job.origin.session_key)}` : null; const localTrigger = isLocalTriggerAutomation(job); const command = automationTriggerCommand(job); const message = localTrigger ? command : job.payload.message || ""; const timezone = job.schedule.kind === "cron" ? job.schedule.tz?.trim() || null : null; const [messageExpanded, setMessageExpanded] = useState(false); const messageId = useId(); const [commandCopied, setCommandCopied] = useState(false); const messageNeedsExpansion = automationMessageNeedsExpansion(message); const busy = Boolean(actionKey); const canManage = !job.protected; const canToggle = canManage && (job.enabled || Boolean(job.origin)); const canRun = canManage && Boolean(job.origin) && job.enabled && !job.state.pending && !localTrigger; const lastStatus = job.state.last_status === "ok" ? tx("settings.automations.status.completed", "Completed") : job.state.last_status === "error" ? tx("settings.automations.status.failed", "Failed") : job.state.last_status === "skipped" ? tx("settings.automations.skipped", "Skipped") : job.state.last_status; return ( <>
{tx("settings.automations.taskInfo", "Task information")}
{formatAutomationSchedule(job, locale, tx)} {!localTrigger ? ( {formatAutomationNext(job, tx)} ) : null} {job.state.last_run_at_ms ? {lastStatus ? {lastStatus} : null} {relativeTime(job.state.last_run_at_ms)} : lastStatus || tx("settings.automations.neverRun", "Not run yet")} {timezone ? ( {timezone} ) : null} {job.delete_after_run ? {tx("settings.automations.oneShotHint", "Removed after running")} : null} {job.created_at_ms ? {fmtDateTime(job.created_at_ms, locale)} : null} {job.updated_at_ms ? {fmtDateTime(job.updated_at_ms, locale)} : null} {job.id}
{job.name || job.id}
{canManage && message.trim() ?
{localTrigger && command ? (
{tx("settings.automations.fields.command", "Command")}
) : null}
{message}
{messageNeedsExpansion ? ( ) : null}
: null} {job.state.last_error ? : null} {error ? : null}
{!job.protected && job.origin?.channel && job.origin.channel !== "websocket" ? ( {automationChannelLabel(job.origin.channel, t)} ) : null}
{canManage ? (
{!localTrigger ? ( ) : null}
{originHref ? : null}
) : null} ); } function AutomationError({ message }: { message: string }) { const { t } = useTranslation(); const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback }); return
{localizedAutomationError(message, tx)}
; } const LEGACY_AUTOMATION_DESTINATION_ERROR = "legacy cron payload is missing channel/to"; function localizedAutomationError( message: string, tx: (key: string, fallback: string) => string, ): string { if (message.toLowerCase().includes(LEGACY_AUTOMATION_DESTINATION_ERROR)) { return tx( "settings.automations.errors.legacyMissingDestination", "This older automation is missing its delivery destination. Recreate it from the linked chat to continue.", ); } return message; } function automationMessageNeedsExpansion(message: string): boolean { return message.length > 360 || message.split(/\r?\n/).length > 6; } function AutomationDetail({ label, title, children }: { label: ReactNode; title?: string; children: ReactNode }) { return (
{label}
{children}
); } type AutomationEveryUnit = "second" | "minute" | "hour" | "day"; // These dialogs are opened programmatically, without a mounted DialogTrigger. function useAutomationDialogFocus() { const previousFocus = useRef(null); return { onOpenAutoFocus: (event: Event) => { previousFocus.current = document.activeElement instanceof HTMLElement ? document.activeElement : null; event.preventDefault(); if (event.target instanceof HTMLElement) event.target.focus({ preventScroll: true }); }, onCloseAutoFocus: (event: Event) => { event.preventDefault(); previousFocus.current?.focus({ preventScroll: true }); }, }; } type AutomationEditDraft = { name: string; message: string; scheduleKind: "at" | "every" | "cron"; everyValue: string; everyUnit: AutomationEveryUnit; cronExpr: string; tz: string; atLocal: string; }; type AutomationScheduleUpdate = NonNullable; const AUTOMATION_EVERY_UNITS: Array<{ value: AutomationEveryUnit; ms: number }> = [ { value: "second", ms: 1000 }, { value: "minute", ms: 60_000 }, { value: "hour", ms: 3_600_000 }, { value: "day", ms: 86_400_000 }, ]; export function AutomationEditDialog({ job, saving, onOpenChange, onCancel, onSave, }: { job: SessionAutomationJob | null; saving: boolean; onOpenChange: (open: boolean) => void; onCancel?: (job: SessionAutomationJob) => void; onSave: (job: SessionAutomationJob, values: AutomationUpdatePayload) => void | Promise; }) { const dialogFocus = useAutomationDialogFocus(); const { t } = useTranslation(); const tx = (key: string, fallback: string, values?: Record) => t(key, { defaultValue: fallback, ...(values ?? {}) }); const [draft, setDraft] = useState(() => automationDraftFromJob(null)); const validationId = useId(); const localTrigger = isLocalTriggerAutomation(job); useEffect(() => { setDraft(automationDraftFromJob(job)); }, [job]); const validation = automationEditDraftError(draft, job, tx); const scheduleOptions = [ { value: "every", label: tx("settings.automations.scheduleTypes.every", "Interval") }, { value: "cron", label: tx("settings.automations.scheduleTypes.cron", "Cron") }, { value: "at", label: tx("settings.automations.scheduleTypes.at", "Once") }, ]; const unitLabels: Record = { second: tx("settings.automations.everyUnits.second", "Seconds"), minute: tx("settings.automations.everyUnits.minute", "Minutes"), hour: tx("settings.automations.everyUnits.hour", "Hours"), day: tx("settings.automations.everyUnits.day", "Days"), }; const submit = (event: FormEvent) => { event.preventDefault(); const payload = automationUpdatePayloadFromDraft(draft, job); if (!job || typeof payload === "string") return; void onSave(job, payload); }; const changeOpen = (open: boolean) => { onOpenChange(open); if (!open && job) onCancel?.(job); }; return ( {job ? ( { // Escape in the nested date calendar must not cancel the editor. if (event.target instanceof Element && event.target.closest("[data-automation-date-calendar]")) { event.preventDefault(); } }} >
{tx("settings.automations.editTitle", "Edit automation")}
{!localTrigger ? (