Skip to content

fix(review): 28 verified bugs across gateway, pool, generator and GUI - #2

Open
mahyartdb wants to merge 5 commits into
B3hnamR:masterfrom
mahyartdb:fix/review-bugs
Open

mahyartdb wants to merge 5 commits into
B3hnamR:masterfrom
mahyartdb:fix/review-bugs

Conversation

@mahyartdb

@mahyartdb mahyartdb commented Nov 15, 2026 •

Copy link
Copy Markdown

fix(review): 28 verified bugs across gateway, pool, generator and GUI

A full-codebase review found 28 bugs that the test suite did not
catch. This PR fixes all of them, each with a regression test that
failed before the change and passes after.

High

  • One U+2028/U+2029/U+0085 character in a model reply killed the whole
    request: SSE frames were split with str.splitlines(), which also
    breaks on those separators that ensure_ascii=False JSON carries raw
    (upstream.py, translate_anthropic.py).
  • Missing ddddocr defeated the entire auto captcha strategy: the lazy
    OCR factory raised RuntimeError instead of returning None, so all 15
    attempts failed with a misleading log (captcha_solver.py).

Pool / accounts

  • cool()/kill_after_strikes() downgraded quota-drained (EXHAUSTED)
    accounts to COOLING, putting them back in rotation after the
    cooldown (pool.py).
  • upsert/enable/apply_credentials(reset=True) never reset
    quota_strikes, so an account that recovered from quota exhaustion
    re-retired on its first rejection with 3 banked strikes (pool.py,
    tokens.py); upsert also force-flipped live state to READY against
    its own docstring - re-add/login/import flows now revive explicitly
    via enable() (api_admin.py, api_dash.py).
  • The edge-block notification callback fired per blocked response
    instead of once per block episode (breaker.py).

API / service

  • /health returned 500 (hmac TypeError) on a non-ASCII update header;
    after any in-app update the nonce persists for the process lifetime,
    so internet scanners kept hitting it (api_health.py).
  • generator/locate left the old manager's ClaimScheduler, captcha-mint
    thread and proxy checker running; a second scheduler then fired
    duplicate daily claims (api_dash.py).
  • Worker/claim stop and proxy-checker endpoints ran subprocess kills
    (up to 5s) and multi-MB pool.json parsing directly on the event
    loop, freezing all traffic including live SSE streams
    (api_admin.py, api_dash.py); _check_update_idle also iterated
    manager dicts without the lock (500 on a rare race).
  • The request body was deep-copied on the event loop for every
    recorded request even when JSONL capture was disabled
    (service.py).
  • proxy auto-verify 500'd on a non-numeric interval_min instead of
    400 (api_admin.py); a non-ASCII comment in proxies.txt aborted the
    whole Auto Generate preflight (generator.py).

Relays

  • The relay retry re-sent through the relay that had just failed,
    hammering the same dead relay for every attempt while never trying
    the others (upstream.py).
  • An unreadable relays.json was cached as authoritative defaults, so
    the next save permanently wiped the user's relays
    (relay_manager.py); update_options(models="GLM-5.3") exploded the
    string into single characters and silently routed nothing.

Generator

  • Telemetry and exported snapshots carried one shared hardcoded
    x-device-mid and a hardcoded Asia/Tehran timezone while headers
    claimed the exit IP's zone - the cross-account correlation signals
    risk control clusters on (invite_claim.py, export_starter.py,
    plan_check.py, claim500.py).
  • One flaky account aborted the whole recheck/export batch
    (recheck_plans.py, export_starter.py); a portless ZAI_PROXY became
    socks5://host:None and crashed the Playwright launch
    (invite_claim.py); leading-zero octets (0177.0.0.1 = 127.0.0.1
    octal) bypassed the loopback SSRF guard (proxy_parse.py).

