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; export type AutomationChatNames = ReadonlyMap; function ChatIdentity({ chat, title }: { chat: AutomationChat; title: string }) { 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 {chat.channel === "websocket" ? : } {title}{platform} ; } export function AutomationChatBinding({ job, token, chatNames, onSave, children }: { job: SessionAutomationJob; token: string; onSave: ChangeAutomationChat; chatNames?: AutomationChatNames; children: (picker: ReactNode) => ReactNode; }) { const { t } = useTranslation(); const tx = (key: string, values?: Record) => t(`settings.automations.chat.${key}`, values); const [data, setData] = useState(null); const [loadError, setLoadError] = useState(false); const [reload, setReload] = useState(0); const [draft, setDraft] = useState<{ target: AutomationChat; previous: AutomationChat; revision: string; message: string; editingMessage?: boolean } | null>(null); const [saving, setSaving] = useState(false); const [error, setError] = useState(""); const [saved, setSaved] = useState<{ target: AutomationChat; previous: AutomationChat } | null>(null); const heading = useRef(null); const trigger = useRef(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); setSaved(previous => previous?.target.id === value.current?.id ? previous : null); } }).catch(() => { if (!controller.signal.aborted) setLoadError(true); }); return () => controller.abort(); }, [token, job.id, job.chat_binding_revision, reload]); const reviewing = draft !== null; const locked = saving || Boolean(job.state.pending); const pickerDisabled = locked || !data?.chats.length || loadError || (!reviewing && data.revision !== job.chat_binding_revision); useEffect(() => { if (reviewing) heading.current?.focus(); }, [reviewing]); useEffect(() => { if (!reviewing && !pickerDisabled && returning.current) { trigger.current?.focus(); returning.current = false; } }, [reviewing, pickerDisabled]); 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 baseTitle = (chat: AutomationChat) => chatNames?.get(chat.id)?.title ?? chat.title; const counts = new Map(); for (const chat of data?.chats ?? []) { const title = baseTitle(chat); counts.set(title, (counts.get(title) ?? 0) + 1); } const chatTitle = (chat: AutomationChat) => { const title = baseTitle(chat); const name = chatNames?.get(chat.id); return name && (counts.get(title) ?? 0) > 1 ? `${title} ยท @${name.handle}` : title; }; const identity = (chat: AutomationChat) => ; const targetUnavailable = Boolean(draft && data && !data.chats.some(chat => chat.id === draft.target.id && !chat.unavailable)); const picker = (review: boolean) => ; const save = async () => { if (!draft || locked || targetUnavailable || !draft.message.trim()) return; setSaving(true); setError(""); try { await onSave(job, { target_id: draft.target.id, revision: draft.revision, message: draft.message }); setData(previous => previous ? { ...previous, current: draft.target } : previous); setSaved({ target: draft.target, previous: draft.previous }); back(); setReload(value => value + 1); } catch (cause) { const reasons: Record = { 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(

{tx("label")}

{picker(false)}

{job.state.pending ? tx("busy") : saved ? tx("saved", { chat: chatTitle(saved.target) }) : tx("hint")}

{saved && current?.id === saved.target.id && data?.chats.some(chat => chat.id === saved.previous.id && !chat.unavailable) ? ( ) : null} {loadError ? : null} {data && data.chats.length <= (current ? 1 : 0) ?

{tx("available")}

: null}
); return <> {tx("change")}
{tx("previous")} {identity(draft.previous)}

{tx("new")}

{picker(true)}

{tx("effect")}

{tx("history")}

{tx("message")}

{!draft.editingMessage ? : null}
{draft.editingMessage ? <>