diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index fdd726d9..34f4b757 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -23,7 +23,9 @@ repos: rev: v5.0.0 hooks: - id: trailing-whitespace # 去除行尾空白 + exclude: ^docs/diagrams/ # Archify 图产物与校验回执按字节绑定,不能被 hook 改写 - id: end-of-file-fixer # 确保文件以换行符结尾 + exclude: ^docs/diagrams/ - id: check-yaml args: ["--unsafe"] # 兼容 GitHub Actions ${{ }} 表达式语法 - id: check-toml # 校验 TOML 语法(pyproject.toml) diff --git a/assets/dashboard/config-tab.png b/assets/dashboard/config-tab.png index 316daaf5..b845871b 100644 Binary files a/assets/dashboard/config-tab.png and b/assets/dashboard/config-tab.png differ diff --git a/assets/dashboard/overview.png b/assets/dashboard/overview.png index 5bc5e16c..7e78600c 100644 Binary files a/assets/dashboard/overview.png and b/assets/dashboard/overview.png differ diff --git a/docs/.agents/issue.md b/docs/.agents/issue.md index 7da0bf4d..22440cd2 100644 --- a/docs/.agents/issue.md +++ b/docs/.agents/issue.md @@ -23,6 +23,8 @@ | I-011 | Antigravity 桌面 2.32.1 模型流绕过 `CLOUD_CODE_URL` 通道(前端只见控制面调用次数,无模型/Token 指标) | ✅ 已完成 | 2026-11-16 | [详情](#I-011) | | I-012 | Dashboard 供应商行拖拽在列表外松开后卡死(行停在半透明,列表不再刷新) | ✅ 已完成 | 2026-11-24 | [详情](#I-012) | | I-013 | Dashboard 无用量数据时第二次刷新起抛 TypeError(图表空态替换掉 canvas 后未恢复) | ✅ 已完成 | 2026-11-24 | [详情](#I-013) | +| I-014 | Model Bind 下拉缺 GLM 5.4(pricing 与调用记录已有,但内置目录停在 GLM 5.3) | ✅ 已完成 | 2026-11-27 | [详情](#I-014) | +| I-015 | Dashboard 编辑 Model Calling 并行度时轮询提交半截输入、每次编辑连发两个 PUT | ✅ 已完成 | 2026-11-27 | [详情](#I-015) | --- @@ -540,4 +542,54 @@ Overview 页拖动供应商行调整优先级:行越过相邻行(发生一 同类风险:任何「无数据时用 innerHTML 替换容器内容」的图表或列表面板(Chart.js、地图、表格容器);排查时先看报错前的第一次渲染有没有移除节点。Chart.js 实例销毁后再调用 `destroy()` 不会出错(canvas 已置空,直接跳过),空态分支不清空图表变量不影响正确性。 + +## I-014:Model Bind 下拉缺 GLM 5.4(pricing 与调用记录已有,但内置目录停在 GLM 5.3) + +**问题描述** + +用户在 Config 页 pricing 给 zhipu 加了 `glm-5.4`,调用记录与 Sessions 页 Models 列也已出现 `glm-5.4`,但 Sessions 页 Model Bind 下拉里没有 GLM 5.4,无法把会话绑到该模型。 + +**表因根因** + +表因:下拉选项来自 `/api/status` 的 `bindable_models`,前端原样渲染、不做过滤。根因:`bindable_models` 在 app 构建时由「内置 vendor 目录(`vendors/model_catalog.py` 的代码常量)∪ `session_policies.bindable_models` 显式条目」合成,pricing 和调用记录都不是目录来源;内置 zhipu 目录停在 GLM 5.3,没有 `glm-5.4`。[session-model-bind.md](../arch/session-model-bind.md) §6 已把「内置目录滞后于上游新模型」列为已知边界,这次是该边界在 GLM 5.4 上的实际触发。 + +**处理方式** + +`_ZHIPU` 补 `("GLM 5.4", "glm-5.4")`;条目随目录自动获得 zhipu 锁定与 identity 映射规则(`glm-5.4 → glm-5.4`,不被 default 回退改写)。`tests/test_model_catalog.py` 补目录与 identity 规则两条回归用例,`tests/test_app_routes.py::test_status_returns_bindable_models` 补 `/api/status` 断言,补完先红后绿。对照验证(隔离实例,Playwright):`/api/status` 含 GLM 5.4,Sessions 下拉 Zhipu 组首位出现 GLM 5.4,选中后 `PUT /api/session-vendor` 返回 200,绑定为 `vendors=[zhipu]`、`model=glm-5.4`。 + +**第二步(同日,用户拍板「pricing 并入目录 + 只能下线不能删除」后实施)**:`compose_bindable_catalog` 扩为「内置 ∪ pricing 行(仅 native vendor,配价即入下拉)∪ bindable_models」;pricing 行新增 `online` 字段(false = 下线:不进下拉、PUT 拒绝新绑,executor 锁定链与热切换迁移改用 `get_known_models()` 含下线清单,已绑会话保留);`ConfigService._plan` 加「pricing 不可缩减」校验(删除/改名/恢复默认丢行一律拒绝,错误只带条数不回显值);Config 页 Pricing 表去删除、vendor/model 只读、加 Status 列与「下线/上线」,「恢复默认」改「恢复默认价格并保留自定义行」。全量 2270 项通过;隔离实例 + Playwright 端到端:配价即入下拉并可绑定,下线后下拉消失、已绑会话保留并显示 `(off-list)`、新绑 400 指明 offline,删除行被 422 拒绝,`online: true` 恢复可绑。 + +**后续防范** + +上游出新 native 模型(GLM、MiniMax、Kimi、Doubao、MiMo、Qwen)时,配价(pricing 行)即入下拉,无需等发版补目录;非 native 模型或需要自定义 label/tiers 时,Config 页 Session Policies → Bindable Models 加一条 `label` + `model`(`tiers` 留空即可,自动获得 identity 规则),保存并应用配置后生效(每代配置经 `create_app` 重新合成目录)。模型退役走 pricing 行「下线」,不可删除。 + +**同类问题影响与处理注意事项** + +同类风险:所有 native 系 vendor 的新型号。pricing 并入目录已落地(第二步):配价即入下拉,删除被服务端拦截,退役走 `online: false`;注意该规则使「打错一行 pricing」无法删除只能下线后重加,属刻意取舍。`config.default.yaml` 的默认 pricing 未含 `glm-5.3` / `glm-5.4`,这两个型号的价格需用户按官方公布自配,代码里不臆填。 + +--- + + +## I-015:Dashboard 编辑 Model Calling 并行度时轮询提交半截输入、每次编辑连发两个 PUT + +**问题描述** + +在 Overview 的「Model Calling 实时状态」卡片点开某个模型的上限、输入新值时,如果赶上 10 秒一次的轮询,输入框被整体重绘移除;移除触发 blur,挂起的提交把半截输入当成最终值发给 `PUT /api/concurrency`(真实页面复现:想把 10 改成 12,刚敲出「1」时发出了 `{"limit":1}`,成功与失败的闪烁又落在已脱离文档的旧节点上,用户毫无察觉)。另外每次编辑会连发两个相同的 PUT;上限是不可聚焦的 span,键盘用户无法修改;`7.5`、`1e2` 这类输入被 `parseInt` 截断后提交。 + +**表因根因** + +表因:`updateModelCalling` 每轮轮询用 `innerHTML` 整体重建列表,没有判断是否处在编辑态;blur 回调里的 `submit()` 没有幂等守卫,回车提交后移除输入框又触发一次提交。根因:把「每 10 秒刷新」实现成「整块 DOM 替换」,用户正在输入的节点没有被当作受保护的状态;提交路径没有单一出口,「回车提交」与「失焦提交」各自成立、叠加后不收敛。 + +**处理方式** + +Model Calling 改为按 vendor / model 键复用行节点,轮询只改文字与条宽;`_mcEditing` 为真时整卡跳过重绘,输入框、焦点与已输入的内容原样保留。编辑流程重写:上限是可聚焦的按钮;提交带一次性与在途守卫,输入只接受 1 到 20 的整数;请求挂起时 8 秒兜底解除编辑态;结束编辑后焦点回到按钮;成功后就地重算这一行并拉一次状态对齐服务端;结果用静态色标并写入模板里常驻的 `role=status` 节点供读屏播报;编辑一行时点另一行的上限,当前提交完成后接着打开那一行,不再要点第二次。新增 `tests/test_dashboard_overview.py`,在 Node 假 DOM 上覆盖编辑全流程(轮询不打断、回车后失焦不二次提交、非法输入、失败、超时)。真实页面复测:编辑中触发轮询,输入框、值与焦点保留且不发请求;回车后只发 1 个 PUT。 + +**后续防范** + +轮询驱动的面板不要整块重建 DOM,改为按键复用节点、就地更新;用户正在输入的节点视为受保护状态,重绘前先判断编辑态。「失焦即提交」的控件必须有单一提交出口(一次性守卫先落标记再移除节点),验证用例至少覆盖「回车提交后紧跟失焦」「提交未决时再次回车」「输入到一半时刷新到达」三条路径。 + +**同类问题影响与处理注意事项** + +同类风险:其它「变更即提交」的控件,以及任何用 `innerHTML` 周期性重建、内部含输入控件的列表。排查时先问两件事:重绘会不会移除正在编辑的节点;提交函数重入时会不会再发一次请求。用浏览器自动化复现这类时序问题时,要直接调用页面的刷新函数制造「输入到一半时刷新到达」,不要等真实的轮询周期。 + --- diff --git a/docs/.agents/knowledge-map.md b/docs/.agents/knowledge-map.md index 4cc3fa21..2b59784f 100644 --- a/docs/.agents/knowledge-map.md +++ b/docs/.agents/knowledge-map.md @@ -71,7 +71,17 @@ --- -## 6. Agent 协作与问题档案([docs/.agents/](./)) +## 6. 设计向([docs/design/](../design/)) + +> 面向已批准改造的设计文档(Lightweight RFC),记录关键取舍与依据;图源在 [docs/diagrams/](../diagrams/)。 + +| 文档 | 主旨 | +| ------------------------------------------------------------- | ----------------------------------------------------- | +| [design/config-tab-ux-batch1.md](../design/config-tab-ux-batch1.md) | Config 页保存反馈、操作落点、破坏性操作与 label 列宽 | + +--- + +## 7. Agent 协作与问题档案([docs/.agents/](./)) > 面向 AI Agent 协作与跨上下文问题沉淀的支撑文档。 @@ -82,7 +92,7 @@ --- -## 7. 工程规范(顶层) +## 8. 工程规范(顶层) | 文档 | 主旨 | | --------------------------------- | ----------------------------------------------------- | diff --git a/docs/arch/config-reference.md b/docs/arch/config-reference.md index f11893c9..43047630 100644 --- a/docs/arch/config-reference.md +++ b/docs/arch/config-reference.md @@ -251,11 +251,14 @@ | --------------------------- | ----- | -------------------------------------------------- | | `vendor` | str | 供应商名称 | | `model` | str | 实际模型名 | +| `online` | bool | 下线开关(默认 `true`):`false` 后该模型不进 Model Bind 下拉、不可新绑定;已绑会话保留并继续按锁定 vendor 路由,成本照常计价 | | `input_cost_per_mtok` | float | 输入 Token 单价($/百万 token,支持 `$`/`¥` 前缀) | | `output_cost_per_mtok` | float | 输出 Token 单价 | | `cache_write_cost_per_mtok` | float | 缓存创建 Token 单价 | | `cache_read_cost_per_mtok` | float | 缓存读取 Token 单价 | +写入边界:pricing 行**不可删除**——任何 (vendor, model) 行消失(删除、改名、「恢复默认」丢行)的保存一律拒绝(错误只带条数不回显值);退役模型请置 `online: false`。`config import` 整体替换不在其限。已保存行的 vendor/model 在 Config 页只读。native 系 vendor(zhipu/minimax/kimi/doubao/xiaomi/alibaba)的 pricing 行同时是 Model Bind 目录的派生来源:配价即入下拉,无需等发版补内置目录(见 [session-model-bind.md](session-model-bind.md))。 + --- ## 8. tiers — 显式优先级 @@ -379,7 +382,7 @@ env var(运行时) > 存储的显式字段(Dashboard / CLI 配置) > Pyd | --- | --- | --- | --- | | `policies` | `list[SessionPolicy]` | `[]` | 配置态 Session 路由策略,按序求值首次命中生效(存量键:`name`/`match.session_keys`/`tiers`,注释见 `config.default.yaml`) | | `policies.*.model` | `str \| null` | `null` | 会话级模型覆盖:非空时该 Session 的后续请求体 `model` 统一改写为此值(逐请求生效,在途请求不受影响) | -| `bindable_models` | `list[BindableModel]` | claude 三档 | 可绑定模型显式定制层:下拉选项为其与内置 vendor 目录(按激活 vendor 过滤)的合成结果;空清单 = 整体关闭模型绑定(含内置目录) | +| `bindable_models` | `list[BindableModel]` | claude 三档 | 可绑定模型显式定制层:下拉选项为其与「内置 vendor 目录 ∪ pricing 行(native vendor)」(按激活 vendor 过滤)的合成结果;空清单 = 整体关闭模型绑定(含内置目录与 pricing 派生条目) | | `bindable_models.*.label` | `str` | — | UI 显示名,清单内唯一,非空 | | `bindable_models.*.model` | `str` | — | 覆盖目标模型名,清单内唯一,非空 | | `bindable_models.*.tiers` | `list[str]` | `[]` | 随绑定重排的 vendor 优先级;同名覆盖内置条目时留空继承内置锁定值,纯自定义条目留空 = 不改当前 tier 顺序 | @@ -388,7 +391,7 @@ env var(运行时) > 存储的显式字段(Dashboard / CLI 配置) > Pyd ### 11.2 目录合成与 identity 规则 -下拉选项在 app 构建时合成(内置目录 ∪ 本清单,按 `model` 去重、config 覆盖 label/tiers、`exclude` 剔除);合成目录中 native 系 vendor 的模型自动获得 identity `model_mapping` 规则(pattern = target,custom 条目按锁定 tiers 或原生前缀族归属),无需手工配置,防 `ModelMapper` default 静默改写。绑定语义为 vendor.model 锁定(严格链,不做跨系列静默降级);详见 [session-model-bind.md](session-model-bind.md)。 +下拉选项在 app 构建时合成(内置目录 ∪ pricing 行 ∪ 本清单,按 `model` 去重、config 覆盖 label/tiers、`exclude` 剔除);pricing 派生条目仅取 native 系 vendor 且在激活链(label = model 名,tiers 锁定该 vendor),`online: false` 的模型带 `offline` 标记——不进下拉与 PUT 校验,executor 锁定链与热切换迁移仍可见(已绑会话保留)。合成目录中 native 系 vendor 的模型自动获得 identity `model_mapping` 规则(pattern = target,custom 条目按锁定 tiers 或原生前缀族归属),无需手工配置,防 `ModelMapper` default 静默改写。绑定语义为 vendor.model 锁定(严格链,不做跨系列静默降级);详见 [session-model-bind.md](session-model-bind.md)。 ## 12. antigravity_gateway — Antigravity 客户端透传配置 diff --git a/docs/arch/session-model-bind.md b/docs/arch/session-model-bind.md index a5e9df48..8aa38d43 100644 --- a/docs/arch/session-model-bind.md +++ b/docs/arch/session-model-bind.md @@ -32,7 +32,7 @@ ## 3. 可绑定目录与配置([config-reference.md](config-reference.md) 为参数权威) -下拉选项 = **内置 vendor 目录(按激活 vendor 过滤)∪ `bindable_models` 显式条目**,合成于 app 构建时([model_catalog.py](../../src/coding/proxy/vendors/model_catalog.py)): +下拉选项 = **内置 vendor 目录 ∪ pricing 行(仅 native vendor)∪ `bindable_models` 显式条目**(三者均按激活 vendor 过滤),合成于 app 构建时([model_catalog.py](../../src/coding/proxy/vendors/model_catalog.py)): ```yaml session_policies: @@ -45,14 +45,17 @@ session_policies: ``` - 合成规则:按 `model` 去重;config 同名条目覆盖 `label`/`tiers`(`tiers` 留空继承内置锁定值),`exclude: true` 剔除内置同名条目;纯自定义条目原样保留(`vendor: custom`,tiers 留空 = 沿用全局链路顺序)。 +- **pricing 派生条目**:native 系 vendor(zhipu/minimax/kimi/doubao/xiaomi/alibaba)的已配价模型即时进目录(label = model 名,tiers 锁定该 vendor),填补内置目录的发版滞后;与内置/config 同名时让位。 +- **下线(`pricing.*.online: false`)**:模型带 `offline` 标记——不进下拉,`PUT /api/session-vendor` 拒绝新绑(400,文案指明 offline);executor 锁定链与热切换迁移消费含下线的全量清单(`get_known_models()`),已绑会话保留并继续按锁定 vendor 路由(Sessions 页显示 `(off-list)`);成本照常计价,identity 规则保留。 +- **pricing 行不可删除**:Config 页与 `PUT /api/config`、CLI `config set` / `config reset` 对任何会使 (vendor, model) 行消失的保存一律拒绝(错误只带条数不回显值;`config import` 整体替换除外)。Config 页已保存行以「下线/上线」替代删除,vendor/model 只读,「恢复默认价格」保留自定义行。 - **identity 映射规则自动合成**:合成目录中 native 系 vendor(zhipu/minimax/kimi/doubao/xiaomi/alibaba)的模型在 app 构建时自动获得 `pattern=target=model` 规则(custom 条目按锁定 tiers 或原生前缀族归属),无需手工配置,杜绝 ModelMapper default 回退静默改写;已被用户显式映射规则(exact/通配/正则)覆盖的模型跳过合成,用户规则优先。 - 未知名(不在任何原生前缀族,如自定义微调模型名)绑定到 native 系 vendor 需配套显式 `model_mapping` 规则,否则门控不放行(native 系对未知名的 default 回退是静默改写而非透传,不放行是刻意防错);anthropic 真透传 vendor 对未知名仍放行。 - 合成目录外的模型无法通过 API 绑定(PUT 校验返回 400)。 -- 内置目录是发版节奏的静态快照:上游新模型未经目录/自定义条目触达不出现在下拉;用户可经自定义条目即时自救(自动获得 identity 规则)。 +- 内置目录是发版节奏的静态快照:native vendor 的新模型配价(pricing 行)即入下拉,或经自定义条目即时自救(自动获得 identity 规则)。 ## 4. API 与 CLI -- `PUT /api/session-vendor`:body `{session_key, vendors?: [..], model?: "..."}`,至少一项;`model` 必须在合成目录(内置 ∪ config)内;`vendors` 省略时沿用目录 entry 的 `tiers`。 +- `PUT /api/session-vendor`:body `{session_key, vendors?: [..], model?: "..."}`,至少一项;`model` 必须在合成目录(内置 ∪ pricing ∪ config)内且未下线(下线模型返回 400,文案指明 offline);`vendors` 省略时沿用目录 entry 的 `tiers`。 - `GET /api/session-vendor`:bindings 增返 `model` 字段(无模型覆盖时为 `null`)。 - `DELETE /api/session-vendor/{session_key}`:清除整条运行时绑定(model + tiers 一并移除,恢复配置态策略备份)。 - `GET /api/status`:增返 `bindable_models` 数组(UI 选项源)。 @@ -76,7 +79,8 @@ session_policies: | 风险 | 处置 | | --- | --- | | ModelMapper default 静默改写原生模型名 | 目录内模型自动获得 identity 规则(构造期合成);目录外自定义条目按 tiers/前缀族兜底合成 + executor map 漂移 WARNING | -| 内置目录滞后于上游新模型 | 发版补目录为补给线;自定义条目即时自救(自动 identity 规则);identity 透传保证「发什么是什么」,无静默错路由 | +| 内置目录滞后于上游新模型 | 发版补目录为补给线;native vendor 新模型配价(pricing 行)即入目录;自定义条目即时自救(自动 identity 规则);identity 透传保证「发什么是什么」,无静默错路由 | +| 删除 pricing 行导致已绑会话在热切换时被丢弃 | pricing 行不可删除(服务端 `_plan` 校验 + Config 页去删除),退役走 `online: false` 下线:下拉隐藏但目录保留,已绑会话继续路由 | | 绑定 vendor.model 后该 vendor 全体不可用 | 严格链显式失败(可用性换确定性,流式/非流式同型 `NoCompatibleVendorError`、文案指向锁定链真因);custom 条目(tiers 空)不受影响 | | 标题自动绑定覆盖手动绑定(compat TTL 24h 过期重触发) | `_apply_title_based_policy` 先查 `get_runtime_binding`,存在即跳过 | | 跨供应商 thinking signature / cache_control 残留 | `VENDOR_TRANSITIONS` 通道按方向注册;无通道方向原样透传,可能上游 400 → 走 semantic failover;跨系列放开前需补通道并实测 | @@ -86,9 +90,11 @@ session_policies: ## 7. 测试锚点 -- `tests/test_model_catalog.py`:目录合成矩阵(激活过滤/覆盖/exclude/去重/label 冲突降级/空清单关闭)、identity 规则合成(内置/custom/前缀族兜底/用户规则优先)、`supports_model` 判定矩阵、executor 严格链与模型门控。 +- `tests/test_model_catalog.py`:目录合成矩阵(激活过滤/覆盖/exclude/去重/label 冲突降级/空清单关闭)、pricing 派生(native 过滤/激活过滤/去重/下线标记/identity 规则)、identity 规则合成(内置/custom/前缀族兜底/用户规则优先)、`supports_model` 判定矩阵、executor 严格链与模型门控。 - `tests/test_session_aware.py`:resolver model 语义(upsert / get_runtime_binding / list)、空 tiers 继承配置策略顺序、`bindable_models` 配置校验(唯一性 / 非空)。 - `tests/test_router_executor.py`:模型覆盖注入(shadow copy、绑定按原 session_key 命中、客户端原始模型名留存于 INFO 日志)、在途请求不受绑定变更影响(流式 / 非流式)、failover 接单与映射改写的漂移告警、配置策略携带 model、标题自动绑定避让。 -- `tests/test_app_routes.py`:`PUT/DELETE/GET /api/session-vendor` 路由级校验(含 model 分支、合成目录、清单为空、vendors 非列表)与 `/api/status` 的 `bindable_models`。 +- `tests/test_app_routes.py`:`PUT/DELETE/GET /api/session-vendor` 路由级校验(含 model 分支、合成目录、下线模型拒绑、清单为空、vendors 非列表)、`/api/status` 的 `bindable_models`(下线模型过滤)与热切换迁移保留已绑下线模型。 +- `tests/test_config_service.py`:pricing 行不可删除(删除 / 改名 / 恢复默认丢行拒绝,新增与 `online` 开关放行,错误不回显值)。 +- `tests/test_dashboard_config_tab.py`:Config 页 Pricing 表(已保存行无删除、vendor/model 只读、下线/上线、恢复默认价格保留自定义行)。 - `tests/test_config_loader.py`:默认清单来自 `config.default.yaml` 的加载守护。 - `tests/test_cli_usage.py`:`session bind --model/--vendor` payload 与缺参退出码。 diff --git a/docs/arch/subscription-status.md b/docs/arch/subscription-status.md index 46eacc20..9db60f10 100644 --- a/docs/arch/subscription-status.md +++ b/docs/arch/subscription-status.md @@ -25,10 +25,11 @@ Dashboard Overview ── GET /api/dashboard/subscriptions 卡片是纯前端渲染:订阅数据(`GET /api/dashboard/subscriptions`)与路由 tier 数据(`GET /api/status` 的 `tiers`)并发拉取后,在 `_renderStatusRows` 里做 full outer join。两个端点与响应形状互不耦合,订阅数据不并入 `/api/status`(后者被 Model Calling 面板 10 秒轮询,而订阅拉取带上游超时)。 - 归并键:`SUB_META[key].tier`,`claude → anthropic`、`glm → zhipu`、`antigravity → antigravity`。`tier.name` 恒等于 vendor 类型字面量且运行时同类型至多一个 tier,按名归并不会串行;取值必须是 [config/routing.py](../../src/coding/proxy/config/routing.py) 的 `VendorType` 之一,由测试钉死; -- 三类行:合并行(订阅 × tier,行名取订阅名;订阅显示名与 tier 名仅大小写不同时不标注,其余在路由区灰字标注 tier 名)、供应商行(无订阅对应,路由区灰字「供应商状态」;头像首字母与订阅行头像撞字母时取前两个字母,如 copilot → `Co`,见 `_tierInitial`)、订阅行(无对应 tier,行尾灰字「未加入路由链」,没有路由区也就不画分隔线); -- 渲染语法:每个分区都是 `[灰字标签] [状态胶囊] [用量格]*`。胶囊只承载状态(熔断 / 限速 / 等待 / 未启用 / 查询失败);档位是行名后的加粗亮字,档位名与行名相同时不重复显示(`_planLabel`,如 Antigravity);用量格 `renderQuotaCell` = 窗口短标签 + 40px 进度条 + 百分比,订阅窗口再缀紧凑重置倒计时(`fmtResetShort`,完整写法 `fmtResetCountdown` 进 Tooltip),严重度类名 `quotaClass` 同时决定格底色与进度条填充色。订阅窗口的短标签取自 `window`(`5h` / `weekly` → `5h` / `周`),配额守卫窗口按 `window_hours` 折算(`quotaWindowLabel`),认不出的类别回退 `label`。类别表与分组表都是 `Map`:上游给到 `constructor`、`__proto__` 一类的值时不会命中继承成员而让整卡渲染抛错; +- 三类行:合并行(订阅 × tier,行名取订阅名;路由区只有该 vendor 的可用状态,tier 名只进悬停详情)、供应商行(无订阅对应,路由区同样只有可用状态;头像首字母与订阅行头像撞字母时取前两个字母,如 copilot → `Co`,见 `_tierInitial`)、订阅行(无对应 tier,行尾灰字「未加入路由链」,没有路由区); +- 渲染语法:订阅区是 `[灰字标签] [状态胶囊] [用量格]*`,路由区是 `[可用状态]`。胶囊只承载状态(订阅区:等待 / 未启用 / 查询失败;路由区:熔断 / 半开 / 限速中 / 配额超限);档位是行名后的加粗亮字,档位名与行名相同时不重复显示(`_planLabel`,如 Antigravity);用量格 `renderQuotaCell` = 窗口短标签 + 40px 进度条 + 百分比,订阅窗口再缀紧凑重置倒计时(`fmtResetShort`,完整写法 `fmtResetCountdown` 进 Tooltip),严重度类名 `quotaClass` 同时决定格底色与进度条填充色。订阅窗口的短标签取自 `window`(`5h` / `weekly` → `5h` / `周`),认不出的类别回退 `label`;配额守卫窗口按 `window_hours` 折算(`quotaWindowLabel`),只出现在路由区悬停详情里。类别表与分组表都是 `Map`:上游给到 `constructor`、`__proto__` 一类的值时不会命中继承成员而让整卡渲染抛错; +- 可用状态(`_tierZoneHTML`):路由区只回答该行 vendor 现在能不能接请求,取值与顺序固定为 `熔断 ×N`、`半开`、`限速中`、`配额超限`:`熔断 ×N` 对应 `circuit_breaker.state` 为 `OPEN`(N 取 `failure_count`,为 0 或非数字时只写「熔断」),`半开` 对应 `HALF_OPEN`,`限速中` 对应 `rate_limit.is_rate_limited` 为真,`配额超限` 对应 `quota_guard` / `weekly_quota_guard` 任一 `state` 为 `quota_exceeded`。多个条件并存时全部列出,一个都没有时只有「正常」。呈现分两档:无异常是 6px 绿点加灰字,异常才是 `status-badge` 胶囊,整列里异常一眼可见。tier 名、熔断器状态与失败次数、限速剩余秒数、各配额守卫窗口的已用百分比与阈值收进整块的 `title` 悬停详情; - 分组与排序(`_subZoneHTML`):窗口按 `group` 分组,每组 = 灰字标签 + 该组用量格,无 `group` 的家(GLM / Claude)并为一组不出标签;组内先 5h 后 周,未知类别殿后(`_windowRank`); -- 单行与对齐:视口宽于 960px 时行是 `nowrap` 的 flex 行,分区各自 `overflow-x: auto`,余量不足时只由订阅区横向滚动(路由区 `flex: 0 0 auto` 不收缩)。滚动条隐藏:经典滚动条平台(Windows / Linux、macOS 接鼠标)上它会占掉分区的行内高度,让放不下的一行文字比行名高出几个像素。分区滚动位置按「行名 + 区」在重绘前后带走(`_zoneScroll` / `_restoreZoneScroll`),刷新不会把用户滚到的位置弹回起点。标识区 `min-width: 168px` 让各行的订阅区从同一竖线起排,路由区 `min-width: 208px` 让内容不超过它的行分隔线彼此对齐(tier 名 + 状态徽章 + 一个用量格),内容更多的行(如同时配了 5h 与周两个配额守卫)自动外扩、仅该行的分隔线左移。960px 及以下退回两行:标识与路由区占首行,订阅区独占次行; +- 单行与对齐:视口宽于 960px 时行是 `nowrap` 的 flex 行,分区各自 `overflow-x: auto`,余量不足时只由订阅区横向滚动(路由区 `flex: 0 0 auto` 不收缩)。滚动条隐藏:经典滚动条平台(Windows / Linux、macOS 接鼠标)上它会占掉分区的行内高度,让放不下的一行文字比行名高出几个像素。分区滚动位置按「行名 + 区」在重绘前后带走(`_zoneScroll` / `_restoreZoneScroll`),刷新不会把用户滚到的位置弹回起点。标识区 `min-width: 168px` 让各行的订阅区从同一竖线起排;路由区按内容取宽、右对齐,状态多的行(熔断、限速中、配额超限并存)自动外扩,余量不足时被挤压的仍是订阅区。960px 及以下退回两行:标识与路由区占首行,订阅区独占次行; - 容器与行序:带 tier 的行按 `tiers` 顺序排在 `#vendor-list`,无 tier 的订阅行排在其后的 `#subscription-list`。拖拽按 `#vendor-list` 的 DOM 顺序拼 `PUT /api/tier-order` 载荷,可拖拽行必须是连续前缀,订阅行不得进入该容器; - 并发守卫:`updateVendorStatus` 与 `updateSubscriptions` 只更新缓存(`_tierStatus` / `_subData`)再调 `_renderStatusRows`,拖拽进行中或 PUT 未决时跳过重绘。仅带 tier 数据的定向重渲染(拖拽回滚、复位后刷新)复用订阅缓存,订阅区不会被清空;`PUT /api/tier-order` 成功后先按已提交顺序同步 `_tierStatus`(`_syncTierOrder`)再刷新,拖拽结束时的补绘不会用过期顺序把行序画回去。三处拉取路由状态的入口统一走 `fetchTierStatus`:请求发出后才有重排被确认时(连按方向键),迟到的快照只采用状态字段,行序以已确认的顺序为准;整页刷新时两路数据到齐后只重绘一次,避免行节点被连续替换; - 键盘调整:手柄是可聚焦按钮,`↑` / `↓` 触发 `_tierMove`(乐观重排并重绘,再走与拖拽相同的 `persistTierOrder` 与失败回滚);重绘会替换节点,`_renderStatusRows` 记住焦点所在的行,重绘后回到同一行的手柄; @@ -85,4 +86,4 @@ Dashboard Overview ── GET /api/dashboard/subscriptions ## 测试锚点 - [tests/test_subscription_status.py](../../tests/test_subscription_status.py):unified 头解析(含大小写/畸形值/NaN/Infinity/钳制)、vendor 钩子旁路采集(流式+非流式)、两家 fetcher(MockTransport、双字段形态、403 门控、token 失效、缺 displayName / window 的容错、模型族短名)、服务 TTL/错误隔离、端点集成、token store 回退构建(含 enabled 口径与 gateway host 覆写); -- [tests/test_dashboard_subscription_card.py](../../tests/test_dashboard_subscription_card.py):HTML 接线、XSS 转义静态检查、`SUB_META` 归并键与 `VendorType` 的一致性、内联渲染函数 Node vm 行为验证(三类行与行序、用量格语法与严重度、倒计时两种写法、分组与排序、档位去重、未知窗口类别与原型键名称回退、徽章分支、订阅数据缺失降级、拖拽并发守卫、恶意档位名 / 模型族 / 窗口标签与 tier 名转义)、单行 CSS 约束的静态断言;拖拽状态机在最小假 DOM 上的 Node 行为验证(指针在列表外松开、多指重入、过期缓存补绘、PUT 失败回滚、键盘调整与焦点保持、迟到的状态快照不覆盖行序、按住期间行被重绘、重绘保留分区滚动位置)。 +- [tests/test_dashboard_subscription_card.py](../../tests/test_dashboard_subscription_card.py):HTML 接线、XSS 转义静态检查、`SUB_META` 归并键与 `VendorType` 的一致性、内联渲染函数 Node vm 行为验证(三类行与行序、用量格语法与严重度、倒计时两种写法、分组与排序、档位去重、未知窗口类别与原型键名称回退、路由区只剩状态:正常、熔断、半开、限速中、配额超限、多条件并存、缺字段、订阅数据缺失降级、拖拽并发守卫、恶意档位名 / 模型族 / 窗口标签与 tier 名转义)、单行 CSS 约束的静态断言;拖拽状态机在最小假 DOM 上的 Node 行为验证(指针在列表外松开、多指重入、过期缓存补绘、PUT 失败回滚、键盘调整与焦点保持、迟到的状态快照不覆盖行序、按住期间行被重绘、重绘保留分区滚动位置)。 diff --git a/docs/arch/testing.md b/docs/arch/testing.md index 1202eecc..f472d536 100644 --- a/docs/arch/testing.md +++ b/docs/arch/testing.md @@ -111,9 +111,10 @@ | `test_generations_app.py` | 真实 app/store 下的 PUT 热切换、流式跨切换、会话绑定迁移、真实 uvicorn | | `test_generations_cli.py` | CLI `start` 与 GenerationManager 接线、Dashboard URL 提示、degraded 启动 | | `test_security_middleware.py`| L1 跨站请求拒绝 / L2 管理面 Host 白名单 / 响应安全头加固 | -| `test_dashboard_config_tab.py`| Config 页 HTML 接线、CSP/XSS 静态检查与 config.js Node harness | +| `test_dashboard_config_tab.py`| Config 页 HTML 接线、CSP/XSS 静态检查与 config.js Node harness(含保存后果清单与字段差异纯函数、保存栏结果态与关闭、行级移除撤销) | | `test_dashboard_subscription_card.py`| 订阅状态卡片 HTML 接线、XSS 静态检查、归并键一致性、单行 CSS 约束静态断言、合并渲染与拖拽状态机 Node harness(三类行 / 行序 / 用量格语法与分组排序 / 档位去重 / 并发守卫 / 列表外松开 / 多指 / 键盘调整 / 焦点保持 / 迟到快照 / 失败回滚 / 重绘保留滚动位置) | -| `test_dashboard_charts.py`| 图表空态:canvas 恒留在 DOM 中,无数据与有数据之间反复刷新不抛错(静态检查 + Node harness) | +| `test_dashboard_charts.py`| 图表空态与堆叠填充:canvas 恒留在 DOM 中,无数据与有数据之间反复刷新不抛错,四张图的空态进出与实例引用清理(静态检查 + Node harness) | +| `test_dashboard_overview.py`| Overview 布局硬约束(两栏、KPI 列、Model Calling 定宽列、页签下划线、渐隐提示)静态断言;KPI 区间标签(取数天数)与副行拆段、自选区间折算天数与本地日期、刷新途中改区间的补刷循环、Model Calling 行复用与并行度编辑全流程(含轮询不打断、单次提交、8 秒超时、编辑接力)、趋势页签切换与键盘、图表读屏摘要与分布图图例位置、订阅区溢出提示的 Node harness | | `test_subscription_status.py`| 订阅状态聚合:被动信号解析、两家 fetcher(含模型族短名与上游缺字段容错)、TTL 服务、端点集成 | ### 2.9 其他 diff --git a/docs/design/config-tab-ux-batch1.md b/docs/design/config-tab-ux-batch1.md new file mode 100644 index 00000000..c4be6fad --- /dev/null +++ b/docs/design/config-tab-ux-batch1.md @@ -0,0 +1,199 @@ +# Config 页第一批体验改造:保存反馈、操作落点、破坏性操作、label 列宽 + +Jira: N/A — 技术侧发起(Config 页 UI/UX 审计的第一批 1~4 项) +PRD: N/A +Related designs: [Dashboard 看板](../guide/dashboard.md);[配置字段参考](../arch/config-reference.md) +Author / Reviewers: ThreeFish / 待定 + +## Summary + +Config 页的保存结果改由页面底部的保存栏显示,确认框只在保存会产生实际后果时弹出并列出字段级新旧值;「添加」「排序」「展开」等操作后,新行滚入视口、键盘焦点留在原控件上;「全部恢复默认」和「移除 vendor」先确认,单行移除改为可撤销;label 列在窄窗口下保留 104px 下限,不再截断。改动只在 `config.js` 与 `config.css`,不动服务端 API、`dashboard.py` 外壳与列宽 token。 + +## Motivation + +在长页面下滚后点「保存」,成功、失败、409 的结果都渲染在视口外的页面顶部;每次保存都弹出同一个只列 section 名的确认框,有后果的保存和普通保存看起来一样。同时,Pricing 点「添加」后新行出现在 y=2707(视口高 900),排序、展开、开关分组之后焦点掉回 body,同屏两个同名「恢复默认」作用范围差 9 倍且都不确认。窗口小于约 1260px 时 label 被截断,1024 宽下 vendor 页 22 个 label 截断 11 个。 + +## Detailed Design + +### 1. 保存反馈与确认 + +保存栏成为唯一的保存结果反馈面。顶部 Banner 只保留模式类提示(`defaults`、`legacy_readonly`、`degraded`、待生效 section)。保存完成后保存栏不消失,切换为结果态,直到用户点「关闭」或再次编辑: + +| 结果 | 保存栏表现 | 是否自动消失 | +| --- | --- | --- | +| 已保存并生效 | 绿色圆点 + 文案 + 运行时重置明细(如「配额窗口已按用量数据库重建」)+「关闭」 | 否,再次编辑时清除 | +| 已保存,需重启 | 黄色圆点 + 原因 +「关闭」 | 否 | +| 保存失败(4xx / 5xx / 网络) | 红色圆点 + 原因,保留「放弃修改」「保存」(即重试) | 否 | +| 422 校验错误 | 行内红字不变;保存栏错误链接改为可读字段名(「Timeout(zhipu):不能为负数」),原路径放进 title | 否 | + +结果不自动消失,依据是 W3C APG 对 alert 的要求:「It is also important to avoid designing alerts that disappear automatically」[3];Atlassian 的 flag 规范同样要求失败与警告不自动消失 [7]。成功结果也不自动消失,是因为保存栏本身常驻底部、不遮挡内容,用户关闭的成本是一次点击。如果后续发现成功提示占位令人厌烦,可改为成功态 6 秒后收起,失败态保持不变。 + +保存时文案按阶段区分:拉取运行时状态与等待确认期间显示「等待确认…」,提交与重载期间显示「保存中…」。保存栏左侧由「N 个字段待保存(K 个 section)」改为「待保存:Vendors › zhipu、Pricing(3 处)」,按钮只写「保存」,不再重复计数。 + +确认框改为按后果触发:后果清单为空时直接提交,非空才弹。后果清单只收录保存前能确定的事实: + +| 后果 | 判定来源 | 是否危险(红色主按钮) | +| --- | --- | --- | +| 密钥写入、清空或改用环境变量 | 本次载荷的 `secret_ops` | 清空为危险 | +| 目标地址变更将清空已存密钥 | 前端已有的 `predictClearedSecrets()` | 是 | +| 有在途请求 | `/api/status` 的 `in_flight > 0` | 否 | +| 熔断、限流、配额超限状态将重置 | `/api/status` 各 tier 的状态 | 否 | +| 运行中的优先级与保存的 Tiers 不同 | `view.running.tiers` 与工作副本链路 | 否 | +| 上次保存后未生效的 section 会一并生效 | `running.boot_revisions` 与 `revisions` | 否 | +| 移除 vendor(同时移出 Tiers) | 工作副本与 base 的 vendor 差集 | 否(移除时已确认过) | + +运行时并发上限被重置这一条不进清单:前端不知道 Overview 是否调整过并发上限,服务端在保存后通过 `reset_runtime` 报告(`generations.py` 的 `_runtime_resets`),它出现在保存栏的结果明细里。旧实现把它写成无条件套话,`in_flight` 为 0 时也输出「进行中的请求:0 个」,这两句被删掉。 + +确认框列出字段级新旧值(「Timeout:300021 → 300023」)。vendors 按 vendor 名配对,列表型 section 按行键配对(Pricing 用 vendor + model,Model Mapping 用 pattern),配不上的行显示为「新增」或「移除」;超过 8 行时折叠在 `
` 里。密钥字段不进 diff,URL 中的 userinfo 打码。 + +这样做的依据:NN/g 指出「Do not use confirmation dialogs for routine actions」,并说明对例行操作反复确认会让用户养成不看就点的习惯 [1];WCAG 3.3.4 的理解文档明确「It is not the intent to require a confirmation for each save command」[4]。 + +```mermaid +flowchart LR + A[修改字段] --> B["点「保存」,冻结表单"] + B --> J{判定保存后果} + J -- 有后果 --> C[确认框:后果清单 + 字段级 diff] + J -. 无后果,直接提交 .-> P[提交并重载] + C -- 确认保存 --> P + P --> R[保存栏显示结果] + B -. 移除 .-> X[每次都弹确认框] + P -. 移除 .-> Y[结果只在顶部 Banner] + + classDef unchanged fill:#f3f4f6,stroke:#6b7280,color:#111827 + classDef added fill:#dcfce7,stroke:#16a34a,color:#14532d + classDef removed fill:#fee2e2,stroke:#dc2626,color:#7f1d1d,stroke-dasharray:5 5 + class A,B,P unchanged + class J,C,R added + class X,Y removed +``` + +图例:灰色为未变化,绿色为新增,红色虚线为删除。下图是同一流程的 Archify 版本,双主题 SVG,深浅模式自适应;交互版与图源见 [`docs/diagrams/config-save-flow/`](../diagrams/config-save-flow/)。 + +![Config 页保存流程:改造前后](../diagrams/config-save-flow/config-save-flow.svg) + +### 2. 操作后的焦点与落点 + +`rerender()` 在清空 DOM 之前记录焦点所在控件的「容器路径 + 控件角色」,重建后按同一键找回焦点。容器路径用现有的 `data-path`、`data-pill`、`data-vendor` 属性,角色取 `aria-label`、按钮文案或控件类名。找不到同一控件时依次退到:同一容器里的同类按钮(「编辑」变成「收起」时)、同一容器里的第一个可聚焦控件、当前激活的 pill。目标控件被禁用时跳过(排序到首行后「上移」禁用,焦点落到同行「下移」)。 + +需要显式落点的操作由调用方指定: + +| 操作 | 落点 | +| --- | --- | +| 列表「添加」 | 新行的编辑表单滚到视口中部,焦点在第一个输入框,新行高亮 2 秒 | +| 上移 / 下移 | 被移动行的同一颗按钮(按移动后的下标重映射) | +| 移除一行 | 同位置下一行的「编辑」;表已空时落到该表的「添加」 | +| 切换 section / vendor | 新的激活 pill | +| 密钥菜单「设置新值」 | 新值输入框(现状已如此);其余选项留在菜单上 | +| 确认框取消 | 打开它的控件(保存时为「保存」按钮) | +| Per-Model 添加 / 移除 | 「模型名」输入框 / 「添加」按钮 | +| 行内「下线 / 上线」(pricing) | 该行的同一颗按钮:按钮文案变化后,按它在同类按钮里的序号找回 | + +焦点原本由键盘获得时,重建后用 `data-focus-ring` 属性补画焦点环,因为脚本调用 `focus()` 不会触发浏览器的 `:focus-visible`。依据:Primer 焦点管理规范要求移除或重绘内容后「focus should return to a logical spot」,否则会回到 body、用户需要从头遍历整页 [9];WCAG 2.4.3 要求焦点顺序保留操作的连贯性 [5]。 + +表单卡 `.cfg-body` 继承全局 `.card` 的 400ms 入场动画与 hover 阴影,每次重建都重放。本次在 `config.css` 里用 `.card.cfg-body { animation: none }` 关掉,不改 `dashboard.py` 的全局规则,Overview 的卡片不受影响。整行点击展开时,若用户刚拖选了文字则不展开,保留表格文字可复制。 + +保存栏常驻时,页面设置 `scroll-padding-bottom: 120px`,键盘聚焦到页面底部的控件时浏览器会把它滚到保存栏上方,满足 WCAG 2.4.11 [6]。`:has()` 需要 Chrome 105、Safari 15.4、Firefox 121 以上;更老的浏览器只是失去这一条滚动补偿。 + +### 3. 破坏性操作:确认与撤销的分界 + +确认框与撤销按作用范围分工:范围超出当前可见对象时先确认,只影响当前列表里一行时不确认、给撤销。 + +| 操作 | 改造前 | 改造后 | +| --- | --- | --- | +| Vendors 子 pill 行「恢复默认」(重置全部 vendor) | 与 vendor 级同名同样式,无确认 | 改名「全部恢复默认」,降为透明底按钮;总是确认,写明「全部 9 个 vendor」与「其他 vendor 上未保存的修改也会丢弃」 | +| vendor 级「恢复默认」 | 无确认 | 该 vendor 有已保存的自定义值时确认,否则直接执行 | +| 其他 section 的「恢复默认」 | 无确认 | 该 section 已覆盖包内默认时确认,否则直接执行 | +| 移除 vendor | 无确认,无提示 | 确认,写明会移出 Tiers 链路及当前位次、已存密钥不删除;执行后保存栏给「撤销」 | +| 移除表格行 / Per-Model 行 | 「删除」,无确认,无撤销 | 动词改「移除」;不确认,保存栏给「撤销」(插回原位)。已保存的 pricing 行按 [Model Bind 设计](../arch/session-model-bind.md) 不可移除,只能下线 / 上线;新增的 pricing 行可移除并撤销 | +| 放弃修改、锁定、脏态刷新 | 原生 `window.confirm` | 页面内确认框,主按钮红色 | + +撤销只保留最近一次移除,撤销时只把被移除的对象插回原位,不回滚它之后的其它编辑;保存、放弃修改、锁定、重新加载或下一次结构性操作(添加、排序、重新添加 vendor)会清掉撤销入口,保存进行中「撤销」按钮禁用。「恢复默认」不提供撤销,因为它已经确认过,且保存前可用「放弃修改」整体找回。 + +依据:Raskin 的「Never use a warning when you mean undo」[2] 与 NN/g「Use a confirmation dialog before committing to actions with serious consequences」[1] 分别对应撤销和确认两侧;Primer 把 danger 按钮定义为「Used sparingly for destructive actions, typically prompt a confirmation dialog」[8];APG 建议不可逆操作的确认框把初始焦点放在「the least destructive action」[3],所以确认框打开时焦点在「取消」。四处原生 `window.confirm` 换成页面内确认框,是为了统一按钮文案、危险样式与焦点归还;破坏性确认使用 `alertdialog` 角色,正文与后果清单通过 `aria-describedby` 关联,焦点落在「取消」时读屏也会读出;不支持 `` 的环境仍回退到 `window.confirm` 并同步执行,Node 测试环境走这条分支。 + +工作副本在编辑、确认与撤销之间的状态: + +![Config 页编辑与撤销:工作副本的状态](../diagrams/config-edit-undo/config-edit-undo.svg) + +交互版与图源见 [`docs/diagrams/config-edit-undo/`](../diagrams/config-edit-undo/)。同一状态机的文本版: + +```mermaid +stateDiagram-v2 + [*] --> 未修改 + 未修改 --> 有未保存修改: 编辑字段、添加行或移除一行 + 有未保存修改 --> 先确认再执行: 全部恢复默认 / 移除 vendor + 先确认再执行 --> 有未保存修改: 取消,或确认后作用于工作副本 + 有未保存修改 --> 有未保存修改: 点「撤销」,插回原位 + 有未保存修改 --> 已保存: 保存成功 + 已保存 --> 未修改: 点「关闭」 + 已保存 --> 有未保存修改: 再次编辑 +``` + +### 4. label 列宽下限 + +`.cfg-row` 的列定义由 `calc(100% / 12)` 改为 `minmax(104px, calc(100% / 12))`。卡片内宽约 1250px 以上时(视口约 1314px 以上),label 列仍精确等于行宽的 1/12,与现状逐像素一致;更窄时 label 列停在 104px。104px 的来源:注册表里 label 最长 14 个 ASCII 字符(`test_spec_constraints` 钉住),实测最宽的「Fail Threshold」「Max Recovery」需要 91px,加 `.cfg-label` 的 6px 右内边距为 97px,再留 7px 余量。 + +视口 640px 以下,label 与 ⓘ 占第一行(ⓘ 紧跟 label),控件独占第二行;在 390px 宽下控件可用宽度从约 150px 增加到约 270px,说明气泡改为在该行下方展开并限宽,不再伸出视口。 + +label 被截断时,渲染完成后立即补 `title`(原先只在鼠标移入时懒补,键盘与触屏拿不到);表单行 ⓘ 的说明首行带上完整 label(「Timeout:单次请求超时」)。 + +实测效果(同一隔离实例、包内默认配置,分别加载改造前后的 `config.js` / `config.css`): + +| 视口 | label 列宽(前 → 后) | vendor 页截断数(前 → 后,共 22 个) | +| --- | --- | --- | +| 1440 | 111px → 111px | 0 → 0 | +| 1280 | 97px → 104px | 0 → 0 | +| 1024 | 76px → 104px | 11 → 0 | +| 768 | 55px → 104px | 15 → 0 | +| 390 | 23px → 整行 | 22 → 0 | + +### 5. Test plan + +| 风险 | 测试级别 | 断言 | +| --- | --- | --- | +| 保存结果位置迁移 | Node DOM harness(`test_config_js_rendering_under_node`) | 步骤 6:结果文案出现在 `.cfg-savebar`,顶部 Banner 不含「已保存」;无后果的保存不调用 `confirm` | +| 结果态可关闭 | 同上 | 步骤 7:重载成功后保存栏可见且含「已保存并生效」,点「关闭」后隐藏 | +| Google Secret 单独保存文案 | 同上 | 步骤 9:读取位置从 Banner 改为保存栏,断言内容不变 | +| 行级移除可撤销 | 同上 | 步骤 1:移除不调用 `confirm`;保存栏出现「撤销」;撤销后行数恢复、`isDirty()` 为 false | +| 后果清单与字段 diff | 纯函数 harness(`test_config_js_pure_helpers_under_node`) | 新增 `saveImpact`、`changedRows` 用例:无后果返回空数组;`in_flight > 0`、clear、地址变更各产生对应条目;Pricing 按 vendor + model 配对,删除一行输出 `removed` | +| 焦点找回与新行定位 | Node DOM harness + 隔离实例浏览器回归 | harness:排序后焦点落在被移动行的同一颗按钮,「添加」后焦点落在新行自己的编辑表单;浏览器回归:开关分组、Tiers 勾选与排序、Model Mapping 排序与展开、密钥菜单、Per-Model 添加、切换 pill、确认框取消与结果关闭后焦点都不落回 body | +| 撤销 | Node DOM harness | 行级移除后保存栏出现「撤销」,撤销后行数与脏态恢复;Per-Model 行移除后「撤销」恢复该模型上限;移除 vendor 后撤销把它插回 vendors 与 tiers 原位,期间重新添加会清掉撤销入口 | +| label 列宽 | 隔离实例浏览器回归 | 1024 / 768 / 390 下 vendor 页截断数为 0;1440 下 label 列仍为 111px | + +`test_dashboard_config_tab.py` 现有 11 个 DOM 场景中,随本设计调整断言的只有上表前 4 条,其余场景断言不变。 + +## Drawbacks + +- 保存栏在结果态常驻,直到用户关闭或再次编辑。习惯了「保存完自动收起」的用户需要多点一次「关闭」。 +- 焦点找回依赖控件角色的启发式匹配:两个同类按钮在同一容器里时,按顺序取第一个可聚焦的。表格行内两个以上同名按钮的场景目前不存在,后续新增时需要补显式落点。 +- 撤销只有一级,连续移除两行只能撤销后一次;「恢复默认」不可撤销。 +- `config.js` 增加约 420 行(1290 → 1713),主要是确认框、字段 diff 与焦点管理。没有引入依赖,仍是 vanilla ES2017。 +- 运行时并发上限重置无法在保存前提示,只能在结果明细里事后报告。 +- 961 到 1313px 视口之间,label 列不再精确等于行宽 1/12(固定 104px),这是对现有表单规范的有意偏离。 + +## Alternatives + +- **toast 显示保存结果**:否决。Primer 的可访问性规范写明「Toasts pose significant accessibility concerns and are not recommended for use」[10],且 toast 自动消失,失败原因可能来不及读。 +- **结果仍在顶部,保存后把页面滚回顶部**:否决。用户刚编辑的位置会丢失,长页面上来回跳动。 +- **保留每次必弹的确认框,只补字段 diff**:否决。WCAG 3.3.4 明确不要求每次保存都确认 [4];NN/g 认为例行确认会被习惯性跳过 [1]。字段 diff 在有后果时更值得看。 +- **所有破坏性操作都弹确认,不做撤销**:否决。行级移除是高频小操作,每次确认会让确认框失去提醒作用 [1][2]。 +- **按 section 增量更新 DOM,从根本上避免整页重建**:本期不做。1290 行文件与 Node DOM 测试桩都建立在整页重建之上,改动面远大于焦点找回,而焦点找回已覆盖可观测的问题。 +- **label 列按断点切换比例(如 1440 以下改 1/8)**:否决。仍会在某个宽度截断,下限方案只在截断即将发生时介入。 + +## Unresolved Questions + +None. 与本设计相关的两条规范裁决已由负责人确定:label 列在 1/12 之外加 104px 下限、视口 640px 以下 label 与控件分行;确认框按保存后果触发。 + +## References + +1. J. Nielsen, "Confirmation Dialogs Can Prevent User Errors — If Not Overused," Nielsen Norman Group, Feb. 2018. [Online]. Available: https://www.nngroup.com/articles/confirmation-dialog/ +2. A. Raskin, "Never Use a Warning When you Mean Undo," *A List Apart*, no. 241, Jul. 2007. [Online]. Available: https://alistapart.com/article/neveruseawarning/ +3. W3C WAI, "Dialog (Modal) Pattern" and "Alert Pattern," *ARIA Authoring Practices Guide*. [Online]. Available: https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/ ; https://www.w3.org/WAI/ARIA/apg/patterns/alert/ +4. W3C WAI, "Understanding SC 3.3.4: Error Prevention (Legal, Financial, Data)," *WCAG 2.2 Understanding*. [Online]. Available: https://www.w3.org/WAI/WCAG22/Understanding/error-prevention-legal-financial-data.html +5. W3C WAI, "Understanding SC 2.4.3: Focus Order," *WCAG 2.2 Understanding*. [Online]. Available: https://www.w3.org/WAI/WCAG22/Understanding/focus-order.html +6. W3C WAI, "Understanding SC 2.4.11: Focus Not Obscured (Minimum)," *WCAG 2.2 Understanding*. [Online]. Available: https://www.w3.org/WAI/WCAG22/Understanding/focus-not-obscured-minimum.html +7. Atlassian, "Flag — Usage," *Atlassian Design System*. [Online]. Available: https://atlassian.design/components/flag/usage +8. GitHub, "Button," *Primer Product UI*. [Online]. Available: https://primer.style/product/components/button +9. GitHub, "Focus management," *Primer Accessibility*. [Online]. Available: https://primer.style/accessibility/design-guidance/focus-management +10. GitHub, "Accessible notifications and messages," *Primer Accessibility*. [Online]. Available: https://primer.style/accessibility/patterns/accessible-notifications-and-messages/ +11. W3C WAI, "Understanding SC 4.1.3: Status Messages," *WCAG 2.2 Understanding*. [Online]. Available: https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html diff --git a/docs/diagrams/config-edit-undo/config-edit-undo.html b/docs/diagrams/config-edit-undo/config-edit-undo.html new file mode 100644 index 00000000..b248d0e5 --- /dev/null +++ b/docs/diagrams/config-edit-undo/config-edit-undo.html @@ -0,0 +1,13708 @@ + + + + + + + + Config 页编辑与撤销:工作副本的状态 + + + + + + + + +
+ +
+
+
+

Config 页编辑与撤销:工作副本的状态

+
+
+ + + + +
+ + Config 页编辑与撤销:工作副本的状态 + 由 Archify 生成的生命周期图。 + + + + + + + + + + + + + + + + + + + + + + + + 工作副本 + 需要先确认的大范围操作 + + + + + + + + + + + + + + + + + + + + + + + + + + 未修改 · 保存栏隐藏 · 工作副本 · 起点 + + + + + 01 + 未修改 + 保存栏隐藏 + 起点 + + + + 有未保存修改 · 移除一行后带「撤销」 · 工作副本 · 可保存 + + + + 02 + 有未保存修改 + 移除一行后带「撤销」 + 可保存 + + + + 先确认再执行 · 全部恢复默认 / 移除 vendor · 需要先确认的大范围操作 · 新增 + + + + 先确认再执行 + 全部恢复默认 / 移除 vendor + 新增 + + + + 已保存 · 保存栏显示结果 · 工作副本 · 新增:结果在底部 + + + + 03 + 已保存 + 保存栏显示结果 + 新增:结果在底部 + + + + + + 编辑字段、添加行或移除一行 + + + + 点大范围操作 + + + + 取消,或确认后作用于工作副本 + + + + 保存成功 + + + + 关闭或再次编辑 + + + + + 图例 + + + 起点 + + + + 有未保存修改 + + + + 先确认再执行 + + + + 已保存 + + + +

+ + + + + + + + + +
+ + + +
+ + + + diff --git a/docs/diagrams/config-edit-undo/config-edit-undo.json b/docs/diagrams/config-edit-undo/config-edit-undo.json new file mode 100644 index 00000000..93d0e2a4 --- /dev/null +++ b/docs/diagrams/config-edit-undo/config-edit-undo.json @@ -0,0 +1,144 @@ +{ + "schema_version": 2, + "diagram_type": "lifecycle", + "meta": { + "title": "Config 页编辑与撤销:工作副本的状态", + "locale": "zh-CN", + "animation": "none", + "quality_profile": "showcase", + "output": "config-edit-undo.html", + "legend": { + "entries": { + "start": { + "label": "起点" + }, + "active": { + "label": "有未保存修改" + }, + "decision": { + "label": "先确认再执行" + }, + "success": { + "label": "已保存" + } + } + } + }, + "lanes": [ + { + "id": "main", + "label": "工作副本" + }, + { + "id": "confirm", + "label": "需要先确认的大范围操作" + } + ], + "states": [ + { + "id": "clean", + "type": "start", + "label": "未修改", + "sublabel": "保存栏隐藏", + "lane": "main", + "col": 0, + "step": "01", + "tag": "起点" + }, + { + "id": "dirty", + "type": "active", + "label": "有未保存修改", + "sublabel": "移除一行后带「撤销」", + "lane": "main", + "col": 1, + "step": "02", + "tag": "可保存" + }, + { + "id": "ask", + "type": "decision", + "label": "先确认再执行", + "sublabel": "全部恢复默认 / 移除 vendor", + "lane": "confirm", + "col": 0, + "tag": "新增" + }, + { + "id": "done", + "type": "success", + "label": "已保存", + "sublabel": "保存栏显示结果", + "lane": "main", + "col": 2, + "step": "03", + "tag": "新增:结果在底部" + } + ], + "transitions": [ + { + "id": "t-edit", + "from": "clean", + "to": "dirty", + "label": "编辑字段、添加行或移除一行" + }, + { + "id": "t-ask", + "from": "dirty", + "to": "ask", + "variant": "emphasis", + "label": "点大范围操作", + "route": "auto" + }, + { + "id": "t-back", + "from": "ask", + "to": "dirty", + "label": "取消,或确认后作用于工作副本", + "route": "auto" + }, + { + "id": "t-save", + "from": "dirty", + "to": "done", + "variant": "emphasis", + "label": "保存成功" + }, + { + "id": "t-close", + "from": "done", + "to": "clean", + "label": "关闭或再次编辑", + "route": "top-channel" + } + ], + "cards": [ + { + "dot": "cyan", + "title": "确认与撤销的分界", + "items": [ + "范围超出当前可见对象(全部 vendor、整个 vendor)时先弹确认框", + "只影响当前列表里的一行时不弹确认,保存栏给「撤销」", + "全部恢复默认、移除 vendor、放弃修改、锁定共用同一个页面内确认框" + ] + }, + { + "dot": "amber", + "title": "撤销的边界", + "items": [ + "只保留最近一次移除", + "撤销把对象插回原位,不影响其后的其它编辑", + "不覆盖「恢复默认」:它有确认,已保存的值可用「放弃修改」找回" + ] + }, + { + "dot": "rose", + "title": "重绘后焦点落在哪里", + "items": [ + "添加:新行滚入视口,焦点在第一个输入框", + "排序:同一行的同一颗按钮,按钮禁用时落到同行另一颗", + "展开:该行的「收起」;切换 section:新的激活项" + ] + } + ] +} \ No newline at end of file diff --git a/docs/diagrams/config-edit-undo/config-edit-undo.svg b/docs/diagrams/config-edit-undo/config-edit-undo.svg new file mode 100644 index 00000000..96c7a7c9 --- /dev/null +++ b/docs/diagrams/config-edit-undo/config-edit-undo.svg @@ -0,0 +1,561 @@ + + + Config 页编辑与撤销:工作副本的状态 + 由 Archify 生成的生命周期图。 + + + + + + + + + + + + + + + + + + + + + + + + 工作副本 + 需要先确认的大范围操作 + + + + + + + + + + + + + + + + + + + + + + + + + + 未修改 · 保存栏隐藏 · 工作副本 · 起点 + + + + + 01 + 未修改 + 保存栏隐藏 + 起点 + + + + 有未保存修改 · 移除一行后带「撤销」 · 工作副本 · 可保存 + + + + 02 + 有未保存修改 + 移除一行后带「撤销」 + 可保存 + + + + 先确认再执行 · 全部恢复默认 / 移除 vendor · 需要先确认的大范围操作 · 新增 + + + + 先确认再执行 + 全部恢复默认 / 移除 vendor + 新增 + + + + 已保存 · 保存栏显示结果 · 工作副本 · 新增:结果在底部 + + + + 03 + 已保存 + 保存栏显示结果 + 新增:结果在底部 + + + + + + 编辑字段、添加行或移除一行 + + + + 点大范围操作 + + + + 取消,或确认后作用于工作副本 + + + + 保存成功 + + + + 关闭或再次编辑 + + + + + 图例 + + + 起点 + + + + 有未保存修改 + + + + 先确认再执行 + + + + 已保存 + + + \ No newline at end of file diff --git a/docs/diagrams/config-edit-undo/config-edit-undo.visual-check.json b/docs/diagrams/config-edit-undo/config-edit-undo.visual-check.json new file mode 100644 index 00000000..9e0e9f1b --- /dev/null +++ b/docs/diagrams/config-edit-undo/config-edit-undo.visual-check.json @@ -0,0 +1,930 @@ +{ + "schemaVersion": 1, + "ok": true, + "command": "visual-check", + "evidenceKind": "automated-browser", + "status": "pass", + "visualReview": "pending", + "provenance": "current", + "deliveryReceiptId": "4747bb0d-dd91-4d6d-b068-889639f24739", + "artifact": { + "path": "/private/tmp/claude-501/-Users-cm-huang-orca-workspaces-coding-proxy-blenny/fd640297-2c00-4aba-b756-f33398d52a18/scratchpad/cfg-design/diagrams/lifecycle-config-edit-undo-20261127-144023/config-edit-undo.html", + "sha256": "c8bb934be7baa0e75bbd1dde9cc9fba2defbfb6e427f328556ae7158ce19b774", + "bytes": 752622 + }, + "state": { + "detail": "read", + "motion": "still" + }, + "chrome": { + "status": "available", + "executable": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" + }, + "diagnostics": [], + "containment": { + "status": "pass", + "policy": "fit-or-reader-declared-readable-vertical-scroll", + "viewports": [ + { + "width": 1440, + "height": 900, + "theme": "light", + "innerWidth": 1440, + "innerHeight": 900, + "scrollWidth": 1440, + "scrollHeight": 900, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": "intrinsic-height", + "ok": true, + "readerWidth": 1376, + "diagramWidth": 1346, + "pageComposition": { + "bodyPaddingPx": 12, + "headerPx": 52, + "diagramChromePx": 78, + "svgPx": 690, + "cardsPx": 0, + "viewBoxHeight": 400 + }, + "viewBoxWidth": 780, + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏隐藏", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "clean" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + }, + { + "width": 1600, + "height": 1000, + "theme": "light", + "innerWidth": 1600, + "innerHeight": 1000, + "scrollWidth": 1600, + "scrollHeight": 1000, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": "intrinsic-height", + "ok": true, + "readerWidth": 1536, + "diagramWidth": 1506, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 60, + "diagramChromePx": 84, + "svgPx": 772, + "cardsPx": 0, + "viewBoxHeight": 400 + }, + "viewBoxWidth": 780, + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏隐藏", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "clean" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + }, + { + "width": 1920, + "height": 1080, + "theme": "light", + "innerWidth": 1920, + "innerHeight": 1080, + "scrollWidth": 1920, + "scrollHeight": 1080, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": "intrinsic-height", + "ok": true, + "readerWidth": 1707, + "diagramWidth": 1677, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 60, + "diagramChromePx": 84, + "svgPx": 860, + "cardsPx": 0, + "viewBoxHeight": 400 + }, + "viewBoxWidth": 780, + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏隐藏", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "clean" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + }, + { + "width": 2048, + "height": 1320, + "theme": "light", + "innerWidth": 2048, + "innerHeight": 1320, + "scrollWidth": 2048, + "scrollHeight": 1320, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": "intrinsic-height", + "ok": true, + "readerWidth": 1920, + "diagramWidth": 1870, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 68, + "diagramChromePx": 94, + "svgPx": 959, + "cardsPx": 0, + "viewBoxHeight": 400 + }, + "viewBoxWidth": 780, + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏隐藏", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "clean" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 44, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + } + ] + }, + "themeStates": { + "status": "pass", + "viewports": [ + { + "width": 1440, + "height": 900, + "requestedTheme": "light", + "resolvedTheme": "light", + "ok": true + }, + { + "width": 1600, + "height": 1000, + "requestedTheme": "light", + "resolvedTheme": "light", + "ok": true + }, + { + "width": 1920, + "height": 1080, + "requestedTheme": "light", + "resolvedTheme": "light", + "ok": true + }, + { + "width": 2048, + "height": 1320, + "requestedTheme": "light", + "resolvedTheme": "light", + "ok": true + }, + { + "width": 1440, + "height": 900, + "requestedTheme": "dark", + "resolvedTheme": "dark", + "ok": true + }, + { + "width": 2048, + "height": 1320, + "requestedTheme": "dark", + "resolvedTheme": "dark", + "ok": true + } + ] + }, + "readability": { + "status": "pass", + "minimumProjectedNodeTextPx": 6, + "viewports": [ + { + "width": 1440, + "height": 900, + "theme": "light", + "innerWidth": 1440, + "innerHeight": 900, + "scrollWidth": 1440, + "scrollHeight": 900, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": "intrinsic-height", + "ok": true, + "readerWidth": 1376, + "diagramWidth": 1346, + "pageComposition": { + "bodyPaddingPx": 12, + "headerPx": 52, + "diagramChromePx": 78, + "svgPx": 690, + "cardsPx": 0, + "viewBoxHeight": 400 + }, + "viewBoxWidth": 780, + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏隐藏", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "clean" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + }, + { + "width": 1600, + "height": 1000, + "theme": "light", + "innerWidth": 1600, + "innerHeight": 1000, + "scrollWidth": 1600, + "scrollHeight": 1000, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": "intrinsic-height", + "ok": true, + "readerWidth": 1536, + "diagramWidth": 1506, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 60, + "diagramChromePx": 84, + "svgPx": 772, + "cardsPx": 0, + "viewBoxHeight": 400 + }, + "viewBoxWidth": 780, + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏隐藏", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "clean" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + }, + { + "width": 1920, + "height": 1080, + "theme": "light", + "innerWidth": 1920, + "innerHeight": 1080, + "scrollWidth": 1920, + "scrollHeight": 1080, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": "intrinsic-height", + "ok": true, + "readerWidth": 1707, + "diagramWidth": 1677, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 60, + "diagramChromePx": 84, + "svgPx": 860, + "cardsPx": 0, + "viewBoxHeight": 400 + }, + "viewBoxWidth": 780, + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏隐藏", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "clean" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + }, + { + "width": 2048, + "height": 1320, + "theme": "light", + "innerWidth": 2048, + "innerHeight": 1320, + "scrollWidth": 2048, + "scrollHeight": 1320, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": "intrinsic-height", + "ok": true, + "readerWidth": 1920, + "diagramWidth": 1870, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 68, + "diagramChromePx": 94, + "svgPx": 959, + "cardsPx": 0, + "viewBoxHeight": 400 + }, + "viewBoxWidth": 780, + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏隐藏", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "clean" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 44, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + } + ] + }, + "viewerChrome": { + "status": "pass", + "viewports": [ + { + "width": 1440, + "height": 900, + "theme": "light", + "innerWidth": 1440, + "innerHeight": 900, + "scrollWidth": 1440, + "scrollHeight": 900, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": "intrinsic-height", + "ok": true, + "readerWidth": 1376, + "diagramWidth": 1346, + "pageComposition": { + "bodyPaddingPx": 12, + "headerPx": 52, + "diagramChromePx": 78, + "svgPx": 690, + "cardsPx": 0, + "viewBoxHeight": 400 + }, + "viewBoxWidth": 780, + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏隐藏", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "clean" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + }, + { + "width": 1600, + "height": 1000, + "theme": "light", + "innerWidth": 1600, + "innerHeight": 1000, + "scrollWidth": 1600, + "scrollHeight": 1000, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": "intrinsic-height", + "ok": true, + "readerWidth": 1536, + "diagramWidth": 1506, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 60, + "diagramChromePx": 84, + "svgPx": 772, + "cardsPx": 0, + "viewBoxHeight": 400 + }, + "viewBoxWidth": 780, + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏隐藏", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "clean" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + }, + { + "width": 1920, + "height": 1080, + "theme": "light", + "innerWidth": 1920, + "innerHeight": 1080, + "scrollWidth": 1920, + "scrollHeight": 1080, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": "intrinsic-height", + "ok": true, + "readerWidth": 1707, + "diagramWidth": 1677, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 60, + "diagramChromePx": 84, + "svgPx": 860, + "cardsPx": 0, + "viewBoxHeight": 400 + }, + "viewBoxWidth": 780, + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏隐藏", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "clean" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + }, + { + "width": 2048, + "height": 1320, + "theme": "light", + "innerWidth": 2048, + "innerHeight": 1320, + "scrollWidth": 2048, + "scrollHeight": 1320, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": "intrinsic-height", + "ok": true, + "readerWidth": 1920, + "diagramWidth": 1870, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 68, + "diagramChromePx": 94, + "svgPx": 959, + "cardsPx": 0, + "viewBoxHeight": 400 + }, + "viewBoxWidth": 780, + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏隐藏", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "clean" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 44, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + } + ] + }, + "captures": { + "status": "pass", + "screenshots": [ + { + "width": 1440, + "height": 900, + "theme": "light", + "innerWidth": 1440, + "innerHeight": 900, + "scrollWidth": 1440, + "scrollHeight": 900, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": "intrinsic-height", + "ok": true, + "readerWidth": 1376, + "diagramWidth": 1346, + "pageComposition": { + "bodyPaddingPx": 12, + "headerPx": 52, + "diagramChromePx": 78, + "svgPx": 690, + "cardsPx": 0, + "viewBoxHeight": 400 + }, + "viewBoxWidth": 780, + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏隐藏", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "clean" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light", + "file": "config-edit-undo.visual-check.1440x900.light.png" + }, + { + "width": 1440, + "height": 900, + "theme": "dark", + "innerWidth": 1440, + "innerHeight": 900, + "scrollWidth": 1440, + "scrollHeight": 900, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": "intrinsic-height", + "ok": true, + "readerWidth": 1376, + "diagramWidth": 1346, + "pageComposition": { + "bodyPaddingPx": 12, + "headerPx": 52, + "diagramChromePx": 78, + "svgPx": 690, + "cardsPx": 0, + "viewBoxHeight": 400 + }, + "viewBoxWidth": 780, + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏隐藏", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "clean" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "dark", + "file": "config-edit-undo.visual-check.1440x900.dark.png" + }, + { + "width": 2048, + "height": 1320, + "theme": "light", + "innerWidth": 2048, + "innerHeight": 1320, + "scrollWidth": 2048, + "scrollHeight": 1320, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": "intrinsic-height", + "ok": true, + "readerWidth": 1920, + "diagramWidth": 1870, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 68, + "diagramChromePx": 94, + "svgPx": 959, + "cardsPx": 0, + "viewBoxHeight": 400 + }, + "viewBoxWidth": 780, + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏隐藏", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "clean" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 44, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light", + "file": "config-edit-undo.visual-check.2048x1320.light.png" + }, + { + "width": 2048, + "height": 1320, + "theme": "dark", + "innerWidth": 2048, + "innerHeight": 1320, + "scrollWidth": 2048, + "scrollHeight": 1320, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": "intrinsic-height", + "ok": true, + "readerWidth": 1920, + "diagramWidth": 1870, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 68, + "diagramChromePx": 94, + "svgPx": 959, + "cardsPx": 0, + "viewBoxHeight": 400 + }, + "viewBoxWidth": 780, + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏隐藏", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "clean" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 44, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "dark", + "file": "config-edit-undo.visual-check.2048x1320.dark.png" + } + ], + "contactSheet": "config-edit-undo.visual-check.html" + }, + "sidecars": { + "directory": "/private/tmp/claude-501/-Users-cm-huang-orca-workspaces-coding-proxy-blenny/fd640297-2c00-4aba-b756-f33398d52a18/scratchpad/cfg-design/diagrams/lifecycle-config-edit-undo-20261127-144023/visual-check-r4", + "receipt": "config-edit-undo.visual-check.json", + "contactSheet": "config-edit-undo.visual-check.html", + "files": [ + { + "sha256": "836b83d07d81d53bf3462a0193d6d1a3bee26d93cefdb8a1d07c9dd349492374", + "bytes": 1940, + "file": "config-edit-undo.visual-check.html" + }, + { + "sha256": "cf20667de41fee24b2e29dba3ed2e545c45c43cf3320ccff987c60c8e5819bf3", + "bytes": 121469, + "file": "config-edit-undo.visual-check.1440x900.light.png" + }, + { + "sha256": "6556230b2da45b5f89e41900a183ebcedd5ffbab43c505394cde0fd42cfb30f1", + "bytes": 127707, + "file": "config-edit-undo.visual-check.1440x900.dark.png" + }, + { + "sha256": "639facba08627397d894c7f318db8198a9014d67a65db20be07d7109159a95a9", + "bytes": 205972, + "file": "config-edit-undo.visual-check.2048x1320.light.png" + }, + { + "sha256": "9e122faeb2354a8e50b941b503d8a920dbb6e22526831308257029e95bcd712e", + "bytes": 217537, + "file": "config-edit-undo.visual-check.2048x1320.dark.png" + } + ] + } +} diff --git a/docs/diagrams/config-save-flow/config-save-flow.html b/docs/diagrams/config-save-flow/config-save-flow.html new file mode 100644 index 00000000..ef30591b --- /dev/null +++ b/docs/diagrams/config-save-flow/config-save-flow.html @@ -0,0 +1,13765 @@ + + + + + + + + Config 页保存流程:改造前后 + + + + + + + + +
+ +
+
+
+

Config 页保存流程:改造前后

+
+
+ + + + +
+ + Config 页保存流程:改造前后 + 由 Archify 生成的工作流图。 + + + + + + + + + + + + + + + + + + + + + + + + + 01 / 保存流程 + + + + EX / 移除的旧行为 + + + + + 发起保存 + + + 是否需要确认 + + + 提交与结果 + + + + 新增:有后果才弹 + + 新增:结果进保存栏 + + + + + + + + + + + + + + + 修改字段 · 保存栏列出待保存范围 · 保存流程 › 发起保存 + + + + 修改字段 + 保存栏列出待保存范围 + + + + 点「保存」,冻结表单 · 读取 /api/status · 保存流程 › 发起保存 + + + + 点「保存」,冻结表单 + 读取 /api/status + + + + 判定保存后果 · 密钥 · 在途请求 · 状态重置 · 保存流程 › 新增:有后果才弹 › 是否需要确认 · 新增 + + + + 判定保存后果 + 密钥 · 在途请求 · 状态重置 + 新增 + + + + 确认框 · 后果清单 + 字段级 diff · 保存流程 › 新增:有后果才弹 › 是否需要确认 · 仅在有后果时 + + + + 确认框 + 后果清单 + 字段级 diff + 仅在有后果时 + + + + 提交并重载 · PUT /api/config · 保存流程 › 提交与结果 + + + + 提交并重载 + PUT /api/config + + + + 保存栏显示结果 · 成功 / 待重启 / 失败 · 保存流程 › 新增:结果进保存栏 › 提交与结果 · 新增 + + + + 保存栏显示结果 + 成功 / 待重启 / 失败 + 新增 + + + + 每次都弹确认框 · 只列 section 名与套话 · 移除的旧行为 › 是否需要确认 · 移除 + + + + 每次都弹确认框 + 只列 section 名与套话 + 移除 + + + + 结果只在顶部 Banner · 下滚后看不到 · 移除的旧行为 › 提交与结果 · 移除 + + + + 结果只在顶部 Banner + 下滚后看不到 + 移除 + + + + + + + + + 确认保存 + + + + + 有后果 + + + + 无后果,直接提交 + + + + + 保存完成 + + + + + 图例 + + + 页面(config.js) + + + + 服务端 API + + + + 判断与移除的旧行为 + + + +

+ + + + + + + + + +
+ + + +
+ + + + diff --git a/docs/diagrams/config-save-flow/config-save-flow.json b/docs/diagrams/config-save-flow/config-save-flow.json new file mode 100644 index 00000000..0aa75e02 --- /dev/null +++ b/docs/diagrams/config-save-flow/config-save-flow.json @@ -0,0 +1,253 @@ +{ + "schema_version": 2, + "diagram_type": "workflow", + "meta": { + "title": "Config 页保存流程:改造前后", + "locale": "zh-CN", + "animation": "none", + "quality_profile": "showcase", + "output": "config-save-flow.html", + "legend": { + "entries": { + "frontend": { + "label": "页面(config.js)" + }, + "backend": { + "label": "服务端 API" + }, + "security": { + "label": "判断与移除的旧行为" + } + } + } + }, + "lanes": [ + { + "id": "main", + "label": "保存流程" + }, + { + "id": "old", + "label": "移除的旧行为", + "variant": "exception" + } + ], + "phases": [ + { + "id": "start", + "label": "发起保存", + "fromCol": 0, + "toCol": 1 + }, + { + "id": "confirm", + "label": "是否需要确认", + "fromCol": 2, + "toCol": 3, + "variant": "emphasis" + }, + { + "id": "commit", + "label": "提交与结果", + "fromCol": 4, + "toCol": 5 + } + ], + "groups": [ + { + "id": "g-judge", + "label": "新增:有后果才弹", + "lane": "main", + "fromCol": 2, + "toCol": 3, + "variant": "emphasis" + }, + { + "id": "g-result", + "label": "新增:结果进保存栏", + "lane": "main", + "fromCol": 5, + "toCol": 5, + "variant": "emphasis" + } + ], + "mainPath": [ + "edit", + "click", + "judge", + "confirm", + "put", + "result" + ], + "nodes": [ + { + "id": "edit", + "lane": "main", + "col": 0, + "type": "frontend", + "label": "修改字段", + "sublabel": "保存栏列出待保存范围", + "width": 144 + }, + { + "id": "click", + "lane": "main", + "col": 1, + "type": "frontend", + "label": "点「保存」,冻结表单", + "sublabel": "读取 /api/status", + "width": 144 + }, + { + "id": "judge", + "lane": "main", + "col": 2, + "type": "security", + "label": "判定保存后果", + "sublabel": "密钥 · 在途请求 · 状态重置", + "tag": "新增", + "width": 144 + }, + { + "id": "confirm", + "lane": "main", + "col": 3, + "type": "frontend", + "label": "确认框", + "sublabel": "后果清单 + 字段级 diff", + "tag": "仅在有后果时", + "width": 144 + }, + { + "id": "put", + "lane": "main", + "col": 4, + "type": "backend", + "label": "提交并重载", + "sublabel": "PUT /api/config", + "width": 144 + }, + { + "id": "result", + "lane": "main", + "col": 5, + "type": "frontend", + "label": "保存栏显示结果", + "sublabel": "成功 / 待重启 / 失败", + "tag": "新增", + "width": 144 + }, + { + "id": "always", + "lane": "old", + "col": 3, + "type": "security", + "label": "每次都弹确认框", + "sublabel": "只列 section 名与套话", + "tag": "移除", + "width": 144 + }, + { + "id": "banner", + "lane": "old", + "col": 5, + "type": "security", + "label": "结果只在顶部 Banner", + "sublabel": "下滚后看不到", + "tag": "移除", + "width": 144 + } + ], + "edges": [ + { + "id": "e-edit-click", + "from": "edit", + "to": "click", + "variant": "default" + }, + { + "id": "e-click-judge", + "from": "click", + "to": "judge", + "variant": "emphasis" + }, + { + "id": "e-judge-confirm", + "from": "judge", + "to": "confirm", + "variant": "emphasis", + "label": "有后果" + }, + { + "id": "e-judge-put", + "from": "judge", + "to": "put", + "variant": "dashed", + "role": "branch", + "label": "无后果,直接提交" + }, + { + "id": "e-confirm-put", + "from": "confirm", + "to": "put", + "variant": "emphasis", + "label": "确认保存" + }, + { + "id": "e-put-result", + "from": "put", + "to": "result", + "variant": "emphasis", + "label": "保存完成" + }, + { + "id": "e-click-always", + "from": "click", + "to": "always", + "variant": "dashed", + "role": "error" + }, + { + "id": "e-always-put", + "from": "always", + "to": "put", + "variant": "dashed", + "role": "error" + }, + { + "id": "e-put-banner", + "from": "put", + "to": "banner", + "variant": "dashed", + "role": "error" + } + ], + "cards": [ + { + "dot": "cyan", + "title": "怎么看这张图", + "items": [ + "「保存流程」泳道里没有「新增」标记的步骤,改造前后都存在", + "「判定保存后果」「保存栏显示结果」是本次加入的", + "「移除的旧行为」泳道与虚线边是本次去掉的" + ] + }, + { + "dot": "amber", + "title": "确认框何时出现", + "items": [ + "后果清单为空时不弹,直接提交", + "清单含密钥写入或清空、在途请求、运行时状态重置、移除 vendor", + "确认框列出每个字段的新旧值,破坏性后果用红色主按钮" + ] + }, + { + "dot": "rose", + "title": "无法提前预判的后果", + "items": [ + "运行时并发上限被重置只能由服务端在保存后报告", + "这条信息出现在保存栏的结果明细里" + ] + } + ] +} \ No newline at end of file diff --git a/docs/diagrams/config-save-flow/config-save-flow.svg b/docs/diagrams/config-save-flow/config-save-flow.svg new file mode 100644 index 00000000..7563169b --- /dev/null +++ b/docs/diagrams/config-save-flow/config-save-flow.svg @@ -0,0 +1,619 @@ + + + Config 页保存流程:改造前后 + 由 Archify 生成的工作流图。 + + + + + + + + + + + + + + + + + + + + + + + + + 01 / 保存流程 + + + + EX / 移除的旧行为 + + + + + 发起保存 + + + 是否需要确认 + + + 提交与结果 + + + + 新增:有后果才弹 + + 新增:结果进保存栏 + + + + + + + + + + + + + + + 修改字段 · 保存栏列出待保存范围 · 保存流程 › 发起保存 + + + + 修改字段 + 保存栏列出待保存范围 + + + + 点「保存」,冻结表单 · 读取 /api/status · 保存流程 › 发起保存 + + + + 点「保存」,冻结表单 + 读取 /api/status + + + + 判定保存后果 · 密钥 · 在途请求 · 状态重置 · 保存流程 › 新增:有后果才弹 › 是否需要确认 · 新增 + + + + 判定保存后果 + 密钥 · 在途请求 · 状态重置 + 新增 + + + + 确认框 · 后果清单 + 字段级 diff · 保存流程 › 新增:有后果才弹 › 是否需要确认 · 仅在有后果时 + + + + 确认框 + 后果清单 + 字段级 diff + 仅在有后果时 + + + + 提交并重载 · PUT /api/config · 保存流程 › 提交与结果 + + + + 提交并重载 + PUT /api/config + + + + 保存栏显示结果 · 成功 / 待重启 / 失败 · 保存流程 › 新增:结果进保存栏 › 提交与结果 · 新增 + + + + 保存栏显示结果 + 成功 / 待重启 / 失败 + 新增 + + + + 每次都弹确认框 · 只列 section 名与套话 · 移除的旧行为 › 是否需要确认 · 移除 + + + + 每次都弹确认框 + 只列 section 名与套话 + 移除 + + + + 结果只在顶部 Banner · 下滚后看不到 · 移除的旧行为 › 提交与结果 · 移除 + + + + 结果只在顶部 Banner + 下滚后看不到 + 移除 + + + + + + + + + 确认保存 + + + + + 有后果 + + + + 无后果,直接提交 + + + + + 保存完成 + + + + + 图例 + + + 页面(config.js) + + + + 服务端 API + + + + 判断与移除的旧行为 + + + \ No newline at end of file diff --git a/docs/diagrams/config-save-flow/config-save-flow.visual-check.json b/docs/diagrams/config-save-flow/config-save-flow.visual-check.json new file mode 100644 index 00000000..33720b7c --- /dev/null +++ b/docs/diagrams/config-save-flow/config-save-flow.visual-check.json @@ -0,0 +1,1410 @@ +{ + "schemaVersion": 1, + "ok": true, + "command": "visual-check", + "evidenceKind": "automated-browser", + "status": "pass", + "visualReview": "pending", + "provenance": "current", + "deliveryReceiptId": "3d6270d4-923f-42b3-9ddc-23daa321e5eb", + "artifact": { + "path": "/private/tmp/claude-501/-Users-cm-huang-orca-workspaces-coding-proxy-blenny/fd640297-2c00-4aba-b756-f33398d52a18/scratchpad/cfg-design/diagrams/workflow-config-save-flow-20261127-144023/config-save-flow.html", + "sha256": "94b7817c58030496d8c5ebe14a66da9a8efb83183b11027485c71383cf14a74e", + "bytes": 759765 + }, + "state": { + "detail": "read", + "motion": "still" + }, + "chrome": { + "status": "available", + "executable": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" + }, + "diagnostics": [], + "containment": { + "status": "pass", + "policy": "fit-or-reader-declared-readable-vertical-scroll", + "viewports": [ + { + "width": 1440, + "height": 900, + "theme": "light", + "innerWidth": 1440, + "innerHeight": 900, + "scrollWidth": 1440, + "scrollHeight": 900, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": null, + "ok": true, + "readerWidth": 1376, + "diagramWidth": 1346, + "pageComposition": { + "bodyPaddingPx": 12, + "headerPx": 52, + "diagramChromePx": 78, + "svgPx": 484, + "cardsPx": 0, + "viewBoxHeight": 416 + }, + "viewBoxWidth": 1156, + "workflowLanes": [ + { + "frameId": "lane-0", + "heightPx": 133, + "nodeCount": 6, + "nodeIds": [ + "edit", + "click", + "judge", + "confirm", + "put", + "result" + ], + "nodeSpanPx": 79, + "spaceAboveNodesPx": 48, + "spaceBelowNodesPx": 6 + }, + { + "frameId": "lane-1", + "heightPx": 123, + "nodeCount": 2, + "nodeIds": [ + "always", + "banner" + ], + "nodeSpanPx": 79, + "spaceAboveNodesPx": 40, + "spaceBelowNodesPx": 5 + } + ], + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏列出待保存范围", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "edit" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + }, + { + "width": 1600, + "height": 1000, + "theme": "light", + "innerWidth": 1600, + "innerHeight": 1000, + "scrollWidth": 1600, + "scrollHeight": 1000, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": null, + "ok": true, + "readerWidth": 1536, + "diagramWidth": 1506, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 60, + "diagramChromePx": 84, + "svgPx": 542, + "cardsPx": 0, + "viewBoxHeight": 416 + }, + "viewBoxWidth": 1156, + "workflowLanes": [ + { + "frameId": "lane-0", + "heightPx": 149, + "nodeCount": 6, + "nodeIds": [ + "edit", + "click", + "judge", + "confirm", + "put", + "result" + ], + "nodeSpanPx": 89, + "spaceAboveNodesPx": 53, + "spaceBelowNodesPx": 7 + }, + { + "frameId": "lane-1", + "heightPx": 138, + "nodeCount": 2, + "nodeIds": [ + "always", + "banner" + ], + "nodeSpanPx": 89, + "spaceAboveNodesPx": 44, + "spaceBelowNodesPx": 5 + } + ], + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏列出待保存范围", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "edit" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + }, + { + "width": 1920, + "height": 1080, + "theme": "light", + "innerWidth": 1920, + "innerHeight": 1080, + "scrollWidth": 1920, + "scrollHeight": 1080, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": null, + "ok": true, + "readerWidth": 1856, + "diagramWidth": 1826, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 60, + "diagramChromePx": 84, + "svgPx": 657, + "cardsPx": 0, + "viewBoxHeight": 416 + }, + "viewBoxWidth": 1156, + "workflowLanes": [ + { + "frameId": "lane-0", + "heightPx": 180, + "nodeCount": 6, + "nodeIds": [ + "edit", + "click", + "judge", + "confirm", + "put", + "result" + ], + "nodeSpanPx": 107, + "spaceAboveNodesPx": 65, + "spaceBelowNodesPx": 8 + }, + { + "frameId": "lane-1", + "heightPx": 167, + "nodeCount": 2, + "nodeIds": [ + "always", + "banner" + ], + "nodeSpanPx": 107, + "spaceAboveNodesPx": 54, + "spaceBelowNodesPx": 6 + } + ], + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏列出待保存范围", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "edit" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + }, + { + "width": 2048, + "height": 1320, + "theme": "light", + "innerWidth": 2048, + "innerHeight": 1320, + "scrollWidth": 2048, + "scrollHeight": 1320, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": null, + "ok": true, + "readerWidth": 1920, + "diagramWidth": 1870, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 68, + "diagramChromePx": 94, + "svgPx": 673, + "cardsPx": 0, + "viewBoxHeight": 416 + }, + "viewBoxWidth": 1156, + "workflowLanes": [ + { + "frameId": "lane-0", + "heightPx": 184, + "nodeCount": 6, + "nodeIds": [ + "edit", + "click", + "judge", + "confirm", + "put", + "result" + ], + "nodeSpanPx": 110, + "spaceAboveNodesPx": 66, + "spaceBelowNodesPx": 8 + }, + { + "frameId": "lane-1", + "heightPx": 171, + "nodeCount": 2, + "nodeIds": [ + "always", + "banner" + ], + "nodeSpanPx": 110, + "spaceAboveNodesPx": 55, + "spaceBelowNodesPx": 6 + } + ], + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏列出待保存范围", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "edit" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 44, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + } + ] + }, + "themeStates": { + "status": "pass", + "viewports": [ + { + "width": 1440, + "height": 900, + "requestedTheme": "light", + "resolvedTheme": "light", + "ok": true + }, + { + "width": 1600, + "height": 1000, + "requestedTheme": "light", + "resolvedTheme": "light", + "ok": true + }, + { + "width": 1920, + "height": 1080, + "requestedTheme": "light", + "resolvedTheme": "light", + "ok": true + }, + { + "width": 2048, + "height": 1320, + "requestedTheme": "light", + "resolvedTheme": "light", + "ok": true + }, + { + "width": 1440, + "height": 900, + "requestedTheme": "dark", + "resolvedTheme": "dark", + "ok": true + }, + { + "width": 2048, + "height": 1320, + "requestedTheme": "dark", + "resolvedTheme": "dark", + "ok": true + } + ] + }, + "readability": { + "status": "pass", + "minimumProjectedNodeTextPx": 6, + "viewports": [ + { + "width": 1440, + "height": 900, + "theme": "light", + "innerWidth": 1440, + "innerHeight": 900, + "scrollWidth": 1440, + "scrollHeight": 900, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": null, + "ok": true, + "readerWidth": 1376, + "diagramWidth": 1346, + "pageComposition": { + "bodyPaddingPx": 12, + "headerPx": 52, + "diagramChromePx": 78, + "svgPx": 484, + "cardsPx": 0, + "viewBoxHeight": 416 + }, + "viewBoxWidth": 1156, + "workflowLanes": [ + { + "frameId": "lane-0", + "heightPx": 133, + "nodeCount": 6, + "nodeIds": [ + "edit", + "click", + "judge", + "confirm", + "put", + "result" + ], + "nodeSpanPx": 79, + "spaceAboveNodesPx": 48, + "spaceBelowNodesPx": 6 + }, + { + "frameId": "lane-1", + "heightPx": 123, + "nodeCount": 2, + "nodeIds": [ + "always", + "banner" + ], + "nodeSpanPx": 79, + "spaceAboveNodesPx": 40, + "spaceBelowNodesPx": 5 + } + ], + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏列出待保存范围", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "edit" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + }, + { + "width": 1600, + "height": 1000, + "theme": "light", + "innerWidth": 1600, + "innerHeight": 1000, + "scrollWidth": 1600, + "scrollHeight": 1000, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": null, + "ok": true, + "readerWidth": 1536, + "diagramWidth": 1506, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 60, + "diagramChromePx": 84, + "svgPx": 542, + "cardsPx": 0, + "viewBoxHeight": 416 + }, + "viewBoxWidth": 1156, + "workflowLanes": [ + { + "frameId": "lane-0", + "heightPx": 149, + "nodeCount": 6, + "nodeIds": [ + "edit", + "click", + "judge", + "confirm", + "put", + "result" + ], + "nodeSpanPx": 89, + "spaceAboveNodesPx": 53, + "spaceBelowNodesPx": 7 + }, + { + "frameId": "lane-1", + "heightPx": 138, + "nodeCount": 2, + "nodeIds": [ + "always", + "banner" + ], + "nodeSpanPx": 89, + "spaceAboveNodesPx": 44, + "spaceBelowNodesPx": 5 + } + ], + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏列出待保存范围", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "edit" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + }, + { + "width": 1920, + "height": 1080, + "theme": "light", + "innerWidth": 1920, + "innerHeight": 1080, + "scrollWidth": 1920, + "scrollHeight": 1080, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": null, + "ok": true, + "readerWidth": 1856, + "diagramWidth": 1826, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 60, + "diagramChromePx": 84, + "svgPx": 657, + "cardsPx": 0, + "viewBoxHeight": 416 + }, + "viewBoxWidth": 1156, + "workflowLanes": [ + { + "frameId": "lane-0", + "heightPx": 180, + "nodeCount": 6, + "nodeIds": [ + "edit", + "click", + "judge", + "confirm", + "put", + "result" + ], + "nodeSpanPx": 107, + "spaceAboveNodesPx": 65, + "spaceBelowNodesPx": 8 + }, + { + "frameId": "lane-1", + "heightPx": 167, + "nodeCount": 2, + "nodeIds": [ + "always", + "banner" + ], + "nodeSpanPx": 107, + "spaceAboveNodesPx": 54, + "spaceBelowNodesPx": 6 + } + ], + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏列出待保存范围", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "edit" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + }, + { + "width": 2048, + "height": 1320, + "theme": "light", + "innerWidth": 2048, + "innerHeight": 1320, + "scrollWidth": 2048, + "scrollHeight": 1320, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": null, + "ok": true, + "readerWidth": 1920, + "diagramWidth": 1870, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 68, + "diagramChromePx": 94, + "svgPx": 673, + "cardsPx": 0, + "viewBoxHeight": 416 + }, + "viewBoxWidth": 1156, + "workflowLanes": [ + { + "frameId": "lane-0", + "heightPx": 184, + "nodeCount": 6, + "nodeIds": [ + "edit", + "click", + "judge", + "confirm", + "put", + "result" + ], + "nodeSpanPx": 110, + "spaceAboveNodesPx": 66, + "spaceBelowNodesPx": 8 + }, + { + "frameId": "lane-1", + "heightPx": 171, + "nodeCount": 2, + "nodeIds": [ + "always", + "banner" + ], + "nodeSpanPx": 110, + "spaceAboveNodesPx": 55, + "spaceBelowNodesPx": 6 + } + ], + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏列出待保存范围", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "edit" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 44, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + } + ] + }, + "viewerChrome": { + "status": "pass", + "viewports": [ + { + "width": 1440, + "height": 900, + "theme": "light", + "innerWidth": 1440, + "innerHeight": 900, + "scrollWidth": 1440, + "scrollHeight": 900, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": null, + "ok": true, + "readerWidth": 1376, + "diagramWidth": 1346, + "pageComposition": { + "bodyPaddingPx": 12, + "headerPx": 52, + "diagramChromePx": 78, + "svgPx": 484, + "cardsPx": 0, + "viewBoxHeight": 416 + }, + "viewBoxWidth": 1156, + "workflowLanes": [ + { + "frameId": "lane-0", + "heightPx": 133, + "nodeCount": 6, + "nodeIds": [ + "edit", + "click", + "judge", + "confirm", + "put", + "result" + ], + "nodeSpanPx": 79, + "spaceAboveNodesPx": 48, + "spaceBelowNodesPx": 6 + }, + { + "frameId": "lane-1", + "heightPx": 123, + "nodeCount": 2, + "nodeIds": [ + "always", + "banner" + ], + "nodeSpanPx": 79, + "spaceAboveNodesPx": 40, + "spaceBelowNodesPx": 5 + } + ], + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏列出待保存范围", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "edit" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + }, + { + "width": 1600, + "height": 1000, + "theme": "light", + "innerWidth": 1600, + "innerHeight": 1000, + "scrollWidth": 1600, + "scrollHeight": 1000, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": null, + "ok": true, + "readerWidth": 1536, + "diagramWidth": 1506, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 60, + "diagramChromePx": 84, + "svgPx": 542, + "cardsPx": 0, + "viewBoxHeight": 416 + }, + "viewBoxWidth": 1156, + "workflowLanes": [ + { + "frameId": "lane-0", + "heightPx": 149, + "nodeCount": 6, + "nodeIds": [ + "edit", + "click", + "judge", + "confirm", + "put", + "result" + ], + "nodeSpanPx": 89, + "spaceAboveNodesPx": 53, + "spaceBelowNodesPx": 7 + }, + { + "frameId": "lane-1", + "heightPx": 138, + "nodeCount": 2, + "nodeIds": [ + "always", + "banner" + ], + "nodeSpanPx": 89, + "spaceAboveNodesPx": 44, + "spaceBelowNodesPx": 5 + } + ], + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏列出待保存范围", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "edit" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + }, + { + "width": 1920, + "height": 1080, + "theme": "light", + "innerWidth": 1920, + "innerHeight": 1080, + "scrollWidth": 1920, + "scrollHeight": 1080, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": null, + "ok": true, + "readerWidth": 1856, + "diagramWidth": 1826, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 60, + "diagramChromePx": 84, + "svgPx": 657, + "cardsPx": 0, + "viewBoxHeight": 416 + }, + "viewBoxWidth": 1156, + "workflowLanes": [ + { + "frameId": "lane-0", + "heightPx": 180, + "nodeCount": 6, + "nodeIds": [ + "edit", + "click", + "judge", + "confirm", + "put", + "result" + ], + "nodeSpanPx": 107, + "spaceAboveNodesPx": 65, + "spaceBelowNodesPx": 8 + }, + { + "frameId": "lane-1", + "heightPx": 167, + "nodeCount": 2, + "nodeIds": [ + "always", + "banner" + ], + "nodeSpanPx": 107, + "spaceAboveNodesPx": 54, + "spaceBelowNodesPx": 6 + } + ], + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏列出待保存范围", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "edit" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + }, + { + "width": 2048, + "height": 1320, + "theme": "light", + "innerWidth": 2048, + "innerHeight": 1320, + "scrollWidth": 2048, + "scrollHeight": 1320, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": null, + "ok": true, + "readerWidth": 1920, + "diagramWidth": 1870, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 68, + "diagramChromePx": 94, + "svgPx": 673, + "cardsPx": 0, + "viewBoxHeight": 416 + }, + "viewBoxWidth": 1156, + "workflowLanes": [ + { + "frameId": "lane-0", + "heightPx": 184, + "nodeCount": 6, + "nodeIds": [ + "edit", + "click", + "judge", + "confirm", + "put", + "result" + ], + "nodeSpanPx": 110, + "spaceAboveNodesPx": 66, + "spaceBelowNodesPx": 8 + }, + { + "frameId": "lane-1", + "heightPx": 171, + "nodeCount": 2, + "nodeIds": [ + "always", + "banner" + ], + "nodeSpanPx": 110, + "spaceAboveNodesPx": 55, + "spaceBelowNodesPx": 6 + } + ], + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏列出待保存范围", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "edit" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 44, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light" + } + ] + }, + "captures": { + "status": "pass", + "screenshots": [ + { + "width": 1440, + "height": 900, + "theme": "light", + "innerWidth": 1440, + "innerHeight": 900, + "scrollWidth": 1440, + "scrollHeight": 900, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": null, + "ok": true, + "readerWidth": 1376, + "diagramWidth": 1346, + "pageComposition": { + "bodyPaddingPx": 12, + "headerPx": 52, + "diagramChromePx": 78, + "svgPx": 484, + "cardsPx": 0, + "viewBoxHeight": 416 + }, + "viewBoxWidth": 1156, + "workflowLanes": [ + { + "frameId": "lane-0", + "heightPx": 133, + "nodeCount": 6, + "nodeIds": [ + "edit", + "click", + "judge", + "confirm", + "put", + "result" + ], + "nodeSpanPx": 79, + "spaceAboveNodesPx": 48, + "spaceBelowNodesPx": 6 + }, + { + "frameId": "lane-1", + "heightPx": 123, + "nodeCount": 2, + "nodeIds": [ + "always", + "banner" + ], + "nodeSpanPx": 79, + "spaceAboveNodesPx": 40, + "spaceBelowNodesPx": 5 + } + ], + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏列出待保存范围", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "edit" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light", + "file": "config-save-flow.visual-check.1440x900.light.png" + }, + { + "width": 1440, + "height": 900, + "theme": "dark", + "innerWidth": 1440, + "innerHeight": 900, + "scrollWidth": 1440, + "scrollHeight": 900, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": null, + "ok": true, + "readerWidth": 1376, + "diagramWidth": 1346, + "pageComposition": { + "bodyPaddingPx": 12, + "headerPx": 52, + "diagramChromePx": 78, + "svgPx": 484, + "cardsPx": 0, + "viewBoxHeight": 416 + }, + "viewBoxWidth": 1156, + "workflowLanes": [ + { + "frameId": "lane-0", + "heightPx": 133, + "nodeCount": 6, + "nodeIds": [ + "edit", + "click", + "judge", + "confirm", + "put", + "result" + ], + "nodeSpanPx": 79, + "spaceAboveNodesPx": 48, + "spaceBelowNodesPx": 6 + }, + { + "frameId": "lane-1", + "heightPx": 123, + "nodeCount": 2, + "nodeIds": [ + "always", + "banner" + ], + "nodeSpanPx": 79, + "spaceAboveNodesPx": 40, + "spaceBelowNodesPx": 5 + } + ], + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏列出待保存范围", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "edit" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 54, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "dark", + "file": "config-save-flow.visual-check.1440x900.dark.png" + }, + { + "width": 2048, + "height": 1320, + "theme": "light", + "innerWidth": 2048, + "innerHeight": 1320, + "scrollWidth": 2048, + "scrollHeight": 1320, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": null, + "ok": true, + "readerWidth": 1920, + "diagramWidth": 1870, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 68, + "diagramChromePx": 94, + "svgPx": 673, + "cardsPx": 0, + "viewBoxHeight": 416 + }, + "viewBoxWidth": 1156, + "workflowLanes": [ + { + "frameId": "lane-0", + "heightPx": 184, + "nodeCount": 6, + "nodeIds": [ + "edit", + "click", + "judge", + "confirm", + "put", + "result" + ], + "nodeSpanPx": 110, + "spaceAboveNodesPx": 66, + "spaceBelowNodesPx": 8 + }, + { + "frameId": "lane-1", + "heightPx": 171, + "nodeCount": 2, + "nodeIds": [ + "always", + "banner" + ], + "nodeSpanPx": 110, + "spaceAboveNodesPx": 55, + "spaceBelowNodesPx": 6 + } + ], + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏列出待保存范围", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "edit" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 44, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "light", + "file": "config-save-flow.visual-check.2048x1320.light.png" + }, + { + "width": 2048, + "height": 1320, + "theme": "dark", + "innerWidth": 2048, + "innerHeight": 1320, + "scrollWidth": 2048, + "scrollHeight": 1320, + "overflowX": false, + "overflowY": false, + "verticalScrollAccepted": false, + "overflowDisposition": "contained", + "readerLayout": "adaptive", + "readerOverflow": null, + "readerFit": null, + "ok": true, + "readerWidth": 1920, + "diagramWidth": 1870, + "pageComposition": { + "bodyPaddingPx": 64, + "headerPx": 68, + "diagramChromePx": 94, + "svgPx": 673, + "cardsPx": 0, + "viewBoxHeight": 416 + }, + "viewBoxWidth": 1156, + "workflowLanes": [ + { + "frameId": "lane-0", + "heightPx": 184, + "nodeCount": 6, + "nodeIds": [ + "edit", + "click", + "judge", + "confirm", + "put", + "result" + ], + "nodeSpanPx": 110, + "spaceAboveNodesPx": 66, + "spaceBelowNodesPx": 8 + }, + { + "frameId": "lane-1", + "heightPx": 171, + "nodeCount": 2, + "nodeIds": [ + "always", + "banner" + ], + "nodeSpanPx": 110, + "spaceAboveNodesPx": 55, + "spaceBelowNodesPx": 6 + } + ], + "minimumProjectedNodeTextPx": 8, + "minimumProjectedNonEdgeTextPx": 8, + "minimumProjectedEdgeTextPx": 8, + "minimumProjectedNodeText": "保存栏列出待保存范围", + "minimumProjectedNodeTextDetail": "context", + "minimumProjectedNodeTextOwner": { + "kind": "node", + "id": "edit" + }, + "minimumRequiredNodeTextPx": 6, + "readabilityOk": true, + "hasLegend": true, + "hasNavigationDock": true, + "legendDockIntersectionArea": 0, + "dockStageIntersectionArea": 0, + "dockStageGap": 10, + "requiredDockStageGap": 10, + "viewerChromeStageOk": true, + "viewerChromeReserve": 44, + "viewerChromeActive": true, + "viewerChromeOk": true, + "resolvedTheme": "dark", + "file": "config-save-flow.visual-check.2048x1320.dark.png" + } + ], + "contactSheet": "config-save-flow.visual-check.html" + }, + "sidecars": { + "directory": "/private/tmp/claude-501/-Users-cm-huang-orca-workspaces-coding-proxy-blenny/fd640297-2c00-4aba-b756-f33398d52a18/scratchpad/cfg-design/diagrams/workflow-config-save-flow-20261127-144023/visual-check-r3", + "receipt": "config-save-flow.visual-check.json", + "contactSheet": "config-save-flow.visual-check.html", + "files": [ + { + "sha256": "e6ff3a4259f0005b50d16ebd31313d6347cb7c3897c53824f03813f4d896a59f", + "bytes": 1940, + "file": "config-save-flow.visual-check.html" + }, + { + "sha256": "293078dbd68519e729d0c3d1e441906955b3efe935eeeb091b4753cff8b84cdb", + "bytes": 186052, + "file": "config-save-flow.visual-check.1440x900.light.png" + }, + { + "sha256": "641a41b87b570b771f6da5ddfd974982729752328722826d308a814a527033be", + "bytes": 195429, + "file": "config-save-flow.visual-check.1440x900.dark.png" + }, + { + "sha256": "eeab7842b415dcf98de40612d89cebdd6fdc4b80c9d72e28557e881d35710f17", + "bytes": 255502, + "file": "config-save-flow.visual-check.2048x1320.light.png" + }, + { + "sha256": "d8305dc2df5aa81996d42e13a0f50261b5933fb19287333309fb6feefba0cfd2", + "bytes": 272023, + "file": "config-save-flow.visual-check.2048x1320.dark.png" + } + ] + } +} diff --git a/docs/guide/dashboard.md b/docs/guide/dashboard.md index d9c97e0a..13fab1c3 100644 --- a/docs/guide/dashboard.md +++ b/docs/guide/dashboard.md @@ -14,49 +14,75 @@ http://127.0.0.1:3392/dashboard ### KPI 卡片 -顶部展示核心指标: - -| 卡片 | 说明 | -| ---------------- | ------------------------------------------ | -| 今日请求数 | 当日总请求数(子行显示本周累计) | -| 今日 Token 总量 | 当日总 Token 消耗(子行显示本周累计) | -| 今日输出 Token | 当日输出 Token 数(子行显示本周累计) | -| 今日费用估算 | 基于定价配置的费用估算(子行显示本周累计) | -| 故障转移(今日) | 当日故障转移事件数(子行显示本周累计) | -| 平均延迟(今日) | 当日请求平均响应时间(子行显示本周累计) | +页面顶部是一条 KPI strip:六项指标合成一个表面,格与格之间以细线分隔。每格主行是当日值,副行是所选时间区间的累计值,前缀写区间标签「近 N 天」。自选区间也只折算成天数:接口取的是截至今天的最近 N 天,起止日期只用来算 N(最多 90 天),不是取数窗口。视口 1023px 及以下排 3 列两行,519px 及以下排 2 列三行。 + +| 卡片 | 说明 | +| --------------- | ---------------------------------------------------------------------------------- | +| 今日请求数 | 当日总请求数 | +| 今日 Token 总量 | 当日总 Token 消耗 | +| 今日输出 Token | 当日输出 Token 数 | +| 今日费用估算 | 基于定价配置的费用估算;双币种(如 `¥298.96 + $412.37`)放不下时在两种币种之间换行 | +| 今日故障转移 | 当日故障转移事件数 | +| 今日平均延迟 | 当日请求平均响应时间 | + +### Model Calling 实时状态 + +「Model Calling 实时状态」卡片按行列出各 vendor / 模型当前的并行度占用,标题右侧的「每 10 秒刷新」对应卡片对 `GET /api/status` 的 10 秒轮询(只在 Overview 页签激活期间轮询)。每个模型一行,五列逐行对齐: + +| 列 | 内容 | +| --------- | ------------------------------------------------------------------------------ | +| vendor | 供应商名 | +| 模型 | 模型名;过长时省略,悬停看 `vendor/model` 全名 | +| 并行度条 | 在途占上限的比例;填充色不超过 50% 为绿、不超过 80% 为黄、其余为红 | +| 在途/上限 | 如 `4/10`;斜杠后的上限是按钮,点击或键盘聚焦后回车即可修改并行度 | +| 排队 | 有排队时是琥珀胶囊「排队 N」;当前无排队但最近 10 秒排过队时是灰字「曾排队 N」 | + +- 布局:视口不少于 1280px 且不少于 3 行时排两列;759px 及以下每行折成两行(模型名与排队一行,vendor、并行度条与计数一行); +- monitor 模式:不画并行度条,原位显示灰字「仅监控 · 不限并行度」(759px 及以下只写「仅监控」),计数写成「N 进行中」; +- 修改并行度:进入编辑后原地出现输入框,只接受 1 到 20 的整数,Enter 或失焦提交、Esc 取消,结束后焦点回到上限。编辑期间轮询不重绘这张卡;非法输入(如 `7.5`、`99`)不提交,上限标红;提交成功后这一行立即按新上限重算,不等下一轮轮询。编辑一行时点另一行的上限,当前这行提交完成后接着打开那一行(期间焦点已被移走则不抢焦点);编辑结果写入页面里常驻的 `role=status` 节点供读屏播报。 +- 模型名:最多折成两行,两行还放不下才省略,完整名称在悬停提示里。 ### 图表 -| 图表 | 说明 | -| ----------------------------- | ------------------------------------ | -| 请求时间线 | 按天的请求量趋势图 | -| 供应商分布 | 各供应商请求占比甜甜圈图 | -| Token 时间线(按供应商) | 各供应商按天的 Token 消耗堆叠图 | -| Token 时间线(按供应商+模型) | 细粒度的模型级 Token 消耗堆叠图 | +「供应商请求分布」与「订阅状态」并排一行,并排与堆叠的断点见[订阅状态](#订阅状态);三张趋势图共用一个图位的三个页签,页签行右端标明当前时间区间。 + +| 图表 | 说明 | +| ---------------------- | ---------------------------------------- | +| 供应商请求分布 | 所选时间区间内各供应商请求占比的甜甜圈图 | +| 请求量 | 按天的请求量 | +| Token(按供应商) | 各供应商按天的 Token 消耗 | +| Token(Vendor / 模型) | 模型级 Token 消耗 | + +三张趋势图都是堆叠面积图,每条线填充到上一条堆叠线;所选区间没有数据时,图位显示「暂无数据」。图形读屏读不到,每张图的 canvas 带 `role=img` 与一句文字摘要(区间、合计、单日最高;分布图是各供应商占比)。分布图的图例默认在右侧;并排右列放不下最长的标签(视口约 1210px 以下)时移到图下方自动换行,避免标签被画布右缘裁掉。 ### 订阅状态 -「🎫 订阅状态」卡片把三家订阅(Claude Code / GLM Coding Plan / Antigravity)的档位与用量,同各供应商的路由状态放进同一张卡片,同一个账号只占一行。视口宽于 960px 时每行始终单行:行名之后是订阅区,竖线右侧是路由区;一行放不下时只在订阅区内横向滚动(触控板左右滑动,鼠标按住 Shift 滚动),被遮住的部分不会折到第二行。视口 960px 及以下退回两行:标识与路由状态占首行,订阅区独占次行。 +「🎫 订阅状态」卡片把三家订阅(Claude Code / GLM Coding Plan / Antigravity)的档位与用量,同各供应商的可用状态放进同一张卡片,同一个账号只占一行。视口不少于 1180px 时它与「供应商请求分布」并排(订阅卡在左,分布卡随它等高),1179px 及以下上下堆叠。 -| 元素 | 样式 | 例 | -| -------- | ------------------------------------------------------ | ------------------------------------------------ | -| 状态 | 胶囊,全卡只有状态用胶囊 | `正常` / `熔断 ×3` / `限速中` / `未启用` / `查询失败` | -| 档位 | 行名后的加粗亮字,与行名相同则不显示 | `Max` | -| 分组标签 | 灰字:模型族或 tier 名 | `Gemini` / `Claude+GPT` / `zhipu` | -| 用量格 | 窗口标签 + 细进度条 + 百分比,订阅窗口再缀重置倒计时 | `5h`、进度条、`8%`、`◷2h` | +视口宽于 960px 时每行始终单行:行名之后是订阅区,行尾右对齐是该供应商的可用状态;一行放不下时只在订阅区内横向滚动(触控板左右滑动,鼠标按住 Shift 滚动),被遮住的部分不会折到第二行,订阅区右缘渐隐提示后面还有内容,滚到头提示消失。视口 960px 及以下退回两行:标识与可用状态占首行,订阅区独占次行。 -用量格的底色与进度条随用量转黄(≥ 70%)、转红(≥ 90%),悬停可看完整窗口名与完整倒计时。窗口标签三家同一套:订阅窗口是 `5h` / `周`,配额守卫窗口是 `5h` / `1d` / `7d`。Antigravity 的四个窗口按模型族分成两组,组内先 5h 后 周。 +| 元素 | 样式 | 例 | +| -------- | -------------------------------------------------------------- | --------------------------------------------------- | +| 可用状态 | 行尾右对齐:无异常是绿点加灰字,异常才是胶囊,多个异常全部列出 | `正常` / `熔断 ×3` / `半开` / `限速中` / `配额超限` | +| 订阅状态 | 胶囊,全卡只有状态用胶囊 | `未启用` / `查询失败` / `等待首个请求` | +| 档位 | 行名后的加粗亮字,与行名相同则不显示 | `Max` | +| 分组标签 | 灰字:模型族 | `Gemini` / `Claude+GPT` | +| 用量格 | 窗口标签 + 细进度条 + 百分比,订阅窗口再缀重置倒计时 | `5h`、进度条、`8%`、`◷2h` | -| 行 | 内容 | 拖拽 | -| ------------------------------------------------------------- | -------------------------------------------------------------------- | -------- | -| 合并行(订阅与路由 tier 属同一账号) | 竖线左侧为订阅档位与用量窗口;右侧为该供应商的熔断状态、限速、配额守卫 | 可拖拽 | -| 供应商行(无订阅对应的供应商,如 copilot) | 仅路由状态,以灰字「供应商状态」标注 | 可拖拽 | -| 订阅行(无路由 tier,如仅经 IDE gateway 透传的 Antigravity) | 仅订阅档位与用量,行尾灰字「未加入路由链」,不画分隔线 | 不可拖拽 | +用量格的底色与进度条随用量转黄(≥ 70%)、转红(≥ 90%),悬停可看完整窗口名与完整倒计时。订阅窗口的标签三家同一套:`5h` / `周`。Antigravity 的四个窗口按模型族分成两组,组内先 5h 后 周。 + +可用状态只回答「这个供应商现在能不能接请求」:`熔断 ×N` 的 N 是失败次数,为 0 时只写「熔断」;`半开` 是熔断器在放行探测请求;`限速中` 是限速冷却未结束;`配额超限` 是任一配额守卫(`5h` / `1d` / `7d` 滑动窗口)超过阈值。多个条件并存时按 熔断、半开、限速中、配额超限 的顺序全部列出。tier 名、熔断器状态与失败次数、限速剩余秒数、各配额守卫窗口的已用百分比与阈值只在悬停详情里出现。 + +| 行 | 内容 | 拖拽 | +| ------------------------------------------------------------ | -------------------------------------------- | -------- | +| 合并行(订阅与路由 tier 属同一账号) | 订阅档位与用量窗口,行尾是该供应商的可用状态 | 可拖拽 | +| 供应商行(无订阅对应的供应商,如 copilot) | 仅该供应商的可用状态 | 可拖拽 | +| 订阅行(无路由 tier,如仅经 IDE gateway 透传的 Antigravity) | 仅订阅档位与用量,行尾灰字「未加入路由链」 | 不可拖拽 | - 行的先后顺序等于路由优先级:拖动行首的 ⠿ 手柄,或用 Tab 聚焦手柄后按 ↑ / ↓ 调整;运行时生效,保存配置后恢复为配置的 `tiers` 顺序,调整过程不重置配额; -- 竖线两侧的百分比口径不同:左侧是上游账号的套餐额度,按窗口重置;右侧是本代理自记的滑动窗口 Token 预算; +- 百分比有两种口径:用量格是上游账号的套餐额度,按窗口重置;悬停详情里的配额守卫用量是本代理自记的滑动窗口 Token 预算; - Claude Code 订阅的用量来自被动采集,只有 OAuth 订阅流量会回填,按 API key 计费的 anthropic 供应商会一直显示「等待首个请求」(悬停看说明); -- 订阅接口请求失败或服务未装配时,卡片底部显示「无订阅数据」,路由状态照常展示;单家上游查询失败只在该行显示「查询失败」徽章(悬停看原因),不影响其他家。 +- 订阅接口请求失败或服务未装配时,卡片底部显示「无订阅数据」,各供应商的可用状态照常展示;单家上游查询失败只在该行显示「查询失败」徽章(悬停看原因),不影响其他家。 数据来源与上游契约见 [订阅状态面板](../arch/subscription-status.md)。 @@ -64,41 +90,47 @@ http://127.0.0.1:3392/dashboard 「订阅状态」卡片标题栏右侧提供 **⟲ 状态复位** 按钮,用于把处于熔断 / 限流等异常态的供应商一键复位为可正常访问(只作用于供应商路由状态,不涉及订阅用量)。等价于 [`POST /api/reset`](./api-reference.md#6-post-apireset) 的**无 body** 形态: -| 复位 | 保留 | -| ---------------------------------------------------------- | ------------------------------------------------------------ | -| 熔断器状态(→ CLOSED,「熔断 ×N」徽章转「正常」) | 配额窗口用量(「1d」用量格的数值不变) | -| 配额守卫状态(用量未超阈值 → WITHIN_QUOTA;确已超阈值 → 保持 EXCEEDED,但仍清除 cap 卡死标志并还原探测间隔) | 供应商优先级顺序(无 body 即不触发重排序) | -| Rate Limit 冷却截止时间(→ 清除,「限速中」徽章消失) | 数据库用量记录(`coding-proxy usage` 统计不受影响) | +| 复位 | 保留 | +| ------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------- | +| 熔断器状态(→ CLOSED,「熔断 ×N」徽章转「正常」) | 配额窗口用量(悬停详情里各配额守卫窗口的已用百分比不变) | +| 配额守卫状态(用量未超阈值 → WITHIN_QUOTA;确已超阈值 → 保持 EXCEEDED,但仍清除 cap 卡死标志并还原探测间隔) | 供应商优先级顺序(无 body 即不触发重排序) | +| Rate Limit 冷却截止时间(→ 清除,「限速中」徽章消失) | 数据库用量记录(`coding-proxy usage` 统计不受影响) | 执行期间按钮进入禁用态并显示「复位中…」,成功后短暂显示「✓ 已复位」并立即重渲染订阅状态卡片(不必等 10 分钟轮询),失败显示「✗ 失败」,详情见浏览器控制台。 -> 若某供应商的窗口用量**确实**已超过配额阈值,复位不会放行它 —— 用量数字不会被伪造,守卫保持 `QUOTA_EXCEEDED`;但 cap 错误卡死标志会被清除、探测间隔还原为默认值,探测恢复不会被推迟。 +> 若某供应商的窗口用量**确实**已超过配额阈值,复位不会放行它:用量数字不会被伪造,守卫保持 `QUOTA_EXCEEDED`;但 cap 错误卡死标志会被清除、探测间隔还原为默认值,探测恢复不会被推迟。 ### 时间范围选择器 -页面右上角提供时间范围选择: +Overview 页签顶部、KPI 上方的时间区间栏独占一行,同时作用于 KPI 副行与全部图表: + +- **近 7 天**(默认) +- **近 30 天** +- **自选区间**:选起止日期,默认带出本地今天的近 7 天;起止日期只折算成天数(含首尾两天,反向区间不取数),服务端最多按 90 天取数 -- **7 天**(默认) -- **30 天** -- **自定义天数**(1~90 天) +刷新途中改了区间,当前这轮刷新按旧区间收尾(已上屏的数据与区间标签一致),随后按新区间补刷一次;取数失败不补刷。 ### Config 页(在线配置) Config 页签在线编辑配置存储(`~/.coding-proxy/config.db`):Vendors(9 类供应商,含熔断 / 配额 / 并发等弹性参数与密钥三态控件)、Tiers、Failover、Model Mapping、Pricing($ / ¥ 双币种)、Native API、Session Policies,以及 System(bootstrap 字段只读展示 + 迁移状态)。 - **解锁**:首次进入粘贴 admin token(`coding-proxy config token` 输出),仅存于本浏览器;管理 API 只认 `X-Coding-Proxy-Admin` 请求头。 -- **保存**:单一 Save 汇总「Save N fields in K sections」,确认框列出将被重置的运行时状态与因目标地址变化被清空的密钥;保存后**进程内热切换生效,无需重启**。 -- **冲突与校验**:并发修改返回 409(只重载冲突 section);校验错误定位到具体字段行内展示,且从不回显输入值。 -- **密钥**:只写不读,展示 Stored / Env / Empty 状态与尾 4 位(长度 ≥ 16 时);vendor 目标地址变化时自动清空关联密钥并在确认框提示。 +- **保存**:底部保存栏列出待保存范围(如「待保存:Vendors › zhipu、Pricing(3 处)」)。保存会产生后果时先弹确认框,列出后果与每个字段的新旧值;后果包括密钥写入或清空、目标地址变化清空已存密钥、有进行中的请求、熔断 / 限流 / 配额状态将重置、运行中的优先级与 Tiers 不同、上次保存后未生效的 section 会一并生效。没有这些后果时直接保存。保存后**进程内热切换生效,无需重启**。 +- **保存结果**:显示在底部保存栏(成功 / 需重启 / 失败),不会自动消失,点「关闭」或再次编辑后清除;保存失败时保留修改,再点「保存」即重试。 +- **恢复默认与移除**:Vendors 子 pill 行的「全部恢复默认」作用于全部 vendor,总是先确认;vendor 级与其他 section 的「恢复默认」只在会替换已保存的自定义值时确认。移除 vendor 先确认(会同时移出 Tiers 链路);移除表格行不确认。两种移除之后保存栏都提供「撤销」,把对象插回原位,只保留最近一次。Pricing 里已保存的行不可移除,只能「下线 / 上线」。 +- **冲突与校验**:并发修改返回 409(只重载冲突 section);校验错误定位到具体字段行内展示,保存栏列出出错字段的可读名称,且从不回显输入值。 +- **密钥**:只写不读,展示 Stored / Env / Empty 状态与尾 4 位(长度 ≥ 16 时);vendor 目标地址变化时自动清空关联密钥并在确认框提示,确认框的字段差异不含密钥字段。 +- **键盘**:添加行后新行滚入视口并聚焦第一个输入框;排序、展开、切换 section 后焦点留在原控件或新的激活项上。字段名在窄窗口下不截断(label 列最窄 104px),视口 640px 以下 label 与控件分两行。 ![Config 页 — Vendors 编辑与密钥三态控件](../../assets/dashboard/config-tab.png) ### 自动刷新 -看板每 **10 分钟**自动刷新数据。也可点击右上角「刷新」按钮手动刷新。Config 页不参与定时刷新(避免覆盖编辑中的表单)。 +看板每 **10 分钟**自动刷新数据。也可点击右上角「刷新」按钮手动刷新。Config 页不参与定时刷新(避免覆盖编辑中的表单);Overview 的「Model Calling 实时状态」卡片另有 10 秒一次的独立轮询。 ### 图表交互 +- 趋势图的三个页签:点击切换;键盘聚焦页签后用 ← / → 循环切换、Home / End 跳到首尾,焦点移到哪个页签就选中哪个;当前页签跨刷新、跨时间区间保持 - **单击**图例项:隔离显示该系列 - **Ctrl+单击**图例项:多选显示 - **Shift+单击**图例项:排除该系列 diff --git a/src/coding/proxy/config/routing.py b/src/coding/proxy/config/routing.py index c2dd6063..7a0c9a80 100644 --- a/src/coding/proxy/config/routing.py +++ b/src/coding/proxy/config/routing.py @@ -122,6 +122,9 @@ class ModelPricingEntry(BaseModel): vendor: str # 供应商名称(对应 usage 表"供应商"列) model: str # 实际模型名(对应 usage 表"实际模型"列) + # 下线开关:False = 不进 Model Bind 下拉、不可再绑定;已绑会话保留并继续 + # 按锁定 vendor 路由,成本照常计价(pricing 行不可删除,退役走下线) + online: bool = True input_cost_per_mtok: PriceField = 0.0 # 输入 Token 单价 output_cost_per_mtok: PriceField = 0.0 # 输出 Token 单价 cache_write_cost_per_mtok: PriceField = 0.0 # 缓存创建 Token 单价 diff --git a/src/coding/proxy/config/service.py b/src/coding/proxy/config/service.py index 96dee4d0..d36664f6 100644 --- a/src/coding/proxy/config/service.py +++ b/src/coding/proxy/config/service.py @@ -402,6 +402,43 @@ def boundary_errors(section: str, value: Any, current: Any = _MISSING) -> list[d return [*errors, *rules] +def _pricing_shrink_errors( + current_raw: Mapping[str, Any], new_raw: Mapping[str, Any] +) -> list[dict]: + """pricing 行不可删除:任何 (vendor, model) 行消失(删除 / 改名 / 恢复默认丢行)都拒绝. + + pricing 行是 Model Bind 目录的派生来源与下线锚点,删除会使已绑该模型的 + 会话在热切换时被整条丢弃;退役请将该行 ``online`` 置 false。错误只带 + 消失条数,不回显任何值。 + """ + + def _keys(rows: Any) -> set[tuple[str, str]]: + out: set[tuple[str, str]] = set() + if isinstance(rows, list): + for row in rows: + if isinstance(row, dict): + vendor, model = row.get("vendor"), row.get("model") + if ( + isinstance(vendor, str) + and isinstance(model, str) + and vendor + and model + ): + out.add((vendor, model)) + return out + + removed = _keys(current_raw.get("pricing")) - _keys(new_raw.get("pricing")) + if removed: + return [ + _err( + ["pricing"], + f"pricing 行不可删除(将移除 {len(removed)} 行);" + "下线请将该行 online 置为 false", + ) + ] + return [] + + # ── 服务 ──────────────────────────────────────────────────────── @@ -597,6 +634,7 @@ def _plan( json.dumps(override, ensure_ascii=False) ) new_raw = compose_raw(defaults, new_sections) + errors += _pricing_shrink_errors(current_raw, new_raw) self._check_tiers_membership(new_raw, sections, errors) if not allow_env_any: errors += _http_env_binding_errors(defaults, new_raw, secret_ops) diff --git a/src/coding/proxy/config/ui_registry.py b/src/coding/proxy/config/ui_registry.py index 5737e3a9..da6fb583 100644 --- a/src/coding/proxy/config/ui_registry.py +++ b/src/coding/proxy/config/ui_registry.py @@ -470,6 +470,12 @@ def _vendor_qg(prefix: str, group: str, window_desc: str) -> list[FieldSpec]: unit="/Mtok", min=0, ), + _f( + "pricing.*.online", + "Online", + "bool", + "下线(false)后不进 Model Bind 下拉、不可新绑定;已绑会话保留,成本照常计价", + ), ] for _provider in ("openai", "gemini", "anthropic"): diff --git a/src/coding/proxy/routing/executor.py b/src/coding/proxy/routing/executor.py index 04538cdb..1837c875 100644 --- a/src/coding/proxy/routing/executor.py +++ b/src/coding/proxy/routing/executor.py @@ -998,7 +998,7 @@ def _pinned_tier_names(self, model: str | None) -> list[str] | None: """ if not model or not self._router: return None - for entry in self._router.get_bindable_models(): + for entry in self._router.get_known_models(): if str(entry.get("model", "")) == model: tiers = [str(t) for t in entry.get("tiers", []) if t] return tiers or None diff --git a/src/coding/proxy/routing/router.py b/src/coding/proxy/routing/router.py index 7f48467f..267ed6d2 100644 --- a/src/coding/proxy/routing/router.py +++ b/src/coding/proxy/routing/router.py @@ -85,7 +85,20 @@ def get_vendor_names(self) -> list[str]: return [t.name for t in self._tiers] def get_bindable_models(self) -> list[dict[str, Any]]: - """返回可绑定模型清单(Model Bind 下拉选项与 API 校验的来源).""" + """返回可绑定模型清单(Model Bind 下拉选项与 API 校验的来源). + + 只含可选条目:pricing 下线(``offline`` 标记)的模型不在此列; + executor 锁定链与热切换迁移需含下线的全量清单,见 :meth:`get_known_models`. + """ + return [m for m in self._bindable_models if not m.get("offline")] + + def get_known_models(self) -> list[dict[str, Any]]: + """返回全部已知模型(含下线条目). + + 下线模型对「已绑会话保持绑定」仍需可见:executor 锁定链 + (``_pinned_tier_names``)与热切换绑定迁移(``_migrate_bindings``) + 消费本清单;下拉与 PUT 校验消费 :meth:`get_bindable_models`. + """ return self._bindable_models def reorder_tiers(self, vendor_names: list[str]) -> None: diff --git a/src/coding/proxy/server/app.py b/src/coding/proxy/server/app.py index 820e429c..57f93a1d 100644 --- a/src/coding/proxy/server/app.py +++ b/src/coding/proxy/server/app.py @@ -137,7 +137,7 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI: else: _active_vendor_names = [v.vendor for v in config.vendors if v.enabled] _bindable_catalog = compose_bindable_catalog( - _active_vendor_names, config.session_policies.bindable_models + _active_vendor_names, config.session_policies.bindable_models, config.pricing ) mapper = ModelMapper( [ diff --git a/src/coding/proxy/server/dashboard.py b/src/coding/proxy/server/dashboard.py index 8bcd6c15..d2be8c22 100644 --- a/src/coding/proxy/server/dashboard.py +++ b/src/coding/proxy/server/dashboard.py @@ -248,19 +248,16 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: --text-primary: #e6edf3; --text-secondary: #8b949e; --text-tertiary: #6e7681; - --text-muted: #6e7681; --accent-blue: #58a6ff; --accent-green: #3fb950; --accent-yellow: #d29922; --accent-red: #f85149; --accent-purple: #bc8cff; - --accent-orange: #ffa657; --accent-teal: #39d353; --radius: 14px; --radius-sm: 8px; --shadow: 0 1px 2px rgba(0,0,0,.3); --shadow-md: 0 8px 24px rgba(0,0,0,.3); - --glow-blue: 0 0 0 1px rgba(88,166,255,.1), 0 8px 32px rgba(88,166,255,.04); --gradient-primary: linear-gradient(135deg, #667eea, #764ba2); --gap-section: 12px; /* 表格固定列宽 token(Sessions 与 Config 共用:同一属性同一宽度; @@ -353,86 +350,94 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: } /* ── 主内容 ── */ main { padding: 28px 32px; max-width: 1440px; margin: 0 auto; } - /* ── KPI 卡片 ── */ + /* ── KPI:一条 stat strip ── + 六格合成一个表面,格间只留 hairline。数值穿文字色;图标、彩色顶线、hover 光晕这类装饰一概不加 */ .kpi-grid { display: grid; - grid-template-columns: repeat(6, minmax(0, 1fr)); - gap: var(--gap-section); - margin-bottom: var(--gap-section); - } - .kpi-card { + gap: 0; + /* 费用可能是双币种长串(¥1,234.56 + $987.65),那一列略宽,其余五列等宽 */ + grid-template-columns: repeat(3, minmax(0, 1fr)) minmax(0, 1.45fr) repeat(2, minmax(0, 1fr)); + overflow: hidden; background: rgba(18,22,30,.7); border: 1px solid rgba(255,255,255,.05); border-radius: var(--radius); - padding: 20px 22px 18px; box-shadow: var(--shadow); backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px); - transition: all .2s ease; - animation: fadeInUp .4s ease both; + margin-bottom: var(--gap-section); + } + .kpi-card { position: relative; - overflow: hidden; + min-width: 0; + padding: 16px 20px 14px; + border-left: 1px solid rgba(255,255,255,.06); + animation: fadeInUp .4s ease both; } - .kpi-card::before { - content: ''; - position: absolute; - top: 0; left: 0; right: 0; - height: 1px; - opacity: .6; - border-radius: var(--radius) var(--radius) 0 0; - } - .kpi-card:nth-child(1)::before { background: var(--accent-blue); } - .kpi-card:nth-child(2)::before { background: var(--accent-purple); } - .kpi-card:nth-child(3)::before { background: var(--accent-green); } - .kpi-card:nth-child(4)::before { background: var(--accent-yellow); } - .kpi-card:nth-child(5)::before { background: var(--accent-red); } - .kpi-card:nth-child(6)::before { background: var(--accent-orange); } - .kpi-card:hover { - background: var(--bg-card-hover); - box-shadow: var(--glow-blue); + .kpi-card:nth-child(6n+1) { border-left: 0; } + /* 首末两格的外侧内边距取卡片标准内边距:首格文字与其它卡片标题左对齐 */ + .kpi-card:first-child { padding-left: 24px; } + .kpi-card:last-child { padding-right: 24px; } + .kpi-label { + font-size: 13px; font-weight: 500; color: var(--text-secondary); letter-spacing: .2px; + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } - .kpi-header { display: flex; align-items: center; gap: 6px; margin-bottom: 8px; } - .kpi-icon { font-size: 15px; opacity: .8; } - .kpi-label { font-size: 13px; color: var(--text-secondary); font-weight: 600; letter-spacing: .2px; } .kpi-value { - font-size: clamp(20px, 2.2vw, 32px); font-weight: 700; line-height: 1.2; + margin-top: 6px; + font-size: clamp(22px, 1.95vw, 28px); font-weight: 700; line-height: 1.15; letter-spacing: -.5px; font-family: 'JetBrains Mono', monospace; - letter-spacing: -1px; + color: var(--text-primary); + white-space: nowrap; } - #kpi-cost-today { - font-size: clamp(15px, 1.3vw + 0.25rem, 20px); - white-space: normal; - word-break: keep-all; - overflow-wrap: anywhere; - line-height: 1.25; + /* 费用:updateKPI 按「 + 」拆成两段,每段整体不断开,放不下时在段之间换行;数字比其它格小一号 */ + .kpi-cost .kpi-value { + display: flex; flex-wrap: wrap; column-gap: 6px; + font-size: clamp(18px, 1.5vw, 22px); line-height: 1.25; letter-spacing: -.3px; } - .kpi-sub { font-size: 13px; color: var(--text-tertiary); margin-top: 5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 100%; } - /* ── KPI 响应式:桌面/笔记本/平板横屏(≥1024px)强制 6 列单行,杜绝数值裁剪;窄屏优雅降级 ── */ + .kpi-cost .kpi-value > span { white-space: nowrap; } + /* 副行 = 区间标签 + 数值:放不下时在两段之间换行,两段各自不断开,不截断 */ + .kpi-sub { + display: flex; flex-wrap: wrap; column-gap: 5px; + margin-top: 6px; font-size: 12px; line-height: 1.35; color: var(--text-secondary); + } + .kpi-sub-label, .kpi-sub-val { white-space: nowrap; } + /* ── KPI 响应式:平板横屏及以下转 3 列两行,手机转 2 列三行;分隔线跟着换行位置走 ── */ @media (max-width: 1023px) { .kpi-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); } + .kpi-card:nth-child(3n+1) { border-left: 0; padding-left: 24px; } + .kpi-card:nth-child(3n) { padding-right: 24px; } + .kpi-card:nth-child(n+4) { border-top: 1px solid rgba(255,255,255,.06); } } - @media (max-width: 480px) { + /* 列内边距规则按「先清 3 列、再排 2 列」的顺序写:同特异性下后写的赢,末列才是 24px */ + @media (max-width: 519px) { .kpi-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } - } - .color-blue { color: var(--accent-blue); } - .color-green { color: var(--accent-green); } - .color-yellow { color: var(--accent-yellow); } - .color-red { color: var(--accent-red); } - .color-purple { color: var(--accent-purple); } - .color-orange { color: var(--accent-orange); } - /* ── 图表网格 ── */ - .charts-grid-2 { + .kpi-card { padding: 14px 16px 12px; } + .kpi-card:nth-child(3n+1) { border-left: 1px solid rgba(255,255,255,.06); padding-left: 16px; padding-right: 16px; } + .kpi-card:nth-child(3n) { padding-right: 16px; } + .kpi-card:nth-child(2n+1) { border-left: 0; padding-left: 24px; } + .kpi-card:nth-child(2n) { padding-right: 24px; } + .kpi-card:nth-child(n+3) { border-top: 1px solid rgba(255,255,255,.06); } + } + /* ── 同一水平栏:订阅状态 | 供应商请求分布 ── + 右列放甜甜圈与图例;视口不够宽时订阅区会被挤到横向滚动,这一档改为上下堆叠 */ + .status-row { display: grid; - grid-template-columns: 1fr 2fr; - gap: 16px; + grid-template-columns: minmax(0, 1fr) clamp(280px, 24vw, 360px); + gap: var(--gap-section); margin-bottom: var(--gap-section); } - .charts-grid-2 > .card { + .status-row > .card { min-width: 0; + margin-bottom: 0; overflow: hidden; } - @media (max-width: 960px) { - .charts-grid-2 { grid-template-columns: 1fr; } + /* 分布卡随左卡等高:标题留在顶上,图形区吃掉余量,甜甜圈与图例在余量里垂直居中。 + flex-basis 取 0 而不是 auto:auto 会让图形区的高度钉在 canvas 上一次写下的像素高度上, + 左卡变矮后这一行回不去 */ + .dist-card { display: flex; flex-direction: column; } + .dist-card .chart-wrap { flex: 1 1 0; height: auto; min-height: 250px; } + @media (max-width: 1179px) { + .status-row { grid-template-columns: minmax(0, 1fr); } + .dist-card .chart-wrap { flex: none; height: 240px; min-height: 0; } } .card { background: rgba(18,22,30,.7); @@ -467,8 +472,9 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: } .btn-card-action:disabled { opacity: .35; cursor: default; } .chart-wrap { position: relative; height: 260px; min-width: 0; } - .chart-wrap-lg { position: relative; height: 260px; min-width: 0; } - .chart-wrap-xl { position: relative; height: 280px; min-width: 0; } + /* 图位高度由外层容器定死;960px 及以下 .chart-with-legend 转为纵向 flex,那里要把图位的 flex-basis 解除(见下方媒体查询) */ + .chart-wrap-lg { position: relative; height: 300px; min-width: 0; } + .chart-wrap-xl { position: relative; height: 300px; min-width: 0; } /* ── HTML Legend(单列可滚动) ── */ .chart-with-legend { display: flex; align-items: stretch; gap: 0; @@ -503,8 +509,61 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: } @media (max-width: 960px) { .chart-with-legend { flex-direction: column; } + /* 纵向 flex 下 flex-basis: 0 会让图位高度跟着 canvas 内在高度走、塌成 150px */ + .chart-with-legend > .chart-wrap-xl { flex: none; } .html-legend-wrap { flex: none; max-height: 120px; padding: 8px 0 0 0; } .html-legend-wrap ul { flex-direction: row; flex-wrap: wrap; gap: 4px 10px; } + .chart-wrap-lg, .chart-wrap-xl { height: 260px; } + } + /* ── 趋势页签:三张图共用一个图位 ── + 类名另起 trend- 前缀:.tab-btn / .tab-pane 被页首主页签的状态逻辑按类名全文档匹配,不能借用 */ + .trend-head { + display: flex; align-items: flex-end; justify-content: space-between; gap: 12px; + margin-bottom: 16px; + border-bottom: 1px solid rgba(255,255,255,.06); + } + .trend-tabs { + display: flex; gap: 4px; overflow-x: auto; scrollbar-width: none; + /* 负下边距:选中页签的 2px 下划线盖在头部 hairline 上;负左边距抵消首个页签的左内边距, + 页签文字与其它卡片标题左对齐,各页签的内边距保持一致 */ + margin: 0 0 -1px -12px; + } + /* 区间说明再长也不挤页签(≤600px 页签折行,需保留收缩,见下) */ + @media (min-width: 601px) { + .trend-tabs { flex: 0 0 auto; } + } + .trend-tabs::-webkit-scrollbar { display: none; } + .trend-tab { + appearance: none; + background: transparent; + border: 0; + border-bottom: 2px solid transparent; + padding: 8px 12px 10px; + font-family: inherit; font-size: 13px; font-weight: 500; + color: var(--text-secondary); + white-space: nowrap; cursor: pointer; + transition: color .15s ease, border-color .15s ease; + } + .trend-tab:hover { color: var(--text-primary); } + .trend-tab[aria-selected="true"] { color: var(--text-primary); border-bottom-color: var(--accent-blue); } + .trend-tab:focus-visible { outline: 2px solid var(--accent-blue); outline-offset: -2px; border-radius: 4px; } + /* 区间说明只有「近 N 天」,不换行 */ + .trend-range { + flex: 0 0 auto; padding-bottom: 11px; + font-size: 12px; line-height: 1.35; color: var(--text-secondary); + white-space: nowrap; + } + .trend-panel[hidden] { display: none; } + /* 面板可聚焦(tabpanel 惯例):焦点环画在内侧,与全页 2px 蓝色焦点环一致 */ + .trend-panel:focus-visible { outline: 2px solid var(--accent-blue); outline-offset: -2px; border-radius: 4px; } + .trend-panel .html-legend-wrap { max-height: 300px; } + @media (max-width: 960px) { + .trend-panel .html-legend-wrap { max-height: 120px; } + } + /* 手机宽度:页签折成两行而不是横向截断;区间说明收起(上方区间栏已写明当前区间) */ + @media (max-width: 600px) { + .trend-tabs { flex-wrap: wrap; overflow-x: visible; row-gap: 2px; } + .trend-range { display: none; } } /* ── 订阅状态(订阅档位 / 用量窗口 × 路由 tier 运行状态)── */ .vendor-list { display: flex; flex-direction: column; gap: 8px; } @@ -540,7 +599,7 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: } .vendor-badges::-webkit-scrollbar { display: none; } /* 分区标签(tier 名 / 模型族)统一灰字;档位是订阅的关键属性,重一级 */ - .tier-tag, .zone-label { font-size: 11px; font-weight: 500; color: var(--text-secondary); white-space: nowrap; } + .zone-label { font-size: 11px; font-weight: 500; color: var(--text-secondary); white-space: nowrap; } .zone-label.plan { font-size: 12px; font-weight: 600; color: var(--text-primary); } /* 同一模型族的标签与窗口成组 */ .qg { display: inline-flex; align-items: center; gap: 6px; } @@ -561,7 +620,6 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: border-radius: 10px; font-weight: 500; } - .sb-ok { background: rgba(63,185,80,.12); color: var(--accent-green); border: 1px solid rgba(63,185,80,.2); } .sb-warn { background: rgba(210,153,34,.12); color: var(--accent-yellow); border: 1px solid rgba(210,153,34,.2); } .sb-err { background: rgba(248,81,73,.12); color: var(--accent-red); border: 1px solid rgba(248,81,73,.2); } .sb-info { background: rgba(88,166,255,.12); color: var(--accent-blue); border: 1px solid rgba(88,166,255,.2); } @@ -593,28 +651,32 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: .drag-handle:hover, .drag-handle:focus-visible { opacity: 1 !important; color: var(--text-secondary); } /* 键盘焦点环不做淡入:调整优先级后行节点会被重建,淡入会让焦点环闪烁 */ .drag-handle:focus-visible { transition: none; } - /* 同一实体一行:[标识] [订阅区] │ [路由区]。订阅区吃掉余宽,路由区不收缩;余量不足时只由 - 订阅区内横向滚动(单行硬约束)。手柄脱离文档流落在行左内边距里 */ + /* 同一实体一行:[标识] [订阅区] [路由区]。订阅区吃掉余宽,路由区不收缩、靠行尾右对齐成一列; + 余量不足时只由订阅区内横向滚动(单行硬约束)。手柄脱离文档流落在行左内边距里 */ .vendor-item[data-vendor] { position: relative; } .has-sub > .sub-zone { flex: 1 1 auto; } - /* 路由区按「tier 名 + 状态徽章 + 一个用量格」的常见内容定最小宽:内容不超过它的行, - 分隔线彼此对齐;内容更多的行(如同时配了 5h 与周两个配额守卫)自动外扩,仅该行的分隔线左移 */ - .tier-zone { flex: 0 0 auto; min-width: 208px; } - /* 路由区紧跟订阅区时以竖线分隔(列间距 10px + 左内边距 10px,竖线居中) */ - .sub-zone + .tier-zone { padding-left: 10px; border-left: 1px solid rgba(255,255,255,.22); } + .tier-zone { flex: 0 0 auto; justify-content: flex-end; } + /* 路由区只剩可用状态:无异常是「圆点 + 正常」,异常才是彩色胶囊(.status-badge) */ + .tier-avail { display: inline-flex; align-items: center; column-gap: 6px; white-space: nowrap; } + .avail-ok { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--text-secondary); white-space: nowrap; padding: 2px 0; } + .avail-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--accent-green); } .zone-note { font-size: 11px; color: var(--text-tertiary); white-space: nowrap; } .list-note { padding: 0 14px 0 38px; font-size: 12px; } .subscription-card .vendor-list + .vendor-list { margin-top: 8px; } .subscription-card .vendor-list + .vendor-list:empty { display: none; } + /* 放不下的行仍在订阅区内横向滚动(单行硬约束不变):右缘渐隐提示「后面还有」,滚到头提示消失 + (.has-more 由 syncZoneCues 在行重绘、滚动、窗口缩放时同步) */ + .vendor-badges.has-more { + -webkit-mask-image: linear-gradient(90deg, #000 calc(100% - 28px), transparent); + mask-image: linear-gradient(90deg, #000 calc(100% - 28px), transparent); + } @media (max-width: 960px) { /* 窄屏:标识与路由区占首行,订阅区独占次行(整行放不下才折行,分区内仍不折行) */ .subscription-card .vendor-item { flex-wrap: wrap; row-gap: 6px; } .subscription-card .vendor-info { flex: 1 1 auto; min-width: 0; } - .subscription-card .tier-zone { min-width: 0; } .subscription-card .has-sub > .sub-zone { order: 3; flex: 1 1 100%; } .subscription-card .has-sub > .tier-zone, .subscription-card .has-sub > .sub-only { order: 2; flex: 0 1 auto; } - .sub-zone + .tier-zone { padding-left: 0; border-left: 0; } } /* ── 故障转移表 ── */ .ft-table-wrap { overflow-x: auto; } @@ -867,133 +929,141 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: .tab-pane { display: none; } .tab-pane.active { display: block; } - /* ── Model Calling 实时状态 ────────────────────────── */ + /* ── Model Calling 实时状态:对齐成列的 meter list ───── + 一个表面内按行列出:vendor | 模型 | 并行度条 | 在途/上限 | 排队,五列逐行对齐 */ .model-calling-card, - .subscription-card, .timeline-card { margin-bottom: var(--gap-section); } - .model-token-card { - margin-bottom: var(--gap-section); + .card-note { font-size: 12px; font-weight: 400; color: var(--text-secondary); letter-spacing: 0; white-space: nowrap; } + /* 仅供读屏的文本 */ + .sr-only { + position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; + overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; } .mc-empty { text-align: center; - color: var(--text-muted); + color: var(--text-secondary); padding: 16px 0; font-size: 13px; } - .mc-grid { + .mc-list { display: grid; - grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); - gap: 8px; - } - .mc-model-row { - display: flex; - align-items: center; - gap: 10px; - padding: 8px 12px; - background: var(--bg-secondary); - border-radius: var(--radius-sm); + grid-template-columns: minmax(0, 1fr); border: 1px solid var(--border-subtle); - } - .mc-model-name { - font-family: 'JetBrains Mono', monospace; - font-size: 12px; - color: var(--text-primary); - min-width: 140px; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - } - .mc-bar-wrap { - flex: 1; - min-width: 60px; - height: 6px; - background: rgba(255,255,255,.06); - border-radius: 3px; + border-radius: var(--radius-sm); + background: var(--bg-secondary); overflow: hidden; } - .mc-bar-fill { - height: 100%; - border-radius: 3px; - transition: width .3s ease, background .3s ease; - } - .mc-bar-fill.mc-low { background: var(--accent-green); } - .mc-bar-fill.mc-mid { background: var(--accent-yellow); } - .mc-bar-fill.mc-high { background: var(--accent-red); } - .mc-stats { - display: flex; - align-items: center; - gap: 6px; - font-size: 11px; - font-family: 'JetBrains Mono', monospace; - color: var(--text-muted); - white-space: nowrap; - } - .mc-badge { - display: inline-flex; + .mc-row { + display: grid; + /* 计数列定宽并右对齐:条形终点逐行对齐,不随「4/10」「5/8」的字数变化 */ + grid-template-columns: minmax(72px, 96px) minmax(0, 1.5fr) minmax(80px, 1fr) 64px minmax(80px, auto); align-items: center; - padding: 1px 6px; - border-radius: 4px; - font-size: 10px; - font-weight: 600; + column-gap: 12px; + min-height: 38px; + padding: 6px 16px; + } + .mc-row + .mc-row { border-top: 1px solid rgba(255,255,255,.04); } + /* 视口不少于 1280px 且不少于 3 行时排两列(更窄时模型名列连常见的带日期后缀的模型 ID 都要折行):列间竖线,行间横线 */ + @media (min-width: 1280px) { + .mc-list.mc-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .mc-list.mc-cols-2 .mc-row + .mc-row { border-top: 0; } + .mc-list.mc-cols-2 .mc-row:nth-child(n+3) { border-top: 1px solid rgba(255,255,255,.04); } + .mc-list.mc-cols-2 .mc-row:nth-child(even) { border-left: 1px solid rgba(255,255,255,.04); } + } + .mc-vendor, + .mc-model-name { font-family: 'JetBrains Mono', monospace; + overflow: hidden; min-width: 0; } - .mc-badge-pending { - background: rgba(251,146,60,.15); - color: #fb923c; - } - .mc-badge-peak { - background: rgba(148,163,184,.12); - color: #94a3b8; - } - .mc-badge-active { - background: rgba(74,222,128,.12); - color: #4ade80; - } - .mc-vendor-tag { - font-size: 10px; - color: var(--text-muted); - background: rgba(255,255,255,.06); - padding: 1px 6px; - border-radius: 3px; - } + .mc-vendor { font-size: 11px; color: var(--text-secondary); white-space: nowrap; text-overflow: ellipsis; } + /* 模型名最多折成两行:带日期后缀的模型 ID(claude-sonnet-4-5-20250929)在两列布局下放不进一行, + 折行后仍完整可读;两行还放不下才省略,全名在 title 里(title 键盘与触屏拿不到,所以不默认截断) */ + .mc-model-name { + font-size: 12px; color: var(--text-primary); + display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; + white-space: normal; overflow-wrap: anywhere; + } + .mc-meter { + height: 6px; border-radius: 3px; overflow: hidden; + background: rgba(255,255,255,.16); + } + .mc-fill { + display: block; height: 100%; border-radius: 3px; + transition: width .6s cubic-bezier(.4,0,.2,1), background .3s ease; + } + .mc-fill.mc-low { background: var(--accent-green); } + .mc-fill.mc-mid { background: var(--accent-yellow); } + .mc-fill.mc-high { background: var(--accent-red); } + /* monitor 模式没有上限:不出进度条,条的位置写明只监控 */ + .mc-meter-note { display: none; font-size: 11px; color: var(--text-secondary); white-space: nowrap; } + .mc-monitor .mc-meter { display: none; } + .mc-monitor .mc-meter-note { display: block; } + .mc-note-narrow { display: none; } + .mc-use { + display: flex; align-items: center; justify-content: flex-end; + font-family: 'JetBrains Mono', monospace; font-size: 12px; color: var(--text-secondary); + white-space: nowrap; font-variant-numeric: tabular-nums; + } + .mc-use .mc-in { font-weight: 600; color: var(--text-primary); } + .mc-use-unit { margin-left: 4px; } + /* 可编辑的上限:虚线下划线是「可点」的常驻提示,行悬停或按钮聚焦时露出铅笔图标 */ .mc-limit-editable { + appearance: none; + display: inline-flex; align-items: center; justify-content: flex-start; + /* 一位数与两位数的上限同宽:斜杠后的数字左缘逐行对齐,命中区不小于 24×24 */ + width: 40px; + background: none; + border: 0; + border-bottom: 1px dashed rgba(88,166,255,.8); + border-radius: 0; + padding: 3px 2px 3px 0; + margin: -3px 0; + min-height: 24px; + font: inherit; color: inherit; text-align: left; cursor: pointer; - border-bottom: 1px dashed rgba(74,222,128,.4); transition: border-color .2s, color .2s; } - .mc-limit-editable:hover { - border-bottom-color: #4ade80; - color: #4ade80; - } + .mc-limit-editable:hover { border-bottom-color: var(--accent-blue); color: var(--accent-blue); } + .mc-limit-editable:focus-visible { outline: 2px solid var(--accent-blue); outline-offset: 1px; border-radius: 3px; } + /* 编辑结果用静态色标而不是闪烁动画:系统开启「减少动态效果」时同样看得见 */ + .mc-limit-editable.mc-limit-ok { color: var(--accent-green); border-bottom-color: var(--accent-green); } + .mc-limit-editable.mc-limit-err { color: var(--accent-red); border-bottom-color: var(--accent-red); } + .mc-pencil { opacity: 0; margin-left: auto; flex: 0 0 auto; transition: opacity .15s ease; } + .mc-row:hover .mc-pencil, + .mc-limit-editable:focus-visible .mc-pencil { opacity: .75; } + /* 编辑输入框:与它替换掉的数字同字号,宽度与按钮相同(进入编辑态列不跳) */ .mc-limit-input { - width: 36px; - background: var(--bg-primary); + width: 40px; height: 24px; padding: 0 5px; + background: var(--bg); border: 1px solid var(--accent-blue); - border-radius: 3px; + border-radius: 4px; color: var(--text-primary); - font-size: 10px; - font-family: 'JetBrains Mono', monospace; - text-align: center; - padding: 0 2px; + font-family: 'JetBrains Mono', monospace; font-size: 12px; text-align: left; outline: none; - -moz-appearance: textfield; - } - .mc-limit-input::-webkit-outer-spin-button, - .mc-limit-input::-webkit-inner-spin-button { - -webkit-appearance: none; - margin: 0; } - .mc-limit-flash-ok { animation: mc-flash-ok .6s ease; } - .mc-limit-flash-err { animation: mc-flash-err .6s ease; } - @keyframes mc-flash-ok { - 0%,100% { color: inherit; } - 40% { color: #4ade80; } - } - @keyframes mc-flash-err { - 0%,100% { color: inherit; } - 40% { color: #f87171; } + .mc-queue { display: flex; justify-content: flex-end; white-space: nowrap; min-height: 18px; } + .mc-badge { font-size: 11px; font-weight: 500; padding: 1px 8px; border-radius: 10px; } + .mc-badge-pending { background: rgba(251,146,60,.15); color: #fb923c; } + .mc-peak { font-size: 11px; color: var(--text-secondary); } + /* 窄屏:一行放不下五列,折成两行(模型名与排队一行,vendor、并行度条与计数一行) */ + @media (max-width: 759px) { + .mc-row { + grid-template-columns: minmax(64px, 88px) minmax(0, 1fr) 88px; + grid-template-areas: "model model queue" "vendor meter use"; + column-gap: 10px; + row-gap: 8px; + padding: 10px 14px; + } + .mc-vendor { grid-area: vendor; } + .mc-model-name { grid-area: model; } + .mc-meter { grid-area: meter; } + .mc-monitor .mc-meter-note { grid-area: meter; } + .mc-use { grid-area: use; } + .mc-queue { grid-area: queue; } + .mc-note-wide { display: none; } + .mc-note-narrow { display: inline; } } /* ── 尊重「减少动态效果」系统偏好(前庭敏感用户)── */ @media (prefers-reduced-motion: reduce) { @@ -1041,91 +1111,98 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: - +
-
📊今日请求数
-
–
-
本周 –
+
今日请求数
+
–
+
–
-
🔢今日 Token 总量
-
–
-
本周 –
+
今日 Token 总量
+
–
+
–
-
💬今日输出 Token
-
–
-
本周 –
+
今日输出 Token
+
–
+
–
-
-
💰今日费用估算
-
–
-
本周 –
+
+
今日费用估算
+
–
+
–
-
🔄故障转移(今日)
-
–
-
本周 –
+
今日故障转移
+
–
+
–
-
⚡平均延迟(今日)
-
–
-
本周 –
+
今日平均延迟
+
–
+
–
-
📡 Model Calling 实时状态
+
Model Calling 实时状态每 10 秒刷新
加载中…
+ +
- -
-
🎫 订阅状态
-
-
加载中…
-
-
-
- - -
-
近 7 天请求量趋势
-
- + +
+ +
+
🎫 订阅状态
+
+
加载中…
+
+
-
- - -
-
+
供应商请求分布(近 7 天)
-
-
近 7 天 Token 量趋势(按供应商)
+
+ + +
+
+
+ + + +
+ 近 7 天 +
+ +
+
+ +
+
+ -
- - -
-
近 7 天 Token 用量(按 Vendor / 模型)
-
-
- + -
+ @@ -1300,6 +1377,10 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: Chart.defaults.font.size = 13; Chart.defaults.plugins.tooltip.usePointStyle = true; Chart.defaults.devicePixelRatio = window.devicePixelRatio || 1; + // 系统开启「减少动态效果」时关掉画布动画(页面下方的 CSS 规则管不到 canvas) + if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) { + Chart.defaults.animation = false; + } } const COMMON_SCALE_X = { grid: { display: false }, ticks: { maxTicksLimit: 10, font: { size: 12 } } }; @@ -1533,10 +1614,25 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: ctx.canvas.style.display = 'none'; const note = document.createElement('div'); note.className = 'empty'; - note.innerHTML = '
📭
暂无数据'; + note.textContent = '暂无数据'; ctx.canvas.parentElement.appendChild(note); } +// ── 图表的读屏摘要 ──────────────────────────────────────── +// canvas 里的图形与 Chart.js 自绘的图例读屏都读不到:建图时给 canvas 一句文字摘要,作为 role=img 的可访问名称 +function setChartSummary(canvas, text) { + canvas.setAttribute('role', 'img'); + canvas.setAttribute('aria-label', text); +} + +// 堆叠趋势图的摘要:区间、合计、单日最高 +function trendSummary(name, fmt, unit, dates, datasets) { + const dayTotals = dates.map((_, i) => datasets.reduce((sum, ds) => sum + (Number(ds.data[i]) || 0), 0)); + const peak = dayTotals.indexOf(Math.max(...dayTotals)); + return name + ',' + rangeLabel(overviewDays) + ':合计 ' + fmt(dayTotals.reduce((s, v) => s + v, 0)) + unit + + ',单日最高 ' + fmt(dayTotals[peak]) + unit + '(' + dates[peak] + ')'; +} + // ── 数据拉取 ────────────────────────────────────────────── async function fetchJSON(url) { const r = await fetch(url); @@ -1545,47 +1641,68 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: } // ── KPI 更新 ────────────────────────────────────────────── -function updateKPI(summary) { +// 费用串形如「¥298.96 + $412.37」:按「 + 」拆段,每段是一个整体(放不下时在段之间换行) +function costParts(cost) { + const parts = String(cost || '–').split(' + '); + return parts.map((part, i) => (i ? '+\u00a0' : '') + part); +} + +// days:这批 summary 实际取数的天数,区间标签由它生成 +function updateKPI(summary, days) { const t = summary.today, r = summary.range; - const lbl = currentRangeLabel; + const lbl = rangeLabel(days); + // 副行 = 区间标签 + 若干数值段,用 DOM API 写入(文案来自接口) + const sub = (id, label, ...values) => { + const node = document.getElementById(id); + if (!node) return; + node.replaceChildren(); + const tag = document.createElement('span'); + tag.className = 'kpi-sub-label'; + tag.textContent = label; + node.appendChild(tag); + values.forEach((value) => { + const val = document.createElement('span'); + val.className = 'kpi-sub-val'; + val.textContent = value; + node.appendChild(val); + }); + }; + const text = (id, value) => { + const node = document.getElementById(id); + if (node) node.textContent = value; + }; + const parts = (id, values) => { + const node = document.getElementById(id); + if (!node) return; + node.replaceChildren(); + values.forEach((value) => { + const val = document.createElement('span'); + val.textContent = value; + node.appendChild(val); + }); + }; - document.getElementById('kpi-req-today').textContent = fmtNum(t.requests); - document.getElementById('kpi-req-week').textContent = lbl + ' ' + fmtNum(r.requests); + text('kpi-req-today', fmtNum(t.requests)); + sub('kpi-req-week', lbl, fmtNum(r.requests)); const tokT = t.tokens, tokR = r.tokens; const totalT = tokT.input + tokT.output + tokT.cache_creation + tokT.cache_read; const totalR = tokR.input + tokR.output + tokR.cache_creation + tokR.cache_read; - document.getElementById('kpi-tok-today').textContent = fmtTokens(totalT); - document.getElementById('kpi-tok-week').textContent = lbl + ' ' + fmtTokens(totalR); - - document.getElementById('kpi-out-today').textContent = fmtTokens(tokT.output); - document.getElementById('kpi-out-week').textContent = lbl + ' ' + fmtTokens(tokR.output); - - document.getElementById('kpi-cost-today').textContent = t.cost || '–'; - document.getElementById('kpi-cost-week').textContent = lbl + ' ' + (r.cost || '–'); + text('kpi-tok-today', fmtTokens(totalT)); + sub('kpi-tok-week', lbl, fmtTokens(totalR)); + text('kpi-out-today', fmtTokens(tokT.output)); + sub('kpi-out-week', lbl, fmtTokens(tokR.output)); - document.getElementById('kpi-fo-today').textContent = fmtNum(t.failovers); - document.getElementById('kpi-fo-week').textContent = lbl + ' ' + fmtNum(r.failovers); + parts('kpi-cost-today', costParts(t.cost)); + sub('kpi-cost-week', lbl, ...costParts(r.cost)); - document.getElementById('kpi-lat-today').textContent = t.avg_duration_ms ? t.avg_duration_ms + 'ms' : '–'; - document.getElementById('kpi-lat-week').textContent = lbl + ' ' + (r.avg_duration_ms ? r.avg_duration_ms + 'ms' : '–'); + text('kpi-fo-today', fmtNum(t.failovers)); + sub('kpi-fo-week', lbl, fmtNum(r.failovers)); + text('kpi-lat-today', t.avg_duration_ms ? t.avg_duration_ms + 'ms' : '–'); + sub('kpi-lat-week', lbl, r.avg_duration_ms ? r.avg_duration_ms + 'ms' : '–'); } -// ── 订阅状态:路由区(熔断 / 配额守卫 / 限速)──────────────── -function cbStateClass(state) { - if (!state) return 'sb-ok'; - const s = state.toUpperCase(); - if (s === 'OPEN') return 'sb-err'; - if (s === 'HALF_OPEN') return 'sb-warn'; - return 'sb-ok'; -} -function cbStateLabel(state) { - if (!state) return 'CLOSED'; - const s = state.toUpperCase(); - if (s === 'OPEN') return '熔断'; - if (s === 'HALF_OPEN') return '半开'; - return '正常'; -} +// ── 订阅状态:用量格(订阅窗口共用)───────────────────────── // 用量格严重度(同时决定格底色与进度条填充色):≥ 90% 红 / ≥ 70% 黄 / 其余绿 function quotaClass(pct) { if (pct >= 90) return 'q-err'; @@ -1609,12 +1726,6 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: (reset ? `${RESET_ICON}${escapeHtml(reset)}` : '') + ``; } -function renderQuotaBar(qg) { - if (!qg || qg.usage_percent == null) return ''; - const pct = Math.round(qg.usage_percent); - const label = quotaWindowLabel(qg.window_hours); - return renderQuotaCell(label, pct, '', '本代理 ' + label + ' 滑动窗口配额守卫:已用 ' + pct + '%'); -} // 供应商行头像首字母(撞字母时取前两个字母,见 SUB_INITIALS) function _tierInitial(name) { @@ -1622,16 +1733,47 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: return SUB_INITIALS.has(text.charAt(0).toUpperCase()) ? text.charAt(0).toUpperCase() + text.charAt(1) : text.charAt(0).toUpperCase(); } -// 路由区:[状态徽章] [配额守卫用量格](本 proxy 的滑动窗口用量,与订阅区上游额度不同源) -function _tierZoneHTML(tier) { +// 路由区的可用状态:该 tier 现在能不能正常接请求。条件按熔断器、限速、配额守卫排列,多个并存时全部列出 +// (各自是独立的不可用原因);没有异常返回 null,由调用方渲染成「圆点 + 正常」 +function tierAvailability(tier) { const cb = tier.circuit_breaker || {}; const rlInfo = tier.rate_limit || {}; + const state = String(cb.state || '').toUpperCase(); // 失败次数来自载荷:转成数字再拼,非数字一律当作 0 const failures = Number(cb.failure_count) || 0; - return `${cbStateLabel(cb.state)}${failures ? ' ×' + failures : ''}` + - (rlInfo.is_rate_limited ? `限速中` : '') + - (tier.quota_guard ? renderQuotaBar(tier.quota_guard) : '') + - (tier.weekly_quota_guard ? renderQuotaBar(tier.weekly_quota_guard) : ''); + const exceeded = (g) => String((g && g.state) || '').toUpperCase() === 'QUOTA_EXCEEDED'; + const out = []; + if (state === 'OPEN') out.push({ cls: 'sb-err', text: failures ? '熔断 ×' + failures : '熔断' }); + if (state === 'HALF_OPEN') out.push({ cls: 'sb-warn', text: '半开' }); + if (rlInfo.is_rate_limited) out.push({ cls: 'sb-warn', text: '限速中' }); + if (exceeded(tier.quota_guard) || exceeded(tier.weekly_quota_guard)) out.push({ cls: 'sb-err', text: '配额超限' }); + return out.length ? out : null; +} + +// 悬停详情:不再常驻的 tier 名、熔断失败次数、限速剩余时间与配额守卫用量 +// (配额守卫是本 proxy 的滑动窗口预算,与订阅区上游额度不同源) +function tierAvailabilityTitle(tier) { + const cb = tier.circuit_breaker || {}; + const rlInfo = tier.rate_limit || {}; + const state = String(cb.state || '').toUpperCase(); + const failures = Number(cb.failure_count) || 0; + const parts = [String(tier.name || '') + ' 的路由状态']; + parts.push('熔断器 ' + ({ OPEN: '熔断', HALF_OPEN: '半开' }[state] || '正常') + (failures ? '(失败 ' + failures + ' 次)' : '')); + if (rlInfo.is_rate_limited) parts.push('限速中,剩余 ' + Math.ceil(Number(rlInfo.remaining_seconds) || 0) + ' 秒'); + [tier.quota_guard, tier.weekly_quota_guard].forEach((g) => { + if (!g || g.usage_percent == null) return; + parts.push('配额守卫 ' + quotaWindowLabel(g.window_hours) + ' 窗口已用 ' + Math.round(g.usage_percent) + '%(阈值 ' + Math.round(Number(g.threshold_percent) || 0) + '%)'); + }); + return parts.join(';'); +} + +// 路由区只留可用状态:无异常是「圆点 + 正常」,异常才是彩色胶囊,整列里异常一眼可见 +function _tierZoneHTML(tier) { + const states = tierAvailability(tier); + const inner = states + ? states.map((s) => `${s.text}`).join('') + : '正常'; + return `${inner}`; } let _tierStatus = { tiers: [] }; // 最近一次 /api/status 载荷 @@ -1777,7 +1919,7 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: const handle = reorderable ? `` : ''; const routeHTML = _tierZoneHTML(tier); if (!meta) { - // 无订阅对应的 tier 行:路由区加「供应商状态」标注,避免在订阅卡片里被读成订阅行 + // 无订阅对应的 tier 行:只有路由区(可用状态),不出订阅区 const initial = escapeHtml(_tierInitial(tier.name)); return `
@@ -1786,16 +1928,13 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: ${safeName}
- 供应商状态 ${routeHTML}
`; } - // 同一实体合并为一行:[标识] [订阅区] │ [路由区];显示名取订阅名,订阅数据缺失时也不跳变 + // 同一实体合并为一行:[标识] [订阅区] [路由区];显示名取订阅名,订阅数据缺失时也不跳变 const v = subByTier[tier.name]; const subHTML = v ? _subZoneHTML(v) : ''; - // 订阅显示名与 tier 名仅大小写不同时不重复标注 - const tag = meta.label.toLowerCase() === tier.name ? '' : `${safeName}`; return `
${handle} @@ -1803,7 +1942,7 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: ${escapeHtml(meta.label)}
${subHTML ? `
${subHTML}
` : ''} -
${tag}${routeHTML}
+
${routeHTML}
`; }).join(''); tierList.innerHTML = (tiers.length ? '' : '
🔌
无供应商数据
') + tierRows; @@ -1869,6 +2008,29 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: if (handle) handle.focus({ preventScroll: true }); } +// ── 订阅区放不下的提示:右缘渐隐 ────────────────────────── +// 行重绘由多处触发(刷新、拖拽、复位),用 MutationObserver 统一收口,不去改渲染函数 +function syncZoneCues() { + document.querySelectorAll('#subscription-card .vendor-badges').forEach(function (zone) { + zone.classList.toggle('has-more', zone.scrollWidth - zone.clientWidth - zone.scrollLeft > 1); + }); +} +(function initZoneCues() { + const card = document.getElementById('subscription-card'); + if (!card) return; + if (window.MutationObserver) { + const observer = new MutationObserver(syncZoneCues); + ['vendor-list', 'subscription-list'].forEach(function (id) { + const list = document.getElementById(id); + if (list) observer.observe(list, { childList: true, subtree: true }); + }); + } + card.addEventListener('scroll', function (e) { + if (e.target.closest && e.target.closest('.vendor-badges')) syncZoneCues(); + }, true); + window.addEventListener('resize', syncZoneCues); +})(); + // ── 订阅状态:拖拽调整优先级(Pointer Events 重排,运行时生效,不重置配额) ──── // 采用 Pointer Events 而非原生 HTML5 DnD:后者触屏不支持、跨浏览器易「拿不起来」, // 是业界公认脆弱的重排序方案(故 SortableJS / dnd-kit 等均改用指针事件)。 @@ -2101,74 +2263,136 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: }); } -// ── Model Calling 实时状态 ──────────────────────────────── +// ── Model Calling 实时状态:对齐成列的 meter list ────────── +// 行节点按 vendor/model 键复用,只改文字与条宽,不整体重建 DOM:轮询不闪,编辑并行度时也不打断输入 +const _mcRows = new Map(); // key → 行节点引用 +var _mcEditing = false; // 正在编辑并行度 +var _mcPendingEdit = null; // 编辑期间点了另一行的上限:当前编辑结束后接着打开那一行 + +function _mcRowKey(vendor, model) { return vendor + '/' + model; } + +function _mcEl(tag, cls, text) { + const node = document.createElement(tag); + if (cls) node.className = cls; + if (text != null) node.textContent = text; + return node; +} + +function _mcBuildRow(m) { + const row = _mcEl('div', 'mc-row'); + row.setAttribute('role', 'listitem'); + row.dataset.key = _mcRowKey(m.vendor, m.model); + const vendor = _mcEl('span', 'mc-vendor', m.vendor); + vendor.title = m.vendor; + const model = _mcEl('span', 'mc-model-name', m.model); + model.title = _mcRowKey(m.vendor, m.model); + const meter = _mcEl('div', 'mc-meter'); + meter.setAttribute('aria-hidden', 'true'); + const fill = _mcEl('i', 'mc-fill'); + fill.style.width = '0%'; + meter.appendChild(fill); + const meterNote = _mcEl('span', 'mc-meter-note'); + meterNote.appendChild(_mcEl('span', 'mc-note-wide', '仅监控 · 不限并行度')); + meterNote.appendChild(_mcEl('span', 'mc-note-narrow', '仅监控')); + // 上限是一个真按钮:键盘可达(Tab 聚焦、Enter / 空格触发),点击后原地变成数字输入 + const limit = _mcEl('button', 'mc-limit-editable'); + limit.type = 'button'; + limit.title = '点击修改并行度'; + limit.appendChild(_mcEl('span', 'mc-limit-val')); + limit.insertAdjacentHTML('beforeend', ''); + const use = _mcEl('span', 'mc-use'); + const inUse = _mcEl('b', 'mc-in', '0'); + const sep = _mcEl('span', 'mc-sep', '/'); + const unit = _mcEl('span', 'mc-use-unit', '进行中'); + use.append(inUse, sep, limit, unit); + const queue = _mcEl('span', 'mc-queue'); + row.append(vendor, model, meter, meterNote, use, queue); + return { row, vendor, model, meter, fill, meterNote, use, inUse, sep, limit, unit, queue, m: null }; +} + +function _mcUpdateRow(r, m) { + r.m = m; // 行缓存最近一次载荷:并行度改成功后用它就地重算,不等下一轮轮询 + const monitor = m.mode === 'monitor'; + r.row.classList.toggle('mc-monitor', monitor); + r.vendor.textContent = m.vendor; + r.model.textContent = m.model; + r.model.title = _mcRowKey(m.vendor, m.model); + if (monitor) { + r.inUse.textContent = m.in_use; + r.sep.style.display = 'none'; + r.limit.style.display = 'none'; + r.unit.style.display = ''; + } else { + const limit = m.limit || 0; + const pct = limit > 0 ? Math.round((m.in_use / limit) * 100) : 0; + r.fill.style.width = Math.min(pct, 100) + '%'; + r.fill.className = 'mc-fill ' + (pct <= 50 ? 'mc-low' : (pct <= 80 ? 'mc-mid' : 'mc-high')); + r.meter.title = '并行度 ' + m.in_use + ' / ' + limit; + r.inUse.textContent = m.in_use; + r.sep.style.display = ''; + r.limit.style.display = ''; + r.unit.style.display = 'none'; + r.limit.querySelector('.mc-limit-val').textContent = limit; + r.limit.setAttribute('aria-label', m.vendor + '/' + m.model + ' 的并行度上限,当前 ' + limit + ',点击修改'); + r.limit.setAttribute('data-limit', limit); + r.limit.setAttribute('data-tier', m.vendor); + r.limit.setAttribute('data-model', m.model); + } + const peak = m.peak_pending_recent || 0; + if (m.pending > 0) r.queue.replaceChildren(_mcEl('span', 'mc-badge mc-badge-pending', '排队 ' + m.pending)); + else if (peak > 0) r.queue.replaceChildren(_mcEl('span', 'mc-peak', '曾排队 ' + peak)); + else r.queue.replaceChildren(); +} + function updateModelCalling(status) { - var wrap = document.getElementById('model-calling-wrap'); + const wrap = document.getElementById('model-calling-wrap'); if (!wrap) return; - var tiers = status.tiers || []; - - // 收集所有带 concurrency 诊断的模型 - var models = []; - for (var i = 0; i < tiers.length; i++) { - var tier = tiers[i]; - var diag = tier.diagnostics || {}; - var conc = diag.concurrency; + // 正在编辑并行度时不碰 DOM:输入框、焦点与已输入的内容都原样保留,编辑结束后由下一轮轮询同步 + if (_mcEditing) return; + const tiers = status.tiers || []; + + const models = []; + for (const tier of tiers) { + const conc = (tier.diagnostics || {}).concurrency; if (!conc) continue; - var names = Object.keys(conc); - for (var j = 0; j < names.length; j++) { - var model = names[j]; - var d = conc[model]; + for (const model of Object.keys(conc)) { + const d = conc[model] || {}; models.push({ - vendor: tier.name, - model: model, - mode: d.mode || 'limited', - limit: d.limit, - in_use: d.in_use || 0, - available: d.available, - pending: d.pending || 0, + vendor: tier.name, model, mode: d.mode || 'limited', limit: d.limit, + in_use: d.in_use || 0, available: d.available, pending: d.pending || 0, peak_pending_recent: d.peak_pending_recent || 0, }); } } if (!models.length) { - wrap.innerHTML = '
无活跃模型调用
'; + wrap.replaceChildren(_mcEl('div', 'mc-empty', '无活跃模型调用')); + _mcRows.clear(); return; } - - var html = '
'; - for (var k = 0; k < models.length; k++) { - var m = models[k]; - - if (m.mode === 'monitor') { - // monitor 模式:纯计数徽章,无 limit/进度条 - html += '
' - + '' + escapeHtml(m.vendor + '/' + m.model) + '' - + '
' - + '
' - + '' + m.in_use + '' - + '
' - + '
'; - } else { - // limited 模式:保留现有渲染(进度条 + limit 编辑) - var limit = m.limit || 0; - var pct = limit > 0 ? Math.round((m.in_use / limit) * 100) : 0; - var barClass = pct <= 50 ? 'mc-low' : (pct <= 80 ? 'mc-mid' : 'mc-high'); - - html += '
' - + '' + escapeHtml(m.vendor + '/' + m.model) + '' - + '
' - + '
' - + '' + m.in_use - + '/' + limit + '' - + (m.pending > 0 ? '⏳ ' + m.pending + '' : '') - + (m.pending === 0 && m.peak_pending_recent > 0 ? '🕘 曾排队 ' + m.peak_pending_recent + '' : '') - + '
' - + '
'; - } + let list = wrap.querySelector('.mc-list'); + if (!list) { + wrap.replaceChildren(); + list = _mcEl('div', 'mc-list'); + list.setAttribute('role', 'list'); + wrap.appendChild(list); + } + const seen = new Set(); + models.forEach(function (m, idx) { + const key = _mcRowKey(m.vendor, m.model); + seen.add(key); + let r = _mcRows.get(key); + if (!r || !r.row.parentNode) { + r = _mcBuildRow(m); + _mcRows.set(key, r); + } + if (list.children[idx] !== r.row) list.insertBefore(r.row, list.children[idx] || null); + _mcUpdateRow(r, m); + }); + for (const [key, r] of _mcRows) { + if (!seen.has(key)) { r.row.remove(); _mcRows.delete(key); } } - html += '
'; - wrap.innerHTML = html; + list.classList.toggle('mc-cols-2', models.length >= 3); } // Model Calling 独立短间隔轮询 @@ -2188,77 +2412,120 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: } // ── 并行度运行时编辑 ────────────────────────────────────── -var _mcEditing = false; -document.addEventListener('click', function(e) { - if (_mcEditing) return; - var el = e.target.closest('.mc-limit-editable'); - if (!el) return; +// 输入只接受 1 到 20 的整数:7.5、1e2 这类输入按非法处理,不截断后提交 +function limitValue(raw) { + const text = String(raw == null ? '' : raw).trim(); + if (!/^\\d{1,2}$/.test(text)) return NaN; + const value = Number(text); + return value >= 1 && value <= 20 ? value : NaN; +} + +// 事件委托接管上限按钮的点击。编辑期间(含提交在途)_mcEditing 为真、轮询不重绘:这时点了另一行的上限, +// 先记入 _mcPendingEdit,由当前编辑的 restore 接着打开,这次点击不被吞掉。 +// 提交带在途守卫与 8 秒超时,请求悬住时也能解除编辑态;结束编辑后焦点回到按钮; +// 结果用静态色标并写进 role=status 节点供读屏播报 +document.addEventListener('click', function (e) { + const btn = e.target.closest('.mc-limit-editable'); + if (!btn) return; + if (_mcEditing) { _mcPendingEdit = btn; return; } e.preventDefault(); + startLimitEdit(btn); +}); + +// 播报节点 #mc-live 写在模板里:动态插入的 live region,首条内容可能被读屏漏掉 +function _mcAnnounce(text) { + const live = document.getElementById('mc-live'); + if (!live) return; + live.textContent = ''; + setTimeout(function () { live.textContent = text; }, 30); +} + +function startLimitEdit(btn) { _mcEditing = true; - var oldVal = el.getAttribute('data-limit'); - var tier = el.getAttribute('data-tier'); - var model = el.getAttribute('data-model'); - var input = document.createElement('input'); - input.type = 'number'; + const oldVal = btn.getAttribute('data-limit'); + const tier = btn.getAttribute('data-tier'); + const model = btn.getAttribute('data-model'); + const input = document.createElement('input'); + input.type = 'text'; + input.inputMode = 'numeric'; input.className = 'mc-limit-input'; - input.min = '1'; - input.max = '20'; + input.setAttribute('aria-label', tier + '/' + model + ' 的并行度上限(1 到 20 的整数)'); input.value = oldVal; - el.style.display = 'none'; - el.parentNode.insertBefore(input, el.nextSibling); + btn.style.display = 'none'; + btn.parentNode.insertBefore(input, btn.nextSibling); input.focus(); input.select(); - var _cancelled = false; - - function restore() { + let done = false; + let inFlight = false; // PUT 未决期间不再接受第二次提交 + const restore = function () { + if (done) return; + const hadFocus = document.activeElement === input; + done = true; // 先落标记再移除输入框:移除引发的 blur 不会再提交 _mcEditing = false; - if (input.parentNode) input.parentNode.removeChild(input); - el.style.display = ''; - } - - function flash(cls) { - el.classList.add(cls); - setTimeout(function() { el.classList.remove(cls); }, 600); - } - - input.addEventListener('keydown', function(ev) { - if (ev.key === 'Escape') { _cancelled = true; restore(); return; } + input.remove(); + btn.style.display = ''; + // 编辑期间点了另一行的上限:接着编辑那一行。期间焦点已被用户移到别处就作罢,不抢焦点 + const next = _mcPendingEdit; + _mcPendingEdit = null; + const idle = document.activeElement === next || document.activeElement === document.body; + if (next && next.isConnected && idle) { startLimitEdit(next); return; } + if (hadFocus) btn.focus(); // 回车 / Esc 结束后焦点回到上限按钮,键盘用户不用从头 Tab + }; + let markTimer = null; + const mark = function (cls) { + btn.classList.remove('mc-limit-ok', 'mc-limit-err'); + clearTimeout(markTimer); + btn.classList.add(cls); + markTimer = setTimeout(function () { btn.classList.remove(cls); }, 1500); + }; + const submit = function () { + if (done || inFlight) return; + const value = limitValue(input.value); + if (isNaN(value)) { restore(); mark('mc-limit-err'); _mcAnnounce('并行度须是 1 到 20 的整数'); return; } + if (String(value) === oldVal) { restore(); return; } + inFlight = true; + // 8 秒兜底:请求悬住(网络挂起、fetch 不响应 abort)时也解除编辑态,不让整张表停在「编辑中」 + const controller = typeof AbortController === 'function' ? new AbortController() : null; + let timeoutId = null; + const timeout = new Promise(function (_, reject) { + timeoutId = setTimeout(function () { reject(new Error('timeout')); if (controller) controller.abort(); }, 8000); + }); + const request = fetch('/api/concurrency', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ tier: tier, model: model, limit: value }), + signal: controller ? controller.signal : undefined, + }); + Promise.race([request, timeout]).then(function (res) { + if (!res.ok) throw new Error(String(res.status)); + btn.querySelector('.mc-limit-val').textContent = value; + btn.setAttribute('data-limit', value); + // 就地重算这一行(条形、可访问名称立刻自洽),再拉一次状态对齐服务端 + const row = _mcRows.get(_mcRowKey(tier, model)); + if (row && row.m && row.m.mode !== 'monitor') { row.m.limit = value; _mcUpdateRow(row, row.m); } + mark('mc-limit-ok'); + _mcAnnounce(tier + '/' + model + ' 的并行度已更新为 ' + value); + fetchJSON('/api/status').then(function (status) { updateModelCalling(status); }).catch(function () {}); + }).catch(function () { + mark('mc-limit-err'); + _mcAnnounce(tier + '/' + model + ' 的并行度更新失败'); + }).finally(function () { + clearTimeout(timeoutId); + inFlight = false; + restore(); + }); + }; + input.addEventListener('keydown', function (ev) { + if (ev.key === 'Escape') { restore(); return; } if (ev.key !== 'Enter') return; ev.preventDefault(); submit(); }); - - input.addEventListener('blur', function() { - setTimeout(function() { if (!_cancelled) submit(); }, 50); + input.addEventListener('blur', function () { + setTimeout(function () { if (!done) submit(); }, 50); }); - - function submit() { - if (_cancelled) return; - var v = parseInt(input.value, 10); - if (isNaN(v) || v < 1 || v > 20) { restore(); flash('mc-limit-flash-err'); return; } - if (String(v) === oldVal) { restore(); return; } - fetch('/api/concurrency', { - method: 'PUT', - headers: {'Content-Type': 'application/json'}, - body: JSON.stringify({tier: tier, model: model, limit: v}) - }).then(function(res) { - if (res.ok) { - return res.json().then(function() { - el.textContent = v; - el.setAttribute('data-limit', v); - flash('mc-limit-flash-ok'); - }); - } else { - flash('mc-limit-flash-err'); - } - }).catch(function() { - flash('mc-limit-flash-err'); - }).finally(function() { - restore(); - }); - } -}); +} // ── 按 tiers 顺序排序 vendor 列表 ───────────────────────── function sortByTierOrder(vendors, tierOrder) { @@ -2287,8 +2554,12 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: const dates = [...allDates].sort(); const vendors = sortByTierOrder(Object.keys(vendorDateMap), tierOrder); - if (chartTimeline) chartTimeline.destroy(); - const ctx = document.getElementById('chart-timeline').getContext('2d'); + if (chartTimeline) { chartTimeline.destroy(); chartTimeline = null; } + const ctx = chartContext('chart-timeline'); + if (!dates.length) { + chartEmpty(ctx); + return; + } const datasets = vendors.map((v, i) => { const color = VENDOR_COLORS[i % VENDOR_COLORS.length]; return { @@ -2297,9 +2568,11 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: data: dates.map(d => vendorDateMap[v][d] || 0), borderColor: color, backgroundColor: color + '30', - fill: true, + // 真堆叠面积:每条线填充到上一条堆叠线,首条填到底;各自填到底会叠成灰褐色 + fill: i === 0 ? 'start' : '-1', }; }); + setChartSummary(ctx.canvas, trendSummary('请求量趋势', fmtNum, ' 次', dates, datasets)); chartTimeline = new Chart(ctx, { type: 'line', @@ -2324,6 +2597,18 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: } // ── 供应商分布环形图 ────────────────────────────────────── +// 图例位置:Chart.js 给右侧图例最多一半画布宽,最长的标签(「agy | antigravity」实测约 130px)放不下时会被裁掉。 +// 并排右列在约 1210px 视口以下放不下,这时图例移到下方自动换行。宽度用 Chart.js 自己的字体量出来,不另抄一份 +function distLegendPosition(ctx, labels, canvasWidth) { + const opts = COMMON_LEGEND.labels; + const font = Chart.helpers.toFont(opts.font); + ctx.save(); + ctx.font = font.string; + const widest = labels.reduce((w, text) => Math.max(w, opts.boxWidth + font.size / 2 + ctx.measureText(text).width), 0); + ctx.restore(); + return canvasWidth >= 2 * (opts.padding + widest) ? 'right' : 'bottom'; +} + function buildVendorDist(rows, tierOrder) { const vendorTotals = {}; for (const r of rows) { @@ -2340,10 +2625,14 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: chartEmpty(ctx); return; } + const total = data.reduce((s, v) => s + v, 0); + const legendLabels = labels.map(formatVendorLabel); + setChartSummary(ctx.canvas, '供应商请求分布,' + rangeLabel(overviewDays) + ':共 ' + fmtNum(total) + ' 次请求;' + + legendLabels.map((text, i) => text + ' ' + (total ? Math.round((data[i] / total) * 100) : 0) + '%').join(',')); chartVendorDist = new Chart(ctx, { type: 'doughnut', data: { - labels: labels.map(formatVendorLabel), + labels: legendLabels, datasets: [{ data, backgroundColor: labels.map((_,i) => VENDOR_COLORS[i % VENDOR_COLORS.length]), @@ -2354,9 +2643,11 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: options: { responsive: true, maintainAspectRatio: false, cutout: '55%', + // 建图与每次尺寸变化都会经过这里:跨过并排 / 堆叠断点、右列变宽变窄时图例位置跟着走 + onResize: function (chart, size) { chart.options.plugins.legend.position = distLegendPosition(chart.ctx, chart.data.labels, size.width); }, plugins: { legend: { - position: 'right', + position: distLegendPosition(ctx, legendLabels, ctx.canvas.parentElement.clientWidth), onClick: legendOnClick, labels: { ...COMMON_LEGEND.labels, @@ -2404,7 +2695,7 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: const dates = [...allDates].sort(); const vendors = sortByTierOrder(Object.keys(vendorDateMap), tierOrder); - if (chartTokenTimeline) chartTokenTimeline.destroy(); + if (chartTokenTimeline) { chartTokenTimeline.destroy(); chartTokenTimeline = null; } const ctx = chartContext('chart-token-timeline'); if (!dates.length) { chartEmpty(ctx); @@ -2419,9 +2710,11 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: data: dates.map(d => vendorDateMap[v][d] || 0), borderColor: color, backgroundColor: color + '30', - fill: true, + // 真堆叠面积:每条线填充到上一条堆叠线,首条填到底;各自填到底会叠成灰褐色 + fill: i === 0 ? 'start' : '-1', }; }); + setChartSummary(ctx.canvas, trendSummary('Token 量趋势(按供应商)', fmtTokens, ' Token', dates, datasets)); chartTokenTimeline = new Chart(ctx, { type: 'line', @@ -2469,7 +2762,7 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: return sumB - sumA; }); - if (chartModelTokenTimeline) chartModelTokenTimeline.destroy(); + if (chartModelTokenTimeline) { chartModelTokenTimeline.destroy(); chartModelTokenTimeline = null; } const ctx = chartContext('chart-model-token-timeline'); // 清理 HTML Legend 容器 @@ -2494,7 +2787,8 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: data: dates.map(d => modelDateMap[key][d] || 0), borderColor: color, backgroundColor: color + '30', - fill: true, + // 真堆叠面积:每条线填充到上一条堆叠线,首条填到底;各自填到底会叠成灰褐色 + fill: i === 0 ? 'start' : '-1', }; }); @@ -2514,6 +2808,8 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: }, }; + setChartSummary(ctx.canvas, trendSummary('Token 用量趋势(Vendor / 模型)', fmtTokens, ' Token', dates, datasets)); + chartModelTokenTimeline = new Chart(ctx, { type: 'line', data: { labels: dates, datasets }, @@ -2548,12 +2844,24 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: // ── 时间区间控制 ────────────────────────────────────────── let currentDays = 7; -let currentRangeLabel = '本周'; +let overviewDays = 0; // Overview 最近一次成功取数用的天数(0 = 尚未取数) +// 与服务端 summary / timeline 接口的天数上限一致:接口只收 days,超出部分不取数 +const MAX_RANGE_DAYS = 90; + +// 本地日期的 YYYY-MM-DD(toISOString 给的是 UTC 日期:东八区 0 到 8 点会写成昨天) +function localDateStr(d) { + return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); +} + +// 区间标签:KPI 副行、趋势页签说明、分布图标题共用同一口径,一律「近 N 天」。入参是这次取数实际用的天数, +// 不是页面当前选中的区间:刷新途中改了区间,已上屏的数据仍属于旧区间,标签要跟数据走。 +// 自选区间也只折算成天数:接口取的是截至今天的最近 N 天,区间栏里选的起止日期不是取数窗口,写成起止日期会和横轴对不上 +function rangeLabel(days) { + return '近 ' + days + ' 天'; +} function setTimeRange(days, btn) { currentDays = days; - if (days === 7) currentRangeLabel = '本周'; - else if (days === 30) currentRangeLabel = '本月'; // 仅限时间区间栏:Config 页的 section pills 复用 .range-btn document.querySelectorAll('.time-range-bar .range-btn').forEach(b => b.classList.remove('active')); if (btn) btn.classList.add('active'); @@ -2563,8 +2871,8 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: const today = new Date(); const weekAgo = new Date(today); weekAgo.setDate(weekAgo.getDate() - 6); - document.getElementById('range-end').value = today.toISOString().slice(0, 10); - document.getElementById('range-start').value = weekAgo.toISOString().slice(0, 10); + document.getElementById('range-end').value = localDateStr(today); + document.getElementById('range-start').value = localDateStr(weekAgo); applyCustomRange(); } else { customEl.classList.remove('visible'); @@ -2579,23 +2887,77 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: const startMs = new Date(s).getTime(); const endMs = new Date(e).getTime(); if (endMs < startMs) return; - currentDays = Math.ceil((endMs - startMs) / 86400000) + 1; - currentRangeLabel = s + '—' + e; + currentDays = Math.min(MAX_RANGE_DAYS, Math.ceil((endMs - startMs) / 86400000) + 1); refresh(); } +// 区间说明同步到分布图标题与趋势页签行(三张趋势图的标题就是页签文案,不带区间) function updateChartTitles(days) { - const label = days <= 7 ? '近 7 天' : (days <= 30 ? '近 30 天' : '近 ' + days + ' 天'); - const tl = document.getElementById('title-timeline'); - const tt = document.getElementById('title-token-timeline'); + const label = rangeLabel(days); const vd = document.getElementById('title-vendor-dist'); - const mt = document.getElementById('title-model-token-timeline'); - if (tl) tl.textContent = label + ' 请求量趋势'; - if (tt) tt.textContent = label + ' Token 量趋势(按供应商)'; if (vd) vd.textContent = '供应商请求分布(' + label + ')'; - if (mt) mt.textContent = label + ' Token 用量(按 Vendor / 模型)'; + const range = document.getElementById('trend-range'); + if (range) range.textContent = label; +} + +// ── 趋势页签:三张图共用一个图位 ────────────────────────── +// 三张图在刷新时一并重建,非当前页签 hidden;切换只改显示,不做懒建。 +// 类名另起 trend- 前缀:applyTabState / switchTab 按 .tab-btn / .tab-pane 全文档匹配,借用量会被主页签逻辑误伤 +const TREND_CHARTS = { + requests: 'chart-timeline', + tokens: 'chart-token-timeline', + models: 'chart-model-token-timeline', +}; + +// 面板由隐藏变可见后让 Chart.js 按容器尺寸重算并直接出终帧:它在 resize 里会先建一段 attach 动画, +// 只调 update('none') 取消不了在途动画,要先 stop +function showTrendChart(key) { + const instance = window.Chart ? Chart.getChart(TREND_CHARTS[key]) : null; + if (instance) { instance.resize(); instance.stop(); instance.update('none'); } } +function setTrendTab(key, focus) { + document.querySelectorAll('.trend-tab').forEach(function (tab) { + const on = tab.dataset.trend === key; + tab.setAttribute('aria-selected', on ? 'true' : 'false'); + tab.tabIndex = on ? 0 : -1; + }); + document.querySelectorAll('.trend-panel').forEach(function (panel) { + const on = panel.id === 'trend-panel-' + key; + panel.hidden = !on; + if (on) showTrendChart(key); + }); + if (focus) { + const tab = document.getElementById('trend-tab-' + key); + if (tab) tab.focus(); + } +} + +(function initTrendTabs() { + const tablist = document.querySelector('.trend-tabs'); + if (!tablist) return; + tablist.addEventListener('click', function (e) { + const tab = e.target.closest('.trend-tab'); + if (tab) setTrendTab(tab.dataset.trend, false); + }); + // 方向键在页签间循环,Home / End 到首尾;焦点移到哪个页签就选中哪个 + // (automatic activation:面板内容都已在 DOM 里,切换没有延迟) + tablist.addEventListener('keydown', function (e) { + const tab = e.target.closest('.trend-tab'); + if (!tab) return; + const keys = Array.from(tablist.querySelectorAll('.trend-tab'), function (t) { return t.dataset.trend; }); + const i = keys.indexOf(tab.dataset.trend); + let next = null; + if (e.key === 'ArrowRight') next = keys[(i + 1) % keys.length]; + else if (e.key === 'ArrowLeft') next = keys[(i - 1 + keys.length) % keys.length]; + else if (e.key === 'Home') next = keys[0]; + else if (e.key === 'End') next = keys[keys.length - 1]; + if (next == null) return; + e.preventDefault(); + setTrendTab(next, true); + }); +})(); + // ── Sessions Panel ────────────────────────────────────────────── function relativeTime(tsStr) { if (!tsStr) return '–'; @@ -2854,11 +3216,14 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: fetchJSON('/api/dashboard/subscriptions').catch(function () { return { vendors: [] }; }), ]); + // 这批数据实际取数的天数:区间标签与图表摘要读它,不读页面当前选中的区间 + overviewDays = days; + if (summary.version) { document.getElementById('version-badge').textContent = 'v' + summary.version; } - updateKPI(summary); + updateKPI(summary, days); // 行数据与随后的订阅数据到齐后只重绘一次:连续替换行节点会让键盘焦点环闪烁 updateVendorStatus(status, true); updateModelCalling(status); @@ -2882,9 +3247,11 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: if (refreshing) return; refreshing = true; try { - // 循环:若 await 期间用户切到了尚未加载的另一页签,补一次刷新,避免 tabLoaded 错位。 + // 循环:若 await 期间用户切到了尚未加载的另一页签,或改了时间区间,补一次刷新, + // 避免 tabLoaded 错位、或新区间的点击被在途标记挡掉后没有下文。 while (true) { const tab = currentTab; + let ok = false; document.getElementById('refresh-time').textContent = '刷新中…'; try { if (tab === 'config') { @@ -2895,6 +3262,7 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: await refreshOverview(); } tabLoaded[tab] = true; + ok = true; if (tab === currentTab) { document.getElementById('refresh-time').textContent = '上次刷新: ' + now() + '(' + TAB_LABELS[tab] + ')'; @@ -2904,6 +3272,8 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response: document.getElementById('refresh-time').textContent = '刷新失败 ' + now(); } if (currentTab !== tab && !tabLoaded[currentTab]) continue; + // 取数成功但区间已在途中改掉:按新区间再取一次(取数失败不重试,否则接口不可达时会空转) + if (ok && tab === 'overview' && overviewDays !== currentDays) continue; break; } } finally { diff --git a/src/coding/proxy/server/generations.py b/src/coding/proxy/server/generations.py index ba09409f..447594f3 100644 --- a/src/coding/proxy/server/generations.py +++ b/src/coding/proxy/server/generations.py @@ -671,7 +671,7 @@ def _migrate_bindings( ) catalog = { str(entry.get("model")) - for entry in (router.get_bindable_models() if router else []) + for entry in (router.get_known_models() if router else []) } dropped = 0 model_dropped = 0 diff --git a/src/coding/proxy/server/routes.py b/src/coding/proxy/server/routes.py index 061256cf..3a219217 100644 --- a/src/coding/proxy/server/routes.py +++ b/src/coding/proxy/server/routes.py @@ -477,7 +477,13 @@ async def bind_session_vendor(request: Request) -> Response: if model is not None: model = model.strip() if not any(m.get("model") == model for m in bindable): - if not bindable: + known = {str(m.get("model")) for m in router.get_known_models()} + if model in known: + message = ( + f"model is offline (pricing online=false): {model}; " + "set the pricing row online to re-enable binding" + ) + elif not bindable: message = ( "model binding is disabled: " "session_policies.bindable_models is empty or unset in " diff --git a/src/coding/proxy/server/static/config/config.css b/src/coding/proxy/server/static/config/config.css index 57d469cc..fe9b2712 100644 --- a/src/coding/proxy/server/static/config/config.css +++ b/src/coding/proxy/server/static/config/config.css @@ -1,6 +1,7 @@ /* Dashboard → Config 页样式(深色主题,复用 dashboard :root token). * 规范:表格固定列宽(同属性同宽 token)、单行 + 省略号 + tooltip; - * 表单行 label 恰占 1/12、ⓘ 独占右侧 20px、控件同一行。 + * 表单行 label 占行宽 1/12(下限 104px,窗口变窄时不截断)、ⓘ 独占右侧 20px、控件同一行; + * 视口 ≤640px 时 label 与控件分两行。 */ /* 列宽 token(--col-*)定义在 dashboard :root,与 Sessions 表共用 */ #config-root { color-scheme: dark; --cfg-control-bg: rgba(48,54,61,.4); } @@ -27,6 +28,9 @@ /* ── 卡片与分组 ── */ .cfg-body { margin-bottom: 72px; } +/* 表单卡每次 rerender 都会重建:不重放入场动画,也不做 hover 抬升 */ +.card.cfg-body, .card.cfg-lock { animation: none; } +.card.cfg-body:hover { box-shadow: var(--shadow); } .cfg-body[inert] { opacity: .65; pointer-events: none; } /* 保存进行中冻结表单(pointer-events 兜底不支持 inert 的浏览器) */ .cfg-section-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin: 4px 0 12px; } .cfg-section-title { @@ -48,7 +52,7 @@ /* ── 表单行:[label 恰占行宽 1/12][ⓘ 20px][control] 同一行(详情卡内同样适用) ── */ .cfg-row { - display: grid; grid-template-columns: calc(100% / 12) 20px minmax(0, 1fr); + display: grid; grid-template-columns: minmax(104px, calc(100% / 12)) 20px minmax(0, 1fr); align-items: center; min-height: 36px; padding: 3px 0; } .cfg-label { font-size: 13px; color: var(--text-secondary); padding-right: 6px; cursor: default; } @@ -69,7 +73,7 @@ .cfg-info:hover, .cfg-info:focus-visible { color: var(--accent-blue); outline: none; background: rgba(88,166,255,.1); } .cfg-tip { display: none; position: absolute; left: 22px; top: 50%; transform: translateY(-50%); z-index: 20; - width: max-content; max-width: 360px; padding: 8px 10px; white-space: normal; + width: max-content; max-width: min(360px, calc(100vw - 3rem)); padding: 8px 10px; white-space: normal; font-size: 12px; font-weight: 400; line-height: 1.5; color: var(--text-primary); text-transform: none; letter-spacing: 0; background: rgba(10,14,20,.97); border: 1px solid rgba(255,255,255,.1); border-radius: var(--radius-sm); box-shadow: var(--shadow-md); @@ -121,6 +125,13 @@ span.cfg-map-key { color: var(--text-secondary); } .cfg-btn-primary { background: rgba(88,166,255,.16); border-color: rgba(88,166,255,.35); color: var(--accent-blue); } .cfg-btn-primary:hover:not(:disabled) { background: rgba(88,166,255,.24); color: #fff; } .cfg-btn-danger:hover:not(:disabled) { color: var(--accent-red); border-color: rgba(248,81,73,.4); } +/* 大范围操作的入口降权:透明底,hover 才显形 */ +.cfg-btn-ghost { background: transparent; border-color: transparent; } +.cfg-btn-ghost:hover:not(:disabled) { background: rgba(255,255,255,.06); border-color: transparent; color: var(--text-primary); } +.cfg-vendor-head .cfg-actions .cfg-btn-danger { margin-left: 8px; } +/* 确认框的主按钮在破坏性操作上用 danger */ +.cfg-btn-primary.cfg-btn-danger-solid { background: rgba(248,81,73,.16); border-color: rgba(248,81,73,.45); color: var(--accent-red); } +.cfg-btn-primary.cfg-btn-danger-solid:hover:not(:disabled) { background: rgba(248,81,73,.24); border-color: var(--accent-red); color: #fff; } .cfg-link { border: none; background: none; padding: 0; max-width: 100%; cursor: pointer; font: inherit; color: var(--accent-blue); text-align: left; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; @@ -140,6 +151,10 @@ span.cfg-map-key { color: var(--text-secondary); } .cfg-row-open > td { background: rgba(88,166,255,.05); } .cfg-detail-row > td { padding: 0 0 6px; white-space: normal; overflow: visible; } .cfg-detail { margin: 4px 0 0; padding: 12px 16px; } +@media (prefers-reduced-motion: no-preference) { + .cfg-list-row.cfg-row-new > td { animation: cfg-row-new 2s ease-out; } +} +@keyframes cfg-row-new { from { background: rgba(88,166,255,.24); } to { background: rgba(88,166,255,.05); } } /* ── Banner / 保存栏 / 对话框 ── */ .cfg-banner { @@ -159,6 +174,25 @@ span.cfg-map-key { color: var(--text-secondary); } } .cfg-savebar[hidden] { display: none; } .cfg-savebar-msg { flex: 1; min-width: 0; font-size: 13px; color: var(--text-secondary); } +.cfg-savebar-msg > * + * { margin-top: 2px; } +.cfg-savebar-ok { border-color: rgba(63,185,80,.35); } +.cfg-savebar-warn { border-color: rgba(210,153,34,.45); } +.cfg-savebar-err { border-color: rgba(248,81,73,.45); } +.cfg-result { display: flex; align-items: baseline; flex-wrap: wrap; gap: 2px 8px; color: var(--text-primary); } +.cfg-result:focus { outline: none; } +.cfg-result:focus-visible { outline: 2px solid var(--accent-blue); outline-offset: 2px; } +.cfg-result-dot { flex: none; align-self: center; width: 8px; height: 8px; border-radius: 50%; background: var(--text-tertiary); } +.cfg-savebar-ok .cfg-result-dot { background: var(--accent-green); } +.cfg-savebar-warn .cfg-result-dot { background: var(--accent-yellow); } +.cfg-savebar-err .cfg-result-dot { background: var(--accent-red); } +.cfg-result .cfg-note { flex-basis: 100%; margin: 0; max-height: 72px; overflow-y: auto; } +.cfg-undo { display: flex; align-items: center; gap: 8px; min-width: 0; } +.cfg-undo .cfg-link { flex: none; } +.cfg-scope { color: var(--text-secondary); } +/* 保存栏常驻时,键盘焦点不被它盖住 */ +html:has(#config-root .cfg-savebar:not([hidden])) { scroll-padding-bottom: 120px; } +#config-root [data-focus-ring]:focus { outline: 2px solid var(--accent-blue); outline-offset: 2px; } +.cfg-live { position: absolute; width: 1px; height: 1px; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; } .cfg-savebar-errors { list-style: none; margin: 4px 0 0; padding: 0; max-height: 120px; overflow-y: auto; } .cfg-savebar-errors .cfg-link { color: var(--accent-red); font-size: 12px; } .cfg-lock { max-width: 720px; } @@ -173,9 +207,28 @@ span.cfg-map-key { color: var(--text-secondary); } .cfg-dialog-block { margin: 12px 0; font-size: 13px; } .cfg-dialog-block ul { margin: 0; padding-left: 18px; color: var(--text-secondary); } .cfg-dialog-block li { overflow-wrap: anywhere; } +.cfg-dialog-text { margin: 8px 0 2px; font-size: 13px; line-height: 1.55; color: var(--text-secondary); } +.cfg-dialog-impact li { padding: 1px 0; } +.cfg-diff-group-title { margin-top: 6px; font-size: 12px; color: var(--text-tertiary); } +.cfg-diff-row { display: grid; grid-template-columns: minmax(120px, 34%) minmax(0, 1fr); gap: 8px; padding: 1px 0; font-size: 13px; color: var(--text-secondary); } +.cfg-diff-val { font-family: 'JetBrains Mono', monospace; font-size: 12px; color: var(--text-primary); min-width: 0; overflow-wrap: anywhere; } +.cfg-diff-val del { color: var(--text-tertiary); } +.cfg-diff-val ins { color: var(--accent-blue); text-decoration: none; } +.cfg-dialog details > summary { cursor: pointer; color: var(--accent-blue); } +.cfg-dialog details[open] > summary { margin-bottom: 4px; } .cfg-dialog-warn .cfg-group-title, .cfg-dialog-warn li { color: var(--accent-yellow); } .cfg-dialog .cfg-actions { margin-top: 16px; } @media (max-width: 960px) { .cfg-input, .cfg-secret-input, .cfg-lock-row .cfg-input { width: 100%; } } +@media (max-width: 640px) { + .cfg-row { grid-template-columns: minmax(0, max-content) 20px; justify-content: start; row-gap: 4px; } + .cfg-control { grid-column: 1 / -1; padding-left: 0; } + .cfg-control > .cfg-input { flex: 1 1 140px; width: auto; } + .cfg-control > .cfg-unit { flex: none; } + /* 说明气泡改为贴着行的左缘展开,停在视口内(ⓘ 在两行布局下位于 label 右侧,向右展开会出屏) */ + .cfg-row { position: relative; } + .cfg-row .cfg-info-wrap { position: static; } + .cfg-row .cfg-tip { left: 0; top: 100%; transform: none; max-width: calc(100vw - 5rem); } /* 展开在行的下方,不盖住自己的 ⓘ */ +} diff --git a/src/coding/proxy/server/static/config/config.js b/src/coding/proxy/server/static/config/config.js index 4b4dd3a1..a0d092a9 100644 --- a/src/coding/proxy/server/static/config/config.js +++ b/src/coding/proxy/server/static/config/config.js @@ -204,6 +204,89 @@ return newDefaultRows(work, newDefaultRows(base, defaults)); } + // 字段级 diff(保存确认框用):对象按路径递归;vendors 按 vendor 名配对;列表型 section 按行键配对 + var ROW_KEY = { + pricing: ['vendor', 'model'], model_mapping: ['pattern'], 'session_policies.policies': ['name'], + 'session_policies.bindable_models': ['label'], 'session_policies.title_vendor_bindings': ['prefix'], + }; + function rowKeyOf(sec, row) { + var ks = ROW_KEY[sec]; + return ks && isObj(row) ? ks.map(function (k) { return String(row[k]); }).join('/') : JSON.stringify(row); + } + function shortVal(v) { + var s = Array.isArray(v) ? (v.length ? v.map(String).join(' → ') : '[]') : fmtVal(v); + return s.length > 60 ? s.slice(0, 57) + '…' : s; + } + function maskUrl(v) { return typeof v === 'string' ? v.replace(/\/\/[^/@\s]+@/, '//***@') : v; } + function diffLeaves(a, b, path, out, o) { + if (deepEqual(a, b)) return; + if (Array.isArray(a) && Array.isArray(b) && ROW_KEY[path]) { diffRows(path, a, b, out, o); return; } + if (isObj(a) && isObj(b)) { + Object.keys(a).concat(Object.keys(b).filter(function (k) { return !(k in a); })) + .forEach(function (k) { if (!o.skip(path + '.' + k)) diffLeaves(a[k], b[k], path + '.' + k, out, o); }); + return; + } + out.push({ path: path, label: o.label(path), before: maskUrl(shortVal(a)), after: maskUrl(shortVal(b)) }); + } + function diffRows(sec, a, b, out, o) { + var pool = {}, hit = {}; + (b || []).forEach(function (r, j) { var k = rowKeyOf(sec, r); (pool[k] = pool[k] || []).push(j); }); + (a || []).forEach(function (r, i) { + var q = pool[rowKeyOf(sec, r)]; + if (q && q.length) { var j = q.shift(); hit[j] = true; diffLeaves(r, b[j], sec + '.' + j, out, o); } + else out.push({ path: sec + '.' + i, label: o.rowTitle(sec, r), before: '', after: '', removed: true }); + }); + (b || []).forEach(function (r, j) { if (!hit[j]) out.push({ path: sec + '.' + j, label: o.rowTitle(sec, r), before: '', after: '', added: true }); }); + } + // 返回按 section 分组的差异行;数组型 section 只给「新增 / 移除 / 同键条目的字段变化」 + function changedRows(base, work, o) { + var groups = [], open = function (title) { var g = { title: title, rows: [] }; groups.push(g); return g.rows; }; + dirtySections(base, work).forEach(function (s) { + if (s === 'vendors') { + var a = vendorMap(base.vendors), b = vendorMap(work.vendors); + var oa = (base.vendors || []).map(function (v) { return v.vendor; }), ob = (work.vendors || []).map(function (v) { return v.vendor; }); + if (oa.join('\u0000') !== ob.join('\u0000') && oa.slice().sort().join('\u0000') === ob.slice().sort().join('\u0000')) { + open(o.sectionLabel(s)).push({ path: 'vendors', label: '顺序', before: oa.join(' → '), after: ob.join(' → ') }); + } + Object.keys(a).concat(Object.keys(b).filter(function (t) { return !(t in a); })).forEach(function (t) { + var rows = open(o.sectionLabel(s) + ' › ' + t); + if (!a[t]) rows.push({ path: 'vendors.' + t, label: t, before: '', after: '', added: true }); + else if (!b[t]) rows.push({ path: 'vendors.' + t, label: t, before: '', after: '', removed: true }); + else diffLeaves(a[t], b[t], 'vendors.' + t, rows, o); + }); + return; + } + var rows = open(o.sectionLabel(s)); + if (Array.isArray(base[s]) || Array.isArray(work[s])) diffRows(s, base[s] || [], work[s] || [], rows, o); + else diffLeaves(base[s], work[s], s, rows, o); + }); + return groups.filter(function (g) { return g.rows.length; }); + } + // 保存后果清单(非空才弹确认框):只返回原因码与数据,文案由界面层生成 + function saveImpact(o) { + var out = [], p = o.payload, v = o.view, st = o.status || {}, tiers = st.tiers || []; + var names = function (pred) { return tiers.filter(pred).map(function (t) { return t.name; }); }; + var ops = Object.keys(p.secret_ops); + if (ops.length) out.push({ code: 'secrets', danger: ops.some(function (x) { return p.secret_ops[x].op === 'clear'; }), paths: ops }); + if (o.cleared.length) out.push({ code: 'cleared', danger: true, paths: o.cleared }); + if (st.in_flight > 0) out.push({ code: 'inflight', n: st.in_flight }); + var cb = names(function (t) { return t.circuit_breaker && t.circuit_breaker.state && t.circuit_breaker.state !== 'closed'; }); + var rl = names(function (t) { return t.rate_limit && t.rate_limit.is_rate_limited; }); + var qx = names(function (t) { return [t.quota_guard, t.weekly_quota_guard].some(function (q) { return q && q.state === 'quota_exceeded'; }); }); + if (cb.length) out.push({ code: 'breaker', names: cb }); + if (rl.length) out.push({ code: 'ratelimit', names: rl }); + if (qx.length) out.push({ code: 'quota', names: qx }); + var running = v.running && v.running.tiers; + if (Array.isArray(running) && (p.sections.vendors || p.sections.tiers) && !deepEqual(running, o.chain)) out.push({ code: 'tiers' }); + var boot = (v.running && v.running.boot_revisions) || {}; + var pend = Object.keys(p.sections).filter(function (s) { return s in boot && boot[s] !== v.revisions[s]; }); + if (pend.length) out.push({ code: 'pending', sections: pend }); + var before = vendorMap(o.base.vendors), after = vendorMap(o.work.vendors); + var gone = Object.keys(before).filter(function (t) { return !after[t]; }); + if (gone.length && p.sections.vendors) out.push({ code: 'removed', vendors: gone }); + return out; + } + var helpers = { deepEqual: deepEqual, clone: clone, isTmpl: isTmpl, validToken: validToken, assignField: assignField, parsePrice: parsePrice, entryCurrency: entryCurrency, priceText: priceText, withCurrency: withCurrency, @@ -211,6 +294,7 @@ countChangedFields: countChangedFields, buildPayload: buildPayload, predictClearedSecrets: predictClearedSecrets, movedOpenIndex: movedOpenIndex, effectiveChain: effectiveChain, newDefaultRows: newDefaultRows, pricingMergeRows: pricingMergeRows, + changedRows: changedRows, saveImpact: saveImpact, }; if (typeof module !== 'undefined' && module.exports) module.exports = helpers; if (typeof window === 'undefined' || typeof document === 'undefined') return; @@ -232,6 +316,7 @@ pill: 'vendors', vendor: null, expanded: {}, loaded: false, saving: false, readonly: false, specs: [], specMap: {}, schema: { fields: {}, groups: {} }, retryOnly: null, fatalText: null, + confirming: false, focus: null, focusTo: null, focusRemap: null, newRow: null, undo: null, live: null, }; var uid = 0; @@ -331,8 +416,10 @@ ['mode', 'errors', 'notices', 'overridden', 'vendor_overrides', 'secrets', 'sources', 'running', 'apply_supported'] .forEach(function (k) { prev[k] = view[k]; }); prev.values.absent_vendors = view.values.absent_vendors; + clearUndo(only); // 冲突 section 的工作副本已被服务器值替换 } else { S.view = view; + S.undo = null; S.base = {}; S.work = {}; S.ops = {}; @@ -346,8 +433,95 @@ } // ── 渲染骨架 ────────────────────────────────────────────── + // ── 焦点找回:rerender 整体重建 DOM,按「容器路径 + 控件角色」把焦点还给同一控件 ── + var ROLE_CLASS = /^(cfg-(input|num|check|info|chip-add|chip-x|link|secret-menu|secret-input|map-key|btn-icon|btn-sm|btn-primary)|range-btn)$/; + function roleOf(el) { + if (!el || !el.getAttribute) return null; + var aria = el.getAttribute('aria-label'); + if (aria) return el.tagName + '@' + aria; + if (/^(BUTTON|A|SUMMARY)$/.test(el.tagName)) return el.tagName + ':' + String(el.textContent || '').trim().slice(0, 24); + var cls = String(el.className || '').split(/\s+/).filter(function (c) { return ROLE_CLASS.test(c); }); + return el.tagName + '.' + (cls[0] || ''); + } + // :focus-visible 在旧浏览器是未知伪类,matches() 会抛 SyntaxError + function visibleRing(el) { + if (!el || !el.matches) return false; + try { return el.matches(':focus-visible'); } catch (e) { return false; } + } + function captureFocus() { + S.focus = null; + var a = document.activeElement; + if (!a || a === document.body || !S.root) return; + if (S.root.contains && !S.root.contains(a)) return; + var host = a.closest && a.closest('[data-path], [data-pill], [data-vendor]'); + if (!host) return; + var attr = host.hasAttribute('data-path') ? 'data-path' : host.hasAttribute('data-pill') ? 'data-pill' : 'data-vendor'; + var loose = looseRole(a); + S.focus = { attr: attr, val: host.getAttribute(attr), role: roleOf(a), loose: loose, li: sameLoose(host, loose).indexOf(a), ring: visibleRing(a) }; + } + // 容器内与某控件同属一类的控件(文档序),用于按钮文案变化后按序号找回 + function sameLoose(host, loose) { + return [host].concat(Array.prototype.slice.call(host.querySelectorAll('*'))).filter(function (n) { return looseRole(n) === loose; }); + } + // 按钮文案会变(编辑 ↔ 收起),用「标签 + 首个按钮类」做第二级匹配 + function looseRole(el) { + if (!/^(BUTTON|A|SUMMARY)$/.test(el.tagName)) return roleOf(el); + var c = String(el.className || '').split(/\s+/).filter(function (x) { return /^(cfg-btn|range-btn)/.test(x); }); + return el.tagName + '.' + (c[c.length - 1] || ''); + } + function focusable(n) { + return !!(n && n.focus && !n.disabled && n.getAttribute('tabindex') !== '-1'); + } + // 落点优先级:调用方指定的 S.focusTo > 同容器内同角色 > 同容器内同类按钮 > 同容器内首个控件 > 当前激活的 pill; + // 目标必须可聚焦(如上移到首行后「上移」已禁用,落到同行的「下移」) + function restoreFocus() { + // focusRemap 无条件取走:鼠标点 ↑/↓ 不聚焦按钮的浏览器不会带 key,不能让它留到下一次重绘 + var pick = S.focusTo, key = S.focus, remap = S.focusRemap; + S.focusTo = null; S.focus = null; S.focusRemap = null; + if (!S.root) return; + var target = null, ring = !!(key && key.ring); + // 调用方的落点:返回 false 表示「不聚焦」(如撤销目标已不在当前页),不走回退 + if (pick) { try { target = pick(); } catch (e) { target = null; } if (target === false) return; } + if (!target && key && key.val !== null && key.role) { + var val = remap && remap.from === key.val ? remap.to : key.val; + var host = S.root.querySelector('[' + key.attr + '="' + val + '"]'); + if (host) { + var first = function (list, f) { for (var i = 0; i < list.length; i++) if (f(list[i]) && focusable(list[i])) return list[i]; return null; }; + var all = [host].concat(Array.prototype.slice.call(host.querySelectorAll('*'))); + target = first(all, function (n) { return roleOf(n) === key.role; }); + if (!target) { + // 按钮文案会变(编辑 ↔ 收起、下线 ↔ 上线):按它在同类按钮里的序号找回同一位置的那颗 + var peers = sameLoose(host, key.loose); + target = first([peers[Math.min(key.li, peers.length - 1)]], function () { return true; }) || first(peers, function () { return true; }); + } + if (!target) target = first(all, function (n) { return /^(BUTTON|INPUT|SELECT|TEXTAREA|A)$/.test(n.tagName) && n.type !== 'hidden'; }); + } + if (!target) target = S.root.querySelector('.cfg-pills .range-btn.active'); + } + if (!focusable(target)) return; + // 焦点原由键盘而来时,重绘后脚本聚焦不触发 :focus-visible,用属性补回焦点环,失焦即撤 + if (ring && target.setAttribute) { + target.setAttribute('data-focus-ring', '1'); + target.addEventListener('blur', function () { target.removeAttribute('data-focus-ring'); }); + } + // 不用 preventScroll:控件被常驻保存栏盖住时,让浏览器按 scroll-padding-bottom 把它滚出来; + // 控件本来就在视口内时 focus() 不会滚动 + target.focus(); + } + // 「添加」后的新行:高亮 2 秒,并把展开的编辑表单滚到视口中部 + function flashNewRow() { + var key = S.newRow; + S.newRow = null; + if (!key || !S.root) return; + var row = S.root.querySelector('.cfg-list-row[data-path="' + key + '"]'); + if (!row) return; + row.classList.add('cfg-row-new'); + if (row.nextElementSibling && row.nextElementSibling.scrollIntoView) row.nextElementSibling.scrollIntoView({ block: 'center' }); + setTimeout(function () { row.classList.remove('cfg-row-new'); }, 2000); + } function rerender() { if (!S.root || !S.view) return; + captureFocus(); var nodes = [renderToolbar()].concat(renderBanners()); var body = h('div', { class: 'card cfg-body', 'data-path': S.pill === 'system' ? null : S.pill }); RENDER[S.pill](body); @@ -355,7 +529,10 @@ clear(S.root); add(S.root, nodes); applyErrors(); + syncTruncTitles(); updateDirty(); + restoreFocus(); + flashNewRow(); } function renderToolbar() { // pills 为按钮组(非 tabs 模式):当前项以 aria-current 标注 @@ -368,17 +545,21 @@ }); return h('div', { class: 'cfg-toolbar' }, [ pills, - btn('锁定', function () { - if (isDirty() && !window.confirm('锁定会丢弃未保存的修改,继续?')) return; - forgetToken(); - renderLocked(); - }, 'cfg-btn-sm', { title: '清除本浏览器保存的管理 token' }), + btn('锁定', lockNow, 'cfg-btn-sm', { title: '清除本浏览器保存的管理 token' }), ]); } + function lockNow() { + var run = function () { forgetToken(); S.undo = null; renderLocked(); }; + if (!isDirty()) { run(); return; } + askConfirm({ title: '锁定并丢弃修改?', body: '锁定会丢弃全部未保存的修改,已保存的配置不受影响。', confirmText: '丢弃并锁定', danger: true }, run); + } function goPill(name, vendor) { S.pill = name; if (vendor) S.vendor = vendor; syncUrl(); + // 整页重绘后焦点落到新的激活项,而不是掉回 body + var sel = vendor ? '.cfg-subpills .range-btn[data-vendor="' + vendor + '"]' : '.cfg-pills .range-btn[data-pill="' + name + '"]'; + S.focusTo = function () { return S.root.querySelector(sel); }; rerender(); } function syncUrl() { @@ -404,7 +585,6 @@ } function renderBanners() { var out = [], v = S.view; - if (S.notice) out.push(noticeBanner()); if (v.mode !== 'store') out.push(banner(v.mode === 'defaults' ? 'info' : 'err', MODE_TEXT[v.mode] || v.mode)); if (!v.apply_supported && !S.readonly) out.push(banner('info', '当前实例不支持在线生效:保存会写入 config.db,需重启 coding-proxy 后生效')); var boot = (v.running && v.running.boot_revisions) || {}; @@ -417,6 +597,7 @@ S.loaded = false; S.view = null; // 丢弃工作副本(含待设置的密钥明文) S.ops = {}; + S.undo = null; updateDirty(); // 清除 Config 页签上的 dirty 点 var input = h('input', { type: 'password', class: 'cfg-input', autocomplete: 'off', 'aria-label': 'Admin token', @@ -459,13 +640,13 @@ } // ── 表单行与控件 ────────────────────────────────────────── - function infoTip(label, desc) { + function infoTip(label, desc, withLabel) { var id = 'cfg-tip' + (++uid); // Esc 隐藏全部说明;再次悬停或聚焦某个 ⓘ 时恢复该项 var rearm = function (e) { e.currentTarget.classList.remove('cfg-tip-off'); }; return h('span', { class: 'cfg-info-wrap', onmouseenter: rearm, onfocusin: rearm }, [ h('button', { type: 'button', class: 'cfg-info', 'aria-label': 'Help: ' + label, 'aria-describedby': id, text: 'ⓘ' }), - h('span', { class: 'cfg-tip', role: 'tooltip', id: id, text: desc || label }), + h('span', { class: 'cfg-tip', role: 'tooltip', id: id, text: withLabel && desc ? label + ':' + desc : (desc || label) }), ]); } var LABELABLE = ['INPUT', 'SELECT', 'TEXTAREA', 'BUTTON', 'OUTPUT', 'METER', 'PROGRESS']; @@ -479,7 +660,7 @@ labelable ? h('label', { class: 'cfg-label cfg-trunc', for: id, text: sp.label }) : h('span', { class: 'cfg-label cfg-trunc', id: lid, text: sp.label }), - infoTip(sp.label, sp.description), + infoTip(sp.label, sp.description, true), h('div', { class: 'cfg-control', role: labelable ? null : 'group', 'aria-labelledby': labelable ? null : lid }, [ctrl, sp.unit ? h('span', { class: 'cfg-unit', text: sp.unit }) : null].concat(extras || [])), ]); @@ -586,7 +767,16 @@ type: 'number', class: 'cfg-input cfg-num', value: String(cur()[k]), disabled: dis, 'aria-label': k, oninput: function (e) { var n = cur(); n[k] = numVal(e.target.value); b.set(n); }, }), - dis ? null : btn('删除', function () { var n = cur(); delete n[k]; b.set(n); redraw(); }, 'cfg-btn-sm'), + dis ? null : btn('移除', function () { + var n = cur(), old = n[k]; + delete n[k]; + // 先记撤销再写工作副本(b.set 会立刻重建保存栏);b.path 只是展示路径(vendors 是数组),撤销用闭包回写 + S.undo = { kind: 'fn', section: b.path.split('.')[0], path: b.path, label: '已移除 ' + sp.label + ' 中的 ' + k, run: function () { var m = cur(); m[k] = old; b.set(m); } }; + b.set(n); + redraw(); + var add = wrap.querySelector('[data-map-add]'); + if (add && add.focus) add.focus(); + }, 'cfg-btn-sm'), ])); }); if (dis) return; @@ -596,7 +786,9 @@ var k = key.value.trim(); if (!k || val.value === '') return; var n = cur(); n[k] = numVal(val.value); b.set(n); redraw(); - }, 'cfg-btn-sm')])); + var first = wrap.querySelector('.cfg-map-key[type="text"]'); + if (first && first.focus) first.focus(); + }, 'cfg-btn-sm', { 'data-map-add': '1' })])); } redraw(); return wrap; @@ -625,16 +817,17 @@ if (!kind || kind === 'keep') delete S.ops[path]; else S.ops[path] = kind === 'set' ? { op: 'set', value: '' } : { op: kind }; changed(); + S.focusTo = function () { + return S.root.querySelector(kind === 'set' ? '.cfg-secret-input[data-for="' + path + '"]' : 'select.cfg-secret-menu[data-for="' + path + '"]'); + }; rerender(); - var input = kind === 'set' && S.root.querySelector('.cfg-secret-input[data-for="' + path + '"]'); - if (input) input.focus(); } function secretWidget(sp, path, id) { var st = (S.view.secrets || {})[path] || { kind: 'empty' }, op = S.ops[path]; var wrap = h('div', { class: 'cfg-secret' }, [secretPill(st, op, sp)]); if (S.readonly || sp.readonly) return wrap; wrap.appendChild(h('select', { - id: id, class: 'cfg-input cfg-secret-menu', onchange: function (e) { var k = e.target.value; e.target.value = ''; if (k) setOp(path, k); }, + id: id, class: 'cfg-input cfg-secret-menu', 'data-for': path, onchange: function (e) { var k = e.target.value; e.target.value = ''; if (k) setOp(path, k); }, }, [ h('option', { value: '', text: '更改 ▾' }), h('option', { value: 'set', text: '设置新值' }), @@ -660,10 +853,28 @@ h('div', { class: 'cfg-actions' }, actions || []), ]); } + // 「恢复默认」:vendors 的入口重置全部 vendor,改名并降权;会替换已保存值或波及当前对象之外时先确认 function resetBtn(section) { if (S.readonly) return null; - return btn('恢复默认', function () { S.work[section] = clone(S.view.defaults[section]); changed(); rerender(); }, 'cfg-btn-sm', - { title: '把本 section 改回包内默认值(保存后生效)' }); + var all = section === 'vendors'; + var n = ((S.view.defaults || {}).vendors || S.work.vendors || []).length; + return btn(all ? '全部恢复默认' : '恢复默认', function () { resetSection(section); }, 'cfg-btn-sm' + (all ? ' cfg-btn-ghost' : ''), all + ? { title: '把全部 ' + n + ' 个 vendor 改回包内默认值,其他 vendor 上未保存的修改也会丢弃(保存后生效)', 'aria-label': '全部恢复默认(所有 vendor)' } + : { title: '把本 section 改回包内默认值(保存后生效)' }); + } + function resetSection(section) { + var dflt = S.view.defaults[section]; + if (deepEqual(S.work[section], dflt)) return; + var all = section === 'vendors'; + var saved = (S.view.overridden || []).indexOf(section) >= 0; + var run = function () { S.work[section] = clone(dflt); S.undo = null; changed(); rerender(); }; + if (!all && !saved) { run(); return; } + var name = all ? '全部 ' + ((S.view.defaults.vendors || S.work.vendors || []).length) + ' 个 vendor' : sectionLabel(section); + askConfirm({ + title: (all ? '全部' : '') + '恢复默认?', + body: '以下范围将改回包内默认值:' + name + '。' + (saved ? '已保存的自定义值会在保存后被替换。' : '') + (all ? '其他 vendor 上未保存的修改也会丢弃。' : ''), + confirmText: all ? '全部恢复默认' : '恢复默认', danger: true, + }, run); } // ── 表格 ────────────────────────────────────────────────── @@ -682,27 +893,53 @@ ]); } // 列表 section:固定列宽表格 + 展开行编辑 +(可选)↑/↓ 排序 + // 被移除行在保存栏里的名字:取前两列;刚「添加」还没填的空行统一叫「空行」 + function rowName(o, item) { + var name = o.cols.slice(0, 2).map(function (c) { return fmtVal(c.text(item)); }).join(' / '); + return name === '— / —' ? '空行' : name; + } + // o.deletable(item, i):行级移除开关(返回 false 不出「移除」);o.rowActions(item, i):行内额外按钮 function listBlock(o) { var arr = function () { var a = getIn(S.work, o.parts); return Array.isArray(a) ? a : []; }; var setArr = function (a, open) { setIn(S.work, o.parts, a); S.expanded[o.key] = open; changed(); rerender(); }; var prefix = o.parts.join('.'); + var canDelete = o.deletable || function () { return true; }; var cols = (o.ordered ? [{ label: 'Order', w: '--col-order' }] : []).concat(o.cols, [{ label: 'Actions', w: '--col-actions' }]); var move = function (from, to) { var a = arr().slice(), item = a.splice(from, 1)[0]; a.splice(to, 0, item); + S.focusRemap = { from: prefix + '.' + from, to: prefix + '.' + to }; + S.undo = null; // 撤销按下标插回,行序变了就不再是原位 setArr(a, movedOpenIndex(S.expanded[o.key], from, to)); }; + // 移除一行:不弹确认,保存栏给单级「撤销」(插回原位,不影响其后的其它编辑) + var removeRow = function (i) { + var a = arr().slice(), item = a.splice(i, 1)[0]; + S.undo = { kind: 'row', section: o.parts[0], key: o.key, label: '已移除 ' + o.title + ' 的「' + rowName(o, item) + '」', parts: o.parts, index: i, item: clone(item) }; + S.focusTo = function () { + var wrap = S.root.querySelector('.ft-table-wrap[data-path="' + prefix + '"]'); + var rs = wrap.querySelectorAll('.cfg-list-row'); + if (!rs.length) { // 表已空:落到该表的「添加」 + var acts = wrap.parentNode.querySelector('.cfg-section-head .cfg-actions'); + return acts && acts.children.length ? acts.children[acts.children.length - 1] : false; + } + var r = rs[Math.min(i, rs.length - 1)]; + return r.querySelector('.cfg-btn-sm') || false; + }; + setArr(a, null); + }; var rows = []; arr().forEach(function (item, i) { var open = S.expanded[o.key] === i; var cells = o.cols.map(function (c) { return cell(c.text(item), c.mono ? 'cfg-mono' : ''); }); var refresh = function () { var it = arr()[i]; o.cols.forEach(function (c, k) { cells[k].textContent = fmtVal(c.text(it)); }); }; - var toggle = function () { S.expanded[o.key] = open ? null : i; rerender(); }; + var toggle = function () { if (window.getSelection && String(window.getSelection())) return; S.expanded[o.key] = open ? null : i; rerender(); }; rows.push(h('tr', { class: 'cfg-list-row' + (open ? ' cfg-row-open' : ''), 'data-path': prefix + '.' + i, onclick: toggle }, (o.ordered ? [orderCell(arr(), i, move)] : []).concat(cells, [h('td', { class: 'cfg-cell-actions' }, [ btn(open ? '收起' : '编辑', function (e) { e.stopPropagation(); toggle(); }, 'cfg-btn-sm', { 'aria-expanded': open ? 'true' : 'false' }), - S.readonly ? null : btn('删除', function (e) { e.stopPropagation(); var a = arr().slice(); a.splice(i, 1); setArr(a, null); }, 'cfg-btn-sm cfg-btn-danger'), - ]), h('td')]))); + ].concat(o.rowActions ? (o.rowActions(item, i) || []) : [], [ + S.readonly || !canDelete(item, i) ? null : btn('移除', function (e) { e.stopPropagation(); removeRow(i); }, 'cfg-btn-sm cfg-btn-danger'), + ])), h('td')]))); if (!open) return; var fields = o.fields(i).map(function (f) { var b = f.bind, set = b.set; @@ -712,7 +949,19 @@ rows.push(h('tr', { class: 'cfg-detail-row' }, h('td', { colspan: String(cols.length + 1) }, h('div', { class: 'detail-card cfg-detail' }, fields)))); }); if (!rows.length) rows.push(h('tr', {}, h('td', { colspan: String(cols.length + 1), class: 'empty', text: '暂无条目' }))); - var actions = (o.actions || []).concat(S.readonly ? [] : [btn('添加', function () { var a = arr().slice(); a.push(o.blank()); setArr(a, a.length - 1); }, 'cfg-btn-sm')]); + var actions = (o.actions || []).concat(S.readonly ? [] : [btn('添加', function () { + var a = arr().slice(); a.push(o.blank()); + S.undo = null; + var at = a.length - 1; + S.newRow = prefix + '.' + at; + // 落点限定在「新行自己的展开表单」:别的行可能也处于展开状态 + S.focusTo = function () { + var row = S.root.querySelector('.cfg-list-row[data-path="' + prefix + '.' + at + '"]'); + var detail = row && row.nextElementSibling; + return detail ? detail.querySelector('.cfg-control input, .cfg-control select') : null; + }; + setArr(a, a.length - 1); + }, 'cfg-btn-sm')]); return h('div', { class: 'cfg-list' }, [sectionHead(o.title, spec(o.specPath), actions)].concat(o.before || [], [table(cols, rows, prefix)])); } function itemBind(parts, i, rel, specPath) { @@ -805,8 +1054,8 @@ if (t !== 'anthropic' && !scoped) badges.push(badge('No scoped mapping', 'warn', '没有仅作用于该 vendor 的 model_mapping 规则,请求模型名可能被通用规则映射')); return h('div', { class: 'cfg-vendor-head' }, [ sectionHead(t, null, S.readonly ? [] : [ - btn('恢复默认', function () { replaceVendor(t, clone(findVendor(S.view.defaults.vendors, t)) || { vendor: t }); }, 'cfg-btn-sm', { title: '把该 vendor 改回包内默认参数(保存后生效)' }), - btn('移除', function () { removeVendor(t); }, 'cfg-btn-sm cfg-btn-danger', { title: '从配置中移除该 vendor(同时移出 tiers)' }), + btn('恢复默认', function () { resetVendor(t); }, 'cfg-btn-sm', { title: '把该 vendor 改回包内默认参数(保存后生效)', 'aria-label': '恢复默认(' + t + ')' }), + btn('移除', function () { removeVendor(t); }, 'cfg-btn-sm cfg-btn-danger', { title: '从配置中移除该 vendor(同时移出 tiers)', 'aria-label': '移除 ' + t }), ]), h('div', { class: 'cfg-badges' }, badges), ]); @@ -814,6 +1063,7 @@ function addVendor(t) { var v = clone(findVendor(S.base.vendors, t) || findVendor(S.view.defaults.vendors, t)) || { vendor: t }; S.work.vendors = (S.work.vendors || []).concat([v]); + S.undo = null; changed(); rerender(); } @@ -822,11 +1072,31 @@ changed(); rerender(); } + // vendor 级恢复默认:只在会替换已保存的自定义值时确认 + function resetVendor(t) { + var v = clone(findVendor(S.view.defaults.vendors, t)) || { vendor: t }; + if (deepEqual(findVendor(S.work.vendors, t), v)) return; + var run = function () { replaceVendor(t, v); }; + if ((S.view.vendor_overrides || []).indexOf(t) < 0) { run(); return; } + askConfirm({ title: '恢复默认?', body: t + ' 有已保存的自定义参数,恢复默认后会在保存时被替换(保存前可用「放弃修改」找回)。', confirmText: '恢复默认', danger: true }, run); + } + // 移除 vendor:总是确认(会同时移出 tiers 链路);保存栏给单级「撤销」 function removeVendor(t) { - S.work.vendors = (S.work.vendors || []).filter(function (x) { return x.vendor !== t; }); - if (Array.isArray(S.work.tiers)) S.work.tiers = S.work.tiers.filter(function (x) { return x !== t; }); - changed(); - rerender(); + var pos = effectiveChain(S.work.tiers, S.work.vendors).indexOf(t); + askConfirm({ + title: '移除 ' + t + '?', + body: '将从配置中移除 ' + t + (pos >= 0 ? ',并移出 Tiers 链路(当前 Tier #' + (pos + 1) + ')' : '') + '。已保存的密钥不会删除,重新添加后仍可用。', + confirmText: '移除', danger: true, + }, function () { + var list = S.work.vendors || [], i = -1; + list.forEach(function (x, k) { if (x.vendor === t) i = k; }); + if (i < 0) return; + S.undo = { kind: 'vendor', section: 'vendors', label: '已移除 vendor ' + t, index: i, vendor: clone(list[i]), tierIndex: Array.isArray(S.work.tiers) ? S.work.tiers.indexOf(t) : -1 }; + S.work.vendors = list.filter(function (x) { return x.vendor !== t; }); + if (Array.isArray(S.work.tiers)) S.work.tiers = S.work.tiers.filter(function (x) { return x !== t; }); + changed(); + rerender(); + }); } RENDER.tiers = function (body) { @@ -890,20 +1160,48 @@ RENDER.pricing = function (body) { var fresh = pricingMergeRows(S.view.overridden, S.base.pricing, S.work.pricing, S.view.defaults.pricing); - var before = [h('p', { class: 'cfg-note', text: '单价单位为每百万 token;修改后历史用量成本按新价格重算。' })]; + var before = [h('p', { class: 'cfg-note', text: '单价单位为每百万 token;修改后历史用量成本按新价格重算。定价行不可删除:退役模型请下线(不进 Model Bind 下拉,已绑会话保留,成本照常计价)。' })]; if (fresh.length && !S.readonly) { before.push(banner('info', '包内默认定价中有 ' + fresh.length + ' 行不在已保存的定价表中(定价表已覆盖默认值,不会自动合入)', [btn('合并', function () { S.work.pricing = (S.work.pricing || []).concat(clone(fresh)); changed(); rerender(); }, 'cfg-btn-sm')])); } var price = function (f) { return function (r) { return r[f] === undefined ? '0' : fmtVal(r[f]); }; }; var curSpec = { label: 'Currency', description: '整行单价的币种:$ 为 USD,¥ 为 CNY', widget: 'enum', enum: ['USD', 'CNY'] }; + var savedRow = function (i) { return i < (S.base.pricing || []).length; }; + // pricing 行不可删除(Model Bind 目录派生与下线的锚):已保存行只可下线/上线,vendor/model 不可改名 + var restoreBtn = btn('恢复默认价格', function () { + var defaults = S.view.defaults.pricing || []; + var merged = (S.work.pricing || []).map(function (row) { + var hit = defaults.filter(function (d) { return pricingKey(d) === pricingKey(row); })[0]; + return hit ? clone(hit) : row; + }); + defaults.forEach(function (d) { + if (!merged.some(function (row) { return pricingKey(row) === pricingKey(d); })) merged.push(clone(d)); + }); + S.work.pricing = merged; + changed(); + rerender(); + }, 'cfg-btn-sm', { title: '默认行恢复包内默认价格,自定义行保留(pricing 行不可删除)' }); body.appendChild(listBlock({ key: 'pricing', parts: ['pricing'], specPath: 'pricing', title: 'Pricing', ordered: false, before: before, - actions: [resetBtn('pricing')], + actions: S.readonly ? [] : [restoreBtn], + deletable: function (item, i) { return !savedRow(i); }, + rowActions: function (item, i) { + if (S.readonly || !savedRow(i)) return null; + var off = item.online === false; + return [btn(off ? '上线' : '下线', function (e) { + e.stopPropagation(); + var row = S.work.pricing[i]; + if (off) delete row.online; else row.online = false; + changed(); + rerender(); + }, 'cfg-btn-sm', { title: off ? '重新进入 Model Bind 下拉,新绑定可用' : '不进 Model Bind 下拉;已绑会话保留,成本照常计价' })]; + }, cols: [ { label: 'Vendor', w: '--col-vendor', text: function (r) { return r.vendor; } }, { label: 'Model', w: '--col-model', mono: true, text: function (r) { return r.model; } }, { label: 'Currency', w: '--col-currency', text: entryCurrency }, + { label: 'Status', w: '--col-bool', text: function (r) { return r.online === false ? 'Offline' : 'Online'; } }, { label: 'Input', w: '--col-price', mono: true, text: price(PRICE_FIELDS[0]) }, { label: 'Output', w: '--col-price', mono: true, text: price(PRICE_FIELDS[1]) }, { label: 'Cache W', w: '--col-price', mono: true, text: price(PRICE_FIELDS[2]) }, @@ -922,7 +1220,13 @@ changed(); }, }; - return itemFields(['pricing'], i, ['vendor', 'model']).concat([{ spec: curSpec, bind: cur }], PRICE_FIELDS.map(function (f) { + var baseFields = itemFields(['pricing'], i, ['vendor', 'model']); + if (savedRow(i)) { + baseFields = baseFields.map(function (f, k) { + return { spec: f.spec, bind: f.bind, row: function (b) { return field(spec('pricing.*.' + ['vendor', 'model'][k]), b, true); } }; + }); + } + return baseFields.concat([{ spec: curSpec, bind: cur }], PRICE_FIELDS.map(function (f) { return { spec: spec('pricing.*.' + f), bind: { @@ -1032,7 +1336,7 @@ // ── Dirty / 错误 / 保存 ─────────────────────────────────── function isDirty() { return !!S.view && (dirtySections(S.base, S.work).length > 0 || activeOps(S.ops).length > 0); } - function changed() { updateDirty(); } + function changed() { if (S.notice && S.notice.kind === 'ok') S.notice = null; updateDirty(); } function affectedSections() { var set = {}; dirtySections(S.base, S.work).forEach(function (s) { set[s] = true; }); @@ -1063,26 +1367,96 @@ var bar = S.root.querySelector('.cfg-savebar'); if (bar) fillSaveBar(bar); } + function sectionLabel(s) { + for (var i = 0; i < PILLS.length; i++) if (PILLS[i][0] === s) return PILLS[i][1]; + return s; + } + // 待保存范围的可读名称:vendors 细到具体 vendor,其余用 pill 名 + function scopeText() { + return affectedSections().map(function (s) { + if (s !== 'vendors') return sectionLabel(s); + var seen = {}; + var vs = (S.base.vendors || []).concat(S.work.vendors || []).map(function (v) { return v.vendor; }) + .filter(function (t) { return !seen[t] && (seen[t] = true) && vendorDirty(t); }); + activeOps(S.ops).forEach(function (p) { var m = /^vendors\.([^.]+)\./.exec(p); if (m && vs.indexOf(m[1]) < 0) vs.push(m[1]); }); + return vs.length ? 'Vendors › ' + vs.slice(0, 3).join('、') + (vs.length > 3 ? ' 等 ' + vs.length + ' 个' : '') : 'Vendors'; + }).join('、'); + } function renderSaveBar() { var bar = h('div', { class: 'cfg-savebar', role: 'region', 'aria-label': 'Save changes' }); fillSaveBar(bar); return bar; } + // 保存栏是唯一的保存结果反馈面(顶部 Banner 只留模式类提示);结果不自动消失,由用户关闭或在下一次编辑时清除 function fillSaveBar(bar) { - var dirty = isDirty(), n = countChangedFields(S.base, S.work, S.ops), k = affectedSections().length; - bar.hidden = !dirty && !S.errors.length; + var dirty = isDirty(), n = countChangedFields(S.base, S.work, S.ops); + var hadFocus = !!(document.activeElement && bar.contains && bar.contains(document.activeElement)); + bar.hidden = !dirty && !S.errors.length && !S.notice && !S.undo; + bar.className = 'cfg-savebar' + (S.notice ? ' cfg-savebar-' + S.notice.kind : ''); clear(bar); - var msg = h('div', { class: 'cfg-savebar-msg' }, [h('div', { text: dirty ? n + ' 个字段待保存(' + k + ' 个 section)' : '没有未保存的修改' })]); + var msg = h('div', { class: 'cfg-savebar-msg' }); + if (S.notice) { + msg.appendChild(h('div', { class: 'cfg-result', tabindex: '-1' }, [h('span', { class: 'cfg-result-dot', 'aria-hidden': 'true' }), h('span', { text: S.notice.text })] + .concat((S.notice.lines || []).map(function (l) { return h('div', { class: 'cfg-note cfg-trunc', text: l, title: l }); })))); + } + if (S.undo) msg.appendChild(h('div', { class: 'cfg-undo' }, [h('span', { class: 'cfg-trunc', text: S.undo.label, title: S.undo.label }), h('button', { type: 'button', class: 'cfg-link', text: '撤销', onclick: undoLast, disabled: S.saving })])); + if (dirty) msg.appendChild(h('div', { class: 'cfg-scope', text: '待保存:' + scopeText() + '(' + n + ' 处)' })); if (S.errors.length) { msg.appendChild(h('ul', { class: 'cfg-savebar-errors' }, S.errors.slice(0, 8).map(function (e) { var p = locToPath(e.loc); - return h('li', { class: 'cfg-trunc' }, h('button', { type: 'button', class: 'cfg-link', text: (p || '') + ':' + e.msg, onclick: function () { focusError(p); } })); + return h('li', { class: 'cfg-trunc' }, h('button', { type: 'button', class: 'cfg-link', text: (p ? labelOf(p) : '') + ':' + e.msg, title: p, onclick: function () { focusError(p); } })); }).concat(S.errors.length > 8 ? [h('li', { text: '…共 ' + S.errors.length + ' 个错误' })] : []))); } - add(bar, [msg, btn('放弃修改', discard, '', { disabled: !dirty || S.saving }), - btn(S.saving ? '保存中…' : '保存 ' + n + ' 个字段(' + k + ' 个 section)', onSave, 'cfg-btn-primary', { disabled: !dirty || S.saving || S.readonly })]); + var acts = []; + if (S.notice && !dirty) acts.push(btn('关闭', function () { S.notice = null; updateDirty(); }, 'cfg-btn-sm')); + if (dirty || S.errors.length) { + acts.push(btn('放弃修改', discard, '', { disabled: !dirty || S.saving })); + acts.push(btn(S.confirming ? '等待确认…' : S.saving ? '保存中…' : '保存', onSave, 'cfg-btn-primary', { disabled: !dirty || S.saving || S.readonly })); + } + add(bar, [msg].concat(acts)); + // 保存栏每次整体重建:原先落在栏内的焦点(通常是「保存」按钮)跟着回来; + // 栏里已没有可聚焦控件(如点「关闭」后隐藏)时落到当前激活的 pill,而不是掉回 body + if (hadFocus) { + var b = bar.querySelector('.cfg-btn-primary') || bar.querySelector('.cfg-btn'); + if (b && b.focus) b.focus(); + else if (S.root) { var p = S.root.querySelector('.cfg-pills .range-btn.active'); if (p && p.focus) p.focus(); } + } } function discard() { - if (!window.confirm('放弃全部未保存的修改?')) return; - EDITABLE.forEach(function (s) { S.work[s] = clone(S.base[s]); }); - S.ops = {}; - S.errors = []; + askConfirm({ title: '放弃修改?', body: '将丢弃全部未保存的修改,已保存的配置不受影响。', confirmText: '放弃修改', danger: true }, function () { + EDITABLE.forEach(function (s) { S.work[s] = clone(S.base[s]); }); + S.ops = {}; + S.errors = []; + S.undo = null; + S.focusTo = function () { return S.root.querySelector('.cfg-pills .range-btn.active'); }; + rerender(); + }); + } + // 撤销快照指向工作副本里的位置:重载替换了它所在的 section 就作废 + function clearUndo(sections) { + if (S.undo && (!sections || sections.indexOf(S.undo.section) >= 0)) S.undo = null; + } + // 单级撤销:只恢复被移除的对象本身并插回原位,不影响其后的其它编辑 + function undoLast() { + var u = S.undo; + if (!u || S.saving) return; // 保存进行中载荷已定稿,此时撤销会被随后的重载覆盖 + S.undo = null; + if (u.kind === 'row') { + var a = getIn(S.work, u.parts); + if (!Array.isArray(a)) { a = []; setIn(S.work, u.parts, a); } + a.splice(Math.min(u.index, a.length), 0, clone(u.item)); + if (typeof S.expanded[u.key] === 'number' && S.expanded[u.key] >= u.index) S.expanded[u.key] += 1; // 展开行跟着后移 + S.focusTo = function () { + var rs = S.root.querySelectorAll('.ft-table-wrap[data-path="' + u.parts.join('.') + '"] .cfg-list-row'); + return rs[u.index] ? rs[u.index].querySelector('.cfg-btn-sm') : false; + }; + } else if (u.kind === 'fn') { + u.run(); + S.focusTo = function () { return S.root.querySelector('.cfg-row[data-path="' + u.path + '"] [data-map-add]'); }; + } else if (u.kind === 'vendor') { + if (findVendor(S.work.vendors, u.vendor.vendor)) { changed(); rerender(); return; } // 期间已重新添加,不再插入 + S.work.vendors = S.work.vendors || []; + S.work.vendors.splice(Math.min(u.index, S.work.vendors.length), 0, clone(u.vendor)); + if (u.tierIndex >= 0 && Array.isArray(S.work.tiers) && S.work.tiers.indexOf(u.vendor.vendor) < 0) S.work.tiers.splice(Math.min(u.tierIndex, S.work.tiers.length), 0, u.vendor.vendor); + S.focusTo = function () { return S.root.querySelector('.cfg-subpills .range-btn[data-vendor="' + u.vendor.vendor + '"]'); }; + } + changed(); rerender(); } function focusError(path) { @@ -1116,25 +1490,28 @@ function fetchStatus() { return fetch('/api/status', { cache: 'no-store' }).then(function (r) { return r.ok ? r.json() : null; }).catch(function () { return null; }); } - function runtimeLines(status) { - if (!S.view.apply_supported) return ['当前实例不支持在线生效:保存后需重启,运行时状态不受影响。']; - var tiers = (status && status.tiers) || [], lines = []; - var names = function (pred) { return tiers.filter(pred).map(function (t) { return t.name; }); }; - var cb = names(function (t) { return t.circuit_breaker && t.circuit_breaker.state && t.circuit_breaker.state !== 'closed'; }); - var rl = names(function (t) { return t.rate_limit && t.rate_limit.is_rate_limited; }); - var qx = names(function (t) { return [t.quota_guard, t.weekly_quota_guard].some(function (q) { return q && q.state === 'quota_exceeded'; }); }); - if (status && typeof status.in_flight === 'number') lines.push('进行中的请求:' + status.in_flight + ' 个(在旧实例上继续完成)'); - if (cb.length) lines.push('熔断状态将重置:' + cb.join('、')); - if (rl.length) lines.push('限流状态将重置:' + rl.join('、')); - if (qx.length) lines.push('配额超限状态按用量数据库重建:' + qx.join('、')); - lines.push('运行时调整的并发上限恢复为配置值;配额窗口按用量数据库重建。'); - var running = S.view.running && S.view.running.tiers; - if (Array.isArray(running) && !deepEqual(running, enabledChain())) { - lines.push('运行中的优先级(含 Overview 拖拽)与保存的 tiers 不同,保存后以 tiers 为准。'); + // 具体路径 → 注册表 spec(vendors 的 vendor 段与列表下标泛化为 *) + function specFor(path) { + var parts = String(path).split('.'); + if (S.specMap[path]) return S.specMap[path]; + for (var i = 1; i < parts.length; i++) { + if (parts[0] === 'vendors' ? i !== 1 : !/^\d+$/.test(parts[i])) continue; + var hit = S.specMap[parts.slice(0, i).concat(['*'], parts.slice(i + 1)).join('.')]; + if (hit) return hit; } - return lines; + return null; } - function confirmSave(payload, status) { + function labelOf(path) { + var parts = String(path).split('.'), sp = specFor(path); + if (parts[0] === 'vendors') return (sp ? sp.label : parts[parts.length - 1]) + '(' + parts[1] + ')'; + return sp ? sp.label : parts[parts.length - 1]; + } + function rowTitleOf(sec, row) { + var ks = ROW_KEY[sec] || [], sub = sec.split('.').slice(1); + return (sub.length ? sub.join(' › ') + ' › ' : '') + (ks.length ? ks.map(function (k) { return String(row[k]); }).join(' / ') : fmtVal(row)); + } + // 保存后果清单:每一项都来自可预判的运行时状态或本次载荷;非空才弹确认框 + function saveImpactList(payload, status) { var secretFields = {}; S.specs.forEach(function (sp) { if (sp.widget !== 'secret' || !sp.vendors) return; @@ -1144,26 +1521,85 @@ base: S.base, work: S.work, defaults: S.view.defaults, secrets: S.view.secrets, ops: S.ops, secretFields: secretFields, targetDefaults: { base_url: dflt('vendors.*.base_url'), token_url: dflt('vendors.*.token_url') }, }); - var blocks = [ - ['修改的 section', Object.keys(payload.sections)], - ['密钥操作', Object.keys(payload.secret_ops).map(function (p) { return p + ':' + payload.secret_ops[p].op; })], - ['目标地址已变更,以下密钥将被清空(需重新设置)', cleared], - ['运行时影响', runtimeLines(status)], - ].filter(function (b) { return b[1].length; }); - var text = blocks.map(function (b) { return b[0] + ':\n- ' + b[1].join('\n- '); }).join('\n\n'); - if (typeof window.HTMLDialogElement !== 'function') return Promise.resolve(window.confirm('确认保存?\n\n' + text)); - return new Promise(function (resolve) { - var dlg = h('dialog', { class: 'cfg-dialog', 'aria-label': '确认保存' }); - var close = function (ok) { dlg.close(); dlg.remove(); resolve(ok); }; - add(dlg, [h('div', { class: 'cfg-section-title', text: '确认保存' })].concat(blocks.map(function (b, i) { - return h('div', { class: 'cfg-dialog-block' + (b[1] === cleared ? ' cfg-dialog-warn' : '') }, [ - h('div', { class: 'cfg-group-title', text: b[0] }), - h('ul', {}, b[1].map(function (l) { return h('li', { text: l }); })), - ]); - }), [h('div', { class: 'cfg-actions' }, [btn('取消', function () { close(false); }), btn('确认保存', function () { close(true); }, 'cfg-btn-primary')])])); - dlg.addEventListener('cancel', function (e) { e.preventDefault(); close(false); }); - document.body.appendChild(dlg); - dlg.showModal(); + return saveImpact({ payload: payload, base: S.base, work: S.work, view: S.view, status: status, cleared: cleared, chain: enabledChain() }); + } + function impactLines(impact, payload) { + var l = function (a) { return a.join('、'); }; + return impact.map(function (it) { + if (it.code === 'secrets') return '密钥:' + l(it.paths.map(function (p) { var op = payload.secret_ops[p]; return op.op === 'set' ? '设置 ' + labelOf(p) : op.op === 'clear' ? '清空 ' + labelOf(p) : labelOf(p) + ' 改用环境变量 ' + ((S.view.secrets[p] || {}).default_env || ''); })); + if (it.code === 'cleared') return '目标地址已变更,保存后将清空密钥(需重新设置):' + l(it.paths.map(labelOf)); + if (it.code === 'inflight') return it.n + ' 个请求正在进行,会在旧实例上完成后切到新配置'; + if (it.code === 'breaker') return '熔断状态将重置:' + l(it.names); + if (it.code === 'ratelimit') return '限流状态将重置:' + l(it.names); + if (it.code === 'quota') return '配额超限状态将按用量数据库重建:' + l(it.names); + if (it.code === 'tiers') return '运行中的优先级与保存的 Tiers 不同,保存后以 Tiers 为准'; + if (it.code === 'pending') return '上次保存后尚未生效的 section 会一并生效:' + l(it.sections.map(sectionLabel)); + if (it.code === 'removed') return '移除 vendor(同时移出 Tiers 链路):' + l(it.vendors); + return it.code; + }); + } + function diffBlock(groups) { + var rows = []; + groups.forEach(function (g) { + rows.push(h('div', { class: 'cfg-diff-group-title', text: g.title })); + g.rows.forEach(function (r) { + rows.push(h('div', { class: 'cfg-diff-row' }, [h('span', { class: 'cfg-diff-label cfg-trunc', text: r.label, title: r.label }), + h('span', { class: 'cfg-diff-val' }, r.added ? [h('ins', { text: '新增' })] : r.removed ? [h('del', { text: '移除' })] : [h('del', { text: r.before }), ' → ', h('ins', { text: r.after })])])); + }); + }); + var block = h('div', { class: 'cfg-dialog-block cfg-dialog-diff' }, [h('div', { class: 'cfg-group-title', text: '将保存的修改' })]); + if (rows.length > 8) block.appendChild(h('details', {}, [h('summary', { text: '共 ' + groups.reduce(function (n, g) { return n + g.rows.length; }, 0) + ' 处,展开查看' })].concat(rows))); + else rows.forEach(function (r) { block.appendChild(r); }); + return block; + } + // 页面内确认框;不支持 的环境回退到 window.confirm 并同步执行 + function askConfirm(o, onOk, onCancel) { + if (typeof window.HTMLDialogElement !== 'function') { + var text = o.title + (o.body ? '\n\n' + o.body : '') + (o.impacts && o.impacts.length ? '\n\n保存后会发生:\n- ' + o.impacts.join('\n- ') : ''); + if (window.confirm(text)) onOk(); else if (onCancel) onCancel(); + return; + } + var bodyId = 'cfg-dlg-' + (++uid) + '-body', impactId = 'cfg-dlg-' + uid + '-impact'; + var described = [o.body ? bodyId : null, o.impacts && o.impacts.length ? impactId : null].filter(Boolean).join(' '); + // 破坏性确认用 alertdialog;正文与后果清单挂到 aria-describedby,焦点落在「取消」时也会被读出 + var opener = document.activeElement, dlg = h('dialog', { class: 'cfg-dialog', 'aria-label': o.title, role: o.danger ? 'alertdialog' : null, 'aria-describedby': described || null }); + var close = function (ok) { + dlg.close(); dlg.remove(); + if (ok) onOk(); + else if (onCancel) onCancel(); + else if (opener && opener.focus) opener.focus(); + }; + var kids = [h('div', { class: 'cfg-section-title', text: o.title })]; + if (o.body) kids.push(h('p', { class: 'cfg-dialog-text', id: bodyId, text: o.body })); + if (o.impacts && o.impacts.length) kids.push(h('div', { class: 'cfg-dialog-block cfg-dialog-impact', id: impactId }, [h('div', { class: 'cfg-group-title', text: '保存后会发生' }), + h('ul', {}, o.impacts.map(function (l) { return h('li', { text: l }); }))])); + if (o.diff && o.diff.length) kids.push(diffBlock(o.diff)); + kids.push(h('div', { class: 'cfg-actions' }, [btn('取消', function () { close(false); }), + btn(o.confirmText || '确认', function () { close(true); }, 'cfg-btn-primary' + (o.danger ? ' cfg-btn-danger-solid' : ''))])); + add(dlg, kids); + dlg.addEventListener('cancel', function (e) { e.preventDefault(); close(false); }); + document.body.appendChild(dlg); + dlg.showModal(); + // 初始焦点放在「取消」:不可逆操作把焦点放在破坏性最小的一项上 + var cancel = dlg.querySelector('.cfg-actions .cfg-btn'); + if (cancel && cancel.focus) cancel.focus(); + } + function askConfirmP(o) { + return new Promise(function (resolve) { askConfirm(o, function () { resolve(true); }, function () { resolve(false); }); }); + } + function confirmSave(payload, status) { + var impact = saveImpactList(payload, status); + if (!impact.length) return Promise.resolve(true); + return askConfirmP({ + title: impact.some(function (it) { return it.danger; }) ? '保存并应用这些变更?' : '确认保存?', + impacts: impactLines(impact, payload), + diff: changedRows(S.base, S.work, { + label: function (path) { var sp = specFor(path); return sp ? sp.label : String(path).split('.').pop(); }, + skip: function (path) { var sp = specFor(path); return !!(sp && sp.widget === 'secret'); }, + sectionLabel: sectionLabel, rowTitle: rowTitleOf, + }), + danger: impact.some(function (it) { return it.danger; }), + confirmText: '确认保存', }); } function onSave() { @@ -1175,23 +1611,47 @@ rerender(); return; } - S.saving = true; + S.saving = true; S.confirming = true; updateDirty(); - fetchStatus().then(function (status) { return confirmSave(payload, status); }).then(function (ok) { - if (!ok) { S.saving = false; updateDirty(); return null; } + fetchStatus().then(function (status) { S.confirming = false; return confirmSave(payload, status); }).then(function (ok) { + S.confirming = false; + if (!ok) { S.saving = false; updateDirty(); focusSaveButton(); return null; } + updateDirty(); return request('PUT', payload).then(function (r) { return handleSave(r, payload); }); }).catch(function () { + S.confirming = false; S.saving = false; S.notice = { kind: 'err', text: '保存请求失败:网络错误' }; rerender(); + reportResult(); }); } + function focusSaveButton() { + var b = S.root && S.root.querySelector('.cfg-savebar .cfg-btn-primary'); + if (b && b.focus) b.focus(); + } + // 常驻播报节点:rerender 整体重建 #config-root,带 aria-live 的新节点不保证被朗读 + function ensureLive() { + if (S.live || !S.root || !S.root.parentNode) return; + S.live = h('div', { class: 'cfg-live', role: 'status', 'aria-live': 'polite' }); + S.root.parentNode.insertBefore(S.live, S.root.nextSibling); + } + function reportResult() { + ensureLive(); + if (!S.live || !S.notice) return; + S.live.textContent = ''; + // 回调里现读:409 之后的重载失败会把提示换成另一段,不能提前拼好 + setTimeout(function () { if (S.live && S.notice) S.live.textContent = [S.notice.text].concat(S.notice.lines || []).join('。'); }, 0); + var res = S.root && S.root.querySelector('.cfg-result'); + if (res && res.focus) { try { res.focus({ preventScroll: true }); } catch (e) { res.focus(); } } + } // PUT 成功即在本地落定:已提交 section 并入 base,丢弃密钥明文;随后重载失败也不残留 dirty / 明文 function commitSaved(payload, revisions) { Object.keys(payload.sections).forEach(function (s) { S.base[s] = clone(payload.sections[s]); S.work[s] = clone(payload.sections[s]); }); [payload.secret_ops, S.ops].forEach(function (ops) { Object.keys(ops).forEach(function (p) { if (ops[p]) delete ops[p].value; }); }); S.ops = {}; S.errors = []; + S.undo = null; if (isObj(revisions)) Object.keys(revisions).forEach(function (s) { S.view.revisions[s] = revisions[s]; }); } // 重载完成前保持冻结:重载会覆盖工作副本;'locked'(已渲染解锁界面)不叠 fatal 视图 @@ -1200,6 +1660,7 @@ S.saving = false; updateDirty(); if (ok === false && only) conflictReloadFailed(only); + reportResult(); }); } @@ -1247,6 +1708,7 @@ if (r.status === 423) { S.readonly = true; S.notice = { kind: 'err', text: errText(d) || MODE_TEXT.legacy_readonly }; } else S.notice = { kind: 'err', text: '保存失败(HTTP ' + r.status + ')' + (errText(d) ? ':' + errText(d) : '') }; rerender(); + reportResult(); return null; } @@ -1258,6 +1720,15 @@ if (el.scrollWidth > el.clientWidth) { el.title = el.textContent; el.setAttribute('data-auto-title', '1'); } else if (el.getAttribute('data-auto-title')) { el.removeAttribute('title'); el.removeAttribute('data-auto-title'); } } + // rerender 后立即为被截断的文本补 title(原先只在鼠标移入时懒补,键盘与触屏拿不到) + function syncTruncTitles() { + if (!S.root) return; + Array.prototype.forEach.call(S.root.querySelectorAll('.cfg-trunc'), function (el) { + if (el.title && !el.getAttribute('data-auto-title')) return; + if (el.scrollWidth > el.clientWidth) { el.title = el.textContent; el.setAttribute('data-auto-title', '1'); } + else if (el.getAttribute('data-auto-title')) { el.removeAttribute('title'); el.removeAttribute('data-auto-title'); } + }); + } function readSchemaDefaults() { var el = document.getElementById('config-schema-defaults'); try { return el ? JSON.parse(el.textContent) : { fields: {}, groups: {} }; } catch (e) { return { fields: {}, groups: {} }; } @@ -1265,6 +1736,7 @@ function mount(el) { if (!el || S.root === el) return; S.root = el; + ensureLive(); S.schema = readSchemaDefaults(); readUrlSection(); clear(el); @@ -1273,7 +1745,10 @@ function refresh(force) { if (!S.root) mount(document.getElementById('config-root')); if (S.saving) return Promise.resolve(); // 保存结束后自行重载 - if (!force && isDirty() && !window.confirm('放弃未保存的修改并重新加载?')) return Promise.resolve(); + if (!force && isDirty()) { + return askConfirmP({ title: '重新加载?', body: '将放弃全部未保存的修改,并重新加载服务器上的配置。', confirmText: '放弃并重新加载', danger: true }) + .then(function (ok) { return ok ? load() : undefined; }); + } return load(); } diff --git a/src/coding/proxy/vendors/model_catalog.py b/src/coding/proxy/vendors/model_catalog.py index ed1ad95b..44456b2b 100644 --- a/src/coding/proxy/vendors/model_catalog.py +++ b/src/coding/proxy/vendors/model_catalog.py @@ -4,8 +4,9 @@ - 每类 vendor 一份内置目录常量(label/model/归属 tiers),随包升级自动 触达所有用户,不受 config.db「list 整体替换」合并语义的存量冻结影响 - ``compose_bindable_catalog`` 在 app 构建时把「内置目录按激活 vendor 过滤」 - 与 ``session_policies.bindable_models`` 显式条目按 model 去重合并: - config 同名条目可覆盖 label/tiers(tiers 留空 = 继承内置值), + 与 pricing 行(仅 native vendor:配价即入目录,``online: false`` 只标记 + 下线、不可删除)及 ``session_policies.bindable_models`` 显式条目按 model + 去重合并:config 同名条目可覆盖 label/tiers(tiers 留空 = 继承内置值), ``exclude: true`` 可剔除内置同名条目 - 合成结果注入 ``RequestRouter._bindable_models``,/api/status 展示、 PUT /api/session-vendor 白名单校验、generations 热切换迁移三个消费点 @@ -21,10 +22,11 @@ from __future__ import annotations import logging +from collections.abc import Sequence from dataclasses import dataclass, field from typing import Any -from ..config.routing import ModelMappingRule +from ..config.routing import ModelMappingRule, ModelPricingEntry from ..config.session_policy import BindableModel logger = logging.getLogger(__name__) @@ -66,6 +68,7 @@ def _entry(label: str, model: str, vendor: str) -> CatalogEntry: # zhipu(智谱)可绑定的 glm 家族 _ZHIPU = [ + ("GLM 5.4", "glm-5.4"), ("GLM 5.3", "glm-5.3"), ("GLM 5.3 Flash", "glm-5.3-flash"), ("GLM 5.2", "glm-5.2"), @@ -132,58 +135,94 @@ def builtin_entries_for(vendor: str) -> list[CatalogEntry]: def compose_bindable_catalog( active_vendor_names: list[str], config_entries: list[BindableModel], + priced: Sequence[ModelPricingEntry] | None = None, ) -> list[dict[str, Any]]: - """合成可绑定模型清单 = 内置目录(按激活 vendor 过滤)∪ config 显式条目. + """合成可绑定模型清单 = 内置目录(按激活 vendor 过滤)∪ pricing 行 ∪ config 显式条目. 合并规则: - - config 清单为空 = 整体关闭模型绑定(含内置目录,保留「空清单即禁用」 - 的既有语义作为 off 开关) + - config 清单为空 = 整体关闭模型绑定(含内置目录与 pricing 派生条目, + 保留「空清单即禁用」的既有语义作为 off 开关) + - pricing 行仅取 native vendor(``_NATIVE_MAPPER_VENDORS``)且在激活链: + 配价即入目录(派生条目 label = model 名,tiers 锁定该 vendor,自动获得 + identity 映射规则),填补内置目录滞后于上游新型号的缺口;按 (vendor, + model) 精确去重,与内置/config 同名时让位 + - 下线以 model 为粒度:同名模型任一 pricing 行 ``online: false`` 即视为 + 下线,条目带 ``offline: true`` 标记——不进 ``get_bindable_models()`` + 下拉与 PUT 校验,executor 锁定链与热切换迁移仍可见(已绑会话保留) - 按 model 去重;config 同名条目覆盖 label,tiers 非空时覆盖 tiers, - ``exclude=True`` 时剔除该内置条目(纯自定义条目 exclude 无效,warning) + ``exclude=True`` 时剔除该内置/派生条目(纯自定义条目 exclude 无效,warning) - config 纯自定义条目(model 不在内置目录)原样保留:tiers 留空表示 沿用全局链路顺序(executor 侧仍受支持性门控保护) - - 返回条目含 vendor 字段(内置归属或 "custom"),供前端 optgroup 分组 + - 返回条目含 vendor 字段(内置归属 / pricing 归属或 "custom"),供前端 + optgroup 分组 """ if not config_entries: return [] active = [v for v in dict.fromkeys(active_vendor_names) if v] + active_set = set(active) builtin_models = {e.model for v in active for e in builtin_entries_for(v)} + # pricing 行登记:下线状态按 model 聚合(任一行下线即下线),派生条目按 + # (vendor, model) 精确匹配、保持配置顺序 + priced_online: dict[str, bool] = {} + priced_rows: list[tuple[str, str]] = [] + seen_rows: set[tuple[str, str]] = set() + for row in priced or (): + vendor, model = str(row.vendor), str(row.model) + online = bool(getattr(row, "online", True)) + priced_online[model] = priced_online.get(model, True) and online + if (vendor, model) not in seen_rows: + seen_rows.add((vendor, model)) + priced_rows.append((vendor, model)) merged: dict[str, dict[str, Any]] = {} order: list[str] = [] - # 用户 label 意图优先:内置条目 label 撞上 config 中「指向不同 model」的 - # label 时降级(同 label 同 model 的覆盖合并不算冲突);exclude 剔除的 - # 内置条目本身不进目录,其 label 不参与冲突判定 + # 用户 label 意图优先:内置/派生条目 label 撞上 config 中「指向不同 model」 + # 的 label 时降级(同 label 同 model 的覆盖合并不算冲突);exclude 剔除的 + # 条目本身不进目录,其 label 不参与冲突判定 config_label_models = { c.label: c.model for c in config_entries if not (c.exclude and c.model in builtin_models) } + def _claim_label(label: str, model: str, owner: str) -> str: + """label 撞 config 中指向不同 model 的 label 时降级为保证可区分的兜底名.""" + if config_label_models.get(label, model) == model: + return label + fallback = model + if fallback in config_label_models: + fallback = f"{model} ({owner})" + logger.warning( + "bindable label %r collides with config label, falling back to %r", + label, + fallback, + ) + return fallback + for vendor in active: for e in builtin_entries_for(vendor): if e.model in merged: continue - label = e.label - if config_label_models.get(label, e.model) != e.model: - fallback = e.model - if fallback in config_label_models: - # 降级兜底名再撞 config label:附 vendor 保证可区分 - fallback = f"{e.model} ({e.vendor})" - logger.warning( - "builtin bindable label %r collides with config label, " - "falling back to %r", - label, - fallback, - ) - label = fallback merged[e.model] = { - "label": label, + "label": _claim_label(e.label, e.model, e.vendor), "model": e.model, "tiers": list(e.tiers), "vendor": e.vendor, } order.append(e.model) + for vendor, model in priced_rows: + if vendor not in _NATIVE_MAPPER_VENDORS or vendor not in active_set: + continue + if model in merged: + continue + merged[model] = { + "label": _claim_label(model, model, vendor), + "model": model, + "tiers": [vendor], + "vendor": vendor, + } + order.append(model) + for cfg in config_entries: existing = merged.get(cfg.model) if existing is not None and cfg.exclude: @@ -209,7 +248,11 @@ def compose_bindable_catalog( } order.append(cfg.model) - return [merged[m] for m in order] + catalog = [merged[m] for m in order] + for entry in catalog: + if not priced_online.get(str(entry["model"]), True): + entry["offline"] = True + return catalog def builtin_identity_rules( diff --git a/tests/test_app_routes.py b/tests/test_app_routes.py index 6bc2f6eb..71590bed 100644 --- a/tests/test_app_routes.py +++ b/tests/test_app_routes.py @@ -1486,6 +1486,7 @@ def test_status_returns_bindable_models(): # 内置 zhipu 目录随激活 vendor 进入下拉,config 条目按 model 去重合并 assert "glm-5.3" in models_only assert "glm-5.3-flash" in models_only # 内置目录条目 + assert "glm-5.4" in models_only # 内置目录条目(最新 GLM) assert "claude-opus-4.6" in models_only # config 纯自定义条目 assert models_only.count("glm-5.3") == 1 # 同名去重不重复 glm = next(m for m in models if m["model"] == "glm-5.3") @@ -1495,6 +1496,61 @@ def test_status_returns_bindable_models(): assert custom["vendor"] == "custom" +def _offline_pricing_app() -> TestClient: + """创建带下线 pricing 行的测试应用(offline 过滤与 PUT 拒绑路径).""" + config = ProxyConfig( + primary={"enabled": False}, + fallback={"enabled": True}, + database={"path": "/tmp/test-coding-proxy-routes.db"}, + session_policies={ + "bindable_models": [ + {"label": "GLM 5.3", "model": "glm-5.3", "tiers": ["zhipu"]} + ] + }, + pricing=[ + {"vendor": "zhipu", "model": "glm-5.4"}, + {"vendor": "zhipu", "model": "glm-9.9", "online": False}, + ], + ) + return TestClient(create_app(config)) + + +def test_status_hides_offline_pricing_models(): + """/api/status 不含下线(pricing online=false)模型,在线 pricing 模型正常派生.""" + with _offline_pricing_app() as client: + models = [ + m["model"] for m in client.get("/api/status").json()["bindable_models"] + ] + assert "glm-5.4" in models # 在线 pricing 行派生 + assert "glm-9.9" not in models # 下线行不进下拉 + + +def test_bind_offline_model_rejected_with_offline_message(): + """绑定下线模型返回 400 且文案指明 offline(而非 unknown).""" + with _offline_pricing_app() as client: + resp = client.put( + "/api/session-vendor", + json={"session_key": "s-off", "model": "glm-9.9"}, + ) + assert resp.status_code == 400 + assert "offline" in resp.json()["error"]["message"] + assert "unknown model" not in resp.json()["error"]["message"] + + +def test_migrate_bindings_keep_offline_pricing_model(): + """热切换迁移保留已绑的下线模型(known 清单含 offline 条目).""" + from coding.proxy.server.generations import _migrate_bindings + + with _offline_pricing_app() as client: + app = client.app + dropped, model_dropped, vendor_dropped = _migrate_bindings( + {"s-off": (("zhipu",), "glm-9.9")}, app + ) + assert (dropped, model_dropped, vendor_dropped) == (0, 0, 0) + resolver = app.state.router._executor._policy_resolver # noqa: SLF001 + assert resolver.resolve("s-off").model == "glm-9.9" + + def test_dashboard_model_bind_column(): """Sessions 页交付 Model Bind 列(替换 Vendor Bind),PUT 走 model 字段.""" with _bindable_app() as client: diff --git a/tests/test_config_service.py b/tests/test_config_service.py index 0568208e..037b12af 100644 --- a/tests/test_config_service.py +++ b/tests/test_config_service.py @@ -1045,3 +1045,85 @@ def test_put_list_with_policy_wraps_to_dict(self, service): } view = service.view()["values"]["session_policies"] assert isinstance(view, dict) and len(view["policies"]) == 1 + + +# ── pricing 行不可删除(下线开关替代删除) ────────────────────── + + +def _pricing_rows(service: ConfigService) -> list[dict]: + return service.view()["values"]["pricing"] + + +def _set_pricing(service: ConfigService, rows: list[dict]): + return _http( + service, + { + "revisions": {"pricing": service.revision("pricing")}, + "sections": {"pricing": rows}, + }, + ) + + +class TestPricingNoDelete: + """pricing 行不可删除:删除 / 改名 / 恢复默认丢行一律 422,online 开关放行.""" + + def _rows_with_custom(self, service: ConfigService) -> list[dict]: + rows = _pricing_rows(service) + rows.append( + {"vendor": "zhipu", "model": "glm-5.5", "input_cost_per_mtok": "$1.0"} + ) + return rows + + def test_add_row_allowed(self, service): + result = _set_pricing(service, self._rows_with_custom(service)) + assert "pricing" in result.changed_sections + models = {r["model"] for r in _pricing_rows(service)} + assert "glm-5.5" in models + + def test_delete_custom_row_rejected(self, service): + _set_pricing(service, self._rows_with_custom(service)) + rows = [r for r in _pricing_rows(service) if r.get("model") != "glm-5.5"] + with pytest.raises(ConfigValidationError) as ei: + _set_pricing(service, rows) + err = _errors(ei)[0] + assert err["loc"] == ["pricing"] + assert "不可删除" in err["msg"] + + def test_delete_default_row_rejected(self, service): + rows = _pricing_rows(service) + assert len(rows) >= 2 # 包内默认定价表非空 + with pytest.raises(ConfigValidationError) as ei: + _set_pricing(service, rows[1:]) + assert "不可删除" in _errors(ei)[0]["msg"] + + def test_rename_model_rejected(self, service): + rows = _pricing_rows(service) + rows[0] = dict(rows[0], model="renamed-model") + with pytest.raises(ConfigValidationError) as ei: + _set_pricing(service, rows) + assert "不可删除" in _errors(ei)[0]["msg"] + + def test_online_toggle_roundtrip(self, service): + rows = _pricing_rows(service) + rows[0] = dict(rows[0], online=False) + _set_pricing(service, rows) + assert _pricing_rows(service)[0]["online"] is False + rows = _pricing_rows(service) + rows[0] = {k: v for k, v in rows[0].items() if k != "online"} + _set_pricing(service, rows) + assert "online" not in _pricing_rows(service)[0] + + def test_reset_section_with_custom_row_rejected(self, service): + _set_pricing(service, self._rows_with_custom(service)) + with pytest.raises(ConfigValidationError) as ei: + service.reset_section("pricing") + assert "不可删除" in _errors(ei)[0]["msg"] + + def test_error_does_not_leak_values(self, service): + rows = _pricing_rows(service) + dropped = rows[0] + with pytest.raises(ConfigValidationError) as ei: + _set_pricing(service, rows[1:]) + msg = _errors(ei)[0]["msg"] + assert str(dropped.get("model")) not in msg + assert str(dropped.get("vendor")) not in msg diff --git a/tests/test_dashboard_charts.py b/tests/test_dashboard_charts.py index 2f086ac6..780099d6 100644 --- a/tests/test_dashboard_charts.py +++ b/tests/test_dashboard_charts.py @@ -17,6 +17,7 @@ ) _CHARTS = ( + ("buildTimeline", "chart-timeline"), ("buildVendorDist", "chart-vendor-dist"), ("buildTokenTimeline", "chart-token-timeline"), ("buildModelTokenTimeline", "chart-model-token-timeline"), @@ -56,6 +57,29 @@ def test_chart_builders_keep_canvas_in_dom(client: TestClient): assert pattern not in source, (builder, pattern) +def test_trend_charts_are_stacked_areas_with_empty_states(client: TestClient): + """三张趋势图共用一个页签图位:折线填到上一条堆叠线,空数据时显示「暂无数据」而不是空坐标轴.""" + script = _inline_script(client.get("/dashboard").text) + for builder in ("buildTimeline", "buildTokenTimeline", "buildModelTokenTimeline"): + source = _extract_function(script, f"function {builder}(") + assert "fill: i === 0 ? 'start' : '-1'," in source, builder + assert "chartEmpty(ctx);" in source, builder + # 空态提示只有文字:不依赖 emoji 图标(各平台渲染不一) + assert "note.textContent = '暂无数据';" in _extract_function( + script, "function chartEmpty(" + ) + # 销毁后随即清空实例引用:空态分支返回后,不能再对已销毁的实例调用 update + for builder, instance in ( + ("buildTimeline", "chartTimeline"), + ("buildTokenTimeline", "chartTokenTimeline"), + ("buildModelTokenTimeline", "chartModelTokenTimeline"), + ): + source = _extract_function(script, f"function {builder}(") + assert ( + f"if ({instance}) {{ {instance}.destroy(); {instance} = null; }}" in source + ), builder + + def test_chart_empty_state_class_pairs_with_selector(client: TestClient): """chartEmpty 打的类名必须能被 chartContext 的选择器命中,否则空态提示清不掉、逐轮残留.""" script = _inline_script(client.get("/dashboard").text) @@ -93,12 +117,12 @@ def test_chart_empty_state_class_pairs_with_selector(client: TestClient): getElementById(id) { return canvases[id] || null; }, createElement() { return { - className: '', innerHTML: '', + className: '', textContent: '', remove() { const p = this.parentElement; p.children.splice(p.children.indexOf(this), 1); }, }; }, }; - for (const id of ['chart-vendor-dist', 'chart-token-timeline', 'chart-model-token-timeline']) canvases[id] = makeCanvas(id); + for (const id of ['chart-timeline', 'chart-vendor-dist', 'chart-token-timeline', 'chart-model-token-timeline']) canvases[id] = makeCanvas(id); for (const id of Object.keys(canvases)) { const canvas = canvases[id]; @@ -108,7 +132,7 @@ def test_chart_empty_state_class_pairs_with_selector(client: TestClient): chartEmpty(ctx); // 数据清空:显示空态 assert.strictEqual(canvas.style.display, 'none'); assert.strictEqual(canvas.parentElement.notes().length, 1); - assert.ok(canvas.parentElement.notes()[0].innerHTML.includes('暂无数据')); + assert.ok(canvas.parentElement.notes()[0].textContent.includes('暂无数据')); ctx = chartContext(id); // 下一次刷新:空态清除、canvas 复原(旧实现在此抛 TypeError) assert.strictEqual(ctx.canvas, canvas); assert.strictEqual(canvas.style.display, ''); diff --git a/tests/test_dashboard_config_tab.py b/tests/test_dashboard_config_tab.py index 31827140..0426a506 100644 --- a/tests/test_dashboard_config_tab.py +++ b/tests/test_dashboard_config_tab.py @@ -400,6 +400,28 @@ def test_sessions_cells_get_truncation_tooltip(client: TestClient): assert.deepStrictEqual(h.pricingMergeRows(['pricing'], saved, dflt, dflt), []); assert.ok(h.validToken('A'.repeat(32)) && !h.validToken('short') && !h.validToken('a b'.repeat(16))); assert.ok(h.isTmpl({ $tmpl: '${X}' }) && !h.isTmpl({ $tmpl: 1 })); + + // 保存后果清单:无后果为空(不弹确认框);在途请求、密钥、地址变更、熔断、移除 vendor 各自成条 + const view0 = { running: { tiers: ['a'], boot_revisions: {} }, revisions: {} }; + const plain = { sections: { failover: {} }, secret_ops: {}, revisions: {} }; + assert.deepStrictEqual(h.saveImpact({ payload: plain, base: {}, work: {}, view: view0, status: { in_flight: 0, tiers: [] }, cleared: [], chain: ['a'] }), []); + const codes = o => h.saveImpact(o).map(x => x.code); + assert.deepStrictEqual(codes({ payload: plain, base: {}, work: {}, view: view0, status: { in_flight: 2, tiers: [] }, cleared: [], chain: ['a'] }), ['inflight']); + const sec = { sections: {}, secret_ops: { 'vendors.zhipu.api_key': { op: 'clear' } }, revisions: {} }; + const it = h.saveImpact({ payload: sec, base: {}, work: {}, view: view0, status: null, cleared: [], chain: ['a'] }); + assert.deepStrictEqual(it.map(x => [x.code, x.danger]), [['secrets', true]]); + assert.ok(h.saveImpact({ payload: plain, base: {}, work: {}, view: view0, status: null, cleared: ['vendors.zhipu.api_key'], chain: ['a'] })[0].danger); + assert.deepStrictEqual(codes({ payload: plain, base: {}, work: {}, view: view0, status: { tiers: [{ name: 'a', circuit_breaker: { state: 'open' } }] }, cleared: [], chain: ['a'] }), ['breaker']); + const vpay = { sections: { vendors: [] }, secret_ops: {}, revisions: {} }; + assert.ok(codes({ payload: vpay, base: { vendors: [{ vendor: 'kimi' }] }, work: { vendors: [] }, view: view0, status: null, cleared: [], chain: ['a'] }).includes('removed')); + // 字段级 diff:vendors 按名配对、pricing 按 vendor + model 配对,未配上的行记为新增 / 移除 + const lab = { label: p => p.split('.').pop(), skip: () => false, sectionLabel: s => s, rowTitle: (s, r) => r.vendor + '/' + r.model }; + const g = h.changedRows( + { vendors: [{ vendor: 'zhipu', timeout_ms: 1 }], pricing: [{ vendor: 'a', model: 'x' }, { vendor: 'a', model: 'y' }] }, + { vendors: [{ vendor: 'zhipu', timeout_ms: 2 }], pricing: [{ vendor: 'a', model: 'y' }] }, lab); + assert.deepStrictEqual(g.map(x => x.title), ['vendors › zhipu', 'pricing']); + assert.deepStrictEqual([g[0].rows[0].label, g[0].rows[0].before, g[0].rows[0].after], ['timeout_ms', '1', '2']); + assert.deepStrictEqual(g[1].rows.map(r => [r.label, !!r.removed]), [['a/x', true]]); console.log('ok'); """ ) @@ -482,7 +504,7 @@ class Node { for (let n = this; n; n = n.parentNode) (n.listeners[t] || []).forEach(f => f(Object.assign(e, { currentTarget: n }))); } click() { if (!this.disabled) this.dispatch('click'); } - focus() {} + focus() { doc.activeElement = this; } scrollIntoView() {} showModal() { this.open = true; } close() { this.open = false; } @@ -586,15 +608,19 @@ class Node { const pill = name => root.querySelector('.cfg-pills .range-btn[data-pill="' + name + '"]').click(); const banners = () => root.querySelectorAll('.cfg-banner-text').map(b => b.textContent); const rows = () => root.querySelectorAll('.cfg-list-row'); - const delRow = i => rows()[i].querySelector('.cfg-btn-danger').click(); + const actionBtn = (row, label) => row.querySelectorAll('.cfg-cell-actions .cfg-btn').find(b => b.textContent === label); + const undo = () => root.querySelectorAll('.cfg-savebar .cfg-link').find(b => b.textContent === '撤销'); (async () => { - // 1) 未覆盖 pricing:删除默认行不出现「合并」banner + // 1) pricing 行不可删除:已保存行无「删除」,以「下线」产生本地修改;未覆盖时无「合并」banner view = mkView([], pricing.slice()); await CT.refresh(true); pill('pricing'); - delRow(0); - assert.strictEqual(rows().length, 1); + assert.strictEqual(rows()[0].querySelector('.cfg-btn-danger'), null, 'saved pricing row must not offer delete'); + assert.strictEqual(rows()[1].querySelector('.cfg-btn-danger'), null); + actionBtn(rows()[0], '下线').click(); + assert.strictEqual(rows().length, 2); + assert.ok(rows()[0].textContent.includes('Offline'), 'offline row shows Status Offline'); assert.ok(!banners().some(t => t.includes('包内默认定价')), banners().join('|')); assert.ok(tabBtn.classList.contains('cfg-dirty')); @@ -604,7 +630,7 @@ class Node { assert.strictEqual(CT.isDirty(), false); assert.strictEqual(tabBtn.classList.contains('cfg-dirty'), false); - // 1b) 已覆盖 pricing:仅统计已保存表中缺失的默认行;本地未保存删除不计入;合并后消失 + // 1b) 已覆盖 pricing:仅统计已保存表中缺失的默认行;合并补齐后提示消失 store['coding-proxy.admin-token'] = 'T'.repeat(43); view = mkView(['pricing'], pricing.slice(0, 1)); await CT.refresh(true); @@ -612,10 +638,8 @@ class Node { const hint = () => banners().filter(t => t.includes('包内默认定价')); assert.deepStrictEqual(hint().length, 1); assert.ok(hint()[0].includes(' 1 行'), hint()[0]); - delRow(0); - assert.ok(hint()[0].includes(' 1 行'), hint()[0]); root.querySelectorAll('.cfg-banner .cfg-btn').find(b => b.textContent === '合并').click(); - assert.deepStrictEqual(rows().map(r => r.textContent.includes('y')), [true]); + assert.deepStrictEqual(rows().map(r => r.textContent.includes('y')), [false, true]); assert.strictEqual(hint().length, 0); // 5) pills 为 group + aria-current(不再声明缺少 tab 子项的 tablist) @@ -696,7 +720,10 @@ class Node { await until(() => !CT.isDirty() && !root.querySelector('.cfg-body').hasAttribute('inert'), 'still saving'); assert.strictEqual(root.querySelector('.cfg-body').getAttribute('aria-busy'), null); assert.strictEqual(chips(), '429,500'); - assert.ok(banners().some(t => t.startsWith('已保存并生效')), banners().join('|')); + const bar6 = root.querySelector('.cfg-savebar').textContent; + assert.ok(bar6.includes('已保存并生效'), bar6); + assert.ok(!banners().some(t => t.startsWith('已保存')), banners().join('|')); + assert.strictEqual(confirms.length, confirmsDuring, 'routine save must not ask for confirmation'); net.putGate = Promise.resolve(); // 7) PUT 200 但随后 GET 失败:本地已落定(无 dirty、无待设置明文),「已保存」提示仍可见 @@ -726,8 +753,13 @@ class Node { const confirmsAfter = confirms.length; await CT.refresh(false); assert.strictEqual(confirms.length, confirmsAfter, 'asked to discard already-saved changes'); - assert.ok(root.querySelector('.cfg-savebar').hidden); assert.ok(!root.querySelectorAll('input').some(i => i.value === PLAIN)); + const bar7 = root.querySelector('.cfg-savebar'); + assert.ok(!bar7.hidden && bar7.textContent.includes('已保存并生效'), bar7.textContent); + const close7 = root.querySelectorAll('.cfg-savebar .cfg-btn').find(b => b.textContent === '关闭'); + assert.ok(close7, 'result state must be dismissible'); + close7.click(); + assert.ok(root.querySelector('.cfg-savebar').hidden); // 8) Esc 只隐藏当前说明;再次悬停 / 聚焦其他 ⓘ 时恢复显示 pill('failover'); @@ -757,7 +789,7 @@ class Node { saveBtn().click(); await until(() => net.puts.length > putsBefore9 && !CT.isDirty() && !root.querySelector('.cfg-body').hasAttribute('inert'), 'save not finished'); assert.deepStrictEqual(net.puts[net.puts.length - 1].secret_ops, { 'auth.google_client_secret': { op: 'clear' } }); - const note = banners().find(t => t.startsWith('已保存')); + const note = root.querySelector('.cfg-savebar').textContent; assert.ok(note && !note.startsWith('已保存并生效') && note.includes('CLI 登录'), String(note)); // 10) 排序后展开行仍指向原条目:move 对夹在区间内的展开下标做 ∓1 平移 @@ -771,17 +803,28 @@ class Node { pill('model_mapping'); rows()[1].click(); // 展开 B(index 1) assert.ok(root.querySelector('.cfg-detail-row .cfg-row[data-path="model_mapping.1.pattern"]')); + rows()[0].querySelector('.cfg-btn-icon[aria-label="下移"]').focus(); rows()[0].querySelector('.cfg-btn-icon[aria-label="下移"]').click(); // [A,B,C] → [B,A,C] assert.ok(root.querySelector('.cfg-detail-row .cfg-row[data-path="model_mapping.0.pattern"]'), 'expanded row must follow the original entry after move'); assert.ok(root.querySelectorAll('.cfg-detail-row').length === 1); + const moved = doc.activeElement; + assert.ok(moved && moved.tagName === 'BUTTON' && moved.getAttribute('aria-label') === '下移' && + moved.closest('[data-path]').getAttribute('data-path') === 'model_mapping.1', 'focus must follow the moved row'); + + // 10b) 「添加」后焦点落在新行自己的编辑表单(此时另一行处于展开状态) + root.querySelectorAll('.cfg-section-head .cfg-btn').find(b => b.textContent === '添加').click(); + const added = doc.activeElement; + assert.ok(added && added.tagName === 'INPUT' && added.closest('.cfg-detail-row') && + added.closest('.cfg-detail-row').querySelector('.cfg-row').getAttribute('data-path') === 'model_mapping.3.pattern', + 'focus must land in the newly added row, not an already expanded one'); // 11) 409 + 定向重载失败:不保留「已重新加载」承诺;重试仅重载冲突 section view = mkView([], pricing.slice()); view.values.failover = { status_codes: [429] }; await CT.refresh(true); pill('pricing'); - delRow(0); // pricing 与 failover 同时有本地修改 + actionBtn(rows()[0], '下线').click(); // pricing 与 failover 同时有本地修改 pill('failover'); addChip('500'); assert.ok(CT.isDirty()); @@ -799,6 +842,81 @@ class Node { assert.ok(chips().includes('500')); assert.ok(!root.textContent.includes('但重新加载失败')); net.put409 = null; + + // 12) pricing 行生命周期:下线 ↔ 上线;已保存行 vendor/model 只读、价格可改;恢复默认价格保留自定义行;新增行可移除并撤销 + // 注:Node shim 的 dispatch 不模拟 stopPropagation,行内按钮点击会连带触发行展开(真实浏览器不会) + view = mkView(['pricing'], pricing.slice()); + await CT.refresh(true); + pill('pricing'); + actionBtn(rows()[0], '下线').focus(); + actionBtn(rows()[0], '下线').click(); + assert.ok(rows()[0].textContent.includes('Offline'), 'offline row shows Status Offline'); + assert.ok(doc.activeElement && doc.activeElement.textContent === '上线', 'focus follows the row action whose label just changed'); + const vInp = root.querySelector('.cfg-row[data-path="pricing.0.vendor"] input'); + assert.ok(vInp && vInp.disabled, 'saved row vendor is readonly'); + assert.ok(root.querySelector('.cfg-row[data-path="pricing.0.model"] input').disabled, 'saved row model is readonly'); + const priceInp = root.querySelector('.cfg-row[data-path="pricing.0.input_cost_per_mtok"] input'); + priceInp.value = '9.0'; priceInp.dispatch('input'); + root.querySelectorAll('.cfg-section-head .cfg-btn').find(b => b.textContent === '添加').click(); + assert.strictEqual(rows().length, 3); + assert.ok(rows()[2].querySelector('.cfg-btn-danger'), 'unsaved row can still be removed'); + root.querySelectorAll('.cfg-section-head .cfg-btn').find(b => b.textContent === '恢复默认价格').click(); + assert.strictEqual(rows().length, 3, 'custom row survives restore-defaults'); + assert.ok(rows()[0].textContent.includes('$1.0'), 'default row price restored'); + assert.ok(rows()[1].textContent.includes('$2.0')); + const confirmsBefore = confirms.length; + rows()[2].querySelector('.cfg-btn-danger').click(); + assert.strictEqual(rows().length, 2); + assert.strictEqual(confirms.length, confirmsBefore, 'row removal must not ask for confirmation'); + assert.ok(undo(), 'row removal must offer undo'); + undo().click(); + assert.strictEqual(rows().length, 3, 'undo puts the removed row back'); + rows()[2].querySelector('.cfg-btn-danger').click(); // 再移除一次,保持后续步骤的前置状态 + assert.strictEqual(rows().length, 2); + actionBtn(rows()[0], '下线').click(); + assert.ok(rows()[0].textContent.includes('Offline')); + rows()[0].click(); // shim 连带展开后的收起(浏览器中此处不会展开) + actionBtn(rows()[0], '上线').click(); + assert.ok(rows()[0].textContent.includes('Online'), 'online row shows Status Online'); + + // 13) Per-Model 行移除后保存栏给「撤销」,撤销恢复该模型的上限 + view = mkView([], pricing.slice()); + view.registry.fields = registry.concat([ + { path: 'vendors.*.concurrency', label: 'Concurrency', widget: 'optional_group', vendors: ['zhipu'], group: 'Concurrency', description: '并发' }, + { path: 'vendors.*.concurrency.models', label: 'Per-Model', widget: 'map', vendors: ['zhipu'], group: 'Concurrency', description: '上限' }, + ]); + view.values.vendors = [{ vendor: 'zhipu', enabled: true, concurrency: { models: { 'glm-x': 3 } } }]; + await CT.refresh(true); + pill('vendors'); + assert.strictEqual(root.querySelector('.cfg-map-row span.cfg-map-key').textContent, 'glm-x'); + root.querySelector('.cfg-map-row .cfg-btn-sm').click(); // 移除 glm-x + assert.strictEqual(root.querySelector('.cfg-map-row span.cfg-map-key'), null); + assert.ok(undo(), 'map removal must offer undo immediately'); + undo().click(); + assert.strictEqual(root.querySelector('.cfg-map-row span.cfg-map-key').textContent, 'glm-x', 'undo restores the removed limit'); + assert.strictEqual(CT.isDirty(), false); + + // 14) 移除 vendor 后撤销把它插回 vendors 与 tiers 的原位;期间重新添加会清掉撤销入口,不产生重复 vendor + view = mkView([], pricing.slice()); + view.registry.fields = registry.concat([{ path: 'tiers', label: 'Tiers', widget: 'list', description: '链路', enum: ['zhipu', 'kimi'] }]); + view.values.vendors = [{ vendor: 'zhipu', enabled: true }, { vendor: 'kimi', enabled: true }]; + view.values.tiers = ['zhipu', 'kimi']; + view.defaults.vendors = [{ vendor: 'zhipu', enabled: true }, { vendor: 'kimi', enabled: true }]; + await CT.refresh(true); + pill('vendors'); + const pills = () => root.querySelectorAll('.cfg-subpills .range-btn[data-vendor]').map(x => x.getAttribute('data-vendor')); + const removeVendorBtn = () => root.querySelector('.cfg-vendor-head .cfg-btn-danger'); + removeVendorBtn().click(); // window.confirm 桩恒为 true + assert.deepStrictEqual(pills(), ['kimi', 'zhipu']); + assert.ok(undo(), 'vendor removal must offer undo'); + undo().click(); + assert.deepStrictEqual(pills(), ['zhipu', 'kimi'], 'undo puts the vendor back at its original position'); + assert.strictEqual(CT.isDirty(), false); + removeVendorBtn().click(); + assert.ok(undo()); + root.querySelectorAll('.cfg-body .cfg-btn-primary').find(b => b.textContent === '添加').click(); // 在「未配置」视图里重新添加 zhipu + assert.strictEqual(undo(), undefined, 're-adding the vendor clears the undo entry'); + assert.deepStrictEqual(pills(), ['kimi', 'zhipu']); console.log('ok'); })().catch(e => { console.error(e && e.stack || e); process.exit(1); }); """ diff --git a/tests/test_dashboard_overview.py b/tests/test_dashboard_overview.py new file mode 100644 index 00000000..7d2b8171 --- /dev/null +++ b/tests/test_dashboard_overview.py @@ -0,0 +1,1307 @@ +"""Dashboard Overview 的 KPI 条、Model Calling 列表、趋势页签与订阅区溢出提示:HTML 接线(静态检查)与内联 JS 行为(Node).""" + +from __future__ import annotations + +import re +import textwrap + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from coding.proxy.server.dashboard import register_dashboard_routes +from tests.test_dashboard_subscription_card import ( + _NODE, + _extract_block, + _extract_function, + _inline_script, + _run_node, +) + +_KPI_CARDS = ( + ("req", "今日请求数", "kpi-card"), + ("tok", "今日 Token 总量", "kpi-card"), + ("out", "今日输出 Token", "kpi-card"), + ("cost", "今日费用估算", "kpi-card kpi-cost"), + ("fo", "今日故障转移", "kpi-card"), + ("lat", "今日平均延迟", "kpi-card"), +) +_TREND_TABS = ( + ("requests", "请求量", "chart-timeline"), + ("tokens", "Token(按供应商)", "chart-token-timeline"), + ("models", "Token(Vendor / 模型)", "chart-model-token-timeline"), +) + + +@pytest.fixture +def client() -> TestClient: + app = FastAPI() + register_dashboard_routes(app) + return TestClient(app, base_url="http://127.0.0.1:3392") + + +def _attrs(tag: str) -> dict[str, str]: + return dict(re.findall(r"([\w-]+)=\"([^\"]*)\"", tag)) + + +def _rule(html: str, selector: str) -> str: + match = re.search(r"(?m)^\s*" + re.escape(selector) + r"\s*\{([^}]*)\}", html) + assert match, f"{selector} 规则缺失" + return match.group(1) + + +# ── HTML / CSS 接线 ──────────────────────────────────────────────────────── + + +def test_overview_status_row_and_trend_card_wired(client: TestClient): + """订阅状态与供应商请求分布并排;三张趋势图收进一个页签图位,页签与面板的 ARIA 引用两两对应.""" + html = client.get("/dashboard").text + assert 'class="charts-grid' not in html + row_at = html.index('
') + trend_tag_at = html.rindex( + "", trend_tag_at)] + tablist_at = trend.index('role="tablist"') + tablist = trend[: trend.index("
", tablist_at)] + assert 'role="tablist" aria-label="趋势图"' in tablist + tab_tags = re.findall(r"") + assert panel["id"] == panel_id and panel["aria-labelledby"] == tab_id + assert panel["role"] == "tabpanel" and panel["tabindex"] == "0" + # 面板只靠 aria-labelledby 取名:再写 aria-label 会被它覆盖,等于没写 + assert "aria-label" not in panel + # 只有当前页签的面板可见(hidden 是布尔属性,没有值) + assert (" hidden" in panel_tags[i]) is (i != 0) + panel_at = html.rindex( + '
", panel_at) : canvas_at] + # 页签类名另起一套:.tab-btn / .tab-pane 被页首主页签的状态逻辑按类名全文档匹配 + assert not re.search(r'class="[^"]*\btab-(btn|pane)\b[^"]*trend', html) + assert 'class="trend-range" id="trend-range"' in trend + for gone in ( + "title-timeline", + "title-token-timeline", + "title-model-token-timeline", + ): + assert gone not in html + + +def test_overview_kpi_and_model_calling_markup(client: TestClient): + """KPI 是一条 strip(标签、数值、副行,无图标与装饰色类);Model Calling 标题不带 emoji.""" + html = client.get("/dashboard").text + grid = html[html.index('
') :] + grid = grid[: grid.index("\n
")] + cards = re.split(r"(?=
'), key + assert f'
{label}
' in card + assert f'
' in card + assert f'
' in card + assert "kpi-icon" not in html + assert not re.search( + r"class=\"[^\"]*\bcolor-(blue|purple|green|yellow|red|orange)\b", html + ) + + title = html[html.index('id="model-calling-card"') :] + title = title[title.index('
') :] + title = title[: title.index("
")] + assert title.startswith('
Model Calling 实时状态') + assert title.endswith('每 10 秒刷新') + # 并行度编辑结果的播报节点写在模板里,而不是首次播报时才插入(首条内容可能被读屏漏掉) + assert ( + '
' + in html + ) + assert html.count('id="mc-live"') == 1 + + +def test_overview_css_constraints(client: TestClient): + """布局硬约束落在 CSS 上:两栏列宽与堆叠断点、KPI 列、Model Calling 定宽列、页签下划线、渐隐提示.""" + html = client.get("/dashboard").text + assert "clamp(280px, 24vw, 360px)" in _rule(html, ".status-row") + assert ".status-row { grid-template-columns: minmax(0, 1fr);" in _rule( + html, "@media (max-width: 1179px)" + ) + assert ( + "repeat(3, minmax(0, 1fr)) minmax(0, 1.45fr) repeat(2, minmax(0, 1fr))" + in _rule(html, ".kpi-grid") + ) + assert "@media (max-width: 1023px)" in html and "@media (max-width: 519px)" in html + # 计数列定宽:条形终点逐行对齐,不随「4/10」「5/8」的字数变化 + assert ( + "minmax(72px, 96px) minmax(0, 1.5fr) minmax(80px, 1fr) 64px minmax(80px, auto)" + in _rule(html, ".mc-row") + ) + # 上限按钮与编辑输入框同宽:进入编辑态列不跳;命中区不小于 24×24 + editable = _rule(html, ".mc-limit-editable") + assert "width: 40px;" in editable and "min-height: 24px;" in editable + assert "rgba(88,166,255,.8)" in editable # 虚线是非文字对比信息:对行底色不低于 3:1 + assert "width: 40px; height: 24px;" in _rule(html, ".mc-limit-input") + assert "@media (min-width: 1280px)" in html and "@media (max-width: 759px)" in html + assert "border-bottom-color: var(--accent-blue)" in _rule( + html, '.trend-tab[aria-selected="true"]' + ) + # 负下边距:选中页签的下划线盖住头部 hairline;负左边距:首个页签的文字与其它卡片标题左对齐 + assert "margin: 0 0 -1px -12px;" in _rule(html, ".trend-tabs") + # 区间标签只有「近 N 天」:标签与说明都不需要任意断行 + assert "white-space: nowrap;" in _rule(html, ".trend-range") + assert "white-space: nowrap;" in _rule(html, ".kpi-sub-label, .kpi-sub-val") + # 可聚焦的页签面板有与全页一致的焦点环(2px 蓝色,画在内侧) + focus = _rule(html, ".trend-panel:focus-visible") + assert "outline: 2px solid var(--accent-blue); outline-offset: -2px;" in focus + # 分布卡图形区的 flex-basis 为 0:钉在 canvas 上一次写下的像素高度上,左卡变矮后这一行回不去 + assert "flex: 1 1 0;" in _rule(html, ".dist-card .chart-wrap") + # 模型名最多折两行,不默认截断(全名只在 title 里,键盘与触屏拿不到) + name = html[html.index(".mc-model-name {\n font-size: 12px") :] + assert "-webkit-line-clamp: 2" in name[: name.index("}")] + # 手机两列:先清掉 3 列布局的列内边距,再排 2 列(同特异性下后写的赢,末列才是 24px) + phone = html[html.index("@media (max-width: 519px)") :] + assert re.findall(r"\.kpi-card:nth-child\(([^)]*)\) \{ ([^}]*?);? \}", phone) == [ + ( + "3n+1", + "border-left: 1px solid rgba(255,255,255,.06); padding-left: 16px; padding-right: 16px", + ), + ("3n", "padding-right: 16px"), + ("2n+1", "border-left: 0; padding-left: 24px"), + ("2n", "padding-right: 24px"), + ("n+3", "border-top: 1px solid rgba(255,255,255,.06)"), + ] + # 简化后不再有引用的规则与变量已删除 + for dead in (".sb-ok", "--glow-blue:", "--accent-orange:", "--text-muted:"): + assert dead not in html, dead + assert "linear-gradient(90deg, #000 calc(100% - 28px), transparent)" in _rule( + html, ".vendor-badges.has-more" + ) + # 新增小字不用 --text-tertiary:它在卡片底色上只有 4.02:1,不到 AA + for selector in ( + ".kpi-sub", + ".mc-model-name", + ".mc-meter-note", + ".mc-peak", + ".card-note", + ".trend-range", + ): + assert "--text-tertiary" not in _rule(html, selector), selector + + +def test_overview_scripts_avoid_unsafe_dom_writes(client: TestClient): + """KPI、Model Calling 与图表摘要的文案全部来自接口,只能经 textContent / setAttribute 写入.""" + script = _inline_script(client.get("/dashboard").text) + for signature in ( + "function updateKPI(", + "function updateModelCalling(", + "function _mcBuildRow(", + "function _mcUpdateRow(", + "function _mcAnnounce(", + "function startLimitEdit(", + "function setTrendTab(", + "function setChartSummary(", + ): + assert "innerHTML" not in _extract_function(script, signature), signature + # 上限按钮的点击由挂在 document 上的事件委托接管(页面没有别的委托 click 处理器,不需要捕获阶段) + listener = _extract_function( + script, "document.addEventListener('click', function (e) {" + ) + assert listener.startswith("document.addEventListener('click', function (e) {") + assert "startLimitEdit(btn);" in listener and "_mcPendingEdit = btn;" in listener + assert ( + script.count("startLimitEdit(") == 3 + ) # 定义一次,监听器与上一段编辑的收尾各调用一次 + # 页面原有的 CSS 规则管不到 canvas:减少动态时关掉 Chart.js 的画布动画 + assert ( + "if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) {\n" + " Chart.defaults.animation = false;" in script + ) + + +# ── 内联 JS 行为(Node) ──────────────────────────────────────────────────── + +# 最小假 DOM:只实现被测函数用到的表面(类名、属性、数据集、子节点、事件、焦点、按类名查询)。 +# 没有 HTML 解析:被测代码一旦改回 innerHTML 拼接,这里就直接失败 +_FAKE_DOM = textwrap.dedent( + r""" + const byId = {}; + // 假计时器按时长推进:advance(ms) 只触发这段时间内到期的回调(8 秒兜底不会被 50 毫秒的失焦守卫顺带触发) + const timers = new Map(); let clock = 0; let timerSeq = 0; + const setTimeout = (fn, ms) => { timers.set(++timerSeq, { fn: fn, at: clock + (ms || 0) }); return timerSeq; }; + const clearTimeout = (id) => { timers.delete(id); }; + const advance = (ms) => { + clock += ms; + for (let due = [...timers].filter(([, t]) => t.at <= clock); due.length; due = [...timers].filter(([, t]) => t.at <= clock)) { + due.forEach(([id, t]) => { timers.delete(id); t.fn(); }); + } + }; + const tick = () => new Promise((resolve) => setImmediate(resolve)); + + class FakeEl { + constructor(tag) { + this.tagName = String(tag).toUpperCase(); + this.children = []; this.parentNode = null; + this.className = ''; this.dataset = {}; this.attrs = {}; this.style = {}; + this._text = ''; this._handlers = {}; this._id = ''; + this.classList = { + add: (...cs) => { this.className = Array.from(new Set(this.className.split(/\s+/).filter(Boolean).concat(cs))).join(' '); }, + remove: (...cs) => { this.className = this.className.split(/\s+/).filter((c) => c && !cs.includes(c)).join(' '); }, + contains: (c) => this.className.split(/\s+/).includes(c), + toggle: (c, force) => { + const on = force === undefined ? !this.classList.contains(c) : !!force; + if (on) this.classList.add(c); else this.classList.remove(c); + return on; + }, + }; + } + set id(value) { this._id = String(value); byId[this._id] = this; } + get id() { return this._id; } + // 是否挂在树上:假 DOM 用 root 充当文档,祖先链上有 root 才算已连接(被移除的行连同它的子节点一起断开) + get isConnected() { for (let n = this; n; n = n.parentNode) if (n === root) return true; return false; } + get nextSibling() { + if (!this.parentNode) return null; + return this.parentNode.children[this.parentNode.children.indexOf(this) + 1] || null; + } + setAttribute(k, v) { this.attrs[k] = String(v); if (k === 'class') this.className = String(v); } + getAttribute(k) { return k in this.attrs ? this.attrs[k] : null; } + get textContent() { return this._text + this.children.map((c) => c.textContent).join(''); } + set textContent(v) { this.children.slice().forEach((c) => c.remove()); this._text = String(v); } + appendChild(c) { c.remove(); c.parentNode = this; this.children.push(c); return c; } + append(...cs) { cs.forEach((c) => this.appendChild(c)); } + insertBefore(node, ref) { + this.appendChild(node); + if (ref && ref !== node) { + this.children.splice(this.children.indexOf(node), 1); + this.children.splice(this.children.indexOf(ref), 0, node); + } + return node; + } + // 移除带焦点的节点会触发 blur(原实现的第二个 PUT 就是从这里发出的) + remove() { + const hadFocus = document.activeElement === this; + if (this.parentNode) this.parentNode.children.splice(this.parentNode.children.indexOf(this), 1); + this.parentNode = null; + if (hadFocus) { document.activeElement = null; (this._handlers.blur || []).forEach((fn) => fn({})); } + } + replaceChildren(...cs) { this.children.slice().forEach((c) => c.remove()); cs.forEach((c) => this.appendChild(c)); } + // 选择器只支持本页用到的简单形态:#id、.class、tag 的组合,以及「#id .class」后代 + matches(sel) { + const id = (sel.match(/#([\w-]+)/) || [])[1]; + if (id && this._id !== id) return false; + const have = this.className.split(/\s+/); + if (!(sel.match(/\.[\w-]+/g) || []).every((c) => have.includes(c.slice(1)))) return false; + const bare = sel.replace(/#[\w-]+/g, '').replace(/\.[\w-]+/g, '').trim(); + return !bare || this.tagName === bare.toUpperCase(); + } + closest(sel) { for (let el = this; el; el = el.parentNode) if (el.matches(sel)) return el; return null; } + querySelectorAll(sel) { + const parts = sel.trim().split(/\s+/); + const scope = parts.length === 2 && parts[0].startsWith('#') ? byId[parts[0].slice(1)] : this; + const last = parts[parts.length - 1]; + const out = []; + const walk = (el) => el.children.forEach((c) => { if (c.matches(last)) out.push(c); walk(c); }); + if (scope) walk(scope); + return out; + } + querySelector(sel) { return this.querySelectorAll(sel)[0] || null; } + addEventListener(type, fn) { (this._handlers[type] = this._handlers[type] || []).push(fn); } + fire(type, ev) { // 触发监听器,返回是否拦截了默认行为 + const event = Object.assign({ defaultPrevented: false, preventDefault() { this.defaultPrevented = true; } }, ev); + (this._handlers[type] || []).forEach((fn) => fn(event)); + return event.defaultPrevented; + } + focus() { document.activeElement = this; } + select() {} + insertAdjacentHTML(pos, html) { // 被测代码只用它插入铅笔图标 + const m = html.match(/^<(\w+)[^>]*class="([^"]*)"/); + const node = new FakeEl(m[1]); node.className = m[2]; this.appendChild(node); + } + } + // body: null:假 DOM 用 null 表示焦点落空,等价于真实 DOM 里焦点回到 document.body + const document = { activeElement: null, body: null, createElement: (tag) => new FakeEl(tag), getElementById: (id) => byId[id] || null }; + const el = (tag, cls, text) => { const n = new FakeEl(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n; }; + const root = new FakeEl('root'); + document.querySelector = (sel) => root.querySelectorAll(sel)[0] || null; + document.querySelectorAll = (sel) => root.querySelectorAll(sel); + """ +) + + +def _sources(script: str, *signatures: str) -> str: + return "\n".join(_extract_function(script, signature) for signature in signatures) + + +def _kpi_harness(script: str) -> str: + return ( + "const assert = require('assert');\n" + + _FAKE_DOM + + "let currentDays = 7;\nconst MAX_RANGE_DAYS = 90;\nlet refreshed = 0;\n" + "const refresh = () => { refreshed += 1; };\n" + + _sources( + script, + "function localDateStr(", + "function rangeLabel(", + "function applyCustomRange(", + "function costParts(", + "function updateKPI(", + "function fmtTokens(", + "function fmtNum(", + ) + + textwrap.dedent( + r""" + const start = el('input', ''); start.id = 'range-start'; + const end = el('input', ''); end.id = 'range-end'; + const nodes = {}; + for (const key of ['req', 'tok', 'out', 'cost', 'fo', 'lat']) { + nodes[key] = { today: el('div', 'kpi-value'), week: el('div', 'kpi-sub') }; + nodes[key].today.id = 'kpi-' + key + '-today'; nodes[key].week.id = 'kpi-' + key + '-week'; + } + const partsOf = (node) => node.children.map((c) => c.textContent); + const summary = (todayCost, rangeCost) => ({ + today: { requests: 2583, tokens: { input: 1, output: 800700, cache_creation: 2, cache_read: 3 }, failovers: 3, avg_duration_ms: 4820, cost: todayCost }, + range: { requests: 14237, tokens: { input: 0, output: 4410000, cache_creation: 0, cache_read: 0 }, failovers: 21, avg_duration_ms: 4820, cost: rangeCost }, + }); + + // 区间标签只由取数天数决定:接口取的是截至今天的最近 N 天,自选区间也只折算成天数 + assert.strictEqual(rangeLabel(7), '近 7 天'); + assert.strictEqual(rangeLabel(30), '近 30 天'); + // 本地日期:东八区凌晨(UTC 仍是前一天)也写本地的今天 + assert.strictEqual(localDateStr(new Date(2026, 10, 27, 1, 0)), '2026-11-27'); + assert.strictEqual(localDateStr(new Date(2026, 0, 5, 23, 59)), '2026-01-05'); + + // 自选区间:起止日期折算成天数(含首尾两天);反向区间、缺一端都不取数 + start.value = '2026-11-01'; end.value = '2026-11-07'; + applyCustomRange(); + assert.deepStrictEqual([currentDays, refreshed], [7, 1]); + start.value = '2026-11-20'; end.value = '2026-11-15'; + applyCustomRange(); + assert.deepStrictEqual([currentDays, refreshed], [7, 1]); + start.value = ''; + applyCustomRange(); + assert.deepStrictEqual([currentDays, refreshed], [7, 1]); + // 超出接口上限(90 天)按 90 天取数,标签与实际取数一致 + start.value = '2025-12-20'; end.value = '2026-06-30'; + applyCustomRange(); + assert.deepStrictEqual([currentDays, refreshed], [90, 2]); + + // 费用按「 + 」拆段:第二段带加号;没有费用时是一格「–」 + assert.deepStrictEqual(costParts('¥54.24'), ['¥54.24']); + assert.deepStrictEqual(costParts('¥298.96 + $412.37'), ['¥298.96', '+\u00a0$412.37']); // 加号后是不换行空格 + assert.deepStrictEqual(costParts(''), ['–']); + assert.deepStrictEqual(costParts(null), ['–']); + + // 副行标签取这批数据实际取数的天数(入参),不读页面当前选中的区间 + currentDays = 30; + updateKPI(summary('¥54.24', '¥298.96 + $412.37'), 12); + assert.strictEqual(nodes.req.today.textContent, '2,583'); + assert.deepStrictEqual(partsOf(nodes.req.week), ['近 12 天', '14,237']); + assert.deepStrictEqual(nodes.req.week.children.map((c) => c.className), ['kpi-sub-label', 'kpi-sub-val']); + assert.strictEqual(nodes.tok.today.textContent, '800.7K'); + assert.deepStrictEqual(partsOf(nodes.tok.week), ['近 12 天', '4.41M']); + assert.strictEqual(nodes.out.today.textContent, '800.7K'); + assert.deepStrictEqual(partsOf(nodes.out.week), ['近 12 天', '4.41M']); + assert.deepStrictEqual(partsOf(nodes.cost.today), ['¥54.24']); + assert.deepStrictEqual(partsOf(nodes.cost.week), ['近 12 天', '¥298.96', '+\u00a0$412.37']); + assert.strictEqual(nodes.fo.today.textContent, '3'); + assert.strictEqual(nodes.lat.today.textContent, '4820ms'); + + // 重复刷新整体重写,不残留上一轮的段;没有费用时是一格「–」 + updateKPI(summary('', null), 12); + assert.deepStrictEqual(partsOf(nodes.cost.week), ['近 12 天', '–']); + assert.strictEqual(nodes.lat.today.textContent, '4820ms'); + // 没有请求数与延迟时都是「–」 + updateKPI({ today: { requests: null, tokens: {}, failovers: null, avg_duration_ms: 0, cost: '' }, range: { requests: null, tokens: {}, failovers: null, avg_duration_ms: 0, cost: '' } }, 12); + assert.strictEqual(nodes.req.today.textContent, '–'); + assert.strictEqual(nodes.lat.today.textContent, '–'); + assert.deepStrictEqual(partsOf(nodes.lat.week), ['近 12 天', '–']); + // 文案原样进文本节点:带标签的字符串不会被当成标记 + updateKPI({ today: { requests: '', tokens: {}, failovers: 0, avg_duration_ms: 0, cost: 'x' }, range: { requests: 0, tokens: {}, failovers: 0, avg_duration_ms: 0, cost: '' } }, 7); + assert.strictEqual(nodes.req.today.textContent, ''); + assert.deepStrictEqual(nodes.req.today.children, []); + assert.deepStrictEqual(partsOf(nodes.cost.today), ['x']); + assert.ok(nodes.cost.today.children.every((c) => c.tagName === 'SPAN' && c.children.length === 0)); + console.log('kpi harness OK'); + """ + ) + ) + + +@pytest.mark.skipif(_NODE is None, reason="node 不可用") +def test_kpi_range_label_and_sub_lines(client: TestClient, tmp_path): + """区间标签一律「近 N 天」且跟着实际取数的天数走;副行由区间标签与数值段组成,费用按币种拆段,文案不拼 HTML.""" + script = _inline_script(client.get("/dashboard").text) + _run_node(tmp_path, "kpi_harness.js", _kpi_harness(script), "kpi harness OK") + + +# Model Calling harness 的公共前置:按 /api/status 的形状拼载荷(tiers[].diagnostics.concurrency[model]), +# 每个 tier 是 [名字, { 模型: [mode, limit, 在途, 排队, 最近 10 秒排队峰值] }] +_MC_PRELUDE = textwrap.dedent( + r""" + const _status = (...tiers) => { + const out = { tiers: [] }; + tiers.forEach(([name, models]) => { + const concurrency = {}; + Object.keys(models).forEach((model) => { + const [mode, limit, inUse, pending, peak] = models[model]; + const entry = { mode: mode, in_use: inUse, pending: pending, peak_pending_recent: peak }; + if (mode === 'limited') { entry.limit = limit; entry.available = limit - inUse - pending; } + concurrency[model] = entry; + }); + out.tiers.push({ name: name, diagnostics: { concurrency: concurrency } }); + }); + return out; + }; + const status = _status( + ['zhipu', { 'glm-4.6': ['limited', 10, 4, 1, 0], 'glm-4.5-air': ['limited', 6, 1, 0, 1] }], + ['anthropic', { 'claude-sonnet-4-5': ['limited', 8, 5, 2, 0] }], + ['copilot', { 'gpt-5': ['limited', 4, 1, 0, 0] }], + ); + // 与 status 同构,只把 glm-4.6 的上限换成 limit + const fullStatus = (limit) => { + const next = _status( + ['zhipu', { 'glm-4.6': ['limited', 10, 4, 1, 0], 'glm-4.5-air': ['limited', 6, 1, 0, 1] }], + ['anthropic', { 'claude-sonnet-4-5': ['limited', 8, 5, 2, 0] }], + ['copilot', { 'gpt-5': ['limited', 4, 1, 0, 0] }], + ); + next.tiers[0].diagnostics.concurrency['glm-4.6'].limit = limit; + return next; + }; + const card = el('div', 'card model-calling-card'); card.id = 'model-calling-card'; root.appendChild(card); + const wrap = el('div', ''); wrap.id = 'model-calling-wrap'; card.appendChild(wrap); + // 播报节点写在模板里(属性由 HTML 接线测试断言),这里只占位 + const live = el('div', 'sr-only'); live.id = 'mc-live'; card.appendChild(live); + const list = () => wrap.querySelector('.mc-list'); + const rows = () => (list() ? list().children.slice() : []); + const shown = (node) => node.style.display !== 'none'; // 与 CSS 的显隐一致:隐藏的段不算可见文案 + const useText = (row) => row.querySelector('.mc-use').children.filter(shown).map((c) => c.textContent).join(''); + const queueText = (row) => row.querySelector('.mc-queue').textContent; + const fillOf = (row) => row.querySelector('.mc-fill'); + const limitOf = (row) => row.querySelector('.mc-limit-editable'); + const puts = []; const asked = []; + let fetchJSON = (url) => { asked.push(url); return Promise.resolve({ tiers: [] }); }; + let fetch = (url, opts) => { puts.push(opts.body); return Promise.resolve({ ok: true }); }; + const limitClickListener = LIMIT_LISTENER; + const clickLimit = (btn) => limitClickListener({ target: btn, preventDefault() {} }); + """ +) + + +def _mc_harness(script: str, body: str) -> str: + prefix = "document.addEventListener('click', " + listener = _extract_function(script, prefix + "function (e) {") + assert listener.startswith(prefix) + return ( + "const assert = require('assert');\n" + + _FAKE_DOM + + _extract_block( + script, "const _mcRows = new Map();", "var _mcPendingEdit = null;" + ) + + "\n" + + _sources( + script, + "function _mcRowKey(", + "function _mcEl(", + "function _mcBuildRow(", + "function _mcUpdateRow(", + "function updateModelCalling(", + "function _mcAnnounce(", + "function startLimitEdit(", + "function limitValue(", + ) + + _MC_PRELUDE.replace("LIMIT_LISTENER", listener[len(prefix) :]) + + body + ) + + +@pytest.mark.skipif(_NODE is None, reason="node 不可用") +def test_model_calling_rows_are_keyed_and_aligned(client: TestClient, tmp_path): + """行节点按 vendor/model 键复用:刷新只改文字与条宽,行序跟随 tier,消失的模型被移除.""" + script = _inline_script(client.get("/dashboard").text) + _run_node( + tmp_path, + "mc_rows_harness.js", + _mc_harness( + script, + textwrap.dedent( + r""" + updateModelCalling(status); + assert.strictEqual(rows().length, 4); + assert.strictEqual(list().getAttribute('role'), 'list'); + assert.ok(list().classList.contains('mc-cols-2'), '不少于 3 行排两列'); + const first = rows(); + assert.deepStrictEqual(first.map((r) => r.dataset.key), ['zhipu/glm-4.6', 'zhipu/glm-4.5-air', 'anthropic/claude-sonnet-4-5', 'copilot/gpt-5']); + assert.ok(first.every((r) => r.getAttribute('role') === 'listitem')); + const glm = first[0]; + assert.strictEqual(glm.querySelector('.mc-vendor').textContent, 'zhipu'); + assert.strictEqual(glm.querySelector('.mc-model-name').textContent, 'glm-4.6'); + assert.strictEqual(glm.querySelector('.mc-model-name').title, 'zhipu/glm-4.6'); + assert.strictEqual(useText(glm), '4/10'); + assert.strictEqual(fillOf(glm).style.width, '40%'); + assert.ok(fillOf(glm).classList.contains('mc-low')); + assert.strictEqual(queueText(glm), '排队 1'); + const limit = limitOf(glm); + assert.strictEqual(limit.tagName, 'BUTTON', '真按钮:键盘可达'); + assert.deepStrictEqual([limit.getAttribute('data-tier'), limit.getAttribute('data-model'), limit.getAttribute('data-limit')], ['zhipu', 'glm-4.6', '10']); + assert.ok(limit.getAttribute('aria-label').includes('当前 10')); + assert.strictEqual(limit.querySelector('.mc-limit-val').textContent, '10'); + assert.ok(glm.querySelector('.mc-pencil'), '行悬停 / 聚焦时露出的铅笔图标'); + // 严重度阈值:不超过 50% 绿、不超过 80% 黄、其余红 + const sonnet = first[2]; + assert.strictEqual(fillOf(sonnet).style.width, '63%'); + assert.ok(fillOf(sonnet).classList.contains('mc-mid')); + assert.strictEqual(queueText(sonnet), '排队 2'); + // 当前无排队、最近 10 秒排过队:「曾排队 N」;都没有则留空槽位 + assert.strictEqual(queueText(first[1]), '曾排队 1'); + assert.strictEqual(queueText(first[3]), ''); + + // 同样的载荷再刷新:不重建节点;数值变化只就地更新 + updateModelCalling(status); + updateModelCalling(fullStatus(10)); + assert.deepStrictEqual(rows(), first); + const busy = _status( + ['zhipu', { 'glm-4.6': ['limited', 10, 9, 0, 5], 'glm-4.5-air': ['limited', 6, 1, 0, 1] }], + ['anthropic', { 'claude-sonnet-4-5': ['limited', 8, 5, 2, 0] }], + ['copilot', { 'gpt-5': ['limited', 4, 1, 0, 0] }], + ); + updateModelCalling(busy); + assert.deepStrictEqual(rows(), first); + assert.strictEqual(useText(glm), '9/10'); + assert.strictEqual(fillOf(glm).style.width, '90%'); + assert.ok(fillOf(glm).classList.contains('mc-high')); + assert.strictEqual(queueText(glm), '曾排队 5'); + assert.strictEqual(glm.querySelector('.mc-meter').title, '并行度 9 / 10'); + + // 行序 = tier 顺序(路由优先级):节点不重建,只换位置 + updateModelCalling({ tiers: [status.tiers[2], status.tiers[0], status.tiers[1]] }); + assert.deepStrictEqual(rows().map((r) => r.dataset.key), ['copilot/gpt-5', 'zhipu/glm-4.6', 'zhipu/glm-4.5-air', 'anthropic/claude-sonnet-4-5']); + assert.strictEqual(rows()[1], glm); + + // 消失的模型被移除;少于 3 行不再排两列 + updateModelCalling(_status(['zhipu', { 'glm-4.6': ['limited', 10, 4, 0, 0] }])); + assert.deepStrictEqual(rows().map((r) => r.dataset.key), ['zhipu/glm-4.6']); + assert.strictEqual(rows()[0], glm); + assert.ok(!list().classList.contains('mc-cols-2') && _mcRows.size === 1); + + // monitor 模式:没有上限,不画进度条,计数写成「N 进行中」 + // (说明文字分宽屏 / 窄屏两份,由 CSS 只显示其一) + updateModelCalling(_status(['antigravity', { 'gemini-3-pro-preview': ['monitor', null, 2, 0, 0] }])); + const monitor = rows()[0]; + assert.ok(monitor.classList.contains('mc-monitor')); + assert.strictEqual(useText(monitor), '2进行中'); + assert.strictEqual(limitOf(monitor).style.display, 'none'); + assert.strictEqual(monitor.querySelector('.mc-meter-note').textContent, '仅监控 · 不限并行度仅监控'); + assert.strictEqual(monitor.querySelector('.mc-badge'), null); + updateModelCalling(status); + assert.ok(!glm.classList.contains('mc-monitor') && limitOf(glm).style.display === ''); + + // 没有 concurrency 诊断的 tier 不出行;全空显示空态并清掉缓存 + updateModelCalling({ tiers: [{ name: 'zhipu' }, { name: 'anthropic', diagnostics: {} }] }); + assert.strictEqual(wrap.querySelector('.mc-empty').textContent, '无活跃模型调用'); + assert.strictEqual(_mcRows.size, 0); + updateModelCalling({ tiers: [] }); + assert.strictEqual(wrap.children.length, 1); + console.log('mc rows harness OK'); + """ + ), + ), + "mc rows harness OK", + ) + + +@pytest.mark.skipif(_NODE is None, reason="node 不可用") +def test_model_calling_limit_edit_flow(client: TestClient, tmp_path): + """并行度编辑:只收 1 到 20 的整数;编辑中整张表不重绘;每次编辑只发一个 PUT;结束或超时后焦点回到按钮.""" + script = _inline_script(client.get("/dashboard").text) + _run_node( + tmp_path, + "mc_edit_harness.js", + _mc_harness( + script, + textwrap.dedent( + r""" + // 输入判定:7.5、1e2、全角数字、越界都按非法处理,不截断后提交 + for (const raw of ['0', '21', '7.5', '1e2', '007', '7', '', '-1', '1.0', null, undefined, '']) { + assert.ok(Number.isNaN(limitValue(raw)), String(raw)); + } + for (const [raw, want] of [['1', 1], ['7', 7], ['20', 20], [' 8 ', 8]]) assert.strictEqual(limitValue(raw), want, String(raw)); + + updateModelCalling(status); + const btn = limitOf(rows()[0]); + let inputs = 0; + const created = document.createElement; + document.createElement = (tag) => { inputs += 1; return created(tag); }; + const lastInput = () => { const node = btn.nextSibling; assert.strictEqual(node.className, 'mc-limit-input'); return node; }; + const edit = () => { clickLimit(btn); return lastInput(); }; + let resolvePut; + const hang = () => { fetch = (url, opts) => { puts.push(opts.body); return new Promise((resolve) => { resolvePut = resolve; }); }; }; + + // 打开编辑:输入框插到按钮之后并聚焦,整张表进入「编辑中」 + hang(); + let input = edit(); + assert.strictEqual(inputs, 1); + assert.strictEqual(input.getAttribute('aria-label'), 'zhipu/glm-4.6 的并行度上限(1 到 20 的整数)'); + assert.strictEqual(input.value, '10'); + assert.strictEqual(document.activeElement, input); + assert.strictEqual(btn.style.display, 'none'); + assert.ok(_mcEditing); + // 编辑中点别处的上限:不开第二个编辑器,这次点击记下来等当前编辑结束再接手(见 test_model_calling_limit_edit_hands_off_to_next_row) + clickLimit(limitOf(rows()[1])); + assert.strictEqual(inputs, 1); + assert.strictEqual(_mcPendingEdit, limitOf(rows()[1])); + _mcPendingEdit = null; // 下面只验证单行流程,丢掉这次点击 + // 编辑中轮询到达:不重绘,输入框、已输入的内容与焦点都原样保留(原实现在这里提交半截输入) + input.value = '1'; + const drawn = rows(); + updateModelCalling(_status(['zhipu', { 'glm-4.6': ['limited', 3, 3, 0, 0], 'new-model': ['limited', 1, 0, 0, 0] }])); + assert.deepStrictEqual(rows(), drawn); + assert.strictEqual(btn.nextSibling, input); + assert.strictEqual(input.value, '1'); + assert.strictEqual(document.activeElement, input); + // 编辑期间上限按钮是隐藏的:在途数与上限的原值都没被上一步的轮询改掉 + assert.strictEqual(drawn[0].querySelector('.mc-in').textContent + '/' + btn.querySelector('.mc-limit-val').textContent, '4/10'); + assert.deepStrictEqual(puts, []); + + // 补输成 12 回车:只提交一次;PUT 未决期间再按回车、再失焦都不再提交 + input.value = '12'; + assert.strictEqual(input.fire('keydown', { key: 'Enter' }), true); + input.fire('keydown', { key: 'Enter' }); + input.fire('blur', {}); + advance(1000); // 只过 1 秒:失焦守卫到期,8 秒兜底还没到 + assert.deepStrictEqual(puts, ['{"tier":"zhipu","model":"glm-4.6","limit":12}']); + assert.ok(_mcEditing, 'PUT 未决期间仍是编辑中'); + assert.strictEqual(btn.nextSibling, input); + // 成功后:这一行立刻按新上限重算(条形、可访问名称),并拉一次状态对齐服务端 + fetchJSON = (url) => { asked.push(url); return Promise.resolve(fullStatus(12)); }; + resolvePut({ ok: true }); + return tick().then(() => { + assert.strictEqual(document.activeElement, btn, '焦点回到上限按钮'); + assert.ok(btn.classList.contains('mc-limit-ok') && !_mcEditing && btn.style.display === ''); + assert.strictEqual(rows().length, 4); + assert.strictEqual(useText(rows()[0]), '4/12'); + assert.strictEqual(fillOf(rows()[0]).style.width, '33%'); + assert.ok(btn.getAttribute('aria-label').includes('当前 12')); + assert.deepStrictEqual(asked, ['/api/status']); + // 输入框移除引发的 blur 不会再提交第二次(原实现在这里连发两个 PUT) + advance(2000); + assert.strictEqual(puts.length, 1); + // 播报节点来自模板(属性由 HTML 接线测试断言) + assert.strictEqual(live, byId['mc-live']); + assert.strictEqual(live.textContent, 'zhipu/glm-4.6 的并行度已更新为 12'); + assert.ok(!btn.classList.contains('mc-limit-ok'), '静态色标 1.5 秒后清除'); + + // Esc:不提交,值不变 + input = edit(); + input.value = '5'; + input.fire('keydown', { key: 'Escape' }); + assert.strictEqual(puts.length, 1); + assert.strictEqual(document.activeElement, btn); + assert.strictEqual(btn.querySelector('.mc-limit-val').textContent, '12'); + + // 没改动直接回车:不提交 + input = edit(); + input.fire('keydown', { key: 'Enter' }); + assert.strictEqual(puts.length, 1); + + // 非整数 / 越界:不提交,上限标红,播报原因 + for (const bad of ['7.5', '21', '0', '1e2']) { + input = edit(); + input.value = bad; + input.fire('keydown', { key: 'Enter' }); + assert.strictEqual(puts.length, 1, bad); + assert.ok(btn.classList.contains('mc-limit-err'), bad); + assert.strictEqual(document.activeElement, btn, bad); + advance(2000); + assert.strictEqual(live.textContent, '并行度须是 1 到 20 的整数'); + } + + // PUT 失败:值不变,标红,解除编辑 + fetch = (url, opts) => { puts.push(opts.body); return Promise.resolve({ ok: false, status: 500 }); }; + input = edit(); + input.value = '8'; + input.fire('keydown', { key: 'Enter' }); + return tick().then(() => { + assert.strictEqual(puts[1], '{"tier":"zhipu","model":"glm-4.6","limit":8}'); + assert.strictEqual(btn.querySelector('.mc-limit-val').textContent, '12'); + assert.ok(btn.classList.contains('mc-limit-err') && !_mcEditing); + advance(2000); + assert.strictEqual(live.textContent, 'zhipu/glm-4.6 的并行度更新失败'); + + // PUT 悬住:8 秒兜底解除编辑态,标红,焦点回到按钮;迟到的成功不再改动这一行 + puts.length = 0; + hang(); + input = edit(); + input.value = '6'; + input.fire('keydown', { key: 'Enter' }); + assert.ok(_mcEditing); + advance(9000); // 8 秒兜底计时器到点,收尾在微任务里完成 + return tick().then(() => { + assert.ok(!_mcEditing && btn.style.display === '', '超时后解除编辑态'); + assert.strictEqual(document.activeElement, btn); + assert.ok(btn.classList.contains('mc-limit-err')); + assert.strictEqual(btn.querySelector('.mc-limit-val').textContent, '12'); + resolvePut({ ok: true }); + return tick().then(() => { + assert.strictEqual(btn.querySelector('.mc-limit-val').textContent, '12'); + advance(2000); + assert.strictEqual(live.textContent, 'zhipu/glm-4.6 的并行度更新失败'); + console.log('mc edit harness OK'); + }); + }); + }); + }); + """ + ), + ), + "mc edit harness OK", + ) + + +@pytest.mark.skipif(_NODE is None, reason="node 不可用") +def test_model_calling_limit_edit_hands_off_to_next_row(client: TestClient, tmp_path): + """编辑一行时点另一行的上限:当前编辑结束后接着打开那一行(这次点击不被吞掉);焦点已被移走或那一行已消失则作废.""" + script = _inline_script(client.get("/dashboard").text) + _run_node( + tmp_path, + "mc_handoff_harness.js", + _mc_harness( + script, + textwrap.dedent( + r""" + updateModelCalling(status); + const [rowA, rowB] = rows(); + const btnA = limitOf(rowA), btnB = limitOf(rowB); + const inputOf = (btn) => { const node = btn.nextSibling; return node && node.className === 'mc-limit-input' ? node : null; }; + const hang = () => { fetch = (url, opts) => { puts.push(opts.body); return new Promise((resolve) => { resolvePut = resolve; }); }; }; + let resolvePut; + + // 鼠标流:编辑 A 时点 B。浏览器先让 A 的输入框失焦,再派发点击;失焦守卫要 50 毫秒后才提交, + // 点击到达时仍是「编辑中」:记下 B,而不是把这次点击吞掉(原实现要再点一次才进编辑) + clickLimit(btnA); + const inputA = inputOf(btnA); + inputA.value = '12'; + btnB.focus(); + inputA.fire('blur', {}); + clickLimit(btnB); + assert.strictEqual(_mcPendingEdit, btnB); + assert.strictEqual(inputOf(btnB), null, 'A 还在编辑:不同时开两个编辑器'); + advance(50); + assert.deepStrictEqual(puts, ['{"tier":"zhipu","model":"glm-4.6","limit":12}']); + return tick().then(() => { + const inputB = inputOf(btnB); + assert.ok(inputB, 'A 提交完成后接着打开 B'); + assert.strictEqual(inputB.getAttribute('aria-label'), 'zhipu/glm-4.5-air 的并行度上限(1 到 20 的整数)'); + assert.strictEqual(document.activeElement, inputB); + assert.strictEqual(_mcPendingEdit, null); + assert.ok(_mcEditing, 'B 进入编辑,整张表仍是编辑中'); + assert.strictEqual(wrap.querySelectorAll('.mc-limit-input').length, 1); + assert.strictEqual(btnB.style.display, 'none'); + assert.strictEqual(btnA.style.display, ''); + assert.strictEqual(btnA.querySelector('.mc-limit-val').textContent, '12'); + assert.deepStrictEqual(puts.length, 1); + // B 按 Esc:不提交,焦点回到 B 的按钮 + inputB.fire('keydown', { key: 'Escape' }); + assert.strictEqual(puts.length, 1); + assert.strictEqual(document.activeElement, btnB); + assert.ok(!_mcEditing); + + // 键盘流:A 的输入框还聚焦时点了 B(Safari 不把焦点给按钮),A 回车提交后焦点直接交给 B 的输入框 + puts.length = 0; + clickLimit(btnA); + const inputA2 = inputOf(btnA); + inputA2.value = '11'; + clickLimit(btnB); + assert.strictEqual(btnA.nextSibling, inputA2, '点击不打断正在进行的编辑'); + assert.strictEqual(document.activeElement, inputA2); + inputA2.fire('keydown', { key: 'Enter' }); + return tick().then(() => { + assert.deepStrictEqual(puts, ['{"tier":"zhipu","model":"glm-4.6","limit":11}']); + assert.strictEqual(document.activeElement, inputOf(btnB)); + inputOf(btnB).fire('keydown', { key: 'Escape' }); + + // 点了 B 之后焦点又被移到别处(例如开始操作别的控件):不抢焦点,这次点击作废 + puts.length = 0; + hang(); + clickLimit(btnA); + const inputA3 = inputOf(btnA); + inputA3.value = '9'; + inputA3.fire('keydown', { key: 'Enter' }); + clickLimit(btnB); + const elsewhere = el('button', 'range-btn'); root.appendChild(elsewhere); elsewhere.focus(); + resolvePut({ ok: true }); + return tick().then(() => { + assert.strictEqual(inputOf(btnB), null, '不抢焦点'); + assert.strictEqual(_mcPendingEdit, null); + assert.strictEqual(document.activeElement, elsewhere); + assert.ok(!_mcEditing); + + // 排队的那一行在当前编辑结束前已不在页面上了:作废,也不把整张表留在「编辑中」 + clickLimit(btnA); + const inputA4 = inputOf(btnA); + inputA4.value = '7'; + clickLimit(btnB); + rowB.remove(); + inputA4.fire('keydown', { key: 'Escape' }); + assert.strictEqual(inputOf(btnB), null); + assert.strictEqual(_mcPendingEdit, null); + assert.ok(!_mcEditing); + console.log('mc handoff harness OK'); + }); + }); + }); + """ + ), + ), + "mc handoff harness OK", + ) + + +# 时间区间与刷新循环的 harness 前置:取数换成可手动放行的假函数(记下每次用的天数), +# 其余全局与真实脚本同形。refreshOverview 里「取回后记下 overviewDays」这一行由静态断言守住 +_RANGE_PRELUDE = textwrap.dedent( + r""" + let refreshing = false; + let currentTab = 'overview'; let currentDays = 7; let overviewDays = 0; + const tabLoaded = { overview: false, sessions: false, config: false }; + const TAB_LABELS = { overview: 'Overview', sessions: 'Sessions', config: 'Config' }; + const now = () => '22:00:23'; + globalThis.window = {}; + const errors = []; + const console = Object.assign({}, globalThis.console, { error: (...args) => errors.push(args.map(String).join(' ')) }); + const refreshTime = el('div', ''); refreshTime.id = 'refresh-time'; + const title = el('div', 'card-title'); title.id = 'title-vendor-dist'; + const range = el('span', 'trend-range'); range.id = 'trend-range'; + const start = el('input', 'range-date'); start.id = 'range-start'; + const end = el('input', 'range-date'); end.id = 'range-end'; + const custom = el('div', 'range-custom'); custom.id = 'range-custom'; + const fetches = []; let release = null; let failNext = false; let configFetches = 0; + const refreshSessions = () => Promise.resolve(); + const refreshOverview = async () => { + const days = currentDays > 0 ? currentDays : 7; + const mine = {}; release = mine; + await new Promise((resolve) => { mine.resolve = resolve; }); + if (failNext) { failNext = false; throw new Error('fetch failed'); } + overviewDays = days; + updateChartTitles(days); + fetches.push(days); + }; + window.ConfigTab = { refresh: async () => { configFetches += 1; if (configFetches > 5) throw new Error('loop'); } }; + """ +) + + +def _range_harness(script: str, body: str) -> str: + return ( + "const assert = require('assert');\n" + + _FAKE_DOM + + _RANGE_PRELUDE + + "const MAX_RANGE_DAYS = 90;\n" + + _sources( + script, + "function localDateStr(", + "function rangeLabel(", + "function setTimeRange(", + "function applyCustomRange(", + "function updateChartTitles(", + ) + # _extract_function 从 function 起截,async 修饰符要自己补回 + + "async " + + _extract_function(script, "function refresh(") + + "\n" + + textwrap.dedent(body) + ) + + +@pytest.mark.skipif(_NODE is None, reason="node 不可用") +def test_refresh_reruns_when_range_changes_mid_flight(client: TestClient, tmp_path): + """刷新途中改时间区间:那次 refresh() 被在途标记挡掉,但当前这轮结束后按新区间补刷;取数失败不补刷(否则空转).""" + script = _inline_script(client.get("/dashboard").text) + # 标签与摘要读的是这批数据实际取数的天数:取回后先记入 overviewDays,再渲染 + overview = _extract_function(script, "function refreshOverview(") + assert overview.index("overviewDays = days;") < overview.index( + "updateKPI(summary, days);" + ) + assert overview.index("overviewDays = days;") < overview.index( + "updateChartTitles(days);" + ) + assert "fetchJSON('/api/dashboard/summary?days=' + days)" in overview + _run_node( + tmp_path, + "range_refresh_harness.js", + _range_harness( + script, + r""" + // 首轮刷新途中点「近 30 天」:按钮状态立即切换;这次 refresh() 被在途标记挡掉,不另起取数 + const btn30 = el('button', 'range-btn'); root.appendChild(btn30); + const first = refresh(); + assert.strictEqual(refreshTime.textContent, '刷新中…'); + assert.ok(refreshing); + setTimeRange(30, btn30); + assert.ok(btn30.classList.contains('active')); + assert.deepStrictEqual(fetches, []); + // 第一轮按旧区间收尾:已上屏的数据属于 7 天,标签跟着数据写「近 7 天」 + release.resolve(); + tick().then(() => { + assert.deepStrictEqual(fetches, [7]); + assert.strictEqual(title.textContent, '供应商请求分布(近 7 天)'); + // 发现区间已改:接着按新区间补刷(原实现把这次点击丢掉,数据和按钮各说各话) + assert.ok(refreshing); + assert.strictEqual(refreshTime.textContent, '刷新中…'); + release.resolve(); + return first; + }).then(() => { + assert.deepStrictEqual(fetches, [7, 30]); + assert.strictEqual(title.textContent, '供应商请求分布(近 30 天)'); + assert.strictEqual(range.textContent, '近 30 天'); + assert.ok(!refreshing && tabLoaded.overview); + assert.strictEqual(refreshTime.textContent, '上次刷新: 22:00:23(Overview)'); + + // 区间没变:只取一次 + const plain = refresh(); + release.resolve(); + return plain.then(() => { + assert.deepStrictEqual(fetches, [7, 30, 30]); + + // 取数失败:不补刷(否则接口不可达时会空转),在途标记复位,报错进控制台 + failNext = true; + const failed = refresh(); + release.resolve(); + return failed.then(() => { + assert.deepStrictEqual(fetches, [7, 30, 30]); + assert.ok(!refreshing); + assert.strictEqual(refreshTime.textContent, '刷新失败 22:00:23'); + assert.strictEqual(errors.length, 1); + + // 取数失败、且途中又改了区间:同样不补刷 + const failedToo = refresh(); + setTimeRange(12, null); + failNext = true; + release.resolve(); + return failedToo.then(() => { + assert.deepStrictEqual(fetches, [7, 30, 30]); + assert.strictEqual(errors.length, 2); + assert.strictEqual(currentDays, 12, '按钮状态保留用户的最后一次选择'); + + // 下一次刷新(手动 ⟳ 或 10 分钟轮询)按最后选的区间取数 + const next = refresh(); + release.resolve(); + return next.then(() => { + assert.deepStrictEqual(fetches, [7, 30, 30, 12]); + assert.strictEqual(title.textContent, '供应商请求分布(近 12 天)'); + + // 不在 Overview 页签时区间对不上也不循环:只刷新当前页签一次 + currentDays = 30; + currentTab = 'config'; + return refresh().then(() => { + assert.strictEqual(configFetches, 1); + assert.deepStrictEqual(fetches, [7, 30, 30, 12]); + currentTab = 'overview'; + console.log('range refresh harness OK'); + }); + }); + }); + }); + }); + }).catch((e) => { process.stderr.write(String((e && e.stack) || e) + '\n'); process.exit(1); }); +""", + ), + "range refresh harness OK", + ) + + +@pytest.mark.skipif(_NODE is None, reason="node 不可用") +def test_custom_range_defaults_to_local_dates(client: TestClient, tmp_path): + """自选区间默认带出本地今天的近 7 天:东八区 0 到 8 点不再把截止日写成 UTC 的昨天;天数超过接口上限按上限取.""" + script = _inline_script(client.get("/dashboard").text) + assert "toISOString" not in _extract_function(script, "function setTimeRange(") + _run_node( + tmp_path, + "range_custom_harness.js", + _range_harness( + script, + r""" + process.env.TZ = 'Asia/Shanghai'; + const RealDate = globalThis.Date; + const fakeNow = new RealDate(2026, 10, 27, 1, 0); // 本地 11-27 凌晨 1 点,UTC 还是 11-26 + globalThis.Date = class extends RealDate { constructor(...args) { super(...(args.length ? args : [fakeNow])); } }; + assert.strictEqual(new Date().toISOString().slice(0, 10), '2026-11-26', '前置:进程时区已切到东八区'); + + const btnCustom = el('button', 'range-btn'); root.appendChild(btnCustom); + setTimeRange(0, btnCustom); + assert.ok(custom.classList.contains('visible') && btnCustom.classList.contains('active')); + assert.deepStrictEqual([start.value, end.value], ['2026-11-21', '2026-11-27'], '起止日期是本地日期'); + assert.strictEqual(currentDays, 7); + release.resolve(); + tick().then(() => { + assert.deepStrictEqual(fetches, [7]); + assert.strictEqual(title.textContent, '供应商请求分布(近 7 天)'); + + // 超过接口上限(90 天)的自选区间:按 90 天取数,标签随之 + end.value = '2026-11-27'; start.value = '2026-01-01'; + applyCustomRange(); + assert.strictEqual(currentDays, 90); + release.resolve(); + return tick(); + }).then(() => { + assert.deepStrictEqual(fetches, [7, 90]); + assert.strictEqual(range.textContent, '近 90 天'); + + // 点回预设按钮:自选面板收起,按预设天数取数 + const btn30 = el('button', 'range-btn'); root.appendChild(btn30); + setTimeRange(30, btn30); + assert.ok(!custom.classList.contains('visible')); + release.resolve(); + return tick(); + }).then(() => { + assert.deepStrictEqual(fetches, [7, 90, 30]); + assert.strictEqual(title.textContent, '供应商请求分布(近 30 天)'); + console.log('range custom harness OK'); + }).catch((e) => { process.stderr.write(String((e && e.stack) || e) + '\n'); process.exit(1); }); + """, + ), + "range custom harness OK", + ) + + +@pytest.mark.skipif(_NODE is None, reason="node 不可用") +def test_chart_summaries_and_dist_legend_position(client: TestClient, tmp_path): + """图形读屏读不到:canvas 带 role=img 与一句文字摘要(区间、合计、峰值 / 各项占比);分布图图例在窄列移到下方.""" + script = _inline_script(client.get("/dashboard").text) + for builder, name in ( + ("buildTimeline", "请求量趋势"), + ("buildTokenTimeline", "Token 量趋势(按供应商)"), + ("buildModelTokenTimeline", "Token 用量趋势(Vendor / 模型)"), + ): + source = _extract_function(script, f"function {builder}(") + assert f"setChartSummary(ctx.canvas, trendSummary('{name}'," in source + assert source.index("chartEmpty(ctx);") < source.index( + "setChartSummary(" + ) # 空态不写摘要 + dist = _extract_function(script, "function buildVendorDist(") + assert ( + "position: distLegendPosition(ctx, legendLabels, ctx.canvas.parentElement.clientWidth)," + in dist + ) + assert "onResize: function (chart, size) {" in dist + assert ( + "chart.options.plugins.legend.position = distLegendPosition(chart.ctx, chart.data.labels, size.width);" + in dist + ) + # 图例宽度按 COMMON_LEGEND.labels 的色点、内边距与字体量出来:harness 用脚本里的同一份配置 + legend_labels = _extract_block( + script, "const COMMON_LEGEND = {", "font: { size: 13, weight: '500' }" + ) + assert "boxWidth: 10" in legend_labels and "padding: 14" in legend_labels + assert "供应商请求分布," in dist + + _run_node( + tmp_path, + "chart_summary_harness.js", + "const assert = require('assert');\n" + + _FAKE_DOM + + "let overviewDays = 30;\n" + + legend_labels + + "\n}};\n" + + _sources( + script, + "function setChartSummary(", + "function trendSummary(", + "function rangeLabel(", + "function fmtTokens(", + "function fmtNum(", + "function distLegendPosition(", + ) + + textwrap.dedent( + r""" + const canvas = new FakeEl('canvas'); + const dates = ['2026-11-23', '2026-11-24', '2026-11-25']; + const datasets = [ + { data: [1000, 0, 2500] }, + { data: [500, 250, null] }, // 缺值按 0 计 + { data: [0, undefined, 500] }, + ]; + assert.strictEqual(canvas.getAttribute('role'), null); + setChartSummary(canvas, trendSummary('请求量趋势', fmtNum, ' 次', dates, datasets)); + assert.strictEqual(canvas.getAttribute('role'), 'img'); + // 区间取最近一次取数的天数;合计与单日最高都按所有系列逐日相加 + assert.strictEqual( + canvas.getAttribute('aria-label'), + '请求量趋势,近 30 天:合计 4,750 次,单日最高 3,000 次(2026-11-25)', + ); + // 覆盖写入,不残留上一次的摘要 + setChartSummary(canvas, trendSummary('Token 量趋势(按供应商)', fmtTokens, ' Token', dates.slice(0, 1), datasets)); + assert.strictEqual( + canvas.getAttribute('aria-label'), + 'Token 量趋势(按供应商),近 30 天:合计 1.5K Token,单日最高 1.5K Token(2026-11-23)', + ); + + // 分布图图例:右侧图例最多占一半画布宽。宽度用图例自己的字体量:色点 + 字号的一半 + 文字宽。 + // 假字体每个字符 6px:17 个字符的「agy | antigravity」一项 118.5px,连内边距占 132.5px,画布不到 265px 就移到下方 + const fonts = []; + const ctx = { + canvas: { parentElement: { clientWidth: 0 } }, + save() {}, restore() {}, + set font(v) { fonts.push(v); }, + measureText: (text) => ({ width: text.length * 6 }), + }; + globalThis.Chart = { helpers: { toFont: (o) => Object.assign({}, o, { string: o.weight + ' ' + o.size + 'px fake' }) } }; + const labels = ['cc | zhipu', 'agy | antigravity']; + assert.strictEqual(distLegendPosition(ctx, labels, 265), 'right'); + assert.strictEqual(distLegendPosition(ctx, labels, 264.9), 'bottom'); + assert.strictEqual(distLegendPosition(ctx, labels, 233), 'bottom'); + // 标签短时更窄也放得下;没有标签不报错 + assert.strictEqual(distLegendPosition(ctx, ['cc | zhipu'], 181), 'right'); + assert.strictEqual(distLegendPosition(ctx, ['cc | zhipu'], 180), 'bottom'); + assert.strictEqual(distLegendPosition(ctx, [], 233), 'right'); + assert.deepStrictEqual(fonts, Array(6).fill('500 13px fake')); + console.log('chart summary harness OK'); + """ + ), + "chart summary harness OK", + ) + + +@pytest.mark.skipif(_NODE is None, reason="node 不可用") +def test_trend_tabs_switch(client: TestClient, tmp_path): + """页签切换同步 aria-selected / tabindex / 面板 hidden;方向键循环、Home / End 到首尾,切焦点即选中.""" + script = _inline_script(client.get("/dashboard").text) + _run_node( + tmp_path, + "trend_tabs_harness.js", + "const assert = require('assert');\n" + + _FAKE_DOM + + _extract_block(script, "const TREND_CHARTS = {", "};") + + "\n" + + _sources(script, "function showTrendChart(", "function setTrendTab(") + + "\nconst initTrendTabs = " + + _extract_function(script, "function initTrendTabs(") + + ";\n" + + textwrap.dedent( + r""" + const keys = ['requests', 'tokens', 'models']; + const tablist = el('div', 'trend-tabs'); root.appendChild(tablist); + const tabs = keys.map((key, i) => { + const tab = el('button', 'trend-tab', 'x'); + tab.dataset.trend = key; tab.tabIndex = i === 0 ? 0 : -1; tab.setAttribute('aria-selected', i === 0 ? 'true' : 'false'); + tab.id = 'trend-tab-' + key; tablist.appendChild(tab); + return tab; + }); + const panels = keys.map((key, i) => { + const panel = el('div', 'trend-panel'); panel.id = 'trend-panel-' + key; panel.hidden = i !== 0; + root.appendChild(panel); return panel; + }); + // 每个页签一项:选中用大写,可见加叹号 + const state = () => keys.map((key, i) => (tabs[i].getAttribute('aria-selected') === 'true' ? key[0].toUpperCase() : key[0]) + (panels[i].hidden ? '' : '!')).join(' '); + const calls = []; + const askedFor = []; + const stubs = {}; + for (const key of keys) { + stubs[TREND_CHARTS[key]] = { resize: () => calls.push('resize'), stop: () => calls.push('stop'), update: (mode) => calls.push('update:' + mode) }; + } + globalThis.window = { Chart: { getChart: (id) => { askedFor.push(id); return stubs[id]; } } }; + globalThis.Chart = globalThis.window.Chart; + initTrendTabs(); + assert.strictEqual(state(), 'R! t m'); + + // 面板由隐藏变可见:resize → stop → update('none'),只作用于当前页签的图 + // (Chart.js 在 resize 里建的 attach 动画要先停掉,update('none') 取消不了在途动画) + setTrendTab('tokens', false); + assert.strictEqual(state(), 'r T! m'); + assert.deepStrictEqual(askedFor, ['chart-token-timeline']); + assert.deepStrictEqual(calls, ['resize', 'stop', 'update:none']); + assert.strictEqual(tabs[1].tabIndex, 0); + assert.ok(tabs[0].tabIndex === -1 && tabs[2].tabIndex === -1); + assert.strictEqual(document.activeElement, null, '鼠标点击不抢焦点'); + setTrendTab('models', true); + assert.strictEqual(state(), 'r t M!'); + assert.strictEqual(document.activeElement, tabs[2]); + + // 方向键:← → 循环,Home / End 到首尾;切焦点即选中 + const press = (from, key) => { calls.length = 0; return tablist.fire('keydown', { key: key, target: tabs[from] }); }; + assert.strictEqual(press(2, 'ArrowRight'), true); // 末尾回绕到首个 + assert.strictEqual(state(), 'R! t m'); + assert.strictEqual(document.activeElement, tabs[0]); + assert.strictEqual(press(0, 'ArrowLeft'), true); // 首个回绕到末尾 + assert.strictEqual(state(), 'r t M!'); + press(2, 'Home'); + assert.strictEqual(state(), 'R! t m'); + assert.strictEqual(document.activeElement, tabs[0]); + press(0, 'End'); + assert.strictEqual(state(), 'r t M!'); + assert.deepStrictEqual(calls, ['resize', 'stop', 'update:none']); + // 水平页签不拦截 ↑ ↓(留给页面滚动),其它按键也不管 + assert.strictEqual(press(2, 'ArrowDown'), false); + assert.strictEqual(press(2, 'Enter'), false); + assert.strictEqual(state(), 'r t M!'); + + // 点击页签;点在页签行的空白处不做事 + tablist.fire('click', { target: tabs[0] }); + assert.strictEqual(state(), 'R! t m'); + tablist.fire('click', { target: tablist }); + assert.strictEqual(state(), 'R! t m'); + + // 图还没建出来(首轮刷新未完成)或 Chart.js 不可达:照常切换,不报错 + globalThis.window.Chart.getChart = () => null; + setTrendTab('tokens', false); + assert.strictEqual(state(), 'r T! m'); + globalThis.window = {}; + setTrendTab('models', false); + assert.strictEqual(state(), 'r t M!'); + console.log('trend tabs harness OK'); + """ + ), + "trend tabs harness OK", + ) + + +@pytest.mark.skipif(_NODE is None, reason="node 不可用") +def test_zone_overflow_cue(client: TestClient, tmp_path): + """订阅区放不下的提示按各分区自己的溢出量判断,滚到头提示消失.""" + script = _inline_script(client.get("/dashboard").text) + _run_node( + tmp_path, + "zone_cue_harness.js", + "const assert = require('assert');\n" + + _FAKE_DOM + + _sources(script, "function syncZoneCues(") + + textwrap.dedent( + r""" + const card = el('div', 'card subscription-card'); card.id = 'subscription-card'; root.appendChild(card); + const other = el('div', 'card'); root.appendChild(other); // 别的卡片里的同名分区不受影响 + const zone = (parent, cls, scrollWidth, clientWidth) => { + const z = el('span', cls); z.scrollWidth = scrollWidth; z.clientWidth = clientWidth; z.scrollLeft = 0; parent.appendChild(z); return z; + }; + const fits = zone(card, 'vendor-badges sub-zone', 300, 300); + const over = zone(card, 'vendor-badges sub-zone', 410, 300); + const tier = zone(card, 'vendor-badges tier-zone', 90, 90); + const elsewhere = zone(other, 'vendor-badges sub-zone', 410, 300); + const cues = () => [fits, over, tier, elsewhere].map((z) => z.classList.contains('has-more')); + syncZoneCues(); + assert.deepStrictEqual(cues(), [false, true, false, false]); + // 滚到头:只剩 1px 以内的舍入余量就不算「后面还有」 + over.scrollLeft = 108; + syncZoneCues(); + assert.ok(over.classList.contains('has-more')); + over.scrollLeft = 109; + syncZoneCues(); + assert.ok(!over.classList.contains('has-more')); + console.log('zone cue harness OK'); + """ + ), + "zone cue harness OK", + ) diff --git a/tests/test_dashboard_subscription_card.py b/tests/test_dashboard_subscription_card.py index f2093849..b56d7b25 100644 --- a/tests/test_dashboard_subscription_card.py +++ b/tests/test_dashboard_subscription_card.py @@ -32,9 +32,9 @@ def _inline_script(html: str) -> str: def _card(html: str) -> str: - """截取合并卡片的 HTML 片段(起点为卡片 id,终点为紧随其后的折线图卡片).""" + """截取合并卡片的 HTML 片段(起点为卡片 id,终点为同一水平栏里紧随其后的分布卡).""" start = html.index('id="subscription-card"') - return html[start : html.index('class="card timeline-card"', start)] + return html[start : html.index('
', start)] def test_subscription_card_wired(client: TestClient): @@ -45,9 +45,9 @@ def test_subscription_card_wired(client: TestClient): assert 'id="btn-vendor-reset"' in card assert 'id="vendor-list"' in card assert card.index('id="vendor-list"') < card.index('id="subscription-list"') - # 原「供应商状态」卡片不再独立存在,折线图脱离网格变全宽 + # 原「供应商状态」卡片不再独立存在;趋势图收在页签卡里,不再放进 charts-grid 网格 assert '
供应商状态' not in html - assert 'class="charts-grid"' not in html + assert 'class="charts-grid' not in html assert 'class="card timeline-card"' in html # 数据链路:refreshOverview 并发拉取 + 独立兜底 assert "fetchJSON('/api/dashboard/subscriptions').catch" in html @@ -232,7 +232,10 @@ def _extract_block(script: str, start_marker: str, end_marker: str) -> str: { key: 'antigravity', plan: 'Antigravity', status: 'ok', windows: agWindows }, ]; - // 同账号合并为一行:[标识] [订阅区] │ [路由区],行序 = tier 优先级 + const zone = (html) => html.slice(html.indexOf('class="vendor-badges tier-zone"')); + const badges = (html) => Array.from(html.matchAll(/class="status-badge [^"]*">([^<]*)<\/span>/g), m => m[1]); + + // 同账号合并为一行:[标识] [订阅区] [路由区],行序 = tier 优先级 updateVendorStatus({ tiers: screenshotTiers }); updateSubscriptions({ vendors: screenshotVendors }); let rows = tierHTML(); @@ -240,21 +243,22 @@ def _extract_block(script: str, start_marker: str, end_marker: str) -> str: assert.ok(rows.indexOf('data-vendor="zhipu"') < rows.indexOf('data-vendor="anthropic"')); const glmRow = rows.slice(0, rows.indexOf('data-vendor="anthropic"')); assert.ok(glmRow.includes('GLM Coding Plan')); // 行名取订阅名 - assert.ok(glmRow.includes('zhipu')); // 路由区标注 tier 名 + assert.ok(!glmRow.includes('tier-tag')); // 路由区不再标注 tier 名 assert.ok(glmRow.includes('Max')); // 档位:行名后的加粗亮字 - assert.deepStrictEqual(labels(glmRow), ['5h', '1d']); // 订阅区与路由区的窗口短标签同一套 - assert.deepStrictEqual(values(glmRow), ['30%', '0%']); + assert.deepStrictEqual(labels(glmRow), ['5h']); // 用量格只剩订阅区的 + assert.deepStrictEqual(values(glmRow), ['30%']); // 用量格:完整写法进 Tooltip,行内只留紧凑倒计时 assert.ok(/class="quota-group q-ok" title="5 小时:已用 30%,\d+ 分钟后重置">/.test(glmRow)); assert.ok(/class="sub-reset">]*>.*?<\/svg>\d+m<\/span>/.test(glmRow)); - assert.ok(glmRow.includes('title="本代理 1d 滑动窗口配额守卫:已用 0%"')); - assert.ok(glmRow.includes('>正常')); + // 路由区只剩可用状态:无异常是「圆点 + 正常」,tier 名与配额守卫用量收进悬停详情 + assert.ok(zone(glmRow).includes('正常')); + assert.ok(!zone(glmRow).includes('quota-group')); assert.ok(glmRow.indexOf('class="vendor-badges sub-zone"') < glmRow.indexOf('class="vendor-badges tier-zone"')); assert.strictEqual((glmRow.match(/class="drag-handle"/g) || []).length, 1); const claudeRow = rows.slice(rows.indexOf('data-vendor="anthropic"')); assert.ok(claudeRow.includes('Claude Code 订阅')); - assert.ok(claudeRow.includes('anthropic')); + assert.ok(!claudeRow.includes('tier-tag')); assert.ok(claudeRow.includes('>等待首个请求')); // 行内短文案,说明进 Tooltip assert.ok(claudeRow.includes('title="用量来自被动采集')); assert.ok(!rows.includes('无订阅数据')); @@ -274,7 +278,7 @@ def _extract_block(script: str, start_marker: str, end_marker: str) -> str: assert.deepStrictEqual(labels(agHTML), ['5h', '周', '5h', '周']); assert.deepStrictEqual(values(agHTML), ['5%', '0%', '0%', '0%']); - // 无订阅对应的 tier 行:保留路由区并加「供应商状态」标注,不出订阅区 + // 无订阅对应的 tier 行:只有路由区(可用状态),不出订阅区,也不带标注 updateVendorStatus({ tiers: [tier('zhipu'), tier('copilot', { weekly_quota_guard: quota(168, 12) }), tier('anthropic')] }); rows = tierHTML(); @@ -282,10 +286,12 @@ def _extract_block(script: str, start_marker: str, end_marker: str) -> str: assert.ok(rows.indexOf('data-vendor="zhipu"') < rows.indexOf('data-vendor="copilot"')); const copilotRow = rows.slice(rows.indexOf('data-vendor="copilot"'), rows.indexOf('data-vendor="anthropic"')); assert.ok(copilotRow.includes('copilot')); - assert.ok(copilotRow.includes('供应商状态')); - assert.ok(copilotRow.includes('
')); // 路由区类名统一,分隔线才对齐 - assert.deepStrictEqual(labels(copilotRow), ['7d']); - assert.deepStrictEqual(values(copilotRow), ['12%']); + assert.ok(!copilotRow.includes('tier-tag') && !copilotRow.includes('供应商状态')); + assert.ok(copilotRow.includes('
')); // 路由区容器类名固定,滚动位置键靠它区分 + assert.deepStrictEqual(labels(copilotRow), []); // 配额守卫用量不再常驻 + assert.deepStrictEqual(values(copilotRow), []); + assert.ok(copilotRow.includes('配额守卫 7d 窗口已用 12%(阈值 0%)')); // 用量只进悬停详情 + assert.ok(zone(copilotRow).includes('class="avail-ok"')); assert.ok(!copilotRow.includes('sub-zone')); // 头像首字母:供应商行与订阅行头像(C / G / A)撞字母时取前两个字母 @@ -310,21 +316,51 @@ def _extract_block(script: str, start_marker: str, end_marker: str) -> str: rows = tierHTML(); assert.ok(rows.indexOf('data-vendor="anthropic"') < rows.indexOf('data-vendor="zhipu"')); - // 路由区:状态徽章在前(熔断 ×N / 限速中 / 半开),配额守卫用量格在后 + // 路由区可用状态:条件按熔断器、半开、限速、配额守卫排列,多个并存时全部列出;用量格不再出现 updateVendorStatus({ tiers: [ tier('zhipu', { circuit_breaker: { state: 'open', failure_count: 3 }, - rate_limit: { is_rate_limited: true }, weekly_quota_guard: quota(168, 78) }), - tier('anthropic', { circuit_breaker: { state: 'half_open', failure_count: 0 } }), + rate_limit: { is_rate_limited: true, remaining_seconds: 41.2 }, weekly_quota_guard: quota(168, 78) }), + tier('anthropic', { circuit_breaker: { state: 'half_open', failure_count: 2 } }), ] }); rows = tierHTML(); const zhipuRow = rows.slice(0, rows.indexOf('data-vendor="anthropic"')); - const zhipuTier = zhipuRow.slice(zhipuRow.indexOf('class="vendor-badges tier-zone"')); + const zhipuTier = zone(zhipuRow); assert.ok(zhipuRow.includes('熔断 ×3')); assert.ok(zhipuTier.includes('限速中')); - assert.ok(zhipuTier.indexOf('>熔断 ×3') < zhipuTier.indexOf('>限速中')); - assert.ok(zhipuTier.indexOf('>限速中') < zhipuTier.indexOf('class="quota-group')); - assert.ok(zhipuTier.includes('')); - assert.ok(rows.includes('半开')); + assert.deepStrictEqual(badges(zhipuTier), ['熔断 ×3', '限速中']); + assert.ok(!zhipuTier.includes('quota-group')); + assert.ok(zhipuTier.includes('title="zhipu 的路由状态;熔断器 熔断(失败 3 次);限速中,剩余 42 秒;配额守卫 7d 窗口已用 78%(阈值 0%)"')); + assert.ok(zhipuRow.indexOf('class="vendor-badges sub-zone"') < zhipuRow.indexOf('class="vendor-badges tier-zone"')); + const anthropicRow = rows.slice(rows.indexOf('data-vendor="anthropic"')); + assert.deepStrictEqual(badges(anthropicRow), ['半开']); + assert.ok(anthropicRow.includes('熔断器 半开(失败 2 次)')); + + // 配额超限是真实的不可用原因,保留为状态:任一守卫超限即列出,排在熔断与限速之后 + const exceeded = (hours, pct) => ({ state: 'quota_exceeded', usage_percent: pct, window_hours: hours, threshold_percent: 95 }); + updateVendorStatus({ tiers: [ + tier('zhipu', { quota_guard: exceeded(24, 97) }), + tier('copilot', { circuit_breaker: { state: 'open', failure_count: 0 }, rate_limit: { is_rate_limited: true }, + quota_guard: exceeded(24, 40), weekly_quota_guard: exceeded(168, 99) }), + tier('antigravity', { quota_guard: { state: 'within_quota', usage_percent: 96, window_hours: 24, threshold_percent: 95 } }), + ] }); + rows = tierHTML(); + assert.deepStrictEqual(badges(zone(rows.slice(0, rows.indexOf('data-vendor="copilot"')))), ['配额超限']); + const copilotTier = zone(rows.slice(rows.indexOf('data-vendor="copilot"'), rows.indexOf('data-vendor="antigravity"'))); + assert.deepStrictEqual(badges(copilotTier), ['熔断', '限速中', '配额超限']); // 失败 0 次只写「熔断」;双守卫只列一枚 + assert.ok(copilotTier.includes('配额守卫 1d 窗口已用 40%(阈值 95%);配额守卫 7d 窗口已用 99%(阈值 95%)')); + assert.ok(zone(rows.slice(rows.indexOf('data-vendor="antigravity"'))).includes('class="avail-ok"')); // 未超阈值只是用量高 + + // 熔断器状态不分大小写;缺熔断器、限速或守卫字段的 tier 一律是正常 + updateVendorStatus({ tiers: [ + tier('zhipu', { circuit_breaker: { state: 'Open', failure_count: 1 } }), + tier('copilot', { circuit_breaker: null, rate_limit: null, quota_guard: null, weekly_quota_guard: null }), + ] }); + rows = tierHTML(); + assert.deepStrictEqual(badges(zone(rows.slice(0, rows.indexOf('data-vendor="copilot"')))), ['熔断 ×1']); + const bareRow = rows.slice(rows.indexOf('data-vendor="copilot"')); + assert.deepStrictEqual(badges(bareRow), []); + assert.ok(zone(bareRow).includes('class="avail-ok"')); + assert.ok(bareRow.includes('title="copilot 的路由状态;熔断器 正常"')); // 订阅接口失败或为空:行名不跳变、订阅区不渲染,卡片底部提示 updateVendorStatus({ tiers: screenshotTiers }); @@ -476,9 +512,8 @@ def _extract_block(script: str, start_marker: str, end_marker: str) -> str: "function quotaClass(", "function quotaWindowLabel(", "function renderQuotaCell(", - "function renderQuotaBar(", - "function cbStateClass(", - "function cbStateLabel(", + "function tierAvailability(", + "function tierAvailabilityTitle(", "function _tierZoneHTML(", "function _tierInitial(", "function fmtResetCountdown(", diff --git a/tests/test_generations.py b/tests/test_generations.py index 984cf4b4..042ec88d 100644 --- a/tests/test_generations.py +++ b/tests/test_generations.py @@ -562,7 +562,7 @@ def test_migrate_bindings_counts_double_invalidation_once(): resolver = SessionPolicyResolver() router = MagicMock() router.get_vendor_names.return_value = ["zhipu"] - router.get_bindable_models.return_value = [ + router.get_known_models.return_value = [ {"label": "Keep", "model": "keep-me", "tiers": []} ] router._executor._policy_resolver = resolver diff --git a/tests/test_model_catalog.py b/tests/test_model_catalog.py index a8344086..9ead0b38 100644 --- a/tests/test_model_catalog.py +++ b/tests/test_model_catalog.py @@ -9,7 +9,7 @@ import pytest -from coding.proxy.config.routing import ModelMappingRule +from coding.proxy.config.routing import ModelMappingRule, ModelPricingEntry from coding.proxy.config.session_policy import BindableModel from coding.proxy.config.vendors import AnthropicConfig, ZhipuConfig from coding.proxy.routing.model_mapper import ModelMapper @@ -99,6 +99,118 @@ def test_builtin_entries_pin_owner_vendor(self): for entry in builtin_entries_for("zhipu") + builtin_entries_for("anthropic"): assert entry.tiers == (entry.vendor,) + def test_zhipu_glm_5_4_in_builtin_catalog(self): + """回归:pricing 与调用记录不是目录来源,GLM 5.4 须随内置目录进下拉.""" + cat = compose_bindable_catalog(["zhipu"], [_cfg("A", "glm-5.3")]) + glm = next(e for e in cat if e["model"] == "glm-5.4") + assert (glm["label"], glm["vendor"], glm["tiers"]) == ( + "GLM 5.4", + "zhipu", + ["zhipu"], + ) + + +def _price(vendor: str, model: str, online: bool = True) -> ModelPricingEntry: + return ModelPricingEntry(vendor=vendor, model=model, online=online) + + +class TestPricingDerivedCatalog: + """pricing 行并入目录:native vendor 配价即入下拉,online=false 只下线不删除.""" + + def test_native_vendor_priced_model_derives_entry(self): + cat = compose_bindable_catalog( + ["zhipu"], [_cfg("A", "glm-5.3")], [_price("zhipu", "glm-5.5")] + ) + derived = next(e for e in cat if e["model"] == "glm-5.5") + assert (derived["label"], derived["vendor"], derived["tiers"]) == ( + "glm-5.5", + "zhipu", + ["zhipu"], + ) + assert "offline" not in derived + + def test_non_native_vendor_pricing_not_derived(self): + cat = compose_bindable_catalog( + ["zhipu", "anthropic"], + [_cfg("A", "glm-5.3")], + [ + _price("anthropic", "claude-x-9"), + _price("gemini", "gemini-x-9"), + _price("copilot", "copilot-x"), + ], + ) + models = {e["model"] for e in cat} + assert "claude-x-9" not in models + assert "gemini-x-9" not in models + assert "copilot-x" not in models + + def test_inactive_vendor_pricing_not_derived(self): + cat = compose_bindable_catalog( + ["zhipu"], [_cfg("A", "glm-5.3")], [_price("kimi", "kimi-k3")] + ) + assert all(e["model"] != "kimi-k3" for e in cat) + + def test_priced_builtin_model_deduped_builtin_label_wins(self): + cat = compose_bindable_catalog( + ["zhipu"], [_cfg("A", "claude-opus-4.6")], [_price("zhipu", "glm-5.3")] + ) + assert [e["model"] for e in cat].count("glm-5.3") == 1 + builtin = next(e for e in cat if e["model"] == "glm-5.3") + assert builtin["label"] == "GLM 5.3" + + def test_config_entry_overrides_pricing_derived(self): + cat = compose_bindable_catalog( + ["zhipu"], + [_cfg("我的 GLM", "glm-5.5", ["zhipu"])], + [_price("zhipu", "glm-5.5")], + ) + derived = next(e for e in cat if e["model"] == "glm-5.5") + assert derived["label"] == "我的 GLM" + assert derived["tiers"] == ["zhipu"] + + def test_offline_row_marks_derived_entry(self): + cat = compose_bindable_catalog( + ["zhipu"], + [_cfg("A", "glm-5.3")], + [_price("zhipu", "glm-5.5", online=False)], + ) + derived = next(e for e in cat if e["model"] == "glm-5.5") + assert derived["offline"] is True + + def test_offline_row_marks_builtin_entry(self): + cat = compose_bindable_catalog( + ["zhipu"], + [_cfg("A", "glm-5.3")], + [_price("zhipu", "glm-5.3", online=False)], + ) + builtin = next(e for e in cat if e["model"] == "glm-5.3") + assert builtin["offline"] is True + + def test_any_row_offline_marks_model(self): + """下线以 model 为粒度:同名任一 pricing 行 online=false 即下线.""" + cat = compose_bindable_catalog( + ["zhipu"], + [_cfg("A", "glm-5.3")], + [_price("zhipu", "glm-5.5"), _price("minimax", "glm-5.5", online=False)], + ) + assert next(e for e in cat if e["model"] == "glm-5.5")["offline"] is True + + def test_empty_config_disables_binding_even_with_pricing(self): + """bindable_models 空清单仍是整体 off 开关(含 pricing 派生条目).""" + assert ( + compose_bindable_catalog(["zhipu"], [], [_price("zhipu", "glm-5.5")]) == [] + ) + + def test_offline_derived_model_keeps_identity_rule(self): + """下线模型保留 identity 规则:已绑会话继续 exact 命中原名,不被回退改写.""" + cat = compose_bindable_catalog( + ["zhipu"], + [_cfg("A", "glm-5.3")], + [_price("zhipu", "glm-5.5", online=False)], + ) + rules = builtin_identity_rules(cat) + assert any(r.pattern == "glm-5.5" and r.vendors == ["zhipu"] for r in rules) + # ── builtin_identity_rules ────────────────────────────────── @@ -111,6 +223,12 @@ def test_native_vendor_models_get_identity_rules(self): assert "glm-5.3" in zhipu_rules assert all(r.pattern == r.target and not r.is_regex for r in rules) + def test_glm_5_4_gets_identity_rule(self): + """内置目录里的 GLM 5.4 发往 zhipu 时 exact 命中原名,不被 default 回退改写.""" + cat = compose_bindable_catalog(["zhipu"], [_cfg("A", "glm-5.3")]) + rules = builtin_identity_rules(cat) + assert any(r.pattern == "glm-5.4" and r.vendors == ["zhipu"] for r in rules) + def test_anthropic_entries_get_no_rules(self): """anthropic 恒等透传,不进 ModelMapper 规则空间.""" cat = compose_bindable_catalog(["anthropic"], [_cfg("A", "claude-opus-4-6")]) @@ -270,7 +388,7 @@ def test_pinned_model_strict_chain_without_tail_append(): zhipu_tier = _make_tier(_mock_vendor(name="zhipu")) anthropic_tier = _make_tier(_mock_vendor(name="anthropic")) router = MagicMock() - router.get_bindable_models.return_value = [ + router.get_known_models.return_value = [ {"label": "GLM 5.3", "model": "glm-5.3", "tiers": ["zhipu"], "vendor": "zhipu"} ] exec_inst = _executor([zhipu_tier, anthropic_tier], router=router) @@ -302,7 +420,7 @@ def test_unpinned_model_keeps_reorder_with_tail(): zhipu_tier = _make_tier(_mock_vendor(name="zhipu")) anthropic_tier = _make_tier(_mock_vendor(name="anthropic")) router = MagicMock() - router.get_bindable_models.return_value = [ + router.get_known_models.return_value = [ {"label": "C", "model": "claude-opus-4.6", "tiers": [], "vendor": "custom"} ] exec_inst = _executor([zhipu_tier, anthropic_tier], router=router) @@ -330,7 +448,7 @@ def test_pinned_model_honors_explicit_vendor_order(): anthropic_tier = _make_tier(_mock_vendor(name="anthropic")) copilot_tier = _make_tier(_mock_vendor(name="copilot")) router = MagicMock() - router.get_bindable_models.return_value = [ + router.get_known_models.return_value = [ {"label": "GLM 5.3", "model": "glm-5.3", "tiers": ["zhipu"], "vendor": "zhipu"} ] exec_inst = _executor([zhipu_tier, anthropic_tier, copilot_tier], router=router)