feat(webui): refine automation calendar workflows

This commit is contained in:
chengyongru authored and chengyongru committed 2026-09-13 05:43:05 +08:00
1 parent 98b0c3858b
commit 37e29c36e5
25 files changed
+1789 -487

No files matched your search

+223 -125
View File
@@ -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);
}
+35 -96
View File
@@ -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,
};
});
}