Files
plugins/packages/qoder/native-tools.test.mjs
T
yetone 5403c21484 qoder 0.2.51: a native tool call that never gets its name no longer fails the turn (#579)
bigstage915 (Qoder CN, qoder-cn/qfmodel through ZCode) saw qfmodel now and
then begin a native tool call and never send its function name. events()
then ended the stream with "the model's native tool call has no name", an
SSE error frame on a 200, which ZCode reads as not retryable: the whole
turn died, with the reasoning and text already shown (9 incidents in four
days, after reasoning-end and after a named call's tool-input-start and
argument deltas).

An unnamed call is still never given, and its held arguments go nowhere,
not into the text. Now:
- Nothing of the answer said before it (no text, reasoning or call): the
  reply is the same 502 as before, marked nameless, and ask sends the
  request once more under a new request_id. A second such reply goes back
  as the 502, before any byte, which magpie's gateway retries or fails
  over (retryable: status >= 500).
- The answer had begun: the call is dropped and the answer ends as it
  would have without it, tool_calls beside a named call, stop (or length)
  otherwise, and console.warn says so (the host's stderr, in magpie's
  log). The non-streaming reply is the same: named calls kept, the
  unnamed one left out.

Tests (native-tools.test.mjs): the after-reasoning test now expects the
reasoning kept, no tool frame, finish stop and the warning; new cases for
an unnamed call after a named call's start and argument deltas (stream),
beside a named one (non-streaming, unnamed first and after), after text,
and nothing-said (asked twice, then 502; asked twice, second answer
given). The two 502 tests now also count two chat requests.

Run, on the WSL2 box (magpie-desktop, Bun 1.4.2; mote at load ~120):
- native-tools.test.mjs: 15 pass.
- The new test file against origin/main's index.mjs: the 7 new or
  changed tests fail, the 8 others pass.
- Broken by hand: the in-plugin retry off, 3 fail (the retry tests);
  reasoning not counted as said, 1 fails (after-reasoning).
- Full `HOME=$(mktemp -d) bun test` at this tree: 4469 pass, 1 fail,
  agent-office's "midnight and metadata-only changes do not read JSONL
  again", red alone on untouched origin/main 26864ec too, in UTC and
  Asia/Shanghai: filed as #580. `bun scripts/check.mjs`: ok.

Siblings: no other package has this guard (grep of the error text and an
unnamed-call check over packages/). magpie's own chatTidy already drops a
call whose first fragment has no name and ends stop (#1475), the same
choice.

Not tried: a real Qoder CN account; the failure is the model's and not
reproducible on demand.
2026-11-01 07:06:57 +08:00

291 lines
13 KiB
JavaScript

import { afterEach, expect, test } from "bun:test"
import { _internal, QoderAuthPlugin } from "./index.mjs"
const realFetch = globalThis.fetch
afterEach(() => (globalThis.fetch = realFetch))
const line = (body) =>
`data:${JSON.stringify({ body: typeof body === "string" ? body : JSON.stringify(body), statusCodeValue: 200 })}\n\n`
const chunk = (delta, finish_reason) => line({ choices: [{ index: 0, delta, finish_reason }] })
const finish = chunk({}, "tool_calls") + line("[DONE]")
const textCall = '<tool_call>{"name":"Bash","arguments":{"command":"pwd"}}</tool_call>'
async function collect(reply) {
const out = []
for await (const event of _internal.events(new Response(reply).body)) out.push(event)
return out
}
function callsFrom(events) {
const calls = []
for (const event of events) {
if (event.tool) calls[event.tool.index] = { ...event.tool }
if (event.args) calls[event.args.index].args += event.args.text
}
return calls
}
// chats counts the chat requests ask's fetch was sent; a list of replies
// answers them in turn, its last one every request after
let chats = 0
async function ask(reply, stream) {
const auth = {
type: "oauth", access: "fixture-job-token", refresh: "fixture-refresh-token",
expires: Date.now() + 3_600_000, accountId: "native-tools@example.test",
uid: "native-tools", machineId: "fixture-machine",
}
const replies = [reply].flat()
chats = 0
globalThis.fetch = async (url) =>
new URL(String(url)).pathname.endsWith("/model/list")
? Response.json({ chat: [{ key: "efficient", display_name: "Efficient", enable: true }] })
: new Response(replies[Math.min(chats++, replies.length - 1)], { headers: { "Content-Type": "text/event-stream" } })
const hooks = await QoderAuthPlugin({ client: { auth: { set: async () => {} } } })
const loader = await hooks.auth.loader(async () => auth)
return loader.fetch("https://api3.qoder.sh/v1/chat/completions", {
method: "POST",
body: JSON.stringify({ model: "efficient", messages: [{ role: "user", content: "hi" }], stream }),
})
}
async function framesFrom(response) {
return (await response.text()).split("\n")
.filter((s) => s.startsWith("data: ") && s !== "data: [DONE]")
.map((s) => JSON.parse(s.slice(6)))
}
test("an empty native placeholder before a text call does not create an unnamed tool", async () => {
const events = await collect(
chunk({ tool_calls: [{ index: 0, function: { name: "", arguments: "" } }] })
+ chunk({ content: textCall }) + finish,
)
const calls = callsFrom(events)
expect(calls).toHaveLength(1)
expect(calls[0]).toMatchObject({ index: 0, name: "Bash", args: '{"command":"pwd"}' })
expect(events.at(-1)?.stop).toBe("tool_calls")
})
test("empty and null native placeholders leave an ordinary text answer alone", async () => {
for (const placeholder of [
{ index: 0 },
{ index: 0, function: { name: null, arguments: null } },
{ index: 0, function: { name: " ", arguments: "" } },
]) {
const events = await collect(
chunk({ tool_calls: [placeholder] }) + chunk({ content: "Hello" }, "stop") + line("[DONE]"),
)
expect(callsFrom(events)).toEqual([])
expect(events.filter((e) => e.error)).toEqual([])
expect(events.map((e) => e.text ?? "").join("")).toBe("Hello")
expect(events.at(-1)?.stop).toBe("stop")
}
})
test("an id and argument prefix wait for the native tool name", async () => {
const events = await collect(
chunk({ tool_calls: [{ index: 0, id: "call_delayed", type: "function" }] })
+ chunk({ tool_calls: [{ index: 0, function: { arguments: '{"command":' } }] })
+ chunk({ tool_calls: [{ index: 0, function: { name: "Bash", arguments: '"pwd"}' } }] })
+ finish,
)
expect(callsFrom(events)).toEqual([
{ index: 0, id: "call_delayed", name: "Bash", args: '{"command":"pwd"}' },
])
expect(events.filter((e) => e.error)).toEqual([])
})
test("a native call that never supplies its name is an error, not an empty-name tool", async () => {
for (const tool of [
{ index: 0, id: "call_missing" },
{ index: 0, function: { arguments: "{}" } },
{ index: 0, id: "call_blank", function: { name: " ", arguments: "{}" } },
]) {
const events = await collect(chunk({ tool_calls: [tool] }) + finish)
expect(callsFrom(events)).toEqual([])
expect(events.filter((e) => e.stop)).toEqual([])
expect(events.at(-1)?.error).toMatchObject({ status: 502 })
expect(events.at(-1).error.message).toMatch(/tool call.*name/)
}
})
const interleaved =
chunk({ tool_calls: [
{ index: 0, id: "call_first", function: { name: "Read", arguments: '{"path":' } },
{ index: 1, id: "call_second", function: { name: "Bash", arguments: '{"command":' } },
] })
+ chunk({ tool_calls: [{ index: 0, function: { arguments: '"a.go"}' } }] })
+ chunk({ tool_calls: [{ index: 1, function: { arguments: '"pwd"}' } }] })
+ finish
test("interleaved native argument deltas keep their original call indexes", async () => {
expect(callsFrom(await collect(interleaved))).toEqual([
{ index: 0, id: "call_first", name: "Read", args: '{"path":"a.go"}' },
{ index: 1, id: "call_second", name: "Bash", args: '{"command":"pwd"}' },
])
})
test("a delayed native name can follow a text call without stealing its arguments", async () => {
const events = await collect(
chunk({ tool_calls: [{ index: 0, id: "call_later", function: { arguments: '{"path":' } }] })
+ chunk({ content: textCall })
+ chunk({ tool_calls: [{ index: 0, function: { name: "Read", arguments: '"a.go"}' } }] })
+ finish,
)
expect(callsFrom(events)).toMatchObject([
{ index: 0, name: "Bash", args: '{"command":"pwd"}' },
{ index: 1, id: "call_later", name: "Read", args: '{"path":"a.go"}' },
])
})
const unnamedOnly = chunk({ tool_calls: [{ index: 0, id: "call_missing" }] }) + finish
test("the non-streaming adapter rejects an unnamed native call with 502 after asking once more", async () => {
const response = await ask(unnamedOnly, false)
expect(response.status).toBe(502)
const body = await response.json()
expect(body.error.message).toMatch(/tool call.*name/)
expect(body.choices).toBeUndefined()
// nothing of either reply was given: the plugin asked twice, then the
// gateway has a 502 before any byte to retry or fail over (plugins#579)
expect(chats).toBe(2)
})
test("the streaming adapter rejects an unnamed call before emitting any answer, after asking once more", async () => {
const response = await ask(unnamedOnly, true)
expect(response.status).toBe(502)
expect(chats).toBe(2)
})
test("an unnamed call with nothing said before it is asked once more, and the second answer is given", async () => {
for (const stream of [true, false]) {
const response = await ask([unnamedOnly, chunk({ content: "Hello" }, "stop") + line("[DONE]")], stream)
expect(response.status).toBe(200)
expect(chats).toBe(2)
if (stream) {
const frames = await framesFrom(response)
expect(frames.map((f) => f.choices?.[0]?.delta?.content ?? "").join("")).toBe("Hello")
expect(frames.at(-1).choices[0].finish_reason).toBe("stop")
expect(frames.filter((f) => f.error)).toEqual([])
} else {
const choice = (await response.json()).choices[0]
expect(choice.message.content).toBe("Hello")
expect(choice.finish_reason).toBe("stop")
}
}
})
test("an unnamed call after reasoning is dropped and the stream finishes stop, the reasoning kept", async () => {
const warn = console.warn
const warned = []
console.warn = (...xs) => warned.push(xs.join(" "))
try {
const response = await ask(
chunk({ reasoning_content: "Thinking" })
+ chunk({ tool_calls: [{ index: 0, id: "call_missing", function: { arguments: '{"command":"rm' } }] })
+ chunk({ tool_calls: [{ index: 0, function: { arguments: ' -rf x"}' } }] }) + finish,
true,
)
expect(response.status).toBe(200)
expect(chats).toBe(1)
const text = await response.text()
expect(text).not.toContain("-rf")
expect(text).not.toContain('"command')
const frames = text.split("\n").filter((s) => s.startsWith("data: ") && s !== "data: [DONE]").map((s) => JSON.parse(s.slice(6)))
expect(frames.map((f) => f.choices?.[0]?.delta?.reasoning_content ?? "").join("")).toBe("Thinking")
expect(frames.flatMap((f) => f.choices?.[0]?.delta?.tool_calls ?? [])).toEqual([])
expect(frames.filter((f) => f.error)).toEqual([])
expect(frames.at(-1).choices[0].finish_reason).toBe("stop")
expect(text.trimEnd().endsWith("data: [DONE]")).toBe(true)
expect(warned.join("\n")).toMatch(/dropped 1 native tool call the model never named/)
} finally {
console.warn = warn
}
})
// a named call is under way (tool-input-start, then its arguments), and a
// second one never gets its name: its arguments go nowhere
const namedThenUnnamed =
chunk({ tool_calls: [{ index: 0, id: "call_read", function: { name: "Read", arguments: '{"path":' } }] })
+ chunk({ tool_calls: [{ index: 0, function: { arguments: '"a.go"}' } }] })
+ chunk({ tool_calls: [{ index: 1, id: "call_nameless", function: { arguments: '{"secret":' } }] })
+ chunk({ tool_calls: [{ index: 1, function: { arguments: '"LEAKED"}' } }] })
+ finish
test("an unnamed call after a named call's start and arguments is dropped; the named one finishes tool_calls", async () => {
const response = await ask(namedThenUnnamed, true)
expect(response.status).toBe(200)
const text = await response.text()
expect(text).not.toContain("LEAKED")
expect(text).not.toContain("secret")
const frames = text.split("\n").filter((s) => s.startsWith("data: ") && s !== "data: [DONE]").map((s) => JSON.parse(s.slice(6)))
const calls = []
for (const tc of frames.flatMap((f) => f.choices?.[0]?.delta?.tool_calls ?? [])) {
if (tc.function?.name) calls[tc.index] = { id: tc.id, name: tc.function.name, args: tc.function.arguments }
else calls[tc.index].args += tc.function.arguments
}
expect(calls).toEqual([{ id: "call_read", name: "Read", args: '{"path":"a.go"}' }])
expect(frames.map((f) => f.choices?.[0]?.delta?.content ?? "").join("")).toBe("")
expect(frames.filter((f) => f.error)).toEqual([])
expect(frames.at(-1).choices[0].finish_reason).toBe("tool_calls")
expect(chats).toBe(1)
})
test("the non-streaming adapter drops an unnamed call beside a named one", async () => {
// the unnamed one first, upstream index 0, and the named one after it
const response = await ask(
chunk({ tool_calls: [{ index: 0, id: "call_nameless", function: { arguments: '{"secret":"LEAKED"}' } }] })
+ chunk({ tool_calls: [{ index: 1, id: "call_bash", function: { name: "Bash", arguments: '{"command":"pwd"}' } }] })
+ finish,
false,
)
expect(response.status).toBe(200)
const text = await response.text()
expect(text).not.toContain("LEAKED")
const choice = JSON.parse(text).choices[0]
expect(choice.finish_reason).toBe("tool_calls")
expect(choice.message.content).toBe("")
expect(choice.message.tool_calls).toEqual([
{ id: "call_bash", type: "function", function: { name: "Bash", arguments: '{"command":"pwd"}' } },
])
const streamed = await ask(namedThenUnnamed, false)
const named = (await streamed.json()).choices[0]
expect(named.finish_reason).toBe("tool_calls")
expect(named.message.tool_calls.map((c) => c.function.name)).toEqual(["Read"])
})
test("an unnamed call after text is dropped; the text ends stop", async () => {
const events = await collect(
chunk({ content: "Let me look." })
+ chunk({ tool_calls: [{ index: 0, id: "call_missing", function: { arguments: '{"x":1}' } }] }) + finish,
)
expect(events.filter((e) => e.error || e.tool || e.args)).toEqual([])
expect(events.map((e) => e.text ?? "").join("")).toBe("Let me look.")
expect(events.at(-1)?.stop).toBe("stop")
})
test("the non-streaming adapter assembles interleaved calls by output index", async () => {
const response = await ask(interleaved, false)
expect(response.status).toBe(200)
const choice = (await response.json()).choices[0]
expect(choice.finish_reason).toBe("tool_calls")
expect(choice.message.tool_calls).toEqual([
{ id: "call_first", type: "function", function: { name: "Read", arguments: '{"path":"a.go"}' } },
{ id: "call_second", type: "function", function: { name: "Bash", arguments: '{"command":"pwd"}' } },
])
})
test("the streaming adapter emits only the named text call after a native placeholder", async () => {
const response = await ask(
chunk({ tool_calls: [{ index: 0, function: { name: "", arguments: "" } }] })
+ chunk({ content: textCall }) + finish,
true,
)
expect(response.status).toBe(200)
const frames = await framesFrom(response)
const tools = frames.flatMap((f) => f.choices?.[0]?.delta?.tool_calls ?? [])
expect(tools).toHaveLength(1)
expect(tools[0]).toMatchObject({
index: 0, type: "function", function: { name: "Bash", arguments: '{"command":"pwd"}' },
})
})