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(magpie): one restart chain, one instance, nothing spawned after stop()

Marlaf053845970dc
diff --git a/src/magpie/supervisor.ts b/src/magpie/supervisor.ts
index da97f02..6696ebb 100644
--- a/src/magpie/supervisor.ts
+++ b/src/magpie/supervisor.ts
@@ -94,6 +94,8 @@ export class MagpieSupervisor {
private keys!: Keys;
private readonly root: string;
private restartTimer: NodeJS.Timeout | undefined;
+ /** 正在进行的那一次拉起(同一时间只有一次) */
+ private spawning: Promise<void> | undefined;
private logTail: string[] = [];
/** 当前(或最近一次)magpie 子进程 */
pid: number | undefined;
@@ -237,10 +239,32 @@ export class MagpieSupervisor {
this.saveKeys();
} else log.warn("gateway-key add failed (loopback still works)", { stderr: r.stderr.slice(0, 200) });
}
- await this.spawnOnce();
+ await this.launch();
}
- private async spawnOnce(): Promise<void> {
+ /**
+ * 拉起一次,起不来(启动中退出、健康检查超时)就安排下一次。重启只在这里和运行中退出时安排:
+ * 两处都安排的话,每失败一次就多出一条重启链。
+ */
+ private async launch(): Promise<void> {
+ try {
+ await this.spawnOnce();
+ } catch (e) {
+ this.scheduleRestart();
+ throw e;
+ }
+ }
+
+ /** 同一时间只拉起一个(并发调用共用这一次),否则后起的会顶掉 this.child,先起的那个就没人管了 */
+ private spawnOnce(): Promise<void> {
+ this.spawning ??= this.spawnChild().finally(() => (this.spawning = undefined));
+ return this.spawning;
+ }
+
+ private async spawnChild(): Promise<void> {
+ if (this.stopping) return;
+ // 还管着一个旧进程(不该发生):先结束它,不留没人管的实例
+ if (this.child) this.child.kill("SIGKILL");
this.state = this.restarts ? "restarting" : "starting";
const args = ["web", "--addr", `127.0.0.1:${this.webPort}`, "--no-open", "--gateway"];
// windowsHide:magpie 是控制台程序,Electron 是 GUI 程序;不加的话 Windows 上每次启动都会弹出一个黑色控制台窗口
@@ -269,10 +293,12 @@ export class MagpieSupervisor {
}
this.lastError = `magpie exited (code=${code}, signal=${signal})`;
log.warn(this.lastError);
- this.scheduleRestart();
+ // 启动中退出由 launch 安排重启;这里只管运行中崩溃
+ if (this.state === "running") this.scheduleRestart();
});
try {
await this.waitHealthy(this.opts.healthTimeoutMs ?? 20_000);
+ if (this.child !== child) throw new Error("magpie exited during startup: " + this.recentLog.slice(-3).join(" | "));
this.state = "running";
log.info(`magpie running: gateway 127.0.0.1:${this.gatewayPort}, web 127.0.0.1:${this.webPort}`);
} catch (e) {
@@ -283,15 +309,15 @@ export class MagpieSupervisor {
}
private scheduleRestart(): void {
+ // 已经排着一次(或已停止):不再多排
+ if (this.stopping || this.restartTimer) return;
this.restarts++;
const delay = Math.min(30_000, 500 * 2 ** Math.min(this.restarts, 6));
this.state = "restarting";
this.restartTimer = setTimeout(() => {
this.restartTimer = undefined;
- this.spawnOnce().catch((e) => {
- log.error("magpie restart failed", { message: (e as Error).message });
- if (!this.stopping) this.scheduleRestart();
- });
+ if (this.stopping) return;
+ this.launch().catch((e) => log.error("magpie restart failed", { message: (e as Error).message }));
}, delay);
}
@@ -363,9 +389,11 @@ export class MagpieSupervisor {
async stop(): Promise<void> {
this.stopping = true;
- if (this.restartTimer) clearTimeout(this.restartTimer);
+ clearTimeout(this.restartTimer);
+ this.restartTimer = undefined;
const child = this.child;
if (!child) {
+ await this.spawning?.catch(() => undefined);
this.state = "stopped";
return;
}
@@ -377,6 +405,8 @@ export class MagpieSupervisor {
});
child.kill(process.platform === "win32" ? undefined : "SIGTERM");
});
+ // 正在拉起的那一次随子进程结束而失败;等它收尾,之后的 start() 不会接上它
+ await this.spawning?.catch(() => undefined);
this.child = undefined;
this.state = "stopped";
}
diff --git a/test/magpie-supervisor.unit.test.ts b/test/magpie-supervisor.unit.test.ts
new file mode 100644
index 0000000..ed64fb2
--- /dev/null
+++ b/test/magpie-supervisor.unit.test.ts
@@ -0,0 +1,107 @@
+/** magpie 守护:起不来时只有一条重启链,同一时间只有一个实例,stop() 之后不再拉起、不留实例。 */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { MagpieSupervisor } from "../src/magpie/supervisor.js";
+import { until } from "./helpers.js";
+
+const realSetTimeout = globalThis.setTimeout;
+const sleep = (ms: number) => new Promise((r) => realSetTimeout(r, ms));
+const alive = (pid: number) => {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+let dir: string;
+let sup: MagpieSupervisor | undefined;
+let pids: () => number[] = () => [];
+beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-magpie-"));
+});
+afterEach(async () => {
+ await sup?.stop();
+ sup = undefined;
+ vi.restoreAllMocks();
+ for (const pid of pids()) if (alive(pid)) process.kill(pid, "SIGKILL");
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+
+/**
+ * 假的 magpie(Node 脚本):前 failFirst 次 `web` 立刻退出,之后在网关和网页端口上回 200;端口被占就退出。
+ * 每次运行记一行 "<pid> <参数>"。返回可执行文件路径。
+ */
+function fakeMagpie(failFirst: number): string {
+ const log = path.join(dir, "calls.log");
+ const bin = path.join(dir, "magpie-fake");
+ fs.writeFileSync(
+ bin,
+ `#!${process.execPath}
+const fs = require("node:fs");
+const http = require("node:http");
+const LOG = ${JSON.stringify(log)};
+const args = process.argv.slice(2);
+fs.appendFileSync(LOG, process.pid + " " + args.join(" ") + "\\n");
+if (args[0] !== "web") process.exit(0);
+const n = fs.readFileSync(LOG, "utf8").split("\\n").filter((l) => l.includes(" web ")).length;
+if (n <= ${failFirst}) process.exit(1);
+const listen = (addr) => new Promise((ok, fail) => {
+ const [host, port] = addr.split(":");
+ const s = http.createServer((req, res) => res.end("{}"));
+ s.on("error", fail);
+ s.listen(Number(port), host, ok);
+});
+Promise.all([listen(process.env.MAGPIE_ADDR), listen(args[args.indexOf("--addr") + 1])]).catch(() => process.exit(1));
+`,
+ { mode: 0o755 },
+ );
+ pids = () => (fs.existsSync(log) ? fs.readFileSync(log, "utf8") : "").split("\n").filter((l) => l.includes(" web ")).map((l) => Number(l.split(" ")[0]));
+ return bin;
+}
+
+/** 时间缩短 20 倍:重启退避(1 s、2 s、4 s…)和健康检查的轮询间隔(200 ms)一起缩,先后顺序和真实的一样 */
+function fastBackoff() {
+ vi.spyOn(globalThis, "setTimeout").mockImplementation(((fn: () => void, ms?: number, ...a: unknown[]) => realSetTimeout(fn, Math.ceil((ms ?? 0) / 20), ...a)) as any);
+}
+
+describe.skipIf(process.platform === "win32")("magpie supervisor restarts", () => {
+ it("a magpie that keeps failing is retried on one chain, and nothing is spawned after stop()", async () => {
+ const bin = fakeMagpie(Infinity);
+ fastBackoff();
+ sup = new MagpieSupervisor({ dataDir: dir, binPath: bin, healthTimeoutMs: 3000 });
+ await expect(sup.start()).rejects.toThrow(/exited during startup/);
+ await sleep(3000);
+ const spawns = pids().length;
+ expect(spawns).toBeGreaterThan(3);
+ // 每次失败只排一次重启(两处都排的话,重启链每轮翻倍)
+ expect(sup.restarts).toBeLessThanOrEqual(spawns);
+ await sup.stop();
+ expect(sup.state).toBe("stopped");
+ const atStop = pids().length;
+ await sleep(1500);
+ expect(pids().length, "magpie was spawned again after stop()").toBe(atStop);
+ }, 20_000);
+
+ it("the instance that came up is the one tracked: stop() leaves no magpie running", async () => {
+ const bin = fakeMagpie(2);
+ fastBackoff();
+ sup = new MagpieSupervisor({ dataDir: dir, binPath: bin, healthTimeoutMs: 3000 });
+ await expect(sup.start()).rejects.toThrow(/exited during startup/);
+ await until(() => sup!.state === "running", 10_000);
+ // 第二条重启链(如果有)这时会再拉起实例,顶掉正在跑的那个
+ await sleep(1500);
+ const { state, restarts } = sup;
+ const spawned = pids();
+ const pidFile = fs.readFileSync(path.join(dir, "magpie", "magpie.pid"), "utf8");
+ await sup.stop();
+ expect(pids().filter(alive), "a magpie instance is still running after stop()").toEqual([]);
+ expect(state).toBe("running");
+ expect(spawned).toHaveLength(3);
+ expect(restarts).toBe(2);
+ expect(pidFile).toBe(String(spawned[2]));
+ }, 20_000);
+});