2026-09-11 19:10:15 +08:00
import { useEffect , useId , useMemo , useRef , useState } from "react" ;
2026-08-10 19:33:52 +08:00
import type { FormEvent , ReactNode } from "react" ;
2026-09-11 15:22:14 +08:00
import type { TFunction } from "i18next" ;
2026-08-10 19:33:52 +08:00
import {
Check ,
ChevronDown ,
CircleAlert ,
Clipboard ,
Loader2 ,
} from "lucide-react" ;
import { useTranslation } from "react-i18next" ;
2026-09-11 15:22:14 +08:00
import { channelTranslator } from "@/channel-plugins/i18n" ;
import { channelUiOwner , channelUiPresentation } from "@/channel-plugins/registry" ;
2026-09-12 16:32:46 +08:00
import { AutomationCalendar } from "@/components/settings/system/AutomationCalendar" ;
2026-09-12 23:31:35 +08:00
import { SettingsGroup } from "@/components/settings/shared/SettingsControls" ;
2026-09-12 16:32:46 +08:00
import {
modelPresetOptionsFromSettings ,
toModelBadgeInfo ,
} from "@/components/thread/model-preset" ;
import { ThreadComposer } from "@/components/thread/ThreadComposer" ;
2026-08-10 19:33:52 +08:00
import { Button } from "@/components/ui/button" ;
2026-09-11 19:10:15 +08:00
import { Disclosure , DisclosureContent } from "@/components/ui/disclosure" ;
import { ExpandableText } from "@/components/ui/expandable-text" ;
2026-08-10 19:33:52 +08:00
import {
Dialog ,
DialogContent ,
DialogDescription ,
DialogFooter ,
DialogHeader ,
DialogTitle ,
} from "@/components/ui/dialog" ;
2026-08-11 00:00:22 +08:00
import { formControlFocusClassName } from "@/components/ui/form-control" ;
2026-08-10 19:33:52 +08:00
import { Input } from "@/components/ui/input" ;
import { SegmentedControl } from "@/components/ui/segmented-control" ;
import { Textarea } from "@/components/ui/textarea" ;
2026-09-11 19:10:15 +08:00
import { displayTitle } from "@/lib/chat-groups" ;
2026-08-10 19:33:52 +08:00
import { copyTextToClipboard } from "@/lib/clipboard" ;
import { fmtDateTime , relativeTime } from "@/lib/format" ;
2026-09-12 16:32:46 +08:00
import type { SendAttachment , SendOptions } from "@/hooks/useNanobotStream" ;
import type {
AutomationsPayload ,
AutomationUpdatePayload ,
SessionAutomationJob ,
SettingsPayload ,
} from "@/lib/types" ;
2026-08-10 19:33:52 +08:00
import { cn } from "@/lib/utils" ;
export type AutomationFilter = "all" | "active" | "paused" | "failed" | "system" ;
export type AutomationAction = "enable" | "disable" | "delete" | "run" ;
2026-09-11 19:10:15 +08:00
const EMPTY_TITLE_OVERRIDES : Record < string , string > = {};
const SYSTEM_TASKS_OPEN_STORAGE_KEY = "nanobot-webui.automation-system-tasks-open" ;
2026-08-10 19:33:52 +08:00
export function AutomationsSettings ({
2026-09-12 23:31:35 +08:00
payload , loading , filter , actionKey , error ,
2026-09-11 19:10:15 +08:00
titleOverrides = EMPTY_TITLE_OVERRIDES ,
2026-09-12 16:32:46 +08:00
settingsSnapshot = null ,
2026-09-12 23:31:35 +08:00
onFilterChange , onAction ,
2026-09-12 16:32:46 +08:00
onRequestEdit , onRequestDelete , onStartChat , onManageModels ,
returnToDetailJob = null , onReturnToDetailHandled ,
2026-08-10 19:33:52 +08:00
} : {
payload : AutomationsPayload | null ;
2026-09-11 19:10:15 +08:00
titleOverrides? : Record < string , string >;
2026-09-12 16:32:46 +08:00
settingsSnapshot? : SettingsPayload | null ;
2026-08-10 19:33:52 +08:00
loading : boolean ;
filter : AutomationFilter ;
actionKey : string | null ;
error : string | null ;
onFilterChange : ( value : AutomationFilter ) => void ;
onAction : ( action : AutomationAction , job : SessionAutomationJob ) => void | Promise < void >;
onRequestEdit : ( job : SessionAutomationJob ) => void ;
onRequestDelete : ( job : SessionAutomationJob ) => void ;
2026-09-12 16:32:46 +08:00
onStartChat ?: (
content : string ,
images? : SendAttachment [],
options? : SendOptions ,
modelPreset? : string | null ,
) => boolean | void | Promise < boolean | void >;
onManageModels ?: () => void ;
returnToDetailJob? : SessionAutomationJob | null ;
onReturnToDetailHandled ?: () => void ;
2026-08-10 19:33:52 +08:00
}) {
const { t , i18n } = useTranslation ();
const tx = ( key : string , fallback : string , values? : Record < string , unknown >) =>
t ( key , { defaultValue : fallback , ...( values ?? {}) });
2026-09-11 19:10:15 +08:00
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 ]);
2026-08-10 19:33:52 +08:00
const locale = i18n . resolvedLanguage || i18n . language ;
2026-09-11 19:10:15 +08:00
const [ inspectedJob , setInspectedJob ] = useState < SessionAutomationJob | null >( null );
const [ detailOpen , setDetailOpen ] = useState ( false );
2026-09-12 16:32:46 +08:00
const [ localModelPreset , setLocalModelPreset ] = useState < string | null >( null );
2026-09-11 19:10:15 +08:00
const [ systemOpen , setSystemOpen ] = useState (() => {
try {
return window . localStorage . getItem ( SYSTEM_TASKS_OPEN_STORAGE_KEY ) !== "false" ;
} catch {
return true ;
}
});
const pageTitle = useRef < HTMLHeadingElement | null >( null );
2026-09-12 16:32:46 +08:00
const selectedTrigger = useRef < HTMLElement | null >( null );
2026-09-11 19:10:15 +08:00
const afterDetailClose = useRef < (( job : SessionAutomationJob ) => void ) | null > ( null );
2026-08-10 19:33:52 +08:00
const filtered = useMemo (() => {
2026-09-12 23:31:35 +08:00
return jobs
. filter (( job ) => automationMatchesFilter ( job , filter ));
}, [ filter , jobs ]);
2026-09-11 19:10:15 +08:00
const personalJobs = jobs . filter (( job ) => ! job . protected );
const personal = filtered . filter (( job ) => ! job . protected );
const system = filtered . filter (( job ) => job . protected );
// 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 ;
2026-08-10 19:33:52 +08:00
const summaryOptions : Array < { value : AutomationFilter ; label : string ; count : number } > = [
2026-09-11 19:10:15 +08:00
{ value : "all" , label : tx ( "settings.automations.filters.all" , "All" ), count : personalJobs.length },
{ value : "active" , label : tx ( "settings.automations.filters.active" , "Active" ),
count : personalJobs.filter (( job ) => automationMatchesFilter ( job , "active" )). length },
{ value : "paused" , label : tx ( "settings.automations.filters.paused" , "Paused" ),
count : personalJobs.filter (( job ) => automationMatchesFilter ( job , "paused" )). length },
{ value : "failed" , label : tx ( "settings.automations.filters.failed" , "Needs attention" ),
count : personalJobs.filter ( automationNeedsAttention ). length },
2026-08-10 19:33:52 +08:00
];
2026-09-12 16:32:46 +08:00
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 ;
2026-08-10 19:33:52 +08:00
useEffect (() => {
2026-09-11 19:10:15 +08:00
if ( liveSelectedJob ) setInspectedJob ( liveSelectedJob );
else setDetailOpen ( false );
}, [ liveSelectedJob ]);
2026-09-12 16:32:46 +08:00
useEffect (() => {
if ( ! returnToDetailJob ) return ;
const currentJob = jobs . find (( job ) => job . id === returnToDetailJob . id ) ?? returnToDetailJob ;
setInspectedJob ( currentJob );
setDetailOpen ( true );
onReturnToDetailHandled ? .();
}, [ jobs , onReturnToDetailHandled , returnToDetailJob ]);
2026-09-11 19:10:15 +08:00
const renderJob = ( job : SessionAutomationJob ) => (
< AutomationListItem
key = { job . id }
job = { job }
locale = { locale }
disabled = { Boolean ( job . protected ) && ! systemOpen }
onSelect = {( button ) => {
selectedTrigger . current = button ;
setInspectedJob ( job );
setDetailOpen ( true );
}}
/>
);
2026-09-12 16:32:46 +08:00
const inspectJob = ( job : SessionAutomationJob , trigger : HTMLElement ) => {
selectedTrigger . current = trigger ;
setInspectedJob ( job );
setDetailOpen ( true );
};
2026-09-11 19:10:15 +08:00
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 );
};
2026-09-12 16:32:46 +08:00
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 ,
);
2026-08-10 19:33:52 +08:00
return (
2026-09-11 19:10:15 +08:00
< div className = "automations-page" >
2026-09-11 22:02:46 +08:00
< header className = "mb-7" >
< h1 ref = { pageTitle } tabIndex = { - 1 } className = "text-[24px] font-normal leading-tight tracking-normal text-foreground outline-none sm:text-[28px]" >
2026-09-11 19:10:15 +08:00
{ tx ( "settings.nav.automations" , "Automations" )}
</ h1 >
</ header >
2026-09-11 22:02:46 +08:00
< div className = "settings-stack" >
2026-09-12 16:32:46 +08:00
{ onStartChat ? (
< div
className = "automation-create-composer"
aria-label = { tx ( "settings.automations.create" , "Create automation" )}
>
< ThreadComposer
onSend = { startAutomationChat }
inputAriaLabel = { tx ( "settings.automations.createInput" , "Describe an automation" )}
placeholder = { tx (
"settings.automations.createPrompt" ,
2026-09-12 23:31:35 +08:00
"What would you like nanobot to schedule?" ,
2026-09-12 16:32:46 +08:00
)}
variant = "thread"
2026-09-12 23:31:35 +08:00
compactWhenIdle
2026-09-12 16:32:46 +08:00
modelLabel = { modelBadgeLabel }
modelDetail = { modelBadge . model }
modelPreset = { activeModelPreset }
modelPresets = { modelPresetOptions }
onModelPresetChange = { setLocalModelPreset }
modelProvider = { modelBadge . provider }
modelProviderLabel = { modelBadge . providerLabel }
modelNeedsSetup = { modelBadge . needsSetup }
onModelBadgeClick = { modelBadge . needsSetup ? onManageModels : undefined }
onManageModels = { onManageModels }
/>
</ div >
) : null }
{ error ? < AutomationError message = { error } /> : null }
{ loading && ! payload ? (
< div role = "status" className = "flex h-44 items-center justify-center rounded-panel border border-border/70 bg-[hsl(var(--settings-surface))] text-[13px] text-muted-foreground" >
< Loader2 className = "mr-2 h-4 w-4 animate-spin" aria - hidden />
{ tx ( "settings.automations.loading" , "Loading automations..." )}
</ div >
) : (
< AutomationCalendar
jobs = { personal }
locale = { locale }
2026-09-12 23:31:35 +08:00
filters = { jobs . length ? (
< div role = "group" aria-label = { tx ( "settings.nav.automations" , "Automations" )}>
< SegmentedControl
value = { filter }
className = "flex-wrap justify-start"
itemClassName = "px-2.5"
options = { summaryOptions . map (( option ) => ({
value : option.value ,
label : <>{ option . label } < span className = "ml-0.5 tabular-nums opacity-65" >{ option . count }</ span ></>,
}))}
onChange = { onFilterChange }
/>
</ div >
) : null }
2026-09-12 16:32:46 +08:00
copy = {{
previousMonth : tx ( "settings.automations.calendar.previousMonth" , "Previous month" ),
nextMonth : tx ( "settings.automations.calendar.nextMonth" , "Next month" ),
today : tx ( "settings.automations.calendar.today" , "Today" ),
planned : tx ( "settings.automations.calendar.planned" , "Planned" ),
recorded : tx ( "settings.automations.calendar.recorded" , "Recorded" ),
running : tx ( "settings.automations.status.running" , "Running" ),
failed : tx ( "settings.automations.status.failed" , "Failed" ),
more : ( count ) => tx ( "settings.automations.calendar.more" , "+{{count}} more" , { count }),
2026-09-12 23:31:35 +08:00
close : tx ( "common.close" , "Close" ),
2026-09-12 16:32:46 +08:00
noEntries : personal.length
? tx ( "settings.automations.calendar.noEntries" , "No runs in this month." )
: personalJobs . length
? tx ( "settings.automations.noMatches" , "No automations match this view." )
: tx ( "settings.automations.empty" , "No automations yet." ),
completed : tx ( "settings.automations.status.completed" , "Completed" ),
}}
onInspect = { inspectJob }
/>
)}
2026-09-11 22:02:46 +08:00
2026-09-12 16:32:46 +08:00
{ system . length ? (
< SettingsGroup >
< section className = "py-2" >
< button
type = "button"
aria-expanded = { systemOpen }
aria-controls = "automation-system-tasks"
onClick = {() => {
const open = ! systemOpen ;
setSystemOpen ( open );
try {
window . localStorage . setItem ( SYSTEM_TASKS_OPEN_STORAGE_KEY , String ( open ));
} catch {
// Unavailable storage must not prevent expanding or collapsing.
}
}}
className = { cn ( "automation-meta-row min-h-10 w-full items-center rounded-control py-1.5 text-left text-[13px] font-medium text-muted-foreground settings-hover" , formControlFocusClassName )}
>
< span className = "h-4 w-4" aria - hidden />
< span className = "flex min-w-0 items-center gap-2" >
< span className = "truncate" >{ tx ( "settings.automations.systemTasks" , "System tasks" )}</ span >
< span className = "text-[12px] font-normal tabular-nums text-muted-foreground/60" >{ system . length }</ span >
{ system . some ( automationNeedsAttention ) ? (
< span className = "ml-auto inline-flex items-center gap-1.5 text-[12px] font-normal text-amber-700 dark:text-amber-400" >
< CircleAlert className = "h-3.5 w-3.5" aria - hidden />
{ tx ( "settings.automations.filters.failed" , "Needs attention" )}
</ span >
) : null }
</ span >
< ChevronDown className = { cn ( "h-4 w-4 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none" , systemOpen && "rotate-180" )} aria - hidden />
</ button >
< DisclosureContent id = "automation-system-tasks" open = { systemOpen }>
< ul aria-label = { tx ( "settings.automations.systemTasks" , "System tasks" )} className = "space-y-1 px-4 pt-1 sm:px-6" >
{ system . map ( renderJob )}
2026-09-11 22:02:46 +08:00
</ ul >
2026-09-12 16:32:46 +08:00
</ DisclosureContent >
</ section >
</ SettingsGroup >
) : null }
2026-09-11 22:02:46 +08:00
</ div >
2026-09-11 19:10:15 +08:00
2026-09-12 16:32:46 +08:00
< AutomationDetailDialog
job = { selectedJob }
open = { detailOpen }
locale = { locale }
actionKey = { actionKey }
error = { error }
onOpenChange = { setDetailOpen }
onAction = { onAction }
onRequestEdit = {() => handOff ( onRequestEdit )}
onRequestDelete = {() => handOff ( onRequestDelete )}
onCloseAutoFocus = {( event ) => {
event . preventDefault ();
if ( detailOpen ) return ;
setInspectedJob ( null );
const target = selectedTrigger . current ? . isConnected
2026-09-12 23:31:35 +08:00
? selectedTrigger.current : pageTitle.current ;
2026-09-12 16:32:46 +08:00
target ? . focus ({ preventScroll : true });
const next = afterDetailClose . current ;
afterDetailClose . current = null ;
if ( liveSelectedJob ) next ? .( liveSelectedJob );
}}
/>
2026-08-10 19:33:52 +08:00
</ div >
);
}
2026-09-12 16:32:46 +08:00
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 < void >;
onRequestEdit : ( job : SessionAutomationJob ) => void ;
onRequestDelete : ( job : SessionAutomationJob ) => void ;
onCloseAutoFocus ?: ( event : Event ) => void ;
}) {
return (
< Dialog open = { open } onOpenChange = { onOpenChange }>
{ job ? (
< DialogContent
{ ... ( job.protected ? { "aria-describedby" : undefined } : {} ) }
{ ... (! open ? { inert : "" , "aria-hidden" : true } : {} ) }
className = { cn (
"flex max-h-[calc(100dvh-2rem)] max-w-[520px] flex-col gap-0 overflow-hidden p-0" ,
job . protected && "max-w-[440px]" ,
)}
onCloseAutoFocus = { onCloseAutoFocus }
>
< AutomationDetailPanel
key = { job . id }
job = { job }
locale = { locale }
actionKey = { actionKey }
error = { error }
onAction = { onAction }
onRequestEdit = { onRequestEdit }
onRequestDelete = { onRequestDelete }
/>
</ DialogContent >
) : null }
</ Dialog >
);
}
2026-09-11 19:10:15 +08:00
function AutomationListItem ({ job , locale , disabled , onSelect } : {
2026-08-10 19:33:52 +08:00
job : SessionAutomationJob ;
locale : string ;
2026-09-11 19:10:15 +08:00
disabled : boolean ;
onSelect : ( button : HTMLButtonElement ) => void ;
2026-08-10 19:33:52 +08:00
}) {
const { t } = useTranslation ();
const tx = ( key : string , fallback : string , values? : Record < string , unknown >) =>
t ( key , { defaultValue : fallback , ...( values ?? {}) });
2026-09-11 19:10:15 +08:00
const attention = automationNeedsAttention ( job );
const compact = Boolean ( job . protected );
2026-09-12 16:32:46 +08:00
const summary = job . state . last_error
? localizedAutomationError ( job . state . last_error , tx )
: compact ? null : automationSummary ( job , tx );
2026-09-11 19:10:15 +08:00
const running = Boolean ( job . state . pending );
2026-08-10 19:33:52 +08:00
return (
2026-09-11 19:10:15 +08:00
< li >
2026-08-10 19:33:52 +08:00
< button
type = "button"
2026-09-11 19:10:15 +08:00
disabled = { disabled }
aria-haspopup = "dialog"
onClick = {( event ) => onSelect ( event . currentTarget )}
2026-08-10 19:33:52 +08:00
className = { cn (
2026-09-11 22:02:46 +08:00
"automation-task-row grid w-full grid-cols-1 items-center gap-x-4 gap-y-2 rounded-control px-2 py-3 text-left transition-colors duration-150 settings-hover" ,
2026-09-11 19:10:15 +08:00
formControlFocusClassName ,
2026-08-10 19:33:52 +08:00
)}
>
< span className = "min-w-0" >
2026-09-11 22:02:46 +08:00
< span className = "block truncate text-[14px] font-semibold leading-5 text-foreground" >{ job . name || job . id }</ span >
{ summary ? < span className = "mt-0.5 block truncate text-[12px] leading-5 text-muted-foreground" >{ summary }</ span > : null }
2026-08-10 19:33:52 +08:00
</ span >
2026-09-11 22:02:46 +08:00
< span className = "automation-task-state flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-[11px] text-muted-foreground" >
2026-09-11 19:10:15 +08:00
{ running ? < Loader2 className = "h-3.5 w-3.5 animate-spin" aria - hidden /> : null }
{ attention && ! running ? (
<>
< CircleAlert className = "h-4 w-4 shrink-0 text-amber-700 dark:text-amber-400" aria - hidden />
< span className = "text-amber-700 dark:text-amber-400" >{ tx ( "settings.automations.filters.failed" , "Needs attention" )}</ span >
2026-09-12 16:32:46 +08:00
{ ! job . enabled ? < span >{ tx ( "settings.automations.next.paused" , "Paused" )}</ span > : null }
2026-09-11 19:10:15 +08:00
</>
) : (
< span title = { formatAutomationNextTitle ( job , locale , tx )}>{ formatAutomationNext ( job , tx )}</ span >
)}
2026-08-10 19:33:52 +08:00
</ span >
</ button >
2026-09-11 19:10:15 +08:00
</ li >
2026-08-10 19:33:52 +08:00
);
}
function AutomationDetailPanel ({
2026-09-12 23:31:35 +08:00
job , locale , actionKey , error , onAction , onRequestEdit , onRequestDelete ,
2026-08-10 19:33:52 +08:00
} : {
job : SessionAutomationJob ;
locale : string ;
actionKey : string | null ;
2026-09-11 19:10:15 +08:00
error : string | null ;
2026-08-10 19:33:52 +08:00
onAction : ( action : AutomationAction , job : SessionAutomationJob ) => void | Promise < void >;
onRequestEdit : ( job : SessionAutomationJob ) => void ;
onRequestDelete : ( job : SessionAutomationJob ) => void ;
}) {
const { t } = useTranslation ();
const tx = ( key : string , fallback : string , values? : Record < string , unknown >) =>
t ( key , { defaultValue : fallback , ...( values ?? {}) });
2026-09-11 15:22:14 +08:00
const origin = automationOriginLabel ( job , t );
2026-08-10 19:33:52 +08:00
const originHref = job . origin ? . channel === "websocket" && job . origin . session_key
2026-09-11 19:10:15 +08:00
? `#/chat/ ${ encodeURIComponent ( job . origin . session_key ) } ` : null ;
2026-08-10 19:33:52 +08:00
const localTrigger = isLocalTriggerAutomation ( job );
2026-09-11 19:10:15 +08:00
const command = automationTriggerCommand ( job );
2026-09-11 22:55:55 +08:00
const message = localTrigger ? command : job.payload.message || "" ;
2026-09-12 16:32:46 +08:00
const timezone = job . schedule . kind === "cron" ? job . schedule . tz ? . trim () || null : null ;
2026-08-10 19:33:52 +08:00
const [ messageExpanded , setMessageExpanded ] = useState ( false );
2026-09-11 19:10:15 +08:00
const messageId = useId ();
2026-08-10 19:33:52 +08:00
const [ commandCopied , setCommandCopied ] = useState ( false );
const messageNeedsExpansion = automationMessageNeedsExpansion ( message );
2026-09-11 19:10:15 +08:00
const busy = Boolean ( actionKey );
2026-08-10 19:33:52 +08:00
const canManage = ! job . protected ;
2026-09-11 19:10:15 +08:00
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 ;
2026-08-10 19:33:52 +08:00
return (
2026-09-11 19:10:15 +08:00
<>
2026-09-12 23:31:35 +08:00
< DialogHeader className = "shrink-0 px-6 pb-3 pr-14 pt-5 text-left" >
< DialogTitle className = "min-w-0 break-words leading-6 text-balance" >{ job . name || job . id }</ DialogTitle >
2026-09-11 19:10:15 +08:00
{ canManage ? (
2026-09-12 23:31:35 +08:00
< DialogDescription className = "flex flex-wrap items-center gap-x-4 gap-y-1 text-[13px] leading-5" >
< span className = "font-medium text-foreground/80" >{ formatAutomationSchedule ( job , locale , tx )}</ span >
< span className = "inline-flex min-w-0 items-center gap-1.5" >
< span >{ tx ( "settings.automations.labels.next" , "Next" )}</ span >
< span className = "text-foreground/80" title = { formatAutomationNextTitle ( job , locale , tx )}>
{ formatAutomationNext ( job , tx )}
</ span >
2026-09-12 16:32:46 +08:00
</ span >
2026-09-11 19:10:15 +08:00
</ DialogDescription >
) : null }
2026-09-11 22:55:55 +08:00
</ DialogHeader >
< div className = "min-h-0 overflow-y-auto overscroll-contain px-6 pb-3" >
{ canManage && message . trim () ? < section className = "pb-4" >
2026-09-11 19:10:15 +08:00
< div className = "flex items-center justify-between gap-3 text-[12px] text-muted-foreground" >
< span >{ localTrigger ? tx ( "settings.automations.fields.command" , "Command" ) : tx ( "settings.automations.instructions" , "Instructions" )}</ span >
{ localTrigger && command ? (
2026-09-11 22:55:55 +08:00
< Button variant = "ghost" size = "sm" onClick = {() => {
2026-09-11 19:10:15 +08:00
void copyTextToClipboard ( command ). then (( ok ) => { if ( ok ) setCommandCopied ( true ); });
}}>
{ commandCopied ? < Check className = "mr-1.5 h-3.5 w-3.5" aria - hidden /> : < Clipboard className = "mr-1.5 h-3.5 w-3.5" aria - hidden />}
{ commandCopied ? tx ( "settings.automations.commandCopied" , "Copied" ) : tx ( "settings.automations.copyCommand" , "Copy" )}
</ Button >
) : null }
</ div >
< div className = "mt-2" >
2026-09-11 22:55:55 +08:00
< ExpandableText id = { messageId } expanded = { messageExpanded || ! messageNeedsExpansion } lines = { 6 } className = { cn ( "whitespace-pre-wrap break-words text-[13px] leading-5 text-foreground [overflow-wrap:anywhere]" , localTrigger && "font-mono text-[12px]" )}>
2026-09-11 19:10:15 +08:00
{ message }
</ ExpandableText >
</ div >
{ messageNeedsExpansion ? (
< button type = "button" aria-expanded = { messageExpanded } aria-controls = { messageId } onClick = {() => setMessageExpanded (( value ) => ! value )} className = "mt-2 rounded-sm text-[12px] text-muted-foreground underline-offset-4 hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" >
{ messageExpanded ? tx ( "settings.automations.message.showLess" , "Show less" ) : tx ( "settings.automations.message.showMore" , "Show full message" )}
</ button >
) : null }
</ section > : null }
{ job . state . last_error ? < AutomationError message = { job . state . last_error } /> : null }
{ error ? < AutomationError message = { error } /> : null }
2026-09-11 22:55:55 +08:00
< dl >
2026-09-11 19:10:15 +08:00
{ job . protected ? (
<>
< AutomationDetail label = { tx ( "settings.automations.labels.schedule" , "Schedule" )}>
{ formatAutomationSchedule ( job , locale , tx )}
</ AutomationDetail >
2026-09-12 16:32:46 +08:00
{ timezone ? (
< AutomationDetail label = { tx ( "settings.automations.fields.timezone" , "Timezone" )}>
{ timezone }
</ AutomationDetail >
) : null }
2026-09-11 19:10:15 +08:00
< AutomationDetail label = { tx ( "settings.automations.sort.next" , "Next run" )} title = { formatAutomationNextTitle ( job , locale , tx )}>
{ formatAutomationNext ( job , tx )}
</ AutomationDetail >
</>
) : null }
< AutomationDetail label = { tx ( "settings.automations.sort.last" , "Last run" )} title = { job . state . last_run_at_ms ? fmtDateTime ( job . state . last_run_at_ms , locale ) : undefined }>
{ job . state . last_run_at_ms
2026-09-12 16:32:46 +08:00
? < span className = "flex flex-wrap justify-end gap-x-3 gap-y-1" >
{ lastStatus ? < span >{ lastStatus }</ span > : null }
< span >{ relativeTime ( job . state . last_run_at_ms )}</ span >
</ span >
2026-09-11 19:10:15 +08:00
: lastStatus || tx ( "settings.automations.neverRun" , "Not run yet" )}
</ AutomationDetail >
{ ! job . protected ? (
< AutomationDetail label = { tx ( "settings.automations.labels.origin" , "Linked chat" )}>
2026-09-12 23:31:35 +08:00
< span className = "block truncate" title = { origin }>{ origin }</ span >
2026-09-11 19:10:15 +08:00
</ AutomationDetail >
) : null }
</ dl >
< Disclosure
2026-09-12 23:31:35 +08:00
className = "mt-2"
2026-09-11 22:55:55 +08:00
summaryClassName = { cn ( "flex min-h-10 cursor-pointer items-center justify-between gap-3 rounded-control py-2.5 text-[13px] text-muted-foreground transition-colors hover:text-foreground" , formControlFocusClassName )}
2026-09-11 19:10:15 +08:00
summary = {<>
{ tx ( "settings.automations.moreDetails" , "More details" )}
2026-09-11 21:56:42 +08:00
< ChevronDown className = "h-3.5 w-3.5 transition-transform duration-200 group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" aria - hidden />
2026-09-11 19:10:15 +08:00
</>}
2026-08-10 19:33:52 +08:00
>
2026-09-11 22:55:55 +08:00
< dl >
2026-09-12 23:31:35 +08:00
{ timezone && canManage ? (
< AutomationDetail label = { tx ( "settings.automations.fields.timezone" , "Timezone" )}>
{ timezone }
</ AutomationDetail >
) : null }
2026-09-11 19:10:15 +08:00
{ job . delete_after_run ? < AutomationDetail label = { tx ( "settings.automations.oneShot" , "One-time" )}>{ tx ( "settings.automations.oneShotHint" , "Removed after running" )}</ AutomationDetail > : null }
{ job . created_at_ms ? < AutomationDetail label = { tx ( "settings.automations.labels.created" , "Created" )}>{ fmtDateTime ( job . created_at_ms , locale )}</ AutomationDetail > : null }
{ job . updated_at_ms ? < AutomationDetail label = { tx ( "settings.automations.labels.updated" , "Updated" )}>{ fmtDateTime ( job . updated_at_ms , locale )}</ AutomationDetail > : null }
< AutomationDetail label = "ID" >< span className = "break-all font-mono text-[11px]" >{ job . id }</ span ></ AutomationDetail >
</ dl >
</ Disclosure >
</ div >
{ canManage ? (
2026-09-12 23:31:35 +08:00
< div className = "flex shrink-0 flex-col gap-2 border-t border-border/45 px-6 py-3 sm:flex-row sm:items-center" >
< div className = "flex min-w-0 flex-wrap items-center gap-1" >
< Button variant = "ghost" size = "sm" className = "text-muted-foreground" disabled = { busy || ! canToggle } onClick = {() => void onAction ( job . enabled ? "disable" : "enable" , job )}>
{ actionKey === ` ${ job . enabled ? "disable" : "enable" } : ${ job . id } ` ? < Loader2 className = "mr-1.5 h-3.5 w-3.5 animate-spin" aria - hidden /> : null }
{ job . enabled ? tx ( "settings.automations.pause" , "Pause" ) : tx ( "settings.automations.resume" , "Resume" )}
2026-09-12 16:32:46 +08:00
</ Button >
2026-09-12 23:31:35 +08:00
{ ! localTrigger ? (
< Button variant = "ghost" size = "sm" className = "text-muted-foreground" disabled = { ! canRun || busy } onClick = {() => void onAction ( "run" , job )}>
{ actionKey === `run: ${ job . id } ` ? < Loader2 className = "mr-1.5 h-3.5 w-3.5 animate-spin" aria - hidden /> : null }
{ tx ( "settings.automations.runNow" , "Run now" )}
</ Button >
) : null }
< Button
variant = "ghost"
size = "sm"
className = "text-destructive hover:bg-destructive/10 hover:text-destructive"
disabled = { busy }
onClick = {() => onRequestDelete ( job )}
>
{ tx ( "settings.automations.delete" , "Delete" )}
</ Button >
</ div >
< div className = "flex max-w-full flex-wrap justify-end gap-2 sm:ml-auto" >
2026-09-11 22:55:55 +08:00
< Button variant = "outline" size = "sm" disabled = { busy } onClick = {() => onRequestEdit ( job )}>
{ tx ( "settings.automations.edit" , "Edit" )}
</ Button >
{ originHref ? < Button asChild size = "sm" >< a href = { originHref }>{ tx ( "settings.automations.emptyAction" , "Open a chat" )}</ a ></ Button > : null }
</ div >
2026-09-11 19:10:15 +08:00
</ div >
2026-08-10 19:33:52 +08:00
) : null }
2026-09-11 19:10:15 +08:00
</>
2026-08-10 19:33:52 +08:00
);
}
2026-09-11 19:10:15 +08:00
function AutomationError ({ message } : { message : string }) {
2026-09-12 16:32:46 +08:00
const { t } = useTranslation ();
const tx = ( key : string , fallback : string ) => t ( key , { defaultValue : fallback });
2026-09-11 19:10:15 +08:00
return < div role = "alert" className = "mb-4 flex items-start gap-2 rounded-lg bg-destructive/5 px-3 py-2.5 text-[13px] leading-5 text-destructive" >
< CircleAlert className = "mt-0.5 h-4 w-4 shrink-0" aria - hidden />
2026-09-12 16:32:46 +08:00
< span className = "min-w-0 break-words [overflow-wrap:anywhere]" >
{ localizedAutomationError ( message , tx )}
</ span >
2026-09-11 19:10:15 +08:00
</ div >;
2026-08-10 19:33:52 +08:00
}
2026-09-12 16:32:46 +08:00
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 ;
}
2026-08-10 19:33:52 +08:00
function automationMessageNeedsExpansion ( message : string ) : boolean {
return message . length > 360 || message . split ( /\r?\n/ ). length > 6 ;
}
2026-09-11 19:10:15 +08:00
function AutomationDetail ({ label , title , children } : { label : string ; title? : string ; children : ReactNode }) {
2026-08-10 19:33:52 +08:00
return (
2026-09-12 23:31:35 +08:00
< div className = "grid min-w-0 grid-cols-[minmax(6.5rem,0.75fr)_minmax(0,1.75fr)] items-start gap-4 py-2.5 text-[13px] leading-5" >
2026-09-11 19:10:15 +08:00
< dt className = "text-muted-foreground" >{ label }</ dt >
2026-09-11 22:55:55 +08:00
< dd className = "min-w-0 break-words text-right text-foreground [overflow-wrap:anywhere]" title = { title }>{ children }</ dd >
2026-08-10 19:33:52 +08:00
</ div >
);
}
type AutomationEveryUnit = "second" | "minute" | "hour" | "day" ;
2026-09-11 19:10:15 +08:00
// These dialogs are opened programmatically, without a mounted DialogTrigger.
function useAutomationDialogFocus() {
const previousFocus = useRef < HTMLElement | null >( 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 });
},
};
}
2026-08-10 19:33:52 +08:00
type AutomationEditDraft = {
name : string ;
message : string ;
scheduleKind : "at" | "every" | "cron" ;
everyValue : string ;
everyUnit : AutomationEveryUnit ;
cronExpr : string ;
tz : string ;
atLocal : string ;
};
type AutomationScheduleUpdate = NonNullable < AutomationUpdatePayload [ "schedule" ] >;
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 ,
2026-09-12 16:32:46 +08:00
onCancel ,
2026-08-10 19:33:52 +08:00
onSave ,
} : {
job : SessionAutomationJob | null ;
saving : boolean ;
onOpenChange : ( open : boolean ) => void ;
2026-09-12 16:32:46 +08:00
onCancel ?: ( job : SessionAutomationJob ) => void ;
2026-08-10 19:33:52 +08:00
onSave : ( job : SessionAutomationJob , values : AutomationUpdatePayload ) => void | Promise < void >;
}) {
2026-09-11 19:10:15 +08:00
const dialogFocus = useAutomationDialogFocus ();
2026-08-10 19:33:52 +08:00
const { t } = useTranslation ();
const tx = ( key : string , fallback : string , values? : Record < string , unknown >) =>
t ( key , { defaultValue : fallback , ...( values ?? {}) });
const [ draft , setDraft ] = useState < AutomationEditDraft >(() => automationDraftFromJob ( null ));
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 < AutomationEveryUnit , string > = {
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 < HTMLFormElement >) => {
event . preventDefault ();
const payload = automationUpdatePayloadFromDraft ( draft , job );
if ( ! job || typeof payload === "string" ) return ;
void onSave ( job , payload );
};
2026-09-12 16:32:46 +08:00
const changeOpen = ( open : boolean ) => {
onOpenChange ( open );
if ( ! open && job ) onCancel ? .( job );
};
2026-08-10 19:33:52 +08:00
return (
2026-09-12 16:32:46 +08:00
< Dialog
open = { Boolean ( job )}
onOpenChange = { changeOpen }
>
2026-08-10 19:33:52 +08:00
{ job ? (
< DialogContent
2026-09-11 19:10:15 +08:00
{ ...dialogFocus }
2026-08-10 19:33:52 +08:00
aria-describedby = { undefined }
2026-08-14 07:07:09 +09:00
className = "w-[min(calc(100vw-2rem),34rem)]"
2026-08-10 19:33:52 +08:00
>
< form className = "space-y-5" onSubmit = { submit }>
< DialogHeader >
< DialogTitle >{ tx ( "settings.automations.editTitle" , "Edit automation" )}</ DialogTitle >
</ DialogHeader >
< div className = "space-y-4" >
< label className = "block space-y-1.5" >
< span className = "text-[12px] font-medium text-muted-foreground" >
{ tx ( "settings.automations.fields.name" , "Name" )}
</ span >
< Input
value = { draft . name }
onChange = {( event ) => setDraft (( prev ) => ({ ... prev , name : event.target.value }))}
/>
</ label >
{ ! localTrigger ? (
< label className = "block space-y-1.5" >
< span className = "text-[12px] font-medium text-muted-foreground" >
{ tx ( "settings.automations.fields.message" , "Message" )}
</ span >
< Textarea
value = { draft . message }
onChange = {( event ) => setDraft (( prev ) => ({ ... prev , message : event.target.value }))}
2026-08-14 07:07:09 +09:00
className = "min-h-[160px] resize-none text-[13px] leading-5"
2026-08-10 19:33:52 +08:00
/>
</ label >
) : null }
{ ! localTrigger ? (
< div className = "space-y-2" >
< span className = "text-[12px] font-medium text-muted-foreground" >
{ tx ( "settings.automations.fields.scheduleType" , "Schedule type" )}
</ span >
< SegmentedControl
value = { draft . scheduleKind }
options = { scheduleOptions }
onChange = {( value ) =>
setDraft (( prev ) => ({
... prev ,
scheduleKind : value as AutomationEditDraft [ "scheduleKind" ],
}))
}
/>
</ div >
) : null }
{ ! localTrigger && draft . scheduleKind === "every" ? (
< div className = "grid gap-2 sm:grid-cols-[minmax(0,1fr)_10rem]" >
< label className = "block space-y-1.5" >
< span className = "text-[12px] font-medium text-muted-foreground" >
{ tx ( "settings.automations.fields.every" , "Every" )}
</ span >
< Input
type = "number"
min = { 1 }
step = { 1 }
value = { draft . everyValue }
onChange = {( event ) =>
setDraft (( prev ) => ({ ... prev , everyValue : event.target.value }))
}
/>
</ label >
< label className = "block space-y-1.5" >
< span className = "text-[12px] font-medium text-muted-foreground" >
{ tx ( "settings.automations.fields.unit" , "Unit" )}
</ span >
< select
value = { draft . everyUnit }
onChange = {( event ) =>
setDraft (( prev ) => ({
... prev ,
everyUnit : event.target.value as AutomationEveryUnit ,
}))
}
2026-08-11 00:00:22 +08:00
className = { cn (
2026-08-14 07:07:09 +09:00
"h-10 w-full rounded-control border border-input bg-background px-3 text-[13px] text-foreground transition-colors" ,
2026-08-11 00:00:22 +08:00
formControlFocusClassName ,
)}
2026-08-10 19:33:52 +08:00
>
{ AUTOMATION_EVERY_UNITS . map (( unit ) => (
< option key = { unit . value } value = { unit . value }>
{ unitLabels [ unit . value ]}
</ option >
))}
</ select >
</ label >
</ div >
) : null }
{ ! localTrigger && draft . scheduleKind === "cron" ? (
< div className = "grid gap-2 sm:grid-cols-[minmax(0,1fr)_12rem]" >
< label className = "block space-y-1.5" >
< span className = "text-[12px] font-medium text-muted-foreground" >
{ tx ( "settings.automations.fields.cronExpression" , "Cron expression" )}
</ span >
< Input
value = { draft . cronExpr }
onChange = {( event ) => setDraft (( prev ) => ({ ... prev , cronExpr : event.target.value }))}
placeholder = "0 9 * * *"
2026-08-14 07:07:09 +09:00
className = "font-mono text-[13px]"
2026-08-10 19:33:52 +08:00
/>
</ label >
< label className = "block space-y-1.5" >
< span className = "text-[12px] font-medium text-muted-foreground" >
{ tx ( "settings.automations.fields.timezone" , "Timezone" )}
</ span >
< Input
value = { draft . tz }
onChange = {( event ) => setDraft (( prev ) => ({ ... prev , tz : event.target.value }))}
placeholder = "Asia/Shanghai"
2026-08-14 07:07:09 +09:00
className = "text-[13px]"
2026-08-10 19:33:52 +08:00
/>
</ label >
</ div >
) : null }
{ ! localTrigger && draft . scheduleKind === "at" ? (
< label className = "block space-y-1.5" >
< span className = "text-[12px] font-medium text-muted-foreground" >
{ tx ( "settings.automations.fields.runAt" , "Run at" )}
</ span >
< Input
type = "datetime-local"
value = { draft . atLocal }
onChange = {( event ) => setDraft (( prev ) => ({ ... prev , atLocal : event.target.value }))}
/>
</ label >
) : null }
{ validation ? (
2026-08-14 07:07:09 +09:00
< div className = "rounded-control bg-destructive/8 px-3 py-2 text-[12px] text-destructive" >
2026-08-10 19:33:52 +08:00
{ validation }
</ div >
) : null }
</ div >
< DialogFooter >
< Button
type = "button"
variant = "ghost"
2026-09-12 16:32:46 +08:00
onClick = {() => changeOpen ( false )}
2026-08-10 19:33:52 +08:00
disabled = { saving }
>
{ tx ( "settings.automations.cancel" , "Cancel" )}
</ Button >
2026-08-14 07:07:09 +09:00
< Button type = "submit" disabled = { Boolean ( validation ) || saving }>
2026-08-10 19:33:52 +08:00
{ saving ? < Loader2 className = "mr-2 h-4 w-4 animate-spin" aria - hidden /> : null }
{ tx ( "settings.automations.save" , "Save" )}
</ Button >
</ DialogFooter >
</ form >
</ DialogContent >
) : null }
</ Dialog >
);
}
export function AutomationDeleteDialog ({
job ,
deleting ,
onOpenChange ,
onConfirm ,
} : {
job : SessionAutomationJob | null ;
deleting : boolean ;
onOpenChange : ( open : boolean ) => void ;
onConfirm : ( job : SessionAutomationJob ) => void | Promise < void >;
}) {
2026-09-11 19:10:15 +08:00
const dialogFocus = useAutomationDialogFocus ();
2026-08-10 19:33:52 +08:00
const { t } = useTranslation ();
const tx = ( key : string , fallback : string , values? : Record < string , unknown >) =>
t ( key , { defaultValue : fallback , ...( values ?? {}) });
return (
< Dialog open = { Boolean ( job )} onOpenChange = { onOpenChange }>
2026-09-11 19:10:15 +08:00
< DialogContent { ...dialogFocus } className = "w-[min(calc(100vw-2rem),26rem)]" >
2026-08-10 19:33:52 +08:00
< DialogHeader >
< DialogTitle >{ tx ( "settings.automations.deleteTitle" , "Delete automation" )}</ DialogTitle >
< DialogDescription >
{ tx (
"settings.automations.deleteDescription" ,
"This removes {{name}} from automations. Past chat messages stay in the session." ,
{ name : job?.name || job ? . id || "" },
)}
</ DialogDescription >
</ DialogHeader >
< DialogFooter >
< Button
type = "button"
variant = "ghost"
onClick = {() => onOpenChange ( false )}
disabled = { deleting }
>
{ tx ( "settings.automations.cancel" , "Cancel" )}
</ Button >
< Button
type = "button"
variant = "destructive"
onClick = {() => job && void onConfirm ( job )}
disabled = { ! job || deleting }
>
{ deleting ? < Loader2 className = "mr-2 h-4 w-4 animate-spin" aria - hidden /> : null }
{ tx ( "settings.automations.delete" , "Delete" )}
</ Button >
</ DialogFooter >
</ DialogContent >
</ Dialog >
);
}
function isLocalTriggerAutomation ( job : SessionAutomationJob | null ) : boolean {
if ( ! job ) return false ;
return job . kind === "local_trigger"
|| job . payload . kind === "local_trigger"
|| job . schedule . kind === "local" ;
}
function automationTriggerCommand ( job : SessionAutomationJob ) : string {
return job . trigger ? . command || job . payload . command || job . payload . message || "" ;
}
function automationSummary (
job : SessionAutomationJob ,
tx : ( key : string , fallback : string , values? : Record < string , unknown >) => string ,
) : string {
if ( isLocalTriggerAutomation ( job )) {
return automationTriggerCommand ( job ) || tx ( "settings.automations.localTrigger" , "Local trigger" );
}
return job . payload . message || tx ( "settings.automations.systemTask" , "System-managed automation" );
}
function automationNeedsAttention ( job : SessionAutomationJob ) : boolean {
return job . state . last_status === "error" ;
}
function automationStatusKey (
job : SessionAutomationJob ,
) : "active" | "running" | "paused" | "failed" | "system" | "completed" | "idle" {
if ( job . protected ) return "system" ;
if ( job . state . pending ) return "running" ;
if ( ! job . enabled ) return "paused" ;
if ( job . state . last_status === "error" ) return "failed" ;
if ( isLocalTriggerAutomation ( job )) return "active" ;
if ( job . delete_after_run && ! job . state . next_run_at_ms && job . state . last_status === "ok" ) {
return "completed" ;
}
if ( ! job . state . next_run_at_ms ) return "idle" ;
return "active" ;
}
function automationDraftFromJob ( job : SessionAutomationJob | null ) : AutomationEditDraft {
const every = automationIntervalDraft ( job ? . schedule . every_ms ?? 3 _600_000 );
const scheduleKind = job ? . schedule . kind === "at" || job ? . schedule . kind === "cron"
? job . schedule . kind
: "every" ;
return {
name : job?.name ?? "" ,
message : job?.payload.message ?? "" ,
scheduleKind ,
everyValue : every.value ,
everyUnit : every.unit ,
cronExpr : job?.schedule.expr ?? "0 9 * * *" ,
tz : job?.schedule.tz ?? "" ,
atLocal : formatLocalDateTimeInput ( job ? . schedule . at_ms ?? Date . now () + 3 _600_000 ),
};
}
function automationIntervalDraft ( ms : number ) : { value : string ; unit : AutomationEveryUnit } {
for ( const unit of [... AUTOMATION_EVERY_UNITS ]. reverse ()) {
if ( ms >= unit . ms && ms % unit . ms === 0 ) {
return { value : String ( ms / unit . ms ), unit : unit.value };
}
}
return { value : String ( Math . max ( 1 , Math . round ( ms / 60 _000 ))), unit : "minute" };
}
function formatLocalDateTimeInput ( ms : number ) : string {
const date = new Date ( ms );
if ( ! Number . isFinite ( date . getTime ())) return "" ;
const local = new Date ( ms - date . getTimezoneOffset () * 60 _000 );
return local . toISOString (). slice ( 0 , 16 );
}
function automationEditDraftError (
draft : AutomationEditDraft ,
job : SessionAutomationJob | null ,
tx : ( key : string , fallback : string , values? : Record < string , unknown >) => string ,
) : string | null {
2026-09-10 11:10:51 +08:00
if ( ! draft . name . trim ()) return tx ( "settings.automations.validation.nameRequired" , "Enter a task name." );
2026-08-10 19:33:52 +08:00
if ( isLocalTriggerAutomation ( job )) return null ;
if ( ! draft . message . trim ()) {
2026-09-10 11:10:51 +08:00
return tx ( "settings.automations.validation.messageRequired" , "Enter a task message." );
2026-08-10 19:33:52 +08:00
}
if ( draft . scheduleKind === "every" ) {
const value = Number ( draft . everyValue );
if ( ! Number . isInteger ( value ) || value <= 0 ) {
2026-09-10 11:10:51 +08:00
return tx ( "settings.automations.validation.intervalRequired" , "Enter a positive whole number for the interval." );
2026-08-10 19:33:52 +08:00
}
}
if ( draft . scheduleKind === "cron" && ! draft . cronExpr . trim ()) {
2026-09-10 11:10:51 +08:00
return tx ( "settings.automations.validation.cronRequired" , "Enter a Cron expression." );
2026-08-10 19:33:52 +08:00
}
if ( draft . scheduleKind === "at" ) {
const atMs = new Date ( draft . atLocal ). getTime ();
if ( ! Number . isFinite ( atMs )) {
2026-09-10 11:10:51 +08:00
return tx ( "settings.automations.validation.timeRequired" , "Choose a run time." );
2026-08-10 19:33:52 +08:00
}
if ( atMs <= Date . now () && automationScheduleChanged ( draft , job )) {
2026-09-10 11:10:51 +08:00
return tx ( "settings.automations.validation.futureRequired" , "Choose a time in the future." );
2026-08-10 19:33:52 +08:00
}
}
return null ;
}
function automationUpdatePayloadFromDraft (
draft : AutomationEditDraft ,
job : SessionAutomationJob | null ,
) : AutomationUpdatePayload | string {
const name = draft . name . trim ();
if ( isLocalTriggerAutomation ( job )) {
if ( ! name ) return "invalid" ;
return { name };
}
const message = draft . message . trim ();
if ( ! name || ! message ) return "invalid" ;
const payload : AutomationUpdatePayload = { name , message };
const schedule = automationSchedulePayloadFromDraft ( draft );
if ( typeof schedule === "string" ) return schedule ;
if ( automationScheduleChanged ( draft , job , schedule )) {
payload . schedule = schedule ;
}
return payload ;
}
function automationSchedulePayloadFromDraft ( draft : AutomationEditDraft ) : AutomationScheduleUpdate | string {
if ( draft . scheduleKind === "every" ) {
const unit = AUTOMATION_EVERY_UNITS . find (( candidate ) => candidate . value === draft . everyUnit );
const value = Number ( draft . everyValue );
if ( ! unit || ! Number . isInteger ( value ) || value <= 0 ) return "invalid" ;
return { kind : "every" , every_ms : value * unit . ms };
} else if ( draft . scheduleKind === "cron" ) {
const expr = draft . cronExpr . trim ();
if ( ! expr ) return "invalid" ;
return { kind : "cron" , expr , ...( draft . tz . trim () ? { tz : draft.tz.trim () } : {}) };
} else {
const atMs = new Date ( draft . atLocal ). getTime ();
if ( ! Number . isFinite ( atMs )) return "invalid" ;
return { kind : "at" , at_ms : atMs };
}
}
function automationScheduleChanged (
draft : AutomationEditDraft ,
job : SessionAutomationJob | null ,
schedule : AutomationScheduleUpdate | string = automationSchedulePayloadFromDraft ( draft ),
) : boolean {
if ( ! job || typeof schedule === "string" ) return true ;
if ( schedule . kind !== job . schedule . kind ) return true ;
if ( schedule . kind === "every" ) return schedule . every_ms !== job . schedule . every_ms ;
if ( schedule . kind === "cron" ) {
return schedule . expr !== ( job . schedule . expr ?? "" ) || ( schedule . tz ?? null ) !== ( job . schedule . tz ?? null );
}
return draft . atLocal !== formatLocalDateTimeInput ( job . schedule . at_ms ?? NaN );
}
const HOST_AUTOMATION_CHANNEL_LABELS : Record < string , string > = {
api : "API" ,
cli : "CLI" ,
};
function automationMatchesFilter ( job : SessionAutomationJob , filter : AutomationFilter ) : boolean {
const status = automationStatusKey ( job );
if ( filter === "active" ) return status === "active" || status === "running" ;
if ( filter === "paused" ) return status === "paused" ;
if ( filter === "failed" ) return automationNeedsAttention ( job );
if ( filter === "system" ) return Boolean ( job . protected );
return true ;
}
function automationOriginLabel (
job : SessionAutomationJob ,
2026-09-11 15:22:14 +08:00
t : TFunction ,
2026-08-10 19:33:52 +08:00
) : string {
2026-09-11 15:22:14 +08:00
if ( job . protected ) return t ( "settings.automations.origin.system" , { defaultValue : "System" });
2026-08-10 19:33:52 +08:00
const origin = job . origin ;
2026-09-11 15:22:14 +08:00
if ( ! origin ) return t ( "settings.automations.origin.unknown" , { defaultValue : "No linked chat" });
if ( origin . channel !== "websocket" ) return automationChannelLabel ( origin . channel , t );
return origin . title || origin . preview || origin . session_key || automationChannelLabel ( origin . channel , t );
2026-08-10 19:33:52 +08:00
}
function automationChannelLabel (
channel : string ,
2026-09-11 15:22:14 +08:00
t : TFunction ,
2026-08-10 19:33:52 +08:00
) : string {
const key = channel . trim (). toLowerCase ();
2026-09-11 15:22:14 +08:00
const presentation = channelUiPresentation ( key );
if ( presentation ) {
return channelTranslator ( t , channelUiOwner ( key ))( "displayName" , presentation . displayName );
}
const displayName = HOST_AUTOMATION_CHANNEL_LABELS [ key ];
2026-08-10 19:33:52 +08:00
return displayName
2026-09-11 15:22:14 +08:00
? t ( `settings.automations.channels. ${ key } ` , { defaultValue : displayName })
2026-08-10 19:33:52 +08:00
: channel ;
}
function formatAutomationSchedule (
job : SessionAutomationJob ,
locale : string ,
tx : ( key : string , fallback : string , values? : Record < string , unknown >) => string ,
) : string {
if ( job . schedule . kind === "at" && job . schedule . at_ms ) {
return tx ( "settings.automations.schedule.at" , "At {{time}}" , {
time : fmtDateTime ( job . schedule . at_ms , locale ),
});
}
if ( job . schedule . kind === "every" && job . schedule . every_ms ) {
return tx ( "settings.automations.schedule.every" , "Every {{duration}}" , {
duration : formatAutomationInterval ( job . schedule . every_ms , locale ),
});
}
if ( job . schedule . kind === "cron" && job . schedule . expr ) {
const summary = formatCronScheduleSummary ( job . schedule . expr , tx );
2026-09-12 16:32:46 +08:00
if ( summary ) return summary ;
return tx ( "settings.automations.schedule.cron" , "Cron {{expr}}" , {
expr : job.schedule.expr ,
});
2026-08-10 19:33:52 +08:00
}
if ( isLocalTriggerAutomation ( job )) {
return tx ( "settings.automations.schedule.local" , "Local trigger" );
}
return tx ( "settings.automations.schedule.custom" , "Custom schedule" );
}
function formatCronScheduleSummary (
expr : string ,
tx : ( key : string , fallback : string , values? : Record < string , unknown >) => string ,
) : string | null {
const parts = expr . trim (). split ( /\s+/ );
if ( parts . length !== 5 ) return null ;
const [ minute , hour , dayOfMonth , month , dayOfWeek ] = parts ;
const numericMinute = cronNumericToken ( minute , 59 );
const numericHour = cronNumericToken ( hour , 23 );
const everyDay = dayOfMonth === "*" && month === "*" && dayOfWeek === "*" ;
const workdays = dayOfMonth === "*" && month === "*" && [ "1-5" , "MON-FRI" , "mon-fri" ]. includes ( dayOfWeek );
if ( numericMinute !== null && numericHour !== null ) {
const time = ` ${ String ( numericHour ). padStart ( 2 , "0" ) } : ${ String ( numericMinute ). padStart ( 2 , "0" ) } ` ;
if ( everyDay ) return tx ( "settings.automations.schedule.dailyAt" , "Daily at {{time}}" , { time });
if ( workdays ) return tx ( "settings.automations.schedule.weekdaysAt" , "Weekdays at {{time}}" , { time });
}
if ( everyDay && numericMinute !== null && hour === "*" ) {
return tx ( "settings.automations.schedule.hourlyAt" , "Hourly at :{{minute}}" , {
minute : String ( numericMinute ). padStart ( 2 , "0" ),
});
}
const range = /^(\d{1,2})-(\d{1,2})$/ . exec ( hour );
if ( everyDay && numericMinute !== null && range ) {
const start = Number ( range [ 1 ]);
const end = Number ( range [ 2 ]);
if ( start > 23 || end > 23 ) return null ;
return tx ( "settings.automations.schedule.hourlyWindow" , "Hourly {{start}}-{{end}} at :{{minute}}" , {
start : String ( start ). padStart ( 2 , "0" ),
end : String ( end ). padStart ( 2 , "0" ),
minute : String ( numericMinute ). padStart ( 2 , "0" ),
});
}
return null ;
}
function cronNumericToken ( value : string , max : number ) : number | null {
if ( ! /^\d{1,2}$/ . test ( value )) return null ;
const parsed = Number ( value );
return parsed <= max ? parsed : null ;
}
function formatAutomationNext (
job : SessionAutomationJob ,
tx : ( key : string , fallback : string , values? : Record < string , unknown >) => string ,
) : string {
if ( ! job . enabled ) return tx ( "settings.automations.next.paused" , "Paused" );
if ( job . state . pending ) return tx ( "settings.automations.next.pending" , "Running now" );
if ( isLocalTriggerAutomation ( job )) {
return tx ( "settings.automations.next.local" , "Waiting for trigger" );
}
2026-09-11 19:10:15 +08:00
if ( automationStatusKey ( job ) === "completed" ) {
return tx ( "settings.automations.status.completed" , "Completed" );
}
2026-08-10 19:33:52 +08:00
if ( ! job . state . next_run_at_ms ) return tx ( "settings.automations.next.none" , "No next run" );
return relativeTime ( job . state . next_run_at_ms );
}
function formatAutomationNextTitle (
job : SessionAutomationJob ,
locale : string ,
tx : ( key : string , fallback : string , values? : Record < string , unknown >) => string ,
) : string {
if ( ! job . state . next_run_at_ms ) return formatAutomationNext ( job , tx );
return fmtDateTime ( job . state . next_run_at_ms , locale );
}
function formatAutomationUnit (
value : number ,
unit : Intl.NumberFormatOptions [ "unit" ],
locale : string ,
maximumFractionDigits = 0 ,
) : string {
return new Intl . NumberFormat ( locale , {
style : "unit" ,
unit ,
unitDisplay : "long" ,
maximumFractionDigits ,
}). format ( value );
}
function formatAutomationInterval ( ms : number , locale : string ) : string {
const units : Array < [ Intl . NumberFormatOptions [ "unit" ], number ] > = [
[ "day" , 86 _400_000 ],
[ "hour" , 3 _600_000 ],
[ "minute" , 60 _000 ],
[ "second" , 1000 ],
];
for ( const [ unit , size ] of units ) {
if ( ms >= size && ms % size === 0 ) return formatAutomationUnit ( ms / size , unit , locale );
}
const fallbackUnit = ms < 60 _000 ? "second" : "minute" ;
const fallbackSize = fallbackUnit === "second" ? 1000 : 60_000 ;
return formatAutomationUnit ( ms / fallbackSize , fallbackUnit , locale , 1 );
}