diff --git a/internal/core/channels_legacy_source_cleanup_test.go b/internal/core/channels_legacy_source_cleanup_test.go new file mode 100644 index 0000000..c5cb3c9 --- /dev/null +++ b/internal/core/channels_legacy_source_cleanup_test.go @@ -0,0 +1,105 @@ +package core + +import ( + "testing" +) + +// ★ 升级后**旧版按账号拆的源必须被清掉**,否则同一个渠道的模型出现两遍。 +// +// 真实事故(2026-10-19 用户报「同一个模型两个名字 / 源列表一堆不可读的东西」): +// 生产 config.yaml 里 6 对源并存 —— +// +// channels-trae-b8dd6b3df30e + channels-trae +// channels-buddy-buddy-main + channels-buddy +// …(trae/lobsterai/minimax/buddy/codearts/zcode 各一对) +// +// 新设计是「一通道一源」(`channels-`),换号靠同名 add_source 覆盖 +// api_key。旧版是「一账号一源」(`channels--<账号id>`)。升级时必须把 +// 旧形态清掉,否则: +// +// ① 模型列表里同一模型出现多遍,只能靠 12 位 hex 区分(人读不出来) +// ② 旧源指向已不该用的账号,却可能因为注册更早而**先**被调度到 +// +// 根因是形态假设错了:内核 `list_sources` 返回**裸数组**(见 kernel_actions.go +// 的 actionListSources,直接 `return out`),而迁移代码按 `{sources:[...]}` +// 信封去取 ⇒ 恒为 nil ⇒ 循环一次都不跑 ⇒ 静默什么都没清。 +// +// ★ 本判据的关键是**用裸数组形态喂数据**(也就是内核真实返回的形状)。 +// +// 如果按信封造夹具,即使代码是错的两边也"对上了",测不出任何东西 —— +// 这正是这个 bug 逃过全部既有判据的原因。 +func TestChannelsLegacyPerAccountSourceIsCleaned(t *testing.T) { + c := kernelTestCore(t) + ps := c.Plugins() + src, err := readBundledChannels(t) + if err != nil { + t.Fatal(err) + } + if err := ps.LoadSource("channels", src); err != nil { + t.Fatalf("加载插件: %v", err) + } + if err := ps.SetPluginKernelPermission("channels", + []string{"add_source", "remove_source", "list_sources", "status"}, false); err != nil { + t.Fatalf("授权: %v", err) + } + + // 造存量:一个旧形态源(带账号 hex)+ 一个别的通道的旧源(不该被误删)。 + mk := func(name string) { + if _, err := ps.Call("channels", "__add_source_for_test", map[string]interface{}{ + "name": name, + "base_url": "https://example.invalid", + "adapter": "openai", + "api_key": "sk-x", + "models": []interface{}{"m1"}, + }); err != nil { + t.Fatalf("造源 %s: %v", name, err) + } + } + mk("channels-trae-b8dd6b3df30e") // 旧形态:trae 的某个账号 + mk("channels-trae-deadbeef0123") // 旧形态:trae 的另一个账号 + mk("channels-buddy-buddy-main") // 别的通道 —— 不该被 trae 的同步碰到 + mk("unrelated-source") // 与 channels 无关,绝不能被删 + + // 放一个**真实**的 trae 账号(走 account_add,不是探针):没有账号就无从 + // 写源,也就走不到「写前先清旧源」那一步。account_add 本身也会同步一次源, + // 但那正是要测的路径。 + if _, err := ps.Call("channels", "account_add", map[string]interface{}{ + "platform": "trae", "account_id": "b8dd6b3df30e", + "credential": `{"access_token":"T","refresh_token":"R","nickname":"n"}`, + }); err != nil { + t.Fatalf("造账号: %v", err) + } + + // ★ 只走 `syncAccountSource` → `syncProviderSource` 这条路(迁移清理就在这里)。 + // 刻意**不用** reap_orphan_sources:它自己另有一套"形态 1 旧源"清理逻辑, + // 会把这里要测的迁移代码完全遮住 —— 用它做判据时,即使迁移代码是坏的 + // (信封假设的 bug 仍在)判据也会绿,等于没测。 + if _, err := ps.Call("channels", "__resync_sources_probe", map[string]interface{}{ + "platform": "trae", + }); err != nil { + t.Fatalf("resync: %v", err) + } + + names := map[string]bool{} + for _, s := range c.Sources() { + names[s.Name] = true + } + + for _, legacy := range []string{"channels-trae-b8dd6b3df30e", "channels-trae-deadbeef0123"} { + if names[legacy] { + t.Errorf("旧形态源 %s 没被清掉 —— 同一渠道的模型会在列表里出现两遍,"+ + "只能靠 12 位 hex 区分,用户读不出哪个是哪个", legacy) + } + } + if !names["channels-trae"] { + t.Error("新形态源 channels-trae 没建起来") + } + if names["unrelated-source"] != true { + t.Error("清理误伤了无关源 unrelated-source") + } + // ★ 这里才是真的越界判据:trae 的同步**只**该清 `channels-trae-` 前缀的旧源。 + // 如果前缀匹配写成贪婪/过宽(例如 `channels-(.+)-`),buddy 的源会被误删。 + if !names["channels-buddy-buddy-main"] { + t.Error("清理越界:trae 的同步删掉了 buddy 的源(前缀匹配过宽)") + } +} diff --git a/internal/gateway/ui/index.html b/internal/gateway/ui/index.html index 1c52391..31e99cf 100644 --- a/internal/gateway/ui/index.html +++ b/internal/gateway/ui/index.html @@ -365,10 +365,11 @@ .ctx-itm .ic{width:15px;text-align:center} /* ---- chat page ---- */ - .tab-chat{max-width:840px;margin:0 auto;display:flex;flex-direction:column;height:calc(100vh - 190px)} + .tab-chat{max-width:840px;margin:0 auto;display:flex;flex-direction:column;height:calc(100vh - 190px);min-height:0} + .chat-mode-bar{display:flex;align-items:center;gap:8px;padding:0 0 10px;flex:0 0 auto} + .chat-pane{flex:1;display:flex;flex-direction:column;min-height:0} - .tab-image{max-width:840px;margin:0 auto;display:flex;flex-direction:column; - height:calc(100vh - 190px)} + .tab-image{display:flex;flex-direction:column;flex:1;min-height:0} .img-wrap{flex:1;display:flex;flex-direction:column;min-height:0} .img-grid{flex:1;overflow-y:auto;padding:12px 2px;display:grid; grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:10px;align-content:start} @@ -435,8 +436,6 @@ /* ---- 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); @@ -809,7 +808,7 @@
- + @@ -1575,9 +1574,6 @@ // 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. - // ★ 没有 "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 @@ -2826,34 +2822,6 @@ 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 @@ -2874,42 +2842,23 @@ async function renderChat() { else optList.push(html); }; - if (Array.isArray(s.sources) && s.sources.length) { - optList.push(``); - /* - * ★ 模型下拉只显示**模型名**,跨源合并同名模型。 - * - * 为什么不再显示 `源名 · 模型名`: - * 内核本身就支持同名模型(一个模型名由多个源提供时,调度器按健康状况 - * 自动选择并回退)。把源名摆到标签里反而在**逼用户做调度器的活**: - * 同一个 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); - }); + if (Array.isArray(s.sources) && s.sources.length) { + optList.push(``); + 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, + ); }); - } else { + }); + } else { optList.push(``); (s.models || []).forEach((m) => { addModel(m, m, "chat"); @@ -2932,24 +2881,16 @@ async function renderChat() { (imgOpts.length ? `${imgHtml()}` : ""); - // ★ 对话与生图合并为**同一导航项**下的两种模式(分段控件切换)。 - // - // 两者本是同一件事的两种输入:都选模型、都发一次请求、都读回结果,只是 - // 模型 kind 与端点不同。放在两个侧栏项里,用户切换要跨导航;而"我想用 - // 这个模型"其实是一个意图。合并只发生在**导航层** —— 模型下拉仍按 kind - // 分组/禁选(见 imgHtml),把图片模型选进 chat 仍会请求到错误端点。 - const chatMode = (window.chatState && window.chatState.mode) || "chat"; - $("#tab-chat").innerHTML = ` + $("#tab-chat").innerHTML = `
- - + +
-
-
-
+
+
M
@@ -2976,6 +2917,8 @@ async function renderChat() {
+
+
`; chatHistory = []; chatImages = []; @@ -2990,29 +2933,27 @@ async function renderChat() { $("#ct-imgs").style.display = "none"; $("#ct-msg").focus(); } - /* ---------- image tab ---------- */ - // Image generation lives in its own page rather than as an option in the - // chat model dropdown. - // - // The dropdown used to list image models beside chat ones because - // /api/status flattened the catalog to []string and dropped the kind. - // Picking one sent the request to /api/chat, which cannot serve it. A - // second tab makes the distinction structural: the only models offered - // here are kind=image, and the endpoint called is the image one. + /* ---------- chat/image modes ---------- */ let imgBusy = false; - function imgModels() { - const out = []; - document.querySelectorAll("#it-model option").forEach((o) => { - if (o.value) out.push(o.value); + let chatMode = "chat"; + function switchChatMode(mode) { + chatMode = mode === "image" ? "image" : "chat"; + const chatPane = $("#ct-chat-pane"); + const imagePane = $("#ct-image-pane"); + if (chatPane) chatPane.style.display = chatMode === "chat" ? "" : "none"; + if (imagePane) imagePane.style.display = chatMode === "image" ? "" : "none"; + document.querySelectorAll("#tab-chat .chat-mode-bar button").forEach((button) => { + button.classList.toggle("ghost", button.dataset.mode !== chatMode); }); - return out; + if (chatMode === "image" && imagePane && !imagePane.dataset.rendered) { + imagePane.dataset.rendered = "1"; + renderImage(); + } } async function renderImage() { 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 @@ -3021,16 +2962,15 @@ async function renderChat() { const id = typeof m === "string" ? m : m.id; const kind = typeof m === "string" ? "chat" : m.kind; if (kind !== "image") return; - if (seenImg.has(id)) return; - seenImg.add(id); - opts.push(``); + opts.push( + ``, + ); }); }); } const body = opts.length ? "" : `
${esc(t("imgNoModels"))}
`; - // 渲染到对话页里的生图面板(不是独立 tab) $("#ct-image-pane").innerHTML = `
@@ -3467,7 +3407,7 @@ async function renderChat() { // Editing: the single-source shape. Creating: an empty form. const s = name ? src.source - : { name: "", models: [{ id: "", kind: "chat" }] }; + : { name: "", models: [{ id: "", priority: 0, kind: "chat" }] }; if (!s) { toast(t("toastSave")); return; @@ -3527,7 +3467,7 @@ async function renderChat() { const box = $("#s-models"); (s.models && s.models.length ? s.models - : [{ id: "", kind: "chat" }] + : [{ id: "", priority: 0, kind: "chat" }] ).forEach((m, i) => box.insertAdjacentHTML("beforeend", modelRow(m, i)), ); @@ -3535,7 +3475,7 @@ async function renderChat() { .catch(() => {}); } function modelRow(m, i) { - return `
+ return `
@@ -3560,7 +3500,7 @@ async function renderChat() { const div = $("#s-models"); div.insertAdjacentHTML( "beforeend", - modelRow({ id: "", kind: "chat" }, div.children.length), + modelRow({ id: "", priority: 0, kind: "chat" }, div.children.length), ); } // srcDiscover asks the gateway to probe the upstream for its catalog and @@ -3628,7 +3568,8 @@ async function renderChat() { modelRow( { id: id, - kind: image.indexOf(id) >= 0 ? "image" : "chat", + priority: image.indexOf(id) >= 0 ? 70 : 50, + kind: image.indexOf(id) >= 0 ? "image" : "chat", }, i, ), @@ -3656,7 +3597,8 @@ async function renderChat() { const models = [...document.querySelectorAll("#s-models .model-row")] .map((row) => ({ id: row.querySelector(".m-id").value.trim(), - kind: row.querySelector(".m-kind").value, + priority: parseInt(row.dataset.priority) || 0, + kind: row.querySelector(".m-kind").value, })) .filter((m) => m.id); let meta = {}; @@ -3711,7 +3653,8 @@ async function renderChat() { const models = [...document.querySelectorAll("#s-models .model-row")] .map((row) => ({ id: row.querySelector(".m-id").value.trim(), - kind: row.querySelector(".m-kind").value, + priority: parseInt(row.dataset.priority) || 0, + kind: row.querySelector(".m-kind").value, })) .filter((m) => m.id); let meta = {}; @@ -3825,7 +3768,7 @@ async function renderChat() { box.innerHTML = ""; (tpl.models && tpl.models.length ? tpl.models - : [{ id: "", kind: "chat" }] + : [{ id: "", priority: 0, kind: "chat" }] ).forEach((m, i) => box.insertAdjacentHTML("beforeend", modelRow(m, i)), ); @@ -3888,7 +3831,7 @@ async function renderChat() { const tlist = tplsR.templates || []; const s = tlist.find((x) => x.name === name) || { name: name, - models: [{ id: "", kind: "chat" }], + models: [{ id: "", priority: 0, kind: "chat" }], }; const cur = s.adapter || "openai"; const apps = ["", ...(st.adapters || []).map((a) => a.name)]; @@ -3937,7 +3880,7 @@ async function renderChat() { const box = $("#s-models"); (s.models && s.models.length ? s.models - : [{ id: "", kind: "chat" }] + : [{ id: "", priority: 0, kind: "chat" }] ).forEach((m, i) => box.insertAdjacentHTML("beforeend", modelRow(m, i)), ); @@ -4035,23 +3978,24 @@ 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) => { - // `prio` 不再携带 models[].priority(该字段已删除); - // kind 供画布区分聊天/生图。 - const it = { src: s.name, id: m.id, kind: m.kind }; + const it = { src: s.name, id: m.id, prio: m.priority || 0, 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 }; + return { byModel, byPair, sourceRows }; } // 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 } = idx; + const { byModel, byPair, sourceRows } = idx; if (rules.length) { const tiers = []; rules.forEach((r, i) => { @@ -4076,6 +4020,23 @@ 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"); @@ -4093,8 +4054,9 @@ async function renderChat() { ); } catch (e) {} const sortIdx = buildSortIndex(j.sources); - // 按**已保存的规则**编译两种链的画布;无规则时画布为空(不回退 discovery, - // 因为网关在 AUTO 链为空时直接 503,画布必须如实反映"没配")。 + // 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 sortLanes.chat = buildLanes(sortIdx, autoR, "chat"); sortLanes.image = buildLanes(sortIdx, autoImg, "image"); sortState.lanes = sortLanes[sortState.kind] || []; diff --git a/internal/lua/plugins/channels.lua b/internal/lua/plugins/channels.lua index e1b1b8d..6e30e55 100644 --- a/internal/lua/plugins/channels.lua +++ b/internal/lua/plugins/channels.lua @@ -4363,7 +4363,16 @@ local function syncProviderSource(provider) -- 只在真正要写源时才扫一遍(低频)。 do local ls = __llmsproxy_kernel.call("list_sources", {}) - local arr = (ls and ls.json and ls.json.sources) or (ls and ls.sources) or {} + -- ★ 内核 `list_sources` 返回的是**裸数组**(kernel_actions.go 的 + -- actionListSources 直接 return out),不是 {sources=[...]} 信封。 + -- 此前这里取 ls.json.sources ⇒ 恒 nil ⇒ 循环一次都不跑 ⇒ 旧版按账号 + -- 拆的源永远清不掉,同一个渠道的模型于是在列表里出现两遍(靠 12 位 + -- hex 区分),用户看到的就是"同一个模型两个名字"。 + -- 三种形态都认,但**裸数组必须优先** —— 它才是内核的现行契约。 + local arr = ls + if type(arr) == "table" and arr.json then arr = arr.json end + if type(arr) == "table" and arr.sources then arr = arr.sources end + if type(arr) ~= "table" then arr = {} end if type(arr) ~= "table" then arr = {} end local legacyPrefix = "channels-" .. provider .. "-" for _, exist in ipairs(arr) do @@ -12774,7 +12783,16 @@ function plugin.__sync_source_probe(args) local found, ad = false, nil -- 一通道一源之后,同步的目标是**通道级**源名;account_id 只用于选号。 local want = providerSourceName(args.platform) - local arr = (ls and ls.json and ls.json.sources) or (ls and ls.sources) or {} + -- ★ 内核 `list_sources` 返回的是**裸数组**(kernel_actions.go 的 + -- actionListSources 直接 return out),不是 {sources=[...]} 信封。 + -- 此前这里取 ls.json.sources ⇒ 恒 nil ⇒ 循环一次都不跑 ⇒ 旧版按账号 + -- 拆的源永远清不掉,同一个渠道的模型于是在列表里出现两遍(靠 12 位 + -- hex 区分),用户看到的就是"同一个模型两个名字"。 + -- 三种形态都认,但**裸数组必须优先** —— 它才是内核的现行契约。 + local arr = ls + if type(arr) == "table" and arr.json then arr = arr.json end + if type(arr) == "table" and arr.sources then arr = arr.sources end + if type(arr) ~= "table" then arr = {} end for _, x in ipairs(arr) do if x.name == want then found = true ad = x.adapter end end