GUI / desktop

  • Clicking Stop during a pending Save & Restart was silently
    overridden and the gateway restarted itself; Stop during the startup
    import window was a no-op and the server bound anyway; wait_ready()
    could health-check a foreign process on the default port (gui.py).
  • config.yaml - which holds the per-install admin/client keys - was
    written non-atomically from four GUI paths; a crash mid-write
    truncated it (gui.py).
  • The live smoke script closed the store under a pending usage-record
    write (scripts/smoke/live.py).

Verification

  • 1364 passed / 147 skipped / 0 failed (full suite, clean venv)
  • ruff E9,F63,F7,F82,F811,F841: clean
  • captcha-mint sidecar (bun): 30/30
  • Known pre-existing flake test_overload_rotates_accounts_after_wait_
    without_cooling reproduces on the unmodified tree and passes here;
    unrelated to these changes.

Every fix has a regression test that was observed failing before and
passing after; 5 new test files + extensions to test_relays.py.


Summary by cubic

A full-codebase review found 28 bugs that the test suite did not catch. This PR fixes all of them, each with a regression test that failed before the change and passes after.

High-impact fixes

  • SSE frames now split on real line terminators, so a stray U+2028/U+2029/U+0085 in a reply no longer fails the request.
  • Missing ddddocr degrades captcha solving instead of aborting the whole auto captcha strategy.
  • Quota-drained (EXHAUSTED) accounts stay retired; fresh credentials get a clean strike budget.
  • Relay retries no longer hammer a just-failed relay, and an unreadable relays.json can no longer be overwritten by defaults.
  • Subprocess kills, pool parsing, and request-body deep copies moved off the event loop, so live SSE traffic is no longer frozen.
  • All GUI config.yaml writes are atomic; a user Stop now wins over a pending restart.
  • Generator telemetry uses per-account device IDs and the exit IP's timezone instead of shared hardcoded values.

Verification

  • 1364 passed / 147 skipped / 0 failed; ruff and the captcha-mint sidecar are clean.

Written for commit 2d707eb. Summary will update on new commits.

View guided diff

captcha_solver: the lazy ddddocr factory no longer escapes calculate()
with RuntimeError when ddddocr is missing (the documented _need_ocr
contract: return None and fall through to the cv2/ai paths).

invite_claim/export_starter: telemetry and exported snapshots carry a
per-account device mid instead of one shared hardcoded x-device-mid,
the exact cross-account correlation signal risk control clusters on.

plan_check/invite_claim/claim500: client_timezone() replaces the
hardcoded Asia/Tehran so header and event-body timezone always match
the exit IP.

recheck_plans/export_starter: one flaky account no longer aborts the
whole batch; the failure is recorded per account and the run continues.

invite_claim: a portless ZAI_PROXY no longer becomes
socks5://host:None and crashes the Playwright launch (same guard as
main.pw_proxy()).

proxy_parse: leading-zero octets (0177.0.0.1 == 127.0.0.1 octal) are
rejected, closing the loopback bypass of valid_endpoint.
pool: cool() and kill_after_strikes() no longer downgrade an EXHAUSTED
(quota-drained) account to COOLING, which put it back in rotation once
the cooldown lapsed; EXHAUSTED is sticky like DEAD.

pool/tokens: upsert, enable and apply_credentials(reset=True) clear
quota_strikes together with auth_strikes - a fresh credential used to
re-retire on its first rejection with 3 strikes already banked (the
same bug restore() already fixed and documented).

pool: upsert preserves live state as its docstring always promised;
callers that re-add or re-login an account revive it explicitly via
enable() (api_admin/api_dash).

breaker: the edge-block callback fires once per block episode, not on
every blocked response (stale-episode expiry starts a new episode).

captcha_tickets: take() hands out one ticket and keeps the remaining
fresh ones instead of clearing the whole pool of paid mints.

notify: the dedupe scan no longer breaks early on a stale entry whose
ts was bumped in place - a fresh candidate behind it is found.
api_health: the update-nonce probe uses the same non-ASCII-safe compare
as bearer tokens; a malformed X-AutoZCoder-Update header (common from
internet scanners, and the nonce env var persists after an in-app
update) returned 500 + traceback instead of 404.

api_dash: generator/locate fully tears down the previous manager -
stop_all() left the ClaimScheduler, captcha-mint thread and proxy
checker running, so the replacement manager ran beside the old one and
fired duplicate daily claims.

api_admin/api_dash: worker/claim stop and proxy-checker status/run
endpoints run their blocking subprocess-kill and multi-file parsing in
asyncio.to_thread; they used to freeze the event loop - and every live
SSE stream - for up to 5s per kill.

api_dash: _check_update_idle snapshots workers/claims under the manager
lock; iterating them while a generator thread mutates the dicts raised
"dictionary changed size during iteration" (500).

api_admin: proxy auto-verify validates interval_min (400 instead of an
unhandled ValueError 500).

generator: _pool_has_candidates reads with encoding="utf-8",
errors="ignore"; a non-ASCII comment in proxies.txt used to abort the
whole Auto Generate preflight with UnicodeDecodeError.

service: when JSONL capture is disabled the request body is no longer
deep-copied on the event loop per request (multi-hundred-KB stall);
the usage row is written either way.
upstream: SSE frames are split on real line terminators only. The old
str.splitlines() also broke on U+2028/U+2029/U+0085, which JSON written
with ensure_ascii=False carries raw inside string values - one such
character in a model reply cut the data line mid-string and failed the
request (500 non-streaming, mid-stream 502 invalid_stream). The same
fix applies to the error/content scanners in translate_anthropic.

upstream: a relay that already failed within one request is not sent to
a second time; the rotation used to re-pick the same dead relay for
every remaining attempt (each paying the pacing gap and a connect
timeout) while never trying the other relays. Rotation to untried
relays and the direct fallback are unchanged.

relay_manager: an unreadable relays.json is served as defaults for that
read only and never cached as authoritative - the next save used to
write defaults over the user's configured relays permanently.

relay_manager: update_options(models="GLM-5.3") normalizes a single
model string to a one-element list; it used to explode into single
characters and silently route nothing through the relay.
gui: stop_everything() cancels a restart that is still waiting for the
old server to release the port (generation-tagged callbacks); Stop
used to be silently overridden and the gateway came back up on its own.

gui: all four config.yaml writes go through one atomic
temp-file + os.replace helper - the file holds the per-install admin
and client keys, and a crash mid-write used to truncate it.

gui: stop() during the server thread's cold imports now prevents the
bind entirely via a stop flag checked before create_app/serve; the
server used to come up after the UI had already reported "stopped".

gui: wait_ready() refuses to probe until the gateway thread has
published the resolved host/port, so a foreign process answering
/health on the default port can no longer pass readiness.

scripts/smoke/live: ChatService.aclose() is awaited before the store
closes, so the usage record no longer races the executor write and gets
silently dropped.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

18 issues found across 28 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. 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. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="zcode_gateway/relay_manager.py">

<violation number="1" location="zcode_gateway/relay_manager.py:140">
P3: This warning fires on every `get_settings()` call while the file stays unreadable, since failures are no longer cached. `pick_relay_for_model` runs per request, so a persistently bad file floods the log. Log once per distinct failure, or downgrade to debug after the first warning.</violation>

<violation number="2" location="zcode_gateway/relay_manager.py:142">
P1: The new fallback still lets writes destroy relays.json. `update_options`, `add_relay` and `delete_relays` read defaults on a failed read and then `save_settings()` them over the file, which is the data loss the comment says this prevents. Make write paths fail or back up the file instead of overwriting after a failed read, and make the test fail the write-path read too.</violation>
</file>

<file name="generator/recheck_plans.py">

<violation number="1" location="generator/recheck_plans.py:129">
P2: A failed `startplan.txt` append is caught by the new outer `except`, so a confirmed Start Plan account is recorded as an error and dropped from `startplan.txt`. Guard only the append so a write failure is logged without replacing the successful record.</violation>
</file>

<file name="zcode_gateway/api_admin.py">

<violation number="1" location="zcode_gateway/api_admin.py:637">
P2: Moving `remove_claim` to a worker thread makes it race with `clear_finished_claims`, which runs on the event loop and iterates `self.claims` under `self._lock`. `remove_claim` mutates `self.claims` without that lock, so a concurrent remove and clear can raise `RuntimeError` and return a 500. Take `self._lock` around the pop in `remove_claim`.</violation>

<violation number="2" location="zcode_gateway/api_admin.py:721">
P3: `int(interval)` silently accepts and truncates fractional JSON values such as `1.5`, despite this endpoint requiring whole minutes. Reject non-integral floats and booleans before converting the value.</violation>

<violation number="3" location="zcode_gateway/api_admin.py:721">
P2: The new integer validation has no upper bound. A very large `interval_min` makes the background auto-verify thread raise `OverflowError` on its next wait and exit, leaving auto-verify reported as on with no loop running. Clamp the value to a sane maximum here, for example 1440 minutes.</violation>
</file>

<file name="tests/test_generator_bugfixes.py">

<violation number="1" location="tests/test_generator_bugfixes.py:29">
P2: `_module` swallows every ImportError, so a broken import in `invite_claim` or its dependencies makes these regression tests skip silently. Only skip when the top-level module itself is missing, and let other import failures raise.</violation>
</file>

<file name="generator/proxy_parse.py">

<violation number="1" location="generator/proxy_parse.py:83">
P2: The new leading-zero check is ASCII-only, so fullwidth digits still bypass the loopback and link-local guards. `PROXY_RE` matches Unicode `\d`, `int()` accepts those digits, and `getaddrinfo` normalizes them to ASCII. Reject non-ASCII hosts before splitting so `valid_endpoint` only accepts plain dotted quads.</violation>
</file>

<file name="zcode_gateway/api_dash.py">

<violation number="1" location="zcode_gateway/api_dash.py:483">
P2: `enable()` runs before the balance check, so a re-login of an exhausted account makes it READY and routable during the network call. Settle state only after `check_account`, or keep the parked state until the check has run.</violation>

<violation number="2" location="zcode_gateway/api_dash.py:713">
P2: `with lock:` blocks the event loop while a generator thread holds `manager._lock`. That lock is held during `_pool_health` file I/O and claim setup. Take the snapshot in a worker thread, for example `await asyncio.to_thread(...)` around the locked copy, instead of acquiring the threading lock on the loop.</violation>
</file>

<file name="generator/export_starter.py">

<violation number="1" location="generator/export_starter.py:131">
P2: Derive the device id from `chat_token`, not `zjwt`. `zjwt` is re-minted on every run, so a re-export gives the account a new `device_mid`. The `or DEVICE_MID` fallback is also unreachable, since `per_account_device_mid` never returns an empty string.</violation>

<violation number="2" location="generator/export_starter.py:146">
P3: The exit status ignores `failed`, so a run where every account errors still exits 0. Exit non-zero when `failed` is set so callers and pipelines can detect the failure.</violation>
</file>

<file name="generator/invite_claim.py">

<violation number="1" location="generator/invite_claim.py:602">
P2: `device_login` uses a chat-token device ID for OAuth but `report_login_device` now uses a zcode-JWT device ID, so one login reports two device IDs. Pass the OAuth `mid` as `device_mid=mid` to `report_login_device`.</violation>

<violation number="2" location="generator/invite_claim.py:878">
P2: Rejecting a portless proxy launches Chromium directly but still fingerprints it with that proxy URL. Pass only the validated `_pd` proxy URL to `make_identity`, or pass `None` whenever `_pw_proxy` rejects the configured proxy.</violation>

<violation number="3" location="generator/invite_claim.py:883">
P1: When a proxy is configured but has no host:port, the browser claim now launches on the real IP instead of failing. Raise an error here so the claim aborts rather than leaking the home IP.</violation>
</file>

<file name="zcode_gateway/gui.py">

<violation number="1" location="zcode_gateway/gui.py:468">
P1: `ServerController.stop()` can miss a server created after this final stop check. If Stop lands in that window, `run()` still binds while the UI reports the gateway stopped; assign the server before a final check and set `should_exit` when stopping.</violation>
</file>

<file name="zcode_gateway/upstream.py">

<violation number="1" location="zcode_gateway/upstream.py:380">
P2: When every relay is cooling down, `_pick_relay` falls back to the full list, so a `random` pick can return a relay that already failed in this call. The new `break` then ends rotation and the untried relays are never attempted. Consider filtering `tried_relay_urls` out of the candidates (or retrying the pick) instead of exiting the loop.</violation>
</file>

<file name="generator/plan_check.py">

<violation number="1" location="generator/plan_check.py:499">
P2: `client_timezone()` caches one timezone for the whole generator process, so later accounts can report the first account’s proxy timezone after `set_proxy` rotates exits. Key the cache by the active proxy/override or resolve the timezone per account.</violation>
</file>

Reply to a comment to ask cubic a question or push back. It learns from your replies.

View guided diff | Re-trigger cubic

# would write them over the user's relays for good.
log.warning("relays.json could not be read (%s) — serving "
"defaults for this read only", exc)
return self._default_settings()

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: The new fallback still lets writes destroy relays.json. update_options, add_relay and delete_relays read defaults on a failed read and then save_settings() them over the file, which is the data loss the comment says this prevents. Make write paths fail or back up the file instead of overwriting after a failed read, and make the test fail the write-path read too.

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 zcode_gateway/relay_manager.py, line 142:

<comment>The new fallback still lets writes destroy relays.json. `update_options`, `add_relay` and `delete_relays` read defaults on a failed read and then `save_settings()` them over the file, which is the data loss the comment says this prevents. Make write paths fail or back up the file instead of overwriting after a failed read, and make the test fail the write-path read too.</comment>

<file context>
@@ -131,13 +134,17 @@ def get_settings(self) -> dict[str, Any]:
+                    # would write them over the user's relays for good.
+                    log.warning("relays.json could not be read (%s) — serving "
+                                "defaults for this read only", exc)
+                    return self._default_settings()
+                if isinstance(data, dict):
+                    settings = self._default_settings()
</file context>

Comment thread generator/invite_claim.py
Comment on lines +883 to +884
elif _px and _px.get('https'):
log(' invite: proxy has no host:port — launching direct')

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: When a proxy is configured but has no host:port, the browser claim now launches on the real IP instead of failing. Raise an error here so the claim aborts rather than leaking the home IP.

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/invite_claim.py, line 883:

<comment>When a proxy is configured but has no host:port, the browser claim now launches on the real IP instead of failing. Raise an error here so the claim aborts rather than leaking the home IP.</comment>

<file context>
@@ -848,19 +875,13 @@ def claim_invite(chat_token: str, invite_code: str = 'MT9GNDQ8', log=print,
             launch_kwargs['proxy'] = _pd
         elif force_direct:
             log('  invite: direct mode — claiming on the real IP')
+        elif _px and _px.get('https'):
+            log('  invite: proxy has no host:port — launching direct')
 
</file context>
Suggested change
elif _px and _px.get('https'):
log(' invite: proxy has no host:port — launching direct')
elif _px and _px.get('https'):
raise RuntimeError('invite: proxy has no host:port — refusing to claim on the real IP')

Comment thread zcode_gateway/gui.py
from zcode_gateway.app import create_app
from zcode_gateway.config import load_config

if self._stop_requested.is_set():

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: ServerController.stop() can miss a server created after this final stop check. If Stop lands in that window, run() still binds while the UI reports the gateway stopped; assign the server before a final check and set should_exit when stopping.

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 zcode_gateway/gui.py, line 468:

<comment>`ServerController.stop()` can miss a server created after this final stop check. If Stop lands in that window, `run()` still binds while the UI reports the gateway stopped; assign the server before a final check and set `should_exit` when stopping.</comment>

<file context>
@@ -439,15 +456,21 @@ def start(self, cfg_path: Path | None) -> None:
                 from zcode_gateway.app import create_app
                 from zcode_gateway.config import load_config
 
+                if self._stop_requested.is_set():
+                    return
+
</file context>

Comment on lines +129 to +131
if has_start:
with open(startplan_path, 'a', encoding='utf-8') as f:
f.write(f"{email}:{_password}:{token}\n")

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: A failed startplan.txt append is caught by the new outer except, so a confirmed Start Plan account is recorded as an error and dropped from startplan.txt. Guard only the append so a write failure is logged without replacing the successful record.

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/recheck_plans.py, line 129:

<comment>A failed `startplan.txt` append is caught by the new outer `except`, so a confirmed Start Plan account is recorded as an error and dropped from `startplan.txt`. Guard only the append so a write failure is logged without replacing the successful record.</comment>

<file context>
@@ -96,42 +96,51 @@ def main():
+                          'campaign': plan.get('campaign'),
+                          'entitlements': plan.get('entitlements'),
+                          'ts': int(time.time())}
+                if has_start:
+                    with open(startplan_path, 'a', encoding='utf-8') as f:
+                        f.write(f"{email}:{_password}:{token}\n")
</file context>
Suggested change
if has_start:
with open(startplan_path, 'a', encoding='utf-8') as f:
f.write(f"{email}:{_password}:{token}\n")
if has_start:
try:
with open(startplan_path, 'a', encoding='utf-8') as f:
f.write(f"{email}:{_password}:{token}\n")
except OSError as e:
log(f' startplan write failed ({e})')

Comment on lines +29 to +30
except ImportError:
return None

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: _module swallows every ImportError, so a broken import in invite_claim or its dependencies makes these regression tests skip silently. Only skip when the top-level module itself is missing, and let other import failures raise.

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 tests/test_generator_bugfixes.py, line 29:

<comment>`_module` swallows every ImportError, so a broken import in `invite_claim` or its dependencies makes these regression tests skip silently. Only skip when the top-level module itself is missing, and let other import failures raise.</comment>

<file context>
@@ -0,0 +1,334 @@
+def _module(name):
+    try:
+        return __import__(name)
+    except ImportError:
+        return None
+
</file context>
Suggested change
except ImportError:
return None
except ModuleNotFoundError as e:
if e.name != name:
raise
return None

Comment thread generator/invite_claim.py
h['authorization'] = 'Bearer ' + zjwt
h['x-client-timezone'] = client_timezone()
if mid:
h['x-device-mid'] = 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: device_login uses a chat-token device ID for OAuth but report_login_device now uses a zcode-JWT device ID, so one login reports two device IDs. Pass the OAuth mid as device_mid=mid to report_login_device.

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/invite_claim.py, line 602:

<comment>`device_login` uses a chat-token device ID for OAuth but `report_login_device` now uses a zcode-JWT device ID, so one login reports two device IDs. Pass the OAuth `mid` as `device_mid=mid` to `report_login_device`.</comment>

