feat(webui): persist reviewed automation chat changes

This commit is contained in:
Xubin Ren committed 2026-10-07 01:12:23 +08:00
1 parent 707f7eb079
commit 845afe9215
41 files changed
+1210 -626

No files matched your search

@@ -121,6 +121,7 @@ export function SettingsPage({
handleApiServiceAction,
handleAutomationAction,
handleAutomationEdit,
handleAutomationChat,
handleCliAppAction,
handleDeleteModelConfiguration,
handleImportMcpConfig,
@@ -596,6 +597,7 @@ export function SettingsPage({
setAutomationPendingEdit(job);
}}
onRequestDelete={setAutomationPendingDelete}
onChangeChat={handleAutomationChat}
onManageModels={() => selectSection("models")}
returnToDetailJob={automationDetailReturn}
onReturnToDetailHandled={() => setAutomationDetailReturn(null)}
@@ -0,0 +1,138 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { ChannelLogo } from "@/components/settings/channels/ChannelIdentity";
import { channelUiOwner, channelUiPresentation } from "@/channel-plugins/registry";
import { channelTranslator } from "@/channel-plugins/i18n";
import { Button } from "@/components/ui/button";
import { DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { fetchAutomationChats } from "@/lib/api";
import { readLocalPreferences } from "@/lib/local-preferences";
import type { AutomationChat, AutomationChatsPayload, AutomationChatUpdate, NanobotFeatureInfo, SessionAutomationJob } from "@/lib/types";
export type ChangeAutomationChat = (job: SessionAutomationJob, values: AutomationChatUpdate) => Promise<void>;
function ChatIdentity({ chat }: { chat: AutomationChat }) {
const { t } = useTranslation();
const owner = channelUiOwner(chat.channel);
const presentation = channelUiPresentation(chat.channel);
const platform = chat.channel === "websocket" ? t("settings.automations.chat.web")
: channelTranslator(t, owner)("displayName", presentation?.displayName ?? chat.channel);
const feature: NanobotFeatureInfo = {
name: chat.channel, display_name: platform, type: "channel", enabled: true,
installed: true, ready: true, status: "ready", install_supported: false, requires_restart: false,
};
return <span className="flex min-w-0 items-center gap-2.5 text-start">
<span aria-hidden className="relative h-6 w-6 shrink-0">
{chat.channel === "websocket" ? <img src="/brand/nanobot_mark.svg" alt="" className="h-6 w-6" />
: <span className="absolute left-0 top-0 origin-top-left scale-75"><ChannelLogo feature={feature} showBrandLogos={readLocalPreferences().brandLogos} /></span>}
</span>
<span className="flex min-w-0 flex-wrap items-baseline gap-x-2 text-[13px] leading-5">
<span className="min-w-0 break-words">{chat.title}</span><span className="text-[12px] text-muted-foreground">{platform}</span>
</span>
</span>;
}
export function AutomationChatBinding({ job, token, onSave, children }: {
job: SessionAutomationJob; token: string; onSave: ChangeAutomationChat;
children: (picker: ReactNode) => ReactNode;
}) {
const { t } = useTranslation();
const tx = (key: string) => t(`settings.automations.chat.${key}`);
const [data, setData] = useState<AutomationChatsPayload | null>(null);
const [loadError, setLoadError] = useState(false);
const [reload, setReload] = useState(0);
const [draft, setDraft] = useState<{ target: string; revision: string; message: string } | null>(null);
const [saving, setSaving] = useState(false);
const [error, setError] = useState("");
const [saved, setSaved] = useState(false);
const heading = useRef<HTMLHeadingElement>(null);
const trigger = useRef<HTMLButtonElement>(null);
const returning = useRef(false);
useEffect(() => {
const controller = new AbortController();
setLoadError(false);
void fetchAutomationChats(token, job.id, controller.signal).then(value => {
if (!controller.signal.aborted) setData(value);
}).catch(() => { if (!controller.signal.aborted) setLoadError(true); });
return () => controller.abort();
}, [token, job.id, job.chat_binding_revision, reload]);
const reviewing = draft !== null;
useEffect(() => {
if (reviewing) heading.current?.focus();
else if (returning.current) { trigger.current?.focus(); returning.current = false; }
}, [reviewing]);
const back = () => { returning.current = true; setDraft(null); };
const current = data?.current;
const fallback: AutomationChat = { id: "current", title: job.origin?.title || tx("current"), channel: job.origin?.channel || "websocket" };
const locked = saving || Boolean(job.state.pending);
const picker = (review: boolean) => <Select value={review ? draft?.target : current?.id ?? "current"}
disabled={locked || !data?.chats.length || loadError || (!review && data.revision !== job.chat_binding_revision)} onValueChange={target => {
if (target === current?.id) return;
setError(""); setSaved(false);
setDraft(previous => previous ? { ...previous, target } : {
target, revision: job.chat_binding_revision!, message: job.payload.message,
});
}}>
<SelectTrigger ref={review ? undefined : trigger} aria-label={tx(review ? "new" : "label")}
className={`h-auto min-h-11 w-full py-2 [&>span:first-child]:min-w-0 [&>span:first-child]:flex-1 [&>span:first-child]:text-start ${review ? "" : "border-transparent bg-transparent hover:bg-muted/50"}`}>
<SelectValue><ChatIdentity chat={data?.chats.find(chat => chat.id === (review ? draft?.target : current?.id)) ?? fallback} /></SelectValue>
</SelectTrigger>
<SelectContent>
{!current ? <SelectItem value="current" disabled><ChatIdentity chat={fallback} /></SelectItem> : null}
{data?.chats.map(chat => <SelectItem key={chat.id} value={chat.id} textValue={`${chat.title} ${chat.channel}`}
disabled={chat.unavailable || (review && chat.id === current?.id)}
className="h-auto min-h-11 py-2 [&>span:last-child]:min-w-0 [&>span:last-child]:max-w-[calc(100vw-5rem)] [&>span:last-child]:w-full"><ChatIdentity chat={chat} /></SelectItem>)}
</SelectContent>
</Select>;
const save = async () => {
if (!draft || locked || !draft.message.trim()) return;
setSaving(true); setError("");
try {
await onSave(job, { target_id: draft.target, revision: draft.revision, message: draft.message });
setData(previous => previous ? { ...previous, current: previous.chats.find(chat => chat.id === draft.target) ?? null } : previous);
setSaved(true); back(); setReload(value => value + 1);
} catch (cause) {
const reasons: Record<string, string> = {
automation_chat_conflict: "conflict", automation_chat_busy: "schedulerBusy",
automation_chat_unavailable: "unavailable",
};
setError(tx(cause instanceof Error ? reasons[cause.message] ?? "failed" : "failed"));
} finally { setSaving(false); }
};
if (!draft) return children(<div className="space-y-1">
<div className="grid min-w-0 grid-cols-1 items-start gap-1 py-1 min-[420px]:grid-cols-[6rem_minmax(0,1fr)] min-[420px]:gap-4">
<span className="text-[13px] text-muted-foreground min-[420px]:pt-3">{tx("label")}</span>
{picker(false)}
</div>
<p role={saved ? "status" : undefined} className="text-[12px] leading-5 text-muted-foreground">
{job.state.pending ? tx("busy") : saved ? tx("saved") : tx("hint")}
</p>
{loadError ? <Button variant="link" size="sm" onClick={() => setReload(value => value + 1)}>{tx("retry")}</Button> : null}
{data && data.chats.length <= (current ? 1 : 0) ? <p className="text-[12px] leading-5 text-muted-foreground">{tx("available")}</p> : null}
</div>);
return <>
<DialogHeader className="shrink-0 px-6 pb-4 pr-12 pt-5 text-left">
<DialogTitle ref={heading} tabIndex={-1} className="text-lg font-medium leading-snug tracking-normal outline-none">{tx("change")}</DialogTitle>
</DialogHeader>
<div className="min-h-0 space-y-4 overflow-y-auto overscroll-contain px-6">
<div className="space-y-2">
{picker(true)}
<p className="text-[12px] leading-5 text-muted-foreground">{tx("previous")} {current?.title || fallback.title}</p>
<p className="text-[13px] leading-5">{tx("effect")}</p>
</div>
<label className="block space-y-2"><span className="text-[13px] font-medium">{tx("message")}</span>
<Textarea rows={3} value={draft.message} disabled={saving} onChange={event => setDraft({ ...draft, message: event.target.value })}
className="min-h-20 resize-y text-base leading-6 sm:text-[13px] sm:leading-5" />
</label>
<p className="text-[12px] leading-5 text-muted-foreground">{tx("review")}</p>
<p className="text-[12px] leading-5 text-muted-foreground">{tx("history")}</p>
{error ? <p role="alert" className="text-[12px] leading-5 text-destructive">{error}</p> : null}
</div>
<DialogFooter className="shrink-0 flex-row justify-end gap-2 px-6 pb-5 pt-3">
<Button variant="ghost" size="sm" disabled={saving} className="h-11 font-normal text-muted-foreground sm:h-9" onClick={back}>{t("settings.automations.cancel")}</Button>
<Button size="sm" className="h-11 sm:h-9" disabled={locked || !draft.message.trim()} aria-busy={saving} onClick={() => void save()}>{tx(saving ? "saving" : "confirm")}</Button>
</DialogFooter>
</>;
}
@@ -8,12 +8,14 @@ import {
Clipboard,
ListFilter,
Loader2,
MoreHorizontal,
} 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 { AutomationChatBinding, type ChangeAutomationChat } from "@/components/settings/system/AutomationChatBinding";
import { AutomationRunAtPicker, parseAutomationRunAt } from "@/components/settings/system/AutomationRunAtPicker";
import {
modelPresetOptionsFromSettings,
@@ -23,7 +25,7 @@ import { ThreadComposer } from "@/components/thread/ThreadComposer";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { DropdownMenu, DropdownMenuContent, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { ExpandableText } from "@/components/ui/expandable-text";
import {
Dialog,
@@ -62,6 +64,7 @@ export function AutomationsSettings({
onFilterChange, onAction,
onRequestEdit, onRequestDelete, onStartChat, onManageModels,
returnToDetailJob = null, onReturnToDetailHandled,
onChangeChat,
}: {
token?: string;
payload: AutomationsPayload | null;
@@ -84,6 +87,7 @@ export function AutomationsSettings({
onManageModels?: () => void;
returnToDetailJob?: SessionAutomationJob | null;
onReturnToDetailHandled?: () => void;
onChangeChat?: ChangeAutomationChat;
}) {
const { t, i18n } = useTranslation();
const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>
@@ -362,6 +366,8 @@ export function AutomationsSettings({
</div>
<AutomationDetailDialog
token={token}
onChangeChat={onChangeChat}
job={selectedJob}
open={detailOpen}
locale={locale}
@@ -388,6 +394,8 @@ export function AutomationsSettings({
}
export function AutomationDetailDialog({
token = "",
onChangeChat,
job,
open,
locale,
@@ -399,6 +407,8 @@ export function AutomationDetailDialog({
onRequestDelete,
onCloseAutoFocus,
}: {
token?: string;
onChangeChat?: ChangeAutomationChat;
job: SessionAutomationJob | null;
open: boolean;
locale: string;
@@ -410,6 +420,11 @@ export function AutomationDetailDialog({
onRequestDelete: (job: SessionAutomationJob) => void;
onCloseAutoFocus?: (event: Event) => void;
}) {
const panel = (chatPicker?: ReactNode) => job ? <AutomationDetailPanel
key={job.id} job={job} locale={locale} actionKey={actionKey} error={error}
onAction={onAction} onRequestEdit={onRequestEdit} onRequestDelete={onRequestDelete}
chatPicker={chatPicker}
/> : null;
return (
<Dialog open={open} onOpenChange={onOpenChange}>
{job ? (
@@ -422,16 +437,9 @@ export function AutomationDetailDialog({
)}
onCloseAutoFocus={onCloseAutoFocus}
>
<AutomationDetailPanel
key={job.id}
job={job}
locale={locale}
actionKey={actionKey}
error={error}
onAction={onAction}
onRequestEdit={onRequestEdit}
onRequestDelete={onRequestDelete}
/>
{job.chat_binding_revision && onChangeChat ? (
<AutomationChatBinding key={job.id} job={job} token={token} onSave={onChangeChat}>{panel}</AutomationChatBinding>
) : panel()}
</DialogContent>
) : null}
</Dialog>
@@ -441,7 +449,9 @@ export function AutomationDetailDialog({
function AutomationDetailPanel({
job, locale, actionKey, error, onAction, onRequestEdit, onRequestDelete,
chatPicker,
}: {
chatPicker?: ReactNode;
job: SessionAutomationJob;
locale: string;
actionKey: string | null;
@@ -552,44 +562,28 @@ function AutomationDetailPanel({
</section> : null}
{job.state.last_error ? <AutomationError message={job.state.last_error} /> : null}
{error ? <AutomationError message={error} /> : null}
<dl>
{chatPicker ?? <dl>
{!job.protected && job.origin?.channel && job.origin.channel !== "websocket" ? (
<AutomationDetail label={tx("settings.automations.labels.origin", "Linked chat")}>
{automationChannelLabel(job.origin.channel, t)}
</AutomationDetail>
) : null}
</dl>
</dl>}
</div>
{canManage ? (
<div className="flex shrink-0 flex-wrap items-center gap-x-6 gap-y-2 border-t border-border/45 px-6 py-3">
<div className="flex max-w-full flex-wrap gap-2">
<Button variant="ghost" size="sm" className="font-normal text-muted-foreground" disabled={busy || !canToggle}
onClick={() => void onAction(job.enabled ? "disable" : "enable", job)}>
{actionKey === `enable:${job.id}` || actionKey === `disable:${job.id}`
? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden /> : null}
{job.enabled ? tx("settings.automations.pause", "Disable") : tx("settings.automations.resume", "Enable")}
</Button>
{!localTrigger ? (
<Button variant="ghost" size="sm" className="font-normal 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="font-normal text-muted-foreground hover:bg-destructive/10 hover:text-destructive focus-visible:text-destructive"
disabled={busy}
onClick={() => onRequestDelete(job)}
>
{tx("settings.automations.delete", "Delete")}
</Button>
</div>
<div className="ms-auto flex max-w-full flex-wrap justify-end gap-2">
<Button variant="ghost" size="sm" className="font-normal text-muted-foreground" disabled={busy} onClick={() => onRequestEdit(job)}>
{tx("settings.automations.edit", "Edit")}
</Button>
{originHref ? <Button asChild variant="ghost" size="sm" className="font-normal text-muted-foreground"><a href={originHref}>{tx("settings.automations.emptyAction", "Open a chat")}</a></Button> : null}
<div className="flex shrink-0 items-center gap-2 border-t border-border/45 px-6 py-3">
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild><Button size="icon" variant="ghost" disabled={busy} aria-label={tx("settings.automations.moreActions", "More actions")} className="h-11 w-11 text-muted-foreground sm:h-9 sm:w-9"><MoreHorizontal className="h-4 w-4" aria-hidden /></Button></DropdownMenuTrigger>
<DropdownMenuContent side="top" align="start">
<DropdownMenuItem disabled={busy || !canToggle} onSelect={() => void onAction(job.enabled ? "disable" : "enable", job)}>{job.enabled ? tx("settings.automations.pause", "Disable") : tx("settings.automations.resume", "Enable")}</DropdownMenuItem>
{originHref ? <DropdownMenuItem asChild><a href={originHref}>{tx("settings.automations.emptyAction", "Open a chat")}</a></DropdownMenuItem> : null}
<DropdownMenuSeparator />
<DropdownMenuItem tone="destructive" disabled={busy} onSelect={() => onRequestDelete(job)}>{tx("settings.automations.delete", "Delete")}</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<div className="ml-auto flex gap-2">
<Button variant="ghost" size="sm" className="h-11 font-normal sm:h-9" disabled={busy} onClick={() => onRequestEdit(job)}>{tx("settings.automations.edit", "Edit")}</Button>
{!localTrigger ? <Button variant="secondary" size="sm" className="h-11 font-normal sm:h-9" disabled={busy || !canRun} onClick={() => void onAction("run", job)}>{tx("settings.automations.runNow", "Run now")}</Button> : null}
</div>
</div>
) : null}
@@ -11,6 +11,7 @@ import { DEFAULT_CUSTOM_MCP_FORM } from "@/components/settings/system/AppsSettin
import type { SystemSettingsState } from "@/components/settings/system/useSystemSettingsState";
import {
cancelMcpOAuth,
changeAutomationChat,
completeMcpOAuth,
disableNanobotFeature,
enableNanobotFeature,
@@ -34,6 +35,7 @@ import { notifyMcpPresetsChanged } from "@/lib/mcp-preset-events";
import type { NanobotClient } from "@/lib/nanobot-client";
import type {
AutomationUpdatePayload,
AutomationChatUpdate,
McpOAuthFlowPayload,
McpPresetsPayload,
NanobotFeatureInfo,
@@ -298,6 +300,12 @@ export function createSystemSettingsActions({
}
};
const handleAutomationChat = async (job: SessionAutomationJob, values: AutomationChatUpdate) => {
// The dialog owns the draft and error. Publish only the server acknowledgement.
const payload = await changeAutomationChat(client, job.id, values);
setAutomations(payload);
};
const closeMcpOAuthPopup = () => {
const popup = mcpOAuthPopupRef.current;
mcpOAuthPopupRef.current = null;
@@ -668,6 +676,7 @@ export function createSystemSettingsActions({
handleApiServiceAction,
handleAutomationAction,
handleAutomationEdit,
handleAutomationChat,
handleCliAppAction,
handleImportMcpConfig,
handleMcpOAuthCancel,
@@ -476,6 +476,7 @@ export function useSettingsController({
handleApiServiceAction,
handleAutomationAction,
handleAutomationEdit,
handleAutomationChat,
handleCliAppAction,
handleImportMcpConfig,
handleMcpOAuthCancel,
@@ -526,6 +527,7 @@ export function useSettingsController({
handleApiServiceAction,
handleAutomationAction,
handleAutomationEdit,
handleAutomationChat,
handleCliAppAction,
handleDeleteModelConfiguration,
handleImportMcpConfig,