page-chat 0.1.8: the service takes its port once the old host lets go, instead of giving up after 6s (ferock on Discord)

ferock on Discord, after page-chat updated itself to 0.1.7: typing a
system prompt said "保存失败:Failed to fetch", and every message after
failed the same way. The system prompt wasn't the cause. Nothing was
listening on the page's port any more.

magpie swaps plugin hosts when a plugin is updated, installed or set
(Restart, or another magpie's change to plugins.json). An old host that
is still finishing a call (a reply, a tool call) keeps running, up to 10
minutes, and its page service keeps 3477. The new host's service tried
for 6s, threw "3477 一直被占用", and never tried again. When the old
host left, nobody had the port. The page's frame stayed on
127.0.0.1:3477, and every fetch failed until magpie was restarted.

startServer now tries for those 6s (bindTries x 500ms) without holding
up the host. Then it goes on trying once a second in the background
until the port is free, and stops when the service is closed. The page's
next request gets 403 with the new token, and the page reloads itself
as before. index.mjs logs "listening" when the port is bound.

Run (mote):
- Reproduced with real magpie serve (magpie origin/main 36af588e2) in a
  sandbox HOME, page-chat on port 3592. A plugin tool that takes 40s was
  in flight while page-chat 0.1.6 was auto-updated to 0.1.7 by
  KeepUpdated, or while another plugin was added. 0.1.7's service logged
  "could not start: 3592 一直被占用", and every save to /api/settings got
  000 (no listener) after the old host left, even with a fresh token.
  With this change the same run logs "还被占着" and then "listening".
  A save gets 403 (new token), and the page's reload saves 200.
- Without a busy host, an update came back on its own (403, reload). So
  did saves of Chinese, quoted, multi-line and 50k-char system prompts
  and a chat on 0.1.7. None of them failed.
- bun test chat.test.mjs: 31 pass. The two new tests are red on the old
  lib ("58585 一直被占用,服务起不来"), checked by hand.
- bun scripts/check.mjs ok.

Not tried: magpie's desktop window (WebKit). The page there was not
driven; its 403 reload path is unchanged.
This commit is contained in:
yetone
2026-11-01 12:25:02 +08:00
parent 74ef5602f1
commit b38ad66551
5 changed files with 110 additions and 11 deletions
+2
View File
@@ -60,6 +60,8 @@ Only the chat page it served:
The launcher and the service both read it. Change it if something else holds 3477.
When magpie swaps plugin hosts (a plugin updated, installed or set) while the old host is still finishing a call, the old host's service keeps the port until that call ends. The new host's service waits for it, trying again every second, and takes the port once it is free. The open page's next request then gets a new token and the page reloads itself.
## Starting it without magpie's host
`serve.mjs` (`node serve.mjs`, or `start-server.cmd` / `start-server.vbs` on Windows) starts the same service on its own, and `install-autostart.cmd` puts it in Windows' Startup folder. See [SERVE.md](SERVE.md). None of these runs unless you start it.
+48
View File
@@ -544,3 +544,51 @@ test("with mcpAll on, a chat gets magpie's own MCP servers that are on, beside t
await own.close()
}
})
// magpie swaps hosts (a plugin updated, installed or set) while the old one
// still finishes a call, so the old host's service keeps the page's port
// for as long as that call runs. The new host's service used to give up
// after 6s, and once the old host left nothing listened there: every
// request of the page failed to fetch (ferock, page-chat 0.1.6 updated to
// 0.1.7 under a busy host).
test("a port held past the first wait is taken once its holder lets go", async () => {
const { createServer } = await import("node:net")
const holder = createServer()
await new Promise((r) => holder.listen(0, "127.0.0.1", r))
const port = holder.address().port
const { startServer } = await import("./lib/server.mjs")
const svc = await startServer({ configDir: cfg, options: { port }, bindTries: 1 })
try {
expect(svc.listening).toBe(false)
expect(svc.port).toBe(port)
await new Promise((r) => holder.close(r))
expect(await svc.ready).toBe(port)
const got = await new Promise((resolve, reject) => {
const req = request({ host: "127.0.0.1", port, method: "GET", path: "/api/ping", headers: { host: `127.0.0.1:${port}`, origin: "null" } }, (res) => {
let data = ""
res.setEncoding("utf8")
res.on("data", (c) => (data += c))
res.on("end", () => resolve({ status: res.statusCode, body: data }))
})
req.on("error", reject)
req.end()
})
expect(got.status).toBe(200)
expect(JSON.parse(got.body).port).toBe(port)
} finally {
holder.listening && holder.close()
await svc.close()
}
})
test("a service closed while it waits for its port stops waiting", async () => {
const { createServer } = await import("node:net")
const holder = createServer()
await new Promise((r) => holder.listen(0, "127.0.0.1", r))
const port = holder.address().port
const { startServer } = await import("./lib/server.mjs")
const svc = await startServer({ configDir: cfg, options: { port }, bindTries: 1 })
await svc.close()
expect(await svc.ready).toBe(0)
await new Promise((r) => holder.close(r))
})
+8 -1
View File
@@ -21,7 +21,14 @@ function start(options) {
options: Number.isFinite(port) && port > 0 ? { port } : {},
})
.then((info) => {
console.log(`[page-chat] listening on http://127.0.0.1:${info.port}`);
// 端口还在上一个宿主手里时不挡宿主启动:服务在后台等它松手
if (info.listening) console.log(`[page-chat] listening on http://127.0.0.1:${info.port}`);
else {
info.ready.then(
(p) => p && console.log(`[page-chat] listening on http://127.0.0.1:${p}`),
(err) => console.error("[page-chat] could not start:", err?.message || err),
);
}
return info;
})
.catch((err) => {
+51 -9
View File
@@ -548,7 +548,7 @@ async function runChat({ res, body, settings, store, options }, controllers) {
}
}
export async function startServer({ configDir: dirArg, options = {} } = {}) {
export async function startServer({ configDir: dirArg, options = {}, bindTries = 12 } = {}) {
// 调用方常传 configDir: "";libraryView(dir = configDir()) 的默认值只在参数是
// undefined 时生效,空字符串会让 join("", "library") 变成相对路径,指令 / 技能 /
// MCP 全读不到。这里统一兜成真实目录。
@@ -785,25 +785,67 @@ export async function startServer({ configDir: dirArg, options = {} } = {}) {
// 端口固定用 3477 —— 带路页写死了跳这个端口(页面 CSP 是 connect-src 'none',
// 没法先探测再决定跳哪,只能盲跳)。所以这里也必须是 3477,换端口页面就连不上了。
// 被上一次的宿主占着就等它松手,最多等 6 秒。
// 被上一次的宿主占着就等它松手:先等 6 秒(bindTries × 500ms),还没松手就在后台
// 每秒再试,直到绑上为止,不放弃。
//
// 以前等满 6 秒就抛错,这个宿主就再也没有服务了:magpie 换宿主(插件更新、
// 装插件、改选项)时,旧宿主手上还有调用(一条回复、一次工具调用)就会接着跑完,
// 最多 10 分钟,端口一直在它手里。新宿主的服务等 6 秒放弃,旧宿主随后退出,
// 3477 上就谁也没有了 —— 页面每个请求都是 Failed to fetch(ferock,0.1.6 自动
// 更新到 0.1.7 时:「保存失败」「出错:Failed to fetch」,直到重开 magpie)。
let closed = false;
const own = (p) => {
actualPort = p;
OWN = new Set([`http://127.0.0.1:${p}`, `http://localhost:${p}`]);
HOSTS = new Set([`127.0.0.1:${p}`, `localhost:${p}`]);
};
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
let bound = false;
for (let i = 0; i < 12 && !bound; i++) {
for (let i = 0; i < bindTries && !bound; i++) {
try {
await bindOn(port);
bound = true;
} catch (err) {
if (err?.code !== "EADDRINUSE") throw err;
if (i === 0) console.log(`[page-chat] ${port} 被上一次的宿主占着,等一下再绑`);
await new Promise((r) => setTimeout(r, 500));
await sleep(500);
}
}
if (!bound) throw new Error(`${port} 一直被占用,服务起不来`);
actualPort = server.address().port;
OWN = new Set([`http://127.0.0.1:${actualPort}`, `http://localhost:${actualPort}`]);
HOSTS = new Set([`127.0.0.1:${actualPort}`, `localhost:${actualPort}`]);
let ready;
if (bound) {
own(server.address().port);
ready = Promise.resolve(actualPort);
} else {
// 端口是固定的(0 不会被占),页面认的就是它
own(port);
console.log(`[page-chat] ${port} 还被占着:它一松手就接着绑,每秒试一次`);
ready = (async () => {
while (!closed) {
await sleep(1000);
if (closed) break;
try {
await bindOn(port);
own(server.address().port);
return actualPort;
} catch (err) {
if (err?.code !== "EADDRINUSE") throw err;
}
}
return 0;
})();
ready.catch(() => {});
}
// 这里以前会写 port.json 想让带路页读实际端口,但页面 CSP 是 connect-src none,读不到。
return { port: actualPort, server, store, close: async () => { await closeAll(); server.close(); } };
// listening:现在就在听;没有的话 ready 在绑上时给出端口(关掉了就是 0)
return {
port: actualPort,
listening: bound,
ready,
server,
store,
close: async () => { closed = true; await closeAll(); if (server.listening) server.close(); },
};
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/page-chat",
"version": "0.1.7",
"version": "0.1.8",
"description": "在 magpie 窗口里加一个「对话」页面:用 magpie 自己的模型、MCP 服务器、指令和技能聊天,支持图片与 LaTeX。A chat page inside magpie's window: talk with magpie's own models, MCP servers, instructions and skills, with images and LaTeX.",
"author": "Magic_zero (https://github.com/Magiczerowxy)",
"files": [