Files
plugins/packages/workbuddy/testdata/sent.mjs
T
yetone 95fa76126d workbuddy 0.1.44: a huge chat's ids are hashed in pieces, and it is read once on every path (#461)
0.1.42 brought jihuayu's 45 MiB repro from 7 parses a request to 2, and
0.1.43 keeps that: one full parse and one full stringify a request. What
was left of the peak was attendChat: the conversation and turn ids were
made from template strings holding the whole user message (`first:${sig}`,
`u1:${sig}`, `${conv}|${turn}`, then `${SALT}|kind|${key}`), each a fresh
45 MB string, ~160 MiB of peak a request. The keys are now lists of
pieces fed to one sha256 each, whole (Bun hashes a one-byte string in
place; 1 MiB slices cost a copy and were worse), with a high surrogate
split between pieces held for the next one, so every id is the hash of
the same string as before.

Also read once on paths the repro doesn't take:
- "Free models only" parsed the body again for its model; it reads the
  chat prepared already parsed.
- A model known to want a reply after tools (11153) had the body parsed
  and stringified again on every request; the reply goes into the one
  parsed chat before the one stringify.
- The prepared result no longer holds the parsed tree past the send.

Every byte WorkBuddy sees is unchanged: sent.test.mjs runs 12 chats
(OpenCode tools, default effort, developer turn, after-tools refusal and
known, system refusal and known, both, Messages, bytes, not JSON),
switch off and on, and holds the gunzipped body's sha256, url, encoding
and which requests share an id to testdata/sent-0.1.43.json, made by
running the same harness on npm's 0.1.43 index.mjs (sha 9213db6d...).

Run on mote (Bun 1.4.2), the issue's benchmark.mjs as written but for
the import, 45.3 MiB body, 4 requests, concurrency 1, /usr/bin/time -l,
3 runs each:
  direct (no plugin)   336 MiB
  0.1.41               981-1117 MiB, 28 parses (1087.5 MiB), 24 stringifies
  0.1.43               717-760 MiB, 8 parses (181.3 MiB), 20 stringifies
  0.1.44               583 MiB all 3 runs, same counts, ~370-420 ms wall
                       (0.1.43 ~400-530 ms)
One request: direct 134, 0.1.41 569, 0.1.43 390, 0.1.44 275 MiB (with
id derivation stubbed out entirely: 229).
- HOME=$(mktemp -d) bun test in packages/workbuddy at this head:
  201 pass, 0 fail. bun scripts/check.mjs workbuddy: ok.
- Broken by hand, each red: free-only parsing again -> the free-only
  parse-count test; reply after tools put in by re-parsing -> the
  after-tools parse-count test; no surrogate hold -> the idFor pieces
  test; the reply put in before the system move -> sent.test.mjs.
gzip was measured too: Buffer.from before gzipSync made no difference
to the peak, so it is unchanged.

Not tried: a live WorkBuddy request; the reporter's Linux and Bun
1.4.4 (mote has 1.4.2); concurrency 4; a huge body that isn't ASCII
(Bun keeps it two-byte, so hashing it may copy); a huge Messages body
(its own path, not changed here).
2026-10-28 23:26:45 +08:00

114 lines
8.5 KiB
JavaScript

