Skip to content

🤖 Open-source, local-first alternative to Grok Bot, OpenAI dots and Claude Duet. Your own AI bots on any model: GPT, Claude, Gemini, Grok, DeepSeek, Kimi, GLM and 70+ more through one Modelflare key. Reach them in the app, WeChat or Feishu; they remember you, work in the background, run commands and use your computer. Pay per use.

feat: model picker sliders for value and intelligence along the Pareto frontier

Marla5758d76dc604
diff --git a/assets/model-quality.json b/assets/model-quality.json
new file mode 100644
index 0000000..2c636aa
--- /dev/null
+++ b/assets/model-quality.json
@@ -0,0 +1,202 @@
+{
+ "updatedAt": "2026-11-02",
+ "source": "https://artificialanalysis.ai/leaderboards/models",
+ "attribution": "Artificial Analysis (artificialanalysis.ai)",
+ "models": {
+ "claude-fable-5-1": {
+ "aa": "claude-fable-5-1",
+ "name": "Claude Fable 5.1",
+ "default": {
+ "variant": "max",
+ "intelligence": 49,
+ "costPerTask": 12.99
+ },
+ "medium": {
+ "intelligence": 43,
+ "costPerTask": 5.56
+ }
+ },
+ "claude-haiku-5-5": {
+ "aa": "claude-haiku-5-5",
+ "name": "Claude Haiku 5.5",
+ "default": {
+ "variant": "max",
+ "intelligence": 36,
+ "costPerTask": 0.41
+ },
+ "medium": {
+ "intelligence": 25,
+ "costPerTask": 0.09
+ }
+ },
+ "claude-opus-5-5": {
+ "aa": "claude-opus-5-5",
+ "name": "Claude Opus 5.5",
+ "default": {
+ "variant": "max",
+ "intelligence": 58,
+ "costPerTask": 10.04
+ },
+ "medium": {
+ "intelligence": 48,
+ "costPerTask": 2.45
+ }
+ },
+ "claude-sonnet-5-5": {
+ "aa": "claude-sonnet-5-5",
+ "name": "Claude Sonnet 5.5",
+ "default": {
+ "variant": "max",
+ "intelligence": 54,
+ "costPerTask": 10.02
+ },
+ "medium": {
+ "intelligence": 30,
+ "costPerTask": 0.78
+ }
+ },
+ "deepseek-v4-pro": {
+ "aa": "deepseek-v4-pro",
+ "name": "DeepSeek V4 Pro 0813",
+ "default": {
+ "variant": "max",
+ "intelligence": 23,
+ "costPerTask": 1.77
+ }
+ },
+ "deepseek-v4.1-flash": {
+ "aa": "deepseek-v4-1-flash-1017",
+ "name": "DeepSeek V4.1 Flash 1017",
+ "default": {
+ "variant": "max",
+ "intelligence": 32,
+ "costPerTask": 0.6
+ }
+ },
+ "gemini-3.5-flash-lite": {
+ "aa": "gemini-3-5-flash-lite",
+ "name": "Gemini 3.5 Flash-Lite",
+ "default": {
+ "intelligence": 12,
+ "costPerTask": 0.69
+ }
+ },
+ "gemini-3.8-flash": {
+ "aa": "gemini-3-8-flash",
+ "name": "Gemini 3.8 Flash",
+ "default": {
+ "variant": "high",
+ "intelligence": 31,
+ "costPerTask": 7.77
+ },
+ "medium": {
+ "intelligence": 30,
+ "costPerTask": 6.26
+ }
+ },
+ "gemini-3.8-flash-high": {
+ "aa": "gemini-3-8-flash",
+ "name": "Gemini 3.8 Flash",
+ "default": {
+ "variant": "high",
+ "intelligence": 31,
+ "costPerTask": 7.77
+ }
+ },
+ "gemini-4-argon": {
+ "aa": "gemini-4-argon",
+ "name": "Gemini 4 Argon",
+ "default": {
+ "variant": "high",
+ "intelligence": 50,
+ "costPerTask": 7.68
+ }
+ },
+ "glm-5.3": {
+ "aa": "glm-5-3",
+ "name": "GLM-5.3",
+ "default": {
+ "variant": "max",
+ "intelligence": 32,
+ "costPerTask": 5.01
+ }
+ },
+ "glm-5.3-flash": {
+ "aa": "glm-5-3-flash",
+ "name": "GLM-5.3-Flash",
+ "default": {
+ "intelligence": 28,
+ "costPerTask": 0.58
+ }
+ },
+ "gpt-6-astra": {
+ "aa": "gpt-6-astra",
+ "name": "GPT-6 Astra",
+ "default": {
+ "variant": "max",
+ "intelligence": 57,
+ "costPerTask": 6.24
+ },
+ "medium": {
+ "intelligence": 51,
+ "costPerTask": 2.73
+ }
+ },
+ "gpt-6-luna": {
+ "aa": "gpt-6-luna",
+ "name": "GPT-6 Luna",
+ "default": {
+ "variant": "max",
+ "intelligence": 28,
+ "costPerTask": 0.15
+ },
+ "medium": {
+ "intelligence": 18,
+ "costPerTask": 0.04
+ }
+ },
+ "gpt-6.1-sol": {
+ "aa": "gpt-6-1-sol",
+ "name": "GPT-6.1 Sol",
+ "default": {
+ "variant": "max",
+ "intelligence": 55,
+ "costPerTask": 1.27
+ },
+ "medium": {
+ "intelligence": 46,
+ "costPerTask": 0.36
+ }
+ },
+ "gpt-6.1-terra": {
+ "aa": "gpt-6-1-terra",
+ "name": "GPT-6.1 Terra",
+ "default": {
+ "variant": "max",
+ "intelligence": 51,
+ "costPerTask": 0.96
+ },
+ "medium": {
+ "intelligence": 38,
+ "costPerTask": 0.17
+ }
+ },
+ "grok-4.7": {
+ "aa": "grok-4-7",
+ "name": "Grok 4.7",
+ "default": {
+ "variant": "xhigh",
+ "intelligence": 34,
+ "costPerTask": 7.51
+ }
+ },
+ "qwen3.8-max": {
+ "aa": "qwen3-8-max",
+ "name": "Qwen3.8 Max (0902)",
+ "default": {
+ "intelligence": 34,
+ "costPerTask": 10.02
+ }
+ }
+ }
+}
diff --git a/docs/development.md b/docs/development.md
index 3452602..35e79b0 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -103,6 +103,9 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令
- **飞书**(`feishu-account.ts`):和官方 lark-cli 同一套流程:扫码创建个人应用(也可以填已有的自建应用),再设备授权拿用户令牌。只读,工具是 `feishu_list_chats`、`feishu_read_chat`、`feishu_search_messages`。
- 默认图片 / 视频模型:首次设置时和默认文本模型一起选,之后在 设置 → Modelflare 修改;选「自动」时用推荐顺序里第一个不需要参考素材的模型。
- 模型选择器里显示上下文长度、视觉 / 工具 / 推理能力,以及每百万 tokens 输入 / 输出的起步参考价(来自公开价格目录,以账单为准)。
+- 性价比(需要登录):应用签发的 Key(本机 Key 和各机器人的预算 Key)都带 Modelflare Smart Key 的路由策略 `routing_strategy`——省钱 `low_cost`(倍率最低的分组先试)、均衡 `balanced`(默认,从价格居中的分组开始)、质量 `stable`(倍率最高的先试)。在 设置 → Modelflare → 性价比 或模型选择器的第一个滑块里改,改的时候连同已有的 Key 一起改(`PATCH /api/connected-app/api-keys/<id>`),选择存在本机数据库(`account.routing`)。没选过的老用户第一次核对 Key 时把均衡应用到已有的 Key 上,只这一次(日志 `applied the default key routing strategy`)。Modelflare 回显了 `routing_strategy` 才算支持;拒绝(400 / 422)时不带这个字段再签一次,签发、核对、预算都不会因此失败,忽略(不回显)也一样记为不支持,这时界面不显示这个设置,一天后再试一次。
+- 模型智能(模型选择器的第二个滑块):在这个账户能用、又有 Artificial Analysis 数据的模型里,按智能指数(越高越好)和每次任务的花费(越低越好)取帕累托前沿,最多 5 档,最便宜的和最强的总在。智能取应用实际用的那一档:走 Responses 接口的推理模型默认发 medium,就用 AA 的 medium 那一行,其余用 AA 的默认那一行(`src/account/model-quality.ts`)。花费 = AA 的每次任务花费(官方定价)× 这个模型在当前性价比下的价格比例(可用公开分组的倍率 × 售价倍率:省钱取最低,质量取最高,均衡取居中;企业专用分组不算;没登录或不支持时按均衡估)。拖到哪一档就把模型换成那个;点模型名进完整列表,照样手动选,选了不在档上的模型时滑块显示「自定义」。前沿不到两档时选择器直接是列表。算法在 `ui/lib/frontier.js`。
+- AA 数据在仓库里:`assets/model-quality.json`(`updatedAt`、`source`、只留用得到的字段,已经按 Modelflare 的模型 ID 对应好)。刷新:`node scripts/update-model-quality.mjs`,默认抓公开排行榜页面 https://artificialanalysis.ai/leaderboards/models 和 Modelflare 的公开价格目录;设了 `AA_API_KEY` 时改用官方 API(字段还没有拿 Key 核对过)。`--html <文件>`、`--pricing <文件>` 用保存下来的页面和目录,`--dry-run` 只打印。页面结构变了(找不到列、行的形状不对、数字解析不出来、行数太少、对上的模型太少)时退出码为 1 并说明是哪一项,原来的快照不动。名字按规则对不上的模型写在脚本的 `OVERRIDES` 里。数据来自 Artificial Analysis,选择器底部注明出处。
- 调用归因:经 Modelflare 的请求都带 `X-Modelflare-Skill: anymodel-bot/<版本>`,链接都带 `utm_source=anymodelbot&utm_campaign=amb_<位置>`(应用内 `amb_signup`、`amb_topup`、`amb_console` 等,README 与仓库文档 `amb_readme`,官网 `amb_homepage`;格式由 `test/utm.unit.test.ts` 固定)。
- 线路:默认国际线路 `https://modelflare.dev/v1`;中国大陆可在「高级」或 设置 → Modelflare → 线路 选「中国大陆优化」(`https://origin.modelflare.dev/v1`)。线路由你选定,不自动切换。
- 设置 → Modelflare:账户、余额与充值、余额提醒、用量、通知、邀请;连接状态(只显示 Key 尾号);未登录时可更换密钥或断开(机器人与会话保留,断开后回到首次连接页);默认模型、刷新模型列表。
diff --git a/docs/development_en.md b/docs/development_en.md
index 482be0b..f2068b4 100644
--- a/docs/development_en.md
+++ b/docs/development_en.md
@@ -103,6 +103,9 @@ Inside the container the console listens on 0.0.0.0, so token access is enforced
- **Feishu** (`feishu-account.ts`): the same flow as the official lark-cli: scan to create a personal app (or enter your own app), then device authorization for a user token. Read-only, with `feishu_list_chats`, `feishu_read_chat` and `feishu_search_messages`.
- Default image / video models: chosen together with the default text model during first-run setup, changeable later in Settings → Modelflare. "Auto" uses the first model in the recommended order that needs no reference material.
- The model picker shows context length, vision / tools / reasoning capabilities, and starting reference prices per million input / output tokens (from the public price catalog; your bill is authoritative).
+- Value (requires sign-in): keys the app issues (this computer's key and each bot's budget key) carry the Modelflare Smart Key routing strategy `routing_strategy`: Cheap `low_cost` (lowest-multiplier group first), Balanced `balanced` (the default; starts from the mid-priced group) or Quality `stable` (highest multiplier first). Change it in Settings → Modelflare → Value or with the first slider in the model picker; existing keys are updated along with it (`PATCH /api/connected-app/api-keys/<id>`), and the choice is stored in the local database (`account.routing`). Signed-in users who never chose get Balanced applied to their existing keys once, at the first key check (logged as `applied the default key routing strategy`). Support counts only when Modelflare echoes `routing_strategy` back; if it rejects the field (400 / 422) the key is issued again without it, so issuing, key checks and budgets never fail because of it. If it ignores the field (no echo) that also counts as unsupported. Either way the setting is hidden and retried a day later.
+- Intelligence (the model picker's second slider): among models this account can use that have Artificial Analysis data, it takes the Pareto frontier of intelligence index (higher is better) and cost per task (lower is better), up to 5 stops, always including the cheapest and the strongest. Intelligence is taken for the effort the app actually uses: reasoning models on the Responses API get medium by default, so AA's medium row is used; everything else uses AA's default row (`src/account/model-quality.ts`). Cost = AA's cost per task (official list prices) × the model's price factor under the current Value setting (the multiplier of its usable public groups × its sale multiplier: lowest for Cheap, highest for Quality, the middle one for Balanced; enterprise-only groups are left out; when signed out or unsupported, Balanced is assumed). Moving the slider switches to that stop's model; the model name opens the full list for manual choice, and a model that isn't a stop shows as Custom. With fewer than two stops the picker is just the list. The math is in `ui/lib/frontier.js`.
+- AA data ships in the repo as `assets/model-quality.json` (`updatedAt`, `source`, only the fields we use, already mapped to Modelflare model IDs). Refresh it with `node scripts/update-model-quality.mjs`, which fetches the public leaderboard https://artificialanalysis.ai/leaderboards/models and Modelflare's public price catalog; with `AA_API_KEY` set it uses the official API instead (its fields haven't been checked with a key yet). `--html <file>` and `--pricing <file>` use saved copies, `--dry-run` only prints. If the page changes shape (a missing column, rows of the wrong shape, numbers that don't parse, too few rows or too few matched models) it exits 1 naming what was wrong and leaves the existing snapshot untouched. Models whose names don't map by the rules go in the script's `OVERRIDES`. The data is from Artificial Analysis, credited at the bottom of the picker.
- Attribution: requests through Modelflare carry `X-Modelflare-Skill: anymodel-bot/<version>`, and links carry `utm_source=anymodelbot&utm_campaign=amb_<placement>` (`amb_signup`, `amb_topup`, `amb_console` and so on inside the app, `amb_readme` for the README and repository docs, `amb_homepage` for the website; `test/utm.unit.test.ts` pins the format).
- Routes: the international route `https://modelflare.dev/v1` is the default; in mainland China you can pick "Optimized for mainland China" (`https://origin.modelflare.dev/v1`) under Advanced or Settings → Modelflare → Route. You choose the route; it never switches automatically.
- Settings → Modelflare: account, balance and top-up, balance reminder, usage, notifications, invites; connection status (only the key's last characters are shown); when not signed in you can replace the key or disconnect (bots and sessions are kept; disconnecting returns to the first-connection screen); default model, refresh model list.
diff --git a/scripts/update-model-quality.mjs b/scripts/update-model-quality.mjs
new file mode 100644
index 0000000..a5dac9b
--- /dev/null
+++ b/scripts/update-model-quality.mjs
@@ -0,0 +1,243 @@
+#!/usr/bin/env node
+// 刷新模型智能快照 assets/model-quality.json(模型选择器的「模型智能」滑块用)。无第三方依赖。
+//
+// node scripts/update-model-quality.mjs 抓 Artificial Analysis 的公开排行榜页面和 Modelflare 的公开价格目录,写快照
+// AA_API_KEY=… node scripts/update-model-quality.mjs 改用 AA 的官方 API(字段没有核对过,见 fromApi)
+// --html <file> 用保存下来的排行榜页面,不去抓
+// --pricing <file> 用保存下来的 Modelflare 价格目录(https://modelflare.dev/api/pricing),不去抓
+// --out <file> 写到别处(默认 assets/model-quality.json)
+// --dry-run 只打印结果,不写文件
+//
+// 页面结构变了(找不到某一列、行的形状不对、数字解析不出来、行数太少、对上的模型太少)时退出码为 1,
+// 说清楚是哪一项不对,原来的快照不动。
+//
+// 快照只留用得到的:每个 Modelflare 模型 ID 对应的 AA 模型,它默认那一档(链接里没有档位后缀的那一行)和 medium
+// 那一档的智能指数(Artificial Analysis Intelligence Index)与每次任务的花费(Cost per Task,美元,官方定价)。
+// 对应规则:小写、点换成横线(gpt-6.1-sol → gpt-6-1-sol);ID 末尾带档位的(gemini-3.8-flash-high)对应那一档;
+// 名字对不上的写在 OVERRIDES 里。数据来自 Artificial Analysis,界面上注明出处(他们的免费数据要求署名)。
+
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+export const PAGE_URL = "https://artificialanalysis.ai/leaderboards/models";
+export const API_URL = "https://artificialanalysis.ai/api/v2/data/llms/models";
+export const PRICING_URL = "https://modelflare.dev/api/pricing";
+const UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36";
+
+/** Modelflare 的 ID 和 AA 的 slug 按规则对不上的:Modelflare ID → AA slug(不带档位) */
+export const OVERRIDES = {
+ "deepseek-v4.1-flash": "deepseek-v4-1-flash-1017",
+};
+
+/** 档位:AA 名字括号里的第一个这类词("max with fallback" → max) */
+const EFFORTS = ["minimal", "low", "medium", "high", "xhigh", "max", "non-reasoning"];
+/** 合格的门槛:低于这些说明页面结构变了,不写快照 */
+export const LIMITS = { minRows: 50, minNumeric: 30, numericShare: 0.9, minMapped: 5 };
+
+export class ShapeError extends Error {}
+
+const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
+const textOf = (cell) =>
+ cell
+ .replace(/<[^>]+>/g, " ")
+ .replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (m, e) => (e[0] === "#" ? String.fromCodePoint(e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : Number(e.slice(1))) : (ENTITIES[e.toLowerCase()] ?? m)))
+ .replace(/\s+/g, " ")
+ .trim();
+
+/** "59" → 59,"$7.76" → 7.76,"--" / 空 → null,其他 → NaN(解析失败) */
+export function numberOf(s) {
+ const v = String(s ?? "").trim();
+ if (!v || v === "--" || v === "—" || v === "-") return null;
+ const n = Number(v.replace(/^\$/, "").replace(/,/g, ""));
+ return Number.isFinite(n) ? n : NaN;
+}
+
+/** "GPT-6 Astra (high)" → { base: "GPT-6 Astra", variant: "high" };括号里没有档位词("(0902)")时 variant 为空 */
+export function splitVariant(name) {
+ const m = name.match(/^(.*?)\s*\(([^)]*)\)\s*$/);
+ if (!m) return { base: name, variant: "" };
+ const variant = m[2].toLowerCase().split(/[\s,]+/).find((w) => EFFORTS.includes(w)) ?? "";
+ return variant ? { base: m[1], variant } : { base: name, variant: "" };
+}
+
+/**
+ * 解析排行榜页面的表格:按表头文字找列(Model、Artificial Analysis Intelligence Index、Cost per Task),
+ * 每行取名字、档位、slug(/models/<slug> 链接)、智能指数与每次任务的花费。结构不对时抛 ShapeError。
+ */
+export function parseLeaderboard(html) {
+ const table = html.match(/<table[\s\S]*?<\/table>/i)?.[0];
+ if (!table) throw new ShapeError("no <table> on the leaderboard page");
+ const rows = [...table.matchAll(/<tr[^>]*>([\s\S]*?)<\/tr>/gi)].map((m) => m[1]);
+ const cellsOf = (row) => [...row.matchAll(/<t[hd][^>]*>([\s\S]*?)<\/t[hd]>/gi)].map((m) => m[1]);
+ const headAt = rows.findIndex((r) => cellsOf(r).some((c) => /^Model$/i.test(textOf(c))));
+ if (headAt < 0) throw new ShapeError('no header row with a "Model" column');
+ const head = cellsOf(rows[headAt]).map(textOf);
+ const col = (label, re) => {
+ const i = head.findIndex((h) => re.test(h));
+ if (i < 0) throw new ShapeError(`missing column "${label}" (header: ${head.join(" | ")})`);
+ return i;
+ };
+ const cName = col("Model", /^Model$/i);
+ const cIntel = col("Artificial Analysis Intelligence Index", /Intelligence Index/i);
+ const cCost = col("Cost per Task", /Cost per Task/i);
+ const body = rows.slice(headAt + 1);
+ const out = [];
+ let badShape = 0;
+ let noLink = 0;
+ for (const r of body) {
+ const cells = cellsOf(r);
+ if (cells.length !== head.length) {
+ badShape++;
+ continue;
+ }
+ const slug = r.match(/href="\/models\/([a-z0-9][a-z0-9.-]*)"/i)?.[1]?.toLowerCase();
+ if (!slug) {
+ noLink++;
+ continue;
+ }
+ const name = textOf(cells[cName]);
+ out.push({ name, slug, ...splitVariant(name), intelligence: numberOf(textOf(cells[cIntel])), costPerTask: numberOf(textOf(cells[cCost])) });
+ }
+ if (badShape > body.length * 0.1) throw new ShapeError(`${badShape} of ${body.length} rows don't have the ${head.length} header columns`);
+ if (noLink > body.length * 0.1) throw new ShapeError(`${noLink} of ${body.length} rows have no /models/<slug> link`);
+ return out;
+}
+
+/**
+ * AA 官方 API(/api/v2/data/llms/models,要 x-api-key)的行。没有 Key 核对过字段:智能指数取
+ * evaluations.artificial_analysis_intelligence_index,每次任务的花费认这几个名字;一个都没有时抛错(别用页面以外的东西猜)。
+ */
+export function fromApi(json) {
+ const list = Array.isArray(json?.data) ? json.data : Array.isArray(json) ? json : null;
+ if (!list) throw new ShapeError("API response has no data array");
+ const cost = (m) => m.cost_per_task_usd ?? m.cost_per_task ?? m.evaluations?.cost_per_task ?? m.pricing?.cost_per_task;
+ if (!list.some((m) => cost(m) !== undefined)) throw new ShapeError("API response has no cost per task; unset AA_API_KEY to use the public page");
+ return list.map((m) => {
+ const name = String(m.name ?? "");
+ const num = (v) => (v === null || v === undefined ? null : Number.isFinite(Number(v)) ? Number(v) : NaN);
+ return { name, slug: String(m.slug ?? "").toLowerCase(), ...splitVariant(name), intelligence: num(m.evaluations?.artificial_analysis_intelligence_index), costPerTask: num(cost(m)) };
+ });
+}
+
+/** 数字列的健康检查:有值(不是 --)的格子绝大多数要解析得出数字,而且够多行两个都有 */
+export function checkRows(rows) {
+ if (rows.length < LIMITS.minRows) throw new ShapeError(`only ${rows.length} rows (need at least ${LIMITS.minRows})`);
+ for (const [key, label] of [["intelligence", "Intelligence Index"], ["costPerTask", "Cost per Task"]]) {
+ const filled = rows.filter((r) => r[key] !== null);
+ const ok = filled.filter((r) => Number.isFinite(r[key]));
+ if (ok.length < LIMITS.minNumeric) throw new ShapeError(`only ${ok.length} rows have a number in "${label}" (need at least ${LIMITS.minNumeric})`);
+ if (ok.length < filled.length * LIMITS.numericShare) throw new ShapeError(`"${label}" didn't parse as a number in ${filled.length - ok.length} of ${filled.length} filled rows`);
+ }
+ const both = rows.filter((r) => Number.isFinite(r.intelligence) && Number.isFinite(r.costPerTask)).length;
+ if (both < LIMITS.minNumeric) throw new ShapeError(`only ${both} rows have both an intelligence index and a cost per task`);
+}
+
+/** 按模型归组:slug 去掉档位后缀就是这个模型(gpt-6-astra-medium → gpt-6-astra);默认那一档是 slug 不带后缀的那一行 */
+export function groupRows(rows) {
+ const groups = new Map();
+ for (const r of rows) {
+ const base = r.variant && r.slug.endsWith(`-${r.variant}`) ? r.slug.slice(0, -r.variant.length - 1) : r.slug;
+ const g = groups.get(base) ?? { name: r.base, rows: {} };
+ if (r.slug === base) g.default = r;
+ if (r.variant && !g.rows[r.variant]) g.rows[r.variant] = r;
+ groups.set(base, g);
+ }
+ return groups;
+}
+
+/** Modelflare ID → 对应规则下的 AA slug:去掉前缀、小写、点和下划线换成横线 */
+export function normalizeId(id) {
+ return String(id).replace(/^.*\//, "").toLowerCase().replace(/[._\s]+/g, "-");
+}
+
+/** 一个 Modelflare 模型对应哪个 AA 模型;ID 末尾带档位的(-high)固定取那一档。对不上时 undefined */
+export function mapModel(id, groups) {
+ const want = OVERRIDES[id] ?? normalizeId(id);
+ if (groups.has(want)) return { base: want };
+ const m = want.match(/-(minimal|low|medium|high|xhigh|max)$/);
+ if (m && groups.has(want.slice(0, -m[0].length))) return { base: want.slice(0, -m[0].length), variant: m[1] };
+ return undefined;
+}
+
+const usable = (r) => r && Number.isFinite(r.intelligence) && Number.isFinite(r.costPerTask) && r.costPerTask >= 0;
+const pick = (r) => ({ intelligence: r.intelligence, costPerTask: r.costPerTask });
+
+/** 生成快照:只含对得上、而且有数字的 Modelflare 模型 */
+export function buildSnapshot(rows, modelIds, { updatedAt, source }) {
+ const groups = groupRows(rows);
+ const models = {};
+ for (const id of [...new Set(modelIds)].sort()) {
+ const hit = mapModel(id, groups);
+ if (!hit) continue;
+ const g = groups.get(hit.base);
+ let entry;
+ if (hit.variant) {
+ const r = g.default?.variant === hit.variant ? g.default : g.rows[hit.variant];
+ if (usable(r)) entry = { aa: hit.base, name: g.name, default: { variant: hit.variant, ...pick(r) } };
+ } else {
+ const d = usable(g.default) ? { variant: g.default.variant || undefined, ...pick(g.default) } : undefined;
+ const med = g.rows.medium && g.rows.medium !== g.default && usable(g.rows.medium) ? pick(g.rows.medium) : undefined;
+ if (d || med) entry = { aa: hit.base, name: g.name, ...(d ? { default: d } : {}), ...(med ? { medium: med } : {}) };
+ }
+ if (entry) models[id] = entry;
+ }
+ return { updatedAt, source, attribution: "Artificial Analysis (artificialanalysis.ai)", models };
+}
+
+/** Modelflare 价格目录里的模型 ID */
+export function modelflareIds(pricing) {
+ const list = Array.isArray(pricing?.data) ? pricing.data : null;
+ if (!list) throw new ShapeError("Modelflare pricing catalog has no data array");
+ return list.map((e) => String(e.model_name ?? "")).filter(Boolean);
+}
+
+async function get(url, headers) {
+ const res = await fetch(url, { headers, signal: AbortSignal.timeout(30_000) });
+ if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`);
+ return res;
+}
+
+async function main(argv) {
+ const arg = (name) => {
+ const i = argv.indexOf(name);
+ return i >= 0 ? argv[i + 1] : undefined;
+ };
+ const out = path.resolve(arg("--out") ?? path.join(ROOT, "assets", "model-quality.json"));
+ const htmlFile = arg("--html");
+ const pricingFile = arg("--pricing");
+ const key = process.env.AA_API_KEY?.trim();
+
+ let rows;
+ let source;
+ if (key && !htmlFile) {
+ rows = fromApi(await (await get(API_URL, { "x-api-key": key, Accept: "application/json" })).json());
+ source = API_URL;
+ } else {
+ const html = htmlFile ? fs.readFileSync(htmlFile, "utf8") : await (await get(PAGE_URL, { "User-Agent": UA, Accept: "text/html,application/xhtml+xml", "Accept-Language": "en-US,en;q=0.9" })).text();
+ rows = parseLeaderboard(html);
+ source = PAGE_URL;
+ }
+ checkRows(rows);
+ const pricing = pricingFile ? JSON.parse(fs.readFileSync(pricingFile, "utf8")) : await (await get(PRICING_URL, { Accept: "application/json" })).json();
+ const snap = buildSnapshot(rows, modelflareIds(pricing), { updatedAt: new Date().toISOString().slice(0, 10), source });
+ const mapped = Object.keys(snap.models);
+ if (mapped.length < LIMITS.minMapped) throw new ShapeError(`only ${mapped.length} Modelflare models matched an AA entry (need at least ${LIMITS.minMapped})`);
+
+ const text = JSON.stringify(snap, null, 2) + "\n";
+ console.log(`${rows.length} AA rows, ${mapped.length} Modelflare models matched: ${mapped.join(", ")}`);
+ if (argv.includes("--dry-run")) return void console.log(text);
+ const tmp = `${out}.${process.pid}.tmp`;
+ fs.writeFileSync(tmp, text);
+ fs.renameSync(tmp, out);
+ console.log(`wrote ${path.relative(process.cwd(), out) || out}`);
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
+ main(process.argv.slice(2)).catch((e) => {
+ console.error(`update-model-quality: ${e instanceof ShapeError ? "the source changed shape: " : ""}${e.message}`);
+ console.error("the existing snapshot was left untouched");
+ process.exit(1);
+ });
+}
diff --git a/src/account/model-info.ts b/src/account/model-info.ts
index 37d3ab0..2208c48 100644
--- a/src/account/model-info.ts
+++ b/src/account/model-info.ts
@@ -5,7 +5,12 @@
* 只算按 token 计费和按次计费的模型:价格 = 基础价 × 该模型可用公开分组里最低的分组倍率 ×
* 模型售价倍率,单位美元 / 百万 tokens(按次为美元 / 次)。这是“起步参考价”,实际以账单为准;
* 阶梯计费、图片、视频等复杂计费不展示价格。
+ * - 模型智能与每次任务的花费(「模型智能」滑块):Artificial Analysis 的快照(model-quality.ts),花费再乘上
+ * 这个模型在三种性价比下的分组倍率(factors)。
*/
+import { qualityFor, type QualitySnapshot } from "./model-quality.js";
+import type { RoutingStrategy } from "./client.js";
+
export interface ModelInfo {
context?: number;
vision?: boolean;
@@ -16,6 +21,10 @@ export interface ModelInfo {
rates?: Rates;
/** 支持的接口(目录的 supported_endpoint_types:openai、openai-response、openai-response-compact、anthropic、gemini…) */
endpoints?: string[];
+ /** 三种性价比(Key 的路由策略)下实际付的比例:分组倍率 × 模型售价倍率(strategyFactors) */
+ factors?: Record<RoutingStrategy, number>;
+ /** 应用实际用的那一档的 AA 智能指数与每次任务的花费(官方定价,美元) */
+ quality?: { intelligence: number; costPerTask: number };
}
interface Profile {
@@ -71,6 +80,23 @@ function factorOf(entry: PricingEntry, catalog: PricingCatalog): number | undefi
return Math.min(...ratios) * sale;
}
+/**
+ * 三种性价比下的价格倍率(相对官方定价):这个模型可用的公开分组的倍率 × 模型售价倍率。
+ * 低价优先取最低的分组,稳定优先取最高的,均衡取居中的那个(偶数个时取居中两个里贵的那个:Modelflare 的均衡
+ * 从价格居中的分组开始,先往贵的试)。企业专用的分组(名字带 enterprise)普通账户用不了,不算。
+ */
+export function strategyFactors(entry: PricingEntry, catalog: PricingCatalog): Record<RoutingStrategy, number> | undefined {
+ const ratios = (entry.enable_groups ?? [])
+ .filter((g) => (!catalog.usable_group || g in catalog.usable_group) && !/enterprise/i.test(g))
+ .map((g) => catalog.group_ratio?.[g])
+ .filter((r): r is number => typeof r === "number" && Number.isFinite(r) && r >= 0)
+ .sort((a, b) => a - b);
+ if (!ratios.length) return undefined;
+ const sale = Number(entry.sale_price_multiplier) > 0 ? Number(entry.sale_price_multiplier) : 1;
+ const f = (r: number) => round(r * sale);
+ return { low_cost: f(ratios[0]), balanced: f(ratios[Math.floor(ratios.length / 2)]), stable: f(ratios[ratios.length - 1]) };
+}
+
/** 一个模型的起步参考价;算不出来(复杂计费、没有可用分组)时 undefined */
export function referencePrice(entry: PricingEntry, catalog: PricingCatalog): ModelInfo["price"] {
if (entry.billing_mode || entry.pricing_rules) return undefined;
@@ -127,6 +153,8 @@ export async function loadModelInfo(o: {
apiKey: string;
headers: Record<string, string>;
pricingUrl: string;
+ /** Artificial Analysis 快照(assets/model-quality.json) */
+ quality?: QualitySnapshot;
fetchImpl?: typeof fetch;
}): Promise<Record<string, ModelInfo>> {
const f = o.fetchImpl ?? fetch;
@@ -159,6 +187,13 @@ export async function loadModelInfo(o: {
// 没有 Key(拿不到 model-profiles)时,上下文长度用公开目录里的
if (Number(entry.context_window) > 0 && !out[entry.model_name]?.context) out[entry.model_name] = { ...out[entry.model_name], context: Number(entry.context_window) };
if (Array.isArray(entry.supported_endpoint_types)) out[entry.model_name] = { ...out[entry.model_name], endpoints: entry.supported_endpoint_types.map(String) };
+ const factors = strategyFactors(entry, catalog!);
+ if (factors) out[entry.model_name] = { ...out[entry.model_name], factors };
+ }
+ // 智能与花费:要知道走哪个接口、推理不推理(上面的 endpoints、reasoning),才知道取哪一档
+ for (const [id, entry] of Object.entries(o.quality?.models ?? {})) {
+ const q = out[id]?.factors ? qualityFor(entry, out[id]) : undefined;
+ if (q) out[id] = { ...out[id], quality: q };
}
return out;
}
diff --git a/src/account/model-quality.ts b/src/account/model-quality.ts
new file mode 100644
index 0000000..a7df81f
--- /dev/null
+++ b/src/account/model-quality.ts
@@ -0,0 +1,62 @@
+/**
+ * 模型的智能与每次任务的花费(模型选择器的「模型智能」滑块用)。数据是仓库里的 Artificial Analysis 快照
+ * assets/model-quality.json(scripts/update-model-quality.mjs 生成,已经按 Modelflare 的模型 ID 对应好)。
+ *
+ * 每个模型取哪一档:应用实际用的推理强度。代理走 Responses 接口、模型推理时默认发 medium(agent/host.ts 的
+ * providerProfiles),就取 AA 的 medium 那一行;走 Chat / Anthropic 接口不发推理强度,模型用自己的默认,
+ * 就取 AA 的默认那一行(链接里没有档位后缀的那一行)。没有 medium 那一行时也用默认那一行。
+ */
+import fs from "node:fs";
+import path from "node:path";
+import { findAppRoot } from "../magpie/supervisor.js";
+import { agentApi } from "../agent/host.js";
+
+export interface QualityRow {
+ /** Artificial Analysis Intelligence Index */
+ intelligence: number;
+ /** 跑一次 AA 评测任务的花费(美元,按官方定价) */
+ costPerTask: number;
+}
+
+export interface QualityEntry {
+ /** AA 的模型 slug(不带档位) */
+ aa: string;
+ /** AA 的显示名(不带档位) */
+ name?: string;
+ /** 默认那一行;variant 是它的档位(max、high…,没有档位时为空) */
+ default?: QualityRow & { variant?: string };
+ medium?: QualityRow;
+}
+
+export interface QualitySnapshot {
+ updatedAt: string;
+ source: string;
+ models: Record<string, QualityEntry>;
+}
+
+/** 应用对这个模型发的推理强度:和 providerProfiles 一致,只有 Responses 接口上的推理模型发 medium */
+export function appEffort(info: { endpoints?: string[]; reasoning?: boolean } | undefined): "medium" | undefined {
+ return info && agentApi(info.endpoints) === "openai-responses" && info.reasoning !== false ? "medium" : undefined;
+}
+
+/** 这个模型在应用里的智能与花费:发 medium 且有 medium 那一行时取它,否则取默认那一行 */
+export function qualityFor(entry: QualityEntry | undefined, info: { endpoints?: string[]; reasoning?: boolean } | undefined): QualityRow | undefined {
+ if (!entry) return undefined;
+ const row = (appEffort(info) === "medium" && entry.medium) || entry.default;
+ if (!row || !Number.isFinite(row.intelligence) || !Number.isFinite(row.costPerTask) || row.costPerTask < 0) return undefined;
+ return { intelligence: row.intelligence, costPerTask: row.costPerTask };
+}
+
+let cached: QualitySnapshot | null | undefined;
+
+/** 读仓库里的快照(读一次);文件不在或坏了时 undefined,选择器退回只有列表 */
+export function loadQualitySnapshot(file = path.join(findAppRoot(), "assets", "model-quality.json")): QualitySnapshot | undefined {
+ if (cached !== undefined) return cached ?? undefined;
+ try {
+ const s = JSON.parse(fs.readFileSync(file, "utf8")) as QualitySnapshot;
+ cached = s && typeof s.models === "object" ? s : null;
+ } catch {
+ cached = null;
+ }
+ return cached ?? undefined;
+}
diff --git a/src/app.ts b/src/app.ts
index 8946850..9e1099b 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -44,6 +44,7 @@ import {
import { AccountManager } from "./account/manager.js";
import { AccountVault, type SecretBox } from "./account/vault.js";
import { loadModelInfo, type ModelInfo, type Rates } from "./account/model-info.js";
+import { loadQualitySnapshot } from "./account/model-quality.js";
import { MediaService, pickDefault } from "./agent/media.js";
import { SearchService, loadWebSearch, saveWebSearch, type SearchProvider, type WebSearchSettings, type WebSearchView } from "./agent/search.js";
import { ConnectionService } from "./agent/connections.js";
@@ -566,6 +567,7 @@ export class App {
apiKey: key,
headers: this.requestHeaders(),
pricingUrl: `${modelflareIssuer()}/api/pricing`,
+ quality: loadQualitySnapshot(),
});
this.modelInfoCache = { at: Date.now(), data };
return data;
diff --git a/test/model-quality.unit.test.ts b/test/model-quality.unit.test.ts
new file mode 100644
index 0000000..acff5ae
--- /dev/null
+++ b/test/model-quality.unit.test.ts
@@ -0,0 +1,342 @@
+/**
+ * 模型选择器的两个滑块:沿帕累托前沿挑模型(ui/lib/frontier.js)、性价比下的价格倍率(model-info.ts)、
+ * 应用实际用的那一档(model-quality.ts)、Artificial Analysis 排行榜的解析与对应(scripts/update-model-quality.mjs),
+ * 以及界面上的面板(只看 vnode 结构,不渲染)。
+ */
+import { describe, it, expect, beforeAll } from "vitest";
+import fs from "node:fs";
+// @ts-expect-error 界面代码是不经构建的 JS
+import { candidates, paretoFrontier, pickStops, levelOf, defaultStop, anchorOf, tiers } from "../ui/lib/frontier.js";
+// @ts-expect-error 脚本是不经构建的 JS
+import * as upd from "../scripts/update-model-quality.mjs";
+import { loadModelInfo, strategyFactors, type PricingCatalog, type PricingEntry } from "../src/account/model-info.js";
+import { appEffort, qualityFor, type QualitySnapshot } from "../src/account/model-quality.js";
+
+const pt = (id: string, intelligence: number, cost: number) => ({ id, intelligence, cost });
+
+describe("帕累托前沿", () => {
+ it("只留没被支配的:更贵又不更聪明的、同价更笨的都去掉;完全相同的留 ID 靠前的", () => {
+ const front = paretoFrontier([
+ pt("a", 20, 0.1),
+ pt("b", 30, 0.5),
+ pt("c", 25, 0.6), // 比 b 贵还更笨
+ pt("d", 30, 0.8), // 和 b 一样聪明但更贵
+ pt("e", 50, 2),
+ pt("f", 45, 2), // 和 e 同价更笨
+ pt("h", 20, 0.1), // 和 a 完全一样
+ pt("g", 55, 9),
+ ]);
+ expect(front.map((p: { id: string }) => p.id)).toEqual(["a", "b", "e", "g"]);
+ });
+
+ it("最多 5 档:两头总在,中间按智能均分挑;不到 5 个时全要", () => {
+ const front = [pt("a", 10, 0.1), pt("b", 12, 0.2), pt("c", 14, 0.3), pt("d", 30, 0.5), pt("e", 31, 0.6), pt("f", 45, 1), pt("g", 60, 5), pt("h", 61, 6)];
+ // 均分点 22.75 / 35.5 / 48.25:离得最近的是 d(30)、e(31)、f(45)
+ expect(pickStops(front).map((p: { id: string }) => p.id)).toEqual(["a", "d", "e", "f", "h"]);
+ expect(pickStops(front.slice(0, 3)).map((p: { id: string }) => p.id)).toEqual(["a", "b", "c"]);
+ expect(pickStops(front, 2).map((p: { id: string }) => p.id)).toEqual(["a", "h"]);
+ });
+
+ it("档名:两头总是最低、最高;恢复默认停在居中偏省的那一档", () => {
+ expect([0, 1, 2, 3, 4].map((i) => levelOf(i, 5))).toEqual([0, 1, 2, 3, 4]);
+ expect([0, 1, 2].map((i) => levelOf(i, 3))).toEqual([0, 2, 4]);
+ expect([0, 1, 2, 3].map((i) => levelOf(i, 4))).toEqual([0, 1, 3, 4]);
+ expect([0, 1].map((i) => levelOf(i, 2))).toEqual([0, 4]);
+ expect([2, 3, 4, 5].map(defaultStop)).toEqual([0, 1, 1, 2]);
+ });
+
+ it("候选:列表里有智能和倍率的模型;花费 = 每次任务的花费 × 当前性价比的倍率,带不带 modelflare/ 前缀算一个", () => {
+ const info = {
+ x: { quality: { intelligence: 40, costPerTask: 2 }, factors: { low_cost: 0.1, balanced: 0.2, stable: 0.5 } },
+ y: { quality: { intelligence: 30, costPerTask: 1 } }, // 没有倍率:不在 Modelflare 目录里
+ z: { factors: { low_cost: 1, balanced: 1, stable: 1 } }, // 没有 AA 数据
+ };
+ expect(candidates(["modelflare/x", "x", "y", "z", "w"], info, "low_cost")).toEqual([pt("modelflare/x", 40, 0.2)]);
+ expect(candidates(["x"], info, "stable")).toEqual([pt("x", 40, 1)]);
+ });
+
+ it("性价比变了前沿跟着变:省钱时便宜分组多的模型更占便宜", () => {
+ const info = {
+ gpt: { quality: { intelligence: 50, costPerTask: 3 }, factors: { low_cost: 0.03, balanced: 0.13, stable: 0.13 } },
+ claude: { quality: { intelligence: 48, costPerTask: 2.5 }, factors: { low_cost: 0.06, balanced: 0.315, stable: 0.5 } },
+ small: { quality: { intelligence: 20, costPerTask: 0.1 }, factors: { low_cost: 0.5, balanced: 0.5, stable: 0.5 } },
+ };
+ const ids = (s: string) => tiers(["gpt", "claude", "small"], info, s, "").stops.map((p: { id: string }) => p.id);
+ // 省钱:gpt 0.09,claude 0.15 → claude 被 gpt 支配
+ expect(ids("low_cost")).toEqual(["small", "gpt"]);
+ // 质量:gpt 0.39,claude 1.25 → 还是 gpt;均衡:gpt 0.39,claude 0.79
+ expect(ids("stable")).toEqual(["small", "gpt"]);
+ const cheapClaude = { ...info, claude: { ...info.claude, factors: { low_cost: 0.03, balanced: 0.1, stable: 0.5 } } };
+ // claude 在省钱时只要 0.075:比 gpt 便宜,于是两个都在前沿上
+ expect(tiers(["gpt", "claude", "small"], cheapClaude, "low_cost", "").stops.map((p: { id: string }) => p.id)).toEqual(["small", "claude", "gpt"]);
+ });
+
+ it("当前模型在第几档;不在档上时是 -1,并给出它落在哪两档之间", () => {
+ const info = Object.fromEntries(
+ [["a", 10, 0.1], ["b", 30, 0.5], ["c", 50, 2], ["mid", 40, 3]].map(([id, i, c]) => [id, { quality: { intelligence: i, costPerTask: c }, factors: { low_cost: 1, balanced: 1, stable: 1 } }]),
+ );
+ expect(tiers(["a", "b", "c", "mid"], info, "balanced", "modelflare/b")).toMatchObject({ cur: 1, anchor: undefined });
+ const off = tiers(["a", "b", "c", "mid"], info, "balanced", "mid");
+ expect(off.cur).toBe(-1);
+ expect(off.anchor).toBeGreaterThan(1);
+ expect(off.anchor).toBeLessThan(2);
+ // 没有资料的模型:不知道在哪
+ expect(tiers(["a", "b", "c"], info, "balanced", "unknown").anchor).toBeUndefined();
+ expect(anchorOf([pt("a", 10, 0), pt("b", 20, 1)], pt("x", 5, 0))).toBe(-0.5);
+ expect(anchorOf([pt("a", 10, 0), pt("b", 20, 1)], pt("x", 25, 0))).toBe(1.5);
+ });
+});
+
+describe("性价比下的价格倍率", () => {
+ const catalog: PricingCatalog = {
+ group_ratio: { "openai-award": 0.03, "openai-stable": 0.08, "openai-premium": 0.13, "openai-enterprise": 0.5, "openai-first-topup": 0.015, "claude-award": 0.25, "claude-stable": 0.315, "claude-premium": 0.5, "claude-tmp-cheap": 0.06 },
+ usable_group: { "openai-award": "", "openai-stable": "", "openai-premium": "", "openai-enterprise": "", "claude-award": "", "claude-stable": "", "claude-premium": "", "claude-tmp-cheap": "" },
+ };
+ const entry = (groups: string[], sale?: number): PricingEntry => ({ model_name: "m", quota_type: 0, enable_groups: groups, sale_price_multiplier: sale });
+
+ it("省钱取最低的公开分组,质量取最高的,均衡取居中(偶数个时取贵的那个);不公开的、企业专用的不算", () => {
+ expect(strategyFactors(entry(["openai-award", "openai-first-topup", "openai-stable", "openai-premium", "openai-enterprise"]), catalog)).toEqual({ low_cost: 0.03, balanced: 0.08, stable: 0.13 });
+ expect(strategyFactors(entry(["claude-stable", "claude-tmp-cheap", "claude-award", "claude-premium"]), catalog)).toEqual({ low_cost: 0.06, balanced: 0.315, stable: 0.5 });
+ });
+
+ it("乘上模型售价倍率;没有可用分组时没有", () => {
+ expect(strategyFactors(entry(["claude-award"], 2), catalog)).toEqual({ low_cost: 0.5, balanced: 0.5, stable: 0.5 });
+ expect(strategyFactors(entry(["openai-first-topup"]), catalog)).toBeUndefined();
+ });
+});
+
+describe("应用实际用的那一档", () => {
+ const entry = { aa: "x", default: { variant: "max", intelligence: 57, costPerTask: 6.24 }, medium: { intelligence: 51, costPerTask: 2.73 } };
+
+ it("走 Responses 接口的推理模型发 medium,取 medium 那一行;不推理、走 Chat / Anthropic 的取默认那一行", () => {
+ expect(appEffort({ endpoints: ["openai", "openai-response"], reasoning: true })).toBe("medium");
+ expect(appEffort({ endpoints: ["openai", "openai-response"] })).toBe("medium");
+ expect(appEffort({ endpoints: ["openai", "openai-response"], reasoning: false })).toBeUndefined();
+ expect(appEffort({ endpoints: ["anthropic", "openai"] })).toBeUndefined();
+ expect(qualityFor(entry, { endpoints: ["openai-response"] })).toEqual({ intelligence: 51, costPerTask: 2.73 });
+ expect(qualityFor(entry, { endpoints: ["anthropic", "openai"] })).toEqual({ intelligence: 57, costPerTask: 6.24 });
+ // 发 medium 但 AA 没有 medium 那一行:用默认那一行
+ expect(qualityFor({ aa: "y", default: { intelligence: 34, costPerTask: 7.51 } }, { endpoints: ["openai-response"] })).toEqual({ intelligence: 34, costPerTask: 7.51 });
+ });
+
+ it("/models/info 带上 factors 和 quality(要有 Modelflare 价格目录才有)", async () => {
+ const catalog = {
+ group_ratio: { "openai-award": 0.03, "openai-stable": 0.08 },
+ usable_group: { "openai-award": "", "openai-stable": "" },
+ data: [
+ { model_name: "gpt-6-astra", quota_type: 0, input_price: 10, completion_ratio: 5, enable_groups: ["openai-award", "openai-stable"], supported_endpoint_types: ["openai", "openai-response"] },
+ { model_name: "claude-opus-5-5", quota_type: 0, input_price: 5, completion_ratio: 5, enable_groups: ["openai-stable"], supported_endpoint_types: ["anthropic", "openai"] },
+ ],
+ };
+ const quality: QualitySnapshot = {
+ updatedAt: "2026-11-02",
+ source: "test",
+ models: {
+ "gpt-6-astra": entry,
+ "claude-opus-5-5": { aa: "claude-opus-5-5", default: { variant: "max", intelligence: 58, costPerTask: 10.04 }, medium: { intelligence: 48, costPerTask: 2.45 } },
+ "not-on-modelflare": { aa: "z", default: { intelligence: 1, costPerTask: 1 } },
+ },
+ };
+ const fetchImpl = (async () => new Response(JSON.stringify(catalog))) as typeof fetch;
+ const info = await loadModelInfo({ baseUrl: "http://x", apiKey: "", headers: {}, pricingUrl: "http://x/api/pricing", quality, fetchImpl });
+ expect(info["gpt-6-astra"]).toMatchObject({ factors: { low_cost: 0.03, balanced: 0.08, stable: 0.08 }, quality: { intelligence: 51, costPerTask: 2.73 } });
+ expect(info["claude-opus-5-5"]).toMatchObject({ quality: { intelligence: 58, costPerTask: 10.04 } });
+ expect(info["not-on-modelflare"]).toBeUndefined();
+ });
+});
+
+describe("Artificial Analysis 排行榜", () => {
+ // 和真实页面一样:两行表头(第一行是 colSpan 的分组),模型名带档位,链接 /models/<slug>
+ const row = (name: string, intel: string, cost: string, slug: string) =>
+ `<tr><td><a href="/models/${slug}">${name}</a></td><td>1M</td><td>X</td><td>${intel}</td><td>${cost}</td><td>95</td><td>1.2</td><td>3.4</td><td><a href="/models/${slug}">Model</a> <a href="/models/${slug}/providers">Providers</a></td></tr>`;
+ const page = (rows: string[]) =>
+ `<html><body><table><thead><tr><th colSpan="1"></th><th colSpan="2">Features</th><th>Intelligence</th><th>Price</th><th>Speed</th><th>Latency</th><th>End-to-End</th><th></th></tr>` +
+ `<tr><th>Model</th><th>Context Window</th><th>Creator</th><th><span>Artificial Analysis</span> Intelligence Index</th><th>Cost per Task <span>USD</span></th><th>Median Tokens/s</th><th>Latency First Chunk (s)</th><th>Total Response (s)</th><th>Further Analysis</th></tr></thead><tbody>` +
+ rows.join("") +
+ `</tbody></table></body></html>`;
+ const sample = [
+ row("GPT-6 Astra (max)", "57", "$6.24", "gpt-6-astra"),
+ row("GPT-6 Astra (medium)", "51", "$2.73", "gpt-6-astra-medium"),
+ row("GPT-6 Astra (high)", "55", "$3.24", "gpt-6-astra-high"),
+ row("Claude Opus 5.5 (max with fallback)", "58", "$10.04", "claude-opus-5-5"),
+ row("Claude Opus 5.5 (medium with fallback)", "48", "$2.45", "claude-opus-5-5-medium"),
+ row("Gemini 3.8 Flash (high)", "31", "$7.77", "gemini-3-8-flash"),
+ row("Gemini 3.8 Flash (medium)", "30", "$6.26", "gemini-3-8-flash-medium"),
+ row("DeepSeek V4.1 Flash 1017 (max)", "32", "$0.60", "deepseek-v4-1-flash-1017"),
+ row("Qwen3.8 Max (0902)", "34", "$10.02", "qwen3-8-max"),
+ row("Muse Wonder Full (max)", "50", "--", "muse-wonder-full"),
+ row("Granite 4.2 3B", "--", "--", "granite-4-2-3b"),
+ ];
+
+ it("按表头文字找列;名字拆出档位(「max with fallback」算 max,「(0902)」不算档位),-- 是没有数据", () => {
+ const rows = upd.parseLeaderboard(page(sample));
+ expect(rows).toHaveLength(sample.length);
+ expect(rows[0]).toEqual({ name: "GPT-6 Astra (max)", slug: "gpt-6-astra", base: "GPT-6 Astra", variant: "max", intelligence: 57, costPerTask: 6.24 });
+ expect(rows[3]).toMatchObject({ base: "Claude Opus 5.5", variant: "max" });
+ expect(rows[8]).toMatchObject({ base: "Qwen3.8 Max (0902)", variant: "" });
+ expect(rows[9]).toMatchObject({ intelligence: 50, costPerTask: null });
+ expect(upd.splitVariant("GPT-6 Sol (Daybreak Blue, max)")).toEqual({ base: "GPT-6 Sol", variant: "max" });
+ expect(upd.numberOf("$1,234.5")).toBe(1234.5);
+ expect(upd.numberOf("n/a")).toBeNaN();
+ });
+
+ it("页面结构变了就报清楚哪里不对:少了列、行的形状不对、没有链接", () => {
+ expect(() => upd.parseLeaderboard("<html>no table</html>")).toThrow(/no <table>/);
+ expect(() => upd.parseLeaderboard(page(sample).replace("Cost per Task", "Price per Task"))).toThrow(/missing column "Cost per Task"/);
+ expect(() => upd.parseLeaderboard(page(sample).replace("Intelligence Index", "Index"))).toThrow(/missing column "Artificial Analysis Intelligence Index"/);
+ const short = sample.map((r) => r.replace("<td>1M</td>", ""));
+ expect(() => upd.parseLeaderboard(page(short))).toThrow(/don't have the 9 header columns/);
+ const unlinked = sample.map((r) => r.replace(/href="\/models\/[^"]+"/g, 'href="#"'));
+ expect(() => upd.parseLeaderboard(page(unlinked))).toThrow(/no \/models\/<slug> link/);
+ });
+
+ it("健康检查:行数太少、数字解析不出来的太多都不行", () => {
+ const rows = upd.parseLeaderboard(page(sample));
+ expect(() => upd.checkRows(rows)).toThrow(/only 11 rows/);
+ const many = Array.from({ length: 60 }, (_, i) => ({ name: `m${i}`, slug: `m${i}`, base: `m${i}`, variant: "", intelligence: i, costPerTask: i / 10 }));
+ expect(() => upd.checkRows(many)).not.toThrow();
+ const garbled = many.map((r, i) => (i % 3 ? r : { ...r, costPerTask: NaN }));
+ expect(() => upd.checkRows(garbled)).toThrow(/"Cost per Task" didn't parse as a number in 20 of 60/);
+ const empty = many.map((r) => ({ ...r, intelligence: null }));
+ expect(() => upd.checkRows(empty)).toThrow(/only 0 rows have a number in "Intelligence Index"/);
+ });
+
+ it("对应 Modelflare 的 ID:点换横线、末尾的档位、名字对不上的查表;只留有数字的", () => {
+ const snap = upd.buildSnapshot(upd.parseLeaderboard(page(sample)), ["gpt-6-astra", "claude-opus-5-5", "gemini-3.8-flash", "gemini-3.8-flash-high", "deepseek-v4.1-flash", "qwen3.8-max", "muse-wonder-full", "kimi-k3", "gpt-image-2"], { updatedAt: "2026-11-02", source: "test" });
+ expect(Object.keys(snap.models)).toEqual(["claude-opus-5-5", "deepseek-v4.1-flash", "gemini-3.8-flash", "gemini-3.8-flash-high", "gpt-6-astra", "qwen3.8-max"]);
+ expect(snap.models["gpt-6-astra"]).toEqual({ aa: "gpt-6-astra", name: "GPT-6 Astra", default: { variant: "max", intelligence: 57, costPerTask: 6.24 }, medium: { intelligence: 51, costPerTask: 2.73 } });
+ // ID 里带了档位:固定那一档,没有 medium
+ expect(snap.models["gemini-3.8-flash-high"]).toEqual({ aa: "gemini-3-8-flash", name: "Gemini 3.8 Flash", default: { variant: "high", intelligence: 31, costPerTask: 7.77 } });
+ expect(snap.models["deepseek-v4.1-flash"].aa).toBe("deepseek-v4-1-flash-1017");
+ expect(snap.attribution).toMatch(/Artificial Analysis/);
+ expect(upd.normalizeId("modelflare/GPT-6.1_Sol")).toBe("gpt-6-1-sol");
+ });
+
+ it("官方 API:没有每次任务的花费时直接报错,不拿别的数凑", () => {
+ expect(() => upd.fromApi({ data: [{ name: "A (high)", slug: "a", evaluations: { artificial_analysis_intelligence_index: 50 } }] })).toThrow(/no cost per task/);
+ expect(upd.fromApi({ data: [{ name: "A (high)", slug: "a-high", evaluations: { artificial_analysis_intelligence_index: 50 }, cost_per_task: 1.5 }] })).toEqual([
+ { name: "A (high)", slug: "a-high", base: "A", variant: "high", intelligence: 50, costPerTask: 1.5 },
+ ]);
+ });
+
+ it("仓库里的快照:每个模型都有一档带数字,ID 都在 Modelflare 的写法里(小写、点号)", () => {
+ const snap = JSON.parse(fs.readFileSync(new URL("../assets/model-quality.json", import.meta.url), "utf8"));
+ expect(snap.source).toMatch(/^https:\/\/artificialanalysis\.ai\//);
+ expect(Object.keys(snap.models).length).toBeGreaterThanOrEqual(5);
+ for (const [id, e] of Object.entries<any>(snap.models)) {
+ expect(id).toBe(id.toLowerCase());
+ const r = e.default ?? e.medium;
+ expect(Number.isFinite(r.intelligence) && Number.isFinite(r.costPerTask)).toBe(true);
+ }
+ });
+});
+
+/** vnode 里所有的字(只看结构,不渲染) */
+const textOf = (v: any): string => (v == null || typeof v === "boolean" ? "" : typeof v !== "object" ? String(v) : Array.isArray(v) ? v.map(textOf).join("") : textOf(v.props?.children));
+/** vnode 里第一个满足条件的节点 */
+const find = (v: any, ok: (n: any) => boolean): any => {
+ if (v == null || typeof v !== "object") return undefined;
+ if (Array.isArray(v)) {
+ for (const c of v) {
+ const hit = find(c, ok);
+ if (hit) return hit;
+ }
+ return undefined;
+ }
+ return ok(v) ? v : find(v.props?.children, ok);
+};
+const all = (v: any, ok: (n: any) => boolean, out: any[] = []): any[] => {
+ if (v == null || typeof v !== "object") return out;
+ if (Array.isArray(v)) v.forEach((c) => all(c, ok, out));
+ else {
+ if (ok(v)) out.push(v);
+ all(v.props?.children, ok, out);
+ }
+ return out;
+};
+
+describe("界面:选择器的两个滑块", () => {
+ let mp: any;
+ let ui: any;
+ let lib: any;
+ beforeAll(async () => {
+ // 界面模块在浏览器里跑:只补上它们加载时要的那一点
+ (globalThis as any).window ??= { matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }), addEventListener() {}, removeEventListener() {} };
+ // @ts-expect-error 界面代码是不经构建的 JS
+ mp = await import("../ui/components/model-picker.js");
+ // @ts-expect-error 同上
+ ui = await import("../ui/components/ui.js");
+ // @ts-expect-error 同上
+ lib = await import("../ui/lib/i18n.js");
+ });
+ const stops = [pt("gpt-6-luna", 18, 0.002), pt("gpt-6.1-terra", 38, 0.02), pt("gpt-6.1-sol", 46, 0.04), pt("gpt-6-astra", 51, 0.3), pt("claude-opus-5-5", 58, 3)];
+ const panel = (o: Record<string, unknown> = {}) =>
+ mp.TierPanel({ strategy: "balanced", showStrategy: true, stops, cur: 3, model: "gpt-6-astra", canReset: true, onStrategy() {}, onStop() {}, onList() {}, onReset() {}, ...o });
+ const sliders = (v: any) => all(v, (n) => n.type === ui.Stops);
+
+ it("登录且 Modelflare 支持时:性价比(省钱 / 均衡 / 质量)+ 模型智能(档名、模型名、更省 / 更强)+ 出处", () => {
+ lib.setLangPref("zh-CN");
+ const v = panel();
+ expect(textOf(v)).toBe("性价比均衡省钱均衡质量模型智能高gpt-6-astra更省更强沿帕累托前沿选择模型,数据来自 Artificial Analysis");
+ const [s1, s2] = sliders(v);
+ expect(s1.props).toMatchObject({ count: 3, value: 1, valueText: "均衡" });
+ expect(s2.props).toMatchObject({ count: 5, value: 3, valueText: "高:gpt-6-astra", autoFocus: true });
+ expect(find(v, (n) => n.type === "a").props).toMatchObject({ href: "https://artificialanalysis.ai/", target: "_blank" });
+ lib.setLangPref("en");
+ expect(textOf(panel())).toBe("ValueBalancedCheapBalancedQualityIntelligenceHighgpt-6-astraCheaperSmarterPareto-optimal models, data from Artificial Analysis");
+ lib.setLangPref("zh-CN");
+ });
+
+ it("没登录或不支持时没有性价比;当前模型不在档上是「自定义」,模型名照样显示", () => {
+ const v = panel({ showStrategy: false, cur: -1, model: "kimi-k3", anchor: 2.5 });
+ expect(textOf(v)).toBe("模型智能自定义kimi-k3更省更强沿帕累托前沿选择模型,数据来自 Artificial Analysis");
+ const [s2, more] = sliders(v);
+ expect(more).toBeUndefined();
+ expect(s2.props).toMatchObject({ value: -1, anchor: 2.5, valueText: "自定义", fallback: 2 });
+ expect(find(v, (n) => n.props?.class === "tier-val custom")).toBeTruthy();
+ });
+
+ it("滑块和模型名:拖到第几档就选那个模型;点模型名去完整列表;恢复默认只在不是默认时出现", () => {
+ const got: string[] = [];
+ const v = panel({ onStop: (m: string) => got.push(`stop:${m}`), onStrategy: (s: string) => got.push(`strategy:${s}`), onList: () => got.push("list") });
+ const [s1, s2] = sliders(v);
+ s1.props.onChange(0);
+ s2.props.onChange(4);
+ find(v, (n) => n.props?.class === "tier-model").props.onClick();
+ expect(got).toEqual(["strategy:low_cost", "stop:claude-opus-5-5", "list"]);
+ expect(find(v, (n) => String(n.props?.class).includes("tiers-reset"))).toBeTruthy();
+ expect(find(panel({ canReset: false }), (n) => String(n.props?.class).includes("tiers-reset"))).toBeUndefined();
+ });
+
+ it("前沿不到两档:没有第二个滑块,只剩模型名", () => {
+ const v = panel({ showStrategy: false, stops: stops.slice(0, 1), cur: 0 });
+ expect(sliders(v)).toEqual([]);
+ expect(textOf(v)).toBe("模型智能gpt-6-astra沿帕累托前沿选择模型,数据来自 Artificial Analysis");
+ });
+
+ it("第一个滑块只在登录了、Modelflare 认这个设置时显示;否则按均衡估花费", () => {
+ const acct = (state: string, supported: boolean, strategy = "low_cost") => ({ state, keyQuality: { strategy, supported } });
+ expect(mp.showsStrategy(acct("signed_in", true))).toBe(true);
+ expect(mp.showsStrategy(acct("signed_in", false))).toBe(false);
+ expect(mp.showsStrategy(acct("signed_out", true))).toBe(false);
+ expect(mp.showsStrategy(null)).toBe(false);
+ expect(mp.strategyOf(acct("signed_in", true))).toBe("low_cost");
+ expect(mp.strategyOf(acct("signed_in", false))).toBe("balanced");
+ expect(mp.strategyOptions()).toEqual([["low_cost", "省钱"], ["balanced", "均衡"], ["stable", "质量"]]);
+ });
+
+ it("方向键:一档一档走,两头停住;不在档上时从它的位置往上或往下,不知道位置时去默认那一档", () => {
+ expect(ui.stepKey("ArrowRight", 1, 5)).toBe(2);
+ expect(ui.stepKey("ArrowUp", 4, 5)).toBe(4);
+ expect(ui.stepKey("ArrowLeft", 0, 5)).toBe(0);
+ expect(ui.stepKey("ArrowDown", 3, 5)).toBe(2);
+ expect(ui.stepKey("Home", 3, 5)).toBe(0);
+ expect(ui.stepKey("End", 1, 5)).toBe(4);
+ expect(ui.stepKey("Enter", 1, 5)).toBeUndefined();
+ expect(ui.stepKey("ArrowRight", -1, 5, 1.4)).toBe(2);
+ expect(ui.stepKey("ArrowLeft", -1, 5, 1.4)).toBe(1);
+ expect(ui.stepKey("ArrowLeft", -1, 5, -0.5)).toBe(0);
+ expect(ui.stepKey("ArrowRight", -1, 5, 4.5)).toBe(4);
+ expect(ui.stepKey("ArrowRight", -1, 5, undefined, 2)).toBe(2);
+ });
+});
diff --git a/ui/components/model-picker.js b/ui/components/model-picker.js
index d45c92e..72c2aa5 100644
--- a/ui/components/model-picker.js
+++ b/ui/components/model-picker.js
@@ -1,28 +1,34 @@
// 模型选择器(magpie picker 的样式;数据来自 Modelflare 的 /v1/models)。按模型族分组,组头可以展开收起。
// 不做厂商图标栏:各厂商 logo 是第三方商标,未取得授权前不用。
+// 对话和机器人设置里打开时先是两个滑块(TierPanel):性价比(账户级,Key 的路由策略)和模型智能(沿帕累托前沿的几档,
+// lib/frontier.js);点模型名进完整列表,照样可以手动选。
import { useEffect, useMemo, useRef, useState } from "preact/hooks";
-import { html, Popover, Icon } from "./ui.js";
+import { html, Popover, Icon, Stops } from "./ui.js";
import { api } from "../lib/api.js";
-import { createStore, useStore } from "../lib/store.js";
+import { createStore, useStore, failed } from "../lib/store.js";
import { t } from "../lib/i18n.js";
import { OTHER_FAMILY, groupModels, modelFamily, normModel, sameModel, shortModel } from "../lib/models.js";
+import { DEFAULT_STRATEGY, STRATEGIES, defaultStop, levelOf, tiers } from "../lib/frontier.js";
export { groupModels, normModel, sameModel, shortModel } from "../lib/models.js";
// —— 模型能力与参考价(/models/info,后端缓存一小时;界面第一次打开选择器时取一次)——
const infoStore = createStore(null);
let infoLoading = false;
-function useModelInfo() {
+/** 先取一次(对话页挂上时就取,打开选择器时滑块不用等) */
+export function prefetchModelInfo() {
+ if (infoStore.get() || infoLoading) return;
+ infoLoading = true;
+ api("/models/info")
+ .then((d) => infoStore.set(d.models || {}))
+ .catch(() => infoStore.set({}))
+ .finally(() => (infoLoading = false));
+}
+/** 模型资料;还没取到时 null */
+function useModelInfoRaw() {
const info = useStore(infoStore);
- useEffect(() => {
- if (info || infoLoading) return;
- infoLoading = true;
- api("/models/info")
- .then((d) => infoStore.set(d.models || {}))
- .catch(() => infoStore.set({}))
- .finally(() => (infoLoading = false));
- }, []);
- return info || {};
+ useEffect(prefetchModelInfo, []);
+ return info;
}
const num = (n) => String(+Number(n).toFixed(n < 1 ? 3 : 2));
@@ -60,16 +66,118 @@ export function FamilyHead({ name, count, current }) {
return html`<span class="v">${familyName(name)}</span><span class="n">${current || ""}</span><span class="cnt">${count}</span><${Icon} name="chevRight" size="xs" class="chev" />`;
}
+// —— 两个滑块 ——
+const AA_URL = "https://artificialanalysis.ai/";
+/** 档名:levelOf 的 0…4 */
+const LEVELS = ["min", "low", "medium", "high", "max"];
+
+/** 第一个滑块显示不显示:登录了 Modelflare 账户,而且 Modelflare 认这个设置 */
+export const showsStrategy = (account) => !!(account && account.state === "signed_in" && account.keyQuality && account.keyQuality.supported);
+/** 按哪种性价比算花费:显示第一个滑块时用账户的,否则按均衡估 */
+export const strategyOf = (account) => (showsStrategy(account) ? account.keyQuality.strategy : DEFAULT_STRATEGY);
+export const strategyLabel = (s) => t(`models.tiers.strategy.${s}`);
+/** 性价比的三个选项(设置页的分段控件也用) */
+export const strategyOptions = () => STRATEGIES.map((s) => [s, strategyLabel(s)]);
+
+/** 当前模型在第二个滑块上的档名;不在档上时是「自定义」 */
+export const levelLabel = (cur, n) => (cur >= 0 ? t(`models.tiers.level.${LEVELS[levelOf(cur, n)]}`) : t("models.tiers.custom"));
+
+/**
+ * 两个滑块的面板(不带状态)。stops / cur / anchor 来自 frontier.js 的 tiers;model 是当前模型。
+ * 没有第一个滑块时(没登录、Modelflare 不支持)只有模型智能;前沿不到两档时只剩模型名,点它进列表。
+ * 右上角的恢复默认只在不是默认(均衡 + 居中那一档)时出现。
+ */
+export function TierPanel({ strategy, showStrategy, stops, cur, anchor, model, canReset, onStrategy, onStop, onList, onReset }) {
+ const n = stops.length;
+ const si = STRATEGIES.indexOf(strategy);
+ const level = levelLabel(cur, n);
+ return html`<div class="tiers">
+ ${canReset && html`<button type="button" class="icon-btn tiers-reset" title=${t("models.tiers.reset")} aria-label=${t("models.tiers.reset")} onClick=${onReset}><${Icon} name="reset" size="sm" /></button>`}
+ ${showStrategy && html`<section class="tier">
+ <div class="tier-head"><span class="tier-name">${t("models.tiers.value")}</span><span class="tier-val">${strategyLabel(strategy)}</span></div>
+ <${Stops} count=${STRATEGIES.length} value=${si} label=${t("models.tiers.value")} valueText=${strategyLabel(strategy)} onChange=${(i) => onStrategy(STRATEGIES[i])} />
+ <div class="tier-ticks">${STRATEGIES.map((s) => html`<span key=${s} class=${s === strategy ? "on" : ""}>${strategyLabel(s)}</span>`)}</div>
+ </section>`}
+ <section class="tier">
+ <div class="tier-head"><span class="tier-name">${t("models.tiers.intelligence")}</span>${n >= 2 && html`<span class=${`tier-val${cur < 0 ? " custom" : ""}`}>${level}</span>`}</div>
+ <button type="button" class="tier-model" title=${t("models.tiers.allModels")} onClick=${onList}><span class="v">${model ? shortModel(model) : t("common.auto")}</span><${Icon} name="chevRight" size="xs" /></button>
+ ${n >= 2 && html`<${Stops} count=${n} value=${cur} anchor=${anchor} fallback=${defaultStop(n)} autoFocus label=${t("models.tiers.intelligence")}
+ valueText=${cur >= 0 ? t("models.tiers.valueText", { level, model: shortModel(stops[cur].id) }) : level} onChange=${(i) => onStop(stops[i].id)} />
+ <div class="tier-ticks ends"><span>${t("models.tiers.cheaper")}</span><span>${t("models.tiers.smarter")}</span></div>`}
+ </section>
+ <p class="tier-foot">${t("models.tiers.foot", { aa: html`<a href=${AA_URL} target="_blank" rel="noopener noreferrer">Artificial Analysis</a>` })}</p>
+ </div>`;
+}
+
/**
* models: string[] | null(加载中);error: 加载失败时的说明。
* reset: { label, note, onSelect } 顶部"恢复默认"项;foot: { label, onClick, disabled } 底部操作。
* 不筛选时按模型族折叠(只有一个族时不出组头);筛选时全部展开,组名只作标签。
+ * account / onAccount:给了就先打开两个滑块(对话、机器人设置);前沿不到两档时直接是列表。
+ * effective:current 为空(跟随默认)时实际用的模型,滑块按它定位。
*/
-export function ModelPicker({ anchor, models, error, current, onPick, onClose, reset, foot, onRetry, prefer = "down", align = "left" }) {
+export function ModelPicker({ anchor, models, error, current, onPick, onClose, reset, foot, onRetry, prefer = "down", align = "left", account, onAccount, effective = "" }) {
+ const panelWanted = onAccount !== undefined;
+ const infoRaw = useModelInfoRaw();
+ const info = infoRaw || {};
+ // 滑块拖到的那一档 / 刚选的性价比:保存完成前先这样显示
+ const [picked, setPicked] = useState(null);
+ const [pendingStrategy, setPendingStrategy] = useState(null);
+ const strategy = pendingStrategy ?? strategyOf(account);
+ const shown = picked ?? (current || effective);
+ const tier = useMemo(() => (panelWanted && models && infoRaw ? tiers(models, info, strategy, shown) : null), [panelWanted, models, infoRaw, strategy, shown]);
+ // 打开时定下先看哪一面(数据还没到就等它到了再定),之后不再自己变
+ const decide = () => (!panelWanted ? "list" : tier ? (tier.stops.length >= 2 ? "panel" : "list") : null);
+ const [view, setView] = useState(decide);
+ useEffect(() => {
+ if (view === null && tier) setView(decide());
+ }, [view, tier]);
+ let body;
+ if (view === "panel" && tier) {
+ const pickStop = (m) => {
+ if (sameModel(m, shown)) return;
+ setPicked(m);
+ Promise.resolve(onPick(m)).finally(() => setPicked(null));
+ };
+ const setStrategy = (s) => {
+ if (s === strategy) return;
+ setPendingStrategy(s);
+ api("/account/key-quality", { method: "PUT", body: { strategy: s } })
+ .then((r) => onAccount(r))
+ .catch((e) => {
+ failed(e);
+ // Modelflare 不支持时状态里 supported 变成 false,第一个滑块随之收起
+ return api("/account").then(onAccount).catch(() => {});
+ })
+ .finally(() => setPendingStrategy(null));
+ };
+ const showStrategy = showsStrategy(account);
+ const home = showStrategy && strategy !== DEFAULT_STRATEGY ? tiers(models, info, DEFAULT_STRATEGY, shown) : tier;
+ const homeModel = home.stops.length ? home.stops[defaultStop(home.stops.length)].id : "";
+ const onReset = () => {
+ if (showStrategy && strategy !== DEFAULT_STRATEGY) setStrategy(DEFAULT_STRATEGY);
+ if (homeModel) pickStop(homeModel);
+ };
+ body = html`<${TierPanel} strategy=${strategy} showStrategy=${showStrategy} stops=${tier.stops} cur=${tier.cur} anchor=${tier.anchor} model=${shown}
+ canReset=${(showStrategy && strategy !== DEFAULT_STRATEGY) || (!!homeModel && !sameModel(homeModel, shown))}
+ onStrategy=${setStrategy} onStop=${pickStop} onList=${() => setView("list")} onReset=${onReset} />`;
+ } else {
+ body = html`<${ModelList} models=${models} error=${error} current=${current} onPick=${onPick} onClose=${onClose} reset=${reset} foot=${foot}
+ onRetry=${onRetry} info=${info} onBack=${view === "list" && panelWanted && tier && tier.stops.length >= 2 ? () => setView("panel") : undefined} />`;
+ }
+ return html`<${Popover} anchor=${anchor} onClose=${onClose} class="model-picker" width=${340} maxHeight=${420} prefer=${prefer} align=${align} label=${t("models.choose")}>${body}<//>`;
+}
+
+/** 完整的模型列表(选择器原来的样子);onBack:从滑块面板进来时,搜索框左边有返回 */
+function ModelList({ models, error, current, onPick, onClose, reset, foot, onRetry, info, onBack }) {
const [q, setQ] = useState("");
const [sel, setSel] = useState(0);
const listRef = useRef(null);
- const info = useModelInfo();
+ const searchRef = useRef(null);
+ // 从面板切过来时面板上的焦点没了:交给搜索框
+ useEffect(() => {
+ if (onBack) searchRef.current?.focus();
+ }, []);
const groups = useMemo(() => groupModels(models || [], q), [models, q]);
const { isOpen, toggle } = useFamilies(groups, current);
const folding = !q.trim() && groups.length > 1;
@@ -139,9 +247,10 @@ export function ModelPicker({ anchor, models, error, current, onPick, onClose, r
</li>`;
};
const rows = (ms) => ms.map(([m, label]) => item({ m }, label, modelNote(info, m)));
- return html`<${Popover} anchor=${anchor} onClose=${onClose} class="model-picker" width=${340} maxHeight=${420} prefer=${prefer} align=${align} label=${t("models.choose")}>
- <div class="search"><${Icon} name="search" size="sm" />
- <input placeholder=${t("models.filterOrId")} value=${q} onInput=${(e) => { setQ(e.target.value); setSel(0); }} onKeyDown=${onKey} aria-label=${t("models.filter")} />
+ return html`<div class="search">${onBack
+ ? html`<button type="button" class="icon-btn xs search-back" title=${t("models.tiers.back")} aria-label=${t("models.tiers.back")} onClick=${onBack}><${Icon} name="chevLeft" size="sm" /></button>`
+ : html`<${Icon} name="search" size="sm" />`}
+ <input ref=${searchRef} placeholder=${t("models.filterOrId")} value=${q} onInput=${(e) => { setQ(e.target.value); setSel(0); }} onKeyDown=${onKey} aria-label=${t("models.filter")} />
</div>
<ul role="listbox" ref=${listRef}>
${models === null && !error && [0, 1, 2, 3, 4].map((k) => html`<li key=${k}><span class="skel" style=${{ width: 60 + ((k * 37) % 30) + "%" }}></span></li>`)}
@@ -155,7 +264,7 @@ export function ModelPicker({ anchor, models, error, current, onPick, onClose, r
${models && !models.length && !q && html`<li class="explained"><span class="v" style="white-space:normal">${t("models.none")}</span></li>`}
</ul>
${foot && html`<div class="foot"><button type="button" disabled=${foot.disabled} onClick=${() => { onClose(); foot.onClick(); }}>${foot.label}</button></div>`}
- <//>`;
+ `;
}
/**
diff --git a/ui/components/ui.js b/ui/components/ui.js
index abb80d5..c2361d6 100644
--- a/ui/components/ui.js
+++ b/ui/components/ui.js
@@ -33,6 +33,7 @@ const P = {
file: "M9 1.75H4.25a.75.75 0 0 0-.75.75v11c0 .41.34.75.75.75h7.5c.41 0 .75-.34.75-.75V5.25L9 1.75ZM9 1.75v3.5h3.5M5.75 8.25h4.5M5.75 10.75h4.5",
folder: "M2.25 4.25c0-.41.34-.75.75-.75h3.1l1.5 1.5H13c.41 0 .75.34.75.75v6.5c0 .41-.34.75-.75.75H3a.75.75 0 0 1-.75-.75v-8Z",
refresh: "M13.25 8a5.25 5.25 0 1 1-1.54-3.71M13.25 2.75v2.5h-2.5",
+ reset: "M2.75 8a5.25 5.25 0 1 0 1.54-3.71M2.75 2.75v2.5h2.5",
stop: { f: "M5.75 4h4.5c.97 0 1.75.78 1.75 1.75v4.5c0 .97-.78 1.75-1.75 1.75h-4.5C4.78 12 4 11.22 4 10.25v-4.5C4 4.78 4.78 4 5.75 4Z" },
more: { f: dot(3.5, 8, 1.25) + dot(8, 8, 1.25) + dot(12.5, 8, 1.25) },
panel: "M2.75 3.25h10.5c.41 0 .75.34.75.75v8c0 .41-.34.75-.75.75H2.75a.75.75 0 0 1-.75-.75V4c0-.41.34-.75.75-.75ZM10 3.25v9.5",
@@ -166,6 +167,60 @@ export function Seg({ options, value, onChange, disabled, label }) {
</div>`;
}
+// —— 档位滑块:几档离散的值(模型选择器里的性价比、模型智能)——
+/**
+ * 方向键怎么走:→ ↑ 往后一档,← ↓ 往前一档,Home / End 两头。value < 0 是"不在任何一档上":从 anchor(落在哪两档之间的小数位置)
+ * 往上或往下走到最近的一档,没有 anchor 时去 fallback。不是这几个键时 undefined。
+ */
+export function stepKey(key, value, count, anchor, fallback = 0) {
+ const last = count - 1;
+ if (key === "Home") return 0;
+ if (key === "End") return last;
+ const up = key === "ArrowRight" || key === "ArrowUp";
+ const down = key === "ArrowLeft" || key === "ArrowDown";
+ if (!up && !down) return undefined;
+ if (value < 0) return anchor === undefined ? fallback : Math.max(0, Math.min(last, up ? Math.ceil(anchor) : Math.floor(anchor)));
+ return Math.max(0, Math.min(last, value + (up ? 1 : -1)));
+}
+
+/**
+ * count 档的滑块(role=slider)。value = 当前档,-1 = 不在任何一档上(没有圆钮和填充,见 stepKey)。
+ * 拖动时只预览,松手才 onChange;点轨道直接跳到那一档;键盘见 stepKey。valueText 是读屏读的当前值。
+ */
+export function Stops({ count, value, onChange, label, valueText, anchor, fallback = 0, autoFocus, class: cls }) {
+ const ref = useRef(null);
+ const [drag, setDrag] = useState(null);
+ const shown = drag ?? value;
+ const last = Math.max(1, count - 1);
+ /** 指针落在哪一档:圆钮中心离两头各半个轨道高 */
+ const at = (e) => {
+ const r = ref.current.getBoundingClientRect();
+ const x = (e.clientX - r.left - r.height / 2) / Math.max(1, r.width - r.height);
+ return Math.max(0, Math.min(count - 1, Math.round(x * last)));
+ };
+ const end = (e) => {
+ if (drag === null) return;
+ setDrag(null);
+ const v = at(e);
+ if (v !== value) onChange(v);
+ };
+ const onKeyDown = (e) => {
+ const v = stepKey(e.key, value, count, anchor, fallback);
+ if (v === undefined) return;
+ e.preventDefault();
+ if (v !== value) onChange(v);
+ };
+ return html`<div class=${cx("stops", shown < 0 && "custom", drag !== null && "dragging", cls)} ref=${ref} role="slider" tabindex="0" data-autofocus=${autoFocus ? "" : undefined}
+ aria-label=${label} aria-valuemin="0" aria-valuemax=${count - 1} aria-valuenow=${shown >= 0 ? shown : undefined} aria-valuetext=${valueText}
+ style=${{ "--stops-at": String(shown >= 0 ? shown / last : 0) }}
+ onKeyDown=${onKeyDown} onPointerDown=${(e) => { ref.current.setPointerCapture?.(e.pointerId); setDrag(at(e)); }}
+ onPointerMove=${(e) => drag !== null && setDrag(at(e))} onPointerUp=${end} onPointerCancel=${() => setDrag(null)}>
+ <span class="stops-fill"></span>
+ ${Array.from({ length: count }, (_, i) => html`<span key=${i} class=${cx("stops-dot", shown >= 0 && i <= shown && "on")} style=${{ "--stops-i": String(i / last) }}></span>`)}
+ <span class="stops-knob"></span>
+ </div>`;
+}
+
/** 长度 token 的像素值("--pop-offset" → 6,"--side-w-cap: 36vw" → 窗口宽 × .36):JS 里的尺寸也从 token 来,不写死。
* el:从哪个元素上读(缺省 <html>;注册过的属性如 .app 上的 --side-col 要从定义它的元素读) */
export function tokenPx(name, fallback, el = document.documentElement) {
@@ -336,7 +391,7 @@ export function Popover({ anchor, onClose, class: cls = "", width = 280, prefer,
if (keepFocus) return;
const prev = document.activeElement;
requestAnimationFrame(() => {
- const target = ref.current?.querySelector("input, [role=option], [role=menuitem], button");
+ const target = ref.current?.querySelector("[data-autofocus]") || ref.current?.querySelector("input, [role=option], [role=menuitem], button");
target?.focus?.();
});
return () => prev?.focus?.({ preventScroll: true });
diff --git a/ui/design/README.md b/ui/design/README.md
index dcec2f4..5b2c738 100644
--- a/ui/design/README.md
+++ b/ui/design/README.md
@@ -19,11 +19,11 @@ ui/design/
motion.css 关键帧库 + .anim-* 工具类 + 减少动态效果
typography.css 文字角色 .t-*(在 utilities 层)
utilities.css .stack .cluster .grow .truncate .tone-* .sr-only
- components/ 一个组件一个文件:icon glass button field badge list seg switch popover model-family sheet splitter toast notice feedback avatar
+ components/ 一个组件一个文件:icon glass button field badge list seg switch stops popover model-family sheet splitter toast notice feedback avatar
motion.js ms("--dur-base")、usePresence()、reducedMotion()
index.html / gallery.* 样例页
ui/css/ 页面样式(shell / chat / settings / guide),放在 app 层
-ui/components/ui.js 组件的 JS 写法:Icon Button IconButton Notice Skeleton Seg Switch Menu MenuButton Sheet …
+ui/components/ui.js 组件的 JS 写法:Icon Button IconButton Notice Skeleton Seg Switch Stops Menu MenuButton Sheet …
```
## 层叠顺序
@@ -255,6 +255,7 @@ ui/components/ui.js 组件的 JS 写法:Icon Button IconButton Notice Ske
| 列表行 | `.list > .row [compact] [clickable] [off] [flash]`,`.row-edit`,`.list-head`;`.list` 是一块 `--well`,行间 `--line-2` | `--row-h --row-py --row-pl --row-pr --row-gap` |
| 分段 | `Seg` 组件(`.seg > .thumb + button`),两个以上的选项 | `--seg-r --seg-pad --seg-thumb --seg-on` |
| 开关 | `Switch` 组件(`button.switch[role=switch] [sm]`),只有开 / 关 | `--switch-w --switch-h --switch-pad --switch-track --switch-track-hover --switch-dot --switch-stretch` |
+| 档位滑块 | `Stops` 组件(`.stops[role=slider] [custom] > .stops-fill + .stops-dot + .stops-knob`),几档离散的值;`value = -1` 不在任何一档上 | `--stops-h --stops-pad --stops-track --stops-fill-bg --stops-knob-bg --stops-dot-bg --stops-dot-on` |
| 菜单 | `.pick`,`.pop [up]`,`.palette`,`Menu` / `MenuButton` / `Popover` | `--pop-r --pop-pad` |
| 对话框 | `Sheet` / `confirmSheet()`(`.scrim > .sheet [wide]`) | `--sheet-w --sheet-r` |
| 分隔条 | `Splitter`(`.splitter [dragging]`),见下文「分隔条」 | `--split-x --split-hit --split-line-w --split-inset --split-line-on`;悬停色是语义 token `--split-line` |
diff --git a/ui/design/components/popover.css b/ui/design/components/popover.css
index cc751ec..08d1bed 100644
--- a/ui/design/components/popover.css
+++ b/ui/design/components/popover.css
@@ -30,6 +30,30 @@
.pop.model-picker { width: 340px; max-height: 420px; }
.pop.model-picker li:not(.group):not(.sep) { min-height: 34px; }
+/* —— 模型选择器的两个滑块(TierPanel):性价比、模型智能;标题在左,当前值大字居中,滑块下面是档名或两头的说法 —— */
+.tiers { position: relative; display: grid; padding: var(--space-3) var(--space-4) var(--space-2-5); overflow-y: auto; }
+.tiers-reset { position: absolute; top: var(--space-2); right: var(--space-2); }
+.tier { display: grid; gap: var(--space-2); padding: var(--space-1) 0 var(--space-3); }
+.tier + .tier { border-top: 1px solid var(--line-2); padding-top: var(--space-3); }
+.tier-head { display: grid; grid-template-columns: 1fr auto 1fr; align-items: baseline; min-height: var(--ctl-sm); }
+.tier-name { font-size: var(--fs-md); color: var(--fg-2); }
+.tier-val { font-size: var(--fs-2xl); font-weight: var(--fw-semibold); letter-spacing: var(--tracking-tight); color: var(--accent); }
+.tier-val.custom { color: var(--muted); font-weight: var(--fw-medium); }
+.tier-model {
+ justify-self: center; display: inline-flex; align-items: center; gap: var(--space-0-5); max-width: 100%;
+ margin-top: calc(-1 * var(--space-1-5)); padding: 0 var(--space-1-5); height: var(--ctl-xs); border-radius: var(--r-sm);
+ font-size: var(--fs-sm); color: var(--fg-2); transition: background var(--t-fast), color var(--t-fast);
+}
+.tier-model:hover { background: var(--sel); color: var(--fg); }
+.tier-model .v { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.tier-model .ic { color: var(--muted); }
+.tier-ticks { display: flex; justify-content: space-between; font-size: var(--fs-xs); color: var(--muted); }
+.tier-ticks .on { color: var(--fg); font-weight: var(--fw-medium); }
+.tier-foot { margin: 0; padding-top: var(--space-2-5); border-top: 1px solid var(--line-2); text-align: center; font-size: var(--fs-2xs); color: var(--muted); }
+.tier-foot a { color: inherit; text-decoration: underline; text-underline-offset: 2px; }
+.tier-foot a:hover { color: var(--fg-2); }
+:is(.pop, .palette) .search .search-back { margin-left: calc(-1 * var(--space-1)); color: var(--muted); }
+
/* —— 命令面板 —— */
.palette-scrim {
position: fixed; inset: 0; z-index: calc(var(--z-palette) - 1); background: var(--scrim-soft);
diff --git a/ui/design/components/stops.css b/ui/design/components/stops.css
new file mode 100644
index 0000000..22c9fc4
--- /dev/null
+++ b/ui/design/components/stops.css
@@ -0,0 +1,44 @@
+/* 档位滑块:几档离散的值(模型选择器里的性价比、模型智能)。和开关一个样子:圆头轨道、圆钮在轨道里,
+ 填充 = 主操作色(浅色墨、深色黄绿),从左头一直填到圆钮。每一档一个小点,填充上的点用前景色。
+ 不在任何一档上(.custom):没有圆钮和填充,只剩轨道和点。
+ 结构:<div role="slider" class="stops" style="--stops-at: 0…1"> .stops-fill .stops-dot(--stops-i)×n .stops-knob
+ 位置都用 transform 移(容器查询单位 cqw = 轨道宽),只给 transform / opacity 做动画。 */
+.stops {
+ --stops-h: 20px; /* 和开关同高 */
+ --stops-pad: var(--space-0-5);
+ --stops-knob-d: calc(var(--stops-h) - 2 * var(--stops-pad));
+ --stops-dot-d: 4px;
+ --stops-track: var(--switch-off);
+ --stops-track-hover: var(--switch-off-hover);
+ --stops-fill-bg: var(--primary);
+ --stops-knob-bg: var(--switch-knob-on);
+ --stops-dot-bg: color-mix(in srgb, var(--fg) 28%, transparent);
+ --stops-dot-on: color-mix(in srgb, var(--on-primary) 55%, transparent);
+ --stops-run: calc(100cqw - var(--stops-h)); /* 圆钮能走的距离 */
+ position: relative; container-type: inline-size; height: var(--stops-h); border-radius: var(--r-full); overflow: hidden;
+ background: var(--stops-track); cursor: pointer; touch-action: none; user-select: none;
+ transition: background var(--t-base);
+}
+.stops:hover { --stops-track: var(--stops-track-hover); }
+/* 填充是一整条圆头的面,往左挪到右端正好落在圆钮右边 */
+.stops-fill {
+ position: absolute; inset: 0; border-radius: inherit; background: var(--stops-fill-bg);
+ transform: translateX(calc(var(--stops-run) * (var(--stops-at) - 1)));
+ transition: transform var(--t-moderate), opacity var(--t-base);
+}
+.stops-dot {
+ position: absolute; top: 50%; left: 0; width: var(--stops-dot-d); height: var(--stops-dot-d); border-radius: 50%;
+ background: var(--stops-dot-bg); pointer-events: none;
+ transform: translate(calc(var(--stops-h) / 2 + var(--stops-run) * var(--stops-i) - 50%), -50%);
+ transition: background var(--t-fast);
+}
+.stops-dot.on { background: var(--stops-dot-on); }
+.stops-knob {
+ position: absolute; top: var(--stops-pad); left: var(--stops-pad); width: var(--stops-knob-d); height: var(--stops-knob-d); border-radius: 50%;
+ background: var(--stops-knob-bg); box-shadow: var(--seg-edge); pointer-events: none;
+ transform: translateX(calc(var(--stops-run) * var(--stops-at)));
+ transition: transform var(--dur-moderate) var(--ease-spring), opacity var(--t-base);
+}
+/* 拖动时跟手,不弹 */
+.stops.dragging :is(.stops-fill, .stops-knob) { transition: none; }
+.stops.custom :is(.stops-fill, .stops-knob) { opacity: 0; }
diff --git a/ui/design/gallery.js b/ui/design/gallery.js
index b9ee63d..90e78d9 100644
--- a/ui/design/gallery.js
+++ b/ui/design/gallery.js
@@ -1,7 +1,7 @@
// 设计库样例页:token 表直接解析 tokens/*.css(单一来源,不会和代码脱节),组件用真实实现渲染。
import { render, createContext } from "preact";
import { useContext, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
-import { html, Icon, ICONS, Button, IconButton, Seg, Switch, MenuButton, Menu, Badge, Notice, Skeleton, Spinner, CopyButton, Toasts, DialogHost, Splitter } from "../components/ui.js";
+import { html, Icon, ICONS, Button, IconButton, Seg, Switch, Stops, MenuButton, Menu, Badge, Notice, Skeleton, Spinner, CopyButton, Toasts, DialogHost, Splitter } from "../components/ui.js";
import { BotAvatar, AvatarPicker, AppMark, BOT_CHARS, CHAR_KEYS, MAIN_CHAR } from "../components/avatar.js";
import { NeedItem, NeedsRow } from "../screens/needs-you.js";
import { RuleRow, RuleDetail } from "../components/rules.js";
@@ -130,6 +130,15 @@ function SwitchDemo() {
return html`<${Switch} label="长期记忆" value=${on} onChange=${setOn} /><${Switch} label="关" value=${false} onChange=${() => {}} />
<${Switch} label="小号" size="sm" value=${on} onChange=${setOn} /><${Switch} label="禁用" value=${true} disabled onChange=${() => {}} />`;
}
+function StopsDemo() {
+ const [a, setA] = useState(1);
+ const [b, setB] = useState(3);
+ return html`<div style=${{ display: "grid", gap: "var(--space-3)", width: "260px" }}>
+ <${Stops} label="性价比" count=${3} value=${a} valueText=${["省钱", "均衡", "质量"][a]} onChange=${setA} />
+ <${Stops} label="模型智能" count=${5} value=${b} onChange=${setB} />
+ <${Stops} label="不在档上" count=${5} value=${-1} anchor=${1.5} onChange=${setB} />
+ </div>`;
+}
function MenuButtonDemo() {
const [v, setV] = useState("auto");
return html`<${MenuButton} label="默认模型" value=${v} onChange=${setV}
@@ -606,6 +615,7 @@ const { mounted, leaving } = usePresence(open); /* design/motion.js:退场
<${Section} id="menus" title="菜单与分段">
<${Demo} title="Seg" note="两个以上的选项;中性 thumb 按值滑动">${() => html`<${SegDemo} />`}<//>
<${Demo} title="Switch" note="只有开 / 关两态;打开 = 主操作色(浅色墨、深色黄绿)" code=${`<${"${Switch}"} label="长期记忆" value=\${on} onChange=\${setOn} />`}>${() => html`<${SwitchDemo} />`}<//>
+ <${Demo} title="Stops" note="几档离散的值(模型选择器的性价比、模型智能);← → 一档,Home / End 两头;value = -1 时不在任何一档上" code=${`<${"${Stops}"} label="性价比" count={3} value=\${i} onChange=\${setI} />`}>${() => html`<${StopsDemo} />`}<//>
<${Demo} title="MenuButton · Menu" note="↑↓ 选择,Enter 执行,Esc 关闭">${() => html`<${MenuButtonDemo} /><${MenuDemo} />`}<//>
<//>
diff --git a/ui/design/index.css b/ui/design/index.css
index de65892..c447da7 100644
--- a/ui/design/index.css
+++ b/ui/design/index.css
@@ -19,6 +19,7 @@
@import url("components/list.css") layer(components);
@import url("components/seg.css") layer(components);
@import url("components/switch.css") layer(components);
+@import url("components/stops.css") layer(components);
@import url("components/popover.css") layer(components);
@import url("components/model-family.css") layer(components);
@import url("components/sheet.css") layer(components);
diff --git a/ui/lib/frontier.js b/ui/lib/frontier.js
new file mode 100644
index 0000000..412f6cf
--- /dev/null
+++ b/ui/lib/frontier.js
@@ -0,0 +1,109 @@
+// 沿帕累托前沿选模型(模型选择器的两个滑块;不依赖界面,单元测试直接引入)。
+//
+// 候选:选择器列表里的模型(这个账户能用的),而且 /models/info 给了它的 quality 和 factors:
+// - quality:Artificial Analysis 的智能指数与每次任务的花费(官方定价),取应用实际用的那一档(服务端 model-quality.ts);
+// - factors:三种性价比(Key 的路由策略)下实际付的比例(分组倍率 × 售价倍率,服务端 model-info.ts)。
+// 花费 = 每次任务的花费 × 当前性价比的比例。前沿 = 没有别的模型又便宜又不笨(花费 ≤、智能 ≥,至少一项严格)的那些。
+// 前沿上最多取 5 档,最便宜的和最强的总在,中间几档按智能均匀地挑。
+import { normModel, sameModel } from "./models.js";
+
+/** 性价比的三档,滑块从左到右:省钱 / 均衡 / 质量 */
+export const STRATEGIES = ["low_cost", "balanced", "stable"];
+export const DEFAULT_STRATEGY = "balanced";
+/** 第二个滑块最多几档;档名按 levelOf 映射到 5 个词上 */
+export const MAX_STOPS = 5;
+
+/** 这个模型的资料:先按完整 ID,再按最后一段(内置网关的 provider/model) */
+function infoOf(info, id) {
+ const n = normModel(id);
+ return info[n] || info[n.slice(n.lastIndexOf("/") + 1)];
+}
+
+/** 候选点:{ id, intelligence, cost };同一个模型(带不带 modelflare/ 前缀)只算一次 */
+export function candidates(models, info, strategy) {
+ const out = [];
+ const seen = new Set();
+ for (const id of models || []) {
+ const i = infoOf(info || {}, id);
+ const f = i && i.factors ? Number(i.factors[strategy]) : NaN;
+ if (!i || !i.quality || !Number.isFinite(f) || f < 0) continue;
+ const key = normModel(id);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push({ id, intelligence: i.quality.intelligence, cost: i.quality.costPerTask * f });
+ }
+ return out;
+}
+
+/** 前沿:按花费从低到高,智能也从低到高。花费相同只留更聪明的;完全相同的两个留 ID 排前面的 */
+export function paretoFrontier(points) {
+ const sorted = [...points].sort((a, b) => a.cost - b.cost || b.intelligence - a.intelligence || String(a.id).localeCompare(String(b.id)));
+ const out = [];
+ let best = -Infinity;
+ for (const p of sorted) {
+ if (p.intelligence > best) {
+ out.push(p);
+ best = p.intelligence;
+ }
+ }
+ return out;
+}
+
+/** 从前沿上挑最多 max 档:两头总在,中间每一档挑智能最接近均分点、还没被挑过的 */
+export function pickStops(front, max = MAX_STOPS) {
+ if (front.length <= max) return front.slice();
+ const lo = front[0].intelligence;
+ const hi = front[front.length - 1].intelligence;
+ const chosen = new Set([0, front.length - 1]);
+ for (let k = 1; k < max - 1; k++) {
+ const target = lo + ((hi - lo) * k) / (max - 1);
+ let at = -1;
+ let gap = Infinity;
+ for (let i = 1; i < front.length - 1; i++) {
+ if (chosen.has(i)) continue;
+ const d = Math.abs(front[i].intelligence - target);
+ if (d < gap) {
+ gap = d;
+ at = i;
+ }
+ }
+ if (at >= 0) chosen.add(at);
+ }
+ return [...chosen].sort((a, b) => a - b).map((i) => front[i]);
+}
+
+/** n 档里的第 i 档用哪个档名(0 最低 … 4 最高):两头总是最低、最高,中间按位置取 */
+export function levelOf(i, n) {
+ return n <= 1 ? MAX_STOPS - 1 : Math.round((i * (MAX_STOPS - 1)) / (n - 1));
+}
+
+/** 恢复默认时停在哪一档:居中,偶数档时偏便宜的那一档 */
+export const defaultStop = (n) => Math.max(0, Math.floor((n - 1) / 2));
+
+/** 当前模型是第几档;不在档上时 -1 */
+export const stopIndex = (stops, current) => stops.findIndex((s) => sameModel(s.id, current));
+
+/**
+ * 当前模型不在档上时,它落在哪两档之间(按智能,小数):方向键从这里往上或往下走到最近的一档。
+ * 没有它的资料时 undefined。
+ */
+export function anchorOf(stops, point) {
+ if (!point || !stops.length) return undefined;
+ const v = point.intelligence;
+ if (v <= stops[0].intelligence) return -0.5;
+ for (let i = 1; i < stops.length; i++) {
+ const a = stops[i - 1].intelligence;
+ const b = stops[i].intelligence;
+ if (v <= b) return i - 1 + (b === a ? 0.5 : Math.min(0.9, Math.max(0.1, (v - a) / (b - a))));
+ }
+ return stops.length - 0.5;
+}
+
+/** 一次算齐:候选、前沿、档位、当前模型在哪一档(-1 = 自定义)和它的位置 */
+export function tiers(models, info, strategy, current) {
+ const points = candidates(models, info, strategy);
+ const stops = pickStops(paretoFrontier(points));
+ const cur = current ? stopIndex(stops, current) : -1;
+ const anchor = cur < 0 ? anchorOf(stops, points.find((p) => sameModel(p.id, current))) : undefined;
+ return { points, stops, cur, anchor };
+}
diff --git a/ui/locales/en/models.js b/ui/locales/en/models.js
index 0c87da8..b2f33e7 100644
--- a/ui/locales/en/models.js
+++ b/ui/locales/en/models.js
@@ -15,4 +15,28 @@ export default {
useCustom: "Use “{id}”",
customId: "Custom model ID",
none: "No models available: this key's group doesn't have any models enabled yet",
+ tiers: {
+ value: "Value",
+ strategy: {
+ low_cost: "Cheap",
+ balanced: "Balanced",
+ stable: "Quality",
+ },
+ intelligence: "Intelligence",
+ level: {
+ min: "Lowest",
+ low: "Low",
+ medium: "Medium",
+ high: "High",
+ max: "Highest",
+ },
+ custom: "Custom",
+ valueText: "{level}: {model}",
+ cheaper: "Cheaper",
+ smarter: "Smarter",
+ allModels: "All models",
+ back: "Back",
+ reset: "Reset",
+ foot: "Pareto-optimal models, data from {aa}",
+ },
};
diff --git a/ui/locales/en/settings.js b/ui/locales/en/settings.js
index 0f019c6..6bb7d85 100644
--- a/ui/locales/en/settings.js
+++ b/ui/locales/en/settings.js
@@ -283,6 +283,11 @@ export default {
sub: "Used by default when a bot generates videos",
keys: "video generate model",
},
+ keyQuality: {
+ name: "Value",
+ sub: "Whether your app keys try cheaper or steadier routes first",
+ keys: "cheap balanced quality routing route group cost",
+ },
autoModel: "Auto ({model})",
models: {
name: "Available models",
diff --git a/ui/locales/zh-CN/models.js b/ui/locales/zh-CN/models.js
index 0a34832..ae424d5 100644
--- a/ui/locales/zh-CN/models.js
+++ b/ui/locales/zh-CN/models.js
@@ -17,4 +17,31 @@ export default {
useCustom: "使用「{id}」",
customId: "自定义模型 ID",
none: "没有可用模型:这个 Key 所在的分组还没有开放模型",
+ /** 选择器的两个滑块 */
+ tiers: {
+ value: "性价比",
+ strategy: {
+ low_cost: "省钱",
+ balanced: "均衡",
+ stable: "质量",
+ },
+ intelligence: "模型智能",
+ /** 第二个滑块的档名,从省到强 */
+ level: {
+ min: "最低",
+ low: "低",
+ medium: "中",
+ high: "高",
+ max: "最高",
+ },
+ custom: "自定义",
+ valueText: "{level}:{model}",
+ cheaper: "更省",
+ smarter: "更强",
+ allModels: "全部模型",
+ back: "返回",
+ reset: "恢复默认",
+ /** aa 是指向 Artificial Analysis 的链接 */
+ foot: "沿帕累托前沿选择模型,数据来自 {aa}",
+ },
};
diff --git a/ui/locales/zh-CN/settings.js b/ui/locales/zh-CN/settings.js
index 9279319..58f5590 100644
--- a/ui/locales/zh-CN/settings.js
+++ b/ui/locales/zh-CN/settings.js
@@ -283,6 +283,11 @@ export default {
sub: "机器人生成视频时默认选它",
keys: "视频 生视频 video 模型",
},
+ keyQuality: {
+ name: "性价比",
+ sub: "应用签发的 Key 先用便宜的还是更稳的渠道",
+ keys: "省钱 均衡 质量 路由 渠道 分组 routing",
+ },
autoModel: "自动({model})",
models: {
name: "可用模型",
diff --git a/ui/main.js b/ui/main.js
index 6ad90a5..fccdebe 100644
--- a/ui/main.js
+++ b/ui/main.js
@@ -397,7 +397,8 @@ function App() {
<main class="main">
${view === "chat" && bot && html`<${ChatScreen} key=${bot.id} bot=${bot} models=${models} modelsError=${modelsError} reloadModels=${reloadModels}
defaultModel=${settings && settings.defaultModel} infoOpen=${infoOpen} onToggleInfo=${() => setInfoOpen((v) => !v)}
- onWorking=${onWorking} pending=${pending[bot.id] || 0} serverBusy=${!!agentWorking[bot.id]} onOpenSettings=${openSettings} onOpenBotSettings=${openBotSettings} onBotUpdated=${onBotUpdated} />`}
+ onWorking=${onWorking} pending=${pending[bot.id] || 0} serverBusy=${!!agentWorking[bot.id]} onOpenSettings=${openSettings} onOpenBotSettings=${openBotSettings} onBotUpdated=${onBotUpdated}
+ account=${managed ? account : null} onAccount=${setAccount} />`}
${view === "group" && routedGroup && bots && html`<${GroupScreen} key=${routedGroup.id} group=${routedGroup} bots=${bots} onEdit=${() => setGroupSheet({ group: routedGroup })} onOpenSettings=${openSettings} onChanged=${reloadGroups} />`}
${view === "group" && groupsData && !routedGroup && html`<div class="empty-state"><b>${t("app.groupMissing")}</b><button type="button" class="text" onClick=${() => openChat()}>${t("app.backToChat")}</button></div>`}
${(view === "new" || (view === "chat" && bots && !bots.length)) && html`<${NewBotScreen} first=${!!bots && !bots.length}
@@ -408,7 +409,7 @@ function App() {
${view === "needs" && html`<${NeedsYouScreen} multiBot=${!!bots && bots.length > 1} onChanged=${pollWorking} onOpenChat=${openChat} onRelogin=${relogin} onOpenBotSettings=${openBotSettings} />`}
${view === "bot-settings" && routedBot && html`<${BotSettingsScreen} key=${routedBot.id} bot=${routedBot} section=${route.section}
models=${models} modelsError=${modelsError} reloadModels=${reloadModels} defaultModel=${settings && settings.defaultModel}
- account=${managed ? account : null} onOpenSettings=${openSettings}
+ account=${managed ? account : null} onAccount=${setAccount} onOpenSettings=${openSettings}
onBack=${() => openChat(routedBot.id)} onBotUpdated=${onBotUpdated} onDeleted=${() => onDeleted(routedBot.id)} />`}
${view === "bot-settings" && bots && !routedBot && html`<div class="empty-state"><b>${t("app.botMissing")}</b><button type="button" class="text" onClick=${() => openChat()}>${t("app.backToChat")}</button></div>`}
</main>
diff --git a/ui/screens/bot-settings.js b/ui/screens/bot-settings.js
index 7dc7b31..7500237 100644
--- a/ui/screens/bot-settings.js
+++ b/ui/screens/bot-settings.js
@@ -23,14 +23,16 @@ function Row({ id, name, sub, title, children, off }) {
</div>`;
}
-function ModelButton({ value, models, modelsError, reloadModels, resetLabel, onChange }) {
+/** tiers:{ account, onAccount, effective } 给了就先打开两个滑块(机器人的默认模型);effective = 跟随全局时实际用的模型 */
+function ModelButton({ value, models, modelsError, reloadModels, resetLabel, onChange, tiers }) {
const [open, setOpen] = useState(false);
const ref = useRef(null);
return html`<button type="button" class="pick" ref=${ref} aria-haspopup="listbox" aria-expanded=${open} onClick=${() => setOpen((v) => !v)}>
<span class="v">${value ? shortModel(value) : resetLabel}</span><${Icon} name="chevDown" />
</button>
${open && html`<${ModelPicker} anchor=${ref.current} align="right" models=${models} error=${modelsError} onRetry=${reloadModels} current=${value}
- onPick=${onChange} onClose=${() => setOpen(false)} reset=${{ label: resetLabel, onSelect: () => onChange("") }} />`}`;
+ onPick=${onChange} onClose=${() => setOpen(false)} reset=${{ label: resetLabel, onSelect: () => onChange("") }}
+ account=${tiers && tiers.account} onAccount=${tiers && tiers.onAccount} effective=${tiers && tiers.effective} />`}`;
}
/**
@@ -88,7 +90,7 @@ function BudgetRows({ bot, budget, account, onSaved, onOpenSettings }) {
* 谁能使用:只有主人和允许名单里的人。主人 = 扫码登录的微信 / 连上之后第一个发消息的人,后者可以更换(下一个发消息的人成为主人)。
* 允许名单和拒绝过的人可以移除(移除后他再发消息会重新申请)。没有的项不显示。
*/
-export function BotSettingsScreen({ bot, section, models, modelsError, reloadModels, defaultModel, account, onOpenSettings, onBack, onBotUpdated, onDeleted }) {
+export function BotSettingsScreen({ bot, section, models, modelsError, reloadModels, defaultModel, account, onAccount, onOpenSettings, onBack, onBotUpdated, onDeleted }) {
const [d, setD] = useState(null);
const [name, setName] = useState(bot.name);
const [prompt, setPrompt] = useState(bot.systemPrompt || "");
@@ -180,7 +182,8 @@ export function BotSettingsScreen({ bot, section, models, modelsError, reloadMod
<div class="list">
<${Row} id="model" name=${t("botSettings.model.default")} sub=${t("botSettings.model.defaultSub")}>
<${ModelButton} value=${bot.defaultModel} models=${models} modelsError=${modelsError} reloadModels=${reloadModels}
- resetLabel=${defaultModel ? t("botSettings.model.followGlobalWith", { model: shortModel(defaultModel) }) : t("botSettings.model.followGlobal")} onChange=${(m) => putBot({ defaultModel: m })} />
+ resetLabel=${defaultModel ? t("botSettings.model.followGlobalWith", { model: shortModel(defaultModel) }) : t("botSettings.model.followGlobal")} onChange=${(m) => putBot({ defaultModel: m })}
+ tiers=${{ account, onAccount: onAccount || (() => {}), effective: defaultModel || (models && models[0]) || "" }} />
<//>
<${Row} id="utility" name=${t("botSettings.model.utility")} sub=${t("botSettings.model.utilitySub")}>
${s && html`<${ModelButton} value=${s.utilityModel} models=${models} modelsError=${modelsError} reloadModels=${reloadModels} resetLabel=${t("botSettings.model.sameAsChat")} onChange=${(m) => put({ utilityModel: m })} />`}
diff --git a/ui/screens/chat.js b/ui/screens/chat.js
index 4346a47..0327334 100644
--- a/ui/screens/chat.js
+++ b/ui/screens/chat.js
@@ -4,7 +4,7 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } fr
import { html, Icon, IconButton, CopyButton, Menu, Popover, Badge, Notice, Skeleton, Spinner, autoGrow } from "../components/ui.js";
import { BotAvatar } from "../components/avatar.js";
import { Markdown, Linkified } from "../components/markdown.js";
-import { ModelPicker, shortModel, sameModel } from "../components/model-picker.js";
+import { ModelPicker, prefetchModelInfo, shortModel, sameModel } from "../components/model-picker.js";
import { PwshHint } from "../components/pwsh-hint.js";
import { ActivityLine, currentStep, upsertStep } from "../components/activity.js";
import { TaskChip } from "../components/tasks.js";
@@ -209,7 +209,7 @@ export function ErrorNotice({ text, onRetry, onFixKey }) {
${onRetry && html`<button type="button" class="btn" onClick=${onRetry}>${t("common.retry")}</button>`}`}>${auth ? t("chat.error.authInvalid") : text}<//>`;
}
-export function ChatScreen({ bot, models, modelsError, reloadModels, defaultModel, infoOpen, onToggleInfo, onWorking, onOpenSettings, onOpenBotSettings, onBotUpdated, pending = 0, serverBusy = false }) {
+export function ChatScreen({ bot, models, modelsError, reloadModels, defaultModel, infoOpen, onToggleInfo, onWorking, onOpenSettings, onOpenBotSettings, onBotUpdated, pending = 0, serverBusy = false, account, onAccount }) {
const [items, setItems] = useState(null);
const [convModel, setConvModel] = useState("");
const [text, setText] = useState("");
@@ -603,6 +603,10 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultMode
// —— 模型 ——
const effective = convModel || bot.defaultModel || defaultModel || (models && models[0]) || "";
+ // 模型资料(滑块要用)先取好,打开选择器时不用等
+ useEffect(() => {
+ if (models && models.length) prefetchModelInfo();
+ }, [!!(models && models.length)]);
const pickModel = async (m) => {
try {
await api(`/bots/${encodeURIComponent(bot.id)}/chat/model`, { method: "PUT", body: { model: m } });
@@ -790,7 +794,7 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultMode
{ label: t("chat.perm.more"), onSelect: () => onOpenBotSettings?.(bot.id, "permission") },
]} />`}
${menu === "model" && html`<${ModelPicker} anchor=${modelRef.current} prefer="up" align="right" models=${models} error=${modelsError} onRetry=${reloadModels}
- current=${convModel || bot.defaultModel || defaultModel} onPick=${pickModel} onClose=${() => setMenu(null)}
+ current=${convModel || bot.defaultModel || defaultModel} onPick=${pickModel} onClose=${() => setMenu(null)} account=${account} onAccount=${onAccount || (() => {})}
reset=${{ label: t("chat.model.followBot"), note: shortModel(bot.defaultModel || defaultModel) || t("common.auto"), onSelect: () => pickModel("") }}
foot=${{ label: t("chat.model.setDefault"), disabled: !effective || sameModel(effective, bot.defaultModel), onClick: setBotDefault }} />`}
</section>`;
diff --git a/ui/screens/settings.js b/ui/screens/settings.js
index e38ea40..d40fefb 100644
--- a/ui/screens/settings.js
+++ b/ui/screens/settings.js
@@ -5,7 +5,7 @@
import { useEffect, useMemo, useRef, useState } from "preact/hooks";
import { html, Icon, Seg, Switch, Sheet, CopyButton, Skeleton, MenuButton } from "../components/ui.js";
import { AccountButton } from "./sidebar.js";
-import { PickModel, shortModel } from "../components/model-picker.js";
+import { PickModel, shortModel, showsStrategy, strategyOptions } from "../components/model-picker.js";
import { KeyForm, lineOptions } from "./onboarding.js";
import { LoginSheet, NotificationsSheet, UsageSheet } from "./account.js";
import { api } from "../lib/api.js";
@@ -257,6 +257,17 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, onTab, focusRow,
api("/account/refresh", { method: "POST", body: {} })
.then(onAccount)
.catch(failed);
+ // 性价比(Key 的路由策略):Modelflare 不支持时状态里 supported 变成 false,这一行随之消失
+ const putKeyQuality = (strategy) =>
+ api("/account/key-quality", { method: "PUT", body: { strategy } })
+ .then((r) => {
+ onAccount(r);
+ saved();
+ })
+ .catch((e) => {
+ failed(e);
+ return api("/account").then(onAccount).catch(() => {});
+ });
const putAlerts = (patch) =>
api("/account/alerts", { method: "PUT", body: patch })
.then((r) => {
@@ -374,6 +385,8 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, onTab, focusRow,
ctl: html`<button type="button" class="text" onClick=${() => setSheet("notifications")}>${t("common.view")}</button>` },
signedIn && invite && { tab: "modelflare", id: "invite", name: t("settings.rows.invite.name"), sub: t("settings.rows.invite.sub"), keys: t("settings.rows.invite.keys"),
ctl: html`<span class="val">${invite.code}</span><${CopyButton} text=${invite.url} label=${t("settings.rows.invite.copy")} />` },
+ showsStrategy(acct) && { tab: "modelflare", id: "key-quality", name: t("settings.rows.keyQuality.name"), sub: t("settings.rows.keyQuality.sub"), keys: t("settings.rows.keyQuality.keys"),
+ ctl: html`<${Seg} label=${t("settings.rows.keyQuality.name")} value=${acct.keyQuality.strategy} onChange=${putKeyQuality} options=${strategyOptions()} />` },
managed && { tab: "modelflare", id: "line", name: t("settings.rows.line.name"), sub: t("settings.rows.line.sub"), keys: t("settings.rows.line.keys"),
ctl: html`<${Seg} label=${t("settings.rows.line.name")} value=${mf.line} onChange=${setLine} options=${lineOptions()} />` },
{ tab: "modelflare", id: "default-model", name: t("settings.rows.defaultModel.name"), sub: t("settings.rows.defaultModel.sub"), keys: t("settings.rows.defaultModel.keys"),