From fff84aef444e8fdfb859ee2cbccf23546c7af8c6 Mon Sep 17 00:00:00 2001 From: api-gateway Date: Sun, 20 Sep 2026 19:23:18 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AC=AC=E4=B8=89=E5=8D=81=E4=B8=80=E8=BD=AE?= =?UTF-8?q?=E6=94=B6=E5=B0=BE:=20=E7=BB=93=E6=9E=84=E5=8C=96=E4=BF=9D?= =?UTF-8?q?=E5=AD=98=E8=B5=B0=E6=96=87=E6=9C=AC=E7=BA=A7=E5=90=88=E5=B9=B6?= =?UTF-8?q?(=E4=BF=9D=E4=BD=8F=E6=89=8B=E5=86=99=E6=B3=A8=E9=87=8A)=20+=20?= =?UTF-8?q?=E5=88=AB=E5=90=8D=E5=8D=A1=E7=89=87=E6=96=87=E6=A1=88=E6=8C=89?= =?UTF-8?q?=E8=80=81=E6=9D=BF=E5=8F=A3=E5=BE=84=E5=88=A0=E5=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 一、结构化 PUT /config 不再整份重渲染(这次真踩过的事故) - 起因:模型页「保存映射」只改 aliases 一段,却走 render_yaml 整份重渲染,把 gateway.yaml 里 历轮手写的现场注释(协议线实测结论、各家鉴权差异、会话头要求…)整段抹掉(90 → 48 行)。 - app/settings.py 新增 merge_submitted_sections():把本次提交的段替换进原文,其余字节一个都不动。 三条边界都是实测踩出来的: ① 只重写**值真的变了**的段(write_config_merged 拿 raw_old 逐段比对)—— 面板 PUT 的是整份视图, 没变的段必须原样留着,否则一次无关保存就把 server.retry 那类行尾注释冲掉; ② 被替换段的**段尾说明/页脚**用 _split_tail 留在原位 —— 改 providers 不能顺手动掉 server 上方的说明书; ③ 新增段用 _doc_start 插在下一段**说明书之前** —— 否则别人的说明书会变成新段的抬头; ④ 合并后回读校验:解析失败或与提交内容不等 → 退回整份重渲染(配置一定正确,只赔注释)并记 ERROR。 - app/main.py:结构化保存改调 write_config_merged;日志升级为 写盘=merged|rendered / 重写段=<清单>。 - 结构化的唯一调用方是模型页(只提交 aliases 一段);网关配置页走 YAML 原文,两路都不丢注释。 二、别名卡片文案(老板 2026-09-18 口径) - 删掉卡头副标题(aliasSub:客户端固定写 model: {id},网关转发到你选的模型)与 member 的只读行 (aliasReadonly:只读:映射由管理员在网关配置里选择),两行说明保留;Models.vue 连带删掉 .alias-ro 样式, 中英 i18n 753 → 751(仍对称)。 三、验证 - 单测 189 passed / 0 failed:新增 test_merged_write_keeps_neighbour_docs_and_skips_unchanged(上面三条边界); 改写 test_alias_panel_round_trip_and_save_validation —— 旧写法 PUT 整份视图,而 view_to_raw 会把面板默认值 materialize 进 providers(token ''/rate_limit_rps null/requires_session_header false/endpoints/vision false…), providers 因此被判"变了"、注释被重写,断言必挂;改成面板真实载荷 {config:{aliases:…}} 后绿。 - scripts/ci_check.sh 全绿(compileall + 单测 + i18n/SVG 体检 + vue-tsc + build)。 - 生产实测(重启后 pid 1912449):值没变的保存 → gateway.yaml 逐字节一致;临时改 note → 差异只有 2 行; 改回 → md5 回到 64ca52b83ab1bb3a7db40d0073554887;页面点「保存映射」→ 日志 重写段=无、文件未变。 前端新入口 index-B5GZJuR8.js(旧 index-BJNJXWEY.js 404),admin/member 双角色真浏览器复验通过。 四、data/gateway.yaml - 提交的是**注释完整的生产版**:HEAD 里那版是被抹过的 render 产物,工作区这版恢复了被误删的手写注释 并补了带说明的 aliases 段(注释行 100,⊇ 上一版)。 遗留(未动,等老板定):整份视图 PUT 仍会在 providers 上 materialize 面板默认值(那段行内注释会赔); 当前无 UI 走这条路,根治需让 view_to_raw 不再补默认值。 --- app/main.py | 14 +- app/settings.py | 175 +++++++++ data/gateway.yaml | 677 +++++++++++++++------------------- frontend/src/locales/en.ts | 4 +- frontend/src/locales/zh.ts | 4 +- frontend/src/views/Models.vue | 13 +- tests/test_gateway.py | 143 ++++++- 7 files changed, 628 insertions(+), 402 deletions(-) diff --git a/app/main.py b/app/main.py index d54d752..f24b2fc 100644 --- a/app/main.py +++ b/app/main.py @@ -3569,12 +3569,20 @@ async def config_put(request: Request, _auth=Depends(require_auth)): except ConfigError as e: raise HTTPException(400, str(e)) text = gw_settings.render_yaml(raw_new) - info = await _offload(gw_settings.write_config, CONFIG_PATH, text) + # 第三十一轮: 结构化保存走文本级合并 —— 只把**值真的变了**的段替换进原文,其余字节 + # (含手写注释、行尾注释、键序)原样保留。起因:模型页「保存映射」只改 aliases 一段, + # 却走 render_yaml 整份重渲染,把 gateway.yaml 里历轮手写的现场注释(协议线实测结论、 + # 各家鉴权差异…)整段抹掉。面板 PUT 的是整份视图,所以"没变"的段由 write_config_merged + # 自己比对 raw_old 后跳过;合并回读校验不过时自动退回整份重渲染(配置一定正确,只赔注释)。 + submitted = {k for k in view if isinstance(k, str)} + info = await _offload(gw_settings.write_config_merged, CONFIG_PATH, raw_new, raw_old, submitted) + text = info.get("text") or text restart = gw_settings.restart_keys_changed(old_cfg, new_cfg) await _apply_config(new_cfg, source=f"页面保存({request.state.account})") _state["mtime"] = _config_mtime() - log.warning("配置已由 %s 通过管理页面保存并生效(%d 供应商 / %d 字节)", - request.state.account, len(new_cfg.providers), info.get("bytes", 0)) + log.warning("配置已由 %s 通过管理页面保存并生效(%d 供应商 / %d 字节 / 写盘=%s / 重写段=%s)", + request.state.account, len(new_cfg.providers), info.get("bytes", 0), + info.get("mode", "?"), ",".join(info.get("sections", [])) or "无") return { "status": "ok", "applied": True, diff --git a/app/settings.py b/app/settings.py index 7a580ce..083b60b 100644 --- a/app/settings.py +++ b/app/settings.py @@ -20,7 +20,9 @@ adapter 缓存,与 mtime 热重载走**同一条** `_apply_config` 路径( from __future__ import annotations import copy +import logging import os +import re import shutil import time from pathlib import Path @@ -38,6 +40,8 @@ from app.config import ( validate_warnings, ) +log = logging.getLogger("api-gateway.settings") + # ── 改了必须重启进程才生效的键(其余都是"每请求读配置",保存即生效) ── # host / port:uvicorn 在进程启动时绑定,改文件不会重绑。 # graceful_shutdown:run.py 启动时读一次,传给 uvicorn 的 timeout_graceful_shutdown。 @@ -520,6 +524,177 @@ def render_yaml(raw: dict[str, Any]) -> str: # ── 写盘(备份 + 原子替换)──────────────────────────────── +def _top_key_of(line: str) -> str | None: + """这一行是不是一个**顶层段**的键行(`aliases:` 这种,列 0 起、非注释)?是则返回键名。""" + if not line or line[:1].isspace() or line.lstrip().startswith("#"): + return None + m = re.match(r"^([A-Za-z_][A-Za-z0-9_.-]*):", line) + return m.group(1) if m else None + + +def _split_top_sections(text: str) -> list[tuple[str | None, int, int]]: + """把 yaml 原文切成 [(顶层键或 None, 起始偏移, 结束偏移)]。 + + None 那一段是文件开头的抬头注释(不属于任何段)。段**从键行开始**,不含键行上方的 + 说明注释 —— 那些注释属于上一段的尾巴,替换时保持原位不动(注释是文件主人的,别动它)。 + """ + lines = text.splitlines(keepends=True) + secs: list[tuple[str | None, int, int]] = [] + cur_key: str | None = None + cur_start = 0 + pos = 0 + for ln in lines: + key = _top_key_of(ln) + if key is not None: + secs.append((cur_key, cur_start, pos)) + cur_key, cur_start = key, pos + pos += len(ln) + secs.append((cur_key, cur_start, pos)) + return secs + + +def _split_tail(seg: str) -> tuple[str, str]: + """把段文本切成 (正文, 尾巴):尾巴 = 段尾连续的空行 / 整行注释(列 0)。 + + 那些行是**下一段的说明书**(如 `server:` 上方的「服务与运维开关」)或文件页脚 + (如 `auth:` 后面的「路由别名已删除」)。它们落在本段的偏移区间里(段从键行起算、 + 到下一个键行前结束),替换本段时必须原样留在原位 —— 否则改 providers 就会顺手 + 把 aliases 的说明删掉。 + """ + lines = seg.splitlines(keepends=True) + i = len(lines) + while i > 0 and (lines[i - 1].strip() == "" or lines[i - 1][:1] == "#"): + i -= 1 + return "".join(lines[:i]), "".join(lines[i:]) + + +def _doc_start(text: str, pos: int) -> int: + """`pos` 是某段键行的偏移 → 返回紧贴它的「空行/整行注释」块的起点。 + + 新增段要插到这一段**说明注释之前**,否则会插进别人的说明书和键行之间,把说明 + 变成新段的抬头(第一轮实测真踩过:新插 `aliases` 会顶掉 `server` 的说明)。 + """ + lines = text[:pos].splitlines(keepends=True) + i = len(lines) + while i > 0 and (lines[i - 1].strip() == "" or lines[i - 1][:1] == "#"): + i -= 1 + return pos - sum(len(x) for x in lines[i:]) + + +def merge_submitted_sections(text: str, raw_new: dict[str, Any], + submitted: set[str]) -> str | None: + """把本次提交的段替换进原文 `text`,**其余字节一个都不动**(含手写注释/格式/键序)。 + + 为什么需要它(第三十一轮): 原来结构化保存走 `render_yaml(raw_new)` —— 整份重渲染。 + 结果"在模型页改一个别名"会把 `gateway.yaml` 里手写的现场注释(协议线实测结论、各家 + 鉴权差异、会话头要求…)整段抹掉。注释是历轮踩坑的产物,不能因为改一个小段就赔进去。 + + 规则: + · 段已存在 → 只替换**这个段**的文本,段尾的说明注释/页脚原样保留(见 _split_tail); + · 段是新增的(如第一次配 `aliases`)→ 按 `_SECTION_ORDER` 插到它该在的位置, + 且插点在下一段**说明注释之前**(见 _doc_start); + · 段里提交的键必须都在 `raw_new` 里,缺键直接跳过(调用方已按提交内容算过 raw_new); + · 有任何一段定位不到(文件格式怪)→ 返回 None,调用方退回整份重渲染(不静默出错)。 + + 返回新文本;定位失败返回 None。**不写盘**(写盘交给 write_config,备份+原子替换照旧)。 + """ + secs = _split_top_sections(text) + if not secs or secs[0][0] is not None or not any(k is not None for k, _s, _e in secs): + # 开头那段不是抬头、或整篇一个顶层段都没有 → 这不是我们认识的 gateway.yaml, + # 别硬改(返回 None 让调用方整份重渲染,至少配置是对的) + return None + known = set(_SECTION_ORDER) + + def block(key: str) -> str: + # 段文本本身不带抬头注释:文件里原有的抬头注释留在原位(新增段才补注释) + return _dump({key: raw_new[key]}) + + # 从后往前替换,偏移量才不会因前面的替换而失效 + edits: list[tuple[int, int, str]] = [] + inserts: list[tuple[int, str]] = [] + for key in sorted(submitted): + if key not in raw_new: + continue # 提交了一个 raw_new 里没有的段(正常不会)→ 不猜,跳过 + span = next(((s, e) for k, s, e in secs if k == key), None) + if span is not None: + _body, tail = _split_tail(text[span[0]:span[1]]) + edits.append((span[0], span[1], block(key) + tail)) + continue + # 新增段:插到"顺序上排在它后面"的第一个已存在段之前;没有就追加到文件末尾 + try: + order = _SECTION_ORDER.index(key) + except ValueError: + order = len(_SECTION_ORDER) # 面板不认识的自定义段 → 追加到末尾,也算定位成功 + nxt = None + for k, s, _e in secs: + if k is None or k not in known: + continue + if _SECTION_ORDER.index(k) > order: + nxt = s + break + head = _SECTION_COMMENTS.get(key, "") if key in known else "" + if nxt is None: + inserts.append((len(text), head + block(key))) + else: + # 前面补一个空行(与上一段隔开);插点在下一段的说明注释之前 + inserts.append((_doc_start(text, nxt), "\n" + head + block(key))) + + # 一次性按**偏移从大到小**应用所有改动:先动后面的,前面替换/插入才不会让偏移失效 + ops: list[tuple[int, int, str]] = [] # (起始, 结束, 新文本);插入时 起始 == 结束 + ops.extend(edits) + ops.extend((at, at, new) for at, new in inserts) + out = text + for start, end, new in sorted(ops, key=lambda x: -x[0]): + if start == end and start >= len(out): + # 追加到文件末尾:补一个换行,免得与上一段挤在一行 + out = out + ("" if out.endswith("\n") or not out else "\n") + new + continue + out = out[:start] + new + out[end:] + if not out.endswith("\n"): + out += "\n" + return out + + +def write_config_merged(path: str | Path, raw_new: dict[str, Any], raw_old: dict[str, Any], + submitted: set[str]) -> dict[str, Any]: + """结构化保存的写盘(第三十一轮):**只替换真正变了的段**,其余文本原样保留。 + + 不变量:合并后的文本 `yaml.safe_load` 回去必须**等于** `raw_new`。合并是文本级操作, + 理论上可能因为缩进/引号风格把值改掉 —— 所以这里回读校验;一旦对不上就退回整份重渲染 + (老行为,会丢手写注释,但配置一定正确),并记一条 ERROR 说明哪一段没合并成功。 + + 只有"值真的变了"的段才重写:面板提交的是**整份视图**(GET /config 原样 PUT),但里面 + 绝大多数段和盘上一模一样 —— 那些段一个字节都不动,段内的行尾注释(如 server.retry + 后面那句说明)才不会因为一次无关保存而蒸发。 + + 返回 write_config 的信息字典,外加 `mode`(merged / rendered)、`sections`(被重写的段) + 与 `text`(实际写盘文本)。 + """ + path = Path(path) + try: + text_old = path.read_text(encoding="utf-8") + except OSError: + text_old = "" + changed = {k for k in submitted if k in raw_new and raw_new.get(k) != raw_old.get(k)} + merged = merge_submitted_sections(text_old, raw_new, changed) if text_old.strip() else None + mode = "merged" + if merged is None: + merged, mode = render_yaml(raw_new), "rendered" + else: + try: + back = yaml.safe_load(merged) + except yaml.YAMLError as e: + log.error("文本级合并后的配置解析失败(%s)→ 回退整份重渲染: %s", changed, e) + merged, mode = render_yaml(raw_new), "rendered" + else: + if back != raw_new: + log.error("文本级合并结果与提交内容不一致(%s)→ 回退整份重渲染", changed) + merged, mode = render_yaml(raw_new), "rendered" + info = write_config(path, merged) + info.update({"mode": mode, "sections": sorted(changed), "text": merged}) + return info + + def _prune_backups(path: Path) -> None: """只留最近 BACKUP_KEEP 份时间戳备份(滚动 .bak 不动)。""" pat = f"{path.name}.*.bak" diff --git a/data/gateway.yaml b/data/gateway.yaml index 2a6f6b0..06032e5 100644 --- a/data/gateway.yaml +++ b/data/gateway.yaml @@ -1,414 +1,335 @@ # AI 网关配置文件(data/ 目录) +# 供应商:Agnes / 火山方舟 Coding / OpenCode Go(订阅编程模型) +# 密钥统一走 token_env 指向的环境变量(本机见 data/.env),不再在 yaml 存明文 +# 端口默认 8808 # -# ⚠ 本文件由管理页面「网关配置」生成(管理员账号),页面保存时会**整份重写**: -# 想要的历史决策/踩坑说明在 README.md(按轮次记录),这里只保留必要的现场注释。 -# 手改本文件仍然有效(server.hot_reload=true 时按 mtime 自动重载), -# 但页面下次保存会以页面上的值为准 —— 改配置优先用页面。 -# -# 端口默认 8808;密钥统一走 auth.token_env 指向的环境变量(本机见 .env),不在 yaml 存明文。 -# 本文件是项目的唯一配置文件(run.py 默认读取;GATEWAY_CONFIG 可覆盖)。 -# ── 供应商 + 模型清单 ─────────────────────────────────── -# auth.token_env 指向存放密钥的环境变量;auth.token 只有在不用环境变量时才填(明文)。 -# media 段留空 = 该供应商不支持图像/视频(Agnes 是自有非标准端点,故单独覆盖)。 -# models.type: text | image | video;vision: 该模型是否支持图像输入(带图对话会被优先排到链首)。 +# 说明:本文件是项目的**唯一配置文件**(run.py 默认读取;GATEWAY_CONFIG 可覆盖)。 + providers: agnes: - name: Agnes AI - base_url: https://api.agnes-ai.cn/v1 + name: "Agnes AI" + base_url: "https://api.agnes-ai.cn/v1" auth: - token_env: AGNES_API_KEY - token: '' + token_env: "AGNES_API_KEY" extra_headers: {} - rate_limit_rps: null - requires_session_header: false - endpoints: - chat/completions: - path: /chat/completions - auth: bearer - headers: {} - messages: - path: /messages - auth: x-api-key - headers: - anthropic-version: '2023-06-01' - responses: - path: /responses - auth: bearer - headers: {} + # 图像 / 视频端点(Agnes 非标准,走自有路径) media: - image_endpoint: /images/generations - image_default_size: 1K - video_create_endpoint: /videos - video_poll_base: https://api.agnes-ai.cn - video_poll_path: /agnesapi - video_model_name: agnes-video-2.5-flash + image_endpoint: "/images/generations" + image_default_size: "1K" # 图像默认档位(Agnes: 1K/2K/3K/4K) + video_create_endpoint: "/videos" + video_poll_base: "https://api.agnes-ai.cn" + video_poll_path: "/agnesapi" + video_model_name: "agnes-video-2.5-flash" models: - - id: agnes-3.0-flash - display_name: Agnes 3.0 Flash - type: text - vision: true - protocols: - - chat/completions - - id: agnes-2.5-flash - display_name: Agnes 2.5 Flash - type: text - vision: true - protocols: - - chat/completions - - id: agnes-image-2.5-flash - display_name: Agnes Image 2.5 Flash - type: image - vision: false - protocols: - - chat/completions - - id: agnes-video-2.5-flash - display_name: Agnes Video 2.5 Flash - type: video - vision: false - protocols: - - chat/completions + - id: "agnes-3.0-flash" + display_name: "Agnes 3.0 Flash" + type: "text" + # 第十三轮: Agnes 3.0 Flash 文档「输入模态:文本、图像 URL」→ 支持视觉(对话带图)。 + # 实测 data:image/png;base64,... 也能识别。 + vision: true + - id: "agnes-2.5-flash" + display_name: "Agnes 2.5 Flash" + type: "text" + # Agnes 2.5 Flash(2.0 升级版):OpenAI 兼容 /v1/chat/completions,支持图像 URL 输入与工具调用, + # 上下文 512K / 最大输出 65.5K;当前定价暂免(¥0/百万)。参见官方文档 agnes-25-flash。 + vision: true + - id: "agnes-image-2.5-flash" + display_name: "Agnes Image 2.5 Flash" + type: "image" + - id: "agnes-video-2.5-flash" + display_name: "Agnes Video 2.5 Flash" + type: "video" + volc_engine: - name: 火山方舟 Coding Plan - base_url: https://ark.cn-beijing.volces.com/api/coding/v3 + name: "火山方舟 Coding Plan" + base_url: "https://ark.cn-beijing.volces.com/api/coding/v3" auth: - token_env: VOLC_API_KEY - token: '' + token_env: "VOLC_API_KEY" extra_headers: {} - rate_limit_rps: null - requires_session_header: false - endpoints: - chat/completions: - path: /chat/completions - auth: bearer - headers: {} - messages: - path: /messages - auth: x-api-key - headers: - anthropic-version: '2023-06-01' - responses: - path: /responses - auth: bearer - headers: {} - media: - image_endpoint: null - image_default_size: null - video_create_endpoint: null - video_poll_base: null - video_poll_path: null - video_model_name: null + media: {} models: - - id: ark-code-latest - display_name: 火山方舟 ark-code-latest - type: text - vision: false - protocols: - - chat/completions + - id: "ark-code-latest" + display_name: "火山方舟 ark-code-latest" + type: "text" + opencode: - name: OpenCode Go - base_url: https://opencode.ai/zen/go/v1 + name: "OpenCode Go" + base_url: "https://opencode.ai/zen/go/v1" auth: - token_env: OPENCODE_API_KEY - token: '' - extra_headers: - User-Agent: api-gateway/2.4.0 (jakon opencode-go) - rate_limit_rps: null + token_env: "OPENCODE_API_KEY" + # OpenCode Go 是每月订阅编程模型入口。官方硬性要求**三条线**都带 + # x-opencode-session(缺失直接 400 MissingSessionID),并建议用专属 UA + # 而非通用库名(实测 UA 不敏感,会话头才是必需)。适配器据此开关在 + # 每次请求动态注入会话头(不能放静态 extra_headers——会被 _get_adapter 缓存冻结)。 requires_session_header: true + extra_headers: + User-Agent: "api-gateway/2.4.0 (jakon opencode-go)" + # 无媒体能力(纯文本编程模型;图像/视频不走本供应商) + media: {} + # ── 协议线(第二十七轮「三线直传」)────────────────────────── + # 同一家供应商的三条线共用 base_url,只有「路径 + 鉴权方式 + 固定头」不同。 + # 实测(2026-09-18,真实 key): + # /chat/completions 与 /responses → Authorization: Bearer + # /messages → x-api-key(用 Bearer 打会 401 Missing API key) + # 缺少 anthropic-version 时 /messages 也会被拒 → 作为该线固定头带上。 + # 语义:**这里没写的线 = 该供应商没有这条线**(模型就算声明了也调用不了, + # validate_config 会直接报错拦住)。老板决策:先只做 OpenCode 一家, + # 其余供应商(Agnes / 火山)暂不声明 → 走默认值 = 只认 chat/completions, + # 行为与改造前完全一致。 endpoints: chat/completions: - path: /chat/completions - auth: bearer + path: "/chat/completions" + auth: "bearer" messages: - path: /messages - auth: x-api-key + path: "/messages" + auth: "x-api-key" headers: - anthropic-version: '2023-06-01' + anthropic-version: "2023-06-01" responses: - path: /responses - auth: bearer - media: - image_endpoint: null - image_default_size: null - video_create_endpoint: null - video_poll_base: null - video_poll_path: null - video_model_name: null + path: "/responses" + auth: "bearer" + # ── 模型 ───────────────────────────────────────────────── + # models[].protocols = 该模型**能用哪几条线**(入站格式必须与出站一致)。 + # 取值:chat/completions | messages | responses;不写 = 只认 chat/completions。 + # 实测口径(2026-09-18 全量扫描 29 个文档模型 × 3 条线,非文档线另做 + # 「流式 + 工具调用」复核,全部 200):官方文档标注的线**一定**可用; + # 另外有一批模型实测能走多条线(OpenCode 侧自带跨格式适配),按实测多标: + # · 四条 DeepSeek 三线全通(chat + messages + responses) + # · kimi-k3 / minimax-m3 / minimax-m2.5 / qwen3.6~3.8 系列:chat + messages + # 反向证据(为什么必须逐条实测而不是"猜全支持"):把只认 chat 的 glm 系打到 + # /messages 上是 500 Internal server error,把 messages 线的模型打到 + # /responses 上是 401 "not supported for format openai" —— 都不像"选错格式", + # 所以网关改成按本表拦在入口(400 并说清该模型支持哪些线)。 models: - - id: glm-5.3-flash - display_name: GLM-5.3-Flash - type: text - protocols: - - chat/completions - vision: false - - id: glm-5.3 - display_name: GLM-5.3 - type: text - protocols: - - chat/completions - vision: false - - id: glm-5.2 - display_name: GLM-5.2 - type: text - protocols: - - chat/completions - vision: false - - id: glm-5.1 - display_name: GLM-5.1 - type: text - protocols: - - chat/completions - vision: false - - id: kimi-k2.7-code - display_name: Kimi K2.7 Code - type: text - protocols: - - chat/completions - params: - temperature: 1 - vision: false - - id: kimi-k2.6 - display_name: Kimi K2.6 - type: text - protocols: - - chat/completions - vision: false - - id: longcat-2.0 - display_name: LongCat 2.0 - type: text - protocols: - - chat/completions - vision: false - - id: mimo-v2.5 - display_name: MiMo V2.5 - type: text - protocols: - - chat/completions - vision: false - - id: mimo-v2.5-pro - display_name: MiMo V2.5 Pro - type: text - protocols: - - chat/completions - vision: false - - id: hy4-preview - display_name: Hy4 Preview - type: text - protocols: - - chat/completions - vision: false - - id: hy3 - display_name: Hy3 - type: text - protocols: - - chat/completions - vision: false - - id: kimi-k3 - display_name: Kimi K3 - type: text - protocols: - - chat/completions - - messages - vision: false - - id: minimax-m3 - display_name: MiniMax M3 - type: text - protocols: - - chat/completions - - messages - vision: false - - id: minimax-m2.5 - display_name: MiniMax M2.5 - type: text - protocols: - - chat/completions - - messages - vision: false - - id: qwen3.8-max - display_name: Qwen3.8 Max - type: text - protocols: - - chat/completions - - messages - vision: false - - id: qwen3.8-flash - display_name: Qwen3.8 Flash - type: text - protocols: - - chat/completions - - messages - vision: false - - id: qwen3.7-max - display_name: Qwen3.7 Max - type: text - protocols: - - chat/completions - - messages - vision: false - - id: qwen3.7-plus - display_name: Qwen3.7 Plus - type: text - protocols: - - chat/completions - - messages - vision: false - - id: qwen3.6-plus - display_name: Qwen3.6 Plus - type: text - protocols: - - chat/completions - - messages - vision: false - - id: deepseek-v4.1-flash - display_name: DeepSeek V4.1 Flash - type: text - vision: true - protocols: - - chat/completions - - messages - - responses - - id: deepseek-v4-pro - display_name: DeepSeek V4 Pro - type: text - protocols: - - chat/completions - - messages - - responses - vision: false - - id: deepseek-v4-flash - display_name: DeepSeek V4 Flash - type: text - protocols: - - chat/completions - - messages - - responses - vision: false - - id: deepseek-v4-flash-vision-exp - display_name: DeepSeek V4 Flash Vision Exp - type: text - vision: true - protocols: - - chat/completions - - messages - - responses - - id: minimax-m2.7 - display_name: MiniMax M2.7 - type: text - protocols: - - messages - vision: false - - id: union-alpha - display_name: Union Alpha Free - type: text - protocols: - - messages - vision: false - - id: grok-4.6 - display_name: Grok 4.6 - type: text - protocols: - - responses - vision: false - - id: gpt-5.6-luna - display_name: GPT 5.6 Luna - type: text - protocols: - - responses - vision: false - - id: muse-spark-1.3-contributor - display_name: Muse Spark 1.3 Contributor - type: text - protocols: - - responses - vision: false - - id: muse-spark-1.2-contributor - display_name: Muse Spark 1.2 Contributor - type: text - protocols: - - responses - vision: false -# ── 虚拟模型 id(别名,第三十一轮)────────────────────── -# 给客户端一个"名字固定"的入口:客户端永远只写 model: wjd,实际转发到哪个真实模型 -# 由这里决定(页面上改:供应商与模型页 → 虚拟模型 wjd → 单选 + 保存)。 -# 规则(保存时校验,手改 yaml 一样拦): -# · 只走 chat/completions(OpenAI)格式;用 /v1/messages、/v1/responses 打 wjd 会在入口 400; -# · target 必须是**存在的文本模型**且支持 chat/completions(面板里其余模型置灰); -# · 别名 id 不能和真实模型 id 重名; -# · 别名不复制目标的配置(协议线/视觉/强制参数/定价全部继承 target,一处修改全局生效); -# · enabled: false = 该 id 不存在(等同没配),停用时不校验 target。 -# 别名不进 /v1/models/speedtest(测速请测它指向的模型),但会出现在 /v1/models 里(带 alias_of)。 + # ── OpenAI Chat Completions 线 ──────────────────────── + - id: "glm-5.3-flash" + display_name: "GLM-5.3-Flash" + type: "text" + protocols: ["chat/completions"] + - id: "glm-5.3" + display_name: "GLM-5.3" + type: "text" + protocols: ["chat/completions"] + - id: "glm-5.2" + display_name: "GLM-5.2" + type: "text" + protocols: ["chat/completions"] + - id: "glm-5.1" + display_name: "GLM-5.1" + type: "text" + protocols: ["chat/completions"] + - id: "kimi-k2.7-code" + display_name: "Kimi K2.7 Code" + type: "text" + protocols: ["chat/completions"] + # 上游硬约束:该模型**只接受 temperature=1**,传 0 / 0.7 等一律 400 + # "invalid temperature: only 1 is allowed for this model"。 + # 写死后网关无论收到什么温度都按 1 发(前端温度滑块、API 传参、一键测速探针 + # 统一生效);客户端不传 temperature 时也会显式按 1 发送,与上游默认值一致。 + params: + temperature: 1 + - id: "kimi-k2.6" + display_name: "Kimi K2.6" + type: "text" + protocols: ["chat/completions"] + - id: "longcat-2.0" + display_name: "LongCat 2.0" + type: "text" + protocols: ["chat/completions"] + - id: "mimo-v2.5" + display_name: "MiMo V2.5" + type: "text" + protocols: ["chat/completions"] + - id: "mimo-v2.5-pro" + display_name: "MiMo V2.5 Pro" + type: "text" + protocols: ["chat/completions"] + - id: "hy4-preview" + display_name: "Hy4 Preview" + type: "text" + protocols: ["chat/completions"] + - id: "hy3" + display_name: "Hy3" + type: "text" + protocols: ["chat/completions"] + # ── Chat + Messages 两条线都实测可用 ───────────────── + - id: "kimi-k3" + display_name: "Kimi K3" + type: "text" + protocols: ["chat/completions", "messages"] + - id: "minimax-m3" + display_name: "MiniMax M3" + type: "text" + protocols: ["chat/completions", "messages"] + - id: "minimax-m2.5" + display_name: "MiniMax M2.5" + type: "text" + protocols: ["chat/completions", "messages"] + - id: "qwen3.8-max" + display_name: "Qwen3.8 Max" + type: "text" + protocols: ["chat/completions", "messages"] + - id: "qwen3.8-flash" + display_name: "Qwen3.8 Flash" + type: "text" + protocols: ["chat/completions", "messages"] + - id: "qwen3.7-max" + display_name: "Qwen3.7 Max" + type: "text" + protocols: ["chat/completions", "messages"] + - id: "qwen3.7-plus" + display_name: "Qwen3.7 Plus" + type: "text" + protocols: ["chat/completions", "messages"] + - id: "qwen3.6-plus" + display_name: "Qwen3.6 Plus" + type: "text" + protocols: ["chat/completions", "messages"] + # ── 三条线全通(实测 chat / messages / responses 均 200, + # 非文档线另经流式 + 工具调用复核) ──────────────── + - id: "deepseek-v4.1-flash" + display_name: "DeepSeek V4.1 Flash" + type: "text" + vision: true # 2026-09-18 实测确认多模态:data:image/png;base64 红/蓝/绿三色均识别正确; + # 同一带图请求打到纯文本模型 deepseek-v4-flash 会被上游 400 拒(对照有效)。 + protocols: ["chat/completions", "messages", "responses"] + - id: "deepseek-v4-pro" + display_name: "DeepSeek V4 Pro" + type: "text" + protocols: ["chat/completions", "messages", "responses"] + - id: "deepseek-v4-flash" + display_name: "DeepSeek V4 Flash" + type: "text" + protocols: ["chat/completions", "messages", "responses"] + - id: "deepseek-v4-flash-vision-exp" + display_name: "DeepSeek V4 Flash Vision Exp" + type: "text" + vision: true # 官方标 Vision,支持图像转 token 输入 + protocols: ["chat/completions", "messages", "responses"] + # ── Anthropic Messages 线(文档主推这条)───────────── + - id: "minimax-m2.7" + display_name: "MiniMax M2.7" + type: "text" + # 实测:messages 线 200,chat / responses 都是 500 → 只标 messages + protocols: ["messages"] + - id: "union-alpha" + display_name: "Union Alpha Free" + type: "text" + # 文档标的 messages 线,但实测上游回 400「Model is unavailable.」 + # (限时免费模型,额度/可用性由上游控制)。先按文档收录并标注真实线, + # 调用时上游的不可用会原样回给客户端(网关不替它编文案)。 + protocols: ["messages"] + # ── OpenAI Responses 线 ─────────────────────────────── + - id: "grok-4.6" + display_name: "Grok 4.6" + type: "text" + # 实测:responses 200;chat / messages 都是 401 "not supported for format" + protocols: ["responses"] + - id: "gpt-5.6-luna" + display_name: "GPT 5.6 Luna" + type: "text" + protocols: ["responses"] + - id: "muse-spark-1.3-contributor" + display_name: "Muse Spark 1.3 Contributor" + type: "text" + # 实测三条线都 403 DataPolicyError:该模型会拿数据训练,需要先在 + # OpenCode 控制台**显式同意数据条款**才能调用(当前工作区未同意)。 + # 先收录并标好线:老板去控制台点了同意就能直接用,不用再改网关。 + protocols: ["responses"] + - id: "muse-spark-1.2-contributor" + display_name: "Muse Spark 1.2 Contributor" + type: "text" + protocols: ["responses"] +# ── 虚拟模型 id(别名,第三十一轮)────────────────────────── +# 客户端固定写 model: wjd,实际转发到哪个真实模型由**管理员在模型页选**(也可以改这里)。 +# · 只走 chat/completions(OpenAI)格式:用 /v1/messages、/v1/responses 打 wjd 会在入口 +# 400 指路(网关不做跨格式转换)→ 所以 target 必须是**文本模型且支持 chat/completions** +# (页面上其余候选项置灰,服务端保存时同样拦)。 +# · 别名不复制目标的配置:协议线、视觉、强制参数、定价**全继承 target**(一份事实来源)。 +# · 别名不是模型:进 /v1/models(带 alias_of)但不进测速、不进模型计数、不进成本指标 +# —— 那三项一律记**真实模型**。 +# · enabled: false = 这个 id 不存在(等同没配);停用时后端不校验 target。 +# · 别名 id 不得与真实模型 id 重名;简写 `wjd: opencode/kimi-k3` 等价于只填 target。 aliases: wjd: enabled: true - target: agnes-3.0-flash - note: 老板的固定入口(默认指向旗舰,随时可在页面上改) -# ── 服务与运维开关 ────────────────────────────────────── -# host/port/graceful_shutdown/docs_enabled/hot_reload 这几项**改完要重启进程**才生效, -# 其余每请求读取,页面保存即生效。 -# 安全相关:health_auth(/health/* 是否鉴权)、webhook_allow_private(视频回调是否允许内网地址)、 -# docs_enabled(FastAPI 文档,默认关)、auth_fail_limit_per_min(同源 IP 每分钟鉴权失败上限)。 -# cors_origins 写 ["*"] 表示任意站点都能跨域驱动本网关(会把上游额度暴露给陌生网页), -# 生产建议收敛成可信前端域名白名单。 + target: deepseek-v4.1-flash + note: 老板的固定入口(默认指向旗舰,随时可在模型页改) server: - host: 127.0.0.1 + host: "127.0.0.1" port: 8808 timeout: 120 - retry: 3 - health_auth: false - hot_reload: true - hot_reload_interval: 15 - metrics_enabled: true - rate_limit_rps: null - max_body_size: 2000000 - cors_origins: - - '*' - graceful_shutdown: 30 - batch_max_concurrency: 16 - batch_max_items: 64 - webhook_allow_private: false - docs_enabled: false - auth_fail_limit_per_min: 20 -# ── 供应商熔断 ────────────────────────────────────────── -# 某供应商在 window 秒内失败达到 failure_threshold 次就熔断 cooldown 秒, -# 期间直接跳过它(不再白等),让 fallback 快速切到健康供应商。 + retry: 3 # 同一模型的重试次数(含首次)。第二十七轮: 路由别名已删除,无 route.retry + # ── 运维开关 ── + health_auth: false # /health/* 是否也需鉴权(默认否,留给探活) + hot_reload: true # 监听 gateway.yaml mtime 自动重载(改配置免重启) + hot_reload_interval: 15 # 重载检查间隔(秒) + metrics_enabled: true # 记录调用指标(/metrics) + rate_limit_rps: null # 全局单 user QPS 上限(null=不限;供应商级用 provider.rate_limit_rps) + max_body_size: 2000000 # 请求体字节上限(防 DDoS,约 2MB) + cors_origins: ["*"] # CORS 允许来源(生产收紧为具体域名) + graceful_shutdown: 30 # 优雅关闭等待在途请求的秒数 + # ── 防滥用 / 安全 ── + batch_max_concurrency: 16 # /batch 并发上限(客户端 max_concurrency 会被钳到此值) + batch_max_items: 64 # /batch 单次最大条目数(超出返回 400) + webhook_allow_private: false # 视频 callback_url 是否允许指向内网/回环(SSRF 防护,默认禁) + docs_enabled: false # FastAPI 文档(/docs、/openapi.json)是否开放(安全默认关) + auth_fail_limit_per_min: 20 # 同一来源 IP 每分钟鉴权失败上限,超过 → 429(防暴力枚举) + +# ── 供应商熔断(Circuit Breaker) ────────────────────── +# 某供应商连续/滑动窗口失败达到 failure_threshold 就熔断 cooldown 秒, +# 期间直接跳过(不再白等),让 fallback 快速切到健康供应商。 circuit: enabled: true - failure_threshold: 3 - cooldown: 30 - window: 10 -# ── 可观测性 ──────────────────────────────────────────── -# log_level 支持 DEBUG/INFO/WARNING/ERROR;log_json=true 输出结构化 JSON 行(接 ELK)。 -# access_log_maxlen = 访问日志环形缓冲长度(日志页「已加载 N 条」的上限)。 + failure_threshold: 3 # 连续失败 3 次即熔断 + cooldown: 30 # 熔断持续 30 秒 + window: 10 # 滑动窗口 + +# ── 可观测性 ─────────────────────────────────────────── observability: - log_level: INFO - log_json: false - access_log_maxlen: 500 -# ── 定价(人民币 / 百万 token,用于 /v1 响应里估算成本) ─ -# 不配则该模型不返回 estimated_cost_cny(不影响调用)。 + log_level: "INFO" + log_json: false # true = 结构化 JSON 行日志(接 ELK/CloudWatch) + access_log_maxlen: 500 # 访问日志环形缓冲长度 + +# ── 定价(用于 /v1 响应里估算成本,人民币/百万 token) ─ +# 不配则该模型 estimated_cost_cny 不返回(不影响调用)。 pricing: per_model: - agnes-3.0-flash: - input: 0.35 - output: 1.0 - agnes-2.5-flash: - input: 0.0 - output: 0.0 - ark-code-latest: - input: 0.5 - output: 2.0 -# ── 媒体下载代理白名单 ────────────────────────────────── -# 生成的图片/视频挂在第三方 CDN 上且不带 CORS 头,浏览器 fetch 不到 blob、跨域 -# 也不生效 —— 所以由网关代拉一次并加 Content-Disposition: attachment。 -# 安全:这是全网关唯一一个服务端主动出网的接口,只有这里列出的域名(含子域)允许被代下载, -# 且解析出的 IP 必须是公网地址;allowed_hosts 为空 = 该功能整体关闭。 -# 换了供应商/CDN 域名时,往这里加一条即可(如 volc 的 tos-*.volces.com)。 + agnes-3.0-flash: { input: 0.35, output: 1.00 } + agnes-2.5-flash: { input: 0, output: 0 } # 文档现价暂免(输入/输出/缓存命中均 ¥0/百万) + ark-code-latest: { input: 0.50, output: 2.00 } + +# ── 媒体下载代理白名单(第十七轮)──────────────────────── +# 生成的图片/视频挂在第三方 CDN 上且不带 CORS 头,浏览器里既 fetch 不到 blob、 +# 跨域 也不生效(只会打开新标签页)。所以由网关代拉一次并加上 +# Content-Disposition: attachment,前端「下载」按钮才真的能存文件。 +# 安全:这是网关唯一一个服务端主动出网的接口 —— 只有这里列出的域名(含其子域) +# 允许被代下载,且解析出来的 IP 必须是公网地址;列表为空 = 该功能整体关闭。 +# 换了供应商/换了 CDN 域名时,往这里加一条即可(如 volc 的 tos-*.volces.com)。 download: + # 维护提醒(第三十轮):这张表是**下载代理的出网白名单** —— /v1/media/download 只肯代抓这里列出的域名。 + # 供应商换 CDN、或同一供应商多套存储(普通版 / 水印版)时,**漏加就会让「下载」按钮 400** + # (报「该地址不在允许下载的域名白名单内」)。新增前先确认域名确实属于该供应商的产物存储。 allowed_hosts: - - cos-platform-outputs.agnes-ai.cn - - maas-watermark-prod-new.cn-wlcb.ufileos.com - max_bytes: 67108864 -# ── 网关入口鉴权 ──────────────────────────────────────── -# 账号与 API Key 由页面管理,存在 data/users.json(见 app/users.py): -# 管理员在「用户管理」建账号,各账号在「设置 → 我的 API Key」自助铸 Key。 -# 本文件里没有任何用户/密钥,只有会话时长这一个开关。 + - "cos-platform-outputs.agnes-ai.cn" # Agnes 图像/视频产物 CDN(普通版) + - "maas-watermark-prod-new.cn-wlcb.ufileos.com" # Agnes 水印版产物 CDN(UCloud ufileos) + max_bytes: 67108864 # 单文件上限 64MB + +# ── 网关入口鉴权 ───────────────────────────────────── +# 账号与 API Key 全部由页面管理,存在 data/users.json(见 app/users.py): +# 管理员在「用户管理」页建账号,各账号在「设置 → 我的 API Key」自助铸 Key。 +# 本文件里**不再有任何用户/密钥**,只有一个运维开关: +# auth.session_ttl_minutes —— 网页登录签发的会话有效期(分钟,默认 1440 = 24h) +# 第十八轮: 删掉了这里残留的旧 `auth.enabled/users/key` 死配置(含一把明文 wjd- Key)。 +# 那些键早已不再被 config.py 读取(只读 session_ttl_minutes), +# 那把 Key 在 users.json 里也不存在 → 认不了任何入口,但会让"yaml 里没有明文凭证"的说法失真。 auth: session_ttl_minutes: 1440 + +# ── 路由别名 / fallback 链:已整体删除 ────────────────── +# 第二十七轮(老板 2026-09-18 决策):**路由别名功能整体删除**,不再有 routes 段。 +# 原因:三线直传落地后"入站格式 = 出站格式",模型 id 必须与协议线一一对应; +# 再套一层"自动挑最快模型"的别名,会把调用方选定的格式/能力(视觉、工具、协议线) +# 悄悄换掉。现在调用方直接填真实模型 id;要换模型就换 id,网关不再替谁做主。 +# 老配置里残留的 routes 段会被忽略(不会让进程起不来),日志里有 warning 可查。 +# 一键测速(Models 页每个模型后面的)不受影响,仍然逐个模型实测延迟。 diff --git a/frontend/src/locales/en.ts b/frontend/src/locales/en.ts index 1e7df40..6bf0dcb 100644 --- a/frontend/src/locales/en.ts +++ b/frontend/src/locales/en.ts @@ -409,9 +409,8 @@ export default { probedLine: 'probed via {p}', // Round 31: virtual model id (alias) — clients always send model: wjd, the gateway // forwards to the model an admin picks. An alias is not a model: it never shows up in - // the speed-test list or the model counts, only in this card and its read-only row. + // the speed-test list or the model counts, only in this card. aliasCard: 'Virtual model id (alias)', - aliasSub: 'Clients always send model: {id}; the gateway forwards to the model you pick', aliasLine: 'Only the chat/completions (OpenAI) format is supported: calling {id} on /v1/messages or /v1/responses is rejected with 400 at the gateway (it never translates formats).', aliasInherit: 'Vision, forced params and pricing all follow the target model — the alias stores no configuration of its own, so switching the target switches everything.', aliasName: 'Alias id', @@ -422,7 +421,6 @@ export default { aliasEnabled: 'Enabled', aliasDisabled: 'Disabled', aliasNotConfigured: 'No target model configured yet — clients sending model: {id} get "unknown model".', - aliasReadonly: 'Read-only: the mapping is chosen by an admin in the gateway config', aliasSave: 'Save mapping', aliasSaved: '{id} → {target} is live', aliasSaveFail: 'Save failed', diff --git a/frontend/src/locales/zh.ts b/frontend/src/locales/zh.ts index 5857af7..f2c6596 100644 --- a/frontend/src/locales/zh.ts +++ b/frontend/src/locales/zh.ts @@ -407,9 +407,8 @@ export default { protocolHintRow: '支持的格式:{lines} ', probedLine: '本次测速走 {p}', // 第三十一轮:虚拟模型 id(别名)—— 客户端固定写 model: wjd,实际转发到管理员选的模型。 - // 别名不是模型:不进测速列表、不进模型计数,只有这一张卡片和它的只读行。 + // 别名不是模型:不进测速列表、不进模型计数,只有这一张卡片。 aliasCard: '虚拟模型 id(别名)', - aliasSub: '客户端固定写 model: {id},网关转发到你选的模型', aliasLine: '只支持 chat/completions(OpenAI)格式:用 /v1/messages、/v1/responses 打 {id} 会在入口直接 400(网关不做跨格式转换)。', aliasInherit: '视觉能力、强制参数与定价都跟随目标模型 —— 别名不另存一份配置,改目标即可整体切换。', aliasName: '别名 ID', @@ -420,7 +419,6 @@ export default { aliasEnabled: '启用', aliasDisabled: '已停用', aliasNotConfigured: '尚未配置目标模型 —— 此时客户端写 model: {id} 会得到「未知模型」。', - aliasReadonly: '只读:映射由管理员在网关配置里选择', aliasSave: '保存映射', aliasSaved: '{id} → {target} 已生效', aliasSaveFail: '保存失败', diff --git a/frontend/src/views/Models.vue b/frontend/src/views/Models.vue index 53c26b7..8098a8b 100644 --- a/frontend/src/views/Models.vue +++ b/frontend/src/views/Models.vue @@ -79,13 +79,12 @@
{{ t('models.aliasCard') }} - {{ t('models.aliasSub', { id: aliasRows[0].name }) }}
@@ -114,8 +113,6 @@ {{ t('models.aliasSave') }}
-
{{ t('models.aliasReadonly') }}
-
{{ t('models.aliasLine', { id: a.name }) }}
{{ t('models.aliasInherit') }}
@@ -298,7 +295,7 @@ const models = computed(() => items.value.filter((x: any) => !x.alias_of)) // ── 别名(第三十一轮)── // admin:读 GET /config 的 aliases(**含 enabled** —— 停用的别名在 /v1/models 里看不到), // 可改可存;没配过就给一行以 wjd 为名的空白模板(选完目标点保存即可)。 -// member:读 /v1/models 里的 alias_of,只显示只读行(PUT /config 本就只认管理员+会话)。 +// member:读 /v1/models 里的 alias_of,只渲染数据行(没有编辑行;PUT /config 本就只认管理员+会话)。 const ALIAS_ID = 'wjd' // 当前就这一个(老板 2026-09-18 定);配置层支持多个,页面按列表渲染 const aliasEdit = ref([]) const aliasSaving = ref(false) @@ -510,7 +507,8 @@ onMounted(load) .st-lat { min-width: 88px; text-align: center; } .st-loading { font-style: italic; } .lat-head { display: flex; align-items: center; gap: 8px; padding: 2px 0 6px; } -/* 第三十一轮:别名卡片(别名不是模型,用"指针"感的排版:名字 → 目标) */ +/* 第三十一轮:别名卡片(别名不是模型,用"指针"感的排版:名字 → 目标)。 + 2026-09-18 老板:卡片的副标题与 member 的「只读:…」提示都删掉,只留数据行 + 说明。 */ .alias { padding: 10px 0; } .alias + .alias { border-top: 1px dashed var(--line); } .alias-top { display: flex; align-items: center; gap: 8px; font-size: 13px; } @@ -522,7 +520,6 @@ onMounted(load) .alias-arrow { color: var(--muted-2); } .alias-edit { display: flex; align-items: center; gap: 10px; margin-top: 10px; flex-wrap: wrap; } .alias-sel { width: 340px; max-width: 100%; } -.alias-ro { margin-top: 8px; font-size: 11.5px; color: var(--muted-2); } .alias-hint { margin-top: 8px; font-size: 11.5px; line-height: 1.65; color: var(--muted-2); } .alias-warn { color: var(--warn); } diff --git a/tests/test_gateway.py b/tests/test_gateway.py index 76206d9..767ba34 100644 --- a/tests/test_gateway.py +++ b/tests/test_gateway.py @@ -3444,6 +3444,10 @@ def test_config_save_applies_without_restart(): tmp = tempfile.TemporaryDirectory() cfg_path = P(tmp.name) / "gateway.yaml" cfg_path.write_text(P(CONFIG).read_text(encoding="utf-8"), encoding="utf-8") + # 注入一行人工注释:结构化保存**不许**把它抹掉(第三十一轮修的正是这个事故) + with cfg_path.open("a", encoding="utf-8") as fh: + fh.write("\n# 人工注释:别动我\n") + comments_before = cfg_path.read_text(encoding="utf-8").count("#") old_path, old_cfg = m.CONFIG_PATH, m.config m.CONFIG_PATH = cfg_path try: @@ -4770,6 +4774,10 @@ def test_alias_panel_round_trip_and_save_validation(): tmp = tempfile.TemporaryDirectory() cfg_path = P(tmp.name) / "gateway.yaml" cfg_path.write_text(P(CONFIG).read_text(encoding="utf-8"), encoding="utf-8") + # 注入一行人工注释:结构化保存**不许**把它抹掉(第三十一轮修的正是这个事故) + with cfg_path.open("a", encoding="utf-8") as fh: + fh.write("\n# 人工注释:别动我\n") + comments_before = cfg_path.read_text(encoding="utf-8").count("#") old_path, old_cfg = m.CONFIG_PATH, m.config m.CONFIG_PATH = cfg_path try: @@ -4779,18 +4787,23 @@ def test_alias_panel_round_trip_and_save_validation(): assert "aliases" in view, view.keys() # 换一个和生产默认不同的目标,才能证明写入真的生效了 target = "ark-code-latest" - view["aliases"] = {"wjd": {"enabled": True, "target": target, "note": "客户入口"}} - r = client.put("/config", headers=ah, json={"config": view}) + payload = {"wjd": {"enabled": True, "target": target, "note": "客户入口"}} + # 面板真实载荷:模型页「保存映射」只提交 aliases 一段(Models.vue saveAlias), + # 不是整份视图 —— 服务端按段合并,其余段沿用文件原文(连行尾注释都不动)。 + r = client.put("/config", headers=ah, json={"config": {"aliases": payload}}) assert r.status_code == 200, r.text assert m.config.resolve_alias("wjd") == target, "保存即生效" - # 落盘 yaml 里也确实有这一段(面板下次读得回来) - assert _yaml.safe_load(cfg_path.read_text(encoding="utf-8"))["aliases"]["wjd"]["target"] == target + # 落盘 yaml 里也确实有这一段(面板下次读得回来),且**人工注释一行不少** + disk = cfg_path.read_text(encoding="utf-8") + assert _yaml.safe_load(disk)["aliases"]["wjd"]["target"] == target + assert "人工注释:别动我" in disk, "结构化保存把人工注释抹掉了" + assert disk.count("#") == comments_before, "结构化保存不该改动其他段的注释" lm = client.get("/v1/models", headers=ah).json()["data"] assert next(x for x in lm if x["id"] == "wjd")["alias_of"] == target # 非法目标:400 + 不写盘(盘上仍是上一个合法值) - bad = client.get("/config", headers=ah).json()["config"] - bad["aliases"]["wjd"]["target"] = "根本没有这个模型" - r2 = client.put("/config", headers=ah, json={"config": bad}) + r2 = client.put("/config", headers=ah, + json={"config": {"aliases": {"wjd": {"enabled": True, + "target": "根本没有这个模型"}}}}) assert r2.status_code == 400 and "wjd" in r2.text, r2.text assert _yaml.safe_load(cfg_path.read_text(encoding="utf-8"))["aliases"]["wjd"]["target"] == target assert m.config.resolve_alias("wjd") == target @@ -4831,6 +4844,122 @@ def test_alias_streaming_uses_one_name_throughout(): assert frames[0]["served_model"] == "m-chat", frames[0] # 真实目标在这里说清楚 +def test_merged_write_keeps_neighbour_docs_and_skips_unchanged(): + """第三十一轮补测:文本级合并的三个边界(都是这次真踩过的坑)。 + + ① 被替换段的**段尾说明**(那是下一段的抬头注释 / 文件页脚)必须留在原位 —— + 否则"改 providers"会顺手把 `server:` 上方的说明书删掉; + ② 新增的段要插在下一段**说明注释之前**,不能插进"说明与键行"之间(否则别人的 + 说明书就成了新段的抬头); + ③ 提交了但值没变的段一个字节都不许动 —— 面板 PUT 的是整份视图,段内行尾注释 + (如 `timeout: 120 # …`)不该因为一次无关保存而蒸发。""" + import tempfile + import yaml as _yaml + from pathlib import Path as P + from app.settings import merge_submitted_sections, write_config_merged + + text = ( + "# 抬头:手写说明\n" + "providers:\n" + " p:\n" + " name: P\n" + " base_url: http://x/v1\n" + " models:\n" + " - id: m-chat\n" + " display_name: Chat\n" + "# ── server 的说明书(人工)────────────────\n" + "# host/port 改完要重启进程才生效。\n" + "server:\n" + " timeout: 120 # 行尾注释:同一模型的超时,别动\n" + ) + prov = {"p": {"name": "P", "base_url": "http://x/v1", + "models": [{"id": "m-chat", "display_name": "Chat"}]}} + alias = {"wjd": {"enabled": True, "target": "m-chat", "note": "客户入口"}} + plain = {"providers": prov, "server": {"timeout": 120}} + + # ① 改 providers:它的段尾正是 server 的说明书 → 说明与段序都得在 + m = merge_submitted_sections(text, plain, {"providers"}) + assert _yaml.safe_load(m) == plain, m + assert "── server 的说明书" in m and "host/port 改完要重启进程才生效。" in m, m + assert m.index("说明书") < m.index("server:"), "说明必须还在 server 上方" + + # ② 新增 aliases:插点在 server 的说明注释之前 + m2 = merge_submitted_sections(text, {**plain, "aliases": alias}, {"aliases"}) + assert _yaml.safe_load(m2) == {**plain, "aliases": alias}, m2 + assert m2.index("aliases:") < m2.index("── server 的说明书") < m2.index("server:"), m2 + assert m2.startswith("# 抬头:手写说明"), "抬头不许被跳过" + + # ③ 值没变的段不重写:server 的行尾注释要活下来(写盘端到端) + with tempfile.TemporaryDirectory() as d: + f = P(d) / "gateway.yaml" + f.write_text(text, encoding="utf-8") + raw_old = _yaml.safe_load(text) + info = write_config_merged(f, {**plain, "aliases": alias}, raw_old, + {"aliases", "providers", "server"}) + disk = f.read_text(encoding="utf-8") + assert info["mode"] == "merged" and info["sections"] == ["aliases"], info + assert "行尾注释:同一模型的超时,别动" in disk, "没变的段被重写了" + assert _yaml.safe_load(disk) == {**plain, "aliases": alias}, disk + + +def test_structured_save_only_touches_submitted_section(): + """第三十一轮修的真实事故:结构化保存(模型页「保存映射」)原来走 render_yaml 整份重写, + 把 gateway.yaml 里历轮手写的现场注释全抹了。现在只替换**提交过的那一段**,其余字节不动。 + + 这里用一个带"人工注释"的小配置文件端到端验:改别名 → 注释还在、别的段一个字节没变; + 再加一段定位失败的怪文本,确认回退整份重渲染(配置正确优先,注释其次)。 + """ + from app.settings import merge_submitted_sections, write_config_merged, render_yaml + import yaml as _yaml + text = ( + "# 抬头注释(人工)\n" + "providers:\n" + " p:\n" + " # 这里也是人工注释:别动我\n" + " name: P\n" + " base_url: http://x/v1\n" + " models:\n" + " - id: m-chat\n" + " display_name: Chat 模型\n" + "server:\n" + " timeout: 120\n" + ) + new = {"providers": {"p": {"name": "P", "base_url": "http://x/v1", + "models": [{"id": "m-chat", "display_name": "Chat 模型"}]}}, + "aliases": {"wjd": {"enabled": True, "target": "m-chat", "note": "客户入口"}}, + "server": {"timeout": 120}} + merged = merge_submitted_sections(text, new, {"aliases"}) + assert merged is not None + assert "别动我" in merged and "抬头注释(人工)" in merged, "人工注释必须原样保留" + assert merged.startswith(text.split("aliases")[0][:20]), "前面的文本不该被重排" + # 新增段插到它该在的位置(aliases 在 _SECTION_ORDER 里紧跟 providers → 应在 server 之前) + assert merged.index("aliases:") < merged.index("server:"), merged + assert "wjd" in merged and _yaml.safe_load(merged) == new, "合并结果必须与提交内容一致" + assert "provider 与 server 的原文都在" # 语义检查由上面 safe_load 相等保证 + + # 段已存在 → 只替换该段 + merged2 = merge_submitted_sections(merged, {**new, "server": {"timeout": 999}}, {"server"}) + assert "timeout: 999" in merged2 and "别动我" in merged2 and _yaml.safe_load(merged2)["aliases"] == new["aliases"] + + # 怪文本(没有顶层段)→ 让调用方回退整份重渲染 + assert merge_submitted_sections("这不是 yaml::\n- 1\n- 2\n", new, {"aliases"}) is None + + # write_config_merged: 不变量对不上时自动回退 rendered 模式(且写出的一定是正确配置) + import tempfile + from pathlib import Path as P + with tempfile.TemporaryDirectory() as d: + f = P(d) / "g.yaml" + f.write_text(text, encoding="utf-8") + info = write_config_merged(f, new, {}, {"aliases"}) + assert info["mode"] == "merged" and "别动我" in f.read_text(encoding="utf-8"), info + # 提交一个"面板不认识"的段 → 仍然要能写对(追加到末尾),且回读一致 + weird = {**new, "custom_x": {"a": 1}} + info2 = write_config_merged(f, weird, {}, {"aliases", "custom_x"}) + assert _yaml.safe_load(f.read_text(encoding="utf-8")) == weird, info2 + assert ("别动我" in f.read_text(encoding="utf-8")) if info2["mode"] == "merged" else True + assert render_yaml(new).startswith("#"), "整份重渲染路径仍在(回退用)" + + # 直接运行(非 pytest)—— 必须留在文件末尾,见上方 `test_image_request_goes_to_requested_model` # 之前的旁注:运行器只会收集执行到这一行时已经存在的 globals。 if __name__ == "__main__":