diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 43367a565..f33249640 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -8216,6 +8216,9 @@ function headerEditor(hints = []) { const add = el("button", "text", t("+ Add header")); add.onclick = () => { draft.headers.push(["", "", false]); render(); }; adds.append(add); + const pre = el("button", "text hpresets", t("Presets")); + pre.onclick = () => { if (pre.classList.contains("open")) return closeProtoMenu(); import("./headerpresets.js").then(() => headerPresetsOpen(pre, draft.headers, render), statusErr); }; + adds.append(pre); for (const h of hints) { if (draft.headers.some((r) => (r[0] || "").trim().toLowerCase() === h.toLowerCase())) continue; const b = el("button", "text", "+ " + h); diff --git a/internal/gui/assets/headerpresets.js b/internal/gui/assets/headerpresets.js new file mode 100644 index 000000000..db0ac67b5 --- /dev/null +++ b/internal/gui/assets/headerpresets.js @@ -0,0 +1,38 @@ +// A provider's Headers can be filled from what a common client sends +// (l3123109756 on X). app.js draws the Presets button and imports this when +// it is pressed, so the list weighs nothing on the core. Each value is that +// client's own, cited above it; none imitates Claude Code. A client's name +// is not translated. Versions are the latest on 2026-11-11. +const HEADER_PRESETS = [ + // codex-rs login/src/auth/default_client.rs (originator, User-Agent); @openai/codex 0.167.0 on npm + { name: "Codex CLI", headers: [["originator", "codex_cli_rs"], ["User-Agent", "codex_cli_rs/0.167.0 (Mac OS 26.6.0; arm64) Apple_Terminal/455"], ["version", "0.167.0"]] }, + // google-gemini/gemini-cli's Code Assist User-Agent; @google/gemini-cli 0.67.0 on npm + { name: "Gemini CLI", headers: [["User-Agent", "GeminiCLI/0.67.0/gemini-2.5-pro (darwin; arm64; terminal)"]] }, + // packages/core/src/app.ts: opencode/${channel}/${version}/${name}; @opencode/cli 2.2.7 on npm + { name: "OpenCode", headers: [["User-Agent", "opencode/latest/2.2.7/cli"]] }, + // Kilo-Org/kilocode request.ts and kilo-gateway headers.ts; @kilocode/cli 7.8.27 on npm + { name: "Kilo Code", headers: [["HTTP-Referer", "https://kilocode.ai"], ["X-Title", "Kilo Code"], ["User-Agent", "Kilo-Code/7.8.27"], ["X-KILOCODE-EDITORNAME", "Kilo CLI 7.8.27"]] }, + // cline/cline sdk/packages/llms/src/providers/cline-client-headers.ts, desktop client + { name: "Cline", headers: [["HTTP-Referer", "https://cline.bot"], ["X-Title", "Cline"], ["X-IS-MULTIROOT", "false"], ["X-CLIENT-TYPE", "cline-desktop"], ["X-CLIENT-VERSION", "3.5.54"], ["User-Agent", "Cline/3.5.54"]] }, + // RooCodeInc/Roo-Code src/api/providers/constants.ts DEFAULT_HEADERS; src/package.json 3.53.0 + { name: "Roo Code", headers: [["HTTP-Referer", "https://github.com/RooVetGit/Roo-Cline"], ["X-Title", "Roo Code"], ["User-Agent", "RooCode/3.53.0"]] }, + // CherryHQ/cherry-studio src/main/utils/http.ts defaultAppHeaders + { name: "Cherry Studio", headers: [["HTTP-Referer", "https://cherry-ai.com"], ["X-Title", "Cherry Studio"]] }, +]; +// applyHeaderPreset adds a preset's headers to the draft: a header the draft +// already has with a value keeps the user's own, one with no value yet is +// filled, the rest become rows. +function applyHeaderPreset(rows, preset) { + for (let i = rows.length - 1; i >= 0; i--) if (!(rows[i][0] || "").trim() && !(rows[i][1] || "").trim()) rows.splice(i, 1); + for (const [k, v] of preset.headers) { + const had = rows.find((r) => (r[0] || "").trim().toLowerCase() === k.toLowerCase()); + if (!had) rows.push([k, v, false]); + else if (!(had[1] || "").trim()) had[1] = v; + } +} +window.headerPresetsOpen = function open(b, rows, redraw) { + openProtoMenu(b, HEADER_PRESETS.map((p) => ({ v: p.name, name: p.name, literalName: true, note: "" })), "", (v) => { + applyHeaderPreset(rows, HEADER_PRESETS.find((p) => p.name === v)); + redraw(); + }, "Presets"); +}; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index df1c128ff..2eaf8de74 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2664,6 +2664,7 @@ const I18N = { "value": "值", "Remove header": "删除请求头", "+ Add header": "+ 添加请求头", + "Presets": "预设", "Add the {h} header; its value is yours to fill in": "添加 {h} 请求头,值由你填写", "Optional headers sent with every request to {p}, applied after auth. ${sessionId} in a value is the conversation's id; ${threadId} is the thread's, where the agent names one (Codex), else the same.": "随每个发往 {p} 的请求发送的可选请求头,在鉴权之后应用。值里的 ${sessionId} 是会话的 ID;${threadId} 是线程的 ID(智能体单独给出时,如 Codex),否则与会话 ID 相同。", "Extra body": "额外请求体", @@ -7663,6 +7664,7 @@ const I18N = { "value": "值", "Remove header": "刪除請求頭", "+ Add header": "+ 新增請求頭", + "Presets": "預設", "Add the {h} header; its value is yours to fill in": "新增 {h} 請求頭,值由你填寫", "Optional headers sent with every request to {p}, applied after auth. ${sessionId} in a value is the conversation's id; ${threadId} is the thread's, where the agent names one (Codex), else the same.": "隨每個發往 {p} 的請求傳送的可選請求頭,在鑑權之後應用。值裡的 ${sessionId} 是對話的 ID;${threadId} 是執行緒的 ID(代理單獨給出時,如 Codex),否則與對話 ID 相同。", "Extra body": "額外請求體", @@ -12638,6 +12640,7 @@ const I18N = { "value": "値", "Remove header": "ヘッダーを削除", "+ Add header": "+ ヘッダーを追加", + "Presets": "プリセット", "Add the {h} header; its value is yours to fill in": "{h} ヘッダーを追加します。値は自分で入力してください", "Optional headers sent with every request to {p}, applied after auth. ${sessionId} in a value is the conversation's id; ${threadId} is the thread's, where the agent names one (Codex), else the same.": "{p} へのすべてのリクエストに付ける任意のヘッダー。認証の後に適用されます。値の中の ${sessionId} は会話の ID、${threadId} はスレッドの ID です(エージェントが別に示す場合。Codex など)。示さない場合は会話の ID と同じです。", "Extra body": "追加ボディ", @@ -17644,6 +17647,7 @@ const I18N = { "value": "Wert", "Remove header": "Header entfernen", "+ Add header": "+ Header hinzufügen", + "Presets": "Vorlagen", "Add the {h} header; its value is yours to fill in": "Header {h} hinzufügen; den Wert tragen Sie selbst ein", "Optional headers sent with every request to {p}, applied after auth. ${sessionId} in a value is the conversation's id; ${threadId} is the thread's, where the agent names one (Codex), else the same.": "Optionale Header, die mit jeder Anfrage an {p} gesendet und nach der Authentifizierung angewendet werden.${sessionId} in einem Wert ist die ID der Unterhaltung; ${threadId} die des Threads, wo der Agent einen eigenen nennt (Codex), sonst dieselbe.", "Extra body": "Zusätzlicher Body", diff --git a/internal/gui/tests/header-presets.test.cjs b/internal/gui/tests/header-presets.test.cjs new file mode 100644 index 000000000..c66978046 --- /dev/null +++ b/internal/gui/tests/header-presets.test.cjs @@ -0,0 +1,89 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Presets in a provider's Headers (l3123109756 on X): a small Presets menu +// fills in what a common client sends. A header the user already set keeps +// its value, a blank row is filled, none of the presets imitates Claude +// Code. In English, Chinese, Traditional Chinese, Japanese and German, +// Chromium and WebKit, wide and narrow. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const gw = { + id: "azgw", name: "Azure Gateway", preset: "", icon: "generic", chat: "", responses: "https://gw.example.com/v1", anthropic: "", catalog: "", baseAPI: "responses", + models: [{ id: "gpt-5.1", name: "gpt-5.1", on: true }], agents: [], fallback: [], headers: { "User-Agent": "mine/1", "X-Title": "" }, + key: { set: true, masked: "sk-…one" }, keyList: [{ id: "k1", name: "", masked: "sk-…one", on: true, active: true }], + balanceToken: { takes: false, set: false }, proxy: "", +}; + +function serve(lang, calls) { + const providers = { providers: [gw], presets: [], excluded: [], gateway: { running: true, window: true } }; + const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname.startsWith("/api/provider/")) { + calls.push([url.pathname.slice(14), route.request().postDataJSON()]); + if (url.pathname === "/api/provider/save") return json(providers); + } + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const label = { en: "Presets", zh: "预设", "zh-TW": "預設", ja: "プリセット", de: "Vorlagen" }; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(label)) { + for (const width of [900, 420]) { + test(`${engine} ${lang} ${width}px: Presets fills a client's headers and keeps the user's own`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], calls = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, calls)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: "Azure Gateway" }).click(); + const ed = page.locator(".editor"); + await ed.locator(".headers").waitFor({ state: "attached" }); + + // a click Playwright scrolls to would close the menu with that scroll + await ed.locator(".headers .hpresets").scrollIntoViewIfNeeded(); + await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))); + await ed.locator(".headers .hpresets").click(); + assert.equal(await ed.locator(".headers .hpresets").textContent(), label[lang]); + await page.locator(".proto-menu .pm-name").first().waitFor(); + const items = await page.locator(".proto-menu .pm-name").allTextContents(); + assert.deepEqual(items, ["Codex CLI", "Gemini CLI", "OpenCode", "Kilo Code", "Cline", "Roo Code", "Cherry Studio"]); + assert.ok(!items.some((n) => /claude/i.test(n)), "no Claude Code preset"); + await page.locator(".proto-menu .pm-item", { hasText: "Kilo Code" }).click(); + assert.equal(await page.locator(".proto-menu").count(), 0, "the menu closes"); + + await ed.locator(".bar").getByRole("button", { name: { en: "Save", zh: "保存", "zh-TW": "儲存", ja: "保存", de: "Speichern" }[lang], exact: true }).click(); + for (let i = 0; i < 60 && !calls.some((c) => c[0] === "save"); i++) await page.waitForTimeout(50); + const saved = calls.find((c) => c[0] === "save"); + assert.ok(saved, "saved"); + assert.deepEqual(saved[1].headers, { + "User-Agent": "mine/1", // the user's own value stays + "X-Title": "Kilo Code", // an empty one is filled + "HTTP-Referer": "https://kilocode.ai", + "X-KILOCODE-EDITORNAME": "Kilo CLI 7.8.27", + }); + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth), "no sideways scroll"); + assert.deepEqual(errors, []); + }); + } + } +}