diff --git a/cmd/bootagent-desktop/core_e2e.go b/cmd/bootagent-desktop/core_e2e.go index 74e7ba18..3f0254d0 100644 --- a/cmd/bootagent-desktop/core_e2e.go +++ b/cmd/bootagent-desktop/core_e2e.go @@ -6,6 +6,7 @@ import ( "context" "io" "net/http" + "os" "path/filepath" "strings" "sync" @@ -104,6 +105,20 @@ func (r *e2eRunner) Run(_ context.Context, argv []string, _ map[string]string, _ return result, nil } +// RunPrivateInput plays an Agent given a task on stdin. The first task is the +// only caller that sets a working directory, and what it checks afterwards is +// that a page exists there. +func (r *e2eRunner) RunPrivateInput(ctx context.Context, argv []string, _ map[string]string, _ time.Duration, _ string) (process.Result, error) { + result := process.Result{Args: append([]string(nil), argv...), ExitCode: 0} + if directory := process.WorkingDirectory(ctx); directory != "" { + if err := os.WriteFile(filepath.Join(directory, "index.html"), []byte("BootAgent e2e"), 0o600); err != nil { + return result, err + } + result.Stdout = "Created index.html\n" + } + return result, nil +} + type e2eProviderDoer struct{} func (e2eProviderDoer) Do(request *http.Request) (*http.Response, error) { diff --git a/cmd/bootagent-desktop/main_wails.go b/cmd/bootagent-desktop/main_wails.go index e068f909..9a6a5e21 100644 --- a/cmd/bootagent-desktop/main_wails.go +++ b/cmd/bootagent-desktop/main_wails.go @@ -10,7 +10,6 @@ import ( "log/slog" "os" "runtime" - "strings" "sync" "sync/atomic" @@ -206,10 +205,12 @@ func configureSystemTray(appInstance *application.App, core *app.UseCases, windo menu := appInstance.Menu.New() menu.Add("显示 BootAgent").OnClick(func(*application.Context) { tray.ShowWindow() }) menu.AddSeparator() + // Only on and off: each Agent in compatibility mode has its own model, + // chosen on that Agent's page, so there is no single target to pick here. enabled := config.Enabled - toggleLabel := "启动 API 转换" + toggleLabel := "开启兼容模式" if enabled { - toggleLabel = "停止 API 转换" + toggleLabel = "停止兼容模式" } menu.AddCheckbox(toggleLabel, enabled).OnClick(func(*application.Context) { if _, err := core.SetConversionEnabled(context.Background(), !enabled); err != nil { @@ -217,26 +218,6 @@ func configureSystemTray(appInstance *application.App, core *app.UseCases, windo } refresh() }) - profilesMenu := menu.AddSubmenu("转换目标 Profile") - profiles, err := core.ListProfiles(context.Background()) - if err == nil { - for _, profile := range profiles { - if profile.Protocol != "openai" || strings.HasPrefix(profile.ID, "bootagent-converter-") || strings.HasPrefix(profile.ID, "bootagent_converter_") { - continue - } - label := profile.Label - if label == "" { - label = profile.ID - } - profileID := profile.ID - profilesMenu.AddRadio(label, profileID == config.TargetProfile).OnClick(func(*application.Context) { - if _, err := core.SetConversionTargetProfile(context.Background(), profileID); err != nil { - slog.Warn("conversion tray profile switch failed", "error", err) - } - refresh() - }) - } - } menu.AddSeparator() menu.Add("退出 BootAgent").OnClick(func(*application.Context) { quitting.Store(true) diff --git a/docs/official-login-plan.md b/docs/official-login-plan.md new file mode 100644 index 00000000..c0941def --- /dev/null +++ b/docs/official-login-plan.md @@ -0,0 +1,101 @@ +# 官方账号登录:让 Agent 切回自己的登录方式 + +> 状态:方案草稿,未实施。起草于 2026-10-12,代码核对至 `claude/compat-mode-flow` 工作区(基于 `3d335e0`)。 + +## 1. 结论 + +「切到官方登录」这一步本身确实只是改配置文件: + +- **Codex**:在 `config.toml` 删掉 3 个键,在 `auth.json` 改 2 个键。 +- **Claude Code**:删掉 `settings.json` 里 `env` 下的 3 个键。 + +难点不在写文件,而在以下三处: + +1. **登录这一步改文件做不到。** ChatGPT 账号和 Claude 订阅都是浏览器 OAuth,凭据由 Agent 自己写入 `auth.json` 或系统钥匙串。BootAgent 能做的是: + - 判断用户是否已经登录; + - 没登录时打开终端执行官方的登录命令。 +2. **Codex 的 API Key 和 ChatGPT 登录共用 `auth.json`。** BootAgent 现在写入 Key 的方式本身会改动登录状态。往回切时需要恢复登录状态,而且两种方式共存时有一个需要先核实的安全风险,见 §5。 +3. **BootAgent 自己的状态还不认识「没有模型服务」这种情况。** 涉及 Agent 绑定、保存模型服务后的重新应用、配置识别、启动命令里的 `-m`、模型检测按钮,每一处都默认 Agent 背后有一个模型服务、一个 Key、一个模型。 + +## 2. CC Switch 的做法 + +参考:(README)。 + +- **内置官方预设**:Claude Code、Codex 等都有「Claude Official」「OpenAI Official」这类预设。切到它之后,需要用户重启 Agent,再走 Agent 自己的登录流程(Claude Code 的 `/login`、Codex 的 `codex login`)。CC Switch 不自己实现 OAuth。 +- **只替换连接字段**:端点、Key、模型、协议(Codex 另加推理强度)。插件、hooks、MCP 等不动。 +- **Codex 登录暂存**:CC Switch 切换时整份覆盖 `auth.json`。所以切到第三方时,它先把官方登录挪到 `codex-login-stash.json`,切回官方时再恢复。 +- **Claude 官方**:没有暂存,因为 Claude Code 的登录凭据不在 `settings.json` 里。 + +BootAgent 写 `auth.json` 时只合并 `OPENAI_API_KEY` 和 `auth_mode` 两个键,ChatGPT 的 `tokens` 一直留在原处(`internal/config/write.go:215`,ADR-008 的取舍)。所以不需要暂存文件,切回时把这两个键改回来即可。 + +## 3. 各 Agent 怎么切 + +### 3.1 第一批:Codex、Claude Code + +| | Codex(同时影响共用其配置的 ChatGPT 桌面版,`internal/desktopapp/registry.go:90`) | Claude Code | +| --- | --- | --- | +| BootAgent 现在写的 | `config.toml`:`model_provider = "bootagent"`、`model`、`model_reasoning_effort`、`[model_providers.bootagent]`(其中 `requires_openai_auth = true`),见 `write.go:173`、`:1048`
`auth.json`:`OPENAI_API_KEY`、`auth_mode = "apikey"`,见 `write.go:215` | `settings.json` 的 `env.ANTHROPIC_BASE_URL`、`env.ANTHROPIC_AUTH_TOKEN`、`env.ANTHROPIC_MODEL`,见 `write.go:227` | +| 切到官方要写的 | `config.toml`:删掉 3 个自有键和 `[model_providers.bootagent]` 表
`auth.json`:`auth_mode = "chatgpt"`,`OPENAI_API_KEY = null`,`tokens` 不动 | 删掉这 3 个 env 键,`env` 里其他键和文件里其他内容不动 | +| 登录凭据在哪 | 由 `cli_auth_credentials_store` 决定:`auth.json`(默认)或系统钥匙串 | macOS 钥匙串;Linux 和 Windows 上是 `~/.claude/.credentials.json`(Agent 自管,BootAgent 不读也不写) | +| 判断是否已登录(本机命令,不发计费请求) | `codex login status` | `claude auth status --json` | +| 登录命令(在终端里执行,会打开浏览器) | `codex login`;无浏览器时用 `codex login --device-auth` | `claude auth login`(默认使用 Claude 订阅,`--console` 改用 Console 计费) | +| 切换后还会覆盖官方登录的东西 | 待核实:shell 里的 `OPENAI_API_KEY`,以及管理员强制的 `forced_login_method` | shell 里的 `ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN`,以及 `settings.json` 的 `apiKeyHelper`,会优先于订阅登录。BootAgent 能识别这些,但不应该去改 | + +上表中的登录命令和子命令是在本机核对的:Codex CLI 0.153.4、Claude Code 2.1.223。凭据存储方式参考 Codex 官方文档()。 + +### 3.2 第二批:需要先调研 + +- **Claude 桌面版**:BootAgent 写的是一个自有的第三方推理 profile(`internal/config/claude_desktop.go`)。切回官方应该是取消激活这个 profile,而不是删除它。需要先确认桌面版切回自身账号的开关在哪个文件里。 +- **OpenCode、Kilo CLI**:这两个 Agent 都有自己的 `auth login`,可以登录多家服务,凭据存在各自的数据目录。「官方」对它们来说不是一个固定的选项,而是从它们自己已登录的服务里选一个。建议放在后面做,或者不做。 +- **Kimi Code**:有 Kimi 账号登录。它和 Kimi Code 桌面版共用配置(`registry.go:154`)。需要先确认登录后的凭据和 `default_model` 是什么关系。 +- **其他 Agent**(Aider、OpenClaw、Hermes、Pi、DeepSeek Harness):没有统一的官方账号登录,这次不做。 + +## 4. BootAgent 里需要认识「官方登录」的地方 + +| 位置 | 现状 | 需要改成 | +| --- | --- | --- | +| `internal/app/agent.go:62` `activateAgentLocked` | 必须有 Key 和模型,否则报错;然后写入配置和绑定 | 新增一条独立的 `UseOfficialLogin(agentID)` 路径。不经过 Provider 解析,不要求 Key,也不检测模型 | +| `internal/profile/binding.go:113` | 绑定必须有 provider、base URL 和 model | 允许一种 `Auth: "official"` 的绑定,此时 base URL 和 model 可以为空,`Provider` 记为 `official` | +| `internal/app/provider.go:389` 重新应用 | 按 provider 或 profile 匹配,然后改写 Agent | 天然不会选中 `official` 绑定,但要加测试固定这一点,防止以后有人建了一个 ID 叫 `official` 的模型服务 | +| `internal/config/discovery.go:24`、`:42` | Codex 以有无 `[model_providers.bootagent]` 判断是否由 BootAgent 管理;Claude 以 3 个 env 键是否都有值判断 | 增加 `Official` 判断:
• Codex:没有 `model_provider`,且 `auth_mode` 不是 `apikey`
• Claude:没有这 3 个键
只返回布尔值,不返回任何凭据内容 | +| `internal/app/launch.go:57` | 从绑定读取模型,拼进启动命令 | 官方登录的绑定没有模型,命令里不带 `-m`,由 Agent 用自己的默认模型 | +| 前端:总览的 Agent 行、Agent 配置页 | 显示「模型服务 · 模型」,并提供检测模型按钮 | 显示「官方登录 · 已登录 / 未登录」。没有检测模型按钮(没有 Key,也不应发计费请求) | + +## 5. 先核实的风险:ChatGPT 令牌可能发给第三方 + +`[model_providers.bootagent]` 写的是 `requires_openai_auth = true`。按 Codex 的 schema,这个字段表示该模型服务「使用 OpenAI API Key 或 ChatGPT 登录令牌」,凭据从 `cli_auth_credentials_store` 指定的位置读取。 + +由此推测有两种情况会出问题: + +- 用户在 BootAgent 配置好 Codex 之后,自己又执行了 `codex login`,这会把 `auth_mode` 改回 `chatgpt`。 +- 用户的 Codex 用的是钥匙串存储(`cli_auth_credentials_store = "keyring"` 或 `auto`),根本不读 BootAgent 写的 `auth.json`。 + +这两种情况下,发往第三方 `base_url` 的请求带的可能是 ChatGPT 的访问令牌。第一种还会让 BootAgent 写入的 Key 失效。这一点需要先用一个本机抓包的假服务验证;如果属实,单独作为一个问题处理。 + +如果属实,Codex 的模型服务配置还提供另外两种传 Key 的方式,可以把 BootAgent 的 Key 和登录状态彻底分开。这样「切回官方」就真的只是删掉 `model_provider`: + +- `experimental_bearer_token`:Key 写进 `config.toml`。Codex 的说明里不推荐,字段名也标着 experimental。 +- `auth`:由一个命令输出 Key。这要求 BootAgent 提供一个可执行的取 Key 命令。 + +这会推翻 ADR-008 中 Codex 那一行,所以需要写一份新的 ADR,不在本方案里直接改。在此之前,本方案按现状设计:切换时改写 `auth_mode`。 + +## 6. 交互 + +- **入口**:Agent 配置页的配置模版列表最上方,固定一项「官方账号登录」,副标题分别为「使用 ChatGPT 账号」和「使用 Claude 订阅」。它不是一个配置模版,不出现在配置模版页,也不能被编辑或删除。 +- **应用后**: + - 已登录时,回执条显示「Codex 已改用官方登录」。 + - 未登录时,回执条为警告「Codex 已改用官方登录,还需要登录」,并带动作按钮「去登录」。点击后用设置里选择的终端执行登录命令;终端关闭后重新检查登录状态。 +- **总览行**:标签为「官方登录」。未登录时行内显示可点击的「未登录」标记,与「启动失败」的标记用法一致。 +- **切回第三方**:照常选一个配置模版应用。Codex 会再次把 `auth_mode` 写成 `apikey`,ChatGPT 的 `tokens` 保留,下次切回官方时不需要重新登录。但如果令牌在这段时间里过期了,仍然要重新登录,这时用上面的登录状态检查兜底。 +- **不做的事**:BootAgent 不读取、不保存、不导出任何 OAuth 令牌;迁移包(TransferPage)不包含官方登录凭据;不从 BootAgent 内部发起 OAuth。 + +## 7. 实施顺序 + +1. **核实 §5**:用本机假服务观察 `auth_mode = "chatgpt"` 和钥匙串存储两种情况下,发往 `bootagent` 模型服务的 `Authorization` 头。结论记入 `docs/internal/`。 +2. **后端**: + - 新增 `WriteCodexOfficial`、`WriteClaudeOfficial`,并配 golden 测试:只删除自有键,其他内容逐字节不变。 + - 新增 `UseOfficialLogin`,以及 `official` 绑定和识别规则。 + - 新增 `OfficialLoginStatus`,它执行上表里的本机状态命令并设置超时,只返回「已登录 / 未登录 / 无法判断」。 + - 新增 `LaunchOfficialLogin`,复用 `launch.go` 的终端选择。 +3. **前端**:Agent 配置页的固定项、回执条和「去登录」、总览行标签。 +4. **第二批 Agent**:按 §3.2 逐个调研后再决定做不做。 diff --git a/docs/public-site-operations.md b/docs/public-site-operations.md index bcfe8fcd..c70b8603 100644 --- a/docs/public-site-operations.md +++ b/docs/public-site-operations.md @@ -29,18 +29,23 @@ must not influence Agent rank, compatibility conclusions, default selection, or tests. That boundary belongs to this repository; the site only displays the result. **Those fields are not read by the application, and that is enforced by omission.** -`relationship`, `disclosure`, `referral_url`, `order`, and `protocols` have no counterpart -in `providerFileEntry` (`internal/catalog/providers.go`), so `json.Unmarshal` discards -them. Filling in `referral_url` therefore changes nothing in the desktop app or the CLI — -it is published for the site to render, and the "get a key" button will keep opening -`key_management_url` (falling back to `home`) regardless. Routing users through a referral -link would be a product decision requiring the field to be parsed and given an explicit -precedence, not a matter of setting a value here. - -The reverse also holds: `key_management_url` and `default_model` are read by the app. They -are not disclosure fields and are not subject to the paragraph above; `default_model` is -the model pre-filled for a user who has not chosen one, so changing it changes what gets -written into a real Agent configuration. +`relationship`, `disclosure`, and `referral_url` have no counterpart in `providerFileEntry` +(`internal/catalog/providers.go`), so `json.Unmarshal` discards them. Filling in +`referral_url` therefore changes nothing in the desktop app or the CLI — it is published +for the site to render, and the "get a key" button will keep opening `key_management_url` +(falling back to `home`) regardless. Routing users through a referral link would be a +product decision requiring the field to be parsed and given an explicit precedence, not a +matter of setting a value here. + +The reverse also holds: `key_management_url`, `default_model`, `order`, and `protocols` are +read by the app. They are not disclosure fields and are not subject to the paragraph above; +`default_model` is the model pre-filled for a user who has not chosen one, so changing it +changes what gets written into a real Agent configuration. `order` is the display order of +the built-in Providers. `protocols` records how far each protocol has been confirmed on a +Provider's endpoint: when the protocol an Agent needs is anything other than +`implementation-supported` while `openai` is, the setup wizard offers compatibility mode +before any request is sent. It only ever adds that optional hint; it never hides a Provider, +and connection tests still decide what actually works. **Changing a lock file does not change the site.** The site vendors `agents.lock.json` and `providers.lock.json` into its own `data/` directory, refreshed from release tags diff --git a/docs/ui-friendliness-plan.md b/docs/ui-friendliness-plan.md new file mode 100644 index 00000000..28a5cc6b --- /dev/null +++ b/docs/ui-friendliness-plan.md @@ -0,0 +1,175 @@ +# 界面友好度改造方案:少一点小字,让新手看得懂 + +> 状态:已确认,按阶段实施。起草于 2026-10-10,代码核对至 `main`(`3d335e0`)。 +> 文中的现状均带本仓库 `file:line`;字号统计来自 `frontend/src/styles/app.css`。 + +## 1. 目标与非目标 + +目标:第一次打开 BootAgent 的人,不需要懂配置文件、环境变量和 API 协议,也能看懂每个页面在说什么、下一步该点哪里。 + +非目标: + +- **不换配色和字体。** [ADR-010](decisions/ADR-010-visual-restyle-swiss-blueprint.md) 的配色改版这次不做(2026-10-10 决定)。扫描器关于配色的提示(见 §3.5)记录在案,不处理。 +- 不删功能,不改后端行为。技术细节从「默认展示」改为「展开可见」,信息一条不丢。 +- 不弱化安全提示。[ADR-011](decisions/ADR-011-provider-keys-for-multimodal-skills.md) 要求安装确认告知 Key 对 Agent 可见,这类提示只缩短,不删除。 + +## 2. 原则 + +1. **默认只回答三个问题**:这是什么,现在什么状态,下一步点哪里。 +2. **技术细节收进「详情」**:文件路径、环境变量名、协议名、Skill ID、程序路径、安装目录,默认折叠在每一项自己的「详情」里,开发者一键展开。不做全局的「开发者模式」开关:开关藏得深,新手不会开,老手每次都要找。 +3. **一件事一个状态**:同一位置不并排两个徽标。能用一个词说清的状态,不写成一句话。 +4. **一句话说清,长解释收起来**:说明文字最多一句,超过的部分放进「了解详情」。 +5. **用任务语言,不用实现语言**:说「让 Codex 也能用这个模型服务」,不说「把 Responses 请求转换为 Chat Completions」。 +6. **风险和花钱的事必须看得见**:删除、覆盖、计费、Key 可见性,保留在默认视图,压成一句。 + +## 3. 现状 + +### 3.1 字号 + +没有统一的正文字号:页面说明和区块说明各自写 13px(`frontend/src/styles/app.css:202`、`441`),按钮也是 13px。`app.css` 中另有 127 处小于 13px 的声明: + +| 字号 | 声明数 | 典型用途 | +| --- | --- | --- | +| 10px | 13 | `.provider-title small`、`.profile-title small`、`.runtime-fact small`、`.agent-manage-identity-copy small` | +| 11px | 47 | 路径 `code`、徽标、元信息 | +| 12px | 67 | 提示文字、下拉框、说明 | + +中文在 12px 以下明显难读,10px 已经低于大多数桌面应用的下限。 + +### 3.2 默认展示的技术细节 + +全部文案共 964 条,其中 88 条直接出现路径、变量名、协议名或「配置文件」等实现概念。主要位置: + +- 配置文件路径:`frontend/src/components/AgentManageRow.tsx:99`(「配置文件当前指向 {url}」)、`frontend/src/components/DesktopAppSection.tsx:226`(「与 {name} 共用配置文件 {path}」「配置文件:{path}」)。 +- 程序路径:`frontend/src/components/AgentManageRow.tsx:449`。 +- 运行时安装目录与 PATH:`frontend/src/components/RuntimeSection.tsx:145`。 +- 多模态:Skill ID(`frontend/src/components/MultimodalSection.tsx:334`)、环境变量名与私有 Key 文件路径(安装弹窗)、笔记路径、说明文件路径(`MultimodalSection.tsx:617`)。 +- 模型服务表单:「OpenAI 兼容 Base URL」「Anthropic 兼容 Base URL」。 +- 协议适配:约 30 条文案直接使用 Responses、Chat Completions、Anthropic Messages。 + +### 3.3 说明过长 + +- 多模态安装弹窗:4 段说明(Key 写入位置、私有文件、Node 版本与计费、探索模式三段)。 +- 卸载确认、全量清理、npm 环境卸载:整段长句。 +- 协议适配页的开头说明:两段,各三到四句。 +- 多模态账号行:「证据来源」与「安装状态」两个徽标并排。 + +### 3.4 信息最密的页面 + +按含辅助文字的元素数(`` 与 note/hint/detail 类): + +| 位置 | 数量 | +| --- | --- | +| `frontend/src/pages/MarketplaceDetailPage.tsx` | 57 | +| `frontend/src/components/AgentManageRow.tsx` | 14 | +| `frontend/src/components/SkillhubDetailSection.tsx` | 8 | +| `frontend/src/components/MultimodalSection.tsx` | 8 | + +### 3.5 「AI 味」扫描基线 + +用 `avoid-ai-design` 的扫描器(见 §7)对 `frontend/src` 的结果:P0 0 条,P1 20 条,P2 3 条。 + +| 编号 | 条数 | 内容 | 处理 | +| --- | --- | --- | --- | +| I3 | 18 | 常见 Lucide 图标组合;`Sparkles` 用作 Skills 图标(`SkillsPage.tsx:149`、`TransferPage.tsx:416`)和推荐按钮(`MarketplacePage.tsx:725`) | 第 1 阶段换掉 `Sparkles`;`Check` 等通用图标保留 | +| SD4 | 1 | 全大写加字距的标签(`app.css:2077`、`3607`、`3671`) | 第 2 阶段改为常规大小写 | +| SD4d | 1 | 用「·」拼接的元信息(`TaskCenter.tsx:39`、`52`、`53`) | 第 1 阶段改为分行或标签 | +| SD5 | 1 | `PageScaffold.tsx:47` 标题旁的徽标 | 误报:是独立徽标,不是标题里的强调词,保留 | +| C8 | 1 | 主色与强调色色相过近(`tokens.css`) | 属于配色,本次不做 | + +扫描器只看代码能确定的部分。奶油底加赭红的配色属于视觉层面,扫描器看不出来,也不在本次范围。 + +## 4. 文案规则与用词表 + +规则: + +- 一条提示最多一句。需要第二句时,第二句以后放进「了解详情」。 +- 不在默认视图出现:文件路径、`~/`、环境变量名、协议名、Skill ID、哈希、程序路径。 +- 状态用短词:可以直接安装 / 需要先测试 / 暂不支持 / 已安装。 +- 按钮写动作:「安装」「测试连接」「去添加模型服务」,不写「确定」「继续」。 + +用词表(中文界面): + +| 现在 | 改为 | 说明 | +| --- | --- | --- | +| Base URL | 接口地址 | 字段旁给出示例占位 | +| OpenAI 兼容 Base URL | 接口地址(OpenAI 格式) | | +| Anthropic 兼容 Base URL | 接口地址(Anthropic 格式) | | +| 协议适配 | 兼容模式 | 说明写「让只认某种格式的 Agent 也能用这个模型服务」 | +| Responses / Chat Completions / Anthropic Messages | 不出现在默认视图 | 放进「详情」 | +| 配置文件 | 不出现在默认视图 | 需要时说「Agent 的设置」 | +| 运行时 | 运行环境 | 如 Node.js | +| 实测 | 测试 | 按钮仍提示可能产生费用 | +| 按模型名推断 / 模型服务声明 / 内置目录 | 不单独展示 | 并入一个状态,来源放进「详情」 | + +英文界面同步改写,原则相同。 + +## 5. 公共做法 + +### 5.1 「详情」折叠 + +`AgentManageRow` 已有 `agent-manage-details` 折叠,抽成一个公共组件,供所有卡片和行使用: + +- 默认收起,标题固定为「详情」。 +- 内容是键值列表:「设置文件」「程序位置」「安装目录」「接口地址」等,路径用等宽字体,可复制。 +- 键盘可操作,展开状态不跨页面保存。 + +### 5.2 「了解详情」 + +弹窗和说明里第二句以后的内容,用同一个小链接展开,展开后原地显示,不跳页。 + +### 5.3 字号层级(第 2 阶段) + +| 角色 | 字号 | +| --- | --- | +| 正文、表单、按钮 | 14px | +| 辅助说明 | 13px | +| 徽标、计数、等宽路径 | 12px(下限) | + +在现有 CSS 不变量测试旁加一条:`app.css` 与 `base.css` 中不得出现小于 12px 的字号。 + +## 6. 分阶段 + +每个阶段内,每个页面一个 PR,独立可回退。 + +### 第 1 阶段:信息层级(按新手路径) + +| 顺序 | 页面 | 主要改动 | +| --- | --- | --- | +| 1 | 总览、Agent 行(`AgentManageRow`、`DesktopAppSection`、`RuntimeSection`) | 路径、程序位置、安装目录进「详情」;「配置文件当前指向 {url}」改为「正在使用:{模型服务}」,有偏差时只提示「设置被其他程序改过」;卸载类确认压成一句加「了解详情」 | +| 2 | 配置向导(`setup/*`) | 每步一句说明;协议名移出默认视图 | +| 3 | 模型服务、配置模板 | 按用词表改字段名;示例占位;一条提示一句 | +| 4 | 多模态 | 账号行合并为一个状态徽标;安装弹窗压成「会使用你在 {服务} 的 Key,每次调用按价格计费」一句,其余进「了解详情」;Skill ID、环境变量、文件路径进「详情」 | +| 5 | 兼容模式(原协议适配) | 已扩大为动线改造(2026-10-12):在出问题的地方提出兼容模式——向导测试连接、Agent 页选模版、检测模型失败;命令行 Agent 一键开启(`ConfigureAgentWithConversion`);兼容模式页改为状态页;下拉框隐藏转换器条目并写明不可选原因 | +| 6 | Skills、MCP | 同上规则;`Sparkles` 换为与 Skill 含义相符的图标 | +| 7 | Marketplace 详情 | 元信息分组,次要字段进「详情」 | +| 8 | 设置、导入导出 | 同上规则 | + +### 第 2 阶段:字号和间距 + +按 §5.3 调整,并加 CSS 不变量测试;全大写标签改为常规大小写。 + +## 7. 工具 + +项目内安装了两个第三方 Skill,均固定版本,详见各自的 `VENDORED.md`: + +- `.claude/skills/anti-ui-slop/`(Apache-2.0,固定在 `github/awesome-copilot@82701c2`):做每个页面时加载一个对应的手册——第 1 阶段用 `reference/distill.md`(精简),收尾用 `reference/polish.md`。已移除付费 MCP 相关内容。 +- `.claude/skills/avoid-ai-design/`(MIT,固定在 `funboy322/avoid-ai-design@2b7c718`):以 `detect` 模式使用(只审查、不重写),并用其扫描器检查代码层面的问题: + +```bash +node .claude/skills/avoid-ai-design/scripts/detect.mjs --min=P1 frontend/src +``` + +配色相关的提示(C8 等)按 §1 不处理。扫描器目前不进 CI:它的大部分规则面向营销页,误报(如 §3.5 的 SD5)需要人工判断。 + +## 8. 验收 + +每个页面的 PR 都要满足: + +- 默认视图不出现路径、环境变量名、协议名、Skill ID。 +- 页面上每条提示不超过一句;风险和计费提示仍在默认视图。 +- 原有信息在「详情」或「了解详情」中都能找到。 +- 中英文文案同步。 +- `pnpm run test`、`pnpm run build` 通过;新增或更新的测试覆盖「默认不显示、展开可见」。 +- 用预览检查:计算后的字号、窄窗口(560px)下无横向溢出、深色模式。 +- 扫描器对改动文件不新增 P1。 diff --git a/docs/ui-interaction-plan.md b/docs/ui-interaction-plan.md new file mode 100644 index 00000000..30b73d8c --- /dev/null +++ b/docs/ui-interaction-plan.md @@ -0,0 +1,244 @@ +# 交互修复与操作反馈方案 + +> 状态:实施中,§5 第 1–5 步已完成(2026-10-12)。起草于 2026-10-12,代码核对至 `claude/compat-mode-flow` 工作区(基于 `3d335e0`)。 +> 本文只管「点了之后发生什么」:流程断点、失败处理和操作反馈。字号、术语和信息层级见 +> [界面友好度改造方案](ui-friendliness-plan.md),两份方案互不覆盖;重叠处(10px 错误小字)以本文 §3 的做法为准。 + +## 1. 问题清单 + +编号供 PR 引用。「反馈」列标 ✓ 的条目由 §3 的反馈方式一并解决,不单独修。 + +### P0:首次使用的主线断掉 + +| 编号 | 问题 | 位置 | 修复方向 | 反馈 | +| --- | --- | --- | --- | --- | +| I-01 | 点「开始安装」后立刻跳到任务页,「下一步命令」、连接测试警告、「前往 Claude Desktop 下载」都只渲染在激活页,用户永远看不到;任务页没有「启动」按钮,标题重复为「正在安装 · 安装 X」 | `frontend/src/pages/ActivationPage.tsx:253`、`:491`、`:496`、`:509`;`frontend/src/pages/InstallTaskPage.tsx:48` | 安装期间留在激活页,任务页只用于从任务中心回看进度;完成后主按钮为「启动 {Agent}」,「进入总览」降为次要 | | +| I-02 | 向导里 Key 未保存前「测试连接」不可用且无说明;兼容模式只在测试失败后提出,不测就会在 Agent 包装完后配置失败,失败页只有必然再失败的「重试」 | `frontend/src/pages/ProviderKeyPage.tsx:28`、`:52`、`:209`;`internal/app/install.go:442` | 向导测试复用 `draft: true`(`frontend/src/pages/ProvidersPage.tsx:170`),允许用未保存的 Key 测试;激活失败且错误可由兼容模式解决时,行内给出「改用兼容模式」 | | + +### P1:启动与失败处理 + +| 编号 | 问题 | 位置 | 修复方向 | 反馈 | +| --- | --- | --- | --- | --- | +| I-03 | 命令行 Agent 启动成功无任何反馈;后端返回的实际终端、Web 地址被丢弃;桌面 Agent 却会提示「已打开」,两边不一致 | `frontend/src/components/AgentManageRow.tsx:189`;`internal/app/launch.go:20`;`frontend/src/components/DesktopAppSection.tsx:100` | 读取 `LaunchAgentResult`,终端被替换时说明用了哪个 | ✓ | +| I-04 | 未配置模型服务的 Agent 也能直接启动,到第一句对话才报错 | `frontend/src/components/AgentManageRow.tsx:179` | 未配置时主按钮改为「先配置」,或在启动目录弹窗中提醒 | | +| I-05 | 行内失败 10px 单行截断、无悬停全文、不可关闭;无中文文案的错误码直接显示后端英文(含测试**成功**消息);52 处只取 `.message`,丢掉了 `hint` | `frontend/src/styles/app.css:1407`;`frontend/src/backend/errors.ts:59`;`internal/app/launch.go:77`;`internal/app/terminal.go:223`;`internal/provider/client.go:393`;`frontend/src/pages/ModelSelectionPage.tsx:17` | 失败统一走 §3.3;补齐常见错误码文案;成功消息不再透传后端原文 | ✓ | +| I-06 | 模型服务页编辑模式忽略 `returnTo`,从向导去改 Key 后回不去;侧边栏无向导入口,「安装 Agent」会重置向导 | `frontend/src/pages/ProvidersPage.tsx:120`、`:228`;`frontend/src/components/NavigationSidebar.tsx:8`;`frontend/src/pages/EnvironmentOverviewPage.tsx:24` | 编辑保存与取消都遵守 `returnTo`;向导未完成时总览给「继续设置」 | | +| I-07 | 应用桌面 Agent 配置丢掉后端的「需要重启」说明;应用后跳回总览无任何确认 | `frontend/src/pages/AgentProfilePage.tsx:372`、`:396`;对照 `frontend/src/pages/ActivationPage.tsx:239` | 读取 `restart`,跳转后用 §3.3 告知 | ✓ | +| I-08 | MCP、Skills 页请求失败几乎全部静默:读取失败显示为「尚未发现」;编辑失败无反应;「应用更改」无忙碌态可重复点、无结果;Skills 删除先从列表移除再发请求,失败后仍显示已删 | `frontend/src/pages/MCPPage.tsx:121`、`:124`、`:137`、`:141`、`:148`;`frontend/src/pages/SkillsPage.tsx:89`、`:96` | 区分「读取失败」与「为空」;应用期间禁用;删除等请求成功后再改列表 | ✓ | + +### P2:易误操作或困惑 + +| 编号 | 问题 | 位置 | 修复方向 | 反馈 | +| --- | --- | --- | --- | --- | +| I-09 | 勾选「记住此 Agent 的目录」后每次仍弹目录框;目录为空时点「启动」无反应 | `frontend/src/components/AgentManageRow.tsx:199`、`:217` | 已记住则直接启动,目录可在「更多」里修改;空目录禁用「启动」并说明 | | +| I-10 | 配置页模型框失焦即保存,且会改动共用该配置模版的其他 Agent,无提示、无成功反馈 | `frontend/src/pages/AgentProfilePage.tsx:182`、`:597` | 共用时在模型框下注明「也会改动 {agents}」;保存结果走 §3.2 | ✓ | +| I-11 | 无说明的禁用或回跳:配置模版 ID 重复时保存变灰;确认页无 Key 时静默跳回;切换模型服务静默清空已粘贴的 Key | `frontend/src/pages/AgentProfilePage.tsx:164`;`frontend/src/pages/ReviewPage.tsx:44`;`frontend/src/pages/ProviderKeyPage.tsx:67` | 字段下给出原因;回跳前说明;切换前若有未保存 Key 先确认 | | +| I-12 | 总览读取失败时写「请刷新后重试」却无刷新按钮;两处「按引导安装…」空状态看似可点实为文字 | `frontend/src/pages/EnvironmentOverviewPage.tsx:37`、`:117`、`:153` | 加「重试」;空状态改为按钮 | | +| I-13 | 离开 MCP/Skills 页时不清除草稿状态,退出应用时会为已丢弃的草稿弹「未应用的更改」 | `frontend/src/pages/MCPPage.tsx:127`;`frontend/src/pages/SkillsPage.tsx:90` | effect 卸载时上报 `dirty=false`;站内离开有草稿时先确认 | | +| I-14 | 命令行 Agent 列表无简介(只在图标 title 里);「待安装」读作已排队 | `frontend/src/components/AgentRow.tsx:21`、`:34` | 显示一行简介;状态改为「未安装」 | | + +### P3:细节 + +| 编号 | 问题 | 位置 | +| --- | --- | --- | +| I-15 | 已安装的 Agent 在确认页仍写「开始安装」 | `frontend/src/pages/ReviewPage.tsx:60` | +| I-16 | 模型服务步的「返回」跳过「选择配置模版」;步骤条不可点击回退 | `frontend/src/pages/ProviderKeyPage.tsx:145`;`frontend/src/components/SetupStepper.tsx:39` | +| I-17 | 卸载实例弹窗「继续卸载」不是危险样式 | `frontend/src/components/AgentManageRow.tsx:392` | +| I-18 | 运行环境任何失败都提示「官方源和镜像都已尝试过」 | `frontend/src/components/RuntimeSection.tsx:96` | +| I-19 | 中文界面残留英文:「{n} variant」「MCP Registry」「Base URL」 | `frontend/src/pages/SkillsPage.tsx:151`;`frontend/src/pages/MCPPage.tsx:200`;`frontend/src/pages/ReviewPage.tsx:84` | + +## 2. 操作反馈:现状 + +成功和失败都写进正文: + +| 形式 | 数量 | 例 | +| --- | --- | --- | +| `notice` 块(插在正文顶部或中间) | 18 处 | `DesktopAppSection.tsx:147`、`AgentProfilePage.tsx:438`、`ProviderKeyPage.tsx:219` | +| 错误段落(`agent-manage-error`、`settings-field-error` 等) | 13 处 | `ProvidersPage.tsx:392`、`ConversionPage.tsx:140` | +| 行内 10px 小字 | Agent 行 | `AgentManageRow.tsx:344` | +| 全局横幅 | 1 处 | `AppWindow.tsx:15`(`app.css:170` 的注释记录了它曾把页脚按钮挤出窗口) | + +由此带来四个问题: + +1. **挤压布局。** 提示出现时正文整体下移,用户正要点的按钮会跟着移走;消失时再移回来。 +2. **出现在别处。** 提示插在页面顶部,按钮在页脚或列表深处,用户看不到结果。 +3. **不会消失。** 成功提示大多一直留着,直到下一次操作或离开页面(`DesktopAppSection` 的 4 秒自动消失是唯一例外)。 +4. **跨页即丢。** 「应用」后跳回总览,提示属于上一页的组件状态,跟着一起卸载(I-07)。 + +## 3. 设计 + +### 3.1 原则 + +与 [ADR-010](decisions/ADR-010-visual-restyle-swiss-blueprint.md) 的「安静的表面、扁平、1px 线代替阴影」以及友好度方案的「一句话」一致: + +1. **不改变布局。** 反馈只在预留的位置或浮层上出现,正文不因它移动一个像素。 +2. **结果出现在视线所在处。** 优先在被点的按钮上,其次在固定位置。 +3. **一句话,十八个字以内。** 原因和建议收进「详情」,需要时再展开。 +4. **成功自己消失,失败等人处理。** 失败一律不自动消失。 +5. **一个结果只说一次。** 按钮已经表达了成功,就不再弹提示。 + +### 3.2 四个去处 + +| 结果 | 去处 | 停留 | +| --- | --- | --- | +| 单个按钮触发、结果立刻可见的**成功** | 按钮原位(§3.2.1) | 1.6 秒后复原 | +| 成功的影响在别处,或发生了跳转 | 回执条(§3.3) | 3 秒,鼠标悬停时暂停 | +| 任何**失败** | 回执条;属于某个 Agent 的失败另在该行留状态标记(§3.4) | 直到关闭或重试成功 | +| 耗时任务(安装、下载、更新、迁移) | 任务中心(不变) | 直到关闭 | + +另外两类不属于「反馈」,保持现有方式: + +- **需要用户做决定的提示**仍留在正文:兼容模式提议、缺少运行环境、模型检测结果。它们本身就是页面内容,挪走反而找不到。这类提示只允许这三种,新增需在本文登记。 +- **确认**(删除、卸载、迁移)继续用系统原生对话框(`frontend/src/state/confirmDelete.ts`)。 + +#### 3.2.1 按钮原位 + +按钮宽度在首次渲染时锁定,后面三个状态都不改变宽度: + +```text + [ ▶ 启动 ] → [ ◌ 启动 ] → [ ✓ 已打开 ] → [ ▶ 启动 ] + 空闲 进行中 成功 1.6s 复原 +``` + +- 失败时按钮直接复原,原因交给回执条。不做抖动或变红:按钮变红会被误读为危险操作。 +- 文字由调用方给出,限四个字以内:「已打开」「已保存」「已应用」「已刷新」。 +- 按钮旁放一个视觉隐藏的 `role="status"` 区域,供读屏软件播报。 + +适用于:启动、打开桌面 Agent、保存模型服务(未改动其他 Agent 时)、刷新状态、设置页的各项保存。 + +### 3.3 回执条 + +一个全局浮层(下称「回执条」),挂在 `App` 层(与 `TaskCenterProvider` 同级),所以跨页跳转后仍在。 + +**位置**:内容区右上角(2026-10-12 确认)。这是桌面应用通知出现的位置,符合用户预期。 + +- 上沿贴在页头分隔线下方 12px,右沿与正文右边距对齐(42px)。不压页头,所以向导页右上的步骤条不受影响。 +- 覆盖正文右上角的一小块,不遮挡页脚按钮、侧边栏和任务中心。 +- 窗口宽度小于 560px 时,左右各留 16px 横向铺满。 + +```text +┌ sidebar ┬───────────────────────────────────────────────────────┐ +│ │ 环境总览 [刷新] [安装] │ +│ ├───────────────────────────────────────────────────────┤ +│ │ ┌──────────────────────────────────────┐│ +│ │ ┃ ✕ 无法启动 Claude Code 详情 重试 × ││ +│ │ └──────────────────────────────────────┘│ +│ │ Codex 团队默认 · PPIO · gpt-5 [配置][启动] │ +│ │ Claude Code 无配置模版 · 无模型服务 [配置][启动] │ +│ │ │ +│ ├───────────────────────────────────────────────────────┤ +│ 任务中心 │ 页脚按钮 │ +└─────────┴───────────────────────────────────────────────────────┘ +``` + +**样式**: + +- 单行,最大宽度 420px;窗口宽度小于 560px 时左右各留 16px。 +- `--window-bg` 底,1px `--border` 边,左侧 3px 状态色条(`--green` / `--red` / `--orange` / `--info`),圆角 `--radius-control`。不用阴影和模糊(Linux 的 WebKitGTK 不适合模糊效果)。 +- 文字 13px(友好度方案中的辅助说明层级),图标 16px。 +- 浅色与深色只换 token,不写死颜色。 + +**结构**:`图标 · 一句话 · 详情(有详情时) · 最多一个动作 · 关闭`。 + +- 动作只能是「重试」「查看」「撤销」之一。点击动作会先关闭回执条再执行;重试用同一个 key 报告结果。 +- 「详情」在回执条下方展开为小卡片,内容是 `describeFailure` 给出的原因、建议,以及错误码。正文依旧不动。这样做同时解决了 I-05 中被丢掉的 hint。 + +**时序**: + +- 进入:160ms 淡入,同时下移 4px;`prefers-reduced-motion` 下不做动画。 +- 成功:3 秒后消失,鼠标悬停或键盘聚焦时暂停计时。 +- 失败:不自动消失。 +- 同时只显示一条。新消息与当前消息同 key(如 `launch:codex`)时直接替换;不同 key 的排队,最多排 3 条。未关闭的失败不会被后来的成功顶掉;排在失败后面的成功如果等待超过 3 秒就丢弃,免得关掉失败后冒出一条过时的「已保存」。 + +**无障碍**: + +- 播报区域常驻 DOM,内容为空也存在,避免首次插入时读屏软件漏报。 +- 成功用 `role="status"`,失败用 `role="alert"`。 +- 不抢焦点;回执条获得焦点时,按 Esc 关闭。 + +**文案预算**(主句十八个字以内,英文约 40 个字符): + +| 场景 | 现在 | 改为 | +| --- | --- | --- | +| 启动失败 | 行内 10px:`Invalid launch directory: /Users/…/proj`(截断) | 「无法启动 Claude Code」·详情 → 「启动目录不存在」+ 完整路径 | +| 终端被替换 | 无 | 「已用「终端」打开,iTerm2 未安装」 | +| 保存模型服务并重新应用 | 列表上方绿框「应用完成 已重新应用到 Codex、Claude Code」 | 「已更新 2 个 Agent」·查看 | +| 重新应用部分失败 | 红色段落:「Codex 重新应用失败:…」 | 「Codex 未能更新」·详情 | +| 应用配置模版(跳回总览) | 无 | 「Codex 已改用「团队默认」」 | +| 桌面 Agent 需重启 | 无(I-07) | 「重启 Claude Desktop 后生效」(失败级别:不自动消失) | +| MCP 应用更改 | 无 | 「已同步 3 个 MCP 服务器」/「2 个未同步」·详情 | +| 连接测试成功 | `OpenAI Chat Completions connection test passed.` | 保持在测试按钮旁的状态位(见 §3.5),文案「连接正常」 | + +### 3.4 Agent 行的状态标记 + +属于某个 Agent 的失败(启动、更新、卸载),除了弹出回执条,还要在该行留下记号,因为用户可能已经关掉了回执条: + +- 复用 `agent-manage-meta` 中已有的状态位(`AgentManageRow.tsx:371`),显示一个固定尺寸的标记,如「启动失败」,取代 10px 小字行。 +- 点击标记弹出与回执条「详情」相同的小卡片;该 Agent 下一次操作成功后,标记自动清除。 +- 与状态灯计划的圆点方向兼容:圆点落地后,这里改为红点加悬停卡片。 + +### 3.5 原地状态位(表单内) + +「测试连接」「检测模型」这类结果本身就是表单的一部分,继续留在按钮旁,但要预留固定高度。目前 `ConnectionStatus` 的「尚未测试连接」已经起到占位作用;失败时如果有多行细节(按协议分列),只显示一行摘要,其余收进「详情」。 + +字段校验错误显示在对应字段下方,并预留一行高度。按钮变灰时,用 `title` 和 `aria-describedby` 说明原因(I-11)。 + +### 3.6 迁移映射 + +| 现有位置 | 改为 | +| --- | --- | +| `AgentManageRow` 启动、更新、卸载的 `failure` 与 `taskFailure` 小字 | 回执条 + 行状态标记 | +| `DesktopAppSection.tsx:147`、`:148`(含 4 秒自动消失的「已打开」) | 按钮原位;失败走回执条 | +| `ProvidersPage.tsx:392`、`:396` | 回执条 | +| `ProfilesPage`、`AgentProfilePage.tsx:438` 的保存与应用失败 | 回执条 | +| `ConversionPage.tsx:140` | 回执条 | +| `SettingsPage` 各 `*Failure` 段落 | 按钮原位 + 回执条 | +| MCP、Skills 的应用与导入(含 `SkillsPage` 的 `message`) | 回执条 | +| `RuntimeSection`、`RuntimePrompt` 的下载失败 | 保持:任务中心 + 原位(属于任务) | +| `ProviderKeyPage` 兼容模式提议、`RuntimePrompt`、`ModelCheckNotice` | 保持在正文(需要决策) | +| `AppWindow.tsx:15` 迁移横幅 | 改为一次性回执条,失败级别(不自动消失),动作为「详情」 | + +## 4. 接口草案 + +```ts +// frontend/src/state/FeedbackContext.tsx +type FeedbackTone = "success" | "failure" | "warning"; +interface FeedbackAction { label: string; run: () => void | Promise } +interface FeedbackInput { + key?: string; // 同 key 替换,如 `launch:${agentId}` + tone: FeedbackTone; + message: string; // 主句,≤ 18 字 + detail?: string; // 「详情」卡片正文 + action?: FeedbackAction; +} +const feedback = useFeedback(); +feedback.show(input); +// 失败的快捷写法:内部调用 describeFailure,message → 主句,hint 与错误码 → detail +feedback.failure(error, t("无法启动 {name}", { name }), { key, action }); +``` + +```tsx +// 按钮原位:调用方返回 Promise,成功后显示 doneLabel,失败时复原并交给 feedback.failure + +``` + +`failureLine` 与 `.message` 的 52 处调用,凡是把结果展示给用户的,逐页改用 `feedback.failure`。只用于判断错误码的调用保持不变。 + +## 5. 实施顺序 + +1. `FeedbackProvider`、回执条、`ActionButton` 以及它们的单元测试(不改任何页面)。**已完成**:`frontend/src/state/FeedbackContext.tsx`、`frontend/src/components/FeedbackViewport.tsx`、`frontend/src/components/ActionButton.tsx`;`PageScaffold` 渲染回执条,`App` 挂载 Provider。 +2. 总览:Agent 行与桌面 Agent(I-03、I-05、§3.4),同时修 I-07 的跳转后提示。**已完成**:两类「启动」改为 `ActionButton`,命令行 Agent 的按钮在目录弹窗确认后才进入成功态,取消不算成功;启动、更新、卸载、安装失败在行内只留可点击的标记,点开即重现回执条;终端被替换时给出警告回执并提供「去设置」;`DesktopAppSection` 去掉了正文里的成功与失败块和 4 秒计时;配置页应用后在总览给出回执,桌面应用需要重启时改为不自动消失的警告。后端 `LaunchResponse` 没有 Web 地址字段,Web 类 Agent 只确认「已打开」。I-05 的错误码中文文案仍待第 3 步一并补齐。 +3. 模型服务、配置模版、兼容模式、设置页。**已完成**:四个页面的保存、删除、应用、检测失败都改为回执条,正文里的错误段落和「应用完成」块已移除;保存结果统一由 `frontend/src/state/saveReceipt.ts` 生成(「已保存,N 个 Agent 已更新 / 未能更新」,涉及的 Agent 在「详情」里),配置页改模型时因此能看到同时改动了哪些 Agent(I-10 的提示部分);作为「应用」「检测模型」前置步骤的保存不单独报成功。设置页各控件自己显示保存后的值,只在失败时回滚并给回执条。兼容模式读取失败的回执条带「重试」。I-05:后端新增 `LAUNCH_DIRECTORY_INVALID`、`TERMINAL_NOT_FOUND`、`TERMINAL_LAUNCH_FAILED` 三个错误码并配中文文案;连接测试成功不再显示后端英文句子;模型列表的状态由结构化字段生成(`modelListMessage`),并从字段上方的提示块移到字段下方的固定状态行。向导的连接模型服务页仍用正文提示,随 I-02 一起改。 +4. MCP、Skills(与 I-08 的失败处理一起修)。**已完成**:两页的扫描失败给回执条并带「重试」,空状态改为「没能读取…」而不是邀请用户新增第一个;MCP 打开编辑失败给回执条,「保存草稿」在 ID 与命令或 URL 填全前禁用;「应用更改」「应用 Skills」应用期间转圈并禁用,结果由 `frontend/src/state/applyReceipt.ts` 统计每个 Agent 的结果(「已同步 N 个 MCP 服务器」/「N 项未能应用」,原因在「详情」里)。Skills 删除改为后端确认后才从列表移除,失败时仍显示「待删除」可重试。导入结果从标题下的一行字改为回执条;后端 `SkillService.PreviewImport` 在用户关闭文件选择框时返回空预览而不是错误,前端据此不提示任何内容。 +5. 删除不再使用的 `notice` 样式分支,以及 `agent-manage-error`、`agent-manage-applied`。**已完成**:`agent-manage-error`、`agent-manage-applied` 已删除(向导连接模型服务页最后一处保存失败也改为回执条);`notice` 的四个色调仍被 §3.6 中保持在正文的提示使用,未删。`AppWindow` 的迁移横幅按 §3.6 改为一次性回执条(失败为失败级别,成功迁移为警告级别,原文在「详情」里),`.app-migration-notice` 已删除。 + +I-01、I-02 不依赖本方案,可以先行。 + +## 6. 验收 + +- 正文中不再出现成功提示;失败提示只出现在回执条、行状态标记或 §3.5 的预留位上。 +- 正文因反馈而移动为零:在预览中对比触发前后主按钮的 `getBoundingClientRect()`,差值为 0。 +- 回执条:成功 3 秒后消失、悬停时暂停;失败不自动消失;跨页跳转后仍在;同 key 替换。 +- 深色模式、`prefers-reduced-motion`、560px 窄窗口下均检查一遍。 +- 中英文文案同步;主句不超过 18 个字。 +- `pnpm run test`、`pnpm run build` 通过。 diff --git a/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/app/index.ts b/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/app/index.ts index f1594f45..ac238d73 100644 --- a/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/app/index.ts +++ b/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/app/index.ts @@ -16,6 +16,9 @@ export type { DesktopAgentProfileResult, DesktopAgentStatus, DetectedConfig, + FirstTaskAgent, + FirstTaskRequest, + FirstTaskResult, InstallRuntimeResult, InstalledMultimodal, MCPAgentApplyResult, diff --git a/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/app/models.ts b/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/app/models.ts index 4415da2c..219b6ceb 100644 --- a/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/app/models.ts +++ b/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/app/models.ts @@ -111,7 +111,19 @@ export interface ConversionConfig { "enabled": boolean; "listen": string; "has_api_key": boolean; + + /** + * TargetProfile is where Agents still on the shared converter entries are + * forwarded. New Agents get a route of their own instead. + */ "target_profile": string; + + /** + * Routes maps an Agent to the Chat Completions Profile its requests are + * forwarded to. Written by ConfigureAgentWithConversion; SaveConversion + * keeps what is stored. + */ + "routes": { [_ in string]?: string } | null; "anthropic_model": string; "responses_model": string; "chat_model": string; @@ -214,6 +226,29 @@ export interface DetectedConfig { "unreadable": string | null; } +export interface FirstTaskAgent { + "id": string; + "name": string; +} + +export interface FirstTaskRequest { + "agent_id": string; + "locale": string; +} + +/** + * FirstTaskResult describes a run that started. OK is false when the Agent + * failed or wrote nothing, and Directory is empty then: an empty directory is + * removed rather than reported. + */ +export interface FirstTaskResult { + "agent_id": string; + "ok": boolean; + "directory": string; + "files": string[] | null; + "log": string; +} + /** * InstallRuntimeResult reports what the bootstrap did. PathUpdated is separate * from Installed because an already-downloaded runtime may still need its @@ -779,6 +814,13 @@ export interface StatusResponse { "environment": any; "environmentError": string | null; "desktopAgents": DesktopAgentStatus[] | null; + + /** + * ConversionRoutes maps each Agent using compatibility mode to the Chat + * Completions Profile its requests actually go to, so a page can name the + * real model service instead of the adapter. + */ + "conversionRoutes": { [_ in string]?: string } | null; } export interface TaskHistoryEvent { diff --git a/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/binding/agentservice.ts b/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/binding/agentservice.ts index 1c04e392..1a751f15 100644 --- a/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/binding/agentservice.ts +++ b/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/binding/agentservice.ts @@ -17,6 +17,22 @@ export function Activate(request: $models.ActivateRequest): $CancellablePromise< return $Call.ByID(1566640042, request); } +/** + * ActivateWithConversion points an Agent at the local adapter, which forwards + * to the named Chat Completions Profile. It sends billed check requests, so the + * UI calls it only from a button. + */ +export function ActivateWithConversion(request: $models.AgentConversionRequest): $CancellablePromise<$models.AgentConversionResponse> { + return $Call.ByID(3840302198, request); +} + +/** + * FirstTaskAgents lists the installed Agents RunFirstTask can drive unattended. + */ +export function FirstTaskAgents(): $CancellablePromise { + return $Call.ByID(1312481620); +} + export function Install(request: $models.InstallRequest): $CancellablePromise<$models.InstallResponse> { return $Call.ByID(1289781782, request); } @@ -37,6 +53,15 @@ export function PreviewUninstall(request: $models.UpdateRequest): $CancellablePr return $Call.ByID(224864709, request); } +/** + * RunFirstTask has an Agent write a small page in a temporary directory of its + * own. It is a billed request to the Agent's model, so the UI calls it only from + * a button the user pressed. + */ +export function RunFirstTask(request: app$0.FirstTaskRequest): $CancellablePromise { + return $Call.ByID(1393373323, request); +} + export function Uninstall(request: $models.UpdateRequest): $CancellablePromise { return $Call.ByID(67868259, request); } diff --git a/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/binding/index.ts b/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/binding/index.ts index d17724f3..af0ba8f6 100644 --- a/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/binding/index.ts +++ b/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/binding/index.ts @@ -35,6 +35,8 @@ export { export type { ActivateRequest, ActivateResponse, + AgentConversionRequest, + AgentConversionResponse, AgentInstallResult, CheckProfileModelRequest, DesktopAgentProfileRequest, diff --git a/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/binding/models.ts b/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/binding/models.ts index 3fd4eee8..c8d6f4b1 100644 --- a/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/binding/models.ts +++ b/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/binding/models.ts @@ -20,6 +20,23 @@ export interface ActivateResponse { "next": string; } +export interface AgentConversionRequest { + "agent_id": string; + "profile_id": string; +} + +export interface AgentConversionResponse { + "ok": boolean; + "agent": string; + "config": string; + "provider": string; + "model": string; + "restart": string; + "next": string; + "upstreamVerified": boolean; + "endToEndVerified": boolean; +} + export interface AgentInstallResult { "agent": string; "status": string; @@ -160,6 +177,12 @@ export interface ModelsResponse { */ "model"?: string; "auto_selected_model"?: boolean; + + /** + * Convertible names the protocols that failed but that compatibility mode + * can serve over Chat Completions. Top-level only, like Model. + */ + "convertible"?: string[] | null; "models": string[] | null; } @@ -234,6 +257,12 @@ export interface ProbeResponse { */ "model"?: string; "auto_selected_model"?: boolean; + + /** + * Convertible names the protocols that failed but that compatibility mode + * can serve over Chat Completions. Top-level only, like Model. + */ + "convertible"?: string[] | null; } export interface ProviderIDRequest { diff --git a/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/catalog/models.ts b/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/catalog/models.ts index 84ab6bb5..31eb5434 100644 --- a/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/catalog/models.ts +++ b/frontend/bindings/github.com/MaimoryLab/BootAgent/internal/catalog/models.ts @@ -122,6 +122,13 @@ export interface Provider { * custom Provider, which the frontend sorts by creation time instead. */ "order"?: number; + + /** + * Protocol ID -> confirmed support level on a built-in Provider's endpoint, + * from providers.lock.json. Absent for a custom Provider, whose endpoint + * nothing is known about. + */ + "protocols"?: { [_ in string]?: string } | null; "custom"?: boolean; "has_key"?: boolean; "created_at"?: string; diff --git a/frontend/e2e/wails.spec.ts b/frontend/e2e/wails.spec.ts index 2f70d499..367e4c04 100644 --- a/frontend/e2e/wails.spec.ts +++ b/frontend/e2e/wails.spec.ts @@ -1,6 +1,17 @@ import { expect, test, type Locator } from "@playwright/test"; -// Every test addresses a route directly. "/" is a decision, not a page: on a +// The one test that lands on "/", and it has to run first: a first run is a home +// nothing has written to yet, which stops being true as soon as any test saves. +test("a first run opens the wizard with an Agent already chosen", async ({ page }) => { + await page.goto("/"); + await expect(page.getByRole("heading", { name: "选择 Agent", level: 1 })).toBeVisible(); + await expect(page.getByRole("group", { name: "本机环境" })).toContainText("macOS"); + // exact, because "选择 WorkBuddy AI" is the row below it. + await expect(page.getByLabel("选择 WorkBuddy", { exact: true })).toBeChecked(); + await expect(page.getByRole("button", { name: "继续" })).toBeEnabled(); +}); + +// Every other test addresses a route directly. "/" is a decision, not a page: on a // home without ~/.bootagent it opens onboarding, so landing there would make // these tests depend on whichever one ran first and wrote state. // selectOption is gone from these tests: the pickers are custom listboxes now, @@ -89,6 +100,36 @@ test("a machine with no BootAgent state opens onboarding from the landing route" await expect(page.getByRole("heading", { name: "选择 Agent", level: 1 })).toBeVisible(); }); +// A first-time user is not required to test the connection, so the step itself +// has to say when the Agent's format is unconfirmed on the chosen service. This +// runs against the real status binding: the protocol table comes from +// providers.lock.json through Go, which a unit-test fixture cannot show. +test("the Provider step suggests compatibility mode without a connection test", async ({ page }) => { + await page.goto("/#/"); + await expect(page.getByRole("heading", { name: "选择 Agent", level: 1 })).toBeVisible(); + await page.getByRole("tab", { name: "命令行 Agent" }).click(); + await page.getByLabel("选择 Codex").check(); + await page.getByRole("button", { name: "继续" }).click(); + + await expect(page.getByRole("heading", { name: "连接模型服务" })).toBeVisible(); + // JieKou.AI ships first and has not confirmed OpenAI Responses. + await expect(page.getByRole("combobox", { name: "模型服务" })).toHaveText("JieKou.AI"); + const suggestion = page.getByText("尚未确认 JieKou.AI 支持 Codex 的请求格式(OpenAI Responses),可以改用兼容模式,由 BootAgent 在本机转换"); + await expect(suggestion).toBeVisible(); + + await page.getByRole("button", { name: "使用兼容模式" }).click(); + await expect(page.getByText("已选择兼容模式,使用 Codex 时需要保持 BootAgent 运行")).toBeVisible(); + await page.getByRole("button", { name: "不用兼容模式" }).click(); + await expect(suggestion).toBeVisible(); + + // DeepSeek has confirmed it, so there is nothing to suggest. + await page.getByRole("combobox", { name: "模型服务" }).click(); + await page.getByRole("option", { name: "DeepSeek" }).click(); + await expect(page.getByRole("combobox", { name: "模型服务" })).toHaveText("DeepSeek"); + await expect(page.getByText(/尚未确认/)).toHaveCount(0); + await expect(page.getByRole("button", { name: "使用兼容模式" })).toHaveCount(0); +}); + test("onboarding installs one Agent end to end and writes its Profile", async ({ page }) => { const bindingMethodIDs = new Set(); page.on("request", (request) => { @@ -131,6 +172,16 @@ test("onboarding installs one Agent end to end and writes its Profile", async ({ await page.getByRole("button", { name: "开始安装" }).click(); await expect(page.getByRole("heading", { name: "安装完成" })).toBeVisible({ timeout: 60_000 }); + + // The Agent just installed is offered one small task. The test build's runner + // plays the Agent, so what this covers is the path from the button to the + // page it names: the binding, the temporary directory and the file listing. + await expect(page.getByRole("heading", { name: "跑一个小任务试试" })).toBeVisible(); + await page.getByRole("button", { name: "开始", exact: true }).click(); + await expect(page.getByRole("status").filter({ hasText: "Codex 写好了" })).toBeVisible(); + await expect(page.getByRole("list", { name: "生成的文件" })).toHaveText("index.html"); + await expect(page.locator(".first-task-output code")).toContainText("bootagent-first-task-"); + await page.getByRole("button", { name: "进入总览" }).click(); await expect(page.getByRole("heading", { name: "环境总览" })).toBeVisible(); @@ -219,17 +270,21 @@ test("Claude Desktop adapts a Chat Completions Profile after one confirmation", await page.getByRole("textbox", { name: "模型", exact: true }).fill("bootagent-e2e-model"); await page.getByRole("button", { name: "保存配置模版" }).click(); + // Only the port: there is no single model to choose here any more. The + // default 8787 may be taken on the machine running the tests. await page.goto("/#/conversion"); - await page.getByRole("combobox", { name: "请求最终发往" }).click(); - await page.getByRole("option", { name: "Claude Desktop E2E Chat" }).click(); await page.getByRole("button", { name: "高级设置" }).click(); await page.getByLabel("监听地址").fill("127.0.0.1:34125"); - await page.getByRole("button", { name: "保存设置" }).click(); + await page.getByRole("button", { name: "保存更改" }).click(); + // Nothing uses compatibility mode yet, so once the address is saved the + // primary action goes back to turning it on. The save button is only disabled + // while the request is in flight, which a fast save finishes before this runs. + await expect(page.getByRole("button", { name: "开启兼容模式" })).toBeDisabled(); await page.goto("/#/agents/claude-desktop"); await page.getByLabel("选择 Claude Desktop E2E Chat").check(); - await expect(page.getByText("该模型服务不能直接使用 Claude Desktop 所需的 Anthropic Messages。BootAgent 可以在本机转换请求格式。")).toBeVisible(); - const apply = page.getByRole("button", { name: "启用协议适配并应用" }); + await expect(page.getByText("Claude Desktop 不能直接使用这个模型服务,应用时会开启兼容模式在本机转换,使用期间需要保持 BootAgent 运行")).toBeVisible(); + const apply = page.getByRole("button", { name: "用兼容模式应用" }); await expect(apply).toBeEnabled(); page.once("dialog", (dialog) => void dialog.accept()); await apply.click(); @@ -238,6 +293,41 @@ test("Claude Desktop adapts a Chat Completions Profile after one confirmation", await expect(page.getByRole("heading", { name: "环境总览" })).toBeVisible(); }); +// Runs after the Claude Desktop case. Codex is pointed at a different model, +// and Claude Desktop must keep the one it had: compatibility mode used to have +// a single target, so the second Agent silently moved the first. +test("Codex and Claude Desktop use different models through compatibility mode", async ({ page }) => { + await page.goto("/#/profiles"); + await page.getByRole("button", { name: "新增配置模版" }).click(); + await page.getByLabel("配置模版 ID").fill("codex-e2e-chat"); + await page.getByLabel("名称").fill("Codex E2E Chat"); + await page.getByRole("combobox", { name: "API 类型" }).click(); + await page.getByRole("option", { name: "OpenAI Chat Completions" }).click(); + await page.getByRole("textbox", { name: "模型", exact: true }).fill("codex-e2e-model"); + await page.getByRole("button", { name: "保存配置模版" }).click(); + + await page.goto("/#/agents/codex"); + await page.getByLabel("选择 Codex E2E Chat").check(); + await expect(page.getByText("Codex 不能直接使用这个配置模版,应用时会开启兼容模式在本机转换,使用期间需要保持 BootAgent 运行")).toBeVisible(); + const apply = page.getByRole("button", { name: "用兼容模式应用" }); + await expect(apply).toBeEnabled(); + page.once("dialog", (dialog) => void dialog.accept()); + await apply.click(); + await expect(page).toHaveURL(/#\/overview$/); + + await page.goto("/#/conversion"); + const users = page.getByRole("region", { name: "正在使用的 Agent" }); + const row = (name: string) => users.getByRole("listitem").filter({ has: page.getByText(name, { exact: true }) }); + await expect(row("Codex")).toContainText("codex-e2e-model"); + await expect(row("Claude Desktop")).toContainText("bootagent-e2e-model"); + // ChatGPT Desktop shares Codex's settings, so it follows Codex's route. + await expect(row("ChatGPT Desktop")).toContainText("codex-e2e-model"); + + // Reopening Codex shows the model it uses, not the adapter. + await users.getByRole("button", { name: "为 Codex 更换模型" }).click(); + await expect(page.getByLabel("选择 Codex E2E Chat")).toBeChecked(); +}); + test("Skills and MCP management lead to their marketplace categories", async ({ page }) => { const browserProblems: string[] = []; page.on("console", (message) => { diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index f807587b..7a20a551 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -23,6 +23,7 @@ import { MarketplaceRecommendationDetailPage } from "./pages/MarketplaceRecommen import { SkillsPage } from "./pages/SkillsPage"; import { TransferPage } from "./pages/TransferPage"; import { I18nProvider, useI18n } from "./i18n"; +import { FeedbackProvider } from "./state/FeedbackContext"; import { TaskCenterProvider, useTaskCenter } from "./state/TaskCenterContext"; import { ThemeProvider } from "./state/ThemeContext"; import { WizardProvider, useWizard } from "./state/WizardContext"; @@ -125,9 +126,11 @@ export default function App() { - - - + + + + + diff --git a/frontend/src/backend/failureCopy.test.ts b/frontend/src/backend/failureCopy.test.ts index fac1b3b1..fae1692d 100644 --- a/frontend/src/backend/failureCopy.test.ts +++ b/frontend/src/backend/failureCopy.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { sourceTranslate } from "../i18n"; -import { failureCopyFor, isHTTPStatus, runtimeDownloadHint } from "./failureCopy"; +import { failureCopyFor, isHTTPStatus, modelListMessage, runtimeDownloadHint } from "./failureCopy"; // sourceTranslate returns the Chinese keys, which is what the source language is. const t = sourceTranslate; @@ -73,6 +73,9 @@ describe("failureCopyFor", () => { "UPDATE_LOCATION_BLOCKED", "UPDATE_STALLED", "UPDATE_INTERRUPTED", + "LAUNCH_DIRECTORY_INVALID", + "TERMINAL_NOT_FOUND", + "TERMINAL_LAUNCH_FAILED", ]) { const copy = failureCopyFor(code, 0, t); expect(copy, code).not.toBeNull(); @@ -82,7 +85,7 @@ describe("failureCopyFor", () => { it("distinguishes protocol adapter startup, verification, and rollback failures", () => { expect(failureCopyFor("CONVERSION_PORT_UNAVAILABLE", 409, t)?.message).toContain("端口"); - expect(failureCopyFor("CONVERSION_VERIFICATION_FAILED", 502, t)?.message).toContain("验证"); + expect(failureCopyFor("CONVERSION_VERIFICATION_FAILED", 502, t)?.message).toContain("测试"); expect(failureCopyFor("CONVERSION_ROLLBACK_FAILED", 500, t)?.message).toContain("恢复"); }); @@ -159,3 +162,26 @@ describe("runtimeDownloadHint", () => { expect(hint).toContain("不会改变结果"); }); }); + +describe("modelListMessage", () => { + // The backend's sentences are English; the facts are in the fields. + const listing = (over: Partial[0]>) => + modelListMessage({ ok: true, models: [], error_code: null, status: 200, ...over }, t); + + it("counts what was found", () => { + expect(listing({ models: ["a", "b"] })).toEqual({ ok: true, message: "找到 2 个模型" }); + }); + + it("asks for a model by hand when the list came back empty", () => { + expect(listing({})).toEqual({ ok: false, message: "没有返回模型,请手动输入模型 ID" }); + }); + + it("explains a failure with its copy and remedy", () => { + expect(listing({ ok: false, error_code: "MODELS_UNSUPPORTED", status: 404 }).message) + .toBe("无法获取模型列表。这个端点不提供模型列表,可以直接手动输入模型 ID"); + }); + + it("never falls back to the backend sentence", () => { + expect(listing({ ok: false, error_code: "INTERNAL_ERROR", status: 0 }).message).toBe("无法获取模型列表,请手动输入模型 ID"); + }); +}); diff --git a/frontend/src/backend/failureCopy.ts b/frontend/src/backend/failureCopy.ts index 27d5fe4e..8493e3e3 100644 --- a/frontend/src/backend/failureCopy.ts +++ b/frontend/src/backend/failureCopy.ts @@ -1,4 +1,5 @@ import type { Translate } from "../i18n"; +import type { ModelsResponse } from "../types/api"; /** * Localised copy for backend failures. @@ -92,11 +93,11 @@ export function failureCopyFor(code: string | null | undefined, status: number | case "CONFIG_WRITE_FAILED": return { message: t("无法写入配置文件"), hint: t("确认配置文件没有被其他程序占用,以及你对它有写入权限") }; case "CONVERSION_PORT_UNAVAILABLE": - return { message: t("本地协议适配端口不可用"), hint: t("关闭占用该端口的程序,或在高级设置中更换端口") }; + return { message: t("兼容模式需要的本机端口被占用"), hint: t("关闭占用端口的程序,或在兼容模式的高级设置里换一个端口") }; case "CONVERSION_VERIFICATION_FAILED": - return { message: t("协议适配端到端验证失败"), hint: t("检查上游配置模板、模型服务余额和网络后重试") }; + return { message: t("兼容模式没有通过测试"), hint: t("检查所选模型服务的余额和网络后重试") }; case "CONVERSION_ROLLBACK_FAILED": - return { message: t("协议适配失败且未能完整恢复原配置"), hint: t("保留 BootAgent 运行并检查 Claude Desktop 与协议适配设置") }; + return { message: t("兼容模式开启失败,原来的设置未能完整恢复"), hint: t("请保持 BootAgent 运行,并到兼容模式页面检查") }; case "UPDATE_LOCATION_BLOCKED": // Withheld at check time on purpose: the swap runs after the app exits, so // this is the last moment anything can tell the user. @@ -121,6 +122,12 @@ export function failureCopyFor(code: string | null | undefined, status: number | return { message: t("npm 权限不足"), hint: t("检查全局 npm 目录权限,或修复 Node/npm 的用户权限") }; case "AGENT_NPM_EXECUTION_FAILED": return { message: t("npm 执行失败"), hint: t("检查 npm 环境后重试") }; + case "LAUNCH_DIRECTORY_INVALID": + return { message: t("启动目录不存在"), hint: t("换一个已有的文件夹,或用目录旁的按钮选择") }; + case "TERMINAL_NOT_FOUND": + return { message: t("找不到可用的终端"), hint: t("安装一个终端程序,或在设置中选择已安装的终端") }; + case "TERMINAL_LAUNCH_FAILED": + return { message: t("终端没有打开"), hint: t("稍后重试,或在设置中换一个终端") }; default: return null; } @@ -142,3 +149,23 @@ export function failureCopyFor(code: string | null | undefined, status: number | */ export const runtimeDownloadHint = (t: Translate): string => t("官方源和镜像都已尝试过,切换下载源不会改变结果。请检查网络连接后重试"); + +/** + * What a model listing found, in the interface's words. + * + * The backend's sentences are English ("Found 3 models.", "No model IDs + * returned; enter model ID manually.") and were shown as they came, with one + * regex translating the first. The facts are all in the structured fields, so + * the sentence is built from those instead. + */ +export function modelListMessage(result: Pick, t: Translate): { ok: boolean; message: string } { + const count = result.models?.length ?? 0; + if (result.ok) { + return count + ? { ok: true, message: t("找到 {count} 个模型", { count }) } + : { ok: false, message: t("没有返回模型,请手动输入模型 ID") }; + } + const copy = failureCopyFor(result.error_code, result.status, t); + if (!copy) return { ok: false, message: t("无法获取模型列表,请手动输入模型 ID") }; + return { ok: false, message: copy.hint ? t("{message}。{hint}", { message: copy.message, hint: copy.hint }) : copy.message }; +} diff --git a/frontend/src/backend/wails.ts b/frontend/src/backend/wails.ts index fb9e9cbc..ec2f5820 100644 --- a/frontend/src/backend/wails.ts +++ b/frontend/src/backend/wails.ts @@ -231,8 +231,16 @@ export const wailsApi = { model: input.model, profile_id: input.profileId ?? "", })) as Promise, + // Billed: checks the upstream and the local adapter before writing, so call it + // only from a button. + activateAgentWithConversion: (agentId: string, profileId: string): CancellableRequest => + call(() => AgentService.ActivateWithConversion({ agent_id: agentId, profile_id: profileId })) as CancellableRequest, launchAgent: (agentId: string, workingDirectory = ""): Promise => call(() => AgentService.Launch({ agent_id: agentId, working_directory: workingDirectory })) as Promise, + firstTaskAgents: (): Promise => + call(() => AgentService.FirstTaskAgents()).then((agents) => agents ?? []), + runFirstTask: (agentId: string, locale: string): CancellableRequest => + call(() => AgentService.RunFirstTask({ agent_id: agentId, locale })) as CancellableRequest, migrateConversations: (): Promise => call(() => AgentService.MigrateConversations()) as Promise, uninstallAgent: (agentId: string, allowCrossEnvironment = false, installationId = "", installationIds: string[] = [], removeUserData = false): CancellableRequest => diff --git a/frontend/src/components/ActionButton.test.tsx b/frontend/src/components/ActionButton.test.tsx new file mode 100644 index 00000000..8eb49aa1 --- /dev/null +++ b/frontend/src/components/ActionButton.test.tsx @@ -0,0 +1,68 @@ +import { act, fireEvent, render, screen } from "@testing-library/react"; +import { Play } from "lucide-react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { BootAgentApiError } from "../backend/errors"; +import { I18nProvider, LOCALE_STORAGE_KEY } from "../i18n"; +import { FeedbackProvider } from "../state/FeedbackContext"; +import { ACTION_DONE_MS, ActionButton } from "./ActionButton"; +import { FeedbackViewport } from "./FeedbackViewport"; + +function mount(onAction: () => unknown) { + render( + + + + + + , + ); +} + +/** Settles the awaited action inside act, without letting fake time move. */ +const settle = () => act(async () => { await Promise.resolve(); }); + +describe("ActionButton", () => { + beforeEach(() => { + localStorage.setItem(LOCALE_STORAGE_KEY, "zh-CN"); + vi.useFakeTimers(); + }); + afterEach(() => vi.useRealTimers()); + + it("confirms in place, then returns to its label", async () => { + let resolve: () => void = () => {}; + mount(() => new Promise((done) => { resolve = done; })); + const button = screen.getByRole("button", { name: "启动" }); + + fireEvent.click(button); + expect(button).toBeDisabled(); + expect(button).toHaveAttribute("aria-busy", "true"); + + resolve(); + await settle(); + // Same element throughout: the face changes, the button does not. + expect(screen.getByRole("button", { name: "已打开" })).toBe(button); + expect(button).toBeEnabled(); + + act(() => vi.advanceTimersByTime(ACTION_DONE_MS)); + expect(screen.getByRole("button", { name: "启动" })).toBe(button); + }); + + it("claims nothing when the action did not go ahead", async () => { + mount(() => Promise.resolve(false)); + fireEvent.click(screen.getByRole("button", { name: "启动" })); + await settle(); + expect(screen.getByRole("button", { name: "启动" })).toBeEnabled(); + expect(screen.queryByRole("button", { name: "已打开" })).toBeNull(); + }); + + it("returns to its label and reports a failure as a receipt", async () => { + mount(() => Promise.reject(new BootAgentApiError("Invalid launch directory: /missing", "INVALID_REQUEST", false, 400))); + fireEvent.click(screen.getByRole("button", { name: "启动" })); + await settle(); + expect(screen.getByRole("button", { name: "启动" })).toBeEnabled(); + expect(screen.getByRole("alert")).toHaveTextContent("无法启动 Codex"); + fireEvent.click(screen.getByRole("button", { name: "详情" })); + expect(screen.getByText(/Invalid launch directory: \/missing/)).toBeInTheDocument(); + }); +}); diff --git a/frontend/src/components/ActionButton.tsx b/frontend/src/components/ActionButton.tsx new file mode 100644 index 00000000..eef9228b --- /dev/null +++ b/frontend/src/components/ActionButton.tsx @@ -0,0 +1,96 @@ +import { Check, type LucideIcon, RefreshCw } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; + +import { useFeedback } from "../state/FeedbackContext"; + +/** How long the confirmed face stays before the button returns to its label. */ +export const ACTION_DONE_MS = 1600; + +type Phase = "idle" | "busy" | "done"; + +interface ActionButtonProps { + icon: LucideIcon; + label: string; + /** Four characters at most: 已打开, 已保存, 已应用. */ + doneLabel: string; + /** Headline for the receipt when the action throws, e.g. 无法启动 Codex. */ + failureMessage: string; + /** Receipt key, so a retry replaces the failure it answers. */ + feedbackKey?: string; + /** Resolving to `false` means the action did not go ahead (a declined + * confirmation): the button returns to idle without claiming success. */ + onAction: () => unknown | Promise; + className?: string; + disabled?: boolean; + title?: string; +} + +/** + * A button that reports its own result in place (docs/ui-interaction-plan.md + * §3.2.1): idle, busy, then a short confirmation, all at one width. Both faces + * share a single grid cell, so the button is as wide as the longer of the two + * from the first render and never resizes the row it sits in. A failure goes + * to the receipt overlay rather than turning the button red, which would read + * as a destructive action. + */ +export function ActionButton({ + icon: Icon, + label, + doneLabel, + failureMessage, + feedbackKey, + onAction, + className = "button button-primary", + disabled, + title, +}: ActionButtonProps) { + const feedback = useFeedback(); + const [phase, setPhase] = useState("idle"); + const mounted = useRef(true); + useEffect(() => () => { mounted.current = false; }, []); + + useEffect(() => { + if (phase !== "done") return; + const timer = setTimeout(() => setPhase("idle"), ACTION_DONE_MS); + return () => clearTimeout(timer); + }, [phase]); + + const run = async () => { + setPhase("busy"); + try { + const result = await onAction(); + if (mounted.current) setPhase(result === false ? "idle" : "done"); + } catch (error) { + if (mounted.current) setPhase("idle"); + feedback.failure(error, failureMessage, { key: feedbackKey }); + } + }; + + const done = phase === "done"; + return ( + <> + + {/* The face swap changes the button's text, which screen readers do not + announce on their own. */} + {done ? doneLabel : ""} + + ); +} diff --git a/frontend/src/components/AgentManageRow.test.tsx b/frontend/src/components/AgentManageRow.test.tsx index 9d6c9c7f..f84b20e2 100644 --- a/frontend/src/components/AgentManageRow.test.tsx +++ b/frontend/src/components/AgentManageRow.test.tsx @@ -4,11 +4,17 @@ import userEvent from "@testing-library/user-event"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { BootAgentApiError } from "../backend/errors"; +import { FeedbackProvider } from "../state/FeedbackContext"; +import { TaskCenterProvider } from "../state/TaskCenterContext"; import type { AgentCatalogItem, AgentStatus } from "../types/api"; import { AgentManageRow, compareVersions, isBehind, targetSummary, updateOffer } from "./AgentManageRow"; +import { FeedbackViewport } from "./FeedbackViewport"; const bridge = vi.hoisted(() => ({ + // TaskCenterProvider subscribes to install output when it mounts. + onInstallOutput: () => () => {}, launchAgent: vi.fn(), + getSettings: vi.fn(), updateAgent: vi.fn(), uninstallAgent: vi.fn(), question: vi.fn(), @@ -27,6 +33,8 @@ vi.mock("../backend/api", async () => { beforeEach(() => { bridge.launchAgent.mockReset(); + bridge.getSettings.mockReset(); + bridge.getSettings.mockResolvedValue({ terminal_app: "", terminals: [] }); bridge.updateAgent.mockReset(); bridge.uninstallAgent.mockReset(); bridge.question.mockReset(); @@ -77,6 +85,7 @@ function agentStatus(over: Partial = {}): AgentStatus { function renderRow(over: Partial = {}, profileName = "团队 PPIO", catalogOver: Partial = {}, onChanged = vi.fn()) { render( + = {}, profileName = "团队 PPIO", defaultDirectory="/tmp" onChanged={onChanged} /> + + , ); } @@ -180,7 +191,20 @@ describe("AgentManageRow", () => { // 2.1.217 and the row read "可更新", inviting a downgrade. renderRow({ version: "2.1.220", lockedVersion: "2.1.217" }); expect(screen.queryByText(/→/)).toBeNull(); - expect(screen.getByText(/锁定 2\.1\.217/)).toBeTruthy(); + expect(screen.queryByText(/锁定/)).toBeNull(); + expect(screen.getByText("2.1.220")).toBeTruthy(); + // The locked version is a detail, worded as a recommendation. + const recommended = screen.getByText("2.1.217"); + expect(recommended.closest("details")?.open).toBe(false); + expect(recommended.previousElementSibling?.textContent).toBe("推荐版本"); + }); + + it("keeps the endpoint and package in the closed details, and says drift in the row", () => { + renderRow({ detected: { baseUrl: "https://moved.example/v1", model: "m", managedByBootAgent: false, unreadable: null } }); + expect(screen.getByText("设置已在 BootAgent 之外被修改")).toBeTruthy(); + const endpoint = screen.getByText("https://api.ppio.com/openai"); + expect(endpoint.closest("details")?.open).toBe(false); + expect(screen.getByText("实际使用的接口地址是 https://moved.example/v1").closest("details")).toBe(endpoint.closest("details")); }); it("orders versions numerically, not as strings", () => { @@ -247,12 +271,90 @@ describe("AgentManageRow", () => { expect(bridge.launchAgent).not.toHaveBeenCalled(); }); - it("reports a launch failure in the row instead of failing silently", async () => { + it("confirms a launch on the button once the terminal has opened", async () => { + renderRow(); + await userEvent.click(screen.getByRole("button", { name: "启动" })); + // The dialog is still open: nothing has launched, so nothing is confirmed. + expect(screen.queryByRole("button", { name: "已打开" })).toBeNull(); + await userEvent.click(screen.getByRole("dialog").querySelector("button[type=submit]") as HTMLElement); + expect(await screen.findByRole("button", { name: "已打开" })).toBeTruthy(); + }); + + it("claims nothing when the directory dialog is cancelled", async () => { + renderRow(); + await userEvent.click(screen.getByRole("button", { name: "启动" })); + await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "取消" })); + expect(await screen.findByRole("button", { name: "启动" })).toBeEnabled(); + expect(bridge.launchAgent).not.toHaveBeenCalled(); + expect(screen.queryByRole("alert")).toBeNull(); + }); + + it("reports a launch failure as a receipt and keeps a marker that reopens it", async () => { bridge.launchAgent.mockRejectedValue(new BootAgentApiError("没有可用的终端", "PREREQUISITE_MISSING", false, 500)); renderRow(); await userEvent.click(screen.getByRole("button", { name: /启动/ })); await userEvent.click(screen.getByRole("dialog").querySelector("button[type=submit]") as HTMLElement); - expect(await screen.findByText("没有可用的终端")).toBeTruthy(); + const receipt = await screen.findByRole("alert"); + expect(receipt).toHaveTextContent("无法启动 Codex"); + // The reason is one click away, not a truncated line under the name. + await userEvent.click(within(receipt).getByRole("button", { name: "详情" })); + expect(within(receipt).getByText(/没有可用的终端/)).toBeTruthy(); + expect(document.querySelector(".agent-manage-note.is-error")).toBeNull(); + + await userEvent.click(within(receipt).getByRole("button", { name: "关闭" })); + expect(screen.queryByRole("alert")).toBeNull(); + await userEvent.click(screen.getByRole("button", { name: "启动失败" })); + expect(screen.getByRole("alert")).toHaveTextContent("无法启动 Codex"); + }); + + it("says which terminal opened when the one chosen in settings is missing", async () => { + bridge.launchAgent.mockResolvedValue({ ok: true, agent: "codex", command: "codex", terminal: "terminal" }); + bridge.getSettings.mockResolvedValue({ + terminal_app: "iterm", + terminals: [{ id: "terminal", name: "Terminal", installed: true }, { id: "iterm", name: "iTerm2", installed: false }], + }); + renderRow(); + await userEvent.click(screen.getByRole("button", { name: "启动" })); + await userEvent.click(screen.getByRole("dialog").querySelector("button[type=submit]") as HTMLElement); + const receipt = await screen.findByRole("alert"); + expect(receipt).toHaveTextContent("已改用 Terminal 打开"); + await userEvent.click(within(receipt).getByRole("button", { name: "详情" })); + expect(receipt).toHaveTextContent("iTerm2 未安装"); + }); + + it("marks a failed update in the row and reopens its reason from the marker", async () => { + bridge.updateAgent.mockRejectedValue(new BootAgentApiError("npm exited 1", "AGENT_NPM_EXECUTION_FAILED", true, 500)); + render( + + + + + + + + , + ); + await userEvent.click(screen.getByRole("button", { name: "Codex 更多操作" })); + await userEvent.click(screen.getByRole("menuitem", { name: "更新" })); + const marker = await screen.findByRole("button", { name: "更新失败" }); + // The outcome is in the Task Center; the row only marks it. + expect(screen.queryByRole("alert")).toBeNull(); + await userEvent.click(marker); + const receipt = screen.getByRole("alert"); + expect(receipt).toHaveTextContent("无法更新 Codex"); + await userEvent.click(within(receipt).getByRole("button", { name: "详情" })); + expect(receipt).toHaveTextContent("npm 执行失败"); + }); + + it("says nothing about the terminal when the chosen one opened", async () => { + bridge.launchAgent.mockResolvedValue({ ok: true, agent: "codex", command: "codex", terminal: "iterm" }); + bridge.getSettings.mockResolvedValue({ terminal_app: "iterm", terminals: [] }); + renderRow(); + await userEvent.click(screen.getByRole("button", { name: "启动" })); + await userEvent.click(screen.getByRole("dialog").querySelector("button[type=submit]") as HTMLElement); + await screen.findByRole("button", { name: "已打开" }); + await waitFor(() => expect(bridge.getSettings).toHaveBeenCalled()); + expect(screen.queryByRole("alert")).toBeNull(); }); }); @@ -278,7 +380,8 @@ describe("targetSummary", () => { ); expect(summary.text).toContain("https://api.other-vendor.com/v1"); expect(summary.text).toContain("gpt-5-mini"); - expect(summary.note).toContain("非 BootAgent 写入"); + expect(summary.note).toBe("这份设置不是 BootAgent 写入的"); + expect(summary.alert).toBe("正在使用 BootAgent 之外的设置"); }); it("says the file changed under us when the two sources disagree", () => { @@ -292,6 +395,9 @@ describe("targetSummary", () => { ); expect(summary.text).toContain("PPIO"); expect(summary.note).toContain("https://moved.example/v1"); + // The row says it in plain words; the endpoint is for the details. + expect(summary.alert).toBe("设置已在 BootAgent 之外被修改"); + expect(summary.alert).not.toContain("https://"); }); it("stays quiet when the record and the file agree", () => { @@ -308,6 +414,7 @@ describe("targetSummary", () => { ); expect(summary.text).toBe("PPIO · deepseek/deepseek-v3"); expect(summary.note).toBe(""); + expect(summary.alert).toBe(""); }); it("shows an unreadable config as such rather than guessing", () => { @@ -428,7 +535,7 @@ describe("the update affordance in the row", () => { expect(bridge.question).toHaveBeenCalledWith(expect.objectContaining({ Title: "卸载 Agent", - Message: expect.stringMatching(/配置模版.*模型服务.*配置文件.*对话数据.*保留/), + Message: expect.stringMatching(/只移除程序.*设置和对话都会保留/), })); await waitFor(() => expect(bridge.uninstallAgent).toHaveBeenCalledWith("codex")); await waitFor(() => expect(onChanged).toHaveBeenCalledOnce()); diff --git a/frontend/src/components/AgentManageRow.tsx b/frontend/src/components/AgentManageRow.tsx index 428dee2e..413e04f0 100644 --- a/frontend/src/components/AgentManageRow.tsx +++ b/frontend/src/components/AgentManageRow.tsx @@ -1,15 +1,19 @@ import { Dialogs } from "@wailsio/runtime"; import { FolderOpen, History, Play, RefreshCw, SlidersHorizontal, Trash2 } from "lucide-react"; -import { useState } from "react"; -import { Link } from "react-router-dom"; +import { useRef, useState } from "react"; +import { Link, useNavigate } from "react-router-dom"; import { api, describeFailure } from "../backend/api"; import { BootAgentApiError } from "../backend/errors"; import { useConversationMigration } from "../hooks/useConversationMigration"; import { sourceTranslate, type Translate, useI18n } from "../i18n"; +import { providerDisplayName } from "../state/conversion"; +import { useFeedback } from "../state/FeedbackContext"; import { taskCanceller, taskKey, updateTaskRoute, useTaskCenter, useTaskRoute } from "../state/TaskCenterContext"; import type { AgentCatalogItem, AgentStatus, ProfileSummary, StatusResponse } from "../types/api"; +import { ActionButton } from "./ActionButton"; import { AgentActionMenu, type AgentActionMenuItem } from "./AgentActionMenu"; +import { DetailsDisclosure } from "./DetailsDisclosure"; import { AgentIcon, agentTagline } from "./icons/agents"; import { ModalDialog } from "./ModalDialog"; @@ -55,21 +59,17 @@ export function isBehind(installed: string, locked: string): boolean { return compareVersions(installed, locked) < 0; } -function versionNote(status: AgentStatus, t: Translate = sourceTranslate): { text: string; behind: boolean } | null { +function versionNote(status: AgentStatus): { text: string; behind: boolean } | null { if (!status.installed || !status.version) return null; - if (!status.lockedVersion || status.version === status.lockedVersion) { - // Being current is the normal case and needs no words: the bare version is - // enough, and five rows each saying "已是最新" is noise. - return { text: status.version, behind: false }; - } - // Only an older local version is an update. A newer one is normal — the user - // upgraded the Agent themselves — and calling it "updatable" would send them - // to downgrade. - if (compareVersions(status.version, status.lockedVersion) < 0) { - // The arrow already says which way this goes. + // Only an older local version is an update; the arrow says which way it goes. + // A newer one is normal -- the user upgraded the Agent themselves -- and is + // shown as the plain version: the locked one, a term a newcomer cannot place, + // is in the details as the recommended version. + if (status.lockedVersion && compareVersions(status.version, status.lockedVersion) < 0) { return { text: `${status.version} → ${status.lockedVersion}`, behind: true }; } - return { text: t("{version}(锁定 {lockedVersion})", { version: status.version, lockedVersion: status.lockedVersion }), behind: false }; + // Being current needs no words either: five rows saying "已是最新" is noise. + return { text: status.version, behind: false }; } /** @@ -79,35 +79,42 @@ function versionNote(status: AgentStatus, t: Translate = sourceTranslate): { tex * file as found on disk. Reporting only the first is what made a hand-written * configuration render as "未配置" — the file was seen but never read. Where they * disagree the file wins, because that is what the Agent will actually use. + * + * `alert` is the one line the row itself shows when something needs the + * user's attention, in plain words; `text` and `note` carry the specifics + * (endpoint, parse error) for the details. */ export function targetSummary( status: AgentStatus, providers: Providers, t: Translate = sourceTranslate, -): { text: string; note: string } { +): { text: string; note: string; alert: string } { const detected = status.detected; if (detected?.unreadable) { - return { text: t("配置无法解析"), note: detected.unreadable }; + return { text: t("配置无法解析"), note: detected.unreadable, alert: t("这个 Agent 的设置无法读取") }; } - const providerName = status.provider ? providers[status.provider]?.name || status.provider : ""; + const providerName = status.provider ? providerDisplayName(providers, status.provider, t) : ""; // Ours, and the file agrees (or has nothing to add). if (status.provider && status.model) { const drifted = detected && detected.baseUrl && status.baseUrl && detected.baseUrl !== status.baseUrl; return { text: `${providerName} · ${status.model}`, - note: drifted ? t("配置文件当前指向 {url}", { url: detected!.baseUrl }) : "", + note: drifted ? t("实际使用的接口地址是 {url}", { url: detected!.baseUrl }) : "", + alert: drifted ? t("设置已在 BootAgent 之外被修改") : "", }; } // No record of our own, but the file says something. if (detected && (detected.baseUrl || detected.model)) { const parts = [detected.baseUrl, detected.model].filter(Boolean); + const foreign = !detected.managedByBootAgent; return { text: parts.join(" · "), - note: detected.managedByBootAgent ? "" : t("检测到的配置,非 BootAgent 写入"), + note: foreign ? t("这份设置不是 BootAgent 写入的") : "", + alert: foreign ? t("正在使用 BootAgent 之外的设置") : "", }; } - return { text: t("未配置"), note: "" }; + return { text: t("未配置"), note: "", alert: "" }; } /** @@ -133,12 +140,19 @@ export function AgentManageRow({ defaultDirectory?: string; }) { const { t } = useI18n(); + const navigate = useNavigate(); + const feedback = useFeedback(); const { startTask, finishTask, setTaskCanceller, taskFor, isTaskRunning } = useTaskCenter(); const route = useTaskRoute(); const [launching, setLaunching] = useState(false); const [localUpdating, setLocalUpdating] = useState(false); const [localUninstalling, setLocalUninstalling] = useState(false); - const [failure, setFailure] = useState(""); + // The last launch failure, kept so the row can still name it after its + // receipt is closed. Cleared by the next launch that succeeds. + const [launchFailure, setLaunchFailure] = useState(null); + // Settles the launch button's pending action once the directory dialog + // answers: false when it is dismissed, the launch outcome when it is submitted. + const launchSettle = useRef<{ resolve: (launched: boolean) => void; reject: (error: unknown) => void } | null>(null); const [launchDirectory, setLaunchDirectory] = useState(""); const [rememberDirectory, setRememberDirectory] = useState(false); const [installationID, setInstallationID] = useState(""); @@ -153,20 +167,29 @@ export function AgentManageRow({ const migration = useConversationMigration(); const updating = updateTask?.state === "running" || localUpdating; const uninstalling = uninstallTask?.state === "running" || localUninstalling; - const version = versionNote(status, t); + const version = versionNote(status); + const recommended = status.lockedVersion && status.version && status.lockedVersion !== status.version && !version?.behind ? status.lockedVersion : ""; const target = targetSummary(status, providers, t); const providerId = profile?.provider || status.provider || ""; - const providerName = providerId ? providers[providerId]?.name || providerId : ""; + const providerName = providerId ? providerDisplayName(providers, providerId, t) : ""; const profileLabel = profileName || status.profileId || ""; const model = profile?.model || status.model || status.detected?.model || ""; const baseUrl = status.baseUrl || status.detected?.baseUrl || ""; + const agentName = catalog?.name || agentId; + const launchKey = `launch:${agentId}`; // No "not configured" state here: the Profile and Provider tokens already name // whichever piece is absent, so a third word for the same condition only adds // a term the user has to map back onto them. - const taskFailure = updateTask?.state === "failure" - ? updateTask.message || t("失败") - : uninstallTask?.state === "failure" ? uninstallTask.message || t("失败") : ""; - const statusLabel = failure || taskFailure ? t("失败") : !status.installed ? t("未安装") : ""; + // + // A failure is a fixed-size marker in the token strip, not a line of text + // under the name: the reason is in the receipt, which the marker reopens. + const failureMarker = launchFailure + ? { label: t("启动失败"), reopen: () => feedback.failure(launchFailure, t("无法启动 {name}", { name: agentName }), { key: launchKey }) } + : updateTask?.state === "failure" + ? { label: t("更新失败"), reopen: () => feedback.show({ key: updateTaskID, tone: "failure", message: t("无法更新 {name}", { name: agentName }), detail: updateTask.message || undefined }) } + : uninstallTask?.state === "failure" + ? { label: t("卸载失败"), reopen: () => feedback.show({ key: uninstallTaskID, tone: "failure", message: t("无法卸载 {name}", { name: agentName }), detail: uninstallTask.message || undefined }) } + : null; // installed is true only when the Agent's command resolved on the managed // PATH, so it is already the precise "there is something to launch" signal. @@ -175,30 +198,67 @@ export function AgentManageRow({ const manageable = Boolean(catalog?.packageManager && ["npm", "uv", "official-script"].includes(catalog.packageManager) && status.installed); const busy = launching || updating || uninstalling || migration.running || isTaskRunning(taskKey("install", agentId)); + /** + * Says which terminal opened when it was not the one chosen in settings. The + * backend falls back rather than failing when that terminal is gone, and + * returns the one it used precisely so the substitution is not silent. + */ + const reportTerminal = async (terminal: string) => { + if (!terminal) return; + try { + const settings = await api.getSettings(); + const preferred = settings.terminal_app; + if (!preferred || preferred === terminal) return; + const nameOf = (id: string) => settings.terminals?.find((option) => option.id === id)?.name || id; + feedback.show({ + key: "launch-terminal", + tone: "warning", + message: t("已改用 {terminal} 打开", { terminal: nameOf(terminal) }), + detail: t("设置里选择的 {terminal} 未安装,可以在设置中更换", { terminal: nameOf(preferred) }), + action: { label: t("去设置"), run: () => navigate("/settings") }, + }); + } catch { + // The launch itself succeeded; not naming the terminal is no reason to say otherwise. + } + }; const startLaunch = async (directory: string) => { - setDirectoryDialog(false); setLaunching(true); - setFailure(""); try { - await api.launchAgent(agentId, directory); + const result = await api.launchAgent(agentId, directory); + setLaunchFailure(null); + void reportTerminal(result?.terminal ?? ""); } catch (error) { - setFailure(describeFailure(error, t("无法启动 Agent"), t).message); + setLaunchFailure(error); + throw error; } finally { setLaunching(false); } }; + const settleLaunch = (outcome: { launched: boolean } | { error: unknown }) => { + const pending = launchSettle.current; + launchSettle.current = null; + if (!pending) return; + if ("error" in outcome) pending.reject(outcome.error); + else pending.resolve(outcome.launched); + }; + const closeDirectoryDialog = () => { + setDirectoryDialog(false); + settleLaunch({ launched: false }); + }; // A web-app Agent serves a local page and chooses its own workspace, so asking // where to start it would collect an answer nothing then uses. It launches - // straight away instead. - const launch = () => { + // straight away instead. Otherwise the launch button stays pending until the + // directory dialog answers, so it confirms the launch, not the dialog. + const launch = async (): Promise => { if (catalog?.webApp) { - void startLaunch(""); - return; + await startLaunch(""); + return true; } const stored = localStorage.getItem(`bootagent:launch-directory:${agentId}`); setLaunchDirectory(stored || defaultDirectory || ""); setRememberDirectory(Boolean(stored)); setDirectoryDialog(true); + return new Promise((resolve, reject) => { launchSettle.current = { resolve, reject }; }); }; const chooseDirectory = async () => { try { @@ -211,7 +271,13 @@ export function AgentManageRow({ if (!launchDirectory.trim()) return; if (rememberDirectory) localStorage.setItem(`bootagent:launch-directory:${agentId}`, launchDirectory.trim()); else localStorage.removeItem(`bootagent:launch-directory:${agentId}`); - await startLaunch(launchDirectory.trim()); + setDirectoryDialog(false); + try { + await startLaunch(launchDirectory.trim()); + settleLaunch({ launched: true }); + } catch (error) { + settleLaunch({ error }); + } }; const update = async () => { if (!startTask({ @@ -222,7 +288,6 @@ export function AgentManageRow({ route: updateTaskRoute(agentId), })) return; setLocalUpdating(true); - setFailure(""); try { const request = api.updateAgent(agentId); setTaskCanceller(updateTaskID, taskCanceller(request)); @@ -244,7 +309,7 @@ export function AgentManageRow({ const confirmLabel = t("卸载 Agent"); const choice = await Dialogs.Question({ Title: confirmLabel, - Message: t("确定卸载「{name}」吗?只会移除 Agent 程序,配置模版、模型服务、配置文件和对话数据都会保留。", { name: catalog?.name || agentId }), + Message: t("卸载「{name}」?只移除程序,你的设置和对话都会保留。", { name: catalog?.name || agentId }), Buttons: [{ Label: confirmLabel }, { Label: t("卸载并删除全部数据") }, { Label: t("取消"), IsCancel: true }], }).catch(() => ""); if (![confirmLabel, t("卸载并删除全部数据")].includes(choice)) return; @@ -252,7 +317,7 @@ export function AgentManageRow({ if (removeUserData) { const destructiveChoice = await Dialogs.Question({ Title: t("确认永久删除数据"), - Message: t("全量清理将永久删除配置文件、凭据、会话和对话数据,删除后无法找回。请确认你已完成备份。"), + Message: t("会永久删除这个 Agent 的设置、登录信息和全部对话,无法找回。"), Buttons: [{ Label: t("永久删除并卸载") }, { Label: t("取消"), IsCancel: true }], }).catch(() => ""); if (destructiveChoice !== t("永久删除并卸载")) return; @@ -266,7 +331,6 @@ export function AgentManageRow({ cancellable: false, })) return; setLocalUninstalling(true); - setFailure(""); try { const runUninstall = async (allowCrossEnvironment: boolean) => { const ids = selectedIDs ?? (installations.length === 1 ? [installations[0].id] : []); @@ -280,7 +344,7 @@ export function AgentManageRow({ if (!(error instanceof BootAgentApiError) || error.code !== "AGENT_NPM_ENVIRONMENT_MISMATCH") throw error; const crossChoice = await Dialogs.Question({ Title: t("确认跨环境卸载"), - Message: t("当前 Agent 由另一套 Node/npm 环境管理。是否允许使用已记录的原始 npm 环境卸载?不会使用 sudo,也不会删除配置和对话数据。"), + Message: t("这个 Agent 是用另一套 Node.js 安装的。要用当初安装它的那一套来卸载吗?不会删除你的设置和对话。"), Buttons: [{ Label: t("允许并继续") }, { Label: t("取消"), IsCancel: true }], }).catch(() => ""); if (crossChoice !== t("允许并继续")) throw error; @@ -335,7 +399,7 @@ export function AgentManageRow({ {catalog?.name || agentId} - {failure || taskFailure ? {failure || taskFailure} : null} + {target.alert ? {target.alert} : null} {/* Right-aligned, in a fixed order, with the Profile and Provider slots @@ -360,11 +424,15 @@ export function AgentManageRow({ {version.text} ) : null} - {statusLabel ? {statusLabel} : null} + {failureMarker ? ( + + ) : !status.installed ? {t("未安装")} : null} {directoryDialog ? ( - setDirectoryDialog(false)}> +
{ event.preventDefault(); void confirmLaunch(); }}>

