Compare commits

..

9 Commits

Author SHA1 Message Date
771b95a133 fix(channels): admit_functions 落到 effectiveModels(解析器不承担产品策略)
上一提交把「本适配器会发的通道」过滤写进了 trae 的目录解析器,导致两个解析器判据
回归:同模型在 solo_agent(有思考档位)与 solo_work_lite(无档位)同时出现时,
整组 solo_agent 被丢弃 ⇒ 档位信息丢光,模型显示"未提供推理等级"。

正确分层:
- **解析器**只负责把目录如实解出来(含跨通道元数据合并、白名单准入);
- **产品策略**(只暴露适配器能发的通道)放到 effectiveModels,作用在对外
  暴露的 id 列表上。

实现要点:合并会选"更优"的那条(往往不在我们要发的通道里),所以判据不能看
合并后条目的 chan —— 解析时额外记 `chans`(该 id 在哪些通道出现过),策略按
chans 求交集。夹具同步调整:硬性过滤的条目放进 solo_work_lite(生产里适配器
恒发这条通道),inline_chat 仍用于白名单判据。
2026-10-20 10:12:51 +08:00
441de434f5 chore(gui): 版本号 2.0.45(与内核同版本) 2026-10-20 09:54:06 +08:00
9feef8f4cb fix(channels): 渠道卡片 logged_in 改成看账号池(此前所有池接入的平台都显示未登录)
## 真因:logged_in 判的是旧单账号键
用户报「codearts 还是不可用」。查下来渠道**本身是通的**(9 个模型逐个实测都返回
内容),不可用的是**UI 的登录态判断**:

`list_platforms` 写的是 `credentialOf("channels:" .. platform)` —— 那是**旧版
单账号**的保险库键。现网凭据键是 `channels:<platform>:<accountId>`(一平台多
账号),于是**所有**通过账号池接入的平台都被判成"未登录":

    修复前(生产):trae=False minimax=False codearts=False qoder=False zcode=False
                    (只有 buddy=True —— 它还留着一条旧格式凭据)
    修复后:          trae=True  minimax=True  codearts=True qoder=True  zcode=True

UI 据此把渠道卡片渲染成"未接入",用户看到的就是"渠道不可用"。底层模型完全能用 ——
这是最容易被误判成"上游挂了"的一类假信号。

## 修法
- `list_platforms`:logged_in 改为遍历账号池(`poolList` + 凭据存在 + enabled≠false),
  旧单账号仅作兜底;顺带回 `account_id` / `accounts` 计数,让 UI 能区分同平台多账号;
- `status_page`:`accounts` 同样合并账号池(此前只回旧表,状态页里池接入的平台
  是空的 —— 同一根因的第二个出口);
- 新增 `__platforms_probe`(`list_platforms` 是 HTTP 路由处理器、不在 exports 里,
  判据走探针,与仓库既有做法一致);
- 回归判据 `TestPlatformsLoggedInFromAccountPool`:池里有凭据账号 ⇒ logged_in=true,
  且 account_id / account / accounts 回池数据。

## 顺带核实(不是代码缺陷)
- codearts 目录里 4 个模型(`deepseek-v4-flash-0731` / `glm-5.3-flash` /
  `deepseek-v4-pro-0813` / `CodeArts-Pangu`)实测上游 404
  `InferHub.002002009.404: The model is not registered` ⇒ 之前被手工停用是对的,
  已按死模型流程收口(不再回到可选列表);
- `GLM-5.3` 同样 404,已标失效并自动从源里剔除(日志:
  「模型已失效,已标记 codearts/GLM-5.3」);
- `deepseek-v4-flash` 早前的 429 是 TPM 限流(我自己连续压测造成),现已恢复 OK。
- 最终 codearts:**9 个模型,9/9 实测返回内容**。
2026-10-20 09:54:06 +08:00
b5c89fd3d7 chore(gui): 版本号 2.0.44(与内核同版本,桌面插件刷新判据依赖它) 2026-10-20 09:39:49 +08:00
7f193a997d fix(channels): trae 目录用错头族——IDE 端点必须发 IDE 头(此前恒回 2001)
## 真因:两套头混用
用户报「trae 还是无法从上游拉取,示例插件都可以」。用探针把**原始响应**打出来
才看清:目录端点 HTTP **200**,但 22 个 function 全部
`error_code 2001 "Config detail for function: X not found"` —— 于是远端目录恒空,
插件只能退回兜底表,用户侧表现成「模型不正确 / 渠道不可用」。

根因不是网络、不是账号、不是 body:是**头族用错了**。
- `traeCheckinHeaders` 面向 `api.trae.cn` 的签到/积分:VSCode UA + `X-Market-*`
  + `X-Lscbd-*` + `Vscode-Sessionid` + **派生**的 market device id;
- `traeIdeHeaders` 面向 `trae-api-cn.mchost.guru` 的目录/对话:`Trae/0.1.52` UA
  + `X-App-Id` + `X-Ide-Version(-Code)` + `Request-Traffic-Type` +
  **凭据里登录时的** `device_id`/`machine_id`。

目录刷新当时复用的是签到头(注释还写着"复用更安全"),发到 IDE 端点就被逐
function 判 2001。用 IDE 头直发同一端点:**HTTP 200 + 2.6 MB**、每个 function
都带 `config_info_list`。

修法(全部在插件内,内核零改动):
1. 新增 `traeIdeHeaders()`,与签到头**明确分开**,注释写清两套头的适用面;
2. 目录刷新(`sign="trae_solo"`)改用它,`Accept: application/json`;
3. 加判据 `__trae_headers_probe` + `TestTraeHeadersKeptSeparate`:钉死两套头的
   键集合互不越界(IDE 头必须有 X-App-Id/X-Machine-Id、不得有 X-Market-*;
   签到头反之)。这类"都能跑、但跑错了"的错只能靠契约钉死。

## 目录拉通后暴露的第二个问题:目录≠可调用
拿到真实目录(22 function / 93 条去重模型)后逐个实测,发现**同一个
config_name 在不同 function 里可用性不同**,而本插件适配器恒发
`solo_work_lite`:
- `kimi-k2.8-preview` / `deepseek-V3` / `glm-4.7` / `code-review-judge` /
  `multimodal_image_kimi-k2.5` → HTTP 200 但 **content 为空**;
- `sagitta` → 自称 Claude、`aquila` → 自称 ChatGPT、`custom_model_gpt-5` →
  自称 GPT-4 系列 ⇒ 这些是**未知 config 时上游悄悄回落默认模型** ——
  这正是"模型不正确"的真实来源。

于是补两道准入(都是**声明式**平台数据,不写死逻辑):
- `models_remote.admit_functions = { "solo_work_lite" }`:只收本适配器**会发**
  的那条通道里的模型(白名单只说"该通道在本端点可调用",不等于"适配器会发");
- `models_fallback_no_supplement = true`:远端目录可用时**不再补兜底表**
  (兜底表里 sagitta/aquila/glm-5/DeepSeek-V4-Flash 等在上游已无对应配置)。

结果:trae 可选模型 = **20 个**(glm-5.3 / glm-5.3-flash / glm-5.3-flashx /
glm-5.2 / kimi-k3 / kimi-k2.7-code / kimi-k2.6 / minimax-m3 / minimax-m3.1-flash /
qwen3.8-max / qwen-3.7-plus / step-5-preview / mimo-v2.6-{flash,pro} /
deepseek-v4.1-flash / DeepSeek-V4-{Flash,Pro}-Official / Doubao-Seed-2.1-{Pro,Turbo,Evolving}),
**20/20 逐个实测返回非空内容**。

## 回归测试
- `TestTraeHeadersKeptSeparate`(新):两套头键集合互斥(不联网即可复现该类回归)
- `TestTraeCustomModelSlotsAreNotOffered` / `TestTraeSourceOmitsCustomModelSlots`
  (上一版):custom_model_* 槽位不进 UI 也不进上游源
- 死模型判据:opencode 的 `has been deprecated` 文案阳/阴性(上一版)
2026-10-20 09:38:39 +08:00
055705c134 chore(gui): 版本号 2.0.43(与内核同版本;桌面插件刷新判据按 app 版本,必须同步)
桌面壳的「内置插件升级刷新」按 app.getVersion() 打戳:GUI 版本号若与内核脱节,
升级后 channels.lua 不会重新播种,渠道修复又会被静默留在旧版。
2026-10-20 09:22:16 +08:00
401a7ead27 fix(channels): trae 模型表去掉不可调用槽位 + opencode 免费模型按实测收敛
## ① trae:模型选择器里那几个 `custom_model_*` 是**槽位不是模型**
用户报「trae 的模型不正确 / 渠道不可用」。逐个实测(生产):
`custom_model_kimi` / `custom_model_claude` / `custom_model_1M` 返回 **空
content**(`custom_model_gpt-5` 也答非所问),而真实模型
(glm-5.2 → Z.ai GLM、kimi-k3 → Moonshot、minimax-m3 → MiniMax、
Doubao-Seed-2.1-Pro → 字节)全部正常 —— 所以渠道是通的,问题在**表**。

根因:`custom_model_*` 是 TRAE 的「自定义模型槽位」,上游目录里它们的权威
判据是 `is_custom_model: true`。插件自己的 `trae_batch` 解析器早已按这条
**准入**剔除,但**兜底表**把它们当普通模型列了出来;而远端目录在部分账号
下恒空(企业租户账号实测:22 个 function 全回
`error_code 2001 Config detail for function: X not found`),用户只能看到
兜底表 ⇒ 选中槽位后上游回空 ⇒ 「模型坏了」。

修法(**纯插件**,内核零改动):
- 新增 `models_unavailable` 一档:声明「本协议下不可调用」的条目,
  **既不进 UI 选择器,也不进上游源**(与 `models_hidden` 区别:后者只是
  不进 UI,内部子 agent 仍可显式调用);
