🤖 Open-source, local-first alternative to Grok Bot, OpenAI dots and Claude Duet. Your own AI bots on any model: GPT, Claude, Gemini, Grok, DeepSeek, Kimi, GLM and 70+ more through one Modelflare key. Reach them in the app, WeChat or Feishu; they remember you, work in the background, run commands and use your computer. Pay per use.
Python ai-agentai-assistantchatbotclaudecomputer-usedeepseekdesktop-appdshelectronfeishugeminigptgrokllmlocal-firstmodelflaremulti-modelopenai-compatiblepersonal-ai-agentwechat
ui: Modelflare-first onboarding, chat-first shell, magpie-style settings
dyk984c18ed0a8ecb
diff --git a/.env.example b/.env.exampleindex b6f6165..54d1053 100644--- a/.env.example+++ b/.env.example@@ -11,16 +11,18 @@# 内置 magpie 可执行文件(默认自动查找 build/bin 或桌面版 resources/magpie)# AMB_MAGPIE_BIN=-# 改用外部 OpenAI 兼容端点(设置后不启动内置 magpie,“模型”页不可用)+# 仅开发/测试:改用外部 OpenAI 兼容端点(设置后不启动内置网关,界面视为已连接、不显示 Modelflare 连接管理)# AMB_MAGPIE_BASE_URL=http://127.0.0.1:8080/v1# AMB_MAGPIE_API_KEY=+# 仅开发/测试:把 Modelflare 基址指向本地 mock(界面无法设置;正式使用只有 modelflare.dev 与 origin.modelflare.dev 两条线路)+# AMB_MODELFLARE_BASE_URL=http://127.0.0.1:8080/v1# 对话-# AMB_DEFAULT_MODEL=deepseek/deepseek-chat+# AMB_DEFAULT_MODEL=openai/gpt-5.6-sol# AMB_CONTEXT_MESSAGES=40# AMB_CONTEXT_CHARS=24000-# 飞书(仅首次创建默认机器人时读取;之后在界面「渠道」页修改)+# 飞书(仅首次创建默认机器人时读取;之后在界面信息面板「渠道」里修改)# FEISHU_APP_ID=cli_xxx# FEISHU_APP_SECRET=# AMB_FEISHU_THROTTLE_MS=400diff --git a/.taste-skill/app/direction.json b/.taste-skill/app/direction.jsondeleted file mode 100644index 03e20a6..0000000--- a/.taste-skill/app/direction.json+++ /dev/null@@ -1,210 +0,0 @@-{- "version": 1,- "kind": "app",- "at": "2026-10-27T16:02:02.968Z",- "seed": 1625474270,- "input": {- "kind": "devtools",- "brief": "anymodel bot: Electron desktop control panel for self-hosted AI bots. Operator manages bots, WeChat/Feishu channels, Magpie model gateway, computer-use, approvals, conversations. Chinese-first UI. Dense technical admin, calm and precise, not SaaS marketing.",- "theme": null,- "screens": [- "overview",- "list",- "settings"- ],- "keep": [],- "style": null- },- "style": {- "id": "framed-sheet",- "name": "Framed sheet",- "theme": "light",- "basis": "6 screens: a developer platform overview, an analytics overview, an events analytics tab, a list detail, a reports dashboard, a flow builder",- "suits": [- "analytics",- "devtools",- "builder",- "smb-admin",- "support",- "commerce",- "report"- ],- "idea": "The app chrome is one tinted L-shaped frame; the work sits on a white sheet with a hairline edge and soft corners, so depth comes from a single tone step and no shadow.",- "colourBudget": "under 3%; the brand shrinks to the logo and a 2px tab underline, the data carries the chroma",- "tokens": {- "ground": "#f9fbfc",- "surface": "#ffffff",- "raised": "#f4f6f8",- "active": "#ebedee",- "border": "#e8eaec",- "rule": "#f0f1f2",- "control": "#cdced1",- "text": "#131416",- "muted": "#5d5f60",- "accent": "#1b6c80",- "positive": "#1e7b4f",- "negative": "#c4242a",- "warning": "#92400e",- "chart": [- "#1b6c80",- "#2f70bb",- "#a86f0c"- ],- "pills": {- "positive": [- "#dcfae5",- "#04250e"- ],- "negative": [- "#ffedea",- "#831c1e"- ],- "warning": [- "#fffbeb",- "#92400e"- ],- "neutral": [- "#ebedee",- "#353736"- ]- },- "radius": {- "card": 8,- "control": 6,- "sheet": 16- },- "sheetInset": 8,- "font": {- "family": "IBM Plex Sans",- "second": "IBM Plex Mono, for IDs and keys only",- "fallback": "Inter, system-ui, sans-serif",- "sizes": {- "title": 22,- "section": 16,- "kpi": 28,- "body": 14,- "small": 12- },- "weights": [- 400,- 500,- 600- ],- "note": "KPI values at 400; the semibold goes on the label and the active tab."- },- "density": "medium",- "rowHeight": 48,- "sidebarWidth": 228,- "gap": 24,- "pad": 24,- "controlHeight": 32- },- "shell": "framed-sheet",- "shellAlternatives": [],- "signature": "One tinted frame holds the sidebar and the 48px top bar with no rule between them; the page is a white sheet inset 8px from the window's right and bottom edges, with a 1px edge, 16px corners and no shadow. The active tab is a 2px underline in ink or the accent; everything else in the chrome is grey.",- "identity": [- "The frame tinted from the product's colour in place of #f9fbfc: one low-chroma step of its hue (a green-grey for a climate or farm tool, a blue-grey for an observability tool, a stone for a print shop). The sheet stays white.",- "The brand's own hue from the brief as --chart-1 in place of the dealt teal, on the main series and the one selected state, at 3:1 or more on white, never violet or indigo.",- "IBM Plex Mono for IDs, keys and the figures in tables (one job): its figures have their own drawing, and a developer reads them as the product's."- ],- "avoid": [- "a border between the sidebar and the top bar",- "a shadow under the sheet",- "cards whose border is heavier than the sheet's (#cdcfcf on cards read as heavy in the study)",- "a fourth nesting level: frame, sheet and card are enough",- "different gutters for the KPI row and the chart row (20 against 24 was flagged)"- ],- "notes": "The study's second data hue in this style was an orange (#e88e46) that falls inside the house terracotta range; the third chart colour here is an amber moved out of that range and darkened to 3:1 on white."- },- "shell": {- "id": "framed-sheet",- "name": "Tinted frame, white sheet",- "basis": "8 of 23 screens, in three variants",- "suits": [- "analytics",- "devtools",- "builder",- "smb-admin",- "support"- ],- "numbers": {- "chrome": "#f6f6f6-#f9fbfc (a warm #f7f6f2 once)",- "sheetInset": "8px from the window's right and bottom edges (12 and 16 once each)",- "sheetRadius": "10-16, median 16",- "sheetEdge": "1px #eaeaea-#ededed, no shadow",- "sidebarWidth": "220-263 (228 on two screens)",- "topBar": "48px on the chrome ground with no rule; search 548x32 centred on the window with a shortcut hint",- "contentPadding": 24,- "floatingVariant": "both panels inset 12px with a 12px gutter, radius 10"- },- "blueprint": "Sidebar and top bar share one tinted ground with no rule between them, forming an L; the page lives on a white sheet. Variant one: the sheet butts against the sidebar and the top bar and is inset 8px from the right and bottom edges, 16px radius, 1px edge. Variant two: a flush L-frame with no inset, the frame marked by one rule. Variant three: sidebar and content are two floating panels inset 12px from every edge with a 12px gutter. The top bar, when present, is 48px and holds a centred search, the account button and a help or AI icon. Inside the sheet the content has 24px padding and starts with the breadcrumb or title row.",- "phone": "The frame disappears: the sheet becomes the screen, with a 48px top bar (menu button, title, one action) on the chrome tint. The search moves into the menu sheet or behind an icon."- },- "screens": [- {- "name": "overview",- "pattern": {- "id": "deploy-health-lead",- "name": "Current deploy and health lead",- "screen": "overview",- "kinds": [- "devtools"- ],- "basis": "house pattern from testing: built after a flat 24-hour chart filled a whole first screen and lost to a richer layout",- "blueprint": "Title row: the project's name as the h1 with a status pill (Healthy, Degraded) and a breadcrumb of team and product above it; repository, branch and a freshness stamp in a 14px grey line under it; the one primary action (Redeploy, or View logs when the latest deploy failed) on the right. Then a full-width card for what is live now: the production deployment's commit message at 16/600, its branch, short SHA in mono, author and age on the left, and three or four facts in divided cells on the right (domain, live since, build time, regions). Then the health strip: three or four KPIs in one divided container, each with its change in words and in the polarity colour when it moved the wrong way. Then a two-column row: the 24-hour chart at two-thirds (deploy markers as 1px ticks with their short SHA, the budget or SLO as a dashed reference line) and, at one-third, the block that explains the worst number (the spike and what reverted it, the status codes behind the error rate). Then the deployments table capped at 6 rows, a failed row carrying its failing step and a View logs action, a building row its elapsed time.",- "phone": "The live deployment card becomes a stack of label-value rows; the KPIs a 2x2 grid; the chart full width with its markers; the explanation under it; deployments as two-line rows with region and duration on line 2."- }- },- {- "name": "list",- "pattern": {- "id": "table-filter-bar",- "name": "Table with tabs and a filter bar",- "screen": "list",- "kinds": [- "community",- "devtools",- "commerce",- "support",- "smb-admin"- ],- "basis": "an events back office, a tracks studio, a sessions overview",- "blueprint": "Title row: an 18-24px title on the left, at most an outlined secondary and the one primary (36px) on the right. Underline tabs for the list's states on a full-width 1px rule with a 2px indicator as wide as the label; 22-32px below, the toolbar: a search of about 252-316 x 32-36 on the left, the count ('7 events') and the sort on the right. The table sits on the panel or page ground with no card around it: a header of 12-13px grey sentence-case labels with no fill and no rule, rows on a 48-56px pitch for one line or 72-92px with a thumbnail (media height plus 24-32px), 1px rules 3-7% darker than the ground or no rules at all, the identity column given the most width, numbers right-aligned in tabular figures with the unit muted ('5 /10'), one status mark per row and one kebab at the far right. Drop a column that is empty in every row (a blank co-host column left a 300px dead band). On an overview, cap the rows and link to the full list; on the full list, state the total and load more at the end.",- "phone": "Rows become two-line items: identity and the key number on line 1, the secondary fields in 13px grey on line 2, the kebab at the right. Tabs scroll in their own row; the search becomes a full-width field."- }- },- {- "name": "settings",- "pattern": {- "id": "settings-two-column",- "name": "Settings in two columns",- "screen": "settings",- "kinds": [- "devtools",- "smb-admin",- "support",- "workspace",- "commerce",- "analytics",- "finance",- "wallet",- "creator",- "community",- "builder",- "markets",- "report"- ],- "basis": "one settings page; stacking from a narrow rail card. The basis is thin.",- "blueprint": "A centred column of about 1152px. Each section is one row: a label column of about 450px (16/500 title, 14px grey description; the title's cap top 6-8px below the panel top, level with the panel's first line) beside a panel of about 700px with a #fafafa fill, 16px radius, 16px padding, no border and no shadow. Sections are split by a full-width 1px rule with 32px above and below. Inside a panel: field labels 14/500 above 40px white inputs (1px #e8e8e8, radius 10), 8px from label to field, 16px between fields, 24px from the description to the first label, 16px to the Save button; switch rows with a 14/500 title, a 20px status badge 8px after it, a 14px grey description and a 28x16 toggle 16px from the right edge, centred on the title line. A plan-gated feature shows a 48px tinted strip with a 32px button directly above its panel, and the panel stays readable. When a panel runs much taller than its label, put the section's help or a summary of the current values in the label column rather than 250px of nothing.",- "phone": "Each section stacks: title and description, then the panel at full width. Inside, label, 8-10px, field, 16-26px to the next pair; toggles stay on the right of their title."- }- }- ],- "fusion": {- "overrideAccent": "#4f46e5",- "reason": "Fuse with embedded magpie GUI; indigo + greys from magpie app.css replace dealt teal #1b6c80",- "font": "system stack + PingFang SC / Microsoft YaHei (magpie)",- "layout": "chat-first three-column (list | chat | detail); framed-sheet tokens kept for density/radii",- "face": "anymodel bot monogram on accent-soft indigo disc; product name in sidebar"- }-}diff --git a/README.md b/README.mdindex d9e53b8..54474ce 100644--- a/README.md+++ b/README.md@@ -1,7 +1,8 @@-# anymodel bot+# AnyModelBot任意模型的个人 AI 助手:一个机器人 = 人设 + 默认模型 + 渠道(飞书 / 微信)。-模型调用全部经过**内置的 [magpie](https://github.com/yetone/magpie) 模型网关**(OpenAI 兼容 `/v1`),在管理界面里加服务商、切模型、看用量。+模型来自 **[Modelflare](https://modelflare.dev)**:首次启动粘贴一个 Modelflare API Key,GPT、Claude、Grok、Gemini 等模型自动列出。+请求经过内置的 [magpie](https://github.com/yetone/magpie) 网关转发(实现细节,界面里不出现)。- 飞书:官方机器人,长连接(WSClient)接收事件,CardKit 流式卡片回复- 微信:官方 iLink 通道(移植自 Tencent/openclaw-weixin),扫码登录@@ -18,11 +19,12 @@ src/magpie/ 内置 magpie 守护:隔离目录、空闲端口、自动生成密钥、健康检查、崩溃重启、干净退出channels/ feishu/(长连接 + CardKit) weixin/(iLink,MIT 声明见 LICENSE.openclaw-weixin)store/ SQLite(node:sqlite,无需原生编译)- web/ 管理界面服务 + /magpie/ 反向代理+ modelflare.ts Modelflare 线路与密钥校验(GET /v1/models)+ web/ 管理界面服务(JSON API + 流式对话 SSE)cli/ init 首次设置向导、weixin-loginmain.ts 命令行入口electron/ 桌面版主进程(启动器 + 托盘)-ui/ 管理界面(Preact + htm,无构建步骤)+ui/ 管理界面(Preact + htm,无构建步骤):tokens.css、css/、lib/、components/、screens/、main.jsscripts/ setup / build-magpie / fetch-cua-driver / electron-smokevendor/magpie magpie 源码(git 子模块,构建时编译)```@@ -34,8 +36,8 @@ vendor/magpie magpie 源码(git 子模块,构建时编译)```bashnpm installnpm run setup # 拉取 vendor/magpie 子模块并编译到 build/bin/-npm run init # 可选:首次设置向导(模型服务商 Key、飞书凭据)-npm start # 启动全部:magpie + 机器人 + 管理界面 http://127.0.0.1:3600/+npm run init # 可选:终端里的首次设置(Modelflare API Key、飞书凭据)+npm start # 启动全部:内置网关 + 机器人 + 管理界面 http://127.0.0.1:3600/```数据默认在 `./data`(`AMB_DATA_DIR` 可改)。其余环境变量见 `.env.example`。@@ -50,7 +52,8 @@ npm run dist:linux | dist:mac | dist:win```- 数据目录:`<userData>/data`(macOS `~/Library/Application Support/anymodel bot/data`,Windows `%APPDATA%\anymodel bot\data`,Linux `~/.config/anymodel bot/data`)-- 单实例;关闭窗口隐藏到托盘;托盘菜单:打开 / 在浏览器中打开 / 开机自启(macOS、Windows)/ 打开数据目录 / 退出+- 单实例;关闭窗口默认隐藏到托盘(设置 → 常规 可改为退出);托盘菜单:打开 / 在浏览器中打开 / 开机自启(macOS、Windows)/ 打开数据目录 / 退出+- macOS 下窗口无标题栏,红绿灯嵌在侧栏顶部;窗口最小宽度 860- 界面只监听 127.0.0.1,且每次启动生成随机访问令牌,其他本机程序无法直接调用管理接口- 退出时先停渠道、再停 magpie;若上次被强杀残留 magpie 进程,下次启动会自动清理(Linux/macOS)@@ -63,18 +66,28 @@ docker run -d --name amb -p 3600:3600 -v amb-data:/data anymodel-botdocker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令牌>```-容器内界面监听 0.0.0.0,因此强制令牌访问。微信扫码在界面「渠道」页完成。+容器内界面监听 0.0.0.0,因此强制令牌访问。微信扫码在对话页的信息面板(点顶部机器人名称)→「渠道」里完成。-## 模型(内置 magpie)+## 模型(Modelflare)-- 管理界面「概览」可快速添加预设服务商(DeepSeek、OpenAI、Anthropic、Kimi、通义等);「模型」页内嵌 magpie 完整界面(自定义端点、路由、用量)。-- 对话中发送 `/model` 查看可用模型,`/model <名称>` 为当前会话切换模型;`/reset` 清空上下文。-- 隔离与安全:magpie 使用本程序数据目录内独立的 HOME/配置目录;**不读取**你电脑上已有的 Claude/Codex 等订阅凭据,**不改写**任何 agent 配置,关闭自动更新与账户发现;界面代理还会拦截 magpie 的 agent 接入、账户、更新等接口。-- API Key 只保存在 magpie 的隔离配置中,不经过命令行参数、不写日志。+- 首次启动只有一个页面:粘贴 Modelflare API Key → 校验(`GET https://modelflare.dev/v1/models`)→ 选默认模型 → 开始对话。还没有 Key 可去 [Modelflare](https://modelflare.dev) 控制台创建。+- 线路:默认国际线路 `https://modelflare.dev/v1`;中国大陆可在「高级」或 设置 → Modelflare → 线路 选「中国大陆优化」(`https://origin.modelflare.dev/v1`)。线路由你选定,不自动切换。+- 设置 → Modelflare:查看连接状态(只显示 Key 尾号)、更换密钥、断开(机器人与会话保留,断开后回到首次连接页)、默认模型、刷新模型列表;用量与账单以 Modelflare 控制台为准。+- 对话中输入框右侧的模型按钮可为当前会话切换模型(也可设为机器人默认);`/model`、`/reset`、`/new`、`/status`、`/help` 照常可用。+- 内置网关:magpie 以 `--gateway` 模式运行,使用本程序数据目录内独立的 HOME/配置目录;**不读取**你电脑上已有的 Claude/Codex 等订阅凭据,**不改写**任何 agent 配置,关闭自动更新与账户发现。它只供本进程内部调用,界面不再反代它的页面或 `/v1`。+- API Key 只保存在内置网关的隔离配置中,不经过命令行参数、不写日志,前端只拿到尾号。+- 开发/测试:设置 `AMB_MAGPIE_BASE_URL` 可直接使用一个 OpenAI 兼容端点(不启动内置网关,界面视为已连接);`AMB_MODELFLARE_BASE_URL` 可把 Modelflare 基址指向本地 mock。++## 界面++- 侧栏:机器人列表(头像 + 名称 + 最近一条消息),+ 新建,右键 重命名 / 删除;左下角账户按钮打开设置(`⌘/Ctrl+,`)。+- 对话页:顶部悬浮的机器人名称胶囊打开信息面板(`⌘/Ctrl+⇧+I`:渠道、待审批、记忆、最近会话,⚙ 进机器人设置);回复流式显示(Markdown、代码块一键复制),可随时停止(`Esc`);审批与提问以卡片形式出现在对话里;向上翻阅时不会被拉回底部。+- 命令面板 `⌘/Ctrl+K`;外观(跟随系统 / 浅色 / 深色)在 设置 → 常规。+- 视觉:中性色与组件改编自 magpie 的界面(MIT),强调色为 Modelflare 荧光黄绿 `#d7ff00`。## 电脑操作(Computer Use)-每个机器人可在「机器人 → 设置 → 电脑操作」中开关、选择后端和审批方式;`/status` 与设置页会显示当前后端、是否可用及原因。+每个机器人可在 机器人设置(信息面板的 ⚙)→ 电脑操作 中开关、选择后端和审批方式;`/status` 与设置页会显示当前后端、是否可用及原因。- **后端**- **Cua Driver(默认,三平台)**:随安装包附带官方预编译的 [cua-driver](https://github.com/trycua/cua/tree/main/libs/cua-driver) 0.37.0(MIT),构建时由 `scripts/fetch-cua-driver.mjs` 按平台/架构下载并校验 SHA256。作为内置 MCP 服务器 `cua-driver mcp` 运行,始终使用 `CUA_DRIVER_PERMISSION_MODE=bounded` + 能力清单,**从不**使用 `--dangerously-bypass-approvals`;子进程环境经过清理,不传任何密钥,关闭遥测,禁用 `run_script`。只开放所需的 24 个工具(读取窗口/截图、启动应用、点击、输入、按键、组合键、滚动、拖拽、设值、菜单等),其余工具(脚本、结束进程、剪贴板、浏览器注入、录制、更新等)对模型不可见且会被拒绝。清单列出本机已安装的图形应用(Linux 读 .desktop、macOS 读 /Applications、Windows 读开始菜单),并允许整屏输入;清单最长 24 小时有效,到期前自动重启驱动。@@ -94,7 +107,7 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令- `im:message.p2p_msg:readonly`(读取用户发给机器人的单聊消息)- `im:message:send_as_bot`(以应用身份发消息)- `cardkit:card:write`(创建与更新卡片,用于流式回复)-3. 先在本程序界面「渠道」页填入 App ID / App Secret 并启用(长连接需要程序在线才能保存下一步)。+3. 先在本程序信息面板的「渠道 → 飞书」里填入 App ID / App Secret 并保存(长连接需要程序在线才能保存下一步)。4. 事件与回调 → 订阅方式选「**使用长连接接收事件**」,添加事件 `im.message.receive_v1`。5. 发布版本并在可用范围内添加自己,然后在飞书里私聊机器人。@@ -102,7 +115,7 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令## 微信(iLink)-- 界面「渠道」页 → 微信 → 「扫码登录」,用微信扫描二维码并确认;或命令行 `npm run weixin:login`(终端显示二维码,同时保存 PNG 到数据目录)。+- 信息面板「渠道」→ 微信 → 「扫码登录」,用微信扫描二维码并确认;或命令行 `npm run weixin:login`(终端显示二维码,同时保存 PNG 到数据目录)。- 登录态、同步游标、context_token 保存在数据目录,重启后自动续用。- 平台限制:用户每发来一条消息后 24 小时内最多可回复 10 条;回复在生成结束后一次发出,超过 4000 字自动分段;生成期间显示“正在输入”。- 登录过期(错误码 -14)时自动暂停并在界面提示,重新扫码即可。@@ -111,9 +124,9 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令```bashnpm run typecheck-npm test # 单元测试 + 离线端到端(模拟飞书/iLink/OpenAI)+ magpie 集成测试(需已编译 magpie)+npm test # 单元测试 + 离线端到端(模拟飞书/iLink/Modelflare,含流式对话与停止)+ 内置网关集成测试(需已编译 magpie)```## 许可-MIT,见 `LICENSE`;第三方组件(magpie MIT、Tencent openclaw-weixin MIT 等)见 `THIRD_PARTY_NOTICES.md`。+MIT,见 `LICENSE`;第三方组件(magpie MIT——含界面样式改编、Tencent openclaw-weixin MIT 等)见 `THIRD_PARTY_NOTICES.md`,也可在 设置 → 关于 中查看。diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex e98a549..6789745 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -4,10 +4,16 @@ anymodel bot 自身以 MIT 许可发布(见 LICENSE)。以下组件随本程部分代码移植/改编自 Fei2411/DS-Bot(Apache-2.0),见下文「DS Bot」一节。-## magpie(内置模型网关,以二进制形式随附)+## magpie(内置模型网关,以二进制形式随附;界面样式部分改编自它)来源:https://github.com/yetone/magpie (vendor/magpie 子模块,v0.1.1720)+- 以二进制形式随附:内置模型网关。+- 改编:`ui/tokens.css`、`ui/css/base.css`、`ui/css/settings.css` 中的中性色、圆角、动效与组件样式+ (`.list` / `.row`、分段控件 `.seg`、弹出菜单 `.pop`、设置页页签、"已保存"胶囊)改编自+ `internal/gui/assets/app.css`。未使用 magpie 的名称、喜鹊标志、`assets/icons/` 中的厂商 logo、+ 赞助商/合作方图片或官网截图。+```MIT Licensediff --git a/electron/main.ts b/electron/main.tsindex 37eed2a..81ad85b 100644--- a/electron/main.ts+++ b/electron/main.ts@@ -3,7 +3,8 @@* - 单实例锁;数据目录 = <userData>/data(可用 AMB_DATA_DIR 覆盖)* - 在进程内启动 App(机器人运行时 + 渠道 + 管理界面 + 受管 magpie 子进程)* - 窗口加载本机管理界面(每次启动生成随机令牌,其他本机程序/浏览器无法直接访问)- * - 托盘:显示 / 开机自启 / 退出;关闭窗口=隐藏到托盘;退出时干净关闭 magpie+ * - 托盘:显示 / 开机自启 / 退出;关闭窗口=隐藏到托盘(可在设置 → 常规里改为退出);退出时干净关闭 magpie+ * - 设置页里的开机自启、缩放、打开数据目录经 core.desktop 回调到这里(同进程,无需 preload/IPC)* CLI(npm start)与 Docker 走同一套 src/ 代码,本文件只做桌面外壳。*/import { app, BrowserWindow, Menu, Tray, nativeImage, shell, dialog } from "electron";@@ -38,16 +39,21 @@ function showWindow(): void {win.focus();}+const PRODUCT = "AnyModelBot";+const canAutostart = process.platform === "darwin" || process.platform === "win32";+function createWindow(): void {win = new BrowserWindow({width: 1200,height: 820,- minWidth: 760,+ minWidth: 860,minHeight: 520,- title: "anymodel bot",+ title: PRODUCT,icon: iconPath(),show: !SMOKE,autoHideMenuBar: true,+ // macOS:无标题栏,红绿灯嵌进侧栏顶部(界面在 Electron + Mac 下给它留位);其他系统用系统标题栏+ ...(process.platform === "darwin" ? { titleBarStyle: "hiddenInset" as const, trafficLightPosition: { x: 16, y: 15 } } : {}),webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true },});const origin = new URL(entryUrl).origin;@@ -62,25 +68,28 @@ function createWindow(): void {if (/^https?:/i.test(url)) void shell.openExternal(url);}});+ win.webContents.on("did-finish-load", () => win?.webContents.setZoomFactor(core?.config.ui.zoom ?? 1));win.on("close", (e) => {- if (!quitting && tray) {+ if (!quitting && tray && core?.config.ui.closeToTray !== false) {e.preventDefault();win?.hide();}});- win.on("closed", () => (win = undefined));+ win.on("closed", () => {+ win = undefined;+ if (!quitting && core?.config.ui.closeToTray === false) app.quit();+ });void win.loadURL(entryUrl);}function buildTray(): void {const img = nativeImage.createFromPath(iconPath()).resize({ width: 18, height: 18 });tray = new Tray(img);- tray.setToolTip("anymodel bot");- const canAutostart = process.platform === "darwin" || process.platform === "win32";+ tray.setToolTip(PRODUCT);const render = () =>tray!.setContextMenu(Menu.buildFromTemplate([- { label: "打开 anymodel bot", click: showWindow },+ { label: `打开 ${PRODUCT}`, click: showWindow },{ label: "在浏览器中打开", click: () => void shell.openExternal(entryUrl) },{ type: "separator" },{@@ -88,20 +97,24 @@ function buildTray(): void {type: "checkbox",enabled: canAutostart,checked: canAutostart && app.getLoginItemSettings().openAtLogin,- click: (item) => {- app.setLoginItemSettings({ openAtLogin: item.checked, args: ["--hidden"] });- render();- },+ click: (item) => setAutostart(item.checked),},{ label: "打开数据目录", click: () => void shell.openPath(core!.config.dataDir) },{ type: "separator" },{ label: "退出", click: () => app.quit() },]),);+ renderTray = render;render();tray.on("click", showWindow);}+let renderTray: (() => void) | undefined;+function setAutostart(on: boolean): void {+ app.setLoginItemSettings({ openAtLogin: on, args: ["--hidden"] });+ renderTray?.();+}+async function boot(): Promise<void> {const dataDir = process.env.AMB_DATA_DIR ? path.resolve(process.env.AMB_DATA_DIR) : path.join(app.getPath("userData"), "data");fs.mkdirSync(dataDir, { recursive: true });@@ -110,6 +123,13 @@ async function boot(): Promise<void> {config.ui.host = "127.0.0.1";if (!config.ui.token) config.ui.token = crypto.randomBytes(24).toString("base64url");core = new App(config);+ core.desktop = {+ autostart: () => ({ supported: canAutostart, on: canAutostart && app.getLoginItemSettings().openAtLogin }),+ setAutostart,+ applyZoom: (z) => win?.webContents.setZoomFactor(z),+ openDataDir: () => void shell.openPath(config.dataDir),+ openInBrowser: () => void shell.openExternal(entryUrl),+ };await core.start();if (!core.web) throw new Error("管理界面未启动");entryUrl = `${core.web.url.replace(/\/$/, "")}/?token=${encodeURIComponent(config.ui.token)}`;@@ -124,17 +144,18 @@ async function boot(): Promise<void> {async function smoke(out: string): Promise<void> {const wc = win!.webContents;await new Promise<void>((r) => (wc.isLoading() ? wc.once("did-finish-load", () => r()) : r()));- let text = "";+ // 未连接 Modelflare 时是引导页,已连接时是对话页;两者都带 data-screen+ let screen = "";for (let i = 0; i < 50; i++) {- text = String(await wc.executeJavaScript("document.body.innerText"));- if (text.includes("概览") && text.length > 40) break;+ screen = String(await wc.executeJavaScript("document.querySelector('[data-screen]')?.getAttribute('data-screen') || ''"));+ if (screen) break;await new Promise((r) => setTimeout(r, 200));}const img = await wc.capturePage();fs.writeFileSync(out, img.toPNG());const status = await wc.executeJavaScript("fetch('/amb/api/status').then(r=>r.status)");const magpie = await wc.executeJavaScript("fetch('/magpie/').then(r=>r.status)");- console.log(`SMOKE ${JSON.stringify({ hasUi: text.includes("概览"), status, magpie, magpieState: core?.magpie?.state, chars: text.length })}`);+ console.log(`SMOKE ${JSON.stringify({ hasUi: !!screen, screen, status, magpie, magpieState: core?.magpie?.state })}`);app.quit();}@@ -166,7 +187,7 @@ if (!app.requestSingleInstanceLock()) {.then(boot).catch((e) => {log.error((e as Error).stack || String(e));- dialog.showErrorBox("anymodel bot 启动失败", (e as Error).message);+ dialog.showErrorBox(`${PRODUCT} 启动失败`, (e as Error).message);app.exit(1);});}diff --git a/scripts/electron-smoke.mjs b/scripts/electron-smoke.mjsindex 93404cf..b28061b 100644--- a/scripts/electron-smoke.mjs+++ b/scripts/electron-smoke.mjs@@ -1,4 +1,4 @@-// 桌面版冒烟测试:启动 Electron(Linux 无显示时自动用 xvfb-run),加载界面、截图、检查 /amb/api/status 与 /magpie/,然后干净退出。+// 桌面版冒烟测试:启动 Electron(Linux 无显示时自动用 xvfb-run),加载界面、截图、检查 /amb/api/status、内置网关已运行且 /magpie/ 不再对外(404),然后干净退出。// 用法:node scripts/electron-smoke.mjs [可执行文件路径,默认 node_modules 中的 electron + 当前目录]import { spawnSync } from "node:child_process";import fs from "node:fs";@@ -26,5 +26,5 @@ if (!line) {}const res = JSON.parse(line.slice(6));console.log(res, "截图:", shot);-const ok = res.hasUi && res.status === 200 && res.magpie === 200 && res.magpieState === "running" && fs.existsSync(shot);+const ok = res.hasUi && res.status === 200 && res.magpie === 404 && res.magpieState === "running" && fs.existsSync(shot);process.exit(ok ? 0 : 1);diff --git a/src/app.ts b/src/app.tsindex 28b4ffc..4a1b37d 100644--- a/src/app.ts+++ b/src/app.ts@@ -1,5 +1,7 @@+import fs from "node:fs";+import os from "node:os";import path from "node:path";-import type { AppConfig } from "./config.js";+import { saveConfigFile, type AppConfig } from "./config.js";import { Store, type Bot } from "./store/db.js";import { OpenAICompatClient, type ModelClient } from "./llm/client.js";import { BotRuntime } from "./core/runtime.js";@@ -15,9 +17,41 @@ import { logger, mask } from "./log.js";import { AgentManager } from "./agent/manager.js";import { locateDshRuntime } from "./agent/host.js";import { findAppRoot } from "./magpie/supervisor.js";+import { MODELFLARE_LINES, modelflareBaseUrl, verifyModelflareKey, type ModelflareLine, type VerifyResult } from "./modelflare.js";const log = logger("app");+/** 桌面外壳(Electron 主进程)提供的能力;CLI / Docker 下为空 */+export interface DesktopHooks {+ autostart(): { supported: boolean; on: boolean };+ setAutostart(on: boolean): void;+ applyZoom(zoom: number): void;+ openDataDir(): void;+ openInBrowser(): void;+}++export interface ModelflareStatus {+ /** managed:经内置网关连接 Modelflare;external:使用环境变量指定的端点(开发/测试),界面不做连接管理 */+ mode: "managed" | "external";+ connected: boolean;+ keyTail: string;+ line: ModelflareLine;+ baseUrl: string;+ gateway: string;+}++let cachedVersion = "";+export function appVersion(): string {+ if (!cachedVersion) {+ try {+ cachedVersion = String(JSON.parse(fs.readFileSync(path.join(findAppRoot(), "package.json"), "utf8")).version || "");+ } catch {+ cachedVersion = "";+ }+ }+ return cachedVersion;+}+export interface AppOptions {/** 测试注入:替换飞书传输层 */feishuTransport?: (bot: Bot) => FeishuTransport;@@ -48,6 +82,7 @@ export class App {readonly queue = new KeyedQueue();readonly channels = new Map<string, BotChannels>();web: WebServer | undefined;+ desktop: DesktopHooks | undefined;private notices: Array<{ at: number; level: "info" | "warn"; text: string }> = [];constructor(readonly config: AppConfig, readonly opts: AppOptions = {}) {@@ -120,6 +155,59 @@ export class App {this.store.close();}+ get username(): string {+ try {+ return os.userInfo().username;+ } catch {+ return "";+ }+ }++ // ---------- Modelflare ----------+ private allowedModelflareUrls(): string[] {+ return [...new Set([...Object.values(MODELFLARE_LINES), modelflareBaseUrl("auto"), modelflareBaseUrl("cn")])];+ }++ modelflareStatus(): ModelflareStatus {+ const line = this.config.modelflare.line;+ if (!this.magpie) return { mode: "external", connected: true, keyTail: "", line, baseUrl: this.config.magpie.externalBaseUrl, gateway: "external" };+ const info = this.magpie.modelflareInfo();+ return { mode: "managed", connected: info.connected, keyTail: info.keyTail, line, baseUrl: info.baseUrl || modelflareBaseUrl(line), gateway: this.magpie.state };+ }++ /** 先校验(GET /models),通过后才写入网关;失败时什么都不改 */+ async connectModelflare(apiKey: string, line: ModelflareLine): Promise<VerifyResult> {+ if (!this.magpie) throw new Error("外部模型端点模式下不管理 Modelflare 连接");+ const baseUrl = modelflareBaseUrl(line);+ const r = await verifyModelflareKey(baseUrl, apiKey.trim(), { line });+ if (!r.ok) return r;+ await this.magpie.connectModelflare(apiKey, baseUrl, this.allowedModelflareUrls());+ this.setModelflareLineConfig(line);+ await this.runtime.listModels(true).catch(() => []);+ return r;+ }++ async setModelflareLine(line: ModelflareLine): Promise<void> {+ if (this.magpie && this.magpie.modelflareInfo().connected) await this.magpie.setModelflareUrl(modelflareBaseUrl(line), this.allowedModelflareUrls());+ this.setModelflareLineConfig(line);+ }++ private setModelflareLineConfig(line: ModelflareLine): void {+ this.config.modelflare.line = line;+ saveConfigFile(this.config.dataDir, (f) => (f.modelflare = { ...(f.modelflare ?? {}), line }));+ }++ async disconnectModelflare(): Promise<void> {+ if (!this.magpie) throw new Error("外部模型端点模式下不管理 Modelflare 连接");+ await this.magpie.disconnectModelflare();+ await this.runtime.listModels(true).catch(() => []);+ }++ setDefaultModel(model: string): void {+ this.config.llm.defaultModel = model;+ saveConfigFile(this.config.dataDir, (f) => (f.llm = { ...(f.llm ?? {}), defaultModel: model }));+ }+private seedDefaultBot(): void {if (this.store.listBots().length) return;const bot = this.store.createBot({@@ -153,7 +241,7 @@ export class App {fetchImpl: this.opts.weixinFetch,pollTimeoutMs: this.opts.weixinPollTimeoutMs,});- ch.weixin.onExpired = () => this.notice("warn", `机器人「${bot.name}」微信登录已过期,请在「渠道」页重新扫码`);+ ch.weixin.onExpired = () => this.notice("warn", `机器人「${bot.name}」微信登录已过期,请在信息面板的「渠道」里重新扫码`);ch.weixin.start();}}diff --git a/src/cli/init.ts b/src/cli/init.tsindex c053ad5..35f8742 100644--- a/src/cli/init.ts+++ b/src/cli/init.ts@@ -1,6 +1,6 @@/*** 首次设置向导(终端版;界面里也能完成同样的设置):- * 1. 模型服务商 + API Key → 写入内置 magpie 的隔离配置(key 经 stdin 传给 magpie CLI)+ * 1. Modelflare API Key → 先校验(GET /v1/models),再写入内置网关的隔离配置(key 不进命令行参数)* 2. 飞书 App ID / App Secret → 写入本程序数据库*/import readline from "node:readline";@@ -53,7 +53,7 @@ async function main(): Promise<void> {await app.magpie?.stop();app.store.close();}- console.log("\n完成。运行 npm start 启动;微信请在管理界面「渠道」页扫码,或运行 npm run weixin:login。");+ console.log("\n完成。运行 npm start 启动;微信请在管理界面的信息面板「渠道」里扫码,或运行 npm run weixin:login。");}async function setup(app: App, rl: ReturnType<typeof lineReader>, dataDir: string): Promise<void> {@@ -63,13 +63,14 @@ async function setup(app: App, rl: ReturnType<typeof lineReader>, dataDir: strinthrow new Error("找不到 magpie 可执行文件,请先运行:npm run setup");}await app.magpie.start();- const preset = (await rl.ask("模型服务商预设(如 deepseek / openai / anthropic / moonshot-cn / qwen-cn,留空跳过;运行 build/bin/magpie presets 查看全部):")).trim();- if (preset) {- const key = await rl.ask(`${preset} API Key:`, true);- if (key) {- const id = await app.magpie.addPresetProvider(preset, key);- console.log(`✓ 已添加服务商 ${id}`);- }+ const status = app.modelflareStatus();+ const hint = status.connected ? `已连接(尾号 ${status.keyTail}),回车保留` : "留空跳过,稍后可在界面里连接";+ const key = await rl.ask(`Modelflare API Key(${hint}):`, true);+ if (key) {+ const line = (await rl.ask("线路:回车 = 国际(modelflare.dev),输入 cn = 中国大陆优化(origin.modelflare.dev):")).trim() === "cn" ? "cn" : "auto";+ const r = await app.connectModelflare(key, line);+ if (!r.ok) throw new Error(r.message + (r.suggestLine === "cn" ? "(可重试并选择 cn 线路)" : ""));+ console.log(`✓ 已连接 Modelflare,找到 ${r.models.length} 个模型`);}}const appId = (await rl.ask("飞书 App ID(cli_xxx,留空跳过):")).trim();diff --git a/src/config.ts b/src/config.tsindex 3536c13..4eba2a4 100644--- a/src/config.ts+++ b/src/config.ts@@ -1,5 +1,6 @@import fs from "node:fs";import path from "node:path";+import { normalizeLine, type ModelflareLine } from "./modelflare.js";/*** 配置:<dataDir>/config.json + 环境变量(环境变量优先)。@@ -7,7 +8,17 @@ import path from "node:path";*/export interface AppConfig {dataDir: string;- ui: { host: string; port: number; token: string };+ ui: {+ host: string;+ port: number;+ token: string;+ /** 桌面版窗口缩放(1 = 100%) */+ zoom: number;+ /** 桌面版关闭窗口时:true 隐藏到托盘,false 退出 */+ closeToTray: boolean;+ };+ /** Modelflare 线路;密钥本身只存在内置 magpie 的隔离配置里 */+ modelflare: { line: ModelflareLine };magpie: {/** managed:由本程序启动并守护内置 magpie;external:使用已有 OpenAI 兼容端点(测试/高级用法) */mode: "managed" | "external";@@ -26,6 +37,8 @@ export function defaultDataDir(): string {return process.env.AMB_DATA_DIR ? path.resolve(process.env.AMB_DATA_DIR) : path.resolve(process.cwd(), "data");}+export const ZOOMS = [1, 1.1, 1.25, 1.5];+function num(v: string | undefined, d: number): number {const n = v === undefined || v === "" ? NaN : Number(v);return Number.isFinite(n) ? n : d;@@ -43,7 +56,10 @@ export function loadConfig(overrides: { dataDir?: string; env?: NodeJS.ProcessEnhost: env.AMB_UI_HOST || file.ui?.host || "127.0.0.1",port: num(env.AMB_UI_PORT, file.ui?.port ?? 3600),token: env.AMB_UI_TOKEN || file.ui?.token || "",+ zoom: ZOOMS.includes(Number(file.ui?.zoom)) ? Number(file.ui?.zoom) : 1,+ closeToTray: file.ui?.closeToTray !== false,},+ modelflare: { line: normalizeLine(file.modelflare?.line) },magpie: {mode: (env.AMB_MAGPIE_BASE_URL ? "external" : file.magpie?.mode) || "managed",binPath: env.AMB_MAGPIE_BIN || file.magpie?.binPath || "",@@ -64,3 +80,18 @@ export function loadConfig(overrides: { dataDir?: string; env?: NodeJS.ProcessEn},};}++/**+ * 改写 <dataDir>/config.json 的部分字段(读-改-写,经临时文件改名,避免写到一半被读到)。+ * 只写调用方给出的键;环境变量覆盖的值不会被写回文件。+ */+export function saveConfigFile(dataDir: string, mutate: (file: Record<string, any>) => void): void {+ const p = path.join(dataDir, "config.json");+ let file: Record<string, any> = {};+ if (fs.existsSync(p)) file = JSON.parse(fs.readFileSync(p, "utf8"));+ mutate(file);+ fs.mkdirSync(dataDir, { recursive: true });+ const tmp = `${p}.${process.pid}.tmp`;+ fs.writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n", { mode: 0o600 });+ fs.renameSync(tmp, p);+}diff --git a/src/core/runtime.ts b/src/core/runtime.tsindex 9702a69..fc0bc3f 100644--- a/src/core/runtime.ts+++ b/src/core/runtime.ts@@ -47,11 +47,12 @@ export class BotRuntime {const m = convModel || botModel || this.opts.defaultModel();if (m) return m;const list = await this.listModels();- if (!list.length) throw new Error("没有可用模型:请先在「模型」页(magpie)添加服务商并配置 API Key");+ if (!list.length) throw new Error("没有可用模型:请先连接 Modelflare(设置 → Modelflare)");return list[0];}- async handle(ev: InboundEvent, out: ReplySession): Promise<void> {+ /** signal:网页"停止"按钮;纯对话路径会中止模型请求并保留已生成的部分(代理回合无法中途打断,会在后台跑完) */+ async handle(ev: InboundEvent, out: ReplySession, opts: { signal?: AbortSignal } = {}): Promise<void> {const { store } = this.opts;const bot = store.getBot(ev.botId);if (!bot) throw new Error(`unknown bot ${ev.botId}`);@@ -89,7 +90,7 @@ export class BotRuntime {await out.apply({ type: "stream.start" });let acc = "";try {- const full = await this.opts.models.streamChat({ model, messages }, (delta) => {+ const full = await this.opts.models.streamChat({ model, messages, signal: opts.signal }, (delta) => {acc += delta;void out.apply({ type: "stream.update", text: acc });});@@ -98,6 +99,11 @@ export class BotRuntime {await out.apply({ type: "stream.finish", text: finalText });} catch (e) {const err = e as Error & { status?: number };+ if (opts.signal?.aborted) {+ if (acc) store.addMessage(conv.id, "assistant", acc);+ await out.apply({ type: "stream.finish", text: acc });+ return;+ }log.warn("model call failed", { model, status: err.status, message: err.message });const msg = acc ? `${acc}\n\n⚠️ 生成中断:${err.message}` : `⚠️ 模型调用失败(${model}):${err.message}`;await out.apply({ type: "stream.finish", text: msg });@@ -223,7 +229,7 @@ export class BotRuntime {}if (!arg) {const cur = convModel || botModel || this.opts.defaultModel();- if (!list.length) return "暂无可用模型,请先在「模型」页添加服务商。";+ if (!list.length) return "暂无可用模型:请先连接 Modelflare(设置 → Modelflare)。";return ["可用模型(回复 /model 编号 切换):", ...list.map((m, i) => `${i + 1}. ${m}${m === cur ? " ← 当前" : ""}`)].join("\n");}if (arg === "default" || arg === "reset") {diff --git a/src/magpie/supervisor.ts b/src/magpie/supervisor.tsindex 54f48e3..95da05e 100644--- a/src/magpie/supervisor.ts+++ b/src/magpie/supervisor.ts@@ -5,6 +5,7 @@ import net from "node:net";import path from "node:path";import { fileURLToPath } from "node:url";import { logger } from "../log.js";+import { MODELFLARE_PROVIDER, keyTail } from "../modelflare.js";const log = logger("magpie");@@ -359,43 +360,71 @@ export class MagpieSupervisor {this.state = "stopped";}- // ---------- 服务商管理(首次设置 / UI) ----------- async addPresetProvider(preset: string, apiKey: string): Promise<string> {- if (!/^[a-z0-9-]+$/.test(preset)) throw new Error("invalid preset id");- // 先用占位 key 创建,再通过 stdin 设置真实 key,避免密钥出现在进程参数里- const add = await this.runCli(["provider", "add", preset, "placeholder-key"]);- if (add.code !== 0) throw new Error(`provider add failed: ${(add.stderr || add.stdout).trim().slice(0, 300)}`);- const id = await this.findProviderId(preset);- await this.setProviderKey(id, apiKey);- return id;+ // ---------- Modelflare(唯一的服务商;界面里不出现"服务商"概念) ----------+ /**+ * 连接 Modelflare:没有就以占位 key 创建固定 id 的 provider,再经 /api/provider/save 写入地址与真实 key+ * (key 不出现在进程参数里)。重复连接 = 覆盖。baseUrl 必须是白名单里的地址。+ */+ async connectModelflare(apiKey: string, baseUrl: string, allowed: string[]): Promise<void> {+ if (!allowed.includes(baseUrl)) throw new Error("不支持的 Modelflare 地址");+ if (!apiKey.trim()) throw new Error("缺少 API Key");+ let id = this.modelflareId();+ if (!id) {+ const add = await this.runCli(["provider", "add", "Modelflare", `id=${MODELFLARE_PROVIDER}`, `url=${baseUrl}`, "key=placeholder-key"]);+ if (add.code !== 0) throw new Error(`创建 Modelflare 连接失败:${(add.stderr || add.stdout).trim().slice(0, 300)}`);+ id = this.modelflareId() ?? (await this.findProviderId(MODELFLARE_PROVIDER));+ }+ await this.saveProvider(id, { chat: baseUrl, key: apiKey.trim() });}- async addCustomProvider(name: string, url: string, apiKey: string, models: string[]): Promise<string> {- const args = ["provider", "add", name, `url=${url}`, "key=placeholder-key"];- if (models.length) args.push(`models=${models.join(",")}`);- const add = await this.runCli(args);- if (add.code !== 0) throw new Error(`provider add failed: ${(add.stderr || add.stdout).trim().slice(0, 300)}`);- const id = await this.findProviderId(name);- if (apiKey) await this.setProviderKey(id, apiKey);- return id;+ /** 切换线路:只改地址,key 不变 */+ async setModelflareUrl(baseUrl: string, allowed: string[]): Promise<void> {+ if (!allowed.includes(baseUrl)) throw new Error("不支持的 Modelflare 地址");+ const id = this.modelflareId();+ if (!id) return;+ await this.saveProvider(id, { chat: baseUrl });}- /**- * 设置服务商 API Key。magpie CLI 只接受命令行参数形式的 key(会出现在进程列表里),- * 所以改走 magpie 自己界面使用的 POST /api/provider/save(key 在请求体里,仅回环、带 web key)。- */- async setProviderKey(id: string, apiKey: string): Promise<void> {- if (this.state !== "running") throw new Error("magpie 未运行,无法保存 API Key");+ async disconnectModelflare(): Promise<void> {+ const id = this.modelflareId();+ if (!id) return;+ if (this.state !== "running") throw new Error("模型网关未运行,稍后再试");+ const res = await fetch(`${this.webOrigin}/api/provider/delete`, {+ method: "POST",+ headers: { "content-type": "application/json", cookie: `${this.cookieName}=${this.webKey}`, origin: this.webOrigin },+ body: JSON.stringify({ id }),+ signal: AbortSignal.timeout(15_000),+ });+ if (!res.ok) throw new Error(`断开失败:HTTP ${res.status} ${(await res.text()).slice(0, 200)}`);+ }++ /** 当前 Modelflare 连接(只回传尾号,不外传 key) */+ modelflareInfo(): { connected: boolean; keyTail: string; baseUrl: string } {+ const id = this.modelflareId();+ const p = id ? this.readProviderRaw(id) : undefined;+ const key = String(p?.key ?? "");+ const connected = !!key && key !== "placeholder-key";+ return { connected, keyTail: connected ? keyTail(key) : "", baseUrl: String(p?.chat ?? "") };+ }++ private modelflareId(): string | undefined {+ const hit = this.listProviders().find((p) => p.id.toLowerCase() === MODELFLARE_PROVIDER || p.name.toLowerCase() === MODELFLARE_PROVIDER);+ return hit?.id;+ }++ private async saveProvider(id: string, patch: Record<string, string>): Promise<void> {+ if (this.state !== "running") throw new Error("模型网关未运行,稍后再试");const p = this.readProviderRaw(id);if (!p) throw new Error(`provider ${id} not found`);const res = await fetch(`${this.webOrigin}/api/provider/save`, {method: "POST",headers: { "content-type": "application/json", cookie: `${this.cookieName}=${this.webKey}`, origin: this.webOrigin },- body: JSON.stringify({ ...p, key: apiKey, from: id }),+ body: JSON.stringify({ ...p, ...patch, from: id }),signal: AbortSignal.timeout(15_000),});- if (!res.ok) throw new Error(`保存 API Key 失败:HTTP ${res.status} ${(await res.text()).slice(0, 200)}`);- if (this.readProviderRaw(id)?.key !== apiKey) throw new Error("保存 API Key 后校验失败");+ if (!res.ok) throw new Error(`保存失败:HTTP ${res.status} ${(await res.text()).slice(0, 200)}`);+ const saved = this.readProviderRaw(id);+ for (const [k, v] of Object.entries(patch)) if (saved?.[k] !== v) throw new Error("保存后校验失败");}private readProviderRaw(id: string): Record<string, unknown> | undefined {diff --git a/src/modelflare.ts b/src/modelflare.tsnew file mode 100644index 0000000..f98c7b6--- /dev/null+++ b/src/modelflare.ts@@ -0,0 +1,84 @@+/**+ * Modelflare:本程序唯一的模型来源。+ * - 两条线路(文档《Which endpoint to call》):国际 modelflare.dev、中国大陆优化 origin.modelflare.dev;+ * 飞行中的 POST 不跨主机重定向,所以线路由用户事先选定,不自动切换。+ * - 连接前用 GET {base}/models + Bearer 校验密钥;错误按状态码给出可操作的说明。+ */+export type ModelflareLine = "auto" | "global" | "cn";++export const MODELFLARE_LINES: Record<Exclude<ModelflareLine, "auto">, string> = {+ global: "https://modelflare.dev/v1",+ cn: "https://origin.modelflare.dev/v1",+};++export const MODELFLARE_PROVIDER = "modelflare";++export function normalizeLine(v: unknown): ModelflareLine {+ return v === "global" || v === "cn" ? v : "auto";+}++/** 线路 → 基址。AMB_MODELFLARE_BASE_URL 仅供开发/测试(指向本地 mock),不经界面设置。 */+export function modelflareBaseUrl(line: ModelflareLine, env: NodeJS.ProcessEnv = process.env): string {+ const override = env.AMB_MODELFLARE_BASE_URL?.trim();+ if (override) return override.replace(/\/+$/, "");+ return line === "cn" ? MODELFLARE_LINES.cn : MODELFLARE_LINES.global;+}++export type VerifyFailure = "invalid_key" | "forbidden" | "rate_limited" | "upstream" | "network" | "bad_response";++export type VerifyResult =+ | { ok: true; models: string[] }+ | { ok: false; code: VerifyFailure; status?: number; message: string; suggestLine?: ModelflareLine };++/** 校验密钥:只发一次 GET /models,不重试、不换线路。 */+export async function verifyModelflareKey(+ baseUrl: string,+ apiKey: string,+ opts: { fetchImpl?: typeof fetch; timeoutMs?: number; line?: ModelflareLine } = {},+): Promise<VerifyResult> {+ const f = opts.fetchImpl ?? fetch;+ let res: Response;+ try {+ res = await f(`${baseUrl}/models`, {+ headers: { Authorization: `Bearer ${apiKey}`, Accept: "application/json" },+ signal: AbortSignal.timeout(opts.timeoutMs ?? 15_000),+ });+ } catch (e) {+ const host = safeHost(baseUrl);+ return {+ ok: false,+ code: "network",+ message: `连不上 ${host}(${(e as Error).name === "TimeoutError" ? "超时" : (e as Error).message})`,+ ...(opts.line !== "cn" ? { suggestLine: "cn" as const } : {}),+ };+ }+ if (res.status === 401) return { ok: false, code: "invalid_key", status: 401, message: "Key 无效或已被撤销" };+ if (res.status === 403) return { ok: false, code: "forbidden", status: 403, message: "这个 Key 没有权限调用该模型或分组" };+ if (res.status === 429) return { ok: false, code: "rate_limited", status: 429, message: `Modelflare 暂时不可用(HTTP 429)${retryAfter(res)}` };+ if (!res.ok) return { ok: false, code: "upstream", status: res.status, message: `Modelflare 暂时不可用(HTTP ${res.status})` };+ try {+ const body = (await res.json()) as { data?: Array<{ id?: unknown }> };+ if (!Array.isArray(body.data)) throw new Error("no data[]");+ return { ok: true, models: body.data.map((m) => String(m.id ?? "")).filter(Boolean).sort() };+ } catch {+ return { ok: false, code: "bad_response", status: res.status, message: "Modelflare 返回了无法识别的模型列表" };+ }+}++function retryAfter(res: Response): string {+ const s = res.headers.get("retry-after");+ return s ? `,${s} 秒后重试` : "";+}++function safeHost(url: string): string {+ try {+ return new URL(url).host;+ } catch {+ return url;+ }+}++/** 只用于展示的密钥尾号 */+export function keyTail(key: string): string {+ return key.length > 4 ? key.slice(-4) : "";+}diff --git a/src/web/proxy.ts b/src/web/proxy.tsdeleted file mode 100644index 0610562..0000000--- a/src/web/proxy.ts+++ /dev/null@@ -1,117 +0,0 @@-import http from "node:http";-import net from "node:net";-import path from "node:path";-import type { Duplex } from "node:stream";--/**- * 同源反向代理到 magpie web:- * - /magpie/* 去掉前缀转发(magpie 的 index.html 使用相对资源路径,可在子路径下工作);- * - magpie 前端写死的绝对路径(/api/*、/_magpie/*、/icons/*、插件页等)由“兜底”路由转发;- * - /v1* 转发到 gateway 端口(web 端口会把 /v1 当作“来自其他机器”而拒绝);- * - 服务端注入 magpie_web_<port> cookie,用户无需二次登录;浏览器端拿不到 magpie key。- */-export interface ProxyTarget {- webOrigin: () => string; // http://127.0.0.1:<webPort>- gatewayOrigin: () => string; // http://127.0.0.1:<gwPort>- cookie: () => string; // magpie_web_<port>=<key>- gatewayKey: () => string;- ready: () => boolean;-}--const HOP = new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade", "host"]);--function mapPath(url: string): { gateway: boolean; path: string } {- let p = url;- if (p === "/magpie") p = "/";- else if (p.startsWith("/magpie/")) p = p.slice("/magpie".length);- else if (p.startsWith("/magpie?")) p = "/" + p.slice("/magpie".length);- const gateway = p === "/v1" || p.startsWith("/v1/") || p.startsWith("/v1?");- return { gateway, path: p };-}--function outHeaders(req: http.IncomingMessage, t: ProxyTarget, gateway: boolean, targetHost: string): http.OutgoingHttpHeaders {- const h: http.OutgoingHttpHeaders = {};- for (const [k, v] of Object.entries(req.headers)) if (!HOP.has(k) && k !== "cookie" && k !== "authorization") h[k] = v;- h.host = targetHost;- // 不把我们自己的 cookie 转给 magpie,只注入 magpie 的- h.cookie = t.cookie();- if (gateway) h.authorization = `Bearer ${t.gatewayKey()}`;- // magpie 用 Origin/Referer 判断同源;改写成目标源- if (h.origin) h.origin = `http://${targetHost}`;- if (h.referer) h.referer = `http://${targetHost}/`;- return h;-}--/**- * 纵深防御:即使 magpie 界面里有入口,也拒绝会改写本机 agent 配置、发现/复用订阅凭据、- * 自更新或交接本机代理的接口(magpie 已以 --gateway 模式和隔离 HOME 运行,此处再兜一层)。- */-const BLOCKED = [/^\/api\/agents(\/|$|\?)/, /^\/api\/agent-models(\/|$|\?)/, /^\/api\/accounts(\/|$|\?)/, /^\/api\/update(\/|$|\?)/, /^\/api\/handover(\/|$|\?)/];-export function isBlockedPath(url: string): boolean {- let p = mapPath(url).path.split("?")[0]!;- try {- p = decodeURIComponent(p);- } catch {- return true;- }- p = path.posix.normalize(p.replace(/\\/g, "/").replace(/\/+/g, "/")).toLowerCase();- return BLOCKED.some((r) => r.test(p));-}--export function proxyHttp(req: http.IncomingMessage, res: http.ServerResponse, t: ProxyTarget): void {- if (isBlockedPath(req.url || "/")) {- res.writeHead(403, { "content-type": "application/json; charset=utf-8" });- res.end(JSON.stringify({ error: "anymodel bot 已禁用此 magpie 功能(agent 配置改写 / 订阅凭据复用 / 自更新)" }));- return;- }- if (!t.ready()) {- res.writeHead(503, { "content-type": "text/plain; charset=utf-8" });- res.end("magpie 尚未启动");- return;- }- const { gateway, path } = mapPath(req.url || "/");- const origin = new URL(gateway ? t.gatewayOrigin() : t.webOrigin());- const upstream = http.request(- { hostname: origin.hostname, port: origin.port, method: req.method, path, headers: outHeaders(req, t, gateway, origin.host) },- (up) => {- const headers = { ...up.headers };- // 防止 magpie 的 Set-Cookie 覆盖/泄露 key;我们在服务端统一注入- delete headers["set-cookie"];- // 重定向改写回 /magpie/ 子路径- if (headers.location && headers.location.startsWith("/") && !headers.location.startsWith("/magpie")) {- const loc = headers.location.replace(/([?&])k=[^&]*&?/, "$1").replace(/[?&]$/, "");- headers.location = loc === "/" || loc.startsWith("/?") ? "/magpie" + loc : loc;- }- res.writeHead(up.statusCode || 502, headers);- up.pipe(res);- },- );- upstream.on("error", (e) => {- if (!res.headersSent) res.writeHead(502, { "content-type": "text/plain; charset=utf-8" });- res.end(`magpie proxy error: ${e.message}`);- });- req.pipe(upstream);-}--export function proxyUpgrade(req: http.IncomingMessage, socket: Duplex, head: Buffer, t: ProxyTarget): void {- if (isBlockedPath(req.url || "/")) {- socket.end("HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n");- return;- }- if (!t.ready()) return void socket.destroy();- const { gateway, path } = mapPath(req.url || "/");- const origin = new URL(gateway ? t.gatewayOrigin() : t.webOrigin());- const up = net.connect(Number(origin.port), origin.hostname, () => {- const h = outHeaders(req, t, gateway, origin.host);- h.connection = "Upgrade";- h.upgrade = req.headers.upgrade || "websocket";- let raw = `${req.method} ${path} HTTP/1.1\r\n`;- for (const [k, v] of Object.entries(h)) if (v !== undefined) raw += `${k}: ${Array.isArray(v) ? v.join(", ") : v}\r\n`;- up.write(raw + "\r\n");- if (head?.length) up.write(head);- up.pipe(socket);- socket.pipe(up);- });- up.on("error", () => socket.destroy());- socket.on("error", () => up.destroy());-}diff --git a/src/web/server.ts b/src/web/server.tsindex 055a01f..8ae439a 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -3,11 +3,13 @@ import fs from "node:fs";import path from "node:path";import crypto from "node:crypto";import { createRequire } from "node:module";-import type { App } from "../app.js";+import { appVersion, type App } from "../app.js";import type { InboundEvent, OutboundOp, ReplySession } from "../core/types.js";import { findAppRoot } from "../magpie/supervisor.js";-import { proxyHttp, proxyUpgrade, type ProxyTarget } from "./proxy.js";import { logger, mask } from "../log.js";+import { ZOOMS, saveConfigFile } from "../config.js";+import { normalizeLine } from "../modelflare.js";+import { SseReply } from "./sse-reply.js";import { connectionFromPids } from "../agent/peer-guard.js";import type { ApprovalRow } from "../store/db.js";import { normalizeSettings } from "../agent/settings.js";@@ -31,6 +33,7 @@ const MIME: Record<string, string> = {".svg": "image/svg+xml",".png": "image/png",".json": "application/json",+ ".woff2": "font/woff2",};function vendorFiles(): Record<string, string> {@@ -102,6 +105,21 @@ class CollectReply implements ReplySession {}}+/** 网页控制台对话:每个机器人一个固定会话 <botId>:web:console */+function webEvent(botId: string, text: string): InboundEvent {+ return {+ id: crypto.randomUUID(),+ channel: "web",+ botId,+ conversation: { kind: "dm", id: "console" },+ sender: { id: "owner", name: "控制台" },+ parts: [{ type: "text", text }],+ replyHandle: {},+ receivedAt: Date.now(),+ };+}+const consoleConvId = (botId: string) => `${botId}:web:console`;+function publicApproval(r: ApprovalRow) {const { payload, result, ...rest } = r;let questions: unknown = undefined;@@ -133,14 +151,6 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strlog.warn(`UI 监听在非回环地址 ${host},访问需带令牌:见 ${f}(打开 /?token=<令牌> 一次即可)`);}- const target: ProxyTarget = {- webOrigin: () => app.magpie?.webOrigin ?? "http://127.0.0.1:9",- gatewayOrigin: () => (app.magpie ? `http://127.0.0.1:${app.magpie.gatewayPort}` : "http://127.0.0.1:9"),- cookie: () => (app.magpie ? `${app.magpie.cookieName}=${app.magpie.webKey}` : ""),- gatewayKey: () => app.magpie?.gatewayKey ?? "",- ready: () => !!app.magpie && app.magpie.state === "running",- };-let boundPort = 0;const allowedHosts = () => new Set([`127.0.0.1:${boundPort}`, `localhost:${boundPort}`, `[::1]:${boundPort}`]);@@ -183,11 +193,13 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strif (p === "/status" && m === "GET") {const mp = app.magpie;return send(res, 200, {- version: "0.1.0",+ version: appVersion(),dataDir: cfg.dataDir,- magpie: mp- ? { mode: "managed", state: mp.state, lastError: mp.lastError, restarts: mp.restarts, gatewayPort: mp.gatewayPort, webPort: mp.webPort, binary: mp.binPath ?? null, providers: mp.listProviders().length }- : { mode: "external", state: "external", baseUrl: cfg.magpie.externalBaseUrl },+ username: app.username,+ desktop: !!app.desktop,+ platform: process.platform,+ // 诊断信息:内置网关只是实现细节,界面里只在"关于 → 诊断信息"展示+ gateway: mp ? { mode: "managed", state: mp.state, lastError: mp.lastError, restarts: mp.restarts } : { mode: "external", state: "external" },notices: app.recentNotices,});}@@ -198,18 +210,79 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strreturn send(res, 200, { models: [], error: (e as Error).message });}}- if (p === "/providers") {- if (!app.magpie) throw new HttpError(400, "外部模型端点模式下不管理服务商");- if (m === "GET") return send(res, 200, { providers: app.magpie.listProviders() });- if (m === "POST") {+ if (p === "/modelflare" || p === "/modelflare/line") {+ if (m === "GET" && p === "/modelflare") return send(res, 200, app.modelflareStatus());+ if (m !== "GET" && !app.magpie) throw new HttpError(409, "外部模型端点模式下不管理 Modelflare 连接");+ }+ if (p === "/modelflare") {+ if (m === "PUT") {const b = await readJson(req);- if (!b.apiKey && !b.url) throw new HttpError(400, "缺少 apiKey");- const id = b.url- ? await app.magpie.addCustomProvider(String(b.name || "custom"), String(b.url), String(b.apiKey || ""), String(b.models || "").split(",").map((s: string) => s.trim()).filter(Boolean))- : await app.magpie.addPresetProvider(String(b.preset), String(b.apiKey));- return send(res, 200, { id });+ const apiKey = String(b.apiKey ?? "").trim();+ if (!apiKey) throw new HttpError(400, "缺少 API Key");+ const r = await app.connectModelflare(apiKey, normalizeLine(b.line ?? cfg.modelflare.line));+ if (!r.ok) return send(res, 400, { error: r.message, code: r.code, status: r.status, suggestLine: r.suggestLine });+ return send(res, 200, { ...app.modelflareStatus(), models: r.models });+ }+ if (m === "DELETE") {+ await app.disconnectModelflare();+ return send(res, 200, app.modelflareStatus());}}+ if (p === "/modelflare/line" && m === "PUT") {+ const b = await readJson(req);+ await app.setModelflareLine(normalizeLine(b.line));+ return send(res, 200, app.modelflareStatus());+ }+ if (p === "/settings") {+ if (m === "PUT") {+ const b = await readJson(req);+ if (b.defaultModel !== undefined) app.setDefaultModel(String(b.defaultModel));+ if (b.closeToTray !== undefined) {+ cfg.ui.closeToTray = !!b.closeToTray;+ saveConfigFile(cfg.dataDir, (f) => (f.ui = { ...(f.ui ?? {}), closeToTray: cfg.ui.closeToTray }));+ }+ if (b.zoom !== undefined) {+ const z = Number(b.zoom);+ if (!ZOOMS.includes(z)) throw new HttpError(400, "不支持的缩放比例");+ cfg.ui.zoom = z;+ saveConfigFile(cfg.dataDir, (f) => (f.ui = { ...(f.ui ?? {}), zoom: z }));+ app.desktop?.applyZoom(z);+ }+ if (b.autostart !== undefined) {+ if (!app.desktop?.autostart().supported) throw new HttpError(400, "当前环境不支持开机自启");+ app.desktop.setAutostart(!!b.autostart);+ }+ } else if (m !== "GET") throw new HttpError(405, "method not allowed");+ return send(res, 200, {+ defaultModel: cfg.llm.defaultModel,+ closeToTray: cfg.ui.closeToTray,+ zoom: cfg.ui.zoom,+ autostart: app.desktop ? app.desktop.autostart() : { supported: false, on: false },+ desktop: !!app.desktop,+ listen: { host, port: boundPort, tokenRequired: !!token },+ dataDir: cfg.dataDir,+ });+ }+ if (p === "/notices" && m === "GET") {+ const read = (f: string) => {+ try {+ return fs.readFileSync(path.join(findAppRoot(), f), "utf8");+ } catch {+ return "";+ }+ };+ return send(res, 200, { license: read("LICENSE"), notices: read("THIRD_PARTY_NOTICES.md") });+ }+ if (p === "/desktop/open-data-dir" && m === "POST") {+ if (!app.desktop) throw new HttpError(400, "仅桌面版可用");+ app.desktop.openDataDir();+ return send(res, 200, { ok: true });+ }+ if (p === "/desktop/open-in-browser" && m === "POST") {+ if (!app.desktop) throw new HttpError(400, "仅桌面版可用");+ app.desktop.openInBrowser();+ return send(res, 200, { ok: true });+ }if (p === "/agent" && m === "GET") return send(res, 200, app.agent.status());if (seg[0] === "approvals") {if (seg.length === 1 && m === "GET") {@@ -369,25 +442,57 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strawait app.weixinLogout(id);return send(res, 200, app.channelStatus(id));}+ if (sub === "chat" && m === "GET") {+ const conv = app.store.getConversation(consoleConvId(id));+ return send(res, 200, {+ conversationId: consoleConvId(id),+ model: conv?.model ?? "",+ messages: conv ? app.store.listMessages(conv.id, 200) : [],+ pending: app.store.listApprovals({ status: "pending", conversationId: consoleConvId(id), limit: 50 }).map(publicApproval),+ });+ }+ if (sub === "chat/model" && m === "PUT") {+ const b = await readJson(req);+ const conv = app.store.ensureConversation(id, "web", "console", "控制台");+ app.store.setConversationModel(conv.id, String(b.model ?? ""));+ return send(res, 200, { conversationId: conv.id, model: String(b.model ?? "") });+ }if (sub === "chat" && m === "POST") {const b = await readJson(req);const text = String(b.text ?? "").trim();if (!text) throw new HttpError(400, "内容为空");- const ev: InboundEvent = {- id: crypto.randomUUID(),- channel: "web",- botId: id,- conversation: { kind: "dm", id: "console" },- sender: { id: "owner", name: "控制台" },- parts: [{ type: "text", text }],- replyHandle: {},- receivedAt: Date.now(),- };+ const ev = webEvent(id, text);const intercepted = app.runtime.interceptReply(ev);if (intercepted.handled) return send(res, 200, { reply: intercepted.ack ?? "", prompts: [] });const out = new CollectReply();await app.queue.run(`web:${id}:console`, () => app.runtime.handle(ev, out));- return send(res, 200, { reply: out.text, prompts: out.prompts, files: out.files });+ return send(res, 200, { reply: out.text, prompts: out.prompts, files: out.files, conversationId: consoleConvId(id) });+ }+ if (sub === "chat/stream" && m === "POST") {+ const b = await readJson(req);+ const text = String(b.text ?? "").trim();+ if (!text) throw new HttpError(400, "内容为空");+ const ev = webEvent(id, text);+ const out = new SseReply(res);+ const ac = new AbortController();+ res.on("close", () => {+ if (!res.writableEnded) ac.abort();+ });+ try {+ const intercepted = app.runtime.interceptReply(ev);+ if (intercepted.handled) {+ if (intercepted.ack) out.send("text", { text: intercepted.ack, final: true, ack: true });+ return out.end("done", { conversationId: consoleConvId(id) });+ }+ await app.queue.run(`web:${id}:console`, async () => {+ if (!ac.signal.aborted) await app.runtime.handle(ev, out, { signal: ac.signal });+ });+ out.end("done", { conversationId: consoleConvId(id) });+ } catch (e) {+ log.warn("web chat failed", { message: (e as Error).message.slice(0, 300) });+ out.end("error", { message: (e as Error).message });+ }+ return;}}throw new HttpError(404, "not found");@@ -423,15 +528,10 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strreturn serveFile(res, f);}if (url.pathname === "/amb/healthz") return send(res, 200, { ok: true });- // 其余路径全部交给 magpie(/magpie/* 以及 magpie 前端用到的绝对路径)- proxyHttp(req, res, target);- });- server.on("upgrade", (req, socket, head) => {- const url = new URL(req.url || "/", "http://localhost");- const fake = { writeHead: () => ({ end: () => socket.destroy() }), end: () => socket.destroy() } as unknown as http.ServerResponse;- if (!authorized(req, url, fake)) return;- proxyUpgrade(req, socket, head, target);+ // 不再反代内置网关的界面或 /v1:网关只供本进程内部调用+ res.writeHead(404, { "content-type": "text/plain; charset=utf-8" }).end("not found");});+ server.on("upgrade", (_req, socket) => socket.end("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"));const port = opts.port ?? cfg.ui.port;const listen = (p: number) =>diff --git a/src/web/sse-reply.ts b/src/web/sse-reply.tsnew file mode 100644index 0000000..5caf41f--- /dev/null+++ b/src/web/sse-reply.ts@@ -0,0 +1,63 @@+import type http from "node:http";+import type { OutboundOp, ReplySession } from "../core/types.js";++/**+ * 网页对话渠道:把运行时的 OutboundOp 写成 text/event-stream。+ * 事件:text(到目前为止的完整回复,覆盖式)、typing、prompt(审批/提问)、file、done、error。+ * 运行时的 stream.update 本身就是累计文本,所以前端只需整体替换,不用拼接增量。+ */+export class SseReply implements ReplySession {+ private closed = false;+ text = "";++ constructor(private res: http.ServerResponse) {+ res.writeHead(200, {+ "content-type": "text/event-stream; charset=utf-8",+ "cache-control": "no-store",+ "x-accel-buffering": "no",+ connection: "keep-alive",+ });+ res.on("close", () => (this.closed = true));+ // 代理回合可能长时间没有输出:定期发注释行,避免中间层断开空闲连接+ const beat = setInterval(() => this.raw(": keep-alive\n\n"), 15_000);+ res.on("close", () => clearInterval(beat));+ }++ get isClosed(): boolean {+ return this.closed;+ }++ send(event: string, data: unknown): void {+ this.raw(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);+ }++ private raw(chunk: string): void {+ if (this.closed || this.res.writableEnded) return;+ this.res.write(chunk);+ }++ async apply(op: OutboundOp): Promise<void> {+ switch (op.type) {+ case "typing":+ return this.send("typing", { on: op.on });+ case "stream.start":+ return;+ case "stream.update":+ this.text = op.text;+ return this.send("text", { text: op.text });+ case "stream.finish":+ case "text":+ this.text = op.text;+ return this.send("text", { text: op.text, final: true });+ case "file":+ return this.send("file", { name: op.name });+ case "interactive":+ return this.send("prompt", { kind: op.kind, prompt: op.prompt, requestId: op.requestId, code: op.code });+ }+ }++ end(event: "done" | "error", data: unknown): void {+ this.send(event, data);+ if (!this.closed && !this.res.writableEnded) this.res.end();+ }+}diff --git a/test/e2e.test.ts b/test/e2e.test.tsindex 3e2bcac..e14627b 100644--- a/test/e2e.test.ts+++ b/test/e2e.test.ts@@ -150,9 +150,23 @@ describe("Web 界面 / API", () => {it("页面与前端依赖可加载", async () => {const html = await (await fetch(base + "/")).text();expect(html).toContain("importmap");- for (const p of ["/amb/vendor/preact.mjs", "/amb/vendor/hooks.mjs", "/amb/vendor/htm.mjs", "/amb/static/app.js", "/amb/static/style.css"]) {- expect((await fetch(base + p)).status, p).toBe(200);+ // index.html 里引用的每一个样式与脚本、以及脚本之间的相对 import 都能取到+ const refs = [...html.matchAll(/(?:href|src)="(\/amb\/[^"]+)"/g)].map((m) => m[1]);+ expect(refs).toContain("/amb/static/main.js");+ const seen = new Set<string>();+ const queue = [...refs, "/amb/vendor/preact.mjs", "/amb/vendor/hooks.mjs", "/amb/vendor/htm.mjs"];+ while (queue.length) {+ const p = queue.shift()!;+ if (seen.has(p)) continue;+ seen.add(p);+ const r = await fetch(base + p);+ expect(r.status, p).toBe(200);+ if (p.startsWith("/amb/static/") && p.endsWith(".js")) {+ const src = await r.text();+ for (const m of src.matchAll(/from "(\.{1,2}\/[^"]+)"/g)) queue.push(new URL(m[1], "http://x" + p).pathname);+ }}+ expect(seen.size).toBeGreaterThan(15);});it("机器人 CRUD + 飞书凭据(secret 不回显)+ 测试对话", async () => {const c = await api("/bots", { method: "POST", body: { name: "测试机器人", systemPrompt: "你是测试", defaultModel: "mock-b" } });@@ -172,14 +186,120 @@ describe("Web 界面 / API", () => {expect((await api(`/bots/${id}`, { method: "DELETE" })).status).toBe(200);expect((await api(`/bots/${id}`)).status).toBe(404);});- it("安全:错误 Host 拒绝、非 JSON 写请求拒绝、外部模式下 /magpie 503", async () => {+ it("安全:错误 Host 拒绝、非 JSON 写请求拒绝、不再反代内置网关(/magpie、/v1 均 404)", async () => {const http = await import("node:http");const port = new URL(base).port;const status = await new Promise<number>((r) => http.get({ host: "127.0.0.1", port, path: "/amb/api/status", headers: { host: "evil.example:80" } }, (res) => r(res.statusCode!)));expect(status).toBe(421);const form = await fetch(base + "/amb/api/bots", { method: "POST", headers: { "content-type": "text/plain" }, body: "{}" });expect(form.status).toBe(415);- expect((await fetch(base + "/magpie/")).status).toBe(503);+ for (const p of ["/magpie/", "/v1/models", "/api/providers"]) expect((await fetch(base + p)).status, p).toBe(404);+ expect((await api("/providers", { method: "POST", body: { preset: "deepseek", apiKey: "x" } })).status).toBe(404);+ });+ it("状态:版本号来自 package.json,不暴露网关端口与二进制路径", async () => {+ const st = await api("/status");+ expect(st.json.version).toBe(JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);+ expect(st.json.gateway).toEqual({ mode: "external", state: "external" });+ expect(JSON.stringify(st.json)).not.toMatch(/gatewayPort|webPort|binary/);+ });+ it("Modelflare:外部端点模式视为已连接,不能在界面里连接/断开", async () => {+ const mf = await api("/modelflare");+ expect(mf.json).toMatchObject({ mode: "external", connected: true });+ expect((await api("/modelflare", { method: "PUT", body: { apiKey: "k" } })).status).toBe(409);+ expect((await api("/modelflare", { method: "DELETE" })).status).toBe(409);+ });+ it("设置:改动即保存到 config.json;非法值拒绝;桌面专属项在浏览器模式下不可改", async () => {+ const s = await api("/settings");+ expect(s.json).toMatchObject({ closeToTray: true, zoom: 1, desktop: false, autostart: { supported: false } });+ const r = await api("/settings", { method: "PUT", body: { defaultModel: "mock-b", closeToTray: false, zoom: 1.25 } });+ expect(r.json).toMatchObject({ defaultModel: "mock-b", closeToTray: false, zoom: 1.25 });+ const file = JSON.parse(fs.readFileSync(path.join(dataDir, "config.json"), "utf8"));+ expect(file).toMatchObject({ llm: { defaultModel: "mock-b" }, ui: { closeToTray: false, zoom: 1.25 } });+ expect((await api("/settings", { method: "PUT", body: { zoom: 3 } })).status).toBe(400);+ expect((await api("/settings", { method: "PUT", body: { autostart: true } })).status).toBe(400);+ await api("/settings", { method: "PUT", body: { defaultModel: "", closeToTray: true, zoom: 1 } });+ });+ it("许可与第三方声明可在界面查看", async () => {+ const n = await api("/notices");+ expect(n.json.license).toContain("MIT");+ expect(n.json.notices).toContain("magpie");+ });+});++/** 读完一个 SSE 响应,返回 [事件, 数据] 列表 */+async function sse(p: string, body: unknown, signal?: AbortSignal, onEvent?: (ev: string, data: any) => void) {+ const res = await fetch(base + "/amb/api" + p, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal });+ expect(res.headers.get("content-type")).toContain("text/event-stream");+ const events: Array<[string, any]> = [];+ let buf = "";+ const dec = new TextDecoder();+ try {+ for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {+ buf += dec.decode(chunk, { stream: true });+ let i: number;+ while ((i = buf.indexOf("\n\n")) >= 0) {+ const block = buf.slice(0, i);+ buf = buf.slice(i + 2);+ const ev = /^event: (.*)$/m.exec(block)?.[1];+ const data = /^data: (.*)$/m.exec(block)?.[1];+ if (ev && data) {+ events.push([ev, JSON.parse(data)]);+ onEvent?.(ev, JSON.parse(data));+ }+ }+ }+ } catch (e) {+ if ((e as Error).name !== "AbortError") throw e;+ }+ return events;+}++describe("网页对话(流式)", () => {+ it("SSE:逐段 text(覆盖式累计)→ done;消息持久化;GET /chat 读回", async () => {+ const ev = await sse("/bots/default/chat/stream", { text: "流式你好" });+ const texts = ev.filter(([e]) => e === "text").map(([, d]) => d.text);+ expect(texts.length).toBeGreaterThan(2);+ for (let i = 1; i < texts.length; i++) expect(texts[i].startsWith(texts[i - 1].slice(0, -1))).toBe(true);+ expect(texts.at(-1)).toMatch(/你说:流式你好$/);+ expect(ev.at(-1)).toEqual(["done", { conversationId: "default:web:console" }]);+ const chat = await api("/bots/default/chat");+ expect(chat.json.conversationId).toBe("default:web:console");+ expect(chat.json.messages.slice(-2).map((m: any) => [m.role, m.content])).toEqual([+ ["user", "流式你好"],+ ["assistant", texts.at(-1)],+ ]);+ expect(chat.json.pending).toEqual([]);+ });+ it("会话级模型:PUT /chat/model 后下一条消息使用它,空字符串恢复默认", async () => {+ expect((await api("/bots/default/chat/model", { method: "PUT", body: { model: "mock-b" } })).json.model).toBe("mock-b");+ expect((await api("/bots/default/chat")).json.model).toBe("mock-b");+ await sse("/bots/default/chat/stream", { text: "用哪个" });+ expect(llm.calls.at(-1)!.model).toBe("mock-b");+ await api("/bots/default/chat/model", { method: "PUT", body: { model: "" } });+ await sse("/bots/default/chat/stream", { text: "又用哪个" });+ expect(llm.calls.at(-1)!.model).toBe("mock-a");+ });+ it("命令回复也走流:/status 一次性 text(final)", async () => {+ const ev = await sse("/bots/default/chat/stream", { text: "/status" });+ expect(ev.find(([e, d]) => e === "text" && d.final)?.[1].text).toContain("当前模型");+ });+ it("停止:客户端断开 → 上游请求被中止,已生成的部分保留为助手消息", async () => {+ const before = llm.calls.length;+ const ac = new AbortController();+ let got = 0;+ await sse("/bots/default/chat/stream", { text: "长".repeat(400) }, ac.signal, (e) => {+ if (e === "text" && ++got === 3) ac.abort();+ });+ expect(llm.calls.length).toBe(before + 1);+ await until(() => llm.aborted > 0, 3000, 20);+ const msgs = (await api("/bots/default/chat")).json.messages;+ const last = msgs.at(-1);+ expect(last.role).toBe("assistant");+ expect(last.content.length).toBeGreaterThan(0);+ expect(last.content.length).toBeLessThan(400);+ // 中止后同一会话还能继续对话(队列没被卡住)+ const ev = await sse("/bots/default/chat/stream", { text: "还在吗" });+ expect(ev.at(-1)![0]).toBe("done");});it("日志与数据库外文件中不含明文密钥", () => {const files = fs.readdirSync(dataDir, { recursive: true }).map(String).filter((f) => !f.endsWith(".db") && !f.includes(".db-") && !f.endsWith(".png"));diff --git a/test/helpers.ts b/test/helpers.tsindex 6a3628a..3be5f24 100644--- a/test/helpers.ts+++ b/test/helpers.ts@@ -25,6 +25,7 @@ async function body(req: http.IncomingMessage): Promise<any> {export async function mockOpenAI(opts: { models?: string[]; key?: string; reply?: (msgs: any[], model: string) => string } = {}) {const models = opts.models ?? ["mock-a", "mock-b"];const calls: Array<{ model: string; messages: any[]; auth?: string }> = [];+ const stats = { aborted: 0 };const srv = await listen(async (req, res) => {if (opts.key && req.headers.authorization !== `Bearer ${opts.key}`) {res.writeHead(401, { "content-type": "application/json" }).end(JSON.stringify({ error: { message: "bad key" } }));@@ -45,7 +46,12 @@ export async function mockOpenAI(opts: { models?: string[]; key?: string; reply?}res.writeHead(200, { "content-type": "text/event-stream" });const pieces = text.match(/.{1,4}/gsu) ?? [];+ let gone = false;+ res.on("close", () => {+ if (!res.writableEnded) (gone = true), stats.aborted++;+ });for (const p of pieces) {+ if (gone) return;res.write(`data: ${JSON.stringify({ choices: [{ delta: { content: p } }] })}\n\n`);await new Promise((r) => setTimeout(r, 2));}@@ -55,7 +61,15 @@ export async function mockOpenAI(opts: { models?: string[]; key?: string; reply?}res.writeHead(404).end();});- return { ...srv, calls, models };+ return {+ ...srv,+ calls,+ models,+ /** 流式回复中途被客户端断开的次数 */+ get aborted() {+ return stats.aborted;+ },+ };}/** 模拟 iLink:登录(wait→scaned→confirmed)、getupdates(队列)、sendmessage、getconfig、sendtyping、-14 */diff --git a/test/magpie.integration.test.ts b/test/magpie.integration.test.tsindex 755862f..df34efa 100644--- a/test/magpie.integration.test.ts+++ b/test/magpie.integration.test.ts@@ -1,5 +1,5 @@/**- * 集成测试:真实内置 magpie(受管模式)+ mock 上游模型。需要先 npm run build:magpie;没有二进制时跳过。+ * 集成测试:真实内置 magpie(受管模式)+ mock Modelflare 上游。需要先 npm run build:magpie;没有二进制时跳过。*/import { describe, it, expect, beforeAll, afterAll } from "vitest";import fs from "node:fs";@@ -20,7 +20,9 @@ d("内置 magpie 集成", () => {let dataDir: string;beforeAll(async () => {- llm = await mockOpenAI({ key: "upstream-key", models: ["up-model"] });+ llm = await mockOpenAI({ key: "mf-upstream-key-a1b2", models: ["up-model"] });+ // 仅测试:把 Modelflare 基址指向本地 mock(界面无法设置这个变量)+ process.env.AMB_MODELFLARE_BASE_URL = llm.url + "/v1";dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-int-"));app = new App(loadConfig({ dataDir, env: { AMB_UI_PORT: "0", AMB_WEIXIN_API_BASE: "http://127.0.0.1:9", AMB_AGENT: "off" } }), {feishuTransport: () => new FakeFeishu(),@@ -31,71 +33,80 @@ d("内置 magpie 集成", () => {}, 60_000);afterAll(async () => {+ delete process.env.AMB_MODELFLARE_BASE_URL;await app?.stop();await llm?.close();});- it("magpie 已在隔离目录中以 gateway 模式运行", async () => {+ const api = async (p: string, method = "GET", body?: unknown) => {+ const r = await fetch(base + "/amb/api" + p, { method, headers: body !== undefined ? { "content-type": "application/json" } : {}, body: body !== undefined ? JSON.stringify(body) : undefined });+ return { status: r.status, text: await r.clone().text(), json: (await r.json().catch(() => ({}))) as any };+ };++ it("magpie 已在隔离目录中以 gateway 模式运行,初始未连接 Modelflare", async () => {expect(app.magpie!.state).toBe("running");- expect(fs.existsSync(path.join(dataDir, "magpie", "config", "magpie", "settings.json"))).toBe(true);const s = JSON.parse(fs.readFileSync(path.join(dataDir, "magpie", "config", "magpie", "settings.json"), "utf8"));expect(s.noAutoUpdate).toBe(true);expect(s.noAccountDiscovery).toBe(true);// 没有从真实 HOME 发现任何订阅账号expect(app.magpie!.listProviders()).toEqual([]);+ const st = await api("/modelflare");+ expect(st.json).toMatchObject({ mode: "managed", connected: false, keyTail: "" });});- it("通过界面 API 添加自定义服务商 → 模型可用 → 对话经 magpie 转发", async () => {- const r = await fetch(base + "/amb/api/providers", {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify({ name: "mockup", url: llm.url + "/v1", apiKey: "upstream-key", models: "up-model" }),- });+ it("无效 Key:返回 401 文案,不创建任何连接", async () => {+ expect((await api("/modelflare", "PUT", {})).status).toBe(400);+ const r = await api("/modelflare", "PUT", { apiKey: "wrong-key" });+ expect(r.status).toBe(400);+ expect(r.json).toMatchObject({ code: "invalid_key", status: 401 });+ expect(app.magpie!.listProviders()).toEqual([]);+ });++ it("连接 Modelflare → 模型可用 → 对话经网关转发;Key 不出现在参数、日志与接口里", async () => {+ const r = await api("/modelflare", "PUT", { apiKey: "mf-upstream-key-a1b2" });expect(r.status).toBe(200);- // 真实 key 没有出现在 magpie 进程参数/日志里,只在 magpie 的配置文件中- expect(app.magpie!.recentLog.join("\n")).not.toContain("upstream-key");+ expect(r.json).toMatchObject({ connected: true, keyTail: "a1b2", models: ["up-model"] });+ expect(r.text).not.toContain("mf-upstream-key");+ expect((await api("/modelflare")).text).not.toContain("mf-upstream-key");+ expect(app.magpie!.recentLog.join("\n")).not.toContain("mf-upstream-key");+ const raw = JSON.parse(fs.readFileSync(path.join(dataDir, "magpie", "config", "magpie", "providers.json"), "utf8"));+ const arr: any[] = Array.isArray(raw) ? raw : raw.providers;+ expect(arr.map((p) => p.id)).toEqual(["modelflare"]);+ expect(arr[0].key).toBe("mf-upstream-key-a1b2");let models: string[] = [];await until(async () => {- models = (await (await fetch(base + "/amb/api/models")).json()).models;+ models = (await api("/models")).json.models;return models.length > 0;}, 15_000, 300);expect(models.some((m) => m.includes("up-model"))).toBe(true);- const chat = await fetch(base + "/amb/api/bots/default/chat", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ text: "经过网关" }) });- const j = (await chat.json()) as { reply: string };- expect(j.reply).toContain("你说:经过网关");- expect(llm.calls.at(-1)!.auth).toBe("Bearer upstream-key");+ const chat = await api("/bots/default/chat", "POST", { text: "经过网关" });+ expect(chat.json.reply).toContain("你说:经过网关");+ expect(llm.calls.at(-1)!.auth).toBe("Bearer mf-upstream-key-a1b2");}, 30_000);- it("预设服务商:key 不经命令行参数保存", async () => {- const id = await app.magpie!.addPresetProvider("deepseek", "sk-fake-not-real-0000");- expect(id).toMatch(/deepseek/);- const raw = JSON.parse(fs.readFileSync(path.join(dataDir, "magpie", "config", "magpie", "providers.json"), "utf8"));- expect(raw.providers.find((p: any) => p.id === id).key).toBe("sk-fake-not-real-0000");- const listed = await (await fetch(base + "/amb/api/providers")).text();- expect(listed).not.toContain("sk-fake");- }, 30_000);+ it("切换线路写入 config.json,Key 保持不变", async () => {+ const r = await api("/modelflare/line", "PUT", { line: "cn" });+ expect(r.json).toMatchObject({ connected: true, line: "cn", keyTail: "a1b2" });+ expect(JSON.parse(fs.readFileSync(path.join(dataDir, "config.json"), "utf8")).modelflare.line).toBe("cn");+ });- it("/magpie/ 内嵌:免二次登录、绝对路径兜底、/v1 走 gateway、敏感接口被拦截", async () => {- const idx = await fetch(base + "/magpie/");- expect(idx.status).toBe(200);- const html = await idx.text();- expect(html).toContain("<title>magpie</title>");- expect(idx.headers.get("set-cookie")).toBeNull();- const icon = await fetch(base + "/icons/favicon.svg");- expect(icon.status).toBe(200);- const trace = await fetch(base + "/api/gateway/trace?after=0");- expect(trace.status).toBe(200);- const v1 = await fetch(base + "/v1/models");- expect(v1.status).toBe(200);- expect(((await v1.json()) as any).data.length).toBeGreaterThan(0);- expect((await fetch(base + "/api/agents/connect/claude", { method: "POST" })).status).toBe(403);- expect((await fetch(base + "/magpie/api/accounts/authorize")).status).toBe(403);+ it("不再反代内置网关:/magpie/、/v1、magpie 绝对路径都是 404", async () => {+ for (const p of ["/magpie/", "/v1/models", "/api/providers", "/icons/favicon.svg"]) expect((await fetch(base + p)).status, p).toBe(404);});it("崩溃后自动重启", async () => {const before = app.magpie!.restarts;app.magpie!.killForTest();await until(() => app.magpie!.restarts > before && app.magpie!.state === "running", 20_000, 100);- expect((await fetch(base + "/magpie/")).status).toBe(200);+ expect(await app.magpie!.healthy()).toBe(true);+ }, 30_000);++ it("断开 Modelflare:回到未连接,机器人与会话保留", async () => {+ const r = await api("/modelflare", "DELETE");+ expect(r.status).toBe(200);+ expect(r.json.connected).toBe(false);+ expect(app.magpie!.listProviders()).toEqual([]);+ expect((await api("/bots")).json.bots.length).toBeGreaterThan(0);+ expect((await api("/conversations?bot=default")).json.conversations.length).toBeGreaterThan(0);}, 30_000);});diff --git a/test/markdown.unit.test.ts b/test/markdown.unit.test.tsnew file mode 100644index 0000000..e2a0a08--- /dev/null+++ b/test/markdown.unit.test.ts@@ -0,0 +1,98 @@+/**+ * 前端 Markdown 子集:解析为纯数据 AST(渲染层用 h(),文本永远是文本节点)。+ * 这里锁住结构,并确认任何输入都不会把可执行的东西带进属性。+ */+import { describe, it, expect } from "vitest";+// @ts-expect-error 前端模块是无类型的原生 ES 模块+import { parseMarkdown, parseInline, safeHref, linkify } from "../ui/lib/markdown.js";++/** 收集 AST 里所有链接地址 */+function hrefs(node: unknown): string[] {+ if (Array.isArray(node)) return node.flatMap(hrefs);+ if (node && typeof node === "object") {+ const n = node as Record<string, unknown>;+ return [...(n.t === "a" ? [String(n.href)] : []), ...Object.values(n).flatMap(hrefs)];+ }+ return [];+}++describe("Markdown 解析", () => {+ it("段落、软换行、标题、分隔线", () => {+ expect(parseMarkdown("你好\n世界\n\n# 标题\n---")).toEqual([+ { t: "p", c: ["你好", { t: "br" }, "世界"] },+ { t: "h", level: 1, c: ["标题"] },+ { t: "hr" },+ ]);+ });+ it("代码块:语言、内容原样;流式中未闭合也算代码块", () => {+ expect(parseMarkdown("```js\nconst a = '<b>';\n```")).toEqual([{ t: "code", lang: "js", text: "const a = '<b>';", open: false }]);+ expect(parseMarkdown("看:\n```py\nprint(1)")).toEqual([+ { t: "p", c: ["看:"] },+ { t: "code", lang: "py", text: "print(1)", open: true },+ ]);+ });+ it("列表(有序起始号、嵌套)与引用", () => {+ const [ol, ul, q] = parseMarkdown("3. 甲\n4. 乙\n\n- 一\n - 一点一\n- 二\n\n> 引用\n> 第二行");+ expect(ol).toMatchObject({ t: "ol", start: 3, items: [{ c: ["甲"] }, { c: ["乙"] }] });+ expect(ul).toMatchObject({ t: "ul", items: [{ c: ["一"], sub: [{ t: "ul", items: [{ c: ["一点一"] }] }] }, { c: ["二"] }] });+ expect(q).toEqual({ t: "quote", c: [{ t: "p", c: ["引用", { t: "br" }, "第二行"] }] });+ });+ it("GFM 表格:表头、对齐、转义的竖线", () => {+ const [t] = parseMarkdown("| 名称 | 数量 |\n|:--|--:|\n| a\\|b | 2 |");+ expect(t).toEqual({ t: "table", head: [["名称"], ["数量"]], align: ["left", "right"], rows: [[["a|b"], ["2"]]] });+ });+ it("行内:代码、粗体、斜体、删除线、snake_case 不变斜体、转义", () => {+ expect(parseInline("用 `a*b*c` 和 **粗** *斜* ~~删~~ my_var_name \\*星\\*")).toEqual([+ "用 ",+ { t: "code", text: "a*b*c" },+ " 和 ",+ { t: "b", c: ["粗"] },+ " ",+ { t: "i", c: ["斜"] },+ " ",+ { t: "s", c: ["删"] },+ " my_var_name *星*",+ ]);+ });+ it("链接:Markdown 链接、尖括号、裸链接(去掉句末标点)", () => {+ expect(parseInline("见 [文档](https://docs.modelflare.dev/a_(b)) 或 <https://x.dev> 或 https://modelflare.dev/v1。")).toEqual([+ "见 ",+ { t: "a", href: "https://docs.modelflare.dev/a_(b)", c: ["文档"] },+ " 或 ",+ { t: "a", href: "https://x.dev", c: ["https://x.dev"] },+ " 或 ",+ { t: "a", href: "https://modelflare.dev/v1", c: ["https://modelflare.dev/v1"] },+ "。",+ ]);+ });+});++describe("Markdown 安全", () => {+ it("只放行 http(s) 与 mailto", () => {+ expect(safeHref("https://a.b")).toBe("https://a.b");+ expect(safeHref("mailto:[email protected]")).toBe("mailto:[email protected]");+ for (const bad of ["javascript:alert(1)", "JaVaScRiPt:alert(1)", " javascript:alert(1)", "data:text/html,<script>", "vbscript:x", "/relative", "//evil.example", "https://a.b/\u0000x", "java\nscript:x"]) {+ expect(safeHref(bad), bad).toBeNull();+ }+ });+ it("HTML 与脚本只会是文本;危险链接退化为文字", () => {+ const ast = parseMarkdown(+ [+ "<script>alert(1)</script>",+ "<img src=x onerror=alert(1)>",+ "[点我](javascript:alert(1)) [又一个]( JAVASCRIPT:alert(1) ) [数据](data:text/html;base64,PHNjcmlwdD4=)",+ "<javascript:alert(1)>",+ "| a |\n|---|\n| [x](javascript:void(0)) |",+ "- [y](vbscript:msgbox)",+ ].join("\n\n"),+ );+ expect(hrefs(ast)).toEqual([]);+ const text = JSON.stringify(ast);+ expect(text).toContain("<script>alert(1)</script>");+ expect(text).toContain("点我");+ expect(ast.every((b: any) => ["p", "table", "ul"].includes(b.t))).toBe(true);+ });+ it("用户消息只做链接识别", () => {+ expect(linkify("**不是粗体** https://modelflare.dev,<b>")).toEqual(["**不是粗体** ", { t: "a", href: "https://modelflare.dev", c: ["https://modelflare.dev"] }, ",<b>"]);+ });+});diff --git a/test/unit.test.ts b/test/unit.test.tsindex 7d355a5..7c92925 100644--- a/test/unit.test.ts+++ b/test/unit.test.ts@@ -14,8 +14,9 @@ import { FeishuReply } from "../src/channels/feishu/card.js";import { feishuParts } from "../src/channels/feishu/channel.js";import { redactValue, mask } from "../src/log.js";import { loadConfig } from "../src/config.js";-import { isBlockedPath } from "../src/web/proxy.js";-import { FakeFeishu, feishuEvent, mockOpenAI } from "./helpers.js";+import { verifyModelflareKey, modelflareBaseUrl, normalizeLine, keyTail, MODELFLARE_LINES } from "../src/modelflare.js";+import { saveConfigFile } from "../src/config.js";+import { FakeFeishu, feishuEvent, listen, mockOpenAI } from "./helpers.js";const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "amb-unit-"));@@ -217,10 +218,6 @@ describe("安全", () => {expect(out).toContain('"name":"ok"');expect(mask("1234567890")).toBe("****7890");});- it("代理拒绝 agent 改写 / 账号复用 / 自更新接口(含编码绕过)", () => {- for (const p of ["/api/agents/connect/claude", "/magpie/api/agents/", "/api/accounts/authorize", "/api/%61gents/connect/codex", "//api//agents/x", "/api/agent-models/codex", "/api/update", "/API/Agents"]) expect(isBlockedPath(p), p).toBe(true);- for (const p of ["/api/gateway/trace", "/magpie/", "/v1/models", "/api/state", "/icons/x.svg"]) expect(isBlockedPath(p), p).toBe(false);- });it("配置:环境变量优先,AMB_UI_PORT=0 合法", () => {const dir = tmp();fs.writeFileSync(path.join(dir, "config.json"), JSON.stringify({ ui: { port: 4000 }, llm: { defaultModel: "f" } }));@@ -230,3 +227,65 @@ describe("安全", () => {expect(c.magpie.mode).toBe("external");});});++describe("Modelflare", () => {+ it("线路:白名单两条,auto=国际;测试覆盖变量优先", () => {+ expect(modelflareBaseUrl("auto", {})).toBe("https://modelflare.dev/v1");+ expect(modelflareBaseUrl("global", {})).toBe(MODELFLARE_LINES.global);+ expect(modelflareBaseUrl("cn", {})).toBe("https://origin.modelflare.dev/v1");+ expect(modelflareBaseUrl("cn", { AMB_MODELFLARE_BASE_URL: "http://127.0.0.1:9/v1/" })).toBe("http://127.0.0.1:9/v1");+ expect(normalizeLine("cn")).toBe("cn");+ expect(normalizeLine("https://evil.example")).toBe("auto");+ expect(keyTail("mf-abcdef1234")).toBe("1234");+ expect(keyTail("abc")).toBe("");+ });+ it("校验密钥:200 列出模型;401/403/429/5xx/坏响应/连不上分别给出可操作的结果", async () => {+ let status = 200;+ let body = JSON.stringify({ data: [{ id: "b" }, { id: "a" }] });+ const auth: string[] = [];+ const srv = await listen((req, res) => {+ auth.push(String(req.headers.authorization));+ res.writeHead(status, { "content-type": "application/json", ...(status === 429 ? { "retry-after": "7" } : {}) }).end(body);+ });+ try {+ const base = srv.url + "/v1";+ expect(await verifyModelflareKey(base, "k1")).toEqual({ ok: true, models: ["a", "b"] });+ expect(auth.at(-1)).toBe("Bearer k1");+ body = JSON.stringify({ data: [] });+ expect(await verifyModelflareKey(base, "k1")).toEqual({ ok: true, models: [] });+ status = 401;+ expect(await verifyModelflareKey(base, "k")).toMatchObject({ ok: false, code: "invalid_key", status: 401 });+ status = 403;+ expect(await verifyModelflareKey(base, "k")).toMatchObject({ ok: false, code: "forbidden" });+ status = 429;+ expect(await verifyModelflareKey(base, "k")).toMatchObject({ ok: false, code: "rate_limited", message: expect.stringContaining("7 秒") });+ status = 502;+ expect(await verifyModelflareKey(base, "k")).toMatchObject({ ok: false, code: "upstream", status: 502 });+ status = 200;+ body = "<html>";+ expect(await verifyModelflareKey(base, "k")).toMatchObject({ ok: false, code: "bad_response" });+ } finally {+ await srv.close();+ }+ const down = await verifyModelflareKey("http://127.0.0.1:9/v1", "k", { line: "auto" });+ expect(down).toMatchObject({ ok: false, code: "network", suggestLine: "cn" });+ expect(await verifyModelflareKey("http://127.0.0.1:9/v1", "k", { line: "cn" })).not.toHaveProperty("suggestLine");+ });+ it("配置写回:只改给出的键,其余保留;读取时规范化", () => {+ const dir = tmp();+ fs.writeFileSync(path.join(dir, "config.json"), JSON.stringify({ ui: { port: 4000 }, llm: { defaultModel: "f" } }));+ saveConfigFile(dir, (f) => (f.modelflare = { line: "cn" }));+ saveConfigFile(dir, (f) => (f.ui = { ...f.ui, zoom: 1.25, closeToTray: false }));+ const c = loadConfig({ dataDir: dir, env: {} });+ expect(c.ui.port).toBe(4000);+ expect(c.llm.defaultModel).toBe("f");+ expect(c.modelflare.line).toBe("cn");+ expect(c.ui.zoom).toBe(1.25);+ expect(c.ui.closeToTray).toBe(false);+ fs.writeFileSync(path.join(dir, "config.json"), JSON.stringify({ ui: { zoom: 3 }, modelflare: { line: "x" } }));+ const d = loadConfig({ dataDir: dir, env: {} });+ expect(d.ui.zoom).toBe(1);+ expect(d.ui.closeToTray).toBe(true);+ expect(d.modelflare.line).toBe("auto");+ });+});diff --git a/ui/app.js b/ui/app.jsdeleted file mode 100644index ca01bf1..0000000--- a/ui/app.js+++ /dev/null@@ -1,673 +0,0 @@-// anymodel bot 管理界面:Preact + htm(无构建步骤,原生 ES 模块)-// 壳:左栏机器人/会话 · 中间对话 · 右栏上下文(渠道/设置/记忆/审批)-import { h, render } from "preact";-import { useEffect, useState, useCallback, useRef, useMemo } from "preact/hooks";-import htm from "htm";-const html = htm.bind(h);--async function api(path, opts = {}) {- const res = await fetch("/amb/api" + path, {- method: opts.method || "GET",- headers: opts.body !== undefined ? { "content-type": "application/json" } : {},- body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,- });- const data = await res.json().catch(() => ({}));- if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);- return data;-}--const STATE_TEXT = {- disabled: "未启用", connecting: "连接中", connected: "已连接", error: "错误", expired: "已过期", paused: "已暂停",- login_required: "未登录", running: "运行中", starting: "启动中", restarting: "重启中", failed: "失败", stopped: "已停止",- wait: "等待扫码", scaned: "已扫码", need_verifycode: "需验证码", confirmed: "已确认", already_bound: "已绑定", cancelled: "已取消", idle: "空闲", fetching: "获取中",-};-const Badge = ({ s }) => html`<span class="badge ${s}">${STATE_TEXT[s] || s}</span>`;-const fmt = (t) => (t ? new Date(t).toLocaleString("zh-CN", { hour12: false }) : "");-/** Stable soft hue (0–359) from bot id/name — pastel face fill. */-function botHue(id, name) {- const s = String(id || name || "?");- let h = 2166136261;- for (let i = 0; i < s.length; i++) {- h ^= s.charCodeAt(i);- h = Math.imul(h, 16777619);- }- return Math.abs(h) % 360;-}--/**- * One shared pointermove on a container; writes --look-x/--look-y on each .bot-face- * inside it (no per-avatar listeners, no React re-renders for look-at).- */-function usePointerLook(containerRef) {- useEffect(() => {- const root = containerRef.current;- if (!root) return;- let raf = 0;- let px = -1e5, py = -1e5;- const apply = () => {- raf = 0;- const faces = root.querySelectorAll(".bot-face");- for (const el of faces) {- const r = el.getBoundingClientRect();- if (!r.width || !r.height) continue;- const cx = r.left + r.width / 2;- const cy = r.top + r.height / 2;- const dx = px - cx;- const dy = py - cy;- const dist = Math.hypot(dx, dy);- const reach = Math.max(96, r.width * 3.2);- let lx = 0, ly = 0;- if (dist < reach * 1.35) {- const fall = Math.max(0, 1 - dist / reach);- lx = Math.max(-1, Math.min(1, (dx / (r.width * 0.55)) * fall));- ly = Math.max(-1, Math.min(1, (dy / (r.height * 0.55)) * fall));- }- el.style.setProperty("--look-x", lx.toFixed(3));- el.style.setProperty("--look-y", ly.toFixed(3));- }- };- const onMove = (e) => {- px = e.clientX; py = e.clientY;- if (!raf) raf = requestAnimationFrame(apply);- };- const onLeave = () => {- px = -1e5; py = -1e5;- if (!raf) raf = requestAnimationFrame(apply);- };- root.addEventListener("pointermove", onMove, { passive: true });- root.addEventListener("pointerleave", onLeave);- return () => {- root.removeEventListener("pointermove", onMove);- root.removeEventListener("pointerleave", onLeave);- if (raf) cancelAnimationFrame(raf);- };- }, []);-}--/** Friendly SVG face — look via CSS vars; working via .is-working. */-function BotAvatar({ name, id, size = 36, working = false }) {- const hue = botHue(id, name);- const eyeR = size * 0.11;- const pupilR = size * 0.055;- const eyeY = size * 0.42;- const eyeDX = size * 0.16;- const mouthY = size * 0.68;- const vb = size;- return html`<div- class=${`bot-face${working ? " is-working" : ""}`}- style=${{ width: size + "px", height: size + "px", "--bot-hue": String(hue) }}- aria-hidden="true"- >- <div class="bot-face-3d">- <svg width=${size} height=${size} viewBox=${`0 0 ${vb} ${vb}`} xmlns="http://www.w3.org/2000/svg">- <circle class="bot-head" cx=${vb / 2} cy=${vb / 2} r=${vb / 2 - 0.5} />- <ellipse class="bot-eye-white" cx=${vb / 2 - eyeDX} cy=${eyeY} rx=${eyeR * 1.15} ry=${eyeR} />- <ellipse class="bot-eye-white" cx=${vb / 2 + eyeDX} cy=${eyeY} rx=${eyeR * 1.15} ry=${eyeR} />- <g class="bot-pupils">- <circle class="bot-pupil" cx=${vb / 2 - eyeDX} cy=${eyeY} r=${pupilR} />- <circle class="bot-pupil" cx=${vb / 2 + eyeDX} cy=${eyeY} r=${pupilR} />- </g>- <path class="bot-mouth bot-mouth-idle" d=${`M ${vb / 2 - size * 0.12} ${mouthY} Q ${vb / 2} ${mouthY + size * 0.08} ${vb / 2 + size * 0.12} ${mouthY}`} fill="none" stroke-linecap="round" />- <ellipse class="bot-mouth bot-mouth-work" cx=${vb / 2} cy=${mouthY + size * 0.02} rx=${size * 0.07} ry=${size * 0.045} />- </svg>- </div>- </div>`;-}---function usePoll(fn, ms, deps = []) {- const [data, setData] = useState(null);- const [err, setErr] = useState("");- const load = useCallback(() => fn().then((d) => { setData(d); setErr(""); }).catch((e) => setErr(e.message)), deps);- useEffect(() => { load(); if (!ms) return; const t = setInterval(load, ms); return () => clearInterval(t); }, [load]);- return [data, err, load];-}--function useTheme() {- const read = () => localStorage.getItem("amb-theme") || "system";- const [mode, setMode] = useState(read);- const apply = (m) => {- const root = document.documentElement;- if (m === "system") root.removeAttribute("data-theme");- else root.setAttribute("data-theme", m);- };- useEffect(() => { apply(mode); localStorage.setItem("amb-theme", mode); }, [mode]);- useEffect(() => {- const mq = window.matchMedia("(prefers-color-scheme: dark)");- const onChange = () => { if (mode === "system") apply("system"); };- mq.addEventListener?.("change", onChange);- return () => mq.removeEventListener?.("change", onChange);- }, [mode]);- const resolved = useMemo(() => {- if (mode === "light" || mode === "dark") return mode;- return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";- }, [mode]);- return [mode, setMode, resolved];-}--const Mark = () => html`<div class="brand-mark" aria-hidden="true">- <svg width="18" height="18" viewBox="0 0 18 18" fill="none">- <path d="M4 12.5V5.5L9 10l5-4.5v7" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>- </svg>-</div>`;--// ---------------- 概览(管理视图) -----------------const PRESETS = ["deepseek", "openai", "anthropic", "google", "moonshot-cn", "qwen-cn", "zhipu", "volcengine", "xai", "minimax-cn", "groq", "mistral"];-function Overview({ goChat }) {- const [st] = usePoll(() => api("/status"), 3000);- const [models, , reloadModels] = usePoll(() => api("/models"), 0);- const [preset, setPreset] = useState("deepseek");- const [key, setKey] = useState("");- const [msg, setMsg] = useState("");- if (!st) return html`<p class="muted">加载中…</p>`;- const mp = st.magpie;- const add = async () => {- setMsg("添加中…");- try { const r = await api("/providers", { method: "POST", body: { preset, apiKey: key } }); setKey(""); setMsg(`✓ 已添加 ${r.id}`); setTimeout(reloadModels, 800); }- catch (e) { setMsg("✗ " + e.message); }- };- return html`- <div class="page-head"><h2>概览</h2><p class="sub">网关状态与快速添加服务商</p></div>- ${st.notices.slice(0, 3).map((n) => html`<div class="notice">${fmt(n.at)} ${n.text}</div>`)}- <div class="kpi-strip">- <div class="kpi"><div class="lbl">网关</div><div class="val">${mp.state}<span class="unit">${mp.mode || ""}</span></div></div>- <div class="kpi"><div class="lbl">服务商</div><div class="val">${mp.providers ?? "—"}</div></div>- <div class="kpi"><div class="lbl">重启</div><div class="val">${mp.restarts ?? 0}</div></div>- <div class="kpi"><div class="lbl">版本</div><div class="val" style="font-size:14px">${st.version || "—"}</div></div>- </div>- <div class="card">- <h3>模型网关(内置 magpie)</h3>- <div class="row"><span>状态</span><${Badge} s=${mp.state} />- ${mp.mode === "managed" && html`<span class="muted">gateway 127.0.0.1:${mp.gatewayPort} · 重启 ${mp.restarts} 次 · 服务商 ${mp.providers} 个</span>`}- </div>- ${mp.lastError && html`<p class="muted">最近错误:${mp.lastError}</p>`}- <p class="muted">可用模型:${models ? (models.models.length ? models.models.join("、") : models.error || "暂无,请添加服务商") : "…"}</p>- </div>- ${mp.mode === "managed" && html`<div class="card">- <h3>快速添加模型服务商</h3>- <div class="row">- <select style="width:180px" value=${preset} onChange=${(e) => setPreset(e.target.value)}>${PRESETS.map((p) => html`<option>${p}</option>`)}</select>- <input class="grow" style="width:auto" type="password" placeholder="API Key(仅保存在本机的 magpie 隔离配置中)" value=${key} onInput=${(e) => setKey(e.target.value)} />- <button class="pri" disabled=${!key} onClick=${add}>添加</button>- </div>- <p class="muted">${msg} 更多配置请打开「模型」面板(magpie)。</p>- </div>`}- <div class="card muted">数据目录:<code>${st.dataDir}</code> · 版本 ${st.version}- <div style="margin-top:8px"><button onClick=${goChat}>返回对话</button></div>- </div>`;-}--// ---------------- 机器人编辑(右栏 / 管理) -----------------function BotEditor({ bot, models, onSaved, onDeleted }) {- const [f, setF] = useState(bot);- const [msg, setMsg] = useState("");- useEffect(() => setF(bot), [bot.id]);- const set = (k) => (e) => setF({ ...f, [k]: e.target.value });- const save = async () => {- try { const r = await api(`/bots/${bot.id}`, { method: "PUT", body: { name: f.name, systemPrompt: f.systemPrompt, defaultModel: f.defaultModel } }); setMsg("✓ 已保存"); onSaved(r.bot); }- catch (e) { setMsg("✗ " + e.message); }- };- const del = async () => { if (confirm(`删除机器人「${bot.name}」及其全部会话?`)) { await api(`/bots/${bot.id}`, { method: "DELETE" }); onDeleted(); } };- return html`<div class="card">- <h3>身份</h3>- <label>名称</label><input value=${f.name} onInput=${set("name")} />- <label>人设 / 系统提示词</label><textarea value=${f.systemPrompt} onInput=${set("systemPrompt")} />- <label>默认模型(会话内可用 /model 覆盖)</label>- <select value=${f.defaultModel} onChange=${set("defaultModel")}>- <option value="">自动(第一个可用模型)</option>- ${[...new Set([...(models || []), f.defaultModel].filter(Boolean))].map((m) => html`<option value=${m}>${m}</option>`)}- </select>- <div class="row" style="margin-top:12px"><button class="pri" onClick=${save}>保存</button><button class="danger" onClick=${del}>删除</button><span class="muted">${msg}</span></div>- </div>`;-}--function BotSettings({ botId, models }) {- const [d, err, reload] = usePoll(() => api(`/bots/${botId}/settings`), 0, [botId]);- const [msg, setMsg] = useState("");- if (!d) return html`<div class="card"><p class="muted">${err || "加载中…"}</p></div>`;- const s = d.settings, cu = d.computerUse;- const put = async (body) => {- try { await api(`/bots/${botId}/settings`, { method: "PUT", body }); setMsg("✓ 已保存(空闲时自动生效)"); reload(); }- catch (e) { setMsg("✗ " + e.message); }- };- const chk = (label, val, body) => html`<label class="row" style="font-weight:normal"><input type="checkbox" style="width:auto" checked=${val} onChange=${(e) => put(body(e.target.checked))} /> ${label}</label>`;- return html`<div class="card"><h3>设置</h3>- <label>权限预设</label>- <select value=${s.permission} onChange=${(e) => put({ permission: e.target.value })}>- <option value="workspace">工作区可写(默认):只能改本机器人工作区,越界操作需审批</option>- <option value="readonly">只读:不能改文件,命令在只读沙箱中运行</option>- </select>- <label>长期记忆</label>- ${chk("启用长期记忆(remember / forget / recall)", s.memory.enabled, (v) => ({ memory: { enabled: v } }))}- ${chk("回合结束后自动整理记忆", s.memory.review, (v) => ({ memory: { review: v } }))}- ${chk("允许写入团队记忆(所有机器人共享)", s.memory.teamWrite, (v) => ({ memory: { teamWrite: v } }))}- <label>上下文管家</label>- ${chk("上下文变长时自动压缩或开新段(带交接便条)", s.steward.enabled, (v) => ({ steward: { enabled: v } }))}- <label>后台小任务模型(记忆整理 / 管家 / 交接)</label>- <select value=${s.utilityModel} onChange=${(e) => put({ utilityModel: e.target.value })}>- <option value="">与对话模型相同</option>- ${[...new Set([...(models || []), s.utilityModel].filter(Boolean))].map((m) => html`<option value=${m}>${m}</option>`)}- </select>- <label>电脑操作(Computer Use)</label>- <p class="muted">${cu ? (cu.available ? "✓ " : "✗ ") + cu.reason : ""}</p>- ${cu && cu.notice && html`<p class="muted">ℹ️ ${cu.notice}</p>`}- ${chk("启用电脑操作", s.computerUse.enabled, (v) => ({ computerUse: { enabled: v } }))}- <select value=${s.computerUse.backend} disabled=${!s.computerUse.enabled} onChange=${(e) => put({ computerUse: { backend: e.target.value } })}>- <option value="cua">Cua Driver(默认,随附,macOS / Windows / Linux)</option>- ${cu && cu.backends.some((b) => b.id === "codex") && html`<option value="codex">Codex Computer Use 桥(仅 macOS${cu.backends.find((b) => b.id === "codex").available ? "" : ",本机不可用"})</option>`}- </select>- <select value=${s.computerUse.approval} disabled=${!s.computerUse.enabled} onChange=${(e) => put({ computerUse: { approval: e.target.value } })}>- <option value="auto">所有操作自动执行,无需审批(默认)</option>- <option value="ask-input">点击、输入等改变界面的操作先问我;读取界面仍自动</option>- </select>- <p class="muted">${msg}</p>- </div>`;-}--function MemoryViewer({ botId }) {- const [d, err, reload] = usePoll(() => api(`/bots/${botId}/memory`), 0, [botId]);- const [msg, setMsg] = useState("");- if (!d) return html`<div class="card"><p class="muted">${err || "加载中…"}</p></div>`;- const forget = async (sc, text, topic) => {- if (!confirm(`删除这条记忆?\n${text}`)) return;- try { await api(`/bots/${botId}/memory/forget`, { method: "POST", body: { kind: sc.kind, id: sc.id, match: text, topic } }); setMsg("✓ 已删除"); reload(); }- catch (e) { setMsg("✗ " + e.message); }- };- const list = (sc, entries, topic) => entries.map((e) => html`<div class="row"><span class="grow">• ${e.text}</span><button onClick=${() => forget(sc, e.text, topic)}>删除</button></div>`);- return html`<div class="card"><h3>长期记忆 <button class="ghost" onClick=${reload}>刷新</button></h3>- ${d.scopes.map((sc) => html`<div><b>${sc.label}</b>- ${!sc.entries.length && !sc.topics.length ? html`<p class="muted">(空)</p>` : ""}- ${list(sc, sc.entries)}- ${sc.topics.map((t) => html`<div class="muted">主题:${t.name}</div>${list(sc, t.entries, t.name)}`)}- </div>`)}- <p class="muted">${msg}</p>- <details><summary>变更日志(最近 ${d.journal.length} 条)</summary>- ${d.journal.slice().reverse().map((j) => html`<div class="muted">${fmt(j.at)} ${j.op === "add" ? "+" : "-"} [${j.file}] ${j.text} · ${j.by}</div>`)}</details>- <details><summary>上下文管家记录(最近 ${d.steward.length} 条)</summary>- ${d.steward.slice().reverse().map((l) => html`<div class="muted">${fmt(l.at)} ${l.action} ${l.detail}</div>`)}</details>- </div>`;-}--// ---------------- 渠道 -----------------function Feishu({ bot, st, reload }) {- const [appId, setAppId] = useState(bot.feishuAppId);- const [secret, setSecret] = useState("");- const [msg, setMsg] = useState("");- useEffect(() => setAppId(bot.feishuAppId), [bot.id]);- const save = async () => { setMsg("保存并连接中…"); try { await api(`/bots/${bot.id}/feishu`, { method: "PUT", body: { appId, appSecret: secret } }); setSecret(""); setMsg("✓ 已保存"); reload(); } catch (e) { setMsg("✗ " + e.message); } };- const clear = async () => { await api(`/bots/${bot.id}/feishu`, { method: "DELETE" }); setAppId(""); reload(); };- return html`<div class="card"><h3>飞书 <${Badge} s=${st.state} /></h3>- ${st.detail && html`<p class="muted">${st.detail}</p>`}- <label>App ID</label><input value=${appId} placeholder="cli_xxxxxxxx" onInput=${(e) => setAppId(e.target.value)} />- <label>App Secret ${bot.feishuAppSecretMasked && html`<span class="muted">(已保存 ${bot.feishuAppSecretMasked},留空则不修改)</span>`}</label>- <input type="password" value=${secret} onInput=${(e) => setSecret(e.target.value)} />- <div class="row" style="margin-top:12px"><button class="pri" disabled=${!appId} onClick=${save}>保存并连接</button>${bot.feishuAppId && html`<button class="danger" onClick=${clear}>断开</button>`}<span class="muted">${msg}</span></div>- <p class="muted">需在飞书开放平台启用「机器人」能力,事件订阅选择「使用长连接接收事件」并订阅 <code>im.message.receive_v1</code>;权限:<code>im:message.p2p_msg:readonly</code>、<code>im:message:send_as_bot</code>、<code>cardkit:card:write</code>。</p>- </div>`;-}--function Weixin({ bot, st, reload }) {- const [code, setCode] = useState("");- const login = st.login;- const active = login && ["fetching", "wait", "scaned", "need_verifycode"].includes(login.state);- useEffect(() => { if (!active) return; const t = setInterval(reload, 1500); return () => clearInterval(t); }, [active]);- const start = async () => { await api(`/bots/${bot.id}/weixin/login`, { method: "POST", body: {} }); reload(); };- const cancel = async () => { await api(`/bots/${bot.id}/weixin/cancel`, { method: "POST", body: {} }); reload(); };- const logout = async () => { if (confirm("解除微信绑定?")) { await api(`/bots/${bot.id}/weixin/logout`, { method: "POST", body: {} }); reload(); } };- const verify = async () => { await api(`/bots/${bot.id}/weixin/verify`, { method: "POST", body: { code } }); setCode(""); };- const toggle = async () => { await api(`/bots/${bot.id}/weixin`, { method: "PUT", body: { enabled: !bot.weixinEnabled } }); reload(); };- return html`<div class="card"><h3>微信(iLink 官方通道) <${Badge} s=${st.state} /></h3>- ${st.detail && html`<p class="muted">${st.detail}</p>`}- ${st.account && html`<p class="muted">已绑定:${st.account.ilinkBotId}${st.account.pausedUntil > Date.now() ? ` · 暂停至 ${fmt(st.account.pausedUntil)}` : ""}</p>`}- ${login && login.state !== "idle" && html`<div class="row"><${Badge} s=${login.state} /><span>${login.message}</span></div>`}- ${active && login.qrDataUrl && html`<p><img class="qr" src=${login.qrDataUrl} alt="微信登录二维码" /></p><p class="muted">用微信扫一扫,然后在手机上确认。</p>`}- ${login && login.state === "need_verifycode" && html`<div class="row"><input style="width:160px" value=${code} placeholder="验证码" onInput=${(e) => setCode(e.target.value)} /><button onClick=${verify}>提交</button></div>`}- <div class="row" style="margin-top:12px">- ${active ? html`<button onClick=${cancel}>取消</button>` : html`<button class="pri" onClick=${start}>${st.account ? "重新扫码登录" : "扫码登录"}</button>`}- ${st.account && html`<button class="danger" onClick=${logout}>解除绑定</button>`}- <button onClick=${toggle}>${bot.weixinEnabled ? "停用微信渠道" : "启用微信渠道"}</button>- </div>- ${st.quota && st.quota.length > 0 && html`<h4>出站配额(每条入站消息后 24 小时内最多 10 条)</h4>- <table>${st.quota.map((q) => html`<tr><td><code>${q.userId}</code></td><td>剩余 <b>${q.remaining}</b> 条</td><td class="muted">窗口开始 ${fmt(q.windowStartedAt)}</td></tr>`)}</table>`}- </div>`;-}--function ChannelsPanel({ botId }) {- const [bots] = usePoll(() => api("/bots"), 0);- const bot = bots && (bots.bots.find((b) => b.id === botId) || bots.bots[0]);- const [detail, , reload] = usePoll(() => (bot ? api(`/bots/${bot.id}`) : Promise.resolve(null)), 5000, [bot && bot.id]);- if (!bots || !bot) return html`<p class="muted">加载中…</p>`;- return html`<div>- ${detail && detail.bot && html`<${Feishu} bot=${detail.bot} st=${detail.channels.feishu} reload=${reload} /><${Weixin} bot=${detail.bot} st=${detail.channels.weixin} reload=${reload} />`}- </div>`;-}--// ---------------- 会话列表(管理视图) -----------------function ConversationsAdmin({ onOpen }) {- const [data] = usePoll(() => api("/conversations"), 5000);- const [sel, setSel] = useState("");- const [msgs] = usePoll(() => (sel ? api(`/conversations/${encodeURIComponent(sel)}/messages`) : Promise.resolve(null)), 5000, [sel]);- if (!data) return html`<p class="muted">加载中…</p>`;- return html`<div>- <div class="page-head"><h2>会话</h2><p class="sub">全部渠道会话</p></div>- <div class="cols">- <div class="card list" style="padding:0">${data.conversations.length === 0 && html`<p class="muted" style="padding:12px">暂无会话</p>`}- ${data.conversations.map((c) => html`<div class="item ${c.id === sel ? "sel" : ""}" onClick=${() => { setSel(c.id); onOpen && onOpen(c); }}>- <b>${c.channel}</b> · ${c.title || c.peerId}<div class="muted">${c.botId} · ${c.messageCount} 条 · ${fmt(c.updatedAt)}${c.model ? " · " + c.model : ""}</div>- <div class="muted">${c.lastMessage}</div></div>`)}</div>- <div class="card">${msgs ? html`<div class="msgs">${msgs.messages.map((m) => html`<div class=${`msg-row ${m.role}`}><div class=${`msg-bubble ${m.role === "assistant" ? "cardish" : ""}`}>${m.content}</div></div>`)}</div>` : html`<p class="muted">选择左侧会话查看消息</p>`}</div>- </div>- </div>`;-}--// ---------------- 审批(DSH,原生面板) -----------------const AP_STATUS = { pending: "待处理", allowed: "已批准", rejected: "已拒绝", expired: "已过期", answered: "已回答", cancelled: "已取消" };-function QuestionForm({ a, done }) {- const [text, setText] = useState("");- const submit = async () => { await api(`/approvals/${a.id}/answer`, { method: "POST", body: { text } }); setText(""); done(); };- return html`<div>${(a.questions || []).map((q, i) => html`<div><b>${i + 1}. ${q.question}</b>${(q.options || []).map((o, j) => html`<div class="muted"> ${j + 1}) ${o.label}${o.description ? " — " + o.description : ""}</div>`)}</div>`)}- <div class="row" style="margin-top:8px"><input class="grow" style="width:auto" placeholder="每行回答一个问题,可填选项编号" value=${text} onInput=${(e) => setText(e.target.value)} /><button class="pri" disabled=${!text.trim()} onClick=${submit}>回答</button></div></div>`;-}-function Approvals({ botId, compact }) {- const [filter, setFilter] = useState("pending");- const [data, err, reload] = usePoll(() => api(`/approvals${filter ? "?status=" + filter : ""}`), 3000, [filter]);- const [agent] = usePoll(() => api("/agent"), 5000);- const decide = async (id, ok) => { try { await api(`/approvals/${id}/${ok ? "approve" : "deny"}`, { method: "POST", body: {} }); } catch (e) { alert(e.message); } reload(); };- const list = (data && data.approvals || []).filter((a) => !botId || a.botId === botId);- return html`<div>- ${!compact && html`<div class="page-head"><h2>审批</h2><p class="sub">DSH 代理请求与提问</p></div>`}- ${agent && html`<div class="card"><h3>代理(DSH) ${agent.enabled ? html`<span class="badge running">已启用</span>` : html`<span class="badge disabled">未启用(普通对话)</span>`}</h3>- ${Object.entries(agent.hosts || {}).filter(([id]) => !botId || id === botId).map(([id, h]) => html`<div class="row"><b>${id}</b><${Badge} s=${h.state} /><span class="muted">pid ${h.pid || "-"} · ${h.model || "默认模型"} · 重启 ${h.restarts} 次 · 进行中 ${h.activeTurns}${h.lastError ? " · " + h.lastError : ""}</span></div>`)}- ${!compact && html`<p class="muted">每个机器人一个 DSH 子进程;bash 默认在工作区沙箱中运行,越权操作会在这里和聊天中请求批准(10 分钟未处理自动拒绝)。</p>`}- </div>`}- <div class="row" style="margin-bottom:12px"><span class="muted">筛选</span><select style="width:140px" value=${filter} onChange=${(e) => setFilter(e.target.value)}>- <option value="pending">待处理</option><option value="">全部</option><option value="allowed">已批准</option><option value="rejected">已拒绝</option><option value="expired">已过期</option></select>- ${err && html`<span class="muted">✗ ${err}</span>`}</div>- ${list.length === 0 && html`<div class="empty">暂无${filter ? AP_STATUS[filter] : ""}请求</div>`}- ${list.map((a) => html`<div class="card">- <div class="row"><b>${a.kind === "question" ? "提问" : "需批准"} · ${a.code}</b><span class="badge ${a.status === "pending" ? "connecting" : a.status === "allowed" || a.status === "answered" ? "connected" : "disabled"}">${AP_STATUS[a.status] || a.status}</span>- <span class="muted">${a.botId} · ${a.conversationId} · ${fmt(a.createdAt)}${a.status === "pending" ? " · 截止 " + fmt(a.expiresAt) : a.decidedBy ? " · " + a.decidedBy : ""}</span></div>- ${a.kind === "approval" && html`<p><code>${a.tool}</code> <code>${a.detail}</code></p>${a.reason && html`<p class="muted">${a.reason}</p>`}`}- ${a.kind === "question" && (a.status === "pending" ? html`<${QuestionForm} a=${a} done=${reload} />` : html`<p class="muted">${(a.questions || []).map((q) => q.question).join(" / ")}</p>`)}- ${a.kind === "approval" && a.status === "pending" && html`<div class="row"><button class="pri" onClick=${() => decide(a.id, true)}>批准(仅本次)</button><button class="danger" onClick=${() => decide(a.id, false)}>拒绝</button></div>`}- </div>`)}- </div>`;-}--const Models = ({ theme }) => html`<iframe class="magpie" src=${`/magpie/?theme=${theme}`} title="magpie"></iframe>`;--// ---------------- 中栏:对话 -----------------function ChatPane({ bot, onToggleRight, rightOpen, onBusyChange }) {- const [text, setText] = useState("");- const [log, setLog] = useState([]);- const [busy, setBusy] = useState(false);- const [convId, setConvId] = useState("");- const bottom = useRef(null);- const ta = useRef(null);-- useEffect(() => { onBusyChange && onBusyChange(busy); return () => onBusyChange && onBusyChange(false); }, [busy]);-- // 加载该机器人最近的网页测试会话消息(若有)- useEffect(() => {- setLog([]); setConvId(""); setText("");- let cancelled = false;- (async () => {- try {- const data = await api("/conversations");- const mine = (data.conversations || []).filter((c) => c.botId === bot.id && c.channel === "web");- mine.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0));- if (mine[0]) {- setConvId(mine[0].id);- const m = await api(`/conversations/${encodeURIComponent(mine[0].id)}/messages`);- if (!cancelled) setLog((m.messages || []).map((x) => ({ role: x.role, content: x.content, at: x.createdAt })));- }- } catch (_) { /* 首次无会话 */ }- })();- return () => { cancelled = true; };- }, [bot.id]);-- useEffect(() => { bottom.current?.scrollIntoView?.({ behavior: "smooth" }); }, [log, busy]);-- const sendMsg = async () => {- const t = text.trim(); if (!t || busy) return;- setText(""); setBusy(true);- setLog((l) => [...l, { role: "user", content: t, at: Date.now() }]);- try {- const r = await api(`/bots/${bot.id}/chat`, { method: "POST", body: { text: t } });- if (r.conversationId) setConvId(r.conversationId);- const extra = [...(r.prompts || []).map((p) => ({ role: "prompt", content: p.prompt }))];- const files = (r.files || []).map((f) => ({ role: "progress", content: "📎 已交付文件:" + f + "(微信/飞书会直接发送;网页端请在机器人工作区查看)" }));- setLog((l) => [...l, ...extra, { role: "assistant", content: r.reply, at: Date.now() }, ...files]);- } catch (e) {- setLog((l) => [...l, { role: "assistant", content: "✗ " + e.message }]);- }- setBusy(false);- ta.current?.focus?.();- };-- const onKey = (e) => {- if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); sendMsg(); }- };-- return html`<div class="center">- <div class="chat-head">- <div>- <div class="chat-head-title">${bot.name}</div>- <div class="chat-head-sub">${bot.defaultModel || "自动模型"}${convId ? " · " + convId.slice(0, 8) : ""}</div>- </div>- <div class="chat-head-actions">- <button class="ghost" title="切换右侧面板" onClick=${onToggleRight}>${rightOpen ? "收起详情" : "详情"}</button>- </div>- </div>- <div class="transcript">- ${log.length === 0 && !busy && html`<div class="empty-chat">- <h2>和 ${bot.name} 对话</h2>- <p>直接在此测试机器人。支持 <code>/model</code>、<code>/reset</code>、<code>/new</code>、<code>/help</code>。渠道与审批在右侧。</p>- </div>`}- ${log.map((m) => {- if (m.role === "progress" || m.role === "prompt") {- return html`<div class="msg-progress"><span class="dot"></span><span>${m.content}</span></div>`;- }- const role = m.role === "user" ? "user" : "assistant";- return html`<div class=${`msg-row ${role}`}>- <div class=${`msg-bubble ${role === "assistant" ? "" : ""}`}>${m.content}</div>- ${m.at && html`<div class="msg-meta">${fmt(m.at)}</div>`}- </div>`;- })}- ${busy && html`<div class="msg-progress"><span class="dot"></span><span>正在处理…</span></div>`}- <div ref=${bottom}></div>- </div>- <div class="composer-wrap">- <div class="composer">- <textarea ref=${ta} rows="1" placeholder=${`给 ${bot.name} 发消息`}- value=${text} onInput=${(e) => setText(e.target.value)} onKeyDown=${onKey}- disabled=${busy} />- <button class="send" disabled=${busy || !text.trim()} onClick=${sendMsg}>${busy ? "…" : "发送"}</button>- </div>- <div class="composer-hint">Enter 发送 · Shift+Enter 换行 · 指令 /model /reset /new /help</div>- </div>- </div>`;-}--// ---------------- 右栏 -----------------function RightPane({ bot, models, onSaved, onDeleted, onClose, working }) {- const [tab, setTab] = useState("channels");- const rightRef = useRef(null);- usePointerLook(rightRef);- const tabs = [- ["channels", "渠道"],- ["settings", "设置"],- ["memory", "记忆"],- ["approvals", "审批"],- ];- return html`<div class="right" ref=${rightRef}>- <div class="right-head">- <div class="row" style="gap:8px">- <${BotAvatar} name=${bot.name} id=${bot.id} size=${28} working=${!!working} />- <b style="font-size:14px">${bot.name}</b>- </div>- <button class="icon-btn" title="收起" onClick=${onClose}>✕</button>- </div>- <div class="right-tabs">- ${tabs.map(([id, label]) => html`<button class=${tab === id ? "on" : ""} onClick=${() => setTab(id)}>${label}</button>`)}- </div>- <div class="right-body">- ${tab === "channels" && html`<${ChannelsPanel} botId=${bot.id} />`}- ${tab === "settings" && html`- <${BotEditor} key=${bot.id} bot=${bot} models=${models} onSaved=${onSaved} onDeleted=${onDeleted} />- <${BotSettings} key=${"s" + bot.id} botId=${bot.id} models=${models} />- `}- ${tab === "memory" && html`<${MemoryViewer} key=${"m" + bot.id} botId=${bot.id} />`}- ${tab === "approvals" && html`<${Approvals} botId=${bot.id} compact=${true} />`}- </div>- </div>`;-}--// ---------------- 左栏 -----------------function LeftRail({ bots, botId, setBotId, view, setView, themeMode, setThemeMode, onCreate, workingById = {} }) {- const [name, setName] = useState("");- const [creating, setCreating] = useState(false);- const leftRef = useRef(null);- usePointerLook(leftRef);- const [convs] = usePoll(() => api("/conversations"), 8000);- const byBot = useMemo(() => {- const map = {};- for (const c of (convs && convs.conversations) || []) {- if (!map[c.botId] || (c.updatedAt || 0) > (map[c.botId].updatedAt || 0)) map[c.botId] = c;- }- return map;- }, [convs]);-- const create = async () => {- const n = name.trim(); if (!n) return;- setCreating(true);- try {- const r = await api("/bots", { method: "POST", body: { name: n } });- setName(""); setCreating(false); onCreate(r.bot);- } catch (e) { alert(e.message); setCreating(false); }- };-- return html`<div class="left" ref=${leftRef}>- <div class="brand">- <${Mark} />- <div>- <div class="brand-name">anymodel bot</div>- <div class="brand-sub">本机控制台</div>- </div>- </div>- <div class="left-tools">- <button class="grow-btn" onClick=${() => setCreating((v) => !v)}>+ 新建机器人</button>- </div>- ${creating && html`<div style="padding:0 12px 10px">- <div class="row">- <input class="grow" style="width:auto" placeholder="名称" value=${name} onInput=${(e) => setName(e.target.value)}- onKeyDown=${(e) => e.key === "Enter" && create()} />- <button class="pri" disabled=${!name.trim()} onClick=${create}>创建</button>- </div>- </div>`}- <div class="left-scroll">- <div class="sec-label">机器人</div>- ${(bots || []).map((b) => {- const snip = byBot[b.id];- return html`<button type="button" class=${`thread ${view === "chat" && b.id === botId ? "sel" : ""}`}- onClick=${() => { setBotId(b.id); setView("chat"); }}>- <${BotAvatar} name=${b.name} id=${b.id} size=${36} working=${!!workingById[b.id]} />- <div class="thread-body">- <div class="thread-title">${b.name}</div>- <div class="thread-snip">${snip ? (snip.lastMessage || snip.title || snip.channel) : (b.defaultModel || "尚未对话")}</div>- ${snip && html`<div class="thread-meta">${fmt(snip.updatedAt)}</div>`}- </div>- </button>`;- })}- ${(!bots || bots.length === 0) && html`<div class="empty" style="margin:8px">还没有机器人。点上方新建。</div>`}- </div>- <div class="left-foot">- <div class="admin-links">- <button class=${view === "overview" ? "on" : ""} onClick=${() => setView("overview")}>概览</button>- <button class=${view === "approvals" ? "on" : ""} onClick=${() => setView("approvals")}>审批</button>- <button class=${view === "conversations" ? "on" : ""} onClick=${() => setView("conversations")}>会话</button>- <button class=${view === "models" ? "on" : ""} onClick=${() => setView("models")}>模型</button>- </div>- <div class="theme-toggle">- <button class=${themeMode === "system" ? "on" : ""} onClick=${() => setThemeMode("system")}>系统</button>- <button class=${themeMode === "light" ? "on" : ""} onClick=${() => setThemeMode("light")}>浅色</button>- <button class=${themeMode === "dark" ? "on" : ""} onClick=${() => setThemeMode("dark")}>深色</button>- </div>- </div>- </div>`;-}--// ---------------- 外壳 -----------------function App() {- const hash = location.hash.slice(1);- const initialView = ["overview", "approvals", "conversations", "models", "chat"].includes(hash) ? hash : "chat";- const [view, setViewRaw] = useState(initialView);- const [botId, setBotId] = useState("");- const [rightOpen, setRightOpen] = useState(true);- const [chatBusy, setChatBusy] = useState(false);- const [themeMode, setThemeMode, theme] = useTheme();- const [botsData, , reloadBots] = usePoll(() => api("/bots"), 0);- const [models] = usePoll(() => api("/models"), 0);- const [agent] = usePoll(() => api("/agent"), 2500);-- const setView = (v) => { setViewRaw(v); location.hash = v; };- useEffect(() => {- const onHash = () => {- const h = location.hash.slice(1);- if (["overview", "approvals", "conversations", "models", "chat"].includes(h)) setViewRaw(h);- };- window.addEventListener("hashchange", onHash);- return () => window.removeEventListener("hashchange", onHash);- }, []);-- const bots = botsData ? botsData.bots : null;- const bot = bots && (bots.find((b) => b.id === botId) || bots[0]);- useEffect(() => { if (bot && bot.id !== botId) setBotId(bot.id); }, [bots, bot && bot.id]);- const workingById = useMemo(() => {- const map = {};- for (const [id, h] of Object.entries((agent && agent.hosts) || {})) {- const turns = Number(h.activeTurns || 0);- map[id] = turns > 0 || h.state === "starting" || h.state === "restarting";- }- if (chatBusy && bot) map[bot.id] = true;- return map;- }, [agent, chatBusy, bot && bot.id]);- const selectedWorking = !!(bot && workingById[bot.id]);-- const shellClass = [- "app",- view === "chat" && !rightOpen ? "right-collapsed" : "",- view === "models" ? "view-models" : "",- view !== "chat" && view !== "models" ? "view-admin" : "",- ].filter(Boolean).join(" ");-- return html`<div class=${shellClass}>- <${LeftRail}- bots=${bots || []}- botId=${bot && bot.id}- setBotId=${setBotId}- view=${view}- setView=${setView}- themeMode=${themeMode}- setThemeMode=${setThemeMode}- workingById=${workingById}- onCreate=${(b) => { reloadBots(); setBotId(b.id); setView("chat"); }}- />- ${view === "chat" && bot && html`<${ChatPane} bot=${bot} rightOpen=${rightOpen} onToggleRight=${() => setRightOpen((v) => !v)} onBusyChange=${setChatBusy} />`}- ${view === "chat" && !bot && html`<div class="center"><div class="transcript"><div class="empty-chat"><h2>开始</h2><p>在左侧新建一个机器人,然后直接对话。</p></div></div></div>`}- ${view === "overview" && html`<div class="admin-pane"><${Overview} goChat=${() => setView("chat")} /></div>`}- ${view === "approvals" && html`<div class="admin-pane"><${Approvals} /></div>`}- ${view === "conversations" && html`<div class="admin-pane"><${ConversationsAdmin} onOpen=${(c) => { setBotId(c.botId); setView("chat"); }} /></div>`}- ${view === "models" && html`<div class="admin-pane bleed"><${Models} theme=${theme} /></div>`}- ${view === "chat" && rightOpen && bot && html`<${RightPane}- bot=${bot}- models=${models && models.models}- onSaved=${() => reloadBots()}- onDeleted=${() => { setBotId(""); reloadBots(); }}- onClose=${() => setRightOpen(false)}- working=${selectedWorking}- />`}- </div>`;-}--render(html`<${App} />`, document.getElementById("app"));diff --git a/ui/components/avatar.js b/ui/components/avatar.jsnew file mode 100644index 0000000..162d150--- /dev/null+++ b/ui/components/avatar.js@@ -0,0 +1,88 @@+// 机器人头像(每个机器人一个色相;只在工作中才动)与应用标志。+import { useEffect } from "preact/hooks";+import { html } from "./ui.js";++/** Stable soft hue (0–359) from bot id/name. */+export function botHue(id, name) {+ const s = String(id || name || "?");+ let h = 2166136261;+ for (let i = 0; i < s.length; i++) {+ h ^= s.charCodeAt(i);+ h = Math.imul(h, 16777619);+ }+ return Math.abs(h) % 360;+}++/**+ * One shared pointermove on a container; writes --look-x/--look-y on each working face+ * inside it (idle faces stay still).+ */+export function usePointerLook(containerRef) {+ useEffect(() => {+ const root = containerRef.current;+ if (!root || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;+ let raf = 0;+ let px = -1e5;+ let py = -1e5;+ const apply = () => {+ raf = 0;+ for (const el of root.querySelectorAll(".bot-face.is-working")) {+ const r = el.getBoundingClientRect();+ if (!r.width) continue;+ const dx = px - (r.left + r.width / 2);+ const dy = py - (r.top + r.height / 2);+ const reach = Math.max(96, r.width * 3.2);+ const fall = Math.max(0, 1 - Math.hypot(dx, dy) / reach);+ el.style.setProperty("--look-x", Math.max(-1, Math.min(1, (dx / (r.width * 0.55)) * fall)).toFixed(3));+ el.style.setProperty("--look-y", Math.max(-1, Math.min(1, (dy / (r.height * 0.55)) * fall)).toFixed(3));+ }+ };+ const onMove = (e) => {+ px = e.clientX;+ py = e.clientY;+ if (!raf) raf = requestAnimationFrame(apply);+ };+ const onLeave = () => {+ px = py = -1e5;+ if (!raf) raf = requestAnimationFrame(apply);+ };+ root.addEventListener("pointermove", onMove, { passive: true });+ root.addEventListener("pointerleave", onLeave);+ return () => {+ root.removeEventListener("pointermove", onMove);+ root.removeEventListener("pointerleave", onLeave);+ if (raf) cancelAnimationFrame(raf);+ };+ }, []);+}++export function BotAvatar({ name, id, size = 34, working = false }) {+ const vb = size;+ const eyeR = size * 0.11;+ const pupilR = size * 0.055;+ const eyeY = size * 0.42;+ const eyeDX = size * 0.16;+ const mouthY = size * 0.68;+ return html`<div class=${`bot-face${working ? " is-working" : ""}`} style=${{ width: size + "px", height: size + "px", "--bot-hue": String(botHue(id, name)) }} aria-hidden="true">+ <div class="bot-face-3d">+ <svg width=${size} height=${size} viewBox=${`0 0 ${vb} ${vb}`} xmlns="http://www.w3.org/2000/svg">+ <circle class="bot-head" cx=${vb / 2} cy=${vb / 2} r=${vb / 2 - 0.5} />+ <ellipse class="bot-eye-white" cx=${vb / 2 - eyeDX} cy=${eyeY} rx=${eyeR * 1.15} ry=${eyeR} />+ <ellipse class="bot-eye-white" cx=${vb / 2 + eyeDX} cy=${eyeY} rx=${eyeR * 1.15} ry=${eyeR} />+ <g class="bot-pupils">+ <circle class="bot-pupil" cx=${vb / 2 - eyeDX} cy=${eyeY} r=${pupilR} />+ <circle class="bot-pupil" cx=${vb / 2 + eyeDX} cy=${eyeY} r=${pupilR} />+ </g>+ <path class="bot-mouth bot-mouth-idle" d=${`M ${vb / 2 - size * 0.12} ${mouthY} Q ${vb / 2} ${mouthY + size * 0.08} ${vb / 2 + size * 0.12} ${mouthY}`} stroke-linecap="round" />+ <ellipse class="bot-mouth bot-mouth-work" cx=${vb / 2} cy=${mouthY + size * 0.02} rx=${size * 0.07} ry=${size * 0.045} />+ </svg>+ </div>+ </div>`;+}++/** AnyModelBot 自己的标志:一个 m 字形的折线 */+export function AppMark({ size = 32 }) {+ return html`<div class="app-mark" style=${{ width: size + "px", height: size + "px" }} aria-hidden="true">+ <svg viewBox="0 0 18 18" fill="none"><path d="M4 12.5V5.5L9 10l5-4.5v7" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" /></svg>+ </div>`;+}diff --git a/ui/components/markdown.js b/ui/components/markdown.jsnew file mode 100644index 0000000..4e09014--- /dev/null+++ b/ui/components/markdown.js@@ -0,0 +1,69 @@+// AST → Preact 节点。文本始终作为文本节点渲染;链接已在解析时经 safeHref 过滤。+import { h } from "preact";+import { parseMarkdown, linkify } from "../lib/markdown.js";+import { html, CopyButton } from "./ui.js";++function inline(nodes) {+ return nodes.map((n, i) => {+ if (typeof n === "string") return n;+ switch (n.t) {+ case "br":+ return h("br", { key: i });+ case "code":+ return h("code", { key: i }, n.text);+ case "b":+ return h("strong", { key: i }, inline(n.c));+ case "i":+ return h("em", { key: i }, inline(n.c));+ case "s":+ return h("del", { key: i }, inline(n.c));+ case "a":+ return h("a", { key: i, href: n.href, target: "_blank", rel: "noopener noreferrer" }, inline(n.c));+ default:+ return null;+ }+ });+}++function CodeBlock({ lang, text }) {+ return html`<div class="codeblock">+ <div class="bar"><span class="lang">${lang || "代码"}</span><${CopyButton} text=${text} label="复制代码" /></div>+ <pre><code>${text}</code></pre>+ </div>`;+}++function blocks(list) {+ return list.map((b, i) => {+ switch (b.t) {+ case "p":+ return h("p", { key: i }, inline(b.c));+ case "h":+ return h("h" + Math.min(4, b.level), { key: i }, inline(b.c));+ case "hr":+ return h("hr", { key: i });+ case "code":+ return h(CodeBlock, { key: i, lang: b.lang, text: b.text });+ case "quote":+ return h("blockquote", { key: i }, blocks(b.c));+ case "ul":+ case "ol":+ return h(b.t, { key: i, start: b.t === "ol" && b.start !== 1 ? b.start : undefined }, b.items.map((it, k) => h("li", { key: k }, inline(it.c), it.sub.length ? blocks(it.sub) : null)));+ case "table":+ return h(+ "div",+ { key: i, class: "table-wrap" },+ h("table", null, h("thead", null, h("tr", null, b.head.map((c, k) => h("th", { key: k, style: b.align[k] ? { textAlign: b.align[k] } : undefined }, inline(c))))), h("tbody", null, b.rows.map((r, k) => h("tr", { key: k }, r.map((c, j) => h("td", { key: j, style: b.align[j] ? { textAlign: b.align[j] } : undefined }, inline(c))))))),+ );+ default:+ return null;+ }+ });+}++export function Markdown({ text }) {+ return h("div", { class: "md" }, blocks(parseMarkdown(text)));+}++export function Linkified({ text }) {+ return inline(linkify(text));+}diff --git a/ui/components/model-picker.js b/ui/components/model-picker.jsnew file mode 100644index 0000000..b6e32d7--- /dev/null+++ b/ui/components/model-picker.js@@ -0,0 +1,79 @@+// 模型选择器(magpie picker 的样式;数据来自 Modelflare 的 /v1/models)。+// 不做厂商图标栏:各厂商 logo 是第三方商标,未取得授权前不用。+import { useMemo, useRef, useState } from "preact/hooks";+import { html, Popover, Icon } from "./ui.js";++/** 内置网关列出的模型带 "modelflare/" 前缀,Modelflare 直接列出的不带;两种写法都能调用,显示与比较时去掉它 */+export const normModel = (m) => (m && m.startsWith("modelflare/") ? m.slice("modelflare/".length) : m || "");+export const sameModel = (a, b) => !!a && !!b && normModel(a) === normModel(b);+export const shortModel = (m) => (m && m.includes("/") ? m.slice(m.lastIndexOf("/") + 1) : m);++/** 按 "厂商/模型" 的前缀分组(没有前缀的放在最后);返回 [厂商, [[原始 id, 显示名]]] */+export function groupModels(models, q = "") {+ const needle = q.trim().toLowerCase();+ const groups = new Map();+ for (const m of models) {+ const n = normModel(m);+ if (needle && !n.toLowerCase().includes(needle)) continue;+ const k = n.includes("/") ? n.slice(0, n.indexOf("/")) : "";+ if (!groups.has(k)) groups.set(k, []);+ groups.get(k).push([m, k ? n.slice(k.length + 1) : n]);+ }+ return [...groups.entries()].sort((a, b) => (a[0] === "" ? 1 : b[0] === "" ? -1 : a[0].localeCompare(b[0])));+}++/**+ * models: string[] | null(加载中);error: 加载失败时的说明。+ * reset: { label, note, onSelect } 顶部"恢复默认"项;foot: { label, onClick, disabled } 底部操作。+ */+export function ModelPicker({ anchor, models, error, current, onPick, onClose, reset, foot, onRetry, prefer = "down", align = "left" }) {+ const [q, setQ] = useState("");+ const [sel, setSel] = useState(0);+ const listRef = useRef(null);+ const groups = useMemo(() => groupModels(models || [], q), [models, q]);+ const custom = q.trim() && !(models || []).some((m) => sameModel(m, q.trim())) ? q.trim() : "";+ const flat = [...(reset && !q ? [{ reset: true }] : []), ...groups.flatMap(([, ms]) => ms.map(([m]) => ({ m }))), ...(custom ? [{ m: custom, custom: true }] : [])];+ const choose = (it) => {+ onClose();+ if (it.reset) reset.onSelect();+ else onPick(it.m);+ };+ const onKey = (e) => {+ if (e.key === "ArrowDown") {+ e.preventDefault();+ setSel((s) => Math.min(flat.length - 1, s + 1));+ } else if (e.key === "ArrowUp") {+ e.preventDefault();+ setSel((s) => Math.max(0, s - 1));+ } else if (e.key === "Enter" && flat[sel]) {+ e.preventDefault();+ choose(flat[sel]);+ }+ requestAnimationFrame(() => listRef.current?.querySelector("li.sel")?.scrollIntoView({ block: "nearest" }));+ };+ let idx = -1;+ const item = (it, label, note) => {+ idx++;+ const i = idx;+ return html`<li role="option" aria-selected=${sel === i} class=${`${sel === i ? "sel" : ""} ${(!it.reset && sameModel(it.m, current)) || (it.reset && !current) ? "cur" : ""}`}+ onPointerMove=${() => setSel(i)} onClick=${() => choose(it)}>+ <span class="v">${label}</span>${note && html`<span class="n">${note}</span>`}+ <span class="check"><${Icon} name="check" size=${14} /></span>+ </li>`;+ };+ return html`<${Popover} anchor=${anchor} onClose=${onClose} class="model-picker" width=${340} maxHeight=${420} prefer=${prefer} align=${align} label="选择模型">+ <div class="search"><${Icon} name="search" size=${14} />+ <input placeholder="筛选,或输入任意模型 ID" value=${q} onInput=${(e) => { setQ(e.target.value); setSel(0); }} onKeyDown=${onKey} aria-label="筛选模型" />+ </div>+ <ul role="listbox" ref=${listRef}>+ ${models === null && !error && [0, 1, 2, 3, 4].map((k) => html`<li key=${k}><span class="skel" style=${{ width: 60 + ((k * 37) % 30) + "%" }}></span></li>`)}+ ${error && html`<li class="explained" style="pointer-events:auto"><span class="v" style="white-space:normal;color:var(--red)">获取模型列表失败:${error}</span>+ ${onRetry && html`<button type="button" class="text" onClick=${onRetry}>重试</button>`}</li>`}+ ${reset && !q && item({ reset: true }, reset.label, reset.note)}+ ${groups.map(([g, ms]) => html`${g && html`<li class="group">${g}</li>`}${ms.map(([m, label]) => item({ m }, label))}`)}+ ${custom && item({ m: custom, custom: true }, `使用「${custom}」`, "自定义模型 ID")}+ ${models && !models.length && !q && html`<li class="explained"><span class="v" style="white-space:normal">没有可用模型:这个 Key 所在的分组还没有开放模型</span></li>`}+ </ul>+ ${foot && html`<div class="foot"><button type="button" disabled=${foot.disabled} onClick=${() => { onClose(); foot.onClick(); }}>${foot.label}</button></div>`}+ <//>`;+}diff --git a/ui/components/ui.js b/ui/components/ui.jsnew file mode 100644index 0000000..6061d44--- /dev/null+++ b/ui/components/ui.js@@ -0,0 +1,303 @@+// 共用组件:图标、分段控件、弹出菜单、确认框、提示胶囊、复制按钮。+import { h } from "preact";+import { useEffect, useLayoutEffect, useRef, useState, useCallback } from "preact/hooks";+import htm from "htm";+import { useStore, toasts, dismissToast, dialog } from "../lib/store.js";++export const html = htm.bind(h);++// —— 线性图标(16px,currentColor)——+const P = {+ search: "M7.25 12.5a5.25 5.25 0 1 0 0-10.5 5.25 5.25 0 0 0 0 10.5ZM11.2 11.2 14 14",+ plus: "M8 3v10M3 8h10",+ close: "M4 4l8 8M12 4l-8 8",+ chevDown: "M4 6l4 4 4-4",+ chevLeft: "M10 3.5 5.5 8l4.5 4.5",+ chevRight: "M6 3.5 10.5 8 6 12.5",+ check: "M3.5 8.5l3 3 6-7",+ up: "M8 13V3.5M3.75 7.75 8 3.5l4.25 4.25",+ down: "M8 3v9.5M3.75 8.25 8 12.5l4.25-4.25",+ gear: "M8 10.25a2.25 2.25 0 1 0 0-4.5 2.25 2.25 0 0 0 0 4.5ZM13 8c0-.4-.04-.79-.12-1.16l1.37-1.07-1.3-2.25-1.62.65a5 5 0 0 0-2-1.16L9.1 1.3H6.5L6.25 3a5 5 0 0 0-2 1.16l-1.62-.65-1.3 2.25 1.37 1.07a5 5 0 0 0 0 2.32L1.33 10.3l1.3 2.25 1.62-.65a5 5 0 0 0 2 1.16l.25 1.64h2.6l.25-1.64a5 5 0 0 0 2-1.16l1.62.65 1.3-2.25-1.37-1.07c.08-.37.12-.76.12-1.16Z",+ copy: "M5.5 5.5V3.25c0-.41.34-.75.75-.75h6.5c.41 0 .75.34.75.75v6.5c0 .41-.34.75-.75.75H10.5M3.25 5.5h6.5c.41 0 .75.34.75.75v6.5c0 .41-.34.75-.75.75h-6.5a.75.75 0 0 1-.75-.75v-6.5c0-.41.34-.75.75-.75Z",+ ext: "M6.5 3.5H3.75a.75.75 0 0 0-.75.75v8c0 .41.34.75.75.75h8c.41 0 .75-.34.75-.75V9.5M9 3h4v4M13 3 7.5 8.5",+ eye: "M1.75 8S4 3.75 8 3.75 14.25 8 14.25 8 12 12.25 8 12.25 1.75 8 1.75 8ZM8 10a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z",+ eyeOff: "M2.5 2.5l11 11M6.6 6.6a2 2 0 0 0 2.8 2.8M4.3 4.9C2.7 6 1.75 8 1.75 8S4 12.25 8 12.25c1.2 0 2.27-.38 3.17-.93M7 3.82c.32-.05.65-.07 1-.07 4 0 6.25 4.25 6.25 4.25s-.52.98-1.48 2.05",+ paste: "M5.5 2.75h5v1.5h-5zM10.5 3.5h1.75c.41 0 .75.34.75.75v9c0 .41-.34.75-.75.75h-8.5a.75.75 0 0 1-.75-.75v-9c0-.41.34-.75.75-.75H5.5",+ trash: "M2.75 4.25h10.5M6.25 4.25V2.75h3.5v1.5M4 4.25l.6 8.6c.03.4.36.7.75.7h5.3c.4 0 .72-.3.75-.7l.6-8.6",+ file: "M9 1.75H4.25a.75.75 0 0 0-.75.75v11c0 .41.34.75.75.75h7.5c.41 0 .75-.34.75-.75V5.25L9 1.75ZM9 1.75v3.5h3.5M5.75 8.25h4.5M5.75 10.75h4.5",+ refresh: "M13.25 8a5.25 5.25 0 1 1-1.54-3.71M13.25 2.75v2.5h-2.5",+ stop: "M4.5 4.5h7v7h-7z",+ more: "M4 8h.01M8 8h.01M12 8h.01",+};+export function Icon({ name, size = 16, stroke = 1.6, class: cls = "" }) {+ const fill = name === "stop";+ return html`<svg class=${`ic ${cls}`} width=${size} height=${size} viewBox="0 0 16 16" fill=${fill ? "currentColor" : "none"}+ stroke="currentColor" stroke-width=${name === "more" ? 2.6 : stroke} stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d=${P[name]} /></svg>`;+}++/** 关闭 / 外部点击 / Esc */+export function useDismiss(ref, onClose, active = true, ignore) {+ useEffect(() => {+ if (!active) return;+ const down = (e) => {+ if (ref.current?.contains(e.target)) return;+ if (ignore?.current?.contains(e.target)) return;+ onClose();+ };+ const key = (e) => {+ if (e.key === "Escape") {+ e.stopPropagation();+ onClose();+ }+ };+ document.addEventListener("pointerdown", down, true);+ document.addEventListener("keydown", key, true);+ return () => {+ document.removeEventListener("pointerdown", down, true);+ document.removeEventListener("keydown", key, true);+ };+ }, [active, onClose]);+}++// —— 分段控件:滑动的品牌色 thumb ——+export function Seg({ options, value, onChange, disabled, label }) {+ const ref = useRef(null);+ const thumb = useRef(null);+ const first = useRef(true);+ const place = useCallback(() => {+ const on = ref.current?.querySelector("button.on");+ const t = thumb.current;+ if (!t) return;+ if (!on) {+ t.style.opacity = "0";+ return;+ }+ t.style.opacity = "1";+ t.style.width = on.offsetWidth + "px";+ t.style.transform = `translateX(${on.offsetLeft}px)`;+ }, []);+ useLayoutEffect(() => {+ place();+ if (first.current) {+ first.current = false;+ requestAnimationFrame(() => thumb.current?.classList.remove("still"));+ }+ }, [value, options.length]);+ useEffect(() => {+ document.fonts?.ready?.then(place);+ }, []);+ return html`<div class=${`seg${disabled ? " disabled" : ""}`} ref=${ref} role="radiogroup" aria-label=${label}>+ <span class="thumb still" ref=${thumb} aria-hidden="true"></span>+ ${options.map(([v, text, title]) => html`<button type="button" role="radio" aria-checked=${v === value} class=${v === value ? "on" : ""}+ disabled=${disabled} title=${title} onClick=${() => v !== value && onChange(v)}>${text}</button>`)}+ </div>`;+}++/** 打开在锚点下方(空间不够时在上方)的浮层,position: fixed */+export function usePopPosition(anchor, open, { width = 280, prefer = "down", align = "left", maxHeight = 360 } = {}) {+ const [pos, setPos] = useState(null);+ useLayoutEffect(() => {+ if (!open || !anchor) return setPos(null);+ const compute = () => {+ const r = anchor.getBoundingClientRect ? anchor.getBoundingClientRect() : anchor;+ const vw = window.innerWidth;+ const vh = window.innerHeight;+ const below = vh - r.bottom - 12;+ const above = r.top - 12;+ const up = prefer === "up" ? above > 160 || above > below : below < Math.min(maxHeight, 220) && above > below;+ let left = align === "right" ? r.right - width : r.left;+ left = Math.max(8, Math.min(left, vw - width - 8));+ const ox = Math.max(12, Math.min(width - 12, r.left + (r.width || 0) / 2 - left));+ setPos(up ? { left, bottom: vh - r.top + 6, up: true, ox, max: Math.min(maxHeight, above) } : { left, top: r.bottom + 6, up: false, ox, max: Math.min(maxHeight, below) });+ };+ compute();+ window.addEventListener("resize", compute);+ return () => window.removeEventListener("resize", compute);+ }, [open, anchor]);+ return pos;+}++export function Popover({ anchor, onClose, class: cls = "", width = 280, prefer, align, maxHeight, children, label, keepFocus }) {+ const ref = useRef(null);+ const anchorRef = useRef(anchor && anchor.nodeType ? anchor : null);+ anchorRef.current = anchor && anchor.nodeType ? anchor : null;+ const pos = usePopPosition(anchor, true, { width, prefer, align, maxHeight });+ useDismiss(ref, onClose, true, anchorRef);+ useEffect(() => {+ if (keepFocus) return;+ const prev = document.activeElement;+ requestAnimationFrame(() => {+ const target = ref.current?.querySelector("input, [role=option], [role=menuitem], button");+ target?.focus?.();+ });+ return () => prev?.focus?.({ preventScroll: true });+ }, []);+ if (!pos) return null;+ const style = { left: pos.left + "px", width: width + "px", "--ox": pos.ox + "px", maxHeight: pos.max + "px", ...(pos.up ? { bottom: pos.bottom + "px" } : { top: pos.top + "px" }) };+ return html`<div class=${`pop ${cls}${pos.up ? " up" : ""}`} ref=${ref} style=${style} role="dialog" aria-label=${label}>${children}</div>`;+}++/**+ * 菜单:items = [{ label, note, onSelect, danger, disabled, cur }] | { sep: true } | { group: "…" }+ * 键盘:↑↓ 选择,Enter 执行,Esc 关闭。+ */+export function Menu({ anchor, items, onClose, width = 240, prefer, align, label }) {+ const pickable = items.map((it, i) => (it.sep || it.group || it.disabled ? -1 : i)).filter((i) => i >= 0);+ const [sel, setSel] = useState(pickable[0] ?? -1);+ const listRef = useRef(null);+ const run = (it) => {+ onClose();+ it.onSelect?.();+ };+ const onKey = (e) => {+ const k = pickable.indexOf(sel);+ if (e.key === "ArrowDown") {+ e.preventDefault();+ setSel(pickable[(k + 1) % pickable.length]);+ } else if (e.key === "ArrowUp") {+ e.preventDefault();+ setSel(pickable[(k - 1 + pickable.length) % pickable.length]);+ } else if (e.key === "Enter" && sel >= 0) {+ e.preventDefault();+ run(items[sel]);+ }+ };+ useEffect(() => listRef.current?.focus(), []);+ return html`<${Popover} anchor=${anchor} onClose=${onClose} width=${width} prefer=${prefer} align=${align} label=${label}>+ <ul role="menu" tabindex="-1" ref=${listRef} onKeyDown=${onKey} style="outline:none">+ ${items.map((it, i) =>+ it.sep+ ? html`<li class="sep" role="separator"></li>`+ : it.group+ ? html`<li class="group">${it.group}</li>`+ : html`<li role="menuitem" aria-disabled=${!!it.disabled}+ class=${[sel === i ? "sel" : "", it.danger ? "danger" : "", it.disabled ? "disabled" : "", it.cur ? "cur" : "", it.note ? "explained" : ""].join(" ")}+ onPointerMove=${() => !it.disabled && setSel(i)} onClick=${() => !it.disabled && run(it)}>+ ${it.note ? html`<span class="v">${it.label}</span><span class="n" style="flex:none">${it.note}</span>` : html`<span class="v">${it.label}</span>`}+ ${!it.note && html`<span class="check"><${Icon} name="check" size=${14} /></span>`}+ </li>`,+ )}+ </ul>+ <//>`;+}++/** 行右侧的菜单按钮(magpie .proto.pick) */+export function MenuButton({ value, options, onChange, disabled, label, width = 260 }) {+ const [open, setOpen] = useState(false);+ const ref = useRef(null);+ const cur = options.find((o) => o[0] === value);+ return html`<button type="button" class="pick" ref=${ref} disabled=${disabled} aria-haspopup="menu" aria-expanded=${open} aria-label=${label}+ onClick=${() => setOpen((v) => !v)}>+ <span class="v">${cur ? cur[1] : value || "—"}</span><${Icon} name="chevDown" />+ </button>+ ${open && html`<${Menu} anchor=${ref.current} width=${width} align="right" label=${label} onClose=${() => setOpen(false)}+ items=${options.map(([v, text, note]) => ({ label: text, note, cur: v === value, onSelect: () => v !== value && onChange(v) }))} />`}`;+}++export function CopyButton({ text, label = "复制" }) {+ const [done, setDone] = useState(false);+ const copy = async () => {+ try {+ await navigator.clipboard.writeText(text);+ } catch {+ const ta = document.createElement("textarea");+ ta.value = text;+ document.body.appendChild(ta);+ ta.select();+ document.execCommand("copy");+ ta.remove();+ }+ setDone(true);+ setTimeout(() => setDone(false), 1200);+ };+ return html`<button type="button" class=${`icon-btn copy${done ? " done" : ""}`} title=${done ? "已复制" : label} aria-label=${label} onClick=${copy}>+ <${Icon} name=${done ? "check" : "copy"} size=${14} />+ </button>`;+}++const STATE = {+ disabled: ["未启用", "off"], connecting: ["连接中", "warn"], connected: ["已连接", "ok"], error: ["错误", "err"], expired: ["已过期", "err"],+ paused: ["已暂停", "off"], login_required: ["未登录", "off"], running: ["运行中", "ok"], starting: ["启动中", "warn"], restarting: ["重启中", "warn"],+ failed: ["失败", "err"], stopped: ["已停止", "off"], wait: ["等待扫码", "warn"], scaned: ["已扫码", "warn"], need_verifycode: ["需验证码", "warn"],+ confirmed: ["已确认", "ok"], already_bound: ["已绑定", "ok"], cancelled: ["已取消", "off"], idle: ["空闲", "off"], fetching: ["获取中", "warn"],+ pending: ["待处理", "warn"], allowed: ["已批准", "ok"], rejected: ["已拒绝", "err"], answered: ["已回答", "ok"],+};+export const Badge = ({ s }) => {+ const [text, kind] = STATE[s] || [s, ""];+ return html`<span class=${`badge ${kind}`}>${text}</span>`;+};++/** 自绘确认框:焦点先在"取消"(安全选项),Esc 关闭,Tab 在框内循环 */+export function Sheet({ title, onClose, children, wide, label }) {+ const ref = useRef(null);+ useEffect(() => {+ const prev = document.activeElement;+ requestAnimationFrame(() => (ref.current?.querySelector("[data-autofocus]") || ref.current?.querySelector("button, input, textarea"))?.focus());+ const key = (e) => {+ if (e.key === "Escape") {+ e.stopPropagation();+ onClose();+ }+ if (e.key === "Tab" && ref.current) {+ const f = [...ref.current.querySelectorAll("button:not(:disabled), input, textarea, a[href], [tabindex='0']")];+ if (!f.length) return;+ const i = f.indexOf(document.activeElement);+ if (e.shiftKey && i <= 0) {+ e.preventDefault();+ f[f.length - 1].focus();+ } else if (!e.shiftKey && i === f.length - 1) {+ e.preventDefault();+ f[0].focus();+ }+ }+ };+ document.addEventListener("keydown", key, true);+ return () => {+ document.removeEventListener("keydown", key, true);+ prev?.focus?.({ preventScroll: true });+ };+ }, []);+ return html`<div class="scrim" onPointerDown=${(e) => e.target === e.currentTarget && onClose()}>+ <div class=${`sheet${wide ? " wide" : ""}`} ref=${ref} role="dialog" aria-modal="true" aria-label=${label || title}>+ ${title && html`<h2>${title}</h2>`}+ ${children}+ </div>+ </div>`;+}++export function DialogHost() {+ const d = useStore(dialog);+ if (!d) return null;+ const done = (v) => {+ dialog.set(null);+ d.resolve(v);+ };+ return html`<${Sheet} title=${d.title} onClose=${() => done(false)}>+ ${d.body && html`<p class="body">${d.body}</p>`}+ <div class="actions">+ <button type="button" class="btn" data-autofocus onClick=${() => done(false)}>${d.cancelLabel || "取消"}</button>+ <button type="button" class=${`btn ${d.danger ? "" : "primary"}`} style=${d.danger ? "background:var(--red);color:#fff" : ""} onClick=${() => done(true)}>${d.confirmLabel || "确定"}</button>+ </div>+ <//>`;+}++export function Toasts() {+ const list = useStore(toasts);+ return html`<div class="toasts" role="status" aria-live="polite">+ ${list.map((t) => html`<div key=${t.id} class=${`toast ${t.kind}${t.leaving ? " leaving" : ""}`}>+ <span>${t.text}</span>+ ${t.kind === "err" && html`<button type="button" class="icon-btn" style="width:18px;height:18px;color:inherit" aria-label="关闭" onClick=${() => dismissToast(t.id)}><${Icon} name="close" size=${12} /></button>`}+ </div>`)}+ </div>`;+}++export function Spinner() {+ return html`<span class="spinner" aria-hidden="true"></span>`;+}++/** 文本框随内容增高(最多 max 行) */+export function autoGrow(el, maxPx) {+ if (!el) return;+ el.style.height = "auto";+ el.style.height = Math.min(el.scrollHeight, maxPx || 9999) + "px";+}diff --git a/ui/css/avatar.css b/ui/css/avatar.cssnew file mode 100644index 0000000..3d8ed80--- /dev/null+++ b/ui/css/avatar.css@@ -0,0 +1,59 @@+/* Bot faces: static when idle (a quiet list); look-at, blink, bob and darting eyes only while working. */+.bot-face {+ --look-x: 0;+ --look-y: 0;+ --face: hsl(var(--bot-hue, 240) 46% 78%);+ --face-ink: hsl(var(--bot-hue, 240) 40% 22%);+ --eye-white: #f8f8fc;+ border-radius: 50%; flex: none; position: relative; perspective: 120px;+}+:root[data-theme="dark"] .bot-face {+ --face: hsl(var(--bot-hue, 240) 34% 38%);+ --face-ink: hsl(var(--bot-hue, 240) 60% 88%);+ --eye-white: #1c1c28;+}+.bot-face-3d { width: 100%; height: 100%; border-radius: 50%; }+.bot-face svg { display: block; width: 100%; height: 100%; overflow: visible; }+.bot-head { fill: var(--face); stroke: color-mix(in srgb, var(--face-ink) 18%, transparent); stroke-width: 1; }+.bot-eye-white { fill: var(--eye-white); transform-box: fill-box; transform-origin: center; }+.bot-pupils { transform-box: view-box; transform-origin: center; }+.bot-pupil { fill: var(--face-ink); }+.bot-mouth { stroke: var(--face-ink); stroke-width: 1.4; transition: opacity .2s ease; }+.bot-mouth-idle { fill: none; }+.bot-mouth-work { fill: var(--face-ink); stroke: none; opacity: 0; }++.bot-face.is-working .bot-mouth-idle { opacity: 0; }+.bot-face.is-working .bot-mouth-work { opacity: 1; }+.bot-face.is-working { animation: bot-bob 1.6s ease-in-out infinite; }+.bot-face.is-working .bot-face-3d {+ transform-style: preserve-3d;+ transform: translateX(calc(var(--look-x) * 1.6px)) rotateY(calc(var(--look-x) * 18deg)) rotateX(calc(var(--look-y) * -10deg - 4deg));+ transition: transform .14s ease-out;+}+.bot-face.is-working .bot-eye-white { animation: bot-eye-blink 2.4s calc(var(--bot-hue, 0) * 7ms) ease-in-out infinite; }+.bot-face.is-working .bot-pupils { animation: bot-dart 2.8s ease-in-out infinite; }+@keyframes bot-eye-blink {+ 0%, 41%, 47%, 100% { transform: scaleY(1); }+ 44% { transform: scaleY(0.08); }+}+@keyframes bot-bob {+ 0%, 100% { transform: translateY(0); }+ 50% { transform: translateY(-1.5px); }+}+@keyframes bot-dart {+ 0%, 100% { transform: translate(calc(var(--look-x) * 2.4px), calc(var(--look-y) * 2.2px)); }+ 22% { transform: translate(calc(var(--look-x) * 2.4px + 1.4px), calc(var(--look-y) * 2.2px - 0.6px)); }+ 48% { transform: translate(calc(var(--look-x) * 2.4px - 1.2px), calc(var(--look-y) * 2.2px + 0.4px)); }+ 70% { transform: translate(calc(var(--look-x) * 2.4px + 0.4px), calc(var(--look-y) * 2.2px + 1px)); }+}+@media (prefers-reduced-motion: reduce) {+ .bot-face.is-working, .bot-face.is-working .bot-eye-white, .bot-face.is-working .bot-pupils { animation: none !important; }+ .bot-face.is-working .bot-face-3d { transition: none; transform: none; }+}++/* the app's own mark (not Modelflare's or anyone else's logo) */+.app-mark {+ display: grid; place-items: center; flex: none; border-radius: 30%;+ background: var(--accent-solid); color: var(--on-accent); box-shadow: inset 0 0 0 1px var(--accent-line);+}+.app-mark svg { width: 56%; height: 56%; }diff --git a/ui/css/base.css b/ui/css/base.cssnew file mode 100644index 0000000..c558d69--- /dev/null+++ b/ui/css/base.css@@ -0,0 +1,257 @@+/* Base + shared components. .list/.row, .seg, .pop, .text and the status pill+ are adapted from yetone/magpie internal/gui/assets/app.css (MIT, © 2026 yetone). */+*, *::before, *::after { box-sizing: border-box; }+html, body { height: 100%; margin: 0; }+body {+ font: 400 13px/1.4 var(--font);+ color: var(--fg);+ background: var(--bg);+ -webkit-font-smoothing: antialiased;+ overflow: hidden;+ /* controls read as an app's: only what the window shows as content can be selected */+ user-select: none;+ -webkit-user-select: none;+}+:where(p, pre, code, td, .selectable, .msg, .notice-text, .err-text) { user-select: text; -webkit-user-select: text; }+h1, h2, h3, h4, p { margin: 0; }+button { font: inherit; color: inherit; background: none; border: 0; padding: 0; margin: 0; cursor: default; appearance: none; -webkit-appearance: none; text-align: center; }+input, textarea { font: inherit; color: inherit; }+a { color: var(--accent); text-decoration: none; }+a:hover { color: var(--accent-strong); text-decoration: underline; }+code, .mono { font-family: var(--code); font-size: 11.5px; font-variant-numeric: tabular-nums; }+.num { font-variant-numeric: tabular-nums; }+button:focus-visible, input:focus-visible, textarea:focus-visible, a:focus-visible, [tabindex]:focus-visible {+ outline: 2px solid var(--accent); outline-offset: 1px;+}+svg.ic { width: 16px; height: 16px; flex: none; display: block; }+.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }++/* —— Buttons: primary / secondary (pill) / ghost / icon / text —— */+.btn {+ display: inline-flex; align-items: center; justify-content: center; gap: 6px;+ height: 28px; padding: 0 12px; border-radius: 8px;+ font-size: 12.5px; font-weight: 500; white-space: nowrap;+ background: var(--pill); color: var(--fg);+ transition: background .12s, color .12s, transform .12s var(--ease), opacity .12s;+}+.btn:hover:not(:disabled) { background: var(--pill-hover); }+.btn:active:not(:disabled) { transform: scale(.96); }+.btn:disabled { opacity: .45; }+.btn.primary { background: var(--accent-solid); color: var(--on-accent); box-shadow: inset 0 0 0 1px var(--accent-line); }+.btn.primary:hover:not(:disabled) { background: var(--accent-hover); }+.btn.primary:active:not(:disabled) { background: var(--accent-press); }+.btn.ghost { background: transparent; color: var(--ctl-fg); }+.btn.ghost:hover:not(:disabled) { background: var(--pill); color: var(--fg); }+.btn.lg { height: 36px; font-size: 13px; border-radius: 9px; }+.btn.block { width: 100%; }+.btn .spinner { width: 14px; height: 14px; }+.icon-btn {+ width: 26px; height: 26px; border-radius: 7px; flex: none;+ display: inline-flex; align-items: center; justify-content: center;+ color: var(--muted); transition: background .12s, color .12s, transform .12s var(--ease);+}+.icon-btn:hover, .icon-btn.on { background: var(--pill); color: var(--fg); }+.icon-btn:active { transform: scale(.94); }+.text {+ font-size: 12px; color: var(--ctl-fg); padding: 3px 7px; border-radius: 6px; white-space: nowrap;+ transition: background .12s, color .12s;+}+.text:hover:not(:disabled) { background: var(--pill); color: var(--fg); }+.text:disabled { opacity: .45; }+.text.danger { color: var(--red); }+.text.danger:hover:not(:disabled) { background: var(--red-soft); color: var(--red); }+.text.accent { color: var(--accent); }+.copy.done { color: var(--green); background: var(--green-soft); animation: copy-pop .36s var(--ease); }+@keyframes copy-pop { 40% { transform: scale(1.12); } }++/* —— Inputs —— */+.field {+ width: 100%; height: 32px; padding: 0 10px;+ border: 1px solid var(--line); border-radius: 8px;+ background: var(--card); color: var(--fg); outline: none;+ transition: border-color .12s, box-shadow .12s;+}+.field::placeholder, textarea.field::placeholder { color: var(--placeholder); }+.field:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }+.field:focus-visible { outline: none; }+.field.mono { font-family: var(--code); font-size: 12.5px; }+.field.err { border-color: var(--red); }+.field.err:focus { border-color: var(--accent); }+textarea.field { height: auto; padding: 8px 10px; resize: none; line-height: 1.5; }+.field[readonly] { background: var(--card-2); }+.field-wrap { position: relative; display: flex; align-items: center; }+.field-wrap .field { padding-right: 62px; }+.field-wrap .tail { position: absolute; right: 4px; display: flex; gap: 2px; }++/* —— Badges / dots —— */+.badge {+ display: inline-flex; align-items: center; height: 20px; padding: 0 8px; border-radius: 999px;+ font-size: 11px; font-weight: 500; white-space: nowrap; flex: none;+ background: var(--pill); color: var(--fg-2);+}+.badge.ok { background: var(--green-soft); color: var(--green); }+.badge.err { background: var(--red-soft); color: var(--red); }+.badge.warn { background: var(--amber-soft); color: var(--amber); }+.badge.off { background: var(--pill); color: var(--muted); }+.badge.count { height: 18px; min-width: 18px; padding: 0 5px; justify-content: center; font-variant-numeric: tabular-nums; }+.dot { width: 7px; height: 7px; border-radius: 50%; flex: none; background: var(--faint); display: inline-block; }+.dot.ok { background: var(--green); }+.dot.err { background: var(--red); }+.dot.warn { background: var(--amber); }++/* —— List card + rows (magpie .list / .row) —— */+.list { background: var(--card); border: 1px solid var(--line); border-radius: 12px; overflow: hidden; flex: none; }+.list + .list, .list-head + .list { margin-top: 8px; }+.list-head { display: flex; align-items: center; gap: 8px; margin: 18px 2px 6px; font-size: 11px; font-weight: 600; color: var(--muted); }+.list-head:first-child { margin-top: 0; }+.list-head .grow { flex: 1; }+.row { display: flex; align-items: center; gap: 12px; min-height: 48px; padding: 7px 12px 7px 14px; }+.row + .row, .row + .row-edit, .row-edit + .row { border-top: 1px solid var(--line-2); }+.row .who { min-width: 0; flex: 1 1 auto; }+.row .name { font-weight: 500; letter-spacing: -.005em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.row .sub { font-size: 11.5px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-top: 1px; }+.row .sub.wrap { white-space: normal; }+.row .ctl { display: flex; align-items: center; gap: 4px; flex: none; }+.row .val { font-family: var(--code); font-size: 11.5px; color: var(--fg-2); max-width: 280px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; user-select: text; -webkit-user-select: text; }+.row.off > :not(.ctl) { opacity: .5; }+.row.compact { min-height: 40px; padding: 5px 9px 5px 11px; gap: 9px; }+.row.clickable:hover { background: var(--card-2); }+.row.flash { animation: row-flash 1.2s var(--ease); }+@keyframes row-flash { 0%, 35% { background: var(--sel); } }+.row-edit { padding: 12px 14px 14px; background: var(--card-2); display: grid; gap: 10px; }+.row-edit label { display: grid; gap: 5px; font-size: 11.5px; color: var(--fg-2); font-weight: 500; }+.row-edit .actions { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }+.row-edit .hint, .hint { font-size: 11.5px; color: var(--muted); line-height: 1.5; }++/* —— Segmented control (magpie .seg; the thumb wears the brand) —— */+.seg {+ position: relative; display: inline-flex; padding: 2px; border-radius: 8px;+ background: var(--seg-track); flex: none;+}+.seg > .thumb {+ position: absolute; top: 2px; left: 0; height: calc(100% - 4px); border-radius: 6px;+ background: var(--accent-solid); box-shadow: var(--seg-edge), inset 0 0 0 1px var(--accent-line);+ transition: transform .22s var(--ease), width .22s var(--ease);+}+.seg > .thumb.still { transition: none; }+.seg button {+ position: relative; z-index: 1; white-space: nowrap; height: 22px; padding: 0 10px; border-radius: 6px;+ font-size: 12px; color: var(--ctl-fg); transition: color .18s var(--ease);+}+.seg button.on { color: var(--on-accent); font-weight: 500; }+.seg button:hover:not(.on):not(:disabled) { color: var(--fg); }+.seg button:disabled { opacity: .45; }+.seg.disabled > .thumb { opacity: .5; }++/* —— Menu button (magpie .proto.pick) —— */+.pick {+ display: inline-flex; align-items: center; gap: 4px; height: 24px; max-width: 260px;+ padding: 0 6px 0 9px; border-radius: 7px; background: var(--pill); color: var(--fg);+ font-size: 12px; transition: background .12s;+}+.pick:hover:not(:disabled) { background: var(--pill-hover); }+.pick:disabled { opacity: .45; }+.pick .v { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.pick .ic { width: 12px; height: 12px; color: var(--muted); transition: transform .18s var(--ease); }+.pick[aria-expanded="true"] .ic { transform: rotate(180deg); }++/* —— Popover (magpie .pop) —— */+.pop {+ position: fixed; z-index: 40; width: 280px; max-height: 360px;+ display: flex; flex-direction: column;+ background: var(--pop-bg); -webkit-backdrop-filter: blur(24px); backdrop-filter: blur(24px);+ border-radius: 11px; box-shadow: var(--shadow); overflow: hidden;+ transform-origin: var(--ox, 24px) top;+ animation: pop-fade .18s ease-out, pop-in .42s cubic-bezier(.16, 1, .3, 1);+}+.pop.up { transform-origin: var(--ox, 24px) bottom; --pop-dy: 6px; }+@keyframes pop-fade { from { opacity: 0; } }+@keyframes pop-in { from { transform: translateY(var(--pop-dy, -6px)) scale(.94); } }+:is(.pop, .palette) .search { display: flex; align-items: center; gap: 8px; padding: 0 12px; border-bottom: 1px solid var(--line-2); color: var(--faint); flex: none; }+:is(.pop, .palette) .search input { flex: 1; min-width: 0; background: none; border: 0; outline: none; height: 38px; font-size: 13px; }+:is(.pop, .palette) .search input::placeholder { color: var(--faint); }+:is(.pop, .palette) ul { list-style: none; margin: 0; overflow-y: auto; padding: 5px; flex: 1 1 auto; }+:is(.pop, .palette) li {+ display: flex; align-items: center; gap: 9px; min-height: 30px; padding: 0 8px; border-radius: 7px;+ font-size: 12.5px; white-space: nowrap;+}+:is(.pop, .palette) li .v { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }+:is(.pop, .palette) li .n { flex: 1 1 0; min-width: 0; font-size: 11px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; }+:is(.pop, .palette) li.sel { background: var(--sel); }+:is(.pop, .palette) li.danger { color: var(--red); }+:is(.pop, .palette) li.disabled { opacity: .45; }+:is(.pop, .palette) li .check { color: var(--accent); margin-left: auto; display: none; }+:is(.pop, .palette) li.cur .check { display: inline-flex; }+:is(.pop, .palette) li.group { min-height: 22px; padding: 6px 8px 0; font-size: 10.5px; font-weight: 600; letter-spacing: .04em; color: var(--faint); pointer-events: none; }+:is(.pop, .palette) li.sep { min-height: 0; height: 1px; margin: 4px 6px; padding: 0; background: var(--line-2); pointer-events: none; }+:is(.pop, .palette) li.explained { white-space: normal; padding: 6px 8px; align-items: flex-start; flex-direction: column; gap: 1px; }+:is(.pop, .palette) .empty { padding: 14px 12px; color: var(--muted); font-size: 12.5px; text-align: center; }+:is(.pop, .palette) .foot { flex: none; border-top: 1px solid var(--line-2); padding: 5px; display: flex; }+:is(.pop, .palette) .foot button { flex: 1; height: 30px; border-radius: 7px; font-size: 12px; color: var(--ctl-fg); }+:is(.pop, .palette) .foot button:hover:not(:disabled) { background: var(--pill); color: var(--fg); }+:is(.pop, .palette) .foot button:disabled { opacity: .45; }+.pop.model-picker { width: 340px; max-height: 420px; border: 1px solid var(--line); }+.pop.model-picker li:not(.group):not(.sep) { min-height: 34px; }++/* —— Sheet (modal dialog) —— */+.scrim {+ position: fixed; inset: 0; z-index: 50; background: rgba(0, 0, 0, .28);+ display: grid; place-items: center; padding: 24px;+ animation: pop-fade .16s ease-out;+}+.sheet {+ width: min(440px, 100%); max-height: calc(100vh - 48px); overflow: auto;+ background: var(--card); border-radius: 14px; box-shadow: var(--shadow);+ padding: 18px 18px 16px; display: grid; gap: 12px;+ animation: pop-in .36s cubic-bezier(.16, 1, .3, 1);+}+.sheet.wide { width: min(640px, 100%); }+.sheet h2 { font-size: 15px; font-weight: 600; letter-spacing: -.01em; }+.sheet .body { color: var(--fg-2); line-height: 1.55; }+.sheet .actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 4px; }+.sheet pre.doc { white-space: pre-wrap; font: 11.5px/1.5 var(--code); color: var(--fg-2); margin: 0; max-height: 60vh; overflow: auto; }++/* —— Status pill ("已保存") —— */+.toasts { position: fixed; z-index: 60; left: 16px; bottom: 16px; display: grid; gap: 6px; justify-items: start; pointer-events: none; }+.toast {+ pointer-events: auto; font-size: 12.5px; line-height: 16px; font-weight: 500; padding: 4px 11px; border-radius: 999px;+ max-width: min(480px, calc(100vw - 32px));+ box-shadow: 0 6px 20px rgba(0, 0, 0, .16);+ animation: toast-in .2s var(--ease);+}+.toast.ok { background: var(--accent-solid); color: var(--on-accent); box-shadow: inset 0 0 0 1px var(--accent-line), 0 6px 20px rgba(0, 0, 0, .16); }+.toast.err { background: var(--red-soft); color: var(--red); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--red) 30%, transparent), 0 6px 20px rgba(0, 0, 0, .16); display: flex; gap: 8px; align-items: center; }+.toast.warn { background: var(--amber-soft); color: var(--amber); }+.toast.leaving { animation: toast-out .2s var(--ease) forwards; }+@keyframes toast-in { from { opacity: 0; transform: translateY(6px); } }+@keyframes toast-out { to { opacity: 0; transform: translateY(4px); } }++/* —— Notice (inline, with an action) —— */+.notice {+ display: flex; align-items: center; gap: 10px; padding: 8px 10px 8px 12px; border-radius: 10px;+ font-size: 12.5px; line-height: 1.5; background: var(--accent-soft); color: var(--fg);+ box-shadow: inset 0 0 0 1px var(--accent-line);+}+.notice .notice-text { flex: 1; min-width: 0; }+.notice.amber { background: var(--amber-soft); color: var(--amber); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--amber) 25%, transparent); }+.notice.red { background: var(--red-soft); color: var(--red); box-shadow: inset 3px 0 0 var(--red), inset 0 0 0 1px color-mix(in srgb, var(--red) 22%, transparent); }+.notice .btn { height: 24px; font-size: 12px; padding: 0 10px; background: var(--card); }+.notice .btn:hover:not(:disabled) { background: var(--card-2); }++/* —— Spinner / skeleton —— */+.spinner { width: 14px; height: 14px; border-radius: 50%; border: 2px solid currentColor; border-right-color: transparent; animation: spin .8s linear infinite; flex: none; }+@keyframes spin { to { transform: rotate(360deg); } }+.skel { height: 12px; border-radius: 6px; background: linear-gradient(90deg, var(--pill) 0%, var(--pill-hover) 50%, var(--pill) 100%); background-size: 200% 100%; animation: skel 1.2s ease-in-out infinite; }+@keyframes skel { from { background-position: 100% 0; } to { background-position: -100% 0; } }++.empty-state { padding: 32px 20px; text-align: center; color: var(--muted); }+.empty-state b { display: block; color: var(--fg); font-weight: 500; margin-bottom: 4px; }++@keyframes view-in { from { opacity: 0; transform: translateY(4px); } }+@keyframes fade-in { from { opacity: 0; } }++@media (prefers-reduced-motion: reduce) {+ *, *::before, *::after { transition-duration: .01ms !important; scroll-behavior: auto !important; }+ .pop, .sheet, .toast, .view { animation: pop-fade .12s ease-out !important; }+ .spinner { animation-duration: 1.6s; }+}diff --git a/ui/css/chat.css b/ui/css/chat.cssnew file mode 100644index 0000000..8abf81e--- /dev/null+++ b/ui/css/chat.css@@ -0,0 +1,173 @@+/* Chat: no header bar; a floating name pill, a 960 column, 560 bubbles, a floating composer. */+.chat { position: relative; flex: 1; min-height: 0; display: flex; flex-direction: column; background: var(--chat-bg); }+.drag-strip { position: absolute; z-index: 4; top: 0; left: 0; right: 0; height: 40px; -webkit-app-region: drag; pointer-events: none; }+:root.mac-app .drag-strip { pointer-events: auto; }++.float-pill {+ position: absolute; z-index: 6; top: 10px; left: 50%; transform: translateX(-50%);+ display: inline-flex; align-items: center; gap: 8px; height: 39px; max-width: min(320px, calc(100% - 32px)); min-width: 120px;+ padding: 0 16px 0 10px; border-radius: 20px;+ background: var(--card); box-shadow: var(--float-edge);+ font-size: 14px; font-weight: 500; color: var(--fg);+ -webkit-app-region: no-drag; transition: background .12s;+}+.float-pill:hover, .float-pill[aria-pressed="true"] { background: var(--card-2); }+.float-pill:active { transform: translateX(-50%) scale(.98); }+.float-pill .name { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }++.chat-scroll { flex: 1; min-height: 0; overflow-y: auto; overflow-anchor: none; }+.chat-col {+ width: min(var(--col-w), calc(100% - 48px)); margin: 0 auto;+ padding: 64px 0 96px; display: flex; flex-direction: column;+}+.msg-row { display: flex; flex-direction: column; margin-top: 16px; }+.msg-row.cont { margin-top: 6px; }+.msg-row.user { align-items: flex-end; }+.msg-row.assistant { align-items: flex-start; }+.msg {+ max-width: min(var(--bubble-w), 85%); padding: 7px 12px 8px; border-radius: 20px;+ font-size: 15px; line-height: 22.5px; word-break: break-word; overflow-wrap: anywhere;+ cursor: text;+}+.msg-row.user .msg {+ background: linear-gradient(180deg, var(--bubble-top), var(--bubble-bottom)); color: var(--on-accent);+ box-shadow: inset 0 0 0 1px var(--accent-line);+ white-space: pre-wrap;+}+.msg-row.user .msg a { color: var(--on-accent); text-decoration: underline; font-weight: 600; }+.msg-row.assistant .msg { background: var(--bubble-ai); color: var(--fg); }+.msg-row.pending .msg { opacity: .85; }+.caret { display: inline-block; width: 7px; height: 15px; margin-left: 2px; vertical-align: -2px; border-radius: 1px; background: var(--accent); animation: blink 1s steps(2) infinite; }+@keyframes blink { 50% { opacity: 0; } }+.typing { display: inline-flex; gap: 4px; padding: 8px 2px; }+.typing i { width: 6px; height: 6px; border-radius: 50%; background: var(--muted); animation: breathe 1.2s ease-in-out infinite; }+.typing i:nth-child(2) { animation-delay: .15s; }+.typing i:nth-child(3) { animation-delay: .3s; }+.msg-row.enter { animation: msg-in .18s var(--ease); }+@keyframes msg-in { from { opacity: 0; transform: translateY(6px); } }++.time-sep { align-self: center; margin: 20px 0 2px; font-size: 11.5px; color: var(--muted); }++/* markdown inside the assistant bubble */+.md > :first-child { margin-top: 0; }+.md > :last-child { margin-bottom: 0; }+.md p, .md ul, .md ol, .md blockquote, .md pre, .md table, .md h1, .md h2, .md h3, .md h4, .md hr { margin: 0 0 8px; }+.md h1, .md h2, .md h3, .md h4 { font-size: 15px; font-weight: 600; line-height: 22px; }+.md h1 { font-size: 17px; }+.md ul, .md ol { padding-left: 22px; }+.md li + li { margin-top: 2px; }+.md blockquote { padding-left: 10px; border-left: 3px solid var(--line); color: var(--fg-2); }+.md hr { border: 0; border-top: 1px solid var(--line); }+.md code { font-size: 12.5px; padding: 1px 5px; border-radius: 5px; background: color-mix(in srgb, var(--fg) 7%, transparent); }+.md a { text-decoration: underline; text-underline-offset: 2px; }+.md .table-wrap { overflow-x: auto; margin: 0 0 8px; }+.md table { border-collapse: collapse; font-size: 13.5px; line-height: 1.45; margin: 0; }+.md th, .md td { border: 1px solid var(--line); padding: 5px 9px; text-align: left; vertical-align: top; }+.md th { font-weight: 600; background: color-mix(in srgb, var(--card) 60%, transparent); }+.codeblock { margin: 0 0 8px; border-radius: 10px; background: var(--card-2); box-shadow: inset 0 0 0 1px var(--line); overflow: hidden; }+.codeblock .bar { display: flex; align-items: center; height: 28px; padding: 0 4px 0 10px; font: 11px var(--code); color: var(--muted); border-bottom: 1px solid var(--line-2); }+.codeblock .bar .lang { flex: 1; }+.codeblock pre { margin: 0; padding: 9px 12px; overflow-x: auto; font: 12.5px/1.55 var(--code); color: var(--fg); white-space: pre; }+.codeblock pre code { font-size: inherit; padding: 0; background: none; }++/* cards in the stream: ask_user / approval / file / error */+.card {+ width: min(var(--bubble-w), 100%); background: var(--card); border-radius: 22px;+ box-shadow: inset 0 0 0 1px #f2f2f2; padding: 18px 20px; display: grid; gap: 10px;+}+:root[data-theme="dark"] .card { box-shadow: inset 0 0 0 1px var(--line); }+.card .q { font-size: 14.5px; font-weight: 600; color: var(--fg); line-height: 1.45; }+.card .q-detail { font-size: 13px; color: var(--fg-2); line-height: 1.5; white-space: pre-wrap; }+.card .opts { display: grid; gap: 2px; margin: 0 -8px; }+.card .opt {+ display: flex; align-items: center; gap: 10px; min-height: 41px; padding: 4px 8px; border-radius: 12px;+ text-align: left; font-size: 15px; color: var(--fg); transition: background .12s;+}+.card .opt:hover:not(:disabled) { background: var(--side-bg); }+.card .opt .letter {+ width: 22px; height: 22px; border-radius: 7px; flex: none; display: grid; place-items: center;+ background: #f2f2f2; color: var(--muted); font-size: 12px; font-weight: 600;+}+:root[data-theme="dark"] .card .opt .letter { background: var(--pill); }+.card .opt .desc { display: block; font-size: 12px; color: var(--muted); }+.card .opt.picked .letter { background: var(--accent-solid); color: var(--on-accent); }+.card.done .q { color: #808080; }+.card.done .opt { color: var(--placeholder); }+.card .meta { display: flex; align-items: center; gap: 8px; font-size: 12px; color: var(--muted); }+.card .actions { display: flex; gap: 8px; flex-wrap: wrap; }+.card .cmd { font: 12px/1.5 var(--code); background: var(--card-2); border-radius: 8px; padding: 7px 9px; white-space: pre-wrap; word-break: break-all; color: var(--fg-2); max-height: 160px; overflow: auto; }+.card .answer { display: flex; gap: 6px; }+.file-card {+ display: flex; align-items: center; gap: 12px; width: min(353px, 100%); height: 71px; padding: 0 16px;+ background: var(--card); border-radius: 20px; box-shadow: inset 0 0 0 1px #e0e0e0, 0 1px 3px rgba(0, 0, 0, .04);+}+:root[data-theme="dark"] .file-card { box-shadow: inset 0 0 0 1px var(--line); }+.file-card .ic { width: 32px; height: 32px; color: var(--muted); }+.file-card .fname { font-size: 14.5px; font-weight: 600; color: var(--fg); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.file-card .fsub { font-size: 12px; color: var(--muted); }+.msg-row .notice { max-width: min(var(--bubble-w), 100%); }++.chat-empty { margin: auto; padding-top: 18vh; display: grid; justify-items: center; gap: 10px; text-align: center; color: var(--muted); }+.chat-empty h2 { font-size: 17px; font-weight: 600; color: var(--fg); }+.chips { display: flex; gap: 8px; flex-wrap: wrap; justify-content: center; margin-top: 6px; }+.chip { height: 30px; padding: 0 12px; border-radius: 15px; background: var(--card); box-shadow: inset 0 0 0 1px var(--line); font-size: 12.5px; color: var(--fg-2); }+.chip:hover { background: var(--card-2); color: var(--fg); }++/* —— floating "back to bottom" —— */+.to-bottom {+ position: absolute; z-index: 5; left: 50%; bottom: 67px; transform: translateX(-50%);+ width: 33px; height: 33px; border-radius: 50%; display: grid; place-items: center;+ background: var(--card); color: var(--fg); box-shadow: var(--float-edge);+ animation: fade-in .18s ease-out;+}+.to-bottom:hover { background: var(--card-2); }+.to-bottom .new { position: absolute; top: 1px; right: 1px; width: 8px; height: 8px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 0 2px var(--card); }++/* —— composer: a 44px floating capsule —— */+.composer-dock { position: absolute; z-index: 5; left: 0; right: 0; bottom: 15px; pointer-events: none; }+.composer {+ pointer-events: auto; position: relative;+ width: min(var(--col-w), calc(100% - 48px)); margin: 0 auto;+ display: flex; align-items: flex-end; gap: 6px; min-height: 44px; padding: 8px 8px 8px 10px;+ background: var(--composer-bg); border-radius: 22px;+ box-shadow: 0 1px 4px rgba(0, 0, 0, .10), 0 0 0 1px #e6e6e6;+ transition: box-shadow .12s;+}+:root[data-theme="dark"] .composer { box-shadow: 0 1px 4px rgba(0, 0, 0, .4), 0 0 0 1px var(--line); }+.composer:focus-within { box-shadow: 0 1px 4px rgba(0, 0, 0, .10), 0 0 0 1px var(--accent), 0 0 0 4px var(--accent-soft); }+.composer.drag { box-shadow: 0 0 0 2px var(--accent); }+.composer textarea {+ flex: 1; min-width: 0; border: 0; outline: none; background: transparent; resize: none;+ font-size: 15px; line-height: 22px; padding: 3px 4px 1px; max-height: calc(22px * 8 + 4px); overflow-y: auto; color: var(--fg);+}+.composer textarea::placeholder { color: var(--placeholder); }+.composer textarea:focus-visible { outline: none; }+.composer .plus {+ width: 28px; height: 28px; border-radius: 50%; flex: none; display: grid; place-items: center;+ background: #f2f2f2; color: #7a7a7a; transition: background .12s;+}+:root[data-theme="dark"] .composer .plus { background: var(--pill); color: var(--ctl-fg); }+.composer .plus:hover, .composer .plus[aria-expanded="true"] { background: var(--pill-hover); color: var(--fg); }+.composer .model-chip {+ flex: none; height: 28px; max-width: 220px; padding: 0 6px 0 9px; border-radius: 14px;+ display: inline-flex; align-items: center; gap: 3px; font-size: 12px; color: var(--muted);+ transition: background .12s, color .12s;+}+.composer .model-chip:hover, .composer .model-chip[aria-expanded="true"] { background: var(--pill); color: var(--fg); }+.composer .model-chip .v { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.composer .model-chip .ic { width: 12px; height: 12px; }+.send {+ width: 28px; height: 28px; border-radius: 50%; flex: none; display: grid; place-items: center;+ background: var(--accent-solid); color: var(--on-accent); box-shadow: inset 0 0 0 1px var(--accent-line);+ transition: background .12s, opacity .12s, transform .12s var(--ease);+}+.send:hover:not(:disabled) { background: var(--accent-hover); }+.send:active:not(:disabled) { background: var(--accent-press); transform: scale(.94); }+.send:disabled { opacity: .4; }+.send.stop { background: var(--fg); color: var(--chat-bg); box-shadow: none; }+.send.stop:hover { background: var(--fg-2); }+.composer-disabled { pointer-events: auto; width: min(var(--col-w), calc(100% - 48px)); margin: 0 auto 8px; }++@media (max-width: 1000px) {+ .chat-col, .composer, .composer-disabled { width: calc(100% - 32px); }+}diff --git a/ui/css/settings.css b/ui/css/settings.cssnew file mode 100644index 0000000..e3f75a9--- /dev/null+++ b/ui/css/settings.css@@ -0,0 +1,63 @@+/* Settings (magpie's settings page: tabs + find, white .list cards, a control per row, saved on change). */+.settings { flex: 1; min-height: 0; overflow-y: auto; background: var(--bg); }+.set-head {+ position: sticky; top: 0; z-index: 5;+ display: flex; align-items: center; gap: 10px; flex-wrap: wrap; row-gap: 6px;+ padding: 14px max(20px, calc((100% - 720px) / 2)) 10px;+ background: color-mix(in srgb, var(--bg) 92%, transparent);+ -webkit-backdrop-filter: saturate(1.6) blur(16px); backdrop-filter: saturate(1.6) blur(16px);+ -webkit-app-region: drag;+}+.set-head > * { -webkit-app-region: no-drag; }+.set-head.stuck { box-shadow: 0 1px 0 var(--line-2); }+:root.mac-app .set-head { padding-top: 16px; }+.set-title { display: flex; align-items: center; gap: 8px; width: 100%; font-size: 15px; font-weight: 600; letter-spacing: -.01em; }+.set-title .grow { flex: 1; }+.warm-tabs { display: flex; align-items: center; gap: 2px; flex-wrap: wrap; row-gap: 2px; min-width: 0; flex: 1; margin-left: -7px; }+.warm-tabs button { height: 22px; padding: 0 7px; border-radius: 6px; font-size: 11.5px; font-weight: 600; color: var(--muted); transition: color .12s, background-color .12s; white-space: nowrap; }+.warm-tabs button:hover:not(.on) { color: var(--fg-2); }+.warm-tabs button.on { color: var(--fg); background: var(--pill); }+.set-find { flex: 0 1 180px; min-width: 120px; height: 26px; padding: 0 10px; border-radius: 7px; border: 1px solid var(--line); background: var(--card); font-size: 12px; outline: none; }+.set-find:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }+.set-find::placeholder { color: var(--placeholder); }+.set-body { padding: 6px max(20px, calc((100% - 720px) / 2)) 40px; }+.set-part { margin: 14px 2px 6px; font-size: 11px; font-weight: 600; color: var(--muted); }+.set-part:first-child { margin-top: 4px; }+.set-none { margin: 18px 2px; font-size: 13px; color: var(--muted); text-align: center; }+.settings .row .sub { max-width: 440px; }+.mf-state { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--fg-2); }++/* bot settings page */+.bot-head { display: flex; align-items: center; gap: 10px; width: 100%; }+.bot-head .grow { flex: 1; min-width: 0; font-size: 15px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.inline-input { width: 220px; height: 26px; padding: 0 8px; border-radius: 7px; border: 1px solid transparent; background: var(--pill); outline: none; font-size: 12.5px; text-align: right; }+.inline-input:hover { background: var(--pill-hover); }+.inline-input:focus { border-color: var(--accent); background: var(--card); box-shadow: 0 0 0 3px var(--accent-soft); text-align: left; }+.prompt-edit { padding: 0 14px 12px; }+.prompt-edit textarea { min-height: 88px; font-size: 13px; }++/* onboarding */+.onboard { flex: 1; min-height: 0; overflow-y: auto; background: var(--bg); display: grid; justify-items: center; align-content: center; padding: 48px 16px; -webkit-app-region: drag; }+.onboard > * { -webkit-app-region: no-drag; }+.onboard-col { width: min(400px, 100%); display: grid; gap: 14px; animation: view-in .24s var(--ease); }+.onboard-hero { display: grid; justify-items: center; gap: 10px; text-align: center; margin-bottom: 6px; }+.onboard-hero h1 { font-size: 20px; font-weight: 600; letter-spacing: -.02em; }+.onboard-hero p { font-size: 13px; color: var(--muted); line-height: 1.55; }+.onboard .list { padding: 16px; display: grid; gap: 10px; }+.onboard label.k { font-size: 12px; font-weight: 600; color: var(--fg-2); }+.onboard .err-text { font-size: 12px; color: var(--red); line-height: 1.5; display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }+.onboard .slow { font-size: 12px; color: var(--muted); }+.onboard .links { display: grid; gap: 8px; justify-items: center; font-size: 12.5px; color: var(--muted); }+.onboard details { width: 100%; }+.onboard details summary { list-style: none; cursor: default; display: flex; justify-content: center; align-items: center; gap: 4px; font-size: 12px; color: var(--muted); }+.onboard details summary::-webkit-details-marker { display: none; }+.onboard details[open] summary .ic { transform: rotate(180deg); }+.onboard details .row { margin-top: 8px; background: var(--card); border: 1px solid var(--line); border-radius: 12px; }+.onboard .connected { display: flex; align-items: center; gap: 8px; font-size: 14px; font-weight: 600; }+.picklist { max-height: 300px; overflow-y: auto; margin: 0 -6px; padding: 0 6px; }+.picklist .group { padding: 8px 4px 3px; font-size: 10.5px; font-weight: 600; color: var(--faint); letter-spacing: .04em; }+.picklist button { display: flex; align-items: center; width: 100%; height: 32px; padding: 0 8px; border-radius: 7px; font-size: 12.5px; text-align: left; gap: 8px; }+.picklist button:hover { background: var(--pill); }+.picklist button.cur { background: var(--sel); }+.picklist button .v { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-variant-numeric: tabular-nums; }+.picklist button .check { color: var(--accent); }diff --git a/ui/css/shell.css b/ui/css/shell.cssnew file mode 100644index 0000000..a5c6549--- /dev/null+++ b/ui/css/shell.css@@ -0,0 +1,125 @@+/* Shell: sidebar 280 | main 1fr | info panel 320 (on demand). No top bar. */+#app { height: 100%; }+.app {+ display: grid; height: 100vh;+ grid-template-columns: var(--side-w) minmax(0, 1fr);+ background: var(--chat-bg);+}+/* "已保存" sits in the window's bottom-left corner, over the sidebar above the account button,+ so it never covers the floating composer */+.app .toasts { bottom: 68px; }+.app.with-panel { grid-template-columns: var(--side-w) minmax(0, 1fr) var(--panel-w); }+.main { position: relative; min-width: 0; min-height: 0; display: flex; flex-direction: column; }+.view { animation: view-in .24s var(--ease); }++/* —— Sidebar —— */+.side {+ min-height: 0; display: flex; flex-direction: column;+ background: var(--side-bg); border-right: 1px solid var(--side-active);+}+.side-top {+ display: flex; align-items: center; justify-content: flex-end; gap: 8px;+ height: 60px; padding: 12px 17px 0 16px; flex: none;+ -webkit-app-region: drag;+}+.side-top > * { -webkit-app-region: no-drag; }+.round-btn {+ width: 36px; height: 36px; border-radius: 50%; flex: none;+ display: inline-flex; align-items: center; justify-content: center;+ background: var(--card); color: var(--fg); box-shadow: inset 0 0 0 1px var(--line);+ transition: background .12s, transform .12s var(--ease);+}+.round-btn:hover { background: var(--card-2); }+.round-btn:active { transform: scale(.96); }+.round-btn.on { background: var(--side-active); }+.side-search { flex: 1; min-width: 0; height: 36px; border-radius: 18px; padding: 0 14px; border: 0; outline: none; background: var(--card); box-shadow: inset 0 0 0 1px var(--line); }+.side-search:focus { box-shadow: inset 0 0 0 1px var(--accent), 0 0 0 3px var(--accent-soft); }+.side-search::placeholder { color: var(--placeholder); }++.side-hero { display: grid; justify-items: center; gap: 8px; padding: 2px 16px 18px; flex: none; }+.side-hero .name { font-size: 13px; font-weight: 500; color: var(--fg); }++.side-list { flex: 1; min-height: 0; overflow-y: auto; padding: 0 12px 8px; display: grid; grid-template-columns: minmax(0, 1fr); align-content: start; gap: 4px; }+.thread {+ min-width: 0;+ display: flex; align-items: center; gap: 11px; width: 100%; height: 54px; padding: 0 9px;+ border-radius: 14px; text-align: left; position: relative;+ transition: background .12s;+}+.thread:hover { background: var(--side-hover); }+.thread.sel { background: var(--side-active); }+.thread .body { min-width: 0; flex: 1; }+.thread .title { font-size: 14px; font-weight: 600; color: var(--fg); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; line-height: 1.3; }+.thread .snip { font-size: 13px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; line-height: 1.35; }+.thread .badge.count { background: var(--amber-soft); color: var(--amber); }+.thread .avatar-wrap { position: relative; flex: none; }+.thread .working-dot {+ position: absolute; right: -1px; bottom: -1px; width: 9px; height: 9px; border-radius: 50%;+ background: var(--accent); box-shadow: 0 0 0 2px var(--side-bg);+ animation: breathe 1.4s ease-in-out infinite;+}+.thread.sel .working-dot { box-shadow: 0 0 0 2px var(--side-active); }+@keyframes breathe { 0%, 100% { opacity: .45; transform: scale(.85); } 50% { opacity: 1; transform: scale(1); } }+.thread-new { display: flex; gap: 6px; align-items: center; padding: 6px 2px 6px 4px; }+.thread-new .field { height: 34px; border-radius: 10px; }+.side-empty { margin: 12px 4px; padding: 18px 14px; border-radius: 12px; background: var(--card); box-shadow: inset 0 0 0 1px var(--line); text-align: center; display: grid; gap: 10px; justify-items: center; color: var(--muted); }++.side-foot { flex: none; display: flex; align-items: center; padding: 8px 17px 16px 16px; }+.account {+ display: flex; align-items: center; gap: 10px; min-width: 0; flex: 1; height: 44px; padding: 0 8px 0 0;+ border-radius: 22px; text-align: left; transition: background .12s;+}+.account:hover { background: var(--side-hover); }+.account.on { background: var(--side-active); }+.account .me {+ width: 36px; height: 36px; border-radius: 50%; flex: none; display: grid; place-items: center;+ background: var(--card); box-shadow: inset 0 0 0 1px var(--line); font-weight: 600; font-size: 14px; color: var(--fg-2);+}+.account .who { font-size: 14px; color: var(--fg); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }++/* macOS desktop: traffic lights live in the sidebar's top-left */+:root.mac-app .side-top { padding-left: 84px; }++/* —— Info panel —— */+.panel {+ min-height: 0; display: flex; flex-direction: column;+ background: var(--bg); border-left: 1px solid var(--line);+ animation: panel-in .24s var(--ease);+}+@keyframes panel-in { from { opacity: 0; transform: translateX(12px); } }+.panel-head {+ height: 52px; flex: none; display: flex; align-items: center; gap: 8px; padding: 0 10px 0 14px;+ -webkit-app-region: drag;+}+.panel-head > * { -webkit-app-region: no-drag; }+.panel-head .title { flex: 1; min-width: 0; font-size: 14px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.panel-body { flex: 1; overflow-y: auto; padding: 0 12px 16px; }+.panel-body .row { min-height: 44px; padding: 6px 10px 6px 12px; gap: 10px; }+.panel-body .row > .hint { flex: none; white-space: nowrap; }++.panel-scrim { display: none; }+/* narrow window: the panel overlays the chat as a drawer over a scrim */+@media (max-width: 1180px) {+ .app.with-panel { grid-template-columns: var(--side-w) minmax(0, 1fr); }+ .app.with-panel .panel {+ position: fixed; z-index: 30; top: 0; right: 0; bottom: 0; width: var(--panel-w);+ box-shadow: var(--shadow);+ }+ .panel-scrim { display: block; position: fixed; z-index: 29; inset: 0; background: rgba(0, 0, 0, .18); animation: fade-in .2s ease-out; }+}+@media (max-width: 900px) {+ :root { --side-w: 240px; }+}++/* —— Command palette —— */+.palette-scrim { position: fixed; inset: 0; z-index: 55; background: rgba(0, 0, 0, .18); animation: pop-fade .14s ease-out; }+.palette {+ position: fixed; z-index: 56; left: 50%; top: 14vh; width: min(520px, calc(100vw - 32px)); transform: translateX(-50%);+ max-height: 60vh; display: flex; flex-direction: column;+ background: var(--pop-bg); -webkit-backdrop-filter: blur(24px); backdrop-filter: blur(24px);+ border-radius: 13px; box-shadow: var(--shadow); overflow: hidden;+ animation: pop-fade .16s ease-out;+}+.palette .search input { height: 46px; font-size: 14px; }+.palette li { min-height: 36px; font-size: 13px; }+.palette li kbd { margin-left: auto; font: 11px var(--code); color: var(--muted); }diff --git a/ui/index.html b/ui/index.htmlindex a3de56c..1a17b9f 100644--- a/ui/index.html+++ b/ui/index.html@@ -3,22 +3,32 @@<head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" />- <title>anymodel bot</title>- <link rel="stylesheet" href="/amb/static/style.css" />- <script type="importmap">- { "imports": { "preact": "/amb/vendor/preact.mjs", "preact/hooks": "/amb/vendor/hooks.mjs", "htm": "/amb/vendor/htm.mjs" } }- </script>+ <title>AnyModelBot</title>+ <link rel="icon" href="data:," /><script>+ // 首帧前解析主题(data-theme 总是 light/dark,CSS 只定义一份深色变量)与平台(function () {- try {- var m = localStorage.getItem("amb-theme");- if (m === "light" || m === "dark") document.documentElement.setAttribute("data-theme", m);- } catch (_) {}+ var root = document.documentElement;+ var m = "system";+ try { m = localStorage.getItem("amb-theme") || "system"; } catch (_) {}+ var dark = m === "dark" || (m !== "light" && window.matchMedia("(prefers-color-scheme: dark)").matches);+ root.setAttribute("data-theme", dark ? "dark" : "light");+ if (/Windows/.test(navigator.userAgent)) root.classList.add("win");+ if (/Electron/.test(navigator.userAgent) && /Mac/.test(navigator.platform)) root.classList.add("mac-app");})();</script>+ <link rel="stylesheet" href="/amb/static/tokens.css" />+ <link rel="stylesheet" href="/amb/static/css/base.css" />+ <link rel="stylesheet" href="/amb/static/css/shell.css" />+ <link rel="stylesheet" href="/amb/static/css/avatar.css" />+ <link rel="stylesheet" href="/amb/static/css/chat.css" />+ <link rel="stylesheet" href="/amb/static/css/settings.css" />+ <script type="importmap">+ { "imports": { "preact": "/amb/vendor/preact.mjs", "preact/hooks": "/amb/vendor/hooks.mjs", "htm": "/amb/vendor/htm.mjs" } }+ </script></head><body>- <div id="app">加载中…</div>- <script type="module" src="/amb/static/app.js"></script>+ <div id="app"></div>+ <script type="module" src="/amb/static/main.js"></script></body></html>diff --git a/ui/lib/api.js b/ui/lib/api.jsnew file mode 100644index 0000000..68f4528--- /dev/null+++ b/ui/lib/api.js@@ -0,0 +1,91 @@+// 本机后端接口:JSON 请求 + 流式对话(POST + text/event-stream,EventSource 不支持 POST)。+export class ApiError extends Error {+ constructor(message, status, data) {+ super(message);+ this.status = status;+ this.data = data || {};+ }+}++export async function api(path, opts = {}) {+ const res = await fetch("/amb/api" + path, {+ method: opts.method || "GET",+ headers: opts.body !== undefined ? { "content-type": "application/json" } : {},+ body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,+ signal: opts.signal,+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) throw new ApiError(data.error || `HTTP ${res.status}`, res.status, data);+ return data;+}++/** 按空行切事件;回调 (event, data)。 */+export function sseParser(onEvent) {+ let buf = "";+ let event = "message";+ let data = [];+ const line = (l) => {+ if (l === "") {+ if (data.length) {+ let parsed;+ try {+ parsed = JSON.parse(data.join("\n"));+ } catch {+ parsed = data.join("\n");+ }+ onEvent(event, parsed);+ }+ event = "message";+ data = [];+ return;+ }+ if (l.startsWith(":")) return;+ if (l.startsWith("event:")) event = l.slice(6).trim();+ else if (l.startsWith("data:")) data.push(l.slice(5).replace(/^ /, ""));+ };+ return {+ push(text) {+ buf += text;+ let i;+ while ((i = buf.search(/\r?\n/)) >= 0) {+ const l = buf.slice(0, i);+ buf = buf.slice(i + (buf[i] === "\r" ? 2 : 1));+ line(l);+ }+ },+ end() {+ if (buf) line(buf);+ buf = "";+ line("");+ },+ };+}++/** 流式对话。返回 Promise(结束或中止时 resolve)。handlers: text/typing/prompt/file/done/error */+export async function streamChat(botId, text, handlers, signal) {+ const res = await fetch(`/amb/api/bots/${encodeURIComponent(botId)}/chat/stream`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ text }),+ signal,+ });+ if (!res.ok || !res.body) {+ const data = await res.json().catch(() => ({}));+ throw new ApiError(data.error || `HTTP ${res.status}`, res.status, data);+ }+ const parser = sseParser((ev, data) => handlers[ev]?.(data));+ const reader = res.body.getReader();+ const dec = new TextDecoder();+ try {+ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ parser.push(dec.decode(value, { stream: true }));+ }+ parser.push(dec.decode());+ parser.end();+ } catch (e) {+ if (e.name === "AbortError") return;+ throw e;+ }+}diff --git a/ui/lib/format.js b/ui/lib/format.jsnew file mode 100644index 0000000..29f72fe--- /dev/null+++ b/ui/lib/format.js@@ -0,0 +1,30 @@+// 时间与数量的中文显示。+const pad = (n) => String(n).padStart(2, "0");+const hm = (d) => `${pad(d.getHours())}:${pad(d.getMinutes())}`;++/** 消息流里的时间分隔条:"今天 15:33" / "昨天 09:10" / "10月26日 14:00" / "2025年3月1日 08:00" */+export function fmtSep(t) {+ const d = new Date(t);+ const now = new Date();+ const day = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();+ const diff = Math.round((day(now) - day(d)) / 86_400_000);+ if (diff === 0) return `今天 ${hm(d)}`;+ if (diff === 1) return `昨天 ${hm(d)}`;+ if (d.getFullYear() === now.getFullYear()) return `${d.getMonth() + 1}月${d.getDate()}日 ${hm(d)}`;+ return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日 ${hm(d)}`;+}++/** 列表里的相对时间:"刚刚" / "5 分钟前" / "15:33" / "10月26日" */+export function fmtAgo(t) {+ if (!t) return "";+ const s = (Date.now() - t) / 1000;+ if (s < 60) return "刚刚";+ if (s < 3600) return `${Math.floor(s / 60)} 分钟前`;+ const d = new Date(t);+ if (new Date().toDateString() === d.toDateString()) return hm(d);+ return `${d.getMonth() + 1}月${d.getDate()}日`;+}++export function fmtTime(t) {+ return t ? new Date(t).toLocaleString("zh-CN", { hour12: false }) : "";+}diff --git a/ui/lib/markdown.js b/ui/lib/markdown.jsnew file mode 100644index 0000000..1eac9df--- /dev/null+++ b/ui/lib/markdown.js@@ -0,0 +1,356 @@+// 助手消息的 Markdown 子集 → 纯数据 AST(不产出 HTML 字符串)。+// 渲染层用 h() 把 AST 变成节点,文本永远是文本节点,所以不需要另做 HTML 清洗;+// 唯一会进入属性的是链接地址,只放行 http(s): 与 mailto:(safeHref)。+// 支持:段落(软换行保留)、# 标题、``` 代码块(流式中未闭合也按代码块显示)、- / 1. 列表(可嵌套)、+// > 引用、GFM 表格、分隔线;行内:`code`、**粗**、*斜*、~~删~~、[文字](链接)、<链接>、裸链接、\ 转义。++const FENCE = /^ {0,3}(`{3,}|~{3,})\s*([^`\s]*)[^`]*$/;+const HEADING = /^ {0,3}(#{1,6})(?:\s+(.*?))?\s*#*\s*$/;+const HR = /^ {0,3}([-*_])(?:\s*\1){2,}\s*$/;+const QUOTE = /^ {0,3}>\s?/;+const LIST = /^( *)([-*+]|\d{1,9}[.)])\s+(.*)$/;+const TABLE_SEP = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;++export function safeHref(url) {+ const u = String(url ?? "").trim().replace(/^<|>$/g, "");+ if (!u || /[\s\u0000-\u001f\u007f]/.test(u)) return null;+ return /^(https?:\/\/|mailto:)/i.test(u) ? u : null;+}++function startsBlock(line, next) {+ return FENCE.test(line) || (HEADING.test(line) && /^ {0,3}#{1,6}(\s|$)/.test(line)) || HR.test(line) || QUOTE.test(line) || LIST.test(line) || isTableStart(line, next);+}++function isTableStart(line, next) {+ return line.includes("|") && next !== undefined && TABLE_SEP.test(next) && next.includes("-");+}++function splitRow(line) {+ let s = line.trim();+ if (s.startsWith("|")) s = s.slice(1);+ if (s.endsWith("|") && !s.endsWith("\\|")) s = s.slice(0, -1);+ const cells = [];+ let cur = "";+ for (let i = 0; i < s.length; i++) {+ if (s[i] === "\\" && s[i + 1] === "|") {+ cur += "|";+ i++;+ } else if (s[i] === "|") {+ cells.push(cur.trim());+ cur = "";+ } else cur += s[i];+ }+ cells.push(cur.trim());+ return cells;+}++export function parseMarkdown(src) {+ const lines = String(src ?? "").replace(/\r\n?/g, "\n").split("\n");+ return parseLines(lines, 0);+}++function parseLines(lines, depth) {+ const out = [];+ let i = 0;+ while (i < lines.length) {+ const line = lines[i];+ if (!line.trim()) {+ i++;+ continue;+ }+ const fence = FENCE.exec(line);+ if (fence) {+ const mark = fence[1];+ const body = [];+ i++;+ let open = true;+ while (i < lines.length) {+ const l = lines[i];+ if (new RegExp(`^ {0,3}${mark[0] === "`" ? "`" : "~"}{${mark.length},}\\s*$`).test(l)) {+ open = false;+ i++;+ break;+ }+ body.push(l);+ i++;+ }+ out.push({ t: "code", lang: fence[2] || "", text: body.join("\n"), open });+ continue;+ }+ const hd = HEADING.exec(line);+ if (hd && /^ {0,3}#{1,6}(\s|$)/.test(line)) {+ out.push({ t: "h", level: hd[1].length, c: parseInline(hd[2] || "") });+ i++;+ continue;+ }+ if (HR.test(line)) {+ out.push({ t: "hr" });+ i++;+ continue;+ }+ if (isTableStart(line, lines[i + 1])) {+ const head = splitRow(line);+ const align = splitRow(lines[i + 1]).map((c) => (c.startsWith(":") && c.endsWith(":") ? "center" : c.endsWith(":") ? "right" : c.startsWith(":") ? "left" : ""));+ i += 2;+ const rows = [];+ while (i < lines.length && lines[i].trim() && lines[i].includes("|")) {+ const cells = splitRow(lines[i]);+ rows.push(head.map((_, k) => parseInline(cells[k] ?? "")));+ i++;+ }+ out.push({ t: "table", head: head.map((c) => parseInline(c)), align: head.map((_, k) => align[k] || ""), rows });+ continue;+ }+ if (QUOTE.test(line)) {+ const inner = [];+ while (i < lines.length && lines[i].trim() && QUOTE.test(lines[i])) {+ inner.push(lines[i].replace(QUOTE, ""));+ i++;+ }+ out.push({ t: "quote", c: depth < 6 ? parseLines(inner, depth + 1) : [{ t: "p", c: [inner.join("\n")] }] });+ continue;+ }+ const li = LIST.exec(line);+ if (li) {+ const ordered = /\d/.test(li[2]);+ const indent = li[1].length;+ const items = [];+ let cur = null;+ while (i < lines.length) {+ const l = lines[i];+ const m = LIST.exec(l);+ if (m && m[1].length <= indent + 1 && /\d/.test(m[2]) === ordered) {+ cur = { first: [m[3]], sub: [] };+ items.push(cur);+ i++;+ continue;+ }+ if (!l.trim()) {+ // 列表项之间的空行:后面还是同一列表才继续+ const n = lines[i + 1];+ const nm = n !== undefined ? LIST.exec(n) : null;+ if ((nm && nm[1].length <= indent + 1 && /\d/.test(nm[2]) === ordered) || (n !== undefined && /^ {2,}\S/.test(n))) {+ i++;+ continue;+ }+ break;+ }+ if (/^ {2,}/.test(l) && (LIST.test(l) || cur.sub.length)) {+ cur.sub.push(l.replace(new RegExp(`^ {0,${indent + 4}}`), ""));+ i++;+ continue;+ }+ if (m || startsBlock(l, lines[i + 1])) break;+ // 懒续行+ if (cur.sub.length) cur.sub.push(l.trim());+ else cur.first.push(l.trim());+ i++;+ }+ out.push({+ t: ordered ? "ol" : "ul",+ start: ordered ? parseInt(li[2], 10) : undefined,+ items: items.map((it) => ({ c: parseInline(it.first.join("\n")), sub: it.sub.length && depth < 6 ? parseLines(it.sub, depth + 1) : [] })),+ });+ continue;+ }+ const para = [line];+ i++;+ while (i < lines.length && lines[i].trim() && !startsBlock(lines[i], lines[i + 1])) {+ para.push(lines[i]);+ i++;+ }+ out.push({ t: "p", c: parseInline(para.map((l) => l.replace(/^ {0,3}/, "")).join("\n")) });+ }+ return out;+}++const PUNCT = /[!-/:-@[-`{-~]/;+const TRAIL = /[.,;:!?。,、;:!?'"”’)】》]+$/;++function bareUrl(s, i) {+ const m = /^https?:\/\/[^\s<>"'`,。;、()【】《》“”]+/i.exec(s.slice(i));+ if (!m) return null;+ let url = m[0].replace(TRAIL, "");+ // 末尾 ) 只在括号成对时保留+ while (url.endsWith(")") && (url.match(/\(/g) || []).length < (url.match(/\)/g) || []).length) url = url.slice(0, -1);+ return url.length > 8 ? url : null;+}++function findClose(s, from, mark) {+ for (let j = from; j < s.length; j++) {+ if (s[j] === "\\") {+ j++;+ continue;+ }+ if (s[j] === "`") {+ const run = /^`+/.exec(s.slice(j))[0];+ const end = s.indexOf(run, j + run.length);+ if (end > -1) j = end + run.length - 1;+ continue;+ }+ if (s.startsWith(mark, j)) {+ if (mark.length === 1 && s[j + 1] === mark) {+ j++;+ continue;+ }+ if (j > from && !/\s/.test(s[j - 1])) return j;+ }+ }+ return -1;+}++function matchLink(s, i) {+ let depth = 0;+ let j = i;+ for (; j < s.length; j++) {+ if (s[j] === "\\") {+ j++;+ continue;+ }+ if (s[j] === "[") depth++;+ else if (s[j] === "]" && --depth === 0) break;+ else if (s[j] === "\n" && s[j + 1] === "\n") return null;+ }+ if (j >= s.length || s[j + 1] !== "(") return null;+ let k = j + 2;+ let paren = 0;+ for (; k < s.length; k++) {+ if (s[k] === "(") paren++;+ else if (s[k] === ")") {+ if (paren === 0) break;+ paren--;+ } else if (s[k] === "\n") return null;+ }+ if (k >= s.length) return null;+ const inner = s.slice(j + 2, k).trim();+ const url = inner.replace(/\s+("[^"]*"|'[^']*')$/, "");+ return { text: s.slice(i + 1, j), url, end: k + 1 };+}++export function parseInline(src) {+ const s = String(src ?? "");+ const out = [];+ let text = "";+ const flush = () => {+ if (text) out.push(text);+ text = "";+ };+ let i = 0;+ while (i < s.length) {+ const ch = s[i];+ if (ch === "\\" && i + 1 < s.length && PUNCT.test(s[i + 1])) {+ text += s[i + 1];+ i += 2;+ continue;+ }+ if (ch === "\n") {+ flush();+ out.push({ t: "br" });+ i++;+ continue;+ }+ if (ch === "`") {+ const run = /^`+/.exec(s.slice(i))[0];+ const end = s.indexOf(run, i + run.length);+ if (end > -1 && s[end + run.length] !== "`") {+ flush();+ let code = s.slice(i + run.length, end).replace(/\n/g, " ");+ if (/^ .*[^ ].* $/.test(code)) code = code.slice(1, -1);+ out.push({ t: "code", text: code });+ i = end + run.length;+ continue;+ }+ text += run;+ i += run.length;+ continue;+ }+ if (ch === "[") {+ const m = matchLink(s, i);+ if (m) {+ flush();+ const href = safeHref(m.url);+ if (href) out.push({ t: "a", href, c: parseInline(m.text) });+ else out.push(...parseInline(m.text));+ i = m.end;+ continue;+ }+ }+ if (ch === "<") {+ const m = /^<((?:https?:\/\/|mailto:)[^\s<>]+)>/i.exec(s.slice(i));+ if (m) {+ flush();+ const href = safeHref(m[1]);+ if (href) out.push({ t: "a", href, c: [m[1]] });+ else text += m[0];+ i += m[0].length;+ continue;+ }+ }+ if ((ch === "h" || ch === "H") && (i === 0 || !/[A-Za-z0-9/]/.test(s[i - 1]))) {+ const url = bareUrl(s, i);+ if (url) {+ flush();+ out.push({ t: "a", href: url, c: [url] });+ i += url.length;+ continue;+ }+ }+ if (ch === "*" || ch === "_" || ch === "~") {+ const two = s.startsWith(ch + ch, i);+ if (ch === "~" && !two) {+ text += ch;+ i++;+ continue;+ }+ // 下划线只在词边界起止,避免 snake_case 被当成斜体+ if (ch === "_" && i > 0 && /[\p{L}\p{N}]/u.test(s[i - 1])) {+ text += ch;+ i++;+ continue;+ }+ const mark = two ? ch + ch : ch;+ const from = i + mark.length;+ if (from < s.length && !/\s/.test(s[from])) {+ const end = findClose(s, from, mark);+ if (end > -1 && !(ch === "_" && /[\p{L}\p{N}]/u.test(s[end + mark.length] || ""))) {+ flush();+ const kind = ch === "~" ? "s" : two ? "b" : "i";+ out.push({ t: kind, c: parseInline(s.slice(from, end)) });+ i = end + mark.length;+ continue;+ }+ }+ text += mark;+ i += mark.length;+ continue;+ }+ text += ch;+ i++;+ }+ flush();+ return out;+}++/** 用户消息:原样显示,只把链接变成可点的 */+export function linkify(src) {+ const s = String(src ?? "");+ const out = [];+ let text = "";+ let i = 0;+ while (i < s.length) {+ if ((s[i] === "h" || s[i] === "H") && (i === 0 || !/[A-Za-z0-9/]/.test(s[i - 1]))) {+ const url = bareUrl(s, i);+ if (url) {+ if (text) out.push(text);+ text = "";+ out.push({ t: "a", href: url, c: [url] });+ i += url.length;+ continue;+ }+ }+ text += s[i];+ i++;+ }+ if (text) out.push(text);+ return out;+}diff --git a/ui/lib/store.js b/ui/lib/store.jsnew file mode 100644index 0000000..1148ac6--- /dev/null+++ b/ui/lib/store.js@@ -0,0 +1,48 @@+// 极小的全局状态:toast、确认框、主题。组件用 useStore 订阅。+import { useEffect, useState } from "preact/hooks";++export function createStore(initial) {+ let value = initial;+ const subs = new Set();+ return {+ get: () => value,+ set(next) {+ value = typeof next === "function" ? next(value) : next;+ for (const fn of subs) fn(value);+ },+ subscribe(fn) {+ subs.add(fn);+ return () => subs.delete(fn);+ },+ };+}++export function useStore(store) {+ const [v, setV] = useState(store.get());+ useEffect(() => store.subscribe(setV), [store]);+ return v;+}++// —— toasts ——+export const toasts = createStore([]);+let toastSeq = 0;+/** 成功提示 1.6 秒后淡出;错误提示一直留着,直到点掉 */+export function toast(text, kind = "ok") {+ const id = ++toastSeq;+ toasts.set((l) => [...l.filter((t) => !(t.kind === kind && t.text === text)), { id, text, kind }]);+ if (kind !== "err") setTimeout(() => dismissToast(id), 1600);+ return id;+}+export function dismissToast(id) {+ toasts.set((l) => l.map((t) => (t.id === id ? { ...t, leaving: true } : t)));+ setTimeout(() => toasts.set((l) => l.filter((t) => t.id !== id)), 200);+}+export const saved = () => toast("已保存");+export const failed = (e) => toast(typeof e === "string" ? e : e?.message || "出错了", "err");++// —— confirm sheet ——+export const dialog = createStore(null);+/** confirm({ title, body, confirmLabel, danger }) → Promise<boolean> */+export function confirmSheet(opts) {+ return new Promise((resolve) => dialog.set({ ...opts, resolve }));+}diff --git a/ui/lib/theme.js b/ui/lib/theme.jsnew file mode 100644index 0000000..fa623b3--- /dev/null+++ b/ui/lib/theme.js@@ -0,0 +1,35 @@+// 外观:跟随系统 / 浅色 / 深色。<html data-theme> 总是解析后的值,CSS 只需定义一份深色变量。+import { createStore } from "./store.js";++const KEY = "amb-theme";+const mq = window.matchMedia("(prefers-color-scheme: dark)");++function readMode() {+ try {+ const m = localStorage.getItem(KEY);+ return m === "light" || m === "dark" ? m : "system";+ } catch {+ return "system";+ }+}++export const themeMode = createStore(readMode());++function apply(mode) {+ const resolved = mode === "system" ? (mq.matches ? "dark" : "light") : mode;+ document.documentElement.setAttribute("data-theme", resolved);+}++export function setThemeMode(mode) {+ try {+ if (mode === "system") localStorage.removeItem(KEY);+ else localStorage.setItem(KEY, mode);+ } catch {+ /* 隐私模式等:只在本次生效 */+ }+ themeMode.set(mode);+ apply(mode);+}++mq.addEventListener?.("change", () => apply(themeMode.get()));+apply(themeMode.get());diff --git a/ui/main.js b/ui/main.jsnew file mode 100644index 0000000..a436cc7--- /dev/null+++ b/ui/main.js@@ -0,0 +1,305 @@+// AnyModelBot 界面:Preact + htm,无构建步骤(原生 ES 模块)。+// 未连接 Modelflare → 整页引导;已连接 → 侧栏 + 对话(信息面板按需),设置与机器人设置占满主区。+import { render } from "preact";+import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";+import { html, Icon, DialogHost, Toasts } from "./components/ui.js";+import { Sidebar } from "./screens/sidebar.js";+import { ChatScreen } from "./screens/chat.js";+import { InfoPanel } from "./screens/info-panel.js";+import { SettingsScreen, TABS } from "./screens/settings.js";+import { BotSettingsScreen } from "./screens/bot-settings.js";+import { Onboarding } from "./screens/onboarding.js";+import { api } from "./lib/api.js";+import { setThemeMode } from "./lib/theme.js";+import { failed } from "./lib/store.js";++// —— 路由:#/chat/<bot> · #/settings/<tab>[/<row>] · #/bot/<bot>/settings[/<section>] ——+function parseHash() {+ const [kind, a, b, c] = location.hash.replace(/^#\/?/, "").split("/").map((x) => decodeURIComponent(x || ""));+ if (kind === "settings") return { view: "settings", tab: TABS.some(([t]) => t === a) ? a : "general", row: b || "" };+ if (kind === "bot" && a && b === "settings") return { view: "bot-settings", botId: a, section: c || "" };+ if (kind === "models") return { view: "settings", tab: "modelflare", row: "" }; // 旧链接+ return { view: "chat", botId: kind === "chat" ? a : "" };+}+const go = (path) => {+ if (location.hash !== "#" + path) location.hash = path;+};++const isMac = /Mac|iPhone|iPad/.test(navigator.platform);+const mod = (e) => (isMac ? e.metaKey : e.ctrlKey);++function readLastBot() {+ try {+ return localStorage.getItem("amb-bot") || "";+ } catch {+ return "";+ }+}++function useLoader(fn, deps = []) {+ const [data, setData] = useState(null);+ const [err, setErr] = useState("");+ const load = useCallback(+ () =>+ fn()+ .then((d) => {+ setData(d);+ setErr("");+ return d;+ })+ .catch((e) => {+ setErr(e.message);+ }),+ deps,+ );+ useEffect(() => {+ load();+ }, [load]);+ return [data, err, load, setData];+}++function useInterval(fn, ms, active = true) {+ const saved = useRef(fn);+ saved.current = fn;+ useEffect(() => {+ if (!active) return;+ const t = setInterval(() => document.visibilityState === "visible" && saved.current(), ms);+ return () => clearInterval(t);+ }, [ms, active]);+}++// —— 命令面板(⌘/Ctrl+K)——+function Palette({ commands, onClose }) {+ const [q, setQ] = useState("");+ const [sel, setSel] = useState(0);+ const ref = useRef(null);+ const input = useRef(null);+ useEffect(() => input.current?.focus(), []);+ const needle = q.trim().toLowerCase();+ const hits = commands.filter((c) => !needle || `${c.label} ${c.keys || ""}`.toLowerCase().includes(needle));+ const run = (c) => {+ onClose();+ c.run();+ };+ const onKey = (e) => {+ if (e.key === "ArrowDown") {+ e.preventDefault();+ setSel((s) => Math.min(hits.length - 1, s + 1));+ } else if (e.key === "ArrowUp") {+ e.preventDefault();+ setSel((s) => Math.max(0, s - 1));+ } else if (e.key === "Enter" && hits[sel]) {+ e.preventDefault();+ run(hits[sel]);+ } else if (e.key === "Escape") {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ }+ requestAnimationFrame(() => ref.current?.querySelector("li.sel")?.scrollIntoView({ block: "nearest" }));+ };+ return html`<div class="palette-scrim" onPointerDown=${onClose}></div>+ <div class="palette" role="dialog" aria-modal="true" aria-label="命令面板">+ <div class="search"><${Icon} name="search" />+ <input ref=${input} placeholder="输入命令或机器人名称" aria-label="命令" value=${q} onInput=${(e) => { setQ(e.target.value); setSel(0); }} onKeyDown=${onKey} />+ </div>+ <ul role="listbox" ref=${ref}>+ ${hits.map((c, i) => html`<li role="option" aria-selected=${i === sel} class=${i === sel ? "sel" : ""} onPointerMove=${() => setSel(i)} onClick=${() => run(c)}>+ <span class="v">${c.label}</span>${c.kbd && html`<kbd>${c.kbd}</kbd>`}+ </li>`)}+ ${!hits.length && html`<li class="group" style="pointer-events:none">没有匹配的命令</li>`}+ </ul>+ </div>`;+}++function App() {+ const [route, setRoute] = useState(parseHash);+ const [mf, mfErr, reloadMf] = useLoader(() => api("/modelflare"));+ const [status, , reloadStatus] = useLoader(() => api("/status"));+ const [settings, , reloadSettings, setSettings] = useLoader(() => api("/settings"));+ const connected = !!(mf && (mf.mode === "external" || mf.connected));+ const [botsData, botsErr, reloadBots] = useLoader(() => (connected ? api("/bots") : Promise.resolve(null)), [connected]);+ const [modelsData, , loadModels] = useLoader(() => (connected ? api("/models") : Promise.resolve(null)), [connected]);+ const [previews, setPreviews] = useState({});+ const [pending, setPending] = useState({});+ const [agentWorking, setAgentWorking] = useState({});+ const [localWorking, setLocalWorking] = useState({});+ const [infoOpen, setInfoOpen] = useState(false);+ const [palette, setPalette] = useState(false);+ const [creating, setCreating] = useState(false);+ const [lastBot, setLastBot] = useState(readLastBot);++ useEffect(() => {+ const on = () => setRoute(parseHash());+ window.addEventListener("hashchange", on);+ return () => window.removeEventListener("hashchange", on);+ }, []);++ const bots = botsData ? botsData.bots : null;+ const wanted = route.botId || lastBot;+ const bot = bots && (bots.find((b) => b.id === wanted) || bots[0]);+ useEffect(() => {+ if (!bot) return;+ try {+ localStorage.setItem("amb-bot", bot.id);+ } catch {+ /* ignore */+ }+ }, [bot && bot.id]);++ const models = modelsData ? modelsData.models : null;+ const modelsError = modelsData && modelsData.error ? modelsData.error : "";+ const reloadModels = () =>+ api("/models")+ .then((d) => {+ loadModels();+ return d;+ })+ .catch(failed);++ // 侧栏的预览、待审批数与"工作中"+ const pollSide = useCallback(() => {+ if (!connected) return;+ api("/conversations")+ .then((d) => {+ const latest = {};+ for (const c of d.conversations || []) if (!latest[c.botId] || c.updatedAt > latest[c.botId].updatedAt) latest[c.botId] = c;+ setPreviews(Object.fromEntries(Object.entries(latest).map(([k, c]) => [k, (c.lastMessage || "").replace(/\s+/g, " ")])));+ })+ .catch(() => {});+ api("/approvals?status=pending")+ .then((d) => {+ const n = {};+ for (const a of d.approvals || []) n[a.botId] = (n[a.botId] || 0) + 1;+ setPending(n);+ })+ .catch(() => {});+ }, [connected]);+ useEffect(pollSide, [pollSide]);+ useInterval(pollSide, 6000, connected);+ useInterval(+ () =>+ api("/agent")+ .then((a) => {+ const map = {};+ for (const [id, h] of Object.entries(a.hosts || {})) map[id] = Number(h.activeTurns || 0) > 0;+ setAgentWorking(map);+ })+ .catch(() => {}),+ 3000,+ connected,+ );+ const working = useMemo(() => {+ const m = { ...agentWorking };+ for (const [k, v] of Object.entries(localWorking)) if (v) m[k] = true;+ return m;+ }, [agentWorking, localWorking]);+ const onWorking = useCallback((id, on) => {+ setLocalWorking((w) => (w[id] === on ? w : { ...w, [id]: on }));+ if (!on) setTimeout(pollSide, 300);+ }, [pollSide]);++ const openSettings = (tab = route.view === "settings" ? route.tab : "general", row = "") => {+ reloadStatus();+ go(`/settings/${tab}${row ? "/" + row : ""}`);+ };+ const openChat = (id) => {+ if (id) setLastBot(id);+ go(`/chat/${encodeURIComponent(id || (bot && bot.id) || "")}`);+ };+ const openBotSettings = (id, section = "") => go(`/bot/${encodeURIComponent(id)}/settings${section ? "/" + section : ""}`);+ const onBotUpdated = () => reloadBots();+ const onDeleted = (id) => {+ reloadBots();+ if (bot && id === bot.id) {+ setLastBot("");+ go("/chat/");+ }+ };++ // —— 全局快捷键 ——+ useEffect(() => {+ const key = (e) => {+ if (!connected) return;+ if (mod(e) && e.key.toLowerCase() === "k") {+ e.preventDefault();+ setPalette((v) => !v);+ } else if (mod(e) && e.key === ",") {+ e.preventDefault();+ openSettings();+ } else if (mod(e) && e.shiftKey && e.key.toLowerCase() === "i") {+ e.preventDefault();+ if (route.view === "chat") setInfoOpen((v) => !v);+ } else if (mod(e) && !e.shiftKey && e.key.toLowerCase() === "n") {+ e.preventDefault();+ setCreating(true);+ } else if (e.key === "Escape" && !e.defaultPrevented) {+ const t = e.target;+ const typing = t && (t.tagName === "TEXTAREA" || t.tagName === "INPUT");+ if (route.view === "bot-settings" && !typing) openChat(route.botId);+ else if (route.view === "settings" && !typing) openChat();+ else if (route.view === "chat" && infoOpen && !typing) setInfoOpen(false);+ }+ };+ window.addEventListener("keydown", key);+ return () => window.removeEventListener("keydown", key);+ }, [connected, route, infoOpen, bot && bot.id]);++ const commands = [+ { label: "打开设置", kbd: isMac ? "⌘," : "Ctrl+,", keys: "settings preferences", run: () => openSettings() },+ { label: "新建机器人", kbd: isMac ? "⌘N" : "Ctrl+N", keys: "new bot", run: () => setCreating(true) },+ ...(route.view === "chat" ? [{ label: infoOpen ? "关闭信息面板" : "打开信息面板", kbd: isMac ? "⌘⇧I" : "Ctrl+Shift+I", keys: "info panel", run: () => setInfoOpen((v) => !v) }] : []),+ ...(bot ? [{ label: `「${bot.name}」的设置`, keys: "bot settings", run: () => openBotSettings(bot.id) }] : []),+ { label: "Modelflare 设置", keys: "modelflare key 密钥 模型", run: () => openSettings("modelflare") },+ { label: "外观:跟随系统", keys: "theme appearance 主题", run: () => setThemeMode("system") },+ { label: "外观:浅色", keys: "theme light 主题", run: () => setThemeMode("light") },+ { label: "外观:深色", keys: "theme dark 主题", run: () => setThemeMode("dark") },+ ...(bots || []).map((b) => ({ label: `切换到「${b.name}」`, keys: "bot switch " + b.id, run: () => openChat(b.id) })),+ ];++ // —— 渲染 ——+ if (!mf) {+ return html`<main class="onboard" data-screen=${mfErr ? "error" : "loading"}>+ ${mfErr ? html`<div class="onboard-col"><div class="notice red"><span class="notice-text">无法连接本机服务:${mfErr}</span><button type="button" class="btn" onClick=${reloadMf}>重试</button></div></div>` : html`<span class="spinner" style="color:var(--muted)"></span>`}+ </main>`;+ }+ if (!connected) {+ return html`<${Onboarding} status=${mf} gateway=${status && status.gateway} defaultModel=${settings && settings.defaultModel}+ onDone=${() => { reloadMf(); reloadSettings(); go("/chat/"); }} />+ <${Toasts} />`;+ }++ const view = route.view;+ const panelBot = view === "chat" && infoOpen && bot;+ const routedBot = view === "bot-settings" && bots ? bots.find((b) => b.id === route.botId) : null;+ return html`<div class=${`app${panelBot ? " with-panel" : ""}`}>+ <${Sidebar} bots=${bots} botsError=${botsErr} reloadBots=${reloadBots} selectedId=${bot && bot.id} view=${view}+ previews=${previews} pending=${pending} working=${working} username=${status && status.username}+ creating=${creating} setCreating=${setCreating}+ onSelect=${openChat} onCreated=${(b) => { reloadBots(); openChat(b.id); }} onDeleted=${onDeleted} onOpenSettings=${() => openSettings()} />+ <main class="main">+ ${view === "chat" && bot && html`<${ChatScreen} key=${bot.id} bot=${bot} models=${models} modelsError=${modelsError} reloadModels=${reloadModels}+ defaultModel=${settings && settings.defaultModel} infoOpen=${infoOpen} onToggleInfo=${() => setInfoOpen((v) => !v)}+ onWorking=${onWorking} onOpenSettings=${openSettings} onBotUpdated=${onBotUpdated} />`}+ ${view === "chat" && bots && !bots.length && html`<section class="chat" data-screen="chat"><div class="chat-empty">+ <h2>还没有机器人</h2><p>在左侧点 + 新建一个,然后直接对话。</p>+ <button type="button" class="btn primary" onClick=${() => setCreating(true)}>新建机器人</button>+ </div></section>`}+ ${view === "settings" && html`<${SettingsScreen} tab=${route.tab} focusRow=${route.row} onTab=${(t) => openSettings(t)}+ mf=${mf} onMfChanged=${reloadMf} onSettings=${setSettings} models=${models} modelsError=${modelsError} reloadModels=${reloadModels}+ status=${status} bots=${bots} onOpenBotSettings=${openBotSettings} />`}+ ${view === "bot-settings" && routedBot && html`<${BotSettingsScreen} key=${routedBot.id} bot=${routedBot} section=${route.section}+ models=${models} modelsError=${modelsError} reloadModels=${reloadModels} defaultModel=${settings && settings.defaultModel}+ onBack=${() => openChat(routedBot.id)} onBotUpdated=${onBotUpdated} onDeleted=${() => onDeleted(routedBot.id)} />`}+ ${view === "bot-settings" && bots && !routedBot && html`<div class="empty-state"><b>机器人不存在</b><button type="button" class="text" onClick=${() => openChat()}>返回对话</button></div>`}+ </main>+ ${panelBot && html`<div class="panel-scrim" onClick=${() => setInfoOpen(false)}></div>`}+ ${panelBot && html`<${InfoPanel} key=${panelBot.id} bot=${panelBot} onClose=${() => setInfoOpen(false)}+ onOpenBotSettings=${() => openBotSettings(panelBot.id)} onOpenChat=${() => setInfoOpen(false)} />`}+ ${palette && html`<${Palette} commands=${commands} onClose=${() => setPalette(false)} />`}+ <${DialogHost} />+ <${Toasts} />+ </div>`;+}++render(html`<${App} />`, document.getElementById("app"));diff --git a/ui/screens/bot-settings.js b/ui/screens/bot-settings.jsnew file mode 100644index 0000000..277274c--- /dev/null+++ b/ui/screens/bot-settings.js@@ -0,0 +1,169 @@+// 机器人设置(信息面板的 ⚙):同样的白色圆角 list + 行,改动即保存。+import { useEffect, useRef, useState } from "preact/hooks";+import { html, Icon, Seg, MenuButton, autoGrow } from "../components/ui.js";+import { BotAvatar } from "../components/avatar.js";+import { ModelPicker, shortModel } from "../components/model-picker.js";+import { api } from "../lib/api.js";+import { confirmSheet, failed, saved } from "../lib/store.js";++const ONOFF = [+ [false, "关"],+ [true, "开"],+];++function Row({ id, name, sub, title, children, off }) {+ return html`<div class=${`row${off ? " off" : ""}`} id=${`bot-${id}`} title=${title}>+ <div class="who"><div class="name">${name}</div>${sub && html`<div class="sub">${sub}</div>`}</div>+ <div class="ctl">${children}</div>+ </div>`;+}++function ModelButton({ value, models, modelsError, reloadModels, resetLabel, onChange }) {+ const [open, setOpen] = useState(false);+ const ref = useRef(null);+ return html`<button type="button" class="pick" ref=${ref} aria-haspopup="listbox" aria-expanded=${open} onClick=${() => setOpen((v) => !v)}>+ <span class="v">${value ? shortModel(value) : resetLabel}</span><${Icon} name="chevDown" />+ </button>+ ${open && html`<${ModelPicker} anchor=${ref.current} align="right" models=${models} error=${modelsError} onRetry=${reloadModels} current=${value}+ onPick=${onChange} onClose=${() => setOpen(false)} reset=${{ label: resetLabel, onSelect: () => onChange("") }} />`}`;+}++export function BotSettingsScreen({ bot, section, models, modelsError, reloadModels, defaultModel, onBack, onBotUpdated, onDeleted }) {+ const [d, setD] = useState(null);+ const [name, setName] = useState(bot.name);+ const [prompt, setPrompt] = useState(bot.systemPrompt || "");+ const promptRef = useRef(null);+ useEffect(() => {+ setName(bot.name);+ setPrompt(bot.systemPrompt || "");+ api(`/bots/${bot.id}/settings`).then(setD).catch(failed);+ }, [bot.id]);+ useEffect(() => autoGrow(promptRef.current, 320), [prompt, d]);+ useEffect(() => {+ if (section && d) requestAnimationFrame(() => document.getElementById(`bot-${section}`)?.scrollIntoView({ block: "center" }));+ }, [section, !!d]);++ const putBot = async (body) => {+ try {+ const r = await api(`/bots/${bot.id}`, { method: "PUT", body });+ onBotUpdated(r.bot);+ saved();+ } catch (e) {+ failed(e);+ }+ };+ const put = async (body) => {+ try {+ setD(await api(`/bots/${bot.id}/settings`, { method: "PUT", body }));+ saved();+ } catch (e) {+ failed(e);+ }+ };+ const del = async () => {+ if (!(await confirmSheet({ title: `删除「${bot.name}」?`, body: "会永久删除这个机器人及其全部会话,无法恢复。", confirmLabel: "永久删除", danger: true }))) return;+ try {+ await api(`/bots/${bot.id}`, { method: "DELETE" });+ onDeleted();+ } catch (e) {+ failed(e);+ }+ };+ const commitName = () => {+ const n = name.trim();+ if (!n) return setName(bot.name);+ if (n !== bot.name) putBot({ name: n });+ };++ const s = d && d.settings;+ const cu = d && d.computerUse;+ const codex = cu && cu.backends && cu.backends.find((b) => b.id === "codex");+ return html`<section class="settings view" data-screen="bot-settings">+ <div class="set-head">+ <div class="bot-head">+ <button type="button" class="icon-btn" aria-label="返回对话" title="返回对话(Esc)" onClick=${onBack}><${Icon} name="chevLeft" /></button>+ <${BotAvatar} name=${bot.name} id=${bot.id} size=${26} />+ <span class="grow">${bot.name} · 设置</span>+ </div>+ </div>+ <div class="set-body">+ <div class="list-head">身份</div>+ <div class="list">+ <${Row} id="name" name="名称">+ <input class="inline-input" value=${name} aria-label="名称" maxlength="60" onInput=${(e) => setName(e.target.value)} onBlur=${commitName}+ onKeyDown=${(e) => { if (e.key === "Enter") e.target.blur(); if (e.key === "Escape") { e.stopPropagation(); setName(bot.name); requestAnimationFrame(() => e.target.blur()); } }} />+ <//>+ <${Row} id="prompt" name="人设 / 系统提示词" sub="离开输入框时保存" />+ <div class="prompt-edit">+ <textarea class="field" ref=${promptRef} aria-label="人设 / 系统提示词" placeholder="例如:你是一个乐于助人的中文助手,回答简洁准确。" value=${prompt}+ onInput=${(e) => setPrompt(e.target.value)} onBlur=${() => prompt !== (bot.systemPrompt || "") && putBot({ systemPrompt: prompt })} />+ </div>+ </div>++ <div class="list-head">模型</div>+ <div class="list">+ <${Row} id="model" name="默认模型" sub="会话里还可以临时切换">+ <${ModelButton} value=${bot.defaultModel} models=${models} modelsError=${modelsError} reloadModels=${reloadModels}+ resetLabel=${`跟随全局默认${defaultModel ? `(${shortModel(defaultModel)})` : ""}`} onChange=${(m) => putBot({ defaultModel: m })} />+ <//>+ <${Row} id="utility" name="后台小任务模型" sub="记忆整理、上下文管家与交接便条">+ ${s && html`<${ModelButton} value=${s.utilityModel} models=${models} modelsError=${modelsError} reloadModels=${reloadModels} resetLabel="与对话模型相同" onChange=${(m) => put({ utilityModel: m })} />`}+ <//>+ </div>++ ${!s && html`<div class="list" style="margin-top:8px"><div class="row"><span class="skel" style="width:45%"></span></div><div class="row"><span class="skel" style="width:35%"></span></div></div>`}+ ${s && html`+ <div class="list-head">权限</div>+ <div class="list">+ <${Row} id="permission" name="文件权限" sub=${s.permission === "readonly" ? "不能改文件,命令在只读沙箱中运行" : "只能改本机器人工作区,越界操作需要你批准"}+ title="工作区可写(默认):只能改本机器人工作区,越界操作需审批;只读:不能改文件,命令在只读沙箱中运行">+ <${Seg} label="文件权限" value=${s.permission} onChange=${(v) => put({ permission: v })} options=${[["workspace", "工作区可写"], ["readonly", "只读"]]} />+ <//>+ </div>++ <div class="list-head">记忆</div>+ <div class="list">+ <${Row} id="memory" name="长期记忆" sub="remember / forget / recall">+ <${Seg} label="长期记忆" value=${s.memory.enabled} onChange=${(v) => put({ memory: { enabled: v } })} options=${ONOFF} />+ <//>+ <${Row} id="memory-review" name="回合结束后自动整理" off=${!s.memory.enabled}>+ <${Seg} label="自动整理记忆" value=${s.memory.review} disabled=${!s.memory.enabled} onChange=${(v) => put({ memory: { review: v } })} options=${ONOFF} />+ <//>+ <${Row} id="memory-team" name="允许写入团队记忆" sub="所有机器人共享" off=${!s.memory.enabled}>+ <${Seg} label="团队记忆" value=${s.memory.teamWrite} disabled=${!s.memory.enabled} onChange=${(v) => put({ memory: { teamWrite: v } })} options=${ONOFF} />+ <//>+ </div>++ <div class="list-head">上下文</div>+ <div class="list">+ <${Row} id="steward" name="自动压缩或开新段" sub="上下文变长时整理,并留下交接便条">+ <${Seg} label="上下文管家" value=${s.steward.enabled} onChange=${(v) => put({ steward: { enabled: v } })} options=${ONOFF} />+ <//>+ </div>++ <div class="list-head">电脑操作</div>+ <div class="list">+ <${Row} id="computer" name="电脑操作" sub=${cu ? cu.reason : ""} title=${cu && cu.notice}>+ <span class=${`dot ${cu && cu.available ? "ok" : "err"}`}></span>+ <${Seg} label="电脑操作" value=${s.computerUse.enabled} onChange=${(v) => put({ computerUse: { enabled: v } })} options=${ONOFF} />+ <//>+ <${Row} id="computer-backend" name="后端" off=${!s.computerUse.enabled}>+ <${MenuButton} label="电脑操作后端" value=${s.computerUse.backend} disabled=${!s.computerUse.enabled} onChange=${(v) => put({ computerUse: { backend: v } })}+ options=${[["cua", "Cua Driver", "随附,macOS / Windows / Linux"], ...(codex ? [["codex", "Codex 桥", codex.available ? "仅 macOS" : "仅 macOS,本机不可用"]] : [])]} />+ <//>+ <${Row} id="computer-approval" name="审批" sub=${s.computerUse.approval === "auto" ? "所有操作自动执行" : "点击、输入等改变界面的操作先问我;读取界面仍自动"} off=${!s.computerUse.enabled}>+ <${Seg} label="电脑操作审批" value=${s.computerUse.approval} disabled=${!s.computerUse.enabled} onChange=${(v) => put({ computerUse: { approval: v } })}+ options=${[["auto", "自动执行"], ["ask-input", "改变界面前先问我"]]} />+ <//>+ </div>+ `}++ <div class="list-head">危险操作</div>+ <div class="list">+ <${Row} id="delete" name="删除机器人" sub="永久删除这个机器人及其全部会话">+ <button type="button" class="text danger" onClick=${del}>删除机器人</button>+ <//>+ </div>+ </div>+ </section>`;+}diff --git a/ui/screens/chat.js b/ui/screens/chat.jsnew file mode 100644index 0000000..afa735a--- /dev/null+++ b/ui/screens/chat.js@@ -0,0 +1,440 @@+// 对话页:无顶栏,顶部居中悬浮名称胶囊(点开信息面板),960 内容列,560 气泡,底部悬浮输入胶囊。+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";+import { html, Icon, Menu, Popover, Badge, autoGrow } from "../components/ui.js";+import { BotAvatar } from "../components/avatar.js";+import { Markdown, Linkified } from "../components/markdown.js";+import { ModelPicker, shortModel, sameModel } from "../components/model-picker.js";+import { api, streamChat } from "../lib/api.js";+import { confirmSheet, failed, saved } from "../lib/store.js";+import { fmtSep } from "../lib/format.js";++const COMMANDS = [+ ["/model", "列出或切换模型"],+ ["/new", "开始新的一段对话(旧对话归档并留交接便条)"],+ ["/reset", "清空本会话上下文"],+ ["/status", "查看当前模型与运行方式"],+ ["/help", "显示全部命令"],+];+const NEAR_BOTTOM = 80;+const LINE_PX = 22;+let seq = 0;+const uid = () => `l${++seq}`;++const isError = (t) => typeof t === "string" && t.startsWith("⚠️");+const errText = (t) => t.replace(/^⚠️\s*/, "");+const isAuthError = (t) => /HTTP 401\b|\b401\b.*(key|密钥|unauthor)/i.test(t);++function toItems(messages) {+ return messages.map((m) =>+ m.role === "assistant" && isError(m.content)+ ? { kind: "error", id: "m" + m.id, text: errText(m.content), at: m.createdAt }+ : { kind: "msg", id: "m" + m.id, role: m.role === "user" ? "user" : "assistant", text: m.content, at: m.createdAt },+ );+}++// —— 审批 / 提问卡片 ——+const LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";+export function PromptCard({ requestId, fallback }) {+ const [row, setRow] = useState(null);+ const [gone, setGone] = useState(false);+ const [picked, setPicked] = useState({});+ const [custom, setCustom] = useState("");+ const [busy, setBusy] = useState(false);+ const load = useCallback(() => api(`/approvals/${encodeURIComponent(requestId)}`).then((d) => setRow(d.approval)).catch(() => setGone(true)), [requestId]);+ useEffect(() => {+ load();+ }, [load]);+ useEffect(() => {+ if (!row || row.status !== "pending") return;+ const t = setInterval(load, 3000);+ return () => clearInterval(t);+ }, [row && row.status]);++ if (gone || (!row && !requestId)) return html`<div class="notice"><span class="notice-text" style="white-space:pre-wrap">${fallback}</span></div>`;+ if (!row) return html`<div class="card"><span class="skel" style="width:60%"></span><span class="skel" style="width:40%"></span></div>`;+ const pending = row.status === "pending";+ const decide = async (ok) => {+ setBusy(true);+ try {+ const r = await api(`/approvals/${row.id}/${ok ? "approve" : "deny"}`, { method: "POST", body: {} });+ setRow(r.approval);+ } catch (e) {+ failed(e);+ load();+ }+ setBusy(false);+ };+ if (row.kind === "approval") {+ return html`<div class=${`card${pending ? "" : " done"}`}>+ <div class="meta"><span>需要你的批准 · <span class="num">${row.code}</span></span>${!pending && html`<${Badge} s=${row.status} />`}</div>+ <div class="q">${row.reason || "机器人想执行一个超出工作区的操作"}</div>+ ${(row.tool || row.detail) && html`<div class="cmd">${row.tool}${row.detail ? " " + row.detail : ""}</div>`}+ ${pending && html`<div class="actions">+ <button type="button" class="btn primary" disabled=${busy} onClick=${() => decide(true)}>允许(仅本次)</button>+ <button type="button" class="btn" disabled=${busy} onClick=${() => decide(false)}>拒绝</button>+ </div>`}+ </div>`;+ }+ const qs = row.questions || [];+ const submit = async (answers) => {+ setBusy(true);+ try {+ const r = await api(`/approvals/${row.id}/answer`, { method: "POST", body: { answers } });+ setRow(r.approval);+ } catch (e) {+ failed(e);+ load();+ }+ setBusy(false);+ };+ const single = qs.length === 1 && (qs[0].options || []).length && !qs[0].multiSelect;+ const choose = (q, label) => {+ if (!pending || busy) return;+ if (single) {+ setPicked({ [q.id]: [label] });+ return submit([{ id: q.id, selected: [label] }]);+ }+ setPicked((p) => {+ const cur = p[q.id] || [];+ const next = q.multiSelect ? (cur.includes(label) ? cur.filter((x) => x !== label) : [...cur, label]) : [label];+ return { ...p, [q.id]: next };+ });+ };+ const sendAll = () =>+ submit(qs.map((q, i) => ({ id: q.id, selected: picked[q.id] || [], ...(i === qs.length - 1 && custom.trim() ? { custom: custom.trim() } : {}) })));+ return html`<div class=${`card${pending ? "" : " done"}`}>+ ${qs.map((q) => html`<div style="display:grid;gap:8px">+ <div class="q">${q.question}</div>+ ${q.detail && html`<div class="q-detail">${q.detail}</div>`}+ ${(q.options || []).length > 0 && html`<div class="opts" role=${q.multiSelect ? "group" : "radiogroup"}>+ ${q.options.map((o, i) => html`<button type="button" class=${`opt${(picked[q.id] || []).includes(o.label) ? " picked" : ""}`} disabled=${!pending || busy}+ role=${q.multiSelect ? "checkbox" : "radio"} aria-checked=${(picked[q.id] || []).includes(o.label)} onClick=${() => choose(q, o.label)}>+ <span class="letter">${LETTERS[i] || i + 1}</span>+ <span>${o.label}${o.description && html`<span class="desc">${o.description}</span>`}</span>+ </button>`)}+ </div>`}+ </div>`)}+ ${pending && !single && html`<div class="answer">+ <input class="field" placeholder=${qs.some((q) => (q.options || []).length) ? "其他回答(可选)" : "输入你的回答"} value=${custom}+ onInput=${(e) => setCustom(e.target.value)} onKeyDown=${(e) => e.key === "Enter" && !e.isComposing && sendAll()} />+ <button type="button" class="btn primary" disabled=${busy || (!custom.trim() && !Object.values(picked).some((v) => v.length))} onClick=${sendAll}>提交</button>+ </div>`}+ ${pending && single && html`<div class="answer">+ <input class="field" placeholder="或者输入其他回答" value=${custom} onInput=${(e) => setCustom(e.target.value)}+ onKeyDown=${(e) => e.key === "Enter" && !e.isComposing && custom.trim() && submit([{ id: qs[0].id, selected: [], custom: custom.trim() }])} />+ </div>`}+ ${!pending && html`<div class="meta"><${Badge} s=${row.status} /></div>`}+ </div>`;+}++function FileCard({ name }) {+ return html`<div class="file-card">+ <${Icon} name="file" size=${32} stroke=${1.2} />+ <div style="min-width:0">+ <div class="fname">${name}</div>+ <div class="fsub">已交付到机器人工作区 · 微信/飞书会直接发送</div>+ </div>+ </div>`;+}++function ErrorNotice({ text, onRetry, onFixKey }) {+ const auth = isAuthError(text);+ return html`<div class="notice red" role="alert">+ <span class="notice-text">${auth ? "Modelflare 密钥失效或已被撤销。" : text}</span>+ ${auth && onFixKey && html`<button type="button" class="btn" onClick=${onFixKey}>去更新</button>`}+ ${onRetry && html`<button type="button" class="btn" onClick=${onRetry}>重试</button>`}+ </div>`;+}++export function ChatScreen({ bot, models, modelsError, reloadModels, defaultModel, infoOpen, onToggleInfo, onWorking, onOpenSettings, onBotUpdated }) {+ const [items, setItems] = useState(null);+ const [convModel, setConvModel] = useState("");+ const [text, setText] = useState("");+ const [generating, setGenerating] = useState(false);+ const [atBottom, setAtBottom] = useState(true);+ const [unseen, setUnseen] = useState(false);+ const [menu, setMenu] = useState(null); // "plus" | "model" | null+ const [slashSel, setSlashSel] = useState(0);+ const [slashOff, setSlashOff] = useState(false);+ const [loadErr, setLoadErr] = useState("");+ const scroller = useRef(null);+ const stick = useRef(true);+ const ta = useRef(null);+ const plusRef = useRef(null);+ const modelRef = useRef(null);+ const ctrl = useRef(null);+ const mounted = useRef(true);+ const lastUser = useRef("");++ const load = useCallback(async () => {+ try {+ const d = await api(`/bots/${encodeURIComponent(bot.id)}/chat`);+ if (!mounted.current) return;+ setConvModel(d.model || "");+ const list = toItems(d.messages || []);+ for (const a of d.pending || []) list.push({ kind: "prompt", id: "p" + a.id, requestId: a.id, prompt: "" });+ setItems(list);+ setLoadErr("");+ } catch (e) {+ if (mounted.current) {+ setItems((v) => v || []);+ setLoadErr(e.message);+ }+ }+ }, [bot.id]);++ useEffect(() => {+ mounted.current = true;+ load();+ requestAnimationFrame(() => ta.current?.focus());+ return () => {+ mounted.current = false;+ };+ }, [load]);+ useEffect(() => onWorking(bot.id, generating), [generating]);+ useEffect(() => () => onWorking(bot.id, false), []);++ // 只有用户本来就在底部附近时才跟随新内容;否则亮出"回到底部"+ useLayoutEffect(() => {+ const el = scroller.current;+ if (!el) return;+ if (stick.current) el.scrollTop = el.scrollHeight;+ else setUnseen(true);+ }, [items]);+ const onScroll = () => {+ const el = scroller.current;+ const near = el.scrollHeight - el.scrollTop - el.clientHeight < NEAR_BOTTOM;+ stick.current = near;+ setAtBottom(near);+ if (near) setUnseen(false);+ };+ const toBottom = () => {+ stick.current = true;+ scroller.current?.scrollTo({ top: scroller.current.scrollHeight, behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" });+ setUnseen(false);+ };++ const patchLive = (id, fn) => mounted.current && setItems((l) => (l || []).map((it) => (it.id === id ? fn(it) : it)));++ const send = async (raw) => {+ const t = (raw ?? text).trim();+ if (!t || generating) return;+ if (raw === undefined) {+ setText("");+ requestAnimationFrame(() => autoGrow(ta.current, LINE_PX * 8 + 8));+ }+ if (!t.startsWith("/")) lastUser.current = t;+ stick.current = true;+ const liveId = uid();+ const isReset = /^\/reset\b/i.test(t);+ setItems((l) => [...(l || []), { kind: "msg", id: uid(), role: "user", text: t, at: Date.now(), enter: true }, { kind: "msg", id: liveId, role: "assistant", text: "", at: Date.now(), live: true }]);+ const ac = new AbortController();+ ctrl.current = ac;+ setGenerating(true);+ let finalText = "";+ try {+ await streamChat(+ bot.id,+ t,+ {+ text: (d) => {+ finalText = d.text;+ patchLive(liveId, (it) => ({ ...it, text: d.text }));+ },+ prompt: (d) => mounted.current && setItems((l) => {+ const i = l.findIndex((x) => x.id === liveId);+ const card = { kind: "prompt", id: uid(), requestId: d.requestId, prompt: d.prompt };+ return i < 0 ? [...l, card] : [...l.slice(0, i), card, ...l.slice(i)];+ }),+ file: (d) => mounted.current && setItems((l) => [...l, { kind: "file", id: uid(), name: d.name }]),+ error: (d) => {+ finalText = "⚠️ " + (d.message || "出错了");+ },+ },+ ac.signal,+ );+ } catch (e) {+ // 在收到第一个字节前就点了停止:不是错误+ if (e.name !== "AbortError") finalText = "⚠️ " + e.message;+ }+ if (!mounted.current) return;+ ctrl.current = null;+ setGenerating(false);+ setItems((l) => {+ const out = [];+ for (const it of l || []) {+ if (it.id !== liveId) out.push(it);+ else if (isError(finalText)) out.push({ kind: "error", id: liveId, text: errText(finalText), retry: t.startsWith("/") ? undefined : t, at: it.at });+ else if (finalText) out.push({ ...it, text: finalText, live: false });+ }+ return isReset && !isError(finalText) ? out.filter((x) => x.id === liveId) : out;+ });+ if (/^\/model\s+\S/i.test(t)) load();+ };++ const stop = () => {+ ctrl.current?.abort();+ };++ // —— 斜杠命令菜单 ——+ const slashQuery = /^\/\S*$/.test(text) && !slashOff ? text.toLowerCase() : null;+ const slashHits = slashQuery !== null ? COMMANDS.filter(([c]) => c.startsWith(slashQuery)) : [];+ const slashOpen = slashHits.length > 0 && !(slashHits.length === 1 && slashHits[0][0] === text);+ const completeSlash = (cmd) => {+ setText(cmd === "/model" ? "/model " : cmd);+ setSlashOff(cmd === "/model");+ ta.current?.focus();+ };++ const onKey = (e) => {+ if (e.isComposing || e.keyCode === 229) return;+ if (slashOpen) {+ if (e.key === "ArrowDown") {+ e.preventDefault();+ return setSlashSel((s) => (s + 1) % slashHits.length);+ }+ if (e.key === "ArrowUp") {+ e.preventDefault();+ return setSlashSel((s) => (s - 1 + slashHits.length) % slashHits.length);+ }+ if (e.key === "Tab" || (e.key === "Enter" && !e.shiftKey)) {+ e.preventDefault();+ return completeSlash(slashHits[Math.min(slashSel, slashHits.length - 1)][0]);+ }+ if (e.key === "Escape") {+ e.preventDefault();+ return setSlashOff(true);+ }+ }+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ send();+ } else if (e.key === "Escape" && generating) {+ e.preventDefault();+ stop();+ }+ };++ // —— 模型 ——+ const effective = convModel || bot.defaultModel || defaultModel || (models && models[0]) || "";+ const pickModel = async (m) => {+ try {+ await api(`/bots/${encodeURIComponent(bot.id)}/chat/model`, { method: "PUT", body: { model: m } });+ setConvModel(m);+ saved();+ } catch (e) {+ failed(e);+ }+ };+ const setBotDefault = async () => {+ try {+ const r = await api(`/bots/${encodeURIComponent(bot.id)}`, { method: "PUT", body: { defaultModel: effective } });+ await api(`/bots/${encodeURIComponent(bot.id)}/chat/model`, { method: "PUT", body: { model: "" } });+ setConvModel("");+ onBotUpdated(r.bot);+ saved();+ } catch (e) {+ failed(e);+ }+ };+ const plusItems = [+ { label: "切换模型…", onSelect: () => requestAnimationFrame(() => setMenu("model")) },+ { sep: true },+ { label: "开始新的一段对话", note: "/new", onSelect: () => send("/new") },+ {+ label: "清空上下文",+ note: "/reset",+ onSelect: async () => {+ if (await confirmSheet({ title: "清空本会话上下文?", body: `「${bot.name}」会忘掉这段网页对话的内容;长期记忆保留。`, confirmLabel: "清空", danger: true })) send("/reset");+ },+ },+ { label: "查看状态", note: "/status", onSelect: () => send("/status") },+ { label: "全部命令", note: "/help", onSelect: () => send("/help") },+ ];++ // —— 渲染 ——+ const rows = useMemo(() => {+ const out = [];+ let prev = null;+ for (const it of items || []) {+ if (it.at && (!prev?.at || new Date(it.at).toDateString() !== new Date(prev.at).toDateString() || it.at - prev.at > 15 * 60_000)) {+ out.push(html`<div class="time-sep" key=${"t" + it.id}>${fmtSep(it.at)}</div>`);+ prev = null;+ }+ const role = it.kind === "msg" ? it.role : "assistant";+ const cont = prev && (prev.kind === "msg" ? prev.role : "assistant") === role;+ const cls = `msg-row ${role}${cont ? " cont" : ""}${it.enter ? " enter" : ""}`;+ if (it.kind === "msg") {+ out.push(html`<div class=${cls} key=${it.id}>+ ${it.role === "user"+ ? html`<div class="msg"><${Linkified} text=${it.text} /></div>`+ : it.live && !it.text+ ? html`<div class="msg" aria-label="正在回复"><span class="typing"><i></i><i></i><i></i></span></div>`+ : html`<div class="msg"><${Markdown} text=${it.text} />${it.live && html`<span class="caret" aria-hidden="true"></span>`}</div>`}+ </div>`);+ } else if (it.kind === "prompt") {+ out.push(html`<div class=${cls} key=${it.id}><${PromptCard} requestId=${it.requestId} fallback=${it.prompt} /></div>`);+ } else if (it.kind === "file") {+ out.push(html`<div class=${cls} key=${it.id}><${FileCard} name=${it.name} /></div>`);+ } else if (it.kind === "error") {+ out.push(html`<div class=${cls} key=${it.id}><${ErrorNotice} text=${it.text} onRetry=${it.retry ? () => send(it.retry) : undefined} onFixKey=${() => onOpenSettings("modelflare", "connection")} /></div>`);+ }+ prev = it;+ }+ return out;+ }, [items, generating]);++ const empty = items && items.length === 0;+ return html`<section class="chat" data-screen="chat" aria-label=${`和 ${bot.name} 的对话`}>+ <div class="drag-strip"></div>+ <button type="button" class="float-pill" aria-pressed=${infoOpen} title="信息面板(⌘⇧I)" onClick=${onToggleInfo}>+ <${BotAvatar} name=${bot.name} id=${bot.id} size=${21} working=${generating} />+ <span class="name">${bot.name}</span>+ </button>+ <div class="chat-scroll" ref=${scroller} onScroll=${onScroll}>+ <div class="chat-col" role="log" aria-live="polite" aria-busy=${generating}>+ ${loadErr && html`<div class="notice red" style="margin-top:8px"><span class="notice-text">读取历史消息失败:${loadErr}</span><button type="button" class="btn" onClick=${load}>重试</button></div>`}+ ${items === null && html`<div style="display:grid;gap:14px;margin-top:24px"><span class="skel" style="width:40%;height:34px;border-radius:17px"></span><span class="skel" style="width:28%;height:34px;border-radius:17px;justify-self:end"></span></div>`}+ ${empty && html`<div class="chat-empty">+ <${BotAvatar} name=${bot.name} id=${bot.id} size=${56} />+ <h2>和 ${bot.name} 开始对话</h2>+ <p>在这里直接测试机器人;飞书和微信渠道在信息面板里配置。</p>+ <div class="chips">+ <button type="button" class="chip" onClick=${() => send("你能帮我做什么?")}>你能帮我做什么?</button>+ <button type="button" class="chip" onClick=${() => send("/help")}>/help 查看命令</button>+ </div>+ </div>`}+ ${rows}+ </div>+ </div>+ ${!atBottom && html`<button type="button" class="to-bottom" aria-label="回到底部" onClick=${toBottom}><${Icon} name="down" />${unseen && html`<span class="new"></span>`}</button>`}+ <div class="composer-dock">+ <div class="composer">+ <button type="button" class="plus" ref=${plusRef} aria-label="更多操作" aria-haspopup="menu" aria-expanded=${menu === "plus"} onClick=${() => setMenu(menu === "plus" ? null : "plus")}><${Icon} name="plus" size=${14} stroke=${1.8} /></button>+ <textarea ref=${ta} rows="1" placeholder=${`给「${bot.name}」发消息`} aria-label="消息" value=${text}+ onInput=${(e) => { setText(e.target.value); setSlashOff(false); setSlashSel(0); autoGrow(e.target, LINE_PX * 8 + 8); }}+ onKeyDown=${onKey} />+ <button type="button" class="model-chip" ref=${modelRef} title=${effective ? `当前模型:${effective}` : "选择模型"} aria-haspopup="listbox" aria-expanded=${menu === "model"}+ onClick=${() => setMenu(menu === "model" ? null : "model")}>+ <span class="v">${effective ? shortModel(effective) : "选择模型"}</span><${Icon} name="chevDown" />+ </button>+ ${generating+ ? html`<button type="button" class="send stop" aria-label="停止生成(Esc)" title="停止(Esc)" onClick=${stop}><${Icon} name="stop" size=${12} /></button>`+ : html`<button type="button" class="send" aria-label="发送" title="发送(Enter)" disabled=${!text.trim()} onClick=${() => send()}><${Icon} name="up" size=${15} stroke=${2} /></button>`}+ </div>+ </div>+ ${slashOpen && ta.current && html`<${Popover} anchor=${ta.current} prefer="up" width=${320} keepFocus label="命令" onClose=${() => setSlashOff(true)}>+ <ul role="listbox" aria-label="命令">+ ${slashHits.map(([c, d], i) => html`<li role="option" aria-selected=${i === slashSel} class=${`explained${i === Math.min(slashSel, slashHits.length - 1) ? " sel" : ""}`}+ onPointerDown=${(e) => e.preventDefault()} onPointerMove=${() => setSlashSel(i)} onClick=${() => completeSlash(c)}>+ <span class="v">${c}</span><span class="n">${d}</span>+ </li>`)}+ </ul>+ <//>`}+ ${menu === "plus" && html`<${Menu} anchor=${plusRef.current} prefer="up" width=${240} label="更多操作" onClose=${() => setMenu(null)} items=${plusItems} />`}+ ${menu === "model" && html`<${ModelPicker} anchor=${modelRef.current} prefer="up" align="right" models=${models} error=${modelsError} onRetry=${reloadModels}+ current=${convModel || bot.defaultModel || defaultModel} onPick=${pickModel} onClose=${() => setMenu(null)}+ reset=${{ label: "跟随机器人默认", note: shortModel(bot.defaultModel || defaultModel) || "自动", onSelect: () => pickModel("") }}+ foot=${{ label: "设为此机器人的默认模型", disabled: !effective || sameModel(effective, bot.defaultModel), onClick: setBotDefault }} />`}+ </section>`;+}diff --git a/ui/screens/info-panel.js b/ui/screens/info-panel.jsnew file mode 100644index 0000000..8b0c93e--- /dev/null+++ b/ui/screens/info-panel.js@@ -0,0 +1,188 @@+// 信息面板:点悬浮胶囊或 ⌘⇧I 打开,面板自己的 ✕ 关闭,⚙ 进机器人设置。+import { useCallback, useEffect, useState } from "preact/hooks";+import { html, Icon, Badge, Sheet, Spinner } from "../components/ui.js";+import { PromptCard } from "./chat.js";+import { api } from "../lib/api.js";+import { confirmSheet, failed, saved, toast } from "../lib/store.js";+import { fmtAgo, fmtTime } from "../lib/format.js";++export function usePoll(fn, ms, deps = []) {+ const [data, setData] = useState(null);+ const [err, setErr] = useState("");+ const load = useCallback(() => fn().then((d) => (setData(d), setErr(""))).catch((e) => setErr(e.message)), deps);+ useEffect(() => {+ load();+ if (!ms) return;+ const t = setInterval(load, ms);+ return () => clearInterval(t);+ }, [load, ms]);+ return [data, err, load];+}++const CHANNEL_NAME = { web: "网页", feishu: "飞书", weixin: "微信" };++function FeishuRow({ bot, st, reload }) {+ const [open, setOpen] = useState(false);+ const [appId, setAppId] = useState(bot.feishuAppId);+ const [secret, setSecret] = useState("");+ const [busy, setBusy] = useState(false);+ useEffect(() => setAppId(bot.feishuAppId), [bot.id, bot.feishuAppId]);+ const save = async () => {+ setBusy(true);+ try {+ await api(`/bots/${bot.id}/feishu`, { method: "PUT", body: { appId, appSecret: secret } });+ setSecret("");+ saved();+ reload();+ } catch (e) {+ failed(e);+ }+ setBusy(false);+ };+ const clear = async () => {+ if (!(await confirmSheet({ title: "断开飞书?", body: "会清除这个机器人的飞书 App ID 与 App Secret。", confirmLabel: "断开", danger: true }))) return;+ try {+ await api(`/bots/${bot.id}/feishu`, { method: "DELETE" });+ setAppId("");+ reload();+ } catch (e) {+ failed(e);+ }+ };+ return html`<div class="row clickable" onClick=${() => setOpen((v) => !v)} role="button" tabindex="0" aria-expanded=${open}+ onKeyDown=${(e) => (e.key === "Enter" || e.key === " ") && (e.preventDefault(), setOpen((v) => !v))}>+ <div class="who"><div class="name">飞书</div><div class="sub">${st.detail || (bot.feishuAppId ? bot.feishuAppId : "长连接接收消息")}</div></div>+ <${Badge} s=${st.state} />+ </div>+ ${open && html`<div class="row-edit">+ <label>App ID<input class="field mono" value=${appId} placeholder="cli_xxxxxxxx" onInput=${(e) => setAppId(e.target.value)} /></label>+ <label>App Secret${bot.feishuAppSecretMasked && html`<span class="hint">已保存 ${bot.feishuAppSecretMasked},留空则不修改</span>`}+ <input class="field mono" type="password" autocomplete="off" value=${secret} onInput=${(e) => setSecret(e.target.value)} /></label>+ <div class="actions">+ <button type="button" class="btn primary" disabled=${!appId.trim() || busy} onClick=${save}>${busy ? html`<${Spinner} />` : "保存并连接"}</button>+ ${bot.feishuAppId && html`<button type="button" class="text danger" onClick=${clear}>断开</button>`}+ </div>+ <p class="hint">在飞书开放平台启用「机器人」,事件订阅选「使用长连接接收事件」并订阅 <code>im.message.receive_v1</code>;权限:<code>im:message.p2p_msg:readonly</code>、<code>im:message:send_as_bot</code>、<code>cardkit:card:write</code>。</p>+ </div>`}`;+}++function WeixinRow({ bot, st, reload }) {+ const [open, setOpen] = useState(false);+ const [code, setCode] = useState("");+ const login = st.login;+ const active = login && ["fetching", "wait", "scaned", "need_verifycode"].includes(login.state);+ useEffect(() => {+ if (!active) return;+ setOpen(true);+ const t = setInterval(reload, 1500);+ return () => clearInterval(t);+ }, [active]);+ const call = (path, body = {}) => api(`/bots/${bot.id}/weixin${path}`, { method: path ? "POST" : "PUT", body }).then(reload).catch(failed);+ const logout = async () => {+ if (await confirmSheet({ title: "解除微信绑定?", body: "解除后需要重新扫码才能收发微信消息。", confirmLabel: "解除绑定", danger: true })) call("/logout");+ };+ return html`<div class="row clickable" onClick=${() => setOpen((v) => !v)} role="button" tabindex="0" aria-expanded=${open}+ onKeyDown=${(e) => (e.key === "Enter" || e.key === " ") && (e.preventDefault(), setOpen((v) => !v))}>+ <div class="who"><div class="name">微信</div><div class="sub">${st.account ? `已绑定 ${st.account.ilinkBotId}` : st.detail || "iLink 官方通道"}</div></div>+ <${Badge} s=${st.state} />+ </div>+ ${open && html`<div class="row-edit">+ ${login && login.state !== "idle" && html`<div class="actions"><${Badge} s=${login.state} /><span class="hint">${login.message}</span></div>`}+ ${active && login.qrDataUrl && html`<img src=${login.qrDataUrl} alt="微信登录二维码" style="width:180px;height:180px;image-rendering:pixelated;background:#fff;padding:8px;border-radius:10px;border:1px solid var(--line)" />+ <p class="hint">用微信扫一扫,然后在手机上确认。</p>`}+ ${login && login.state === "need_verifycode" && html`<div class="actions"><input class="field" style="width:140px" placeholder="验证码" value=${code} onInput=${(e) => setCode(e.target.value)} />+ <button type="button" class="btn" onClick=${() => call("/verify", { code }).then(() => setCode(""))}>提交</button></div>`}+ ${st.account && st.account.pausedUntil > Date.now() && html`<p class="hint">暂停至 ${fmtTime(st.account.pausedUntil)}</p>`}+ <div class="actions">+ ${active ? html`<button type="button" class="btn" onClick=${() => call("/cancel")}>取消</button>` : html`<button type="button" class="btn primary" onClick=${() => call("/login")}>${st.account ? "重新扫码登录" : "扫码登录"}</button>`}+ <button type="button" class="text" onClick=${() => call("", { enabled: !bot.weixinEnabled })}>${bot.weixinEnabled ? "停用微信渠道" : "启用微信渠道"}</button>+ ${st.account && html`<button type="button" class="text danger" onClick=${logout}>解除绑定</button>`}+ </div>+ ${st.quota && st.quota.length > 0 && html`<p class="hint">出站配额(每条入站消息后 24 小时内最多 10 条):${st.quota.map((q) => `${q.userId.slice(0, 8)}… 剩 ${q.remaining} 条`).join(";")}</p>`}+ </div>`}`;+}++function MemorySection({ botId }) {+ const [d, err, reload] = usePoll(() => api(`/bots/${botId}/memory`), 0, [botId]);+ const forget = async (sc, text, topic) => {+ if (!(await confirmSheet({ title: "删除这条记忆?", body: text, confirmLabel: "删除", danger: true }))) return;+ try {+ await api(`/bots/${botId}/memory/forget`, { method: "POST", body: { kind: sc.kind, id: sc.id, match: text, topic } });+ toast("已删除");+ reload();+ } catch (e) {+ failed(e);+ }+ };+ const all = d ? d.scopes.flatMap((sc) => [...sc.entries.map((e) => ({ sc, e })), ...sc.topics.flatMap((t) => t.entries.map((e) => ({ sc, e, topic: t.name })))]) : [];+ return html`<div class="list-head">记忆<span class="grow"></span><button type="button" class="icon-btn" title="刷新" aria-label="刷新记忆" onClick=${reload}><${Icon} name="refresh" size=${13} /></button></div>+ <div class="list">+ ${!d && html`<div class="row"><span class="hint">${err || "加载中…"}</span></div>`}+ ${d && !all.length && html`<div class="row"><span class="hint">还没有长期记忆</span></div>`}+ ${all.slice(0, 30).map(({ sc, e, topic }) => html`<div class="row compact">+ <div class="who"><div class="sub wrap selectable" style="color:var(--fg);font-size:12.5px">${e.text}</div><div class="sub">${sc.label}${topic ? " · " + topic : ""}</div></div>+ <button type="button" class="icon-btn" title="删除" aria-label="删除这条记忆" onClick=${() => forget(sc, e.text, topic)}><${Icon} name="trash" size=${13} /></button>+ </div>`)}+ </div>`;+}++function ConversationSheet({ conv, onClose }) {+ const [d] = usePoll(() => api(`/conversations/${encodeURIComponent(conv.id)}/messages`), 0, [conv.id]);+ return html`<${Sheet} title=${`${CHANNEL_NAME[conv.channel] || conv.channel} · ${conv.title || conv.peerId}`} wide onClose=${onClose}>+ <div style="display:grid;gap:8px;max-height:60vh;overflow:auto">+ ${!d && html`<span class="hint">加载中…</span>`}+ ${d && !d.messages.length && html`<span class="hint">没有消息</span>`}+ ${d && d.messages.map((m) => html`<div style=${`justify-self:${m.role === "user" ? "end" : "start"};max-width:85%`}>+ <div class="selectable" style=${`white-space:pre-wrap;padding:7px 11px;border-radius:14px;font-size:13px;line-height:1.5;${m.role === "user" ? "background:var(--accent-solid);color:var(--on-accent)" : "background:var(--bubble-ai)"}`}>${m.content}</div>+ <div class="hint" style=${`text-align:${m.role === "user" ? "right" : "left"};margin-top:2px`}>${fmtTime(m.createdAt)}</div>+ </div>`)}+ </div>+ <div class="actions"><button type="button" class="btn" data-autofocus onClick=${onClose}>关闭</button></div>+ <//>`;+}++export function InfoPanel({ bot, onClose, onOpenBotSettings, onOpenChat }) {+ const [detail, , reloadDetail] = usePoll(() => api(`/bots/${bot.id}`), 5000, [bot.id]);+ const [appr, , reloadAppr] = usePoll(() => api(`/approvals?status=pending&bot=${encodeURIComponent(bot.id)}`), 4000, [bot.id]);+ const [convs] = usePoll(() => api(`/conversations?bot=${encodeURIComponent(bot.id)}`), 8000, [bot.id]);+ const [viewing, setViewing] = useState(null);+ const pending = (appr && appr.approvals) || [];+ return html`<aside class="panel" aria-label="信息面板">+ <div class="panel-head">+ <span class="title">${bot.name}</span>+ <button type="button" class="icon-btn" title="机器人设置" aria-label="机器人设置" onClick=${onOpenBotSettings}><${Icon} name="gear" /></button>+ <button type="button" class="icon-btn" title="关闭(⌘⇧I)" aria-label="关闭信息面板" onClick=${onClose}><${Icon} name="close" /></button>+ </div>+ <div class="panel-body">+ <div class="list-head">渠道</div>+ <div class="list">+ ${detail && detail.bot+ ? html`<${FeishuRow} bot=${detail.bot} st=${detail.channels.feishu} reload=${reloadDetail} /><${WeixinRow} bot=${detail.bot} st=${detail.channels.weixin} reload=${reloadDetail} />`+ : html`<div class="row"><span class="skel" style="width:50%"></span></div><div class="row"><span class="skel" style="width:40%"></span></div>`}+ </div>++ <div class="list-head">待审批${pending.length > 0 && html`<span class="badge count warn">${pending.length}</span>`}</div>+ ${pending.length+ ? html`<div style="display:grid;gap:8px">${pending.map((a) => html`<div key=${a.id} style="display:grid;gap:4px">+ <span class="hint">${CHANNEL_NAME[a.conversationId.split(":")[1]] || ""} · ${fmtAgo(a.createdAt)} · 截止 ${fmtTime(a.expiresAt).slice(-8, -3)}</span>+ <${PromptCard} requestId=${a.id} fallback="" />+ </div>`)}+ <button type="button" class="text" style="justify-self:start" onClick=${reloadAppr}>刷新</button></div>`+ : html`<div class="list"><div class="row"><span class="hint">没有待处理的审批</span></div></div>`}++ <${MemorySection} botId=${bot.id} />++ <div class="list-head">最近会话</div>+ <div class="list">+ ${!convs && html`<div class="row"><span class="skel" style="width:60%"></span></div>`}+ ${convs && !convs.conversations.length && html`<div class="row"><span class="hint">还没有会话</span></div>`}+ ${convs && convs.conversations.slice(0, 12).map((c) => html`<div class="row compact clickable" role="button" tabindex="0"+ onClick=${() => (c.channel === "web" ? onOpenChat() : setViewing(c))} onKeyDown=${(e) => e.key === "Enter" && (c.channel === "web" ? onOpenChat() : setViewing(c))}>+ <div class="who"><div class="name">${CHANNEL_NAME[c.channel] || c.channel} · ${c.title || c.peerId}</div><div class="sub">${c.lastMessage || "(空)"}</div></div>+ <span class="hint num">${fmtAgo(c.updatedAt)}</span>+ </div>`)}+ </div>+ </div>+ ${viewing && html`<${ConversationSheet} conv=${viewing} onClose=${() => setViewing(null)} />`}+ </aside>`;+}diff --git a/ui/screens/onboarding.js b/ui/screens/onboarding.jsnew file mode 100644index 0000000..7e0577a--- /dev/null+++ b/ui/screens/onboarding.js@@ -0,0 +1,155 @@+// 首次启动 / 断开后:只有一个动作——粘贴 Modelflare API Key。不是向导路由,而是"未连接"时的整页空态。+import { useEffect, useMemo, useRef, useState } from "preact/hooks";+import { html, Icon, Seg, Spinner } from "../components/ui.js";+import { AppMark } from "../components/avatar.js";+import { groupModels } from "../components/model-picker.js";+import { api } from "../lib/api.js";++// 控制台 API Keys 页还没有稳定的深链地址,先指向官网首页(登录后可进控制台)+export const MF_CONSOLE = "https://modelflare.dev";+export const MF_DOCS = "https://docs.modelflare.dev";+export const LINE_OPTIONS = [+ ["auto", "自动"],+ ["global", "国际"],+ ["cn", "中国大陆优化"],+];++/** 粘贴 Key → 校验(GET /v1/models)→ 写入。onConnected(result) 收到 { models, keyTail, … } */+export function KeyForm({ line: initialLine = "auto", onConnected, showLine = true, submitLabel = "连接 Modelflare" }) {+ const [key, setKey] = useState("");+ const [show, setShow] = useState(false);+ const [line, setLine] = useState(initialLine);+ const [busy, setBusy] = useState(false);+ const [slow, setSlow] = useState(false);+ const [err, setErr] = useState(null);+ const input = useRef(null);+ const btn = useRef(null);+ useEffect(() => input.current?.focus(), []);++ const submit = async (lineOverride) => {+ const k = key.trim();+ if (!k || busy) return;+ const useLine = lineOverride || line;+ if (lineOverride) setLine(lineOverride);+ setBusy(true);+ setErr(null);+ setSlow(false);+ const t = setTimeout(() => setSlow(true), 4000);+ try {+ const r = await api("/modelflare", { method: "PUT", body: { apiKey: k, line: useLine } });+ setKey("");+ onConnected(r);+ } catch (e) {+ setErr({ message: e.message, code: e.data?.code, suggestLine: e.data?.suggestLine });+ } finally {+ clearTimeout(t);+ setBusy(false);+ setSlow(false);+ }+ };+ const paste = async () => {+ try {+ const t = (await navigator.clipboard.readText()).trim();+ if (t) {+ setKey(t);+ setErr(null);+ requestAnimationFrame(() => btn.current?.focus());+ }+ } catch {+ input.current?.focus();+ }+ };+ const retype = () => {+ input.current?.focus();+ input.current?.select();+ };++ return html`<form class="list" onSubmit=${(e) => { e.preventDefault(); submit(); }}>+ <label class="k" for="mf-key">API Key</label>+ <div class="field-wrap">+ <input id="mf-key" ref=${input} class=${`field mono${err?.code === "invalid_key" ? " err" : ""}`} type=${show ? "text" : "password"}+ autocomplete="off" spellcheck="false" placeholder="粘贴你的 Modelflare API Key" value=${key} readonly=${busy}+ aria-invalid=${!!err} aria-describedby="mf-key-note"+ onInput=${(e) => { setKey(e.target.value); setErr(null); }}+ onPaste=${() => requestAnimationFrame(() => btn.current?.focus())} />+ <span class="tail">+ <button type="button" class="icon-btn" title="从剪贴板粘贴" aria-label="从剪贴板粘贴" onClick=${paste}><${Icon} name="paste" size=${14} /></button>+ <button type="button" class="icon-btn" title=${show ? "隐藏" : "显示"} aria-label=${show ? "隐藏 Key" : "显示 Key"} onClick=${() => setShow((v) => !v)}><${Icon} name=${show ? "eyeOff" : "eye"} size=${14} /></button>+ </span>+ </div>+ ${err && html`<div class="err-text" role="alert">+ <span>${err.message}</span>+ ${err.code === "invalid_key" && html`<button type="button" class="text" onClick=${retype}>重新输入</button>`}+ ${err.code === "forbidden" && html`<a href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">去控制台检查分组 ↗</a>`}+ ${(err.code === "rate_limited" || err.code === "upstream" || err.code === "bad_response") && html`<button type="button" class="text" onClick=${() => submit()}>重试</button>`}+ ${err.code === "network" && err.suggestLine === "cn" && html`<button type="button" class="text accent" onClick=${() => submit("cn")}>改用大陆优化线路并重试</button>`}+ </div>`}+ <p class="hint" id="mf-key-note">密钥只保存在本机,不会写入日志或命令行参数。</p>+ <button type="submit" ref=${btn} class="btn primary lg block" disabled=${!key.trim() || busy}>+ ${busy ? html`<${Spinner} /> 正在连接…` : submitLabel}+ </button>+ ${slow && html`<p class="slow">网络较慢${showLine ? ",可在「高级」里切换线路" : ""}。</p>`}+ ${showLine && html`<details>+ <summary>高级 <${Icon} name="chevDown" size=${12} /></summary>+ <div class="row compact">+ <div class="who"><div class="name">线路</div><div class="sub">中国大陆访问可选优化线路</div></div>+ <${Seg} label="线路" options=${LINE_OPTIONS} value=${line} onChange=${setLine} disabled=${busy} />+ </div>+ </details>`}+ </form>`;+}++function ModelStep({ models, initial, onDone }) {+ const [q, setQ] = useState("");+ const [cur, setCur] = useState(initial && models.includes(initial) ? initial : models[0] || "");+ const [busy, setBusy] = useState(false);+ const [err, setErr] = useState("");+ const groups = useMemo(() => groupModels(models, q), [models, q]);+ const start = async () => {+ setBusy(true);+ try {+ await api("/settings", { method: "PUT", body: { defaultModel: cur } });+ onDone();+ } catch (e) {+ setErr(e.message);+ setBusy(false);+ }+ };+ return html`<div class="list">+ <div class="connected"><span class="dot ok"></span>已连接 · 找到 <span class="num">${models.length}</span> 个模型</div>+ ${models.length+ ? html`<p class="hint">选一个默认模型,之后随时可在对话里切换。</p>+ <input class="field" placeholder="筛选模型" value=${q} onInput=${(e) => setQ(e.target.value)} aria-label="筛选模型" />+ <div class="picklist" role="listbox" aria-label="默认模型">+ ${groups.map(([g, ms]) => html`${g && html`<div class="group">${g}</div>`}+ ${ms.map(([m, label]) => html`<button type="button" role="option" aria-selected=${m === cur} class=${m === cur ? "cur" : ""} onClick=${() => setCur(m)} onDblClick=${start}>+ <span class="v">${label}</span>${m === cur && html`<span class="check"><${Icon} name="check" size=${14} /></span>`}+ </button>`)}`)}+ ${!groups.length && html`<p class="hint" style="padding:8px">没有匹配的模型</p>`}+ </div>`+ : html`<div class="notice amber"><span class="notice-text">这个 Key 所在的分组暂无可用模型。可以在控制台给分组开放模型后再回来刷新。</span>+ <a class="btn" href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">去控制台 ↗</a></div>`}+ ${err && html`<div class="err-text" role="alert">${err}</div>`}+ <button type="button" class="btn primary lg block" disabled=${busy} onClick=${start}>${busy ? html`<${Spinner} /> 正在保存…` : models.length ? "开始对话" : "仍然开始"}</button>+ </div>`;+}++export function Onboarding({ status, gateway, defaultModel, onDone }) {+ const [models, setModels] = useState(null);+ return html`<main class="onboard" data-screen="onboarding">+ <div class="onboard-col">+ <div class="onboard-hero">+ <${AppMark} size=${44} />+ <h1>用 Modelflare 开始</h1>+ <p>粘贴 API Key,GPT、Claude、Grok、Gemini 等模型会自动列出。</p>+ </div>+ ${gateway && gateway.mode === "managed" && gateway.state === "failed" && html`<div class="notice red"><span class="notice-text">内置模型网关没有启动:${gateway.lastError || "未知原因"}。修复后重启应用再连接。</span></div>`}+ ${models === null+ ? html`<${KeyForm} line=${status.line} onConnected=${(r) => setModels(r.models || [])} />+ <div class="links">+ <a href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">还没有 Key?去 Modelflare 控制台创建 ↗</a>+ </div>`+ : html`<${ModelStep} models=${models} initial=${defaultModel} onDone=${onDone} />`}+ </div>+ </main>`;+}diff --git a/ui/screens/settings.js b/ui/screens/settings.jsnew file mode 100644index 0000000..0fbccb7--- /dev/null+++ b/ui/screens/settings.js@@ -0,0 +1,204 @@+// 设置页(magpie 风格):页签 + 查找设置;白色圆角 list,一行一项;改动即保存,左下角"已保存"。+// 入口只有左下角账户按钮、⌘/Ctrl+, 和命令面板,不放齿轮。+import { useEffect, useMemo, useRef, useState } from "preact/hooks";+import { html, Icon, Seg, Sheet, CopyButton } from "../components/ui.js";+import { ModelPicker, shortModel } from "../components/model-picker.js";+import { KeyForm, LINE_OPTIONS, MF_CONSOLE, MF_DOCS } from "./onboarding.js";+import { api } from "../lib/api.js";+import { useStore, confirmSheet, failed, saved } from "../lib/store.js";+import { themeMode, setThemeMode } from "../lib/theme.js";++export const TABS = [+ ["general", "常规"],+ ["modelflare", "Modelflare"],+ ["computer", "电脑操作"],+ ["privacy", "隐私与安全"],+ ["network", "网络与访问"],+ ["data", "数据"],+ ["about", "关于"],+];+const ZOOMS = [+ [1, "100%"],+ [1.1, "110%"],+ [1.25, "125%"],+ [1.5, "150%"],+];+const GATEWAY = { running: "运行中", starting: "启动中", restarting: "重启中", failed: "失败", stopped: "已停止", external: "外部端点" };++function Row({ id, name, sub, title, children, flash, off }) {+ return html`<div class=${`row${flash ? " flash" : ""}${off ? " off" : ""}`} id=${`set-${id}`} title=${title}>+ <div class="who"><div class="name">${name}</div>${sub && html`<div class="sub">${sub}</div>`}</div>+ <div class="ctl">${children}</div>+ </div>`;+}++function PickModel({ value, models, modelsError, reloadModels, onChange, resetLabel }) {+ const [open, setOpen] = useState(false);+ const ref = useRef(null);+ return html`<button type="button" class="pick" ref=${ref} aria-haspopup="listbox" aria-expanded=${open} onClick=${() => setOpen((v) => !v)}>+ <span class="v">${value ? shortModel(value) : resetLabel}</span><${Icon} name="chevDown" />+ </button>+ ${open && html`<${ModelPicker} anchor=${ref.current} align="right" models=${models} error=${modelsError} onRetry=${reloadModels} current=${value}+ onPick=${onChange} onClose=${() => setOpen(false)} reset=${{ label: resetLabel, onSelect: () => onChange("") }} />`}`;+}++function NoticesSheet({ onClose }) {+ const [d, setD] = useState(null);+ useEffect(() => {+ api("/notices").then(setD).catch((e) => setD({ license: e.message, notices: "" }));+ }, []);+ return html`<${Sheet} title="许可与第三方声明" wide onClose=${onClose}>+ <pre class="doc">${d ? `${d.license}\n\n${d.notices}` : "加载中…"}</pre>+ <div class="actions"><button type="button" class="btn" data-autofocus onClick=${onClose}>关闭</button></div>+ <//>`;+}++export function SettingsScreen({ tab, focusRow, onTab, mf, onMfChanged, onSettings, models, modelsError, reloadModels, status, bots, onOpenBotSettings }) {+ const [s, setS] = useState(null);+ const [q, setQ] = useState("");+ const [rekey, setRekey] = useState(false);+ const [notices, setNotices] = useState(false);+ const [cu, setCu] = useState(null);+ const [flash, setFlash] = useState("");+ const [stuck, setStuck] = useState(false);+ const mode = useStore(themeMode);+ const body = useRef(null);+ const find = useRef(null);++ useEffect(() => {+ api("/settings").then(setS).catch(failed);+ }, []);+ useEffect(() => {+ if (bots && bots[0]) api(`/bots/${encodeURIComponent(bots[0].id)}/settings`).then((d) => setCu(d.computerUse)).catch(() => {});+ }, [bots && bots[0] && bots[0].id]);+ useEffect(() => {+ if (!focusRow) return;+ setQ("");+ requestAnimationFrame(() => {+ document.getElementById(`set-${focusRow}`)?.scrollIntoView({ block: "center" });+ setFlash(focusRow);+ setTimeout(() => setFlash(""), 1300);+ });+ }, [focusRow, tab]);++ const put = async (patch, rollback) => {+ const prev = s;+ setS((v) => ({ ...v, ...rollback }));+ try {+ const next = await api("/settings", { method: "PUT", body: patch });+ setS(next);+ onSettings?.(next);+ saved();+ } catch (e) {+ setS(prev);+ failed(e);+ }+ };+ const setLine = async (line) => {+ try {+ await api("/modelflare/line", { method: "PUT", body: { line } });+ onMfChanged();+ saved();+ } catch (e) {+ failed(e);+ }+ };+ const disconnect = async () => {+ if (!(await confirmSheet({ title: "断开 Modelflare?", body: "会从本机删除这个 API Key。机器人和会话都会保留,重新连接后继续使用。", confirmLabel: "断开", danger: true }))) return;+ try {+ await api("/modelflare", { method: "DELETE" });+ onMfChanged();+ } catch (e) {+ failed(e);+ }+ };+ const desktop = !!(s && s.desktop);+ const managed = mf && mf.mode === "managed";++ // —— 行定义:每行一个稳定 id,可被搜索、可被深链(#/settings/<tab>/<id>)——+ const rows = useMemo(() => {+ if (!s) return [];+ return [+ { tab: "general", id: "appearance", name: "外观", sub: "浅色、深色,或跟随系统", keys: "主题 深色 浅色 theme dark",+ ctl: html`<${Seg} label="外观" value=${mode} onChange=${(m) => { setThemeMode(m); saved(); }} options=${[["system", "跟随系统"], ["light", "浅色"], ["dark", "深色"]]} />` },+ desktop && { tab: "general", id: "zoom", name: "文字大小", sub: "放大窗口里的一切", keys: "缩放 字号 zoom",+ ctl: html`<${Seg} label="文字大小" value=${s.zoom} onChange=${(z) => put({ zoom: z }, { zoom: z })} options=${ZOOMS} />` },+ desktop && { tab: "general", id: "close", name: "关闭窗口时", sub: "隐藏到托盘时机器人继续在后台收发消息", keys: "托盘 退出 tray",+ ctl: html`<${Seg} label="关闭窗口时" value=${s.closeToTray} onChange=${(v) => put({ closeToTray: v }, { closeToTray: v })} options=${[[true, "隐藏到托盘"], [false, "退出"]]} />` },+ desktop && s.autostart.supported && { tab: "general", id: "autostart", name: "开机自启", sub: "登录系统后在后台启动", keys: "启动 login",+ ctl: html`<${Seg} label="开机自启" value=${s.autostart.on} onChange=${(v) => put({ autostart: v }, { autostart: { ...s.autostart, on: v } })} options=${[[false, "关"], [true, "开"]]} />` },+ desktop && { tab: "general", id: "browser", name: "在浏览器中打开", sub: "用系统浏览器打开同一个本机界面", keys: "browser",+ ctl: html`<button type="button" class="text" onClick=${() => api("/desktop/open-in-browser", { method: "POST", body: {} }).catch(failed)}>打开</button>` },++ { tab: "modelflare", id: "connection", name: "连接", sub: managed ? "API Key 只保存在本机" : "由环境变量 AMB_MAGPIE_BASE_URL 指定的端点(开发/测试)", keys: "密钥 key api 断开 更换",+ ctl: managed+ ? html`<span class="mf-state"><span class=${`dot ${mf.connected ? "ok" : "err"}`}></span>${mf.connected ? "已连接" : "未连接"}</span>+ ${mf.keyTail && html`<span class="val">••••${mf.keyTail}</span>`}+ <button type="button" class="text" onClick=${() => setRekey(true)}>更换密钥</button>+ <button type="button" class="text danger" onClick=${disconnect}>断开</button>`+ : html`<span class="val" title=${mf && mf.baseUrl}>${mf && mf.baseUrl}</span>` },+ managed && { tab: "modelflare", id: "line", name: "线路", sub: "中国大陆访问更稳定可选优化线路;切换后新请求生效", keys: "大陆 国际 origin 网络",+ ctl: html`<${Seg} label="线路" value=${mf.line} onChange=${setLine} options=${LINE_OPTIONS} />` },+ { tab: "modelflare", id: "default-model", name: "默认模型", sub: "机器人没有单独指定时使用", keys: "模型 model",+ ctl: html`<${PickModel} value=${s.defaultModel} models=${models} modelsError=${modelsError} reloadModels=${reloadModels} resetLabel="自动(列表第一个)"+ onChange=${(m) => put({ defaultModel: m }, { defaultModel: m })} />` },+ { tab: "modelflare", id: "models", name: "可用模型", sub: modelsError ? `获取失败:${modelsError}` : "这个 Key 所在分组开放的模型", keys: "列表 刷新",+ ctl: html`<span class="val num">${models ? `${models.length} 个` : "…"}</span><button type="button" class="text" onClick=${() => reloadModels().then(() => saved())}>刷新</button>` },+ { tab: "modelflare", id: "billing", name: "用量与账单", sub: "用量、余额与价格以 Modelflare 主站为准", keys: "余额 价格 充值 usage",+ ctl: html`<a class="text" href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">在 Modelflare 控制台查看 ↗</a>` },++ { tab: "computer", id: "cu-status", name: "电脑操作后端", sub: cu ? cu.reason : "读取中…", keys: "computer use cua 辅助功能 屏幕录制",+ ctl: html`<span class=${`dot ${cu ? (cu.available ? "ok" : "err") : ""}`}></span>` },+ cu && cu.notice && { tab: "computer", id: "cu-notice", name: "系统权限", sub: cu.notice, title: cu.notice, keys: "权限 permission", ctl: null },+ { tab: "computer", id: "cu-per-bot", name: "按机器人开启", sub: "每个机器人可以单独开启电脑操作并设置审批方式", keys: "机器人",+ ctl: bots && bots[0] && html`<button type="button" class="text" onClick=${() => onOpenBotSettings(bots[0].id, "computer")}>打开机器人设置</button>` },++ { tab: "privacy", id: "key-storage", name: "密钥存放", sub: "Modelflare 密钥只在本机内置网关的隔离配置里,不写日志、不进命令行参数", ctl: null, keys: "安全" },+ { tab: "privacy", id: "token", name: "访问令牌", sub: s.listen.tokenRequired ? "需要令牌:界面监听在非本机地址,或桌面版每次启动随机生成" : "只监听本机,无需令牌", keys: "token 令牌",+ ctl: html`<span class=${`dot ${s.listen.tokenRequired ? "ok" : ""}`}></span>` },+ { tab: "privacy", id: "sandbox", name: "机器人沙箱", sub: "来自机器人沙箱的请求会被本机界面拒绝,机器人无法自行批准操作或读取配置", ctl: null, keys: "安全 dsh" },+ { tab: "privacy", id: "screens", name: "截图", sub: "电脑操作的截图只发给模型,不会发到聊天里", ctl: null, keys: "隐私" },++ { tab: "network", id: "listen", name: "监听地址", sub: "修改需设置 AMB_UI_HOST / AMB_UI_PORT 并重启", keys: "端口 port host",+ ctl: html`<span class="val">${s.listen.host}:${s.listen.port}</span><${CopyButton} text=${`http://${s.listen.host === "0.0.0.0" ? "127.0.0.1" : s.listen.host}:${s.listen.port}/`} label="复制地址" />` },++ { tab: "data", id: "data-dir", name: "数据目录", sub: "SQLite、机器人工作区、微信登录态与内置网关配置", keys: "路径 目录 folder",+ ctl: html`<span class="val" title=${s.dataDir}>${s.dataDir}</span><${CopyButton} text=${s.dataDir} label="复制路径" />+ ${desktop && html`<button type="button" class="text" onClick=${() => api("/desktop/open-data-dir", { method: "POST", body: {} }).catch(failed)}>打开</button>`}` },++ { tab: "about", id: "version", name: "版本", keys: "version", ctl: html`<span class="val">${status ? status.version : ""}</span>` },+ { tab: "about", id: "licenses", name: "许可与第三方声明", sub: "MIT;界面部分样式改编自 magpie(MIT)", keys: "license",+ ctl: html`<button type="button" class="text" onClick=${() => setNotices(true)}>查看</button>` },+ { tab: "about", id: "diagnostics", name: "诊断信息", sub: status ? `内置模型网关 · ${GATEWAY[status.gateway.state] || status.gateway.state}${status.gateway.restarts ? ` · 重启 ${status.gateway.restarts} 次` : ""}${status.gateway.lastError ? ` · ${status.gateway.lastError}` : ""}` : "", keys: "网关 gateway magpie",+ ctl: null },+ { tab: "about", id: "links", name: "Modelflare", sub: "官网与文档",+ ctl: html`<a class="text" href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">modelflare.dev ↗</a><a class="text" href=${MF_DOCS} target="_blank" rel="noopener noreferrer">文档 ↗</a>` },+ ].filter(Boolean);+ }, [s, mf, mode, models, modelsError, cu, status, bots]);++ const needle = q.trim().toLowerCase();+ const shown = needle ? rows.filter((r) => `${r.name} ${r.sub || ""} ${r.keys || ""}`.toLowerCase().includes(needle)) : rows.filter((r) => r.tab === tab);+ const parts = needle ? TABS.map(([t, label]) => [label, shown.filter((r) => r.tab === t)]).filter(([, l]) => l.length) : [["", shown]];++ return html`<section class="settings view" data-screen="settings" ref=${body} onScroll=${(e) => setStuck(e.target.scrollTop > 2)}>+ <div class=${`set-head${stuck ? " stuck" : ""}`}>+ <div class="set-title">设置</div>+ ${!needle && html`<nav class="warm-tabs" role="tablist" aria-label="设置分页">+ ${TABS.map(([t, label]) => html`<button type="button" role="tab" aria-selected=${t === tab} class=${t === tab ? "on" : ""} onClick=${() => onTab(t)}>${label}</button>`)}+ </nav>`}+ ${needle && html`<span style="flex:1"></span>`}+ <input class="set-find" ref=${find} type="search" placeholder="查找设置" aria-label="查找设置" value=${q} onInput=${(e) => setQ(e.target.value)}+ onKeyDown=${(e) => e.key === "Escape" && q && (e.stopPropagation(), setQ(""))} />+ </div>+ <div class="set-body">+ ${!s && html`<div class="list"><div class="row"><span class="skel" style="width:40%"></span></div><div class="row"><span class="skel" style="width:55%"></span></div></div>`}+ ${s && !shown.length && html`<p class="set-none">没有匹配的设置</p>`}+ ${parts.map(([label, list]) => html`${label && html`<div class="set-part">${label}</div>`}+ <div class="list">${list.map((r) => html`<${Row} key=${r.id} id=${r.id} name=${r.name} sub=${r.sub} title=${r.title || r.sub} flash=${flash === r.id}>${r.ctl}<//>`)}</div>`)}+ </div>+ ${rekey && html`<${Sheet} title="更换 Modelflare 密钥" onClose=${() => setRekey(false)}>+ <${KeyForm} line=${mf.line} showLine=${false} submitLabel="验证并保存" onConnected=${() => { setRekey(false); saved(); onMfChanged(); reloadModels(); }} />+ <//>`}+ ${notices && html`<${NoticesSheet} onClose=${() => setNotices(false)} />`}+ </section>`;+}diff --git a/ui/screens/sidebar.js b/ui/screens/sidebar.jsnew file mode 100644index 0000000..7fd4d49--- /dev/null+++ b/ui/screens/sidebar.js@@ -0,0 +1,125 @@+// 侧栏 280:顶部搜索 / 新建两个圆形按钮,应用标志,机器人行(头像 + 名称 + 一行预览),左下角账户按钮(打开设置)。+import { useEffect, useRef, useState } from "preact/hooks";+import { html, Icon, Menu } from "../components/ui.js";+import { AppMark, BotAvatar, usePointerLook } from "../components/avatar.js";+import { api } from "../lib/api.js";+import { confirmSheet, failed, toast } from "../lib/store.js";++export function Sidebar({ bots, botsError, reloadBots, selectedId, view, previews, pending, working, username, creating, setCreating, onSelect, onCreated, onDeleted, onOpenSettings }) {+ const [q, setQ] = useState("");+ const [searching, setSearching] = useState(false);+ const [name, setName] = useState("");+ const [busy, setBusy] = useState(false);+ const [ctx, setCtx] = useState(null); // { bot, x, y }+ const [renaming, setRenaming] = useState("");+ const [renameText, setRenameText] = useState("");+ const root = useRef(null);+ const searchRef = useRef(null);+ const newRef = useRef(null);+ const renameRef = useRef(null);+ usePointerLook(root);+ useEffect(() => {+ if (creating) requestAnimationFrame(() => newRef.current?.focus());+ }, [creating]);+ useEffect(() => {+ if (renaming) requestAnimationFrame(() => (renameRef.current?.focus(), renameRef.current?.select()));+ }, [renaming]);++ useEffect(() => {+ if (searching) requestAnimationFrame(() => searchRef.current?.focus());+ else setQ("");+ }, [searching]);++ const create = async () => {+ const n = name.trim();+ if (!n || busy) return;+ setBusy(true);+ try {+ const r = await api("/bots", { method: "POST", body: { name: n } });+ setName("");+ setCreating(false);+ onCreated(r.bot);+ } catch (e) {+ failed(e);+ }+ setBusy(false);+ };+ const rename = async (bot) => {+ const n = renameText.trim();+ setRenaming("");+ if (!n || n === bot.name) return;+ try {+ await api(`/bots/${bot.id}`, { method: "PUT", body: { name: n } });+ reloadBots();+ toast("已重命名");+ } catch (e) {+ failed(e);+ }+ };+ const del = async (bot) => {+ if (!(await confirmSheet({ title: `删除「${bot.name}」?`, body: "会永久删除这个机器人及其全部会话,无法恢复。", confirmLabel: "永久删除", danger: true }))) return;+ try {+ await api(`/bots/${bot.id}`, { method: "DELETE" });+ onDeleted(bot.id);+ } catch (e) {+ failed(e);+ }+ };++ const needle = q.trim().toLowerCase();+ const list = (bots || []).filter((b) => !needle || b.name.toLowerCase().includes(needle) || (previews[b.id] || "").toLowerCase().includes(needle));+ const me = (username || "本机用户").trim();++ return html`<aside class="side" ref=${root} aria-label="机器人">+ <div class="side-top">+ ${searching+ ? html`<input class="side-search" ref=${searchRef} placeholder="搜索机器人" aria-label="搜索机器人" value=${q} onInput=${(e) => setQ(e.target.value)}+ onKeyDown=${(e) => e.key === "Escape" && (e.stopPropagation(), setSearching(false))} onBlur=${() => !q && setSearching(false)} />`+ : html`<button type="button" class="round-btn" title="搜索" aria-label="搜索机器人" onClick=${() => setSearching(true)}><${Icon} name="search" /></button>`}+ <button type="button" class=${`round-btn${creating ? " on" : ""}`} title="新建机器人(⌘N)" aria-label="新建机器人" onClick=${() => setCreating(!creating)}><${Icon} name="plus" /></button>+ </div>+ ${!searching && html`<div class="side-hero"><${AppMark} size=${56} /><span class="name">AnyModelBot</span></div>`}+ <nav class="side-list" aria-label="机器人列表">+ ${creating && html`<form class="thread-new" onSubmit=${(e) => { e.preventDefault(); create(); }}>+ <input class="field" placeholder="新机器人的名称" aria-label="新机器人的名称" value=${name} ref=${newRef}+ onInput=${(e) => setName(e.target.value)} onKeyDown=${(e) => e.key === "Escape" && (e.stopPropagation(), setCreating(false))} />+ <button type="submit" class="btn primary" disabled=${!name.trim() || busy}>创建</button>+ </form>`}+ ${botsError && html`<div class="side-empty"><span>无法读取机器人列表</span><button type="button" class="btn" onClick=${reloadBots}>重试</button></div>`}+ ${!bots && !botsError && [0, 1, 2].map((k) => html`<div class="thread" key=${k}><span class="skel" style="width:34px;height:34px;border-radius:50%"></span><span style="flex:1;display:grid;gap:6px"><span class="skel" style="width:50%"></span><span class="skel" style="width:75%"></span></span></div>`)}+ ${bots && !bots.length && !creating && html`<div class="side-empty"><span>还没有机器人</span><button type="button" class="btn primary" onClick=${() => setCreating(true)}>新建机器人</button></div>`}+ ${bots && needle && !list.length && html`<p class="hint" style="padding:8px 10px">没有匹配的机器人</p>`}+ ${list.map((b) => {+ const sel = view === "chat" && b.id === selectedId;+ const n = pending[b.id] || 0;+ if (renaming === b.id)+ return html`<div class="thread sel" key=${b.id}><${BotAvatar} name=${b.name} id=${b.id} size=${34} />+ <input class="field" style="height:30px" value=${renameText} aria-label="新名称" ref=${renameRef}+ onInput=${(e) => setRenameText(e.target.value)} onBlur=${() => rename(b)}+ onKeyDown=${(e) => { if (e.key === "Enter") e.target.blur(); if (e.key === "Escape") { e.stopPropagation(); setRenaming(""); } }} /></div>`;+ return html`<button type="button" key=${b.id} class=${`thread${sel ? " sel" : ""}`} aria-current=${sel ? "page" : undefined}+ onClick=${() => onSelect(b.id)} onContextMenu=${(e) => { e.preventDefault(); setCtx({ bot: b, x: e.clientX, y: e.clientY }); }}>+ <span class="avatar-wrap"><${BotAvatar} name=${b.name} id=${b.id} size=${34} working=${!!working[b.id]} />${working[b.id] && html`<span class="working-dot" title="工作中"></span>`}</span>+ <span class="body">+ <span class="title" style="display:block">${b.name}</span>+ <span class="snip" style="display:block">${previews[b.id] || "还没有对话"}</span>+ </span>+ ${n > 0 && html`<span class="badge count" title=${`${n} 个待审批`}>${n}</span>`}+ </button>`;+ })}+ </nav>+ <div class="side-foot">+ <button type="button" class=${`account${view === "settings" ? " on" : ""}`} title="设置(⌘,)" aria-label="打开设置" onClick=${onOpenSettings}>+ <span class="me" aria-hidden="true">${me.slice(0, 1).toUpperCase()}</span>+ <span class="who">${me}</span>+ </button>+ </div>+ ${ctx && html`<${Menu} anchor=${{ left: ctx.x, right: ctx.x, top: ctx.y, bottom: ctx.y, width: 0 }} width=${200} label=${`${ctx.bot.name} 的操作`} onClose=${() => setCtx(null)}+ items=${[+ { label: "重命名", onSelect: () => { setRenameText(ctx.bot.name); setRenaming(ctx.bot.id); } },+ { label: "复制机器人 ID", onSelect: () => navigator.clipboard?.writeText(ctx.bot.id).then(() => toast("已复制")).catch(failed) },+ { sep: true },+ { label: "删除机器人", danger: true, onSelect: () => del(ctx.bot) },+ ]} />`}+ </aside>`;+}diff --git a/ui/style.css b/ui/style.cssdeleted file mode 100644index 86ff364..0000000--- a/ui/style.css+++ /dev/null@@ -1,564 +0,0 @@-/* anymodel bot — chat-first shell.- Taste framed-sheet density + Magpie greys/indigo (not Taste teal, not Grok orange).- Columns: left 280 | center 1fr | right 320 (collapsible). */--:root {- --bg: #f4f4f6;- --card: #ffffff;- --card-2: #f9f9fb;- --pill: #f1f1f4;- --pill-hover: #e9e9ee;- --line: #e3e3e8;- --line-2: #ececf0;- --fg: #1c1c21;- --fg-2: #4b4b53;- --muted: #85858d;- --faint: #b9b9c2;- --ctl-fg: #63636b;- --accent: #4f46e5; /* taste-skill-ignore: magpie indigo fusion — not Taste teal */- --accent-soft: #eeedfd;- --accent-fg: #ffffff;- --sel: #ecebfb;- --green: #189a58;- --green-soft: #e4f6ec;- --red: #d64545;- --red-soft: #fbe9e9;- --amber: #b45309;- --amber-soft: #fbf0df;- --primary: #1c1c21;- --primary-fg: #ffffff;- --active: #e9e9ee;- --bubble-user: #4f46e5; /* taste-skill-ignore: magpie indigo fusion — not Taste teal */- --bubble-user-fg: #ffffff;- --composer: #ffffff;- --font: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", "PingFang SC", "Microsoft YaHei", system-ui, sans-serif;- --code: ui-monospace, "SF Mono", Menlo, Consolas, monospace;- --left-w: 280px;- --right-w: 340px;- --radius: 10px;- --radius-lg: 16px;- --control-h: 32px;- --fs-body: 14px;- --fs-small: 12px;- --fs-title: 16px;-}--@media (prefers-color-scheme: dark) {- :root:not([data-theme="light"]) {- --bg: #1a1a1e;- --card: #232327;- --card-2: #1f1f23;- --pill: #2d2d33;- --pill-hover: #36363d;- --line: #333339;- --line-2: #2c2c32;- --fg: #ededf1;- --fg-2: #b9b9c1;- --muted: #8b8b94;- --faint: #56565f;- --ctl-fg: #a1a1aa;- --accent: #a5b4fc;- --accent-soft: #2b2c47;- --accent-fg: #14142a;- --sel: #33345a;- --green: #6fd99b;- --green-soft: #1e3a2b;- --red: #f28b82;- --red-soft: #45272a;- --amber: #f2b544;- --amber-soft: #3f3220;- --primary: #ededf1;- --primary-fg: #1a1a1e;- --active: #2d2d33;- --bubble-user: #4f46e5; /* taste-skill-ignore: magpie indigo fusion — not Taste teal */- --bubble-user-fg: #ffffff;- --composer: #2d2d33;- }-}-:root[data-theme="dark"] {- --bg: #1a1a1e; --card: #232327; --card-2: #1f1f23; --pill: #2d2d33; --pill-hover: #36363d;- --line: #333339; --line-2: #2c2c32; --fg: #ededf1; --fg-2: #b9b9c1; --muted: #8b8b94; --faint: #56565f; --ctl-fg: #a1a1aa;- --accent: #a5b4fc; --accent-soft: #2b2c47; --accent-fg: #14142a; --sel: #33345a;- --green: #6fd99b; --green-soft: #1e3a2b; --red: #f28b82; --red-soft: #45272a; --amber: #f2b544; --amber-soft: #3f3220;- --primary: #ededf1; --primary-fg: #1a1a1e; --active: #2d2d33;- --bubble-user: #4f46e5; --bubble-user-fg: #ffffff; --composer: #2d2d33; /* taste-skill-ignore: magpie indigo fusion — not Taste teal */-}-:root[data-theme="light"] {- --bg: #f4f4f6; --card: #ffffff; --card-2: #f9f9fb; --pill: #f1f1f4; --pill-hover: #e9e9ee;- --line: #e3e3e8; --line-2: #ececf0; --fg: #1c1c21; --fg-2: #4b4b53; --muted: #85858d; --faint: #b9b9c2; --ctl-fg: #63636b;- --accent: #4f46e5; --accent-soft: #eeedfd; --accent-fg: #ffffff; --sel: #ecebfb; /* taste-skill-ignore: magpie indigo fusion — not Taste teal */- --green: #189a58; --green-soft: #e4f6ec; --red: #d64545; --red-soft: #fbe9e9; --amber: #b45309; --amber-soft: #fbf0df;- --primary: #1c1c21; --primary-fg: #ffffff; --active: #e9e9ee;- --bubble-user: #4f46e5; --bubble-user-fg: #ffffff; --composer: #ffffff; /* taste-skill-ignore: magpie indigo fusion — not Taste teal */-}--*, *::before, *::after { box-sizing: border-box; }-html, body { height: 100%; }-body {- margin: 0;- font: var(--fs-body)/1.5 var(--font);- background: var(--bg);- color: var(--fg);- -webkit-font-smoothing: antialiased;-}-button, input, textarea, select { font: inherit; color: inherit; }-a { color: var(--accent); }-code, .mono { font-family: var(--code); font-size: .92em; font-variant-numeric: tabular-nums; }-.num { font-variant-numeric: tabular-nums; }--/* —— App shell: 3 columns —— */-.app {- display: grid;- grid-template-columns: var(--left-w) minmax(0, 1fr) var(--right-w);- height: 100vh;- background: var(--bg);-}-.app.right-collapsed { grid-template-columns: var(--left-w) minmax(0, 1fr) 0; }-.app.right-collapsed .right { display: none; }-.app.view-admin { grid-template-columns: var(--left-w) minmax(0, 1fr); }-.app.view-admin .right { display: none; }-.app.view-models { grid-template-columns: var(--left-w) minmax(0, 1fr); }-.app.view-models .right { display: none; }--.left, .center, .right {- min-height: 0;- min-width: 0;- display: flex;- flex-direction: column;-}-.left {- border-right: 1px solid var(--line);- background: var(--bg);-}-.center {- background: var(--card);-}-.right {- border-left: 1px solid var(--line);- background: var(--bg);-}--/* Left rail */-.brand {- display: flex;- align-items: center;- gap: 10px;- padding: 16px 16px 12px;-}-.brand-mark {- width: 32px; height: 32px;- border-radius: 10px;- background: var(--accent-soft);- color: var(--accent);- display: grid; place-items: center;- flex-shrink: 0;-}-.brand-mark svg { display: block; }-.brand-name { font-size: 14px; font-weight: 600; letter-spacing: -.01em; line-height: 1.2; }-.brand-sub { font-size: 11px; color: var(--muted); line-height: 1.2; }--.left-tools {- display: flex; gap: 6px; padding: 0 12px 10px;-}-.left-tools button, .icon-btn {- height: 30px; width: 30px;- display: grid; place-items: center;- border: 1px solid var(--line);- border-radius: 8px;- background: var(--card);- color: var(--ctl-fg);- cursor: pointer;- padding: 0;-}-.left-tools button:hover, .icon-btn:hover { background: var(--pill); color: var(--fg); }-.left-tools .grow-btn {- flex: 1; width: auto; padding: 0 10px;- font-size: 12px; font-weight: 500;- justify-content: center; display: flex; align-items: center; gap: 6px;-}--.left-scroll { flex: 1; overflow: auto; padding: 0 8px 8px; }-.sec-label {- font-size: 11px; color: var(--muted); font-weight: 500;- padding: 10px 8px 6px; letter-spacing: .01em;-}-.thread {- display: flex; gap: 10px; align-items: flex-start;- padding: 10px 10px; border-radius: 10px; cursor: pointer;- border: none; background: transparent; width: 100%; text-align: left; color: inherit;-}-.thread:hover { background: var(--pill); }-.thread.sel { background: var(--active); }-.thread-avatar {- width: 36px; height: 36px; border-radius: 50%;- background: var(--accent-soft); color: var(--accent);- display: grid; place-items: center; font-size: 13px; font-weight: 600;- flex-shrink: 0;-}--/* Lively bot faces (left rail + right head) */-.bot-face {- --look-x: 0;- --look-y: 0;- --face: hsl(var(--bot-hue, 240) 46% 78%);- --face-ink: #312e81;- --eye-white: #f8f8fc;- width: 36px; height: 36px;- border-radius: 50%;- flex-shrink: 0;- position: relative;- perspective: 120px;-}-@media (prefers-color-scheme: dark) {- :root:not([data-theme="light"]) .bot-face {- --face: hsl(var(--bot-hue, 240) 34% 38%);- --face-ink: #c7d2fe;- --eye-white: #1c1c28;- }-}-:root[data-theme="dark"] .bot-face {- --face: hsl(var(--bot-hue, 240) 34% 38%);- --face-ink: #c7d2fe;- --eye-white: #1c1c28;-}-:root[data-theme="light"] .bot-face {- --face: hsl(var(--bot-hue, 240) 46% 78%);- --face-ink: #312e81;- --eye-white: #f8f8fc;-}-.bot-face-3d {- width: 100%; height: 100%;- border-radius: 50%;- transform-style: preserve-3d;- transform:- translateX(calc(var(--look-x) * 1.6px))- rotateY(calc(var(--look-x) * 18deg))- rotateX(calc(var(--look-y) * -10deg));- transition: transform .14s ease-out;- will-change: transform;-}-.bot-face svg { display: block; width: 100%; height: 100%; overflow: visible; }-.bot-head {- fill: var(--face);- stroke: color-mix(in srgb, var(--face-ink) 18%, transparent);- stroke-width: 1;-}-.bot-eye-white {- fill: var(--eye-white);- transform-box: fill-box;- transform-origin: center;- animation: bot-eye-blink 5.2s calc(var(--bot-hue, 0) * 11ms) ease-in-out infinite;-}-.bot-pupils {- transform-box: view-box;- transform-origin: center;- transform: translate(calc(var(--look-x) * 2.4px), calc(var(--look-y) * 2.2px));- transition: transform .12s ease-out;-}-.bot-pupil { fill: var(--face-ink); }-.bot-mouth { stroke: var(--face-ink); stroke-width: 1.4; transition: opacity .2s ease; }-.bot-mouth-idle { fill: none; }-.bot-mouth-work { fill: var(--face-ink); stroke: none; opacity: 0; }-.bot-face.is-working .bot-mouth-idle { opacity: 0; }-.bot-face.is-working .bot-mouth-work { opacity: 1; }-.bot-face.is-working {- animation: bot-bob 1.6s ease-in-out infinite;-}-.bot-face.is-working .bot-eye-white {- animation: bot-eye-blink 2.4s calc(var(--bot-hue, 0) * 7ms) ease-in-out infinite;-}-.bot-face.is-working .bot-face-3d {- transform:- translateX(calc(var(--look-x) * 1.6px))- rotateY(calc(var(--look-x) * 18deg))- rotateX(calc(var(--look-y) * -10deg - 4deg));-}-.bot-face.is-working .bot-pupils {- animation: bot-dart 2.8s ease-in-out infinite;-}-@keyframes bot-eye-blink {- 0%, 41%, 47%, 100% { transform: scaleY(1); }- 44% { transform: scaleY(0.08); }-}-@keyframes bot-bob {- 0%, 100% { transform: translateY(0); }- 50% { transform: translateY(-1.5px); }-}-@keyframes bot-dart {- 0%, 100% { transform: translate(calc(var(--look-x) * 2.4px), calc(var(--look-y) * 2.2px)); }- 22% { transform: translate(calc(var(--look-x) * 2.4px + 1.4px), calc(var(--look-y) * 2.2px - 0.6px)); }- 48% { transform: translate(calc(var(--look-x) * 2.4px - 1.2px), calc(var(--look-y) * 2.2px + 0.4px)); }- 70% { transform: translate(calc(var(--look-x) * 2.4px + 0.4px), calc(var(--look-y) * 2.2px + 1px)); }-}-@media (prefers-reduced-motion: reduce) {- .bot-face,- .bot-face .bot-eye-white,- .bot-face.is-working,- .bot-face.is-working .bot-eye-white,- .bot-face.is-working .bot-pupils {- animation: none !important;- }- .bot-face-3d, .bot-pupils { transition: none; }-}--.thread-body { min-width: 0; flex: 1; }-.thread-title {- font-size: 13px; font-weight: 500; color: var(--fg);- white-space: nowrap; overflow: hidden; text-overflow: ellipsis;-}-.thread-snip {- font-size: 12px; color: var(--muted);- white-space: nowrap; overflow: hidden; text-overflow: ellipsis;- margin-top: 2px;-}-.thread-meta { font-size: 11px; color: var(--faint); margin-top: 2px; }--.left-foot {- border-top: 1px solid var(--line);- padding: 10px 12px;- display: flex; flex-direction: column; gap: 8px;-}-.admin-links { display: flex; flex-wrap: wrap; gap: 4px; }-.admin-links button {- height: 28px; padding: 0 10px; border-radius: 999px;- border: 1px solid transparent; background: transparent;- color: var(--ctl-fg); font-size: 12px; cursor: pointer;-}-.admin-links button:hover, .admin-links button.on {- background: var(--pill); color: var(--fg);-}-.theme-toggle {- display: flex; gap: 3px; background: var(--pill); border-radius: 8px; padding: 3px;-}-.theme-toggle button {- flex: 1; height: 26px; border: none; border-radius: 6px;- background: transparent; color: var(--ctl-fg); cursor: pointer; font-size: 11px;-}-.theme-toggle button.on {- background: var(--card); color: var(--fg);- box-shadow: 0 1px 2px rgba(0,0,0,.08); /* taste-skill-ignore: focus ring / floating control only */-}--/* Center chat */-.chat-head {- height: 52px; flex-shrink: 0;- display: flex; align-items: center; justify-content: space-between;- gap: 12px; padding: 0 16px;- border-bottom: 1px solid var(--line);- background: var(--card);-}-.chat-head-title { font-size: var(--fs-title); font-weight: 600; letter-spacing: -.01em; }-.chat-head-sub { font-size: 12px; color: var(--muted); }-.chat-head-actions { display: flex; gap: 6px; align-items: center; }--.transcript {- flex: 1; overflow: auto; padding: 20px 24px 12px;- display: flex; flex-direction: column; gap: 12px;-}-.transcript .empty-chat {- margin: auto; text-align: center; color: var(--muted); max-width: 360px;- padding: 32px 16px;-}-.transcript .empty-chat h2 {- margin: 0 0 8px; font-size: 18px; font-weight: 600; color: var(--fg);-}-.msg-row { display: flex; flex-direction: column; gap: 4px; max-width: 720px; width: 100%; margin: 0 auto; }-.msg-row.user { align-items: flex-end; }-.msg-row.assistant { align-items: flex-start; }-.msg-bubble {- max-width: 85%;- padding: 10px 14px;- border-radius: 14px;- white-space: pre-wrap; word-break: break-word;- font-size: 14px; line-height: 1.5;-}-.msg-row.user .msg-bubble {- background: var(--bubble-user); color: var(--bubble-user-fg);- border-bottom-right-radius: 4px;-}-.msg-row.assistant .msg-bubble {- background: transparent; color: var(--fg); padding: 4px 2px;-}-.msg-row.assistant .msg-bubble.cardish {- background: var(--card-2); border: 1px solid var(--line); padding: 10px 14px;-}-.msg-meta { font-size: 11px; color: var(--muted); padding: 0 4px; }-.msg-progress {- display: flex; align-items: center; gap: 8px;- font-size: 13px; color: var(--muted); padding: 4px 2px;- max-width: 720px; width: 100%; margin: 0 auto;-}-.msg-progress .dot {- width: 8px; height: 8px; border-radius: 50%; background: var(--accent);- animation: pulse 1.2s ease-in-out infinite;-}-@keyframes pulse { 0%,100%{ opacity:.35 } 50%{ opacity:1 } }--.composer-wrap {- flex-shrink: 0; padding: 12px 20px 16px;- background: var(--card);-}-.composer {- display: flex; align-items: flex-end; gap: 8px;- background: var(--composer);- border: 1px solid var(--line);- border-radius: 14px;- padding: 8px 10px;-}-.composer:focus-within {- border-color: var(--accent);- box-shadow: 0 0 0 3px var(--accent-soft); /* taste-skill-ignore: focus ring / floating control only */-}-.composer textarea {- flex: 1; border: none; background: transparent; resize: none;- min-height: 24px; max-height: 160px; padding: 6px 4px;- outline: none; line-height: 1.45;-}-.composer .send {- height: 32px; min-width: 64px; padding: 0 14px;- border-radius: 10px; border: none;- background: var(--primary); color: var(--primary-fg);- font-weight: 500; cursor: pointer;-}-.composer .send:disabled { opacity: .4; cursor: default; }-.composer-hint {- margin-top: 6px; font-size: 11px; color: var(--muted); padding: 0 4px;-}--/* Right panel */-.right-head {- height: 52px; flex-shrink: 0;- display: flex; align-items: center; justify-content: space-between;- padding: 0 14px; border-bottom: 1px solid var(--line);-}-.right-tabs {- display: flex; gap: 2px; padding: 8px 10px 0; flex-shrink: 0;- border-bottom: 1px solid var(--line);-}-.right-tabs button {- height: 32px; padding: 0 12px; border: none; background: transparent;- color: var(--ctl-fg); font-size: 13px; cursor: pointer;- border-bottom: 2px solid transparent; border-radius: 0; margin-bottom: -1px;-}-.right-tabs button.on {- color: var(--fg); font-weight: 500; border-bottom-color: var(--accent);-}-.right-body { flex: 1; overflow: auto; padding: 14px; }--/* Shared controls / cards inside panels & admin */-.card {- background: var(--card);- border: 1px solid var(--line);- border-radius: var(--radius);- padding: 14px 16px;- margin-bottom: 12px;- box-shadow: none; /* taste-skill-ignore: focus ring / floating control only */-}-.card > h3 { margin: 0 0 10px; font-size: 14px; font-weight: 600; }-.card h4 { margin: 12px 0 6px; font-size: 12px; font-weight: 500; color: var(--fg-2); }-.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }-.grow { flex: 1; min-width: 0; }-.muted { color: var(--muted); font-size: var(--fs-small); }-label {- display: block; margin: 10px 0 5px;- color: var(--fg-2); font-size: var(--fs-small); font-weight: 500;-}-label.row { margin: 6px 0; font-weight: 400; color: var(--fg); gap: 8px; }-input, textarea, select {- width: 100%; height: var(--control-h); padding: 0 10px;- border: 1px solid var(--line); border-radius: 8px;- background: var(--card); color: var(--fg);-}-textarea { height: auto; min-height: 80px; padding: 8px 10px; resize: vertical; line-height: 1.45; }-input:focus, textarea:focus, select:focus {- outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); /* taste-skill-ignore: focus ring / floating control only */-}-input[type="checkbox"] { width: 15px; height: 15px; padding: 0; accent-color: var(--accent); }-button {- height: var(--control-h); padding: 0 12px; border-radius: 8px;- border: 1px solid var(--line); background: var(--card); color: var(--fg);- cursor: pointer; font-size: 13px; font-weight: 500; white-space: nowrap;-}-button:hover:not(:disabled) { background: var(--pill); }-button.pri { background: var(--primary); border-color: var(--primary); color: var(--primary-fg); }-button.pri:hover:not(:disabled) { filter: brightness(1.08); }-button.danger { color: var(--red); }-button.danger:hover:not(:disabled) { background: var(--red-soft); }-button:disabled { opacity: .45; cursor: default; }-button.ghost { border-color: transparent; background: transparent; color: var(--ctl-fg); }-button.ghost:hover:not(:disabled) { background: var(--pill); color: var(--fg); }--.badge {- display: inline-flex; align-items: center; height: 20px; padding: 0 8px;- border-radius: 999px; font-size: 11px; font-weight: 500;- background: var(--pill); color: var(--fg-2); white-space: nowrap; flex: none;-}-.badge.connected, .badge.running, .badge.confirmed, .badge.allowed, .badge.answered {- background: var(--green-soft); color: var(--green);-}-.badge.error, .badge.failed, .badge.expired, .badge.rejected, .badge.cancelled {- background: var(--red-soft); color: var(--red);-}-.badge.connecting, .badge.starting, .badge.restarting, .badge.wait, .badge.scaned,-.badge.need_verifycode, .badge.fetching, .badge.pending {- background: var(--amber-soft); color: var(--amber);-}-.badge.disabled, .badge.stopped, .badge.paused, .badge.idle, .badge.login_required {- background: var(--pill); color: var(--muted);-}--.list .item {- padding: 10px 12px; border-bottom: 1px solid var(--line-2); cursor: pointer;-}-.list .item:last-child { border-bottom: none; }-.list .item:hover { background: var(--card-2); }-.list .item.sel { background: var(--sel); }-.notice {- padding: 8px 12px; border-radius: 8px; margin-bottom: 8px; font-size: 13px;- background: var(--amber-soft); color: var(--amber);- border: 1px solid color-mix(in srgb, var(--amber) 25%, transparent);-}-.empty {- border: 1px dashed var(--line); border-radius: 8px; padding: 14px; color: var(--muted); font-size: 13px;-}-.qr {- width: 200px; height: 200px; image-rendering: pixelated;- background: #fff; padding: 8px; border-radius: 8px; border: 1px solid var(--line);-}-details { margin-top: 8px; }-details summary { cursor: pointer; color: var(--ctl-fg); font-size: 13px; }-details summary:hover { color: var(--fg); }-table { width: 100%; border-collapse: collapse; font-size: 13px; }-th {- text-align: left; font-size: 11px; font-weight: 400; color: var(--muted);- padding: 6px 8px; border-bottom: 1px solid var(--line);-}-td { padding: 8px; border-bottom: 1px solid var(--line-2); vertical-align: top; }-.cols { display: grid; grid-template-columns: 260px 1fr; gap: 12px; align-items: start; }--/* Admin / models overlay views in center */-.admin-pane {- flex: 1; overflow: auto; padding: 20px 24px; background: var(--card);-}-.admin-pane.bleed { padding: 0; overflow: hidden; }-.page-head { margin-bottom: 16px; }-.page-head h2 { margin: 0; font-size: 20px; font-weight: 600; letter-spacing: -.02em; }-.page-head .sub { margin: 4px 0 0; font-size: 13px; color: var(--muted); }-.kpi-strip {- display: grid; grid-template-columns: repeat(4, 1fr);- border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; margin-bottom: 12px;-}-.kpi-strip .kpi { padding: 12px 14px; border-right: 1px solid var(--line); }-.kpi-strip .kpi:last-child { border-right: none; }-.kpi-strip .kpi .lbl { font-size: 12px; color: var(--muted); margin-bottom: 4px; }-.kpi-strip .kpi .val { font-size: 20px; font-variant-numeric: tabular-nums; letter-spacing: -.02em; }-iframe.magpie { border: 0; width: 100%; height: 100%; display: block; background: var(--bg); }--@media (max-width: 960px) {- .app, .app.right-collapsed, .app.view-admin, .app.view-models {- grid-template-columns: 1fr;- grid-template-rows: auto 1fr;- }- .left { border-right: none; border-bottom: 1px solid var(--line); max-height: 40vh; }- .right { display: none !important; }-}diff --git a/ui/tokens.css b/ui/tokens.cssnew file mode 100644index 0000000..2ab2604--- /dev/null+++ b/ui/tokens.css@@ -0,0 +1,112 @@+/* AnyModelBot design tokens.+ Neutral greys, radii and motion adapted from yetone/magpie internal/gui/assets/app.css (MIT, © 2026 yetone).+ Accent = Modelflare signal yellow-green #d7ff00 with ink #161a00 (modelflare.dev / docs.modelflare.dev);+ light-mode foreground accent = Modelflare pricing olive #5f711c (the yellow-green is 1.15:1 on white).+ Derived (not from Modelflare's CSS): --accent-hover/--accent-press used as states, --sel, --bubble-*.++ Dark values are defined once: <html data-theme> always holds the resolved theme+ ("light" | "dark"), set before first paint by index.html and kept in sync by lib/theme.js. */+:root {+ --bg: #f4f4f6;+ --card: #ffffff;+ --card-2: #f9f9fb;+ --pill: #f1f1f4;+ --pill-hover: #e9e9ee;+ --seg-track: #e6e6eb;+ --seg-edge: 0 1px 2px rgba(0, 0, 0, .14), 0 0 0 .5px rgba(0, 0, 0, .08);+ --line: #e3e3e8;+ --line-2: #ececf0;+ --fg: #1c1c21;+ --fg-2: #4b4b53;+ --muted: #85858d;+ --faint: #b9b9c2;+ --ctl-fg: #63636b;++ /* Modelflare brand */+ --accent: #5f711c; /* text, links, icons, focus ring */+ --accent-strong: #465612; /* link hover */+ --accent-solid: #d7ff00; /* filled brand surfaces */+ --on-accent: #161a00; /* ink on --accent-solid, 15.39:1 */+ --accent-hover: #e6ff4d;+ --accent-press: #c7ef00;+ --accent-soft: #f1f4e9;+ --accent-line: #78960059;+ --sel: #edf7b8;+ --bubble-top: #daff14;+ --bubble-bottom: #d7ff00;++ --green: #189a58;+ --green-soft: #e4f6ec;+ --red: #d64545;+ --red-soft: #fbe9e9;+ --amber: #b45309;+ --amber-soft: #fbf0df;++ --pop-bg: rgba(255, 255, 255, .94);+ --shadow: 0 16px 44px rgba(20, 22, 30, .16), 0 2px 8px rgba(20, 22, 30, .06), 0 0 0 .5px rgba(20, 22, 30, .1);+ --float-edge: 0 1px 3px rgba(0, 0, 0, .08), 0 0 0 1px #ededed;++ /* chat surfaces: pure neutral greys */+ --chat-bg: #fcfcfc;+ --side-bg: #f5f5f5;+ --side-hover: #ececec;+ --side-active: #e4e4e4;+ --bubble-ai: #f0f0f0;+ --placeholder: #a4a4a4;+ --composer-bg: #ffffff;++ --font: -apple-system, BlinkMacSystemFont, "SF Pro Text", "PingFang SC", "Segoe UI", "Microsoft YaHei UI", system-ui, sans-serif;+ --code: ui-monospace, "SF Mono", Menlo, Consolas, "Microsoft YaHei UI", monospace;+ --ease: cubic-bezier(.2, .8, .2, 1);+ --side-w: 280px;+ --panel-w: 320px;+ --col-w: 960px;+ --bubble-w: 560px;+ color-scheme: light;+}+:root.win {+ --font: "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif;+ --code: "Cascadia Mono", Consolas, "Microsoft YaHei UI", "Microsoft YaHei", monospace;+}+:root[data-theme="dark"] {+ --bg: #1a1a1e;+ --card: #232327;+ --card-2: #1f1f23;+ --pill: #2d2d33;+ --pill-hover: #36363d;+ --seg-track: rgba(255, 255, 255, .035);+ --seg-edge: inset 0 .5px 0 rgba(255, 255, 255, .08), 0 1px 2px rgba(0, 0, 0, .3);+ --line: #333339;+ --line-2: #2c2c32;+ --fg: #ededf1;+ --fg-2: #b9b9c1;+ --muted: #8b8b94;+ --faint: #56565f;+ --ctl-fg: #a1a1aa;++ --accent: #d7ff00;+ --accent-strong: #e9ff66;+ --accent-soft: #d7ff0014;+ --accent-line: #d7ff004d;+ --sel: #31361a;++ --green: #6fd99b;+ --green-soft: #1e3a2b;+ --red: #f28b82;+ --red-soft: #45272a;+ --amber: #f2b544;+ --amber-soft: #3f3220;++ --pop-bg: rgba(38, 38, 43, .96);+ --shadow: 0 16px 44px rgba(0, 0, 0, .55), 0 2px 8px rgba(0, 0, 0, .3), 0 0 0 .5px rgba(255, 255, 255, .1);+ --float-edge: 0 1px 3px rgba(0, 0, 0, .4), 0 0 0 1px #333339;++ --chat-bg: #1c1c20;+ --side-bg: #1a1a1e;+ --side-hover: #26262b;+ --side-active: #2d2d33;+ --bubble-ai: #2d2d33;+ --placeholder: #6e6e77;+ --composer-bg: #26262b;+ color-scheme: dark;+}