Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,23 @@ upstream:
overload_max_attempts: 11
overload_base_delay_seconds: 2
overload_max_delay_seconds: 60
concurrency_max_attempts: 5
concurrency_base_delay_seconds: 1
concurrency_max_delay_seconds: 10
pool:
strategy: drain_first
cooldown_seconds: 30
max_in_flight_per_account: 4
acquire_wait_seconds: 5
# ZCode admits one concurrent request per account for GLM-5.3 (3008/3009
# above it). Keep this at 1 and let acquire_wait_seconds queue the rest.
max_in_flight_per_account: 1
acquire_wait_seconds: 120
concurrency_hold_seconds: 10
concurrency_hold_max_seconds: 60
# Upstream keeps a just-finished request in its per-user concurrency count
# for a few seconds, so handing a released account out again immediately
# answers 3008 even though the slot is free locally. Wait this long after
# release() before re-admitting the account.
concurrency_settle_seconds: 5
balance_poll_seconds: 60
blocked_model_cooldown_seconds: 900
accounts:
Expand Down
17 changes: 7 additions & 10 deletions generator/invite_claim.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,13 @@
sys.stderr.reconfigure(encoding='utf-8', errors='replace')

from utils import BROWSER_ARGS
from plan_check import APP_VERSION, _request, client_timezone, direct_requests
from plan_check import (
APP_VERSION,
_request,
client_timezone,
direct_requests,
per_account_device_mid,
)

# NOTE: playwright is imported lazily inside claim_invite(). The referral
# helpers below (referral_summary / send_one_message) are imported by the
Expand Down Expand Up @@ -557,20 +563,11 @@ def wrapper(*args, **kwargs):
return wrapper


def per_account_device_mid(token: str) -> str:
"""Stable per-account device id (uuid5 of the chat token) instead of the
hardcoded shared one — every account reporting the SAME x-device-mid in
telemetry is a direct cross-account correlation signal."""
import uuid as _u
return str(_u.uuid5(_u.NAMESPACE_URL, 'zcode-device:' + (token or '')))


APP_HEADERS = { # exact cli/init header set captured from the desktop app
'content-type': 'application/json',
'http-referer': 'https://zcode.z.ai',
'user-agent': 'ZCode/' + APP_VERSION,
'x-client-language': 'en-US',
'x-device-mid': '58aca3b3-3239-4cb7-9c70-df3e5488fb99',
'x-os-category': 'windows',
'x-os-version': '10.0.26200',
'x-platform': 'win32-x64',
Expand Down
18 changes: 12 additions & 6 deletions generator/plan_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,16 +246,22 @@ def is_campaign_plan_name(name) -> bool:
}
# Stable PER-ACCOUNT device id: every account using one shared hardcoded
# x-device-mid is a direct cross-account correlation signal for risk control.
# uuid5 of the chat token keeps the id deterministic per account (the gateway
# plan-checker and the message flow then report a consistent device).
DEVICE_MID = "58aca3b3-3239-4cb7-9c70-df3e5488fb99" # legacy fallback only


def account_device_mid(account_id: str) -> str:
"""Same derivation as zcode_gateway.zcode_device.account_device_mid.

The generator runs under its own interpreter, where the gateway package is
not importable, so the formula is duplicated; tests pin the two together.
"""
return str(uuid.uuid5(uuid.NAMESPACE_URL, 'zcode-device:' + (account_id or '')))


def per_account_device_mid(token: str) -> str:
import uuid as _u
if not token:
return DEVICE_MID
return str(_u.uuid5(_u.NAMESPACE_URL, 'zcode-device:' + token))
"""The device of the account a chat token or zjwt belongs to."""
ident = jwt_user_id(token)
return account_device_mid(ident) if ident else DEVICE_MID

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Non-JWT tokens now fall back to the shared legacy DEVICE_MID, which reintroduces the cross-account correlation this PR removes. The poll token from get_zcode_jwt is secrets.token_hex(32), so it has no user_id/sub and every signup flow sends the same device ID. Keep the per-token derivation as the fallback for non-empty tokens.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At generator/plan_check.py, line 264:

