Files
plugins/packages/workbuddy/reset.test.mjs
T
yetone 9a4ec8600c 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=<temp> 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.
2026-10-15 17:25:38 +08:00

128 lines
5.1 KiB
JavaScript

// 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 = "<html><head><title>401 Authorization Required</title></head></html>"
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)
})