From 9a4ec8600c040f5cb186b28c35977d55d53ea971 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 15 Oct 2026 17:25:38 +0800 Subject: [PATCH] workbuddy 0.1.24: a refused sign-in on a request over 2 MiB says the 401 and to sign in again, not ECONNRESET (wyp on Discord) wyp's WorkBuddy AI requests worked for a while, then every turn failed as "502 WorkBuddy AI: ECONNRESET: The socket connection was closed unexpectedly". Measured on www.workbuddy.ai and copilot.tencent.com: the front door answers a token it refuses with 401 only for a body up to 2097152 bytes. At 2097153 bytes and above it resets the connection with no reply. With an accepted token, 20 MB bodies go through, and app errors (400 11128) still come back on big bodies. So once a long Claude Code session is past 2 MiB and the account's sign-in is refused, every turn is a reset, and nothing about it is temporary. Keep-alive reuse was ruled out: the server closes an idle connection with a FIN at 60s, and Bun opens a new connection for requests at 59.99s and 59.995s. When a chat over 2 MiB fails before any reply, the loader now asks the meter (POST /billing/meter/get-user-resource-summary, 401 for a refused token) once. On a 401 it returns that 401 with the reason and the remedy (sign in again, in magpie or in the desktop app), marked kept like the plugin's other 401s. Any other answer, a failed meter read, or an abort leaves the original error. The chat is never sent again. Run: HOME= bun test in packages/workbuddy: 97 pass (reset.test.mjs is a socket fake of the front door that resets past 2 MiB). Broke it by hand (unanswered rethrows at once): 3 of the 5 new tests go red. bun scripts/check.mjs workbuddy: ok. Against the real endpoint in a sandbox HOME: refused token + 2.2 MB body gives 401 with the message (0.1.23: ECONNRESET); refused short chat gives the front door's HTML 401; good token + 2.2 MB body gives 200. Not run: magpie's gateway end to end with this version. Why wyp's token was refused is not yet confirmed. --- packages/workbuddy/index.mjs | 65 +++++++++++++-- packages/workbuddy/package.json | 2 +- packages/workbuddy/reset.test.mjs | 127 ++++++++++++++++++++++++++++++ 3 files changed, 186 insertions(+), 8 deletions(-) create mode 100644 packages/workbuddy/reset.test.mjs diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index e1de36f..2c7846b 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -1136,17 +1136,67 @@ const STATUS_TEXT = { } const statusText = (n) => STATUS_TEXT[n] || `HTTP ${n}` -// meter asks the billing API as magpie's built-in did, its errors said -// the same: WorkBuddy's message, else its code, else the HTTP status. -async function meter(site, a, path, body = {}) { - const res = await fetch(site.endpoint + path, { +// meterAsked is the billing API's reply to path, asked with a's sign-in. +function meterAsked(site, a, path, body = {}, signal = AbortSignal.timeout(20000)) { + return fetch(site.endpoint + path, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": "WorkBuddy/" + UA_VERSION, Authorization: "Bearer " + a.access, "X-User-Id": a.uid ?? "", "X-Domain": domainOf(site, a), "X-Product": "SaaS", "X-IDE-Type": "WorkBuddy", ...enterpriseHeaders(a) }, body: JSON.stringify(body), - signal: AbortSignal.timeout(20000), + signal, }) +} + +// EDGE_READS is how much of a request WorkBuddy's front door (APISIX, on +// both sites) reads before it answers a sign-in it refuses. A refused +// request with a longer body gets no answer at all: the connection is +// reset, and the chat fails as "ECONNRESET: The socket connection was +// closed unexpectedly", which says nothing of the sign-in (wyp on Discord, +// 2026-10-15: a Claude Code session past 2 MiB failed on every turn). +// Measured on 2026-10-15 on www.workbuddy.ai and copilot.tencent.com: a +// body of 2097152 bytes with a refused token got 401, one of 2097153 a +// reset; with an accepted token 20 MB went through. +const EDGE_READS = 2 * 1024 * 1024 + +const byteLength = (b) => + typeof b === "string" ? Buffer.byteLength(b) : b instanceof ArrayBuffer || ArrayBuffer.isView(b) ? b.byteLength : 0 + +// unanswered is what a chat whose fetch failed with err comes to: a chat +// past EDGE_READS that the connection was reset on is asked about at the +// billing API, which answers a refused sign-in with its 401 whatever the +// size. A 401 there is the chat's own answer, said as one; anything else +// leaves err as it was, as does a smaller chat, which the front door +// answers itself. The chat isn't sent again. +async function unanswered(site, a, body, err, signal) { + if (signal?.aborted || err?.name === "AbortError" || err?.name === "TimeoutError") throw err + const size = byteLength(body) + if (size <= EDGE_READS) throw err + let status = 0 + try { + const res = await meterAsked(site, a, "/billing/meter/get-user-resource-summary", {}, AbortSignal.timeout(20000)) + status = res.status + await res.body?.cancel() + } catch { + throw err + } + if (status !== 401) throw err + const mb = (size / (1024 * 1024)).toFixed(1) + const message = + `${site.name} refused this account's sign-in (401). It closes the connection on a refused request over 2 MiB ` + + `(this one was ${mb} MiB) instead of answering, which is why it read as ECONNRESET. ` + + (a.source === "desktop" ? `Sign in to ${site.name} desktop again.` : `Sign in to ${site.name} again in magpie.`) + return new Response(JSON.stringify({ error: { message, type: "authentication_error", code: 401 } }), { + status: 401, + statusText: "Unauthorized", + headers: { "content-type": "application/json" }, + }) +} + +// meter asks the billing API as magpie's built-in did, its errors said +// the same: WorkBuddy's message, else its code, else the HTTP status. +async function meter(site, a, path, body = {}) { + const res = await meterAsked(site, a, path, body) let env = {} try { env = JSON.parse(await res.text()) ?? {} @@ -1555,7 +1605,8 @@ function makePlugin(site) { const fit = fitted(body) body = normalizeToolChoice(fit.body) attend(headers, body, session) - const send = (b) => fetch(req ? req.url : input, { ...init, method: init?.method ?? req?.method, headers, body: b }) + const send = (b) => + fetch(req ? req.url : input, { ...init, method: init?.method ?? req?.method, headers, body: b }).catch((e) => unanswered(site, a, b, e, init?.signal)) // a model known to turn tool results then the user's message away // gets the empty reply between them up front (see endsAfterTools) const model = chatOf(body)?.model @@ -1711,4 +1762,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy) export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"]) // for tests -export const _internal = { fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, normalizeToolChoice, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, turnKey, conversationKey, signatureOf } +export const _internal = { EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, normalizeToolChoice, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, turnKey, conversationKey, signatureOf } diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index 290798f..8c4286f 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.1.23", + "version": "0.1.24", "description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)", "type": "module", "main": "./index.mjs", diff --git a/packages/workbuddy/reset.test.mjs b/packages/workbuddy/reset.test.mjs new file mode 100644 index 0000000..09fc34c --- /dev/null +++ b/packages/workbuddy/reset.test.mjs @@ -0,0 +1,127 @@ +// WorkBuddy's front door answers a sign-in it refuses with 401, but only +// for a request of up to 2 MiB: past that it resets the connection, and a +// long Claude Code session's every turn failed as ECONNRESET (wyp on +// Discord, 2026-10-15). The fake below is that front door on a real +// socket, so Bun's fetch meets the same reset it met on www.workbuddy.ai. +import { afterAll, beforeAll, expect, test } from "bun:test" +import net from "node:net" +import { WorkBuddyAIAuthPlugin, WorkBuddyAuthPlugin, _internal } from "./index.mjs" + +const { EDGE_READS } = _internal +const GOOD = "Bearer good" + +let server +let origin +let meterAsked = 0 +let resetAll = false // a reset that isn't the sign-in's: every long body + +beforeAll(async () => { + server = net.createServer((s) => { + let buf = Buffer.alloc(0) + let head = null + s.on("error", () => {}) + s.on("data", (d) => { + buf = Buffer.concat([buf, d]) + if (!head) { + const end = buf.indexOf("\r\n\r\n") + if (end < 0) return + const lines = buf.subarray(0, end).toString("latin1").split("\r\n") + const h = Object.fromEntries(lines.slice(1).map((l) => [l.slice(0, l.indexOf(":")).toLowerCase(), l.slice(l.indexOf(":") + 1).trim()])) + head = { path: lines[0].split(" ")[1], auth: h.authorization, length: Number(h["content-length"] ?? 0) } + buf = buf.subarray(end + 4) + } + const refused = head.auth !== GOOD + if (head.length > EDGE_READS && (refused || resetAll)) { + // the front door reads its 2 MiB, then drops the connection unanswered + if (buf.length > EDGE_READS) s.resetAndDestroy() + return + } + if (buf.length < head.length) return + const { path } = head + head = null + buf = Buffer.alloc(0) + if (path.startsWith("/billing/")) meterAsked++ + if (refused) { + const html = "401 Authorization Required" + s.end(`HTTP/1.1 401 Unauthorized\r\ncontent-type: text/html\r\ncontent-length: ${html.length}\r\nconnection: close\r\n\r\n${html}`) + return + } + const body = path.startsWith("/billing/") ? '{"code":0,"msg":"OK","data":{}}' : 'data: {"choices":[{"delta":{"content":"pong"}}]}\n\ndata: [DONE]\n\n' + s.end(`HTTP/1.1 200 OK\r\ncontent-type: ${path.startsWith("/billing/") ? "application/json" : "text/event-stream"}\r\ncontent-length: ${body.length}\r\nconnection: close\r\n\r\n${body}`) + }) + }) + await new Promise((r) => server.listen(0, "127.0.0.1", r)) + origin = `http://127.0.0.1:${server.address().port}` +}) + +afterAll(() => server.close()) + +// chat is a loader fetch of a body of about size bytes, signed in as token, +// with the site (WorkBuddy AI's, else the China build's) served by the fake +async function chat(token, size, plugin = WorkBuddyAIAuthPlugin, site = "https://www.workbuddy.ai") { + const realFetch = globalThis.fetch + globalThis.fetch = (u, init) => realFetch(String(u instanceof Request ? u.url : u).replace(site, origin), init) + try { + const hooks = await plugin({ client: {} }) + const loader = await hooks.auth.loader(async () => ({ type: "oauth", access: token, uid: "uid", expires: Date.now() + 3600_000 })) + const body = JSON.stringify({ + model: "fast-model", + stream: true, + messages: [ + { role: "system", content: "You are helpful." }, + { role: "user", content: "x".repeat(size) }, + ], + }) + return await loader.fetch(site + "/v2/chat/completions", { method: "POST", body }) + } finally { + globalThis.fetch = realFetch + } +} + +test("a refused sign-in on a chat past 2 MiB says the 401, not ECONNRESET", async () => { + meterAsked = 0 + const res = await chat("refused", EDGE_READS + 100_000) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + const { error } = await res.json() + expect(error.message).toContain("refused this account's sign-in (401)") + expect(error.message).toContain("Sign in to WorkBuddy AI again") + expect(meterAsked).toBe(1) +}) + +test("the China build's front door is read the same way", async () => { + meterAsked = 0 + const res = await chat("refused", EDGE_READS + 100_000, WorkBuddyAuthPlugin, "https://copilot.tencent.com") + expect(res.status).toBe(401) + expect((await res.json()).error.message).toContain("Sign in to WorkBuddy again") + expect(meterAsked).toBe(1) +}) + +test("a refused sign-in on a short chat is the front door's own 401, nothing else asked", async () => { + meterAsked = 0 + const res = await chat("refused", 1000) + expect(res.status).toBe(401) + expect(await res.text()).toContain("401 Authorization Required") + expect(meterAsked).toBe(0) +}) + +test("a reset past 2 MiB with the sign-in accepted stays the reset", async () => { + meterAsked = 0 + resetAll = true + try { + let err + await chat("good", EDGE_READS + 100_000).catch((e) => (err = e)) + expect(err?.code).toBe("ECONNRESET") + expect(meterAsked).toBe(1) + } finally { + resetAll = false + } +}) + +test("an accepted sign-in's chat past 2 MiB goes through", async () => { + meterAsked = 0 + const res = await chat(GOOD.slice(7), EDGE_READS + 100_000) + expect(res.status).toBe(200) + expect(await res.text()).toContain("pong") + expect(meterAsked).toBe(0) +})