Files
OmniRoute/tests/unit/zai-web-silent-empty-repro.test.ts
backryun bd472200d5 [v3.8.50] Fix Z.ai web browser transport and model capabilities (#8451)
* fix: complete Z.ai web browser transport

* refactor: address Z.ai review feedback

* test(zai-web): reconcile the #8014 endpoint guard with the chats/new + signed flow

Rebasing onto release/v3.8.49 pulled in #8503, which repointed CHAT_URL to
/api/v2/chat/completions and added an endpoint probe. This branch already
targets v2, so the executor conflict resolved to this branch's superset
(NEW_CHAT_URL + signature constants alongside the same v2 CHAT_URL). The two
tests needed adapting, because #8503's assertions assume the pre-rework flow:

- executor-zai-web.test.ts: the completion URL now carries the request
  signature as a query string, so an exact-equality check on the endpoint can
  never match. Assert the v2 prefix instead.
- zai-web-chat-endpoint-8014-probe.test.ts: the probe drove the executor with a
  bare cookie credential and no captcha proof, which now routes through the
  browser transport — fetch was never called and the probe captured nothing.
  Supplied a direct-path credential, and matched on pathname across all
  requests (the executor also probes the homepage for the frontend version and
  calls /api/v1/chats/new first).

The guard's intent is unchanged and slightly strengthened: it now asserts no
request reaches the stale unversioned path and that exactly one completions
request is issued, against v2.

54/54 across the zai suites; typecheck:core and eslint clean.

* fix(zai-web): surface upstream error frames instead of finishing empty

Reported on this PR: HTTP 200, `out=0`, stream "complete", no content and no
diagnosis.

Cause. HTTP-level failures are already handled — fetchUpstream turns any !ok
response into a makeErrorResult with the sanitized body. The gap is a 200 whose
SSE body carries an error payload: parseZaiFrame returns null for it,
drainSseDeltas drops it, and buildZaiStreamingBody then closes with an empty
assistant message + stop + [DONE]. The caller reads that as a successful empty
completion, so a rejected signature, an expired captcha and a stale token all
look identical — which is why this had to be diagnosed by reading code rather
than logs. Hard Rule #6.

Fix. parseZaiFrame now classifies an affirmatively error-shaped frame
(`error` at the top level or under `data`, string or {detail|message|msg}) as a
terminal delta, checked before the delta paths so it cannot fall through to the
"no usable delta" null. The stream emits it as `[Z.ai error] <message>`,
matching the mid-stream convention the other web executors already use
(zed-hosted's createErrorChunk) — the 200 is on the wire, so the status cannot
change, but the caller must not be left reading a blank success. Content
streamed before the failure is preserved. Message goes through
sanitizeErrorMessage (Rule #12).

Deliberately NOT changed: a contentless frame still parses to null. That is
live-validated behaviour, not an oversight — z.ai emits phase frames with no
delta_content, and executor-zai-web.test.ts pins it ("returns null for frames
with no usable delta"). Treating "nothing parseable arrived" as a failure would
invent policy on top of an observed protocol and risk false errors on the happy
path, so this only adds recognition of explicit error frames.

Tests (TDD, RED then GREEN): zai-web-silent-empty-repro.test.ts — 7 cases.
Error frame classified and terminal; surfaced through the stream with the
upstream's own text; surfaced after partial content without losing it; plus a
REGRESSION GUARD that contentless/phase-only frames are still skipped, and two
controls that the happy path and reasoning-only output are untouched. The guard
and controls passed before the fix; the four error cases did not.

94/94 across the zai + stream suites; typecheck:core, eslint and check:file-size
clean.

* refactor(sse): extract the zai-web transports so the complexity ratchet holds

The v3.8.49 merge-train rebaseline (#8686) set the ceiling to the tip's own
measurement, leaving zero headroom, so this branch's +5 cyclomatic / +3 cognitive
own-growth had nowhere to sit once rebased onto it.

Eight violations, all in code this branch introduces, resolved by extraction —
no behaviour change:

- `execute` (152 lines, complexity 25, cognitive 20) now delegates to
  `resolveZaiRequest()` for the four client-error rejections and to a
  `fetchViaSignedApi()` method for the CAPTCHA/signature path, so it reads as
  "validate, pick a transport, shape the response".
- `fetchThroughBrowser` (126 lines, cognitive 16) hands its image decoding to
  `resolveZaiBrowserAttachments()`, its Playwright options to
  `buildZaiBrowserChatOptions()`, and its call-log payload to
  `buildZaiBrowserAuditBody()`.
- `configureZaiBrowserEffort` (cognitive 35 — the worst of the set) repeated a
  wrap-and-relabel try/catch four times inside an if/else. `runStage`, which
  already existed one function below, is now module-scoped and reused, and the
  toggle collapses to `checked !== config.enabled` (same four cases).
- `validateWebCookieProvider` (complexity 19) moves its can-we-probe-this
  cascade into `resolveWebCookieProbe()`, which returns either a rejection or
  the URL + headers to use.
- `acquireBrowserContext`'s creation closure (complexity 17) hands cookie and
  localStorage seeding to `seedContextSession()`.

That last extraction also clears a violation that predates this branch —
`acquireBrowserContext` was already over the 80-line ceiling — so cyclomatic
lands at 2187 against a baseline of 2188.

Verified: check:complexity-ratchets green both metrics; typecheck:core clean;
ESLint clean on all four files; 85 tests across the zai-web, web-cookie
validation, browser-pool and model-test-runner suites pass.

* fix(zai-web): surface upstream errors on the non-streaming path

collectZaiNonStreaming ignored delta.error — a 200 whose SSE body carries
an error frame (rejected signature, expired captcha, stale token) came
back as a successful empty completion. Now it throws on an error frame,
matching the streaming path's [Z.ai error] convention; the caller's
existing try/catch returns makeErrorResult(502) instead of an empty 200.

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

---------

Co-authored-by: backryun <busan011@ormbiz.co.kr>
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
2026-08-12 08:41:03 -03:00

158 lines
6.5 KiB
TypeScript

import test from "node:test";
import assert from "node:assert/strict";
const { buildZaiStreamingBody, parseZaiFrame, collectZaiNonStreaming } = await import(
"../../open-sse/executors/zai-web/stream.ts"
);
/**
* Hard Rule #6 — "never silently swallow errors in SSE streams".
*
* HTTP-level failures are already handled: `fetchUpstream` turns any `!ok`
* response into a `makeErrorResult` with the sanitized body. The gap is a
* **200 whose SSE body carries an error payload** — `parseZaiFrame` returns
* null for it, `drainSseDeltas` drops it, and the stream closes with an empty
* assistant message + stop + [DONE]. The caller sees a successful empty
* completion: HTTP 200, `out=0`, "complete". That is the shape reported on
* #8451, and it makes a rejected signature, an expired captcha and a stale
* token all look identical.
*
* Scope note: returning null for a *contentless* frame is deliberate and
* live-validated — z.ai sends phase frames with no `delta_content`, and
* `executor-zai-web.test.ts` pins that ("returns null for frames with no usable
* delta"). So this only adds recognition of affirmatively error-shaped frames;
* "nothing parseable arrived" is left alone, because on this protocol that is
* not by itself evidence of failure.
*/
function sseStream(...frames: string[]): ReadableStream<Uint8Array> {
const enc = new TextEncoder();
return new ReadableStream({
start(c) {
for (const f of frames) c.enqueue(enc.encode(`data: ${f}\n\n`));
c.close();
},
});
}
async function readAll(stream: ReadableStream): Promise<string> {
const reader = stream.getReader();
const dec = new TextDecoder();
let out = "";
for (;;) {
const { done, value } = await reader.read();
if (done) break;
out += dec.decode(value as Uint8Array, { stream: true });
}
return out;
}
const emitChunk = (
controller: ReadableStreamDefaultController,
delta: Record<string, unknown>,
finish?: string
) => {
const payload = JSON.stringify({
choices: [{ index: 0, delta, finish_reason: finish ?? null }],
});
controller.enqueue(new TextEncoder().encode(`data: ${payload}\n\n`));
};
const contentOf = (sse: string) =>
[...sse.matchAll(/"content":"([^"]*)"/g)].map((m) => m[1]).join("");
test("parseZaiFrame classifies an error-shaped frame instead of discarding it", () => {
assert.equal(parseZaiFrame({ error: "captcha expired" })?.error, "captcha expired");
assert.equal(
parseZaiFrame({ error: { detail: "signature invalid" } })?.error,
"signature invalid"
);
assert.equal(
parseZaiFrame({ data: { error: { message: "token expired" } } })?.error,
"token expired"
);
});
test("an error frame is terminal", () => {
assert.equal(parseZaiFrame({ error: "nope" })?.done, true);
});
test("REGRESSION GUARD: contentless frames are still skipped, not reported as errors", () => {
// Live-validated behaviour — z.ai emits phase frames with no delta_content.
// Pinned by executor-zai-web.test.ts; re-asserted here because the error path
// added below runs in the same function.
assert.equal(parseZaiFrame({ data: { phase: "answer" } }), null);
assert.equal(parseZaiFrame({ type: "chat:completion", data: { phase: "thinking" } }), null);
assert.equal(parseZaiFrame({}), null);
assert.equal(parseZaiFrame(null), null);
assert.equal(parseZaiFrame("not-an-object"), null);
});
test("a 200 stream carrying an error frame surfaces it instead of finishing empty", async () => {
const upstream = sseStream(JSON.stringify({ error: { detail: "signature invalid" } }));
const out = await readAll(buildZaiStreamingBody(upstream, emitChunk, null));
assert.match(contentOf(out), /signature invalid/, "the upstream's diagnosis must reach the caller");
assert.match(contentOf(out), /\[Z\.ai error\]/, "tagged like the other web executors");
assert.ok(out.includes('"finish_reason":"stop"'));
assert.ok(out.includes("[DONE]"), "the stream still terminates cleanly for the client");
});
test("an error frame after partial content still surfaces, keeping what was streamed", async () => {
const upstream = sseStream(
JSON.stringify({ type: "chat:completion", data: { delta_content: "partial", phase: "answer" } }),
JSON.stringify({ error: "stream aborted upstream" })
);
const out = await readAll(buildZaiStreamingBody(upstream, emitChunk, null));
assert.match(contentOf(out), /partial/, "already-streamed content is preserved");
assert.match(contentOf(out), /stream aborted upstream/, "and the failure is appended, not dropped");
});
test("control: a well-formed stream is untouched", async () => {
const upstream = sseStream(
JSON.stringify({ type: "chat:completion", data: { delta_content: "hello", phase: "answer" } }),
JSON.stringify({ type: "chat:completion", data: { phase: "done", done: true } })
);
const out = await readAll(buildZaiStreamingBody(upstream, emitChunk, null));
assert.equal(contentOf(out), "hello");
assert.ok(!out.includes("[Z.ai error]"), "the happy path must stay clean");
});
test("control: a phase-only stream is not turned into an error", async () => {
// The exact case the deliberate-null design exists for.
const upstream = sseStream(
JSON.stringify({ type: "chat:completion", data: { phase: "answer" } }),
JSON.stringify({ type: "chat:completion", data: { delta_content: "hi", phase: "answer" } }),
JSON.stringify({ type: "chat:completion", data: { phase: "done", done: true } })
);
const out = await readAll(buildZaiStreamingBody(upstream, emitChunk, null));
assert.equal(contentOf(out), "hi");
assert.ok(!out.includes("[Z.ai error]"));
});
// ── Non-streaming path (collectZaiNonStreaming) ───────────────────────────────
test("collectZaiNonStreaming rejects on an error frame instead of returning empty", async () => {
const upstream = sseStream(JSON.stringify({ error: { detail: "captcha expired" } }));
await assert.rejects(
() => collectZaiNonStreaming(upstream),
(err: Error) => {
assert.match(err.message, /captcha expired/);
return true;
}
);
});
test("collectZaiNonStreaming returns content when no error frame is present", async () => {
const upstream = sseStream(
JSON.stringify({ type: "chat:completion", data: { delta_content: "hello", phase: "answer" } }),
JSON.stringify({ type: "chat:completion", data: { phase: "done", done: true } })
);
const result = await collectZaiNonStreaming(upstream);
assert.equal(result.answer, "hello");
assert.equal(result.reasoning, "");
});