feat(webui): persist reviewed automation chat changes
This commit is contained in:
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,
|
||||
|
||||
@@ -1394,6 +1394,29 @@
|
||||
"notEnabled": "Not enabled"
|
||||
},
|
||||
"automations": {
|
||||
"chat": {
|
||||
"conflict": "The task changed elsewhere. Your draft is kept. Reopen the task to review the latest settings.",
|
||||
"unavailable": "This chat is no longer available with the same workspace and access mode. Select another chat.",
|
||||
"schedulerBusy": "A task is running or queued. Wait for it to finish, then try again.",
|
||||
"label": "Task chat",
|
||||
"new": "New chat",
|
||||
"current": "Current chat",
|
||||
"web": "Web chat",
|
||||
"change": "Change chat",
|
||||
"previous": "Previous chat:",
|
||||
"hint": "Uses this chat’s history. Results return here by default.",
|
||||
"effect": "Future runs will use the new chat’s history and send results there by default.",
|
||||
"message": "Task instructions",
|
||||
"review": "Check for instructions that send to another chat. People in the new chat may see the task and its results.",
|
||||
"history": "Old messages stay in the old chat. The schedule stays the same. This does not run the task.",
|
||||
"busy": "Cannot change while this task is running or queued.",
|
||||
"saved": "Changed. Applies to future runs.",
|
||||
"failed": "Could not confirm the change. Your draft is kept.",
|
||||
"retry": "Retry loading chats",
|
||||
"confirm": "Confirm change",
|
||||
"saving": "Changing…",
|
||||
"available": "To add a chat, send nanobot a message there first. Only connected chats with the same workspace and access mode are listed."
|
||||
},
|
||||
"taskInfo": "Task information",
|
||||
"runDetails": {
|
||||
"loading": "Loading response…",
|
||||
|
||||
@@ -1195,6 +1195,29 @@
|
||||
"notEnabled": "No activado"
|
||||
},
|
||||
"automations": {
|
||||
"chat": {
|
||||
"conflict": "La tarea cambió en otro lugar. Se conserva el borrador. Abre la tarea de nuevo para revisar los ajustes.",
|
||||
"unavailable": "Este chat ya no está disponible con el mismo espacio de trabajo y modo de acceso. Elige otro chat.",
|
||||
"schedulerBusy": "Hay una tarea en ejecución o en cola. Espera a que termine e inténtalo de nuevo.",
|
||||
"label": "Chat de la tarea",
|
||||
"new": "Nuevo chat",
|
||||
"current": "Chat actual",
|
||||
"web": "Chat web",
|
||||
"change": "Cambiar chat",
|
||||
"previous": "Chat anterior:",
|
||||
"hint": "Usa el historial de este chat. Los resultados se envían aquí por defecto.",
|
||||
"effect": "Las próximas ejecuciones usarán el historial del nuevo chat y enviarán allí los resultados por defecto.",
|
||||
"message": "Instrucciones de la tarea",
|
||||
"review": "Revisa las instrucciones que envíen a otro chat. Los miembros del nuevo chat pueden ver la tarea y sus resultados.",
|
||||
"history": "Los mensajes anteriores permanecen en el chat original. El horario no cambia. La tarea no se ejecuta ahora.",
|
||||
"busy": "No se puede cambiar mientras la tarea se ejecuta o espera en la cola.",
|
||||
"saved": "Cambiado. Se aplica a las próximas ejecuciones.",
|
||||
"failed": "No se pudo confirmar el cambio. Se conserva el borrador.",
|
||||
"retry": "Volver a cargar chats",
|
||||
"confirm": "Confirmar cambio",
|
||||
"saving": "Cambiando…",
|
||||
"available": "Primero envía un mensaje a nanobot en el chat de destino. Solo se muestran chats conectados con el mismo espacio de trabajo y modo de acceso."
|
||||
},
|
||||
"taskInfo": "Información de la tarea",
|
||||
"runDetails": {
|
||||
"loading": "Cargando respuesta…",
|
||||
|
||||
@@ -1194,6 +1194,29 @@
|
||||
"notEnabled": "Non activé"
|
||||
},
|
||||
"automations": {
|
||||
"chat": {
|
||||
"conflict": "La tâche a été modifiée ailleurs. Le brouillon est conservé. Rouvrez la tâche pour vérifier ses paramètres.",
|
||||
"unavailable": "Cette discussion n’est plus disponible avec le même espace de travail et mode d’accès. Choisissez-en une autre.",
|
||||
"schedulerBusy": "Une tâche est en cours ou en attente. Attendez la fin, puis réessayez.",
|
||||
"label": "Discussion de la tâche",
|
||||
"new": "Nouvelle discussion",
|
||||
"current": "Discussion actuelle",
|
||||
"web": "Discussion web",
|
||||
"change": "Changer de discussion",
|
||||
"previous": "Ancienne discussion :",
|
||||
"hint": "Utilise l’historique de cette discussion et y envoie les résultats par défaut.",
|
||||
"effect": "Les prochaines exécutions utiliseront l’historique de la nouvelle discussion et y enverront les résultats par défaut.",
|
||||
"message": "Instructions de la tâche",
|
||||
"review": "Vérifiez les instructions qui envoient vers une autre discussion. Les membres de la nouvelle discussion peuvent voir la tâche et ses résultats.",
|
||||
"history": "Les anciens messages restent dans la discussion d’origine. L’horaire ne change pas. La tâche ne démarre pas maintenant.",
|
||||
"busy": "Modification impossible si la tâche est en cours ou en attente.",
|
||||
"saved": "Modifié. S’applique aux prochaines exécutions.",
|
||||
"failed": "Impossible de confirmer la modification. Le brouillon est conservé.",
|
||||
"retry": "Recharger les discussions",
|
||||
"confirm": "Confirmer",
|
||||
"saving": "Modification…",
|
||||
"available": "Envoyez d’abord un message à nanobot dans la discussion cible. Seules les discussions connectées avec le même espace de travail et mode d’accès sont proposées."
|
||||
},
|
||||
"taskInfo": "Informations sur la tâche",
|
||||
"runDetails": {
|
||||
"loading": "Chargement de la réponse…",
|
||||
|
||||
@@ -1194,6 +1194,29 @@
|
||||
"notEnabled": "Belum aktif"
|
||||
},
|
||||
"automations": {
|
||||
"chat": {
|
||||
"conflict": "Tugas diubah di tempat lain. Draf disimpan. Buka ulang tugas untuk memeriksa pengaturan terbaru.",
|
||||
"unavailable": "Chat ini tidak tersedia lagi dengan ruang kerja dan mode akses yang sama. Pilih chat lain.",
|
||||
"schedulerBusy": "Ada tugas berjalan atau mengantre. Tunggu hingga selesai, lalu coba lagi.",
|
||||
"label": "Chat tugas",
|
||||
"new": "Chat baru",
|
||||
"current": "Chat saat ini",
|
||||
"web": "Chat web",
|
||||
"change": "Ganti chat",
|
||||
"previous": "Chat sebelumnya:",
|
||||
"hint": "Menggunakan riwayat chat ini. Hasil dikirim ke sini secara default.",
|
||||
"effect": "Pelaksanaan berikutnya menggunakan riwayat chat baru dan mengirim hasil ke sana secara default.",
|
||||
"message": "Instruksi tugas",
|
||||
"review": "Periksa instruksi yang mengirim ke chat lain. Anggota chat baru mungkin dapat melihat tugas dan hasilnya.",
|
||||
"history": "Pesan lama tetap di chat asal. Jadwal tidak berubah. Tugas tidak dijalankan sekarang.",
|
||||
"busy": "Tidak dapat diganti saat tugas berjalan atau mengantre.",
|
||||
"saved": "Diganti. Berlaku untuk pelaksanaan berikutnya.",
|
||||
"failed": "Perubahan belum dapat dikonfirmasi. Draf disimpan.",
|
||||
"retry": "Muat ulang chat",
|
||||
"confirm": "Konfirmasi perubahan",
|
||||
"saving": "Mengganti…",
|
||||
"available": "Kirim pesan ke nanobot di chat tujuan terlebih dahulu. Hanya chat terhubung dengan ruang kerja dan mode akses yang sama yang ditampilkan."
|
||||
},
|
||||
"taskInfo": "Informasi tugas",
|
||||
"runDetails": {
|
||||
"loading": "Memuat respons…",
|
||||
|
||||
@@ -1194,6 +1194,29 @@
|
||||
"notEnabled": "無効"
|
||||
},
|
||||
"automations": {
|
||||
"chat": {
|
||||
"conflict": "タスクが別の場所で変更されました。下書きは保持されています。タスクを開き直して最新の設定を確認してください。",
|
||||
"unavailable": "このチャットは利用できないか、作業場所や権限が変わりました。別のチャットを選んでください。",
|
||||
"schedulerBusy": "実行中または待機中のタスクがあります。完了後に再試行してください。",
|
||||
"label": "タスクのチャット",
|
||||
"new": "新しいチャット",
|
||||
"current": "現在のチャット",
|
||||
"web": "Webチャット",
|
||||
"change": "チャットを変更",
|
||||
"previous": "変更前:",
|
||||
"hint": "このチャットの履歴を使い、通常はここに結果を送ります。",
|
||||
"effect": "今後の実行では新しいチャットの履歴を使い、通常はそこに結果を送ります。",
|
||||
"message": "タスクの指示",
|
||||
"review": "別のチャットへの送信指示が残っていないか確認してください。新しいチャットの参加者にタスクと結果が見える場合があります。",
|
||||
"history": "過去のメッセージは元のチャットに残ります。実行時刻は変わらず、今すぐ実行もしません。",
|
||||
"busy": "実行中または待機中のタスクは変更できません。",
|
||||
"saved": "変更しました。次回から適用されます。",
|
||||
"failed": "変更を確認できませんでした。下書きは保存されています。",
|
||||
"retry": "チャットを再読込",
|
||||
"confirm": "変更を確定",
|
||||
"saving": "変更中…",
|
||||
"available": "先に対象のチャットで nanobot にメッセージを送ってください。同じ作業場所と権限で接続中のチャットのみ表示されます。"
|
||||
},
|
||||
"taskInfo": "タスク情報",
|
||||
"runDetails": {
|
||||
"loading": "応答を読み込み中…",
|
||||
|
||||
@@ -1194,6 +1194,29 @@
|
||||
"notEnabled": "비활성화됨"
|
||||
},
|
||||
"automations": {
|
||||
"chat": {
|
||||
"conflict": "다른 곳에서 작업이 변경되었습니다. 초안은 유지됩니다. 작업을 다시 열어 최신 설정을 확인하세요.",
|
||||
"unavailable": "이 채팅을 사용할 수 없거나 작업 공간 또는 권한이 변경되었습니다. 다른 채팅을 선택하세요.",
|
||||
"schedulerBusy": "실행 중이거나 대기 중인 작업이 있습니다. 완료 후 다시 시도하세요.",
|
||||
"label": "작업 채팅",
|
||||
"new": "새 채팅",
|
||||
"current": "현재 채팅",
|
||||
"web": "웹 채팅",
|
||||
"change": "채팅 변경",
|
||||
"previous": "이전 채팅:",
|
||||
"hint": "이 채팅의 기록을 사용하며 결과도 기본적으로 여기로 보냅니다.",
|
||||
"effect": "다음 실행부터 새 채팅의 기록을 사용하며 결과도 기본적으로 그곳으로 보냅니다.",
|
||||
"message": "작업 지침",
|
||||
"review": "다른 채팅으로 보내라는 지침이 있는지 확인하세요. 새 채팅의 참여자가 작업 내용과 결과를 볼 수 있습니다.",
|
||||
"history": "이전 메시지는 원래 채팅에 남습니다. 일정은 유지되며 지금 실행하지 않습니다.",
|
||||
"busy": "작업이 실행 중이거나 대기 중이면 변경할 수 없습니다.",
|
||||
"saved": "변경했습니다. 다음 실행부터 적용됩니다.",
|
||||
"failed": "변경을 확인하지 못했습니다. 초안은 유지됩니다.",
|
||||
"retry": "채팅 다시 불러오기",
|
||||
"confirm": "변경 확인",
|
||||
"saving": "변경 중…",
|
||||
"available": "먼저 대상 채팅에서 nanobot에 메시지를 보내세요. 같은 작업 공간과 접근 권한을 가진 연결된 채팅만 표시됩니다."
|
||||
},
|
||||
"taskInfo": "작업 정보",
|
||||
"runDetails": {
|
||||
"loading": "응답을 불러오는 중…",
|
||||
|
||||
@@ -1208,6 +1208,29 @@
|
||||
"notEnabled": "Não habilitado"
|
||||
},
|
||||
"automations": {
|
||||
"chat": {
|
||||
"conflict": "A tarefa foi alterada em outro lugar. O rascunho foi mantido. Abra a tarefa novamente para conferir os ajustes.",
|
||||
"unavailable": "Esta conversa não está mais disponível com o mesmo espaço de trabalho e modo de acesso. Escolha outra conversa.",
|
||||
"schedulerBusy": "Há uma tarefa em execução ou na fila. Aguarde a conclusão e tente novamente.",
|
||||
"label": "Conversa da tarefa",
|
||||
"new": "Nova conversa",
|
||||
"current": "Conversa atual",
|
||||
"web": "Conversa web",
|
||||
"change": "Mudar conversa",
|
||||
"previous": "Conversa anterior:",
|
||||
"hint": "Usa o histórico desta conversa. Os resultados são enviados aqui por padrão.",
|
||||
"effect": "As próximas execuções usarão o histórico da nova conversa e enviarão os resultados para lá por padrão.",
|
||||
"message": "Instruções da tarefa",
|
||||
"review": "Confira instruções que enviam para outra conversa. Os membros da nova conversa podem ver a tarefa e seus resultados.",
|
||||
"history": "As mensagens antigas ficam na conversa original. O horário não muda. A tarefa não será executada agora.",
|
||||
"busy": "Não é possível mudar enquanto a tarefa está em execução ou na fila.",
|
||||
"saved": "Alterado. Vale para as próximas execuções.",
|
||||
"failed": "Não foi possível confirmar a alteração. O rascunho foi mantido.",
|
||||
"retry": "Recarregar conversas",
|
||||
"confirm": "Confirmar alteração",
|
||||
"saving": "Alterando…",
|
||||
"available": "Primeiro envie uma mensagem ao nanobot na conversa de destino. Só são listadas conversas conectadas com o mesmo espaço de trabalho e modo de acesso."
|
||||
},
|
||||
"taskInfo": "Informações da tarefa",
|
||||
"runDetails": {
|
||||
"loading": "Carregando resposta…",
|
||||
|
||||
@@ -1194,6 +1194,29 @@
|
||||
"notEnabled": "Chưa bật"
|
||||
},
|
||||
"automations": {
|
||||
"chat": {
|
||||
"conflict": "Tác vụ đã được đổi ở nơi khác. Bản nháp được giữ lại. Mở lại tác vụ để kiểm tra cài đặt mới nhất.",
|
||||
"unavailable": "Cuộc trò chuyện này không còn khả dụng với cùng không gian làm việc và quyền truy cập. Hãy chọn cuộc trò chuyện khác.",
|
||||
"schedulerBusy": "Có tác vụ đang chạy hoặc chờ. Hãy đợi hoàn tất rồi thử lại.",
|
||||
"label": "Cuộc trò chuyện của tác vụ",
|
||||
"new": "Cuộc trò chuyện mới",
|
||||
"current": "Cuộc trò chuyện hiện tại",
|
||||
"web": "Trò chuyện web",
|
||||
"change": "Đổi cuộc trò chuyện",
|
||||
"previous": "Cuộc trò chuyện cũ:",
|
||||
"hint": "Dùng lịch sử trò chuyện này. Mặc định kết quả được gửi về đây.",
|
||||
"effect": "Các lần chạy sau sẽ dùng lịch sử trò chuyện mới và mặc định gửi kết quả đến đó.",
|
||||
"message": "Hướng dẫn tác vụ",
|
||||
"review": "Kiểm tra hướng dẫn gửi đến cuộc trò chuyện khác. Thành viên trong cuộc trò chuyện mới có thể thấy tác vụ và kết quả.",
|
||||
"history": "Tin nhắn cũ vẫn ở cuộc trò chuyện cũ. Lịch chạy không đổi. Tác vụ không chạy ngay.",
|
||||
"busy": "Không thể đổi khi tác vụ đang chạy hoặc chờ trong hàng đợi.",
|
||||
"saved": "Đã đổi. Áp dụng từ lần chạy tiếp theo.",
|
||||
"failed": "Chưa thể xác nhận thay đổi. Bản nháp được giữ lại.",
|
||||
"retry": "Tải lại cuộc trò chuyện",
|
||||
"confirm": "Xác nhận thay đổi",
|
||||
"saving": "Đang đổi…",
|
||||
"available": "Trước tiên hãy gửi tin nhắn cho nanobot trong cuộc trò chuyện đích. Chỉ hiển thị cuộc trò chuyện đã kết nối, có cùng không gian làm việc và chế độ truy cập."
|
||||
},
|
||||
"taskInfo": "Thông tin tác vụ",
|
||||
"runDetails": {
|
||||
"loading": "Đang tải phản hồi…",
|
||||
|
||||
@@ -1394,6 +1394,29 @@
|
||||
"notEnabled": "未启用"
|
||||
},
|
||||
"automations": {
|
||||
"chat": {
|
||||
"conflict": "任务已在别处修改,草稿已保留。请重新打开任务,核对最新设置后再更换。",
|
||||
"unavailable": "这个聊天已不可用,或工作目录、权限已改变。请选择其他聊天。",
|
||||
"schedulerBusy": "有任务正在执行或排队。请等任务结束后再试。",
|
||||
"label": "任务所在聊天",
|
||||
"new": "新聊天",
|
||||
"current": "当前聊天",
|
||||
"web": "网页聊天",
|
||||
"change": "更换聊天",
|
||||
"previous": "原聊天:",
|
||||
"hint": "使用这里的聊天记录,结果也默认发到这里。",
|
||||
"effect": "后续任务会使用新聊天的记录,结果也默认发到这里。",
|
||||
"message": "任务说明",
|
||||
"review": "请检查并移除发往其他聊天的旧指令。新聊天的成员可能看到任务内容和结果。",
|
||||
"history": "旧消息留在原聊天。执行时间不变,也不会立即运行。",
|
||||
"busy": "任务正在执行或排队,暂时不能更换。",
|
||||
"saved": "已更换,下次执行生效。",
|
||||
"failed": "未能确认更换成功,草稿已保留。",
|
||||
"retry": "重新加载聊天",
|
||||
"confirm": "确认并更换",
|
||||
"saving": "正在更换…",
|
||||
"available": "先在目标聊天给 nanobot 发一条消息。这里只列出已连接、工作目录和权限相同的聊天。"
|
||||
},
|
||||
"taskInfo": "任务信息",
|
||||
"runDetails": {
|
||||
"loading": "正在加载回复…",
|
||||
|
||||
@@ -1194,6 +1194,29 @@
|
||||
"notEnabled": "未啟用"
|
||||
},
|
||||
"automations": {
|
||||
"chat": {
|
||||
"conflict": "任務已在別處修改,草稿已保留。請重新開啟任務,確認最新設定後再更換。",
|
||||
"unavailable": "這個聊天已無法使用,或工作目錄、權限已變更。請選擇其他聊天。",
|
||||
"schedulerBusy": "有任務正在執行或排隊。請等任務結束後再試。",
|
||||
"label": "任務所在聊天",
|
||||
"new": "新聊天",
|
||||
"current": "目前聊天",
|
||||
"web": "網頁聊天",
|
||||
"change": "更換聊天",
|
||||
"previous": "原聊天:",
|
||||
"hint": "使用這裡的聊天記錄,結果也預設傳到這裡。",
|
||||
"effect": "之後的任務會使用新聊天的記錄,結果也預設傳到那裡。",
|
||||
"message": "任務說明",
|
||||
"review": "請檢查並移除傳往其他聊天的舊指令。新聊天的成員可能看到任務內容和結果。",
|
||||
"history": "舊訊息留在原聊天。執行時間不變,也不會立即執行。",
|
||||
"busy": "任務正在執行或排隊,暫時無法更換。",
|
||||
"saved": "已更換,下次執行生效。",
|
||||
"failed": "無法確認更換成功,草稿已保留。",
|
||||
"retry": "重新載入聊天",
|
||||
"confirm": "確認並更換",
|
||||
"saving": "正在更換…",
|
||||
"available": "先在目標聊天傳一則訊息給 nanobot。這裡只列出已連線、工作目錄和權限相同的聊天。"
|
||||
},
|
||||
"taskInfo": "任務資訊",
|
||||
"runDetails": {
|
||||
"loading": "正在載入回覆…",
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import type {
|
||||
ApiServicePayload,
|
||||
AutomationChatsPayload,
|
||||
AutomationChatUpdate,
|
||||
AutomationsPayload,
|
||||
AutomationUpdatePayload,
|
||||
ChannelConfigurePayload,
|
||||
@@ -521,6 +523,14 @@ export async function fetchAutomations(
|
||||
);
|
||||
}
|
||||
|
||||
export async function fetchAutomationChats(token: string, id: string, signal?: AbortSignal): Promise<AutomationChatsPayload> {
|
||||
return request(`/api/webui/automations/chats?id=${encodeURIComponent(id)}`, token, { signal }, API_READ_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
export async function changeAutomationChat(transport: WebUIMutationTransport, id: string, values: AutomationChatUpdate): Promise<AutomationsPayload> {
|
||||
return mutation(transport, "automation.change_chat", { id, values });
|
||||
}
|
||||
|
||||
export async function fetchAutomationRunResult(
|
||||
token: string,
|
||||
id: string,
|
||||
|
||||
@@ -220,6 +220,7 @@ interface UISessionMessage {
|
||||
}
|
||||
|
||||
export interface SessionAutomationJob {
|
||||
chat_binding_revision?: string;
|
||||
id: string;
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
@@ -268,6 +269,13 @@ export interface SessionAutomationJob {
|
||||
|
||||
export interface SessionAutomationsPayload { jobs: SessionAutomationJob[]; }
|
||||
export interface AutomationsPayload { jobs: SessionAutomationJob[]; }
|
||||
export interface AutomationChat { id: string; title: string; channel: string; unavailable?: boolean; }
|
||||
export interface AutomationChatsPayload {
|
||||
revision: string;
|
||||
current: AutomationChat | null;
|
||||
chats: AutomationChat[];
|
||||
}
|
||||
export interface AutomationChatUpdate { target_id: string; revision: string; message: string; }
|
||||
export interface AutomationUpdatePayload {
|
||||
name?: string;
|
||||
message?: string;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
changeAutomationChat,
|
||||
cancelMcpOAuth,
|
||||
configureChannel,
|
||||
completeMcpOAuth,
|
||||
@@ -13,6 +14,7 @@ import {
|
||||
fetchFilePreview,
|
||||
fetchFilePreviewAvailability,
|
||||
fetchAutomations,
|
||||
fetchAutomationChats,
|
||||
fetchAutomationRunResult,
|
||||
fetchApiService,
|
||||
fetchCliApps,
|
||||
@@ -377,6 +379,20 @@ describe("webui API helpers", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("reads chat choices over HTTP and commits the opaque choice over WebSocket", async () => {
|
||||
const controller = new AbortController();
|
||||
await fetchAutomationChats("tok", "task/id", controller.signal);
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"/api/webui/automations/chats?id=task%2Fid",
|
||||
expect.objectContaining({ headers: { Authorization: "Bearer tok" }, signal: expect.any(AbortSignal) }),
|
||||
);
|
||||
vi.mocked(fetch).mockClear();
|
||||
const values = { target_id: "opaque-id", revision: "reviewed-version", message: "Reviewed prompt" };
|
||||
await changeAutomationChat(mutationTransport, "task/id", values);
|
||||
expect(requestMutation).toHaveBeenCalledWith("automation.change_chat", { id: "task/id", values }, 20_000);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("validates channel settings with form values", async () => {
|
||||
await validateChannel(
|
||||
mutationTransport,
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { AutomationDetailDialog } from "@/components/settings/system/AutomationsSettings";
|
||||
import { fetchAutomationChats } from "@/lib/api";
|
||||
import type { AutomationChatsPayload, SessionAutomationJob } from "@/lib/types";
|
||||
|
||||
vi.mock("@/lib/api", () => ({ fetchAutomationChats: vi.fn() }));
|
||||
const source = { id: "source", title: "My planning", channel: "websocket" };
|
||||
const target = { id: "target", title: "Product team", channel: "telegram" };
|
||||
const choices: AutomationChatsPayload = { revision: "rev-1", current: source, chats: [source, target] };
|
||||
const job: SessionAutomationJob = {
|
||||
id: "daily", name: "Daily report", enabled: true, chat_binding_revision: "rev-1",
|
||||
schedule: { kind: "every", every_ms: 86400000 }, state: {},
|
||||
payload: { message: "Summarize the work." }, origin: { ...source, session_key: "websocket:source" },
|
||||
};
|
||||
const props = { open: true, locale: "en", actionKey: null, error: null,
|
||||
onOpenChange: vi.fn(), onAction: vi.fn(), onRequestEdit: vi.fn(), onRequestDelete: vi.fn() };
|
||||
beforeEach(() => { vi.mocked(fetchAutomationChats).mockResolvedValue(choices); });
|
||||
afterEach(() => { cleanup(); vi.clearAllMocks(); });
|
||||
|
||||
async function choose() {
|
||||
const control = await screen.findByRole("combobox", { name: "Task chat" });
|
||||
await waitFor(() => expect(control).toBeEnabled());
|
||||
fireEvent.keyDown(control, { key: "ArrowDown" });
|
||||
fireEvent.click(await screen.findByRole("option", { name: /Product team/ }));
|
||||
await screen.findByRole("heading", { name: "Change chat" });
|
||||
}
|
||||
|
||||
it("keeps the original route until acknowledgement and saves the reviewed prompt", async () => {
|
||||
let finish!: () => void;
|
||||
const save = vi.fn(() => new Promise<void>(resolve => { finish = resolve; }));
|
||||
const user = userEvent.setup();
|
||||
render(<AutomationDetailDialog {...props} job={job} onChangeChat={save} />);
|
||||
await choose();
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
expect(screen.getByText(/Previous chat:/)).toHaveTextContent("My planning");
|
||||
await user.clear(screen.getByRole("textbox", { name: "Task instructions" }));
|
||||
await user.type(screen.getByRole("textbox", { name: "Task instructions" }), "New instructions");
|
||||
await user.click(screen.getByRole("button", { name: "Confirm change" }));
|
||||
expect(save).toHaveBeenCalledWith(job, { target_id: "target", revision: "rev-1", message: "New instructions" });
|
||||
expect(screen.getByRole("button", { name: "Changing…" })).toBeDisabled();
|
||||
expect(screen.queryByRole("status")).not.toBeInTheDocument();
|
||||
await act(async () => finish());
|
||||
expect(await screen.findByRole("status")).toHaveTextContent("Applies to future runs");
|
||||
expect(props.onAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps a rejected draft and its original revision across polling", async () => {
|
||||
const user = userEvent.setup();
|
||||
const save = vi.fn().mockRejectedValue(new Error("automation_chat_conflict"));
|
||||
const { rerender } = render(<AutomationDetailDialog {...props} job={job} onChangeChat={save} />);
|
||||
await choose();
|
||||
await user.type(screen.getByRole("textbox", { name: "Task instructions" }), " Reviewed");
|
||||
rerender(<AutomationDetailDialog {...props} job={{ ...job, chat_binding_revision: "rev-2" }} onChangeChat={save} />);
|
||||
await user.click(screen.getByRole("button", { name: "Confirm change" }));
|
||||
expect(save.mock.calls[0][1].revision).toBe("rev-1");
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("draft is kept");
|
||||
expect(screen.getByRole("textbox", { name: "Task instructions" })).toHaveValue("Summarize the work. Reviewed");
|
||||
await user.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
expect(screen.getByRole("combobox", { name: "Task chat" })).toHaveTextContent("My planning");
|
||||
});
|
||||
|
||||
it("does not send the new request to an old host and locks a pending task", async () => {
|
||||
const save = vi.fn();
|
||||
const { rerender } = render(<AutomationDetailDialog {...props} job={{ ...job, chat_binding_revision: undefined }} onChangeChat={save} />);
|
||||
expect(fetchAutomationChats).not.toHaveBeenCalled();
|
||||
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
|
||||
rerender(<AutomationDetailDialog {...props} job={{ ...job, state: { pending: true } }} onChangeChat={save} />);
|
||||
expect(await screen.findByRole("combobox", { name: "Task chat" })).toBeDisabled();
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the current chat visible when discovery fails and permits a retry", async () => {
|
||||
const user = userEvent.setup();
|
||||
vi.mocked(fetchAutomationChats).mockRejectedValueOnce(new Error("offline"));
|
||||
render(<AutomationDetailDialog {...props} job={job} onChangeChat={vi.fn()} />);
|
||||
await user.click(await screen.findByRole("button", { name: "Retry loading chats" }));
|
||||
await waitFor(() => expect(screen.getByRole("combobox", { name: "Task chat" })).toBeEnabled());
|
||||
expect(fetchAutomationChats).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
@@ -54,6 +54,13 @@ function openFilters() {
|
||||
return screen.getByRole("menu", { name: /^Filter/ });
|
||||
}
|
||||
|
||||
function taskMenuItem(name: string) {
|
||||
if (!screen.queryByRole("menu")) {
|
||||
fireEvent.pointerDown(screen.getByRole("button", { name: i18n.t("settings.automations.moreActions") }), { button: 0, ctrlKey: false });
|
||||
}
|
||||
return screen.getByRole("menuitem", { name, exact: true });
|
||||
}
|
||||
|
||||
function selectFilter(name: string) {
|
||||
const menu = openFilters();
|
||||
fireEvent.click(within(menu).getByRole("menuitemradio", { name }));
|
||||
@@ -255,7 +262,7 @@ describe("Automation task list and detail sheet", () => {
|
||||
const dialog = screen.getByRole("dialog", { name: "PR watch" });
|
||||
expect(dialog).not.toHaveAttribute("aria-describedby");
|
||||
expect(within(dialog).queryByText("Instructions")).not.toBeInTheDocument();
|
||||
expect(within(dialog).getByRole("link", { name: "Open a chat" })).toHaveAttribute(
|
||||
expect(taskMenuItem("Open a chat")).toHaveAttribute(
|
||||
"href", "#/chat/websocket%3Ademo",
|
||||
);
|
||||
expect(within(dialog).getByRole("button", { name: "Task information" })).toHaveAttribute("aria-expanded", "false");
|
||||
@@ -424,7 +431,8 @@ describe("Automation task list and detail sheet", () => {
|
||||
await user.click(within(screen.getByRole("dialog", { name: dayLabel })).getByRole("button", { name: /Crowded 4.*Planned/ }));
|
||||
const detail = await screen.findByRole("dialog", { name: "Crowded 4" });
|
||||
expect(screen.queryByRole("dialog", { name: dayLabel })).not.toBeInTheDocument();
|
||||
expect(within(detail).getByRole("link", { name: "Open a chat" })).toBeVisible();
|
||||
expect(taskMenuItem("Open a chat")).toBeVisible();
|
||||
await user.keyboard("{Escape}");
|
||||
await user.click(within(detail).getByRole("button", { name: "Close" }));
|
||||
await waitFor(() => expect(more).toHaveFocus());
|
||||
});
|
||||
@@ -626,14 +634,13 @@ describe("Automation task list and detail sheet", () => {
|
||||
expect(details).toHaveAttribute("aria-expanded", "false");
|
||||
if (!job.protected) {
|
||||
expect(within(dialog).queryByRole("switch")).not.toBeInTheDocument();
|
||||
const disable = within(dialog).getByRole("button", { name: "Disable" });
|
||||
const taskActions = within(dialog).getByRole("button", { name: "Run now" }).parentElement;
|
||||
expect(disable.parentElement).toBe(taskActions);
|
||||
expect(within(dialog).getByRole("button", { name: "Delete" }).parentElement).toBe(taskActions);
|
||||
const edit = within(dialog).getByRole("button", { name: "Edit" });
|
||||
expect(edit.parentElement).not.toBe(taskActions);
|
||||
expect(edit.parentElement).toHaveClass("ms-auto", "flex-wrap", "justify-end");
|
||||
expect(within(dialog).getByRole("link", { name: "Open a chat" }).parentElement).toBe(edit.parentElement);
|
||||
expect(edit.parentElement).toBe(taskActions);
|
||||
expect(edit.parentElement).toHaveClass("ml-auto");
|
||||
expect(taskMenuItem("Disable")).toBeVisible();
|
||||
expect(taskMenuItem("Delete")).toBeVisible();
|
||||
expect(taskMenuItem("Open a chat")).toHaveAttribute("href", "#/chat/websocket%3Ademo");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -782,7 +789,7 @@ describe("Automation task list and detail sheet", () => {
|
||||
rerender(<Harness payload={payload} onAction={action}
|
||||
titleOverrides={{ "websocket:demo": "新会话名称" }} />);
|
||||
expect(within(dialog).queryByText("新会话名称")).not.toBeInTheDocument();
|
||||
await user.click(within(dialog).getByRole("button", { name: "Disable" }));
|
||||
await user.click(taskMenuItem("Disable"));
|
||||
expect(action).toHaveBeenCalledWith("disable", expect.objectContaining({
|
||||
id: task.id, payload: task.payload,
|
||||
origin: expect.objectContaining({ session_key: "websocket:demo" }),
|
||||
@@ -792,19 +799,19 @@ describe("Automation task list and detail sheet", () => {
|
||||
rerender(<Harness payload={payload} titleOverrides={{}} />);
|
||||
await user.click(screen.getByRole("button", { name: /PR watch/ }));
|
||||
expect(screen.queryByText("nanobot-development")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "Open a chat" })).toHaveAttribute("href", "#/chat/websocket%3Ademo");
|
||||
expect(taskMenuItem("Open a chat")).toHaveAttribute("href", "#/chat/websocket%3Ademo");
|
||||
});
|
||||
|
||||
it("retains the inspected task across refreshes and closes if it is removed", () => {
|
||||
const action = vi.fn();
|
||||
const { rerender } = render(<Harness onAction={action} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /PR watch/ }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Disable" }));
|
||||
fireEvent.click(taskMenuItem("Disable"));
|
||||
expect(action).toHaveBeenCalledWith("disable", task);
|
||||
rerender(<Harness payload={{ jobs: [{ ...task, enabled: false }] }} onAction={action} filter="active" />);
|
||||
expect(screen.getByRole("dialog", { name: "PR watch" })).toBeVisible();
|
||||
expect(screen.getByRole("button", { name: "Enable" })).toBeEnabled();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Enable" }));
|
||||
expect(taskMenuItem("Enable")).not.toHaveAttribute("aria-disabled");
|
||||
fireEvent.click(taskMenuItem("Enable"));
|
||||
expect(action).toHaveBeenLastCalledWith("enable", { ...task, enabled: false });
|
||||
rerender(<Harness payload={{ jobs: [] }} />);
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
@@ -819,12 +826,12 @@ describe("Automation task list and detail sheet", () => {
|
||||
expect(screen.getByRole("button", { name: "筛选", exact: true })).toBeVisible();
|
||||
fireEvent.click(screen.getByRole("button", { name: /PR watch/ }));
|
||||
const dialog = screen.getByRole("dialog", { name: "PR watch" });
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "停用", exact: true }));
|
||||
fireEvent.click(taskMenuItem("停用"));
|
||||
expect(action).toHaveBeenLastCalledWith("disable", task);
|
||||
const disabledTask = { ...task, enabled: false };
|
||||
rerender(<Harness payload={{ jobs: [disabledTask] }} onAction={action} />);
|
||||
expect(within(dialog).getByRole("button", { name: "启用", exact: true })).toBeEnabled();
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "启用", exact: true }));
|
||||
expect(taskMenuItem("启用")).not.toHaveAttribute("aria-disabled");
|
||||
fireEvent.click(taskMenuItem("启用"));
|
||||
expect(action).toHaveBeenLastCalledWith("enable", disabledTask);
|
||||
expect(dialog).not.toHaveTextContent("暂停");
|
||||
expect(dialog).not.toHaveTextContent("恢复");
|
||||
@@ -882,7 +889,7 @@ describe("Automation task list and detail sheet", () => {
|
||||
await waitFor(() => expect(edit).toHaveBeenCalledWith(task));
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
await user.click(screen.getByRole("button", { name: /PR watch/ }));
|
||||
await user.click(screen.getByRole("button", { name: "Delete" }));
|
||||
await user.click(taskMenuItem("Delete"));
|
||||
await waitFor(() => expect(remove).toHaveBeenCalledWith(task));
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
});
|
||||
@@ -932,7 +939,7 @@ describe("Automation task list and detail sheet", () => {
|
||||
await user.click(screen.getByRole("button", { name: /PR watch/ }));
|
||||
const detail = screen.getByRole("dialog", { name: "PR watch" });
|
||||
expect(document.body.style.pointerEvents).toBe("none");
|
||||
await user.click(screen.getByRole("button", { name: "Delete" }));
|
||||
await user.click(taskMenuItem("Delete"));
|
||||
expect(detail).toHaveAttribute("data-state", "closed");
|
||||
finishExit(detail);
|
||||
const confirmation = await screen.findByRole("dialog", { name: "Delete automation" });
|
||||
@@ -1005,10 +1012,9 @@ describe("Automation task list and detail sheet", () => {
|
||||
await user.click(screen.getByRole("button", { name: "Run now" }));
|
||||
expect(action).toHaveBeenCalledWith("run", task);
|
||||
rerender(<Harness actionKey="run:private-job-id" />);
|
||||
for (const name of ["Edit", "Run now", "Delete"]) {
|
||||
for (const name of ["Edit", "Run now", "More actions"]) {
|
||||
expect(screen.getByRole("button", { name })).toBeDisabled();
|
||||
}
|
||||
expect(screen.getByRole("button", { name: "Disable" })).toBeDisabled();
|
||||
rerender(<Harness error="Unable to run task" />);
|
||||
expect(within(screen.getByRole("dialog")).getByRole("alert")).toHaveTextContent("Unable to run task");
|
||||
});
|
||||
@@ -1018,18 +1024,15 @@ describe("Automation task list and detail sheet", () => {
|
||||
const action = vi.fn();
|
||||
const { rerender } = render(<Harness onAction={action} />);
|
||||
await user.click(screen.getByRole("button", { name: /PR watch/ }));
|
||||
const control = screen.getByRole("button", { name: "Disable" });
|
||||
control.focus();
|
||||
const control = taskMenuItem("Disable");
|
||||
act(() => control.focus());
|
||||
await user.keyboard(" ");
|
||||
expect(action).toHaveBeenCalledWith("disable", task);
|
||||
expect(control).toHaveTextContent("Disable");
|
||||
rerender(<Harness onAction={action} actionKey={`disable:${task.id}`} />);
|
||||
expect(control).toBeDisabled();
|
||||
await user.click(control);
|
||||
expect(screen.getByRole("button", { name: "More actions" })).toBeDisabled();
|
||||
expect(action).toHaveBeenCalledTimes(1);
|
||||
rerender(<Harness onAction={action} payload={{ jobs: [{ ...task, enabled: false }] }} />);
|
||||
expect(control).toHaveTextContent("Enable");
|
||||
expect(control).toBeEnabled();
|
||||
expect(taskMenuItem("Enable")).not.toHaveAttribute("aria-disabled");
|
||||
});
|
||||
|
||||
it("does not allow running a pending task or resuming an unlinked task", async () => {
|
||||
@@ -1040,7 +1043,7 @@ describe("Automation task list and detail sheet", () => {
|
||||
await user.click(screen.getByRole("button", { name: /PR watch/ }));
|
||||
expect(screen.getByRole("button", { name: "Run now" })).toBeDisabled();
|
||||
rerender(<Harness payload={{ jobs: [{ ...task, enabled: false, origin: null }] }} />);
|
||||
expect(screen.getByRole("button", { name: "Enable" })).toBeDisabled();
|
||||
expect(taskMenuItem("Enable")).toHaveAttribute("aria-disabled", "true");
|
||||
expect(screen.queryByRole("link", { name: "Open a chat" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -1055,7 +1058,7 @@ describe("Automation task list and detail sheet", () => {
|
||||
expect(within(screen.getByRole("dialog")).getByText("nanobot trigger run trigger-1")).toBeVisible();
|
||||
expect(screen.getByRole("button", { name: "Copy" })).toBeEnabled();
|
||||
expect(screen.queryByRole("button", { name: "Run now" })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Delete" })).toBeVisible();
|
||||
expect(taskMenuItem("Delete")).toBeVisible();
|
||||
});
|
||||
|
||||
it("shows paused failures honestly and does not fabricate successful runs", () => {
|
||||
|
||||
Reference in new issue
Block a user