Skip to content

cat: 模型 type: Bug severity: 影响体验 OpenAI-compatible providers: context-window wheel / token stats never populate because stream_options.include_usage is not sent #93

Closed

Description

@mdihay


Summary
For any OpenAI-compatible model provider (e.g. a local llama.cpp / vLLM / Ollama server), the context-window wheel and
token-usage stats never appear, even when contextWindow is configured correctly. The same stats work fine for the built
in Anthropic-format providers (GLM).
Root cause: ZCode streams chat responses but does not send stream_options: { include_usage: true } in the
request to /chat/completions. Per the OpenAI streaming spec, a server only emits the trailing usage chunk when the
client explicitly requests it. Anthropic’s streaming API always sends usage in the terminal event, so GLM works; OpenAI
compatible servers (correctly) stay silent without the flag. As a result ZCode never receives totalTokens, so the wheel’s
render gate (used > 0 && size > 0) is never satisfied.
Suggested fix (one line)
In resources/glm/zcode.cjs, the OpenAI-compatible provider factory is constructed without includeUsage:
case "openai-compatible": return E6r({name:r.name??t,baseURL:r.baseURL,apiKey:o,fetch:i,headers:n})

The bundled @ai-sdk/openai-compatible SDK already supports the option — it only emits stream_options
{include_usage:!0} when includeUsage is truthy. Passing it through fixes the wheel:
case "openai-compatible": return E6r({name:r.name??t,baseURL:r.baseURL,apiKey:o,fetch:i,headers:n,includeUsage:!0})

This is harmless for OpenAI-compatible providers that already stream usage (they simply keep sending it), and spec-correct
for those that wait for the flag (they start sending it). The Anthropic and OpenAI Responses code paths are unaffected.
Reproduction
Run any OpenAI-compatible local server, e.g. llama-server: llama-server -m .gguf --host 0.0.0.0
--port 8080 --jinja
In ZCode, add a custom OpenAI-compatible provider pointing at http://localhost:8080/v1, with a model whose
contextWindow is set (e.g. 131072).
Send one message to the model.
Observed: response streams normally, but the context-window wheel / token stats never populate.
Capture the request ZCode sends to /v1/chat/completions (e.g. with a logging proxy): the body has stream:true
but no stream_options.
Verification of root cause (server side is fine)
Same llama-server responds correctly when the flag is sent:
Without stream_options → final SSE chunk contains only timings, no usage.
With stream_options: {include_usage: true} → final SSE chunk contains: json {"usage"
{"prompt_tokens":13,"completion_tokens":5,"total_tokens":18,"prompt_tokens_details"
{"cached_tokens":9}}}
After applying the one-line fix above, the wheel populates correctly.
Environment
ZCode desktop: @zcode/desktop 3.2.5 (Linux x64, deb)
Provider kind: openai-compatible (custom / user-scope)
Backend tested: llama.cpp llama-server (Qwen3.6-35B-A3B GGUF)
Also confirmed by ecosystem precedent: tools like CLIProxyAPI and cc-switch already auto-inject
stream_options.include_usage for OpenAI-compatible upstreams for exactly this reason — suggesting this is a
known gap on the client side.Impact
Users of local / self-hosted / third-party OpenAI-compatible models (a growing use case — llama.cpp, vLLM, Ollama, LM
Studio, etc.) lose a core UX feature (token/context visibility) for no functional reason. The fix is one field and is fully
backwards-compatible.
Why I can’t just keep a local patch
Patching zcode.cjs works but is overwritten on every ZCode update and is fragile to bundle layout changes. A one-line
upstream fix removes the workaround entirely.


Labels requested: type: Bug, cat: 模型, severity: 影响体

