feat(webui): refine automation calendar workflows
This commit is contained in:
1 parent
98b0c3858b
commit
37e29c36e5
25 files changed
+1789
-487
No files matched your search
@@ -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<SettingsPayload | null>(null);
|
||||
const [pendingAutomationMessage, setPendingAutomationMessage] = useState<{
|
||||
id: string;
|
||||
chatId: string;
|
||||
content: string;
|
||||
images?: SendAttachment[];
|
||||
options?: SendOptions;
|
||||
} | null>(null);
|
||||
const settingsExitGuardRef = useRef<SettingsExitGuard | null>(null);
|
||||
const currentShellRouteRef = useRef<ShellRoute>({ 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}
|
||||
|
||||
@@ -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<boolean | void>;
|
||||
titleOverrides?: Record<string, string>;
|
||||
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<HTMLDivElement | null>(null);
|
||||
const [pendingExit, setPendingExit] = useState<(() => void) | null>(null);
|
||||
const [automationDetailReturn, setAutomationDetailReturn] =
|
||||
useState<SessionAutomationJob | null>(null);
|
||||
const {
|
||||
activeSection,
|
||||
apiService,
|
||||
@@ -565,6 +575,8 @@ export function SettingsPage({
|
||||
<AutomationsSettings
|
||||
payload={automations}
|
||||
titleOverrides={titleOverrides}
|
||||
settingsSnapshot={controller.settings}
|
||||
onStartChat={onStartAutomationChat}
|
||||
loading={automationsLoading}
|
||||
query={automationsQuery}
|
||||
filter={automationsFilter}
|
||||
@@ -575,8 +587,14 @@ export function SettingsPage({
|
||||
onFilterChange={setAutomationsFilter}
|
||||
onSortChange={setAutomationsSort}
|
||||
onAction={handleAutomationAction}
|
||||
onRequestEdit={setAutomationPendingEdit}
|
||||
onRequestEdit={(job) => {
|
||||
setAutomationDetailReturn(null);
|
||||
setAutomationPendingEdit(job);
|
||||
}}
|
||||
onRequestDelete={setAutomationPendingDelete}
|
||||
onManageModels={() => selectSection("models")}
|
||||
returnToDetailJob={automationDetailReturn}
|
||||
onReturnToDetailHandled={() => setAutomationDetailReturn(null)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
@@ -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]",
|
||||
)}
|
||||
>
|
||||
|
||||
@@ -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<boolean | void>;
|
||||
titleOverrides?: Record<string, string>;
|
||||
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}
|
||||
|
||||
@@ -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 = (
|
||||
<>
|
||||
<span className={cn(
|
||||
"mt-[0.4rem] h-1.5 w-1.5 shrink-0 rounded-full",
|
||||
running && "bg-[hsl(var(--usage-token))]",
|
||||
failed && "bg-destructive",
|
||||
!running && !failed && entry.kind === "planned" && "border border-foreground/50 bg-background",
|
||||
!running && !failed && entry.kind === "recorded" && "bg-foreground/45",
|
||||
)} aria-hidden />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate font-medium text-foreground">{name}</span>
|
||||
<span className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[10px] leading-4 text-muted-foreground">
|
||||
{running ? <Loader2 className="h-3 w-3 animate-spin motion-reduce:animate-none" aria-hidden /> : null}
|
||||
{failed ? <CircleAlert className="h-3 w-3" aria-hidden /> : null}
|
||||
<span className="tabular-nums">{entryTime(entry, locale)}</span>
|
||||
{compact ? <span>{status}</span> : null}
|
||||
</span>
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
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 (
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
aria-label={`${name}, ${entryTime(entry, locale)}, ${status}`}
|
||||
aria-haspopup="dialog"
|
||||
onClick={(event) => onInspect(entry.job, event.currentTarget)}
|
||||
>
|
||||
{content}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function AutomationCalendar({ jobs, locale, copy, onInspect }: AutomationCalendarProps) {
|
||||
const [month, setMonth] = useState(() => startOfMonth(new Date()));
|
||||
const calendarRef = useRef<HTMLElement | null>(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<string, CalendarEntry[]>();
|
||||
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 (
|
||||
<section ref={calendarRef} className="automation-calendar overflow-hidden rounded-panel border border-border/70 bg-[hsl(var(--settings-surface))]">
|
||||
<div className="flex min-h-14 flex-wrap items-center gap-x-4 gap-y-2 px-4 py-2.5 sm:px-6">
|
||||
<h2 className="min-w-0 flex-1 text-[15px] font-semibold text-foreground">{monthLabel}</h2>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 rounded-control px-3 text-[12px]"
|
||||
onClick={() => setMonth(startOfMonth(new Date()))}
|
||||
>
|
||||
{copy.today}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-muted-foreground"
|
||||
aria-label={copy.previousMonth}
|
||||
onClick={() => setMonth((value) => addMonths(value, -1))}
|
||||
>
|
||||
<span className="text-lg leading-none" aria-hidden>‹</span>
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-muted-foreground"
|
||||
aria-label={copy.nextMonth}
|
||||
onClick={() => setMonth((value) => addMonths(value, 1))}
|
||||
>
|
||||
<span className="text-lg leading-none" aria-hidden>›</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!jobs.length ? (
|
||||
<div className="flex min-h-48 items-center justify-center px-6 text-center text-[13px] text-muted-foreground">
|
||||
{copy.noEntries}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{jobs.length > 0 && wideCalendar ? <div className="automation-calendar-grid" aria-label={monthLabel}>
|
||||
<div className="automation-calendar-weekdays" aria-hidden>
|
||||
{weekdayLabels.map((label) => <div key={label}>{label}</div>)}
|
||||
</div>
|
||||
<div className="automation-calendar-month">
|
||||
{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 (
|
||||
<div
|
||||
key={dateKey(day)}
|
||||
className={cn("automation-calendar-day", !currentMonth && "bg-muted/15")}
|
||||
aria-label={dayLabel}
|
||||
>
|
||||
<div className="flex h-8 items-center justify-end px-2 pt-1">
|
||||
<time
|
||||
dateTime={`${day.getFullYear()}-${String(day.getMonth() + 1).padStart(2, "0")}-${String(day.getDate()).padStart(2, "0")}`}
|
||||
aria-current={currentDay ? "date" : undefined}
|
||||
className={cn(
|
||||
"inline-flex h-6 min-w-6 items-center justify-center rounded-full px-1 text-[11px] tabular-nums",
|
||||
currentDay ? "bg-foreground font-medium text-background" : currentMonth ? "text-foreground" : "text-muted-foreground/55",
|
||||
)}
|
||||
>
|
||||
{dayFormatter.format(day)}
|
||||
</time>
|
||||
</div>
|
||||
<div className="space-y-0.5 px-1 pb-1">
|
||||
{entries.slice(0, 3).map((entry) => (
|
||||
<CalendarEntryRow
|
||||
key={entry.id}
|
||||
entry={entry}
|
||||
locale={locale}
|
||||
copy={copy}
|
||||
onInspect={onInspect}
|
||||
/>
|
||||
))}
|
||||
{entries.length > 3 ? (
|
||||
<details className="group/more">
|
||||
<summary className={cn(
|
||||
"cursor-pointer list-none rounded-control px-2 py-1 text-[10px] text-muted-foreground settings-hover [&::-webkit-details-marker]:hidden",
|
||||
formControlFocusClassName,
|
||||
)}>
|
||||
{copy.more(entries.length - 3)}
|
||||
</summary>
|
||||
<div className="mt-0.5 space-y-0.5">
|
||||
{entries.slice(3).map((entry) => (
|
||||
<CalendarEntryRow
|
||||
key={entry.id}
|
||||
entry={entry}
|
||||
locale={locale}
|
||||
copy={copy}
|
||||
onInspect={onInspect}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div> : null}
|
||||
|
||||
{jobs.length > 0 && !wideCalendar ? <div className="automation-calendar-agenda px-3 py-2 sm:px-4">
|
||||
{visibleEntries.length ? (
|
||||
<ol>
|
||||
{days.filter((day) => entriesByDay.has(dateKey(day))).map((day) => (
|
||||
<li key={dateKey(day)} className="grid grid-cols-[5.25rem_minmax(0,1fr)] gap-2 py-2.5">
|
||||
<time className={cn("pt-2 text-[11px] leading-4 text-muted-foreground", isSameDay(day, today) && "font-semibold text-foreground")}>{agendaDateFormatter.format(day)}</time>
|
||||
<div className="min-w-0 space-y-1">
|
||||
{(entriesByDay.get(dateKey(day)) ?? []).map((entry) => (
|
||||
<CalendarEntryRow
|
||||
key={entry.id}
|
||||
entry={entry}
|
||||
locale={locale}
|
||||
copy={copy}
|
||||
onInspect={onInspect}
|
||||
compact
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
) : (
|
||||
<div className="flex min-h-28 items-center justify-center text-[13px] text-muted-foreground">{copy.noEntries}</div>
|
||||
)}
|
||||
</div> : null}
|
||||
|
||||
{jobs.length ? (
|
||||
<div className="automation-meta-row py-2 text-[10px] text-muted-foreground">
|
||||
<span className="flex h-4 w-4 items-center justify-center" aria-hidden>
|
||||
<span className="h-1.5 w-1.5 rounded-full border border-foreground/50 bg-background" />
|
||||
</span>
|
||||
<span className="flex flex-wrap items-center gap-x-4 gap-y-1">
|
||||
<span>{copy.planned}</span>
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-foreground/45" aria-hidden />
|
||||
{copy.recorded}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{outsideJobs.length ? (
|
||||
<details
|
||||
key={`${month.getTime()}:${visibleEntries.length ? "mixed" : "outside-only"}`}
|
||||
className="group"
|
||||
open={!visibleEntries.length || undefined}
|
||||
>
|
||||
<summary className={cn("automation-meta-row min-h-11 cursor-pointer list-none items-center text-[12px] text-muted-foreground settings-hover [&::-webkit-details-marker]:hidden", formControlFocusClassName)}>
|
||||
<Clock3 className="h-3.5 w-3.5 place-self-center" aria-hidden />
|
||||
<span className="flex min-w-0 items-center gap-2">
|
||||
<span className="truncate">{copy.outsideMonth}</span>
|
||||
<span className="tabular-nums text-muted-foreground/65">{outsideJobs.length}</span>
|
||||
</span>
|
||||
<ChevronDown className="h-4 w-4 transition-transform group-open:rotate-180 motion-reduce:transition-none" aria-hidden />
|
||||
</summary>
|
||||
<ul className="px-4 pb-2 sm:px-6">
|
||||
{outsideJobs.map((job) => (
|
||||
<li key={job.id}>
|
||||
<button
|
||||
type="button"
|
||||
className={cn("grid min-h-10 w-full grid-cols-[1rem_minmax(0,1fr)_auto] items-center gap-x-2 rounded-control text-left text-[12px] settings-hover", formControlFocusClassName)}
|
||||
aria-haspopup="dialog"
|
||||
onClick={(event) => inspectOutsideJob(job, event.currentTarget)}
|
||||
>
|
||||
<span className="h-4 w-4" aria-hidden />
|
||||
<span className="truncate font-medium text-foreground">{job.name || job.id}</span>
|
||||
<span className="flex shrink-0 flex-wrap justify-end gap-x-2 gap-y-0.5 text-[11px] text-muted-foreground">
|
||||
{(job.state.last_status === "error" || job.state.last_error)
|
||||
? <span>{copy.attention}</span> : null}
|
||||
{!job.enabled ? <span>{copy.paused}</span> : null}
|
||||
{job.enabled && job.delete_after_run && job.state.last_status === "ok"
|
||||
? <span>{copy.completed}</span> : null}
|
||||
{job.enabled && !(job.delete_after_run && job.state.last_status === "ok")
|
||||
&& job.state.last_status !== "error" && !job.state.last_error
|
||||
? <span>{copy.outsideMonth}</span> : null}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -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<string, string>;
|
||||
settingsSnapshot?: SettingsPayload | null;
|
||||
loading: boolean;
|
||||
query: string;
|
||||
filter: AutomationFilter;
|
||||
@@ -71,6 +85,15 @@ export function AutomationsSettings({
|
||||
onAction: (action: AutomationAction, job: SessionAutomationJob) => void | Promise<void>;
|
||||
onRequestEdit: (job: SessionAutomationJob) => void;
|
||||
onRequestDelete: (job: SessionAutomationJob) => void;
|
||||
onStartChat?: (
|
||||
content: string,
|
||||
images?: SendAttachment[],
|
||||
options?: SendOptions,
|
||||
modelPreset?: string | null,
|
||||
) => boolean | void | Promise<boolean | void>;
|
||||
onManageModels?: () => void;
|
||||
returnToDetailJob?: SessionAutomationJob | null;
|
||||
onReturnToDetailHandled?: () => void;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>
|
||||
@@ -87,6 +110,7 @@ export function AutomationsSettings({
|
||||
const locale = i18n.resolvedLanguage || i18n.language;
|
||||
const [inspectedJob, setInspectedJob] = useState<SessionAutomationJob | null>(null);
|
||||
const [detailOpen, setDetailOpen] = useState(false);
|
||||
const [localModelPreset, setLocalModelPreset] = useState<string | null>(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<HTMLInputElement | null>(null);
|
||||
const pageTitle = useRef<HTMLHeadingElement | null>(null);
|
||||
const selectedTrigger = useRef<HTMLButtonElement | null>(null);
|
||||
const selectedTrigger = useRef<HTMLElement | null>(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<AutomationSort, string>;
|
||||
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) => (
|
||||
<AutomationListItem
|
||||
key={job.id}
|
||||
@@ -149,12 +203,31 @@ export function AutomationsSettings({
|
||||
}}
|
||||
/>
|
||||
);
|
||||
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 (
|
||||
<div className="automations-page">
|
||||
@@ -165,12 +238,39 @@ export function AutomationsSettings({
|
||||
</header>
|
||||
|
||||
<div className="settings-stack">
|
||||
{onStartChat ? (
|
||||
<div
|
||||
className="automation-create-composer"
|
||||
aria-label={tx("settings.automations.create", "Create automation")}
|
||||
>
|
||||
<ThreadComposer
|
||||
onSend={startAutomationChat}
|
||||
inputAriaLabel={tx("settings.automations.createInput", "Describe an automation")}
|
||||
placeholder={tx(
|
||||
"settings.automations.createPrompt",
|
||||
"Describe an automation, for example: summarize project updates every weekday at 9:00",
|
||||
)}
|
||||
variant="thread"
|
||||
modelLabel={modelBadgeLabel}
|
||||
modelDetail={modelBadge.model}
|
||||
modelPreset={activeModelPreset}
|
||||
modelPresets={modelPresetOptions}
|
||||
onModelPresetChange={setLocalModelPreset}
|
||||
modelProvider={modelBadge.provider}
|
||||
modelProviderLabel={modelBadge.providerLabel}
|
||||
modelNeedsSetup={modelBadge.needsSetup}
|
||||
onModelBadgeClick={modelBadge.needsSetup ? onManageModels : undefined}
|
||||
onManageModels={onManageModels}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{jobs.length ? (
|
||||
<section
|
||||
aria-label={tx("settings.automations.viewOptions", "Search and filter")}
|
||||
className="flex min-w-0 flex-wrap items-center gap-3"
|
||||
className="grid min-w-0 items-center gap-3 sm:grid-cols-[minmax(13rem,1fr)_auto_auto]"
|
||||
>
|
||||
<div className="relative min-w-0 basis-full sm:flex-1 sm:basis-[240px]">
|
||||
<div className="relative min-w-0">
|
||||
<Search className="pointer-events-none absolute start-4 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" aria-hidden />
|
||||
<Input
|
||||
ref={searchInput}
|
||||
@@ -178,7 +278,7 @@ export function AutomationsSettings({
|
||||
onChange={(event) => 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)}
|
||||
/>
|
||||
</div>
|
||||
<div role="group" aria-label={tx("settings.nav.automations", "Automations")} className="min-w-0 max-w-full">
|
||||
@@ -193,147 +293,189 @@ export function AutomationsSettings({
|
||||
onChange={onFilterChange}
|
||||
/>
|
||||
</div>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" className="h-9 justify-self-start gap-1.5 px-2 text-[11px] text-muted-foreground sm:justify-self-end">
|
||||
<ArrowUpDown className="h-3.5 w-3.5" aria-hidden />
|
||||
{sortLabel[sort]}
|
||||
<ChevronDown className="h-3.5 w-3.5" aria-hidden />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{(Object.keys(sortLabel) as AutomationSort[]).map((value) => (
|
||||
<DropdownMenuItem key={value} onClick={() => onSortChange(value)}>
|
||||
<span>{sortLabel[value]}</span>
|
||||
{sort === value ? <Check className="ml-auto h-3.5 w-3.5" aria-hidden /> : null}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
<SettingsGroup>
|
||||
{jobs.length ? (
|
||||
<div className="flex min-w-0 justify-end px-5 pb-2 pt-3 sm:px-6">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" className="h-8 gap-1.5 px-2 text-[11px] text-muted-foreground">
|
||||
<ArrowUpDown className="h-3.5 w-3.5" aria-hidden />
|
||||
{sortLabel[sort]}
|
||||
<ChevronDown className="h-3.5 w-3.5" aria-hidden />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{(Object.keys(sortLabel) as AutomationSort[]).map((value) => (
|
||||
<DropdownMenuItem key={value} onClick={() => onSortChange(value)}>
|
||||
<span>{sortLabel[value]}</span>
|
||||
{sort === value ? <Check className="ml-auto h-3.5 w-3.5" aria-hidden /> : null}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
) : null}
|
||||
{error ? <AutomationError message={error} /> : null}
|
||||
{loading && !payload ? (
|
||||
<div role="status" className="flex h-44 items-center justify-center rounded-panel border border-border/70 bg-[hsl(var(--settings-surface))] text-[13px] text-muted-foreground">
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden />
|
||||
{tx("settings.automations.loading", "Loading automations...")}
|
||||
</div>
|
||||
) : payload && jobs.length && !filtered.length ? (
|
||||
<div className="flex min-h-32 items-center justify-center gap-3 rounded-panel border border-border/70 bg-[hsl(var(--settings-surface))] px-4 text-[12px] text-muted-foreground">
|
||||
<span>{tx("settings.automations.noMatches", "No automations match this view.")}</span>
|
||||
<Button variant="ghost" size="sm" onClick={() => {
|
||||
onQueryChange("");
|
||||
onFilterChange("all");
|
||||
}}>
|
||||
{tx("settings.automations.clearFilters", "Clear filters")}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<AutomationCalendar
|
||||
jobs={personal}
|
||||
locale={locale}
|
||||
copy={{
|
||||
previousMonth: tx("settings.automations.calendar.previousMonth", "Previous month"),
|
||||
nextMonth: tx("settings.automations.calendar.nextMonth", "Next month"),
|
||||
today: tx("settings.automations.calendar.today", "Today"),
|
||||
planned: tx("settings.automations.calendar.planned", "Planned"),
|
||||
recorded: tx("settings.automations.calendar.recorded", "Recorded"),
|
||||
running: tx("settings.automations.status.running", "Running"),
|
||||
failed: tx("settings.automations.status.failed", "Failed"),
|
||||
more: (count) => tx("settings.automations.calendar.more", "+{{count}} more", { count }),
|
||||
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 ? <AutomationError message={error} /> : null}
|
||||
{loading && !payload ? (
|
||||
<div role="status" className="flex h-44 items-center justify-center text-[13px] text-muted-foreground">
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden />
|
||||
{tx("settings.automations.loading", "Loading automations...")}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-5 px-3 pb-3 sm:px-4">
|
||||
{personal.length ? (
|
||||
<ul aria-label={tx("settings.automations.yourTasks", "Your automations")} className="space-y-1">
|
||||
{personal.map(renderJob)}
|
||||
{system.length ? (
|
||||
<SettingsGroup>
|
||||
<section className="py-2">
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={systemOpen}
|
||||
aria-controls="automation-system-tasks"
|
||||
onClick={() => {
|
||||
const open = !systemOpen;
|
||||
setSystemOpen(open);
|
||||
try {
|
||||
window.localStorage.setItem(SYSTEM_TASKS_OPEN_STORAGE_KEY, String(open));
|
||||
} catch {
|
||||
// Unavailable storage must not prevent expanding or collapsing.
|
||||
}
|
||||
}}
|
||||
className={cn("automation-meta-row min-h-10 w-full items-center rounded-control py-1.5 text-left text-[13px] font-medium text-muted-foreground settings-hover", formControlFocusClassName)}
|
||||
>
|
||||
<span className="h-4 w-4" aria-hidden />
|
||||
<span className="flex min-w-0 items-center gap-2">
|
||||
<span className="truncate">{tx("settings.automations.systemTasks", "System tasks")}</span>
|
||||
<span className="text-[12px] font-normal tabular-nums text-muted-foreground/60">{system.length}</span>
|
||||
{system.some(automationNeedsAttention) ? (
|
||||
<span className="ml-auto inline-flex items-center gap-1.5 text-[12px] font-normal text-amber-700 dark:text-amber-400">
|
||||
<CircleAlert className="h-3.5 w-3.5" aria-hidden />
|
||||
{tx("settings.automations.filters.failed", "Needs attention")}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
<ChevronDown className={cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none", systemOpen && "rotate-180")} aria-hidden />
|
||||
</button>
|
||||
<DisclosureContent id="automation-system-tasks" open={systemOpen}>
|
||||
<ul aria-label={tx("settings.automations.systemTasks", "System tasks")} className="space-y-1 px-4 pt-1 sm:px-6">
|
||||
{system.map(renderJob)}
|
||||
</ul>
|
||||
) : !personalJobs.length && !query && filter === "all" ? (
|
||||
<div className="px-2 py-12 text-center">
|
||||
<p className="text-[14px] font-medium text-foreground">
|
||||
{tx("settings.automations.empty", "No automations yet.")}
|
||||
</p>
|
||||
<p className="mx-auto mt-2 max-w-sm text-[13px] leading-6 text-muted-foreground">
|
||||
{tx("settings.automations.emptyHint", "Tell nanobot in a chat what you'd like it to do on a schedule.")}
|
||||
</p>
|
||||
</div>
|
||||
) : !filtered.length ? (
|
||||
<div className="py-12 text-center text-[13px] text-muted-foreground">
|
||||
<p>{tx("settings.automations.noMatches", "No automations match this view.")}</p>
|
||||
<Button variant="outline" className="mt-4 rounded-full" onClick={() => {
|
||||
onQueryChange("");
|
||||
onFilterChange("all");
|
||||
}}>
|
||||
{tx("settings.automations.clearFilters", "Clear filters")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
{system.length ? (
|
||||
<section className="space-y-1">
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={systemOpen}
|
||||
aria-controls="automation-system-tasks"
|
||||
onClick={() => {
|
||||
const open = !systemOpen;
|
||||
setSystemOpen(open);
|
||||
try {
|
||||
// Persist only the user's choice, not automatic search expansion.
|
||||
window.localStorage.setItem(SYSTEM_TASKS_OPEN_STORAGE_KEY, String(open));
|
||||
} catch {
|
||||
// Unavailable storage must not prevent expanding or collapsing.
|
||||
}
|
||||
}}
|
||||
className={cn("flex min-h-9 w-full items-center gap-2 rounded-control px-2 py-1.5 text-left text-[13px] font-medium text-muted-foreground settings-hover", formControlFocusClassName)}
|
||||
>
|
||||
<span>{tx("settings.automations.systemTasks", "System tasks")}</span>
|
||||
<span className="text-[12px] font-normal tabular-nums text-muted-foreground/60">{system.length}</span>
|
||||
{system.some(automationNeedsAttention) ? (
|
||||
<span className="ml-auto inline-flex items-center gap-1.5 text-[12px] font-normal text-amber-700 dark:text-amber-400">
|
||||
<CircleAlert className="h-3.5 w-3.5" aria-hidden />
|
||||
{tx("settings.automations.filters.failed", "Needs attention")}
|
||||
</span>
|
||||
) : null}
|
||||
<ChevronDown className={cn("ml-auto h-4 w-4 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none", systemOpen && "rotate-180")} aria-hidden />
|
||||
</button>
|
||||
<DisclosureContent
|
||||
id="automation-system-tasks"
|
||||
open={systemOpen}
|
||||
>
|
||||
<ul aria-label={tx("settings.automations.systemTasks", "System tasks")} className="space-y-1">
|
||||
{system.map(renderJob)}
|
||||
</ul>
|
||||
</DisclosureContent>
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</SettingsGroup>
|
||||
</DisclosureContent>
|
||||
</section>
|
||||
</SettingsGroup>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<Dialog open={detailOpen} onOpenChange={setDetailOpen}>
|
||||
{selectedJob ? (
|
||||
<DialogContent
|
||||
{...(selectedJob.protected ? { "aria-describedby": undefined } : {})}
|
||||
{...(!detailOpen ? { inert: "", "aria-hidden": true } : {})}
|
||||
showCloseButton={false}
|
||||
className={cn(
|
||||
"flex max-h-[calc(100dvh-2rem)] max-w-[520px] flex-col gap-0 overflow-hidden p-0",
|
||||
selectedJob.protected && "max-w-[440px]",
|
||||
)}
|
||||
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);
|
||||
}}
|
||||
>
|
||||
<AutomationDetailPanel
|
||||
key={selectedJob.id}
|
||||
job={selectedJob}
|
||||
locale={locale}
|
||||
actionKey={actionKey}
|
||||
error={error}
|
||||
onClose={() => setDetailOpen(false)}
|
||||
onAction={onAction}
|
||||
onRequestEdit={() => handOff(onRequestEdit)}
|
||||
onRequestDelete={() => handOff(onRequestDelete)}
|
||||
/>
|
||||
</DialogContent>
|
||||
) : null}
|
||||
</Dialog>
|
||||
<AutomationDetailDialog
|
||||
job={selectedJob}
|
||||
open={detailOpen}
|
||||
locale={locale}
|
||||
actionKey={actionKey}
|
||||
error={error}
|
||||
onOpenChange={setDetailOpen}
|
||||
onAction={onAction}
|
||||
onRequestEdit={() => handOff(onRequestEdit)}
|
||||
onRequestDelete={() => handOff(onRequestDelete)}
|
||||
onCloseAutoFocus={(event) => {
|
||||
event.preventDefault();
|
||||
if (detailOpen) return;
|
||||
setInspectedJob(null);
|
||||
const target = selectedTrigger.current?.isConnected
|
||||
? selectedTrigger.current : searchInput.current ?? pageTitle.current;
|
||||
target?.focus({ preventScroll: true });
|
||||
const next = afterDetailClose.current;
|
||||
afterDetailClose.current = null;
|
||||
if (liveSelectedJob) next?.(liveSelectedJob);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AutomationDetailDialog({
|
||||
job,
|
||||
open,
|
||||
locale,
|
||||
actionKey,
|
||||
error,
|
||||
onOpenChange,
|
||||
onAction,
|
||||
onRequestEdit,
|
||||
onRequestDelete,
|
||||
onCloseAutoFocus,
|
||||
}: {
|
||||
job: SessionAutomationJob | null;
|
||||
open: boolean;
|
||||
locale: string;
|
||||
actionKey: string | null;
|
||||
error: string | null;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onAction: (action: AutomationAction, job: SessionAutomationJob) => void | Promise<void>;
|
||||
onRequestEdit: (job: SessionAutomationJob) => void;
|
||||
onRequestDelete: (job: SessionAutomationJob) => void;
|
||||
onCloseAutoFocus?: (event: Event) => void;
|
||||
}) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
{job ? (
|
||||
<DialogContent
|
||||
{...(job.protected ? { "aria-describedby": undefined } : {})}
|
||||
{...(!open ? { inert: "", "aria-hidden": true } : {})}
|
||||
showCloseButton={false}
|
||||
className={cn(
|
||||
"flex max-h-[calc(100dvh-2rem)] max-w-[520px] flex-col gap-0 overflow-hidden p-0",
|
||||
job.protected && "max-w-[440px]",
|
||||
)}
|
||||
onCloseAutoFocus={onCloseAutoFocus}
|
||||
>
|
||||
<AutomationDetailPanel
|
||||
key={job.id}
|
||||
job={job}
|
||||
locale={locale}
|
||||
actionKey={actionKey}
|
||||
error={error}
|
||||
onClose={() => onOpenChange(false)}
|
||||
onAction={onAction}
|
||||
onRequestEdit={onRequestEdit}
|
||||
onRequestDelete={onRequestDelete}
|
||||
/>
|
||||
</DialogContent>
|
||||
) : null}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<li>
|
||||
@@ -369,7 +513,7 @@ function AutomationListItem({ job, locale, disabled, onSelect }: {
|
||||
<>
|
||||
<CircleAlert className="h-4 w-4 shrink-0 text-amber-700 dark:text-amber-400" aria-hidden />
|
||||
<span className="text-amber-700 dark:text-amber-400">{tx("settings.automations.filters.failed", "Needs attention")}</span>
|
||||
{!job.enabled ? <span>· {tx("settings.automations.next.paused", "Paused")}</span> : null}
|
||||
{!job.enabled ? <span>{tx("settings.automations.next.paused", "Paused")}</span> : null}
|
||||
</>
|
||||
) : (
|
||||
<span title={formatAutomationNextTitle(job, locale, tx)}>{formatAutomationNext(job, tx)}</span>
|
||||
@@ -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({
|
||||
</Button>
|
||||
</div>
|
||||
{canManage ? (
|
||||
<DialogDescription className="text-[13px] leading-5">
|
||||
{formatAutomationSchedule(job, locale, tx)} · {formatAutomationNext(job, tx)}
|
||||
<DialogDescription className="flex flex-wrap gap-x-3 gap-y-1 text-[13px] leading-5">
|
||||
<span>{formatAutomationSchedule(job, locale, tx)}</span>
|
||||
{timezone ? <span>{timezone}</span> : null}
|
||||
<span title={formatAutomationNextTitle(job, locale, tx)}>
|
||||
{formatAutomationNext(job, tx)}
|
||||
</span>
|
||||
</DialogDescription>
|
||||
) : null}
|
||||
</DialogHeader>
|
||||
@@ -464,6 +613,11 @@ function AutomationDetailPanel({
|
||||
<AutomationDetail label={tx("settings.automations.labels.schedule", "Schedule")}>
|
||||
{formatAutomationSchedule(job, locale, tx)}
|
||||
</AutomationDetail>
|
||||
{timezone ? (
|
||||
<AutomationDetail label={tx("settings.automations.fields.timezone", "Timezone")}>
|
||||
{timezone}
|
||||
</AutomationDetail>
|
||||
) : null}
|
||||
<AutomationDetail label={tx("settings.automations.sort.next", "Next run")} title={formatAutomationNextTitle(job, locale, tx)}>
|
||||
{formatAutomationNext(job, tx)}
|
||||
</AutomationDetail>
|
||||
@@ -471,7 +625,10 @@ function AutomationDetailPanel({
|
||||
) : null}
|
||||
<AutomationDetail label={tx("settings.automations.sort.last", "Last run")} title={job.state.last_run_at_ms ? fmtDateTime(job.state.last_run_at_ms, locale) : undefined}>
|
||||
{job.state.last_run_at_ms
|
||||
? [lastStatus, relativeTime(job.state.last_run_at_ms)].filter(Boolean).join(" · ")
|
||||
? <span className="flex flex-wrap justify-end gap-x-3 gap-y-1">
|
||||
{lastStatus ? <span>{lastStatus}</span> : null}
|
||||
<span>{relativeTime(job.state.last_run_at_ms)}</span>
|
||||
</span>
|
||||
: lastStatus || tx("settings.automations.neverRun", "Not run yet")}
|
||||
</AutomationDetail>
|
||||
{!job.protected ? (
|
||||
@@ -507,18 +664,21 @@ function AutomationDetailPanel({
|
||||
{actionKey === `${job.enabled ? "disable" : "enable"}:${job.id}` ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden /> : null}
|
||||
{job.enabled ? tx("settings.automations.pause", "Pause") : tx("settings.automations.resume", "Resume")}
|
||||
</Button>
|
||||
{/* The detail dialog owns modality, including during the delete handoff. */}
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="text-muted-foreground" disabled={busy} aria-label={tx("settings.automations.moreActions", "More actions")}>
|
||||
<MoreHorizontal className="h-4 w-4" aria-hidden />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start">
|
||||
{!localTrigger ? <DropdownMenuItem disabled={!canRun || busy} onClick={() => void onAction("run", job)}>{tx("settings.automations.runNow", "Run now")}</DropdownMenuItem> : null}
|
||||
<DropdownMenuItem disabled={busy} onClick={() => onRequestDelete(job)} tone="destructive">{tx("settings.automations.delete", "Delete")}</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
{!localTrigger ? (
|
||||
<Button variant="ghost" size="sm" className="text-muted-foreground" disabled={!canRun || busy} onClick={() => void onAction("run", job)}>
|
||||
{actionKey === `run:${job.id}` ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden /> : null}
|
||||
{tx("settings.automations.runNow", "Run now")}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||
disabled={busy}
|
||||
onClick={() => onRequestDelete(job)}
|
||||
>
|
||||
{tx("settings.automations.delete", "Delete")}
|
||||
</Button>
|
||||
<div className="ml-auto flex max-w-full flex-wrap justify-end gap-2">
|
||||
<Button variant="outline" size="sm" disabled={busy} onClick={() => onRequestEdit(job)}>
|
||||
{tx("settings.automations.edit", "Edit")}
|
||||
@@ -532,12 +692,31 @@ function AutomationDetailPanel({
|
||||
}
|
||||
|
||||
function AutomationError({ message }: { message: string }) {
|
||||
const { t } = useTranslation();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
return <div role="alert" className="mb-4 flex items-start gap-2 rounded-lg bg-destructive/5 px-3 py-2.5 text-[13px] leading-5 text-destructive">
|
||||
<CircleAlert className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
|
||||
<span className="min-w-0 break-words [overflow-wrap:anywhere]">{message}</span>
|
||||
<span className="min-w-0 break-words [overflow-wrap:anywhere]">
|
||||
{localizedAutomationError(message, tx)}
|
||||
</span>
|
||||
</div>;
|
||||
}
|
||||
|
||||
const LEGACY_AUTOMATION_DESTINATION_ERROR = "legacy cron payload is missing channel/to";
|
||||
|
||||
function localizedAutomationError(
|
||||
message: string,
|
||||
tx: (key: string, fallback: string) => string,
|
||||
): string {
|
||||
if (message.toLowerCase().includes(LEGACY_AUTOMATION_DESTINATION_ERROR)) {
|
||||
return tx(
|
||||
"settings.automations.errors.legacyMissingDestination",
|
||||
"This older automation is missing its delivery destination. Recreate it from the linked chat to continue.",
|
||||
);
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
function automationMessageNeedsExpansion(message: string): boolean {
|
||||
return message.length > 360 || message.split(/\r?\n/).length > 6;
|
||||
}
|
||||
@@ -593,11 +772,13 @@ export function AutomationEditDialog({
|
||||
job,
|
||||
saving,
|
||||
onOpenChange,
|
||||
onCancel,
|
||||
onSave,
|
||||
}: {
|
||||
job: SessionAutomationJob | null;
|
||||
saving: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onCancel?: (job: SessionAutomationJob) => void;
|
||||
onSave: (job: SessionAutomationJob, values: AutomationUpdatePayload) => void | Promise<void>;
|
||||
}) {
|
||||
const dialogFocus = useAutomationDialogFocus();
|
||||
@@ -630,9 +811,16 @@ export function AutomationEditDialog({
|
||||
if (!job || typeof payload === "string") return;
|
||||
void onSave(job, payload);
|
||||
};
|
||||
const changeOpen = (open: boolean) => {
|
||||
onOpenChange(open);
|
||||
if (!open && job) onCancel?.(job);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={Boolean(job)} onOpenChange={onOpenChange}>
|
||||
<Dialog
|
||||
open={Boolean(job)}
|
||||
onOpenChange={changeOpen}
|
||||
>
|
||||
{job ? (
|
||||
<DialogContent
|
||||
{...dialogFocus}
|
||||
@@ -780,7 +968,7 @@ export function AutomationEditDialog({
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={() => onOpenChange(false)}
|
||||
onClick={() => changeOpen(false)}
|
||||
disabled={saving}
|
||||
>
|
||||
{tx("settings.automations.cancel", "Cancel")}
|
||||
@@ -1221,20 +1409,10 @@ function formatAutomationSchedule(
|
||||
}
|
||||
if (job.schedule.kind === "cron" && job.schedule.expr) {
|
||||
const summary = formatCronScheduleSummary(job.schedule.expr, tx);
|
||||
if (summary) {
|
||||
return job.schedule.tz
|
||||
? tx("settings.automations.schedule.withTz", "{{summary}} · {{tz}}", {
|
||||
summary,
|
||||
tz: job.schedule.tz,
|
||||
})
|
||||
: summary;
|
||||
}
|
||||
return job.schedule.tz
|
||||
? tx("settings.automations.schedule.cronWithTz", "Cron {{expr}} · {{tz}}", {
|
||||
expr: job.schedule.expr,
|
||||
tz: job.schedule.tz,
|
||||
})
|
||||
: tx("settings.automations.schedule.cron", "Cron {{expr}}", { expr: job.schedule.expr });
|
||||
if (summary) return summary;
|
||||
return tx("settings.automations.schedule.cron", "Cron {{expr}}", {
|
||||
expr: job.schedule.expr,
|
||||
});
|
||||
}
|
||||
if (isLocalTriggerAutomation(job)) {
|
||||
return tx("settings.automations.schedule.local", "Local trigger");
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
import { useState } from "react";
|
||||
import { useRef, useState } from "react";
|
||||
import {
|
||||
CalendarClock,
|
||||
ChevronRight,
|
||||
CircleAlert,
|
||||
RefreshCcw,
|
||||
} from "lucide-react";
|
||||
import type { TFunction } from "i18next";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import {
|
||||
AutomationDeleteDialog,
|
||||
AutomationDetailDialog,
|
||||
AutomationEditDialog,
|
||||
} from "@/components/settings/system/AutomationsSettings";
|
||||
import type { AutomationAction } from "@/components/settings/system/AutomationsSettings";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { formControlFocusClassName } from "@/components/ui/form-control";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
@@ -15,8 +23,13 @@ import {
|
||||
} from "@/components/ui/popover";
|
||||
import { useSessionAutomationJobs } from "@/hooks/useSessionAutomationJobs";
|
||||
import { currentLocale } from "@/i18n";
|
||||
import { runAutomationAction, updateAutomation } from "@/lib/api";
|
||||
import type { WebUIMutationTransport } from "@/lib/api";
|
||||
import { fmtDateTime } from "@/lib/format";
|
||||
import type { SessionAutomationJob } from "@/lib/types";
|
||||
import type {
|
||||
AutomationUpdatePayload,
|
||||
SessionAutomationJob,
|
||||
} from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const RELATIVE_THRESHOLDS: [number, Intl.RelativeTimeFormatUnit][] = [
|
||||
@@ -30,148 +43,258 @@ const RELATIVE_THRESHOLDS: [number, Intl.RelativeTimeFormatUnit][] = [
|
||||
];
|
||||
|
||||
interface SessionInfoPopoverProps {
|
||||
client: WebUIMutationTransport;
|
||||
sessionKey: string;
|
||||
token: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export function SessionInfoPopover({ sessionKey, token, title }: SessionInfoPopoverProps) {
|
||||
export function SessionInfoPopover({ client, sessionKey, token, title }: SessionInfoPopoverProps) {
|
||||
const { t } = useTranslation("common");
|
||||
const [open, setOpen] = useState(false);
|
||||
const { jobs, loading, loadFailed, now } = useSessionAutomationJobs(open, token, sessionKey);
|
||||
const [inspectedJob, setInspectedJob] = useState<SessionAutomationJob | null>(null);
|
||||
const [detailOpen, setDetailOpen] = useState(false);
|
||||
const [actionKey, setActionKey] = useState<string | null>(null);
|
||||
const [actionError, setActionError] = useState<string | null>(null);
|
||||
const [pendingEdit, setPendingEdit] = useState<SessionAutomationJob | null>(null);
|
||||
const [pendingDelete, setPendingDelete] = useState<SessionAutomationJob | null>(null);
|
||||
const triggerRef = useRef<HTMLButtonElement | null>(null);
|
||||
const afterDetailClose = useRef<(() => void) | null>(null);
|
||||
const surfacesOpen = open || detailOpen || Boolean(pendingEdit) || Boolean(pendingDelete);
|
||||
const { jobs, loading, loadFailed, now } = useSessionAutomationJobs(
|
||||
surfacesOpen,
|
||||
token,
|
||||
sessionKey,
|
||||
);
|
||||
const selectedJob = inspectedJob;
|
||||
|
||||
const inspectJob = (job: SessionAutomationJob) => {
|
||||
setActionError(null);
|
||||
setInspectedJob(job);
|
||||
setOpen(false);
|
||||
setDetailOpen(true);
|
||||
};
|
||||
const handOffDetail = (next: () => void) => {
|
||||
afterDetailClose.current = next;
|
||||
setDetailOpen(false);
|
||||
};
|
||||
const updateInspectedJob = (nextJobs: SessionAutomationJob[], id: string) => {
|
||||
const nextJob = nextJobs.find((job) => job.id === id);
|
||||
if (nextJob) setInspectedJob(nextJob);
|
||||
};
|
||||
const handleAction = async (action: AutomationAction, job: SessionAutomationJob) => {
|
||||
const key = `${action}:${job.id}`;
|
||||
setActionKey(key);
|
||||
setActionError(null);
|
||||
try {
|
||||
const payload = await runAutomationAction(client, action, job.id);
|
||||
if (action === "delete") {
|
||||
setPendingDelete(null);
|
||||
setInspectedJob(null);
|
||||
} else {
|
||||
updateInspectedJob(payload.jobs, job.id);
|
||||
}
|
||||
} catch (error) {
|
||||
setActionError(error instanceof Error ? error.message : String(error));
|
||||
} finally {
|
||||
setActionKey(null);
|
||||
}
|
||||
};
|
||||
const handleEdit = async (job: SessionAutomationJob, values: AutomationUpdatePayload) => {
|
||||
const key = `update:${job.id}`;
|
||||
setActionKey(key);
|
||||
setActionError(null);
|
||||
try {
|
||||
const payload = await updateAutomation(client, job.id, values);
|
||||
updateInspectedJob(payload.jobs, job.id);
|
||||
setPendingEdit(null);
|
||||
} catch (error) {
|
||||
setActionError(error instanceof Error ? error.message : String(error));
|
||||
} finally {
|
||||
setActionKey(null);
|
||||
}
|
||||
};
|
||||
const automationContent = loading ? (
|
||||
<div className="flex items-center gap-2 rounded-floating bg-muted/45 px-3 py-3 text-[12.5px] text-muted-foreground">
|
||||
<div className="mx-2 flex items-center gap-2 rounded-floating bg-muted/45 px-3 py-3 text-[12.5px] text-muted-foreground">
|
||||
<RefreshCcw className="h-3.5 w-3.5 animate-spin" />
|
||||
{t("thread.sessionInfo.loading")}
|
||||
</div>
|
||||
) : loadFailed ? (
|
||||
<div className="flex items-center gap-2 rounded-floating bg-destructive/10 px-3 py-3 text-[12.5px] text-destructive">
|
||||
<div className="mx-2 flex items-center gap-2 rounded-floating bg-destructive/10 px-3 py-3 text-[12.5px] text-destructive">
|
||||
<CircleAlert className="h-3.5 w-3.5" />
|
||||
{t("thread.sessionInfo.loadFailed")}
|
||||
</div>
|
||||
) : jobs.length ? (
|
||||
<div className="space-y-1.5">
|
||||
<div className="space-y-1 px-2">
|
||||
{jobs.map((job) => (
|
||||
<AutomationRow key={job.id} job={job} now={now} />
|
||||
<AutomationRow key={job.id} job={job} now={now} onSelect={inspectJob} />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-floating bg-muted/35 px-3 py-3 text-[12.5px] leading-relaxed text-muted-foreground">
|
||||
<div className="mx-2 rounded-floating bg-muted/35 px-3 py-3 text-[12.5px] leading-relaxed text-muted-foreground">
|
||||
{t("thread.sessionInfo.empty")}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={t("thread.header.sessionInfo")}
|
||||
className={cn(
|
||||
"host-no-drag h-8 w-8 rounded-full text-muted-foreground/85",
|
||||
"hover:bg-accent/40 hover:text-foreground",
|
||||
)}
|
||||
<>
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
ref={triggerRef}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={t("thread.header.sessionInfo")}
|
||||
className={cn(
|
||||
"host-no-drag h-8 w-8 rounded-full text-muted-foreground/85",
|
||||
"hover:bg-accent/40 hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<CalendarClock className="h-4 w-4 stroke-[1.75]" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="end"
|
||||
sideOffset={8}
|
||||
className="w-[min(23rem,calc(100vw-1.5rem))] overflow-hidden p-0"
|
||||
onCloseAutoFocus={(event) => {
|
||||
if (detailOpen) event.preventDefault();
|
||||
}}
|
||||
>
|
||||
<CalendarClock className="h-4 w-4 stroke-[1.75]" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="end"
|
||||
sideOffset={8}
|
||||
className="w-[min(23rem,calc(100vw-1.5rem))] p-0"
|
||||
>
|
||||
<div className="space-y-3 px-4 py-3.5">
|
||||
<div className="min-w-0">
|
||||
<div className="text-[12px] font-normal text-muted-foreground/75">
|
||||
{t("thread.sessionInfo.title")}
|
||||
<div className="flex max-h-[min(var(--radix-popover-content-available-height),32rem)] flex-col">
|
||||
<div className="px-4 pb-3 pt-3.5">
|
||||
<div className="min-w-0">
|
||||
<div className="text-[12px] font-normal text-muted-foreground/75">
|
||||
{t("thread.sessionInfo.title")}
|
||||
</div>
|
||||
<div className="mt-0.5 truncate text-[14px] font-medium text-foreground">
|
||||
{title || t("thread.sessionInfo.untitled")}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-3 flex items-center justify-between gap-3 border-t border-border/45 pt-3">
|
||||
<span className="truncate text-[13px] font-medium text-foreground">
|
||||
{t("thread.sessionInfo.automations")}
|
||||
</span>
|
||||
<span className="rounded-full bg-muted/70 px-2 py-0.5 text-[11px] tabular-nums text-muted-foreground">
|
||||
{t("thread.sessionInfo.count", { count: jobs.length })}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-0.5 truncate text-[14px] font-medium text-foreground">
|
||||
{title || t("thread.sessionInfo.untitled")}
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain pb-2">
|
||||
{automationContent}
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border/45 p-2">
|
||||
<Button asChild variant="ghost" size="sm" className="w-full justify-between px-2 text-[12px] text-muted-foreground">
|
||||
<a href="#/automations">
|
||||
{t("thread.sessionInfo.openCalendar")}
|
||||
<ChevronRight className="h-3.5 w-3.5" aria-hidden />
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
<div className="h-px bg-border/45" />
|
||||
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span className="truncate text-[13px] font-medium text-foreground">
|
||||
{t("thread.sessionInfo.automations")}
|
||||
</span>
|
||||
</div>
|
||||
<span className="rounded-full bg-muted/70 px-2 py-0.5 text-[11px] text-muted-foreground">
|
||||
{t("thread.sessionInfo.count", { count: jobs.length })}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{automationContent}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
<AutomationDetailDialog
|
||||
job={selectedJob}
|
||||
open={detailOpen}
|
||||
locale={currentLocale()}
|
||||
actionKey={actionKey}
|
||||
error={actionError}
|
||||
onOpenChange={setDetailOpen}
|
||||
onAction={handleAction}
|
||||
onRequestEdit={(job) => 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?.();
|
||||
}}
|
||||
/>
|
||||
<AutomationEditDialog
|
||||
job={pendingEdit}
|
||||
saving={actionKey === `update:${pendingEdit?.id ?? ""}`}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!nextOpen) setPendingEdit(null);
|
||||
}}
|
||||
onCancel={(job) => {
|
||||
setInspectedJob(job);
|
||||
setDetailOpen(true);
|
||||
}}
|
||||
onSave={handleEdit}
|
||||
/>
|
||||
<AutomationDeleteDialog
|
||||
job={pendingDelete}
|
||||
deleting={actionKey === `delete:${pendingDelete?.id ?? ""}`}
|
||||
onOpenChange={(nextOpen) => {
|
||||
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 (
|
||||
<div className="rounded-floating px-3 py-2.5 transition-colors hover:bg-muted/40">
|
||||
<div className="flex items-start gap-2.5">
|
||||
<span className={cn("mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full", statusClass)} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span className="truncate text-[13px] font-medium text-foreground">{job.name}</span>
|
||||
{!job.enabled ? (
|
||||
<span className="shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[10.5px] text-muted-foreground">
|
||||
{t("thread.sessionInfo.disabled")}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="mt-1 line-clamp-2 text-[12px] leading-snug text-muted-foreground">
|
||||
{job.payload.message}
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-x-2 gap-y-1 text-[11.5px] text-muted-foreground/80">
|
||||
<span>{schedule}</span>
|
||||
<span aria-hidden>·</span>
|
||||
<span title={nextRun.title}>{nextRun.label}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
aria-haspopup="dialog"
|
||||
aria-label={`${job.name || job.id}, ${summary}`}
|
||||
onClick={() => onSelect(job)}
|
||||
className={cn(
|
||||
"grid min-h-12 w-full grid-cols-[0.375rem_minmax(0,1fr)_1rem] items-center gap-2.5 rounded-control px-3 py-2 text-left",
|
||||
"transition-colors duration-150 settings-hover",
|
||||
formControlFocusClassName,
|
||||
)}
|
||||
>
|
||||
<span className={cn("h-1.5 w-1.5 shrink-0 rounded-full", statusClass)} aria-hidden />
|
||||
<span className="min-w-0">
|
||||
<span className="block truncate text-[13px] font-medium leading-5 text-foreground">
|
||||
{job.name || job.id}
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
"block truncate text-[11.5px] leading-4 text-muted-foreground",
|
||||
needsAttention && "text-destructive",
|
||||
)}
|
||||
title={needsAttention ? summary : nextRun.title}
|
||||
>
|
||||
{summary}
|
||||
</span>
|
||||
</span>
|
||||
<ChevronRight className="h-4 w-4 text-muted-foreground/65" aria-hidden />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -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<string | null>;
|
||||
pendingFirstMessage?: PendingFirstMessage & { id: string; chatId: string } | null;
|
||||
onPendingFirstMessageConsumed?: (id: string) => void;
|
||||
onForkChat?: (sourceChatId: string, beforeUserIndex: number) => Promise<string | null>;
|
||||
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<number | null>(null);
|
||||
const pendingFirstRef = useRef<PendingFirstMessage | null>(null);
|
||||
const [pendingFirstTargetChatId, setPendingFirstTargetChatId] = useState<string | null>(null);
|
||||
const consumedPendingFirstMessageIdRef = useRef<string | null>(null);
|
||||
const viewportRef = useRef<ThreadViewportHandle | null>(null);
|
||||
const activeViewportTurnByChatIdRef = useRef<Map<string, string>>(new Map());
|
||||
const knownTemporaryChatIdsRef = useRef(new Set<string>());
|
||||
@@ -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({
|
||||
</div>
|
||||
);
|
||||
const sessionInfoAction = historyKey ? (
|
||||
<SessionInfoPopover sessionKey={historyKey} token={token} title={title} />
|
||||
<SessionInfoPopover client={client} sessionKey={historyKey} token={token} title={title} />
|
||||
) : undefined;
|
||||
const promptNavigatorAction = historyKey ? (
|
||||
<PromptNavigator
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import type { ModelPresetOption } from "@/components/thread/ModelPresetBadge";
|
||||
import { inferProviderFromModelName, providerDisplayLabel } from "@/lib/provider-brand";
|
||||
import type { SettingsPayload } from "@/lib/types";
|
||||
|
||||
function compactModelName(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;
|
||||
}
|
||||
|
||||
export 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;
|
||||
const presets = settings.model_presets ?? [];
|
||||
if (scopedPreset) {
|
||||
return presets.find((preset) => 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,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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"
|
||||
},
|
||||
|
||||
@@ -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"
|
||||
},
|
||||
|
||||
@@ -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"
|
||||
},
|
||||
|
||||
@@ -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"
|
||||
},
|
||||
|
||||
@@ -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": "カスタムスケジュール"
|
||||
},
|
||||
|
||||
@@ -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": "사용자 지정 일정"
|
||||
},
|
||||
|
||||
@@ -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"
|
||||
},
|
||||
|
||||
@@ -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"
|
||||
},
|
||||
|
||||
@@ -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": "自定义计划"
|
||||
},
|
||||
|
||||
@@ -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": "自訂排程"
|
||||
},
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<React.ComponentProps<typeof AutomationsSettings>>;
|
||||
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(<Harness />);
|
||||
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(<Harness payload={{ jobs: [jobWithHistory] }} />);
|
||||
|
||||
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(<Harness
|
||||
payload={{ jobs: [] }}
|
||||
onStartChat={onStartChat}
|
||||
settingsSnapshot={modelSettings}
|
||||
/>);
|
||||
|
||||
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(<Harness payload={{ jobs: [] }} onStartChat={onStartChat} settingsSnapshot={modelSettings} />);
|
||||
|
||||
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(<Harness payload={{ jobs: [] }} onStartChat={onStartChat} settingsSnapshot={modelSettings} />);
|
||||
|
||||
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(<Harness payload={{ jobs: [] }} onStartChat={() => {}} 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(<Harness payload={{ jobs: [systemTask] }} />);
|
||||
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(<Harness payload={{ jobs: [{ ...task, delete_after_run: true,
|
||||
state: { last_status: "ok", next_run_at_ms: null } }] }} />);
|
||||
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(<Harness payload={{ jobs: [task, systemTask, {
|
||||
...systemTask, id: "dream", name: "dream",
|
||||
state: { last_status: "error", last_error: "Memory update failed" },
|
||||
}] }} />);
|
||||
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(<Harness payload={{ jobs: [task, outsideTask] }} />);
|
||||
|
||||
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(<Harness payload={{ jobs: [cronTask] }} />);
|
||||
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(<Harness />);
|
||||
@@ -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(<DeletionHarness />);
|
||||
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<SessionAutomationJob | null>(null);
|
||||
const [returning, setReturning] = useState<SessionAutomationJob | null>(null);
|
||||
return <>
|
||||
<Harness onRequestEdit={setEditing} />
|
||||
<Harness
|
||||
onRequestEdit={setEditing}
|
||||
returnToDetailJob={returning}
|
||||
onReturnToDetailHandled={() => setReturning(null)}
|
||||
/>
|
||||
<AutomationEditDialog job={editing} saving={false}
|
||||
onOpenChange={(open) => { if (!open) setEditing(null); }}
|
||||
onCancel={setReturning}
|
||||
onSave={(job, values) => { save(job, values); setEditing(null); }} />
|
||||
</>;
|
||||
}
|
||||
render(<EditorHarness />);
|
||||
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(<Harness payload={{ jobs: [{
|
||||
...task,
|
||||
state: {
|
||||
...task.state,
|
||||
last_status: "error",
|
||||
last_error: "legacy cron payload is missing channel/to; recreate it from a chat session",
|
||||
},
|
||||
}] }} />);
|
||||
|
||||
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(<Harness onAction={action} />);
|
||||
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(<Harness actionKey="run:private-job-id" />);
|
||||
for (const name of ["Edit", "Pause", "More actions"]) {
|
||||
for (const name of ["Edit", "Pause", "Run now", "Delete"]) {
|
||||
expect(screen.getByRole("button", { name })).toBeDisabled();
|
||||
}
|
||||
rerender(<Harness error="Unable to run task" />);
|
||||
@@ -585,9 +742,7 @@ describe("Automation task list and detail sheet", () => {
|
||||
const user = userEvent.setup();
|
||||
const { rerender } = render(<Harness payload={{ jobs: [{ ...task, state: { pending: true } }] }} />);
|
||||
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(<Harness payload={{ jobs: [{ ...task, enabled: false, origin: null }] }} />);
|
||||
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", () => {
|
||||
|
||||
@@ -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(
|
||||
<SessionInfoPopover
|
||||
client={client}
|
||||
sessionKey="websocket:chat-1"
|
||||
token="tok"
|
||||
title="Release work"
|
||||
@@ -66,8 +72,67 @@ describe("SessionInfoPopover", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
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(
|
||||
<SessionInfoPopover
|
||||
client={client}
|
||||
sessionKey="websocket:chat-1"
|
||||
token="tok"
|
||||
title="Release work"
|
||||
/>,
|
||||
);
|
||||
|
||||
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(
|
||||
<SessionInfoPopover
|
||||
client={client}
|
||||
sessionKey="websocket:chat-1"
|
||||
token="tok"
|
||||
title="Release work"
|
||||
/>,
|
||||
);
|
||||
|
||||
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(
|
||||
<SessionInfoPopover
|
||||
client={client}
|
||||
sessionKey="websocket:chat-1"
|
||||
token="tok"
|
||||
title="@hyperframes 使用指南"
|
||||
@@ -103,6 +169,7 @@ describe("SessionInfoPopover", () => {
|
||||
|
||||
render(
|
||||
<SessionInfoPopover
|
||||
client={client}
|
||||
sessionKey="websocket:chat-1"
|
||||
token="tok"
|
||||
title="Release work"
|
||||
@@ -140,6 +207,7 @@ describe("SessionInfoPopover", () => {
|
||||
|
||||
render(
|
||||
<SessionInfoPopover
|
||||
client={client}
|
||||
sessionKey="websocket:chat-1"
|
||||
token="tok"
|
||||
title="Release work"
|
||||
@@ -148,8 +216,12 @@ describe("SessionInfoPopover", () => {
|
||||
|
||||
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(
|
||||
<SessionInfoPopover
|
||||
client={client}
|
||||
sessionKey="websocket:chat-1"
|
||||
token="tok"
|
||||
title="Release work"
|
||||
@@ -192,6 +265,7 @@ describe("SessionInfoPopover", () => {
|
||||
|
||||
render(
|
||||
<SessionInfoPopover
|
||||
client={client}
|
||||
sessionKey="websocket:chat-1"
|
||||
token="tok"
|
||||
title="Release work"
|
||||
|
||||
@@ -208,27 +208,45 @@ describe("Settings system domains", () => {
|
||||
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);
|
||||
});
|
||||
|
||||
@@ -140,6 +140,7 @@ export function renderSettingsView(
|
||||
showSidebar?: boolean;
|
||||
onBackToChat?: () => void;
|
||||
onSettingsChange?: (payload: SettingsPayload) => void;
|
||||
onStartAutomationChat?: React.ComponentProps<typeof SettingsView>["onStartAutomationChat"];
|
||||
onNativeEngineRestart?: () => Promise<string>;
|
||||
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}
|
||||
/>
|
||||
|
||||
@@ -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,
|
||||
<StrictMode>
|
||||
<ThreadShell
|
||||
session={session("chat-new")}
|
||||
title="New automation chat"
|
||||
onToggleSidebar={() => {}}
|
||||
pendingFirstMessage={pendingFirstMessage}
|
||||
onPendingFirstMessageConsumed={consumed}
|
||||
/>
|
||||
</StrictMode>,
|
||||
),
|
||||
);
|
||||
|
||||
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");
|
||||
|
||||
Reference in new issue
Block a user