{t("选择启动目录")}

@@ -373,7 +441,7 @@ export function AgentManageRow({ -
+
) : null} @@ -403,58 +471,44 @@ export function AgentManageRow({ {canLaunch ? ( - + ) : null} -
- {t("详情")} -
- {providerName ? ( -
{t("模型服务")}{providerName}
- ) : null} - {profileLabel ? ( -
{t("配置模版")}{profileLabel}
- ) : null} - {model ? ( -
{t("模型")}{model}
- ) : null} - {baseUrl ? ( -
URL{baseUrl}
- ) : null} - {target.text && target.text !== t("未配置") ? ( -
{t("检测状态")}{target.text}
- ) : null} - {target.note ? ( -
{t("备注")}{target.note}
- ) : null} - {catalog?.packageManager && catalog.packageName ? ( -
npm{catalog.packageName}
- ) : null} - {installations.length ? ( -
- {t("检测到的安装实例")} -
- {installations.map((installation) => ( -
- {installation.manager} - {installation.executable} - {installation.canUninstall ? t("可卸载") : installation.reason || t("不可卸载")} -
- ))} -
+ {/* Facts a newcomer does not need to use the Agent. The Profile, Provider + and model are already in the row above, so they are not repeated. */} + + {installations.length ? ( +
+ {t("安装位置")} +
+ {installations.map((installation) => ( +
+ {installation.manager} + {installation.executable} + {installation.canUninstall ? t("可卸载") : installation.reason || t("不可卸载")} +
+ ))}
- ) : null} -
-
+ + ) : null} + ); } diff --git a/frontend/src/components/AppWindow.test.tsx b/frontend/src/components/AppWindow.test.tsx new file mode 100644 index 00000000..0a1e483e --- /dev/null +++ b/frontend/src/components/AppWindow.test.tsx @@ -0,0 +1,58 @@ +import { render, screen } from "@testing-library/react"; +import { MemoryRouter } from "react-router-dom"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +let mockStatus: { migrationNotice?: string; catalog: unknown[] } = { catalog: [] }; + +vi.mock("@wailsio/runtime", () => ({ Events: { On: vi.fn(), Off: vi.fn() } })); +vi.mock("./NavigationSidebar", () => ({ NavigationSidebar: () => null })); +vi.mock("../state/WizardContext", () => ({ + useWizard: () => ({ state: { status: mockStatus } }), +})); + +import { I18nProvider } from "../i18n"; +import { FeedbackProvider } from "../state/FeedbackContext"; +import { AppWindow } from "./AppWindow"; +import { PageScaffold } from "./PageScaffold"; + +const renderWindow = () => + render( + + + + + + + + + , + ); + +beforeEach(() => localStorage.setItem("bootagent.locale", "zh-CN")); +afterEach(() => { + localStorage.clear(); + mockStatus = { catalog: [] }; +}); + +describe("AppWindow migration notice", () => { + it("reports a failed migration as a receipt instead of a paragraph above the page", async () => { + mockStatus = { catalog: [], migrationNotice: "无法迁移旧 BootAgent 配置:inspect legacy configuration: denied" }; + const { container } = renderWindow(); + + const receipt = await screen.findByRole("alert"); + expect(receipt).toHaveTextContent("没能迁移旧版配置"); + expect(container.querySelector(".app-main")?.firstElementChild).toHaveClass("page-scaffold"); + }); + + it("reports a completed migration as a warning that waits to be read", async () => { + mockStatus = { catalog: [], migrationNotice: "OneAgent configuration was migrated to BootAgent." }; + renderWindow(); + + expect(await screen.findByRole("alert")).toHaveTextContent("已迁移旧版配置"); + }); + + it("shows nothing without a notice", () => { + renderWindow(); + expect(screen.queryByRole("alert")).toBeNull(); + }); +}); diff --git a/frontend/src/components/AppWindow.tsx b/frontend/src/components/AppWindow.tsx index 42de7da8..430cf787 100644 --- a/frontend/src/components/AppWindow.tsx +++ b/frontend/src/components/AppWindow.tsx @@ -1,20 +1,38 @@ -import type { PropsWithChildren } from "react"; +import { type PropsWithChildren, useEffect, useRef } from "react"; import { NavigationSidebar } from "./NavigationSidebar"; +import { useFeedback } from "../state/FeedbackContext"; import { useWizard } from "../state/WizardContext"; import { useI18n } from "../i18n"; +/** The prefix internal/app/status.go puts on a migration that failed. */ +const MIGRATION_FAILED_PREFIX = "无法迁移"; + export function AppWindow({ children }: PropsWithChildren) { const { t } = useI18n(); const { state } = useWizard(); + const feedback = useFeedback(); + const notice = state.status?.migrationNotice ?? ""; + // The notice is in every status poll for the life of the process. It used to + // be a paragraph above every page, taking height from each of them; it is now + // one receipt, shown once, that stays until the user closes it. + const shown = useRef(""); + useEffect(() => { + if (!notice || shown.current === notice) return; + shown.current = notice; + const failed = notice.startsWith(MIGRATION_FAILED_PREFIX); + feedback.show({ + key: "migration", + tone: failed ? "failure" : "warning", + message: failed ? t("没能迁移旧版配置") : t("已迁移旧版配置"), + detail: notice, + }); + }, [notice, feedback, t]); return (
event.preventDefault()}>
-
- {state.status?.migrationNotice ?

{state.status.migrationNotice}

: null} - {children} -
+
{children}
); diff --git a/frontend/src/components/ConnectionStatus.test.tsx b/frontend/src/components/ConnectionStatus.test.tsx index 53fbadd5..440a97c3 100644 --- a/frontend/src/components/ConnectionStatus.test.tsx +++ b/frontend/src/components/ConnectionStatus.test.tsx @@ -43,9 +43,12 @@ describe("ConnectionStatus", () => { expect(screen.queryByText(/BootAgent chose the model/)).toBeNull(); }); - it("reports a successful probe with the provider's own message", () => { - show(probe({ ok: true, status: 200, message: "连接正常", error_code: null })); - expect(screen.getByText("连接正常")).toBeTruthy(); + // The backend's success sentence is English ("OpenAI Chat Completions + // connection test passed."), so the verdict is the interface's own words. + it("reports a successful probe in its own words, not the backend's", () => { + show(probe({ ok: true, status: 200, message: "OpenAI Chat Completions connection test passed.", error_code: null })); + expect(screen.getByText("Connection works")).toBeTruthy(); + expect(screen.queryByText(/connection test passed/)).toBeNull(); }); // The backend's own sentences are English and written for a maintainer reading a diff --git a/frontend/src/components/ConnectionStatus.tsx b/frontend/src/components/ConnectionStatus.tsx index 8d9e8f5e..4c397b46 100644 --- a/frontend/src/components/ConnectionStatus.tsx +++ b/frontend/src/components/ConnectionStatus.tsx @@ -48,7 +48,9 @@ export function ConnectionStatus({ state, result }: { state: AsyncState; result:
- {result.message} + {/* Not result.message: the backend writes " connection test + passed." in English, and which protocols passed is listed below. */} + {t("连接正常")} {breakdown}
diff --git a/frontend/src/components/DesktopAppSection.test.tsx b/frontend/src/components/DesktopAppSection.test.tsx index c22e8cf5..2c0c863b 100644 --- a/frontend/src/components/DesktopAppSection.test.tsx +++ b/frontend/src/components/DesktopAppSection.test.tsx @@ -1,9 +1,14 @@ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; +import { BootAgentApiError } from "../backend/errors"; import type { DesktopAgentActionResult, DesktopAgentStatus } from "../types/api"; +import { FeedbackProvider } from "../state/FeedbackContext"; import { TaskCenterProvider } from "../state/TaskCenterContext"; +import { ACTION_DONE_MS } from "./ActionButton"; import { DesktopAppSection } from "./DesktopAppSection"; +import { FeedbackViewport } from "./FeedbackViewport"; +import { TaskCenter } from "./TaskCenter"; const bridge = vi.hoisted(() => ({ onInstallOutput: () => () => {}, @@ -58,12 +63,18 @@ describe("DesktopAppSection", () => { ); expect(screen.getByRole("heading", { name: "桌面 Agent" })).toBeTruthy(); - const configNote = screen.getByText("与 Example CLI 共用配置文件 /home/u/.example/config.toml;安装和启动不会改动配置"); - expect(configNote.closest(".desktop-app-row")).toBeTruthy(); + // The settings file is a detail: in the row's closed fold, not its text. + const configPath = screen.getByText("/home/u/.example/config.toml"); + expect(configPath.closest("details")?.open).toBe(false); + expect(configPath.closest(".desktop-app-row")).toBeTruthy(); + expect(screen.getByText("和 Example CLI 用同一份设置,安装和启动不会改动它").closest("details")).toBe(configPath.closest("details")); fireEvent.click(screen.getByRole("button", { name: "安装" })); await waitFor(() => expect(onChanged).toHaveBeenCalledTimes(1)); expect(bridge.installDesktopAgent).toHaveBeenCalledWith("chatgpt-desktop"); - expect(screen.getByText("Example Desktop 安装完成")).toBeTruthy(); + // The outcome belongs to the Task Center, not to a notice inside the card + // that pushed the rows below it down. + expect(screen.queryByText("Example Desktop 安装完成")).toBeNull(); + expect(document.querySelector(".desktop-app-section .notice-success")).toBeNull(); }); it("offers conversation migration in the action menu for installed ChatGPT Desktop", () => { @@ -150,16 +161,15 @@ describe("DesktopAppSection", () => { fireEvent.click(screen.getByRole("button", { name: "启动" })); await waitFor(() => expect(bridge.openDesktopAgent).toHaveBeenCalledTimes(1)); expect(bridge.openDesktopAgent).toHaveBeenCalledWith("chatgpt-desktop"); - expect(screen.getByText("Example Desktop 已打开")).toBeTruthy(); + // Confirmed on the button itself rather than in a notice above the card. + expect(await screen.findByRole("button", { name: "已打开" })).toBeTruthy(); expect(screen.queryByRole("button", { name: "更新" })).toBeNull(); // The version is a token now, so its heading lives in title= rather than // beside the value. Assert the labelled element, not the concatenation. expect(screen.getByTitle("版本").textContent).toBe("26.727.51351"); }); - it("retires the launch notice on its own", async () => { - // It used to stay until the user launched again or navigated away, which - // unmounted the row -- so on the page where you launch from, it never left. + it("returns the launch button to its label after confirming", async () => { vi.useFakeTimers(); try { bridge.openDesktopAgent.mockResolvedValue(undefined); @@ -169,56 +179,42 @@ describe("DesktopAppSection", () => { , ); - fireEvent.click(screen.getByRole("button", { name: "启动" })); - await vi.waitFor(() => expect(screen.queryByText("Example Desktop 已打开")).toBeTruthy()); - // Still there a moment later: it is readable, not a flash. - await act(async () => { await vi.advanceTimersByTimeAsync(1000); }); - expect(screen.queryByText("Example Desktop 已打开")).toBeTruthy(); - - await act(async () => { await vi.advanceTimersByTimeAsync(3000); }); - expect(screen.queryByText("Example Desktop 已打开")).toBeNull(); + const button = screen.getByRole("button", { name: "启动" }); + fireEvent.click(button); + await act(async () => { await vi.advanceTimersByTimeAsync(0); }); + expect(button).toHaveAccessibleName("已打开"); + await act(async () => { await vi.advanceTimersByTimeAsync(ACTION_DONE_MS); }); + expect(button).toHaveAccessibleName("启动"); } finally { vi.useRealTimers(); } }); - it("restarts the countdown when the app is launched again", async () => { - // The second launch repeats the same message. If the reset to "" did not - // land between the two, the effect would not re-run and the notice would - // still vanish on the first launch's schedule. - vi.useFakeTimers(); - try { - bridge.openDesktopAgent.mockResolvedValue(undefined); - render( - + it("reports an open failure as a receipt and keeps a marker that reopens it", async () => { + bridge.openDesktopAgent.mockRejectedValue(new BootAgentApiError("Cannot open Example Desktop", "INTERNAL_ERROR", true, 500)); + const { container } = render( + + - , - ); + + + , + ); - // Settle the launch before reading the clock: the notice is set after an - // awaited call, so advancing first would arm the timer mid-advance and - // measure from the wrong instant. - const launch = async () => { - fireEvent.click(screen.getByRole("button", { name: "启动" })); - await act(async () => { await vi.advanceTimersByTimeAsync(0); }); - }; - - await launch(); - expect(screen.queryByText("Example Desktop 已打开")).toBeTruthy(); - await act(async () => { await vi.advanceTimersByTimeAsync(3000); }); - - await launch(); - expect(bridge.openDesktopAgent).toHaveBeenCalledTimes(2); - // 3s of the first window had already elapsed; the notice outliving another - // 2s proves the clock restarted rather than carried over. - await act(async () => { await vi.advanceTimersByTimeAsync(2000); }); - expect(screen.queryByText("Example Desktop 已打开")).toBeTruthy(); - - await act(async () => { await vi.advanceTimersByTimeAsync(2000); }); - expect(screen.queryByText("Example Desktop 已打开")).toBeNull(); - } finally { - vi.useRealTimers(); - } + fireEvent.click(screen.getByRole("button", { name: "启动" })); + expect(await screen.findByRole("alert")).toHaveTextContent("无法打开 Example Desktop"); + // Nothing was written into the card. + expect(container.querySelector(".desktop-app-section .notice-error")).toBeNull(); + + fireEvent.click(screen.getByRole("button", { name: "关闭" })); + expect(screen.queryByRole("alert")).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "启动失败" })); + expect(screen.getByRole("alert")).toHaveTextContent("无法打开 Example Desktop"); + + // The next open that succeeds clears the marker. + bridge.openDesktopAgent.mockResolvedValue(undefined); + fireEvent.click(screen.getByRole("button", { name: "启动" })); + await waitFor(() => expect(screen.queryByRole("button", { name: "启动失败" })).toBeNull()); }); it("keeps the bar and reports the outcome across a navigation mid-download", async () => { @@ -234,6 +230,7 @@ describe("DesktopAppSection", () => { const view = render( + , ); @@ -244,6 +241,7 @@ describe("DesktopAppSection", () => { // Leaving the page unmounts the row while the install keeps running. view.rerender( +
另一个页面
, ); @@ -252,6 +250,7 @@ describe("DesktopAppSection", () => { // Coming back must show the bar again, without starting a second install. view.rerender( + , ); @@ -259,8 +258,9 @@ describe("DesktopAppSection", () => { expect(bridge.installDesktopAgent).toHaveBeenCalledTimes(1); await act(async () => { complete(action(installed)); }); - // The verdict was recorded in the provider, so it survives the round trip. - await waitFor(() => expect(screen.getByText("Example Desktop 安装完成")).toBeTruthy()); + // The verdict was recorded in the provider, so it survives the round trip + // and is reported where install outcomes live: the Task Center. + await waitFor(() => expect(screen.getByText(/Example Desktop 安装完成/)).toBeTruthy()); expect(screen.queryByRole("progressbar", { name: "下载进度" })).toBeNull(); }); @@ -271,8 +271,8 @@ describe("DesktopAppSection", () => { , ); - expect(screen.getByText("应用状态检测不可用")).toBeTruthy(); - expect(screen.queryByText("已检测到应用,但版本信息不可用")).toBeNull(); + expect(screen.getByText("暂时无法检查这个应用是否已安装。")).toBeTruthy(); + expect(screen.queryByText("读不到这个应用的版本,不影响启动和使用。")).toBeNull(); }); it("can omit an uninstalled app from the overview", () => { @@ -293,8 +293,7 @@ describe("DesktopAppSection", () => { , ); - expect(screen.getByText("已检测到应用,但版本信息不可用")).toBeTruthy(); - expect(screen.getByText("可继续尝试启动;版本检测与模型 API 兼容性无关。")).toBeTruthy(); + expect(screen.getByText("读不到这个应用的版本,不影响启动和使用。")).toBeTruthy(); fireEvent.click(screen.getByRole("button", { name: "启动" })); await waitFor(() => expect(bridge.openDesktopAgent).toHaveBeenCalledWith("chatgpt-desktop")); }); diff --git a/frontend/src/components/DesktopAppSection.tsx b/frontend/src/components/DesktopAppSection.tsx index e04262e9..ee849c22 100644 --- a/frontend/src/components/DesktopAppSection.tsx +++ b/frontend/src/components/DesktopAppSection.tsx @@ -1,15 +1,18 @@ import { AppWindow, Download, History, Play, Plus, RefreshCw, SlidersHorizontal, TriangleAlert } from "lucide-react"; -import { useEffect, useState } from "react"; +import { useState } from "react"; import { api, describeFailure } from "../backend/api"; import { useI18n } from "../i18n"; -import { converterProfileName } from "../state/conversion"; +import { converterProfileName, isConverterID } from "../state/conversion"; +import { useFeedback } from "../state/FeedbackContext"; import { useConversationMigration } from "../hooks/useConversationMigration"; import { taskCanceller, taskKey, useTaskCenter, useTaskRoute } from "../state/TaskCenterContext"; import type { DesktopAgentStatus, ProfileSummary } from "../types/api"; +import { ActionButton } from "./ActionButton"; import { DownloadProgress } from "./DownloadProgress"; import { EditionTag } from "./EditionTag"; import { AgentActionMenu, type AgentActionMenuItem } from "./AgentActionMenu"; +import { DetailsDisclosure } from "./DetailsDisclosure"; import { AgentIcon } from "./icons/agents"; interface DesktopAppSectionProps { @@ -25,27 +28,23 @@ interface DesktopAppSectionProps { showHeading?: boolean; } -type Action = "install" | "open"; - -/** - * How long "{name} 已打开" stays on screen. - * - * Long enough to be read, short enough that it does not become furniture. This - * only bounds the launch confirmation: an install outcome lives in the Task - * Center until the user dismisses it, and a failure stays until the next - * attempt, because both carry something still worth acting on. - */ -const LAUNCH_NOTICE_MS = 4000; - export function DesktopAppSection({ app: desktopApp, onChanged, onSetup, onConfigure, profile, providerName, model, showUninstalled = true, showHeading = true }: DesktopAppSectionProps) { const { t } = useI18n(); - const profileName = profile ? converterProfileName(profile.id, profile.label || profile.id, t) : desktopApp.profileId || ""; + // The overview passes the model service behind the adapter for an app in + // compatibility mode; the app itself is still bound to its converter Profile. + const viaConversion = Boolean(profile && desktopApp.profileId && isConverterID(desktopApp.profileId) && profile.id !== desktopApp.profileId); + const profileName = profile + ? viaConversion ? t("{name}(兼容模式)", { name: profile.label || profile.id }) : converterProfileName(profile.id, profile.label || profile.id, t) + : desktopApp.profileId || ""; const { startTask, finishTask, setTaskCanceller, taskFor } = useTaskCenter(); const route = useTaskRoute(); const migration = useConversationMigration(); - const [pending, setPending] = useState(""); - const [localNotice, setLocalNotice] = useState(""); - const [localFailure, setLocalFailure] = useState(""); + const feedback = useFeedback(); + const [installing, setInstalling] = useState(false); + const [opening, setOpening] = useState(false); + // The last failure to open the app, kept so the row can still name it after + // its receipt is closed. Cleared by the next open that succeeds. + const [openFailure, setOpenFailure] = useState(null); if (!desktopApp?.supported || (!showUninstalled && !desktopApp.installed)) return null; @@ -56,22 +55,19 @@ export function DesktopAppSection({ app: desktopApp, onChanged, onSetup, onConfi const installTaskID = taskKey("install", desktopApp.id); const installTask = taskFor(installTaskID); const downloading = installTask?.state === "running"; - const busy = Boolean(pending) || downloading; - const notice = localNotice || (installTask?.state === "success" ? installTask.message : ""); - const failure = localFailure || (!localNotice && installTask?.state === "failure" ? installTask.message : ""); + const busy = installing || opening || downloading; + const openKey = `open:${desktopApp.id}`; + // An install outcome lives in the Task Center; the row keeps only a marker for + // a failure, which reopens its reason as a receipt. Neither is written into + // the card, where it pushed the rows below it down. + const failureMarker = openFailure + ? { label: t("启动失败"), reopen: () => feedback.failure(openFailure, t("无法打开 {name}", { name: desktopApp.name }), { key: openKey }) } + : installTask?.state === "failure" + ? { label: t("安装失败"), reopen: () => feedback.show({ key: installTaskID, tone: "failure", message: t("无法安装 {name}", { name: desktopApp.name }), detail: installTask.message || undefined }) } + : null; - // Launching an app says everything it has to say the moment it appears, so it - // retires itself. Previously nothing cleared it: it sat there until the user - // launched again or navigated away, which unmounted the row. - useEffect(() => { - if (!localNotice) return; - const timer = setTimeout(() => setLocalNotice(""), LAUNCH_NOTICE_MS); - return () => clearTimeout(timer); - }, [localNotice]); - - const run = async (action: Action) => { - const downloads = action === "install"; - if (downloads && !startTask({ + const install = async () => { + if (!startTask({ id: installTaskID, kind: "install", target: desktopApp.id, @@ -79,39 +75,44 @@ export function DesktopAppSection({ app: desktopApp, onChanged, onSetup, onConfi route, progressTarget: desktopApp.id, })) return; - setPending(action); - setLocalNotice(""); - setLocalFailure(""); - // Opening the app is not a download, so it gets no shared bar. Terminal - // install cards stay in the center until the user dismisses them. + setInstalling(true); try { - const request = action === "install" ? api.installDesktopAgent(desktopApp.id) : null; - if (request) setTaskCanceller(installTaskID, taskCanceller(request)); - const result = request ? await request : null; - let message: string; - if (action === "open") { - await api.openDesktopAgent(desktopApp.id); - message = t("{name} 已打开", { name: desktopApp.name }); - } else if (result?.status === "installed") { - message = t("{name} 安装完成", { name: desktopApp.name }); - } else if (result?.status === "already-installed") { - message = t("{name} 已安装", { name: desktopApp.name }); - } else { - message = t("官方安装器已启动"); - } + const request = api.installDesktopAgent(desktopApp.id); + setTaskCanceller(installTaskID, taskCanceller(request)); + const result = await request; + const message = result?.status === "installed" + ? t("{name} 安装完成", { name: desktopApp.name }) + : result?.status === "already-installed" + ? t("{name} 已安装", { name: desktopApp.name }) + : t("官方安装器已启动"); // Recorded in the provider, so it still reaches the user if this row // unmounted while the install was running. - if (downloads) finishTask(installTaskID, { kind: "success", message }); - else setLocalNotice(message); + finishTask(installTaskID, { kind: "success", message }); await onChanged(); } catch (error) { - const message = describeFailure(error, t("{name} 操作失败", { name: desktopApp.name }), t).message; - if (downloads) finishTask(installTaskID, { kind: "failure", message }); - else setLocalFailure(message); + finishTask(installTaskID, { kind: "failure", message: describeFailure(error, t("{name} 操作失败", { name: desktopApp.name }), t).message }); } finally { - setPending(""); + setInstalling(false); } }; + + // Opening the app is not a download, so it gets no task and no shared bar: + // the button confirms it in place, and a failure goes to a receipt. + const open = async () => { + setOpening(true); + try { + await api.openDesktopAgent(desktopApp.id); + setOpenFailure(null); + } catch (error) { + setOpenFailure(error); + throw error; + } finally { + setOpening(false); + } + // Not awaited: a slow status refresh would hold the button on its spinner + // after the app is already on screen. + void onChanged(); + }; const menuItems: AgentActionMenuItem[] = desktopApp.installed ? [ ...(desktopApp.id === "chatgpt-desktop" ? [{ id: "migration", @@ -138,15 +139,10 @@ export function DesktopAppSection({ app: desktopApp, onChanged, onSetup, onConfi ) : null} - {failure ?
: null} - {notice ?
: null} {desktopApp.inspectionUnavailable ? (
) : null}
@@ -155,9 +151,9 @@ export function DesktopAppSection({ app: desktopApp, onChanged, onSetup, onConfi
@@ -196,6 +192,11 @@ export function DesktopAppSection({ app: desktopApp, onChanged, onSetup, onConfi {desktopApp.version} ) : null} + {failureMarker ? ( + + ) : null}
@@ -208,25 +209,32 @@ export function DesktopAppSection({ app: desktopApp, onChanged, onSetup, onConfi {t("配置")} ) : null} - + ) : ( - )}
- {desktopApp.configPath ? ( -

- {desktopApp.configSharedWith - ? t("与 {name} 共用配置文件 {path};安装和启动不会改动配置", { name: desktopApp.configSharedWith, path: desktopApp.configPath }) - : t("配置文件:{path}", { path: desktopApp.configPath })} -

- ) : null} + {/* File locations are for whoever wants to look; using the app needs none of them. */} + {/* No local flag in the condition: DownloadProgress reads the shared in-flight state itself, so navigating away and back keeps the bar. */} diff --git a/frontend/src/components/DetailsDisclosure.tsx b/frontend/src/components/DetailsDisclosure.tsx new file mode 100644 index 00000000..8c98e1ee --- /dev/null +++ b/frontend/src/components/DetailsDisclosure.tsx @@ -0,0 +1,40 @@ +import type { ReactNode } from "react"; + +import { useI18n } from "../i18n"; + +export interface DetailRow { + label: string; + value: ReactNode; + /** Paths, IDs and URLs: monospace, and the full value on hover. */ + code?: boolean; + /** Spans the whole width, for values that are a sentence rather than a token. */ + wide?: boolean; +} + +/** + * The "详情" fold on a card or row. Technical facts -- file paths, program + * locations, endpoints, package names -- live here rather than in the row + * itself: a newcomer does not need them to use the Agent, and a developer gets + * them back in one click (docs/ui-friendliness-plan.md, principle 2). Empty + * values are dropped, so callers can pass every fact they know; with nothing + * left to show, there is no fold. + */ +export function DetailsDisclosure({ rows, className = "", children }: { rows: DetailRow[]; className?: string; children?: ReactNode }) { + const { t } = useI18n(); + const shown = rows.filter((row) => row.value !== "" && row.value !== null && row.value !== undefined && row.value !== false); + if (!shown.length && !children) return null; + return ( +
+ {t("详情")} +
+ {shown.map((row) => ( +
+ {row.label} + {row.value} +
+ ))} + {children} +
+
+ ); +} diff --git a/frontend/src/components/EnvironmentSummary.test.tsx b/frontend/src/components/EnvironmentSummary.test.tsx new file mode 100644 index 00000000..174aa4f5 --- /dev/null +++ b/frontend/src/components/EnvironmentSummary.test.tsx @@ -0,0 +1,51 @@ +import { render, screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; + +import type { StatusResponse } from "../types/api"; +import { EnvironmentSummary } from "./EnvironmentSummary"; + +function runtime(id: string, name: string, installed: boolean, version = "") { + return { + id, name, command: id, installed, version, lockedVersion: "1.0.0", managed: false, supported: true, + note: "", license: "", licenseUrl: "", source: "", installPath: "", + }; +} + +function status(overrides: Partial = {}): StatusResponse { + return { + platform: { os: "macos", arch: "arm64", shell: "zsh" }, + runtimes: [runtime("node", "Node.js", true, "22.1.0"), runtime("uv", "uv", false)], + capabilities: { canInstall: {}, missingRuntime: { aider: "uv" }, supportedAgentIds: [] }, + catalog: [{ id: "codex" }, { id: "aider" }], + agents: { codex: { installed: true }, aider: { installed: false }, workbuddy: { installed: true } }, + desktopAgents: [{ id: "workbuddy", installed: true }, { id: "zcode", installed: false }], + ...overrides, + } as unknown as StatusResponse; +} + +function facts() { + return [...screen.getByRole("group", { name: "本机环境" }).children].map((item) => item.textContent); +} + +describe("EnvironmentSummary", () => { + it("names the system, each runtime and how many Agents are installed", () => { + render(); + // Two installed, not three: workbuddy is in agents as the owner of the + // desktop app's profile, and counting that map would count it twice. + expect(facts()).toEqual(["系统macOS · arm64", "Node.js版本 22.1.0", "uv未安装", "已安装的 Agent2 个"]); + }); + + // The default arrival is a desktop Agent, which needs no runtime. A bare "not + // installed" beside it would read as a fault on a machine that has none. + it("says whether the current selection needs a missing runtime", () => { + const { rerender } = render(); + expect(facts()[2]).toBe("uv未安装,当前选择用不到"); + rerender(); + expect(facts()[2]).toBe("uv未安装,当前选择需要"); + }); + + it("reports a machine with nothing installed without a zero", () => { + render(); + expect(facts().at(-1)).toBe("已安装的 Agent还没有"); + }); +}); diff --git a/frontend/src/components/EnvironmentSummary.tsx b/frontend/src/components/EnvironmentSummary.tsx new file mode 100644 index 00000000..b7aa676e --- /dev/null +++ b/frontend/src/components/EnvironmentSummary.tsx @@ -0,0 +1,52 @@ +import { useI18n } from "../i18n"; +import type { StatusResponse } from "../types/api"; + +const OS_NAMES: Record = { macos: "macOS", windows: "Windows", linux: "Linux" }; + +interface EnvironmentSummaryProps { + status: StatusResponse; + selectedAgentIds: string[]; +} + +/** + * What was found on this machine, shown before the first choice. A missing + * runtime is only a problem for an Agent that installs through it, so each one + * says whether the current selection needs it instead of reading as a fault. + */ +export function EnvironmentSummary({ status, selectedAgentIds }: EnvironmentSummaryProps) { + const { t } = useI18n(); + const runtimes = (status.runtimes ?? []).filter((runtime) => runtime.supported || runtime.installed); + const needed = new Set( + selectedAgentIds + .filter((id) => !status.agents?.[id]?.installed) + .map((id) => status.capabilities.missingRuntime?.[id]) + .filter(Boolean), + ); + // Counted from the two lists the page shows. status.agents also holds the + // profile owners of desktop Agents, which would count those twice. + const installed = (status.catalog ?? []).filter((item) => status.agents?.[item.id]?.installed).length + + (status.desktopAgents ?? []).filter((app) => app.installed).length; + + return ( +
+ + {t("系统")} + {OS_NAMES[status.platform.os] ?? status.platform.os} · {status.platform.arch} + + {runtimes.map((runtime) => ( + + {runtime.name} + {runtime.installed + ? runtime.version ? t("版本 {version}", { version: runtime.version }) : t("已安装") + : !selectedAgentIds.length ? t("未安装") + : needed.has(runtime.id) ? t("未安装,当前选择需要") + : t("未安装,当前选择用不到")} + + ))} + + {t("已安装的 Agent")} + {installed ? t("{count} 个", { count: installed }) : t("还没有")} + +
+ ); +} diff --git a/frontend/src/components/FeedbackViewport.tsx b/frontend/src/components/FeedbackViewport.tsx new file mode 100644 index 00000000..46e43699 --- /dev/null +++ b/frontend/src/components/FeedbackViewport.tsx @@ -0,0 +1,87 @@ +import { CheckCircle2, CircleAlert, TriangleAlert, X } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; + +import { useI18n } from "../i18n"; +import { FEEDBACK_SUCCESS_MS, type FeedbackItem, feedbackPersists, useFeedback } from "../state/FeedbackContext"; + +const icons = { success: CheckCircle2, failure: CircleAlert, warning: TriangleAlert }; + +function FeedbackToast({ item, onDismiss }: { item: FeedbackItem; onDismiss: () => void }) { + const { t } = useI18n(); + const [expanded, setExpanded] = useState(false); + const [paused, setPaused] = useState(false); + // Time left for a success, kept across pauses so hovering twice does not + // restart the full three seconds. + const remaining = useRef(FEEDBACK_SUCCESS_MS); + const Icon = icons[item.tone]; + const persists = feedbackPersists(item.tone); + + useEffect(() => { + if (persists || paused || expanded) return; + const startedAt = Date.now(); + const timer = setTimeout(onDismiss, remaining.current); + return () => { + clearTimeout(timer); + remaining.current = Math.max(0, remaining.current - (Date.now() - startedAt)); + }; + }, [expanded, onDismiss, paused, persists]); + + return ( +
setPaused(true)} + onMouseLeave={() => setPaused(false)} + onFocus={() => setPaused(true)} + onBlur={(event) => { if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setPaused(false); }} + onKeyDown={(event) => { + if (event.key !== "Escape") return; + event.stopPropagation(); + onDismiss(); + }} + > +
+
+ {expanded && item.detail ?

{item.detail}

: null} +
+ ); +} + +/** + * The receipt overlay, top right of the page body. PageScaffold renders it in + * the body's own grid cell, so it covers a corner of the content instead of + * taking a row of the layout: nothing on the page moves when it appears. + */ +export function FeedbackViewport() { + const { t } = useI18n(); + const { available, items, dismiss } = useFeedback(); + if (!available) return null; + const current = items[0]; + return ( + // Always mounted, even empty: a live region inserted together with its + // first message is not reliably announced. +
+ {current ? dismiss(current.id)} /> : null} +
+ ); +} diff --git a/frontend/src/components/FirstTaskSection.test.tsx b/frontend/src/components/FirstTaskSection.test.tsx new file mode 100644 index 00000000..876ad213 --- /dev/null +++ b/frontend/src/components/FirstTaskSection.test.tsx @@ -0,0 +1,99 @@ +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { MemoryRouter } from "react-router-dom"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { api } from "../backend/api"; +import { BootAgentApiError } from "../backend/errors"; +import type { FirstTaskResult } from "../types/api"; +import { FirstTaskSection } from "./FirstTaskSection"; + +const DIRECTORY = "/tmp/bootagent-first-task-123"; + +function result(overrides: Partial = {}): FirstTaskResult { + return { agent_id: "codex", ok: true, directory: DIRECTORY, files: ["index.html"], log: "Created index.html", ...overrides }; +} + +async function renderSection(agentId = "codex") { + vi.spyOn(api, "firstTaskAgents").mockResolvedValue([{ id: "codex", name: "Codex" }]); + const page = render(); + await waitFor(() => expect(api.firstTaskAgents).toHaveBeenCalled()); + return page; +} + +describe("FirstTaskSection", () => { + afterEach(() => vi.restoreAllMocks()); + + it("is absent for an Agent that cannot run unattended", async () => { + const run = vi.spyOn(api, "runFirstTask"); + const { container } = await renderSection("opencode"); + + expect(container.innerHTML).toBe(""); + expect(run).not.toHaveBeenCalled(); + }); + + // The run is a billed request to the user's own Provider. It has to be said + // before the button, and nothing may be sent until the button is pressed. + it("says the run is billed and waits to be asked", async () => { + const run = vi.spyOn(api, "runFirstTask").mockResolvedValue(result()); + await renderSection(); + + const start = await screen.findByRole("button", { name: "开始" }); + expect(screen.getByText(/真实的模型调用,由模型服务按它的价格计费/)).toBeTruthy(); + expect(screen.getByText(/只会写入这个目录/)).toBeTruthy(); + expect(run).not.toHaveBeenCalled(); + + fireEvent.click(start); + expect(run).toHaveBeenCalledTimes(1); + expect(run).toHaveBeenCalledWith("codex", "zh-CN"); + }); + + it("shows where the page is and what was written", async () => { + vi.spyOn(api, "runFirstTask").mockResolvedValue(result({ files: ["assets/style.css", "index.html"] })); + await renderSection(); + fireEvent.click(await screen.findByRole("button", { name: "开始" })); + + expect((await screen.findByRole("status")).textContent).toContain("Codex 写好了"); + expect(screen.getByText(DIRECTORY)).toBeTruthy(); + expect(screen.getAllByRole("listitem").map((item) => item.textContent)).toEqual(["assets/style.css", "index.html"]); + // The record is there, behind a disclosure rather than poured onto the page. + expect(screen.queryByText("Created index.html")).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: /查看运行记录/ })); + expect(screen.getByText("Created index.html")).toBeTruthy(); + }); + + it("offers a next step when the Agent wrote nothing", async () => { + const run = vi.spyOn(api, "runFirstTask").mockResolvedValue(result({ ok: false, directory: "", files: [], log: "401 Unauthorized" })); + await renderSection(); + fireEvent.click(await screen.findByRole("button", { name: "开始" })); + + expect((await screen.findByRole("alert")).textContent).toContain("Codex 没有写出任何文件"); + expect(screen.getByRole("button", { name: "检查模型服务" })).toBeTruthy(); + // The reason is in the record, so a failure opens it without being asked. + expect(screen.getByText("401 Unauthorized")).toBeTruthy(); + + fireEvent.click(screen.getByRole("button", { name: "重试" })); + expect(run).toHaveBeenCalledTimes(2); + }); + + // Files exist, so they are shown, but the Agent did not finish cleanly and the + // page may be half written. Calling that a success would misreport it. + it("keeps the files of a run that ended badly without calling it done", async () => { + vi.spyOn(api, "runFirstTask").mockResolvedValue(result({ ok: false })); + await renderSection(); + fireEvent.click(await screen.findByRole("button", { name: "开始" })); + + expect((await screen.findByRole("alert")).textContent).toContain("Codex 没有正常结束"); + expect(screen.getByText(DIRECTORY)).toBeTruthy(); + expect(screen.queryByRole("status")).toBeNull(); + }); + + it("reports a run that could not start", async () => { + vi.spyOn(api, "runFirstTask").mockRejectedValue(new BootAgentApiError("The selected Agent is not installed", "PREREQUISITE_MISSING", false, 400)); + await renderSection(); + fireEvent.click(await screen.findByRole("button", { name: "开始" })); + + expect(await screen.findByRole("alert")).toBeTruthy(); + expect(screen.getByRole("button", { name: "重试" })).toBeTruthy(); + expect(screen.queryByRole("status")).toBeNull(); + }); +}); diff --git a/frontend/src/components/FirstTaskSection.tsx b/frontend/src/components/FirstTaskSection.tsx new file mode 100644 index 00000000..0fd185f2 --- /dev/null +++ b/frontend/src/components/FirstTaskSection.tsx @@ -0,0 +1,121 @@ +import { Copy, ExternalLink, Play, RefreshCw } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; +import { useNavigate } from "react-router-dom"; + +import { api, failureLine, isCancellationError } from "../backend/api"; +import { useI18n } from "../i18n"; +import type { FirstTaskResult } from "../types/api"; +import { copyToClipboard } from "../utils/clipboard"; +import { LogDisclosure } from "./LogDisclosure"; + +/** + * Offers one small, real task to an Agent that has just been installed: it + * writes a page in a temporary directory of its own. Rendered only for Agents + * the backend can drive unattended, so it is absent rather than disabled for + * the rest. + * + * Nothing is sent until the button is pressed: the run is a billed request. + */ +export function FirstTaskSection({ agentId }: { agentId: string }) { + const { t, locale } = useI18n(); + const navigate = useNavigate(); + // Empty until the backend confirms it can drive this Agent, and then its name. + const [agentName, setAgentName] = useState(""); + const [running, setRunning] = useState(false); + const [result, setResult] = useState(null); + const [failure, setFailure] = useState(""); + const [copied, setCopied] = useState(false); + const request = useRef | null>(null); + + useEffect(() => { + let active = true; + void api.firstTaskAgents() + .then((agents) => { if (active) setAgentName(agents.find((agent) => agent.id === agentId)?.name ?? ""); }) + .catch(() => {}); + return () => { active = false; }; + }, [agentId]); + // Leaving the page ends the run: nobody would see its result, and it would + // keep spending on the user's account. + useEffect(() => () => { void request.current?.cancel?.(); }, []); + + if (!agentName) return null; + + const run = async () => { + setRunning(true); + setResult(null); + setFailure(""); + setCopied(false); + const pending = api.runFirstTask(agentId, locale); + request.current = pending; + try { + setResult(await pending); + } catch (error) { + if (!isCancellationError(error)) setFailure(failureLine(error, t("小任务没能运行"), t)); + } finally { + request.current = null; + setRunning(false); + } + }; + + const files = result?.files ?? []; + const problem = failure + || (result && !result.ok + ? files.length + ? t("{agent} 没有正常结束,下面的文件可能不完整", { agent: agentName }) + : t("{agent} 没有写出任何文件", { agent: agentName }) + : ""); + const finished = Boolean(result || failure); + + return ( +
+

{t("跑一个小任务试试")}

+

{t("让 {agent} 在一个临时目录里写一个介绍页,只会写入这个目录。这是真实的模型调用,由模型服务按它的价格计费", { agent: agentName })}

+ {result?.ok ? ( +
+ {t("{agent} 写好了,文件在下面这个目录", { agent: agentName })} +
+ ) : null} + {problem ?
{problem}
: null} + {result?.directory ? ( +
+ {result.directory} + +
    + {files.map((file) =>
  • {file}
  • )} +
+
+ ) : null} +
+ {running ? ( + <> + + + + ) : !finished ? ( + + ) : problem ? ( + <> + + + + ) : null} +
+ {result?.log ? : null} +
+ ); +} diff --git a/frontend/src/components/LogDisclosure.tsx b/frontend/src/components/LogDisclosure.tsx index 26422610..7cf6fb3c 100644 --- a/frontend/src/components/LogDisclosure.tsx +++ b/frontend/src/components/LogDisclosure.tsx @@ -3,7 +3,7 @@ import { useEffect, useState } from "react"; import { useI18n } from "../i18n"; -export function LogDisclosure({ log, open: openByParent = false, showEmpty = false }: { log: string; open?: boolean; showEmpty?: boolean }) { +export function LogDisclosure({ log, open: openByParent = false, showEmpty = false, label }: { log: string; open?: boolean; showEmpty?: boolean; label?: string }) { const { t } = useI18n(); const [open, setOpen] = useState(openByParent); useEffect(() => { @@ -14,7 +14,7 @@ export function LogDisclosure({ log, open: openByParent = false, showEmpty = fal
{open ?
{log}
: null} diff --git a/frontend/src/components/ModelCheckNotice.test.tsx b/frontend/src/components/ModelCheckNotice.test.tsx index a07df9bc..e0734f22 100644 --- a/frontend/src/components/ModelCheckNotice.test.tsx +++ b/frontend/src/components/ModelCheckNotice.test.tsx @@ -1,5 +1,5 @@ import { fireEvent, render, screen } from "@testing-library/react"; -import { MemoryRouter, Route, Routes } from "react-router-dom"; +import { MemoryRouter } from "react-router-dom"; import { describe, expect, it, vi } from "vitest"; import { translate } from "../i18n"; @@ -20,26 +20,35 @@ function check(overrides: Partial = {}): ProfileModelCheck { }; } -function renderNotice(value: ProfileModelCheck) { +function renderNotice(value: ProfileModelCheck, onUseConversion?: () => void) { return render( - - "Codex"} returnTo="/profiles" onDismiss={vi.fn()} />} /> - API 协议适配设置} /> - + "Codex"} returnTo="/profiles" onUseConversion={onUseConversion} onDismiss={vi.fn()} /> , ); } -describe("Codex model check guidance", () => { - it("offers an explicit adapter path when the Responses request is refused", () => { - renderNotice(check()); +const hint = "这个模型服务可能不支持该 Agent 的请求格式,可以换一个模型,或用兼容模式在本机转换"; + +describe("model check compatibility mode remedy", () => { + it.each>([ + { protocol: "responses" }, + { protocol: "anthropic", detail: "" }, + ])("offers compatibility mode when $protocol is refused", (overrides) => { + const useConversion = vi.fn(); + renderNotice(check(overrides), useConversion); expect(screen.getByRole("alert").textContent).toContain("HTTP 400"); - expect(screen.getByRole("alert").textContent).toContain("does not support endpoint: responses"); - expect(screen.getByText("Codex 使用 Responses API。请选择支持 Responses 的模型;如果模型服务仅支持 Chat Completions,可使用 API 协议适配,并应用适配器生成的 Codex 配置模版。")).toBeTruthy(); - fireEvent.click(screen.getByRole("button", { name: "打开 API 协议适配" })); - expect(screen.getByText("API 协议适配设置")).toBeTruthy(); + expect(screen.getByText(hint)).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "使用兼容模式" })); + expect(useConversion).toHaveBeenCalledOnce(); + }); + + it("keeps the hint but offers no button where no Agent can use compatibility mode", () => { + renderNotice(check()); + + expect(screen.getByText(hint)).toBeTruthy(); + expect(screen.queryByRole("button", { name: "使用兼容模式" })).toBeNull(); }); it.each>([ @@ -47,19 +56,18 @@ describe("Codex model check guidance", () => { { reason: "no_key", status: "unverified" }, { reason: "network", status: "unverified" }, { reason: "transient", status: "unverified", httpStatus: 500 }, - { protocol: "anthropic" }, { protocol: "openai" }, { status: "available", reason: undefined }, - ])("does not suggest protocol adaptation for $reason over $protocol", (overrides) => { - renderNotice(check(overrides)); + ])("does not suggest compatibility mode for $reason over $protocol", (overrides) => { + renderNotice(check(overrides), vi.fn()); - expect(screen.queryByRole("button", { name: "打开 API 协议适配" })).toBeNull(); - expect(screen.queryByText(/Codex 使用 Responses API/)).toBeNull(); + expect(screen.queryByRole("button", { name: "使用兼容模式" })).toBeNull(); + expect(screen.queryByText(hint)).toBeNull(); }); - it("provides the Responses remedy in English", () => { + it("provides the remedy in English", () => { const parts = describeModelCheck(check(), (key, values) => translate("en", key, values), () => "Codex", ", "); - expect(parts.hint).toBe("Codex uses the Responses API. Choose a model that supports Responses. If the provider only supports Chat Completions, use the API protocol adapter and apply its generated Codex Profile."); + expect(parts.hint).toBe("This model service may not accept this Agent's request format; try another model, or use compatibility mode to convert on this computer"); }); }); diff --git a/frontend/src/components/ModelCheckNotice.tsx b/frontend/src/components/ModelCheckNotice.tsx index d48a5b6a..51dbce84 100644 --- a/frontend/src/components/ModelCheckNotice.tsx +++ b/frontend/src/components/ModelCheckNotice.tsx @@ -3,6 +3,7 @@ import { useNavigate } from "react-router-dom"; import type { Translate } from "../i18n"; import { useI18n } from "../i18n"; +import { canConvertProtocol } from "../state/conversion"; import type { ProfileModelCheck } from "../types/api"; const protocolLabels: Record = { @@ -62,8 +63,10 @@ export function describeModelCheck(check: ProfileModelCheck, t: Translate, nameO reason, agents: agents ? t("受影响的 Agent:{agents}", { agents }) : "", detail: check.detail ? t("模型服务返回:{detail}", { detail: check.detail }) : "", - hint: check.reason === "refused" && check.protocol === "responses" - ? t("Codex 使用 Responses API。请选择支持 Responses 的模型;如果模型服务仅支持 Chat Completions,可使用 API 协议适配,并应用适配器生成的 Codex 配置模版。") + // Claude Code and Codex each speak a format of their own, and compatibility + // mode is what lets a Chat Completions-only service serve them. + hint: check.reason === "refused" && canConvertProtocol(check.protocol) + ? t("这个模型服务可能不支持该 Agent 的请求格式,可以换一个模型,或用兼容模式在本机转换") : "", }; } @@ -115,6 +118,9 @@ interface ModelCheckNoticeProps { /** Saves the Profile back to check.previousModel. Omitted where no save path exists. */ onRevert?: () => void; onRecheck?: () => void; + /** Switches the affected Agents to compatibility mode in place. Omitted + * where none of them can use it, which leaves the hint as the only remedy. */ + onUseConversion?: () => void; onDismiss: () => void; } @@ -125,7 +131,7 @@ interface ModelCheckNoticeProps { * is offered follows from why the check failed -- going back to the old model * cannot fix a rejected key. */ -export function ModelCheckNotice({ check, providerId, nameOf, returnTo, profileName, busy, onRevert, onRecheck, onDismiss }: ModelCheckNoticeProps) { +export function ModelCheckNotice({ check, providerId, nameOf, returnTo, profileName, busy, onRevert, onRecheck, onUseConversion, onDismiss }: ModelCheckNoticeProps) { const { t, locale } = useI18n(); const navigate = useNavigate(); const parts = describeModelCheck(check, t, nameOf, locale === "en" ? ", " : "、"); @@ -148,9 +154,9 @@ export function ModelCheckNotice({ check, providerId, nameOf, returnTo, profileN {parts.hint ? {parts.hint} : null}
- {parts.hint ? ( - ) : null} {canRevert ? ( diff --git a/frontend/src/components/NavigationSidebar.tsx b/frontend/src/components/NavigationSidebar.tsx index 396b8e85..da2b927d 100644 --- a/frontend/src/components/NavigationSidebar.tsx +++ b/frontend/src/components/NavigationSidebar.tsx @@ -16,7 +16,7 @@ const navItems: Array<{ to: string; label: TranslationKey; icon: typeof Gauge }> { to: "/mcp", label: "MCP 服务器", icon: Network }, { to: "/skills", label: "Skills", icon: Sparkles }, { to: "/multimodal", label: "多模态能力", icon: Images }, - { to: "/conversion", label: "API 协议适配", icon: Radio }, + { to: "/conversion", label: "兼容模式", icon: Radio }, ]; export function NavigationSidebar() { diff --git a/frontend/src/components/PageScaffold.tsx b/frontend/src/components/PageScaffold.tsx index 44ec41c7..705da7ea 100644 --- a/frontend/src/components/PageScaffold.tsx +++ b/frontend/src/components/PageScaffold.tsx @@ -2,6 +2,7 @@ import { ArrowLeft, ArrowRight } from "lucide-react"; import type { PropsWithChildren, ReactNode } from "react"; import { useI18n } from "../i18n"; +import { FeedbackViewport } from "./FeedbackViewport"; import { SetupStepper } from "./SetupStepper"; interface PageScaffoldProps extends PropsWithChildren { @@ -53,6 +54,7 @@ export function PageScaffold({ {stepper ? : null}
{children}
+
{onBack ? ( diff --git a/frontend/src/components/ProviderModelPicker.tsx b/frontend/src/components/ProviderModelPicker.tsx index 1b5210a7..b728e3c0 100644 --- a/frontend/src/components/ProviderModelPicker.tsx +++ b/frontend/src/components/ProviderModelPicker.tsx @@ -1,6 +1,7 @@ import { useEffect, useState } from "react"; import { api, describeFailure } from "../backend/api"; +import { modelListMessage } from "../backend/failureCopy"; import { useI18n } from "../i18n"; import { ModelPicker } from "./ModelPicker"; @@ -47,9 +48,10 @@ export function ProviderModelPicker({ provider, protocol, hasKey, value, onChang setMessage(""); void api.models({ provider, apiBaseUrl: "", apiKey: "" }).then((result) => { if (cancelled) return; + const listed = modelListMessage(result, t); setModels(result.models ?? []); - setSuccess(result.ok); - setMessage(result.message.replace(/^Found (\d+) models\.$/, (_, count: string) => t("找到 {count} 个模型", { count }))); + setSuccess(listed.ok); + setMessage(listed.message); }).catch((error) => { if (cancelled) return; setModels([]); @@ -63,12 +65,17 @@ export function ProviderModelPicker({ provider, protocol, hasKey, value, onChang return (
- {loading ?
{t("正在读取模型列表")}
: null} - {message && !loading ?
{message}
: null} {/* collapsible: every caller is a compact form where an always-open list pushed the footer off screen. The arrow is also the only affordance that said the discovered models were selectable at all. */} + {/* The listing's status is a line in a reserved slot under the field + (docs/ui-interaction-plan.md §3.5). As a loading block and then a + notice above it, the field itself jumped down and back while the user + was reaching for it. */} + + {loading ? t("正在读取模型列表") : message} + {hint ? {hint} : null}
); diff --git a/frontend/src/components/ProviderSegment.test.tsx b/frontend/src/components/ProviderSegment.test.tsx new file mode 100644 index 00000000..dcb1a215 --- /dev/null +++ b/frontend/src/components/ProviderSegment.test.tsx @@ -0,0 +1,43 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; + +import type { StatusResponse } from "../types/api"; +import { ProviderSegment, providerServes } from "./ProviderSegment"; + +const providers = { + both: { name: "Both", home: "", base_url: "https://both.example/v1", anthropic_base_url: "https://both.example/anthropic", has_key: true }, + "chat-only": { name: "Chat only", home: "", base_url: "https://chat.example/v1", has_key: true }, + "bootagent-converter-anthropic": { name: "BootAgent Converter anthropic", home: "", base_url: "http://127.0.0.1:8787/v1", anthropic_base_url: "http://127.0.0.1:8787", has_key: true }, +} as unknown as StatusResponse["providers"]; + +function open(protocol: "anthropic" | "responses" | "", convertible = false) { + render(); + fireEvent.click(screen.getByRole("combobox", { name: "模型服务" })); + return screen.getAllByRole("option"); +} + +describe("ProviderSegment", () => { + it("never offers the adapter's own Providers", () => { + const options = open(""); + expect(options.map((option) => option.textContent)).not.toContain("BootAgent Converter anthropic"); + }); + + it("says why a Provider cannot serve the step instead of only greying it out", () => { + const chatOnly = open("anthropic").find((option) => option.textContent?.startsWith("Chat only")); + expect(chatOnly?.textContent).toBe("Chat only(不支持此格式)"); + expect(chatOnly).toHaveAttribute("aria-disabled", "true"); + }); + + it("lets a step that can use compatibility mode pick a Chat Completions-only Provider", () => { + const chatOnly = open("anthropic", true).find((option) => option.textContent?.startsWith("Chat only")); + expect(chatOnly?.textContent).toBe("Chat only"); + expect(chatOnly).not.toHaveAttribute("aria-disabled"); + }); + + it("matches each protocol to the endpoint it is sent to", () => { + expect(providerServes(providers.both, "anthropic")).toBe(true); + expect(providerServes(providers["chat-only"], "anthropic")).toBe(false); + expect(providerServes(providers["chat-only"], "anthropic", true)).toBe(true); + expect(providerServes(providers["chat-only"], "responses")).toBe(true); + }); +}); diff --git a/frontend/src/components/ProviderSegment.tsx b/frontend/src/components/ProviderSegment.tsx index 5ac1d49c..b97f2908 100644 --- a/frontend/src/components/ProviderSegment.tsx +++ b/frontend/src/components/ProviderSegment.tsx @@ -1,22 +1,37 @@ import { Plus } from "lucide-react"; import { useI18n } from "../i18n"; +import { userProviders } from "../state/conversion"; import { byProviderCreatedAt } from "../state/ranking"; import type { ProtocolId, ProviderId, StatusResponse } from "../types/api"; import { SelectField } from "./SelectField"; +/** + * Whether a Provider has the endpoint `protocol` is sent to. Anthropic Messages + * has an address of its own; both OpenAI protocols share the base URL. + * `convertible` also accepts a Provider that only has the OpenAI address, for a + * step where compatibility mode can bridge the difference. + */ +export function providerServes(provider: StatusResponse["providers"][string], protocol: ProtocolId | "" | undefined, convertible = false): boolean { + if (!protocol) return true; + if (protocol === "anthropic") return Boolean(provider.anthropic_base_url || (convertible && provider.base_url)); + return Boolean(provider.base_url); +} + export function ProviderSegment({ value, providers, onAdd, onChange, protocol, + convertible = false, }: { value: ProviderId; providers: StatusResponse["providers"]; onAdd: () => void; onChange: (value: ProviderId) => void; protocol?: ProtocolId | ""; + convertible?: boolean; }) { const { t } = useI18n(); return ( @@ -30,11 +45,18 @@ export function ProviderSegment({ label={t("模型服务")} value={value} onChange={onChange} - options={byProviderCreatedAt(providers).map(([id, provider]) => ({ - value: id, - label: provider.name, - disabled: Boolean(protocol) && (protocol === "anthropic" ? !provider.anthropic_base_url : !provider.base_url), - }))} + // The adapter's own Providers are an implementation detail of + // compatibility mode and are never chosen by hand. A Provider that + // cannot serve this step stays listed and says why, rather than + // greying out with no explanation. + options={byProviderCreatedAt(userProviders(providers)).map(([id, provider]) => { + const disabled = !providerServes(provider, protocol, convertible); + return { + value: id, + label: disabled ? t("{name}(不支持此格式)", { name: provider.name }) : provider.name, + disabled, + }; + })} />
))}
- {missing.length ? ( -

- {root - ? t("运行时会安装到 {dir},并写入登录 PATH,不需要管理员权限").replace("{dir}", root) - : t("运行时会安装到 BootAgent 的托管目录,并写入登录 PATH,不需要管理员权限")} -

- ) : null} + {missing.length ?

{t("会装在 BootAgent 自己的目录里,不需要管理员权限。")}

: null} + ({ label: t("{name} 下载地址", { name: runtime.name }), value: runtime.source, code: true })), + ]} + /> ); return (
- + {body}
diff --git a/frontend/src/components/SelectField.test.tsx b/frontend/src/components/SelectField.test.tsx index f999b31e..55f698a0 100644 --- a/frontend/src/components/SelectField.test.tsx +++ b/frontend/src/components/SelectField.test.tsx @@ -1,4 +1,4 @@ -import { render, screen } from "@testing-library/react"; +import { fireEvent, render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { useState } from "react"; import { describe, expect, it } from "vitest"; @@ -102,6 +102,35 @@ describe("SelectField", () => { expect(screen.queryByRole("listbox")).toBeNull(); }); + describe("scrolling while the list is open", () => { + /** jsdom lays nothing out, so the trigger's position is whatever this says. */ + function placeTriggerAt(top: number) { + trigger().getBoundingClientRect = () => ({ top, bottom: top + 36, left: 0, right: 200, width: 200, height: 36, x: 0, y: top, toJSON: () => ({}) }); + } + + // The list is positioned from the trigger, so a scroll that moves the + // trigger leaves it in the wrong place. + it("closes when the scroll moved the trigger", async () => { + render(); + placeTriggerAt(100); + await userEvent.click(trigger()); + placeTriggerAt(40); + fireEvent.scroll(document.body); + expect(screen.queryByRole("listbox")).toBeNull(); + }); + + // Opening the list makes the browser scroll its container to show it. That + // scroll arrives after the list has been placed, and closing on it shut the + // list the moment it opened on a page that was scrolled down. + it("stays open when the scroll left the trigger where it was", async () => { + render(); + placeTriggerAt(100); + await userEvent.click(trigger()); + fireEvent.scroll(document.body); + expect(screen.getByRole("listbox")).toBeTruthy(); + }); + }); + it("jumps to an option by typing its first letters", async () => { render(); trigger().focus(); diff --git a/frontend/src/components/SelectField.tsx b/frontend/src/components/SelectField.tsx index 270cb8f6..268c05fd 100644 --- a/frontend/src/components/SelectField.tsx +++ b/frontend/src/components/SelectField.tsx @@ -50,6 +50,7 @@ export function SelectField({ value, options, onChange, label, id, className = " const [dropUp, setDropUp] = useState(false); const triggerRef = useRef(null); const listRef = useRef(null); + const openedAt = useRef({ top: 0, left: 0 }); const typeahead = useRef({ query: "", at: 0 }); const selectedIndex = options.findIndex((option) => option.value === value); @@ -76,6 +77,7 @@ export function SelectField({ value, options, onChange, label, id, className = " const list = listRef.current; if (!trigger || !list) return; const box = trigger.getBoundingClientRect(); + openedAt.current = { top: box.top, left: box.left }; // The margin covers the 5px CSS offset plus room for the shadow, and gives // the sidebar pickers -- which sit near the bottom edge -- a reason to flip // before the list is merely technically on screen with nothing to spare. @@ -95,15 +97,22 @@ export function SelectField({ value, options, onChange, label, id, className = " const target = event.target as Node; if (!triggerRef.current?.contains(target) && !listRef.current?.contains(target)) close(false); }; - // Any scroll or resize invalidates the measured position above. - const onReflow = () => close(false); + // A resize invalidates the measured position above. A scroll only does if it + // moved the trigger: scroll events are delivered a frame late, so one from + // just before the list opened arrives after it, with the trigger already + // where it was measured. + const onResize = () => close(false); + const onScroll = () => { + const box = triggerRef.current?.getBoundingClientRect(); + if (!box || box.top !== openedAt.current.top || box.left !== openedAt.current.left) close(false); + }; document.addEventListener("pointerdown", onPointerDown); - window.addEventListener("resize", onReflow); - window.addEventListener("scroll", onReflow, true); + window.addEventListener("resize", onResize); + window.addEventListener("scroll", onScroll, true); return () => { document.removeEventListener("pointerdown", onPointerDown); - window.removeEventListener("resize", onReflow); - window.removeEventListener("scroll", onReflow, true); + window.removeEventListener("resize", onResize); + window.removeEventListener("scroll", onScroll, true); }; }, [open]); diff --git a/frontend/src/i18n.tsx b/frontend/src/i18n.tsx index 87dfd10b..856619f5 100644 --- a/frontend/src/i18n.tsx +++ b/frontend/src/i18n.tsx @@ -33,7 +33,6 @@ const english = { "继续卸载": "Continue uninstall", "可卸载": "Removable", "不可卸载": "Not removable", - "检测到的安装实例": "Detected installations", "选择目标 Agent": "Select target Agents", "没有可管理目标": "No compatible Agent targets", "导入预览为空": "Import preview is empty", @@ -50,7 +49,6 @@ const english = { "导入将覆盖已有配置:{names}": "The import will overwrite existing configuration: {names}", "导入预览新增:{names};覆盖:{conflicts}": "Import preview - new: {names}; overwrite: {conflicts}", "无": "None", - "已导入 BootAgent,可在 Skills 页面选择目标 Agent": "Imported into BootAgent; select target Agents on the Skills page", "确认导入并应用": "Confirm import and apply", "请选择至少一个目标 Agent": "Select at least one target Agent", "导入并应用完成": "Imported and applied", @@ -99,7 +97,6 @@ const english = { "开机自启动": "Launch at login", "登录系统后自动启动 BootAgent": "Start BootAgent automatically when you log in", "暂不启用": "Not now", - "API 转换已启用,是否让 BootAgent 随系统启动?": "API conversion is enabled. Start BootAgent automatically when you log in?", "API 模式:": "API mode: ", "无法保存开机自启动设置": "Could not save the launch-at-login setting", "启动 CLI Agent 的终端": "Terminal for launching CLI Agents", @@ -112,9 +109,6 @@ const english = { "每个目标分别保留历史版本,默认保留 3 个": "Keep history per target; the default is 3 versions", "无法保存备份设置": "Could not save the backup setting", "无法读取备份设置": "Could not read the backup setting", - "无法读取格式转换设置": "Could not read the format conversion settings", - "无法保存格式转换设置": "Could not save the format conversion settings", - "无法切换格式转换": "Could not change format conversion state", "启动格式转换": "Start format conversion", "停止格式转换": "Stop format conversion", "格式转换状态": "Format conversion status", @@ -122,10 +116,8 @@ const english = { "格式转换当前已停止": "Format conversion is stopped", "监听本机端口并将请求转发到目标 Profile": "Listen on a local port and forward requests to the target Profile", "本地格式转换": "Local format conversion", - "格式转换设置": "Format conversion settings", "启用本地 API 格式转换": "Enable local API format conversion", "将 Anthropic Messages、OpenAI Responses 和 Chat Completions 转发到目标 Profile": "Forward Anthropic Messages, OpenAI Responses, and Chat Completions to the target Profile", - "Chat Completions 模型": "Chat Completions model", "目标 Profile": "Target Profile", "监听地址": "Listen address", "本地 API Key": "Local API key", @@ -134,50 +126,29 @@ const english = { "启动时自动生成": "Generated automatically on start", "重新生成 Key": "Regenerate key", "无法重新生成本地 Key": "Unable to regenerate the local key", - "本地协议适配端口不可用": "The local protocol adapter port is unavailable", - "关闭占用该端口的程序,或在高级设置中更换端口": "Close the program using that port, or choose another port in advanced settings", - "协议适配端到端验证失败": "Protocol adaptation end-to-end verification failed", - "检查上游配置模板、模型服务余额和网络后重试": "Check the upstream Profile, model service balance, and network, then retry", - "协议适配失败且未能完整恢复原配置": "Protocol adaptation failed and the previous configuration could not be fully restored", - "保留 BootAgent 运行并检查 Claude Desktop 与协议适配设置": "Keep BootAgent running and inspect the Claude Desktop and protocol adapter settings", + "兼容模式需要的本机端口被占用": "The local port compatibility mode needs is in use", + "关闭占用端口的程序,或在兼容模式的高级设置里换一个端口": "Close the program using the port, or choose another port in compatibility mode's advanced settings", + "兼容模式没有通过测试": "Compatibility mode did not pass its test", + "检查所选模型服务的余额和网络后重试": "Check the chosen model service's balance and the network, then try again", + "兼容模式开启失败,原来的设置未能完整恢复": "Compatibility mode could not be turned on, and the previous settings were not fully restored", + "请保持 BootAgent 运行,并到兼容模式页面检查": "Keep BootAgent running and check the compatibility mode page", "Claude Desktop 使用基础地址,保存时将调整为 {url}": "Claude Desktop uses the base address. It will be saved as {url}.", - "Anthropic 模型": "Anthropic model", - "Responses 模型": "Responses model", - "保存格式转换设置": "Save format conversion settings", "API 协议适配": "API protocol adapter", "启用协议适配": "Enable protocol adaptation", "启用协议适配并应用": "Enable adapter and apply", - "启用并应用": "Enable and apply", - "BootAgent 将在本机启动协议适配服务,并自动把 Claude Desktop 指向该服务。是否继续?": "BootAgent will start the local protocol adapter and point Claude Desktop to it automatically. Continue?", - "正在检查模型服务的协议兼容性": "Checking protocol compatibility", - "无法检查协议兼容性": "Unable to check protocol compatibility", "该模型服务不能直接使用 Claude Desktop 所需的 Anthropic Messages。BootAgent 可以在本机转换请求格式。": "This model service cannot be used directly with the Anthropic Messages API required by Claude Desktop. BootAgent can translate requests locally.", - "无法确认该配置模版可以通过协议适配使用": "This profile could not be verified for protocol adaptation", "让只支持某一种 API 协议的 Agent 也能用上这个模型服务": "Let an Agent that speaks only one API protocol use a model service anyway", "将 Responses 与 Messages 请求转换为目标服务支持的 Chat Completions": "Convert Responses and Messages requests into Chat Completions supported by the target service", - "服务状态": "Service status", - "选择目标配置后即可启动": "Select a target profile to start", - "还没有可用的 Chat Completions 配置模板": "No Chat Completions profile is available yet", "创建配置模板": "Create profile", - "适用 Agent": "Compatible Agents", - "{count} 个可使用": "{count} available", - "当前没有可使用协议适配的 Agent": "No installed Agent can use protocol adaptation yet", "查看环境总览": "View environment overview", "了解协议适配": "About protocol adaptation", - "不同 Agent 使用的 API 协议并不相同。Codex 使用 OpenAI Responses,Claude Code 使用 Anthropic Messages,其他 Agent 可能使用 Chat Completions。": "Agents use different API protocols. Codex uses OpenAI Responses, Claude Code uses Anthropic Messages, and other Agents may use Chat Completions.", - "BootAgent 只在本机转换请求格式,再把请求发往上方选中的配置模板;模型与凭据仍由该配置模板管理。": "BootAgent converts request formats locally and forwards them to the selected profile; that profile still owns the model and credentials.", - "适配服务运行中": "Adapter is running", "适配服务已停止": "Adapter is stopped", - "停止服务": "Stop adapter", - "启动服务": "Start adapter", - "保存设置": "Save", "为什么需要它": "Why this exists", "不同 Agent 要求的 API 协议不一样:Codex 只发 OpenAI Responses 请求,Claude Code 只发 Anthropic Messages 请求,OpenCode 和 Aider 发 Chat Completions 请求。而一个模型服务通常只支持其中一部分。": "Agents disagree about which API they speak: Codex sends OpenAI Responses requests, Claude Code sends Anthropic Messages requests, and OpenCode and Aider send Chat Completions requests. A given model service usually serves only some of those.", "开启后,BootAgent 会在本机监听一个地址,把这三种协议的请求都翻译成 Chat Completions 再转发给下面选中的模型服务。这样协议不匹配的 Agent 也能连上它。": "When this is on, BootAgent listens on a local address and rewrites all three request formats into Chat Completions before forwarding them to the model service you pick below. That is what lets a mismatched Agent connect.", "哪些 Agent 会用到它": "Which Agents can use it", "把下面这些 Agent 的配置模版指向本适配器,它们就会走本地转换": "Point these Agents at the adapter and their requests will go through the local conversion", "需要 {protocol}": "needs {protocol}", - "已指向适配器": "using the adapter", "没有可用的 Agent,先在环境总览里安装一个": "No Agents yet. Install one from the environment overview first.", "请求最终发往": "Requests end up at", "适配器把所有请求都转成 Chat Completions 发给这个配置模版,所以它必须是 Chat Completions 协议的": "The adapter converts every request into Chat Completions before sending it here, so this profile has to be a Chat Completions one", @@ -313,6 +284,59 @@ const english = { "任务时间线": "Task timeline", "同批任务": "Tasks in this batch", "错误码": "Error code", + "通知": "Notifications", + "已打开": "Opened", + "启动失败": "Launch failed", + "查看原因": "Show the reason", + "无法启动 {name}": "Couldn't launch {name}", + "无法打开 {name}": "Couldn't open {name}", + "无法安装 {name}": "Couldn't install {name}", + "无法更新 {name}": "Couldn't update {name}", + "无法卸载 {name}": "Couldn't uninstall {name}", + "已改用 {terminal} 打开": "Opened in {terminal} instead", + "设置里选择的 {terminal} 未安装,可以在设置中更换": "{terminal}, chosen in Settings, is not installed. You can choose another terminal in Settings.", + "去设置": "Open Settings", + "已应用,重启 {name} 后生效": "Applied. Restart {name} to use it", + "{agent} 已改用「{profile}」": "{agent} now uses “{profile}”", + "{agent} 已改用兼容模式": "{agent} now uses compatibility mode", + "连接正常": "Connection works", + "启动目录不存在": "The launch folder does not exist", + "换一个已有的文件夹,或用目录旁的按钮选择": "Choose an existing folder, or pick one with the button beside the path", + "找不到可用的终端": "No terminal is available", + "安装一个终端程序,或在设置中选择已安装的终端": "Install a terminal, or choose an installed one in Settings", + "终端没有打开": "The terminal did not open", + "稍后重试,或在设置中换一个终端": "Try again, or choose another terminal in Settings", + "没有返回模型,请手动输入模型 ID": "No models were returned. Enter a model ID by hand", + "无法获取模型列表,请手动输入模型 ID": "Couldn't list models. Enter a model ID by hand", + "「{name}」正在使用,无法删除": "“{name}” is in use and can't be deleted", + "使用它的 Agent:{agents}": "Used by: {agents}", + "已删除「{name}」": "Deleted “{name}”", + "已保存,{count} 个 Agent 未能更新": "Saved, but {count} Agent(s) couldn't be updated", + "已保存,{count} 个 Agent 已更新": "Saved and updated {count} Agent(s)", + "已保存「{name}」": "Saved “{name}”", + "已重新生成本地 Key": "Local key regenerated", + "兼容模式已停止": "Compatibility mode stopped", + "已保存兼容模式设置": "Compatibility mode settings saved", + "兼容模式已开启": "Compatibility mode is on", + "无法读取设置": "Couldn't read settings", + "没能迁移旧版配置": "Couldn't migrate the old configuration", + "已迁移旧版配置": "Old configuration migrated", + "无法扫描 MCP 配置": "Couldn't scan MCP configuration", + "没能读取 MCP 服务器": "Couldn't read MCP servers", + "点击重新扫描再试一次": "Click Rescan to try again", + "无法读取「{name}」": "Couldn't read “{name}”", + "无法应用 MCP 更改": "Couldn't apply MCP changes", + "已同步 {count} 个 MCP 服务器": "Synced {count} MCP server(s)", + "{count} 项未能应用": "{count} change(s) not applied", + "无法扫描 Skills": "Couldn't scan Skills", + "没能读取 Skills": "Couldn't read Skills", + "无法读取要导入的 Skill": "Couldn't read the Skill to import", + "无法应用 Skills": "Couldn't apply Skills", + "已应用 {count} 个 Skill": "Applied {count} Skill(s)", + "无法导入 Skill": "Couldn't import Skills", + "已导入 {count} 个 Skill": "Imported {count} Skill(s)", + "{count} 个 Skill 未能导入": "{count} Skill(s) not imported", + "勾选目标 Agent 后点「应用 Skills」即可使用": "Select target Agents, then click Apply Skills to use them", "退出码": "Exit code", "配置中": "Configuring", "失败": "Failed", @@ -321,8 +345,6 @@ const english = { "等待执行": "Waiting", "高级选项": "Advanced options", "模型服务": "Provider", - "检测状态": "Detected state", - "备注": "Note", "新增模型服务": "Add provider", "模型服务 ID": "Provider ID", "搜索模型": "Search models", @@ -437,7 +459,6 @@ const english = { "已下载 {done} MB / {total} MB({percent}%)": "Downloaded {done} MB of {total} MB ({percent}%)", "已下载 {done} MB": "Downloaded {done} MB", "按官方方式安装与登录": "Install and sign in using the official method", - "已检测到": "Detected", "官方安装": "Official install", "官方文档": "Official docs", "显示官方安装与配置步骤": "Show official installation and setup steps", @@ -446,15 +467,11 @@ const english = { "支持检测、安装与配置,但运行时无法被 BootAgent 管理": "Supports detection, installation, and configuration, but runtime is not managed by BootAgent", "选择 {name}": "Select {name}", "配置无法解析": "Configuration could not be parsed", - "配置文件当前指向 {url}": "Configuration file currently points to {url}", - "检测到的配置,非 BootAgent 写入": "Detected configuration not written by BootAgent", "未配置": "Not configured", - "{version}(锁定 {lockedVersion})": "{version} (locked to {lockedVersion})", "选择 Agent": "Select agents", "选择要安装的桌面 Agent,每次安装一个": "Choose the desktop agent to install. One per run", "安装应用后,会把选定的配置模版应用到对应的配置": "After installation, the selected profile is applied to the matching configuration", "不支持": "Unsupported", - "与 {name} 共用配置": "Shares configuration with {name}", "已安装,可直接应用配置模版": "Installed; a profile can be applied now", "安装官方桌面应用": "Install the official desktop application", "第三方桌面应用,非官方出品": "Third-party desktop application, not an official release", @@ -490,6 +507,12 @@ const english = { // the user may not have yet. "Register and get a key" promised the sign-up // flow; this wording covers both arriving signed in and having to sign up. "获取 API Key": "Get an API key", + "关于 API Key": "About API keys", + "API Key 是 {provider} 发给你的访问凭证,Agent 用它调用模型": "An API key is the credential {provider} issues to you. Agents use it to call models", + "还没有的话,点「获取 API Key」打开 {provider} 的官方页面,在那里注册并创建": "If you do not have one, \"Get an API key\" opens {provider}'s own page, where you sign up and create it", + // States who bills and stops there. An amount, or a word like "cheap", would + // be a promise about a price only the Provider sets. + "连通测试和 Agent 的每次调用都是真实请求,由 {provider} 按它的价格计费;BootAgent 不收费,也不预估费用": "Connection tests and every call an Agent makes are real requests, billed by {provider} at its prices. BootAgent charges nothing and does not estimate the cost", "自定义模型名称(可选)": "Custom model name (optional)", // The connection step's model field. It only decides what the probe requests -- // the configured model is chosen on the next step -- and saying so plainly is @@ -556,13 +579,8 @@ const english = { "本机已安装 Agent 及其当前模型服务、配置模版与模型": "Installed agents and their current providers, profiles, and models", "刷新状态": "Refresh status", "桌面 Agent": "Desktop Agent", - "与 {name} 共用配置文件 {path};安装和启动不会改动配置": "Shares the {path} configuration file with {name}; installation and launch do not modify it", - "配置文件:{path}": "Configuration file: {path}", "位置": "Location", "打开": "Open", - "已检测到应用,但版本信息不可用": "The app was detected, but version information is unavailable", - "可继续尝试启动;版本检测与模型 API 兼容性无关。": "You can still try launching the app; version detection is separate from model API compatibility.", - "应用状态检测不可用": "Desktop app status could not be inspected", "{name} 已打开": "{name} opened", "{name} 安装完成": "{name} installed", "{name} 已安装": "{name} is already installed", @@ -572,7 +590,6 @@ const english = { "已安装 Agent": "Installed agents", "共 {count} 个": "Total: {count}", "尚未安装任何命令行 Agent": "No command-line agents installed", - "在新终端窗口中启动,并载入 BootAgent 写入的配置": "Open a new terminal window running this agent with the configuration BootAgent wrote", "无法启动 Agent": "Could not launch the agent", "选择启动目录": "Choose launch directory", "启动目录": "Launch directory", @@ -589,30 +606,22 @@ const english = { "卸载 Agent": "Uninstall agent", "卸载并删除全部数据": "Uninstall and delete all data", "确认永久删除数据": "Confirm permanent data deletion", - "全量清理将永久删除配置文件、凭据、会话和对话数据,删除后无法找回。请确认你已完成备份。": "Full cleanup permanently deletes configuration files, credentials, sessions, and conversation data. This cannot be undone. Confirm that you have made a backup.", "永久删除并卸载": "Permanently delete and uninstall", "卸载中": "Uninstalling", "卸载 {name}": "Uninstall {name}", - "确定卸载「{name}」吗?只会移除 Agent 程序,配置模版、模型服务、配置文件和对话数据都会保留。": "Uninstall “{name}”? Only the agent program will be removed. Profiles, providers, configuration files, and conversation data will be preserved.", "已卸载 {name},配置和对话数据已保留": "Uninstalled {name}. Configuration and conversation data were preserved.", "已卸载 {name},全部数据已删除": "Uninstalled {name}. All data was deleted.", "无法卸载 Agent": "Could not uninstall the agent", - "运行时": "Runtimes", - "缺少 {count} 个运行时,安装后即可自动安装对应 Agent": "{count} runtime(s) missing. Install them to enable automatic agent installation", - "Agent 安装所需的运行时都已就绪": "Every runtime needed to install agents is ready", "运行时安装失败": "Could not install the runtime", "版本 {version}": "Version {version}", "版本未知": "Version unknown", "{agents} 需要": "Required by {agents}", - "锁定版本": "Locked version", "由 BootAgent 安装": "Installed by BootAgent", "本机已有": "Already on this machine", "安装": "Install", "安装 {name}": "Install {name}", "安装运行时": "Install runtime", "安装中": "Installing", - "运行时会安装到 {dir},并写入登录 PATH,不需要管理员权限": "Runtimes install into {dir} and are added to your login PATH. No administrator rights needed", - "运行时会安装到 BootAgent 的托管目录,并写入登录 PATH,不需要管理员权限": "Runtimes install into BootAgent's managed directory and are added to your login PATH. No administrator rights needed", "运行时下载": "Runtime downloads", // Both hosts are always tried (downloadSources, bootstrap.go:364-372), so by the // time a download fails the mirror has been attempted and the setting cannot help. @@ -639,7 +648,6 @@ const english = { "应用": "Apply", "应用配置模版": "Apply profile", "{name} 已应用": "{name} applied", - "当前指向": "Current target", "配置文件": "Configuration file", "备份": "Backups", "已有历史备份": "Previous backup available", @@ -811,7 +819,6 @@ const english = { "MCP 官方 Registry": "Official MCP Registry", "npm": "npm", "确认跨环境卸载": "Confirm cross-environment uninstall", - "当前 Agent 由另一套 Node/npm 环境管理。是否允许使用已记录的原始 npm 环境卸载?不会使用 sudo,也不会删除配置和对话数据。": "This Agent is managed by another Node/npm environment. Allow uninstalling it with the recorded original npm environment? sudo will not be used, and configuration and conversations will be kept.", "允许并继续": "Allow and continue", "Agent 尚未安装": "Agent is not installed", "先安装这个 Agent,再执行卸载": "Install this Agent before uninstalling it", @@ -904,7 +911,6 @@ const english = { "科恩实验室": "Keen Security Lab", "三堡实验室": "Sanbu Lab", "查看报告": "View report", - "版本信息": "Version info", "最新版本": "Latest version", "更新日志": "Changelog", "安装量": "Installs", @@ -916,6 +922,33 @@ const english = { "收藏数": "Stars", "下载量": "Downloads", // multimodal capabilities + "这个 Agent 的设置无法读取": "This Agent's settings cannot be read", + "实际使用的接口地址是 {url}": "The endpoint actually in use is {url}", + "设置已在 BootAgent 之外被修改": "Settings were changed outside BootAgent", + "这份设置不是 BootAgent 写入的": "These settings were not written by BootAgent", + "正在使用 BootAgent 之外的设置": "Using settings from outside BootAgent", + "卸载「{name}」?只移除程序,你的设置和对话都会保留。": "Uninstall \"{name}\"? Only the program is removed; your settings and conversations are kept.", + "会永久删除这个 Agent 的设置、登录信息和全部对话,无法找回。": "This permanently deletes this Agent's settings, sign-in details and every conversation. They cannot be recovered.", + "这个 Agent 是用另一套 Node.js 安装的。要用当初安装它的那一套来卸载吗?不会删除你的设置和对话。": "This Agent was installed with a different Node.js. Uninstall it with the one that installed it? Your settings and conversations are not deleted.", + "在新的终端窗口里打开": "Open in a new terminal window", + "接口地址": "Endpoint", + "推荐版本": "Recommended version", + "说明": "Note", + "安装包": "Package", + "安装位置": "Installed at", + "读不到这个应用的版本,不影响启动和使用。": "The app's version cannot be read. You can still open and use it.", + "暂时无法检查这个应用是否已安装。": "Cannot check whether this app is installed right now.", + "设置文件": "Settings file", + "共用设置": "Shared settings", + "和 {name} 用同一份设置,安装和启动不会改动它": "Uses the same settings as {name}; installing and opening do not change them", + "程序位置": "Program location", + "还差 {count} 个运行环境,装好后就能安装对应的 Agent": "{count} runtime environments missing; install them to install the Agents that need them", + "安装 Agent 需要的运行环境都已就绪": "Everything needed to install Agents is ready", + "会装在 BootAgent 自己的目录里,不需要管理员权限。": "Installed in BootAgent's own folder; no administrator rights needed.", + "运行环境": "Runtime environments", + "安装目录": "Install folder", + "官方下载": "Official download", + "{name} 下载地址": "{name} download", "多模态能力": "Multimodal capabilities", "按能力查看已保存 API Key 的模型服务能做什么。列出模型不收费;点击实测会发出真实请求。": "See what the providers you have saved an API key for can do, one capability at a time. Listing models is free; Probe sends a real request.", "多模态能力分类": "Multimodal capabilities", @@ -998,6 +1031,84 @@ const english = { "其他 Agent(说明文件)": "Other Agents (guide)", "其他 Agent(生成说明文件)": "Other Agents (write a guide)", "{agents}没有可配置的环境变量,Key 会写进 BootAgent 的私有文件 {path},由 Skill 的脚本读取。": "{agents} have no configurable environment, so the key goes into BootAgent's private file {path}, which the Skill's script reads.", + "BootAgent 会在本机开启兼容模式,并先发送两次测试请求,可能产生少量费用。": "BootAgent will turn on compatibility mode on this computer and send two test requests first, which may cost a little.", + "Claude Code 看到的模型名": "Model name Claude Code sees", + "Codex 看到的模型名": "Model name Codex sees", + "{agents} 已改用兼容模式": "{agents} now use compatibility mode", + "尚未确认 {provider} 支持 {agent} 的请求格式({protocol}),可以改用兼容模式,由 BootAgent 在本机转换": "{provider} isn't confirmed to support {agent}'s request format ({protocol}); compatibility mode lets BootAgent convert it on this computer", + "{agent} 不能直接使用这个模型服务,BootAgent 可以在本机转换后使用": "{agent} can't use this model service directly, but BootAgent can convert its requests on this computer", + "{agent} 不能直接使用这个模型服务,应用时会开启兼容模式在本机转换,使用期间需要保持 BootAgent 运行": "{agent} can't use this model service directly, so applying turns on compatibility mode, which needs BootAgent to keep running", + "{agent} 不能直接使用这个配置模版,应用时会开启兼容模式在本机转换,使用期间需要保持 BootAgent 运行": "{agent} can't use this profile directly, so applying turns on compatibility mode, which needs BootAgent to keep running", + "{name}(不支持此格式)": "{name} (format not supported)", + "{name}(兼容模式)": "{name} (compatibility mode)", + "不用兼容模式": "Don't use compatibility mode", + "了解兼容模式": "About compatibility mode", + "使用兼容模式": "Use compatibility mode", + "使用期间需要保持 BootAgent 运行": "BootAgent needs to keep running while it is in use", + "使用的模型": "Model to use", + "保存更改": "Save changes", + "停止": "Stop", + "停止兼容模式": "Stop compatibility mode", + "停止后 {agents} 将无法使用,直到重新开启兼容模式或换一个配置模版。": "Once stopped, {agents} won't work until compatibility mode is turned back on or they switch to another profile.", + "其他 Agent 看到的模型名": "Model name other Agents see", + "兼容模式": "Compatibility mode", + "兼容模式未开启": "Compatibility mode is off", + "兼容模式状态": "Compatibility mode status", + "兼容模式运行中": "Compatibility mode is running", + "兼容模式需要 BootAgent 保持运行。要让 BootAgent 随系统启动吗?": "Compatibility mode needs BootAgent to keep running. Start BootAgent automatically when you log in?", + "兼容模式(Claude Code)": "Compatibility mode (Claude Code)", + "兼容模式(Codex)": "Compatibility mode (Codex)", + "兼容模式(OpenCode / Aider)": "Compatibility mode (OpenCode / Aider)", + "兼容模式,在本机转换": "Compatibility mode, converted on this computer", + "已停止": "Stopped", + "已选择兼容模式,使用 {agent} 时需要保持 BootAgent 运行": "Compatibility mode chosen; BootAgent needs to keep running while you use {agent}", + "已通过兼容模式配置": "Configured through compatibility mode", + "开启兼容模式": "Turn on compatibility mode", + "开启并应用": "Turn on and apply", + "换一个模型服务": "Choose another model service", + "无法保存兼容模式设置": "Could not save compatibility mode settings", + "无法停止兼容模式": "Could not stop compatibility mode", + "无法开启兼容模式": "Could not turn on compatibility mode", + "无法确认能否使用兼容模式": "Could not confirm whether compatibility mode can be used", + "无法确认这个配置模版能否通过兼容模式使用": "Could not confirm whether this profile works through compatibility mode", + "无法读取兼容模式设置": "Could not read compatibility mode settings", + "正在使用的 Agent": "Agents using it", + "正在确认能否使用兼容模式": "Checking whether compatibility mode can be used", + "用兼容模式应用": "Apply with compatibility mode", + "让只支持特定格式的 Agent 也能用你的模型服务,在本机转换,不经过其他服务器。": "Lets Agents that only speak one format use your model service, converted on this computer without going through any other server.", + "运行中": "Running", + "还没有 Agent 使用兼容模式": "No Agent uses compatibility mode yet", + "这个模型服务可能不支持该 Agent 的请求格式,可以换一个模型,或用兼容模式在本机转换": "This model service may not accept this Agent's request format; try another model, or use compatibility mode to convert on this computer", + "连接方式": "Connection", + "本机转换": "Converted on this computer", + "Codex 发出的是 OpenAI Responses 格式,Claude Code 是 Anthropic Messages 格式,很多模型服务只支持 OpenAI Chat Completions。BootAgent 在本机把前两种转换成 Chat Completions,再发往每个 Agent 各自选择的模型。": "Codex sends requests in the OpenAI Responses format and Claude Code in the Anthropic Messages format, while many model services only accept OpenAI Chat Completions. BootAgent converts the first two into Chat Completions on this computer, then sends each Agent's requests to the model that Agent uses.", + "每个 Agent 用自己的本机 Key 连接,互不影响;模型和 Key 仍由各自的配置模版管理。": "Each Agent connects with a local key of its own, so they don't affect each other; models and keys are still managed by each Agent's profile.", + "{agent} 正在通过兼容模式使用这个配置模版,使用期间需要保持 BootAgent 运行": "{agent} uses this profile through compatibility mode, which needs BootAgent to keep running", + "为 {name} 更换模型": "Change the model {name} uses", + "使用的配置模版已删除": "The profile it used was deleted", + "在 Agent 的配置页选择配置模版时会自动开启": "Turns on by itself when you choose a profile on an Agent's page", + "开启后这些 Agent 才能使用": "These Agents work once it is on", + "更换": "Change", + "跑一个小任务试试": "Try one small task", + // Says who bills and stops there, like the key explainer: no amount, no "small". + "让 {agent} 在一个临时目录里写一个介绍页,只会写入这个目录。这是真实的模型调用,由模型服务按它的价格计费": "{agent} writes an introduction page in a temporary directory and writes nowhere else. This is a real model call, billed by the provider at its prices", + "开始": "Start", + "正在运行,通常需要一两分钟": "Running, usually a minute or two", + "{agent} 写好了,文件在下面这个目录": "{agent} is done. The files are in the directory below", + "{agent} 没有正常结束,下面的文件可能不完整": "{agent} did not finish cleanly, so the files below may be incomplete", + "{agent} 没有写出任何文件": "{agent} did not write any file", + "小任务没能运行": "The task could not run", + "复制路径": "Copy path", + "生成的文件": "Files written", + "检查模型服务": "Check the provider", + "查看运行记录": "View the run record", + "本机环境": "This computer", + "系统": "System", + "已安装的 Agent": "Agents installed", + "{count} 个": "{count}", + "还没有": "None yet", + "未安装,当前选择需要": "Not installed, and this choice needs it", + "未安装,当前选择用不到": "Not installed, and this choice does not need it", } as const; export type Locale = "zh-CN" | "en"; diff --git a/frontend/src/pages/ActivationPage.test.tsx b/frontend/src/pages/ActivationPage.test.tsx index a31f6803..aaf94086 100644 --- a/frontend/src/pages/ActivationPage.test.tsx +++ b/frontend/src/pages/ActivationPage.test.tsx @@ -134,6 +134,64 @@ describe("ActivationPage partial results", () => { expect(screen.queryByText("openclaw onboard")).toBeNull(); }); + it("installs without configuring, then points the Agent at the adapter in compatibility mode", async () => { + const install = vi.spyOn(api, "install").mockResolvedValue({ + ok: true, results: [result("codex", { status: "skipped" })], log: "", probe: null, next: "", + } as never); + const saveProfile = vi.spyOn(api, "saveProfile").mockResolvedValue({ + profile: { id: "codex-ppio-compat", label: "Codex · PPIO", provider: "ppio", baseUrl: null, model: "deepseek/deepseek-v3", protocol: "openai", activatedAt: null }, + reapplied: null, + failures: null, + }); + const activate = vi.spyOn(api, "activateAgentWithConversion").mockResolvedValue({ + ok: true, agent: "codex", config: "/c", provider: "bootagent-converter-responses", model: "gpt-5.6-sol", + restart: "", next: "codex", upstreamVerified: true, endToEndVerified: true, + }); + state = { + ...initialWizardState, + status, + statusState: "success", + setupKind: "cli", + selectedAgentIds: ["codex"], + provider: "ppio", + model: "deepseek/deepseek-v3", + profileId: "codex-ppio-compat", + profileLabel: "Codex · PPIO", + conversion: true, + activationState: "idle", + activationRequested: true, + }; + + render(); + await waitFor(() => expect(activate).toHaveBeenCalledWith("codex", "codex-ppio-compat")); + expect(install).toHaveBeenCalledWith(expect.objectContaining({ agents: ["codex"], configure: false, install_agent: true })); + expect(saveProfile).toHaveBeenCalledWith(expect.objectContaining({ id: "codex-ppio-compat", provider: "ppio", protocol: "openai" })); + }); + + it("refreshes after a failed compatibility mode step, so the saved Profile is visible", async () => { + vi.spyOn(api, "install").mockResolvedValue({ + ok: true, results: [result("codex", { status: "skipped" })], log: "", probe: null, next: "", + } as never); + vi.spyOn(api, "saveProfile").mockResolvedValue({ + profile: { id: "codex-ppio-compat", label: "Codex · PPIO", provider: "ppio", baseUrl: null, model: "m", protocol: "openai", activatedAt: null }, + reapplied: null, + failures: null, + }); + const { BootAgentApiError } = await import("../backend/errors"); + vi.spyOn(api, "activateAgentWithConversion").mockRejectedValue( + new BootAgentApiError("port in use", "CONVERSION_PORT_UNAVAILABLE", true, 409), + ); + state = { + ...initialWizardState, + status, statusState: "success", setupKind: "cli", selectedAgentIds: ["codex"], + provider: "ppio", model: "m", profileId: "codex-ppio-compat", profileLabel: "Codex · PPIO", + conversion: true, activationState: "idle", activationRequested: true, + }; + + render(); + await waitFor(() => expect(refreshStatus).toHaveBeenCalled()); + }); + it("configures a manual desktop app without requesting an install", async () => { vi.spyOn(api, "saveProfile").mockResolvedValue({ profile: { id: "claude-desktop-jiekou", label: "Claude Desktop", provider: "jiekou", baseUrl: null, model: "claude-sonnet-4-5", protocol: "anthropic", activatedAt: null }, diff --git a/frontend/src/pages/ActivationPage.tsx b/frontend/src/pages/ActivationPage.tsx index 4574c95d..191a9860 100644 --- a/frontend/src/pages/ActivationPage.tsx +++ b/frontend/src/pages/ActivationPage.tsx @@ -11,7 +11,7 @@ import { useI18n } from "../i18n"; import { desktopProtocol, profileAgentIdForDesktop, selectedDesktopApp } from "../state/desktopSetup"; import { installTaskRoute, taskCanceller, taskKey, useTaskCenter, useTaskRoute, type TaskCanceller } from "../state/TaskCenterContext"; import { useWizard } from "../state/WizardContext"; -import type { AgentInstallResult, InstallRequest } from "../types/api"; +import type { AgentInstallResult, InstallRequest, InstallResponse } from "../types/api"; export function ActivationPage() { const navigate = useNavigate(); @@ -58,13 +58,67 @@ export function ActivationPage() { model: state.model, profile_id: state.profileId, profile_label: state.profileLabel, - configure: true, + // In compatibility mode the Agent is pointed at the local adapter after + // it is installed, not at the Provider during the install. + configure: !state.conversion, install_agent: true, skip_test: false, }), - [state.model, state.profileId, state.profileLabel, state.provider], + [state.conversion, state.model, state.profileId, state.profileLabel, state.provider], ); + /** + * Installs, then points each installed Agent at the local adapter, which + * forwards to a Chat Completions Profile on the chosen Provider. A failed + * adapter step fails that Agent's row and can be retried: installing again + * is a no-op for an Agent already there. + */ + const installCliWithConversion = useCallback(async (agents: string[], register: (cancel?: TaskCanceller) => void): Promise => { + const installRequest = api.install(requestFor(agents)); + register(taskCanceller(installRequest)); + const installed = await installRequest; + const profileRequest = api.saveProfile({ + id: state.profileId, + label: state.profileLabel, + provider: state.provider, + apiBaseUrl: "", + apiKey: "", + model: state.model, + configMode: "provider", + protocol: "openai", + }); + register(taskCanceller(profileRequest)); + const { profile } = await profileRequest; + const results: AgentInstallResult[] = []; + const next: string[] = []; + for (const result of installed.results) { + if (result.status === "failed") { + results.push(result); + continue; + } + try { + const request = api.activateAgentWithConversion(result.agent, profile.id); + register(taskCanceller(request)); + const activated = await request; + results.push({ ...result, status: "configured", message: t("已通过兼容模式配置") }); + if (activated.next) next.push(activated.next); + } catch (error) { + if (isCancellationError(error)) throw error; + results.push({ ...result, status: "failed", message: describeFailure(error, t("无法开启兼容模式"), t).message, retryable: true }); + } + } + // The Profile is saved even when every Agent failed, and the callers only + // refresh after a success: without this it stayed invisible to the + // compatibility mode page the failure points the user to. + await refreshStatus(); + return { + ...installed, + ok: results.every((result) => result.status !== "failed"), + results, + next: next.join("\n"), + }; + }, [refreshStatus, requestFor, state.model, state.profileId, state.profileLabel, state.provider, t]); + const startActivationTasks = useCallback((agentIds: string[]) => { const officialScriptAgents = new Set( (state.status?.catalog ?? []) @@ -159,14 +213,17 @@ export function ActivationPage() { apiKey: "", model: state.model, configMode: "provider", - protocol: desktopProtocol(desktop), + // Compatibility mode forwards to Chat Completions, whatever the app speaks. + protocol: state.conversion ? "openai" : desktopProtocol(desktop), }); register(taskCanceller(profileRequest)); const { profile } = await profileRequest; const installRequest = desktop.installed || desktop.manualInstall ? undefined : api.installDesktopAgent(desktop.id); if (installRequest) register(taskCanceller(installRequest)); const installed = installRequest ? await installRequest : undefined; - const configureRequest = api.configureDesktopAgent(desktop.id, profile.id); + const configureRequest = state.conversion + ? api.configureDesktopAgentWithConversion(desktop.id, profile.id) + : api.configureDesktopAgent(desktop.id, profile.id); register(taskCanceller(configureRequest)); const configured = await configureRequest; return { @@ -181,7 +238,7 @@ export function ActivationPage() { log: configured.message, next: configured.restart || "", }; - }, [desktop, state.profileId, state.profileLabel, state.provider, state.model, t]); + }, [desktop, state.conversion, state.profileId, state.profileLabel, state.provider, state.model, t]); const activate = useCallback(async () => { const startedTasks = startActivationTasks(state.selectedAgentIds); @@ -200,6 +257,8 @@ export function ActivationPage() { if (isDesktop) { response = await installDesktop((cancel) => registerActivationCanceller(startedTasks, cancel)) .then((result) => ({ ...result, ok: true, probe: null })); + } else if (state.conversion) { + response = await installCliWithConversion(state.selectedAgentIds, (cancel) => registerActivationCanceller(startedTasks, cancel)); } else { const request = api.install(requestFor(state.selectedAgentIds)); registerActivationCanceller(startedTasks, taskCanceller(request)); @@ -227,7 +286,7 @@ export function ActivationPage() { finishActivationTasks(startedTasks, [], false, message); dispatch({ type: "ACTIVATION_FAILED", message }); } - }, [dispatch, finishActivationTasks, installDesktop, isDesktop, navigate, refreshStatus, registerActivationCanceller, requestFor, startActivationTasks, state.selectedAgentIds, t]); + }, [dispatch, finishActivationTasks, installCliWithConversion, installDesktop, isDesktop, navigate, refreshStatus, registerActivationCanceller, requestFor, startActivationTasks, state.conversion, state.selectedAgentIds, t]); useEffect( () => @@ -302,6 +361,8 @@ export function ActivationPage() { if (isDesktop) { response = await installDesktop((cancel) => registerActivationCanceller(startedTasks, cancel)) .then((result) => ({ ...result, ok: true, probe: null })); + } else if (state.conversion) { + response = await installCliWithConversion([agentId], (cancel) => registerActivationCanceller(startedTasks, cancel)); } else { const request = api.install(requestFor([agentId])); registerActivationCanceller(startedTasks, taskCanceller(request)); diff --git a/frontend/src/pages/AgentProfilePage.test.tsx b/frontend/src/pages/AgentProfilePage.test.tsx index dcf48717..f7f0cf3c 100644 --- a/frontend/src/pages/AgentProfilePage.test.tsx +++ b/frontend/src/pages/AgentProfilePage.test.tsx @@ -1,9 +1,11 @@ -import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { MemoryRouter, Route, Routes } from "react-router-dom"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { api } from "../backend/api"; +import { FeedbackViewport } from "../components/FeedbackViewport"; +import { FeedbackProvider } from "../state/FeedbackContext"; import type { ProfileSummary, SaveProfileResult, StatusResponse } from "../types/api"; import { AgentProfilePage } from "./AgentProfilePage"; @@ -68,15 +70,24 @@ function statusWith(profiles: ProfileSummary[]): StatusResponse { function renderPage(profiles: ProfileSummary[]) { mockState = { status: statusWith(profiles), statusState: "success" }; return render( - - - } /> - overview} /> - - , + + + + } /> + overview} /> + + + , ); } +/** The receipt on screen, with 详情 open. */ +async function failureReceipt() { + const receipt = await screen.findByRole("alert"); + fireEvent.click(within(receipt).getByRole("button", { name: "详情" })); + return receipt; +} + function renderClaudeDesktopPage(profiles: ProfileSummary[]) { const status = statusWith(profiles); status.desktopAgents = [{ @@ -119,7 +130,56 @@ const availableCheck = { profileId: "team-ppio", model: "deepseek/deepseek-v3", status: "available" as const, protocol: "responses", agents: ["codex"], }; +/** The page inside the app's feedback layer, with the overview showing receipts. */ +function renderWithReceipts(path: string, status: StatusResponse) { + mockState = { status, statusState: "success" }; + render( + + + + } /> +

overview

} /> +
+
+
, + ); +} + describe("AgentProfilePage", () => { + // The overview row changing was the only sign the apply worked; the receipt + // outlives this page and says it in words. + it("names the applied Profile on the overview it returns to", async () => { + vi.spyOn(api, "activateAgent").mockResolvedValue({ + ok: true, agent: "codex", config: "/c", provider: "ppio", + model: "deepseek/deepseek-v3", restart: "", next: "", + }); + renderWithReceipts("/agents/codex", statusWith([profile()])); + fireEvent.click(screen.getByRole("button", { name: "应用" })); + await screen.findByRole("heading", { name: "overview" }); + expect(screen.getByText("Codex 已改用「团队 PPIO」")).toBeTruthy(); + }); + + // The backend reports that a desktop app reads its settings at startup; that + // used to be dropped, so the running app looked switched when it was not. + it("keeps a restart reminder after applying to a desktop app", async () => { + const status = statusWith([profile({ id: "desk", label: "桌面", protocol: "anthropic", model: "claude-sonnet-5-5" })]); + status.desktopAgents = [{ + id: "claude-desktop", name: "Claude Desktop", installed: true, supported: true, + version: "1.0.0", source: "application", protocol: "anthropic", profileAgentId: "claude-desktop", profileId: null, + }]; + status.providers = { ppio: { name: "PPIO", home: "", base_url: "https://api.ppio.com/openai", anthropic_base_url: "https://api.ppio.com/anthropic", has_key: true } }; + const configure = vi.spyOn(api, "configureDesktopAgent").mockResolvedValue({ + agent: "claude-desktop", profileId: "desk", profileAgentId: "claude-desktop", + message: "Claude Desktop model applied", restart: "Restart Claude Desktop", + }); + renderWithReceipts("/agents/claude-desktop", status); + fireEvent.click(screen.getByRole("button", { name: "应用" })); + await waitFor(() => expect(configure).toHaveBeenCalledWith("claude-desktop", "desk")); + await screen.findByRole("heading", { name: "overview" }); + // A warning, so it waits to be closed rather than retiring itself. + expect(screen.getByRole("alert")).toHaveTextContent("已应用,重启 Claude Desktop 后生效"); + }); + // Requirement: after applying, land where the result is visible instead of // staying on a screen whose job is done. it("returns to the overview after a successful apply", async () => { @@ -140,7 +200,9 @@ describe("AgentProfilePage", () => { ); renderPage([profile()]); fireEvent.click(screen.getByRole("button", { name: "应用" })); - expect(await screen.findByText("Endpoint refused the key")).toBeTruthy(); + const receipt = await failureReceipt(); + expect(receipt).toHaveTextContent("应用配置模版失败"); + expect(receipt).toHaveTextContent("Endpoint refused the key"); // Not navigated away: the user needs to see the error next to the choice. expect(screen.queryByRole("heading", { name: "overview" })).toBeNull(); }); @@ -267,6 +329,21 @@ describe("AgentProfilePage", () => { // Both inline save paths dropped result.failures, so an Agent that could not // be rewritten went unreported here. + // The model belongs to the Profile, so an edit made for this Agent also + // moves every other Agent on it. That used to happen with nothing said. + it("names the other Agents an inline model edit moved", async () => { + vi.spyOn(api, "saveProfile").mockResolvedValue({ ...saved({ model: "deepseek/deepseek-r1" }), reapplied: ["codex", "opencode"] }); + renderPage([profile()]); + await waitFor(() => expect(screen.getByLabelText("模型")).toHaveAttribute("placeholder", "搜索模型")); + const field = screen.getByLabelText("模型"); + await userEvent.clear(field); + await userEvent.type(field, "deepseek/deepseek-r1"); + await userEvent.tab(); + const receipt = (await screen.findByText("已保存,2 个 Agent 已更新")).closest(".feedback-toast") as HTMLElement; + fireEvent.click(within(receipt).getByRole("button", { name: "详情" })); + expect(receipt).toHaveTextContent("Codex、opencode"); + }); + it("reports an Agent an inline model edit could not rewrite", async () => { vi.spyOn(api, "saveProfile").mockResolvedValue({ ...saved({ model: "deepseek/deepseek-r1" }), failures: { codex: "写入失败" } }); renderPage([profile()]); @@ -275,7 +352,9 @@ describe("AgentProfilePage", () => { await userEvent.clear(field); await userEvent.type(field, "deepseek/deepseek-r1"); await userEvent.tab(); - expect(await screen.findByText(/Codex.*重新应用失败.*写入失败/)).toBeTruthy(); + const receipt = await failureReceipt(); + expect(receipt).toHaveTextContent("已保存,1 个 Agent 未能更新"); + expect(receipt).toHaveTextContent("Codex: 写入失败"); }); // Apply right after typing: the flush saves the new model, and the Apply has @@ -312,7 +391,10 @@ describe("AgentProfilePage", () => { fireEvent.click(screen.getByRole("button", { name: "应用" })); // CONFIG_WRITE_FAILED is shown as its localized copy, not the raw message. - expect(await screen.findByText("无法写入配置文件")).toBeTruthy(); + const receipt = await failureReceipt(); + expect(receipt).toHaveTextContent("无法保存配置模版"); + expect(receipt).toHaveTextContent("无法写入配置文件"); + expect(receipt).not.toHaveTextContent("disk full"); expect(activate).not.toHaveBeenCalled(); expect(screen.queryByRole("heading", { name: "overview" })).toBeNull(); }); @@ -433,15 +515,26 @@ describe("AgentProfilePage", () => { expect(await screen.findByLabelText("思考深度")).toBeTruthy(); }); - it("shows generated adapter Profiles with a Chinese user-facing name", () => { - renderPage([profile({ - id: "bootagent-converter-responses", - label: "BootAgent Converter responses", - })]); + // An Agent in compatibility mode is shown on the Profile its requests go + // to; the adapter's own Profile is an implementation detail. + it("preselects the model service a compatibility-mode Agent really uses", () => { + const status = statusWith([ + profile({ id: "bootagent-converter-for-codex", label: "BootAgent codex", provider: "bootagent-converter-for-codex", model: "gpt-5.6-sol" }), + profile({ id: "team-ppio", label: "团队 PPIO", protocol: "responses" }), + profile({ id: "chat-only", label: "Chat only", protocol: "openai" }), + ]); + status.agents.codex = { ...status.agents.codex, profileId: "bootagent-converter-for-codex" }; + status.conversionRoutes = { codex: "chat-only" }; + mockState = { status, statusState: "success" }; + render( + + } /> + , + ); - expect(screen.getAllByText("协议适配(Codex)")).toHaveLength(2); - expect(screen.queryByText("BootAgent Converter responses")).toBeNull(); - expect(screen.getByRole("radio", { name: "选择 协议适配(Codex)" })).toBeTruthy(); + expect(screen.queryByText("BootAgent codex")).toBeNull(); + expect(screen.getByRole("radio", { name: "选择 Chat only" })).toBeChecked(); + expect(screen.getByText("Codex 正在通过兼容模式使用这个配置模版,使用期间需要保持 BootAgent 运行")).toBeTruthy(); }); it("offers one-confirmation protocol adaptation for a Chat Completions Profile", async () => { @@ -458,10 +551,69 @@ describe("AgentProfilePage", () => { id: "chat-profile", label: "Chat Profile", provider: "chat-only", model: "model-a", protocol: "openai", })]); - expect(await screen.findByText("该模型服务不能直接使用 Claude Desktop 所需的 Anthropic Messages。BootAgent 可以在本机转换请求格式。")).toBeTruthy(); - const apply = screen.getByRole("button", { name: "启用协议适配并应用" }); + expect(await screen.findByText("Claude Desktop 不能直接使用这个模型服务,应用时会开启兼容模式在本机转换,使用期间需要保持 BootAgent 运行")).toBeTruthy(); + const apply = screen.getByRole("button", { name: "用兼容模式应用" }); await userEvent.click(apply); await waitFor(() => expect(configure).toHaveBeenCalledWith("claude-desktop", "chat-profile")); expect(await screen.findByRole("heading", { name: "overview" })).toBeTruthy(); }); + + // A command-line Agent used to have no route to the adapter at all: a Chat + // Completions Profile was never listed for Codex, and pointing Codex at the + // adapter meant picking a hidden converter Profile by hand. + it("lists a Chat Completions Profile for Codex and applies it through compatibility mode", async () => { + const assess = vi.spyOn(api, "assessDesktopAgentProfile"); + const activate = vi.spyOn(api, "activateAgent"); + const convert = vi.spyOn(api, "activateAgentWithConversion").mockResolvedValue({ + ok: true, agent: "codex", config: "/c", provider: "bootagent-converter-responses", model: "gpt-5.6-sol", + restart: "", next: "", upstreamVerified: true, endToEndVerified: true, + }); + renderPage([profile({ id: "chat-only", label: "Chat only", protocol: "openai" })]); + + await userEvent.click(screen.getByRole("radio", { name: "选择 Chat only" })); + expect(screen.getByText("Codex 不能直接使用这个配置模版,应用时会开启兼容模式在本机转换,使用期间需要保持 BootAgent 运行")).toBeTruthy(); + // Nothing billed is sent on selection: the check belongs to the button. + expect(assess).not.toHaveBeenCalled(); + await userEvent.click(screen.getByRole("button", { name: "用兼容模式应用" })); + await waitFor(() => expect(convert).toHaveBeenCalledWith("codex", "chat-only")); + expect(activate).not.toHaveBeenCalled(); + expect(await screen.findByRole("heading", { name: "overview" })).toBeTruthy(); + }); + + it("does not offer Chat Completions Profiles to an Agent that already speaks it", () => { + const status = statusWith([ + profile({ id: "chat-only", label: "Chat only", protocol: "openai" }), + profile({ id: "responses-only", label: "Responses only", protocol: "responses" }), + ]); + status.catalog = [{ ...status.catalog[0], id: "opencode", name: "OpenCode", protocol: "openai" }]; + status.agents = { opencode: { ...status.agents.codex, profileId: null } }; + mockState = { status, statusState: "success" }; + render( + + } /> + , + ); + + expect(screen.getByRole("radio", { name: "选择 Chat only" })).toBeTruthy(); + expect(screen.queryByRole("radio", { name: "选择 Responses only" })).toBeNull(); + expect(screen.queryByRole("button", { name: "用兼容模式应用" })).toBeNull(); + }); + + it("turns a refused check into compatibility mode on the same Provider and model", async () => { + vi.mocked(api.checkProfileModel).mockResolvedValue(refusedCheck); + const saveProfile = vi.spyOn(api, "saveProfile").mockResolvedValue(saved({ id: "team-ppio-compat", protocol: "openai" })); + const convert = vi.spyOn(api, "activateAgentWithConversion").mockResolvedValue({ + ok: true, agent: "codex", config: "/c", provider: "bootagent-converter-responses", model: "gpt-5.6-sol", + restart: "", next: "", upstreamVerified: true, endToEndVerified: true, + }); + renderPage([profile()]); + + await userEvent.click(screen.getByRole("button", { name: /检测模型/ })); + await userEvent.click(await screen.findByRole("button", { name: "使用兼容模式" })); + await waitFor(() => expect(convert).toHaveBeenCalledWith("codex", "team-ppio-compat")); + expect(saveProfile).toHaveBeenCalledWith(expect.objectContaining({ + id: "team-ppio-compat", provider: "ppio", model: "deepseek/deepseek-v3", protocol: "openai", + })); + expect(await screen.findByRole("heading", { name: "overview" })).toBeTruthy(); + }); }); diff --git a/frontend/src/pages/AgentProfilePage.tsx b/frontend/src/pages/AgentProfilePage.tsx index 4da30611..91a90ffa 100644 --- a/frontend/src/pages/AgentProfilePage.tsx +++ b/frontend/src/pages/AgentProfilePage.tsx @@ -2,7 +2,7 @@ import { Check, Pencil, Plus, Save, X } from "lucide-react"; import { useEffect, useMemo, useRef, useState, type FormEvent } from "react"; import { useNavigate, useParams } from "react-router-dom"; -import { api, describeFailure } from "../backend/api"; +import { api } from "../backend/api"; import { ModelCheckButton, ModelCheckNotice } from "../components/ModelCheckNotice"; import { PageScaffold } from "../components/PageScaffold"; import { ProviderModelPicker } from "../components/ProviderModelPicker"; @@ -10,9 +10,11 @@ import { ProviderSegment } from "../components/ProviderSegment"; import { SelectField } from "../components/SelectField"; import { useI18n } from "../i18n"; import { desktopApps, desktopProfileUsable, desktopProfiles, desktopProtocol, profileAgentIdForDesktop } from "../state/desktopSetup"; -import { confirmAction } from "../state/confirmDelete"; import { byProfileCreatedAt, byProviderCreatedAt, preferProviderWithKey } from "../state/ranking"; -import { converterProfileName, isConverterID } from "../state/conversion"; +import { applyConversion, confirmConversion, conversionTargets } from "../state/applyConversion"; +import { canConvertProtocol, conversionTargetFor, converterProfileName, isConverterID, providerDisplayName } from "../state/conversion"; +import { useFeedback } from "../state/FeedbackContext"; +import { saveReceipt } from "../state/saveReceipt"; import { useWizard } from "../state/WizardContext"; import type { DesktopAgentProfileAssessment, ProfileModelCheck, ProfileSummary, ProtocolId, ProviderId } from "../types/api"; @@ -63,6 +65,9 @@ export function AgentProfilePage() { const navigate = useNavigate(); const { locale, t } = useI18n(); const { state, refreshStatus } = useWizard(); + const feedback = useFeedback(); + // Stable across receipts, unlike `feedback`, so an effect can depend on it. + const reportFailure = feedback.failure; const status = state.status; const app = status ? desktopApps(status).find((candidate) => candidate.id === agentId) || null : null; const owner = app ? profileAgentIdForDesktop(app) : agentId; @@ -73,7 +78,6 @@ export function AgentProfilePage() { const [selectedId, setSelectedId] = useState(""); const [draft, setDraft] = useState(null); const [busy, setBusy] = useState(false); - const [failure, setFailure] = useState(""); // The model of the selected Profile, edited in place. null means "showing what // is stored"; a string means the field has been touched and not yet committed. const [modelDraft, setModelDraft] = useState(null); @@ -96,23 +100,37 @@ export function AgentProfilePage() { const profiles = useMemo(() => { if (!status) return []; const protocol = catalog?.protocol || ""; - const result = app ? desktopProfiles(status, app) : status.profiles.filter((profile) => profile.protocol === protocol); - return byProfileCreatedAt(result); + // A command-line Agent speaking its own format can also use a Chat + // Completions Profile, through compatibility mode. The adapter's own + // Profiles never appear: an Agent in compatibility mode is shown on the + // Profile its requests go to, which is the one a user would pick again. + const result = app + ? desktopProfiles(status, app) + : status.profiles.filter((profile) => profile.protocol === protocol || (canConvertProtocol(protocol) && profile.protocol === "openai")); + return byProfileCreatedAt(result.filter((profile) => !isConverterID(profile.id))); }, [app, catalog?.protocol, status]); + // Bound to its converter Profile, an Agent in compatibility mode is + // preselected on that route's target instead. + const boundId = app?.profileId || currentAgent?.profileId || ""; + const conversionTarget = boundId && isConverterID(boundId) && status ? conversionTargetFor(status, app?.id || owner) : undefined; + const currentId = conversionTarget?.id || boundId; useEffect(() => { if (!selectedId) { - const current = app?.profileId || currentAgent?.profileId || ""; - if (current && profiles.some((profile) => profile.id === current)) setSelectedId(current); + if (currentId && profiles.some((profile) => profile.id === currentId)) setSelectedId(currentId); else if (profiles[0]) setSelectedId(profiles[0].id); } - }, [app?.profileId, currentAgent?.profileId, profiles, selectedId]); + }, [currentId, profiles, selectedId]); const selected = profiles.find((profile) => profile.id === selectedId); - const requiresConversion = Boolean(app?.id === "claude-desktop" && selected?.protocol === "openai"); + // Claude Desktop is assessed first; a command-line Agent is checked when + // applied, because every check is a billed request (ConfigureAgentWithConversion). + const desktopConversion = Boolean(app?.id === "claude-desktop" && selected?.protocol === "openai"); + const cliConversion = Boolean(!app && canConvertProtocol(protocol) && selected?.protocol === "openai"); + const requiresConversion = desktopConversion || cliConversion; useEffect(() => { - if (!app || !selected || !requiresConversion) { + if (!app || !selected || !desktopConversion) { setAssessment(null); setAssessing(false); return; @@ -123,12 +141,12 @@ export function AgentProfilePage() { void api.assessDesktopAgentProfile(app.id, selected.id).then((result) => { if (active) setAssessment(result); }).catch((error) => { - if (active) setFailure(describeFailure(error, t("无法检查协议兼容性"), t).message); + if (active) reportFailure(error, t("无法确认能否使用兼容模式"), { key: `assess:${app.id}:${selected.id}` }); }).finally(() => { if (active) setAssessing(false); }); return () => { active = false; }; - }, [app, requiresConversion, selected, t]); + }, [app, desktopConversion, reportFailure, selected, t]); if (!status) { return ( @@ -150,7 +168,7 @@ export function AgentProfilePage() { const duplicateID = Boolean(draft && !draft.originalId && status.profiles.some((profile) => profile.id === draft.id.trim().toLowerCase())); const canSave = Boolean(draft?.id.trim() && draft?.provider && draft?.model.trim() && !duplicateID); const canApply = Boolean(selected && desktopProfileUsable(status, selected, app) && ( - !requiresConversion || assessment?.compatibility === "convertible" + !desktopConversion || assessment?.compatibility === "convertible" )); const separator = locale === "en" ? ", " : "、"; @@ -165,7 +183,7 @@ export function AgentProfilePage() { * the Profile showed nothing at all. Nothing is sent to the model: that is * what 检测模型 is for. */ - const persistProfile = async (request: SaveRequest, invalidateCheck = true) => { + const persistProfile = async (request: SaveRequest, invalidateCheck = true, announce = true) => { if (invalidateCheck) { checkGeneration.current += 1; setChecking(false); @@ -173,13 +191,12 @@ export function AgentProfilePage() { if (checked?.profileId === request.id) setChecked(null); const before = status.profiles.find((profile) => profile.id === request.id); const result = await api.saveProfile(request); - const failures = Object.entries(result.failures ?? {}); - if (failures.length) { - setFailure(t("{agents} 重新应用失败:{message}", { - agents: failures.map(([id]) => nameOf(id)).join(separator), - message: failures[0][1] ?? "", - })); - } + // The receipt names every Agent the save rewrote, which is the only sign + // that a model changed here also changed it for the other Agents on this + // Profile. A save that is only the first half of 应用 or 检测模型 stays quiet + // on success: that action reports for both. + const receipt = saveReceipt({ key: `profile:${request.id}`, name: request.label || request.id, result, nameOf, t, separator }); + if (announce || receipt.tone !== "success") feedback.show(receipt); const edit = before && before.provider === request.provider && before.model && before.model !== request.model ? { profileId: request.id, previousModel: before.model, request } : null; @@ -197,13 +214,12 @@ export function AgentProfilePage() { if (current?.model !== checked.model || current.provider !== lastEdit.request.provider) return; const request = { ...lastEdit.request, model: checked.previousModel }; setBusy(true); - setFailure(""); try { await persistProfile(request); setChecked(null); await refreshStatus(); } catch (error) { - setFailure(describeFailure(error, t("无法保存配置模版"), t).message); + feedback.failure(error, t("无法保存配置模版"), { key: `profile:${request.id}` }); } finally { setBusy(false); } @@ -220,7 +236,6 @@ export function AgentProfilePage() { let id = baseID; let suffix = 2; while (ids.has(id)) id = `${baseID}-${suffix++}`; - setFailure(""); setDraft({ id, label: t("{name} 配置模版", { name: targetName }), @@ -234,7 +249,6 @@ export function AgentProfilePage() { const openEdit = (profile: ProfileSummary) => { if (isConverterID(profile.id)) return; - setFailure(""); setDraft(draftFrom(profile)); }; @@ -242,7 +256,6 @@ export function AgentProfilePage() { event.preventDefault(); if (!draft || !canSave) return; setBusy(true); - setFailure(""); try { const { result: saved } = await persistProfile({ id: draft.id.trim().toLowerCase(), @@ -260,7 +273,7 @@ export function AgentProfilePage() { setDraft(null); await refreshStatus(); } catch (error) { - setFailure(describeFailure(error, t("无法保存配置模版"), t).message); + feedback.failure(error, t("无法保存配置模版"), { key: `profile:${draft.id.trim().toLowerCase()}` }); } finally { setBusy(false); } @@ -274,12 +287,11 @@ export function AgentProfilePage() { * write a Profile per letter typed. Everything else about the Profile is passed * through unchanged, so this cannot quietly reset a field the editor owns. */ - const commitModel = async (profile: ProfileSummary, next: string, invalidateCheck = true): Promise => { + const commitModel = async (profile: ProfileSummary, next: string, invalidateCheck = true, announce = true): Promise => { const model = next.trim(); setModelDraft(null); if (!model || model === (profile.model || "")) return { kind: "unchanged" }; setSavingModel(true); - setFailure(""); try { const { edit } = await persistProfile({ id: profile.id, @@ -292,11 +304,11 @@ export function AgentProfilePage() { context1M: Boolean(profile.context1M), configMode: "provider", protocol: profile.protocol || (app ? desktopProtocol(app) : catalog?.protocol || ""), - }, invalidateCheck); + }, invalidateCheck, announce); await refreshStatus(); return { kind: "saved", model, edit }; } catch (error) { - setFailure(describeFailure(error, t("无法保存配置模版"), t).message); + feedback.failure(error, t("无法保存配置模版"), { key: `profile:${profile.id}` }); return { kind: "failed" }; } finally { setSavingModel(false); @@ -312,18 +324,17 @@ export function AgentProfilePage() { if (!selected || checking || busy || savingModel) return; const generation = ++checkGeneration.current; setChecking(true); - setFailure(""); try { // This save belongs to the check; other saves and leaving the page // invalidate its generation, including while this flush is awaiting. - const flushed: CommitOutcome = modelDraft !== null ? await commitModel(selected, modelDraft, false) : { kind: "unchanged" }; + const flushed: CommitOutcome = modelDraft !== null ? await commitModel(selected, modelDraft, false, false) : { kind: "unchanged" }; if (flushed.kind === "failed" || checkGeneration.current !== generation) return; const check = await api.checkProfileModel(selected.id, [app?.id || owner]); if (checkGeneration.current !== generation) return; const edit = flushed.kind === "saved" ? flushed.edit : lastEdit; setChecked({ ...check, previousModel: edit?.profileId === selected.id && edit.request.model === check.model ? edit.previousModel : undefined }); } catch (error) { - if (checkGeneration.current === generation) setFailure(describeFailure(error, t("无法检测模型"), t).message); + if (checkGeneration.current === generation) feedback.failure(error, t("无法检测模型"), { key: `check:${selected.id}` }); } finally { if (checkGeneration.current === generation) setChecking(false); } @@ -335,10 +346,9 @@ export function AgentProfilePage() { // left 应用 enabled while the save was in flight, so a second click started // a second Apply. setBusy(true); - setFailure(""); // An uncommitted inline model edit is flushed first, so clicking 应用 straight // after typing applies what is on screen rather than the older stored model. - const flushed: CommitOutcome = modelDraft !== null ? await commitModel(selected, modelDraft) : { kind: "unchanged" }; + const flushed: CommitOutcome = modelDraft !== null ? await commitModel(selected, modelDraft, true, false) : { kind: "unchanged" }; if (flushed.kind === "failed") { // The Profile still holds the old model; applying now would apply that // while the field showed the new one. The save's error is already shown. @@ -349,22 +359,20 @@ export function AgentProfilePage() { // before the click, and activating with it would write the old model back // over the Agents the flush had just moved to the new one. const model = flushed.kind === "saved" ? flushed.model : selected.model || ""; + // Set by a desktop app that only reads its settings at startup. The backend + // says so for every managed write; dropping it left the user believing the + // running app had already switched. + let restart = ""; try { - if (app) { - if (requiresConversion) { - if (!await confirmAction({ - title: t("启用协议适配"), - message: t("BootAgent 将在本机启动协议适配服务,并自动把 Claude Desktop 指向该服务。是否继续?"), - confirmLabel: t("启用并应用"), - cancelLabel: t("取消"), - })) { - setBusy(false); - return; - } - await api.configureDesktopAgentWithConversion(app.id, selected.id); - } else { - await api.configureDesktopAgent(app.id, selected.id); + if (requiresConversion) { + if (!await confirmConversion(t)) { + setBusy(false); + return; } + if (app) restart = (await api.configureDesktopAgentWithConversion(app.id, selected.id))?.restart || ""; + else await api.activateAgentWithConversion(owner, selected.id); + } else if (app) { + restart = (await api.configureDesktopAgent(app.id, selected.id))?.restart || ""; } else { await api.activateAgent(owner, { provider: selected.provider, @@ -376,15 +384,41 @@ export function AgentProfilePage() { } await refreshStatus(); } catch (error) { - setFailure(describeFailure(error, t("应用配置模版失败"), t).message); + // Stays on this page: the choice that failed is what the user may change. + feedback.failure(error, t("应用配置模版失败"), { key: `apply:${agentId}` }); setBusy(false); return; } // Straight back to the overview, which is where the result is visible: the - // Agent's row now names this Profile. Staying here left the user on a - // screen whose job was done, with a success notice as the only feedback and - // a second click needed to see the effect. `replace` so Back does not - // return to a selection that has already been applied. + // Agent's row now names this Profile. The receipt outlives this page, so + // the switch is also said in words rather than left for the user to spot in + // the row. `replace` so Back does not return to a selection that has + // already been applied. + feedback.show(restart + ? { key: `apply:${agentId}`, tone: "warning", message: t("已应用,重启 {name} 后生效", { name: targetName }) } + : { key: `apply:${agentId}`, tone: "success", message: t("{agent} 已改用「{profile}」", { agent: targetName, profile: displayProfileName(selected) }) }); + navigate("/overview", { replace: true }); + }; + + /** + * The remedy a failed check offers: the checked Profile's Provider and model, + * through compatibility mode. A Chat Completions Profile for them is reused + * or saved first, since that is what the adapter forwards to. + */ + const useConversion = async () => { + const source = checked && status.profiles.find((profile) => profile.id === checked.profileId); + if (!source || busy) return; + if (!await confirmConversion(t)) return; + setBusy(true); + try { + await applyConversion(status, conversionTargets(status, [app?.id || owner]), source, t); + await refreshStatus(); + } catch (error) { + feedback.failure(error, t("无法开启兼容模式"), { key: `apply:${agentId}` }); + setBusy(false); + return; + } + feedback.show({ key: `apply:${agentId}`, tone: "success", message: t("{agent} 已改用兼容模式", { agent: targetName }) }); navigate("/overview", { replace: true }); }; @@ -393,7 +427,7 @@ export function AgentProfilePage() { title={t("选择配置模版")} backLabel={t("返回总览")} onBack={() => navigate("/overview")} - primaryLabel={busy ? t("应用中") : requiresConversion ? t("启用协议适配并应用") : t("应用")} + primaryLabel={busy ? t("应用中") : requiresConversion ? t("用兼容模式应用") : t("应用")} onPrimary={() => void apply()} primaryDisabled={!canApply || busy || savingModel || checking} footerNote={selected ? displayProfileName(selected) : t("选择一个配置模版")} @@ -405,7 +439,6 @@ export function AgentProfilePage() { )} > - {failure ?
{failure}
: null} {checked && !draft ? ( void revertModel()} onRecheck={checked.profileId === selected?.id ? () => void checkModel() : undefined} + onUseConversion={conversionTargets(status, [app?.id || owner]).length ? () => void useConversion() : undefined} onDismiss={() => setChecked(null)} /> ) : null} - {requiresConversion ? ( + {cliConversion ? ( +
+ {conversionTarget && selected?.id === conversionTarget.id + ? t("{agent} 正在通过兼容模式使用这个配置模版,使用期间需要保持 BootAgent 运行", { agent: targetName }) + : t("{agent} 不能直接使用这个配置模版,应用时会开启兼容模式在本机转换,使用期间需要保持 BootAgent 运行", { agent: targetName })} +
+ ) : null} + {desktopConversion ? (
{assessing - ? t("正在检查模型服务的协议兼容性") + ? t("正在确认能否使用兼容模式") : assessment?.compatibility === "convertible" - ? t("该模型服务不能直接使用 Claude Desktop 所需的 Anthropic Messages。BootAgent 可以在本机转换请求格式。") - : assessment?.message || t("无法确认该配置模版可以通过协议适配使用")} + ? t("{agent} 不能直接使用这个模型服务,应用时会开启兼容模式在本机转换,使用期间需要保持 BootAgent 运行", { agent: targetName }) + : assessment?.message || t("无法确认这个配置模版能否通过兼容模式使用")}
) : null} @@ -529,7 +570,7 @@ export function AgentProfilePage() { common change -- same Profile, different model -- costs no trip through the editor. The others stay one line of text; a picker on every card would be a wall of inputs. */} -

{status.providers[profile.provider]?.name || profile.provider} · {profile.model || t("未指定模型")}

+

{providerDisplayName(status.providers, profile.provider, t)} · {profile.model || t("未指定模型")}

{!usable ? {t("这个配置模版还缺少模型服务 Key 或模型")} : null} {!isConverterID(profile.id) ? : null} diff --git a/frontend/src/pages/AgentSelectionPage.tsx b/frontend/src/pages/AgentSelectionPage.tsx index 9e97f3f7..37e8e0e3 100644 --- a/frontend/src/pages/AgentSelectionPage.tsx +++ b/frontend/src/pages/AgentSelectionPage.tsx @@ -4,6 +4,7 @@ import { useNavigate } from "react-router-dom"; import { AgentRow } from "../components/AgentRow"; import { EditionTag } from "../components/EditionTag"; +import { EnvironmentSummary } from "../components/EnvironmentSummary"; import { AgentIcon } from "../components/icons/agents"; import { PageScaffold } from "../components/PageScaffold"; import { RuntimePrompt } from "../components/RuntimePrompt"; @@ -64,6 +65,7 @@ export function AgentSelectionPage() { {state.statusError ?
{state.statusError}
: null} {state.status ? ( <> +
diff --git a/frontend/src/pages/ConversionPage.test.tsx b/frontend/src/pages/ConversionPage.test.tsx index eb914a73..5dd92858 100644 --- a/frontend/src/pages/ConversionPage.test.tsx +++ b/frontend/src/pages/ConversionPage.test.tsx @@ -1,12 +1,17 @@ -import { fireEvent, render, screen } from "@testing-library/react"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import { MemoryRouter } from "react-router-dom"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { api } from "../backend/api"; +import { BootAgentApiError } from "../backend/errors"; +import { FeedbackProvider } from "../state/FeedbackContext"; +import type { StatusResponse } from "../types/api"; import { ConversionPage } from "./ConversionPage"; +let mockStatus: StatusResponse | null = null; + vi.mock("../state/WizardContext", () => ({ - useWizard: () => ({ state: { status: null }, refreshStatus: vi.fn() }), + useWizard: () => ({ state: { status: mockStatus }, refreshStatus: vi.fn() }), })); beforeEach(() => { @@ -16,6 +21,7 @@ beforeEach(() => { listen: "127.0.0.1:8787", has_api_key: false, target_profile: "", + routes: {}, anthropic_model: "claude-sonnet-5", responses_model: "gpt-5.6-sol", chat_model: "gpt-5.6-sol", @@ -25,36 +31,125 @@ beforeEach(() => { afterEach(() => { localStorage.clear(); vi.restoreAllMocks(); + mockStatus = null; }); describe("ConversionPage", () => { - it("keeps the operational controls ahead of optional protocol guidance", async () => { + it("leads with status and the Agents using it, and keeps the format details behind a disclosure", async () => { render( , ); - const status = await screen.findByText("适配服务已停止"); - const target = screen.getByText("请求最终发往"); - const guidance = screen.getByText("了解协议适配"); - - expect(status.compareDocumentPosition(target) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - expect(target.compareDocumentPosition(guidance) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - expect(screen.queryByText(/不同 Agent 要求的 API 协议不一样/)).toBeNull(); + const status = await screen.findByText("兼容模式未开启"); + const users = screen.getByText("正在使用的 Agent"); + const guidance = screen.getByText("了解兼容模式"); + expect(status.compareDocumentPosition(users) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(users.compareDocumentPosition(guidance) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + // There is no single model to pick: each Agent has its own. + expect(screen.queryByRole("combobox")).toBeNull(); + const formats = screen.getByText(/OpenAI Responses 格式/); + expect(formats.closest("details")).not.toHaveAttribute("open"); fireEvent.click(guidance); - expect(screen.getByText(/不同 Agent 使用的 API 协议并不相同/)).toBeTruthy(); + expect(formats.closest("details")).toHaveAttribute("open"); + }); + + it("offers one primary action, and no stop button while stopped", async () => { + render( + + + , + ); + + // Nothing uses it yet, so there is nothing to turn on. + expect(await screen.findByRole("button", { name: "开启兼容模式" })).toBeDisabled(); + expect(screen.queryByRole("button", { name: "停止兼容模式" })).toBeNull(); + }); + + // A failed load leaves the page with nothing on it, so the receipt carries + // the retry rather than the page. + it("offers a retry when the settings cannot be read", async () => { + const load = vi.spyOn(api, "getConversion").mockRejectedValueOnce(new BootAgentApiError("boom", "INTERNAL_ERROR", true, 500)); + render( + + + + + , + ); + const receipt = await screen.findByRole("alert"); + expect(receipt).toHaveTextContent("无法读取兼容模式设置"); + fireEvent.click(screen.getByRole("button", { name: "重试" })); + expect(await screen.findByText("兼容模式未开启")).toBeTruthy(); + expect(load).toHaveBeenCalledTimes(2); + }); + + it("confirms a saved change with a receipt instead of a line in the page", async () => { + vi.spyOn(api, "saveConversion").mockImplementation(async (config) => config); + vi.spyOn(api, "getSettings").mockResolvedValue({ autostart: true } as never); + render( + + + + + , + ); + await screen.findByText("兼容模式未开启"); + fireEvent.click(screen.getByRole("button", { name: "高级设置" })); + fireEvent.change(screen.getByLabelText("监听地址"), { target: { value: "127.0.0.1:9797" } }); + fireEvent.click(screen.getByRole("button", { name: "保存更改" })); + expect(await screen.findByText("已保存兼容模式设置")).toBeTruthy(); + }); + + it("saves an advanced setting without turning compatibility mode on", async () => { + const save = vi.spyOn(api, "saveConversion").mockImplementation(async (config) => config); + vi.spyOn(api, "getSettings").mockResolvedValue({ autostart: true } as never); + render( + + + , + ); + + await screen.findByText("兼容模式未开启"); + fireEvent.click(screen.getByRole("button", { name: "高级设置" })); + fireEvent.change(screen.getByLabelText("监听地址"), { target: { value: "127.0.0.1:9797" } }); + fireEvent.click(screen.getByRole("button", { name: "保存更改" })); + await waitFor(() => expect(save).toHaveBeenCalledWith(expect.objectContaining({ listen: "127.0.0.1:9797", enabled: false }))); }); - it("offers an actionable route when no compatible profile exists", async () => { + // The single shared target this replaced showed every Agent on the same + // model; each now names the service its own requests go to. + it("shows each Agent's own model service and links to change only that Agent", async () => { + mockStatus = { + providers: { ppio: { name: "PPIO" }, novita: { name: "Novita" } }, + catalog: [{ id: "codex", name: "Codex" }, { id: "claude-code", name: "Claude Code" }], + agents: { + codex: { profileId: "bootagent-converter-for-codex" }, + "claude-code": { profileId: "bootagent-converter-for-claude-code" }, + }, + desktopAgents: [], + profiles: [ + { id: "ppio-chat", label: "PPIO", provider: "ppio", model: "deepseek-v3", protocol: "openai" }, + { id: "novita-chat", label: "Novita", provider: "novita", model: "glm-5", protocol: "openai" }, + ], + conversionRoutes: { codex: "ppio-chat", "claude-code": "novita-chat" }, + } as unknown as StatusResponse; render( , ); - expect(await screen.findByRole("link", { name: "创建配置模板" })).toHaveAttribute("href", "/profiles"); + const list = await screen.findByRole("list"); + const rows = Array.from(list.querySelectorAll("li")).map((row) => row.textContent); + expect(rows[0]).toContain("Codex"); + expect(rows[0]).toContain("PPIO · deepseek-v3"); + expect(rows[1]).toContain("Claude Code"); + expect(rows[1]).toContain("Novita · glm-5"); + expect(screen.getByRole("button", { name: "为 Codex 更换模型" })).toBeTruthy(); + expect(screen.getByRole("button", { name: "开启兼容模式" })).toBeEnabled(); }); it("does not expose a local API key input", async () => { @@ -64,7 +159,7 @@ describe("ConversionPage", () => { , ); - await screen.findByText("适配服务已停止"); + await screen.findByText("兼容模式未开启"); fireEvent.click(screen.getByRole("button", { name: "高级设置" })); expect(screen.queryByLabelText("本地 API Key")).toBeNull(); expect(screen.getByText("启动时自动生成")).toBeTruthy(); diff --git a/frontend/src/pages/ConversionPage.tsx b/frontend/src/pages/ConversionPage.tsx index 978cc4a7..fe012a2d 100644 --- a/frontend/src/pages/ConversionPage.tsx +++ b/frontend/src/pages/ConversionPage.tsx @@ -1,26 +1,41 @@ import { ChevronDown, ChevronUp, CircleHelp, Power } from "lucide-react"; -import { useEffect, useRef, useState } from "react"; -import { Link } from "react-router-dom"; +import { useCallback, useEffect, useRef, useState } from "react"; +import { Link, useNavigate } from "react-router-dom"; -import { api, describeFailure } from "../backend/api"; +import { api } from "../backend/api"; import { PageScaffold } from "../components/PageScaffold"; -import { SelectField } from "../components/SelectField"; import { StatusBadge } from "../components/StatusBadge"; import { useI18n } from "../i18n"; import { useWizard } from "../state/WizardContext"; -import { isConverterID } from "../state/conversion"; +import { agentsUsingConversion, providerDisplayName } from "../state/conversion"; import { confirmAction } from "../state/confirmDelete"; -import { PROTOCOL_LABELS, type ConversionConfig, type ProtocolId } from "../types/api"; +import { useFeedback } from "../state/FeedbackContext"; +import type { ConversionConfig } from "../types/api"; +/** + * Compatibility mode: the local adapter that lets an Agent speaking its own + * format use a Chat Completions-only model service. + * + * Mostly a status page. Agents are switched to it where the problem shows -- + * the setup wizard's connection test, an Agent's Profile list, a failed model + * check -- so this page says what is running and, for each Agent, which model + * service its requests go to. Each Agent has its own route; changing one is + * done on that Agent's page and changes nothing for the others. + */ export function ConversionPage() { - const { t } = useI18n(); + const navigate = useNavigate(); + const { locale, t } = useI18n(); const { state, refreshStatus } = useWizard(); const status = state.status; const [config, setConfig] = useState(null); - const [failure, setFailure] = useState(""); + const [saved, setSaved] = useState(null); + const feedback = useFeedback(); + // Stable across receipts, unlike `feedback`, so the load effect can depend on it. + const reportFailure = feedback.failure; const [saving, setSaving] = useState(false); const [showAdvanced, setShowAdvanced] = useState(false); const autostartPrompted = useRef(false); + const separator = locale === "en" ? ", " : "、"; const maybeAskAutostart = async (enabled: boolean) => { if (!enabled || autostartPrompted.current) return; @@ -30,135 +45,138 @@ export function ConversionPage() { if (settings.autostart) return; if (!await confirmAction({ title: t("开机自启动"), - message: t("API 转换已启用,是否让 BootAgent 随系统启动?"), + message: t("兼容模式需要 BootAgent 保持运行。要让 BootAgent 随系统启动吗?"), confirmLabel: t("开机自启动"), cancelLabel: t("暂不启用"), })) return; await api.saveSettings({ autostart: true }); } catch (error) { - setFailure(describeFailure(error, t("无法保存开机自启动设置"), t).message); + feedback.failure(error, t("无法保存开机自启动设置"), { key: "autostart" }); } }; - useEffect(() => { + // Retryable from the receipt: a failed load leaves the page with nothing to + // show, and the receipt is the only control on it. + const load = useCallback(() => { void api.getConversion().then((loaded) => { setConfig(loaded); + setSaved(loaded); void maybeAskAutostart(loaded.enabled); - }).catch((error) => setFailure(describeFailure(error, t("无法读取格式转换设置"), t).message)); - }, [t]); + }).catch((error) => reportFailure(error, t("无法读取兼容模式设置"), { key: "conversion-load", action: { label: t("重试"), run: load } })); + // maybeAskAutostart only reads a ref and stable calls. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [reportFailure, t]); + useEffect(load, [load]); - const save = async () => { - if (!config) return; + const persist = async (next: ConversionConfig, done: string, fallback: string) => { setSaving(true); - setFailure(""); try { - const saved = await api.saveConversion(config); - setConfig(saved); - await maybeAskAutostart(saved.enabled); - void refreshStatus(); - } - catch (error) { setFailure(describeFailure(error, t("无法保存格式转换设置"), t).message); } - finally { setSaving(false); } - }; - - const toggle = async () => { - if (!config) return; - setSaving(true); - setFailure(""); - try { - const saved = await api.saveConversion({ ...config, enabled: !config.enabled }); - setConfig(saved); - await maybeAskAutostart(saved.enabled); + const result = await api.saveConversion(next); + setConfig(result); + setSaved(result); + feedback.show({ key: "conversion", tone: "success", message: done }); + await maybeAskAutostart(result.enabled); void refreshStatus(); + } catch (error) { + feedback.failure(error, fallback, { key: "conversion" }); + } finally { + setSaving(false); } - catch (error) { setFailure(describeFailure(error, t("无法切换格式转换"), t).message); } - finally { setSaving(false); } }; const regenerateKey = async () => { setSaving(true); - setFailure(""); try { - const saved = await api.regenerateConversionKey(); - setConfig(saved); + const result = await api.regenerateConversionKey(); + setConfig(result); + setSaved(result); + feedback.show({ key: "conversion-key", tone: "success", message: t("已重新生成本地 Key") }); void refreshStatus(); } catch (error) { - setFailure(describeFailure(error, t("无法重新生成本地 Key"), t).message); + feedback.failure(error, t("无法重新生成本地 Key"), { key: "conversion-key" }); } finally { setSaving(false); } }; - const profiles = (status?.profiles ?? []).filter((profile) => profile.protocol === "openai" && profile.model); - // Only auto-configured Agents can be pointed anywhere, and an Agent already - // speaking Chat Completions has nothing to gain: the adapter converts *to* that - // protocol, so listing one would suggest a benefit it cannot deliver. - const adaptableAgents = (status?.catalog ?? []).filter( - (agent) => agent.configMode === "auto" && agent.protocol && agent.protocol !== "openai", - ); - const converterProfileIDs = new Set((status?.profiles ?? []).filter((profile) => isConverterID(profile.id)).map((profile) => profile.id)); - const usesAdapter = (agentID: string) => { - const boundProfile = status?.agents[agentID]?.profileId; - return Boolean(boundProfile && converterProfileIDs.has(boundProfile)); + const users = agentsUsingConversion(status); + const dirty = Boolean(config && saved && ( + config.listen !== saved.listen + || config.anthropic_model !== saved.anthropic_model + || config.responses_model !== saved.responses_model + || config.chat_model !== saved.chat_model + )); + + const stop = async () => { + if (!config) return; + if (users.length && !await confirmAction({ + title: t("停止兼容模式"), + message: t("停止后 {agents} 将无法使用,直到重新开启兼容模式或换一个配置模版。", { agents: users.map((user) => user.name).join(separator) }), + confirmLabel: t("停止"), + cancelLabel: t("取消"), + })) return; + await persist({ ...config, enabled: false }, t("兼容模式已停止"), t("无法停止兼容模式")); + }; + + // One primary action. Unsaved changes: save them, leaving it running or not. + // Otherwise stopped: turn it on, which only makes sense once an Agent uses + // it. Stopping is the secondary action, and only exists while it runs. + const running = Boolean(config?.enabled); + const savesChanges = dirty || running; + const primaryLabel = savesChanges ? t("保存更改") : t("开启兼容模式"); + const onPrimary = () => { + if (!config) return; + if (savesChanges) void persist(config, t("已保存兼容模式设置"), t("无法保存兼容模式设置")); + else void persist({ ...config, enabled: true }, t("兼容模式已开启"), t("无法开启兼容模式")); }; + return ( void toggle()} disabled={saving || !config.target_profile}>{config.enabled ? t("停止服务") : t("启动服务")} : null} - primaryLabel={t("保存设置")} - onPrimary={() => void save()} - primaryDisabled={!config || !config.target_profile} + secondaryAction={running ? ( + + ) : null} + primaryLabel={primaryLabel} + onPrimary={onPrimary} + primaryDisabled={!config || (savesChanges ? !dirty : users.length === 0)} primaryBusy={saving} > - {failure ?

{failure}

: null} {config ?
-
+
-
-
- - setConfig({ ...config, target_profile: value })} - options={profiles.map((profile) => ({ value: profile.id, label: profile.label || profile.id }))} - /> - {profiles.length === 0 ? ( -
- {t("还没有可用的 Chat Completions 配置模板")} - {t("创建配置模板")} -
- ) : null} -
-
-
-

{t("适用 Agent")}

- {t("{count} 个可使用", { count: adaptableAgents.length })} +

{t("正在使用的 Agent")}

- {adaptableAgents.length === 0 ? ( + {users.length === 0 ? (
- {t("当前没有可使用协议适配的 Agent")} + {t("还没有 Agent 使用兼容模式")} {t("查看环境总览")}
) : (
    - {adaptableAgents.map((agent) => ( -
  • - {agent.name} + {users.map((user) => ( +
  • + {user.name} - {PROTOCOL_LABELS[agent.protocol as ProtocolId] ?? agent.protocol ?? ""} + {user.target + ? `${status ? providerDisplayName(status.providers, user.target.provider, t) : user.target.provider} · ${user.target.model}` + : t("使用的配置模版已删除")} - {usesAdapter(agent.id) ? {t("已指向适配器")} : null} + {running ? {t("运行中")} : {t("已停止")}} +
  • ))}
@@ -203,8 +221,10 @@ export function ConversionPage() { ) : null}
+ {/* What each Agent is told the model is called. The model that + actually answers is the one chosen above. */}
- +
- +
- +
- {t("了解协议适配")} + {t("了解兼容模式")}
-

{t("不同 Agent 使用的 API 协议并不相同。Codex 使用 OpenAI Responses,Claude Code 使用 Anthropic Messages,其他 Agent 可能使用 Chat Completions。")}

-

{t("BootAgent 只在本机转换请求格式,再把请求发往上方选中的配置模板;模型与凭据仍由该配置模板管理。")}

+

{t("Codex 发出的是 OpenAI Responses 格式,Claude Code 是 Anthropic Messages 格式,很多模型服务只支持 OpenAI Chat Completions。BootAgent 在本机把前两种转换成 Chat Completions,再发往每个 Agent 各自选择的模型。")}

+

{t("每个 Agent 用自己的本机 Key 连接,互不影响;模型和 Key 仍由各自的配置模版管理。")}

: null} diff --git a/frontend/src/pages/EnvironmentOverviewPage.tsx b/frontend/src/pages/EnvironmentOverviewPage.tsx index d86957e7..ec356d8f 100644 --- a/frontend/src/pages/EnvironmentOverviewPage.tsx +++ b/frontend/src/pages/EnvironmentOverviewPage.tsx @@ -6,7 +6,7 @@ import { DesktopAppSection } from "../components/DesktopAppSection"; import { PageScaffold } from "../components/PageScaffold"; import { RuntimeSection } from "../components/RuntimeSection"; import { useI18n } from "../i18n"; -import { converterProfileName } from "../state/conversion"; +import { conversionDisplay, providerDisplayName } from "../state/conversion"; import { desktopApps, profileAgentIdForDesktop } from "../state/desktopSetup"; import { useWizard } from "../state/WizardContext"; import type { AgentStatus } from "../types/api"; @@ -84,11 +84,13 @@ export function EnvironmentOverviewPage() { {installedDesktopApplications.map((app) => { const binding = status.agents[profileAgentIdForDesktop(app)]; const profileID = app.profileId || binding?.profileId; - const profile = profileID ? status.profiles.find((item) => item.id === profileID) : undefined; + // In compatibility mode the row names the model service behind + // the adapter, which is what this app actually uses. + const { profile } = conversionDisplay(status, app.id, profileID ? status.profiles.find((item) => item.id === profileID) : undefined, t); const providerName = profile - ? status.providers[profile.provider]?.name || profile.provider + ? providerDisplayName(status.providers, profile.provider, t) : binding?.provider - ? status.providers[binding.provider]?.name || binding.provider + ? providerDisplayName(status.providers, binding.provider, t) : undefined; const model = profile?.model || binding?.model || undefined; return ( @@ -128,14 +130,14 @@ export function EnvironmentOverviewPage() { {installed.map((item) => { const agent = status.agents[item.id]; if (!agent) return null; - const profile = profileForAgent(item.id, agent); + const { profile, name } = conversionDisplay(status, item.id, profileForAgent(item.id, agent), t); return vi.fn(() => ({ tasks: [], cancelTask: vi.fn(), dismissTask: vi.fn(), progress: {}, running: {} }))); @@ -69,3 +70,40 @@ describe("InstallTaskPage update route", () => { expect(screen.getByRole("region", { name: "任务时间线" })).toBeTruthy(); }); }); + +// An install ends on this page, so it is where the first task has to be offered. +describe("InstallTaskPage first task", () => { + function renderTask(kind: "install" | "update", state: "success" | "failure") { + mockUseTaskCenter.mockReturnValue({ + tasks: [{ + id: `${kind}:codex`, kind, target: "codex", title: "安装 Codex", route: `/tasks/${kind}/codex`, + progressTarget: "", state, message: "", startedAt: 1, events: [], + }], + cancelTask: vi.fn(), dismissTask: vi.fn(), progress: {}, running: {}, + } as never); + render( + + } /> + , + ); + } + + it("is offered once an Agent has installed", async () => { + const agents = vi.spyOn(api, "firstTaskAgents").mockResolvedValue([{ id: "codex", name: "Codex" }]); + renderTask("install", "success"); + + expect(await screen.findByRole("heading", { name: "跑一个小任务试试" })).toBeTruthy(); + agents.mockRestore(); + }); + + // An update leaves an Agent the user already knows, and a failed install + // leaves nothing to run. Neither asks the backend at all. + it("is not offered after an update or a failed install", () => { + const agents = vi.spyOn(api, "firstTaskAgents").mockResolvedValue([{ id: "codex", name: "Codex" }]); + renderTask("update", "success"); + renderTask("install", "failure"); + + expect(agents).not.toHaveBeenCalled(); + agents.mockRestore(); + }); +}); diff --git a/frontend/src/pages/InstallTaskPage.tsx b/frontend/src/pages/InstallTaskPage.tsx index 65c1003b..a61e170c 100644 --- a/frontend/src/pages/InstallTaskPage.tsx +++ b/frontend/src/pages/InstallTaskPage.tsx @@ -1,6 +1,7 @@ import { useLocation, useNavigate, useParams } from "react-router-dom"; import { DownloadProgress } from "../components/DownloadProgress"; +import { FirstTaskSection } from "../components/FirstTaskSection"; import { LogDisclosure } from "../components/LogDisclosure"; import { PageScaffold } from "../components/PageScaffold"; import { useI18n } from "../i18n"; @@ -80,6 +81,10 @@ export function InstallTaskPage() {
) : null} {task.log ? : null} + {/* This is the page an install ends on, so it is where the new Agent is + first offered something to do. The section hides itself for an Agent + that cannot run unattended, which covers every desktop app. */} + {kind === "install" && task.state === "success" ? : null} {task.state !== "running" && task.action ? ( } primaryLabel={dirtyCount ? t("应用更改({count})", { count: dirtyCount }) : t("应用更改")} onPrimary={() => void apply()} primaryDisabled={!dirty}> + return {t("去市场发现")}} primaryLabel={dirtyCount ? t("应用更改({count})", { count: dirtyCount }) : t("应用更改")} onPrimary={() => void apply()} primaryDisabled={!dirty} primaryBusy={applying}>

{t("MCP Registry")}

{t("配置只在点击应用更改后写入 Agent")}

{scanning ?
{t("正在后台扫描")}
: null} {rows.length ?
: null} - {!rows.length ? {t("或者去工具市场发现")}} /> : !visibleRows.length ? :
{visibleRows.map((row) => { const isDeleted = Boolean(deleted[row.id]); return ; })}
{t("服务器")}{t("传输")}{t("同步目标")}{t("状态")}
{row.id}{row.type} setTargets((all) => { const current = new Set(all[row.id] ?? agentsFor(row)); checked ? current.add(agent) : current.delete(agent); return { ...all, [row.id]: [...current] }; })} />{isDeleted ? t("待删除") : row.conflict ? t("冲突") : mcpRowPending(row.id, draft, targets) ? t("待应用") : t("已同步")}{row.has_secrets ? {t("包含秘密字段")} : null}
} + {!rows.length && loadFailed ? : !rows.length ? {t("或者去工具市场发现")}} /> : !visibleRows.length ? :
{visibleRows.map((row) => { const isDeleted = Boolean(deleted[row.id]); return ; })}
{t("服务器")}{t("传输")}{t("同步目标")}{t("状态")}
{row.id}{row.type} setTargets((all) => { const current = new Set(all[row.id] ?? agentsFor(row)); checked ? current.add(agent) : current.delete(agent); return { ...all, [row.id]: [...current] }; })} />{isDeleted ? t("待删除") : row.conflict ? t("冲突") : mcpRowPending(row.id, draft, targets) ? t("待应用") : t("已同步")}{row.has_secrets ? {t("包含秘密字段")} : null}
}
- {editing !== null ? setEditing(null)}>

{editing ? t("编辑 MCP 服务器") : t("新增 MCP 服务器")}

{t("传输")} { const next = changeMCPTransport(form, type); setForm(next); setCommandLine(type === "stdio" ? formatStdioCommandLine(next) : ""); setAdvancedJSON(JSON.stringify(next, null, 2)); }} label={t("传输")} />
{form.type === "stdio" ? : }