// sentBy runs a few realistic chats through a WorkBuddy plugin module's
// loader and gives back every request it sent WorkBuddy, as the bytes on
// the wire read back (see unz), their encoding, and the ids derived from
// the chat. Every fetch is a fake. sent.test.mjs holds the result to what
// workbuddy 0.1.43 sent for the same chats (plugins#461); this runs any
// version's index.mjs, which is how those hashes were made.
import { createHash } from "node:crypto"
import { unz } from "./unz.mjs"
const CONFIG = {
code: 0,
data: {
agents: [{ name: "cli", models: ["deepseek-v4.1-flash", "hy3", "gemini-sent-461", "glm-5.2"] }],
models: [
{ id: "deepseek-v4.1-flash", credits: "x0.00", supportsReasoning: true, onlyReasoning: true,
reasoning: { canDisableThinking: true, defaultEffort: "high", supportedEfforts: ["low", "high", "max"] } },
{ id: "hy3", credits: "x0.00" },
{ id: "gemini-sent-461", credits: "x0.00" },
{ id: "glm-5.2", credits: "x0.79", supportsReasoning: true, reasoning: { defaultEffort: "xhigh", supportedEfforts: ["high", "xhigh"] } },
],
},
}
const AFTER_TOOLS = JSON.stringify({ error: { message: "the conversation must end with a user message", code: 11153 } })
const REFUSAL = JSON.stringify({ error: { message: "unapproved channel", code: 14018 } })
// what an agent sends: OpenCode's tool names and schemas, a tool turn, an
// earlier turn's reasoning, an image, a long system prompt
const SYSTEM = "You are opencode, an interactive CLI tool.\n".repeat(40)
const TOOLS = [
{ type: "function", function: { name: "read", description: "Read a file", parameters: { type: "object", properties: { filePath: { type: "string" }, offset: { type: ["number", "null"] } }, required: ["filePath"] } } },
{ type: "function", function: { name: "github.create_issue", description: "MCP", parameters: { type: "object", properties: { title: { type: "string" }, labels: { type: "array", items: { type: "string" } } } } } },
{ type: "function", function: { name: "bash", parameters: { type: "object", properties: { command: { type: "string" } }, required: ["command"], additionalProperties: false } } },
]
const call = { role: "assistant", content: "", reasoning_content: "I should list them.", tool_calls: [{ id: "call_1", type: "function", function: { name: "bash", arguments: '{"command":"ls"}' } }] }
const result = { role: "tool", tool_call_id: "call_1", content: "a.txt\nb.txt\n中文.md 🙂" }
const image = { type: "image_url", image_url: { url: "data:image/png;base64," + Buffer.from("not really a png").toString("base64") } }
export const CHATS = [
// as an agent spaced it, nothing to change: goes byte for byte
["plain", "https://www.workbuddy.ai/v2/chat/completions", `{"model": "hy3", "stream": true, "messages": [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "hi"}], "reasoning_effort": "low"}`],
["opencode tools", "https://www.workbuddy.ai/v2/chat/completions", JSON.stringify({ model: "deepseek-v4.1-flash", stream: true, stream_options: { include_usage: true }, max_tokens: 32000, messages: [{ role: "system", content: SYSTEM }, { role: "user", content: "List the files." }, call, result, { role: "user", content: [{ type: "text", text: "and this" }, image] }], tools: TOOLS, tool_choice: "auto" })],
["default effort", "https://www.workbuddy.ai/v2/chat/completions", JSON.stringify({ model: "deepseek-v4.1-flash", stream: true, messages: [{ role: "user", content: "hi 🙂" }], tools: TOOLS, tool_choice: { type: "function", function: { name: "github.create_issue" } } })],
["developer, no system", "https://www.workbuddy.ai/v2/chat/completions", JSON.stringify({ model: "glm-5.2", messages: [{ role: "developer", content: "d" }, { role: "user", content: "x" }], max_completion_tokens: 9, reasoning: { effort: "high" } })],
// gemini answers 11153 to tools then the user: the reply goes between
// them, and the next chat has it up front
["after tools, refused", "https://www.workbuddy.ai/v2/chat/completions", JSON.stringify({ model: "gemini-sent-461", stream: true, messages: [{ role: "system", content: "s" }, { role: "user", content: "List the files." }, call, result, { role: "user", content: "now" }], tools: TOOLS })],
["after tools, known", "https://www.workbuddy.ai/v2/chat/completions", JSON.stringify({ model: "gemini-sent-461", stream: true, messages: [{ role: "system", content: "s" }, { role: "user", content: "List the files." }, call, result, { role: "user", content: [{ type: "text", text: "<system-reminder>r</system-reminder>" }] }, { role: "user", content: "now" }], tools: TOOLS })],
// a system prompt refused once goes as the user's words, at once next time
["system refused", "https://www.workbuddy.ai/v2/chat/completions", JSON.stringify({ model: "hy3", messages: [{ role: "system", content: "REFUSE-461 " + SYSTEM }, { role: "user", content: "hi" }] })],
["system known refused", "https://www.workbuddy.ai/v2/chat/completions", JSON.stringify({ model: "hy3", messages: [{ role: "system", content: "REFUSE-461 " + SYSTEM }, { role: "user", content: "hi again" }], tools: TOOLS })],
["both", "https://www.workbuddy.ai/v2/chat/completions", JSON.stringify({ model: "gemini-sent-461", messages: [{ role: "system", content: "REFUSE-461 " + SYSTEM }, { role: "user", content: "go" }, call, result, { role: "system", content: "late" }, { role: "user", content: "now" }] })],
// a Claude model on Messages goes as it came but for unsigned thinking
["messages", "https://www.workbuddy.ai/v1/messages", JSON.stringify({ model: "claude-opus-5.5", max_tokens: 64, system: [{ type: "text", text: "s" }], messages: [{ role: "user", content: "q" }, { role: "assistant", content: [{ type: "thinking", thinking: "t" }, { type: "text", text: "a" }] }, { role: "user", content: "q2" }] })],
["bytes", "https://www.workbuddy.ai/v2/chat/completions", new TextEncoder().encode(JSON.stringify({ model: "hy3", messages: [{ role: "user", content: "bytes ü" }], tools: TOOLS }))],
["not json", "https://www.workbuddy.ai/v2/chat/completions", "{not json"],
]
const sha = (s) => createHash("sha256").update(s ?? "").digest("hex")
// sentBy(mod, freeOnly) is what mod's WorkBuddy AI plugin sent for CHATS,
// with the "Free models only" switch on or off
export async function sentBy(mod, freeOnly = false) {
const real = globalThis.fetch
const sent = []
globalThis.fetch = async (url, init) => {
const u = String(url)
if (u.endsWith("/v3/config")) return Response.json(CONFIG)
const h = new Headers(init?.headers)
const text = unz(init?.body)
const s = typeof text === "string" ? text : new TextDecoder().decode(text)
sent.push({ url: u, encoding: h.get("content-encoding"), body: sha(s), conversation: h.get("x-conversation-id"), turn: h.get("x-conversation-request-id") })
if (s.includes("REFUSE-461") && s.includes('"role":"system","content":"REFUSE-461')) return new Response(REFUSAL, { status: 400, headers: { "content-type": "application/json" } })
if (s.includes('"gemini-sent-461"')) {
const m = JSON.parse(s).messages
let i = m.length - 1
while (i >= 0 && m[i].role === "user") i--
if (i < m.length - 1 && m[i]?.role === "tool") return new Response(AFTER_TOOLS, { status: 400, headers: { "content-type": "application/json" } })
}
return new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } })
}
try {
const hooks = await mod.WorkBuddyAIAuthPlugin({ client: { auth: { set: async () => {} } }, magpie: { option: (_p, k) => freeOnly && k === "free_only" } })
const auth = { type: "oauth", access: "test-only", refresh: "test-only", uid: "u", expires: Date.now() + 3600000 }
const loader = await hooks.auth.loader(async () => auth)
const out = []
for (const [label, url, body] of CHATS) {
const from = sent.length
const res = await loader.fetch(url, { method: "POST", body, headers: { "content-type": "application/json" } })
await res.text()
out.push({ label, status: res.status, sent: sent.slice(from) })
}
return canonical(out)
} finally {
globalThis.fetch = real
}
}
// canonical names each derived id by where it first showed up, as the ids
// are salted afresh in each process: what stays is which requests share one
function canonical(out) {
const seen = new Map()
const name = (id) => {
if (id == null) return null
if (!seen.has(id)) seen.set(id, `id${seen.size}`)
return seen.get(id)
}
for (const o of out) for (const s of o.sent) {
s.conversation = name(s.conversation)
s.turn = name(s.turn)
}
return out
}