Activity

  1. github-actions commented on Jul 5, 2026

    @github-actions

    👋 感谢你的反馈,我们已经收到。

    • 维护者会在 3 个工作日内 给出首次响应。
    • 状态保持为 status: 待评估,你可以随时补充信息。
    • 信息不全时我们会打上 needs: 更多信息 标签并 @ 你。

    👋 Thanks — we've received your issue.

    • A maintainer will respond within 3 business days.
    • Status stays at status: 待评估 (Triage); feel free to add context.
    • If we need more details, we'll add needs: 更多信息 and ping you.
  2. Color2333 commented on Jul 10, 2026

    @Color2333

    Additional impact: this root cause also breaks auto-compact, causing input longer than context length errors

    Reporting a more severe downstream consequence of the exact same root cause (#93 currently only documents the UI wheel not populating). With a self-hosted OpenAI-compatible model that has a small context window, this bug causes auto-compact to silently fall back to an inaccurate local token estimate, so a single send can jump from "under threshold" straight past the 100% ceiling — producing a hard The input (410089 tokens) is longer than the model's context length (409600 tokens) rejection, with no compact ever triggered.

    Environment

    Why auto-compact silently breaks (source evidence from glm/zcode.cjs)

    The auto-compact decision function (xW, ~offset 695205) computes tokenCount like this:

    let u = _0(e.messages),                       // estimatedTokenCount — local estimate
        l = e.tokenOverride?.tokenCount ?? u,     // prefer provider-reported usage; fall back to estimate
        c = e.tokenOverride?.source ?? "estimate" // default source is "estimate"

    tokenOverride comes from syn(latestProviderContextUsage, messages), and latestProviderContextUsage is set by Ojt(g, messages.length, s) — which extracts usage from the streamed response:

    function Ojt(e,t,r){
      let o = y4e(e.usage);                  // pull inputTokens from the response usage
      if(!(o === void 0 || o <= 0))         // ONLY returns when usage is present and > 0
        return { inputTokens:o, cacheReadTokens:e.usage?.cacheReadTokens, ... };
      // otherwise → returns undefined → no tokenOverride → xW falls back to "estimate"
    }

    syn itself guards on the same thing:

    function syn(e,t){ if(!e || e.inputTokens<=0 || e.messageCount>t.length) return; ... }

    So when the OpenAI-compatible server doesn't emit a trailing usage chunk (because stream_options.include_usage isn't sent — exactly #93), Ojt returns undefined, tokenOverride is never set, and auto-compact permanently runs on the local estimate (source: "estimate"), never the real server-side token count.

    The local estimator (_0) appears to under-count in long sessions (it can't see server-side tokenizer totals / reasoning tokens), so for a model with only ~400K context the estimate stays below the 95% threshold while the real input is already at ~100%. The result: compact never fires, and the next send sails past the ceiling.

    Reproduction (real session, from local logs)

    Timeline reconstructed from ~/.zcode/v2/logs/2026-07-10.log for session sess_c1234ab7-...:

    time event messageCount note
    22:16:29 resume + send 493 context still safe (under 95%)
    22:17:35 resume + send 497 two more messages
    22:20:26 resume 506, sessionStatus:"error" previous request already exceeded → session marked error
    22:20:27 send (textLength: 2) — 410089 > 409600 → rejected

    The session crossed from "under the 95% threshold" to "over 100%" in a single send, so the 95% auto-compact window was skipped entirely. Once the session hit error status, subsequent sends kept carrying the over-limit context and failing repeatedly.

    Verification that the server is fine (matches #93)

    Against the same sglang endpoint:

    • stream:true without stream_options → final SSE chunk has no usage (grep -c '"usage"' = 0)
    • stream:true with stream_options:{include_usage:true} → final chunk carries {"usage":{"prompt_tokens":13,"total_tokens":18,"completion_tokens":5,"reasoning_tokens":9}}
    • non-stream → usage present as expected

    So the server is spec-correct; ZCode simply never asks for it.

    Suggested fix (extends #93's one-liner)

    #93's proposed fix (includeUsage: true on the openai-compatible factory) fixes this too — once the real usage flows into Ojt → syn → tokenOverride, xW switches from source:"estimate" to real server counts and auto-compact triggers correctly.

    Two additional hardening ideas, either of which would have softened this even before the include_usage fix:

    1. Expose the auto-compact threshold (thresholdPercentOverride already exists as a read site in OTt, accepting 1–100, but is never wired to any user entry point — config schema / settings / env). For small-context local models, 95% leaves almost no buffer; a user-settable ~80% would let compact fire earlier.
    2. Don't keep sending after a context-length rejection. When a session is already in error because of input longer than context length, the current behavior re-sends the same over-limit context on the next send and fails identically. A single failed-then-auto-compact (or a clear prompt to /compact / start a new session) would avoid the repeat-failure loop.

    Happy to provide more log excerpts or the exact zcode.cjs offsets if useful.

  3. panda920 commented on Aug 18, 2026

    @panda920
    Collaborator

    ✅ 已修复(v3.3.6 起)

    OpenAI 兼容 provider 现在默认带 stream_options.include_usage: true 发流式请求(includeUsage 默认开启,也可在 provider 配置里显式关掉),服务端会回传 usage,上下文表盘 / token 统计能正常显示;@Color2333 提到的 auto-compact 拿不到真实 token 数、只能本地估算的问题也随之解决。请升级到最新版验证,仍有问题请回帖。


    ✅ Fixed (since v3.3.6)

    Streaming requests to OpenAI-compatible providers now send stream_options.include_usage: true by default (includeUsage defaults to on; it can be turned off explicitly in the provider config), so the server returns usage and the context-window wheel / token stats populate. The downstream auto-compact issue @Color2333 described (falling back to a local estimate) is resolved by the same change. Please upgrade to the latest version and verify — reply here if anything is still off.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority: P2status: 已上线

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions