zed 0.1.7: a streamed xAI (chat) reply Zed breaks off after it said something ends cut short, with a note, instead of failing the turn (#91)

This is the sibling of zen-free 0.1.4 (6a5dd01). magpie's gateway goes on
with an Anthropic or Responses reply that was cut short, but not with a
Chat Completions one. For those, the error frame after a 200 threw away
the reply the client had already been shown.

Now, when a chat stream loses Zed's stream_ended, the plugin looks at what
the choices already said:
- If no choice is still open, only [DONE] is added.
- If a choice said text or reasoning and has no tool call half written,
  each open choice gets the note and a `stop`, then [DONE].
- If nothing was said, or a tool call is still unfinished, it fails as
  before.
Anthropic, Responses and non-streamed replies are unchanged.

Run: HOME=$(mktemp -d) bun test packages/zed gave 31 pass. The whole
repo's bun test gave 1129 pass, 0 fail. bun scripts/check.mjs passed. On
the old index.mjs, the 2 new tests that cover the cut-short endings fail.
With the tool-call guard removed by hand, the tool-call test fails.

Not tried: a real Zed account (there is none to test with). The
upstream's cut can't be triggered.
This commit is contained in:
yetone
2026-10-12 20:31:33 +08:00
parent ff2d815249
commit e105f567db
4 changed files with 141 additions and 6 deletions
+5 -1
View File
@@ -55,7 +55,11 @@ GitHub login.
- A caller that didn't ask for a stream gets one whole reply.
- A failure Zed reports mid-stream keeps its status (429, 402, 529 …).
So does a reply without Zed's `stream_ended`, which comes back as an
error rather than a shorter answer.
error rather than a shorter answer, except one case. A streamed xAI
(chat) reply that has already said something, and has no tool call
half written, ends cut short instead, with a note saying so, a `stop`
and `[DONE]` (#91). magpie's gateway can go on with an Anthropic or
Responses reply cut short, but not with a chat one.
- A 402 means the plan doesn't include Zed's hosted models, or its
allowance is used up.
+74
View File
@@ -0,0 +1,74 @@
// A streamed Chat Completions reply (xAI's, through Zed) that Zed breaks
// off before stream_ended (#91): one that said something ends cut short,
// with a note, instead of failing the turn. One that said nothing, one
// with a tool call begun, and Anthropic's and Responses' (which magpie's
// gateway goes on with itself) still fail.
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" }
const NOTE = "(The reply was cut short: Zed closed the stream before it finished. Ask again to go on.)"
async function ask(wire, lines, stream = true) {
globalThis.fetch = async (url) => {
const path = new URL(String(url)).pathname
if (path === "/client/llm_tokens") return Response.json({ token: "llm-token" })
if (path === "/completions")
return new Response(lines.map((l) => JSON.stringify(l)).join("\n") + "\n", { headers: { "x-zed-server-supports-status-messages": "true" } })
return new Response("", { status: 404 })
}
const url = wire === "chat" ? "https://cloud.zed.dev/v1/chat/completions" : "https://cloud.zed.dev/v1/messages"
const res = await _internal.complete(s, url, {
method: "POST",
body: JSON.stringify({ model: wire === "chat" ? "grok-4.7" : "claude-sonnet-5", stream, messages: [{ role: "user", content: "hi" }], max_tokens: 100 }),
})
return { status: res.status, text: await res.text() }
}
const frames = (text) =>
text.split("\n\n").filter((f) => f.startsWith("data: ")).map((f) => (f === "data: [DONE]" ? "[DONE]" : JSON.parse(f.slice(6))))
const chunk = (delta, finish_reason = null, index = 0) => ({ event: { id: "c1", object: "chat.completion.chunk", created: 1, model: "grok-4.7", choices: [{ index, delta, finish_reason }] } })
test("a chat reply cut short after its text ends with the note, a stop and [DONE]", async () => {
const r = await ask("chat", [{ status: "started" }, chunk({ role: "assistant", reasoning_content: "hm" }), chunk({ content: "Half an ans" })])
expect(r.status).toBe(200)
const f = frames(r.text)
expect(f.some((x) => x.error)).toBe(false)
expect(f.at(-1)).toBe("[DONE]")
expect(f.at(-2)).toEqual({ id: "c1", object: "chat.completion.chunk", created: 1, model: "grok-4.7", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] })
expect(f.map((x) => x.choices?.[0]?.delta?.content ?? "").join("")).toBe("Half an ans\n\n" + NOTE)
})
test("a chat reply that finished but lost its stream_ended only gets [DONE]", async () => {
const f = frames((await ask("chat", [chunk({ content: "Done." }), chunk({}, "stop")])).text)
expect(f.at(-1)).toBe("[DONE]")
expect(f.map((x) => x.choices?.[0]?.delta?.content ?? "").join("")).toBe("Done.")
})
test("a chat reply cut short inside a tool call, or before saying anything, still fails", async () => {
const tool = await ask("chat", [chunk({ content: "Let me look." }), chunk({ tool_calls: [{ index: 0, id: "t1", type: "function", function: { name: "read", arguments: '{"pa' } }] })])
const f = frames(tool.text)
expect(f.at(-1).error.message).toBe("the reply ended before it was complete")
expect(f).not.toContain("[DONE]")
const none = await ask("chat", [{ status: "started" }, chunk({ role: "assistant", content: "" })])
expect(none.status).toBe(502)
})
test("an Anthropic reply cut short still fails, for magpie's gateway to go on with it", async () => {
const start = { event: { type: "message_start", message: { id: "m", type: "message", role: "assistant", content: [], model: "claude-sonnet-5", usage: { input_tokens: 1, output_tokens: 0 } } } }
const text = [{ event: { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } } }, { event: { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Hi" } } }]
const r = await ask("anthropic", [start, ...text])
expect(r.text).toContain("event: error")
expect(r.text).not.toContain("cut short")
})
test("a chat reply that isn't streamed and is cut short is a 502", async () => {
const r = await ask("chat", [chunk({ content: "Half" })], false)
expect(r.status).toBe(502)
})
+61 -4
View File
@@ -642,6 +642,52 @@ function eventError(wire, ev) {
return undefined
}
// CUT_SHORT_NOTE ends a streamed Chat Completions reply (xAI's) that Zed
// broke off after it said something, as zen-free does (#91): magpie's
// gateway can go on with an Anthropic or Responses reply cut short, not
// with a Chat one, and failing it would throw away what the client was
// already shown.
const CUT_SHORT_NOTE = "(The reply was cut short: Zed closed the stream before it finished. Ask again to go on.)"
// chatSaid follows a streamed chat reply's choices: which wrote text,
// which have finished, and whether a tool call was begun (its arguments
// may be half written, so a reply cut short after one stays an error).
function chatSaid() {
const wrote = new Set()
const open = new Set()
const tools = new Set()
const done = new Set()
let meta
return {
see(ev) {
if (!Array.isArray(ev?.choices)) return
meta ??= { id: ev.id, created: ev.created, model: ev.model }
for (const c of ev.choices) {
const i = c?.index ?? 0
const d = c?.delta ?? {}
if (d.content) wrote.add(i)
if (d.content || d.reasoning_content || d.reasoning) open.add(i)
if (d.tool_calls?.length) tools.add(i)
if (c?.finish_reason) done.add(i)
}
},
// the frames that end the reply cut short, or undefined when it must
// fail: nothing said, or a tool call begun and not finished
end() {
if (!open.size && !tools.size && !done.size) return undefined
if ([...tools].some((i) => !done.has(i))) return undefined
const left = [...open].filter((i) => !done.has(i)).sort((a, b) => a - b)
if (!left.length) return ["data: [DONE]\n\n"]
const chunk = (choices) => sse("chat", { id: meta?.id ?? "chatcmpl-cut-short", object: "chat.completion.chunk", created: meta?.created ?? Math.floor(Date.now() / 1000), model: meta?.model, choices })
return [
chunk(left.map((index) => ({ index, delta: { content: (wrote.has(index) ? "\n\n" : "") + CUT_SHORT_NOTE }, finish_reason: null }))),
chunk(left.map((index) => ({ index, delta: {}, finish_reason: "stop" }))),
"data: [DONE]\n\n",
]
},
}
}
// streamed turns Zed's lines into the provider's own server-sent events.
// What comes before the reply says anything is held, as magpie's built-in
// holds it (relayStatus): a failure there — a failed status, the
@@ -692,7 +738,12 @@ async function streamed(wire, res) {
else if (wire === "responses") put(`event: error\ndata: ${JSON.stringify(errorBody(wire, status, message))}\n\n`)
else put(`data: ${JSON.stringify(errorBody(wire, status, message))}\n\n`)
}
for (const ev of head) put(sse(wire, ev))
const chat = wire === "chat" ? chatSaid() : null
for (const ev of head) {
chat?.see(ev)
put(sse(wire, ev))
}
chat?.see(first.event)
put(sse(wire, first.event))
try {
for (;;) {
@@ -704,10 +755,16 @@ async function streamed(wire, res) {
fail(failedStatus(l.failed.code), l.failed.message || l.failed.code)
ctl.close()
return
} else put(sse(wire, l.event))
} else {
chat?.see(l.event)
put(sse(wire, l.event))
}
}
// Zed ends every whole reply with stream_ended
if (wrapped && !ended) fail(502, "the reply ended before it was complete")
// Zed ends every whole reply with stream_ended; a chat reply cut
// short after it said something ends with a note instead
const cut = wrapped && !ended ? chat?.end() : undefined
if (cut) for (const f of cut) put(f)
else if (wrapped && !ended) fail(502, "the reply ended before it was complete")
else if (wire === "chat") put("data: [DONE]\n\n")
ctl.close()
} catch (e) {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-zed-auth",
"version": "0.1.6",
"version": "0.1.7",
"description": "Sign in to a Zed subscription (Zed Pro, trial, student, business) from OpenCode or magpie",
"type": "module",
"main": "./index.mjs",