🤖 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.
Python ai-agentai-assistantchatbotclaudecomputer-usedeepseekdesktop-appdshelectronfeishugeminigptgrokllmlocal-firstmodelflaremulti-modelopenai-compatiblepersonal-ai-agentwechat
feat(account): Key 在控制台被删后自动重新签发,失败的消息自动重试一次
dyk984393c4d10450
diff --git a/src/account/client.ts b/src/account/client.tsindex a2d5db1..9f402e0 100644--- a/src/account/client.ts+++ b/src/account/client.ts@@ -22,6 +22,7 @@ export interface ConnectedAccount {export interface AppKey {id: number;name: string;+ /** 完整 Key 的最后 4 位 */key_tail: string;status: "enabled" | "disabled" | "expired" | "exhausted";unlimited: boolean;@@ -73,6 +74,12 @@ export class AccountSession {return this.o.record;}+ /** 改账户记录并立刻落盘。令牌轮换时写回的是这里的记录,所以不能绕过它直接写文件 */+ updateRecord(patch: Partial<AccountRecord>): void {+ this.o.record = { ...this.o.record, ...patch };+ this.o.persist(this.o.record);+ }+private get fetch(): typeof fetch {return this.o.fetchImpl ?? fetch;}diff --git a/src/account/manager.ts b/src/account/manager.tsindex c01dda8..db16312 100644--- a/src/account/manager.ts+++ b/src/account/manager.ts@@ -23,6 +23,10 @@ export interface AccountHooks {removeBotKey(botId: string): Promise<void>;/** 只有 API Key 时的余额;没有连接时 undefined */keyBalance(): Promise<KeyBalance | undefined>;+ /** 内置网关共用连接当前那把 Key 的最后 4 位;没连接时为空 */+ sharedKeyTail(): string;+ /** 共用连接的 Key 已经不能用:没连接,或 Modelflare 说这把 Key 无效 */+ sharedKeyRejected(): Promise<boolean>;/** 提醒:写入应用通知;push = 同时经机器人发到你的微信 / 飞书 */alert(text: string, push: boolean): void;}@@ -76,6 +80,8 @@ export class AccountManager {private quotaPerUnit = 0;private state: AccountState = "signed_out";private refreshing: Promise<AccountStatus> | undefined;+ private keyCheck: Promise<boolean> | undefined;+ private keysChecked = { at: 0, replaced: false };constructor(private o: {@@ -179,8 +185,7 @@ export class AccountManager {const session = this.newSession(rec, { token: tokens.accessToken, expiresAt: tokens.expiresAt });try {const account = await session.account();- const host = this.o.hostname ?? os.hostname();- const key = await session.createKey(`AnyModelBot · ${host}`.slice(0, 50));+ const key = await session.createKey(this.deviceKeyName());if (!key.key) throw new Error(t("account.no_new_key"));try {await this.o.hooks.connectKey(key.key);@@ -189,13 +194,14 @@ export class AccountManager {await this.revokeQuietly(session);throw e;}- this.o.vault.save({ ...session.record, deviceKeyId: key.id });+ session.updateRecord({ deviceKeyId: key.id });this.session = session;this.state = "signed_in";this.applyAccount(account);log.info("signed in to Modelflare", { name: account.display_name || account.username });this.checkLowBalance();- void this.syncBotKeys().catch((e) => log.warn("sync bot keys failed", { message: (e as Error).message }));+ // 给开着预算、还没有 Key 的机器人补签(换设备或重新登录后)。走核对,和刷新余额时的核对合并,不会重复签发+ void this.repairKeys();} catch (e) {this.state = this.session ? "signed_in" : "signed_out";this.snapshot.error = t("account.login_incomplete", { reason: (e as Error).message });@@ -277,6 +283,8 @@ export class AccountManager {try {if (this.session) {this.applyAccount(await this.call((s) => s.account()));+ // 启动后、之后每 5 分钟、切回窗口时都顺带核对一次 Key;不拖慢余额的返回+ void this.repairKeys(60_000);} else {const b = await this.o.hooks.keyBalance();this.snapshot = {@@ -390,14 +398,96 @@ export class AccountManager {try {await this.call((s) => s.deleteKey(id));} catch (e) {- if (!(e instanceof ApiError && e.status === 404)) log.warn("delete bot key failed", { id, message: (e as Error).message });+ if (!(e instanceof ApiError && e.status === 404)) log.warn("delete key failed", { id, message: (e as Error).message });}}- /** 登录后为开着预算、但还没有 Key 的机器人补签(换设备或重新登录后) */- async syncBotKeys(bots: Array<{ id: string; name: string; budget: BotBudget }> = this.botsSource()): Promise<void> {- const have = this.botKeyIds();- for (const b of bots) if (b.budget.enabled && !have.has(b.id)) await this.setBotBudget(b.id, b.name, b.budget);+ // ---------- Key 核对 ----------++ private deviceKeyName(): string {+ return `AnyModelBot · ${this.o.hostname ?? os.hostname()}`.slice(0, 50);+ }++ /**+ * 核对本机 Key 和各机器人的预算 Key 还在不在(用户可能在 Modelflare 控制台把它们删了),+ * 不在就重新签发并接到内置网关。返回 true = 换了 Key,刚才失败的请求可以再试一次。+ * 并发调用合并成一次;maxAgeMs 内刚核对过就沿用那次的结果。不抛错。+ */+ repairKeys(maxAgeMs = 0): Promise<boolean> {+ if (!this.session) return Promise.resolve(false);+ if (this.keyCheck) return this.keyCheck;+ if (Date.now() - this.keysChecked.at < maxAgeMs) return Promise.resolve(this.keysChecked.replaced);+ this.keyCheck = this.doRepairKeys(this.session)+ .catch((e: Error) => {+ log.warn("key check failed", { message: e.message });+ return false;+ })+ .then((replaced) => {+ this.keysChecked = { at: Date.now(), replaced };+ this.keyCheck = undefined;+ return replaced;+ });+ return this.keyCheck;+ }++ private async doRepairKeys(session: AccountSession): Promise<boolean> {+ // 列表只含这次授权签发、而且还在的 Key+ const keys = await this.call((s) => s.listKeys());+ const alive = new Set(keys.map((k) => k.id));+ const botKeys = this.botKeyIds();+ let replaced = false;++ if (!alive.has(session.record.deviceKeyId) && !this.adoptDeviceKey(session, keys, botKeys) && (await this.o.hooks.sharedKeyRejected())) {+ if (this.session !== session) return false;+ log.warn("device key is gone on Modelflare, issuing a new one", { id: session.record.deviceKeyId });+ const key = await this.call((s) => s.createKey(this.deviceKeyName()));+ if (!key.key) throw new Error(t("account.no_new_key"));+ try {+ await this.o.hooks.connectKey(key.key);+ } catch (e) {+ await this.deleteKeyQuietly(key.id);+ throw e;+ }+ session.updateRecord({ deviceKeyId: key.id });+ this.o.hooks.alert(t("account.key_reissued"), false);+ replaced = true;+ }++ // 开着预算却没有 Key 的机器人(Key 被删,或刚登录还没补签):按现在的预算签发,用量从零算起。失败的留到下次核对再试+ const lost = new Set<string>();+ for (const [botId, id] of botKeys) {+ if (alive.has(id)) continue;+ this.o.store.deleteKV(BOT_KEY(botId));+ lost.add(botId);+ }+ for (const b of this.botsSource()) {+ if (!b.budget.enabled || this.botKeyIds().has(b.id) || this.session !== session) continue;+ try {+ await this.setBotBudget(b.id, b.name, b.budget);+ log.info("issued bot budget key", { bot: b.id, replacedDeleted: lost.has(b.id) });+ if (lost.has(b.id)) this.o.hooks.alert(t("account.bot_key_reissued", { name: b.name, limit: b.budget.limitUsd }), false);+ replaced = true;+ } catch (e) {+ log.warn("reissue bot key failed", { bot: b.id, message: (e as Error).message });+ }+ lost.delete(b.id);+ }+ // 预算已经关掉的机器人:只把内置网关里它那把失效的 Key 拿掉+ for (const botId of lost) await this.o.hooks.removeBotKey(botId).catch(() => {});+ return replaced;+ }++ /**+ * 0.1.10 及更早的版本在令牌轮换时把本机 Key 的 id 写回了 0:按网关里那把 Key 的尾号把它认回来。+ * 认不回来说明网关里用的不是这次授权签发的 Key(被删了,或者用户自己粘贴了一把)。+ */+ private adoptDeviceKey(session: AccountSession, keys: AppKey[], botKeys: Map<string, number>): boolean {+ const tail = this.o.hooks.sharedKeyTail();+ const budgetIds = new Set(botKeys.values());+ const k = tail ? keys.find((k) => k.key_tail === tail && !budgetIds.has(k.id)) : undefined;+ if (!k) return false;+ session.updateRecord({ deviceKeyId: k.id });+ return true;}/** App 注入:当前机器人及其预算设置 */diff --git a/src/app.ts b/src/app.tsindex d82ba5d..3dccaa9 100644--- a/src/app.ts+++ b/src/app.ts@@ -234,6 +234,8 @@ export class App {contextChars: config.llm.contextChars,route: (botId, model) => this.routeModel(botId, model),access: this.access,+ // Key 可能在 Modelflare 控制台被删了:核对一下,重新签发了就让失败的那条消息再试一次+ recoverKey: () => (this.account?.signedIn ? this.account.repairKeys(15_000) : Promise.resolve(false)),});}@@ -361,6 +363,16 @@ export class App {const key = this.magpie?.providerKey(this.magpie.modelflareProviderId ?? MODELFLARE_PROVIDER);return key ? fetchKeyBalance(modelflareBaseUrl(this.config.modelflare.line), key) : undefined;},+ sharedKeyTail: () => this.magpie?.modelflareInfo().keyTail ?? "",+ sharedKeyRejected: async () => {+ if (!this.magpie) return false;+ const key = this.magpie.providerKey(this.magpie.modelflareProviderId ?? MODELFLARE_PROVIDER);+ if (!key) return true;+ // 只认 401:连不上、限流、上游出错都不算 Key 坏了,不换+ const line = this.config.modelflare.line;+ const r = await verifyModelflareKey(modelflareBaseUrl(line), key, { line });+ return !r.ok && r.code === "invalid_key";+ },alert: (text, push) => {this.notice("warn", text);if (push) void this.pushToOwner(text);diff --git a/src/core/runtime.ts b/src/core/runtime.tsindex eae4a35..666a1af 100644--- a/src/core/runtime.ts+++ b/src/core/runtime.ts@@ -102,6 +102,11 @@ export interface RuntimeOptions {route?: (botId: string, model: string) => string;/** 谁能和机器人对话(主人 + 允许名单);缺省不限制 */access?: AccessControl;+ /**+ * 模型请求失败后调用:核对 Key 是否已失效(例如在 Modelflare 控制台被删)并重新签发。+ * 返回 true = 换了 Key,这条消息自动再试一次(只在还没有任何输出时)。缺省不重试。+ */+ recoverKey?: () => Promise<boolean>;}const help = () => t("runtime.help");@@ -201,6 +206,13 @@ export class BotRuntime {return list[0];}+ /** 失败后是否值得重试一次:Key 被换掉了才重试;核对本身出错按不重试处理 */+ private async keyRecovered(): Promise<boolean> {+ const recovered = await this.opts.recoverKey?.().catch(() => false);+ if (recovered) log.info("model key was reissued, retrying the message once");+ return !!recovered;+ }+/*** signal:网页的停止按钮(排队时就停了也算);/stop 经 stop() 走同一条路。纯对话中止模型请求并保留已生成的部分,* 代理回合交给代理之前直接收尾,之后由代理中止。@@ -347,11 +359,17 @@ export class BotRuntime {await out.apply({ type: "typing", on: true });await out.apply({ type: "stream.start" });let acc = "";- try {- const full = await this.opts.models.streamChat({ model: routed, messages, signal }, (delta) => {+ const call = () =>+ this.opts.models.streamChat({ model: routed, messages, signal }, (delta) => {acc += delta;void out.apply({ type: "stream.update", text: acc });});+ try {+ const full = await call().catch(async (e: Error) => {+ // 一个字都还没出来就失败:Key 若刚被换掉,就用新 Key 再发一次+ if (acc || signal.aborted || !(await this.keyRecovered())) throw e;+ return call();+ });const finalText = full || acc || t("runtime.emptyReply");store.addMessage(conv.id, "assistant", finalText);await out.apply({ type: "stream.finish", text: note ? `${note}\n\n${finalText}` : finalText });@@ -559,32 +577,42 @@ export class BotRuntime {// 后台任务的结果发出去之后,下一条聊天消息带上那张便条:聊天代理知道发生了什么const notes = takeTaskNotes(store, convId);const input = notes ? `${notes}\n\n${first}` : first;- // runTurn 同步登记回合,之后的停止交给代理(TurnStopped,会重启代理进程)- const turn = agent.runTurn(botId, {- conversationId: convId,- text: input,- model,- ...(images.length ? { images } : {}),- onStep,- observer: {- // 工具调用不进入聊天:只用于判断代理已开始工作(不再回退到纯对话),正在输入状态由渠道维持- onProgress: () => {- visible = true;- },- // 代理收下了这条消息:先存用户消息(之后并进来的消息排在它后面),再让出渠道队列,后来的消息可以并入这一轮- onStart: () => {- if (!inflight.userStored) store.addMessage(convId, "user", text);- inflight.userStored = true;- inflight.release?.();+ const runOnce = async () => {+ // runTurn 同步登记回合,之后的停止交给代理(TurnStopped,会重启代理进程)+ const turn = agent.runTurn(botId, {+ conversationId: convId,+ text: input,+ model,+ ...(images.length ? { images } : {}),+ onStep,+ observer: {+ // 工具调用不进入聊天:只用于判断代理已开始工作(不再回退到纯对话),正在输入状态由渠道维持+ onProgress: () => {+ visible = true;+ },+ // 代理收下了这条消息:先存用户消息(之后并进来的消息排在它后面),再让出渠道队列,后来的消息可以并入这一轮+ onStart: () => {+ if (!inflight.userStored) store.addMessage(convId, "user", text);+ inflight.userStored = true;+ inflight.release?.();+ },},- },- });- const halt = () => agent.stopTurn(convId);- signal.addEventListener("abort", halt, { once: true });- const r = await turn.finally(() => {- clearInterval(startup);- signal.removeEventListener("abort", halt);- });+ });+ const halt = () => agent.stopTurn(convId);+ signal.addEventListener("abort", halt, { once: true });+ try {+ return await turn;+ } finally {+ signal.removeEventListener("abort", halt);+ }+ };+ const r = await runOnce()+ .catch(async (e: Error) => {+ // 还没有任何步骤就失败(没调用工具、没有副作用):Key 若刚被换掉,就用新 Key 把这一回合再跑一次+ if (e instanceof TurnStopped || signal.aborted || visible || steps.size || agent.host(botId).state !== "running" || !(await this.keyRecovered())) throw e;+ return runOnce();+ })+ .finally(() => clearInterval(startup));if (!inflight.userStored) store.addMessage(convId, "user", text);inflight.userStored = true;const finalText = r.text.trim() || t("runtime.doneNoText");diff --git a/src/i18n/messages/account.ts b/src/i18n/messages/account.tsindex 57a6d80..eee75dd 100644--- a/src/i18n/messages/account.ts+++ b/src/i18n/messages/account.ts@@ -13,6 +13,8 @@ export const zh = {sign_in_first: "请先登录 Modelflare 账户",low_balance: "Modelflare 余额只剩 ${balance},低于提醒线 ${threshold}。充值:{url}",budget_needs_login: "给机器人设预算需要先登录 Modelflare 账户",+ key_reissued: "本机用的 Modelflare API Key 已被删除,已自动重新签发一把",+ bot_key_reissued: "机器人「{name}」的预算 Key 已被删除,已按 ${limit} 的预算重新签发(用量从零算起)",// oauth.tshost_unreachable: "连不上 {host}({reason})",discovery_failed: "读取登录配置失败(HTTP {status})",@@ -45,6 +47,8 @@ export const en: Catalog<typeof zh> = {sign_in_first: "Sign in to your Modelflare account first",low_balance: "Your Modelflare balance is down to ${balance}, below your ${threshold} alert threshold. Top up: {url}",budget_needs_login: "Sign in to your Modelflare account to set a bot budget",+ key_reissued: "This computer's Modelflare API key was deleted, so a new one was issued automatically",+ bot_key_reissued: "The budget key for bot \"{name}\" was deleted, so a new one was issued with the ${limit} budget (spending starts from zero)",host_unreachable: "Can't reach {host} ({reason})",discovery_failed: "Couldn't read the sign-in configuration (HTTP {status})",discovery_bad_endpoint: "Invalid {key} in the sign-in configuration",diff --git a/test/account.test.ts b/test/account.test.tsindex e5818af..57fc9b7 100644--- a/test/account.test.ts+++ b/test/account.test.ts@@ -80,12 +80,23 @@ describe("AccountManager", () => {let calls: string[];let alerts: string[];let manager: AccountManager;+ /** 内置网关共用连接现在用的 Key */+ let gw: string;const hooks = (): AccountHooks => ({- connectKey: async (key) => void calls.push(`connect:${key}`),- disconnect: async () => void calls.push("disconnect"),+ connectKey: async (key) => {+ calls.push(`connect:${key}`);+ gw = key;+ },+ disconnect: async () => {+ calls.push("disconnect");+ gw = "";+ },setBotKey: async (botId, key) => void calls.push(`bot:${botId}:${key}`),removeBotKey: async (botId) => void calls.push(`unbot:${botId}`),keyBalance: async () => undefined,+ sharedKeyTail: () => gw.slice(-4),+ // mock 签发的 Key 被删了就失效;别的 Key 当作用户自己粘贴的、还能用的+ sharedKeyRejected: async () => !gw || (gw.startsWith("sk-key-") && !mf.s.keys.some((k) => `sk-key-${k.id}` === gw)),alert: (text) => void alerts.push(text),});const make = () => {@@ -101,6 +112,7 @@ describe("AccountManager", () => {const url = await manager.startLogin();await approveInBrowser(mf, url);await until(() => manager.status().state === "signed_in");+ await manager.repairKeys(Infinity); // 等登录后那次核对跑完};beforeEach(async () => {@@ -109,6 +121,7 @@ describe("AccountManager", () => {store = new Store(":memory:");calls = [];alerts = [];+ gw = "";manager = make();});afterEach(async () => {@@ -189,6 +202,89 @@ describe("AccountManager", () => {it("没登录时不能设预算", async () => {await expect(manager.setBotBudget("b1", "x", { enabled: true, limitUsd: 1 })).rejects.toMatchObject({ status: 409 });});++ it("令牌轮换后账户文件里仍记着本机 Key 的 id", async () => {+ await signIn();+ mf.s.access.clear(); // 让下一次请求 401,强制换一次令牌+ await manager.refresh();+ expect(AccountVault.at(dir).load()).toMatchObject({ refreshToken: "rt-2", deviceKeyId: 1 });+ });++ it("Key 都在:核对不签发、不提醒;并发核对只请求一次,maxAgeMs 内沿用上次结果", async () => {+ await signIn();+ const before = mf.s.keyLists;+ expect(await Promise.all([manager.repairKeys(), manager.repairKeys()])).toEqual([false, false]);+ expect(await manager.repairKeys(60_000)).toBe(false);+ expect(mf.s.keyLists).toBe(before + 1);+ expect(mf.s.keys.map((k) => k.id)).toEqual([1]);+ expect(calls).toEqual(["connect:sk-key-1"]);+ expect(alerts).toEqual([]);+ });++ it("本机 Key 在控制台被删:重新签发、接到网关、记下新 id、提醒一次", async () => {+ await signIn();+ mf.s.keys = [];+ expect(await manager.repairKeys()).toBe(true);+ expect(calls).toEqual(["connect:sk-key-1", "connect:sk-key-2"]);+ expect(mf.s.keys).toMatchObject([{ id: 2, name: "AnyModelBot · test-pc" }]);+ expect(AccountVault.at(dir).load()!.deviceKeyId).toBe(2);+ expect(alerts.filter((a) => a.includes("已自动重新签发"))).toHaveLength(1);+ // 刚换过:maxAgeMs 内再问得到“换过了”(失败的请求可以重试),过后重新核对,没再换+ expect(await manager.repairKeys(60_000)).toBe(true);+ expect(await manager.repairKeys()).toBe(false);+ expect(mf.s.keys).toHaveLength(1);+ });++ it("旧版本把本机 Key 的 id 记成了 0:按网关里 Key 的尾号认回来,不另签", async () => {+ await signIn();+ AccountVault.at(dir).save({ ...AccountVault.at(dir).load()!, deviceKeyId: 0 });+ const again = make();+ expect(await again.repairKeys()).toBe(false);+ expect(AccountVault.at(dir).load()!.deviceKeyId).toBe(1);+ expect(mf.s.keys).toHaveLength(1);+ });++ it("网关里换成了用户自己粘贴、还能用的 Key:本机 Key 被删也不去替换", async () => {+ await signIn();+ gw = "sk-user-own-key";+ mf.s.keys = [];+ expect(await manager.repairKeys()).toBe(false);+ expect(gw).toBe("sk-user-own-key");+ expect(mf.s.keys).toHaveLength(0);+ });++ it("预算 Key 被删:按现在的预算重新签发;预算已关掉的只拿掉网关里失效的 Key", async () => {+ await signIn();+ const bots = [+ { id: "b1", name: "写作助手", budget: { enabled: true, limitUsd: 5 } },+ { id: "b2", name: "翻译", budget: { enabled: true, limitUsd: 2 } },+ ];+ manager.botsSource = () => bots;+ await manager.setBotBudget("b1", "写作助手", bots[0].budget);+ await manager.setBotBudget("b2", "翻译", bots[1].budget);+ bots[1].budget = { enabled: false, limitUsd: 2 }; // 只改了本机设置,Key 还在(模拟不一致的状态)+ mf.s.keys = mf.s.keys.filter((k) => k.id === 1);+ expect(await manager.repairKeys()).toBe(true);+ expect(calls).toContain("bot:b1:sk-key-4");+ expect(calls).toContain("unbot:b2");+ expect(mf.s.keys.find((k) => k.id === 4)).toMatchObject({ name: "AnyModelBot · 写作助手", limit_usd: 5 });+ expect(alerts.filter((a) => a.includes("写作助手") && a.includes("$5"))).toHaveLength(1);+ expect(await manager.botBudgets()).toMatchObject({ b1: { limit_usd: 5 } });+ expect(Object.keys(await manager.botBudgets())).toEqual(["b1"]);+ });++ it("登录后给开着预算的机器人补签 Key,不提醒“被删”", async () => {+ manager.botsSource = () => [{ id: "b1", name: "写作助手", budget: { enabled: true, limitUsd: 3 } }];+ await signIn();+ await until(() => calls.includes("bot:b1:sk-key-2"));+ expect(await manager.repairKeys()).toBe(false);+ expect(mf.s.keys).toHaveLength(2);+ expect(alerts).toEqual([]);+ });++ it("没登录时不核对", async () => {+ expect(await manager.repairKeys()).toBe(false);+ });});describe("账户文件加密", () => {@@ -585,3 +681,95 @@ describe("amb-media 插件与 bridge", () => {}});});++describe("Key 失效后自动重试", () => {+ const ev: any = { id: "e1", channel: "web", botId: "b1", conversation: { kind: "dm", id: "console" }, sender: { id: "u", name: "u" }, parts: [{ type: "text", text: "hi" }], replyHandle: {}, receivedAt: Date.now() };+ const setup = async (o: { agent?: any; models?: any; recovered: boolean }) => {+ const { BotRuntime } = await import("../src/core/runtime.js");+ const store = new Store(":memory:");+ store.createBot({ id: "b1", name: "b", defaultModel: "m1" });+ let recovers = 0;+ const rt = new BotRuntime({+ store,+ models: o.models ?? { listModels: async () => ["m1"], streamChat: async () => "plain" },+ defaultModel: () => "",+ contextMessages: 10,+ contextChars: 5000,+ agent: o.agent,+ recoverKey: async () => (recovers++, o.recovered),+ });+ const ops: any[] = [];+ await rt.handle(ev, { apply: async (op: any) => void ops.push(op) });+ store.close();+ return { finish: ops.filter((x) => x.type === "stream.finish").at(-1)?.text as string, recovers: () => recovers };+ };+ const flaky = (failures: Array<(onDelta: (d: string) => void) => void>) => {+ let n = 0;+ return {+ calls: () => n,+ listModels: async () => ["m1"],+ streamChat: async (_r: unknown, onDelta: (d: string) => void) => {+ const fail = failures[n++];+ if (fail) {+ fail(onDelta);+ throw new Error("HTTP 401 invalid token");+ }+ onDelta("ok");+ return "ok";+ },+ };+ };++ it("纯对话:还没输出就失败、Key 换过了 → 用新 Key 再发一次", async () => {+ const models = flaky([() => {}]);+ const r = await setup({ models, recovered: true });+ expect(models.calls()).toBe(2);+ expect(r.recovers()).toBe(1);+ expect(r.finish).toBe("ok");+ });++ it("纯对话:Key 没换就不重试,照常报错;已经输出了一部分也不重试", async () => {+ const m1 = flaky([() => {}]);+ const r1 = await setup({ models: m1, recovered: false });+ expect(m1.calls()).toBe(1);+ expect(r1.finish).toContain("HTTP 401");+ const m2 = flaky([(d) => d("半句")]);+ const r2 = await setup({ models: m2, recovered: true });+ expect(m2.calls()).toBe(1);+ expect(r2.recovers()).toBe(0);+ expect(r2.finish).toContain("半句");+ });++ const agentWith = (runTurn: (input: any) => Promise<any>) => ({+ available: true,+ host: () => ({ state: "running", workspace: os.tmpdir() }),+ approvals: { bindSink: () => () => {}, handleReply: () => ({ handled: false }), pending: () => [] },+ runTurn: (_botId: string, input: any) => runTurn(input),+ settings: () => ({ memory: { enabled: false } }),+ takeSeed: () => "",+ });++ it("代理回合:还没调用工具就失败、Key 换过了 → 整个回合再跑一次", async () => {+ let n = 0;+ const agent = agentWith(async () => {+ if (n++ === 0) throw new Error("401 invalid token");+ return { text: "agent ok", files: [] };+ });+ const r = await setup({ agent, recovered: true });+ expect(n).toBe(2);+ expect(r.finish).toBe("agent ok");+ });++ it("代理回合:已经调用过工具(可能有副作用)就不重试", async () => {+ let n = 0;+ const agent = agentWith(async (input) => {+ n++;+ input.observer.onProgress("🔧 bash");+ throw new Error("401 invalid token");+ });+ const r = await setup({ agent, recovered: true });+ expect(n).toBe(1);+ expect(r.recovers()).toBe(0);+ expect(r.finish).toContain("401 invalid token");+ });+});diff --git a/test/helpers.ts b/test/helpers.tsindex 87259f8..1760389 100644--- a/test/helpers.ts+++ b/test/helpers.ts@@ -307,9 +307,14 @@ export async function mockModelflare() {keys: [] as Array<{ id: number; name: string; limit_usd: number | null; used_usd: number }>,balance: 12.5,revokeAll: false,+ /** GET /api-keys 被请求的次数 */+ keyLists: 0,};let base = "";let n = 0;+ // Key 的 id 和服务端一样只增不减:删掉一把后新签发的不会和它重号+ let keySeq = 0;+ const keyOut = (k: (typeof s.keys)[number]) => ({ ...k, key_tail: `sk-key-${k.id}`.slice(-4), status: "enabled", unlimited: k.limit_usd === null, remain_usd: k.limit_usd });const issue = (res: http.ServerResponse) => {const access = `at-${++n}`;const refresh = `rt-${n}`;@@ -356,11 +361,14 @@ export async function mockModelflare() {if (p === "/account") return json({ success: true, data: { display_name: "Ada", username: "ada", group: "default", balance_usd: s.balance, used_usd: 3, billed_to_enterprise: false, quota_per_unit: 500000 } });if (p === "/api-keys" && req.method === "POST") {const b = await readJson(req);- const k = { id: s.keys.length + 1, name: b.name, limit_usd: b.limit_usd ?? null, used_usd: 0 };+ const k = { id: ++keySeq, name: b.name, limit_usd: b.limit_usd ?? null, used_usd: 0 };s.keys.push(k);- return json({ success: true, data: { ...k, key: `sk-key-${k.id}`, key_tail: `y-${k.id}`, status: "enabled", unlimited: k.limit_usd === null, remain_usd: k.limit_usd } });+ return json({ success: true, data: { ...keyOut(k), key: `sk-key-${k.id}` } });+ }+ if (p === "/api-keys" && req.method === "GET") {+ s.keyLists++;+ return json({ success: true, data: s.keys.map(keyOut) });}- if (p === "/api-keys" && req.method === "GET") return json({ success: true, data: s.keys.map((k) => ({ ...k, status: "enabled", unlimited: k.limit_usd === null, remain_usd: k.limit_usd })) });const m = p.match(/^\/api-keys\/(\d+)$/);if (m && req.method === "PATCH") {const k = s.keys.find((x) => x.id === Number(m[1]));