feat(webui): persist reviewed automation chat changes

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

No files matched your search

@@ -1,173 +0,0 @@
import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from 'react';
import { ChevronDown, MoreHorizontal, 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 { Disclosure } from '@/components/ui/disclosure';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
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="flex min-w-0 flex-wrap items-baseline gap-x-2 text-[13px] leading-5">
<span className="min-w-0 break-words">{item.name}</span><span className="text-[12px] text-muted-foreground">{item.platform}</span>
</span>
</span>;
}
function ChatPicker({ value, disabled, onChange, detail = false }: {
value: Target; disabled: boolean; onChange: (target: Target) => void; detail?: boolean;
}) {
return <Select value={value} onValueChange={value => onChange(value as Target)} disabled={disabled}>
<SelectTrigger aria-label={detail ? '任务所在聊天' : '新聊天'} data-binding-select={detail || undefined}
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 ${detail ? 'border-transparent bg-transparent hover:bg-muted/50' : ''}`}>
<SelectValue><ConversationIdentity target={value} /></SelectValue>
</SelectTrigger>
<SelectContent>
{(Object.keys(targets) as Target[]).map(key => <SelectItem key={key} value={key} textValue={`${targets[key].name} ${targets[key].platform}`}
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"><ConversationIdentity target={key} /></SelectItem>)}
<SelectItem value="offline" disabled className="h-auto min-h-11 text-[12px]">值班群 · 飞书(暂时无法连接)</SelectItem>
</SelectContent>
</Select>;
}
// 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 [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 (draft === saved || !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(''); 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 outline-none">更换聊天</DialogTitle>
</DialogHeader>
<div className="min-h-0 space-y-4 overflow-y-auto overscroll-contain px-6">
<div className="space-y-2">
<ChatPicker value={draft} disabled={saving || locked} onChange={target => { setDraft(target); setError(''); }} />
<p className="text-[12px] leading-5 text-muted-foreground">原聊天:{targets[saved].name} · {targets[saved].platform}</p>
<p className="text-[13px] leading-5">后续任务会使用新聊天的记录,结果也默认发到这里。</p>
</div>
<div className="space-y-2">
<label className="block space-y-2"><span className="text-[13px] font-medium">任务说明</span>
<Textarea aria-label="任务说明" rows={3} value={message} disabled={saving} onChange={event => { setMessage(event.target.value); setError(''); }} className="min-h-20 resize-y text-base leading-6 sm:text-[13px] sm:leading-5"/>
</label>
{message.includes(legacy.trim()) ? <div className="flex flex-wrap items-center gap-x-2 text-[12px] leading-5">
<span className="text-muted-foreground">说明仍要求发到微信。</span>
<Button variant="link" size="sm" className="h-auto min-h-11 px-0 py-1 text-[12px] sm:min-h-7" disabled={saving} onClick={() => setMessage(message.replace(legacy, ''))}>移除旧指令</Button>
</div> : null}
{targets[draft].group ? <p className="flex items-start gap-2 text-[12px] leading-5 text-muted-foreground"><Users className="mt-0.5 h-4 w-4 shrink-0" aria-hidden/>群成员可能看到任务内容和结果。</p> : null}
</div>
<Disclosure summary={<><ChevronDown className="h-3.5 w-3.5 shrink-0 transition-transform group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" aria-hidden/>记录和执行时间</>}
summaryClassName="flex min-h-9 items-center gap-1.5 rounded-control text-[12px] text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
contentClassName="pt-1 text-[12px] leading-5 text-muted-foreground">
旧聊天记录不会迁移。执行时间和启用状态不变,也不会立即运行。
</Disclosure>
{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}>取消</Button>
<Button size="sm" className="h-11 min-w-24 sm:h-9" disabled={draft === saved || !message.trim() || saving || locked} aria-busy={saving} 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>
<dl><div className="grid min-w-0 grid-cols-1 items-start gap-1 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">
<ChatPicker value={state.saved} disabled={state.locked} onChange={state.select} detail />
</dd>
</div></dl>
<p role={state.notice ? 'status' : undefined} className="mt-1 text-[12px] leading-5 text-muted-foreground">{state.locked ? (job.state.pending ? '执行或排队期间不能更换。' : '当前版本暂不支持更换。') : state.notice || '使用这里的聊天记录,结果也默认发到这里。'}</p>
</div>;
}
export function BindingDetailActions({ job, currentUi, busy, canToggle, canRun, localTrigger, originHref, onToggle, onRun, onEdit, onDelete }: {
job: SessionAutomationJob; currentUi: ReactNode; busy: boolean; canToggle: boolean; canRun: boolean;
localTrigger: boolean; originHref: string | null;
onToggle: () => void; onRun: () => void; onEdit: () => void; onDelete: () => void;
}) {
const preview = useContext(PreviewContext);
if (preview?.mode === 'current') return currentUi;
return <div className="flex shrink-0 items-center gap-2 border-t border-border/45 px-6 py-3">
{/* The detail dialog already owns the modal lock. */}
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild><Button size="icon" variant="ghost" disabled={busy} aria-label="更多操作" 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={onToggle}>{job.enabled ? '停用任务' : '启用任务'}</DropdownMenuItem>
{originHref ? <DropdownMenuItem asChild><a href={originHref}>打开聊天</a></DropdownMenuItem> : null}
<DropdownMenuSeparator />
<DropdownMenuItem tone="destructive" disabled={busy} onSelect={onDelete}>删除任务</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={onEdit}>编辑</Button>
{!localTrigger ? <Button variant="secondary" size="sm" className="h-11 font-normal sm:h-9" disabled={busy || !canRun} onClick={onRun}>立即运行</Button> : null}
</div>
</div>;
}
+72 -165
View File
@@ -1,184 +1,91 @@
# Automation chat proposal
# Automation chat selection
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.
This draft now implements chat selection in the production WebUI and Python
gateway. The earlier in-memory preview and its build transform have been removed.
See [the user guide](../../../docs/automations.md#change-the-chat-for-a-scheduled-task)
for the interaction, limits, and downgrade warning.
## Problem
## Design decision
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 concerns in [#5513](https://github.com/HKUDS/nanobot/issues/5513#issuecomment-5488297111)
and [#5620](https://github.com/HKUDS/nanobot/pull/5620#issuecomment-5534384796)
still apply: running in chat A and forwarding the result to chat B separates
the reply from its history and can expose context from A.
The interface should answer two questions in plain language:
This implementation changes the whole binding for future runs: execution chat,
recorded turn, and default reply route. It does not add a delivery override or
copy old messages. It still changes the creation-chat rule. Maintainer agreement
is pending, so the PR remains a draft.
- Which chat does this task use?
- If I change it, what happens to the next run?
## Ownership and commit boundary
## Proposed interaction
- The gateway resolves existing session handles, titles, canonical reply routes,
channel availability, and effective workspace policy. The browser cannot submit
a raw session key, channel, recipient, or topic address.
- `GET /api/webui/automations/chats?id=...` uses the existing API authentication.
`automation.change_chat` uses the authenticated WebSocket mutation path. A
direct HTTP mutation is rejected. Its values are `target_id`, `revision`, and
the reviewed `message`.
- The gateway resolves the target again at save time. It rejects unknown,
offline, foreign-scope, and unsupported targets. Topic address metadata is
retained; sender identity and previous workspace policy are not copied.
- The cron owner compares the reviewed revision after merging pending CLI
actions. It rejects while a scheduled turn owns a live execution snapshot,
including one waiting in the agent queue. This first version conservatively
blocks changes while any scheduled turn is active.
- One atomic write saves the whole binding and reviewed prompt before the new
snapshot becomes live. A pre-commit write failure leaves the old state intact.
If directory sync fails after replacement, the owner reads back that exact
snapshot before reporting success. A binding version prevents an older CLI
action snapshot from restoring the previous route.
- Each run retains its session identity. Before the first supported move, older
run records are stamped with the known unchanged original binding. Audit result
checks still verify job, run, session, status, and file path.
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.
No new execution path, agent-loop policy, dependencies, or separate CSS system
are added. The dialog uses the existing Select, Dialog, Button, Textarea, channel
logos, and DropdownMenu. The detail dialog owns the modal lock. Confirmation is
explicit and progress stays local to that action. The page remains visible.
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. Keep the new chat editable in that step. Show the original chat below it.
Explain that future runs use the new chat's history and reply there by default.
4. Let the user review and edit the task prompt. Warn when the target is a group.
5. Use one explicit “确认并更换” (“Confirm and change”) action. Do not add a
second confirmation checkbox. Put history and schedule details in a disclosure.
6. Change the displayed saved chat only after the save succeeds. Keep the draft
after a conflict or when the user returns to the task details.
## Compatibility
Keep “Edit” and “Run now” visible in the detail footer. Put enable/disable,
delete, and the existing open-chat link in “More”. Keep the existing delete
confirmation. Reuse the shared Disclosure and DropdownMenu controls, as the
remote-connection screens do; do not add another style system. The menu is
non-modal because the detail dialog already owns the modal interaction lock.
The gateway advertises optional `webui.automation-chat.v1`; the core protocol
floor stays at 1. The optional `chat_binding_revision` job field exposes the
control only for supported jobs. A new client sends no new request to an old
host. An old client can keep using ordinary edits on a new host.
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).
Storage paths and job IDs do not change. `bindingVersion` and per-run `sessionKey`
are additive fields with legacy defaults. The active instance still owns its
cron store and action log. **Downgrade after a move is not transparent**: follow
the backup/restore procedure in the user guide. Mixed-version cron writers after
a move are not supported. Rejected stale CLI updates are logged; retry the edit
from the current version after reading the latest task.
## Decision needed before implementation
Explicit message-tool instructions can still override the default destination.
Prompt review is required, not automatic rewriting. The selector does not create
new isolation for shared workspace memory or files and does not guarantee that a
remote platform will accept delivery.
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.
## Verification
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.
The focused regression suite exercises the actual HTTP/WebSocket gateway,
session manager, scheduler, agent queue, persistence, and audit reader. It
checks save/read-back, execution history and outbound topic routing, old results,
revision conflict, pre/post-replace errors, stale CLI actions, running jobs,
scope and route filtering, and old-host UI behavior.
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 `6b24ed80`, `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.
Browser checks use the normal production build served by an isolated real
gateway. Chat data, model replies, and channel status are synthetic. Saves are
persisted to a temporary cron store; model network calls and external channel
senders are not started. Checks cover restart/read-back, running a saved task,
concurrent-edit rejection with retained draft, deletion cancellation, and
desktop/320 px/390 px layouts. This is not physical-iOS or real-platform delivery
acceptance. Raw test logs and local fixture state are kept outside the repository.
## Screenshots
Synthetic data from this opt-in preview; neither screen changes a real task.
Both screenshots show the production app connected to that isolated gateway.
![Task details with the saved chat and channel logo](detail.jpg)
![Saved task chat with its channel logo](detail.png)
![Review the new chat and task prompt before confirmation](review.jpg)
## 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 the linked-chat and detail-action slots and wraps the
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.
- UI-only browser checks covered desktop, 320/390 px layouts, draft retention,
save acknowledgement, conflict, cancellation, keyboard flow, and the original
UI comparison. The narrow layouts have visible 44 px confirmation buttons and
16 px prompt input text. A delete-menu handoff exposed a stale pointer lock;
the non-modal menu fix was verified by cancelling deletion, closing details,
and opening another task. These 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.
![Review a chat change before saving](review.png)
Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

@@ -1,12 +0,0 @@
<!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>
-115
View File
@@ -1,115 +0,0 @@
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/>);
Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

