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
@@ -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,
|
||||
};
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user