Files
plugins/packages/zed/system-role.test.mjs
T
yetone 3d355d349d zed 0.1.11: a {role: "system"} message inside an Anthropic request reaches Zed as user text where it was said, not as a role Zed refuses
Roy on Discord, Claude Code through magpie on a Zed subscription:
"API Error: 400 Zed: failed to parse Anthropic request: unknown variant
system, expected user or assistant".

Cause: Claude Code (2.1.288 on) writes {role: "system"} messages inside
messages[]: an empty one carrying a turn's effort as output_config, and
(2.1.296) one after tool results with its hooks' notices, <total_tokens>
and what the user typed while a tool ran. Anthropic's API takes them in
place. magpie's gateway passes them on as written (anthropic_shapes.go
mends only after a refusal matching `messages.N.role`, which Zed's serde
message doesn't), and the plugin's providerRequest "anthropic" case
forwarded them to Zed, whose Anthropic Role is user | assistant only.

Fix: providerRequest's anthropic case runs withoutSystemTurns. Each
system message's text goes, as text blocks (cache_control kept), into a
user turn at the same place: appended to the user message before it;
else after the leading tool_result blocks of the user message after it
(tool results must stay first); else a user message of its own. One with
no text (an effort alone) is left out; the request's top-level
output_config still carries the effort.

Why in place and not folded into the top-level system: the prompt cache's
prefix is tools, then system, then messages. Text appended to system on
each turn that has a notice changes the prefix ahead of every message, so
the whole conversation misses the cache from then on, while merging in
place changes only bytes at the conversation's tail, which the next
request repeats unchanged (the transform is deterministic per message).
It also keeps the meaning Anthropic's API gives the message: said at that
point in the turn, not standing instructions for the whole conversation.
magpie's own withSystemOnTop folds to the top for Command Code, which
refuses the role by name; that path never fires for Zed's wording.

Siblings, not changed: responses (OpenAI Responses) and chat (xAI Chat
Completions) both have system/developer roles in their own message
schemas, so a system message there is not this error; gemini has no
system role in contents (the AI SDK sends systemInstruction). None was
tried against Zed's cloud with a mid-conversation system message, and
there is no report of one.

Tests (system-role.test.mjs, built from Claude Code's shapes and
checking the provider_request the plugin hands Zed's /completions):
a hook notice after tool results joins their user turn after the
results and system stays as sent; an empty effort-only system message
is left out; system text before a tool-result user turn goes after the
results, and one after an assistant turn becomes a user turn. With
index.mjs reverted to 43ffb46 all 3 fail; with the fix all pass.

Run at 43ffb46 + this change: `HOME=$(mktemp -d) bun test` in
packages/zed: 47 pass, 0 fail. `bun scripts/check.mjs`: ok (exit 0).
Not tried: a real Zed account (none in a sandbox HOME here); the shape
Zed accepts is Anthropic's user/assistant messages, as the plugin
already sends for every request without system messages.
2026-10-22 10:00:12 +08:00

112 lines
4.9 KiB
JavaScript

// Claude Code puts {role: "system"} messages inside an Anthropic request's
// messages (a turn's effort, its hooks' notices after tool results). Zed's
// cloud takes only user and assistant there: 400 "failed to parse Anthropic
// request: unknown variant `system`, expected `user` or `assistant`" (Roy on
// Discord). The plugin sends their text in a user turn, where it was said.
import { afterEach, expect, test } from "bun:test"
import { _internal } from "./index.mjs"
const real = globalThis.fetch
afterEach(() => {
globalThis.fetch = real
_internal.tokens.clear()
})
const s = { userId: "4242", access: "plain-access", systemId: "", org: "org-me", plan: "zed_pro", who: "octo" }
// sent is the provider_request the plugin hands Zed for an Anthropic body.
async function sent(body) {
let got
globalThis.fetch = async (url, init) => {
const path = new URL(String(url)).pathname
if (path === "/client/llm_tokens") return Response.json({ token: "llm-token" })
if (path === "/completions") {
got = JSON.parse(init.body)
const ev = (e) => JSON.stringify({ event: e })
return new Response(
[
ev({ type: "message_start", message: { id: "m1", type: "message", role: "assistant", model: "claude-sonnet-5", content: [], usage: { input_tokens: 1, output_tokens: 0 } } }),
ev({ type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } }),
ev({ type: "message_stop" }),
JSON.stringify({ status: "stream_ended" }),
].join("\n") + "\n",
{ headers: { "x-zed-server-supports-status-messages": "true" } },
)
}
return new Response("", { status: 404 })
}
const res = await _internal.complete(s, "https://cloud.zed.dev/v1/messages", { method: "POST", body: JSON.stringify(body) })
await res.text()
return got.provider_request
}
const roles = (r) => r.messages.map((m) => m.role)
const SYSTEM = [{ type: "text", text: "You are Claude Code.", cache_control: { type: "ephemeral" } }]
const NOTICE = "PostToolUse:Read hook additional context: the file is generated"
test("a hook notice after tool results joins their user turn, after the results", async () => {
const r = await sent({
model: "claude-sonnet-5",
stream: true,
max_tokens: 100,
system: SYSTEM,
messages: [
{ role: "user", content: "read a.go" },
{ role: "assistant", content: [{ type: "tool_use", id: "t1", name: "Read", input: { file_path: "a.go" } }] },
{ role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "package a" }] },
{ role: "system", content: NOTICE },
],
})
expect(roles(r)).toEqual(["user", "assistant", "user"])
expect(r.messages[2].content).toEqual([
{ type: "tool_result", tool_use_id: "t1", content: "package a", is_error: false },
{ type: "text", text: NOTICE },
])
// the top-level system, the cache's prefix, is as the agent sent it
expect(r.system).toEqual(SYSTEM)
})
test("an empty system message that only carries a turn's effort is left out", async () => {
const r = await sent({
model: "claude-sonnet-5",
stream: true,
max_tokens: 100,
output_config: { effort: "high" },
messages: [
{ role: "user", content: "hi" },
{ role: "system", content: [], output_config: { effort: "low" } },
{ role: "assistant", content: "hello" },
{ role: "user", content: "again" },
],
})
expect(r.messages).toEqual([
{ role: "user", content: "hi" },
{ role: "assistant", content: "hello" },
{ role: "user", content: "again" },
])
expect(r.output_config).toEqual({ effort: "high" })
})
test("system text before a user turn goes after its tool results, and one after an assistant turn is a user turn", async () => {
const r = await sent({
model: "claude-sonnet-5",
stream: true,
max_tokens: 100,
messages: [
{ role: "user", content: "go" },
{ role: "assistant", content: [{ type: "tool_use", id: "t1", name: "Bash", input: { command: "ls" } }] },
{ role: "system", content: [{ type: "text", text: "The user sent a new message while you were working:\nstop", cache_control: { type: "ephemeral" } }] },
{ role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "a.go", is_error: false }, { type: "text", text: "<total_tokens>9</total_tokens>" }] },
{ role: "assistant", content: "Stopping." },
{ role: "system", content: NOTICE },
],
})
expect(roles(r)).toEqual(["user", "assistant", "user", "assistant", "user"])
expect(r.messages[2].content).toEqual([
{ type: "tool_result", tool_use_id: "t1", content: "a.go", is_error: false },
{ type: "text", text: "The user sent a new message while you were working:\nstop", cache_control: { type: "ephemeral" } },
{ type: "text", text: "<total_tokens>9</total_tokens>" },
])
expect(r.messages[4]).toEqual({ role: "user", content: [{ type: "text", text: NOTICE }] })
})