<comment>Non-JWT tokens now fall back to the shared legacy `DEVICE_MID`, which reintroduces the cross-account correlation this PR removes. The poll token from `get_zcode_jwt` is `secrets.token_hex(32)`, so it has no `user_id`/`sub` and every signup flow sends the same device ID. Keep the per-token derivation as the fallback for non-empty tokens.</comment>

<file context>
@@ -246,16 +246,22 @@ def is_campaign_plan_name(name) -> bool:
-    return str(_u.uuid5(_u.NAMESPACE_URL, 'zcode-device:' + token))
+    """The device of the account a chat token or zjwt belongs to."""
+    ident = jwt_user_id(token)
+    return account_device_mid(ident) if ident else DEVICE_MID
 
 
</file context>
Suggested change
return account_device_mid(ident) if ident else DEVICE_MID
if not token:
return DEVICE_MID
ident = jwt_user_id(token)
if ident:
return account_device_mid(ident)
return str(uuid.uuid5(uuid.NAMESPACE_URL, 'zcode-device:' + token))



_TZ_CACHE = None
Expand Down
130 changes: 128 additions & 2 deletions gui_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
Replaces the Tkinter GUI. The gateway runs on a background thread; the window
is the served dashboard (/dash) in a native WebView2 shell via pywebview.
A single-instance mutex prevents a second exe from fighting over the port.

A notification-area icon keeps the gateway reachable with the window closed:
closing hides the window, the tray menu reopens it or quits for real.
"""

from __future__ import annotations
Expand All @@ -23,6 +26,17 @@
MUTEX_NAME = "ZcodeGatewayByB3hnamR-SingleInstance"
DASH_PATH = "/dash"

CMD_OPEN, CMD_COPY, CMD_LOG, CMD_FOLDER, CMD_QUIT = 1, 2, 3, 4, 9
TRAY_MENU = (
(CMD_OPEN, "Open dashboard"),
(CMD_COPY, "Copy address"),
(None, ""),
(CMD_LOG, "Open log"),
(CMD_FOLDER, "Open data folder"),
(None, ""),
(CMD_QUIT, "Quit"),
)

_mutex_handle = None


Expand Down Expand Up @@ -244,6 +258,86 @@ def _offer_webview2_or_browser(url: str) -> bool:
return True


def _log_file() -> Path:
return Path(os.environ.get("LOCALAPPDATA", ".")) / "ZcodeGateway" / "zcode-gateway.log"


def _open_path(path: Path) -> None:
try:
os.startfile(str(path))
except OSError:
pass


def _quit_from_tray(window_ref: list, quitting: threading.Event) -> None:
"""Destroy the window from the tray thread; main() finishes the shutdown."""
quitting.set()

def finish() -> None:
window = window_ref[0]
try:
if window is not None:
window.destroy()
except Exception:
pass
# main() runs the normal shutdown once webview.start() returns. If the
# UI thread is wedged, quit anyway rather than leave a dead tray icon.
time.sleep(8)
_shutdown_generator()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: main() also calls _shutdown_generator() after window.destroy() returns, so this fallback can start a second generator shutdown while the first is still running. Coordinate the fallback with the main shutdown path before issuing cleanup or exiting.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At gui_main.py, line 286:

<comment>`main()` also calls `_shutdown_generator()` after `window.destroy()` returns, so this fallback can start a second generator shutdown while the first is still running. Coordinate the fallback with the main shutdown path before issuing cleanup or exiting.</comment>

<file context>
@@ -244,6 +258,86 @@ def _offer_webview2_or_browser(url: str) -> bool:
+        # main() runs the normal shutdown once webview.start() returns. If the
+        # UI thread is wedged, quit anyway rather than leave a dead tray icon.
+        time.sleep(8)
+        _shutdown_generator()
+        os._exit(0)
+
</file context>

os._exit(0)

threading.Thread(target=finish, daemon=True, name="tray-quit").start()


def _start_tray(url: str, quitting: threading.Event, window_ref: list):
"""Notification-area icon, or None when the shell will not give us one."""
from zcode_gateway import tray as tray_icon

def open_dashboard() -> None:
window = window_ref[0]
if window is None:
return
try:
window.show()
window.restore()
except Exception:
pass

def run_command(command: int) -> None:
if command == CMD_OPEN:
open_dashboard()
elif command == CMD_COPY:
tray_icon.copy_text(url)
elif command == CMD_LOG:
_open_path(_log_file())
elif command == CMD_FOLDER:
_open_path(_exe_dir())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: "Open data folder" opens the exe folder, not the data folder. When the exe folder is read-only the gateway stores its data in %LOCALAPPDATA%/ZcodeGateway, and this item opens the wrong place. Open the folder that holds the active config instead.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At gui_main.py, line 314:

<comment>"Open data folder" opens the exe folder, not the data folder. When the exe folder is read-only the gateway stores its data in `%LOCALAPPDATA%/ZcodeGateway`, and this item opens the wrong place. Open the folder that holds the active config instead.</comment>

<file context>
@@ -244,6 +258,86 @@ def _offer_webview2_or_browser(url: str) -> bool:
+        elif command == CMD_LOG:
+            _open_path(_log_file())
+        elif command == CMD_FOLDER:
+            _open_path(_exe_dir())
+        elif command == CMD_QUIT:
+            _quit_from_tray(window_ref, quitting)
</file context>

elif command == CMD_QUIT:
_quit_from_tray(window_ref, quitting)

icon = tray_icon.TrayIcon(
tooltip=f"Zcode Gateway - {url}",
menu=TRAY_MENU,
on_activate=open_dashboard,
on_command=run_command,
icon_path=tray_icon.asset_path("assets", "zcode.ico"))
if not icon.start():
print("[tray] notification-area icon unavailable", file=sys.stderr, flush=True)
return None
return icon


def _watch_gateway(icon, quitting: threading.Event) -> None:
"""Turn the icon into an alarm when the gateway thread dies."""
_server_failed.wait()
if quitting.is_set() or not icon.alive:
return
icon.set_tooltip("Zcode Gateway - gateway stopped")
icon.notify("Gateway stopped",
"The gateway exited. Open the log, then restart Zcode Gateway.",
warning=True)


def main() -> None:
global _server, _server_error
_server = None
Expand All @@ -253,6 +347,10 @@ def main() -> None:
import argparse
parser = argparse.ArgumentParser(description='Zcode Gateway desktop or headless server')
parser.add_argument('--headless', action='store_true')
parser.add_argument('--tray', action='store_true',
help='start hidden in the notification area')
parser.add_argument('--no-tray', action='store_true',
help='no notification-area icon; closing the window quits')
parser.add_argument('--config')
args = parser.parse_args()
if args.config:
Expand Down Expand Up @@ -315,10 +413,36 @@ def main() -> None:
raise SystemExit(1) from _server_error

import webview
webview.create_window(
quitting = threading.Event()
window_ref: list = [None]
tray_icon = None if args.no_tray else _start_tray(url, quitting, window_ref)
window = webview.create_window(
"Zcode Gateway", url,
width=1280, height=800, min_size=(980, 620),
background_color="#0f1115", text_select=True)
background_color="#0f1115", text_select=True,
hidden=bool(args.tray and tray_icon is not None))
window_ref[0] = window

if tray_icon is not None:
def on_closing():
# if the tray thread died there is no icon to restore from, so
# hiding here would strand an invisible, unclosable app
if quitting.is_set() or not tray_icon.alive:
return True
window.hide()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: This handler also runs when Windows logs off or shuts down. Hiding the window and returning False may veto the OS session end while the gateway is running. The handler needs to detect session end and allow the close, for example by setting quitting on WM_QUERYENDSESSION in the tray window procedure. The tray thread can then avoid the veto.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At gui_main.py, line 432:

<comment>This handler also runs when Windows logs off or shuts down. Hiding the window and returning False may veto the OS session end while the gateway is running. The handler needs to detect session end and allow the close, for example by setting `quitting` on WM_QUERYENDSESSION in the tray window procedure. The tray thread can then avoid the veto.</comment>

<file context>
@@ -315,10 +413,36 @@ def main() -> None:
+            # hiding here would strand an invisible, unclosable app
+            if quitting.is_set() or not tray_icon.alive:
+                return True
+            window.hide()
+            tray_icon.notify(
+                "Zcode Gateway is still running",
</file context>

tray_icon.notify(
"Zcode Gateway is still running",
"The dashboard is in the notification area. Right-click the "
"icon to reopen it or quit.")
return False

window.events.closing += on_closing
threading.Thread(target=_watch_gateway, args=(tray_icon, quitting),
name="tray-watchdog", daemon=True).start()
if args.tray:
tray_icon.notify("Zcode Gateway is running",
f"The dashboard is in the notification area ({url}).")

webview.start(gui="edgechromium")

# The window closed. edgechromium/pythonnet leave non-daemon threads that
Expand All @@ -328,6 +452,8 @@ def main() -> None:
# Before the hard exit, stop the generator's workers — os._exit skips
# atexit and the FastAPI lifespan, and spawned Chromium children would
# otherwise be orphaned on the machine.
if tray_icon is not None:
tray_icon.stop()
_shutdown_generator()
os._exit(0)

Expand Down
71 changes: 71 additions & 0 deletions scripts/accounts/backfill_device_mids.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""Give every account snapshot its own stable device_mid.

Dry run by default. Only accounts that share a mid with another account (or
have none) are touched; an account whose mid is already unique is left alone.
The new mid is `account_device_mid(account_id)`, the same derivation the
generator uses, so both sides agree after migration.
"""
import argparse
import sys
from collections import Counter
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from gui_main import _bootstrap_config
from zcode_gateway.accounts_dir import parse_snapshot, snapshot_transaction, write_snapshot
from zcode_gateway.config import load_config
from zcode_gateway.zcode_device import account_device_mid


def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument('directory', nargs='?',
help='accounts folder (default: the configured accounts.dir)')
parser.add_argument('--config')
parser.add_argument('--apply', action='store_true',
help='rewrite the files (default: dry run)')
args = parser.parse_args()
if args.directory:
directory = Path(args.directory)
else:
directory = Path(load_config(args.config or _bootstrap_config()).accounts.dir)
if not directory.is_dir():
print(f"accounts folder not found: {directory}")
return 1

with snapshot_transaction(directory) as folder:
rows = []
for path in sorted(folder.iterdir()):
if path.suffix.casefold() != '.txt' or not path.is_file() or path.is_symlink():
continue
try:
fields = parse_snapshot(path)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: parse_snapshot returns {} on read or decode errors instead of raising, so this except never fires. An unreadable snapshot (for example non-UTF-8 bytes) is treated as having no device_mid and gets overwritten with only that field, destroying its credentials under --apply. Skip any snapshot that parses to an empty dict.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At scripts/accounts/backfill_device_mids.py, line 42:

<comment>`parse_snapshot` returns `{}` on read or decode errors instead of raising, so this `except` never fires. An unreadable snapshot (for example non-UTF-8 bytes) is treated as having no `device_mid` and gets overwritten with only that field, destroying its credentials under `--apply`. Skip any snapshot that parses to an empty dict.</comment>

<file context>
@@ -0,0 +1,71 @@
+            if path.suffix.casefold() != '.txt' or not path.is_file() or path.is_symlink():
+                continue
+            try:
+                fields = parse_snapshot(path)
+            except Exception:
+                print(f"skipping unreadable snapshot: {path.name}")
</file context>

except Exception:
print(f"skipping unreadable snapshot: {path.name}")
continue
ident = fields.get('account_id') or fields.get('zcode_user_id') or path.stem
rows.append((path, fields, ident, fields.get('device_mid', '').strip()))

shared = Counter(mid for *_, mid in rows if mid)
targets = [row for row in rows if not row[3] or shared[row[3]] > 1]
if not targets:
print(f"every account in {directory} already has a unique device_mid")
return 0
print(f"{'Rewriting' if args.apply else 'Would rewrite'} "
f"{len(targets)} of {len(rows)} account(s) in {directory}")
for path, fields, ident, old in targets:
new = account_device_mid(ident)
print(f"{fields.get('email') or ident} -> {old or '(none)'} -> {new}")
if not args.apply or new == old:
continue
fields['device_mid'] = new
write_snapshot(path, fields)

if not args.apply:
print("Dry run: nothing written. Back up the accounts folder, "
"then re-run with --apply.")
return 0


if __name__ == '__main__':
raise SystemExit(main())
18 changes: 2 additions & 16 deletions scripts/accounts/import_account.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
"""Import a ZCode credentials file or the user's MITM dataset into this install."""
import argparse
import json
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from gui_main import _bootstrap_config
from zcode_gateway.accounts_dir import parse_snapshot, write_snapshot
from zcode_gateway.config import load_config
from zcode_gateway.zcode_accounts import import_credentials

Expand All @@ -18,21 +16,9 @@ def main():
args = parser.parse_args()
cfg = load_config(args.config or _bootstrap_config())
source = Path(args.source)
dataset = source if source.is_dir() else None
if dataset:
source = dataset / 'data' / 'tokens.json'
if source.is_dir():

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The dataset path no longer reads the captured x-device-mid from captures/model-api. For a single-account MITM import without data/telemetry-state.json, the account now gets a derived uuid5 instead of the desktop's real mid. Either keep the captured mid as a fallback for single-account datasets, or call out this behavior change in the PR description.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At scripts/accounts/import_account.py, line 19:

<comment>The dataset path no longer reads the captured `x-device-mid` from `captures/model-api`. For a single-account MITM import without `data/telemetry-state.json`, the account now gets a derived uuid5 instead of the desktop's real mid. Either keep the captured mid as a fallback for single-account datasets, or call out this behavior change in the PR description.</comment>

<file context>
@@ -18,21 +16,9 @@ def main():
-    dataset = source if source.is_dir() else None
-    if dataset:
-        source = dataset / 'data' / 'tokens.json'
+    if source.is_dir():
+        source = source / 'data' / 'tokens.json'
     result = import_credentials(source, cfg.accounts.dir)
</file context>

source = source / 'data' / 'tokens.json'
result = import_credentials(source, cfg.accounts.dir)
if dataset:
flows = sorted((dataset / 'captures' / 'model-api').glob('*.json'))
if flows:
flow = json.loads(flows[-1].read_text(encoding='utf-8'))
mid = flow.get('request', {}).get('headers', {}).get('x-device-mid')
if mid:
for name in result['files']:
path = Path(cfg.accounts.dir) / name
fields = parse_snapshot(path)
fields['device_mid'] = mid
write_snapshot(path, fields)
print(f"Imported {result['written']} account(s) into {cfg.accounts.dir}. Reload pool to activate.")
return 0 if result['written'] else 1

Expand Down
2 changes: 2 additions & 0 deletions scripts/build/windows.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,8 @@ $buildArgs = @(
# so PyInstaller cannot see them
"--hidden-import", "zcode_gateway.generator",
"--hidden-import", "zcode_gateway.accounts_dir_bridge",
# the desktop shell imports the notification-area module inside main()
"--hidden-import", "zcode_gateway.tray",
# ship the example config, the app icon assets, the dashboard page, the
# Cloudflare mail-worker template, and the bundled generator scripts
"--add-data", "$(Join-Path $Here 'config.example.yaml');.",
Expand Down
Loading