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.

fix(account): migrate only legacy stable keys to balanced, follow Modelflare otherwise

Marla64f7288f46ec
diff --git a/src/account/manager.ts b/src/account/manager.ts
index 98a89a9..6abbeda 100644
--- a/src/account/manager.ts
+++ b/src/account/manager.ts
@@ -65,19 +65,28 @@ export interface AccountStatus {
/**
* 性价比(路由策略)的本机记录,存在 KV 的 account.routing 里:
- * chosen:用户选的(没选过时按 DEFAULT_ROUTING);support:Modelflare 认不认这个字段(yes = 回显了,no = 拒绝或忽略),
- * checkedAt:上次判断的时间(no 隔一天再试一次);applied:已经应用到本机全部 Key 的策略。
+ * chosen:现在的策略(在应用里选的,或从 Modelflare 上本机 Key 读回来的;都没有时按 DEFAULT_ROUTING);
+ * support:Modelflare 认不认这个字段(yes = 回显了,no = 拒绝或忽略),checkedAt:上次判断的时间(no 隔一天再试一次);
+ * applied:已经应用到本机全部 Key 的策略;migrated:老 Key 的一次性迁移做过了。
*/
interface RoutingState {
chosen?: RoutingStrategy;
support?: "yes" | "no";
checkedAt?: number;
applied?: RoutingStrategy;
+ migrated?: boolean;
}
export const DEFAULT_ROUTING: RoutingStrategy = "balanced";
/** Modelflare 不认这个字段时,隔多久再试一次(服务端可能已经加上了) */
const ROUTING_RETRY_MS = 24 * 3600_000;
+/**
+ * 老 Key 的一次性迁移:Modelflare 加上这个字段之前签发的 Key 默认是稳定优先。只把「稳定优先、而且签发于这之前」的
+ * 本机 Key 改成均衡;之后的 stable 是用户自己选的,别的值也是后来改的,都不动(Modelflare 后端的约定)。
+ */
+const LEGACY_ROUTING_BEFORE = Date.parse("2026-10-31T00:00:00+08:00") / 1000;
+/** created_at 一般是秒;万一是毫秒也认 */
+const createdSec = (k: AppKey) => (k.created_at > 1e12 ? k.created_at / 1000 : k.created_at);
const BOT_KEY = (botId: string) => `account.botKey.${botId}`;
const ALERTED = "account.lowBalanceAlerted";
@@ -501,7 +510,7 @@ export class AccountManager {
}
// 预算已经关掉的机器人:只把内置网关里它那把失效的 Key 拿掉
for (const botId of lost) await this.o.hooks.removeBotKey(botId).catch(() => {});
- if (this.session === session) await this.syncRouting(session);
+ if (this.session === session) await this.syncRouting(session, keys);
return replaced;
}
@@ -632,18 +641,42 @@ export class AccountManager {
}
/**
- * 核对 Key 时顺带:本机的 Key 还没用上现在的策略就补上。没选过的老用户第一次走到这里,就把默认的均衡
- * 应用到已有的 Key 上(只这一次,之后控制台里手动改的不会被盖掉)。Modelflare 不认时隔一天再试。不抛错。
+ * 核对 Key 时顺带(keys 是这次核对拿到的 Key 列表),不抛错:
+ * 1. 列表里的 Key 不带 routing_strategy:Modelflare 不认,隔一天再看。
+ * 2. 老 Key 迁移,只做一次:稳定优先、签发于 LEGACY_ROUTING_BEFORE 之前的本机 Key 改成均衡,别的不动。
+ * 3. 在应用里改过、还没改到全部 Key 上的(上次没改完),补上。
+ * 4. 否则以 Modelflare 上本机 Key 的为准:在控制台里改过的,应用跟着显示,不盖掉。
*/
- private async syncRouting(session: AccountSession): Promise<void> {
+ private async syncRouting(session: AccountSession, keys: AppKey[]): Promise<void> {
const st = this.routing();
- const strategy = this.routingStrategy();
- const due = st.support === "no" ? Date.now() - (st.checkedAt ?? 0) >= ROUTING_RETRY_MS : st.applied !== strategy;
- if (!due) return;
- const ids = this.appKeyIds(session);
+ if (st.support === "no" && Date.now() - (st.checkedAt ?? 0) < ROUTING_RETRY_MS) return;
+ const mine = new Set(this.appKeyIds(session));
+ const own = keys.filter((k) => mine.has(k.id));
+ const device = own.find((k) => k.id === session.record.deviceKeyId);
+ if (!device) return; // 本机 Key 刚重签:下次核对再说
+ if (!ROUTING_STRATEGIES.some((x) => x === device.routing_strategy)) {
+ this.noteRouting(false, "key list has no routing_strategy");
+ return;
+ }
+ this.noteRouting(true, "");
try {
- if ((await this.applyRouting(strategy, ids)) === "ok") {
- log.info(st.chosen ? "applied key routing strategy" : "applied the default key routing strategy to existing keys", { strategy, keys: ids.length });
+ if (!st.migrated) {
+ const legacy = own.filter((k) => k.routing_strategy === "stable" && createdSec(k) < LEGACY_ROUTING_BEFORE);
+ if (legacy.length && (await this.applyRouting("balanced", legacy.map((k) => k.id))) === "ok") {
+ for (const k of legacy) k.routing_strategy = "balanced";
+ log.info("moved legacy app keys from stability first to balanced", { keys: legacy.length });
+ }
+ this.saveRouting({ migrated: true });
+ }
+ const cur = this.routing();
+ if (cur.chosen && cur.applied !== cur.chosen) {
+ if ((await this.applyRouting(cur.chosen, own.map((k) => k.id))) === "ok") log.info("applied key routing strategy", { strategy: cur.chosen, keys: own.length });
+ return;
+ }
+ const now = ROUTING_STRATEGIES.find((x) => x === device.routing_strategy)!;
+ if (now !== cur.chosen || cur.applied !== now) {
+ this.saveRouting({ chosen: now, applied: now });
+ if (cur.chosen && now !== cur.chosen) log.info("key routing strategy was changed on Modelflare, following it", { strategy: now });
}
} catch (e) {
log.warn("applying key routing strategy failed", { message: (e as Error).message });
diff --git a/test/account.test.ts b/test/account.test.ts
index 1436575..fa70b30 100644
--- a/test/account.test.ts
+++ b/test/account.test.ts
@@ -327,27 +327,46 @@ describe("AccountManager", () => {
expect(patches()).toEqual([]);
});
- it("性价比:已登录、没选过的老用户第一次核对时把均衡应用到已有的全部 Key 上,只这一次", async () => {
+ it("性价比:老 Key 只迁移一次,只改「稳定优先、10/31 之前签发」的;别的值不动,应用跟着 Modelflare 上的显示", async () => {
mf.s.routing = "echo";
- manager.botsSource = () => [{ id: "b1", name: "写作助手", budget: { enabled: true, limitUsd: 3 } }];
+ manager.botsSource = () => [
+ { id: "b1", name: "写作助手", budget: { enabled: true, limitUsd: 3 } },
+ { id: "b2", name: "翻译", budget: { enabled: true, limitUsd: 2 } },
+ ];
await signIn();
- await until(() => calls.includes("bot:b1:sk-key-2"));
- // 模拟升级前:Key 上没有策略,本机也没有记录
+ await until(() => calls.includes("bot:b1:sk-key-2") && calls.includes("bot:b2:sk-key-3"));
+ // 模拟升级前:本机没有记录;本机 Key 和 b1 是 10/30 签发的稳定优先,b2 是用户后来在控制台改成的省钱
store.deleteKV("account.routing");
- for (const k of mf.s.keys) delete k.routing_strategy;
+ const oct30 = Date.parse("2026-10-30T12:00:00+08:00") / 1000;
+ Object.assign(mf.s.keys[0], { routing_strategy: "stable", created_at: oct30 });
+ Object.assign(mf.s.keys[1], { routing_strategy: "stable", created_at: oct30 });
+ Object.assign(mf.s.keys[2], { routing_strategy: "low_cost", created_at: oct30 });
mf.s.keyWrites = [];
const again = make();
again.botsSource = manager.botsSource;
- expect(again.status().keyQuality).toEqual({ strategy: "balanced", supported: false });
await again.repairKeys();
expect(patches().map((w) => [w.id, w.body])).toEqual([
[1, { routing_strategy: "balanced" }],
[2, { routing_strategy: "balanced" }],
]);
- expect(mf.s.keys.map((k) => k.routing_strategy)).toEqual(["balanced", "balanced"]);
+ expect(mf.s.keys.map((k) => k.routing_strategy)).toEqual(["balanced", "balanced", "low_cost"]);
expect(again.status().keyQuality).toEqual({ strategy: "balanced", supported: true });
+ // 只这一次:之后用户在控制台把本机 Key 改回稳定优先,应用不盖掉,跟着显示
+ mf.s.keys[0].routing_strategy = "stable";
await again.repairKeys();
expect(patches()).toHaveLength(2);
+ expect(again.status().keyQuality).toEqual({ strategy: "stable", supported: true });
+ });
+
+ it("性价比:10/31 之后签发的稳定优先是用户自己选的,迁移不动它", async () => {
+ mf.s.routing = "echo";
+ await signIn();
+ store.deleteKV("account.routing");
+ mf.s.keys[0].routing_strategy = "stable";
+ mf.s.keyWrites = [];
+ await make().repairKeys();
+ expect(patches()).toEqual([]);
+ expect(mf.s.keys[0].routing_strategy).toBe("stable");
});
it("性价比:改了就改 Modelflare 上本机的全部 Key,成功了才算;Modelflare 拒绝时不改、控件收起", async () => {
@@ -373,7 +392,8 @@ describe("AccountManager", () => {
const rec = JSON.parse(store.getKV("account.routing")!);
store.setKV("account.routing", JSON.stringify({ ...rec, checkedAt: Date.now() - 25 * 3600_000 }));
await manager.repairKeys();
- expect(patches().map((w) => w.body)).toEqual([{ routing_strategy: "balanced" }]);
+ // Modelflare 现在回显了(没设过的按均衡):记为支持,和本机一致就不用改
+ expect(patches()).toEqual([]);
expect(manager.status().keyQuality).toEqual({ strategy: "balanced", supported: true });
});
diff --git a/test/helpers.ts b/test/helpers.ts
index 42530a1..6d95fc1 100644
--- a/test/helpers.ts
+++ b/test/helpers.ts
@@ -328,8 +328,8 @@ export async function mockModelflare() {
access: new Set<string>(),
revoked: [] as string[],
tokenForms: [] as Record<string, string>[],
- keys: [] as Array<{ id: number; name: string; limit_usd: number | null; used_usd: number; routing_strategy?: string }>,
- /** 服务端怎么对待 Key 的 routing_strategy:echo = 支持(存下并回显),ignore = 不认也不报错,reject = 400 */
+ keys: [] as Array<{ id: number; name: string; limit_usd: number | null; used_usd: number; created_at: number; routing_strategy?: string }>,
+ /** 服务端怎么对待 Key 的 routing_strategy:echo = 支持(存下并回显,没设过的按均衡),ignore = 不认也不报错,reject = 400 */
routing: "ignore" as "echo" | "ignore" | "reject",
/** 收到的 Key 请求(签发、修改)和请求体 */
keyWrites: [] as Array<{ method: string; id?: number; body: Record<string, unknown> }>,
@@ -344,7 +344,7 @@ export async function mockModelflare() {
let keySeq = 0;
const keyOut = ({ routing_strategy, ...k }: (typeof s.keys)[number]) => ({
...k,
- ...(s.routing === "echo" && routing_strategy ? { routing_strategy } : {}),
+ ...(s.routing === "echo" ? { routing_strategy: routing_strategy ?? "balanced" } : {}),
key_tail: `sk-key-${k.id}`.slice(-4),
status: "enabled",
unlimited: k.limit_usd === null,
@@ -399,7 +399,7 @@ export async function mockModelflare() {
const b = await readJson(req);
s.keyWrites.push({ method: "POST", body: b });
if (rejectRouting(b)) return json({ success: false, message: "unknown field: routing_strategy" }, 400);
- const k = { id: ++keySeq, name: b.name, limit_usd: b.limit_usd ?? null, used_usd: 0, ...(s.routing === "echo" && b.routing_strategy ? { routing_strategy: b.routing_strategy } : {}) };
+ const k = { id: ++keySeq, name: b.name, limit_usd: b.limit_usd ?? null, used_usd: 0, created_at: Math.floor(Date.now() / 1000), ...(s.routing === "echo" && b.routing_strategy ? { routing_strategy: b.routing_strategy } : {}) };
s.keys.push(k);
return json({ success: true, data: { ...keyOut(k), key: `sk-key-${k.id}` } });
}