<file context>
@@ -577,12 +597,15 @@ def report_login_device(zjwt: str, user_id: str = None, device_mid: str = None,
     h['authorization'] = 'Bearer ' + zjwt
+    h['x-client-timezone'] = client_timezone()
+    if mid:
+        h['x-device-mid'] = mid
     endpoint = 'https://zcode.z.ai/api/v1/event/report'
 
</file context>

Comment thread generator/invite_claim.py
if _u.username:
_pd['username'] = _u.username
_pd['password'] = _u.password or ''
_pd = _pw_proxy((_px or {}).get('https'))

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: Rejecting a portless proxy launches Chromium directly but still fingerprints it with that proxy URL. Pass only the validated _pd proxy URL to make_identity, or pass None whenever _pw_proxy rejects the configured proxy.

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/invite_claim.py, line 878:

<comment>Rejecting a portless proxy launches Chromium directly but still fingerprints it with that proxy URL. Pass only the validated `_pd` proxy URL to `make_identity`, or pass `None` whenever `_pw_proxy` rejects the configured proxy.</comment>

<file context>
@@ -848,19 +875,13 @@ def claim_invite(chat_token: str, invite_code: str = 'MT9GNDQ8', log=print,
-            if _u.username:
-                _pd['username'] = _u.username
-                _pd['password'] = _u.password or ''
+        _pd = _pw_proxy((_px or {}).get('https'))
+        if _pd:
             launch_kwargs['proxy'] = _pd
</file context>

except Exception as exc:
# Never cache defaults for an unreadable file: a later save
# would write them over the user's relays for good.
log.warning("relays.json could not be read (%s) — serving "

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: This warning fires on every get_settings() call while the file stays unreadable, since failures are no longer cached. pick_relay_for_model runs per request, so a persistently bad file floods the log. Log once per distinct failure, or downgrade to debug after the first warning.

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 zcode_gateway/relay_manager.py, line 140:

<comment>This warning fires on every `get_settings()` call while the file stays unreadable, since failures are no longer cached. `pick_relay_for_model` runs per request, so a persistently bad file floods the log. Log once per distinct failure, or downgrade to debug after the first warning.</comment>

<file context>
@@ -131,13 +134,17 @@ def get_settings(self) -> dict[str, Any]:
+                except Exception as exc:
+                    # Never cache defaults for an unreadable file: a later save
+                    # would write them over the user's relays for good.
+                    log.warning("relays.json could not be read (%s) — serving "
+                                "defaults for this read only", exc)
+                    return self._default_settings()
</file context>

interval = body.get("interval_min")
if interval not in (None, ""):
try:
interval = int(interval)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: int(interval) silently accepts and truncates fractional JSON values such as 1.5, despite this endpoint requiring whole minutes. Reject non-integral floats and booleans before converting the value.

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 zcode_gateway/api_admin.py, line 721:

<comment>`int(interval)` silently accepts and truncates fractional JSON values such as `1.5`, despite this endpoint requiring whole minutes. Reject non-integral floats and booleans before converting the value.</comment>

<file context>
@@ -711,6 +716,15 @@ async def proxy_auto_verify(request: Request, body: dict = Body(...),
     interval = body.get("interval_min")
+    if interval not in (None, ""):
+        try:
+            interval = int(interval)
+        except (TypeError, ValueError):
+            raise HTTPException(
</file context>
Suggested change
interval = int(interval)
if isinstance(interval, bool) or (isinstance(interval, float) and not interval.is_integer()):
raise ValueError
interval = int(interval)

write_snapshot(dest, fields)
exported += 1
print(f" -> wrote {dest}")
except Exception as e:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The exit status ignores failed, so a run where every account errors still exits 0. Exit non-zero when failed is set so callers and pipelines can detect the failure.

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/export_starter.py, line 146:

<comment>The exit status ignores `failed`, so a run where every account errors still exits 0. Exit non-zero when `failed` is set so callers and pipelines can detect the failure.</comment>

<file context>
@@ -99,48 +100,54 @@ def main():
+            write_snapshot(dest, fields)
+            exported += 1
+            print(f"    -> wrote {dest}")
+        except Exception as e:
+            failed += 1
+            print(f"    failed ({type(e).__name__}: {e}) — skip")
</file context>

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants