Skip to content

[Bug] Z.ai OAuth succeeds but ZCode fails with zai_oauth_required on Ubuntu #116

Open

Description

@TheFahim

提交前确认 · Pre-submission checklist

  • 我已搜索过现有 issue,确认这不是重复 / I searched existing issues and confirmed this isn't a duplicate.
  • 我已阅读 CONTRIBUTING.md / I've read CONTRIBUTING.md.

问题类别 · Category

账号 / 登录 · Account / Login

涉及的 Agent 框架 · Agent framework

不涉及框架 · Not framework-specific

严重程度 · Severity

阻塞使用 · Blocking (无法使用核心功能 / core function unusable)

复现频率 · Reproducibility

必现 · Always

问题描述 · Description

I purchased an active ZCode subscription and attempted to sign in to the ZCode desktop application on Ubuntu using “Connect to Z.ai — Global.”

The browser authentication completes successfully and displays “Authorization successful,” but ZCode does not complete the login. The application displays “登录失败,请重试” (“Login failed, please retry”).

The terminal log shows that the initial authentication/token response succeeds with code 0, but the subsequent business-token exchange fails with:

Error: zai_oauth_required

The failure occurs inside ZaiBusinessTokenResolver.exchangeBusinessToken and OAuthService.handleCallback. Because of this, I cannot sign in to ZCode or use my paid subscription.

复现步骤 · Steps to reproduce

  1. Install and open the ZCode desktop application on Ubuntu Linux.
  2. Click “Connect to Z.ai.”
  3. Select/use the Global Z.ai authentication option.
  4. Sign in through the browser using the account that owns the active paid ZCode subscription.
  5. Complete the authorization process.
  6. Observe that the browser displays “Authorization successful” and redirects back to the application.
  7. Observe that ZCode displays “登录失败,请重试” (“Login failed, please retry”).
  8. Check the terminal output.
  9. Observe that oauth.handleCallback fails with Error: zai_oauth_required.

期望表现 · Expected behavior

After successful browser authorization, ZCode should accept the OAuth callback, connect my Z.ai subscription to the desktop application, and sign me in successfully.

实际表现 · Actual behavior

The browser reports that authorization was successful, and the initial token response returns code 0. However, ZCode fails during the business-token exchange with Error: zai_oauth_required.

The application remains logged out and displays “登录失败,请重试” (“Login failed, please retry”).

ZCode 版本 · ZCode version

v3.3.4 [.deb]

设备 / 系统 / 浏览器 · Device / OS / Browser

Ubuntu 24.04 LTS

截图 / 录屏 / 日志 · Screenshots / Recordings / Logs

Browser result:
“Authorization successful — Redirecting to the application...”

ZCode result:
“登录失败,请重试” (“Login failed, please retry”)

Relevant sanitized terminal log:

[zaiOAuth] token final response body:
{
"code": 0,
"msg": "",
"data": {
"token": "[REDACTED]",
"user": {
"user_id": "[REDACTED]",
"email": "[REDACTED]",
"name": "[REDACTED]"
},
"zai": {
"access_token": "[REDACTED]"
}
}
}

[zcode-host] [rpc:call] oauth.handleCallback FAIL

Error: zai_oauth_required
at ZaiBusinessTokenResolver.exchangeBusinessToken
at ZaiProviderAdapter.exchangeToken
at OAuthService.runWithAdapterError
at OAuthService.handleCallback

The initial OAuth/token response succeeds, but the subsequent business-token exchange fails.

Image

