Skip to content
Open
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
18 changes: 18 additions & 0 deletions docs/releases/2.1.2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# AutoZCoder 2.1.2

A Windows desktop startup reliability and diagnostics patch.

## Desktop startup

- Gateway readiness checks now bypass inherited HTTP proxy settings when connecting to the gateway's own listener. A system proxy can no longer intercept the launcher's local dashboard health probe and cause the launcher to shut down a healthy server after the 30-second timeout.
- The readiness loop records the target URL, probe count, last HTTP/connection error, server state, and worker failure state in the diagnostic log.
- Exceptions escaping the gateway background thread are now logged with full tracebacks. Fatal launcher exceptions are also recorded, including `SystemExit` paths that the previous `except Exception` handler missed.
- The same direct-connection helper is used for existing-instance checks and local generator shutdown requests.

## Diagnostics

The desktop log remains at `%LOCALAPPDATA%\ZcodeGateway\zcode-gateway.log`. Startup failures now include the underlying exception instead of only showing a generic message.

## Upgrading

Replace the old executable with the 2.1.2 release. Existing configuration and account data are preserved.
18 changes: 18 additions & 0 deletions docs/releases/2.1.3.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# AutoZCoder 2.1.3

A maintenance release that finalizes the Windows desktop startup reliability fixes introduced in 2.1.2 and aligns the release validation suite.

## Desktop startup

- Keep gateway readiness checks on a direct connection to the local listener, bypassing inherited system HTTP proxy settings.
- Preserve scoped TLS certificate and hostname verification for configured HTTPS gateway origins.
- Improve startup diagnostics with readiness probe details and full background-worker exception tracebacks.

## Test and release reliability

- Update TLS audit tests to mock the desktop launcher's direct gateway URL opener, matching the current implementation.
- Validate the application version, Windows executable metadata, and release notes against the selected version tag.

## Upgrade

Replace the previous executable with the 2.1.3 build. Existing configuration and account data are preserved.
87 changes: 68 additions & 19 deletions gui_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from __future__ import annotations

import ctypes
import logging
import os
import secrets
import ssl
Expand Down Expand Up @@ -66,20 +67,33 @@ def _notify(message: str) -> None:
_server = None
_server_failed = threading.Event()
_server_error: BaseException | None = None
_desktop_log = logging.getLogger("zcode_gateway.desktop")


def _fix_streams() -> None:
"""A --windowed frozen exe has no console; sys.stdout/err may be None.
pywebview and the app log through these — give them a real file."""
"""Give frozen/windowed builds durable stdout/stderr before any startup work."""
log_dir = os.path.join(os.environ.get("LOCALAPPDATA", "."), "ZcodeGateway")
os.makedirs(log_dir, exist_ok=True)
path = os.path.join(log_dir, "zcode-gateway.log")
for name in ("stdout", "stderr"):
try:
f = open(path, "a", encoding="utf-8", buffering=1)
setattr(sys, name, f)
except OSError:
pass
try:
os.makedirs(log_dir, exist_ok=True)
path = os.path.join(log_dir, "zcode-gateway.log")
for name in ("stdout", "stderr"):
try:
setattr(sys, name, open(path, "a", encoding="utf-8", buffering=1))
except OSError:
pass
_desktop_log.info("Desktop launcher starting; diagnostic log: %s", path)
except Exception:
# Logging must never prevent the gateway itself from starting.
pass


def _gateway_urlopen(request, *, timeout: float, context: ssl.SSLContext | None = None):
"""Open our own listener directly; system HTTP proxies must not intercept loopback probes."""
handlers = [urllib.request.ProxyHandler({})]

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: _gateway_urlopen disables proxies for every gateway URL, not only loopback listeners. Preserve the system proxy for non-loopback child_origin values, or remote/corporate deployments can fail readiness and shutdown despite the configured origin being reachable through that 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 gui_main.py, line 92:

<comment>`_gateway_urlopen` disables proxies for every gateway URL, not only loopback listeners. Preserve the system proxy for non-loopback `child_origin` values, or remote/corporate deployments can fail readiness and shutdown despite the configured origin being reachable through that proxy.</comment>

<file context>
@@ -66,20 +67,33 @@ def _notify(message: str) -> None:
+
+def _gateway_urlopen(request, *, timeout: float, context: ssl.SSLContext | None = None):
+    """Open our own listener directly; system HTTP proxies must not intercept loopback probes."""
+    handlers = [urllib.request.ProxyHandler({})]
+    if context is not None:
+        handlers.append(urllib.request.HTTPSHandler(context=context))
</file context>

if context is not None:
handlers.append(urllib.request.HTTPSHandler(context=context))
opener = urllib.request.build_opener(*handlers)
return opener.open(request, timeout=timeout)


def _gateway_context(ca_file: str) -> ssl.SSLContext:
Expand All @@ -97,20 +111,40 @@ def _wait_for(url: str, timeout: float = 30.0, *,
nonce = os.environ.get("ZCODE_GATEWAY_UPDATE_NONCE", "")
if nonce:
url = url.rsplit("/", 1)[0] + "/health"
attempts = 0
last_error: BaseException | None = None
_desktop_log.info("Waiting for gateway readiness: url=%s timeout=%.1fs nonce_check=%s",
url, timeout, bool(nonce))
while time.monotonic() < deadline:
if _server_failed.is_set():
_desktop_log.error("Gateway worker terminated before readiness; error=%r", _server_error)
return False
try:
# A different listener on the configured port is not our server.
if _server is not None and _server.started:
attempts += 1
probe = urllib.request.Request(url, headers={"X-AutoZCoder-Update": nonce}) if nonce else url
with urllib.request.urlopen(probe, timeout=2, context=context) as r:
with _gateway_urlopen(probe, timeout=2, context=context) as r:
if (r.status == 200 and not _server_failed.is_set()
and (not nonce or r.headers.get("X-AutoZCoder-Update") == nonce)):
_desktop_log.info("Gateway readiness confirmed after %d probe(s): HTTP %s",
attempts, r.status)
return True
except Exception:
pass
last_error = RuntimeError(
f"unexpected readiness response: HTTP {r.status}, "
f"nonce_match={not nonce or r.headers.get('X-AutoZCoder-Update') == nonce}")
except Exception as exc:
last_error = exc
if attempts == 1 or attempts % 10 == 0:
_desktop_log.warning("Readiness probe %d failed for %s: %s: %s",
attempts, url, type(exc).__name__, exc)
_server_failed.wait(0.4)
_desktop_log.error(
"Gateway readiness timed out after %.1fs (%d probe(s)); url=%s; "
"server_started=%s; worker_failed=%s; last_error=%s: %s",
timeout, attempts, url, bool(_server is not None and _server.started),
_server_failed.is_set(), type(last_error).__name__ if last_error else "none",
last_error or "no HTTP response received")
return False


Expand Down Expand Up @@ -179,7 +213,13 @@ def _server_worker() -> None:
_server_error = RuntimeError("Gateway stopped")
except BaseException as exc:
_server_error = exc
_desktop_log.error("Gateway server worker crashed: %s: %s",
type(exc).__name__, exc,
exc_info=(type(exc), exc, exc.__traceback__))
finally:
if _server_error is None:
_server_error = RuntimeError("Gateway worker exited unexpectedly")
_desktop_log.error("Gateway server worker exited without an exception")
_server_failed.set()


Expand Down Expand Up @@ -292,7 +332,7 @@ def main() -> None:
# already live — open it in the browser. If it's the old Tkinter build
# (no /dash route) that returns 404, so surface a clear message instead.
try:
with urllib.request.urlopen(url, timeout=3, context=context) as r:
with _gateway_urlopen(url, timeout=3, context=context) as r:
if r.status == 200:
webbrowser.open(url)
return
Expand All @@ -305,10 +345,13 @@ def main() -> None:

threading.Thread(target=_server_worker, daemon=True, name="gateway").start()
browser_fallback = False
_desktop_log.info("Gateway process launched; expected dashboard origin=%s", origin)
if not _wait_for(url, context=context):
if _server is not None:
_server.should_exit = True
_notify("Zcode Gateway could not start. Check the gateway log for details.")
_desktop_log.error("Gateway startup aborted because dashboard readiness was not confirmed; "
"worker_error=%r", _server_error)
_notify("Zcode Gateway could not start. Check the diagnostic log for details.")
raise SystemExit(1) from _server_error
elif not _webview2_available():
# native window impossible on this machine: install prompt + browser
Expand Down Expand Up @@ -361,7 +404,7 @@ def _shutdown_generator() -> None:
data=b"{}", method="POST",
headers={"Authorization": "Bearer " + key,
"Content-Type": "application/json"})
with _ur.urlopen(req, timeout=90, context=_last_gateway_context) as _:
with _gateway_urlopen(req, timeout=90, context=_last_gateway_context) as _:
pass
except Exception:
pass
Expand All @@ -370,7 +413,13 @@ def _shutdown_generator() -> None:
if __name__ == "__main__":
try:
main()
except Exception:
except BaseException as exc:

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 new BaseException handler converts argparse’s normal SystemExit(0) for --help into exit code 1 and labels it fatal. Re-raise SystemExit before the fatal handler.

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

