diff --git a/webui/src/App.tsx b/webui/src/App.tsx index 9f31f5678..a98704fee 100644 --- a/webui/src/App.tsx +++ b/webui/src/App.tsx @@ -46,6 +46,7 @@ import { useSkills } from "@/hooks/useSkills"; import { useLogoFallback } from "@/hooks/useLogoFallback"; import { usePageVisibility } from "@/hooks/usePageVisibility"; import { useMediaQuery } from "@/hooks/useMediaQuery"; +import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream"; import { ThemeProvider, useTheme } from "@/hooks/useTheme"; import { logoFallbackUrls } from "@/lib/provider-brand"; import { cn } from "@/lib/utils"; @@ -1126,6 +1127,13 @@ function Shell({ const skills = useSkills(getToken); const pageVisible = usePageVisibility(); const [settingsSnapshot, setSettingsSnapshot] = useState(null); + const [pendingAutomationMessage, setPendingAutomationMessage] = useState<{ + id: string; + chatId: string; + content: string; + images?: SendAttachment[]; + options?: SendOptions; + } | null>(null); const settingsExitGuardRef = useRef(null); const currentShellRouteRef = useRef({ view, activeKey, settingsSection: settingsInitialSection }); currentShellRouteRef.current = { view, activeKey, settingsSection: settingsInitialSection }; @@ -1581,6 +1589,32 @@ function Shell({ } }, [activeWorkspaceScope, createChat, navigate, t]); + const onStartAutomationChat = useCallback(async ( + content: string, + images?: SendAttachment[], + options?: SendOptions, + modelPreset?: string | null, + ) => { + const chatId = await onCreateChat( + options?.workspaceScope ?? activeWorkspaceScope, + content, + modelPreset, + ); + if (!chatId) return false; + setPendingAutomationMessage({ + id: crypto.randomUUID(), + chatId, + content, + images, + options, + }); + return true; + }, [activeWorkspaceScope, onCreateChat]); + + const onPendingAutomationMessageConsumed = useCallback((id: string) => { + setPendingAutomationMessage((current) => current?.id === id ? null : current); + }, []); + const onCreateTemporaryChat = useCallback( async ( workspaceScope?: WorkspaceScopePayload | null, @@ -2754,6 +2788,8 @@ function Shell({ onCreateChat={ temporaryChatEnabled ? onCreateTemporaryChat : onCreateChat } + pendingFirstMessage={pendingAutomationMessage} + onPendingFirstMessageConsumed={onPendingAutomationMessageConsumed} onForkChat={temporaryChatActive ? undefined : onForkChat} onTurnEnd={onTurnEnd} theme={theme} @@ -2790,6 +2826,8 @@ function Shell({ onToggleSidebar={toggleSidebar} onNewChat={onNewChat} onCreateChat={onCreateChat} + pendingFirstMessage={pendingAutomationMessage} + onPendingFirstMessageConsumed={onPendingAutomationMessageConsumed} onForkChat={onForkChat} onTurnEnd={context.active ? onTurnEnd : () => void refresh()} theme={theme} @@ -2847,6 +2885,7 @@ function Shell({ onModelNameChange={onModelNameChange} onSettingsChange={setSettingsSnapshot} skills={skills} + onStartAutomationChat={onStartAutomationChat} titleOverrides={sidebarState.title_overrides} onSectionChange={onSettingsSectionChange} onLogout={onLogout} diff --git a/webui/src/components/settings/SettingsPage.tsx b/webui/src/components/settings/SettingsPage.tsx index cdccc7169..7b9fb7196 100644 --- a/webui/src/components/settings/SettingsPage.tsx +++ b/webui/src/components/settings/SettingsPage.tsx @@ -40,7 +40,8 @@ import { RUNTIME_CONFIG_FIELDS, type RuntimeConfigPage } from "@/components/sett import { RuntimeConfigSettings } from "@/components/settings/system/RuntimeConfigSettings"; import { RuntimeSettings } from "@/components/settings/system/RuntimeSettings"; import type { SettingsController } from "@/components/settings/useSettingsController"; -import type { SkillSummary } from "@/lib/types"; +import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream"; +import type { SessionAutomationJob, SkillSummary } from "@/lib/types"; import { cn } from "@/lib/utils"; interface SettingsPageProps { @@ -51,6 +52,12 @@ interface SettingsPageProps { onToggleTheme: () => void; onBackToChat: () => void; skills: SkillSummary[]; + onStartAutomationChat?: ( + content: string, + images?: SendAttachment[], + options?: SendOptions, + modelPreset?: string | null, + ) => boolean | void | Promise; titleOverrides?: Record; onLogout?: () => void; isRestarting: boolean; @@ -65,6 +72,7 @@ export function SettingsPage({ onToggleTheme, onBackToChat, skills, + onStartAutomationChat, titleOverrides, onLogout, isRestarting, @@ -72,6 +80,8 @@ export function SettingsPage({ }: SettingsPageProps) { const [dialogLayoutAnchor, setDialogLayoutAnchor] = useState(null); const [pendingExit, setPendingExit] = useState<(() => void) | null>(null); + const [automationDetailReturn, setAutomationDetailReturn] = + useState(null); const { activeSection, apiService, @@ -565,6 +575,8 @@ export function SettingsPage({ { + setAutomationDetailReturn(null); + setAutomationPendingEdit(job); + }} onRequestDelete={setAutomationPendingDelete} + onManageModels={() => selectSection("models")} + returnToDetailJob={automationDetailReturn} + onReturnToDetailHandled={() => setAutomationDetailReturn(null)} /> ); @@ -709,6 +727,7 @@ export function SettingsPage({ onOpenChange={(open) => { if (!open) setAutomationPendingEdit(null); }} + onCancel={(job) => setAutomationDetailReturn(job)} onSave={handleAutomationEdit} /> @@ -728,6 +747,7 @@ export function SettingsPage({ "motion-reduce:animate-none sm:py-8 lg:py-12", "settings-grid", !showSidebar && "settings-feature-page", + !showSidebar && activeSection === "automations" && "settings-automations-grid", hostChromeInset && "pt-[4.25rem] sm:pt-[4.25rem] lg:pt-[4.75rem]", )} > diff --git a/webui/src/components/settings/SettingsView.tsx b/webui/src/components/settings/SettingsView.tsx index b688d6bc6..a14f1ea5f 100644 --- a/webui/src/components/settings/SettingsView.tsx +++ b/webui/src/components/settings/SettingsView.tsx @@ -1,6 +1,7 @@ import { SettingsPage } from "@/components/settings/SettingsPage"; import type { SettingsExitGuard, SettingsSectionKey } from "@/components/settings/contracts"; import { useSettingsController } from "@/components/settings/useSettingsController"; +import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream"; import type { SettingsPayload, SkillSummary } from "@/lib/types"; export type { SettingsSectionKey } from "@/components/settings/contracts"; @@ -16,6 +17,12 @@ interface SettingsViewProps { onModelNameChange: (modelName: string | null) => void; onSettingsChange?: (payload: SettingsPayload) => void; skills?: SkillSummary[]; + onStartAutomationChat?: ( + content: string, + images?: SendAttachment[], + options?: SendOptions, + modelPreset?: string | null, + ) => boolean | void | Promise; titleOverrides?: Record; onSectionChange?: (section: SettingsSectionKey) => void; onLogout?: () => void; @@ -36,6 +43,7 @@ export function SettingsView({ onModelNameChange, onSettingsChange, skills = [], + onStartAutomationChat, titleOverrides, onSectionChange, onLogout, @@ -63,6 +71,7 @@ export function SettingsView({ onToggleTheme={onToggleTheme} onBackToChat={onBackToChat} skills={skills} + onStartAutomationChat={onStartAutomationChat} titleOverrides={titleOverrides} onLogout={onLogout} isRestarting={isRestarting} diff --git a/webui/src/components/settings/system/AutomationCalendar.tsx b/webui/src/components/settings/system/AutomationCalendar.tsx new file mode 100644 index 000000000..0fe46dbfa --- /dev/null +++ b/webui/src/components/settings/system/AutomationCalendar.tsx @@ -0,0 +1,409 @@ +import { ChevronDown, CircleAlert, Clock3, Loader2 } from "lucide-react"; +import { useLayoutEffect, useMemo, useRef, useState } from "react"; + +import { Button } from "@/components/ui/button"; +import { formControlFocusClassName } from "@/components/ui/form-control"; +import type { SessionAutomationJob } from "@/lib/types"; +import { cn } from "@/lib/utils"; + +type CalendarEntry = { + id: string; + job: SessionAutomationJob; + startMs: number; + endMs: number | null; + kind: "planned" | "recorded"; + status: string | null; +}; + +type CalendarCopy = { + previousMonth: string; + nextMonth: string; + today: string; + planned: string; + recorded: string; + running: string; + failed: string; + more: (count: number) => string; + noEntries: string; + outsideMonth: string; + paused: string; + attention: string; + completed: string; +}; + +interface AutomationCalendarProps { + jobs: SessionAutomationJob[]; + locale: string; + copy: CalendarCopy; + onInspect: (job: SessionAutomationJob, trigger: HTMLElement) => void; +} + +function startOfDay(date: Date): Date { + return new Date(date.getFullYear(), date.getMonth(), date.getDate()); +} + +function startOfMonth(date: Date): Date { + return new Date(date.getFullYear(), date.getMonth(), 1); +} + +function addDays(date: Date, amount: number): Date { + return new Date(date.getFullYear(), date.getMonth(), date.getDate() + amount); +} + +function addMonths(date: Date, amount: number): Date { + return new Date(date.getFullYear(), date.getMonth() + amount, 1); +} + +function mondayIndex(date: Date): number { + return (date.getDay() + 6) % 7; +} + +function dateKey(value: Date | number): string { + const date = typeof value === "number" ? new Date(value) : value; + return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`; +} + +function entriesForJobs(jobs: SessionAutomationJob[]): CalendarEntry[] { + return jobs.flatMap((job) => { + const history = job.state.run_history ?? []; + const nextRun = job.enabled ? job.state.next_run_at_ms : null; + const recordedRuns = history.length || job.state.last_run_at_ms == null || nextRun != null + ? history + : [{ + run_at_ms: job.state.last_run_at_ms, + status: job.state.last_status ?? "ok", + }]; + const recorded = recordedRuns.map((run, index) => ({ + id: `${job.id}:recorded:${run.run_at_ms}:${index}`, + job, + startMs: run.run_at_ms, + endMs: run.duration_ms != null && run.duration_ms > 0 + ? run.run_at_ms + run.duration_ms + : null, + kind: "recorded" as const, + status: run.status ?? null, + })); + return nextRun == null ? recorded : [ + ...recorded, + { + id: `${job.id}:planned:${nextRun}`, + job, + startMs: nextRun, + endMs: null, + kind: "planned" as const, + status: null, + }, + ]; + }); +} + +function entryTime(entry: CalendarEntry, locale: string): string { + const formatter = new Intl.DateTimeFormat(locale, { hour: "2-digit", minute: "2-digit" }); + const start = formatter.format(entry.startMs); + if (entry.endMs == null) return start; + return `${start}–${formatter.format(entry.endMs)}`; +} + +function isSameDay(left: Date, right: Date): boolean { + return dateKey(left) === dateKey(right); +} + +function CalendarEntryRow({ entry, locale, copy, onInspect, compact = false }: { + entry: CalendarEntry; + locale: string; + copy: CalendarCopy; + onInspect: AutomationCalendarProps["onInspect"]; + compact?: boolean; +}) { + const name = entry.job.name || entry.job.id; + const running = Boolean(entry.job.state.pending) && entry.kind === "planned"; + const failed = entry.kind === "recorded" && entry.status === "error"; + const completed = entry.kind === "recorded" + && Boolean(entry.job.delete_after_run) + && entry.job.state.next_run_at_ms == null + && entry.job.state.last_status === "ok"; + const status = running + ? copy.running + : failed + ? copy.failed + : completed + ? copy.completed + : entry.kind === "planned" + ? copy.planned + : copy.recorded; + const content = ( + <> + + + {name} + + {running ? : null} + {failed ? : null} + {entryTime(entry, locale)} + {compact ? {status} : null} + + + + ); + const actionClass = cn( + "flex w-full min-w-0 items-start gap-2 rounded-compact px-2 py-1.5 text-left text-[11px] leading-4", + "transition-colors duration-150 hover:bg-foreground/[0.055] motion-reduce:transition-none", + formControlFocusClassName, + compact && "py-2 text-[12px]", + failed && "bg-destructive/[0.045]", + entry.kind === "recorded" && !failed && "bg-muted/45", + ); + + return ( + + ); +} + +export function AutomationCalendar({ jobs, locale, copy, onInspect }: AutomationCalendarProps) { + const [month, setMonth] = useState(() => startOfMonth(new Date())); + const calendarRef = useRef(null); + const [wideCalendar, setWideCalendar] = useState(true); + const today = startOfDay(new Date()); + const gridStart = addDays(month, -mondayIndex(month)); + const daysInMonth = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate(); + const dayCount = mondayIndex(month) + daysInMonth > 35 ? 42 : 35; + const days = Array.from({ length: dayCount }, (_, index) => addDays(gridStart, index)); + const gridEndMs = addDays(gridStart, dayCount).getTime(); + const allEntries = useMemo(() => entriesForJobs(jobs).sort((left, right) => left.startMs - right.startMs), [jobs]); + const visibleEntries = allEntries.filter((entry) => entry.startMs >= gridStart.getTime() && entry.startMs < gridEndMs); + const entriesByDay = new Map(); + visibleEntries.forEach((entry) => { + const key = dateKey(entry.startMs); + entriesByDay.set(key, [...(entriesByDay.get(key) ?? []), entry]); + }); + const visibleJobIds = new Set(visibleEntries.map((entry) => entry.job.id)); + const outsideJobs = jobs.filter((job) => !visibleJobIds.has(job.id)); + const monthLabel = new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" }).format(month); + const weekdayFormatter = new Intl.DateTimeFormat(locale, { weekday: "short" }); + const dayFormatter = new Intl.DateTimeFormat(locale, { day: "numeric" }); + const agendaDateFormatter = new Intl.DateTimeFormat(locale, { month: "short", day: "numeric", weekday: "short" }); + const weekdayLabels = Array.from({ length: 7 }, (_, index) => weekdayFormatter.format(addDays(new Date(2026, 0, 5), index))); + + const inspectOutsideJob = (job: SessionAutomationJob, target: HTMLElement) => onInspect(job, target); + + useLayoutEffect(() => { + const calendar = calendarRef.current; + if (!calendar) return; + const update = (width: number) => { + if (width > 0) setWideCalendar(width >= 704); + }; + update(calendar.getBoundingClientRect().width); + if (typeof ResizeObserver === "undefined") return; + const observer = new ResizeObserver(([entry]) => update(entry?.contentRect.width ?? 0)); + observer.observe(calendar); + return () => observer.disconnect(); + }, []); + + return ( +
+
+

{monthLabel}

+
+ + + +
+
+ + {!jobs.length ? ( +
+ {copy.noEntries} +
+ ) : null} + + {jobs.length > 0 && wideCalendar ?
+
+ {weekdayLabels.map((label) =>
{label}
)} +
+
+ {days.map((day) => { + const entries = entriesByDay.get(dateKey(day)) ?? []; + const currentMonth = day.getMonth() === month.getMonth(); + const currentDay = isSameDay(day, today); + const dayLabel = new Intl.DateTimeFormat(locale, { dateStyle: "full" }).format(day); + return ( +
+
+ +
+
+ {entries.slice(0, 3).map((entry) => ( + + ))} + {entries.length > 3 ? ( +
+ + {copy.more(entries.length - 3)} + +
+ {entries.slice(3).map((entry) => ( + + ))} +
+
+ ) : null} +
+
+ ); + })} +
+
: null} + + {jobs.length > 0 && !wideCalendar ?
+ {visibleEntries.length ? ( +
    + {days.filter((day) => entriesByDay.has(dateKey(day))).map((day) => ( +
  1. + +
    + {(entriesByDay.get(dateKey(day)) ?? []).map((entry) => ( + + ))} +
    +
  2. + ))} +
+ ) : ( +
{copy.noEntries}
+ )} +
: null} + + {jobs.length ? ( +
+ + + + + {copy.planned} + + + {copy.recorded} + + +
+ ) : null} + + {outsideJobs.length ? ( +
+ + + + {copy.outsideMonth} + {outsideJobs.length} + + + +
    + {outsideJobs.map((job) => ( +
  • + +
  • + ))} +
+
+ ) : null} +
+ ); +} diff --git a/webui/src/components/settings/system/AutomationsSettings.tsx b/webui/src/components/settings/system/AutomationsSettings.tsx index cdebe96b8..c8b34cafa 100644 --- a/webui/src/components/settings/system/AutomationsSettings.tsx +++ b/webui/src/components/settings/system/AutomationsSettings.tsx @@ -9,14 +9,19 @@ import { CircleAlert, Clipboard, Loader2, - MoreHorizontal, Search, } 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 { SETTINGS_SEARCH_INPUT_CLASS, SettingsGroup } from "@/components/settings/shared/SettingsControls"; +import { + modelPresetOptionsFromSettings, + toModelBadgeInfo, +} from "@/components/thread/model-preset"; +import { ThreadComposer } from "@/components/thread/ThreadComposer"; import { Button } from "@/components/ui/button"; import { Disclosure, DisclosureContent } from "@/components/ui/disclosure"; import { ExpandableText } from "@/components/ui/expandable-text"; @@ -41,7 +46,13 @@ 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 { AutomationsPayload, AutomationUpdatePayload, SessionAutomationJob } from "@/lib/types"; +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"; @@ -54,11 +65,14 @@ const SYSTEM_TASKS_OPEN_STORAGE_KEY = "nanobot-webui.automation-system-tasks-ope export function AutomationsSettings({ payload, loading, query, filter, sort, actionKey, error, titleOverrides = EMPTY_TITLE_OVERRIDES, + settingsSnapshot = null, onQueryChange, onFilterChange, onSortChange, onAction, - onRequestEdit, onRequestDelete, + onRequestEdit, onRequestDelete, onStartChat, onManageModels, + returnToDetailJob = null, onReturnToDetailHandled, }: { payload: AutomationsPayload | null; titleOverrides?: Record; + settingsSnapshot?: SettingsPayload | null; loading: boolean; query: string; filter: AutomationFilter; @@ -71,6 +85,15 @@ export function AutomationsSettings({ 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) => @@ -87,6 +110,7 @@ export function AutomationsSettings({ const locale = i18n.resolvedLanguage || i18n.language; const [inspectedJob, setInspectedJob] = useState(null); const [detailOpen, setDetailOpen] = useState(false); + const [localModelPreset, setLocalModelPreset] = useState(null); const [systemOpen, setSystemOpen] = useState(() => { try { return window.localStorage.getItem(SYSTEM_TASKS_OPEN_STORAGE_KEY) !== "false"; @@ -96,7 +120,7 @@ export function AutomationsSettings({ }); const searchInput = useRef(null); const pageTitle = useRef(null); - const selectedTrigger = useRef(null); + const selectedTrigger = useRef(null); const afterDetailClose = useRef<((job: SessionAutomationJob) => void) | null>(null); const filtered = useMemo(() => { const searchTokens = parseAutomationSearchQuery(query); @@ -126,6 +150,28 @@ export function AutomationsSettings({ updated: tx("settings.automations.sort.updated", "Updated"), name: tx("settings.automations.sort.name", "Name"), } satisfies Record; + 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); @@ -136,6 +182,14 @@ export function AutomationsSettings({ if (query) setSystemOpen(true); }, [query]); + useEffect(() => { + if (!returnToDetailJob) return; + const currentJob = jobs.find((job) => job.id === returnToDetailJob.id) ?? returnToDetailJob; + setInspectedJob(currentJob); + setDetailOpen(true); + onReturnToDetailHandled?.(); + }, [jobs, onReturnToDetailHandled, returnToDetailJob]); + const renderJob = (job: SessionAutomationJob) => ( ); + 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, + ); return (
@@ -165,12 +238,39 @@ export function AutomationsSettings({
+ {onStartChat ? ( +
+ +
+ ) : null} + {jobs.length ? (
-
+
onQueryChange(event.target.value)} aria-label={tx("settings.automations.search", "Search task, message, linked chat, or schedule")} placeholder={tx("settings.automations.search", "Search task, message, linked chat, or schedule")} - className={cn("h-12 ps-11 text-[15px]", SETTINGS_SEARCH_INPUT_CLASS)} + className={cn("h-10 ps-11 text-[13px]", SETTINGS_SEARCH_INPUT_CLASS)} />
@@ -193,147 +293,189 @@ export function AutomationsSettings({ onChange={onFilterChange} />
+ + + + + + {(Object.keys(sortLabel) as AutomationSort[]).map((value) => ( + onSortChange(value)}> + {sortLabel[value]} + {sort === value ? : null} + + ))} + +
) : null} - - {jobs.length ? ( -
- - - - - - {(Object.keys(sortLabel) as AutomationSort[]).map((value) => ( - onSortChange(value)}> - {sortLabel[value]} - {sort === value ? : null} - - ))} - - -
- ) : null} + {error ? : null} + {loading && !payload ? ( +
+ + {tx("settings.automations.loading", "Loading automations...")} +
+ ) : payload && jobs.length && !filtered.length ? ( +
+ {tx("settings.automations.noMatches", "No automations match this view.")} + +
+ ) : ( + tx("settings.automations.calendar.more", "+{{count}} more", { count }), + 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."), + outsideMonth: tx("settings.automations.calendar.outsideMonth", "Without a date in this month"), + paused: tx("settings.automations.filters.paused", "Paused"), + attention: tx("settings.automations.filters.failed", "Needs attention"), + completed: tx("settings.automations.status.completed", "Completed"), + }} + onInspect={inspectJob} + /> + )} - {error ? : null} - {loading && !payload ? ( -
- - {tx("settings.automations.loading", "Loading automations...")} -
- ) : ( -
- {personal.length ? ( -
    - {personal.map(renderJob)} + {system.length ? ( + +
    + + +
      + {system.map(renderJob)}
    - ) : !personalJobs.length && !query && filter === "all" ? ( -
    -

    - {tx("settings.automations.empty", "No automations yet.")} -

    -

    - {tx("settings.automations.emptyHint", "Tell nanobot in a chat what you'd like it to do on a schedule.")} -

    -
    - ) : !filtered.length ? ( -
    -

    {tx("settings.automations.noMatches", "No automations match this view.")}

    - -
    - ) : null} - {system.length ? ( -
    - - -
      - {system.map(renderJob)} -
    -
    -
    - ) : null} -
- )} -
+ + + + ) : null}
- - {selectedJob ? ( - { - event.preventDefault(); - if (detailOpen) return; - setInspectedJob(null); - const target = selectedTrigger.current?.isConnected - ? selectedTrigger.current : searchInput.current ?? pageTitle.current; - target?.focus({ preventScroll: true }); - const next = afterDetailClose.current; - afterDetailClose.current = null; - if (liveSelectedJob) next?.(liveSelectedJob); - }} - > - setDetailOpen(false)} - onAction={onAction} - onRequestEdit={() => handOff(onRequestEdit)} - onRequestDelete={() => handOff(onRequestDelete)} - /> - - ) : null} - + handOff(onRequestEdit)} + onRequestDelete={() => handOff(onRequestDelete)} + onCloseAutoFocus={(event) => { + event.preventDefault(); + if (detailOpen) return; + setInspectedJob(null); + const target = selectedTrigger.current?.isConnected + ? selectedTrigger.current : searchInput.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 ? ( + + onOpenChange(false)} + onAction={onAction} + onRequestEdit={onRequestEdit} + onRequestDelete={onRequestDelete} + /> + + ) : null} + + ); +} + function AutomationListItem({ job, locale, disabled, onSelect }: { job: SessionAutomationJob; locale: string; @@ -345,7 +487,9 @@ function AutomationListItem({ job, locale, disabled, onSelect }: { t(key, { defaultValue: fallback, ...(values ?? {}) }); const attention = automationNeedsAttention(job); const compact = Boolean(job.protected); - const summary = job.state.last_error || (compact ? null : automationSummary(job, tx)); + const summary = job.state.last_error + ? localizedAutomationError(job.state.last_error, tx) + : compact ? null : automationSummary(job, tx); const running = Boolean(job.state.pending); return (
  • @@ -369,7 +513,7 @@ function AutomationListItem({ job, locale, disabled, onSelect }: { <> {tx("settings.automations.filters.failed", "Needs attention")} - {!job.enabled ? · {tx("settings.automations.next.paused", "Paused")} : null} + {!job.enabled ? {tx("settings.automations.next.paused", "Paused")} : null} ) : ( {formatAutomationNext(job, tx)} @@ -401,6 +545,7 @@ function AutomationDetailPanel({ 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); @@ -427,8 +572,12 @@ function AutomationDetailPanel({ {canManage ? ( - - {formatAutomationSchedule(job, locale, tx)} · {formatAutomationNext(job, tx)} + + {formatAutomationSchedule(job, locale, tx)} + {timezone ? {timezone} : null} + + {formatAutomationNext(job, tx)} + ) : null} @@ -464,6 +613,11 @@ function AutomationDetailPanel({ {formatAutomationSchedule(job, locale, tx)} + {timezone ? ( + + {timezone} + + ) : null} {formatAutomationNext(job, tx)} @@ -471,7 +625,10 @@ function AutomationDetailPanel({ ) : null} {job.state.last_run_at_ms - ? [lastStatus, relativeTime(job.state.last_run_at_ms)].filter(Boolean).join(" · ") + ? + {lastStatus ? {lastStatus} : null} + {relativeTime(job.state.last_run_at_ms)} + : lastStatus || tx("settings.automations.neverRun", "Not run yet")} {!job.protected ? ( @@ -507,18 +664,21 @@ function AutomationDetailPanel({ {actionKey === `${job.enabled ? "disable" : "enable"}:${job.id}` ? : null} {job.enabled ? tx("settings.automations.pause", "Pause") : tx("settings.automations.resume", "Resume")} - {/* The detail dialog owns modality, including during the delete handoff. */} - - - - - - {!localTrigger ? void onAction("run", job)}>{tx("settings.automations.runNow", "Run now")} : null} - onRequestDelete(job)} tone="destructive">{tx("settings.automations.delete", "Delete")} - - + {!localTrigger ? ( + + ) : null} +
    + + { + if (detailOpen) event.preventDefault(); + }} > - - - - -
    -
    -
    - {t("thread.sessionInfo.title")} +
    +
    +
    +
    + {t("thread.sessionInfo.title")} +
    +
    + {title || t("thread.sessionInfo.untitled")} +
    +
    + +
    + + {t("thread.sessionInfo.automations")} + + + {t("thread.sessionInfo.count", { count: jobs.length })} + +
    -
    - {title || t("thread.sessionInfo.untitled")} + +
    + {automationContent} +
    + +
    + + -
    - -
    -
    - - {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 }: { job: SessionAutomationJob; now: number }) { +function AutomationRow({ + job, + now, + onSelect, +}: { + job: SessionAutomationJob; + now: number; + onSelect: (job: SessionAutomationJob) => void; +}) { const { t } = useTranslation("common"); - const schedule = formatSchedule(job, t); 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 - ? job.state.last_status === "error" + ? needsAttention ? "bg-destructive" : "bg-emerald-500" : "bg-muted-foreground/35"; return ( -
    -
    - -
    -
    - {job.name} - {!job.enabled ? ( - - {t("thread.sessionInfo.disabled")} - - ) : null} -
    -
    - {job.payload.message} -
    -
    - {schedule} - · - {nextRun.label} -
    -
    -
    -
    + ); } -function formatSchedule(job: SessionAutomationJob, t: TFunction) { - const locale = currentLocale(); - if (isLocalTriggerAutomation(job)) { - return t("thread.sessionInfo.schedule.local"); - } - if (job.schedule.kind === "at" && job.schedule.at_ms) { - return t("thread.sessionInfo.schedule.at", { time: fmtDateTime(job.schedule.at_ms, locale) }); - } - if (job.schedule.kind === "every" && job.schedule.every_ms) { - return t("thread.sessionInfo.schedule.every", { - duration: formatDuration(job.schedule.every_ms, locale), - }); - } - if (job.schedule.kind === "cron" && job.schedule.expr) { - return job.schedule.tz - ? t("thread.sessionInfo.schedule.cronWithTz", { - expr: job.schedule.expr, - tz: job.schedule.tz, - }) - : t("thread.sessionInfo.schedule.cron", { expr: job.schedule.expr }); - } - return t("thread.sessionInfo.schedule.unknown"); -} - function formatNextRun(job: SessionAutomationJob, t: TFunction, now: number) { const locale = currentLocale(); if (!job.enabled) { @@ -210,28 +333,3 @@ function relativeTimeFrom(value: number, now: number, locale: string): string { } return formatter.format(Math.round(delta), "year"); } - -function formatDuration(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 new Intl.NumberFormat(locale, { - style: "unit", - unit, - unitDisplay: "long", - maximumFractionDigits: 0, - }).format(ms / size); - } - } - return new Intl.NumberFormat(locale, { - style: "unit", - unit: "minute", - unitDisplay: "long", - maximumFractionDigits: 1, - }).format(ms / 60_000); -} diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx index c86f39b50..a5b6739fd 100644 --- a/webui/src/components/thread/ThreadShell.tsx +++ b/webui/src/components/thread/ThreadShell.tsx @@ -14,7 +14,10 @@ import type { ComposerContextUsage, ComposerRoundUsage, } from "@/components/thread/ComposerUsagePopover"; -import type { ModelPresetOption } from "@/components/thread/ModelPresetBadge"; +import { + modelPresetOptionsFromSettings, + toModelBadgeInfo, +} from "@/components/thread/model-preset"; import { ThreadHeader } from "@/components/thread/ThreadHeader"; import { StreamErrorNotice } from "@/components/thread/StreamErrorNotice"; import { ThreadViewport, type ThreadViewportHandle } from "@/components/thread/ThreadViewport"; @@ -40,7 +43,6 @@ import { isMcpPresetsPayload, } from "@/lib/mcp-preset-events"; import type { CanonicalRunSnapshot, StreamError } from "@/lib/nanobot-client"; -import { inferProviderFromModelName, providerDisplayLabel } from "@/lib/provider-brand"; import type { ChatSummary, RoundUsage, @@ -399,6 +401,8 @@ interface ThreadShellProps { initialMessage?: string, modelPreset?: string | null, ) => Promise; + pendingFirstMessage?: PendingFirstMessage & { id: string; chatId: string } | null; + onPendingFirstMessageConsumed?: (id: string) => void; onForkChat?: (sourceChatId: string, beforeUserIndex: number) => Promise; onTurnEnd?: () => void; theme?: "light" | "dark"; @@ -427,99 +431,6 @@ interface ThreadShellProps { skills?: SkillSummary[]; } -function toModelBadgeLabel(modelName: string | null): string | null { - if (!modelName) return null; - const trimmed = modelName.trim(); - if (!trimmed) return null; - const leaf = trimmed.split("/").pop() ?? trimmed; - return leaf || trimmed; -} - -interface ModelBadgeInfo { - label: string | null; - model: string | null; - provider: string | null; - providerLabel: string | null; - needsSetup: boolean; -} - -function modelPresetForBadge( - settings: SettingsPayload | null, - scopedPreset: string | null, -): SettingsPayload["model_presets"][number] | null { - if (!settings) return null; - if (scopedPreset) { - return settings.model_presets.find((preset) => preset.name === scopedPreset) ?? null; - } - const configured = settings.agent.model_preset || "default"; - return ( - settings.model_presets.find((preset) => preset.name === configured) - ?? settings.model_presets.find((preset) => preset.active) - ?? null - ); -} - -function toModelBadgeInfo( - modelName: string | null, - settings: SettingsPayload | null, - modelPreset: string | null = null, -): ModelBadgeInfo { - const scopedPreset = modelPreset?.trim() || null; - const preset = modelPresetForBadge(settings, scopedPreset); - const model = scopedPreset - ? preset?.model || null - : settings?.agent.model || modelName || null; - const label = preset - ? preset.is_default - ? preset.label?.trim() || "Default" - : preset.name.trim() - : scopedPreset || toModelBadgeLabel(model); - const rawProvider = preset?.provider - || (!scopedPreset ? settings?.agent.provider : null) - || null; - const provider = rawProvider === "auto" - ? preset?.resolved_provider - || (!scopedPreset ? settings?.agent.resolved_provider : null) - || null - : rawProvider || inferProviderFromModelName(model); - const providerRow = provider - ? settings?.providers.find((item) => item.name === provider) - : null; - const needsSetup = Boolean( - settings && (!model || !provider || !providerRow || !providerRow.configured), - ); - return { - label, - model: toModelBadgeLabel(model), - provider, - providerLabel: provider ? providerDisplayLabel(settings?.providers ?? [], provider) : null, - needsSetup, - }; -} - -function modelPresetOptionsFromSettings( - settings: SettingsPayload | null, -): ModelPresetOption[] { - if (!settings) return []; - const order = new Map( - (settings.model_call_order ?? []).map((name, index) => [name.trim(), index]), - ); - return settings.model_presets - .filter((preset) => !preset.is_default && preset.name.trim()) - .sort((a, b) => ( - (order.get(a.name.trim()) ?? Number.POSITIVE_INFINITY) - - (order.get(b.name.trim()) ?? Number.POSITIVE_INFINITY) - )) - .map((preset) => { - const name = preset.name.trim(); - return { - name, - model: preset.model, - provider: preset.resolved_provider || preset.provider, - }; - }); -} - const HERO_GREETING_KEYS = [ "thread.empty.greetings.workOn", "thread.empty.greetings.start", @@ -698,6 +609,8 @@ export function ThreadShell({ onTemporaryChatEnabledChange, onToggleSidebar, onCreateChat, + pendingFirstMessage = null, + onPendingFirstMessageConsumed, onForkChat, onTurnEnd, theme = "light", @@ -789,6 +702,7 @@ export function ThreadShell({ const filePreviewCloseTimerRef = useRef(null); const pendingFirstRef = useRef(null); const [pendingFirstTargetChatId, setPendingFirstTargetChatId] = useState(null); + const consumedPendingFirstMessageIdRef = useRef(null); const viewportRef = useRef(null); const activeViewportTurnByChatIdRef = useRef>(new Map()); const knownTemporaryChatIdsRef = useRef(new Set()); @@ -1442,6 +1356,31 @@ export function ThreadShell({ setBooting(false); }, [chatId, pendingFirstTargetChatId, send]); + useEffect(() => { + if ( + !chatId + || pendingFirstMessage?.chatId !== chatId + || consumedPendingFirstMessageIdRef.current === pendingFirstMessage.id + ) return; + consumedPendingFirstMessageIdRef.current = pendingFirstMessage.id; + const submitted = send( + pendingFirstMessage.content, + pendingFirstMessage.images, + withWorkspaceScope(pendingFirstMessage.options), + ); + if (submitted && !submitted.sideChannel) { + activeViewportTurnByChatIdRef.current.set(chatId, submitted.turnId); + setSubmittedViewportTurnId(submitted.turnId); + } + onPendingFirstMessageConsumed?.(pendingFirstMessage.id); + }, [ + chatId, + onPendingFirstMessageConsumed, + pendingFirstMessage, + send, + withWorkspaceScope, + ]); + useEffect(() => { let cancelled = false; (async () => { @@ -1721,7 +1660,7 @@ export function ThreadShell({
    ); const sessionInfoAction = historyKey ? ( - + ) : undefined; const promptNavigatorAction = historyKey ? ( preset.name === scopedPreset) ?? null; + } + const configured = settings.agent.model_preset || "default"; + return ( + presets.find((preset) => preset.name === configured) + ?? presets.find((preset) => preset.active) + ?? null + ); +} + +export function toModelBadgeInfo( + modelName: string | null, + settings: SettingsPayload | null, + modelPreset: string | null = null, +): ModelBadgeInfo { + const scopedPreset = modelPreset?.trim() || null; + const preset = modelPresetForBadge(settings, scopedPreset); + const model = scopedPreset + ? preset?.model || null + : settings?.agent.model || modelName || null; + const label = preset + ? preset.is_default + ? preset.label?.trim() || "Default" + : preset.name.trim() + : scopedPreset || compactModelName(model); + const rawProvider = preset?.provider + || (!scopedPreset ? settings?.agent.provider : null) + || null; + const provider = rawProvider === "auto" + ? preset?.resolved_provider + || (!scopedPreset ? settings?.agent.resolved_provider : null) + || null + : rawProvider || inferProviderFromModelName(model); + const providerRow = provider + ? settings?.providers?.find((item) => item.name === provider) + : null; + const needsSetup = Boolean( + settings && (!model || !provider || !providerRow || !providerRow.configured), + ); + return { + label, + model: compactModelName(model), + provider, + providerLabel: provider ? providerDisplayLabel(settings?.providers ?? [], provider) : null, + needsSetup, + }; +} + +export function modelPresetOptionsFromSettings( + settings: SettingsPayload | null, +): ModelPresetOption[] { + if (!settings) return []; + const order = new Map( + (settings.model_call_order ?? []).map((name, index) => [name.trim(), index]), + ); + return (settings.model_presets ?? []) + .filter((preset) => !preset.is_default && preset.name.trim()) + .sort((a, b) => ( + (order.get(a.name.trim()) ?? Number.POSITIVE_INFINITY) + - (order.get(b.name.trim()) ?? Number.POSITIVE_INFINITY) + )) + .map((preset) => { + const name = preset.name.trim(); + return { + name, + model: preset.model, + provider: preset.resolved_provider || preset.provider, + }; + }); +} diff --git a/webui/src/globals.css b/webui/src/globals.css index 491ab79a6..3830a6291 100644 --- a/webui/src/globals.css +++ b/webui/src/globals.css @@ -1021,10 +1021,57 @@ --settings-margin: 0.75rem; max-inline-size: calc(var(--content-column-width) + 2 * var(--settings-margin)); } + .settings-grid.settings-feature-page.settings-automations-grid { + max-inline-size: calc(60rem + 2 * var(--settings-margin)); + } /* Stack a task's status below its title when the content column is narrow. */ .automations-page { container: automations / inline-size; } + .automation-create-composer .thread-composer-surface { + max-inline-size: none; + } + .automation-meta-row { + display: grid; + grid-template-columns: 1rem minmax(0, 1fr) auto; + column-gap: 0.5rem; + padding-inline: 1rem; + } + @media (min-width: 640px) { + .automation-meta-row { + padding-inline: 1.5rem; + } + } + .automation-calendar-grid { display: none; } + .automation-calendar-agenda { display: block; } + @container automations (min-width: 44rem) { + .automation-calendar-grid { display: block; } + .automation-calendar-agenda { display: none; } + .automation-calendar-weekdays { + display: grid; + grid-template-columns: repeat(7, minmax(0, 1fr)); + border-block-end: 1px solid hsl(var(--border) / 0.6); + } + .automation-calendar-weekdays > div { + padding: 8px 10px; + color: hsl(var(--muted-foreground)); + font-size: 10px; + line-height: 16px; + text-align: end; + } + .automation-calendar-month { + display: grid; + grid-template-columns: repeat(7, minmax(0, 1fr)); + } + .automation-calendar-day { + min-block-size: 112px; + min-inline-size: 0; + border-inline-end: 1px solid hsl(var(--border) / 0.55); + border-block-end: 1px solid hsl(var(--border) / 0.55); + } + .automation-calendar-day:nth-child(7n) { border-inline-end: 0; } + .automation-calendar-day:nth-last-child(-n + 7) { border-block-end: 0; } + } .automation-task-state { grid-column: 1; grid-row: 2; diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json index 354d8cc28..78a3c3cb2 100644 --- a/webui/src/i18n/locales/en/common.json +++ b/webui/src/i18n/locales/en/common.json @@ -1089,6 +1089,23 @@ }, "automations": { "viewOptions": "Search and filter", + "create": "Create automation", + "createPrompt": "Describe an automation, for example: summarize project updates every weekday at 9:00", + "createInput": "Describe an automation", + "createRequest": "Create an automation for this request:\n\n{{request}}", + "errors": { + "legacyMissingDestination": "This older automation is missing its delivery destination. Recreate it from the linked chat to continue." + }, + "calendar": { + "previousMonth": "Previous month", + "nextMonth": "Next month", + "today": "Today", + "planned": "Planned", + "recorded": "Recorded", + "more": "+{{count}} more", + "noEntries": "No runs in this month.", + "outsideMonth": "Without a date in this month" + }, "yourTasks": "Your automations", "systemTasks": "System tasks", "instructions": "Instructions", @@ -1163,8 +1180,8 @@ "at": "At {{time}}", "every": "Every {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", - "withTz": "{{summary}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", + "withTz": "{{summary}} ({{tz}})", "dailyAt": "Daily at {{time}}", "weekdaysAt": "Weekdays at {{time}}", "hourlyAt": "Hourly at :{{minute}}", @@ -1394,7 +1411,7 @@ "at": "{{time}}", "every": "Every {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", "local": "Local trigger", "unknown": "Custom schedule" }, @@ -1497,12 +1514,13 @@ "loading": "Loading automations...", "loadFailed": "Could not load automations.", "empty": "No automations in this session yet.", + "openCalendar": "View all in calendar", "disabled": "Off", "schedule": { "at": "{{time}}", "every": "Every {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", "local": "Local trigger", "unknown": "Custom schedule" }, diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json index 206c91296..66a812119 100644 --- a/webui/src/i18n/locales/es/common.json +++ b/webui/src/i18n/locales/es/common.json @@ -890,6 +890,23 @@ }, "automations": { "viewOptions": "Buscar y filtrar", + "create": "Crear automatización", + "createPrompt": "Describe una automatización, por ejemplo: resume las novedades del proyecto cada día laborable a las 9:00", + "createInput": "Describe una automatización", + "createRequest": "Crea una automatización para esta solicitud:\n\n{{request}}", + "errors": { + "legacyMissingDestination": "Esta automatización antigua no tiene un destino de entrega. Vuelve a crearla desde el chat vinculado para continuar." + }, + "calendar": { + "previousMonth": "Mes anterior", + "nextMonth": "Mes siguiente", + "today": "Hoy", + "planned": "Planificado", + "recorded": "Registrado", + "more": "+{{count}} más", + "noEntries": "No hay ejecuciones este mes.", + "outsideMonth": "Sin fecha en este mes" + }, "yourTasks": "Tus automatizaciones", "systemTasks": "Tareas del sistema", "instructions": "Instrucciones", @@ -964,8 +981,8 @@ "at": "A las {{time}}", "every": "Cada {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", - "withTz": "{{summary}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", + "withTz": "{{summary}} ({{tz}})", "dailyAt": "Todos los días a las {{time}}", "weekdaysAt": "De lunes a viernes a las {{time}}", "hourlyAt": "Cada hora, en el minuto {{minute}}", @@ -1195,7 +1212,7 @@ "at": "{{time}}", "every": "Cada {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", "local": "Activador local", "unknown": "Programación personalizada" }, @@ -1298,12 +1315,13 @@ "loading": "Cargando automatizaciones...", "loadFailed": "No se pudieron cargar las automatizaciones.", "empty": "Esta sesión aún no tiene automatizaciones.", + "openCalendar": "Ver todo en el calendario", "disabled": "Desactivado", "schedule": { "at": "A las {{time}}", "every": "Cada {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", "local": "Activador local", "unknown": "Programación personalizada" }, diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json index 37307bf5f..3e046c5bb 100644 --- a/webui/src/i18n/locales/fr/common.json +++ b/webui/src/i18n/locales/fr/common.json @@ -889,6 +889,23 @@ }, "automations": { "viewOptions": "Rechercher et filtrer", + "create": "Créer une automatisation", + "createPrompt": "Décrivez une automatisation, par exemple : résumer l’avancement du projet chaque jour ouvré à 9 h", + "createInput": "Décrire une automatisation", + "createRequest": "Crée une automatisation pour cette demande :\n\n{{request}}", + "errors": { + "legacyMissingDestination": "Cette ancienne automatisation n’a plus de destination. Recréez-la depuis la discussion liée pour continuer." + }, + "calendar": { + "previousMonth": "Mois précédent", + "nextMonth": "Mois suivant", + "today": "Aujourd’hui", + "planned": "Planifié", + "recorded": "Enregistré", + "more": "+{{count}} de plus", + "noEntries": "Aucune exécution ce mois-ci.", + "outsideMonth": "Sans date ce mois-ci" + }, "yourTasks": "Vos automatisations", "systemTasks": "Tâches système", "instructions": "Instructions", @@ -963,8 +980,8 @@ "at": "À {{time}}", "every": "Toutes les {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", - "withTz": "{{summary}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", + "withTz": "{{summary}} ({{tz}})", "dailyAt": "Chaque jour à {{time}}", "weekdaysAt": "Du lundi au vendredi à {{time}}", "hourlyAt": "Toutes les heures à :{{minute}}", @@ -1194,7 +1211,7 @@ "at": "{{time}}", "every": "Tous les {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", "local": "Déclencheur local", "unknown": "Planification personnalisée" }, @@ -1297,12 +1314,13 @@ "loading": "Chargement des automatisations...", "loadFailed": "Impossible de charger les automatisations.", "empty": "Aucune automatisation dans cette session pour le moment.", + "openCalendar": "Tout voir dans le calendrier", "disabled": "Désactivé", "schedule": { "at": "À {{time}}", "every": "Toutes les {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", "local": "Déclencheur local", "unknown": "Planification personnalisée" }, diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json index 530db94cd..168813123 100644 --- a/webui/src/i18n/locales/id/common.json +++ b/webui/src/i18n/locales/id/common.json @@ -889,6 +889,23 @@ }, "automations": { "viewOptions": "Cari dan filter", + "create": "Buat otomatisasi", + "createPrompt": "Jelaskan otomatisasi, misalnya: rangkum perkembangan proyek setiap hari kerja pukul 09.00", + "createInput": "Jelaskan otomatisasi", + "createRequest": "Buat otomatisasi untuk permintaan ini:\n\n{{request}}", + "errors": { + "legacyMissingDestination": "Otomatisasi lama ini tidak memiliki tujuan pengiriman. Buat ulang dari chat terkait untuk melanjutkan." + }, + "calendar": { + "previousMonth": "Bulan sebelumnya", + "nextMonth": "Bulan berikutnya", + "today": "Hari ini", + "planned": "Terjadwal", + "recorded": "Tercatat", + "more": "+{{count}} lainnya", + "noEntries": "Tidak ada eksekusi bulan ini.", + "outsideMonth": "Tanpa tanggal di bulan ini" + }, "yourTasks": "Otomatisasi Anda", "systemTasks": "Tugas sistem", "instructions": "Instruksi", @@ -963,8 +980,8 @@ "at": "Pada {{time}}", "every": "Setiap {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", - "withTz": "{{summary}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", + "withTz": "{{summary}} ({{tz}})", "dailyAt": "Setiap hari pukul {{time}}", "weekdaysAt": "Senin–Jumat pukul {{time}}", "hourlyAt": "Setiap jam pada menit {{minute}}", @@ -1194,7 +1211,7 @@ "at": "{{time}}", "every": "Setiap {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", "local": "Pemicu lokal", "unknown": "Jadwal khusus" }, @@ -1297,12 +1314,13 @@ "loading": "Memuat otomasi...", "loadFailed": "Tidak dapat memuat otomasi.", "empty": "Belum ada otomasi dalam sesi ini.", + "openCalendar": "Lihat semua di kalender", "disabled": "Mati", "schedule": { "at": "Pada {{time}}", "every": "Setiap {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", "local": "Pemicu lokal", "unknown": "Jadwal khusus" }, diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json index 581225272..aba5e5a80 100644 --- a/webui/src/i18n/locales/ja/common.json +++ b/webui/src/i18n/locales/ja/common.json @@ -889,6 +889,23 @@ }, "automations": { "viewOptions": "検索と絞り込み", + "create": "自動タスクを作成", + "createPrompt": "作成する自動タスクを説明してください。例:平日の9時にプロジェクトの進捗を要約", + "createInput": "自動タスクを説明", + "createRequest": "次の依頼に対する自動タスクを作成してください:\n\n{{request}}", + "errors": { + "legacyMissingDestination": "この旧形式の自動タスクには送信先がありません。続行するには、関連チャットから作り直してください。" + }, + "calendar": { + "previousMonth": "前の月", + "nextMonth": "次の月", + "today": "今日", + "planned": "予定", + "recorded": "実績", + "more": "ほか{{count}}件", + "noEntries": "今月の実行はありません。", + "outsideMonth": "今月の日付なし" + }, "yourTasks": "自分の自動化", "systemTasks": "システムタスク", "instructions": "指示", @@ -963,8 +980,8 @@ "at": "{{time}}", "every": "{{duration}} ごと", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", - "withTz": "{{summary}} · {{tz}}", + "cronWithTz": "Cron {{expr}}({{tz}})", + "withTz": "{{summary}}({{tz}})", "dailyAt": "毎日 {{time}}", "weekdaysAt": "月曜日〜金曜日 {{time}}", "hourlyAt": "毎時 {{minute}} 分", @@ -1194,7 +1211,7 @@ "at": "{{time}}", "every": "{{duration}} ごと", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}}({{tz}})", "local": "ローカルトリガー", "unknown": "カスタムスケジュール" }, @@ -1297,12 +1314,13 @@ "loading": "自動タスクを読み込み中...", "loadFailed": "自動タスクを読み込めませんでした。", "empty": "このセッションにはまだ自動タスクがありません。", + "openCalendar": "カレンダーですべて表示", "disabled": "オフ", "schedule": { "at": "{{time}}", "every": "{{duration}}ごと", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}}({{tz}})", "local": "ローカルトリガー", "unknown": "カスタムスケジュール" }, diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json index 8f8d7d566..e512e3153 100644 --- a/webui/src/i18n/locales/ko/common.json +++ b/webui/src/i18n/locales/ko/common.json @@ -889,6 +889,23 @@ }, "automations": { "viewOptions": "검색 및 필터", + "create": "자동화 만들기", + "createPrompt": "만들 자동화를 설명하세요. 예: 평일 오전 9시에 프로젝트 진행 상황 요약", + "createInput": "자동화 설명", + "createRequest": "다음 요청에 맞는 자동화를 만들어 주세요:\n\n{{request}}", + "errors": { + "legacyMissingDestination": "이전 형식의 자동화에 전송 대상이 없습니다. 계속하려면 연결된 채팅에서 다시 만들어 주세요." + }, + "calendar": { + "previousMonth": "이전 달", + "nextMonth": "다음 달", + "today": "오늘", + "planned": "예정", + "recorded": "기록", + "more": "+{{count}}개 더", + "noEntries": "이번 달 실행 기록이 없습니다.", + "outsideMonth": "이번 달 날짜 없음" + }, "yourTasks": "내 자동화", "systemTasks": "시스템 작업", "instructions": "지침", @@ -963,8 +980,8 @@ "at": "{{time}}", "every": "{{duration}}마다", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", - "withTz": "{{summary}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", + "withTz": "{{summary}} ({{tz}})", "dailyAt": "매일 {{time}}", "weekdaysAt": "월요일~금요일 {{time}}", "hourlyAt": "매시 {{minute}}분", @@ -1194,7 +1211,7 @@ "at": "{{time}}", "every": "{{duration}}마다", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", "local": "로컬 트리거", "unknown": "사용자 지정 일정" }, @@ -1297,12 +1314,13 @@ "loading": "자동화를 불러오는 중...", "loadFailed": "자동화를 불러오지 못했습니다.", "empty": "이 세션에는 아직 자동화가 없습니다.", + "openCalendar": "캘린더에서 모두 보기", "disabled": "꺼짐", "schedule": { "at": "{{time}}", "every": "{{duration}}마다", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", "local": "로컬 트리거", "unknown": "사용자 지정 일정" }, diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json index d6417d861..f8e6c28a9 100644 --- a/webui/src/i18n/locales/pt-BR/common.json +++ b/webui/src/i18n/locales/pt-BR/common.json @@ -903,6 +903,23 @@ }, "automations": { "viewOptions": "Buscar e filtrar", + "create": "Criar automação", + "createPrompt": "Descreva uma automação, por exemplo: resumir o andamento do projeto todo dia útil às 9:00", + "createInput": "Descreva uma automação", + "createRequest": "Crie uma automação para esta solicitação:\n\n{{request}}", + "errors": { + "legacyMissingDestination": "Esta automação antiga não tem um destino de entrega. Recrie-a na conversa vinculada para continuar." + }, + "calendar": { + "previousMonth": "Mês anterior", + "nextMonth": "Próximo mês", + "today": "Hoje", + "planned": "Planejado", + "recorded": "Registrado", + "more": "+{{count}} mais", + "noEntries": "Nenhuma execução neste mês.", + "outsideMonth": "Sem data neste mês" + }, "yourTasks": "Suas automações", "systemTasks": "Tarefas do sistema", "instructions": "Instruções", @@ -977,8 +994,8 @@ "at": "Às {{time}}", "every": "A cada {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", - "withTz": "{{summary}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", + "withTz": "{{summary}} ({{tz}})", "dailyAt": "Diariamente às {{time}}", "weekdaysAt": "De segunda a sexta às {{time}}", "hourlyAt": "A cada hora, no minuto {{minute}}", @@ -1208,7 +1225,7 @@ "at": "{{time}}", "every": "A cada {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", "local": "Gatilho local", "unknown": "Agendamento personalizado" }, @@ -1311,12 +1328,13 @@ "loading": "Carregando automações...", "loadFailed": "Não foi possível carregar as automações.", "empty": "Ainda não há automações nesta sessão.", + "openCalendar": "Ver tudo no calendário", "disabled": "Desligado", "schedule": { "at": "{{time}}", "every": "A cada {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", "local": "Gatilho local", "unknown": "Agendamento personalizado" }, diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json index c86808b0b..291bfdb9f 100644 --- a/webui/src/i18n/locales/vi/common.json +++ b/webui/src/i18n/locales/vi/common.json @@ -889,6 +889,23 @@ }, "automations": { "viewOptions": "Tìm kiếm và lọc", + "create": "Tạo tự động hóa", + "createPrompt": "Mô tả tác vụ tự động, ví dụ: tóm tắt tiến độ dự án lúc 9:00 mỗi ngày làm việc", + "createInput": "Mô tả tác vụ tự động", + "createRequest": "Tạo một tác vụ tự động cho yêu cầu này:\n\n{{request}}", + "errors": { + "legacyMissingDestination": "Tác vụ tự động cũ này thiếu nơi nhận. Hãy tạo lại từ cuộc trò chuyện liên kết để tiếp tục." + }, + "calendar": { + "previousMonth": "Tháng trước", + "nextMonth": "Tháng sau", + "today": "Hôm nay", + "planned": "Đã lên lịch", + "recorded": "Đã ghi nhận", + "more": "+{{count}} mục khác", + "noEntries": "Không có lần chạy nào trong tháng này.", + "outsideMonth": "Không có ngày trong tháng này" + }, "yourTasks": "Tác vụ tự động của bạn", "systemTasks": "Tác vụ hệ thống", "instructions": "Chỉ dẫn", @@ -963,8 +980,8 @@ "at": "Vào {{time}}", "every": "Mỗi {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", - "withTz": "{{summary}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", + "withTz": "{{summary}} ({{tz}})", "dailyAt": "Hằng ngày lúc {{time}}", "weekdaysAt": "Thứ Hai đến thứ Sáu lúc {{time}}", "hourlyAt": "Vào phút {{minute}} mỗi giờ", @@ -1194,7 +1211,7 @@ "at": "{{time}}", "every": "Mỗi {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", "local": "Trình kích hoạt cục bộ", "unknown": "Lịch tùy chỉnh" }, @@ -1297,12 +1314,13 @@ "loading": "Đang tải tự động hóa...", "loadFailed": "Không thể tải tự động hóa.", "empty": "Phiên này chưa có tự động hóa.", + "openCalendar": "Xem tất cả trong lịch", "disabled": "Tắt", "schedule": { "at": "Lúc {{time}}", "every": "Mỗi {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}} ({{tz}})", "local": "Trình kích hoạt cục bộ", "unknown": "Lịch tùy chỉnh" }, diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json index 2068a3a0a..84dc19c4f 100644 --- a/webui/src/i18n/locales/zh-CN/common.json +++ b/webui/src/i18n/locales/zh-CN/common.json @@ -1089,6 +1089,23 @@ }, "automations": { "viewOptions": "搜索与筛选", + "create": "创建自动任务", + "createPrompt": "描述要创建的自动任务,例如:每个工作日 9:00 汇总项目进展", + "createInput": "描述一个自动任务", + "createRequest": "请为以下需求创建自动任务:\n\n{{request}}", + "errors": { + "legacyMissingDestination": "这个旧版自动任务缺少发送目标,无法继续运行。请从关联会话中重新创建该任务。" + }, + "calendar": { + "previousMonth": "上个月", + "nextMonth": "下个月", + "today": "今天", + "planned": "计划运行", + "recorded": "实际记录", + "more": "还有 {{count}} 项", + "noEntries": "本月没有运行记录。", + "outsideMonth": "本月没有日期的任务" + }, "yourTasks": "你的自动任务", "systemTasks": "系统任务", "instructions": "任务指令", @@ -1163,8 +1180,8 @@ "at": "在 {{time}}", "every": "每 {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", - "withTz": "{{summary}} · {{tz}}", + "cronWithTz": "Cron {{expr}}({{tz}})", + "withTz": "{{summary}}({{tz}})", "dailyAt": "每天 {{time}}", "weekdaysAt": "周一至周五 {{time}}", "hourlyAt": "每小时第 {{minute}} 分钟", @@ -1394,7 +1411,7 @@ "at": "{{time}}", "every": "每 {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}}({{tz}})", "local": "本地触发器", "unknown": "自定义计划" }, @@ -1497,12 +1514,13 @@ "loading": "正在加载自动任务...", "loadFailed": "无法加载自动任务。", "empty": "这个会话暂时没有自动任务。", + "openCalendar": "在日历中查看全部", "disabled": "已关闭", "schedule": { "at": "{{time}}", "every": "每 {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}}({{tz}})", "local": "本地触发器", "unknown": "自定义计划" }, diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json index da17454b3..d4bb451e3 100644 --- a/webui/src/i18n/locales/zh-TW/common.json +++ b/webui/src/i18n/locales/zh-TW/common.json @@ -889,6 +889,23 @@ }, "automations": { "viewOptions": "搜尋與篩選", + "create": "建立自動任務", + "createPrompt": "描述要建立的自動任務,例如:每個工作日 9:00 彙整專案進度", + "createInput": "描述自動任務", + "createRequest": "請為以下需求建立自動任務:\n\n{{request}}", + "errors": { + "legacyMissingDestination": "這個舊版自動任務缺少傳送目標,無法繼續執行。請從關聯對話中重新建立該任務。" + }, + "calendar": { + "previousMonth": "上個月", + "nextMonth": "下個月", + "today": "今天", + "planned": "預定執行", + "recorded": "實際記錄", + "more": "另有 {{count}} 項", + "noEntries": "本月沒有執行記錄。", + "outsideMonth": "本月沒有日期的任務" + }, "yourTasks": "你的自動任務", "systemTasks": "系統任務", "instructions": "任務指示", @@ -963,8 +980,8 @@ "at": "於 {{time}}", "every": "每 {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", - "withTz": "{{summary}} · {{tz}}", + "cronWithTz": "Cron {{expr}}({{tz}})", + "withTz": "{{summary}}({{tz}})", "dailyAt": "每天 {{time}}", "weekdaysAt": "每週一至週五 {{time}}", "hourlyAt": "每小時第 {{minute}} 分鐘", @@ -1194,7 +1211,7 @@ "at": "{{time}}", "every": "每 {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}}({{tz}})", "local": "本機觸發器", "unknown": "自訂排程" }, @@ -1297,12 +1314,13 @@ "loading": "正在載入自動任務…", "loadFailed": "無法載入自動任務。", "empty": "這個對話目前沒有自動任務。", + "openCalendar": "在日曆中查看全部", "disabled": "已關閉", "schedule": { "at": "{{time}}", "every": "每 {{duration}}", "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} · {{tz}}", + "cronWithTz": "Cron {{expr}}({{tz}})", "local": "本機觸發器", "unknown": "自訂排程" }, diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsx index 1e2253b70..30a234b7c 100644 --- a/webui/src/tests/app-layout.test.tsx +++ b/webui/src/tests/app-layout.test.tsx @@ -1446,9 +1446,10 @@ describe("App layout", () => { expect(automationsMain).not.toBeNull(); expect(within(automationsMain as HTMLElement).queryByText("Settings")).not.toBeInTheDocument(); expect(screen.getAllByText("Daily repo check").length).toBeGreaterThanOrEqual(1); - expect(screen.getAllByText("Check the repo status").length).toBeGreaterThanOrEqual(1); + expect(screen.queryByText("Check the repo status")).not.toBeInTheDocument(); expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); fireEvent.click(screen.getByRole("button", { name: /Daily repo check/ })); + expect(within(screen.getByRole("dialog", { name: "Daily repo check" })).getByText("Check the repo status")).toBeVisible(); expect(screen.getAllByText("Release prep").length).toBeGreaterThanOrEqual(1); fireEvent.click(screen.getByRole("button", { name: "Done", exact: true })); expect(screen.getByText("WeChat quiz")).toBeInTheDocument(); @@ -1733,9 +1734,11 @@ describe("App layout", () => { expect(within(automationsMain as HTMLElement).queryByText("设置")).not.toBeInTheDocument(); expect(screen.queryByText("任务队列")).not.toBeInTheDocument(); expect(screen.getAllByText("每日检查").length).toBeGreaterThanOrEqual(1); - expect(screen.getAllByText("检查仓库状态").length).toBeGreaterThanOrEqual(1); + expect(screen.queryByText("检查仓库状态")).not.toBeInTheDocument(); fireEvent.click(screen.getByRole("button", { name: /每日检查/ })); - expect(within(screen.getByRole("dialog", { name: "每日检查" })).getByText(/每 1天/)).toBeInTheDocument(); + const detail = within(screen.getByRole("dialog", { name: "每日检查" })); + expect(detail.getByText("检查仓库状态")).toBeVisible(); + expect(detail.getByText(/每 1天/)).toBeInTheDocument(); expect(screen.queryByText("最近健康状态")).not.toBeInTheDocument(); expect(screen.queryByText("近期无问题")).not.toBeInTheDocument(); expect(screen.queryByText("Workspace automations")).not.toBeInTheDocument(); diff --git a/webui/src/tests/automations-settings.test.tsx b/webui/src/tests/automations-settings.test.tsx index e4ed99fbc..461e3800b 100644 --- a/webui/src/tests/automations-settings.test.tsx +++ b/webui/src/tests/automations-settings.test.tsx @@ -1,11 +1,12 @@ import { useState } from "react"; -import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest"; import { AutomationDeleteDialog, AutomationEditDialog, AutomationsSettings } from "@/components/settings/system/AutomationsSettings"; import type { AutomationFilter, AutomationSort } from "@/components/settings/system/AutomationsSettings"; -import type { SessionAutomationJob } from "@/lib/types"; +import i18n from "@/i18n"; +import type { SessionAutomationJob, SettingsPayload } from "@/lib/types"; const now = Date.now(); const task: SessionAutomationJob = { @@ -20,6 +21,20 @@ const systemTask: SessionAutomationJob = { ...task, id: "heartbeat", name: "heartbeat", protected: true, origin: null, payload: { message: "" }, }; +const modelSettings = { + agent: { + model: "openai/gpt-5-mini", + provider: "openai", + resolved_provider: "openai", + model_preset: "fast", + }, + model_presets: [ + { name: "fast", model: "openai/gpt-5-mini", provider: "openai", active: true, is_default: false }, + { name: "deep", model: "openai/gpt-5", provider: "openai", active: false, is_default: false }, + ], + model_call_order: ["fast", "deep"], + providers: [{ name: "openai", label: "OpenAI", configured: true }], +} as SettingsPayload; type Props = Partial>; const SYSTEM_TASKS_OPEN_STORAGE_KEY = "nanobot-webui.automation-system-tasks-open"; @@ -41,6 +56,7 @@ beforeEach(() => { afterEach(() => { cleanup(); + vi.useRealTimers(); vi.restoreAllMocks(); window.localStorage.removeItem(SYSTEM_TASKS_OPEN_STORAGE_KEY); }); @@ -49,7 +65,8 @@ describe("Automation task list and detail sheet", () => { it("avoids redundant headings and decorative uppercase group labels", () => { render(); expect(screen.queryByRole("heading", { name: "Your automations" })).not.toBeInTheDocument(); - expect(screen.getByRole("list", { name: "Your automations" })).toBeVisible(); + const month = new Intl.DateTimeFormat("en", { month: "long", year: "numeric" }).format(new Date()); + expect(screen.getByLabelText(month)).toBeVisible(); const systemToggle = screen.getByRole("button", { name: "System tasks 1" }); expect(systemToggle).toHaveClass("text-[13px]", "font-medium"); expect(systemToggle).not.toHaveClass("uppercase", "tracking-[0.08em]"); @@ -165,10 +182,99 @@ describe("Automation task list and detail sheet", () => { expect(row).toHaveFocus(); }); + it("opens both planned and recorded calendar blocks in details before linking to chat", async () => { + const user = userEvent.setup(); + const jobWithHistory: SessionAutomationJob = { + ...task, + state: { + ...task.state, + run_history: [{ run_at_ms: now - 60_000, status: "ok", duration_ms: 120_000 }], + }, + }; + render(); + + const planned = screen.getByRole("button", { name: /PR watch.*Planned/ }); + const recorded = screen.getByRole("button", { name: /PR watch.*Recorded/ }); + expect(planned).toHaveAttribute("aria-haspopup", "dialog"); + expect(recorded).toHaveAttribute("aria-haspopup", "dialog"); + expect(screen.queryByRole("link", { name: /PR watch/ })).not.toBeInTheDocument(); + + await user.click(recorded); + const dialog = screen.getByRole("dialog", { name: "PR watch" }); + expect(within(dialog).getByRole("link", { name: "Open a chat" })).toHaveAttribute( + "href", "#/chat/websocket%3Ademo", + ); + }); + + it("starts an automation conversation from the inline composer without opening a dialog", async () => { + const user = userEvent.setup(); + const onStartChat = vi.fn().mockResolvedValue(true); + render(); + + const composer = screen.getByRole("textbox", { name: "Describe an automation" }); + await user.type(composer, "Every weekday at 9, summarize my open pull requests"); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + await user.click(screen.getByRole("button", { name: "Send message" })); + + expect(onStartChat).toHaveBeenCalledWith( + "Create an automation for this request:\n\nEvery weekday at 9, summarize my open pull requests", + undefined, + undefined, + "fast", + ); + await waitFor(() => expect(composer).toHaveValue("")); + }); + + it("uses the shared click picker and creates the chat with the selected model preset", async () => { + const user = userEvent.setup(); + const onStartChat = vi.fn().mockResolvedValue(true); + render(); + + await user.click(screen.getByRole("button", { name: "fast" })); + const picker = screen.getByRole("dialog", { name: "Switch model for this chat" }); + await user.click(within(picker).getByRole("option", { name: "deep" })); + expect(screen.getByRole("button", { name: "deep" })).toBeVisible(); + + const composer = screen.getByRole("textbox", { name: "Describe an automation" }); + await user.type(composer, "Run a deep weekly review"); + await user.click(screen.getByRole("button", { name: "Send message" })); + expect(onStartChat).toHaveBeenCalledWith( + "Create an automation for this request:\n\nRun a deep weekly review", + undefined, + undefined, + "deep", + ); + }); + + it("keeps the main chat model chip's long-press drag behavior", () => { + vi.useFakeTimers(); + const onStartChat = vi.fn().mockResolvedValue(true); + render(); + + const badge = screen.getByRole("button", { name: "fast" }); + fireEvent.pointerDown(badge, { pointerId: 1, pointerType: "touch", clientY: 100 }); + act(() => vi.advanceTimersByTime(400)); + expect(screen.getByTestId("composer-model-pill-viewport")).toBeInTheDocument(); + fireEvent.pointerMove(badge, { pointerId: 1, pointerType: "touch", clientY: 56 }); + fireEvent.pointerUp(badge, { pointerId: 1, pointerType: "touch", clientY: 56 }); + expect(screen.getByRole("button", { name: "deep" })).toBeVisible(); + }); + + it("uses an automation-specific placeholder", () => { + render( {}} settingsSnapshot={modelSettings} />); + expect(screen.getByRole("textbox", { name: "Describe an automation" })).toHaveAttribute( + "placeholder", + "Describe an automation, for example: summarize project updates every weekday at 9:00", + ); + }); + it("keeps a text-only empty state when only system tasks exist", () => { render(); expect(screen.getByText("No automations yet.")).toBeVisible(); - expect(screen.getByText("Tell nanobot in a chat what you'd like it to do on a schedule.")).toBeVisible(); expect(screen.queryByRole("button", { name: "Create in chat" })).not.toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Open a chat" })).not.toBeInTheDocument(); expect(screen.getByRole("region", { name: "Search and filter" })).toBeVisible(); @@ -183,7 +289,7 @@ describe("Automation task list and detail sheet", () => { it("distinguishes a finished one-time task from a task with no scheduled run", () => { render(); - expect(screen.getByRole("button", { name: /PR watch/ })).toHaveTextContent("Completed"); + expect(screen.getByRole("button", { name: /PR watch.*Completed/ })).toBeVisible(); expect(screen.queryByText("No next run")).not.toBeInTheDocument(); }); @@ -256,25 +362,25 @@ describe("Automation task list and detail sheet", () => { } }); - it("uses channel search controls and the skills catalog surface for both task groups", async () => { + it("uses the existing settings surfaces for the calendar and system task group", async () => { const user = userEvent.setup(); render(); expect(screen.getByRole("heading", { name: "Automations" })).toHaveClass("font-normal", "text-[24px]"); - const personalRow = screen.getByRole("button", { name: /PR watch/ }); - expect(personalRow).toHaveClass("rounded-control", "px-2", "py-3", "settings-hover"); + const taskBlock = screen.getByRole("button", { name: /PR watch.*Planned/ }); + expect(taskBlock).toHaveAttribute("aria-haspopup", "dialog"); + expect(screen.queryByRole("button", { name: "Manage PR watch" })).not.toBeInTheDocument(); const list = screen.getByRole("list", { name: "System tasks" }); - const surface = personalRow.closest(".bg-settings-surface"); - expect(surface).toHaveClass("rounded-panel"); - expect(list.closest(".bg-settings-surface")).toBe(surface); + expect(taskBlock.closest("section")).toHaveClass("rounded-panel", "bg-[hsl(var(--settings-surface))]"); + expect(list.closest(".bg-settings-surface")).not.toBe(taskBlock.closest("section")); const search = screen.getByRole("textbox"); expect(search.closest(".rounded-panel")).toBeNull(); - expect(search).toHaveClass("h-12", "bg-settings-surface", "focus-visible:bg-background"); + expect(search).toHaveClass("h-10", "bg-settings-surface", "focus-visible:bg-background"); expect(screen.getByRole("button", { name: "All 1" }).parentElement).toHaveClass("segmented-control", "flex-wrap"); const heartbeat = within(list).getByRole("button", { name: /heartbeat/ }); - expect(heartbeat.className).toBe(personalRow.className); + expect(heartbeat).toHaveClass("rounded-control", "settings-hover"); expect(within(list).queryByText("System-managed automation")).not.toBeInTheDocument(); expect(within(list).getByText("Memory update failed")).toBeVisible(); expect(within(list).getByText("Needs attention")).toBeVisible(); @@ -285,6 +391,38 @@ describe("Automation task list and detail sheet", () => { await waitFor(() => expect(heartbeat).toHaveFocus()); }); + it("keeps separators inside the date grid and uses spacing for calendar metadata", () => { + const outsideTask: SessionAutomationJob = { + ...task, + id: "outside-month", + name: "Paused backlog review", + enabled: false, + state: {}, + }; + render(); + + const calendar = screen.getByRole("button", { name: /PR watch.*Planned/ }).closest("section")!; + expect(calendar.firstElementChild).not.toHaveClass("border-b"); + expect(calendar.querySelector(".automation-meta-row")).not.toHaveClass("border-t"); + const outside = within(calendar).getByText("Without a date in this month").closest("details")!; + expect(outside).not.toHaveClass("border-t"); + expect(outside.querySelector("ul")).not.toHaveClass("border-t"); + expect(calendar).not.toHaveTextContent("·"); + }); + + it("renders schedule metadata as separate fields without dot separators", () => { + const cronTask: SessionAutomationJob = { + ...task, + schedule: { kind: "cron", expr: "0 9 * * 1-5", tz: "Asia/Shanghai" }, + }; + render(); + fireEvent.click(screen.getByRole("button", { name: /PR watch/ })); + const dialog = screen.getByRole("dialog", { name: "PR watch" }); + expect(dialog).toHaveTextContent("Weekdays at 09:00"); + expect(dialog).toHaveTextContent("Asia/Shanghai"); + expect(dialog).not.toHaveTextContent("·"); + }); + it("keeps system tasks mounted for shared expand and collapse transitions without hidden tab stops", async () => { const user = userEvent.setup(); render(); @@ -349,8 +487,8 @@ describe("Automation task list and detail sheet", () => { await user.click(screen.getByRole("button", { name: "All 2" })); await user.click(screen.getByRole("button", { name: "Next run" })); await user.click(screen.getByRole("menuitem", { name: "Name" })); - const rows = within(screen.getByRole("list", { name: "Your automations" })).getAllByRole("button"); - expect(rows[0]).toHaveTextContent("PR watch"); + expect(screen.getByRole("button", { name: "Name", exact: true })).toBeVisible(); + expect(screen.getByRole("button", { name: /PR watch.*Planned/ })).toBeVisible(); }); it("uses live renamed chat titles in details and search without changing the bound task", async () => { @@ -433,7 +571,7 @@ describe("Automation task list and detail sheet", () => { await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); expect(screen.getByRole("heading", { name: "Automations" })).toHaveFocus(); expect(screen.getByText("No automations yet.")).toBeVisible(); - expect(screen.queryByRole("button")).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: /PR watch/ })).not.toBeInTheDocument(); }); it("uses chevrons only for disclosures, while task rows open dialogs", async () => { @@ -470,8 +608,7 @@ describe("Automation task list and detail sheet", () => { await waitFor(() => expect(edit).toHaveBeenCalledWith(task)); expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); await user.click(screen.getByRole("button", { name: /PR watch/ })); - await user.click(screen.getByRole("button", { name: "More actions" })); - await user.click(screen.getByRole("menuitem", { name: "Delete" })); + await user.click(screen.getByRole("button", { name: "Delete" })); await waitFor(() => expect(remove).toHaveBeenCalledWith(task)); expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); }); @@ -487,7 +624,7 @@ describe("Automation task list and detail sheet", () => { const getStyle = window.getComputedStyle.bind(window); vi.spyOn(window, "getComputedStyle").mockImplementation((node) => { const style = getStyle(node); - if (!["menu", "dialog"].includes(node.getAttribute("role") ?? "")) return style; + if (node.getAttribute("role") !== "dialog") return style; return new Proxy(style, { get(target, property) { if (property === "animationName") return node.getAttribute("data-state") === "closed" ? "exit" : "enter"; @@ -520,9 +657,8 @@ describe("Automation task list and detail sheet", () => { render(); await user.click(screen.getByRole("button", { name: /PR watch/ })); const detail = screen.getByRole("dialog", { name: "PR watch" }); - await user.click(screen.getByRole("button", { name: "More actions" })); expect(document.body.style.pointerEvents).toBe("none"); - await user.click(screen.getByRole("menuitem", { name: "Delete" })); + await user.click(screen.getByRole("button", { name: "Delete" })); expect(detail).toHaveAttribute("data-state", "closed"); finishExit(detail); const confirmation = await screen.findByRole("dialog", { name: "Delete automation" }); @@ -536,33 +672,55 @@ describe("Automation task list and detail sheet", () => { expect(screen.queryByRole("button", { name: /PR watch/ }) !== null).toBe(operation === "Cancel"); }); - it("returns keyboard focus to the task after cancelling or saving the real editor", async () => { + it("returns to the same detail after cancelling or closing the real editor", async () => { const user = userEvent.setup(); const save = vi.fn(); function EditorHarness() { const [editing, setEditing] = useState(null); + const [returning, setReturning] = useState(null); return <> - + setReturning(null)} + /> { if (!open) setEditing(null); }} + onCancel={setReturning} onSave={(job, values) => { save(job, values); setEditing(null); }} /> ; } render(); const row = screen.getByRole("button", { name: /PR watch/ }); - for (const operation of ["Cancel", "Save"]) { - await user.click(row); + for (const operation of ["Cancel", "Close"]) { + if (!screen.queryByRole("dialog", { name: "PR watch" })) await user.click(row); await user.click(screen.getByRole("button", { name: "Edit", exact: true })); const editor = await screen.findByRole("dialog", { name: "Edit automation" }); expect(screen.getAllByRole("dialog")).toHaveLength(1); - if (operation === "Save") { - await user.clear(within(editor).getByRole("textbox", { name: "Name", exact: true })); - await user.type(within(editor).getByRole("textbox", { name: "Name", exact: true }), "Updated watch"); - } await user.click(within(editor).getByRole("button", { name: operation, exact: true })); - await waitFor(() => expect(row).toHaveFocus()); + await waitFor(() => expect(screen.getByRole("dialog", { name: "PR watch" })).toBeVisible()); + expect(screen.getAllByRole("dialog")).toHaveLength(1); } - expect(save).toHaveBeenCalledWith(task, expect.objectContaining({ name: "Updated watch" })); + expect(save).not.toHaveBeenCalled(); + }); + + it("localizes the legacy destination error with a recovery path", async () => { + await act(() => i18n.changeLanguage("zh-CN")); + render(); + + fireEvent.click(screen.getByRole("button", { name: /PR watch/ })); + const detail = screen.getByRole("dialog", { name: "PR watch" }); + expect(within(detail).getByRole("alert")).toHaveTextContent( + "这个旧版自动任务缺少发送目标,无法继续运行。请从关联会话中重新创建该任务。", + ); + expect(detail).not.toHaveTextContent("legacy cron payload"); }); it("runs a linked task through the existing action and prevents duplicate actions while busy", async () => { @@ -570,11 +728,10 @@ describe("Automation task list and detail sheet", () => { const action = vi.fn(); const { rerender } = render(); await user.click(screen.getByRole("button", { name: /PR watch/ })); - await user.click(screen.getByRole("button", { name: "More actions" })); - await user.click(screen.getByRole("menuitem", { name: "Run now" })); + await user.click(screen.getByRole("button", { name: "Run now" })); expect(action).toHaveBeenCalledWith("run", task); rerender(); - for (const name of ["Edit", "Pause", "More actions"]) { + for (const name of ["Edit", "Pause", "Run now", "Delete"]) { expect(screen.getByRole("button", { name })).toBeDisabled(); } rerender(); @@ -585,9 +742,7 @@ describe("Automation task list and detail sheet", () => { const user = userEvent.setup(); const { rerender } = render(); await user.click(screen.getByRole("button", { name: /PR watch/ })); - await user.click(screen.getByRole("button", { name: "More actions" })); - expect(screen.getByRole("menuitem", { name: "Run now" })).toHaveAttribute("aria-disabled", "true"); - await user.keyboard("{Escape}"); + expect(screen.getByRole("button", { name: "Run now" })).toBeDisabled(); rerender(); expect(screen.getByRole("button", { name: "Resume" })).toBeDisabled(); expect(screen.queryByRole("link", { name: "Open a chat" })).not.toBeInTheDocument(); @@ -603,8 +758,8 @@ describe("Automation task list and detail sheet", () => { expect(screen.getByText("Command")).toBeVisible(); expect(within(screen.getByRole("dialog")).getByText("nanobot trigger run trigger-1")).toBeVisible(); expect(screen.getByRole("button", { name: "Copy" })).toBeEnabled(); - await user.click(screen.getByRole("button", { name: "More actions" })); - expect(screen.queryByRole("menuitem", { name: "Run now" })).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Run now" })).not.toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Delete" })).toBeVisible(); }); it("shows paused failures honestly and does not fabricate successful runs", () => { diff --git a/webui/src/tests/session-info-popover.test.tsx b/webui/src/tests/session-info-popover.test.tsx index f2863ce74..1e1bac12d 100644 --- a/webui/src/tests/session-info-popover.test.tsx +++ b/webui/src/tests/session-info-popover.test.tsx @@ -1,9 +1,13 @@ -import { act, render, screen, waitFor } from "@testing-library/react"; +import { act, render, screen, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { SessionInfoPopover } from "@/components/thread/SessionInfoPopover"; import { setAppLanguage } from "@/i18n"; +import type { WebUIMutationTransport } from "@/lib/api"; + +const requestMutation = vi.fn(); +const client: WebUIMutationTransport = { requestMutation }; function automationJob( nextRunAt = Date.now() + 3_600_000, @@ -32,6 +36,7 @@ function automationsResponse(jobs: unknown[]) { describe("SessionInfoPopover", () => { beforeEach(async () => { await setAppLanguage("en"); + requestMutation.mockReset(); vi.stubGlobal( "fetch", vi.fn().mockResolvedValue(automationsResponse([automationJob()])), @@ -48,6 +53,7 @@ describe("SessionInfoPopover", () => { render( { }), ); }); - expect(await screen.findByText("Morning check")).toBeInTheDocument(); - expect(screen.getByText("Check the project status")).toBeInTheDocument(); + const row = await screen.findByRole("button", { name: /Morning check/ }); + expect(row).toHaveAttribute("aria-haspopup", "dialog"); + expect(screen.queryByText("Check the project status")).not.toBeInTheDocument(); + + await user.click(row); + const detail = screen.getByRole("dialog", { name: "Morning check" }); + expect(detail).toHaveClass("max-w-[520px]", "rounded-modal"); + expect(within(detail).getByText("Instructions")).toBeInTheDocument(); + expect(within(detail).getByText("Check the project status")).toBeInTheDocument(); + await user.click(within(detail).getByRole("button", { name: "Done" })); + await waitFor(() => expect(screen.queryByRole("dialog", { name: "Morning check" })).not.toBeInTheDocument()); + expect(screen.getByRole("button", { name: "Session details" })).toHaveFocus(); + }); + + it("manages a session task through the shared detail dialog", async () => { + const pausedJob = { ...automationJob(), enabled: false }; + requestMutation.mockResolvedValue({ jobs: [pausedJob] }); + const user = userEvent.setup(); + + render( + , + ); + + await user.click(screen.getByRole("button", { name: "Session details" })); + await user.click(await screen.findByRole("button", { name: /Morning check/ })); + const detail = screen.getByRole("dialog", { name: "Morning check" }); + await user.click(within(detail).getByRole("button", { name: "Pause" })); + + expect(requestMutation).toHaveBeenCalledWith( + "automation.disable", + { id: "job-1" }, + 20_000, + ); + expect(await within(detail).findByRole("button", { name: "Resume" })).toBeInTheDocument(); + }); + + it("returns from the shared editor to the same task detail", async () => { + const user = userEvent.setup(); + render( + , + ); + + await user.click(screen.getByRole("button", { name: "Session details" })); + await user.click(await screen.findByRole("button", { name: /Morning check/ })); + await user.click(screen.getByRole("button", { name: "Edit", exact: true })); + const editor = await screen.findByRole("dialog", { name: "Edit automation" }); + expect(screen.getAllByRole("dialog")).toHaveLength(1); + await user.click(within(editor).getByRole("button", { name: "Cancel", exact: true })); + + expect(await screen.findByRole("dialog", { name: "Morning check" })).toBeVisible(); + expect(screen.getAllByRole("dialog")).toHaveLength(1); }); it("localizes the panel chrome in Simplified Chinese", async () => { @@ -76,6 +141,7 @@ describe("SessionInfoPopover", () => { render( { render( { render( { await user.click(screen.getByRole("button", { name: "Session details" })); - expect(await screen.findByText("Review PR #4591")).toBeInTheDocument(); - expect(screen.queryByText('nanobot trigger trg_123 "message"')).not.toBeInTheDocument(); + const row = await screen.findByRole("button", { name: /PR monitor/ }); + expect(screen.queryByText("Review PR #4591")).not.toBeInTheDocument(); + await user.click(row); + const detail = screen.getByRole("dialog", { name: "PR monitor" }); + expect(within(detail).getByText("Command")).toBeInTheDocument(); + expect(within(detail).getByText('nanobot trigger trg_123 "message"')).toBeInTheDocument(); }); it("refreshes while open so completed one-shot automations disappear", async () => { @@ -163,6 +235,7 @@ describe("SessionInfoPopover", () => { render( { render( { expect(screen.getByRole("button", { name: "Open details for cron" })).toBeVisible(); }); - it("opens a chat from the standalone automations empty state", async () => { + it("creates an automation from the standalone empty state", async () => { const onBackToChat = vi.fn(); + const onStartAutomationChat = vi.fn().mockResolvedValue(true); + const settings = settingsPayload(); + settings.providers = [{ + name: "openai", + label: "OpenAI", + configured: true, + }]; vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => { const url = String(input); - if (url === "/api/settings") return jsonResponse(settingsPayload()); + if (url === "/api/settings") return jsonResponse(settings); if (url === "/api/webui/automations") return jsonResponse({ jobs: [] }); return jsonResponse({}); })); renderSettingsView({ initialSection: "automations", - initialSettings: settingsPayload(), + initialSettings: settings, showSidebar: false, onBackToChat, + onStartAutomationChat, }); expect(screen.getByRole("heading", { name: "Automations" })).toBeInTheDocument(); expect(await screen.findByText("No automations yet.")).toBeInTheDocument(); - expect(screen.getByText("Tell nanobot in a chat what you'd like it to do on a schedule.")).toBeInTheDocument(); - expect(screen.queryByRole("button", { name: "Create in chat" })).not.toBeInTheDocument(); - expect(screen.queryByRole("button", { name: "Open a chat" })).not.toBeInTheDocument(); + const input = screen.getByRole("textbox", { name: "Describe an automation" }); + expect(input).toHaveAttribute( + "placeholder", + "Describe an automation, for example: summarize project updates every weekday at 9:00", + ); + fireEvent.change(input, { target: { value: "Summarize updates every weekday at 9" } }); + fireEvent.click(screen.getByRole("button", { name: "Send message" })); + await waitFor(() => expect(onStartAutomationChat).toHaveBeenCalledWith( + "Create an automation for this request:\n\nSummarize updates every weekday at 9", + undefined, + undefined, + "primary", + )); fireEvent.click(screen.getByRole("button", { name: "Back to chat" })); expect(onBackToChat).toHaveBeenCalledTimes(1); }); diff --git a/webui/src/tests/settings-test-utils.tsx b/webui/src/tests/settings-test-utils.tsx index a79a32e50..beb49ddd1 100644 --- a/webui/src/tests/settings-test-utils.tsx +++ b/webui/src/tests/settings-test-utils.tsx @@ -140,6 +140,7 @@ export function renderSettingsView( showSidebar?: boolean; onBackToChat?: () => void; onSettingsChange?: (payload: SettingsPayload) => void; + onStartAutomationChat?: React.ComponentProps["onStartAutomationChat"]; onNativeEngineRestart?: () => Promise; onRestart?: () => void; } = {}, @@ -155,6 +156,7 @@ export function renderSettingsView( onBackToChat={options.onBackToChat ?? (() => {})} onModelNameChange={() => {}} onSettingsChange={options.onSettingsChange} + onStartAutomationChat={options.onStartAutomationChat} onNativeEngineRestart={options.onNativeEngineRestart} onRestart={options.onRestart} /> diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsx index ff33af486..ad0e57227 100644 --- a/webui/src/tests/thread-shell.test.tsx +++ b/webui/src/tests/thread-shell.test.tsx @@ -1601,6 +1601,40 @@ describe("ThreadShell", () => { ); }); + it("consumes an automation-page first message through the normal thread stream", async () => { + const client = makeClient(); + const consumed = vi.fn(); + const pendingFirstMessage = { + id: "automation-first-message", + chatId: "chat-new", + content: "Every weekday at 9, summarize open pull requests", + }; + + render( + wrap( + client, + + {}} + pendingFirstMessage={pendingFirstMessage} + onPendingFirstMessageConsumed={consumed} + /> + , + ), + ); + + await waitFor(() => expectSendMessageWithTurn( + client, + "chat-new", + pendingFirstMessage.content, + )); + expect(client.sendMessage).toHaveBeenCalledTimes(1); + expect(consumed).toHaveBeenCalledOnce(); + expect(consumed).toHaveBeenCalledWith(pendingFirstMessage.id); + }); + it("keeps the first landing message when new chat history is still empty", async () => { const client = makeClient(); const onCreateChat = vi.fn().mockResolvedValue("chat-new");