Activity

  1. added
    status: 待评估
    type: Bug
    on Jul 12, 2026
  2. github-actions commented on Jul 12, 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.
  3. dancenowjid commented on Jul 15, 2026

    @dancenowjid

    Please very urgent, i am also having this same issue.

  4. antonzvonovge commented on Aug 23, 2026

    @antonzvonovge

    I hit the same bug on Ubuntu. Browser login completes (“登录已完成” / returning to ZCode desktop), but the app still shows Login failed, please try again.

    This is not a zcode:// handler problem on my machine: the desktop app does receive the callback (OAuth 回调路由成功). The first token exchange succeeds (POST https://zcode.z.ai/api/v1/oauth/token → code: 0 with user data). Login then fails on the business-token step.

    Environment

    • OS: Ubuntu 22.04.5 LTS (jammy), kernel 6.8.0-138-generic, x86_64
    • Desktop: AppImage via AppImageLauncher 2.2.0
    • ZCode: 3.8.1.5310 (ZCode.AppImage)
    • Login path: Connect to Z.ai — Global (provider: "zai")
    • Browser: Microsoft Edge (xdg default for https)

    Sanitized log (same stack as this issue)

    [deep-link] OAuth 回调路由成功
    [zaiOAuth] token request POST https://zcode.z.ai/api/v1/oauth/token
    [zaiOAuth] token final response body {"code":0,"msg":"","data":{"token":"[REDACTED]","user":{"user_id":"[REDACTED]","email":"[REDACTED]","name":"[REDACTED]"},"zai":{"access_token":"[REDACTED]"}}}
    [zcode-host] [rpc:call] oauth.handleCallback FAIL Error: zai_oauth_required
        at ZaiBusinessTokenResolver.exchangeBusinessToken
        at ZaiProviderAdapter.exchangeToken
        at OAuthService.runWithAdapterError
        at OAuthService.handleCallback
    

    Happy to provide more logs (redacted) if useful.

  5. kadiratesdev commented on Aug 30, 2026

    @kadiratesdev

    Same bug here on CachyOS (Arch-based) Linux, ZCode 3.10.1. Browser login completes (“Authorization successful” / returning to the desktop app), but ZCode still shows Login failed, please try again.

    This is not a zcode:// handler problem on this machine: the desktop app does receive the callback (OAuth 回调路由成功). The first token exchange succeeds (POST https://zcode.z.ai/api/v1/oauth/token → code: 0 with user + data.zai.access_token). Login then fails on the business-token step.

    Environment

    • OS: CachyOS Linux (rolling, ID_LIKE=arch), kernel 7.2.2-1-cachyos, x86_64
    • Desktop: KDE Plasma, Wayland (XDG_SESSION_TYPE=wayland, WAYLAND_DISPLAY=wayland-0, DISPLAY=:0)
    • Install: native package zcode 3.10.1-2 → /opt/ZCode/zcode (Electron 41.0.3)
    • Login path: Connect to Z.ai — Global (provider: "zai")
    • Browser: Google Chrome 152.0.7977.64 (xdg default for https and the login redirect)
    • UID: 1000 (not root / not sudo)
    • URL handler: xdg-mime query default x-scheme-handler/zcode → zcode.desktop
    • Desktop Exec: Exec="/opt/ZCode/zcode" %U

    Sanitized log (same stack as this issue)

    [deep-link] OAuth 回调路由成功  provider=zai  completed=true
    [zaiOAuth] token request POST https://zcode.z.ai/api/v1/oauth/token
    [zaiOAuth] token final response body {"code":0,"msg":"","data":{"token":"[REDACTED]","user":{"user_id":"[REDACTED]","email":"[REDACTED]"},"zai":{"access_token":"[REDACTED]","accessTokenLength":404},"tokenLength":...}}
    [zcode-host] [rpc:call] oauth.handleCallback FAIL (~1300ms) Error: zai_oauth_required
        at ZaiBusinessTokenResolver.exchangeBusinessToken
        at ZaiProviderAdapter.exchangeToken
        at OAuthService.runWithAdapterError
        at OAuthService.handleCallback
    

    Reproduced 5 times in a row on 2026-08-30. Latency of handleCallback is consistently ~1250–1500ms, matching a completed HTTP round-trip rather than a timeout (timeoutMs for this step is 10s).

    Extra probe (this machine)

    https://api.z.ai/api/auth/z/login is reachable from the same host (HTTP 200, ~1.0–1.5s, TLS OK, no proxy env). A dummy POST returns:

    {"code":500,"msg":"User login failed","data":500,"success":false}

    ZCode maps success === false (and missing data.access_token) to a generic Error: zai_oauth_required, so the real upstream body never appears in the app log.

    API Key mode against https://api.z.ai/api/paas/v4/models works on this machine (HTTP 200), so general Z.ai API access is fine — only the OAuth business-token exchange fails.

    Happy to provide more redacted logs if useful.

  6. TON14 commented on Aug 31, 2026

    @TON14

    Fourth independent report, and I think I have the first concrete lead plus a
    working workaround.

    TL;DR

    • Reproduced on Nobara 44 (Fedora-based), ZCode 3.10.2, .rpm. Together
      with the reports above this now spans four distros, four install methods and
      versions 3.3.4 → 3.10.2, so it is neither distro-, version- nor
      packaging-specific.
    • The server is fine. I captured the OAuth callback before the app consumed
      the code and replayed both calls by hand from the same machine:
      POST api.z.ai/api/auth/z/login returned {"code":200,"success":true} with a
      valid business token. All three checks in exchangeBusinessToken would have
      passed — the request simply never reached the server from inside the app.
    • In my case the failure is branch (1), a transport error: Node/undici
      fetch to api.z.ai fails after ~550 ms with AggregateError: ETIMEDOUT
      while curl to the identical URL succeeds. It correlated with api.z.ai
      resolving to both A and AAAA on a machine with no working IPv6.
    • Workaround that got me logged in: pin api.z.ai to its IPv4 addresses in
      /etc/hosts, restart the app.
    • The fix I would ask for is not about IPv6. exchangeBusinessToken
      collapses four different failure modes into one zai_oauth_required, and the
      bare catch discards the original error. Four users in this thread, four
      environments — and none of us can tell which branch is firing. That is the
      core problem.

    Why nobody in this thread can pin it down

    exchangeBusinessToken in app.asar (out/host/index.js):

    async exchangeBusinessToken(t) {
      let n;
      try {
        n = await request(this.apiClient, this.loginUrl, {   // POST api.z.ai/api/auth/z/login
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ token: t })
        })
      } catch {
        throw new Error("zai_oauth_required")   // (1) transport error — cause discarded
      }
      if (!isSuccessfulZaiBusinessCode(n.code) || n.success === false)
        throw new Error("zai_oauth_required")   // (2) non-success code
      let o = n.data?.access_token?.trim() ?? n.data?.accessToken?.trim() ?? ""
      if (!o) throw new Error("zai_oauth_required")   // (3) missing access_token
      …
    }

    Four distinct causes, one identical message, and the transport branch throws the
    original exception away. The name also actively misleads: zai_oauth_required
    reads as "not authenticated", which is why this thread is full of people with
    active paid subscriptions auditing their accounts. I lost hours to exactly
    that before instrumenting the call.

    A note on timing

    Total handleCallback latency cannot separate the branches: it also contains
    the first exchange against zcode.z.ai/api/v1/oauth/token, which alone
    takes ~1 s. My totals were 1570 / 1706 / 2170 / 2580 ms, yet isolating the
    second call showed ~600 ms and a provable transport failure.

    Worth timing the two calls separately before concluding the server answered.

    Evidence for the transport branch

    Same Node fetch, three hosts used by the login flow, from the machine where
    ZCode was failing:

    api.z.ai     families=4+6  → FAIL after 554ms: AggregateError ETIMEDOUT
    zcode.z.ai   families=4    → OK 400 after 1058ms
    chat.z.ai    families=4    → OK 405 after 1230ms
    

    Identical with system Node v22.22.2 and with the Node bundled in ZCode
    (ELECTRON_RUN_AS_NODE=1 /opt/ZCode/zcode probe.js, v24.14.0). curl to the
    same URL succeeded every time — which is exactly why a manual sanity check
    suggests everything is healthy while the app keeps failing.

    RTT is high from here: the TCP handshake alone is ~600 ms
    (connect=0.586…0.624s, DNS excluded). That may be a precondition.

    Workaround

    # /etc/hosts
    8.217.100.151	api.z.ai
    8.217.233.95	api.z.ai
    

    Then fully restart the app (pkill -f '/opt/ZCode/[z]code'). Login completes and
    credentials.json gets oauth:zai:access_token, zcodejwttoken,
    oauth:zai:user_info, oauth:active_provider — previously it held only
    oauth:login_attribution.

    NODE_OPTIONS=--network-family-autoselection-attempt-timeout=… does not
    help — Electron strips NODE_OPTIONS when spawning the host process in a
    packaged app:

    ERROR:electron/shell/common/node_bindings.cc:485]
    Most NODE_OPTIONs are not supported in packaged apps.
    

    What I could NOT verify

    The tempting explanation is Node's Happy Eyeballs per-attempt budget
    (autoSelectFamilyAttemptTimeout, default 250 ms) being blown by the ~600 ms
    handshake. I could not confirm that. A control test with raw net.connect,
    both families and a 250 ms limit connected fine — Node waits for already-started
    attempts instead of abandoning them:

    attempt timeout  250ms →  OK after  935ms → 8.217.233.95
    attempt timeout  700ms →  OK after  610ms → 8.217.100.151
    

    The real failure happened inside undici, not raw TCP, and I could not finish
    that experiment: the AAAA records for api.z.ai disappeared from DNS during
    the investigation
    (present 19:30–19:44 UTC+3 on 2026-08-31, gone by 19:55;
    dig now returns has no AAAA record). Nothing left to reproduce against.

    So: "dual-family resolution → failure, IPv4-only → works" is reproducible and
    solid. The mechanism inside undici is not established. It is also possible that
    others here are hitting branch (2) or (3) instead — which brings me back to the
    main point.

    Suggested fixes, in descending order of confidence

    1. Stop discarding the cause. Log or wrap the original exception instead of
      throwing a bare zai_oauth_required. This is the one change I am certain
      about, and it does not depend on my network theory being right. Right now
      four reporters across four distros cannot distinguish a DNS/transport failure
      from a genuine authorization rejection.
    2. Give the branches distinct messages (transport / non-success code /
      missing access_token), and log the two token calls with separate timings.
    3. Possibly tune undici's autoSelectFamilyAttemptTimeout, or set
      autoSelectFamily: false, for these endpoints. Flagged as a guess — see
      above.

    For others hitting this

    dig +short AAAA api.z.ai                                            # dual-stack?
    curl -4 -so /dev/null -w 'connect=%{time_connect}s\n' https://api.z.ai/
    node -e 'fetch("https://api.z.ai/api/auth/z/login",{method:"POST",
      headers:{"Content-Type":"application/json"},body:"{}"})
     .then(r=>console.log("OK",r.status)).catch(e=>console.log("FAIL",e.cause?.code))'

    An AAAA record present, connect well above 0.25 s, and FAIL ETIMEDOUT while
    curl succeeds is the pattern I saw. If your dig shows no AAAA and the Node
    check returns OK, your cause is probably branch (2) or (3) and the log will
    stay useless until fix #1 lands.

  7. kadiratesdev commented on Aug 31, 2026

    @kadiratesdev

    Thanks @TON14 — confirmed that your diagnosis and workaround solve the issue on my machine.

    Environment: CachyOS Linux, ZCode 3.10.1 (Electron 41.0.3 / bundled Node v24.14.0).

    Before the workaround:

    • api.z.ai resolved to both A and AAAA records.
    • ZCode's bundled Node fetch failed 3/3 times with AggregateError: ETIMEDOUT; the IPv6 attempts also reported ENETUNREACH.
    • curl -4 to the same host succeeded.

    After pinning the two IPv4 addresses from your comment in /etc/hosts:

    • The same bundled Electron/Node probe succeeded 3/3 times with HTTP 200.
    • I fully restarted ZCode and completed Connect to Z.ai → Global successfully.
    • The previous zai_oauth_required login failure is gone.

    So this is a second confirmed case where the IPv4 pinning workaround fixes the actual ZCode OAuth flow. Thank you for the detailed investigation and for sharing a working workaround — it saved me a lot of time.

  8. p99will commented on Sep 1, 2026

    @p99will

    Big thanks to @TON14 for your work investigating this and coming up with a resolve!.


    Fifth independent report — and the first on Windows, so the bug is not Linux-specific either.

    TL;DR

    • Reproduced on Windows 11 Pro (10.0.26200, x64), ZCode 3.10.2, standard Windows installer (%LOCALAPPDATA%\Programs\ZCode). Same signature as everyone above: browser OAuth completes, first token exchange succeeds, login dies at the business-token step with zai_oauth_required.
    • @TON14's diagnosis holds here too: the /etc/hosts IPv4 pinning workaround fixed login on Windows immediately, no restart of the machine needed.
    • My machine matches the suspected precondition: api.z.ai resolves A + AAAA, my IPv6 path to it is dead (connection failure, not just DNS), and my TCP handshake to the IPv4 edge is ~285 ms — above the ~250 ms autoSelectFamilyAttemptTimeout default TON14 flagged.
    • Adding my voice to fix [建议 / Feature] 性能优化,运行一个小时左右任务,整个页面非常卡顿,基本不可用 #1: I also cannot tell which branch of exchangeBusinessToken fired without instrumenting the app. The bare catch that discards the original error is what turned a 30-second network problem into an evening of account auditing.

    Environment

    • OS: Windows 11 Pro, build 10.0.26200, x64
    • Install: standard per-user Windows installer → %LOCALAPPDATA%\Programs\ZCode
    • ZCode: 3.10.2
    • Login path: Connect to Z.ai — Global (provider: "zai")
    • Network: ~280 ms RTT to the api.z.ai (Aliyun) edge; IPv6 present in DNS but not usable on this machine (see below)

    Sanitized log (trimmed to the relevant lines; same stack as the issue)

    [2026-08-31 23:42:16.953] [pid:11616] [zaiOAuth] token request {
      method: 'POST',
      url: 'https://zcode.z.ai/api/v1/oauth/token',
      headers: { 'Content-Type': 'application/json' },
      body: {
        provider: 'zai',
        code: 'code...eba0',
        codeLength: 17,
        redirect_uri: 'https://zcode.z.ai/app/oauth/login?redirect=zcode%3A%2F%2Foauth%2Fcallback&app_version=3.10.2',
        state: '20b1<REDACTED>6ec9a0'
      }
    }
    [2026-08-31 23:42:16.976] [pid:7436] [main] [deep-link] OAuth 回调路由成功 {
      state: '20b1<REDACTED>6ec9a0',
      windowId: 1,
      provider: 'zai',
      completed: true
    }
    [2026-08-31 23:42:17.605] [pid:11616] [zaiOAuth] token final response body {
      code: 0,
      msg: '',
      data: {
        token: 'eyJh...6lTk',
        user: { user_id: '<REDACTED>', email: '<REDACTED>', avatar: '<REDACTED>', name: '<REDACTED>' },
        zai: { access_token: 'eyJh...Doco', accessTokenLength: 404 },
        tokenLength: 255
      }
    }
    [2026-08-31 23:42:18.407] [pid:11616] [zcode-host] [rpc:call] oauth.handleCallback FAIL (1460.6ms) Error: zai_oauth_required
        at ZaiBusinessTokenResolver.exchangeBusinessToken (<REDACTED>/AppData/Local/Programs/ZCode/resources/app.asar/out/host/index.js:1246:33095)
        at process.processTicksAndRejections (node:internal/process/task_queues:104:5)
        at async ZaiProviderAdapter.exchangeToken (<REDACTED>/AppData/Local/Programs/ZCode/resources/app.asar/out/host/index.js:1246:37570)
        at async OAuthService.runWithAdapterError (<REDACTED>/AppData/Local/Programs/ZCode/resources/app.asar/out/host/index.js:1246:63631)
        at async <REDACTED>/AppData/Local/Programs/ZCode/resources/app.asar/out/host/index.js:1246:60925
        at async <REDACTED>/AppData/Local/Programs/ZCode/resources/app.asar/out/host/index.js:1246:53193
    

    The deep-link handler received the callback fine, the first exchange against zcode.z.ai returned code: 0 with full user data, and then the second call (api.z.ai/api/auth/z/login) produced the generic zai_oauth_required ~800 ms later — same four-branches-one-message dead end everyone else hit.

    Diagnostics from my machine (pre-fix, captured after removing the hosts pin)

    I captured the failing state directly on Windows by removing the pin, flushing DNS, and re-running the probes — so this is a live pre-fix reproduction, not just a post-hoc guess:

    • DNS is dual-stack: nslookup -type=AAAA api.z.ai returns two 240b:4001:... addresses, -type=A returns the two Aliyun IPv4 edges.

    • Node fetch to the login endpoint fails reproducibly, curl succeeds. With Node v24.19.0 (same major as the Electron-bundled runtime), 3/3 attempts to POST https://api.z.ai/api/auth/z/login fail in 564–872 ms with fetch failed → AggregateError: ETIMEDOUT. In the same state, curl over IPv4 returns HTTP 200 with tcp_connect = 0.443 s.

    • Full per-attempt breakdown (e.cause.errors) — this is the interesting part:

      attempt 0  ETIMEDOUT      8.217.233.95   (IPv4)   port 443
      attempt 1  ENETUNREACH    240b:4001:...:52d6 (IPv6)
      attempt 2  ETIMEDOUT      8.217.100.151  (IPv4)   port 443
      attempt 3  ENETUNREACH    240b:4001:...:4bb1 (IPv6)
      

      Both IPv6 attempts fail immediately with ENETUNREACH (no usable v6 route — confirmed separately: forced curl -6 --resolve over a real AAAA address cannot connect at all). But note the IPv4 attempts also fail with ETIMEDOUT even though curl connects fine to the same IPs in ~440 ms — i.e. the v4 attempts are being abandoned before they can complete. That is consistent with undici's ~250 ms autoSelectFamilyAttemptTimeout budget being blown by a >250 ms handshake, and unlike TON14's raw net.connect control test, this failure is inside undici's connection logic — so my data strengthens the hypothesis they couldn't confirm. My handshake times to this edge ranged 0.28–0.44 s across the evening, straddling that threshold.

    • With the hosts pin in place, everything flips: the same Node probe returns OK 200 {"code":1002,"msg":"token is empty"} (code:1002 is expected for an empty body — the point is the request reaches the server), and login completes.

    • Login state after the fix: credentials.json (in my case %USERPROFILE%\.zcode\v2\credentials.json) went from oauth:login_attribution only to containing oauth:zai:access_token, oauth:zai:user_info, zcodejwttoken, oauth:active_provider — the same post-success key set TON14 described.

    Windows version of the workaround

    1. Open Notepad as Administrator, open C:\Windows\System32\drivers\etc\hosts, and add (use fresh IPs — see caveat):

      8.217.100.151	api.z.ai
      8.217.233.95	api.z.ai
      
    2. Flush the resolver cache: ipconfig /flushdns

    3. Fully quit ZCode from the system tray (right-click tray icon → quit; closing the window is not enough) and relaunch.

    4. Connect to Z.ai — Global → completes normally.

    Caveat

    These are Aliyun CDN addresses and the AAAA records were already appearing/disappearing around TON14's investigation, so they may rotate. If login breaks again weeks from now, check nslookup api.z.ai and update the two hosts lines to whatever the current A records are.

    +1 on the suggested fixes

    Especially #1 and #2. Four or five of us across five OSes produced four identical, undebuggable logs. zai_oauth_required reads as "you're not authenticated" when the actual causes span DNS/transport failure, a non-success business code, and a missing access_token. Distinct error messages plus the original exception would have saved every one of us the account/subscription audit — and would tell you whether the remaining reports are the IPv6 issue or something else entirely.

  9. KNawm commented on Sep 4, 2026

    @KNawm

    guys if you hit this, ping api.z.ai near or >250ms and this right here is your bug

    problem is syns to the correct ip are abandoned at ~250ms. temporary workaround if ur network sucks:

    sudo $(which node) -e 'const{execSync}=require("child_process"),net=require("net");for(const ip of["127.0.0.2","127.0.0.3","127.0.0.4"]){try{execSync("ifconfig lo0 alias "+ip+" up")}catch{}}for(const[l,u]of[["127.0.0.2","8.217.100.151"],["127.0.0.3","47.86.227.136"],["127.0.0.4","60.205.172.105"]])net.createServer({pauseOnConnect:true},c=>{const s=net.connect({host:u,port:443});s.on("connect",()=>{c.pipe(s);s.pipe(c);c.resume()});const k=()=>{c.destroy();s.destroy()};s.on("error",k);c.on("error",k);s.on("close",()=>c.end());c.on("close",()=>s.end())}).listen(443,l,()=>console.log("relay",l,"->",u))'
    

    as the saying goes: it works where the wires are short...

  10. deegool commented on Sep 7, 2026

    @deegool

    Thanks @TON14 it solved mine aswell

  11. faik-sevim commented on Sep 8, 2026

    @faik-sevim

    Can confirm this bug affects macOS as well. Huge thanks to @KNawm and @TON14 for the diagnosis and the relay concept. If you are physically far from the servers, the hardcoded ~250ms timeout in Node.js/undici will instantly kill your login attempt.

    Here is the step-by-step local relay workaround perfectly adapted for macOS users.

    How to fix on macOS

    1. Check your ping (Diagnosis)
    Open Terminal and run:

    ping api.z.ai

    If your time= is consistently around or above 250ms, you are definitely hitting this exact timeout bug.

    2. The Workaround (Local Relay Bridge)
    Since we can't lower the physical ping, we can trick the app by creating a local bridge (0ms ping) that forwards the request to the real server.

    Step A: Redirect the domain to localhost
    Open Terminal and edit your hosts file:

    sudo nano /etc/hosts

    Add this line to the very bottom:
    127.0.0.2 api.z.ai
    (Save and exit: Ctrl+O, Enter, Ctrl+X)

    Step B: Flush macOS DNS Cache

    sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder

    Step C: Run the Node.js Relay Bridge
    Paste this script into the Terminal and hit Enter. Leave this window open. It creates a local macOS network alias and forwards the traffic, bypassing the app's internal timeout:

    sudo node -e 'const{execSync}=require("child_process"),net=require("net");try{execSync("ifconfig lo0 alias 127.0.0.2 up")}catch{}net.createServer({pauseOnConnect:true},c=>{const s=net.connect({host:"8.217.100.151",port:443});s.on("connect",()=>{c.pipe(s);s.pipe(c);c.resume()});const k=()=>{c.destroy();s.destroy()};s.on("error",k);c.on("error",k);s.on("close",()=>c.end());c.on("close",()=>s.end())}).listen(443,"127.0.0.2",()=>console.log("Relay active: 127.0.0.2 -> 8.217.100.151"))'

    Step D: Log in
    Completely Quit ZCode from the macOS Dock (Right Click -> Quit, don't just close the window), open it again, and complete the "Connect to Z.ai" login. It should work instantly. Once logged in, you can remove the line from your /etc/hosts and close the Terminal.

  12. Shadid516 commented on Sep 8, 2026

    @Shadid516

    Sixth independent confirmation + a cleaner workaround (no /etc/hosts IP pinning).

    Environment: Debian 13 (trixie), ZCode 3.11.2 AppImage (bundled Electron 41 / Node 24, undici v6.24.1). Login path: Connect to Z.ai -> Global.

    Same signature as everyone above: POST /api/v1/oauth/token -> code:0 with data.zai.access_token, then ZaiBusinessTokenResolver.exchangeBusinessToken -> zai_oauth_required, underlying error fetch failed.

    Metrics match @TON14 / @KNawm exactly:

    • curl -6 https://api.z.ai/... -> fails instantly (broken IPv6)
    • curl -4 https://api.z.ai/... -> OK, but connect = 0.319s (i.e. >250ms)
    • bundled undici default -> fetch failed
    • bundled undici with Agent({ connect: { family: 4 } }) -> HTTP 200

    So it's the same autoSelectFamilyAttemptTimeout ~= 250ms abandonment, on a machine that is both IPv6-dead and ~320ms from the IPv4 edge.

    Cleaner workaround (no hardcoded IPs): patch the host bundle's network transport to force IPv4. Two spots in resources/app.asar/out/host/index.js:

    1. createDispatcher (lHe) - build the undici Agent with connect: { family: 4 }.
    2. The transport's fast path - if (W.kind==="direct" && !$.caCertPath) return globalThis.fetch(k,I) - bypasses that dispatcher; reroute it through the dispatcher so family:4 actually applies.

    This makes api.z.ai reachable over IPv4, and login plus the paid Coding Plan complete, with no dependence on the current GA/CDN IPs.

    Even simpler OS-level alternative (system-wide, affects all apps): just disable IPv6 so undici only ever sees an IPv4 route.

    sudo sysctl -w net.ipv6.conf.all.disable_ipv6=1
    sudo sysctl -w net.ipv6.conf.default.disable_ipv6=1

    Persist across reboot:

    echo 'net.ipv6.conf.all.disable_ipv6=1' | sudo tee /etc/sysctl.d/99-disable-ipv6.conf
    echo 'net.ipv6.conf.default.disable_ipv6=1' | sudo tee -a /etc/sysctl.d/99-disable-ipv6.conf
    sudo sysctl --system

    Suggested root fix for the team: in the host undici dispatcher, disable autoSelectFamily (or raise autoSelectFamilyAttemptTimeout) instead of the 250ms default - e.g. new Agent({ connect: { autoSelectFamily: false } }). And please stop swallowing the real error in exchangeBusinessToken (log error.cause).

  13. capgelka commented on Nov 10, 2026

    @capgelka

    I've got the same problem, so vibecoded a solution https://github.com/capgelka/zcode-bridge based on a @faik-sevim comment. Works fine on my Mac and should support Linux as well, though I haven't checked it myself on it yet.

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: Bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions