Repository navigation
Keep the gateway serving: concurrency, account identity, and the tray #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
114288f
9623cea
15b0379
ae03463
d3d8a9d
4708460
1a39412
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
|
@@ -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 | ||
|
|
||
|
|
||
|
|
@@ -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() | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: Prompt for AI agents |
||
| 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()) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 Prompt for AI agents |
||
| 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 | ||
|
|
@@ -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: | ||
|
|
@@ -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() | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 Prompt for AI agents |
||
| 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 | ||
|
|
@@ -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) | ||
|
|
||
|
|
||
| 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) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P1: Prompt for AI agents |
||
| 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()) | ||
| 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 | ||
|
|
||
|
|
@@ -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(): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: The dataset path no longer reads the captured Prompt for AI agents |
||
| 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 | ||
|
|
||
|
|
||
There was a problem hiding this comment.
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 fromget_zcode_jwtissecrets.token_hex(32), so it has nouser_id/suband every signup flow sends the same device ID. Keep the per-token derivation as the fallback for non-empty tokens.Prompt for AI agents