Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
design(webui): preview explicit automation chat selection
Xubin Ren4df9aad18bbe
diff --git a/webui/proposals/automation-chat/BindingControls.tsx b/webui/proposals/automation-chat/BindingControls.tsxnew file mode 100644index 000000000..1a119fffd--- /dev/null+++ b/webui/proposals/automation-chat/BindingControls.tsx@@ -0,0 +1,133 @@+import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from 'react';+import { ArrowLeft, Check, Users } from 'lucide-react';+import { ChannelLogo } from '@/components/settings/channels/ChannelIdentity';+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 type { NanobotFeatureInfo, SessionAutomationJob } from '@/lib/types';++export const targets = {+ weixin: { name: '我的私聊', platform: '微信', channel: 'weixin', group: false },+ feishu: { name: '产品讨论群', platform: '飞书', channel: 'feishu', group: true },+ telegram: { name: '工作群 / 日报', platform: 'Telegram', channel: 'telegram', group: true },+ webui: { name: '天气助手', platform: '网页聊天', channel: 'websocket', group: false },+};+export type Target = keyof typeof targets;+export const legacy = '\n\n投递方式:调用 message 发送到微信。\nchannel="weixin"\nchat_id="demo-person"\ncontent=整理好的天气推送文本';+export const PreviewContext = createContext<{+ mode: string; scenario: string;+ save: (job: SessionAutomationJob, target: Target, message: string) => Promise<void>;+} | null>(null);+const BindingContext = createContext<{+ saved: Target; notice: string; locked: boolean;+ select: (target: Target) => void;+} | null>(null);++export function ConversationIdentity({ target }: { target: Target }) {+ const item = targets[target];+ const feature: NanobotFeatureInfo = {+ name: item.channel, display_name: item.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">+ {target === 'webui' ? <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 /></span>}+ </span>+ <span className="min-w-0">+ <span className="block truncate text-[13px] leading-5">{item.name}<span className="ml-2 text-[12px] text-muted-foreground">{item.platform}</span></span>+ </span>+ </span>;+}++// One original dialog owns the complete interaction. The page never unmounts.+export function BindingDialogFrame({ job, children }: { job: SessionAutomationJob; children: ReactNode }) {+ const preview = useContext(PreviewContext)!;+ const saved = (Object.keys(targets) as Target[]).find(key => targets[key].channel === job.origin?.channel) ?? 'webui';+ const [draft, setDraft] = useState(saved);+ const [reviewing, setReviewing] = useState(false);+ const [message, setMessage] = useState(job.payload.message);+ const [ack, setAck] = useState(false);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState('');+ const [notice, setNotice] = useState('');+ const heading = useRef<HTMLHeadingElement>(null);+ const returning = useRef(false);+ const locked = Boolean(job.state.pending || preview.scenario === 'oldhost');+ useEffect(() => {+ if (reviewing) heading.current?.focus();+ else if (returning.current) {+ document.querySelector<HTMLButtonElement>('[data-binding-select]')?.focus();+ returning.current = false;+ }+ }, [reviewing]);+ const back = () => { returning.current = true; setReviewing(false); };+ const save = async () => {+ if (!ack || !message.trim() || saving || locked) return;+ setSaving(true); setError('');+ try {+ await preview.save(job, draft, message);+ setNotice('已更换,下次执行时使用这个聊天。'); back();+ } catch { setError('没有保存:任务已被其他操作修改。原设置没变,你填写的内容也还在。'); }+ finally { setSaving(false); }+ };+ if (preview.mode === 'current') return children;+ return <BindingContext.Provider value={{ saved, notice, locked,+ select: target => {+ if (target === saved || locked) return;+ setDraft(target); setNotice(''); setAck(false); setError(''); setReviewing(true);+ },+ }}>+ {!reviewing ? children : <>+ <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">确认更换聊天</DialogTitle>+ </DialogHeader>+ <div className="min-h-0 overflow-y-auto overscroll-contain px-6 pb-4">+ <div className="space-y-3 rounded-control bg-muted/50 p-3">+ <div className="flex items-center gap-3"><span className="w-8 shrink-0 text-[12px] text-muted-foreground">现在</span><ConversationIdentity target={saved} /></div>+ <div className="flex items-center gap-3"><span className="w-8 shrink-0 text-[12px] text-muted-foreground">改为</span><ConversationIdentity target={draft} /></div>+ </div>+ <p className="mt-3 text-[13px] leading-5">下次执行时,nanobot 会参考新聊天的记录,并默认把结果发到那里。</p>+ <p className="mt-2 text-[12px] leading-5 text-muted-foreground">原来的聊天记录不会带过去。执行时间不变,也不会马上运行。</p>+ {targets[draft].group ? <p className="mt-3 flex items-start gap-2 text-[12px] leading-5"><Users className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" aria-hidden/>这是群聊,群里的人可能看到任务涉及的内容和结果。</p> : null}+ <label className="mt-4 block space-y-2"><span className="text-[12px] text-muted-foreground">任务说明(可以修改)</span>+ <Textarea aria-label="任务说明" rows={4} value={message} disabled={saving} onChange={event => { setMessage(event.target.value); setAck(false); }} className="min-h-24 resize-y text-base leading-6 sm:text-[13px] sm:leading-5"/>+ </label>+ {message.includes(legacy.trim()) ? <div className="mt-2 text-[12px] leading-5 text-muted-foreground">+ <p>说明里还要求把结果发到微信。只改上面的聊天,不会删除这条要求。</p>+ <Button variant="link" size="sm" className="h-auto px-0 py-2 text-[12px]" disabled={saving} onClick={() => { setMessage(message.replace(legacy, '')); setAck(false); }}>删除说明里的旧发送要求</Button>+ </div> : null}+ <label className="mt-3 flex min-h-11 items-start gap-2 py-2 text-[12px] leading-5"><input type="checkbox" checked={ack} disabled={saving} onChange={event => setAck(event.target.checked)} className="mt-1 h-4 w-4 shrink-0 accent-current"/><span>我已检查,任务内容可以在这里使用</span></label>+ <p role={error ? 'alert' : 'status'} className={`min-h-5 text-[12px] leading-5 ${error ? 'text-destructive' : 'text-muted-foreground'}`}>{error || (saving ? '正在保存,暂时仍使用原来的聊天。' : '')}</p>+ </div>+ <DialogFooter className="shrink-0 flex-row justify-between gap-2 border-t border-border/45 px-6 py-3">+ <Button variant="ghost" size="sm" disabled={saving} className="h-11 gap-1.5 font-normal text-muted-foreground sm:h-9" onClick={back}><ArrowLeft className="h-3.5 w-3.5" aria-hidden/>返回选择</Button>+ <Button size="sm" className="h-11 min-w-24 sm:h-9" disabled={!ack || !message.trim() || saving || locked} onClick={save}>{saving ? '正在保存…' : '确认更换'}</Button>+ </DialogFooter>+ </>}+ </BindingContext.Provider>;+}++export function BindingControls({ job, currentUi }: { job: SessionAutomationJob; currentUi: ReactNode }) {+ const preview = useContext(PreviewContext);+ const state = useContext(BindingContext);+ if (!state || preview?.mode === 'current' || job.protected) return currentUi;+ return <div className="border-t border-border/45 pt-3">+ <dl><div className="grid min-w-0 grid-cols-1 items-start gap-2 py-1 text-sm min-[420px]:grid-cols-[6rem_minmax(0,1fr)] min-[420px]:gap-4">+ <dt className="text-[13px] text-muted-foreground min-[420px]:pt-3">任务所在聊天</dt>+ <dd className="min-w-0">+ <Select value={state.saved} onValueChange={value => state.select(value as Target)} disabled={state.locked}>+ <SelectTrigger aria-label="任务所在聊天" data-binding-select className="h-auto min-h-11 w-full [&>span:first-child]:min-w-0 [&>span:first-child]:flex-1 [&>span:first-child]:text-start"><SelectValue><ConversationIdentity target={state.saved} /></SelectValue></SelectTrigger>+ <SelectContent>+ {(Object.keys(targets) as Target[]).map(key => <SelectItem key={key} value={key} textValue={`${targets[key].name} ${targets[key].platform}`} className="min-h-11 py-2 [&>span:last-child]:min-w-0 [&>span:last-child]:w-full"><ConversationIdentity target={key} /></SelectItem>)}+ <SelectItem value="offline" disabled className="min-h-11 text-[12px]">值班群 · 飞书(暂时无法连接)</SelectItem>+ </SelectContent>+ </Select>+ </dd>+ </div></dl>+ <p className="mt-2 text-[12px] leading-5 text-muted-foreground">{state.locked ? (job.state.pending ? '任务正在执行或等待执行,暂时不能更换聊天。' : '当前连接的 nanobot 版本还不能更换聊天。') : 'nanobot 会参考这里的聊天记录,完成任务后默认在这里回复。'}</p>+ {state.notice ? <p role="status" className="mt-3 flex items-center gap-1.5 text-[12px] text-muted-foreground"><Check className="h-3.5 w-3.5" aria-hidden/>{state.notice}</p> : null}+ </div>;+}diff --git a/webui/proposals/automation-chat/README.md b/webui/proposals/automation-chat/README.mdnew file mode 100644index 000000000..36122bd03--- /dev/null+++ b/webui/proposals/automation-chat/README.md@@ -0,0 +1,172 @@+# Automation chat proposal++Draft for design review. This is a runnable UI prototype, not a working change+to automation routing. It does not change the production build or gateway.++## Problem++Automation details show the channel, such as “WeChat”, but not the specific+conversation. Users cannot check where a task runs and replies. Some put raw+`channel` and `chat_id` instructions in the task prompt to control delivery.+The display gap is confirmed in the source. A wrong-recipient incident has not+been reproduced from the reports.++The interface should answer two questions in plain language:++- Which chat does this task use?+- If I change it, what happens to the next run?++## Proposed interaction++Use the existing Automations page and detail dialog. Show a channel logo on the+left, then the chat name and platform. The Chinese label is “任务所在聊天”+(“Task chat”). Do not show an invented account label or an unexplained ID suffix.+Production must still distinguish real same-name chats or topics when needed.++1. Keep the saved chat selected by default. Do not infer it from the latest chat.+2. Selecting another chat opens a review step in the same dialog.+3. Show the old and new chats. Explain that future runs use the new chat's+ history and reply there by default. Old chat history stays where it is.+4. Let the user review and edit the task prompt. Warn when the target is a group.+5. Require confirmation that the prompt is suitable for the new chat.+6. Change the displayed saved chat only after the save succeeds. Keep the draft+ after a conflict or when the user returns to select another chat.++Changing a chat must not run the task, change its schedule, or enable a paused+task. Keep the page mounted during review and show save progress next to the+action. Do not replace the page with a spinner or report success before an+acknowledgement. This follows the interaction principle discussed in+[The perfect app has no loading states](https://floriankiem.com/writing/the-perfect-app-has-no-loading-states).++## Decision needed before implementation++The maintainer rejected an independent result-delivery target in+[#5513](https://github.com/HKUDS/nanobot/issues/5513#issuecomment-5488297111)+and repeated that concern on+[#5620](https://github.com/HKUDS/nanobot/pull/5620#issuecomment-5534384796).+Running in chat A and sending the result to chat B separates the reply from its+history and can expose context from A.++This proposal does **not** add a delivery override. It proposes changing the+whole binding for future runs: execution chat, recorded result, and default+reply destination move together. This still changes the current rule that a+task stays in its creation chat. Maintainer approval is pending.++Implement this in two stages:++- **A: Read-only identity.** Show the exact bound chat when the gateway can+ resolve it. If it cannot, say that the chat is unknown. Keep all bindings and+ execution behavior unchanged. This stage can ship independently.+- **B: Explicit chat change.** Add the selector only after agreement on the+ binding change and after the gateway contract is implemented and verified.+ If the decision is no, keep A and direct users to create the task in the+ intended chat.++## Gateway contract required for stage B++The gateway owns identity, authorization, execution, and persistence. The client+must not assemble a route from a channel name or provide platform credentials.+A possible operation is `change_binding(job_id, target_ref, expected_revision,+reviewed_message)`; this is a proposal, not an existing API.++- Resolve the target in the same host, configuration, and workspace. A connected+ channel does not prove that a recipient or topic is valid or authorized.+- Initially support ordinary scheduled agent jobs only. Keep system jobs,+ local triggers, unified-session mode, temporary/deleted chats, and cross-host+ moves read-only. Do not allow arbitrary recipient IDs or multiple recipients.+- Check job revision and running/queued state in the same serialized operation+ that changes the binding. Do not check in HTTP and then write without a guard.+- Save the complete binding and reviewed prompt together. A failed write keeps+ the old in-memory and persisted values. Task admission must observe either the+ old binding or the new one, never part of each.+- Preserve enabled state, schedule, timezone, and scheduled occurrence. A save+ must not create an extra run or lose work already admitted.+- Preserve the target used by each historical run. Never fill old history with+ the current target. If the old target was not recorded, report it as unknown.+- Do not copy messages, summaries, transcripts, or files from the previous chat.+ This does not create new isolation for shared workspace files or memory.+- Require prompt review: explicit `message` instructions can still send to a+ different destination. The selector is not an outbound-message sandbox.+ Never rewrite arbitrary prompts automatically.++Use existing session/channel ownership to resolve identities and routes. Keep+the atomic update in the cron owner, not the client. Do not introduce WebUI+policy in `agent/loop.py` or `agent/runner.py`.++At base `948ce382`, `nanobot/webui/session_automations.py::_origin_payload`+returns only channel and empty display text for non-WebSocket jobs. The detail+panel renders that channel label. `nanobot/agent/tools/cron.py` captures the+creation route; `nanobot/cron/bound_runner.py` and `session_delivery.py` consume+the binding. Legacy `channel`/`to` fields are not an API for changing the modern+session binding.++## Compatibility and acceptance gates++Stage A should add optional read fields. Stage B needs an optional capability;+older hosts must not receive the new mutation. Ordinary edits and existing jobs+must continue to work. Any new persisted revision/audit fields need explicit+restart and rollback rules before stage B can ship.++Required evidence before enabling real saves:++- A default run and a moved run use the correct chat history, recorded turn,+ and reply route. A reply in the target chat can continue the task.+- Task admission versus save, two-tab updates, write failure, and restart do not+ produce a partial binding, double delivery, or false success.+- Invalid, deleted, foreign, or unauthorized targets are rejected. Same-name+ chats and topic/account routes remain distinguishable.+- Paused and scheduled jobs retain their state. Running or queued jobs reject+ the change. A busy target chat retains normal queue behavior.+- Supported old/new client-host combinations, missing capability, reconnect,+ and a late response after host switching preserve the correct host scope.+- Desktop and narrow mobile layouts, keyboard selection, cancellation, prompt+ review, failed saves, and save/read-back are verified.++These are implementation gates, not claims about this prototype.++## Screenshots++Synthetic data from this opt-in preview; neither screen changes a real task.++++++## Run the prototype++Install the existing WebUI dependencies with the repository's usual setup.+From `webui/`:++```sh+node node_modules/typescript/bin/tsc --noEmit -p proposals/automation-chat/tsconfig.json+node node_modules/vite/bin/vite.js build --config proposals/automation-chat/vite.config.ts+node node_modules/vite/bin/vite.js preview --config proposals/automation-chat/vite.config.ts+```++Open `http://127.0.0.1:53822/`. For the weather details, open+`http://127.0.0.1:53822/?detail&theme=dark`.+Use the preview menu to compare current/proposed UI and simulate a slow save,+conflict, queued task, or old host. Refresh resets all changes.++The prototype imports the real Sidebar, Automations page, dialogs, channel+logos, UI controls, translations, CSS, and Tailwind configuration. An opt-in+Vite transform replaces only the linked-chat slot and review frame in memory.+The build fails if those source anchors change. The transform is not used by+the product build and is not a proposed production extension point.++## Prototype limits++- All tasks, chat identities, and save responses are synthetic React state.+ There is no API proxy, gateway connection, model call, task run, or message+ delivery. Existing logo components may load remote brand images.+- The current fixtures have one selectable chat per platform. They do not prove+ identity resolution, recipient permissions, or same-name disambiguation.+- The old-send-instruction button removes one exact fixture block on an explicit+ click. It does not detect arbitrary routing instructions or sensitive text.+- The preview is Chinese-first. Production copy still needs all supported+ locales, including verified accessibility labels.+- Earlier UI-only browser checks covered desktop, 320/390 px layouts, draft+ retention, save acknowledgement, conflict, cancellation, and keyboard flow.+ Those checks do not prove real delivery, persistence, or physical iOS behavior.+- No production runtime, wire schema, saved data, or package dependencies change+ in this draft. This proposal is not merge-ready as a routing feature.diff --git a/webui/proposals/automation-chat/detail.jpg b/webui/proposals/automation-chat/detail.jpgnew file mode 100644index 000000000..b0414e129Binary files /dev/null and b/webui/proposals/automation-chat/detail.jpg differdiff --git a/webui/proposals/automation-chat/index.html b/webui/proposals/automation-chat/index.htmlnew file mode 100644index 000000000..19edd6f71--- /dev/null+++ b/webui/proposals/automation-chat/index.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="zh-CN">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>nanobot — Automation chat proposal</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/main.tsx"></script>+ </body>+</html>diff --git a/webui/proposals/automation-chat/main.tsx b/webui/proposals/automation-chat/main.tsxnew file mode 100644index 000000000..aae24b4f9--- /dev/null+++ b/webui/proposals/automation-chat/main.tsx@@ -0,0 +1,115 @@+import { useEffect, useState } from 'react';+import { createRoot } from 'react-dom/client';+import { Menu, Moon, Sun, SlidersHorizontal } from 'lucide-react';+import i18n from 'i18next';+import { initReactI18next } from 'react-i18next';+import zhCN from '@/i18n/locales/zh-CN/common.json';+import { Sidebar } from '@/components/Sidebar';+import { AutomationsSettings, AutomationEditDialog, AutomationDeleteDialog } from '@/components/settings/system/AutomationsSettings';+import { Button } from '@/components/ui/button';+import { DialogLayoutContext } from '@/components/ui/dialog';+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';+import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '@/components/ui/select';+import { Sheet, SheetContent, SheetTitle } from '@/components/ui/sheet';+import { ClientProvider } from '@/providers/ClientProvider';+import { NanobotClient } from '@/lib/nanobot-client';+import type { ChatSummary, SessionAutomationJob } from '@/lib/types';+import { PreviewContext, targets, legacy, type Target } from './BindingControls';+import '@/globals.css';++const params = new URLSearchParams(location.search);+void i18n.use(initReactI18next).init({ lng: 'zh-CN', fallbackLng: 'zh-CN', resources: { 'zh-CN': { translation: zhCN, 'channel-weixin': { displayName: '微信' }, 'channel-feishu': { displayName: '飞书' }, 'channel-telegram': { displayName: 'Telegram' } } }, interpolation: { escapeValue: false }, initAsync: false });+// Required by the real sidebar. Never connect this client to a gateway.+const client = new NanobotClient({ url: 'ws://127.0.0.1:1/preview-disabled', reconnect: false });+const now = Date.now();+const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); tomorrow.setHours(8, 0, 0, 0);+const weather: SessionAutomationJob = {+ id: 'demo-weather-changde', name: '天气推送·常德', enabled: true,+ schedule: { kind: 'cron', expr: '0 8 * * *', tz: 'Asia/Shanghai' },+ payload: { message: '查询常德未来一小时天气,整理一条简短推送,重点写:\n- 天气现象、气温/体感、降水概率\n- 穿衣、带伞、防晒与出行建议\n\n口语化、简短,不照抄原始输出,不加多余分析。' + legacy },+ state: { next_run_at_ms: tomorrow.getTime(), last_run_at_ms: tomorrow.getTime() - 86400000, last_status: 'ok', run_history: [1, 2, 3].map(day => ({ run_at_ms: tomorrow.getTime() - (day + 1) * 86400000, status: 'ok', duration_ms: 16000 })) },+ origin: { channel: 'weixin', chat_id: 'demo-person', session_key: 'weixin:demo-person', title: '我的私聊' },+ created_at_ms: now - 7 * 86400000,+};+const initialJobs: SessionAutomationJob[] = [weather,+ { ...weather, id: 'demo-daily', name: '产品进展日报', schedule: { kind: 'cron', expr: '0 18 * * 1-5', tz: 'Asia/Shanghai' }, payload: { message: '整理今日产品进展、待解决问题和明日安排,发一条简短日报。' }, origin: { channel: 'feishu', chat_id: 'demo-product', session_key: 'feishu:demo-product', title: '产品讨论群' }, state: { next_run_at_ms: tomorrow.getTime() + 36000000, last_status: 'ok' } },+ { ...weather, id: 'demo-weekly', name: '每周阅读回顾', enabled: false, schedule: { kind: 'cron', expr: '0 20 * * 0', tz: 'Asia/Shanghai' }, payload: { message: '回顾本周阅读笔记,挑选三条值得保留的观点。' }, origin: { channel: 'websocket', chat_id: 'demo-reading', session_key: 'websocket:demo-reading', title: '天气助手' }, state: {} },+];+const sessions: ChatSummary[] = [+ ['websocket:demo-weather', '天气助手', '整理天气推送'],+ ['websocket:demo-product', '产品计划', '本周开发进展'],+ ['websocket:demo-reading', '阅读笔记', '整理近期阅读'],+].map(([key, title, preview]) => ({ key, title, preview, channel: 'websocket', chatId: key.split(':')[1], createdAt: new Date(now - 86400000).toISOString(), updatedAt: new Date(now).toISOString() }));++function Preview() {+ const [mode, setMode] = useState(params.get('mode') || 'proposal');+ const [scenario, setScenario] = useState(params.get('scenario') || 'ready');+ const [dark, setDark] = useState(params.has('theme') ? params.get('theme') === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches);+ const [jobs, setJobs] = useState(initialJobs);+ const [filter, setFilter] = useState<'all' | 'active' | 'paused' | 'failed' | 'system'>('all');+ const [sidebarOpen, setSidebarOpen] = useState(true);+ const [mobileOpen, setMobileOpen] = useState(false);+ const [anchor, setAnchor] = useState<HTMLDivElement | null>(null);+ const [editJob, setEditJob] = useState<SessionAutomationJob | null>(null);+ const [deleteJob, setDeleteJob] = useState<SessionAutomationJob | null>(null);+ const [returnJob, setReturnJob] = useState<SessionAutomationJob | null>(params.has('detail') ? weather : null);+ const [notice, setNotice] = useState('');+ useEffect(() => { document.documentElement.classList.toggle('dark', dark); }, [dark]);+ const demoOnly = () => { setMobileOpen(false); setNotice('此预览仅开放自动任务及关联会话流程,其他页面未接入。'); };+ const payload = { jobs: jobs.map(job => ({ ...job, state: { ...job.state, pending: scenario === 'pending' } })) };+ const save = async (job: SessionAutomationJob, target: Target, message: string) => {+ // Latency exists only in the slow-ack demo, never as a decorative minimum.+ if (scenario === 'slow') await new Promise(resolve => setTimeout(resolve, 2200));+ if (scenario === 'conflict') throw new Error('Simulated revision conflict');+ setJobs(current => current.map(item => item.id !== job.id ? item : { ...item,+ payload: { ...item.payload, message },+ origin: { channel: targets[target].channel, chat_id: `demo-${target}`, session_key: `${targets[target].channel}:demo-${target}`, title: targets[target].name },+ }));+ };+ const sidebar = (mobile = false) => <Sidebar sessions={sessions} activeKey={null} loading={false} newChatActive={false} activeUtility="automations"+ collapsed={!mobile && !sidebarOpen} containActionMenus={mobile} onCollapse={() => mobile ? setMobileOpen(false) : setSidebarOpen(false)} onExpand={() => setSidebarOpen(true)}+ onNewChat={demoOnly} onSelect={demoOnly} onRequestDelete={demoOnly} onTogglePin={demoOnly} onRequestRename={demoOnly} onToggleArchive={demoOnly} onToggleGroup={demoOnly} onRequestRenameProject={demoOnly} onNewChatInProject={demoOnly}+ onOpenSettings={demoOnly} onOpenApps={demoOnly} onOpenSkills={demoOnly} onOpenChannels={demoOnly} onOpenSearch={demoOnly} onToggleArchived={demoOnly}+ onOpenAutomations={() => { setMobileOpen(false); setNotice(''); }}/>+ return <ClientProvider client={client} token=""><PreviewContext.Provider value={{ mode, scenario, save }}>+ <div className="flex h-dvh w-full flex-col overflow-hidden bg-background text-foreground">+ <header className="flex h-11 shrink-0 items-center justify-between gap-2 border-b border-border/45 bg-sidebar px-4">+ <div className="flex min-w-0 items-center gap-3 text-[12px]"><span className="shrink-0 font-medium">自动任务 · 交互预览</span><span className="hidden truncate text-muted-foreground sm:inline">合成数据 · 不运行任务,不投递消息</span></div>+ <div className="flex shrink-0 gap-1">+ <Popover><PopoverTrigger asChild><Button variant="ghost" size="sm" className="h-8 gap-1.5 text-[12px] font-normal"><SlidersHorizontal className="h-3.5 w-3.5" aria-hidden/><span>预览选项</span></Button></PopoverTrigger>+ <PopoverContent align="end" className="w-64 space-y-4 text-[13px]">+ <label className="block space-y-2"><span className="text-muted-foreground">界面</span><Select value={mode} onValueChange={setMode}><SelectTrigger aria-label="界面版本"><SelectValue/></SelectTrigger><SelectContent><SelectItem value="proposal">拟议改动</SelectItem><SelectItem value="current">当前代码</SelectItem></SelectContent></Select></label>+ <label className="block space-y-2"><span className="text-muted-foreground">模拟状态</span><Select value={scenario} onValueChange={setScenario}><SelectTrigger aria-label="模拟状态"><SelectValue/></SelectTrigger><SelectContent>{[['ready','正常'],['slow','保存较慢'],['conflict','版本冲突'],['pending','任务已排队'],['oldhost','旧主机']].map(([value,label]) => <SelectItem key={value} value={value}>{label}</SelectItem>)}</SelectContent></Select></label>+ <p className="text-[12px] leading-5 text-muted-foreground">仅模拟 UI。真实保存还需 gateway 接口与能力校验。</p>+ </PopoverContent>+ </Popover>+ <Button variant="ghost" size="icon" className="h-8 w-8" aria-label={dark ? '切换浅色' : '切换深色'} onClick={() => setDark(!dark)}>{dark ? <Sun className="h-4 w-4"/> : <Moon className="h-4 w-4"/>}</Button>+ </div>+ </header>+ <div className="relative flex min-h-0 flex-1 overflow-hidden">+ <aside className="relative z-20 hidden h-full shrink-0 overflow-hidden lg:block" style={{ width: sidebarOpen ? 256 : 56 }}>{sidebar()}</aside>+ <Sheet open={mobileOpen} onOpenChange={setMobileOpen}><SheetContent side="left" showCloseButton={false} aria-describedby={undefined} className="w-[280px] max-w-[85vw] p-0 lg:hidden"><SheetTitle className="sr-only">侧边栏</SheetTitle>{sidebar(true)}</SheetContent></Sheet>+ <main className="relative flex min-w-0 flex-1 flex-col overflow-hidden bg-settings-canvas">+ <div className="flex h-12 shrink-0 items-center gap-2 px-3 lg:hidden"><Button variant="ghost" size="icon" aria-label="打开侧边栏" onClick={() => setMobileOpen(true)}><Menu className="h-4 w-4"/></Button><span className="text-[13px]">nanobot</span></div>+ <DialogLayoutContext.Provider value={anchor}>+ <div className="min-w-0 flex-1 overflow-y-auto [scrollbar-gutter:stable]">+ <div ref={setAnchor} data-settings-section="automations" data-main-navigation-expanded={sidebarOpen} className="settings-grid settings-feature-page settings-automations-grid mx-auto w-full py-6 sm:py-8 lg:py-12">+ <AutomationsSettings payload={payload} loading={false} filter={filter} actionKey={null} error={null} onFilterChange={setFilter}+ onStartChat={() => { setNotice('仅演示:创建请求未发送。输入草稿仍保留。'); return false; }} onManageModels={demoOnly}+ onAction={(action, job) => { if (action === 'enable' || action === 'disable') setJobs(current => current.map(item => item.id === job.id ? { ...item, enabled: action === 'enable' } : item)); else setNotice('仅演示:没有运行任务或投递消息。'); }}+ onRequestEdit={setEditJob} onRequestDelete={setDeleteJob} returnToDetailJob={returnJob} onReturnToDetailHandled={() => setReturnJob(null)}/>+ {notice ? <p role="status" className="mt-4 text-[12px] leading-5 text-muted-foreground">{notice}</p> : null}+ </div>+ </div>+ <AutomationEditDialog job={editJob} saving={false} onOpenChange={open => { if (!open) { setReturnJob(editJob); setEditJob(null); } }} onCancel={() => { setReturnJob(editJob); setEditJob(null); }} onSave={(job, values) => {+ setJobs(current => current.map(item => item.id !== job.id ? item : { ...item, name: values.name ?? item.name, payload: { ...item.payload, message: values.message ?? item.payload.message }, schedule: { ...item.schedule, ...values.schedule } }));+ setReturnJob(job); setEditJob(null);+ }}/>+ <AutomationDeleteDialog job={deleteJob} deleting={false} onOpenChange={open => { if (!open) { setReturnJob(deleteJob); setDeleteJob(null); } }} onConfirm={() => { setNotice('仅演示:任务没有删除。'); setReturnJob(deleteJob); setDeleteJob(null); }}/>+ </DialogLayoutContext.Provider>+ </main>+ </div>+ </div>+ </PreviewContext.Provider></ClientProvider>;+}+createRoot(document.getElementById('root')!).render(<Preview/>);diff --git a/webui/proposals/automation-chat/review.jpg b/webui/proposals/automation-chat/review.jpgnew file mode 100644index 000000000..54d448a2fBinary files /dev/null and b/webui/proposals/automation-chat/review.jpg differdiff --git a/webui/proposals/automation-chat/tsconfig.json b/webui/proposals/automation-chat/tsconfig.jsonnew file mode 100644index 000000000..dae8d473e--- /dev/null+++ b/webui/proposals/automation-chat/tsconfig.json@@ -0,0 +1,5 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": { "types": ["node", "vite/client"] },+ "include": ["main.tsx", "BindingControls.tsx"]+}diff --git a/webui/proposals/automation-chat/vite.config.ts b/webui/proposals/automation-chat/vite.config.tsnew file mode 100644index 000000000..719b0b874--- /dev/null+++ b/webui/proposals/automation-chat/vite.config.ts@@ -0,0 +1,69 @@+import { defineConfig, normalizePath } from 'vite';+import react from '@vitejs/plugin-react';+import tailwindcss from 'tailwindcss';+import autoprefixer from 'autoprefixer';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import baseTailwind from '../../tailwind.config.js';++const root = path.dirname(fileURLToPath(import.meta.url));+const webui = path.resolve(root, '../..');+const repository = path.dirname(webui);+const realAutomations = normalizePath(path.join(webui, 'src/components/settings/system/AutomationsSettings.tsx'));+const linkedChat = ` <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>`;+const panelStart = ' <AutomationDetailPanel\n';+const panelEnd = ' onRequestDelete={onRequestDelete}\n />';++// This opt-in build replaces one slot in memory. It never edits product source.+export default defineConfig({+ root,+ publicDir: path.join(webui, 'public'),+ cacheDir: path.join(root, '.vite'),+ plugins: [{+ name: 'automation-chat-proposal',+ enforce: 'pre',+ transform(source, id) {+ if (normalizePath(id.split('?')[0]) !== realAutomations) return;+ const code = source.replace(/\r\n/g, '\n');+ for (const anchor of [linkedChat, panelStart, panelEnd]) {+ if (code.split(anchor).length !== 2) {+ throw new Error('Automation detail markup changed. Update the proposal seam.');+ }+ }+ return {+ code: `import { BindingControls, BindingDialogFrame } from ${JSON.stringify(normalizePath(path.join(root, 'BindingControls.tsx')))};\n`+ + code.replace(linkedChat, ` <BindingControls job={job} currentUi={${linkedChat.trim()}} />`)+ .replace(panelStart, ' <BindingDialogFrame key={job.id} job={job}><AutomationDetailPanel\n')+ .replace(panelEnd, ' onRequestDelete={onRequestDelete}\n /></BindingDialogFrame>'),+ map: null,+ };+ },+ }, react()],+ resolve: {+ alias: { '@': path.join(webui, 'src') },+ dedupe: ['react', 'react-dom', 'lucide-react', 'react-i18next', 'i18next'],+ },+ css: {+ postcss: {+ plugins: [tailwindcss({+ ...baseTailwind,+ content: [+ normalizePath(path.join(webui, 'src/**/*.{ts,tsx}')),+ normalizePath(path.join(repository, 'nanobot/channels/*/webui/**/*.{ts,tsx}')),+ normalizePath(path.join(webui, 'node_modules/streamdown/dist/*.js')),+ normalizePath(path.join(root, '*.{tsx,html}')),+ ],+ }), autoprefixer()],+ },+ },+ // No API proxy. The proposal must not talk to an installed gateway.+ server: { host: '127.0.0.1', port: 53822, strictPort: true, fs: { allow: [repository] } },+ preview: { host: '127.0.0.1', port: 53822, strictPort: true },+ build: { outDir: path.join(root, 'dist') },+});