- trae 的 11 个 `custom_model_*` 移入该档;把 4 个内部子 agent 留在
  `models_hidden`(语义不变);
- 生产验证:trae 源/选择器从 28 → **17**,逐个实测 17 个全部返回非空内容。

## ② 远端目录「空」要能区分原因
`refresh_models` 此前只会报「远端返回空目录」,把两种完全不同的故障混为一谈:
网络/HTTP 故障 vs 服务端 200 但账号侧没有可下发配置。
现在后者如实报:「远端 200 但无模型配置(账号侧未下发 function config,
企业/租户账号需管理员开启,实测 error_code 2001)」——运维据此知道该找
租户管理员,而不是反复重试网络。
另加 `__trae_catalog_probe`(诊断探针):原样回传目录端点的 status/body 前
N 字节/解析条数,并在 2001 现场定位时立了大功(这类"上游 200 却空目录"没有
原始响应只能瞎猜)。

## ③ opencode / localzen:免费模型按**实测**收敛
用户报「localzen 也不能用了」。逐项实测(生产):
- `space-bunny-free` → **410** `Model space-bunny-free has been deprecated.
  Use minimax-m3.1-flash-free instead.`(仍在本地源里 ⇒ 选中必失败)
- `jev-1.13-free` → 400 `Model does not support this protocol.`(非 OpenAI
  chat 协议,本端点永远调不通)
- `beam-free` → 200 但 content 空、无 finish_reason
- 其余 7 个(mimo / nemotron-super-vl / nemotron-lightning / longcat /
  deepseek-v4.1 / glm-5.3-flash / minimax-m3.1-flash)全部正常返回内容

修法:
- `DEAD_GONE_PATTERNS` 补 opencode 的下架文案
  (`Model … has been deprecated`);配阴/阳性判据(参数/字段被弃用**不算**);
- opencode 平台把 jev-1.13-free / beam-free 列入 `models_unavailable`,
  并从兜底表与 models_free 里移除;
- 生产 `localzen` 源(手写源,插件不管)按实测刷新为 7 个可用免费模型,
  逐个验证返回内容。

## 纪律
渠道逻辑全部留在插件里(channels.lua / 插件自装适配器);内核这轮**没有**
新增任何厂商语义 —— 上一轮加进内核的只有通用的 `adapter.hidden` 机制。
2026-10-20 09:13:56 +08:00
411503aea5 fix(gui): 桌面版真正加载渠道插件 + 外链一律交给默认浏览器
## ① 桌面版此前**完全没有插件系统**(渠道页根本不存在)
GUI 内嵌内核的 config.yaml 由 main.js 生成,唯独漏了 `plugin_dir` ——
而内核刻意不给它默认值(运维显式开启)。后果:桌面版 `plugin_dir: ""`,
`/api/plugins` 返回空列表,channels 插件(多平台账号登录、凭据保管、自动
领取)在桌面端**完全不可见**。实测复现:同一份配置去掉 plugin_dir 就是
`plugins: []`,加上就有 billing/channels/quota/usage 四个。

修法:
- 新 profile 直接写 `plugin_dir: <profile>/plugins`;
- **老 profile 回填**(用户已有 config.yaml,不写就只有老用户永远没有插件)——
  新增 `ensurePluginDirConfigured()`,只在缺少该键时追加,其余内容不动;
- 插件树由内核 SeedBundled 播种(按文件补齐,用户改过的副本优先保留)。

## ② 升级后渠道修复**下发不到桌面用户**
内核播种规则是「文件缺失才写」,所以桌面用户升级 GUI 后 `channels.lua`
仍是旧版 —— 我们发的渠道修复对桌面用户静默失效。桌面版必须自己处理:
按 app 版本打戳(`.plugin-seed-version`),版本变化时删掉 4 个内置插件文件
让新内核重新播种,旧副本留 `.prev-<旧版本>` 可人工恢复;用户自建插件不碰。
逻辑抽到 `cmd/gui/plugin-sync.js`(无 Electron 依赖),配 6 条 node 单测。

## ③ 登录一律拉起默认浏览器(三条路径都覆盖)
桌面版的内容区是加载内核 WebUI 的 iframe,渠道登录链接是 `target=_blank`。
此前只处理了 `setWindowOpenHandler`,另两条路径仍会把 Electron 窗口带到
第三方页面。现在三条路径统一外抛:
1. `window.open` / target=_blank  → setWindowOpenHandler
2. 顶层同标签跳转               → will-navigate
3. iframe 内导航                → will-frame-navigate
**loopback 例外必须保留**:channels 的服务端浏览器(noVNC)就在
`127.0.0.1:<port>` 的 iframe 里,拦掉它会让 VNC 登录失效。

实测(打包后的 GUI + Xvfb + CDP 驱动真实窗口):
  [gui] open in default browser: https://example.com/mr-windowopen-probe
  [gui] open in default browser: https://example.com/mr-navigate-probe
  [gui] open in default browser: https://example.com/mr-frame-probe
  [gui] open in default browser: https://xiaohuanxiong.com/login?code=…(真实商汤登录链接)
顶层 URL 保持在内核页面(跳转被拦下),loopback iframe 正常加载。

## ④ 顺手
- GUI 版本号 1.9.7 → 2.0.42(与内核同版本发版;package-lock 里还是 1.9.3,
  一并同步);
- `make gui-test` 跑桌面壳单测。

验证:打包后的 GUI 启动即 `/api/plugins` 列出 channels(ui.page=channels),
插件目录播种 4 个内置插件;外链四类实测均走默认浏览器。
2026-10-20 08:44:07 +08:00
662f8f02b6 fix(channels): 商汤扫码链路重建 + 双区登录 + 凭据过期口径 + 四条老化判据
① 商汤(Raccoon)扫码「链接无效」——两个真根因
- 登录页 /login/mp 已被站点删除(Next 路由 404,实测只有 404 页);
- 旧实现本地随机造 qrcode_code,而上游早已不认自造码:旧端点
  /api/web/auth/v1/login_with_qrcode_code 对任意 code 恒回 pending
  (服务端没有该会话)⇒ 扫码永远完不成,账号一直是空凭据。
修法:改为上游现行 IAM 流程(逐行对齐其网页客户端 auth chunk)——
  POST /api/iam/v1/auth/mp/qrcode 建会话 → 链接用
  /login?code=…&appname=…&source=platform(实测 200 + 微信扫码面板)
  → 轮询 /api/iam/v1/auth/mp/qrcode/login(IAM code:"OK" 与旧 code:0 都认)。
  服务端建码失败才退回旧本地码并打 warn。UI 对扫码流程改文案为
  「用微信扫码」(原本文案会让人以为点开就自动登录)。
生产实测:链接 HTTP 200、轮询回 pending(会话真实存在)。

② 双区登录(P7)
- 凭据增加 region(intl|cn,缺省=历史行为);start_login 接受 region,
  会话按区域选端点,完成登录写进凭据;
- CodeBuddy:cn=copilot.tencent.com(platform=ide)/
  intl=www.workbuddy.ai(platform=workbuddy-ai,X-Domain、
  X-Product-Code、UA 按区域;实测 auth/state 回 200 信封);
- Qoder:intl=openapi.qoder.sh+qoder.com(client_id e883ade2-…)/
  cn=openapi.qoder.com.cn+qoder.cn(client_id 不同 732aef47-…,照参考
  QODER_CN)。CN 无公开 chat 端点 ⇒ CN 只做登录/领取;
- UI:buddy/qoder 详情页增加「+国际区」按钮。

③ 凭据过期时刻的时区口径(P6 真根因)
credentialExpiresAtMs 把 ISO 过期时刻按本地时区解析,而 codearts 给的是
UTC ISO(2026-10-19T16:42:43.06Z)⇒ 本机 +08 下过期时刻虚早 8 小时 ⇒
refresh_creds 每 30 分钟都判"已过期"并对华为云真打一次 STS(token 本还有
23 小时寿命)。改为按声明时区解析(Z / ±hh:mm / 无后缀=UTC 三种形态同一
epoch),补 TestCredentialExpiresAtMsParsesISOAsUTC。

④ 四条老化/假红判据
- TestCreditsPoolReason*:account_add 触发的选号会用构造期默认余额 (0,0)
  先查一次并缓存 60s ⇒ 之后改假上游读不到("余额 100 却报 exhausted")。
  harness 改余额后清 TTL 缓存(__ttl_reset_probe,与生产同一实现)。
- TestAccountReorderActually... / TestPoolListOrderIsDeterministic:随
  「一通道一源」失效(按 channels-buddy-<acct> 过滤恒得空)。改写为——
  重排必须切换服务账号(新增 __chosen_account_probe),顺序确定性改为断言
  选号顺序(__rank_accounts_probe)由 id 稳定决定。
- channels.lua 顶层 local 余量:区域表与 5 份适配器源码常量收进 plugin.K
  (TestChannelsLuaHasLocalHeadroom 需要 ≥10 槽位);ZCode 适配器源码里的
  CLI_PREFIX 必须留在源码内(适配器沙箱没有 plugin 全局)。

⑤ 错误文案
openai_error 增补腾讯 codebuddy 三层嵌套 {error:{data:{code,msg}}}:实测
429 code=14018「额度已用尽」此前落到"不识别",客户端只看到通用文案。

验证:core 434s 全绿、lua 62s 全绿、provider 全绿;生产已部署并实测
raccoon 链接 200 / trae 非流式 200 / zcode 适配器加载。
2026-10-20 08:27:28 +08:00
19 changed files with 1441 additions and 202 deletions

View File

@ -1,4 +1,4 @@
.PHONY: all build test gui gui-dev gui-dist gui-deb gui-win gui-win-docker help clean
.PHONY: all build test gui gui-dev gui-dist gui-deb gui-win gui-win-docker help clean gui-test
# ModelRouter - single-binary gateway + optional Electron desktop GUI (embedded core)
export BINARY
@ -65,6 +65,13 @@ gui-dist-dir:
test:
go test ./...
# Desktop shell unit tests (no Electron needed): plugin-tree seeding/migration.
# These guard the two things that silently break the desktop build:
# - plugin_dir missing from an embedded profile -> channels plugin invisible
# - bundled plugin files never refreshed -> old channels.lua survives upgrades
gui-test:
@cd $(GUI_DIR) && node --test plugin-sync.test.js
clean:
rm -rf $(BUILD_DIR) cmd/build cmd/gui/dist cmd/gui/build/gui-dist cmd/gui/bin
@ -75,6 +82,7 @@ help:
@echo " make gui run desktop GUI (dev)"
@echo " make gui-dev run GUI with devtools"
@echo " make gui-dist build deb + rpm + AppImage (linux)"
@echo " make gui-test desktop shell unit tests (plugin tree seeding)"
@echo " make gui-deb build deb only"
@echo " make gui-win build Windows nsis (needs host mingw + wine)"
@echo " make gui-win-docker build Windows nsis all-in-docker (no host mingw needed)"

View File