<comment>The new `BaseException` handler converts argparse’s normal `SystemExit(0)` for `--help` into exit code 1 and labels it fatal. Re-raise `SystemExit` before the fatal handler.</comment>

<file context>
@@ -370,7 +413,13 @@ def _shutdown_generator() -> None:
     try:
         main()
-    except Exception:
+    except BaseException as exc:
         import traceback
-        sys.stderr.write(traceback.format_exc()[-1200:] + "\n")
</file context>
Suggested change
except BaseException as exc:
except SystemExit:
raise
except BaseException as exc:

import traceback
sys.stderr.write(traceback.format_exc()[-1200:] + "\n")
raise SystemExit(1)
try:
sys.stderr.write("\n[FATAL] Desktop launcher terminated: "
f"{type(exc).__name__}: {exc}\n")
traceback.print_exception(type(exc), exc, exc.__traceback__, file=sys.stderr)
sys.stderr.flush()
except Exception:
pass
raise SystemExit(1) from exc
8 changes: 4 additions & 4 deletions scripts/packaging/exe_version.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
# PyInstaller --version-file: exe properties (right-click -> Details).
VSVersionInfo(
ffi=FixedFileInfo(
filevers=(2, 1, 1, 0),
prodvers=(2, 1, 1, 0),
filevers=(2, 1, 3, 0),
prodvers=(2, 1, 3, 0),
mask=0x3f,
flags=0x0,
OS=0x40004,
Expand All @@ -17,12 +17,12 @@ VSVersionInfo(
StringTable('040904B0', [
StringStruct('CompanyName', '@B3hnamR'),
StringStruct('FileDescription', 'Zcode Gateway, Coded by @B3hnamR'),
StringStruct('FileVersion', '2.1.1.0'),
StringStruct('FileVersion', '2.1.3.0'),
StringStruct('InternalName', 'ZcodeGateway'),
StringStruct('LegalCopyright', 'Personal tool. Zcode is a trademark of its owner.'),
StringStruct('OriginalFilename', 'ZcodeGateway.exe'),
StringStruct('ProductName', 'Zcode Gateway'),
StringStruct('ProductVersion', '2.1.1.0'),
StringStruct('ProductVersion', '2.1.3.0'),
]),
]),
VarFileInfo([VarStruct('Translation', [1033, 1200])]),
Expand Down
8 changes: 4 additions & 4 deletions tests/test_tls_config_audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def urlopen(url, **kwargs):
calls.append((url, kwargs))
return nullcontext(SimpleNamespace(status=200))

monkeypatch.setattr(gui_main.urllib.request, "urlopen", urlopen)
monkeypatch.setattr(gui_main, "_gateway_urlopen", urlopen)
assert gui_main._wait_for("https://gw.example.test:9443/dash", context=context)
assert calls == [("https://gw.example.test:9443/dash", {"timeout": 2, "context": context})]

Expand All @@ -121,7 +121,7 @@ def urlopen(url, **kwargs):
calls.append(kwargs)
raise ssl.SSLCertVerificationError("dummy hostname mismatch")

monkeypatch.setattr(gui_main.urllib.request, "urlopen", urlopen)
monkeypatch.setattr(gui_main, "_gateway_urlopen", urlopen)
assert not gui_main._wait_for("https://gw.example.test:9443/dash", timeout=1, context=context)
assert calls == [{"timeout": 2, "context": context}]

Expand All @@ -137,7 +137,7 @@ def urlopen(request, **kwargs):
calls.append((request, kwargs))
return nullcontext(SimpleNamespace(status=200))

monkeypatch.setattr(gui_main.urllib.request, "urlopen", urlopen)
monkeypatch.setattr(gui_main, "_gateway_urlopen", urlopen)
gui_main._shutdown_generator()
request, kwargs = calls[0]
assert request.full_url == "https://gw.example.test:9443/admin/dash/generator/shutdown"
Expand Down Expand Up @@ -173,7 +173,7 @@ def ready(url, *, context):
calls.append(("ready", url, context))
return True

monkeypatch.setattr(gui_main.urllib.request, "urlopen", urlopen)
monkeypatch.setattr(gui_main, "_gateway_urlopen", urlopen)
monkeypatch.setattr(gui_main, "_wait_for", ready)
monkeypatch.setattr(gui_main, "_webview2_available", lambda: True)
monkeypatch.setattr(gui_main.threading, "Thread", lambda **kwargs: SimpleNamespace(start=lambda: None))
Expand Down
61 changes: 58 additions & 3 deletions tests/test_windows_startup_fixes.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def fail():
assert gui._server_failed.is_set()
assert gui._server_error is error
network = Mock(side_effect=AssertionError("must not probe a failed server"))
monkeypatch.setattr(gui.urllib.request, "urlopen", network)
monkeypatch.setattr(gui, "_gateway_urlopen", network)
assert not gui._wait_for("http://127.0.0.1/dash")
network.assert_not_called()

Expand Down Expand Up @@ -73,7 +73,7 @@ def test_actual_server_startup_failure_is_terminal_without_retries(monkeypatch,
def test_readiness_never_accepts_unowned_listener(monkeypatch):
monkeypatch.setattr(gui, "_server", SimpleNamespace(started=False))
network = Mock(side_effect=AssertionError("must wait for own bound listener"))
monkeypatch.setattr(gui.urllib.request, "urlopen", network)
monkeypatch.setattr(gui, "_gateway_urlopen", network)
assert not gui._wait_for("http://127.0.0.1/dash", timeout=0.001)
network.assert_not_called()

Expand All @@ -86,7 +86,7 @@ def test_update_readiness_requires_exact_nonce(monkeypatch, received, ready):
response.__enter__ = Mock(return_value=response)
response.__exit__ = Mock(return_value=False)
network = Mock(return_value=response)
monkeypatch.setattr(gui.urllib.request, "urlopen", network)
monkeypatch.setattr(gui, "_gateway_urlopen", network)
assert gui._wait_for("http://127.0.0.1:9876/dash", timeout=0.001) is ready
request = network.call_args.args[0]
assert request.full_url == "http://127.0.0.1:9876/health"
Expand Down Expand Up @@ -216,3 +216,58 @@ def log_message(self, *_):
server.shutdown()
server.server_close()
worker.join(2)



def test_gateway_urlopen_bypasses_system_proxy(monkeypatch):
response = Mock()
opener = Mock()
opener.open.return_value = response
captured = {}

def build_opener(*handlers):
captured["handlers"] = handlers
return opener

monkeypatch.setattr(gui.urllib.request, "build_opener", build_opener)
result = gui._gateway_urlopen("http://127.0.0.1:9876/dash", timeout=2)

assert result is response
proxy_handlers = [h for h in captured["handlers"]
if isinstance(h, gui.urllib.request.ProxyHandler)]
assert len(proxy_handlers) == 1
assert proxy_handlers[0].proxies == {}
opener.open.assert_called_once_with("http://127.0.0.1:9876/dash", timeout=2)


def test_gateway_urlopen_uses_supplied_tls_context(monkeypatch):
context = ssl.create_default_context()
opener = Mock()
monkeypatch.setattr(gui.urllib.request, "build_opener", Mock(return_value=opener))

gui._gateway_urlopen("https://localhost:9876/dash", timeout=2, context=context)

handlers = gui.urllib.request.build_opener.call_args.args
https_handlers = [h for h in handlers
if isinstance(h, gui.urllib.request.HTTPSHandler)]
assert len(https_handlers) == 1
assert https_handlers[0]._context is context


def test_readiness_timeout_records_last_connection_error(monkeypatch, caplog):
monkeypatch.setattr(gui, "_server", SimpleNamespace(started=True))
monkeypatch.setattr(gui, "_gateway_urlopen",
Mock(side_effect=OSError("proxy refused local connection")))
assert not gui._wait_for("http://127.0.0.1:9876/dash", timeout=0.01)
assert "proxy refused local connection" in caplog.text
assert "readiness timed out" in caplog.text.lower()


def test_worker_logs_full_exception(monkeypatch, caplog):
def fail():
raise ValueError("diagnostic sentinel")

monkeypatch.setattr(gui, "_run_server", fail)
gui._server_worker()
assert "diagnostic sentinel" in caplog.text
assert "Gateway server worker crashed" in caplog.text
2 changes: 1 addition & 1 deletion zcode_gateway/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
__version__ = "2.1.1"
__version__ = "2.1.3"