@@ -1,5 +0,0 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": { "types": ["node", "vite/client"] },
"include": ["main.tsx", "BindingControls.tsx"]
}
@@ -1,78 +0,0 @@
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 />';
const actionsStart = ' {canManage ? (\n <div className="flex shrink-0 flex-wrap items-center gap-x-6 gap-y-2 border-t border-border/45 px-6 py-3">';
const actionsEnd = '\n ) : null}';
// These opt-in slots never edit product source or enter the production build.
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, actionsStart]) {
if (code.split(anchor).length !== 2) {
throw new Error('Automation detail markup changed. Update the proposal seam.');
}
}
const from = code.indexOf(actionsStart);
const to = code.indexOf(actionsEnd, from);
if (to < 0) throw new Error('Automation detail actions changed. Update the proposal seam.');
const actions = code.slice(from, to + actionsEnd.length);
return {
code: `import { BindingControls, BindingDialogFrame, BindingDetailActions } 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>')
.replace(actions, ` {canManage ? <BindingDetailActions job={job} busy={busy} canToggle={canToggle} canRun={canRun} localTrigger={localTrigger} originHref={originHref}
onToggle={() => void onAction(job.enabled ? "disable" : "enable", job)} onRun={() => void onAction("run", job)}
onEdit={() => onRequestEdit(job)} onDelete={() => onRequestDelete(job)} currentUi={<>{${actions.trim().slice(1, -1)}}</>} /> : null}`),
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') },
});