refactor(scheduler)!: 移除 priority 废弃字段 + 一通道一源 + discover 复用凭据

用户判据:「priority 直接移除」「即使带 key 也没有 /v1/responses」
「channel 插件的问题还没完全解决」「生图和聊天合并到一个导航项」

## 一、删除 priority(它从未参与跨源调度)

`config.Model.Priority` 号称"高者优先参与 AUTO 选源",**那是错的**:
AUTO 链由 `config.ModelScope.Tier` 驱动(scheduler.Chain),priority 只被
`bestChatModel/bestImageModel` 用于"本源内部该发哪个模型",与跨源调度无关。
把它当调度依据会让人以为拖个数字就能改顺序,改完毫无效果。

- 删 `config.Model.Priority` 字段与 `bestChatModel/bestImageModel` 的优先级比较
- 删 `seedAuto()`:**AUTO 链为空时网关应直接 503**,不能凭空播种用户没配过的档位
- 删 UI `buildLanes` 的 discovery 回退(按源 priority 自动铺开)与 sourceRows
- 清掉 config.yaml 里 140 行 priority

## 二、一通道 = 一个适配器 = 一个源(channels 插件)

旧设计「一账号一源」(`channels-<平台>-<12位hex>`) 有三个结构性后果:
1. 三个账号 ⇒ 三个源、三份同名模型,用户看到三行无法区分的东西
2. 谁先谁后**取决于注册顺序,不是余额**(rankAccounts 只用于展示,从未接进同步路径)
3. 换号要改源名 ⇒ 用户书签里的 `源:模型` 全部失效

新设计:
- 源名只跟通道绑定:`channels-<平台>`,换号 = 同名 add_source 覆盖 api_key
  (内核 AddSource 是 UpsertSourceInYAML + 内存替换),对客户端完全透明
- `pickAccountForSource()`:凭据可用 → 余额分档(先快作废后永久)→
  跳过已标记失效的号。没有 balance 声明的平台不据此排除(不因"不会查"判死)
- `request_end` 钩子:真实请求失败且是**终态**错误(需充值/封禁/凭据永久失效)
  时给当前账号打 termErr,下次选号跳过;成功则清标记。
  ⚠️ 只认终态 —— 429/超时/抖动都**不**标记(那会把好号一个个废掉)
- `refresh_creds` 每 30 分钟巡检后重新选号(兜底心跳,纯本地判定)
- 迁移:同步时自动清掉旧版按账号拆的源(按已知平台前缀匹配,不用贪婪 match)
- 顺带修:`refresh_creds` 漏认 `refresh_fn` ⇒ codearts 的 DPoP 续期永不触发

## 三、discover 支持用已存凭据(真实缺口)

刷新已有源的模型目录,此前必须让运维**再粘一次明文 key** —— 而库里是
`enc:v1:` 密文,WebUI 也不回显明文。结果就是"想刷新 → 得重新申请 key",
很多人干脆不刷,源的目录越放越旧(实例:某源 3 个生图模型从未登记)。

- `{"name":"oin"}` ⇒ 从已存源取 base_url + 解密凭据 + adapter
- 安全边界:已要求 admin;只能探测**本网关已配置的**源(不能拿任意 URL+key
  做探测,那就成了 SSRF/密钥外带);响应不回显 key

## 四、image_models 显式声明(补元数据缺失)

`discoveredModelKind` 只看上游 modality 字段,并刻意**不从模型名推断**
(错误的 kind 会毒死 AUTO 链)。但有些网关的 /v1/models 只返回
`{id,object,created,owned_by}` —— 零 modality,于是生图模型全落成 chat,
生图端点永远 `no image source configured`。

不解这个两难:默认仍完全按元数据(不猜),但允许 `image_models` **显式声明**。
写错的 id 明确报 400,不静默造一个不存在的模型。

## 五、UI:对话与生图合并为一个导航项

两者本是同一件事的两种输入(都选模型、都发请求、都读结果),只是 kind 与端点
不同。合并只发生在**导航层**:模型下拉仍按 kind 分组/禁选(把图片模型选进 chat
会请求到错误端点)。两个面板同时存在于 DOM,切换只改 display —— 来回切不会丢
已输入的文字、对话历史或已生成的图。

## 测试

- `TestUI_ImageModeIsReachableFromChatTab`:改为钉"合并后仍可达"(分段控件、
  切换函数、面板容器、端点),并断言**旧 tab 三件套必须消失**(否则 goTab 会找
  一个不存在的面板)
- 测试夹具显式建 AUTO 链(内核不再 seedAuto):默认一源一 tier 倒序
  (TestChatAUTO 验优先级);TestChatAutoChainTierFailover 自己覆盖成同 tier
  (验 tier 内轮转)—— 两者验不同机制,不能共用一个默认
- core 的一批断言从"按账号 id 找源"改为"按平台名找源"

gateway/config/provider 全绿;core 的 channels 用例全绿。
TestRealMutants 需工作树干净后才跑(其自带的变异残留防护)。

BREAKING CHANGE: config.Model.Priority 已删除。旧的 priority 字段会被 YAML
解码静默忽略(内核不校验未知字段),因此既有 config.yaml 仍可加载,但该字段
不再有任何作用 —— 调度顺序请通过 AUTO 链的 tier 表达。
This commit is contained in:
JianFeeeee
2026-10-19 16:26:59 +08:00
parent 6f2d4dc6eb
commit 25970a2135
30 changed files with 830 additions and 346 deletions

View File

@ -62,13 +62,18 @@ const (
DefaultSourceConcurrency = 8
)
// Model is a single exposed model id bound to a source, with priority used by
// AUTO auto selection (higher number = preferred).
// Model is a single exposed model id bound to a source.
//
// ★ 曾经有 `Priority int` 字段,并号称"高者优先参与 AUTO 选源"。**那是错的**:
//
// AUTO 链由 `config.ModelScope.Tier` 驱动(见 scheduler.Chain),而 priority
// 只被 `bestChatModel/bestImageModel` 用于"本源码内部该发哪个模型",
// 与跨源调度毫无关系。把它当成调度依据会让人误以为改个数字就能改顺序,
// 改完发现毫无效果 —— 已彻底删除,避免再次误导。
type Model struct {
ID string `yaml:"id" json:"id"`
Priority int `yaml:"priority" json:"priority"`
Kind string `yaml:"kind" json:"kind"` // "chat" (default) | "image"
Meta map[string]interface{} `yaml:"meta" json:"meta,omitempty"`
ID string `yaml:"id" json:"id"`
Kind string `yaml:"kind" json:"kind"` // "chat" (default) | "image"
Meta map[string]interface{} `yaml:"meta" json:"meta,omitempty"`
}
// Source describes a single upstream LLM provider.

View File

@ -52,9 +52,6 @@ sources:
if cfg.Sources[1].MaxConcurrent == 0 {
t.Fatal("default max_concurrent not applied")
}
if cfg.Sources[0].Models[0].Priority != 100 {
t.Fatalf("priority = %d", cfg.Sources[0].Models[0].Priority)
}
if cfg.DefaultModel != "AUTO" {
t.Fatalf("default model = %q", cfg.DefaultModel)
}

View File

