🤖 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
feat: 界面中英双语、上手清单、系统通知与发送键(合入本地工作区,适配到最新 master)
dyk980a94a289aab5
diff --git a/.env.example b/.env.exampleindex 529a613..6b8a22e 100644--- a/.env.example+++ b/.env.example@@ -38,5 +38,9 @@# AMB_PWSH_HOME= # 安装位置# AMB_PWSH_IGNORE_SYSTEM=1 # 仅测试:不用系统里的 PowerShell(CI 用它验证内置副本)+# 语言:界面设置里选"跟随系统"时用的语言(zh-CN | en)。不设时看 LC_ALL / LANG,没有或是 C / POSIX 时用简体中文。+# 托盘菜单、服务端报错、机器人发到微信 / 飞书的系统消息都跟着应用语言;界面里可以随时切换+# AMB_LANG=zh-CN+# 日志级别 debug|info|warn|error# AMB_LOG_LEVEL=infodiff --git a/.gitignore b/.gitignoreindex 4584f80..7edb072 100644--- a/.gitignore+++ b/.gitignore@@ -9,3 +9,5 @@ data/*.logtest-results/.DS_Store+# 在仓库根目录误跑 Astro 时生成的类型文件(官网的在 site/.astro,由 site/.gitignore 忽略)+.astro/diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex db99205..63626c0 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -62,6 +62,7 @@ npm run setup # 拉取 vendor/magpie 子模块并编译到 build/bin/- 品牌强调色是荧光黄绿 `#d7ff00`,界面里不引入蓝色。- 管理界面是 Preact + htm,没有构建步骤,请不要引入打包工具或需要编译的前端依赖。- 浅色和深色主题都要看一遍。+- 界面上的文字不直接写在代码里:放进 `ui/locales/zh-CN/` 和 `ui/locales/en/`(两种语言都写),代码里用 `t()`;提交前跑 `node scripts/i18n-check.mjs`。中英两种语言都看一遍,英文通常更长。## 第三方代码与依赖diff --git a/CONTRIBUTING_en.md b/CONTRIBUTING_en.mdindex 49deb53..37faa70 100644--- a/CONTRIBUTING_en.md+++ b/CONTRIBUTING_en.md@@ -62,6 +62,7 @@ Repository layout, packaging and channel setup are covered in the [development g- The brand accent is fluorescent yellow-green `#d7ff00`; do not introduce blue into the UI.- The console is Preact + htm with no build step; please do not add a bundler or front-end dependencies that need compiling.- Check both the light and dark themes.+- Don't hard-code UI text: add it to `ui/locales/zh-CN/` and `ui/locales/en/` (both languages) and use `t()`; run `node scripts/i18n-check.mjs` before submitting. Check both languages — English is usually longer.## Third-party code and dependenciesdiff --git a/anymodelbot_design/onboarding/Main.html b/anymodelbot_design/onboarding/Main.htmlnew file mode 100644index 0000000..2711495--- /dev/null+++ b/anymodelbot_design/onboarding/Main.html@@ -0,0 +1,232 @@+<!doctype html>+<html lang="zh-CN">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>上手清单 · 对话页空状态 · 新手引导预览</title>+<style>+body{margin:0;background:#060706}+*,*::before,*::after{box-sizing:border-box}+button{font:inherit;color:inherit;border:0;background:none;padding:0;cursor:pointer}+input,textarea{font:inherit}+a{color:#d7ff00}a:hover{color:#e9ff66}+</style>+<link rel="stylesheet" href="css/bots.css">+<link rel="stylesheet" href="css/proto.css">+</head>+<body data-page="main">+<div style="min-height: 100vh; display: flex; flex-wrap: wrap; background: #060706; color: #fafaf7; font-family: Geist, 'Noto Sans SC', 'PingFang SC', system-ui, sans-serif; font-size: 14px; line-height: 1.5">++ <!-- 侧栏 -->+ <aside aria-label="机器人" style="flex: 1 1 248px; max-width: 100%; display: flex; flex-direction: column; gap: 6px; padding: 14px 12px 12px; background: #0a0b0a; border-right: 1px solid rgba(255,255,255,.10)">+ <div aria-hidden="true" style="display: flex; gap: 8px; padding: 4px 6px 14px">+ <span style="width: 11px; height: 11px; border-radius: 50%; background: rgba(127,127,127,.45)"></span>+ <span style="width: 11px; height: 11px; border-radius: 50%; background: rgba(127,127,127,.45)"></span>+ <span style="width: 11px; height: 11px; border-radius: 50%; background: rgba(127,127,127,.45)"></span>+ </div>+ <button type="button" style="display: flex; align-items: center; gap: 10px; min-height: 40px; padding: 0 10px; border-radius: 10px; color: #a1a1aa; font-size: 13.5px">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>+ 新建机器人+ </button>+ <div style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; letter-spacing: .08em; color: #a1a1aa; padding: 10px 10px 4px">机器人</div>+ <a href="Main.html" style="display: flex; align-items: center; gap: 10px; min-height: 52px; padding: 6px 10px; border-radius: 12px; background: rgba(255,255,255,.06); color: #fafaf7; text-decoration: none">+ <span class="face" data-char="blue" style="width: 34px; height: 34px; flex: none"></span>+ <span style="display: flex; flex-direction: column; min-width: 0">+ <span style="font-weight: 600; font-size: 14px">小蓝</span>+ <span style="color: #a1a1aa; font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">还没有消息</span>+ </span>+ </a>+ <div style="flex: 1"></div>+ <!-- 清单的常驻入口 -->+ <button type="button" style="display: flex; align-items: center; gap: 10px; min-height: 44px; padding: 0 12px; border-radius: 12px; background: rgba(215,255,0,.10); box-shadow: inset 0 0 0 1px rgba(215,255,0,.30); color: #fafaf7; font-size: 13.5px; text-align: left">+ <span style="display: flex; gap: 3px" aria-hidden="true">+ <span style="width: 5px; height: 14px; border-radius: 2px; background: rgba(255,255,255,.16)"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: rgba(255,255,255,.16)"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: rgba(255,255,255,.16)"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: rgba(255,255,255,.16)"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: rgba(255,255,255,.16)"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: rgba(255,255,255,.16)"></span>+ </span>+ <span style="flex: 1; font-weight: 500">上手清单</span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">0 / 6</span>+ </button>+ <button type="button" style="display: flex; align-items: center; gap: 10px; min-height: 48px; padding: 0 10px; border-radius: 12px; text-align: left">+ <span aria-hidden="true" style="display: grid; place-items: center; width: 28px; height: 28px; border-radius: 50%; background: #d7ff00; color: #161a00; font-weight: 700; font-size: 13px">Z</span>+ <span style="flex: 1; font-size: 13.5px">我的账户</span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12.5px; color: #a1a1aa">$12.40</span>+ </button>+ </aside>++ <!-- 对话区 -->+ <main style="flex: 999 1 560px; min-width: 0; display: flex; flex-direction: column; min-height: 100vh">+ <header style="display: flex; align-items: center; gap: 8px; height: 54px; padding: 0 16px; border-bottom: 1px solid rgba(255,255,255,.10)">+ <button type="button" style="display: inline-flex; align-items: center; gap: 8px; height: 34px; padding: 0 12px 0 6px; border-radius: 999px; background: rgba(255,255,255,.05); box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); font-weight: 600; font-size: 14px">+ <span class="face" data-char="blue" style="width: 24px; height: 24px"></span>+ 小蓝+ </button>+ <span style="flex: 1"></span>+ <button type="button" aria-label="开始新的一段对话" style="display: grid; place-items: center; width: 36px; height: 36px; border-radius: 50%; color: #a1a1aa">+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>+ </button>+ <button type="button" aria-label="信息面板" style="display: grid; place-items: center; width: 36px; height: 36px; border-radius: 50%; color: #a1a1aa">+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="16" rx="3"/><path d="M15 4v16"/></svg>+ </button>+ </header>++ <div id="scroll" style="flex: 1; overflow: auto">+ <div id="log" hidden style="max-width: 720px; margin: 0 auto; padding: 32px 24px 24px; display: flex; flex-direction: column; gap: 22px"></div>+ <div id="intro" style="max-width: 720px; margin: 0 auto; padding: 72px 24px 24px">++ <!-- 章节头:细线 + 编号 + 两段式标题,主持机器人蹲在细线右端 -->+ <header style="position: relative; padding-top: 16px; border-top: 1px solid rgba(255,255,255,.10)">+ <span class="face" data-char="blue" style="position: absolute; right: 0; bottom: calc(100% - 6px); width: 76px; height: 76px"></span>+ <p style="display: flex; align-items: baseline; gap: 12px; margin: 0 0 22px; font-size: 13px; letter-spacing: .08em; color: #a1a1aa">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; letter-spacing: .04em; color: #d7ff00">0 / 6</span>+ <span style="color: rgba(255,255,255,.18)">/</span>+ 上手清单+ </p>+ <h1 style="margin: 0; font-size: 34px; line-height: 1.2; font-weight: 600; letter-spacing: -.012em">+ <span style="display: block">嗨,我是小蓝。</span>+ <span style="display: block; color: #a1a1aa">花 5 分钟,看看我能帮你做什么。</span>+ </h1>+ </header>++ <div aria-hidden="true" style="display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 6px; margin: 28px 0 16px">+ <span style="height: 4px; border-radius: 2px; background: rgba(215,255,0,.45)"></span>+ <span style="height: 4px; border-radius: 2px; background: rgba(255,255,255,.10)"></span>+ <span style="height: 4px; border-radius: 2px; background: rgba(255,255,255,.10)"></span>+ <span style="height: 4px; border-radius: 2px; background: rgba(255,255,255,.10)"></span>+ <span style="height: 4px; border-radius: 2px; background: rgba(255,255,255,.10)"></span>+ <span style="height: 4px; border-radius: 2px; background: rgba(255,255,255,.10)"></span>+ </div>++ <ol style="list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px">+ <!-- 1 当前项:展开 -->+ <li style="display: flex; gap: 14px; padding: 18px 18px 18px 16px; border-radius: 20px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(215,255,0,.35)">+ <span aria-hidden="true" style="flex: none; display: grid; place-items: center; width: 26px; height: 26px; border-radius: 50%; box-shadow: inset 0 0 0 1.5px #d7ff00; color: #d7ff00; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px">1</span>+ <div style="flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 10px">+ <div>+ <div style="font-size: 16px; font-weight: 600">跟小蓝打个招呼</div>+ <div style="color: #a1a1aa; margin-top: 2px">在这里直接和机器人聊天,回复会边写边出来。</div>+ </div>+ <div style="display: flex; flex-wrap: wrap; gap: 8px 18px; color: #a1a1aa; font-size: 13px">+ <span><kbd style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11.5px; padding: 2px 6px; border-radius: 6px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); color: #fafaf7">Enter</kbd> 发送</span>+ <span><kbd style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11.5px; padding: 2px 6px; border-radius: 6px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); color: #fafaf7">Esc</kbd> 让它停下</span>+ <span><kbd style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11.5px; padding: 2px 6px; border-radius: 6px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); color: #fafaf7">/</kbd> 看全部命令</span>+ </div>+ <div style="display: flex; flex-wrap: wrap; align-items: center; gap: 12px; padding: 10px 10px 10px 14px; border-radius: 14px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; letter-spacing: .06em; color: #a1a1aa">试试这句</span>+ <span style="flex: 1; min-width: 160px; font-size: 14.5px">你能帮我做什么?</span>+ <button type="button" id="try" style="display: inline-flex; align-items: center; gap: 8px; min-height: 36px; padding: 0 16px; border-radius: 999px; background: #d7ff00; color: #161a00; font-weight: 600; font-size: 14px">+ 发送这句+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 19V5M5 12l7-7 7 7"/></svg>+ </button>+ </div>+ </div>+ </li>++ <!-- 2–6 待做:整行可点,进入对应步骤 -->+ <li>+ <a href="Step2-Model.html" style="display: flex; align-items: center; gap: 14px; padding: 14px 18px 14px 16px; border-radius: 16px; color: #fafaf7; text-decoration: none">+ <span aria-hidden="true" style="flex: none; display: grid; place-items: center; width: 26px; height: 26px; border-radius: 50%; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); color: #a1a1aa; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px">2</span>+ <span style="flex: 1; min-width: 0">+ <span style="display: block; font-size: 15px; font-weight: 500">换个模型</span>+ <span style="display: block; color: #a1a1aa; font-size: 13.5px">一个账户就能用 GPT、Claude、Gemini 等模型,不同的事交给不同的模型。</span>+ </span>+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#a1a1aa" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 6 6 6-6 6"/></svg>+ </a>+ </li>+ <li>+ <a href="Step3-Weixin.html" style="display: flex; align-items: center; gap: 14px; padding: 14px 18px 14px 16px; border-radius: 16px; color: #fafaf7; text-decoration: none">+ <span aria-hidden="true" style="flex: none; display: grid; place-items: center; width: 26px; height: 26px; border-radius: 50%; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); color: #a1a1aa; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px">3</span>+ <span style="flex: 1; min-width: 0">+ <span style="display: block; font-size: 15px; font-weight: 500">把小蓝接到微信</span>+ <span style="display: block; color: #a1a1aa; font-size: 13.5px">扫码后在微信里直接私聊它,不用装新 App;电脑开着它就在线。</span>+ </span>+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#a1a1aa" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 6 6 6-6 6"/></svg>+ </a>+ </li>+ <li>+ <a href="Step4-Hands.html" style="display: flex; align-items: center; gap: 14px; padding: 14px 18px 14px 16px; border-radius: 16px; color: #fafaf7; text-decoration: none">+ <span aria-hidden="true" style="flex: none; display: grid; place-items: center; width: 26px; height: 26px; border-radius: 50%; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); color: #a1a1aa; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px">4</span>+ <span style="flex: 1; min-width: 0">+ <span style="display: block; font-size: 15px; font-weight: 500">让它动手做件事</span>+ <span style="display: block; color: #a1a1aa; font-size: 13.5px">在自己的工作区里写文件、跑命令,做好的文件交给你。</span>+ </span>+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#a1a1aa" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 6 6 6-6 6"/></svg>+ </a>+ </li>+ <li>+ <a href="Step5-Memory.html" style="display: flex; align-items: center; gap: 14px; padding: 14px 18px 14px 16px; border-radius: 16px; color: #fafaf7; text-decoration: none">+ <span aria-hidden="true" style="flex: none; display: grid; place-items: center; width: 26px; height: 26px; border-radius: 50%; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); color: #a1a1aa; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px">5</span>+ <span style="flex: 1; min-width: 0">+ <span style="display: block; font-size: 15px; font-weight: 500">让它记住你</span>+ <span style="display: block; color: #a1a1aa; font-size: 13.5px">告诉它你的习惯,开新对话、到微信里它都记得。</span>+ </span>+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#a1a1aa" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 6 6 6-6 6"/></svg>+ </a>+ </li>+ <li>+ <a href="Step6-Media.html" style="display: flex; align-items: center; gap: 14px; padding: 14px 18px 14px 16px; border-radius: 16px; color: #fafaf7; text-decoration: none">+ <span aria-hidden="true" style="flex: none; display: grid; place-items: center; width: 26px; height: 26px; border-radius: 50%; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); color: #a1a1aa; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px">6</span>+ <span style="flex: 1; min-width: 0">+ <span style="display: block; font-size: 15px; font-weight: 500">生成一张图</span>+ <span style="display: block; color: #a1a1aa; font-size: 13.5px">画图、做视频;每次生成前先问你,确认了才花钱。</span>+ </span>+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#a1a1aa" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 6 6 6-6 6"/></svg>+ </a>+ </li>+ </ol>++ <div style="display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px; margin-top: 18px; padding-top: 14px; border-top: 1px solid rgba(255,255,255,.10)">+ <span style="color: #a1a1aa; font-size: 13px">收起后,清单在左下角,随时能打开。</span>+ <button type="button" id="collapse" style="min-height: 36px; padding: 0 14px; border-radius: 999px; color: #fafaf7; font-size: 14px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">收起清单</button>+ </div>+ </div>+ </div>++ <!-- 输入框:第一项进行中时给出聚焦光圈 -->+ <div style="padding: 0 24px 24px">+ <div id="composer" class="spot-soft" style="position: relative; max-width: 720px; margin: 0 auto; border-radius: 18px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <section id="coach" hidden aria-label="上手引导" style="position: absolute; right: 0; bottom: calc(100% + 22px); z-index: 3; width: 340px; max-width: calc(100vw - 32px); padding: 20px 20px 16px; border-radius: 20px; background: #0b0b10; box-shadow: 0 0 0 1px rgba(255,255,255,.18), 0 30px 80px -20px rgba(0,0,0,.75)">+ <span class="face" data-char="blue" style="position: absolute; right: 18px; top: -40px; width: 52px; height: 52px"></span>+ <p style="display: flex; align-items: center; gap: 10px; margin: 0 0 12px; font-size: 12.5px; letter-spacing: .06em; color: #a1a1aa">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">01 / 06</span>上手清单+ <span style="display: inline-flex; align-items: center; gap: 4px; height: 22px; padding: 0 8px; border-radius: 999px; background: #d7ff00; color: #161a00; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; letter-spacing: 0">+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" class="tick"><path d="m5 12 5 5 9-10"/></svg>完成+ </span>+ </p>+ <h2 style="margin: 0 0 6px; font-size: 19px; font-weight: 600; letter-spacing: -.01em">清单收进了左下角</h2>+ <p style="margin: 0 0 16px; color: #a1a1aa; line-height: 1.7">随时点左下角的「上手清单」接着做。下一项:换个模型,同一个问题换个脑子问问。</p>+ <div style="display: flex; align-items: center; justify-content: space-between; gap: 8px">+ <button type="button" id="c-later" style="min-height: 36px; padding: 0 4px; color: #a1a1aa; font-size: 13.5px">稍后再说</button>+ <a href="Step2-Model.html" style="display: inline-flex; align-items: center; gap: 8px; min-height: 36px; padding: 0 16px; border-radius: 999px; background: #d7ff00; color: #161a00; font-weight: 600; font-size: 14px; text-decoration: none">下一步</a>+ </div>+ </section>+ <textarea id="input" class="input" rows="1" aria-label="消息" placeholder="给「小蓝」发消息,/ 查看命令"></textarea>+ <div style="display: flex; align-items: center; gap: 6px; padding: 6px 8px 8px">+ <button type="button" aria-label="更多操作" style="display: grid; place-items: center; width: 32px; height: 32px; border-radius: 50%; color: #a1a1aa">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>+ </button>+ <button type="button" style="display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 10px; border-radius: 999px; color: #a1a1aa; font-size: 12.5px">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3l7 3v6c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6z"/></svg>+ 工作区可写+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>+ </button>+ <span style="flex: 1"></span>+ <button type="button" style="display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 10px; border-radius: 999px; color: #a1a1aa; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12.5px">+ claude-sonnet-5-5+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>+ </button>+ <button type="button" id="send" aria-label="发送" style="display: grid; place-items: center; width: 32px; height: 32px; border-radius: 50%; background: #161a00; color: #d7ff00; opacity: .5">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 19V5M5 12l7-7 7 7"/></svg>+ </button>+ </div>+ </div>+ </div>+ </main>+</div>++<script type="module" src="js/page-main.js"></script>+</body>+</html>diff --git a/anymodelbot_design/onboarding/README.md b/anymodelbot_design/onboarding/README.mdnew file mode 100644index 0000000..447d787--- /dev/null+++ b/anymodelbot_design/onboarding/README.md@@ -0,0 +1,31 @@+# 新手引导 · 可交互原型++App 内新手引导(上手清单 6 步 + 随用随教的小提示)的可点击原型,风格与官网一致。静态设计稿在 claude.ai 的画布上(AnyModelBot 新手引导),这里是它会动的版本。++- 页面:`index.html`(目录)、`Main.html`、`Step2-Model.html` … `Step6-Media.html`、`Tips.html`。布局沿用设计稿的内联样式。+- `css/bots.css`、`js/eyes.js`:机器人头像与动效,来自官网(`site/src/styles/bots.css`、`site/src/lib/eyes.ts` 用 esbuild 转出),改动请回源文件再同步。+- `js/bots.js`:把 `<span class="face" data-char="blue" style="width: …">` 渲染成会动的头像。+- `css/proto.css`、`js/proto.js`:引导的动效与公共交互(聚光、引导卡片进出场、左下角清单与进度、吐司、彩带、流式回复)。+- `js/page-*.js`:每一页自己的流程。+- 字体用 `assets/fonts` 里自带的 Geist(不连 Google Fonts,大陆打开不会卡住);中文落到系统字体。++## 预览++服务器上用独立的静态服务提供(不经过 Caddy,不影响其他站点):++```bash+# /site/ 是官网的预览构建,同步原型时别把它删了+rsync -a --delete --exclude /site/ anymodelbot_design/onboarding/ /srv/amb-preview/ && chmod -R a+rX /srv/amb-preview+# 打开 http://64.83.27.22:18600/(官网预览在 /site/),防火墙 ufw 放行 18600/tcp+```++服务是 systemd 临时单元 `amb-preview`,跑的是 `site/scripts/preview-serve.py`(gzip、HTTP/1.1 长连接、缓存头和线上 nginx 一致;`python3 -m http.server` 不压缩、每个请求都重新建连接,远程打开很慢)。单元是临时的,服务器重启后要重新起:++```bash+install -D -m 0644 site/scripts/preview-serve.py /usr/local/lib/amb-preview/preview-serve.py+systemd-run --unit amb-preview --description "AnyModelBot design preview (static, :18600, gzip)" \+ -p DynamicUser=yes -p ProtectSystem=strict -p ProtectHome=yes -p PrivateTmp=yes -p NoNewPrivileges=yes -p Restart=on-failure \+ /usr/bin/python3 -I /usr/local/lib/amb-preview/preview-serve.py --port 18600 --bind 0.0.0.0 --directory /srv/amb-preview+```++`/assets/bots/*.webp` 用的是站点根路径,所以要从目录根提供服务(直接双击打开 html 文件时头像不显示)。diff --git a/anymodelbot_design/onboarding/Step2-Model.html b/anymodelbot_design/onboarding/Step2-Model.htmlnew file mode 100644index 0000000..51a9bb9--- /dev/null+++ b/anymodelbot_design/onboarding/Step2-Model.html@@ -0,0 +1,206 @@+<!doctype html>+<html lang="zh-CN">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>第 2 步 · 换个模型 · 新手引导预览</title>+<style>+body{margin:0;background:#060706}+*,*::before,*::after{box-sizing:border-box}+button{font:inherit;color:inherit;border:0;background:none;padding:0;cursor:pointer}+input,textarea{font:inherit}+a{color:#d7ff00}a:hover{color:#e9ff66}+</style>+<link rel="stylesheet" href="css/bots.css">+<link rel="stylesheet" href="css/proto.css">+</head>+<body data-page="model">+<div style="min-height: 100vh; display: flex; flex-wrap: wrap; background: #060706; color: #fafaf7; font-family: Geist, 'Noto Sans SC', 'PingFang SC', system-ui, sans-serif; font-size: 14px; line-height: 1.5">++ <aside aria-label="机器人" style="flex: 1 1 248px; max-width: 100%; display: flex; flex-direction: column; gap: 6px; padding: 14px 12px 12px; background: #0a0b0a; border-right: 1px solid rgba(255,255,255,.10)">+ <div aria-hidden="true" style="display: flex; gap: 8px; padding: 4px 6px 14px">+ <span style="width: 11px; height: 11px; border-radius: 50%; background: rgba(127,127,127,.45)"></span>+ <span style="width: 11px; height: 11px; border-radius: 50%; background: rgba(127,127,127,.45)"></span>+ <span style="width: 11px; height: 11px; border-radius: 50%; background: rgba(127,127,127,.45)"></span>+ </div>+ <button type="button" style="display: flex; align-items: center; gap: 10px; min-height: 40px; padding: 0 10px; border-radius: 10px; color: #a1a1aa; font-size: 13.5px">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>+ 新建机器人+ </button>+ <div style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; letter-spacing: .08em; color: #a1a1aa; padding: 10px 10px 4px">机器人</div>+ <a href="Main.html" style="display: flex; align-items: center; gap: 10px; min-height: 52px; padding: 6px 10px; border-radius: 12px; background: rgba(255,255,255,.06); color: #fafaf7; text-decoration: none">+ <span class="face" data-char="blue" style="width: 34px; height: 34px; flex: none"></span>+ <span style="display: flex; flex-direction: column; min-width: 0">+ <span style="font-weight: 600; font-size: 14px">小蓝</span>+ <span style="color: #a1a1aa; font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">我能帮你聊天答疑、写东西…</span>+ </span>+ </a>+ <div style="flex: 1"></div>+ <a href="Main.html" style="display: flex; align-items: center; gap: 10px; min-height: 44px; padding: 0 12px; border-radius: 12px; background: rgba(215,255,0,.10); box-shadow: inset 0 0 0 1px rgba(215,255,0,.30); color: #fafaf7; font-size: 13.5px; text-decoration: none">+ <span style="display: flex; gap: 3px" aria-hidden="true">+ <span style="width: 5px; height: 14px; border-radius: 2px; background: #d7ff00"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: rgba(255,255,255,.16)"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: rgba(255,255,255,.16)"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: rgba(255,255,255,.16)"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: rgba(255,255,255,.16)"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: rgba(255,255,255,.16)"></span>+ </span>+ <span style="flex: 1; font-weight: 500">上手清单</span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">1 / 6</span>+ </a>+ <button type="button" style="display: flex; align-items: center; gap: 10px; min-height: 48px; padding: 0 10px; border-radius: 12px; text-align: left">+ <span aria-hidden="true" style="display: grid; place-items: center; width: 28px; height: 28px; border-radius: 50%; background: #d7ff00; color: #161a00; font-weight: 700; font-size: 13px">Z</span>+ <span style="flex: 1; font-size: 13.5px">我的账户</span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12.5px; color: #a1a1aa">$12.40</span>+ </button>+ </aside>++ <main style="flex: 999 1 560px; min-width: 0; display: flex; flex-direction: column; min-height: 100vh">+ <header style="display: flex; align-items: center; gap: 8px; height: 54px; padding: 0 16px; border-bottom: 1px solid rgba(255,255,255,.10)">+ <button type="button" style="display: inline-flex; align-items: center; gap: 8px; height: 34px; padding: 0 12px 0 6px; border-radius: 999px; background: rgba(255,255,255,.05); box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); font-weight: 600; font-size: 14px">+ <span class="face" data-char="blue" style="width: 24px; height: 24px"></span>+ 小蓝+ </button>+ <span style="flex: 1"></span>+ <button type="button" aria-label="开始新的一段对话" style="display: grid; place-items: center; width: 36px; height: 36px; border-radius: 50%; color: #a1a1aa">+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>+ </button>+ <button type="button" aria-label="信息面板" style="display: grid; place-items: center; width: 36px; height: 36px; border-radius: 50%; color: #a1a1aa">+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="16" rx="3"/><path d="M15 4v16"/></svg>+ </button>+ </header>++ <div style="flex: 1; overflow: auto">+ <div id="log" style="max-width: 760px; margin: 0 auto; padding: 32px 24px 24px; display: flex; flex-direction: column; gap: 22px">+ <div style="align-self: flex-end; max-width: 80%; padding: 10px 16px; border-radius: 18px; background: rgba(255,255,255,.07)">你能帮我做什么?</div>+ <div style="display: flex; flex-direction: column; gap: 6px">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11.5px; color: #a1a1aa">用时 4 秒</span>+ <p style="margin: 0; line-height: 1.75">我能帮你聊天答疑、写东西、整理资料,也能在自己的工作区里写文件、跑命令,还能画图、做视频。把我接到微信,出门也能找我。想先试试哪个?</p>+ </div>+ </div>+ </div>++ <div style="padding: 0 24px 24px">+ <div style="position: relative; max-width: 760px; margin: 0 auto">++ <!-- 模型选择器(已展开) -->+ <div id="picker" hidden role="listbox" aria-label="选择模型" style="transform-origin: 75% 100%; position: absolute; right: 36px; bottom: calc(100% + 10px); z-index: 2; width: 380px; max-width: calc(100vw - 48px); padding: 6px; border-radius: 16px; background: #0b0b10; box-shadow: 0 0 0 1px rgba(255,255,255,.18), 0 24px 60px -16px rgba(0,0,0,.7)">+ <label style="display: flex; align-items: center; gap: 8px; height: 38px; padding: 0 10px; margin-bottom: 4px; border-radius: 10px; background: #101110; color: #a1a1aa">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>+ <input type="search" placeholder="搜索模型" aria-label="搜索模型" style="flex: 1; min-width: 0; border: 0; background: none; outline: none; color: #fafaf7; font-size: 13.5px">+ </label>+ <button type="button" role="option" aria-selected="false" style="display: flex; align-items: center; gap: 10px; width: 100%; min-height: 40px; padding: 0 10px; border-radius: 10px; text-align: left; font-size: 13.5px">+ <span style="flex: 1">跟随机器人默认</span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #a1a1aa">claude-sonnet-5-5</span>+ </button>+ <div style="height: 1px; margin: 4px 6px; background: rgba(255,255,255,.10)"></div>++ <button type="button" aria-expanded="true" style="display: flex; align-items: center; gap: 8px; width: 100%; min-height: 34px; padding: 0 10px; border-radius: 10px; color: #a1a1aa; font-size: 12.5px; text-align: left">+ <span style="flex: 1; font-weight: 500; color: #fafaf7">Anthropic</span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace">3</span>+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 15 6-6 6 6"/></svg>+ </button>+ <button type="button" role="option" aria-selected="false" style="display: flex; flex-direction: column; align-items: stretch; gap: 2px; width: 100%; padding: 8px 10px 8px 22px; border-radius: 10px; text-align: left">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 13px">claude-opus-5-5</span>+ <span style="display: flex; flex-wrap: wrap; align-items: center; gap: 6px; color: #a1a1aa; font-size: 11.5px">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace">1M</span>+ <span style="padding: 0 6px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">视觉</span>+ <span style="padding: 0 6px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">工具</span>+ <span style="padding: 0 6px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">推理</span>+ <span style="flex: 1"></span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace">$1.26 / $6.30</span>+ </span>+ </button>+ <button type="button" role="option" aria-selected="true" style="display: flex; flex-direction: column; align-items: stretch; gap: 2px; width: 100%; padding: 8px 10px 8px 22px; border-radius: 10px; background: rgba(215,255,0,.10); text-align: left">+ <span style="display: flex; align-items: center; gap: 8px">+ <span style="flex: 1; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 13px">claude-sonnet-5-5</span>+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#d7ff00" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12 5 5 9-10"/></svg>+ </span>+ <span style="display: flex; flex-wrap: wrap; align-items: center; gap: 6px; color: #a1a1aa; font-size: 11.5px">+ <span style="padding: 0 6px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">视觉</span>+ <span style="padding: 0 6px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">工具</span>+ <span style="padding: 0 6px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">推理</span>+ <span style="flex: 1"></span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace">$0.63 / $3.15</span>+ </span>+ </button>+ <button type="button" role="option" aria-selected="false" style="display: flex; flex-direction: column; align-items: stretch; gap: 2px; width: 100%; padding: 8px 10px 8px 22px; border-radius: 10px; text-align: left">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 13px">claude-haiku-5-5</span>+ <span style="display: flex; flex-wrap: wrap; align-items: center; gap: 6px; color: #a1a1aa; font-size: 11.5px">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace">1M</span>+ <span style="padding: 0 6px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">视觉</span>+ <span style="padding: 0 6px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">工具</span>+ <span style="flex: 1"></span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace">$0.03 / $0.16</span>+ </span>+ </button>++ <button type="button" aria-expanded="false" style="display: flex; align-items: center; gap: 8px; width: 100%; min-height: 34px; padding: 0 10px; border-radius: 10px; color: #a1a1aa; font-size: 12.5px; text-align: left">+ <span style="flex: 1; font-weight: 500; color: #fafaf7">OpenAI</span><span style="font-family: 'Geist Mono', ui-monospace, monospace">gpt-6.1-terra 等 6 个</span>+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>+ </button>+ <button type="button" aria-expanded="false" style="display: flex; align-items: center; gap: 8px; width: 100%; min-height: 34px; padding: 0 10px; border-radius: 10px; color: #a1a1aa; font-size: 12.5px; text-align: left">+ <span style="flex: 1; font-weight: 500; color: #fafaf7">Google</span><span style="font-family: 'Geist Mono', ui-monospace, monospace">gemini-3.8-flash 等 5 个</span>+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>+ </button>+ <button type="button" aria-expanded="false" style="display: flex; align-items: center; gap: 8px; width: 100%; min-height: 34px; padding: 0 10px; border-radius: 10px; color: #a1a1aa; font-size: 12.5px; text-align: left">+ <span style="flex: 1; font-weight: 500; color: #fafaf7">DeepSeek</span><span style="font-family: 'Geist Mono', ui-monospace, monospace">deepseek-v4-flash 等 3 个</span>+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>+ </button>++ <div style="height: 1px; margin: 4px 6px; background: rgba(255,255,255,.10)"></div>+ <div style="display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 4px 4px 2px 10px">+ <span style="color: #a1a1aa; font-size: 11.5px">价格:每百万 tokens 输入 / 输出</span>+ <button type="button" style="min-height: 34px; padding: 0 12px; border-radius: 999px; background: rgba(215,255,0,.14); color: #d7ff00; font-size: 13px; font-weight: 500" id="set-default">设为此机器人的默认模型</button>+ </div>+ </div>++ <!-- 引导卡片:在选择器左侧 -->+ <section id="coach" hidden aria-label="上手引导" style="position: absolute; right: 440px; bottom: 64px; z-index: 3; width: 320px; padding: 20px 20px 16px; border-radius: 20px; background: #0b0b10; box-shadow: 0 0 0 1px rgba(255,255,255,.18), 0 30px 80px -20px rgba(0,0,0,.75)">+ <span class="face" data-char="blue" style="position: absolute; right: 18px; top: -40px; width: 52px; height: 52px"></span>+ <span id="arrow" aria-hidden="true" style="position: absolute; right: -7px; bottom: 34px; width: 14px; height: 14px; transform: rotate(45deg); background: #0b0b10; box-shadow: 1px -1px 0 rgba(255,255,255,.18)"></span>+ <p id="c-kick" style="display: flex; align-items: center; gap: 10px; margin: 0 0 12px; font-size: 12.5px; letter-spacing: .06em; color: #a1a1aa">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">02 / 06</span>上手清单+ </p>+ <h2 id="c-title" style="margin: 0 0 6px; font-size: 19px; font-weight: 600; letter-spacing: -.01em">换个模型</h2>+ <p id="c-body" style="margin: 0 0 12px; color: #a1a1aa; line-height: 1.7">一个账户就能用 GPT、Claude、Gemini 等模型。点输入框右下角的模型名,挑一个就换好了。</p>+ <ul id="c-list" style="list-style: none; margin: 0 0 16px; padding: 12px 0 0; border-top: 1px solid rgba(255,255,255,.10); display: flex; flex-direction: column; gap: 8px; font-size: 13px; color: #a1a1aa">+ <li style="display: flex; gap: 10px"><span aria-hidden="true" style="flex: none; width: 10px; height: 6px; margin-top: 6px; border-left: 2px solid #d7ff00; border-bottom: 2px solid #d7ff00; transform: rotate(-45deg)"></span>只对当前对话生效</li>+ <li style="display: flex; gap: 10px"><span aria-hidden="true" style="flex: none; width: 10px; height: 6px; margin-top: 6px; border-left: 2px solid #d7ff00; border-bottom: 2px solid #d7ff00; transform: rotate(-45deg)"></span>想一直用它,点列表底部「设为此机器人的默认模型」</li>+ <li style="display: flex; gap: 10px"><span aria-hidden="true" style="flex: none; width: 10px; height: 6px; margin-top: 6px; border-left: 2px solid #d7ff00; border-bottom: 2px solid #d7ff00; transform: rotate(-45deg)"></span>每行标着上下文长度、能力和参考价</li>+ </ul>+ <div style="display: flex; align-items: center; justify-content: space-between; gap: 8px">+ <button type="button" id="c-later" style="min-height: 36px; padding: 0 4px; color: #a1a1aa; font-size: 13.5px">稍后再说</button>+ <a id="c-next" href="Step3-Weixin.html" style="display: inline-flex; align-items: center; gap: 8px; min-height: 36px; padding: 0 16px; border-radius: 999px; background: #d7ff00; color: #161a00; font-weight: 600; font-size: 14px; text-decoration: none">下一步</a>+ </div>+ </section>++ <div style="border-radius: 18px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <textarea id="input" class="input" rows="1" aria-label="消息" placeholder="给「小蓝」发消息,/ 查看命令"></textarea>+ <div style="display: flex; align-items: center; gap: 6px; padding: 6px 8px 8px">+ <button type="button" aria-label="更多操作" style="display: grid; place-items: center; width: 32px; height: 32px; border-radius: 50%; color: #a1a1aa">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>+ </button>+ <button type="button" style="display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 10px; border-radius: 999px; color: #a1a1aa; font-size: 12.5px">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3l7 3v6c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6z"/></svg>+ 工作区可写+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>+ </button>+ <span style="flex: 1"></span>+ <button type="button" id="chip" aria-expanded="false" aria-haspopup="listbox" class="spot" style="display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 10px; border-radius: 999px; color: #fafaf7; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12.5px">+ <span id="chip-label">claude-sonnet-5-5</span>+ <svg id="chip-chev" style="transition: transform .3s" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>+ </button>+ <button type="button" id="send" aria-label="发送" style="display: grid; place-items: center; width: 32px; height: 32px; border-radius: 50%; background: #161a00; color: #d7ff00; opacity: .5">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 19V5M5 12l7-7 7 7"/></svg>+ </button>+ </div>+ </div>+ </div>+ </div>+ </main>+</div>++<script type="module" src="js/page-model.js"></script>+</body>+</html>diff --git a/anymodelbot_design/onboarding/Step3-Weixin.html b/anymodelbot_design/onboarding/Step3-Weixin.htmlnew file mode 100644index 0000000..50fed4d--- /dev/null+++ b/anymodelbot_design/onboarding/Step3-Weixin.html@@ -0,0 +1,201 @@+<!doctype html>+<html lang="zh-CN">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>第 3 步 · 接到微信 · 新手引导预览</title>+<style>+body{margin:0;background:#060706}+*,*::before,*::after{box-sizing:border-box}+button{font:inherit;color:inherit;border:0;background:none;padding:0;cursor:pointer}+input,textarea{font:inherit}+a{color:#d7ff00}a:hover{color:#e9ff66}+</style>+<link rel="stylesheet" href="css/bots.css">+<link rel="stylesheet" href="css/proto.css">+</head>+<body data-page="weixin">+<div style="min-height: 100vh; display: flex; flex-wrap: wrap; background: #060706; color: #fafaf7; font-family: Geist, 'Noto Sans SC', 'PingFang SC', system-ui, sans-serif; font-size: 14px; line-height: 1.5">++ <aside aria-label="机器人" style="flex: 1 1 248px; max-width: 100%; display: flex; flex-direction: column; gap: 6px; padding: 14px 12px 12px; background: #0a0b0a; border-right: 1px solid rgba(255,255,255,.10)">+ <div aria-hidden="true" style="display: flex; gap: 8px; padding: 4px 6px 14px">+ <span style="width: 11px; height: 11px; border-radius: 50%; background: rgba(127,127,127,.45)"></span>+ <span style="width: 11px; height: 11px; border-radius: 50%; background: rgba(127,127,127,.45)"></span>+ <span style="width: 11px; height: 11px; border-radius: 50%; background: rgba(127,127,127,.45)"></span>+ </div>+ <button type="button" style="display: flex; align-items: center; gap: 10px; min-height: 40px; padding: 0 10px; border-radius: 10px; color: #a1a1aa; font-size: 13.5px">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>+ 新建机器人+ </button>+ <div style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; letter-spacing: .08em; color: #a1a1aa; padding: 10px 10px 4px">机器人</div>+ <a href="Main.html" style="display: flex; align-items: center; gap: 10px; min-height: 52px; padding: 6px 10px; border-radius: 12px; background: rgba(255,255,255,.06); color: #fafaf7; text-decoration: none">+ <span class="face" data-char="blue" style="width: 34px; height: 34px; flex: none"></span>+ <span style="display: flex; flex-direction: column; min-width: 0">+ <span style="font-weight: 600; font-size: 14px">小蓝</span>+ <span style="color: #a1a1aa; font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">换好了,现在用 gpt-6.1-terra…</span>+ </span>+ </a>+ <div style="flex: 1"></div>+ <a href="Main.html" style="display: flex; align-items: center; gap: 10px; min-height: 44px; padding: 0 12px; border-radius: 12px; background: rgba(215,255,0,.10); box-shadow: inset 0 0 0 1px rgba(215,255,0,.30); color: #fafaf7; font-size: 13.5px; text-decoration: none">+ <span style="display: flex; gap: 3px" aria-hidden="true">+ <span style="width: 5px; height: 14px; border-radius: 2px; background: #d7ff00"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: #d7ff00"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: rgba(255,255,255,.16)"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: rgba(255,255,255,.16)"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: rgba(255,255,255,.16)"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: rgba(255,255,255,.16)"></span>+ </span>+ <span style="flex: 1; font-weight: 500">上手清单</span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">2 / 6</span>+ </a>+ <button type="button" style="display: flex; align-items: center; gap: 10px; min-height: 48px; padding: 0 10px; border-radius: 12px; text-align: left">+ <span aria-hidden="true" style="display: grid; place-items: center; width: 28px; height: 28px; border-radius: 50%; background: #d7ff00; color: #161a00; font-weight: 700; font-size: 13px">Z</span>+ <span style="flex: 1; font-size: 13.5px">我的账户</span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12.5px; color: #a1a1aa">$12.39</span>+ </button>+ </aside>++ <div style="flex: 999 1 560px; min-width: 0; display: flex; flex-wrap: wrap; min-height: 100vh">+ <!-- 对话区 -->+ <main style="position: relative; flex: 999 1 420px; min-width: 0; display: flex; flex-direction: column">+ <header style="display: flex; align-items: center; gap: 8px; height: 54px; padding: 0 16px; border-bottom: 1px solid rgba(255,255,255,.10)">+ <button type="button" id="capsule" aria-pressed="false" style="position: relative; display: inline-flex; align-items: center; gap: 8px; height: 34px; padding: 0 12px 0 6px; border-radius: 999px; background: rgba(215,255,0,.10); box-shadow: 0 0 0 2px #d7ff00, 0 0 0 7px rgba(215,255,0,.16); font-weight: 600; font-size: 14px">+ <span class="face" data-char="blue" style="width: 24px; height: 24px"></span>+ 小蓝+ <span class="mk" data-mk="1" aria-hidden="true" style="position: absolute; right: -10px; top: -10px; display: grid; place-items: center; width: 20px; height: 20px; border-radius: 50%; background: #d7ff00; color: #161a00; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; font-weight: 600">1</span>+ </button>+ <span style="flex: 1"></span>+ <button type="button" aria-label="开始新的一段对话" style="display: grid; place-items: center; width: 36px; height: 36px; border-radius: 50%; color: #a1a1aa">+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>+ </button>+ <button type="button" id="panel-btn" aria-label="信息面板" aria-pressed="false" style="display: grid; place-items: center; width: 36px; height: 36px; border-radius: 50%; background: rgba(255,255,255,.06); color: #fafaf7">+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="16" rx="3"/><path d="M15 4v16"/></svg>+ </button>+ </header>++ <div style="flex: 1; overflow: auto">+ <div style="max-width: 720px; margin: 0 auto; padding: 32px 24px 24px; display: flex; flex-direction: column; gap: 22px">+ <div style="align-self: flex-end; max-width: 80%; padding: 10px 16px; border-radius: 18px; background: rgba(255,255,255,.07)">换成 gpt-6.1-terra,用一句话介绍你自己。</div>+ <div style="display: flex; flex-direction: column; gap: 6px">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11.5px; color: #a1a1aa">gpt-6.1-terra · 用时 3 秒</span>+ <p style="margin: 0; line-height: 1.75">换好了,现在用 gpt-6.1-terra。我是住在你电脑里的小蓝:能聊、能写、能动手,还记得你交代过的事。</p>+ </div>+ </div>+ </div>++ <!-- 引导卡片:指向右侧信息面板 -->+ <section id="coach" hidden aria-label="上手引导" style="position: absolute; right: 22px; top: 150px; z-index: 3; width: 340px; padding: 20px 20px 16px; border-radius: 20px; background: #0b0b10; box-shadow: 0 0 0 1px rgba(255,255,255,.18), 0 30px 80px -20px rgba(0,0,0,.75)">+ <span class="face" data-char="blue" style="position: absolute; right: 18px; top: -40px; width: 52px; height: 52px"></span>+ <span id="arrow" aria-hidden="true" style="position: absolute; right: -7px; top: 120px; width: 14px; height: 14px; transform: rotate(45deg); background: #0b0b10; box-shadow: 1px -1px 0 rgba(255,255,255,.18)"></span>+ <p id="c-kick" style="display: flex; align-items: center; gap: 10px; margin: 0 0 12px; font-size: 12.5px; letter-spacing: .06em; color: #a1a1aa">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">03 / 06</span>上手清单+ </p>+ <h2 id="c-title" style="margin: 0 0 6px; font-size: 19px; font-weight: 600; letter-spacing: -.01em">把小蓝接到微信</h2>+ <p id="c-body" style="margin: 0 0 14px; color: #a1a1aa; line-height: 1.7">扫码后,在微信里直接私聊小蓝,不用装新 App。电脑开着,它就在线。</p>+ <ol id="c-list" style="list-style: none; margin: 0 0 14px; padding: 12px 0 0; border-top: 1px solid rgba(255,255,255,.10); display: flex; flex-direction: column; gap: 10px; font-size: 13.5px">+ <li data-s="1" style="display: flex; gap: 10px; align-items: flex-start; transition: opacity .3s"><span aria-hidden="true" style="flex: none; display: grid; place-items: center; width: 20px; height: 20px; margin-top: 1px; border-radius: 50%; background: #d7ff00; color: #161a00; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; font-weight: 600">1</span>点顶部的「小蓝」,打开信息面板</li>+ <li data-s="2" style="display: flex; gap: 10px; align-items: flex-start; transition: opacity .3s"><span aria-hidden="true" style="flex: none; display: grid; place-items: center; width: 20px; height: 20px; margin-top: 1px; border-radius: 50%; background: #d7ff00; color: #161a00; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; font-weight: 600">2</span>在「渠道」里点「微信」→「扫码登录」</li>+ <li data-s="3" style="display: flex; gap: 10px; align-items: flex-start; transition: opacity .3s"><span aria-hidden="true" style="flex: none; display: grid; place-items: center; width: 20px; height: 20px; margin-top: 1px; border-radius: 50%; background: #d7ff00; color: #161a00; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; font-weight: 600">3</span>用微信扫码,在手机上确认</li>+ </ol>+ <p style="display: flex; gap: 8px; margin: 0 0 6px; padding: 10px 12px; border-radius: 12px; background: #101110; color: #a1a1aa; font-size: 12.5px; line-height: 1.6">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" style="flex: none; margin-top: 2px"><circle cx="12" cy="12" r="9"/><path d="M12 11v5M12 8h.01"/></svg>+ 微信的规定:你每发一条消息,它 24 小时内最多回 10 条。+ </p>+ <a href="#feishu" style="display: inline-block; margin: 0 0 14px; font-size: 13px">用飞书?查看接入步骤</a>+ <div style="display: flex; align-items: center; justify-content: space-between; gap: 8px">+ <button type="button" id="c-later" style="min-height: 36px; padding: 0 4px; color: #a1a1aa; font-size: 13.5px">稍后再说</button>+ <a id="c-next" href="Step4-Hands.html" style="display: inline-flex; align-items: center; gap: 8px; min-height: 36px; padding: 0 16px; border-radius: 999px; background: #d7ff00; color: #161a00; font-weight: 600; font-size: 14px; text-decoration: none">下一步</a>+ </div>+ </section>++ <div style="padding: 0 24px 24px">+ <div style="max-width: 720px; margin: 0 auto; border-radius: 18px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <textarea id="input" class="input" rows="1" aria-label="消息" placeholder="给「小蓝」发消息,/ 查看命令"></textarea>+ <div style="display: flex; align-items: center; gap: 6px; padding: 6px 8px 8px">+ <button type="button" aria-label="更多操作" style="display: grid; place-items: center; width: 32px; height: 32px; border-radius: 50%; color: #a1a1aa">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>+ </button>+ <button type="button" style="display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 10px; border-radius: 999px; color: #a1a1aa; font-size: 12.5px">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3l7 3v6c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6z"/></svg>+ 工作区可写+ </button>+ <span style="flex: 1"></span>+ <button type="button" style="display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 10px; border-radius: 999px; color: #a1a1aa; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12.5px">gpt-6.1-terra</button>+ <button type="button" id="send" aria-label="发送" style="display: grid; place-items: center; width: 32px; height: 32px; border-radius: 50%; background: #161a00; color: #d7ff00; opacity: .5">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 19V5M5 12l7-7 7 7"/></svg>+ </button>+ </div>+ </div>+ </div>+ </main>++ <!-- 信息面板 -->+ <aside id="panel" hidden aria-label="信息面板" style="flex: 1 1 340px; max-width: 100%; display: flex; flex-direction: column; background: #0a0b0a; border-left: 1px solid rgba(255,255,255,.10)">+ <div style="display: flex; align-items: center; gap: 4px; height: 54px; padding: 0 10px 0 18px; border-bottom: 1px solid rgba(255,255,255,.10)">+ <span style="flex: 1; font-weight: 600">小蓝</span>+ <button type="button" aria-label="机器人设置" style="display: grid; place-items: center; width: 34px; height: 34px; border-radius: 50%; color: #a1a1aa">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M4.2 4.2l2.1 2.1M17.7 17.7l2.1 2.1M2 12h3M19 12h3M4.2 19.8l2.1-2.1M17.7 6.3l2.1-2.1"/></svg>+ </button>+ <button type="button" aria-label="关闭信息面板" style="display: grid; place-items: center; width: 34px; height: 34px; border-radius: 50%; color: #a1a1aa">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"/></svg>+ </button>+ </div>+ <div style="flex: 1; overflow: auto; padding: 16px 14px; display: flex; flex-direction: column; gap: 8px">+ <div style="position: relative; display: flex; align-items: center; gap: 10px; padding: 0 6px; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; letter-spacing: .08em; color: #a1a1aa">+ 渠道+ <span class="mk" data-mk="2" aria-hidden="true" style="display: grid; place-items: center; width: 20px; height: 20px; border-radius: 50%; background: #d7ff00; color: #161a00; font-size: 11px; font-weight: 600; letter-spacing: 0">2</span>+ </div>+ <div style="border-radius: 16px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <button type="button" aria-expanded="false" style="display: flex; align-items: center; gap: 10px; width: 100%; min-height: 56px; padding: 8px 14px; text-align: left; border-bottom: 1px solid rgba(255,255,255,.10)">+ <span style="flex: 1; min-width: 0"><span style="display: block; font-weight: 500">飞书</span><span style="display: block; color: #a1a1aa; font-size: 12.5px">长连接接收消息</span></span>+ <span style="height: 22px; padding: 0 9px; border-radius: 999px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); color: #a1a1aa; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; line-height: 22px">未连接</span>+ </button>+ <div id="wx" style="border-radius: 0 0 16px 16px">+ <button type="button" id="wx-row" aria-expanded="false" style="display: flex; align-items: center; gap: 10px; width: 100%; min-height: 56px; padding: 8px 14px; text-align: left">+ <span style="flex: 1; min-width: 0"><span style="display: block; font-weight: 500">微信</span><span style="display: block; color: #a1a1aa; font-size: 12.5px">iLink 官方通道</span></span>+ <span id="wx-badge" style="display: inline-flex; align-items: center; gap: 6px; height: 22px; padding: 0 9px; border-radius: 999px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); color: #a1a1aa; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; line-height: 22px">未登录</span>+ </button>+ <div id="wx-body" hidden style="display: flex; flex-direction: column; align-items: center; gap: 12px; padding: 4px 14px 16px">+ <button type="button" id="wx-login" style="min-height: 38px; padding: 0 18px; border-radius: 999px; background: #d7ff00; color: #161a00; font-weight: 600; font-size: 13.5px">扫码登录</button>+ <p id="wx-done" hidden style="margin: 0; align-self: stretch; padding: 10px 12px; border-radius: 12px; background: rgba(111,217,155,.10); color: #6fd99b; font-size: 13px">已绑定「小蓝」· 现在可以在微信里私聊它了</p>+ <div id="wx-qr" hidden style="position: relative; padding: 12px; border-radius: 14px; background: #ffffff">+ <span id="wx-scan" class="scan" aria-hidden="true"></span>+ <div id="wx-scanned" hidden style="position: absolute; inset: 0; z-index: 2; display: grid; place-content: center; gap: 2px; border-radius: 14px; background: rgba(255,255,255,.93); color: #161a00; text-align: center; font-weight: 600; font-size: 14px"><span>已扫码</span><span style="font-weight: 400; font-size: 12px; color: #465612">请在手机上点「确认」</span></div>+ <svg width="152" height="152" viewBox="0 0 29 29" aria-hidden="true" shape-rendering="crispEdges">+ <defs>+ <pattern id="qr-dots" width="5" height="5" patternUnits="userSpaceOnUse">+ <rect x="0" y="0" width="1" height="1" fill="#161a00"/><rect x="2" y="0" width="2" height="1" fill="#161a00"/><rect x="1" y="1" width="1" height="2" fill="#161a00"/><rect x="3" y="2" width="1" height="1" fill="#161a00"/><rect x="0" y="3" width="2" height="1" fill="#161a00"/><rect x="4" y="3" width="1" height="2" fill="#161a00"/><rect x="2" y="4" width="1" height="1" fill="#161a00"/>+ </pattern>+ </defs>+ <rect x="0" y="0" width="29" height="29" fill="url(#qr-dots)"/>+ <rect x="0" y="0" width="9" height="9" fill="#ffffff"/><rect x="20" y="0" width="9" height="9" fill="#ffffff"/><rect x="0" y="20" width="9" height="9" fill="#ffffff"/>+ <rect x="0.5" y="0.5" width="7" height="7" fill="none" stroke="#161a00"/><rect x="2" y="2" width="4" height="4" fill="#161a00"/>+ <rect x="21.5" y="0.5" width="7" height="7" fill="none" stroke="#161a00"/><rect x="23" y="2" width="4" height="4" fill="#161a00"/>+ <rect x="0.5" y="21.5" width="7" height="7" fill="none" stroke="#161a00"/><rect x="2" y="23" width="4" height="4" fill="#161a00"/>+ <rect x="11" y="11" width="7" height="7" rx="1.5" fill="#ffffff"/>+ </svg>+ <span class="face" data-char="blue" style="position: absolute; left: 50%; top: 50%; width: 34px; height: 34px; transform: translate(-50%, -50%)"></span>+ <span class="mk" data-mk="3" aria-hidden="true" style="position: absolute; right: -10px; top: -10px; display: grid; place-items: center; width: 20px; height: 20px; border-radius: 50%; background: #d7ff00; color: #161a00; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; font-weight: 600">3</span>+ </div>+ <p id="wx-hint" hidden style="margin: 0; color: #a1a1aa; font-size: 13px; text-align: center">用微信扫一扫,然后在手机上确认。</p>+ <p id="wx-demo" hidden style="margin: -6px 0 0; color: #a1a1aa; font-size: 11.5px; font-family: 'Geist Mono', ui-monospace, monospace">演示:几秒后自动模拟扫码</p>+ <div id="wx-actions" hidden style="display: flex; flex-wrap: wrap; justify-content: center; gap: 8px">+ <button type="button" style="min-height: 34px; padding: 0 14px; border-radius: 999px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); font-size: 13px" id="wx-cancel">取消</button>+ <button type="button" style="min-height: 34px; padding: 0 10px; color: #a1a1aa; font-size: 13px">停用微信渠道</button>+ </div>+ </div>+ </div>+ </div>++ <div style="padding: 14px 6px 0; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; letter-spacing: .08em; color: #a1a1aa">待审批</div>+ <div style="padding: 14px; border-radius: 16px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); color: #a1a1aa; font-size: 13px">没有待处理的审批</div>+ <div style="padding: 14px 6px 0; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; letter-spacing: .08em; color: #a1a1aa">记忆</div>+ <div style="padding: 14px; border-radius: 16px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); color: #a1a1aa; font-size: 13px">还没有长期记忆</div>+ </div>+ </aside>+ </div>+</div>++<script type="module" src="js/page-weixin.js"></script>+</body>+</html>diff --git a/anymodelbot_design/onboarding/Step4-Hands.html b/anymodelbot_design/onboarding/Step4-Hands.htmlnew file mode 100644index 0000000..0c2c210--- /dev/null+++ b/anymodelbot_design/onboarding/Step4-Hands.html@@ -0,0 +1,161 @@+<!doctype html>+<html lang="zh-CN">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>第 4 步 · 让它动手做件事 · 新手引导预览</title>+<style>+body{margin:0;background:#060706}+*,*::before,*::after{box-sizing:border-box}+button{font:inherit;color:inherit;border:0;background:none;padding:0;cursor:pointer}+input,textarea{font:inherit}+a{color:#d7ff00}a:hover{color:#e9ff66}+</style>+<link rel="stylesheet" href="css/bots.css">+<link rel="stylesheet" href="css/proto.css">+</head>+<body data-page="hands">+<div style="min-height: 100vh; display: flex; flex-wrap: wrap; background: #060706; color: #fafaf7; font-family: Geist, 'Noto Sans SC', 'PingFang SC', system-ui, sans-serif; font-size: 14px; line-height: 1.5">++ <aside aria-label="机器人" style="flex: 1 1 248px; max-width: 100%; display: flex; flex-direction: column; gap: 6px; padding: 14px 12px 12px; background: #0a0b0a; border-right: 1px solid rgba(255,255,255,.10)">+ <div aria-hidden="true" style="display: flex; gap: 8px; padding: 4px 6px 14px">+ <span style="width: 11px; height: 11px; border-radius: 50%; background: rgba(127,127,127,.45)"></span>+ <span style="width: 11px; height: 11px; border-radius: 50%; background: rgba(127,127,127,.45)"></span>+ <span style="width: 11px; height: 11px; border-radius: 50%; background: rgba(127,127,127,.45)"></span>+ </div>+ <button type="button" style="display: flex; align-items: center; gap: 10px; min-height: 40px; padding: 0 10px; border-radius: 10px; color: #a1a1aa; font-size: 13.5px">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>+ 新建机器人+ </button>+ <div style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; letter-spacing: .08em; color: #a1a1aa; padding: 10px 10px 4px">机器人</div>+ <a href="Main.html" style="display: flex; align-items: center; gap: 10px; min-height: 52px; padding: 6px 10px; border-radius: 12px; background: rgba(255,255,255,.06); color: #fafaf7; text-decoration: none">+ <span class="face" data-char="blue" style="width: 34px; height: 34px; flex: none"></span>+ <span style="display: flex; flex-direction: column; min-width: 0">+ <span style="font-weight: 600; font-size: 14px">小蓝</span>+ <span style="color: #a1a1aa; font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">建好了,列了三件事…</span>+ </span>+ </a>+ <div style="flex: 1"></div>+ <a href="Main.html" style="display: flex; align-items: center; gap: 10px; min-height: 44px; padding: 0 12px; border-radius: 12px; background: rgba(215,255,0,.10); box-shadow: inset 0 0 0 1px rgba(215,255,0,.30); color: #fafaf7; font-size: 13.5px; text-decoration: none">+ <span style="display: flex; gap: 3px" aria-hidden="true">+ <span style="width: 5px; height: 14px; border-radius: 2px; background: #d7ff00"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: #d7ff00"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: #d7ff00"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: #d7ff00"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: rgba(255,255,255,.16)"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: rgba(255,255,255,.16)"></span>+ </span>+ <span style="flex: 1; font-weight: 500">上手清单</span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">4 / 6</span>+ </a>+ <button type="button" style="display: flex; align-items: center; gap: 10px; min-height: 48px; padding: 0 10px; border-radius: 12px; text-align: left">+ <span aria-hidden="true" style="display: grid; place-items: center; width: 28px; height: 28px; border-radius: 50%; background: #d7ff00; color: #161a00; font-weight: 700; font-size: 13px">Z</span>+ <span style="flex: 1; font-size: 13.5px">我的账户</span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12.5px; color: #a1a1aa">$12.37</span>+ </button>+ </aside>++ <main style="flex: 999 1 560px; min-width: 0; display: flex; flex-direction: column; min-height: 100vh">+ <header style="display: flex; align-items: center; gap: 8px; height: 54px; padding: 0 16px; border-bottom: 1px solid rgba(255,255,255,.10)">+ <button type="button" style="display: inline-flex; align-items: center; gap: 8px; height: 34px; padding: 0 12px 0 6px; border-radius: 999px; background: rgba(255,255,255,.05); box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); font-weight: 600; font-size: 14px">+ <span class="face" data-char="blue" style="width: 24px; height: 24px"></span>+ 小蓝+ </button>+ <span style="flex: 1"></span>+ <button type="button" aria-label="开始新的一段对话" style="display: grid; place-items: center; width: 36px; height: 36px; border-radius: 50%; color: #a1a1aa">+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>+ </button>+ <button type="button" aria-label="信息面板" style="display: grid; place-items: center; width: 36px; height: 36px; border-radius: 50%; color: #a1a1aa">+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="16" rx="3"/><path d="M15 4v16"/></svg>+ </button>+ </header>++ <div style="position: relative; flex: 1; overflow: auto">+ <div style="max-width: 980px; margin: 0 auto; padding: 32px 24px 24px; display: flex; flex-wrap: wrap; gap: 24px 40px; align-items: flex-start">++ <!-- 对话列 -->+ <div id="log" style="flex: 999 1 460px; min-width: 0; display: flex; flex-direction: column; gap: 22px">+ <div id="r1" hidden style="display: flex; flex-direction: column; gap: 8px">+ <span id="r1-wl" style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11.5px; color: #a1a1aa">思考中</span>+ <p id="r1-a" style="margin: 0; line-height: 1.75"></p>+ <ol id="r1-list" style="margin: 0; padding-left: 1.4em; line-height: 1.75">+ <li>回复昨天的客户邮件</li>+ <li>整理本周的会议纪要</li>+ <li>下午 5 点前提交周报</li>+ </ol>+ <p id="r1-b" style="margin: 0; line-height: 1.75"></p>+ </div>++ <!-- 文件卡:能预览、能打开 -->+ <div id="file" hidden style="max-width: 440px; border-radius: 20px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); overflow: hidden">+ <div style="display: flex; align-items: center; gap: 12px; padding: 14px 16px">+ <span aria-hidden="true" style="display: grid; place-items: center; width: 40px; height: 40px; border-radius: 12px; background: rgba(215,255,0,.14); color: #d7ff00">+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/></svg>+ </span>+ <span style="flex: 1; min-width: 0">+ <span style="display: block; font-weight: 600">今日待办.md</span>+ <span style="display: block; color: #a1a1aa; font-size: 12.5px; font-family: 'Geist Mono', ui-monospace, monospace">1 KB · 工作区</span>+ </span>+ </div>+ <pre id="file-pre" style="min-height: 104px; margin: 0 16px; padding: 12px 14px; border-radius: 12px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12.5px; line-height: 1.7; color: #a1a1aa; white-space: pre-wrap"># 今日待办+- [ ] 回复昨天的客户邮件+- [ ] 整理本周的会议纪要+- [ ] 下午 5 点前提交周报</pre>+ <div style="display: flex; flex-wrap: wrap; gap: 8px; padding: 12px 16px 14px">+ <button type="button" style="min-height: 34px; padding: 0 14px; border-radius: 999px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); font-size: 13px">打开</button>+ <button type="button" style="min-height: 34px; padding: 0 12px; border-radius: 999px; color: #a1a1aa; font-size: 13px">在文件夹中显示</button>+ </div>+ </div>+ </div>++ <!-- 引导卡片:完成态,指向左边的文件卡 -->+ <section id="coach" hidden aria-label="上手引导" style="position: relative; flex: 1 1 300px; max-width: 340px; margin-top: 180px; padding: 20px 20px 16px; border-radius: 20px; background: #0b0b10; box-shadow: 0 0 0 1px rgba(255,255,255,.18), 0 30px 80px -20px rgba(0,0,0,.75)">+ <span class="face" data-char="blue" style="position: absolute; right: 18px; top: -40px; width: 52px; height: 52px"></span>+ <span id="arrow" aria-hidden="true" style="position: absolute; left: -7px; top: 44px; width: 14px; height: 14px; transform: rotate(45deg); background: #0b0b10; box-shadow: -1px 1px 0 rgba(255,255,255,.18)"></span>+ <p id="c-kick" style="display: flex; align-items: center; gap: 10px; margin: 0 0 12px; font-size: 12.5px; letter-spacing: .06em; color: #a1a1aa">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">04 / 06</span>上手清单+ <span id="c-badge" style="display: inline-flex; align-items: center; gap: 4px; height: 22px; padding: 0 8px; border-radius: 999px; background: #d7ff00; color: #161a00; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; letter-spacing: 0">+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12 5 5 9-10"/></svg>完成+ </span>+ </p>+ <h2 id="c-title" style="margin: 0 0 6px; font-size: 19px; font-weight: 600; letter-spacing: -.01em">做好的文件,就在这里</h2>+ <p id="c-body" style="margin: 0 0 12px; color: #a1a1aa; line-height: 1.7">小蓝能在自己的工作区里写文件、跑命令。做好的文件会出现在对话里;在微信、飞书里会直接发给你。</p>+ <ul id="c-list" style="list-style: none; margin: 0 0 16px; padding: 12px 0 0; border-top: 1px solid rgba(255,255,255,.10); display: flex; flex-direction: column; gap: 10px; font-size: 13px; color: #a1a1aa">+ <li style="display: flex; gap: 10px"><span aria-hidden="true" style="flex: none; width: 10px; height: 6px; margin-top: 6px; border-left: 2px solid #d7ff00; border-bottom: 2px solid #d7ff00; transform: rotate(-45deg)"></span>它只改自己工作区里的东西</li>+ <li style="display: flex; gap: 10px"><span aria-hidden="true" style="flex: none; width: 10px; height: 6px; margin-top: 6px; border-left: 2px solid #d7ff00; border-bottom: 2px solid #d7ff00; transform: rotate(-45deg)"></span>要动工作区以外的文件,会先弹卡片问你,你点「允许」才做</li>+ <li style="display: flex; gap: 10px"><span aria-hidden="true" style="flex: none; width: 10px; height: 6px; margin-top: 6px; border-left: 2px solid #d7ff00; border-bottom: 2px solid #d7ff00; transform: rotate(-45deg)"></span><span>不放心?把输入框左下角的 <span style="display: inline-flex; align-items: center; gap: 4px; padding: 0 7px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); color: #fafaf7; font-size: 12px; white-space: nowrap">工作区可写</span> 切成「只读」,它就不能改任何文件</span></li>+ </ul>+ <div style="display: flex; align-items: center; justify-content: space-between; gap: 8px">+ <button type="button" id="c-later" style="min-height: 36px; padding: 0 4px; color: #a1a1aa; font-size: 13.5px">稍后再说</button>+ <a id="c-next" href="Step5-Memory.html" style="display: inline-flex; align-items: center; gap: 8px; min-height: 36px; padding: 0 16px; border-radius: 999px; background: #d7ff00; color: #161a00; font-weight: 600; font-size: 14px; text-decoration: none">下一步</a>+ </div>+ </section>+ </div>+ </div>++ <div style="padding: 0 24px 24px">+ <div style="max-width: 760px; margin: 0 auto; border-radius: 18px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <textarea id="input" class="input" rows="1" aria-label="消息" placeholder="给「小蓝」发消息,/ 查看命令"></textarea>+ <div style="display: flex; align-items: center; gap: 6px; padding: 6px 8px 8px">+ <button type="button" aria-label="更多操作" style="display: grid; place-items: center; width: 32px; height: 32px; border-radius: 50%; color: #a1a1aa">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>+ </button>+ <button type="button" style="display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 10px; border-radius: 999px; color: #fafaf7; font-size: 12.5px; box-shadow: inset 0 0 0 1px rgba(215,255,0,.45)">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3l7 3v6c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6z"/></svg>+ 工作区可写+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>+ </button>+ <span style="flex: 1"></span>+ <button type="button" style="display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 10px; border-radius: 999px; color: #a1a1aa; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12.5px">gpt-6.1-terra</button>+ <button type="button" id="send" aria-label="发送" style="display: grid; place-items: center; width: 32px; height: 32px; border-radius: 50%; background: #161a00; color: #d7ff00; opacity: .5">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 19V5M5 12l7-7 7 7"/></svg>+ </button>+ </div>+ </div>+ </div>+ </main>+</div>++<script type="module" src="js/page-hands.js"></script>+</body>+</html>diff --git a/anymodelbot_design/onboarding/Step5-Memory.html b/anymodelbot_design/onboarding/Step5-Memory.htmlnew file mode 100644index 0000000..b954509--- /dev/null+++ b/anymodelbot_design/onboarding/Step5-Memory.html@@ -0,0 +1,212 @@+<!doctype html>+<html lang="zh-CN">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>第 5 步 · 让它记住你 · 新手引导预览</title>+<style>+body{margin:0;background:#060706}+*,*::before,*::after{box-sizing:border-box}+button{font:inherit;color:inherit;border:0;background:none;padding:0;cursor:pointer}+input,textarea{font:inherit}+a{color:#d7ff00}a:hover{color:#e9ff66}+</style>+<link rel="stylesheet" href="css/bots.css">+<link rel="stylesheet" href="css/proto.css">+</head>+<body data-page="memory">+<div style="min-height: 100vh; display: flex; flex-wrap: wrap; background: #060706; color: #fafaf7; font-family: Geist, 'Noto Sans SC', 'PingFang SC', system-ui, sans-serif; font-size: 14px; line-height: 1.5">++ <aside aria-label="机器人" style="flex: 1 1 248px; max-width: 100%; display: flex; flex-direction: column; gap: 6px; padding: 14px 12px 12px; background: #0a0b0a; border-right: 1px solid rgba(255,255,255,.10)">+ <div aria-hidden="true" style="display: flex; gap: 8px; padding: 4px 6px 14px">+ <span style="width: 11px; height: 11px; border-radius: 50%; background: rgba(127,127,127,.45)"></span>+ <span style="width: 11px; height: 11px; border-radius: 50%; background: rgba(127,127,127,.45)"></span>+ <span style="width: 11px; height: 11px; border-radius: 50%; background: rgba(127,127,127,.45)"></span>+ </div>+ <button type="button" style="display: flex; align-items: center; gap: 10px; min-height: 40px; padding: 0 10px; border-radius: 10px; color: #a1a1aa; font-size: 13.5px">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>+ 新建机器人+ </button>+ <div style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; letter-spacing: .08em; color: #a1a1aa; padding: 10px 10px 4px">机器人</div>+ <a href="Main.html" style="display: flex; align-items: center; gap: 10px; min-height: 52px; padding: 6px 10px; border-radius: 12px; background: rgba(255,255,255,.06); color: #fafaf7; text-decoration: none">+ <span class="face" data-char="blue" style="width: 34px; height: 34px; flex: none"></span>+ <span style="display: flex; flex-direction: column; min-width: 0">+ <span style="font-weight: 600; font-size: 14px">小蓝</span>+ <span style="color: #a1a1aa; font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">记得:回答简短,结论先行。</span>+ </span>+ </a>+ <div style="flex: 1"></div>+ <a href="Main.html" style="display: flex; align-items: center; gap: 10px; min-height: 44px; padding: 0 12px; border-radius: 12px; background: rgba(215,255,0,.10); box-shadow: inset 0 0 0 1px rgba(215,255,0,.30); color: #fafaf7; font-size: 13.5px; text-decoration: none">+ <span style="display: flex; gap: 3px" aria-hidden="true">+ <span style="width: 5px; height: 14px; border-radius: 2px; background: #d7ff00"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: #d7ff00"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: #d7ff00"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: #d7ff00"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: #d7ff00"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: rgba(255,255,255,.16)"></span>+ </span>+ <span style="flex: 1; font-weight: 500">上手清单</span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">5 / 6</span>+ </a>+ <button type="button" style="display: flex; align-items: center; gap: 10px; min-height: 48px; padding: 0 10px; border-radius: 12px; text-align: left">+ <span aria-hidden="true" style="display: grid; place-items: center; width: 28px; height: 28px; border-radius: 50%; background: #d7ff00; color: #161a00; font-weight: 700; font-size: 13px">Z</span>+ <span style="flex: 1; font-size: 13.5px">我的账户</span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12.5px; color: #a1a1aa">$12.36</span>+ </button>+ </aside>++ <div style="flex: 999 1 560px; min-width: 0; display: flex; flex-wrap: wrap; min-height: 100vh">+ <main style="position: relative; flex: 999 1 420px; min-width: 0; display: flex; flex-direction: column">+ <header style="display: flex; align-items: center; gap: 8px; height: 54px; padding: 0 16px; border-bottom: 1px solid rgba(255,255,255,.10)">+ <button type="button" aria-pressed="true" style="display: inline-flex; align-items: center; gap: 8px; height: 34px; padding: 0 12px 0 6px; border-radius: 999px; background: rgba(255,255,255,.08); box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); font-weight: 600; font-size: 14px">+ <span class="face" data-char="blue" style="width: 24px; height: 24px"></span>+ 小蓝+ </button>+ <span style="flex: 1"></span>+ <button type="button" aria-label="开始新的一段对话" style="display: grid; place-items: center; width: 36px; height: 36px; border-radius: 50%; color: #a1a1aa">+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>+ </button>+ <button type="button" aria-label="信息面板" aria-pressed="true" style="display: grid; place-items: center; width: 36px; height: 36px; border-radius: 50%; background: rgba(255,255,255,.06); color: #fafaf7">+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="16" rx="3"/><path d="M15 4v16"/></svg>+ </button>+ </header>++ <div style="flex: 1; overflow: auto">+ <div id="log" style="max-width: 720px; margin: 0 auto; padding: 32px 24px 24px; display: flex; flex-direction: column; gap: 22px">+ <div style="align-self: flex-end; max-width: 80%; padding: 10px 16px; border-radius: 18px; background: rgba(255,255,255,.07)">记住:回答尽量简短,结论放在最前面。</div>+ <div style="display: flex; flex-direction: column; gap: 8px; align-items: flex-start">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11.5px; color: #a1a1aa">用时 2 秒</span>+ <p style="margin: 0; line-height: 1.75">记下了。以后先说结论,尽量简短。</p>+ <span style="display: inline-flex; align-items: center; gap: 6px; height: 26px; padding: 0 10px; border-radius: 999px; background: rgba(215,255,0,.10); box-shadow: inset 0 0 0 1px rgba(215,255,0,.30); color: #d7ff00; font-size: 12px">+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 4h14v16l-7-4-7 4z"/></svg>+ 已写入记忆+ </span>+ </div>+ <div style="align-self: flex-end; max-width: 80%; padding: 10px 16px; border-radius: 18px; background: rgba(255,255,255,.07)">你还记得我的习惯吗?</div>+ <div style="display: flex; flex-direction: column; gap: 6px">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11.5px; color: #a1a1aa">用时 1 秒</span>+ <p style="margin: 0; line-height: 1.75">记得:回答简短,结论先行。</p>+ </div>+ </div>+ </div>++ <!-- 引导卡片:指向右侧「记忆」 -->+ <section id="coach" hidden aria-label="上手引导" style="position: absolute; right: 22px; top: 300px; z-index: 3; width: 340px; padding: 20px 20px 16px; border-radius: 20px; background: #0b0b10; box-shadow: 0 0 0 1px rgba(255,255,255,.18), 0 30px 80px -20px rgba(0,0,0,.75)">+ <span class="face" data-char="blue" style="position: absolute; right: 18px; top: -40px; width: 52px; height: 52px"></span>+ <span id="arrow" aria-hidden="true" style="position: absolute; right: -7px; top: 40px; width: 14px; height: 14px; transform: rotate(45deg); background: #0b0b10; box-shadow: 1px -1px 0 rgba(255,255,255,.18)"></span>+ <p id="c-kick" style="display: flex; align-items: center; gap: 10px; margin: 0 0 12px; font-size: 12.5px; letter-spacing: .06em; color: #a1a1aa">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">05 / 06</span>上手清单+ <span id="c-badge" style="display: inline-flex; align-items: center; gap: 4px; height: 22px; padding: 0 8px; border-radius: 999px; background: #d7ff00; color: #161a00; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; letter-spacing: 0">+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12 5 5 9-10"/></svg>完成+ </span>+ </p>+ <h2 id="c-title" style="margin: 0 0 6px; font-size: 19px; font-weight: 600; letter-spacing: -.01em">让它记住你</h2>+ <p id="c-body" style="margin: 0 0 12px; color: #a1a1aa; line-height: 1.7">告诉小蓝你的习惯和常用信息,它会记下来。开新对话、到微信里,它都记得。</p>+ <ul id="c-list" style="list-style: none; margin: 0 0 14px; padding: 12px 0 0; border-top: 1px solid rgba(255,255,255,.10); display: flex; flex-direction: column; gap: 9px; font-size: 13px; color: #a1a1aa">+ <li style="display: flex; gap: 10px"><span aria-hidden="true" style="flex: none; width: 10px; height: 6px; margin-top: 6px; border-left: 2px solid #d7ff00; border-bottom: 2px solid #d7ff00; transform: rotate(-45deg)"></span>说「记住……」就行;聊天中它也会自己记下重要的事</li>+ <li style="display: flex; gap: 10px"><span aria-hidden="true" style="flex: none; width: 10px; height: 6px; margin-top: 6px; border-left: 2px solid #d7ff00; border-bottom: 2px solid #d7ff00; transform: rotate(-45deg)"></span>想让它忘掉,说「忘掉……」,或在右边删掉</li>+ <li style="display: flex; gap: 10px"><span aria-hidden="true" style="flex: none; width: 10px; height: 6px; margin-top: 6px; border-left: 2px solid #d7ff00; border-bottom: 2px solid #d7ff00; transform: rotate(-45deg)"></span>密码、密钥这类内容,它不会记</li>+ </ul>+ <div id="c-try" style="display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin-bottom: 14px; padding: 10px 10px 10px 14px; border-radius: 14px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; letter-spacing: .06em; color: #a1a1aa" id="c-try-label">再试试</span>+ <span id="c-try-text" style="flex: 1; min-width: 140px; font-size: 13.5px">忘掉:每天的待办记在「今日待办.md」</span>+ </div>+ <div style="display: flex; align-items: center; justify-content: space-between; gap: 8px">+ <button type="button" id="c-later" style="min-height: 36px; padding: 0 4px; color: #a1a1aa; font-size: 13.5px">稍后再说</button>+ <a id="c-next" href="Step6-Media.html" style="display: inline-flex; align-items: center; gap: 8px; min-height: 36px; padding: 0 16px; border-radius: 999px; background: #d7ff00; color: #161a00; font-weight: 600; font-size: 14px; text-decoration: none">下一步</a>+ </div>+ </section>++ <div style="padding: 0 24px 24px">+ <div style="max-width: 720px; margin: 0 auto; border-radius: 18px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <textarea id="input" class="input" rows="1" aria-label="消息" placeholder="给「小蓝」发消息,/ 查看命令"></textarea>+ <div style="display: flex; align-items: center; gap: 6px; padding: 6px 8px 8px">+ <button type="button" aria-label="更多操作" style="display: grid; place-items: center; width: 32px; height: 32px; border-radius: 50%; color: #a1a1aa">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>+ </button>+ <button type="button" style="display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 10px; border-radius: 999px; color: #a1a1aa; font-size: 12.5px">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3l7 3v6c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6z"/></svg>+ 工作区可写+ </button>+ <span style="flex: 1"></span>+ <button type="button" style="display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 10px; border-radius: 999px; color: #a1a1aa; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12.5px">gpt-6.1-terra</button>+ <button type="button" id="send" aria-label="发送" style="display: grid; place-items: center; width: 32px; height: 32px; border-radius: 50%; background: #161a00; color: #d7ff00; opacity: .5">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 19V5M5 12l7-7 7 7"/></svg>+ </button>+ </div>+ </div>+ </div>+ </main>++ <aside aria-label="信息面板" style="flex: 1 1 340px; max-width: 100%; display: flex; flex-direction: column; background: #0a0b0a; border-left: 1px solid rgba(255,255,255,.10)">+ <div style="display: flex; align-items: center; gap: 4px; height: 54px; padding: 0 10px 0 18px; border-bottom: 1px solid rgba(255,255,255,.10)">+ <span style="flex: 1; font-weight: 600">小蓝</span>+ <button type="button" aria-label="机器人设置" style="display: grid; place-items: center; width: 34px; height: 34px; border-radius: 50%; color: #a1a1aa">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M4.2 4.2l2.1 2.1M17.7 17.7l2.1 2.1M2 12h3M19 12h3M4.2 19.8l2.1-2.1M17.7 6.3l2.1-2.1"/></svg>+ </button>+ <button type="button" aria-label="关闭信息面板" style="display: grid; place-items: center; width: 34px; height: 34px; border-radius: 50%; color: #a1a1aa">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"/></svg>+ </button>+ </div>+ <div style="flex: 1; overflow: auto; padding: 16px 14px; display: flex; flex-direction: column; gap: 8px">+ <div style="padding: 0 6px; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; letter-spacing: .08em; color: #a1a1aa">渠道</div>+ <div style="border-radius: 16px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <div style="display: flex; align-items: center; gap: 10px; min-height: 52px; padding: 8px 14px; border-bottom: 1px solid rgba(255,255,255,.10)">+ <span style="flex: 1"><span style="display: block; font-weight: 500">飞书</span></span>+ <span style="height: 22px; padding: 0 9px; border-radius: 999px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); color: #a1a1aa; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; line-height: 22px">未连接</span>+ </div>+ <div style="display: flex; align-items: center; gap: 10px; min-height: 52px; padding: 8px 14px">+ <span style="flex: 1"><span style="display: block; font-weight: 500">微信</span></span>+ <span style="display: inline-flex; align-items: center; gap: 6px; height: 22px; padding: 0 9px; border-radius: 999px; background: rgba(111,217,155,.12); color: #6fd99b; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px">+ <span aria-hidden="true" style="width: 6px; height: 6px; border-radius: 50%; background: #6fd99b"></span>已连接+ </span>+ </div>+ </div>++ <div style="padding: 14px 6px 0; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; letter-spacing: .08em; color: #a1a1aa">待审批</div>+ <div style="padding: 14px; border-radius: 16px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); color: #a1a1aa; font-size: 13px">没有待处理的审批</div>++ <div style="display: flex; align-items: center; padding: 14px 6px 0; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; letter-spacing: .08em; color: #a1a1aa">+ <span style="flex: 1">记忆</span>+ <span id="mem-count" style="letter-spacing: 0">2 条</span>+ </div>+ <div id="mem" style="border-radius: 16px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <div style="display: flex; align-items: flex-start; gap: 10px; padding: 12px 10px 12px 14px; border-bottom: 1px solid rgba(255,255,255,.10)">+ <span style="flex: 1; min-width: 0">+ <span style="display: block; font-size: 13.5px">回答尽量简短,结论放在最前面</span>+ <span style="display: block; color: #a1a1aa; font-size: 12px">机器人记忆 · 刚刚</span>+ </span>+ <button type="button" aria-label="删除这条记忆" style="display: grid; place-items: center; width: 30px; height: 30px; border-radius: 50%; color: #a1a1aa">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"/></svg>+ </button>+ </div>+ <div style="display: flex; align-items: flex-start; gap: 10px; padding: 12px 10px 12px 14px">+ <span style="flex: 1; min-width: 0">+ <span style="display: block; font-size: 13.5px">每天的待办记在工作区「今日待办.md」</span>+ <span style="display: block; color: #a1a1aa; font-size: 12px">机器人记忆 · 自动整理</span>+ </span>+ <button type="button" aria-label="删除这条记忆" style="display: grid; place-items: center; width: 30px; height: 30px; border-radius: 50%; color: #a1a1aa">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"/></svg>+ </button>+ </div>+ </div>++ <div style="padding: 14px 6px 0; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; letter-spacing: .08em; color: #a1a1aa">最近会话</div>+ <div style="border-radius: 16px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <div style="display: flex; align-items: center; gap: 10px; padding: 10px 14px; border-bottom: 1px solid rgba(255,255,255,.10)">+ <span style="flex: 1; min-width: 0"><span style="display: block; font-size: 13.5px">网页 · 小蓝</span><span style="display: block; color: #a1a1aa; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">记得:回答简短,结论先行。</span></span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; color: #a1a1aa; font-size: 11.5px">刚刚</span>+ </div>+ <div style="display: flex; align-items: center; gap: 10px; padding: 10px 14px">+ <span style="flex: 1; min-width: 0"><span style="display: block; font-size: 13.5px">微信 · 我</span><span style="display: block; color: #a1a1aa; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">在呢,有什么要我做的?</span></span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; color: #a1a1aa; font-size: 11.5px">3 分钟前</span>+ </div>+ </div>+ </div>+ </aside>+ </div>+</div>++<script type="module" src="js/page-memory.js"></script>+</body>+</html>diff --git a/anymodelbot_design/onboarding/Step6-Media.html b/anymodelbot_design/onboarding/Step6-Media.htmlnew file mode 100644index 0000000..01eba49--- /dev/null+++ b/anymodelbot_design/onboarding/Step6-Media.html@@ -0,0 +1,181 @@+<!doctype html>+<html lang="zh-CN">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>第 6 步 · 生成一张图 · 新手引导预览</title>+<style>+body{margin:0;background:#060706}+*,*::before,*::after{box-sizing:border-box}+button{font:inherit;color:inherit;border:0;background:none;padding:0;cursor:pointer}+input,textarea{font:inherit}+a{color:#d7ff00}a:hover{color:#e9ff66}+</style>+<link rel="stylesheet" href="css/bots.css">+<link rel="stylesheet" href="css/proto.css">+</head>+<body data-page="media">+<div style="min-height: 100vh; display: flex; flex-wrap: wrap; background: #060706; color: #fafaf7; font-family: Geist, 'Noto Sans SC', 'PingFang SC', system-ui, sans-serif; font-size: 14px; line-height: 1.5">++ <aside aria-label="机器人" style="flex: 1 1 248px; max-width: 100%; display: flex; flex-direction: column; gap: 6px; padding: 14px 12px 12px; background: #0a0b0a; border-right: 1px solid rgba(255,255,255,.10)">+ <div aria-hidden="true" style="display: flex; gap: 8px; padding: 4px 6px 14px">+ <span style="width: 11px; height: 11px; border-radius: 50%; background: rgba(127,127,127,.45)"></span>+ <span style="width: 11px; height: 11px; border-radius: 50%; background: rgba(127,127,127,.45)"></span>+ <span style="width: 11px; height: 11px; border-radius: 50%; background: rgba(127,127,127,.45)"></span>+ </div>+ <button type="button" style="display: flex; align-items: center; gap: 10px; min-height: 40px; padding: 0 10px; border-radius: 10px; color: #a1a1aa; font-size: 13.5px">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>+ 新建机器人+ </button>+ <div style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; letter-spacing: .08em; color: #a1a1aa; padding: 10px 10px 4px">机器人</div>+ <a href="Main.html" style="display: flex; align-items: center; gap: 10px; min-height: 52px; padding: 6px 10px; border-radius: 12px; background: rgba(255,255,255,.06); color: #fafaf7; text-decoration: none">+ <span class="face" data-char="blue" style="width: 34px; height: 34px; flex: none"></span>+ <span style="display: flex; flex-direction: column; min-width: 0">+ <span style="font-weight: 600; font-size: 14px">小蓝</span>+ <span style="color: #a1a1aa; font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">等你确认:生成图片</span>+ </span>+ </a>+ <div style="flex: 1"></div>+ <a href="Main.html" style="display: flex; align-items: center; gap: 10px; min-height: 44px; padding: 0 12px; border-radius: 12px; background: rgba(215,255,0,.10); box-shadow: inset 0 0 0 1px rgba(215,255,0,.30); color: #fafaf7; font-size: 13.5px; text-decoration: none">+ <span style="display: flex; gap: 3px" aria-hidden="true">+ <span style="width: 5px; height: 14px; border-radius: 2px; background: #d7ff00"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: #d7ff00"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: #d7ff00"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: #d7ff00"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: #d7ff00"></span>+ <span style="width: 5px; height: 14px; border-radius: 2px; background: rgba(255,255,255,.16)"></span>+ </span>+ <span style="flex: 1; font-weight: 500">上手清单</span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">5 / 6</span>+ </a>+ <button type="button" style="display: flex; align-items: center; gap: 10px; min-height: 48px; padding: 0 10px; border-radius: 12px; text-align: left">+ <span aria-hidden="true" style="display: grid; place-items: center; width: 28px; height: 28px; border-radius: 50%; background: #d7ff00; color: #161a00; font-weight: 700; font-size: 13px">Z</span>+ <span style="flex: 1; font-size: 13.5px">我的账户</span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12.5px; color: #a1a1aa">$12.35</span>+ </button>+ </aside>++ <main style="flex: 999 1 560px; min-width: 0; display: flex; flex-direction: column; min-height: 100vh">+ <header style="display: flex; align-items: center; gap: 8px; height: 54px; padding: 0 16px; border-bottom: 1px solid rgba(255,255,255,.10)">+ <button type="button" style="display: inline-flex; align-items: center; gap: 8px; height: 34px; padding: 0 12px 0 6px; border-radius: 999px; background: rgba(255,255,255,.05); box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); font-weight: 600; font-size: 14px">+ <span class="face" data-char="blue" style="width: 24px; height: 24px"></span>+ 小蓝+ </button>+ <span style="flex: 1"></span>+ <button type="button" aria-label="开始新的一段对话" style="display: grid; place-items: center; width: 36px; height: 36px; border-radius: 50%; color: #a1a1aa">+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>+ </button>+ <button type="button" aria-label="信息面板" style="display: grid; place-items: center; width: 36px; height: 36px; border-radius: 50%; color: #a1a1aa">+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="16" rx="3"/><path d="M15 4v16"/></svg>+ </button>+ </header>++ <div style="flex: 1; overflow: auto">+ <div style="max-width: 980px; margin: 0 auto; padding: 32px 24px 24px; display: flex; flex-wrap: wrap; gap: 24px 40px; align-items: flex-start">++ <div id="log" style="flex: 999 1 460px; min-width: 0; display: flex; flex-direction: column; gap: 22px">+ <div id="status" hidden style="display: flex; flex-direction: column; gap: 6px">+ <span style="display: inline-flex; align-items: center; gap: 8px; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11.5px; color: #a1a1aa"><span id="status-dot" aria-hidden="true" style="width: 7px; height: 7px; border-radius: 50%; background: #f2b544"></span><span id="status-text">等你确认</span>+ </span>+ </div>++ <!-- 生成前的确认卡片(与审批 / 提问卡片同一套样式) -->+ <form id="confirm" hidden style="max-width: 520px; padding: 18px; border-radius: 20px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <div style="display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px">+ <span style="display: inline-flex; align-items: center; gap: 8px; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11.5px; letter-spacing: .06em; color: #a1a1aa">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="16" rx="3"/><circle cx="9" cy="10" r="2"/><path d="m21 16-5-5-9 9"/></svg>+ 生成图片+ </span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11.5px; color: #a1a1aa">10 分钟内有效</span>+ </div>+ <p style="margin: 0 0 8px; font-size: 16px; font-weight: 600">这次用 <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-weight: 500">[默认图片模型]</span> 生成图片吗?</p>+ <p style="margin: 0 0 14px; color: #a1a1aa; font-size: 13px; line-height: 1.7; white-space: pre-line">提示词:戴着耳机的蓝色小机器人,扁平插画风+尺寸 1024×1024 · 1 张+也可以直接回复其他模型名。</p>+ <fieldset style="margin: 0 0 12px; padding: 0; border: 0; display: flex; flex-direction: column; gap: 6px">+ <legend style="position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0)">选择模型</legend>+ <label style="display: flex; align-items: center; gap: 12px; min-height: 48px; padding: 8px 12px; border-radius: 14px; background: rgba(215,255,0,.10); box-shadow: inset 0 0 0 1px rgba(215,255,0,.45); cursor: pointer">+ <input type="radio" name="m" checked style="accent-color: #d7ff00; width: 16px; height: 16px; margin: 0">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">A</span>+ <span style="flex: 1; min-width: 0; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 13px">[默认图片模型]</span>+ <span style="color: #a1a1aa; font-size: 12.5px">默认 · 约 $[0.04] / 张</span>+ </label>+ <label style="display: flex; align-items: center; gap: 12px; min-height: 48px; padding: 8px 12px; border-radius: 14px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); cursor: pointer">+ <input type="radio" name="m" style="accent-color: #d7ff00; width: 16px; height: 16px; margin: 0">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #a1a1aa">B</span>+ <span style="flex: 1; min-width: 0; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 13px">[图片模型 2]</span>+ <span style="color: #a1a1aa; font-size: 12.5px">约 $[0.02] / 张</span>+ </label>+ <label style="display: flex; align-items: center; gap: 12px; min-height: 48px; padding: 8px 12px; border-radius: 14px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); cursor: pointer">+ <input type="radio" name="m" style="accent-color: #d7ff00; width: 16px; height: 16px; margin: 0">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #a1a1aa">C</span>+ <span style="flex: 1; min-width: 0; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 13px">[图片模型 3]</span>+ <span style="color: #a1a1aa; font-size: 12.5px">约 $[0.08] / 张</span>+ </label>+ <label style="display: flex; align-items: center; gap: 12px; min-height: 48px; padding: 8px 12px; border-radius: 14px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); cursor: pointer">+ <input type="radio" name="m" style="accent-color: #d7ff00; width: 16px; height: 16px; margin: 0">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #a1a1aa">D</span>+ <span style="flex: 1; min-width: 0; font-size: 13.5px">取消</span>+ <span style="color: #a1a1aa; font-size: 12.5px">这次不生成</span>+ </label>+ </fieldset>+ <label style="display: block; margin-bottom: 14px">+ <span style="position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0)">其他回答</span>+ <input type="text" placeholder="或者输入其他回答" style="width: 100%; height: 40px; padding: 0 12px; border: 0; border-radius: 12px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); color: #fafaf7; font-size: 13.5px; outline: none">+ </label>+ <div style="display: flex; align-items: center; gap: 10px">+ <button type="button" style="min-height: 40px; padding: 0 20px; border-radius: 999px; background: #d7ff00; color: #161a00; font-weight: 600; font-size: 14px" id="go">确认生成</button>+ <span style="color: #a1a1aa; font-size: 12.5px">确认后才会扣费</span>+ </div>+ </form>+ <div id="result" hidden></div>+ </div>++ <!-- 引导卡片:指向左边的确认卡片 -->+ <section id="coach" hidden aria-label="上手引导" style="position: relative; flex: 1 1 300px; max-width: 340px; margin-top: 120px; padding: 20px 20px 16px; border-radius: 20px; background: #0b0b10; box-shadow: 0 0 0 1px rgba(255,255,255,.18), 0 30px 80px -20px rgba(0,0,0,.75)">+ <span class="face" data-char="blue" style="position: absolute; right: 18px; top: -40px; width: 52px; height: 52px"></span>+ <span id="arrow" aria-hidden="true" style="position: absolute; left: -7px; top: 44px; width: 14px; height: 14px; transform: rotate(45deg); background: #0b0b10; box-shadow: -1px 1px 0 rgba(255,255,255,.18)"></span>+ <p id="c-kick" style="display: flex; align-items: center; gap: 10px; margin: 0 0 12px; font-size: 12.5px; letter-spacing: .06em; color: #a1a1aa">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">06 / 06</span>上手清单+ </p>+ <h2 id="c-title" style="margin: 0 0 6px; font-size: 19px; font-weight: 600; letter-spacing: -.01em">生成一张图</h2>+ <p id="c-body" style="margin: 0 0 12px; color: #a1a1aa; line-height: 1.7">小蓝可以画图、做视频。每次生成前,都会先问你用哪个模型,并给出参考价。</p>+ <ul id="c-list" style="list-style: none; margin: 0 0 14px; padding: 12px 0 0; border-top: 1px solid rgba(255,255,255,.10); display: flex; flex-direction: column; gap: 9px; font-size: 13px; color: #a1a1aa">+ <li style="display: flex; gap: 10px"><span aria-hidden="true" style="flex: none; width: 10px; height: 6px; margin-top: 6px; border-left: 2px solid #d7ff00; border-bottom: 2px solid #d7ff00; transform: rotate(-45deg)"></span>你点「确认生成」才会生成,才会花钱</li>+ <li style="display: flex; gap: 10px"><span aria-hidden="true" style="flex: none; width: 10px; height: 6px; margin-top: 6px; border-left: 2px solid #d7ff00; border-bottom: 2px solid #d7ff00; transform: rotate(-45deg)"></span>可以换个模型,或者直接取消</li>+ <li style="display: flex; gap: 10px"><span aria-hidden="true" style="flex: none; width: 10px; height: 6px; margin-top: 6px; border-left: 2px solid #d7ff00; border-bottom: 2px solid #d7ff00; transform: rotate(-45deg)"></span>10 分钟内没回答,就不生成</li>+ </ul>+ <p id="c-note" style="margin: 0 0 16px; color: #a1a1aa; font-size: 12.5px">默认的图片、视频模型,在「设置 → Modelflare」里改。</p>+ <div style="display: flex; align-items: center; justify-content: space-between; gap: 8px">+ <button type="button" id="c-later" style="min-height: 36px; padding: 0 4px; color: #a1a1aa; font-size: 13.5px">稍后再说</button>+ <a id="c-next" href="Main.html" style="display: inline-flex; align-items: center; gap: 8px; min-height: 36px; padding: 0 16px; border-radius: 999px; background: #d7ff00; color: #161a00; font-weight: 600; font-size: 14px; text-decoration: none">完成清单</a>+ </div>+ </section>+ </div>+ </div>++ <div style="padding: 0 24px 24px">+ <div style="max-width: 760px; margin: 0 auto; border-radius: 18px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <textarea id="input" class="input" rows="1" aria-label="消息" placeholder="给「小蓝」发消息,/ 查看命令"></textarea>+ <div style="display: flex; align-items: center; gap: 6px; padding: 6px 8px 8px">+ <button type="button" aria-label="更多操作" style="display: grid; place-items: center; width: 32px; height: 32px; border-radius: 50%; color: #a1a1aa">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>+ </button>+ <button type="button" style="display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 10px; border-radius: 999px; color: #a1a1aa; font-size: 12.5px">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3l7 3v6c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6z"/></svg>+ 工作区可写+ </button>+ <span style="flex: 1"></span>+ <button type="button" style="display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 10px; border-radius: 999px; color: #a1a1aa; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12.5px">gpt-6.1-terra</button>+ <button type="button" id="send" aria-label="发送" style="display: grid; place-items: center; width: 32px; height: 32px; border-radius: 50%; background: #161a00; color: #d7ff00; opacity: .5">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 19V5M5 12l7-7 7 7"/></svg>+ </button>+ </div>+ </div>+ </div>+ </main>+</div>++<script type="module" src="js/page-media.js"></script>+</body>+</html>diff --git a/anymodelbot_design/onboarding/Tips.html b/anymodelbot_design/onboarding/Tips.htmlnew file mode 100644index 0000000..bb378a8--- /dev/null+++ b/anymodelbot_design/onboarding/Tips.html@@ -0,0 +1,253 @@+<!doctype html>+<html lang="zh-CN">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>随用随教的小提示 · 新手引导预览</title>+<style>+body{margin:0;background:#060706}+*,*::before,*::after{box-sizing:border-box}+button{font:inherit;color:inherit;border:0;background:none;padding:0;cursor:pointer}+input,textarea{font:inherit}+a{color:#d7ff00}a:hover{color:#e9ff66}+</style>+<link rel="stylesheet" href="css/bots.css">+<link rel="stylesheet" href="css/proto.css">+</head>+<body data-page="tips">+<div style="min-height: 100vh; background: #060706; color: #fafaf7; font-family: Geist, 'Noto Sans SC', 'PingFang SC', system-ui, sans-serif; font-size: 14px; line-height: 1.5; padding: 104px clamp(16px, 5vw, 48px) 96px">+ <div style="max-width: 1200px; margin: 0 auto">++ <!-- 章节头 -->+ <header style="position: relative; display: grid; grid-template-columns: repeat(12, minmax(0, 1fr)); column-gap: 32px; margin-bottom: 64px; padding-top: 18px; border-top: 1px solid rgba(255,255,255,.10)">+ <span class="face" data-char="orange" style="position: absolute; right: 0; bottom: calc(100% - 6px); width: 64px; height: 64px"></span>+ <p style="grid-column: 1 / -1; display: flex; align-items: baseline; gap: 14px; margin: 0 0 40px; font-size: 13px; letter-spacing: .08em; color: #a1a1aa">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; letter-spacing: .04em; color: #d7ff00">07</span>+ <span style="color: rgba(255,255,255,.18)">/</span>随用随教+ </p>+ <h1 style="grid-column: 1 / -1; margin: 0; font-size: clamp(34px, 4.9vw, 64px); line-height: 1.16; letter-spacing: -.012em; font-weight: 600">+ <span style="display: block">第一次遇到时,</span>+ <span style="display: block; color: #a1a1aa">只提醒一次。</span>+ </h1>+ <p style="grid-column: 7 / -1; margin: 28px 0 0; max-width: 25em; color: #a1a1aa; font-size: 17px; line-height: 1.75">这些提示不进清单:用户第一次碰到某个场景时,在旁边轻轻出现;点「知道了」就不再出现。</p>+ </header>++ <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 340px), 1fr)); gap: 24px">++ <!-- 01 审批卡片 -->+ <article style="display: flex; flex-direction: column; gap: 14px; padding: 22px; border-radius: 20px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <p style="display: flex; align-items: baseline; gap: 10px; margin: 0; font-size: 13px; color: #a1a1aa"><span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">01</span>第一次弹出审批卡片</p>+ <div style="padding: 14px; border-radius: 16px; background: #060706; box-shadow: 0 0 0 2px #d7ff00, 0 0 0 6px rgba(215,255,0,.14)">+ <div style="display: flex; justify-content: space-between; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; color: #a1a1aa; margin-bottom: 6px"><span>需要你的批准</span><span>7F3K</span></div>+ <div style="font-size: 13.5px; font-weight: 500; margin-bottom: 8px">整理好的清单要写到工作区以外</div>+ <div style="padding: 8px 10px; border-radius: 10px; background: #101110; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11.5px; color: #a1a1aa; margin-bottom: 10px; overflow-wrap: anywhere">写入 ~/Documents/整理清单.md</div>+ <div style="display: flex; gap: 8px">+ <button type="button" style="min-height: 32px; padding: 0 12px; border-radius: 999px; background: #d7ff00; color: #161a00; font-weight: 600; font-size: 12.5px">允许(仅本次)</button>+ <button type="button" style="min-height: 32px; padding: 0 12px; border-radius: 999px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); font-size: 12.5px">拒绝</button>+ </div>+ </div>+ <div style="position: relative; display: flex; gap: 10px; padding: 14px; border-radius: 16px; background: #101110; box-shadow: 0 0 0 1px rgba(255,255,255,.18)">+ <span class="face" data-char="blue" style="flex: none; width: 30px; height: 30px"></span>+ <div style="flex: 1; min-width: 0">+ <div style="font-weight: 600; font-size: 14.5px; margin-bottom: 2px">它在等你点头</div>+ <p style="margin: 0 0 10px; color: #a1a1aa; font-size: 13px; line-height: 1.65">它想做一件超出工作区的事。点「允许(仅本次)」放行,点「拒绝」它就不做。</p>+ <button type="button" style="min-height: 30px; padding: 0 12px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); font-size: 12.5px">知道了</button>+ </div>+ </div>+ </article>++ <!-- 02 信息面板 -->+ <article style="display: flex; flex-direction: column; gap: 14px; padding: 22px; border-radius: 20px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <p style="display: flex; align-items: baseline; gap: 10px; margin: 0; font-size: 13px; color: #a1a1aa"><span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">02</span>第一次打开信息面板</p>+ <div style="display: flex; flex-direction: column; gap: 8px; padding: 14px; border-radius: 16px; background: #060706; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <div style="display: flex; align-items: center; gap: 6px; padding-bottom: 8px; border-bottom: 1px solid rgba(255,255,255,.10)">+ <span style="flex: 1; font-weight: 600; font-size: 13.5px">小蓝</span>+ <span aria-hidden="true" style="display: grid; place-items: center; width: 30px; height: 30px; border-radius: 50%; color: #fafaf7; box-shadow: 0 0 0 2px #d7ff00, 0 0 0 6px rgba(215,255,0,.14)">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M4.2 4.2l2.1 2.1M17.7 17.7l2.1 2.1M2 12h3M19 12h3M4.2 19.8l2.1-2.1M17.7 6.3l2.1-2.1"/></svg>+ </span>+ </div>+ <div style="display: flex; flex-wrap: wrap; gap: 6px; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; color: #a1a1aa">+ <span style="padding: 2px 8px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">渠道</span>+ <span style="padding: 2px 8px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">待审批</span>+ <span style="padding: 2px 8px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">记忆</span>+ <span style="padding: 2px 8px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">最近会话</span>+ </div>+ </div>+ <div style="display: flex; gap: 10px; padding: 14px; border-radius: 16px; background: #101110; box-shadow: 0 0 0 1px rgba(255,255,255,.18)">+ <span class="face" data-char="blue" style="flex: none; width: 30px; height: 30px"></span>+ <div style="flex: 1; min-width: 0">+ <div style="font-weight: 600; font-size: 14.5px; margin-bottom: 2px">关于小蓝的一切都在这里</div>+ <p style="margin: 0 0 10px; color: #a1a1aa; font-size: 13px; line-height: 1.65">渠道、待审批、记忆和最近会话都在这个面板。点 ⚙ 可以改它的模型、权限和预算。</p>+ <button type="button" style="min-height: 30px; padding: 0 12px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); font-size: 12.5px">知道了</button>+ </div>+ </div>+ </article>++ <!-- 03 对话变长 -->+ <article style="display: flex; flex-direction: column; gap: 14px; padding: 22px; border-radius: 20px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <p style="display: flex; align-items: baseline; gap: 10px; margin: 0; font-size: 13px; color: #a1a1aa"><span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">03</span>同一段对话聊得很长时</p>+ <div style="display: flex; align-items: center; gap: 10px; padding: 14px; border-radius: 16px; background: #060706; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <span style="flex: 1; color: #a1a1aa; font-size: 13px">顶栏右侧</span>+ <span aria-hidden="true" style="display: grid; place-items: center; width: 34px; height: 34px; border-radius: 50%; color: #fafaf7; box-shadow: 0 0 0 2px #d7ff00, 0 0 0 6px rgba(215,255,0,.14)">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>+ </span>+ <span style="color: #a1a1aa; font-size: 13px">或输入</span>+ <kbd style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; padding: 3px 8px; border-radius: 8px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">/new</kbd>+ </div>+ <div style="display: flex; gap: 10px; padding: 14px; border-radius: 16px; background: #101110; box-shadow: 0 0 0 1px rgba(255,255,255,.18)">+ <span class="face" data-char="blue" style="flex: none; width: 30px; height: 30px"></span>+ <div style="flex: 1; min-width: 0">+ <div style="font-weight: 600; font-size: 14.5px; margin-bottom: 2px">换个话题?开一段新对话</div>+ <p style="margin: 0 0 10px; color: #a1a1aa; font-size: 13px; line-height: 1.65">旧对话会归档,小蓝会留一张交接便条;长期记忆不受影响。</p>+ <button type="button" style="min-height: 30px; padding: 0 12px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); font-size: 12.5px">知道了</button>+ </div>+ </div>+ </article>++ <!-- 04 电脑操作 -->+ <article style="display: flex; flex-direction: column; gap: 14px; padding: 22px; border-radius: 20px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <p style="display: flex; align-items: baseline; gap: 10px; margin: 0; font-size: 13px; color: #a1a1aa"><span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">04</span>第一次让它操作电脑</p>+ <div style="display: flex; flex-direction: column; gap: 8px; padding: 14px; border-radius: 16px; background: #060706; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <div style="align-self: flex-end; max-width: 90%; padding: 7px 12px; border-radius: 14px; background: rgba(255,255,255,.07); font-size: 13px">打开计算器,算一下 128 × 46。</div>+ <span style="display: inline-flex; align-items: center; gap: 8px; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 11px; color: #a1a1aa">+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="12" rx="2"/><path d="M8 20h8M12 16v4"/></svg>+ 正在操作:计算器+ </span>+ </div>+ <div style="display: flex; gap: 10px; padding: 14px; border-radius: 16px; background: #101110; box-shadow: 0 0 0 1px rgba(255,255,255,.18)">+ <span class="face" data-char="blue" style="flex: none; width: 30px; height: 30px"></span>+ <div style="flex: 1; min-width: 0">+ <div style="font-weight: 600; font-size: 14.5px; margin-bottom: 2px">它能帮你操作电脑</div>+ <p style="margin: 0 0 8px; color: #a1a1aa; font-size: 13px; line-height: 1.65">看屏幕、点鼠标、打字,帮你操作电脑上的应用。默认直接执行;想让它点击、输入前先问你,去「机器人设置 → 电脑操作 → 审批」里改。</p>+ <p style="margin: 0 0 10px; padding: 8px 10px; border-radius: 10px; background: #060706; color: #a1a1aa; font-size: 12.5px; line-height: 1.6"><span style="color: #fafaf7">仅 macOS:</span>第一次使用前,在「系统设置 → 隐私与安全性」里给 AnyModelBot 打开「辅助功能」和「屏幕录制」。</p>+ <div style="display: flex; flex-wrap: wrap; gap: 8px">+ <button type="button" style="min-height: 30px; padding: 0 12px; border-radius: 999px; background: #d7ff00; color: #161a00; font-weight: 600; font-size: 12.5px">去设置审批</button>+ <button type="button" style="min-height: 30px; padding: 0 12px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); font-size: 12.5px">知道了</button>+ </div>+ </div>+ </div>+ </article>++ <!-- 05 余额 -->+ <article style="display: flex; flex-direction: column; gap: 14px; padding: 22px; border-radius: 20px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <p style="display: flex; align-items: baseline; gap: 10px; margin: 0; font-size: 13px; color: #a1a1aa"><span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">05</span>第一次看到侧栏的余额</p>+ <div style="padding: 14px; border-radius: 16px; background: #060706; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <div style="display: flex; align-items: center; gap: 10px; min-height: 44px; padding: 0 10px; border-radius: 12px; box-shadow: 0 0 0 2px #d7ff00, 0 0 0 6px rgba(215,255,0,.14)">+ <span aria-hidden="true" style="display: grid; place-items: center; width: 26px; height: 26px; border-radius: 50%; background: #d7ff00; color: #161a00; font-weight: 700; font-size: 12px">Z</span>+ <span style="flex: 1; font-size: 13px">我的账户</span>+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12.5px">$12.40</span>+ </div>+ </div>+ <div style="display: flex; gap: 10px; padding: 14px; border-radius: 16px; background: #101110; box-shadow: 0 0 0 1px rgba(255,255,255,.18)">+ <span class="face" data-char="blue" style="flex: none; width: 30px; height: 30px"></span>+ <div style="flex: 1; min-width: 0">+ <div style="font-weight: 600; font-size: 14.5px; margin-bottom: 2px">这是你的余额</div>+ <p style="margin: 0 0 10px; color: #a1a1aa; font-size: 13px; line-height: 1.65">Modelflare 账户的余额,所有机器人共用。点这里可以充值、看用量、设置余额提醒。</p>+ <button type="button" style="min-height: 30px; padding: 0 12px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); font-size: 12.5px">知道了</button>+ </div>+ </div>+ </article>++ <!-- 06 第二个机器人 -->+ <article style="display: flex; flex-direction: column; gap: 14px; padding: 22px; border-radius: 20px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <p style="display: flex; align-items: baseline; gap: 10px; margin: 0; font-size: 13px; color: #a1a1aa"><span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">06</span>新建第二个机器人时</p>+ <div style="display: flex; flex-wrap: wrap; gap: 8px; padding: 14px; border-radius: 16px; background: #060706; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <span style="display: inline-flex; align-items: center; gap: 6px; height: 36px; padding: 0 12px 0 4px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); font-size: 13px"><span class="face" data-char="orange" style="width: 28px; height: 28px"></span>翻译官</span>+ <span style="display: inline-flex; align-items: center; gap: 6px; height: 36px; padding: 0 12px 0 4px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); font-size: 13px"><span class="face" data-char="purple" style="width: 28px; height: 28px"></span>写作助手</span>+ <span style="display: inline-flex; align-items: center; gap: 6px; height: 36px; padding: 0 12px 0 4px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); font-size: 13px"><span class="face" data-char="red" style="width: 28px; height: 28px"></span>代码助手</span>+ <span style="display: inline-flex; align-items: center; gap: 6px; height: 36px; padding: 0 12px 0 4px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); font-size: 13px"><span class="face" data-char="yellow" style="width: 28px; height: 28px"></span>客服助手</span>+ </div>+ <div style="display: flex; gap: 10px; padding: 14px; border-radius: 16px; background: #101110; box-shadow: 0 0 0 1px rgba(255,255,255,.18)">+ <span class="face" data-char="blue" style="flex: none; width: 30px; height: 30px"></span>+ <div style="flex: 1; min-width: 0">+ <div style="font-weight: 600; font-size: 14.5px; margin-bottom: 2px">一件事交给一个机器人</div>+ <p style="margin: 0 0 10px; color: #a1a1aa; font-size: 13px; line-height: 1.65">翻译、写作、写代码……每个机器人都有自己的人设、模型和工作区,互不打扰。</p>+ <button type="button" style="min-height: 30px; padding: 0 12px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); font-size: 12.5px">知道了</button>+ </div>+ </div>+ </article>++ <!-- 07 机器人预算 -->+ <article style="display: flex; flex-direction: column; gap: 14px; padding: 22px; border-radius: 20px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <p style="display: flex; align-items: baseline; gap: 10px; margin: 0; font-size: 13px; color: #a1a1aa"><span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">07</span>第一次打开机器人设置(已登录账户)</p>+ <div style="border-radius: 16px; background: #060706; box-shadow: 0 0 0 2px #d7ff00, 0 0 0 6px rgba(215,255,0,.14)">+ <div style="display: flex; align-items: center; gap: 10px; padding: 12px 14px; border-bottom: 1px solid rgba(255,255,255,.10)">+ <span style="flex: 1"><span style="display: block; font-size: 13.5px">预算</span><span style="display: block; color: #a1a1aa; font-size: 12px">用这个机器人自己的 Key,花到上限就停</span></span>+ <span aria-hidden="true" style="position: relative; width: 38px; height: 22px; border-radius: 999px; background: #d7ff00"><span style="position: absolute; right: 3px; top: 3px; width: 16px; height: 16px; border-radius: 50%; background: #161a00"></span></span>+ </div>+ <div style="display: flex; align-items: center; gap: 10px; padding: 12px 14px">+ <span style="flex: 1; font-size: 13.5px">上限(美元)</span>+ <span style="min-width: 64px; padding: 4px 10px; border-radius: 8px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12.5px; text-align: right">5</span>+ </div>+ </div>+ <div style="display: flex; gap: 10px; padding: 14px; border-radius: 16px; background: #101110; box-shadow: 0 0 0 1px rgba(255,255,255,.18)">+ <span class="face" data-char="blue" style="flex: none; width: 30px; height: 30px"></span>+ <div style="flex: 1; min-width: 0">+ <div style="font-weight: 600; font-size: 14.5px; margin-bottom: 2px">给它定个零花钱</div>+ <p style="margin: 0 0 10px; color: #a1a1aa; font-size: 13px; line-height: 1.65">设一个花费上限,花完就停,不影响其他机器人。</p>+ <button type="button" style="min-height: 30px; padding: 0 12px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); font-size: 12.5px">知道了</button>+ </div>+ </div>+ </article>++ <!-- 08 关闭窗口:对话框 -->+ <article style="display: flex; flex-direction: column; gap: 14px; padding: 22px; border-radius: 20px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <p style="display: flex; align-items: baseline; gap: 10px; margin: 0; font-size: 13px; color: #a1a1aa"><span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">08</span>第一次关闭窗口(桌面版)</p>+ <div role="dialog" aria-label="关闭窗口" style="display: flex; flex-direction: column; align-items: flex-start; gap: 10px; padding: 20px; border-radius: 24px; background: #101110; box-shadow: 0 0 0 1px rgba(255,255,255,.18), 0 30px 60px -20px rgba(0,0,0,.7)">+ <span class="face" data-char="blue" style="width: 48px; height: 48px"></span>+ <div style="font-weight: 600; font-size: 16px">小蓝会留在托盘里</div>+ <p style="margin: 0; color: #a1a1aa; font-size: 13px; line-height: 1.65">窗口关了,它还在后台继续收发微信、飞书消息。想完全退出,在托盘菜单里选「退出」。</p>+ <div style="display: flex; flex-wrap: wrap; gap: 8px; margin-top: 4px">+ <button type="button" style="min-height: 34px; padding: 0 16px; border-radius: 999px; background: #d7ff00; color: #161a00; font-weight: 600; font-size: 13px">好的</button>+ <button type="button" style="min-height: 34px; padding: 0 14px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); font-size: 13px">改为直接退出</button>+ </div>+ </div>+ </article>++ <!-- 09 快捷键 -->+ <article style="display: flex; flex-direction: column; gap: 14px; padding: 22px; border-radius: 20px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <p style="display: flex; align-items: baseline; gap: 10px; margin: 0; font-size: 13px; color: #a1a1aa"><span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">09</span>清单完成后放一次</p>+ <div style="display: flex; flex-direction: column; gap: 10px; padding: 16px; border-radius: 16px; background: #060706; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <div style="display: flex; align-items: center; gap: 10px"><span style="display: flex; gap: 4px"><kbd style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; min-width: 26px; text-align: center; padding: 3px 7px; border-radius: 8px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">⌘</kbd><kbd style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; min-width: 26px; text-align: center; padding: 3px 7px; border-radius: 8px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">K</kbd></span><span style="color: #a1a1aa; font-size: 13px">命令面板</span></div>+ <div style="display: flex; align-items: center; gap: 10px"><span style="display: flex; gap: 4px"><kbd style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; min-width: 26px; text-align: center; padding: 3px 7px; border-radius: 8px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">⌘</kbd><kbd style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; min-width: 26px; text-align: center; padding: 3px 7px; border-radius: 8px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">⇧</kbd><kbd style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; min-width: 26px; text-align: center; padding: 3px 7px; border-radius: 8px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">I</kbd></span><span style="color: #a1a1aa; font-size: 13px">信息面板</span></div>+ <div style="display: flex; align-items: center; gap: 10px"><span style="display: flex; gap: 4px"><kbd style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; min-width: 26px; text-align: center; padding: 3px 7px; border-radius: 8px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">⌘</kbd><kbd style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; min-width: 26px; text-align: center; padding: 3px 7px; border-radius: 8px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">,</kbd></span><span style="color: #a1a1aa; font-size: 13px">设置</span></div>+ <div style="display: flex; align-items: center; gap: 10px"><span style="display: flex; gap: 4px"><kbd style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; min-width: 26px; text-align: center; padding: 3px 7px; border-radius: 8px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">Esc</kbd></span><span style="color: #a1a1aa; font-size: 13px">停止生成</span></div>+ </div>+ <div style="display: flex; gap: 10px; padding: 14px; border-radius: 16px; background: #101110; box-shadow: 0 0 0 1px rgba(255,255,255,.18)">+ <span class="face" data-char="blue" style="flex: none; width: 30px; height: 30px"></span>+ <div style="flex: 1; min-width: 0">+ <div style="font-weight: 600; font-size: 14.5px; margin-bottom: 2px">再送你几个快捷键</div>+ <p style="margin: 0 0 10px; color: #a1a1aa; font-size: 13px; line-height: 1.65">Windows 和 Linux 上把 ⌘ 换成 Ctrl。</p>+ <button type="button" style="min-height: 30px; padding: 0 12px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); font-size: 12.5px">知道了</button>+ </div>+ </div>+ </article>+ </div>++ <!-- 清单完成:收尾横幅 -->+ <section style="position: relative; display: flex; flex-wrap: wrap; align-items: center; gap: 24px 40px; margin-top: 48px; padding: clamp(28px, 4vw, 48px); border-radius: 32px; background: #d7ff00; color: #161a00; overflow: hidden">+ <div style="flex: 999 1 420px; min-width: 0">+ <p style="margin: 0 0 14px; font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; letter-spacing: .06em">上手清单 · 6 / 6</p>+ <h2 style="margin: 0; font-size: clamp(30px, 3.6vw, 48px); line-height: 1.18; letter-spacing: -.012em; font-weight: 600">+ <span style="display: block">六件事都做完了。</span>+ <span style="display: block; color: #465612">小蓝已经准备好了。</span>+ </h2>+ <div style="display: flex; flex-wrap: wrap; gap: 10px; margin-top: 24px">+ <button type="button" style="min-height: 44px; padding: 0 22px; border-radius: 999px; background: #161a00; color: #d7ff00; font-weight: 600; font-size: 14.5px">再养一个机器人</button>+ <button type="button" style="min-height: 44px; padding: 0 20px; border-radius: 999px; box-shadow: inset 0 0 0 1.5px rgba(22,26,0,.35); font-weight: 500; font-size: 14.5px">收起清单</button>+ </div>+ </div>+ <div aria-hidden="true" style="flex: 1 1 300px; display: flex; justify-content: center; align-items: flex-end; gap: 4px">+ <span class="face" data-char="yellow" style="width: 64px; height: 64px"></span>+ <span class="face" data-char="green" style="width: 72px; height: 72px"></span>+ <span class="face" data-char="blue" style="width: 104px; height: 104px"></span>+ <span class="face" data-char="red" style="width: 72px; height: 72px"></span>+ <span class="face" data-char="purple" style="width: 64px; height: 64px"></span>+ </div>+ </section>+ </div>+</div>++<script type="module" src="js/page-tips.js"></script>+</body>+</html>diff --git a/anymodelbot_design/onboarding/assets/bots/blue.webp b/anymodelbot_design/onboarding/assets/bots/blue.webpnew file mode 100644index 0000000..e3c4085Binary files /dev/null and b/anymodelbot_design/onboarding/assets/bots/blue.webp differdiff --git a/anymodelbot_design/onboarding/assets/bots/green.webp b/anymodelbot_design/onboarding/assets/bots/green.webpnew file mode 100644index 0000000..40f271bBinary files /dev/null and b/anymodelbot_design/onboarding/assets/bots/green.webp differdiff --git a/anymodelbot_design/onboarding/assets/bots/orange.webp b/anymodelbot_design/onboarding/assets/bots/orange.webpnew file mode 100644index 0000000..145e858Binary files /dev/null and b/anymodelbot_design/onboarding/assets/bots/orange.webp differdiff --git a/anymodelbot_design/onboarding/assets/bots/purple.webp b/anymodelbot_design/onboarding/assets/bots/purple.webpnew file mode 100644index 0000000..764b4b6Binary files /dev/null and b/anymodelbot_design/onboarding/assets/bots/purple.webp differdiff --git a/anymodelbot_design/onboarding/assets/bots/red.webp b/anymodelbot_design/onboarding/assets/bots/red.webpnew file mode 100644index 0000000..b906787Binary files /dev/null and b/anymodelbot_design/onboarding/assets/bots/red.webp differdiff --git a/anymodelbot_design/onboarding/assets/bots/yellow.webp b/anymodelbot_design/onboarding/assets/bots/yellow.webpnew file mode 100644index 0000000..e49768cBinary files /dev/null and b/anymodelbot_design/onboarding/assets/bots/yellow.webp differdiff --git a/anymodelbot_design/onboarding/assets/fonts/Geist-Variable.woff2 b/anymodelbot_design/onboarding/assets/fonts/Geist-Variable.woff2new file mode 100644index 0000000..600c92cBinary files /dev/null and b/anymodelbot_design/onboarding/assets/fonts/Geist-Variable.woff2 differdiff --git a/anymodelbot_design/onboarding/assets/fonts/GeistMono-Variable.woff2 b/anymodelbot_design/onboarding/assets/fonts/GeistMono-Variable.woff2new file mode 100644index 0000000..10c0501Binary files /dev/null and b/anymodelbot_design/onboarding/assets/fonts/GeistMono-Variable.woff2 differdiff --git a/anymodelbot_design/onboarding/assets/fonts/OFL.txt b/anymodelbot_design/onboarding/assets/fonts/OFL.txtnew file mode 100644index 0000000..8d003fe--- /dev/null+++ b/anymodelbot_design/onboarding/assets/fonts/OFL.txt@@ -0,0 +1,92 @@+Copyright (c) 2023 Vercel, in collaboration with basement.studio++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION AND CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/anymodelbot_design/onboarding/css/bots.css b/anymodelbot_design/onboarding/css/bots.cssnew file mode 100644index 0000000..62836d9--- /dev/null+++ b/anymodelbot_design/onboarding/css/bots.css@@ -0,0 +1,554 @@+@layer tokens, base, components, app, utilities;+@layer components {+/* 移植自 App 的 ui/design/components/avatar.css(只取头像本身,不含选择器与 AppMark),由 scripts 手动同步。+ 下面的 .bot-face 块把 App 的 token 映射到官网 token;动效时长保持 App 的值,让两边的头像一模一样。 */+.bot-face {+ --dur-fast: 120ms; --dur-base: 180ms; --dur-moderate: 240ms; --dur-slow: 360ms; --dur-slower: 420ms; --dur-spin: 800ms;+ --ease-in-out: cubic-bezier(.42, 0, .58, 1); --ease-spring: cubic-bezier(.16, 1, .3, 1); --ease-back: cubic-bezier(.34, 1.56, .64, 1);+ --t-fast: var(--dur-fast) var(--ease-out);+ --bot-hello: 1.6s; --bot-done: 1.3s; --bot-error: 1.5s; --bot-poke: .7s; --bot-love: 1.6s; --bot-dizzy: 2.2s;+ --fg: var(--text); --muted: var(--text-2); --surface-solid: var(--bg-raised); --amber: var(--warn);+ --fs-xs: 12px; --fw-medium: 500; --fw-semibold: 600; --r-lg: 12px; --r-full: 999px;+ --space-1: 4px; --space-1-5: 6px; --space-2-5: 10px;+ --shadow-sm: 0 1px 2px rgba(0, 0, 0, .12);+}+/* 机器人头像:6 个内置毛绒角色,精灵图 ui/design/bots/<角色>.webp 由 scripts/build-bot-avatars.py 拆层生成。+ 结构 .bot-face > .bf-shadow + .bf-aura + .bf-body(持续状态)> .bf-shot(一次性反应)> .bf-look(看指针)+ > 耳朵 / 配件(.bf-part > .bf-pin > .bf-img + .bf-glow)+ 头 + 腮红 + 眼睛 SVG + 粒子+ 属性 data-char 角色;data-state 持续状态;data-shot 一次性反应;data-eyes 当前表情(都由 avatar.js 写)+ 分工 外层 .bf-part 放持续状态的循环(transform)和姿势(rotate,比如竖耳朵、耷拉),内层 .bf-pin 放一次性反应,+ 两者叠加互不覆盖。空闲的列表头像不自己动:只在指针靠近时看过去、悬停时抖一下天线;lively(大头像)才会呼吸、眨眼、张望。+ 角色颜色(--bot-*)是原画的颜色,两个主题相同,所以直接用 primitives;随主题变的只有光晕和影子(--avatar-*)。 */+.bot-face {+ --look-x: 0;+ --look-y: 0;+ --bf-eye: var(--bot-blue-eye);+ --bf-glow: var(--bot-blue-glow);+ /* 循环周期 */+ --bf-blink: 4.2s; /* 眨眼间隔 */+ --bf-blink-spread: -4s; /* 按 --bf-seed 错开,几个头像不会一起眨眼 */+ --bf-breathe: 3.4s; /* 大头像空闲时的呼吸 */+ --bf-glance: 7s; /* 大头像空闲时四处看 */+ --bf-nod: 1.6s; /* 你在输入时点头 */+ --bf-ponder: 2.6s; /* 思考:歪头、眼睛看左上右上 */+ --bf-read: 1.4s; /* 回复:眼睛像读行一样左右扫 */+ --bf-bob: .9s; /* 工作中上下浮动 */+ --bf-hop: 2.4s; /* 等你批准:跳两下停一下 */+ --bf-snore: 3.6s; /* 睡觉 */+ --bf-perk: .9s; /* 悬停时天线弹一下 */+ --bf-ring: 1.5s; /* 小蓝的天线信号 */+ --bf-ring-gap: .5s;+ --bf-sway: .55s; /* 天线、角左右晃 */+ --bf-twinkle: 1.3s; /* 小萌的星星、紫钻的闪光 */+ --bf-flutter: .9s; /* 绿草的叶子 */+ --bf-beat: .6s; /* 红魔的灯带节拍 */+ --bf-spin: 3.2s; /* 紫钻的宝石转动 */+ --bf-float: 2.2s; /* 紫钻的宝石悬浮 */+ --bf-sweep: 2.2s; /* 探险者护目镜的反光 */+ --bf-scan: 1.6s; /* 探险者四处搜寻 */+ --bf-dot: 1.2s; /* 思考气泡里的点 */+ --bf-bang: 1.2s;+ --bf-z: 3s;+ --bf-orbit: .9s;+ position: relative; flex: none; width: var(--s); height: var(--s);+ -webkit-user-select: none; user-select: none;+}+.bot-face[data-char="yellow"] { --bf-eye: var(--bot-yellow-eye); --bf-glow: var(--bot-yellow-glow); }+.bot-face[data-char="green"] { --bf-eye: var(--bot-green-eye); --bf-glow: var(--bot-green-glow); }+.bot-face[data-char="red"] { --bf-eye: var(--bot-red-eye); --bf-glow: var(--bot-red-glow); }+.bot-face[data-char="purple"] { --bf-eye: var(--bot-purple-eye); --bf-glow: var(--bot-purple-glow); }+.bot-face[data-char="orange"] { --bf-eye: var(--bot-orange-eye); --bf-glow: var(--bot-orange-glow); }+.bot-face.pokeable { cursor: pointer; }+.bot-face.neutral { filter: grayscale(1) contrast(.85) brightness(1.06); opacity: .5; }++/* —— 图层 —— */+.bf-shadow, .bf-body, .bf-shot, .bf-look, .bf-part, .bf-pin, .bf-img, .bf-glow { position: absolute; inset: 0; }+.bf-body, .bf-shot { transform-origin: 50% 89%; }+.bf-look {+ transform-origin: 50% 60%;+ transform: translate(calc(var(--look-x) * var(--s) * .03), calc(var(--look-y) * var(--s) * .018)) rotate(calc(var(--look-x) * 3deg));+ transition: transform var(--dur-moderate) var(--ease-out);+}+.bf-img, .bf-glow { background: var(--bf-sprite) 0 0 / 800% 100% no-repeat; }+.bf-ear-l .bf-img { background-position-x: calc(100% / 7); }+.bf-ear-r .bf-img { background-position-x: calc(200% / 7); }+.bf-top .bf-img { background-position-x: calc(300% / 7); }+.bf-head .bf-glow { background-position-x: calc(400% / 7); }+.bf-ear-l .bf-glow { background-position-x: calc(500% / 7); }+.bf-ear-r .bf-glow { background-position-x: calc(600% / 7); }+.bf-top .bf-glow { background-position-x: 100%; }+.bf-glow { opacity: 0; mix-blend-mode: plus-lighter; filter: drop-shadow(0 0 calc(var(--s) * .03) var(--bf-glow)); }+.bot-face:not([data-char="red"], [data-char="purple"]) .bf-glow { display: none; } /* 只有红魔、紫钻有发光层 */+.bf-ear-l, .bf-ear-l .bf-pin { transform-origin: var(--o-el); }+.bf-ear-r, .bf-ear-r .bf-pin { transform-origin: var(--o-er); }+.bf-top, .bf-top .bf-pin, .bf-top .bf-img { transform-origin: var(--o-top); }+.bf-part { transition: rotate var(--dur-slow) var(--ease-back), filter var(--dur-moderate) var(--ease-out); }++.bf-aura {+ position: absolute; inset: -14%; border-radius: 50%; opacity: 0;+ background: radial-gradient(closest-side, color-mix(in srgb, var(--bf-glow) var(--avatar-aura), transparent) 35%, transparent);+ transition: opacity var(--dur-moderate) var(--ease-out);+}+.bf-shadow {+ inset: auto 23% 3% 23%; height: 8%; border-radius: 50%;+ background: radial-gradient(closest-side, var(--avatar-shadow), transparent);+}++/* 腮红:开心时在面罩上亮起来 */+.bf-blush {+ position: absolute; width: 9%; height: 4.4%; translate: -50% -50%; border-radius: 50%;+ background: radial-gradient(closest-side, color-mix(in srgb, var(--bot-blush) 70%, var(--bf-glow)), transparent);+ opacity: 0; scale: .5;+ transition: opacity var(--dur-base) var(--ease-out), scale var(--dur-moderate) var(--ease-back);+}+.bot-face:is([data-eyes="happy"], [data-eyes="heart"]) .bf-blush { opacity: .9; scale: 1; }++/* 探险者的护目镜:镜片上扫过一道反光 */+.bf-lens { position: absolute; width: var(--lens); aspect-ratio: 1; translate: -50% -50%; border-radius: 50%; overflow: hidden; }+.bf-lens::after {+ content: ""; position: absolute; inset: -30%; translate: -110% 0;+ background: linear-gradient(115deg, transparent 38%, var(--bot-glint) 50%, transparent 62%);+}++/* —— 眼睛与表情:坐标同 viewBox 0–100,每只眼睛以自己的中心为原点,右眼是镜像 —— */+.bf-eyes { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; filter: drop-shadow(0 0 calc(var(--s) * .028) var(--bf-glow)); }+.bf-gaze { transform: translate(calc(var(--look-x) * 2.4px), calc(var(--look-y) * 1.6px)); transition: transform var(--dur-fast) var(--ease-out); }+.bf-glance { transition: transform var(--dur-moderate) var(--ease-out); }+.bf-lid { transform-box: view-box; transform-origin: 0 0; transition: scale var(--dur-base) var(--ease-back); }+.bf-eyes .e {+ fill: var(--bf-eye); opacity: 0; scale: .3;+ transform-box: view-box; transform-origin: 0 0;+ transition: opacity var(--dur-fast) var(--ease-out), scale var(--dur-base) var(--ease-back);+}+.bf-eyes .line { fill: none; stroke: var(--bf-eye); stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; }+.bf-eyes .thin { stroke-width: 1.15; }+.bot-face[data-eyes="open"] .e-open,+.bot-face[data-eyes="happy"] .e-happy,+.bot-face[data-eyes="closed"] .e-closed,+.bot-face[data-eyes="heart"] .e-heart,+.bot-face[data-eyes="spiral"] .e-spiral { opacity: 1; scale: 1; }+.bot-face[data-eyes="spiral"] .e-spiral { animation: spin var(--dur-spin) linear infinite; }+.bot-face[data-eyes="heart"] .e-heart { animation: bf-heartbeat var(--bf-beat) var(--ease-in-out) infinite alternate; }+.bot-face[data-eyes="error"] .e-x { animation: bf-eye-x var(--bot-error) var(--ease-out) both; }+.bot-face[data-eyes="error"] .e-sad { animation: bf-eye-sad var(--bot-error) var(--ease-out) both; }+@keyframes bf-eye-x { 0%, 42% { opacity: 1; scale: 1; } 52%, 100% { opacity: 0; scale: .3; } }+@keyframes bf-eye-sad { 0%, 44% { opacity: 0; scale: .3; rotate: -14deg; } 58%, 100% { opacity: 1; scale: 1; rotate: -14deg; } }+@keyframes bf-heartbeat { to { scale: 1.25; } }+@keyframes bf-blink { 0%, 91%, 100% { transform: none; } 94.5% { transform: scaleY(.08); } }++/* —— 持续状态 —— */+/* 眨眼:大头像空闲时,以及所有"醒着做事"的状态 */+.bot-face.lively .bf-lid,+.bot-face:is([data-state="listening"], [data-state="thinking"], [data-state="replying"], [data-state="working"], [data-state="waiting"]) .bf-lid {+ animation: bf-blink var(--bf-blink) var(--ease-in-out) calc(var(--bf-seed) * var(--bf-blink-spread)) infinite;+}++/* 空闲(lively):呼吸、偶尔看看左右、天线轻轻晃 */+.bot-face.lively { --avatar-aura: 18%; }+.bot-face.lively .bf-aura { opacity: .7; }+.bot-face.lively[data-state="idle"] .bf-body { animation: bf-breathe var(--bf-breathe) var(--ease-in-out) infinite; }+.bot-face.lively[data-state="idle"] .bf-glance { animation: bf-glance-idle var(--bf-glance) var(--ease-in-out) calc(var(--bf-seed) * var(--bf-blink-spread)) infinite; }+.bot-face.lively[data-state="idle"] .bf-top { animation: bf-sway-soft var(--bf-breathe) var(--ease-in-out) infinite alternate; }+@keyframes bf-breathe { 50% { transform: translateY(-1.2%) scale(.994, 1.012); } }+@keyframes bf-glance-idle {+ 0%, 34%, 56%, 74%, 94%, 100% { transform: none; }+ 38%, 52% { transform: translate(-2px, .4px); }+ 78%, 90% { transform: translate(2px, -.8px); }+}+@keyframes bf-sway-soft { from { transform: rotate(-3deg); } to { transform: rotate(3deg); } }++/* 你在输入:竖起耳朵、眼睛看向输入框、轻轻点头 */+.bot-face[data-state="listening"] .bf-body { animation: bf-nod var(--bf-nod) var(--ease-in-out) infinite; }+.bot-face[data-state="listening"] .bf-glance { transform: translate(0, 1.4px); }+.bot-face[data-state="listening"] .bf-ear-l { rotate: 7deg; }+.bot-face[data-state="listening"] .bf-ear-r { rotate: -7deg; }+@keyframes bf-nod { 0%, 45%, 100% { transform: none; } 15% { transform: translateY(1.6%) scale(1.01, .98); } 30% { transform: translateY(-.6%); } }++/* 思考(还没出字):歪着头,眼睛在左上和右上之间找答案,背后发光,头上冒思考泡泡 */+.bot-face[data-state="thinking"] .bf-body { animation: bf-ponder var(--bf-ponder) var(--ease-in-out) infinite; }+.bot-face[data-state="thinking"] .bf-glance { animation: bf-glance-think var(--bf-ponder) var(--ease-in-out) infinite; }+@keyframes bf-ponder { 0%, 100% { transform: rotate(-4deg); } 50% { transform: translateY(-1.5%) rotate(4deg); } }+@keyframes bf-glance-think {+ 0%, 40%, 100% { transform: translate(-1.8px, -1.5px); }+ 52%, 88% { transform: translate(1.8px, -1.5px); }+}++/* 回复 / 工作中:上下浮动,眼睛眯起来专注地左右扫 */+.bot-face:is([data-state="replying"], [data-state="working"]) .bf-body { animation: bf-bob var(--bf-bob) var(--ease-in-out) infinite; }+.bot-face:is([data-state="replying"], [data-state="working"]) .bf-glance { animation: bf-glance-read var(--bf-read) linear infinite; }+.bot-face:is([data-state="replying"], [data-state="working"]) .bf-lid { scale: 1 .62; }+@keyframes bf-bob { 50% { transform: translateY(-3.5%); } }+@keyframes bf-glance-read {+ 0%, 100% { transform: translate(-1.8px, 0); }+ 72% { transform: translate(1.8px, 0); }+ 84% { transform: translate(1.8px, .8px); }+}++/* 思考、回复、工作、等待:背后的辉光一起一伏 */+.bot-face:is([data-state="thinking"], [data-state="replying"], [data-state="working"], [data-state="waiting"]) .bf-aura {+ opacity: 1; animation: bf-aura-pulse var(--bf-ponder) var(--ease-in-out) infinite;+}+@keyframes bf-aura-pulse { 0%, 100% { opacity: .55; transform: scale(.9); } 50% { opacity: 1; transform: scale(1.04); } }++/* 等你批准:睁大眼睛看着你,跳两下停一下,头顶一个感叹号 */+.bot-face[data-state="waiting"] .bf-body { animation: bf-hop var(--bf-hop) var(--ease-out) infinite; }+.bot-face[data-state="waiting"] .bf-shadow { animation: bf-shadow-hop var(--bf-hop) var(--ease-out) infinite; }+.bot-face[data-state="waiting"] .bf-lid { scale: 1.2; }+.bot-face[data-state="waiting"] .bf-ear-l { rotate: 12deg; }+.bot-face[data-state="waiting"] .bf-ear-r { rotate: -12deg; }+@keyframes bf-hop {+ 0%, 44%, 100% { transform: none; }+ 6% { transform: scale(1.06, .92); }+ 14% { transform: translateY(-11%) scale(.96, 1.05); }+ 22% { transform: scale(1.05, .94); }+ 29% { transform: translateY(-6%); }+ 36% { transform: scale(1.02, .98); }+}+@keyframes bf-shadow-hop { 0%, 44%, 100% { transform: none; } 14% { transform: scale(.7); opacity: .5; } 29% { transform: scale(.85); } }++/* 睡觉:闭眼、歪头、耳朵和配件耷拉下来,冒 z */+.bot-face[data-state="sleep"] .bf-body { rotate: -6deg; animation: bf-snore var(--bf-snore) var(--ease-in-out) infinite; }+.bot-face[data-state="sleep"] .bf-ear-l { rotate: -9deg; }+.bot-face[data-state="sleep"] .bf-ear-r { rotate: 9deg; }+.bot-face[data-state="sleep"] .bf-top { rotate: 14deg; }+.bot-face[data-state="sleep"] .bf-eyes { filter: none; opacity: .75; }+@keyframes bf-snore { 50% { transform: scale(1.025, .975); } }++/* —— 一次性反应(.bf-shot 每次重新挂载,动画从头播) —— */+.bot-face[data-shot="hello"] .bf-shot { animation: bf-hello var(--bot-hello) var(--ease-out) both; }+.bot-face[data-shot="done"] .bf-shot { animation: bf-done var(--bot-done) var(--ease-out) both; }+.bot-face[data-shot="error"] .bf-shot { animation: bf-error var(--bot-error) var(--ease-out) both; }+.bot-face[data-shot="poke"] .bf-shot { animation: bf-poke var(--bot-poke) var(--ease-out) both; }+.bot-face[data-shot="love"] .bf-shot { animation: bf-love var(--bot-love) var(--ease-in-out) both; }+.bot-face[data-shot="dizzy"] .bf-shot { animation: bf-dizzy var(--bot-dizzy) var(--ease-in-out) both; }+.bot-face[data-shot="done"] .bf-shadow { animation: bf-shadow-done var(--bot-done) var(--ease-out) both; }+.bot-face[data-shot="hello"] .bf-shadow { animation: bf-shadow-hello var(--bot-hello) var(--ease-out) both; }+.bot-face:is([data-shot="hello"], [data-shot="done"], [data-shot="love"]) .bf-aura { opacity: 1; animation: bf-aura-flash var(--bot-done) var(--ease-out) both; }+@keyframes bf-hello {+ 0% { opacity: 0; transform: translateY(14%) scale(0); }+ 22% { opacity: 1; transform: scale(1.14, .88); }+ 34% { transform: translateY(-9%) scale(.94, 1.08); }+ 46% { transform: none; }+ 58% { transform: rotate(-9deg); }+ 70% { transform: rotate(8deg); }+ 82% { transform: rotate(-5deg); }+ 92% { transform: rotate(2deg); }+ 100% { transform: none; }+}+@keyframes bf-done {+ 0%, 100% { transform: none; }+ 14% { transform: scale(1.12, .84); }+ 36% { transform: translateY(-24%) scale(.92, 1.1) rotate(-5deg); }+ 52% { transform: translateY(-26%) rotate(5deg); }+ 70% { transform: scale(1.12, .86); }+ 84% { transform: scale(.96, 1.05); }+}+@keyframes bf-error {+ 0%, 100% { transform: none; }+ 8% { transform: translateX(-8%) rotate(-7deg); }+ 18% { transform: translateX(7%) rotate(6deg); }+ 28% { transform: translateX(-5%) rotate(-4deg); }+ 38% { transform: translateX(3%) rotate(2deg); }+ 48% { transform: none; }+ 62%, 86% { transform: translateY(3%) scale(1.03, .95); }+}+@keyframes bf-poke {+ 0%, 100% { transform: none; }+ 16% { transform: scale(1.18, .8); }+ 38% { transform: translateY(-8%) scale(.9, 1.12); }+ 58% { transform: scale(1.05, .95); }+ 76% { transform: scale(.98, 1.02); }+}+@keyframes bf-love {+ 0%, 100% { transform: none; }+ 12% { transform: scale(1.1, .9); }+ 26% { transform: translateY(-6%) scale(.96, 1.05) rotate(-6deg); }+ 40% { transform: rotate(6deg); }+ 54% { transform: translateY(-4%) rotate(-5deg); }+ 68% { transform: rotate(4deg); }+ 84% { transform: rotate(-2deg); }+}+@keyframes bf-dizzy {+ 0%, 100% { transform: none; }+ 10% { transform: translateX(-5%) rotate(-12deg); }+ 22% { transform: translateX(5%) rotate(11deg); }+ 34% { transform: translateX(-4%) rotate(-10deg); }+ 46% { transform: translateX(3%) rotate(8deg); }+ 58% { transform: translateX(-2%) rotate(-6deg); }+ 70% { transform: rotate(4deg); }+ 82% { transform: rotate(-2deg); }+}+@keyframes bf-shadow-done { 0%, 100% { transform: none; } 36%, 52% { transform: scale(.55); opacity: .4; } 70% { transform: scale(1.1); } }+@keyframes bf-shadow-hello { 0% { transform: scale(0); } 22% { transform: scale(1.1); } 34% { transform: scale(.8); } 46%, 100% { transform: none; } }+@keyframes bf-aura-flash { 0% { opacity: 0; transform: scale(.6); } 30% { opacity: 1; transform: scale(1.12); } 100% { opacity: 0; transform: scale(1); } }++/* 耳朵和配件跟着一次性反应动:天线弹簧、耳朵扇两下;悬停时也弹一下(打招呼) */+@keyframes bf-spring {+ 0%, 100% { transform: none; }+ 14% { transform: rotate(-16deg); }+ 30% { transform: rotate(13deg); }+ 46% { transform: rotate(-8deg); }+ 62% { transform: rotate(5deg); }+ 78% { transform: rotate(-2deg); }+}+@keyframes bf-flap-l { 0%, 100% { transform: none; } 25% { transform: rotate(16deg); } 50% { transform: rotate(-6deg); } 75% { transform: rotate(5deg); } }+@keyframes bf-flap-r { 0%, 100% { transform: none; } 25% { transform: rotate(-16deg); } 50% { transform: rotate(6deg); } 75% { transform: rotate(-5deg); } }+.bot-face.pokeable:hover:not([data-shot]) .bf-top .bf-pin,+.bot-hover:hover .bot-face:not([data-shot]) .bf-top .bf-pin { animation: bf-spring var(--bf-perk) var(--ease-out); }+.bot-face.pokeable:hover:not([data-shot]) .bf-ear-l .bf-pin,+.bot-hover:hover .bot-face:not([data-shot]) .bf-ear-l .bf-pin { animation: bf-flap-l var(--bf-perk) var(--ease-out); }+.bot-face.pokeable:hover:not([data-shot]) .bf-ear-r .bf-pin,+.bot-hover:hover .bot-face:not([data-shot]) .bf-ear-r .bf-pin { animation: bf-flap-r var(--bf-perk) var(--ease-out); }+.bot-face:is([data-shot="hello"], [data-shot="done"], [data-shot="poke"], [data-shot="love"], [data-shot="dizzy"]) .bf-top .bf-pin { animation: bf-spring var(--bot-done) var(--ease-out); }+.bot-face:is([data-shot="hello"], [data-shot="done"], [data-shot="poke"], [data-shot="love"]) .bf-ear-l .bf-pin { animation: bf-flap-l var(--bot-poke) var(--ease-out); }+.bot-face:is([data-shot="hello"], [data-shot="done"], [data-shot="poke"], [data-shot="love"]) .bf-ear-r .bf-pin { animation: bf-flap-r var(--bot-poke) var(--ease-out); }+.bot-face[data-shot="error"] .bf-ear-l { rotate: -10deg; }+.bot-face[data-shot="error"] .bf-ear-r { rotate: 10deg; }+.bot-face[data-shot="error"] .bf-top { rotate: 12deg; }++/* —— 角色的招牌动作 —— */+/* 小蓝:天线左右晃、天线球亮起来、一圈圈发出信号;完成时天线球闪一下 */+.bot-face[data-char="blue"]:is([data-state="thinking"], [data-state="replying"], [data-state="working"]) .bf-top { animation: bf-sway var(--bf-sway) var(--ease-in-out) infinite alternate; }+.bot-face[data-char="blue"]:is([data-state="thinking"], [data-state="replying"], [data-state="working"]) .bf-top .bf-img { animation: bf-bulb var(--bf-ring) var(--ease-in-out) infinite; }+.bot-face[data-char="blue"]:is([data-shot="done"], [data-shot="hello"]) .bf-top .bf-img { animation: bf-bulb var(--bot-poke) var(--ease-out) 2; }+@keyframes bf-sway { from { transform: rotate(-5deg); } to { transform: rotate(5deg); } }+@keyframes bf-bulb { 0%, 100% { filter: none; } 40% { filter: brightness(1.45) drop-shadow(0 0 calc(var(--s) * .05) var(--bf-glow)); } }++/* 小萌:星星一闪一闪、身边冒小星星;完成时星星像硬币一样转两圈 */+.bot-face[data-char="yellow"]:is([data-state="thinking"], [data-state="replying"], [data-state="working"]) .bf-top { animation: bf-twinkle var(--bf-twinkle) var(--ease-in-out) infinite; }+.bot-face[data-char="yellow"]:is([data-shot="done"], [data-shot="hello"], [data-shot="love"]) .bf-top .bf-pin { animation: bf-coin var(--bot-done) var(--ease-out); }+@keyframes bf-twinkle {+ 0%, 100% { transform: none; filter: none; }+ 30% { transform: rotate(-10deg) scale(1.08); filter: brightness(1.25) drop-shadow(0 0 calc(var(--s) * .04) var(--bf-glow)); }+ 60% { transform: rotate(8deg) scale(1.03); }+}+@keyframes bf-coin {+ 0% { transform: perspective(calc(var(--s) * 2)) translateY(0) rotateY(0); }+ 60% { transform: perspective(calc(var(--s) * 2)) translateY(-5%) rotateY(720deg); }+ 100% { transform: perspective(calc(var(--s) * 2)) translateY(0) rotateY(720deg); }+}++/* 绿草:叶子像被风吹一样扑簌;完成时嫩芽长高一截、飘下一片叶子;出错时蔫了 */+.bot-face[data-char="green"]:is([data-state="thinking"], [data-state="replying"], [data-state="working"]) .bf-top { animation: bf-flutter var(--bf-flutter) var(--ease-in-out) infinite; }+.bot-face[data-char="green"]:is([data-shot="done"], [data-shot="hello"]) .bf-top .bf-pin { animation: bf-grow var(--bot-done) var(--ease-out); }+.bot-face[data-char="green"][data-shot="error"] .bf-top { rotate: 22deg; scale: 1 .86; }+@keyframes bf-flutter { 0%, 100% { transform: rotate(-6deg) skewX(3deg); } 50% { transform: rotate(6deg) skewX(-3deg); } }+@keyframes bf-grow {+ 0%, 100% { transform: none; }+ 30% { transform: scale(1.3) rotate(-6deg); }+ 50% { transform: scale(.92) rotate(4deg); }+ 68% { transform: scale(1.1); }+ 84% { transform: scale(.98); }+}++/* 红魔:耳机灯带跟着节拍亮(左耳 → 角 → 右耳),耳机一下一下地震;完成时灯带闪三下;出错时灯带乱闪 */+.bot-face[data-char="red"]:is([data-state="thinking"], [data-state="replying"], [data-state="working"]) .bf-glow { animation: bf-beat var(--bf-beat) var(--ease-out) infinite; }+.bot-face[data-char="red"]:is([data-state="thinking"], [data-state="replying"], [data-state="working"]) .bf-top .bf-glow { animation-delay: calc(var(--bf-beat) / 3); }+.bot-face[data-char="red"]:is([data-state="thinking"], [data-state="replying"], [data-state="working"]) .bf-ear-r .bf-glow { animation-delay: calc(var(--bf-beat) * 2 / 3); }+.bot-face[data-char="red"]:is([data-state="replying"], [data-state="working"]) .bf-ear-l { animation: bf-thump var(--bf-beat) var(--ease-out) infinite; }+.bot-face[data-char="red"]:is([data-state="replying"], [data-state="working"]) .bf-ear-r { animation: bf-thump var(--bf-beat) var(--ease-out) infinite; }+.bot-face[data-char="red"][data-state="thinking"] .bf-top { animation: bf-sway var(--bf-sway) var(--ease-in-out) infinite alternate; }+.bot-face[data-char="red"]:is([data-shot="done"], [data-shot="hello"]) .bf-glow { animation: bf-flash3 var(--bot-done) linear both; }+.bot-face[data-char="red"][data-shot="error"] .bf-glow { animation: bf-flicker var(--bot-error) steps(1) both; }+@keyframes bf-beat { 0%, 100% { opacity: .1; } 18% { opacity: 1; } }+@keyframes bf-thump { 0%, 100% { transform: none; } 18% { transform: scale(1.05); } }+@keyframes bf-flash3 { 0%, 30%, 62%, 100% { opacity: 0; } 14%, 46%, 78% { opacity: 1; } }+@keyframes bf-flicker { 0%, 12%, 30%, 44%, 70% { opacity: 1; } 6%, 22%, 38%, 58%, 100% { opacity: 0; } }++/* 紫钻:宝石浮起来慢慢转、霓虹线一明一暗、身边闪光;完成时宝石飞快转两圈;出错时霓虹乱闪 */+.bot-face[data-char="purple"]:is([data-state="thinking"], [data-state="replying"], [data-state="working"]) .bf-top { animation: bf-levitate var(--bf-float) var(--ease-in-out) infinite alternate; }+.bot-face[data-char="purple"]:is([data-state="thinking"], [data-state="replying"], [data-state="working"]) .bf-top .bf-img { animation: bf-gem var(--bf-spin) linear infinite; }+.bot-face[data-char="purple"]:is([data-state="thinking"], [data-state="replying"], [data-state="working"]) .bf-glow { animation: bf-neon var(--bf-float) var(--ease-in-out) infinite alternate; }+.bot-face[data-char="purple"]:is([data-shot="done"], [data-shot="hello"], [data-shot="love"]) .bf-top .bf-pin { animation: bf-coin var(--bot-done) var(--ease-out); }+.bot-face[data-char="purple"]:is([data-shot="done"], [data-shot="hello"]) .bf-glow { animation: bf-flash3 var(--bot-done) linear both; }+.bot-face[data-char="purple"][data-shot="error"] .bf-glow { animation: bf-flicker var(--bot-error) steps(1) both; }+.bot-face[data-char="purple"][data-state="sleep"] .bf-top { rotate: 0deg; filter: brightness(.7) saturate(.6); }+@keyframes bf-levitate { from { transform: translateY(-2%); } to { transform: translateY(-6%); } }+@keyframes bf-gem { from { transform: perspective(calc(var(--s) * 2)) rotateY(0); } to { transform: perspective(calc(var(--s) * 2)) rotateY(360deg); } }+@keyframes bf-neon { from { opacity: .15; } to { opacity: .9; } }++/* 探险者:天线一蹦一蹦、眼睛大范围地左右搜寻、护目镜反光;完成时两只镜片一起闪 */+.bot-face[data-char="orange"]:is([data-state="thinking"], [data-state="replying"], [data-state="working"]) .bf-top { animation: bf-sway var(--bf-sway) var(--ease-back) infinite alternate; }+.bot-face[data-char="orange"]:is([data-state="thinking"], [data-state="replying"], [data-state="working"]) .bf-glance { animation: bf-scan var(--bf-scan) var(--ease-in-out) infinite alternate; }+.bot-face[data-char="orange"]:is([data-state="thinking"], [data-state="replying"], [data-state="working"]) .bf-lens::after { animation: bf-glint var(--bf-sweep) var(--ease-in-out) infinite; }+.bot-face[data-char="orange"].lively[data-state="idle"] .bf-lens::after { animation: bf-glint var(--bf-glance) var(--ease-in-out) infinite; }+.bot-face[data-char="orange"]:is([data-shot="done"], [data-shot="hello"]) .bf-lens::after { animation: bf-glint var(--bot-poke) var(--ease-out) both; }+.bot-face[data-char="orange"] .bf-lens + .bf-lens::after { animation-delay: calc(var(--bf-sweep) / 12); }+@keyframes bf-scan { from { transform: translate(-2.6px, -.3px); } to { transform: translate(2.6px, -.3px); } }+@keyframes bf-glint { 0%, 55% { translate: -110% 0; } 85%, 100% { translate: 110% 0; } }++/* —— 粒子(≥ 36px 才画) —— */+.bot-face .fx, .bot-face .fx i { position: absolute; display: block; pointer-events: none; }+.fx-rings { left: var(--tip-x); top: var(--tip-y); }+.fx-rings i {+ width: calc(var(--s) * .22); aspect-ratio: 1; translate: -50% -50%; border-radius: 50%; opacity: 0;+ border: calc(var(--s) * .016) solid var(--bf-glow);+ animation: bf-ring var(--bf-ring) var(--ease-out) infinite;+}+.fx-rings i:nth-child(2) { animation-delay: var(--bf-ring-gap); }+.fx-rings i:nth-child(3) { animation-delay: calc(var(--bf-ring-gap) * 2); }+@keyframes bf-ring { 0% { opacity: .9; transform: scale(.5); } 100% { opacity: 0; transform: scale(2.4); } }++.fx-twinkle { left: var(--tip-x); top: var(--tip-y); }+.fx-twinkle i {+ width: calc(var(--s) * .07); aspect-ratio: 1; translate: -50% -50%; scale: 0;+ background: var(--bf-eye); filter: drop-shadow(0 0 calc(var(--s) * .02) var(--bf-glow));+ clip-path: polygon(50% 0, 62% 38%, 100% 50%, 62% 62%, 50% 100%, 38% 62%, 0 50%, 38% 38%);+ animation: bf-sparkle var(--bf-twinkle) var(--ease-in-out) infinite;+}+.fx-twinkle i:nth-child(1) { left: calc(var(--s) * -.17); top: calc(var(--s) * -.04); }+.fx-twinkle i:nth-child(2) { left: calc(var(--s) * .16); top: calc(var(--s) * -.09); animation-delay: calc(var(--bf-twinkle) / 3); }+.fx-twinkle i:nth-child(3) { left: calc(var(--s) * .12); top: calc(var(--s) * .07); animation-delay: calc(var(--bf-twinkle) * 2 / 3); }+@keyframes bf-sparkle { 0%, 100% { scale: 0; rotate: 0deg; } 50% { scale: 1; rotate: 45deg; } }++/* 思考泡泡 */+.fx-think {+ right: -14%; top: 0; width: 38%; height: 20%; border-radius: var(--r-full);+ display: flex; align-items: center; justify-content: center; gap: 9%;+ background: var(--surface-solid); box-shadow: var(--shadow-sm);+ --pop-dy: 4px; animation: fade-in var(--dur-base) var(--ease-out), pop-in var(--dur-slower) var(--ease-spring);+}+.bot-face .fx-think i { position: static; width: 16%; aspect-ratio: 1; border-radius: 50%; background: var(--muted); animation: bf-dot var(--bf-dot) var(--ease-in-out) infinite; }+.fx-think i:nth-child(2) { animation-delay: calc(var(--bf-dot) / 6); }+.fx-think i:nth-child(3) { animation-delay: calc(var(--bf-dot) / 3); }+@keyframes bf-dot { 0%, 60%, 100% { transform: none; opacity: .5; } 30% { transform: translateY(-40%); opacity: 1; } }++/* 等你批准的感叹号 */+.fx-bang {+ right: -6%; top: -4%; width: 28%; aspect-ratio: 1; border-radius: 50%;+ display: grid; place-items: center; background: var(--amber); color: var(--surface-solid);+ font-size: calc(var(--s) * .2); font-weight: var(--fw-semibold); line-height: 1;+ box-shadow: 0 0 0 calc(var(--s) * .03) var(--surface-solid);+ transform-origin: 50% 100%; animation: bf-bang var(--bf-bang) var(--ease-in-out) infinite;+}+@keyframes bf-bang { 0%, 100% { transform: rotate(-10deg); } 50% { transform: rotate(10deg) scale(1.1); } }++/* 睡觉的 z */+.fx-zzz { right: 4%; top: 6%; }+.fx-zzz i {+ font-size: calc(var(--s) * .16); font-style: normal; font-weight: var(--fw-semibold); color: var(--muted); opacity: 0;+ animation: bf-z var(--bf-z) var(--ease-out) infinite;+}+.fx-zzz i:nth-child(2) { animation-delay: calc(var(--bf-z) / 3); }+.fx-zzz i:nth-child(3) { animation-delay: calc(var(--bf-z) * 2 / 3); }+@keyframes bf-z {+ 0% { opacity: 0; transform: scale(.5); }+ 20% { opacity: 1; }+ 100% { opacity: 0; transform: translate(calc(var(--s) * .2), calc(var(--s) * -.32)) scale(1.15) rotate(12deg); }+}++/* 完成 / 打招呼 / 爱心:一圈闪光炸开 */+.fx-burst { left: 50%; top: 48%; filter: drop-shadow(0 0 calc(var(--s) * .02) var(--bf-glow)); }+.fx-burst i {+ width: calc(var(--s) * .1); aspect-ratio: 1; translate: -50% -50%; opacity: 0;+ background: var(--bf-eye);+ clip-path: polygon(50% 0, 62% 38%, 100% 50%, 62% 62%, 50% 100%, 38% 62%, 0 50%, 38% 38%);+ animation: bf-burst var(--bot-done) var(--ease-out) both;+}+.fx-burst i:nth-child(odd) { --far: .7; width: calc(var(--s) * .07); }+.bot-face[data-shot="hello"] .fx-burst i { animation-name: bf-burst-late; animation-duration: var(--bot-hello); }+.bot-face[data-shot="love"] .fx-burst i { background: var(--bot-blush); }+@keyframes bf-burst {+ 0% { opacity: 1; transform: rotate(var(--a)) translateY(0) scale(0); }+ 65% { opacity: 1; }+ 100% { opacity: 0; transform: rotate(var(--a)) translateY(calc(var(--s) * -.62 * var(--far, 1))) scale(1) rotate(90deg); }+}+@keyframes bf-burst-late {+ 0%, 22% { opacity: 0; transform: rotate(var(--a)) translateY(0) scale(0); }+ 30% { opacity: 1; }+ 80% { opacity: 1; }+ 100% { opacity: 0; transform: rotate(var(--a)) translateY(calc(var(--s) * -.62 * var(--far, 1))) scale(1) rotate(90deg); }+}++/* 绿草长高时飘下来的叶子 */+.fx-leaf {+ left: var(--tip-x); top: var(--tip-y); width: calc(var(--s) * .12); height: calc(var(--s) * .07);+ border-radius: 0 100%; background: color-mix(in srgb, var(--bf-glow) 60%, var(--bf-eye));+ animation: bf-leaf var(--bot-done) var(--ease-in-out) both;+}+@keyframes bf-leaf {+ 0% { opacity: 0; transform: translate(0, 0) rotate(0); }+ 20% { opacity: 1; }+ 100% { opacity: 0; transform: translate(calc(var(--s) * .42), calc(var(--s) * .22)) rotate(200deg); }+}++/* 连戳三下:冒爱心 */+.fx-hearts { left: 50%; top: 18%; }+.fx-hearts i {+ font-size: calc(var(--s) * .16); font-style: normal; line-height: 1; color: var(--bot-blush); opacity: 0;+ animation: bf-heart-up var(--bot-love) var(--ease-out) both;+}+.fx-hearts i::before { content: "♥"; }+.fx-hearts i:nth-child(1) { --hx: -1; }+.fx-hearts i:nth-child(2) { --hx: .2; animation-delay: calc(var(--bot-love) / 6); }+.fx-hearts i:nth-child(3) { --hx: 1; animation-delay: calc(var(--bot-love) / 3); }+@keyframes bf-heart-up {+ 0% { opacity: 0; transform: translate(-50%, 0) scale(.4); }+ 25% { opacity: 1; transform: translate(calc(-50% + var(--hx) * var(--s) * .1), calc(var(--s) * -.12)) scale(1); }+ 100% { opacity: 0; transform: translate(calc(-50% + var(--hx) * var(--s) * .26), calc(var(--s) * -.42)) scale(.9); }+}++/* 戳晕了:头顶绕圈的小星星 */+.fx-orbit { left: 50%; top: 22%; }+.fx-orbit i {+ width: calc(var(--s) * .09); aspect-ratio: 1; margin: calc(var(--s) * -.045);+ background: var(--bot-yellow-glow);+ clip-path: polygon(50% 0, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%);+ animation: bf-orbit-x var(--bf-orbit) var(--ease-in-out) infinite alternate, bf-orbit-y var(--bf-orbit) var(--ease-in-out) calc(var(--bf-orbit) / -2) infinite alternate;+}+.fx-orbit i:nth-child(2) { animation-delay: calc(var(--bf-orbit) * -2 / 3), calc(var(--bf-orbit) * -2 / 3 - var(--bf-orbit) / 2); }+.fx-orbit i:nth-child(3) { animation-delay: calc(var(--bf-orbit) * -4 / 3), calc(var(--bf-orbit) * -4 / 3 - var(--bf-orbit) / 2); }+@keyframes bf-orbit-x { from { translate: calc(var(--s) * -.34) 0; } to { translate: calc(var(--s) * .34) 0; } }+@keyframes bf-orbit-y { from { transform: translateY(calc(var(--s) * -.07)) scale(.7); } to { transform: translateY(calc(var(--s) * .07)) scale(1.1); } }++/* —— 官网补充(App 里没有):被吵醒、睡觉时不眨眼、粒子用到的通用关键帧 —— */+/* 打瞌睡被吵醒:一激灵跳起来、眼睛瞪圆、耳朵竖直,头顶一个 !,然后左右看看装没事 */+.bot-face[data-shot="startle"] .bf-shot { animation: bf-startle .9s var(--ease-out) both; }+.bot-face[data-shot="startle"] .bf-lid { scale: 1.32; }+.bot-face[data-shot="startle"] .bf-ear-l { rotate: 14deg; }+.bot-face[data-shot="startle"] .bf-ear-r { rotate: -14deg; }+.bot-face[data-shot="startle"] .bf-top .bf-pin { animation: bf-spring .9s var(--ease-out); }+.bot-face[data-shot="startle"] .fx-bang { animation: pop-in .3s var(--ease-back) both, bf-bang .6s var(--ease-in-out) .3s 1; }+@keyframes bf-startle {+ 0% { transform: none; }+ 10% { transform: translateY(-18%) scale(.92, 1.1); }+ 26% { transform: translateY(-3%) scale(1.06, .95); }+ 38% { transform: none; }+ 54% { transform: translateX(-3.5%) rotate(-4deg); }+ 72% { transform: translateX(3%) rotate(3deg); }+ 86%, 100% { transform: none; }+}+.bot-face[data-state="sleep"] .bf-lid { animation: none; }+.bot-face[data-state="sleep"] .bf-aura { opacity: 0; }+.fx-think, .fx-bang { z-index: 1; }+@keyframes spin { to { rotate: 360deg; } }+@keyframes fade-in { from { opacity: 0; } }+@keyframes pop-in { from { transform: translateY(var(--pop-dy, 4px)) scale(.6); } }++/* —— 台词气泡(lib/eyes.ts 的 say):挂在 body 上,按页面坐标贴在头顶;尾巴指向说话的机器人 —— */+.quip {+ position: absolute; z-index: var(--z-float, 60); max-width: min(260px, calc(100vw - 20px));+ padding: 8px 13px; border-radius: 14px; translate: 0 calc(-100% - 10px);+ background: var(--text); color: var(--bg);+ font: 500 13.5px/1.4 var(--font-sans); letter-spacing: 0; white-space: normal; text-wrap: balance; pointer-events: none;+ box-shadow: 0 10px 28px -10px rgba(0, 0, 0, .45);+ transform-origin: var(--tail, 50%) calc(100% + 8px);+ animation: quip-in .32s cubic-bezier(.34, 1.56, .64, 1) both;+}+.quip::after {+ content: ""; position: absolute; left: var(--tail, 50%); top: 100%; width: 12px; height: 7px; margin-left: -6px;+ background: inherit; clip-path: polygon(0 0, 100% 0, 50% 100%);+}+.quip.is-out { animation: quip-out .2s var(--ease-out, ease-out) both; }+@keyframes quip-in { from { opacity: 0; transform: translateY(6px) scale(.6); } }+@keyframes quip-out { to { opacity: 0; transform: translateY(-4px) scale(.92); } }++/* 减少动态效果:只留表情变化,不动 */+@media (prefers-reduced-motion: reduce) {+ .bot-face, .bot-face * { animation: none !important; transition: none !important; }+ .bot-face .bf-look, .bot-face .bf-gaze { transform: none; }+ .bot-face .fx:not(.fx-bang, .fx-think) { display: none; }+ .bot-face[data-eyes="error"] .e-sad { opacity: 1; scale: 1; rotate: -14deg; }+ .quip, .quip.is-out { animation: none; }+}+}diff --git a/anymodelbot_design/onboarding/css/proto.css b/anymodelbot_design/onboarding/css/proto.cssnew file mode 100644index 0000000..1d34cfc--- /dev/null+++ b/anymodelbot_design/onboarding/css/proto.css@@ -0,0 +1,149 @@+@layer tokens, base, components, app, utilities;+/* 新手引导原型的 token 与动效。颜色、字体、圆角与官网(site/src/styles/tokens.css 深色)一致;+ 页面本身大多是内联样式(来自设计稿),这里只放会动的部分,由 js/proto.js 和各页脚本加减 class。 */++@font-face { font-family: "Geist"; src: url("../assets/fonts/Geist-Variable.woff2") format("woff2"); font-weight: 100 900; font-display: swap; }+@font-face { font-family: "Geist Mono"; src: url("../assets/fonts/GeistMono-Variable.woff2") format("woff2"); font-weight: 100 900; font-display: swap; }++@layer tokens {+ :root {+ color-scheme: dark;+ --bg: #060706; --bg-raised: #0b0b10; --bg-sunken: #101110;+ --text: #fafaf7; --text-2: #a1a1aa;+ --lime: #d7ff00; --lime-200: #e9ff66; --ink: #161a00; --wash: rgba(215, 255, 0, .14);+ --ok: #6fd99b; --warn: #f2b544;+ --line: rgba(255, 255, 255, .10); --line-strong: rgba(255, 255, 255, .18);+ --font-sans: Geist, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans SC", system-ui, sans-serif;+ --font-mono: "Geist Mono", ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace;+ --ease-out: cubic-bezier(.2, .8, .2, 1); --ease-spring: cubic-bezier(.16, 1, .3, 1); --ease-back: cubic-bezier(.34, 1.56, .64, 1);+ --z-float: 60;+ --bot-blue-eye: #6dd4fb; --bot-blue-glow: #2a9dff;+ --bot-yellow-eye: #fcfcdc; --bot-yellow-glow: #ffc21a;+ --bot-green-eye: #b5fbd6; --bot-green-glow: #2ee88a;+ --bot-red-eye: #fc9379; --bot-red-glow: #ff3b2a;+ --bot-purple-eye: #fdc1fb; --bot-purple-glow: #c24dff;+ --bot-orange-eye: #fdd77c; --bot-orange-glow: #ff8c1a;+ --bot-blush: #ff7aa8; --bot-glint: rgba(255, 255, 255, .8); --bot-dizzy: #c0a6ff;+ --avatar-aura: 52%; --avatar-shadow: rgba(0, 0, 0, .5);+ }+}++@layer app {+ [hidden] { display: none !important; }+ /* 脚本跑起来之前先不画:否则会先闪一下静态页,再跳到出场动画的第一帧。脚本出错时 2.5 秒后照样显示 */+ body[data-page]:not(.ready) { opacity: 0; animation: show-anyway 0s 2.5s forwards; }+ @keyframes show-anyway { to { opacity: 1; } }+ textarea.input { display: block; width: 100%; resize: none; border: 0; outline: none; background: none; color: var(--text); font: 14px/1.6 var(--font-sans); padding: 14px 16px 6px; }+ textarea.input::placeholder { color: var(--text-2); opacity: 1; }++ /* —— 聚光:要用户点的地方,一圈往外扩散的黄绿光 ——+ 设计稿里静态写死的光圈(inline box-shadow: 0 0 0 2px #d7ff00 …)也一起动起来 */+ .spot, [style*="0 0 0 2px #d7ff00"] { animation: spot 1.9s var(--ease-out) infinite; }+ @keyframes spot {+ 0% { box-shadow: 0 0 0 2px var(--lime), 0 0 0 0 rgba(215, 255, 0, .42); }+ 70%, 100% { box-shadow: 0 0 0 2px var(--lime), 0 0 0 14px rgba(215, 255, 0, 0); }+ }+ /* 输入框:内圈 + 柔光呼吸 */+ .spot-soft { animation: spot-soft 2.2s ease-in-out infinite; }+ @keyframes spot-soft {+ 0%, 100% { box-shadow: inset 0 0 0 1.5px var(--lime), 0 0 0 4px rgba(215, 255, 0, .10); }+ 50% { box-shadow: inset 0 0 0 1.5px var(--lime), 0 0 0 9px rgba(215, 255, 0, .04); }+ }+ .send-ready { opacity: 1 !important; background: var(--lime) !important; color: var(--ink) !important; animation: send-beat 1.6s var(--ease-out) infinite; }+ @keyframes send-beat { 0%, 100% { transform: scale(1); } 12% { transform: scale(1.12); } 24% { transform: scale(1); } }++ /* —— 出场 —— */+ .rise { animation: rise .62s var(--ease-spring) both; animation-delay: var(--d, 0ms); }+ @keyframes rise { from { opacity: 0; transform: translateY(14px); } }+ .pop { animation: pop .5s var(--ease-back) both; animation-delay: var(--d, 0ms); }+ @keyframes pop { from { opacity: 0; transform: scale(.86); } }+ .bubble-in { transform-origin: 100% 100%; animation: bubble-in .42s var(--ease-spring) both; }+ @keyframes bubble-in { from { opacity: 0; transform: translate(14px, 10px) scale(.92); } }+ .fade-in { animation: fade-in .4s var(--ease-out) both; animation-delay: var(--d, 0ms); }+ @keyframes fade-in { from { opacity: 0; } }++ /* 引导卡片:弹出时整体上浮;卡片上的主持机器人用它自己的入场动画(hello,从无到有弹出来),见 js/proto.js 的 coach() */+ .coach-in { animation: coach-in .6s var(--ease-spring) both; }+ @keyframes coach-in { from { opacity: 0; transform: translateY(16px) scale(.96); } }+ .coach-out { animation: coach-out .22s var(--ease-out) both; }+ @keyframes coach-out { to { opacity: 0; transform: translateY(8px) scale(.98); } }+ .swap { animation: swap .45s var(--ease-spring) both; }+ @keyframes swap { from { opacity: 0; transform: translateY(6px); filter: blur(2px); } }++ /* 进度格:点亮时弹一下 */+ .seg-on { animation: seg-on .7s var(--ease-back) both; }+ @keyframes seg-on { 0% { transform: scaleY(.2); background: #fff; } 60% { transform: scaleY(1.5); } }+ .bump { animation: bump .6s var(--ease-back); }+ @keyframes bump { 30% { transform: scale(1.05); box-shadow: inset 0 0 0 1px var(--lime), 0 0 0 8px rgba(215, 255, 0, .16); } }+ .roll { display: inline-block; animation: roll .45s var(--ease-spring) both; }+ @keyframes roll { from { opacity: 0; transform: translateY(70%); } }+ .flash { animation: flash 1.6s var(--ease-out) both; }+ @keyframes flash { 0%, 30% { background-color: rgba(215, 255, 0, .22); } }++ /* 正在打字:光标、思考中的三个点 */+ .caret::after { content: ""; display: inline-block; width: 2px; height: 1.05em; margin-left: 2px; vertical-align: -.18em; background: var(--lime); animation: caret 1s steps(1) infinite; }+ @keyframes caret { 50% { opacity: 0; } }+ .dots { display: inline-flex; gap: 3px; margin-left: 4px; vertical-align: middle; }+ .dots i { width: 4px; height: 4px; border-radius: 50%; background: currentColor; animation: dot 1.1s ease-in-out infinite; }+ .dots i:nth-child(2) { animation-delay: .15s; } .dots i:nth-child(3) { animation-delay: .3s; }+ @keyframes dot { 0%, 60%, 100% { transform: none; opacity: .4; } 30% { transform: translateY(-4px); opacity: 1; } }++ /* 打勾:描一笔 */+ .tick path { stroke-dasharray: 24; stroke-dashoffset: 24; animation: tick .5s var(--ease-out) .1s forwards; }+ @keyframes tick { to { stroke-dashoffset: 0; } }++ /* 骨架闪光、二维码扫描线、生成进度 */+ .shimmer { position: relative; overflow: hidden; }+ .shimmer::after { content: ""; position: absolute; inset: 0; background: linear-gradient(100deg, transparent 30%, rgba(255, 255, 255, .07) 50%, transparent 70%); transform: translateX(-100%); animation: shimmer 1.4s ease-in-out infinite; }+ @keyframes shimmer { to { transform: translateX(100%); } }+ .scan { position: absolute; left: 8px; right: 8px; height: 2px; top: 10px; border-radius: 2px; background: var(--lime); box-shadow: 0 0 12px 2px rgba(215, 255, 0, .6); animation: scan 1.8s ease-in-out infinite alternate; }+ @keyframes scan { to { top: calc(100% - 12px); } }+ .reveal-img { animation: reveal-img 1.1s var(--ease-out) both; }+ @keyframes reveal-img { from { filter: blur(18px) saturate(.4); transform: scale(1.04); opacity: .2; } }+ .bar { height: 4px; border-radius: 2px; background: var(--line); overflow: hidden; }+ .bar > i { display: block; height: 100%; width: 0; background: var(--lime); border-radius: inherit; transition: width .4s var(--ease-out); }++ /* 滚动到才出现(小提示页) */+ .reveal { opacity: 0; transform: translateY(18px); transition: opacity .6s var(--ease-out), transform .7s var(--ease-spring); transition-delay: var(--d, 0ms); }+ .reveal.is-in { opacity: 1; transform: none; }++ /* —— 吐司:顶部居中,完成一步时出现 —— */+ .toasts { position: fixed; left: 50%; top: 58px; z-index: 1100; display: grid; gap: 8px; justify-items: center; transform: translateX(-50%); pointer-events: none; }+ .toast { display: flex; align-items: center; gap: 10px; padding: 10px 16px 10px 10px; border-radius: 999px; background: var(--text); color: var(--bg); font: 500 13.5px/1.3 var(--font-sans); box-shadow: 0 14px 40px -12px rgba(0, 0, 0, .6); animation: toast-in .5s var(--ease-back) both; }+ .toast.is-out { animation: toast-out .25s var(--ease-out) both; }+ .toast__ic { display: grid; place-items: center; width: 24px; height: 24px; border-radius: 50%; background: var(--lime); color: var(--ink); flex: none; }+ .toast__sub { color: #52525b; font-weight: 400; }+ @keyframes toast-in { from { opacity: 0; transform: translateY(-10px) scale(.9); } }+ @keyframes toast-out { to { opacity: 0; transform: translateY(-6px) scale(.96); } }++ /* —— 彩带 —— */+ .confetti { position: fixed; inset: 0; z-index: 1200; pointer-events: none; overflow: hidden; }+ .confetti i { position: absolute; width: 8px; height: 12px; border-radius: 2px; }++ /* —— 清单浮层:点左下角「上手清单」打开 —— */+ .cl-pop { position: fixed; z-index: 1050; width: 320px; padding: 16px; border-radius: 20px; background: var(--bg-raised); color: var(--text); font: 14px/1.5 var(--font-sans); box-shadow: 0 0 0 1px var(--line-strong), 0 30px 80px -20px rgba(0, 0, 0, .75); transform-origin: 20% 100%; animation: pop .4s var(--ease-back) both; }+ .cl-pop.is-out { animation: coach-out .2s var(--ease-out) both; }+ .cl-pop h3 { margin: 0; font-size: 15px; font-weight: 600; }+ .cl-pop ol { list-style: none; margin: 12px 0 0; padding: 0; display: grid; gap: 2px; }+ .cl-pop a { display: flex; align-items: center; gap: 12px; min-height: 44px; padding: 6px 8px; border-radius: 12px; color: var(--text); text-decoration: none; }+ .cl-pop a:hover { background: rgba(255, 255, 255, .05); }+ .cl-pop .n { flex: none; display: grid; place-items: center; width: 24px; height: 24px; border-radius: 50%; box-shadow: inset 0 0 0 1px var(--line-strong); color: var(--text-2); font: 11.5px var(--font-mono); }+ .cl-pop .done .n { background: var(--lime); color: var(--ink); box-shadow: none; }+ .cl-pop .done .t { color: var(--text-2); }+ .cl-pop .cur { background: rgba(215, 255, 0, .08); box-shadow: inset 0 0 0 1px rgba(215, 255, 0, .3); }+ .cl-pop .cur .n { box-shadow: inset 0 0 0 1.5px var(--lime); color: var(--lime); }+ .cl-pop .go { margin-left: auto; color: var(--lime); font-size: 12.5px; }++ /* —— 预览翻页条 —— */+ .pv-nav { position: fixed; top: 10px; left: 50%; transform: translateX(-50%); z-index: 1000; display: flex; align-items: center; gap: 2px; height: 36px; padding: 0 6px; border-radius: 999px; background: rgba(11, 11, 16, .92); box-shadow: 0 0 0 1px var(--line-strong), 0 10px 30px -10px rgba(0, 0, 0, .6); font: 12.5px/1 var(--font-sans); color: var(--text-2); backdrop-filter: blur(8px); }+ .pv-nav a, .pv-nav button { display: inline-grid; place-items: center; min-width: 28px; height: 28px; padding: 0 8px; border-radius: 999px; color: var(--text); text-decoration: none; }+ .pv-nav a:hover, .pv-nav button:hover { background: rgba(255, 255, 255, .08); color: var(--text); }+ .pv-nav .num { font-family: var(--font-mono); color: var(--lime); padding: 0 4px; }++ @media (prefers-reduced-motion: reduce) {+ .spot, [style*="0 0 0 2px #d7ff00"], .spot-soft, .send-ready, .rise, .pop, .bubble-in, .fade-in, .coach-in, .swap,+ .seg-on, .bump, .roll, .flash, .caret::after, .dots i, .shimmer::after, .scan, .reveal-img, .toast, .cl-pop { animation: none !important; }+ .tick path { animation: none; stroke-dashoffset: 0; }+ .reveal { opacity: 1; transform: none; transition: none; }+ }+}diff --git a/anymodelbot_design/onboarding/index.html b/anymodelbot_design/onboarding/index.htmlnew file mode 100644index 0000000..0f77ffc--- /dev/null+++ b/anymodelbot_design/onboarding/index.html@@ -0,0 +1,92 @@+<!doctype html>+<html lang="zh-CN">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>新手引导 · 设计稿预览</title>+<style>+body{margin:0;background:#060706}+*,*::before,*::after{box-sizing:border-box}+a:hover{color:#e9ff66}+</style>+<link rel="stylesheet" href="css/bots.css">+<link rel="stylesheet" href="css/proto.css">+</head>+<body data-page="index">+<main style="max-width: 1200px; margin: 0 auto; padding: 88px clamp(16px, 5vw, 48px) 96px; color: #fafaf7; font: 15px/1.6 Geist, 'Noto Sans SC', 'PingFang SC', system-ui, sans-serif">+ <header style="position: relative; padding-top: 18px; margin-bottom: 56px; border-top: 1px solid rgba(255,255,255,.10)">+ <span class="face" data-char="blue" style="position: absolute; right: 0; bottom: calc(100% - 6px); width: 64px; height: 64px"></span>+ <p style="margin: 0 0 32px; font-size: 13px; letter-spacing: .08em; color: #a1a1aa"><span style="font-family: 'Geist Mono', ui-monospace, monospace; color: #d7ff00">AnyModelBot</span> <span style="color: rgba(255,255,255,.18)">/</span> 设计稿预览</p>+ <h1 style="margin: 0; font-size: clamp(32px, 4.6vw, 60px); line-height: 1.16; letter-spacing: -.012em; font-weight: 600">+ <span style="display: block">新手引导,</span><span style="display: block; color: #a1a1aa">共 7 张。</span>+ </h1>+ <p style="margin: 24px 0 0; max-width: 36em; color: #a1a1aa">每一页都能操作:照着引导卡片点一遍,就能看到完整的流程和动效;顶部的 ↻ 可以从头重播,‹ › 或键盘左右键翻页。机器人头像可以戳。</p>+ </header>+ <ul style="list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 340px), 1fr)); gap: 40px 28px">+ <li style="display: flex; flex-direction: column; gap: 12px">+ <a href="Main.html" style="display: block; position: relative; aspect-ratio: 1280 / 900; overflow: hidden; border-radius: 16px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <iframe src="Main.html" title="01 上手清单 · 对话页空状态" loading="lazy" tabindex="-1" aria-hidden="true" style="position: absolute; left: 0; top: 0; width: 1280px; height: 900px; border: 0; transform: scale(var(--k)); transform-origin: 0 0; pointer-events: none"></iframe>+ </a>+ <a href="Main.html" style="display: flex; align-items: baseline; gap: 10px; color: #fafaf7; text-decoration: none; font-weight: 500">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">01</span>01 上手清单 · 对话页空状态+ </a>+ </li>+ <li style="display: flex; flex-direction: column; gap: 12px">+ <a href="Step2-Model.html" style="display: block; position: relative; aspect-ratio: 1280 / 900; overflow: hidden; border-radius: 16px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <iframe src="Step2-Model.html" title="02 换个模型" loading="lazy" tabindex="-1" aria-hidden="true" style="position: absolute; left: 0; top: 0; width: 1280px; height: 900px; border: 0; transform: scale(var(--k)); transform-origin: 0 0; pointer-events: none"></iframe>+ </a>+ <a href="Step2-Model.html" style="display: flex; align-items: baseline; gap: 10px; color: #fafaf7; text-decoration: none; font-weight: 500">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">02</span>02 换个模型+ </a>+ </li>+ <li style="display: flex; flex-direction: column; gap: 12px">+ <a href="Step3-Weixin.html" style="display: block; position: relative; aspect-ratio: 1280 / 900; overflow: hidden; border-radius: 16px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <iframe src="Step3-Weixin.html" title="03 接到微信" loading="lazy" tabindex="-1" aria-hidden="true" style="position: absolute; left: 0; top: 0; width: 1280px; height: 900px; border: 0; transform: scale(var(--k)); transform-origin: 0 0; pointer-events: none"></iframe>+ </a>+ <a href="Step3-Weixin.html" style="display: flex; align-items: baseline; gap: 10px; color: #fafaf7; text-decoration: none; font-weight: 500">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">03</span>03 接到微信+ </a>+ </li>+ <li style="display: flex; flex-direction: column; gap: 12px">+ <a href="Step4-Hands.html" style="display: block; position: relative; aspect-ratio: 1280 / 900; overflow: hidden; border-radius: 16px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <iframe src="Step4-Hands.html" title="04 让它动手做件事" loading="lazy" tabindex="-1" aria-hidden="true" style="position: absolute; left: 0; top: 0; width: 1280px; height: 900px; border: 0; transform: scale(var(--k)); transform-origin: 0 0; pointer-events: none"></iframe>+ </a>+ <a href="Step4-Hands.html" style="display: flex; align-items: baseline; gap: 10px; color: #fafaf7; text-decoration: none; font-weight: 500">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">04</span>04 让它动手做件事+ </a>+ </li>+ <li style="display: flex; flex-direction: column; gap: 12px">+ <a href="Step5-Memory.html" style="display: block; position: relative; aspect-ratio: 1280 / 900; overflow: hidden; border-radius: 16px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <iframe src="Step5-Memory.html" title="05 让它记住你" loading="lazy" tabindex="-1" aria-hidden="true" style="position: absolute; left: 0; top: 0; width: 1280px; height: 900px; border: 0; transform: scale(var(--k)); transform-origin: 0 0; pointer-events: none"></iframe>+ </a>+ <a href="Step5-Memory.html" style="display: flex; align-items: baseline; gap: 10px; color: #fafaf7; text-decoration: none; font-weight: 500">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">05</span>05 让它记住你+ </a>+ </li>+ <li style="display: flex; flex-direction: column; gap: 12px">+ <a href="Step6-Media.html" style="display: block; position: relative; aspect-ratio: 1280 / 900; overflow: hidden; border-radius: 16px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <iframe src="Step6-Media.html" title="06 生成一张图" loading="lazy" tabindex="-1" aria-hidden="true" style="position: absolute; left: 0; top: 0; width: 1280px; height: 900px; border: 0; transform: scale(var(--k)); transform-origin: 0 0; pointer-events: none"></iframe>+ </a>+ <a href="Step6-Media.html" style="display: flex; align-items: baseline; gap: 10px; color: #fafaf7; text-decoration: none; font-weight: 500">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">06</span>06 生成一张图+ </a>+ </li>+ <li style="display: flex; flex-direction: column; gap: 12px">+ <a href="Tips.html" style="display: block; position: relative; aspect-ratio: 1280 / 900; overflow: hidden; border-radius: 16px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">+ <iframe src="Tips.html" title="随用随教的小提示 · 清单完成" loading="lazy" tabindex="-1" aria-hidden="true" style="position: absolute; left: 0; top: 0; width: 1280px; height: 900px; border: 0; transform: scale(var(--k)); transform-origin: 0 0; pointer-events: none"></iframe>+ </a>+ <a href="Tips.html" style="display: flex; align-items: baseline; gap: 10px; color: #fafaf7; text-decoration: none; font-weight: 500">+ <span style="font-family: 'Geist Mono', ui-monospace, monospace; font-size: 12px; color: #d7ff00">07</span>随用随教的小提示 · 清单完成+ </a>+ </li>+ </ul>+</main>+<script>+// 缩略图:按格子宽度缩放 1280px 宽的页面+const fit = () => document.querySelectorAll("li > a:first-child").forEach((a) => a.style.setProperty("--k", a.clientWidth / 1280));+addEventListener("resize", fit);+fit();+</script>+<script type="module" src="js/page-index.js"></script>+</body>+</html>diff --git a/anymodelbot_design/onboarding/js/bots.js b/anymodelbot_design/onboarding/js/bots.jsnew file mode 100644index 0000000..ed7e240--- /dev/null+++ b/anymodelbot_design/onboarding/js/bots.js@@ -0,0 +1,68 @@+// 把页面里的 <span class="face" data-char="blue" style="width: 34px; …"> 换成会动的毛绒机器人。+// 结构与官网 site/src/components/BotFace.astro、App 的 ui/components/avatar.js 一致;几何抄自 site/src/lib/bots.ts。+const CHARS = {+ blue: { eyes: [[38.81, 62.99], [60.82, 62.99]], r: 3.41, earL: [18.14, 62.21], earR: [81.94, 62.21], top: [49.96, 31.78], tip: [49.8, 21.2] },+ yellow: { eyes: [[38.34, 63.5], [61.4, 63.48]], r: 3.57, earL: [17.91, 62.13], earR: [82.25, 62.13], top: [50.04, 31.32], tip: [50, 19.7] },+ green: { eyes: [[38.8, 63.07], [61.09, 63.08]], r: 3.49, earL: [17.91, 62.71], earR: [82.02, 62.71], top: [50, 31.32], tip: [50.2, 21.2] },+ red: { eyes: [[37.53, 59.46], [62.24, 59.45]], r: 3.88, earL: [19.53, 58.06], earR: [80.47, 58.06], top: [50.04, 28.37], tip: [50, 15] },+ purple: { eyes: [[38.86, 63.04], [60.96, 63.04]], r: 3.49, earL: [18.14, 62.91], earR: [81.94, 62.91], top: [49.84, 32.87], tip: [50, 22] },+ orange: {+ eyes: [[38.18, 61.84], [61.83, 61.84]], r: 3.57, earL: [15.66, 61.47], earR: [84.34, 61.47], top: [50.12, 27.44], tip: [50, 17],+ lens: [[35.27, 40.85], [64.81, 40.85], 6.4],+ },+};++const pct = (p) => `${p[0]}% ${p[1]}%`;++function eyesSvg(c) {+ const R = c.r, f = (n) => +(n * R).toFixed(2);+ const spiral = Array.from({ length: 29 }, (_, i) => {+ const t = (i / 28) * Math.PI * 4.2, rr = (0.12 + (0.9 * i) / 28) * R;+ return `${i ? "L" : "M"}${(Math.cos(t) * rr).toFixed(2)} ${(Math.sin(t) * rr).toFixed(2)}`;+ }).join("");+ const eye = (e, i) => `<g transform="translate(${e[0]} ${e[1]})${i ? " scale(-1 1)" : ""}"><g class="bf-lid">+ <circle class="e e-open" r="${R}"/>+ <path class="e e-happy line" d="M${f(-1.05)} ${f(0.45)}Q0 ${f(-1.3)} ${f(1.05)} ${f(0.45)}"/>+ <path class="e e-closed line" d="M${f(-1.05)} ${f(-0.15)}Q0 ${f(0.8)} ${f(1.05)} ${f(-0.15)}"/>+ <path class="e e-sad" d="M${f(-1.05)} 0L${f(1.05)} 0A${f(1.05)} ${f(1.05)} 0 0 1 ${f(-1.05)} 0Z"/>+ <path class="e e-x line" d="M${f(-0.8)} ${f(-0.8)}L${f(0.8)} ${f(0.8)}M${f(0.8)} ${f(-0.8)}L${f(-0.8)} ${f(0.8)}"/>+ <path class="e e-spiral line thin" d="${spiral}"/>+ <path class="e e-heart" d="M0 ${f(1.05)}C${f(-1.7)} ${f(-0.05)} ${f(-1)} ${f(-1.4)} 0 ${f(-0.5)}C${f(1)} ${f(-1.4)} ${f(1.7)} ${f(-0.05)} 0 ${f(1.05)}Z"/>+ </g></g>`;+ return `<svg class="bf-eyes" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><g class="bf-gaze"><g class="bf-glance">${c.eyes.map(eye).join("")}</g></g></svg>`;+}++/** 一个占位 → 一个 .bot-face;保留占位上的定位样式和 id / data-*。48px 以上的大头像会呼吸、眨眼、四处看 */+export function renderFace(slot) {+ const char = CHARS[slot.dataset.char] ? slot.dataset.char : "blue";+ const c = CHARS[char];+ const size = parseFloat(slot.style.width) || 48;+ const lively = size >= 48;+ const el = document.createElement("div");+ el.style.cssText = slot.style.cssText;+ for (const a of slot.attributes) if (a.name === "id" || (a.name.startsWith("data-") && a.name !== "data-char")) el.setAttribute(a.name, a.value);+ el.className = ["bot-face", "pokeable", lively && "lively", size < 36 && "sm"].filter(Boolean).join(" ");+ el.dataset.char = char;+ el.dataset.state = "idle";+ el.dataset.eyes = "open";+ el.setAttribute("aria-hidden", "true");+ [+ ["--s", `${size}px`],+ ["--bf-sprite", `url("/assets/bots/${char}.webp")`],+ ["--o-el", pct(c.earL)], ["--o-er", pct(c.earR)], ["--o-top", pct(c.top)],+ ["--tip-x", `${c.tip[0]}%`], ["--tip-y", `${c.tip[1]}%`],+ ["--bf-seed", Math.random().toFixed(3)],+ ].forEach(([k, v]) => el.style.setProperty(k, v));+ const part = (k) => `<i class="bf-part bf-${k}"><i class="bf-pin"><b class="bf-img"></b><b class="bf-glow"></b></i></i>`;+ const lens = c.lens ? c.lens.slice(0, 2).map((l) => `<i class="bf-lens" style="left:${l[0]}%;top:${l[1]}%;--lens:${c.lens[2] * 2}%"></i>`).join("") : "";+ const blush = c.eyes.map((e) => `<i class="bf-blush" style="left:${(e[0] + (e[0] < 50 ? -5.6 : 5.6)).toFixed(2)}%;top:${(e[1] + 6.2).toFixed(2)}%"></i>`).join("");+ el.innerHTML = `${lively ? '<i class="bf-shadow"></i>' : ""}<i class="bf-aura"></i><div class="bf-body"><div class="bf-shot"><div class="bf-look">+ ${part("ear-l")}${part("ear-r")}${part("top")}<i class="bf-part bf-head"><b class="bf-img"></b><b class="bf-glow"></b></i>+ ${lens}${blush}${eyesSvg(c)}</div></div></div>`;+ slot.replaceWith(el);+ return el;+}++export function mountFaces(root = document) {+ return [...root.querySelectorAll(".face[data-char]")].map(renderFace);+}diff --git a/anymodelbot_design/onboarding/js/eyes.js b/anymodelbot_design/onboarding/js/eyes.jsnew file mode 100644index 0000000..8e32b9c--- /dev/null+++ b/anymodelbot_design/onboarding/js/eyes.js@@ -0,0 +1,352 @@+// 由 site/src/lib/eyes.ts 用 esbuild 转出(官网与 App 同一套机器人动效),改动请回源文件。+const clamp = (v, a, b) => Math.min(b, Math.max(a, v));+const rnd = (a, b) => a + Math.random() * (b - a);+const marks = /* @__PURE__ */ new Map();+const faces = /* @__PURE__ */ new Map();+const reduce = matchMedia("(prefers-reduced-motion: reduce)");+let px = NaN, py = NaN, raf = 0, idleT = 0, bound = false;+let io = null;+function setMode(m, mode) {+ if (m.el.dataset.mode !== mode) m.el.dataset.mode = mode;+}+function write(m, x, y) {+ if (Math.abs(x - m.x) < 0.01 && Math.abs(y - m.y) < 0.01) return;+ m.x = x;+ m.y = y;+ m.el.style.setProperty("--look-x", x.toFixed(3));+ m.el.style.setProperty("--look-y", y.toFixed(3));+}+function aim(r, tx, ty) {+ const dx = tx - (r.left + r.width / 2), dy = ty - (r.top + r.height / 2), d = Math.hypot(dx, dy);+ if (d < 2) return [0, 0];+ const t = Math.min(d / clamp(r.width * 3.2, 200, 520), 1), e = 1 - (1 - t) * (1 - t);+ return [dx / d * e, dy / d * e];+}+function aimFace(r, tx, ty) {+ const dx = tx - (r.left + r.width / 2), dy = ty - (r.top + r.height / 2);+ const fall = Math.max(0, 1 - Math.hypot(dx, dy) / Math.max(140, r.width * 4));+ return [clamp(dx / (r.width * 0.7) * fall, -1, 1), clamp(dy / (r.height * 0.7) * fall, -1, 1)];+}+function toward(r, t) {+ const dx = t.left + t.width / 2 - (r.left + r.width / 2), dy = t.top + t.height / 2 - (r.top + r.height / 2), d = Math.hypot(dx, dy);+ if (d < 2) return [0, 0];+ return [dx / d * 0.85, dy / d * 0.6];+}+function frame() {+ raf = 0;+ const vm = [...marks.values()].filter((m) => m.visible && !m.glanceT);+ const vf = [...faces.values()].filter((f) => f.visible);+ const rm = vm.map((m) => m.el.getBoundingClientRect());+ const rf = vf.map((f) => f.el.getBoundingClientRect());+ const rt = vf.map((f) => f.target?.getBoundingClientRect() ?? null);+ vm.forEach((m, i) => {+ const [x, y] = Number.isNaN(px) ? [0, 0] : aim(rm[i], px, py);+ setMode(m, "follow");+ write(m, x, y);+ });+ vf.forEach((f, i) => {+ let [x, y] = Number.isNaN(px) ? [0, 0] : aimFace(rf[i], px, py);+ if (rt[i] && Math.hypot(x, y) < 0.08) [x, y] = toward(rf[i], rt[i]);+ write(f, x, y);+ });+}+function toIdle() {+ px = py = NaN;+ faces.forEach((f) => f.target ? write(f, ...toward(f.el.getBoundingClientRect(), f.target.getBoundingClientRect())) : write(f, 0, 0));+ marks.forEach((m) => {+ if (m.glanceT) return;+ write(m, 0, 0);+ setTimeout(() => {+ if (!m.glanceT && Number.isNaN(px)) setMode(m, "idle");+ }, 220);+ });+}+function onMove(e) {+ if (e.pointerType === "touch") return;+ px = e.clientX;+ py = e.clientY;+ if (!raf) raf = requestAnimationFrame(frame);+ clearTimeout(idleT);+ idleT = window.setTimeout(toIdle, 3e3);+}+function onLeave(e) {+ if (!e.relatedTarget) {+ clearTimeout(idleT);+ idleT = window.setTimeout(toIdle, 600);+ }+}+function glanceAt(el, target, ms = 1400) {+ const m = marks.get(el);+ if (!m || reduce.matches) return;+ const t = target.getBoundingClientRect(), r = m.el.getBoundingClientRect();+ const [x, y] = aim(r, t.left + t.width / 2, t.top + t.height / 2);+ setMode(m, "follow");+ write(m, x, y);+ clearTimeout(m.glanceT);+ m.glanceT = window.setTimeout(() => {+ m.glanceT = void 0;+ if (!Number.isNaN(px)) return;+ write(m, 0, 0);+ setTimeout(() => Number.isNaN(px) && setMode(m, "idle"), 220);+ }, ms);+}+function scheduleGlance(m) {+ if (!m.target) return;+ setTimeout(() => {+ if (m.visible && m.el.dataset.mode === "idle" && m.target) glanceAt(m.el, m.target);+ scheduleGlance(m);+ }, rnd(6e3, 1e4));+}+function gazeAt(el, target) {+ const f = faces.get(el);+ if (!f) return;+ f.target = target;+ const r = el.getBoundingClientRect();+ if (!Number.isNaN(px) && Math.hypot(...aimFace(r, px, py)) >= 0.08) return;+ if (target) write(f, ...toward(r, target.getBoundingClientRect()));+ else write(f, 0, 0);+}+const BUSY = /* @__PURE__ */ new Set(["thinking", "replying", "working"]);+const sizeOf = (el) => parseFloat(getComputedStyle(el).getPropertyValue("--s")) || el.offsetWidth;+function setState(el, st) {+ if (el.dataset.state === st) return;+ el.dataset.state = st;+ const body = el.querySelector(".bf-body");+ body?.querySelectorAll(".fx-st").forEach((n) => n.remove());+ if (!el.dataset.shot) el.dataset.eyes = st === "sleep" ? "closed" : "open";+ if (!body || sizeOf(el) < 36) return;+ const add = (h) => body.insertAdjacentHTML("beforeend", h);+ if (st === "waiting") add(`<span class="fx fx-st fx-bang">!</span>`);+ if (st === "thinking") add(`<span class="fx fx-st fx-think"><i></i><i></i><i></i></span>`);+ if (reduce.matches) return;+ if (st === "sleep") add(`<span class="fx fx-st fx-zzz"><i>z</i><i>z</i><i>z</i></span>`);+ if (BUSY.has(st) && el.dataset.char === "blue") add(`<span class="fx fx-st fx-rings"><i></i><i></i><i></i></span>`);+ if (BUSY.has(st) && (el.dataset.char === "yellow" || el.dataset.char === "purple")) add(`<span class="fx fx-st fx-twinkle"><i></i><i></i><i></i></span>`);+}+const restEyes = (el) => el.dataset.state === "sleep" ? "closed" : "open";+const SHOT_EYES = { hello: "happy", poke: "happy", love: "heart", dizzy: "spiral", done: "happy", error: "error", startle: "open" };+const SHOT_MS = { hello: 1600, poke: 700, love: 1600, dizzy: 2200, done: 1300, error: 1500, startle: 900 };+const BURST = [0, 45, 90, 135, 180, 225, 270, 315];+function playShot(el, kind) {+ if (reduce.matches) {+ el.dataset.eyes = SHOT_EYES[kind];+ setTimeout(() => el.dataset.eyes = restEyes(el), SHOT_MS[kind]);+ return;+ }+ const shot = el.querySelector(".bf-shot");+ delete el.dataset.shot;+ shot?.querySelectorAll(".fx-dyn").forEach((n) => n.remove());+ void el.offsetWidth;+ el.dataset.shot = kind;+ el.dataset.eyes = SHOT_EYES[kind];+ const big = el.offsetWidth >= 36;+ if (shot && big) {+ const add = (html) => shot.insertAdjacentHTML("beforeend", html);+ if (kind === "hello" || kind === "love" || kind === "done") add(`<span class="fx fx-burst fx-dyn">${BURST.map((a, i) => `<i style="--a:${a}deg;--i:${i}"></i>`).join("")}</span>`);+ if (kind === "love") add(`<span class="fx fx-hearts fx-dyn"><i></i><i></i><i></i></span>`);+ if (kind === "dizzy") add(`<span class="fx fx-orbit fx-dyn"><i></i><i></i><i></i></span>`);+ if (kind === "done" && el.dataset.char === "green") add(`<span class="fx fx-leaf fx-dyn"></span>`);+ if (kind === "startle") add(`<span class="fx fx-bang fx-dyn">!</span>`);+ }+ clearTimeout(Number(el.dataset.shotT));+ el.dataset.shotT = String(window.setTimeout(() => {+ delete el.dataset.shot;+ el.dataset.eyes = restEyes(el);+ shot?.querySelectorAll(".fx-dyn").forEach((n) => n.remove());+ }, SHOT_MS[kind]));+}+let quipData = null;+const quipTurn = /* @__PURE__ */ new Map();+function quipFor(char, kind) {+ if (!quipData) {+ try {+ quipData = JSON.parse(document.getElementById("amb-quips")?.textContent || "{}");+ } catch {+ quipData = {};+ }+ }+ const list = kind === "wake" ? quipData.wake : kind === "poke" ? quipData[char ?? ""]?.poke : void 0;+ if (list?.length) {+ const key = `${char}:${kind}`, i = quipTurn.get(key) ?? (kind === "wake" ? Math.floor(Math.random() * list.length) : 0);+ quipTurn.set(key, i + 1);+ return list[i % list.length];+ }+ return kind === "wake" || kind === "poke" ? void 0 : quipData[char ?? ""]?.[kind];+}+const bubbles = /* @__PURE__ */ new WeakMap();+function say(el, text, ms = 2400) {+ bubbles.get(el)?.remove();+ const r = el.getBoundingClientRect();+ if (!r.width || r.bottom < 0 || r.top > innerHeight) return;+ const b = document.createElement("div");+ b.className = "quip";+ b.setAttribute("aria-hidden", "true");+ b.textContent = text;+ const scope = el.closest("[data-theme]");+ if (scope && scope !== document.documentElement) b.dataset.theme = scope.dataset.theme;+ document.body.append(b);+ const w = b.offsetWidth, cx = r.left + r.width / 2;+ const left = Math.min(Math.max(cx - w / 2, 10), document.documentElement.clientWidth - w - 10);+ b.style.left = `${left + scrollX}px`;+ b.style.top = `${r.top + scrollY + r.height * 0.1}px`;+ b.style.setProperty("--tail", `${Math.min(Math.max(cx - left, 16), w - 16)}px`);+ bubbles.set(el, b);+ setTimeout(() => {+ b.classList.add("is-out");+ setTimeout(() => b.remove(), 220);+ if (bubbles.get(el) === b) bubbles.delete(el);+ }, ms);+}+const talk = (el, kind) => {+ if (el.offsetWidth < 40) return;+ const q = quipFor(el.dataset.char, kind);+ if (q) say(el, q);+};+const pokes = /* @__PURE__ */ new WeakMap();+function poke(el) {+ const now = performance.now();+ const list = (pokes.get(el) ?? []).filter((t) => now - t < 1800).concat(now);+ const k = list.length;+ pokes.set(el, k >= 6 ? [] : list);+ const kind = k >= 6 ? "dizzy" : k >= 3 ? "love" : "poke";+ if (el.dataset.state === "sleep") {+ setState(el, "idle");+ playShot(el, "startle");+ talk(el, "wake");+ return;+ }+ playShot(el, kind);+ if (kind !== "love" || k === 3) talk(el, kind);+}+const pets = /* @__PURE__ */ new WeakMap();+function onPet(e) {+ if (e.pointerType !== "mouse") return;+ const el = e.currentTarget;+ if (el.offsetWidth < 56) return;+ const s = pets.get(el) ?? { lx: e.clientX, dir: 0, run: 0, flips: [], cool: 0 };+ pets.set(el, s);+ const dx = e.clientX - s.lx;+ s.lx = e.clientX;+ if (Math.abs(dx) < 1) return;+ const dir = Math.sign(dx), now = performance.now();+ if (dir === s.dir) {+ s.run += Math.abs(dx);+ return;+ }+ if (s.dir && s.run >= 12) s.flips = s.flips.filter((t) => now - t < 1200).concat(now);+ s.dir = dir;+ s.run = Math.abs(dx);+ if (s.flips.length >= 5 && now > s.cool && !el.dataset.shot) {+ s.flips = [];+ s.cool = now + 2600;+ playShot(el, "love");+ talk(el, "pet");+ }+}+const petReset = (e) => pets.delete(e.currentTarget);+function mountDoze(root = document) {+ const groups = [...root.querySelectorAll("[data-doze]")];+ if (!groups.length || reduce.matches) return;+ const IDLE = 2e4;+ const seen = /* @__PURE__ */ new Set(), asleep = /* @__PURE__ */ new Set(), timers = [];+ let idleT2 = 0, last = 0;+ const io2 = new IntersectionObserver((es) => es.forEach((e) => e.isIntersecting ? seen.add(e.target) : seen.delete(e.target)), { threshold: 0.2 });+ groups.forEach((g) => io2.observe(g));+ const doze = () => groups.filter((g) => seen.has(g)).forEach((g) => {+ const fs = [...g.querySelectorAll(".bot-face.lively")].filter((f) => f.offsetParent && f.dataset.state === "idle");+ fs.sort(() => Math.random() - 0.5).forEach((f, i) => timers.push(window.setTimeout(() => {+ if (f.dataset.state !== "idle" || f.dataset.shot) return;+ setState(f, "sleep");+ asleep.add(f);+ }, 300 + i * rnd(900, 2400))));+ });+ const wake = () => {+ const now = performance.now();+ if (now - last < 200 && !asleep.size) return;+ last = now;+ timers.splice(0).forEach(clearTimeout);+ clearTimeout(idleT2);+ idleT2 = window.setTimeout(doze, IDLE);+ if (!asleep.size) return;+ const list = [...asleep].sort((a, b) => sizeOf(b) - sizeOf(a));+ asleep.clear();+ list.forEach((f, i) => setTimeout(() => {+ if (f.dataset.state !== "sleep") return;+ setState(f, "idle");+ playShot(f, "startle");+ if (i === 0) setTimeout(() => talk(f, "wake"), 380);+ }, i * rnd(70, 180)));+ };+ for (const ev of ["pointermove", "pointerdown", "keydown", "scroll", "wheel", "touchstart"]) addEventListener(ev, wake, { passive: true });+ wake();+}+function mountEyes(root = document) {+ const markEls = [...root.querySelectorAll("[data-amb-mark]")].filter((el) => !marks.has(el));+ const faceEls = [...root.querySelectorAll(".bot-face")].filter((el) => !faces.has(el));+ faceEls.forEach((el) => {+ if (!el.classList.contains("pokeable") || el.dataset.pokeBound) return;+ el.dataset.pokeBound = "1";+ el.addEventListener("click", () => poke(el));+ if (el.classList.contains("lively") && !reduce.matches) {+ el.addEventListener("pointermove", onPet);+ el.addEventListener("pointerleave", petReset);+ }+ });+ if (reduce.matches) {+ markEls.forEach((el) => el.dataset.mode = "static");+ return;+ }+ io ?? (io = new IntersectionObserver((es) => es.forEach((e) => {+ const el = e.target;+ const m = marks.get(el) ?? faces.get(el);+ if (!m) return;+ m.visible = e.isIntersecting;+ if (marks.has(el)) el.dataset.visible = String(e.isIntersecting);+ }), { rootMargin: "120px" }));+ markEls.forEach((el) => {+ const sel = el.dataset.lookAt;+ const m = { el, visible: false, x: 0, y: 0, target: sel ? document.querySelector(sel) : null };+ marks.set(el, m);+ el.style.setProperty("--idle-delay", `${-rnd(0, 7.2).toFixed(2)}s`);+ el.style.setProperty("--blink-delay", `${-rnd(0, 5).toFixed(2)}s`);+ el.querySelector(".amb-mark__lids")?.addEventListener("animationiteration", () => {+ el.style.setProperty("--blink-period", `${rnd(3.2, 7.2).toFixed(2)}s`);+ el.classList.toggle("is-double", Math.random() < 0.15);+ });+ if (!el.closest("a,button")) el.addEventListener("click", () => {+ el.dataset.state = "happy";+ setTimeout(() => delete el.dataset.state, 900);+ });+ io.observe(el);+ scheduleGlance(m);+ });+ faceEls.forEach((el) => {+ faces.set(el, { el, visible: false, x: 0, y: 0, target: null });+ io.observe(el);+ });+ if (!bound) {+ bound = true;+ addEventListener("pointermove", onMove, { passive: true });+ document.addEventListener("mouseout", onLeave);+ addEventListener("pointerdown", (e) => {+ if (e.pointerType !== "touch") return;+ const hit = document.elementFromPoint(e.clientX, e.clientY);+ marks.forEach((m) => m.visible && hit && glanceAt(m.el, hit, 1200));+ }, { passive: true });+ document.addEventListener("visibilitychange", () => document.documentElement.toggleAttribute("data-tab-hidden", document.hidden));+ reduce.addEventListener("change", () => location.reload());+ }+}+export {+ aim,+ aimFace,+ gazeAt,+ glanceAt,+ mountDoze,+ mountEyes,+ playShot,+ quipFor,+ say,+ setState,+ toward+};diff --git a/anymodelbot_design/onboarding/js/page-hands.js b/anymodelbot_design/onboarding/js/page-hands.jsnew file mode 100644index 0000000..06cc100--- /dev/null+++ b/anymodelbot_design/onboarding/js/page-hands.js@@ -0,0 +1,75 @@+// 04 让它动手:输入框里已替你写好一句 → 发送 → 小蓝思考、干活(头像上下浮动)→ 逐字回复、清单逐条出现 →+// 文件卡片弹出、内容一行行写进去 → 余额扣一点 → 第 4 步完成+import * as P from "./proto.js";++P.init({ progress: 3 });+const { $, $$ } = P;+const log = $("#log"), r1 = $("#r1"), wl = $("#r1-wl"), file = $("#file"), pre = $("#file-pre");+const coach = $("#coach"), arrow = $("#arrow"), input = $("#input");+const head = P.headFace();+const SENTENCE = "在你的工作区建一个「今日待办.md」,列三件今天要做的事,然后发给我。";+const items = $$("#r1-list li");+const preText = pre.textContent;+const orig = { title: $("#c-title").textContent, body: $("#c-body").textContent };+items.forEach((li) => (li.hidden = true));+pre.textContent = "";+const bal = P.balanceEl();+if (bal) bal.textContent = "$12.39";++function stage(s) {+ const done = s === "B";+ coach.style.marginTop = done ? "180px" : "0px";+ arrow.hidden = !done;+ $("#c-badge").hidden = !done;+ $("#c-list").hidden = !done;+ $("#c-title").textContent = done ? orig.title : "让它动手做件事";+ $("#c-body").textContent = done ? orig.body : "小蓝能在自己的工作区里写文件、跑命令,做好的文件会交给你。输入框里已经替你写好了一句,点发送试试。";+}+setTimeout(() => P.coach(coach, () => stage("A")), 500);+$("#c-later").addEventListener("click", () => P.leave(coach));++const chat = P.composer({ input, send: $("#send"), onSend: run });+chat.set(SENTENCE);+input.parentElement.classList.add("spot-soft");++let busy = false;+async function run(text) {+ if (busy) return;+ busy = true;+ input.parentElement.classList.remove("spot-soft");+ P.leave(coach);+ log.insertBefore(P.userBubble(log, text), r1);+ P.enter(r1, "fade-in");+ wl.innerHTML = '思考中<span class="dots"><i></i><i></i><i></i></span>';+ P.setState(head, "thinking");+ await P.wait(1300);+ P.setState(head, "working");+ await P.wait(1500);+ P.setState(head, "replying");+ const t0 = performance.now(), sec = () => Math.max(1, Math.round((performance.now() - t0) / 1000) + 3);+ wl.textContent = `正在回复 ${sec()} 秒`;+ const tick = setInterval(() => (wl.textContent = `正在回复 ${sec()} 秒`), 1000);+ await P.stream($("#r1-a"), "建好了,先帮你列了三件:");+ for (const li of items) { P.enter(li, "rise"); await P.wait(260); }+ await P.stream($("#r1-b"), "文件已经发给你,想改哪条直接告诉我。");+ // 文件卡片:弹出来,内容一行一行写进去+ P.enter(file, "pop");+ file.classList.add("spot");+ for (const line of preText.split("\n")) {+ pre.textContent += (pre.textContent ? "\n" : "") + line;+ await P.wait(220);+ }+ clearInterval(tick);+ wl.textContent = `用时 ${sec()} 秒`;+ P.setState(head, "idle");+ if (bal) P.countTo(bal, 12.39, 12.37);+ P.lastMessage("建好了,列了三件事…");+ P.stepDone(4, "让它动手做件事", head);+ await P.wait(700);+ P.coach(coach, () => stage("B"));+ setTimeout(() => file.classList.remove("spot"), 6000);+ busy = false;+}++// 文件卡上的两个按钮在原型里只给反馈+$$("#file button").forEach((b) => b.addEventListener("click", () => P.toast(b.textContent.trim() === "打开" ? "用系统默认应用打开" : "在访达 / 资源管理器中显示", "今日待办.md")));diff --git a/anymodelbot_design/onboarding/js/page-index.js b/anymodelbot_design/onboarding/js/page-index.jsnew file mode 100644index 0000000..f4a17a1--- /dev/null+++ b/anymodelbot_design/onboarding/js/page-index.js@@ -0,0 +1,6 @@+// 目录页:标题旁的小蓝一进来就弹出来打招呼,之后会动、能戳+import * as P from "./proto.js";++P.init();+const host = P.$("header .bot-face");+if (host) P.playShot(host, "hello");diff --git a/anymodelbot_design/onboarding/js/page-main.js b/anymodelbot_design/onboarding/js/page-main.jsnew file mode 100644index 0000000..87c0f5b--- /dev/null+++ b/anymodelbot_design/onboarding/js/page-main.js@@ -0,0 +1,60 @@+// 01 上手清单:清单依次浮现 → 发出第一句 → 清单缩进左下角 → 小蓝思考、逐字回复 → 第 1 步完成+import * as P from "./proto.js";++P.init({ progress: 0 });+const { $, $$ } = P;+const intro = $("#intro"), log = $("#log"), coach = $("#coach"), input = $("#input"), send = $("#send");+const composerBox = input.parentElement;+const head = P.headFace();+const host = $("#intro .bot-face");++const ANSWER = "我能帮你聊天答疑、写东西、整理资料,也能在自己的工作区里写文件、跑命令,还能画图、做视频。把我接到微信,出门也能找我。想先试试哪个?";++// 出场:章节头、进度条、清单一行一行浮上来;主持机器人跟着章节头一起从细线上弹出来(hello 是入场动画,必须在这一帧播)+[$("#intro > header"), ...$$("#intro > div"), ...$$("#intro li")].forEach((el, i) => P.enter(el, "rise", 80 + i * 70));+if (host) P.playShot(host, "hello");+setTimeout(() => host && P.say(host, "先跟我打个招呼吧!", 2600), 1500);++let busy = false, done = false;+const chat = P.composer({ input, send, onSend: run });+$("#try").addEventListener("click", () => run("你能帮我做什么?"));+$("#collapse").addEventListener("click", collapse);+$("#c-later").addEventListener("click", () => P.leave(coach));+// 在输入:头像竖起耳朵听+input.addEventListener("input", () => !busy && P.setState(head, input.value.trim() ? "listening" : "idle"));++async function collapse() {+ if (intro.hidden) return;+ const pill = P.pill();+ await P.flyTo(intro, pill, 650);+ intro.hidden = true;+ P.setProgress(done ? 1 : 0);+}++async function run(text) {+ if (busy) return;+ busy = true;+ composerBox.classList.remove("spot-soft");+ await collapse();+ log.hidden = false;+ P.userBubble(log, text);+ P.setState(head, "thinking");+ const reply = P.botReply(log);+ await P.wait(1200);+ P.setState(head, "replying");+ const generic = !/做什么|能干|会什么|你好|嗨|hi|hello/i.test(text);+ const answer = generic ? `收到:「${text.slice(0, 24)}」。${ANSWER}` : ANSWER;+ await reply.say(answer);+ reply.done();+ P.setState(head, "idle");+ P.lastMessage(answer.slice(0, 16) + "…");+ if (!done) {+ done = true;+ await P.wait(300);+ P.stepDone(1, "跟小蓝打个招呼", head);+ await P.wait(800);+ P.coach(coach);+ }+ busy = false;+ chat.focus();+}diff --git a/anymodelbot_design/onboarding/js/page-media.js b/anymodelbot_design/onboarding/js/page-media.jsnew file mode 100644index 0000000..2be48da--- /dev/null+++ b/anymodelbot_design/onboarding/js/page-media.js@@ -0,0 +1,155 @@+// 06 生成一张图:发出一句 → 小蓝想一下 → 弹出「先确认」卡片(头像跳着等你)→ 选模型、确认 →+// 生成中(闪光 + 进度)→ 图片从模糊到清晰 → 余额扣一点 → 第 6 步完成,清单全部完成,撒彩带+import * as P from "./proto.js";++P.init({ progress: 5 });+const { $, $$ } = P;+const log = $("#log"), status = $("#status"), form = $("#confirm"), result = $("#result"), coach = $("#coach"), arrow = $("#arrow"), input = $("#input");+const head = P.headFace();+const MONO = "font-family: 'Geist Mono', ui-monospace, monospace";+const SENTENCE = "画一只戴着耳机的蓝色小机器人,扁平插画风。";+const orig = { title: $("#c-title").textContent, body: $("#c-body").textContent };+const bal = P.balanceEl();+let busy = false;++// —— 引导卡片:A 试试这句 / B 先确认再花钱 / C 全部完成 / X 取消了 ——+function stage(s) {+ coach.style.marginTop = s === "B" ? "120px" : "0px";+ arrow.hidden = s !== "B";+ $("#c-list").hidden = s !== "B";+ $("#c-note").hidden = s !== "B";+ $("#c-next").hidden = s !== "C";+ const T = {+ A: ["生成一张图", "小蓝可以画图、做视频。输入框里已经替你写好了一句,点发送看看。"],+ B: [orig.title, orig.body],+ C: ["六件事都做完了", "小蓝已经准备好了。还有一些小提示,会在你第一次用到对应功能时出现。"],+ X: ["没关系,这次没花钱", "想好了再让它画。换个说法,或者换个模型都行。"],+ }[s];+ $("#c-title").textContent = T[0];+ $("#c-body").textContent = T[1];+ if (s === "C") {+ $("#c-next").textContent = "看看小提示";+ $("#c-next").href = "Tips.html";+ $("#c-kick").insertAdjacentHTML("beforeend", `<span style="display: inline-flex; align-items: center; gap: 4px; height: 22px; padding: 0 8px; border-radius: 999px; background: #d7ff00; color: #161a00; ${MONO}; font-size: 11px; letter-spacing: 0">${P.ICON.check}完成</span>`);+ }+}+setTimeout(() => P.coach(coach, () => stage("A")), 500);+$("#c-later").addEventListener("click", () => P.leave(coach));++const chat = P.composer({ input, send: $("#send"), onSend: run });+chat.set(SENTENCE);+input.parentElement.classList.add("spot-soft");++// —— 单选:选中的那一行亮起来 ——+const labels = $$("label", form).filter((l) => $('input[type="radio"]', l));+function paint() {+ labels.forEach((l) => {+ const on = $("input", l).checked;+ l.style.background = on ? "rgba(215,255,0,.10)" : "";+ l.style.boxShadow = on ? "inset 0 0 0 1px rgba(215,255,0,.45)" : "inset 0 0 0 1px rgba(255,255,255,.10)";+ $$("span", l)[0].style.color = on ? "#d7ff00" : "#a1a1aa";+ });+}+form.addEventListener("change", paint);++async function run(text) {+ if (busy) return;+ busy = true;+ input.parentElement.classList.remove("spot-soft");+ P.leave(coach);+ log.insertBefore(P.userBubble(log, text), status);+ P.setState(head, "thinking");+ await P.wait(1400);+ // 生成前先问:头像跳着等你、确认卡片带光圈出现+ P.enter(status, "fade-in");+ P.setState(head, "waiting");+ P.enter(form, "pop");+ form.classList.add("spot");+ P.coach(coach, () => stage("B"));+}++$("#go").addEventListener("click", async () => {+ const picked = labels.find((l) => $("input", l).checked);+ const cancel = $$("span", picked).some((s) => s.textContent.trim() === "取消");+ const name = $$("span", picked)[1].textContent.trim(), price = $$("span", picked)[2].textContent.trim();+ form.classList.remove("spot");+ await P.leave(form);+ const summary = document.createElement("div");+ summary.style.cssText = `align-self: flex-start; display: inline-flex; align-items: center; gap: 8px; padding: 8px 14px; border-radius: 999px; background: #0b0b10; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); color: #a1a1aa; font-size: 12.5px`;+ summary.innerHTML = cancel ? "已取消 · 没有生成,也没有扣费" : `<span style="color: #d7ff00">${P.ICON.check}</span>已确认 · <span style="${MONO}; color: #fafaf7">${name}</span> · ${price.replace(/^默认 · /, "")}`;+ log.insertBefore(summary, result);+ P.enter(summary, "pop");+ if (cancel) {+ status.hidden = true;+ P.setState(head, "idle");+ P.playShot(head, "error");+ P.coach(coach, () => stage("X"));+ busy = false;+ chat.set(SENTENCE);+ return;+ }+ await generate(name);+});++// —— 生成中 → 出图 ——+async function generate(name) {+ P.setState(head, "working");+ $("#status-dot").style.background = "#d7ff00";+ $("#status-text").innerHTML = '正在生成<span class="dots"><i></i><i></i><i></i></span>';+ result.style.cssText = "width: 100%; max-width: 360px";+ result.innerHTML = `<div class="shimmer" style="aspect-ratio: 1; border-radius: 20px; background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); display: grid; place-items: center">+ <div style="display: grid; gap: 10px; justify-items: center; width: 60%">+ <span style="${MONO}; font-size: 12px; color: #a1a1aa" id="gen-t">${name} · 0 秒</span>+ <div class="bar" style="width: 100%"><i id="gen-bar"></i></div>+ </div></div>`;+ P.enter(result, "pop");+ const t0 = performance.now();+ for (let k = 1; k <= 10; k++) {+ await P.wait(430);+ $("#gen-bar").style.width = `${k * 10}%`;+ $("#gen-t").textContent = `${name} · ${Math.round((performance.now() - t0) / 1000)} 秒`;+ }+ result.innerHTML = `<figure style="margin: 0; display: grid; gap: 8px">+ <div style="overflow: hidden; border-radius: 20px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10)">${ROBOT}</div>+ <figcaption style="display: flex; align-items: center; gap: 8px; color: #a1a1aa; font-size: 12.5px"><span style="${MONO}; color: #fafaf7">robot-headphones.png</span>已存到工作区 media/</figcaption>+ </figure>`;+ $("svg", result).classList.add("reveal-img");+ $("#status-dot").style.background = "#6fd99b";+ $("#status-text").textContent = `用时 ${Math.round((performance.now() - t0) / 1000) + 2} 秒`;+ P.setState(head, "idle");+ P.playShot(head, "love");+ if (bal) P.countTo(bal, 12.35, 12.31);+ P.lastMessage("画好了:robot-headphones.png");+ await P.wait(700);+ P.confetti(result, 70);+ P.stepDone(6, "生成一张图");+ setTimeout(() => P.toast("上手清单全部完成", "小蓝已经准备好了"), 900);+ await P.wait(800);+ P.coach(coach, () => stage("C"));+ busy = false;+}++// 生成结果:一张扁平插画(原型里的示意图)+const ROBOT = `<svg viewBox="0 0 320 320" width="100%" style="display: block" role="img" aria-label="生成的图片:戴着耳机的蓝色小机器人,扁平插画风">+ <rect width="320" height="320" fill="#eef6c8"/>+ <circle cx="262" cy="64" r="34" fill="#d7ff00"/>+ <circle cx="54" cy="260" r="22" fill="#d7ff00" opacity=".6"/>+ <ellipse cx="160" cy="292" rx="86" ry="10" fill="#161a00" opacity=".12"/>+ <rect x="112" y="222" width="96" height="66" rx="26" fill="#2a9dff"/>+ <rect x="140" y="240" width="40" height="10" rx="5" fill="#6dd4fb"/>+ <line x1="160" y1="104" x2="160" y2="74" stroke="#13233a" stroke-width="6" stroke-linecap="round"/>+ <circle cx="160" cy="66" r="11" fill="#ff7aa8"/>+ <rect x="80" y="102" width="160" height="128" rx="46" fill="#4fb6ff"/>+ <rect x="100" y="128" width="120" height="80" rx="34" fill="#13233a"/>+ <circle cx="136" cy="166" r="11" fill="#6dd4fb"/>+ <circle cx="184" cy="166" r="11" fill="#6dd4fb"/>+ <path d="M147 188q13 10 26 0" stroke="#6dd4fb" stroke-width="5" fill="none" stroke-linecap="round"/>+ <path d="M66 170C66 70 254 70 254 170" stroke="#161a00" stroke-width="12" fill="none" stroke-linecap="round"/>+ <rect x="48" y="140" width="36" height="66" rx="15" fill="#161a00"/>+ <rect x="236" y="140" width="36" height="66" rx="15" fill="#161a00"/>+ <rect x="57" y="154" width="18" height="38" rx="8" fill="#ff8c1a"/>+ <rect x="245" y="154" width="18" height="38" rx="8" fill="#ff8c1a"/>+ <path d="M266 248v-30l18-5v28" stroke="#161a00" stroke-width="5" fill="none" stroke-linejoin="round"/>+ <circle cx="260" cy="249" r="7" fill="#161a00"/>+ <circle cx="278" cy="243" r="7" fill="#161a00"/>+</svg>`;diff --git a/anymodelbot_design/onboarding/js/page-memory.js b/anymodelbot_design/onboarding/js/page-memory.jsnew file mode 100644index 0000000..c8dd85d--- /dev/null+++ b/anymodelbot_design/onboarding/js/page-memory.js@@ -0,0 +1,119 @@+// 05 让它记住你:发「记住……」→ 回复下冒出「已写入记忆」→ 小标签飞进右边的「记忆」→ 新条目闪一下 → 第 5 步完成;+// 之后自动整理再记一条;问「还记得吗」会答出来;说「忘掉……」或点垃圾桶会删掉+import * as P from "./proto.js";++P.init({ progress: 4 });+const { $, $$ } = P;+const log = $("#log"), mem = $("#mem"), count = $("#mem-count"), coach = $("#coach"), input = $("#input");+const head = P.headFace();+const [e1, e2] = $$("#mem > div");+const textOf = (e) => $("span span", e);+const SENTENCE = "记住:回答尽量简短,结论放在最前面。";+const orig = { body: $("#c-body").textContent };+let busy = false, done = false;++// 一开始还没有记忆+log.innerHTML = "";+e1.hidden = e2.hidden = true;+mem.insertAdjacentHTML("afterbegin", '<div id="mem-empty" style="padding: 14px; color: #a1a1aa; font-size: 13px">还没有长期记忆</div>');+const empty = $("#mem-empty");+function refresh() {+ const n = [e1, e2].filter((e) => !e.hidden).length;+ count.textContent = `${n} 条`;+ P.enter(count, "roll");+ empty.hidden = n > 0;+ e1.style.borderBottom = !e1.hidden && !e2.hidden ? "1px solid rgba(255,255,255,.10)" : "0";+}+refresh();++// —— 引导卡片 ——+const tryBtn = document.createElement("button");+tryBtn.type = "button";+tryBtn.textContent = "填入";+tryBtn.style.cssText = "min-height: 30px; padding: 0 12px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); font-size: 12.5px";+$("#c-try").append(tryBtn);+tryBtn.addEventListener("click", () => { chat.set($("#c-try-text").textContent); chat.focus(); input.parentElement.classList.add("spot-soft"); });+function stage(s) {+ const b = s === "B";+ $("#c-badge").hidden = !b;+ $("#c-title").textContent = b ? "记住了,也能忘掉" : "让它记住你";+ $("#c-body").textContent = b ? "右边就是它记下的东西。开新对话、到微信里,它都记得。" : orig.body;+ $("#c-try-label").textContent = b ? "再试试" : "试试这句";+ $("#c-try-text").textContent = b ? "你还记得我的习惯吗?" : SENTENCE;+}+setTimeout(() => P.coach(coach, () => stage("A")), 500);+$("#c-later").addEventListener("click", () => P.leave(coach));++const chat = P.composer({ input, send: $("#send"), onSend: run });+chat.set(SENTENCE);+input.parentElement.classList.add("spot-soft");++async function reply(text) {+ P.setState(head, "thinking");+ const r = P.botReply(log);+ await P.wait(900);+ P.setState(head, "replying");+ await r.say(text);+ r.done();+ P.setState(head, "idle");+ return r;+}+function show(e, text) {+ if (text) textOf(e).textContent = text;+ P.enter(e, "rise");+ e.classList.remove("flash"); void e.offsetWidth; e.classList.add("flash");+ refresh();+}+async function drop(e) {+ if (e.hidden) return;+ if (!P.reduce) await e.animate([{ opacity: 1, transform: "none" }, { opacity: 0, transform: "translateX(24px)" }], { duration: 260, easing: "ease-in" }).finished;+ e.hidden = true;+ refresh();+ P.toast("已删除这条记忆");+}+$$('#mem button[aria-label="删除这条记忆"]').forEach((b) => b.addEventListener("click", () => drop(b.closest("#mem > div"))));++async function run(text) {+ if (busy) return;+ busy = true;+ input.parentElement.classList.remove("spot-soft");+ P.userBubble(log, text);+ if (/还记得|记得.*[吗??]/.test(text)) {+ await reply(e1.hidden && e2.hidden ? "我还没记住你的习惯。告诉我「记住……」就行。"+ : [!e1.hidden && `记得:${textOf(e1).textContent}。`, !e2.hidden && `还有,${textOf(e2).textContent}。`].filter(Boolean).join(""));+ } else if (/^(忘掉|忘记|别记)/.test(text)) {+ const target = /待办/.test(text) ? e2 : !e1.hidden ? e1 : e2;+ if (target.hidden) await reply("目前没有可以忘掉的记忆。");+ else { await reply("好,已经忘掉了。"); await drop(target); }+ } else if (/^(记住|记一下|帮我记)/.test(text)) {+ await remember(text.replace(/^(记住|记一下|帮我记)[::,,\s]*/, "").replace(/[。.]$/, ""));+ } else {+ await reply("收到。想让我记住什么,就说「记住……」。");+ }+ busy = false;+}++async function remember(content) {+ const r = await reply(content === "回答尽量简短,结论放在最前面" ? "记下了。以后先说结论,尽量简短。" : `记下了:${content}。`);+ // 回复下面冒出「已写入记忆」,然后飞进右边的记忆列表+ const chip = document.createElement("span");+ chip.style.cssText = "display: inline-flex; align-items: center; gap: 6px; height: 26px; padding: 0 10px; border-radius: 999px; background: rgba(215,255,0,.10); box-shadow: inset 0 0 0 1px rgba(215,255,0,.30); color: #d7ff00; font-size: 12px";+ chip.innerHTML = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 4h14v16l-7-4-7 4z"/></svg>已写入记忆';+ r.wrap.append(chip);+ P.enter(chip, "pop");+ await P.wait(500);+ await P.flyTo(chip, mem, 700);+ show(e1, content);+ mem.classList.add("spot");+ setTimeout(() => mem.classList.remove("spot"), 3200);+ if (done) return;+ done = true;+ P.lastMessage("记下了。以后先说结论…");+ P.stepDone(5, "让它记住你", head);+ await P.wait(600);+ P.coach(coach, () => stage("B"));+ // 回合结束后自动整理:又记下一条+ await P.wait(2600);+ show(e2);+ P.toast("自动整理了一条记忆", "每天的待办记在「今日待办.md」");+}diff --git a/anymodelbot_design/onboarding/js/page-model.js b/anymodelbot_design/onboarding/js/page-model.jsnew file mode 100644index 0000000..85bd3d1--- /dev/null+++ b/anymodelbot_design/onboarding/js/page-model.js@@ -0,0 +1,143 @@+// 02 换个模型:模型按钮在呼吸 → 点开选择器(按厂商折叠,可展开)→ 选一个 → 按钮上的名字换掉、对话里留一行说明 → 第 2 步完成+import * as P from "./proto.js";++P.init({ progress: 1 });+const { $, $$ } = P;+const picker = $("#picker"), chip = $("#chip"), coach = $("#coach"), arrow = $("#arrow"), log = $("#log");+const head = P.headFace();+let model = "claude-sonnet-5-5", done = false, busy = false;++const FAMILY = {+ OpenAI: [["gpt-6.1-terra", "1.05M", ["视觉", "工具", "推理"], "$0.08 / $0.40"], ["gpt-5.6-sol", "1.05M", ["视觉", "工具", "推理"], "$0.40 / $2.40"]],+ Google: [["gemini-3.8-flash", "1M", ["视觉", "工具"], "$0.23 / $1.13"]],+ DeepSeek: [["deepseek-v4-flash", "1M", ["工具", "推理"], "$0.26 / $0.77"]],+};+const MONO = "font-family: 'Geist Mono', ui-monospace, monospace";+const tag = (t) => `<span style="padding: 0 6px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18)">${t}</span>`;+const rowHtml = ([id, ctx, caps, price]) => `<button type="button" role="option" aria-selected="false" data-model="${id}" style="display: flex; flex-direction: column; align-items: stretch; gap: 2px; width: 100%; padding: 8px 10px 8px 22px; border-radius: 10px; text-align: left">+ <span style="${MONO}; font-size: 13px">${id}</span>+ <span style="display: flex; flex-wrap: wrap; align-items: center; gap: 6px; color: #a1a1aa; font-size: 11.5px"><span style="${MONO}">${ctx}</span>${caps.map(tag).join("")}<span style="flex: 1"></span><span style="${MONO}">${price}</span></span>+</button>`;++// 每一行记下自己是哪个模型+$$('[role="option"]', picker).forEach((b) => {+ b.dataset.model ??= $$("span", b).map((s) => s.textContent.trim()).find((x) => /^(claude|gpt|gemini|deepseek|grok|kimi)/.test(x));+});++// —— 引导卡片的三段 ——+const kick = $("#c-kick");+function stage(s) {+ const st = coach.style, a = arrow.style;+ if (s === "B") {+ Object.assign(st, { right: "440px", bottom: "64px" });+ Object.assign(a, { right: "-7px", bottom: "34px", boxShadow: "1px -1px 0 rgba(255,255,255,.18)" });+ } else {+ Object.assign(st, { right: "0px", bottom: "calc(100% + 20px)" });+ Object.assign(a, { right: "112px", bottom: "-7px", boxShadow: "1px 1px 0 rgba(255,255,255,.18)" });+ }+ const t = $("#c-title"), b = $("#c-body"), l = $("#c-list");+ if (s === "A") {+ t.textContent = "换个模型";+ b.textContent = "一个账户就能用 GPT、Claude、Gemini 等模型。先点输入框右下角的模型名。";+ l.hidden = true;+ } else if (s === "B") {+ t.textContent = "挑一个就换好了";+ b.textContent = "试试展开 OpenAI,换成 gpt-6.1-terra。";+ l.hidden = false;+ } else {+ t.textContent = "换好了";+ b.textContent = `现在小蓝用的是 ${model},只对这段对话生效。问它一句试试,或者继续下一步。`;+ l.hidden = true;+ if (!$("#c-badge")) kick.insertAdjacentHTML("beforeend", `<span id="c-badge" style="display: inline-flex; align-items: center; gap: 4px; height: 22px; padding: 0 8px; border-radius: 999px; background: #d7ff00; color: #161a00; ${MONO}; font-size: 11px; letter-spacing: 0">${P.ICON.check}完成</span>`);+ }+}+setTimeout(() => P.coach(coach, () => stage("A")), 500);+$("#c-later").addEventListener("click", () => P.leave(coach));++// —— 选择器 ——+function open() {+ chip.classList.remove("spot");+ chip.setAttribute("aria-expanded", "true");+ $("#chip-chev").style.transform = "rotate(180deg)";+ P.enter(picker, "pop");+ $('input[type="search"]', picker).focus();+ if (!done) P.coach(coach, () => stage("B"));+}+async function close() {+ chip.setAttribute("aria-expanded", "false");+ $("#chip-chev").style.transform = "";+ await P.leave(picker);+}+chip.addEventListener("click", () => (picker.hidden ? open() : close()));+addEventListener("pointerdown", (e) => { if (!picker.hidden && !picker.contains(e.target) && !chip.contains(e.target)) close(); });+addEventListener("keydown", (e) => e.key === "Escape" && !picker.hidden && close());++// 厂商分组:展开时一行一行冒出来+picker.addEventListener("click", (e) => {+ const fam = e.target.closest("button[aria-expanded]");+ if (fam && picker.contains(fam)) return toggleFamily(fam);+ const opt = e.target.closest('[role="option"]');+ if (opt) pick(opt);+});+function rowsAfter(head) {+ const out = [];+ for (let n = head.nextElementSibling; n && n.getAttribute("role") === "option"; n = n.nextElementSibling) out.push(n);+ return out;+}+function toggleFamily(fam) {+ const name = $("span", fam).textContent.trim();+ const opening = fam.getAttribute("aria-expanded") !== "true";+ let rows = rowsAfter(fam);+ if (opening && !rows.length && FAMILY[name]) {+ fam.insertAdjacentHTML("afterend", FAMILY[name].map(rowHtml).join(""));+ rows = rowsAfter(fam);+ }+ rows.forEach((r, i) => (opening ? P.enter(r, "rise", i * 60) : (r.hidden = true)));+ fam.setAttribute("aria-expanded", String(opening));+ $("path", fam).setAttribute("d", opening ? "m6 15 6-6 6 6" : "m6 9 6 6 6-6");+}+$('input[type="search"]', picker).addEventListener("input", (e) => {+ const q = e.target.value.trim().toLowerCase();+ $$('[role="option"]', picker).slice(1).forEach((r) => (r.hidden = !!q && !r.dataset.model.includes(q)));+});++async function pick(opt) {+ model = opt.dataset.model || model;+ $$('[role="option"]', picker).forEach((r) => { r.setAttribute("aria-selected", String(r === opt)); r.style.background = r === opt ? "rgba(215,255,0,.14)" : ""; });+ await P.wait(160);+ await close();+ const label = $("#chip-label");+ label.textContent = model;+ P.enter(label, "swap");+ P.playShot(head, "poke");+ const note = document.createElement("p");+ note.style.cssText = "align-self: center; margin: 0; padding: 4px 12px; border-radius: 999px; background: rgba(255,255,255,.05); color: #a1a1aa; font: 12px var(--font-mono)";+ note.textContent = `已切换到 ${model} · 只对这段对话生效`;+ log.append(note);+ P.enter(note, "pop");+ if (!done) {+ done = true;+ P.stepDone(2, "换个模型", head);+ await P.wait(500);+ P.coach(coach, () => stage("C"));+ chat.set("用一句话介绍你自己");+ }+}++$("#set-default").addEventListener("click", () => P.toast("已设为小蓝的默认模型", model));++// —— 换了模型后问一句 ——+const chat = P.composer({ input: $("#input"), send: $("#send"), onSend: ask });+async function ask(text) {+ if (busy) return;+ busy = true;+ P.userBubble(log, text);+ P.setState(head, "thinking");+ const r = P.botReply(log);+ await P.wait(900);+ P.setState(head, "replying");+ await r.say(`现在是 ${model} 在回答你:我是住在你电脑里的小蓝,能聊、能写、能动手,还记得你交代过的事。`);+ r.done(`${model} · `);+ P.setState(head, "idle");+ busy = false;+}diff --git a/anymodelbot_design/onboarding/js/page-tips.js b/anymodelbot_design/onboarding/js/page-tips.jsnew file mode 100644index 0000000..d62cd69--- /dev/null+++ b/anymodelbot_design/onboarding/js/page-tips.js@@ -0,0 +1,45 @@+// 随用随教:卡片滚到才浮现;点「知道了」提示收起、变成「已读」,聚光停下;看到收尾横幅时机器人们一起打招呼+import * as P from "./proto.js";++P.init();+const { $, $$ } = P;++const cards = $$("main article, body > div article");+const banner = $$("section").pop();+[...cards, banner].forEach((el, i) => { el.classList.add("reveal"); el.style.setProperty("--d", `${(i % 3) * 90}ms`); });+const io = new IntersectionObserver((es) => es.forEach((e) => {+ if (!e.isIntersecting) return;+ e.target.classList.add("is-in");+ io.unobserve(e.target);+ if (e.target === banner) celebrate();+}), { threshold: 0.25 });+[...cards, banner].forEach((el) => io.observe(el));++const host = $("header .bot-face");+if (host) P.playShot(host, "hello");++// 「知道了」:提示收起,留一行「已读」+const READ = `<p class="pop" style="margin: 0; display: flex; align-items: center; gap: 8px; padding: 10px 12px; border-radius: 12px; background: rgba(111,217,155,.08); color: #6fd99b; font-size: 13px">${P.ICON.check}已读,之后不会再出现</p>`;+async function dismiss(btn, box) {+ const card = btn.closest("article");+ if (!P.reduce) await box.animate([{ opacity: 1, transform: "none" }, { opacity: 0, transform: "translateY(-6px) scale(.98)" }], { duration: 220, easing: "ease-in" }).finished;+ box.outerHTML = READ;+ $$('[style*="0 0 0 2px #d7ff00"]', card).forEach((el) => (el.style.boxShadow = "inset 0 0 0 1px rgba(255,255,255,.10)"));+ const f = $(".bot-face", card);+ if (f) P.playShot(f, "done");+}+$$("article button").forEach((b) => {+ const t = b.textContent.trim();+ if (t === "知道了") b.addEventListener("click", () => dismiss(b, b.closest('[style*="background: #101110; box-shadow: 0 0 0 1px"]')));+ else if (t === "好的" || t === "改为直接退出") b.addEventListener("click", () => { dismiss(b, b.closest('[role="dialog"]')); if (t !== "好的") P.toast("已改为:关闭窗口时直接退出"); });+ else if (t === "去设置审批") b.addEventListener("click", () => P.toast("打开 机器人设置 → 电脑操作 → 审批"));+});++// 收尾横幅:横幅浮现的同一帧机器人们一起弹出来(hello 是入场动画),随后挨个跳一下、撒一把彩带+function celebrate() {+ const faces = $$(".bot-face", banner);+ faces.forEach((f) => P.playShot(f, "hello"));+ faces.forEach((f, i) => setTimeout(() => P.playShot(f, "done"), 1900 + i * 160));+ setTimeout(() => P.confetti(banner, 60), 500);+}+$$("button", banner).forEach((b) => b.addEventListener("click", () => P.toast(b.textContent.includes("再养") ? "打开「新建机器人」" : "清单已收起", "原型演示")));diff --git a/anymodelbot_design/onboarding/js/page-weixin.js b/anymodelbot_design/onboarding/js/page-weixin.jsnew file mode 100644index 0000000..2306585--- /dev/null+++ b/anymodelbot_design/onboarding/js/page-weixin.js@@ -0,0 +1,114 @@+// 03 接到微信:① 点顶部名字 → 信息面板滑出 ② 点「微信」→「扫码登录」→ 二维码 + 扫描线 ③ 模拟扫码 → 已扫码 → 已连接 → 第 3 步完成+import * as P from "./proto.js";++P.init({ progress: 2 });+const { $, $$ } = P;+const panel = $("#panel"), capsule = $("#capsule"), coach = $("#coach"), arrow = $("#arrow");+const wx = $("#wx"), row = $("#wx-row"), body = $("#wx-body"), login = $("#wx-login"), badgeEl = $("#wx-badge");+const qrParts = ["#wx-qr", "#wx-hint", "#wx-demo", "#wx-actions"].map((s) => $(s));+const head = P.headFace();+const MONO = "font-family: 'Geist Mono', ui-monospace, monospace";+let timers = [], done = false;++// —— 渠道状态徽标 ——+const BADGE = {+ idle: ["未登录", "background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); color: #a1a1aa"],+ fetch: ["获取二维码…", "background: #101110; box-shadow: inset 0 0 0 1px rgba(255,255,255,.10); color: #a1a1aa"],+ wait: ["等待扫码", "background: rgba(215,255,0,.14); color: #d7ff00"],+ scanned: ["已扫码", "background: rgba(242,181,68,.14); color: #f2b544"],+ ok: ["已连接", "background: rgba(111,217,155,.12); color: #6fd99b"],+};+function badge(k) {+ const [text, css] = BADGE[k];+ badgeEl.style.cssText = `display: inline-flex; align-items: center; gap: 6px; height: 22px; padding: 0 9px; border-radius: 999px; ${MONO}; font-size: 11px; line-height: 22px; ${css}`;+ badgeEl.innerHTML = `${k === "ok" ? '<span aria-hidden="true" style="width: 6px; height: 6px; border-radius: 50%; background: #6fd99b"></span>' : ""}${text}`;+ P.enter(badgeEl, "pop");+}++// —— 引导卡片:① ② ③ 三步依次点亮,完成后换成完成态 ——+function marker(n) { $$(".mk").forEach((m) => (m.hidden = Number(m.dataset.mk) !== n)); const m = $(`.mk[data-mk="${n}"]`); if (m) P.enter(m, "pop"); }+function stage(n) {+ const st = coach.style, a = arrow.style;+ if (n === 1) {+ Object.assign(st, { left: "16px", right: "auto", top: "70px" });+ Object.assign(a, { left: "34px", right: "auto", top: "-7px", boxShadow: "-1px -1px 0 rgba(255,255,255,.18)" });+ } else {+ Object.assign(st, { left: "auto", right: "22px", top: "150px" });+ Object.assign(a, { left: "auto", right: "-7px", top: n === 3 ? "200px" : "120px", boxShadow: "1px -1px 0 rgba(255,255,255,.18)" });+ }+ $$("#c-list li").forEach((li) => (li.style.opacity = Number(li.dataset.s) === n ? "1" : ".42"));+ if (n === 4) {+ $("#c-title").textContent = "小蓝已经在微信里了";+ $("#c-body").textContent = "在微信里给它发条消息试试:同一个机器人,同一份记忆。";+ $("#c-list").hidden = true;+ if (!$("#c-badge")) $("#c-kick").insertAdjacentHTML("beforeend", `<span id="c-badge" style="display: inline-flex; align-items: center; gap: 4px; height: 22px; padding: 0 8px; border-radius: 999px; background: #d7ff00; color: #161a00; ${MONO}; font-size: 11px; letter-spacing: 0">${P.ICON.check}完成</span>`);+ marker(0);+ } else marker(n);+}+marker(1);+setTimeout(() => P.coach(coach, () => stage(1)), 500);+$("#c-later").addEventListener("click", () => P.leave(coach));++// ① 打开信息面板+function togglePanel() {+ if (!panel.hidden) { panel.hidden = true; return; }+ panel.hidden = false;+ if (!P.reduce) panel.animate([{ transform: "translateX(36px)", opacity: 0 }, { transform: "none", opacity: 1 }], { duration: 460, easing: "cubic-bezier(.16,1,.3,1)" });+ capsule.style.boxShadow = "inset 0 0 0 1px rgba(255,255,255,.18)";+ capsule.style.background = "rgba(255,255,255,.08)";+ capsule.setAttribute("aria-pressed", "true");+ if (!done && body.hidden) { wx.classList.add("spot"); P.coach(coach, () => stage(2)); }+}+capsule.addEventListener("click", togglePanel);+$("#panel-btn").addEventListener("click", togglePanel);++// ② 展开微信那一行 → 扫码登录+row.addEventListener("click", () => {+ const open = body.hidden;+ row.setAttribute("aria-expanded", String(open));+ if (!open) { body.hidden = true; return; }+ P.enter(body, "rise");+ if (!done && login.hidden === false) { wx.classList.remove("spot"); login.classList.add("spot"); }+});+login.addEventListener("click", async () => {+ login.hidden = true;+ login.classList.remove("spot");+ badge("fetch");+ await P.wait(700);+ qrParts.forEach((el, i) => P.enter(el, i ? "fade-in" : "pop", i * 90));+ $("#wx-scan").hidden = false;+ badge("wait");+ P.coach(coach, () => stage(3));+ // 演示:几秒后自动模拟扫码 → 手机上确认+ timers = [setTimeout(scanned, 4200), setTimeout(connected, 6600)];+});+function scanned() {+ $("#wx-scan").hidden = true;+ P.enter($("#wx-scanned"), "pop");+ badge("scanned");+ P.setState(head, "waiting");+}+$("#wx-cancel").addEventListener("click", () => {+ timers.forEach(clearTimeout);+ qrParts.forEach((el) => (el.hidden = true));+ $("#wx-scanned").hidden = true;+ P.setState(head, "idle");+ login.hidden = false;+ badge("idle");+ P.coach(coach, () => stage(2));+});++// ③ 已连接+async function connected() {+ done = true;+ qrParts.forEach((el) => (el.hidden = true));+ P.enter($("#wx-done"), "rise");+ badge("ok");+ P.setState(head, "idle");+ P.confetti(badgeEl, 36);+ P.playShot(head, "love");+ P.stepDone(3, "把小蓝接到微信");+ P.lastMessage("微信已连接");+ await P.wait(600);+ P.coach(coach, () => stage(4));+}diff --git a/anymodelbot_design/onboarding/js/proto.js b/anymodelbot_design/onboarding/js/proto.jsnew file mode 100644index 0000000..147b3a3--- /dev/null+++ b/anymodelbot_design/onboarding/js/proto.js@@ -0,0 +1,313 @@+// 原型的公共部分:机器人、翻页条、左下角清单与进度、吐司、彩带、流式打字、引导卡片的进出场。+// 每页的脚本(page-*.js)只写自己的流程,用这里的小工具拼起来。+import { mountEyes, playShot, setState, say } from "./eyes.js";+import { mountFaces } from "./bots.js";++export { playShot, setState, say };+export const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches;+export const $ = (s, r = document) => r.querySelector(s);+export const $$ = (s, r = document) => [...r.querySelectorAll(s)];+export const wait = (ms) => new Promise((r) => setTimeout(r, reduce ? Math.min(ms, 80) : ms));++export const PAGES = ["Main.html", "Step2-Model.html", "Step3-Weixin.html", "Step4-Hands.html", "Step5-Memory.html", "Step6-Media.html", "Tips.html"];+export const STEPS = [+ ["跟小蓝打个招呼", "Main.html"],+ ["换个模型", "Step2-Model.html"],+ ["把小蓝接到微信", "Step3-Weixin.html"],+ ["让它动手做件事", "Step4-Hands.html"],+ ["让它记住你", "Step5-Memory.html"],+ ["生成一张图", "Step6-Media.html"],+];++const ICON = {+ check: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" class="tick" aria-hidden="true"><path d="m5 12 5 5 9-10"/></svg>',+ trash: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"/></svg>',+ spark: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5 18 18M6 18l2.5-2.5M15.5 8.5 18 6"/></svg>',+};+export { ICON };++// —— 机器人的台词(戳一下会说话;同官网 i18n 的 quips) ——+const QUIPS = {+ blue: { poke: ["收到,信号满格。", "在呢在呢。", "戳一下就算已读了啊。"], love: "天线要冒火花了!", dizzy: "信号……丢……了……", pet: "滋滋——幸福满格。" },+ yellow: { poke: ["哎呀,被发现了~", "亲,请问有什么可以帮您?", "戳脸要收费的哦~"], love: "脸红了,脸红了!", dizzy: "星星……在转圈圈……", pet: "再摸摸~这里这里~" },+ green: { poke: ["别戳,我在长个子。", "光合作用 +1。", "已记入日报:被戳一次。"], love: "被你戳得发芽了。", dizzy: "叶子……打结了……", pet: "好舒服,又长高了一毫米。" },+ red: { poke: ["嘘,正放到副歌。", "别吵,在编译。", "这个 bug 是你放的吧?"], love: "行吧,摘一边耳机听你说。", dizzy: "Segmentation fault (core dumped)", pet: "节拍对了,继续。" },+ purple: { poke: ["灵感 +1。", "这一下可以写进诗里。", "别急,宝石还在结晶。"], love: "好了好了,给你写首诗。", dizzy: "灵感……碎了一地……", pet: "这手感,值得一个比喻。" },+ orange: { poke: ["护目镜被你戳歪了!", "Hola!Bonjour!你好!", "正在搜索:是谁在戳我"], love: "发现新大陆:你!", dizzy: "地图……拿反了……", pet: "此处风景甚好,标记一下。" },+ wake: ["我没睡!我在思考。", "嗯?刚才谁在打呼?", "在的在的,随时待命!"],+};++// —— 左下角「上手清单」:进度格、计数、点开的浮层 ——+let progress = 0;+const pillEl = () => $$("aside a, aside button").find((e) => e.textContent.includes("上手清单"));+const segsOf = (pill) => $$('span[aria-hidden="true"] > span', pill);+const countOf = (pill) => $$("span", pill).find((s) => !s.children.length && /\d+ \/ 6/.test(s.textContent));++function paintProgress(n, animate) {+ const pill = pillEl();+ if (!pill) return;+ segsOf(pill).forEach((s, i) => {+ const on = i < n;+ s.style.background = on ? "#d7ff00" : "rgba(255,255,255,.16)";+ if (animate && on && i >= progress) {+ s.classList.remove("seg-on");+ void s.offsetWidth;+ s.style.animationDelay = `${(i - progress) * 90}ms`;+ s.classList.add("seg-on");+ }+ });+ const c = countOf(pill);+ if (c) {+ c.innerHTML = animate ? `<span class="roll">${n}</span> / 6` : `${n} / 6`;+ }+ if (animate) {+ pill.classList.remove("bump");+ void pill.offsetWidth;+ pill.classList.add("bump");+ }+}+export function setProgress(n, { animate = true } = {}) {+ paintProgress(n, animate);+ progress = n;+}++let pop = null;+function closeChecklist() {+ if (!pop) return;+ const p = pop;+ pop = null;+ p.classList.add("is-out");+ setTimeout(() => p.remove(), 200);+}+function openChecklist(pill) {+ if (pop) return closeChecklist();+ const here = location.pathname.split("/").pop() || "Main.html";+ const items = STEPS.map(([t, href], i) => {+ const done = i < progress, cur = i === progress;+ return `<li><a href="${href}" class="${done ? "done" : cur ? "cur" : ""}"${href === here ? ' aria-current="page"' : ""}>+ <span class="n">${done ? ICON.check : i + 1}</span><span class="t">${t}</span>${cur ? '<span class="go">继续 →</span>' : ""}</a></li>`;+ }).join("");+ pop = document.createElement("div");+ pop.className = "cl-pop";+ pop.setAttribute("role", "dialog");+ pop.setAttribute("aria-label", "上手清单");+ pop.innerHTML = `<div style="display:flex;align-items:baseline;justify-content:space-between;gap:12px">+ <h3>上手清单</h3><span style="font:12px var(--font-mono);color:var(--lime)">${progress} / 6</span></div>+ <div aria-hidden="true" style="display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:4px;margin-top:10px">+ ${STEPS.map((_, i) => `<span style="height:4px;border-radius:2px;background:${i < progress ? "var(--lime)" : "var(--line)"}"></span>`).join("")}</div>+ <ol>${items}</ol>+ <p style="margin:10px 4px 0;color:var(--text-2);font-size:12.5px">${progress >= 6 ? "全部完成!这个入口之后会自动收起。" : "做完一项会自动打勾,不用回来点。"}</p>`;+ document.body.append(pop);+ const r = pill.getBoundingClientRect();+ pop.style.left = `${Math.max(12, r.left)}px`;+ pop.style.bottom = `${innerHeight - r.top + 10}px`;+}++// —— 翻页条 ——+function mountNav() {+ const here = location.pathname.split("/").pop();+ const i = PAGES.indexOf(here);+ if (i < 0) return;+ const prev = i > 0 ? PAGES[i - 1] : "index.html";+ const next = i + 1 < PAGES.length ? PAGES[i + 1] : "index.html";+ const nav = document.createElement("nav");+ nav.className = "pv-nav";+ nav.setAttribute("aria-label", "预览导航");+ nav.innerHTML = `<a href="${prev}" aria-label="上一张">‹</a><a href="index.html">目录</a><span class="num">${i + 1} / ${PAGES.length}</span>+ <button type="button" title="从头再演示一遍" aria-label="重播">↻</button><a href="${next}" aria-label="下一张">›</a>`;+ nav.querySelector("button").addEventListener("click", () => location.reload());+ document.body.append(nav);+ addEventListener("keydown", (e) => {+ if (e.target.closest("input, textarea")) return;+ if (e.key === "ArrowLeft") location.href = prev;+ if (e.key === "ArrowRight") location.href = next;+ });+}++// —— 吐司与彩带 ——+let toasts = null;+export function toast(text, sub = "") {+ toasts ??= Object.assign(document.createElement("div"), { className: "toasts" });+ if (!toasts.isConnected) document.body.append(toasts);+ const t = document.createElement("div");+ t.className = "toast";+ t.setAttribute("role", "status");+ t.innerHTML = `<span class="toast__ic">${ICON.check}</span><span>${text}${sub ? ` <span class="toast__sub">· ${sub}</span>` : ""}</span>`;+ toasts.append(t);+ setTimeout(() => { t.classList.add("is-out"); setTimeout(() => t.remove(), 260); }, 2800);+}++const CONFETTI = ["#d7ff00", "#e9ff66", "#6dd4fb", "#ffc21a", "#2ee88a", "#ff7aa8", "#c24dff", "#fafaf7"];+export function confetti(from, count = 46) {+ if (reduce) return;+ const r = from instanceof Element ? from.getBoundingClientRect() : { left: innerWidth / 2, top: innerHeight / 3, width: 0, height: 0 };+ const x0 = r.left + r.width / 2, y0 = r.top + r.height / 2;+ const layer = Object.assign(document.createElement("div"), { className: "confetti" });+ layer.setAttribute("aria-hidden", "true");+ document.body.append(layer);+ for (let i = 0; i < count; i++) {+ const p = document.createElement("i");+ p.style.background = CONFETTI[i % CONFETTI.length];+ p.style.left = `${x0}px`;+ p.style.top = `${y0}px`;+ if (i % 3 === 0) p.style.borderRadius = "50%";+ layer.append(p);+ const a = (Math.random() * 2 - 1) * Math.PI * 0.55 - Math.PI / 2, v = 160 + Math.random() * 260;+ const dx = Math.cos(a) * v, dy = Math.sin(a) * v;+ p.animate([+ { transform: "translate(-50%,-50%) rotate(0deg) scale(1)", opacity: 1 },+ { transform: `translate(${dx}px, ${dy}px) rotate(${Math.random() * 540}deg) scale(1)`, opacity: 1, offset: 0.45 },+ { transform: `translate(${dx * 1.2}px, ${dy + 320 + Math.random() * 200}px) rotate(${Math.random() * 900}deg) scale(.6)`, opacity: 0 },+ ], { duration: 1500 + Math.random() * 900, easing: "cubic-bezier(.2,.7,.3,1)", fill: "forwards" });+ }+ setTimeout(() => layer.remove(), 2600);+}++// —— 文字:流式打出、数字滚动 ——+/** 像模型回复一样逐字出现(中文一次 1–2 个字,标点处稍停) */+export async function stream(el, text, cps = 34) {+ if (reduce) { el.textContent = text; return; }+ el.textContent = "";+ el.classList.add("caret");+ for (let i = 0; i < text.length; ) {+ const n = 1 + (Math.random() < 0.4 ? 1 : 0);+ el.textContent = text.slice(0, (i += n));+ const ch = text[i - 1];+ await new Promise((r) => setTimeout(r, (1000 / cps) * n * (",。!?;".includes(ch) ? 4 : 1)));+ }+ el.classList.remove("caret");+}+export function countTo(el, from, to, ms = 900, fmt = (v) => `$${v.toFixed(2)}`) {+ if (reduce) { el.textContent = fmt(to); return; }+ const t0 = performance.now();+ const tick = (t) => {+ const k = Math.min(1, (t - t0) / ms), e = 1 - (1 - k) ** 3;+ el.textContent = fmt(from + (to - from) * e);+ if (k < 1) requestAnimationFrame(tick);+ };+ requestAnimationFrame(tick);+}++// —— 进出场 ——+export function enter(el, cls = "rise", delay = 0) {+ if (!el) return;+ el.hidden = false;+ el.classList.remove(cls);+ void el.offsetWidth;+ el.style.setProperty("--d", `${delay}ms`);+ el.classList.add(cls);+}+export async function leave(el, cls = "coach-out") {+ if (!el || el.hidden) return;+ el.classList.add(cls);+ await wait(210);+ el.hidden = true;+ el.classList.remove(cls);+}+/** 引导卡片换一段内容:先淡出,换好再从下面浮上来;卡片里的主持机器人同时弹出来打招呼。+ * hello 是入场动画(从缩放 0 弹出),只能在头像出现的同一帧播;对已经看得见的头像播会先消失再弹回来,看起来像闪了一下。+ * 已经在场的头像要表示「好的 / 完成」用 done 或 poke。 */+export async function coach(card, update) {+ if (!card.hidden) await leave(card);+ update?.(card);+ enter(card, "coach-in");+ const f = $(".bot-face", card);+ if (f) playShot(f, "hello");+}+/** 一个元素的「影子」飞到另一个元素上,再消失:清单收进左下角、记忆飞进面板 */+export function flyTo(from, to, ms = 700) {+ const a = from.getBoundingClientRect(), b = to.getBoundingClientRect();+ if (reduce || !a.width) return Promise.resolve();+ const ghost = from.cloneNode(true);+ Object.assign(ghost.style, { position: "fixed", left: `${a.left}px`, top: `${a.top}px`, width: `${a.width}px`, height: `${a.height}px`, margin: "0", zIndex: "1300", pointerEvents: "none", transformOrigin: "0 0" });+ document.body.append(ghost);+ const sx = b.width / a.width, sy = b.height / a.height;+ const anim = ghost.animate([+ { transform: "none", opacity: 1 },+ { transform: `translate(${b.left - a.left}px, ${b.top - a.top}px) scale(${sx}, ${sy})`, opacity: 0.15 },+ ], { duration: ms, easing: "cubic-bezier(.6,0,.2,1)", fill: "forwards" });+ return anim.finished.then(() => ghost.remove());+}++/** 用户气泡:插到对话列里,从右下角弹出来 */+export function userBubble(log, text) {+ const b = document.createElement("div");+ b.style.cssText = "align-self: flex-end; max-width: 80%; padding: 10px 16px; border-radius: 18px; background: rgba(255,255,255,.07)";+ b.textContent = text;+ log.append(b);+ enter(b, "bubble-in");+ return b;+}+/** 机器人回复:上面一行工作状态(思考中 / 正在回复 N 秒 / 用时 N 秒),下面是正文 */+export function botReply(log) {+ const wrap = document.createElement("div");+ wrap.style.cssText = "display: flex; flex-direction: column; gap: 6px; align-items: flex-start";+ wrap.innerHTML = `<span class="wl" style="font: 11.5px var(--font-mono); color: var(--text-2)">思考中<span class="dots"><i></i><i></i><i></i></span></span><p class="tx" style="margin: 0; line-height: 1.75"></p>`;+ log.append(wrap);+ enter(wrap, "fade-in");+ const wl = $(".wl", wrap), tx = $(".tx", wrap), t0 = performance.now();+ let timer = 0;+ const secs = () => Math.max(1, Math.round((performance.now() - t0) / 1000));+ return {+ wrap,+ async say(text, cps) {+ wl.textContent = `正在回复 ${secs()} 秒`;+ timer = setInterval(() => (wl.textContent = `正在回复 ${secs()} 秒`), 1000);+ await stream(tx, text, cps);+ },+ done(extra = "") {+ clearInterval(timer);+ wl.textContent = `${extra}用时 ${secs() + 2} 秒`;+ },+ };+}++/** 输入框:Enter 发送(Shift+Enter 换行);有字时发送键变亮并轻轻跳 */+export function composer({ input, send, onSend }) {+ const sync = () => send.classList.toggle("send-ready", !!input.value.trim());+ const fire = () => {+ const v = input.value.trim();+ if (!v) return;+ input.value = "";+ sync();+ onSend(v);+ };+ input.addEventListener("input", sync);+ input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); fire(); } });+ send.addEventListener("click", fire);+ sync();+ return { set(v) { input.value = v; sync(); }, sync, focus: () => input.focus() };+}++/** 页面入口:机器人动起来、翻页条、左下角清单 */+export function init({ progress: n = 0 } = {}) {+ const q = Object.assign(document.createElement("script"), { type: "application/json", id: "amb-quips", textContent: JSON.stringify(QUIPS) });+ document.head.append(q);+ mountFaces();+ mountEyes();+ mountNav();+ setProgress(n, { animate: false });+ const pill = pillEl();+ pill?.addEventListener("click", (e) => { e.preventDefault(); openChecklist(pill); });+ addEventListener("pointerdown", (e) => { if (pop && !pop.contains(e.target) && !pillEl()?.contains(e.target)) closeChecklist(); });+ addEventListener("keydown", (e) => e.key === "Escape" && closeChecklist());+ // 各页在 init() 之后同一个任务里挂好出场动画,下一帧才开始画,所以这里就可以显示了+ document.body.classList.add("ready");+}++/** 完成一步:进度 +1、吐司、机器人开心一下 */+export function stepDone(n, title, faceEl) {+ setProgress(n);+ toast(`第 ${n} 步完成`, title);+ if (faceEl) playShot(faceEl, "done");+}+export const pill = pillEl;+/** 侧栏左下角的余额数字 */+export const balanceEl = () => $$("span", $$("aside button").find((e) => e.textContent.includes("我的账户"))).find((s) => s.textContent.startsWith("$"));+/** 顶栏胶囊里的机器人 */+export const headFace = () => $("main header .bot-face");+/** 侧栏机器人那一行的最后一条消息 */+export function lastMessage(text) {+ const row = $("aside a[href='Main.html'] span span:last-child");+ if (row) row.textContent = text;+}diff --git a/docs/development.md b/docs/development.mdindex 7620dc5..6fa2367 100644--- a/docs/development.md+++ b/docs/development.md@@ -23,15 +23,19 @@ src/web/ 管理界面服务(JSON API + 流式对话 SSE)cli/ init 首次设置向导、weixin-loginmodelflare.ts Modelflare 线路、密钥校验(GET /v1/models)、模型路由与归因+ guide.ts 上手清单的进度+ i18n/ 服务端多语言:报错、状态文字、托盘菜单、机器人发出的系统消息(messages/<命名空间>.ts)diagnostics.ts 故障排查:探测、日志尾部、脱敏的诊断报告main.ts 命令行入口electron/ 桌面版主进程(启动器 + 托盘)ui/ 管理界面(Preact + htm,无构建步骤)design/ 设计系统:tokens/、base/、components/、机器人形象 bots/+ locales/ 界面文案:zh-CN/ 与 en/,每个命名空间一个文件css/ lib/ components/ screens/ assets/ main.jsdsh-runtime/ DSH 代理运行时的依赖清单与 AnyModelBot 插件(plugins/)scripts/ setup / build-magpie / fetch-cua-driver / prepare-dsh / bundle-dsh / electron-smoke / check-readme 等vendor/ git 子模块:magpie(构建时编译)、deepseek-harness、kimi-computer-use+site/ 官网(Astro 静态站),说明见 site/README.mddocs/ 开发文档、隐私说明、README 素材(docs/assets/)```@@ -113,6 +117,10 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令- 侧栏:机器人列表(头像 + 名称 + 最近一条消息),+ 新建,右键 重命名 / 删除;左下角账户按钮打开设置(`⌘/Ctrl+,`)。- 对话页:顶部悬浮的机器人名称胶囊打开信息面板(`⌘/Ctrl+⇧+I`:渠道、使用请求、待审批、记忆、最近会话,⚙ 进机器人设置);回复流式显示(Markdown、代码块一键复制),可随时停止(`Esc`);审批与提问以卡片形式出现在对话里;向上翻阅时不会被拉回底部。- 命令面板 `⌘/Ctrl+K`;外观(跟随系统 / 浅色 / 深色)在 设置 → 常规。+- 语言:简体中文 / English,设置 → 常规 → 语言(引导页右上角、命令面板里也能切),默认跟随系统(系统语言不是中文也不是英文时用英文)。偏好存在 config.json 的 `ui.lang`,托盘菜单、服务端报错和状态文字、机器人发到微信 / 飞书的系统消息(`/help`、审批提示等)都跟着它;命令行 / Docker 下"跟随系统"看 `AMB_LANG`,再看 `LC_ALL` / `LANG`,都没有时用简体中文。日志、发给模型的提示词和用户自己起的机器人名不翻译。+ - 界面文案在 `ui/locales/<语言>/<命名空间>.js`,代码里写 `t("命名空间.键", { 参数 })`(`ui/lib/i18n.js`);服务端在 `src/i18n/messages/<命名空间>.ts`,键有类型检查。每个界面请求带 `x-amb-lang`,服务端在这个请求里用同一种语言回话。+ - 新增文案两种语言都要写;`node scripts/i18n-check.mjs [文件…]` 检查界面代码里有没有漏掉的中文、用到的键在不在、中英词典是否对齐(`npm test` 里的 `test/i18n.unit.test.ts` 也会查)。确需留在代码里的中文(字体名、匹配中文输入的正则)在那一行写 `// i18n-ignore`。+- 上手清单(新手引导):对话空状态里是 6 步清单——打招呼、换模型、接到微信、让它动手、让它记住你、生成一张图。最后一步在引导里只放预置演示,不管账户有没有图片 / 视频模型都一样:同样先确认、再生成、出图,但不发给机器人、不调用模型、不扣费,图是客户端自带的 `ui/assets/guide-demo.svg`。目的是教会怎么操作,不替用户花钱;之后真的让它画图、收到图片也会算完成这一步。点「发送这句」直接试,点「带我去」或侧栏左下角的清单入口,会有一张引导卡片指着要点的地方(那里亮一圈)。做完自动打勾:对话里有了回复、换了模型、收到文件 / 图片、渠道连上、记忆写入;进度存在 config.json 的 `ui.guide`(接口 `/amb/api/guide`),老用户已经做过的步骤会自动算完成。清单可以收起到左下角或「不再显示」,设置 → 常规 → 上手清单 可以重新开始。- 视觉:中性色与组件改编自 magpie 的界面(MIT),强调色为 Modelflare 荧光黄绿 `#d7ff00`。设计系统说明见 `ui/design/README.md`。## 人设与提示词diff --git a/docs/development_en.md b/docs/development_en.mdindex 8b2fd01..20a8330 100644--- a/docs/development_en.md+++ b/docs/development_en.md@@ -23,15 +23,19 @@ src/web/ console server (JSON API + streaming chat over SSE)cli/ init first-run wizard, weixin-loginmodelflare.ts Modelflare routes, key validation (GET /v1/models), model routing and attribution+ guide.ts onboarding checklist progress+ i18n/ server-side i18n: errors, status text, tray menu, system messages from bots (messages/<namespace>.ts)diagnostics.ts troubleshooting: probes, log tail, redacted diagnostics reportmain.ts command-line entry pointelectron/ desktop main process (launcher + tray)ui/ console UI (Preact + htm, no build step)design/ design system: tokens/, base/, components/, bot characters bots/+ locales/ UI strings: zh-CN/ and en/, one file per namespacecss/ lib/ components/ screens/ assets/ main.jsdsh-runtime/ dependency manifest for the DSH agent runtime and AnyModelBot plugins (plugins/)scripts/ setup / build-magpie / fetch-cua-driver / prepare-dsh / bundle-dsh / electron-smoke / check-readme and morevendor/ git submodules: magpie (compiled at build time), deepseek-harness, kimi-computer-use+site/ website (Astro static site); see site/README.mddocs/ development guide, privacy notes, README assets (docs/assets/)```@@ -113,6 +117,10 @@ Inside the container the console listens on 0.0.0.0, so token access is enforced- Sidebar: bot list (avatar + name + latest message), + New, right-click to rename / delete; the account button at the bottom-left opens Settings (`⌘/Ctrl+,`).- Chat screen: the floating bot-name pill at the top opens the info panel (`⌘/Ctrl+⇧+I`: channels, requests, pending approvals, memory, recent sessions; ⚙ opens bot settings). Replies stream in (Markdown, one-click copy for code blocks) and can be stopped at any time (`Esc`). Approvals and questions appear as cards in the chat. Scrolling up is never yanked back to the bottom.- Command palette `⌘/Ctrl+K`; appearance (system / light / dark) is in Settings → General.+- Language: 简体中文 / English, in Settings → General → Language (also at the top-right of the onboarding screen and in the command palette). It follows the system by default (English when the system language is neither Chinese nor English). The preference is stored in `ui.lang` in config.json; the tray menu, server error and status messages, and system messages bots send to WeChat / Feishu (`/help`, approval prompts, …) all follow it. On the command line / Docker, "System" means `AMB_LANG`, then `LC_ALL` / `LANG`, falling back to Simplified Chinese. Logs, prompts sent to the model and bot names users chose are not translated.+ - UI strings live in `ui/locales/<lang>/<namespace>.js` and are used as `t("namespace.key", { params })` (`ui/lib/i18n.js`); server strings live in `src/i18n/messages/<namespace>.ts` with type-checked keys. Every UI request carries `x-amb-lang`, and the server answers that request in the same language.+ - Add every new string in both languages. `node scripts/i18n-check.mjs [files…]` reports Chinese left in UI code, keys that don't exist, and zh / en dictionaries that are out of sync (`test/i18n.unit.test.ts` in `npm test` checks the same). Chinese that must stay in code (font names, regexes matching Chinese input) gets a `// i18n-ignore` on that line.+- Onboarding checklist: the empty chat state shows a six-step checklist — say hello, switch models, connect WeChat, let it do something, let it remember you, generate an image. The last step only plays a built-in demo inside the guide, whether or not the account has image / video models: it still confirms, generates and shows the image, but nothing is sent to the bot, no model is called and nothing is charged; the image is the bundled `ui/assets/guide-demo.svg`. The point is to teach the flow without spending the user's money; actually asking it to draw, or receiving an image later, also completes the step. "Send this" tries it directly; "Show me" or the checklist entry at the bottom-left of the sidebar shows a guide card pointing at the right control (highlighted with a ring). Steps tick themselves off: a reply in the chat, a model switch, a received file / image, a connected channel, a memory write. Progress is stored in `ui.guide` in config.json (API `/amb/api/guide`), and steps that existing users have already done count as complete. The checklist can be collapsed to the bottom-left or hidden for good, and Settings → General → Onboarding checklist starts it over.- Visuals: neutrals and components are adapted from magpie's UI (MIT); the accent is Modelflare's fluorescent yellow-green `#d7ff00`. The design system is described in `ui/design/README.md`.## Persona and promptsdiff --git a/electron/main.ts b/electron/main.tsindex cccad42..a171225 100644--- a/electron/main.ts+++ b/electron/main.ts@@ -5,9 +5,10 @@* - 窗口加载本机管理界面(每次启动生成随机令牌,其他本机程序/浏览器无法直接访问)* - 托盘:显示 / 开机自启 / 退出;关闭窗口=隐藏到托盘(可在设置 → 常规里改为退出);退出时干净关闭 magpie* - 设置页里的开机自启、缩放、打开数据目录经 core.desktop 回调到这里(同进程,无需 preload/IPC)+ * - 托盘菜单和对话框跟着应用语言(src/i18n):跟随系统时取系统首选语言,界面里换了语言托盘菜单立刻重建* CLI(npm start)与 Docker 走同一套 src/ 代码,本文件只做桌面外壳。*/-import { app, BrowserWindow, Menu, Tray, nativeImage, net, shell, dialog, safeStorage } from "electron";+import { app, BrowserWindow, Menu, Tray, nativeImage, nativeTheme, net, shell, dialog, safeStorage } from "electron";import crypto from "node:crypto";import fs from "node:fs";import path from "node:path";@@ -16,6 +17,7 @@ import { loadConfig } from "../src/config.js";import { App } from "../src/app.js";import { findAppRoot } from "../src/magpie/supervisor.js";import { initFileLog, logFilePath, logger, registerSecret, setConsoleLog } from "../src/log.js";+import { normalizeLang, onLangChange, setLangPref, setSystemLang, t } from "../src/i18n/index.js";const log = logger("desktop");const SMOKE = process.env.AMB_ELECTRON_SMOKE; // 冒烟测试:截图到该路径后退出@@ -47,6 +49,25 @@ function showWindow(): void {const PRODUCT = "AnyModelBot";const canAutostart = process.platform === "darwin" || process.platform === "win32";+// Windows:也不要系统标题栏,侧栏顶部那一行就是标题栏——左上角是应用图标 + 名称(Windows 的习惯;macOS 那里是红绿灯),+// 右上角由 Electron 画系统的最小化 / 最大化 / 关闭(Window Controls Overlay),贴住窗口的右上角,界面里最右的顶栏给它让位+// (界面在 Electron + Windows 下带 win-app,见 shell.css)。Linux 的窗口管理器各不相同,仍用系统标题栏。+// 叠层透明,高度 = 侧栏顶部那一行(--pane-gap 8 + --head-h 52),跟着页面缩放一起变;+// 符号颜色跟界面主题:主题存在界面的 localStorage 里,界面解析后经 core.desktop.setTitleBarTheme 告诉这里,在那之前先按系统主题猜。+// 底色虽然透明,RGB 也不能随便填:Electron 按底色的亮度挑悬停时那层灰(亮底 → 黑色、暗底 → 白色)+const TITLE_BAR_H = 60;+let titleBarDark = nativeTheme.shouldUseDarkColors;+function titleBarOverlay(): Electron.TitleBarOverlay {+ return {+ color: titleBarDark ? "rgba(0, 0, 0, 0)" : "rgba(255, 255, 255, 0)",+ symbolColor: titleBarDark ? "#ececec" : "#1a1a1a", // = --fg+ height: Math.round(TITLE_BAR_H * (core?.config.ui.zoom ?? 1)),+ };+}+function updateTitleBar(): void {+ if (isWin && win && !win.isDestroyed()) win.setTitleBarOverlay(titleBarOverlay());+}+function createWindow(): void {win = new BrowserWindow({width: 1200,@@ -57,9 +78,11 @@ function createWindow(): void {icon: windowIconPath(),show: !SMOKE,autoHideMenuBar: true,- // macOS:无标题栏,红绿灯嵌进侧栏顶部(界面在 Electron + Mac 下给它留位);其他系统用系统标题栏。- // 侧栏顶部先让出 --pane-gap(8)再放 52 高的顶栏,和主区顶栏同一条中线,所以红绿灯也比顶栏原来的位置低 8+ // macOS:无标题栏,红绿灯嵌进侧栏顶部(界面在 Electron + Mac 下给它留位)。+ // 侧栏顶部先让出 --pane-gap(8)再放 52 高的顶栏,和主区顶栏同一条中线,所以红绿灯也比顶栏原来的位置低 8。+ // Windows:无标题栏 + 窗口按钮叠层(见上面的 titleBarOverlay);Linux 用系统标题栏...(process.platform === "darwin" ? { titleBarStyle: "hiddenInset" as const, trafficLightPosition: { x: 16, y: 23 } } : {}),+ ...(isWin ? { titleBarStyle: "hidden" as const, titleBarOverlay: titleBarOverlay() } : {}),webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true },});const origin = new URL(entryUrl).origin;@@ -95,23 +118,24 @@ function buildTray(): void {const render = () =>tray!.setContextMenu(Menu.buildFromTemplate([- { label: `打开 ${PRODUCT}`, click: showWindow },- { label: "在浏览器中打开", click: () => void shell.openExternal(entryUrl) },+ { label: t("desktop.trayOpen", { product: PRODUCT }), click: showWindow },+ { label: t("desktop.trayOpenInBrowser"), click: () => void shell.openExternal(entryUrl) },{ type: "separator" },{- label: "开机自启",+ label: t("desktop.trayAutostart"),type: "checkbox",enabled: canAutostart,checked: canAutostart && app.getLoginItemSettings().openAtLogin,click: (item) => setAutostart(item.checked),},- { label: "打开数据目录", click: () => void shell.openPath(core!.config.dataDir) },+ { label: t("desktop.trayOpenDataDir"), click: () => void shell.openPath(core!.config.dataDir) },{ type: "separator" },- { label: "退出", click: () => app.quit() },+ { label: t("desktop.trayQuit"), click: () => app.quit() },]),);renderTray = render;render();+ onLangChange(render); // 界面里换了语言:托盘菜单跟着换tray.on("click", showWindow);}@@ -127,6 +151,9 @@ async function boot(): Promise<void> {// 尽早打开日志文件:配置读取失败、启动失败也能留下记录initFileLog(path.join(dataDir, "logs"));const config = loadConfig({ dataDir });+ // 语言:跟随系统时用系统的首选语言(不支持的语言用英文);偏好本身在 config.ui.lang+ setSystemLang(app.getPreferredSystemLanguages().map(normalizeLang).find(Boolean) ?? normalizeLang(app.getLocale()) ?? "en");+ setLangPref(config.ui.lang);// 桌面版:仅回环 + 每次启动随机令牌;端口沿用配置(默认 3600,被占用时自动换随机端口)config.ui.host = "127.0.0.1";if (!config.ui.token) config.ui.token = crypto.randomBytes(24).toString("base64url");@@ -135,7 +162,15 @@ async function boot(): Promise<void> {core.desktop = {autostart: () => ({ supported: canAutostart, on: canAutostart && app.getLoginItemSettings().openAtLogin }),setAutostart,- applyZoom: (z) => win?.webContents.setZoomFactor(z),+ applyZoom: (z) => {+ win?.webContents.setZoomFactor(z);+ updateTitleBar(); // 叠层高度跟着缩放(调用方已把 z 写进 config.ui.zoom)+ },+ setTitleBarTheme: (dark) => {+ if (dark === titleBarDark) return;+ titleBarDark = dark;+ updateTitleBar();+ },openDataDir: () => void shell.openPath(config.dataDir),openInBrowser: () => void shell.openExternal(entryUrl),openExternal: (url) => {@@ -149,7 +184,7 @@ async function boot(): Promise<void> {fetch: ((input: string | URL | Request, init?: RequestInit) => net.fetch(input instanceof URL ? input.href : input, init)) as typeof fetch,};await core.start();- if (!core.web) throw new Error("管理界面未启动");+ if (!core.web) throw new Error(t("desktop.uiNotStarted"));entryUrl = `${core.web.url.replace(/\/$/, "")}/?token=${encodeURIComponent(config.ui.token)}`;log.info(`数据目录:${dataDir}`);log.info(`管理界面:${core.web.url}`);@@ -194,7 +229,12 @@ process.on("uncaughtException", (e) => {if (Date.now() - lastErrorBox < 60_000 || !app.isReady()) return;lastErrorBox = Date.now();void dialog- .showMessageBox({ type: "error", title: PRODUCT, message: `${PRODUCT} 出错了`, detail: `${err?.message ?? String(e)}\n\n详细信息见日志:${logFilePath() ?? "(未启用)"}` })+ .showMessageBox({+ type: "error",+ title: PRODUCT,+ message: t("desktop.errorTitle", { product: PRODUCT }),+ detail: t("desktop.errorDetail", { message: err?.message ?? String(e), log: logFilePath() ?? t("desktop.logDisabled") }),+ }).catch(() => {});});process.on("unhandledRejection", (e) => log.warn(`unhandled rejection: ${(e as Error)?.stack || String(e)}`));@@ -229,7 +269,7 @@ if (!app.requestSingleInstanceLock()) {.then(boot).catch((e) => {log.error((e as Error).stack || String(e));- dialog.showErrorBox(`${PRODUCT} 启动失败`, (e as Error).message);+ dialog.showErrorBox(t("desktop.bootFailed", { product: PRODUCT }), (e as Error).message);app.exit(1);});}diff --git a/scripts/build-bot-avatars.py b/scripts/build-bot-avatars.pyindex 7beed97..99f80fa 100644--- a/scripts/build-bot-avatars.py+++ b/scripts/build-bot-avatars.py@@ -10,6 +10,8 @@4–7 上面四层各自的"发光部分"(红魔的灯带、紫钻的霓虹线),没有就是空的只用 numpy + Pillow: python3 scripts/build-bot-avatars.py+官网的 AVIF 版要从无损的精灵图编码(site/scripts/make-bot-avif.ts): python3 scripts/build-bot-avatars.py --out <目录> --png+ --out 改输出目录(默认 ui/design/bots),--png 另存一份无损 PNG几何(源图像素)和 ui/components/avatar.js 里的 BOT_CHARS 是同一套数,改一边要改另一边。"""import os@@ -173,6 +175,8 @@ def build(key, c):os.makedirs(OUT, exist_ok=True)path = os.path.join(OUT, key + ".webp")sheet.save(path, "WEBP", quality=QUALITY, alpha_quality=90, method=6)+ if PNG:+ sheet.save(os.path.join(OUT, key + ".png"))k = CELL / SIDEto = lambda x, y: (round((x - x0) * k / CELL * 100, 2), round((y - y0) * k / CELL * 100, 2))@@ -182,6 +186,16 @@ def build(key, c):f"top={to((t['stem'][0] + t['stem'][1]) / 2, t['cut'])}")+PNG = False+if __name__ == "__main__":- for key in sys.argv[1:] or CHARS:+ args = sys.argv[1:]+ if "--out" in args:+ i = args.index("--out")+ OUT = os.path.abspath(args[i + 1])+ del args[i:i + 2]+ if "--png" in args:+ PNG = True+ args.remove("--png")+ for key in args or CHARS:build(key, CHARS[key])diff --git a/scripts/i18n-check.mjs b/scripts/i18n-check.mjsnew file mode 100644index 0000000..d894ee9--- /dev/null+++ b/scripts/i18n-check.mjs@@ -0,0 +1,226 @@+#!/usr/bin/env node+// 界面多语言自检(test/i18n.unit.test.ts 也调这里的函数)。无第三方依赖。+//+// node scripts/i18n-check.mjs 检查全部界面代码+// node scripts/i18n-check.mjs ui/screens/chat.js ... 只查这几个文件(词典的对齐检查照做)+//+// 1. 界面代码(去掉注释后)不再出现中文:文案都应该进 ui/locales/。确实要留的(字体名、语言自称、+// 匹配中文输入的正则……)在那一行写 `// i18n-ignore`+// 2. 代码里 t("…") 用到的键在两种语言的词典里都有+// 3. zh-CN 与 en 的键一一对应;同一个键两边的 {占位符} 相同;复数文案两边都有 other+//+// 动态拼出来的键(t(`gateway.${state}`))查不到,写的时候配合 has() 兜底。++import fs from "node:fs";+import path from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");+export const LANGS = ["zh-CN", "en"];+const CJK = /[ -〿㐀-䶿一-鿿-]/;+/** 只给开发者看的页面(设计库展示页),不进多语言 */+const SKIP = new Set(["ui/design/gallery.js"]);++/** 界面代码:ui/ 下的 .js,去掉词典和第三方 */+export function uiFiles() {+ const out = [];+ const walk = (dir) => {+ for (const e of fs.readdirSync(path.join(ROOT, dir), { withFileTypes: true })) {+ const rel = `${dir}/${e.name}`;+ if (e.isDirectory()) {+ if (rel !== "ui/locales" && rel !== "ui/vendor") walk(rel);+ } else if (e.name.endsWith(".js") && !SKIP.has(rel)) out.push(rel);+ }+ };+ walk("ui");+ return out.sort();+}++/**+ * 去掉 JS 注释(换成空格,保留换行,行号不变)。认得字符串、模板字符串(含嵌套的 ${})和正则字面量,+ * 所以 "https://…" 和 /\/\// 不会被当成注释。正则的判断是启发式的(看前一个有效字符),界面代码够用。+ */+export function stripComments(src) {+ let out = "";+ let i = 0;+ const n = src.length;+ const stack = []; // 模板字符串里 ${ 的花括号深度+ let prev = ""; // 上一个非空白的代码字符,用来判断 / 是除号还是正则+ const blank = (s) => s.replace(/[^\n]/g, " ");+ const readString = (q) => {+ let j = i + 1;+ while (j < n && src[j] !== q) {+ if (src[j] === "\\") j++;+ else if (src[j] === "\n") break;+ j++;+ }+ out += src.slice(i, j + 1);+ i = j + 1;+ prev = q;+ };+ const readTemplate = () => {+ // i 指向 ` 或 }(从 ${} 回到模板)后的第一个字符+ let j = i;+ while (j < n) {+ if (src[j] === "\\") {+ j += 2;+ continue;+ }+ if (src[j] === "`") {+ out += src.slice(i, j + 1);+ i = j + 1;+ prev = "`";+ return;+ }+ if (src[j] === "$" && src[j + 1] === "{") {+ out += src.slice(i, j + 2);+ i = j + 2;+ stack.push(0);+ prev = "{";+ return;+ }+ j++;+ }+ out += src.slice(i);+ i = n;+ };+ while (i < n) {+ const c = src[i];+ const d = src[i + 1];+ if (c === "/" && d === "/") {+ const j = src.indexOf("\n", i);+ const end = j < 0 ? n : j;+ out += blank(src.slice(i, end));+ i = end;+ } else if (c === "/" && d === "*") {+ const j = src.indexOf("*/", i + 2);+ const end = j < 0 ? n : j + 2;+ out += blank(src.slice(i, end));+ i = end;+ } else if (c === '"' || c === "'") {+ readString(c);+ } else if (c === "`") {+ out += c;+ i++;+ readTemplate();+ } else if (c === "/" && (prev === "" || /[(,=:[!&|?{};+\-*%<>~^]/.test(prev) || /\b(return|typeof|case|in|of)$/.test(out.trimEnd()))) {+ // 正则字面量+ let j = i + 1;+ let cls = false;+ while (j < n && src[j] !== "\n") {+ if (src[j] === "\\") j++;+ else if (src[j] === "[") cls = true;+ else if (src[j] === "]") cls = false;+ else if (src[j] === "/" && !cls) break;+ j++;+ }+ j++;+ while (j < n && /[a-z]/i.test(src[j])) j++;+ out += src.slice(i, j);+ i = j;+ prev = "/";+ } else {+ if (stack.length && c === "{") stack[stack.length - 1]++;+ else if (stack.length && c === "}") {+ if (stack[stack.length - 1] === 0) {+ stack.pop();+ out += c;+ i++;+ readTemplate();+ continue;+ }+ stack[stack.length - 1]--;+ }+ out += c;+ if (!/\s/.test(c)) prev = c;+ i++;+ }+ }+ return out;+}++/** 去掉注释后仍含中文、且没标 i18n-ignore 的行 */+export function cjkLines(rel) {+ const src = fs.readFileSync(path.join(ROOT, rel), "utf8");+ const raw = src.split("\n");+ return stripComments(src)+ .split("\n")+ .map((line, idx) => ({ line: idx + 1, text: line.trim() }))+ .filter((l) => CJK.test(l.text) && !raw[l.line - 1].includes("i18n-ignore"));+}++/** 代码里写死的 t("…") 键(模板字符串里带 ${} 的动态键跳过) */+export function usedKeys(rel) {+ const src = stripComments(fs.readFileSync(path.join(ROOT, rel), "utf8"));+ const keys = [];+ for (const m of src.matchAll(/(?<![\w.$])t\(\s*(["'`])([A-Za-z][\w.]*)\1/g)) keys.push(m[2]);+ return keys;+}++export async function loadDicts() {+ const dicts = {};+ for (const l of LANGS) dicts[l] = (await import(pathToFileURL(path.join(ROOT, "ui/locales", l, "index.js")).href)).default;+ return dicts;+}++const isPlural = (v) => v !== null && typeof v === "object" && typeof v.other === "string";++/** 拍平成 { "ns.key": string | {one, other} } */+export function flatten(obj, prefix = "", out = {}) {+ for (const [k, v] of Object.entries(obj)) {+ const key = prefix ? `${prefix}.${k}` : k;+ if (typeof v === "string" || isPlural(v)) out[key] = v;+ else if (v && typeof v === "object") flatten(v, key, out);+ else out[key] = v; // 非法值,交给 checkDicts 报+ }+ return out;+}++const placeholders = (v) => {+ const texts = typeof v === "string" ? [v] : isPlural(v) ? Object.values(v) : [];+ const s = new Set();+ for (const t of texts) for (const m of String(t).matchAll(/\{(\w+)\}/g)) s.add(m[1]);+ return [...s].sort().join(",");+};++/** 两种语言的词典是否对齐;返回问题列表 */+export function checkDicts(dicts) {+ const errs = [];+ const flat = Object.fromEntries(LANGS.map((l) => [l, flatten(dicts[l])]));+ const [a, b] = LANGS;+ for (const l of LANGS)+ for (const [k, v] of Object.entries(flat[l])) {+ if (typeof v !== "string" && !isPlural(v)) errs.push(`${l}: ${k} 的值不是字符串或 { one, other }`);+ else if ((typeof v === "string" ? v : v.other).trim() === "") errs.push(`${l}: ${k} 是空文案`);+ }+ for (const k of Object.keys(flat[a])) if (!(k in flat[b])) errs.push(`${b} 缺少 ${k}`);+ for (const k of Object.keys(flat[b])) if (!(k in flat[a])) errs.push(`${a} 缺少 ${k}`);+ for (const k of Object.keys(flat[a])) {+ if (!(k in flat[b])) continue;+ const pa = placeholders(flat[a][k]);+ const pb = placeholders(flat[b][k]);+ if (pa !== pb) errs.push(`${k} 的占位符不一致:${a} {${pa}} / ${b} {${pb}}`);+ }+ return errs;+}++export function missingKeys(dicts, files) {+ const flat = Object.fromEntries(LANGS.map((l) => [l, flatten(dicts[l])]));+ const out = [];+ for (const f of files)+ for (const k of usedKeys(f)) for (const l of LANGS) if (!(k in flat[l])) out.push(`${f}: ${l} 缺少 ${k}`);+ return out;+}++async function main() {+ const args = process.argv.slice(2);+ const files = args.length ? args.map((f) => path.relative(ROOT, path.resolve(f)).split(path.sep).join("/")) : uiFiles();+ const dicts = await loadDicts();+ const problems = [...checkDicts(dicts), ...missingKeys(dicts, files)];+ for (const f of files) for (const l of cjkLines(f)) problems.push(`${f}:${l.line}: 还有中文 → ${l.text.slice(0, 120)}`);+ for (const p of problems) console.log(p);+ console.log(problems.length ? `\n${problems.length} 个问题` : "多语言检查通过");+ process.exitCode = problems.length ? 1 : 0;+}++if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main();diff --git a/src/account/client.ts b/src/account/client.tsindex fa9bd6e..a2d5db1 100644--- a/src/account/client.ts+++ b/src/account/client.ts@@ -4,6 +4,7 @@*/import { OAuthError, refreshTokens, type OidcEndpoints } from "./oauth.js";import type { AccountRecord } from "./vault.js";+import { lang, t } from "../i18n/index.js";/** 授权已失效(用户在网页上撤销、账户被停用等):需要重新登录 */export class AccountRevokedError extends Error {}@@ -87,7 +88,7 @@ export class AccountSession {this.access = { token: t.accessToken, expiresAt: t.expiresAt };return t.accessToken;} catch (e) {- if (e instanceof OAuthError && e.code === "invalid_grant") throw new AccountRevokedError("Modelflare 授权已失效,请重新登录");+ if (e instanceof OAuthError && e.code === "invalid_grant") throw new AccountRevokedError(t("account.revoked"));throw e;} finally {this.refreshing = undefined;@@ -108,18 +109,18 @@ export class AccountSession {Authorization: `Bearer ${token}`,Accept: "application/json",// 通知等内容按语言返回- "Accept-Language": "zh-CN",+ "Accept-Language": lang(),...(body !== undefined ? { "content-type": "application/json" } : {}),},body: body !== undefined ? JSON.stringify(body) : undefined,signal: AbortSignal.timeout(20_000),});} catch (e) {- throw new ApiError(`连不上 Modelflare(${(e as Error).message})`, 0);+ throw new ApiError(t("account.unreachable", { reason: (e as Error).message }), 0);}if (res.status === 401) {if (attempt === 0) continue;- throw new AccountRevokedError("Modelflare 授权已失效,请重新登录");+ throw new AccountRevokedError(t("account.revoked"));}const data = (await res.json().catch(() => ({}))) as { success?: boolean; data?: T; message?: string; error_description?: string };// 部分校验沿用控制台的写法:HTTP 200 + success:falsediff --git a/src/account/manager.ts b/src/account/manager.tsindex 3558a71..c01dda8 100644--- a/src/account/manager.ts+++ b/src/account/manager.ts@@ -5,6 +5,7 @@*/import os from "node:os";import { logger } from "../log.js";+import { t } from "../i18n/index.js";import type { Store } from "../store/db.js";import { MODELFLARE_CLIENT_ID, MODELFLARE_SCOPES, MODELFLARE_WEB, UTM, webUrl, type KeyBalance } from "../modelflare.js";import { discover, OAuthError, revokeToken, startLogin, type LoginAttempt, type OidcEndpoints } from "./oauth.js";@@ -146,7 +147,7 @@ export class AccountManager {/** 开始登录:返回在浏览器里打开的地址;完成后自动签发本机 Key 并接到内置网关 */async startLogin(): Promise<string> {if (this.state === "signing_in" && this.login) return this.login.url;- if (this.session) throw new ApiError("已经登录了 Modelflare 账户", 409);+ if (this.session) throw new ApiError(t("account.already_signed_in"), 409);const ep = await this.ensureEndpoints();const attempt = await startLogin(ep, {clientId: MODELFLARE_CLIENT_ID,@@ -180,7 +181,7 @@ export class AccountManager {const account = await session.account();const host = this.o.hostname ?? os.hostname();const key = await session.createKey(`AnyModelBot · ${host}`.slice(0, 50));- if (!key.key) throw new Error("Modelflare 没有返回新 Key");+ if (!key.key) throw new Error(t("account.no_new_key"));try {await this.o.hooks.connectKey(key.key);} catch (e) {@@ -197,7 +198,7 @@ export class AccountManager {void this.syncBotKeys().catch((e) => log.warn("sync bot keys failed", { message: (e as Error).message }));} catch (e) {this.state = this.session ? "signed_in" : "signed_out";- this.snapshot.error = `登录没有完成:${(e as Error).message}`;+ this.snapshot.error = t("account.login_incomplete", { reason: (e as Error).message });log.warn("login failed", { message: (e as Error).message });} finally {this.login = undefined;@@ -237,12 +238,12 @@ export class AccountManager {private async onRevoked(): Promise<void> {log.warn("Modelflare authorization revoked");await this.forget();- this.snapshot.error = "Modelflare 授权已失效(可能在网页上撤销了),请重新登录";+ this.snapshot.error = t("account.revoked_elsewhere");this.o.hooks.alert(this.snapshot.error, false);}private async call<T>(fn: (s: AccountSession) => Promise<T>): Promise<T> {- if (!this.session) throw new ApiError("请先登录 Modelflare 账户", 409);+ if (!this.session) throw new ApiError(t("account.sign_in_first"), 409);try {return await fn(this.session);} catch (e) {@@ -302,7 +303,7 @@ export class AccountManager {const alerted = !!this.o.store.getKV(ALERTED);if (bal < lowBalanceUsd && !alerted) {this.o.store.setKV(ALERTED, String(Date.now()));- this.o.hooks.alert(`Modelflare 余额只剩 $${bal.toFixed(2)},低于提醒线 $${lowBalanceUsd}。充值:${webUrl("/billing", "amb_low_balance")}`, push);+ this.o.hooks.alert(t("account.low_balance", { balance: bal.toFixed(2), threshold: lowBalanceUsd, url: webUrl("/billing", "amb_low_balance") }), push);} else if (bal >= lowBalanceUsd && alerted) {this.o.store.deleteKV(ALERTED);}@@ -357,7 +358,7 @@ export class AccountManager {* 机器人的请求改走这把 Key;关闭时删除 Key,机器人回到本机共用的 Key。*/async setBotBudget(botId: string, botName: string, budget: BotBudget): Promise<void> {- if (!this.session) throw new ApiError("给机器人设预算需要先登录 Modelflare 账户", 409);+ if (!this.session) throw new ApiError(t("account.budget_needs_login"), 409);let id = this.botKeyIds().get(botId);if (!budget.enabled) {if (id) await this.deleteKeyQuietly(id);@@ -375,7 +376,7 @@ export class AccountManager {}}const key = await this.call((s) => s.createKey(keyName(botName), budget.limitUsd));- if (!key.key) throw new Error("Modelflare 没有返回新 Key");+ if (!key.key) throw new Error(t("account.no_new_key"));try {await this.o.hooks.setBotKey(botId, key.key);} catch (e) {diff --git a/src/account/oauth.ts b/src/account/oauth.tsindex befc890..6c5c9e6 100644--- a/src/account/oauth.ts+++ b/src/account/oauth.ts@@ -7,6 +7,7 @@import crypto from "node:crypto";import http from "node:http";import type { AddressInfo } from "node:net";+import { lang, t, tl, type Lang } from "../i18n/index.js";export interface OidcEndpoints {issuer: string;@@ -41,17 +42,17 @@ export async function discover(issuer: string, fetchImpl: typeof fetch = fetch):try {res = await fetchImpl(`${issuer}/.well-known/openid-configuration`, { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(15_000) });} catch (e) {- throw new OAuthError("network", `连不上 ${new URL(issuer).host}(${(e as Error).message})`);+ throw new OAuthError("network", t("account.host_unreachable", { host: new URL(issuer).host, reason: (e as Error).message }));}- if (!res.ok) throw new OAuthError("discovery", `读取登录配置失败(HTTP ${res.status})`, res.status);+ if (!res.ok) throw new OAuthError("discovery", t("account.discovery_failed", { status: res.status }), res.status);const doc = (await res.json().catch(() => ({}))) as Record<string, unknown>;const origin = new URL(issuer).origin;const endpoint = (key: string) => {const v = typeof doc[key] === "string" ? (doc[key] as string) : "";- if (!v || new URL(v).origin !== origin) throw new OAuthError("discovery", `登录配置里的 ${key} 无效`);+ if (!v || new URL(v).origin !== origin) throw new OAuthError("discovery", t("account.discovery_bad_endpoint", { key }));return v;};- if (doc.issuer !== issuer) throw new OAuthError("discovery", "登录配置的发行方不匹配");+ if (doc.issuer !== issuer) throw new OAuthError("discovery", t("account.discovery_issuer_mismatch"));return {issuer,authorization: endpoint("authorization_endpoint"),@@ -70,7 +71,7 @@ async function tokenRequest(endpoint: string, params: Record<string, string>, fesignal: AbortSignal.timeout(20_000),});} catch (e) {- throw new OAuthError("network", `连不上 Modelflare(${(e as Error).message})`);+ throw new OAuthError("network", t("account.unreachable", { reason: (e as Error).message }));}const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;if (!res.ok) {@@ -79,7 +80,7 @@ async function tokenRequest(endpoint: string, params: Record<string, string>, fe}const accessToken = String(body.access_token ?? "");const refreshToken = String(body.refresh_token ?? params.refresh_token ?? "");- if (!accessToken || !refreshToken) throw new OAuthError("bad_response", "Modelflare 返回的令牌不完整");+ if (!accessToken || !refreshToken) throw new OAuthError("bad_response", t("account.tokens_incomplete"));const ttl = Number(body.expires_in);return {accessToken,@@ -101,7 +102,7 @@ export async function revokeToken(ep: OidcEndpoints, clientId: string, token: stbody: new URLSearchParams({ token, client_id: clientId }).toString(),signal: AbortSignal.timeout(15_000),});- if (!res.ok) throw new OAuthError(`http_${res.status}`, `退出登录失败(HTTP ${res.status})`, res.status);+ if (!res.ok) throw new OAuthError(`http_${res.status}`, t("account.logout_failed", { status: res.status }), res.status);}export interface LoginAttempt {@@ -120,8 +121,8 @@ export interface LoginOptions {fetchImpl?: typeof fetch;}-const PAGE = (title: string, text: string) =>- `<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title}</title>` ++const PAGE = (l: Lang, title: string, text: string) =>+ `<!doctype html><html lang="${l}"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title}</title>` +`<body style="font:16px/1.6 system-ui,sans-serif;display:grid;place-items:center;min-height:90vh;margin:0;color:#222;background:#fafafa">` +`<main style="text-align:center;padding:24px"><h1 style="font-size:20px">${title}</h1><p>${text}</p></main></body></html>`;@@ -131,6 +132,8 @@ const PAGE = (title: string, text: string) =>*/export async function startLogin(ep: OidcEndpoints, o: LoginOptions): Promise<LoginAttempt> {const fetchImpl = o.fetchImpl ?? fetch;+ // 浏览器回调不在发起登录的那个请求里:语言在这里定下(授权页、回调页、报错都用它)+ const l = lang();const { verifier, challenge } = pkcePair();const state = b64url(crypto.randomBytes(24));let settle: { resolve: (t: TokenSet) => void; reject: (e: Error) => void };@@ -149,14 +152,14 @@ export async function startLogin(ep: OidcEndpoints, o: LoginOptions): Promise<Loconst error = u.searchParams.get("error");const code = u.searchParams.get("code");const html = (status: number, title: string, text: string) => {- res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }).end(PAGE(title, text));+ res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }).end(PAGE(l, title, text));};if (error || !code) {- html(400, "没有完成登录", error === "access_denied" ? "你取消了这次授权,可以回到 AnyModelBot 重新登录。" : "授权没有完成,请回到 AnyModelBot 重试。");- finish(new OAuthError(error || "invalid_request", error === "access_denied" ? "你取消了授权" : u.searchParams.get("error_description") || "授权没有完成"));+ html(400, tl(l, "account.page_not_done_title"), tl(l, error === "access_denied" ? "account.page_denied" : "account.page_not_done"));+ finish(new OAuthError(error || "invalid_request", error === "access_denied" ? tl(l, "account.denied") : u.searchParams.get("error_description") || tl(l, "account.not_done")));return;}- html(200, "登录完成", "可以关闭这个页面,回到 AnyModelBot。");+ html(200, tl(l, "account.page_done_title"), tl(l, "account.page_done"));done = true;tokenRequest(ep.token, { grant_type: "authorization_code", code, redirect_uri: redirectUri, client_id: o.clientId, code_verifier: verifier }, fetchImpl).then((t) => finish(undefined, t),@@ -176,7 +179,7 @@ export async function startLogin(ep: OidcEndpoints, o: LoginOptions): Promise<Loserver.listen(0, "127.0.0.1", () => resolve());});const redirectUri = `http://127.0.0.1:${(server.address() as AddressInfo).port}/callback`;- timer = setTimeout(() => finish(new OAuthError("timeout", "登录等待超时,请重新开始")), o.timeoutMs ?? 10 * 60_000);+ timer = setTimeout(() => finish(new OAuthError("timeout", tl(l, "account.login_timeout"))), o.timeoutMs ?? 10 * 60_000);const url = new URL(ep.authorization);const params: Record<string, string> = {response_type: "code",@@ -187,7 +190,7 @@ export async function startLogin(ep: OidcEndpoints, o: LoginOptions): Promise<Locode_challenge: challenge,code_challenge_method: "S256",prompt: "consent",- ui_locales: "zh-CN",+ ui_locales: l,...o.extra,};for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);@@ -195,7 +198,7 @@ export async function startLogin(ep: OidcEndpoints, o: LoginOptions): Promise<Lourl: url.toString(),result,cancel: () => {- if (!done) finish(new OAuthError("cancelled", "已取消登录"));+ if (!done) finish(new OAuthError("cancelled", tl(l, "account.login_cancelled")));},};}diff --git a/src/account/vault.ts b/src/account/vault.tsindex 07cac22..9575d0e 100644--- a/src/account/vault.ts+++ b/src/account/vault.ts@@ -5,6 +5,7 @@*/import fs from "node:fs";import path from "node:path";+import { t } from "../i18n/index.js";/** 由桌面外壳提供的加解密(系统钥匙串) */export interface SecretBox {@@ -38,16 +39,16 @@ export class AccountVault {load(): AccountRecord | undefined {if (!fs.existsSync(this.file)) return undefined;const raw = JSON.parse(fs.readFileSync(this.file, "utf8")) as FileShape;- if (raw.v !== 1) throw new Error("不认识的账户文件版本");+ if (raw.v !== 1) throw new Error(t("account.vault_bad_version"));let json: string;if (raw.enc === "safe-storage") {- if (!this.box) throw new Error("账户凭据由桌面版加密,当前运行方式无法读取");+ if (!this.box) throw new Error(t("account.vault_encrypted"));json = this.box.decrypt(Buffer.from(raw.data, "base64"));} else {json = Buffer.from(raw.data, "base64").toString("utf8");}const rec = JSON.parse(json) as AccountRecord;- if (!rec.refreshToken || !rec.issuer) throw new Error("账户文件不完整");+ if (!rec.refreshToken || !rec.issuer) throw new Error(t("account.vault_incomplete"));return rec;}diff --git a/src/agent/approvals.ts b/src/agent/approvals.tsindex 981a583..e009b6b 100644--- a/src/agent/approvals.ts+++ b/src/agent/approvals.ts@@ -1,6 +1,7 @@import crypto from "node:crypto";import type { ApprovalRow, Store } from "../store/db.js";import { logger } from "../log.js";+import { t } from "../i18n/index.js";const log = logger("approvals");@@ -166,34 +167,34 @@ export class ApprovalCenter {/*** 解析渠道里的用户回复(在每用户串行队列之前调用,避免与等待审批的回合互相阻塞):- * - “y 1234” / “n 1234”(也接受 是/否/同意/拒绝/yes/no;会话中只有一个待批准时可省略编号)+ * - “y 1234” / “n 1234”(也接受 是/否/同意/拒绝/yes/no/approve/allow/deny/reject;会话中只有一个待批准时可省略编号)* - 有待回答的提问时,回复编号(多选用逗号/空格分隔)或直接回复文字*/handleReply(conversationId: string, text: string, by: string): ReplyResult {- const t = text.trim();- if (!t || t.startsWith("/")) return { handled: false };- const m = /^(y|yes|ok|是|同意|批准|允许|n|no|否|拒绝|不)\s*[#::]?\s*(\d{4})?$/i.exec(t);+ const s = text.trim();+ if (!s || s.startsWith("/")) return { handled: false };+ const m = /^(y|yes|ok|approve|allow|是|同意|批准|允许|n|no|deny|reject|否|拒绝|不)\s*[#::]?\s*(\d{4})?$/i.exec(s);if (m && (m[2] || this.pending(conversationId, "approval").length)) {- const allow = /^(y|yes|ok|是|同意|批准|允许)$/i.test(m[1]);+ const allow = /^(y|yes|ok|approve|allow|是|同意|批准|允许)$/i.test(m[1]);let row: ApprovalRow | undefined;if (m[2]) {row = this.store.pendingApprovalByCode(m[2]);if (!row || row.conversationId !== conversationId || row.kind !== "approval") {- return { handled: true, ack: `⚠️ 没有编号为 ${m[2]} 的待批准请求(可能已过期或已处理)` };+ return { handled: true, ack: t("approvals.noSuchCode", { code: m[2] }) };}} else {const list = this.pending(conversationId, "approval");if (list.length === 1) row = list[0];- else return { handled: true, ack: `有 ${list.length} 个待批准请求,请带上编号回复,例如 y ${list[0].code}` };+ else return { handled: true, ack: t("approvals.needCode", { count: list.length, code: list[0].code }) };}const ok = this.decide(row.id, allow, by);- if (!ok) return { handled: true, ack: `⚠️ 请求 ${row.code} 已过期或已处理` };- return { handled: true, ack: allow ? `✅ 已批准 ${row.code}(仅本次)` : `❌ 已拒绝 ${row.code}` };+ if (!ok) return { handled: true, ack: t("approvals.expiredOrDone", { code: row.code }) };+ return { handled: true, ack: t(allow ? "approvals.approved" : "approvals.rejected", { code: row.code }) };}const q = this.pending(conversationId, "question")[0];if (q) {const questions = safeJson<QuestionItem[]>(q.payload, []);- const answer = parseAnswer(questions, t);+ const answer = parseAnswer(questions, s);this.answer(q.id, answer, by);return { handled: true };}@@ -233,8 +234,8 @@ export function parseAnswer(questions: QuestionItem[], text: string): QuestionAnexport function promptText(row: ApprovalRow): string {if (row.kind === "approval") {const cmd = row.detail ? ` \`${row.detail.replace(/`/g, "'").slice(0, 300)}\`` : "";- const why = row.reason && !row.detail ? `(${row.reason.slice(0, 200)})` : "";- return `需批准: ${row.tool}${cmd}${why} — 回复 y ${row.code} / n ${row.code}`;+ const why = row.reason && !row.detail ? t("approvals.promptWhy", { reason: row.reason.slice(0, 200) }) : "";+ return t("approvals.prompt", { tool: row.tool, cmd, why, code: row.code });}const qs = safeJson<QuestionItem[]>(row.payload, []);const blocks = qs.map((q, i) => {@@ -242,6 +243,11 @@ export function promptText(row: ApprovalRow): string {const opts = (q.options ?? []).map((o, j) => ` ${j + 1}. ${o.label}${o.description ? ` — ${o.description}` : ""}`);return [head, ...opts].join("\n");});- const hint = qs.length > 1 ? "(每行回答一个问题:回复编号或直接写答案)" : qs[0]?.options?.length ? `(回复编号${qs[0].multiSelect ? ",可多选用逗号分隔" : ""},或直接写答案)` : "(直接回复答案)";+ const hint =+ qs.length > 1+ ? t("approvals.hintMulti")+ : qs[0]?.options?.length+ ? t("approvals.hintOptions", { multi: qs[0].multiSelect ? t("approvals.hintOptionsMulti") : "" })+ : t("approvals.hintFree");return `❓ ${blocks.join("\n\n")}\n${hint}`;}diff --git a/src/agent/bridge.ts b/src/agent/bridge.tsindex e876c5f..0b74d19 100644--- a/src/agent/bridge.ts+++ b/src/agent/bridge.ts@@ -4,6 +4,7 @@ import { Readable } from "node:stream";import type { AddressInfo } from "node:net";import { logger, redactText, registerSecret } from "../log.js";import { peekStream, type CompactionPlan, type ServerCompaction } from "./server-compaction.js";+import { t } from "../i18n/index.js";const log = logger("agent.bridge");/** 长调用的保活间隔:远小于 fetch 默认的 5 分钟数据间隔超时 */@@ -142,7 +143,7 @@ export class AgentBridge {private async proxy(req: http.IncomingMessage, res: http.ServerResponse, url: string): Promise<void> {const up = this.h.upstream();- if (!up.baseUrl) throw new Error("模型网关未就绪");+ if (!up.baseUrl) throw new Error(t("agent.gatewayNotReady"));const target = up.baseUrl.replace(/\/+$/, "").replace(/\/v1$/, "") + url;const headers: Record<string, string> = {};for (const [k, v] of Object.entries(req.headers)) {diff --git a/src/agent/computer-use.ts b/src/agent/computer-use.tsindex e63f972..6041bc1 100644--- a/src/agent/computer-use.ts+++ b/src/agent/computer-use.ts@@ -3,6 +3,7 @@ import os from "node:os";import path from "node:path";import { cuaRoots, detectCua, CUA_READ_TOOLS, type CuaStatus } from "./cua-driver.js";import type { CuBackend } from "./settings.js";+import { t, tl, type MessageKey } from "../i18n/index.js";/*** 电脑操作(Computer Use)有两个后端:@@ -15,7 +16,8 @@ export const CU_SERVER = "computer-use";export const CU_TOOL_PREFIX = `mcp__${CU_SERVER}__`;/** Codex 桥里只读取界面、不改变任何东西的工具(ask-input 模式下也免审批) */export const CU_READONLY_TOOLS = ["list_apps", "get_app_state"];-export const CU_UNAVAILABLE = "Codex Computer Use 桥: 需要 macOS 14.4+ 和已安装的 Codex Computer Use";+/** 中文原文(测试比对用);界面里的说明按当前语言,见 detectComputerUse */+export const CU_UNAVAILABLE = tl("zh-CN", "cu.codexUnavailable");export interface CuProbe {platform: NodeJS.Platform;@@ -29,7 +31,7 @@ export interface CuProbe {export interface CuStatus {available: boolean;- /** 给界面的说明(中文) */+ /** 给界面的说明(检测时的当前语言;每次读状态都重新检测) */reason: string;client?: string;launcher?: string;@@ -101,19 +103,19 @@ export function bundledRoots(runtimeDir: string): string[] {}export function detectComputerUse(roots: string[], probe: CuProbe = defaultProbe()): CuStatus {- const off = (why: string): CuStatus => ({ available: false, reason: `${CU_UNAVAILABLE}(${why})` });- if (probe.platform !== "darwin") return off("当前系统不是 macOS");- if (!macAtLeast144(probe.release)) return off("macOS 版本低于 14.4");+ const off = (why: MessageKey): CuStatus => ({ available: false, reason: t("cu.codexOff", { base: t("cu.codexUnavailable"), why: t(why) }) });+ if (probe.platform !== "darwin") return off("cu.codexNotMac");+ if (!macAtLeast144(probe.release)) return off("cu.codexOldMac");const root = roots.find((r) => probe.isFile(path.join(r, "bin", "computer-use-mcp-bridge.mjs")));- if (!root) return off("安装包缺少 kimi-computer-use 组件");+ if (!root) return off("cu.codexNoBridge");const { codexHome, client } = clientPath(probe.env, probe.homedir);- if (!probe.isExecutable(client)) return off("未找到 Codex Computer Use 客户端");+ if (!probe.isExecutable(client)) return off("cu.codexNoClient");const direct = probe.env.COMPUTER_USE_BRIDGE_DIRECT_LAUNCH === "1";const launcher = direct ? undefined : launcherCandidates(probe.env).find((p) => probe.isExecutable(p));- if (!direct && !launcher) return off("未找到 ChatGPT/Codex 应用自带的 codex 启动器");+ if (!direct && !launcher) return off("cu.codexNoLauncher");return {available: true,- reason: "Codex Computer Use 桥: 可用(macOS)",+ reason: t("cu.codexAvailable"),client,launcher,codexHome,@@ -179,6 +181,6 @@ export function resolveComputerUse(want: CuBackend, runtimeDir: string): CuResolif (want === "codex" && codex.available) {return { backend: "codex", available: true, reason: codex.reason, backends, cua, codex, readTools: CU_READONLY_TOOLS };}- const fallback = want === "codex" ? `(Codex 桥不可用,已改用 Cua Driver:${codex.reason})` : "";+ const fallback = want === "codex" ? t("cu.codexFallback", { reason: codex.reason }) : "";return { backend: "cua", available: cua.available, reason: cua.reason + fallback, notice: cua.notice, backends, cua, codex, readTools: CUA_READ_TOOLS };}diff --git a/src/agent/cua-driver.ts b/src/agent/cua-driver.tsindex 47279eb..a5b758d 100644--- a/src/agent/cua-driver.ts+++ b/src/agent/cua-driver.ts@@ -2,6 +2,7 @@ import { execFile, execFileSync } from "node:child_process";import fs from "node:fs";import os from "node:os";import path from "node:path";+import { t } from "../i18n/index.js";/*** Cua Driver(trycua/cua libs/cua-driver,MIT):默认的电脑操作后端,三个平台都用官方预编译的@@ -60,7 +61,7 @@ export interface CuaProbe {export interface CuaStatus {available: boolean;- /** 给界面与 /status 的说明(中文) */+ /** 给界面与 /status 的说明(检测时的当前语言;每次读状态都重新检测) */reason: string;/** 平台提示(权限、Wayland 降级等) */notice?: string;@@ -102,31 +103,26 @@ export function cuaRoots(runtimeDir: string, platform = process.platform, arch =].filter((x): x is string => !!x);}-const LINUX_ATSPI = "需要 AT-SPI(at-spi2-core)才能读取窗口元素";-export function detectCua(roots: string[], probe: CuaProbe = defaultCuaProbe()): CuaStatus {- const off = (why: string): CuaStatus => ({ available: false, reason: `Cua Driver: 不可用(${why})` });- if (!["linux", "darwin", "win32"].includes(probe.platform)) return off(`不支持 ${probe.platform}`);+ const off = (why: string): CuaStatus => ({ available: false, reason: t("cu.cuaOff", { why }) });+ if (!["linux", "darwin", "win32"].includes(probe.platform)) return off(t("cu.cuaUnsupported", { platform: probe.platform }));const exe = probe.platform === "win32" ? "cua-driver.exe" : "cua-driver";const root = roots.find((r) => probe.isFile(path.join(r, exe)));- if (!root) return off(`安装包缺少 ${probe.platform}-${probe.arch} 的 cua-driver ${CUA_VERSION}`);+ if (!root) return off(t("cu.cuaMissing", { plat: `${probe.platform}-${probe.arch}`, version: CUA_VERSION }));const bin = path.join(root, exe);const env = probe.env;if (probe.platform === "linux") {const x11 = !!env.DISPLAY;const wayland = !!env.WAYLAND_DISPLAY || env.XDG_SESSION_TYPE === "wayland";- if (!x11 && !wayland) return off("没有图形会话:DISPLAY / WAYLAND_DISPLAY 均未设置");- const notice = wayland- ? `Wayland 会话:功能降级——窗口读取依赖 AT-SPI,键鼠输入走 XWayland,只能操作前台窗口;${LINUX_ATSPI}`- : `X11 会话;${LINUX_ATSPI}`;- return { available: true, reason: "Cua Driver: 可用(Linux)", notice, bin };+ if (!x11 && !wayland) return off(t("cu.cuaNoDisplay"));+ const notice = t(wayland ? "cu.cuaWayland" : "cu.cuaX11", { atspi: t("cu.cuaAtspi") });+ return { available: true, reason: t("cu.cuaAvailable", { os: "Linux" }), notice, bin };}if (probe.platform === "darwin") {return {available: true,- reason: "Cua Driver: 可用(macOS)",- notice:- "首次使用需在「系统设置 → 隐私与安全性」给本应用打开「辅助功能」和「屏幕录制」。以 --direct 模式运行,授权应归属本应用(尚未在真机验证)。",+ reason: t("cu.cuaAvailable", { os: "macOS" }),+ notice: t("cu.cuaMacNotice"),bin,direct: true,};@@ -135,8 +131,8 @@ export function detectCua(roots: string[], probe: CuaProbe = defaultCuaProbe()):if (env.SESSIONNAME) {return {available: true,- reason: "Cua Driver: 可用(Windows)",- notice: "需在已登录用户的交互式桌面会话中运行;无法操作以管理员权限运行的窗口(除非本应用也以管理员运行)。",+ reason: t("cu.cuaAvailable", { os: "Windows" }),+ notice: t("cu.cuaWinNotice"),bin,};}@@ -145,12 +141,12 @@ export function detectCua(roots: string[], probe: CuaProbe = defaultCuaProbe()):// 仅在真实 Windows 进程上查询;交叉平台单测不注入时走下方启发式,避免误起 PowerShell。sid = process.platform === "win32" ? (queryWindowsSessionId() ?? null) : null;}- if (sid === 0) return off("需要在已登录用户的交互式会话中运行(检测到服务或非交互会话)");+ if (sid === 0) return off(t("cu.cuaNonInteractive"));if (typeof sid === "number" && sid > 0) {return {available: true,- reason: "Cua Driver: 可用(Windows)",- notice: "需在已登录用户的交互式桌面会话中运行;无法操作以管理员权限运行的窗口(除非本应用也以管理员运行)。",+ reason: t("cu.cuaAvailable", { os: "Windows" }),+ notice: t("cu.cuaWinNotice"),bin,};}@@ -158,12 +154,12 @@ export function detectCua(roots: string[], probe: CuaProbe = defaultCuaProbe()):if (looksLikeWindowsUserDesktop(env)) {return {available: true,- reason: "Cua Driver: 可用(Windows)",- notice: "需在已登录用户的交互式桌面会话中运行;无法操作以管理员权限运行的窗口(除非本应用也以管理员运行)。",+ reason: t("cu.cuaAvailable", { os: "Windows" }),+ notice: t("cu.cuaWinNotice"),bin,};}- return off("需要在已登录用户的交互式会话中运行(检测到服务或非交互会话)");+ return off(t("cu.cuaNonInteractive"));}/** 进程的 SessionId 不会变:只查一次(每次查都要同步起一个 PowerShell,冷启动时会卡住主进程好几秒)。 */diff --git a/src/agent/host.ts b/src/agent/host.tsindex ba8a776..1254d8c 100644--- a/src/agent/host.ts+++ b/src/agent/host.ts@@ -15,6 +15,7 @@ import { pwshPatchLines, pwshProbe } from "./pwsh.js";import { DEFAULT_SETTINGS, permissionMode, type BotSettings } from "./settings.js";import { acceptsImages } from "../llm/client.js";import { CUA_SKILL, MEDIA_SKILL, TASK_RULES, agentPersona, botPrompt } from "./prompts/index.js";+import { t } from "../i18n/index.js";const log = logger("agent.host");@@ -990,7 +991,7 @@ exec "$REAL" "$@"this.syncPrompt();// 连续启动失败后不再每条消息都重试一遍(每次都要等满初始化超时):直到手动重启或冷却结束if (!this.harness && !this.starting && this.state === "error" && Date.now() < this.retryAfter) {- throw new Error(`代理进程启动失败,${Math.ceil((this.retryAfter - Date.now()) / 60_000)} 分钟后再试(或在 设置 → 故障排查 里重启代理进程):${this.lastError}`);+ throw new Error(t("agent.startRetryLater", { min: Math.ceil((this.retryAfter - Date.now()) / 60_000), error: this.lastError }));}if (this.harness && this.sig !== this.settingsSig() && this.active === 0 && this.tasksAllowRestart()) {log.info("bot settings or PowerShell changed, restarting dsh", { bot: this.o.botId, backgroundTasks: this.taskBusy.size });@@ -1217,7 +1218,7 @@ exec "$REAL" "$@"this.state = "error";this.retryAfter = Date.now() + 10 * 60_000;log.error("dsh failed to start twice; agent paused for 10 minutes (plain chat still works)", { bot: this.o.botId, message: this.lastError });- this.o.onNotice?.(`代理进程连续两次启动失败,已暂停 10 分钟(期间用纯对话回复)。可在 设置 → 故障排查 查看原因并重启代理进程。原因:${this.lastError.slice(0, 200)}`);+ this.o.onNotice?.(t("agent.startPaused", { error: this.lastError.slice(0, 200) }));return;}const delay = Math.min(30_000, 1000 * 2 ** Math.min(this.failures - 1, 5));diff --git a/src/agent/manager.ts b/src/agent/manager.tsindex fa53a33..1d7c491 100644--- a/src/agent/manager.ts+++ b/src/agent/manager.ts@@ -13,6 +13,7 @@ import { APPROVAL_TTL_MS, ApprovalCenter, type QuestionItem } from "./approvals.import { MemoryError, MemoryStore, type Scope } from "./memory.js";import type { TaskHost, TaskService } from "../tasks/service.js";import { DEFAULT_SETTINGS, type BotSettings, type MediaConfirm } from "./settings.js";+import { t, tl } from "../i18n/index.js";import {HANDOFF_SYSTEM,REVIEW_SYSTEM,@@ -78,8 +79,8 @@ export interface TurnProgress {media: number;}-/** 生成确认里"取消"那一项 */-const CANCEL = "取消";+/** 生成确认里"取消"那一项(问题建好后界面语言可能变了:两种语言的都认) */+const CANCELS = [tl("zh-CN", "media.cancel"), tl("en", "media.cancel")];/** 预计花费超过它(美元)就先问用户 */export const MEDIA_ASK_USD = 0.5;@@ -252,13 +253,13 @@ export class AgentManager {computerUse(botId: string): ComputerUseInfo {const st = this.settings(botId).computerUse;if (!this.o.runtimeDir) {- const reason = "Computer Use: 不可用(代理运行时缺失)";+ const reason = t("agent.cuNoRuntime");return { available: false, enabled: st.enabled, active: false, backend: st.backend, selectedBackend: st.backend, approval: st.approval, reason, backends: [] };}const sys = resolveComputerUse(st.backend, this.o.runtimeDir);const active = this.available && sys.available && st.enabled;- const mode = st.approval === "ask-input" ? "点击/输入前先问我" : "操作自动执行";- const reason = !st.enabled ? "Computer Use: 已在本机器人设置中关闭" : sys.available ? `${sys.reason};${mode}` : sys.reason;+ const mode = t(st.approval === "ask-input" ? "agent.cuModeAsk" : "agent.cuModeAuto");+ const reason = !st.enabled ? t("agent.cuDisabled") : sys.available ? t("agent.cuReasonMode", { reason: sys.reason, mode }) : sys.reason;return {available: sys.available,enabled: st.enabled,@@ -682,17 +683,27 @@ export class AgentManager {/** 生成前的确认:问用户这次用哪个模型(本次的、默认的和几个推荐的,或回复别的模型名),等到回答、取消或过期 */private async confirmMedia(botId: string, conv: string, sessionId: string, plan: MediaPlan, tool: string, why: MediaAskReason): Promise<{ model?: MediaModel; cancel?: boolean; reply?: string }> {- const name = plan.kind === "image" ? "图片" : "视频";+ const image = plan.kind === "image";const opt = (m: MediaModel, tag = "") => ({ label: m.id, description: [tag, m.price].filter(Boolean).join(" · ") || undefined });// 为什么问:花费高、不是默认模型时说一句(每次都问、代理要问的不用解释)const reason =- why === "cost" ? (plan.estimate !== undefined ? `预计花费约 $${Math.round(plan.estimate * 100) / 100},超过 $${MEDIA_ASK_USD}` : "这次的花费估算不出来") : why === "model" ? `不是默认模型(默认是 ${plan.default.id})` : "";+ why === "cost"+ ? plan.estimate !== undefined+ ? t("media.reasonCost", { amount: Math.round(plan.estimate * 100) / 100, limit: MEDIA_ASK_USD })+ : t("media.reasonCostUnknown")+ : why === "model"+ ? t("media.reasonModel", { model: plan.default.id })+ : "";const q: QuestionItem = {id: "model",- header: `生成${name}`,- question: `这次用 ${plan.model.id} 生成${name}吗?`,- detail: `${plan.summary}${reason ? `\n${reason}` : ""}\n也可以直接回复其他模型名。`,- options: [opt(plan.model, plan.model === plan.default ? "默认" : "机器人选的"), ...plan.candidates.map((m) => opt(m, m === plan.default ? "默认" : "")), { label: CANCEL, description: "这次不生成" }],+ header: t(image ? "media.confirmHeaderImage" : "media.confirmHeaderVideo"),+ question: t(image ? "media.confirmQuestionImage" : "media.confirmQuestionVideo", { model: plan.model.id }),+ detail: t("media.confirmDetail", { summary: plan.summary, reason: reason ? `\n${reason}` : "" }),+ options: [+ opt(plan.model, t(plan.model === plan.default ? "media.tagDefault" : "media.tagBotPick")),+ ...plan.candidates.map((m) => opt(m, m === plan.default ? t("media.tagDefault") : "")),+ { label: t("media.cancel"), description: t("media.cancelDesc") },+ ],};const row = this.approvals.create({ kind: "question", botId, conversationId: conv, sessionId, tool, detail: q.question, reason: "", payload: JSON.stringify([q]) });const deadline = Date.now() + (this.o.approvalTtlMs ?? APPROVAL_TTL_MS) + 10_000;@@ -715,9 +726,9 @@ export class AgentManager {}const pick = (a?.selected?.[0] ?? "").trim();const text = (a?.custom ?? "").trim();- if (pick === CANCEL || /^(取消|不要?|不用|算了|no?|cancel)$/i.test(text)) return { cancel: true };- if (!pick && /^(好的?|行|可以|确认|确定|是的?|对|嗯|ok(ay)?|y(es)?|生成吧?|就用它)$/i.test(text)) return { model: plan.model };- const want = (pick || text).replace(/^(用|换成|改用)\s*/, "");+ if (CANCELS.includes(pick) || /^(取消|不要?|不用|算了|no?|cancel|don'?t|stop|skip)$/i.test(text)) return { cancel: true };+ if (!pick && /^(好的?|行|可以|确认|确定|是的?|对|嗯|ok(ay)?|y(es)?|sure|confirm|go( ahead)?|generate( it)?|生成吧?|就用它)$/i.test(text)) return { model: plan.model };+ const want = (pick || text).replace(/^(用|换成|改用)\s*/, "").replace(/^(use|switch to)\s+/i, "");const hit = plan.all.find((m) => m.id.toLowerCase() === want.toLowerCase());if (hit) return { model: hit };return text ? { reply: text } : { cancel: true };@@ -863,15 +874,15 @@ export class AgentManager {hostSummary(botId: string): string {if (!this.available) return "";const h = this.hosts.get(botId);- if (!h || h.state === "stopped") return "代理进程:未启动(收到消息时启动)";+ if (!h || h.state === "stopped") return t("agent.hostNotStarted");const d = h.diagnostics() as any;- if (h.state === "running") return `代理进程:运行中(pid ${h.pid ?? "?"}${d.lastInitMs ? `,启动用时 ${Math.round(d.lastInitMs / 1000)} 秒` : ""})`;+ if (h.state === "running") return t("agent.hostRunning", { pid: h.pid ?? "?", init: d.lastInitMs ? t("agent.hostRunningInit", { s: Math.round(d.lastInitMs / 1000) }) : "" });if (h.state === "starting") {const s = Math.round((d.startingForMs ?? 0) / 1000);- return `代理进程:正在启动(已 ${s} 秒${d.firstStart ? ";第一次启动可能要几分钟" : ""})`;+ return t("agent.hostStarting", { s, first: d.firstStart ? t("agent.hostStartingFirst") : "" });}- if (h.state === "backoff") return `代理进程:上次启动失败,稍后重试(${h.lastError.slice(0, 120)})`;- return `代理进程:启动失败,已暂停(${h.lastError.slice(0, 120)})`;+ if (h.state === "backoff") return t("agent.hostBackoff", { error: h.lastError.slice(0, 120) });+ return t("agent.hostPaused", { error: h.lastError.slice(0, 120) });}/** 故障排查的"重启代理进程":关掉(全部或指定机器人的)子进程并清掉退避;返回重启了哪些。 */diff --git a/src/agent/media.ts b/src/agent/media.tsindex 9525503..5aaddfb 100644--- a/src/agent/media.ts+++ b/src/agent/media.ts@@ -13,6 +13,7 @@import fs from "node:fs";import path from "node:path";import { logger } from "../log.js";+import { t } from "../i18n/index.js";const log = logger("agent.media");@@ -76,7 +77,7 @@ export interface MediaPlan {all: MediaModel[];/** 代理按文档写了自己的请求体:换模型后需要按新模型的文档重写 */custom: boolean;- /** 给用户看的说明:提示词摘要、参数、参考素材 */+ /** 给用户看的说明:提示词摘要、参数、参考素材(按当前语言) */summary: string;/** 预计花费(美元);算不出来(按 token 计费、目录里没有价格、视频不知道多长)时为空 */estimate?: number;@@ -153,11 +154,11 @@ export function unitPrice(e: CatalogEntry | undefined, catalog: Catalog): UnitPrreturn undefined;}-/** 一句参考价;复杂计费(按 token)只说明计费方式 */+/** 一句参考价(按当前语言);复杂计费(按 token)只说明计费方式 */export function priceNote(e: CatalogEntry | undefined, catalog: Catalog): string {const p = unitPrice(e, catalog);- if (p) return `$${num(p.usd)}/${p.per === "second" ? `秒(${p.resolution})` : p.per === "call" ? "次" : "张"}`;- if (e?.billing_unit === "token") return "按 token 计费";+ if (p) return t(p.per === "second" ? "media.pricePerSecond" : p.per === "call" ? "media.pricePerCall" : "media.pricePerImage", { price: `$${num(p.usd)}`, res: p.resolution ?? "" });+ if (e?.billing_unit === "token") return t("media.priceToken");return "";}@@ -215,7 +216,8 @@ export function optionsNote(m: MediaModel): string {/** 从请求体里挑出给用户看的参数(分辨率、比例、时长……),并数一数参考素材 */export function describeBody(body: Record<string, unknown> | undefined): string {if (!body) return "";- const keys: Record<string, string> = { resolution: "", aspect_ratio: "", ratio: "", size: "", imageSize: "", aspectRatio: "", seconds: "秒", duration: "秒", quality: "" };+ // true = 时长(数字时带单位"秒")+ const keys: Record<string, boolean> = { resolution: false, aspect_ratio: false, ratio: false, size: false, imageSize: false, aspectRatio: false, seconds: true, duration: true, quality: false };const seen = new Map<string, string>();let refs = 0;const walk = (v: unknown, depth: number) => {@@ -228,13 +230,13 @@ export function describeBody(body: Record<string, unknown> | undefined): stringif (k in keys && (typeof x === "string" || typeof x === "number")) {// 时长两种写法只显示一个const label = k === "duration" ? "seconds" : k === "aspectRatio" || k === "aspect_ratio" ? "ratio" : k === "imageSize" ? "size" : k;- if (!seen.has(label)) seen.set(label, `${x}${keys[k] && Number(x) > 0 ? ` ${keys[k]}` : ""}`);+ if (!seen.has(label)) seen.set(label, keys[k] && Number(x) > 0 ? t("media.seconds", { n: x }) : String(x));} else walk(x, depth + 1);}};walk(body, 0);const parts = [...seen.values()];- if (refs) parts.push(`${refs} 个参考素材`);+ if (refs) parts.push(t("media.references", { count: refs }));return parts.join(" · ");}@@ -390,8 +392,14 @@ export class MediaService {if (!model) throw new MediaError(`没有这个模型:${name}。可用:${all.map((m) => m.id).join("、")}`);const hasRefs = /"workspace(-base64)?:|"https?:\/\/|"data:/.test(JSON.stringify(body ?? {}));const candidates = [def, ...all].filter((m, i, a) => m !== model && a.indexOf(m) === i && (hasRefs || !m.requiresReference)).slice(0, 3);- const params = describeBody(body) || [typeof args.size === "string" ? args.size : "", Number(args.seconds) > 0 ? `${args.seconds} 秒` : ""].filter(Boolean).join(" · ");- const summary = [`提示词:${prompt.length > 120 ? `${prompt.slice(0, 120)}…` : prompt}`, params && `参数:${params}`, model.price && `参考价:${model.price}`].filter(Boolean).join("\n");+ const params = describeBody(body) || [typeof args.size === "string" ? args.size : "", Number(args.seconds) > 0 ? t("media.seconds", { n: String(args.seconds) }) : ""].filter(Boolean).join(" · ");+ const summary = [+ t("media.summaryPrompt", { prompt: prompt.length > 120 ? `${prompt.slice(0, 120)}…` : prompt }),+ params && t("media.summaryParams", { params }),+ model.price && t("media.summaryPrice", { price: model.price }),+ ]+ .filter(Boolean)+ .join("\n");return { kind, model, default: def, candidates, all, custom: !!body, summary, estimate: estimateUsd(model, body, args) };}diff --git a/src/agent/memory.ts b/src/agent/memory.tsindex 127dcbd..5ac87ca 100644--- a/src/agent/memory.ts+++ b/src/agent/memory.ts@@ -1,5 +1,6 @@import fs from "node:fs";import path from "node:path";+import { t, tl, lang, type Lang } from "../i18n/index.js";/*** 三层长期记忆(机器人 / 群 / 团队),Markdown 存储:@@ -33,6 +34,9 @@ export interface Entry {export class MemoryError extends Error {}+/** 记忆操作的回执与报错:回给代理(工具结果),也显示在界面的记忆页(删除),按当前语言。remember 里的局部变量 t 会遮住 t(),所以起个别名 */+const msg: typeof t = (key, params) => t(key, params);+// ---------- 秘密检测(模式移植自 DS Bot ds-bot/src/host/memory.js,Apache-2.0) ----------const KEY_PATTERNS = [/\bsk-[A-Za-z0-9_-]{16,}/,@@ -76,10 +80,10 @@ export function parseEntries(md: string): Entry[] {return out;}-export function validTopic(t: string): string {- const s = t.trim().toLowerCase().replace(/\s+/g, "-");- if (!/^[\p{L}\p{N}_-]{1,40}$/u.test(s)) throw new MemoryError(`主题名「${t}」无效:只能用字母、数字、中文、- 和 _,最长 40 字`);- if (s === "memory" || s === "index") throw new MemoryError(`主题名「${t}」是保留名`);+export function validTopic(topic: string): string {+ const s = topic.trim().toLowerCase().replace(/\s+/g, "-");+ if (!/^[\p{L}\p{N}_-]{1,40}$/u.test(s)) throw new MemoryError(msg("agent.memTopicInvalid", { topic }));+ if (s === "memory" || s === "index") throw new MemoryError(msg("agent.memTopicReserved", { topic }));return s;}@@ -93,9 +97,14 @@ function today(): string {return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;}-export function scopeLabel(s: Scope): string {- return s.kind === "team" ? "团队记忆" : s.kind === "group" ? "本群记忆" : "机器人记忆";+/**+ * 作用域名称:默认按当前语言(界面的记忆页、记忆操作的回执)。+ * 写进 MEMORY.md 的标题和给模型的快照 / 检索结果固定用中文(FILE_LANG):文件内容与提示前缀不随界面语言变。+ */+export function scopeLabel(s: Scope, l: Lang = lang()): string {+ return tl(l, s.kind === "team" ? "agent.scopeTeam" : s.kind === "group" ? "agent.scopeGroup" : "agent.scopeBot");}+const FILE_LANG: Lang = "zh-CN";function safeKey(s: string): string {return s.replace(/[^A-Za-z0-9@._-]/g, "_").slice(0, 120) || "_";@@ -172,41 +181,43 @@ export class MemoryStore {if (topic) return [`# ${topic}`, "", ...lines, ""].join("\n");const topics = this.topics(s);const idx = topics.length ? ["", "## Index", "", ...topics.map((t) => `- [[${t}]] — ${this.entries(s, t).length} 条`)] : [];- return [`# ${scopeLabel(s)}`, "", ...lines, ...idx, ""].join("\n");+ return [`# ${scopeLabel(s, FILE_LANG)}`, "", ...lines, ...idx, ""].join("\n");}remember(s: Scope, text: string, opts: { topic?: string; source: string; by?: string }): string {const t = text.replace(/\s+/g, " ").trim();- if (!t) throw new MemoryError("内容为空");- if (t.length > ENTRY_MAX) throw new MemoryError(`单条记忆最多 ${ENTRY_MAX} 字(现在 ${t.length} 字),请精简后再保存`);- if (looksSecret(t)) throw new MemoryError("内容看起来含有密码、密钥、令牌或证件号,记忆里不能保存这类信息");+ if (!t) throw new MemoryError(msg("agent.memEmpty"));+ if (t.length > ENTRY_MAX) throw new MemoryError(msg("agent.memTooLong", { max: ENTRY_MAX, n: t.length }));+ if (looksSecret(t)) throw new MemoryError(msg("agent.memSecret"));const topic = opts.topic ? validTopic(opts.topic) : undefined;- if (topic && !this.topics(s).includes(topic) && this.topics(s).length >= TOPICS_MAX) throw new MemoryError(`主题已达上限 ${TOPICS_MAX} 个,请把内容记到已有主题里`);+ if (topic && !this.topics(s).includes(topic) && this.topics(s).length >= TOPICS_MAX) throw new MemoryError(msg("agent.memTopicsFull", { max: TOPICS_MAX }));const list = this.entries(s, topic);- if (list.some((e) => squash(e.text) === squash(t))) return "这条已经记过了";+ if (list.some((e) => squash(e.text) === squash(t))) return msg("agent.memDuplicate");const entry: Entry = { text: t, meta: `source: ${opts.source.replace(/[\];]/g, "")}; added: ${today()}`, line: "" };const next = this.render(s, [...list, entry], topic);const cap = topic ? TOPIC_MAX : MEMORY_MAX;if (next.length > cap)- throw new MemoryError(topic ? `主题「${topic}」已满(上限 ${cap} 字),请先 forget 过时的内容` : `MEMORY.md 已满(上限 ${cap} 字),请把细节记到某个 topic 里,或先 forget 过时的内容`);+ throw new MemoryError(topic ? msg("agent.memTopicFull", { topic, cap }) : msg("agent.memMainFull", { cap }));this.write(this.file(s, topic), next);if (topic) this.write(this.file(s), this.render(s, this.entries(s)));this.journal({ scope: this.key(s), file: topic ?? "MEMORY", op: "add", text: t, by: opts.by ?? opts.source });- return `已记住(${scopeLabel(s)}${topic ? ` · ${topic}` : ""})`;+ return msg("agent.memRemembered", { where: `${scopeLabel(s)}${topic ? ` · ${topic}` : ""}` });}/** 按内容片段删除;多条匹配且未指定 all 时报错并列出候选。 */forget(s: Scope, match: string, opts: { topic?: string; all?: boolean; by: string }): string {const key = squash(match);- if (!key) throw new MemoryError("请给出要删除的内容片段");+ if (!key) throw new MemoryError(msg("agent.memForgetEmpty"));const topics = opts.topic ? [validTopic(opts.topic)] : [undefined, ...this.topics(s)];const hits: Array<{ topic?: string; e: Entry }> = [];for (const t of topics) for (const e of this.entries(s, t)) if (squash(e.text).includes(key)) hits.push({ topic: t, e });- if (!hits.length) throw new MemoryError(`${scopeLabel(s)}里没有包含「${match}」的条目`);+ if (!hits.length) throw new MemoryError(msg("agent.memForgetNone", { scope: scopeLabel(s), match }));const exact = hits.filter((h) => squash(h.e.text) === key);const chosen = exact.length === 1 ? exact : hits;if (chosen.length > 1 && !opts.all)- throw new MemoryError(`有 ${chosen.length} 条匹配,请写得更具体,或传 all: true 全部删除:\n${chosen.map((h) => `- ${h.e.text}${h.topic ? `(${h.topic})` : ""}`).join("\n")}`);+ throw new MemoryError(+ msg("agent.memForgetMany", { count: chosen.length, list: chosen.map((h) => `- ${h.e.text}${h.topic ? msg("agent.memInTopic", { topic: h.topic }) : ""}`).join("\n") }),+ );const byTopic = new Map<string | undefined, Entry[]>();for (const h of chosen) byTopic.set(h.topic, [...(byTopic.get(h.topic) ?? []), h.e]);for (const [t, gone] of byTopic) {@@ -216,7 +227,7 @@ export class MemoryStore {for (const g of gone) this.journal({ scope: this.key(s), file: t ?? "MEMORY", op: "remove", text: g.text, by: opts.by });}this.write(this.file(s), this.render(s, this.entries(s)));- return `已删除 ${chosen.length} 条(${scopeLabel(s)})`;+ return msg("agent.memForgotten", { count: chosen.length, scope: scopeLabel(s) });}/** 检索:所有关键词都出现的条目(不区分大小写);中文无空格时按整串匹配。 */@@ -228,7 +239,7 @@ export class MemoryStore {for (const t of [undefined, ...this.topics(s)]) {for (const e of this.entries(s, t)) {const hay = e.text.toLowerCase();- if (terms.every((w) => hay.includes(w))) out.push(`[${scopeLabel(s)}${t ? ` · ${t}` : ""}] ${e.text}`);+ if (terms.every((w) => hay.includes(w))) out.push(`[${scopeLabel(s, FILE_LANG)}${t ? ` · ${t}` : ""}] ${e.text}`);if (out.length >= limit) return out;}}@@ -243,7 +254,7 @@ export class MemoryStore {const es = this.entries(s);const ts = this.topics(s);if (!es.length && !ts.length) continue;- parts.push(`## ${scopeLabel(s)}`, ...es.map((e) => `- ${e.text}`));+ parts.push(`## ${scopeLabel(s, FILE_LANG)}`, ...es.map((e) => `- ${e.text}`));if (ts.length) parts.push(`(主题,用 recall 读取:${ts.join("、")})`);parts.push("");}diff --git a/src/agent/pwsh.ts b/src/agent/pwsh.tsindex 8269130..01bff4b 100644--- a/src/agent/pwsh.ts+++ b/src/agent/pwsh.ts@@ -33,6 +33,7 @@ import {type PrivatePwshStatus,type Runner,} from "./pwsh-private.js";+import { t, type MessageKey } from "../i18n/index.js";const log = logger("pwsh");const W = path.win32;@@ -580,73 +581,86 @@ export function pwshPatchLines(pwshPath: string | undefined): string[] {return pwshPath ? ["- id: pwsh-sandbox", " config:", ` pwshPath: ${JSON.stringify(pwshPath)}`] : [];}-const SOURCE: Record<PwshSource, string> = { "program-files": "安装目录", path: "PATH", preview: "预览版", store: "Microsoft Store", private: "应用内置" };+const SOURCE: Record<PwshSource, MessageKey> = { "program-files": "pwsh.sourceProgramFiles", path: "pwsh.sourcePath", preview: "pwsh.sourcePreview", store: "pwsh.sourceStore", private: "pwsh.sourcePrivate" };const mb = (n?: number) => (n === undefined ? "?" : (n / 1048576).toFixed(0));-/** 安装进度的一句话 */+/** 安装进度的一句话(按当前语言) */export function installProgressText(p: InstallProgress): string {switch (p.state) {case "waiting":- return p.error ?? "准备中";+ return p.error ?? t("pwsh.installWaiting");case "downloading":- return `下载 ${mb(p.received)} / ${mb(p.total)} MB${p.total ? `(${Math.min(100, Math.floor(((p.received ?? 0) / p.total) * 100))}%)` : ""}`;+ return t("pwsh.installDownloading", {+ received: mb(p.received),+ total: mb(p.total),+ pct: p.total ? t("pwsh.installPct", { n: Math.min(100, Math.floor(((p.received ?? 0) / p.total) * 100)) }) : "",+ });case "extracting":- return "解压";+ return t("pwsh.installExtracting");case "verifying":- return "核对签名";+ return t("pwsh.installVerifying");case "testing":- return "试运行";+ return t("pwsh.installTesting");case "done":- return "已装好";+ return t("pwsh.installDone");case "failed":- return `没装上:${p.error ?? "未知原因"}`;+ return t("pwsh.installFailed", { error: p.error ?? t("pwsh.unknownReason") });default:return "";}}-const SLOW = "代理执行命令用的是系统自带的 Windows PowerShell 5.1,每条可能要二三十秒";+/** "代理在用 5.1,每条要二三十秒":按当前语言,用的时候才取 */+const slow = () => t("pwsh.slow");-/** 聊天里 /status 的一行(只在 Windows 上有) */+/** 聊天里 /status 的一行(只在 Windows 上有;按当前语言,读的时候才拼) */export function pwshStatusLine(st: PwshStatus): string {if (!st.applicable) return "";- if (st.checking) return "PowerShell:检测中";- const fb = st.fallback ? `;之前用的 ${st.fallback.from} 起不来(${st.fallback.reason.slice(0, 120)}),已自动换掉` : "";- if (!st.missing) return `PowerShell:${st.version ?? "7"}(${st.source === "private" ? "应用内置," : ""}代理用它执行命令)${fb}`;+ if (st.checking) return t("pwsh.statusChecking");+ const fb = st.fallback ? t("pwsh.statusFallback", { from: st.fallback.from, reason: st.fallback.reason.slice(0, 120) }) : "";+ if (!st.missing) return t(st.source === "private" ? "pwsh.statusOkPrivate" : "pwsh.statusOk", { version: st.version ?? "7" }) + fb;const p = st.private;- if (p && isInstalling(p.install)) return `PowerShell:正在为代理安装 PowerShell 7…${installProgressText(p.install)}。装好之前命令照常用 Windows PowerShell 5.1`;- if (p?.bad && st.mode !== "system") return `PowerShell:应用内置的 PowerShell 7 用不了(${p.bad.reason.slice(0, 160)}),${SLOW}。在 设置 → 故障排查 里可以一键重新安装`;- if (p?.install.state === "failed" && st.mode !== "system") return `PowerShell:为代理安装 PowerShell 7 没有成功(${p.install.error ?? "未知原因"}),${SLOW}。在 设置 → 故障排查 里可以重试,或者自己安装:${PWSH_WINGET}`;- if (p && !p.supported && p.reason) return `PowerShell:${p.reason},${SLOW}`;- const now = st.systemIssue ? `系统里的 PowerShell 7 用不了(${st.systemIssue.slice(0, 120)}),${SLOW}` : st.found && st.version ? `PowerShell ${st.version} 版本较旧,${SLOW}` : `没有安装 PowerShell 7,${SLOW}`;- const how = st.mode === "system" || !p?.supported ? `装上 PowerShell 7,命令执行快得多,也更稳定:${PWSH_WINGET}(或打开 ${PWSH_INSTALL_URL})` : `应用可以自己装一份(不需要管理员权限):设置 → 故障排查 → 安装;或者:${PWSH_WINGET}`;- return `PowerShell:${now}。${how}`;+ if (p && isInstalling(p.install)) return t("pwsh.statusInstalling", { progress: installProgressText(p.install) });+ if (p?.bad && st.mode !== "system") return t("pwsh.statusPrivateBad", { reason: p.bad.reason.slice(0, 160), slow: slow() });+ if (p?.install.state === "failed" && st.mode !== "system") return t("pwsh.statusInstallFailed", { error: p.install.error ?? t("pwsh.unknownReason"), slow: slow(), winget: PWSH_WINGET });+ if (p && !p.supported && p.reason) return t("pwsh.statusUnsupported", { reason: p.reason, slow: slow() });+ const now = st.systemIssue+ ? t("pwsh.statusSystemIssue", { issue: st.systemIssue.slice(0, 120), slow: slow() })+ : st.found && st.version+ ? t("pwsh.statusOld", { version: st.version, slow: slow() })+ : t("pwsh.statusNone", { slow: slow() });+ const how = st.mode === "system" || !p?.supported ? t("pwsh.adviceInstall", { winget: PWSH_WINGET, url: PWSH_INSTALL_URL }) : t("pwsh.advicePrivate", { winget: PWSH_WINGET });+ return t("pwsh.statusAdvice", { now, how });}/** 诊断报告里的 PowerShell 行(只在 Windows 上有;内置副本另起一行) */export function pwshReportLine(st: PwshStatus): string | undefined {if (!st.applicable) return undefined;- if (st.checking) return "[PowerShell] 检测中";- const where = st.path ? ` · ${st.path}(${SOURCE[st.source!] ?? st.source})` : "";+ if (st.checking) return t("pwsh.reportChecking");+ const source = st.source && SOURCE[st.source] ? t(SOURCE[st.source]) : st.source;+ const where = st.path ? t("pwsh.reportWhere", { path: st.path, source }) : "";const lines: string[] = [];- if (!st.missing) lines.push(`[PowerShell] ${st.version ?? "7(版本未知)"}${where} · 代理用它执行命令`);- else if (st.systemIssue) lines.push(`[PowerShell] 系统里的 PowerShell 7 用不了${where} · ${st.systemIssue} · 代理用 ${st.using ?? "Windows PowerShell 5.1(DSH 默认)"}`);- else if (st.found) lines.push(`[PowerShell] ${st.version ?? "?"} 版本较旧${where} · 建议安装 PowerShell 7`);- else lines.push(`[PowerShell] 未安装 PowerShell 7:代理用 Windows PowerShell 5.1 执行命令(经沙箱每条约 25 秒,7 约 1 秒)${st.forced ? " · AMB_PWSH_FORCE 模拟" : ""}`);- if (st.fallback) lines.push(` 自动退回 ${new Date(st.fallback.at).toISOString()}:${st.fallback.from} → ${st.fallback.to ?? "DSH 默认"} · ${st.fallback.reason}`);+ if (!st.missing) lines.push(t("pwsh.reportOk", { version: st.version ?? t("pwsh.reportUnknownVersion"), where }));+ else if (st.systemIssue) lines.push(t("pwsh.reportSystemIssue", { where, issue: st.systemIssue, using: st.using ?? t("pwsh.reportDshDefault51") }));+ else if (st.found) lines.push(t("pwsh.reportOld", { version: st.version ?? "?", where }));+ else lines.push(t("pwsh.reportNone", { forced: st.forced ? t("pwsh.reportForced") : "" }));+ if (st.fallback) lines.push(t("pwsh.reportFallback", { at: new Date(st.fallback.at).toISOString(), from: st.fallback.from, to: st.fallback.to ?? t("pwsh.reportDshDefault"), reason: st.fallback.reason }));const p = st.private;if (p) {const state = !p.supported- ? `不能装:${p.reason ?? "?"}`+ ? t("pwsh.privateUnsupported", { reason: p.reason ?? "?" }): p.ready- ? `已就绪 · 试运行通过${p.test ? `(${p.test.ms} ms,${new Date(p.test.at).toISOString()})` : ""}`+ ? t("pwsh.privateReady", { test: p.test ? t("pwsh.privateTest", { ms: p.test.ms, at: new Date(p.test.at).toISOString() }) : "" }): p.bad- ? `用不了:${p.bad.reason}`+ ? t("pwsh.privateBad", { reason: p.bad.reason }): p.installed- ? "已装,还没试运行"- : "未安装";- const inst = p.install.state !== "idle" ? ` · 安装:${installProgressText(p.install)}` : "";- lines.push(` 内置 PowerShell ${p.version}${p.arch ? ` ${p.arch}` : ""} · ${state}${inst}${p.dir ? ` · ${p.dir}` : ""} · ${st.mode === "system" ? "已改回系统默认" : st.autoInstall ? "缺 7 时自动安装" : "不自动安装"}${st.ignoreSystem ? " · AMB_PWSH_IGNORE_SYSTEM=1" : ""}`);+ ? t("pwsh.privateUntested")+ : t("pwsh.privateNotInstalled");+ const inst = p.install.state !== "idle" ? t("pwsh.privateInstall", { progress: installProgressText(p.install) }) : "";+ const policy = st.mode === "system" ? t("pwsh.policySystem") : st.autoInstall ? t("pwsh.policyAuto") : t("pwsh.policyManual");+ lines.push(+ t("pwsh.privateLine", { version: p.version, arch: p.arch ? ` ${p.arch}` : "", state, inst, dir: p.dir ? ` · ${p.dir}` : "", policy, ignore: st.ignoreSystem ? " · AMB_PWSH_IGNORE_SYSTEM=1" : "" }),+ );}return lines.join("\n");}diff --git a/src/app.ts b/src/app.tsindex c767487..d82ba5d 100644--- a/src/app.ts+++ b/src/app.ts@@ -43,14 +43,18 @@ import { MediaService, pickDefault } from "./agent/media.js";import { COMPACT_ENDPOINT, serverCompactionEnabled, type CompactEndpoint } from "./agent/server-compaction.js";import type { BotSettings } from "./agent/settings.js";import { TaskService } from "./tasks/service.js";+import { detached, setLangPref, t } from "./i18n/index.js";const log = logger("app");+/** 桌面外壳(Electron 主进程)提供的能力;CLI / Docker 下为空 */export interface DesktopHooks {autostart(): { supported: boolean; on: boolean };setAutostart(on: boolean): void;applyZoom(zoom: number): void;+ /** Windows 桌面版:窗口右上角的最小化 / 最大化 / 关闭由系统画在界面上,符号颜色跟界面主题(主题只存在界面里) */+ setTitleBarTheme?(dark: boolean): void;openDataDir(): void;openInBrowser(): void;/** 在系统浏览器里打开外部链接(Modelflare 登录、充值) */@@ -134,6 +138,8 @@ export class App {private modelInfoLoading: Promise<Record<string, ModelInfo>> | undefined;constructor(readonly config: AppConfig, readonly opts: AppOptions = {}) {+ // 应用语言(托盘菜单、后台和发到微信 / 飞书的系统消息用它;界面请求用请求自己的语言,见 src/i18n)+ setLangPref(config.ui.lang);// 日志文件:<dataDir>/logs/app.log(打包后的桌面版看不到 stdout,故障排查全靠它)if (opts.fileLog !== false) initFileLog(path.join(config.dataDir, "logs"));registerSecret(config.ui.token);@@ -342,7 +348,7 @@ export class App {},disconnect: () => this.disconnectModelflare(),setBotKey: async (botId, key) => {- if (!this.magpie) throw new Error("外部模型端点模式下不管理 Modelflare 连接");+ if (!this.magpie) throw new Error(t("app.external_mode"));const baseUrl = modelflareBaseUrl(this.config.modelflare.line);const r = await verifyModelflareKey(baseUrl, key, { line: this.config.modelflare.line });if (!r.ok) throw new Error(r.message);@@ -385,7 +391,7 @@ export class App {/** 开启 / 调整 / 关闭机器人预算:先改 Modelflare 上的 Key,成功后才保存设置 */async setBotBudget(botId: string, budget: BotSettings["budget"]): Promise<Bot> {const bot = this.store.getBot(botId);- if (!bot) throw new Error("机器人不存在");+ if (!bot) throw new Error(t("app.bot_not_found"));await this.account.setBotBudget(bot.id, bot.name, budget);return this.store.updateBot(botId, { settings: { ...bot.settings, budget } })!;}@@ -442,7 +448,7 @@ export class App {try {await this.magpie.start();} catch (e) {- this.notice("warn", `magpie 启动失败:${(e as Error).message}`);+ this.notice("warn", t("app.magpie_failed", { message: (e as Error).message }));}}this.agent.start();@@ -550,7 +556,7 @@ export class App {/** 先校验(GET /models),通过后才写入网关;失败时什么都不改 */async connectModelflare(apiKey: string, line: ModelflareLine): Promise<VerifyResult> {- if (!this.magpie) throw new Error("外部模型端点模式下不管理 Modelflare 连接");+ if (!this.magpie) throw new Error(t("app.external_mode"));const baseUrl = modelflareBaseUrl(line);const r = await verifyModelflareKey(baseUrl, apiKey.trim(), { line });if (!r.ok) return r;@@ -574,7 +580,7 @@ export class App {}async disconnectModelflare(): Promise<void> {- if (!this.magpie) throw new Error("外部模型端点模式下不管理 Modelflare 连接");+ if (!this.magpie) throw new Error(t("app.external_mode"));await this.magpie.disconnectModelflare();await this.runtime.listModels(true).catch(() => []);}@@ -612,8 +618,8 @@ export class App {if (this.store.listBots().length) return;const bot = this.store.createBot({id: "default",- name: "我的助手",- systemPrompt: "你是一个乐于助人的中文助手,回答简洁准确。",+ name: t("app.default_bot_name"),+ systemPrompt: t("app.default_bot_prompt"),feishuAppId: process.env.FEISHU_APP_ID ?? "",feishuAppSecret: process.env.FEISHU_APP_SECRET ?? "",weixinEnabled: true,@@ -636,9 +642,10 @@ export class App {const fs = ch.feishu;this.runtime.registerReplier(bot.id, "feishu", (conv, handle, key) => (handle?.messageId ? { out: fs.followUp(conv.peerId, handle.messageId, key) } : undefined));ch.feishuError = undefined;- ch.feishu.start().catch((e) => {+ const feishu = ch.feishu;+ detached(() => feishu.start()).catch((e) => {ch.feishuError = (e as Error).message;- this.notice("warn", `机器人「${bot.name}」飞书长连接启动失败:${ch.feishuError}`);+ this.notice("warn", t("app.feishu_failed", { name: bot.name, message: ch.feishuError }));});log.info(`bot ${bot.id}: feishu starting`, { appId: bot.feishuAppId, secret: mask(bot.feishuAppSecret) });}@@ -649,11 +656,11 @@ export class App {pollTimeoutMs: this.opts.weixinPollTimeoutMs,outbox: this.outbox,});- ch.weixin.onExpired = () => this.notice("warn", `机器人「${bot.name}」微信登录已过期,请在信息面板的「渠道」里重新扫码`);+ ch.weixin.onExpired = () => this.notice("warn", t("app.weixin_expired", { name: bot.name }));const wx = ch.weixin;// 代理自己醒来的一轮:经出站队列发给这个微信用户(发送时才查 24 小时窗口和配额)this.runtime.registerReplier(bot.id, "weixin", (conv, _handle, key) => ({ out: wx.followUp(conv.peerId, key) }));- ch.weixin.start();+ detached(() => wx.start());}}@@ -699,7 +706,7 @@ export class App {await ch.weixin?.stop();ch.weixin = undefined;await this.startBot(botId);- this.notice("info", `机器人「${bot?.name ?? botId}」微信已连接`);+ this.notice("info", t("app.weixin_connected", { name: bot?.name ?? botId }));});return login;}@@ -716,12 +723,12 @@ export class App {const bot = this.store.getBot(botId);const ch = this.channels.get(botId);const feishu: ChannelStatus = !bot?.feishuAppId- ? { state: "disabled", detail: "未配置凭据", since: 0 }+ ? { state: "disabled", detail: t("channel.feishu_no_credentials"), since: 0 }: ch?.feishuError? { state: "error", detail: ch.feishuError, since: Date.now() }: ch?.feishu?.status ?? { state: "disabled", since: 0 };const acct = this.store.getWeixinAccount(botId);- const wx = ch?.weixin?.status ?? (acct ? { state: "disabled" as const, since: 0 } : { state: "login_required" as const, detail: "尚未扫码登录", since: 0 });+ const wx = ch?.weixin?.status ?? (acct ? { state: "disabled" as const, since: 0 } : { state: "login_required" as const, detail: t("channel.wx_login_required"), since: 0 });const quota = ch?.weixin? this.store.listWeixinPeers(botId).map((p) => ({ userId: p.userId, remaining: ch.weixin!.quota.remaining(p.userId), windowStartedAt: p.windowStartedAt })): [];diff --git a/src/channels/feishu/card.ts b/src/channels/feishu/card.tsindex 30ea861..2e632d2 100644--- a/src/channels/feishu/card.ts+++ b/src/channels/feishu/card.ts@@ -5,6 +5,7 @@ import { Gone, ReplyIds, stableId, type Outbox } from "../../core/outbox.js";import type { OutboxBody, OutboxKind, OutboxRow } from "../../store/db.js";import { CARD_ELEMENT_ID, actionCardSpec, type FeishuTransport } from "./transport.js";import { logger } from "../../log.js";+import { t } from "../../i18n/index.js";const log = logger("feishu.card");@@ -145,7 +146,7 @@ export class FeishuReply implements ReplySession {return this.post("file", { path: op.path, name: op.name }, this.ids.of("file", op.path));case "interactive": {const text = op.requestId ? op.prompt : `${op.prompt}${op.options?.length ? "\n" + op.options.map((o, i) => `${i + 1}. ${o}`).join("\n") : ""}`;- const title = op.kind === "approval" ? `需批准(${op.code ?? ""})` : "需要你的回答";+ const title = op.kind === "approval" ? t("channel.approval_title", { code: op.code ?? "" }) : t("channel.question_title");const card = op.buttons?.length ? actionCardSpec(title, op.prompt, op.buttons) : undefined;// 审批/提问十分钟后过期,发不出去就不必再等return this.post(card ? "card" : "text", { text, ...(card ? { card } : {}) }, this.ids.of("prompt", op.requestId ?? text), 10 * 60_000);diff --git a/src/channels/feishu/channel.ts b/src/channels/feishu/channel.tsindex 93b586f..4654b00 100644--- a/src/channels/feishu/channel.ts+++ b/src/channels/feishu/channel.ts@@ -6,6 +6,7 @@ import { FeishuReply, deliverFeishu } from "./card.js";import { Outbox, stableId } from "../../core/outbox.js";import type { Store } from "../../store/db.js";import { logger } from "../../log.js";+import { t } from "../../i18n/index.js";export const FEISHU_CAPS: ChannelCapabilities = {streaming: true,@@ -44,7 +45,7 @@ export function feishuParts(ev: FeishuMessageEvent): Part[] {case "audio":return [{ type: "voice", ref: c.file_key }];default:- return [{ type: "text", text: `[暂不支持的消息类型:${ev.messageType}]` }];+ return [{ type: "text", text: t("channel.unsupported_message", { type: ev.messageType }) }];}}@@ -128,7 +129,7 @@ export class FeishuChannel {await this.runtime.handle(inbound, reply);} catch (e) {this.log.error("handle failed", { message: (e as Error).message });- await reply.apply({ type: "text", text: `⚠️ 处理失败:${(e as Error).message}` }).catch(() => {});+ await reply.apply({ type: "text", text: t("channel.handle_failed", { message: (e as Error).message }) }).catch(() => {});}});this.pending.add(p);diff --git a/src/channels/feishu/transport.ts b/src/channels/feishu/transport.tsindex 34bfad0..b82853d 100644--- a/src/channels/feishu/transport.ts+++ b/src/channels/feishu/transport.ts@@ -3,6 +3,7 @@ import path from "node:path";import * as Lark from "@larksuiteoapi/node-sdk";import { randomUUID } from "node:crypto";import { logger } from "../../log.js";+import { t } from "../../i18n/index.js";const FEISHU_IMAGE_EXT = new Set(["png", "jpg", "jpeg", "gif", "webp", "bmp"]);const FEISHU_FILE_TYPES: Record<string, string> = {@@ -62,7 +63,7 @@ export function streamingCardSpec(initial: string) {schema: "2.0",config: {streaming_mode: true,- summary: { content: "[生成中…]" },+ summary: { content: t("channel.card_generating") },streaming_config: {print_frequency_ms: { default: 50 },print_step: { default: 2 },@@ -140,7 +141,7 @@ export class LarkTransport implements FeishuTransport {return { toast: { type: r.ok ? "success" : "warning", content: r.toast } };} catch (e) {this.log.warn("card action failed", { message: (e as Error).message });- return { toast: { type: "error", content: "处理失败" } };+ return { toast: { type: "error", content: t("channel.card_action_failed") } };}},"im.message.receive_v1": async (data: any) => {diff --git a/src/channels/weixin/api.ts b/src/channels/weixin/api.tsindex 5cc4649..c004a23 100644--- a/src/channels/weixin/api.ts+++ b/src/channels/weixin/api.ts@@ -7,6 +7,7 @@import crypto from "node:crypto";import fs from "node:fs/promises";import path from "node:path";+import { t } from "../../i18n/index.js";export const ILINK_APP_ID = "bot";export const DEFAULT_ILINK_BASE = "https://ilinkai.weixin.qq.com";@@ -43,7 +44,7 @@ export function parseAesKey(aesKeyBase64: string): Buffer {if (decoded.length === 16) return decoded;const ascii = decoded.toString("ascii");if (decoded.length === 32 && /^[0-9a-fA-F]{32}$/.test(ascii)) return Buffer.from(ascii, "hex");- throw new Error(`aes_key 解码后为 ${decoded.length} 字节,应为 16 字节或 32 位十六进制`);+ throw new Error(t("channel.aes_key_bad", { len: decoded.length }));}export type ImageMime = "image/png" | "image/jpeg" | "image/gif" | "image/webp";@@ -398,14 +399,14 @@ export class IlinkClient {} else if (item.type === MessageItemType.FILE || item.type === MessageItemType.VIDEO) {kind = item.type === MessageItemType.FILE ? "file" : "video";media = kind === "file" ? item.file_item?.media : item.video_item?.media;- if (!media?.aes_key) throw new Error("缺少 aes_key");+ if (!media?.aes_key) throw new Error(t("channel.aes_key_missing"));key = parseAesKey(media.aes_key);} else {- throw new Error(`不支持下载的条目类型 ${item.type}`);+ throw new Error(t("channel.item_unsupported", { type: item.type }));}const full = media?.full_url?.trim();- if (full && !/^https?:\/\//i.test(full)) throw new Error("full_url 不是 http(s) 地址");- if (!full && !media?.encrypt_query_param) throw new Error("没有 CDN 引用");+ if (full && !/^https?:\/\//i.test(full)) throw new Error(t("channel.full_url_bad"));+ if (!full && !media?.encrypt_query_param) throw new Error(t("channel.no_cdn_ref"));const url = full || `${this.cdnBase}/download?encrypted_query_param=${encodeURIComponent(media!.encrypt_query_param!)}`;let raw: Buffer | undefined;@@ -415,28 +416,28 @@ export class IlinkClient {const res = await this.fetchImpl(url, { signal: AbortSignal.timeout(CDN_TIMEOUT_MS) });if (!res.ok) {await res.arrayBuffer().catch(() => {});- const err = new Error(`CDN 下载失败 HTTP ${res.status} ${res.headers.get("x-error-message") ?? ""}`.trim());+ const err = new Error(t("channel.cdn_failed_http", { status: res.status, message: res.headers.get("x-error-message") ?? "" }).trim());throw res.status < 500 ? Object.assign(err, { fatal: true }) : err;}const declared = Number(res.headers.get("content-length") ?? 0);if (declared > maxBytes) {await res.body?.cancel().catch(() => {});- throw Object.assign(new Error(`文件过大(${(declared / 1048576).toFixed(1)} MB,上限 ${maxBytes / 1048576} MB)`), { fatal: true });+ throw Object.assign(new Error(t("channel.too_large", { size: (declared / 1048576).toFixed(1), max: maxBytes / 1048576 })), { fatal: true });}const buf = Buffer.from(await res.arrayBuffer());- if (buf.length > maxBytes) throw Object.assign(new Error(`文件过大(${(buf.length / 1048576).toFixed(1)} MB,上限 ${maxBytes / 1048576} MB)`), { fatal: true });+ if (buf.length > maxBytes) throw Object.assign(new Error(t("channel.too_large", { size: (buf.length / 1048576).toFixed(1), max: maxBytes / 1048576 })), { fatal: true });raw = buf;} catch (e) {lastErr = e;if ((e as { fatal?: boolean }).fatal) throw e;}}- if (!raw) throw lastErr instanceof Error ? lastErr : new Error("CDN 下载失败");+ if (!raw) throw lastErr instanceof Error ? lastErr : new Error(t("channel.cdn_failed"));let data: Buffer;try {data = key ? decryptAesEcb(raw, key) : raw;} catch {- throw new Error("解密失败(密钥不对?)");+ throw new Error(t("channel.decrypt_failed"));}if (kind === "image") return { kind, data, mime: sniffImageMime(data) };if (kind === "file") return { kind, data, name: item.file_item?.file_name || "file" };diff --git a/src/channels/weixin/channel.ts b/src/channels/weixin/channel.tsindex 6d02d50..6e75e02 100644--- a/src/channels/weixin/channel.ts+++ b/src/channels/weixin/channel.ts@@ -9,6 +9,7 @@ import { IlinkClient, MessageItemType, MessageType, WeixinApiError, hasDownloadaimport { StreamingMarkdownFilter } from "./markdown-filter.js";import { WeixinQuota } from "./quota.js";import { logger } from "../../log.js";+import { t } from "../../i18n/index.js";export const WEIXIN_CAPS: ChannelCapabilities = {streaming: false,@@ -225,7 +226,7 @@ export class WeixinReply implements ReplySession {case "interactive": {const text = op.requestId? op.prompt // 代理请求:提示里已含编号/回复方式- : `${op.prompt}${op.options?.length ? "\n" + op.options.map((o, i) => `${i + 1}. ${o}`).join("\n") + "\n(回复编号选择)" : ""}`;+ : `${op.prompt}${op.options?.length ? "\n" + op.options.map((o, i) => `${i + 1}. ${o}`).join("\n") + "\n" + t("channel.reply_with_number") : ""}`;return this.enqueue(async () => {await this.post("text", { text, raw: !!op.requestId }, this.ids.of("prompt", op.requestId ?? text), SHORT_TTL_MS);if (this.typingOn) await this.typing(true);@@ -278,7 +279,14 @@ export class WeixinReply implements ReplySession {/** 微信 iLink 渠道:getupdates 长轮询 → 每用户串行队列 → 运行时。 */export class WeixinChannel {readonly caps = WEIXIN_CAPS;- status: ChannelStatus = { state: "disabled", since: Date.now() };+ private st: ChannelStatus = { state: "disabled", since: Date.now() };++ /** 尚未扫码、登录过期的说明读的时候再翻译(界面换了语言跟着变) */+ get status(): ChannelStatus {+ if (this.st.state === "login_required") return { ...this.st, detail: t("channel.wx_login_required") };+ if (this.st.state === "expired") return { ...this.st, detail: t("channel.wx_expired") };+ return this.st;+ }private client: IlinkClient | undefined;private abort: AbortController | undefined;private loop: Promise<void> | undefined;@@ -315,7 +323,7 @@ export class WeixinChannel {if (this.loop) return;const acct = this.store.getWeixinAccount(this.botId);if (!acct) {- this.status = { state: "login_required", detail: "尚未扫码登录", since: Date.now() };+ this.st = { state: "login_required", since: Date.now() };return;}this.client = new IlinkClient({ baseUrl: acct.baseUrl, token: acct.botToken, fetchImpl: this.opts.fetchImpl, cdnBaseUrl: this.opts.cdnBaseUrl });@@ -371,7 +379,7 @@ export class WeixinChannel {this.abort?.abort();await this.loop?.catch(() => {});this.loop = undefined;- if (this.status.state !== "expired") this.status = { state: "disabled", since: Date.now() };+ if (this.st.state !== "expired") this.st = { state: "disabled", since: Date.now() };}private sleep(ms: number, signal: AbortSignal): Promise<void> {@@ -386,22 +394,22 @@ export class WeixinChannel {private async run(signal: AbortSignal): Promise<void> {let failures = 0;- this.status = { state: "connecting", since: Date.now() };+ this.st = { state: "connecting", since: Date.now() };while (!signal.aborted) {const acct = this.store.getWeixinAccount(this.botId);if (!acct) {- this.status = { state: "login_required", detail: "尚未扫码登录", since: Date.now() };+ this.st = { state: "login_required", since: Date.now() };return;}if (acct.pausedUntil > Date.now()) {- this.status = { state: "expired", detail: "登录已过期(-14),请在界面重新扫码", since: Date.now() };+ this.st = { state: "expired", since: Date.now() };await this.sleep(Math.min(acct.pausedUntil - Date.now(), 60_000), signal);continue;}try {const resp = await this.client!.getUpdates(acct.cursor, this.opts.pollTimeoutMs ?? 35_000, signal);failures = 0;- if (this.status.state !== "connected") this.status = { state: "connected", since: Date.now() };+ if (this.st.state !== "connected") this.st = { state: "connected", since: Date.now() };if (resp.get_updates_buf) this.store.setWeixinCursor(this.botId, resp.get_updates_buf);for (const m of resp.msgs ?? []) this.onMessage(m);} catch (e) {@@ -409,12 +417,12 @@ export class WeixinChannel {if (e instanceof WeixinApiError && e.sessionExpired) {this.log.warn(`bot ${this.botId}: iLink session expired (-14), pausing 1h; re-login required`);this.store.setWeixinPaused(this.botId, Date.now() + SESSION_PAUSE_MS);- this.status = { state: "expired", detail: "登录已过期(-14),请在界面重新扫码", since: Date.now() };+ this.st = { state: "expired", since: Date.now() };this.onExpired?.(this.botId);continue;}failures++;- this.status = { state: "error", detail: (e as Error).message, since: Date.now() };+ this.st = { state: "error", detail: (e as Error).message, since: Date.now() };this.log.warn("getupdates failed", { failures, message: (e as Error).message });await this.sleep(failures >= 3 ? this.opts.backoffMs ?? 30_000 : this.opts.retryDelayMs ?? 2000, signal);if (failures >= 3) failures = 0;@@ -458,7 +466,7 @@ export class WeixinChannel {await this.runtime.handle(ev, reply);} catch (e) {this.log.error("handle failed", { message: (e as Error).message });- await reply.apply({ type: "text", text: `⚠️ 处理失败:${(e as Error).message}` }).catch(() => {});+ await reply.apply({ type: "text", text: t("channel.handle_failed", { message: (e as Error).message }) }).catch(() => {});}});this.pending.add(p);diff --git a/src/channels/weixin/login.ts b/src/channels/weixin/login.tsindex 5f9e68d..21f58c8 100644--- a/src/channels/weixin/login.ts+++ b/src/channels/weixin/login.ts@@ -7,6 +7,7 @@ import path from "node:path";import QRCode from "qrcode";import { IlinkClient, type QrStatusResp } from "./api.js";import { logger } from "../../log.js";+import { t } from "../../i18n/index.js";const log = logger("weixin.login");const MAX_QR_REFRESH = 3;@@ -72,7 +73,7 @@ export class WeixinLogin {cancel(): void {this.abort.abort();- if (!["confirmed", "failed", "already_bound"].includes(this.snapshot.state)) this.set({ state: "cancelled", message: "已取消" });+ if (!["confirmed", "failed", "already_bound"].includes(this.snapshot.state)) this.set({ state: "cancelled", message: t("channel.login_cancelled") });}private async showQr(client: IlinkClient): Promise<string> {@@ -85,10 +86,10 @@ export class WeixinLogin {}if (this.opts.printTerminal) {const qt = (await import("qrcode-terminal")).default;- qt.generate(content, { small: true }, (s: string) => process.stdout.write(`\n用微信扫描二维码登录:\n${s}\n`));- if (this.opts.pngPath) process.stdout.write(`二维码图片已保存:${this.opts.pngPath}\n`);+ qt.generate(content, { small: true }, (s: string) => process.stdout.write(`\n${t("channel.login_terminal_scan")}\n${s}\n`));+ if (this.opts.pngPath) process.stdout.write(`${t("channel.login_terminal_saved", { path: this.opts.pngPath })}\n`);}- this.set({ state: "wait", message: "请用微信扫码", qrContent: content, qrDataUrl, qrPngPath: this.opts.pngPath });+ this.set({ state: "wait", message: t("channel.login_wait"), qrContent: content, qrDataUrl, qrPngPath: this.opts.pngPath });return qr.qrcode;}@@ -99,7 +100,7 @@ export class WeixinLogin {const deadline = Date.now() + LOGIN_TIMEOUT_MS;let refreshCount = 0;try {- this.set({ state: "fetching", message: "正在获取二维码…", refreshCount });+ this.set({ state: "fetching", message: t("channel.login_fetching"), refreshCount });let qrcode = await this.showQr(client);while (!signal.aborted && Date.now() < deadline) {let st: QrStatusResp;@@ -110,10 +111,10 @@ export class WeixinLogin {case "wait":break;case "scaned":- if (this.snapshot.state !== "scaned") this.set({ state: "scaned", message: "已扫码,请在微信上确认" });+ if (this.snapshot.state !== "scaned") this.set({ state: "scaned", message: t("channel.login_scanned") });break;case "need_verifycode":- if (this.snapshot.state !== "need_verifycode") this.set({ state: "need_verifycode", message: "请输入微信上显示的验证码" });+ if (this.snapshot.state !== "need_verifycode") this.set({ state: "need_verifycode", message: t("channel.login_need_code") });break;case "scaned_but_redirect":if (st.redirect_host) {@@ -122,24 +123,24 @@ export class WeixinLogin {}break;case "binded_redirect":- this.set({ state: "already_bound", message: "该微信已绑定过此机器人,无需重复连接" });+ this.set({ state: "already_bound", message: t("channel.login_already_bound") });return undefined;case "expired":case "verify_code_blocked":refreshCount++;if (refreshCount > MAX_QR_REFRESH) {- this.set({ state: "failed", message: "二维码多次过期,请重新开始登录" });+ this.set({ state: "failed", message: t("channel.login_qr_expired_too_often") });return undefined;}- this.set({ refreshCount, message: `二维码已过期,正在刷新(${refreshCount}/${MAX_QR_REFRESH})` });+ this.set({ refreshCount, message: t("channel.login_qr_refreshing", { n: refreshCount, max: MAX_QR_REFRESH }) });qrcode = await this.showQr(client);break;case "confirmed": {if (!st.ilink_bot_id || !st.bot_token) {- this.set({ state: "failed", message: "登录失败:服务器未返回 ilink_bot_id/bot_token" });+ this.set({ state: "failed", message: t("channel.login_no_token") });return undefined;}- this.set({ state: "confirmed", message: "✅ 微信已连接", qrDataUrl: undefined, qrContent: undefined });+ this.set({ state: "confirmed", message: t("channel.login_confirmed"), qrDataUrl: undefined, qrContent: undefined });log.info("weixin login confirmed", { ilinkBotId: st.ilink_bot_id });return {botToken: st.bot_token,@@ -151,11 +152,11 @@ export class WeixinLogin {}await new Promise((r) => setTimeout(r, this.opts.pollDelayMs ?? 1000));}- if (!signal.aborted) this.set({ state: "failed", message: "登录超时,请重试" });+ if (!signal.aborted) this.set({ state: "failed", message: t("channel.login_timeout") });return undefined;} catch (e) {if (signal.aborted) return undefined;- this.set({ state: "failed", message: `登录失败:${(e as Error).message}` });+ this.set({ state: "failed", message: t("channel.login_failed", { message: (e as Error).message }) });return undefined;}}diff --git a/src/config.ts b/src/config.tsindex 31c91d2..68d5001 100644--- a/src/config.ts+++ b/src/config.ts@@ -1,6 +1,8 @@import fs from "node:fs";import path from "node:path";import { normalizeLine, type ModelflareLine } from "./modelflare.js";+import { normalizeGuide, type GuideState } from "./guide.js";+import { normalizeLangPref, type LangPref } from "./i18n/index.js";/*** 配置:<dataDir>/config.json + 环境变量(环境变量优先)。@@ -18,6 +20,10 @@ export interface AppConfig {closeToTray: boolean;/** Windows 上"建议安装 PowerShell 7"的提示点过"不再提示" */pwshHintDismissed: boolean;+ /** 新手引导(上手清单)的进度,见 src/guide.ts */+ guide: GuideState;+ /** 界面语言:system 跟随系统,或 zh-CN / en;托盘菜单和机器人发出的系统消息也用它(src/i18n) */+ lang: LangPref;};/*** Modelflare 线路;密钥本身只存在内置 magpie 的隔离配置里。@@ -77,6 +83,8 @@ export function loadConfig(overrides: { dataDir?: string; env?: NodeJS.ProcessEnzoom: ZOOMS.includes(Number(file.ui?.zoom)) ? Number(file.ui?.zoom) : 1,closeToTray: file.ui?.closeToTray !== false,pwshHintDismissed: file.ui?.pwshHintDismissed === true,+ guide: normalizeGuide(file.ui?.guide),+ lang: normalizeLangPref(file.ui?.lang),},modelflare: {line: normalizeLine(file.modelflare?.line),diff --git a/src/core/runtime.ts b/src/core/runtime.tsindex 34ee6c9..eae4a35 100644--- a/src/core/runtime.ts+++ b/src/core/runtime.ts@@ -18,6 +18,7 @@ import { isBotProviderModel } from "../modelflare.js";import type { ApprovalRow, Conversation } from "../store/db.js";import type { AccessControl } from "./access.js";import { takeTaskNotes } from "../tasks/service.js";+import { t } from "../i18n/index.js";const log = logger("runtime");@@ -103,18 +104,7 @@ export interface RuntimeOptions {access?: AccessControl;}-const HELP = [- "可用命令:",- "/model — 列出可用模型(带编号)",- "/model <编号或模型名> — 切换当前会话的模型",- "/reset — 清空当前会话的上下文(代理模式下同时开启新的代理会话;长期记忆保留)",- "/new — 开始新的一段对话:旧对话归档并生成交接便条,长期记忆保留",- "/status — 查看当前模型、代理状态和正在处理的消息走到了哪一步",- "/stop — 中止正在处理的消息(只停这个会话,机器人的其它会话照常进行)",- "/tasks — 列出这个会话的后台任务",- "/stop <编号> — 停止 /tasks 里的一个后台任务",- "/help — 显示本帮助",-].join("\n");+const help = () => t("runtime.help");/** 一条正在处理的消息(各渠道都有):/stop、网页的停止按钮经 abort 中止它 */interface Inflight {@@ -207,7 +197,7 @@ 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("没有可用模型:请先连接 Modelflare(设置 → Modelflare)");+ if (!list.length) throw new Error(t("runtime.noModels"));return list[0];}@@ -274,9 +264,9 @@ export class BotRuntime {};}- private async handleMessage(ev: InboundEvent, out: ReplySession, bot: NonNullable<ReturnType<Store["getBot"]>>, convId: string, t: Inflight, prior: Promise<void> | undefined): Promise<void> {+ private async handleMessage(ev: InboundEvent, out: ReplySession, bot: NonNullable<ReturnType<Store["getBot"]>>, convId: string, run: Inflight, prior: Promise<void> | undefined): Promise<void> {const { store } = this.opts;- const signal = t.abort.signal;+ const signal = run.abort.signal;const agent = this.opts.agent;// 代理模式:收到的图片/文件先进工作区,消息里写路径if (agent?.available) storeInbound(agent.host(bot.id).workspace, ev);@@ -290,10 +280,10 @@ export class BotRuntime {// 前面还有消息在处理:代理回合进行中就把这条并进去(模型下一步看到,回复一起给),否则排在它们后面。// 命令(/model、/reset…)不并入,等前面的处理完if (prior) {- if (agent?.available && !signal.aborted && !text.startsWith("/") && (await this.steer(agent, bot.id, convId, text, images, out, t))) {+ if (agent?.available && !signal.aborted && !text.startsWith("/") && (await this.steer(agent, bot.id, convId, text, images, out, run))) {await prior;// 应用正在退出、它并进的那一轮没做完:重启标记留着(下次启动告诉用户)- if (this.closing) t.interrupted = true;+ if (this.closing) run.interrupted = true;return;}await prior;@@ -303,9 +293,9 @@ export class BotRuntime {// 排队时就被停止了:不再处理(命令也不执行),留一句"已中止"if (signal.aborted) {- const msg = stoppedText(Date.now() - t.since);+ const msg = stoppedText(Date.now() - run.since);if (!text.startsWith("/")) {- if (!t.userStored) store.addMessage(conv.id, "user", text);+ if (!run.userStored) store.addMessage(conv.id, "user", text);store.addMessage(conv.id, "assistant", msg);}await out.apply({ type: "text", text: msg });@@ -332,19 +322,19 @@ export class BotRuntime {let note = "";if (agent?.available) {const place: ChatPlace = { channel: ev.channel, kind: ev.conversation.kind === "group" ? "group" : "dm" };- const handled = await this.handleAgent(agent, bot.id, conv.id, text, routed, place, out, seen, t);+ const handled = await this.handleAgent(agent, bot.id, conv.id, text, routed, place, out, seen, run);if (handled === true) return;// 应用正在退出:代理进程没了不是该改用纯对话的时候,留给下次启动提醒if (this.closing) {- t.interrupted = true;+ run.interrupted = true;return;}// 代理进程还在启动(第一次可能要几分钟):这条消息先由模型直接回答,不让用户干等- if (handled === "starting") note = "(代理还在启动,这条消息先由模型直接回答;启动完成后会自动用回代理。)";+ if (handled === "starting") note = t("runtime.startingNote");}- if (!t.userStored) store.addMessage(conv.id, "user", text);- t.userStored = true;+ if (!run.userStored) store.addMessage(conv.id, "user", text);+ run.userStored = true;const history = store.contextWindow(conv.id, this.opts.contextMessages, this.opts.contextChars);const messages: ChatMessage[] = [];if (bot.systemPrompt.trim()) messages.push({ role: "system", content: bot.systemPrompt });@@ -362,20 +352,20 @@ export class BotRuntime {acc += delta;void out.apply({ type: "stream.update", text: acc });});- const finalText = full || acc || "(模型没有返回内容)";+ const finalText = full || acc || t("runtime.emptyReply");store.addMessage(conv.id, "assistant", finalText);await out.apply({ type: "stream.finish", text: note ? `${note}\n\n${finalText}` : finalText });} catch (e) {const err = e as Error & { status?: number };if (signal.aborted) {// 停止:已生成的部分保留,末尾注明;还没出字就只说已中止- const msg = acc ? `${acc}\n\n(已中止)` : stoppedText(Date.now() - t.since);+ const msg = acc ? `${acc}\n\n(已中止)` : stoppedText(Date.now() - run.since);store.addMessage(conv.id, "assistant", msg);await out.apply({ type: "stream.finish", text: msg });return;}log.warn("model call failed", { model, status: err.status, message: err.message });- const msg = acc ? `${acc}\n\n⚠️ 生成中断:${err.message}` : `⚠️ 模型调用失败(${model}):${err.message}`;+ const msg = acc ? `${acc}\n\n${t("runtime.interrupted", { error: err.message })}` : t("runtime.modelFailed", { model, error: err.message });await out.apply({ type: "stream.finish", text: msg });} finally {await out.apply({ type: "typing", on: false });@@ -398,7 +388,7 @@ export class BotRuntime {const cmd = text.trim().toLowerCase();if (cmd === "/status" || cmd === "/help") {const bot = this.opts.store.getBot(ev.botId);- if (bot) return { handled: true, ack: cmd === "/help" ? HELP : this.statusText(bot.id, convId, this.opts.store.getConversation(convId)?.model ?? "", bot.defaultModel) };+ if (bot) return { handled: true, ack: cmd === "/help" ? help() : this.statusText(bot.id, convId, this.opts.store.getConversation(convId)?.model ?? "", bot.defaultModel) };}const agent = this.opts.agent;const tasks = agent?.tasks;@@ -432,15 +422,21 @@ export class BotRuntime {/** /status 的内容:只读本地状态,立即返回 */statusText(botId: string, convId: string, convModel: string, botModel: string): string {- const m = convModel || botModel || this.opts.defaultModel() || "(自动:第一个可用模型)";+ const m = convModel || botModel || this.opts.defaultModel() || t("runtime.autoModel");const a = this.opts.agent;const perm = a?.available ? a.settings(botId).permission : undefined;- const mode = !a?.available ? "纯对话模式" : `代理模式(DeepSeek Harness,${perm === "full" ? "完全权限:不经沙箱" : perm === "readonly" ? "只读沙箱" : "工作区沙箱"})`;+ const sandbox = t(perm === "full" ? "runtime.sandboxFull" : perm === "readonly" ? "runtime.sandboxReadonly" : "runtime.sandboxWorkspace");+ const mode = a?.available ? t("runtime.modeAgent", { sandbox }) : t("runtime.modeChat");// 完全权限:每次 /status 都提醒风险- const full = perm === "full" ? ["注意:完全权限下命令以你的用户身份直接运行,可以读写你电脑上的任何文件(包括 AnyModelBot 自己的数据);只有递归删除仍会先问你。在机器人设置里可以改回「工作区可写」。"] : [];- const pend = a ? a.approvals.pending(convId).map((r) => `${r.kind === "approval" ? "待批准" : "待回答"} ${r.code}`) : [];+ const full = perm === "full" ? [t("runtime.fullWarning")] : [];+ const pend = a ? a.approvals.pending(convId).map((r) => t(r.kind === "approval" ? "runtime.pendingApproval" : "runtime.pendingQuestion", { code: r.code })) : [];const cui = a?.available ? a.computerUse(botId) : undefined;- const cu = cui ? [`电脑操作:${cui.backend === "codex" ? "Codex 桥" : "Cua Driver"},${cui.active ? "已启用" : "未启用"}——${cui.reason}`, ...(cui.notice && cui.enabled ? [cui.notice] : [])] : [];+ const cu = cui+ ? [+ t("runtime.cuLine", { backend: cui.backend === "codex" ? t("runtime.cuCodex") : "Cua Driver", state: t(cui.active ? "runtime.cuOn" : "runtime.cuOff"), reason: cui.reason }),+ ...(cui.notice && cui.enabled ? [cui.notice] : []),+ ]+ : [];const host = a?.available ? [a.hostSummary(botId)] : [];// Windows:代理执行命令用的 PowerShell;没有 7 时建议安装const ps = a?.available ? pwshStatusLine(pwshProbe.snapshot()) : "";@@ -449,25 +445,36 @@ export class BotRuntime {const who = this.opts.access ? [this.opts.access.policyLine(botId)] : [];// 这个会话有后台任务在进行时说一句(没有就不说)const working = a?.tasks?.working(convId) ?? [];- const bg = working.length ? [`后台任务:${working.map((t) => `「${t.title}」${t.stage.label}`).join(",")}`] : [];- return [`当前模型:${m}${convModel ? "(会话设置)" : ""}`, `运行方式:${mode}`, ...full, ...who, ...host, ...(ps ? [ps] : []), ...busy, ...bg, ...cu, ...(pend.length ? [`未决:${pend.join(",")}`] : [])].join("\n");+ const bg = working.length ? [t("runtime.backgroundTasks", { list: working.map((x) => t("runtime.backgroundTask", { title: x.title, stage: x.stage.label })).join(t("runtime.listSep")) })] : [];+ return [+ t("runtime.currentModel", { model: m, suffix: convModel ? t("runtime.convSetting") : "" }),+ t("runtime.runMode", { mode }),+ ...full,+ ...who,+ ...host,+ ...(ps ? [ps] : []),+ ...busy,+ ...bg,+ ...cu,+ ...(pend.length ? [t("runtime.pending", { list: pend.join(t("runtime.listSep")) })] : []),+ ].join("\n");}/** 卡片按钮回调:批准/拒绝/选择选项。 */cardAction(botId: string, value: Record<string, string>, by: string): { toast: string; ok: boolean } {const agent = this.opts.agent;const row = agent && value?.id ? this.opts.store.getApproval(String(value.id)) : undefined;- if (!agent || !row || row.botId !== botId) return { toast: "请求不存在", ok: false };- if (row.status !== "pending") return { toast: `请求 ${row.code} 已处理或已过期`, ok: false };+ if (!agent || !row || row.botId !== botId) return { toast: t("runtime.requestMissing"), ok: false };+ if (row.status !== "pending") return { toast: t("runtime.requestDone", { code: row.code }), ok: false };if (value.amb === "approval") {const allow = value.decision === "allow";- return agent.approvals.decide(row.id, allow, by) ? { toast: allow ? `已批准 ${row.code}(仅本次)` : `已拒绝 ${row.code}`, ok: true } : { toast: "已过期", ok: false };+ return agent.approvals.decide(row.id, allow, by) ? { toast: t(allow ? "runtime.approvedOnce" : "runtime.rejected", { code: row.code }), ok: true } : { toast: t("runtime.expired"), ok: false };}if (value.amb === "question") {const r = agent.approvals.handleReply(row.conversationId, String(value.option ?? ""), by);- return r.handled ? { toast: "已提交", ok: true } : { toast: "提交失败", ok: false };+ return r.handled ? { toast: t("runtime.submitted"), ok: true } : { toast: t("runtime.submitFailed"), ok: false };}- return { toast: "未知操作", ok: false };+ return { toast: t("runtime.unknownAction"), ok: false };}/**@@ -508,11 +515,11 @@ export class BotRuntime {const show = () => {if (host.state === "running") {clearInterval(startup);- return void out.apply({ type: "stream.update", text: "代理已就绪,正在处理…" });+ return void out.apply({ type: "stream.update", text: t("runtime.agentReady") });}const s = Math.round((Date.now() - since) / 1000);const first = (host.diagnostics() as any).firstStart;- void out.apply({ type: "stream.update", text: `代理正在启动…${s >= 5 ? `(已 ${s} 秒)` : ""}${first ? "首次启动可能需要几分钟。" : ""}` });+ void out.apply({ type: "stream.update", text: t("runtime.agentStarting", { elapsed: s >= 5 ? t("runtime.agentStartingElapsed", { s }) : "", first: first ? t("runtime.agentStartingFirst") : "" }) });};show();startup = setInterval(show, 5000);@@ -580,7 +587,7 @@ export class BotRuntime {});if (!inflight.userStored) store.addMessage(convId, "user", text);inflight.userStored = true;- const finalText = r.text.trim() || "(已完成,没有文字回复)";+ const finalText = r.text.trim() || t("runtime.doneNoText");store.addMessage(convId, "assistant", finalText, [...steps.values()]);await out.apply({ type: "stream.finish", text: finalText });for (const f of r.files ?? []) {@@ -723,21 +730,21 @@ export class BotRuntime {const arg = rest.join(" ");switch (cmd.toLowerCase()) {case "/help":- return HELP;+ return help();case "/reset":this.opts.store.clearMessages(convId);this.opts.agent?.resetConversation(convId);- return "✅ 已清空本会话上下文";+ return t("runtime.resetDone");case "/new": {const a = this.opts.agent;- if (!a?.available) return "⚠️ /new 只在代理模式下可用;纯对话模式请用 /reset";- if (!this.opts.store.getAgentSession(convId)) return "当前已经是新的一段对话";+ if (!a?.available) return t("runtime.newAgentOnly");+ if (!this.opts.store.getAgentSession(convId)) return t("runtime.alreadyNew");try {await a.newSegment(botId, convId, await this.resolveModel(convModel, botModel));} catch (e) {- return `⚠️ 开新段失败:${(e as Error).message.slice(0, 200)}`;+ return t("runtime.newFailed", { error: (e as Error).message.slice(0, 200) });}- return "✅ 已开始新的一段对话(旧对话已归档并留下交接便条,长期记忆保留)";+ return t("runtime.newDone");}case "/status":return this.statusText(botId, convId, convModel, botModel);@@ -746,22 +753,22 @@ export class BotRuntime {try {list = await this.listModels(true);} catch (e) {- return `⚠️ 获取模型列表失败:${(e as Error).message}`;+ return t("runtime.modelListFailed", { error: (e as Error).message });}if (!arg) {const cur = convModel || botModel || this.opts.defaultModel();- if (!list.length) return "暂无可用模型:请先连接 Modelflare(设置 → Modelflare)。";- return ["可用模型(回复 /model 编号 切换):", ...list.map((m, i) => `${i + 1}. ${m}${m === cur ? " ← 当前" : ""}`)].join("\n");+ if (!list.length) return t("runtime.modelListEmpty");+ return [t("runtime.modelListHead"), ...list.map((m, i) => `${i + 1}. ${m}${m === cur ? t("runtime.modelCurrent") : ""}`)].join("\n");}if (arg === "default" || arg === "reset") {this.opts.store.setConversationModel(convId, "");- return "✅ 已恢复为机器人默认模型";+ return t("runtime.modelReset");}const idx = /^\d+$/.test(arg) ? Number(arg) - 1 : -1;const target = idx >= 0 ? list[idx] : list.find((m) => m === arg) ?? list.find((m) => m.endsWith("/" + arg) || m.includes(arg));- if (!target) return `⚠️ 找不到模型「${arg}」,发送 /model 查看列表`;+ if (!target) return t("runtime.modelNotFound", { name: arg });this.opts.store.setConversationModel(convId, target);- return `✅ 本会话已切换到 ${target}`;+ return t("runtime.modelSwitched", { model: target });}default:return null;@@ -790,8 +797,8 @@ export function interactiveOp(row: ApprovalRow) {requestId: row.id,code: row.code,buttons: [- { label: "允许(仅本次)", value: { amb: "approval", id: row.id, decision: "allow" }, style: "primary" as const },- { label: "拒绝", value: { amb: "approval", id: row.id, decision: "deny" }, style: "danger" as const },+ { label: t("runtime.allowOnce"), value: { amb: "approval", id: row.id, decision: "allow" }, style: "primary" as const },+ { label: t("runtime.deny"), value: { amb: "approval", id: row.id, decision: "deny" }, style: "danger" as const },],};}diff --git a/src/core/types.ts b/src/core/types.tsindex 12babfa..efc52fe 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -3,6 +3,7 @@* 运行时只产出 OutboundOp,由渠道按自身能力(ChannelCapabilities)落地或降级。*/import type { ActivityStep } from "../agent/activity.js";+import { t, type MessageKey } from "../i18n/index.js";export type ChannelId = "feishu" | "weixin" | "web";@@ -88,7 +89,11 @@ export type ChannelStatus = {since: number;};-const MEDIA_LABEL = { image: "图片", file: "文件", video: "视频" } as const;+const MEDIA_LABEL = {+ image: ["app.media_image", "app.media_quoted_image"],+ file: ["app.media_file", "app.media_quoted_file"],+ video: ["app.media_video", "app.media_quoted_video"],+} as const satisfies Record<string, readonly [MessageKey, MessageKey]>;export function eventText(ev: InboundEvent): string {return ev.parts@@ -99,14 +104,14 @@ export function eventText(ev: InboundEvent): string {case "quote":return `> ${p.text}`;case "voice":- return p.transcript ? p.transcript : "[语音]";+ return p.transcript ? p.transcript : t("app.media_voice");case "image":case "file":case "video": {// [图片 inbox/x.jpg]、[引用的文件 报告.pdf → inbox/x-报告.pdf]、[视频(未能下载:…)]- const label = `${p.quoted ? "引用的" : ""}${MEDIA_LABEL[p.type]}${p.type === "file" && p.name ? " " + p.name : ""}`;+ const label = `${t(MEDIA_LABEL[p.type][p.quoted ? 1 : 0])}${p.type === "file" && p.name ? " " + p.name : ""}`;if (p.path) return `[${label}${p.type === "file" && p.name ? " →" : ""} ${p.path}]`;- return p.error ? `[${label}(未能下载:${p.error})]` : `[${label}]`;+ return p.error ? `[${t("app.media_not_downloaded", { label, error: p.error })}]` : `[${label}]`;}}})diff --git a/src/diagnostics.ts b/src/diagnostics.tsindex 6a63b39..3e94b90 100644--- a/src/diagnostics.ts+++ b/src/diagnostics.ts@@ -11,6 +11,7 @@ import { shapeRejection } from "./agent/api-fallback.js";import { logFilePath, logger, readLogTail, redactText, redactValue } from "./log.js";import { bareModel } from "./modelflare.js";import { pwshProbe, pwshReportLine } from "./agent/pwsh.js";+import { t, type MessageKey } from "./i18n/index.js";const log = logger("diagnostics");@@ -45,7 +46,7 @@ export const PROBE_PROMPT = "Reply with the single word: pong";function describeFetchError(e: unknown, timeoutMs: number): string {const err = e as Error & { cause?: { code?: string; message?: string } };- if (err?.name === "TimeoutError" || err?.name === "AbortError") return `超时(${Math.round(timeoutMs / 1000)} 秒内没有响应)`;+ if (err?.name === "TimeoutError" || err?.name === "AbortError") return t("diag.fetch_timeout", { s: Math.round(timeoutMs / 1000) });const cause = err?.cause?.code || err?.cause?.message;return redactText(cause ? `${err.message}(${cause})` : String(err?.message ?? err));}@@ -67,8 +68,8 @@ export async function probeChat(const timeoutMs = opts.timeoutMs ?? 60_000;const base = baseUrl.replace(/\/+$/, "");const res: ProbeResult = { route, url: redactText(base), ok: false, model };- if (!base) return { ...res, error: "没有配置端点地址" };- if (!model) return { ...res, error: "没有可用的模型:请先在 Modelflare 里选择默认模型" };+ if (!base) return { ...res, error: t("diag.no_endpoint") };+ if (!model) return { ...res, error: t("diag.no_model") };const t0 = Date.now();try {const r = await (opts.fetchImpl ?? fetch)(`${base}/chat/completions`, {@@ -89,7 +90,7 @@ export async function probeChat(if (typeof j?.model === "string") res.echoedModel = j.model;if (!r.ok) return { ...res, error: errorText(j, text) || `HTTP ${r.status}` };const content = j?.choices?.[0]?.message?.content;- if (typeof content !== "string") return { ...res, error: `响应里没有 choices[0].message.content:${redactText(text.slice(0, 500))}` };+ if (typeof content !== "string") return { ...res, error: t("diag.no_content", { body: redactText(text.slice(0, 500)) }) };return { ...res, ok: true, reply: redactText(content.slice(0, 200)) };} catch (e) {return { ...res, ms: Date.now() - t0, error: describeFetchError(e, timeoutMs) };@@ -108,12 +109,12 @@ export async function pickModel(app: App, botId?: string, explicit?: string): Prfunction modelVerdict(g: ProbeResult, d: ProbeResult): string {- if (g.skipped) return d.ok ? "端点正常" : `端点出错:${d.status ? `HTTP ${d.status}` : d.error}`;- if (g.ok && d.ok) return "内置网关与直连端点都正常";- if (g.ok && !d.ok) return d.skipped ? "内置网关正常" : "经内置网关正常,直连端点失败(网关可能用了别的线路或重试)";- if (!g.ok && d.ok) return "端点本身正常,问题在内置网关";- if (d.skipped) return "内置网关出错,未能直连对比";- return `端点本身出错(${d.status ? `HTTP ${d.status}` : d.error}),内置网关也失败`;+ if (g.skipped) return d.ok ? t("diag.verdict_endpoint_ok") : t("diag.verdict_endpoint_error", { error: d.status ? `HTTP ${d.status}` : d.error });+ if (g.ok && d.ok) return t("diag.verdict_both_ok");+ if (g.ok && !d.ok) return d.skipped ? t("diag.verdict_gateway_ok") : t("diag.verdict_direct_failed");+ if (!g.ok && d.ok) return t("diag.verdict_gateway_broken");+ if (d.skipped) return t("diag.verdict_gateway_failed_no_direct");+ return t("diag.verdict_both_failed", { error: d.status ? `HTTP ${d.status}` : d.error });}export async function testModel(app: App, opts: { botId?: string; model?: string; timeoutMs?: number; fetchImpl?: typeof fetch } = {}): Promise<ModelTestResult> {@@ -126,15 +127,17 @@ export async function testModel(app: App, opts: { botId?: string; model?: stringlet direct: Promise<ProbeResult>;if (mp) {gateway = probeChat("gateway", mp.baseUrl, mp.gatewayKey, model, probeOpts).then((r) =>- mp.state === "running" || r.ok ? r : { ...r, error: `${r.error ?? ""}(内置网关状态:${mp.state}${mp.lastError ? `,${redactText(mp.lastError)}` : ""})` },+ mp.state === "running" || r.ok+ ? r+ : { ...r, error: mp.lastError ? t("diag.gateway_state_error", { error: r.error ?? "", state: mp.state, lastError: redactText(mp.lastError) }) : t("diag.gateway_state", { error: r.error ?? "", state: mp.state }) },);const up = mp.upstreamEndpoint(model.includes("/") ? model.split("/")[0] : undefined);direct = up? probeChat("direct", up.baseUrl, up.apiKey, bareModel(model), { ...probeOpts, headers: app.requestHeaders() })- : Promise.resolve({ route: "direct", url: "", ok: false, skipped: "还没有连接 Modelflare" });+ : Promise.resolve({ route: "direct", url: "", ok: false, skipped: t("diag.skip_not_connected") });} else {const base = app.config.magpie.externalBaseUrl;- gateway = Promise.resolve({ route: "gateway", url: "", ok: false, skipped: "外部端点模式:机器人直接调用该端点,不经内置网关" });+ gateway = Promise.resolve({ route: "gateway", url: "", ok: false, skipped: t("diag.skip_external") });direct = probeChat("direct", base, app.config.magpie.externalApiKey, model, probeOpts);}const [g, d] = await Promise.all([gateway, direct]);@@ -172,20 +175,21 @@ export interface AgentTestResult {error?: string;}-const STAGES: Array<[StageId, string]> = [- ["queue", "消息队列"],- ["spawn", "启动代理进程"],- ["plugins", "加载插件"],- ["model", "调用模型"],- ["reply", "得到回复"],+const STAGES: Array<[StageId, MessageKey]> = [+ ["queue", "diag.stage_queue"],+ ["spawn", "diag.stage_spawn"],+ ["plugins", "diag.stage_plugins"],+ ["model", "diag.stage_model"],+ ["reply", "diag.stage_reply"],];+const STAGE_LABEL = Object.fromEntries(STAGES) as Record<StageId, MessageKey>;const TIMEOUT_DETAIL: Record<StageId, (s: number) => string> = {queue: () => "",- spawn: (s) => `代理进程 ${s} 秒内没有完成启动(initialize 没有返回)`,- plugins: (s) => `代理进程已启动,但 ${s} 秒内没有发出模型请求`,- model: (s) => `模型请求已发出,${s} 秒内上游没有响应`,- reply: (s) => `模型已响应,但代理 ${s} 秒内没有结束这一轮`,+ spawn: (s) => t("diag.timeout_spawn", { s }),+ plugins: (s) => t("diag.timeout_plugins", { s }),+ model: (s) => t("diag.timeout_model", { s }),+ reply: (s) => t("diag.timeout_reply", { s }),};/**@@ -196,7 +200,7 @@ export async function testAgent(app: App, opts: { botId?: string; model?: stringconst t0 = Date.now();const timeoutMs = Math.min(Math.max(opts.timeoutMs ?? 120_000, 5_000), 600_000);const botId = opts.botId || app.store.listBots()[0]?.id || "default";- const stages: AgentStage[] = STAGES.map(([id, label]) => ({ id, label, status: "pending" }));+ const stages: AgentStage[] = STAGES.map(([id, label]) => ({ id, label: t(label), status: "pending" }));const result: AgentTestResult = { at: Date.now(), ok: false, botId, model: "", ms: 0, stages };const st = (id: StageId) => stages.find((s) => s.id === id)!;const begun: Partial<Record<StageId, number>> = {};@@ -222,13 +226,13 @@ export async function testAgent(app: App, opts: { botId?: string; model?: string};if (!app.agent.available) {- mark("spawn", "fail", app.config.agent.mode === "off" ? "代理模式已关闭(AMB_AGENT=off),机器人只做纯对话" : "找不到代理运行时(DSH),机器人只能纯对话");+ mark("spawn", "fail", app.config.agent.mode === "off" ? t("diag.agent_off") : t("diag.no_runtime"));return finish();}const picked = await pickModel(app, botId, opts.model);result.model = picked ? app.routeModel(botId, picked) : "";if (!result.model) {- mark("spawn", "fail", "没有可用的模型:请先连接 Modelflare 并选择默认模型");+ mark("spawn", "fail", t("diag.agent_no_model"));return finish();}@@ -240,26 +244,29 @@ export async function testAgent(app: App, opts: { botId?: string; model?: stringconst expectedTools = ["present", "ask_user_question", ...(memory ? ["remember"] : [])];// 同一机器人正在处理的回合:同一会话里后来的消息(包括用户看到"一直思考中"的那条)并入它(代理还没接手时排在它后面)- const turns = app.agent.diagnostics().turns.filter((t) => t.botId === botId);- if (!turns.length) mark("queue", "ok", "没有正在处理的回合", 0);- else mark("queue", "warn", `${turns.length} 轮对话正在处理(最长已 ${Math.round(Math.max(...turns.map((t) => t.forMs)) / 1000)} 秒);同一会话的新消息会并入正在进行的回合(代理还没接手时排在后面)。卡住时用 /stop,或下面的"重启代理进程"`, 0);+ const turns = app.agent.diagnostics().turns.filter((x) => x.botId === botId);+ if (!turns.length) mark("queue", "ok", t("diag.queue_idle"), 0);+ else mark("queue", "warn", t("diag.queue_busy", { count: turns.length, s: Math.round(Math.max(...turns.map((x) => x.forMs)) / 1000) }), 0);begun.spawn = Date.now();if (host.state === "starting") {const d = host.diagnostics() as { startingForMs?: number; initStage?: string };- st("spawn").detail = `等待正在进行的启动(已 ${Math.round((d.startingForMs ?? 0) / 1000)} 秒,阶段:${d.initStage ?? "-"})`;+ st("spawn").detail = t("diag.spawn_waiting", { s: Math.round((d.startingForMs ?? 0) / 1000), stage: d.initStage ?? "-" });}/** 这一轮 Responses / Messages 被拒、代理换 Chat 重做:模型这一步等重做的结果,期间的重启不算失败 */let rejected: { path: string; why: string } | undefined;const offHost = host.on((e: HostEvent) => {- if (e.type === "spawned") st("spawn").detail = `pid ${e.pid ?? "?"},等待初始化…`;+ if (e.type === "spawned") st("spawn").detail = t("diag.spawn_initializing", { pid: e.pid ?? "?" });else if (e.type === "initialized") mark("spawn", "ok", `pid ${e.pid ?? "?"}`, e.ms);else if (e.type === "failed") mark("spawn", "fail", e.message);else if (e.type === "exit") {// 接口被拒、代理换到 Chat Completions 重做:这次退出是有意的重启if (rejected && st("model").status === "pending") return;const pending = failedAlready() ? undefined : stages.find((s) => s.status === "pending");- if (pending) mark(pending.id, "fail", `代理进程退出(code=${e.code ?? "-"}, signal=${e.signal ?? "-"})${host.stderrTail.length ? `;stderr:${host.stderrTail.slice(-5).join(" | ")}` : ""}`);+ if (pending) {+ const exit = { code: e.code ?? "-", signal: e.signal ?? "-" };+ mark(pending.id, "fail", host.stderrTail.length ? t("diag.agent_exited_stderr", { ...exit, stderr: host.stderrTail.slice(-5).join(" | ") }) : t("diag.agent_exited", exit));+ }}});const offProxy = app.agent.bridge.onProxy((e: ProxyEvent) => {@@ -268,8 +275,8 @@ export async function testAgent(app: App, opts: { botId?: string; model?: stringif (!e.lastUser?.includes(marker)) return;ours.add(e.id);if (st("plugins").status === "pending") {- const missing = expectedTools.filter((t) => !e.tools?.includes(t));- mark("plugins", missing.length ? "fail" : "ok", missing.length ? `模型请求里缺少插件提供的工具:${missing.join(", ")}` : `${e.tools?.length ?? 0} 个工具`);+ const missing = expectedTools.filter((x) => !e.tools?.includes(x));+ mark("plugins", missing.length ? "fail" : "ok", missing.length ? t("diag.plugins_missing", { tools: missing.join(", ") }) : t("diag.plugins_tools", { count: e.tools?.length ?? 0 }));}return;}@@ -279,8 +286,8 @@ export async function testAgent(app: App, opts: { botId?: string; model?: stringconst why = e.status >= 400 ? shapeRejection([{ status: e.status, error: e.error ?? "" }], "") : undefined;if (why) return void (rejected = { path: e.path, why });}- const after = rejected ? `(${rejected.path} 被拒:${rejected.why};已改用 Chat Completions)` : "";- if (e.phase === "response") mark("model", e.status < 400 ? "ok" : "fail", e.status < 400 ? `HTTP ${e.status}${after}` : `HTTP ${e.status}${e.error ? `:${e.error}` : ""}${after}`, e.ms);+ const after = rejected ? t("diag.api_rejected", { path: rejected.path, why: rejected.why }) : "";+ if (e.phase === "response") mark("model", e.status < 400 ? "ok" : "fail", (e.status < 400 || !e.error ? `HTTP ${e.status}` : t("diag.http_error", { status: e.status, error: e.error })) + after, e.ms);else mark("model", "fail", e.error, e.ms);});@@ -288,7 +295,7 @@ export async function testAgent(app: App, opts: { botId?: string; model?: stringapp.store.clearAgentSession(conv);let timer: NodeJS.Timeout | undefined;try {- if (host.state === "running" && host.pid) mark("spawn", "ok", `已在运行(pid ${host.pid})`, 0);+ if (host.state === "running" && host.pid) mark("spawn", "ok", t("diag.already_running", { pid: host.pid }), 0);host.resetBackoff();const turn = host.runTurn({ conversationId: conv, text: `${marker} ${PROBE_PROMPT}`, model: result.model });const outcome = await Promise.race([@@ -302,9 +309,9 @@ export async function testAgent(app: App, opts: { botId?: string; model?: stringresult.reply = redactText(outcome.r.text.slice(0, 300));// 回合结束了但某一步没看到(例如 bridge 事件丢失):按结果补齐if (st("spawn").status === "pending") mark("spawn", "ok");- if (st("plugins").status === "pending") mark("plugins", "ok", "(没有观察到模型请求)");- if (st("model").status === "pending") mark("model", "ok", "(没有观察到上游响应)");- mark("reply", outcome.r.text.trim() ? "ok" : "fail", outcome.r.text.trim() ? result.reply : "回合结束了,但没有文字回复");+ if (st("plugins").status === "pending") mark("plugins", "ok", t("diag.no_request_seen"));+ if (st("model").status === "pending") mark("model", "ok", t("diag.no_response_seen"));+ mark("reply", outcome.r.text.trim() ? "ok" : "fail", outcome.r.text.trim() ? result.reply : t("diag.no_text_reply"));} else if (outcome.kind === "error") {result.error = redactText(outcome.e.message.slice(0, 1500));// 已经有一步明确失败(启动失败、上游报错)时不再往后记@@ -312,9 +319,14 @@ export async function testAgent(app: App, opts: { botId?: string; model?: stringif (pending) mark(pending.id, "fail", result.error);} else {const pending = stages.find((s) => s.status === "pending");- const stageNow = pending?.id === "spawn" && host.initStage ? `;当前阶段:${host.initStage}${host.stderrTail.length ? `;最近输出:${host.stderrTail.at(-1)}` : ""}` : "";+ const stageNow =+ pending?.id === "spawn" && host.initStage+ ? host.stderrTail.length+ ? t("diag.stage_now_output", { stage: host.initStage, line: host.stderrTail.at(-1) })+ : t("diag.stage_now", { stage: host.initStage })+ : "";if (pending) mark(pending.id, "timeout", TIMEOUT_DETAIL[pending.id](Math.round(timeoutMs / 1000)) + stageNow);- result.error = "超时";+ result.error = t("diag.timeout");turn.catch(() => undefined);}} finally {@@ -377,27 +389,36 @@ function outboxSummary(app: App): Record<string, unknown> | undefined {const ts = (t?: number) => (t ? new Date(t).toISOString() : "-");function probeLine(name: string, p: ProbeResult): string {- if (p.skipped) return ` ${name}: 未测(${p.skipped})`;- return ` ${name}: ${p.ok ? "正常" : "失败"} · HTTP ${p.status ?? "-"} · ${p.ms ?? "-"} ms · ${p.url}${p.echoedModel ? ` · 回显模型 ${p.echoedModel}` : ""}${p.reply ? ` · 回复 ${JSON.stringify(p.reply)}` : ""}${p.error ? `\n 错误:${p.error}` : ""}`;+ if (p.skipped) return ` ${t("diag.report_probe_skipped", { name, reason: p.skipped })}`;+ const head = t("diag.report_probe", { name, result: t(p.ok ? "diag.report_ok" : "diag.report_failed"), status: p.status ?? "-", ms: p.ms ?? "-", url: p.url });+ const echoed = p.echoedModel ? t("diag.report_echoed", { model: p.echoedModel }) : "";+ const reply = p.reply ? t("diag.report_reply", { reply: JSON.stringify(p.reply) }) : "";+ return ` ${head}${echoed}${reply}${p.error ? `\n ${t("diag.report_error", { error: p.error })}` : ""}`;}/** 可复制的纯文本诊断报告:状态 + 最近的测试结果 + 日志尾部,整体再脱敏一遍。 */export function diagnosticsReport(app: App, lines = 200): string {const s = diagnosticsStatus(app) as any;const out: string[] = [];- out.push(`anymodel bot 诊断信息 · ${ts(s.at)}`);- out.push(`版本 ${s.version} · ${s.platform} ${s.arch} · ${s.os}${s.electron ? ` · Electron ${s.electron}` : ""} · Node ${s.node} · 运行 ${s.uptimeSec} 秒`);- out.push(`数据目录 ${s.dataDir}`);- out.push(`日志文件 ${s.logFile ?? "(未启用)"}`);- out.push(`默认模型 ${s.defaultModel || "(自动)"}`);+ out.push(t("diag.report_title", { at: ts(s.at) }));+ out.push(t("diag.report_version", { version: s.version, platform: s.platform, arch: s.arch, os: s.os, electron: s.electron ? ` · Electron ${s.electron}` : "", node: s.node, uptime: s.uptimeSec }));+ out.push(t("diag.report_data_dir", { dir: s.dataDir }));+ out.push(t("diag.report_log_file", { file: s.logFile ?? t("diag.report_not_enabled_paren") }));+ out.push(t("diag.report_default_model", { model: s.defaultModel || t("diag.report_auto") }));out.push("");const g = s.gateway;- out.push(`[模型网关] ${g.mode === "managed" ? `内置 magpie · ${g.state} · pid ${g.pid ?? "-"} · 重启 ${g.restarts} 次${g.lastExit ? ` · 上次退出 code=${g.lastExit.code} signal=${g.lastExit.signal}` : ""}${g.lastError ? ` · ${g.lastError}` : ""}` : `外部端点 ${g.url}`}`);+ const lastExit = (x: any) => (x ? t("diag.report_last_exit", { code: x.code, signal: x.signal }) : "");+ out.push(+ g.mode === "managed"+ ? t("diag.report_gateway_managed", { state: g.state, pid: g.pid ?? "-", restarts: g.restarts, lastExit: lastExit(g.lastExit), lastError: g.lastError ? ` · ${g.lastError}` : "" })+ : t("diag.report_gateway_external", { url: g.url }),+ );for (const l of g.logTail ?? []) out.push(` | ${l}`);const a = s.agent;- out.push(`[代理] ${a.enabled ? "已启用" : "未启用"} · 运行时 ${a.runtimeDir ?? "缺失"}`);+ out.push(t("diag.report_agent", { enabled: t(a.enabled ? "diag.report_enabled" : "diag.report_not_enabled"), runtime: a.runtimeDir ?? t("diag.report_missing") }));for (const [id, h] of Object.entries<any>(a.hosts ?? {})) {- out.push(` 机器人 ${id}: ${h.state} · pid ${h.pid ?? "-"} · 重启 ${h.restarts} 次 · 进行中 ${h.activeTurns}${h.lastExit ? ` · 上次退出 code=${h.lastExit.code} signal=${h.lastExit.signal} @ ${ts(h.lastExit.at)}` : ""}${h.lastError ? `\n 最近错误:${h.lastError}` : ""}`);+ const exit = h.lastExit ? `${lastExit(h.lastExit)} @ ${ts(h.lastExit.at)}` : "";+ out.push(` ${t("diag.report_host", { id, state: h.state, pid: h.pid ?? "-", restarts: h.restarts, active: h.activeTurns, lastExit: exit })}${h.lastError ? `\n ${t("diag.report_last_error", { error: h.lastError })}` : ""}`);for (const l of h.stderrTail ?? []) out.push(` | ${l}`);}const ps = pwshReportLine(s.pwsh);@@ -407,18 +428,20 @@ export function diagnosticsReport(app: App, lines = 200): string {const m = app.lastDiagnostics.model;if (m) {out.push("");- out.push(`[测试模型] ${ts(m.at)} · 模型 ${m.model || "-"} · ${m.verdict}`);- out.push(probeLine("经内置网关", m.gateway));- out.push(probeLine("直连端点", m.direct));+ // 结论按报告的语言重新给出(测试结果里存的是测试时的语言)+ out.push(t("diag.report_model_test", { at: ts(m.at), model: m.model || "-", verdict: modelVerdict(m.gateway, m.direct) }));+ out.push(probeLine(t("diag.report_via_gateway"), m.gateway));+ out.push(probeLine(t("diag.report_direct"), m.direct));}- const t = app.lastDiagnostics.agent;- if (t) {+ const ag = app.lastDiagnostics.agent;+ if (ag) {out.push("");- out.push(`[测试代理] ${ts(t.at)} · 机器人 ${t.botId} · 模型 ${t.model || "-"} · ${t.ok ? "通过" : `未通过(${t.stuckAt ?? "?"})`} · ${t.ms} ms`);- for (const st of t.stages) out.push(` ${st.label}: ${st.status}${st.ms !== undefined ? ` · ${st.ms} ms` : ""}${st.detail ? ` · ${st.detail}` : ""}`);+ const result = ag.ok ? t("diag.report_passed") : t("diag.report_not_passed", { stage: ag.stuckAt ?? "?" });+ out.push(t("diag.report_agent_test", { at: ts(ag.at), bot: ag.botId, model: ag.model || "-", result, ms: ag.ms }));+ for (const st of ag.stages) out.push(` ${t(STAGE_LABEL[st.id])}: ${st.status}${st.ms !== undefined ? ` · ${st.ms} ms` : ""}${st.detail ? ` · ${st.detail}` : ""}`);}out.push("");- out.push(`[最近 ${lines} 行日志]`);+ out.push(t("diag.report_log_tail", { count: lines }));out.push(...readLogTail(lines));return redactText(out.join("\n"));}diff --git a/src/guide.ts b/src/guide.tsnew file mode 100644index 0000000..34736c0--- /dev/null+++ b/src/guide.ts@@ -0,0 +1,49 @@+// 新手引导(界面里的「上手清单」):进度存在 config.json 的 ui.guide。+// 有些步骤能从现有数据看出来已经做过(有过回复、换过模型、绑了微信或飞书、记下过东西),读取时并进去,+// 老用户升级后不会被要求从头再做一遍;其余步骤(动手、生图)由界面在看到结果时标记。++export const GUIDE_STEPS = ["hello", "model", "weixin", "hands", "memory", "media"] as const;+export type GuideStep = (typeof GUIDE_STEPS)[number];++export interface GuideState {+ /** 做过的步骤(按清单顺序) */+ done: GuideStep[];+ /** 整个清单不再显示(清单浮层里的「不再显示」) */+ hidden: boolean;+ /** 看过的一次性提示:intro = 对话空状态里的清单卡已收起;以后的「随用随教」提示也记在这里 */+ seen: string[];+}++export const isGuideStep = (s: unknown): s is GuideStep => (GUIDE_STEPS as readonly unknown[]).includes(s);++const SEEN_ID = /^[\w-]{1,40}$/;++export function normalizeGuide(v: unknown): GuideState {+ const o = (v && typeof v === "object" ? v : {}) as Record<string, unknown>;+ const done = Array.isArray(o.done) ? GUIDE_STEPS.filter((s) => (o.done as unknown[]).includes(s)) : [];+ const seen = Array.isArray(o.seen) ? [...new Set(o.seen.filter((x): x is string => typeof x === "string" && SEEN_ID.test(x)))].slice(0, 100) : [];+ return { done, hidden: o.hidden === true, seen };+}++/** 推导需要的数据,由调用方从 store / 记忆里取(便于测试) */+export interface GuideFacts {+ conversations: Array<{ messageCount: number; model: string }>;+ bots: Array<{ id: string; defaultModel: string; feishuAppId: string }>;+ weixinBound: (botId: string) => boolean;+ memoryCount: (botId: string) => number;+}++export function deriveGuide(f: GuideFacts): GuideStep[] {+ const out: GuideStep[] = [];+ // 一问一答至少两条消息+ if (f.conversations.some((c) => c.messageCount >= 2)) out.push("hello");+ if (f.conversations.some((c) => c.model) || f.bots.some((b) => b.defaultModel)) out.push("model");+ if (f.bots.some((b) => b.feishuAppId || f.weixinBound(b.id))) out.push("weixin");+ if (f.bots.some((b) => f.memoryCount(b.id) > 0)) out.push("memory");+ return out;+}++/** 合并:已记录的 + 推导出的,保持清单顺序 */+export function mergeGuide(g: GuideState, extra: readonly GuideStep[]): GuideState {+ return { ...g, done: GUIDE_STEPS.filter((s) => g.done.includes(s) || extra.includes(s)) };+}diff --git a/src/i18n/index.ts b/src/i18n/index.tsnew file mode 100644index 0000000..f50fea1--- /dev/null+++ b/src/i18n/index.ts@@ -0,0 +1,154 @@+/**+ * 服务端多语言:简体中文 / English。界面那一份见 ui/lib/i18n.js,两边的语言代码一致(zh-CN | en)。+ *+ * 用哪种语言(lang()):+ * 1. 正在处理的界面请求:请求头 x-amb-lang(界面解析后的语言),由 web/server.ts 用 requestLang() 包住整个请求,+ * 请求里抛出的报错、返回的状态文字都是界面当前的语言。请求结束后这个语言就失效:在请求里启动、之后还在跑的+ * 后台任务(渠道收消息循环、代理进程的回调、排队的工作)自动退回应用语言,不会一直沿用某次请求的语言;+ * 2. 其他时候(后台任务、机器人发到微信 / 飞书的系统消息、托盘菜单):应用的语言偏好 config.ui.lang;+ * 偏好是"跟随系统"时用系统语言——桌面版取系统首选语言(electron/main.ts 调 setSystemLang),+ * 命令行 / Docker 先看 AMB_LANG,再看 LC_ALL / LC_MESSAGES / LANG,都没有(或是 C / POSIX)时用简体中文。+ *+ * 文案在 src/i18n/messages/<命名空间>.ts;t() 的键有类型检查,写错键或漏了英文都编译不过。+ * 日志、给模型看的提示词和工具说明不走这里:前者给开发者看,后者模型两种语言都懂。+ */+import { AsyncLocalStorage } from "node:async_hooks";+import { catalogs } from "./messages/index.js";+import type { Msg } from "./types.js";++export type Lang = "zh-CN" | "en";+export type LangPref = "system" | Lang;+export const LANGS: readonly Lang[] = ["zh-CN", "en"];++type Catalogs = typeof catalogs;+export type MessageKey = { [N in keyof Catalogs]: `${N & string}.${Extract<keyof Catalogs[N]["zh"], string>}` }[keyof Catalogs];+export type Params = Record<string, string | number | boolean | null | undefined>;++/** "zh" / "zh_CN.UTF-8" / "zh-Hans" → zh-CN;"en-US" → en;其他 → undefined */+export function normalizeLang(s: unknown): Lang | undefined {+ const v = String(s ?? "").trim().toLowerCase();+ if (v.startsWith("zh")) return "zh-CN";+ if (v.startsWith("en")) return "en";+ return undefined;+}+export function normalizeLangPref(s: unknown): LangPref {+ return s === "system" ? "system" : (normalizeLang(s) ?? "system");+}++/** 命令行 / Docker 的系统语言:AMB_LANG → LC_ALL → LC_MESSAGES → LANG;没设或是 C / POSIX 时用简体中文(产品的默认语言),其他语言用英文 */+export function envLang(env: NodeJS.ProcessEnv = process.env): Lang {+ const explicit = normalizeLang(env.AMB_LANG);+ if (explicit) return explicit;+ for (const k of ["LC_ALL", "LC_MESSAGES", "LANG"]) {+ const v = String(env[k] ?? "").trim();+ if (!v) continue;+ if (/^(c|posix)([._].*)?$/i.test(v)) return "zh-CN";+ return normalizeLang(v) ?? "en";+ }+ return "zh-CN";+}++let systemLang: Lang = envLang();+let pref: LangPref = "system";+const listeners = new Set<(l: Lang) => void>();+/** live:请求还没结束。AsyncLocalStorage 会把 store 传给请求里派生出去的所有异步任务,结束时把它关掉 */+interface Scope {+ lang: Lang;+ live: boolean;+}+const als = new AsyncLocalStorage<Scope>();++/** 应用的语言(不看当前请求) */+export function appLang(): Lang {+ return pref === "system" ? systemLang : pref;+}+/** 当前该用的语言:界面请求里用请求的语言,否则用应用的语言 */+export function lang(): Lang {+ const s = als.getStore();+ return s && s.live ? s.lang : appLang();+}+export function getLangPref(): LangPref {+ return pref;+}++function changed(before: Lang): void {+ const now = appLang();+ if (now !== before) for (const fn of listeners) fn(now);+}+/** 系统语言(桌面版启动时按系统首选语言设一次) */+export function setSystemLang(l: Lang): void {+ const before = appLang();+ systemLang = l;+ changed(before);+}+/** 应用的语言偏好(读配置、界面里改了语言时调用) */+export function setLangPref(p: LangPref): void {+ const before = appLang();+ pref = normalizeLangPref(p);+ changed(before);+}+/** 应用语言变了(托盘菜单据此重建);返回取消订阅的函数 */+export function onLangChange(fn: (l: Lang) => void): () => void {+ listeners.add(fn);+ return () => listeners.delete(fn);+}++/** 在指定语言下执行(含其中所有的 await);l 为空时照常用应用语言 */+export function withLang<T>(l: Lang | undefined, fn: () => T): T {+ return l ? als.run({ lang: l, live: true }, fn) : fn();+}++/** 一次界面请求的语言:run() 里(含派生出去的异步任务)用 l,end() 之后它们都退回应用语言 */+export function requestLang(l: Lang | undefined): { run<T>(fn: () => T): T; end(): void } {+ const scope: Scope | undefined = l ? { lang: l, live: true } : undefined;+ return {+ run: (fn) => (scope ? als.run(scope, fn) : fn()),+ end: () => {+ if (scope) scope.live = false;+ },+ };+}++/** 不带任何请求的语言执行:常驻的后台循环从这里启动,一开始就用应用语言 */+export function detached<T>(fn: () => T): T {+ return als.exit(fn);+}++const rules = new Map<Lang, Intl.PluralRules>();+function pick(m: Msg, l: Lang, params?: Params): string {+ if (typeof m === "string") return m;+ const n = Number(params?.count);+ if (!Number.isFinite(n)) return m.other;+ let r = rules.get(l);+ if (!r) rules.set(l, (r = new Intl.PluralRules(l)));+ return (r.select(n) === "one" && m.one) || m.other;+}++function format(s: string, params?: Params): string {+ if (!params || !s.includes("{")) return s;+ return s.replace(/\{(\w+)\}/g, (all, k: string) => (k in params ? String(params[k] ?? "") : all));+}++function lookup(l: Lang, key: string): Msg | undefined {+ const i = key.indexOf(".");+ const ns = (catalogs as Record<string, { zh: Record<string, Msg>; en: Record<string, Msg> }>)[key.slice(0, i)];+ if (!ns) return undefined;+ const k = key.slice(i + 1);+ return (l === "en" ? ns.en[k] : undefined) ?? ns.zh[k];+}++/** 按指定语言取文案 */+export function tl(l: Lang, key: MessageKey, params?: Params): string {+ const m = lookup(l, key);+ return m === undefined ? key : format(pick(m, l, params), params);+}+/** 按当前语言(lang())取文案 */+export function t(key: MessageKey, params?: Params): string {+ return tl(lang(), key, params);+}+/** 只给拼出来的动态键用:键不存在时返回 undefined */+export function tMaybe(key: string, params?: Params): string | undefined {+ const l = lang();+ const m = lookup(l, key);+ return m === undefined ? undefined : format(pick(m, l, params), params);+}diff --git a/src/i18n/messages/account.ts b/src/i18n/messages/account.tsnew file mode 100644index 0000000..57a6d80--- /dev/null+++ b/src/i18n/messages/account.ts@@ -0,0 +1,66 @@+// account:zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。+import type { Catalog } from "../types.js";++export const zh = {+ // client.ts+ revoked: "Modelflare 授权已失效,请重新登录",+ unreachable: "连不上 Modelflare({reason})",+ // manager.ts+ already_signed_in: "已经登录了 Modelflare 账户",+ no_new_key: "Modelflare 没有返回新 Key",+ login_incomplete: "登录没有完成:{reason}",+ revoked_elsewhere: "Modelflare 授权已失效(可能在网页上撤销了),请重新登录",+ sign_in_first: "请先登录 Modelflare 账户",+ low_balance: "Modelflare 余额只剩 ${balance},低于提醒线 ${threshold}。充值:{url}",+ budget_needs_login: "给机器人设预算需要先登录 Modelflare 账户",+ // oauth.ts+ host_unreachable: "连不上 {host}({reason})",+ discovery_failed: "读取登录配置失败(HTTP {status})",+ discovery_bad_endpoint: "登录配置里的 {key} 无效",+ discovery_issuer_mismatch: "登录配置的发行方不匹配",+ tokens_incomplete: "Modelflare 返回的令牌不完整",+ logout_failed: "退出登录失败(HTTP {status})",+ page_not_done_title: "没有完成登录",+ page_denied: "你取消了这次授权,可以回到 AnyModelBot 重新登录。",+ page_not_done: "授权没有完成,请回到 AnyModelBot 重试。",+ page_done_title: "登录完成",+ page_done: "可以关闭这个页面,回到 AnyModelBot。",+ denied: "你取消了授权",+ not_done: "授权没有完成",+ login_timeout: "登录等待超时,请重新开始",+ login_cancelled: "已取消登录",+ // vault.ts+ vault_bad_version: "不认识的账户文件版本",+ vault_encrypted: "账户凭据由桌面版加密,当前运行方式无法读取",+ vault_incomplete: "账户文件不完整",+} satisfies Catalog;++export const en: Catalog<typeof zh> = {+ revoked: "Your Modelflare authorization has expired. Please sign in again",+ unreachable: "Can't reach Modelflare ({reason})",+ already_signed_in: "Already signed in to a Modelflare account",+ no_new_key: "Modelflare didn't return a new key",+ login_incomplete: "Sign-in didn't complete: {reason}",+ revoked_elsewhere: "Your Modelflare authorization has expired (it may have been revoked on the website). Please sign in again",+ sign_in_first: "Sign in to your Modelflare account first",+ low_balance: "Your Modelflare balance is down to ${balance}, below your ${threshold} alert threshold. Top up: {url}",+ budget_needs_login: "Sign in to your Modelflare account to set a bot budget",+ host_unreachable: "Can't reach {host} ({reason})",+ discovery_failed: "Couldn't read the sign-in configuration (HTTP {status})",+ discovery_bad_endpoint: "Invalid {key} in the sign-in configuration",+ discovery_issuer_mismatch: "The sign-in configuration's issuer doesn't match",+ tokens_incomplete: "Modelflare returned incomplete tokens",+ logout_failed: "Sign-out failed (HTTP {status})",+ page_not_done_title: "Sign-in not completed",+ page_denied: "You cancelled the authorization. You can go back to AnyModelBot and sign in again.",+ page_not_done: "Authorization didn't complete. Please go back to AnyModelBot and try again.",+ page_done_title: "Signed in",+ page_done: "You can close this page and go back to AnyModelBot.",+ denied: "You cancelled the authorization",+ not_done: "Authorization didn't complete",+ login_timeout: "Sign-in timed out. Please start again",+ login_cancelled: "Sign-in cancelled",+ vault_bad_version: "Unrecognized account file version",+ vault_encrypted: "Account credentials were encrypted by the desktop app and can't be read in this mode",+ vault_incomplete: "The account file is incomplete",+};diff --git a/src/i18n/messages/agent.ts b/src/i18n/messages/agent.tsnew file mode 100644index 0000000..c2f1b09--- /dev/null+++ b/src/i18n/messages/agent.ts@@ -0,0 +1,80 @@+// agent:zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。+import type { Catalog } from "../types.js";++export const zh = {+ // manager:电脑操作状态(界面与 /status)+ cuNoRuntime: "Computer Use: 不可用(代理运行时缺失)",+ cuDisabled: "Computer Use: 已在本机器人设置中关闭",+ cuModeAsk: "点击/输入前先问我",+ cuModeAuto: "操作自动执行",+ cuReasonMode: "{reason};{mode}",+ // manager:/status 里的代理进程状态+ hostNotStarted: "代理进程:未启动(收到消息时启动)",+ hostRunning: "代理进程:运行中(pid {pid}{init})",+ hostRunningInit: ",启动用时 {s} 秒",+ hostStarting: "代理进程:正在启动(已 {s} 秒{first})",+ hostStartingFirst: ";第一次启动可能要几分钟",+ hostBackoff: "代理进程:上次启动失败,稍后重试({error})",+ hostPaused: "代理进程:启动失败,已暂停({error})",+ // host+ startRetryLater: "代理进程启动失败,{min} 分钟后再试(或在 设置 → 故障排查 里重启代理进程):{error}",+ startPaused: "代理进程连续两次启动失败,已暂停 10 分钟(期间用纯对话回复)。可在 设置 → 故障排查 查看原因并重启代理进程。原因:{error}",+ // bridge+ gatewayNotReady: "模型网关未就绪",+ // memory:作用域名称(界面的记忆页、记忆操作的回执)+ scopeTeam: "团队记忆",+ scopeGroup: "本群记忆",+ scopeBot: "机器人记忆",+ memTopicInvalid: "主题名「{topic}」无效:只能用字母、数字、中文、- 和 _,最长 40 字",+ memTopicReserved: "主题名「{topic}」是保留名",+ memEmpty: "内容为空",+ memTooLong: "单条记忆最多 {max} 字(现在 {n} 字),请精简后再保存",+ memSecret: "内容看起来含有密码、密钥、令牌或证件号,记忆里不能保存这类信息",+ memTopicsFull: "主题已达上限 {max} 个,请把内容记到已有主题里",+ memDuplicate: "这条已经记过了",+ memTopicFull: "主题「{topic}」已满(上限 {cap} 字),请先 forget 过时的内容",+ memMainFull: "MEMORY.md 已满(上限 {cap} 字),请把细节记到某个 topic 里,或先 forget 过时的内容",+ memRemembered: "已记住({where})",+ memForgetEmpty: "请给出要删除的内容片段",+ memForgetNone: "{scope}里没有包含「{match}」的条目",+ memForgetMany: "有 {count} 条匹配,请写得更具体,或传 all: true 全部删除:\n{list}",+ memInTopic: "({topic})",+ memForgotten: "已删除 {count} 条({scope})",+} satisfies Catalog;++export const en: Catalog<typeof zh> = {+ cuNoRuntime: "Computer Use: unavailable (agent runtime missing)",+ cuDisabled: "Computer Use: turned off in this bot's settings",+ cuModeAsk: "ask me before clicking or typing",+ cuModeAuto: "actions run automatically",+ cuReasonMode: "{reason}; {mode}",+ hostNotStarted: "Agent process: not started (starts when a message arrives)",+ hostRunning: "Agent process: running (pid {pid}{init})",+ hostRunningInit: ", started in {s}s",+ hostStarting: "Agent process: starting ({s}s so far{first})",+ hostStartingFirst: "; the first start can take a few minutes",+ hostBackoff: "Agent process: last start failed, retrying soon ({error})",+ hostPaused: "Agent process: failed to start, paused ({error})",+ startRetryLater: "The agent process failed to start; try again in {min} min (or restart it in Settings → Troubleshooting): {error}",+ startPaused:+ "The agent process failed to start twice in a row and is paused for 10 minutes (replies use chat-only mode meanwhile). See the cause and restart it in Settings → Troubleshooting. Cause: {error}",+ gatewayNotReady: "The model gateway isn't ready",+ scopeTeam: "Team memory",+ scopeGroup: "Group memory",+ scopeBot: "Bot memory",+ memTopicInvalid: "Invalid topic name \"{topic}\": use only letters, digits, Chinese characters, - and _, up to 40 characters",+ memTopicReserved: "\"{topic}\" is a reserved topic name",+ memEmpty: "The content is empty",+ memTooLong: "A memory entry can be at most {max} characters (this one has {n}); shorten it and try again",+ memSecret: "This looks like it contains a password, key, token or ID number; memory can't store that kind of information",+ memTopicsFull: "The limit of {max} topics is reached; add this to an existing topic",+ memDuplicate: "Already remembered",+ memTopicFull: "Topic \"{topic}\" is full (limit {cap} characters); forget outdated entries first",+ memMainFull: "MEMORY.md is full (limit {cap} characters); put details in a topic, or forget outdated entries first",+ memRemembered: "Remembered ({where})",+ memForgetEmpty: "Give a snippet of the entry to delete",+ memForgetNone: "{scope} has no entry containing \"{match}\"",+ memForgetMany: "{count} entries match; be more specific, or pass all: true to delete them all:\n{list}",+ memInTopic: " ({topic})",+ memForgotten: { one: "Deleted 1 entry ({scope})", other: "Deleted {count} entries ({scope})" },+};diff --git a/src/i18n/messages/app.ts b/src/i18n/messages/app.tsnew file mode 100644index 0000000..f4b7adf--- /dev/null+++ b/src/i18n/messages/app.ts@@ -0,0 +1,42 @@+// app:zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。+import type { Catalog } from "../types.js";++export const zh = {+ external_mode: "外部模型端点模式下不管理 Modelflare 连接",+ bot_not_found: "机器人不存在",+ magpie_failed: "magpie 启动失败:{message}",+ // 第一次启动时建的机器人(按当时的语言)+ default_bot_name: "我的助手",+ default_bot_prompt: "你是一个乐于助人的中文助手,回答简洁准确。",+ feishu_failed: "机器人「{name}」飞书长连接启动失败:{message}",+ weixin_expired: "机器人「{name}」微信登录已过期,请在信息面板的「渠道」里重新扫码",+ weixin_connected: "机器人「{name}」微信已连接",+ // 收到的消息里图片 / 文件 / 语音的占位(core/types.ts eventText)+ media_image: "图片",+ media_file: "文件",+ media_video: "视频",+ media_quoted_image: "引用的图片",+ media_quoted_file: "引用的文件",+ media_quoted_video: "引用的视频",+ media_voice: "[语音]",+ media_not_downloaded: "{label}(未能下载:{error})",+} satisfies Catalog;++export const en: Catalog<typeof zh> = {+ external_mode: "Modelflare connections aren't managed when using an external model endpoint",+ bot_not_found: "Bot not found",+ magpie_failed: "magpie failed to start: {message}",+ default_bot_name: "My Assistant",+ default_bot_prompt: "You are a helpful assistant. Answer concisely and accurately.",+ feishu_failed: "Bot \"{name}\": Feishu long connection failed to start: {message}",+ weixin_expired: "Bot \"{name}\": WeChat sign-in expired. Scan the QR code again under Channels in the info panel",+ weixin_connected: "Bot \"{name}\": WeChat connected",+ media_image: "Image",+ media_file: "File",+ media_video: "Video",+ media_quoted_image: "Quoted image",+ media_quoted_file: "Quoted file",+ media_quoted_video: "Quoted video",+ media_voice: "[Voice]",+ media_not_downloaded: "{label} (couldn't download: {error})",+};diff --git a/src/i18n/messages/approvals.ts b/src/i18n/messages/approvals.tsnew file mode 100644index 0000000..ca2e3c2--- /dev/null+++ b/src/i18n/messages/approvals.ts@@ -0,0 +1,30 @@+// approvals:zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。+import type { Catalog } from "../types.js";++export const zh = {+ noSuchCode: "⚠️ 没有编号为 {code} 的待批准请求(可能已过期或已处理)",+ needCode: "有 {count} 个待批准请求,请带上编号回复,例如 y {code}",+ expiredOrDone: "⚠️ 请求 {code} 已过期或已处理",+ approved: "✅ 已批准 {code}(仅本次)",+ rejected: "❌ 已拒绝 {code}",+ prompt: "需批准: {tool}{cmd}{why} — 回复 y {code} / n {code}",+ promptWhy: "({reason})",+ hintMulti: "(每行回答一个问题:回复编号或直接写答案)",+ hintOptions: "(回复编号{multi},或直接写答案)",+ hintOptionsMulti: ",可多选用逗号分隔",+ hintFree: "(直接回复答案)",+} satisfies Catalog;++export const en: Catalog<typeof zh> = {+ noSuchCode: "⚠️ No request {code} is awaiting approval (it may have expired or been handled)",+ needCode: "{count} requests are awaiting approval; reply with the code, e.g. y {code}",+ expiredOrDone: "⚠️ Request {code} has expired or was already handled",+ approved: "✅ Approved {code} (this time only)",+ rejected: "❌ Denied {code}",+ prompt: "Approval needed: {tool}{cmd}{why} — reply y {code} / n {code}",+ promptWhy: " ({reason})",+ hintMulti: "(Answer one question per line: reply with an option number or type your answer)",+ hintOptions: "(Reply with an option number{multi}, or type your answer)",+ hintOptionsMulti: " or several separated by commas",+ hintFree: "(Type your answer)",+};diff --git a/src/i18n/messages/channel.ts b/src/i18n/messages/channel.tsnew file mode 100644index 0000000..af3c927--- /dev/null+++ b/src/i18n/messages/channel.ts@@ -0,0 +1,84 @@+// channel:zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。+import type { Catalog } from "../types.js";++export const zh = {+ // 发给微信 / 飞书用户+ file_failed: "⚠️ 文件「{name}」发送失败,可在工作区中查看。",+ handle_failed: "⚠️ 处理失败:{message}",+ reply_with_number: "(回复编号选择)",+ reply_truncated: "…(回复过长,已达到本轮可发送条数上限,请回复任意消息继续)",+ sent_file: "[文件] {name}",+ approval_title: "需批准({code})",+ question_title: "需要你的回答",+ card_generating: "[生成中…]",+ card_action_failed: "处理失败",+ unsupported_message: "[暂不支持的消息类型:{type}]",+ // 渠道状态(信息面板)+ feishu_no_credentials: "未配置凭据",+ wx_login_required: "尚未扫码登录",+ wx_expired: "登录已过期(-14),请在界面重新扫码",+ // 微信扫码登录+ login_cancelled: "已取消",+ login_terminal_scan: "用微信扫描二维码登录:",+ login_terminal_saved: "二维码图片已保存:{path}",+ login_wait: "请用微信扫码",+ login_fetching: "正在获取二维码…",+ login_scanned: "已扫码,请在微信上确认",+ login_need_code: "请输入微信上显示的验证码",+ login_already_bound: "该微信已绑定过此机器人,无需重复连接",+ login_qr_expired_too_often: "二维码多次过期,请重新开始登录",+ login_qr_refreshing: "二维码已过期,正在刷新({n}/{max})",+ login_no_token: "登录失败:服务器未返回 ilink_bot_id/bot_token",+ login_confirmed: "✅ 微信已连接",+ login_timeout: "登录超时,请重试",+ login_failed: "登录失败:{message}",+ // 微信收到的图片 / 文件下载失败(写进消息里,例如 [图片(未能下载:…)])+ aes_key_bad: "aes_key 解码后为 {len} 字节,应为 16 字节或 32 位十六进制",+ aes_key_missing: "缺少 aes_key",+ item_unsupported: "不支持下载的条目类型 {type}",+ full_url_bad: "full_url 不是 http(s) 地址",+ no_cdn_ref: "没有 CDN 引用",+ cdn_failed_http: "CDN 下载失败 HTTP {status} {message}",+ cdn_failed: "CDN 下载失败",+ too_large: "文件过大({size} MB,上限 {max} MB)",+ decrypt_failed: "解密失败(密钥不对?)",+} satisfies Catalog;++export const en: Catalog<typeof zh> = {+ file_failed: "⚠️ Couldn't send the file \"{name}\". You can find it in the workspace.",+ handle_failed: "⚠️ Something went wrong: {message}",+ reply_with_number: "(Reply with a number to choose)",+ reply_truncated: "… (Reply too long: reached the message limit for this turn. Send any message to continue)",+ sent_file: "[File] {name}",+ approval_title: "Approval needed ({code})",+ question_title: "Your answer is needed",+ card_generating: "[Generating…]",+ card_action_failed: "Failed",+ unsupported_message: "[Unsupported message type: {type}]",+ feishu_no_credentials: "Credentials not configured",+ wx_login_required: "Not signed in yet: scan the QR code",+ wx_expired: "Sign-in expired (-14). Scan the QR code again in the app",+ login_cancelled: "Cancelled",+ login_terminal_scan: "Scan the QR code with WeChat to sign in:",+ login_terminal_saved: "QR code image saved: {path}",+ login_wait: "Scan the QR code with WeChat",+ login_fetching: "Getting the QR code…",+ login_scanned: "Scanned. Confirm in WeChat",+ login_need_code: "Enter the verification code shown in WeChat",+ login_already_bound: "This WeChat account is already linked to this bot",+ login_qr_expired_too_often: "The QR code expired too many times. Please start again",+ login_qr_refreshing: "QR code expired, refreshing ({n}/{max})",+ login_no_token: "Sign-in failed: the server didn't return ilink_bot_id/bot_token",+ login_confirmed: "✅ WeChat connected",+ login_timeout: "Sign-in timed out. Please try again",+ login_failed: "Sign-in failed: {message}",+ aes_key_bad: "aes_key decodes to {len} bytes; expected 16 bytes or 32 hex characters",+ aes_key_missing: "aes_key is missing",+ item_unsupported: "Item type {type} can't be downloaded",+ full_url_bad: "full_url isn't an http(s) URL",+ no_cdn_ref: "No CDN reference",+ cdn_failed_http: "CDN download failed: HTTP {status} {message}",+ cdn_failed: "CDN download failed",+ too_large: "File too large ({size} MB, limit {max} MB)",+ decrypt_failed: "Decryption failed (wrong key?)",+};diff --git a/src/i18n/messages/cu.ts b/src/i18n/messages/cu.tsnew file mode 100644index 0000000..4abd5b9--- /dev/null+++ b/src/i18n/messages/cu.ts@@ -0,0 +1,51 @@+// cu:zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。+import type { Catalog } from "../types.js";++export const zh = {+ // Codex Computer Use 桥(computer-use.ts)+ codexUnavailable: "Codex Computer Use 桥: 需要 macOS 14.4+ 和已安装的 Codex Computer Use",+ codexOff: "{base}({why})",+ codexNotMac: "当前系统不是 macOS",+ codexOldMac: "macOS 版本低于 14.4",+ codexNoBridge: "安装包缺少 kimi-computer-use 组件",+ codexNoClient: "未找到 Codex Computer Use 客户端",+ codexNoLauncher: "未找到 ChatGPT/Codex 应用自带的 codex 启动器",+ codexAvailable: "Codex Computer Use 桥: 可用(macOS)",+ codexFallback: "(Codex 桥不可用,已改用 Cua Driver:{reason})",+ // Cua Driver(cua-driver.ts)+ cuaOff: "Cua Driver: 不可用({why})",+ cuaAvailable: "Cua Driver: 可用({os})",+ cuaUnsupported: "不支持 {platform}",+ cuaMissing: "安装包缺少 {plat} 的 cua-driver {version}",+ cuaNoDisplay: "没有图形会话:DISPLAY / WAYLAND_DISPLAY 均未设置",+ cuaAtspi: "需要 AT-SPI(at-spi2-core)才能读取窗口元素",+ cuaWayland: "Wayland 会话:功能降级——窗口读取依赖 AT-SPI,键鼠输入走 XWayland,只能操作前台窗口;{atspi}",+ cuaX11: "X11 会话;{atspi}",+ cuaMacNotice: "首次使用需在「系统设置 → 隐私与安全性」给本应用打开「辅助功能」和「屏幕录制」。以 --direct 模式运行,授权应归属本应用(尚未在真机验证)。",+ cuaWinNotice: "需在已登录用户的交互式桌面会话中运行;无法操作以管理员权限运行的窗口(除非本应用也以管理员运行)。",+ cuaNonInteractive: "需要在已登录用户的交互式会话中运行(检测到服务或非交互会话)",+} satisfies Catalog;++export const en: Catalog<typeof zh> = {+ codexUnavailable: "Codex Computer Use bridge: requires macOS 14.4+ with Codex Computer Use installed",+ codexOff: "{base} ({why})",+ codexNotMac: "this system isn't macOS",+ codexOldMac: "macOS is older than 14.4",+ codexNoBridge: "the kimi-computer-use component is missing from the installation",+ codexNoClient: "Codex Computer Use client not found",+ codexNoLauncher: "the codex launcher bundled with the ChatGPT/Codex app was not found",+ codexAvailable: "Codex Computer Use bridge: available (macOS)",+ codexFallback: " (Codex bridge unavailable, using Cua Driver instead: {reason})",+ cuaOff: "Cua Driver: unavailable ({why})",+ cuaAvailable: "Cua Driver: available ({os})",+ cuaUnsupported: "{platform} is not supported",+ cuaMissing: "cua-driver {version} for {plat} is missing from the installation",+ cuaNoDisplay: "no graphical session: neither DISPLAY nor WAYLAND_DISPLAY is set",+ cuaAtspi: "reading window elements requires AT-SPI (at-spi2-core)",+ cuaWayland: "Wayland session: limited — reading windows relies on AT-SPI, keyboard and mouse input go through XWayland, and only the foreground window can be operated; {atspi}",+ cuaX11: "X11 session; {atspi}",+ cuaMacNotice:+ "On first use, turn on Accessibility and Screen Recording for this app in System Settings → Privacy & Security. It runs in --direct mode, so the permissions should belong to this app (not yet verified on a real Mac).",+ cuaWinNotice: "Must run in a signed-in user's interactive desktop session; windows running as administrator can't be operated (unless this app also runs as administrator).",+ cuaNonInteractive: "must run in a signed-in user's interactive session (a service or non-interactive session was detected)",+};diff --git a/src/i18n/messages/desktop.ts b/src/i18n/messages/desktop.tsnew file mode 100644index 0000000..df18fea--- /dev/null+++ b/src/i18n/messages/desktop.ts@@ -0,0 +1,28 @@+// desktop:Electron 外壳(electron/main.ts)的托盘菜单与对话框。zh 与 en 的键必须一一对应(en 的类型由 zh 推出)。+import type { Catalog } from "../types.js";++export const zh = {+ trayOpen: "打开 {product}",+ trayOpenInBrowser: "在浏览器中打开",+ trayAutostart: "开机自启",+ trayOpenDataDir: "打开数据目录",+ trayQuit: "退出",+ errorTitle: "{product} 出错了",+ errorDetail: "{message}\n\n详细信息见日志:{log}",+ logDisabled: "(未启用)",+ bootFailed: "{product} 启动失败",+ uiNotStarted: "管理界面未启动",+} satisfies Catalog;++export const en: Catalog<typeof zh> = {+ trayOpen: "Open {product}",+ trayOpenInBrowser: "Open in browser",+ trayAutostart: "Launch at login",+ trayOpenDataDir: "Open data folder",+ trayQuit: "Quit",+ errorTitle: "{product} ran into a problem",+ errorDetail: "{message}\n\nSee the log for details: {log}",+ logDisabled: "(disabled)",+ bootFailed: "{product} couldn't start",+ uiNotStarted: "The local interface didn't start",+};diff --git a/src/i18n/messages/diag.ts b/src/i18n/messages/diag.tsnew file mode 100644index 0000000..5f753f6--- /dev/null+++ b/src/i18n/messages/diag.ts@@ -0,0 +1,165 @@+// diag:zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。+// 设置 → 故障排查:测试模型 / 测试代理的结果,以及可复制的诊断报告。+import type { Catalog } from "../types.js";++export const zh = {+ // 测试模型+ fetch_timeout: "超时({s} 秒内没有响应)",+ no_endpoint: "没有配置端点地址",+ no_model: "没有可用的模型:请先在 Modelflare 里选择默认模型",+ no_content: "响应里没有 choices[0].message.content:{body}",+ verdict_endpoint_ok: "端点正常",+ verdict_endpoint_error: "端点出错:{error}",+ verdict_both_ok: "内置网关与直连端点都正常",+ verdict_gateway_ok: "内置网关正常",+ verdict_direct_failed: "经内置网关正常,直连端点失败(网关可能用了别的线路或重试)",+ verdict_gateway_broken: "端点本身正常,问题在内置网关",+ verdict_gateway_failed_no_direct: "内置网关出错,未能直连对比",+ verdict_both_failed: "端点本身出错({error}),内置网关也失败",+ gateway_state: "{error}(内置网关状态:{state})",+ gateway_state_error: "{error}(内置网关状态:{state},{lastError})",+ skip_not_connected: "还没有连接 Modelflare",+ skip_external: "外部端点模式:机器人直接调用该端点,不经内置网关",+ // 测试代理+ stage_queue: "消息队列",+ stage_spawn: "启动代理进程",+ stage_plugins: "加载插件",+ stage_model: "调用模型",+ stage_reply: "得到回复",+ timeout_spawn: "代理进程 {s} 秒内没有完成启动(initialize 没有返回)",+ timeout_plugins: "代理进程已启动,但 {s} 秒内没有发出模型请求",+ timeout_model: "模型请求已发出,{s} 秒内上游没有响应",+ timeout_reply: "模型已响应,但代理 {s} 秒内没有结束这一轮",+ agent_off: "代理模式已关闭(AMB_AGENT=off),机器人只做纯对话",+ no_runtime: "找不到代理运行时(DSH),机器人只能纯对话",+ agent_no_model: "没有可用的模型:请先连接 Modelflare 并选择默认模型",+ queue_idle: "没有正在处理的回合",+ queue_busy: "{count} 轮对话正在处理(最长已 {s} 秒);同一会话的新消息会并入正在进行的回合(代理还没接手时排在后面)。卡住时用 /stop,或下面的\"重启代理进程\"",+ spawn_waiting: "等待正在进行的启动(已 {s} 秒,阶段:{stage})",+ spawn_initializing: "pid {pid},等待初始化…",+ agent_exited: "代理进程退出(code={code}, signal={signal})",+ agent_exited_stderr: "代理进程退出(code={code}, signal={signal});stderr:{stderr}",+ plugins_missing: "模型请求里缺少插件提供的工具:{tools}",+ plugins_tools: "{count} 个工具",+ http_error: "HTTP {status}:{error}",+ api_rejected: "({path} 被拒:{why};已改用 Chat Completions)",+ already_running: "已在运行(pid {pid})",+ no_request_seen: "(没有观察到模型请求)",+ no_response_seen: "(没有观察到上游响应)",+ no_text_reply: "回合结束了,但没有文字回复",+ stage_now: ";当前阶段:{stage}",+ stage_now_output: ";当前阶段:{stage};最近输出:{line}",+ timeout: "超时",+ // 诊断报告+ report_title: "anymodel bot 诊断信息 · {at}",+ report_version: "版本 {version} · {platform} {arch} · {os}{electron} · Node {node} · 运行 {uptime} 秒",+ report_data_dir: "数据目录 {dir}",+ report_log_file: "日志文件 {file}",+ report_not_enabled_paren: "(未启用)",+ report_default_model: "默认模型 {model}",+ report_auto: "(自动)",+ report_gateway_managed: "[模型网关] 内置 magpie · {state} · pid {pid} · 重启 {restarts} 次{lastExit}{lastError}",+ report_gateway_external: "[模型网关] 外部端点 {url}",+ report_last_exit: " · 上次退出 code={code} signal={signal}",+ report_agent: "[代理] {enabled} · 运行时 {runtime}",+ report_enabled: "已启用",+ report_not_enabled: "未启用",+ report_missing: "缺失",+ report_host: "机器人 {id}: {state} · pid {pid} · 重启 {restarts} 次 · 进行中 {active}{lastExit}",+ report_last_error: "最近错误:{error}",+ report_model_test: "[测试模型] {at} · 模型 {model} · {verdict}",+ report_via_gateway: "经内置网关",+ report_direct: "直连端点",+ report_probe_skipped: "{name}: 未测({reason})",+ report_probe: "{name}: {result} · HTTP {status} · {ms} ms · {url}",+ report_ok: "正常",+ report_failed: "失败",+ report_echoed: " · 回显模型 {model}",+ report_reply: " · 回复 {reply}",+ report_error: "错误:{error}",+ report_agent_test: "[测试代理] {at} · 机器人 {bot} · 模型 {model} · {result} · {ms} ms",+ report_passed: "通过",+ report_not_passed: "未通过({stage})",+ report_log_tail: "[最近 {count} 行日志]",+} satisfies Catalog;++export const en: Catalog<typeof zh> = {+ fetch_timeout: "Timed out (no response within {s}s)",+ no_endpoint: "No endpoint address configured",+ no_model: "No model available: choose a default model in Modelflare first",+ no_content: "No choices[0].message.content in the response: {body}",+ verdict_endpoint_ok: "Endpoint OK",+ verdict_endpoint_error: "Endpoint error: {error}",+ verdict_both_ok: "Built-in gateway and direct endpoint both OK",+ verdict_gateway_ok: "Built-in gateway OK",+ verdict_direct_failed: "OK via the built-in gateway, but the direct endpoint failed (the gateway may have used another route or retried)",+ verdict_gateway_broken: "The endpoint itself is fine; the problem is in the built-in gateway",+ verdict_gateway_failed_no_direct: "The built-in gateway failed; couldn't compare with a direct call",+ verdict_both_failed: "The endpoint itself failed ({error}), and so did the built-in gateway",+ gateway_state: "{error} (built-in gateway state: {state})",+ gateway_state_error: "{error} (built-in gateway state: {state}, {lastError})",+ skip_not_connected: "Modelflare isn't connected yet",+ skip_external: "External endpoint mode: bots call the endpoint directly, without the built-in gateway",+ stage_queue: "Message queue",+ stage_spawn: "Start agent process",+ stage_plugins: "Load plugins",+ stage_model: "Call model",+ stage_reply: "Get reply",+ timeout_spawn: "The agent process didn't finish starting within {s}s (initialize didn't return)",+ timeout_plugins: "The agent process started, but sent no model request within {s}s",+ timeout_model: "The model request was sent, but the upstream didn't respond within {s}s",+ timeout_reply: "The model responded, but the agent didn't finish the turn within {s}s",+ agent_off: "Agent mode is off (AMB_AGENT=off); bots are chat-only",+ no_runtime: "Agent runtime (DSH) not found; bots can only chat",+ agent_no_model: "No model available: connect Modelflare and choose a default model first",+ queue_idle: "No turns in progress",+ queue_busy: {+ one: "{count} turn in progress (running for {s}s); new messages in the same conversation join it (or wait behind it until the agent picks it up). If it's stuck, use /stop or \"Restart agent process\" below",+ other: "{count} turns in progress (longest running for {s}s); new messages in the same conversation join the turn in progress (or wait behind it until the agent picks it up). If they're stuck, use /stop or \"Restart agent process\" below",+ },+ spawn_waiting: "Waiting for a start already in progress ({s}s so far, stage: {stage})",+ spawn_initializing: "pid {pid}, waiting for initialization…",+ agent_exited: "Agent process exited (code={code}, signal={signal})",+ agent_exited_stderr: "Agent process exited (code={code}, signal={signal}); stderr: {stderr}",+ plugins_missing: "The model request is missing tools provided by plugins: {tools}",+ plugins_tools: { one: "{count} tool", other: "{count} tools" },+ http_error: "HTTP {status}: {error}",+ api_rejected: " ({path} was rejected: {why}; switched to Chat Completions)",+ already_running: "Already running (pid {pid})",+ no_request_seen: "(no model request observed)",+ no_response_seen: "(no upstream response observed)",+ no_text_reply: "The turn ended without a text reply",+ stage_now: "; current stage: {stage}",+ stage_now_output: "; current stage: {stage}; latest output: {line}",+ timeout: "Timed out",+ report_title: "anymodel bot diagnostics · {at}",+ report_version: "Version {version} · {platform} {arch} · {os}{electron} · Node {node} · up {uptime}s",+ report_data_dir: "Data directory {dir}",+ report_log_file: "Log file {file}",+ report_not_enabled_paren: "(disabled)",+ report_default_model: "Default model {model}",+ report_auto: "(auto)",+ report_gateway_managed: "[Model gateway] built-in magpie · {state} · pid {pid} · {restarts} restarts{lastExit}{lastError}",+ report_gateway_external: "[Model gateway] external endpoint {url}",+ report_last_exit: " · last exit code={code} signal={signal}",+ report_agent: "[Agent] {enabled} · runtime {runtime}",+ report_enabled: "enabled",+ report_not_enabled: "disabled",+ report_missing: "missing",+ report_host: "Bot {id}: {state} · pid {pid} · {restarts} restarts · {active} active{lastExit}",+ report_last_error: "Last error: {error}",+ report_model_test: "[Test model] {at} · model {model} · {verdict}",+ report_via_gateway: "Via built-in gateway",+ report_direct: "Direct endpoint",+ report_probe_skipped: "{name}: not tested ({reason})",+ report_probe: "{name}: {result} · HTTP {status} · {ms} ms · {url}",+ report_ok: "OK",+ report_failed: "failed",+ report_echoed: " · echoed model {model}",+ report_reply: " · reply {reply}",+ report_error: "Error: {error}",+ report_agent_test: "[Test agent] {at} · bot {bot} · model {model} · {result} · {ms} ms",+ report_passed: "passed",+ report_not_passed: "failed ({stage})",+ report_log_tail: { one: "[Last {count} log line]", other: "[Last {count} log lines]" },+};diff --git a/src/i18n/messages/index.ts b/src/i18n/messages/index.tsnew file mode 100644index 0000000..f9c3936--- /dev/null+++ b/src/i18n/messages/index.ts@@ -0,0 +1,17 @@+// 服务端文案的命名空间。新增命名空间:在这里加一行,键 = "命名空间.键"。+import * as web from "./web.js";+import * as desktop from "./desktop.js";+import * as app from "./app.js";+import * as diag from "./diag.js";+import * as modelflare from "./modelflare.js";+import * as account from "./account.js";+import * as magpie from "./magpie.js";+import * as channel from "./channel.js";+import * as runtime from "./runtime.js";+import * as agent from "./agent.js";+import * as approvals from "./approvals.js";+import * as media from "./media.js";+import * as cu from "./cu.js";+import * as pwsh from "./pwsh.js";++export const catalogs = { web, desktop, app, diag, modelflare, account, magpie, channel, runtime, agent, approvals, media, cu, pwsh };diff --git a/src/i18n/messages/magpie.ts b/src/i18n/messages/magpie.tsnew file mode 100644index 0000000..c03f3e4--- /dev/null+++ b/src/i18n/messages/magpie.ts@@ -0,0 +1,26 @@+// magpie:zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。+import type { Catalog } from "../types.js";++export const zh = {+ no_binary_cli: "找不到 magpie 可执行文件,请先运行 npm run setup",+ no_binary: "找不到 magpie 可执行文件(运行 npm run setup 从 vendor/magpie 构建)",+ unsupported_url: "不支持的 Modelflare 地址",+ missing_key: "缺少 API Key",+ create_failed: "创建 Modelflare 连接失败:{detail}",+ not_running: "模型网关未运行,稍后再试",+ disconnect_failed: "断开失败:HTTP {status} {body}",+ save_failed: "保存失败:HTTP {status} {body}",+ verify_failed: "保存后校验失败",+} satisfies Catalog;++export const en: Catalog<typeof zh> = {+ no_binary_cli: "magpie executable not found. Run npm run setup first",+ no_binary: "magpie executable not found (run npm run setup to build it from vendor/magpie)",+ unsupported_url: "Unsupported Modelflare address",+ missing_key: "API key is missing",+ create_failed: "Couldn't create the Modelflare connection: {detail}",+ not_running: "The model gateway isn't running. Try again shortly",+ disconnect_failed: "Disconnect failed: HTTP {status} {body}",+ save_failed: "Save failed: HTTP {status} {body}",+ verify_failed: "Verification failed after saving",+};diff --git a/src/i18n/messages/media.ts b/src/i18n/messages/media.tsnew file mode 100644index 0000000..ab465d2--- /dev/null+++ b/src/i18n/messages/media.ts@@ -0,0 +1,54 @@+// media:zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。+// 只有给用户看的部分(生成前的确认、参考价)在这里;工具结果与错误是给模型看的,留在 media.ts。+import type { Catalog } from "../types.js";++export const zh = {+ // 参考价+ pricePerSecond: "{price}/秒({res})",+ pricePerImage: "{price}/张",+ pricePerCall: "{price}/次",+ priceToken: "按 token 计费",+ // 确认里的摘要+ seconds: "{n} 秒",+ references: "{count} 个参考素材",+ summaryPrompt: "提示词:{prompt}",+ summaryParams: "参数:{params}",+ summaryPrice: "参考价:{price}",+ // 生成前的确认(manager.ts confirmMedia)+ confirmHeaderImage: "生成图片",+ confirmHeaderVideo: "生成视频",+ confirmQuestionImage: "这次用 {model} 生成图片吗?",+ confirmQuestionVideo: "这次用 {model} 生成视频吗?",+ confirmDetail: "{summary}{reason}\n也可以直接回复其他模型名。",+ reasonCost: "预计花费约 ${amount},超过 ${limit}",+ reasonCostUnknown: "这次的花费估算不出来",+ reasonModel: "不是默认模型(默认是 {model})",+ tagDefault: "默认",+ tagBotPick: "机器人选的",+ cancel: "取消",+ cancelDesc: "这次不生成",+} satisfies Catalog;++export const en: Catalog<typeof zh> = {+ pricePerSecond: "{price}/s ({res})",+ pricePerImage: "{price}/image",+ pricePerCall: "{price}/call",+ priceToken: "billed per token",+ seconds: "{n}s",+ references: { one: "1 reference", other: "{count} references" },+ summaryPrompt: "Prompt: {prompt}",+ summaryParams: "Settings: {params}",+ summaryPrice: "Estimated price: {price}",+ confirmHeaderImage: "Generate image",+ confirmHeaderVideo: "Generate video",+ confirmQuestionImage: "Generate this image with {model}?",+ confirmQuestionVideo: "Generate this video with {model}?",+ confirmDetail: "{summary}{reason}\nYou can also reply with another model name.",+ reasonCost: "Estimated cost about ${amount}, above ${limit}",+ reasonCostUnknown: "The cost of this run can't be estimated",+ reasonModel: "Not the default model (the default is {model})",+ tagDefault: "default",+ tagBotPick: "picked by the bot",+ cancel: "Cancel",+ cancelDesc: "Don't generate this time",+};diff --git a/src/i18n/messages/modelflare.ts b/src/i18n/messages/modelflare.tsnew file mode 100644index 0000000..9f3db37--- /dev/null+++ b/src/i18n/messages/modelflare.ts@@ -0,0 +1,26 @@+// modelflare:zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。+import type { Catalog } from "../types.js";++export const zh = {+ unreachable: "连不上 {host}({reason})",+ timeout: "超时",+ invalid_key: "Key 无效或已被撤销",+ forbidden: "这个 Key 没有权限调用该模型或分组",+ unavailable: "Modelflare 暂时不可用(HTTP {status}){retry}",+ retry_after: ",{s} 秒后重试",+ bad_models: "Modelflare 返回了无法识别的模型列表",+ balance_failed: "读取余额失败(HTTP {status})",+ bad_balance: "Modelflare 返回了无法识别的余额",+} satisfies Catalog;++export const en: Catalog<typeof zh> = {+ unreachable: "Can't reach {host} ({reason})",+ timeout: "timed out",+ invalid_key: "The key is invalid or has been revoked",+ forbidden: "This key isn't allowed to use this model or group",+ unavailable: "Modelflare is temporarily unavailable (HTTP {status}){retry}",+ retry_after: "; retry in {s}s",+ bad_models: "Modelflare returned a model list we couldn't read",+ balance_failed: "Couldn't read the balance (HTTP {status})",+ bad_balance: "Modelflare returned a balance we couldn't read",+};diff --git a/src/i18n/messages/pwsh.ts b/src/i18n/messages/pwsh.tsnew file mode 100644index 0000000..e83da18--- /dev/null+++ b/src/i18n/messages/pwsh.ts@@ -0,0 +1,114 @@+// pwsh:zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。+import type { Catalog } from "../types.js";++export const zh = {+ // 装在哪儿+ sourceProgramFiles: "安装目录",+ sourcePath: "PATH",+ sourcePreview: "预览版",+ sourceStore: "Microsoft Store",+ sourcePrivate: "应用内置",+ // 应用内置 PowerShell 7 的安装进度+ installWaiting: "准备中",+ installDownloading: "下载 {received} / {total} MB{pct}",+ installPct: "({n}%)",+ installExtracting: "解压",+ installVerifying: "核对签名",+ installTesting: "试运行",+ installDone: "已装好",+ installFailed: "没装上:{error}",+ unknownReason: "未知原因",+ slow: "代理执行命令用的是系统自带的 Windows PowerShell 5.1,每条可能要二三十秒",+ // 聊天里 /status 的一行+ statusChecking: "PowerShell:检测中",+ statusFallback: ";之前用的 {from} 起不来({reason}),已自动换掉",+ statusOk: "PowerShell:{version}(代理用它执行命令)",+ statusOkPrivate: "PowerShell:{version}(应用内置,代理用它执行命令)",+ statusInstalling: "PowerShell:正在为代理安装 PowerShell 7…{progress}。装好之前命令照常用 Windows PowerShell 5.1",+ statusPrivateBad: "PowerShell:应用内置的 PowerShell 7 用不了({reason}),{slow}。在 设置 → 故障排查 里可以一键重新安装",+ statusInstallFailed: "PowerShell:为代理安装 PowerShell 7 没有成功({error}),{slow}。在 设置 → 故障排查 里可以重试,或者自己安装:{winget}",+ statusUnsupported: "PowerShell:{reason},{slow}",+ statusSystemIssue: "系统里的 PowerShell 7 用不了({issue}),{slow}",+ statusOld: "PowerShell {version} 版本较旧,{slow}",+ statusNone: "没有安装 PowerShell 7,{slow}",+ adviceInstall: "装上 PowerShell 7,命令执行快得多,也更稳定:{winget}(或打开 {url})",+ advicePrivate: "应用可以自己装一份(不需要管理员权限):设置 → 故障排查 → 安装;或者:{winget}",+ statusAdvice: "PowerShell:{now}。{how}",+ // 诊断报告里的几行+ reportChecking: "[PowerShell] 检测中",+ reportWhere: " · {path}({source})",+ reportUnknownVersion: "7(版本未知)",+ reportOk: "[PowerShell] {version}{where} · 代理用它执行命令",+ reportSystemIssue: "[PowerShell] 系统里的 PowerShell 7 用不了{where} · {issue} · 代理用 {using}",+ reportDshDefault51: "Windows PowerShell 5.1(DSH 默认)",+ reportOld: "[PowerShell] {version} 版本较旧{where} · 建议安装 PowerShell 7",+ reportNone: "[PowerShell] 未安装 PowerShell 7:代理用 Windows PowerShell 5.1 执行命令(经沙箱每条约 25 秒,7 约 1 秒){forced}",+ reportForced: " · AMB_PWSH_FORCE 模拟",+ reportFallback: " 自动退回 {at}:{from} → {to} · {reason}",+ reportDshDefault: "DSH 默认",+ privateUnsupported: "不能装:{reason}",+ privateReady: "已就绪 · 试运行通过{test}",+ privateTest: "({ms} ms,{at})",+ privateBad: "用不了:{reason}",+ privateUntested: "已装,还没试运行",+ privateNotInstalled: "未安装",+ privateInstall: " · 安装:{progress}",+ policySystem: "已改回系统默认",+ policyAuto: "缺 7 时自动安装",+ policyManual: "不自动安装",+ privateLine: " 内置 PowerShell {version}{arch} · {state}{inst}{dir} · {policy}{ignore}",+} satisfies Catalog;++export const en: Catalog<typeof zh> = {+ sourceProgramFiles: "install folder",+ sourcePath: "PATH",+ sourcePreview: "preview",+ sourceStore: "Microsoft Store",+ sourcePrivate: "app-managed",+ installWaiting: "preparing",+ installDownloading: "downloading {received} / {total} MB{pct}",+ installPct: " ({n}%)",+ installExtracting: "extracting",+ installVerifying: "verifying the signature",+ installTesting: "test run",+ installDone: "installed",+ installFailed: "not installed: {error}",+ unknownReason: "unknown reason",+ slow: "the agent runs commands with the built-in Windows PowerShell 5.1, which can take 20–30 seconds each",+ statusChecking: "PowerShell: checking",+ statusFallback: "; {from} wouldn't start ({reason}), so it was replaced automatically",+ statusOk: "PowerShell: {version} (the agent runs commands with it)",+ statusOkPrivate: "PowerShell: {version} (app-managed; the agent runs commands with it)",+ statusInstalling: "PowerShell: installing PowerShell 7 for the agent… {progress}. Until it's ready, commands keep using Windows PowerShell 5.1",+ statusPrivateBad: "PowerShell: the app-managed PowerShell 7 can't be used ({reason}), so {slow}. Reinstall it in one click in Settings → Troubleshooting",+ statusInstallFailed: "PowerShell: installing PowerShell 7 for the agent didn't work ({error}), so {slow}. Retry in Settings → Troubleshooting, or install it yourself: {winget}",+ statusUnsupported: "PowerShell: {reason}, so {slow}",+ statusSystemIssue: "the PowerShell 7 on this system can't be used ({issue}), so {slow}",+ statusOld: "PowerShell {version} is outdated, so {slow}",+ statusNone: "PowerShell 7 isn't installed, so {slow}",+ adviceInstall: "Install PowerShell 7 for much faster, more reliable commands: {winget} (or open {url})",+ advicePrivate: "The app can install its own copy (no admin rights needed): Settings → Troubleshooting → Install; or: {winget}",+ statusAdvice: "PowerShell: {now}. {how}",+ reportChecking: "[PowerShell] checking",+ reportWhere: " · {path} ({source})",+ reportUnknownVersion: "7 (version unknown)",+ reportOk: "[PowerShell] {version}{where} · the agent runs commands with it",+ reportSystemIssue: "[PowerShell] the PowerShell 7 on this system can't be used{where} · {issue} · the agent uses {using}",+ reportDshDefault51: "Windows PowerShell 5.1 (DSH default)",+ reportOld: "[PowerShell] {version} is outdated{where} · installing PowerShell 7 is recommended",+ reportNone: "[PowerShell] PowerShell 7 not installed: the agent runs commands with Windows PowerShell 5.1 (about 25 s per command in the sandbox vs. about 1 s with 7){forced}",+ reportForced: " · simulated by AMB_PWSH_FORCE",+ reportFallback: " fell back automatically at {at}: {from} → {to} · {reason}",+ reportDshDefault: "DSH default",+ privateUnsupported: "can't be installed: {reason}",+ privateReady: "ready · test run passed{test}",+ privateTest: " ({ms} ms, {at})",+ privateBad: "can't be used: {reason}",+ privateUntested: "installed, not test-run yet",+ privateNotInstalled: "not installed",+ privateInstall: " · install: {progress}",+ policySystem: "switched back to the system default",+ policyAuto: "installs automatically when 7 is missing",+ policyManual: "no automatic install",+ privateLine: " app-managed PowerShell {version}{arch} · {state}{inst}{dir} · {policy}{ignore}",+};diff --git a/src/i18n/messages/runtime.ts b/src/i18n/messages/runtime.tsnew file mode 100644index 0000000..e32e26f--- /dev/null+++ b/src/i18n/messages/runtime.ts@@ -0,0 +1,144 @@+// runtime:zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。+import type { Catalog } from "../types.js";++export const zh = {+ help: [+ "可用命令:",+ "/model — 列出可用模型(带编号)",+ "/model <编号或模型名> — 切换当前会话的模型",+ "/reset — 清空当前会话的上下文(代理模式下同时开启新的代理会话;长期记忆保留)",+ "/new — 开始新的一段对话:旧对话归档并生成交接便条,长期记忆保留",+ "/status — 查看当前模型、代理状态和正在处理的消息走到了哪一步",+ "/stop — 中止正在处理的消息(只停这个会话,机器人的其它会话照常进行)",+ "/tasks — 列出这个会话的后台任务",+ "/stop <编号> — 停止 /tasks 里的一个后台任务",+ "/help — 显示本帮助",+ ].join("\n"),+ noModels: "没有可用模型:请先连接 Modelflare(设置 → Modelflare)",+ startingNote: "(代理还在启动,这条消息先由模型直接回答;启动完成后会自动用回代理。)",+ emptyReply: "(模型没有返回内容)",+ interrupted: "⚠️ 生成中断:{error}",+ modelFailed: "⚠️ 模型调用失败({model}):{error}",+ // /status+ autoModel: "(自动:第一个可用模型)",+ modeAgent: "代理模式(DeepSeek Harness,{sandbox})",+ sandboxWorkspace: "工作区沙箱",+ sandboxReadonly: "只读沙箱",+ sandboxFull: "完全权限:不经沙箱",+ fullWarning: "注意:完全权限下命令以你的用户身份直接运行,可以读写你电脑上的任何文件(包括 AnyModelBot 自己的数据);只有递归删除仍会先问你。在机器人设置里可以改回「工作区可写」。",+ backgroundTasks: "后台任务:{list}",+ backgroundTask: "「{title}」{stage}",+ modeChat: "纯对话模式",+ pendingApproval: "待批准 {code}",+ pendingQuestion: "待回答 {code}",+ cuCodex: "Codex 桥",+ cuOn: "已启用",+ cuOff: "未启用",+ cuLine: "电脑操作:{backend},{state}——{reason}",+ busy: "本会话上一条消息还在处理(已 {s} 秒),新消息会排在它后面",+ currentModel: "当前模型:{model}{suffix}",+ convSetting: "(会话设置)",+ runMode: "运行方式:{mode}",+ pending: "未决:{list}",+ listSep: ",",+ // 卡片按钮+ requestMissing: "请求不存在",+ requestDone: "请求 {code} 已处理或已过期",+ approvedOnce: "已批准 {code}(仅本次)",+ rejected: "已拒绝 {code}",+ expired: "已过期",+ submitted: "已提交",+ submitFailed: "提交失败",+ unknownAction: "未知操作",+ allowOnce: "允许(仅本次)",+ deny: "拒绝",+ // 代理回合+ agentReady: "代理已就绪,正在处理…",+ agentStarting: "代理正在启动…{elapsed}{first}",+ agentStartingElapsed: "(已 {s} 秒)",+ agentStartingFirst: "首次启动可能需要几分钟。",+ doneNoText: "(已完成,没有文字回复)",+ agentFailed: "⚠️ 代理执行失败:{error}",+ // 命令+ resetDone: "✅ 已清空本会话上下文",+ newAgentOnly: "⚠️ /new 只在代理模式下可用;纯对话模式请用 /reset",+ alreadyNew: "当前已经是新的一段对话",+ newFailed: "⚠️ 开新段失败:{error}",+ newDone: "✅ 已开始新的一段对话(旧对话已归档并留下交接便条,长期记忆保留)",+ modelListFailed: "⚠️ 获取模型列表失败:{error}",+ modelListEmpty: "暂无可用模型:请先连接 Modelflare(设置 → Modelflare)。",+ modelListHead: "可用模型(回复 /model 编号 切换):",+ modelCurrent: " ← 当前",+ modelReset: "✅ 已恢复为机器人默认模型",+ modelNotFound: "⚠️ 找不到模型「{name}」,发送 /model 查看列表",+ modelSwitched: "✅ 本会话已切换到 {model}",+} satisfies Catalog;++export const en: Catalog<typeof zh> = {+ help: [+ "Commands:",+ "/model — list available models (numbered)",+ "/model <number or name> — switch the model for this conversation",+ "/reset — clear this conversation's context (in agent mode, also starts a new agent session; long-term memory is kept)",+ "/new — start a new conversation: the old one is archived with a handoff note; long-term memory is kept",+ "/status — show the current model, the agent's state and how far the message in progress has got",+ "/stop — stop the message in progress (only this conversation; the bot's other conversations carry on)",+ "/tasks — list this conversation's background tasks",+ "/stop <number> — stop one of the background tasks listed by /tasks",+ "/help — show this help",+ ].join("\n"),+ noModels: "No models available: connect Modelflare first (Settings → Modelflare)",+ startingNote: "(The agent is still starting, so the model answered this message directly; the agent takes over automatically once it's ready.)",+ emptyReply: "(The model returned nothing)",+ interrupted: "⚠️ Generation interrupted: {error}",+ modelFailed: "⚠️ Model call failed ({model}): {error}",+ autoModel: "(auto: first available model)",+ modeAgent: "agent mode (DeepSeek Harness, {sandbox})",+ sandboxWorkspace: "workspace sandbox",+ sandboxReadonly: "read-only sandbox",+ sandboxFull: "full access: no sandbox",+ fullWarning: "Note: with full access, commands run directly as your user and can read and change any file on your computer (including AnyModelBot's own data); only recursive deletes still ask first. You can switch back to \"Workspace write\" in bot settings.",+ backgroundTasks: "Background tasks: {list}",+ backgroundTask: "\"{title}\" {stage}",+ modeChat: "chat-only mode",+ pendingApproval: "awaiting approval {code}",+ pendingQuestion: "awaiting answer {code}",+ cuCodex: "Codex bridge",+ cuOn: "on",+ cuOff: "off",+ cuLine: "Computer use: {backend}, {state} — {reason}",+ busy: "The previous message in this conversation is still being processed ({s}s so far); new messages queue behind it",+ currentModel: "Current model: {model}{suffix}",+ convSetting: " (conversation setting)",+ runMode: "Mode: {mode}",+ pending: "Pending: {list}",+ listSep: ", ",+ requestMissing: "Request not found",+ requestDone: "Request {code} was already handled or has expired",+ approvedOnce: "Approved {code} (this time only)",+ rejected: "Denied {code}",+ expired: "Expired",+ submitted: "Submitted",+ submitFailed: "Couldn't submit",+ unknownAction: "Unknown action",+ allowOnce: "Allow (this time only)",+ deny: "Deny",+ agentReady: "Agent ready, working on it…",+ agentStarting: "Agent starting…{elapsed}{first}",+ agentStartingElapsed: " ({s}s so far)",+ agentStartingFirst: " The first start can take a few minutes.",+ doneNoText: "(Done, no text reply)",+ agentFailed: "⚠️ Agent run failed: {error}",+ resetDone: "✅ Cleared this conversation's context",+ newAgentOnly: "⚠️ /new only works in agent mode; in chat-only mode use /reset",+ alreadyNew: "This is already a new conversation",+ newFailed: "⚠️ Couldn't start a new conversation: {error}",+ newDone: "✅ Started a new conversation (the old one is archived with a handoff note; long-term memory is kept)",+ modelListFailed: "⚠️ Couldn't get the model list: {error}",+ modelListEmpty: "No models available: connect Modelflare first (Settings → Modelflare).",+ modelListHead: "Available models (reply /model <number> to switch):",+ modelCurrent: " ← current",+ modelReset: "✅ Back to the bot's default model",+ modelNotFound: "⚠️ No model \"{name}\"; send /model to see the list",+ modelSwitched: "✅ This conversation now uses {model}",+};diff --git a/src/i18n/messages/web.ts b/src/i18n/messages/web.tsnew file mode 100644index 0000000..6d3c392--- /dev/null+++ b/src/i18n/messages/web.ts@@ -0,0 +1,54 @@+// web:本机界面接口(src/web/server.ts)的报错。zh 与 en 的键必须一一对应(en 的类型由 zh 推出)。+import type { Catalog } from "../types.js";++export const zh = {+ needJson: "需要 application/json",+ bodyTooLarge: "请求体过大",+ needToken: "需要访问令牌:打开 /?token=<令牌>",+ externalNoConnection: "外部模型端点模式下不管理 Modelflare 连接",+ externalNoAccount: "外部模型端点模式下不管理 Modelflare 账户",+ missingApiKey: "缺少 API Key",+ noBrowserLogin: "Docker 或远程部署时无法用浏览器登录,请改用 API Key",+ lowBalanceRange: "提醒线要在 0 到 1000 美元之间",+ badZoom: "不支持的缩放比例",+ badLang: "不支持的语言",+ noAutostart: "当前环境不支持开机自启",+ desktopOnly: "仅桌面版可用",+ unknownGuideStep: "未知的引导步骤",+ botNotFound: "机器人不存在",+ requestNotFound: "请求不存在",+ notApproval: "不是审批请求",+ requestDone: "请求已处理或已过期",+ submitFailed: "提交失败",+ conversationNotFound: "会话不存在",+ nameRequired: "名称不能为空",+ budgetRange: "预算要在 0 到 100000 美元之间",+ groupNotOwned: "群不属于该机器人",+ emptyText: "内容为空",+} satisfies Catalog;++export const en: Catalog<typeof zh> = {+ needJson: "Expected application/json",+ bodyTooLarge: "Request body too large",+ needToken: "Access token required: open /?token=<token>",+ externalNoConnection: "The Modelflare connection isn't managed in external endpoint mode",+ externalNoAccount: "The Modelflare account isn't managed in external endpoint mode",+ missingApiKey: "API key is missing",+ noBrowserLogin: "Browser sign-in isn't available in Docker or remote deployments. Use an API key instead",+ lowBalanceRange: "The alert threshold must be between $0 and $1,000",+ badZoom: "Unsupported zoom level",+ badLang: "Unsupported language",+ noAutostart: "Launch at login isn't supported here",+ desktopOnly: "Only available in the desktop app",+ unknownGuideStep: "Unknown checklist step",+ botNotFound: "Bot not found",+ requestNotFound: "Request not found",+ notApproval: "Not an approval request",+ requestDone: "This request was already handled or has expired",+ submitFailed: "Couldn't submit",+ conversationNotFound: "Conversation not found",+ nameRequired: "Name can't be empty",+ budgetRange: "The budget must be between $0 and $100,000",+ groupNotOwned: "This group doesn't belong to this bot",+ emptyText: "Message is empty",+};diff --git a/src/i18n/types.ts b/src/i18n/types.tsnew file mode 100644index 0000000..64491e7--- /dev/null+++ b/src/i18n/types.ts@@ -0,0 +1,8 @@+/** 一条文案:纯文本(可带 {占位符}),或按数量选的复数形式(count 参数,Intl.PluralRules 的类别) */+export type Msg = string | { one?: string; other: string };++/**+ * 一个命名空间的词典。zh 写成 `{ … } satisfies Catalog`,en 写成 `Catalog<typeof zh>`:+ * 键由 zh 推出,en 少键、多键都是类型错误。+ */+export type Catalog<T = Record<string, unknown>> = { [K in keyof T]: Msg };diff --git a/src/magpie/supervisor.ts b/src/magpie/supervisor.tsindex c784cc8..0749710 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 { lineLogger, logger, registerSecret } from "../log.js";+import { t } from "../i18n/index.js";import { BOT_PROVIDER_PREFIX, MODELFLARE_PROVIDER, botProviderId, keyTail, modelflareApiBases } from "../modelflare.js";const log = logger("magpie");@@ -197,7 +198,7 @@ export class MagpieSupervisor {/** 运行一次 magpie CLI(同一隔离环境)。secret 通过 stdin 传入,不出现在命令行参数里。 */runCli(args: string[], stdin?: string, timeoutMs = 20_000): Promise<{ code: number; stdout: string; stderr: string }> {- if (!this.binPath) return Promise.reject(new Error("找不到 magpie 可执行文件,请先运行 npm run setup"));+ if (!this.binPath) return Promise.reject(new Error(t("magpie.no_binary_cli")));if (!this.keys) this.prepare();return new Promise((resolve, reject) => {const p = spawn(this.binPath!, args, { env: this.env(), stdio: ["pipe", "pipe", "pipe"], windowsHide: true });@@ -223,7 +224,7 @@ export class MagpieSupervisor {async start(): Promise<void> {if (!this.binPath) {this.state = "failed";- this.lastError = "找不到 magpie 可执行文件(运行 npm run setup 从 vendor/magpie 构建)";+ this.lastError = t("magpie.no_binary");throw new Error(this.lastError);}this.stopping = false;@@ -444,13 +445,13 @@ export class MagpieSupervisor {}private async upsertProvider(existing: string | undefined, wantId: string, name: string, apiKey: string, baseUrl: string, allowed: string[], headers: Record<string, string>, picks: string[]): Promise<void> {- if (!allowed.includes(baseUrl)) throw new Error("不支持的 Modelflare 地址");- if (!apiKey.trim()) throw new Error("缺少 API Key");+ if (!allowed.includes(baseUrl)) throw new Error(t("magpie.unsupported_url"));+ if (!apiKey.trim()) throw new Error(t("magpie.missing_key"));registerSecret(apiKey.trim());let id = existing;if (!id) {const add = await this.runCli(["provider", "add", name, `id=${wantId}`, `url=${baseUrl}`, "key=placeholder-key"]);- if (add.code !== 0) throw new Error(`创建 Modelflare 连接失败:${(add.stderr || add.stdout).trim().slice(0, 300)}`);+ if (add.code !== 0) throw new Error(t("magpie.create_failed", { detail: (add.stderr || add.stdout).trim().slice(0, 300) }));id = this.hasProvider(wantId) ? wantId : await this.findProviderId(wantId);}await this.saveProvider(id, { ...modelflareApiBases(baseUrl), key: apiKey.trim(), headers, ...(picks.length ? { models: picks } : {}) });@@ -458,7 +459,7 @@ export class MagpieSupervisor {/** 切换线路:只改地址,key 不变(机器人自己的 provider 一起切) */async setModelflareUrl(baseUrl: string, allowed: string[]): Promise<void> {- if (!allowed.includes(baseUrl)) throw new Error("不支持的 Modelflare 地址");+ if (!allowed.includes(baseUrl)) throw new Error(t("magpie.unsupported_url"));for (const id of [this.modelflareId(), ...this.botProviderIds()]) if (id) await this.saveProvider(id, modelflareApiBases(baseUrl));}@@ -509,14 +510,14 @@ export class MagpieSupervisor {}private async deleteProvider(id: string): Promise<void> {- if (this.state !== "running") throw new Error("模型网关未运行,稍后再试");+ if (this.state !== "running") throw new Error(t("magpie.not_running"));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)}`);+ if (!res.ok) throw new Error(t("magpie.disconnect_failed", { status: res.status, body: (await res.text()).slice(0, 200) }));}hasProvider(id: string): boolean {@@ -571,7 +572,7 @@ export class MagpieSupervisor {}private async saveProvider(id: string, patch: Record<string, unknown>): Promise<void> {- if (this.state !== "running") throw new Error("模型网关未运行,稍后再试");+ if (this.state !== "running") throw new Error(t("magpie.not_running"));const p = this.readProviderRaw(id);if (!p) throw new Error(`provider ${id} not found`);const res = await fetch(`${this.webOrigin}/api/provider/save`, {@@ -580,9 +581,9 @@ export class MagpieSupervisor {body: JSON.stringify({ ...p, ...patch, from: id }),signal: AbortSignal.timeout(15_000),});- if (!res.ok) throw new Error(`保存失败:HTTP ${res.status} ${(await res.text()).slice(0, 200)}`);+ if (!res.ok) throw new Error(t("magpie.save_failed", { status: res.status, body: (await res.text()).slice(0, 200) }));const saved = this.readProviderRaw(id);- for (const [k, v] of Object.entries(patch)) if (JSON.stringify(saved?.[k] ?? {}) !== JSON.stringify(v ?? {})) throw new Error("保存后校验失败");+ for (const [k, v] of Object.entries(patch)) if (JSON.stringify(saved?.[k] ?? {}) !== JSON.stringify(v ?? {})) throw new Error(t("magpie.verify_failed"));}private readProviderRaw(id: string): Record<string, unknown> | undefined {diff --git a/src/modelflare.ts b/src/modelflare.tsindex 33ddb97..ac85570 100644--- a/src/modelflare.ts+++ b/src/modelflare.ts@@ -4,6 +4,8 @@* 飞行中的 POST 不跨主机重定向,所以线路由用户事先选定,不自动切换。* - 连接前用 GET {base}/models + Bearer 校验密钥;错误按状态码给出可操作的说明。*/+import { t } from "./i18n/index.js";+export type ModelflareLine = "auto" | "global" | "cn";export const MODELFLARE_LINES: Record<Exclude<ModelflareLine, "auto">, string> = {@@ -133,14 +135,14 @@ export async function verifyModelflareKey(return {ok: false,code: "network",- message: `连不上 ${host}(${(e as Error).name === "TimeoutError" ? "超时" : (e as Error).message})`,+ message: t("modelflare.unreachable", { host, reason: (e as Error).name === "TimeoutError" ? t("modelflare.timeout") : (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})` };+ if (res.status === 401) return { ok: false, code: "invalid_key", status: 401, message: t("modelflare.invalid_key") };+ if (res.status === 403) return { ok: false, code: "forbidden", status: 403, message: t("modelflare.forbidden") };+ if (res.status === 429) return { ok: false, code: "rate_limited", status: 429, message: t("modelflare.unavailable", { status: 429, retry: retryAfter(res) }) };+ if (!res.ok) return { ok: false, code: "upstream", status: res.status, message: t("modelflare.unavailable", { status: res.status, retry: "" }) };try {const body = (await res.json()) as { data?: Array<{ id?: unknown; kind?: unknown }> };if (!Array.isArray(body.data)) throw new Error("no data[]");@@ -152,13 +154,13 @@ export async function verifyModelflareKey(chatModels: rows.filter((m) => !classified || m.kind === "text").map((m) => m.id).sort(),};} catch {- return { ok: false, code: "bad_response", status: res.status, message: "Modelflare 返回了无法识别的模型列表" };+ return { ok: false, code: "bad_response", status: res.status, message: t("modelflare.bad_models") };}}function retryAfter(res: Response): string {const s = res.headers.get("retry-after");- return s ? `,${s} 秒后重试` : "";+ return s ? t("modelflare.retry_after", { s }) : "";}function safeHost(url: string): string {@@ -190,10 +192,10 @@ export async function fetchKeyBalance(baseUrl: string, apiKey: string, fetchImplheaders: { Authorization: `Bearer ${apiKey}`, Accept: "application/json" },signal: AbortSignal.timeout(15_000),});- if (!res.ok) throw new Error(`读取余额失败(HTTP ${res.status})`);+ if (!res.ok) throw new Error(t("modelflare.balance_failed", { status: res.status }));const body = (await res.json()) as { total_available?: unknown; total_used?: unknown; unit?: unknown };const available = Number(body.total_available);const used = Number(body.total_used);- if (!Number.isFinite(available)) throw new Error("Modelflare 返回了无法识别的余额");+ if (!Number.isFinite(available)) throw new Error(t("modelflare.bad_balance"));return { available, used: Number.isFinite(used) ? used : 0, unit: typeof body.unit === "string" && body.unit ? body.unit : "USD" };}diff --git a/src/web/server.ts b/src/web/server.tsindex 616080c..9302c74 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -19,9 +19,11 @@ import { connectionFromPids } from "../agent/peer-guard.js";import type { ApprovalRow } from "../store/db.js";import { normalizeSettings } from "../agent/settings.js";import { scopeLabel } from "../agent/memory.js";-import { pwshProbe, type PwshMode } from "../agent/pwsh.js";+import { pwshProbe, type PwshMode, type PwshStatus } from "../agent/pwsh.js";import { peerName, shortPeer, whoText } from "../core/access.js";import type { AccessEntry } from "../store/db.js";+import { GUIDE_STEPS, deriveGuide, isGuideStep, mergeGuide, normalizeGuide, type GuideState } from "../guide.js";+import { normalizeLang, requestLang, setLangPref, t, type LangPref } from "../i18n/index.js";const log = logger("web");const require = createRequire(import.meta.url);@@ -73,11 +75,11 @@ class HttpError extends Error {async function readJson(req: http.IncomingMessage): Promise<any> {const ct = String(req.headers["content-type"] || "");- if (!ct.includes("application/json")) throw new HttpError(415, "需要 application/json");+ if (!ct.includes("application/json")) throw new HttpError(415, t("web.needJson"));let body = "";for await (const c of req) {body += c;- if (body.length > 1_000_000) throw new HttpError(413, "请求体过大");+ if (body.length > 1_000_000) throw new HttpError(413, t("web.bodyTooLarge"));}return body ? JSON.parse(body) : {};}@@ -257,7 +259,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strres.end();return false;}- res.writeHead(401, { "content-type": "text/plain; charset=utf-8" }).end("需要访问令牌:打开 /?token=<令牌>");+ res.writeHead(401, { "content-type": "text/plain; charset=utf-8" }).end(t("web.needToken"));return false;}@@ -267,7 +269,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strconst seg = p.split("/").filter(Boolean);// 写操作要求 JSON(触发 CORS 预检,阻止跨站表单 CSRF)if ((m === "POST" || m === "PUT" || m === "PATCH") && !/^application\/json\s*(;|$)/i.test(String(req.headers["content-type"] || "").trim())) {- throw new HttpError(415, "需要 application/json");+ throw new HttpError(415, t("web.needJson"));}if (p === "/status" && m === "GET") {@@ -292,13 +294,13 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str}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 (m !== "GET" && !app.magpie) throw new HttpError(409, t("web.externalNoConnection"));}if (p === "/modelflare") {if (m === "PUT") {const b = await readJson(req);const apiKey = String(b.apiKey ?? "").trim();- if (!apiKey) throw new HttpError(400, "缺少 API Key");+ if (!apiKey) throw new HttpError(400, t("web.missingApiKey"));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 });@@ -322,7 +324,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str}if (seg[0] === "account") {const sub = seg.slice(1).join("/");- if (m !== "GET" && !app.magpie) throw new HttpError(409, "外部模型端点模式下不管理 Modelflare 账户");+ if (m !== "GET" && !app.magpie) throw new HttpError(409, t("web.externalNoAccount"));// 浏览器登录的回调落在本程序所在机器的 127.0.0.1;界面监听在非本机地址(Docker、远程部署)时,// 用户的浏览器访问不到它,只能粘贴 API Keyconst loginAvailable = isLoopback(host);@@ -334,7 +336,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strreturn send(res, 200, status());}if (sub === "login" && m === "POST") {- if (!loginAvailable) throw new HttpError(409, "Docker 或远程部署时无法用浏览器登录,请改用 API Key");+ if (!loginAvailable) throw new HttpError(409, t("web.noBrowserLogin"));const loginUrl = await accountCall(() => app.account.startLogin());app.desktop?.openExternal(loginUrl);return send(res, 200, { ...status(), loginUrl, opened: !!app.desktop });@@ -352,7 +354,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strconst mf = cfg.modelflare;if (b.lowBalanceUsd !== undefined) {const v = normalizeLowBalance(b.lowBalanceUsd);- if (v !== Number(b.lowBalanceUsd)) throw new HttpError(400, "提醒线要在 0 到 1000 美元之间");+ if (v !== Number(b.lowBalanceUsd)) throw new HttpError(400, t("web.lowBalanceRange"));mf.lowBalanceUsd = v;}if (b.lowBalancePush !== undefined) mf.lowBalancePush = !!b.lowBalancePush;@@ -384,13 +386,20 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str}if (b.zoom !== undefined) {const z = Number(b.zoom);- if (!ZOOMS.includes(z)) throw new HttpError(400, "不支持的缩放比例");+ if (!ZOOMS.includes(z)) throw new HttpError(400, t("web.badZoom"));cfg.ui.zoom = z;saveConfigFile(cfg.dataDir, (f) => (f.ui = { ...(f.ui ?? {}), zoom: z }));app.desktop?.applyZoom(z);}+ if (b.lang !== undefined) {+ const l = b.lang === "system" ? "system" : normalizeLang(b.lang);+ if (!l) throw new HttpError(400, t("web.badLang"));+ cfg.ui.lang = l as LangPref;+ saveConfigFile(cfg.dataDir, (f) => (f.ui = { ...(f.ui ?? {}), lang: l }));+ setLangPref(cfg.ui.lang);+ }if (b.autostart !== undefined) {- if (!app.desktop?.autostart().supported) throw new HttpError(400, "当前环境不支持开机自启");+ if (!app.desktop?.autostart().supported) throw new HttpError(400, t("web.noAutostart"));app.desktop.setAutostart(!!b.autostart);}} else if (m !== "GET") throw new HttpError(405, "method not allowed");@@ -400,6 +409,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strvideoModel: cfg.media.videoModel,closeToTray: cfg.ui.closeToTray,zoom: cfg.ui.zoom,+ lang: cfg.ui.lang,autostart: app.desktop ? app.desktop.autostart() : { supported: false, on: false },desktop: !!app.desktop,listen: { host, port: boundPort, tokenRequired: !!token },@@ -417,12 +427,18 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strreturn 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, "仅桌面版可用");+ if (!app.desktop) throw new HttpError(400, t("web.desktopOnly"));app.desktop.openDataDir();return send(res, 200, { ok: true });}+ // 界面主题变了(或刚加载完):窗口按钮的符号颜色跟着换。只有 Windows 桌面版有这个钩子,其他环境静默忽略+ if (p === "/desktop/title-bar" && m === "POST") {+ const b = await readJson(req);+ app.desktop?.setTitleBarTheme?.(b.dark === true);+ return send(res, 200, { ok: true });+ }if (p === "/desktop/open-in-browser" && m === "POST") {- if (!app.desktop) throw new HttpError(400, "仅桌面版可用");+ if (!app.desktop) throw new HttpError(400, t("web.desktopOnly"));app.desktop.openInBrowser();return send(res, 200, { ok: true });}@@ -505,6 +521,36 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str}throw new HttpError(405, "method not allowed");}+ // —— 新手引导(上手清单):进度写进 config.json;读的时候把能从数据里看出来做过的步骤并进去 ——+ if (p === "/guide") {+ const save = (g: GuideState) => {+ cfg.ui.guide = g;+ saveConfigFile(cfg.dataDir, (f) => (f.ui = { ...(f.ui ?? {}), guide: g }));+ };+ if (m === "PUT") {+ const b = await readJson(req);+ const add: unknown[] = b.done === undefined ? [] : Array.isArray(b.done) ? b.done : [b.done];+ if (!add.every(isGuideStep)) throw new HttpError(400, t("web.unknownGuideStep"));+ const g = b.reset ? normalizeGuide({}) : cfg.ui.guide;+ save(normalizeGuide({+ done: [...g.done, ...add],+ hidden: b.hidden !== undefined ? !!b.hidden : g.hidden,+ seen: [...g.seen, ...(typeof b.seen === "string" ? [b.seen] : [])],+ }));+ } else if (m !== "GET") throw new HttpError(405, "method not allowed");+ const bots = app.store.listBots();+ const derived = deriveGuide({+ conversations: app.store.listConversations(),+ bots,+ weixinBound: (id) => !!app.store.getWeixinAccount(id),+ // 机器人自己的记忆,或所有机器人共享的团队记忆,有一条就算记下过+ memoryCount: (id) =>+ [{ kind: "bot" as const, id }, { kind: "team" as const, id: "" }].reduce((n, s) => n + app.agent.memory.entries(s).length + app.agent.memory.topics(s).length, 0),+ });+ const merged = mergeGuide(cfg.ui.guide, derived);+ if (merged.done.length !== cfg.ui.guide.done.length) save(merged);+ return send(res, 200, { steps: GUIDE_STEPS, ...cfg.ui.guide });+ }// —— 故障排查(设置 → 故障排查):所有输出都已脱敏 ——if (seg[0] === "diagnostics") {const sub = seg.slice(1).join("/");@@ -517,13 +563,13 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strif (sub === "test-model" && m === "POST") {const b = await readJson(req);const botId = b.botId ? String(b.botId) : undefined;- if (botId && !app.store.getBot(botId)) throw new HttpError(404, "机器人不存在");+ if (botId && !app.store.getBot(botId)) throw new HttpError(404, t("web.botNotFound"));return send(res, 200, await testModel(app, { botId, model: b.model ? String(b.model) : undefined, timeoutMs: b.timeoutMs ? Number(b.timeoutMs) : undefined }));}if (sub === "test-agent" && m === "POST") {const b = await readJson(req);const botId = b.botId ? String(b.botId) : undefined;- if (botId && !app.store.getBot(botId)) throw new HttpError(404, "机器人不存在");+ if (botId && !app.store.getBot(botId)) throw new HttpError(404, t("web.botNotFound"));return send(res, 200, await testAgent(app, { botId, model: b.model ? String(b.model) : undefined, timeoutMs: b.timeoutMs ? Number(b.timeoutMs) : undefined }));}if (sub === "restart-agent" && m === "POST") {@@ -540,21 +586,21 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strreturn send(res, 200, { approvals: app.store.listApprovals({ status: status as any, botId: url.searchParams.get("bot") || undefined, limit: 100 }).map(publicApproval) });}const row = seg[1] ? app.store.getApproval(decodeURIComponent(seg[1])) : undefined;- if (!row) throw new HttpError(404, "请求不存在");+ if (!row) throw new HttpError(404, t("web.requestNotFound"));if (seg.length === 2 && m === "GET") return send(res, 200, { approval: publicApproval(row) });if (seg.length === 3 && m === "POST" && (seg[2] === "approve" || seg[2] === "deny")) {- if (row.kind !== "approval") throw new HttpError(400, "不是审批请求");+ if (row.kind !== "approval") throw new HttpError(400, t("web.notApproval"));const ok = app.agent.approvals.decide(row.id, seg[2] === "approve", "web");- if (!ok) throw new HttpError(409, "请求已处理或已过期");+ if (!ok) throw new HttpError(409, t("web.requestDone"));return send(res, 200, { approval: publicApproval(app.store.getApproval(row.id)!) });}if (seg.length === 3 && m === "POST" && seg[2] === "answer") {- if (row.kind !== "question" || row.status !== "pending") throw new HttpError(409, "请求已处理或已过期");+ if (row.kind !== "question" || row.status !== "pending") throw new HttpError(409, t("web.requestDone"));const b = await readJson(req);const ok = Array.isArray(b.answers)? app.agent.approvals.answer(row.id, { answers: b.answers.map((a: any) => ({ id: String(a.id), selected: (a.selected ?? []).map(String), ...(a.custom ? { custom: String(a.custom) } : {}) })) }, "web"): app.agent.approvals.handleReply(row.conversationId, String(b.text ?? ""), "web").handled;- if (!ok) throw new HttpError(409, "提交失败");+ if (!ok) throw new HttpError(409, t("web.submitFailed"));return send(res, 200, { approval: publicApproval(app.store.getApproval(row.id)!) });}}@@ -562,7 +608,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strif (seg.length === 1 && m === "GET") return send(res, 200, { conversations: app.store.listConversations(url.searchParams.get("bot") || undefined) });if (seg.length === 3 && seg[2] === "messages" && m === "GET") {const conv = app.store.getConversation(decodeURIComponent(seg[1]));- if (!conv) throw new HttpError(404, "会话不存在");+ if (!conv) throw new HttpError(404, t("web.conversationNotFound"));return send(res, 200, { conversation: conv, messages: app.store.listMessages(conv.id) });}// 一条回复的代理活动记录(展开时才取)@@ -584,7 +630,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strif (m === "GET") return send(res, 200, { bots: app.store.listBots().map(publicBot) });if (m === "POST") {const b = await readJson(req);- if (!String(b.name || "").trim()) throw new HttpError(400, "名称不能为空");+ if (!String(b.name || "").trim()) throw new HttpError(400, t("web.nameRequired"));const bot = app.store.createBot({name: String(b.name).trim(),systemPrompt: String(b.systemPrompt ?? ""),@@ -597,7 +643,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str}const id = seg[1];const bot = id ? app.store.getBot(id) : undefined;- if (!bot) throw new HttpError(404, "机器人不存在");+ if (!bot) throw new HttpError(404, t("web.botNotFound"));if (seg.length === 2) {if (m === "GET") return send(res, 200, { bot: publicBot(bot), channels: app.channelStatus(id) });if (m === "PUT") {@@ -637,7 +683,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strif (sub === "budget" && m === "PUT") {const b = await readJson(req);const limitUsd = Number(b.limitUsd ?? bot.settings.budget.limitUsd);- if (!Number.isFinite(limitUsd) || limitUsd < 0 || limitUsd > 100_000) throw new HttpError(400, "预算要在 0 到 100000 美元之间");+ if (!Number.isFinite(limitUsd) || limitUsd < 0 || limitUsd > 100_000) throw new HttpError(400, t("web.budgetRange"));const next = await accountCall(() => app.setBotBudget(id, normalizeSettings({ budget: { enabled: !!b.enabled, limitUsd } }).budget));return send(res, 200, { settings: next.settings });}@@ -666,7 +712,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strconst b = await readJson(req);const kind = String(b.kind ?? "bot");const scope = kind === "team" ? { kind: "team" as const, id: "" } : kind === "group" ? { kind: "group" as const, id: String(b.id ?? "") } : { kind: "bot" as const, id };- if (scope.kind === "group" && !scope.id.startsWith(id + ":")) throw new HttpError(400, "群不属于该机器人");+ if (scope.kind === "group" && !scope.id.startsWith(id + ":")) throw new HttpError(400, t("web.groupNotOwned"));try {const text = app.agent.memory.forget(scope, String(b.match ?? ""), { topic: b.topic ? String(b.topic) : undefined, by: "web" });return send(res, 200, { ok: true, text });@@ -792,20 +838,20 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strif (sub === "chat" && m === "POST") {const b = await readJson(req);const text = String(b.text ?? "").trim();- if (!text) throw new HttpError(400, "内容为空");+ if (!text) throw new HttpError(400, t("web.emptyText"));const ev = webEvent(id, text);const intercepted = interceptWeb(ev);if (intercepted.handled) return send(res, 200, { reply: intercepted.ack ?? "", prompts: [] });const out = new CollectReply();- const t = startLive(id, text);- await runLive(t, ev, { apply: async (op) => (await t.apply(op), await out.apply(op)) });+ const lt = startLive(id, text);+ await runLive(lt, ev, { apply: async (op) => (await lt.apply(op), await out.apply(op)) });return send(res, 200, { reply: out.text, prompts: out.prompts, files: out.files, conversationId: consoleConvId(id) });}// 断开连接(切走、刷新、关窗口)不再中止这条消息:回合照常跑完,界面回来时经 chat/live 接上;停止走 /conversations/:id/stopif (sub === "chat/stream" && m === "POST") {const b = await readJson(req);const text = String(b.text ?? "").trim();- if (!text) throw new HttpError(400, "内容为空");+ if (!text) throw new HttpError(400, t("web.emptyText"));const ev = webEvent(id, text);const out = new SseReply(res);try {@@ -817,10 +863,10 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str} catch (e) {return out.end("error", { message: (e as Error).message });}- const t = startLive(id, text);- const off = t.subscribe((e, d) => (e === "done" || e === "error" ? out.end(e, d) : out.send(e, d)));+ const lt = startLive(id, text);+ const off = lt.subscribe((e, d) => (e === "done" || e === "error" ? out.end(e, d) : out.send(e, d)));res.on("close", off);- await runLive(t, ev);+ await runLive(lt, ev);return;}}@@ -835,7 +881,14 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str});}+ // 界面请求带 x-amb-lang(界面当前的语言):整个请求里的报错和状态文字都用这种语言(src/i18n);+ // 没带的(curl、旧页面)按应用的语言偏好。连接关闭后,请求里启动的后台任务退回应用语言const server = http.createServer((req, res) => {+ const scope = requestLang(normalizeLang(req.headers["x-amb-lang"]));+ res.once("close", scope.end);+ scope.run(() => handle(req, res));+ });+ function handle(req: http.IncomingMessage, res: http.ServerResponse): void {const url = new URL(req.url || "/", "http://localhost");if (!authorized(req, url, res)) return;if (url.pathname.startsWith("/amb/api/")) {@@ -859,7 +912,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strif (url.pathname === "/amb/healthz") return send(res, 200, { ok: true });// 不再反代内置网关的界面或 /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;diff --git a/test/design-system.unit.test.ts b/test/design-system.unit.test.tsindex f0e019f..2ee4ca5 100644--- a/test/design-system.unit.test.ts+++ b/test/design-system.unit.test.ts@@ -100,6 +100,7 @@ const SIDE_BAR = /inset\s+-?([\d.]+)px\s+0\s+0\b/;/** 宽度:取声明里第一个长度(px 或 calc/var 都算"有宽度") */const edgeWidth = (v: string) => {if (/^\s*(0|none)\s*(!important)?\s*$/.test(v) || /^\s*(0|none)\s/.test(v)) return 0;+ if (/^\s*var\(--hairline\)/.test(v)) return 1; // 细线 token:一个物理像素(1px / 高分屏 .5px)const px = v.match(/(?<![\w.-])([\d.]+)px\b/);return px ? parseFloat(px[1]) : /calc\(|var\(|\b(thin|medium|thick)\b/.test(v) ? Infinity : 0;};@@ -173,8 +174,10 @@ describe("设计规范", () => {".g { border: 1px solid var(--ctl-edge); } /* 描边:输入框的边 */",".h { --x-edge: 0 0 0 var(--w) var(--line); }",".i { border-bottom: 2px solid var(--accent); }",+ ".j { border-top: var(--hairline) solid var(--line-2); }",+ ".k { border-left: var(--w) solid var(--red); }",].join("\n"));- expect(lintEdgesCss(tmp).map((h) => h.split(" ")[0].split(":").pop())).toEqual(["1", "2", "3", "4", "8", "9"]);+ expect(lintEdgesCss(tmp).map((h) => h.split(" ")[0].split(":").pop())).toEqual(["1", "2", "3", "4", "8", "9", "11"]);} finally {fs.rmSync(path.dirname(tmp), { recursive: true, force: true });}diff --git a/test/e2e.test.ts b/test/e2e.test.tsindex ffdf351..5e06f2a 100644--- a/test/e2e.test.ts+++ b/test/e2e.test.ts@@ -273,6 +273,11 @@ describe("Web 界面 / API", () => {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 r = await api("/desktop/title-bar", { method: "POST", body: { dark: true } });+ expect(r.status).toBe(200);+ expect(r.json).toEqual({ ok: true });+ });it("许可与第三方声明可在界面查看", async () => {const n = await api("/notices");expect(n.json.license).toContain("MIT");diff --git a/test/guide.unit.test.ts b/test/guide.unit.test.tsnew file mode 100644index 0000000..ec8a2a9--- /dev/null+++ b/test/guide.unit.test.ts@@ -0,0 +1,93 @@+// 新手引导(上手清单):进度的规整、从数据推导已做过的步骤、/guide 接口与 config.json 持久化。+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { App } from "../src/app.js";+import { loadConfig } from "../src/config.js";+import { GUIDE_STEPS, deriveGuide, mergeGuide, normalizeGuide } from "../src/guide.js";++describe("引导进度", () => {+ it("规整:只留认识的步骤并按清单排序,seen 去重、过滤非法 id", () => {+ expect(normalizeGuide(undefined)).toEqual({ done: [], hidden: false, seen: [] });+ expect(normalizeGuide({ done: ["media", "hello", "nope", "hello"], hidden: true, seen: ["intro", "intro", "bad id!", 3] })).toEqual({+ done: ["hello", "media"],+ hidden: true,+ seen: ["intro"],+ });+ });++ it("推导:有过回复、换过模型、绑了渠道、记下过东西", () => {+ const none = { conversations: [], bots: [], weixinBound: () => false, memoryCount: () => 0 };+ expect(deriveGuide(none)).toEqual([]);+ expect(deriveGuide({ ...none, conversations: [{ messageCount: 1, model: "" }] })).toEqual([]);+ expect(+ deriveGuide({+ conversations: [{ messageCount: 2, model: "" }],+ bots: [{ id: "a", defaultModel: "gpt-x", feishuAppId: "" }, { id: "b", defaultModel: "", feishuAppId: "" }],+ weixinBound: (id) => id === "b",+ memoryCount: (id) => (id === "a" ? 1 : 0),+ }),+ ).toEqual(["hello", "model", "weixin", "memory"]);+ expect(deriveGuide({ ...none, bots: [{ id: "a", defaultModel: "", feishuAppId: "cli_x" }] })).toEqual(["weixin"]);+ });++ it("合并保持清单顺序", () => {+ expect(mergeGuide({ done: ["media"], hidden: false, seen: [] }, ["hello"]).done).toEqual(["hello", "media"]);+ expect(GUIDE_STEPS).toEqual(["hello", "model", "weixin", "hands", "memory", "media"]);+ });+});++describe("界面接口 /guide", () => {+ let app: App;+ let base = "";+ const TOKEN = "ui-token-guide-0123456789";+ const api = async (p: string, init: { method?: string; body?: unknown } = {}) => {+ const res = await fetch(`${base}/amb/api${p}`, {+ method: init.method ?? "GET",+ headers: { "x-amb-token": TOKEN, ...(init.body !== undefined ? { "content-type": "application/json" } : {}) },+ body: init.body !== undefined ? JSON.stringify(init.body) : undefined,+ });+ return { status: res.status, json: (await res.json()) as any };+ };++ beforeAll(async () => {+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-guide-"));+ const config = loadConfig({ dataDir, env: { AMB_MAGPIE_BASE_URL: "http://127.0.0.1:9/v1", AMB_UI_PORT: "0", AMB_UI_TOKEN: TOKEN, AMB_AGENT: "off", AMB_WEIXIN_API_BASE: "http://127.0.0.1:9" } });+ app = new App(config, { printQrToTerminal: false });+ await app.start();+ base = app.web!.url.replace(/\/$/, "");+ });+ afterAll(async () => {+ await app?.stop();+ });++ it("新用户:什么都没做过", async () => {+ const r = await api("/guide");+ expect(r.status).toBe(200);+ expect(r.json).toMatchObject({ steps: [...GUIDE_STEPS], done: [], hidden: false, seen: [] });+ });++ it("标记完成、收起、不再显示都写进 config.json,重启后还在", async () => {+ expect((await api("/guide", { method: "PUT", body: { done: "hands" } })).json.done).toEqual(["hands"]);+ expect((await api("/guide", { method: "PUT", body: { done: "hands", seen: "intro" } })).json).toMatchObject({ done: ["hands"], seen: ["intro"] });+ expect((await api("/guide", { method: "PUT", body: { hidden: true } })).json.hidden).toBe(true);+ expect(JSON.parse(fs.readFileSync(path.join(app.config.dataDir, "config.json"), "utf8")).ui.guide).toEqual({ done: ["hands"], hidden: true, seen: ["intro"] });+ expect(loadConfig({ dataDir: app.config.dataDir, env: {} }).ui.guide).toEqual({ done: ["hands"], hidden: true, seen: ["intro"] });+ expect((await api("/guide", { method: "PUT", body: { done: "fly" } })).status).toBe(400);+ expect((await api("/guide", { method: "DELETE" })).status).toBe(405);+ });++ it("能从数据看出来的步骤自动打勾,并记下来", async () => {+ const bot = app.store.createBot({ name: "小蓝" });+ app.store.updateBot(bot.id, { defaultModel: "gpt-x", feishuAppId: "cli_test" });+ const r = await api("/guide");+ expect(r.json.done).toEqual(["model", "weixin", "hands"]);+ expect(loadConfig({ dataDir: app.config.dataDir, env: {} }).ui.guide.done).toEqual(["model", "weixin", "hands"]);+ });++ it("重置后从头来(推导出的仍算做过)", async () => {+ const r = await api("/guide", { method: "PUT", body: { reset: true } });+ expect(r.json).toMatchObject({ done: ["model", "weixin"], hidden: false, seen: [] });+ });+});diff --git a/test/i18n.unit.test.ts b/test/i18n.unit.test.tsnew file mode 100644index 0000000..0c9cf90--- /dev/null+++ b/test/i18n.unit.test.ts@@ -0,0 +1,189 @@+// 多语言:界面词典两种语言对齐、界面代码里没有漏掉的中文、t() 的插值 / 复数 / 回退,+// 服务端的语言选择(请求头 → 应用偏好 → 系统)、/settings 的语言偏好与 config.json 持久化。+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+// @ts-expect-error 检查脚本是无类型的原生 ES 模块+import { checkDicts, cjkLines, loadDicts, missingKeys, stripComments, uiFiles } from "../scripts/i18n-check.mjs";+// @ts-expect-error 界面代码是不经构建的 JS+import * as ui from "../ui/lib/i18n.js";+import { catalogs } from "../src/i18n/messages/index.js";+import { appLang, detached, envLang, lang, normalizeLang, normalizeLangPref, requestLang, setLangPref, setSystemLang, t, tl, withLang } from "../src/i18n/index.js";+import { App } from "../src/app.js";+import { loadConfig } from "../src/config.js";++describe("界面词典", () => {+ it("zh-CN 与 en 的键一一对应,占位符相同", async () => {+ expect(checkDicts(await loadDicts())).toEqual([]);+ });++ it("界面代码里 t() 用到的键两种语言都有", async () => {+ expect(missingKeys(await loadDicts(), uiFiles())).toEqual([]);+ });++ it("界面代码里没有漏掉的中文(注释除外;确需保留的行标 i18n-ignore)", () => {+ const left = uiFiles().flatMap((f: string) => cjkLines(f).map((l: { line: number; text: string }) => `${f}:${l.line} ${l.text}`));+ expect(left).toEqual([]);+ });++ it("去注释认得字符串、模板和正则", () => {+ const src = 'const a = "https://x.dev"; // 注释\nconst b = /\\/\\//g; /* 块 */ const c = `${"//"}中文`;';+ const out = stripComments(src);+ expect(out).toContain('"https://x.dev"');+ expect(out).not.toContain("注释");+ expect(out).not.toContain("块");+ expect(out).toContain("/\\/\\//g");+ expect(out).toContain("中文");+ expect(out.split("\n").length).toBe(2);+ });+});++describe("界面 t()", () => {+ it("插值、复数、vnode 参数、回退", () => {+ ui.setLangPref("en");+ expect(ui.getLang()).toBe("en");+ expect(ui.t("common.cancel")).toBe("Cancel");+ expect(ui.t("app.cmd.switchBot", { name: "Ping" })).toBe("Switch to “Ping”");+ expect(ui.t("time.minutesAgo", { count: 1 })).toBe("1 min ago");+ // vnode(对象)参数:返回数组,可直接放进 htm 模板+ const node = { type: "b" };+ expect(ui.t("app.serviceDown", { error: node })).toEqual(["Can't reach the local service: ", node]);+ // 没有的键原样返回键名+ expect(ui.t("nope.missing")).toBe("nope.missing");+ expect(ui.has("common.cancel")).toBe(true);+ expect(ui.has("nope.missing")).toBe(false);++ ui.setLangPref("zh-CN");+ expect(ui.t("common.cancel")).toBe("取消");+ expect(ui.t("time.minutesAgo", { count: 5 })).toBe("5 分钟前");+ expect(ui.format("{a} 和 {b}", { a: 1 })).toBe("1 和 {b}");+ });++ it("语言代码规整", () => {+ expect(ui.normalizeLang("zh-Hans-CN")).toBe("zh-CN");+ expect(ui.normalizeLang("zh-TW")).toBe("zh-CN");+ expect(ui.normalizeLang("en-GB")).toBe("en");+ expect(ui.normalizeLang("ja")).toBe(null);+ expect(ui.normalizePref("fr")).toBe("system");+ expect(ui.normalizePref("en")).toBe("en");+ });++ it("订阅:切换语言时通知,同一语言不重复通知", () => {+ ui.setLangPref("zh-CN");+ let n = 0;+ const off = ui.onLangChange(() => n++);+ ui.setLangPref("en");+ ui.setLangPref("en");+ off();+ ui.setLangPref("zh-CN");+ expect(n).toBe(1);+ });+});++describe("服务端词典", () => {+ it("每个命名空间 zh 与 en 的键、占位符一致", () => {+ const ph = (v: unknown) => [...new Set([...JSON.stringify(v).matchAll(/\{(\w+)\}/g)].map((m) => m[1]))].sort().join(",");+ for (const [ns, c] of Object.entries(catalogs)) {+ const zh = c.zh as Record<string, unknown>;+ const en = c.en as Record<string, unknown>;+ expect(Object.keys(en).sort(), ns).toEqual(Object.keys(zh).sort());+ for (const k of Object.keys(zh)) expect(ph(en[k]), `${ns}.${k}`).toBe(ph(zh[k]));+ }+ });++ it("系统语言:AMB_LANG → LC_ALL → LC_MESSAGES → LANG;C / POSIX / 没设时用简体中文", () => {+ expect(envLang({ AMB_LANG: "en", LANG: "zh_CN.UTF-8" })).toBe("en");+ expect(envLang({ LANG: "en_US.UTF-8" })).toBe("en");+ expect(envLang({ LC_ALL: "zh_CN.UTF-8", LANG: "en_US.UTF-8" })).toBe("zh-CN");+ expect(envLang({ LANG: "C.UTF-8" })).toBe("zh-CN");+ expect(envLang({ LANG: "POSIX" })).toBe("zh-CN");+ expect(envLang({ LANG: "de_DE.UTF-8" })).toBe("en");+ expect(envLang({})).toBe("zh-CN");+ expect(normalizeLang("zh_CN.UTF-8")).toBe("zh-CN");+ expect(normalizeLangPref("xx")).toBe("system");+ });++ it("请求语言优先于应用语言;应用语言 = 偏好,跟随系统时 = 系统语言", async () => {+ setSystemLang("zh-CN");+ setLangPref("system");+ expect(lang()).toBe("zh-CN");+ expect(t("web.botNotFound")).toBe("机器人不存在");+ setLangPref("en");+ expect(appLang()).toBe("en");+ expect(t("web.botNotFound")).toBe("Bot not found");+ // withLang 里的异步延续也用请求的语言+ const inner = await withLang("zh-CN", async () => {+ await new Promise((r) => setTimeout(r, 5));+ return t("web.botNotFound");+ });+ expect(inner).toBe("机器人不存在");+ expect(tl("en", "desktop.trayOpen", { product: "AnyModelBot" })).toBe("Open AnyModelBot");+ setLangPref("system");+ });++ it("请求结束后,请求里启动的后台任务退回应用语言;detached 一开始就用应用语言", async () => {+ setSystemLang("zh-CN");+ setLangPref("system");+ const scope = requestLang("en");+ let later: () => string = () => "";+ scope.run(() => {+ later = () => lang(); // 在请求里注册、之后才调用的回调(像渠道循环、子进程事件)+ expect(lang()).toBe("en");+ expect(detached(() => lang())).toBe("zh-CN");+ });+ const loop = scope.run(() => new Promise<string>((r) => setTimeout(() => r(lang()), 20)));+ scope.end();+ expect(await loop).toBe("zh-CN");+ expect(later()).toBe("zh-CN");+ expect(requestLang(undefined).run(() => lang())).toBe("zh-CN");+ });+});++describe("界面接口:语言偏好", () => {+ let app: App;+ let base = "";+ const TOKEN = "ui-token-i18n-0123456789";+ const api = async (p: string, init: { method?: string; body?: unknown; lang?: string } = {}) => {+ const res = await fetch(`${base}/amb/api${p}`, {+ method: init.method ?? "GET",+ headers: {+ "x-amb-token": TOKEN,+ ...(init.lang ? { "x-amb-lang": init.lang } : {}),+ ...(init.body !== undefined ? { "content-type": "application/json" } : {}),+ },+ body: init.body !== undefined ? JSON.stringify(init.body) : undefined,+ });+ return { status: res.status, json: (await res.json()) as any };+ };++ beforeAll(async () => {+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-i18n-"));+ const config = loadConfig({ dataDir, env: { AMB_MAGPIE_BASE_URL: "http://127.0.0.1:9/v1", AMB_UI_PORT: "0", AMB_UI_TOKEN: TOKEN, AMB_AGENT: "off", AMB_WEIXIN_API_BASE: "http://127.0.0.1:9" } });+ app = new App(config, { printQrToTerminal: false });+ await app.start();+ base = app.web!.url.replace(/\/$/, "");+ });+ afterAll(async () => {+ setLangPref("system");+ await app?.stop();+ });++ it("报错跟着请求头 x-amb-lang 的语言", async () => {+ expect((await api("/bots/nope", { lang: "en" })).json.error).toBe("Bot not found");+ expect((await api("/bots/nope", { lang: "zh-CN" })).json.error).toBe("机器人不存在");+ });++ it("语言偏好写进 config.json;没带请求头时报错用应用语言", async () => {+ expect((await api("/settings")).json.lang).toBe("system");+ const r = await api("/settings", { method: "PUT", body: { lang: "en" } });+ expect(r.status).toBe(200);+ expect(r.json.lang).toBe("en");+ expect(JSON.parse(fs.readFileSync(path.join(app.config.dataDir, "config.json"), "utf8")).ui.lang).toBe("en");+ expect(loadConfig({ dataDir: app.config.dataDir, env: {} }).ui.lang).toBe("en");+ expect(appLang()).toBe("en");+ expect((await api("/bots/nope")).json.error).toBe("Bot not found");+ expect((await api("/settings", { method: "PUT", body: { lang: "fr" }, lang: "en" })).json.error).toBe("Unsupported language");+ expect((await api("/settings", { method: "PUT", body: { lang: "system" } })).json.lang).toBe("system");+ });+});diff --git a/test/model-family.unit.test.ts b/test/model-family.unit.test.tsindex a89a479..bf96ed2 100644--- a/test/model-family.unit.test.ts+++ b/test/model-family.unit.test.ts@@ -1,7 +1,7 @@/** 模型选择器的模型族分组:Modelflare 的 ID 不带厂商前缀,按名字归族,族内版本新的在前。 */import { describe, it, expect } from "vitest";// @ts-expect-error 界面代码是不经构建的 JS-import { groupModels, modelFamily } from "../ui/lib/models.js";+import { groupModels, modelFamily, OTHER_FAMILY } from "../ui/lib/models.js";// Modelflare 2026-10-30 公开的对话模型(节选)const LIST = [@@ -18,12 +18,13 @@ describe("模型族", () => {expect(modelFamily("modelflare/claude-opus-5-5")).toBe("Claude");expect(modelFamily("qwen3.8-max")).toBe("Qwen");expect(modelFamily("kimi-k3")).toBe("Kimi");- expect(modelFamily("muse-spark-1.3")).toBe("其他");+ expect(modelFamily("muse-spark-1.3")).toBe(OTHER_FAMILY);+ expect(OTHER_FAMILY).toBe("other");});it("族按固定顺序,「其他」最后;族内版本新的在前,同版本按名字", () => {const g = groupModels(LIST);- expect(g.map(([f]: [string]) => f)).toEqual(["GPT", "Claude", "Gemini", "Grok", "DeepSeek", "Qwen", "Kimi", "GLM", "其他"]);+ expect(g.map(([f]: [string]) => f)).toEqual(["GPT", "Claude", "Gemini", "Grok", "DeepSeek", "Qwen", "Kimi", "GLM", OTHER_FAMILY]);const of = (f: string) => g.find(([x]: [string]) => x === f)[1].map(([, label]: [string, string]) => label);expect(of("GPT")).toEqual(["gpt-6.1-sol", "gpt-6-sol", "gpt-5.6-sol", "gpt-5.4", "codex-auto-review"]);expect(of("Claude")).toEqual(["claude-opus-5-5", "claude-sonnet-5-5", "claude-fable-5-1", "claude-fable-5", "claude-opus-5", "claude-haiku-4-5"]);diff --git a/ui/assets/guide-demo.svg b/ui/assets/guide-demo.svgnew file mode 100644index 0000000..dbe5dc5--- /dev/null+++ b/ui/assets/guide-demo.svg@@ -0,0 +1,24 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 320" width="1024" height="1024" role="img" aria-label="示例图:戴着耳机的蓝色小机器人,扁平插画风">+ <!-- 上手清单「生成一张图」的预置演示用图(ui/components/guide.js 的 MediaDemo),客户端自带,不是模型生成的 -->+ <rect width="320" height="320" fill="#eef6c8"/>+ <circle cx="262" cy="64" r="34" fill="#d7ff00"/>+ <circle cx="54" cy="260" r="22" fill="#d7ff00" opacity=".6"/>+ <ellipse cx="160" cy="292" rx="86" ry="10" fill="#161a00" opacity=".12"/>+ <rect x="112" y="222" width="96" height="66" rx="26" fill="#2a9dff"/>+ <rect x="140" y="240" width="40" height="10" rx="5" fill="#6dd4fb"/>+ <line x1="160" y1="104" x2="160" y2="74" stroke="#13233a" stroke-width="6" stroke-linecap="round"/>+ <circle cx="160" cy="66" r="11" fill="#ff7aa8"/>+ <rect x="80" y="102" width="160" height="128" rx="46" fill="#4fb6ff"/>+ <rect x="100" y="128" width="120" height="80" rx="34" fill="#13233a"/>+ <circle cx="136" cy="166" r="11" fill="#6dd4fb"/>+ <circle cx="184" cy="166" r="11" fill="#6dd4fb"/>+ <path d="M147 188q13 10 26 0" stroke="#6dd4fb" stroke-width="5" fill="none" stroke-linecap="round"/>+ <path d="M66 170C66 70 254 70 254 170" stroke="#161a00" stroke-width="12" fill="none" stroke-linecap="round"/>+ <rect x="48" y="140" width="36" height="66" rx="15" fill="#161a00"/>+ <rect x="236" y="140" width="36" height="66" rx="15" fill="#161a00"/>+ <rect x="57" y="154" width="18" height="38" rx="8" fill="#ff8c1a"/>+ <rect x="245" y="154" width="18" height="38" rx="8" fill="#ff8c1a"/>+ <path d="M266 248v-30l18-5v28" stroke="#161a00" stroke-width="5" fill="none" stroke-linejoin="round"/>+ <circle cx="260" cy="249" r="7" fill="#161a00"/>+ <circle cx="278" cy="243" r="7" fill="#161a00"/>+</svg>diff --git a/ui/components/activity.js b/ui/components/activity.jsindex e71f555..da216b5 100644--- a/ui/components/activity.js+++ b/ui/components/activity.js@@ -4,23 +4,24 @@import { useEffect, useState } from "preact/hooks";import { html, Icon } from "./ui.js";import { fmtDur } from "../lib/format.js";+import { t } from "../lib/i18n.js";const KIND_ICON = { model: "spark", tool: "code", retry: "refresh", subagent: "chat", compact: "database", error: "alert", job: "clock", steer: "chat" };const DOT = { ok: "ok", error: "err", running: "warn" };/** 步骤用时:不到 1 秒显示一位小数 */-const stepDur = (ms) => (ms < 100 ? "<0.1 秒" : ms < 1000 ? `${(ms / 1000).toFixed(1)} 秒` : fmtDur(ms));+const stepDur = (ms) => (ms < 100 ? t("activity.lessThanTenth") : ms < 1000 ? t("activity.seconds", { s: (ms / 1000).toFixed(1) }) : fmtDur(ms));const kTokens = (n) => (n >= 1000 ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}k` : String(n));/** 正在进行的那一步,用在工作状态行上:"运行 bash" / "等待 grok-4.7 回复" */export function currentStep(steps) {const s = (steps || []).findLast((x) => x.status === "running");if (!s) return "";- if (s.kind === "model") return `等待 ${s.title} 回复`;- if (s.kind === "tool") return `运行 ${s.title}`;- if (s.kind === "subagent") return "子代理在工作";- if (s.kind === "compact") return "压缩上下文";- if (s.kind === "job") return "后台命令在运行";+ if (s.kind === "model") return t("activity.waitingModel", { model: s.title });+ if (s.kind === "tool") return t("activity.runningTool", { tool: s.title });+ if (s.kind === "subagent") return t("activity.subagent");+ if (s.kind === "compact") return t("activity.compact");+ if (s.kind === "job") return t("activity.job");return s.title;}@@ -49,20 +50,20 @@ function Step({ s, now }) {const ms = s.status === "running" ? now - s.at : s.ms;const head = html`<span class=${`dot ${DOT[s.status] || ""}`} aria-hidden="true"></span><${Icon} name=${KIND_ICON[s.kind] || "info"} size=${14} class="k" />- <span class="t">${s.kind === "model" && (s.status === "running" || s.cut) ? `等待 ${s.title} 回复` : s.title}</span>+ <span class="t">${s.kind === "model" && (s.status === "running" || s.cut) ? t("activity.waitingModel", { model: s.title }) : s.title}</span>${s.summary && html`<span class="s">${s.summary}</span>`}<span class="grow"></span>${ms != null && html`<span class=${`d num${s.status === "running" ? " shimmer" : ""}`}>${stepDur(ms)}</span>`}${more && html`<${Icon} name="chevRight" size=${12} class="chev" />`}`;- const label = `${s.status === "error" ? "失败" : s.status === "running" ? "进行中" : "完成"}:${s.title}`;+ const label = t("activity.stepLabel", { status: t(s.status === "error" ? "activity.failed" : s.status === "running" ? "activity.running" : "activity.done"), title: s.title });return html`<li class=${`act-step ${s.status}${open ? " open" : ""}`}>${more- ? html`<button type="button" class="act-head" aria-expanded=${open} aria-label=${`${label},${open ? "收起" : "展开"}详情`} onClick=${() => setOpen(!open)}>${head}</button>`+ ? html`<button type="button" class="act-head" aria-expanded=${open} aria-label=${t(open ? "activity.collapseDetail" : "activity.expandDetail", { label })} onClick=${() => setOpen(!open)}>${head}</button>`: html`<div class="act-head" aria-label=${label}>${head}</div>`}${open && html`<div class="act-body">- ${s.tokens && html`<div class="t-label num">输入 ${kTokens(s.tokens.input || 0)} tokens · 输出 ${kTokens(s.tokens.output || 0)} tokens</div>`}- ${s.input && html`<div class="t-label">参数</div><pre class="selectable">${s.input}</pre>`}- ${s.output && html`<div class="t-label">${s.kind === "model" ? "回复" : "输出"}</div><pre class="selectable">${s.output}</pre>`}+ ${s.tokens && html`<div class="t-label num">${t("activity.tokens", { input: kTokens(s.tokens.input || 0), output: kTokens(s.tokens.output || 0) })}</div>`}+ ${s.input && html`<div class="t-label">${t("activity.input")}</div><pre class="selectable">${s.input}</pre>`}+ ${s.output && html`<div class="t-label">${t(s.kind === "model" ? "activity.reply" : "activity.output")}</div><pre class="selectable">${s.output}</pre>`}</div>`}</li>`;}@@ -70,15 +71,16 @@ function Step({ s, now }) {/** 步骤列表(一块 --well;步骤之间一条细线) */export function ActivityList({ steps }) {const now = useNow((steps || []).some((s) => s.status === "running"));- if (!steps?.length) return html`<div class="act-list empty"><span class="hint">还没有步骤</span></div>`;+ if (!steps?.length) return html`<div class="act-list empty"><span class="hint">${t("activity.noSteps")}</span></div>`;return html`<ol class="act-list">${steps.map((s) => html`<${Step} key=${s.id} s=${s} now=${now} />`)}</ol>`;}/*** 回复上方的工作状态行,可展开成活动明细。* live:进行中(label 由调用方给,比如"思考中 12 秒");steps:已有的步骤;count + load:历史消息只知道有几步,展开时再取。+ * phase:阶段(思考 / 回复 / 用时…)变了文字淡入一次(.wl 的 key 换掉才重播,秒数跳动不重播)。*/-export function ActivityLine({ label, live, steps, count = 0, load }) {+export function ActivityLine({ label, phase, live, steps, count = 0, load }) {const [open, setOpen] = useState(false);const [loaded, setLoaded] = useState(null);const [err, setErr] = useState("");@@ -88,13 +90,13 @@ export function ActivityLine({ label, live, steps, count = 0, load }) {if (!open || list || !load) return;load().then(setLoaded, (e) => setErr(e.message));}, [open]);- const text = html`<span class=${live ? "shimmer" : ""}>${label}</span>`;+ const text = html`<span key=${phase} class=${`wl${live ? " shimmer" : ""}`}>${label}</span>`;if (!n && !live) return html`<div class="work-line">${text}</div>`;if (!n) return html`<div class="work-line live" aria-live="off">${text}</div>`;return html`<div class=${`activity${open ? " open" : ""}`}>- <button type="button" class=${`work-line toggle${live ? " live" : ""}`} aria-expanded=${open} aria-live="off" title=${open ? "收起处理过程" : "查看处理过程"} onClick=${() => setOpen(!open)}>- ${text}<span class="steps num">${n} 步</span><${Icon} name="chevRight" size=${12} class="chev" />+ <button type="button" class=${`work-line toggle${live ? " live" : ""}`} aria-expanded=${open} aria-live="off" title=${t(open ? "activity.collapse" : "activity.expand")} onClick=${() => setOpen(!open)}>+ ${text}<span class="steps num">${t("activity.steps", { count: n })}</span><${Icon} name="chevRight" size=${12} class="chev" /></button>- ${open && (list ? html`<${ActivityList} steps=${list} />` : html`<div class="act-list empty"><span class="hint">${err || "加载中…"}</span></div>`)}+ ${open && (list ? html`<${ActivityList} steps=${list} />` : html`<div class="act-list empty"><span class="hint">${err || t("common.loading")}</span></div>`)}</div>`;}diff --git a/ui/components/avatar.js b/ui/components/avatar.jsindex 06d1b5f..55887bd 100644--- a/ui/components/avatar.js+++ b/ui/components/avatar.js@@ -4,34 +4,31 @@import { useEffect, useRef, useState } from "preact/hooks";import { html } from "./ui.js";import { ms, reducedMotion } from "../design/motion.js";+import { t } from "../lib/i18n.js";/*** 角色。eyes:两眼中心;r:眼睛半径;earL / earR / top:耳朵与头顶配件的转轴;tip:配件的中心(特效从这里发出);- * lens:护目镜镜片(只有探险者有)。pick:适合配给哪些机器人(新建页模板按这个配对)。+ * lens:护目镜镜片(只有探险者有)。+ * 名字 name、定位 role、介绍 pick(适合配给哪些机器人,新建页模板按这个配对)在词典 avatar.chars.<key> 里,+ * 用 charText(key) 取;BOT_CHARS[key].name / .role / .pick 也能读(getter,读的时候按当前语言翻译)。*/export const BOT_CHARS = {blue: {- name: "小蓝", role: "主角 · 通用助手", pick: "天线一直在线,什么信号都接得住。默认助手、会议纪要。",eyes: [[38.81, 62.99], [60.82, 62.99]], r: 3.41, earL: [18.14, 62.21], earR: [81.94, 62.21], top: [49.96, 31.78], tip: [49.8, 21.2],},yellow: {- name: "小萌", role: "客服 · 陪聊", pick: "头顶一颗小星星,一笑就脸红。客服、答疑、陪聊。",eyes: [[38.34, 63.5], [61.4, 63.48]], r: 3.57, earL: [17.91, 62.13], earR: [82.25, 62.13], top: [50.04, 31.32], tip: [50, 19.7],},green: {- name: "绿草", role: "日报 · 整理", pick: "每天长高一点点。群聊日报、记忆整理、知识库。",eyes: [[38.8, 63.07], [61.09, 63.08]], r: 3.49, earL: [17.91, 62.71], earR: [82.02, 62.71], top: [50, 31.32], tip: [50.2, 21.2],},red: {- name: "红魔", role: "代码 · 自动化", pick: "戴上耳机就进入状态。写代码、跑脚本、自动化。",eyes: [[37.53, 59.46], [62.24, 59.45]], r: 3.88, earL: [19.53, 58.06], earR: [80.47, 58.06], top: [50.04, 28.37], tip: [50, 15],},purple: {- name: "紫钻", role: "写作 · 创意", pick: "灵感会在头顶结晶。写作、润色、出点子。",eyes: [[38.86, 63.04], [60.96, 63.04]], r: 3.49, earL: [18.14, 62.91], earR: [81.94, 62.91], top: [49.84, 32.87], tip: [50, 22],},orange: {- name: "探险者", role: "翻译 · 搜索", pick: "护目镜一戴,满世界找答案。翻译、搜索、操作电脑。",eyes: [[38.18, 61.84], [61.83, 61.84]], r: 3.57, earL: [15.66, 61.47], earR: [84.34, 61.47], top: [50.12, 27.44], tip: [50, 17],lens: [[35.27, 40.85], [64.81, 40.85], 6.4],},@@ -39,6 +36,11 @@ export const BOT_CHARS = {export const CHAR_KEYS = Object.keys(BOT_CHARS);export const MAIN_CHAR = "blue";+/** 角色的名字、定位和介绍(按当前语言) */+export const charText = (key) => ({ name: t(`avatar.chars.${key}.name`), role: t(`avatar.chars.${key}.role`), pick: t(`avatar.chars.${key}.pick`) });+for (const k of CHAR_KEYS)+ for (const f of ["name", "role", "pick"]) Object.defineProperty(BOT_CHARS[k], f, { get: () => t(`avatar.chars.${k}.${f}`), enumerable: true });+function hash(s) {let h = 2166136261;for (let i = 0; i < s.length; i++) {@@ -225,14 +227,17 @@ export function BotAvatar({ bot, id, name, char, size = 34, state = "idle", work}/** 选角色:一排 6 个头像(单选)。value 为空时高亮 fallback(当前由 id 决定的那个) */-export function AvatarPicker({ value, fallback, onChange, size = 44, label = "头像" }) {+export function AvatarPicker({ value, fallback, onChange, size = 44, label = t("avatar.label") }) {const cur = value || fallback;return html`<div class="avatar-picker" role="radiogroup" aria-label=${label}>- ${CHAR_KEYS.map((k) => html`<button type="button" key=${k} class=${`avatar-opt${k === cur ? " on" : ""}`} role="radio" aria-checked=${k === cur}- title=${`${BOT_CHARS[k].name} · ${BOT_CHARS[k].pick}`} onClick=${() => k !== cur && onChange(k)}>- <${BotAvatar} char=${k} size=${size} state=${k === cur ? "listening" : "idle"} />- <span class="avatar-name">${BOT_CHARS[k].name}</span>- </button>`)}+ ${CHAR_KEYS.map((k) => {+ const c = charText(k);+ return html`<button type="button" key=${k} class=${`avatar-opt${k === cur ? " on" : ""}`} role="radio" aria-checked=${k === cur}+ title=${`${c.name} · ${c.pick}`} onClick=${() => k !== cur && onChange(k)}>+ <${BotAvatar} char=${k} size=${size} state=${k === cur ? "listening" : "idle"} />+ <span class="avatar-name">${c.name}</span>+ </button>`;+ })}</div>`;}diff --git a/ui/components/guide.js b/ui/components/guide.jsnew file mode 100644index 0000000..a16646e--- /dev/null+++ b/ui/components/guide.js@@ -0,0 +1,344 @@+// 新手引导的界面:对话空状态里的「上手清单」卡、侧栏左下角的清单入口、指着要点的地方的引导卡片、全部完成时的彩带。+// 状态与文案在 lib/guide.js;样式在 css/guide.css。+import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";+import { html, Badge, Icon, IconButton, Menu } from "./ui.js";+import { BotAvatar } from "./avatar.js";+import { useStore } from "../lib/store.js";+import { ms, reducedMotion } from "../design/motion.js";+import {+ STEPS, arm, completed, currentStep, fillComposer, guide, hideGuide, isActive, markDone, markSeen, nextStep, refreshGuide, runMediaDemo, setFocus, stepHow, stepText, visibleSteps,+} from "../lib/guide.js";+import { t } from "../lib/i18n.js";+import { MF_CONSOLE } from "../lib/links.js";++const token = (name) => getComputedStyle(document.documentElement).getPropertyValue(name).trim();+const px = (name, fallback) => {+ const n = parseFloat(token(name));+ return Number.isFinite(n) ? n : fallback;+};+const clamp = (v, a, b) => Math.min(b, Math.max(a, v));++/** 进度格:做完的格子点亮时弹一下(key 带着状态,点亮的那一格重新挂载、重播动画) */+function Progress({ steps, done }) {+ return html`<span class="guide-bar" aria-hidden="true" style=${{ "--n": String(steps.length) }}>+ ${steps.map((s, i) => {+ const on = done.includes(s.id);+ return html`<i key=${`${s.id}-${on}`} class=${on ? "on" : ""} style=${{ "--i": String(i) }}></i>`;+ })}+ </span>`;+}++/** 对话空状态里的清单:当前这一步展开(说明、怎么做、试试这句),其余一行一项;可以收起到左下角 */+export function GuideChecklist({ bot, onSend }) {+ const g = useStore(guide);+ const [open, setOpen] = useState("");+ if (!isActive(g) || g.seen.includes("intro")) return null;+ const steps = visibleSteps(g);+ const cur = currentStep(g);+ if (!cur) return null;+ const shown = open && !g.done.includes(open) ? open : cur.id;+ const n = steps.filter((s) => g.done.includes(s.id)).length;+ const txt = (s, field) => stepText(s, field, bot.name);+ return html`<section class="guide-card" aria-label=${t("guide.title")}>+ <div class="guide-card-head">+ <span class="t-label">${t("guide.title")}</span><span class="guide-count num">${n} / ${steps.length}</span>+ <span class="grow"></span>+ <button type="button" class="text" onClick=${() => markSeen("intro")}>${t("guide.collapse")}</button>+ </div>+ <${Progress} steps=${steps} done=${g.done} />+ <ol class="guide-steps">+ ${steps.map((s, i) => {+ const done = g.done.includes(s.id);+ const style = { "--anim-delay": `calc(var(--stagger) * ${i} / 3)` };+ if (done) {+ return html`<li key=${s.id} class="guide-step done anim-rise-in" style=${style}>+ <span class="n"><${Icon} name="check" size="xs" strong /></span><span class="title">${txt(s, "title")}</span>+ </li>`;+ }+ if (s.id !== shown) {+ return html`<li key=${s.id} class="anim-rise-in" style=${style}>+ <button type="button" class="guide-step" onClick=${() => setOpen(s.id)}>+ <span class="n num">${i + 1}</span><span class="title">${txt(s, "title")}</span><${Icon} name="chevRight" size="sm" />+ </button>+ </li>`;+ }+ const sample = txt(s, "try");+ return html`<li key=${s.id} class="guide-step open anim-rise-in" style=${style}>+ <span class="n num">${i + 1}</span>+ <div class="body">+ <div class="title">${txt(s, "title")}</div>+ <p class="desc">${txt(s, "desc")}</p>+ <ul class="how">${stepHow(s).map((h) => html`<li>${h}</li>`)}</ul>+ ${s.id === "media" && html`<p class="t-meta">${txt(s, "demoNote")}</p>`}+ ${s.id === "media"+ ? html`<div class="guide-try">+ <span class="t-label">${t("guide.demoThis")}</span>+ <span class="txt">${sample}</span>+ <button type="button" class="btn primary sm" onClick=${() => (arm(s.id), runMediaDemo())}>${t("guide.watchDemo")}</button>+ </div>`+ : sample+ ? html`<div class="guide-try">+ <span class="t-label">${t("guide.tryThis")}</span>+ <span class="txt">${sample}</span>+ <button type="button" class="btn primary sm" onClick=${() => (arm(s.id), onSend(sample))}>${t("guide.sendThis")}</button>+ </div>`+ : html`<div class="guide-try">+ <span class="txt tone-muted">${t("guide.followHint")}</span>+ <button type="button" class="btn primary sm" onClick=${() => setFocus(s.id)}>${t("guide.takeMe")}</button>+ </div>`}+ </div>+ </li>`;+ })}+ </ol>+ </section>`;+}++/** 侧栏左下角的清单入口:进度格 + n/6;点开是清单菜单,点一项就带你去做;全部完成后这次还留着,下次启动就不再出现 */+export function GuidePill({ onGo }) {+ const g = useStore(guide);+ const last = useStore(completed);+ const ref = useRef(null);+ const [open, setOpen] = useState(false);+ if (!isActive(g)) return null;+ const steps = visibleSteps(g);+ const n = steps.filter((s) => g.done.includes(s.id)).length;+ const finished = n === steps.length;+ if (finished && !(last && last.all)) return null;+ const cur = currentStep(g);+ return html`<button type="button" ref=${ref} class=${`guide-pill${last && !finished ? " bumped" : ""}`} key=${last ? last.at : 0}+ aria-haspopup="menu" aria-expanded=${open} title=${t("guide.title")} onClick=${() => setOpen((v) => !v)}>+ <${Progress} steps=${steps} done=${g.done} />+ <span class="v">${finished ? t("guide.allDone") : t("guide.title")}</span>+ <span class="num">${n}/${steps.length}</span>+ </button>+ ${open && html`<${Menu} anchor=${ref.current} prefer="up" width=${280} label=${t("guide.title")} onClose=${() => setOpen(false)}+ items=${[+ { group: t("guide.progress", { progress: `${n}/${steps.length}` }) },+ ...steps.map((s) => ({+ label: stepText(s, "title", t("guide.nameGeneric")),+ note: g.done.includes(s.id) ? t("guide.completed") : cur && s.id === cur.id ? t("guide.upNext") : undefined,+ cur: g.done.includes(s.id),+ onSelect: () => onGo(s.id),+ })),+ { sep: true },+ { label: t("guide.hide"), onSelect: hideGuide },+ ]} />`}`;+}++/** 全部完成:撒一把彩带(颜色是六个机器人的眼睛色和品牌黄绿) */+const CONFETTI = ["--accent-solid", "--bot-blue-eye", "--bot-yellow-glow", "--bot-green-glow", "--bot-red-eye", "--bot-purple-eye", "--bot-orange-eye"];+function confetti() {+ if (reducedMotion()) return;+ const layer = document.createElement("div");+ layer.className = "guide-confetti";+ layer.setAttribute("aria-hidden", "true");+ document.body.append(layer);+ const x0 = innerWidth / 2;+ const y0 = innerHeight * 0.42;+ const dur = ms("--bot-love", 1600);+ for (let i = 0; i < 64; i++) {+ const p = document.createElement("i");+ p.style.background = `var(${CONFETTI[i % CONFETTI.length]})`;+ p.style.left = `${x0}px`;+ p.style.top = `${y0}px`;+ if (i % 3 === 0) p.classList.add("dot");+ layer.append(p);+ const a = (Math.random() * 2 - 1) * Math.PI * 0.6 - Math.PI / 2;+ const v = 180 + Math.random() * 280;+ const dx = Math.cos(a) * v;+ const dy = Math.sin(a) * v;+ p.animate(+ [+ { transform: "translate(-50%, -50%) rotate(0deg)", opacity: 1 },+ { transform: `translate(${dx}px, ${dy}px) rotate(${Math.random() * 540}deg)`, opacity: 1, offset: 0.45 },+ { transform: `translate(${dx * 1.2}px, ${dy + 340 + Math.random() * 200}px) rotate(${Math.random() * 900}deg) scale(.6)`, opacity: 0 },+ ],+ { duration: dur + Math.random() * dur * 0.6, easing: token("--ease-out") || "ease-out", fill: "forwards" },+ );+ }+ setTimeout(() => layer.remove(), dur * 1.8);+}++/**+ * 引导卡片:指着当前步骤要点的地方(data-guide="…"),那里亮起一圈;卡片放在它旁边,跟着它移动。+ * 指着的东西被菜单盖住(模型菜单打开)时先藏起来;做完后同一张卡片换成「做好了 → 下一步」。+ */+export function CoachMark({ bot, view, infoOpen }) {+ const g = useStore(guide);+ const last = useStore(completed);+ const card = useRef(null);+ const [pos, setPos] = useState(null);+ // 第一次放好位置之后才开始"滑过去",否则会从左上角飘过来+ const [glide, setGlide] = useState(false);+ useEffect(() => {+ if (!pos) return setGlide(false);+ const r = requestAnimationFrame(() => setGlide(true));+ return () => cancelAnimationFrame(r);+ }, [!!pos]);+ const id = g.focus;+ const step = id ? STEPS.find((s) => s.id === id) : null;+ const done = !!step && g.done.includes(id);+ const active = isActive(g) && !!step && view === "chat" && !!bot;+ const sel = !step ? "" : step.target === "weixin" ? (infoOpen ? '[data-guide="weixin"]' : '[data-guide="info"]') : `[data-guide="${step.target}"]`;++ // 全部完成:撒彩带(只认挂载之后完成的,重新挂载时不重放)+ const born = useRef(Date.now());+ useEffect(() => {+ if (last && last.all && last.at > born.current) confetti();+ }, [last && last.at]);++ // 渠道这一步:扫码发生在微信里,隔几秒问一次后端有没有连上+ useEffect(() => {+ if (!active || done || id !== "weixin") return;+ const timer = setInterval(refreshGuide, ms("--dur-pulse", 1400) * 2);+ return () => clearInterval(timer);+ }, [active, done, id]);++ useLayoutEffect(() => {+ if (!active) return setPos(null);+ let el = null;+ const place = () => {+ const a = document.querySelector(sel);+ if (a !== el) {+ el?.classList.remove("guide-spot");+ el = a;+ }+ // 模型菜单打开时它盖住了按钮:先藏起来,选完再出来+ if (!a || !a.getClientRects().length || (step.target === "model" && a.getAttribute("aria-expanded") === "true")) return setPos(null);+ a.classList.toggle("guide-spot", !done);+ const r = a.getBoundingClientRect();+ const w = card.current ? card.current.offsetWidth : 300;+ const h = card.current ? card.current.offsetHeight : 240;+ const gap = px("--space-3", 12);+ const edge = px("--pane-gap", 8);+ const vw = innerWidth;+ const vh = innerHeight;+ const side = r.left > vw * 0.6 && r.left - w - gap > edge ? "left" : r.top - h - gap > edge ? "up" : "down";+ let left;+ let top;+ if (side === "left") {+ left = r.left - w - gap;+ top = clamp(r.top + r.height / 2 - h / 2, edge, vh - h - edge);+ } else {+ // 很宽的目标(输入框):卡片靠右,箭头指向发送钮那一侧+ left = clamp(r.width > w * 1.5 ? r.right - w : r.left + r.width / 2 - w / 2, edge, vw - w - edge);+ top = side === "up" ? r.top - h - gap : r.bottom + gap;+ }+ const ax = clamp((r.width > w * 1.5 ? r.right - 48 : r.left + r.width / 2) - left, 20, w - 20);+ const ay = clamp(r.top + r.height / 2 - top, 20, h - 20);+ const open = a.getAttribute("aria-expanded") === "true";+ setPos((p) => (p && p.left === left && p.top === top && p.side === side && p.ax === ax && p.ay === ay && p.open === open ? p : { left, top, side, ax, ay, open }));+ };+ place();+ const timer = setInterval(place, ms("--dur-moderate", 240));+ addEventListener("resize", place);+ return () => {+ clearInterval(timer);+ removeEventListener("resize", place);+ el?.classList.remove("guide-spot");+ };+ }, [active, sel, done]);++ if (!active) return null;+ const list = visibleSteps(g);+ const idx = list.findIndex((s) => s.id === id) + 1;+ const next = done ? nextStep(id, g) : null;+ const txt = (s, field) => stepText(s, field, bot.name);+ const sample = txt(step, "try");+ // 渠道那一步:① 打开信息面板 → ② 点「微信」→ ③ 扫码(微信那一行展开了)+ const sub = id === "weixin" ? (!infoOpen ? 1 : pos && pos.open ? 3 : 2) : 0;+ // 生图那一步:引导里只放预置演示,不替用户调用真的模型花钱+ const demoOnly = id === "media";+ const style = pos+ ? { left: `${pos.left}px`, top: `${pos.top}px`, "--ax": `${pos.ax}px`, "--ay": `${pos.ay}px` }+ : { left: "0px", top: "0px", visibility: "hidden" };+ return html`<div key=${id} ref=${card} class=${`guide-coach ${pos ? pos.side : "up"}${glide ? " glide" : ""}`} style=${style} role="dialog" aria-label=${t("guide.coachLabel")}+ onKeyDown=${(e) => e.key === "Escape" && (e.stopPropagation(), setFocus(null))}>+ <span class="guide-coach-arrow" aria-hidden="true"></span>+ <div class="guide-coach-top">+ <${BotAvatar} bot=${bot} size=${30} greet cue=${done ? { kind: "done", at: last ? last.at : 1 } : undefined} />+ <span class="t-label">${t("guide.progress", { progress: html`<span class="num">${idx}/${list.length}</span>` })}</span>+ ${done && html`<span class="guide-done"><${Icon} name="check" size="xs" strong />${t("common.done")}</span>`}+ <span class="grow"></span>+ <${IconButton} icon="close" size="xs" iconSize="xs" label=${t("guide.closeCoach")} onClick=${() => setFocus(null)} />+ </div>+ <div class="guide-coach-body anim-fade-in" key=${String(done)}>+ <h3>${done ? t("guide.doneTitle") : txt(step, "title")}</h3>+ <p class="desc">${done ? txt(step, demoOnly && !g.media ? "noModelText" : "doneText") : txt(step, "desc")}</p>+ ${!done && html`<ol class=${`how${sub ? " steps" : ""}`}>${stepHow(step).map((h, i) => html`<li class=${sub && i + 1 === sub ? "cur" : sub && i + 1 < sub ? "past" : ""}>${h}</li>`)}</ol>`}+ ${!done && txt(step, "note") && html`<p class="t-meta">${txt(step, "note")}</p>`}+ ${!done && demoOnly && html`<p class="t-meta">${txt(step, "demoNote")}</p>`}+ ${!done && sample && html`<div class="guide-try">+ <span class="txt">${sample}</span>+ ${demoOnly+ ? html`<button type="button" class="btn primary sm" onClick=${runMediaDemo}>${t("guide.watchDemo")}</button>`+ : html`<button type="button" class="btn sm" onClick=${() => fillComposer(sample)}>${t("guide.fill")}</button>`}+ </div>`}+ ${done && demoOnly && !g.media && html`<a class="t-meta" href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">${t("guide.openConsole")}</a>`}+ </div>+ <div class="guide-coach-actions">+ <button type="button" class="text" onClick=${() => setFocus(null)}>${done ? t("guide.stopHere") : t("guide.later")}</button>+ ${done && (next+ ? html`<button type="button" class="btn primary sm" onClick=${() => setFocus(next.id)}>${t("guide.next", { title: txt(next, "title") })}</button>`+ : html`<button type="button" class="btn primary sm" onClick=${() => setFocus(null)}>${t("common.done")}</button>`)}+ </div>+ </div>`;+}++/**+ * 生图的预置演示:和真的一样先问你用哪个模型(同一种提问卡片)→ 生成中 → 出图;+ * 不发给机器人、不调用模型、不扣费,图是客户端自带的示例(assets/guide-demo.svg)。看完就算做完了这一步。+ */+export function MediaDemo({ prompt }) {+ const g = useStore(guide);+ const [stage, setStage] = useState("ask"); // ask → gen → done;或 cancel+ const [pct, setPct] = useState(0);+ useEffect(() => {+ if (stage !== "gen") return;+ let k = 0;+ const timer = setInterval(() => {+ k += 1;+ setPct(Math.min(100, k * 12));+ if (k >= 9) {+ clearInterval(timer);+ setStage("done");+ markDone("media");+ }+ }, ms("--dur-slow", 360));+ return () => clearInterval(timer);+ }, [stage]);+ const asking = stage === "ask";+ const picked = stage === "gen" || stage === "done";+ const text = (prompt || "").replace(/[。.]$/, ""); // i18n-ignore:去掉句末的中英文句号+ const detail = t("guide.demo.detail", { prompt: text });+ return html`<div class="guide-demo">+ <div class=${`card${asking ? "" : " done"}`}>+ <div class="meta"><span class="t-label">${t("guide.demo.label")}</span></div>+ <div class="q-block">+ <div class="q">${t("guide.demo.question")}</div>+ <div class="q-detail">${detail}</div>+ </div>+ <div class="opts" role="radiogroup" aria-label=${t("guide.demo.pickModel")}>+ <button type="button" class=${`opt${picked ? " picked" : ""}`} role="radio" aria-checked=${picked} disabled=${!asking} onClick=${() => setStage("gen")}>+ <span class="letter">A</span><span>${t("guide.demo.sampleModel")}<span class="desc">${t("guide.demo.sampleDesc")}</span></span>+ </button>+ <button type="button" class=${`opt${stage === "cancel" ? " picked" : ""}`} role="radio" aria-checked=${stage === "cancel"} disabled=${!asking} onClick=${() => setStage("cancel")}>+ <span class="letter">B</span><span>${t("common.cancel")}<span class="desc">${t("guide.demo.cancelDesc")}</span></span>+ </button>+ </div>+ ${!asking && html`<div class="meta"><${Badge} s=${stage === "cancel" ? "cancelled" : "answered"} /></div>`}+ </div>+ ${picked && html`<figure class="guide-demo-figure anim-rise-in">+ <div class="guide-demo-img">+ ${stage === "gen"+ ? html`<span class="skel"></span><span class="guide-demo-bar" aria-hidden="true"><i style=${{ width: `${pct}%` }}></i></span>`+ : html`<img src="/amb/static/assets/guide-demo.svg" alt=${t("guide.demo.alt")} />`}+ </div>+ <figcaption class="t-meta" role="status">+ ${stage === "gen" ? t("guide.demo.generating") : t("guide.demo.caption")}+ ${stage === "done" && !g.media && html` · <a href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">${t("guide.demo.enable")}</a>`}+ </figcaption>+ </figure>`}+ ${stage === "cancel" && html`<p class="t-meta">${t("guide.demo.cancelled")} <button type="button" class="text" onClick=${() => setStage("ask")}>${t("guide.demo.again")}</button></p>`}+ </div>`;+}diff --git a/ui/components/markdown.js b/ui/components/markdown.jsindex 4e09014..2a83ee5 100644--- a/ui/components/markdown.js+++ b/ui/components/markdown.js@@ -2,6 +2,7 @@import { h } from "preact";import { parseMarkdown, linkify } from "../lib/markdown.js";import { html, CopyButton } from "./ui.js";+import { t } from "../lib/i18n.js";function inline(nodes) {return nodes.map((n, i) => {@@ -27,7 +28,7 @@ function inline(nodes) {function CodeBlock({ lang, text }) {return html`<div class="codeblock">- <div class="bar"><span class="lang">${lang || "代码"}</span><${CopyButton} text=${text} label="复制代码" /></div>+ <div class="bar"><span class="lang">${lang || t("markdown.code")}</span><${CopyButton} text=${text} label=${t("markdown.copyCode")} /></div><pre><code>${text}</code></pre></div>`;}diff --git a/ui/components/model-picker.js b/ui/components/model-picker.jsindex 7b1c804..d45c92e 100644--- a/ui/components/model-picker.js+++ b/ui/components/model-picker.js@@ -4,7 +4,8 @@ import { useEffect, useMemo, useRef, useState } from "preact/hooks";import { html, Popover, Icon } from "./ui.js";import { api } from "../lib/api.js";import { createStore, useStore } from "../lib/store.js";-import { groupModels, modelFamily, normModel, sameModel, shortModel } from "../lib/models.js";+import { t } from "../lib/i18n.js";+import { OTHER_FAMILY, groupModels, modelFamily, normModel, sameModel, shortModel } from "../lib/models.js";export { groupModels, normModel, sameModel, shortModel } from "../lib/models.js";@@ -32,12 +33,14 @@ export function modelNote(info, id) {if (!i) return "";const parts = [];if (i.context) parts.push(i.context >= 1e6 ? `${num(i.context / 1e6)}M` : `${Math.round(i.context / 1000)}K`);- const caps = [i.vision && "视觉", i.tools && "工具", i.reasoning && "推理"].filter(Boolean).join(" ");+ const caps = [i.vision && t("models.caps.vision"), i.tools && t("models.caps.tools"), i.reasoning && t("models.caps.reasoning")].filter(Boolean).join(" ");if (caps) parts.push(caps);- if (i.price) parts.push(i.price.perCall !== undefined ? `$${num(i.price.perCall)}/次` : `$${num(i.price.input)}/${i.price.output !== undefined ? num(i.price.output) : "—"}`);+ if (i.price) parts.push(i.price.perCall !== undefined ? t("models.perCall", { price: `$${num(i.price.perCall)}` }) : `$${num(i.price.input)}/${i.price.output !== undefined ? num(i.price.output) : "—"}`);return parts.join(" · ");}-const NOTE_TITLE = "上下文 · 能力 · 每百万 tokens 输入/输出的起步参考价(美元,以账单为准)";++/** 族名的显示:认不出的族(OTHER_FAMILY)按当前语言显示,其余是品牌名原样 */+export const familyName = (g) => (g === OTHER_FAMILY ? t("models.otherFamily") : g);// —— 模型族的开合:当前模型所在的族默认展开(没有当前模型时展开第一个);用户点过的按点的算,本次运行内记住 ——const famOpen = new Map();@@ -54,7 +57,7 @@ export function useFamilies(groups, current) {/** 组头的内容:族名、收起时里面的当前模型、数量、箭头(展开时转向下) */export function FamilyHead({ name, count, current }) {- return html`<span class="v">${name}</span><span class="n">${current || ""}</span><span class="cnt">${count}</span><${Icon} name="chevRight" size=${12} class="chev" />`;+ return html`<span class="v">${familyName(name)}</span><span class="n">${current || ""}</span><span class="cnt">${count}</span><${Icon} name="chevRight" size="xs" class="chev" />`;}/**@@ -122,8 +125,8 @@ export function ModelPicker({ anchor, models, error, current, onPick, onClose, rconst 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" title=${it.reset || it.custom ? undefined : NOTE_TITLE}>${note}</span>`}- <span class="check"><${Icon} name="check" size=${14} /></span>+ <span class="v">${label}</span>${note && html`<span class="n" title=${it.reset || it.custom ? undefined : t("models.noteTitle")}>${note}</span>`}+ <span class="check"><${Icon} name="check" size="sm" /></span></li>`;};const head = (g, ms) => {@@ -136,20 +139,20 @@ export function ModelPicker({ anchor, models, error, current, onPick, onClose, r</li>`;};const rows = (ms) => ms.map(([m, label]) => item({ m }, label, modelNote(info, m)));- 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="筛选模型" />+ return html`<${Popover} anchor=${anchor} onClose=${onClose} class="model-picker" width=${340} maxHeight=${420} prefer=${prefer} align=${align} label=${t("models.choose")}>+ <div class="search"><${Icon} name="search" size="sm" />+ <input placeholder=${t("models.filterOrId")} value=${q} onInput=${(e) => { setQ(e.target.value); setSel(0); }} onKeyDown=${onKey} aria-label=${t("models.filter")} /></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>`}+ ${error && html`<li class="explained" style="pointer-events:auto"><span class="v" style="white-space:normal;color:var(--red)">${t("models.loadFailed", { error })}</span>+ ${onRetry && html`<button type="button" class="text" onClick=${onRetry}>${t("common.retry")}</button>`}</li>`}${reset && !q && item({ reset: true }, reset.label, reset.note)}${groups.map(([g, ms]) =>- folding ? html`${head(g, ms)}${isOpen(g) && rows(ms)}` : html`${groups.length > 1 && html`<li class="group">${g}</li>`}${rows(ms)}`,+ folding ? html`${head(g, ms)}${isOpen(g) && rows(ms)}` : html`${groups.length > 1 && html`<li class="group">${familyName(g)}</li>`}${rows(ms)}`,)}- ${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>`}+ ${custom && item({ m: custom, custom: true }, t("models.useCustom", { id: custom }), t("models.customId"))}+ ${models && !models.length && !q && html`<li class="explained"><span class="v" style="white-space:normal">${t("models.none")}</span></li>`}</ul>${foot && html`<div class="foot"><button type="button" disabled=${foot.disabled} onClick=${() => { onClose(); foot.onClick(); }}>${foot.label}</button></div>`}<//>`;@@ -159,7 +162,7 @@ export function ModelPicker({ anchor, models, error, current, onPick, onClose, r* 菜单按钮 + 模型选择器(设置页、首次设置用)。value 为空时按钮显示 resetLabel;* 给了 resetLabel 时列表顶部有一项"恢复默认",选它 onChange("")。*/-export function PickModel({ value, models, modelsError, reloadModels, onChange, resetLabel, align = "right", label = "选择模型" }) {+export function PickModel({ value, models, modelsError, reloadModels, onChange, resetLabel, align = "right", label = t("models.choose") }) {const [open, setOpen] = useState(false);const ref = useRef(null);return html`<button type="button" class="pick" ref=${ref} aria-haspopup="listbox" aria-expanded=${open} aria-label=${label} onClick=${() => setOpen((v) => !v)}>diff --git a/ui/components/pwsh-hint.js b/ui/components/pwsh-hint.jsindex 005f097..71d275e 100644--- a/ui/components/pwsh-hint.js+++ b/ui/components/pwsh-hint.js@@ -4,14 +4,14 @@ import { useState } from "preact/hooks";import { html, Icon, CopyButton, Spinner } from "./ui.js";import { PWSH_INSTALL_URL, PWSH_WINGET, ackPwsh, dismissPwsh, installPwsh, pwshHint, pwshProgress, recheckPwsh, usePwsh } from "../lib/pwsh.js";import { failed } from "../lib/store.js";--const SLOW = "机器人执行命令现在用的是系统自带的 Windows PowerShell 5.1,每条可能要等二三十秒";+import { t } from "../lib/i18n.js";export function PwshHint() {const s = usePwsh();const [busy, setBusy] = useState("");const kind = pwshHint(s);if (!kind) return null;+ const slow = t("pwsh.slow");const run = (what, fn) => async () => {setBusy(what);try {@@ -26,7 +26,7 @@ export function PwshHint() {const inst = p.install || {};const btn = (what, label, fn, cls = "text", busyLabel = `${label}…`) =>html`<button type="button" class=${cls} disabled=${!!busy} aria-busy=${busy === what || undefined} onClick=${run(what, fn)}>${busy === what ? busyLabel : label}</button>`;- const dismiss = btn("dismiss", "不再提示", dismissPwsh);+ const dismiss = btn("dismiss", t("pwsh.dismiss"), dismissPwsh);const box = (icon, title, body, actions, tone = "") => html`<div class=${`notice pwsh-hint${tone ? ` ${tone}` : ""}`} role=${kind === "installing" ? "status" : "note"} aria-label=${title}>${icon === "spinner" ? html`<${Spinner} />` : html`<${Icon} name=${icon} size=${14} />`}<div class="pwsh-body">@@ -36,38 +36,38 @@ export function PwshHint() {</div>`;if (kind === "installing")- return box("spinner", "正在为代理安装 PowerShell 7…", `${pwshProgress(inst)}。装好后机器人执行命令快得多(大约 1 秒一条);不需要管理员权限,也不影响你自己的 PowerShell。装好之前命令照常用 Windows PowerShell 5.1。`);+ return box("spinner", t("pwsh.installingTitle"), t("pwsh.installingBody", { progress: pwshProgress(inst) }));if (kind === "installed")- return box("check", "PowerShell 7 已就绪", `机器人之后执行命令用应用内置的 PowerShell ${s.version || p.version}(已核对微软签名并试运行通过),大约 1 秒一条。`, html`<button type="button" class="text" onClick=${() => ackPwsh(`ok:${inst.finishedAt}`)}>知道了</button>`);+ return box("check", t("pwsh.installedTitle"), t("pwsh.installedBody", { version: s.version || p.version }), html`<button type="button" class="text" onClick=${() => ackPwsh(`ok:${inst.finishedAt}`)}>${t("pwsh.ack")}</button>`);if (kind === "fallback")return box("alert",- "PowerShell 出了问题,已自动换掉",- `${s.fallback.from} 起不来(${s.fallback.reason})。机器人改用 ${s.source === "private" ? "应用内置的" : ""}PowerShell ${s.version || "7"} 执行命令。`,- html`<button type="button" class="text" onClick=${() => ackPwsh(`fb:${s.fallback.at}`)}>知道了</button>`,+ t("pwsh.fallbackTitle"),+ t("pwsh.fallbackBody", { from: s.fallback.from, reason: s.fallback.reason, private: s.source === "private" ? t("pwsh.privatePrefix") : "", version: s.version || "7" }),+ html`<button type="button" class="text" onClick=${() => ackPwsh(`fb:${s.fallback.at}`)}>${t("pwsh.ack")}</button>`,"amber",);if (kind === "broken")- return box("alert", "应用内置的 PowerShell 7 用不了", `${p.bad.reason}。${SLOW}。重新安装一般就能恢复。`, html`${btn("install", "重新安装", () => installPwsh(true), "btn")}${dismiss}`, "amber");+ return box("alert", t("pwsh.brokenTitle"), t("pwsh.brokenBody", { reason: p.bad.reason, slow }), html`${btn("install", t("pwsh.reinstall"), () => installPwsh(true), "btn")}${dismiss}`, "amber");if (kind === "failed")return box("alert",- "PowerShell 7 没装上",- `${inst.error || "未知原因"}。${SLOW}。`,- html`${btn("install", "重试", () => installPwsh(false), "btn")}<a class="text" href=${PWSH_INSTALL_URL} target="_blank" rel="noopener noreferrer">自己安装 ↗</a>${dismiss}`,+ t("pwsh.failedTitle"),+ t("pwsh.failedBody", { error: inst.error || t("pwsh.unknownReason"), slow }),+ html`${btn("install", t("pwsh.retry"), () => installPwsh(false), "btn")}<a class="text" href=${PWSH_INSTALL_URL} target="_blank" rel="noopener noreferrer">${t("pwsh.installSelf")}</a>${dismiss}`,"amber",);- if (kind === "unsupported") return box("info", "这台电脑装不了 PowerShell 7", `${p.reason}。${SLOW}。`, dismiss);+ if (kind === "unsupported") return box("info", t("pwsh.unsupportedTitle"), t("pwsh.unsupportedBody", { reason: p.reason, slow }), dismiss);// missing:改回了系统默认、关了自动安装,或者还没开始装- return html`<div class="notice pwsh-hint" role="note" aria-label="建议安装 PowerShell 7">+ return html`<div class="notice pwsh-hint" role="note" aria-label=${t("pwsh.title")}><${Icon} name="info" size=${14} /><div class="pwsh-body">- <p><b>建议安装 PowerShell 7</b>${SLOW}。装上 PowerShell 7,命令执行快得多,也更稳定。${p.supported ? "应用可以自己装一份,不需要管理员权限,也不影响你自己的 PowerShell。" : ""}</p>- <div class="pwsh-cmd"><span class="t-meta">或在终端运行</span><code>${PWSH_WINGET}</code><${CopyButton} text=${PWSH_WINGET} label="复制安装命令" /></div>+ <p><b>${t("pwsh.title")}</b>${t("pwsh.body", { slow, canInstall: p.supported ? t("pwsh.canInstall") : "" })}</p>+ <div class="pwsh-cmd"><span class="t-meta">${t("pwsh.orRun")}</span><code>${PWSH_WINGET}</code><${CopyButton} text=${PWSH_WINGET} label=${t("pwsh.copyCommand")} /></div><div class="pwsh-actions">- ${p.supported ? btn("install", "一键安装", () => installPwsh(false), "btn") : html`<a class="btn" href=${PWSH_INSTALL_URL} target="_blank" rel="noopener noreferrer">安装 PowerShell 7 ↗</a>`}- ${p.supported && html`<a class="text" href=${PWSH_INSTALL_URL} target="_blank" rel="noopener noreferrer">自己安装 ↗</a>`}- ${btn("recheck", "重新检测", recheckPwsh, "text", "检测中…")}+ ${p.supported ? btn("install", t("pwsh.oneClick"), () => installPwsh(false), "btn") : html`<a class="btn" href=${PWSH_INSTALL_URL} target="_blank" rel="noopener noreferrer">${t("pwsh.install")}</a>`}+ ${p.supported && html`<a class="text" href=${PWSH_INSTALL_URL} target="_blank" rel="noopener noreferrer">${t("pwsh.installSelf")}</a>`}+ ${btn("recheck", t("pwsh.recheck"), recheckPwsh, "text", t("pwsh.checking"))}${dismiss}</div></div>diff --git a/ui/components/tasks.js b/ui/components/tasks.jsindex 2c87ee2..fae91d4 100644--- a/ui/components/tasks.js+++ b/ui/components/tasks.js@@ -6,6 +6,7 @@ import { ActivityLine } from "./activity.js";import { api } from "../lib/api.js";import { failed, toast } from "../lib/store.js";import { fmtAgo, fmtDur } from "../lib/format.js";+import { t, has } from "../lib/i18n.js";/** 阶段 → 状态点 */export function stageDot(stage) {@@ -16,20 +17,20 @@ export function stageDot(stage) {return "";}-/** 每次运行怎么来的 */-const CAUSE = { launch: "开始", followup: "追加后继续", recover: "重启后继续", retry: "重试", continue: "继续", answer: "回答后继续", manual: "手动运行" };+/** 每次运行怎么来的(launch、followup、recover、retry、continue、answer、manual) */+const cause = (c) => (has(`tasks.cause.${c}`) ? t(`tasks.cause.${c}`) : c);/** 运行一行:"第 2 次 · 重启后继续 · 3 分钟" */function runLabel(r, i, now) {const ms = (r.endedAt || now) - (r.startedAt || r.queuedAt);- const tail = r.state === "queued" ? "排队中" : r.startedAt ? fmtDur(ms) : "";- return [`第 ${i + 1} 次`, CAUSE[r.cause] || r.cause, tail].filter(Boolean).join(" · ");+ const tail = r.state === "queued" ? t("tasks.queued") : r.startedAt ? fmtDur(ms) : "";+ return [t("tasks.run", { n: i + 1 }), cause(r.cause), tail].filter(Boolean).join(" · ");}-export async function stopTask(t) {+export async function stopTask(task) {try {- await api(`/tasks/${encodeURIComponent(t.id)}/stop`, { method: "POST", body: {} });- toast(`已停止「${t.title}」`);+ await api(`/tasks/${encodeURIComponent(task.id)}/stop`, { method: "POST", body: {} });+ toast(t("tasks.stopped", { title: task.title }));return true;} catch (e) {failed(e);@@ -47,10 +48,10 @@ export function TaskDetail({ task, onChanged }) {const load = () => api(`/tasks/${encodeURIComponent(task.id)}`).then((x) => on && setD(x)).catch(() => {});load();if (!working) return () => (on = false);- const t = setInterval(load, 3000);+ const timer = setInterval(load, 3000);return () => {on = false;- clearInterval(t);+ clearInterval(timer);};}, [task.id, working, task.updatedAt]);const now = Date.now();@@ -61,13 +62,13 @@ export function TaskDetail({ task, onChanged }) {setStopping(false);};return html`<div class="task-detail">- ${task.latest && html`<div class="task-line"><span class="t-label">最新进展</span><span class="v selectable">${task.latest}</span></div>`}- <div class="task-line"><span class="t-label">文件夹</span><span class="v mono selectable">${task.folder}</span></div>+ ${task.latest && html`<div class="task-line"><span class="t-label">${t("tasks.latest")}</span><span class="v selectable">${task.latest}</span></div>`}+ <div class="task-line"><span class="t-label">${t("tasks.folder")}</span><span class="v mono selectable">${task.folder}</span></div>${runs.map((r, i) => html`<${ActivityLine} key=${r.id + (r.state === "ended" ? ":e" : "")} label=${runLabel(r, i, now)} live=${r.state === "running" || r.state === "settling"} count=${r.steps}load=${() => api(`/tasks/${encodeURIComponent(task.id)}/runs/${encodeURIComponent(r.id)}/activity`).then((x) => x.steps)} />`,)}- ${working && html`<div class="task-actions"><button type="button" class="text danger" disabled=${stopping} onClick=${stop}>${stopping ? "正在停止…" : "停止"}</button></div>`}+ ${working && html`<div class="task-actions"><button type="button" class="text danger" disabled=${stopping} onClick=${stop}>${stopping ? t("tasks.stopping") : t("tasks.stop")}</button></div>`}</div>`;}@@ -76,9 +77,9 @@ export function TaskChip({ task, onChanged }) {const [open, setOpen] = useState(false);const dot = stageDot(task.stage);return html`<div class=${`task-chip${open ? " open" : ""}`}>- <button type="button" class="task-pill" aria-expanded=${open} title=${open ? "收起" : "查看后台任务"} onClick=${() => setOpen(!open)}>+ <button type="button" class="task-pill" aria-expanded=${open} title=${open ? t("tasks.collapse") : t("tasks.view")} onClick=${() => setOpen(!open)}><span class=${`dot ${dot}`} aria-hidden="true"></span>- <span class="k">后台任务</span><span class="sep">·</span><span class="t">${task.title}</span><span class="sep">·</span><span class="st">${task.stage.label}</span>+ <span class="k">${t("tasks.chip")}</span><span class="sep">·</span><span class="t">${task.title}</span><span class="sep">·</span><span class="st">${task.stage.label}</span><${Icon} name="chevRight" size=${12} class="chev" /></button>${open && html`<${TaskDetail} task=${task} onChanged=${onChanged} />`}@@ -89,7 +90,7 @@ export function TaskChip({ task, onChanged }) {export function TaskRow({ task, onChanged, onOpen }) {const [stopping, setStopping] = useState(false);const working = task.stage.group === "working";- const when = working ? `${Math.max(1, Math.round((Date.now() - task.createdAt) / 60_000))} 分钟` : fmtAgo(task.endedAt || task.updatedAt);+ const when = working ? t("tasks.minutes", { count: Math.max(1, Math.round((Date.now() - task.createdAt) / 60_000)) }) : fmtAgo(task.endedAt || task.updatedAt);const stop = async (e) => {e.stopPropagation();setStopping(true);@@ -103,6 +104,6 @@ export function TaskRow({ task, onChanged, onOpen }) {<div class="name">${task.title}</div><div class="sub">${task.stage.label} · ${when}</div></div>- ${working && html`<button type="button" class="text danger" disabled=${stopping} onClick=${stop}>${stopping ? "停止中…" : "停止"}</button>`}+ ${working && html`<button type="button" class="text danger" disabled=${stopping} onClick=${stop}>${stopping ? t("tasks.stopping") : t("tasks.stop")}</button>`}</div>`;}diff --git a/ui/components/ui.js b/ui/components/ui.jsindex 4b8f39a..77b35db 100644--- a/ui/components/ui.js+++ b/ui/components/ui.js@@ -5,10 +5,14 @@ import { useEffect, useLayoutEffect, useRef, useState, useCallback } from "preacimport htm from "htm";import { useStore, toasts, dismissToast, dialog } from "../lib/store.js";import { usePresence } from "../design/motion.js";+import { has, t } from "../lib/i18n.js";export const html = htm.bind(h);-// —— 线性图标(16px,currentColor)——+// —— 线性图标(16 格画布,currentColor;样式 design/components/icon.css,规范见 README「图标」)——+// 每个图标是一条描边路径;要实心的部分(信息点、省略号、停止方块)写成 { s: 描边, f: 实心 }。+/** 实心圆点的路径:圆心 (x, y)、半径 r */+const dot = (x, y, r) => `M${x} ${y - r}a${r} ${r} 0 1 1 0 ${2 * r}a${r} ${r} 0 1 1 0 ${-2 * r}Z`;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",@@ -28,8 +32,8 @@ const P = {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",+ stop: { f: "M5.75 4h4.5c.97 0 1.75.78 1.75 1.75v4.5c0 .97-.78 1.75-1.75 1.75h-4.5C4.78 12 4 11.22 4 10.25v-4.5C4 4.78 4.78 4 5.75 4Z" },+ more: { f: dot(3.5, 8, 1.25) + dot(8, 8, 1.25) + dot(12.5, 8, 1.25) },panel: "M2.75 3.25h10.5c.41 0 .75.34.75.75v8c0 .41-.34.75-.75.75H2.75a.75.75 0 0 1-.75-.75V4c0-.41.34-.75.75-.75ZM10 3.25v9.5",compose: "M7.5 2.75H3.75a1 1 0 0 0-1 1v8.5a1 1 0 0 0 1 1h8.5a1 1 0 0 0 1-1V8.5M11.6 2.4a1.4 1.4 0 0 1 2 2L8 10l-2.5.5L6 8l5.6-5.6Z",clock: "M8 14a6 6 0 1 0 0-12 6 6 0 0 0 0 12ZM8 4.75V8l2.25 1.5",@@ -41,30 +45,44 @@ const P = {unlock: "M4.25 7.25h7.5c.41 0 .75.34.75.75v5c0 .41-.34.75-.75.75h-7.5a.75.75 0 0 1-.75-.75V8c0-.41.34-.75.75-.75ZM5.5 7.25V5a2.5 2.5 0 0 1 4.9-.7",globe: "M8 14a6 6 0 1 0 0-12 6 6 0 0 0 0 12ZM2.25 8h11.5M8 2c1.55 1.65 2.35 3.65 2.35 6S9.55 12.35 8 14M8 2C6.45 3.65 5.65 5.65 5.65 8s.8 4.35 2.35 6",database: "M8 5.25c2.9 0 5.25-.78 5.25-1.75S10.9 1.75 8 1.75 2.75 2.53 2.75 3.5 5.1 5.25 8 5.25ZM2.75 3.5v9c0 .97 2.35 1.75 5.25 1.75s5.25-.78 5.25-1.75v-9M2.75 8c0 .97 2.35 1.75 5.25 1.75S13.25 8.97 13.25 8",- info: "M8 14a6 6 0 1 0 0-12 6 6 0 0 0 0 12ZM8 7.25v3.75M8 4.9v.1",- alert: "M8 14a6 6 0 1 0 0-12 6 6 0 0 0 0 12ZM8 4.75v3.75M8 11v.1",+ info: { s: "M8 14a6 6 0 1 0 0-12 6 6 0 0 0 0 12ZM8 7.25v3.75", f: dot(8, 5, 0.8) },+ alert: { s: "M8 14a6 6 0 1 0 0-12 6 6 0 0 0 0 12ZM8 4.75v3.5", f: dot(8, 10.9, 0.8) },chat: "M3.25 2.75h9.5c.41 0 .75.34.75.75v6.75c0 .41-.34.75-.75.75H7.25L4.5 13.25V11H3.25a.75.75 0 0 1-.75-.75V3.5c0-.41.34-.75.75-.75Z",code: "M5.25 4.5 1.75 8l3.5 3.5M10.75 4.5 14.25 8l-3.5 3.5M9.1 2.75 6.9 13.25",shield: "M8 1.75 2.75 3.6v4.15c0 3.05 2.2 5.4 5.25 6.5 3.05-1.1 5.25-3.45 5.25-6.5V3.6L8 1.75Z",pulse: "M1.75 8.25h2.5l1.5-3.75 2.75 7.5 1.75-5 1 1.25h3",+ palette: {+ s: "M8 1.75a6.25 6.25 0 1 0 0 12.5c.83 0 1.25-.55 1.25-1.2 0-.75-.6-1.05-.6-1.75 0-.62.5-1.05 1.15-1.05h1.45a3 3 0 0 0 3-3C14.25 4.2 11.45 1.75 8 1.75Z",+ f: dot(4.75, 8.25, 0.8) + dot(5.75, 5.25, 0.8) + dot(8.75, 4.25, 0.8) + dot(11.25, 6.25, 0.8),+ },};-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>`;-}+export const ICONS = Object.keys(P);+const IC_PX = { xs: 12, sm: 14, md: 16, lg: 20, xl: 24 }; // 和 --ic-xs … --ic-xl 一致;宽高属性只是样式表加载前的兜底const cx = (...a) => a.filter(Boolean).join(" ");+/**+ * 图标。size = "xs" 12 | "sm" 14 | "md" 16 | "lg" 20 | "xl" 24;不传时由上下文的 CSS 决定(缺省 md)。+ * strong:实心面上的图标(发送钮、完成圆点)用粗一档的线。线宽按显示像素算,换尺寸不会变粗。+ */+export function Icon({ name, size, strong, class: cls }) {+ const p = P[name];+ const s = typeof p === "string" ? p : p.s;+ const f = typeof p === "string" ? null : p.f;+ const px = IC_PX[size] ?? IC_PX.md;+ return html`<svg class=${cx("ic", size && `ic-${size}`, strong && "ic-strong", cls)} width=${px} height=${px} viewBox="0 0 16 16" fill="none"+ stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${s && html`<path d=${s} />`}${f && html`<path d=${f} fill="currentColor" stroke="none" />`}</svg>`;+}+/** 按钮:variant = "primary" | "ghost" | "danger";size = "sm" | "lg";loading 时转圈并禁用 */export function Button({ variant, size, block, loading, icon, class: cls, type = "button", disabled, children, ...rest }) {return html`<button type=${type} class=${cx("btn", variant, size, block && "block", cls)} disabled=${disabled || loading} aria-busy=${loading || undefined} ...${rest}>- ${loading ? html`<${Spinner} />` : icon && html`<${Icon} name=${icon} size=${14} />`}${children}+ ${loading ? html`<${Spinner} />` : icon && html`<${Icon} name=${icon} size="sm" />`}${children}</button>`;}/** 图标按钮:必须给 label(读屏与悬停提示) */-export function IconButton({ icon, label, size, iconSize = 14, on, class: cls, type = "button", ...rest }) {+export function IconButton({ icon, label, size, iconSize = "sm", on, class: cls, type = "button", ...rest }) {return html`<button type=${type} class=${cx("icon-btn", size, on && "on", cls)} title=${label} aria-label=${label} ...${rest}><${Icon} name=${icon} size=${iconSize} /></button>`;@@ -73,7 +91,7 @@ export function IconButton({ icon, label, size, iconSize = 14, on, class: cls, t/** 行内提示:tone = "amber" | "red"(缺省为中性);左边一个图标表达语气,action 放在右侧 */export function Notice({ tone, action, children }) {return html`<div class=${cx("notice", tone)} role=${tone === "red" ? "alert" : undefined}>- <${Icon} name=${tone ? "alert" : "info"} size=${14} /><span class="notice-text">${children}</span>${action}+ <${Icon} name=${tone ? "alert" : "info"} size="sm" /><span class="notice-text">${children}</span>${action}</div>`;}@@ -146,10 +164,138 @@ export function Seg({ options, value, onChange, disabled, label }) {</div>`;}-/** 长度 token 的像素值("--pop-offset" → 6):JS 里的间距也从 token 来,不写死 */-function tokenPx(name, fallback) {- const n = parseFloat(getComputedStyle(document.documentElement).getPropertyValue(name));- return Number.isFinite(n) ? n : fallback;+/** 长度 token 的像素值("--pop-offset" → 6,"--side-w-cap: 36vw" → 窗口宽 × .36):JS 里的尺寸也从 token 来,不写死。+ * el:从哪个元素上读(缺省 <html>;注册过的属性如 .app 上的 --side-col 要从定义它的元素读) */+export function tokenPx(name, fallback, el = document.documentElement) {+ const v = getComputedStyle(el).getPropertyValue(name).trim();+ const n = parseFloat(v);+ if (!Number.isFinite(n)) return fallback;+ return v.endsWith("vw") ? (n * window.innerWidth) / 100 : n;+}++// —— 分隔条:拖动两块面板之间的空隙调整一侧面板的宽度(README「分隔条」,样式 design/components/splitter.css)——+const SPLIT_STEP = 8; // ← → 一次挪 8px,按住 Shift 挪 32px+const SPLIT_STEP_BIG = 32;+const SPLIT_SNAP = 6; // 拖到离默认宽度 6px 以内时吸附回默认宽度+/**+ * size:宽度 token,例如 "--side-w":默认宽度 --side-w,范围 --side-w-min … min(--side-w-max, --side-w-cap, room());+ * 拖动时直接改 <html> 上的 --side-w-user(不经过渲染,跟手),页面用 var(--side-w-user, var(--side-w)) 取值。+ * edge:面板在分隔条的哪一边。"start" = 左边的面板(往右拖变宽),"end" = 右边的面板(往左拖变宽)。+ * value:当前保存的宽度(px,0 = 默认),变了会同步读屏的数值。+ * room():可选,此刻最多还能给多宽(比如窗口宽 − 另一侧面板 − 主区最小宽度)。+ * onCommit(px):松手、键盘调整、双击恢复时调用一次;px = 0 表示回到默认宽度(之后跟着默认值和断点走)。+ * 交互:拖动;双击恢复默认;聚焦后 ← → 调整(Shift 大步),Home / End 最窄 / 最宽,Enter 恢复默认。+ */+export function Splitter({ size, edge = "start", label, value = 0, room, onCommit, class: cls }) {+ const ref = useRef(null);+ const root = document.documentElement;+ const user = `${size}-user`;+ // cap:CSS 里的上限(-max 和 -cap,页面的 clamp() 也是它);max 再加上此刻的 room()。+ // 已经比 room 宽的面板不会被一下子挤窄,只是不能再变宽+ const limits = () => {+ const def = Math.round(tokenPx(size, 0));+ const min = Math.round(tokenPx(`${size}-min`, def));+ const cap = Math.max(min, Math.round(Math.min(tokenPx(`${size}-max`, Infinity), tokenPx(`${size}-cap`, Infinity))));+ const w = Math.round(Math.min(cap, Math.max(min, tokenPx(user, def))));+ const max = Math.max(min, Math.min(cap, Math.max(w, room ? Math.round(room()) : Infinity)));+ return { def, min, max, w };+ };+ const clamp = (w, l) => Math.round(Math.min(l.max, Math.max(l.min, w)));+ const current = (l) => l.w;+ const sync = (w, l) => {+ const el = ref.current;+ if (!el) return;+ el.setAttribute("aria-valuenow", String(w));+ el.setAttribute("aria-valuemin", String(l.min));+ el.setAttribute("aria-valuemax", String(l.max));+ };+ const write = (w) => (w ? root.style.setProperty(user, `${w}px`) : root.style.removeProperty(user));+ const commit = (w, l) => {+ const v = w === l.def ? 0 : w;+ write(v);+ sync(w, l);+ onCommit?.(v);+ };+ useLayoutEffect(() => {+ const l = limits();+ sync(current(l), l);+ }, [value]);++ const onPointerDown = (e) => {+ if (e.button !== 0 || !e.isPrimary) return;+ e.preventDefault(); // 不选中文字、不抢焦点+ const el = ref.current;+ const l = limits();+ const start = current(l);+ const x0 = e.clientX;+ const dir = edge === "start" ? 1 : -1;+ // 到头了:指针换成单向箭头,提示只能往另一边拖+ const grow = edge === "start" ? "e" : "w";+ const shrink = edge === "start" ? "w" : "e";+ let w = start;+ let moved = false;+ let raf = 0;+ let done = false;+ el.setPointerCapture?.(e.pointerId);+ const paint = () => {+ raf = 0;+ write(w);+ el.setAttribute("aria-valuenow", String(w));+ root.dataset.resizing = w >= l.max && l.max > l.min ? shrink : w <= l.min && l.max > l.min ? grow : "col";+ };+ const move = (ev) => {+ const dx = ev.clientX - x0;+ if (!moved) {+ if (Math.abs(dx) < 2) return; // 手抖不算拖:双击时不会把宽度改掉+ moved = true;+ el.classList.add("dragging");+ root.dataset.resizing = "col";+ }+ let next = clamp(start + dir * dx, l);+ if (Math.abs(next - l.def) <= SPLIT_SNAP && l.def >= l.min && l.def <= l.max) next = l.def;+ w = next;+ if (!raf) raf = requestAnimationFrame(paint);+ };+ const end = () => {+ if (done) return;+ done = true;+ el.removeEventListener("pointermove", move);+ el.removeEventListener("pointerup", end);+ el.removeEventListener("pointercancel", end);+ el.removeEventListener("lostpointercapture", end);+ if (raf) {+ // 最后一次移动还没画:趁 data-resizing 还在(列宽不过渡)先画上并让样式生效,松手时不会再"滑"一下+ cancelAnimationFrame(raf);+ paint();+ void getComputedStyle(el).left;+ }+ el.classList.remove("dragging");+ delete root.dataset.resizing;+ if (moved) commit(w, l);+ };+ el.addEventListener("pointermove", move);+ el.addEventListener("pointerup", end);+ el.addEventListener("pointercancel", end);+ el.addEventListener("lostpointercapture", end);+ };+ const reset = () => {+ const l = limits();+ commit(clamp(l.def, l), l);+ };+ const onKeyDown = (e) => {+ const l = limits();+ const cur = current(l);+ const step = e.shiftKey ? SPLIT_STEP_BIG : SPLIT_STEP;+ const wider = edge === "start" ? "ArrowRight" : "ArrowLeft";+ const narrower = edge === "start" ? "ArrowLeft" : "ArrowRight";+ const next =+ e.key === wider ? cur + step : e.key === narrower ? cur - step : e.key === "Home" ? l.min : e.key === "End" ? l.max : e.key === "Enter" ? l.def : null;+ if (next === null) return;+ e.preventDefault();+ commit(clamp(next, l), l);+ };+ return html`<div class=${cx("splitter", cls)} ref=${ref} role="separator" aria-orientation="vertical" aria-label=${label} tabindex="0"+ onPointerDown=${onPointerDown} onDblClick=${reset} onKeyDown=${onKeyDown}></div>`;}/** 打开在锚点下方(空间不够时在上方)的浮层,position: fixed。离锚点 --pop-offset,离窗口边缘 --pane-gap(和面板的边对齐) */@@ -234,9 +380,9 @@ export function Menu({ anchor, items, onClose, width = 240, prefer, align, label: html`<li role="menuitem" aria-disabled=${!!it.disabled}class=${[sel === i ? "sel" : "", it.danger ? "danger" : "", it.disabled ? "disabled" : "", it.cur ? "cur" : "", it.note ? "rich" : ""].join(" ")}onPointerMove=${() => !it.disabled && setSel(i)} onClick=${() => !it.disabled && run(it)}>- ${it.icon && html`<span class="lead"><${Icon} name=${it.icon} size=${15} /></span>`}+ ${it.icon && html`<span class="lead"><${Icon} name=${it.icon} size="sm" /></span>`}${it.note ? html`<span class="txt"><span class="v">${it.label}</span><span class="n">${it.note}</span></span>` : html`<span class="v">${it.label}</span>`}- <span class="check"><${Icon} name="check" size=${14} /></span>+ <span class="check"><${Icon} name="check" size="sm" /></span></li>`,)}</ul>@@ -256,8 +402,10 @@ export function MenuButton({ value, options, onChange, disabled, label, width =items=${options.map(([v, text, note]) => ({ label: text, note, cur: v === value, onSelect: () => v !== value && onChange(v) }))} />`}`;}-export function CopyButton({ text, label = "复制" }) {+/** label 缺省为「复制」 */+export function CopyButton({ text, label }) {const [done, setDone] = useState(false);+ const name = label || t("common.copy");const copy = async () => {try {await navigator.clipboard.writeText(text);@@ -272,22 +420,23 @@ export function CopyButton({ text, label = "复制" }) {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} />+ return html`<button type="button" class=${`icon-btn copy${done ? " done" : ""}`} title=${done ? t("common.copied") : name} aria-label=${name} onClick=${copy}>+ <${Icon} name=${done ? "check" : "copy"} size="sm" /></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"],- denied: ["已拒绝", "err"],+/** 状态 → 徽标的语气;文字在 ui/locales/<语言>/ui.js 的 state.<状态>。不认识的状态原样显示 */+const STATE_KIND = {+ 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",+ denied: "err",};export const Badge = ({ s }) => {- const [text, kind] = STATE[s] || [s, ""];- return html`<span class=${`badge ${kind}`}>${text}</span>`;+ const known = Object.hasOwn(STATE_KIND, s) && has(`ui.state.${s}`);+ return html`<span class=${`badge ${known ? STATE_KIND[s] : ""}`}>${known ? t(`ui.state.${s}`) : s}</span>`;};/** 自绘确认框:焦点先在"取消"(安全选项),Esc 关闭,Tab 在框内循环 */@@ -343,8 +492,8 @@ export function DialogHost() {return html`<${Sheet} title=${d.title} leaving=${leaving} onClose=${() => done(false)}>${d.body && html`<p class="body">${d.body}</p>`}<div class="actions">- <${Button} data-autofocus onClick=${() => done(false)}>${d.cancelLabel || "取消"}<//>- <${Button} variant=${d.danger ? "danger" : "primary"} onClick=${() => done(true)}>${d.confirmLabel || "确定"}<//>+ <${Button} data-autofocus onClick=${() => done(false)}>${d.cancelLabel || t("common.cancel")}<//>+ <${Button} variant=${d.danger ? "danger" : "primary"} onClick=${() => done(true)}>${d.confirmLabel || t("common.confirm")}<//></div><//>`;}@@ -352,9 +501,9 @@ export function DialogHost() {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`<${IconButton} icon="close" size="xs" iconSize=${12} label="关闭" onClick=${() => dismissToast(t.id)} />`}+ ${list.map((it) => html`<div key=${it.id} class=${`toast ${it.kind}${it.leaving ? " leaving" : ""}`}>+ <span>${it.text}</span>+ ${it.kind === "err" && html`<${IconButton} icon="close" size="xs" iconSize="xs" label=${t("common.close")} onClick=${() => dismissToast(it.id)} />`}</div>`)}</div>`;}diff --git a/ui/css/chat.css b/ui/css/chat.cssindex 66e1406..054268b 100644--- a/ui/css/chat.css+++ b/ui/css/chat.css@@ -6,7 +6,7 @@/* 对话列和输入框同宽、同一个居中列(两侧至少 --page-gutter)。输入框浮在主区底部,对话列的下边距和"回到底部"的位置都从它的高度算出来,改输入框的内边距时这里跟着变。 */.chat, .composer {- --composer-line: 22px; /* 输入框的行高 */+ --composer-line: calc(22px * var(--fs-scale)); /* 输入框的行高:跟着设置 › 外观 › 字体大小变 */--composer-pad: var(--space-2); /* 工具栏离输入框的左、右、下边:加号和发送钮都贴着这条线 *//* 一行字时输入框的高度:文字区(上 14 + 行高 + 下 4)+ 工具栏(上 6 + 发送钮 + 下 --composer-pad) */--composer-h: calc(var(--space-3-5) + var(--composer-line) + var(--space-1) + var(--space-1-5) + var(--ctl-lg) + var(--composer-pad));@@ -31,10 +31,10 @@.chat.scrolled > .chat-head { box-shadow: 0 .5px 0 var(--glass-edge), var(--shadow-xs); }.chat-head > * { -webkit-app-region: no-drag; }.chat-head .grow { -webkit-app-region: drag; align-self: stretch; }-.chat-head .icon-btn { --ib-size: 30px; }+.chat-head .icon-btn { --ib-size: var(--ctl-md); } /* 16 的图标四周各 6:最右的图标外沿落在 --head-px + 6 = 16,和左边的头像对称 */.head-bot {- display: inline-flex; align-items: center; gap: var(--space-2); min-width: 0; height: 32px; padding: 0 var(--space-2-5) 0 var(--space-1-5);- border-radius: var(--r-md); font-size: var(--fs-xl); font-weight: var(--fw-semibold); color: var(--fg);+ display: inline-flex; align-items: center; gap: var(--space-2); min-width: 0; height: var(--ctl-lg); padding: 0 var(--space-2-5) 0 var(--space-1-5);+ border-radius: var(--r-md); font-size: var(--fs-lg); font-weight: var(--fw-semibold); color: var(--fg);transition: background var(--t-fast);}button.head-bot:hover { background: var(--pill); }@@ -58,6 +58,8 @@ button.head-bot:active { background: var(--pill-press); }.chat-skel .skel { height: 34px; border-radius: var(--r-bubble); }.chat-skel .skel:nth-child(2) { justify-self: end; }.chat-col > .notice { margin-top: var(--space-2); }+/* 历史读到之后整列淡入一次(不是一行行弹出来);之后的新消息各自有入场 */+.chat-col.ready { animation: fade-in var(--dur-base) var(--ease-out); }.msg-row { position: relative; display: flex; flex-direction: column; margin-top: var(--space-4); }.msg-row.cont { margin-top: var(--space-1); }@@ -66,16 +68,43 @@ button.head-bot:active { background: var(--pill-press); }.msg { font-size: var(--fs-xl); word-break: break-word; overflow-wrap: anywhere; cursor: text; }.msg-row.user .msg {max-width: min(var(--bubble-w), 80%); padding: var(--space-2-5) var(--space-4); border-radius: var(--r-bubble);- background: var(--bubble-user); color: var(--fg); line-height: 1.55; white-space: pre-wrap;+ background: var(--bubble-user); color: var(--fg); line-height: var(--lh-relaxed); white-space: pre-wrap;}-.msg-row.assistant .msg { color: var(--fg); line-height: 1.7; }+.msg-row.assistant .msg { color: var(--fg); line-height: var(--lh-prose); }.msg-row.pending .msg { opacity: .85; }-.msg-row.enter { --rise: 6px; animation: rise-in var(--dur-base) var(--ease-out); }-/* 回复上方的工作状态:进行中带微光,结束后变成一条细线上的"用时" */+/* —— 对话流的动效:一句话"发出 → 思考 → 输出 → 收尾",每一步只动一样东西,幅度小、不循环抢眼 ——+ 发出:气泡从输入框的方向浮上来。透明度先到位(base),位移和一点点缩放用弹性曲线慢一拍收尾(slow),+ 缩放的原点在右下角,像是从发送钮那边送出去的 */+.msg-row.user.enter {+ --pop-dy: 12px; --pop-scale: .96; transform-origin: 100% 100%;+ animation: fade-in var(--dur-base) var(--ease-out), pop-in var(--dur-slow) var(--ease-spring);+}+/* 流里新插进来的提问 / 审批卡、文件、出错提示:轻轻浮起 */+.msg-row.assistant.enter { --rise: 6px; animation: rise-in var(--dur-moderate) var(--ease-out); }+/* 思考:工作状态行比你的气泡晚一拍(--stagger)淡入,先看到"发出去了",再看到"在想" */+.msg-row.live > .work { animation: fade-in var(--dur-moderate) var(--ease-out) var(--stagger) backwards; }+/* 输出:新出现的段落、列表项淡入,已经在的不重播;只在输出中,回复结束后不再有动画 */+.msg-row.live .md > *, .msg-row.live .md > :is(ul, ol) > li + li { animation: fade-in var(--dur-moderate) var(--ease-out); }+/* 输出中:最后一段文字末尾一个慢慢呼吸的小点,视线不用离开正在读的地方就知道"还在写"(代码块、表格结尾不画) */+.msg-row.live .md > :is(p, h1, h2, h3, h4):last-child::after,+.msg-row.live .md > :is(ul, ol):last-child > li:last-child:not(:has(> :is(ul, ol)))::after,+.msg-row.live .md > blockquote:last-child > :last-child::after {+ content: ""; display: inline-block; width: .45em; height: .45em; margin-left: .35em; vertical-align: .08em;+ border-radius: 50%; background: var(--muted);+ animation: breathe var(--dur-pulse) var(--ease-in-out) infinite;+}++/* 回复上方的工作状态:进行中带微光,结束后变成一条细线上的"用时"(细线淡入)。+ 外面包一层可以收起的轨道 .work(grid 1fr → 0fr):很快答完、不显示"用时"的回复,这一行平滑收起,+ 正文不会一下跳上去。这是对话流里唯一的布局动画,只播一次 */+.work { display: grid; grid-template-rows: 1fr; transition: grid-template-rows var(--t-moderate), opacity var(--t-base); }+.work.gone { grid-template-rows: 0fr; opacity: 0; }+.work-in { min-height: 0; overflow: hidden; }.work-line {display: flex; align-items: center; gap: var(--space-1-5); padding-bottom: var(--space-2); margin-bottom: var(--space-3);font-size: var(--fs-md); color: var(--muted); border-bottom: 1px solid var(--line-2);+ transition: border-color var(--t-moderate);}.work-line.live { border-bottom-color: transparent; }.msg-row.assistant .work-line:last-child { margin-bottom: 0; }@@ -113,22 +142,30 @@ button.act-head:active { background: var(--pill-hover); }margin: 0; max-height: 240px; overflow: auto; font: var(--fs-xs)/var(--lh-relaxed) var(--code);color: var(--fg); white-space: pre-wrap; overflow-wrap: anywhere;}++.msg-row.assistant > .work-line:last-child, .msg-row.assistant > .work:last-child .work-line { margin-bottom: 0; }+/* "思考中 → 正在回复 → 用时"换阶段时文字淡入(换的是 key,秒数跳动不重播) */+.work-line > .wl { animation: fade-in var(--dur-base) var(--ease-out); }+/* 文字微光:底色是 --muted,一道 --fg-2 的光慢慢扫过去再停一拍;对比只差一档,余光里知道"在动"就够了 */.shimmer {color: transparent;- background: linear-gradient(90deg, var(--muted) 0%, var(--muted) 40%, var(--faint) 50%, var(--muted) 60%, var(--muted) 100%) 0 0 / 300% 100%;+ background: linear-gradient(90deg, var(--muted) 35%, var(--fg-2) 50%, var(--muted) 65%) 0 0 / 300% 100%;-webkit-background-clip: text; background-clip: text;- animation: shimmer var(--dur-shimmer) linear infinite;+ animation: sheen var(--dur-sheen) var(--ease-in-out) infinite;}+.work-line > .wl.shimmer { animation: fade-in var(--dur-base) var(--ease-out), sheen var(--dur-sheen) var(--ease-in-out) infinite; }/* 消息下方的操作:悬停出现;最后一条回复常显 */.msg-actions {- display: flex; align-items: center; gap: var(--bar-gap); height: 24px; margin-top: var(--space-0-5);+ display: flex; align-items: center; gap: var(--bar-gap); height: var(--ctl-sm); margin-top: var(--space-0-5);color: var(--muted); opacity: 0; transition: opacity var(--t-fast);}.msg-row.user .msg-actions { flex-direction: row-reverse; }.msg-row:hover .msg-actions, .msg-row.last .msg-actions, .msg-actions:focus-within { opacity: 1; }+/* 收尾:回复写完,复制和时刻晚一拍淡入(输出中不出现,免得在正文下面闪) */+.msg-row.assistant.last .msg-actions { animation: fade-in var(--dur-moderate) var(--ease-out) var(--stagger) backwards; }.msg-actions .when { font-size: var(--fs-xs); }-.msg-actions .icon-btn { --ib-size: 24px; }+.msg-actions .icon-btn { --ib-size: var(--ctl-sm); }.caret { display: inline-block; width: 7px; height: 15px; margin-left: var(--space-0-5); vertical-align: -2px; border-radius: 1px; background: var(--accent); animation: blink var(--dur-blink) steps(2) infinite; }.typing { display: inline-flex; gap: var(--space-1); padding: var(--space-2) var(--space-0-5); }@@ -143,16 +180,17 @@ button.act-head:active { background: var(--pill-hover); }.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 hr { margin: 0 0 var(--space-3); }-.md h1, .md h2, .md h3, .md h4 { margin: var(--space-5) 0 var(--space-2); font-size: var(--fs-xl); font-weight: var(--fw-semibold); line-height: 1.5; }-.md h1 { font-size: var(--fs-2xl); }+.md h1, .md h2, .md h3, .md h4 { margin: var(--space-5) 0 var(--space-2); font-size: var(--fs-xl); font-weight: var(--fw-semibold); line-height: var(--lh-normal); }+.md h1 { font-size: var(--fs-2xl); letter-spacing: var(--tracking-tight); line-height: var(--lh-tight); }+.md h4 { font-size: var(--fs-lg); }.md ul, .md ol { padding-left: var(--space-6); }.md li + li { margin-top: var(--space-1); }.md blockquote { padding-left: var(--space-3); border-left: 3px solid var(--line); color: var(--fg-2); } /* 描边:引文的排版记号(灰色、不圈住内容),不是提示框的色条 */.md hr { border: 0; border-top: 1px solid var(--line); }-.md code { font-size: var(--fs-sm); padding: var(--space-0-5) var(--space-1); border-radius: var(--r-xs); background: var(--code-bg); }+.md code { font-size: .86em; padding: .12em .36em; border-radius: var(--r-xs); background: var(--code-bg); } /* 跟着所在文字缩放:正文、标题、表格里一样合身 */.md a { text-decoration: underline; text-underline-offset: 2px; }.md .table-wrap { overflow-x: auto; margin: 0 0 var(--space-3); }-.md table { border-collapse: collapse; font-size: var(--fs-md); line-height: 1.45; margin: 0; }+.md table { border-collapse: collapse; font-size: var(--fs-md); line-height: var(--lh-normal); margin: 0; }/* 表格不画格子:表头下一条 --line,行与行之间一条 --line-2,没有外框、竖线和表头底色;列靠右边距分开,第一列贴着正文左边 */.md th, .md td { padding: var(--space-1-5) var(--space-5) var(--space-1-5) 0; text-align: left; vertical-align: top; }.md :is(th, td):last-child { padding-right: 0; }@@ -167,7 +205,7 @@ button.act-head:active { background: var(--pill-hover); }}.codeblock .bar .lang { flex: 1; }.codeblock .bar .icon-btn { --ib-size: var(--ctl-xs); }-.codeblock pre { margin: 0; padding: 0 var(--space-3) var(--space-3); overflow-x: auto; font: var(--fs-sm)/var(--lh-relaxed) var(--code); color: var(--fg); white-space: pre; }+.codeblock pre { margin: 0; padding: 0 var(--space-3) var(--space-3); overflow-x: auto; font: var(--fs-sm)/var(--lh-relaxed) var(--code); color: var(--fg); white-space: var(--code-wrap); overflow-wrap: anywhere; }.codeblock pre code { font-size: inherit; padding: 0; background: none; }/* 流里的一组:提问 / 审批 / 文件。一块 --well,不描边、不加投影;里面不再套框——@@ -176,25 +214,25 @@ button.act-head:active { background: var(--pill-hover); }width: min(var(--bubble-w), 100%); background: var(--well); border-radius: var(--r-well);padding: var(--card-pad); display: grid; gap: var(--space-2-5);}-.card .q { font-size: var(--fs-xl); font-weight: var(--fw-semibold); color: var(--fg); line-height: 1.45; }+.card .q { font-size: var(--fs-xl); font-weight: var(--fw-semibold); color: var(--fg); line-height: var(--lh-snug); }.card .q-detail { font-size: var(--fs-md); color: var(--fg-2); line-height: var(--lh-normal); white-space: pre-wrap; }.card .q-block { display: grid; gap: var(--space-2); }.card .opts { display: grid; gap: var(--space-0-5); margin: 0 calc(-1 * var(--space-2)); }.card .opt {--focus-offset: 0px;- display: flex; align-items: center; gap: var(--space-2-5); min-height: 41px; padding: var(--space-1) var(--space-2); border-radius: var(--r-lg);- text-align: left; font-size: var(--fs-xl); color: var(--fg); transition: background var(--t-fast);+ display: flex; align-items: center; gap: var(--space-2-5); min-height: 40px; padding: var(--space-1) var(--space-2); border-radius: var(--r-lg);+ text-align: left; font-size: var(--fs-lg); line-height: var(--lh-snug); color: var(--fg); transition: background var(--t-fast);}.card .opt:hover:not(:disabled) { background: var(--pill); }.card .opt:active:not(:disabled) { background: var(--pill-hover); }/* 选项字母平时只是一列字;选中后才填成一块(这是状态,不是容器) */.card .opt .letter {- width: 22px; height: 22px; border-radius: var(--r-sm); flex: none; display: grid; place-items: center;- color: var(--muted); font-size: var(--fs-sm); font-weight: var(--fw-semibold);+ width: var(--ctl-xs); height: var(--ctl-xs); border-radius: var(--r-sm); flex: none; display: grid; place-items: center;+ color: var(--muted); font-size: var(--fs-xs); font-weight: var(--fw-semibold); font-variant-numeric: tabular-nums;transition: background var(--t-fast), color var(--t-fast);}.card .opt:hover:not(:disabled) .letter { color: var(--fg); }-.card .opt .desc { display: block; font-size: var(--fs-sm); color: var(--muted); }+.card .opt .desc { display: block; margin-top: var(--space-0-5); font-size: var(--fs-sm); color: var(--muted); }.card .opt.picked .letter, .card .opt.picked:hover .letter { background: var(--fg); color: var(--surface-solid); }.card.done .q { color: var(--muted); }.card.done .opt { color: var(--placeholder); }@@ -209,17 +247,19 @@ button.act-head:active { background: var(--pill-hover); }display: flex; align-items: center; gap: var(--space-3); width: min(360px, 100%); padding: var(--space-2-5) var(--space-3-5) var(--space-2-5) var(--space-2-5);background: var(--well); border-radius: var(--r-well);}-.file-card > .ic { width: 40px; height: 40px; padding: var(--space-2); color: var(--fg-2); }-.file-card .fname { font-size: var(--fs-lg); font-weight: var(--fw-semibold); color: var(--fg); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }-.file-card .fsub { font-size: var(--fs-sm); color: var(--muted); }+.file-card > .ic { --ic-size: var(--ic-xl); margin: var(--space-2); color: var(--fg-2); } /* 24px 图标 + 四周 8 = 40 见方,和两行文字等高 */+.file-card .fname { font-size: var(--fs-lg); font-weight: var(--fw-medium); color: var(--fg); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.file-card .fsub { margin-top: var(--space-0-5); font-size: var(--fs-xs); color: var(--muted); }.msg-row .notice { max-width: min(var(--bubble-w), 100%); }.chat-empty { margin: auto; padding-top: 16vh; display: grid; justify-items: center; gap: var(--space-2-5); text-align: center; color: var(--muted); }-.chat-empty h2 { font-size: var(--fs-2xl); font-weight: var(--fw-semibold); color: var(--fg); }-.chips { display: flex; gap: var(--space-2); flex-wrap: wrap; justify-content: center; margin-top: var(--space-1-5); }+/* 头像和标题之间多留一点:大头像会呼吸、会动,贴太近显得挤 */+.chat-empty h2 { margin-top: var(--space-2); font-size: var(--fs-2xl); font-weight: var(--fw-semibold); letter-spacing: var(--tracking-tight); line-height: var(--lh-tight); color: var(--fg); }+.chat-empty > p { max-width: 440px; margin: 0; font-size: var(--fs-md); line-height: var(--lh-normal); }+.chips { display: flex; gap: var(--space-2); flex-wrap: wrap; justify-content: center; margin-top: var(--space-2-5); }/* 建议:和次级按钮一样是一层静默填充,不描边、不浮起 */.chip {- height: 32px; padding: 0 var(--space-3-5); border-radius: var(--r-full); background: var(--pill);+ height: var(--ctl-md); padding: 0 var(--space-3-5); border-radius: var(--r-full); background: var(--pill);font-size: var(--fs-sm); color: var(--fg-2); transition: background var(--t-fast), color var(--t-fast), transform var(--t-fast);}.chip:hover { background: var(--pill-hover); color: var(--fg); }@@ -233,9 +273,11 @@ button.act-head:active { background: var(--pill-hover); }--rise: 6px; animation: rise-in var(--dur-base) var(--ease-out);transition: color var(--t-fast), scale var(--t-fast);}+.to-bottom.leaving { animation: sink-out var(--dur-base) var(--ease-in) forwards; pointer-events: none; }.to-bottom:hover { color: var(--fg); }.to-bottom:active { scale: var(--press-strong); }.to-bottom .new { position: absolute; top: 0; right: 0; width: 8px; height: 8px; border-radius: 50%; background: var(--accent-solid); box-shadow: 0 0 0 2px var(--surface-solid), 0 0 0 2.5px var(--accent-line); } /* 描边:圆点外的缺口和墨色细边,黄绿点才压得住白底 */+.to-bottom .new { --scale-from: 0; animation: scale-in var(--dur-slow) var(--ease-back); }/* —— 输入框:文字区 + 工具栏两行,一块浮在对话流上的玻璃(和菜单、提示同一种材质:细边 + 投影,不额外描边)。认得出它靠的是:浮起的投影、常显的占位文字(3:1)、工具栏和发送钮,以及固定在底部的位置。@@ -256,7 +298,7 @@ button.act-head:active { background: var(--pill-hover); }background: var(--grain), linear-gradient(var(--composer-tint), var(--composer-tint)), var(--glass-float);backdrop-filter: var(--glass-filter); border-radius: var(--r-3xl);box-shadow: inset 0 1px 0 var(--glass-hi), 0 0 0 var(--composer-edge-w) var(--composer-edge), var(--composer-shadow); /* 描边:浮层玻璃的细边;拖入文件时换成 accent */- transition: box-shadow var(--t-base);+ transition: box-shadow var(--t-moderate); /* 聚焦时浮高一点:投影慢慢长出来,不是一下变大 */}.composer:focus-within { --composer-shadow: var(--shadow-lg); }.composer.drag { --composer-edge: var(--accent); --composer-edge-w: 1.5px; --composer-shadow: var(--ring), var(--shadow-md); --composer-tint: var(--accent-wash); }@@ -269,21 +311,22 @@ button.act-head:active { background: var(--pill-hover); }.composer textarea:focus-visible { outline: none; }.composer-bar { display: flex; align-items: center; gap: var(--bar-gap); padding: var(--space-1-5) var(--composer-pad) var(--composer-pad); }.composer-bar .grow { flex: 1; }+/* 加号钮和发送钮一样是 32 的圆:加号落在 --composer-pad + 8 = 16,和上面文字的起点对齐;模型胶囊矮一档(28),不和两端的圆钮抢 */.composer :is(.plus, .model-chip) {- flex: none; height: 30px; display: inline-flex; align-items: center; justify-content: center; color: var(--ctl-fg);+ flex: none; height: var(--ctl-md); display: inline-flex; align-items: center; justify-content: center; color: var(--ctl-fg);transition: background var(--t-fast), color var(--t-fast), transform var(--t-fast);}.composer :is(.plus, .model-chip):hover { background: var(--pill); color: var(--fg); }.composer :is(.plus, .model-chip)[aria-expanded="true"] { background: var(--pill-hover); color: var(--fg); }.composer :is(.plus, .model-chip):active { background: var(--pill-press); transform: scale(var(--press)); }-.composer .plus { width: 30px; border-radius: 50%; }+.composer .plus { width: var(--ctl-lg); height: var(--ctl-lg); border-radius: 50%; }.composer .plus .ic { transition: transform var(--t-moderate); }.composer .plus[aria-expanded="true"] .ic { transform: rotate(45deg); }.composer .model-chip { max-width: 240px; padding: 0 var(--space-2) 0 var(--space-2-5); border-radius: var(--r-full); gap: var(--space-1); font-size: var(--fs-sm); }.composer .model-chip .v { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }-.composer .model-chip .ic { width: 12px; height: 12px; transition: transform var(--t-base); }+.composer .model-chip .ic { --ic-size: var(--ic-xs); transition: transform var(--t-base); }.composer .model-chip[aria-expanded="true"] .ic:last-child { transform: rotate(180deg); }-.composer .model-chip .ic.lead { width: 14px; height: 14px; }+.composer .model-chip .ic.lead { --ic-size: var(--ic-sm); }.composer .model-chip.perm { max-width: 160px; }/* 完全权限:胶囊常驻一层淡红,图标用 --red;字仍是 --fg(淡红底上的红字对比度不够)。悬停 / 打开 / 按下在淡红上再叠一层 */.composer .model-chip.perm.full { background: var(--red-wash); color: var(--fg); }@@ -291,13 +334,18 @@ button.act-head:active { background: var(--pill-hover); }.composer .model-chip.perm.full:hover { background: linear-gradient(var(--pill), var(--pill)), var(--red-wash); }.composer .model-chip.perm.full[aria-expanded="true"] { background: linear-gradient(var(--pill-hover), var(--pill-hover)), var(--red-wash); }.composer .model-chip.perm.full:active { background: linear-gradient(var(--pill-press), var(--pill-press)), var(--red-wash); }-/* 发送:空的时候是中性的灰钮(不用半透明的墨色或黄绿,会发浑);能发了才亮起品牌色,悬停时箭头往上提一点 */+/* 发送:空的时候是中性的灰钮(不用半透明的墨色或黄绿,会发浑),箭头也小一号;能发了才亮起品牌色,+ 箭头带一点回弹放大到位("可以发了");悬停时箭头往上提一点。+ 发出后换成停止方块,方块从小弹到位;回复结束,箭头从下面升回来(.back:发过一次之后才有,打开页面时不动) */.send {width: var(--ctl-lg); height: var(--ctl-lg); border-radius: 50%; flex: none; display: grid; place-items: center;background: var(--send-bg); color: var(--send-fg); box-shadow: var(--primary-edge);transition: background var(--t-base), color var(--t-base), box-shadow var(--t-base), transform var(--t-fast);}-.send .ic { transition: transform var(--t-base); }+.send .ic { transition: transform var(--t-base), scale var(--dur-base) var(--ease-back); }+.send:disabled .ic { scale: .86; }+.send.stop .ic { --scale-from: .4; animation: scale-in var(--dur-slow) var(--ease-spring); }+.send.back .ic { --rise: 4px; animation: rise-in var(--dur-moderate) var(--ease-out); }.send:hover:not(:disabled) { background: var(--primary-hover); }.send:hover:not(:disabled):not(.stop) .ic { transform: translateY(-1px); }.send:active:not(:disabled) { background: var(--primary-press); transform: scale(var(--press-strong)); }diff --git a/ui/css/guide.css b/ui/css/guide.cssnew file mode 100644index 0000000..6aab185--- /dev/null+++ b/ui/css/guide.css@@ -0,0 +1,128 @@+/* 新手引导(components/guide.js):对话空状态里的上手清单卡、侧栏左下角的清单入口、指着要点的地方的引导卡片、彩带。+ 清单卡是内容里的一组(--well,不描边);引导卡片是浮层玻璃(和菜单同一种材质);+ 要点的地方亮一圈 accent(和键盘焦点同一种语言),输入框借用拖入文件时的样子。 */+@layer app {++/* —— 进度格:做完的格子是主操作色,点亮时弹一下 —— */+.guide-bar { display: grid; grid-template-columns: repeat(var(--n, 6), minmax(0, 1fr)); gap: var(--space-1); }+.guide-bar i { height: 4px; border-radius: 2px; background: var(--pill-hover); }+.guide-bar i.on { background: var(--primary); animation: guide-seg var(--dur-slow) var(--ease-back) both; animation-delay: calc(var(--stagger) * var(--i, 0) / 4); }+@keyframes guide-seg { from { opacity: .3; transform: scaleY(calc(1 + 1.2 * var(--motion))); } }++/* —— 对话空状态里的清单卡 —— */+.chat-empty.with-guide { padding-top: var(--space-12); }+.guide-card {+ width: min(540px, 100%); margin-top: var(--space-2); padding: var(--card-pad);+ display: grid; gap: var(--space-3); text-align: left; color: var(--fg);+ background: var(--well); border-radius: var(--r-well);+}+.guide-card-head { display: flex; align-items: baseline; gap: var(--space-2); }+.guide-count { font-size: var(--fs-xs); color: var(--muted); }+.guide-steps { list-style: none; margin: 0 calc(-1 * var(--space-2)); padding: 0; display: grid; gap: var(--space-0-5); }+.guide-step {+ display: flex; align-items: center; gap: var(--space-3); width: 100%; min-height: var(--ctl-xl);+ padding: var(--space-1-5) var(--space-2); border-radius: calc(var(--r-well) - var(--space-1));+ text-align: left; font-size: var(--fs-md); color: var(--fg);+}+button.guide-step { transition: background var(--t-fast); }+button.guide-step:hover { background: var(--pill); }+button.guide-step:active { background: var(--pill-hover); }+button.guide-step > .ic { color: var(--muted); }+.guide-step .title { flex: 1; min-width: 0; font-weight: var(--fw-medium); }+.guide-step .n {+ flex: none; display: grid; place-items: center; width: var(--ctl-xs); height: var(--ctl-xs); border-radius: 50%;+ background: var(--pill-hover); color: var(--muted); font-size: var(--fs-2xs); font-weight: var(--fw-semibold);+}+.guide-step.done .n { background: var(--primary); color: var(--on-primary); }+.guide-step.done .title { color: var(--muted); font-weight: var(--fw-regular); }+/* 当前这一步:铺一层 --accent-wash(状态,不是又一层容器),序号亮成黄绿片 */+.guide-step.open { align-items: flex-start; padding: var(--space-2-5) var(--space-2); background: var(--accent-wash); }+.guide-step.open .n { background: var(--accent-solid); color: var(--on-accent); box-shadow: 0 0 0 .5px var(--accent-line); } /* 描边:黄绿圆点在白底上只有 1.15:1,要一道墨色细边 */+.guide-step .body { flex: 1; min-width: 0; display: grid; gap: var(--space-1-5); }+.guide-step.open .title { font-weight: var(--fw-semibold); }+.guide-step .desc { margin: 0; color: var(--fg-2); line-height: var(--lh-normal); }+:is(.guide-step, .guide-coach) .how { margin: 0; padding-left: var(--space-4); display: grid; gap: var(--space-1); color: var(--muted); font-size: var(--fs-sm); line-height: var(--lh-normal); }+.guide-try { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2); margin-top: var(--space-1); padding-top: var(--space-2); border-top: 1px solid var(--line-2); }+.guide-try .txt { flex: 1 1 160px; min-width: 0; font-size: var(--fs-md); color: var(--fg); line-height: var(--lh-snug); }++/* —— 侧栏左下角的清单入口:账户行上面,和侧栏的行对齐 —— */+.guide-pill {+ flex: none; display: flex; align-items: center; gap: var(--space-2-5); height: var(--ctl-xl); margin: 0 var(--side-inset);+ padding: 0 var(--side-row-px); border-radius: var(--r-lg); background: var(--accent-wash);+ font-size: var(--fs-md); color: var(--fg); text-align: left;+ transition: background var(--t-fast);+}+.guide-pill:hover { background: var(--side-hover); }+.guide-pill:active { background: var(--side-press); }+.guide-pill[aria-expanded="true"] { background: var(--side-active); box-shadow: var(--shadow-tile); }+.guide-pill .guide-bar { flex: none; grid-template-columns: repeat(var(--n, 6), 4px); gap: var(--space-0-5); }+.guide-pill .guide-bar i { height: 14px; }+.guide-pill .v { flex: 1; min-width: 0; font-weight: var(--fw-medium); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.guide-pill .num { font-size: var(--fs-xs); color: var(--muted); }+.guide-pill.bumped { animation: bump var(--dur-slow) var(--ease-out); }++/* —— 引导卡片:浮层玻璃,放在要点的地方旁边(.up / .down / .left),小三角指过去 —— */+.guide-coach {+ position: fixed; z-index: calc(var(--z-popover) - 1); width: min(300px, calc(100vw - 2 * var(--pane-gap)));+ padding: var(--card-pad); display: grid; gap: var(--space-2-5); color: var(--fg);+ background: var(--grain), var(--glass-pop); backdrop-filter: var(--glass-filter-lg);+ border-radius: var(--r-pane); box-shadow: var(--shadow-pop);+ --pop-scale: .96;+ animation: fade-in var(--dur-base) var(--ease-out), pop-in var(--dur-slower) var(--ease-spring);+}+.guide-coach.glide { transition: left var(--t-moderate), top var(--t-moderate); }+.guide-coach.up { transform-origin: var(--ax) 100%; --pop-dy: 6px; }+.guide-coach.down { transform-origin: var(--ax) 0; }+.guide-coach.left { transform-origin: 100% var(--ay); --pop-dy: 0px; }+/* 小三角:转 45° 的方块只露出卡片外面那一半 */+.guide-coach-arrow { position: absolute; width: 12px; height: 12px; rotate: 45deg; background: var(--grain), var(--glass-pop); backdrop-filter: var(--glass-filter-lg); }+.guide-coach.up .guide-coach-arrow { left: var(--ax); bottom: 0; translate: -50% 50%; clip-path: polygon(100% 0, 100% 100%, 0 100%); }+.guide-coach.down .guide-coach-arrow { left: var(--ax); top: 0; translate: -50% -50%; clip-path: polygon(0 0, 100% 0, 0 100%); }+.guide-coach.left .guide-coach-arrow { top: var(--ay); right: 0; translate: 50% -50%; clip-path: polygon(0 0, 100% 0, 100% 100%); }+.guide-coach-top { display: flex; align-items: center; gap: var(--space-2); }+.guide-coach-top .icon-btn { margin-right: calc(-1 * var(--space-1-5)); }+.guide-done {+ display: inline-flex; align-items: center; gap: var(--space-1); height: var(--ctl-xs); padding: 0 var(--space-2); border-radius: var(--r-full);+ background: var(--accent-solid); color: var(--on-accent); font-size: var(--fs-2xs); font-weight: var(--fw-semibold);+ box-shadow: 0 0 0 .5px var(--accent-line); /* 描边:黄绿填充面在白底上要一道墨色细边 */+ animation: fade-in var(--dur-base) var(--ease-out), pop-in var(--dur-slower) var(--ease-back);+}+.guide-coach-body { display: grid; gap: var(--space-2); }+.guide-coach h3 { margin: 0; font-size: var(--fs-xl); font-weight: var(--fw-semibold); line-height: var(--lh-tight); }+.guide-coach .desc { margin: 0; font-size: var(--fs-md); color: var(--fg-2); line-height: var(--lh-normal); }+/* 渠道那一步:① ② ③ 依次点亮 */+.guide-coach .how.steps { list-style: none; padding-left: 0; counter-reset: s; }+.guide-coach .how.steps li { display: flex; align-items: flex-start; gap: var(--space-2); counter-increment: s; transition: color var(--t-base), opacity var(--t-base); }+.guide-coach .how.steps li::before {+ content: counter(s); flex: none; display: grid; place-items: center; width: 18px; height: 18px; border-radius: 50%;+ background: var(--pill-hover); color: var(--muted); font-size: var(--fs-2xs); font-weight: var(--fw-semibold);+ transition: background var(--t-base), color var(--t-base);+}+.guide-coach .how.steps li.cur { color: var(--fg); }+.guide-coach .how.steps li.cur::before { background: var(--primary); color: var(--on-primary); }+.guide-coach .how.steps li.past { opacity: .55; }+.guide-coach .guide-try { margin-top: 0; }+.guide-coach-actions { display: flex; align-items: center; justify-content: space-between; gap: var(--ctl-gap); }++/* —— 要点的地方:和键盘焦点同一种 accent 外圈,轻轻往外呼吸;输入框用拖入文件时的样子 —— */+.guide-spot:not(.composer) { outline: 2px solid var(--accent); outline-offset: var(--space-0-5); animation: guide-ping calc(var(--dur-pulse) * 1.2) var(--ease-in-out) infinite; } /* 描边:引导时要你点的地方 */+@keyframes guide-ping { 50% { outline-offset: calc(var(--space-0-5) + var(--space-1) * var(--motion)); outline-color: var(--accent-soft); } }+/* 信息面板里的行装在会裁切的分组里:外圈往里收,不呼吸 */+.row.guide-spot { outline-offset: calc(-1 * var(--space-0-5)); animation: none; }+.composer.guide-spot { --composer-edge: var(--accent); --composer-edge-w: 1.5px; --composer-shadow: var(--ring), var(--shadow-md); --composer-tint: var(--accent-wash); }++/* —— 生图的预置演示(MediaDemo):提问卡片用对话里的 .card,下面是生成中 → 出图 —— */+.guide-demo { display: grid; gap: var(--space-3); justify-items: start; }+.guide-demo-figure { margin: 0; display: grid; gap: var(--space-1-5); }+.guide-demo-img { position: relative; width: min(320px, 100%); aspect-ratio: 1; border-radius: var(--r-well); overflow: hidden; background: var(--well); }+.guide-demo-img .skel { position: absolute; inset: 0; height: auto; border-radius: 0; }+.guide-demo-img img { display: block; width: 100%; height: 100%; object-fit: cover; animation: guide-reveal calc(var(--dur-slower) * 2) var(--ease-out) both; }+@keyframes guide-reveal { from { opacity: 0; filter: blur(calc(16px * var(--motion))); transform: scale(calc(1 + .04 * var(--motion))); } }+.guide-demo-bar { position: absolute; left: var(--space-5); right: var(--space-5); bottom: var(--space-5); height: 4px; border-radius: 2px; background: var(--pill-hover); overflow: hidden; }+.guide-demo-bar i { display: block; height: 100%; background: var(--primary); transition: width var(--t-moderate); }++/* —— 全部完成的彩带(颜色由 JS 取机器人眼睛色的 token) —— */+.guide-confetti { position: fixed; inset: 0; z-index: var(--z-toast); pointer-events: none; overflow: hidden; }+.guide-confetti i { position: absolute; width: 8px; height: 12px; border-radius: 2px; }+.guide-confetti i.dot { height: 8px; border-radius: 50%; }+}diff --git a/ui/css/settings.css b/ui/css/settings.cssindex fa1786e..0acfe24 100644--- a/ui/css/settings.css+++ b/ui/css/settings.css@@ -15,7 +15,7 @@.set-titles .set-title { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }.set-sub { font-size: var(--fs-md); color: var(--muted); }/* 返回钮往左探出,箭头的笔画落在内容列的左边上(和分组标题、标签、卡片同一条线) */-.set-back { --ib-size: 32px; --ib-r: var(--r-full); --ib-fg: var(--ctl-fg); margin-left: calc(-1 * var(--space-2-5)); }+.set-back { --ib-size: var(--ctl-lg); --ib-r: var(--r-full); --ib-fg: var(--ctl-fg); margin-left: calc(-1 * var(--space-2-5)); }.set-body { padding: var(--space-2) var(--page-px) var(--page-bottom); }/* 分组标题与卡片:标题、输入框标签、卡片共用内容列的左边 */@@ -25,8 +25,10 @@/* 分组下方的风险提示(完全权限):紧跟在组的下面,不放进组里 */.settings .list + .notice { margin-top: var(--space-2); align-items: flex-start; padding: var(--space-3); }.settings .list + .notice > .ic { margin-top: 3px; } /* 微调:图标对齐第一行文字(14px 图标 / 约 20px 行高) */-.settings .row { --row-h: 60px; --row-py: var(--space-3); --row-pl: var(--space-4); --row-pr: var(--space-4); --row-gap: var(--space-4); }-.settings .row .name { font-size: var(--fs-lg); }+/* 行:上下 10,一行的行和"名称 + 说明"两行的行都是 60 高(14 × 1.4 + 2 + 12.5 × 1.4 + 20 ≈ 59)。+ 名称用常规字重、说明用 --muted:一页十几行时不发闷,层次交给分组标题的字重和说明的颜色 */+.settings .row { --row-h: 60px; --row-py: var(--space-2-5); --row-pl: var(--space-4); --row-pr: var(--space-4); --row-gap: var(--space-4); }+.settings .row .name { font-size: var(--fs-lg); font-weight: var(--fw-regular); line-height: var(--lh-snug); }.settings .row .sub { font-size: var(--fs-sm); line-height: var(--lh-snug); max-width: 460px; white-space: normal; }.settings .pick { height: var(--ctl-md); padding: 0 var(--space-2) 0 var(--space-3); border-radius: var(--r-lg); }.settings .seg { --seg-r: var(--r-lg); }@@ -39,21 +41,44 @@.balance { font-size: var(--fs-lg); font-weight: var(--fw-semibold); font-variant-numeric: tabular-nums; }.balance.low { color: var(--red); }.settings input.field.num-in { width: 96px; --field-h: var(--ctl-md); text-align: right; font-variant-numeric: tabular-nums; }+.settings input.field.font-in { width: min(220px, 36vw); --field-h: var(--ctl-md); }++/* 外观预览(设置 › 外观顶部):一组 --well,里面一问一答 + 一行代码,用对话页同样的字号与字体 token,+ 跟着字体大小、界面字体、代码字体和代码换行实时变 */+.ap-preview {+ display: grid; gap: var(--space-3); margin-top: var(--space-6); padding: var(--card-pad);+ background: var(--well); border-radius: var(--r-well);+}+.set-body > .ap-preview + .list { margin-top: var(--space-3); }+.ap-bubble {+ justify-self: end; max-width: 80%; padding: var(--space-2-5) var(--space-4); border-radius: var(--r-bubble);+ background: var(--bubble-user); font-size: var(--fs-xl); line-height: var(--lh-relaxed);+}+.ap-reply { font-size: var(--fs-xl); line-height: var(--lh-relaxed); }+.ap-reply b { font-weight: var(--fw-semibold); }+.ap-code {+ margin: 0; font: var(--fs-sm)/var(--lh-relaxed) var(--code); color: var(--fg-2);+ white-space: var(--code-wrap); overflow-wrap: anywhere; overflow-x: auto;+}/* 用量:近 N 天的日柱状图 + 模型排行 */.usage-days { display: grid; grid-auto-flow: column; grid-auto-columns: minmax(0, 1fr); align-items: end; gap: var(--space-1); height: 120px; padding: var(--space-2) 0; }-.usage-days .bar { display: grid; align-content: end; justify-items: center; gap: var(--space-1); height: 100%; font-size: var(--fs-2xs); color: var(--faint); }-.usage-days .bar i { display: block; width: 100%; min-height: 2px; border-radius: var(--r-sm) var(--r-sm) 0 0; background: var(--accent-solid); }+.usage-days .bar { display: grid; align-content: end; justify-items: center; gap: var(--space-1); height: 100%; font-size: var(--fs-2xs); color: var(--muted); }+.usage-days .bar i {+ display: block; width: 100%; min-height: 2px; border-radius: var(--r-sm) var(--r-sm) 0 0; background: var(--accent-solid);+ box-shadow: inset 0 0 0 var(--hairline) var(--accent-line); /* 描边:黄绿柱子在白底上只有 1.15:1,要一道细边才看得出高度(同应用标志) */+}.usage-models { display: grid; gap: var(--space-1); font-size: var(--fs-sm); }.usage-models div { display: flex; justify-content: space-between; gap: var(--space-3); }.usage-models .v { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.usage-models .n { color: var(--muted); font-variant-numeric: tabular-nums; }-.notif { display: grid; gap: var(--space-1); padding: var(--space-3) 0; border-bottom: .5px solid var(--line); }+.notif { display: grid; gap: var(--space-1); padding: var(--space-3) 0; border-bottom: 1px solid var(--line-2); }.notif:last-child { border-bottom: 0; }.notif b { font-weight: var(--fw-semibold); }-.notif.unread b::before { content: ""; display: inline-block; width: 6px; height: 6px; margin-right: var(--space-1-5); border-radius: 50%; background: var(--accent-solid); vertical-align: middle; }+/* 未读点用 --accent(浅色墨、深色黄绿):6px 的黄绿点在浅色玻璃上几乎看不见 */+.notif.unread b::before { content: ""; display: inline-block; width: 6px; height: 6px; margin-right: var(--space-1-5); border-radius: 50%; background: var(--accent); vertical-align: middle; }.notif p { font-size: var(--fs-sm); color: var(--fg-2); white-space: pre-wrap; }-.notif time { font-size: var(--fs-2xs); color: var(--faint); }+.notif time { font-size: var(--fs-2xs); color: var(--muted); }/* 故障排查(screens/troubleshoot.js):状态和检测结果是普通的行;stderr 尾部是组里展开的一块(不再套底);日志是自己的一块 --well(和代码块同一种面),不描边 */@@ -77,8 +102,8 @@.set-field { display: grid; gap: var(--space-2); margin-bottom: var(--space-5); }.set-field .k { display: flex; align-items: baseline; gap: var(--space-2); font-size: var(--fs-md); font-weight: var(--fw-medium); color: var(--fg-2); }.set-field .k .hint { font-weight: var(--fw-regular); }-.set-field .field { --field-h: var(--ctl-xl); --field-px: var(--space-3-5); --field-r: var(--r-xl); font-size: var(--fs-lg); }-.set-field textarea.field { min-height: 120px; padding: var(--space-3) var(--field-px); line-height: var(--lh-relaxed); }+.set-field .field { --field-h: var(--ctl-xl); --field-px: var(--space-3); --field-r: var(--r-lg); font-size: var(--fs-lg); }+.set-field textarea.field { min-height: 120px; padding: var(--space-2-5) var(--field-px); line-height: var(--lh-relaxed); }/* 新建机器人(参考 Grok Bot 的创建页):居中的表单,下面是模板卡片 */.new-bot { flex: 1; min-height: 0; display: flex; flex-direction: column; }@@ -104,12 +129,12 @@.tpl:active { background: var(--well-press); transform: scale(var(--press)); }.tpl.on, .tpl.on:hover { background: var(--accent-wash); }.tpl-ic {- grid-row: span 2; width: 36px; height: 36px; border-radius: var(--r-lg); display: grid; place-items: center; color: var(--fg-2);+ grid-row: span 2; width: var(--ctl-xl); height: var(--ctl-xl); border-radius: var(--r-lg); display: grid; place-items: center; color: var(--fg-2);transition: background var(--t-base), color var(--t-base);}.tpl:hover .tpl-ic { color: var(--fg); }-.tpl.on .tpl-ic { background: var(--accent-solid); color: var(--on-accent); box-shadow: inset 0 0 0 .5px var(--accent-line); } /* 描边:黄绿在白底上只有 1.15:1,要一道墨色细边 */-.tpl-name { font-size: var(--fs-lg); font-weight: var(--fw-semibold); }+.tpl.on .tpl-ic { background: var(--accent-solid); color: var(--on-accent); box-shadow: inset 0 0 0 var(--hairline) var(--accent-line); } /* 描边:黄绿在白底上只有 1.15:1,要一道墨色细边 */+.tpl-name { font-size: var(--fs-lg); font-weight: var(--fw-medium); line-height: var(--lh-snug); }.tpl-desc { font-size: var(--fs-sm); color: var(--muted); line-height: var(--lh-snug); }/* onboarding */@@ -130,7 +155,7 @@}/* 同一个表单(onboarding.js 的 KeyForm)在"更换密钥"对话框里:对话框本身就是那张卡,表单直接排在对话框的内边距里,不再套一层 */.sheet > form.list { padding: 0; background: none; border-radius: 0; overflow: visible; display: grid; gap: var(--space-2-5); }-.onboard label.k { font-size: var(--fs-sm); font-weight: var(--fw-semibold); color: var(--fg-2); }+.onboard label.k { font-size: var(--fs-sm); font-weight: var(--fw-medium); color: var(--fg-2); }.onboard .err-text { font-size: var(--fs-sm); color: var(--red); line-height: var(--lh-normal); display: flex; gap: var(--space-2); align-items: center; flex-wrap: wrap; }.onboard .slow { font-size: var(--fs-sm); color: var(--muted); }.onboard .links { display: grid; gap: var(--space-2); justify-items: center; font-size: var(--fs-sm); color: var(--muted); }diff --git a/ui/css/shell.css b/ui/css/shell.cssindex e21b062..5ac11a2 100644--- a/ui/css/shell.css+++ b/ui/css/shell.css@@ -1,7 +1,12 @@/* Shell:sidebar 280 | main 1fr | info panel 320(按需)。没有顶栏。窗口最底层是环境光(--bg + 左上的品牌黄绿光 + 跟着当前机器人变的色相光),- 侧栏是直接盖在环境光上的毛玻璃;主区和信息面板是浮在上面的圆角面板(--pane-gap 间隙)。 */+ 侧栏是直接盖在环境光上的毛玻璃;主区和信息面板是浮在上面的圆角面板(--pane-gap 间隙)。+ 侧栏、信息面板和主区之间的空隙是分隔条(README「分隔条」):拖动调宽,双击恢复。 */@property --aura-hue { syntax: "<number>"; inherits: true; initial-value: 250; }+/* 列宽注册成 <length>,才能平滑过渡:信息面板开合、双击恢复默认宽度、键盘调宽时列宽滑过去,主区跟着让位。+ 不继承:过渡的每一帧只重算 .app 和两条分隔条(它们显式 inherit),不牵动整棵对话的样式 */+@property --side-col { syntax: "<length>"; inherits: false; initial-value: 280px; }+@property --panel-track { syntax: "<length>"; inherits: false; initial-value: 0px; }@layer app {#app { height: 100%; }@@ -16,24 +21,46 @@var(--bg);transition: --aura-hue var(--dur-ambient) var(--ease-in-out);}+/* 引导页的语言切换(onboarding.js 的 LangSwitch):在引导列顶上靠右,不碰窗口角上的红绿灯 / 窗口按钮;+ 左边的地球图标是标识,展开时不跟着箭头转 */+.onboard-lang { justify-self: end; }+.onboard-lang .pick[aria-expanded="true"] .lead { transform: none; }+/* 三列总在:侧栏 | 主区 | 信息面板。信息面板关着时那一列是 0,打开时滑到 --panel-col(面板本身定宽,+ 列变窄时它往右滑出窗口,所以开合是"滑进来 / 滑出去",面板里的内容不会被挤扁重排) */.app {+ --side-col: clamp(var(--side-w-min), var(--side-w-user, var(--side-w)), min(var(--side-w-max), var(--side-w-cap)));+ --panel-col: clamp(var(--panel-w-min), var(--panel-w-user, var(--panel-w)), min(var(--panel-w-max), var(--panel-w-cap)));+ --panel-track: 0px;+ position: relative; overflow: hidden;display: grid; height: 100vh;- grid-template-columns: var(--side-w) minmax(0, 1fr);+ grid-template-columns: var(--side-col) minmax(0, 1fr) var(--panel-track);+ grid-template-rows: minmax(0, 1fr);+ transition: --aura-hue var(--dur-ambient) var(--ease-in-out), --side-col var(--dur-slow) var(--ease-spring), --panel-track var(--dur-slow) var(--ease-spring);}+.app > .side { grid-area: 1 / 1; }+.app > .main { grid-area: 1 / 2; }+.app > .panel { grid-area: 1 / 3; }+.app.with-panel { --panel-track: var(--panel-col); }+/* 拖分隔条时列宽跟手,不过渡 */+:root[data-resizing] .app { transition: --aura-hue var(--dur-ambient) var(--ease-in-out); }+/* 分隔条在空隙的正中,比空隙宽一点(两边各探进 2px,更好抓);细线只画在面板直边那一段(上下让出面板的圆角) */+.app > .splitter { --side-col: inherit; --panel-track: inherit; z-index: calc(var(--z-float) + 1); --split-inset: calc(var(--pane-gap) + var(--r-pane)); }+.app > .split-side { --split-x: calc(var(--side-col) - var(--pane-gap) / 2); }+.app > .split-panel { --split-x: calc(100% - var(--panel-track) - var(--pane-gap) / 2); }/* "已保存" sits in the window's bottom-left corner, over the sidebar above the account button,so it never covers the floating composer: left edge on the sidebar rows' line, one --side-inset above the account row */.app .toasts { left: var(--side-inset); bottom: calc(var(--side-inset) * 2 + var(--ctl-2xl)); }-.app.with-panel { grid-template-columns: var(--side-w) minmax(0, 1fr) var(--panel-w); }/* 主区:浮在环境光上的面板。不要给它加 backdrop-filter / transform——里面的菜单是 position: fixed */.main {position: relative; min-width: 0; min-height: 0; display: flex; flex-direction: column;margin: var(--pane-gap) var(--pane-gap) var(--pane-gap) 0;- border-radius: var(--r-pane); background: var(--surface); box-shadow: var(--shadow-pane); overflow: hidden; /* 描边:浮在环境光上的面板,浅色下和环境光只差 1.1:1,要一道 .5px 的边 */+ border-radius: var(--r-pane); background: var(--surface); box-shadow: var(--shadow-pane); overflow: hidden; /* 描边:浮在环境光上的面板,浅色下和环境光只差 1.1:1,要一道细线(--hairline)的边 */}.view { --rise: 4px; animation: rise-in var(--dur-moderate) var(--ease-out); }/* —— Sidebar(参考 Grok Bot):新建按钮 | 常驻搜索 | 机器人行 | 账户。- 行的状态:悬停是更亮的一层玻璃,按下稍暗,选中是浮起的玻璃片(--side-active + --shadow-tile) —— */+ 行的状态:悬停叠一层淡灰,按下再深一级,选中是浮起的白色玻璃片(--side-active + --shadow-tile)——+ 悬停偏暗、选中偏亮,两种状态一眼分得开 —— */.side {--ib-bg-hover: var(--side-hover);--ib-bg-press: var(--side-press);@@ -41,25 +68,28 @@min-height: 0; display: flex; flex-direction: column;background: var(--grain), var(--glass-side);}-/* 顶部按钮和主区顶栏在同一条中线上:主区离窗口上沿 --pane-gap,这里也先让出 --pane-gap */+/* 顶部按钮和主区顶栏在同一条中线上:主区离窗口上沿 --pane-gap,这里也先让出 --pane-gap。+ 右边让到新建按钮的图标(28 的按钮里 16 的图标,四周各 6)落在行文字的右边线上(--side-inset + --side-row-px),+ 和机器人行的时间右对齐 */.side-top {display: flex; align-items: center; justify-content: flex-end; gap: var(--bar-gap);- height: calc(var(--pane-gap) + var(--head-h)); padding: var(--pane-gap) var(--side-inset) 0; flex: none;+ height: calc(var(--pane-gap) + var(--head-h)); padding: var(--pane-gap) calc(var(--side-inset) + var(--side-row-px) - var(--space-1-5)) 0 var(--side-inset); flex: none;-webkit-app-region: drag;}.side-top > * { -webkit-app-region: no-drag; }.side-top.start { justify-content: flex-start; }+/* 返回:箭头和间隙与设置导航一样(16 + 10),"返回应用"和下面的导航文字落在同一条竖线上 */.side-back {- display: inline-flex; align-items: center; gap: var(--space-1-5); height: var(--ctl-lg); padding: 0 var(--side-row-px);+ display: inline-flex; align-items: center; gap: var(--space-2-5); height: var(--ctl-lg); padding: 0 var(--side-row-px);border-radius: var(--r-lg); font-size: var(--fs-md); color: var(--ctl-fg); transition: background var(--t-fast), color var(--t-fast);}.side-back:hover { background: var(--side-hover); color: var(--fg); }.side-back:active { background: var(--side-press); }-.side-top .icon-btn { --ib-size: 30px; --ib-fg: var(--ctl-fg); }+.side-top .icon-btn { --ib-size: var(--ctl-md); --ib-fg: var(--ctl-fg); }.side-top .icon-btn.on { box-shadow: var(--shadow-tile); }-/* 搜索框和行同宽;图标、间隙和设置导航一样,搜索文字和导航文字对齐 */+/* 搜索框和行同宽、和返回按钮同高;搜索图标 14 + 间隙 12 = 导航图标 16 + 间隙 10,搜索文字和导航文字对齐 */.side-search {- flex: none; display: flex; align-items: center; gap: var(--space-2-5); height: 34px; margin: 0 var(--side-inset) var(--side-inset); padding: 0 var(--side-row-px);+ flex: none; display: flex; align-items: center; gap: var(--space-3); height: var(--ctl-lg); margin: 0 var(--side-inset) var(--side-inset); padding: 0 var(--side-row-px);border-radius: var(--r-lg); background: var(--pill); color: var(--muted);transition: box-shadow var(--t-fast), background var(--t-fast), color var(--t-fast);}@@ -69,18 +99,19 @@.side-search input::placeholder { color: var(--muted); }.side-search input::-webkit-search-cancel-button { display: none; }-/* 上边留一行的间隙,选中行的投影不被滚动容器裁掉 */+/* 上边留一行的间隙,选中行的投影不被滚动容器裁掉。+ 右边用外边距而不是内边距:滚动条落在行的右边上,不落进侧栏和主区之间的空隙(那里是分隔条) */.side-list {- flex: 1; min-height: 0; overflow-y: auto; padding: var(--side-row-gap) var(--side-inset) var(--side-inset);+ flex: 1; min-height: 0; overflow-y: auto; padding: var(--side-row-gap) 0 var(--side-inset) var(--side-inset); margin-right: var(--side-inset);display: grid; grid-template-columns: minmax(0, 1fr); align-content: start; gap: var(--side-row-gap);}.side-list > .hint { padding: var(--space-2) var(--side-row-px); }-/* 设置时的侧栏:分页导航 */-.side-nav { --rise: 3px; animation: rise-in var(--dur-moderate) var(--ease-out); }+/* 机器人列表和设置导航在侧栏里互换时(进出设置)轻轻浮上来,两个方向一样 */+.side-list { --rise: 3px; animation: rise-in var(--dur-moderate) var(--ease-out); }.nav-item {--focus-offset: -2px;- display: flex; align-items: center; gap: var(--space-2-5); height: var(--ctl-xl); padding: 0 var(--side-row-px);- border-radius: var(--r-lg); font-size: var(--fs-lg); color: var(--fg-2); text-align: left;+ display: flex; align-items: center; gap: var(--space-2-5); height: var(--ctl-lg); padding: 0 var(--side-row-px);+ border-radius: var(--r-lg); font-size: var(--fs-md); color: var(--fg-2); text-align: left;transition: background var(--t-fast), color var(--t-fast), box-shadow var(--t-fast);}.nav-item .ic { color: var(--muted); transition: color var(--t-fast); }@@ -95,22 +126,34 @@border-radius: var(--r-xl); text-align: left; position: relative;transition: background var(--t-fast), box-shadow var(--t-fast);}-.thread:hover { background: var(--side-hover); }+/* 行外面包一层 .thread-item,"更多"按钮叠在行上:指针在按钮上时整行仍是悬停的样子 */+.thread:hover, .thread-item:hover > .thread { background: var(--side-hover); }button.thread:active { background: var(--side-press); }-.thread.sel, button.thread.sel:active { background: var(--side-active); box-shadow: var(--shadow-tile); }+.thread.sel, .thread-item > .thread.sel, button.thread.sel:active { background: var(--side-active); box-shadow: var(--shadow-tile); }.thread .body { min-width: 0; flex: 1; display: grid; gap: var(--space-0-5); }.thread .line { display: flex; align-items: baseline; gap: var(--space-2); min-width: 0; }-.thread .title { flex: 1; min-width: 0; font-size: var(--fs-lg); font-weight: var(--fw-semibold); color: var(--fg); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; line-height: var(--lh-tight); }-.thread .when { flex: none; font-size: var(--fs-xs); color: var(--muted); }-.thread .snip { flex: 1; min-width: 0; font-size: var(--fs-md); color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; line-height: 1.4; }+.thread .title { flex: 1; min-width: 0; font-size: var(--fs-lg); font-weight: var(--fw-medium); color: var(--fg); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; line-height: var(--lh-tight); }+.thread .when { flex: none; font-size: var(--fs-xs); color: var(--muted); transition: opacity var(--t-fast); }+.thread .snip { flex: 1; min-width: 0; font-size: var(--fs-md); color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; line-height: var(--lh-snug); }.thread.sel .snip { color: var(--fg-2); }.thread .badge.count { --badge-bg: var(--amber-soft); --badge-fg: var(--amber); align-self: center; }.thread .avatar-wrap { position: relative; flex: none; }.thread .working-dot {position: absolute; right: -1px; bottom: -1px; width: 10px; height: 10px; border-radius: 50%; /* 微调:压住头像的边 */- background: var(--green); box-shadow: 0 0 0 2px var(--surface-solid); /* 描边:压在头像上的缺口,不是边框 */+ background: var(--green); box-shadow: 0 0 0 2px var(--dot-cut, var(--side-solid)); /* 描边:压在头像上的缺口(和行底同色),不是边框 */animation: breathe var(--dur-pulse) var(--ease-in-out) infinite;}+.thread.sel .working-dot { --dot-cut: var(--side-solid-on); }+/* "更多"(重命名 / 复制 ID / 删除,和右键菜单同一份):叠在行的右上角、和名称同一行;悬停、键盘聚焦、菜单打开时出现,+ 出现时把时间让出来。按钮的图标右沿落在行文字的右边线上 */+.thread-item { position: relative; min-width: 0; }+.thread-more {+ --ib-size: var(--ctl-sm); --ib-fg: var(--muted);+ position: absolute; top: var(--space-2); right: var(--space-1-5);+ opacity: 0; transition: opacity var(--t-fast), background var(--t-fast), color var(--t-fast), transform var(--t-fast);+}+.thread-item:hover > .thread-more, .thread-more:focus-visible, .thread-more[aria-expanded="true"] { opacity: 1; }+.thread-item:is(:hover, :has(> .thread-more:focus-visible), :has(> .thread-more[aria-expanded="true"])) .when { opacity: 0; }.thread-skel { flex: 1; display: grid; gap: var(--space-1-5); }.thread .field { --field-h: 30px; }/* 侧栏空状态:一句话 + 一个按钮,靠留白成组,不套卡片 */@@ -130,40 +173,77 @@ button.thread:active { background: var(--side-press); }.account:active { background: var(--side-press); }.account.on { background: var(--side-active); box-shadow: var(--shadow-tile); }.account .me {- width: 30px; height: 30px; border-radius: 50%; flex: none; display: grid; place-items: center;+ width: var(--ctl-md); height: var(--ctl-md); border-radius: 50%; flex: none; display: grid; place-items: center;background: var(--pill);font-weight: var(--fw-semibold); font-size: var(--fs-sm); color: var(--fg-2);}-.account .who { flex: 1; min-width: 0; font-size: var(--fs-lg); color: var(--fg); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }-.account .who .bal { display: block; font-size: var(--fs-2xs); color: var(--muted); }+.account .who { flex: 1; min-width: 0; font-size: var(--fs-md); font-weight: var(--fw-medium); color: var(--fg); line-height: var(--lh-snug); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.account .who .bal { display: block; font-size: var(--fs-2xs); font-weight: var(--fw-regular); color: var(--muted); }.account .who .bal.low { color: var(--red); }+/* 余额不足:和其他出错的提示行一样只铺一层淡红(--red-wash),字用 --fg,前面一个红点;+ 悬停、按下时淡红加深一级,不加下划线(整条都是链接) */.low-balance {- flex: none; margin: 0 var(--space-2); padding: var(--space-2) var(--space-3); border-radius: var(--r-lg);- font-size: var(--fs-sm); color: var(--red); background: var(--side-hover); text-decoration: none;+ --low-wash: var(--red-wash);+ flex: none; display: flex; align-items: center; gap: var(--space-2);+ margin: 0 var(--side-inset); padding: var(--space-2) var(--side-row-px); border-radius: var(--r-lg);+ font-size: var(--fs-sm); line-height: var(--lh-snug); color: var(--fg); background: var(--low-wash);+ transition: background var(--t-fast);}-.low-balance:hover { background: var(--side-press); }+.low-balance::before { content: ""; width: 6px; height: 6px; border-radius: 50%; flex: none; background: var(--red); }+.low-balance:hover { --low-wash: color-mix(in srgb, var(--red) 14%, transparent); text-decoration: none; }+.low-balance:active { --low-wash: color-mix(in srgb, var(--red) 20%, transparent); }.account > .ic { color: var(--muted); transition: color var(--t-fast); }.account:hover > .ic { color: var(--fg); }-/* macOS desktop: traffic lights live in the sidebar's top-left.- 拖动窗口只靠侧栏顶部和各页顶栏;不要把 .app 整个设成拖动区——盖在上面的命令面板、对话框、提示会跟着变成拖动区 */+/* —— 窗口标题栏:桌面版没有系统标题栏,侧栏顶部这一行(--pane-gap + --head-h)就是标题栏。+ 左上角归谁看平台:macOS 是红绿灯(应用名在菜单栏里,这里不再放 Logo),Windows 是应用图标 + 名称(Windows 的习惯)。+ 拖动窗口只靠侧栏顶部和各页顶栏;不要把 .app 整个设成拖动区——盖在上面的命令面板、对话框、提示会跟着变成拖动区 —— */:root.mac-app .side-top { padding-left: var(--titlebar-inset); }+/* Windows desktop(:root.win-app):右上角是系统画的最小化 / 最大化 / 关闭(Window Controls Overlay,electron/main.ts),+ 和侧栏顶部这一行一样高、贴住窗口右上角,背景透明。最右边的顶栏给它让位:信息面板开着时是面板的顶栏(抽屉模式也是),+ 关着时是主区的顶栏。让出的宽度 = 按钮宽度(env(titlebar-area-*) 算出来)减去面板离窗口右边的 --pane-gap,+ 再留一个 --head-px,自家的按钮和窗口按钮之间空出一截 */+:root.win-app {+ --caption-w: calc(100vw - env(titlebar-area-x, calc(100vw - var(--caption-w-fallback))) - env(titlebar-area-width, 0px));+ --caption-reserve: calc(var(--caption-w) - var(--pane-gap));+}+:root.win-app .app:not(.with-panel) .chat-head,+:root.win-app .panel-head { padding-right: calc(var(--head-px) + var(--caption-reserve)); }+/* 信息面板开合时主区顶栏的让位跟着列宽一起滑,不跳 */+:root.win-app .chat > .chat-head { transition: box-shadow var(--t-base), padding-right var(--dur-slow) var(--ease-spring); }+/* 面板自己的关闭钮会和窗口的关闭钮挨在一起(两个 ×):Windows 上不放,主区顶栏的面板开关、⌘⇧I、Esc、点遮罩都能关 */+:root.win-app .panel-close { display: none; }++/* 应用图标 + 名称:图标的左沿和机器人行的头像、搜索图标同一条竖线(--side-inset + --side-row-px)。+ 它属于标题栏,是拖动区的一部分(按住能拖、双击最大化),不是按钮 */+.side-brand { display: none; }+:root.win-app .side-top > .side-brand {+ display: flex; align-items: center; gap: var(--space-2); min-width: 0; margin: 0 auto 0 var(--side-row-px);+ font-size: var(--fs-md); font-weight: var(--fw-semibold); color: var(--fg-2); line-height: var(--lh-tight);+ -webkit-app-region: drag; user-select: none;+}+.side-brand img { flex: none; width: var(--brand-mark); height: var(--brand-mark); -webkit-user-drag: none; }+.side-brand span { min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+/* —— Info panel(参考 Grok Bot 的详情栏):一块更通透的玻璃面板,分组直接是列表行,不再套卡片;需要成组的东西(展开的编辑区、待审批)是面板上唯一的一层 --well —— */+/* 面板定宽:开合时是它那一列在变(见 .app),面板跟着列的左边滑进 / 滑出窗口,同时淡入 / 淡出;+ 关上时 main.js 让它多留一会儿(usePresence)播完 .leaving */.panel {- min-height: 0; display: flex; flex-direction: column;+ width: calc(var(--panel-col) - var(--pane-gap)); min-height: 0; display: flex; flex-direction: column;margin: var(--pane-gap) var(--pane-gap) var(--pane-gap) 0;border-radius: var(--r-pane); background: var(--grain), var(--glass-panel); box-shadow: var(--shadow-pane); overflow: hidden;- animation: slide-in var(--dur-moderate) var(--ease-out);+ animation: fade-in var(--dur-slow) var(--ease-out);}+.panel.leaving { animation: fade-out var(--dur-slow) var(--ease-in) forwards; pointer-events: none; }.panel-head {height: var(--head-h); flex: none; display: flex; align-items: center; gap: var(--bar-gap); padding: 0 var(--head-px) 0 var(--pane-px);-webkit-app-region: drag;}.panel-head > * { -webkit-app-region: no-drag; }-.panel-head .title { flex: 1; min-width: 0; font-size: var(--fs-xl); font-weight: var(--fw-semibold); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }-.panel-head .icon-btn { --ib-size: 30px; }+.panel-head .title { flex: 1; min-width: 0; font-size: var(--fs-lg); font-weight: var(--fw-semibold); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.panel-head .icon-btn { --ib-size: var(--ctl-md); } /* 16 的图标四周各 6:图标外沿落在 --head-px + 6 = --pane-px 上,和标题左边对称 *//* 行是贴着面板的玻璃片:片离面板边缘 8,行里再缩进 8,文字落在 --pane-px,和面板标题对齐 */.panel-body { flex: 1; overflow-y: auto; padding: 0 var(--space-2) var(--space-6); }.panel-body .list-head { margin: var(--section-gap-sm) var(--space-2) var(--space-1); }@@ -205,15 +285,19 @@ button.thread:active { background: var(--side-press); }.panel-scrim { display: none; }/* narrow window: the panel floats over the chat as a glass 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: var(--z-drawer); top: var(--pane-gap); right: var(--pane-gap); bottom: var(--pane-gap); width: var(--panel-w); margin: 0;+ .app.with-panel { --panel-track: 0px; }+ .app > .panel {+ position: fixed; z-index: var(--z-drawer); top: var(--pane-gap); right: var(--pane-gap); bottom: var(--pane-gap); margin: 0;background: var(--grain), var(--glass-pop); backdrop-filter: var(--glass-filter-lg); box-shadow: var(--shadow-pop);+ animation: slide-in var(--dur-moderate) var(--ease-out);}+ .app > .panel.leaving { animation: slide-out var(--dur-base) var(--ease-in) forwards; }+ .app > .split-panel { display: none; } /* 抽屉浮在对话上,宽度不用调 */.panel-scrim {display: block; position: fixed; z-index: calc(var(--z-drawer) - 1); inset: 0;background: var(--scrim-soft); animation: fade-in var(--dur-base) var(--ease-out);}+ .panel-scrim.leaving { animation: fade-out var(--dur-base) var(--ease-in) forwards; pointer-events: none; }}@media (max-width: 900px) {:root { --side-w: 240px; }diff --git a/ui/design/README.md b/ui/design/README.mdindex bc191f3..9d7ac40 100644--- a/ui/design/README.md+++ b/ui/design/README.md@@ -2,7 +2,7 @@界面样式的唯一来源。无构建步骤:原生 CSS(`@layer` + 自定义属性)+ Preact/htm 组件。-- 样例页:本机服务的 `/amb/static/design/index.html`。token 表直接从 `tokens/*.css` 解析,不会和代码脱节;支持浅色/深色和双主题对照,也能模拟"减少动态效果"。+- 样例页:本机服务的 `/amb/static/design/index.html`。token 表直接从 `tokens/*.css` 解析,不会和代码脱节;支持浅色/深色和双主题对照,也能模拟"减少动态效果";设置 › 外观里的偏好(字体大小、字体、动画、毛玻璃)在样例页里同样生效。- 守卫测试:`test/design-system.unit.test.ts`。`npm test` 时检查规范有没有被破坏(规则见文末)。## 目录@@ -12,18 +12,18 @@ ui/design/index.css 入口:声明层顺序并按层引入下面所有文件tokens/primitives.css L1 原始值:品牌/状态色板,间距、字号、圆角、控件高度、层级等尺度- semantic.css L2 语义 token:按用途命名、按主题取值(浅色 + 深色);另有与主题无关的间距角色+ semantic.css L2 语义 token:按用途命名、按主题取值(浅色 + 深色);另有与主题无关的间距角色、字体与用户偏好motion.css 动效 token:时长、缓动、位移量、--motion 开关base/reset.css 重置、焦点环、可选中规则motion.css 关键帧库 + .anim-* 工具类 + 减少动态效果typography.css 文字角色 .t-*(在 utilities 层)utilities.css .stack .cluster .grow .truncate .tone-* .sr-only- components/ 一个组件一个文件:glass button field badge list seg switch popover model-family sheet toast notice feedback avatar+ components/ 一个组件一个文件:icon glass button field badge list seg switch popover model-family sheet splitter toast notice feedback avatarmotion.js ms("--dur-base")、usePresence()、reducedMotion()index.html / gallery.* 样例页-ui/css/ 页面样式(shell / chat / settings),放在 app 层-ui/components/ui.js 组件的 JS 写法:Button IconButton Notice Skeleton Seg Switch Menu MenuButton Sheet …+ui/css/ 页面样式(shell / chat / settings / guide),放在 app 层+ui/components/ui.js 组件的 JS 写法:Icon Button IconButton Notice Skeleton Seg Switch Menu MenuButton Sheet …```## 层叠顺序@@ -45,10 +45,13 @@ ui/components/ui.js 组件的 JS 写法:Button IconButton Notice Skeleton| 类别 | 规则 ||---|---|| 颜色 | 页面和组件**只用语义色**。原始色板只在 `semantic.css` 里引用。新颜色先加语义 token(两个主题都要给值),再用。 |-| 字号 | 9 级 `--fs-2xs … --fs-4xl`(11 / 11.5 / 12.5 / 13 / 14 / 15 / 17 / 20 / 24)。新界面优先用文字角色 `.t-*`。 |+| 字号 | 9 级 `--fs-2xs … --fs-4xl`(11 / 11.5 / 12.5 / 13 / 14 / 15 / 17 / 20 / 22),都乘以 `--fs-scale`(设置 › 外观 › 字体大小)。新界面优先用文字角色 `.t-*`;跟着文字走的长度(比如输入框行高 `--composer-line`)也乘 `--fs-scale`。 |+| 字重与字距 | `--fw-semibold` 只给标题:页面、分组、对话框、顶栏与面板标题、提问卡的问题、正文里的标题、11px 小标签。名称一类(机器人名、文件名、模板名、账户名、信息面板的行)用 `--fw-medium`;设置页的行名称用常规字重,层次交给分组标题和 `--muted` 的说明。大标题用 `--tracking-tighter`(-.015em)、二级标题 `--tracking-tight`(-.01em)——中文字形本来就满,不要收得更紧;行高用 `--lh-*`,不写 1.45 这类散值。 |+| 字体 | 只用 `--font` / `--code`。它们默认是各平台的系统字体 `--font-system` / `--code-system`,用户可以换成衬线 `--font-serif` 或自定义字体(见「用户偏好」)。 || 圆角 | `--r-xs … --r-3xl`、`--r-full`。同一种面用同一个圆角角色:`--r-well`(内容里的一组)、`--r-pane`(面板与浮层)、`--r-bubble`(消息气泡),见「容器与层次」。嵌套时内层 = 外层 − 内边距(`.seg`、`.pop` 里的列表项就是这样算的)。圆形用 `50%`。 || 间距 | 4 的倍数 `--space-1 … --space-16`,另有 `-0-5 / -1-5 / -2-5 / -3-5` 半步。页面和组件先用按用途命名的间距角色(见下文「间距」)。写死的像素只允许 0、≤1px 的细线,以及同一行带 `/* 微调:… */` 注释的光学微调。 || 控件高度 | `--ctl-xs … --ctl-2xl`(22 / 24 / 28 / 32 / 36 / 44)。 |+| 细线 | `--hairline`:一个物理像素(普通屏 1px,高分屏 .5px)。面板、玻璃浮层、黄绿填充面的细边都用它——写死 `.5px` 在 1x 屏上会被抗锯齿成一道若有若无的虚影。 || 层次 | `--well` / `--well-hover` / `--well-press`(内容里的一组,只有这一层);`--line-2`(行间细线);`--ctl-edge` / `--ctl-edge-hover`(输入框的边,≥ 3:1);`--red-wash` / `--amber-wash`(提示行的淡底)。规则见「容器与层次」。 || 投影 | `--shadow-xs / sm / md / lg`;`--shadow-pane`(浮在环境光上的面板)、`--shadow-tile`(侧栏选中项,只有投影)、`--shadow-float` / `--shadow-pop`(玻璃的边 + 投影)、`--primary-edge`、`--seg-edge`(分段 thumb、开关圆钮,只有投影)。深色下更重,都是主题 token。内容里的组不加投影。 || 层级 | 只用 `--z-*`;同一窗格内的浮动件用 `calc(var(--z-float) ± 1)`。 |@@ -81,10 +84,13 @@ ui/components/ui.js 组件的 JS 写法:Button IconButton Notice Skeleton**对齐的线**,改间距时守住:-- **顶部中线**:侧栏顶部先让出 `--pane-gap` 再放 `--head-h`,新建按钮和主区、信息面板的顶栏按钮在同一条水平线上;搜索框的上沿就是顶栏的下沿。+- **顶部中线**:侧栏顶部先让出 `--pane-gap` 再放 `--head-h`,新建按钮和主区、信息面板的顶栏按钮在同一条水平线上;搜索框的上沿就是顶栏的下沿。顶栏里的图标按钮一律 28(`--ctl-md`):16 的图标四周各 6,算对齐时按图标的外沿算。+- **窗口标题栏**:桌面版没有系统标题栏,侧栏顶部这一行就是标题栏。左上角看平台:macOS 让给红绿灯(`--titlebar-inset`),不放 Logo(应用名在菜单栏里);Windows(`:root.win-app`)放应用图标(`--brand-mark` 20)+「AnyModelBot」,图标的左沿落在侧栏竖线上,整块是拖动区。Windows 的右上角是系统画的最小化 / 最大化 / 关闭,和这一行一样高、贴住窗口右上角;最右边的顶栏(信息面板开着时是面板的顶栏,关着时是主区的顶栏)右边多让出 `--caption-reserve`,这时两种顶栏不再左右对称。信息面板自己的关闭钮在 Windows 上不放,免得和窗口的关闭钮挨成两个 ×。浏览器里和 Linux 桌面版用的是系统 / 浏览器的标题栏,这些都不出现。- **底边**:侧栏的账户行离窗口下沿 `--pane-gap`,和主区、信息面板的下沿对齐;"已保存"浮在账户行上方一个 `--side-inset`,左边和侧栏的行对齐。-- **侧栏竖线**:行、搜索框、账户的边离侧栏边缘 `--side-inset`;头像、导航图标、搜索图标、返回箭头都在 `--side-inset + --side-row-px`(18);搜索框的文字和设置导航的文字对齐。-- **面板竖线**:信息面板的标题、分组标题、行文字、展开编辑区、待审批说明都在 `--pane-px`(16);对话顶栏是 `--head-px` + 按钮自带的 6,头像也落在 16。+- **侧栏竖线**:行、搜索框、账户的边离侧栏边缘 `--side-inset`;头像、导航图标、搜索图标、返回箭头都在 `--side-inset + --side-row-px`(18);搜索框的文字、"返回应用"和设置导航的文字在同一条竖线上(搜索图标 14 + 间隙 12 = 导航图标 16 + 间隙 10)。新建按钮的图标右沿落在行文字的右边线上(同样离侧栏右边 18),和机器人行的时间右对齐。机器人列表的右边距用外边距:滚动条贴着行的右边,不落进侧栏和主区之间的空隙(那里是分隔条)。+- **空隙**:侧栏与主区、主区与信息面板之间都是 `--pane-gap`;分隔条就放在空隙正中(见「分隔条」)。+- **面板竖线**:信息面板的标题、分组标题、行文字、展开编辑区、待审批说明都在 `--pane-px`(16);对话顶栏是 `--head-px` + 按钮自带的 6,头像也落在 16。两种顶栏都左右对称:最右边那个图标的外沿同样离面板右边 16。+- **输入框**:加号钮和发送钮都是 32 的圆、离输入框的边 `--composer-pad`(8),加号的图标框正好落在文字的起点(16)上;模型、权限胶囊矮一档(28),不和两端的圆钮抢。- **居中列**:对话列和输入框同宽 `min(--col-w, 100% − 2 × --page-gutter)`,设置页、新建页、引导页两侧也至少 `--page-gutter`。对话列的下边距和"回到底部"的位置由输入框高度 `--composer-h` 算出来。- **弹出层**:列表离边缘 `--pop-pad`(4),项再缩进 8,于是项的文字、分组名、分隔线、搜索图标、空状态都在离边缘 12 的线上。- **行**:默认行上下 6,"标题 + 说明"两行的行和一行的行一样高(48);`.row.compact` 只是矮一些,左右和默认行一样;`.row-edit` 的左右也和行一样,输入框和上面那行的文字对齐。@@ -129,7 +135,7 @@ ui/components/ui.js 组件的 JS 写法:Button IconButton Notice Skeleton- **填充、悬停、描边都是半透明的一层**(`--pill*`、`--side-*`、`--line*`、`--sel*`),放在玻璃和实色上都对。不要在玻璃上用实色灰。- **`backdrop-filter` 会让元素变成 `position: fixed` 子元素的包含块**。里面会渲染菜单、对话框的容器(侧栏、主区、`.chat`)不要加,模糊只加在叶子级的浮层上。-- 系统开了"降低透明度"(`prefers-reduced-transparency`),材质自动换成接近实色,层次靠浮层的细边和投影。+- 关掉毛玻璃(`<html data-glass="off">`:设置 › 外观 › 毛玻璃效果;跟随系统时看"降低透明度" `prefers-reduced-transparency`),材质换成接近实色、`--glass-filter*` 变成 `none`,层次靠浮层的细边和投影。- **模糊只给浮层**:对话框、命令面板后面的遮罩只压暗、不模糊——对话框自己的玻璃已经模糊了一层,两层叠在一起既糊又费 GPU。## 容器与层次@@ -169,7 +175,7 @@ ui/components/ui.js 组件的 JS 写法:Button IconButton Notice Skeleton| 状态 | 怎么表现 | 用什么 ||---|---|---|-| 悬停 | 叠一层半透明,静默控件的字从 `--ctl-fg` 变 `--fg`;可点的组(模板卡)底色深一级,不浮起、不加描边 | `--pill` → `--pill-hover`,`--well` → `--well-hover`;侧栏里是更亮的一层玻璃 `--side-hover` |+| 悬停 | 叠一层半透明,静默控件的字从 `--ctl-fg` 变 `--fg`;可点的组(模板卡)底色深一级,不浮起、不加描边 | `--pill` → `--pill-hover`,`--well` → `--well-hover`;侧栏里也是一层淡灰 `--side-hover`(侧栏本来就接近白色,再亮一层看不出来),和选中的白色玻璃片一暗一亮 || 按下 | 再深一级,并轻微缩小(`--press` / `--press-strong`);列表行只变色不缩放 | `--pill-press`、`--sel-press`、`--side-press` || 键盘焦点 | `:focus-visible` 2px `--accent` 描边;输入框是描边 + 光晕 | `--focus-offset`、`--ring` || 打开 | 菜单展开时触发它的按钮保持"按住"的样子,箭头翻转,加号转成叉 | `[aria-expanded="true"]`,`.icon-btn.on` |@@ -180,6 +186,31 @@ ui/components/ui.js 组件的 JS 写法:Button IconButton Notice Skeleton| 只读 | 次级底,聚焦不发光 | `[readonly]` || 滚动边缘 | 内容滚到顶栏底下时,顶栏才出现细线和投影 | `.chat.scrolled` |+## 分隔条++两块面板之间的空隙可以拖:侧栏 | 主区、主区 | 信息面板。组件是 `Splitter`(`ui/components/ui.js`),样式在 `components/splitter.css`。++| 方面 | 规范 |+|---|---|+| 位置 | 就是面板之间那道 `--pane-gap` 空隙,分隔条的中线落在空隙正中;能抓住的宽度 `--split-hit`(12)比空隙宽一点,两边各探进面板 2px。Electron 里是 `no-drag`,盖在顶栏的拖动区上也抓得住 |+| 平时 | 看不见,指针移上去只变成 ↔(`col-resize`) |+| 悬停 | 停住 `--dur-intent` 后空隙中间从中点长出一道 2px 的细线 `--split-line`;只是划过去不闪,移开立刻消失。细线只画在面板直边那一段(上下让出 `--pane-gap + --r-pane`) |+| 拖动 | 细线换成 `--split-line-on`(`--accent`:浅色墨、深色黄绿);整个窗口都是 ↔、不会选中文字(`<html data-resizing>`);宽度跟手(直接写 CSS 变量,不经过渲染,列宽不过渡);离默认宽度 6px 以内吸附回默认;到了最窄 / 最宽,指针换成单向箭头 |+| 范围 | `--side-w-min … min(--side-w-max, --side-w-cap)`(220 … 400,且不超过窗口的 36%),信息面板 `--panel-w-min … min(--panel-w-max, --panel-w-cap)`(280 … 440,34%);拖动时还要给主区留至少 `--main-w-min` |+| 恢复 | 双击分隔条恢复默认宽度,列宽用 `--dur-slow` + `--ease-spring` 滑回去 |+| 键盘 | `role="separator"`,可以 Tab 到;焦点就是那道 accent 细线(不画外描边)。← → 一次 8px、Shift 一次 32px,Home / End 最窄 / 最宽,Enter 恢复默认 |+| 保存 | 松手、键盘、双击时提交一次:`lib/prefs.js` 的 `sideW` / `panelW`(px,0 = 默认),每个窗口各一份;首帧前 `index.html` 先写到 `<html>` 上的 `--side-w-user` / `--panel-w-user`,不闪 |+| 不出现 | 窗口窄于 1180px 时信息面板是浮在对话上的抽屉,它的分隔条隐藏 |++页面怎么接:列宽在 `.app` 上用 `clamp(-min, var(-user, 默认), min(-max, -cap))` 算出来(`--side-col`、`--panel-col`),分隔条用 `--split-x` 定位到空隙中线:++```css+.app > .split-side { --split-x: calc(var(--side-col) - var(--pane-gap) / 2); }+<${Splitter} class="split-side" size="--side-w" label="调整侧栏宽度" value=${sideW} room=${…} onCommit=${(px) => setPrefs({ sideW: px })} />+```++`--side-col`、`--panel-track`(信息面板那一列此刻的宽度:关着是 0)注册成 `<length>`(`@property`,不继承),所以信息面板开合、恢复默认时列宽能平滑过渡:面板本身定宽,列变窄时它往右滑出窗口,里面的内容不会被挤扁重排。+## 主题- `<html data-theme>` 总是解析后的 `light` / `dark`(`index.html` 首帧前设置,`lib/theme.js` 同步)。@@ -187,6 +218,22 @@ ui/components/ui.js 组件的 JS 写法:Button IconButton Notice Skeleton- 因此**不要写** `:root[data-theme="dark"] .xxx { … }` 这类按主题的覆盖。需要两个主题不同的值,就加一个语义 token。- 由其他语义 token 推导的值(`--ring`、`--code-bg`)写在 `:root, [data-theme] { … }` 里,每个作用域都会重新计算。+## 用户偏好++设置 › 外观(和常规里的发送键、通知)是**本机界面偏好**,和主题一样存在 localStorage(`amb-prefs`,`lib/prefs.js`),每个浏览器 / 桌面窗口各一份。外观类的偏好解析成 `<html>` 上的属性,`semantic.css` 的「用户偏好」块和 `motion.css` 把属性翻译成 token——**页面和组件只用 token,不认这些属性**:++| 属性 | 取值 | 翻译成 |+|---|---|---|+| `data-text` | `sm / md / lg / xl` | `--fs-scale`(.92 / 1 / 1.1 / 1.2):只放大文字,控件高度、图标、间距不变;整体放大是桌面版的「界面缩放」(Electron zoom) |+| `data-font` | `system / serif / custom` | `--font`;`custom` 时 `prefs.js` 在 `<html>` 上内联 `--font: "自定义", var(--font-system)`。自定义代码字体同样内联 `--code` |+| `data-width` | `normal / wide / full` | `--col-w`、`--bubble-w`(对话列和输入框) |+| `data-code-wrap` | `on / off` | `--code-wrap`(代码块的 `white-space`) |+| `data-glass` | `on / off` | 材质(见「材质」) |+| `data-motion` | `full / reduce / off` | `--motion`、`--press*`、`--dur-*`(见「动效」) |++- 首帧前 `index.html` 的内联脚本按同样的规则先套一遍,避免闪;改解析规则时它和 `prefs.js` 的 `apply()` 一起改。+- "跟随系统"在 JS 里解析:属性永远是解析后的值,CSS 里不写 `@media (prefers-reduced-*)`。+## 组件每个组件把可调的地方开放成自己的变量。**变体、尺寸和上下文覆盖都只改变量,不改属性**:@@ -200,7 +247,8 @@ ui/components/ui.js 组件的 JS 写法:Button IconButton Notice Skeleton|---|---|---|| 按钮 | `.btn [primary\|ghost\|danger] [sm\|lg] [block]` | `--btn-h --btn-px --btn-r --btn-fs --btn-bg --btn-bg-hover --btn-bg-press --btn-fg --btn-fg-hover --btn-edge` || 毛玻璃 | `.glass`(组件自己是玻璃时直接写三行,见「材质」) | `--glass-bg --glass-blur --glass-shadow` |-| 图标按钮 | `.icon-btn [xs] [on]` | `--ib-size --ib-r --ib-fg --ib-fg-hover --ib-bg-hover --ib-bg-on --ib-bg-press` |+| 图标 | `Icon`(`svg.ic [ic-xs\|ic-sm\|ic-md\|ic-lg\|ic-xl] [ic-strong]`),见下文「图标」 | `--ic-size --ic-w` |+| 图标按钮 | `.icon-btn [xs] [on]`;`IconButton` 的 `iconSize` 缺省 `sm` | `--ib-size --ib-r --ib-fg --ib-fg-hover --ib-bg-hover --ib-bg-on --ib-bg-press` || 文字按钮 | `.text [danger\|accent]` | — || 输入框 | `.field [mono] [err]`,`.field-wrap > .field + .tail`;边是 `--ctl-edge`(≥ 3:1),底透明 | `--field-h --field-px --field-r --field-bg --field-edge --field-edge-hover --field-edge-focus --field-ring` || 状态 / 计数 / 点 | `.badge [ok\|err\|warn\|off]`(状态点 + 文字),`.badge.count [warn]`(计数,唯一带底的徽标),`.dot [ok\|err\|warn]` | `--badge-fg`(点的颜色;计数的字色)`--badge-bg`(只对计数),`--dot-bg` |@@ -209,6 +257,7 @@ ui/components/ui.js 组件的 JS 写法:Button IconButton Notice Skeleton| 开关 | `Switch` 组件(`button.switch[role=switch] [sm]`),只有开 / 关 | `--switch-w --switch-h --switch-pad --switch-track --switch-track-hover --switch-dot --switch-stretch` || 菜单 | `.pick`,`.pop [up]`,`.palette`,`Menu` / `MenuButton` / `Popover` | `--pop-r --pop-pad` || 对话框 | `Sheet` / `confirmSheet()`(`.scrim > .sheet [wide]`) | `--sheet-w --sheet-r` |+| 分隔条 | `Splitter`(`.splitter [dragging]`),见下文「分隔条」 | `--split-x --split-hit --split-line-w --split-inset --split-line-on`;悬停色是语义 token `--split-line` || 提示胶囊 | `toast()` / `saved()` / `failed()`(`.toast [ok\|err\|warn]`) | `--toast-bg --toast-fg --toast-edge` || 行内提示 | `Notice`(自带图标)/ `.notice [amber\|red]`:淡底 + 图标 + `--fg` 字,不描边 | `--notice-bg --notice-ic` || 加载 | `Spinner`、`Skeleton`(`.skel [circle]`)、`.empty-state` | — |@@ -216,6 +265,24 @@ ui/components/ui.js 组件的 JS 写法:Button IconButton Notice SkeletonJS 组件(`ui/components/ui.js`)只是给常用组合一个带逻辑的写法(loading、图标、无障碍属性);直接写类名同样合法。+## 图标++线性图标,16 格画布、`currentColor`、圆头圆角(`ui.js` 的 `P`,样式 `components/icon.css`)。**细、轻、少**:图标是文字旁边的记号,不和文字抢分量。++| 档 | `size` | 像素 | 用在 |+|---|---|---|---|+| xs | `"xs"` | 12 | 下拉箭头(`.pick`、模型胶囊,上下文自动给)、`.icon-btn.xs` 里的关闭、实心圆点里的勾、列表行尾的 › |+| sm | `"sm"` | 14 | **默认**:`Button` / `IconButton` / `Notice` / 菜单的图标和勾、输入框尾部、行内操作(刷新、删除、复制)、侧栏和弹出层的搜索 |+| md | `"md"` | 16 | 顶栏与工具栏按钮(新对话、信息面板、关闭)、侧栏的新建 / 导航 / 账户 / 返回、对话输入框(加号、发送、停止、回到底部)、命令面板搜索 |+| lg | `"lg"` | 20 | 模板卡 |+| xl | `"xl"` | 24 | 文件卡片 |++- **线宽按显示像素算**:`--ic-stroke`(1.25px)对所有尺寸都一样,12px 的箭头和 24px 的文件图标一样细;`icon.css` 把它换算回画布单位(× 16 / 尺寸)。只有实心面上的图标加 `strong`(`--ic-stroke-strong` 1.6px):发送钮的箭头、完成圆点里的勾——细线压在墨色 / 黄绿上会发虚。不要再传任意的 `stroke`。+- **只用这五档**,不写 13、15、17 这类中间值。图标和旁边的文字差不多高或略高一点:12.5–13px 的控件文字配 14,侧栏和顶栏配 16。+- **上下文改尺寸只改 `--ic-size`**(`.pick .ic { --ic-size: var(--ic-xs) }`),不要直接写 `width / height`——那样线宽会跟着缩放。`icon.css` 全部包在 `:where()` 里,任何上下文选择器都能盖过 `size` 属性。+- **实心的小部件**(信息 / 警告的点、省略号、停止方块、调色盘的色点)在 `P` 里写成 `{ s: 描边, f: 实心 }`,用 `dot(x, y, r)` 画圆点,不靠加粗线头冒充圆点。+- 新图标:留 1.75 格左右的边距(主体落在 2–14 之间),拐角 .75 的圆角,能用一条线就不用两条;画好在样例页「图标」一节里和现有图标并排看一遍粗细和大小。+## 动效| 用途 | 时长 | 缓动 |@@ -223,15 +290,30 @@ JS 组件(`ui/components/ui.js`)只是给常用组合一个带逻辑的写| 悬停、按下、颜色变化 | `--dur-fast` 120ms(`--t-fast`) | `--ease-out` || 出现 / 消失、提示胶囊、遮罩 | `--dur-base` 180ms | 入场 `--ease-out`,退场 `--ease-in` || 视图切换、面板、分段 thumb | `--dur-moderate` 240ms | `--ease-out` |+| 布局滑动:信息面板开合、分隔条恢复默认 / 键盘调宽 | `--dur-slow` 360ms | `--ease-spring` |+| 悬停意图:停住多久才亮起提示(分隔条的细线) | `--dur-intent` 240ms | 只延迟出现,移开立刻消失 || 对话框 / 弹出层的弹性入场 | `--dur-slow` 360ms / `--dur-slower` 420ms | `--ease-spring` |-| 循环(转圈、骨架、呼吸、光标) | `--dur-spin --dur-shimmer --dur-pulse --dur-blink` | `linear` / `--ease-in-out` |+| 循环(转圈、骨架、文字微光、呼吸、光标) | `--dur-spin --dur-shimmer --dur-sheen --dur-pulse --dur-blink` | `linear` / `--ease-in-out` |-- **关键帧库**(`base/motion.css`):`fade-in/out`、`rise-in`、`sink-out`、`slide-in`、`pop-in/out`、`bump`、`flash`、`spin`、`shimmer`、`breathe`、`blink`。关键帧只描述起止,时长缓动由使用处给 token。-- **位移量是 token**:`--rise`、`--slide`、`--pop-dy`、`--pop-scale`,组件可以局部覆盖(`.toast { --rise: 6px }`)。-- **减少动态效果**:关键帧里的位移都乘以 `--motion`;系统开启"减少动态效果"时 `--motion: 0`,所有入场自动退化成纯淡入,按下不缩放,过渡几乎瞬时。新写的关键帧也要乘 `--motion`。+- **关键帧库**(`base/motion.css`):`fade-in/out`、`rise-in`、`sink-out`、`slide-in/out`、`pop-in/out`、`scale-in`、`bump`、`flash`、`spin`、`shimmer`、`sheen`(文字微光,配 `background-clip: text`)、`breathe`、`blink`。关键帧只描述起止,时长缓动由使用处给 token。+- **位移量是 token**:`--rise`、`--slide`、`--pop-dy`、`--pop-scale`、`--scale-from`,组件可以局部覆盖(`.toast { --rise: 6px }`)。+- **减少 / 关闭动画**:看 `<html data-motion>`(`full | reduce | off`,设置 › 外观 › 动画;跟随系统时看 `prefers-reduced-motion`)。关键帧里的位移都乘以 `--motion`;`reduce` 时 `--motion: 0`,所有入场自动退化成纯淡入,按下不缩放,过渡几乎瞬时;`off` 时 `--dur-fast … --dur-slower` 也变成 `--dur-off`,出现 / 消失 / 视图切换瞬时完成,只留转圈、骨架、光标这类"正在进行"的循环和定位闪烁。新写的关键帧也要乘 `--motion`;CSS 里不要再写 `@media (prefers-reduced-motion)`,JS 用 `reducedMotion()`(`design/motion.js`)。- **退场动画**:用 `usePresence(open)`(`design/motion.js`)让组件在退场时长内保持挂载,并给元素加 `.leaving` / `.anim-*-out`。`DialogHost` 是参考实现。- **JS 里不写死毫秒数**:`ms("--dur-base")` 读 token(toast 的移除时机就是这样同步的)。-- 只给 `transform` 和 `opacity` 做动画;空闲列表保持安静(头像空闲时只在指针靠近时看过去、悬停时抖一下天线,不自己动)。+- **每个动画都要有明确的表意**:只用来表达状态变化(出现 / 消失、选中、成功 / 失败)、对操作的反馈、真实在进行的过程(加载、生成、传输)、机器人的状态。**严禁背景 / 装饰层的动画**——背景、光晕、边框、纹理一律静止:不做自己循环的光圈 / 光框扩散("隧道"、涟漪、雷达波)、呼吸的光晕、沿边框巡游的扫光、漂浮的光斑 / 粒子、跟随指针的点阵 / 聚光灯。说不出"它在告诉用户什么"的动画一律不加(官网同一条,见 `site/README.md`)。+- 只给 `transform` 和 `opacity` 做动画;空闲列表保持安静(头像空闲时只在指针靠近时看过去、悬停时抖一下天线,不自己动)。唯一的例外是对话里很快答完时工作状态行的收起(`.work.gone`,grid `1fr → 0fr`,只播一次),为的是正文不跳。++**对话流的编排**(`ui/css/chat.css`):发出 → 思考 → 输出 → 收尾,每一步只动一样东西,幅度小,循环都放慢、对比只差一档,余光里知道"在动"就够了。++| 环节 | 动什么 | 怎么动 |+|---|---|---|+| 发出 | 你的气泡 | `fade-in`(base)+ `pop-in`(slow,spring),从下方 12px、缩放 .96,原点右下角(从发送钮那边送出去) |+| 思考 | 工作状态行 | 比气泡晚 `--stagger` 淡入;"思考中"是 `sheen` 微光:`--muted` 底上一道 `--fg-2` 的光,`--dur-sheen` 扫过去再停一拍 |+| 输出 | 新段落 / 列表项 | 新挂载的块淡入(moderate),已在的不重播;最后一段末尾一个 `breathe` 小点(代码块、表格结尾不画) |+| 收尾 | 状态行、操作 | "用时"换字淡入、细线淡入;短于 3 秒的整行平滑收起;最后一条回复的复制 / 时刻晚一拍淡入 |+| 插入 | 提问 / 审批卡、文件、出错提示 | `rise-in`(6px,moderate) |+| 输入框 | 投影、发送钮 | 聚焦时投影 moderate 长大;空时箭头小一号,有字时 `--ease-back` 回弹到位;发出后停止方块 `scale-in`,结束后箭头 `rise-in` 升回(只在发过之后);点发送 / 停止不抢输入框焦点 |+| 其他 | 首次加载、回到底部 | 历史读到后整列淡入一次;回到底部 `rise-in` 出现、`sink-out` 退场,新消息点 `scale-in` |## 头像@@ -270,7 +352,7 @@ JS 组件(`ui/components/ui.js`)只是给常用组合一个带逻辑的写- 间距写死 px:`margin` / `padding` / `gap` / `inset` / `top|right|bottom|left` / `scroll-margin|padding`,以及 `--*-gap|pad|px|py|pl|pr|pt|pb|inset|gutter` 这类间距变量;`calc()` 里加减写死的 px。0、≤1px 细线、同一行带 `/* 微调:… */` 注释的除外- JS 内联样式里写死颜色、字号或间距- 描边容器:`border` / `outline` 带宽度,或 `box-shadow`(包括自定义属性的值)里画一圈 `0 0 0 <宽>` 的边,而同一行没有 `/* 描边:… */`;`:focus*` 选择器里的焦点描边除外-- 侧边色条:左右两侧 ≥ 2px 的 `border`,或 `box-shadow: inset Npx 0 0`;以及上下 > 1px 的分隔线+- 侧边色条:左右两侧 ≥ 2px 的 `border`,或 `box-shadow: inset Npx 0 0`;以及上下 > 1px 的分隔线(`var(--hairline)` 算 1px)- JS 内联样式里画边框- `text-transform: uppercase` 和正的 `letter-spacing`(小标签不全大写、不加字距)- 引用了没定义的 `var(--x)`(带回退值的除外)diff --git a/ui/design/base/motion.css b/ui/design/base/motion.cssindex fb30e04..edbacb6 100644--- a/ui/design/base/motion.css+++ b/ui/design/base/motion.css@@ -5,14 +5,19 @@@keyframes rise-in { from { opacity: 0; transform: translateY(calc(var(--rise) * var(--motion))); } }@keyframes sink-out { to { opacity: 0; transform: translateY(calc(var(--rise) * var(--motion))); } }@keyframes slide-in { from { opacity: 0; transform: translateX(calc(var(--slide) * var(--motion))); } }+@keyframes slide-out { to { opacity: 0; transform: translateX(calc(var(--slide) * var(--motion))); } }/* 弹出层:只管位移与缩放,配合 fade-in 一起用(两者时长不同) */@keyframes pop-in { from { transform: translateY(calc(var(--pop-dy) * var(--motion))) scale(calc(1 - (1 - var(--pop-scale)) * var(--motion))); } }+/* 小东西原地出现:图标替换、提示点 */+@keyframes scale-in { from { opacity: 0; transform: scale(calc(1 - (1 - var(--scale-from)) * var(--motion))); } }@keyframes pop-out { to { opacity: 0; transform: translateY(calc(var(--pop-dy) * var(--motion) / 2)) scale(calc(1 - (1 - var(--pop-scale)) * var(--motion) / 2)); } }/* 一次性反馈 */@keyframes bump { 40% { transform: scale(calc(1 + .12 * var(--motion))); } }@keyframes flash { 0%, 35% { background: var(--mark); } }/* 循环 */@keyframes spin { to { transform: rotate(360deg); } }+/* 文字微光:配合 background-clip: text、300% 宽的渐变;扫过去(0–70%)后停一拍再来 */+@keyframes sheen { 0% { background-position: 100% 0; } 70%, 100% { background-position: 0 0; } }@keyframes shimmer { from { background-position: 100% 0; } to { background-position: -100% 0; } }@keyframes breathe { 0%, 100% { opacity: .45; transform: scale(calc(1 - .15 * var(--motion))); } 50% { opacity: 1; transform: scale(1); } }@keyframes blink { 50% { opacity: 0; } }@@ -21,13 +26,14 @@.anim-fade-in { animation: fade-in var(--anim-dur, var(--dur-base)) var(--anim-ease, var(--ease-out)) var(--anim-delay, 0s) both; }.anim-rise-in { animation: rise-in var(--anim-dur, var(--dur-moderate)) var(--anim-ease, var(--ease-out)) var(--anim-delay, 0s) both; }.anim-slide-in { animation: slide-in var(--anim-dur, var(--dur-moderate)) var(--anim-ease, var(--ease-out)) var(--anim-delay, 0s) both; }+.anim-scale-in { animation: scale-in var(--anim-dur, var(--dur-slow)) var(--anim-ease, var(--ease-spring)) var(--anim-delay, 0s) both; }.anim-pop-in { animation: fade-in var(--dur-base) var(--ease-out), pop-in var(--anim-dur, var(--dur-slower)) var(--anim-ease, var(--ease-spring)); }.anim-fade-out { animation: fade-out var(--anim-dur, var(--dur-base)) var(--anim-ease, var(--ease-in)) forwards; pointer-events: none; }+.anim-slide-out { animation: slide-out var(--anim-dur, var(--dur-base)) var(--anim-ease, var(--ease-in)) forwards; pointer-events: none; }.anim-sink-out { animation: sink-out var(--anim-dur, var(--dur-base)) var(--anim-ease, var(--ease-in)) forwards; pointer-events: none; }.anim-pop-out { animation: pop-out var(--anim-dur, var(--dur-base)) var(--anim-ease, var(--ease-in)) forwards; pointer-events: none; }.anim-flash { animation: flash var(--dur-flash) var(--ease-out); }.anim-bump { animation: bump var(--dur-slow) var(--ease-out); }-@media (prefers-reduced-motion: reduce) {- *, *::before, *::after { transition-duration: var(--dur-off) !important; scroll-behavior: auto !important; }-}+/* 减少 / 关闭动画(<html data-motion>,见 tokens/motion.css):过渡几乎瞬时,不平滑滚动 */+:root:is([data-motion="reduce"], [data-motion="off"]) :is(*, ::before, ::after) { transition-duration: var(--dur-off) !important; scroll-behavior: auto !important; }diff --git a/ui/design/base/reset.css b/ui/design/base/reset.cssindex 9c7e24c..ee2deed 100644--- a/ui/design/base/reset.css+++ b/ui/design/base/reset.css@@ -29,4 +29,3 @@ button:focus-visible, input:focus-visible, textarea:focus-visible, a:focus-visib}/* 滚动条:细、半透明,盖在玻璃和环境光上都不突兀(macOS 的浮动滚动条不受影响) */* { scrollbar-width: thin; scrollbar-color: var(--scroll-thumb) transparent; }-svg.ic { width: 16px; height: 16px; flex: none; display: block; }diff --git a/ui/design/components/avatar.css b/ui/design/components/avatar.cssindex 0614a26..47a3320 100644--- a/ui/design/components/avatar.css+++ b/ui/design/components/avatar.css@@ -487,13 +487,11 @@@keyframes bf-orbit-x { from { translate: calc(var(--s) * -.34) 0; } to { translate: calc(var(--s) * .34) 0; } }@keyframes bf-orbit-y { from { transform: translateY(calc(var(--s) * -.07)) scale(.7); } to { transform: translateY(calc(var(--s) * .07)) scale(1.1); } }-/* 减少动态效果:只留表情变化,不动 */-@media (prefers-reduced-motion: reduce) {- .bot-face, .bot-face * { animation: none !important; transition: none !important; }- .bot-face .bf-look, .bot-face .bf-gaze { transform: none; }- .bot-face .fx:not(.fx-bang, .fx-think) { display: none; }- .bot-face[data-eyes="error"] .e-sad { opacity: 1; scale: 1; rotate: -14deg; }-}+/* 减少 / 关闭动画(<html data-motion>,见 tokens/motion.css):只留表情变化,不动 */+:root:is([data-motion="reduce"], [data-motion="off"]) :is(.bot-face, .bot-face *) { animation: none !important; transition: none !important; }+:root:is([data-motion="reduce"], [data-motion="off"]) .bot-face :is(.bf-look, .bf-gaze) { transform: none; }+:root:is([data-motion="reduce"], [data-motion="off"]) .bot-face .fx:not(.fx-bang, .fx-think) { display: none; }+:root:is([data-motion="reduce"], [data-motion="off"]) .bot-face[data-eyes="error"] .e-sad { opacity: 1; scale: 1; rotate: -14deg; }/* —— 选角色 —— */.avatar-picker { display: flex; flex-wrap: wrap; gap: var(--space-1); }diff --git a/ui/design/components/icon.css b/ui/design/components/icon.cssnew file mode 100644index 0000000..78aa2b7--- /dev/null+++ b/ui/design/components/icon.css@@ -0,0 +1,17 @@+/* 线性图标 svg.ic(ui.js 的 Icon)。规范见 README「图标」。+ 16 格画布、currentColor、圆头圆角。尺寸只取 --ic-xs … --ic-xl 五档;线宽 --ic-stroke 是显示出来的像素,+ 这里把它换算回画布单位(× 16 / 尺寸),所以图标放大缩小,线都一样细。+ 上下文要换尺寸就覆盖 --ic-size(.pick .ic { --ic-size: var(--ic-xs) }),不要直接写 width / height——那样线会跟着变粗变细。+ 这里全部包在 :where() 里:任何上下文选择器都能盖过 Icon 的 size / strong。 */+:where(svg.ic) {+ --ic-size: var(--ic-md);+ --ic-w: var(--ic-stroke);+ width: calc(var(--ic-size) * 1px); height: calc(var(--ic-size) * 1px); flex: none; display: block;+ stroke-width: calc(var(--ic-w) * 16px / var(--ic-size));+}+:where(svg.ic.ic-xs) { --ic-size: var(--ic-xs); }+:where(svg.ic.ic-sm) { --ic-size: var(--ic-sm); }+:where(svg.ic.ic-md) { --ic-size: var(--ic-md); }+:where(svg.ic.ic-lg) { --ic-size: var(--ic-lg); }+:where(svg.ic.ic-xl) { --ic-size: var(--ic-xl); }+:where(svg.ic.ic-strong) { --ic-w: var(--ic-stroke-strong); }diff --git a/ui/design/components/popover.css b/ui/design/components/popover.cssindex f47ac17..cc751ec 100644--- a/ui/design/components/popover.css+++ b/ui/design/components/popover.css@@ -12,7 +12,7 @@.pick:active:not(:disabled) { background: var(--pill-press); transform: scale(var(--press)); }.pick:disabled { opacity: var(--o-disabled); }.pick .v { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }-.pick .ic { width: 12px; height: 12px; color: var(--muted); transition: transform var(--t-base); }+.pick .ic { --ic-size: var(--ic-xs); color: var(--muted); transition: transform var(--t-base); }.pick[aria-expanded="true"] .ic { transform: rotate(180deg); }/* —— 弹出层:从锚点方向(--ox)弹出;向上打开时加 .up —— */@@ -53,7 +53,7 @@:is(.pop, .palette) .search { display: flex; align-items: center; gap: var(--space-2); padding: 0 var(--space-3); border-bottom: 1px solid var(--line-2); color: var(--muted); flex: none; transition: color var(--t-fast); }:is(.pop, .palette) .search:focus-within { color: var(--fg-2); }:is(.pop, .palette) .search input { flex: 1; min-width: 0; background: none; border: 0; outline: none; height: 38px; font-size: var(--fs-md); }-:is(.pop, .palette) .search input::placeholder { color: var(--faint); }+:is(.pop, .palette) .search input::placeholder { color: var(--placeholder); }:is(.pop, .palette) ul { list-style: none; margin: 0; overflow-y: auto; padding: var(--pop-pad); flex: 1 1 auto; }:is(.pop, .palette) li {display: flex; align-items: center; gap: var(--space-2); min-height: 30px; padding: 0 var(--space-2);@@ -81,7 +81,7 @@:is(.pop, .palette) li.explained { white-space: normal; padding: var(--space-1-5) var(--space-2); align-items: flex-start; flex-direction: column; gap: var(--space-0-5); }/* Menu 的说明项:[图标] 标题 / 说明两行 [✓] */:is(.pop, .palette) li.rich { white-space: normal; padding: var(--space-1-5) var(--space-2); }-:is(.pop, .palette) li .lead { flex: none; align-self: flex-start; margin-top: 1px; color: var(--ctl-fg); display: inline-flex; } /* 微调:图标和第一行文字居中 */+:is(.pop, .palette) li .lead { flex: none; align-self: flex-start; margin-top: 2px; color: var(--ctl-fg); display: inline-flex; } /* 微调:14px 图标和第一行文字(约 17.5px 行高)居中 */:is(.pop, .palette) li .txt { flex: 1; min-width: 0; display: grid; gap: var(--space-0-5); }:is(.pop, .palette) li .txt .n { font-size: var(--fs-xs); line-height: var(--lh-snug); }:is(.pop, .palette) .empty { padding: var(--space-3-5) var(--space-3); color: var(--muted); font-size: var(--fs-sm); text-align: center; }diff --git a/ui/design/components/splitter.css b/ui/design/components/splitter.cssnew file mode 100644index 0000000..907c053--- /dev/null+++ b/ui/design/components/splitter.css@@ -0,0 +1,32 @@+/* 分隔条 .splitter:两块面板之间那道空隙,拖动它调整一侧面板的宽度(Splitter 组件,README「分隔条」)。+ 平时看不见,指针移上去只变成 ↔;停住一会儿(--dur-intent,只是划过不闪)空隙中间才从中点长出一道细线;+ 拖动时、键盘焦点时细线是 --accent,到了最窄 / 最宽,指针换成单向箭头(只能往另一边拖了)。+ 容器给 --split-x(分隔条中线离容器左边多远)并且 position: relative。+ 定制:--split-x --split-hit(能抓住的宽度)--split-line-w --split-inset(细线离上下边)--split-line-on;+ 悬停时的颜色是语义 token --split-line,要换就在分隔条上覆盖它 */+.splitter {+ --split-hit: 12px;+ --split-line-w: 2px;+ --split-inset: 0px;+ --split-line-on: var(--accent);+ position: absolute; z-index: var(--z-raised); top: 0; bottom: 0; left: var(--split-x, 50%); width: var(--split-hit);+ translate: -50% 0; cursor: col-resize; touch-action: none;+ -webkit-app-region: no-drag; /* Electron:盖在顶栏的拖动区上也要能抓住 */+}+.splitter::after {+ content: ""; position: absolute; top: var(--split-inset); bottom: var(--split-inset); left: 50%; width: var(--split-line-w);+ translate: -50% 0; border-radius: var(--r-full); background: var(--split-line);+ opacity: 0; transform: scaleY(calc(1 - .4 * var(--motion)));+ transition: opacity var(--t-base), transform var(--dur-slow) var(--ease-spring), background var(--t-fast);+}+/* 悬停:停够 --dur-intent 才亮;移开立刻消失 */+.splitter:hover::after { opacity: 1; transform: none; transition-delay: var(--dur-intent); }+.splitter.dragging::after, .splitter:focus-visible::after { opacity: 1; transform: none; background: var(--split-line-on); transition-delay: 0s; }+/* 键盘焦点就是那道 accent 细线,不再画一圈外描边 */+.splitter:focus-visible { outline: none; }++/* 拖动中(Splitter 在 <html> 上设 data-resizing):整个窗口都是这个指针、不会选中文字;+ 到头了换成单向箭头:e = 只能往右,w = 只能往左 */+:root[data-resizing], :root[data-resizing] * { cursor: col-resize !important; user-select: none !important; -webkit-user-select: none !important; }+:root[data-resizing="e"], :root[data-resizing="e"] * { cursor: e-resize !important; }+:root[data-resizing="w"], :root[data-resizing="w"] * { cursor: w-resize !important; }diff --git a/ui/design/components/toast.css b/ui/design/components/toast.cssindex dee9fcb..9a70625 100644--- a/ui/design/components/toast.css+++ b/ui/design/components/toast.css@@ -12,7 +12,7 @@padding: var(--space-1) var(--space-3); border-radius: var(--r-full);max-width: min(480px, calc(100vw - 2 * var(--float-inset)));background: var(--grain), var(--toast-bg); color: var(--toast-fg); backdrop-filter: var(--glass-filter-sm);- box-shadow: inset 0 1px 0 var(--glass-hi), 0 0 0 .5px var(--toast-edge), var(--shadow-md); /* 描边:浮层玻璃的细边 */+ box-shadow: inset 0 1px 0 var(--glass-hi), 0 0 0 var(--hairline) var(--toast-edge), var(--shadow-md); /* 描边:浮层玻璃的细边 */display: flex; gap: var(--space-2); align-items: center;--rise: 6px;animation: rise-in var(--dur-base) var(--ease-out);diff --git a/ui/design/gallery.css b/ui/design/gallery.cssindex 2396dff..5d3b6d9 100644--- a/ui/design/gallery.css+++ b/ui/design/gallery.css@@ -3,7 +3,7 @@.gal { display: grid; grid-template-columns: 196px minmax(0, 1fr); height: 100vh; background: var(--bg); }.gal-nav {display: grid; align-content: start; gap: var(--space-0-5); overflow-y: auto;- padding: var(--space-5) var(--space-3); background: var(--grain), var(--glass-side); border-right: .5px solid var(--line-2);+ padding: var(--space-5) var(--space-3); background: var(--grain), var(--glass-side); border-right: var(--hairline) solid var(--line-2);}.gal-nav .brand { display: flex; align-items: center; gap: var(--space-2); padding: 0 var(--space-2) var(--space-4); font-weight: var(--fw-semibold); }.gal-nav .t-label { padding: var(--space-3) var(--space-2-5) var(--space-1); }@@ -78,6 +78,7 @@.gal-curve { width: 56px; height: 56px; flex: none; overflow: visible; }.gal-curve rect { fill: none; stroke: var(--line); }.gal-curve path { fill: none; stroke: var(--accent); stroke-width: 2; }+.gal-icon { display: grid; justify-items: center; align-content: center; gap: var(--space-1-5); min-width: 76px; min-height: 52px; color: var(--fg-2); }.gal-anim { display: grid; justify-items: center; gap: var(--space-2); width: 120px; }.gal-anim-box { width: 72px; height: 48px; border-radius: var(--r-lg); background: var(--accent-solid); box-shadow: inset 0 0 0 1px var(--accent-line); } /* 描边:黄绿样例块要一道墨色细边 */@@ -101,7 +102,7 @@.gal-mat b { font-weight: var(--fw-semibold); }/* —— 状态矩阵:一行一个组件,浅色 / 深色两条,画在真实的表面上 —— */-.gal-state > .gal-strip + .gal-strip { border-top: .5px solid var(--line); }+.gal-state > .gal-strip + .gal-strip { border-top: var(--hairline) solid var(--line); }.gal-strip-in { display: flex; flex-wrap: wrap; align-items: flex-start; gap: var(--space-4) var(--space-5); padding: var(--space-4) var(--space-5) var(--space-3-5); }.ctx-surface > .gal-strip-in { background: var(--surface); }.ctx-side > .gal-strip-in { background: var(--grain), var(--glass-side); }@@ -122,4 +123,15 @@.gal-stage-over { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); }.gal-pair > .gal-demo + .gal-demo { border-left: 0; border-top: 1px solid var(--line-2); }}+/* —— 分隔条样例:左边一块"侧栏"、右边一块浮起的"主区",中间 --pane-gap 的空隙就是分隔条(和 shell.css 同一种排法) —— */+:root { --gal-split-w: 200px; --gal-split-w-min: 140px; --gal-split-w-max: 320px; }+.gal-split {+ --gal-col: clamp(var(--gal-split-w-min), var(--gal-split-w-user, var(--gal-split-w)), var(--gal-split-w-max));+ position: relative; display: grid; grid-template-columns: var(--gal-col) minmax(0, 1fr); height: 160px;+ background: var(--grain), var(--glass-side);+}+.gal-split-a { display: grid; place-items: center; }+.gal-split-b { display: grid; place-items: center; margin: var(--pane-gap) var(--pane-gap) var(--pane-gap) 0; border-radius: var(--r-pane); background: var(--surface); box-shadow: var(--shadow-pane); } /* 描边:和主区同一种面板 */+.gal-split > .splitter { --split-x: calc(var(--gal-col) - var(--pane-gap) / 2); --split-inset: calc(var(--pane-gap) + var(--r-pane)); }+.gal-split.mini { --gal-col: 64px; width: 180px; height: 72px; background: none; }}diff --git a/ui/design/gallery.js b/ui/design/gallery.jsindex caf4a91..5748f68 100644--- a/ui/design/gallery.js+++ b/ui/design/gallery.js@@ -1,12 +1,13 @@// 设计库样例页:token 表直接解析 tokens/*.css(单一来源,不会和代码脱节),组件用真实实现渲染。import { render, createContext } from "preact";import { useContext, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";-import { html, Icon, Button, IconButton, Seg, Switch, MenuButton, Menu, Badge, Notice, Skeleton, Spinner, CopyButton, Toasts, DialogHost } from "../components/ui.js";+import { html, Icon, ICONS, Button, IconButton, Seg, Switch, MenuButton, Menu, Badge, Notice, Skeleton, Spinner, CopyButton, Toasts, DialogHost, Splitter } from "../components/ui.js";import { BotAvatar, AvatarPicker, AppMark, BOT_CHARS, CHAR_KEYS, MAIN_CHAR } from "../components/avatar.js";import { TEMPLATES } from "../screens/new-bot.js";import { Markdown } from "../components/markdown.js";import { useStore, toast, saved, failed, confirmSheet } from "../lib/store.js";import { themeMode, setThemeMode } from "../lib/theme.js";+import "../lib/prefs.js"; // 外观偏好(字体大小、动画、毛玻璃…)在样例页里也生效const Compare = createContext(false);@@ -274,16 +275,18 @@ function SegState({ st, disabled }) {}, []);return html`<div ref=${ref}><${Seg} label="示例" value="a" disabled=${disabled} onChange=${noop} options=${[["a", "自动"], ["b", "国际"]]} /></div>`;}-const thread = (c, { working } = {}) => html`<button type="button" class=${`thread ${c}`} style="width: 236px">+const thread = (c, { working } = {}) => html`<div class=${`thread-item ${c}`} style="width: 236px"><button type="button" class=${`thread ${c}`}><span class="avatar-wrap"><${BotAvatar} id="a1f3c9d2" name="群聊日报" size=${38} working=${working} />${working && html`<span class="working-dot"></span>`}</span><span class="body"><span class="line"><span class="title">群聊日报</span><span class="when num">09:24</span></span><span class="line"><span class="snip">${working ? "正在工作…" : "今日结论:周五前上线"}</span></span></span>-</button>`;+</button><button type="button" class="icon-btn thread-more" tabindex="-1" aria-label="更多操作"><${Icon} name="more" size="sm" /></button></div>`;+/** 分隔条的静态样例:左右两块面板,中间的空隙就是分隔条 */+const splitStage = (c) => html`<div class="gal-split mini"><div class="gal-split-a"></div><div class=${`splitter ${c}`} aria-hidden="true"></div><div class="gal-split-b"></div></div>`;const menuItem = (c, label = "机器人设置") => html`<div class="pop gal-pop-static"><ul>- <li class=${c}><span class="v">${label}</span><span class="check"><${Icon} name="check" size=${14} /></span></li></ul></div>`;+ <li class=${c}><span class="v">${label}</span><span class="check"><${Icon} name="check" size="sm" /></span></li></ul></div>`;const composer = (c) => html`<div class=${`composer ${c}`} style="width: 250px"><textarea rows="1" placeholder="发消息,/ 查看命令" tabindex="-1"></textarea>- <div class="composer-bar"><button type="button" class="plus" tabindex="-1" aria-label="更多"><${Icon} name="plus" size=${15} stroke=${1.7} /></button><span class="grow"></span>- <button type="button" class="send" tabindex="-1" aria-label="发送"><${Icon} name="up" size=${15} stroke=${2} /></button></div></div>`;+ <div class="composer-bar"><button type="button" class="plus" tabindex="-1" aria-label="更多"><${Icon} name="plus" size="md" /></button><span class="grow"></span>+ <button type="button" class="send" tabindex="-1" aria-label="发送"><${Icon} name="up" size="md" strong /></button></div></div>`;const STATE_ROWS = [{ name: "主按钮", note: ".btn.primary · 加载保持本色只是不可点;禁用退成中性灰", cells: [...basic(btn("primary", "保存")), ["加载", () => html`<${Button} variant="primary" loading>保存<//>`], ["禁用", () => html`<button type="button" class="btn primary" disabled>保存</button>`]] },@@ -310,27 +313,33 @@ const STATE_ROWS = [["禁用", () => html`<button type="button" class="pick" disabled><span class="v">自动</span><${Icon} name="chevDown" /></button>`]] },{ name: "菜单项", note: ".pop li · 悬停和键盘指着是同一个 .sel,同一时刻只有一项", cells: [["默认", () => menuItem("")], ["指着", () => menuItem("sel")], ["按下", () => menuItem("sel is-active")],["当前", () => menuItem("cur")], ["危险 · 指着", () => menuItem("danger sel", "删除")], ["禁用", () => menuItem("disabled", "不可用")]] },- { name: "侧栏行", note: ".thread · 悬停是更亮的一层玻璃,选中是浮起的玻璃片", ctx: "side", cells: [...basic((c) => thread(c)), ["选中", () => thread("sel")], ["工作中", () => thread("", { working: true })]] },+ { name: "侧栏行", note: ".thread-item > .thread + .thread-more · 悬停叠一层淡灰并亮出「更多」(时间让位),选中是浮起的白色玻璃片", ctx: "side", cells: [...basic((c) => thread(c)), ["选中", () => thread("sel")], ["工作中", () => thread("", { working: true })]] },+ { name: "分隔条", note: ".splitter · 平时看不见;指针停住 --dur-intent 后亮起细线,拖动和键盘焦点是 accent", ctx: "side", cells: [+ ["默认", () => splitStage("")], ["悬停", () => splitStage("is-hover")], ["拖动", () => splitStage("dragging")], ["键盘焦点", () => splitStage("is-focus")]] },{ name: "设置导航", note: ".nav-item", ctx: "side", cells: [...basic((c) => html`<button type="button" class=${`nav-item ${c}`} style="width: 200px"><${Icon} name="sliders" />常规</button>`),["选中", () => html`<button type="button" class="nav-item sel" style="width: 200px"><${Icon} name="sliders" />常规</button>`]] },{ name: "侧栏搜索 · 账户", note: ".side-search · .account", ctx: "side", cells: [- ["默认", () => html`<label class="side-search" style="width: 200px; margin: 0"><${Icon} name="search" /><input placeholder="搜索" tabindex="-1" /></label>`],- ["悬停", () => html`<label class="side-search is-hover" style="width: 200px; margin: 0"><${Icon} name="search" /><input placeholder="搜索" tabindex="-1" /></label>`],- ["聚焦", () => html`<label class="side-search is-focus" style="width: 200px; margin: 0"><${Icon} name="search" /><input value="日报" tabindex="-1" /></label>`],+ ["默认", () => html`<label class="side-search" style="width: 200px; margin: 0"><${Icon} name="search" size="sm" /><input placeholder="搜索" tabindex="-1" /></label>`],+ ["悬停", () => html`<label class="side-search is-hover" style="width: 200px; margin: 0"><${Icon} name="search" size="sm" /><input placeholder="搜索" tabindex="-1" /></label>`],+ ["聚焦", () => html`<label class="side-search is-focus" style="width: 200px; margin: 0"><${Icon} name="search" size="sm" /><input value="日报" tabindex="-1" /></label>`],["账户 · 悬停", () => html`<button type="button" class="account is-hover" style="width: 200px"><span class="me">R</span><span class="who">root</span><${Icon} name="gear" /></button>`],["账户 · 打开", () => html`<button type="button" class="account on" style="width: 200px"><span class="me">R</span><span class="who">root</span><${Icon} name="gear" /></button>`]] },+ { name: "余额不足提示", note: ".low-balance · 一层淡红 + 红点,字用 --fg;悬停、按下淡红加深", ctx: "side", cells: basic((c) => html`<a class=${`low-balance ${c}`} href="#states" style="width: 220px; margin: 0">余额只剩 $0.42,去充值 ↗</a>`) },+ { name: "选角色", note: ".avatar-opt · 选中比悬停深一级、名字变实,不描边", cells: [+ ...basic((c) => html`<button type="button" class=${`avatar-opt ${c}`}><${BotAvatar} char="green" size=${36} /><span class="avatar-name">${BOT_CHARS.green.name}</span></button>`),+ ["选中", () => html`<button type="button" class="avatar-opt on" aria-checked="true" role="radio"><${BotAvatar} char="blue" size=${36} /><span class="avatar-name">${BOT_CHARS.blue.name}</span></button>`]] },{ name: "发送按钮", note: ".send · 空的时候是中性灰钮,能发了才亮起品牌色;悬停时箭头上提", cells: [- ["空", () => html`<button type="button" class="send" disabled aria-label="发送"><${Icon} name="up" size=${15} stroke=${2} /></button>`],- ...basic((c) => html`<button type="button" class=${`send ${c}`} aria-label="发送"><${Icon} name="up" size=${15} stroke=${2} /></button>`),- ["停止", () => html`<button type="button" class="send stop" aria-label="停止"><${Icon} name="stop" size=${12} /></button>`]] },+ ["空", () => html`<button type="button" class="send" disabled aria-label="发送"><${Icon} name="up" size="md" strong /></button>`],+ ...basic((c) => html`<button type="button" class=${`send ${c}`} aria-label="发送"><${Icon} name="up" size="md" strong /></button>`),+ ["停止", () => html`<button type="button" class="send stop" aria-label="停止"><${Icon} name="stop" size="md" /></button>`]] },{ name: "对话输入框", note: ".composer · 输入中描边更实、投影更大;拖入文件时 accent 描边 + 一层黄绿", cells: [["默认", () => composer("")], ["悬停", () => composer("is-hover")], ["输入中", () => composer("is-focus")], ["拖入文件", () => composer("drag")]] },{ name: "输入框工具", note: ".composer .model-chip / .plus · 打开时箭头翻转、加号转成叉", cells: [...basic((c) => html`<div class="composer gal-bare"><button type="button" class=${`model-chip ${c}`}><span class="v">claude-sonnet-5-5</span><${Icon} name="chevDown" /></button></div>`),["打开", () => html`<div class="composer gal-bare"><button type="button" class="model-chip" aria-expanded="true"><span class="v">claude-sonnet-5-5</span><${Icon} name="chevDown" /></button></div>`],- ["加号 · 打开", () => html`<div class="composer gal-bare"><button type="button" class="plus" aria-expanded="true" aria-label="更多"><${Icon} name="plus" size=${15} stroke=${1.7} /></button></div>`]] },+ ["加号 · 打开", () => html`<div class="composer gal-bare"><button type="button" class="plus" aria-expanded="true" aria-label="更多"><${Icon} name="plus" size="md" /></button></div>`]] },{ name: "模板卡", note: ".tpl · 一块 --well;悬停底色深一级,选中是一层黄绿 + 黄绿图标,不描边", cells: [- ...basic((c) => html`<button type="button" class=${`tpl ${c}`} style="width: 190px"><span class="tpl-ic"><${Icon} name="chat" size=${17} /></span><span class="tpl-name">群聊日报</span><span class="tpl-desc">每天整理群消息</span></button>`),- ["选中", () => html`<button type="button" class="tpl on" style="width: 190px"><span class="tpl-ic"><${Icon} name="chat" size=${17} /></span><span class="tpl-name">群聊日报</span><span class="tpl-desc">每天整理群消息</span></button>`]] },+ ...basic((c) => html`<button type="button" class=${`tpl ${c}`} style="width: 190px"><span class="tpl-ic"><${Icon} name="chat" size="lg" /></span><span class="tpl-name">群聊日报</span><span class="tpl-desc">每天整理群消息</span></button>`),+ ["选中", () => html`<button type="button" class="tpl on" style="width: 190px"><span class="tpl-ic"><${Icon} name="chat" size="lg" /></span><span class="tpl-name">群聊日报</span><span class="tpl-desc">每天整理群消息</span></button>`]] },{ name: "建议胶囊", note: ".chip", cells: basic((c) => html`<button type="button" class=${`chip ${c}`}>你能帮我做什么?</button>`) },{ name: "问题选项", note: ".card .opt", cells: [...basic((c) => html`<div class="card gal-bare-card"><button type="button" class=${`opt ${c}`}><span class="letter">A</span><span>国内线路<span class="desc">延迟低</span></span></button></div>`),@@ -370,7 +379,7 @@ function Gallery() {const nav = [["原则", [["principles", "分层与约定"]]],["Token", [["color", "颜色"], ["material", "材质"], ["type", "文字"], ["space", "间距与尺寸"], ["elevation", "投影与层级"], ["motion", "动效"]]],- ["组件", [["states", "状态矩阵"], ["buttons", "按钮"], ["inputs", "输入"], ["menus", "菜单与分段"], ["status", "状态与反馈"], ["lists", "列表行"], ["overlays", "对话框与提示"], ["avatars", "头像"]]],+ ["组件", [["states", "状态矩阵"], ["icons", "图标"], ["buttons", "按钮"], ["inputs", "输入"], ["menus", "菜单与分段"], ["status", "状态与反馈"], ["lists", "列表行"], ["splitter", "分隔条"], ["overlays", "对话框与提示"], ["avatars", "头像"]]],["页面模式", [["patterns", "对话"], ["custom", "定制"]]],];return html`<${Compare.Provider} value=${compare}><div class="gal">@@ -461,10 +470,11 @@ function Gallery() {<${Demo} code=${`<div class="anim-rise-in">…</div> /* 可用 --anim-dur / --anim-ease / --anim-delay 微调 */.toast { --rise: 6px; animation: rise-in var(--dur-base) var(--ease-out); } /* 组件里直接用关键帧 + token */const { mounted, leaving } = usePresence(open); /* design/motion.js:退场动画播完再卸载 */`}>- ${() => html`${[["anim-fade-in", "fade-in"], ["anim-rise-in", "rise-in"], ["anim-slide-in", "slide-in"], ["anim-pop-in", "pop-in"], ["anim-sink-out", "sink-out"], ["anim-pop-out", "pop-out"], ["anim-bump", "bump"], ["anim-flash", "flash"]].map(([c, l]) => html`<${Replay} cls=${c} label=${l} />`)}+ ${() => html`${[["anim-fade-in", "fade-in"], ["anim-rise-in", "rise-in"], ["anim-slide-in", "slide-in"], ["anim-pop-in", "pop-in"], ["anim-scale-in", "scale-in"], ["anim-sink-out", "sink-out"], ["anim-pop-out", "pop-out"], ["anim-bump", "bump"], ["anim-flash", "flash"]].map(([c, l]) => html`<${Replay} cls=${c} label=${l} />`)}<div class="gal-anim"><${Spinner} /><span class="t-meta">spin</span></div><div class="gal-anim"><span class="typing"><i></i><i></i><i></i></span><span class="t-meta">breathe(stagger)</span></div>- <div class="gal-anim"><span><span class="caret"></span></span><span class="t-meta">blink</span></div>`}+ <div class="gal-anim"><span><span class="caret"></span></span><span class="t-meta">blink</span></div>+ <div class="gal-anim"><span class="shimmer">思考中 12 秒</span><span class="t-meta">sheen(文字微光)</span></div>`}<//></div><//>@@ -473,6 +483,17 @@ const { mounted, leaving } = usePresence(open); /* design/motion.js:退场${STATE_ROWS.map((r) => html`<${StateRow} key=${r.name} ...${r} />`)}<//>+ <${Section} id="icons" title="图标" lead="16 格画布的线性图标,五档尺寸 xs 12 · sm 14 · md 16 · lg 20 · xl 24;线宽按显示像素算(--ic-stroke 1.25px),任何尺寸都一样细,实心面上的图标用 strong(1.6px)。默认 sm,顶栏、侧栏和对话输入框用 md。">+ <${Demo} title="全部图标" note="sm · 14px" code=${`<${"${Icon}"} name="gear" size="sm" /> /* 尺寸只用 xs / sm / md / lg / xl */+.pick .ic { --ic-size: var(--ic-xs); } /* 上下文改尺寸只改 --ic-size,线宽自动跟着换算 */`}>+ ${() => ICONS.map((n) => html`<span class="gal-icon" key=${n} title=${n}><${Icon} name=${n} size="sm" /><span class="t-meta">${n}</span></span>`)}+ <//>+ <${Demo} title="五档尺寸" note="同一个图标放大缩小,线宽不变">+ ${() => html`${["xs", "sm", "md", "lg", "xl"].map((s) => html`<span class="gal-icon" key=${s}><span class="cluster" style="--gap: var(--space-2)"><${Icon} name="gear" size=${s} /><${Icon} name="chat" size=${s} /><${Icon} name="search" size=${s} /></span><span class="t-meta">${s}</span></span>`)}+ <span class="gal-icon"><button type="button" class="send" tabindex="-1" aria-label="发送"><${Icon} name="up" size="md" strong /></button><span class="t-meta">md strong</span></span>`}+ <//>+ <//>+<${Section} id="buttons" title="按钮" lead="变体 primary / 默认 / ghost / danger,尺寸 sm / 默认 / lg。图标按钮必须有 label。"><${Demo} title=".btn" code=${`<button class="btn primary lg block">连接</button><${"${Button}"} variant="primary" size="lg" loading=\${busy} icon="plus">新建<//>`}>@@ -481,7 +502,7 @@ const { mounted, leaving } = usePresence(open); /* design/motion.js:退场<${Button} icon="plus">带图标<//><${Button} variant="primary" loading>保存中<//><${Button} disabled>禁用<//>`}<//><${Demo} title=".icon-btn · .text · CopyButton">- ${() => html`<${IconButton} icon="gear" label="设置" /><${IconButton} icon="refresh" label="刷新" on /><${IconButton} icon="close" label="关闭" size="xs" iconSize=${12} />+ ${() => html`<${IconButton} icon="gear" label="设置" /><${IconButton} icon="refresh" label="刷新" on /><${IconButton} icon="close" label="关闭" size="xs" iconSize="xs" /><${CopyButton} text="复制的内容" /><button type="button" class="text">文字按钮</button><button type="button" class="text accent">强调</button><button type="button" class="text danger">危险</button>`}<//><//>@@ -529,6 +550,17 @@ const { mounted, leaving } = usePresence(open); /* design/motion.js:退场<//><//>+ <${Section} id="splitter" title="分隔条" lead="两块面板之间的空隙可以拖:侧栏和主区、主区和信息面板。平时看不见,只有指针变成 ↔;停住一会儿空隙中间长出一道细线;拖到离默认宽度 6px 以内会吸附回去,到头了指针换成单向箭头;双击恢复默认。键盘:聚焦后 ← → 调整(Shift 大步)、Home / End 最窄 / 最宽、Enter 恢复默认。宽度存在本机偏好里。">+ <${Demo} flush title="Splitter" note="拖动中间的空隙试试(这里的宽度不保存)" code=${`<${"${Splitter}"} class="split-side" size="--side-w" label="调整侧栏宽度" value=\${sideW}+ room=\${() => innerWidth - 另一侧那一列 - mainMin} onCommit=\${(px) => setPrefs({ sideW: px })} /> /* px = 0:回到默认 */+.app { --side-col: clamp(var(--side-w-min), var(--side-w-user, var(--side-w)), min(var(--side-w-max), var(--side-w-cap))); }+.app > .split-side { --split-x: calc(var(--side-col) - var(--pane-gap) / 2); } /* 分隔条在空隙正中 */`}>+ ${() => html`<div class="gal-split"><div class="gal-split-a"><span class="t-meta">侧栏</span></div>+ <${Splitter} size="--gal-split-w" label="调整示例侧栏宽度" />+ <div class="gal-split-b"><span class="t-meta">主区 · 双击空隙恢复默认宽度</span></div></div>`}+ <//>+ <//>+<${Section} id="overlays" title="对话框与提示" lead="确认框默认聚焦「取消」;危险操作用 danger。对话框退场有动画(usePresence)。"><${Demo} title="confirmSheet · toast">${() => html`<${Button} onClick=${() => confirmSheet({ title: "保存这些更改?", body: "改动会立即生效。" }).then((ok) => ok && saved())}>普通确认<//>@@ -552,15 +584,16 @@ const { mounted, leaving } = usePresence(open); /* design/motion.js:退场<div class="msg-actions"><${CopyButton} text=${MD} /><span class="when num">09:26</span></div></div><div class="msg-row user"><div class="msg">再整理成日报</div></div><div class="msg-row assistant"><div class="work-line live"><span class="shimmer">思考中 12 秒</span></div></div>+ <div class="msg-row assistant live"><div class="work-line live"><span class="shimmer">正在回复 4 秒</span></div><div class="msg"><${Markdown} text="好的,先按群把今天的消息分组,再挑出要你处理的" /></div></div><div class="msg-row assistant"><div class="card"><div class="q-block"><div class="q">要用哪条线路?</div><div class="opts"><button type="button" class="opt picked"><span class="letter">A</span><span>国内线路<span class="desc">延迟低</span></span></button><button type="button" class="opt"><span class="letter">B</span><span>海外线路<span class="desc">模型更全</span></span></button></div></div></div></div>- <div class="msg-row assistant"><div class="file-card"><${Icon} name="file" size=${32} stroke=${1.2} /><div class="grow"><div class="fname">report.pdf</div><div class="fsub">已交付到机器人工作区</div></div></div></div>+ <div class="msg-row assistant"><div class="file-card"><${Icon} name="file" size="xl" /><div class="grow"><div class="fname">report.pdf</div><div class="fsub">已交付到机器人工作区</div></div></div></div></div><div class="composer"><textarea rows="1" placeholder="给「我的助手」发消息,/ 查看命令"></textarea>- <div class="composer-bar"><button type="button" class="plus" aria-label="更多"><${Icon} name="plus" size=${15} stroke=${1.7} /></button><span class="grow"></span>+ <div class="composer-bar"><button type="button" class="plus" aria-label="更多"><${Icon} name="plus" size="md" /></button><span class="grow"></span><button type="button" class="model-chip"><span class="v">claude-sonnet-5-5</span><${Icon} name="chevDown" /></button>- <button type="button" class="send" aria-label="发送"><${Icon} name="up" size=${15} stroke=${2} /></button></div></div>+ <button type="button" class="send" aria-label="发送"><${Icon} name="up" size="md" strong /></button></div></div><div class="chips"><button type="button" class="chip">总结今天的消息</button><button type="button" class="chip">写一封邮件</button></div>`}<//><//>diff --git a/ui/design/index.css b/ui/design/index.cssindex 0a63d84..de65892 100644--- a/ui/design/index.css+++ b/ui/design/index.css@@ -11,6 +11,7 @@@import url("base/reset.css") layer(base);@import url("base/motion.css") layer(base);+@import url("components/icon.css") layer(components);@import url("components/glass.css") layer(components);@import url("components/button.css") layer(components);@import url("components/field.css") layer(components);@@ -21,6 +22,7 @@@import url("components/popover.css") layer(components);@import url("components/model-family.css") layer(components);@import url("components/sheet.css") layer(components);+@import url("components/splitter.css") layer(components);@import url("components/toast.css") layer(components);@import url("components/notice.css") layer(components);@import url("components/feedback.css") layer(components);diff --git a/ui/design/motion.js b/ui/design/motion.jsindex 7edea87..f9a4e5a 100644--- a/ui/design/motion.js+++ b/ui/design/motion.js@@ -1,10 +1,14 @@-// 动效的 JS 一侧:读取 CSS 时长 token、尊重"减少动态效果"、让退场动画播完再卸载。+// 动效的 JS 一侧:读取 CSS 时长 token、尊重"减少 / 关闭动画"、让退场动画播完再卸载。// 时长只在 tokens/motion.css 里定义一次,JS 用 ms("--dur-base") 读,不要再写死毫秒数。import { useEffect, useState } from "preact/hooks";const mq = window.matchMedia("(prefers-reduced-motion: reduce)");-export const reducedMotion = () => mq.matches;+/** 减少或关闭了动画:<html data-motion>(lib/prefs.js 解析设置 › 外观 › 动画)不是 full;没有这个属性时看系统 */+export const reducedMotion = () => {+ const m = document.documentElement.dataset.motion;+ return m ? m !== "full" : mq.matches;+};/** "--dur-base" → 180;token 不存在或不是时长时返回 fallback */export function ms(token, fallback = 0) {diff --git a/ui/design/tokens/motion.css b/ui/design/tokens/motion.cssindex ff8996b..b793353 100644--- a/ui/design/tokens/motion.css+++ b/ui/design/tokens/motion.css@@ -3,7 +3,7 @@弹出层与对话框的弹性入场用 slow/slower + spring。- 入场用 ease-out(或 spring),退场用 ease-in,循环用 ease-in-out 或 linear。- 位移量也是 token(--rise / --slide / --pop-*),组件可以局部覆盖;关键帧把它们乘以 --motion,- 减少动态效果时 --motion = 0,所有入场自动退化成纯淡入。 */+ 减少动态效果时 --motion = 0,所有入场自动退化成纯淡入;关闭动画时连淡入也没有(见文末 data-motion)。 */:root {--dur-fast: 120ms;--dur-base: 180ms;@@ -26,10 +26,12 @@--dur-spin: 800ms;--dur-blink: 1s;--dur-shimmer: 1.2s;+ --dur-sheen: 2.4s; /* 文字微光(思考中 / 正在回复):扫过一遍后停一拍,比骨架慢,不抢正文的注意力 */--dur-pulse: 1.4s;--dur-flash: 1.2s;--dur-ambient: 1.2s; /* 环境光换色(切换机器人时) */--stagger: 150ms;+ --dur-intent: 240ms; /* 悬停意图:指针停这么久才亮起提示(分隔条的细线),只是划过去不闪 */--dur-off: .01ms; /* 减少动态效果时代替 0:时长为 0 的过渡不触发 transitionend *//* 机器人头像的一次性反应(avatar.js 用 ms() 读,播完回到持续状态) */@@ -46,14 +48,26 @@--slide: 12px;--pop-dy: -6px;--pop-scale: .94;+ --scale-from: .6; /* scale-in 的起点:发送钮里换图标、小圆点出现 */--press: .96;--press-strong: .94;}-@media (prefers-reduced-motion: reduce) {- :root {- --motion: 0;- --press: 1;- --press-strong: 1;- --dur-spin: 1.6s;- }+/* 动画偏好:<html data-motion> 由 lib/prefs.js 解析(设置 › 外观 › 动画;跟随系统时看 prefers-reduced-motion)。+ reduce:位移归零,入场只剩淡入,按下不缩放,过渡几乎瞬时(base/motion.css)。+ off:在 reduce 之上,出现 / 消失 / 视图切换也瞬时完成;只留表示"正在进行"的循环(转圈、骨架、光标)和定位闪烁。 */+:root:is([data-motion="reduce"], [data-motion="off"]) {+ --motion: 0;+ --press: 1;+ --press-strong: 1;+ --dur-spin: 1.6s;+}+:root[data-motion="off"] {+ --dur-fast: var(--dur-off);+ --dur-base: var(--dur-off);+ --dur-moderate: var(--dur-off);+ --dur-slow: var(--dur-off);+ --dur-slower: var(--dur-off);+ --dur-ambient: var(--dur-off);+ --dur-intent: 0ms;+ --stagger: 0ms;}diff --git a/ui/design/tokens/primitives.css b/ui/design/tokens/primitives.cssindex d3b850e..3ea758f 100644--- a/ui/design/tokens/primitives.css+++ b/ui/design/tokens/primitives.css@@ -69,16 +69,16 @@--space-12: 48px;--space-16: 64px;- /* —— 字号:8 级。桌面应用的密度,小号保留半像素 —— */- --fs-2xs: 11px; /* 分组标题、徽标、快捷键 */- --fs-xs: 11.5px; /* 次要说明、元信息、等宽值 */- --fs-sm: 12.5px; /* 控件:按钮、菜单项、分段、输入框 */- --fs-md: 13px; /* 界面正文 */- --fs-lg: 14px; /* 列表标题、面板标题 */- --fs-xl: 15px; /* 对话正文、对话框标题 */- --fs-2xl: 17px; /* 空状态标题 */- --fs-3xl: 20px; /* 引导页标题 */- --fs-4xl: 24px; /* 页面大标题(设置、机器人设置) */+ /* —— 字号:9 级。桌面应用的密度,小号保留半像素;都乘以 --fs-scale(设置 › 外观 › 字体大小,见 semantic.css「用户偏好」) —— */+ --fs-2xs: calc(11px * var(--fs-scale)); /* 分组标题、徽标、快捷键 */+ --fs-xs: calc(11.5px * var(--fs-scale)); /* 次要说明、元信息、等宽值 */+ --fs-sm: calc(12.5px * var(--fs-scale)); /* 控件:按钮、菜单项、分段、输入框 */+ --fs-md: calc(13px * var(--fs-scale)); /* 界面正文 */+ --fs-lg: calc(14px * var(--fs-scale)); /* 列表标题、面板标题 */+ --fs-xl: calc(15px * var(--fs-scale)); /* 对话正文、对话框标题 */+ --fs-2xl: calc(17px * var(--fs-scale)); /* 空状态标题 */+ --fs-3xl: calc(20px * var(--fs-scale)); /* 引导页标题 */+ --fs-4xl: calc(22px * var(--fs-scale)); /* 页面大标题(设置、机器人设置、新建页):比引导页标题大一档就够,不压过内容 *//* —— 字重、行高、字距 —— */--fw-regular: 400;@@ -89,9 +89,10 @@--lh-snug: 1.4;--lh-normal: 1.5;--lh-relaxed: 1.55;+ --lh-prose: 1.7; /* 机器人回复的正文:整列长文,中文要多一点行距才不累 */- --tracking-tighter: -.02em;- --tracking-tight: -.01em; /* 只收紧大字;不给小标签加字距,也不用全大写 */+ --tracking-tighter: -.015em; /* 大标题。中文字形本来就排得满,收得太紧会挤在一起 */+ --tracking-tight: -.01em; /* 只收紧大字;不给小标签加字距,也不用全大写 *//* —— 圆角:嵌套时内层 = 外层 − 内边距(.seg 8 → thumb 6) —— */--r-xs: 4px;@@ -111,6 +112,16 @@--ctl-xl: 36px;--ctl-2xl: 44px;+ /* —— 图标:五档尺寸(无单位的 px,components/icon.css 换算成宽高和线宽)。+ 线宽是显示出来的像素,和尺寸无关:12px 的箭头和 24px 的文件图标线一样细 —— */+ --ic-xs: 12; /* 下拉箭头、小按钮里的关闭、实心圆点里的勾 */+ --ic-sm: 14; /* 默认:按钮、菜单、输入框尾部、行内操作 */+ --ic-md: 16; /* 顶栏与工具栏按钮、侧栏导航、对话输入框、命令面板搜索 */+ --ic-lg: 20; /* 模板卡 */+ --ic-xl: 24; /* 文件卡片 */+ --ic-stroke: 1.25; /* 常规线宽 */+ --ic-stroke-strong: 1.6; /* 实心面上的图标:发送钮的箭头、完成圆点里的勾 */+/* —— 层级:同一窗格内的浮动件 < 抽屉 < 弹出层 < 模态 < 命令面板 < 提示 —— */--z-raised: 1;--z-float: 5;@@ -120,6 +131,9 @@--z-palette: 56;--z-toast: 60;+ /* —— 细线:一个物理像素。高分屏 .5px,普通屏 1px(.5px 在 1x 屏上会被抗锯齿成半透明的虚影甚至消失) —— */+ --hairline: 1px;+/* —— 透明度 —— */--o-disabled: .45;@@ -132,12 +146,27 @@--glass-filter-lg: blur(var(--blur-lg)) saturate(var(--glass-sat));--glass-filter-sm: blur(var(--blur-sm)) saturate(var(--glass-sat));- /* —— 版式宽度 —— */- --side-w: 280px;- --panel-w: 320px;- --col-w: 760px; /* 对话阅读列:参考 Codex,回复是整列宽的正文 */+ /* —— 版式宽度:侧栏、信息面板可以拖分隔条调宽(README「分隔条」) —— */+ /* 拖过的宽度是 <html> 上内联的 --side-w-user / --panel-w-user;shell.css 用 clamp(-min, var(-user, 默认), min(-max, -cap)) 取值 */+ --side-w: 280px; /* 侧栏默认宽度(窗口窄于 900px 时 240) */+ --side-w-min: 220px; /* 再窄机器人名称就只剩两三个字 */+ --side-w-max: 400px;+ --side-w-cap: 36vw; /* 窗口变窄时侧栏最多占这么宽,拖宽过的侧栏不会把主区挤没 */+ --panel-w: 320px; /* 信息面板默认宽度(含它右边的 --pane-gap) */+ --panel-w-min: 280px;+ --panel-w-max: 440px;+ --panel-w-cap: 34vw;+ --main-w-min: 420px; /* 拖宽侧栏或信息面板时,主区至少留这么宽 */+ --col-w: 760px; /* 对话阅读列:参考 Codex,回复是整列宽的正文 */--bubble-w: 600px; /* 用户气泡最大宽度 */+ --col-w-wide: 960px; /* 设置 › 外观 › 对话宽度「宽」 */+ --bubble-w-wide: 760px; /* 对话列加宽(宽 / 铺满)时用户气泡的最大宽度 */--head-h: 52px; /* 对话顶栏、信息面板顶栏 */--page-w: 680px; /* 设置页、机器人设置的内容列 */--titlebar-inset: 84px; /* macOS 桌面版:侧栏顶部给红绿灯让出的宽度 */+ --caption-w-fallback: 138px; /* Windows 桌面版:右上角最小化 / 最大化 / 关闭(3 × 46)的宽度,拿不到 env(titlebar-area-*) 时用 */+ --brand-mark: 20px; /* Windows 桌面版:侧栏左上角的应用图标 */+}+@media (min-resolution: 2dppx) {+ :root { --hairline: .5px; }}diff --git a/ui/design/tokens/semantic.css b/ui/design/tokens/semantic.cssindex 459d888..93f0a25 100644--- a/ui/design/tokens/semantic.css+++ b/ui/design/tokens/semantic.css@@ -45,9 +45,11 @@--pill-press: rgba(0, 0, 0, .1);--seg-track: rgba(0, 0, 0, .055);--seg-thumb-bg: var(--white);- --side-hover: rgba(255, 255, 255, .55); /* 侧栏行:悬停是更亮的一层玻璃 */- --side-press: rgba(255, 255, 255, .36);- --side-active: rgba(255, 255, 255, .9); /* 选中:浮起的白色玻璃片 */+ --side-hover: rgba(0, 0, 0, .042); /* 侧栏行:悬停叠一层淡灰(侧栏本来就接近白色,再亮一层几乎看不出来) */+ --side-press: rgba(0, 0, 0, .07);+ --side-active: rgba(255, 255, 255, .92); /* 选中:浮起的白色玻璃片。悬停暗一点、选中亮一点,一眼分得开 */+ --side-solid: #f4f4f2; /* 侧栏的近似实色:压在侧栏头像上的状态点要挖一圈和底一样的缺口 */+ --side-solid-on: #fefefe; /* 选中的行上的近似实色 */--bubble-user: rgba(0, 0, 0, .05); /* 用户消息气泡;机器人回复不加气泡 */--bubble-ai: rgba(0, 0, 0, .035); /* 信息面板里的会话记录等次要气泡 */--qr-bg: var(--white); /* 二维码在任何主题下都要白底 */@@ -59,6 +61,7 @@/* —— 线 —— */--line: rgba(0, 0, 0, .1); /* 表格表头的下沿、正文里的分隔线 hr */--line-2: rgba(0, 0, 0, .06); /* 行与行之间的细线:列表行、表格行、菜单里的分隔 */+ --split-line: rgba(0, 0, 0, .2); /* 分隔条:指针停住时空隙中间亮起的细线(拖动、键盘焦点时换成 --accent) */--ctl-edge: rgba(0, 0, 0, .44); /* 文字输入框的边:对主区、信息面板、对话框和 --well 都 ≥ 3:1(3.2:1) */--ctl-edge-hover: rgba(0, 0, 0, .6);@@ -109,24 +112,21 @@--shadow-sm: 0 1px 2px rgba(0, 0, 0, .05), 0 3px 10px rgba(0, 0, 0, .05);--shadow-md: 0 2px 6px rgba(0, 0, 0, .05), 0 10px 28px rgba(0, 0, 0, .09);--shadow-lg: 0 4px 12px rgba(0, 0, 0, .06), 0 24px 60px rgba(0, 0, 0, .16);- --shadow-pane: 0 0 0 .5px rgba(0, 0, 0, .1), 0 1px 3px rgba(0, 0, 0, .04), 0 8px 30px rgba(0, 0, 0, .04);- --shadow-tile: 0 1px 2px rgba(0, 0, 0, .07); /* 侧栏选中项:浮起的玻璃片(只有投影,不描边) */+ --shadow-pane: 0 0 0 var(--hairline) rgba(0, 0, 0, .1), 0 1px 3px rgba(0, 0, 0, .04), 0 8px 30px rgba(0, 0, 0, .04);+ --shadow-tile: 0 1px 2px rgba(0, 0, 0, .06), 0 2px 6px rgba(0, 0, 0, .035); /* 侧栏选中项:浮起的玻璃片(只有投影,不描边) */--seg-edge: 0 1px 2px rgba(0, 0, 0, .14); /* 分段 thumb、开关圆钮:只有投影,不描边 *//* —— 机器人头像:角色颜色在 primitives 的 --bot-*,这里只给随主题变的光晕和影子 —— */--avatar-aura: 30%; /* 工作中头像背后的辉光(角色辉光色的混合比例) */--avatar-shadow: rgba(0, 0, 0, .16); /* 大头像脚下的影子 */- /* —— 字体 —— */- --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;}/* 由其他语义 token 推导的值:每个主题作用域都要重新计算,否则子树会继承外层主题算好的结果 */:root, [data-theme] {--code-bg: color-mix(in srgb, var(--fg) 7%, transparent);--ring: 0 0 0 3px var(--accent-soft); /* 焦点光晕,配合 accent 色描边 */--ring-danger: 0 0 0 3px color-mix(in srgb, var(--red) 18%, transparent);- --glass-ring: inset 0 1px 0 var(--glass-hi), 0 0 0 .5px var(--glass-edge); /* 玻璃的边:顶边高光 + 细描边 */+ --glass-ring: inset 0 1px 0 var(--glass-hi), 0 0 0 var(--hairline) var(--glass-edge); /* 玻璃的边:顶边高光 + 细描边 */--shadow-float: var(--glass-ring), var(--shadow-md); /* 浮在内容上的玻璃:输入框、回到底部、提示 */--shadow-pop: var(--glass-ring), var(--shadow-lg); /* 菜单、命令面板、对话框 */}@@ -169,11 +169,41 @@--r-pane: var(--r-2xl); /* 浮起的面板与浮层:主区、信息面板、对话框、命令面板、引导页卡片 */--r-bubble: var(--r-3xl); /* 消息气泡:对话里的用户消息、会话记录里的双方消息 */}+/* 字体:与主题无关。--font-system / --code-system 是各平台的系统字体;页面和组件只用 --font / --code,+ 它们默认就是系统字体,设置 › 外观可以换成衬线或自定义字体(见下文「用户偏好」)。 */+:root {+ --font-system: -apple-system, BlinkMacSystemFont, "SF Pro Text", "PingFang SC", "Segoe UI", "Microsoft YaHei UI", system-ui, sans-serif;+ --code-system: ui-monospace, "SF Mono", Menlo, Consolas, "Microsoft YaHei UI", monospace;+ --font-serif: ui-serif, "New York", Georgia, "Songti SC", "STSong", "Noto Serif CJK SC", "Source Han Serif SC", "Noto Serif SC", "SimSun", serif;+ --font: var(--font-system);+ --code: var(--code-system);+}: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;+ --font-system: "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif;+ --code-system: "Cascadia Mono", Consolas, "Microsoft YaHei UI", "Microsoft YaHei", monospace;}+/* 用户偏好(设置 › 外观):lib/prefs.js 把偏好解析成 <html> 上的 data-* 属性(首帧前 index.html 先套一遍),+ 这里只把属性翻译成 token,页面和组件不认这些属性。都只挂在 :root 上,和主题作用域无关。+ data-text sm | md | lg | xl 字体大小:--fs-* 都乘以 --fs-scale;控件高度、图标和间距不变+ data-font system | serif | custom 界面字体;custom 时 prefs.js 在 <html> 上内联 --font(自定义字体 + 系统字体兜底),+ 自定义代码字体同样内联 --code+ data-width normal | wide | full 对话宽度(--col-w)+ data-code-wrap on | off 代码块自动换行(--code-wrap)+ data-glass on | off 毛玻璃;off 时材质换成实色(见下一段)+ data-motion full | reduce | off 动画(tokens/motion.css) */+:root {+ --fs-scale: 1;+ --code-wrap: pre; /* 代码块的 white-space */+}+:root[data-text="sm"] { --fs-scale: .92; }+:root[data-text="lg"] { --fs-scale: 1.1; }+:root[data-text="xl"] { --fs-scale: 1.2; }+:root[data-font="serif"] { --font: var(--font-serif); }+:root[data-width="wide"] { --col-w: var(--col-w-wide); --bubble-w: var(--bubble-w-wide); }+:root[data-width="full"] { --col-w: 100%; --bubble-w: var(--bubble-w-wide); } /* 对话列铺满,两侧仍留 --page-gutter */+:root[data-code-wrap="on"] { --code-wrap: pre-wrap; }+[data-theme="dark"] {color-scheme: dark;@@ -183,7 +213,7 @@--aura-c: .1;--aura-a: .55;- --surface: rgba(20, 20, 20, .84);+ --surface: rgba(23, 23, 23, .86); /* 比侧栏亮一档:深色下面板要浮得出来 */--surface-solid: #151515;--glass-side: rgba(16, 16, 16, .4);--glass-chrome: rgba(22, 22, 22, .7);@@ -204,9 +234,11 @@--pill-press: rgba(255, 255, 255, .125);--seg-track: rgba(255, 255, 255, .05);--seg-thumb-bg: rgba(255, 255, 255, .14);- --side-hover: rgba(255, 255, 255, .045);- --side-press: rgba(255, 255, 255, .03);- --side-active: rgba(255, 255, 255, .085);+ --side-hover: rgba(255, 255, 255, .05);+ --side-press: rgba(255, 255, 255, .035);+ --side-active: rgba(255, 255, 255, .09);+ --side-solid: #121212;+ --side-solid-on: #232323;--bubble-user: rgba(255, 255, 255, .075);--bubble-ai: rgba(255, 255, 255, .05);--scrim: rgba(0, 0, 0, .48);@@ -216,6 +248,7 @@--line: rgba(255, 255, 255, .1);--line-2: rgba(255, 255, 255, .065);+ --split-line: rgba(255, 255, 255, .22);--ctl-edge: rgba(255, 255, 255, .36); /* 3.2:1 */--ctl-edge-hover: rgba(255, 255, 255, .5);@@ -260,32 +293,37 @@--shadow-sm: 0 1px 2px rgba(0, 0, 0, .3), 0 3px 10px rgba(0, 0, 0, .25);--shadow-md: 0 2px 8px rgba(0, 0, 0, .3), 0 12px 32px rgba(0, 0, 0, .42);--shadow-lg: 0 4px 14px rgba(0, 0, 0, .35), 0 28px 70px rgba(0, 0, 0, .6);- --shadow-pane: 0 0 0 .5px rgba(255, 255, 255, .08), 0 8px 30px rgba(0, 0, 0, .35);+ --shadow-pane: 0 0 0 var(--hairline) rgba(255, 255, 255, .08), 0 8px 30px rgba(0, 0, 0, .35);--shadow-tile: inset 0 1px 0 rgba(255, 255, 255, .05), 0 1px 2px rgba(0, 0, 0, .3);- --seg-edge: inset 0 .5px 0 rgba(255, 255, 255, .1), 0 1px 2px rgba(0, 0, 0, .3);+ --seg-edge: inset 0 var(--hairline) 0 rgba(255, 255, 255, .1), 0 1px 2px rgba(0, 0, 0, .3);--avatar-aura: 52%;--avatar-shadow: rgba(0, 0, 0, .5);}-/* 系统设置了"降低透明度":玻璃换成接近实色的材质,层次靠描边和投影 */-@media (prefers-reduced-transparency: reduce) {- [data-theme="light"] {- --surface: #fbfbfb;- --glass-side: #f2f2f1;- --glass-chrome: #fbfbfb;- --glass-float: #ffffff;- --glass-panel: #f8f8f8;- --glass-pop: #fcfcfc;- --glass-sheet: #ffffff;- }- [data-theme="dark"] {- --surface: #161616;- --glass-side: #121212;- --glass-chrome: #161616;- --glass-float: #262626;- --glass-panel: #1a1a1a;- --glass-pop: #242424;- --glass-sheet: #1e1e1e;- }+/* 关掉毛玻璃(data-glass="off":设置 › 外观 › 毛玻璃效果,跟随系统时看"降低透明度" prefers-reduced-transparency):+ 玻璃换成接近实色的材质、不再模糊背景,层次靠描边和投影。局部主题作用域也要跟着换,所以两种写法都要 */+:root[data-glass="off"] {+ --glass-filter: none;+ --glass-filter-lg: none;+ --glass-filter-sm: none;+}+:root[data-glass="off"][data-theme="light"], :root[data-glass="off"] [data-theme="light"] {+ --surface: #fbfbfb;+ --glass-side: #f2f2f1;+ --side-solid: #f2f2f1;+ --glass-chrome: #fbfbfb;+ --glass-float: #ffffff;+ --glass-panel: #f8f8f8;+ --glass-pop: #fcfcfc;+ --glass-sheet: #ffffff;+}+:root[data-glass="off"][data-theme="dark"], :root[data-glass="off"] [data-theme="dark"] {+ --surface: #161616;+ --glass-side: #121212;+ --glass-chrome: #161616;+ --glass-float: #262626;+ --glass-panel: #1a1a1a;+ --glass-pop: #242424;+ --glass-sheet: #1e1e1e;}diff --git a/ui/index.html b/ui/index.htmlindex ed036ec..8269e4d 100644--- a/ui/index.html+++ b/ui/index.html@@ -8,15 +8,43 @@<link rel="icon" href="/amb/static/assets/favicon-64.png" sizes="64x64" type="image/png" /><link rel="apple-touch-icon" href="/amb/static/assets/apple-touch-icon.png" /><script>- // 首帧前解析主题(data-theme 总是 light/dark,CSS 只定义一份深色变量)与平台+ // 首帧前解析主题(data-theme 总是 light/dark,CSS 只定义一份深色变量)、界面语言、外观偏好与平台。+ // 外观偏好的解析规则和 lib/prefs.js 的 apply() 一致,语言的和 lib/i18n.js 一致,改一处要两处一起改。(function () {var root = document.documentElement;+ var mq = function (q) { return window.matchMedia(q).matches; };var m = "system";try { m = localStorage.getItem("amb-theme") || "system"; } catch (_) {}- var dark = m === "dark" || (m !== "light" && window.matchMedia("(prefers-color-scheme: dark)").matches);+ var dark = m === "dark" || (m !== "light" && mq("(prefers-color-scheme: dark)"));root.setAttribute("data-theme", dark ? "dark" : "light");+ // 语言:本机缓存的偏好(服务端配置为准,启动后 App 再校正),没有时按浏览器首选语言;不支持的语言用英文+ var norm = function (s) { s = String(s || "").toLowerCase(); return s.indexOf("zh") === 0 ? "zh-CN" : s.indexOf("en") === 0 ? "en" : ""; };+ var lang = "";+ try { lang = norm(localStorage.getItem("amb-lang")); } catch (_) {}+ if (!lang) { var ls = navigator.languages && navigator.languages.length ? navigator.languages : [navigator.language]; for (var i = 0; i < ls.length && !lang; i++) lang = norm(ls[i]); }+ root.setAttribute("lang", lang || "en");+ var p = {};+ try { p = JSON.parse(localStorage.getItem("amb-prefs") || "{}") || {}; } catch (_) {}+ var stack = function (s) {+ return String(s || "").replace(/["'\\;{}<>]/g, "").split(",").map(function (x) { return x.trim(); })+ .filter(Boolean).map(function (x) { return '"' + x + '"'; }).join(", ");+ };+ var font = p.font === "custom" ? stack(p.fontName) : "";+ var code = stack(p.codeFont);+ root.setAttribute("data-text", /^(sm|lg|xl)$/.test(p.text) ? p.text : "md");+ root.setAttribute("data-font", font ? "custom" : p.font === "serif" ? "serif" : "system");+ if (font) root.style.setProperty("--font", font + ", var(--font-system)");+ if (code) root.style.setProperty("--code", code + ", var(--code-system)");+ root.setAttribute("data-width", /^(wide|full)$/.test(p.width) ? p.width : "normal");+ root.setAttribute("data-code-wrap", p.codeWrap === true ? "on" : "off");+ root.setAttribute("data-motion", p.motion === "off" ? "off" : p.motion === "on" ? "full" : mq("(prefers-reduced-motion: reduce)") ? "reduce" : "full");+ root.setAttribute("data-glass", p.glass === "on" || p.glass === "off" ? p.glass : mq("(prefers-reduced-transparency: reduce)") ? "off" : "on");+ var px = function (v) { return typeof v === "number" && v >= 120 && v <= 1200 ? Math.round(v) + "px" : ""; };+ if (px(p.sideW)) root.style.setProperty("--side-w-user", px(p.sideW));+ if (px(p.panelW)) root.style.setProperty("--panel-w-user", px(p.panelW));if (/Windows/.test(navigator.userAgent)) root.classList.add("win");if (/Electron/.test(navigator.userAgent) && /Mac/.test(navigator.platform)) root.classList.add("mac-app");+ if (/Electron/.test(navigator.userAgent) && /Windows/.test(navigator.userAgent)) root.classList.add("win-app");})();</script><!-- 设计库(token / 基础 / 组件 / 工具类,见 ui/design/README.md)+ 页面样式(@layer app) -->@@ -24,6 +52,7 @@<link rel="stylesheet" href="/amb/static/css/shell.css" /><link rel="stylesheet" href="/amb/static/css/chat.css" /><link rel="stylesheet" href="/amb/static/css/settings.css" />+ <link rel="stylesheet" href="/amb/static/css/guide.css" /><script type="importmap">{ "imports": { "preact": "/amb/vendor/preact.mjs", "preact/hooks": "/amb/vendor/hooks.mjs", "htm": "/amb/vendor/htm.mjs" } }</script>diff --git a/ui/lib/access.js b/ui/lib/access.jsindex 23f5e19..23d1d16 100644--- a/ui/lib/access.js+++ b/ui/lib/access.js@@ -1,11 +1,8 @@// 谁能使用机器人:信息面板(使用请求)和机器人设置(主人、允许名单)共用的说法。-export const CHANNEL_NAME = { web: "网页", feishu: "飞书", weixin: "微信" };+// 文案跟着界面语言:写成函数,渲染时再取。不认识的渠道 / 来源原样显示。+import { t, has } from "./i18n.js";++export const channelName = (c) => (has(`access.channel.${c}`) ? t(`access.channel.${c}`) : c);/** 允许名单里每个人是怎么来的 */-export const SOURCE_LABEL = {- request: "你允许的",- migration: "升级前已在使用",- "previous-owner": "之前的主人",- app: "在应用里添加",- test: "测试",-};+export const sourceLabel = (s) => (has(`access.source.${s}`) ? t(`access.source.${s}`) : s);diff --git a/ui/lib/api.js b/ui/lib/api.jsindex 4fd8cdc..e2739cb 100644--- a/ui/lib/api.js+++ b/ui/lib/api.js@@ -1,4 +1,6 @@// 本机后端接口:JSON 请求 + 流式对话(POST + text/event-stream,EventSource 不支持 POST)。+// 每个请求带 x-amb-lang(界面当前语言),服务端的报错和状态文字用同一种语言(src/i18n)。+import { getLang } from "./i18n.js";export class ApiError extends Error {constructor(message, status, data) {super(message);@@ -10,7 +12,7 @@ export class ApiError extends Error {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" } : {},+ headers: { "x-amb-lang": getLang(), ...(opts.body !== undefined ? { "content-type": "application/json" } : {}) },body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,signal: opts.signal,});@@ -99,7 +101,7 @@ export function streamChat(botId, text, handlers, signal) {return readEvents(fetch(`/amb/api/bots/${encodeURIComponent(botId)}/chat/stream`, {method: "POST",- headers: { "content-type": "application/json" },+ headers: { "content-type": "application/json", "x-amb-lang": getLang() },body: JSON.stringify({ text }),signal,}),@@ -109,5 +111,5 @@ export function streamChat(botId, text, handlers, signal) {/** 接上进行中的那条消息(切走再切回、刷新后):先 snapshot(到目前为止的样子),之后的事件同 streamChat,最后 done */export function attachChat(botId, turnId, handlers, signal) {- return readEvents(fetch(`/amb/api/bots/${encodeURIComponent(botId)}/chat/live?turn=${encodeURIComponent(turnId)}`, { signal }), handlers);+ return readEvents(fetch(`/amb/api/bots/${encodeURIComponent(botId)}/chat/live?turn=${encodeURIComponent(turnId)}`, { headers: { "x-amb-lang": getLang() }, signal }), handlers);}diff --git a/ui/lib/format.js b/ui/lib/format.jsindex c774bed..6c2c48a 100644--- a/ui/lib/format.js+++ b/ui/lib/format.js@@ -1,39 +1,48 @@-// 时间与数量的中文显示。+// 时间与时长的显示,跟着界面语言(文案在 ui/locales/<语言>/time.js,日期部分交给 Intl)。+import { t, locale } from "./i18n.js";+const pad = (n) => String(n).padStart(2, "0");const hm = (d) => `${pad(d.getHours())}:${pad(d.getMinutes())}`;+const dateFmt = (opts) => new Intl.DateTimeFormat(locale(), opts);-/** 消息流里的时间分隔条:"今天 15:33" / "昨天 09:10" / "10月26日 14:00" / "2025年3月1日 08:00" */-export function fmtSep(t) {- const d = new Date(t);+/** 消息流里的时间分隔条:"今天 15:33" / "昨天 09:10" / "10月26日 14:00" / "2025年3月1日 08:00"(英文:Today 15:33 / Oct 26 14:00 / Mar 1, 2025 08:00) */+export function fmtSep(at) {+ const d = new Date(at);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)}`;+ if (diff === 0) return t("time.today", { time: hm(d) });+ if (diff === 1) return t("time.yesterday", { time: hm(d) });+ const date = dateFmt(d.getFullYear() === now.getFullYear() ? { month: locale() === "en" ? "short" : "long", day: "numeric" } : { year: "numeric", month: locale() === "en" ? "short" : "long", day: "numeric" }).format(d);+ return t("time.dateTime", { date, time: 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);+export function fmtAgo(at) {+ if (!at) return "";+ const s = (Date.now() - at) / 1000;+ if (s < 60) return t("time.justNow");+ if (s < 3600) return t("time.minutesAgo", { count: Math.floor(s / 60) });+ const d = new Date(at);if (new Date().toDateString() === d.toDateString()) return hm(d);- return `${d.getMonth() + 1}月${d.getDate()}日`;+ return dateFmt({ month: locale() === "en" ? "short" : "long", day: "numeric" }).format(d);}/** 消息旁的时刻:"15:33" */-export const fmtClock = (t) => (t ? hm(new Date(t)) : "");+export const fmtClock = (at) => (at ? hm(new Date(at)) : "");-/** 一段工作的用时:"12 秒" / "1 分 24 秒" */+/** 一段工作的用时:"12 秒" / "1 分 24 秒"(英文:12s / 1m 24s) */export function fmtDur(ms) {const s = Math.max(1, Math.round(ms / 1000));- return s < 60 ? `${s} 秒` : `${Math.floor(s / 60)} 分 ${s % 60} 秒`;+ return s < 60 ? t("time.seconds", { s }) : t("time.minSec", { m: Math.floor(s / 60), s: s % 60 });+}++/** 完整的日期时间(24 小时制) */+export function fmtTime(at) {+ return at ? new Date(at).toLocaleString(locale(), { hour12: false }) : "";}-export function fmtTime(t) {- return t ? new Date(t).toLocaleString("zh-CN", { hour12: false }) : "";+/** 只有时刻(带秒):"15:33:08" */+export function fmtTimeOfDay(at) {+ return at ? new Date(at).toLocaleTimeString(locale(), { hour12: false }) : "";}diff --git a/ui/lib/guide.js b/ui/lib/guide.jsnew file mode 100644index 0000000..0072731--- /dev/null+++ b/ui/lib/guide.js@@ -0,0 +1,123 @@+// 新手引导(上手清单)的状态:步骤(文案在 ui/locales/<语言>/guide.js)、进度(存在后端 /guide,见 src/guide.ts)、当前在引导哪一步。+// 各界面在看到结果时调 markDone():对话里收到回复、换了模型、收到文件;信息面板看到渠道已连接。+// 有些步骤后端能从数据里推导出来(记忆、渠道),refreshGuide() 取回来时一并庆祝。+import { createStore, toast } from "./store.js";+import { api } from "./api.js";+import { has, t } from "./i18n.js";++/**+ * 清单的六步,id 与 src/guide.ts 的 GUIDE_STEPS 一致;target:引导卡片指向的界面位置(data-guide)。+ * 文案在 ui/locales/<语言>/guide.js 的 steps.<id>,渲染时用 stepText / stepHow 取(切换语言后跟着变,这里不缓存):+ * title、desc、how(几条怎么做)、try(可以一键发出的示例,没有就不给按钮)、note、doneText;生图那一步另有 demoNote、noModelText。+ */+export const STEPS = [+ { id: "hello", target: "composer" },+ { id: "model", target: "model" },+ { id: "weixin", target: "weixin" },+ { id: "hands", target: "composer" },+ { id: "memory", target: "composer" },+ // 引导里这一步只放预置演示:教会怎么操作就够了,不替用户调用真的模型花钱(见 runMediaDemo)+ { id: "media", target: "composer" },+];++const stepKey = (s, field) => `guide.steps.${s.id}.${field}`;+/** 步骤的一段文案(field 见上),{name} 换成机器人的名字;这一步没有这段(比如换模型没有 try)时返回 "" */+export const stepText = (s, field, name = t("guide.defaultBotName")) => (has(stepKey(s, field)) ? t(stepKey(s, field), { name }) : "");+/** 「怎么做」的几条 */+export function stepHow(s) {+ const out = [];+ for (let i = 0; has(stepKey(s, `how.${i}`)); i++) out.push(t(stepKey(s, `how.${i}`)));+ return out;+}++/** loaded:读到了后端进度;media:账户有可用的图片 / 视频模型(只决定演示完了说什么、要不要给开通链接);+ * focus:引导卡片正指着的步骤;armed:从清单卡里直接发出了这一步的示例,做完时引导卡片接着出来说「做好了 → 下一步」 */+export const guide = createStore({ loaded: false, done: [], hidden: false, seen: [], media: false, focus: null, armed: null });+/** 刚完成一步:{ id, n, total, all, at },对话页的头像、左下角的清单据此动一下 */+export const completed = createStore(null);+/** 往对话输入框里填一句(引导卡片的「填入」) */+export const fill = createStore(null);+/** 在对话里放一遍生图的预置演示(对话页订阅它) */+export const demo = createStore(null);++/** 六步都在;生图那一步不管有没有可用模型都走预置演示 */+export const visibleSteps = () => STEPS;+export const currentStep = (g = guide.get()) => visibleSteps(g).find((s) => !g.done.includes(s.id)) || null;+export const nextStep = (id, g = guide.get()) => {+ const list = visibleSteps(g);+ const i = list.findIndex((s) => s.id === id);+ return list.slice(i + 1).find((s) => !g.done.includes(s.id)) || list.find((s) => !g.done.includes(s.id) && s.id !== id) || null;+};+export const isActive = (g = guide.get()) => g.loaded && !g.hidden;++const ORDER = STEPS.map((s) => s.id);++function celebrate(ids, g) {+ if (!ids.length || g.hidden) return;+ const list = visibleSteps(g);+ const n = list.filter((s) => g.done.includes(s.id)).length;+ const all = n === list.length;+ const last = STEPS.find((s) => s.id === ids[ids.length - 1]);+ completed.set({ id: last.id, n, total: list.length, all, at: Date.now() });+ toast(all ? t("guide.allDone") : t("guide.toastProgress", { progress: `${n}/${list.length}`, title: stepText(last, "title", t("guide.nameToast")) }));+}++/** 后端进度 → 本地;新出现的完成项(后端推导出来的)也庆祝一下 */+function apply(d, quiet) {+ const g = guide.get();+ const fresh = g.loaded ? d.done.filter((id) => !g.done.includes(id)) : [];+ const next = { ...g, loaded: true, done: ORDER.filter((id) => d.done.includes(id) || g.done.includes(id)), hidden: !!d.hidden, seen: d.seen || [] };+ guide.set(next);+ if (!quiet) celebrate(fresh, next);+}++/** 先读进度把清单显示出来;有没有可用的图片模型要问 Modelflare(可能要好几秒),在后台慢慢问,问不到就当没有 */+export async function loadGuide() {+ const d = await api("/guide").catch(() => null);+ if (d) apply(d, true);+ api("/media/models")+ .then((m) => guide.set((g) => ({ ...g, media: !!(m.image?.length || m.video?.length) })))+ .catch(() => {});+}+/** 再读一次(回复结束后、指着渠道那一步时):后端推导出的新完成项会被庆祝 */+export const refreshGuide = () => api("/guide").then((d) => apply(d, false)).catch(() => {});++export function markDone(id) {+ const g = guide.get();+ if (!g.loaded || g.done.includes(id)) return;+ const next = { ...g, done: ORDER.filter((x) => g.done.includes(x) || x === id), ...(g.armed === id ? { focus: id, armed: null } : {}) };+ guide.set(next);+ celebrate([id], next);+ api("/guide", { method: "PUT", body: { done: id } }).catch(() => {});+}++export const setFocus = (id) => guide.set((g) => ({ ...g, focus: id }));+/** 清单卡里点了「发送这句」:做完这一步时把引导卡片叫出来 */+export const arm = (id) => guide.set((g) => ({ ...g, armed: id }));++export function markSeen(key) {+ guide.set((g) => (g.seen.includes(key) ? g : { ...g, seen: [...g.seen, key] }));+ api("/guide", { method: "PUT", body: { seen: key } }).catch(() => {});+}++/** 设置 → 常规 → 上手清单「重新开始」:清掉收起与不再显示,已经能从数据看出来做过的步骤仍算做过 */+export async function resetGuide() {+ const d = await api("/guide", { method: "PUT", body: { reset: true } });+ guide.set((g) => ({ ...g, done: [], focus: null, armed: null }));+ apply(d, true);+}++export function hideGuide() {+ guide.set((g) => ({ ...g, hidden: true, focus: null }));+ api("/guide", { method: "PUT", body: { hidden: true } }).catch(() => {});+}++export const fillComposer = (text) => fill.set({ text, at: Date.now() });++/** 放一遍生图的预置演示:流程和真的一样(先确认 → 生成中 → 出图),图是客户端自带的示例,不调用模型、不扣费 */+export function runMediaDemo() {+ demo.set({ text: stepText(STEPS.find((s) => s.id === "media"), "try"), at: Date.now() });+}++/** 文件名看起来是图片或视频:算「生成一张图」,其余的交付算「让它动手做件事」 */+export const isMediaFile = (name) => /\.(png|jpe?g|webp|gif|bmp|mp4|mov|webm)$/i.test(name || "");diff --git a/ui/lib/i18n.js b/ui/lib/i18n.jsnew file mode 100644index 0000000..30d5abb--- /dev/null+++ b/ui/lib/i18n.js@@ -0,0 +1,207 @@+// 界面多语言:简体中文 / English。+//+// 语言偏好(system | zh-CN | en)是应用级设置,以服务端配置 config.ui.lang 为准:托盘菜单、服务端报错、+// 机器人发到微信 / 飞书的系统消息都跟着它。localStorage 只缓存一份给首帧用(index.html 先按它设 <html lang>),+// 启动后 App 读到 /settings 里的 lang 再以服务端为准(adoptServerLang)。+// 每个 API 请求带 x-amb-lang(解析后的语言),服务端据此返回同一种语言的报错和状态文字。+//+// 文案在 ui/locales/<语言>/<命名空间>.js,键 = "命名空间.键",可以嵌套("settings.rows.theme.name")。+// t("chat.send") → 纯文本+// t("chat.queued", { n: 3 }) → 插值:文案里写 {n}+// t("chat.files", { count: 2 }) → 复数:文案写成 { one: "…", other: "…" },按 count 选(Intl.PluralRules)+// t("appearance.hint", { b: html`<b>…</b>` }) → 插值里有 vnode 时返回数组,可直接放进 htm 模板+// 缺失的键先回退到简体中文,再回退到键名本身(开发时控制台警告一次)。+// 切换语言时 App 订阅 useLang() 整棵树重渲染:模块顶层不要缓存翻译后的字符串(写成函数,渲染时再取),+// useMemo 的依赖里要带上 useLang() 的返回值。+import { useEffect, useState } from "preact/hooks";+import zhCN from "../locales/zh-CN/index.js";+import en from "../locales/en/index.js";++export const LANGS = ["zh-CN", "en"];+/** 各语言用自己的文字写名字(语言菜单的惯例),不随界面语言翻译 */+export const LANG_NAMES = { "zh-CN": "简体中文", en: "English" }; // i18n-ignore+const DICTS = { "zh-CN": zhCN, en };+const FALLBACK = "zh-CN";+const KEY = "amb-lang";++/** "zh" / "zh-Hans-CN" / "zh-TW" → zh-CN;"en-US" → en;其他 → null */+export function normalizeLang(s) {+ const v = String(s || "").trim().toLowerCase();+ if (v.startsWith("zh")) return "zh-CN";+ if (v.startsWith("en")) return "en";+ return null;+}+export const normalizePref = (s) => (s === "system" ? "system" : normalizeLang(s) || "system");++/** 系统语言:按浏览器的首选语言列表找第一个支持的;都不支持时用英文 */+export function systemLang() {+ const list = (typeof navigator !== "undefined" && (navigator.languages?.length ? navigator.languages : [navigator.language])) || [];+ for (const l of list) {+ const n = normalizeLang(l);+ if (n) return n;+ }+ return "en";+}++function readPref() {+ try {+ return normalizePref(localStorage.getItem(KEY));+ } catch {+ return "system";+ }+}++let pref = readPref();+let current = pref === "system" ? systemLang() : pref;+const subs = new Set();++/** 当前界面语言(解析后的 zh-CN | en) */+export const getLang = () => current;+/** 语言偏好(system | zh-CN | en) */+export const getLangPref = () => pref;+/** 给 Intl / toLocaleString 用的语言标签 */+export const locale = () => current;++function apply() {+ if (typeof document !== "undefined") document.documentElement.lang = current;+}++/** 只在本机生效(不写服务端):读到服务端配置时、或保存失败回滚时用 */+export function setLangPref(next) {+ const p = normalizePref(next);+ try {+ if (p === "system") localStorage.removeItem(KEY);+ else localStorage.setItem(KEY, p);+ } catch {+ /* 隐私模式等:只在本次生效 */+ }+ const resolved = p === "system" ? systemLang() : p;+ const changed = resolved !== current || p !== pref;+ pref = p;+ current = resolved;+ apply();+ if (changed) for (const fn of subs) fn();+}++/** 用户在界面上换语言:本机立刻生效,再存到服务端(托盘菜单、系统消息跟着变);保存失败时回滚并抛出 */+export async function changeLang(next) {+ const prev = pref;+ setLangPref(next);+ try {+ const res = await fetch("/amb/api/settings", {+ method: "PUT",+ headers: { "content-type": "application/json", "x-amb-lang": current },+ body: JSON.stringify({ lang: pref }),+ });+ if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error || `HTTP ${res.status}`);+ return await res.json();+ } catch (e) {+ setLangPref(prev);+ throw e;+ }+}++/** 启动时读到服务端的语言偏好:以服务端为准(同一份配置可能在另一个窗口 / 浏览器里改过) */+export function adoptServerLang(serverPref) {+ if (serverPref === undefined || serverPref === null) return;+ if (normalizePref(serverPref) !== pref) setLangPref(serverPref);+}++/** 订阅语言变化;返回取消订阅的函数 */+export function onLangChange(fn) {+ subs.add(fn);+ return () => subs.delete(fn);+}++/** 组件里取当前语言并在切换时重渲染 */+export function useLang() {+ // 偏好变了但解析后的语言没变(系统本来就是英文,从"跟随系统"换到 English)也要重渲染:语言菜单的选中项变了+ const [, bump] = useState(0);+ useEffect(() => {+ const fn = () => bump((n) => n + 1);+ subs.add(fn);+ return () => subs.delete(fn);+ }, []);+ return current;+}++// 跟随系统时,系统语言变了(浏览器 / 系统设置里改了首选语言)也跟着变+if (typeof window !== "undefined") {+ window.addEventListener("languagechange", () => pref === "system" && setLangPref("system"));+ // 同一浏览器开了多个标签页:一处改了,其他标签页跟着变+ window.addEventListener("storage", (e) => {+ if (e.key === KEY || e.key === null) setLangPref(readPref());+ });+}+apply();++// —— 查表与格式化 ——+function lookup(dict, key) {+ let v = dict;+ for (const k of key.split(".")) {+ if (v === null || typeof v !== "object") return undefined;+ v = v[k];+ }+ return v;+}++const isPlural = (v) => v !== null && typeof v === "object" && typeof v.other === "string";+const rulesCache = {};+const pluralRules = (l) => (rulesCache[l] ||= new Intl.PluralRules(l));+const warned = new Set();++function resolve(key) {+ let v = lookup(DICTS[current], key);+ if (typeof v !== "string" && !isPlural(v)) v = lookup(DICTS[FALLBACK], key);+ if (typeof v === "string" || isPlural(v)) return v;+ if (!warned.has(key)) {+ warned.add(key);+ console.warn(`[i18n] missing message: ${key}`);+ }+ return undefined;+}++/** 这个键有没有文案(给拼出来的动态键用:t(has(k) ? k : "common.unknown")) */+export const has = (key) => {+ const v = lookup(DICTS[current], key) ?? lookup(DICTS[FALLBACK], key);+ return typeof v === "string" || isPlural(v);+};++/** 把 {name} 换成参数;参数里有 vnode(对象)时返回数组 */+export function format(s, params) {+ if (!params || !s.includes("{")) return s;+ const parts = s.split(/\{(\w+)\}/);+ let rich = false;+ const out = parts.map((p, i) => {+ if (i % 2 === 0) return p;+ if (!(p in params)) return `{${p}}`;+ const v = params[p];+ if (v !== null && typeof v === "object") {+ rich = true;+ return v;+ }+ return v === null || v === undefined ? "" : String(v);+ });+ return rich ? out.filter((x) => x !== "") : out.join("");+}++export function t(key, params) {+ let v = resolve(key);+ if (v === undefined) return key;+ if (isPlural(v)) {+ const n = Number(params?.count);+ v = (Number.isFinite(n) && v[pluralRules(current).select(n)]) || v.other;+ }+ return format(v, params);+}++/** 数字按当前语言分组:1,234 */+export const fmtNum = (n, opts) => (Number.isFinite(Number(n)) ? new Intl.NumberFormat(current, opts).format(Number(n)) : String(n ?? ""));+/** 列表连接:"A、B 和 C" / "A, B, and C" */+export const fmtList = (items, type = "conjunction") => {+ try {+ return new Intl.ListFormat(current, { type }).format(items.map(String));+ } catch {+ return items.join(current === "en" ? ", " : "、"); // i18n-ignore+ }+};diff --git a/ui/lib/markdown.js b/ui/lib/markdown.jsindex 1eac9df..bcc6666 100644--- a/ui/lib/markdown.js+++ b/ui/lib/markdown.js@@ -165,10 +165,11 @@ function parseLines(lines, depth) {}const PUNCT = /[!-/:-@[-`{-~]/;-const TRAIL = /[.,;:!?。,、;:!?'"”’)】》]+$/;+// 中文标点不算链接的一部分(匹配的是消息正文,不是界面文案)+const TRAIL = /[.,;:!?。,、;:!?'"”’)】》]+$/; // i18n-ignorefunction bareUrl(s, i) {- const m = /^https?:\/\/[^\s<>"'`,。;、()【】《》“”]+/i.exec(s.slice(i));+ const m = /^https?:\/\/[^\s<>"'`,。;、()【】《》“”]+/i.exec(s.slice(i)); // i18n-ignoreif (!m) return null;let url = m[0].replace(TRAIL, "");// 末尾 ) 只在括号成对时保留diff --git a/ui/lib/models.js b/ui/lib/models.jsindex 66fa681..6f8e097 100644--- a/ui/lib/models.js+++ b/ui/lib/models.js@@ -5,7 +5,7 @@ export const normModel = (m) => (m && m.startsWith("modelflare/") ? m.slice("modexport const sameModel = (a, b) => !!a && !!b && normModel(a) === normModel(b);export const shortModel = (m) => (m && m.includes("/") ? m.slice(m.lastIndexOf("/") + 1) : m);-// —— 模型族:按名字认(Modelflare 的 ID 不带厂商前缀,如 gpt-6-sol、claude-opus-5-5)。数组顺序就是显示顺序,认不出的归「其他」放最后 ——+// —— 模型族:按名字认(Modelflare 的 ID 不带厂商前缀,如 gpt-6-sol、claude-opus-5-5)。数组顺序就是显示顺序,认不出的归 OTHER_FAMILY 放最后 ——const FAMILIES = [["GPT", /^(gpt|chatgpt|codex|o\d)/],["Claude", /^claude/],@@ -20,7 +20,8 @@ const FAMILIES = [["Llama", /^llama/],["Mistral", /^(mistral|mixtral|magistral|codestral|devstral|ministral)/],];-export const OTHER_FAMILY = "其他";+/** 认不出的族:一个不随语言变的记号,显示时由界面翻译(model-picker.js 的 familyName,「其他」/ Other) */+export const OTHER_FAMILY = "other";const ORDER = [...FAMILIES.map(([f]) => f), OTHER_FAMILY];export function modelFamily(id) {diff --git a/ui/lib/notify.js b/ui/lib/notify.jsnew file mode 100644index 0000000..7f16672--- /dev/null+++ b/ui/lib/notify.js@@ -0,0 +1,45 @@+// 系统通知(设置 › 常规 › 回复完成时通知):窗口不在前台时,机器人回复完或等你确认,弹一条系统通知。+// 桌面版走 Electron 的 HTML5 通知(默认已授权);浏览器里第一次打开开关时向用户申请权限。+import { prefs } from "./prefs.js";+import { t } from "./i18n.js";++export const canNotify = typeof window !== "undefined" && "Notification" in window;++/** 打开开关前申请权限;返回是否可以发通知 */+export async function requestNotify() {+ if (!canNotify) return false;+ if (Notification.permission === "granted") return true;+ if (Notification.permission === "denied") return false;+ try {+ return (await Notification.requestPermission()) === "granted";+ } catch {+ return false;+ }+}++/** Markdown 回复 → 一行摘要 */+export function plainSnippet(text, max = 120) {+ const s = String(text || "")+ .replace(/```[\s\S]*?```/g, () => ` ${t("notify.code")} `)+ .replace(/!\[[^\]]*\]\([^)]*\)/g, () => ` ${t("notify.image")} `)+ .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")+ .replace(/[`*_#>|~]/g, "")+ .replace(/\s+/g, " ")+ .trim();+ return s.length > max ? s.slice(0, max - 1) + "…" : s;+}++/** 偏好打开、已授权、窗口不在前台时才发;tag 相同的通知会互相替换 */+export function notify(title, body, tag) {+ if (!canNotify || !prefs.get().notify || Notification.permission !== "granted") return;+ if (document.visibilityState === "visible" && document.hasFocus()) return;+ try {+ const n = new Notification(title, { body, tag });+ n.onclick = () => {+ window.focus();+ n.close();+ };+ } catch {+ /* 有的环境(比如 Android Chrome)不允许页面直接 new Notification */+ }+}diff --git a/ui/lib/perms.js b/ui/lib/perms.jsindex 1485042..b928744 100644--- a/ui/lib/perms.js+++ b/ui/lib/perms.js@@ -1,18 +1,19 @@// 文件权限的三个预设:输入框左下角的权限胶囊和机器人设置共用。完全权限有风险,切换前先确认。+// 文案跟着界面语言:写成函数,渲染时再取(不在模块顶层缓存翻译)。import { confirmSheet } from "./store.js";+import { t } from "./i18n.js";-export const PERMS = {- workspace: { label: "工作区可写", icon: "shield", note: "只能改这个机器人的工作区,越界操作先问你" },- readonly: { label: "只读", icon: "lock", note: "不能改文件,命令在只读沙箱里运行" },- full: { label: "完全权限", icon: "unlock", note: "命令不经沙箱,可读写你的所有文件;递归删除仍会先问你", danger: true },-};+export const perms = () => ({+ workspace: { label: t("perms.workspace"), icon: "shield", note: t("perms.workspaceNote") },+ readonly: { label: t("perms.readonly"), icon: "lock", note: t("perms.readonlyNote") },+ full: { label: t("perms.full"), icon: "unlock", note: t("perms.fullNote"), danger: true },+});/** 完全权限意味着什么(确认框与机器人设置里的提示用同一段话) */-export const FULL_WARNING =- "命令不经沙箱,以你的用户身份直接运行:可以读取和修改你电脑上的任何文件,包括 AnyModelBot 自己的数据(会话记录、渠道令牌和密钥)。越界操作不再请求批准,只有递归删除(rm -r、Remove-Item -Recurse 等)仍会先问你。只在你信任当前模型和任务时开启。";+export const fullWarning = () => t("perms.fullWarning");/** 切到完全权限前确认;切到其他预设不用 */export function confirmPermission(p) {if (p !== "full") return Promise.resolve(true);- return confirmSheet({ title: "开启完全权限?", body: FULL_WARNING, confirmLabel: "开启完全权限", danger: true });+ return confirmSheet({ title: t("perms.confirmTitle"), body: fullWarning(), confirmLabel: t("perms.confirmLabel"), danger: true });}diff --git a/ui/lib/prefs.js b/ui/lib/prefs.jsnew file mode 100644index 0000000..7d8a948--- /dev/null+++ b/ui/lib/prefs.js@@ -0,0 +1,125 @@+// 本机界面偏好:设置 › 外观(字体大小、字体、对话宽度、代码换行、动画、毛玻璃)、设置 › 常规里的对话习惯(发送键、完成通知),+// 以及拖分隔条调过的侧栏 / 信息面板宽度。+// 和主题(lib/theme.js)一样存在 localStorage:每个浏览器 / 桌面窗口各一份,不进服务端配置。+// 外观类的偏好解析成 <html> 上的 data-* 属性(取值见 design/tokens/semantic.css「用户偏好」),CSS 只认这些属性;+// 首帧前 index.html 先按同样的规则套一遍,避免闪——改这里的解析规则时两处一起改。+import { createStore } from "./store.js";++const KEY = "amb-prefs";++export const PREF_DEFAULTS = Object.freeze({+ text: "md", // 字体大小:sm | md | lg | xl+ font: "system", // 界面字体:system | serif | custom+ fontName: "", // font = custom 时的字体名(逗号分隔可写多个)+ codeFont: "", // 代码字体名,空 = 系统等宽字体+ width: "normal", // 对话宽度:normal | wide | full+ codeWrap: false, // 代码块自动换行+ motion: "system", // 动画:system | on | off+ glass: "system", // 毛玻璃:system | on | off+ sendKey: "enter", // 发送:enter(Shift+Enter 换行)| mod(⌘/Ctrl+Enter 发送,Enter 换行)+ notify: false, // 窗口不在前台时,回复完成 / 需要确认弹系统通知+ sideW: 0, // 侧栏宽度(px),拖分隔条调的;0 = 默认(tokens 的 --side-w,窄窗口时更窄)+ panelW: 0, // 信息面板宽度(px),同上+});+/** "恢复默认外观"重置的键(对话习惯不动) */+export const APPEARANCE_KEYS = ["text", "font", "fontName", "codeFont", "width", "codeWrap", "motion", "glass"];++const CHOICES = {+ text: ["sm", "md", "lg", "xl"],+ font: ["system", "serif", "custom"],+ width: ["normal", "wide", "full"],+ motion: ["system", "on", "off"],+ glass: ["system", "on", "off"],+ sendKey: ["enter", "mod"],+};++/** 字体名只留能安全放进 CSS 字符串的字符:去掉引号、反斜杠、分号、花括号、尖括号 */+export const cleanFontName = (s) => String(s || "").replace(/["'\\;{}<>]/g, "").replace(/\s+/g, " ").trim().slice(0, 120);+/** "LXGW WenKai, 霞鹜文楷" → "\"LXGW WenKai\", \"霞鹜文楷\"" */+export const fontStack = (s) =>+ cleanFontName(s)+ .split(",")+ .map((x) => x.trim())+ .filter(Boolean)+ .map((x) => `"${x}"`)+ .join(", ");++function sanitize(raw) {+ const p = { ...PREF_DEFAULTS };+ if (!raw || typeof raw !== "object") return p;+ for (const [k, list] of Object.entries(CHOICES)) if (list.includes(raw[k])) p[k] = raw[k];+ for (const k of ["fontName", "codeFont"]) if (typeof raw[k] === "string") p[k] = cleanFontName(raw[k]);+ for (const k of ["codeWrap", "notify"]) if (typeof raw[k] === "boolean") p[k] = raw[k];+ // 宽度只粗查一下是不是合理的像素数;精确的范围(最窄 / 最宽 / 窗口占比)由 CSS 的 clamp() 和 Splitter 管+ for (const k of ["sideW", "panelW"]) if (Number.isFinite(raw[k]) && raw[k] >= 120 && raw[k] <= 1200) p[k] = Math.round(raw[k]);+ return p;+}++function read() {+ try {+ return sanitize(JSON.parse(localStorage.getItem(KEY) || "null"));+ } catch {+ return sanitize(null);+ }+}++function write(p) {+ try {+ const diff = Object.fromEntries(Object.entries(p).filter(([k, v]) => v !== PREF_DEFAULTS[k]));+ if (Object.keys(diff).length) localStorage.setItem(KEY, JSON.stringify(diff));+ else localStorage.removeItem(KEY);+ } catch {+ /* 隐私模式等:只在本次生效 */+ }+}++const mqMotion = window.matchMedia("(prefers-reduced-motion: reduce)");+const mqGlass = window.matchMedia("(prefers-reduced-transparency: reduce)");++function apply(p) {+ const root = document.documentElement;+ const d = root.dataset;+ const custom = p.font === "custom" && fontStack(p.fontName);+ d.text = p.text;+ d.font = custom ? "custom" : p.font === "serif" ? "serif" : "system";+ if (custom) root.style.setProperty("--font", `${custom}, var(--font-system)`);+ else root.style.removeProperty("--font");+ const code = fontStack(p.codeFont);+ if (code) root.style.setProperty("--code", `${code}, var(--code-system)`);+ else root.style.removeProperty("--code");+ d.width = p.width;+ d.codeWrap = p.codeWrap ? "on" : "off";+ d.motion = p.motion === "off" ? "off" : p.motion === "on" ? "full" : mqMotion.matches ? "reduce" : "full";+ d.glass = p.glass === "system" ? (mqGlass.matches ? "off" : "on") : p.glass;+ // 拖过的宽度:<html> 上内联 --side-w-user / --panel-w-user(shell.css 取 var(--side-w-user, var(--side-w)))+ for (const [k, prop] of [["sideW", "--side-w-user"], ["panelW", "--panel-w-user"]])+ if (p[k]) root.style.setProperty(prop, `${p[k]}px`);+ else root.style.removeProperty(prop);+}++export const prefs = createStore(read());++export function setPrefs(patch) {+ const next = sanitize({ ...prefs.get(), ...patch });+ write(next);+ prefs.set(next);+ apply(next);+}++export function resetAppearance() {+ setPrefs(Object.fromEntries(APPEARANCE_KEYS.map((k) => [k, PREF_DEFAULTS[k]])));+}++/** 和默认外观是否不同(设置页的"恢复默认"据此可用) */+export const appearanceChanged = (p) => APPEARANCE_KEYS.some((k) => p[k] !== PREF_DEFAULTS[k]);++mqMotion.addEventListener?.("change", () => apply(prefs.get()));+mqGlass.addEventListener?.("change", () => apply(prefs.get()));+// 同一浏览器开了多个标签页:一处改了,其他标签页跟着变+window.addEventListener("storage", (e) => {+ if (e.key !== KEY && e.key !== null) return;+ const next = read();+ prefs.set(next);+ apply(next);+});+apply(prefs.get());diff --git a/ui/lib/pwsh.js b/ui/lib/pwsh.jsindex 455f988..be91034 100644--- a/ui/lib/pwsh.js+++ b/ui/lib/pwsh.js@@ -3,6 +3,7 @@import { useEffect } from "preact/hooks";import { api } from "./api.js";import { createStore, toast, useStore } from "./store.js";+import { t } from "./i18n.js";export const PWSH_INSTALL_URL = "https://aka.ms/PSWindows";export const PWSH_WINGET = "winget install --id Microsoft.PowerShell --source winget";@@ -17,11 +18,14 @@ const BUSY = ["waiting", "downloading", "extracting", "verifying", "testing"];export const pwshInstalling = (s) => !!s?.private && BUSY.includes(s.private.install?.state);const mb = (n) => (n === undefined || n === null ? "?" : Math.round(n / 1048576));-/** 安装进度的一句话 */+/** 安装进度的一句话(按当前语言) */export function pwshProgress(p) {if (!p) return "";- if (p.state === "downloading") return `下载 ${mb(p.received)} / ${mb(p.total)} MB${p.total ? `(${Math.min(100, Math.floor(((p.received || 0) / p.total) * 100))}%)` : ""}`;- return { waiting: p.error || "准备中", extracting: "解压", verifying: "核对签名", testing: "试运行", done: "已装好", failed: `没装上:${p.error || "未知原因"}` }[p.state] || "";+ if (p.state === "downloading")+ return t("pwsh.progress.downloading", { received: mb(p.received), total: mb(p.total), pct: p.total ? t("pwsh.progress.pct", { n: Math.min(100, Math.floor(((p.received || 0) / p.total) * 100)) }) : "" });+ if (p.state === "waiting") return p.error || t("pwsh.progress.waiting");+ if (p.state === "failed") return t("pwsh.progress.failed", { error: p.error || t("pwsh.unknownReason") });+ return ["extracting", "verifying", "testing", "done"].includes(p.state) ? t(`pwsh.progress.${p.state}`) : "";}function schedule(s) {@@ -47,23 +51,23 @@ export function loadPwsh() {/** 重新检测:重新找、重新试运行(装好系统的 PowerShell 7 后点它;代理空闲时换用) */export async function recheckPwsh() {const s = set(await api("/pwsh/recheck", { method: "POST", body: {} }));- if (!s.missing) toast(`已检测到 PowerShell ${s.version || "7"}${s.source === "private" ? "(应用内置)" : ""},代理空闲时换用`, "ok");- else toast(pwshInstalling(s) ? "还没有能用的 PowerShell 7,正在为代理安装" : "还没有检测到能用的 PowerShell 7", "warn");+ if (!s.missing) toast(t("pwsh.found", { version: s.version || "7", private: s.source === "private" ? t("pwsh.privateSuffix") : "" }), "ok");+ else toast(t(pwshInstalling(s) ? "pwsh.notFoundInstalling" : "pwsh.notFound"), "warn");return s;}/** 安装 / 重新安装应用内置的 PowerShell 7(后台进行,进度在提示和故障排查里) */export async function installPwsh(reinstall = false) {const s = set(await api("/pwsh/install", { method: "POST", body: { reinstall } }));- if (pwshInstalling(s)) toast(reinstall ? "正在重新安装 PowerShell 7…" : "正在安装 PowerShell 7…");- else if (!s.missing) toast(`代理用 PowerShell ${s.version || "7"}`, "ok");+ if (pwshInstalling(s)) toast(t(reinstall ? "pwsh.reinstalling" : "pwsh.installing"));+ else if (!s.missing) toast(t("pwsh.using", { version: s.version || "7" }), "ok");return s;}/** 改回系统默认(system)/ 重新用应用内置的(auto) */export async function setPwshMode(mode) {const s = set(await api("/pwsh/mode", { method: "PUT", body: { mode } }));- toast(mode === "system" ? "已改回系统默认,代理空闲时生效" : "已改用应用内置的 PowerShell 7", "ok");+ toast(t(mode === "system" ? "pwsh.modeSystem" : "pwsh.modePrivate"), "ok");return s;}diff --git a/ui/lib/store.js b/ui/lib/store.jsindex b2b5c3b..4e21700 100644--- a/ui/lib/store.js+++ b/ui/lib/store.js@@ -1,6 +1,7 @@-// 极小的全局状态:toast、确认框、主题。组件用 useStore 订阅。+// 极小的全局状态:toast、确认框、主题。toast 的文字在调用时就按当前语言取好。组件用 useStore 订阅。import { useEffect, useState } from "preact/hooks";import { ms } from "../design/motion.js";+import { t } from "./i18n.js";export function createStore(initial) {let value = initial;@@ -38,8 +39,8 @@ 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)), ms("--dur-base", 180));}-export const saved = () => toast("已保存");-export const failed = (e) => toast(typeof e === "string" ? e : e?.message || "出错了", "err");+export const saved = () => toast(t("common.saved"));+export const failed = (e) => toast(typeof e === "string" ? e : e?.message || t("common.error"), "err");// —— confirm sheet ——export const dialog = createStore(null);diff --git a/ui/lib/theme.js b/ui/lib/theme.jsindex fa623b3..623d042 100644--- a/ui/lib/theme.js+++ b/ui/lib/theme.js@@ -1,8 +1,19 @@// 外观:跟随系统 / 浅色 / 深色。<html data-theme> 总是解析后的值,CSS 只需定义一份深色变量。+import { api } from "./api.js";import { createStore } from "./store.js";const KEY = "amb-theme";const mq = window.matchMedia("(prefers-color-scheme: dark)");+// Windows 桌面版:右上角的最小化 / 最大化 / 关闭是系统画在界面上的,符号颜色要跟着主题换(electron/main.ts 的 titleBarOverlay)+const winApp = document.documentElement.classList.contains("win-app");+let sentDark;+function syncTitleBar(dark) {+ if (!winApp || dark === sentDark) return;+ sentDark = dark;+ api("/desktop/title-bar", { method: "POST", body: { dark } }).catch(() => {+ sentDark = undefined; // 下次切主题再试+ });+}function readMode() {try {@@ -18,6 +29,7 @@ export const themeMode = createStore(readMode());function apply(mode) {const resolved = mode === "system" ? (mq.matches ? "dark" : "light") : mode;document.documentElement.setAttribute("data-theme", resolved);+ syncTitleBar(resolved === "dark");}export function setThemeMode(mode) {diff --git a/ui/locales/en/access.js b/ui/locales/en/access.jsnew file mode 100644index 0000000..a3196a9--- /dev/null+++ b/ui/locales/en/access.js@@ -0,0 +1,11 @@+// access · en+export default {+ channel: { web: "Web", feishu: "Feishu", weixin: "WeChat" },+ source: {+ request: "Allowed by you",+ migration: "Already using it before the upgrade",+ "previous-owner": "Previous owner",+ app: "Added in the app",+ test: "Test",+ },+};diff --git a/ui/locales/en/account.js b/ui/locales/en/account.jsnew file mode 100644index 0000000..9c5dc5d--- /dev/null+++ b/ui/locales/en/account.js@@ -0,0 +1,23 @@+// account · en+export default {+ login: {+ title: "Sign in to Modelflare",+ hint: "Signing in replaces the API key you entered.",+ },+ usage: {+ title: "Usage",+ days: "{n} days",+ range: "Range",+ total: "Total {amount}",+ daily: "Daily spending",+ bar: { one: "{date}: {amount}, {count} request", other: "{date}: {amount}, {count} requests" },+ byModel: "By model",+ requests: { one: "{count} request", other: "{count} requests" },+ empty: "No usage in this period",+ },+ notifications: {+ title: "Modelflare notifications",+ empty: "No notifications",+ details: "View details ↗",+ },+};diff --git a/ui/locales/en/activity.js b/ui/locales/en/activity.jsnew file mode 100644index 0000000..7722573--- /dev/null+++ b/ui/locales/en/activity.js@@ -0,0 +1,24 @@+// activity · en+export default {+ lessThanTenth: "<0.1s",+ seconds: "{s}s",+ waitingModel: "Waiting for {model}",+ runningTool: "Running {tool}",+ subagent: "Sub-agent working",+ compact: "Compacting context",+ job: "Background command running",+ stepLabel: "{status}: {title}",+ failed: "Failed",+ running: "In progress",+ done: "Done",+ expandDetail: "{label}, show details",+ collapseDetail: "{label}, hide details",+ tokens: "Input {input} tokens · output {output} tokens",+ input: "Arguments",+ reply: "Reply",+ output: "Output",+ noSteps: "No steps yet",+ expand: "Show activity",+ collapse: "Hide activity",+ steps: { one: "{count} step", other: "{count} steps" },+};diff --git a/ui/locales/en/app.js b/ui/locales/en/app.jsnew file mode 100644index 0000000..b7e89c4--- /dev/null+++ b/ui/locales/en/app.js@@ -0,0 +1,39 @@+// app · en+export default {+ palette: {+ title: "Command palette",+ placeholder: "Type a command or bot name",+ inputLabel: "Command",+ empty: "No matching commands",+ },+ cmd: {+ settings: "Open Settings",+ settingsKeys: "settings preferences options",+ newBot: "New bot",+ newBotKeys: "new bot create add",+ openInfo: "Open info panel",+ closeInfo: "Close info panel",+ infoKeys: "info panel details",+ botSettings: "Settings for “{name}”",+ botSettingsKeys: "bot settings configure",+ modelflare: "Modelflare settings",+ modelflareKeys: "modelflare key api model",+ appearance: "Appearance settings",+ appearanceKeys: "appearance font text size motion animation glass blur width",+ themeSystem: "Theme: System",+ themeKeys: "theme appearance",+ themeLight: "Theme: Light",+ themeLightKeys: "theme light appearance",+ themeDark: "Theme: Dark",+ themeDarkKeys: "theme dark night appearance",+ lang: "Language: {name}",+ langKeys: "language english chinese 中文",+ switchBot: "Switch to “{name}”",+ },+ lowBalance: "Your Modelflare balance is down to ${amount}",+ serviceDown: "Can't reach the local service: {error}",+ resizeSide: "Resize sidebar",+ resizePanel: "Resize info panel",+ botMissing: "Bot not found",+ backToChat: "Back to chat",+};diff --git a/ui/locales/en/avatar.js b/ui/locales/en/avatar.jsnew file mode 100644index 0000000..8871d39--- /dev/null+++ b/ui/locales/en/avatar.js@@ -0,0 +1,12 @@+// avatar · en: bot avatar characters (components/avatar.js). Names match the website (site/src/i18n/en.ts).+export default {+ label: "Avatar",+ chars: {+ blue: { name: "Ping", role: "Lead · All-rounder", pick: "Its antenna pings the moment a message lands. Default assistant, meeting notes." },+ yellow: { name: "Twinkle", role: "Support & chat", pick: "A little star on top — it blushes when it smiles. Support, Q&A, casual chat." },+ green: { name: "Sprout", role: "Digests & tidying", pick: "Grows a little every day. Digests, memory tidying, knowledge base." },+ red: { name: "Beat", role: "Code & automation", pick: "Headset on, it's in the zone. Coding, scripts, automation." },+ purple: { name: "Crystal", role: "Writing & ideas", pick: "Ideas crystallize on top. Writing, polishing, brainstorming." },+ orange: { name: "Pilot", role: "Translation & search", pick: "Goggles down, it scours the world for answers. Translation, search, computer use." },+ },+};diff --git a/ui/locales/en/botSettings.js b/ui/locales/en/botSettings.jsnew file mode 100644index 0000000..3499ed7--- /dev/null+++ b/ui/locales/en/botSettings.js@@ -0,0 +1,110 @@+// botSettings · en: bot settings (screens/bot-settings.js)+export default {+ back: "Back to chat",+ backTitle: "Back to chat (Esc)",+ title: "Bot settings",+ identity: "Identity",+ avatar: "Avatar",+ avatarHint: "Each character has its own little moves",+ name: "Name",+ prompt: "Persona / system prompt",+ promptHint: "Saved when you leave the field",+ promptPlaceholder: "e.g. You are a helpful assistant. Keep answers concise and accurate.",+ model: {+ head: "Model",+ default: "Default model",+ defaultSub: "You can still switch temporarily in a chat",+ followGlobal: "Use global default",+ followGlobalWith: "Use global default ({model})",+ utility: "Background task model",+ utilitySub: "Memory tidying, context steward, and handoff notes",+ sameAsChat: "Same as chat model",+ },+ budget: {+ name: "Budget",+ signedOut: "Sign in to Modelflare to set a separate spending limit for this bot",+ signIn: "Sign in",+ off: "Shares this device's key with other bots, with no separate limit",+ on: "Uses this bot's own key and stops at the limit",+ usage: "{used} used, {remain} left",+ exhausted: "{used} used, {remain} left · Used up — the bot has paused model calls",+ limit: "Limit (USD)",+ limitSub: "Includes what's already spent. Raising it restores a used-up key automatically.",+ limitLabel: "Budget limit (USD)",+ },+ perm: {+ head: "Permissions",+ name: "File access",+ workspaceSub: "Can only modify this bot's workspace; anything beyond needs your approval",+ readonlySub: "Can't modify files; commands run in a read-only sandbox",+ title: "Workspace write (default): can only modify this bot's workspace; anything beyond needs approval. Read-only: can't modify files; commands run in a read-only sandbox. Full access: commands run without a sandbox; only recursive deletes still need confirmation.",+ workspace: "Workspace write",+ readonly: "Read-only",+ full: "Full access",+ },+ memory: {+ head: "Memory",+ name: "Long-term memory",+ review: "Tidy up automatically after each turn",+ reviewLabel: "Auto-tidy memory",+ team: "Allow writing to team memory",+ teamSub: "Shared by all bots",+ teamLabel: "Team memory",+ },+ context: {+ head: "Context",+ name: "Auto-compact or start a new segment",+ sub: "Tidies up as the context grows and leaves a handoff note",+ label: "Context steward",+ },+ computer: {+ head: "Computer use",+ backend: "Backend",+ backendLabel: "Computer use backend",+ cuaNote: "Bundled · macOS / Windows / Linux",+ codex: "Codex bridge",+ macOnly: "macOS only",+ macOnlyUnavailable: "macOS only, unavailable on this device",+ approval: "Approval",+ approvalLabel: "Computer use approval",+ autoSub: "All actions run automatically",+ askSub: "Ask before clicks, typing, and other UI-changing actions; reading the screen stays automatic",+ auto: "Run automatically",+ ask: "Ask before UI changes",+ },+ danger: {+ head: "Danger zone",+ delete: "Delete bot",+ deleteSub: "Permanently delete this bot and all its conversations",+ },+ delete: {+ title: "Delete “{name}”?",+ body: "This permanently deletes the bot and all its conversations. This can't be undone.",+ confirm: "Delete permanently",+ },+ access: {+ head: "Who can use it",+ policy: "Only the owner and people you allow",+ owner: "{channel} owner",+ reset: "Change",+ resetOwnerTitle: "Change the {channel} owner?",+ resetOwnerBody: "The next person to message the bot becomes the {channel} owner, and \"{who}\" will need to be allowed again.",+ allowed: "Allowed",+ denied: "Denied",+ deniedSub: "Denied {when} · they get no reply if they message again",+ allow: "Allow",+ remove: "Remove",+ removeDeniedTitle: "Remove \"{who}\"?",+ removeDeniedBody: "If they message again after this, they'll show up again under usage requests in the info panel.",+ revokeTitle: "Stop allowing \"{who}\"?",+ revokeBody: "If they message again, they'll only get a short notice and will need to be allowed again.",+ },+ media: {+ head: "Images and video",+ confirm: "Confirm before generating",+ alwaysSub: "Ask me which model to use before every generation",+ autoSub: "Generate right away when the default model works and the cost is low; ask first when switching models, above about $0.5, or when the request is unclear",+ auto: "Ask when needed",+ always: "Always ask",+ },+};diff --git a/ui/locales/en/chat.js b/ui/locales/en/chat.jsnew file mode 100644index 0000000..a203fc6--- /dev/null+++ b/ui/locales/en/chat.js@@ -0,0 +1,95 @@+// chat · en+export default {+ aria: "Conversation with {name}",+ infoPanel: "Info panel (⌘⇧I)",+ newConvCmd: "New conversation (/new)",+ toBottom: "Scroll to bottom",+ copyMessage: "Copy message",+ commandsLabel: "Commands",+ commands: {+ stop: "Stop the message in progress",+ tasks: "List background tasks (/stop <number> stops one)",+ model: "List or switch models",+ new: "Start a new conversation (archives the old one with a handoff note)",+ reset: "Clear this conversation's context",+ status: "Show the current model, mode and progress",+ help: "Show all commands",+ },+ perm: {+ menu: "File access",+ title: "File access: {note}",+ workspace: "Workspace write",+ workspaceNote: "Can only edit this bot's workspace; asks you before going outside it",+ readonly: "Read only",+ readonlyNote: "Can't edit files; commands run in a read-only sandbox",+ more: "More permission settings…",+ },+ approval: {+ needed: "Needs your approval · {code}",+ fallbackReason: "The bot wants to do something outside its workspace",+ allowOnce: "Allow once",+ deny: "Deny",+ },+ question: {+ otherOptional: "Something else (optional)",+ yourAnswer: "Type your answer",+ orOther: "Or type a different answer",+ submit: "Submit",+ },+ file: {+ delivered: "Delivered to the bot's workspace · sent directly on WeChat/Feishu",+ },+ work: {+ stopping: "Stopping…{extra}",+ processedFor: " · ran for {d}",+ process: "Activity",+ done: "Worked for {d}",+ replying: "Replying for {d}",+ thinkingFor: "Thinking for {d}",+ thinking: "Thinking",+ },+ error: {+ stopFailed: "Couldn't stop: {error}",+ fixKey: "Update key",+ authInvalid: "Your Modelflare key is invalid or has been revoked.",+ loadHistory: "Couldn't load message history: {error}",+ },+ menu: {+ more: "More actions",+ switchModel: "Switch model…",+ newConv: "New conversation",+ reset: "Clear context",+ status: "Show status",+ allCommands: "All commands",+ },+ reset: {+ title: "Clear this conversation's context?",+ body: "{name} will forget what was said in this web conversation. Long-term memory is kept.",+ confirm: "Clear",+ },+ empty: {+ guideTitle: "Hi, I'm {name}",+ guideBody: "Take 5 minutes and walk through the checklist to see what I can do.",+ title: "Start chatting with {name}",+ body: "Test your bot right here. Set up Feishu and WeChat channels in the info panel.",+ sample: "What can you help me with?",+ helpChip: "/help for commands",+ },+ composer: {+ steer: "Add to the reply in progress",+ steerTitle: "Add to the reply in progress ({key})",+ stopping: "Stopping…",+ placeholder: "Message {name}, or type / for commands",+ label: "Message",+ currentModel: "Current model: {model}",+ pickModel: "Choose model",+ stop: "Stop generating (Esc)",+ stopTitle: "Stop (Esc)",+ send: "Send",+ sendTitle: "Send ({key})",+ },+ model: {+ followBot: "Use bot default",+ setDefault: "Set as this bot's default model",+ },+};diff --git a/ui/locales/en/common.js b/ui/locales/en/common.jsnew file mode 100644index 0000000..6a8e9bd--- /dev/null+++ b/ui/locales/en/common.js@@ -0,0 +1,50 @@+// common · en+export default {+ ok: "OK",+ cancel: "Cancel",+ close: "Close",+ confirm: "Confirm",+ save: "Save",+ saved: "Saved",+ delete: "Delete",+ edit: "Edit",+ rename: "Rename",+ retry: "Retry",+ refresh: "Refresh",+ open: "Open",+ openExternal: "Open ↗",+ view: "View",+ back: "Back",+ next: "Next",+ done: "Done",+ skip: "Skip",+ copy: "Copy",+ copied: "Copied",+ copyFailed: "Couldn't copy",+ loading: "Loading…",+ reading: "Loading…",+ error: "Something went wrong",+ failed: "Failed",+ unknown: "Unknown",+ none: "None",+ on: "On",+ off: "Off",+ enabled: "On",+ disabled: "Off",+ auto: "Auto",+ default: "Default",+ system: "System",+ more: "More",+ search: "Search",+ learnMore: "Learn more",+ connected: "Connected",+ notConnected: "Not connected",+ quoted: "“{name}”",+ sep: ", ",+ comma: ", ",+ colon: ": ",+ lang: {+ label: "Language",+ system: "System",+ },+};diff --git a/ui/locales/en/guide.js b/ui/locales/en/guide.jsnew file mode 100644index 0000000..25e4223--- /dev/null+++ b/ui/locales/en/guide.js@@ -0,0 +1,96 @@+// guide · en+export default {+ defaultBotName: "Ping",+ nameGeneric: "your bot",+ nameToast: "your bot",+ title: "Getting started",+ allDone: "Getting started complete",+ progress: "Getting started · {progress}",+ toastProgress: "Getting started {progress} · {title}",+ collapse: "Minimize to sidebar",+ demoThis: "Demo prompt",+ watchDemo: "Watch demo",+ tryThis: "Try this",+ sendThis: "Send",+ followHint: "Just follow the hints",+ takeMe: "Show me",+ completed: "Done",+ upNext: "Up next",+ hide: "Hide checklist",+ coachLabel: "Getting started guide",+ closeCoach: "Close guide",+ doneTitle: "Nice work!",+ fill: "Fill in",+ openConsole: "Enable image models in the Modelflare console ↗",+ later: "Maybe later",+ stopHere: "Done for now",+ next: "Next: {title}",+ demo: {+ detail: "Prompt: {prompt}\nSize 1024×1024 · 1 image\nThis is a built-in demo: no model is called and nothing is charged.",+ label: "Generate image · Demo",+ question: "Generate this image with “Sample image model”?",+ pickModel: "Choose a model",+ sampleModel: "Sample image model",+ sampleDesc: "Default · free in this demo",+ cancelDesc: "Don't generate this time",+ alt: "Sample image: a little blue robot wearing headphones, flat illustration style",+ generating: "Generating (demo)…",+ caption: "Sample image · bundled with the app, no model called",+ enable: "Enable image models ↗",+ cancelled: "Cancelled: nothing was generated or charged.",+ again: "Try again",+ },+ steps: {+ hello: {+ title: "Say hi to {name}",+ desc: "Chat with your bot right here. Replies stream in as they're written.",+ how: ["Enter to send, Shift + Enter for a new line", "Esc to stop it", "Type / to see all commands"],+ try: "What can you help me with?",+ doneText: "Come back here anytime. The checklist in the bottom left stays with you.",+ },+ model: {+ title: "Switch models",+ desc: "One account gets you GPT, Claude, Gemini and more, so different jobs can go to different models.",+ how: [+ "Click the model name at the bottom right of the input box and pick one",+ "Applies to this conversation only. To keep using it, click “Set as this bot's default model” at the bottom of the list",+ "Each model shows its context length, capabilities and estimated price",+ ],+ doneText: "Switched, for this conversation only. Ask it something.",+ },+ weixin: {+ title: "Connect {name} to WeChat",+ desc: "Scan a QR code, then message it directly in WeChat. No new app to install, and it's online whenever your computer is on.",+ how: ["Click the bot's name at the top to open the info panel", "Under “Channels”, click “WeChat” → “Scan to log in”", "Scan the code with WeChat and confirm on your phone"],+ note: "WeChat's rule: for each message you send, it can reply up to 10 times within 24 hours. For Feishu, enter your Feishu app's App ID and App Secret in the same place.",+ doneText: "Send it a message in WeChat: same bot, same memory.",+ },+ hands: {+ title: "Put it to work",+ desc: "It can write files and run commands in its own workspace, then hand you the results.",+ how: [+ "It only changes things in its own workspace",+ "Before touching files outside it, it asks you in the chat and waits for you to click “Allow once”",+ "Want to play it safe? Switch the permission at the bottom left of the input box to “Read only”",+ ],+ try: "Create “today-todo.md” in your workspace listing three things to do today, then send it to me.",+ doneText: "Finished files show up in the chat. In WeChat and Feishu, they're sent straight to you.",+ },+ memory: {+ title: "Let it remember you",+ desc: "Tell it your preferences and details you use often. It remembers them in new chats and in WeChat, but never stores passwords, keys and the like.",+ how: ["Just say “Remember…”. It also notes important things on its own as you chat", "To make it forget, say “Forget…”, or delete it under “Memory” in the info panel"],+ try: "Remember: keep answers short and lead with the conclusion.",+ doneText: "Got it. You can view or delete it under “Memory” in the info panel.",+ },+ media: {+ title: "Generate an image",+ desc: "It can make images and videos. Before each one, it asks which model to use and shows an estimated price. Nothing is charged until you confirm.",+ how: ["Describe the image you want", "Pick a model on the confirmation card in the chat and confirm", "If you don't answer within 10 minutes, nothing is generated"],+ try: "Draw a little blue robot wearing headphones, flat illustration style.",+ demoNote: "Watch the demo to see how it works: same flow as the real thing, but no model is called and nothing is charged.",+ doneText: "That was a demo. To make a real one, just ask. It'll check which model to use and show an estimated price first, and you only pay once you confirm.",+ noModelText: "That was a demo. Your account doesn't have an image model yet. Once you enable one, the same request gets you a real image.",+ },+ },+};diff --git a/ui/locales/en/index.js b/ui/locales/en/index.jsnew file mode 100644index 0000000..2c44af1--- /dev/null+++ b/ui/locales/en/index.js@@ -0,0 +1,26 @@+// en 文案:每个命名空间一个文件,键 = "命名空间.键"(见 ui/lib/i18n.js)。两种语言的键必须一一对应(test/i18n.unit.test.ts 会查)。+import common from "./common.js";+import app from "./app.js";+import time from "./time.js";+import settings from "./settings.js";+import account from "./account.js";+import pwsh from "./pwsh.js";+import chat from "./chat.js";+import info from "./info.js";+import markdown from "./markdown.js";+import notify from "./notify.js";+import troubleshoot from "./troubleshoot.js";+import onboarding from "./onboarding.js";+import newBot from "./newBot.js";+import botSettings from "./botSettings.js";+import sidebar from "./sidebar.js";+import avatar from "./avatar.js";+import models from "./models.js";+import ui from "./ui.js";+import guide from "./guide.js";+import activity from "./activity.js";+import tasks from "./tasks.js";+import access from "./access.js";+import perms from "./perms.js";++export default { common, app, time, settings, account, pwsh, chat, info, markdown, notify, troubleshoot, onboarding, newBot, botSettings, sidebar, avatar, models, ui, guide, activity, perms, access, tasks };diff --git a/ui/locales/en/info.js b/ui/locales/en/info.jsnew file mode 100644index 0000000..5a834bf--- /dev/null+++ b/ui/locales/en/info.js@@ -0,0 +1,77 @@+// info · en+export default {+ aria: "Info panel",+ botSettings: "Bot settings",+ closeTitle: "Close (⌘⇧I)",+ closeAria: "Close info panel",+ channels: "Channels",+ approvals: "Pending approvals",+ due: "Expires {time}",+ noApprovals: "No pending approvals",+ recent: "Recent conversations",+ noConvs: "No conversations yet",+ noMessages: "No messages",+ emptyMessage: "(empty)",+ channel: {+ web: "Web",+ feishu: "Feishu",+ weixin: "WeChat",+ },+ feishu: {+ bindHint: "Send the bot a message from your own Feishu account to finish binding.",+ sub: "Receives messages over a long connection",+ secretSaved: "Saved {masked} · leave blank to keep it",+ saveConnect: "Save and connect",+ disconnect: "Disconnect",+ disconnectTitle: "Disconnect Feishu?",+ disconnectBody: "This removes the bot's Feishu App ID and App Secret.",+ setupHint: "In the Feishu Open Platform, enable the Bot capability, set event subscription to “Receive events through long connection”, and subscribe to {event}. Permissions: {p1}, {p2}, {p3}.",+ },+ weixin: {+ sub: "Official iLink channel",+ linked: "Linked: {id}",+ qrAlt: "WeChat login QR code",+ scanHint: "Scan with WeChat, then confirm on your phone.",+ verifyCode: "Verification code",+ submit: "Submit",+ pausedUntil: "Paused until {time}",+ login: "Scan to log in",+ relogin: "Scan to log in again",+ enable: "Turn on WeChat channel",+ disable: "Turn off WeChat channel",+ unlink: "Unlink",+ unlinkTitle: "Unlink WeChat?",+ unlinkBody: "You'll need to scan the QR code again to send and receive WeChat messages.",+ quota: "Outbound quota (up to 10 messages within 24 hours of each incoming message): {list}",+ quotaItem: "{user}…: {count} left",+ quotaSep: "; ",+ },+ memory: {+ title: "Memory",+ refresh: "Refresh memory",+ empty: "No long-term memory yet",+ delete: "Delete this memory",+ deleteTitle: "Delete this memory?",+ deleted: "Deleted",+ },+ access: {+ head: "Usage requests",+ allowed: "Allowed \"{who}\"",+ denied: "Denied \"{who}\"",+ messages: { one: "sent {count} message", other: "sent {count} messages" },+ wants: "Wants to use this bot · pairing code {code}",+ quote: "\"{text}\"",+ allow: "Allow",+ deny: "Deny",+ replyHint: "You can also reply \"yes {code}\" in the chat.",+ },+ turn: {+ stopFailed: "Couldn't stop: {error}",+ processing: "Processing for {d}",+ waitingAgent: " · waiting for the agent process",+ idle: "No progress for {d}",+ stop: "Stop",+ activity: "Activity",+ },+ tasks: "Tasks",+};diff --git a/ui/locales/en/markdown.js b/ui/locales/en/markdown.jsnew file mode 100644index 0000000..497ce4c--- /dev/null+++ b/ui/locales/en/markdown.js@@ -0,0 +1,5 @@+// markdown · en+export default {+ code: "Code",+ copyCode: "Copy code",+};diff --git a/ui/locales/en/models.js b/ui/locales/en/models.jsnew file mode 100644index 0000000..0c87da8--- /dev/null+++ b/ui/locales/en/models.js@@ -0,0 +1,18 @@+// models · en: model picker (components/model-picker.js)+export default {+ otherFamily: "Other",+ caps: {+ vision: "Vision",+ tools: "Tools",+ reasoning: "Reasoning",+ },+ perCall: "{price}/call",+ noteTitle: "Context · Capabilities · Starting reference price per million tokens, input/output (USD; your bill is final)",+ choose: "Choose model",+ filter: "Filter models",+ filterOrId: "Filter, or enter any model ID",+ loadFailed: "Couldn't load models: {error}",+ useCustom: "Use “{id}”",+ customId: "Custom model ID",+ none: "No models available: this key's group doesn't have any models enabled yet",+};diff --git a/ui/locales/en/newBot.js b/ui/locales/en/newBot.jsnew file mode 100644index 0000000..eb71f00--- /dev/null+++ b/ui/locales/en/newBot.js@@ -0,0 +1,47 @@+// newBot · en: new bot screen (screens/new-bot.js)+export default {+ headName: "New bot",+ cancel: "Cancel (Esc)",+ firstTitle: "Create your first bot",+ title: "New bot",+ lead: "Pick a buddy, give it a name and a few lines of persona, or start from a template below.",+ name: "Name",+ namePlaceholder: "e.g. Group digest",+ persona: "Persona",+ personaHint: "Optional — you can change it later in bot settings",+ personaPlaceholder: "e.g. You are a helpful assistant. Keep answers concise and accurate.",+ create: "Create",+ fromTemplate: "Start from a template",+ tpl: {+ digest: {+ name: "Group digest",+ desc: "Turns group discussions into a daily digest: decisions, to-dos, and owners",+ prompt: "You are a group chat digest assistant. When asked for a summary, turn the group's discussion into a daily digest: start with up to three key decisions, then list to-dos (task, owner, due date), and finally list open questions. Only include what was actually said in the group — never make anything up.",+ },+ support: {+ name: "Support assistant",+ desc: "Answers customer questions from known info and hands off to a human when unsure",+ prompt: "You are a customer support assistant. Answer customer questions concisely and politely, based only on the information you have. If the answer isn't there or you're not sure, say you'll hand it off to a human — don't guess.",+ },+ translate: {+ name: "Translator",+ desc: "Translates between Chinese and English, keeping tone, terms, and formatting",+ prompt: "You are a translator. Translate English into Chinese, and any other language into English. Keep the original tone, terminology, and formatting (lists, code, links), and output only the translation.",+ },+ minutes: {+ name: "Meeting notes",+ desc: "Turns meeting notes into decisions, action items, and open questions",+ prompt: "You are a meeting notes assistant. Turn meeting notes or transcripts into: topic, decisions, action items (task, owner, deadline), and open questions. Keep it tight, and don't add anything that isn't in the notes.",+ },+ writer: {+ name: "Writing assistant",+ desc: "Drafts announcements, emails, and weekly reports, polished in your voice",+ prompt: "You are a writing assistant. Help me draft and polish announcements, emails, weekly reports, and other writing. First figure out the purpose and the audience, then deliver a finished draft — natural in tone, clearly structured, no filler.",+ },+ coder: {+ name: "Coding assistant",+ desc: "Reads code, writes scripts, and edits files in its own workspace",+ prompt: "You are a coding assistant. Read and modify the code in your workspace, and write scripts to solve problems. Explain your plan before you start; when you're done, explain what you changed and how to verify it.",+ },+ },+};diff --git a/ui/locales/en/notify.js b/ui/locales/en/notify.jsnew file mode 100644index 0000000..8ed7395--- /dev/null+++ b/ui/locales/en/notify.js@@ -0,0 +1,8 @@+// notify · en+export default {+ code: "[code]",+ image: "[image]",+ prompt: "Waiting for you: go back to the conversation to handle this step",+ replyDone: "Reply finished",+ replyError: "Something went wrong: {text}",+};diff --git a/ui/locales/en/onboarding.js b/ui/locales/en/onboarding.jsnew file mode 100644index 0000000..55b5e15--- /dev/null+++ b/ui/locales/en/onboarding.js@@ -0,0 +1,55 @@+// onboarding · en: onboarding screen (screens/onboarding.js: sign in, paste a key, pick a default model)+export default {+ slogan: "Any model, one assistant",+ gatewayFailed: "The built-in model gateway didn't start: {error}. Fix it, then restart the app and connect again.",+ unknownReason: "unknown reason",+ keyOnly: "Docker and remote deployments can't sign in through the browser. Enter an API key instead.",+ createKey: "Create a key in the Modelflare console ↗",+ line: {+ label: "Route",+ sub: "Use the optimized route when connecting from mainland China",+ global: "Global",+ cn: "China-optimized",+ },+ key: {+ label: "API key",+ placeholder: "Paste your Modelflare API key",+ paste: "Paste from clipboard",+ show: "Show",+ hide: "Hide",+ showKey: "Show key",+ hideKey: "Hide key",+ retype: "Re-enter",+ checkGroup: "Check the group in the console ↗",+ useCn: "Switch to the China-optimized route and retry",+ note: "Your key stays on this device and is never written to logs or command-line arguments.",+ connecting: "Connecting…",+ submit: "Connect Modelflare",+ slow: "The network is slow.",+ slowLine: "The network is slow. You can switch routes under Advanced.",+ advanced: "Advanced",+ },+ login: {+ label: "Sign in or sign up with Modelflare",+ waiting: "Finish signing in in your browser — you'll come back here automatically",+ reopen: "Reopen sign-in page ↗",+ copyLink: "Copy link",+ },+ model: {+ found: { one: "Connected · {n} model found", other: "Connected · {n} models found" },+ hint: "Pick a default model. You can switch anytime in a chat.",+ filter: "Filter models",+ default: "Default model",+ noMatch: "No matching models",+ mediaHint: "Default models for generating images and videos. You'll be asked before each generation and can switch then.",+ image: "Image",+ imageLabel: "Default image model",+ video: "Video",+ videoLabel: "Default video model",+ console: "Open console ↗",+ empty: "No models are available to this key's group yet. Enable models for the group in the console, then come back and refresh.",+ saving: "Saving…",+ start: "Start chatting",+ startAnyway: "Start anyway",+ },+};diff --git a/ui/locales/en/perms.js b/ui/locales/en/perms.jsnew file mode 100644index 0000000..a133c2e--- /dev/null+++ b/ui/locales/en/perms.js@@ -0,0 +1,12 @@+// perms · en+export default {+ workspace: "Workspace write",+ workspaceNote: "Can only change this bot's workspace; anything outside asks you first",+ readonly: "Read-only",+ readonlyNote: "Can't change files; commands run in a read-only sandbox",+ full: "Full access",+ fullNote: "Commands run without a sandbox and can read and change all your files; recursive deletes still ask first",+ fullWarning: "Commands run without a sandbox, directly as your user: they can read and change any file on your computer, including AnyModelBot's own data (conversation history, channel tokens and keys). Out-of-bounds actions no longer ask for approval; only recursive deletes (rm -r, Remove-Item -Recurse and the like) still ask first. Only turn this on when you trust the current model and task.",+ confirmTitle: "Turn on full access?",+ confirmLabel: "Turn on full access",+};diff --git a/ui/locales/en/pwsh.js b/ui/locales/en/pwsh.jsnew file mode 100644index 0000000..68782ff--- /dev/null+++ b/ui/locales/en/pwsh.js@@ -0,0 +1,51 @@+// pwsh · en+export default {+ slow: "Your bots currently run commands with the built-in Windows PowerShell 5.1, which can take 20–30 seconds per command",+ unknownReason: "unknown reason",+ privateSuffix: " (app-managed)",+ privatePrefix: "the app-managed ",+ progress: {+ waiting: "Preparing",+ downloading: "Downloading {received} / {total} MB{pct}",+ pct: " ({n}%)",+ extracting: "Extracting",+ verifying: "Verifying the signature",+ testing: "Test run",+ done: "Installed",+ failed: "Not installed: {error}",+ },+ found: "PowerShell {version}{private} detected. The agent switches to it when idle",+ notFound: "No working PowerShell 7 detected yet",+ notFoundInstalling: "No working PowerShell 7 yet; installing one for the agent",+ reinstalling: "Reinstalling PowerShell 7…",+ installing: "Installing PowerShell 7…",+ using: "The agent uses PowerShell {version}",+ modeSystem: "Switched back to the system default. Takes effect when the agent is idle",+ modePrivate: "Switched to the app-managed PowerShell 7",+ installingTitle: "Installing PowerShell 7 for the agent…",+ installingBody: "{progress}. Once it's installed, your bots run commands much faster (about 1 second each). No admin rights needed, and your own PowerShell isn't touched. Until then, commands keep using Windows PowerShell 5.1.",+ installedTitle: "PowerShell 7 is ready",+ installedBody: "From now on your bots run commands with the app-managed PowerShell {version} (Microsoft signature verified, test run passed), about 1 second each.",+ fallbackTitle: "PowerShell had a problem and was replaced automatically",+ fallbackBody: "{from} wouldn't start ({reason}). Your bots now run commands with {private}PowerShell {version}.",+ brokenTitle: "The app-managed PowerShell 7 can't be used",+ brokenBody: "{reason}. {slow}. Reinstalling usually fixes it.",+ failedTitle: "PowerShell 7 wasn't installed",+ failedBody: "{error}. {slow}.",+ unsupportedTitle: "PowerShell 7 can't be installed on this computer",+ unsupportedBody: "{reason}. {slow}.",+ title: "PowerShell 7 recommended",+ body: "{slow}. With PowerShell 7, commands run much faster and more reliably. {canInstall}",+ canInstall: "The app can install its own copy: no admin rights needed, and your own PowerShell isn't touched.",+ orRun: "Or run in a terminal",+ copyCommand: "Copy install command",+ oneClick: "Install",+ install: "Install PowerShell 7 ↗",+ installSelf: "Install it yourself ↗",+ reinstall: "Reinstall",+ retry: "Retry",+ checking: "Checking…",+ recheck: "Check again",+ ack: "Got it",+ dismiss: "Don't show again",+};diff --git a/ui/locales/en/settings.js b/ui/locales/en/settings.jsnew file mode 100644index 0000000..c4b356a--- /dev/null+++ b/ui/locales/en/settings.js@@ -0,0 +1,323 @@+// settings · en+export default {+ tabs: {+ general: "General",+ appearance: "Appearance",+ modelflare: "Modelflare",+ computer: "Computer use",+ privacy: "Privacy & security",+ network: "Network & access",+ data: "Data",+ troubleshoot: "Troubleshooting",+ about: "About",+ },+ gateway: {+ running: "Running",+ starting: "Starting",+ restarting: "Restarting",+ failed: "Failed",+ stopped: "Stopped",+ external: "External endpoint",+ },+ theme: { light: "Light", dark: "Dark" },+ textSize: { sm: "Small", md: "Default", lg: "Large", xl: "Extra large" },+ font: { system: "System", serif: "Serif", custom: "Custom" },+ width: { normal: "Default", wide: "Wide", full: "Full" },+ side: {+ label: "Settings",+ back: "Back to app",+ backTitle: "Back to app (Esc)",+ search: "Search settings",+ nav: "Settings sections",+ },+ searchResults: "Search results",+ noMatch: "No matching settings",+ preview: {+ ask: "Rewrite this request using async / await",+ reply: "Sure, and error handling gets clearer too. With {b} on, the line below wraps:",+ },+ rekey: {+ title: "Change Modelflare key",+ submit: "Verify and save",+ },+ disconnect: {+ title: "Disconnect Modelflare?",+ body: "This deletes the API key from this computer. Your bots and conversations stay, ready for when you reconnect.",+ confirm: "Disconnect",+ },+ logout: {+ title: "Sign out of Modelflare?",+ body: "This revokes this computer's access and deletes the API keys issued to it and your bots at sign-in. Your bots and conversations stay.",+ confirm: "Sign out",+ notRevoked: "The server didn't confirm the revocation. You're signed out here — you can revoke access again under Authorized apps on the Modelflare website",+ },+ notifyDenied: "Notifications aren't allowed. Allow them for this page in your system or browser site settings",+ rows: {+ language: {+ sub: "Used for the interface, the tray menu and system messages from your bots",+ keys: "language english chinese 中文", // i18n-ignore+ },+ sendKey: {+ name: "Send with",+ sub: "{key} adds a new line. Enter won't send while you're typing with an input method",+ keys: "send enter return new line newline shortcut keyboard",+ },+ notify: {+ name: "Notify when a reply is done",+ sub: "When the window isn't in front, show a system notification when a bot finishes replying or needs you to confirm",+ keys: "notification notify alert background",+ },+ close: {+ name: "When closing the window",+ sub: "While hidden in the tray, bots keep sending and receiving messages in the background",+ keys: "tray quit close minimize background",+ tray: "Hide to tray",+ quit: "Quit",+ },+ autostart: {+ name: "Launch at login",+ sub: "Start in the background after you log in",+ keys: "startup launch login boot autostart",+ },+ browser: {+ name: "Open in browser",+ sub: "Open this same local interface in your default browser",+ keys: "browser web",+ },+ guide: {+ name: "Getting-started checklist",+ hidden: "Hidden. Start over to bring it back on the chat page and at the bottom of the sidebar",+ progress: "Learn what your bots can do, one step at a time · {done}/{total} done",+ keys: "guide onboarding tutorial checklist getting started",+ restart: "Start over",+ restarted: "Checklist restarted",+ },+ theme: {+ name: "Theme",+ sub: "Light, dark, or match your system",+ keys: "theme appearance dark light night mode",+ },+ textSize: {+ name: "Text size",+ subDesktop: "Changes text only. To scale icons and spacing too, use Zoom below",+ sub: "Changes text only; icons and spacing stay the same",+ keys: "text size font size larger bigger",+ },+ font: {+ name: "Interface font",+ sub: "System default, serif, or any font installed on your computer",+ keys: "font family typeface serif",+ },+ fontName: {+ name: "Custom font",+ subSet: "Separate several fonts with commas to fall back in order. Fonts that aren't installed fall back to the system font",+ subEmpty: "Enter a font name, like Inter. Until then, the system font is used",+ keys: "font custom typeface",+ placeholder: "Font name",+ },+ codeFont: {+ name: "Code font",+ sub: "Monospace font for code blocks, commands and paths. Leave empty to use the system monospace font",+ keys: "code font monospace",+ placeholder: "System monospace",+ },+ zoom: {+ name: "Zoom",+ sub: "Make everything in the window bigger or smaller, including icons and spacing",+ keys: "zoom scale bigger smaller",+ },+ chatWidth: {+ name: "Chat width",+ sub: "Widen the conversation on large screens so long code and tables wrap less",+ keys: "width wide full conversation column",+ },+ codeWrap: {+ name: "Wrap code",+ sub: "Wrap long lines in code blocks instead of scrolling sideways",+ keys: "code wrap line wrap",+ },+ motion: {+ name: "Animations",+ sub: "When off, transitions, pop-ups and bot avatars stay still. System follows your Reduce motion setting",+ keys: "animation motion transition reduce motion",+ },+ glass: {+ name: "Frosted glass",+ sub: "When off, the sidebar, menus and dialogs use solid colors for clearer text and longer battery life. System follows your Reduce transparency setting",+ keys: "glass frosted blur transparency reduce transparency battery performance lag",+ },+ resetAppearance: {+ name: "Reset appearance",+ subDesktop: "Restore theme, fonts, zoom and all the settings above to their defaults",+ sub: "Restore theme, fonts and all the settings above to their defaults",+ keys: "reset restore default",+ button: "Reset",+ },+ account: {+ name: "Modelflare account",+ signedIn: "Signed in",+ enterprise: "{name} · Billed to your organization's wallet",+ signedOut: "Sign in to see usage, notifications and your invite link, and to set budgets for individual bots",+ keys: "account sign in sign up log in log out login",+ logout: "Sign out",+ noBrowserLogin: "Browser sign-in isn't available for Docker or remote deployments",+ login: "Sign in / Sign up",+ },+ connection: {+ name: "Connection",+ nameSignedIn: "This computer's key",+ subExternal: "Endpoint set by the AMB_MAGPIE_BASE_URL environment variable (development/testing)",+ subSignedIn: "Issued to this computer when you signed in; deleted when you sign out",+ sub: "Your API key is stored only on this computer",+ keys: "key api key disconnect change replace",+ rekey: "Change key",+ disconnect: "Disconnect",+ },+ balance: {+ name: "Balance",+ error: "Couldn't load: {error}",+ fromKey: "Wallet balance of the account this key belongs to",+ updated: "Updated {time}",+ keys: "balance top up wallet credit",+ refresh: "Refresh balance",+ topUp: "Top up ↗",+ },+ lowBalance: {+ name: "Low balance alert",+ sub: "Get one in-app alert when your balance drops below this amount. Resets after you top up",+ keys: "alert low balance reminder",+ none: "Off",+ },+ lowBalancePush: {+ name: "Also send alerts to WeChat / Feishu",+ sub: "Sent by your bot: on WeChat to whoever scanned the login QR code (they need to have messaged recently), on Feishu to the most recent direct chat",+ keys: "push alert wechat feishu lark",+ },+ usage: {+ name: "Usage",+ sub: "Spending by day and by model",+ keys: "usage spending cost billing",+ },+ notifications: {+ name: "Notifications",+ unread: "{count} unread",+ sub: "Notifications and announcements from Modelflare",+ keys: "notification announcement message",+ },+ invite: {+ name: "Invite friends",+ sub: "Earn a reward when friends sign up and top up through your link",+ keys: "invite referral reward",+ copy: "Copy invite link",+ },+ line: {+ name: "Route",+ sub: "The optimized route gives steadier access from mainland China. Applies to new requests",+ keys: "route mainland china global origin network",+ },+ defaultModel: {+ name: "Default model",+ sub: "Used when a bot doesn't set its own",+ keys: "default model",+ auto: "Auto (first in list)",+ },+ imageModel: {+ name: "Default image model",+ sub: "Used by default when a bot generates images. You'll confirm before each one",+ keys: "image picture generate model",+ },+ videoModel: {+ name: "Default video model",+ sub: "Used by default when a bot generates videos. You'll confirm before each one",+ keys: "video generate model",+ },+ autoModel: "Auto ({model})",+ models: {+ name: "Available models",+ error: "Couldn't load: {error}",+ sub: "Models open to this key's group",+ keys: "models list refresh",+ count: { one: "{count} model", other: "{count} models" },+ },+ console: {+ name: "Modelflare console",+ sub: "Billing, invoices and API key management",+ keys: "console dashboard billing invoice",+ },+ cuStatus: {+ name: "Computer use backend",+ keys: "computer use cua accessibility screen recording",+ },+ cuNotice: {+ name: "System permissions",+ keys: "permission permissions",+ },+ cuPerBot: {+ name: "Turn on per bot",+ sub: "Each bot can turn on computer use and set its own approval mode",+ keys: "bot bots",+ open: "Open bot settings",+ },+ keyStorage: {+ name: "Key storage",+ sub: "Your Modelflare key lives only in the built-in gateway's isolated config on this computer, never in logs or command-line arguments",+ keys: "security key storage",+ },+ accountStorage: {+ name: "Account credentials",+ sub: "Modelflare sign-in credentials are stored only in the data folder, encrypted with the system keychain on desktop. The interface only sees your account name",+ keys: "security sign in keychain credentials",+ },+ token: {+ name: "Access token",+ required: "Required: the interface listens on a non-local address, or the desktop app generates a random one at each launch",+ local: "Listening on this computer only, so no token is needed",+ keys: "token access",+ },+ sandbox: {+ name: "Bot sandbox",+ sub: "The local interface rejects requests from bot sandboxes, so bots can't approve their own actions or read your config",+ keys: "security dsh sandbox",+ },+ screens: {+ name: "Screenshots",+ sub: "Computer use screenshots go only to the model, never into chats",+ keys: "privacy screenshot",+ },+ listen: {+ name: "Listen address",+ sub: "To change it, set AMB_UI_HOST / AMB_UI_PORT and restart",+ keys: "port host address listen",+ copy: "Copy address",+ },+ dataDir: {+ name: "Data folder",+ sub: "SQLite, bot workspaces, WeChat sign-in state and built-in gateway config",+ keys: "path folder directory data",+ copy: "Copy path",+ },+ version: {+ name: "Version",+ keys: "version",+ },+ licenses: {+ name: "Licenses & third-party notices",+ sub: "MIT. Some interface styles adapted from magpie (MIT)",+ keys: "license licenses notices open source",+ },+ diagnostics: {+ name: "Diagnostics",+ gateway: "Built-in gateway",+ restarts: { one: "Restarted {count} time", other: "Restarted {count} times" },+ keys: "gateway magpie diagnostics",+ },+ troubleshoot: {+ sub: "Gateway and agent process status, model and agent tests, recent logs, and copying diagnostics",+ keys: "log logs test agent stuck spinning hang diagnostics restart PowerShell pwsh slow commands",+ },+ links: {+ sub: "Website and docs",+ docs: "Docs ↗",+ },+ },+};diff --git a/ui/locales/en/sidebar.js b/ui/locales/en/sidebar.jsnew file mode 100644index 0000000..47cfaf4--- /dev/null+++ b/ui/locales/en/sidebar.js@@ -0,0 +1,36 @@+// sidebar · en: sidebar (screens/sidebar.js)+export default {+ localUser: "Local user",+ settingsTitle: "Settings (⌘,)",+ openSettings: "Open Settings",+ balance: "Balance {amount}",+ lowBalance: "Only {amount} left — top up ↗",+ renamed: "Renamed",+ delete: {+ title: "Delete “{name}”?",+ body: "This permanently deletes the bot and all its conversations. This can't be undone.",+ confirm: "Delete permanently",+ },+ bots: "Bots",+ newShortcut: "New bot (⌘N)",+ search: "Search bots",+ list: "Bot list",+ newBot: "New bot",+ creating: "Creating…",+ loadFailed: "Couldn't load bots",+ empty: "No bots yet",+ create: "New bot",+ noMatch: "No matching bots",+ newName: "New name",+ working: "Working",+ workingNow: "Working…",+ noChats: "No conversations yet",+ pending: { one: "{count} pending approval", other: "{count} pending approvals" },+ moreFor: "More actions for {name}",+ actionsFor: "Actions for {name}",+ menu: {+ settings: "Bot settings",+ copyId: "Copy bot ID",+ delete: "Delete bot",+ },+};diff --git a/ui/locales/en/tasks.js b/ui/locales/en/tasks.jsnew file mode 100644index 0000000..ea5ddf0--- /dev/null+++ b/ui/locales/en/tasks.js@@ -0,0 +1,15 @@+// tasks · en+export default {+ cause: { launch: "Started", followup: "Continued after a follow-up", recover: "Resumed after a restart", retry: "Retry", continue: "Continued", answer: "Continued after your answer", manual: "Run manually" },+ run: "Run {n}",+ queued: "Queued",+ stopped: "Stopped \"{title}\"",+ latest: "Latest progress",+ folder: "Folder",+ stop: "Stop",+ stopping: "Stopping…",+ collapse: "Collapse",+ view: "View background task",+ chip: "Background task",+ minutes: { one: "{count} min", other: "{count} min" },+};diff --git a/ui/locales/en/time.js b/ui/locales/en/time.jsnew file mode 100644index 0000000..bfab5d0--- /dev/null+++ b/ui/locales/en/time.js@@ -0,0 +1,10 @@+// time · en+export default {+ today: "Today {time}",+ yesterday: "Yesterday {time}",+ dateTime: "{date} {time}",+ justNow: "Just now",+ minutesAgo: { one: "{count} min ago", other: "{count} min ago" },+ seconds: "{s}s",+ minSec: "{m}m {s}s",+};diff --git a/ui/locales/en/troubleshoot.js b/ui/locales/en/troubleshoot.jsnew file mode 100644index 0000000..cc235e5--- /dev/null+++ b/ui/locales/en/troubleshoot.js@@ -0,0 +1,145 @@+// troubleshoot · en+export default {+ status: "Status",+ checks: "Tests",+ version: "Version",+ dataDir: "Data folder",+ copyPath: "Copy path",+ logFile: "Log file",+ logFileSub: "Rotated by size; keeps the 4 most recent files",+ logFileOff: "Not enabled",+ test: "Test",+ model: "Model: {model}",+ none: "(none)",+ copyReport: "Copy diagnostics",+ copied: "Diagnostics copied (keys removed)",+ note: "Copied diagnostics include the status above, the latest test results, and logs. API keys, tokens, and other secrets are replaced with ***, so you can send it straight to support.",+ secs: "{s}s",+ restarts: { one: "Restarted once", other: "Restarted {count} times" },+ lastExit: "Last exit code={code}{signal}",+ verdict: {+ ok: "Healthy",+ bad: "Issues found",+ },+ gateway: {+ name: "Model gateway",+ fromEnv: "Set by {env}",+ running: "Running",+ starting: "Starting",+ restarting: "Restarting",+ failed: "Failed",+ stopped: "Stopped",+ external: "External endpoint",+ },+ agent: {+ name: "Agent process",+ nameFor: "Agent process · {bot}",+ noRuntime: "Agent runtime (DSH) not found; bots are chat-only",+ disabled: "Agent mode is off; bots are chat-only",+ startsOnFirst: "Starts when the first message arrives",+ stderr: { one: "Agent process output (last {count} line of stderr)", other: "Agent process output (last {count} lines of stderr)" },+ },+ host: {+ running: "Running",+ starting: "Starting",+ backoff: "Waiting to retry",+ error: "Paused",+ stopped: "Not started",+ },+ hostSub: {+ elapsed: "{time} elapsed",+ stage: "Stage: {stage}",+ firstStart: "First launch can take a few minutes (antivirus software scans each runtime file)",+ maxWait: { one: "Waits up to {count} minute", other: "Waits up to {count} minutes" },+ initTime: "Started in {time}",+ activeTurns: { one: "{count} turn in progress", other: "{count} turns in progress" },+ retryIn: { one: "Retrying automatically in {count} minute, or click “Restart agent process” below", other: "Retrying automatically in {count} minutes, or click “Restart agent process” below" },+ },+ init: {+ prepare: "Preparing",+ bridgeReady: "Model bridge ready",+ sdkLoaded: "Loading runtime",+ patchWritten: "Writing config",+ childSpawned: "Process started",+ initializing: "Initializing (loading plugins)",+ },+ stage: {+ ok: "Passed",+ warn: "Warning",+ fail: "Failed",+ timeout: "Timed out",+ skipped: "Skipped",+ pending: "In progress",+ },+ pwsh: {+ checking: "Checking",+ checkingBusy: "Checking…",+ missing: "Not installed",+ looking: "Looking for PowerShell 7",+ usedBy: "The agent runs commands with it",+ old: "Older version: install PowerShell 7 for much faster, more reliable commands",+ builtin: "The agent is running commands with the built-in Windows PowerShell 5.1, which can take 20–30 seconds each. Install PowerShell 7 for much faster, more reliable commands",+ recheck: "Check again",+ install: "Install PowerShell 7",+ copyCmd: "Copy install command",+ download: "Download ↗",+ fallback: "{from} wouldn't start ({reason}), so it was replaced automatically",+ unusable: "Unusable",+ notInstalled: "Not installed",+ usedByFrom: "The agent runs commands with it ({source})",+ installingSub: "Installing PowerShell 7 for the agent (no admin rights needed); until then, commands keep using Windows PowerShell 5.1",+ badSub: "The app-managed PowerShell 7 can't be used: {reason}",+ failedSub: "Not installed: {error}",+ unknownReason: "unknown reason",+ using51: "The agent uses Windows PowerShell 5.1 for now",+ slow51: "The agent is using Windows PowerShell 5.1, which can take 20–30 seconds per command",+ slow51Advice: "The agent is using Windows PowerShell 5.1, which can take 20–30 seconds per command; PowerShell 7 is much faster",+ reinstall: "Reinstall",+ installShort: "Install",+ reinstallPrivate: "Reinstall the app-managed PowerShell 7",+ useSystem: "Switch back to the system default",+ useSystemNote: "Stop using the app-managed PowerShell 7",+ usePrivate: "Use the app-managed PowerShell 7",+ installSelf: "Install PowerShell 7 yourself…",+ more: "More",+ moreLabel: "More PowerShell actions",+ source: {+ private: "App-managed",+ programFiles: "Program Files",+ preview: "Preview",+ },+ },+ testModel: {+ name: "Test model",+ sub: "Sends one minimal request through the built-in gateway and one directly to the endpoint, then compares status codes, latency, and the echoed model name",+ viaGateway: "Via built-in gateway",+ direct: "Direct to endpoint",+ },+ probe: {+ untested: "Not tested",+ ok: "OK",+ echoed: "Echoed model {model}",+ reply: "Reply “{reply}”",+ },+ testAgent: {+ name: "Test agent",+ sub: "Runs one minimal turn through the agent process (not saved to chat history) to find where it gets stuck: start → plugins → model → reply",+ ok: "Agent is working",+ stuckAt: "Stuck at: {stage}",+ bot: "Bot: {name}",+ total: "Total {time}",+ },+ restart: {+ name: "Restart agent process",+ sub: "Use this when replies keep spinning: stops the agent process and clears the retry wait. It restarts with the next message",+ button: "Restart",+ done: "Agent process restarted",+ notRunning: "The agent process hasn't started yet; it will start with the next message",+ },+ logs: {+ title: "Recent logs",+ lines: { one: "{count} line", other: "{count} lines" },+ empty: "(no logs yet)",+ readFailed: "Couldn't read logs: {error}",+ },+};diff --git a/ui/locales/en/ui.js b/ui/locales/en/ui.jsnew file mode 100644index 0000000..aba0f58--- /dev/null+++ b/ui/locales/en/ui.js@@ -0,0 +1,30 @@+// ui · en+export default {+ state: {+ disabled: "Off",+ connecting: "Connecting",+ connected: "Connected",+ error: "Error",+ expired: "Expired",+ paused: "Paused",+ login_required: "Not signed in",+ running: "Running",+ starting: "Starting",+ restarting: "Restarting",+ failed: "Failed",+ stopped: "Stopped",+ wait: "Waiting for scan",+ scaned: "Scanned",+ need_verifycode: "Code required",+ confirmed: "Confirmed",+ already_bound: "Linked",+ cancelled: "Cancelled",+ idle: "Idle",+ fetching: "Fetching",+ pending: "Pending",+ allowed: "Approved",+ rejected: "Denied",+ answered: "Answered",+ denied: "Denied",+ },+};diff --git a/ui/locales/zh-CN/access.js b/ui/locales/zh-CN/access.jsnew file mode 100644index 0000000..d9e4c5f--- /dev/null+++ b/ui/locales/zh-CN/access.js@@ -0,0 +1,11 @@+// access · zh-CN+export default {+ channel: { web: "网页", feishu: "飞书", weixin: "微信" },+ source: {+ request: "你允许的",+ migration: "升级前已在使用",+ "previous-owner": "之前的主人",+ app: "在应用里添加",+ test: "测试",+ },+};diff --git a/ui/locales/zh-CN/account.js b/ui/locales/zh-CN/account.jsnew file mode 100644index 0000000..34c4b40--- /dev/null+++ b/ui/locales/zh-CN/account.js@@ -0,0 +1,23 @@+// account · zh-CN(screens/account.js)+export default {+ login: {+ title: "登录 Modelflare 账户",+ hint: "登录后会替换现在填的 API Key。",+ },+ usage: {+ title: "用量",+ days: "{n} 天",+ range: "范围",+ total: "合计 {amount}",+ daily: "每日花费",+ bar: "{date}:{amount},{count} 次请求",+ byModel: "按模型",+ requests: "{count} 次",+ empty: "这段时间没有用量",+ },+ notifications: {+ title: "Modelflare 通知",+ empty: "没有通知",+ details: "查看详情 ↗",+ },+};diff --git a/ui/locales/zh-CN/activity.js b/ui/locales/zh-CN/activity.jsnew file mode 100644index 0000000..e607226--- /dev/null+++ b/ui/locales/zh-CN/activity.js@@ -0,0 +1,24 @@+// activity · zh-CN(components/activity.js:回复上方的工作状态行与处理过程)+export default {+ lessThanTenth: "<0.1 秒",+ seconds: "{s} 秒",+ waitingModel: "等待 {model} 回复",+ runningTool: "运行 {tool}",+ subagent: "子代理在工作",+ compact: "压缩上下文",+ job: "后台命令在运行",+ stepLabel: "{status}:{title}",+ failed: "失败",+ running: "进行中",+ done: "完成",+ expandDetail: "{label},展开详情",+ collapseDetail: "{label},收起详情",+ tokens: "输入 {input} tokens · 输出 {output} tokens",+ input: "参数",+ reply: "回复",+ output: "输出",+ noSteps: "还没有步骤",+ expand: "查看处理过程",+ collapse: "收起处理过程",+ steps: { other: "{count} 步" },+};diff --git a/ui/locales/zh-CN/app.js b/ui/locales/zh-CN/app.jsnew file mode 100644index 0000000..d80906c--- /dev/null+++ b/ui/locales/zh-CN/app.js@@ -0,0 +1,39 @@+// app · zh-CN(ui/main.js:命令面板、全局提示)+export default {+ palette: {+ title: "命令面板",+ placeholder: "输入命令或机器人名称",+ inputLabel: "命令",+ empty: "没有匹配的命令",+ },+ cmd: {+ settings: "打开设置",+ settingsKeys: "settings preferences 设置 偏好",+ newBot: "新建机器人",+ newBotKeys: "new bot 新建 机器人",+ openInfo: "打开信息面板",+ closeInfo: "关闭信息面板",+ infoKeys: "info panel 信息面板",+ botSettings: "「{name}」的设置",+ botSettingsKeys: "bot settings 机器人设置",+ modelflare: "Modelflare 设置",+ modelflareKeys: "modelflare key 密钥 模型",+ appearance: "外观设置",+ appearanceKeys: "appearance 外观 字体 字号 动画 毛玻璃 宽度 font size motion",+ themeSystem: "主题:跟随系统",+ themeKeys: "theme appearance 外观 主题",+ themeLight: "主题:浅色",+ themeLightKeys: "theme light 外观 主题",+ themeDark: "主题:深色",+ themeDarkKeys: "theme dark 外观 主题 暗色",+ lang: "语言:{name}",+ langKeys: "language 语言 中文 英文 English",+ switchBot: "切换到「{name}」",+ },+ lowBalance: "Modelflare 余额只剩 {amount} 美元",+ serviceDown: "无法连接本机服务:{error}",+ resizeSide: "调整侧栏宽度",+ resizePanel: "调整信息面板宽度",+ botMissing: "机器人不存在",+ backToChat: "返回对话",+};diff --git a/ui/locales/zh-CN/avatar.js b/ui/locales/zh-CN/avatar.jsnew file mode 100644index 0000000..c3d3955--- /dev/null+++ b/ui/locales/zh-CN/avatar.js@@ -0,0 +1,13 @@+// avatar · zh-CN:机器人头像角色(components/avatar.js)+export default {+ label: "头像",+ /** 每个角色:name 名字、role 定位、pick 介绍(头像选择器的提示里显示) */+ chars: {+ blue: { name: "小蓝", role: "主角 · 通用助手", pick: "天线一直在线,什么信号都接得住。默认助手、会议纪要。" },+ yellow: { name: "小萌", role: "客服 · 陪聊", pick: "头顶一颗小星星,一笑就脸红。客服、答疑、陪聊。" },+ green: { name: "绿草", role: "日报 · 整理", pick: "每天长高一点点。群聊日报、记忆整理、知识库。" },+ red: { name: "红魔", role: "代码 · 自动化", pick: "戴上耳机就进入状态。写代码、跑脚本、自动化。" },+ purple: { name: "紫钻", role: "写作 · 创意", pick: "灵感会在头顶结晶。写作、润色、出点子。" },+ orange: { name: "探险者", role: "翻译 · 搜索", pick: "护目镜一戴,满世界找答案。翻译、搜索、操作电脑。" },+ },+};diff --git a/ui/locales/zh-CN/botSettings.js b/ui/locales/zh-CN/botSettings.jsnew file mode 100644index 0000000..30850c4--- /dev/null+++ b/ui/locales/zh-CN/botSettings.js@@ -0,0 +1,110 @@+// botSettings · zh-CN:机器人设置(screens/bot-settings.js)+export default {+ back: "返回对话",+ backTitle: "返回对话(Esc)",+ title: "机器人设置",+ identity: "身份",+ avatar: "头像",+ avatarHint: "每个角色有自己的小动作",+ name: "名称",+ prompt: "人设 / 系统提示词",+ promptHint: "离开输入框时保存",+ promptPlaceholder: "例如:你是一个乐于助人的中文助手,回答简洁准确。",+ model: {+ head: "模型",+ default: "默认模型",+ defaultSub: "会话里还可以临时切换",+ followGlobal: "跟随全局默认",+ followGlobalWith: "跟随全局默认({model})",+ utility: "后台小任务模型",+ utilitySub: "记忆整理、上下文管家与交接便条",+ sameAsChat: "与对话模型相同",+ },+ budget: {+ name: "预算",+ signedOut: "登录 Modelflare 账户后,可以给这个机器人单独设花费上限",+ signIn: "去登录",+ off: "与其他机器人共用本机的 Key,不单独限额",+ on: "用这个机器人自己的 Key,花到上限就停",+ usage: "已用 {used},还剩 {remain}",+ exhausted: "已用 {used},还剩 {remain} · 已用完,机器人暂停调用模型",+ limit: "上限(美元)",+ limitSub: "包括已经花掉的部分;调高后用完的 Key 会自动恢复",+ limitLabel: "预算上限(美元)",+ },+ perm: {+ head: "权限",+ name: "文件权限",+ workspaceSub: "只能改本机器人工作区,越界操作需要你批准",+ readonlySub: "不能改文件,命令在只读沙箱中运行",+ title: "工作区可写(默认):只能改本机器人工作区,越界操作需审批;只读:不能改文件,命令在只读沙箱中运行;完全权限:命令不经沙箱,只有递归删除仍需确认",+ workspace: "工作区可写",+ readonly: "只读",+ full: "完全权限",+ },+ memory: {+ head: "记忆",+ name: "长期记忆",+ review: "回合结束后自动整理",+ reviewLabel: "自动整理记忆",+ team: "允许写入团队记忆",+ teamSub: "所有机器人共享",+ teamLabel: "团队记忆",+ },+ context: {+ head: "上下文",+ name: "自动压缩或开新段",+ sub: "上下文变长时整理,并留下交接便条",+ label: "上下文管家",+ },+ computer: {+ head: "电脑操作",+ backend: "后端",+ backendLabel: "电脑操作后端",+ cuaNote: "随附,macOS / Windows / Linux",+ codex: "Codex 桥",+ macOnly: "仅 macOS",+ macOnlyUnavailable: "仅 macOS,本机不可用",+ approval: "审批",+ approvalLabel: "电脑操作审批",+ autoSub: "所有操作自动执行",+ askSub: "点击、输入等改变界面的操作先问我;读取界面仍自动",+ auto: "自动执行",+ ask: "改变界面前先问我",+ },+ danger: {+ head: "危险操作",+ delete: "删除机器人",+ deleteSub: "永久删除这个机器人及其全部会话",+ },+ delete: {+ title: "删除「{name}」?",+ body: "会永久删除这个机器人及其全部会话,无法恢复。",+ confirm: "永久删除",+ },+ access: {+ head: "谁能使用",+ policy: "只有主人和你允许的人",+ owner: "{channel}主人",+ reset: "更换",+ resetOwnerTitle: "更换{channel}主人?",+ resetOwnerBody: "下一个给机器人发消息的人会成为{channel}主人,「{who}」需要重新被允许。",+ allowed: "允许名单",+ denied: "拒绝过的人",+ deniedSub: "{when}拒绝 · 他再发消息不会收到任何回复",+ allow: "允许",+ remove: "移除",+ removeDeniedTitle: "移除「{who}」?",+ removeDeniedBody: "移除后他再发消息,会重新出现在信息面板的使用请求里。",+ revokeTitle: "不再允许「{who}」使用?",+ revokeBody: "他再发消息时只会收到一句提示,需要你重新允许。",+ },+ media: {+ head: "生图 / 生视频",+ confirm: "生成前确认",+ alwaysSub: "每次生成前都问我用哪个模型",+ autoSub: "默认模型能用、花费不高时直接生成;换模型、预计超过 $0.5 或要求不明确时先问我",+ auto: "需要时再问",+ always: "每次都问",+ },+};diff --git a/ui/locales/zh-CN/chat.js b/ui/locales/zh-CN/chat.jsnew file mode 100644index 0000000..a033904--- /dev/null+++ b/ui/locales/zh-CN/chat.js@@ -0,0 +1,97 @@+// chat · zh-CN(screens/chat.js:对话页、输入框、审批 / 提问卡片)+export default {+ aria: "和 {name} 的对话",+ infoPanel: "信息面板(⌘⇧I)",+ newConvCmd: "开始新的一段对话(/new)",+ toBottom: "回到底部",+ copyMessage: "复制这条消息",+ commandsLabel: "命令",+ commands: {+ stop: "中止正在处理的消息",+ tasks: "列出后台任务(/stop 编号 停止一个)",+ model: "列出或切换模型",+ new: "开始新的一段对话(旧对话归档并留交接便条)",+ reset: "清空本会话上下文",+ status: "查看当前模型、运行方式和处理进度",+ help: "显示全部命令",+ },+ perm: {+ menu: "文件权限",+ title: "文件权限:{note}",+ workspace: "工作区可写",+ workspaceNote: "只能改这个机器人的工作区,越界操作先问你",+ readonly: "只读",+ readonlyNote: "不能改文件,命令在只读沙箱里运行",+ more: "更多权限设置…",+ },+ approval: {+ needed: "需要你的批准 · {code}",+ fallbackReason: "机器人想执行一个超出工作区的操作",+ allowOnce: "允许(仅本次)",+ deny: "拒绝",+ },+ question: {+ otherOptional: "其他回答(可选)",+ yourAnswer: "输入你的回答",+ orOther: "或者输入其他回答",+ submit: "提交",+ },+ file: {+ delivered: "已交付到机器人工作区 · 微信/飞书会直接发送",+ },+ /** 回复上方的工作状态;{d} 是 fmtDur 的用时 */+ work: {+ stopping: "正在停止…{extra}",+ processedFor: " 已处理 {d}",+ process: "处理过程",+ done: "用时 {d}",+ replying: "正在回复 {d}",+ thinkingFor: "思考中 {d}",+ thinking: "思考中",+ },+ error: {+ stopFailed: "停止失败:{error}",+ fixKey: "去更新",+ authInvalid: "Modelflare 密钥失效或已被撤销。",+ loadHistory: "读取历史消息失败:{error}",+ },+ menu: {+ more: "更多操作",+ switchModel: "切换模型…",+ newConv: "开始新的一段对话",+ reset: "清空上下文",+ status: "查看状态",+ allCommands: "全部命令",+ },+ reset: {+ title: "清空本会话上下文?",+ body: "「{name}」会忘掉这段网页对话的内容;长期记忆保留。",+ confirm: "清空",+ },+ empty: {+ guideTitle: "嗨,我是{name}",+ guideBody: "花 5 分钟,跟着清单认识一下我能做什么。",+ title: "和 {name} 开始对话",+ body: "在这里直接测试机器人;飞书和微信渠道在信息面板里配置。",+ /** 点一下就发给机器人的示例问题 */+ sample: "你能帮我做什么?",+ helpChip: "/help 查看命令",+ },+ composer: {+ steer: "补充给正在进行的回复",+ steerTitle: "补充给正在进行的回复({key})",+ stopping: "正在停止…",+ placeholder: "给「{name}」发消息,/ 查看命令",+ label: "消息",+ currentModel: "当前模型:{model}",+ pickModel: "选择模型",+ stop: "停止生成(Esc)",+ stopTitle: "停止(Esc)",+ send: "发送",+ sendTitle: "发送({key})",+ },+ model: {+ followBot: "跟随机器人默认",+ setDefault: "设为此机器人的默认模型",+ },+};diff --git a/ui/locales/zh-CN/common.js b/ui/locales/zh-CN/common.jsnew file mode 100644index 0000000..4de7864--- /dev/null+++ b/ui/locales/zh-CN/common.js@@ -0,0 +1,53 @@+// common · zh-CN:多处共用的短词。只放意思完全相同、语气也通用的词;带上下文的文案放各自的命名空间。+export default {+ ok: "好",+ cancel: "取消",+ close: "关闭",+ confirm: "确定",+ save: "保存",+ saved: "已保存",+ delete: "删除",+ edit: "编辑",+ rename: "重命名",+ retry: "重试",+ refresh: "刷新",+ open: "打开",+ openExternal: "打开 ↗",+ view: "查看",+ back: "返回",+ next: "下一步",+ done: "完成",+ skip: "跳过",+ copy: "复制",+ copied: "已复制",+ copyFailed: "复制失败",+ loading: "加载中…",+ reading: "读取中…",+ error: "出错了",+ failed: "失败",+ unknown: "未知",+ none: "无",+ on: "开启",+ off: "关闭",+ enabled: "已开启",+ disabled: "已关闭",+ auto: "自动",+ default: "默认",+ system: "跟随系统",+ more: "更多",+ search: "搜索",+ learnMore: "了解更多",+ connected: "已连接",+ notConnected: "未连接",+ /** 名字两边的引号:「助手」 / “Assistant” */+ quoted: "「{name}」",+ /** 中文顿号 / 英文逗号:列举短词时用 */+ sep: "、",+ /** 句中的分隔:"A · B" 两种语言相同,这里放的是"A,B"那种 */+ comma: ",",+ colon: ":",+ lang: {+ label: "语言",+ system: "跟随系统",+ },+};diff --git a/ui/locales/zh-CN/guide.js b/ui/locales/zh-CN/guide.jsnew file mode 100644index 0000000..0305e9f--- /dev/null+++ b/ui/locales/zh-CN/guide.js@@ -0,0 +1,96 @@+// guide · zh-CN:新手引导(上手清单)。lib/guide.js 的步骤文案 + components/guide.js 的界面+export default {+ /** 文案里 {name} 的缺省值:主角机器人的名字 */+ defaultBotName: "小蓝",+ /** 清单菜单里各步骤标题的 {name}(不针对某个机器人) */+ nameGeneric: "机器人",+ /** 完成一步时提示里的 {name} */+ nameToast: "它",+ title: "上手清单",+ allDone: "上手清单全部完成",+ /** 「上手清单 · 3/6」;progress 可以是带样式的数字 */+ progress: "上手清单 · {progress}",+ toastProgress: "上手清单 {progress} · {title}",+ collapse: "收起到左下角",+ demoThis: "演示这句",+ watchDemo: "看演示",+ tryThis: "试试这句",+ sendThis: "发送这句",+ followHint: "跟着提示点一下就好",+ takeMe: "带我去",+ completed: "已完成",+ upNext: "接下来做这个",+ hide: "不再显示清单",+ coachLabel: "上手引导",+ closeCoach: "关闭引导",+ doneTitle: "做好了",+ fill: "填入",+ openConsole: "去 Modelflare 控制台开通图片模型 ↗",+ later: "稍后再说",+ stopHere: "先到这里",+ next: "下一步:{title}",+ demo: {+ detail: "提示词:{prompt}\n尺寸 1024×1024 · 1 张\n这是预置演示:不调用模型,也不扣费。",+ label: "生成图片 · 预置演示",+ question: "这次用「示例图片模型」生成图片吗?",+ pickModel: "选择模型",+ sampleModel: "示例图片模型",+ sampleDesc: "默认 · 演示不扣费",+ cancelDesc: "这次不生成",+ alt: "示例图:戴着耳机的蓝色小机器人,扁平插画风",+ generating: "正在生成(演示)…",+ caption: "示例图 · 客户端自带,没有调用模型",+ enable: "开通图片模型 ↗",+ cancelled: "已取消:没有生成,也没有扣费。",+ again: "再来一次",+ },+ /**+ * 各步骤(id 与 src/guide.ts 的 GUIDE_STEPS 一致):title、desc、how(几条怎么做)、try(可以一键发出的示例,没有就不给按钮)、+ * note、doneText(做完后);生图那一步另有 demoNote、noModelText(账户还没有图片模型时的 doneText)。{name} = 机器人的名字+ */+ steps: {+ hello: {+ title: "跟{name}打个招呼",+ desc: "在这里直接和机器人聊天,回复会边写边出来。",+ how: ["Enter 发送,Shift + Enter 换行", "Esc 让它停下", "输入 / 查看全部命令"],+ try: "你能帮我做什么?",+ doneText: "以后在这里随时找它;左下角的清单会一直陪着你。",+ },+ model: {+ title: "换个模型",+ desc: "一个账户就能用 GPT、Claude、Gemini 等模型,不同的事可以交给不同的模型。",+ how: ["点输入框右下角的模型名,挑一个就换好了", "只对这段对话生效;想一直用它,点列表底部的「设为此机器人的默认模型」", "每个模型都标着上下文长度、能力和参考价"],+ doneText: "换好了,只对这段对话生效。问它一句试试。",+ },+ weixin: {+ title: "把{name}接到微信",+ desc: "扫码后,在微信里直接私聊它,不用装新 App。电脑开着,它就在线。",+ how: ["点顶部的机器人名字,打开信息面板", "在「渠道」里点「微信」→「扫码登录」", "用微信扫码,在手机上确认"],+ note: "微信的规定:你每发一条消息,它 24 小时内最多回 10 条。用飞书的话,在同一处填飞书应用的 App ID 和 App Secret。",+ doneText: "在微信里给它发条消息试试:同一个机器人,同一份记忆。",+ },+ hands: {+ title: "让它动手做件事",+ desc: "它能在自己的工作区里写文件、跑命令,做好的文件会交给你。",+ how: ["它只改自己工作区里的东西", "要动工作区以外的文件,会先在对话里问你,你点「允许」才做", "不放心?把输入框左下角的权限切成「只读」"],+ try: "在你的工作区建一个「今日待办.md」,列三件今天要做的事,然后发给我。",+ doneText: "做好的文件在对话里;在微信、飞书里会直接发给你。",+ },+ memory: {+ title: "让它记住你",+ desc: "告诉它你的习惯和常用信息,开新对话、到微信里它都记得。密码、密钥这类内容它不会记。",+ how: ["说「记住……」就行,聊天中它也会自己记下重要的事", "想让它忘掉,说「忘掉……」,或在信息面板的「记忆」里删掉"],+ try: "记住:回答尽量简短,结论放在最前面。",+ doneText: "记下了。信息面板的「记忆」里能看到、也能删掉。",+ },+ media: {+ title: "生成一张图",+ desc: "它可以画图、做视频。每次生成前都会先问你用哪个模型,并给出参考价,你确认了才会花钱。",+ how: ["描述你想要的画面", "在对话里的确认卡片上选模型、确认", "10 分钟内没回答就不生成"],+ try: "画一只戴着耳机的蓝色小机器人,扁平插画风。",+ demoNote: "看一遍演示就知道怎么操作:流程和真的一样,但不调用模型、不扣费。",+ doneText: "刚才是演示。想真的画,直接跟它说一句;生成前它会先问你用哪个模型、标出参考价,你确认了才花钱。",+ noModelText: "刚才是演示。你的账户暂时还没有可用的图片模型,开通后同样一句话它就会真的画给你。",+ },+ },+};diff --git a/ui/locales/zh-CN/index.js b/ui/locales/zh-CN/index.jsnew file mode 100644index 0000000..2325b54--- /dev/null+++ b/ui/locales/zh-CN/index.js@@ -0,0 +1,26 @@+// zh-CN 文案:每个命名空间一个文件,键 = "命名空间.键"(见 ui/lib/i18n.js)。两种语言的键必须一一对应(test/i18n.unit.test.ts 会查)。+import common from "./common.js";+import app from "./app.js";+import time from "./time.js";+import settings from "./settings.js";+import account from "./account.js";+import pwsh from "./pwsh.js";+import chat from "./chat.js";+import info from "./info.js";+import markdown from "./markdown.js";+import notify from "./notify.js";+import troubleshoot from "./troubleshoot.js";+import onboarding from "./onboarding.js";+import newBot from "./newBot.js";+import botSettings from "./botSettings.js";+import sidebar from "./sidebar.js";+import avatar from "./avatar.js";+import models from "./models.js";+import ui from "./ui.js";+import guide from "./guide.js";+import activity from "./activity.js";+import tasks from "./tasks.js";+import access from "./access.js";+import perms from "./perms.js";++export default { common, app, time, settings, account, pwsh, chat, info, markdown, notify, troubleshoot, onboarding, newBot, botSettings, sidebar, avatar, models, ui, guide, activity, perms, access, tasks };diff --git a/ui/locales/zh-CN/info.js b/ui/locales/zh-CN/info.jsnew file mode 100644index 0000000..ef3b1b6--- /dev/null+++ b/ui/locales/zh-CN/info.js@@ -0,0 +1,81 @@+// info · zh-CN(screens/info-panel.js:信息面板)+export default {+ aria: "信息面板",+ botSettings: "机器人设置",+ closeTitle: "关闭(⌘⇧I)",+ closeAria: "关闭信息面板",+ channels: "渠道",+ approvals: "待审批",+ /** 审批卡片的截止时刻(HH:MM) */+ due: "截止 {time}",+ noApprovals: "没有待处理的审批",+ recent: "最近会话",+ noConvs: "还没有会话",+ noMessages: "没有消息",+ /** 会话没有最后一条消息时 */+ emptyMessage: "(空)",+ channel: {+ web: "网页",+ feishu: "飞书",+ weixin: "微信",+ },+ feishu: {+ bindHint: "用你自己的飞书给机器人发一句话,就完成绑定。",+ sub: "长连接接收消息",+ secretSaved: "已保存 {masked},留空则不修改",+ saveConnect: "保存并连接",+ disconnect: "断开",+ disconnectTitle: "断开飞书?",+ disconnectBody: "会清除这个机器人的飞书 App ID 与 App Secret。",+ /** {event} {p1} {p2} {p3} 是 <code> 包着的事件名 / 权限名 */+ setupHint: "在飞书开放平台启用「机器人」,事件订阅选「使用长连接接收事件」并订阅 {event};权限:{p1}、{p2}、{p3}。",+ },+ weixin: {+ sub: "iLink 官方通道",+ linked: "已绑定 {id}",+ qrAlt: "微信登录二维码",+ scanHint: "用微信扫一扫,然后在手机上确认。",+ verifyCode: "验证码",+ submit: "提交",+ pausedUntil: "暂停至 {time}",+ login: "扫码登录",+ relogin: "重新扫码登录",+ enable: "启用微信渠道",+ disable: "停用微信渠道",+ unlink: "解除绑定",+ unlinkTitle: "解除微信绑定?",+ unlinkBody: "解除后需要重新扫码才能收发微信消息。",+ quota: "出站配额(每条入站消息后 24 小时内最多 10 条):{list}",+ /** {user} 是用户 id 的前 8 位 */+ quotaItem: "{user}… 剩 {count} 条",+ quotaSep: ";",+ },+ memory: {+ title: "记忆",+ refresh: "刷新记忆",+ empty: "还没有长期记忆",+ delete: "删除这条记忆",+ deleteTitle: "删除这条记忆?",+ deleted: "已删除",+ },+ access: {+ head: "使用请求",+ allowed: "已允许「{who}」",+ denied: "已拒绝「{who}」",+ messages: { other: "发了 {count} 条消息" },+ wants: "想使用这个机器人 · 配对码 {code}",+ quote: "「{text}」",+ allow: "允许",+ deny: "拒绝",+ replyHint: "也可以在聊天里回复「同意 {code}」。",+ },+ turn: {+ stopFailed: "中止失败:{error}",+ processing: "正在处理 {d}",+ waitingAgent: " · 等代理进程接手",+ idle: "{d}没有新进展",+ stop: "中止",+ activity: "处理过程",+ },+ tasks: "任务",+};diff --git a/ui/locales/zh-CN/markdown.js b/ui/locales/zh-CN/markdown.jsnew file mode 100644index 0000000..131d285--- /dev/null+++ b/ui/locales/zh-CN/markdown.js@@ -0,0 +1,6 @@+// markdown · zh-CN(components/markdown.js:回复里的代码块)+export default {+ /** 代码块没写语言时,左上角显示的名字 */+ code: "代码",+ copyCode: "复制代码",+};diff --git a/ui/locales/zh-CN/models.js b/ui/locales/zh-CN/models.jsnew file mode 100644index 0000000..0a34832--- /dev/null+++ b/ui/locales/zh-CN/models.js@@ -0,0 +1,20 @@+// models · zh-CN:模型选择器(components/model-picker.js)+export default {+ /** 认不出的模型族 */+ otherFamily: "其他",+ caps: {+ vision: "视觉",+ tools: "工具",+ reasoning: "推理",+ },+ /** 按次计费的参考价,price 形如 $0.04 */+ perCall: "{price}/次",+ noteTitle: "上下文 · 能力 · 每百万 tokens 输入/输出的起步参考价(美元,以账单为准)",+ choose: "选择模型",+ filter: "筛选模型",+ filterOrId: "筛选,或输入任意模型 ID",+ loadFailed: "获取模型列表失败:{error}",+ useCustom: "使用「{id}」",+ customId: "自定义模型 ID",+ none: "没有可用模型:这个 Key 所在的分组还没有开放模型",+};diff --git a/ui/locales/zh-CN/newBot.js b/ui/locales/zh-CN/newBot.jsnew file mode 100644index 0000000..1332fa9--- /dev/null+++ b/ui/locales/zh-CN/newBot.js@@ -0,0 +1,48 @@+// newBot · zh-CN:新建机器人(screens/new-bot.js)+export default {+ headName: "新机器人",+ cancel: "取消(Esc)",+ firstTitle: "创建你的第一个机器人",+ title: "新建机器人",+ lead: "挑一个伙伴,起个名字、写几句人设,或者从下面的模板开始。",+ name: "名称",+ namePlaceholder: "例如:群聊日报",+ persona: "人设",+ personaHint: "可选,之后在机器人设置里也能改",+ personaPlaceholder: "例如:你是一个乐于助人的中文助手,回答简洁准确。",+ create: "创建",+ fromTemplate: "从模板开始",+ /** 模板:选中后 name 填进名称、prompt 填进人设 */+ tpl: {+ digest: {+ name: "群聊日报",+ desc: "把群里的讨论整理成日报:结论、待办和负责人",+ prompt: "你是群聊日报助手。被要求总结时,把群里的讨论整理成日报:先写三条以内的结论,再列待办(事项、负责人、时间),最后列还没解决的问题。只写群里确实说过的内容,不要编造。",+ },+ support: {+ name: "客服助手",+ desc: "按已知资料回答客户问题,拿不准就转人工",+ prompt: "你是客服助手。用简洁、礼貌的中文回答客户问题,只依据已知的资料作答;资料里没有或拿不准时,直接说明会转给人工处理,不要猜测。",+ },+ translate: {+ name: "翻译官",+ desc: "中英互译,保留语气、术语和格式",+ prompt: "你是翻译官。收到中文就译成英文,收到其他语言就译成中文。保留原文的语气、术语和格式(列表、代码、链接),只输出译文。",+ },+ minutes: {+ name: "会议纪要",+ desc: "把会议记录整理成结论、待办和待定问题",+ prompt: "你是会议纪要助手。把会议记录或转写整理成:会议主题、结论、待办(事项、负责人、截止时间)、待定问题。语言精炼,不添加记录里没有的信息。",+ },+ writer: {+ name: "写作助手",+ desc: "起草公告、邮件和周报,按你的语气润色",+ prompt: "你是写作助手。帮我起草和润色公告、邮件、周报等文字。先弄清用途和读者,再给出成稿;语气自然、结构清楚,不写空话。",+ },+ coder: {+ name: "代码助手",+ desc: "读代码、写脚本,在自己的工作区里改文件",+ prompt: "你是代码助手。阅读和修改工作区里的代码,编写脚本解决问题。动手前先说明计划,改完说明改了什么、怎么验证。",+ },+ },+};diff --git a/ui/locales/zh-CN/notify.js b/ui/locales/zh-CN/notify.jsnew file mode 100644index 0000000..6f543ff--- /dev/null+++ b/ui/locales/zh-CN/notify.js@@ -0,0 +1,9 @@+// notify · zh-CN(lib/notify.js 与对话页发出的系统通知)+export default {+ /** 通知摘要里代替代码块 / 图片的占位 */+ code: "[代码]",+ image: "[图片]",+ prompt: "等你确认:回到对话里处理这一步",+ replyDone: "回复完成",+ replyError: "出错了:{text}",+};diff --git a/ui/locales/zh-CN/onboarding.js b/ui/locales/zh-CN/onboarding.jsnew file mode 100644index 0000000..6f184f0--- /dev/null+++ b/ui/locales/zh-CN/onboarding.js@@ -0,0 +1,57 @@+// onboarding · zh-CN:引导页(screens/onboarding.js:登录、粘贴 Key、选默认模型)+export default {+ slogan: "任意模型,一个助手",+ gatewayFailed: "内置模型网关没有启动:{error}。修复后重启应用再连接。",+ unknownReason: "未知原因",+ keyOnly: "Docker 或远程部署无法用浏览器登录,请填写 API Key",+ createKey: "在 Modelflare 控制台创建 Key ↗",+ /** Modelflare 线路("自动"用 common.auto) */+ line: {+ label: "线路",+ sub: "中国大陆访问可选优化线路",+ global: "国际",+ cn: "中国大陆优化",+ },+ key: {+ label: "API Key",+ placeholder: "粘贴你的 Modelflare API Key",+ paste: "从剪贴板粘贴",+ show: "显示",+ hide: "隐藏",+ showKey: "显示 Key",+ hideKey: "隐藏 Key",+ retype: "重新输入",+ checkGroup: "去控制台检查分组 ↗",+ useCn: "改用大陆优化线路并重试",+ note: "密钥只保存在本机,不会写入日志或命令行参数。",+ connecting: "正在连接…",+ submit: "连接 Modelflare",+ slow: "网络较慢。",+ slowLine: "网络较慢,可在「高级」里切换线路。",+ advanced: "高级",+ },+ login: {+ label: "登录 / 注册 Modelflare",+ waiting: "在浏览器里完成登录后,会自动回到这里",+ reopen: "重新打开登录页 ↗",+ copyLink: "复制链接",+ },+ model: {+ /** n 是带样式的数字,count 用来选单复数 */+ found: "已连接 · 找到 {n} 个模型",+ hint: "选一个默认模型,之后随时可在对话里切换。",+ filter: "筛选模型",+ default: "默认模型",+ noMatch: "没有匹配的模型",+ mediaHint: "生成图片和视频时默认用的模型。每次生成前都会先问你,也可以当场换。",+ image: "图片",+ imageLabel: "默认图片模型",+ video: "视频",+ videoLabel: "默认视频模型",+ console: "去控制台 ↗",+ empty: "这个 Key 所在的分组暂无可用模型。可以在控制台给分组开放模型后再回来刷新。",+ saving: "正在保存…",+ start: "开始对话",+ startAnyway: "仍然开始",+ },+};diff --git a/ui/locales/zh-CN/perms.js b/ui/locales/zh-CN/perms.jsnew file mode 100644index 0000000..fddb214--- /dev/null+++ b/ui/locales/zh-CN/perms.js@@ -0,0 +1,12 @@+// perms · zh-CN+export default {+ workspace: "工作区可写",+ workspaceNote: "只能改这个机器人的工作区,越界操作先问你",+ readonly: "只读",+ readonlyNote: "不能改文件,命令在只读沙箱里运行",+ full: "完全权限",+ fullNote: "命令不经沙箱,可读写你的所有文件;递归删除仍会先问你",+ fullWarning: "命令不经沙箱,以你的用户身份直接运行:可以读取和修改你电脑上的任何文件,包括 AnyModelBot 自己的数据(会话记录、渠道令牌和密钥)。越界操作不再请求批准,只有递归删除(rm -r、Remove-Item -Recurse 等)仍会先问你。只在你信任当前模型和任务时开启。",+ confirmTitle: "开启完全权限?",+ confirmLabel: "开启完全权限",+};diff --git a/ui/locales/zh-CN/pwsh.js b/ui/locales/zh-CN/pwsh.jsnew file mode 100644index 0000000..3041bba--- /dev/null+++ b/ui/locales/zh-CN/pwsh.js@@ -0,0 +1,53 @@+// pwsh · zh-CN(components/pwsh-hint.js、lib/pwsh.js)+export default {+ slow: "机器人执行命令现在用的是系统自带的 Windows PowerShell 5.1,每条可能要等二三十秒",+ unknownReason: "未知原因",+ privateSuffix: "(应用内置)",+ privatePrefix: "应用内置的",+ progress: {+ waiting: "准备中",+ downloading: "下载 {received} / {total} MB{pct}",+ pct: "({n}%)",+ extracting: "解压",+ verifying: "核对签名",+ testing: "试运行",+ done: "已装好",+ failed: "没装上:{error}",+ },+ // 操作结果的提示+ found: "已检测到 PowerShell {version}{private},代理空闲时换用",+ notFound: "还没有检测到能用的 PowerShell 7",+ notFoundInstalling: "还没有能用的 PowerShell 7,正在为代理安装",+ reinstalling: "正在重新安装 PowerShell 7…",+ installing: "正在安装 PowerShell 7…",+ using: "代理用 PowerShell {version}",+ modeSystem: "已改回系统默认,代理空闲时生效",+ modePrivate: "已改用应用内置的 PowerShell 7",+ // 提示条+ installingTitle: "正在为代理安装 PowerShell 7…",+ installingBody: "{progress}。装好后机器人执行命令快得多(大约 1 秒一条);不需要管理员权限,也不影响你自己的 PowerShell。装好之前命令照常用 Windows PowerShell 5.1。",+ installedTitle: "PowerShell 7 已就绪",+ installedBody: "机器人之后执行命令用应用内置的 PowerShell {version}(已核对微软签名并试运行通过),大约 1 秒一条。",+ fallbackTitle: "PowerShell 出了问题,已自动换掉",+ fallbackBody: "{from} 起不来({reason})。机器人改用 {private}PowerShell {version} 执行命令。",+ brokenTitle: "应用内置的 PowerShell 7 用不了",+ brokenBody: "{reason}。{slow}。重新安装一般就能恢复。",+ failedTitle: "PowerShell 7 没装上",+ failedBody: "{error}。{slow}。",+ unsupportedTitle: "这台电脑装不了 PowerShell 7",+ unsupportedBody: "{reason}。{slow}。",+ title: "建议安装 PowerShell 7",+ body: "{slow}。装上 PowerShell 7,命令执行快得多,也更稳定。{canInstall}",+ canInstall: "应用可以自己装一份,不需要管理员权限,也不影响你自己的 PowerShell。",+ orRun: "或在终端运行",+ copyCommand: "复制安装命令",+ oneClick: "一键安装",+ install: "安装 PowerShell 7 ↗",+ installSelf: "自己安装 ↗",+ reinstall: "重新安装",+ retry: "重试",+ checking: "检测中…",+ recheck: "重新检测",+ ack: "知道了",+ dismiss: "不再提示",+};diff --git a/ui/locales/zh-CN/settings.js b/ui/locales/zh-CN/settings.jsnew file mode 100644index 0000000..f911c47--- /dev/null+++ b/ui/locales/zh-CN/settings.js@@ -0,0 +1,323 @@+// settings · zh-CN(screens/settings.js)+export default {+ tabs: {+ general: "常规",+ appearance: "外观",+ modelflare: "Modelflare",+ computer: "电脑操作",+ privacy: "隐私与安全",+ network: "网络与访问",+ data: "数据",+ troubleshoot: "故障排查",+ about: "关于",+ },+ gateway: {+ running: "运行中",+ starting: "启动中",+ restarting: "重启中",+ failed: "失败",+ stopped: "已停止",+ external: "外部端点",+ },+ theme: { light: "浅色", dark: "深色" },+ textSize: { sm: "小", md: "标准", lg: "大", xl: "特大" },+ font: { system: "系统默认", serif: "衬线", custom: "自定义" },+ width: { normal: "标准", wide: "宽", full: "铺满" },+ side: {+ label: "设置",+ back: "返回应用",+ backTitle: "返回应用(Esc)",+ search: "查找设置",+ nav: "设置分页",+ },+ searchResults: "搜索结果",+ noMatch: "没有匹配的设置",+ preview: {+ ask: "帮我把这段请求改成 async / await 的写法",+ reply: "好的,改写后错误处理也更直观。下面这行在开启{b}后会折行显示:",+ },+ rekey: {+ title: "更换 Modelflare 密钥",+ submit: "验证并保存",+ },+ disconnect: {+ title: "断开 Modelflare?",+ body: "会从本机删除这个 API Key。机器人和会话都会保留,重新连接后继续使用。",+ confirm: "断开",+ },+ logout: {+ title: "退出 Modelflare 账户?",+ body: "会撤销这台电脑的授权,并删除登录时为它和各机器人签发的 API Key。机器人和会话都会保留。",+ confirm: "退出登录",+ notRevoked: "服务端没有确认撤销:本机已退出,可在 Modelflare 网页的「已授权的应用」里再撤销一次",+ },+ notifyDenied: "没有通知权限:请在系统或浏览器的网站设置里允许本页面发通知",+ rows: {+ language: {+ sub: "界面、托盘菜单和机器人发出的系统消息都用这种语言",+ keys: "语言 中文 英文 English language",+ },+ sendKey: {+ name: "发送消息",+ sub: "{key} 换行;输入法选字时的回车不会发送",+ keys: "发送 回车 换行 快捷键 enter send shortcut",+ },+ notify: {+ name: "回复完成时通知",+ sub: "窗口不在前台时,机器人回复完或等你确认,弹一条系统通知",+ keys: "通知 提醒 系统通知 后台 notification",+ },+ close: {+ name: "关闭窗口时",+ sub: "隐藏到托盘时机器人继续在后台收发消息",+ keys: "托盘 退出 tray",+ tray: "隐藏到托盘",+ quit: "退出",+ },+ autostart: {+ name: "开机自启",+ sub: "登录系统后在后台启动",+ keys: "启动 login",+ },+ browser: {+ name: "在浏览器中打开",+ sub: "用系统浏览器打开同一个本机界面",+ keys: "browser",+ },+ guide: {+ name: "上手清单",+ hidden: "已不再显示;重新开始后,对话页和侧栏左下角会再出现",+ progress: "跟着清单认识机器人能做的事 · 已完成 {done}/{total}",+ keys: "引导 新手 教程 清单 onboarding guide",+ restart: "重新开始",+ restarted: "上手清单已重新开始",+ },+ theme: {+ name: "主题",+ sub: "浅色、深色,或跟随系统",+ keys: "主题 外观 深色 浅色 暗色 夜间 theme dark light",+ },+ textSize: {+ name: "字体大小",+ subDesktop: "只调整文字;图标和间距一起放大用下面的「界面缩放」",+ sub: "只调整文字,图标和间距不变",+ keys: "字号 字体大小 文字 大字 font size",+ },+ font: {+ name: "界面字体",+ sub: "系统默认、衬线(宋体风格),或电脑上装的任意字体",+ keys: "字体 宋体 衬线 楷体 font family typeface",+ },+ fontName: {+ name: "自定义字体",+ subSet: "可以用逗号写多个,按顺序回退;没装的字体退回系统字体",+ subEmpty: "填字体名称,例如 LXGW WenKai;没填时仍用系统字体",+ keys: "字体 自定义 font",+ placeholder: "字体名称",+ },+ codeFont: {+ name: "代码字体",+ sub: "代码块、命令和路径用的等宽字体;留空用系统等宽字体",+ keys: "代码 等宽 字体 monospace code font",+ placeholder: "系统等宽字体",+ },+ zoom: {+ name: "界面缩放",+ sub: "放大或缩小窗口里的一切,包括图标和间距",+ keys: "缩放 放大 字号 zoom scale",+ },+ chatWidth: {+ name: "对话宽度",+ sub: "宽屏上让对话列更宽,长代码和表格少折行",+ keys: "宽度 对话列 宽屏 铺满 width",+ },+ codeWrap: {+ name: "代码自动换行",+ sub: "代码块里的长行折到下一行显示,不用左右滚动",+ keys: "代码 换行 折行 wrap",+ },+ motion: {+ name: "动画",+ sub: "关闭后界面切换、弹出和机器人头像都不再动;跟随系统时遵循「减少动态效果」",+ keys: "动画 动效 过渡 减少动态效果 晕 animation motion",+ },+ glass: {+ name: "毛玻璃效果",+ sub: "关闭后侧栏、菜单和对话框换成实色,文字更清楚、也更省电;跟随系统时遵循「降低透明度」",+ keys: "毛玻璃 透明 模糊 降低透明度 省电 卡顿 blur transparency",+ },+ resetAppearance: {+ name: "恢复默认外观",+ subDesktop: "主题、字体、缩放和以上所有外观设置回到默认",+ sub: "主题、字体和以上所有外观设置回到默认",+ keys: "恢复 默认 重置 reset",+ button: "恢复默认",+ },+ account: {+ name: "Modelflare 账户",+ signedIn: "已登录",+ enterprise: "{name} · 由企业钱包付费",+ signedOut: "登录后可以查看用量、通知和邀请链接,也能给机器人单独设预算",+ keys: "登录 注册 账户 退出 account login",+ logout: "退出登录",+ noBrowserLogin: "Docker / 远程部署不支持浏览器登录",+ login: "登录 / 注册",+ },+ connection: {+ name: "连接",+ nameSignedIn: "本机 Key",+ subExternal: "由环境变量 AMB_MAGPIE_BASE_URL 指定的端点(开发/测试)",+ subSignedIn: "登录时为这台电脑签发,退出登录会一并删除",+ sub: "API Key 只保存在本机",+ keys: "密钥 key api 断开 更换",+ rekey: "更换密钥",+ disconnect: "断开",+ },+ balance: {+ name: "余额",+ error: "读取失败:{error}",+ fromKey: "这把 Key 所在账户的钱包余额",+ updated: "更新于 {time}",+ keys: "余额 充值 钱包 balance top up",+ refresh: "刷新余额",+ topUp: "充值 ↗",+ },+ lowBalance: {+ name: "余额提醒",+ sub: "余额低于这个数时在应用里提醒一次,充值后重新计",+ keys: "提醒 余额不足 low balance",+ none: "不提醒",+ },+ lowBalancePush: {+ name: "提醒也发到微信 / 飞书",+ sub: "由机器人发给你:微信发给扫码登录的人(需要他最近发过消息),飞书发到最近的单聊",+ keys: "推送 提醒 微信 飞书",+ },+ usage: {+ name: "用量",+ sub: "按天、按模型的花费",+ keys: "用量 花费 账单 usage",+ },+ notifications: {+ name: "通知",+ unread: "{count} 条未读",+ sub: "Modelflare 发给你的通知与公告",+ keys: "通知 公告 消息 notification",+ },+ invite: {+ name: "邀请好友",+ sub: "好友通过你的链接注册并充值,你会获得返利",+ keys: "邀请 返利 推广 invite",+ copy: "复制邀请链接",+ },+ line: {+ name: "线路",+ sub: "中国大陆访问更稳定可选优化线路;切换后新请求生效",+ keys: "大陆 国际 origin 网络",+ },+ defaultModel: {+ name: "默认模型",+ sub: "机器人没有单独指定时使用",+ keys: "模型 model",+ auto: "自动(列表第一个)",+ },+ imageModel: {+ name: "默认图片模型",+ sub: "机器人生成图片时默认选它,每次生成前都会让你确认",+ keys: "图片 生图 画图 image 模型",+ },+ videoModel: {+ name: "默认视频模型",+ sub: "机器人生成视频时默认选它,每次生成前都会让你确认",+ keys: "视频 生视频 video 模型",+ },+ autoModel: "自动({model})",+ models: {+ name: "可用模型",+ error: "获取失败:{error}",+ sub: "这个 Key 所在分组开放的模型",+ keys: "列表 刷新",+ count: "{count} 个",+ },+ console: {+ name: "Modelflare 控制台",+ sub: "账单、发票与 API Key 管理",+ keys: "控制台 账单 console",+ },+ cuStatus: {+ name: "电脑操作后端",+ keys: "computer use cua 辅助功能 屏幕录制",+ },+ cuNotice: {+ name: "系统权限",+ keys: "权限 permission",+ },+ cuPerBot: {+ name: "按机器人开启",+ sub: "每个机器人可以单独开启电脑操作并设置审批方式",+ keys: "机器人",+ open: "打开机器人设置",+ },+ keyStorage: {+ name: "密钥存放",+ sub: "Modelflare 密钥只在本机内置网关的隔离配置里,不写日志、不进命令行参数",+ keys: "安全",+ },+ accountStorage: {+ name: "账户凭据",+ sub: "登录 Modelflare 的凭据只存在数据目录,桌面版用系统钥匙串加密;界面只拿到账户名称",+ keys: "安全 登录 钥匙串",+ },+ token: {+ name: "访问令牌",+ required: "需要令牌:界面监听在非本机地址,或桌面版每次启动随机生成",+ local: "只监听本机,无需令牌",+ keys: "token 令牌",+ },+ sandbox: {+ name: "机器人沙箱",+ sub: "来自机器人沙箱的请求会被本机界面拒绝,机器人无法自行批准操作或读取配置",+ keys: "安全 dsh",+ },+ screens: {+ name: "截图",+ sub: "电脑操作的截图只发给模型,不会发到聊天里",+ keys: "隐私",+ },+ listen: {+ name: "监听地址",+ sub: "修改需设置 AMB_UI_HOST / AMB_UI_PORT 并重启",+ keys: "端口 port host",+ copy: "复制地址",+ },+ dataDir: {+ name: "数据目录",+ sub: "SQLite、机器人工作区、微信登录态与内置网关配置",+ keys: "路径 目录 folder",+ copy: "复制路径",+ },+ version: {+ name: "版本",+ keys: "version",+ },+ licenses: {+ name: "许可与第三方声明",+ sub: "MIT;界面部分样式改编自 magpie(MIT)",+ keys: "license",+ },+ diagnostics: {+ name: "诊断信息",+ gateway: "内置模型网关",+ restarts: "重启 {count} 次",+ keys: "网关 gateway magpie",+ },+ troubleshoot: {+ sub: "模型网关与代理进程的状态、测试模型、测试代理、最近日志、复制诊断信息",+ keys: "日志 log 测试 test 代理 agent 卡住 转圈 诊断 diagnostics 重启 PowerShell pwsh 命令慢",+ },+ links: {+ sub: "官网与文档",+ docs: "文档 ↗",+ },+ },+};diff --git a/ui/locales/zh-CN/sidebar.js b/ui/locales/zh-CN/sidebar.jsnew file mode 100644index 0000000..318333e--- /dev/null+++ b/ui/locales/zh-CN/sidebar.js@@ -0,0 +1,38 @@+// sidebar · zh-CN:侧栏(screens/sidebar.js)+export default {+ /** 没登录、也没有用户名时左下角显示的名字 */+ localUser: "本机用户",+ settingsTitle: "设置(⌘,)",+ openSettings: "打开设置",+ balance: "余额 {amount}",+ lowBalance: "余额只剩 {amount},去充值 ↗",+ renamed: "已重命名",+ delete: {+ title: "删除「{name}」?",+ body: "会永久删除这个机器人及其全部会话,无法恢复。",+ confirm: "永久删除",+ },+ bots: "机器人",+ newShortcut: "新建机器人(⌘N)",+ search: "搜索机器人",+ list: "机器人列表",+ /** 新建页打开时列表顶部的占位行 */+ newBot: "新机器人",+ creating: "正在创建…",+ loadFailed: "无法读取机器人列表",+ empty: "还没有机器人",+ create: "新建机器人",+ noMatch: "没有匹配的机器人",+ newName: "新名称",+ working: "工作中",+ workingNow: "正在工作…",+ noChats: "还没有对话",+ pending: "{count} 个待审批",+ moreFor: "{name} 的更多操作",+ actionsFor: "{name} 的操作",+ menu: {+ settings: "机器人设置",+ copyId: "复制机器人 ID",+ delete: "删除机器人",+ },+};diff --git a/ui/locales/zh-CN/tasks.js b/ui/locales/zh-CN/tasks.jsnew file mode 100644index 0000000..43be68c--- /dev/null+++ b/ui/locales/zh-CN/tasks.js@@ -0,0 +1,15 @@+// tasks · zh-CN+export default {+ cause: { launch: "开始", followup: "追加后继续", recover: "重启后继续", retry: "重试", continue: "继续", answer: "回答后继续", manual: "手动运行" },+ run: "第 {n} 次",+ queued: "排队中",+ stopped: "已停止「{title}」",+ latest: "最新进展",+ folder: "文件夹",+ stop: "停止",+ stopping: "正在停止…",+ collapse: "收起",+ view: "查看后台任务",+ chip: "后台任务",+ minutes: { other: "{count} 分钟" },+};diff --git a/ui/locales/zh-CN/time.js b/ui/locales/zh-CN/time.jsnew file mode 100644index 0000000..36ef128--- /dev/null+++ b/ui/locales/zh-CN/time.js@@ -0,0 +1,10 @@+// time · zh-CN(lib/format.js)+export default {+ today: "今天 {time}",+ yesterday: "昨天 {time}",+ dateTime: "{date} {time}",+ justNow: "刚刚",+ minutesAgo: "{count} 分钟前",+ seconds: "{s} 秒",+ minSec: "{m} 分 {s} 秒",+};diff --git a/ui/locales/zh-CN/troubleshoot.js b/ui/locales/zh-CN/troubleshoot.jsnew file mode 100644index 0000000..b2c18a3--- /dev/null+++ b/ui/locales/zh-CN/troubleshoot.js@@ -0,0 +1,151 @@+// troubleshoot · zh-CN(screens/troubleshoot.js:设置 › 故障排查)+export default {+ status: "状态",+ checks: "检测",+ version: "版本",+ dataDir: "数据目录",+ copyPath: "复制路径",+ logFile: "日志文件",+ logFileSub: "按大小轮转,保留最近 4 个文件",+ logFileOff: "未启用",+ test: "测试",+ /** {model} 是模型 id */+ model: "模型 {model}",+ none: "(无)",+ copyReport: "复制诊断信息",+ copied: "诊断信息已复制(已去掉密钥)",+ note: "复制的诊断信息包含上面的状态、最近一次测试结果和日志,API Key、令牌等已替换成 ***,可以直接发给支持人员。",+ /** {s} 是秒数(可能带一位小数) */+ secs: "{s} 秒",+ restarts: "重启 {count} 次",+ /** {signal} 是 " signal=SIGTERM" 这样的一段,或者空 */+ lastExit: "上次退出 code={code}{signal}",+ verdict: {+ ok: "正常",+ bad: "有问题",+ },+ gateway: {+ name: "模型网关",+ fromEnv: "由 {env} 指定",+ running: "运行中",+ starting: "启动中",+ restarting: "重启中",+ failed: "失败",+ stopped: "已停止",+ external: "外部端点",+ },+ agent: {+ name: "代理进程",+ nameFor: "代理进程 · {bot}",+ noRuntime: "找不到代理运行时(DSH),机器人只能纯对话",+ disabled: "代理模式已关闭,机器人只做纯对话",+ startsOnFirst: "收到第一条消息时启动",+ stderr: "代理进程输出(stderr 最后 {count} 行)",+ },+ host: {+ running: "运行中",+ starting: "启动中",+ backoff: "等待重试",+ error: "已暂停",+ stopped: "未启动",+ },+ /** 代理进程一行的说明 */+ hostSub: {+ elapsed: "已 {time}",+ stage: "阶段:{stage}",+ firstStart: "首次启动可能需要几分钟(杀毒软件会逐个扫描运行时文件)",+ maxWait: "最多等 {count} 分钟",+ initTime: "启动用时 {time}",+ activeTurns: "{count} 轮进行中",+ retryIn: '{count} 分钟后自动重试,或点下面的"重启代理进程"',+ },+ /** 代理进程启动的阶段 */+ init: {+ prepare: "准备",+ bridgeReady: "模型桥已就绪",+ sdkLoaded: "加载运行时",+ patchWritten: "写入配置",+ childSpawned: "进程已拉起",+ initializing: "初始化(加载插件)",+ },+ /** 测试代理每一段的结果 */+ stage: {+ ok: "通过",+ warn: "注意",+ fail: "失败",+ timeout: "超时",+ skipped: "未执行",+ pending: "进行中",+ },+ pwsh: {+ checking: "检测中",+ checkingBusy: "检测中…",+ missing: "未安装",+ looking: "正在找 PowerShell 7",+ usedBy: "代理用它执行命令",+ old: "版本较旧:装上 PowerShell 7,命令执行快得多,也更稳定",+ builtin: "代理执行命令用的是系统自带的 Windows PowerShell 5.1,每条可能要二三十秒。装上 PowerShell 7,命令执行快得多,也更稳定",+ recheck: "重新检测",+ install: "安装 PowerShell 7",+ copyCmd: "复制安装命令",+ download: "下载安装 ↗",+ fallback: "之前用的 {from} 起不来({reason}),已自动换掉",+ unusable: "用不了",+ notInstalled: "没装上",+ usedByFrom: "代理用它执行命令({source})",+ installingSub: "正在为代理安装 PowerShell 7,不需要管理员权限;装好前命令照常用 Windows PowerShell 5.1",+ badSub: "应用内置的 PowerShell 7 用不了:{reason}",+ failedSub: "没装上:{error}",+ unknownReason: "未知原因",+ using51: "代理先用 Windows PowerShell 5.1",+ slow51: "代理在用 Windows PowerShell 5.1,每条命令可能要二三十秒",+ slow51Advice: "代理在用 Windows PowerShell 5.1,每条命令可能要二三十秒;装上 PowerShell 7 快得多",+ reinstall: "重新安装",+ installShort: "安装",+ reinstallPrivate: "重新安装应用内置的 PowerShell 7",+ useSystem: "改回系统默认",+ useSystemNote: "不用应用内置的 PowerShell 7",+ usePrivate: "改用应用内置的 PowerShell 7",+ installSelf: "自己安装 PowerShell 7…",+ more: "更多",+ moreLabel: "PowerShell 的更多操作",+ source: {+ private: "应用内置",+ programFiles: "安装目录",+ preview: "预览版",+ },+ },+ testModel: {+ name: "测试模型",+ sub: "发一个最小请求:经内置网关、直连端点各一次,对比两边的状态码、耗时与回显的模型名",+ viaGateway: "经内置网关",+ direct: "直连端点",+ },+ probe: {+ untested: "未测",+ ok: "正常",+ echoed: "回显模型 {model}",+ reply: "回复 “{reply}”",+ },+ testAgent: {+ name: "测试代理",+ sub: "让代理进程完整跑一轮最小对话(不进聊天记录),看卡在哪一步:启动 → 插件 → 模型 → 回复",+ ok: "代理正常",+ stuckAt: "卡在:{stage}",+ bot: "机器人 {name}",+ total: "共 {time}",+ },+ restart: {+ name: "重启代理进程",+ sub: "回复一直转圈时用:结束代理进程并清掉重试等待,下一条消息重新启动",+ button: "重启",+ done: "代理进程已重启",+ notRunning: "代理进程还没有启动,下一条消息时启动",+ },+ logs: {+ title: "最近日志",+ lines: "{count} 行",+ empty: "(还没有日志)",+ readFailed: "读取日志失败:{error}",+ },+};diff --git a/ui/locales/zh-CN/ui.js b/ui/locales/zh-CN/ui.jsnew file mode 100644index 0000000..cd89107--- /dev/null+++ b/ui/locales/zh-CN/ui.js@@ -0,0 +1,31 @@+// ui · zh-CN:共用组件(components/ui.js)。按钮的「取消 / 确定 / 关闭 / 复制」用 common+export default {+ /** 状态徽标(Badge s="…"):渠道、网关、扫码登录、审批、提问卡片的状态 */+ state: {+ disabled: "未启用",+ connecting: "连接中",+ connected: "已连接",+ error: "错误",+ expired: "已过期",+ paused: "已暂停",+ login_required: "未登录",+ running: "运行中",+ starting: "启动中",+ restarting: "重启中",+ failed: "失败",+ stopped: "已停止",+ wait: "等待扫码",+ scaned: "已扫码",+ need_verifycode: "需验证码",+ confirmed: "已确认",+ already_bound: "已绑定",+ cancelled: "已取消",+ idle: "空闲",+ fetching: "获取中",+ pending: "待处理",+ allowed: "已批准",+ rejected: "已拒绝",+ answered: "已回答",+ denied: "已拒绝",+ },+};diff --git a/ui/main.js b/ui/main.jsindex f6dfa39..5ebc8ca 100644--- a/ui/main.js+++ b/ui/main.js@@ -2,7 +2,7 @@// 未连接 Modelflare → 整页引导;已连接 → 侧栏 + 对话(信息面板按需),设置与机器人设置占满主区。import { render } from "preact";import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";-import { html, Icon, DialogHost, Notice, Toasts } from "./components/ui.js";+import { html, Icon, DialogHost, Notice, Toasts, Splitter, tokenPx } from "./components/ui.js";import { Sidebar } from "./screens/sidebar.js";import { ChatScreen } from "./screens/chat.js";import { InfoPanel } from "./screens/info-panel.js";@@ -11,9 +11,14 @@ import { BotSettingsScreen } from "./screens/bot-settings.js";import { NewBotScreen } from "./screens/new-bot.js";import { BotAvatar, MAIN_CHAR, charOf } from "./components/avatar.js";import { Onboarding } from "./screens/onboarding.js";+import { CoachMark } from "./components/guide.js";import { api } from "./lib/api.js";+import { loadGuide, setFocus } from "./lib/guide.js";import { setThemeMode } from "./lib/theme.js";-import { failed, toast } from "./lib/store.js";+import { failed, toast, useStore } from "./lib/store.js";+import { prefs, setPrefs } from "./lib/prefs.js";+import { usePresence } from "./design/motion.js";+import { t, useLang, adoptServerLang, changeLang, getLangPref, LANG_NAMES } from "./lib/i18n.js";// —— 路由:#/chat/<bot> · #/new · #/settings/<tab>[/<row>] · #/bot/<bot>/settings[/<section>] ——function parseHash() {@@ -102,15 +107,15 @@ function Palette({ commands, 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 class="palette" role="dialog" aria-modal="true" aria-label=${t("app.palette.title")}>+ <div class="search"><${Icon} name="search" size="md" />+ <input ref=${input} placeholder=${t("app.palette.placeholder")} aria-label=${t("app.palette.inputLabel")} 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>`}+ ${!hits.length && html`<li class="group" style="pointer-events:none">${t("app.palette.empty")}</li>`}</ul></div>`;}@@ -119,10 +124,16 @@ function Palette({ commands, onClose }) {const AURA_HUE = { blue: 245, yellow: 95, green: 155, red: 25, purple: 305, orange: 55 };function App() {+ // 订阅界面语言:切换语言时整棵树跟着重渲染(子组件里的 t() 都在渲染时取)+ const lang = useLang();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"));+ // 语言偏好以服务端配置为准(可能在另一个窗口 / 浏览器里改过);本机缓存只管首帧+ useEffect(() => {+ if (settings) adoptServerLang(settings.lang);+ }, [settings && settings.lang]);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]);@@ -147,6 +158,10 @@ function App() {}, []);useInterval(() => api("/account").then(setAccount).catch(() => {}), 60_000, connected && managed);+ // 上手清单:连上 Modelflare 之后读进度(新用户在对话空状态里看到清单,老用户已做过的步骤会自动打勾)+ useEffect(() => {+ if (connected) loadGuide();+ }, [connected]);useEffect(() => {if (!connected || !managed) return;const on = () => document.visibilityState === "visible" && api("/account/refresh", { method: "POST", body: {} }).then(setAccount).catch(() => {});@@ -160,7 +175,7 @@ function App() {prevAccount.current = account;if (!prev || !account) return;if (prev.state === "signed_in" && account.state !== "signed_in") reloadMf();- if (!prev.lowBalance && account.lowBalance) toast(`Modelflare 余额只剩 ${account.balanceUsd.toFixed(2)} 美元`, "err");+ if (!prev.lowBalance && account.lowBalance) toast(t("app.lowBalance", { amount: account.balanceUsd.toFixed(2) }), "err");}, [account]);const bots = botsData ? botsData.bots : null;@@ -175,6 +190,17 @@ function App() {}}, [bot && bot.id]);+ // 信息面板:关上时多留一会儿,播完"列宽滑回 0、面板淡出"再卸载+ const panelOpen = route.view === "chat" && infoOpen && !!bot;+ const panelFx = usePresence(panelOpen, "--dur-slow");+ const lastPanel = useRef(null);+ if (panelOpen) lastPanel.current = bot;+ // 侧栏 / 信息面板的宽度:拖分隔条调整,存在本机偏好里(lib/prefs.js 把它写成 <html> 上的 --side-w-user / --panel-w-user)+ const { sideW, panelW } = useStore(prefs);+ const appRef = useRef(null);+ /** 拖宽一侧时最多还能给多宽:窗口 − 另一侧那一列此刻的宽度 − 主区最小宽度 */+ const room = (otherCol) => () => window.innerWidth - tokenPx(otherCol, 0, appRef.current || undefined) - tokenPx("--main-w-min", 0);+const models = modelsData ? modelsData.models : null;const modelsError = modelsData && modelsData.error ? modelsData.error : "";const reloadModels = () =>@@ -245,6 +271,11 @@ function App() {go(`/chat/${encodeURIComponent(id || (bot && bot.id) || "")}`);};const newBot = () => go("/new");+ // 清单里点一项:回到对话页,引导卡片指着要点的地方+ const startGuide = (id) => {+ setFocus(id);+ if (route.view !== "chat") openChat();+ };useEffect(() => {if (route.view !== "settings") setSettingsQ("");}, [route.view]);@@ -287,16 +318,23 @@ function App() {return () => window.removeEventListener("keydown", key);}, [connected, route, infoOpen, bot && bot.id]);+ // keys:搜索用的关键词(不显示),两种语言的词典各有一份+ const setLang = (l) => changeLang(l).then(() => toast(t("common.saved"))).catch(failed);const commands = [- { label: "打开设置", kbd: isMac ? "⌘," : "Ctrl+,", keys: "settings preferences", run: () => openSettings() },- { label: "新建机器人", kbd: isMac ? "⌘N" : "Ctrl+N", keys: "new bot", run: newBot },- ...(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) })),+ { label: t("app.cmd.settings"), kbd: isMac ? "⌘," : "Ctrl+,", keys: t("app.cmd.settingsKeys"), run: () => openSettings() },+ { label: t("app.cmd.newBot"), kbd: isMac ? "⌘N" : "Ctrl+N", keys: t("app.cmd.newBotKeys"), run: newBot },+ ...(route.view === "chat" ? [{ label: infoOpen ? t("app.cmd.closeInfo") : t("app.cmd.openInfo"), kbd: isMac ? "⌘⇧I" : "Ctrl+Shift+I", keys: t("app.cmd.infoKeys"), run: () => setInfoOpen((v) => !v) }] : []),+ ...(bot ? [{ label: t("app.cmd.botSettings", { name: bot.name }), keys: t("app.cmd.botSettingsKeys"), run: () => openBotSettings(bot.id) }] : []),+ { label: t("app.cmd.modelflare"), keys: t("app.cmd.modelflareKeys"), run: () => openSettings("modelflare") },+ { label: t("app.cmd.appearance"), keys: t("app.cmd.appearanceKeys"), run: () => openSettings("appearance") },+ { label: t("app.cmd.themeSystem"), keys: t("app.cmd.themeKeys"), run: () => setThemeMode("system") },+ { label: t("app.cmd.themeLight"), keys: t("app.cmd.themeLightKeys"), run: () => setThemeMode("light") },+ { label: t("app.cmd.themeDark"), keys: t("app.cmd.themeDarkKeys"), run: () => setThemeMode("dark") },+ // 语言:各语言用自己的文字写名字;当前选中的那一项不列+ ...[["system", t("common.lang.system")], ["zh-CN", LANG_NAMES["zh-CN"]], ["en", LANG_NAMES.en]]+ .filter(([v]) => v !== getLangPref())+ .map(([v, name]) => ({ label: t("app.cmd.lang", { name }), keys: t("app.cmd.langKeys"), run: () => setLang(v) })),+ ...(bots || []).map((b) => ({ label: t("app.cmd.switchBot", { name: b.name }), keys: "bot switch " + b.id, run: () => openChat(b.id) })),];// —— 渲染 ——@@ -304,7 +342,7 @@ function App() {return html`<main class="onboard" data-screen=${mfErr ? "error" : "loading"}>${mfErr? html`<div class="onboard-col"><div class="onboard-hero"><${BotAvatar} char=${MAIN_CHAR} size=${88} state="sleep" lively pokeable /></div>- <${Notice} tone="red" action=${html`<button type="button" class="btn" onClick=${reloadMf}>重试</button>`}>无法连接本机服务:${mfErr}<//></div>`+ <${Notice} tone="red" action=${html`<button type="button" class="btn" onClick=${reloadMf}>${t("common.retry")}</button>`}>${t("app.serviceDown", { error: mfErr })}<//></div>`: html`<${BotAvatar} char=${MAIN_CHAR} size=${72} state="thinking" lively />`}</main>`;}@@ -316,17 +354,19 @@ function App() {const view = route.view;const panelBot = view === "chat" && infoOpen && bot;+ const shownPanel = panelFx.mounted ? panelBot || lastPanel.current : null;const routedBot = view === "bot-settings" && bots ? bots.find((b) => b.id === route.botId) : null;// 环境光的色相跟着当前机器人角色的主色(设置页和新建页用缺省的冷色)const auraBot = view === "chat" ? bot : view === "bot-settings" ? routedBot : null;const auraHue = (auraBot && AURA_HUE[charOf(auraBot)]) || 250;- return html`<div class=${`app${panelBot ? " with-panel" : ""}`} style=${{ "--aura-hue": String(auraHue) }}>+ return html`<div class=${`app${panelBot ? " with-panel" : ""}`} ref=${appRef} style=${{ "--aura-hue": String(auraHue) }}>${view === "settings"? html`<${SettingsSide} tab=${route.tab} query=${settingsQ} onQuery=${setSettingsQ} onTab=${(t) => openSettings(t)} onBack=${() => openChat()}username=${status && status.username} account=${managed ? account : null} />`: html`<${Sidebar} bots=${bots} botsError=${botsErr} reloadBots=${reloadBots} selectedId=${bot && bot.id} view=${view === "chat" && bots && !bots.length ? "new" : view}previews=${previews} pending=${pending} working=${working} username=${status && status.username} account=${managed ? account : null}- onNew=${newBot} onSelect=${openChat} onDeleted=${onDeleted} onOpenSettings=${() => openSettings()} />`}+ onNew=${newBot} onSelect=${openChat} onDeleted=${onDeleted} onOpenSettings=${() => openSettings()} onBotSettings=${openBotSettings} onGuide=${startGuide} />`}+ <${Splitter} class="split-side" size="--side-w" label=${t("app.resizeSide")} value=${sideW} room=${room("--panel-track")} onCommit=${(v) => setPrefs({ sideW: v })} /><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)}@@ -340,11 +380,14 @@ function App() {models=${models} modelsError=${modelsError} reloadModels=${reloadModels} defaultModel=${settings && settings.defaultModel}account=${managed ? account : null} onOpenSettings=${openSettings}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>`}+ ${view === "bot-settings" && bots && !routedBot && html`<div class="empty-state"><b>${t("app.botMissing")}</b><button type="button" class="text" onClick=${() => openChat()}>${t("app.backToChat")}</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)} />`}+ ${panelBot && html`<${Splitter} class="split-panel" size="--panel-w" edge="end" label=${t("app.resizePanel")} value=${panelW} room=${room("--side-col")}+ onCommit=${(v) => setPrefs({ panelW: v })} />`}+ ${shownPanel && html`<div class=${`panel-scrim${panelFx.leaving ? " leaving" : ""}`} onClick=${() => setInfoOpen(false)}></div>`}+ ${shownPanel && html`<${InfoPanel} key=${shownPanel.id} bot=${shownPanel} leaving=${panelFx.leaving} onClose=${() => setInfoOpen(false)}+ onOpenBotSettings=${() => openBotSettings(shownPanel.id)} onOpenChat=${() => setInfoOpen(false)} />`}+ <${CoachMark} bot=${view === "chat" ? bot : null} view=${view} infoOpen=${!!panelBot} />${palette && html`<${Palette} commands=${commands} onClose=${() => setPalette(false)} />`}<${DialogHost} /><${Toasts} />diff --git a/ui/screens/account.js b/ui/screens/account.jsindex d625290..192a8ab 100644--- a/ui/screens/account.js+++ b/ui/screens/account.js@@ -4,6 +4,8 @@ import { html, Seg, Sheet, Skeleton } from "../components/ui.js";import { AccountLogin } from "./onboarding.js";import { api } from "../lib/api.js";import { MF_SITE, tagLink, usd } from "../lib/links.js";+import { t } from "../lib/i18n.js";+import { fmtTime } from "../lib/format.js";/** 通知里的链接:站内路径补成官网地址;只放行 https */const notifLink = (link) => {@@ -12,16 +14,13 @@ const notifLink = (link) => {};export function LoginSheet({ onClose, onSignedIn }) {- return html`<${Sheet} title="登录 Modelflare 账户" onClose=${onClose}>- <p class="hint">登录后会替换现在填的 API Key。</p>+ return html`<${Sheet} title=${t("account.login.title")} onClose=${onClose}>+ <p class="hint">${t("account.login.hint")}</p><${AccountLogin} onSignedIn=${(s) => { onSignedIn(s); onClose(); }} /><//>`;}-const RANGES = [- [7, "7 天"],- [30, "30 天"],-];+const RANGES = () => [7, 30].map((n) => [n, t("account.usage.days", { n })]);export function UsageSheet({ onClose }) {const [days, setDays] = useState(7);@@ -33,22 +32,22 @@ export function UsageSheet({ onClose }) {api(`/account/usage?days=${days}`).then(setD).catch((e) => setErr(e.message));}, [days]);const max = d ? Math.max(...d.days.map((x) => x.usd), 0) : 0;- return html`<${Sheet} title="用量" wide onClose=${onClose}>- <div class="row compact"><div class="who"><div class="name">${d ? `合计 ${usd(d.totalUsd)}` : "读取中…"}</div></div>- <${Seg} label="范围" options=${RANGES} value=${days} onChange=${setDays} /></div>+ return html`<${Sheet} title=${t("account.usage.title")} wide onClose=${onClose}>+ <div class="row compact"><div class="who"><div class="name">${d ? t("account.usage.total", { amount: usd(d.totalUsd) }) : t("common.reading")}</div></div>+ <${Seg} label=${t("account.usage.range")} options=${RANGES()} value=${days} onChange=${setDays} /></div>${err && html`<div class="err-text" role="alert">${err}</div>`}${!d && !err && html`<${Skeleton} w="100%" h=${120} />`}- ${d && html`<div class="usage-days" role="img" aria-label="每日花费">- ${d.days.map((x) => html`<div class="bar" title=${`${x.date}:${usd(x.usd)},${x.requests} 次请求`}>+ ${d && html`<div class="usage-days" role="img" aria-label=${t("account.usage.daily")}>+ ${d.days.map((x) => html`<div class="bar" title=${t("account.usage.bar", { date: x.date, amount: usd(x.usd), count: x.requests })}><i style=${{ height: `${max > 0 ? Math.max(2, (x.usd / max) * 100) : 2}%` }}></i>${days <= 7 ? x.date.slice(5) : ""}</div>`)}</div>- <div class="set-part">按模型</div>+ <div class="set-part">${t("account.usage.byModel")}</div><div class="usage-models">- ${d.models.slice(0, 12).map((m) => html`<div><span class="v">${m.model}</span><span class="n">${usd(m.usd)} · ${m.requests} 次</span></div>`)}- ${!d.models.length && html`<p class="hint">这段时间没有用量</p>`}+ ${d.models.slice(0, 12).map((m) => html`<div><span class="v">${m.model}</span><span class="n">${usd(m.usd)} · ${t("account.usage.requests", { count: m.requests })}</span></div>`)}+ ${!d.models.length && html`<p class="hint">${t("account.usage.empty")}</p>`}</div>`}- <div class="actions"><button type="button" class="btn" data-autofocus onClick=${onClose}>关闭</button></div>+ <div class="actions"><button type="button" class="btn" data-autofocus onClick=${onClose}>${t("common.close")}</button></div><//>`;}@@ -58,16 +57,16 @@ export function NotificationsSheet({ onClose }) {useEffect(() => {api("/account/notifications").then((r) => setD(r.data || { items: [] })).catch((e) => setErr(e.message));}, []);- return html`<${Sheet} title="Modelflare 通知" wide onClose=${onClose}>+ return html`<${Sheet} title=${t("account.notifications.title")} wide onClose=${onClose}>${err && html`<div class="err-text" role="alert">${err}</div>`}${!d && !err && html`<${Skeleton} w="100%" h=${80} />`}- ${d && !d.items.length && html`<p class="hint">没有通知</p>`}+ ${d && !d.items.length && html`<p class="hint">${t("account.notifications.empty")}</p>`}${d && d.items.map((n) => html`<div class=${`notif${n.read_at ? "" : " unread"}`}>${n.title && html`<b>${n.title}</b>`}<p>${n.content}</p>- <time>${new Date(n.created_at * 1000).toLocaleString()}</time>- ${notifLink(n.link) && html`<a class="text" href=${notifLink(n.link)} target="_blank" rel="noopener noreferrer">查看详情 ↗</a>`}+ <time>${fmtTime(n.created_at * 1000)}</time>+ ${notifLink(n.link) && html`<a class="text" href=${notifLink(n.link)} target="_blank" rel="noopener noreferrer">${t("account.notifications.details")}</a>`}</div>`)}- <div class="actions"><button type="button" class="btn" data-autofocus onClick=${onClose}>关闭</button></div>+ <div class="actions"><button type="button" class="btn" data-autofocus onClick=${onClose}>${t("common.close")}</button></div><//>`;}diff --git a/ui/screens/bot-settings.js b/ui/screens/bot-settings.jsindex 2644d91..36d2f6d 100644--- a/ui/screens/bot-settings.js+++ b/ui/screens/bot-settings.js@@ -6,9 +6,10 @@ import { ModelPicker, shortModel } from "../components/model-picker.js";import { api } from "../lib/api.js";import { confirmSheet, failed, saved } from "../lib/store.js";import { usd } from "../lib/links.js";-import { PERMS, FULL_WARNING, confirmPermission } from "../lib/perms.js";-import { CHANNEL_NAME, SOURCE_LABEL } from "../lib/access.js";+import { perms, fullWarning, confirmPermission } from "../lib/perms.js";+import { channelName, sourceLabel } from "../lib/access.js";import { fmtAgo } from "../lib/format.js";+import { t } from "../lib/i18n.js";function Row({ id, name, sub, title, children, off }) {return html`<div class=${`row${off ? " off" : ""}`} id=${`bot-${id}`} title=${title}>@@ -60,20 +61,20 @@ function BudgetRows({ bot, budget, account, onSaved, onOpenSettings }) {if (v !== budget.limitUsd) save(budget.enabled, v);};if (!signedIn) {- return html`<${Row} id="budget" name="预算" sub="登录 Modelflare 账户后,可以给这个机器人单独设花费上限">- <button type="button" class="text accent" onClick=${() => onOpenSettings("modelflare", "account")}>去登录</button>+ return html`<${Row} id="budget" name=${t("botSettings.budget.name")} sub=${t("botSettings.budget.signedOut")}>+ <button type="button" class="text accent" onClick=${() => onOpenSettings("modelflare", "account")}>${t("botSettings.budget.signIn")}</button><//>`;}const sub = !budget.enabled- ? "与其他机器人共用本机的 Key,不单独限额"+ ? t("botSettings.budget.off"): use- ? `已用 ${usd(use.used_usd)},还剩 ${usd(use.remain_usd)}${use.status === "exhausted" ? " · 已用完,机器人暂停调用模型" : ""}`- : "用这个机器人自己的 Key,花到上限就停";- return html`<${Row} id="budget" name="预算" sub=${sub}>- <${Switch} label="预算" value=${budget.enabled} disabled=${busy} onChange=${(v) => save(v, Number(limit) || budget.limitUsd)} />+ ? t(use.status === "exhausted" ? "botSettings.budget.exhausted" : "botSettings.budget.usage", { used: usd(use.used_usd), remain: usd(use.remain_usd) })+ : t("botSettings.budget.on");+ return html`<${Row} id="budget" name=${t("botSettings.budget.name")} sub=${sub}>+ <${Switch} label=${t("botSettings.budget.name")} value=${budget.enabled} disabled=${busy} onChange=${(v) => save(v, Number(limit) || budget.limitUsd)} /><//>- <${Row} id="budget-limit" name="上限(美元)" sub="包括已经花掉的部分;调高后用完的 Key 会自动恢复" off=${!budget.enabled}>- <input class="field num-in" type="number" min="0" step="1" inputmode="decimal" aria-label="预算上限(美元)" value=${limit} disabled=${!budget.enabled || busy}+ <${Row} id="budget-limit" name=${t("botSettings.budget.limit")} sub=${t("botSettings.budget.limitSub")} off=${!budget.enabled}>+ <input class="field num-in" type="number" min="0" step="1" inputmode="decimal" aria-label=${t("botSettings.budget.limitLabel")} value=${limit} disabled=${!budget.enabled || busy}onInput=${(e) => setLimit(e.target.value)} onBlur=${commitLimit} onKeyDown=${(e) => e.key === "Enter" && e.target.blur()} /><//>`;}@@ -100,45 +101,45 @@ function AccessRows({ botId }) {const remove = async (e) => {const denied = e.status === "denied";if (!(await confirmSheet({- title: denied ? `移除「${e.who}」?` : `不再允许「${e.who}」使用?`,- body: denied ? "移除后他再发消息,会重新出现在信息面板的使用请求里。" : "他再发消息时只会收到一句提示,需要你重新允许。",- confirmLabel: "移除",+ title: t(denied ? "botSettings.access.removeDeniedTitle" : "botSettings.access.revokeTitle", { who: e.who }),+ body: t(denied ? "botSettings.access.removeDeniedBody" : "botSettings.access.revokeBody"),+ confirmLabel: t("botSettings.access.remove"),danger: !denied,}))) return;call(encodeURIComponent(e.id), "DELETE");};const resetOwner = async (ch, o) => {- const name = CHANNEL_NAME[ch];- if (!(await confirmSheet({ title: `更换${name}主人?`, body: `下一个给机器人发消息的人会成为${name}主人,「${o.name}」需要重新被允许。`, confirmLabel: "更换", danger: true }))) return;+ const name = channelName(ch);+ if (!(await confirmSheet({ title: t("botSettings.access.resetOwnerTitle", { channel: name }), body: t("botSettings.access.resetOwnerBody", { channel: name, who: o.name }), confirmLabel: t("botSettings.access.reset"), danger: true }))) return;call(`owner/${ch}`, "DELETE");};- if (!d) return html`<div class="list-head">谁能使用</div><div class="list"><div class="row"><${Skeleton} w="45%" /></div></div>`;+ if (!d) return html`<div class="list-head">${t("botSettings.access.head")}</div><div class="list"><div class="row"><${Skeleton} w="45%" /></div></div>`;const allowed = d.entries.filter((e) => e.status === "allowed");const denied = d.entries.filter((e) => e.status === "denied");const owner = (ch) => {const o = d.owners[ch];- return o && html`<${Row} id=${`access-${ch}`} name=${`${CHANNEL_NAME[ch]}主人`}>+ return o && html`<${Row} id=${`access-${ch}`} name=${t("botSettings.access.owner", { channel: channelName(ch) })}><span class="val">${o.name}</span>- ${o.via !== "login" && html`<button type="button" class="text" onClick=${() => resetOwner(ch, o)}>更换</button>`}+ ${o.via !== "login" && html`<button type="button" class="text" onClick=${() => resetOwner(ch, o)}>${t("botSettings.access.reset")}</button>`}<//>`;};- return html`<div class="list-head">谁能使用</div>+ return html`<div class="list-head">${t("botSettings.access.head")}</div><div class="list">- <${Row} id="access" name="只有主人和你允许的人" />+ <${Row} id="access" name=${t("botSettings.access.policy")} />${owner("weixin")}${owner("feishu")}</div>- ${allowed.length > 0 && html`<div class="list-head">允许名单<span class="badge count">${allowed.length}</span></div>+ ${allowed.length > 0 && html`<div class="list-head">${t("botSettings.access.allowed")}<span class="badge count">${allowed.length}</span></div><div class="list">- ${allowed.map((e) => html`<${Row} key=${e.id} id=${`access-${e.id}`} name=${e.who} sub=${[SOURCE_LABEL[e.source] || e.source, e.decidedAt ? fmtAgo(e.decidedAt) : ""].filter(Boolean).join(" · ")}>- <button type="button" class="text danger" onClick=${() => remove(e)}>移除</button>+ ${allowed.map((e) => html`<${Row} key=${e.id} id=${`access-${e.id}`} name=${e.who} sub=${[sourceLabel(e.source), e.decidedAt ? fmtAgo(e.decidedAt) : ""].filter(Boolean).join(" · ")}>+ <button type="button" class="text danger" onClick=${() => remove(e)}>${t("botSettings.access.remove")}</button><//>`)}</div>`}- ${denied.length > 0 && html`<div class="list-head">拒绝过的人</div>+ ${denied.length > 0 && html`<div class="list-head">${t("botSettings.access.denied")}</div><div class="list">- ${denied.map((e) => html`<${Row} key=${e.id} id=${`access-${e.id}`} name=${e.who} sub=${`${fmtAgo(e.decidedAt)}拒绝 · 他再发消息不会收到任何回复`}>- <button type="button" class="text accent" onClick=${() => call(`${encodeURIComponent(e.id)}/approve`, "POST")}>允许</button>- <button type="button" class="text" onClick=${() => remove(e)}>移除</button>+ ${denied.map((e) => html`<${Row} key=${e.id} id=${`access-${e.id}`} name=${e.who} sub=${t("botSettings.access.deniedSub", { when: fmtAgo(e.decidedAt) })}>+ <button type="button" class="text accent" onClick=${() => call(`${encodeURIComponent(e.id)}/approve`, "POST")}>${t("botSettings.access.allow")}</button>+ <button type="button" class="text" onClick=${() => remove(e)}>${t("botSettings.access.remove")}</button><//>`)}</div>`}`;}@@ -186,7 +187,7 @@ export function BotSettingsScreen({ bot, section, models, modelsError, reloadModonBotUpdated();};const del = async () => {- if (!(await confirmSheet({ title: `删除「${bot.name}」?`, body: "会永久删除这个机器人及其全部会话,无法恢复。", confirmLabel: "永久删除", danger: true }))) return;+ if (!(await confirmSheet({ title: t("botSettings.delete.title", { name: bot.name }), body: t("botSettings.delete.body"), confirmLabel: t("botSettings.delete.confirm"), danger: true }))) return;try {await api(`/bots/${bot.id}`, { method: "DELETE" });onDeleted();@@ -205,35 +206,35 @@ export function BotSettingsScreen({ bot, section, models, modelsError, reloadModconst 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">- <button type="button" class="icon-btn set-back" aria-label="返回对话" title="返回对话(Esc)" onClick=${onBack}><${Icon} name="arrowLeft" size=${16} /></button>+ <button type="button" class="icon-btn set-back" aria-label=${t("botSettings.back")} title=${t("botSettings.backTitle")} onClick=${onBack}><${Icon} name="arrowLeft" size="md" /></button><${BotAvatar} bot=${bot} char=${s && s.avatar} size=${36} cue=${hi} pokeable />- <div class="set-titles"><h1 class="set-title">${bot.name}</h1><div class="set-sub">机器人设置</div></div>+ <div class="set-titles"><h1 class="set-title">${bot.name}</h1><div class="set-sub">${t("botSettings.title")}</div></div></div><div class="set-body">- <div class="list-head">身份</div>+ <div class="list-head">${t("botSettings.identity")}</div><div class="set-field" id="bot-avatar">- <span class="k">头像<span class="hint">每个角色有自己的小动作</span></span>+ <span class="k">${t("botSettings.avatar")}<span class="hint">${t("botSettings.avatarHint")}</span></span>${s ? html`<${AvatarPicker} value=${s.avatar} fallback=${charOf(bot)} onChange=${pickAvatar} />` : html`<${Skeleton} w="60%" />`}</div><label class="set-field" id="bot-name">- <span class="k">名称</span>+ <span class="k">${t("botSettings.name")}</span><input class="field" value=${name} 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()); } }} /></label><label class="set-field" id="bot-prompt">- <span class="k">人设 / 系统提示词<span class="hint">离开输入框时保存,下一条消息起生效</span></span>- <textarea class="field" ref=${promptRef} placeholder="例如:你是一个乐于助人的中文助手,回答简洁准确。" value=${prompt}+ <span class="k">${t("botSettings.prompt")}<span class="hint">${t("botSettings.promptHint")}</span></span>+ <textarea class="field" ref=${promptRef} placeholder=${t("botSettings.promptPlaceholder")} value=${prompt}onInput=${(e) => setPrompt(e.target.value)} onBlur=${() => prompt !== (bot.systemPrompt || "") && putBot({ systemPrompt: prompt })} /></label>- <div class="list-head">模型</div>+ <div class="list-head">${t("botSettings.model.head")}</div><div class="list">- <${Row} id="model" name="默认模型" sub="会话里还可以临时切换">+ <${Row} id="model" name=${t("botSettings.model.default")} sub=${t("botSettings.model.defaultSub")}><${ModelButton} value=${bot.defaultModel} models=${models} modelsError=${modelsError} reloadModels=${reloadModels}- resetLabel=${`跟随全局默认${defaultModel ? `(${shortModel(defaultModel)})` : ""}`} onChange=${(m) => putBot({ defaultModel: m })} />+ resetLabel=${defaultModel ? t("botSettings.model.followGlobalWith", { model: shortModel(defaultModel) }) : t("botSettings.model.followGlobal")} 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 })} />`}+ <${Row} id="utility" name=${t("botSettings.model.utility")} sub=${t("botSettings.model.utilitySub")}>+ ${s && html`<${ModelButton} value=${s.utilityModel} models=${models} modelsError=${modelsError} reloadModels=${reloadModels} resetLabel=${t("botSettings.model.sameAsChat")} onChange=${(m) => put({ utilityModel: m })} />`}<//>${s && account && html`<${BudgetRows} bot=${bot} budget=${s.budget} account=${account} onOpenSettings=${onOpenSettings}onSaved=${(settings) => setD((v) => ({ ...v, settings }))} />`}@@ -241,67 +242,67 @@ export function BotSettingsScreen({ bot, section, models, modelsError, reloadMod${!s && html`<div class="list"><div class="row"><${Skeleton} w="45%" /></div><div class="row"><${Skeleton} w="35%" /></div></div>`}${s && html`- <div class="list-head">权限</div>+ <div class="list-head">${t("botSettings.perm.head")}</div><div class="list">- <${Row} id="permission" name="文件权限" sub=${PERMS[s.permission] ? PERMS[s.permission].note : ""}- title="工作区可写(默认):只能改本机器人工作区,越界操作需审批;只读:不能改文件,命令在只读沙箱中运行;完全权限:命令不经沙箱,只有递归删除仍需确认">- <${Seg} label="文件权限" value=${s.permission} onChange=${pickPerm} options=${[["workspace", "工作区可写"], ["readonly", "只读"], ["full", "完全权限"]]} />+ <${Row} id="permission" name=${t("botSettings.perm.name")} sub=${perms()[s.permission]?.note ?? ""}+ title=${t("botSettings.perm.title")}>+ <${Seg} label=${t("botSettings.perm.name")} value=${s.permission} onChange=${pickPerm} options=${[["workspace", t("botSettings.perm.workspace")], ["readonly", t("botSettings.perm.readonly")], ["full", t("botSettings.perm.full")]]} /><//></div>- ${s.permission === "full" && html`<${Notice} tone="red">${FULL_WARNING}<//>`}+ ${s.permission === "full" && html`<${Notice} tone="red">${fullWarning()}<//>`}<${AccessRows} botId=${bot.id} />- <div class="list-head">记忆</div>+ <div class="list-head">${t("botSettings.memory.head")}</div><div class="list">- <${Row} id="memory" name="长期记忆" sub="remember / forget / recall">- <${Switch} label="长期记忆" value=${s.memory.enabled} onChange=${(v) => put({ memory: { enabled: v } })} />+ <${Row} id="memory" name=${t("botSettings.memory.name")} sub="remember / forget / recall">+ <${Switch} label=${t("botSettings.memory.name")} value=${s.memory.enabled} onChange=${(v) => put({ memory: { enabled: v } })} /><//>- <${Row} id="memory-review" name="回合结束后自动整理" off=${!s.memory.enabled}>- <${Switch} label="自动整理记忆" value=${s.memory.review} disabled=${!s.memory.enabled} onChange=${(v) => put({ memory: { review: v } })} />+ <${Row} id="memory-review" name=${t("botSettings.memory.review")} off=${!s.memory.enabled}>+ <${Switch} label=${t("botSettings.memory.reviewLabel")} value=${s.memory.review} disabled=${!s.memory.enabled} onChange=${(v) => put({ memory: { review: v } })} /><//>- <${Row} id="memory-team" name="允许写入团队记忆" sub="所有机器人共享" off=${!s.memory.enabled}>- <${Switch} label="团队记忆" value=${s.memory.teamWrite} disabled=${!s.memory.enabled} onChange=${(v) => put({ memory: { teamWrite: v } })} />+ <${Row} id="memory-team" name=${t("botSettings.memory.team")} sub=${t("botSettings.memory.teamSub")} off=${!s.memory.enabled}>+ <${Switch} label=${t("botSettings.memory.teamLabel")} value=${s.memory.teamWrite} disabled=${!s.memory.enabled} onChange=${(v) => put({ memory: { teamWrite: v } })} /><//></div>- <div class="list-head">上下文</div>+ <div class="list-head">${t("botSettings.context.head")}</div><div class="list">- <${Row} id="steward" name="自动压缩或开新段" sub="上下文变长时整理,并留下交接便条">- <${Switch} label="上下文管家" value=${s.steward.enabled} onChange=${(v) => put({ steward: { enabled: v } })} />+ <${Row} id="steward" name=${t("botSettings.context.name")} sub=${t("botSettings.context.sub")}>+ <${Switch} label=${t("botSettings.context.label")} value=${s.steward.enabled} onChange=${(v) => put({ steward: { enabled: v } })} /><//></div>- <div class="list-head">电脑操作</div>+ <div class="list-head">${t("botSettings.computer.head")}</div><div class="list">- <${Row} id="computer" name="电脑操作" sub=${cu ? cu.reason : ""} title=${cu && cu.notice}>+ <${Row} id="computer" name=${t("botSettings.computer.head")} sub=${cu ? cu.reason : ""} title=${cu && cu.notice}><span class=${`dot ${cu && cu.available ? "ok" : "err"}`}></span>- <${Switch} label="电脑操作" value=${s.computerUse.enabled} onChange=${(v) => put({ computerUse: { enabled: v } })} />+ <${Switch} label=${t("botSettings.computer.head")} value=${s.computerUse.enabled} onChange=${(v) => put({ computerUse: { enabled: v } })} /><//>- <${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-backend" name=${t("botSettings.computer.backend")} off=${!s.computerUse.enabled}>+ <${MenuButton} label=${t("botSettings.computer.backendLabel")} value=${s.computerUse.backend} disabled=${!s.computerUse.enabled} onChange=${(v) => put({ computerUse: { backend: v } })}+ options=${[["cua", "Cua Driver", t("botSettings.computer.cuaNote")], ...(codex ? [["codex", t("botSettings.computer.codex"), codex.available ? t("botSettings.computer.macOnly") : t("botSettings.computer.macOnlyUnavailable")]] : [])]} /><//>- <${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", "改变界面前先问我"]]} />+ <${Row} id="computer-approval" name=${t("botSettings.computer.approval")} sub=${s.computerUse.approval === "auto" ? t("botSettings.computer.autoSub") : t("botSettings.computer.askSub")} off=${!s.computerUse.enabled}>+ <${Seg} label=${t("botSettings.computer.approvalLabel")} value=${s.computerUse.approval} disabled=${!s.computerUse.enabled} onChange=${(v) => put({ computerUse: { approval: v } })}+ options=${[["auto", t("botSettings.computer.auto")], ["ask-input", t("botSettings.computer.ask")]]} /><//></div>- <div class="list-head">生图 / 生视频</div>+ <div class="list-head">${t("botSettings.media.head")}</div><div class="list">- <${Row} id="media-confirm" name="生成前确认"- sub=${s.media.confirm === "always" ? "每次生成前都问我用哪个模型" : "默认模型能用、花费不高时直接生成;换模型、预计超过 $0.5 或要求不明确时先问我"}>- <${Seg} label="生成前确认" value=${s.media.confirm} onChange=${(v) => put({ media: { confirm: v } })}- options=${[["auto", "需要时再问"], ["always", "每次都问"]]} />+ <${Row} id="media-confirm" name=${t("botSettings.media.confirm")}+ sub=${s.media.confirm === "always" ? t("botSettings.media.alwaysSub") : t("botSettings.media.autoSub")}>+ <${Seg} label=${t("botSettings.media.confirm")} value=${s.media.confirm} onChange=${(v) => put({ media: { confirm: v } })}+ options=${[["auto", t("botSettings.media.auto")], ["always", t("botSettings.media.always")]]} /><//></div>`}- <div class="list-head">危险操作</div>+ <div class="list-head">${t("botSettings.danger.head")}</div><div class="list">- <${Row} id="delete" name="删除机器人" sub="永久删除这个机器人及其全部会话">- <button type="button" class="text danger" onClick=${del}>删除机器人</button>+ <${Row} id="delete" name=${t("botSettings.danger.delete")} sub=${t("botSettings.danger.deleteSub")}>+ <button type="button" class="text danger" onClick=${del}>${t("botSettings.danger.delete")}</button><//></div></div>diff --git a/ui/screens/chat.js b/ui/screens/chat.jsindex 12016ed..d439cba 100644--- a/ui/screens/chat.js+++ b/ui/screens/chat.js@@ -8,29 +8,38 @@ import { ModelPicker, shortModel, sameModel } from "../components/model-picker.jimport { PwshHint } from "../components/pwsh-hint.js";import { ActivityLine, currentStep, upsertStep } from "../components/activity.js";import { TaskChip } from "../components/tasks.js";+import { GuideChecklist, MediaDemo } from "../components/guide.js";import { api, attachChat, streamChat } from "../lib/api.js";-import { confirmSheet, failed, saved } from "../lib/store.js";+import { confirmSheet, failed, saved, useStore } from "../lib/store.js";+import { completed, currentStep as guideStep, demo, fill, guide, isActive, isMediaFile, markDone, refreshGuide } from "../lib/guide.js";import { fmtSep, fmtClock, fmtDur } from "../lib/format.js";-import { PERMS, confirmPermission } from "../lib/perms.js";+import { perms, confirmPermission } from "../lib/perms.js";+import { prefs } from "../lib/prefs.js";+import { t, useLang } from "../lib/i18n.js";+import { notify, plainSnippet } from "../lib/notify.js";+import { reducedMotion, usePresence } from "../design/motion.js";-const COMMANDS = [- ["/model", "列出或切换模型"],- ["/new", "开始新的一段对话(旧对话归档并留交接便条)"],- ["/reset", "清空本会话上下文"],- ["/status", "查看当前模型、运行方式和处理进度"],- ["/stop", "中止正在处理的消息"],- ["/tasks", "列出后台任务(/stop 编号 停止一个)"],- ["/help", "显示全部命令"],+// 文案跟着界面语言:渲染时再取(写成函数,不在模块顶层缓存翻译)+const commands = () => [+ ["/model", t("chat.commands.model")],+ ["/new", t("chat.commands.new")],+ ["/reset", t("chat.commands.reset")],+ ["/status", t("chat.commands.status")],+ ["/stop", t("chat.commands.stop")],+ ["/tasks", t("chat.commands.tasks")],+ ["/help", t("chat.commands.help")],];// 文件权限(输入框左下角,参考 Codex 的权限胶囊):机器人设置里的同一项,预设在 lib/perms.jsconst NEAR_BOTTOM = 80;-const LINE_PX = 22;+const isMac = /Mac|iPhone|iPad/.test(navigator.platform);+const MOD_ENTER = isMac ? "⌘Enter" : "Ctrl+Enter";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);+const isError = (s) => typeof s === "string" && s.startsWith("⚠️");+const errText = (s) => s.replace(/^⚠️\s*/, "");+// 服务端报错的文字(两种语言都认)+const isAuthError = (s) => /HTTP 401\b|\b401\b.*(key|密钥|unauthor)/i.test(s); // i18n-ignore// steps:代理回合的活动记录有几步(展开时按 mid 取)function toItems(messages) {@@ -66,8 +75,8 @@ export function PromptCard({ requestId, fallback }) {}, [load]);useEffect(() => {if (!row || row.status !== "pending") return;- const t = setInterval(load, 3000);- return () => clearInterval(t);+ const timer = setInterval(load, 3000);+ return () => clearInterval(timer);}, [row && row.status]);if (gone || (!row && !requestId)) return html`<${Notice}><span class="pre-wrap">${fallback}</span><//>`;@@ -86,12 +95,12 @@ export function PromptCard({ requestId, fallback }) {};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>+ <div class="meta"><span>${t("chat.approval.needed", { code: html`<span class="num">${row.code}</span>` })}</span>${!pending && html`<${Badge} s=${row.status} />`}</div>+ <div class="q">${row.reason || t("chat.approval.fallbackReason")}</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>+ <button type="button" class="btn primary" disabled=${busy} onClick=${() => decide(true)}>${t("chat.approval.allowOnce")}</button>+ <button type="button" class="btn" disabled=${busy} onClick=${() => decide(false)}>${t("chat.approval.deny")}</button></div>`}</div>`;}@@ -135,12 +144,12 @@ export function PromptCard({ requestId, fallback }) {</div>`}</div>`)}${pending && !single && html`<div class="answer">- <input class="field" placeholder=${qs.some((q) => (q.options || []).length) ? "其他回答(可选)" : "输入你的回答"} value=${custom}+ <input class="field" placeholder=${qs.some((q) => (q.options || []).length) ? t("chat.question.otherOptional") : t("chat.question.yourAnswer")} 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>+ <button type="button" class="btn primary" disabled=${busy || (!custom.trim() && !Object.values(picked).some((v) => v.length))} onClick=${sendAll}>${t("chat.question.submit")}</button></div>`}${pending && single && html`<div class="answer">- <input class="field" placeholder="或者输入其他回答" value=${custom} onInput=${(e) => setCustom(e.target.value)}+ <input class="field" placeholder=${t("chat.question.orOther")} 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>`}@@ -149,10 +158,10 @@ export function PromptCard({ requestId, fallback }) {function FileCard({ name }) {return html`<div class="file-card">- <${Icon} name="file" size=${32} stroke=${1.2} />+ <${Icon} name="file" size="xl" /><div class="grow"><div class="fname">${name}</div>- <div class="fsub">已交付到机器人工作区 · 微信/飞书会直接发送</div>+ <div class="fsub">${t("chat.file.delivered")}</div></div></div>`;}@@ -165,8 +174,8 @@ function WorkLine({ live, stopping, text, startedAt, workedMs, steps, count, loaconst [, tick] = useState(0);useEffect(() => {if (!live) return;- const t = setInterval(() => tick((n) => n + 1), 1000);- return () => clearInterval(t);+ const timer = setInterval(() => tick((n) => n + 1), 1000);+ return () => clearInterval(timer);}, [live]);const ms = live ? Date.now() - startedAt : workedMs;if (!live && !(ms >= 3000) && !steps?.length && !count) return null;@@ -174,21 +183,23 @@ function WorkLine({ live, stopping, text, startedAt, workedMs, steps, count, loa// 按了停止:代理要重启进程,可能要几秒,先说清楚在停const label = live? stopping- ? `正在停止…${ms >= 3000 ? ` 已处理 ${fmtDur(ms)}` : ""}`- : `${text ? `正在回复 ${fmtDur(ms)}` : ms >= 3000 ? `思考中 ${fmtDur(ms)}` : "思考中"}${cur ? ` · ${cur}` : ""}`- : ms >= 3000 ? `用时 ${fmtDur(ms)}` : "处理过程";- return html`<${ActivityLine} label=${label} live=${live} steps=${steps} count=${count} load=${load} />`;+ ? t("chat.work.stopping", { extra: ms >= 3000 ? t("chat.work.processedFor", { d: fmtDur(ms) }) : "" })+ : `${text ? t("chat.work.replying", { d: fmtDur(ms) }) : ms >= 3000 ? t("chat.work.thinkingFor", { d: fmtDur(ms) }) : t("chat.work.thinking")}${cur ? ` · ${cur}` : ""}`+ : ms >= 3000 ? t("chat.work.done", { d: fmtDur(ms) }) : t("chat.work.process");+ // 换阶段(思考 → 回复 → 用时)时文字淡入:key 变才重播,秒数跳动不重播+ const phase = !live ? "done" : stopping ? "stop" : text ? "reply" : "think";+ return html`<${ActivityLine} label=${label} phase=${phase} live=${live} steps=${steps} count=${count} load=${load} />`;}/** 消息下方的操作:复制 + 时刻(悬停时出现,最后一条回复常显) */function MsgActions({ text, at }) {- return html`<div class="msg-actions"><${CopyButton} text=${text} label="复制这条消息" />${at && html`<span class="when num">${fmtClock(at)}</span>`}</div>`;+ return html`<div class="msg-actions"><${CopyButton} text=${text} label=${t("chat.copyMessage")} />${at && html`<span class="when num">${fmtClock(at)}</span>`}</div>`;}function ErrorNotice({ text, onRetry, onFixKey }) {const auth = isAuthError(text);- return html`<${Notice} tone="red" action=${html`${auth && onFixKey && html`<button type="button" class="btn" onClick=${onFixKey}>去更新</button>`}- ${onRetry && html`<button type="button" class="btn" onClick=${onRetry}>重试</button>`}`}>${auth ? "Modelflare 密钥失效或已被撤销。" : text}<//>`;+ return html`<${Notice} tone="red" action=${html`${auth && onFixKey && html`<button type="button" class="btn" onClick=${onFixKey}>${t("chat.error.fixKey")}</button>`}+ ${onRetry && html`<button type="button" class="btn" onClick=${onRetry}>${t("common.retry")}</button>`}`}>${auth ? t("chat.error.authInvalid") : text}<//>`;}export function ChatScreen({ bot, models, modelsError, reloadModels, defaultModel, infoOpen, onToggleInfo, onWorking, onOpenSettings, onOpenBotSettings, onBotUpdated, pending = 0, serverBusy = false }) {@@ -207,6 +218,7 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultModeconst [slashOff, setSlashOff] = useState(false);const [loadErr, setLoadErr] = useState("");const [cue, setCue] = useState(null); // 头像的一次性反应(出错);完成时头像自己会播+ const lang = useLang();const scroller = useRef(null);const stick = useRef(true);const ta = useRef(null);@@ -224,6 +236,32 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultMode// 这个会话的后台任务(胶囊挂在请求它的那条消息的回复下面);任务结束时结果写进了历史,重新读一次const [tasks, setTasks] = useState([]);const taskGroups = useRef({});+ const sentOnce = useRef(false); // 发过消息:之后发送钮换回箭头时才播"升回来",打开页面时不动+ // 上手清单:完成一步时头像开心一下;引导卡片「填入」的句子进输入框(只认这个页面挂载之后的请求)+ const g = useStore(guide);+ const justDone = useStore(completed);+ const fillReq = useStore(fill);+ const demoReq = useStore(demo);+ const { sendKey } = useStore(prefs);+ const born = useRef(Date.now());+ // 生图的预置演示:只在本地对话流里放一遍(你的那句话 + 演示卡片),不发给机器人,刷新后就没了+ useEffect(() => {+ if (!demoReq || demoReq.at < born.current) return;+ stick.current = true;+ setItems((l) => [...(l || []), { kind: "msg", id: uid(), role: "user", text: demoReq.text, at: Date.now(), enter: true }, { kind: "media-demo", id: uid(), text: demoReq.text, enter: true }]);+ }, [demoReq && demoReq.at]);+ useEffect(() => {+ if (justDone && justDone.at > born.current) setCue({ kind: "done", at: justDone.at });+ }, [justDone && justDone.at]);+ useEffect(() => {+ if (!fillReq || fillReq.at < born.current) return;+ setText(fillReq.text);+ setSlashOff(true);+ requestAnimationFrame(() => {+ ta.current?.focus();+ autoGrow(ta.current);+ });+ }, [fillReq && fillReq.at]);// ended:刚接着的那条消息结束了 { since, ms },存下的回复照样显示"用时"(和一直停在这页时一样)const load = useCallback(async (ended) => {@@ -296,8 +334,8 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultModeif (!generating) loadTasks();}, [generating]);useEffect(() => {- const t = setInterval(loadTasks, tasksWorking ? 3000 : 15000);- return () => clearInterval(t);+ const timer = setInterval(loadTasks, tasksWorking ? 3000 : 15000);+ return () => clearInterval(timer);}, [loadTasks, tasksWorking]);// 只有用户本来就在底部附近时才跟随新内容;否则亮出"回到底部"@@ -317,7 +355,7 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultMode};const toBottom = () => {stick.current = true;- scroller.current?.scrollTo({ top: scroller.current.scrollHeight, behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" });+ scroller.current?.scrollTo({ top: scroller.current.scrollHeight, behavior: reducedMotion() ? "auto" : "smooth" });setUnseen(false);};@@ -337,7 +375,7 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultModesetItems((l) => {if (d.requestId && l.some((x) => x.kind === "prompt" && x.requestId === d.requestId)) return l;const i = l.findIndex((x) => x.id === liveId);- const c = { kind: "prompt", id: uid(), requestId: d.requestId, prompt: d.prompt, turn };+ const c = { kind: "prompt", id: uid(), requestId: d.requestId, prompt: d.prompt, turn, enter: true };return i < 0 ? [...l, c] : [...l.slice(0, i), c, ...l.slice(i)];});try {@@ -354,11 +392,17 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultModepatchLive(liveId, (it) => ({ ...it, text: d.text }));},activity: (d) => patchLive(liveId, (it) => ({ ...it, activity: upsertStep(it.activity, d) })),- prompt: card,- file: (d) => mounted.current && setItems((l) => [...l, { kind: "file", id: uid(), name: d.name, turn }]),+ prompt: (d) => {+ notify(bot.name, t("notify.prompt"), `amb-prompt-${bot.id}`);+ card(d);+ },+ file: (d) => {+ markDone(isMediaFile(d.name) ? "media" : "hands");+ if (mounted.current) setItems((l) => [...l, { kind: "file", id: uid(), name: d.name, turn, enter: true }]);+ },stopping: () => mounted.current && setStopping(true),error: (d) => {- finalText = "⚠️ " + (d.message || "出错了");+ finalText = "⚠️ " + (d.message || t("common.error"));},},f.ac.signal,@@ -392,21 +436,21 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultMode* 回复还在进行时又发一条(不是命令):交给服务端并进正在进行的处理,模型下一步就看到它,回复在那一条里一起给。* 用户消息先插在进行中的回复上面;服务端没能并入(那一轮刚好结束)时它按普通消息处理,结束后重新读历史。*/- const steer = async (t) => {+ const steer = async (msg) => {setText("");- requestAnimationFrame(() => autoGrow(ta.current, LINE_PX * 8 + 8));- lastUser.current = t;+ requestAnimationFrame(() => autoGrow(ta.current));+ lastUser.current = msg;stick.current = true;const turn = following.current?.turn;setItems((l) => {const list = l || [];- const user = { kind: "msg", id: uid(), role: "user", text: t, at: Date.now(), enter: true, turn };+ const user = { kind: "msg", id: uid(), role: "user", text: msg, at: Date.now(), enter: true, turn };const i = list.findIndex((x) => x.live && x.turn === turn);return i < 0 ? [...list, user] : [...list.slice(0, i), user, ...list.slice(i)];});reloadAfter.current = true;try {- await streamChat(bot.id, t, {}, new AbortController().signal);+ await streamChat(bot.id, msg, {}, new AbortController().signal);} catch (e) {failed(e);}@@ -417,20 +461,30 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultMode};const send = async (raw) => {- const t = (raw ?? text).trim();- if (t && (generating || following.current) && !t.startsWith("/") && raw === undefined) return steer(t);- if (!t || generating || following.current) return;+ const msg = (raw ?? text).trim();+ if (msg && (generating || following.current) && !msg.startsWith("/") && raw === undefined) return steer(msg);+ if (!msg || generating || following.current) return;if (raw === undefined) {setText("");- requestAnimationFrame(() => autoGrow(ta.current, LINE_PX * 8 + 8));+ requestAnimationFrame(() => autoGrow(ta.current));}- if (!t.startsWith("/")) lastUser.current = t;+ if (!msg.startsWith("/")) lastUser.current = msg;+ sentOnce.current = true;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, turn: liveId }, { kind: "msg", id: liveId, role: "assistant", text: "", at: Date.now(), live: true, startedAt: Date.now(), turn: liveId }]);- const finalText = await follow(liveId, liveId, (h, signal) => streamChat(bot.id, t, h, signal));+ const isReset = /^\/reset\b/i.test(msg);+ setItems((l) => [...(l || []), { kind: "msg", id: uid(), role: "user", text: msg, at: Date.now(), enter: true, turn: liveId }, { kind: "msg", id: liveId, role: "assistant", text: "", at: Date.now(), live: true, startedAt: Date.now(), turn: liveId }]);+ const finalText = await follow(liveId, liveId, (h, signal) => streamChat(bot.id, msg, h, signal));if (finalText === null) return;+ // 窗口不在前台时通知(设置 › 常规 › 回复完成时通知)+ if (finalText) notify(bot.name, isError(finalText) ? t("notify.replyError", { text: plainSnippet(errText(finalText)) }) : plainSnippet(finalText) || t("notify.replyDone"), `amb-reply-${bot.id}`);+ // 上手清单:普通消息有了回复就算打过招呼;/model 切换成功算换过模型;其余能从数据里看出来的(记忆、渠道)问一次后端+ if (finalText && !isError(finalText)) {+ if (!msg.startsWith("/")) markDone("hello");+ else if (/^\/model\s+\S/i.test(msg)) markDone("model");+ const gs = guide.get();+ if (isActive(gs) && guideStep(gs)) refreshGuide();+ }if (isError(finalText)) setCue({ kind: "error", at: Date.now() });if (reloadAfter.current) {reloadAfter.current = false;@@ -445,12 +499,12 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultMode}const { turn, ...it } = item; // 结束了:不再属于进行中的消息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, activity: it.activity, workedMs: Date.now() - it.startedAt });+ else if (isError(finalText)) out.push({ kind: "error", id: liveId, text: errText(finalText), retry: msg.startsWith("/") ? undefined : msg, at: it.at, activity: it.activity, workedMs: Date.now() - it.startedAt, enter: true });else if (finalText || it.activity?.length) out.push({ ...it, text: finalText, live: false, workedMs: Date.now() - it.startedAt });}return isReset && !isError(finalText) ? out.filter((x) => x.id === liveId) : out;});- if (/^\/model\s+\S/i.test(t)) load();+ if (/^\/model\s+\S/i.test(msg)) load();};/**@@ -474,14 +528,14 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultMode}} catch (e) {if (mounted.current) setStopping(false);- failed(`停止失败:${e.message}`);+ failed(t("chat.error.stopFailed", { error: e.message }));}};const loadActivity = (mid) => () => api(`/conversations/${encodeURIComponent(convId.current)}/messages/${mid}/activity`).then((d) => d.steps);// —— 斜杠命令菜单 ——const slashQuery = /^\/\S*$/.test(text) && !slashOff ? text.toLowerCase() : null;- const slashHits = slashQuery !== null ? COMMANDS.filter(([c]) => c.startsWith(slashQuery)) : [];+ 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);@@ -509,7 +563,8 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultModereturn setSlashOff(true);}}- if (e.key === "Enter" && !e.shiftKey) {+ // 发送键(设置 › 常规 › 发送消息):Enter 发送、Shift+Enter 换行;或 ⌘/Ctrl+Enter 发送、Enter 换行+ if (e.key === "Enter" && !e.shiftKey && (sendKey !== "mod" || e.metaKey || e.ctrlKey)) {e.preventDefault();send();} else if (e.key === "Escape" && generating) {@@ -540,6 +595,7 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultModeawait api(`/bots/${encodeURIComponent(bot.id)}/chat/model`, { method: "PUT", body: { model: m } });setConvModel(m);saved();+ markDone("model");} catch (e) {failed(e);}@@ -551,23 +607,24 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultModesetConvModel("");onBotUpdated(r.bot);saved();+ markDone("model");} catch (e) {failed(e);}};const plusItems = [- { label: "切换模型…", onSelect: () => requestAnimationFrame(() => setMenu("model")) },+ { label: t("chat.menu.switchModel"), onSelect: () => requestAnimationFrame(() => setMenu("model")) },{ sep: true },- { label: "开始新的一段对话", note: "/new", onSelect: () => send("/new") },+ { label: t("chat.menu.newConv"), note: "/new", onSelect: () => send("/new") },{- label: "清空上下文",+ label: t("chat.menu.reset"),note: "/reset",onSelect: async () => {- if (await confirmSheet({ title: "清空本会话上下文?", body: `「${bot.name}」会忘掉这段网页对话的内容;长期记忆保留。`, confirmLabel: "清空", danger: true })) send("/reset");+ if (await confirmSheet({ title: t("chat.reset.title"), body: t("chat.reset.body", { name: bot.name }), confirmLabel: t("chat.reset.confirm"), danger: true })) send("/reset");},},- { label: "查看状态", note: "/status", onSelect: () => send("/status") },- { label: "全部命令", note: "/help", onSelect: () => send("/help") },+ { label: t("chat.menu.status"), note: "/status", onSelect: () => send("/status") },+ { label: t("chat.menu.allCommands"), note: "/help", onSelect: () => send("/help") },];// —— 渲染 ——@@ -598,7 +655,7 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultMode}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" : ""}`;+ const cls = `msg-row ${role}${cont ? " cont" : ""}${it.enter ? " enter" : ""}${it.live ? " live" : ""}`;if (it.kind === "msg") {out.push(html`<div class=${`${cls}${it.id === lastAi ? " last" : ""}`} key=${it.id}>${it.role === "user"@@ -613,6 +670,8 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultModeout.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 === "media-demo") {+ out.push(html`<div class=${cls} key=${it.id}><${MediaDemo} prompt=${it.text} /></div>`);} else if (it.kind === "error") {out.push(html`<div class=${cls} key=${it.id}>${(it.activity?.length || it.steps) && html`<${WorkLine} workedMs=${it.workedMs} steps=${it.activity} count=${it.steps} load=${it.mid ? loadActivity(it.mid) : undefined} />`}@@ -624,85 +683,94 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultModeprev = it;}return out;- }, [items, generating, stopping, chipsAfter]);+ }, [items, generating, stopping, chipsAfter, lang]);const empty = items && items.length === 0;+ const showGuide = isActive(g) && !g.seen.includes("intro") && !!guideStep(g);// 头像跟着对话走:等你批准 > 还没出字(思考)/ 出字了(回复)> 你在输入(在听)const replying = generating && (items || []).some((x) => x.live && x.text);const face = pending > 0 ? "waiting" : generating ? (replying ? "replying" : "thinking") : text.trim() ? "listening" : "idle";- return html`<section class=${`chat${scrolled ? " scrolled" : ""}`} data-screen="chat" aria-label=${`和 ${bot.name} 的对话`}>+ const toBottomBtn = usePresence(!atBottom);+ // 点发送 / 停止不抢输入框的焦点:光标留在原处,接着就能打下一句(键盘 Tab 过去照样能按)+ const keepFocus = (e) => e.preventDefault();+ const permMap = perms();+ return html`<section class=${`chat${scrolled ? " scrolled" : ""}`} data-screen="chat" aria-label=${t("chat.aria", { name: bot.name })}><header class="chat-head">- <button type="button" class="head-bot bot-hover" aria-pressed=${infoOpen} title="信息面板(⌘⇧I)" onClick=${onToggleInfo}>+ <button type="button" class="head-bot bot-hover" data-guide="info" aria-pressed=${infoOpen} title=${t("chat.infoPanel")} onClick=${onToggleInfo}><${BotAvatar} bot=${bot} size=${22} state=${face} cue=${cue} /><span class="name">${bot.name}</span></button><span class="grow"></span>- <${IconButton} icon="compose" iconSize=${16} label="开始新的一段对话(/new)" disabled=${generating} onClick=${() => send("/new")} />- <${IconButton} icon="panel" iconSize=${16} label="信息面板(⌘⇧I)" on=${infoOpen} aria-pressed=${infoOpen} onClick=${onToggleInfo} />+ <${IconButton} icon="compose" iconSize="md" label=${t("chat.newConvCmd")} disabled=${generating} onClick=${() => send("/new")} />+ <${IconButton} icon="panel" iconSize="md" label=${t("chat.infoPanel")} on=${infoOpen} aria-pressed=${infoOpen} onClick=${onToggleInfo} /></header><div class="chat-scroll" ref=${scroller} onScroll=${onScroll}>- <div class="chat-col" role="log" aria-live="polite" aria-busy=${generating}>- ${loadErr && html`<${Notice} tone="red" action=${html`<button type="button" class="btn" onClick=${() => load()}>重试</button>`}>读取历史消息失败:${loadErr}<//>`}+ <div class=${`chat-col${items ? " ready" : ""}`} role="log" aria-live="polite" aria-busy=${generating}>+ ${loadErr && html`<${Notice} tone="red" action=${html`<button type="button" class="btn" onClick=${() => load()}>${t("common.retry")}</button>`}>${t("chat.error.loadHistory", { error: loadErr })}<//>`}${items === null && html`<div class="chat-skel"><${Skeleton} w="40%" /><${Skeleton} w="28%" /></div>`}- ${empty && html`<div class="chat-empty">+ ${empty && html`<div class=${`chat-empty${showGuide ? " with-guide" : ""}`}><${BotAvatar} bot=${bot} size=${88} state=${face} cue=${cue} lively pokeable greet />- <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>+ ${showGuide+ ? html`<h2>${t("chat.empty.guideTitle", { name: bot.name })}</h2>+ <p>${t("chat.empty.guideBody")}</p>+ <${GuideChecklist} bot=${bot} onSend=${(x) => send(x)} />`+ : html`<h2>${t("chat.empty.title", { name: bot.name })}</h2>+ <p>${t("chat.empty.body")}</p>+ <div class="chips">+ <button type="button" class="chip" onClick=${() => send(t("chat.empty.sample"))}>${t("chat.empty.sample")}</button>+ <button type="button" class="chip" onClick=${() => send("/help")}>${t("chat.empty.helpChip")}</button>+ </div>`}<${PwshHint} /></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>`}+ ${toBottomBtn.mounted && html`<button type="button" class=${`to-bottom${toBottomBtn.leaving ? " leaving" : ""}`} aria-label=${t("chat.toBottom")} onClick=${toBottom}><${Icon} name="down" size="md" />${unseen && html`<span class="new"></span>`}</button>`}<div class="composer-dock">- <div class="composer">- <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); }}+ <div class="composer" data-guide="composer">+ <textarea ref=${ta} rows="1" placeholder=${t("chat.composer.placeholder", { name: bot.name })} aria-label=${t("chat.composer.label")} value=${text}+ onInput=${(e) => { setText(e.target.value); setSlashOff(false); setSlashSel(0); autoGrow(e.target); }}onKeyDown=${onKey} /><div class="composer-bar">- <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=${15} stroke=${1.7} /></button>- ${PERMS[perm] && html`<button type="button" class=${`model-chip perm ${perm}`} ref=${permRef} title=${`文件权限:${PERMS[perm].note}`} aria-haspopup="menu" aria-expanded=${menu === "perm"}+ <button type="button" class="plus" ref=${plusRef} aria-label=${t("chat.menu.more")} aria-haspopup="menu" aria-expanded=${menu === "plus"} onClick=${() => setMenu(menu === "plus" ? null : "plus")}><${Icon} name="plus" size="md" /></button>+ ${permMap[perm] && html`<button type="button" class=${`model-chip perm ${perm}`} ref=${permRef} title=${t("chat.perm.title", { note: permMap[perm].note })} aria-haspopup="menu" aria-expanded=${menu === "perm"}onClick=${() => setMenu(menu === "perm" ? null : "perm")}>- <${Icon} name=${PERMS[perm].icon} size=${14} class="lead" /><span class="v">${PERMS[perm].label}</span><${Icon} name="chevDown" />+ <${Icon} name=${permMap[perm].icon} size="sm" class="lead" /><span class="v">${permMap[perm].label}</span><${Icon} name="chevDown" /></button>`}<span class="grow"></span>- <button type="button" class="model-chip" ref=${modelRef} title=${effective ? `当前模型:${effective}` : "选择模型"} aria-haspopup="listbox" aria-expanded=${menu === "model"}+ <button type="button" class="model-chip" ref=${modelRef} data-guide="model" title=${effective ? t("chat.composer.currentModel", { model: effective }) : t("chat.composer.pickModel")} aria-haspopup="listbox" aria-expanded=${menu === "model"}onClick=${() => setMenu(menu === "model" ? null : "model")}>- <span class="v">${effective ? shortModel(effective) : "选择模型"}</span><${Icon} name="chevDown" />+ <span class="v">${effective ? shortModel(effective) : t("chat.composer.pickModel")}</span><${Icon} name="chevDown" /></button>${generating && text.trim() && !text.trim().startsWith("/") && !stopping- ? html`<button type="button" class="send" aria-label="补充给正在进行的回复" title="补充给正在进行的回复(Enter)" onClick=${() => send()}><${Icon} name="up" size=${15} stroke=${2} /></button>`+ ? html`<button type="button" class="send" aria-label=${t("chat.composer.steer")} title=${t("chat.composer.steerTitle", { key: sendKey === "mod" ? MOD_ENTER : "Enter" })} onMouseDown=${keepFocus} onClick=${() => send()}><${Icon} name="up" size="md" strong /></button>`: null}${generating- ? html`<button type="button" class="send stop" aria-label=${stopping ? "正在停止…" : "停止生成(Esc)"} title=${stopping ? "正在停止…" : "停止(Esc)"}- disabled=${stopping} aria-busy=${stopping} onClick=${stop}>${stopping ? html`<${Spinner} />` : html`<${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>`}+ ? html`<button type="button" class="send stop" aria-label=${stopping ? t("chat.composer.stopping") : t("chat.composer.stop")} title=${stopping ? t("chat.composer.stopping") : t("chat.composer.stopTitle")}+ disabled=${stopping} aria-busy=${stopping} onMouseDown=${keepFocus} onClick=${stop}>${stopping ? html`<${Spinner} />` : html`<${Icon} name="stop" size="md" />`}</button>`+ : html`<button type="button" class=${`send${sentOnce.current ? " back" : ""}`} aria-label=${t("chat.composer.send")} title=${t("chat.composer.sendTitle", { key: sendKey === "mod" ? MOD_ENTER : "Enter" })} disabled=${!text.trim()} onMouseDown=${keepFocus} onClick=${() => send()}><${Icon} name="up" size="md" strong /></button>`}</div></div></div>- ${slashOpen && ta.current && html`<${Popover} anchor=${ta.current} prefer="up" width=${320} keepFocus label="命令" onClose=${() => setSlashOff(true)}>- <ul role="listbox" aria-label="命令">+ ${slashOpen && ta.current && html`<${Popover} anchor=${ta.current} prefer="up" width=${320} keepFocus label=${t("chat.commandsLabel")} onClose=${() => setSlashOff(true)}>+ <ul role="listbox" aria-label=${t("chat.commandsLabel")}>${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 === "perm" && html`<${Menu} anchor=${permRef.current} prefer="up" width=${280} label="文件权限" onClose=${() => setMenu(null)}+ ${menu === "plus" && html`<${Menu} anchor=${plusRef.current} prefer="up" width=${240} label=${t("chat.menu.more")} onClose=${() => setMenu(null)} items=${plusItems} />`}+ ${menu === "perm" && html`<${Menu} anchor=${permRef.current} prefer="up" width=${280} label=${t("chat.perm.menu")} onClose=${() => setMenu(null)}items=${[- { group: "文件权限" },- ...Object.entries(PERMS).map(([k, p]) => ({ label: p.label, note: p.note, icon: p.icon, danger: p.danger, cur: k === perm, onSelect: () => k !== perm && pickPerm(k) })),+ { group: t("chat.perm.menu") },+ ...Object.entries(permMap).map(([k, p]) => ({ label: p.label, note: p.note, icon: p.icon, danger: p.danger, cur: k === perm, onSelect: () => k !== perm && pickPerm(k) })),{ sep: true },- { label: "更多权限设置…", onSelect: () => onOpenBotSettings?.(bot.id, "permission") },+ { label: t("chat.perm.more"), onSelect: () => onOpenBotSettings?.(bot.id, "permission") },]} />`}${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 }} />`}+ reset=${{ label: t("chat.model.followBot"), note: shortModel(bot.defaultModel || defaultModel) || t("common.auto"), onSelect: () => pickModel("") }}+ foot=${{ label: t("chat.model.setDefault"), disabled: !effective || sameModel(effective, bot.defaultModel), onClick: setBotDefault }} />`}</section>`;}diff --git a/ui/screens/info-panel.js b/ui/screens/info-panel.jsindex 6dc668b..80ade74 100644--- a/ui/screens/info-panel.js+++ b/ui/screens/info-panel.js@@ -5,9 +5,11 @@ import { ActivityLine, currentStep, useNow } from "../components/activity.js";import { PromptCard } from "./chat.js";import { api } from "../lib/api.js";import { confirmSheet, failed, saved, toast } from "../lib/store.js";-import { fmtAgo, fmtDur, fmtTime } from "../lib/format.js";-import { CHANNEL_NAME } from "../lib/access.js";+import { markDone } from "../lib/guide.js";+import { fmtAgo, fmtClock, fmtDur, fmtTime } from "../lib/format.js";+import { channelName as accessChannel } from "../lib/access.js";import { TaskRow } from "../components/tasks.js";+import { t } from "../lib/i18n.js";export function usePoll(fn, ms, deps = []) {const [data, setData] = useState(null);@@ -16,12 +18,15 @@ export function usePoll(fn, ms, deps = []) {useEffect(() => {load();if (!ms) return;- const t = setInterval(load, ms);- return () => clearInterval(t);+ const timer = setInterval(load, ms);+ return () => clearInterval(timer);}, [load, ms]);return [data, err, load];}+/** 渠道名(渲染时取,跟着界面语言);不认识的渠道原样显示 id */+const channelName = (c) => ({ web: t("info.channel.web"), feishu: t("info.channel.feishu"), weixin: t("info.channel.weixin") })[c];+function FeishuRow({ bot, st, owner, reload }) {const [open, setOpen] = useState(false);const [appId, setAppId] = useState(bot.feishuAppId);@@ -41,7 +46,7 @@ function FeishuRow({ bot, st, owner, reload }) {setBusy(false);};const clear = async () => {- if (!(await confirmSheet({ title: "断开飞书?", body: "会清除这个机器人的飞书 App ID 与 App Secret。", confirmLabel: "断开", danger: true }))) return;+ if (!(await confirmSheet({ title: t("info.feishu.disconnectTitle"), body: t("info.feishu.disconnectBody"), confirmLabel: t("info.feishu.disconnect"), danger: true }))) return;try {await api(`/bots/${bot.id}/feishu`, { method: "DELETE" });setAppId("");@@ -52,19 +57,19 @@ function FeishuRow({ bot, st, owner, reload }) {};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>+ <div class="who"><div class="name">${t("info.channel.feishu")}</div><div class="sub">${st.detail || (bot.feishuAppId ? bot.feishuAppId : t("info.feishu.sub"))}</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>`}+ <label>App Secret${bot.feishuAppSecretMasked && html`<span class="hint">${t("info.feishu.secretSaved", { masked: 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>`}+ <button type="button" class="btn primary" disabled=${!appId.trim() || busy} onClick=${save}>${busy ? html`<${Spinner} />` : t("info.feishu.saveConnect")}</button>+ ${bot.feishuAppId && html`<button type="button" class="text danger" onClick=${clear}>${t("info.feishu.disconnect")}</button>`}</div>- ${bot.feishuAppId && owner === null && html`<p class="hint">用你自己的飞书给机器人发一句话,就完成绑定。</p>`}- <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>+ ${bot.feishuAppId && owner === null && html`<p class="hint">${t("info.feishu.bindHint")}</p>`}+ <p class="hint">${t("info.feishu.setupHint", { event: html`<code>im.message.receive_v1</code>`, p1: html`<code>im:message.p2p_msg:readonly</code>`, p2: html`<code>im:message:send_as_bot</code>`, p3: html`<code>cardkit:card:write</code>` })}</p></div>`}`;}@@ -76,31 +81,31 @@ function WeixinRow({ bot, st, reload }) {useEffect(() => {if (!active) return;setOpen(true);- const t = setInterval(reload, 1500);- return () => clearInterval(t);+ const timer = setInterval(reload, 1500);+ return () => clearInterval(timer);}, [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");+ if (await confirmSheet({ title: t("info.weixin.unlinkTitle"), body: t("info.weixin.unlinkBody"), confirmLabel: t("info.weixin.unlink"), danger: true })) call("/logout");};- return html`<div class="row clickable" onClick=${() => setOpen((v) => !v)} role="button" tabindex="0" aria-expanded=${open}+ return html`<div class="row clickable" data-guide="weixin" 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>+ <div class="who"><div class="name">${t("info.channel.weixin")}</div><div class="sub">${st.account ? t("info.weixin.linked", { id: st.account.ilinkBotId }) : st.detail || t("info.weixin.sub")}</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 class="panel-qr" src=${login.qrDataUrl} alt="微信登录二维码" />- <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>`}+ ${active && login.qrDataUrl && html`<img class="panel-qr" src=${login.qrDataUrl} alt=${t("info.weixin.qrAlt")} />+ <p class="hint">${t("info.weixin.scanHint")}</p>`}+ ${login && login.state === "need_verifycode" && html`<div class="actions"><input class="field" style="width:140px" placeholder=${t("info.weixin.verifyCode")} value=${code} onInput=${(e) => setCode(e.target.value)} />+ <button type="button" class="btn" onClick=${() => call("/verify", { code }).then(() => setCode(""))}>${t("info.weixin.submit")}</button></div>`}+ ${st.account && st.account.pausedUntil > Date.now() && html`<p class="hint">${t("info.weixin.pausedUntil", { time: 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>`}+ ${active ? html`<button type="button" class="btn" onClick=${() => call("/cancel")}>${t("common.cancel")}</button>` : html`<button type="button" class="btn primary" onClick=${() => call("/login")}>${st.account ? t("info.weixin.relogin") : t("info.weixin.login")}</button>`}+ <button type="button" class="text" onClick=${() => call("", { enabled: !bot.weixinEnabled })}>${bot.weixinEnabled ? t("info.weixin.disable") : t("info.weixin.enable")}</button>+ ${st.account && html`<button type="button" class="text danger" onClick=${logout}>${t("info.weixin.unlink")}</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>`}+ ${st.quota && st.quota.length > 0 && html`<p class="hint">${t("info.weixin.quota", { list: st.quota.map((q) => t("info.weixin.quotaItem", { user: q.userId.slice(0, 8), count: q.remaining })).join(t("info.weixin.quotaSep")) })}</p>`}</div>`}`;}@@ -112,25 +117,25 @@ function AccessRequests({ botId, data, reload }) {setBusy(r.id + what);try {await api(`/bots/${botId}/access/${encodeURIComponent(r.id)}/${what}`, { method: "POST", body: {} });- toast(what === "approve" ? `已允许「${r.who}」` : `已拒绝「${r.who}」`);+ toast(t(what === "approve" ? "info.access.allowed" : "info.access.denied", { who: r.who }));} catch (e) {failed(e);}setBusy("");reload();};- return html`<div class="list-head">使用请求<span class="badge count warn">${data.requests.length}</span></div>+ return html`<div class="list-head">${t("info.access.head")}<span class="badge count warn">${data.requests.length}</span></div><div class="stack">${data.requests.map((r) => html`<div key=${r.id} class="stack approval" style="--gap: var(--space-1)">- <span class="hint">${CHANNEL_NAME[r.channel] || r.channel} · ${fmtAgo(r.createdAt)}${r.requests > 1 ? ` · 发了 ${r.requests} 条消息` : ""}</span>+ <span class="hint">${accessChannel(r.channel)} · ${fmtAgo(r.createdAt)}${r.requests > 1 ? ` · ${t("info.access.messages", { count: r.requests })}` : ""}</span><div class="card">- <div class="meta"><span>想使用这个机器人 · 配对码 <span class="num">${r.code}</span></span></div>+ <div class="meta"><span>${t("info.access.wants", { code: html`<span class="num">${r.code}</span>` })}</span></div><div class="q">${r.who}</div>- ${r.text && html`<div class="q-detail selectable">「${r.text}」</div>`}+ ${r.text && html`<div class="q-detail selectable">${t("info.access.quote", { text: r.text })}</div>`}<div class="actions">- <${Button} variant="primary" loading=${busy === r.id + "approve"} disabled=${!!busy} onClick=${() => act(r, "approve")}>允许</${Button}>- <${Button} loading=${busy === r.id + "deny"} disabled=${!!busy} onClick=${() => act(r, "deny")}>拒绝</${Button}>+ <${Button} variant="primary" loading=${busy === r.id + "approve"} disabled=${!!busy} onClick=${() => act(r, "approve")}>${t("info.access.allow")}</${Button}>+ <${Button} loading=${busy === r.id + "deny"} disabled=${!!busy} onClick=${() => act(r, "deny")}>${t("info.access.deny")}</${Button}></div>- <span class="hint">也可以在聊天里回复「同意 ${r.code}」。</span>+ <span class="hint">${t("info.access.replyHint", { code: r.code })}</span></div></div>`)}</div>`;}@@ -138,23 +143,23 @@ function AccessRequests({ botId, data, reload }) {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;+ if (!(await confirmSheet({ title: t("info.memory.deleteTitle"), body: text, confirmLabel: t("common.delete"), danger: true }))) return;try {await api(`/bots/${botId}/memory/forget`, { method: "POST", body: { kind: sc.kind, id: sc.id, match: text, topic } });- toast("已删除");+ toast(t("info.memory.deleted"));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>+ const all = d ? d.scopes.flatMap((sc) => [...sc.entries.map((e) => ({ sc, e })), ...sc.topics.flatMap((tp) => tp.entries.map((e) => ({ sc, e, topic: tp.name })))]) : [];+ return html`<div class="list-head">${t("info.memory.title")}<span class="grow"></span><button type="button" class="icon-btn" title=${t("common.refresh")} aria-label=${t("info.memory.refresh")} onClick=${reload}><${Icon} name="refresh" size="sm" /></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>`}+ ${!d && html`<div class="row"><span class="hint">${err || t("common.loading")}</span></div>`}+ ${d && !all.length && html`<div class="row"><span class="hint">${t("info.memory.empty")}</span></div>`}${all.slice(0, 30).map(({ sc, e, topic }) => html`<div class="row compact"><div class="who"><div class="sub wrap selectable tone-fg t-control">${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>+ <button type="button" class="icon-btn" title=${t("common.delete")} aria-label=${t("info.memory.delete")} onClick=${() => forget(sc, e.text, topic)}><${Icon} name="trash" size="sm" /></button></div>`)}</div>`;}@@ -168,19 +173,19 @@ function LiveTurn({ turn, convId }) {try {await api(`/conversations/${encodeURIComponent(convId)}/stop`, { method: "POST", body: {} });} catch (e) {- failed(`中止失败:${e.message}`);+ failed(t("info.turn.stopFailed", { error: e.message }));setStopping(false);}};const idle = turn.lastProgress ? now - turn.lastProgress : 0;const cur = currentStep(turn.steps);- const label = `正在处理 ${fmtDur(now - turn.since)}${cur ? ` · ${cur}` : turn.lastProgress ? "" : " · 等代理进程接手"}`;+ const label = `${t("info.turn.processing", { d: fmtDur(now - turn.since) })}${cur ? ` · ${cur}` : turn.lastProgress ? "" : t("info.turn.waitingAgent")}`;return html`<div class="transcript-turn"><${ActivityLine} label=${label} live steps=${turn.steps} /><div class="cluster">- ${idle >= 60_000 && html`<span class="hint">${fmtDur(idle)}没有新进展</span>`}+ ${idle >= 60_000 && html`<span class="hint">${t("info.turn.idle", { d: fmtDur(idle) })}</span>`}<span class="grow"></span>- <${Button} variant="danger" size="sm" loading=${stopping} onClick=${stop}>中止</${Button}>+ <${Button} variant="danger" size="sm" loading=${stopping} onClick=${stop}>${t("info.turn.stop")}</${Button}></div></div>`;}@@ -188,30 +193,30 @@ function LiveTurn({ turn, convId }) {function ConversationSheet({ conv, onClose }) {const enc = encodeURIComponent(conv.id);const [d, , reload] = usePoll(() => api(`/conversations/${enc}/messages`), 0, [conv.id]);- const [t] = usePoll(() => api(`/conversations/${enc}/turn`), 2000, [conv.id]);- const turn = t?.turn;+ const [tr] = usePoll(() => api(`/conversations/${enc}/turn`), 2000, [conv.id]);+ const turn = tr?.turn;// 那一轮结束了:重新取消息,新回复和它的处理过程出现在列表里const busy = useRef(false);useEffect(() => {if (busy.current && !turn) reload();busy.current = !!turn;}, [!!turn]);- return html`<${Sheet} title=${`${CHANNEL_NAME[conv.channel] || conv.channel} · ${conv.title || conv.peerId}`} wide onClose=${onClose}>+ return html`<${Sheet} title=${`${channelName(conv.channel) || conv.channel} · ${conv.title || conv.peerId}`} wide onClose=${onClose}><div class="transcript">- ${!d && html`<span class="hint">加载中…</span>`}- ${d && !d.messages.length && !turn && html`<span class="hint">没有消息</span>`}+ ${!d && html`<span class="hint">${t("common.loading")}</span>`}+ ${d && !d.messages.length && !turn && html`<span class="hint">${t("info.noMessages")}</span>`}${d && d.messages.map((m) => html`<div class=${`transcript-msg${m.role === "user" ? " user" : ""}`}>- ${m.steps && html`<${ActivityLine} label="处理过程" count=${m.steps} load=${() => api(`/conversations/${enc}/messages/${m.id}/activity`).then((x) => x.steps)} />`}+ ${m.steps && html`<${ActivityLine} label=${t("info.turn.activity")} count=${m.steps} load=${() => api(`/conversations/${enc}/messages/${m.id}/activity`).then((x) => x.steps)} />`}<div class="bubble selectable">${m.content}</div><div class="hint">${fmtTime(m.createdAt)}</div></div>`)}${turn && html`<${LiveTurn} key=${turn.since} turn=${turn} convId=${conv.id} />`}</div>- <div class="actions"><button type="button" class="btn" data-autofocus onClick=${onClose}>关闭</button></div>+ <div class="actions"><button type="button" class="btn" data-autofocus onClick=${onClose}>${t("common.close")}</button></div><//>`;}-export function InfoPanel({ bot, onClose, onOpenBotSettings, onOpenChat }) {+export function InfoPanel({ bot, leaving, 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]);@@ -221,14 +226,20 @@ export function InfoPanel({ bot, onClose, onOpenBotSettings, onOpenChat }) {const tasks = (taskData?.tasks || []).filter((t) => t.stage.group !== "ended");const [viewing, setViewing] = useState(null);const pending = (appr && appr.approvals) || [];- return html`<aside class="panel" aria-label="信息面板">+ // 上手清单:微信扫码绑定了,或飞书连上了,就算接好了渠道+ useEffect(() => {+ const ch = detail && detail.channels;+ if (ch && (ch.weixin.account || ch.feishu.state === "connected")) markDone("weixin");+ }, [detail]);+ // leaving:关上后还在播滑出的那一小会儿(main.js 的 usePresence),不再接收操作+ return html`<aside class=${`panel${leaving ? " leaving" : ""}`} aria-label=${t("info.aria")} inert=${leaving || undefined}><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>+ <button type="button" class="icon-btn" title=${t("info.botSettings")} aria-label=${t("info.botSettings")} onClick=${onOpenBotSettings}><${Icon} name="gear" size="md" /></button>+ <button type="button" class="icon-btn panel-close" title=${t("info.closeTitle")} aria-label=${t("info.closeAria")} onClick=${onClose}><${Icon} name="close" size="md" /></button></div><div class="panel-body">- <div class="list-head">渠道</div>+ <div class="list-head">${t("info.channels")}</div><div class="list">${detail && detail.bot? html`<${FeishuRow} bot=${detail.bot} st=${detail.channels.feishu} owner=${access ? access.owners.feishu : undefined} reload=${reloadDetail} /><${WeixinRow} bot=${detail.bot} st=${detail.channels.weixin} reload=${reloadDetail} />`@@ -237,28 +248,28 @@ export function InfoPanel({ bot, onClose, onOpenBotSettings, onOpenChat }) {<${AccessRequests} botId=${bot.id} data=${access} reload=${reloadAccess} />- <div class="list-head">待审批${pending.length > 0 && html`<span class="badge count warn">${pending.length}</span>`}</div>+ <div class="list-head">${t("info.approvals")}${pending.length > 0 && html`<span class="badge count warn">${pending.length}</span>`}</div>${pending.length? html`<div class="stack">${pending.map((a) => html`<div key=${a.id} class="stack approval" style="--gap: var(--space-1)">- <span class="hint">${CHANNEL_NAME[a.conversationId.split(":")[1]] || ""} · ${fmtAgo(a.createdAt)} · 截止 ${fmtTime(a.expiresAt).slice(-8, -3)}</span>+ <span class="hint">${channelName(a.conversationId.split(":")[1]) || ""} · ${fmtAgo(a.createdAt)} · ${t("info.due", { time: fmtClock(a.expiresAt) })}</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>`}+ <button type="button" class="text" style="justify-self:start" onClick=${reloadAppr}>${t("common.refresh")}</button></div>`+ : html`<div class="list"><div class="row"><span class="hint">${t("info.noApprovals")}</span></div></div>`}- ${tasks.length > 0 && html`<div class="list-head">任务</div>+ ${tasks.length > 0 && html`<div class="list-head">${t("info.tasks")}</div><div class="list">${tasks.slice(0, 8).map((t) => html`<${TaskRow} key=${t.id} task=${t} onChanged=${reloadTasks}onOpen=${() => (t.channel === "web" ? onOpenChat() : setViewing((convs?.conversations || []).find((c) => c.id === t.conversationId) || null))} />`)}</div>`}<${MemorySection} botId=${bot.id} />- <div class="list-head">最近会话</div>+ <div class="list-head">${t("info.recent")}</div><div class="list">${!convs && html`<div class="row"><${Skeleton} w="60%" /></div>`}- ${convs && !convs.conversations.length && html`<div class="row"><span class="hint">还没有会话</span></div>`}+ ${convs && !convs.conversations.length && html`<div class="row"><span class="hint">${t("info.noConvs")}</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 || "").replace(/^⚠️\s*/, "") || "(空)"}</div></div>+ <div class="who"><div class="name">${channelName(c.channel) || c.channel} · ${c.title || c.peerId}</div><div class="sub">${(c.lastMessage || "").replace(/^⚠️\s*/, "") || t("info.emptyMessage")}</div></div><span class="hint num">${fmtAgo(c.updatedAt)}</span></div>`)}</div>diff --git a/ui/screens/new-bot.js b/ui/screens/new-bot.jsindex 204de3c..d100daa 100644--- a/ui/screens/new-bot.js+++ b/ui/screens/new-bot.js@@ -5,20 +5,30 @@ import { html, Icon, IconButton, Button, autoGrow } from "../components/ui.js";import { BotAvatar, AvatarPicker, MAIN_CHAR } from "../components/avatar.js";import { api } from "../lib/api.js";import { failed } from "../lib/store.js";+import { t } from "../lib/i18n.js";+/** 模板。名称、简介和人设在词典 newBot.tpl.<key> 里,读的时候按当前语言翻译(选模板时按当时的语言填进表单) */+const template = (key, icon, avatar) => ({+ key,+ icon,+ avatar,+ get name() {+ return t(`newBot.tpl.${key}.name`);+ },+ get desc() {+ return t(`newBot.tpl.${key}.desc`);+ },+ get prompt() {+ return t(`newBot.tpl.${key}.prompt`);+ },+});export const TEMPLATES = [- { key: "digest", icon: "file", avatar: "green", name: "群聊日报", desc: "把群里的讨论整理成日报:结论、待办和负责人",- prompt: "你是群聊日报助手。被要求总结时,把群里的讨论整理成日报:先写三条以内的结论,再列待办(事项、负责人、时间),最后列还没解决的问题。只写群里确实说过的内容,不要编造。" },- { key: "support", icon: "chat", avatar: "yellow", name: "客服助手", desc: "按已知资料回答客户问题,拿不准就转人工",- prompt: "你是客服助手。用简洁、礼貌的中文回答客户问题,只依据已知的资料作答;资料里没有或拿不准时,直接说明会转给人工处理,不要猜测。" },- { key: "translate", icon: "globe", avatar: "orange", name: "翻译官", desc: "中英互译,保留语气、术语和格式",- prompt: "你是翻译官。收到中文就译成英文,收到其他语言就译成中文。保留原文的语气、术语和格式(列表、代码、链接),只输出译文。" },- { key: "minutes", icon: "clock", avatar: "blue", name: "会议纪要", desc: "把会议记录整理成结论、待办和待定问题",- prompt: "你是会议纪要助手。把会议记录或转写整理成:会议主题、结论、待办(事项、负责人、截止时间)、待定问题。语言精炼,不添加记录里没有的信息。" },- { key: "writer", icon: "compose", avatar: "purple", name: "写作助手", desc: "起草公告、邮件和周报,按你的语气润色",- prompt: "你是写作助手。帮我起草和润色公告、邮件、周报等文字。先弄清用途和读者,再给出成稿;语气自然、结构清楚,不写空话。" },- { key: "coder", icon: "code", avatar: "red", name: "代码助手", desc: "读代码、写脚本,在自己的工作区里改文件",- prompt: "你是代码助手。阅读和修改工作区里的代码,编写脚本解决问题。动手前先说明计划,改完说明改了什么、怎么验证。" },+ template("digest", "file", "green"),+ template("support", "chat", "yellow"),+ template("translate", "globe", "orange"),+ template("minutes", "clock", "blue"),+ template("writer", "compose", "purple"),+ template("coder", "code", "red"),];export function NewBotScreen({ first, onCreated, onCancel }) {@@ -35,11 +45,11 @@ export function NewBotScreen({ first, onCreated, onCancel }) {}, []);useEffect(() => autoGrow(promptRef.current, 240), [prompt]);- const pick = (t) => {- setTpl(t.key);- if (t.avatar !== avatar) choose(t.avatar);- setName(t.name);- setPrompt(t.prompt);+ const pick = (tp) => {+ setTpl(tp.key);+ if (tp.avatar !== avatar) choose(tp.avatar);+ setName(tp.name);+ setPrompt(tp.prompt);requestAnimationFrame(() => (nameRef.current?.focus(), nameRef.current?.select()));};const choose = (k) => {@@ -62,35 +72,35 @@ export function NewBotScreen({ first, onCreated, onCancel }) {return html`<section class="new-bot view" data-screen="new-bot"><header class="chat-head">- <span class="head-bot static"><${BotAvatar} char=${avatar} size=${22} /><span class="name">新机器人</span></span>+ <span class="head-bot static"><${BotAvatar} char=${avatar} size=${22} /><span class="name">${t("newBot.headName")}</span></span><span class="grow"></span>- ${onCancel && html`<${IconButton} icon="close" iconSize=${15} label="取消(Esc)" onClick=${onCancel} />`}+ ${onCancel && html`<${IconButton} icon="close" iconSize="md" label=${t("newBot.cancel")} onClick=${onCancel} />`}</header><div class="new-body"><form class="new-form" onSubmit=${create}><${BotAvatar} char=${avatar} size=${96} lively pokeable greet cue=${hi} state=${busy ? "thinking" : name.trim() ? "listening" : "idle"} />- <h1 class="new-title">${first ? "创建你的第一个机器人" : "新建机器人"}</h1>- <p class="new-lead">挑一个伙伴,起个名字、写几句人设,或者从下面的模板开始。</p>+ <h1 class="new-title">${first ? t("newBot.firstTitle") : t("newBot.title")}</h1>+ <p class="new-lead">${t("newBot.lead")}</p><${AvatarPicker} value=${avatar} onChange=${choose} size=${40} /><label class="set-field">- <span class="k">名称</span>- <input class="field" ref=${nameRef} maxlength="60" placeholder="例如:群聊日报" value=${name} onInput=${(e) => setName(e.target.value)}+ <span class="k">${t("newBot.name")}</span>+ <input class="field" ref=${nameRef} maxlength="60" placeholder=${t("newBot.namePlaceholder")} value=${name} onInput=${(e) => setName(e.target.value)}onKeyDown=${(e) => e.key === "Escape" && name && (e.stopPropagation(), setName(""))} /></label><label class="set-field">- <span class="k">人设<span class="hint">可选,之后在机器人设置里也能改</span></span>- <textarea class="field" ref=${promptRef} rows="3" placeholder="例如:你是一个乐于助人的中文助手,回答简洁准确。" value=${prompt}+ <span class="k">${t("newBot.persona")}<span class="hint">${t("newBot.personaHint")}</span></span>+ <textarea class="field" ref=${promptRef} rows="3" placeholder=${t("newBot.personaPlaceholder")} value=${prompt}onInput=${(e) => { setPrompt(e.target.value); setTpl(""); }} /></label>- <${Button} type="submit" variant="primary" size="lg" loading=${busy} disabled=${!name.trim()}>创建<//>+ <${Button} type="submit" variant="primary" size="lg" loading=${busy} disabled=${!name.trim()}>${t("newBot.create")}<//></form><div class="new-sugg">- <div class="list-head">从模板开始</div>+ <div class="list-head">${t("newBot.fromTemplate")}</div><div class="tpl-grid">- ${TEMPLATES.map((t) => html`<button type="button" key=${t.key} class=${`tpl${tpl === t.key ? " on" : ""}`} aria-pressed=${tpl === t.key} onClick=${() => pick(t)}>- <span class="tpl-ic"><${Icon} name=${t.icon} size=${17} /></span>- <span class="tpl-name">${t.name}</span>- <span class="tpl-desc">${t.desc}</span>+ ${TEMPLATES.map((tp) => html`<button type="button" key=${tp.key} class=${`tpl${tpl === tp.key ? " on" : ""}`} aria-pressed=${tpl === tp.key} onClick=${() => pick(tp)}>+ <span class="tpl-ic"><${Icon} name=${tp.icon} size="lg" /></span>+ <span class="tpl-name">${tp.name}</span>+ <span class="tpl-desc">${tp.desc}</span></button>`)}</div></div>diff --git a/ui/screens/onboarding.js b/ui/screens/onboarding.jsindex 304dad2..6f76b6c 100644--- a/ui/screens/onboarding.js+++ b/ui/screens/onboarding.js@@ -2,22 +2,25 @@// 回来后自动签发本机 Key 并连接)。只有 Docker / 远程部署(浏览器登录的回调回不到这台机器)才显示粘贴 API Key。// 不是向导路由。import { useEffect, useMemo, useRef, useState } from "preact/hooks";-import { html, Icon, Notice, Seg, Spinner, CopyButton } from "../components/ui.js";+import { html, Icon, Menu, Notice, Seg, Spinner, CopyButton } from "../components/ui.js";import { BotAvatar, MAIN_CHAR } from "../components/avatar.js";-import { FamilyHead, PickModel, groupModels, useFamilies } from "../components/model-picker.js";+import { FamilyHead, PickModel, familyName, groupModels, useFamilies } from "../components/model-picker.js";import { api } from "../lib/api.js";+import { failed } from "../lib/store.js";+import { LANG_NAMES, changeLang, getLangPref, t, useLang } from "../lib/i18n.js";import { MF_CONSOLE, MF_DOCS, MF_KEYS } from "../lib/links.js";export { MF_CONSOLE, MF_DOCS };-export const LINE_OPTIONS = [- ["auto", "自动"],- ["global", "国际"],- ["cn", "中国大陆优化"],+/** Modelflare 线路的选项 [值, 显示名](引导页"高级"和设置页共用;按当前语言,渲染时再调) */+export const lineOptions = () => [+ ["auto", t("common.auto")],+ ["global", t("onboarding.line.global")],+ ["cn", t("onboarding.line.cn")],];/** 粘贴 Key → 校验(GET /v1/models)→ 写入。onConnected(result) 收到 { models, keyTail, … } *//** onFace(state):给旁边的头像用——"listening"(在输入)/ "thinking"(正在校验)/ "idle" / "error"(一次性) */-export function KeyForm({ line: initialLine = "auto", onConnected, onFace, showLine = true, submitLabel = "连接 Modelflare" }) {+export function KeyForm({ line: initialLine = "auto", onConnected, onFace, showLine = true, submitLabel = t("onboarding.key.submit") }) {const [key, setKey] = useState("");const [show, setShow] = useState(false);const [line, setLine] = useState(initialLine);@@ -37,7 +40,7 @@ export function KeyForm({ line: initialLine = "auto", onConnected, onFace, showLsetBusy(true);setErr(null);setSlow(false);- const t = setTimeout(() => setSlow(true), 4000);+ const slowTimer = setTimeout(() => setSlow(true), 4000);try {const r = await api("/modelflare", { method: "PUT", body: { apiKey: k, line: useLine } });setKey("");@@ -46,16 +49,16 @@ export function KeyForm({ line: initialLine = "auto", onConnected, onFace, showLsetErr({ message: e.message, code: e.data?.code, suggestLine: e.data?.suggestLine });onFace?.("error");} finally {- clearTimeout(t);+ clearTimeout(slowTimer);setBusy(false);setSlow(false);}};const paste = async () => {try {- const t = (await navigator.clipboard.readText()).trim();- if (t) {- setKey(t);+ const text = (await navigator.clipboard.readText()).trim();+ if (text) {+ setKey(text);setErr(null);requestAnimationFrame(() => btn.current?.focus());}@@ -69,35 +72,35 @@ export function KeyForm({ line: initialLine = "auto", onConnected, onFace, showL};return html`<form class="list" onSubmit=${(e) => { e.preventDefault(); submit(); }}>- <label class="k" for="mf-key">API Key</label>+ <label class="k" for="mf-key">${t("onboarding.key.label")}</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}+ autocomplete="off" spellcheck="false" placeholder=${t("onboarding.key.placeholder")} 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>+ <button type="button" class="icon-btn" title=${t("onboarding.key.paste")} aria-label=${t("onboarding.key.paste")} onClick=${paste}><${Icon} name="paste" size="sm" /></button>+ <button type="button" class="icon-btn" title=${show ? t("onboarding.key.hide") : t("onboarding.key.show")} aria-label=${show ? t("onboarding.key.hideKey") : t("onboarding.key.showKey")} onClick=${() => setShow((v) => !v)}><${Icon} name=${show ? "eyeOff" : "eye"} size="sm" /></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>`}+ ${err.code === "invalid_key" && html`<button type="button" class="text" onClick=${retype}>${t("onboarding.key.retype")}</button>`}+ ${err.code === "forbidden" && html`<a href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">${t("onboarding.key.checkGroup")}</a>`}+ ${(err.code === "rate_limited" || err.code === "upstream" || err.code === "bad_response") && html`<button type="button" class="text" onClick=${() => submit()}>${t("common.retry")}</button>`}+ ${err.code === "network" && err.suggestLine === "cn" && html`<button type="button" class="text accent" onClick=${() => submit("cn")}>${t("onboarding.key.useCn")}</button>`}</div>`}- <p class="hint" id="mf-key-note">密钥只保存在本机,不会写入日志或命令行参数。</p>+ <p class="hint" id="mf-key-note">${t("onboarding.key.note")}</p><button type="submit" ref=${btn} class="btn primary lg block" disabled=${!key.trim() || busy}>- ${busy ? html`<${Spinner} /> 正在连接…` : submitLabel}+ ${busy ? html`<${Spinner} /> ${t("onboarding.key.connecting")}` : submitLabel}</button>- ${slow && html`<p class="slow">网络较慢${showLine ? ",可在「高级」里切换线路" : ""}。</p>`}+ ${slow && html`<p class="slow">${showLine ? t("onboarding.key.slowLine") : t("onboarding.key.slow")}</p>`}${showLine && html`<details>- <summary>高级 <${Icon} name="chevDown" size=${12} /></summary>+ <summary>${t("onboarding.key.advanced")} <${Icon} name="chevDown" size="xs" /></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 class="who"><div class="name">${t("onboarding.line.label")}</div><div class="sub">${t("onboarding.line.sub")}</div></div>+ <${Seg} label=${t("onboarding.line.label")} options=${lineOptions()} value=${line} onChange=${setLine} disabled=${busy} /></div></details>`}</form>`;@@ -107,7 +110,7 @@ export function KeyForm({ line: initialLine = "auto", onConnected, onFace, showL* 登录 / 注册 Modelflare:桌面版由主进程在系统浏览器里打开授权页;浏览器版在新标签页打开(被拦截时* 用下面的链接)。等待期间每秒读一次账户状态,登录完成(本机 Key 已接上)后 onSignedIn(status)。*/-export function AccountLogin({ onSignedIn, onFace, label = "登录 / 注册 Modelflare" }) {+export function AccountLogin({ onSignedIn, onFace, label = t("onboarding.login.label") }) {const [waiting, setWaiting] = useState(false);const [url, setUrl] = useState("");const [err, setErr] = useState("");@@ -115,7 +118,7 @@ export function AccountLogin({ onSignedIn, onFace, label = "登录 / 注册 ModeuseEffect(() => {if (!waiting) return;let stop = false;- const t = setInterval(async () => {+ const poll = setInterval(async () => {const s = await api("/account").catch(() => null);if (!s || stop) return;if (s.state === "signed_in") {@@ -131,7 +134,7 @@ export function AccountLogin({ onSignedIn, onFace, label = "登录 / 注册 Mode}}}, 1000);- return () => clearInterval(t);+ return () => clearInterval(poll);}, [waiting]);const start = async () => {setErr("");@@ -151,11 +154,11 @@ export function AccountLogin({ onSignedIn, onFace, label = "登录 / 注册 Mode};if (waiting) {return html`<div class="login-cta" role="status">- <div class="login-wait"><${Spinner} /> 在浏览器里完成登录后,会自动回到这里</div>+ <div class="login-wait"><${Spinner} /> ${t("onboarding.login.waiting")}</div><div class="login-links">- <a class="text" href=${url} target="_blank" rel="noopener noreferrer">重新打开登录页 ↗</a>- <${CopyButton} text=${url} label="复制链接" />- <button type="button" class="text" onClick=${cancel}>取消</button>+ <a class="text" href=${url} target="_blank" rel="noopener noreferrer">${t("onboarding.login.reopen")}</a>+ <${CopyButton} text=${url} label=${t("onboarding.login.copyLink")} />+ <button type="button" class="text" onClick=${cancel}>${t("common.cancel")}</button></div></div>`;}@@ -201,36 +204,53 @@ function ModelStep({ models, initial, onDone }) {}};return html`<div class="list">- <div class="connected"><span class="dot ok"></span>已连接 · 找到 <span class="num">${models.length}</span> 个模型</div>+ <div class="connected"><span class="dot ok"></span>${t("onboarding.model.found", { count: models.length, n: html`<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="默认模型">+ ? html`<p class="hint">${t("onboarding.model.hint")}</p>+ <input class="field" placeholder=${t("onboarding.model.filter")} value=${q} onInput=${(e) => setQ(e.target.value)} aria-label=${t("onboarding.model.filter")} />+ <div class="picklist" role="listbox" aria-label=${t("onboarding.model.default")}>${groups.map(([g, ms]) => {const rows = 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>`}+ <span class="v">${label}</span>${m === cur && html`<span class="check"><${Icon} name="check" size="sm" /></span>`}</button>`);- if (!folding) return html`${groups.length > 1 && html`<div class="group">${g}</div>`}${rows}`;+ if (!folding) return html`${groups.length > 1 && html`<div class="group">${familyName(g)}</div>`}${rows}`;const open = isOpen(g);const hit = open ? undefined : ms.find(([m]) => m === cur);return html`<button type="button" class="fam" aria-expanded=${open} onClick=${() => toggle(g)}><${FamilyHead} name=${g} count=${ms.length} current=${hit?.[1]} /></button>${open && rows}`;})}- ${!groups.length && html`<p class="hint">没有匹配的模型</p>`}+ ${!groups.length && html`<p class="hint">${t("onboarding.model.noMatch")}</p>`}</div>${hasMedia && html`<div class="media-pick">- <p class="hint">生成图片和视频时默认用的模型。每次生成前都会先问你,也可以当场换。</p>+ <p class="hint">${t("onboarding.model.mediaHint")}</p>${media.image.length > 0 && html`<div class="row compact">- <div class="who"><div class="name">图片</div></div>- <${PickModel} value=${img} models=${media.image} onChange=${setImg} label="默认图片模型" />+ <div class="who"><div class="name">${t("onboarding.model.image")}</div></div>+ <${PickModel} value=${img} models=${media.image} onChange=${setImg} label=${t("onboarding.model.imageLabel")} /></div>`}${media.video.length > 0 && html`<div class="row compact">- <div class="who"><div class="name">视频</div></div>- <${PickModel} value=${vid} models=${media.video} onChange=${setVid} label="默认视频模型" />+ <div class="who"><div class="name">${t("onboarding.model.video")}</div></div>+ <${PickModel} value=${vid} models=${media.video} onChange=${setVid} label=${t("onboarding.model.videoLabel")} /></div>`}</div>`}`- : html`<${Notice} tone="amber" action=${html`<a class="btn" href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">去控制台 ↗</a>`}>这个 Key 所在的分组暂无可用模型。可以在控制台给分组开放模型后再回来刷新。<//>`}+ : html`<${Notice} tone="amber" action=${html`<a class="btn" href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">${t("onboarding.model.console")}</a>`}>${t("onboarding.model.empty")}<//>`}${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>+ <button type="button" class="btn primary lg block" disabled=${busy} onClick=${start}>${busy ? html`<${Spinner} /> ${t("onboarding.model.saving")}` : models.length ? t("onboarding.model.start") : t("onboarding.model.startAnyway")}</button>+ </div>`;+}++/** 语言切换:在引导列顶上靠右。新用户连接前就能换语言(按钮上是当前界面语言的名字,菜单里勾的是偏好) */+function LangSwitch() {+ const lang = useLang();+ const pref = getLangPref();+ const [open, setOpen] = useState(false);+ const ref = useRef(null);+ const label = t("common.lang.label");+ const opts = [["system", t("common.lang.system")], ["zh-CN", LANG_NAMES["zh-CN"]], ["en", LANG_NAMES.en]];+ return html`<div class="onboard-lang">+ <button type="button" class="pick" ref=${ref} aria-haspopup="menu" aria-expanded=${open} aria-label=${label} title=${label} onClick=${() => setOpen((v) => !v)}>+ <${Icon} name="globe" size="sm" class="lead" /><span class="v">${LANG_NAMES[lang]}</span><${Icon} name="chevDown" />+ </button>+ ${open && html`<${Menu} anchor=${ref.current} width=${180} align="right" label=${label} onClose=${() => setOpen(false)}+ items=${opts.map(([v, text]) => ({ label: text, cur: v === pref, onSelect: () => v !== pref && changeLang(v).catch(failed) }))} />`}</div>`;}@@ -257,19 +277,20 @@ export function Onboarding({ status, gateway, defaultModel, onDone }) {.catch(() => setModels([]));return html`<main class="onboard" data-screen="onboarding"><div class="onboard-col">+ <${LangSwitch} /><div class="onboard-hero"><${BotAvatar} char=${MAIN_CHAR} size=${models === null ? 168 : 88} state=${face} cue=${cue} lively pokeable greet />- <h1>任意模型,一个助手</h1>+ <h1>${t("onboarding.slogan")}</h1></div>- ${gateway && gateway.mode === "managed" && gateway.state === "failed" && html`<${Notice} tone="red">内置模型网关没有启动:${gateway.lastError || "未知原因"}。修复后重启应用再连接。<//>`}+ ${gateway && gateway.mode === "managed" && gateway.state === "failed" && html`<${Notice} tone="red">${t("onboarding.gatewayFailed", { error: gateway.lastError || t("onboarding.unknownReason") })}<//>`}${why && models === null && html`<${Notice} tone="amber">${why}<//>`}${models !== null? html`<${ModelStep} models=${models} initial=${defaultModel} onDone=${onDone} />`: useKey? html`<${KeyForm} line=${status.line} onFace=${onFace} onConnected=${(r) => (setFace("idle"), setModels(r.models || []))} /><div class="links">- <span>Docker 或远程部署无法用浏览器登录,请填写 API Key</span>- <a href=${MF_KEYS} target="_blank" rel="noopener noreferrer">在 Modelflare 控制台创建 Key ↗</a>+ <span>${t("onboarding.keyOnly")}</span>+ <a href=${MF_KEYS} target="_blank" rel="noopener noreferrer">${t("onboarding.createKey")}</a></div>`: html`<${AccountLogin} onFace=${onFace} onSignedIn=${loadModels} />`}</div>diff --git a/ui/screens/settings.js b/ui/screens/settings.jsindex a9d9f45..9576d36 100644--- a/ui/screens/settings.js+++ b/ui/screens/settings.js@@ -1,37 +1,59 @@// 设置页(参考 Codex):侧栏换成设置导航(返回应用 + 查找 + 分页),主区是大标题 + 白色圆角 list,一行一项;改动即保存。// 入口只有左下角账户按钮、⌘/Ctrl+, 和命令面板。+// 外观(主题、字体、动画、毛玻璃…)和对话习惯(发送键、通知)是本机界面偏好,存在浏览器里(lib/theme.js、lib/prefs.js);+// 其余设置走服务端 /settings。import { useEffect, useMemo, useRef, useState } from "preact/hooks";import { html, Icon, Seg, Switch, Sheet, CopyButton, Skeleton } from "../components/ui.js";import { AccountButton } from "./sidebar.js";import { PickModel, shortModel } from "../components/model-picker.js";-import { KeyForm, LINE_OPTIONS } from "./onboarding.js";+import { KeyForm, lineOptions } from "./onboarding.js";import { LoginSheet, NotificationsSheet, UsageSheet } from "./account.js";import { api } from "../lib/api.js";import { MF_CONSOLE, MF_DOCS_LINK, MF_TOPUP, usd } from "../lib/links.js";-import { useStore, confirmSheet, failed, saved } from "../lib/store.js";+import { useStore, confirmSheet, failed, saved, toast } from "../lib/store.js";+import { guide, resetGuide, visibleSteps } from "../lib/guide.js";import { themeMode, setThemeMode } from "../lib/theme.js";+import { prefs, setPrefs, resetAppearance, appearanceChanged, fontStack } from "../lib/prefs.js";+import { canNotify, requestNotify } from "../lib/notify.js";import { TroubleshootPane } from "./troubleshoot.js";import { PwshHint } from "../components/pwsh-hint.js";+import { t, has, useLang, getLangPref, onLangChange, changeLang, LANG_NAMES } from "../lib/i18n.js";+import { fmtTimeOfDay } from "../lib/format.js";+/** [id, 标题的文案键, 图标];标题渲染时再 t()(tabLabel) */export const TABS = [- ["general", "常规", "sliders"],- ["modelflare", "Modelflare", "spark"],- ["computer", "电脑操作", "monitor"],- ["privacy", "隐私与安全", "lock"],- ["network", "网络与访问", "globe"],- ["data", "数据", "database"],- ["troubleshoot", "故障排查", "pulse"],- ["about", "关于", "info"],+ ["general", "settings.tabs.general", "sliders"],+ ["appearance", "settings.tabs.appearance", "palette"],+ ["modelflare", "settings.tabs.modelflare", "spark"],+ ["computer", "settings.tabs.computer", "monitor"],+ ["privacy", "settings.tabs.privacy", "lock"],+ ["network", "settings.tabs.network", "globe"],+ ["data", "settings.tabs.data", "database"],+ ["troubleshoot", "settings.tabs.troubleshoot", "pulse"],+ ["about", "settings.tabs.about", "info"],];+const tabLabel = (key) => t(key);const ZOOMS = [[1, "100%"],[1.1, "110%"],[1.25, "125%"],[1.5, "150%"],];-const GATEWAY = { running: "运行中", starting: "启动中", restarting: "重启中", failed: "失败", stopped: "已停止", external: "外部端点" };-const ALERT_LINES = [- [0, "不提醒"],+// 带文案的选项都写成函数:切换语言后重新取+const gatewayState = (st) => (has(`settings.gateway.${st}`) ? t(`settings.gateway.${st}`) : st);+const THEMES = () => [["system", t("common.system")], ["light", t("settings.theme.light")], ["dark", t("settings.theme.dark")]];+const TEXT_SIZES = () => ["sm", "md", "lg", "xl"].map((v) => [v, t(`settings.textSize.${v}`)]);+const FONTS = () => ["system", "serif", "custom"].map((v) => [v, t(`settings.font.${v}`)]);+const WIDTHS = () => ["normal", "wide", "full"].map((v) => [v, t(`settings.width.${v}`)]);+const AUTO_ON_OFF = () => [["system", t("common.system")], ["on", t("common.on")], ["off", t("common.off")]];+const LANG_OPTIONS = () => [["system", t("common.lang.system")], ["zh-CN", LANG_NAMES["zh-CN"]], ["en", LANG_NAMES.en]];+const isMac = /Mac|iPhone|iPad/.test(navigator.platform);+const MOD_ENTER = isMac ? "⌘Enter" : "Ctrl+Enter";+// 本机没开放字体列表(queryLocalFonts)时的候选:常见的中文 / 西文界面字体与等宽字体+const SUGGEST_UI = ["LXGW WenKai", "霞鹜文楷", "HarmonyOS Sans SC", "MiSans", "Source Han Sans SC", "Noto Sans SC", "Sarasa UI SC", "Inter"]; // i18n-ignore+const SUGGEST_CODE = ["JetBrains Mono", "Fira Code", "Cascadia Code", "SF Mono", "Source Code Pro", "Sarasa Mono SC", "Maple Mono"];+const ALERT_LINES = () => [+ [0, t("settings.rows.lowBalance.none")],[1, "$1"],[5, "$5"],[20, "$20"],@@ -44,34 +66,74 @@ function Row({ id, name, sub, title, children, flash, off }) {</div>`;}+// 本机已安装字体(Local Font Access API):第一次聚焦字体输入框时读一次,浏览器里可能会先弹权限+let localFonts = null;+function loadLocalFonts() {+ if (!localFonts)+ localFonts = (typeof window.queryLocalFonts === "function" ? window.queryLocalFonts() : Promise.resolve([]))+ .then((list) => [...new Set(list.map((f) => f.family))].sort((a, b) => a.localeCompare(b)))+ .catch(() => {+ localFonts = null; // 拒绝了或不支持:下次聚焦再试,这次先用候选+ return [];+ });+ return localFonts;+}++/** 字体名输入框:边打字边生效(外观实时变),离开或从候选里选中时提示"已保存";输入框自己用这个字体显示 */+function FontInput({ id, value, onChange, placeholder, suggest, fallback, label }) {+ const ref = useRef(null);+ const [v, setV] = useState(value);+ const [fonts, setFonts] = useState(null);+ // 外面改了(恢复默认)且没在输入时,跟着变+ useEffect(() => {+ if (document.activeElement !== ref.current) setV(value);+ }, [value]);+ const stack = fontStack(v);+ return html`<input ref=${ref} class="field font-in" type="text" list=${`${id}-list`} aria-label=${label} placeholder=${placeholder} value=${v}+ spellcheck="false" autocomplete="off" style=${{ fontFamily: stack ? `${stack}, ${fallback}` : "" }}+ onFocus=${() => !(fonts && fonts.length) && loadLocalFonts().then(setFonts)}+ onInput=${(e) => { setV(e.target.value); onChange(e.target.value); }}+ onChange=${() => saved()} />+ <datalist id=${`${id}-list`}>${(fonts && fonts.length ? fonts : suggest).map((f) => html`<option key=${f} value=${f} />`)}</datalist>`;+}++/** 外观分页顶部的预览:一问一答 + 一行代码,跟着字体大小、字体、代码字体和代码换行实时变 */+function AppearancePreview() {+ return html`<div class="ap-preview" aria-hidden="true">+ <div class="ap-bubble">${t("settings.preview.ask")}</div>+ <div class="ap-reply">${t("settings.preview.reply", { b: html`<b>${t("settings.rows.codeWrap.name")}</b>` })}</div>+ <pre class="ap-code">const res = await fetch(\`\${base}/v1/chat/completions\`, { method: "POST", headers, body: JSON.stringify({ model, messages }) });</pre>+ </div>`;+}+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>+ return html`<${Sheet} title=${t("settings.rows.licenses.name")} wide onClose=${onClose}>+ <pre class="doc">${d ? `${d.license}\n\n${d.notices}` : t("common.loading")}</pre>+ <div class="actions"><button type="button" class="btn" data-autofocus onClick=${onClose}>${t("common.close")}</button></div><//>`;}/** 设置时的侧栏:返回应用 | 查找设置 | 分页 | 账户 */export function SettingsSide({ tab, query, onQuery, onTab, onBack, username, account }) {const searching = !!query.trim();- return html`<aside class="side" aria-label="设置">+ return html`<aside class="side" aria-label=${t("settings.side.label")}><div class="side-top start">- <button type="button" class="side-back" title="返回应用(Esc)" onClick=${onBack}><${Icon} name="arrowLeft" size=${15} />返回应用</button>+ <button type="button" class="side-back" title=${t("settings.side.backTitle")} onClick=${onBack}><${Icon} name="arrowLeft" size="md" />${t("settings.side.back")}</button></div><label class="side-search">- <${Icon} name="search" size=${14} />- <input type="search" placeholder="查找设置" aria-label="查找设置" value=${query} onInput=${(e) => onQuery(e.target.value)}+ <${Icon} name="search" size="sm" />+ <input type="search" placeholder=${t("settings.side.search")} aria-label=${t("settings.side.search")} value=${query} onInput=${(e) => onQuery(e.target.value)}onKeyDown=${(e) => e.key === "Escape" && query && (e.stopPropagation(), onQuery(""))} /></label>- <nav class="side-list side-nav" aria-label="设置分页">- ${TABS.map(([t, label, icon]) => {- const on = !searching && t === tab;- return html`<button type="button" key=${t} class=${`nav-item${on ? " sel" : ""}`} aria-current=${on ? "page" : undefined}- onClick=${() => { onQuery(""); onTab(t); }}><${Icon} name=${icon} size=${16} /><span>${label}</span></button>`;+ <nav class="side-list side-nav" aria-label=${t("settings.side.nav")}>+ ${TABS.map(([id, label, icon]) => {+ const on = !searching && id === tab;+ return html`<button type="button" key=${id} class=${`nav-item${on ? " sel" : ""}`} aria-current=${on ? "page" : undefined}+ onClick=${() => { onQuery(""); onTab(id); }}><${Icon} name=${icon} size="md" /><span>${tabLabel(label)}</span></button>`;})}</nav><div class="side-foot"><${AccountButton} username=${username} account=${account} on onClick=${() => onTab("general")} /></div>@@ -80,6 +142,7 @@ export function SettingsSide({ tab, query, onQuery, onTab, onBack, username, accexport function SettingsScreen({ tab, query: q, onQuery: setQ, onTab, focusRow, mf, onMfChanged, onSettings, models, modelsError, reloadModels, status, bots, onOpenBotSettings, account: acct, onAccount }) {const [s, setS] = useState(null);+ const g = useStore(guide);const [rekey, setRekey] = useState(false);const [notices, setNotices] = useState(false);const [sheet, setSheet] = useState(""); // login | usage | notifications@@ -88,6 +151,11 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, onTab, focusRow,const [cu, setCu] = useState(null);const [flash, setFlash] = useState("");const mode = useStore(themeMode);+ const p = useStore(prefs);+ const lang = useLang();+ // 语言偏好单独订阅:系统语言本来就是英文时,"跟随系统" → "English" 不改变界面语言,useLang() 不会变+ const [langPref, setLangPrefView] = useState(getLangPref);+ useEffect(() => onLangChange(() => setLangPrefView(getLangPref())), []);// 图片 / 视频模型(共用 Key 能用的,按推荐顺序):连上 Modelflare 后取const [media, setMedia] = useState(null);@@ -137,7 +205,7 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, onTab, focusRow,}};const disconnect = async () => {- if (!(await confirmSheet({ title: "断开 Modelflare?", body: "会从本机删除这个 API Key。机器人和会话都会保留,重新连接后继续使用。", confirmLabel: "断开", danger: true }))) return;+ if (!(await confirmSheet({ title: t("settings.disconnect.title"), body: t("settings.disconnect.body"), confirmLabel: t("settings.disconnect.confirm"), danger: true }))) return;try {await api("/modelflare", { method: "DELETE" });onMfChanged();@@ -146,10 +214,10 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, onTab, focusRow,}};const logout = async () => {- if (!(await confirmSheet({ title: "退出 Modelflare 账户?", body: "会撤销这台电脑的授权,并删除登录时为它和各机器人签发的 API Key。机器人和会话都会保留。", confirmLabel: "退出登录", danger: true }))) return;+ if (!(await confirmSheet({ title: t("settings.logout.title"), body: t("settings.logout.body"), confirmLabel: t("settings.logout.confirm"), danger: true }))) return;try {const r = await api("/account/logout", { method: "POST", body: {} });- if (!r.revoked) failed("服务端没有确认撤销:本机已退出,可在 Modelflare 网页的「已授权的应用」里再撤销一次");+ if (!r.revoked) failed(t("settings.logout.notRevoked"));onAccount(r);onMfChanged();} catch (e) {@@ -168,6 +236,23 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, onTab, focusRow,}).catch(failed);const desktop = !!(s && s.desktop);+ const pickFont = (v) => {+ setPrefs({ font: v });+ if (v === "custom") requestAnimationFrame(() => document.querySelector("#set-font-name input")?.focus());+ else saved();+ };+ const toggleNotify = async (v) => {+ if (v && !(await requestNotify())) return failed(t("settings.notifyDenied"));+ setPrefs({ notify: v });+ saved();+ };+ const customized = mode !== "system" || appearanceChanged(p) || (desktop && s.zoom !== 1);+ const resetLook = () => {+ setThemeMode("system");+ resetAppearance();+ if (desktop && s.zoom !== 1) put({ zoom: 1 }, { zoom: 1 });+ else saved();+ };const managed = mf && mf.mode === "managed";const signedIn = !!(acct && acct.state === "signed_in");// 登录后才有邀请码和通知;进入 Modelflare 分页时读一次@@ -180,116 +265,154 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, onTab, focusRow,// —— 行定义:每行一个稳定 id,可被搜索、可被深链(#/settings/<tab>/<id>)——const rows = useMemo(() => {if (!s) return [];+ const guideSteps = g.loaded ? visibleSteps(g) : [];+ const acctName = signedIn ? acct.name || t("settings.rows.account.signedIn") : "";+ const gw = status && status.gateway;+ const alertLines = ALERT_LINES();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`<${Switch} label="开机自启" value=${s.autostart.on} onChange=${(v) => put({ autostart: v }, { autostart: { ...s.autostart, on: v } })} />` },- 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: "general", id: "language", name: t("common.lang.label"), sub: t("settings.rows.language.sub"), keys: t("settings.rows.language.keys"),+ ctl: html`<${Seg} label=${t("common.lang.label")} value=${langPref} onChange=${(v) => changeLang(v).then(() => saved()).catch(failed)} options=${LANG_OPTIONS()} />` },+ { tab: "general", id: "send-key", name: t("settings.rows.sendKey.name"), sub: t("settings.rows.sendKey.sub", { key: p.sendKey === "mod" ? "Enter" : "Shift+Enter" }), keys: t("settings.rows.sendKey.keys"),+ ctl: html`<${Seg} label=${t("settings.rows.sendKey.name")} value=${p.sendKey} onChange=${(v) => { setPrefs({ sendKey: v }); saved(); }} options=${[["enter", "Enter"], ["mod", MOD_ENTER]]} />` },+ canNotify && { tab: "general", id: "notify", name: t("settings.rows.notify.name"), sub: t("settings.rows.notify.sub"), keys: t("settings.rows.notify.keys"),+ ctl: html`<${Switch} label=${t("settings.rows.notify.name")} value=${p.notify} onChange=${toggleNotify} />` },+ desktop && { tab: "general", id: "close", name: t("settings.rows.close.name"), sub: t("settings.rows.close.sub"), keys: t("settings.rows.close.keys"),+ ctl: html`<${Seg} label=${t("settings.rows.close.name")} value=${s.closeToTray} onChange=${(v) => put({ closeToTray: v }, { closeToTray: v })} options=${[[true, t("settings.rows.close.tray")], [false, t("settings.rows.close.quit")]]} />` },+ desktop && s.autostart.supported && { tab: "general", id: "autostart", name: t("settings.rows.autostart.name"), sub: t("settings.rows.autostart.sub"), keys: t("settings.rows.autostart.keys"),+ ctl: html`<${Switch} label=${t("settings.rows.autostart.name")} value=${s.autostart.on} onChange=${(v) => put({ autostart: v }, { autostart: { ...s.autostart, on: v } })} />` },+ desktop && { tab: "general", id: "browser", name: t("settings.rows.browser.name"), sub: t("settings.rows.browser.sub"), keys: t("settings.rows.browser.keys"),+ ctl: html`<button type="button" class="text" onClick=${() => api("/desktop/open-in-browser", { method: "POST", body: {} }).catch(failed)}>${t("common.open")}</button>` },+ g.loaded && { tab: "general", id: "guide", name: t("settings.rows.guide.name"),+ sub: g.hidden ? t("settings.rows.guide.hidden") : t("settings.rows.guide.progress", { done: guideSteps.filter((x) => g.done.includes(x.id)).length, total: guideSteps.length }),+ keys: t("settings.rows.guide.keys"),+ ctl: html`<button type="button" class="text" onClick=${() => resetGuide().then(() => toast(t("settings.rows.guide.restarted"))).catch(failed)}>${t("settings.rows.guide.restart")}</button>` },++ { tab: "appearance", id: "theme", name: t("settings.rows.theme.name"), sub: t("settings.rows.theme.sub"), keys: t("settings.rows.theme.keys"),+ ctl: html`<${Seg} label=${t("settings.rows.theme.name")} value=${mode} onChange=${(m) => { setThemeMode(m); saved(); }} options=${THEMES()} />` },+ { tab: "appearance", id: "text-size", name: t("settings.rows.textSize.name"), sub: desktop ? t("settings.rows.textSize.subDesktop") : t("settings.rows.textSize.sub"), keys: t("settings.rows.textSize.keys"),+ ctl: html`<${Seg} label=${t("settings.rows.textSize.name")} value=${p.text} onChange=${(v) => { setPrefs({ text: v }); saved(); }} options=${TEXT_SIZES()} />` },+ { tab: "appearance", id: "font", name: t("settings.rows.font.name"), sub: t("settings.rows.font.sub"), keys: t("settings.rows.font.keys"),+ ctl: html`<${Seg} label=${t("settings.rows.font.name")} value=${p.font} onChange=${pickFont} options=${FONTS()} />` },+ p.font === "custom" && { tab: "appearance", id: "font-name", name: t("settings.rows.fontName.name"), sub: p.fontName ? t("settings.rows.fontName.subSet") : t("settings.rows.fontName.subEmpty"), keys: t("settings.rows.fontName.keys"),+ ctl: html`<${FontInput} id="font-ui" label=${t("settings.rows.fontName.name")} value=${p.fontName} placeholder=${t("settings.rows.fontName.placeholder")} suggest=${SUGGEST_UI} fallback="var(--font-system)"+ onChange=${(v) => setPrefs({ fontName: v })} />` },+ { tab: "appearance", id: "code-font", name: t("settings.rows.codeFont.name"), sub: t("settings.rows.codeFont.sub"), keys: t("settings.rows.codeFont.keys"),+ ctl: html`<${FontInput} id="font-code" label=${t("settings.rows.codeFont.name")} value=${p.codeFont} placeholder=${t("settings.rows.codeFont.placeholder")} suggest=${SUGGEST_CODE} fallback="var(--code-system)"+ onChange=${(v) => setPrefs({ codeFont: v })} />` },+ desktop && { tab: "appearance", id: "zoom", name: t("settings.rows.zoom.name"), sub: t("settings.rows.zoom.sub"), keys: t("settings.rows.zoom.keys"),+ ctl: html`<${Seg} label=${t("settings.rows.zoom.name")} value=${s.zoom} onChange=${(z) => put({ zoom: z }, { zoom: z })} options=${ZOOMS} />` },+ { tab: "appearance", id: "chat-width", name: t("settings.rows.chatWidth.name"), sub: t("settings.rows.chatWidth.sub"), keys: t("settings.rows.chatWidth.keys"),+ ctl: html`<${Seg} label=${t("settings.rows.chatWidth.name")} value=${p.width} onChange=${(v) => { setPrefs({ width: v }); saved(); }} options=${WIDTHS()} />` },+ { tab: "appearance", id: "code-wrap", name: t("settings.rows.codeWrap.name"), sub: t("settings.rows.codeWrap.sub"), keys: t("settings.rows.codeWrap.keys"),+ ctl: html`<${Switch} label=${t("settings.rows.codeWrap.name")} value=${p.codeWrap} onChange=${(v) => { setPrefs({ codeWrap: v }); saved(); }} />` },+ { tab: "appearance", id: "motion", name: t("settings.rows.motion.name"), sub: t("settings.rows.motion.sub"), keys: t("settings.rows.motion.keys"),+ ctl: html`<${Seg} label=${t("settings.rows.motion.name")} value=${p.motion} onChange=${(v) => { setPrefs({ motion: v }); saved(); }} options=${AUTO_ON_OFF()} />` },+ { tab: "appearance", id: "glass", name: t("settings.rows.glass.name"), sub: t("settings.rows.glass.sub"), keys: t("settings.rows.glass.keys"),+ ctl: html`<${Seg} label=${t("settings.rows.glass.name")} value=${p.glass} onChange=${(v) => { setPrefs({ glass: v }); saved(); }} options=${AUTO_ON_OFF()} />` },+ { tab: "appearance", id: "reset-appearance", name: t("settings.rows.resetAppearance.name"), sub: desktop ? t("settings.rows.resetAppearance.subDesktop") : t("settings.rows.resetAppearance.sub"), keys: t("settings.rows.resetAppearance.keys"),+ ctl: html`<button type="button" class="text" disabled=${!customized} onClick=${resetLook}>${t("settings.rows.resetAppearance.button")}</button>` },- managed && acct && { tab: "modelflare", id: "account", name: "Modelflare 账户",- sub: signedIn ? `${acct.name || "已登录"}${acct.billedToEnterprise ? " · 由企业钱包付费" : ""}` : acct.state === "unavailable" ? acct.error : "登录后可以查看用量、通知和邀请链接,也能给机器人单独设预算", keys: "登录 注册 账户 退出 account login",+ managed && acct && { tab: "modelflare", id: "account", name: t("settings.rows.account.name"),+ sub: signedIn ? (acct.billedToEnterprise ? t("settings.rows.account.enterprise", { name: acctName }) : acctName) : acct.state === "unavailable" ? acct.error : t("settings.rows.account.signedOut"), keys: t("settings.rows.account.keys"),ctl: signedIn- ? html`<button type="button" class="text danger" onClick=${logout}>退出登录</button>`+ ? html`<button type="button" class="text danger" onClick=${logout}>${t("settings.rows.account.logout")}</button>`: acct.loginAvailable === false- ? html`<span class="val">Docker / 远程部署不支持浏览器登录</span>`- : html`<button type="button" class="text accent" onClick=${() => setSheet("login")}>登录 / 注册</button>` },- { tab: "modelflare", id: "connection", name: signedIn ? "本机 Key" : "连接",- sub: !managed ? "由环境变量 AMB_MAGPIE_BASE_URL 指定的端点(开发/测试)" : signedIn ? "登录时为这台电脑签发,退出登录会一并删除" : "API Key 只保存在本机", keys: "密钥 key api 断开 更换",+ ? html`<span class="val">${t("settings.rows.account.noBrowserLogin")}</span>`+ : html`<button type="button" class="text accent" onClick=${() => setSheet("login")}>${t("settings.rows.account.login")}</button>` },+ { tab: "modelflare", id: "connection", name: signedIn ? t("settings.rows.connection.nameSignedIn") : t("settings.rows.connection.name"),+ sub: !managed ? t("settings.rows.connection.subExternal") : signedIn ? t("settings.rows.connection.subSignedIn") : t("settings.rows.connection.sub"), keys: t("settings.rows.connection.keys"),ctl: managed- ? html`<span class="mf-state"><span class=${`dot ${mf.connected ? "ok" : "err"}`}></span>${mf.connected ? "已连接" : "未连接"}</span>+ ? html`<span class="mf-state"><span class=${`dot ${mf.connected ? "ok" : "err"}`}></span>${mf.connected ? t("common.connected") : t("common.notConnected")}</span>${mf.keyTail && html`<span class="val">••••${mf.keyTail}</span>`}- ${!signedIn && html`<button type="button" class="text" onClick=${() => setRekey(true)}>更换密钥</button>- <button type="button" class="text danger" onClick=${disconnect}>断开</button>`}`+ ${!signedIn && html`<button type="button" class="text" onClick=${() => setRekey(true)}>${t("settings.rows.connection.rekey")}</button>+ <button type="button" class="text danger" onClick=${disconnect}>${t("settings.rows.connection.disconnect")}</button>`}`: html`<span class="val" title=${mf && mf.baseUrl}>${mf && mf.baseUrl}</span>` },- managed && acct && mf.connected && { tab: "modelflare", id: "balance", name: "余额",- sub: acct.error ? `读取失败:${acct.error}` : acct.source === "key" ? "这把 Key 所在账户的钱包余额" : acct.updatedAt ? `更新于 ${new Date(acct.updatedAt).toLocaleTimeString()}` : "读取中…", keys: "余额 充值 钱包 balance top up",+ managed && acct && mf.connected && { tab: "modelflare", id: "balance", name: t("settings.rows.balance.name"),+ sub: acct.error ? t("settings.rows.balance.error", { error: acct.error }) : acct.source === "key" ? t("settings.rows.balance.fromKey") : acct.updatedAt ? t("settings.rows.balance.updated", { time: fmtTimeOfDay(acct.updatedAt) }) : t("common.reading"), keys: t("settings.rows.balance.keys"),ctl: html`<span class=${`balance${acct.lowBalance ? " low" : ""}`}>${usd(acct.balanceUsd)}</span>- <button type="button" class="icon-btn" title="刷新" aria-label="刷新余额" onClick=${refreshBalance}><${Icon} name="refresh" size=${14} /></button>- <a class="btn" href=${MF_TOPUP} target="_blank" rel="noopener noreferrer">充值 ↗</a>` },- managed && acct && mf.connected && { tab: "modelflare", id: "low-balance", name: "余额提醒", sub: "余额低于这个数时在应用里提醒一次,充值后重新计", keys: "提醒 余额不足 low balance",- ctl: html`<${Seg} label="余额提醒" value=${acct.alerts.lowBalanceUsd} onChange=${(v) => putAlerts({ lowBalanceUsd: v })}- options=${ALERT_LINES.some(([v]) => v === acct.alerts.lowBalanceUsd) ? ALERT_LINES : [...ALERT_LINES, [acct.alerts.lowBalanceUsd, usd(acct.alerts.lowBalanceUsd)]]} />` },- managed && acct && mf.connected && acct.alerts.lowBalanceUsd > 0 && { tab: "modelflare", id: "low-balance-push", name: "提醒也发到微信 / 飞书", sub: "由机器人发给你:微信发给扫码登录的人(需要他最近发过消息),飞书发到最近的单聊", keys: "推送 提醒 微信 飞书",- ctl: html`<${Switch} label="提醒也发到微信 / 飞书" value=${acct.alerts.push} onChange=${(v) => putAlerts({ lowBalancePush: v })} />` },- signedIn && { tab: "modelflare", id: "usage", name: "用量", sub: "按天、按模型的花费", keys: "用量 花费 账单 usage",- ctl: html`<button type="button" class="text" onClick=${() => setSheet("usage")}>查看</button>` },- signedIn && { tab: "modelflare", id: "notifications", name: "通知", sub: unread ? `${unread} 条未读` : "Modelflare 发给你的通知与公告", keys: "通知 公告 消息 notification",- ctl: html`<button type="button" class="text" onClick=${() => setSheet("notifications")}>查看</button>` },- signedIn && invite && { tab: "modelflare", id: "invite", name: "邀请好友", sub: "好友通过你的链接注册并充值,你会获得返利", keys: "邀请 返利 推广 invite",- ctl: html`<span class="val">${invite.code}</span><${CopyButton} text=${invite.url} label="复制邀请链接" />` },- 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="自动(列表第一个)"+ <button type="button" class="icon-btn" title=${t("common.refresh")} aria-label=${t("settings.rows.balance.refresh")} onClick=${refreshBalance}><${Icon} name="refresh" size="sm" /></button>+ <a class="btn" href=${MF_TOPUP} target="_blank" rel="noopener noreferrer">${t("settings.rows.balance.topUp")}</a>` },+ managed && acct && mf.connected && { tab: "modelflare", id: "low-balance", name: t("settings.rows.lowBalance.name"), sub: t("settings.rows.lowBalance.sub"), keys: t("settings.rows.lowBalance.keys"),+ ctl: html`<${Seg} label=${t("settings.rows.lowBalance.name")} value=${acct.alerts.lowBalanceUsd} onChange=${(v) => putAlerts({ lowBalanceUsd: v })}+ options=${alertLines.some(([v]) => v === acct.alerts.lowBalanceUsd) ? alertLines : [...alertLines, [acct.alerts.lowBalanceUsd, usd(acct.alerts.lowBalanceUsd)]]} />` },+ managed && acct && mf.connected && acct.alerts.lowBalanceUsd > 0 && { tab: "modelflare", id: "low-balance-push", name: t("settings.rows.lowBalancePush.name"), sub: t("settings.rows.lowBalancePush.sub"), keys: t("settings.rows.lowBalancePush.keys"),+ ctl: html`<${Switch} label=${t("settings.rows.lowBalancePush.name")} value=${acct.alerts.push} onChange=${(v) => putAlerts({ lowBalancePush: v })} />` },+ signedIn && { tab: "modelflare", id: "usage", name: t("settings.rows.usage.name"), sub: t("settings.rows.usage.sub"), keys: t("settings.rows.usage.keys"),+ ctl: html`<button type="button" class="text" onClick=${() => setSheet("usage")}>${t("common.view")}</button>` },+ signedIn && { tab: "modelflare", id: "notifications", name: t("settings.rows.notifications.name"), sub: unread ? t("settings.rows.notifications.unread", { count: unread }) : t("settings.rows.notifications.sub"), keys: t("settings.rows.notifications.keys"),+ ctl: html`<button type="button" class="text" onClick=${() => setSheet("notifications")}>${t("common.view")}</button>` },+ signedIn && invite && { tab: "modelflare", id: "invite", name: t("settings.rows.invite.name"), sub: t("settings.rows.invite.sub"), keys: t("settings.rows.invite.keys"),+ ctl: html`<span class="val">${invite.code}</span><${CopyButton} text=${invite.url} label=${t("settings.rows.invite.copy")} />` },+ managed && { tab: "modelflare", id: "line", name: t("settings.rows.line.name"), sub: t("settings.rows.line.sub"), keys: t("settings.rows.line.keys"),+ ctl: html`<${Seg} label=${t("settings.rows.line.name")} value=${mf.line} onChange=${setLine} options=${lineOptions()} />` },+ { tab: "modelflare", id: "default-model", name: t("settings.rows.defaultModel.name"), sub: t("settings.rows.defaultModel.sub"), keys: t("settings.rows.defaultModel.keys"),+ ctl: html`<${PickModel} value=${s.defaultModel} models=${models} modelsError=${modelsError} reloadModels=${reloadModels} resetLabel=${t("settings.rows.defaultModel.auto")}onChange=${(m) => put({ defaultModel: m }, { defaultModel: m })} />` },- managed && mf.connected && { tab: "modelflare", id: "image-model", name: "默认图片模型", sub: "机器人生成图片时默认选它,每次生成前都会让你确认", keys: "图片 生图 画图 image 模型",+ managed && mf.connected && { tab: "modelflare", id: "image-model", name: t("settings.rows.imageModel.name"), sub: t("settings.rows.imageModel.sub"), keys: t("settings.rows.imageModel.keys"),ctl: html`<${PickModel} value=${s.imageModel} models=${media ? media.image : null} modelsError=${media && media.error} reloadModels=${loadMedia}- resetLabel=${media && media.recommended.image ? `自动(${shortModel(media.recommended.image)})` : "自动"} label="默认图片模型"+ resetLabel=${media && media.recommended.image ? t("settings.rows.autoModel", { model: shortModel(media.recommended.image) }) : t("common.auto")} label=${t("settings.rows.imageModel.name")}onChange=${(m) => put({ imageModel: m }, { imageModel: m })} />` },- managed && mf.connected && { tab: "modelflare", id: "video-model", name: "默认视频模型", sub: "机器人生成视频时默认选它,每次生成前都会让你确认", keys: "视频 生视频 video 模型",+ managed && mf.connected && { tab: "modelflare", id: "video-model", name: t("settings.rows.videoModel.name"), sub: t("settings.rows.videoModel.sub"), keys: t("settings.rows.videoModel.keys"),ctl: html`<${PickModel} value=${s.videoModel} models=${media ? media.video : null} modelsError=${media && media.error} reloadModels=${loadMedia}- resetLabel=${media && media.recommended.video ? `自动(${shortModel(media.recommended.video)})` : "自动"} label="默认视频模型"+ resetLabel=${media && media.recommended.video ? t("settings.rows.autoModel", { model: shortModel(media.recommended.video) }) : t("common.auto")} label=${t("settings.rows.videoModel.name")}onChange=${(m) => put({ videoModel: m }, { videoModel: 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: "console", name: "Modelflare 控制台", sub: "账单、发票与 API Key 管理", keys: "控制台 账单 console",- ctl: html`<a class="text" href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">打开 ↗</a>` },+ { tab: "modelflare", id: "models", name: t("settings.rows.models.name"), sub: modelsError ? t("settings.rows.models.error", { error: modelsError }) : t("settings.rows.models.sub"), keys: t("settings.rows.models.keys"),+ ctl: html`<span class="val num">${models ? t("settings.rows.models.count", { count: models.length }) : "…"}</span><button type="button" class="text" onClick=${() => reloadModels().then(() => saved())}>${t("common.refresh")}</button>` },+ { tab: "modelflare", id: "console", name: t("settings.rows.console.name"), sub: t("settings.rows.console.sub"), keys: t("settings.rows.console.keys"),+ ctl: html`<a class="text" href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">${t("common.openExternal")}</a>` },- { tab: "computer", id: "cu-status", name: "电脑操作后端", sub: cu ? cu.reason : "读取中…", keys: "computer use cua 辅助功能 屏幕录制",+ { tab: "computer", id: "cu-status", name: t("settings.rows.cuStatus.name"), sub: cu ? cu.reason : t("common.reading"), keys: t("settings.rows.cuStatus.keys"),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>` },+ cu && cu.notice && { tab: "computer", id: "cu-notice", name: t("settings.rows.cuNotice.name"), sub: cu.notice, title: cu.notice, keys: t("settings.rows.cuNotice.keys"), ctl: null },+ { tab: "computer", id: "cu-per-bot", name: t("settings.rows.cuPerBot.name"), sub: t("settings.rows.cuPerBot.sub"), keys: t("settings.rows.cuPerBot.keys"),+ ctl: bots && bots[0] && html`<button type="button" class="text" onClick=${() => onOpenBotSettings(bots[0].id, "computer")}>${t("settings.rows.cuPerBot.open")}</button>` },- { tab: "privacy", id: "key-storage", name: "密钥存放", sub: "Modelflare 密钥只在本机内置网关的隔离配置里,不写日志、不进命令行参数", ctl: null, keys: "安全" },- { tab: "privacy", id: "account-storage", name: "账户凭据", sub: "登录 Modelflare 的凭据只存在数据目录,桌面版用系统钥匙串加密;界面只拿到账户名称", ctl: null, keys: "安全 登录 钥匙串" },- { tab: "privacy", id: "token", name: "访问令牌", sub: s.listen.tokenRequired ? "需要令牌:界面监听在非本机地址,或桌面版每次启动随机生成" : "只监听本机,无需令牌", keys: "token 令牌",+ { tab: "privacy", id: "key-storage", name: t("settings.rows.keyStorage.name"), sub: t("settings.rows.keyStorage.sub"), ctl: null, keys: t("settings.rows.keyStorage.keys") },+ { tab: "privacy", id: "account-storage", name: t("settings.rows.accountStorage.name"), sub: t("settings.rows.accountStorage.sub"), ctl: null, keys: t("settings.rows.accountStorage.keys") },+ { tab: "privacy", id: "token", name: t("settings.rows.token.name"), sub: s.listen.tokenRequired ? t("settings.rows.token.required") : t("settings.rows.token.local"), keys: t("settings.rows.token.keys"),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: "privacy", id: "sandbox", name: t("settings.rows.sandbox.name"), sub: t("settings.rows.sandbox.sub"), ctl: null, keys: t("settings.rows.sandbox.keys") },+ { tab: "privacy", id: "screens", name: t("settings.rows.screens.name"), sub: t("settings.rows.screens.sub"), ctl: null, keys: t("settings.rows.screens.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: "network", id: "listen", name: t("settings.rows.listen.name"), sub: t("settings.rows.listen.sub"), keys: t("settings.rows.listen.keys"),+ 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=${t("settings.rows.listen.copy")} />` },- { 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: "data", id: "data-dir", name: t("settings.rows.dataDir.name"), sub: t("settings.rows.dataDir.sub"), keys: t("settings.rows.dataDir.keys"),+ ctl: html`<span class="val" title=${s.dataDir}>${s.dataDir}</span><${CopyButton} text=${s.dataDir} label=${t("settings.rows.dataDir.copy")} />+ ${desktop && html`<button type="button" class="text" onClick=${() => api("/desktop/open-data-dir", { method: "POST", body: {} }).catch(failed)}>${t("common.open")}</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: html`<button type="button" class="text" onClick=${() => onTab?.("troubleshoot")}>故障排查</button>` },+ { tab: "about", id: "version", name: t("settings.rows.version.name"), keys: t("settings.rows.version.keys"), ctl: html`<span class="val">${status ? status.version : ""}</span>` },+ { tab: "about", id: "licenses", name: t("settings.rows.licenses.name"), sub: t("settings.rows.licenses.sub"), keys: t("settings.rows.licenses.keys"),+ ctl: html`<button type="button" class="text" onClick=${() => setNotices(true)}>${t("common.view")}</button>` },+ { tab: "about", id: "diagnostics", name: t("settings.rows.diagnostics.name"),+ sub: gw ? [t("settings.rows.diagnostics.gateway"), gatewayState(gw.state), gw.restarts && t("settings.rows.diagnostics.restarts", { count: gw.restarts }), gw.lastError].filter(Boolean).join(" · ") : "",+ keys: t("settings.rows.diagnostics.keys"),+ ctl: html`<button type="button" class="text" onClick=${() => onTab?.("troubleshoot")}>${t("settings.tabs.troubleshoot")}</button>` },// 故障排查页是单独的面板(troubleshoot.js),这一行只给搜索用:搜"日志""测试模型"时能找到入口- { tab: "troubleshoot", id: "troubleshoot", name: "故障排查", sub: "模型网关与代理进程的状态、测试模型、测试代理、最近日志、复制诊断信息", keys: "日志 log 测试 test 代理 agent 卡住 转圈 诊断 diagnostics 重启 PowerShell pwsh 命令慢 安装 重新安装 内置 系统默认",- ctl: html`<button type="button" class="text" onClick=${() => { setQ(""); onTab?.("troubleshoot"); }}>打开</button>` },- { 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_LINK} target="_blank" rel="noopener noreferrer">文档 ↗</a>` },+ { tab: "troubleshoot", id: "troubleshoot", name: t("settings.tabs.troubleshoot"), sub: t("settings.rows.troubleshoot.sub"), keys: t("settings.rows.troubleshoot.keys"),+ ctl: html`<button type="button" class="text" onClick=${() => { setQ(""); onTab?.("troubleshoot"); }}>${t("common.open")}</button>` },+ { tab: "about", id: "links", name: "Modelflare", sub: t("settings.rows.links.sub"),+ ctl: html`<a class="text" href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">modelflare.dev ↗</a><a class="text" href=${MF_DOCS_LINK} target="_blank" rel="noopener noreferrer">${t("settings.rows.links.docs")}</a>` },].filter(Boolean);- }, [s, mf, mode, models, modelsError, cu, status, bots, acct, invite, unread]);+ }, [s, mf, mode, p, models, modelsError, cu, status, bots, acct, invite, unread, g, media, lang, langPref]);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]];+ const parts = needle ? TABS.map(([id, label]) => [tabLabel(label), shown.filter((r) => r.tab === id)]).filter(([, l]) => l.length) : [["", shown]];- const title = needle ? "搜索结果" : (TABS.find(([t]) => t === tab) || TABS[0])[1];+ const title = needle ? t("settings.searchResults") : tabLabel((TABS.find(([id]) => id === tab) || TABS[0])[1]);return html`<section class="settings view" data-screen="settings" key=${needle ? "search" : tab}><div class="set-head"><h1 class="set-title">${title}</h1></div><div class="set-body">${!s && html`<div class="list"><div class="row"><${Skeleton} w="40%" /></div><div class="row"><${Skeleton} w="55%" /></div></div>`}- ${s && !shown.length && html`<p class="set-none">没有匹配的设置</p>`}+ ${s && !shown.length && html`<p class="set-none">${t("settings.noMatch")}</p>`}${s && !needle && tab === "general" && html`<${PwshHint} />`}+ ${s && !needle && tab === "appearance" && html`<${AppearancePreview} />`}${s && !needle && tab === "troubleshoot" ? html`<${TroubleshootPane} bots=${bots} desktop=${desktop} />` : 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(); }} />+ ${rekey && html`<${Sheet} title=${t("settings.rekey.title")} onClose=${() => setRekey(false)}>+ <${KeyForm} line=${mf.line} showLine=${false} submitLabel=${t("settings.rekey.submit")} onConnected=${() => { setRekey(false); saved(); onMfChanged(); reloadModels(); }} /><//>`}${notices && html`<${NoticesSheet} onClose=${() => setNotices(false)} />`}${sheet === "login" && html`<${LoginSheet} onClose=${() => setSheet("")} onSignedIn=${(r) => { onAccount(r); onMfChanged(); reloadModels(); }} />`}diff --git a/ui/screens/sidebar.js b/ui/screens/sidebar.jsindex dfbd975..7d07175 100644--- a/ui/screens/sidebar.js+++ b/ui/screens/sidebar.js@@ -1,21 +1,24 @@-// 侧栏 280(参考 Grok Bot):顶部只有新建按钮,常驻搜索框,机器人行(头像 + 名称 + 时间 + 一行预览),左下角账户(打开设置)。+// 侧栏 280(参考 Grok Bot,宽度可以拖右边的分隔条调整):顶部只有新建按钮,常驻搜索框,+// 机器人行(头像 + 名称 + 时间 + 一行预览;悬停出现"更多",和右键是同一份菜单),左下角账户(打开设置)。// 新建在主区的新建页(screens/new-bot.js);新建页打开时列表顶部有一行占位的"新机器人"。import { useEffect, useRef, useState } from "preact/hooks";import { html, Icon, IconButton, Menu, Skeleton } from "../components/ui.js";import { BotAvatar } from "../components/avatar.js";+import { GuidePill } from "../components/guide.js";import { api } from "../lib/api.js";import { confirmSheet, failed, toast } from "../lib/store.js";import { fmtAgo } from "../lib/format.js";import { MF_TOPUP, usd } from "../lib/links.js";+import { t } from "../lib/i18n.js";/** 左下角账户:头像字母 + 名称(登录后是 Modelflare 账户名)与余额 + 齿轮,点开设置 */export function AccountButton({ username, account, on, onClick }) {- const me = ((account && account.state === "signed_in" && account.name) || username || "本机用户").trim();+ const me = ((account && account.state === "signed_in" && account.name) || username || t("sidebar.localUser")).trim();const bal = account && account.balanceUsd !== null && account.balanceUsd !== undefined ? usd(account.balanceUsd) : "";- return html`<button type="button" class=${`account${on ? " on" : ""}`} title="设置(⌘,)" aria-label="打开设置" onClick=${onClick}>+ return html`<button type="button" class=${`account${on ? " on" : ""}`} title=${t("sidebar.settingsTitle")} aria-label=${t("sidebar.openSettings")} onClick=${onClick}><span class="me" aria-hidden="true">${me.slice(0, 1).toUpperCase()}</span>- <span class="who">${me}${bal && html`<span class=${`bal num${account.lowBalance ? " low" : ""}`}>余额 ${bal}</span>`}</span>- <${Icon} name="gear" size=${15} />+ <span class="who">${me}${bal && html`<span class=${`bal num${account.lowBalance ? " low" : ""}`}>${t("sidebar.balance", { amount: bal })}</span>`}</span>+ <${Icon} name="gear" size="md" /></button>`;}@@ -23,13 +26,13 @@ export function AccountButton({ username, account, on, onClick }) {function LowBalance({ account }) {if (!account || !account.lowBalance) return null;return html`<a class="low-balance" href=${MF_TOPUP} target="_blank" rel="noopener noreferrer" role="status">- 余额只剩 ${usd(account.balanceUsd)},去充值 ↗+ ${t("sidebar.lowBalance", { amount: usd(account.balanceUsd) })}</a>`;}-export function Sidebar({ bots, botsError, reloadBots, selectedId, view, previews, pending, working, username, account, onNew, onSelect, onDeleted, onOpenSettings }) {+export function Sidebar({ bots, botsError, reloadBots, selectedId, view, previews, pending, working, username, account, onNew, onSelect, onDeleted, onOpenSettings, onBotSettings, onGuide }) {const [q, setQ] = useState("");- const [ctx, setCtx] = useState(null); // { bot, x, y }+ const [ctx, setCtx] = useState(null); // 行的操作菜单:右键 { bot, x, y },或者"更多"按钮 { bot, el }const [renaming, setRenaming] = useState("");const [renameText, setRenameText] = useState("");const root = useRef(null);@@ -46,13 +49,13 @@ export function Sidebar({ bots, botsError, reloadBots, selectedId, view, previewtry {await api(`/bots/${bot.id}`, { method: "PUT", body: { name: n } });reloadBots();- toast("已重命名");+ toast(t("sidebar.renamed"));} catch (e) {failed(e);}};const del = async (bot) => {- if (!(await confirmSheet({ title: `删除「${bot.name}」?`, body: "会永久删除这个机器人及其全部会话,无法恢复。", confirmLabel: "永久删除", danger: true }))) return;+ if (!(await confirmSheet({ title: t("sidebar.delete.title", { name: bot.name }), body: t("sidebar.delete.body"), confirmLabel: t("sidebar.delete.confirm"), danger: true }))) return;try {await api(`/bots/${bot.id}`, { method: "DELETE" });onDeleted(bot.id);@@ -64,49 +67,58 @@ export function Sidebar({ bots, botsError, reloadBots, selectedId, view, previewconst needle = q.trim().toLowerCase();const list = (bots || []).filter((b) => !needle || b.name.toLowerCase().includes(needle) || (previews[b.id]?.text || "").toLowerCase().includes(needle));- return html`<aside class="side" ref=${root} aria-label="机器人">+ return html`<aside class="side" ref=${root} aria-label=${t("sidebar.bots")}><div class="side-top">- <${IconButton} icon="plus" iconSize=${16} label="新建机器人(⌘N)" on=${view === "new"} onClick=${onNew} />+ <span class="side-brand"><img src="/amb/static/assets/favicon-64.png" alt="" /><span>AnyModelBot</span></span>+ <${IconButton} icon="plus" iconSize="md" label=${t("sidebar.newShortcut")} on=${view === "new"} onClick=${onNew} /></div><label class="side-search">- <${Icon} name="search" size=${14} />- <input ref=${searchRef} type="search" placeholder="搜索" aria-label="搜索机器人" value=${q} onInput=${(e) => setQ(e.target.value)}+ <${Icon} name="search" size="sm" />+ <input ref=${searchRef} type="search" placeholder=${t("common.search")} aria-label=${t("sidebar.search")} value=${q} onInput=${(e) => setQ(e.target.value)}onKeyDown=${(e) => e.key === "Escape" && q && (e.stopPropagation(), setQ(""))} /></label>- <nav class="side-list" aria-label="机器人列表">+ <nav class="side-list" aria-label=${t("sidebar.list")}>${view === "new" && html`<div class="thread sel" aria-current="page"><${BotAvatar} neutral size=${38} />- <span class="body"><span class="line"><span class="title">新机器人</span></span><span class="line"><span class="snip">正在创建…</span></span></span></div>`}- ${botsError && html`<div class="side-empty"><span>无法读取机器人列表</span><button type="button" class="btn" onClick=${reloadBots}>重试</button></div>`}+ <span class="body"><span class="line"><span class="title">${t("sidebar.newBot")}</span></span><span class="line"><span class="snip">${t("sidebar.creating")}</span></span></span></div>`}+ ${botsError && html`<div class="side-empty"><span>${t("sidebar.loadFailed")}</span><button type="button" class="btn" onClick=${reloadBots}>${t("common.retry")}</button></div>`}${!bots && !botsError && [0, 1, 2].map((k) => html`<div class="thread" key=${k}><${Skeleton} w="38px" circle /><span class="thread-skel"><${Skeleton} w="50%" /><${Skeleton} w="75%" /></span></div>`)}- ${bots && !bots.length && view !== "new" && html`<div class="side-empty"><span>还没有机器人</span><button type="button" class="btn primary" onClick=${onNew}>新建机器人</button></div>`}- ${bots && needle && !list.length && html`<p class="hint">没有匹配的机器人</p>`}+ ${bots && !bots.length && view !== "new" && html`<div class="side-empty"><span>${t("sidebar.empty")}</span><button type="button" class="btn primary" onClick=${onNew}>${t("sidebar.create")}</button></div>`}+ ${bots && needle && !list.length && html`<p class="hint">${t("sidebar.noMatch")}</p>`}${list.map((b) => {const sel = (view === "chat" || view === "bot-settings") && b.id === selectedId;const n = pending[b.id] || 0;if (renaming === b.id)return html`<div class="thread sel" key=${b.id}><${BotAvatar} bot=${b} size=${38} />- <input class="field" value=${renameText} aria-label="新名称" ref=${renameRef}+ <input class="field" value=${renameText} aria-label=${t("sidebar.newName")} 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>`;const pv = previews[b.id];- return html`<button type="button" key=${b.id} class=${`thread bot-hover${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} bot=${b} size=${38} state=${n > 0 ? "waiting" : working[b.id] ? "working" : "idle"} />${working[b.id] && html`<span class="working-dot" title="工作中"></span>`}</span>- <span class="body">- <span class="line"><span class="title">${b.name}</span>${pv?.at && html`<span class="when num">${fmtAgo(pv.at)}</span>`}</span>- <span class="line"><span class="snip">${working[b.id] ? "正在工作…" : pv?.text || "还没有对话"}</span>${n > 0 && html`<span class="badge count" title=${`${n} 个待审批`}>${n}</span>`}</span>- </span>- </button>`;+ const menuOpen = !!(ctx && ctx.el && ctx.bot.id === b.id);+ return html`<div class="thread-item" key=${b.id}>+ <button type="button" class=${`thread bot-hover${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} bot=${b} size=${38} state=${n > 0 ? "waiting" : working[b.id] ? "working" : "idle"} />${working[b.id] && html`<span class="working-dot" title=${t("sidebar.working")}></span>`}</span>+ <span class="body">+ <span class="line"><span class="title">${b.name}</span>${pv?.at && html`<span class="when num">${fmtAgo(pv.at)}</span>`}</span>+ <span class="line"><span class="snip">${working[b.id] ? t("sidebar.workingNow") : pv?.text || t("sidebar.noChats")}</span>${n > 0 && html`<span class="badge count" title=${t("sidebar.pending", { count: n })}>${n}</span>`}</span>+ </span>+ </button>+ <${IconButton} icon="more" class="thread-more" label=${t("sidebar.moreFor", { name: b.name })} aria-haspopup="menu" aria-expanded=${menuOpen}+ onClick=${(e) => { const el = e.currentTarget; setCtx((c) => (c && c.el && c.bot.id === b.id ? null : { bot: b, el })); }} />+ </div>`;})}</nav><${LowBalance} account=${account} />+ ${bots && bots.length > 0 && html`<${GuidePill} onGo=${onGuide} />`}<div class="side-foot"><${AccountButton} username=${username} account=${account} onClick=${onOpenSettings} /></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)}+ ${ctx && html`<${Menu} anchor=${ctx.el || { left: ctx.x, right: ctx.x, top: ctx.y, bottom: ctx.y, width: 0 }} align=${ctx.el ? "right" : undefined}+ width=${200} label=${t("sidebar.actionsFor", { name: 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) },+ ...(onBotSettings ? [{ label: t("sidebar.menu.settings"), onSelect: () => onBotSettings(ctx.bot.id) }, { sep: true }] : []),+ { label: t("common.rename"), onSelect: () => { setRenameText(ctx.bot.name); setRenaming(ctx.bot.id); } },+ { label: t("sidebar.menu.copyId"), onSelect: () => navigator.clipboard?.writeText(ctx.bot.id).then(() => toast(t("common.copied"))).catch(failed) },{ sep: true },- { label: "删除机器人", danger: true, onSelect: () => del(ctx.bot) },+ { label: t("sidebar.menu.delete"), danger: true, onSelect: () => del(ctx.bot) },]} />`}</aside>`;}diff --git a/ui/screens/troubleshoot.js b/ui/screens/troubleshoot.jsindex e9d0eb9..5480cc3 100644--- a/ui/screens/troubleshoot.js+++ b/ui/screens/troubleshoot.js@@ -5,24 +5,60 @@ import { html, Button, CopyButton, Icon, Menu, Skeleton } from "../components/uiimport { api } from "../lib/api.js";import { failed, toast } from "../lib/store.js";import { PWSH_INSTALL_URL, PWSH_WINGET, installPwsh, pwshInstalling, pwshProgress, recheckPwsh, setPwshMode } from "../lib/pwsh.js";+import { t } from "../lib/i18n.js";-const GATEWAY = { running: ["运行中", "ok"], starting: ["启动中", "warn"], restarting: ["重启中", "warn"], failed: ["失败", "err"], stopped: ["已停止", "off"], external: ["外部端点", "ok"] };-const HOST = { running: ["运行中", "ok"], starting: ["启动中", "warn"], backoff: ["等待重试", "warn"], error: ["已暂停", "err"], stopped: ["未启动", "off"] };-const STAGE = { ok: ["通过", "ok"], warn: ["注意", "warn"], fail: ["失败", "err"], timeout: ["超时", "err"], skipped: ["未执行", "off"], pending: ["进行中", "warn"] };-const INIT_STAGE = { prepare: "准备", "bridge ready": "模型桥已就绪", "sdk loaded": "加载运行时", "patch written": "写入配置", "child spawned": "进程已拉起", initializing: "初始化(加载插件)" };+// 状态 → [文字, 圆点颜色]。文字跟着界面语言,渲染时再取(写成函数)+const GATEWAY = () => ({+ running: [t("troubleshoot.gateway.running"), "ok"],+ starting: [t("troubleshoot.gateway.starting"), "warn"],+ restarting: [t("troubleshoot.gateway.restarting"), "warn"],+ failed: [t("troubleshoot.gateway.failed"), "err"],+ stopped: [t("troubleshoot.gateway.stopped"), "off"],+ external: [t("troubleshoot.gateway.external"), "ok"],+});+const HOST = () => ({+ running: [t("troubleshoot.host.running"), "ok"],+ starting: [t("troubleshoot.host.starting"), "warn"],+ backoff: [t("troubleshoot.host.backoff"), "warn"],+ error: [t("troubleshoot.host.error"), "err"],+ stopped: [t("troubleshoot.host.stopped"), "off"],+});+const STAGE = () => ({+ ok: [t("troubleshoot.stage.ok"), "ok"],+ warn: [t("troubleshoot.stage.warn"), "warn"],+ fail: [t("troubleshoot.stage.fail"), "err"],+ timeout: [t("troubleshoot.stage.timeout"), "err"],+ skipped: [t("troubleshoot.stage.skipped"), "off"],+ pending: [t("troubleshoot.stage.pending"), "warn"],+});+const initStage = (s) =>+ ({+ prepare: t("troubleshoot.init.prepare"),+ "bridge ready": t("troubleshoot.init.bridgeReady"),+ "sdk loaded": t("troubleshoot.init.sdkLoaded"),+ "patch written": t("troubleshoot.init.patchWritten"),+ "child spawned": t("troubleshoot.init.childSpawned"),+ initializing: t("troubleshoot.init.initializing"),+ })[s] || s;+const secsText = (n) => t("troubleshoot.secs", { s: n });/** 代理进程一行的说明:启动中显示进度和阶段,运行中显示上次启动用时 */function hostSub(h) {- const secs = (ms) => (ms >= 10_000 ? `${Math.round(ms / 1000)} 秒` : `${(ms / 1000).toFixed(1)} 秒`);+ const secs = (ms) => secsText(ms >= 10_000 ? Math.round(ms / 1000) : (ms / 1000).toFixed(1));if (h.state === "starting")- return join(`已 ${secs(h.startingForMs || 0)}`, h.initStage && `阶段:${INIT_STAGE[h.initStage] || h.initStage}`, h.firstStart && "首次启动可能需要几分钟(杀毒软件会逐个扫描运行时文件)", h.initTimeoutMs && `最多等 ${Math.round(h.initTimeoutMs / 60000)} 分钟`);+ return join(+ t("troubleshoot.hostSub.elapsed", { time: secs(h.startingForMs || 0) }),+ h.initStage && t("troubleshoot.hostSub.stage", { stage: initStage(h.initStage) }),+ h.firstStart && t("troubleshoot.hostSub.firstStart"),+ h.initTimeoutMs && t("troubleshoot.hostSub.maxWait", { count: Math.round(h.initTimeoutMs / 60000) }),+ );return join(h.pid && `pid ${h.pid}`,h.model,- h.lastInitMs && `启动用时 ${secs(h.lastInitMs)}`,- h.restarts ? `重启 ${h.restarts} 次` : "",- h.activeTurns ? `${h.activeTurns} 轮进行中` : "",- h.retryInMs ? `${Math.ceil(h.retryInMs / 60000)} 分钟后自动重试,或点下面的"重启代理进程"` : "",+ h.lastInitMs && t("troubleshoot.hostSub.initTime", { time: secs(h.lastInitMs) }),+ h.restarts ? t("troubleshoot.restarts", { count: h.restarts }) : "",+ h.activeTurns ? t("troubleshoot.hostSub.activeTurns", { count: h.activeTurns }) : "",+ h.retryInMs ? t("troubleshoot.hostSub.retryIn", { count: Math.ceil(h.retryInMs / 60000) }) : "",exitText(h.lastExit),h.lastError,);@@ -36,17 +72,17 @@ function Row({ id, name, sub, mono, children, compact }) {}const State = ({ map, s }) => {- const [text, kind] = map[s] || [s || "未知", "off"];+ const [text, kind] = map[s] || [s || t("common.unknown"), "off"];return html`<span class="ts-state"><span class=${`dot ${kind === "off" ? "" : kind}`}></span>${text}</span>`;};-const Verdict = ({ ok }) => html`<span class="ts-state"><span class=${`dot ${ok ? "ok" : "err"}`}></span>${ok ? "正常" : "有问题"}</span>`;+const Verdict = ({ ok }) => html`<span class="ts-state"><span class=${`dot ${ok ? "ok" : "err"}`}></span>${ok ? t("troubleshoot.verdict.ok") : t("troubleshoot.verdict.bad")}</span>`;-const ms = (v) => (v === undefined || v === null ? "" : v >= 10_000 ? `${(v / 1000).toFixed(1)} 秒` : `${v} ms`);-const exitText = (e) => (e ? `上次退出 code=${e.code ?? "-"}${e.signal ? ` signal=${e.signal}` : ""}` : "");+const ms = (v) => (v === undefined || v === null ? "" : v >= 10_000 ? secsText((v / 1000).toFixed(1)) : `${v} ms`);+const exitText = (e) => (e ? t("troubleshoot.lastExit", { code: e.code ?? "-", signal: e.signal ? ` signal=${e.signal}` : "" }) : "");const join = (...a) => a.filter(Boolean).join(" · ");-const PS_SOURCE = { "program-files": "安装目录", path: "PATH", preview: "预览版", store: "Microsoft Store", private: "应用内置" };-const fmtTime = (t) => (t ? new Date(t).toLocaleString() : "");+const psSource = (s) =>+ ({ "program-files": t("troubleshoot.pwsh.source.programFiles"), path: "PATH", preview: t("troubleshoot.pwsh.source.preview"), store: "Microsoft Store", private: t("troubleshoot.pwsh.source.private") })[s];/*** PowerShell(只在 Windows 上,其他平台整行不出现):一行说清代理现在用哪个、装没装好;@@ -61,55 +97,54 @@ function PwshRows({ ps, busy, onRecheck, onInstall, onMode }) {const installing = pwshInstalling(ps);const system = ps.mode === "system";const failed = !!p && !installing && (p.bad || inst.state === "failed");- const fb = ps.fallback ? `之前用的 ${ps.fallback.from} 起不来(${ps.fallback.reason}),已自动换掉` : "";+ const fb = ps.fallback ? t("troubleshoot.pwsh.fallback", { from: ps.fallback.from, reason: ps.fallback.reason }) : "";const [text, kind] = ps.checking- ? ["检测中", ""]+ ? [t("troubleshoot.pwsh.checking"), ""]: !ps.missing? [ps.version || "7", "ok"]: installing? [pwshProgress(inst), "warn"]: failed- ? [p.bad ? "用不了" : "没装上", "err"]- : ["未安装", "warn"];+ ? [t(p.bad ? "troubleshoot.pwsh.unusable" : "troubleshoot.pwsh.notInstalled"), "err"]+ : [t("troubleshoot.pwsh.missing"), "warn"];const sub = ps.checking- ? "正在找 PowerShell 7"+ ? t("troubleshoot.pwsh.looking"): !ps.missing- ? join(`代理用它执行命令(${PS_SOURCE[ps.source] || ps.source})`, fb)+ ? join(t("troubleshoot.pwsh.usedByFrom", { source: psSource(ps.source) || ps.source }), fb): installing- ? "正在为代理安装 PowerShell 7,不需要管理员权限;装好前命令照常用 Windows PowerShell 5.1"+ ? t("troubleshoot.pwsh.installingSub"): failed- ? join(p.bad ? `应用内置的 PowerShell 7 用不了:${p.bad.reason}` : `没装上:${inst.error || "未知原因"}`, "代理先用 Windows PowerShell 5.1")+ ? join(p.bad ? t("troubleshoot.pwsh.badSub", { reason: p.bad.reason }) : t("troubleshoot.pwsh.failedSub", { error: inst.error || t("troubleshoot.pwsh.unknownReason") }), t("troubleshoot.pwsh.using51")): p && !p.supported- ? join(p.reason, "代理在用 Windows PowerShell 5.1,每条命令可能要二三十秒")- : "代理在用 Windows PowerShell 5.1,每条命令可能要二三十秒;装上 PowerShell 7 快得多";+ ? join(p.reason, t("troubleshoot.pwsh.slow51"))+ : t("troubleshoot.pwsh.slow51Advice");// 主按钮:只在需要用户动手时出现- const primary = !ps.checking && ps.missing && !installing && p?.supported ? (failed ? ["重新安装", () => onInstall(true)] : !system ? ["安装", () => onInstall(false)] : null) : null;+ const primary =+ !ps.checking && ps.missing && !installing && p?.supported+ ? failed+ ? [t("troubleshoot.pwsh.reinstall"), () => onInstall(true)]+ : !system+ ? [t("troubleshoot.pwsh.installShort"), () => onInstall(false)]+ : null+ : null;const items = [- { label: "重新检测", onSelect: onRecheck },- ...(p?.supported && !installing && p.installed && !failed ? [{ label: "重新安装应用内置的 PowerShell 7", onSelect: () => onInstall(true) }] : []),- ...(p?.supported && !installing && (p.installed || p.ready) && !system ? [{ label: "改回系统默认", note: "不用应用内置的 PowerShell 7", onSelect: () => onMode("system") }] : []),- ...(p?.supported && system ? [{ label: "改用应用内置的 PowerShell 7", onSelect: () => onMode("auto") }] : []),- ...(ps.missing && !installing && (!p?.supported || failed || system) ? [{ sep: true }, { label: "自己安装 PowerShell 7…", note: PWSH_WINGET, onSelect: () => window.open(PWSH_INSTALL_URL, "_blank", "noopener") }] : []),+ { label: t("troubleshoot.pwsh.recheck"), onSelect: onRecheck },+ ...(p?.supported && !installing && p.installed && !failed ? [{ label: t("troubleshoot.pwsh.reinstallPrivate"), onSelect: () => onInstall(true) }] : []),+ ...(p?.supported && !installing && (p.installed || p.ready) && !system ? [{ label: t("troubleshoot.pwsh.useSystem"), note: t("troubleshoot.pwsh.useSystemNote"), onSelect: () => onMode("system") }] : []),+ ...(p?.supported && system ? [{ label: t("troubleshoot.pwsh.usePrivate"), onSelect: () => onMode("auto") }] : []),+ ...(ps.missing && !installing && (!p?.supported || failed || system)+ ? [{ sep: true }, { label: t("troubleshoot.pwsh.installSelf"), note: PWSH_WINGET, onSelect: () => window.open(PWSH_INSTALL_URL, "_blank", "noopener") }]+ : []),];const dis = !!busy || installing;return html`<${Row} id="pwsh" name="PowerShell" sub=${sub}><span class="ts-state"><span class=${`dot ${kind}`}></span>${text}</span>${primary && html`<button type="button" class="text" disabled=${dis} aria-busy=${busy === "pwsh-install" || undefined} onClick=${primary[1]}>${busy === "pwsh-install" ? `${primary[0]}…` : primary[0]}</button>`}- <button type="button" class="icon-btn" ref=${more} title="更多" aria-label="PowerShell 的更多操作" aria-haspopup="menu" aria-expanded=${menu} disabled=${dis} onClick=${() => setMenu(!menu)}><${Icon} name="more" size=${14} /></button>+ <button type="button" class="icon-btn" ref=${more} title=${t("troubleshoot.pwsh.more")} aria-label=${t("troubleshoot.pwsh.moreLabel")} aria-haspopup="menu" aria-expanded=${menu} disabled=${dis} onClick=${() => setMenu(!menu)}><${Icon} name="more" size=${14} /></button>${menu && html`<${Menu} anchor=${more.current} align="right" width=${300} label="PowerShell" items=${items} onClose=${() => setMenu(false)} />`}<//>`;}-function ProbeRow({ name, p }) {- if (!p) return null;- if (p.skipped) return html`<${Row} compact name=${name} sub=${p.skipped}><span class="ts-state"><span class="dot"></span>未测</span><//>`;- const sub = p.ok ? join(p.url, p.echoedModel && `回显模型 ${p.echoedModel}`, p.reply && `回复 “${p.reply}”`) : join(p.url, p.error);- return html`<${Row} compact name=${name} sub=${sub} mono=${!p.ok}>- <span class="ts-state"><span class=${`dot ${p.ok ? "ok" : "err"}`}></span>${p.status ? `HTTP ${p.status}` : p.ok ? "正常" : "失败"}</span>- ${p.ms !== undefined && html`<span class="val num">${ms(p.ms)}</span>`}- <//>`;-}-export function TroubleshootPane({ bots, desktop }) {const [st, setSt] = useState(null);const [logs, setLogs] = useState(null);@@ -134,13 +169,13 @@ export function TroubleshootPane({ bots, desktop }) {setLogs(d);requestAnimationFrame(() => logRef.current && (logRef.current.scrollTop = logRef.current.scrollHeight));})- .catch((e) => setLogs({ lines: [`读取日志失败:${e.message}`] }));+ .catch((e) => setLogs({ lines: [t("troubleshoot.logs.readFailed", { error: e.message })] }));useEffect(() => {loadStatus();loadLogs();- const t = setInterval(loadStatus, 3000);- return () => clearInterval(t);+ const timer = setInterval(loadStatus, 3000);+ return () => clearInterval(timer);}, []);const run = async (what, fn) => {@@ -160,7 +195,7 @@ export function TroubleshootPane({ bots, desktop }) {const restart = () =>run("restart", async () => {const r = await api("/diagnostics/restart-agent", { method: "POST", body: {} });- toast(r.restarted.length ? "代理进程已重启" : "代理进程还没有启动,下一条消息时启动");+ toast(r.restarted.length ? t("troubleshoot.restart.done") : t("troubleshoot.restart.notRunning"));});const recheckPs = () => run("pwsh", recheckPwsh);const installPs = (reinstall) => run("pwsh-install", () => installPwsh(reinstall));@@ -169,7 +204,7 @@ export function TroubleshootPane({ bots, desktop }) {run("copy", async () => {const { text } = await api("/diagnostics/report?lines=200");await navigator.clipboard.writeText(text);- toast("诊断信息已复制(已去掉密钥)");+ toast(t("troubleshoot.copied"));});if (!st) return html`<div class="list"><div class="row"><${Skeleton} w="40%" /></div><div class="row"><${Skeleton} w="55%" /></div></div>`;@@ -177,66 +212,67 @@ export function TroubleshootPane({ bots, desktop }) {const g = st.gateway || {};const hosts = Object.entries(st.agent?.hosts || {});const tail = hosts.flatMap(([, h]) => h.stderrTail || []).slice(-12);+ const stageMap = STAGE();return html`- <div class="set-part">状态</div>+ <div class="set-part">${t("troubleshoot.status")}</div><div class="list">- <${Row} id="gateway" name="模型网关"- sub=${g.mode === "managed" ? join(g.pid && `pid ${g.pid}`, g.restarts ? `重启 ${g.restarts} 次` : "", exitText(g.lastExit), g.lastError) : join("由 AMB_MAGPIE_BASE_URL 指定", g.url)}>- <${State} map=${GATEWAY} s=${g.state} />+ <${Row} id="gateway" name=${t("troubleshoot.gateway.name")}+ sub=${g.mode === "managed" ? join(g.pid && `pid ${g.pid}`, g.restarts ? t("troubleshoot.restarts", { count: g.restarts }) : "", exitText(g.lastExit), g.lastError) : join(t("troubleshoot.gateway.fromEnv", { env: "AMB_MAGPIE_BASE_URL" }), g.url)}>+ <${State} map=${GATEWAY()} s=${g.state} /><//>- ${!st.agent?.available && html`<${Row} id="agent" name="代理进程" sub=${st.agent?.enabled ? "找不到代理运行时(DSH),机器人只能纯对话" : "代理模式已关闭,机器人只做纯对话"}><${State} map=${HOST} s="error" /><//>`}- ${st.agent?.available && !hosts.length && html`<${Row} id="agent" name="代理进程" sub="收到第一条消息时启动"><${State} map=${HOST} s="stopped" /><//>`}- ${hosts.map(([id, h]) => html`<${Row} key=${id} id=${`agent-${id}`} name=${hosts.length > 1 ? `代理进程 · ${botName(id)}` : "代理进程"}+ ${!st.agent?.available && html`<${Row} id="agent" name=${t("troubleshoot.agent.name")} sub=${st.agent?.enabled ? t("troubleshoot.agent.noRuntime") : t("troubleshoot.agent.disabled")}><${State} map=${HOST()} s="error" /><//>`}+ ${st.agent?.available && !hosts.length && html`<${Row} id="agent" name=${t("troubleshoot.agent.name")} sub=${t("troubleshoot.agent.startsOnFirst")}><${State} map=${HOST()} s="stopped" /><//>`}+ ${hosts.map(([id, h]) => html`<${Row} key=${id} id=${`agent-${id}`} name=${hosts.length > 1 ? t("troubleshoot.agent.nameFor", { bot: botName(id) }) : t("troubleshoot.agent.name")}sub=${hostSub(h)}>- <${State} map=${HOST} s=${h.state} />+ <${State} map=${HOST()} s=${h.state} /><//>`)}- ${tail.length > 0 && html`<div class="row-edit ts-tail"><span class="t-label">代理进程输出(stderr 最后 ${tail.length} 行)</span><pre class="ts-mono">${tail.join("\n")}</pre></div>`}+ ${tail.length > 0 && html`<div class="row-edit ts-tail"><span class="t-label">${t("troubleshoot.agent.stderr", { count: tail.length })}</span><pre class="ts-mono">${tail.join("\n")}</pre></div>`}<${PwshRows} ps=${st.pwsh} busy=${busy} onRecheck=${recheckPs} onInstall=${installPs} onMode=${modePs} />- <${Row} id="version" name="版本" sub=${join(st.os, st.electron && `Electron ${st.electron}`, `Node ${st.node}`)}>+ <${Row} id="version" name=${t("troubleshoot.version")} sub=${join(st.os, st.electron && `Electron ${st.electron}`, `Node ${st.node}`)}><span class="val">${st.version} · ${st.platform} ${st.arch}</span><//>- <${Row} id="data-dir" name="数据目录">- <span class="val" title=${st.dataDir}>${st.dataDir}</span><${CopyButton} text=${st.dataDir} label="复制路径" />- ${desktop && html`<button type="button" class="text" onClick=${() => api("/desktop/open-data-dir", { method: "POST", body: {} }).catch(failed)}>打开</button>`}+ <${Row} id="data-dir" name=${t("troubleshoot.dataDir")}>+ <span class="val" title=${st.dataDir}>${st.dataDir}</span><${CopyButton} text=${st.dataDir} label=${t("troubleshoot.copyPath")} />+ ${desktop && html`<button type="button" class="text" onClick=${() => api("/desktop/open-data-dir", { method: "POST", body: {} }).catch(failed)}>${t("common.open")}</button>`}<//>- <${Row} id="log-file" name="日志文件" sub="按大小轮转,保留最近 4 个文件">- <span class="val" title=${st.logFile || ""}>${st.logFile || "未启用"}</span>${st.logFile && html`<${CopyButton} text=${st.logFile} label="复制路径" />`}+ <${Row} id="log-file" name=${t("troubleshoot.logFile")} sub=${t("troubleshoot.logFileSub")}>+ <span class="val" title=${st.logFile || ""}>${st.logFile || t("troubleshoot.logFileOff")}</span>${st.logFile && html`<${CopyButton} text=${st.logFile} label=${t("troubleshoot.copyPath")} />`}<//></div>- <div class="set-part">检测</div>+ <div class="set-part">${t("troubleshoot.checks")}</div><div class="list">- <${Row} id="test-model" name="测试模型" sub="发一个最小请求:经内置网关、直连端点各一次,对比两边的状态码、耗时与回显的模型名">- <${Button} size="sm" loading=${busy === "model"} disabled=${!!busy} onClick=${testModel}>测试<//>+ <${Row} id="test-model" name=${t("troubleshoot.testModel.name")} sub=${t("troubleshoot.testModel.sub")}>+ <${Button} size="sm" loading=${busy === "model"} disabled=${!!busy} onClick=${testModel}>${t("troubleshoot.test")}<//><//>${modelRes && html`- <${Row} compact name=${modelRes.verdict} sub=${`模型 ${modelRes.model || "(无)"}`}>+ <${Row} compact name=${modelRes.verdict} sub=${t("troubleshoot.model", { model: modelRes.model || t("troubleshoot.none") })}><${Verdict} ok=${modelRes.direct.ok && (modelRes.gateway.ok || !!modelRes.gateway.skipped)} /><//>- <${ProbeRow} name="经内置网关" p=${modelRes.gateway} />- <${ProbeRow} name="直连端点" p=${modelRes.direct} />`}- <${Row} id="test-agent" name="测试代理" sub="让代理进程完整跑一轮最小对话(不进聊天记录),看卡在哪一步:启动 → 插件 → 模型 → 回复">- <${Button} size="sm" loading=${busy === "agent"} disabled=${!!busy} onClick=${testAgent}>测试<//>+ <${ProbeRow} name=${t("troubleshoot.testModel.viaGateway")} p=${modelRes.gateway} />+ <${ProbeRow} name=${t("troubleshoot.testModel.direct")} p=${modelRes.direct} />`}+ <${Row} id="test-agent" name=${t("troubleshoot.testAgent.name")} sub=${t("troubleshoot.testAgent.sub")}>+ <${Button} size="sm" loading=${busy === "agent"} disabled=${!!busy} onClick=${testAgent}>${t("troubleshoot.test")}<//><//>${agentRes && html`- <${Row} compact name=${agentRes.ok ? "代理正常" : `卡在:${(agentRes.stages.find((s) => s.id === agentRes.stuckAt) || {}).label || "未知"}`}- sub=${join(`机器人 ${botName(agentRes.botId)}`, agentRes.model && `模型 ${agentRes.model}`, `共 ${ms(agentRes.ms)}`)}>+ <${Row} compact name=${agentRes.ok ? t("troubleshoot.testAgent.ok") : t("troubleshoot.testAgent.stuckAt", { stage: (agentRes.stages.find((s) => s.id === agentRes.stuckAt) || {}).label || t("common.unknown") })}+ sub=${join(t("troubleshoot.testAgent.bot", { name: botName(agentRes.botId) }), agentRes.model && t("troubleshoot.model", { model: agentRes.model }), t("troubleshoot.testAgent.total", { time: ms(agentRes.ms) }))}><${Verdict} ok=${agentRes.ok} /><//>${agentRes.stages.map((s) => html`<${Row} compact key=${s.id} name=${s.label} sub=${s.detail} mono=${s.status === "fail" || s.status === "timeout"}>- <${State} map=${STAGE} s=${s.status} />${s.ms !== undefined && html`<span class="val num">${ms(s.ms)}</span>`}+ <${State} map=${stageMap} s=${s.status} />${s.ms !== undefined && html`<span class="val num">${ms(s.ms)}</span>`}<//>`)}`}- <${Row} id="restart-agent" name="重启代理进程" sub="回复一直转圈时用:结束代理进程并清掉重试等待,下一条消息重新启动">- <${Button} size="sm" loading=${busy === "restart"} disabled=${!!busy} onClick=${restart}>重启<//>+ <${Row} id="restart-agent" name=${t("troubleshoot.restart.name")} sub=${t("troubleshoot.restart.sub")}>+ <${Button} size="sm" loading=${busy === "restart"} disabled=${!!busy} onClick=${restart}>${t("troubleshoot.restart.button")}<//><//></div><div class="set-part ts-log-head">- <span>最近日志</span><span class="t-meta">${logs ? `${logs.lines.length} 行` : ""}</span><span class="grow"></span>- <button type="button" class="text" onClick=${loadLogs}><${Icon} name="refresh" size=${13} /> 刷新</button>- <${Button} size="sm" icon="copy" loading=${busy === "copy"} disabled=${!!busy && busy !== "copy"} onClick=${copy}>复制诊断信息<//>+ <span>${t("troubleshoot.logs.title")}</span><span class="t-meta">${logs ? t("troubleshoot.logs.lines", { count: logs.lines.length }) : ""}</span><span class="grow"></span>+ <button type="button" class="text" onClick=${loadLogs}><${Icon} name="refresh" size="sm" /> ${t("common.refresh")}</button>+ <${Button} size="sm" icon="copy" loading=${busy === "copy"} disabled=${!!busy && busy !== "copy"} onClick=${copy}>${t("troubleshoot.copyReport")}<//></div>- <pre class="ts-log" ref=${logRef} tabindex="0" aria-label="最近日志">${logs ? logs.lines.join("\n") || "(还没有日志)" : "加载中…"}</pre>- <p class="ts-note">复制的诊断信息包含上面的状态、最近一次测试结果和日志,API Key、令牌等已替换成 ***,可以直接发给支持人员。</p>+ <pre class="ts-log" ref=${logRef} tabindex="0" aria-label=${t("troubleshoot.logs.title")}>${logs ? logs.lines.join("\n") || t("troubleshoot.logs.empty") : t("common.loading")}</pre>+ <p class="ts-note">${t("troubleshoot.note")}</p>`;}diff --git a/vitest.config.ts b/vitest.config.tsindex f7a1465..a6c8a5f 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -1,4 +1,5 @@import { defineConfig } from "vitest/config";export default defineConfig({- test: { include: ["test/**/*.test.ts"], testTimeout: 30_000, hookTimeout: 60_000, pool: "forks", fileParallelism: false },+ // AMB_LANG:服务端"跟随系统"时的语言(src/i18n)。测试固定用简体中文,不受开发机 LANG 影响;英文由 i18n 测试单独覆盖+ test: { include: ["test/**/*.test.ts"], testTimeout: 30_000, hookTimeout: 60_000, pool: "forks", fileParallelism: false, env: { AMB_LANG: "zh-CN" } },});