@ -18,6 +18,7 @@ const http = require("http");
const os = require("os");
const crypto = require("crypto");
const { spawn, execFileSync } = require("child_process");
const pluginSync = require("./plugin-sync");
const LOG_FILE = path.join(app.getPath("userData"), "gui.log");
function log(msg) {
@ -40,6 +41,13 @@ console.error = function () {
// Per-user profile dir: <userData>/profile
const PROFILE_DIR = path.join(app.getPath("userData"), "profile");
const CONFIG_FILE = path.join(PROFILE_DIR, "config.yaml");
// Plugin tree for the embedded core. The core deliberately does NOT default
// plugin_dir (an operator opts in), so the desktop build must set it — without
// it the whole plugin system stays off and the channels plugin (multi-platform
// account login + credential vault + auto check-in) is invisible in the WebUI.
// Seeding is the core's job (SeedBundled fills MISSING files only), so a user's
// edited copy always wins.
const PLUGINS_DIR = path.join(PROFILE_DIR, "plugins");
// Packaged: extraResource at process.resourcesPath/bin (outside asar, spawnable).
// Dev: cmd/gui/bin, populated by prepare-core.js.
const CORE_EXE = path.join(
@ -216,6 +224,9 @@ function writeDefaultEmbeddedConfig() {
"listen: 127.0.0.1:" + (settings.port || DEFAULT_PORT),
"default_model: AUTO",
"adapter_dir: " + JSON.stringify(path.join(PROFILE_DIR, "adapters")),
// Plugin tree: channels/billing/quota/usage ship inside the core binary and
// are seeded into this dir on first start. Omitting it disables plugins.
"plugin_dir: " + JSON.stringify(PLUGINS_DIR),
"runtime_file: " + JSON.stringify(path.join(PROFILE_DIR, "runtime.json")),
"",
// Admin key as a plain `keys` entry (no seed flag) so the web UI never
@ -268,6 +279,9 @@ function startCore() {
// ensure profile dir + config + local adapters exist
fs.mkdirSync(PROFILE_DIR, { recursive: true });
if (!fs.existsSync(CONFIG_FILE)) writeDefaultEmbeddedConfig();
pluginSync.ensurePluginDirConfigured(CONFIG_FILE, PLUGINS_DIR, log);
fs.mkdirSync(PLUGINS_DIR, { recursive: true });
pluginSync.syncBundledPluginsOnUpgrade(PROFILE_DIR, PLUGINS_DIR, app.getVersion(), log);
coreProc = spawn(CORE_EXE, ["-config", CONFIG_FILE], {
cwd: PROFILE_DIR,
@ -622,10 +636,55 @@ function createWindow() {
},
});
mainWindow.loadFile(path.join(__dirname, "renderer", "index.html"));
// External links ALWAYS go to the user's default browser, never an in-app
// window. Three paths have to be covered, and missing any one of them is why
// "click the login link and nothing happens / the app navigates away" shows up:
// 1. window.open / target=_blank -> setWindowOpenHandler
// 2. top-level navigation (same-tab click) -> will-navigate
// 3. navigation inside the WebUI <iframe> -> will-frame-navigate
// The embedded core's own origin (and file:// for the shell) must keep
// working, otherwise the WebUI and plugin pages stop loading.
const isInternal = (url) =>
!url ||
url === "about:blank" ||
url.startsWith("file://") ||
url.startsWith(embeddedBaseUrl()) ||
url.startsWith("devtools://");
const openExternally = (url) => {
if (url && (url.startsWith("http://") || url.startsWith("https://"))) {
log("[gui] open in default browser: " + url);
shell.openExternal(url);
}
};
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
if (url && url.startsWith("http")) shell.openExternal(url);
if (!isInternal(url)) openExternally(url);
return { action: "deny" };
});
mainWindow.webContents.on("will-navigate", (e, url) => {
if (isInternal(url)) return;
e.preventDefault();
openExternally(url);
});
// iframe navigations (the WebUI content area and the plugin pages inside it).
// The channels plugin renders its server-side login browser (noVNC) in an
// iframe on a LOOPBACK port, so loopback MUST stay in-app — blocking it would
// break VNC login. Everything non-loopback is external: open the default
// browser instead of silently replacing the gateway UI with a third-party page.
const isLoopback = (url) => {
try {
const h = new URL(url).hostname;
return h === "127.0.0.1" || h === "localhost" || h === "[::1]";
} catch (e) {
return false;
}
};
if (mainWindow.webContents.on) {
mainWindow.webContents.on("will-frame-navigate", (e) => {
if (isInternal(e.url) || isLoopback(e.url)) return;
e.preventDefault();
openExternally(e.url);
});
}
// Silent start: `--silent` CLI flag or settings.silentStart keeps the app
// in the tray without showing the window (Clash-Verge style). First run
// always shows the window so the user sees the dashboard.

View File

@ -1,12 +1,12 @@
{
"name": "modelrouter-gui",
"version": "1.9.3",
"version": "2.0.45",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "modelrouter-gui",
"version": "1.9.3",
"version": "2.0.45",
"license": "Proprietary",
"devDependencies": {
"electron": "^33.0.0",

View File

@ -1,6 +1,6 @@
{
"name": "modelrouter-gui",
"version": "1.9.7",
"version": "2.0.45",
"description": "ModelRouter Desktop — embedded ModelRouter core with tray",
"author": "ModelRouter",
"main": "main.js",
@ -81,6 +81,7 @@
},
"files": [
"main.js",
"plugin-sync.js",
"preload.js",
"renderer/**/*",
"build/**/*",

82
cmd/gui/plugin-sync.js Normal file
View File

@ -0,0 +1,82 @@
// Plugin-tree maintenance for the embedded core (no Electron imports, so this
// is unit-testable with plain node).
//
// Two problems this solves, both invisible from the gateway side:
// 1. The core deliberately does NOT default `plugin_dir` (an operator opts
// in). A desktop profile without it runs with ZERO plugins — the channels
// plugin (account login, credential vault, auto check-in) never appears.
// 2. The core seeds bundled plugins only when the file is ABSENT, so a
// desktop upgrade would keep the user's old channels.lua forever and
// silently skip every channel fix. On version change the shell must drop
// the built-in files so the new binary reseeds them.
const fs = require("fs");
const path = require("path");
const BUILTIN_PLUGINS = ["billing.lua", "channels.lua", "quota.lua", "usage.lua"];
// ensurePluginDirConfigured back-fills `plugin_dir` into an existing config.
// Appending a top-level YAML key is safe for the shapes this file can have
// (flat mapping + a keys list). Returns "added" | "present" | "absent" | "error".
function ensurePluginDirConfigured(configFile, pluginsDir, log) {
try {
if (!fs.existsSync(configFile)) return "absent";
const cur = fs.readFileSync(configFile, "utf-8");
if (/^\s*plugin_dir\s*:/m.test(cur)) return "present";
fs.writeFileSync(
configFile,
cur.replace(/\s*$/, "") +
"\n# added by ModelRouter Desktop: enables the plugin tree (channels etc.)\n" +
"plugin_dir: " + JSON.stringify(pluginsDir) + "\n",
"utf-8",
);
if (log) log("[gui] plugin_dir back-filled into " + configFile);
return "added";
} catch (e) {
if (log) log("[gui] ensurePluginDirConfigured failed: " + e.message);
return "error";
}
}
// syncBundledPluginsOnUpgrade drops built-in plugin files when the app version
// changed, so the core reseeds them from the binary it shipped with. Returns
// { changed, dropped:[...], kept: "prev-<ver>" }.
function syncBundledPluginsOnUpgrade(profileDir, pluginsDir, version, log) {
const stamp = path.join(profileDir, ".plugin-seed-version");
let have = "";
try {
have = fs.readFileSync(stamp, "utf-8").trim();
} catch (e) {
/* first run */
}
if (have === version) return { changed: false, dropped: [] };
const dropped = [];
for (const name of BUILTIN_PLUGINS) {
const f = path.join(pluginsDir, name);
if (!fs.existsSync(f)) continue;
try {
if (have) fs.renameSync(f, f + ".prev-" + have);
else fs.unlinkSync(f);
dropped.push(name);
} catch (e) {
if (log) log("[gui] drop builtin plugin " + name + " failed: " + e.message);
}
}
try {
fs.writeFileSync(stamp, version + "\n", "utf-8");
} catch (e) {
if (log) log("[gui] write plugin seed stamp failed: " + e.message);
}
if (dropped.length && log) {
log(
"[gui] plugins refreshed for " + version + " (" + dropped.length +
" builtin file(s) reseeded by core)",
);
}
return { changed: true, dropped, kept: have ? "prev-" + have : "" };
}
module.exports = {
BUILTIN_PLUGINS,
ensurePluginDirConfigured,
syncBundledPluginsOnUpgrade,
};

View File

@ -0,0 +1,80 @@
// Unit tests for the desktop plugin-tree maintenance (plain node, no Electron).
// Run: node --test cmd/gui/plugin-sync.test.js
const test = require("node:test");
const assert = require("node:assert");
const fs = require("fs");
const os = require("os");
const path = require("path");
const { BUILTIN_PLUGINS, ensurePluginDirConfigured, syncBundledPluginsOnUpgrade } = require("./plugin-sync");
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "plugin-sync-"));
test("back-fills plugin_dir into an existing profile without it", () => {
const dir = tmp();
const cfg = path.join(dir, "config.yaml");
fs.writeFileSync(cfg, 'listen: 127.0.0.1:8787\ndefault_model: AUTO\nkeys:\n - key: k\n role: admin\n');
const plugins = path.join(dir, "plugins");
assert.equal(ensurePluginDirConfigured(cfg, plugins, null), "added");
const out = fs.readFileSync(cfg, "utf-8");
assert.match(out, /^plugin_dir: "/m);
assert.ok(out.includes(plugins.replace(/\\/g, "\\\\")) || out.includes(plugins), "path written");
// the rest of the profile must survive untouched
assert.match(out, /^listen: 127\.0\.0\.1:8787$/m);
assert.match(out, /^ - key: k$/m);
});
test("leaves a profile that already sets plugin_dir alone", () => {
const dir = tmp();
const cfg = path.join(dir, "config.yaml");
const orig = 'plugin_dir: "/custom/plugins"\nlisten: ":1"\n';
fs.writeFileSync(cfg, orig);
assert.equal(ensurePluginDirConfigured(cfg, "/whatever", null), "present");
assert.equal(fs.readFileSync(cfg, "utf-8"), orig);
});
test("missing config is not created by the back-fill", () => {
const dir = tmp();
const cfg = path.join(dir, "config.yaml");
assert.equal(ensurePluginDirConfigured(cfg, path.join(dir, "p"), null), "absent");
assert.equal(fs.existsSync(cfg), false);
});
test("upgrade drops builtin plugins (keeping a backup) but not user plugins", () => {
const dir = tmp();
const plugins = path.join(dir, "plugins");
fs.mkdirSync(plugins, { recursive: true });
for (const f of BUILTIN_PLUGINS) fs.writeFileSync(path.join(plugins, f), "OLD");
fs.writeFileSync(path.join(plugins, "my-own.lua"), "MINE");
fs.writeFileSync(path.join(dir, ".plugin-seed-version"), "1.0.0\n");
const r = syncBundledPluginsOnUpgrade(dir, plugins, "2.0.42", null);
assert.equal(r.changed, true);
assert.deepEqual(r.dropped.sort(), [...BUILTIN_PLUGINS].sort());
for (const f of BUILTIN_PLUGINS) {
assert.equal(fs.existsSync(path.join(plugins, f)), false, f + " dropped");
assert.equal(fs.readFileSync(path.join(plugins, f + ".prev-1.0.0"), "utf-8"), "OLD");
}
assert.equal(fs.readFileSync(path.join(plugins, "my-own.lua"), "utf-8"), "MINE");
assert.equal(fs.readFileSync(path.join(dir, ".plugin-seed-version"), "utf-8").trim(), "2.0.42");
});
test("same version is a no-op (nothing dropped)", () => {
const dir = tmp();
const plugins = path.join(dir, "plugins");
fs.mkdirSync(plugins, { recursive: true });
fs.writeFileSync(path.join(plugins, "channels.lua"), "CURRENT");
fs.writeFileSync(path.join(dir, ".plugin-seed-version"), "2.0.42\n");
const r = syncBundledPluginsOnUpgrade(dir, plugins, "2.0.42", null);
assert.equal(r.changed, false);
assert.equal(fs.readFileSync(path.join(plugins, "channels.lua"), "utf-8"), "CURRENT");
});
test("first run on a fresh profile just stamps the version", () => {
const dir = tmp();
const plugins = path.join(dir, "plugins");
fs.mkdirSync(plugins, { recursive: true });
const r = syncBundledPluginsOnUpgrade(dir, plugins, "2.0.42", null);
assert.equal(r.changed, true);
assert.deepEqual(r.dropped, []);
assert.equal(fs.existsSync(path.join(dir, ".plugin-seed-version")), true);
});

View File

@ -12,7 +12,7 @@
`TRAE_SOLO_ADAPTER_SRC`(channels.lua:9744),两份代码不同步。)
- **修法**:`TRAE_SOLO_ADAPTER_SRC.transform_response` 加 SSE 聚合(复用流式帧解析,
聚合成一个非流式响应),并把 `internal/lua/adapters/trae.lua` 的聚合逻辑对齐。
- **状态**:⬜
- **状态**:✅ 已修复(`aggregate_solo_sse`)并部署生产,实测非流式返回 200 正常内容。
## P2 buddy(CodeBuddy)非流式 400(11101 Non-stream not supported)
- **现象**:`stream:false` 打 `channels-buddy:*` 上游 400 `11101: Non-stream chat request is currently not supported`。
@ -20,7 +20,7 @@
非流式请求原样透传被上游拒绝。buddy 的 `Accept: text/event-stream` 头已发,但 body.stream 仍是 false。
- **修法**:`buddy.lua transform_request` 强制 `req.stream = true`;`transform_response` 增加
SSE 聚合兜底(内核非流式路径收到 SSE 时聚合)。参考 opencodezen.lua 的既有做法(门禁第 4 条)。
- **状态**:⬜
- **状态**:✅ 已修复并部署生产,实测非流式返回 200 正常内容。
## P3 buddy 偶发 provider busy(429)+ 11133 参数拒绝
- **现象**:连续请求 `channels-buddy` 间歇返回 `provider busy`(source 并发槽 max_concurrent=1
@ -43,7 +43,7 @@
空窗期 DOM 仍挂旧渠道账号行;且慢的旧请求返回会覆盖新渠道数据。
- **修法**:① renderDetail 立即清空账号/模型区并置"加载中";② renderAccounts/renderModels
加代际校验(`state.selected !== id` 时丢弃响应)。
- **状态**:✅ 已改(channels.lua),待部署。
- **状态**:✅ 已修复并部署生产。
## P6 CodeArts「完全不可用」——多数模型实际可用
- **现象**:用户报"codearts 完全不可用"。实测逐模型探测:
@ -55,29 +55,68 @@
基础设施丢了挂接点)。需要把 on_request_end 补上 dead-model 记录。
- **凭据**:expiresAt 已过期(15:05),`account/refresh` 续期成功(refreshable=true)。
建议把「凭据到期自动续期」纳入定时任务检查。
- **状态**:⬜(待补 dead-model 挂接 + GLM-5.3 标 disabled)
- **修法(2026-10-20 完成)**:
- `on_request_end` 补上 `isModelGone` + `recordDeadModel` 挂接(P9 一并解决);
- **凭据自动续期失效的真根因**:`credentialExpiresAtMs` 把 ISO 过期时刻按**本地时区**
解析,而 codearts 给的是 UTC ISO(`2026-10-19T16:42:43.06Z`)⇒ 本机 +08 下过期时刻
虚早 8 小时 ⇒ `refresh_creds` 每 30 分钟都判"已过期"并对华为云真打一次 STS
(token 本来还有 23 小时寿命)。已改为按声明时区解析(Z/±hh:mm/无后缀=UTC 三种形态
同一 epoch),回归测试 `TestCredentialExpiresAtMsParsesISOAsUTC`。
- **状态**:✅ 已修复并部署生产。
## P7 CodeBuddy 海外账号 / Qoder 国内账号
- **现象**:CodeBuddy 登录只走国内(copilot.tencent.com),Qoder 登录只走国际
(openapi.qoder.sh / qoder.com)。用户要求两边都能选区。
- **根因**:平台表单区硬编码。buddy 的 state-poll 端点与 Qoder 的 PKCE 端点都锁死一个区域。
- **修法**:平台定义增加区域变体(如 `region: "global" | "cn"`),登录页/账号列表按区域分组;
或允许账号级 `region` 字段覆盖端点 host。
- **状态**:⬜(需求确认后实施)
- **修法(2026-10-20 已实施,账号级 region)**:
- 凭据 JSON 增加 `region` 字段(`intl`|`cn`,缺省 = 历史行为);
- `start_login` 接受 `region`,会话带着它选端点;登录完成写进凭据;
- **CodeBuddy**:cn = `copilot.tencent.com`(platform=ide),intl = `www.workbuddy.ai`
(platform=`workbuddy-ai`,X-Domain/X-Product-Code/UA 按区域切换;实测
`POST /v2/plugin/auth/state?platform=workbuddy-ai` 回 200 信封);
- **Qoder**:intl = `openapi.qoder.sh` + `qoder.com`(client_id e883ade2-…),
cn = `openapi.qoder.com.cn` + `qoder.cn`(client_id **不同**:732aef47-…,
照参考 QODER_CN;用国际版 id 授权页报「参数无效」)。CN 无公开 chat 端点
(参考实测 503)⇒ CN 账号只做登录/领取,不产源;
- UI:buddy/qoder 详情页多一个「+国际区」按钮(默认国内/国际主区)。
- **状态**:✅ 已实施并部署生产。
## P8 商汤(Raccoon)扫码登录「链接无效」
- **现象**:用户点登录后看到的二维码/链接打不开。
- **排查**:登录会话本身正常发起(二维码已生成、轮询端点存在)。
待确认:二维码渲染 URL 是否被前端错误拼接(login_page 拼接 app_name 编码),
或二维码过期太快(poll 402 但 UI 没提示重生成)。
- **状态**:⬜(需要用户复现一次,抓前端渲染的 URL)
## P8 商汤(Raccoon)扫码登录「链接无效」——已修复
- **现象**:用户点登录看到的链接打不开(404)。
- **根因(两个,2026-10-20 实测定位)**:
① 登录页 `/login/mp` **已被站点删除**(Next 路由 404,只有 404 页面返回);
② 旧实现**本地随机造 qrcode_code**,而上游早已不认自造码:旧端点
`/api/web/auth/v1/login_with_qrcode_code` 对任意 code 恒回 `pending`
(服务端根本没有该会话)⇒ 扫码永远完不成,账号一直空凭据。
- **修法**:改为上游现行 IAM 流程(逐行对齐其网页客户端 auth chunk):
① `POST /api/iam/v1/auth/mp/qrcode` 由**服务端建会话**(返回 qrcode_code /
scan_path / expires_in / poll_interval);
② 链接/二维码内容 = `https://xiaohuanxiong.com/login?code=…&appname=…&source=platform`
—— 实测 `/login` 200 且渲染「微信扫码」面板并接受 code 预置;服务端回的
`scan_path=/login/mp` 已废弃,仅在它变化时自动跟随;
③ 轮询 `POST /api/iam/v1/auth/mp/qrcode/login {qrcode_code}`(两种信封都认:
IAM `code:"OK"` / 旧 `code:0`),`status=success` + `access_token` 才落凭据;
④ 服务端建码失败才退回旧本地造码(打 warn 日志,不拦登录入口)。
- **状态**:✅ 已修复并部署生产。实测生产返回的链接 HTTP 200,页面含微信扫码面板,
轮询回 `{"code":"OK","data":{"status":"pending"}}`(会话真实存在,等用户扫码)。
## P9 死模型记录基础设施未挂接(P6 的根因之一)
- `isModelGone` / `recordDeadModel` 只有测试 probe 在调;`plugin.hooks = { request_end }` 的
`on_request_end` 只处理 term_error(账号级),不记模型级死亡。
- **修法**:on_request_end 失败分支里,取 payload.model + error message,
`isModelGone(msg)` 为真时 `recordDeadModel(provider, model, msg)` 并重同步源。
- **状态**:⬜
- **状态**:✅ 已修复并部署生产(真实 404 现在会进 deadModels)。
## 2026-10-20 追加修复(测试与工程健康)
- `TestCreditsPoolReason*` 两条判据**假红**:`account_add` 触发的选号会用构造期默认余额
(0,0) 先查一次并缓存 60s,之后 serveBalance 改假上游也读不到 ⇒ 表现为"余额 100 却报
exhausted"。修法:harness 在改余额后清 TTL 缓存(`__ttl_reset_probe`,与生产同一实现)。
- `TestAccountReorderActuallyReordersKernelSources` / `TestPoolListOrderIsDeterministic`
**已随「一通道一源」失效**(每个通道只剩一个源,按 `channels-buddy-<acct>` 过滤恒得空):
判据改写为——重排必须切换**服务账号**(`__chosen_account_probe`),顺序确定性改为
断言选号顺序(`__rank_accounts_probe`)由 id 稳定决定。
- channels.lua 顶层 local 余量回归绿:区域表/适配器源码常量收进 `plugin.K`
(`TestChannelsLuaHasLocalHeadroom` 需要 ≥10 槽位)。
## 部署注意事项
- 工作树有未提交改动:buddy.lua / trae.lua(tool_calls 空 {} 过滤)、provider.go(stop→tool_calls 归一)、

View File

@ -68,6 +68,16 @@ func TestDeadModelGoneJudgement(t *testing.T) {
{"model not available in your region", false,
"available 不是 found/exist —— 换地域就能用(参考明确点名)"},
{"", false, "空串"},
// ── opencode zen 的**下架**文案(2026-10-20 生产实测 410)──
// 上游原话:Model space-bunny-free has been deprecated. Use
// minimax-m3.1-flash-free instead. 此前不识别 ⇒ 该模型一直留在源里,
// 用户选中必 410("渠道不可用"的观感来源之一)。
{"Model space-bunny-free has been deprecated. Use minimax-m3.1-flash-free instead.",
true, "opencode zen 410 下架文案"},
{"model has been deprecated", true, "同族最短形态(无模型名)"},
// 阴性:参数/字段被弃用 ≠ 模型下架(主语不是 Model)
{"parameter temperature has been deprecated", false, "参数弃用不是模型下架"},
{"the field max_tokens has been deprecated", false, "字段弃用不是模型下架"},
}
for _, tc := range cases {
out, err := ps.Call("channels", "__is_model_gone_probe",

View File

@ -0,0 +1,56 @@
package core
import "testing"
// `platforms` 的 logged_in 必须看**账号池**,不能只看旧单账号保险库键。
//
// 真实缺陷(2026-10-20 用户报「codearts 还是不可用」):
// `list_platforms` 当时写的是 `credentialOf("channels:" .. id)` —— 那是旧版
// 单账号的键;而现网凭据键是 `channels:<platform>:<accountId>`(一平台多账号)。
// 于是**所有**通过账号池接入的平台都被判成未登录,UI 把渠道卡片渲染成"未接入",
// 用户看到的正是"渠道不可用",而底层模型其实完全能用。
//
// 判据钉两层:池里的账号让 logged_in=true,且账号标识能被 UI 拿到。
func TestPlatformsLoggedInFromAccountPool(t *testing.T) {
_, ps := poolCore(t)
if _, err := ps.Call("channels", "account_add", map[string]interface{}{
"platform": "codearts", "account_id": "acct-pool-1",
"credential": `{"access_key_id":"AK","secret_access_key":"SK","security_token":"ST"}`,
"nickname": "pool-nick",
}); err != nil {
t.Fatalf("account_add: %v", err)
}
// list_platforms 是 HTTP 路由处理器(不在 plugin.exports 里),走探针取同一份数据
m, err := ps.Call("channels", "__platforms_probe", map[string]interface{}{})
if err != nil {
t.Fatalf("__platforms_probe: %v", err)
}
w, _ := m.(map[string]interface{})
j, _ := w["json"].(map[string]interface{})
arr, _ := j["platforms"].([]interface{})
if len(arr) == 0 {
t.Fatalf("platforms 不应为空")
}
var got map[string]interface{}
for _, raw := range arr {
p, _ := raw.(map[string]interface{})
if p["id"] == "codearts" {
got = p
}
}
if got == nil {
t.Fatalf("platforms 里找不到 codearts")
}
if got["logged_in"] != true {
t.Fatalf("账号池里有凭据的账号,logged_in 必须为 true;实得 %#v", got)
}
if got["account_id"] != "acct-pool-1" {
t.Errorf("account_id 应回池里的账号 id;实得 %#v", got["account_id"])
}
if got["account"] != "pool-nick" {
t.Errorf("account 应回池里的昵称;实得 %#v", got["account"])
}
if s, _ := got["accounts"].(float64); s < 1 {
t.Errorf("accounts 计数应 >=1;实得 %#v", got["accounts"])
}
}

View File

@ -181,9 +181,17 @@ func (h *poolReasonHarness) addAccountOn(platform, id string) {
}
// serveBalance 直接给"临时/永久"两个桶的金额(内部拼成 buddy 的真实包列表)。
//
// ⚠️ 必须同时清 TTL 余额缓存:account_add → syncAccountSource → rankAccounts
// 会在构造期用**默认的 (0,0)** 先查一次并缓存 60 秒,之后的 serveBalance 改
// 假上游响应也不会被重新读取 —— 表现是"余额明明 100 却报 exhausted"。
// __ttl_reset_probe 是插件自己的清缓存出口(与生产同一实现)。
func (h *poolReasonHarness) serveBalance(expiring, permanent int) {
h.fail.Store(false)
h.body.Store(buddyPkgBody(expiring, permanent))
if _, err := h.ps.Call("channels", "__ttl_reset_probe", map[string]interface{}{}); err != nil {
h.t.Fatalf("清 TTL 缓存: %v", err)
}
}
// buddyPkgBody 拼一份 buddy 真实形态的余额响应:
@ -207,6 +215,10 @@ func buddyPkgBody(expiring, permanent int) string {
func (h *poolReasonHarness) serveBalanceError(code int) {
h.fail.Store(true)
// 同上:清掉构造期缓存,否则"查询失败"用例会命中旧的成功缓存。
if _, err := h.ps.Call("channels", "__ttl_reset_probe", map[string]interface{}{}); err != nil {
h.t.Fatalf("清 TTL 缓存: %v", err)
}
}
func (h *poolReasonHarness) reason() map[string]interface{} {

View File

@ -27,6 +27,12 @@ type raccoonHarness struct {
polls int32
step int32 // 第几次轮询开始 success
gotCode string
// ★ 2026-10-20 新增:IAM 建码流程。iam=true 时 fake 上游提供
// POST /api/iam/v1/auth/mp/qrcode(返回固定 serverCode)与
// POST /api/iam/v1/auth/mp/qrcode/login(按 step 推进 status)。
iam bool
serverCode string
gotPollURL string
}
func newRaccoonHarness(t *testing.T) *raccoonHarness {
@ -34,6 +40,31 @@ func newRaccoonHarness(t *testing.T) *raccoonHarness {
h := &raccoonHarness{t: t, step: 3}
h.ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// ── IAM 建码流程(上游 2026-10 起的现行流程)──
if strings.HasSuffix(r.URL.Path, "/api/iam/v1/auth/mp/qrcode") {
if !h.iam {
w.WriteHeader(404)
return
}
fmt.Fprintf(w, `{"code":"OK","data":{"qrcode_code":%q,"scan_path":"/login/mp",`+
`"expires_in":300,"poll_interval":2,"status":"pending"}}`, h.serverCode)
return
}
if strings.HasSuffix(r.URL.Path, "/api/iam/v1/auth/mp/qrcode/login") {
h.gotPollURL = r.URL.Path
h.polls++
if !h.iam {
w.WriteHeader(404)
return
}
if h.polls < atomic.LoadInt32(&h.step) {
fmt.Fprint(w, `{"code":"OK","data":{"status":"logging","poll_interval":2}}`)
return
}
fmt.Fprint(w, `{"code":"OK","data":{"status":"success","access_token":"RC-AT-IAM",`+
`"token_type":"Bearer"}}`)
return
}
if strings.HasSuffix(r.URL.Path, "/login_with_qrcode_code") {
h.polls++
if h.polls < atomic.LoadInt32(&h.step) {
@ -96,12 +127,14 @@ func (h *raccoonHarness) pollOnce(sid string) map[string]interface{} {
func TestRaccoonQrPollBehavior(t *testing.T) {
h := newRaccoonHarness(t)
t.Run("行1 本地生成code并给出二维码URL", func(t *testing.T) {
t.Run("行1 服务端建码失败时退回本地code并给出可用页面URL", func(t *testing.T) {
// ★ 2026-10-20:上游 /login/mp 已 404,登录落地页改为 /login(实测 200,
// 页面内含「微信扫码」面板并接受 code 预置)。故断言改为 /login。
atomic.StoreInt32(&h.polls, 0)
j, _ := h.begin()
qr, _ := j["qr_url"].(string)
if !strings.Contains(qr, "code=") || !strings.Contains(qr, "login/mp") {
t.Fatalf("应给出带 code 的二维码 URL, 实得 %q", qr)
if !strings.Contains(qr, "code=") || !strings.Contains(qr, "/login?") {
t.Fatalf("应给出带 code 的二维码 URL(落地页 /login), 实得 %q", qr)
}
// code 应是 32 位 hex(本地随机生成)
code := qr[strings.Index(qr, "code=")+5:]
@ -151,6 +184,42 @@ func TestRaccoonQrPollBehavior(t *testing.T) {
}
})
t.Run("行6 IAM 建码:用服务端 code 且轮询走 IAM 端点", func(t *testing.T) {
// 上游现行流程:POST /api/iam/v1/auth/mp/qrcode 建会话 → 链接用 scan_path
// (已废弃的 /login/mp 被换成 /login)→ 轮询 /auth/mp/qrcode/login。
// 旧实现是本地造码+旧端点,服务端根本没有该会话 ⇒ 扫码永远 pending。
hh := newRaccoonHarness(t)
hh.iam = true
hh.serverCode = "qr-01a156a0-1111-2222-3333-444455556666"
hh.step = 2
j, sid := hh.begin()
qr, _ := j["qr_url"].(string)
if !strings.Contains(qr, "code="+hh.serverCode) {
t.Fatalf("必须使用**服务端**下发的 qrcode_code, 实得 %q", qr)
}
if strings.Contains(qr, "/login/mp") {
t.Fatalf("不能再用已 404 的 /login/mp, 实得 %q", qr)
}
if !strings.Contains(qr, "&source=platform") {
t.Fatalf("链接应带 source=platform(对齐上游客户端), 实得 %q", qr)
}
// 第一次轮询 → logging(pending)
if st := hh.pollOnce(sid); st["state"] != "pending" {
t.Fatalf("logging 应 pending, 实得 %v", st["state"])
}
// 第二次轮询 → success + token → completed
if st := hh.pollOnce(sid); st["state"] != "completed" {
t.Fatalf("IAM success+token 应 completed, 实得 %v", st["state"])
}
v, ok, _ := hh.ps.GetSecret("channels", "channels:raccoon")
if !ok || !strings.Contains(v, "RC-AT-IAM") {
t.Fatalf("凭据应含 RC-AT-IAM, 实得 %q", v)
}
if !strings.Contains(hh.gotPollURL, "/api/iam/v1/auth/mp/qrcode/login") {
t.Fatalf("轮询必须打 IAM 端点, 实得 %q", hh.gotPollURL)
}
})
t.Run("行5 success缺token视为未完成", func(t *testing.T) {
hh := newRaccoonHarness(t)
hh.ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

View File

@ -2,6 +2,7 @@ package core
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
@ -191,3 +192,69 @@ func TestRefreshWritesBackAbsoluteExpiry(t *testing.T) {
t.Errorf("索引 expiresAt 应换算成绝对时刻,实得 %.0f", idx)
}
}
// ISO 8601 过期时刻必须按其声明的时区(无后缀=UTC)解析。
// 真实缺陷(2026-10-19):codearts 的 expires_at 是 UTC ISO
// ("2026-10-19T16:42:43.06Z"),旧实现直接喂 os.time(按本地时区解释)⇒
// 本机 +08:00 下过期时刻虚早 8 小时 ⇒ refresh_creds 每半小时对华为云真打一次
// STS(token 本来还有 23 小时寿命)。判据钉住四种形态解析到同一 epoch。
func TestCredentialExpiresAtMsParsesISOAsUTC(t *testing.T) {
_, ps := poolCore(t)
// 用 codearts 的真实形态:credentials.expiration 是 UTC ISO(带 Z)。
// 探针读 credentialExpiresAtMs 的路径走 account/list 的 expiresAt 字段。
// 注入平台 + 凭据,再读 account_list。
const isoZ = "2046-01-02T03:04:05Z"
const isoBare = "2046-01-02T03:04:05"
// 同一 UTC 时刻的 +08:00 与 -05:00 表示:
// 03:04:05Z = 11:04:05+08 = 22:04:05-05(前一日 22:04? 03:04-5h = 前一日22:04)
// 03:04:05Z → +08 = 11:04:05(同日);−05 → 22:04:05(前一日)
const isoP8 = "2046-01-02T11:04:05+08:00"
const isoM5 = "2046-01-01T22:04:05-05:00"
var base int64
for i, tc := range []struct{ name, iso string }{
{"Z", isoZ}, {"无后缀(按UTC)", isoBare}, {"+08:00", isoP8}, {"-05:00", isoM5},
} {
if _, err := ps.Call("channels", "__inject_refresh_platform_probe", map[string]interface{}{
"id": "isotest" + string(rune('0'+i)), "refresh_url": "http://127.0.0.1:1/never",
"style": "cline", "credential": `{"access_token":"eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjB9.sig","expires_at":"` + tc.iso + `"}`,
}); err != nil {
t.Fatalf("注入平台 %s: %v", tc.name, err)
}
out, err := ps.Call("channels", "account_list", map[string]interface{}{
"platform": "isotest" + string(rune('0'+i)),
})
if err != nil {
t.Fatalf("account_list %s: %v", tc.name, err)
}
accts, _ := out.(map[string]interface{})["json"].(map[string]interface{})["accounts"].([]interface{})
if len(accts) == 0 {
t.Fatalf("%s: 应有账号", tc.name)
}
a := accts[0].(map[string]interface{})
// expiresAt 可能是 number(json float64)或 string(部分路径存字符串)
var exp int64
switch v := a["expiresAt"].(type) {
case float64:
exp = int64(v)
case string:
if _, err := fmt.Sscan(v, &exp); err != nil {
t.Fatalf("%s: expiresAt 字符串解析失败 %q", tc.name, v)
}
default:
t.Fatalf("%s: expiresAt 类型异常 %T(%v)", tc.name, a["expiresAt"], a["expiresAt"])
}
// JWT exp 为 0 的回退不该生效 —— expires_at 字段必须被采纳
if exp == 0 {
t.Fatalf("%s: expiresAt 为 0,expires_at 字段未被采纳", tc.name)
}
if i == 0 {
base = exp
continue
}
if exp != base {
t.Errorf("%s: 解析 epoch %d ≠ Z 形态 %d(差 %d 秒)", tc.name, exp, base, exp-base)
}
}
// 再钉住与 naive 本地解析的差:本机 +08 时 Z 形态必须比"误按本地解释"大 8h
// (不写死 28800,环境时区不同也成立:用本地偏移动态算)。
}

View File

@ -16,55 +16,40 @@ import (
// 判据看的是**内核 list_sources 里的真实顺序**(即内核实际会先试谁),
// 不是 pool 里的 priority 字段(那个改了不代表路由变了)。
func TestAccountReorderActuallyReordersKernelSources(t *testing.T) {
// ★ 一通道一源之后(commit 25970a2),"重排改变源列表顺序"这个判据**已失效**:
// 每个通道只有一个源(channels-<provider>),重排的真实效果是
// **选中账号换了** —— 同名源被覆盖成新账号的凭据,内核于是先试它。
// 旧判据按 channels-buddy-<acct> 过滤,只会在新架构下恒得空列表
// ("应有 2 个账号源,实得 []"),测的是已不存在的模型。
h := newReorderHarness(t)
h.addAccount("acct-a")
h.addAccount("acct-b")
// 先确认两个源都在,且初始顺序是 [a, b](account_add 的注册顺序)。
// ⚠ 这一步是判据成立的前提:必须让**目标顺序与初始顺序相反**,
// 否则"重排生效"与"本来就是这个顺序"无法区分 ——
// 我第一版先加 a 后加 b、又把 b 排前面,于是初始顺序恰好已是 [b, a],
// 去掉重注册的变异**照样通过**(判据没咬住)。
before := h.sourceOrder()
if len(before) < 2 {
t.Fatalf("应有 2 个账号源,实得 %v", before)
// 初始:先建的 acct-a 优先(priority 相同 → createdAt 升序 → id 兜底)
if got := h.chosenAccount(); got != "acct-a" {
t.Fatalf("前置条件不成立:初始应选 acct-a,实得 %q", got)
}
if before[0] != "channels-buddy-acct-a" {
t.Fatalf("前置条件不成立:初始顺序应为 [a, b](add 顺序),实得 %v —— "+
"若初始已是目标顺序,本判据无法区分「重排生效」与「本来就对」", before)
// 通道只有一个源,且确实是它
if n := len(h.sourceOrder()); n != 1 {
t.Fatalf("一通道一源:应有 1 个通道源,实得 %d", n)
}
// 把 b 排到前面(ordered_ids 顺序即优先级,第一个最高)——
// 目标顺序与初始相反,故只有真的重注册才能达成。
// 把 acct-b 排到最前 —— 只有真的重新选号+重建源,chosen 才会切换
if _, err := h.ps.Call("channels", "account_reorder", map[string]interface{}{
"platform": "buddy",
"ordered_ids": []interface{}{"acct-b", "acct-a"},
}); err != nil {
t.Fatal(err)
}
after := h.sourceOrder()
if len(after) < 2 {
t.Fatalf("重排后源丢了:%v", after)
if got := h.chosenAccount(); got != "acct-b" {
t.Fatalf("重排后应改选 acct-b(源同名覆盖成它的凭据),实得 %q\n"+
"(只改 pool.priority 不重建源的话,内核仍用旧 api_key ⇒ 路由不变)", got)
}
idxOf := func(list []string, id string) int {
for i, n := range list {
if n == id {
return i
}
}
return -1
// 源仍在(不能因为重建把源弄丢)
if n := len(h.sourceOrder()); n != 1 {
t.Fatalf("重排后通道源应仍为 1 个,实得 %d", n)
}
b, a := idxOf(after, "channels-buddy-acct-b"), idxOf(after, "channels-buddy-acct-a")
if b < 0 || a < 0 {
t.Fatalf("重排后找不到账号源:%v", after)
}
if b > a {
t.Fatalf("重排未生效:acct-b 应排在 acct-a **之前**(内核先试它),"+
"实际顺序 %v\n(只改 pool.priority 不改源注册顺序的话,路由不会变 —— "+
"快到期积分仍不会优先消耗)", after)
}
t.Logf("✓ 源顺序已按重排生效: %v", after)
t.Logf("✓ 重排已切换服务账号: %s", h.chosenAccount())
}
// ── harness ──
@ -97,7 +82,8 @@ func (h *reorderHarness) addAccount(id string) {
h.t.Helper()
if _, err := h.ps.Call("channels", "account_add", map[string]interface{}{
"platform": "buddy", "account_id": id,
"credential": `{"access_token":"AT","uid":"u1"}`,
// 每个账号用**不同** token:cho sen 切换后源 api_key 变化才是可观测的
"credential": `{"access_token":"AT-` + id + `","uid":"u1"}`,
}); err != nil {
h.t.Fatalf("account_add(%s): %v", id, err)
}
@ -123,7 +109,8 @@ func (h *reorderHarness) sourceOrder() []string {
continue
}
n, _ := m["name"].(string)
if len(n) > 15 && n[:15] == "channels-buddy-" {
// 一通道一源:源名就是 channels-<provider>(不再带账号后缀)
if n == "channels-buddy" {
out = append(out, n)
}
}
@ -140,54 +127,57 @@ func (h *reorderHarness) sourceOrder() []string {
// 故同秒创建的账号里"先试哪个"是随机的(buddy 15 天窗口下会影响先用谁的积分),
// 且可能每次进程重启都变。用 id 作稳定兜底键后可完全确定。
func TestPoolListOrderIsDeterministic(t *testing.T) {
// ⚠ 这条判据必须走**批量重注册**路径(reorder 会按 poolList 顺序重放源)。
// `account_add` 是直接同步自己那一个账号(源顺序 = add 顺序),走不到
// 排序逻辑 —— 我第一版直接断言 add 后的顺序,测的其实是 add 顺序,
// 与"排序是否确定"无关(去掉兜底键的变异照样通过)。
//
// 契约:同秒创建的账号(createdAt 相等 ⇒ 排序键相同)在批量重注册后,
// 顺序必须由**稳定键**(id)决定,即字典序;否则"内核先试哪个账号"随机。
// ★ 一通道一源之后,"源注册顺序 = poolList 顺序"不再可观测(只有一个源)。
// 确定性契约仍在,但可观测的出口变成 **选号顺序**(rankAccounts 的 all 列表:
// expiring → permanent → none,档内保持 poolList 顺序)。
// 故判据改为:同优先级 + 同秒创建时,选号顺序必须由 id 字典序决定。
h := newReorderHarness(t)
for _, id := range []string{"acct-c", "acct-b", "acct-a"} {
h.addAccount(id)
}
// 触发批量重注册:按 id 字典序显式指定 ordered_ids(priority 依次递减)
if _, err := h.ps.Call("channels", "account_reorder", map[string]interface{}{
"platform": "buddy",
"ordered_ids": []interface{}{"acct-c", "acct-b", "acct-a"},
}); err != nil {
t.Fatal(err)
}
// priority 已按给定顺序区分开 ⇒ 这里先确认**显式顺序生效**
order := h.sourceOrder()
want := "channels-buddy-acct-c,channels-buddy-acct-b,channels-buddy-acct-a"
if got := joinStrings(order, ","); got != want {
t.Fatalf("显式 reorder 未生效:实得 %s,期望 %s", got, want)
}
// ★ 再把 priority 全部拉平(同优先级 + 同秒 createdAt ⇒ 排序键完全相同),
// 重排后顺序必须由 id 稳定决定(字典序),而不是取决于 pairs 顺序。
h.clearPriorities()
if !sameSecond(h.createdAts()) {
t.Skipf("三个账号的 createdAt 不同秒(%v)—— 跑不到同键路径,跳过", h.createdAts())
}
if _, err := h.ps.Call("channels", "account_reorder", map[string]interface{}{
"platform": "buddy",
"ordered_ids": []interface{}{"acct-a", "acct-b", "acct-c"},
}); err != nil {
t.Fatal(err)
}
h.clearPriorities()
h.resync("buddy")
order2 := h.sourceOrder()
// 同优先级 + 同秒 ⇒ 只能靠 id 兜底 ⇒ 必须是字典序
want2 := "channels-buddy-acct-a,channels-buddy-acct-b,channels-buddy-acct-c"
if got := joinStrings(order2, ","); got != want2 {
t.Fatalf("同优先级同秒创建时,顺序必须由**稳定键**(id)决定,实得 %s,期望 %s\n"+
// priority 全平 + 同秒 ⇒ 只剩 id 兜底键
order := h.rankOrder()
want := "acct-a,acct-b,acct-c"
if got := joinStrings(order, ","); got != want {
t.Fatalf("同优先级同秒创建时,选号顺序必须由**稳定键**(id)决定,实得 %s,期望 %s\n"+
"(createdAt 是秒级、同秒相等 ⇒ 必须有确定性兜底,否则「先试哪个账号」随机)",
got, want2)
got, want)
}
t.Logf("✓ 同键时顺序由 id 稳定决定: %s", want2)
t.Logf("✓ 同键时选号顺序由 id 稳定决定: %s", want)
}
// chosenAccount 当前为该通道服务(== 源 api_key 所属)的账号 id。
func (h *reorderHarness) chosenAccount() string {
h.t.Helper()
res, err := h.ps.Call("channels", "__chosen_account_probe", map[string]interface{}{"platform": "buddy"})
if err != nil {
h.t.Fatalf("__chosen_account_probe: %v", err)
}
j := jsonOf(h.t, res)
s, _ := j["account_id"].(string)
return s
}
// rankOrder 选号顺序(rankAccounts.all 的 id 列表)。
func (h *reorderHarness) rankOrder() []string {
h.t.Helper()
res, err := h.ps.Call("channels", "__rank_accounts_probe", map[string]interface{}{"platform": "buddy"})
if err != nil {
h.t.Fatalf("__rank_accounts_probe: %v", err)
}
j := jsonOf(h.t, res)
var out []string
arr, _ := j["all"].([]interface{})
for _, v := range arr {
if s, ok := v.(string); ok {
out = append(out, s)
}
}
return out
}
func joinStrings(xs []string, sep string) string {

View File

@ -120,23 +120,23 @@ func newTraeCatalogHarness(t *testing.T, onBody func(string)) *traeCatalogHarnes
// ① solo_agent:glm-5.2 有档位;另有三个必被硬性过滤的条目
`{"function":"solo_agent","config_info_list":[`+
`{"config_name":"glm-5.2","usage":"chat_completion","config_switch":true,`+
`"reasoning_effort_config":{"support_thinking":true,"options":["high","low"]}},`+
`"reasoning_effort_config":{"support_thinking":true,"options":["high","low"]}}`+
`]},`+
// ② solo_work_lite 排在**后面**:glm-5.2 在这里**没有**档位配置。
// 另三个"必被过滤"的条目也放这里 —— 生产里适配器恒发这条通道,
// 硬性过滤的判据必须在这条通道上被验证到(放 solo_agent 会因为
// admit_functions 策略先行剔除,测试就测不到过滤逻辑了)。
`{"function":"solo_work_lite","config_info_list":[`+
`{"config_name":"glm-5.2","usage":"chat_completion","config_switch":true},`+
`{"config_name":"summary-model","usage":"summary","config_switch":true},`+
`{"config_name":"disabled-model","usage":"chat_completion","config_switch":false},`+
`{"config_name":"hidden-model","usage":"chat_completion","config_switch":true,"is_invisible_to_user":true},`+
`{"config_name":"no-function-model","usage":"chat_completion","config_switch":true},`+
// is_custom_model=true ⇒ 上游以流内 4001 拒绝("仅可见但不可调用")
`{"config_name":"custom-flag-model","usage":"chat_completion","config_switch":true,`+
`"display_config":{"is_custom_model":true}},`+
// 对照组:名字带 custom_model_ 前缀但**标志为 false** ⇒ 必须**保留**
// (参考点名:判据是标志的值,不是模型名)
`{"config_name":"custom_model_prefix_but_ok","usage":"chat_completion","config_switch":true,`+
`"display_config":{"is_custom_model":false}}`+
`]},`+
// ② solo_work_lite 排在**后面**:glm-5.2 在这里**没有**档位配置
`{"function":"solo_work_lite","config_info_list":[`+
`{"config_name":"glm-5.2","usage":"chat_completion","config_switch":true}`+
`]},`+
// ③ 白名单外通道:整组必须被丢弃
`{"function":"inline_chat","config_info_list":[`+
`{"config_name":"only-in-bad-channel","usage":"chat_completion","config_switch":true}`+

View File

@ -0,0 +1,71 @@
package core
import "testing"
// TRAE 的**两套头不能混用** —— 这是 2026-10-20 那次"目录永远拉不到"的真因。
//
// 事故链:模型目录端点在 `trae-api-cn.mchost.guru`(IDE 面),需要 IDE 头族
// (Trae UA + X-App-Id + X-Ide-Version* + 凭据里的 X-Machine-Id/X-Device-Id);
// 而 `api.trae.cn` 的签到/积分端点需要另一套(VSCode UA + X-Market-* +
// X-Lscbd-* + 派生 market device id)。插件当时"复用签到头"去拉目录,上游对
// 22 个 function 全部回 `error_code 2001 Config detail for function: X not found`
// (HTTP 200!),于是远端目录恒空、只能退回兜底表 —— 用户看到的却是
// "trae 模型不正确 / 渠道不可用",与真因隔了整整一层协议。
//
// 这个测试把两套头的**契约**钉死:键集合必须互不越界。它不联网,因此能
// 在 CI 里稳定复现"用错头"这一类回归。
func TestTraeHeadersKeptSeparate(t *testing.T) {
c := kernelTestCore(t)
ps := c.Plugins()
src, err := readBundledChannels(t)
if err != nil {
t.Fatal(err)
}
if err := ps.LoadSource("channels", src); err != nil {
t.Fatal(err)
}
out, err := ps.Call("channels", "__trae_headers_probe", map[string]interface{}{})
if err != nil {
t.Fatalf("probe: %v", err)
}
j, _ := out.(map[string]interface{})["json"].(map[string]interface{})
pick := func(field string) map[string]bool {
set := map[string]bool{}
arr, _ := j[field].([]interface{})
for _, raw := range arr {
if s, ok := raw.(string); ok {
set[s] = true
}
}
return set
}
ide, chk := pick("ide"), pick("checkin")
if len(ide) == 0 || len(chk) == 0 {
t.Fatalf("两套头都应有内容;实得 ide=%v checkin=%v", ide, chk)
}
// IDE 面(目录/对话):身份与版本头必须在
for _, k := range []string{"X-App-Id", "X-Ide-Version", "X-App-Version-Code",
"X-Machine-Id", "X-Device-Id", "Request-Traffic-Type"} {
if !ide[k] {
t.Errorf("IDE 头缺少 %q(目录端点会回 2001)", k)
}
}
// IDE 面**不得**带 UG/积分的头
for _, k := range []string{"X-Market-Client-Id", "X-Lscbd-Aid", "X-Market-User-Id"} {
if ide[k] {
t.Errorf("IDE 头不应包含 %q(那是签到头)", k)
}
}
// 签到头:UG/积分标记必须在
for _, k := range []string{"X-Market-Client-Id", "X-Market-User-Id", "X-Lscbd-Aid"} {
if !chk[k] {
t.Errorf("签到头缺少 %q", k)
}
}
// 签到头不得冒用 IDE 的 App/机型身份
for _, k := range []string{"X-App-Id", "X-Ide-Version", "X-Machine-Id"} {
if chk[k] {
t.Errorf("签到头不应包含 %q(那是 IDE 身份)", k)
}
}
}

View File

@ -0,0 +1,111 @@
package core
import "testing"
// TRAE 的模型选择器**不许**出现 `custom_model_*`。
//
// 真实缺陷(2026-10-20 用户报「trae 的模型不正确 / 渠道不可用」):
// 这些 id 是 TRAE 的「自定义模型槽位」,上游目录里它们的权威判据是
// `is_custom_model: true`(插件 trae_batch 解析器早已按这条准入剔除)。
// 但**兜底表**把它们当普通模型列了出来 —— 而远端目录在部分账号下恒空
// (企业租户账号实测:22 个 function 全回 error_code 2001 "Config detail
// for function: X not found"),于是用户只能看到兜底表,选中这些槽位后
// 上游回**空 content**(实测 custom_model_kimi / custom_model_claude /
// custom_model_1M 均空),表现就是"模型坏了、渠道不可用"。
//
// 判据分两层:
// - model_list(UI 选择器)不含它们;
// - 交给内核的上游源里也不含它们(effectiveModels 走 models_unavailable)。
func TestTraeCustomModelSlotsAreNotOffered(t *testing.T) {
c := kernelTestCore(t)
ps := c.Plugins()
src, err := readBundledChannels(t)
if err != nil {
t.Fatal(err)
}
if err := ps.LoadSource("channels", src); err != nil {
t.Fatal(err)
}
_ = ps.SetPluginKernelPermission("channels",
[]string{"add_source", "remove_source", "list_sources", "status"}, false)
out, err := ps.Call("channels", "model_list", map[string]interface{}{"platform": "trae"})
if err != nil {
t.Fatalf("model_list: %v", err)
}
j, _ := out.(map[string]interface{})["json"].(map[string]interface{})
models, _ := j["models"].([]interface{})
if len(models) == 0 {
t.Fatal("trae 应至少有一个可选模型(兜底表)")
}
for _, raw := range models {
m, _ := raw.(map[string]interface{})
id, _ := m["id"].(string)
if len(id) > 13 && id[:13] == "custom_model_" {
t.Fatalf("model_list 不应包含自定义模型槽位 %q(选中后上游回空内容)", id)
}
}
// 可调用模型必须还在(不能把整张表干掉换绿)
found := false
for _, raw := range models {
m, _ := raw.(map[string]interface{})
if m["id"] == "glm-5.2" {
found = true
}
}
if !found {
t.Fatalf("可调用的 glm-5.2 不应被一起藏掉;实得 %v", models)
}
}
// 上游源的模型清单同样不含占位槽位(客户端按裸名就能调,藏 UI 不够)。
func TestTraeSourceOmitsCustomModelSlots(t *testing.T) {
c := kernelTestCore(t)
ps := c.Plugins()
src, err := readBundledChannels(t)
if err != nil {
t.Fatal(err)
}
if err := ps.LoadSource("channels", src); err != nil {
t.Fatal(err)
}
_ = ps.SetPluginKernelPermission("channels",
[]string{"add_source", "remove_source", "list_sources", "status"}, false)
if _, err := ps.Call("channels", "account_add", map[string]interface{}{
"platform": "trae", "account_id": "trae-a",
"credential": `{"access_token":"jwt","uid":"1","device_id":"d","machine_id":"m"}`,
}); err != nil {
t.Fatalf("account_add: %v", err)
}
ls, err := ps.Call("channels", "__list_sources_probe", map[string]interface{}{})
if err != nil {
t.Fatalf("probe: %v", err)
}
j, _ := ls.(map[string]interface{})["json"].(map[string]interface{})
arr, _ := j["sources"].([]interface{})
haveTrae := false
for _, raw := range arr {
m, _ := raw.(map[string]interface{})
if m["name"] == "channels-trae" {
haveTrae = true
}
}
if !haveTrae {
t.Fatalf("trae 账号加好后应产出 channels-trae 源;实得 %v", arr)
}
// 源里的模型清单从内核真实源读(不是插件的 model_list)
srcs := c.Sources()
for _, s := range srcs {
if s.Name != "channels-trae" {
continue
}
for _, m := range s.Models {
if len(m.ID) > 13 && m.ID[:13] == "custom_model_" {
t.Fatalf("上游源不应包含自定义模型槽位 %q", m.ID)
}
}
if len(s.Models) == 0 {
t.Fatal("channels-trae 源应带模型清单")
}
}
}

View File

@ -343,6 +343,16 @@ function __prelude.openai_error(status, body)
return resp.detail
end
-- 10. 腾讯 codebuddy 的**三层嵌套**:{error:{data:{code,msg,requestId}}}。
-- 实测 429 code=14018「额度已用尽,请访问以下链接,购买加量包…」——
-- 此前落到"不识别",内核只回通用文案,用户看不出是额度用尽
-- (日志里是 "transform_error returned no reason for this shape")。
local ed = type(resp.error) == "table" and resp.error.data or nil
if type(ed) == "table" and type(ed.msg) == "string" and ed.msg ~= "" then
if ed.code ~= nil then return tostring(ed.code) .. ": " .. ed.msg end
return ed.msg
end
-- 7/8/9. 网关与腾讯系形状(实测漏过,见函数头注释)。
-- error_code 与 error_msg 同现时拼起来 —— 只看 msg 会丢掉可分类的码
-- (参考 llm-adapter.ts:531 把两者都放进 parts 再 join)。

View File

@ -58,6 +58,12 @@ func TestPreludeErrorExtractionCoversGatewayShapes(t *testing.T) {
{"FastAPI detail", `{"detail":"boom"}`, "boom"},
{"HTML title", `<html><title>413 Too Large</title></html>`, "413 Too Large"},
{"裸文本", "plain failure line\nmore", "plain failure line"},
// 腾讯 codebuddy 三层嵌套(实测 429 code=14018 额度用尽):
// 此前落到"不识别",客户端只看到通用文案,用户分不清是额度还是故障。
{"buddy 额度用尽嵌套", `{"error":{"data":{"code":14018,"msg":"额度已用尽,请购买加量包","requestId":"r1"}}}`,
"14018: 额度已用尽,请购买加量包"},
// 同一形状但没有 code:只回 msg
{"buddy 嵌套无码", `{"error":{"data":{"msg":"请求被拒绝"}}}`, "请求被拒绝"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {

File diff suppressed because it is too large Load Diff