@ -14,9 +14,9 @@ var PresetTemplates = []SourceTemplate{
Adapter: "deepseek",
MaxConcurrent: 8,
Models: []Model{
{ID: "deepseek-v4-flash", Priority: 100, Kind: "chat"},
{ID: "deepseek-v4-pro", Priority: 90, Kind: "chat"},
{ID: "deepseek-v4-flash-vision-exp", Priority: 60, Kind: "chat"},
{ID: "deepseek-v4-flash", Kind: "chat"},
{ID: "deepseek-v4-pro", Kind: "chat"},
{ID: "deepseek-v4-flash-vision-exp", Kind: "chat"},
},
},
{
@ -25,10 +25,10 @@ var PresetTemplates = []SourceTemplate{
Adapter: "openai",
MaxConcurrent: 8,
Models: []Model{
{ID: "glm-5.3", Priority: 100, Kind: "chat"},
{ID: "glm-5.3-flash", Priority: 90, Kind: "chat"},
{ID: "glm-5.2", Priority: 80, Kind: "chat"},
{ID: "glm-5.1", Priority: 60, Kind: "chat"},
{ID: "glm-5.3", Kind: "chat"},
{ID: "glm-5.3-flash", Kind: "chat"},
{ID: "glm-5.2", Kind: "chat"},
{ID: "glm-5.1", Kind: "chat"},
},
},
{
@ -37,10 +37,10 @@ var PresetTemplates = []SourceTemplate{
Adapter: "openai",
MaxConcurrent: 8,
Models: []Model{
{ID: "kimi-k3", Priority: 100, Kind: "chat"},
{ID: "kimi-k2.7-code", Priority: 90, Kind: "chat"},
{ID: "kimi-k2.7-code-highspeed", Priority: 85, Kind: "chat"},
{ID: "kimi-k2.6", Priority: 70, Kind: "chat"},
{ID: "kimi-k3", Kind: "chat"},
{ID: "kimi-k2.7-code", Kind: "chat"},
{ID: "kimi-k2.7-code-highspeed", Kind: "chat"},
{ID: "kimi-k2.6", Kind: "chat"},
},
},
{
@ -49,11 +49,11 @@ var PresetTemplates = []SourceTemplate{
Adapter: "openai",
MaxConcurrent: 8,
Models: []Model{
{ID: "deepseek-ai/DeepSeek-V4-Pro", Priority: 100, Kind: "chat"},
{ID: "deepseek-ai/DeepSeek-V4-Flash", Priority: 90, Kind: "chat"},
{ID: "moonshotai/Kimi-K2.6", Priority: 80, Kind: "chat"},
{ID: "zai-org/GLM-5.1", Priority: 70, Kind: "chat"},
{ID: "Kwai-Kolors/Kolors", Priority: 50, Kind: "image"},
{ID: "deepseek-ai/DeepSeek-V4-Pro", Kind: "chat"},
{ID: "deepseek-ai/DeepSeek-V4-Flash", Kind: "chat"},
{ID: "moonshotai/Kimi-K2.6", Kind: "chat"},
{ID: "zai-org/GLM-5.1", Kind: "chat"},
{ID: "Kwai-Kolors/Kolors", Kind: "image"},
},
},
{
@ -62,9 +62,9 @@ var PresetTemplates = []SourceTemplate{
Adapter: "openai",
MaxConcurrent: 4,
Models: []Model{
{ID: "4.0Ultra", Priority: 100, Kind: "chat"},
{ID: "generalv3.5", Priority: 80, Kind: "chat"},
{ID: "max-32k", Priority: 70, Kind: "chat"},
{ID: "4.0Ultra", Kind: "chat"},
{ID: "generalv3.5", Kind: "chat"},
{ID: "max-32k", Kind: "chat"},
},
},
{
@ -73,11 +73,11 @@ var PresetTemplates = []SourceTemplate{
Adapter: "openai",
MaxConcurrent: 8,
Models: []Model{
{ID: "qwen3.8-max", Priority: 100, Kind: "chat"},
{ID: "qwen3.8-flash", Priority: 90, Kind: "chat"},
{ID: "qwen3.7-plus", Priority: 85, Kind: "chat"},
{ID: "deepseek-v4-pro", Priority: 70, Kind: "chat"},
{ID: "kimi-k3", Priority: 70, Kind: "chat"},
{ID: "qwen3.8-max", Kind: "chat"},
{ID: "qwen3.8-flash", Kind: "chat"},
{ID: "qwen3.7-plus", Kind: "chat"},
{ID: "deepseek-v4-pro", Kind: "chat"},
{ID: "kimi-k3", Kind: "chat"},
},
},
{
@ -86,9 +86,9 @@ var PresetTemplates = []SourceTemplate{
Adapter: "openai",
MaxConcurrent: 8,
Models: []Model{
{ID: "ernie-5.0-turbo", Priority: 100, Kind: "chat"},
{ID: "ernie-5.0", Priority: 90, Kind: "chat"},
{ID: "deepseek-v4-pro", Priority: 70, Kind: "chat"},
{ID: "ernie-5.0-turbo", Kind: "chat"},
{ID: "ernie-5.0", Kind: "chat"},
{ID: "deepseek-v4-pro", Kind: "chat"},
},
},
{
@ -97,9 +97,9 @@ var PresetTemplates = []SourceTemplate{
Adapter: "openai",
MaxConcurrent: 8,
Models: []Model{
{ID: "doubao-seed-2.0-pro", Priority: 100, Kind: "chat"},
{ID: "doubao-seed-2.0", Priority: 90, Kind: "chat"},
{ID: "doubao-seed-2.0-flash", Priority: 80, Kind: "chat"},
{ID: "doubao-seed-2.0-pro", Kind: "chat"},
{ID: "doubao-seed-2.0", Kind: "chat"},
{ID: "doubao-seed-2.0-flash", Kind: "chat"},
},
},
{
@ -108,8 +108,8 @@ var PresetTemplates = []SourceTemplate{
Adapter: "openai",
MaxConcurrent: 8,
Models: []Model{
{ID: "MiniMax-M3", Priority: 100, Kind: "chat"},
{ID: "MiniMax-M2.5", Priority: 80, Kind: "chat"},
{ID: "MiniMax-M3", Kind: "chat"},
{ID: "MiniMax-M2.5", Kind: "chat"},
},
},
// ── 国际主流 ────────────────────────────────────────────────────────────
@ -119,9 +119,9 @@ var PresetTemplates = []SourceTemplate{
Adapter: "openai",
MaxConcurrent: 8,
Models: []Model{
{ID: "gpt-5.6-sol", Priority: 100, Kind: "chat"},
{ID: "gpt-5.6-terra", Priority: 90, Kind: "chat"},
{ID: "gpt-5.6-luna", Priority: 80, Kind: "chat"},
{ID: "gpt-5.6-sol", Kind: "chat"},
{ID: "gpt-5.6-terra", Kind: "chat"},
{ID: "gpt-5.6-luna", Kind: "chat"},
},
},
{
@ -130,10 +130,10 @@ var PresetTemplates = []SourceTemplate{
Adapter: "anthropic",
MaxConcurrent: 8,
Models: []Model{
{ID: "claude-opus-5", Priority: 100, Kind: "chat"},
{ID: "claude-fable-5", Priority: 95, Kind: "chat"},
{ID: "claude-sonnet-5", Priority: 85, Kind: "chat"},
{ID: "claude-haiku-4-5", Priority: 70, Kind: "chat"},
{ID: "claude-opus-5", Kind: "chat"},
{ID: "claude-fable-5", Kind: "chat"},
{ID: "claude-sonnet-5", Kind: "chat"},
{ID: "claude-haiku-4-5", Kind: "chat"},
},
},
{
@ -142,10 +142,10 @@ var PresetTemplates = []SourceTemplate{
Adapter: "gemini",
MaxConcurrent: 8,
Models: []Model{
{ID: "gemini-3.6-flash", Priority: 100, Kind: "chat"},
{ID: "gemini-3.5-flash", Priority: 90, Kind: "chat"},
{ID: "gemini-3.5-flash-lite", Priority: 80, Kind: "chat"},
{ID: "gemini-3.1-pro", Priority: 85, Kind: "chat"},
{ID: "gemini-3.6-flash", Kind: "chat"},
{ID: "gemini-3.5-flash", Kind: "chat"},
{ID: "gemini-3.5-flash-lite", Kind: "chat"},
{ID: "gemini-3.1-pro", Kind: "chat"},
},
},
{
@ -154,9 +154,9 @@ var PresetTemplates = []SourceTemplate{
Adapter: "groq",
MaxConcurrent: 8,
Models: []Model{
{ID: "openai/gpt-oss-120b", Priority: 100, Kind: "chat"},
{ID: "openai/gpt-oss-20b", Priority: 80, Kind: "chat"},
{ID: "groq/compound", Priority: 70, Kind: "chat"},
{ID: "openai/gpt-oss-120b", Kind: "chat"},
{ID: "openai/gpt-oss-20b", Kind: "chat"},
{ID: "groq/compound", Kind: "chat"},
},
},
{
@ -165,9 +165,9 @@ var PresetTemplates = []SourceTemplate{
Adapter: "mistral",
MaxConcurrent: 8,
Models: []Model{
{ID: "mistral-medium-latest", Priority: 100, Kind: "chat"},
{ID: "mistral-large-latest", Priority: 90, Kind: "chat"},
{ID: "codestral-latest", Priority: 85, Kind: "chat"},
{ID: "mistral-medium-latest", Kind: "chat"},
{ID: "mistral-large-latest", Kind: "chat"},
{ID: "codestral-latest", Kind: "chat"},
},
},
{
@ -180,10 +180,10 @@ var PresetTemplates = []SourceTemplate{
"X-Title": "ModelRouter",
},
Models: []Model{
{ID: "openrouter/auto", Priority: 100, Kind: "chat"},
{ID: "deepseek/deepseek-v4-flash", Priority: 90, Kind: "chat"},
{ID: "anthropic/claude-opus-5", Priority: 85, Kind: "chat"},
{ID: "openai/gpt-5.6-sol", Priority: 85, Kind: "chat"},
{ID: "openrouter/auto", Kind: "chat"},
{ID: "deepseek/deepseek-v4-flash", Kind: "chat"},
{ID: "anthropic/claude-opus-5", Kind: "chat"},
{ID: "openai/gpt-5.6-sol", Kind: "chat"},
},
},
{
@ -192,8 +192,8 @@ var PresetTemplates = []SourceTemplate{
Adapter: "github",
MaxConcurrent: 8,
Models: []Model{
{ID: "gpt-5.6-sol", Priority: 100, Kind: "chat"},
{ID: "gpt-5.6-luna", Priority: 80, Kind: "chat"},
{ID: "gpt-5.6-sol", Kind: "chat"},
{ID: "gpt-5.6-luna", Kind: "chat"},
},
},
// ── 本地模型 ────────────────────────────────────────────────────────────
@ -204,9 +204,9 @@ var PresetTemplates = []SourceTemplate{
Endpoint: "/api/chat",
MaxConcurrent: 4,
Models: []Model{
{ID: "qwen3", Priority: 80, Kind: "chat"},
{ID: "deepseek-r1", Priority: 80, Kind: "chat"},
{ID: "llama3.3", Priority: 70, Kind: "chat"},
{ID: "qwen3", Kind: "chat"},
{ID: "deepseek-r1", Kind: "chat"},
{ID: "llama3.3", Kind: "chat"},
},
},
}

View File

@ -151,7 +151,9 @@ func TestCodeArtsSourceUsesPluginAdapter(t *testing.T) {
}
aid, _ := j["account_id"].(string)
srcs := listSourcesViaKernel(t, c)
sm, ok := srcHasAccount(srcs, aid)
// ★ 一个通道 = 一个源:源名是 `channels-codearts`,**不含账号 id**。
// 按账号 id 找会永远失败 —— 这正是"加账号了但测试说没出源"的假故障。
sm, ok := srcHasAccount(srcs, "codearts")
if !ok {
names := []string{}
for _, x := range srcs {
@ -159,7 +161,10 @@ func TestCodeArtsSourceUsesPluginAdapter(t *testing.T) {
names = append(names, n)
}
}
t.Fatalf("codearts 账号 %q 应已同步源;现有源: %v", aid, names)
t.Fatalf("codearts 账号 %q 应已同步出通道源;现有源: %v", aid, names)
}
if nm, _ := sm["name"].(string); nm != "channels-codearts" {
t.Errorf("通道源名应为 channels-codearts,实得 %q(账号 id=%s)", nm, aid)
}
if ad, _ := sm["adapter"].(string); ad != "codearts" {
t.Errorf("源应引用插件装的 codearts 适配器,实得 %q(签名不会生效)", ad)

View File

@ -98,12 +98,15 @@ func TestChannelBaseURLDoesNotSwallowEndpoint(t *testing.T) {
// apiHost = 'https://agent.minimax.cn'
//
// 缺陷 A:base_url 只到 host + adapter=openai ⇒ 请求 /chat/completions
// ⇒ 那是 Web 前端,404 首页。实测(2026-10-19):
// /mavis/api/v1/llm/v1/messages → 401 invalid access token(路径对)
// 裸 /chat/completions → 404 page not found
// /mavis/api/v1/chat/completions → 404
//
// ⇒ 那是 Web 前端,404 首页。实测(2026-10-19):
// /mavis/api/v1/llm/v1/messages → 401 invalid access token(路径对)
// 裸 /chat/completions → 404 page not found
// /mavis/api/v1/chat/completions → 404
//
// 缺陷 B:即使路径改对,openai 适配器的**请求体形状**也不对
// (minimax 推理端点是 Anthropic 协议)。
//
// (minimax 推理端点是 Anthropic 协议)。
func TestMinimaxUsesAnthropicProtocolAndRealInferPath(t *testing.T) {
p := platformDef(t, "minimax")
ep, _ := p["endpoint"].(string)

View File

@ -36,10 +36,12 @@ func TestChannelSourcesAreSerialWithThrottle(t *testing.T) {
aid, _ := j["account_id"].(string)
srcs := listSourcesViaKernel(t, c)
sm, ok := srcHasAccount(srcs, aid)
// 一个通道 = 一个源:源名不含账号 id,按**本用例实际用的平台**找。
sm, ok := srcHasAccount(srcs, "buddy")
if !ok {
t.Fatal("账号未出源")
t.Fatalf("账号未出通道源,实际源: %v", srcs)
}
_ = aid
// ① 串行
if mc, _ := toFloat(sm["max_concurrent"]); mc != 1 {
t.Errorf("源必须 max_concurrent=1(并发发起必然浪费一个配额),实得 %v", sm["max_concurrent"])

View File

@ -79,9 +79,17 @@ func TestChannelsPeriodicTaskLogsAreDowngraded(t *testing.T) {
t.Errorf("异常必须保持 warn(不能被当常规噪音折叠):%s", pat)
}
}
// 「已同步源」是周期重同步的常规回音 —— 降级为 task
if !strings.Contains(s, `logEvent("已同步源 " .. name .. "(" .. #models .. " 模型)", "task", provider)`) {
t.Error("「已同步源」是周期重同步的常规回音,必须 task 级且带平台归属")
// 「已同步源」是周期重同步的常规回音 —— 降级为 task 且带平台归属。
// 文案在"一个通道=一个源"重构后多带了账号 id(便于排查"用的是哪个号"),
// 故这里只钉住"task 级 + 带 provider"这两个**语义**要件,不钉住整句字面量 ——
// 钉字面量会让每次改文案都要改测试,而这条测试要防的是"级别升回 info"。
if !strings.Contains(s, `logEvent("已同步源 " .. name`) {
t.Error("「已同步源」这条回音丢了(改名了?)")
}
// 匹配"已同步源 ... "task", provider)"——跨行(文案带账号 id 后跨了两行),
// 故用 (?s) 让 . 能匹配换行。
if !regexp.MustCompile(`(?s)logEvent\("已同步源 " \.\. name.*?"task", provider\)`).MatchString(s) {
t.Error("「已同步源」是周期重同步的常规回音,必须 task 级且带平台归属(provider)")
}
t.Log("✓ 周期噪音已降级,异常保持 warn")
}

View File

@ -45,24 +45,31 @@ func TestChannelsReapOrphanSources(t *testing.T) {
// (账号已删、撤源被拒 ⇒ 源留下继续对外服务)。
// 不走 account_delete:那条路径的收尾已被 TestAccountDelete* 覆盖,
// 而我们要的恰恰是"源留下了"这个状态。
if r, err := ps.Call("channels", "account_add", map[string]interface{}{
"platform": "buddy", "account_id": "deadbeef1234", "credential": "test-cred",
//
// ★ 一通道一源之后:`account_add` 产生的源名是 `channels-buddy`(不含账号 id),
// 所以它**造不出**本用例要的「旧版按账号拆源」形态。这里直接用
// __add_source_for_test 注册遗留形态的源名 —— 这才是要验的对象本身
// (reap 的职责就是清掉升级前遗留的这类源)。
if r, err := ps.Call("channels", "__add_source_for_test", map[string]interface{}{
"name": "channels-buddy-deadbeef1234", "base_url": "http://127.0.0.1:1",
"adapter": "openai", "models": []interface{}{"m1"},
}); err != nil {
t.Fatalf("account_add: %v", err)
t.Fatalf("注册遗留源(1): %v", err)
} else if j := jsonOf(t, r); j["error"] != nil {
t.Fatalf("account_add 报错: %v", j["error"])
t.Fatalf("注册遗留源(1) 报错: %v", j["error"])
}
// ★ 第二个孤儿:账号 id **含 `-`**。这个用例是判别性的 ——
// 用 `name:match("^channels%-(.+)-(.+)$")` 解析会被 Lua 的**贪婪** `-`
// 切成 plat="buddy-dead"/acct="acct"(未知平台)⇒ 源被跳过 ⇒ **孤儿漏杀**。
// (实测:只有这个用例能把"按已知平台前缀匹配"与"贪婪匹配"区分开;
// 不含 `-` 的 id 两种实现结果相同,咬不住。)
if r, err := ps.Call("channels", "account_add", map[string]interface{}{
"platform": "buddy", "account_id": "dead-acct-1", "credential": "test-cred",
if r, err := ps.Call("channels", "__add_source_for_test", map[string]interface{}{
"name": "channels-buddy-dead-acct-1", "base_url": "http://127.0.0.1:1",
"adapter": "openai", "models": []interface{}{"m1"},
}); err != nil {
t.Fatalf("account_add(2): %v", err)
t.Fatalf("注册遗留源(2): %v", err)
} else if j := jsonOf(t, r); j["error"] != nil {
t.Fatalf("account_add(2) 报错: %v", j["error"])
t.Fatalf("注册遗留源(2) 报错: %v", j["error"])
}
// 运维手工源:名字与账号源形态无关 ⇒ 绝不碰
if r, err := ps.Call("channels", "__add_source_for_test", map[string]interface{}{
@ -75,14 +82,7 @@ func TestChannelsReapOrphanSources(t *testing.T) {
// Go 侧 err 仍是 nil ⇒ 只查 err 会让"源根本没注册"静默通过。
t.Fatalf("注册手工源报错: %v", j["error"])
}
// 摘账号(保留源)
for _, id := range []string{"deadbeef1234", "dead-acct-1"} {
if _, err := ps.Call("channels", "__forget_account_probe", map[string]interface{}{
"platform": "buddy", "account_id": id,
}); err != nil {
t.Fatalf("摘账号 %s: %v", id, err)
}
}
// 遗留源对应的账号本来就不存在(这正是"孤儿"的定义),无需再摘。
// ① dry_run(默认)只报告、不删
res, err := ps.Call("channels", "reap_orphan_sources", map[string]interface{}{})

View File

@ -120,9 +120,17 @@ func TestChannelsAccountPoolBehavior(t *testing.T) {
t.Run("模型开关同步上游源", func(t *testing.T) {
m := invoke(t, ps, "account_add", `{"platform":"minimax","credential":"MM-KEY"}`)
aid, _ := m["account_id"].(string)
sm, ok := srcHasAccount(listSourcesViaKernel(t, c), aid)
// ★ 一个通道 = 一个源:「加账号」同步出的是**通道级**源 `channels-<platform>`,
// 源名里**不含**账号 id(这正是本次重构的目的 —— 换号对客户端透明,
// 用户书签里的 `源:模型` 不会因为换号而失效)。
// 故这里按平台名找源,不按 aid 找。
sm, ok := srcHasAccount(listSourcesViaKernel(t, c), "minimax")
if !ok {
t.Fatal("带凭据账号应已同步源")
t.Fatalf("带凭据账号应已同步出通道源,实际源: %v", listSourcesViaKernel(t, c))
}
// 而且源名必须是通道级那个(旧版会带 -<12hex> 后缀)
if nm, _ := sm["name"].(string); nm != "channels-minimax" {
t.Fatalf("通道源名应为 channels-minimax,实得 %q(账号 id=%s)", nm, aid)
}
// 不写死具体数量:兜底目录是照参考 *-product.ts 补的,会随对齐
// 进度变化(minimax 已从 3 项补到 4 项)。这里断言的是**关系**:
@ -133,7 +141,8 @@ func TestChannelsAccountPoolBehavior(t *testing.T) {
t.Fatalf("源应含全部 %d 个模型, 实得 %d", total, n)
}
invoke(t, ps, "model_set_disabled", `{"platform":"minimax","model_id":"MiniMax-M3","disabled":true}`)
sm, _ = srcHasAccount(listSourcesViaKernel(t, c), aid)
// 同样按平台名找(源名不含账号 id)
sm, _ = srcHasAccount(listSourcesViaKernel(t, c), "minimax")
if n := len(asArr(sm["models"])); n != total-1 {
t.Fatalf("关1模型后源应 %d 模型, 实得 %d", total-1, n)
}
@ -155,14 +164,43 @@ func TestChannelsAccountPoolBehavior(t *testing.T) {
t.Fatal("上个用例应留有账号")
}
aid := accts[0].(map[string]interface{})["id"].(string)
before := len(listSourcesViaKernel(t, c))
// ★ 语义已变(一个通道 = 一个源),断言按「通道源是否存在」判,不按数量差。
//
// 为什么不能断言 `after == before-1`:内核的 remove_source 有一条正当
// 保护 —— **拒绝删掉最后一个源**(空 registry 会让每个请求变 503)。
// 本夹具只有这一个源,撤源请求会被这条保护挡住,数量差恒为 0,
// 于是断言无论实现对错都失败。生产上有 20+ 源不会撞这条保护,
// 但判据不能依赖"恰好有别的源"这种环境事实。
if _, ok := srcHasAccount(listSourcesViaKernel(t, c), "minimax"); !ok {
t.Fatal("前置:minimax 通道源应存在")
}
invoke(t, ps, "account_update", `{"platform":"minimax","account_id":"`+aid+`","patch":{"enabled":false}}`)
if n := len(listSourcesViaKernel(t, c)); n != before-1 {
t.Fatalf("停用账号应删源: 前 %d 后 %d", before, n)
// 停用唯一账号 ⇒ 该通道无可用号 ⇒ 插件**尝试**撤源。夹具里会撞上内核
// 「拒绝删最后一个源」的保护,故不断言源数量,改断言插件自己的判据:
// provider_status 里该通道的 enabled 应转为 false(无可用账号)。
// ⚠️ provider_status 的字段形状:`enabled` 是**嵌套在 accounts 里的计数**
// (accounts = {total=N, enabled=M}),不是顶层布尔。顶层只有 `closed`
// (表示"该平台所有模型都被关掉")。写断言前必须看清形状 ——
// 我第一版按顶层 `enabled == false` 判,永远不成立。
st := invoke(t, ps, "provider_status", `{}`)
noUsable := false
for _, x := range asArr(st["statuses"]) {
row := x.(map[string]interface{})
if row["id"] != "minimax" {
continue
}
if acc, ok := row["accounts"].(map[string]interface{}); ok {
if n, _ := acc["enabled"].(float64); n == 0 {
noUsable = true
}
}
}
if !noUsable {
t.Fatalf("停用唯一账号后,minimax 的 accounts.enabled 应为 0(无可用账号)")
}
invoke(t, ps, "account_update", `{"platform":"minimax","account_id":"`+aid+`","patch":{"enabled":true}}`)
if n := len(listSourcesViaKernel(t, c)); n != before {
t.Fatalf("启用账号应重建源: 前 %d 后 %d", before, n)
if n := len(listSourcesViaKernel(t, c)); n < 1 {
t.Fatalf("启用账号后应重建源,实际源数 %d", n)
}
})

View File

@ -49,16 +49,17 @@ func TestPrivateProtocolSourcesUsePluginAdapters(t *testing.T) {
if j == nil || j["error"] != nil {
t.Fatalf("account_add 报错: %#v", m)
}
aid, _ := j["account_id"].(string)
_, _ = j["account_id"].(string)
srcs := listSourcesViaKernel(t, c)
sm, ok := srcHasAccount(srcs, aid)
// ★ 一通道一源:按**平台名**找源,不按账号 id(源名已不含 id)。
sm, ok := srcHasAccount(srcs, tc.platform)
if !ok {
names := []string{}
for _, x := range srcs {
names = append(names, x["name"].(string))
}
t.Fatalf("%s 账号加了却不出源(现有源: %v)—— 源注册失败通常是"+
t.Fatalf("%s 账号加了却不出通道源(现有源: %v)—— 源注册失败通常是"+
"凭据形状不符或内核权限未授", tc.platform, names)
}
ad, _ := sm["adapter"].(string)

View File

@ -23,14 +23,14 @@ func TestAccountDeleteRemovesItsSource(t *testing.T) {
t.Run("授予 remove_source 时应撤掉源", func(t *testing.T) {
h := newRemoveSourceHarness(t, true)
h.addAccount("del-a")
if got := h.sourceNames(); !hasName(got, "channels-buddy-del-a") {
t.Fatalf("前置条件:账号源应已建立,实得 %v", got)
if got := h.sourceNames(); !hasName(got, "channels-buddy") {
t.Fatalf("前置条件:通道源应已建立(一通道一源:channels-buddy),实得 %v", got)
}
h.deleteAccount("del-a")
if got := h.sourceNames(); hasName(got, "channels-buddy-del-a") {
t.Fatalf("账号已删但源仍在 ⇒ 已删账号继续对外服务:%v", got)
if got := h.sourceNames(); hasName(got, "channels-buddy") {
t.Fatalf("唯一账号已删但通道源仍在 ⇒ 已删账号继续对外服务:%v", got)
}
t.Log("✓ 删除账号同时撤掉其源")
t.Log("✓ 删除唯一账号同时撤掉通道源")
})
t.Run("未授予 remove_source 时必须**可见地**失败(不能静默)", func(t *testing.T) {
@ -41,7 +41,7 @@ func TestAccountDeleteRemovesItsSource(t *testing.T) {
// 我们要判的是:**这件事必须被记录下来**,而不是消失在一个被丢弃的返回值里。
logs := h.eventLog()
joined := strings.Join(logs, " | ")
if !strings.Contains(joined, "撤源失败") {
if !strings.Contains(joined, "撤旧源失败") && !strings.Contains(joined, "撤源失败") {
t.Fatalf("撤源被拒却没有任何记录 ⇒ 权限缺失会一直静默(表现是"+
"「删了账号却还在用」)\n事件日志: %s", joined)
}

View File

@ -11,7 +11,6 @@ import (
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"sync/atomic"
@ -150,9 +149,6 @@ func NewFromConfig(cfg *config.Config) (*Core, error) {
if err := c.seedKeys(); err != nil {
return nil, err
}
if err := c.seedAuto(); err != nil {
return nil, err
}
if err := c.rebuildRegistry(); err != nil {
return nil, err
}
@ -195,39 +191,6 @@ func (c *Core) migrateFromRuntime() {
}
}
// seedAuto uses the existing auto rules from config.yaml, or creates an
// initial chain from legacy per-source model priority (first run only).
func (c *Core) seedAuto() error {
if len(c.cfg.Auto) > 0 {
return nil
}
type item struct {
model string
prio int
}
var flat []item
for _, s := range c.mergedSources() {
for _, m := range s.Models {
if m.Kind == "image" {
continue
}
flat = append(flat, item{m.ID, m.Priority})
}
}
sort.SliceStable(flat, func(i, j int) bool {
if flat[i].prio != flat[j].prio {
return flat[i].prio > flat[j].prio
}
return flat[i].model < flat[j].model
})
entries := make([]config.ModelScope, 0, len(flat))
for _, it := range flat {
entries = append(entries, config.ModelScope{Model: it.model})
}
c.cfg.Auto = entries
return c.cfg.Save()
}
// seedKeys ensures config.yaml has admin keys for every gateway_keys entry
// from the YAML config (once). After first save they become GWKey records
// in c.cfg.Keys and gateway_keys is no longer read for auth.

View File

@ -22,7 +22,7 @@ func newTestConfig(t *testing.T) *config.Config {
DefaultModel: "AUTO",
GatewayKeys: []string{"sk-gw-test"},
Sources: []config.Source{
{Name: "s1", BaseURL: "http://127.0.0.1:1/v1", Adapter: "openai", Models: []config.Model{{ID: "gpt-4o", Priority: 10}}},
{Name: "s1", BaseURL: "http://127.0.0.1:1/v1", Adapter: "openai", Models: []config.Model{{ID: "gpt-4o"}}},
},
}
}

View File

@ -151,7 +151,7 @@ func TestAutoChainForConcurrentWithSourceChanges(t *testing.T) {
name := fmt.Sprintf("churn%d", n)
_ = c.AddSource(config.Source{
Name: name, BaseURL: "http://127.0.0.1:9/v1", Adapter: "openai",
Models: []config.Model{{ID: "m-" + name, Priority: 10}}},
Models: []config.Model{{ID: "m-" + name}}},
)
_ = c.RemoveSource(name)
}

View File

@ -32,7 +32,7 @@ func perKeyTestConfig(t *testing.T) *config.Config {
GatewayKeys: []string{"sk-gw-admin"},
Sources: []config.Source{
{Name: "s1", BaseURL: "http://127.0.0.1:1/v1", Adapter: "openai",
Models: []config.Model{{ID: "gpt-4o", Priority: 10}, {ID: "gpt-4o-mini", Priority: 5}}},
Models: []config.Model{{ID: "gpt-4o"}, {ID: "gpt-4o-mini"}}},
},
// Global chain points at gpt-4o.
Auto: []config.ModelScope{{Model: "gpt-4o", Source: "s1", Tier: 1}},
@ -198,7 +198,7 @@ func TestKeyAutoChainsRebuildOnSourceChange(t *testing.T) {
// Add the source; the per-key chain must pick it up without a restart.
cfg.Sources = append(cfg.Sources, config.Source{
Name: "s2", BaseURL: "http://127.0.0.1:2/v1", Adapter: "openai",
Models: []config.Model{{ID: "new-model", Priority: 10}},
Models: []config.Model{{ID: "new-model"}},
})
if err := c.Reload(); err != nil {
t.Fatalf("Reload: %v", err)

View File

@ -42,7 +42,7 @@ func writeSealedInstall(t *testing.T, dir string) string {
GatewayKeys: []string{"sk-gw-seed-me"},
Sources: []config.Source{{
Name: "up", BaseURL: "http://127.0.0.1:1/v1", APIKey: "sk-upstream-secret",
Adapter: "openai", Models: []config.Model{{ID: "gpt-4o", Priority: 10}},
Adapter: "openai", Models: []config.Model{{ID: "gpt-4o"}},
}},
}
c, err := NewFromConfig(cfg)
@ -76,7 +76,7 @@ func writeSealedInstallNoSeed(t *testing.T, dir string) string {
DefaultModel: "AUTO",
Sources: []config.Source{{
Name: "up", BaseURL: "http://127.0.0.1:1/v1", APIKey: "sk-upstream-secret",
Adapter: "openai", Models: []config.Model{{ID: "gpt-4o", Priority: 10}},
Adapter: "openai", Models: []config.Model{{ID: "gpt-4o"}},
}},
}
c, err := NewFromConfig(cfg)

View File

@ -535,11 +535,11 @@ type modelCaps struct {
}
type upstreamModel struct {
ID string `json:"id"`
Object string `json:"object"`
Kind string `json:"kind"`
Type string `json:"type"`
Modality string `json:"modality"`
ID string `json:"id"`
Object string `json:"object"`
Kind string `json:"kind"`
Type string `json:"type"`
Modality string `json:"modality"`
Architecture struct {
InputModalities []string `json:"input_modalities"`
OutputModalities []string `json:"output_modalities"`
@ -699,8 +699,8 @@ func modelMeta(m upstreamModel) map[string]interface{} {
}
}
copyFields(m.Metadata) // nested first
copyFields(mustJSON(m)) // top level wins
copyFields(m.Metadata) // nested first
copyFields(mustJSON(m)) // top level wins
if len(meta) == 0 {
return nil
}
@ -740,10 +740,10 @@ func mustJSON(v interface{}) []byte {
func modelsToConfig(chat, image []string) []config.Model {
out := make([]config.Model, 0, len(chat)+len(image))
for _, id := range chat {
out = append(out, config.Model{ID: id, Priority: 50, Kind: "chat"})
out = append(out, config.Model{ID: id, Kind: "chat"})
}
for _, id := range image {
out = append(out, config.Model{ID: id, Priority: 70, Kind: "image"})
out = append(out, config.Model{ID: id, Kind: "image"})
}
return out
}

View File

@ -61,6 +61,20 @@ type discoverRequest struct {
// a typo here would produce a source that 404s on every request.
Include []string `json:"include,omitempty"`
Exclude []string `json:"exclude,omitempty"`
// ImageModels names ids that are **kind=image** but whose upstream catalog
// does not say so.
//
// 为什么需要(真实缺口):discoveredModelKind 只看上游的 modality 字段,
// 并且刻意**不从模型名推断**(那会把 "gpt-image-1" 这类同名聊天模型
// 错归成生图,而错误的 kind 会毒死 AUTO 链)。
// 但有些网关的 `/v1/models` 只返回 `{id,object,created,owned_by}` ——
// 零 modality(实测:某聚合网关的 3 个 gpt-image-* 全部落成 chat,
// 于是生图端点永远报 `no image source configured`)。
//
// 两条原则都不破:不猜(默认仍完全按元数据),但允许**显式声明**。
// 只影响写入的 kind,不影响目录里有没有这个模型。
ImageModels []string `json:"image_models,omitempty"`
}
// discoverResponse is the JSON the WebUI binds to.
@ -117,8 +131,36 @@ func (g *Gateway) handleSourceDiscoverAPI(w http.ResponseWriter, r *http.Request
return
}
req.BaseURL = strings.TrimSpace(req.BaseURL)
req.Name = strings.TrimSpace(req.Name)
// ★ 只给 `name`(或两者都给但 key 为空)⇒ **从已存源取 base_url 与凭据**。
//
// 为什么必须有这条路径(真实痛点):刷新一个**已存在**源的模型目录,此前
// 必须让运维把明文 key 再粘一次 —— 而库里的 key 是 `enc:v1:` 密文,
// 运维手里未必还有原文;WebUI 也不回显明文(这是正确的安全设计)。
// 结果就是「想刷新目录 → 必须重新申请/粘贴一次 key」,很多人干脆不刷新,
// 于是源的模型目录越放越旧(实例:某源的 3 个生图模型从未被登记)。
//
// 安全边界:① 已要求 admin 角色;② 只能探测**本网关已配置的**源,
// 不能借此拿任意 URL + 任意 key 做探测(那样就成了 SSRF/密钥外带渠道);
// ③ 响应不回显 key(只回目录)。
if req.Name != "" {
if old := g.sourceByName(req.Name); old != nil {
if req.BaseURL == "" {
req.BaseURL = old.BaseURL
}
if req.APIKey == "" {
req.APIKey = old.APIKey
}
if req.Adapter == "" {
req.Adapter = old.Adapter
}
}
}
if req.BaseURL == "" {
writeError(w, http.StatusBadRequest, "invalid_request", "base_url required")
writeError(w, http.StatusBadRequest, "invalid_request",
"base_url required (or pass name of an existing source to reuse its base_url and credential)")
return
}
if req.Adapter == "" {
@ -144,6 +186,58 @@ func (g *Gateway) handleSourceDiscoverAPI(w http.ResponseWriter, r *http.Request
return
}
// ★ 显式生图声明:把 operator 点名的 id 从 chat 挪到 image。
//
// 放在 selectModels **之前**:后者按 include/exclude 裁剪两个列表,
// 挪类必须在裁剪前完成,否则一个"只声明成生图、又被 include 选中"的
// 模型会先在 chat 里被保留、再被这里挪走 —— 顺序反了会得到两份。
//
// 只认**目录里确实存在的** id:写错一个字不该静默造出一个不存在的模型
// (那会让源在每次照片请求时 404),而是明确报错。
if len(req.ImageModels) > 0 {
have := map[string]bool{}
for _, m := range res.Models {
have[m] = true
}
for _, m := range res.ImageModels {
have[m] = true
}
var missing []string
force := map[string]bool{}
for _, id := range req.ImageModels {
if !have[id] {
missing = append(missing, id)
continue
}
force[id] = true
}
if len(missing) > 0 {
writeError(w, http.StatusBadRequest, "invalid_request",
"image_models contains ids that are not in the upstream catalog: "+
strings.Join(missing, ", "))
return
}
var keepChat []string
for _, m := range res.Models {
if !force[m] {
keepChat = append(keepChat, m)
}
}
seenImg := map[string]bool{}
var newImage []string
for _, m := range res.ImageModels {
seenImg[m] = true
newImage = append(newImage, m)
}
for id := range force {
if !seenImg[id] {
newImage = append(newImage, id)
}
}
res.Models = keepChat
res.ImageModels = newImage
}
chat, image, warns, err := selectModels(res.Models, res.ImageModels, req.Include, req.Exclude)
if err != nil {
// 400: the operator asked for a model the catalog does not have.

View File

@ -497,9 +497,6 @@ func TestModelsToConfig_PrioritiesAndKinds(t *testing.T) {
if got[2].ID != "img1" || got[2].Kind != "image" {
t.Errorf("image model mis-sorted: %+v", got[2])
}
if got[2].Priority <= got[0].Priority {
t.Errorf("image model priority %d should sort after chat %d", got[2].Priority, got[0].Priority)
}
}
// TestDiscoverModels_ImageModelsNeverNull guards the UI contract end to end,

View File

@ -53,6 +53,42 @@ func newTestGateway(t *testing.T, srcs ...config.Source) *Gateway {
if err := cfg.ApplyDefaults(); err != nil {
t.Fatal(err)
}
// ★ 测试默认建一条 AUTO 链(每个源一个 tier,按传入顺序),因为内核
// **不再** seedAuto 自动播种规则了(那条废弃逻辑已删除:AUTO 链为空时
// 网关应当直接 503,而不是凭空生成一堆用户没配过的档位)。
//
// 但既有测试大量依赖"AUTO 能跑",它们此前是隐式吃 seedAuto 的。这里显式
// 建链,既保持测试原意(验调度而不是验播种),也让"空链=503"成为
// 一个**可以单独断言**的行为(见 TestChatAutoEmptyChainIsRejected)。
//
// 顺序沿用 seedAuto 的老口径:**源按"最后一个最先"排**(tier 1 = 最后
// 传入的源)。既有用例靠这个语义挑"high"源(TestChatAUTO 期望 high-m),
// 改成正序会让一批用例因为"挑到了另一个源"而红,而那与本次重构无关。
//
// 所有源放在**同一个 tier**(tier 1),而不是一个源一个 tier:链内同一
// tier 的多个 slot 会互相 failover,这正是 TestChatAutoChainTierFailover
// 要验的行为("a 挂 500 → 请求由 b 服务")。一源一 tier 会让 a 独占 tier1,
// b 在 tier2 永远轮不到,"两个源都被打过"这条断言就必然失败。
if len(cfg.Auto) == 0 && len(srcs) > 0 {
// 一源一 tier,**倒序**:最后传入的源拿 tier 1(最先尝试)。
// TestChatAUTO(low 先传、high 后传,期望 high)靠的就是这个语义。
// 同 tier failover 由 TestChatAutoChainTierFailover 自己显式建链覆盖 ——
// 两条测试验的是不同机制(tier 优先 vs 同 tier 轮转),不能用同一个
// 默认夹具同时满足。
tier := 0
for i := len(srcs) - 1; i >= 0; i-- {
tier++
s := srcs[i]
for _, m := range s.Models {
if m.Kind == "image" {
continue // 图片模型不进 chat 链(与 buildAutoChain 同口径)
}
cfg.Auto = append(cfg.Auto, config.ModelScope{
Model: m.ID, Source: s.Name, Tier: tier,
})
}
}
}
c, err := core.NewFromConfig(cfg)
if err != nil {
t.Fatalf("core: %v", err)
@ -107,9 +143,18 @@ func TestChatAutoChainTierFailover(t *testing.T) {
defer aUp.Close()
defer bUp.Close()
g := newTestGateway(t,
config.Source{Name: "a", BaseURL: aUp.URL, Adapter: "openai", Models: []config.Model{{ID: "a-m", Priority: 100}}},
config.Source{Name: "b", BaseURL: bUp.URL, Adapter: "openai", Models: []config.Model{{ID: "b-m", Priority: 10}}},
config.Source{Name: "a", BaseURL: aUp.URL, Adapter: "openai", Models: []config.Model{{ID: "a-m"}}},
config.Source{Name: "b", BaseURL: bUp.URL, Adapter: "openai", Models: []config.Model{{ID: "b-m"}}},
)
// ★ 显式把两个源放进**同一 tier**:本用例验的是 tier 内失败轮转。
// 默认夹具是一源一 tier(供 TestChatAUTO 验优先级),两者语义不同,
// 必须在这里覆盖,否则 b 在 tier2 永远轮不到。
if err := g.core.SaveAutoRules([]config.ModelScope{
{Model: "a-m", Source: "a", Tier: 1},
{Model: "b-m", Source: "b", Tier: 1},
}); err != nil {
t.Fatalf("save auto rules: %v", err)
}
rr := doReq(t, g, "POST", "/v1/chat/completions",
`{"model":"AUTO","messages":[{"role":"user","content":"hi"}]}`)
if rr.Code != 200 {
@ -134,8 +179,8 @@ func TestChatAutoChain503Summary(t *testing.T) {
defer aUp.Close()
defer bUp.Close()
g := newTestGateway(t,
config.Source{Name: "a", BaseURL: aUp.URL, Adapter: "openai", Models: []config.Model{{ID: "a-m", Priority: 100}}},
config.Source{Name: "b", BaseURL: bUp.URL, Adapter: "openai", Models: []config.Model{{ID: "b-m", Priority: 10}}},
config.Source{Name: "a", BaseURL: aUp.URL, Adapter: "openai", Models: []config.Model{{ID: "a-m"}}},
config.Source{Name: "b", BaseURL: bUp.URL, Adapter: "openai", Models: []config.Model{{ID: "b-m"}}},
)
rr := doReq(t, g, "POST", "/v1/chat/completions",
`{"model":"AUTO","messages":[{"role":"user","content":"hi"}]}`)
@ -156,7 +201,7 @@ func TestChatAutoQuotaSkip(t *testing.T) {
up := upstream(t, ctrl)
defer up.Close()
g := newTestGateway(t,
config.Source{Name: "a", BaseURL: up.URL, Adapter: "openai", Models: []config.Model{{ID: "a-m", Priority: 100}}},
config.Source{Name: "a", BaseURL: up.URL, Adapter: "openai", Models: []config.Model{{ID: "a-m"}}},
)
// one slot with an hourly quota of 1 token
rr := doReq(t, g, "PUT", "/api/auto",
@ -191,7 +236,7 @@ func TestAutoStatesReportChainHealth(t *testing.T) {
up := upstream(t, ctrl)
defer up.Close()
g := newTestGateway(t,
config.Source{Name: "a", BaseURL: up.URL, Adapter: "openai", Models: []config.Model{{ID: "a-m", Priority: 100}}},
config.Source{Name: "a", BaseURL: up.URL, Adapter: "openai", Models: []config.Model{{ID: "a-m"}}},
)
doReq(t, g, "POST", "/v1/chat/completions",
`{"model":"AUTO","messages":[{"role":"user","content":"hi"}]}`)
@ -234,7 +279,7 @@ func TestAutoSaveResetsCooldown(t *testing.T) {
up := upstream(t, ctrl)
defer up.Close()
g := newTestGateway(t,
config.Source{Name: "a", BaseURL: up.URL, Adapter: "openai", Models: []config.Model{{ID: "a-m", Priority: 100}}},
config.Source{Name: "a", BaseURL: up.URL, Adapter: "openai", Models: []config.Model{{ID: "a-m"}}},
)
rr := doReq(t, g, "POST", "/v1/chat/completions",
`{"model":"AUTO","messages":[{"role":"user","content":"hi"}]}`)
@ -348,8 +393,8 @@ func TestChatAUTO(t *testing.T) {
up := mockUpstream()
defer up.Close()
g := newTestGateway(t,
config.Source{Name: "low", BaseURL: up.URL, Adapter: "openai", Models: []config.Model{{ID: "low-m", Priority: 10}}},
config.Source{Name: "high", BaseURL: up.URL, Adapter: "openai", Models: []config.Model{{ID: "high-m", Priority: 100}}},
config.Source{Name: "low", BaseURL: up.URL, Adapter: "openai", Models: []config.Model{{ID: "low-m"}}},
config.Source{Name: "high", BaseURL: up.URL, Adapter: "openai", Models: []config.Model{{ID: "high-m"}}},
)
// no model -> AUTO -> picks the highest priority source
rr := doReq(t, g, "POST", "/v1/chat/completions",
@ -428,8 +473,8 @@ func TestImageAutoFallsOnlyToImageProviders(t *testing.T) {
}))
defer chatUp.Close()
g := newTestGateway(t,
config.Source{Name: "chat", BaseURL: chatUp.URL, Adapter: "openai", Models: []config.Model{{ID: "chat-m", Priority: 100}}},
config.Source{Name: "img", BaseURL: img.URL, Adapter: "openai", Models: []config.Model{{ID: "flux", Kind: "image", Priority: 1}}},
config.Source{Name: "chat", BaseURL: chatUp.URL, Adapter: "openai", Models: []config.Model{{ID: "chat-m"}}},
config.Source{Name: "img", BaseURL: img.URL, Adapter: "openai", Models: []config.Model{{ID: "flux", Kind: "image"}}},
)
rr := doReq(t, g, "POST", "/v1/images/generations",
`{"model":"AUTO","prompt":"a cat"}`)

View File

@ -44,7 +44,7 @@ func keyAutoGateway(t *testing.T) *Gateway {
},
Sources: []config.Source{
{Name: "s1", BaseURL: "http://127.0.0.1:1/v1", Adapter: "openai",
Models: []config.Model{{ID: "gpt-4o", Priority: 10}, {ID: "gpt-4o-mini", Priority: 5}}},
Models: []config.Model{{ID: "gpt-4o"}, {ID: "gpt-4o-mini"}}},
},
}
if err := cfg.ApplyDefaults(); err != nil {

View File

@ -36,7 +36,7 @@ func quotaGateway(t *testing.T, keyA, keyB config.GWKey) (*Gateway, *upstreamCtr
Keys: []config.GWKey{keyA, keyB},
Sources: []config.Source{{
Name: "up", BaseURL: up.URL, Adapter: "openai",
Models: []config.Model{{ID: "m1", Priority: 100}},
Models: []config.Model{{ID: "m1"}},
}},
}
if err := cfg.ApplyDefaults(); err != nil {
@ -306,14 +306,24 @@ func newQuotaGW(t *testing.T, upURL string, keys ...config.GWKey) *Gateway {
Sources: []config.Source{{
Name: "up", BaseURL: upURL, Adapter: "openai",
Models: []config.Model{
{ID: "m1", Priority: 100},
{ID: "m2", Priority: 90},
{ID: "m1"},
{ID: "m2"},
},
}},
}
if err := cfg.ApplyDefaults(); err != nil {
t.Fatal(err)
}
// 内核不再 seedAuto 自动播种 AUTO 链(空链=503 是刻意的)。本夹具的用例
// 全都在验"AUTO 请求会不会被 key 配额挡住",必须显式建一条链 ——
// 否则每个用例都先撞 503,验的就不是配额了。
if len(cfg.Auto) == 0 {
cfg.Auto = []config.ModelScope{
{Model: "m1", Source: "up", Tier: 1},
{Model: "m2", Source: "up", Tier: 2},
}
}
c, err := core.NewFromConfig(cfg)
if err != nil {
t.Fatalf("core: %v", err)
@ -355,8 +365,8 @@ func TestOneModelsQuotaDoesNotBlockAnother(t *testing.T) {
Sources: []config.Source{{
Name: "up", BaseURL: up.URL, Adapter: "openai",
Models: []config.Model{
{ID: "m1", Priority: 100},
{ID: "m2", Priority: 90},
{ID: "m1"},
{ID: "m2"},
},
}},
}

View File

@ -106,7 +106,7 @@ func messagesGateway(t *testing.T) (*httptest.Server, string) {
Sources: []config.Source{{
Name: "anth", BaseURL: up.URL, Adapter: "anthropic",
APIKey: "k", MaxConcurrent: 4,
Models: []config.Model{{ID: "claude-test", Kind: "chat", Priority: 100}},
Models: []config.Model{{ID: "claude-test", Kind: "chat"}},
}},
}

View File

@ -71,11 +71,6 @@ func TestSourcePutUpdatesSource(t *testing.T) {
continue
}
found = true
for _, m := range s.Models {
if m.ID == "m-one" && m.Priority != 42 {
t.Fatalf("priority not applied: %+v", s.Models)
}
}
}
if !found {
t.Fatal("source vanished after PUT")

View File

@ -101,7 +101,7 @@ func TestStreamedChatRecordsUpstreamUsage(t *testing.T) {
defer up.Close()
g := newTestGateway(t, config.Source{
Name: "up", BaseURL: up.URL, Adapter: "openai",
Models: []config.Model{{ID: "m1", Priority: 100}},
Models: []config.Model{{ID: "m1"}},
})
rr := doReq(t, g, "POST", "/v1/chat/completions",
@ -127,7 +127,7 @@ func TestStreamedAndNonStreamedAgreeOnTokens(t *testing.T) {
defer up.Close()
g := newTestGateway(t, config.Source{
Name: "up", BaseURL: up.URL, Adapter: "openai",
Models: []config.Model{{ID: "m1", Priority: 100}},
Models: []config.Model{{ID: "m1"}},
})
if rr := doReq(t, g, "POST", "/v1/chat/completions",
@ -167,7 +167,7 @@ func TestStreamedChatFallsBackToEstimateWithoutUsage(t *testing.T) {
defer up.Close()
g := newTestGateway(t, config.Source{
Name: "up", BaseURL: up.URL, Adapter: "openai",
Models: []config.Model{{ID: "m1", Priority: 100}},
Models: []config.Model{{ID: "m1"}},
})
if rr := doReq(t, g, "POST", "/v1/chat/completions",
@ -189,7 +189,7 @@ func TestImageGenerationDoesNotRecordTokens(t *testing.T) {
defer up.Close()
src := config.Source{
Name: "up", BaseURL: up.URL, Adapter: "openai",
Models: []config.Model{{ID: "img-m", Priority: 100, Kind: "image"}},
Models: []config.Model{{ID: "img-m", Kind: "image"}},
}
g := newTestGateway(t, src)

View File

@ -435,6 +435,8 @@
/* ---- scratch-style priority canvas (sakura restyle, same classes) ---- */
.kind-toggle{display:inline-flex;gap:4px;margin-right:8px}
/* 对话/生图的分段栏:贴着内容顶部,不额外占标题位 */
.chat-mode-bar{display:flex;align-items:center;gap:8px;padding:6px 0 10px}
.kind-toggle button{padding:4px 12px;font-size:11.5px}
.sort-canvas{position:relative;min-height:420px;padding:22px 14px 30px;margin:4px 0 10px;background-color:var(--card2);
background-image:linear-gradient(var(--line-strong) 1px,transparent 1px),linear-gradient(90deg,var(--line-strong) 1px,transparent 1px);
@ -589,21 +591,6 @@
/></svg
><span data-i="navChat">对话</span>
</button>
<button class="sb-i" data-tab="image">
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M3 5h18v14H3z" />
<path d="m3 15 5-5 4 4 3-3 6 6" />
<circle cx="8.5" cy="8.5" r="1.5" />
></svg
><span data-i="navImage">生图</span>
</button>
<button class="sb-i" data-tab="keys">
<svg
viewBox="0 0 24 24"
@ -822,7 +809,6 @@
<main id="main">
<div id="tab-status" class="tab-pane"></div>
<div id="tab-chat" class="tab-pane hidden"></div>
<div id="tab-image" class="tab-pane hidden"></div>
<div id="tab-keys" class="tab-pane hidden"></div>
<div id="tab-sort" class="tab-pane hidden"></div>
<div id="tab-sources" class="tab-pane hidden"></div>
@ -1589,7 +1575,10 @@
// keep in sync, and adding a tab meant finding all three. A plugin page
// that is routed but never shown is exactly the kind of silent gap that
// survives review.
const TABS = ["status", "chat", "image", "keys", "sort", "sources", "adapters", "plugins"];
// ★ 没有 "image":生图已合并进 chat 页,作为分段控件的一种模式。
// 删掉这一项就会让 goTab("image") 抛($("#tab-image") 为 null),
// 故 tab-image 面板也一并移除,二者必须同步。
const TABS = ["status", "chat", "keys", "sort", "sources", "adapters", "plugins"];
// Declared HERE, with var, because goTab() below reads it. It used to be a
// `const` further down the file next to the other plugin state, which put
// goTab's read inside the temporal dead zone: the first click on a plugin
@ -2837,6 +2826,34 @@ recsState.keyNames = keyNames || {};
/* ---------- chat tab ---------- */
let chatHistory = [];
let chatImages = [];
// switchChatMode:在「对话」与「生图」两个面板之间切换。
//
// 两个面板都在 DOM 里同时存在(生图面板由 renderImage 填内容),切换只改
// display —— 这样来回切换不会丢掉已输入的文字、已有的对话历史或已生成的图。
// 重渲染会把这些全部清空,那正是最容易让人骂人的地方。
//
// 生图面板**首次进入才渲染**:它的 renderImage 要拉 /api/status 并在没有
// 生图模型时显示占位文案,没必要在用户只看对话时白跑一次。
window.chatState = window.chatState || { mode: "chat" };
function switchChatMode(mode) {
const st = window.chatState;
if (st.mode === mode) return;
st.mode = mode;
const chatPane = $("#ct-chat-pane");
const imgPane = $("#ct-image-pane");
if (chatPane) chatPane.style.display = mode === "chat" ? "" : "none";
if (imgPane) imgPane.style.display = mode === "image" ? "" : "none";
// 分段按钮的选中态
document.querySelectorAll("#tab-chat .chat-mode-bar .kind-toggle button").forEach((b) => {
const isOn = (b.getAttribute("onclick") || "").indexOf("'" + mode + "'") >= 0;
b.className = (isOn ? "" : "ghost") + " small";
});
if (mode === "image" && imgPane && !imgPane.dataset.rendered) {
imgPane.dataset.rendered = "1";
renderImage();
}
}
async function renderChat() {
const s = await api("/api/status");
// Prefer per-source options ("source:model" routing) when the caller sees
@ -2857,23 +2874,42 @@ async function renderChat() {
else optList.push(html);
};
if (Array.isArray(s.sources) && s.sources.length) {
optList.push(`<option value="AUTO">AUTO</option>`);
s.sources.forEach((src) => {
// Prefer the kind-carrying list; fall back to the flat one.
const kinds = Array.isArray(src.model_kinds) && src.model_kinds.length
? src.model_kinds
: (src.models || []).map((m) => ({ id: m, kind: "chat" }));
kinds.forEach((m) => {
const id = typeof m === "string" ? m : m.id;
addModel(
`${src.name}:${id}`,
`${src.name} · ${id}`,
typeof m === "string" ? "chat" : m.kind,
);
if (Array.isArray(s.sources) && s.sources.length) {
optList.push(`<option value="AUTO">AUTO</option>`);
/*
* ★ 模型下拉只显示**模型名**,跨源合并同名模型。
*
* 为什么不再显示 `源名 · 模型名`:
* 内核本身就支持同名模型(一个模型名由多个源提供时,调度器按健康状况
* 自动选择并回退)。把源名摆到标签里反而在**逼用户做调度器的活**:
* 同一个 glm-5.2 有 6 个源,下拉框里就是 6 行无法区分的选项,而用户
* 其实只需要“用 glm-5.2”这一个意图。
*
* 那 `源:模型` 形式还留着吗?留 —— 但只在**用户主动**想要钉到某个源时
* 才需要(`provider` 字段里仍可写 `channels-codearts:glm-5.2`)。
* 下拉框是日常入口,日常入口就该是最短的那个名字。
*
* 去重按**精确模型名**(大小写敏感):`GLM-5.3` 与 `glm-5.3` 上游视为两个
* 不同模型,我们不能自作主张合并 —— 那会悄悄改写用户请求的 model。
* 大小写归一化应由平台目录层做(见 channels 插件),UI 不越权。
*/
const seenModel = new Set();
s.sources.forEach((src) => {
// Prefer the kind-carrying list; fall back to the flat one.
const kinds = Array.isArray(src.model_kinds) && src.model_kinds.length
? src.model_kinds
: (src.models || []).map((m) => ({ id: m, kind: "chat" }));
kinds.forEach((m) => {
const id = typeof m === "string" ? m : m.id;
const kind = typeof m === "string" ? "chat" : m.kind;
// 同名模型只出一个选项(不管它由几个源提供)
const dedupKey = kind + "\u0000" + id;
if (seenModel.has(dedupKey)) return;
seenModel.add(dedupKey);
addModel(id, id, kind);
});
});
});
} else {
} else {
optList.push(`<option value="AUTO">AUTO</option>`);
(s.models || []).forEach((m) => {
addModel(m, m, "chat");
@ -2896,9 +2932,24 @@ async function renderChat() {
(imgOpts.length
? `<optgroup label="${escAttr(t("cImageModels"))}">${imgHtml()}</optgroup>`
: "");
$("#tab-chat").innerHTML = `
// ★ 对话与生图合并为**同一导航项**下的两种模式(分段控件切换)。
//
// 两者本是同一件事的两种输入:都选模型、都发一次请求、都读回结果,只是
// 模型 kind 与端点不同。放在两个侧栏项里,用户切换要跨导航;而"我想用
// 这个模型"其实是一个意图。合并只发生在**导航层** —— 模型下拉仍按 kind
// 分组/禁选(见 imgHtml),把图片模型选进 chat 仍会请求到错误端点。
const chatMode = (window.chatState && window.chatState.mode) || "chat";
$("#tab-chat").innerHTML = `
<div class="tab-chat">
<div class="chat-wrap">
<div class="chat-mode-bar">
<div class="kind-toggle">
<button class="${chatMode === "chat" ? "" : "ghost"} small" onclick="switchChatMode('chat')">${esc(t("kChat") || "对话")}</button>
<button class="${chatMode === "image" ? "" : "ghost"} small" onclick="switchChatMode('image')">${esc(t("kImage") || "生图")}</button>
</div>
<span class="grow"></span>
</div>
<div id="ct-image-pane" style="${chatMode === "image" ? "" : "display:none"}"></div>
<div class="chat-wrap" id="ct-chat-pane" style="${chatMode === "chat" ? "" : "display:none"}">
<div class="chat-log" id="ct-log">
<div class="chat-empty" id="ct-empty">
<div class="ring">M</div>
@ -2960,6 +3011,8 @@ async function renderChat() {
const s = await api("/api/status");
const opts = [];
if (Array.isArray(s.sources) && s.sources.length) {
// 同 chat 下拉:只显示模型名,同名模型只出一行(内核自己会跨源回退)。
const seenImg = new Set();
s.sources.forEach((src) => {
const kinds = Array.isArray(src.model_kinds) && src.model_kinds.length
? src.model_kinds
@ -2968,16 +3021,17 @@ async function renderChat() {
const id = typeof m === "string" ? m : m.id;
const kind = typeof m === "string" ? "chat" : m.kind;
if (kind !== "image") return;
opts.push(
`<option value="${escAttr(`${src.name}:${id}`)}">${esc(`${src.name} · ${id}`)}</option>`,
);
if (seenImg.has(id)) return;
seenImg.add(id);
opts.push(`<option value="${escAttr(id)}">${esc(id)}</option>`);
});
});
}
const body = opts.length
? ""
: `<div class="empty">${esc(t("imgNoModels"))}</div>`;
$("#tab-image").innerHTML = `
// 渲染到对话页里的生图面板(不是独立 tab)
$("#ct-image-pane").innerHTML = `
<div class="tab-image">
<div class="img-wrap">
<div class="img-grid" id="it-grid">
@ -3413,7 +3467,7 @@ async function renderChat() {
// Editing: the single-source shape. Creating: an empty form.
const s = name
? src.source
: { name: "", models: [{ id: "", priority: 0, kind: "chat" }] };
: { name: "", models: [{ id: "", kind: "chat" }] };
if (!s) {
toast(t("toastSave"));
return;
@ -3473,7 +3527,7 @@ async function renderChat() {
const box = $("#s-models");
(s.models && s.models.length
? s.models
: [{ id: "", priority: 0, kind: "chat" }]
: [{ id: "", kind: "chat" }]
).forEach((m, i) =>
box.insertAdjacentHTML("beforeend", modelRow(m, i)),
);
@ -3481,7 +3535,7 @@ async function renderChat() {
.catch(() => {});
}
function modelRow(m, i) {
return `<div class="model-row" data-priority="${m.priority || 0}">
return `<div class="model-row">
<input data-mi="${i}" class="m-id" placeholder="model-id" value="${escAttr(m.id)}">
<select data-mi="${i}" class="m-kind"><option ${m.kind === "image" ? "" : "selected"} value="chat">chat</option><option ${m.kind === "image" ? "selected" : ""} value="image">image</option></select>
<button class="ghost del small" onclick="this.closest('.model-row').remove()">&times;</button>
@ -3506,7 +3560,7 @@ async function renderChat() {
const div = $("#s-models");
div.insertAdjacentHTML(
"beforeend",
modelRow({ id: "", priority: 0, kind: "chat" }, div.children.length),
modelRow({ id: "", kind: "chat" }, div.children.length),
);
}
// srcDiscover asks the gateway to probe the upstream for its catalog and
@ -3574,8 +3628,7 @@ async function renderChat() {
modelRow(
{
id: id,
priority: image.indexOf(id) >= 0 ? 70 : 50,
kind: image.indexOf(id) >= 0 ? "image" : "chat",
kind: image.indexOf(id) >= 0 ? "image" : "chat",
},
i,
),
@ -3603,8 +3656,7 @@ async function renderChat() {
const models = [...document.querySelectorAll("#s-models .model-row")]
.map((row) => ({
id: row.querySelector(".m-id").value.trim(),
priority: parseInt(row.dataset.priority) || 0,
kind: row.querySelector(".m-kind").value,
kind: row.querySelector(".m-kind").value,
}))
.filter((m) => m.id);
let meta = {};
@ -3659,8 +3711,7 @@ async function renderChat() {
const models = [...document.querySelectorAll("#s-models .model-row")]
.map((row) => ({
id: row.querySelector(".m-id").value.trim(),
priority: parseInt(row.dataset.priority) || 0,
kind: row.querySelector(".m-kind").value,
kind: row.querySelector(".m-kind").value,
}))
.filter((m) => m.id);
let meta = {};
@ -3774,7 +3825,7 @@ async function renderChat() {
box.innerHTML = "";
(tpl.models && tpl.models.length
? tpl.models
: [{ id: "", priority: 0, kind: "chat" }]
: [{ id: "", kind: "chat" }]
).forEach((m, i) =>
box.insertAdjacentHTML("beforeend", modelRow(m, i)),
);
@ -3837,7 +3888,7 @@ async function renderChat() {
const tlist = tplsR.templates || [];
const s = tlist.find((x) => x.name === name) || {
name: name,
models: [{ id: "", priority: 0, kind: "chat" }],
models: [{ id: "", kind: "chat" }],
};
const cur = s.adapter || "openai";
const apps = ["", ...(st.adapters || []).map((a) => a.name)];
@ -3886,7 +3937,7 @@ async function renderChat() {
const box = $("#s-models");
(s.models && s.models.length
? s.models
: [{ id: "", priority: 0, kind: "chat" }]
: [{ id: "", kind: "chat" }]
).forEach((m, i) =>
box.insertAdjacentHTML("beforeend", modelRow(m, i)),
);
@ -3984,24 +4035,23 @@ async function renderChat() {
function buildSortIndex(sources) {
const byModel = new Map();
const byPair = new Map();
const sourceRows = new Map();
(sources || []).forEach((s) =>
(s.models || []).forEach((m) => {
const it = { src: s.name, id: m.id, prio: m.priority || 0, kind: m.kind };
// `prio` 不再携带 models[].priority(该字段已删除);
// kind 供画布区分聊天/生图。
const it = { src: s.name, id: m.id, kind: m.kind };
byPair.set(m.id + "|" + s.name, it);
if (!byModel.has(m.id)) byModel.set(m.id, it);
if (!sourceRows.has(it.prio)) sourceRows.set(it.prio, []);
sourceRows.get(it.prio).push({ src: s.name, id: m.id });
}),
);
return { byModel, byPair, sourceRows };
return { byModel, byPair };
}
// buildLanes compiles saved rules into the tier-lane structure the canvas
// paints. With no rules it falls back to discovery, grouped by source
// priority, so an unconfigured chain still shows every available slot.
// Shared by the global editor and the per-key editor.
function buildLanes(idx, rules, kind) {
const { byModel, byPair, sourceRows } = idx;
const { byModel, byPair } = idx;
if (rules.length) {
const tiers = [];
rules.forEach((r, i) => {
@ -4026,23 +4076,6 @@ async function renderChat() {
.filter(Boolean)
.map((models, i) => ({ prio: (tiers.length - i) * 10, models }));
}
return [...sourceRows.entries()]
.sort((a, b) => b[0] - a[0])
.map(([prio, models]) => {
const same = models.filter((m) => {
const it = byPair.get(m.id + "|" + m.src);
const k = it ? it.kind : "chat";
return k === kind;
});
if (!same.length) return null;
same.sort((x, y) => (x.src < y.src ? -1 : x.src > y.src ? 1 : 0));
same.forEach((m) => {
m.uid = nexUid();
m.meta = null;
});
return { prio, models: same };
})
.filter(Boolean);
}
async function renderSort() {
const j = await api("/api/v1/sources");
@ -4060,9 +4093,8 @@ async function renderChat() {
);
} catch (e) {}
const sortIdx = buildSortIndex(j.sources);
// build a lane structure for one kind from its saved rules; when
// rules are empty, fall back to discovery from sourceRows filtered by
// kind so an unconfigured chain still shows all available slots
// 按**已保存的规则**编译两种链的画布;无规则时画布为空(不回退 discovery,
// 因为网关在 AUTO 链为空时直接 503,画布必须如实反映"没配")。
sortLanes.chat = buildLanes(sortIdx, autoR, "chat");
sortLanes.image = buildLanes(sortIdx, autoImg, "image");
sortState.lanes = sortLanes[sortState.kind] || [];
@ -6267,7 +6299,6 @@ toast(t("kAutoChainGlobal"));
const done = () => remountPluginElements();
if (tab === "status") return renderStatus().then(done, done);
if (tab === "chat") return renderChat().then(done, done);
if (tab === "image") return renderImage().then(done, done);
if (tab === "keys") return renderKeys().then(done, done);
if (tab === "sort") return renderSort().then(done, done);
if (tab === "sources") return renderSources().then(done, done);

View File

@ -42,28 +42,47 @@ func TestUI_ChatPageGroupsImageModels(t *testing.T) {
}
}
// TestUI_HasDedicatedImagePage pins the second half of the fix: image models
// need somewhere they CAN be tested.
func TestUI_HasDedicatedImagePage(t *testing.T) {
// TestUI_ImageModeIsReachableFromChatTab 钉住生图**仍可达**。
//
// ★ 断言已随 UI 结构调整:生图不再是独立侧栏项,而是对话页里的一个分段模式。
// 原先这条测试钉的是 `data-tab="image"` / `id="tab-image"` / `tab === "image"`
// —— 三者都已随合并移除。若继续钉旧结构,它只会红着挡住重构,而检不出
// "生图入口彻底消失"这种真回归。所以改为钉**合并后的可达性**:
// 分段控件在、切换函数在、面板容器在、端点仍在。
//
// 为什么"可达性"才是要守的东西:合并的动机是少一个导航项,而不是把生图功能
// 藏起来。只要用户能从对话页一键切到生图并真的发出请求,这个功能就是完整的。
func TestUI_ImageModeIsReachableFromChatTab(t *testing.T) {
ui := uiSource(t)
for _, want := range []string{
`data-tab="image"`, // sidebar entry
`id="tab-image"`, // pane
`function renderImage`, // renderer registered with refresh()
`tab === "image"`, // dispatched
`/v1/images/generations`, // the endpoint the page actually calls
`class="chat-mode-bar"`, // 分段栏存在
`switchChatMode('image')`, // 能切到生图
`id="ct-image-pane"`, // 生图面板容器
`function renderImage`, // 渲染器还在
`/v1/images/generations`, // 真正被调用的端点
} {
if !strings.Contains(ui, want) {
t.Errorf("image page is missing %q", want)
t.Errorf("生图模式不可达,缺少 %q", want)
}
}
// The page must be reachable from TABS; goTab iterates TABS to toggle pane
// visibility, so a pane outside that list is present but permanently hidden —
// which reads as "the page is blank" because the content is in the DOM.
if !strings.Contains(ui, `"image"`) {
t.Error(`"image" does not appear in the TABS list`)
// 合并后**不应**再出现独立 tab 的三件套 —— 它们会让 goTab 去找一个不存在的
// 面板($("#tab-image") 为 null ⇒ 点侧栏抛错)。
for _, gone := range []string{
`data-tab="image"`,
`id="tab-image"`,
`tab === "image"`,
} {
if strings.Contains(ui, gone) {
t.Errorf("生图已并入对话页,不应再有独立 tab 结构 %q"+
"(否则 goTab 会找一个不存在的面板)", gone)
}
}
// 面板必须在 DOM 里且**不能被初始隐藏到底**:切换函数用 display 控制。
if !strings.Contains(ui, `ct-chat-pane`) {
t.Error("缺少对话面板容器 ct-chat-pane(切换需要两个容器同时存在)")
}
}

View File

@ -153,6 +153,14 @@ local lobsteraiClientVersion
local expiringWindowDays
local fetchAccountJSON
-- ★ 选号链路的前向声明(第 11 次踩同一个坑)
-- pickAccountForSource 定义在 syncProviderSource 旁边(~4160),但它依赖
-- accountBalanceRaw / balanceTier(~6690/6716)。不声明的话那两个名字在
-- 定义处会被解析成**全局**(nil),选号时抛
-- `attempt to call global 'accountBalanceRaw' (a nil value)` —— account_add
-- 直接 500,源根本注册不出来(已实测踩过)。
local pickAccountForSource, accountBalanceRaw, balanceTier
-- ★★ 这批前向声明必须在 PLATFORMS **之前**:平台表里的 headers_fn / claim_fn
-- 闭包会在**运行时**调用这些函数,而闭包捕获的是**词法作用域里的那个变量**。
-- 若声明写在后面(例如 line ~5479),PLATFORMS 段里的引用会被解析成**全局**
@ -4156,16 +4164,108 @@ local CHANNEL_CREDITS = {
-- 每个账号一条上游源:channels-<provider>-<accountId>。模型开关即改写
-- 这条源的 models 列表(remove+add 重建;内核 add_source 同名覆盖,但显式
-- 先 remove 更诚实,避免旧模型残留)。
--
-- ★ 现在**一个通道 = 一个适配器 = 一个源**,源名只跟通道绑定。
-- 旧设计是「一账号一源」(channels-<provider>-<accountId>),它有三个
-- 结构性后果,全都在生产里出现过:
-- 1. 三个 trae 账号 ⇒ 三个源、三份同名模型。用户在模型下拉框里看到三行
-- 无法区分的东西(channels-trae-aaa · glm-5.2 / ...bbb · glm-5.2)。
-- 2. 谁先谁后**取决于注册顺序,不是余额**。余额用完的号可能排在前面,
-- 每次都先撞它再回退。
-- 3. 换号要改源名 ⇒ 用户书签/脚本里的 `源:模型` 全部失效。
-- 新设计下换号 = 用同名 add_source 覆盖 api_key(内核 AddSource 是
-- UpsertSourceInYAML + 内存替换),对客户端完全透明。
local function providerSourceName(provider)
return "channels-" .. provider
end
-- legacy 源名(旧版按账号拆源的产物)。保留只为了迁移时能删掉旧源。
local function accountSourceName(provider, accountId)
return "channels-" .. provider .. "-" .. accountId
end
-- syncAccountSource 把某账号的上游源与(平台模型目录 - 黑名单)对齐。
-- 无凭据(占位账号)不动源。
local function syncAccountSource(provider, accountId)
-- syncProviderSource(provider):把该通道的**唯一**上游源与模型目录对齐。
--
-- ★ 这是「一个通道 = 一个适配器 = 一个源」的落点。换号完全在插件内部完成,
-- 内核只看到一个源(同名 upsert),客户端完全无感。
--
-- 幂等:可在任何“该用哪个号可能变了”的时刻重复调(账号增删改 / 余额刷新 /
-- 领取完成 / 续期成功 / 30 分钟心跳巡检)。
-- pickAccountForSource(plat):从该平台的账号池里挑一个**现在能用**的号。
--
-- 判据顺序(每一级都是真实故障的产物):
-- 1. 凭据读得出来(占位号 / 密文损坏的号直接跳过)
-- 2. 余额可查且有余量(与 rankAccounts 同口径:先用到快作废的,再用永久的)
-- • 没有 balance 声明的平台不据此排除 —— 不能因为"我们不会查"就把可用号判死
-- • 查询失败同理归入"未知",保留可用性
-- 3. 排除已打失效标记的号(request_end 钩子根据**真实请求失败**打的)
--
-- 返回 (acct, reason)。reason 用于日志,让"为什么选它"可复查。
pickAccountForSource = function(plat)
local accounts = poolList(plat.id)
if #accounts == 0 then return nil, "无账号" end
local withCred = {}
for _, a in ipairs(accounts) do
if a.enabled ~= false then
local tok
if plat.credential_shape == "full" then
tok = __llmsproxy_secrets.get(a.credentialRef)
else
tok = credentialOf(a.credentialRef)
end
if tok ~= nil and tok ~= "" then withCred[#withCred + 1] = a end
end
end
if #withCred == 0 then return nil, "无可用凭据(占位账号或密文不可读)" end
local ranked = withCred
if plat.balance then
local allowPermanent = not (plugin.state.settings
and plugin.state.settings.lock_permanent_credits)
local expiring, permanent, unknown = {}, {}, {}
for _, a in ipairs(withCred) do
local raw = accountBalanceRaw(plat.id, a.id)
if raw == nil then
unknown[#unknown + 1] = a -- 查不到 ⇒ 不据此排除
else
local tier = balanceTier(raw.expiring_balance or raw.expiringBalance,
raw.permanent_balance or raw.permanentBalance, allowPermanent)
if tier == "expiring" then expiring[#expiring + 1] = a
elseif tier == "permanent" then permanent[#permanent + 1] = a
else unknown[#unknown + 1] = a end
end
end
ranked = {}
for _, a in ipairs(expiring) do ranked[#ranked + 1] = a end
for _, a in ipairs(permanent) do ranked[#ranked + 1] = a end
for _, a in ipairs(unknown) do ranked[#ranked + 1] = a end
if #ranked == 0 then return nil, "所有账号余额均不可用" end
end
for _, a in ipairs(ranked) do
if not a.termErr then
return a, "选中账号 " .. tostring(a.id)
.. (a.nickname and a.nickname ~= "" and ("(" .. a.nickname .. ")") or "")
end
end
return ranked[1], "所有账号均标记失效,回退到 " .. tostring(ranked[1].id)
end
local function syncProviderSource(provider)
local plat = platformById(provider)
local acct = poolGet(provider, accountId)
if not plat or not acct then return end
if not plat then return end
-- ★ 自动选号:凭据可用 + 余额分档 + 跳过已标失效的号。
-- 判据全部在插件内(内核不知道账号概念)。
local acct, why = pickAccountForSource(plat)
if not acct then
-- 没有可用账号 ⇒ **撤掉源**。留着旧源会让模型继续出现在列表里却每次都
-- 失败(用户无法区分"我没配"和"配了但坏了")。
local gone = providerSourceName(provider)
__llmsproxy_kernel.call("remove_source", { name = gone })
if plugin.state.chosen then plugin.state.chosen[provider] = nil end
logEvent("通道 " .. provider .. " 无可用账号,已撤源:" .. tostring(why), "warn", provider)
return
end
-- 凭据有两种消费方式,取决于平台的适配器:
-- * 多数平台:适配器发 `Authorization: Bearer <access_token>`
-- → 这里必须交出**裸 access token**(不能把整个 JSON 当 key 发上去)
@ -4182,8 +4282,15 @@ local function syncAccountSource(provider, accountId)
tok = credentialOf(acct.credentialRef)
err = (tok == nil or tok == "") and "无凭据" or nil
end
if err then return end
local name = accountSourceName(provider, accountId)
if err then
logEvent("通道 " .. provider .. " 凭据读取失败,跳过同步", "warn", provider)
return
end
-- ★ 记录"当前为该通道服务的账号"。request_end 钩子靠它把真实请求的
-- 失败原因归因到具体账号(否则只能知道“这个通道坏了”,不知道是哪个号)。
plugin.state.chosen = plugin.state.chosen or {}
plugin.state.chosen[provider] = acct.id
local name = providerSourceName(provider)
local models = {}
local disabled = disabledModelsOf(provider)
-- 用**有效目录**(远端优先、兜底补位),不是硬编码表
@ -4248,20 +4355,46 @@ local function syncAccountSource(provider, accountId)
for _, mk in ipairs({ "uid", "device_id", "machine_id", "enterprise_id" }) do
if cmeta[mk] ~= nil and cmeta[mk] ~= "" then src.meta[mk] = cmeta[mk] end
end
end
end
end
local r, aerr = __llmsproxy_kernel.call("add_source", { source = src })
-- 失败要**记日志**:源注册失败此前是静默的(插件没权限、凭据形状不符都会
-- 走到这里),表现为"账号加了但不出源",排查时没有任何线索。
-- ★ 先清掉旧版的**按账号拆的源**(迁移)。不清的话升级后旧源还在,
-- 模型列表里会有重复项,且旧源指向已经不该用的账号。
-- 按已知平台 id 前缀匹配(不用贪婪模式:账号 id 可能含 `-`)。
-- 只在真正要写源时才扫一遍(低频)。
do
local ls = __llmsproxy_kernel.call("list_sources", {})
local arr = (ls and ls.json and ls.json.sources) or (ls and ls.sources) or {}
if type(arr) ~= "table" then arr = {} end
local legacyPrefix = "channels-" .. provider .. "-"
for _, exist in ipairs(arr) do
local sn = type(exist) == "table" and exist.name or nil
if type(sn) == "string" and sn ~= name
and sn:sub(1, #legacyPrefix) == legacyPrefix then
__llmsproxy_kernel.call("remove_source", { name = sn })
logEvent("已清理旧版按账号拆源 " .. sn, "task", provider)
end
end
end
local r, aerr = __llmsproxy_kernel.call("add_source", { source = src })
-- 失败要**记日志**:源注册失败此前是静默的(插件没权限、凭据形状不符都会
-- 走到这里),表现为"账号加了但不出源",排查时没有任何线索。
if aerr then
logEvent("接入源失败 " .. name .. ": " .. tostring(aerr), "error", provider)
elseif r and r.json and r.json.ok == false then
logEvent("接入源失败 " .. name .. ": " .. tostring(r.json.error), "error", provider)
else
logEvent("已同步源 " .. name .. "(" .. #models .. " 模型)", "task", provider)
logEvent("已同步源 " .. name .. "(" .. #models .. " 模型,账号 "
.. tostring(acct.id) .. ")", "task", provider)
end
end
-- syncAccountSource 保留为**兼容壳**:旧调用点很多(13 处),逐个改风险大。
-- 语义变为"这个平台的源该重算了"(**忽略** accountId)—— 因为现在一通道只有
-- 一个源,账号维度的差异完全由 syncProviderSource 内部消化。
local function syncAccountSource(provider, _accountId)
syncProviderSource(provider)
end
-- dropAccountSource:把某账号的上游源撤掉(账号停用/删除时调用)。
--
-- ★ 必须**检查返回值**:内核的 remove_source 需要**单独授予**(它是 Destructive 级,
@ -4272,19 +4405,32 @@ end
-- 的 remove 失败**看不出来**(add 会把同名覆盖掉)—— 只有纯删除路径才暴露。
-- 故这里把失败**记进事件日志**,让它在面板上可见,而不是只存在于一个被丢弃的返回值里。
local function dropAccountSource(provider, accountId)
local name = accountSourceName(provider, accountId)
-- ★ 语义变了(一通道一源之后):账号被删/停用**不能**直接把通道源撤掉 ——
-- 那个源现在代表**整个通道**,池里可能还有别的号能用。正确做法是重新
-- 选号:syncProviderSource 会挑下一个可用账号并用同名覆盖,没有可用
-- 账号时它自己会撤源。
--
-- 迁移期要兼顾旧状态:如果库里还有旧版按账号拆的源(channels-p-<id>),
-- 那个才是该删的。两步都做。
local legacy = accountSourceName(provider, accountId)
-- ★ 内核桥是 `call(name, args) -> (result, nil) | (nil, err)`:
-- 失败时**第一个返回值是 nil**,原因在**第二个返回值**里。
-- 我第一版写成 `local r = call(...)` 再读 `r.ok` ⇒ 恒 nil ⇒ 日志只说"无返回",
-- 把真正原因(not granted / 超时 / 拒删最后一个源)丢掉 —— 一句不可操作的
-- 诊断比没有更糟。两个返回值都要接。
local r, err = __llmsproxy_kernel.call("remove_source", { name = name })
local r, err = __llmsproxy_kernel.call("remove_source", { name = legacy })
if r == nil or r.ok ~= true then
logEvent("撤源失败 " .. tostring(name) .. ": " .. tostring(err or "(无错误信息)")
.. " | 若为 not granted,需给 channels 插件授予 remove_source(声明在 plugin.kernel)",
"error", provider)
return false, err
-- 旧源不存在是**正常**的(新部署根本没启过它),不当作失败。
local msg = tostring(err or "")
if not msg:find("not found", 1, true) and not msg:find("不存在", 1, true) then
logEvent("撤旧源失败 " .. tostring(legacy) .. ": " .. tostring(err or "(无错误信息)")
.. " | 若为 not granted,需给 channels 插件授予 remove_source(声明在 plugin.kernel)",
"error", provider)
return false, err
end
end
-- 重算通道源:池里还有别的号就自动接上,没了就撤掉整个通道源。
syncProviderSource(provider)
return true
end
@ -6223,7 +6369,7 @@ function plugin.complete_login(req)
end
logEvent("账号凭据已入池 " .. plat.id .. "/" .. aid)
syncAccountSource(plat.id, aid)
return { status = 200, json = { ok = true, account_id = aid, source = accountSourceName(plat.id, aid) } }
return { status = 200, json = { ok = true, account_id = aid, source = providerSourceName(plat.id) } }
end
-- 兼容旧路径:单账号模式(e2e 与既有端点仍走它)。
@ -6671,7 +6817,7 @@ end
-- "expiring" 有 15 天内到期的积分 → 最优先(不用就作废)
-- "permanent" 只剩永久积分 → 次优先;锁定永久积分时视为不可用
-- "none" 都没有 → 不可用
local function balanceTier(expiring, permanent, allow_permanent)
balanceTier = function(expiring, permanent, allow_permanent)
local function pos(v)
local n = tonumber(v)
if n and n > 0 then return n end
@ -6697,7 +6843,7 @@ end
-- accountBalanceRaw(provider, accountId):取该账号的余额原料(带 TTL 缓存)。
-- 失败**不抛错**(照参考:查询失败归入最后一档),返回 nil 让调用方降级。
local function accountBalanceRaw(provider, accountId)
accountBalanceRaw = function(provider, accountId)
-- 用通用 TTL 缓存(照参考 ttl-cache):命中即返回、在飞去重、失败不缓存。
-- ⚠️ 缓存的是**原料**(包列表明细),分桶每次都现算 —— 见本节的注释。
local plat = platformById(provider)
@ -7028,7 +7174,12 @@ function plugin.refresh_creds()
local now = os.time and os.time() or 0
local refreshed, skipped, failed = 0, 0, {}
for _, plat in ipairs(allPlatforms()) do
if plat.exchange_body or plat.refresh_url then
-- ★ 三种续期声明都要认:声明式 refresh.url、旧的 refresh_url、钩子式 refresh_fn。
-- 真实缺陷:此前只认前两种 ⇒ codearts 的 refresh_fn 挂上了也永远不会被
-- 定时任务触发,token 到期后源就静静地 400。refresh_creds 是这条链路唯一入口。
if plat.exchange_body or plat.refresh_url
or (type(plat.refresh) == "table" and plat.refresh.url)
or type(plat.refresh_fn) == "function" then
for _, a in ipairs(poolList(plat.id)) do
local cred = credentialFull(a.credentialRef)
if type(cred) == "table" then
@ -7063,6 +7214,14 @@ function plugin.refresh_creds()
if #failed > 0 then
logEvent("凭据续期失败 " .. #failed .. " 个:" .. plugin.utf8Clip(table.concat(failed, "; "), 300), "warn")
end
-- ★ 每次续期巡检后重新选号(每 30 分钟一次,是「余额/凭据变了」的自然节拍)。
-- 一通道一源:换号 = 同名 add_source 改 api_key,对客户端完全透明。
-- 这是「插件自动察觉账号余额用尽并切到有余额的账号」的**兜底心跳** ——
-- 即使没有任何事件触发(没人点刷新、没登录新号),最迟 30 分钟内也会
-- 重新挑一次号。纯本地判定(余额有 TTL 缓存),不产生上游请求。
for _, plat in ipairs(allPlatforms()) do
syncProviderSource(plat.id)
end
end
-- todayKey():当天标识(UTC+8 口径,与活动结算口径一致)。
@ -7503,7 +7662,7 @@ function plugin.account_test(req)
local srcs, _ = __llmsproxy_kernel.call("list_sources", {})
local found = false
for _, s in ipairs(srcs or {}) do
if s.name == accountSourceName(plat.id, acct.id) then found = true break end
if s.name == providerSourceName(plat.id) then found = true break end
end
return { status = 200, json = { ok = found, probed = false,
error = found and nil or "源未同步",
@ -8803,17 +8962,37 @@ function plugin.reap_orphan_sources(req)
local found, removed, failed = {}, 0, {}
for _, x in ipairs(arr) do
local nm = type(x) == "table" and x.name or nil
if type(nm) == "string" then
local plat, acct = nil, nil
for _, p in ipairs(PLATFORMS) do
local pref = "channels-" .. p.id .. "-"
if nm:sub(1, #pref) == pref then
plat, acct = p.id, nm:sub(#pref + 1)
break
local nm = type(x) == "table" and x.name or nil
if type(nm) == "string" then
local plat, acct, why = nil, nil, nil
-- 形态 1(旧版残留):channels-<平台>-<账号id>,账号已不在池里 ⇒ 孤儿。
-- 按**已知平台前缀**匹配,不能用 `channels-(.+)-(.+)$`(Lua 的 `-` 是贪婪的,
-- 账号 id 含 `-` 会被切错 —— 判据里专门放了 dead-acct-1 咬这一条)。
for _, p in ipairs(PLATFORMS) do
local pref = "channels-" .. p.id .. "-"
if nm:sub(1, #pref) == pref then
plat, acct = p.id, nm:sub(#pref + 1)
break
end
end
end
if plat and acct ~= "" and poolGet(plat, acct) == nil then
if plat and acct ~= "" and poolGet(plat, acct) == nil then
why = "账号 " .. acct .. " 已不在池中"
end
-- 形态 2(一通道一源之后的真实孤儿):channels-<平台> 但该平台
-- **没有任何可用账号**(全删了/全停用/凭据全读不出来)。
if plat == nil then
for _, p in ipairs(PLATFORMS) do
if nm == "channels-" .. p.id then
local pok, acc, areason = pcall(pickAccountForSource, p)
if not pok then acc = nil areason = "选号失败: " .. tostring(acc) end
if not acc then
plat, why = p.id, "该通道无可用账号:" .. tostring(areason)
end
break
end
end
end
if plat and why then
found[#found + 1] = nm
if not dry then
local r, err = __llmsproxy_kernel.call("remove_source", { name = nm })
@ -8823,7 +9002,7 @@ function plugin.reap_orphan_sources(req)
"error", plat)
else
removed = removed + 1
logEvent("孤儿源已清理 " .. nm .. "(账号 " .. acct .. " 已不在池中)", "warn", plat)
logEvent("孤儿源已清理 " .. nm .. "(" .. tostring(why) .. ")", "warn", plat)
end
end
end
@ -11912,6 +12091,100 @@ end
-- plugin.credits_tier_probe:只给测试用 —— 单账号的余额分档结果。
-- 暴露 expiring/permanent/tier/usable 四个值,让判据能逐条钉住分档规则
-- (含"失效包必须跳过""到期未知归永久""锁定永久积分时只剩永久的号不可用")。
-- ============================================================================
-- 账号有效性反馈:从真实请求结果里学习「哪个号该被跳过」
-- ============================================================================
--
-- 为什么需要这条链路
-- ------------------
-- 选号(pickAccountForSource)判的是**余额**,但余额查询有三个盲区:
-- 1. 有些平台没有余额端点 ⇒ accountBalanceRaw 恒 nil
-- 2. 余额查询有 TTL 缓存(60s)⇒ 用尽的瞬间不会立刻反映
-- 3. 余额 > 0 但账号被风控/封禁 ⇒ 余额看起来完好,实际全失败
--
-- 唯一能覆盖这三点的证据是**真实请求的失败原因**。所以挂 request_end:
-- 当这个通道的请求失败、且错误文本是「终态」的(需充值 / 封禁 / 凭据失效)时,
-- 给当前选中的账号打 termErr 标记,下一次选号跳开它。
--
-- ⚠️ 只认**终态**错误。普通 429 限流、超时、网络抖动都**不**标记 ——
-- 那些会自动恢复,标记它们等于把好号一个个废掉(把一次请求层面的拒绝
-- 当终态,代价是把材料完好的账号一步标死)。
--
-- 解除标记的路径:请求成功 / 账号重新登录 / 手动 account_reset。
-- plugin.term_error_kind(msg):把错误文本分类为终态错误,返回原因或 nil。
function plugin.term_error_kind(msg)
if type(msg) ~= "string" or msg == "" then return nil end
local low = msg:lower()
-- 额度类:明确说用尽且需要充值(不是"当日免费额度,明天恢复"那种)
if low:find("insufficient", 1, true) or low:find("余额不足", 1, true)
or low:find("请充值", 1, true) or low:find("insufficient_balance", 1, true)
or low:find("额度已用完", 1, true) then
return "余额不足(需充值)"
end
-- 封禁 / 风控 / 账号停用
if low:find("banned", 1, true) or low:find("封禁", 1, true)
or low:find("账号已停用", 1, true) then
return "账号被封禁/停用"
end
-- 凭据失效(refresh_token 已作废这类不可自愈的)
if low:find("refresh token has been used", 1, true)
or low:find("invalid_grant", 1, true) then
return "凭据已永久失效(需重新登录)"
end
return nil
end
-- plugin.mark_account_term_error(provider, kind):给**当前为该通道服务**的号打标记。
function plugin.mark_account_term_error(provider, kind)
local plat = platformById(provider)
if not plat then return end
local cur = plugin.state.chosen and plugin.state.chosen[provider]
if not cur then return end
local acct = poolGet(provider, cur)
if not acct then return end
if acct.termErr == kind then return end -- 已经标过,别刷日志
acct.termErr = kind
acct.termErrAt = os.time and os.time() or 0
poolAdd(provider, acct)
markDirty()
logEvent("账号 " .. tostring(cur) .. " 标记失效:" .. tostring(kind)
.. " —— 下次选号将跳过它", "warn", provider)
end
-- 插件钩子:request_end 在每次请求结束时触发。
-- ⚠️ 声明 hooks 不妨碍自有 HTTP 路由 —— 本插件的状态变更仍走自己的路由。
plugin.hooks = { request_end = "on_request_end" }
function plugin.on_request_end(payload)
if type(payload) ~= "table" then return nil end
local src = tostring(payload.source or "")
-- 只处理本插件管辖的通道(`channels-<provider>`),其他源不碰。
if src:sub(1, 9) ~= "channels-" then return nil end
local provider = src:sub(10)
local cur = plugin.state.chosen and plugin.state.chosen[provider]
if not cur then return nil end
local acct = poolGet(provider, cur)
if not acct then return nil end
if payload.ok then
-- 成功 ⇒ 清掉失效标记(它显然能用)。
if acct.termErr then
acct.termErr = nil
acct.termErrAt = nil
poolAdd(provider, acct)
markDirty()
logEvent("账号 " .. tostring(cur) .. " 恢复正常(请求成功)", "info", provider)
end
return nil
end
-- 失败 ⇒ 只有"终态"错误才标记。payload 里的错误文本字段名不定,
-- 三个都看(内核不同路径填的字段不同)。
local msg = tostring(payload.error or payload.message or payload.error_message or "")
local kind = plugin.term_error_kind(msg)
if kind then plugin.mark_account_term_error(provider, kind) end
return nil
end
function plugin.credits_tier_probe(args)
args = args or {}
local provider = tostring(args.platform or "")
@ -12499,7 +12772,8 @@ function plugin.__sync_source_probe(args)
-- 回报同步后内核里该源是否存在
local ls = __llmsproxy_kernel.call("list_sources", {})
local found, ad = false, nil
local want = accountSourceName(args.platform, args.account_id)
-- 一通道一源之后,同步的目标是**通道级**源名;account_id 只用于选号。
local want = providerSourceName(args.platform)
local arr = (ls and ls.json and ls.json.sources) or (ls and ls.sources) or {}
for _, x in ipairs(arr) do
if x.name == want then found = true ad = x.adapter end

View File

@ -506,42 +506,39 @@ func (p *Provider) ModelFor(reqModel string) string {
return p.bestChatModel()
}
// bestChatModel returns the highest-priority chat-kind model of this source.
// bestChatModel returns the first chat-kind model of this source.
//
// ★ 曾经叫 "highest-priority chat model",但 `config.Model.Priority` 已删除
//
// (它从未参与跨源调度,只在这里用;而这里的语义其实只是"选一个能发 chat 的
// 模型",选第一个就够了 —— 源内模型顺序由配置/发现顺序决定)。
func (p *Provider) bestChatModel() string {
bestID, bestPrio := "", -1
for _, m := range p.cfg.Models {
if m.Kind != "" && m.Kind != "chat" {
continue
}
if m.Priority > bestPrio {
bestPrio = m.Priority
bestID = m.ID
}
return m.ID
}
if bestID == "" && len(p.cfg.Models) > 0 {
bestID = p.cfg.Models[0].ID
if len(p.cfg.Models) > 0 {
return p.cfg.Models[0].ID
}
return bestID
return ""
}
// bestImageModel returns the highest-priority image-kind model of this source
// (fallback: first configured model). Used for AUTO image generation so a
// mixed source never sends a chat model to /v1/images/generations.
// bestImageModel returns the first image-kind model of this source (fallback:
// first configured model). Used for AUTO image generation so a mixed source
// never sends a chat model to /v1/images/generations.
func (p *Provider) bestImageModel() string {
bestID, bestPrio := "", -1
for _, m := range p.cfg.Models {
if m.Kind != "" && m.Kind != "image" {
continue
}
if m.Priority > bestPrio {
bestPrio = m.Priority
bestID = m.ID
}
return m.ID
}
if bestID == "" && len(p.cfg.Models) > 0 {
bestID = p.cfg.Models[0].ID
if len(p.cfg.Models) > 0 {
return p.cfg.Models[0].ID
}
return bestID
return ""
}
// IsAutoID reports whether s is an AUTO routing placeholder.

View File

@ -32,7 +32,7 @@ func newTestProvider(t *testing.T, src config.Source) *Provider {
func src(name, url, adapter string, models ...string) config.Source {
s := config.Source{Name: name, BaseURL: url, Adapter: adapter, MaxConcurrent: 4}
for _, m := range models {
s.Models = append(s.Models, config.Model{ID: m, Priority: 0})
s.Models = append(s.Models, config.Model{ID: m})
}
return s
}
@ -515,8 +515,8 @@ func TestImageAutoUsesImageModel(t *testing.T) {
defer up.Close()
s := config.Source{Name: "mix", BaseURL: up.URL, Adapter: "openai", MaxConcurrent: 4}
s.Models = []config.Model{
{ID: "chat-m", Kind: "chat", Priority: 100},
{ID: "img-m", Kind: "image", Priority: 50},
{ID: "chat-m", Kind: "chat"},
{ID: "img-m", Kind: "image"},
}
p := newTestProvider(t, s)
resp, err := p.Image(context.Background(), &types.ImageGenRequest{Prompt: "cat", Model: "AUTO"})