From 87cc91cb11b904e7070cdc2fd62b858c492778e0 Mon Sep 17 00:00:00 2001 From: Esmail Sarhadi <45729949+Esmail-sarhadi@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:08:29 +0330 Subject: [PATCH 01/15] feat: add PR proposal, installer, HTML reports and auto-reload fix --- PR_PROPOSAL.md | 201 ++++++++++++++++++++++++++ WORKBUDDY_MEMORY.md | 98 +++++++++++++ scripts/install/windows_install.py | 142 ++++++++++++++++++ scripts/report/generate_html.py | 223 +++++++++++++++++++++++++++++ tests/test_workbuddy_additions.py | 217 ++++++++++++++++++++++++++++ zcode_gateway/api_admin.py | 25 ++-- zcode_gateway/api_dash.py | 20 +++ zcode_gateway/auto_generate.py | 24 +++- zcode_gateway/paths.py | 5 + 9 files changed, 941 insertions(+), 14 deletions(-) create mode 100644 PR_PROPOSAL.md create mode 100644 WORKBUDDY_MEMORY.md create mode 100644 scripts/install/windows_install.py create mode 100644 scripts/report/generate_html.py create mode 100644 tests/test_workbuddy_additions.py diff --git a/PR_PROPOSAL.md b/PR_PROPOSAL.md new file mode 100644 index 0000000..62c6c6c --- /dev/null +++ b/PR_PROPOSAL.md @@ -0,0 +1,201 @@ +# درخواست Pull Request: AutoZCoder، از یک اگزه قابل حمل به یک ابزار قابل نگهداری + +> نویسنده پیشنهاد: اسماعیل سرحدی +> تاریخ: 2026-11-29 +> شاخه پیشنهادی: `workbuddy/pr-overhaul` +> وضعیت: **پیشنهاد فازبندیشده**. فاز ۱ در همین PR اجرا میشود؛ فازهای بعدی در PRهای جداگانه. + +--- + +## 1. چرا این PR؟ + +AutoZCoder هسته Gateway خوبی دارد، ولی تجربه کاربری و اوتوماسیون آن برای استفاده جدی آماده نیست: + +- اگزه portable است و `config.yaml`، `accounts/`، `logs/`، `gateway.db` و `generator-data/` را **کنار فایل اجرایی** میسازد. همیشه همان پوشه Downloads شلوغ میشود. +- کاربر نمیداند آیا محیطش درست است یا نه؛ تا وقتی چیزی نشکند، خبری نیست. +- بعد از Auto Generate، اکانتهای qualified ساخته و ذخیره میشوند ولی **pool خودکار reload نمیشود**؛ داشبورد تعداد قدیمی نشان میدهد. (امشب با `POST /admin/pool/reload` دیدیم: ۳ اکانت روی دیسک بود، ۲ تا در حافظه.) +- لاگها متنی پراکندهاند، خروجی قابل خواندن برای انسان ندارند، و secretها گاهی در آنها میمانند. +- UI پر از برچسبهای فنی است (`ip_source`, `failure_limit`, `device_mid`) و کاربر تازهکار گیج میشود. +- `mail-worker` تست ندارد؛ `npm test` عملاً `exit 1` است. +- god-fileها (`generator.py` ~۴٬۸۰۰ خط، `api_dash.py` ~۲٬۲۰۳، `gui.py` ~۱٬۹۹۶) هر تغییری را سخت میکنند. +- ۴۹ مورد `except Exception: pass` خطاها را بیصدا میخورند. + +--- + +## 2. مرزهای صریح این پیشنهاد + +من **هیچ قابلیت جدیدی برای** موارد زیر نمینویسم: + +- دور زدن کپچا یا تقویت `captcha_solver` +- چرخش IP / پروکسی برای فرار از `SIGNUP_RATE_LIMITED` +- claim خودکار پلن رایگان یا ساخت انبوه اکانت + +دلیل: همانطور که در بررسی کد گفتم، این بخش بیشترین ریسک ToS/حقوقی و کمترین کیفیت کد را دارد. پیشنهاد من این است که انرژی روی **هسته Gateway، نصب، پیکربندی، لاگ، گزارش و UI** برود. + +--- + +## 3. فاز ۱ — نصب و چیدمان داده (در همین PR) + +### 3.1 حالت نصبی +- اسکریپت `scripts/install/windows_install.py` (فقط ASCII در مسیرها، بدون `.ps1` غیر ASCII): + - اگزه را به `%LOCALAPPDATA%\ZcodeGateway\app\ZcodeGateway.exe` کپی میکند. + - دادهها را به `%LOCALAPPDATA%\ZcodeGateway\data\` منتقل میکند. + - میانبر دسکتاپ و Start Menu میسازد. + - نسخه قبلی portable را شناسایی و با تأیید کاربر migrate میکند (کپی، نه حذف). +- پرچم `--portable` حفظ میشود تا کسانی که اگزه را کنار خودشان میخواهند، همان رفتار قدیمی را داشته باشند. + +### 3.2 جداسازی مسیرها +- `paths.py`: `data_dir()` به ترتیب از `ZGW_DATA_DIR`، پوشه نصب، و `%LOCALAPPDATA%` استفاده میکند. +- `app_dir()` فقط برای فایلهای اجرایی است، نه داده. + +### 3.3 معیار پذیرش +- اجرای نصاب روی یک پوشه تمیز، dashboard روی `127.0.0.1:8788/dash` بالا میآید. +- اجرای مجدد نصاب، دادهها را پاک نمیکند. +- حالت portable masih کار میکند. + +--- + +## 4. فاز ۲ — Config Doctor (تشخیص هوشمند) + +یک صفحه واحد «**پزشک تنظیمات**» که با یک دکمه everything را چک میکند: + +| چک | آنچه نشان میدهد | +|---|---| +| Python و نسخه | آیا generator میتواند اجرا شود | +| پکیجها (`playwright`, `ddddocr`, ...) | نصب نشدهاند | +| Chromium | دانلود شده / نشده | +| Node و wrangler | برای mail worker | +| توکن Cloudflare | معتبر است؟ دسترسیهای لازم را دارد؟ | +| دامنه و Email Routing | MX و catch-all درست متصلاند؟ | +| Inbox | `/inbox` با secret جواب میدهد؟ | +| AI judge | یک اکانت واقعی و vision دارد؟ | +| Pool | چند اکانت ready است؟ | + +خروجی: چکلیست سبز/زرد/قرمز + دکمه «**خودکار تعمیر کن**» برای موارد امن (نصب پکیج، دانلود Chromium، تنظیم inbox). + +> چک توکن Cloudflare **هیچوقت مقدار توکن را چاپ نمیکند**؛ فقط میگوید معتبر است یا کدام scope کم است. + +--- + +## 5. فاز ۳ — اوتوماسیون قابل اعتماد + +### 5.1 رفع باگ reload (فوری) +- بعد از اتمام Auto Generate، اگر `qualified > 0`، فراخوانی `state.pool.reload()` بهصورت sync قبل از بستن session. +- دکمه «Reload pool» بعد از هر run بهصورت خودکار زده شود. + +### 5.2 Adaptive concurrency و timeout +- محدودیت سخت: `concurrency ≤ 5` در UI (پیشنهاد ۳). +- timeout پیشفرض ۱۸۰۰ ثانیه (نه ۹۰۰). +- تشخیص «deadline به زودی» و تمدید هوشمند تا ۳۰ دقیقه برای workerهایی که `finish_signup` را 200 گرفتهاند. + +### 5.3 طبقهبندی شکست +بهجای `timeout` کلی: +- `captcha_timeout` +- `signup_timeout` +- `email_timeout` +- `finish_signup_timeout` +- `plan_check_timeout` + +### 5.4 Checkpoint / Resume +- ذخیره وضعیت هر attempt در `state.json`، امکان ادامه بعد از restart. + +--- + +## 6. فاز ۴ — لاگ و گزارش HTML هوشمند + +### 6.1 لاگ ساختاریافته +- لاگها علاوه بر متن، به JSONL هم نوشته شوند: `logs/auto_.jsonl`. +- فیلدها: `ts`, `level`, `worker`, `stage`, `event`, `duration_ms`, `redacted=true`. + +### 6.2 Sanitization +- قبل از نوشتن، regexهای `[REDACTED]` موجود را گسترش بده: توکن، inbox secret، JWT، `captcha_verify_param`، password. + +### 6.3 گزارش HTML +- `scripts/report/generate_html.py`: + - ورودی: پوشه logs + auto status + - خروجی: `reports/run_.html` + - محتوا: خلاصه (qualified/failed/timeout)، نمودار timelines، جدول workerها، لینک به لاگ هر worker، هشدارها. + - فاقد هرگونه secret. +- دکمه «**گزارش HTML**» در Auto Generate. + +--- + +## 7. فاز ۵ — UI/UX + +- Wizard سه مرحلهای: **نصب → پزشک تنظیمات → اولین اجرا**. +- برچسبهای ساده: بجای `ip_source` → «از کدام IP برویم؟»؛ بجای `failure_limit` → «بعد از چند شکست متوقف شو؟». +- Topology diagram کوچک: Gateway ← اکانتها ← ورکرها. +- Status chipها: `Ready`, `Cooling`, `Rate limited`, `Needs attention`. +- RTL کامل برای فارسی (existing preference). +- Empty-stateها: وقتی اکانت یا ورکری نیست، متن بگوید «اولین اکانتت را اضافه کن». + +--- + +## 8. فاز ۶ — ۱۰ قابلیت خلاقانه (غیر تهاجمی) + +1. **Config Doctor** (بالا) +2. **HTML Run Report** (بالا) +3. **Quota Forecast** — تخمین زمان تمام شدن توکن براساس مصرف اخیر +4. **Model Health Score** — هر مدلbrای هر اکانت امتیاز سلامت بگیرد +5. **Smart Routing Advisor** — پیشنهاد strategy براساس الگوی 405/529 +6. **Maintenance Calendar** — نمایش reset time پلنها در تقویم +7. **Secure Export/Import Bundle** — خروجی کاملاً رمزگذاریشده، بدون secret خام +8. **Audit Log** — چه کسی کلید admin را کی استفاده کرد +9. **Safe Mode** — غیرفعال کردن خودکار generator وقتی rate-limit دیده شد +10. **Local Docs Search** — جستجو در مستندات داخل داشبورد + +> هیچکدام از اینها کپچا یا محدودیت IP را دور نمیزنند. + +--- + +## 9. فاز ۷ — رفع باگهای شناختهشده + +| باگ | محل | وضعیت در این PR | +|---|---|---| +| Auto run pool reload نشد | `api_dash.py` auto endpoints | ✅ رفع میشود | +| `mail-worker` تست ندارد | `mail-worker/package.json` | ✅ تست اضافه میشود | +| ۴۹ تا `except Exception: pass` | `zcode_gateway/*.py` | در فاز ۷ لاگ هشدار اضافه میشود | +| god-file `api_dash.py` | — | استخراج mail logic به `mail_service.py` در فاز ۷ | +| secretها plaintext | `accounts_dir.py` | فاز ۸: DPAPI/keyring | +| `locate` اجرای دلخواه `main.py` | `api_dash.py` | فاز ۸: گزینه امن | +| لاگ 503 AI judge نویز زیاد | generator | فاز ۳: طبقهبندی | + +--- + +## 10. فاز ۸ — نقشه تست (واقعیت ۲۵۰۰) + +پروژه الان **۱٬۰۷۱ تست** دارد. هدف ۲۵۰۰ تست در **چند release** قابل دستیابی است، نه در یک PR: + +| فاز | تعداد تستهای جدید | +|---|---| +| فاز ۱ (نصب) | ۳۰ | +| فاز ۲ (doctor) | ۱۲۰ | +| فاز ۳ (automation) | ۲۰۰ | +| فاز ۴ (report/sanitize) | ۱۵۰ | +| فاز ۵ (UI smoke) | ۱۰۰ | +| فاز ۶ (features) | ۳۰۰ | +| فاز ۷ (bug fixes) | ۲۰۰ | +| فاز ۸ (security) | ۳۰۰ | +| **جمع هدف** | **≈ ۱٬۴۰۰new + ۱٬۰۷۱existing ≈ ۲٬۴۷۱** | + +برای رسیدن به ۲۵۰۰exact، فاز ۹ (فشار/انtegration) ≈ ۱۰۰ تست اضافه میکند. + +**در همین PR**: ۲۴ تست معنیدار برای فاز ۱ و رفع باگ reload و report generator اضافه میشود (همه ۲۴ تا اجرا و سبز شدند). عددسازی نمیکنم. + +--- + +## 11. معیارهای پذیرش کلی + +- `python -m pytest tests -q` روی Windows و Linux سبز. +- نصاب روی پوشه تمیز و روی نصب قبلی بدون از دست دادن دادهها کار میکند. +- Auto Generate بعد از run، pool را خودکار reload میکند. +- گزاره HTML بدون secret تولید میشود. +- مستندات فارسی/انگلیسی بهروز. + +--- + +## 12. ریسکها + +- تغییر مسیر دادهها میتواند نصبهای قدیمی را بشکند → migration با backup. +- god-fileهاreview را کند میکنند → PRهای کوچکتر. +- ریسک ToS Generator همچنان پابرجاست → مرز section 2. diff --git a/WORKBUDDY_MEMORY.md b/WORKBUDDY_MEMORY.md new file mode 100644 index 0000000..189582e --- /dev/null +++ b/WORKBUDDY_MEMORY.md @@ -0,0 +1,98 @@ +# یادداشت کاری دایی گل — AutoZcoder + +> این فایل همان «فایل حافظه کنار پروژه» است که اسماعیل خواست. +> هر کاری که روی این پروژه میشود، در آن یادداشت میشود. +> آخرین بهروزرسانی: 2026-11-29 21:54 (GMT+3:30) + +--- + +## 1. درخواست اسماعیل + +اسماعیل میخواهد یک **Pull Request خیلی کامل** به پروژه AutoZcoder بزند. خواستهها: + +- نصابشده کردن فایل اگزه (فعلاً portable است و فایلها کنار exe میسازد) +- قابلیت هوشمند: تشخیص خودکار مقادیر (config doctor) و هوشمندسازیهای دیگه +- کاملتر کردن کد، بهتر کردن اوتوماسیون +- UI/UX جذابتر و بدون گیجی کاربر +- لاگگیری بهتر + خروجی خودکار HTML بهصورت گزارش هوشمند +- ۱۰ قابلیت جدید خلاقانه +- رفع باگهایی که خودم گفته بودم (god-fileها، `except Exception: pass`، plaintext JWT، reload نشدن pool، تست نداشتن mail-worker و ...) +- «انقلاب» در نرمافزار +- حداقل ۲۵۰۰ تست +- یک فایل حافظه کنار پروژه که هر کاری یادداشت شود (همین فایل) + +--- + +## 2. تصمیم مرزی من (مهم) + +پروژه دو بخش دارد: + +1. **هسته gateway/relay** (`service.py`, `upstream.py`, `pool.py`, `deps.py`) — مهندسی خوب، قانونی، قابل توسعه. +2. **زیرسیستم generator/captcha/claim** — ساخت انبوه اکانت، دور زدن کپچا، چرخش IP، claim پلن رایگان. + +من **قابلیت جدیدی برای دور زدن کپچا / محدودیت IP / claim اکانت نمینویسم**. این بخشalready ریسک ToS/حقوقی بالایی دارد و خودم در بررسی کد به اسماعیل گفتم. کاری که میکنم: + +- بهبودهای gateway، نصب، پیکربندی، لاگ،报告 HTML، UI/UX و رفع باگ میزان. +- رفع باگ `auto-reload pool` (باگ واقعی ای امشب دیدیم). +- تستهای معنیدار مینویسم، نه عددسازی. + +--- + +## 3. واقعیتها (از کد و GitHub، نه حدس) + +- ریپو: ۷۶ ستاره، ۱۲ فورک، ۲ contributor، MIT، ۱۷ ریلیز در ۶ هفته. +- تست فعلی: ۷۵ فایل تست، ۱٬۰۷۱ تابع تست، ۳٬۶۲۲ assert. +- ۲۵۰۰ تست در یک PR غیرواقعی است؛ هدف مرحلهای است. در `PR_PROPOSAL.md` این موضوع را شفاف مینویسم. +- Regex god-fileها: `generator.py` ~۴٬۸۰۰ خط، `api_dash.py` ~۲٬۲۰۳، `gui.py` ~۱٬۹۹۶. +- ۴۹ مورد `except Exception: pass` در `zcode_gateway/*.py`. +- اکانتها: JWT و refresh token در snapshotها plaintext. +- `mail-worker` تست ندارد (`npm test` عملاً `exit 1`). +- باگ دیده شده امشب: Auto Generate ۳ اکانت ساخت و ذخیره کرد، ولی pool خودکار reload نشد؛ من دستی `POST /admin/pool/reload` زدم و ۵ اکانت لود شد (۴ ready + ۱ dead). + +--- + +## 4. اقدامات انجامشده + +### 2026-11-29 21:55 +- ریپو عمومی را clone کردم در: + `C:\Users\esmail\WorkBuddy AI\2026-11-29-20-04-23\AutoZcoder` +- شاخه محلی `workbuddy/pr-overhaul` ساخته شد (مرحله بعدی). +- این فایل حافظه ساخته شد. + +--- + +### 2026-11-29 22:05 +- `PR_PROPOSAL.md` نوشته شد: درخواست Pull Request فازبندیشده، فارسی/RTL، با ۸ فاز، ۱۰ قابلیت خلاقانه، جدول رفع باگها و نقشه واقعی ۲۵۰۰ تست. +- مرز قانونی در آن صریح است: قابلیت جدید برای کپچا/IP/claim نمینویسم. + +### 2026-11-29 22:08 +- شاخه `workbuddy/pr-overhaul` ساخته شد. +- باگ auto-reload رفع شد: `AutoGenerateController` حالا `on_finish` callback دارد؛ `api_dash` بعد از اتمام run با qualified>0، `reload_pool_from_disk` را صدا میزند. +- `api_admin.reload_pool_from_disk` استخراج شد تا endpoint و hook از یک منطق استفاده کنند. +- `scripts/report/generate_html.py` اضافه شد: گزارش HTML self-contained، با redaction کامل JWT/password/captcha/token/k=. +- `scripts/install/windows_install.py` اضافه شد: نصب غیرمخرب، `ZGW_DATA_DIR`، migration با کپی، launcher `.cmd`. +- `zcode_gateway/paths.py`: پشتیبانی از `ZGW_DATA_DIR` اضافه شد. + +### 2026-11-29 22:12 +- ۲۴ تست معنیدار در `tests/test_workbuddy_additions.py` نوشته شد. +- تستها خارج از conftest ریپو اجرا شدند (چون `yaml` نصب نیست): **24 passed**. +- report روی لاگهای واقعی اجرا شد: `run_e69a...html`، ۱۶٬۷۹۴ بایت، بدون JWT/password/cfat. +- installer dry-run روی exe واقعی اجرا شد: لیست مهاجرت درست نشان داده شد، هیچ فایلی کپی نشد. + +## 5. مراحل پیش رو + +1. نوشتن `PR_PROPOSAL.md` — درخواست خیلی کامل، فارسی، RTL، با فازبندی و مرز قانونی. +2. رفع باگ auto-reload pool در کد. +3. اضافه کردن `scripts/report/generate_html.py` — گزارش HTML هوشمند از لاگها. +4. اضافه کردن `scripts/install/windows_install.py` — نصاب کوچک و تمیز. +5. اضافه کردن تست معنیدار برای موارد بالا (چند ده تست، نه ۲۵۰۰). +6. اجرای تستها، بهروزرسانی این فایل، ارائه فایلها. + +--- + +## 6. یادآورهای شخصی + +- عدد از خودم درنمیآورم: ۲۵۰۰ تست را ادعا نمیکنم؛ مینویسم «هدف مرحلهای». +- تا ندیدهام «انجام شد» نمیگویم: تستها را اجرا میکنم و خروجی را میبینم. +- سورس کاربر مال خودش است؛ در فایلهای اصلیاش جز تغییرات لازم دست نمیزنم. +- توکن Cloudflare و inbox secret را دوباره در چت نمیآورم. diff --git a/scripts/install/windows_install.py b/scripts/install/windows_install.py new file mode 100644 index 0000000..b53dc07 --- /dev/null +++ b/scripts/install/windows_install.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""Non-destructive installer for the portable ZcodeGateway.exe. + +The upstream exe is portable and writes config/accounts/logs beside itself. +This helper puts the exe in a stable folder and keeps data in a separate +folder via the ZGW_DATA_DIR environment variable. + +Nothing is deleted or moved: existing files are copied, never overwritten. +Run with --dry-run to see the plan without touching the filesystem. +""" + +from __future__ import annotations + +import argparse +import filecmp +import os +import shutil +import sys +from pathlib import Path + +DATA_ITEMS = ( + "config.yaml", + "accounts", + "generator-data", + "logs", + "gateway.db", + "gateway.db-shm", + "gateway.db-wal", + "mail-worker", + "pool.json", +) + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--exe", type=Path, required=True, + help="Path to ZcodeGateway.exe") + parser.add_argument("--target", type=Path, + default=Path(os.environ.get("LOCALAPPDATA", Path.home())) / "ZcodeGateway", + help="Installation root (default: %%LOCALAPPDATA%%/ZcodeGateway)") + parser.add_argument("--data-dir", type=Path, default=None, + help="Data folder (default: /data)") + parser.add_argument("--portable", action="store_true", + help="Do not set ZGW_DATA_DIR; keep data beside the exe") + parser.add_argument("--dry-run", action="store_true", + help="Print the plan only") + return parser + + +def copy_if_missing_source(source: Path, destination: Path, dry_run: bool) -> bool: + """Copy a file or directory only when the destination does not exist.""" + if not source.exists(): + return False + if destination.exists(): + return False + if dry_run: + return True + destination.parent.mkdir(parents=True, exist_ok=True) + if source.is_dir(): + shutil.copytree(source, destination, dirs_exist_ok=False) + else: + shutil.copy2(source, destination) + return True + + +def install(exe: Path, target: Path, data_dir: Path | None = None, + portable: bool = False, dry_run: bool = False) -> dict: + """Install the exe and prepare an isolated data directory.""" + exe = exe.expanduser().resolve() + target = target.expanduser().resolve() + if not exe.is_file(): + raise FileNotFoundError(f"executable not found: {exe}") + if "zcodegateway" not in exe.name.lower(): + raise ValueError("expected a ZcodeGateway executable") + + app_bin = target / "app" + data = data_dir.expanduser().resolve() if data_dir else target / "data" + launcher = target / "ZcodeGateway.cmd" + + if not dry_run: + app_bin.mkdir(parents=True, exist_ok=True) + data.mkdir(parents=True, exist_ok=True) + + exe_copy = app_bin / exe.name + copied_exe = False + if not exe_copy.exists() or (exe_copy.is_file() and not filecmp.cmp(exe, exe_copy, shallow=False)): + copied_exe = True + if not dry_run: + shutil.copy2(exe, exe_copy) + + migrated = [] + if not portable: + for name in DATA_ITEMS: + source = exe.parent / name + destination = data / name + if copy_if_missing_source(source, destination, dry_run): + migrated.append(name) + + if not dry_run: + if portable: + launcher.write_text( + '@echo off\n"%s" %%*\n' % exe_copy, + encoding="ascii", + ) + else: + launcher.write_text( + '@echo off\nset "ZGW_DATA_DIR=%s"\n"%s" %%*\n' % (data, exe_copy), + encoding="ascii", + ) + (target / "README.txt").write_text( + "ZcodeGateway installed.\n" + "Use ZcodeGateway.cmd to start the gateway.\n" + "Data folder: %s\n" + "Portable mode: %s\n" % (data, portable), + encoding="utf-8", + ) + + return { + "exe": str(exe_copy), + "data": str(data) if not portable else str(exe_copy.parent), + "launcher": str(launcher), + "copied_exe": copied_exe, + "migrated": migrated, + "dry_run": dry_run, + } + + +def main(argv: list[str] | None = None) -> int: + args = build_parser().parse_args(argv) + try: + result = install(args.exe, args.target, args.data_dir, + portable=args.portable, dry_run=args.dry_run) + except (OSError, ValueError) as exc: + print(f"install failed: {exc}", file=sys.stderr) + return 1 + for key, value in result.items(): + print(f"{key}: {value}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/report/generate_html.py b/scripts/report/generate_html.py new file mode 100644 index 0000000..84119fe --- /dev/null +++ b/scripts/report/generate_html.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python3 +"""Generate a self-contained HTML report from Auto Generate logs. + +No third-party dependencies. Every string is redacted before it reaches the +HTML so the report is safe to share as a support attachment. +""" + +from __future__ import annotations + +import argparse +import html +import json +import re +import sys +import time +from pathlib import Path + +JWT_RE = re.compile(r"\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b") +PASSWORD_RE = re.compile(r"(?im)^(Password:\s*).+$") +CAPTCHA_PARAM_RE = re.compile(r"(?i)(captcha_verify_param:\s*).+$") +QUERY_KEY_RE = re.compile(r"(?i)([?&]k=)[^&\s\"']+") +CF_TOKEN_RE = re.compile(r"\bcfat_[A-Za-z0-9_-]{8,}\b") +BEARER_RE = re.compile(r"(?i)(Bearer\s+)[A-Za-z0-9._-]{8,}") +TOKEN_JSON_RE = re.compile(r"(?i)(\"token\"\s*:\s*\")[^\"]+(\")") + + +def redact(text: str) -> str: + """Remove credentials from a log line before it is written to a report.""" + if not text: + return "" + text = JWT_RE.sub("[REDACTED_JWT]", text) + text = PASSWORD_RE.sub(r"\1[REDACTED]", text) + text = CAPTCHA_PARAM_RE.sub(r"\1[REDACTED]", text) + text = QUERY_KEY_RE.sub(r"\1[REDACTED]", text) + text = CF_TOKEN_RE.sub("[REDACTED_CF_TOKEN]", text) + text = BEARER_RE.sub(r"\1[REDACTED]", text) + text = TOKEN_JSON_RE.sub(r"\1[REDACTED]\2", text) + return text + + +def classify(text: str) -> str: + if "fully created" in text: + return "qualified" + if "SIGNUP_RATE_LIMITED" in text: + return "rate_limited" + if "Start Plan already active" in text or "Start Plan claimed" in text: + return "start_plan" + if "finish_signup: status=200" in text: + return "token_issued" + if "Captcha solved!" not in text: + return "captcha_timeout" + return "timeout" + + +def parse_worker_log(path: Path) -> dict: + raw = path.read_text(encoding="utf-8", errors="replace") + safe = redact(raw) + lines = [line.strip() for line in safe.splitlines() if line.strip()] + email = "" + for line in lines: + if line.startswith("Email: "): + email = line.split("Email: ", 1)[1].strip() + break + finish = re.findall(r"finish_signup: status=(\d+)", safe) + return { + "id": path.stem, + "file": path.name, + "email": email, + "category": classify(safe), + "captcha_solved": safe.count("Captcha solved!"), + "finish_status": finish[-1] if finish else "", + "last_lines": lines[-5:], + } + + +def load_progress(data_dir: Path) -> dict: + path = data_dir / "auto_generate_progress.json" + if not path.is_file(): + return {} + try: + value = json.loads(path.read_text(encoding="utf-8")) + return value if isinstance(value, dict) else {} + except (OSError, ValueError): + return {} + + +def _esc(value) -> str: + return html.escape(redact(str(value if value is not None else ""))) + + +def build_html(report: dict) -> str: + status = report.get("status") or "unknown" + reason = report.get("reason") or "" + counts = report.get("counts") or {} + workers = report.get("workers") or [] + events = report.get("events") or [] + config = report.get("config") or {} + + cards = "".join( + '
%s%s
' + % (_esc(key), _esc(value)) + for key, value in ( + ("Status", status), ("Reason", reason or "-"), + ("Attempts", counts.get("attempts", 0)), + ("Qualified", counts.get("qualified", 0)), + ("Failed", counts.get("failed", 0)), + ) + ) + + rows = "".join( + "%s%s%s%s%s" % ( + _esc(w.get("file", "")), _esc(w.get("email", "")), + _esc(w.get("category", "")), _esc(w.get("finish_status", "")), + _esc(w.get("captcha_solved", 0)), + ) + for w in workers + ) or 'No worker logs found.' + + timeline = "".join( + '
  • %s
  • ' % ( + _esc(time.strftime("%H:%M:%S", time.localtime(float(e.get("ts", 0))))), + _esc(e.get("message", "")), + ) + for e in events[-40:] + ) or "
  • No events recorded.
  • " + + config_rows = "".join( + "
  • %s: %s
  • " % (_esc(key), _esc(value)) + for key, value in config.items() + ) + + detail_blocks = "".join( + "
    %s
    %s
    " % ( + _esc(w.get("file", "")), + _esc("\n".join(w.get("last_lines", []))), + ) + for w in workers + ) + + return """ + + +Auto Generate Report +
    +

    گزارش Auto Generate

    +
    Run: %s · produced %s
    +
    %s
    +

    وضعیت ورکرها

    %s
    لاگایمیلدستهfinishکپچا
    +

    زمانлайн

      %s
    +

    تنظیمات اجرا

      %s
    +

    آخرین خطوط لاگها

    %s +
    Every value is redacted before rendering. Safe to share as a support attachment.
    +
    """ % ( + _esc(report.get("run_id", "")), + _esc(time.strftime("%Y-%m-%d %H:%M:%S")), + cards, rows, timeline, config_rows, detail_blocks, + ) + + +def generate(data_dir: Path, run_id: str = "", out_dir: Path | None = None) -> Path: + data_dir = data_dir.expanduser().resolve() + out_dir = (out_dir or data_dir / "reports").expanduser().resolve() + out_dir.mkdir(parents=True, exist_ok=True) + + logs_dir = data_dir / "logs" / "workers" + pattern = f"auto-{run_id}*.log" if run_id else "auto-*.log" + logs = sorted(logs_dir.glob(pattern)) if logs_dir.is_dir() else [] + workers = [parse_worker_log(p) for p in logs] + + progress = load_progress(data_dir) + if run_id and progress.get("id") and not str(progress["id"]).startswith(run_id): + progress = {} + counts = dict(progress.get("counts") or {}) + if not counts: + for category in ("qualified", "token_issued", "start_plan", + "rate_limited", "captcha_timeout", "timeout"): + counts[category] = sum(1 for w in workers if w["category"] == category) + + report = { + "run_id": run_id or progress.get("id", "latest"), + "status": progress.get("status", "unknown"), + "reason": progress.get("reason", ""), + "counts": counts, + "config": progress.get("config", {}), + "events": progress.get("events", []), + "workers": workers, + } + target = out_dir / ("run_%s.html" % re.sub(r"[^A-Za-z0-9_-]", "_", str(report["run_id"]))) + target.write_text(build_html(report), encoding="utf-8") + return target + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--data-dir", type=Path, required=True, + help="generator-data folder") + parser.add_argument("--run-id", default="", help="optional Auto Generate run id") + parser.add_argument("--out", type=Path, default=None, help="output folder") + args = parser.parse_args(argv) + try: + path = generate(args.data_dir, args.run_id, args.out) + except OSError as exc: + print(f"report failed: {exc}", file=sys.stderr) + return 1 + print(path) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_workbuddy_additions.py b/tests/test_workbuddy_additions.py new file mode 100644 index 0000000..a3fdcaa --- /dev/null +++ b/tests/test_workbuddy_additions.py @@ -0,0 +1,217 @@ +"""Tests for the WorkBuddy first-slice additions. + +These are real behavioural tests, not placeholder counts. +""" + +from __future__ import annotations + +import importlib.util +import os +from pathlib import Path + +import pytest + +ROOT = Path(os.environ.get("AUTOZCODER_ROOT", Path(__file__).resolve().parent.parent)) + + +def _load(name: str, relative: str): + path = ROOT / relative + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +report = _load("wb_report", "scripts/report/generate_html.py") +installer = _load("wb_installer", "scripts/install/windows_install.py") + + +# ---- report redaction ---------------------------------------------------- # + +def test_redact_jwt(): + token = "eyJhbGciOiJFUzI1NiJ9.eyJpZCI6ImFiYyJ9.ZZZZZZZZZZZZZZZZ" + assert token not in report.redact("token " + token) + assert "[REDACTED_JWT]" in report.redact("token " + token) + + +def test_redact_password(): + assert "[REDACTED]" in report.redact("Password: SuperSecret123") + + +def test_redact_captcha_param(): + assert "[REDACTED]" in report.redact("captcha_verify_param: abcDEF123") + + +def test_redact_query_key(): + assert "k=verysecret" not in report.redact("GET /inbox?k=verysecret&to=a@b.c") + assert "[REDACTED]" in report.redact("GET /inbox?k=verysecret&to=a@b.c") + + +def test_redact_cf_token(): + assert "[REDACTED_CF_TOKEN]" in report.redact("cfat_1234567890abcdefgh") + + +def test_redact_bearer(): + assert "[REDACTED]" in report.redact("Authorization: Bearer abcdefgh12345678") + + +def test_redact_token_json(): + line = '{"token":"eyJhbGciOiJ9.abc.def"}' + assert '"[REDACTED]"' in report.redact(line) + + +# ---- classification ------------------------------------------------------ # + +def test_classify_qualified(): + assert report.classify("1 fully created (1 with Starter plan)") == "qualified" + + +def test_classify_rate_limited(): + assert report.classify("429 SIGNUP_RATE_LIMITED") == "rate_limited" + + +def test_classify_captcha_timeout(): + assert report.classify("Hybrid Solve attempt 1 [1/15]") == "captcha_timeout" + + +def test_classify_token_issued(): + assert report.classify("finish_signup: status=200") == "token_issued" + + +# ---- report generation --------------------------------------------------- # + +def test_parse_worker_log(tmp_path): + log = tmp_path / "auto-abc_200000.log" + log.write_text( + "Email: test@example.com\nPassword: hunter2\n" + "finish_signup: status=200\nCaptcha solved!\n", + encoding="utf-8", + ) + result = report.parse_worker_log(log) + assert result["email"] == "test@example.com" + assert result["finish_status"] == "200" + assert result["captcha_solved"] == 1 + assert "hunter2" not in str(result) + + +def test_build_html_escapes(tmp_path): + page = report.build_html({"run_id": "", "workers": [], + "counts": {}, "events": [], "config": {}}) + assert "<script>" in page + assert "" not in page + + +def test_generate_creates_safe_report(tmp_path): + data = tmp_path / "generator-data" + logs = data / "logs" / "workers" + logs.mkdir(parents=True) + (logs / "auto-run1_1.log").write_text( + "Email: a@b.c\nPassword: secretpass\n" + "eyJhbGciOiJ9.eyJpZCI6IjEifQ.signature\n" + "1 fully created (1 with Starter plan)\n", + encoding="utf-8", + ) + path = report.generate(data, run_id="run1") + page = path.read_text(encoding="utf-8") + assert path.is_file() + assert "secretpass" not in page + assert "eyJhbGciOiJ9" not in page + assert "[REDACTED]" in page + + +def test_load_progress_missing(tmp_path): + assert report.load_progress(tmp_path) == {} + + +def test_load_progress_invalid(tmp_path): + (tmp_path / "auto_generate_progress.json").write_text("not json", encoding="utf-8") + assert report.load_progress(tmp_path) == {} + + +# ---- installer ----------------------------------------------------------- # + +def _fake_exe(tmp_path) -> Path: + exe = tmp_path / "source" / "ZcodeGateway.exe" + exe.parent.mkdir(parents=True, exist_ok=True) + exe.write_bytes(b"fake exe") + return exe + + +def test_installer_dry_run(tmp_path): + exe = _fake_exe(tmp_path) + target = tmp_path / "install" + result = installer.install(exe, target, dry_run=True) + assert result["dry_run"] is True + assert not target.exists() + + +def test_installer_copies_exe_and_launcher(tmp_path): + exe = _fake_exe(tmp_path) + target = tmp_path / "install" + result = installer.install(exe, target) + assert (target / "app" / "ZcodeGateway.exe").is_file() + launcher = (target / "ZcodeGateway.cmd").read_text(encoding="ascii") + assert "ZGW_DATA_DIR" in launcher + assert result["copied_exe"] is True + + +def test_installer_migrates_data(tmp_path): + exe = _fake_exe(tmp_path) + (exe.parent / "config.yaml").write_text("server: {}", encoding="utf-8") + (exe.parent / "accounts").mkdir() + (exe.parent / "accounts" / "a.txt").write_text("x", encoding="utf-8") + target = tmp_path / "install" + result = installer.install(exe, target) + assert "config.yaml" in result["migrated"] + assert (target / "data" / "config.yaml").is_file() + assert (target / "data" / "accounts" / "a.txt").is_file() + + +def test_installer_portable_launcher(tmp_path): + exe = _fake_exe(tmp_path) + target = tmp_path / "install" + result = installer.install(exe, target, portable=True) + launcher = (target / "ZcodeGateway.cmd").read_text(encoding="ascii") + assert "ZGW_DATA_DIR" not in launcher + assert result["data"].endswith("app") + + +def test_installer_does_not_overwrite_config(tmp_path): + exe = _fake_exe(tmp_path) + (exe.parent / "config.yaml").write_text("port: 1", encoding="utf-8") + target = tmp_path / "install" + installer.install(exe, target) + (target / "data" / "config.yaml").write_text("port: 2", encoding="utf-8") + installer.install(exe, target) + assert (target / "data" / "config.yaml").read_text(encoding="utf-8") == "port: 2" + + +def test_installer_rejects_wrong_exe(tmp_path): + wrong = tmp_path / "notepad.exe" + wrong.write_bytes(b"x") + with pytest.raises(ValueError): + installer.install(wrong, tmp_path / "install") + + +# ---- paths override ------------------------------------------------------ # + +def test_paths_data_dir_override(monkeypatch, tmp_path): + from zcode_gateway import paths + monkeypatch.setenv("ZGW_DATA_DIR", str(tmp_path / "custom-data")) + assert paths.base_dir() == tmp_path / "custom-data" + + +# ---- auto finish callback ------------------------------------------------ # + +def test_auto_finish_callback_once(tmp_path): + from zcode_gateway.auto_generate import AutoGenerateController + + controller = AutoGenerateController(tmp_path, launch=lambda *a: None) + seen = [] + controller.set_finish_callback(lambda status: seen.append(status)) + controller._run_id = "run-1" + controller._notify_finish() + controller._notify_finish() + assert len(seen) == 1 + assert seen[0]["status"] == controller.status()["status"] diff --git a/zcode_gateway/api_admin.py b/zcode_gateway/api_admin.py index d9bf225..d776bfe 100644 --- a/zcode_gateway/api_admin.py +++ b/zcode_gateway/api_admin.py @@ -553,10 +553,12 @@ async def check_balance(request: Request, account_id: str, "plans": account.notes.get("plans", [])} -@router.post("/pool/reload") -async def reload_pool(request: Request, key: str = Depends(admin_key)) -> dict: - """Re-read the credential source (e.g. providers.json after a desktop login).""" - state = get_state(request) +async def reload_pool_from_disk(state) -> dict: + """Re-read the credential source and reconcile the in-memory pool. + + Shared by the HTTP endpoint and the Auto Generate finish hook so a + qualified account is always visible in the dashboard at session end. + """ try: # providers.json can be large and AV-scanned; keep it off the loop accounts = await asyncio.to_thread(load_accounts, state.cfg.accounts) @@ -576,9 +578,6 @@ async def reload_pool(request: Request, key: str = Depends(admin_key)) -> dict: if existing is None: await state.pool.upsert(account) added += 1 - # populate balance/plan immediately: the GUI (and quota_aware - # routing) should see fresh data on import, not after the 300s - # background poller. Best-effort — upstream may be unreachable. try: await state.tokens.check_account(account) except Exception: @@ -588,9 +587,6 @@ async def reload_pool(request: Request, key: str = Depends(admin_key)) -> dict: except Exception: pass elif account.access_token != existing.access_token or account.expires_at > existing.expires_at: - # mutate under the account's refresh lock: writing the fields - # directly raced concurrent requests building headers and any - # in-flight token refresh adopted = await state.tokens.apply_credentials( existing, access_token=account.access_token, @@ -601,9 +597,6 @@ async def reload_pool(request: Request, key: str = Depends(admin_key)) -> dict: if not adopted: continue updated += 1 - # re-settle plan/balance too — a re-exported snapshot after a plan - # change (e.g. Global Build issued) must surface here, otherwise the - # dashboard keeps showing the stale plan until the poller catches up try: await state.tokens.check_account(existing) except Exception: @@ -616,6 +609,12 @@ async def reload_pool(request: Request, key: str = Depends(admin_key)) -> dict: "pool": await state.pool.snapshot()} +@router.post("/pool/reload") +async def reload_pool(request: Request, key: str = Depends(admin_key)) -> dict: + """Re-read the credential source (e.g. providers.json after a desktop login).""" + return await reload_pool_from_disk(get_state(request)) + + @router.post("/pool/persist") async def persist_pool(request: Request, key: str = Depends(admin_key)) -> dict: state = get_state(request) diff --git a/zcode_gateway/api_dash.py b/zcode_gateway/api_dash.py index 06d8e37..91be054 100644 --- a/zcode_gateway/api_dash.py +++ b/zcode_gateway/api_dash.py @@ -1484,6 +1484,26 @@ async def inspect(): proxy_types=GeneratorManager.normalize_proxy_types( gc.proxy_types, legacy_socks_only=gc.socks_only)) state.generator = mgr + + # Auto Generate used to leave qualified accounts on disk but invisible + # in the dashboard until the user pressed "Reload pool". Re-read the + # credential source once a run reaches a terminal state so the pool, + # the dashboard and the run counters always agree. + def _auto_finish_reload(status_snapshot, state=state): + if int(status_snapshot.get("qualified") or 0) <= 0: + return + try: + from .api_admin import reload_pool_from_disk + future = asyncio.run_coroutine_threadsafe( + reload_pool_from_disk(state), main_loop) + result = future.result(timeout=30) + log.info("auto generate: post-run pool reload loaded %s account(s)", + result.get("loaded")) + except Exception: + log.exception("auto generate: post-run pool reload failed") + + mgr.auto_generate.set_finish_callback(_auto_finish_reload) + # Reconcile receipts after an interrupted registration-before-progress # write. Never count arbitrary snapshots without a qualification mark. try: diff --git a/zcode_gateway/auto_generate.py b/zcode_gateway/auto_generate.py index 4729d8c..968af93 100644 --- a/zcode_gateway/auto_generate.py +++ b/zcode_gateway/auto_generate.py @@ -8,6 +8,7 @@ from __future__ import annotations import json +import logging import math import os from pathlib import Path @@ -17,6 +18,8 @@ import uuid from collections import deque +log = logging.getLogger(__name__) + DEFAULT_CONFIG = { "mode": "goal", "target": 20, "attempt_limit": 100, "concurrency": 1, @@ -140,12 +143,14 @@ class AutoGenerateController: Raw worker errors/exceptions are deliberately not persisted or exposed. """ - def __init__(self, data_dir, launch, preflight=None): + def __init__(self, data_dir, launch, preflight=None, on_finish=None): self._config_path = Path(data_dir) / "auto_generate_config.json" self._progress_path = Path(data_dir) / "auto_generate_progress.json" self._journal_path = Path(data_dir) / "auto_generate_registrations.json" self._launch = launch self._preflight = preflight + self._on_finish = on_finish + self._finish_notified_run_id = "" self._lock = threading.RLock() self._wake = threading.Event() self._thread = None @@ -168,6 +173,22 @@ def __init__(self, data_dir, launch, preflight=None): if self._status == "interrupted": self._event("Session interrupted by a gateway restart; Resume is required.", "warn") + def set_finish_callback(self, callback): + """Register a callback invoked once when a run reaches a terminal state.""" + self._on_finish = callback + + def _notify_finish(self): + """Tell the owner that result processing is done, exactly once per run.""" + callback = self._on_finish + run_id = self._run_id + if callback is None or not run_id or self._finish_notified_run_id == run_id: + return + self._finish_notified_run_id = run_id + try: + callback(self.status()) + except Exception: + log.exception("Auto Generate finish callback failed") + def _event(self, message, level="info", worker=""): self._event_seq += 1 self._events.append({"id": self._event_seq, "ts": time.time(), "level": level, @@ -690,6 +711,7 @@ def _schedule(self): self._thread = None self._stop_handles(handles) if finished: + self._notify_finish() return if launch: attempt_id, config = launch diff --git a/zcode_gateway/paths.py b/zcode_gateway/paths.py index 9b62d8f..ec56841 100644 --- a/zcode_gateway/paths.py +++ b/zcode_gateway/paths.py @@ -29,6 +29,11 @@ def base_dir() -> Path: %LOCALAPPDATA%/ZcodeGateway so a read-only install still works. A source checkout uses ignored .local/runtime instead of the source root. """ + override = os.environ.get("ZGW_DATA_DIR", "").strip() + if override: + base = Path(override).expanduser() + base.mkdir(mode=0o700, parents=True, exist_ok=True) + return base base = app_dir() if not getattr(sys, "frozen", False) and (base / ".git").is_dir(): base = base / ".local" / "runtime" From c16e8c08949088e55161417858c684fbef304c3b Mon Sep 17 00:00:00 2001 From: Esmail Sarhadi <45729949+Esmail-sarhadi@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:24:55 +0330 Subject: [PATCH 02/15] feat: add Config Doctor, themes, log colouring and HTML reports --- PR_PROPOSAL.md | 19 +- WORKBUDDY_MEMORY.md | 30 +- scripts/report/generate_html.py | 213 ++------------ tests/test_workbuddy_additions.py | 145 ++++++++++ zcode_gateway/api_dash.py | 78 +++++ zcode_gateway/config_doctor.py | 270 ++++++++++++++++++ .../dashboard/assets/css/components.css | 15 + zcode_gateway/dashboard/assets/css/tokens.css | 117 ++++++++ zcode_gateway/dashboard/assets/js/boot.js | 4 +- .../dashboard/assets/js/core/logs.js | 17 ++ .../dashboard/assets/js/core/theme.js | 25 +- .../assets/js/views/auto-generate.js | 51 +++- .../dashboard/assets/js/views/doctor.js | 149 ++++++++++ zcode_gateway/run_report.py | 214 ++++++++++++++ 14 files changed, 1140 insertions(+), 207 deletions(-) create mode 100644 zcode_gateway/config_doctor.py create mode 100644 zcode_gateway/dashboard/assets/js/core/logs.js create mode 100644 zcode_gateway/dashboard/assets/js/views/doctor.js create mode 100644 zcode_gateway/run_report.py diff --git a/PR_PROPOSAL.md b/PR_PROPOSAL.md index 62c6c6c..64ffcad 100644 --- a/PR_PROPOSAL.md +++ b/PR_PROPOSAL.md @@ -146,6 +146,23 @@ AutoZCoder هسته Gateway خوبی دارد، ولی تجربه کاربری > هیچکدام از اینها کپچا یا محدودیت IP را دور نمیزنند. +### فاز ۶ب — ۱۰ قابلیت کاربردی 다른 (درخواست دوم اسماعیل) + +همانطور که اسماعیل خواست، ۱۰ قابلیت تازه جذاب و عملی هم اضافه میشود: + +1. **رنگبندی لاگ هوشمند** — خطوط موفقیت سبز، خطا قرمز، هشدار زرد، پیشرفت آبی؛ برای live log و هر worker card یکسان. +2. **فیلتر سطح لاگ** — All / Progress / Success / Warnings / Errors با یک.select کوچک. +3. **انتخاب تم ۵گانه** — Dark, Light, Midnight, Sepia, High-contrast؛ انتخاب ذخیره میشود. +4. **گزارش HTML در داخل داشبورد** — دکمه «HTML report» در Auto Generate و در Config Doctor. +5. **Config Doctor صفحه** — همان چکلیست بالا با دکمه «Repair what is safe». +6. **Collapse finished workers** — پنهان کردن ورکرهای تمامشده با یک دکمه. +7. **جستجوی ایمیل در ورکرها** — پیدا کردن سریع یک attempt. +8. **Copy clean log** — کپی لاگ بدون secretها. +9. **Run comparison** — مقایسه دو اجرا از نظر qualified/timeout. +10. **Daily digest** — خلاصه روزانه از آخرین اجرا در بالای صفحه. + +> موارد ۱-۵ در همین برش پیادهایم; ۶-۱۰ در فاز ۶ب کامل میشوند. + --- ## 9. فاز ۷ — رفع باگهای شناختهشده @@ -180,7 +197,7 @@ AutoZCoder هسته Gateway خوبی دارد، ولی تجربه کاربری برای رسیدن به ۲۵۰۰exact، فاز ۹ (فشار/انtegration) ≈ ۱۰۰ تست اضافه میکند. -**در همین PR**: ۲۴ تست معنیدار برای فاز ۱ و رفع باگ reload و report generator اضافه میشود (همه ۲۴ تا اجرا و سبز شدند). عددسازی نمیکنم. +**در همین PR**: ۴۰ تست معنیدار برای فاز ۱، رفع باگ reload، report generator و Config Doctor اضافه میشود (همه ۴۰ تا اجرا و سبز شدند). عددسازی نمیکنم. --- diff --git a/WORKBUDDY_MEMORY.md b/WORKBUDDY_MEMORY.md index 189582e..8d97b1e 100644 --- a/WORKBUDDY_MEMORY.md +++ b/WORKBUDDY_MEMORY.md @@ -32,7 +32,7 @@ من **قابلیت جدیدی برای دور زدن کپچا / محدودیت IP / claim اکانت نمینویسم**. این بخشalready ریسک ToS/حقوقی بالایی دارد و خودم در بررسی کد به اسماعیل گفتم. کاری که میکنم: -- بهبودهای gateway، نصب، پیکربندی، لاگ،报告 HTML، UI/UX و رفع باگ میزان. +- بهبودهای gateway، نصب، پیکربندی، لاگ، گزارش HTML، UI/UX و رفع باگ میزان. - رفع باگ `auto-reload pool` (باگ واقعی ای امشب دیدیم). - تستهای معنیدار مینویسم، نه عددسازی. @@ -79,6 +79,34 @@ - report روی لاگهای واقعی اجرا شد: `run_e69a...html`، ۱۶٬۷۹۴ بایت، بدون JWT/password/cfat. - installer dry-run روی exe واقعی اجرا شد: لیست مهاجرت درست نشان داده شد، هیچ فایلی کپی نشد. +### 2026-11-29 22:15 +- `git compile` روی تمام فایلهای Python تغییریافته ok. +- `git status` تمیز شد و commit محلی زده شد: + `62939dd feat: add PR proposal, installer, HTML reports and auto-reload fix` + روی شاخه `workbuddy/pr-overhaul`. +- **push نشد**: دسترسی GitHub احراز نشده است. کاربر باید خودش push کند یا من بعد از اتصال connectorpush میکنم. + +### 2026-11-29 22:25 — درخواست دوم اسماعیل +اسماعیل خواست: رنگبندی لاگ مشخص، تمهای مختلف قابل انتخاب، ۱۰ قابلیت تازه جذاب/کاربردی. + +### 2026-11-29 22:35 +- `zcode_gateway/config_doctor.py` ساخته شد: ۱۰ چک امن (python/packages/chromium/generator/node/wrangler/cloudflare/inbox/pool/ai_judge)، بدون چاپ توکن. +- `zcode_gateway/api_dash.py` endpointها: `GET /admin/dash/doctor`, `POST /admin/dash/doctor/repair`, `GET /admin/dash/reports`, `POST /admin/dash/reports/generate`, `GET /admin/dash/reports/file/{name}`. +- `zcode_gateway/run_report.py` ساخته شد؛ اسکریپت CLI حالا wrapper آن است. +- `WORKBUDDY_MEMORY.md` و `PR_PROPOSAL.md` بهروز شدند. + +### 2026-11-29 22:45 +- ۵ تم اضافه شد: dark, light, midnight, sepia, contrast (`tokens.css` + `theme.js`). +- `core/logs.js` ساخته شد:logTone/logLineClass برای رنگبندی لاگ. +- `auto-generate.js`: رنگبندی worker lines و event lines، فیلتر سطح لاگ، دکمه HTML report. +- `views/doctor.js` ساخته و در `boot.js` ثبت شد: چکلیست، Repair،select تم، لیست report. +- ۱۰ قابلیت تازه به `PR_PROPOSAL.md` اضافه شد (فاز ۶ب). + +### 2026-11-29 22:48 +- تستها: **40 passed** (از ۲۴ به ۴۰ رسید). +- `py_compile` و `node --check`/all js ok. +- `logTone` با Node تست شد: ok/err/warn/info درست. + ## 5. مراحل پیش رو 1. نوشتن `PR_PROPOSAL.md` — درخواست خیلی کامل، فارسی، RTL، با فازبندی و مرز قانونی. diff --git a/scripts/report/generate_html.py b/scripts/report/generate_html.py index 84119fe..7cb9cc5 100644 --- a/scripts/report/generate_html.py +++ b/scripts/report/generate_html.py @@ -1,206 +1,33 @@ #!/usr/bin/env python3 -"""Generate a self-contained HTML report from Auto Generate logs. +"""CLI wrapper around :mod:`zcode_gateway.run_report`. -No third-party dependencies. Every string is redacted before it reaches the -HTML so the report is safe to share as a support attachment. +Kept as a standalone script so it can be used without starting the gateway: + + python scripts/report/generate_html.py --data-dir generator-data """ from __future__ import annotations import argparse -import html -import json -import re import sys -import time from pathlib import Path -JWT_RE = re.compile(r"\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b") -PASSWORD_RE = re.compile(r"(?im)^(Password:\s*).+$") -CAPTCHA_PARAM_RE = re.compile(r"(?i)(captcha_verify_param:\s*).+$") -QUERY_KEY_RE = re.compile(r"(?i)([?&]k=)[^&\s\"']+") -CF_TOKEN_RE = re.compile(r"\bcfat_[A-Za-z0-9_-]{8,}\b") -BEARER_RE = re.compile(r"(?i)(Bearer\s+)[A-Za-z0-9._-]{8,}") -TOKEN_JSON_RE = re.compile(r"(?i)(\"token\"\s*:\s*\")[^\"]+(\")") - - -def redact(text: str) -> str: - """Remove credentials from a log line before it is written to a report.""" - if not text: - return "" - text = JWT_RE.sub("[REDACTED_JWT]", text) - text = PASSWORD_RE.sub(r"\1[REDACTED]", text) - text = CAPTCHA_PARAM_RE.sub(r"\1[REDACTED]", text) - text = QUERY_KEY_RE.sub(r"\1[REDACTED]", text) - text = CF_TOKEN_RE.sub("[REDACTED_CF_TOKEN]", text) - text = BEARER_RE.sub(r"\1[REDACTED]", text) - text = TOKEN_JSON_RE.sub(r"\1[REDACTED]\2", text) - return text - - -def classify(text: str) -> str: - if "fully created" in text: - return "qualified" - if "SIGNUP_RATE_LIMITED" in text: - return "rate_limited" - if "Start Plan already active" in text or "Start Plan claimed" in text: - return "start_plan" - if "finish_signup: status=200" in text: - return "token_issued" - if "Captcha solved!" not in text: - return "captcha_timeout" - return "timeout" - - -def parse_worker_log(path: Path) -> dict: - raw = path.read_text(encoding="utf-8", errors="replace") - safe = redact(raw) - lines = [line.strip() for line in safe.splitlines() if line.strip()] - email = "" - for line in lines: - if line.startswith("Email: "): - email = line.split("Email: ", 1)[1].strip() - break - finish = re.findall(r"finish_signup: status=(\d+)", safe) - return { - "id": path.stem, - "file": path.name, - "email": email, - "category": classify(safe), - "captcha_solved": safe.count("Captcha solved!"), - "finish_status": finish[-1] if finish else "", - "last_lines": lines[-5:], - } - - -def load_progress(data_dir: Path) -> dict: - path = data_dir / "auto_generate_progress.json" - if not path.is_file(): - return {} - try: - value = json.loads(path.read_text(encoding="utf-8")) - return value if isinstance(value, dict) else {} - except (OSError, ValueError): - return {} - - -def _esc(value) -> str: - return html.escape(redact(str(value if value is not None else ""))) - - -def build_html(report: dict) -> str: - status = report.get("status") or "unknown" - reason = report.get("reason") or "" - counts = report.get("counts") or {} - workers = report.get("workers") or [] - events = report.get("events") or [] - config = report.get("config") or {} - - cards = "".join( - '
    %s%s
    ' - % (_esc(key), _esc(value)) - for key, value in ( - ("Status", status), ("Reason", reason or "-"), - ("Attempts", counts.get("attempts", 0)), - ("Qualified", counts.get("qualified", 0)), - ("Failed", counts.get("failed", 0)), - ) - ) - - rows = "".join( - "%s%s%s%s%s" % ( - _esc(w.get("file", "")), _esc(w.get("email", "")), - _esc(w.get("category", "")), _esc(w.get("finish_status", "")), - _esc(w.get("captcha_solved", 0)), - ) - for w in workers - ) or 'No worker logs found.' - - timeline = "".join( - '
  • %s
  • ' % ( - _esc(time.strftime("%H:%M:%S", time.localtime(float(e.get("ts", 0))))), - _esc(e.get("message", "")), - ) - for e in events[-40:] - ) or "
  • No events recorded.
  • " - - config_rows = "".join( - "
  • %s: %s
  • " % (_esc(key), _esc(value)) - for key, value in config.items() - ) - - detail_blocks = "".join( - "
    %s
    %s
    " % ( - _esc(w.get("file", "")), - _esc("\n".join(w.get("last_lines", []))), - ) - for w in workers - ) - - return """ - - -Auto Generate Report -
    -

    گزارش Auto Generate

    -
    Run: %s · produced %s
    -
    %s
    -

    وضعیت ورکرها

    %s
    لاگایمیلدستهfinishکپچا
    -

    زمانлайн

      %s
    -

    تنظیمات اجرا

      %s
    -

    آخرین خطوط لاگها

    %s -
    Every value is redacted before rendering. Safe to share as a support attachment.
    -
    """ % ( - _esc(report.get("run_id", "")), - _esc(time.strftime("%Y-%m-%d %H:%M:%S")), - cards, rows, timeline, config_rows, detail_blocks, - ) - - -def generate(data_dir: Path, run_id: str = "", out_dir: Path | None = None) -> Path: - data_dir = data_dir.expanduser().resolve() - out_dir = (out_dir or data_dir / "reports").expanduser().resolve() - out_dir.mkdir(parents=True, exist_ok=True) - - logs_dir = data_dir / "logs" / "workers" - pattern = f"auto-{run_id}*.log" if run_id else "auto-*.log" - logs = sorted(logs_dir.glob(pattern)) if logs_dir.is_dir() else [] - workers = [parse_worker_log(p) for p in logs] - - progress = load_progress(data_dir) - if run_id and progress.get("id") and not str(progress["id"]).startswith(run_id): - progress = {} - counts = dict(progress.get("counts") or {}) - if not counts: - for category in ("qualified", "token_issued", "start_plan", - "rate_limited", "captcha_timeout", "timeout"): - counts[category] = sum(1 for w in workers if w["category"] == category) - - report = { - "run_id": run_id or progress.get("id", "latest"), - "status": progress.get("status", "unknown"), - "reason": progress.get("reason", ""), - "counts": counts, - "config": progress.get("config", {}), - "events": progress.get("events", []), - "workers": workers, - } - target = out_dir / ("run_%s.html" % re.sub(r"[^A-Za-z0-9_-]", "_", str(report["run_id"]))) - target.write_text(build_html(report), encoding="utf-8") - return target +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +from zcode_gateway.run_report import ( # noqa: E402 + build_html, + classify, + generate, + list_reports, + load_progress, + parse_worker_log, + redact, +) + +__all__ = [ + "redact", "classify", "parse_worker_log", "load_progress", + "build_html", "generate", "list_reports", +] def main(argv: list[str] | None = None) -> int: diff --git a/tests/test_workbuddy_additions.py b/tests/test_workbuddy_additions.py index a3fdcaa..747ce75 100644 --- a/tests/test_workbuddy_additions.py +++ b/tests/test_workbuddy_additions.py @@ -215,3 +215,148 @@ def test_auto_finish_callback_once(tmp_path): controller._notify_finish() assert len(seen) == 1 assert seen[0]["status"] == controller.status()["status"] + + +# ---- config doctor ------------------------------------------------------- # + +def test_doctor_result_redacts(monkeypatch): + from zcode_gateway import config_doctor as cd + value = cd.result(False, "error", "cfat_abcdefgh12345678 password: hunter2") + assert "cfat_" not in str(value) + assert "hunter2" not in str(value) + + +def test_doctor_check_python_ok(monkeypatch): + from zcode_gateway import config_doctor as cd + monkeypatch.setattr(cd, "_run", lambda *a, **k: (0, "Python 3.13.0")) + assert cd.check_python()["ok"] is True + + +def test_doctor_check_python_missing(monkeypatch): + from zcode_gateway import config_doctor as cd + monkeypatch.setattr(cd, "_run", lambda *a, **k: (127, "not found")) + assert cd.check_python()["status"] == "missing" + + +def test_doctor_packages_missing(monkeypatch): + from zcode_gateway import config_doctor as cd + payload = '{"playwright": true, "ddddocr": false, "cv2": true, "httpx": true, "yaml": true}' + monkeypatch.setattr(cd, "_run", lambda *a, **k: (0, payload)) + value = cd.check_packages() + assert value["ok"] is False + assert "ddddocr" in value["detail"] + + +def test_doctor_chromium_missing(monkeypatch): + from zcode_gateway import config_doctor as cd + monkeypatch.setattr(cd, "_run", lambda *a, **k: (1, "ModuleNotFoundError")) + value = cd.check_chromium() + assert value["fixable"] is True + + +def test_doctor_generator_dir(tmp_path): + from zcode_gateway import config_doctor as cd + assert cd.check_generator_dir("")["ok"] is False + (tmp_path / "main.py").write_text("", encoding="utf-8") + assert cd.check_generator_dir(str(tmp_path))["ok"] is True + + +def test_doctor_node_missing(monkeypatch): + from zcode_gateway import config_doctor as cd + monkeypatch.setattr(cd.shutil, "which", lambda name: None) + assert cd.check_node()["status"] == "missing" + + +def test_doctor_wrangler_requires_token(): + from zcode_gateway import config_doctor as cd + value = cd.check_wrangler(False, "") + assert value["ok"] is False + assert "token" in value["hint"] + + +def test_doctor_cloudflare_scopes(monkeypatch): + from zcode_gateway import config_doctor as cd + calls = [] + + def fake(url, token=""): + calls.append(token) + if url.endswith("/accounts"): + return 200, {"success": True, "result": [{"id": "a"}]} + if "/zones" in url: + return 200, {"success": True, "result": [{"id": "z"}]} + return 200, {"success": True, "result": []} + + monkeypatch.setattr(cd, "_http_json", fake) + value = cd.check_cloudflare({"cf_api_token": "cfat_abcdefgh12345678", + "cf_account_id": "a", "domains": ["example.com"]}) + assert value["ok"] is True + assert len(calls) >= 3 + assert "cfat_" not in str(value) + + +def test_doctor_cloudflare_missing_scope(monkeypatch): + from zcode_gateway import config_doctor as cd + monkeypatch.setattr(cd, "_http_json", lambda url, token="": (403, None)) + value = cd.check_cloudflare({"cf_api_token": "x"}) + assert value["ok"] is False + assert "scope" in value["hint"] + + +def test_doctor_inbox_unauthorized(monkeypatch): + from zcode_gateway import config_doctor as cd + monkeypatch.setattr(cd, "_http_json", lambda url, token="": (401, None)) + value = cd.check_inbox({"inbox_url": "https://x.workers.dev/inbox", "inbox_secret": "s"}) + assert value["status"] == "error" + assert "secret" in value["hint"].lower() + + +def test_doctor_pool_summary(): + from zcode_gateway import config_doctor as cd + assert cd.check_pool_summary({"ready": 4, "accounts": 5})["ok"] is True + assert cd.check_pool_summary({"ready": 0, "accounts": 1})["fixable"] is True + + +def test_doctor_ai_judge_custom(): + from zcode_gateway import config_doctor as cd + assert cd.check_ai_judge({"url": "https://x/v1", "key_set": True}, None)["ok"] is True + assert cd.check_ai_judge({"url": "https://x/v1"}, None)["ok"] is False + + +def test_doctor_run_doctor_uses_checks(monkeypatch): + from types import SimpleNamespace + from zcode_gateway import config_doctor as cd + for name in ("check_python", "check_packages", "check_chromium", "check_generator_dir", + "check_node", "check_wrangler", "check_cloudflare", "check_inbox", + "check_pool_summary", "check_ai_judge"): + monkeypatch.setattr(cd, name, lambda *a, **k: cd.result(True, "ok")) + state = SimpleNamespace(cfg=SimpleNamespace(generator=SimpleNamespace( + python_exe="", zcodeauto_dir="")), generator=None) + report = cd.run_doctor(state, {}, {}) + assert report["overall"] == "ok" + assert set(report["checks"]) == {"python", "packages", "chromium", "generator", + "node", "wrangler", "cloudflare", "inbox", + "pool", "ai_judge"} + + +def test_doctor_run_doctor_blocked(monkeypatch): + from types import SimpleNamespace + from zcode_gateway import config_doctor as cd + for name in ("check_python", "check_packages", "check_chromium", "check_generator_dir", + "check_node", "check_wrangler", "check_cloudflare", "check_inbox", + "check_pool_summary", "check_ai_judge"): + monkeypatch.setattr(cd, name, lambda *a, **k: cd.result(False, "missing")) + state = SimpleNamespace(cfg=SimpleNamespace(generator=SimpleNamespace( + python_exe="", zcodeauto_dir="")), generator=None) + assert cd.run_doctor(state, {}, {})["overall"] == "blocked" + + +# ---- report inventory ---------------------------------------------------- # + +def test_list_reports(tmp_path): + from zcode_gateway.run_report import list_reports + folder = tmp_path / "reports" + folder.mkdir() + (folder / "run_a.html").write_text("x", encoding="utf-8") + rows = list_reports(tmp_path) + assert len(rows) == 1 + assert rows[0]["name"] == "run_a.html" diff --git a/zcode_gateway/api_dash.py b/zcode_gateway/api_dash.py index 91be054..b78c202 100644 --- a/zcode_gateway/api_dash.py +++ b/zcode_gateway/api_dash.py @@ -1671,6 +1671,84 @@ async def generator_mail_test(request: Request, key: str = Depends(admin_key)) - return {"ok": False, "error": f"inbox verification failed ({type(exc).__name__}); retry after deployment"} +def _generator_data_dir(request: Request) -> Path: + """Where the generator keeps logs, reports and its config.""" + state = get_state(request) + mgr = getattr(state, "generator", None) + if mgr is not None: + value = str(getattr(mgr, "data_dir", "") or "") + if value: + return Path(value) + from .paths import base_dir + return base_dir() / "generator-data" + + +@router.get("/admin/dash/doctor") +async def doctor_get(request: Request, key: str = Depends(admin_key)) -> dict: + """One-call, secret-safe health check of the whole installation.""" + from .config_doctor import run_doctor + state = get_state(request) + pool = await state.pool.snapshot() + mgr = getattr(state, "generator", None) + mail = mgr.mail_config() if mgr and hasattr(mgr, "mail_config") else {} + custom = {} + if mgr: + options = mgr.options() + custom = {"url": str(options.get("custom_ai_url") or ""), + "key_set": bool(options.get("custom_ai_key_set"))} + return await asyncio.to_thread(run_doctor, state, pool, mail, custom) + + +@router.post("/admin/dash/doctor/repair") +async def doctor_repair(request: Request, body: dict = Body(default={}), + key: str = Depends(admin_key)) -> dict: + """Apply only the repairs that are safe and reversible.""" + check = str((body or {}).get("check") or "all") + actions = [] + if check in ("all", "generator"): + try: + actions.append({"check": "generator", + "result": await generator_locate_set(request, {}, key)}) + except HTTPException as exc: + actions.append({"check": "generator", "error": str(exc.detail), + "status": exc.status_code}) + if check in ("all", "pool"): + from .api_admin import reload_pool_from_disk + actions.append({"check": "pool", + "result": await reload_pool_from_disk(get_state(request))}) + for item in actions: + if "result" not in item and "error" not in item: + item["error"] = "check is not automatically repairable; follow its hint" + return {"check": check, "actions": actions} + + +@router.get("/admin/dash/reports") +async def reports_list(request: Request, key: str = Depends(admin_key)) -> dict: + from .run_report import list_reports + return {"reports": await asyncio.to_thread(list_reports, _generator_data_dir(request))} + + +@router.post("/admin/dash/reports/generate") +async def reports_generate(request: Request, body: dict = Body(default={}), + key: str = Depends(admin_key)) -> dict: + from .run_report import generate + path = await asyncio.to_thread(generate, _generator_data_dir(request), + str((body or {}).get("run_id") or "")) + return {"name": path.name, "url": "/admin/dash/reports/file/" + path.name} + + +@router.get("/admin/dash/reports/file/{name}") +async def reports_file(request: Request, name: str, + key: str = Depends(admin_key)) -> HTMLResponse: + import re + if not re.fullmatch(r"run_[A-Za-z0-9_-]+\.html", name): + raise HTTPException(status_code=400, detail="invalid report name") + path = _generator_data_dir(request) / "reports" / name + if not path.is_file(): + raise HTTPException(status_code=404, detail="report not found") + return HTMLResponse(path.read_text(encoding="utf-8")) + + @router.get("/admin/dash/generator/status") async def generator_status(request: Request, key: str = Depends(admin_key)) -> dict: try: diff --git a/zcode_gateway/config_doctor.py b/zcode_gateway/config_doctor.py new file mode 100644 index 0000000..dc3ab39 --- /dev/null +++ b/zcode_gateway/config_doctor.py @@ -0,0 +1,270 @@ +"""Config Doctor: one-call, secret-safe health checks for the whole install. + +The dashboard used to make people guess why generation failed. This module +answers the question directly: is Python there, are the packages installed, +can Cloudflare be reached, is the inbox alive, is there a usable account? +No check ever returns a token, password, JWT or query secret. +""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import sys +import time +from pathlib import Path +from urllib.error import HTTPError, URLError +from urllib.parse import urlencode +from urllib.request import Request, urlopen + +from .run_report import redact + +TIMEOUT = 8 +REQUIRED_PACKAGES = ("playwright", "ddddocr", "cv2", "httpx", "yaml") + + +def result(ok, status, detail="", hint="", fixable=False) -> dict: + """Uniform check result. `detail` must already be redacted by the caller.""" + return { + "ok": bool(ok), + "status": status, + "detail": redact(str(detail or "")), + "hint": redact(str(hint or "")), + "fixable": bool(fixable), + } + + +def _run(argv, timeout=TIMEOUT) -> tuple[int, str]: + try: + proc = subprocess.run(argv, capture_output=True, text=True, + timeout=timeout, check=False) + return proc.returncode, (proc.stdout or "") + (proc.stderr or "") + except FileNotFoundError: + return 127, "not found" + except subprocess.TimeoutExpired: + return 124, "timed out" + except OSError as exc: + return 1, exc.__class__.__name__ + + +def _http_json(url: str, token: str = "") -> tuple[int, dict | None]: + headers = {"Accept": "application/json", "User-Agent": "zcode-doctor/1"} + if token: + headers["Authorization"] = "Bearer " + token + try: + with urlopen(Request(url, headers=headers), timeout=TIMEOUT) as response: + return response.status, json.loads(response.read().decode("utf-8", "replace")) + except HTTPError as exc: + return exc.code, None + except (URLError, ValueError, TimeoutError): + return 0, None + + +def check_python(python_exe: str = "") -> dict: + exe = python_exe.strip() or shutil.which("python") or sys.executable + code, output = _run([exe, "--version"]) + version = " ".join(output.split())[:80] + if code == 0 and version.lower().startswith("python"): + return result(True, "ok", version, + "Python 3.10+ recommended" if "Python 3." not in version else "") + return result(False, "missing" if code == 127 else "error", version, + "Install Python 3.10+ or set generator.python_exe") + + +def check_packages(python_exe: str = "") -> dict: + exe = python_exe.strip() or shutil.which("python") or sys.executable + script = ("import importlib.util,json;print(json.dumps({m:bool(importlib.util.find_spec(m)) " + "for m in %s}))" % json.dumps(list(REQUIRED_PACKAGES))) + code, output = _run([exe, "-c", script], timeout=15) + if code != 0: + return result(False, "error", output, "Python could not run the import probe") + try: + found = json.loads(output.strip().splitlines()[-1]) + except ValueError: + return result(False, "error", output, "Unexpected import probe output") + missing = [name for name, present in found.items() if not present] + if missing: + return result(False, "missing", "missing: " + ", ".join(missing), + "pip install -r generator/requirements.txt", fixable=True) + return result(True, "ok", "all required packages importable") + + +def check_chromium(python_exe: str = "") -> dict: + exe = python_exe.strip() or shutil.which("python") or sys.executable + script = ("from playwright.sync_api import sync_playwright\n" + "with sync_playwright() as p: print(p.chromium.executable_path)") + code, output = _run([exe, "-c", script], timeout=15) + if code != 0: + return result(False, "missing", output, + "Run: python -m playwright install chromium", fixable=True) + path = Path(output.strip().splitlines()[-1]) + if path.is_file(): + return result(True, "ok", str(path)) + return result(False, "missing", str(path), + "Run: python -m playwright install chromium", fixable=True) + + +def check_generator_dir(path: str = "") -> dict: + if not path: + return result(False, "missing", "not configured", + "Open Generator > Locate generator", fixable=True) + root = Path(path).expanduser() + if not root.is_dir() or not (root / "main.py").is_file(): + return result(False, "error", str(root), + "Pick the folder containing main.py", fixable=True) + return result(True, "ok", str(root)) + + +def check_node(node_exe: str = "") -> dict: + exe = node_exe.strip() or shutil.which("node") or "" + if not exe: + return result(False, "missing", "node not on PATH", + "Node.js is only needed to deploy the mail worker") + code, output = _run([exe, "--version"]) + if code == 0: + return result(True, "ok", output.strip()[:60]) + return result(False, "error", output) + + +def check_wrangler(token_set: bool = False, worker_dir: str = "") -> dict: + if not token_set: + return result(False, "missing", "no Cloudflare API token saved", + "Email setup > paste token > Save token only") + if worker_dir and not Path(worker_dir).is_dir(): + return result(False, "missing", "mail-worker files not exported", + "Click Export worker files in Email setup") + npx = shutil.which("npx") + return result(bool(npx), "ok" if npx else "missing", + "npx available" if npx else "npx not on PATH", + "" if npx else "Install Node.js") + + +def check_cloudflare(mail_cfg: dict) -> dict: + cfg = mail_cfg or {} + token = str(cfg.get("cf_api_token") or "").strip() + if not token: + return result(False, "missing", "no token saved", + "Email setup > Save token only") + account = str(cfg.get("cf_account_id") or "").strip() + domain = str(cfg.get("domains") or [""])[0] if isinstance(cfg.get("domains"), list) else "" + base = "https://api.cloudflare.com/client/v4" + probes = { + "accounts": base + "/accounts", + "zones": base + "/zones?per_page=1", + } + if account: + probes["workers"] = base + "/accounts/" + account + "/workers/scripts" + counts = {} + failures = [] + zone_id = "" + for name, url in probes.items(): + code, body = _http_json(url, token) + if code == 200 and body and body.get("success"): + rows = body.get("result") or [] + counts[name] = len(rows) if isinstance(rows, list) else 1 + if name == "zones" and isinstance(rows, list) and rows: + zone_id = str(rows[0].get("id") or "") + else: + failures.append(name + "=" + (str(code) or "unreachable")) + if domain and not zone_id: + code, body = _http_json(base + "/zones?name=" + domain, token) + if code == 200 and body and isinstance(body.get("result"), list) and body["result"]: + zone_id = str(body["result"][0].get("id") or "") + routing = "" + if zone_id and "zones" not in failures: + code, body = _http_json(base + "/zones/" + zone_id + "/email/routing", token) + if code == 200 and body and isinstance(body.get("result"), dict): + routing = "enabled" if body["result"].get("enabled") else "disabled" + detail = "probes: " + ", ".join("%s=%s" % (k, v) for k, v in counts.items()) + if routing: + detail += "; routing " + routing + if failures: + return result(False, "error", detail + "; failed " + ", ".join(failures), + "The token is missing a scope — see Email setup > How to create a Cloudflare token") + return result(True, "ok", detail) + + +def check_inbox(mail_cfg: dict) -> dict: + cfg = mail_cfg or {} + url = str(cfg.get("inbox_url") or "").strip() + secret = str(cfg.get("inbox_secret") or "").strip() + if not url or not secret: + return result(False, "missing", "inbox URL or secret not saved", + "Email setup > Advanced / manual recovery") + if "?" in url: + url = url.split("?", 1)[0] + full = url + "?" + urlencode({"k": secret}) + code, body = _http_json(full) + if code == 200: + return result(True, "ok", "inbox reachable (" + + ("array" if isinstance(body, list) else "json") + ")") + if code == 401: + return result(False, "error", "401 from worker", + "The saved secret does not match INBOX_SECRET") + return result(False, "error", "HTTP " + str(code), + "Check the worker URL ends in /inbox") + + +def check_pool_summary(pool_snapshot: dict | None) -> dict: + snap = pool_snapshot or {} + ready = int(snap.get("ready") or 0) + total = int(snap.get("accounts") or 0) + if ready > 0: + return result(True, "ok", "%d/%d accounts ready" % (ready, total)) + return result(False, "missing", "%d/%d accounts ready" % (ready, total), + "Add an account or run the generator once", fixable=True) + + +def check_ai_judge(custom: dict | None, pool_snapshot: dict | None) -> dict: + custom = custom or {} + url = str(custom.get("url") or "").strip() + key_set = bool(custom.get("key_set")) + if url and key_set: + return result(True, "ok", "custom vision endpoint configured") + if url and not key_set: + return result(False, "error", "endpoint set but key missing", + "Fill the AI judge API key") + ready = int((pool_snapshot or {}).get("ready") or 0) + if ready: + return result(True, "ok", "using this gateway's pool (%d ready)" % ready) + return result(False, "missing", "no judge endpoint and no ready account", + "Add one account first, or configure a custom vision endpoint") + + +def run_doctor(state, pool_snapshot: dict | None = None, + mail_cfg: dict | None = None, custom_judge: dict | None = None) -> dict: + """Run every check. Safe to call from a worker thread.""" + cfg = getattr(state, "cfg", None) + gen = getattr(cfg, "generator", None) + python_exe = str(getattr(gen, "python_exe", "") or "") + configured_dir = str(getattr(gen, "zcodeauto_dir", "") or "") + mgr = getattr(state, "generator", None) + if mail_cfg is None: + mail_cfg = mgr.mail_config() if mgr and hasattr(mgr, "mail_config") else {} + data_dir = "" + if mgr: + data_dir = str(getattr(mgr, "data_dir", "") or "") + checks = { + "python": check_python(python_exe), + "packages": check_packages(python_exe), + "chromium": check_chromium(python_exe), + "generator": check_generator_dir(configured_dir), + "node": check_node(), + "wrangler": check_wrangler(bool((mail_cfg or {}).get("cf_api_token")), + str(data_dir)), + "cloudflare": check_cloudflare(mail_cfg), + "inbox": check_inbox(mail_cfg), + "pool": check_pool_summary(pool_snapshot), + "ai_judge": check_ai_judge(custom_judge, pool_snapshot), + } + failed = [name for name, value in checks.items() if not value["ok"]] + blocking = {"python", "packages", "generator", "pool"} + overall = "ok" if not failed else ("blocked" if blocking & set(failed) else "attention") + return { + "generated_at": time.time(), + "overall": overall, + "failed": failed, + "checks": checks, + } diff --git a/zcode_gateway/dashboard/assets/css/components.css b/zcode_gateway/dashboard/assets/css/components.css index 8af7ff8..666c479 100644 --- a/zcode_gateway/dashboard/assets/css/components.css +++ b/zcode_gateway/dashboard/assets/css/components.css @@ -1009,6 +1009,14 @@ .logpane__line--err { color: var(--err); } .logpane__line--warn { color: var(--warn); } .logpane__line--ok { color: var(--ok); } +.logpane__line--info { color: var(--info); } +.logpane__line--muted { color: var(--fg-faint); } +.logpane__line--filter-hidden { display: none; } +.job__log .logpane__line { padding: 1px 0; border-left: 2px solid transparent; padding-left: 6px; } +.job__log .logpane__line--err { border-left-color: var(--err); background: color-mix(in srgb, var(--err-bg) 45%, transparent); } +.job__log .logpane__line--warn { border-left-color: var(--warn); } +.job__log .logpane__line--ok { border-left-color: var(--ok); } +.job__log .logpane__line--info { border-left-color: var(--info); } /* ---- empty / error ---------------------------------------------------- */ .empty { padding: var(--s-10) var(--s-6); text-align: center; } @@ -1139,3 +1147,10 @@ .text-sm { font-size: var(--text-sm); } .text-xs { font-size: var(--text-xs); } .truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + +/* ---- Config Doctor ---------------------------------------------------- */ +.doctor-wrap { display: grid; gap: var(--s-5); } +.doctor-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: var(--s-4); } +.doctor-grid .card__desc { color: var(--fg-muted); word-break: break-word; } +.doctor-summary { padding: var(--s-4); border: 1px solid var(--border); border-radius: var(--r-md); background: var(--surface); } +.doctor-reports { display: grid; gap: var(--s-2); } diff --git a/zcode_gateway/dashboard/assets/css/tokens.css b/zcode_gateway/dashboard/assets/css/tokens.css index 951aa7f..73188aa 100644 --- a/zcode_gateway/dashboard/assets/css/tokens.css +++ b/zcode_gateway/dashboard/assets/css/tokens.css @@ -164,3 +164,120 @@ --focus-ring: 0 0 0 2px var(--surface), 0 0 0 4px var(--accent); } + +/* ---- midnight: deeper blue, easy on the eyes at night ----------------- */ +:root[data-theme="midnight"] { + color-scheme: dark; + --bg: #070b16; + --bg-sunken: #040711; + --surface: #0d1424; + --surface-2: #131c30; + --surface-3: #1a2540; + --surface-hover: #17223a; + --border: #22304c; + --border-strong: #354866; + --border-subtle: #151f34; + --fg: #dbe7ff; + --fg-muted: #93a7ca; + --fg-faint: #65799f; + --fg-on-accent: #050914; + --accent: #62b6ff; + --accent-hover: #8acaff; + --accent-fg: #9ed2ff; + --accent-bg: #0e2338; + --accent-border: #1d4c73; + --ok: #52d39b; + --ok-bg: #0a2b20; + --ok-border: #1a5a43; + --warn: #f0c05a; + --warn-bg: #33270c; + --warn-border: #5e4915; + --err: #ff7b8a; + --err-bg: #35121b; + --err-border: #682839; + --info: #6cc4ff; + --info-bg: #0c2740; + --info-border: #1d4d70; + --shadow-sm: 0 1px 2px rgb(0 0 0 / 0.5); + --shadow-md: 0 4px 16px rgb(0 0 0 / 0.55); + --shadow-lg: 0 16px 48px rgb(0 0 0 / 0.65); + --focus-ring: 0 0 0 2px var(--bg), 0 0 0 4px var(--accent); +} + +/* ---- sepia: warm light, lower glare ----------------------------------- */ +:root[data-theme="sepia"] { + color-scheme: light; + --bg: #f4ecdd; + --bg-sunken: #e9deca; + --surface: #fbf6ea; + --surface-2: #f5eddb; + --surface-3: #ece1cc; + --surface-hover: #f0e6d2; + --border: #dbc9a8; + --border-strong: #c2a97c; + --border-subtle: #e9dcc3; + --fg: #392f22; + --fg-muted: #776650; + --fg-faint: #9a8970; + --fg-on-accent: #fffaf0; + --accent: #9a5b12; + --accent-hover: #834c0e; + --accent-fg: #7a470c; + --accent-bg: #f5e3c4; + --accent-border: #d8b175; + --ok: #3d6b32; + --ok-bg: #e2edd8; + --ok-border: #bcd3a9; + --warn: #8a5a00; + --warn-bg: #f7e8c4; + --warn-border: #dcc38a; + --err: #a3312f; + --err-bg: #f4dcd9; + --err-border: #dfb1ad; + --info: #2f6482; + --info-bg: #dceaf1; + --info-border: #aecbdc; + --shadow-sm: 0 1px 2px rgb(80 60 30 / 0.10); + --shadow-md: 0 4px 16px rgb(80 60 30 / 0.14); + --shadow-lg: 0 16px 48px rgb(80 60 30 / 0.20); + --focus-ring: 0 0 0 2px var(--surface), 0 0 0 4px var(--accent); +} + +/* ---- contrast: maximum separation ------------------------------------- */ +:root[data-theme="contrast"] { + color-scheme: dark; + --bg: #000000; + --bg-sunken: #000000; + --surface: #0a0a0a; + --surface-2: #141414; + --surface-3: #1e1e1e; + --surface-hover: #202020; + --border: #6a6a6a; + --border-strong: #a8a8a8; + --border-subtle: #3a3a3a; + --fg: #ffffff; + --fg-muted: #e0e0e0; + --fg-faint: #b0b0b0; + --fg-on-accent: #000000; + --accent: #ffe14d; + --accent-hover: #fff07a; + --accent-fg: #ffe14d; + --accent-bg: #2b2600; + --accent-border: #7a6b00; + --ok: #4dff88; + --ok-bg: #00220c; + --ok-border: #007a2e; + --warn: #ffcb33; + --warn-bg: #2b1e00; + --warn-border: #8a6100; + --err: #ff5c75; + --err-bg: #2b0009; + --err-border: #8a001d; + --info: #66d9ff; + --info-bg: #001d2b; + --info-border: #00607f; + --shadow-sm: none; + --shadow-md: none; + --shadow-lg: none; + --focus-ring: 0 0 0 3px #ffffff; +} diff --git a/zcode_gateway/dashboard/assets/js/boot.js b/zcode_gateway/dashboard/assets/js/boot.js index e6a3ce4..9956821 100644 --- a/zcode_gateway/dashboard/assets/js/boot.js +++ b/zcode_gateway/dashboard/assets/js/boot.js @@ -46,6 +46,8 @@ const SECTIONS = [ load: () => import("./views/logs.js") }, ]}, { group: "Configure", items: [ + { name: "doctor", title: "Config Doctor", icon: "help", poll: 0, + load: () => import("./views/doctor.js") }, { name: "settings", title: "Settings", icon: "settings", poll: 0, load: () => import("./views/settings.js") }, { name: "guide", title: "Guide", icon: "help", poll: 0, @@ -177,7 +179,7 @@ function wireLogin(onSuccess) { function wireChrome() { const themeBtn = $("#theme-toggle"); - const paintTheme = () => fill(themeBtn, icon(theme.current() === "dark" ? ICONS.sun : ICONS.moon)); + const paintTheme = () => fill(themeBtn, icon(theme.isLight() ? ICONS.moon : ICONS.sun)); themeBtn.addEventListener("click", () => { theme.toggle(); paintTheme(); }); paintTheme(); diff --git a/zcode_gateway/dashboard/assets/js/core/logs.js b/zcode_gateway/dashboard/assets/js/core/logs.js new file mode 100644 index 0000000..647db2f --- /dev/null +++ b/zcode_gateway/dashboard/assets/js/core/logs.js @@ -0,0 +1,17 @@ +// Shared log colouring. One place decides what red/yellow/green/blue means so +// the live session log and every worker card agree with each other. + +export function logTone(text = "") { + const line = String(text || ""); + if (/captcha solved|success detected|status=200|qualified|start plan|verification link received|joined the pool|\bready\b|\bpassed\b/i.test(line)) return "ok"; + if (/http error|\b429\b|exception|traceback|\berror\b|\bdead\b|unauthorized|invalid|rate.limited/i.test(line)) return "err"; + if (/failed detected|\btimeout\b|timed out|retry|cooldown|\bpending\b|cooling|slow|\bwarn/i.test(line)) return "warn"; + if (/captcha|creep|vote|attempt|launch|waiting|starting|drag|driver|poll|progress/i.test(line)) return "info"; + return ""; +} + +export function logLineClass(text = "", extra = "") { + const tone = logTone(text); + return ["logpane__line", extra, tone ? "logpane__line--" + tone : ""] + .filter(Boolean).join(" "); +} diff --git a/zcode_gateway/dashboard/assets/js/core/theme.js b/zcode_gateway/dashboard/assets/js/core/theme.js index 82ac913..d2be536 100644 --- a/zcode_gateway/dashboard/assets/js/core/theme.js +++ b/zcode_gateway/dashboard/assets/js/core/theme.js @@ -1,28 +1,43 @@ -// Theme: dark by default, light on request, persisted locally. +// Theme: persisted locally. Five looks, cycled by the header button and +// selectable from Config Doctor > Appearance. // localStorage (not sessionStorage) — a look preference should survive a restart. const STORAGE = "gw-theme"; +export const THEMES = ["dark", "light", "midnight", "sepia", "contrast"]; +export const LABELS = { + dark: "Dark", + light: "Light", + midnight: "Midnight blue", + sepia: "Sepia (warm light)", + contrast: "High contrast", +}; const root = document.documentElement; export function current() { - return root.getAttribute("data-theme") === "light" ? "light" : "dark"; + const value = root.getAttribute("data-theme"); + return THEMES.includes(value) ? value : "dark"; } export function apply(theme) { - const next = theme === "light" ? "light" : "dark"; + const next = THEMES.includes(theme) ? theme : "dark"; root.setAttribute("data-theme", next); try { localStorage.setItem(STORAGE, next); } catch (_) { /* private mode */ } return next; } export function toggle() { - return apply(current() === "dark" ? "light" : "dark"); + const index = THEMES.indexOf(current()); + return apply(THEMES[(index + 1) % THEMES.length]); +} + +export function isLight(theme = current()) { + return theme === "light" || theme === "sepia"; } export function init() { let saved = null; try { saved = localStorage.getItem(STORAGE); } catch (_) { /* private mode */ } - if (saved === "light" || saved === "dark") return apply(saved); + if (THEMES.includes(saved)) return apply(saved); const prefersLight = window.matchMedia?.("(prefers-color-scheme: light)").matches; return apply(prefersLight ? "light" : "dark"); } diff --git a/zcode_gateway/dashboard/assets/js/views/auto-generate.js b/zcode_gateway/dashboard/assets/js/views/auto-generate.js index 551cab4..83c057b 100644 --- a/zcode_gateway/dashboard/assets/js/views/auto-generate.js +++ b/zcode_gateway/dashboard/assets/js/views/auto-generate.js @@ -1,8 +1,9 @@ import { el, fill, copyText } from "../core/dom.js"; import { toast } from "../core/toast.js"; -import { api } from "../core/api.js"; +import { api, getKey } from "../core/api.js"; import { card, button, stateBadge, badge } from "../core/ui.js"; import { platform } from "../core/caps.js"; +import { logLineClass, logTone } from "../core/logs.js"; const PATH = "/admin/dash/generator/auto"; const VPN_SOURCES = ["psiphon", "surfshark"]; @@ -62,7 +63,7 @@ function workerCard(w, onStop, onRemove, onDetail) { : button({ icon: "eyeOff", title: "Remove from list", variant: "quiet", onClick: () => onRemove(w.name) }), ]), lines.length - ? el("div", { class: "job__log mono" }, lines.map((line) => el("div", { class: "logpane__line", text: line }))) + ? el("div", { class: "job__log mono" }, lines.map((line) => el("div", { class: logLineClass(line), text: line }))) : null, ]); } @@ -101,6 +102,14 @@ export function createAutoGenerate({ signal } = {}) { const logPane = el("div", { class: "logpane mono auto-log", role: "region", tabindex: 0, "aria-label": "Auto Generate live session log" }); const follow = el("input", { type: "checkbox", checked: true }); + const logFilter = el("select", { class: "select select--sm", "aria-label": "Filter log lines" }, [ + el("option", { value: "all", text: "All lines" }), + el("option", { value: "info", text: "Progress" }), + el("option", { value: "ok", text: "Success" }), + el("option", { value: "warn", text: "Warnings" }), + el("option", { value: "err", text: "Errors" }), + ]); + logFilter.addEventListener("change", () => applyLogFilter()); let lastLog = ""; const copyLog = button({ label: "Copy log", icon: "copy", onClick: async () => { const ok = await copyText(lastLog); @@ -224,6 +233,7 @@ export function createAutoGenerate({ signal } = {}) { const resumeButton = button({ label: "Resume", onClick: () => mutate("resume") }); const stopButton = button({ label: "Stop session", variant: "danger", onClick: () => mutate("stop") }); const retryButton = button({ label: "Refresh status", onClick: refresh }); + const reportButton = button({ label: "HTML report", icon: "logs", onClick: openReport }); const tuning = el("details", { class: "help-details auto-tuning" }, [ el("summary", { text: "Browser and retry settings" }), el("div", { class: "auto-fields" }, [concurrencyField, cooldownField, displayField, @@ -242,7 +252,8 @@ export function createAutoGenerate({ signal } = {}) { if (tuning.contains(event.target)) tuning.open = true; }, true); const logControls = el("div", { class: "auto-actions auto-log-controls", hidden: true }, [ - el("label", { class: "checkline" }, [follow, el("span", { text: "Follow latest" })]), copyLog, + el("label", { class: "checkline" }, [follow, el("span", { text: "Follow latest" })]), + logFilter, copyLog, ]); const logEmpty = el("p", { class: "auto-note", text: "No session events yet." }); const clearWorkers = button({ label: "Clear finished", variant: "quiet", onClick: () => clearFinishedWorkers() }); @@ -252,7 +263,7 @@ export function createAutoGenerate({ signal } = {}) { form, error, connection, el("section", { class: "auto-session", "aria-label": "Auto Generate session" }, [ el("div", { class: "auto-session-head" }, [state, progress, - el("div", { class: "auto-actions" }, [pauseButton, resumeButton, stopButton, retryButton])]), + el("div", { class: "auto-actions" }, [pauseButton, resumeButton, stopButton, retryButton, reportButton])]), profile, counts, reason, slots, el("div", { class: "auto-workers-head" }, [ el("h3", { class: "auto-subtitle", text: "Attempt workers" }), clearWorkers, @@ -400,9 +411,10 @@ export function createAutoGenerate({ signal } = {}) { if (text !== lastLog || !logPane.children.length) { const scroll = logPane.scrollTop; fill(logPane, lines.map((line, index) => el("div", { - class: "logpane__line" + ((status.events[index].level === "error") ? " logpane__line--err" - : status.events[index].level === "warn" ? " logpane__line--warn" : ""), text: line, + class: logLineClass(line, status.events[index].level === "error" ? "logpane__line--err" : ""), + data: { tone: logTone(line) }, text: line, }))); + applyLogFilter(); logPane.scrollTop = follow.checked ? logPane.scrollHeight : scroll; lastLog = text; } @@ -450,6 +462,33 @@ export function createAutoGenerate({ signal } = {}) { healthy = false; } finally { busy = ""; if (!disposed) renderControls(); } } + async function openReport() { + try { + reportButton.disabled = true; + const made = await api.post("/admin/dash/reports/generate", { run_id: runID || "" }); + const response = await fetch(made.url, { + headers: { Authorization: "Bearer " + getKey() }, signal: controller.signal, + }); + if (!response.ok) throw new Error("HTTP " + response.status); + const blob = new Blob([await response.text()], { type: "text/html" }); + const url = URL.createObjectURL(blob); + window.open(url, "_blank", "noopener,noreferrer"); + setTimeout(() => URL.revokeObjectURL(url), 60000); + toast("HTML report opened", "ok"); + } catch (exception) { + if (exception.name !== "AbortError") showError("Could not open report", exception); + } finally { + if (!disposed) reportButton.disabled = false; + } + } + + function applyLogFilter() { + const wanted = logFilter.value; + for (const line of logPane.children) { + line.hidden = wanted !== "all" && (line.dataset.tone || "") !== wanted; + } + } + async function workerDetail(worker, action) { try { const result = await api.post(`/admin/dash/generator/workers/details/${action}`, diff --git a/zcode_gateway/dashboard/assets/js/views/doctor.js b/zcode_gateway/dashboard/assets/js/views/doctor.js new file mode 100644 index 0000000..0e06f0b --- /dev/null +++ b/zcode_gateway/dashboard/assets/js/views/doctor.js @@ -0,0 +1,149 @@ +// Config Doctor: one page that answers "why isn't this working?" without +// making the user read five different tabs. No secret is ever rendered here. + +import { el, fill } from "../core/dom.js"; +import { api, getKey } from "../core/api.js"; +import { toast } from "../core/toast.js"; +import { card, button, badge } from "../core/ui.js"; +import * as theme from "../core/theme.js"; + +const DOCTOR = "/admin/dash/doctor"; +const REPORTS = "/admin/dash/reports"; + +const LABELS = { + python: "Python runtime", + packages: "Generator packages", + chromium: "Chromium browser", + generator: "Generator folder", + node: "Node.js (mail worker)", + wrangler: "Wrangler / Cloudflare credentials", + cloudflare: "Cloudflare token & routing", + inbox: "Verification inbox", + pool: "Account pool", + ai_judge: "AI judge for captcha", +}; + +function tone(status) { + if (status === "ok") return "ok"; + if (status === "error") return "err"; + if (status === "missing") return "warn"; + return ""; +} + +export function mount({ root, signal }) { + const summary = el("div", { class: "doctor-summary" }); + const checks = el("div", { class: "doctor-grid" }); + const reportBox = el("div", { class: "doctor-reports" }); + const busy = el("p", { class: "auto-note", hidden: true, text: "Checking…" }); + + const repairAll = button({ + label: "Repair what is safe", variant: "primary", + onClick: async () => { + busy.hidden = false; + try { + const result = await api.post(DOCTOR + "/repair", { check: "all" }, { signal }); + const failed = (result.actions || []).filter((a) => a.error).length; + toast(failed ? `Repaired with ${failed} manual step(s) left` : "Safe repairs applied", + failed ? "warn" : "ok"); + await refresh(); + } catch (error) { + toast("Repair failed: " + error.message, "err"); + } finally { busy.hidden = true; } + }, + }); + + const themeSelect = el("select", { + class: "select", "aria-label": "Colour theme", + on: { change: (event) => { theme.apply(event.target.value); paintTheme(); } }, + }, theme.THEMES.map((name) => el("option", { value: name, text: theme.LABELS[name] }))); + + function paintTheme() { themeSelect.value = theme.current(); } + paintTheme(); + + const appearance = card({ + title: "Appearance", + desc: "Dark, light, midnight, sepia and high-contrast. Saved on this device.", + body: el("div", { class: "row" }, [ + el("label", { class: "field__label", text: "Colour theme" }), themeSelect, + el("span", { class: "spacer" }), + button({ label: "Next theme", onClick: () => { theme.toggle(); paintTheme(); } }), + ]), + }); + + const reportGenerate = button({ + label: "Generate latest HTML report", icon: "logs", + onClick: async () => { + try { + const made = await api.post(REPORTS + "/generate", { run_id: "" }, { signal }); + const response = await fetch(made.url, { + headers: { Authorization: "Bearer " + getKey() }, signal, + }); + if (!response.ok) throw new Error("HTTP " + response.status); + const url = URL.createObjectURL(new Blob([await response.text()], { type: "text/html" })); + window.open(url, "_blank", "noopener,noreferrer"); + setTimeout(() => URL.revokeObjectURL(url), 60000); + await loadReports(); + } catch (error) { toast("Report failed: " + error.message, "err"); } + }, + }); + + async function loadReports() { + try { + const data = await api.get(REPORTS, { signal }); + const rows = data.reports || []; + fill(reportBox, rows.length + ? rows.map((row) => el("div", { class: "row row--tight" }, [ + el("span", { class: "mono text-sm", text: row.name }), + el("span", { class: "muted text-xs", text: (row.size / 1024).toFixed(1) + " KB" }), + ])) + : el("p", { class: "auto-note", text: "No HTML reports yet. Generate one from Auto Generate or here." })); + } catch (_) { /* the doctor call below reports reachability */ } + } + + function checkCard(name, value) { + const fix = value.fixable && value.status !== "ok" + ? button({ label: "Repair", variant: "quiet", onClick: async () => { + try { + await api.post(DOCTOR + "/repair", { check: name }, { signal }); + toast("Repair attempted for " + (LABELS[name] || name), "ok"); + await refresh(); + } catch (error) { toast("Repair failed: " + error.message, "err"); } + } }) + : null; + return card({ + title: LABELS[name] || name, + desc: value.detail || "", + actions: [badge(value.status || "unknown", tone(value.status)), fix], + body: value.hint ? el("p", { class: "auto-note", text: value.hint }) : el("span"), + }); + } + + async function refresh() { + try { + const data = await api.get(DOCTOR, { signal }); + fill(summary, el("div", { class: "row" }, [ + badge(data.overall === "ok" ? "Everything ready" : + data.overall === "blocked" ? "Setup blocked" : "Needs attention", + data.overall === "ok" ? "ok" : data.overall === "blocked" ? "err" : "warn"), + el("span", { class: "muted text-sm", text: (data.failed || []).length + " check(s) need work" }), + el("span", { class: "spacer" }), repairAll, + ])); + fill(checks, Object.entries(data.checks || {}).map(([name, value]) => checkCard(name, value))); + } catch (error) { + fill(summary, el("p", { class: "auto-error", text: error.message })); + } + await loadReports(); + } + + fill(root, [ + el("div", { class: "doctor-wrap" }, [ + el("h2", { class: "auto-subtitle", text: "Config Doctor" }), + el("p", { class: "auto-note", text: "From the log you sent: German locale and a small browser fingerprint were fine; the blockers were captcha timeouts and an IP rate limit. These checks tell you what is ready right now." }), + busy, summary, checks, appearance, + card({ title: "HTML reports", desc: "Redacted, printable, safe to share.", + actions: [reportGenerate], body: reportBox }), + ]), + ]); + await refresh(); + return { refresh }; +} diff --git a/zcode_gateway/run_report.py b/zcode_gateway/run_report.py new file mode 100644 index 0000000..cd22a62 --- /dev/null +++ b/zcode_gateway/run_report.py @@ -0,0 +1,214 @@ +"""Build self-contained HTML reports from Auto Generate logs. + +Every string passes through :func:`redact` before it reaches the HTML, so a +report can be shared as a support attachment without leaking credentials. +""" + +from __future__ import annotations + +import html +import json +import re +import time +from pathlib import Path + +JWT_RE = re.compile(r"\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b") +PASSWORD_RE = re.compile(r"(?i)(\b[Pp]assword:\s*)[^\s,;]+") +CAPTCHA_PARAM_RE = re.compile(r"(?i)(captcha_verify_param:\s*).+$") +QUERY_KEY_RE = re.compile(r"(?i)([?&]k=)[^&\s\"']+") +CF_TOKEN_RE = re.compile(r"\bcfat_[A-Za-z0-9_-]{8,}\b") +BEARER_RE = re.compile(r"(?i)(Bearer\s+)[A-Za-z0-9._-]{8,}") +TOKEN_JSON_RE = re.compile(r"(?i)(\"token\"\s*:\s*\")[^\"]+(\")") + + +def redact(text: str) -> str: + """Remove credentials from a log line before it is written to a report.""" + if not text: + return "" + text = JWT_RE.sub("[REDACTED_JWT]", text) + text = PASSWORD_RE.sub(r"\1[REDACTED]", text) + text = CAPTCHA_PARAM_RE.sub(r"\1[REDACTED]", text) + text = QUERY_KEY_RE.sub(r"\1[REDACTED]", text) + text = CF_TOKEN_RE.sub("[REDACTED_CF_TOKEN]", text) + text = BEARER_RE.sub(r"\1[REDACTED]", text) + return TOKEN_JSON_RE.sub(r"\1[REDACTED]\2", text) + + +def classify(text: str) -> str: + """Coarse failure category for one worker log.""" + if "fully created" in text: + return "qualified" + if "SIGNUP_RATE_LIMITED" in text: + return "rate_limited" + if "Start Plan already active" in text or "Start Plan claimed" in text: + return "start_plan" + if "finish_signup: status=200" in text: + return "token_issued" + if "Captcha solved!" not in text: + return "captcha_timeout" + return "timeout" + + +def parse_worker_log(path: Path) -> dict: + raw = path.read_text(encoding="utf-8", errors="replace") + safe = redact(raw) + lines = [line.strip() for line in safe.splitlines() if line.strip()] + email = "" + for line in lines: + if line.startswith("Email: "): + email = line.split("Email: ", 1)[1].strip() + break + finish = re.findall(r"finish_signup: status=(\d+)", safe) + return { + "id": path.stem, + "file": path.name, + "email": email, + "category": classify(safe), + "captcha_solved": safe.count("Captcha solved!"), + "finish_status": finish[-1] if finish else "", + "last_lines": lines[-5:], + } + + +def load_progress(data_dir: Path) -> dict: + path = Path(data_dir) / "auto_generate_progress.json" + if not path.is_file(): + return {} + try: + value = json.loads(path.read_text(encoding="utf-8")) + return value if isinstance(value, dict) else {} + except (OSError, ValueError): + return {} + + +def _esc(value) -> str: + return html.escape(redact(str(value if value is not None else ""))) + + +def build_html(report: dict) -> str: + status = report.get("status") or "unknown" + reason = report.get("reason") or "" + counts = report.get("counts") or {} + workers = report.get("workers") or [] + events = report.get("events") or [] + config = report.get("config") or {} + + cards = "".join( + '
    %s%s
    ' + % (_esc(key), _esc(value)) + for key, value in ( + ("Status", status), ("Reason", reason or "-"), + ("Attempts", counts.get("attempts", 0)), + ("Qualified", counts.get("qualified", 0)), + ("Failed", counts.get("failed", 0)), + ) + ) + + rows = "".join( + "%s%s%s%s%s" % ( + _esc(w.get("file", "")), _esc(w.get("email", "")), + _esc(w.get("category", "")), _esc(w.get("finish_status", "")), + _esc(w.get("captcha_solved", 0)), + ) + for w in workers + ) or 'No worker logs found.' + + timeline = "".join( + '
  • %s
  • ' % ( + _esc(time.strftime("%H:%M:%S", time.localtime(float(e.get("ts", 0))))), + _esc(e.get("message", "")), + ) + for e in events[-40:] + ) or "
  • No events recorded.
  • " + + config_rows = "".join( + "
  • %s: %s
  • " % (_esc(key), _esc(value)) + for key, value in config.items() + ) + + detail_blocks = "".join( + "
    %s
    %s
    " % ( + _esc(w.get("file", "")), _esc("\n".join(w.get("last_lines", []))), + ) + for w in workers + ) + + return """ + + +Auto Generate Report +
    +

    گزارش Auto Generate

    +
    Run: %s · produced %s
    +
    %s
    +

    وضعیت ورکرها

    %s
    لاگایمیلدستهfinishکپچا
    +

    زمانлайн

      %s
    +

    تنظیمات اجرا

      %s
    +

    آخرین خطوط لاگها

    %s +
    Every value is redacted before rendering. Safe to share as a support attachment.
    +
    """ % ( + _esc(report.get("run_id", "")), + _esc(time.strftime("%Y-%m-%d %H:%M:%S")), + cards, rows, timeline, config_rows, detail_blocks, + ) + + +def generate(data_dir: Path, run_id: str = "", out_dir: Path | None = None) -> Path: + data_dir = Path(data_dir).expanduser().resolve() + out_dir = (Path(out_dir) if out_dir else data_dir / "reports").expanduser().resolve() + out_dir.mkdir(parents=True, exist_ok=True) + + logs_dir = data_dir / "logs" / "workers" + pattern = f"auto-{run_id}*.log" if run_id else "auto-*.log" + logs = sorted(logs_dir.glob(pattern)) if logs_dir.is_dir() else [] + workers = [parse_worker_log(p) for p in logs] + + progress = load_progress(data_dir) + if run_id and progress.get("id") and not str(progress["id"]).startswith(run_id): + progress = {} + counts = dict(progress.get("counts") or {}) + if not counts: + for category in ("qualified", "token_issued", "start_plan", + "rate_limited", "captcha_timeout", "timeout"): + counts[category] = sum(1 for w in workers if w["category"] == category) + + report = { + "run_id": run_id or progress.get("id", "latest"), + "status": progress.get("status", "unknown"), + "reason": progress.get("reason", ""), + "counts": counts, + "config": progress.get("config", {}), + "events": progress.get("events", []), + "workers": workers, + } + target = out_dir / ("run_%s.html" % re.sub(r"[^A-Za-z0-9_-]", "_", str(report["run_id"]))) + target.write_text(build_html(report), encoding="utf-8") + return target + + +def list_reports(data_dir: Path) -> list[dict]: + """Newest-first report inventory for the dashboard.""" + folder = Path(data_dir) / "reports" + if not folder.is_dir(): + return [] + rows = [] + for path in folder.glob("run_*.html"): + rows.append({ + "name": path.name, + "size": path.stat().st_size, + "modified": path.stat().st_mtime, + }) + return sorted(rows, key=lambda r: r["modified"], reverse=True) From 5d3929cef2fce06b279e09fff59a2e803fc642bc Mon Sep 17 00:00:00 2001 From: Esmail Sarhadi <45729949+Esmail-sarhadi@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:34:01 +0330 Subject: [PATCH 03/15] feat: add Safe Mode, domain rotation hints, setup error guidance and build verification --- PR_PROPOSAL.md | 15 ++- WORKBUDDY_MEMORY.md | 24 +++- tests/test_workbuddy_additions.py | 68 ++++++++++- zcode_gateway/api_dash.py | 35 +++++- zcode_gateway/config_doctor.py | 13 +++ .../assets/js/views/auto-generate.js | 29 ++++- .../dashboard/assets/js/views/doctor.js | 2 + .../assets/js/views/generator/mail.js | 5 +- .../assets/js/views/generator/setup.js | 19 ++- zcode_gateway/rate_limit.py | 108 ++++++++++++++++++ 10 files changed, 302 insertions(+), 16 deletions(-) create mode 100644 zcode_gateway/rate_limit.py diff --git a/PR_PROPOSAL.md b/PR_PROPOSAL.md index 64ffcad..eff38fc 100644 --- a/PR_PROPOSAL.md +++ b/PR_PROPOSAL.md @@ -2,7 +2,7 @@ > نویسنده پیشنهاد: اسماعیل سرحدی > تاریخ: 2026-11-29 -> شاخه پیشنهادی: `workbuddy/pr-overhaul` +> شاخه پیشنهادی: `esmail/pr-overhaul` > وضعیت: **پیشنهاد فازبندیشده**. فاز ۱ در همین PR اجرا میشود؛ فازهای بعدی در PRهای جداگانه. --- @@ -101,6 +101,15 @@ AutoZCoder هسته Gateway خوبی دارد، ولی تجربه کاربری --- +## 5ب. فاز ۳ب — Safe Mode و چرخش دامنه + +- **Safe Mode**: وقتی `SIGNUP_RATE_LIMITED` دیده شود، START تا زمان آزاد شدن IP مسدود میشود و شمارش معکوس نشان داده میشود. جای دور زدن محدودیت، احترام به آن است. +- **Compliance Notice**: هشدار کوتاه داخل UI درباره قوانین سرویسدهنده. +- **چرخش دامنه**: چک/new Doctor `mail_rotation` وقتی چند دامنهRotate نشدهاند هشدار میدهد و دکمه Repair آنرا روشن میکند. دکمه «Use first» هم تعیین میکند کدام دامنه اول چرخه باشد. +- **Environment setup**: پیام خوانای فارسی برای خطای `ResolutionImpossible` روی Python 3.9. + +--- + ## 6. فاز ۴ — لاگ و گزارش HTML هوشمند ### 6.1 لاگ ساختاریافته @@ -197,7 +206,9 @@ AutoZCoder هسته Gateway خوبی دارد، ولی تجربه کاربری برای رسیدن به ۲۵۰۰exact، فاز ۹ (فشار/انtegration) ≈ ۱۰۰ تست اضافه میکند. -**در همین PR**: ۴۰ تست معنیدار برای فاز ۱، رفع باگ reload، report generator و Config Doctor اضافه میشود (همه ۴۰ تا اجرا و سبز شدند). عددسازی نمیکنم. +**در همین PR**: ۴۷ تست معنیدار برای فاز ۱، رفع باگ reload، report generator، Config Doctor، Safe Mode و چرخش دامنه اضافه میشود (همه ۴۷ تا اجرا و سبز شدند). عددسازی نمیکنم. + +نتیجه اجرای کامل سورس روی Python 3.13: **۱٬۴۶۶ تست passed، ۱۷۳ skipped**. تعدادی تست قدیمی در اجرای تکجریانی کامل، وابسته به ترتیب اجرا هستند (در اجرای جداگانه همان ماژولها سبزاند). --- diff --git a/WORKBUDDY_MEMORY.md b/WORKBUDDY_MEMORY.md index 8d97b1e..79c49ad 100644 --- a/WORKBUDDY_MEMORY.md +++ b/WORKBUDDY_MEMORY.md @@ -56,7 +56,7 @@ ### 2026-11-29 21:55 - ریپو عمومی را clone کردم در: `C:\Users\esmail\WorkBuddy AI\2026-11-29-20-04-23\AutoZcoder` -- شاخه محلی `workbuddy/pr-overhaul` ساخته شد (مرحله بعدی). +- شاخه محلی `esmail/pr-overhaul` ساخته شد (مرحله بعدی). - این فایل حافظه ساخته شد. --- @@ -66,7 +66,7 @@ - مرز قانونی در آن صریح است: قابلیت جدید برای کپچا/IP/claim نمینویسم. ### 2026-11-29 22:08 -- شاخه `workbuddy/pr-overhaul` ساخته شد. +- شاخه `esmail/pr-overhaul` ساخته شد (به درخواست اسماعیل، نام ورکبادی در PR نیامد). - باگ auto-reload رفع شد: `AutoGenerateController` حالا `on_finish` callback دارد؛ `api_dash` بعد از اتمام run با qualified>0، `reload_pool_from_disk` را صدا میزند. - `api_admin.reload_pool_from_disk` استخراج شد تا endpoint و hook از یک منطق استفاده کنند. - `scripts/report/generate_html.py` اضافه شد: گزارش HTML self-contained، با redaction کامل JWT/password/captcha/token/k=. @@ -83,7 +83,7 @@ - `git compile` روی تمام فایلهای Python تغییریافته ok. - `git status` تمیز شد و commit محلی زده شد: `62939dd feat: add PR proposal, installer, HTML reports and auto-reload fix` - روی شاخه `workbuddy/pr-overhaul`. + روی شاخه `esmail/pr-overhaul`. - **push نشد**: دسترسی GitHub احراز نشده است. کاربر باید خودش push کند یا من بعد از اتصال connectorpush میکنم. ### 2026-11-29 22:25 — درخواست دوم اسماعیل @@ -107,6 +107,24 @@ - `py_compile` و `node --check`/all js ok. - `logTone` با Node تست شد: ok/err/warn/info درست. +### 2026-11-29 23:20 — Safe Mode + درخواست تلگرام +- `rate_limit.py` ساخته شد: اسکن لاگها برای SIGNUP_RATE_LIMITED، ذخیره unlock_at، مسدود کردن START، Compliance Notice. +- Endpoint `/admin/dash/generator/rate-limit` و guard در `generator/start` و `auto/{start,resume}`. +- UI: پیام شمارش معکوس، غیرفعال شدن START، هشدار Compliance. +- چرخش دامنه: چک Doctor `mail_rotation` + Repair، دکمه «Use first»، متن راهنما. +- Environment setup: پیام فارسی برای ResolutionImpossible/Python 3.9. +- باگ جدی پیدا و رفع شد: `_generator_data_dir` دوبار تعریف شده بود و نسخه دوم با پارامتر Request، توابع قدیمی را میشکست. به `_runtime_data_dir` تغییر نام داده شد. + +### 2026-11-29 23:35 — تست و بیلد نهایی +- تستهای تازه: `47 passed`. +- سورس کامل: `1466 passed, 173 skipped` (تعدادی تست قدیمی وابسته به ترتیب اجرا؛ در اجرای جداگانه سبز). +- وابستگیها در `.venv` (Python 3.13 سیستم، tkinter ok) نصب شد. +- bun بهصورت محلی نصب شد و sidecar captcha-mint کامپایل شد. +- اگزه نهایی ساخته شد: + `C:\Users\esmail\WorkBuddy AI\2026-11-29-20-04-23\AutoZcoder\.local\dist\ZcodeGateway.exe` (90.8 MB). +- اگزه را در پوشه ایزوله با پورت 8888 اجرا و تست کردم: health=200، doctor 11 چک، rate-limit، reports، و `views/doctor.js` در باندل حضور دارد. سپس متوقفش کردم. +- نام شاخه به `esmail/pr-overhaul` تغییر یافت؛ در PR_PROPOSAL نام ورکبادی نیامد. + ## 5. مراحل پیش رو 1. نوشتن `PR_PROPOSAL.md` — درخواست خیلی کامل، فارسی، RTL، با فازبندی و مرز قانونی. diff --git a/tests/test_workbuddy_additions.py b/tests/test_workbuddy_additions.py index 747ce75..1b05c7c 100644 --- a/tests/test_workbuddy_additions.py +++ b/tests/test_workbuddy_additions.py @@ -327,7 +327,7 @@ def test_doctor_run_doctor_uses_checks(monkeypatch): from zcode_gateway import config_doctor as cd for name in ("check_python", "check_packages", "check_chromium", "check_generator_dir", "check_node", "check_wrangler", "check_cloudflare", "check_inbox", - "check_pool_summary", "check_ai_judge"): + "check_domain_rotation", "check_pool_summary", "check_ai_judge"): monkeypatch.setattr(cd, name, lambda *a, **k: cd.result(True, "ok")) state = SimpleNamespace(cfg=SimpleNamespace(generator=SimpleNamespace( python_exe="", zcodeauto_dir="")), generator=None) @@ -335,7 +335,7 @@ def test_doctor_run_doctor_uses_checks(monkeypatch): assert report["overall"] == "ok" assert set(report["checks"]) == {"python", "packages", "chromium", "generator", "node", "wrangler", "cloudflare", "inbox", - "pool", "ai_judge"} + "mail_rotation", "pool", "ai_judge"} def test_doctor_run_doctor_blocked(monkeypatch): @@ -343,7 +343,7 @@ def test_doctor_run_doctor_blocked(monkeypatch): from zcode_gateway import config_doctor as cd for name in ("check_python", "check_packages", "check_chromium", "check_generator_dir", "check_node", "check_wrangler", "check_cloudflare", "check_inbox", - "check_pool_summary", "check_ai_judge"): + "check_domain_rotation", "check_pool_summary", "check_ai_judge"): monkeypatch.setattr(cd, name, lambda *a, **k: cd.result(False, "missing")) state = SimpleNamespace(cfg=SimpleNamespace(generator=SimpleNamespace( python_exe="", zcodeauto_dir="")), generator=None) @@ -360,3 +360,65 @@ def test_list_reports(tmp_path): rows = list_reports(tmp_path) assert len(rows) == 1 assert rows[0]["name"] == "run_a.html" + + +# ---- safe mode ----------------------------------------------------------- # + +def test_rate_limit_scan_and_guard(tmp_path): + from zcode_gateway import rate_limit + logs = tmp_path / "logs" / "workers" + logs.mkdir(parents=True) + log = logs / "auto-abc.log" + log.write_text('finish_signup status=429 {"code":"SIGNUP_RATE_LIMITED",' + '"retry_after_seconds":3600,"scope":"signup:ip"}', encoding="utf-8") + state = rate_limit.scan(tmp_path) + assert state["active"] is True + assert state["scope"] == "signup:ip" + assert state["source"] == "auto-abc.log" + try: + rate_limit.guard(tmp_path) + except RuntimeError as exc: + assert "rate limit" in str(exc) + else: + raise AssertionError("guard should block while locked") + + +def test_rate_limit_expired_allows(tmp_path): + from zcode_gateway import rate_limit + (tmp_path / rate_limit.STATE_FILE).write_text( + '{"unlock_at": 1, "scope": "signup:ip", "retry_after_seconds": 1}', encoding="utf-8") + state = rate_limit.status(tmp_path) + assert state["active"] is False + rate_limit.guard(tmp_path) + + +def test_rate_limit_no_logs(tmp_path): + from zcode_gateway import rate_limit + assert rate_limit.scan(tmp_path)["active"] is False + + +def test_compliance_notice(): + from zcode_gateway.rate_limit import compliance_notice + assert "terms" in compliance_notice() + + +# ---- domain rotation ----------------------------------------------------- # + +def test_doctor_domain_rotation_off(): + from zcode_gateway.config_doctor import check_domain_rotation + value = check_domain_rotation({"domains": ["a.test", "b.test"], "rotate": False}) + assert value["ok"] is False + assert value["fixable"] is True + assert "Rotate" in value["hint"] + + +def test_doctor_domain_rotation_on(): + from zcode_gateway.config_doctor import check_domain_rotation + value = check_domain_rotation({"domains": ["a.test", "b.test"], "rotate": True}) + assert value["ok"] is True + assert "a.test" in value["detail"] + + +def test_doctor_domain_rotation_single_domain(): + from zcode_gateway.config_doctor import check_domain_rotation + assert check_domain_rotation({"domains": ["a.test"]})["ok"] is True diff --git a/zcode_gateway/api_dash.py b/zcode_gateway/api_dash.py index b78c202..10ebb2b 100644 --- a/zcode_gateway/api_dash.py +++ b/zcode_gateway/api_dash.py @@ -1490,6 +1490,11 @@ async def inspect(): # credential source once a run reaches a terminal state so the pool, # the dashboard and the run counters always agree. def _auto_finish_reload(status_snapshot, state=state): + try: + from .rate_limit import scan as scan_rate_limit + scan_rate_limit(data_dir) + except Exception: + log.exception("auto generate: rate-limit scan failed") if int(status_snapshot.get("qualified") or 0) <= 0: return try: @@ -1671,7 +1676,7 @@ async def generator_mail_test(request: Request, key: str = Depends(admin_key)) - return {"ok": False, "error": f"inbox verification failed ({type(exc).__name__}); retry after deployment"} -def _generator_data_dir(request: Request) -> Path: +def _runtime_data_dir(request: Request) -> Path: """Where the generator keeps logs, reports and its config.""" state = get_state(request) mgr = getattr(state, "generator", None) @@ -1683,6 +1688,15 @@ def _generator_data_dir(request: Request) -> Path: return base_dir() / "generator-data" +@router.get("/admin/dash/generator/rate-limit") +async def generator_rate_limit(request: Request, key: str = Depends(admin_key)) -> dict: + """Safe Mode: whether a recent IP rate-limit blocks new attempts.""" + from .rate_limit import compliance_notice, scan, status + data_dir = _runtime_data_dir(request) + scan(data_dir) + return {**status(data_dir), "notice": compliance_notice()} + + @router.get("/admin/dash/doctor") async def doctor_get(request: Request, key: str = Depends(admin_key)) -> dict: """One-call, secret-safe health check of the whole installation.""" @@ -1712,6 +1726,14 @@ async def doctor_repair(request: Request, body: dict = Body(default={}), except HTTPException as exc: actions.append({"check": "generator", "error": str(exc.detail), "status": exc.status_code}) + if check in ("all", "mail_rotation"): + try: + actions.append({"check": "mail_rotation", + "result": await generator_mail_set( + request, {"rotate": True}, key)}) + except HTTPException as exc: + actions.append({"check": "mail_rotation", "error": str(exc.detail), + "status": exc.status_code}) if check in ("all", "pool"): from .api_admin import reload_pool_from_disk actions.append({"check": "pool", @@ -1725,14 +1747,14 @@ async def doctor_repair(request: Request, body: dict = Body(default={}), @router.get("/admin/dash/reports") async def reports_list(request: Request, key: str = Depends(admin_key)) -> dict: from .run_report import list_reports - return {"reports": await asyncio.to_thread(list_reports, _generator_data_dir(request))} + return {"reports": await asyncio.to_thread(list_reports, _runtime_data_dir(request))} @router.post("/admin/dash/reports/generate") async def reports_generate(request: Request, body: dict = Body(default={}), key: str = Depends(admin_key)) -> dict: from .run_report import generate - path = await asyncio.to_thread(generate, _generator_data_dir(request), + path = await asyncio.to_thread(generate, _runtime_data_dir(request), str((body or {}).get("run_id") or "")) return {"name": path.name, "url": "/admin/dash/reports/file/" + path.name} @@ -1743,7 +1765,7 @@ async def reports_file(request: Request, name: str, import re if not re.fullmatch(r"run_[A-Za-z0-9_-]+\.html", name): raise HTTPException(status_code=400, detail="invalid report name") - path = _generator_data_dir(request) / "reports" / name + path = _runtime_data_dir(request) / "reports" / name if not path.is_file(): raise HTTPException(status_code=404, detail="report not found") return HTMLResponse(path.read_text(encoding="utf-8")) @@ -1860,6 +1882,8 @@ async def generator_start(request: Request, body: dict = Body(default={}), except (TypeError, ValueError): raise HTTPException(status_code=400, detail="count must be an integer") from None count = max(1, min(count, 10)) + from .rate_limit import guard + guard(_runtime_data_dir(request)) mgr = _generator(request) def _emit(line: str) -> None: @@ -1907,6 +1931,9 @@ async def auto_generate_save(request: Request, body: dict = Body(...), key: str async def auto_generate_action(request: Request, action: str, key: str = Depends(admin_key)) -> dict: if action not in ("start", "pause", "resume", "stop"): raise HTTPException(404, "Unknown Auto Generate action") + if action in ("start", "resume"): + from .rate_limit import guard + guard(_runtime_data_dir(request)) manager = _generator(request) controller = manager.auto_generate try: diff --git a/zcode_gateway/config_doctor.py b/zcode_gateway/config_doctor.py index dc3ab39..d697ae5 100644 --- a/zcode_gateway/config_doctor.py +++ b/zcode_gateway/config_doctor.py @@ -207,6 +207,18 @@ def check_inbox(mail_cfg: dict) -> dict: "Check the worker URL ends in /inbox") +def check_domain_rotation(mail_cfg: dict) -> dict: + cfg = mail_cfg or {} + domains = [str(d).strip().lower() for d in (cfg.get("domains") or []) if str(d).strip()] + if len(domains) < 2: + return result(True, "ok", "one domain configured") + if cfg.get("rotate") is True: + return result(True, "ok", "using " + ", ".join(domains)) + return result(False, "warn", "only the active domain receives signups", + "Email setup > turn on 'Rotate signups across all routed domains'", + fixable=True) + + def check_pool_summary(pool_snapshot: dict | None) -> dict: snap = pool_snapshot or {} ready = int(snap.get("ready") or 0) @@ -256,6 +268,7 @@ def run_doctor(state, pool_snapshot: dict | None = None, str(data_dir)), "cloudflare": check_cloudflare(mail_cfg), "inbox": check_inbox(mail_cfg), + "mail_rotation": check_domain_rotation(mail_cfg), "pool": check_pool_summary(pool_snapshot), "ai_judge": check_ai_judge(custom_judge, pool_snapshot), } diff --git a/zcode_gateway/dashboard/assets/js/views/auto-generate.js b/zcode_gateway/dashboard/assets/js/views/auto-generate.js index 83c057b..72cfca1 100644 --- a/zcode_gateway/dashboard/assets/js/views/auto-generate.js +++ b/zcode_gateway/dashboard/assets/js/views/auto-generate.js @@ -89,8 +89,12 @@ export function createAutoGenerate({ signal } = {}) { let ipChoices = []; let pickChoices = []; let poolAvailable = 0; + let rateLock = { active: false, unlock_at: 0, seconds_left: 0 }; + let countdownTimer = null; const note = el("p", { class: "auto-note", role: "status", "aria-live": "polite", text: "Loading saved configuration..." }); + const ratelimitNote = el("p", { class: "auto-error text-warn", role: "status", hidden: true }); + const complianceNote = el("p", { class: "auto-note text-sm", text: "ساخت انبوه اکانت و دور زدن محدودیتها بر خلاف قوانین سرویسدهنده است." }); const error = el("p", { class: "auto-error", role: "alert", hidden: true }); const connection = el("p", { class: "auto-error", role: "status", hidden: true }); const state = el("span"); @@ -247,6 +251,7 @@ export function createAutoGenerate({ signal } = {}) { ipBlock, tuning, el("div", { class: "auto-actions" }, [saveButton, startButton, note]), + ratelimitNote, complianceNote, ]); form.addEventListener("invalid", (event) => { if (tuning.contains(event.target)) tuning.open = true; @@ -324,7 +329,7 @@ export function createAutoGenerate({ signal } = {}) { controls.attempt_limit.setCustomValidity(!targetField.hidden && Number(controls.attempt_limit.value) < Number(controls.target.value) ? "Maximum attempts must be at least the qualified success goal." : ""); saveButton.disabled = locked || !healthy; - startButton.disabled = locked || !healthy || !saved || dirty; + startButton.disabled = locked || !healthy || !saved || dirty || !!rateLock.active; pauseButton.hidden = !["preparing", "running", "starting", "cooling"].includes(status.state); resumeButton.hidden = !["paused", "interrupted"].includes(status.state); stopButton.hidden = !live(); @@ -482,6 +487,25 @@ export function createAutoGenerate({ signal } = {}) { } } + function paintRateLimit() { + if (!rateLock.active || disposed) { ratelimitNote.hidden = true; return; } + const left = Math.max(0, Math.ceil((rateLock.unlock_at - Date.now()) / 1000)); + if (left <= 0) { rateLock.active = false; ratelimitNote.hidden = true; renderControls(); return; } + rateLock.seconds_left = left; + const until = new Date(rateLock.unlock_at).toLocaleTimeString(); + ratelimitNote.textContent = "Safe Mode: محدودیت IP تا " + until + + " (" + left + " ثانیه). تلاش جدیدی شروع نمیشود."; + ratelimitNote.hidden = false; + } + + async function loadRateLimit() { + try { + rateLock = await api.get("/admin/dash/generator/rate-limit", { signal: controller.signal }); + paintRateLimit(); + renderControls(); + } catch (_) { /* status refresh below reports reachability */ } + } + function applyLogFilter() { const wanted = logFilter.value; for (const line of logPane.children) { @@ -522,6 +546,7 @@ export function createAutoGenerate({ signal } = {}) { const version = requestVersion; pendingRefresh = (async () => { try { + await loadRateLimit(); const data = await api.get(PATH, { signal: controller.signal }); if (!disposed && version === requestVersion) paint(data); } catch (exception) { @@ -540,6 +565,7 @@ export function createAutoGenerate({ signal } = {}) { } function destroy() { disposed = true; + if (countdownTimer) { clearInterval(countdownTimer); countdownTimer = null; } controller.abort(); signal?.removeEventListener("abort", destroy); renderControls(); @@ -547,6 +573,7 @@ export function createAutoGenerate({ signal } = {}) { signal?.addEventListener("abort", destroy, { once: true }); renderIpExits(); renderControls(); + countdownTimer = setInterval(paintRateLimit, 1000); if (signal?.aborted) destroy(); else refresh(); return { node, refresh, destroy }; diff --git a/zcode_gateway/dashboard/assets/js/views/doctor.js b/zcode_gateway/dashboard/assets/js/views/doctor.js index 0e06f0b..9f6049f 100644 --- a/zcode_gateway/dashboard/assets/js/views/doctor.js +++ b/zcode_gateway/dashboard/assets/js/views/doctor.js @@ -19,6 +19,7 @@ const LABELS = { wrangler: "Wrangler / Cloudflare credentials", cloudflare: "Cloudflare token & routing", inbox: "Verification inbox", + mail_rotation: "Domain rotation", pool: "Account pool", ai_judge: "AI judge for captcha", }; @@ -139,6 +140,7 @@ export function mount({ root, signal }) { el("div", { class: "doctor-wrap" }, [ el("h2", { class: "auto-subtitle", text: "Config Doctor" }), el("p", { class: "auto-note", text: "From the log you sent: German locale and a small browser fingerprint were fine; the blockers were captcha timeouts and an IP rate limit. These checks tell you what is ready right now." }), + el("p", { class: "auto-note text-sm", text: "ساخت انبوه اکانت و دور زدن محدودیتها بر خلاف قوانین سرویسدهنده است." }), busy, summary, checks, appearance, card({ title: "HTML reports", desc: "Redacted, printable, safe to share.", actions: [reportGenerate], body: reportBox }), diff --git a/zcode_gateway/dashboard/assets/js/views/generator/mail.js b/zcode_gateway/dashboard/assets/js/views/generator/mail.js index ab2977d..74b9761 100644 --- a/zcode_gateway/dashboard/assets/js/views/generator/mail.js +++ b/zcode_gateway/dashboard/assets/js/views/generator/mail.js @@ -91,6 +91,9 @@ export function createMailCard() { multi && !m.rotate && !isActive ? button({ label: "Use for signups", disabled: state.deploying, onClick: () => setActive(domain) }) + : multi && m.rotate && !isActive + ? button({ label: "Use first", variant: "quiet", disabled: state.deploying, + onClick: () => setActive(domain) }) : null, review && deferred ? button({ label: "Review change", disabled: state.deploying, @@ -396,7 +399,7 @@ export function createMailCard() { el("span", { class: "text-sm", text: "Rotate signups across all routed domains" }), ]), el("div", { class: "field__help", text: - "Each signup picks a random domain whose routing is configured. Domains still pending are skipped." }), + "Each signup picks a random domain whose routing is configured. Domains still pending are skipped. Turn this OFF to pin one domain; 'Use first' only changes which domain starts the rotation." }), ]); const deployBtn = button({ label: "Set up email", variant: "primary", onClick: deploy }); diff --git a/zcode_gateway/dashboard/assets/js/views/generator/setup.js b/zcode_gateway/dashboard/assets/js/views/generator/setup.js index 6418c75..95c5a42 100644 --- a/zcode_gateway/dashboard/assets/js/views/generator/setup.js +++ b/zcode_gateway/dashboard/assets/js/views/generator/setup.js @@ -67,6 +67,20 @@ export function openEnvSetup({ auto = false } = {}) { const progress = el("p", { class: "field__help", role: "status", "aria-live": "polite", text: "Checking Python, packages and Chromium. This may take a few seconds..." }); + function friendlySetupError(raw) { + const text = String(raw || ""); + if (/ResolutionImpossible|dependency.conflict|Could not find a version/i.test(text)) { + return "نصب پکیجها گیر کرد: نسخه Python خیلی قدیمی است (مثلاً 3.9). " + + "ddddocr و وابستگیهایش به Python 3.10 یا بالاتر نیاز دارند. " + + "یک Python 3.10+ نصب کن و در تنظیمات Generator مسیر آن را بده، سپس دوباره Install بزن."; + } + if (/ddddocr|opencv|onnxruntime/i.test(text)) { + return "یکی از پکیجهای تشخیص کپچا نصب نشد. لاگ پایین را ببین؛ " + + "معمولاً با Python 3.10+ و تکرار Install حل میشود."; + } + return text; + } + const installBtn = button({ label: "Install missing", variant: "primary" }); const recheckBtn = button({ label: "Check again", icon: "refresh" }); const closeBtn = button({ label: "Close", variant: "ghost" }); @@ -81,7 +95,8 @@ export function openEnvSetup({ auto = false } = {}) { el("div", { class: "modal__head" }, el("div", { class: "modal__title", text: "Environment setup" })), el("div", { class: "modal__body stack" }, [ el("p", { text: "The account generator needs a real Python, its packages and a Chromium browser. " - + "Checks are read-only. Missing packages/browser downloads can be installed here; Linux OS dependencies may require the server installer." }), + + "Checks are read-only. Missing packages/browser downloads can be installed here; Linux OS dependencies may require the server installer. " + + "Use Python 3.10 or newer — Python 3.9 cannot resolve ddddocr's dependencies." }), progress, steps, logPane, errorBox, ]), el("div", { class: "modal__foot" }, [closeBtn, recheckBtn, installBtn]), @@ -133,7 +148,7 @@ export function openEnvSetup({ auto = false } = {}) { timer = null; if (auto && check.all_ok) { toast("Environment ready", "ok"); close(); } } else if (st.state === "failed") { - errorBox.textContent = st.error || "Installation failed — press Install to retry."; + errorBox.textContent = friendlySetupError(st.error || "Installation failed — press Install to retry."); errorBox.hidden = false; } } diff --git a/zcode_gateway/rate_limit.py b/zcode_gateway/rate_limit.py new file mode 100644 index 0000000..d7aa5df --- /dev/null +++ b/zcode_gateway/rate_limit.py @@ -0,0 +1,108 @@ +"""Safe Mode: remember an IP rate-limit instead of trying to evade it. + +When z.ai answers SIGNUP_RATE_LIMITED we stop starting new attempts and show +the unlock time. Nothing here rotates IPs, proxies or fingerprints. +""" + +from __future__ import annotations + +import json +import re +import time +from pathlib import Path + +STATE_FILE = "rate_limit.json" +RETRY_RE = re.compile(r"retry_after_seconds[\"':\s]+(\d+)") +SCOPE_RE = re.compile(r"scope[\"':\s]+([A-Za-z0-9_:.-]+)") + + +def _state_path(data_dir: Path) -> Path: + return Path(data_dir) / STATE_FILE + + +def scan(data_dir: Path) -> dict: + """Read worker logs and persist the newest IP rate-limit observation.""" + data_dir = Path(data_dir) + logs_dir = data_dir / "logs" / "workers" + newest = None + if logs_dir.is_dir(): + for path in list(logs_dir.glob("auto-*.log")) + list(logs_dir.glob("g*.log")): + try: + text = path.read_text(encoding="utf-8", errors="replace") + except OSError: + continue + if "SIGNUP_RATE_LIMITED" not in text: + continue + retry_match = RETRY_RE.search(text) + if not retry_match: + continue + observed = path.stat().st_mtime + if newest is None or observed > newest["observed_at"]: + scope_match = SCOPE_RE.search(text) + newest = { + "observed_at": observed, + "retry_after_seconds": int(retry_match.group(1)), + "scope": scope_match.group(1) if scope_match else "unknown", + "source": path.name, + } + path = _state_path(data_dir) + if newest is None: + if path.is_file(): + try: + previous = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + previous = {} + if previous.get("manual_until", 0) > time.time(): + return status(data_dir) + if path.is_file(): + try: + path.unlink() + except OSError: + pass + return status(data_dir) + newest["unlock_at"] = newest["observed_at"] + newest["retry_after_seconds"] + try: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(newest, ensure_ascii=True, sort_keys=True), encoding="utf-8") + except OSError: + pass + return status(data_dir) + + +def status(data_dir: Path) -> dict: + """Current Safe Mode status. Never includes tokens, emails or paths beyond a log name.""" + path = _state_path(data_dir) + record = {} + if path.is_file(): + try: + value = json.loads(path.read_text(encoding="utf-8")) + if isinstance(value, dict): + record = value + except (OSError, ValueError): + record = {} + unlock = float(record.get("unlock_at") or 0) + left = max(0, int(unlock - time.time())) + active = left > 0 + return { + "active": active, + "seconds_left": left if active else 0, + "unlock_at": unlock, + "scope": str(record.get("scope") or ""), + "retry_after_seconds": int(record.get("retry_after_seconds") or 0), + "source": str(record.get("source") or ""), + "message": ("Provider rate limit is active. No attempts can start until " + + time.strftime("%H:%M", time.localtime(unlock))) if active else "", + } + + +def guard(data_dir: Path) -> None: + """Raise RuntimeError when Safe Mode blocks a new run.""" + state = status(data_dir) + if state["active"]: + raise RuntimeError(state["message"]) + + +def compliance_notice() -> str: + return ("Auto-creating accounts, solving captchas or rotating IPs to bypass " + "provider limits may violate the service provider's terms. " + "Use this tool with accounts you are entitled to use.") From 525ae1b52b98ea89bf7ac230ac473e24884f3ddf Mon Sep 17 00:00:00 2001 From: Esmail Sarhadi <45729949+Esmail-sarhadi@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:10:07 +0330 Subject: [PATCH 04/15] feat: redesign dashboard with overview page and fix NO_PROXY crash Adds a landing Overview view (health ring, KPIs, quick actions, doctor checklist, reports, endpoints, safe-mode banner), polishes the design system (gradient hero, tinted chrome, button busy/focus states, new login overlay), and keeps all five themes consistent. Installed copies now keep data in LOCALAPPDATA via installed.flag. Fixes a startup crash where bracketed IPv6 entries in NO_PROXY made httpx raise InvalidURL. Adds meaningful tests for NO_PROXY normalisation, installed.flag pathing and the login copy. --- gui_main.py | 2 + tests/test_workbuddy_additions.py | 62 +++ zcode_gateway/app.py | 4 + .../dashboard/assets/css/components.css | 448 ++++++++++++++- zcode_gateway/dashboard/assets/css/layout.css | 31 +- zcode_gateway/dashboard/assets/css/tokens.css | 58 ++ zcode_gateway/dashboard/assets/js/boot.js | 18 +- .../dashboard/assets/js/core/icons.js | 4 + .../dashboard/assets/js/views/logs.js | 11 + .../dashboard/assets/js/views/overview.js | 515 ++++++++++++++++++ zcode_gateway/dashboard/index.html | 24 +- zcode_gateway/main.py | 3 + zcode_gateway/paths.py | 11 +- zcode_gateway/process_env.py | 16 + 14 files changed, 1158 insertions(+), 49 deletions(-) create mode 100644 zcode_gateway/dashboard/assets/js/views/overview.js diff --git a/gui_main.py b/gui_main.py index 9aa67ca..a025a34 100644 --- a/gui_main.py +++ b/gui_main.py @@ -256,6 +256,8 @@ def _offer_webview2_or_browser(url: str) -> bool: def main() -> None: global _server, _server_error + from zcode_gateway.process_env import normalize_no_proxy + normalize_no_proxy() _server = None _server_error = None _server_failed.clear() diff --git a/tests/test_workbuddy_additions.py b/tests/test_workbuddy_additions.py index 1b05c7c..9995f9e 100644 --- a/tests/test_workbuddy_additions.py +++ b/tests/test_workbuddy_additions.py @@ -202,6 +202,28 @@ def test_paths_data_dir_override(monkeypatch, tmp_path): assert paths.base_dir() == tmp_path / "custom-data" +def test_paths_installed_flag_uses_per_user_dir(monkeypatch, tmp_path): + from zcode_gateway import paths + app = tmp_path / "app" + app.mkdir() + (app / "installed.flag").write_text("", encoding="utf-8") + monkeypatch.delenv("ZGW_DATA_DIR", raising=False) + monkeypatch.setattr(paths, "app_dir", lambda: app) + monkeypatch.setattr(paths, "_per_user_dir", lambda: tmp_path / "per-user") + assert paths.base_dir() == tmp_path / "per-user" + assert (tmp_path / "per-user").is_dir() + + +def test_paths_portable_without_flag(monkeypatch, tmp_path): + from zcode_gateway import paths + app = tmp_path / "app" + app.mkdir() + monkeypatch.delenv("ZGW_DATA_DIR", raising=False) + monkeypatch.setattr(paths, "app_dir", lambda: app) + monkeypatch.setattr(paths, "_per_user_dir", lambda: tmp_path / "per-user") + assert paths.base_dir() == app + + # ---- auto finish callback ------------------------------------------------ # def test_auto_finish_callback_once(tmp_path): @@ -422,3 +444,43 @@ def test_doctor_domain_rotation_on(): def test_doctor_domain_rotation_single_domain(): from zcode_gateway.config_doctor import check_domain_rotation assert check_domain_rotation({"domains": ["a.test"]})["ok"] is True + + +# ---- NO_PROXY normalisation (httpx crash fix) ---------------------------- # + +def test_no_proxy_brackets_stripped(monkeypatch): + from zcode_gateway.process_env import normalize_no_proxy + monkeypatch.setenv("NO_PROXY", "localhost,.localhost,127.0.0.1,[::1],[2001:db8::1]:8080") + normalize_no_proxy() + assert os.environ["NO_PROXY"] == "localhost,.localhost,127.0.0.1,::1,2001:db8::1:8080" + assert "[" not in os.environ["NO_PROXY"] + + +def test_no_proxy_lowercase_variant(monkeypatch): + from zcode_gateway.process_env import normalize_no_proxy + monkeypatch.setenv("no_proxy", "[::1]") + normalize_no_proxy() + assert os.environ["no_proxy"] == "::1" + + +def test_no_proxy_untouched_without_ipv6(monkeypatch): + from zcode_gateway.process_env import normalize_no_proxy + monkeypatch.setenv("NO_PROXY", "localhost,127.0.0.1") + normalize_no_proxy() + assert os.environ["NO_PROXY"] == "localhost,127.0.0.1" + + +def test_no_proxy_missing_is_safe(monkeypatch): + from zcode_gateway.process_env import normalize_no_proxy + monkeypatch.delenv("NO_PROXY", raising=False) + monkeypatch.delenv("no_proxy", raising=False) + normalize_no_proxy() + + +def test_no_proxy_result_builds_httpx_client(monkeypatch): + httpx = pytest.importorskip("httpx") + from zcode_gateway.process_env import normalize_no_proxy + monkeypatch.setenv("NO_PROXY", "localhost,[::1]") + normalize_no_proxy() + client = httpx.Client(timeout=1) + client.close() diff --git a/zcode_gateway/app.py b/zcode_gateway/app.py index cbaede2..765485f 100644 --- a/zcode_gateway/app.py +++ b/zcode_gateway/app.py @@ -24,6 +24,7 @@ from .logbuffer import LogBuffer from .model_catalog import ModelCatalog from .pool import PoolManager, load_accounts +from .process_env import normalize_no_proxy from .ratelimit import RateLimiter from .registry import Registry from .service import ChatService @@ -220,6 +221,9 @@ def _norm_netloc(netloc: str, scheme: str) -> str: def create_app(cfg: Config | None = None) -> FastAPI: + # Do this before any httpx client is built: bracketed IPv6 NO_PROXY + # entries crash httpx's environment parser. + normalize_no_proxy() cfg = cfg or load_config() setup_logging(cfg.logging.level) diff --git a/zcode_gateway/dashboard/assets/css/components.css b/zcode_gateway/dashboard/assets/css/components.css index 666c479..de443b7 100644 --- a/zcode_gateway/dashboard/assets/css/components.css +++ b/zcode_gateway/dashboard/assets/css/components.css @@ -94,10 +94,10 @@ align-items: center; justify-content: center; gap: var(--s-3); - height: 30px; + height: 32px; padding: 0 var(--s-5); border: 1px solid var(--border-strong); - border-radius: var(--r-md); + border-radius: 8px; background: var(--surface-2); color: var(--fg); font-size: var(--text-base); @@ -106,19 +106,32 @@ user-select: none; transition: background var(--dur-1) var(--ease-out), border-color var(--dur-1) var(--ease-out), - color var(--dur-1) var(--ease-out); + color var(--dur-1) var(--ease-out), + box-shadow var(--dur-2) var(--ease-out), + transform var(--dur-1) var(--ease-out); +} +.btn:hover:not(:disabled) { + background: var(--surface-3); + border-color: var(--fg-faint); + transform: translateY(-1px); } -.btn:hover:not(:disabled) { background: var(--surface-3); border-color: var(--fg-faint); } -.btn:active:not(:disabled) { transform: translateY(0.5px); } +.btn:active:not(:disabled) { transform: translateY(0); } +.btn:focus-visible { box-shadow: var(--focus-ring); } .btn:disabled { opacity: 0.45; } .btn--primary { - background: var(--accent); - border-color: var(--accent); + background: var(--grad-brand); + border-color: transparent; color: var(--fg-on-accent); font-weight: var(--weight-semibold); + box-shadow: var(--glow-accent); +} +.btn--primary:hover:not(:disabled) { + background: var(--grad-brand); + border-color: transparent; + filter: brightness(1.07); + box-shadow: var(--glow-accent), 0 10px 28px -12px color-mix(in srgb, var(--accent) 55%, transparent); } -.btn--primary:hover:not(:disabled) { background: var(--accent-hover); border-color: var(--accent-hover); } .btn--ghost { background: transparent; border-color: var(--border); } .btn--ghost:hover:not(:disabled) { background: var(--surface-hover); } @@ -133,11 +146,31 @@ but clearly inert, with the reason in the tooltip. */ .btn.is-unavailable { opacity: 0.4; text-decoration: line-through; } -.btn--sm { height: 25px; padding: 0 var(--s-4); font-size: var(--text-sm); } -.btn--icon { width: 30px; padding: 0; } -.btn--icon.btn--sm { width: 25px; } +.btn--sm { height: 26px; padding: 0 var(--s-4); font-size: var(--text-sm); border-radius: 7px; } +.btn--lg { height: 40px; padding: 0 var(--s-7); font-size: var(--text-md); border-radius: 10px; } +.btn--icon { width: 32px; padding: 0; } +.btn--icon.btn--sm { width: 26px; } +.btn--lg.btn--icon { width: 40px; } .btn--block { width: 100%; } +/* While a request is in flight the label stays in place for width, but the + button reads as busy instead of clickable. */ +.btn[aria-busy="true"] { pointer-events: none; color: transparent; position: relative; } +.btn[aria-busy="true"] svg { opacity: 0; } +.btn[aria-busy="true"]::after { + content: ""; + position: absolute; + inset: 0; + margin: auto; + width: 14px; height: 14px; + border: 2px solid color-mix(in srgb, var(--fg) 30%, transparent); + border-top-color: var(--fg); + border-radius: 50%; + animation: spin 0.7s linear infinite; +} +.btn--primary[aria-busy="true"]::after { border-color: color-mix(in srgb, var(--fg-on-accent) 30%, transparent); border-top-color: var(--fg-on-accent); } +@keyframes spin { to { rotate: 360deg; } } + /* ---- nav item --------------------------------------------------------- */ .nav-item { display: flex; @@ -173,10 +206,12 @@ left: calc(var(--s-4) * -1); top: 50%; translate: 0 -50%; - width: 3px; height: 16px; + width: 3px; height: 18px; border-radius: var(--r-full); - background: var(--accent); + background: var(--grad-brand); } +.nav-item.is-active .nav-item__icon, +.nav-item.is-active svg { color: var(--accent-fg); } .nav-item__icon { width: 16px; height: 16px; opacity: 0.85; } .nav-item__badge { margin-left: auto; @@ -194,8 +229,9 @@ .card { background: var(--surface); border: 1px solid var(--border); - border-radius: var(--r-lg); + border-radius: var(--r-xl); overflow: hidden; + box-shadow: var(--shadow-card); } .card__head { display: flex; @@ -203,8 +239,9 @@ gap: var(--s-4); padding: var(--s-5) var(--s-6); border-bottom: 1px solid var(--border-subtle); + background: color-mix(in srgb, var(--surface-2) 42%, transparent); } -.card__title { font-size: var(--text-base); font-weight: var(--weight-semibold); } +.card__title { font-size: var(--text-base); font-weight: var(--weight-semibold); letter-spacing: -0.01em; } .card__desc { color: var(--fg-muted); font-size: var(--text-sm); } .card__body { padding: var(--s-6); } .card__body--flush { padding: 0; } @@ -218,8 +255,9 @@ .metric { background: var(--surface); border: 1px solid var(--border); - border-radius: var(--r-lg); + border-radius: var(--r-xl); padding: var(--s-5) var(--s-6); + box-shadow: var(--shadow-card); } .metric__label { color: var(--fg-muted); @@ -1066,21 +1104,22 @@ display: flex; align-items: flex-start; gap: var(--s-4); - max-width: 380px; + max-width: 400px; padding: var(--s-4) var(--s-5); border: 1px solid var(--border-strong); - border-radius: var(--r-md); - background: var(--surface-3); + border-left: 3px solid var(--accent); + border-radius: 10px; + background: var(--surface); color: var(--fg); font-size: var(--text-base); - box-shadow: var(--shadow-md); + box-shadow: var(--shadow-lg); pointer-events: auto; animation: toast-in var(--dur-3) var(--ease-out); } .toast.is-leaving { animation: toast-out var(--dur-2) var(--ease-in-out) forwards; } -.toast--ok { border-color: var(--ok-border); } -.toast--err { border-color: var(--err-border); } -.toast--warn { border-color: var(--warn-border); } +.toast--ok { border-color: var(--ok-border); border-left-color: var(--ok); } +.toast--err { border-color: var(--err-border); border-left-color: var(--err); } +.toast--warn { border-color: var(--warn-border); border-left-color: var(--warn); } .toast__dot { margin-top: 6px; } .toast__text { flex: 1; min-width: 0; word-break: break-word; } @keyframes toast-in { from { opacity: 0; translate: 0 10px; scale: 0.97; } } @@ -1094,8 +1133,10 @@ display: grid; place-items: center; padding: var(--s-6); - background: color-mix(in srgb, var(--bg-sunken) 78%, transparent); - backdrop-filter: blur(3px); + background: + radial-gradient(700px 420px at 50% 0%, color-mix(in srgb, var(--accent) 12%, transparent), transparent 70%), + color-mix(in srgb, var(--bg-sunken) 84%, transparent); + backdrop-filter: blur(6px); animation: fade-in var(--dur-2) var(--ease-out); } @keyframes fade-in { from { opacity: 0; } } @@ -1124,19 +1165,32 @@ } /* ---- login ------------------------------------------------------------ */ -.login { width: 100%; max-width: 340px; } +.login { width: 100%; max-width: 360px; } .login__head { text-align: center; margin-bottom: var(--s-7); } .login__mark { - width: 38px; height: 38px; + width: 46px; height: 46px; margin: 0 auto var(--s-5); display: grid; place-items: center; - border-radius: var(--r-lg); - background: linear-gradient(145deg, var(--accent), var(--accent-hover)); + border-radius: 13px; + background: var(--grad-brand); color: var(--fg-on-accent); font-weight: var(--weight-semibold); + font-size: var(--text-lg); + box-shadow: var(--glow-accent); } -.login__title { font-size: var(--text-lg); font-weight: var(--weight-semibold); } +.login__title { font-size: var(--text-xl); font-weight: var(--weight-semibold); letter-spacing: -0.02em; } .login__sub { margin-top: var(--s-3); color: var(--fg-muted); font-size: var(--text-sm); } +.login .card { box-shadow: var(--shadow-lg); border-color: var(--border-strong); } +.login .card__body { padding: var(--s-7); } + +.input-group { position: relative; display: flex; align-items: center; } +.input-group .input { padding-right: 44px; } +.input-group .btn { + position: absolute; + right: 4px; + top: 50%; + translate: 0 -50%; +} /* ---- utilities -------------------------------------------------------- */ .muted { color: var(--fg-muted); } @@ -1154,3 +1208,337 @@ .doctor-grid .card__desc { color: var(--fg-muted); word-break: break-word; } .doctor-summary { padding: var(--s-4); border: 1px solid var(--border); border-radius: var(--r-md); background: var(--surface); } .doctor-reports { display: grid; gap: var(--s-2); } + +/* ---- Overview --------------------------------------------------------- */ +.ov { display: flex; flex-direction: column; gap: var(--s-6); } + +.hero { + position: relative; + overflow: hidden; + border: 1px solid var(--accent-border); + border-radius: var(--r-2xl); + background: var(--grad-hero); + padding: var(--s-8) var(--s-9); + box-shadow: var(--shadow-card); +} +.hero::after { + content: ""; + position: absolute; + right: -120px; + top: -140px; + width: 420px; + height: 420px; + border-radius: 50%; + background: radial-gradient(circle, color-mix(in srgb, var(--accent-2) 22%, transparent), transparent 65%); + pointer-events: none; +} +.hero__grid { + position: relative; + z-index: 1; + display: grid; + grid-template-columns: minmax(0, 1.55fr) minmax(260px, 0.85fr); + gap: var(--s-8); + align-items: center; +} +@media (max-width: 980px) { .hero__grid { grid-template-columns: minmax(0, 1fr); } } +@media (max-width: 620px) { .hero { padding: var(--s-7) var(--s-6); } } + +.hero__eyebrow { + display: inline-flex; + align-items: center; + gap: var(--s-3); + padding: 2px var(--s-4) 2px 3px; + border: 1px solid var(--accent-border); + border-radius: var(--r-full); + background: color-mix(in srgb, var(--surface) 60%, transparent); + color: var(--fg-muted); + font-size: var(--text-xs); + font-weight: var(--weight-medium); + letter-spacing: 0.06em; + text-transform: uppercase; +} +.hero__eyebrow .dot { margin-inline-start: var(--s-2); } +.hero__title { + margin-top: var(--s-5); + font-size: clamp(24px, 3.1vw, 34px); + font-weight: var(--weight-semibold); + letter-spacing: -0.03em; + line-height: 1.12; +} +.hero__title em { + font-style: normal; + background: var(--grad-brand); + -webkit-background-clip: text; + background-clip: text; + color: transparent; +} +.hero__sub { + margin-top: var(--s-4); + max-width: 62ch; + color: var(--fg-muted); + font-size: var(--text-md); + line-height: 1.65; +} +.hero__actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--s-4); + margin-top: var(--s-7); +} +.hero__meta { + margin-top: var(--s-6); + display: flex; + flex-wrap: wrap; + gap: var(--s-2) var(--s-5); + color: var(--fg-faint); + font-size: var(--text-xs); +} + +.hero__side { + display: flex; + flex-direction: column; + gap: var(--s-5); + padding: var(--s-6); + border: 1px solid var(--border); + border-radius: var(--r-xl); + background: color-mix(in srgb, var(--surface) 74%, transparent); + backdrop-filter: blur(8px); +} +.hero__side-head { display: flex; align-items: center; gap: var(--s-5); } +.hero__side-title { font-weight: var(--weight-semibold); } +.hero__side-sub { color: var(--fg-muted); font-size: var(--text-xs); line-height: 1.5; } +.hero__side .kv { grid-template-columns: minmax(0, 1fr) auto; column-gap: var(--s-4); } +.hero__side .kv__key, .hero__side .kv__val { padding: var(--s-2) 0; font-size: var(--text-xs); } +.hero__side .kv__val { text-align: end; border-bottom: 1px solid var(--border-subtle); } + +.ring { + --pct: 0; + width: 86px; height: 86px; + flex: none; + display: grid; + place-items: center; + position: relative; + border-radius: 50%; + background: conic-gradient(var(--ring-color, var(--ok)) calc(var(--pct) * 1%), var(--ring-track) 0); + transition: background var(--dur-3) var(--ease-out); +} +.ring::before { + content: ""; + position: absolute; + inset: 7px; + border-radius: 50%; + background: var(--surface); + border: 1px solid var(--border-subtle); +} +.ring__value { + position: relative; + font-size: var(--text-lg); + font-weight: var(--weight-semibold); + letter-spacing: -0.02em; + font-variant-numeric: tabular-nums; +} +.ring--ok { --ring-color: var(--ok); } +.ring--warn { --ring-color: var(--warn); } +.ring--err { --ring-color: var(--err); } +.ring--muted { --ring-color: var(--fg-faint); } + +.kpis { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: var(--s-4); +} +@media (max-width: 1100px) { .kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); } } +@media (max-width: 460px) { .kpis { grid-template-columns: minmax(0, 1fr); } } + +.kpi { + position: relative; + overflow: hidden; + display: flex; + flex-direction: column; + gap: var(--s-3); + padding: var(--s-5) var(--s-6); + border: 1px solid var(--border); + border-radius: var(--r-xl); + background: var(--surface); + box-shadow: var(--shadow-card); +} +.kpi__top { display: flex; align-items: center; gap: var(--s-3); } +.kpi__icon { + width: 30px; height: 30px; + display: grid; place-items: center; + border-radius: 8px; + background: var(--accent-bg); + border: 1px solid var(--accent-border); + color: var(--accent-fg); + flex: none; +} +.kpi__label { + color: var(--fg-muted); + font-size: var(--text-xs); + font-weight: var(--weight-medium); + letter-spacing: 0.04em; + text-transform: uppercase; +} +.kpi__value { + font-size: var(--text-2xl); + font-weight: var(--weight-semibold); + letter-spacing: -0.02em; + line-height: 1.05; + font-variant-numeric: tabular-nums; +} +.kpi__value small { margin-left: var(--s-2); font-size: var(--text-sm); font-weight: var(--weight-medium); color: var(--fg-faint); } +.kpi__hint { color: var(--fg-faint); font-size: var(--text-xs); min-height: 1.2em; } +.kpi--ok .kpi__icon { background: var(--ok-bg); border-color: var(--ok-border); color: var(--ok); } +.kpi--warn .kpi__icon { background: var(--warn-bg); border-color: var(--warn-border); color: var(--warn); } +.kpi--err .kpi__icon { background: var(--err-bg); border-color: var(--err-border); color: var(--err); } + +.ov-grid { + display: grid; + grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr); + gap: var(--s-6); + align-items: start; +} +@media (max-width: 1040px) { .ov-grid { grid-template-columns: minmax(0, 1fr); } } +.ov-col { display: flex; flex-direction: column; gap: var(--s-6); min-width: 0; } + +.section-head { display: flex; align-items: center; gap: var(--s-4); flex-wrap: wrap; } +.section-head__title { font-size: var(--text-md); font-weight: var(--weight-semibold); letter-spacing: -0.01em; } +.section-head__desc { color: var(--fg-muted); font-size: var(--text-sm); } +.section-head .spacer { flex: 1; } + +.quick { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: var(--s-4); } +@media (max-width: 900px) { .quick { grid-template-columns: repeat(2, minmax(0, 1fr)); } } +@media (max-width: 520px) { .quick { grid-template-columns: minmax(0, 1fr); } } +.quick__item { + position: relative; + display: flex; + flex-direction: column; + align-items: flex-start; + gap: var(--s-2); + padding: var(--s-5); + border: 1px solid var(--border); + border-radius: var(--r-lg); + background: var(--surface); + color: var(--fg); + text-align: start; + transition: border-color var(--dur-1) var(--ease-out), + background var(--dur-1) var(--ease-out), + transform var(--dur-2) var(--ease-out), + box-shadow var(--dur-2) var(--ease-out); +} +.quick__item:hover { + border-color: var(--accent-border); + background: var(--grad-panel); + transform: translateY(-2px); + box-shadow: var(--shadow-md); +} +.quick__item:focus-visible { box-shadow: var(--focus-ring); } +.quick__icon { + width: 34px; height: 34px; + display: grid; place-items: center; + border-radius: 9px; + background: var(--accent-bg); + border: 1px solid var(--accent-border); + color: var(--accent-fg); + margin-bottom: var(--s-2); +} +.quick__title { font-size: var(--text-base); font-weight: var(--weight-semibold); } +.quick__desc { color: var(--fg-muted); font-size: var(--text-xs); line-height: 1.5; padding-right: var(--s-5); } +.quick__go { + position: absolute; + top: var(--s-4); + right: var(--s-4); + color: var(--fg-faint); + opacity: 0; + transition: opacity var(--dur-1) var(--ease-out), translate var(--dur-2) var(--ease-out); +} +.quick__item:hover .quick__go { opacity: 1; translate: 2px 0; } + +.checklist { display: flex; flex-direction: column; gap: var(--s-2); } +.check { + display: flex; + align-items: center; + gap: var(--s-4); + padding: var(--s-3) var(--s-4); + border: 1px solid var(--border-subtle); + border-radius: var(--r-md); + background: var(--surface-2); + font-size: var(--text-sm); +} +.check__name { font-weight: var(--weight-medium); white-space: nowrap; } +.check__detail { + min-width: 0; + margin-inline-start: auto; + color: var(--fg-faint); + font-size: var(--text-xs); + text-align: end; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.check--warn { border-color: var(--warn-border); background: color-mix(in srgb, var(--warn-bg) 55%, var(--surface)); } +.check--err { border-color: var(--err-border); background: color-mix(in srgb, var(--err-bg) 55%, var(--surface)); } +.check--all { border-style: dashed; } + +.feed { display: flex; flex-direction: column; } +.feed__row { + display: grid; + grid-template-columns: 58px minmax(0, 1fr); + gap: var(--s-4); + align-items: baseline; + padding: var(--s-3) 0; + border-bottom: 1px solid var(--border-subtle); + font-size: var(--text-xs); +} +.feed__row:last-child { border-bottom: 0; } +.feed__time { color: var(--fg-faint); font-variant-numeric: tabular-nums; } +.feed__msg { color: var(--fg-muted); line-height: 1.55; overflow-wrap: anywhere; } +.feed__msg--err { color: var(--err); } +.feed__msg--warn { color: var(--warn); } +.feed__msg--ok { color: var(--ok); } + +.report-row { + display: flex; + align-items: center; + gap: var(--s-3); + padding: var(--s-3) 0; + border-bottom: 1px solid var(--border-subtle); + font-size: var(--text-sm); +} +.report-row:last-child { border-bottom: 0; } +.report-row__name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.report-row .spacer { flex: 1; } + +.endpoints { display: grid; gap: var(--s-3); } +.endpoint { + display: flex; + align-items: center; + gap: var(--s-4); + padding: var(--s-3) var(--s-4); + border: 1px solid var(--border-subtle); + border-radius: var(--r-md); + background: var(--surface-2); + font-size: var(--text-sm); +} +.endpoint__label { color: var(--fg-muted); min-width: 74px; font-size: var(--text-xs); text-transform: uppercase; letter-spacing: 0.04em; } +.endpoint .spacer { flex: 1; } + +.ov-callout { + display: flex; + align-items: flex-start; + gap: var(--s-4); + padding: var(--s-4) var(--s-5); + border: 1px solid var(--warn-border); + border-left-width: 3px; + border-radius: var(--r-md); + background: color-mix(in srgb, var(--warn-bg) 60%, var(--surface)); + color: var(--fg); + font-size: var(--text-sm); + line-height: 1.55; +} +.ov-callout__title { font-weight: var(--weight-semibold); } +.ov-callout .text-sm { color: var(--fg-muted); } + +.ov-loading { display: grid; gap: var(--s-3); } +.ov-loading .skeleton { height: 14px; } diff --git a/zcode_gateway/dashboard/assets/css/layout.css b/zcode_gateway/dashboard/assets/css/layout.css index 6fbbf24..40203f1 100644 --- a/zcode_gateway/dashboard/assets/css/layout.css +++ b/zcode_gateway/dashboard/assets/css/layout.css @@ -11,7 +11,7 @@ display: flex; flex-direction: column; min-height: 0; - background: var(--bg-sunken); + background: var(--sidebar-tint); border-right: 1px solid var(--border); } @@ -22,13 +22,15 @@ padding: var(--s-6) var(--s-6) var(--s-5); } .brand__mark { - width: 26px; height: 26px; + width: 32px; height: 32px; display: grid; place-items: center; - border-radius: var(--r-md); - background: linear-gradient(145deg, var(--accent), var(--accent-hover)); + border-radius: 9px; + background: var(--grad-brand); color: var(--fg-on-accent); font-weight: var(--weight-semibold); - font-size: var(--text-sm); + font-size: var(--text-md); + letter-spacing: 0.02em; + box-shadow: var(--glow-accent); flex: none; } .brand__text { min-width: 0; } @@ -44,7 +46,9 @@ color: var(--fg-faint); font-size: var(--text-xs); white-space: nowrap; + transition: color var(--dur-1) var(--ease-out); } +.brand__sub:hover { color: var(--accent-fg); text-decoration: none; } .nav { flex: 1; @@ -78,6 +82,10 @@ flex-direction: column; min-width: 0; min-height: 0; + background: + radial-gradient(900px 480px at 100% -10%, color-mix(in srgb, var(--accent) 7%, transparent), transparent 60%), + radial-gradient(760px 420px at -5% 108%, color-mix(in srgb, var(--accent-2) 6%, transparent), transparent 58%), + var(--bg); } .topbar { @@ -88,14 +96,25 @@ gap: var(--s-4); padding: 0 var(--s-7); border-bottom: 1px solid var(--border); - background: var(--bg); + background: var(--topbar-tint); } .topbar__title { + display: flex; + align-items: center; + gap: var(--s-4); font-size: var(--text-md); font-weight: var(--weight-semibold); letter-spacing: -0.01em; white-space: nowrap; } +.topbar__title::before { + content: ""; + width: 3px; + height: 15px; + border-radius: var(--r-full); + background: var(--grad-brand); + flex: none; +} .topbar__spacer { flex: 1; min-width: var(--s-4); } .view { diff --git a/zcode_gateway/dashboard/assets/css/tokens.css b/zcode_gateway/dashboard/assets/css/tokens.css index 73188aa..9a7555a 100644 --- a/zcode_gateway/dashboard/assets/css/tokens.css +++ b/zcode_gateway/dashboard/assets/css/tokens.css @@ -281,3 +281,61 @@ --shadow-lg: none; --focus-ring: 0 0 0 3px #ffffff; } + +/* ---- brand extension --------------------------------------------------- + Two-stop accent used by large surfaces (hero, primary buttons, marks). + Declared per theme so every look keeps its own voice instead of tinting + one shared violet. */ +:root, +:root[data-theme="dark"] { + --accent-2: #b18cff; + --ring-track: #1c2230; +} +:root[data-theme="light"] { + --accent-2: #7c5cff; + --ring-track: #e7eaf2; +} +:root[data-theme="midnight"] { + --accent-2: #9a86ff; + --ring-track: #142038; +} +:root[data-theme="sepia"] { + --accent-2: #b7791f; + --ring-track: #eadcc4; +} +:root[data-theme="contrast"] { + --accent-2: #fff3a3; + --ring-track: #2a2a2a; +} + +:root { + --r-2xl: 18px; + + --grad-brand: linear-gradient(135deg, var(--accent) 0%, var(--accent-2) 100%); + --grad-hero: + radial-gradient(120% 170% at 0% 0%, color-mix(in srgb, var(--accent) 22%, transparent) 0%, transparent 55%), + radial-gradient(100% 150% at 100% 0%, color-mix(in srgb, var(--accent-2) 16%, transparent) 0%, transparent 52%), + linear-gradient(180deg, color-mix(in srgb, var(--accent) 7%, var(--surface)) 0%, var(--surface) 72%); + --grad-panel: linear-gradient(180deg, color-mix(in srgb, var(--surface-2) 72%, transparent), var(--surface)); + --glow-accent: 0 6px 22px color-mix(in srgb, var(--accent) 26%, transparent); + --glow-soft: 0 0 0 1px color-mix(in srgb, var(--accent) 16%, transparent), + 0 10px 32px color-mix(in srgb, var(--accent) 10%, transparent); + --shadow-card: 0 1px 2px rgb(0 0 0 / 0.18), 0 12px 32px -20px rgb(0 0 0 / 0.35); + --topbar-tint: color-mix(in srgb, var(--bg) 84%, transparent); + --sidebar-tint: linear-gradient(180deg, color-mix(in srgb, var(--bg-sunken) 90%, var(--accent) 10%), var(--bg-sunken)); +} + +:root[data-theme="light"], +:root[data-theme="sepia"] { + --shadow-card: 0 1px 2px rgb(16 22 32 / 0.05), 0 12px 30px -22px rgb(16 22 32 / 0.28); + --topbar-tint: color-mix(in srgb, var(--bg) 88%, transparent); +} + +:root[data-theme="contrast"] { + --glow-accent: none; + --glow-soft: none; + --shadow-card: none; + --topbar-tint: var(--bg); + --sidebar-tint: var(--bg-sunken); + --grad-hero: var(--surface); +} diff --git a/zcode_gateway/dashboard/assets/js/boot.js b/zcode_gateway/dashboard/assets/js/boot.js index 9956821..43c3448 100644 --- a/zcode_gateway/dashboard/assets/js/boot.js +++ b/zcode_gateway/dashboard/assets/js/boot.js @@ -17,6 +17,8 @@ let signedIn = false; // Order here is the order in the sidebar. const SECTIONS = [ { group: "Operate", items: [ + { name: "overview", title: "Overview", icon: "home", poll: 10000, + load: () => import("./views/overview.js") }, { name: "accounts", title: "Accounts", icon: "accounts", poll: 6000, load: () => import("./views/accounts.js") }, { name: "models", title: "Models", icon: "models", poll: 8000, @@ -157,7 +159,7 @@ function wireLogin(onSuccess) { const previous = getKey(); setKey(input.value); btn.disabled = true; - btn.textContent = "Checking…"; + btn.setAttribute("aria-busy", "true"); if (await probe()) { input.value = ""; $("#login-error").hidden = true; @@ -171,7 +173,19 @@ function wireLogin(onSuccess) { input.select(); } btn.disabled = false; - btn.textContent = "Continue"; + btn.removeAttribute("aria-busy"); + }); + + const reveal = $("#login-reveal"); + fill(reveal, icon(ICONS.eye, 14)); + reveal.addEventListener("click", () => { + const input = $("#login-key"); + const show = input.type === "password"; + input.type = show ? "text" : "password"; + reveal.setAttribute("aria-label", show ? "Hide admin key" : "Show admin key"); + reveal.title = show ? "Hide key" : "Show key"; + fill(reveal, icon(show ? ICONS.eyeOff : ICONS.eye, 14)); + input.focus(); }); } diff --git a/zcode_gateway/dashboard/assets/js/core/icons.js b/zcode_gateway/dashboard/assets/js/core/icons.js index fcd4861..2e0bd8e 100644 --- a/zcode_gateway/dashboard/assets/js/core/icons.js +++ b/zcode_gateway/dashboard/assets/js/core/icons.js @@ -3,6 +3,10 @@ export const ICONS = { dot: "M12 12h.01", + home: ["M4.5 10.5 12 4l7.5 6.5", "M6.5 9.5V20h11V9.5", "M10 20v-5.5h4V20"], + arrowRight: ["M4 12h15", "M13 6l6 6-6 6"], + shield: ["M12 3 19 6v5.5c0 4.3-2.9 7.4-7 9-4.1-1.6-7-4.7-7-9V6z", "M8.8 12l2.2 2.2 4.2-4.4"], + file: ["M6 3h8l4 4v14H6z", "M14 3v4h4", "M9 13h6", "M9 17h6"], server: ["M4 5.5h16v5H4z", "M4 13.5h16v5H4z", "M7.5 8h.01", "M7.5 16h.01"], accounts: ["M16 19v-1.5a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4V19", "M9 9.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7", "M22 19v-1.5a4 4 0 0 0-3-3.87", "M16 2.63a4 4 0 0 1 0 7.75"], bolt: "M13 2 4.5 13.5H11l-1 8.5 8.5-11.5H12z", diff --git a/zcode_gateway/dashboard/assets/js/views/logs.js b/zcode_gateway/dashboard/assets/js/views/logs.js index b659769..3ea9c80 100644 --- a/zcode_gateway/dashboard/assets/js/views/logs.js +++ b/zcode_gateway/dashboard/assets/js/views/logs.js @@ -81,6 +81,17 @@ export async function mount({ root, signal }) { const ok = await copyText(text); toast(ok ? "Logs copied" : "Could not copy", ok ? "ok" : "err", 1600); } }), + button({ label: "Download", icon: "download", onClick: () => { + if (!records.length) { toast("Nothing to download", "warn", 1600); return; } + const text = records.map((r) => [r.time, r.level, r.logger + ":", r.message].join(" ")).join("\n"); + const name = "zcode-gateway-" + new Date().toISOString().replace(/[:.]/g, "-") + ".log"; + const url = URL.createObjectURL(new Blob([text], { type: "text/plain" })); + const link = el("a", { href: url, download: name }); + document.body.append(link); + link.click(); + link.remove(); + setTimeout(() => URL.revokeObjectURL(url), 5000); + } }), clearBtn, ])); diff --git a/zcode_gateway/dashboard/assets/js/views/overview.js b/zcode_gateway/dashboard/assets/js/views/overview.js new file mode 100644 index 0000000..b2ab27d --- /dev/null +++ b/zcode_gateway/dashboard/assets/js/views/overview.js @@ -0,0 +1,515 @@ +// Overview: the one screen that answers "is everything healthy, and what do I +// do next?" without visiting five tabs. Every panel loads its own endpoint, so +// one slow or failing source degrades that panel alone instead of the page. + +import { el, fill, icon } from "../core/dom.js"; +import { api, getKey } from "../core/api.js"; +import { toast } from "../core/toast.js"; +import { card, button, copyable } from "../core/ui.js"; +import { num, bytes, duration, dateTime } from "../core/format.js"; +import { compactNumber } from "../core/chart.js"; +import { ICONS } from "../core/icons.js"; +import * as router from "../core/router.js"; + +const CHECK_LABELS = { + python: "Python runtime", + packages: "Generator packages", + chromium: "Chromium browser", + generator: "Generator folder", + node: "Node.js (mail worker)", + wrangler: "Wrangler / Cloudflare", + cloudflare: "Cloudflare token & routing", + inbox: "Verification inbox", + mail_rotation: "Domain rotation", + pool: "Account pool", + ai_judge: "AI judge for captcha", +}; + +const QUICK = [ + { title: "Accounts", desc: "Pool health, JWT refresh and balances.", icon: "accounts", route: "accounts" }, + { title: "Manual signup", desc: "One account, step by step, with live logs.", icon: "bolt", route: "generator" }, + { title: "Auto Generate", desc: "Batch runs, worker output and HTML reports.", icon: "terminal", route: "generator/auto" }, + { title: "IP routes", desc: "Proxy pool and VPN exits for outbound traffic.", icon: "swap", route: "proxy" }, + { title: "Config Doctor", desc: "Eleven checks with safe one-click repairs.", icon: "shield", route: "doctor" }, + { title: "Analytics", desc: "Requests, tokens, latency and error breakdown.", icon: "chart", route: "analytics" }, +]; + +const reportUrl = (name) => "/admin/dash/reports/file/" + encodeURIComponent(name); + +async function openReport(name) { + const response = await fetch(reportUrl(name), { headers: { Authorization: "Bearer " + getKey() } }); + if (!response.ok) throw new Error("HTTP " + response.status); + const url = URL.createObjectURL(new Blob([await response.text()], { type: "text/html" })); + window.open(url, "_blank", "noopener,noreferrer"); + setTimeout(() => URL.revokeObjectURL(url), 60000); +} + +export async function mount({ root, signal }) { + // ---- hero ------------------------------------------------------------- + const heroVersion = el("span", { text: "starting…" }); + const heroRing = el("div", { class: "ring ring--muted", role: "img", "aria-label": "Health" }); + const heroPct = el("span", { class: "ring__value", text: "—" }); + heroRing.append(heroPct); + const heroDetail = el("p", { class: "hero__side-sub", text: "Waiting for the first health report." }); + const kvGateway = el("span", { class: "muted", text: "checking…" }); + const kvPool = el("span", { class: "muted", text: "—" }); + const kvZcode = el("span", { class: "muted", text: "—" }); + const kvVersion = el("span", { class: "muted", text: "—" }); + const updated = el("span", { text: "never" }); + + const healthBtn = button({ + label: "Run health check", icon: "shield", variant: "primary", size: "lg", + onClick: () => runHealthCheck(), + }); + const accountsBtn = button({ + label: "Open Accounts", icon: "accounts", variant: "ghost", size: "lg", + onClick: () => router.navigate("accounts"), + }); + const logsBtn = button({ + label: "View logs", icon: "logs", variant: "quiet", size: "lg", + onClick: () => router.navigate("logs"), + }); + + const hero = el("section", { class: "hero", "aria-label": "Gateway status" }, [ + el("div", { class: "hero__grid" }, [ + el("div", {}, [ + el("span", { class: "hero__eyebrow" }, [ + el("span", { class: "dot dot--ok dot--live" }), + el("span", { text: "Zcode Gateway · " }), + heroVersion, + ]), + el("h2", { class: "hero__title" }, [ + "Your models, pool and reports ", + el("em", { text: "at a glance" }), + ".", + ]), + el("p", { + class: "hero__sub", + text: "An OpenAI- and Anthropic-compatible relay for Z.ai, running on this machine. " + + "Check health, jump into a task, or hand a redacted HTML report to someone else.", + }), + el("div", { class: "hero__actions" }, [healthBtn, accountsBtn, logsBtn]), + el("div", { class: "hero__meta" }, [ + el("span", { text: "Local admin console" }), + el("span", { text: "·" }), + el("span", { text: "API on /v1 and /v1/messages" }), + el("span", { text: "·" }), + el("span", { text: "Updated " }), + updated, + ]), + ]), + el("div", { class: "hero__side" }, [ + el("div", { class: "hero__side-head" }, [ + heroRing, + el("div", {}, [ + el("div", { class: "hero__side-title", text: "System health" }), + heroDetail, + ]), + ]), + el("div", { class: "kv" }, [ + el("span", { class: "kv__key", text: "Gateway" }), el("span", { class: "kv__val" }, kvGateway), + el("span", { class: "kv__key", text: "Pool" }), el("span", { class: "kv__val" }, kvPool), + el("span", { class: "kv__key", text: "Zcode app" }), el("span", { class: "kv__val" }, kvZcode), + el("span", { class: "kv__key", text: "Version" }), el("span", { class: "kv__val" }, kvVersion), + ]), + ]), + ]), + ]); + + // ---- alerts, KPIs, grids --------------------------------------------- + const alerts = el("div", { class: "stack stack--tight" }); + const kpis = el("div", { class: "kpis", "aria-live": "polite" }); + + const quickGrid = el("div", { class: "quick" }, QUICK.map((item) => + el("button", { + class: "quick__item", type: "button", title: item.title, + on: { click: () => router.navigate(item.route) }, + }, [ + el("span", { class: "quick__icon" }, iconFor(item.icon)), + el("span", { class: "quick__title", text: item.title }), + el("span", { class: "quick__desc", text: item.desc }), + el("span", { class: "quick__go", "aria-hidden": "true" }, iconFor("arrowRight", 14)), + ]))); + const quickCard = card({ + title: "Quick actions", + desc: "The six places people open most, one click away.", + body: quickGrid, + }); + + const healthBody = el("div", { class: "checklist" }, loadingLines(4)); + const doctorLink = button({ + label: "Open doctor", icon: "shield", variant: "quiet", + onClick: () => router.navigate("doctor"), + }); + const repairBtn = button({ + label: "Repair safe", icon: "refresh", variant: "ghost", + onClick: () => repairSafe(), + }); + const healthCard = card({ + title: "Health check", + desc: "Local runtime, folders, pool and mail setup.", + actions: [repairBtn, doctorLink], + body: healthBody, + }); + + const activityBody = el("div", { class: "feed" }, loadingLines(5)); + const activityCard = card({ + title: "Recent activity", + desc: "Newest log lines from the gateway process.", + actions: [button({ label: "All logs", icon: "logs", variant: "quiet", onClick: () => router.navigate("logs") })], + body: activityBody, + }); + + const reportsBody = el("div", {}, loadingLines(3)); + const reportBtn = button({ + label: "Generate report", icon: "logs", variant: "primary", + onClick: (event) => generateReport(event.currentTarget), + }); + const reportsCard = card({ + title: "HTML reports", + desc: "Redacted run reports, safe to share or print.", + actions: [reportBtn], + body: reportsBody, + }); + + const endpointsBody = el("div", { class: "endpoints" }, loadingLines(3)); + const endpointsCard = card({ + title: "Client endpoints", + desc: "Point an OpenAI or Anthropic client at this gateway.", + actions: [button({ label: "Server settings", icon: "server", variant: "quiet", onClick: () => router.navigate("server") })], + body: endpointsBody, + }); + + const compliance = el("p", { + class: "field__help", + text: "Use this tool only with accounts you are entitled to. Auto-creating accounts, " + + "solving captchas or rotating IPs to bypass provider limits may violate z.ai's terms.", + }); + + fill(root, el("div", { class: "ov" }, [ + alerts, + hero, + kpis, + quickCard, + el("div", { class: "ov-grid" }, [ + el("div", { class: "ov-col" }, [reportsCard, endpointsCard, compliance]), + el("div", { class: "ov-col" }, [healthCard, activityCard]), + ]), + ])); + + // ---- data ------------------------------------------------------------- + let repairing = false; + + async function load() { + const paths = [ + "/admin/dash/server", + "/admin/pool/state", + "/admin/dash/doctor", + "/admin/dash/generator/rate-limit", + "/admin/dash/zcode-status", + "/admin/dash/analytics/overview?range=24h", + "/admin/dash/reports", + "/admin/dash/logs?limit=40", + ]; + const results = await Promise.allSettled(paths.map((path) => api.get(path, { signal }))); + if (signal.aborted) return; + const [server, pool, doctor, rate, zcode, usage, reports, logs] = + results.map((result) => result.status === "fulfilled" ? result.value : null); + + paintHero(server, pool, doctor, zcode); + paintAlerts(rate); + paintKpis(usage, pool, doctor); + paintHealth(doctor); + paintActivity(logs); + paintReports(reports); + paintEndpoints(server); + updated.textContent = new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" }); + } + + function paintHero(server, pool, doctor, zcode) { + if (server) { + heroVersion.textContent = "v" + server.version; + kvGateway.replaceChildren(el("span", { class: "dot dot--ok dot--live" }), el("span", { text: "online" })); + kvVersion.textContent = server.version; + } else { + heroVersion.textContent = "offline"; + kvGateway.replaceChildren(el("span", { class: "dot dot--err" }), el("span", { text: "unreachable" })); + kvVersion.textContent = "—"; + } + if (pool) { + kvPool.textContent = pool.ready + "/" + pool.accounts + " ready"; + } else { + kvPool.textContent = "—"; + } + kvZcode.textContent = zcode?.detail || "—"; + + const checks = doctor ? Object.values(doctor.checks || {}) : []; + const total = checks.length; + const ok = checks.filter((value) => value.ok).length; + const pct = total ? Math.round((ok / total) * 100) : 0; + heroRing.style.setProperty("--pct", String(pct)); + heroRing.className = "ring " + (!doctor ? "ring--muted" + : doctor.overall === "ok" ? "ring--ok" + : doctor.overall === "blocked" ? "ring--err" : "ring--warn"); + heroPct.textContent = total ? pct + "%" : "—"; + heroDetail.textContent = !doctor + ? "Health check is not reachable right now." + : doctor.overall === "ok" + ? "All " + total + " checks pass. Nothing needs attention." + : ok + " of " + total + " checks pass. " + + (doctor.overall === "blocked" ? "A blocking check needs a fix." : "A few optional checks need work."); + } + + function paintAlerts(rate) { + const nodes = []; + if (rate?.active) { + nodes.push(el("div", { class: "ov-callout", role: "alert" }, [ + el("span", { class: "dot dot--warn" }), + el("div", {}, [ + el("div", { class: "ov-callout__title", text: "Safe Mode is on" }), + el("div", { class: "text-sm" }, [ + rate.message || "Provider rate limit is active.", + " Unlocks in " + duration(rate.seconds_left) + ".", + ]), + el("div", { class: "text-sm", text: rate.notice || "" }), + ]), + ])); + } + fill(alerts, nodes); + alerts.hidden = !nodes.length; + } + + function paintKpis(usage, pool, doctor) { + const summary = usage?.summary || null; + const requests = summary ? Number(summary.requests) || 0 : null; + const ok = summary ? Number(summary.ok) || 0 : 0; + const tokens = summary ? Number(summary.total_tokens) || 0 : null; + + const checks = doctor ? Object.values(doctor.checks || {}) : []; + const okChecks = checks.filter((value) => value.ok).length; + + fill(kpis, [ + kpi({ + icon: "accounts", label: "Pool ready", + value: pool ? pool.ready : "—", + unit: pool ? "of " + pool.accounts : "", + hint: pool ? stateSummary(pool.by_state) : "Pool snapshot unavailable", + tone: pool && pool.accounts ? (pool.ready > 0 ? "ok" : "err") : "", + }), + kpi({ + icon: "chart", label: "Requests · 24h", + value: requests === null ? "—" : num(requests), + hint: requests === null ? "Usage ledger unavailable" + : num(ok) + " succeeded · " + num(Math.max(0, requests - ok)) + " failed", + tone: requests ? "ok" : "", + }), + kpi({ + icon: "models", label: "Tokens · 24h", + value: tokens === null ? "—" : compactNumber(tokens), + hint: tokens === null ? "No ledger data" + : "Prompt " + compactNumber(summary.prompt_tokens) + " · completion " + compactNumber(summary.completion_tokens), + tone: "", + }), + kpi({ + icon: "shield", label: "Checks passing", + value: doctor ? okChecks + "/" + checks.length : "—", + hint: !doctor ? "Doctor unavailable" + : (doctor.failed || []).length ? (doctor.failed || []).length + " need attention" : "Everything ready", + tone: !doctor ? "" : (doctor.failed || []).length ? "warn" : "ok", + }), + ]); + } + + function paintHealth(doctor) { + if (!doctor) { + repairBtn.hidden = true; + fill(healthBody, el("p", { class: "auto-note", text: "The doctor endpoint did not answer. Try again from Config Doctor." })); + return; + } + repairBtn.hidden = !(doctor.failed || []).length; + const entries = Object.entries(doctor.checks || {}); + fill(healthBody, entries.map(([name, value]) => el("div", { + class: "check" + (value.ok ? "" : value.status === "error" ? " check--err" : " check--warn"), + title: value.detail || "", + }, [ + el("span", { class: "dot " + (value.ok ? "dot--ok" : value.status === "error" ? "dot--err" : "dot--warn") }), + el("span", { class: "check__name", text: CHECK_LABELS[name] || name.replace(/_/g, " ") }), + el("span", { class: "check__detail", text: value.detail || "" }), + value.ok ? null : button({ + label: "Fix", icon: "refresh", size: "sm", variant: "quiet", + onClick: (event) => repairOne(name, event.currentTarget), + }), + ]))); + if (!entries.length) { + fill(healthBody, el("p", { class: "auto-note", text: "No checks reported." })); + } + } + + function paintActivity(logs) { + const records = (logs?.records || []).slice(-9).reverse(); + if (!records.length) { + fill(activityBody, el("p", { class: "auto-note", text: "No log records yet. The ring buffer fills as requests arrive." })); + return; + } + const tone = (level) => { + if (level === "ERROR" || level === "CRITICAL") return " feed__msg--err"; + if (level === "WARNING") return " feed__msg--warn"; + if (level === "INFO") return ""; + return " faint"; + }; + fill(activityBody, records.map((record) => el("div", { class: "feed__row" }, [ + el("span", { class: "feed__time", text: record.time || "" }), + el("span", { + class: "feed__msg" + tone(record.level), + text: record.message || record.logger || "", + title: (record.level || "") + " · " + (record.logger || ""), + }), + ]))); + } + + function paintReports(reports) { + const rows = (reports?.reports || []).slice(0, 4); + if (!rows.length) { + fill(reportsBody, el("p", { class: "auto-note", text: "No reports yet. Generate one after a run to get a redacted HTML summary." })); + return; + } + fill(reportsBody, rows.map((row) => el("div", { class: "report-row" }, [ + el("span", { class: "report-row__name mono text-sm", text: row.name, title: row.name }), + el("span", { class: "faint text-xs", text: bytes(row.size) }), + el("span", { class: "spacer" }), + el("span", { class: "faint text-xs", text: dateTime(Number(row.modified) * 1000) }), + button({ + label: "Open", icon: "eye", size: "sm", variant: "ghost", + onClick: () => openReport(row.name).catch((error) => toast("Could not open report: " + error.message, "err")), + }), + ]))); + } + + function paintEndpoints(server) { + if (!server) { + fill(endpointsBody, el("p", { class: "auto-note", text: "Server info unavailable." })); + return; + } + const origin = "http://" + server.host + ":" + server.port; + const endpoint = (label, path) => el("div", { class: "endpoint" }, [ + el("span", { class: "endpoint__label", text: label }), + copyable(origin + path, { label }), + ]); + fill(endpointsBody, [ + endpoint("Base URL", ""), + endpoint("OpenAI", server.endpoints.openai), + endpoint("Anthropic", server.endpoints.anthropic), + endpoint("Models", server.endpoints.models), + ]); + } + + async function refresh() { + try { + await load(); + } catch (error) { + if (error?.name !== "AbortError" && !signal.aborted) { + toast("Overview refresh failed: " + error.message, "err", 5000); + } + } + } + + async function runHealthCheck() { + healthBtn.setAttribute("aria-busy", "true"); + healthBtn.disabled = true; + try { + const doctor = await api.get("/admin/dash/doctor", { signal }); + await load(); + const failed = (doctor.failed || []).length; + toast(failed ? "Health check finished — " + failed + " item(s) need attention" : "All checks pass", + failed ? "warn" : "ok"); + } catch (error) { + toast("Health check failed: " + error.message, "err"); + } finally { + healthBtn.removeAttribute("aria-busy"); + healthBtn.disabled = false; + } + } + + async function repairSafe() { + if (repairing) return; + repairing = true; + repairBtn.setAttribute("aria-busy", "true"); + try { + const result = await api.post("/admin/dash/doctor/repair", { check: "all" }, { signal }); + const leftover = (result.actions || []).filter((action) => action.error).length; + toast(leftover ? "Repaired what was safe — " + leftover + " manual step(s) left" + : "Safe repairs applied", leftover ? "warn" : "ok"); + await load(); + } catch (error) { + toast("Repair failed: " + error.message, "err"); + } finally { + repairBtn.removeAttribute("aria-busy"); + repairing = false; + } + } + + async function repairOne(name, btn) { + btn.setAttribute("aria-busy", "true"); + try { + await api.post("/admin/dash/doctor/repair", { check: name }, { signal }); + toast("Repair attempted for " + (CHECK_LABELS[name] || name), "ok"); + await load(); + } catch (error) { + toast("Repair failed: " + error.message, "err"); + } finally { + btn.removeAttribute("aria-busy"); + } + } + + async function generateReport(btn) { + btn.setAttribute("aria-busy", "true"); + btn.disabled = true; + try { + const made = await api.post("/admin/dash/reports/generate", { run_id: "" }, { signal }); + await openReport(made.name); + toast("Report generated", "ok"); + const reports = await api.get("/admin/dash/reports", { signal }); + paintReports(reports); + } catch (error) { + toast("Report failed: " + error.message, "err"); + } finally { + btn.removeAttribute("aria-busy"); + btn.disabled = false; + } + } + + await load(); + return { refresh }; +} + +function iconFor(name, size = 16) { + return icon(ICONS[name] || ICONS.dot, size); +} + +function kpi({ icon: name, label, value, unit, hint, tone }) { + return el("div", { class: "kpi" + (tone ? " kpi--" + tone : "") }, [ + el("div", { class: "kpi__top" }, [ + el("span", { class: "kpi__icon" }, iconFor(name)), + el("span", { class: "kpi__label", text: label }), + ]), + el("div", { class: "kpi__value" }, [ + String(value), + unit ? el("small", { text: unit }) : null, + ]), + el("div", { class: "kpi__hint", text: hint }), + ]); +} + +function stateSummary(byState = {}) { + const parts = Object.entries(byState) + .sort((a, b) => b[1] - a[1]) + .map(([state, count]) => count + " " + state.replace(/_/g, " ")); + return parts.length ? parts.join(" · ") : "No accounts in the pool yet"; +} + +function loadingLines(count) { + return Array.from({ length: count }, (_, index) => el("div", { + class: "skeleton", + style: { height: "14px", width: (60 + ((index * 17) % 40)) + "%" }, + })); +} \ No newline at end of file diff --git a/zcode_gateway/dashboard/index.html b/zcode_gateway/dashboard/index.html index f76658a..f37f620 100644 --- a/zcode_gateway/dashboard/index.html +++ b/zcode_gateway/dashboard/index.html @@ -5,6 +5,7 @@ Zcode Gateway + @@ -14,7 +15,7 @@ // dark flash. Mirrors core/theme.js — kept inline on purpose. try { var t = localStorage.getItem("gw-theme"); - if (t !== "light" && t !== "dark") + if (["dark", "light", "midnight", "sepia", "contrast"].indexOf(t) === -1) t = window.matchMedia && window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark"; document.documentElement.setAttribute("data-theme", t); } catch (e) {} @@ -81,23 +82,28 @@

    Server

    diff --git a/zcode_gateway/main.py b/zcode_gateway/main.py index b70393e..57c3bf5 100644 --- a/zcode_gateway/main.py +++ b/zcode_gateway/main.py @@ -25,6 +25,9 @@ def build_parser() -> argparse.ArgumentParser: def main(argv: list[str] | None = None) -> int: args = build_parser().parse_args(argv) + from zcode_gateway.process_env import normalize_no_proxy + normalize_no_proxy() + if not args.config and not os.environ.get("ZCODE_GATEWAY_CONFIG"): # tkinter-free bootstrap: on a headless box this must never pull in # gui.py (which imports tkinter at module level) diff --git a/zcode_gateway/paths.py b/zcode_gateway/paths.py index ec56841..ca34346 100644 --- a/zcode_gateway/paths.py +++ b/zcode_gateway/paths.py @@ -24,8 +24,11 @@ def app_dir() -> Path: def base_dir() -> Path: """Where config/accounts/logs live. - Portable by default: the exe's folder. If that folder is not writable - (Program Files, some corporate lockdowns), fall back to + The Windows installer drops an ``installed.flag`` file next to the exe: + that copy keeps user data in %LOCALAPPDATA%/ZcodeGateway, never inside + Program Files, so uninstalling or updating the app cannot touch accounts. + Otherwise portable by default: the exe's folder. If that folder is not + writable (Program Files, some corporate lockdowns), fall back to %LOCALAPPDATA%/ZcodeGateway so a read-only install still works. A source checkout uses ignored .local/runtime instead of the source root. """ @@ -35,6 +38,10 @@ def base_dir() -> Path: base.mkdir(mode=0o700, parents=True, exist_ok=True) return base base = app_dir() + if (base / "installed.flag").is_file(): + fallback = _per_user_dir() + fallback.mkdir(mode=0o700, parents=True, exist_ok=True) + return fallback if not getattr(sys, "frozen", False) and (base / ".git").is_dir(): base = base / ".local" / "runtime" base.mkdir(mode=0o700, parents=True, exist_ok=True) diff --git a/zcode_gateway/process_env.py b/zcode_gateway/process_env.py index 54b5218..1802846 100644 --- a/zcode_gateway/process_env.py +++ b/zcode_gateway/process_env.py @@ -4,6 +4,22 @@ from collections.abc import Mapping +def normalize_no_proxy() -> None: + """Make NO_PROXY safe for httpx's environment parser. + + httpx (<0.30) reads every NO_PROXY entry as a URL and raises + ``InvalidURL: Invalid port`` for the bracketed IPv6 form that Windows + tooling writes (``[::1]``). The same host without brackets is accepted, + so strip only the brackets and keep each entry (and its port) intact. + Idempotent, and does nothing on machines without IPv6 entries. + """ + for name in ("NO_PROXY", "no_proxy"): + raw = os.environ.get(name) + if not raw or ("[" not in raw and "]" not in raw): + continue + os.environ[name] = raw.replace("[", "").replace("]", "") + + def external_process_env(overrides: Mapping[str, str] | None = None) -> dict[str, str]: """Restore the pre-bootloader loader path for external Linux executables. From 23d3c13cbfd202f8e3749d6c10aa327e3f633bb5 Mon Sep 17 00:00:00 2001 From: Esmail Sarhadi <45729949+Esmail-sarhadi@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:10:11 +0330 Subject: [PATCH 05/15] feat: add Inno Setup installer and build pipeline Adds a real Windows Setup.exe (Inno Setup 7): admin install with a per-user option, app mutex integration, Start Menu/desktop shortcuts, optional autostart, branded wizard bitmaps generated from the dashboard palette, and an installed.flag so user data stays in LOCALAPPDATA across upgrades and uninstalls. Includes a one-command build pipeline that reads the package version and compiles the setup, plus README and PR proposal updates. Silent install, launch and clean uninstall were verified end to end. --- PR_PROPOSAL.md | 13 +- README.md | 21 ++- WORKBUDDY_MEMORY.md | 39 ++++- scripts/installer/assets/wizard-large.bmp | Bin 0 -> 154542 bytes scripts/installer/assets/wizard-small.bmp | Bin 0 -> 9294 bytes scripts/installer/build_installer.ps1 | 72 ++++++++++ scripts/installer/installed.flag | 1 + scripts/installer/make_wizard_images.py | 168 ++++++++++++++++++++++ scripts/installer/zcode-gateway.iss | 86 +++++++++++ 9 files changed, 390 insertions(+), 10 deletions(-) create mode 100644 scripts/installer/assets/wizard-large.bmp create mode 100644 scripts/installer/assets/wizard-small.bmp create mode 100644 scripts/installer/build_installer.ps1 create mode 100644 scripts/installer/installed.flag create mode 100644 scripts/installer/make_wizard_images.py create mode 100644 scripts/installer/zcode-gateway.iss diff --git a/PR_PROPOSAL.md b/PR_PROPOSAL.md index eff38fc..d0d8b94 100644 --- a/PR_PROPOSAL.md +++ b/PR_PROPOSAL.md @@ -53,6 +53,15 @@ AutoZCoder هسته Gateway خوبی دارد، ولی تجربه کاربری - اجرای مجدد نصاب، دادهها را پاک نمیکند. - حالت portable masih کار میکند. +### 3.4 نصاب واقعی ویندوز — Inno Setup (در همین PR) +علاوه بر اسکریپت پایتونی بالا، یک **Setup.exe واقعی** هم ساخته می‌شود: + +- `scripts/installer/zcode-gateway.iss`: نصب پیش‌فرض در Program Files با گزینه «فقط برای من» بدون UAC (`PrivilegesRequiredOverridesAllowed`)، ارتباط با `AppMutex` برنامه برای بستن نسخه در حال اجرا، میانبر Start Menu/دسکتاپ، و autostart اختیاری. +- `scripts/installer/make_wizard_images.py`: تصاویر ویزارد (164×314 و 55×55) هم‌رنگ برند داشبورد، تولید خودکار در هر بیلد. +- `scripts/installer/build_installer.ps1`: نسخه را از `zcode_gateway.__version__` می‌خواند، exe را می‌سازد و با ISCC کامپایل می‌کند؛ خروجی `.local/dist/ZcodeGateway-Setup-.exe`. +- `installed.flag` کنار exe: نسخه نصبی داده‌ها را در `%LOCALAPPDATA%\ZcodeGateway` نگه می‌دارد؛ حذف یا آپدیت برنامه به اکانت‌ها دست نمی‌زند. نسخه portable همان رفتار قبلی (داده کنار exe) را دارد. +- تست دودی: نصب بی‌صدا با `/CURRENTUSER`، اجرای سالم، سپس حذف تمیز و باقی‌ماندن داده‌ها. + --- ## 4. فاز ۲ — Config Doctor (تشخیص هوشمند) @@ -206,9 +215,9 @@ AutoZCoder هسته Gateway خوبی دارد، ولی تجربه کاربری برای رسیدن به ۲۵۰۰exact، فاز ۹ (فشار/انtegration) ≈ ۱۰۰ تست اضافه میکند. -**در همین PR**: ۴۷ تست معنیدار برای فاز ۱، رفع باگ reload، report generator، Config Doctor، Safe Mode و چرخش دامنه اضافه میشود (همه ۴۷ تا اجرا و سبز شدند). عددسازی نمیکنم. +**در همین PR**: ۵۴ تست معنیدار برای فاز ۱، رفع باگ reload، report generator، Config Doctor، Safe Mode و چرخش دامنه اضافه میشود (همه ۵۴ تا اجرا و سبز شدند). عددسازی نمیکنم. -نتیجه اجرای کامل سورس روی Python 3.13: **۱٬۴۶۶ تست passed، ۱۷۳ skipped**. تعدادی تست قدیمی در اجرای تکجریانی کامل، وابسته به ترتیب اجرا هستند (در اجرای جداگانه همان ماژولها سبزاند). +نتیجه اجرای کامل سورس روی Python 3.13: **۱٬۵۲۴ تست passed، ۱۷۳ skipped**. تعدادی تست قدیمی در اجرای تکجریانی کامل، وابسته به ترتیب اجرا هستند (در اجرای جداگانه همان ماژولها سبزاند). --- diff --git a/README.md b/README.md index 6d21bcd..e2f3002 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,8 @@ Choose where the gateway runs. Then [add an account](#adding-accounts) and | Platform | Start here | Requirements | | :--- | :--- | :--- | -| **Windows desktop** | [Download ZcodeGateway.exe](https://github.com/B3hnamR/AutoZcoder/releases/latest/download/ZcodeGateway.exe) | Portable app; no Python needed for the gateway | +| **Windows installer** | [Download from Releases](https://github.com/B3hnamR/AutoZcoder/releases/latest) (`ZcodeGateway-Setup-.exe`) | Installs like a normal app; data stays in `%LOCALAPPDATA%` | +| **Windows portable** | [Download ZcodeGateway.exe](https://github.com/B3hnamR/AutoZcoder/releases/latest/download/ZcodeGateway.exe) | Portable app; no Python needed for the gateway | | **Linux VPS** | [Install over SSH](#run-on-a-linux-vps) | x86_64, systemd, glibc 2.35+ | | **From source** | [Run locally](#run-from-source) | Python 3.10+; 3.13 recommended | @@ -52,7 +53,17 @@ Choose where the gateway runs. Then [add an account](#adding-accounts) and > OS user. Use a **client key** for coding clients. Read [Security](SECURITY.md) > before exposing the gateway beyond loopback. -### Run the packaged app (Windows) +### Install the packaged app (Windows) + +Run `ZcodeGateway-Setup-.exe` from the latest release. Setup offers a +per-user install without UAC or a machine-wide install in Program Files, adds +Start Menu and (optionally) desktop shortcuts, and can start the app at sign-in. +It does not touch user data on uninstall or upgrade: config, accounts and logs +live in `%LOCALAPPDATA%\ZcodeGateway`, never inside the program folder. + +Dashboard: + +### Run the portable app (Windows) Double-click `ZcodeGateway.exe` from the latest release. On first launch it writes its own `config.yaml`, `accounts/`, `logs/` and `gateway.db` **beside @@ -258,8 +269,14 @@ python -m venv .venv .\.venv\Scripts\python.exe -m pip install -r requirements/windows.txt -r requirements/dev.txt pyinstaller .\.venv\Scripts\python.exe -m pytest tests -q .\scripts\build\windows.ps1 # Windows exe (bun compiles the captcha-mint sidecar) +.\scripts\installer\build_installer.ps1 # Setup.exe (reuses the build above) ``` +The installer build needs [Inno Setup](https://jrsoftware.org/isdl.php) 6.3+; +`build_installer.ps1` prefers a portable extraction in +`.local\tools\InnoSetup`, then `ISCC.exe` on `PATH`, then the default install +folders. Wizard branding is regenerated from `scripts\installer\make_wizard_images.py`. + On Linux, from the repository root: ```bash diff --git a/WORKBUDDY_MEMORY.md b/WORKBUDDY_MEMORY.md index 79c49ad..b7b25e9 100644 --- a/WORKBUDDY_MEMORY.md +++ b/WORKBUDDY_MEMORY.md @@ -125,14 +125,41 @@ - اگزه را در پوشه ایزوله با پورت 8888 اجرا و تست کردم: health=200، doctor 11 چک، rate-limit، reports، و `views/doctor.js` در باندل حضور دارد. سپس متوقفش کردم. - نام شاخه به `esmail/pr-overhaul` تغییر یافت؛ در PR_PROPOSAL نام ورکبادی نیامد. +### 2026-11-29 23:58 — redesign داشبورد +- صفحه **Overview** به‌عنوان خانه پیش‌فرض: hero با ring سلامت، KPIها، Quick actions، چک‌لیست Doctor، گزارش‌ها، endpoints قابل کپی، Safe Mode. +- سیستم طراحی: hero gradient در `.main`، سایدبار/تاپ‌بار tinted، برند gradient، دکمه‌های 32px با hover lift و spinner busy، فوکوس ring، nav active gradient. +- لاگین جدید: reveal کلید، دکمه «Unlock dashboard» با busy state، favicon. +- CSS تازه برای Overview با breakpointهای 980/1040/900/520. +- QA با Edge headless روی ۴ صفحه Overview/Accounts/Analytics/Settings؛ ۲ اصلاح: گرید ۵+۱ → ۳ ستون، KPI پول خالی هم‌رنگ خنثی شد. +- باگ واقعی پیدا شد: `httpx.InvalidURL: Invalid port: ':1]'` چون NO_PROXY سیستم `[::1]` دارد و httpx هر آیتم را URL می‌خواند. `normalize_no_proxy()` در `process_env.py` اضافه و در `create_app`/`gui_main.main`/`main` صدا زده شد. تست: health=200 در ۱ ثانیه. + +### 2026-11-30 00:10 — نصاب ویندوز (Inno Setup) +- Inno Setup 7.1.1 x64 از ریلیز رسمی GitHub دانلود و **portable** در `.local/tools/InnoSetup` باز شد (بدون نصب سیستم). نکته: مسیر setup نباید فاصله داشته باشد و در Git Bash باید از PowerShell برای پاس‌دادن سوییچ‌ها استفاده کرد، وگرنه `/SWITCH` به مسیر تبدیل می‌شود. +- `scripts/installer/make_wizard_images.py`: ساخت BMPهای 164×314 و 55×55 از برند (Pillow در venv). +- `scripts/installer/zcode-gateway.iss`: AppId ثابت `982950A2-06F2-4F6A-B440-B34F9DEEB7D4`، نصب پیش‌فرض Program Files + گزینه per-user، AppMutex هم‌نام برنامه، Start Menu/دسکتاپ، autostart اختیاری، `installed.flag` در [Code]، حذف داده انجام نمی‌شود. +- `scripts/installer/build_installer.ps1`: نسخه از پکیج، اجرای `windows.ps1`، پیدا کردن ISCC از `.local/tools` یا PATH، رجیستری wizard images، خروجی `ZcodeGateway-Setup-.exe`. +- `paths.py`: اگر `installed.flag` کنار exe باشد، داده در `%LOCALAPPDATA%/ZcodeGateway` می‌ماند؛ portable دست‌نخورده. تست اضافه شد. +- تست‌ها: **54 passed** در `test_workbuddy_additions.py` (شامل ۴ تست NO_PROXY و ۲ تست installed.flag). +- بیلد exe با داشبورد جدید در حال اجراست؛ بعد: کامپایل Setup و تست نصب/اجرا/حذف بی‌صدا. + +### 2026-11-30 00:25 — نصاب نهایی و تست دودی +- exe نهایی با داشبورد جدید: **97.8 MB** (`.local/dist/ZcodeGateway.exe`). +- Setup نهایی: **`.local/dist/ZcodeGateway-Setup-3.0.0.exe`** (99.1 MB) — Inno Setup 7.1.1. +- نصب بی‌صدا `/VERYSILENT /CURRENTUSER /DIR=C:\Users\esmail\ZcodeGatewayQA3`: exit=0، فایل‌ها و `installed.flag` سرجا؛ uninstall: exit=0 و پوشه کامل حذف شد. +- اجرای نسخه نصبی: `/health`=200، `/dash/`=200، متن راهنمای جدید لاگین داخل باندل، `overview.js`=200 (20.5KB). سپس بسته شد. +- اسکرین‌شات ویزارد: `.local/qa-installer-welcome.png` — پنل برند سمت چپ، عنوان Welcome، دکمه‌های استاندارد. +- تست کامل سورس: **1524 passed, 173 skipped** در 253s. +- نکته تست: نصب در ریشه `C:\` به‌خاطر نبود دسترسی نوشتن با exit=1 شکست می‌خورد؛ مسیر تست باید زیر پروفایل کاربر باشد. همچنین PyInstaller یک child process جدا دارد؛ برای حذف کامل باید هر دو پروسه بسته شوند، وگرنه uninstaller فایل exe را باقی می‌گذارد (رفتار طبیعی ویندوز). +- Welcome page با `DisableWelcomePage=no` فعال شد تا برند دیده شود. +- تغییری در کد اپ لازم نبود؛ فقط [Files] حالا `installed.flag` را نصب می‌کند تا uninstaller آن را هم پاک کند. + ## 5. مراحل پیش رو -1. نوشتن `PR_PROPOSAL.md` — درخواست خیلی کامل، فارسی، RTL، با فازبندی و مرز قانونی. -2. رفع باگ auto-reload pool در کد. -3. اضافه کردن `scripts/report/generate_html.py` — گزارش HTML هوشمند از لاگها. -4. اضافه کردن `scripts/install/windows_install.py` — نصاب کوچک و تمیز. -5. اضافه کردن تست معنیدار برای موارد بالا (چند ده تست، نه ۲۵۰۰). -6. اجرای تستها، بهروزرسانی این فایل، ارائه فایلها. +1. کامپایل Setup: `.\scripts\installer\build_installer.ps1 -SkipAppBuild` (exe تازه ساخته شد). +2. تست دودی نصب بی‌صدا با `/CURRENTUSER` در `C:\ZcodeGatewayQA`، اجرا و health، سپس uninstall و بررسی باقی‌ماندن داده‌ها. +3. اجرای تست کامل `pytest tests -q` روی سورس. +4. commit روی `esmail/pr-overhaul` و آماده‌سازی متن PR. +5. push: `gh` و توکن در دسترس نیست؛ دستورهای دقیق به اسماعیل داده می‌شود. --- diff --git a/scripts/installer/assets/wizard-large.bmp b/scripts/installer/assets/wizard-large.bmp new file mode 100644 index 0000000000000000000000000000000000000000..ac59df3222ec314b427787aa49745e7e6398270f GIT binary patch literal 154542 zcmeF42b>+nk^h%0A)&N6YO^-yRZb`egg_D!Adz#9Cg*IDjSm}~&iHKOaCi3kf5G7# zaJq9mXPGUkdc^H(bG1nZ0?KfyXS>4-zQ7Nd*=z(Sqcr;c;%Kcms~bZ@=mbMNNt?(%J{ai-`E7}jHNfhI%7e3m%Rqc z&HIbee~y#CcS5eyG3nWH!b{&LOT>HU3D#K(4cB<(mNA!HHcs+Ru+B(robbx{wz1z> zbHz;gD+)a#<3!$!g*INws$ym%hPnz5P54MA@@6Zy@l#f_%ck!^kk4ZeG9t@F-t6U8 z#InMzvOm|ovWV~C-ZpQ1;<v*RT11Z$5=($8_iE9v!O z)4g|oRj_U-orb>!$GVwQ<^AhtO+&K+DfP1sLW*2~YwGYb+5C{aavvP=6WMW3DJZ!~ z^jL47qUG7ZkHD3PG?bFHLvemdy~d5mbKR8e@gnBMt+GGYy|Re!;NCVij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ZIn!C&5S=07R)MI8>xU!vQ z+PL=W>kK_+fnf&LVvQs6V&vLoEz>Tr`jF|bw&?X|5aD49<{M(I;!I|km1qKO+leRF%9>kSW-pHzxwd`ays%X;wq;mTA2+!!>VNi^UO?4tOJiF%X&x5ULIlFOd8kRZzhdvY??`ZDUfRtZ4Tmh#G0I! ztz!qXU@t{D6Y?ZnyNDV3!_l46BE&_R+sS&ga-Fl5f^>%KMtg|VVR+YD-A3(yUvxYSjb1SlE(iZ=may^nbK(In4v{I TkPAPY5Salv?FuL&&JRKW3D6PW literal 0 HcmV?d00001 diff --git a/scripts/installer/assets/wizard-small.bmp b/scripts/installer/assets/wizard-small.bmp new file mode 100644 index 0000000000000000000000000000000000000000..6d6c9beb214daea8cecfeb8b8b27ddc47fcf4567 GIT binary patch literal 9294 zcmeH|&rTCj6vpudT=M`fd;;CO*Z2e^jlrQQ4YXpXe<@bR(n$&q6PIZ}ahSt+` zoo!qvy1LE#-Be#YX8PySOvs(Q}e0x6sv&PZfZW2o?;ac+fB`< z(o?JgV!NsNRChoR(Ib zpOGrUH-(`Y1nwX-i^v>e1;iIHzJm1)6IC{=os&?fm(XV*I0KzBi(n4nS;Pw%U2LF! zt(vG!-~C?{4mm9`D^=)|7)ZlEfk+lc0hwjodIV#EQ4JHdye(f+JLhf{fegG!^p7F^ z06+Hd_9NCm;QmwSc_fNF05q!VkhyNJ&te2QwFXZdt{}8w&Ylol zQS^@Ru^O6$ew%%@+*UnFBI^j}mT*ynOJ`NJINS+%40ZrAE6w1)fZ8|KQ*IodBiffZ zDR(O%R1Y1c1kb833333MRr1y8Wo&(6K)I$w8y?|gg8d-F->EP&IqE@LMX83=;Bnxz jRNd#be@a)<0&w883Kp$xwL{DM-jq`w!XNF_L7cw;Rkh}= literal 0 HcmV?d00001 diff --git a/scripts/installer/build_installer.ps1 b/scripts/installer/build_installer.ps1 new file mode 100644 index 0000000..cbdd902 --- /dev/null +++ b/scripts/installer/build_installer.ps1 @@ -0,0 +1,72 @@ +# build_installer.ps1 - build the app exe and wrap it in a signed-free Setup.exe +# +# .\scripts\installer\build_installer.ps1 build app + installer +# .\scripts\installer\build_installer.ps1 -SkipAppBuild reuse .local\dist\ZcodeGateway.exe +# +# Requires Inno Setup 6.3+ (tested with 7.1.1). The script looks for +# ISCC.exe in .local\tools\InnoSetup (portable extraction), then PATH, then +# the default Inno Setup install folders. +# +# Output: .\.local\dist\ZcodeGateway-Setup-.exe + +[CmdletBinding()] +param( + [switch]$SkipAppBuild +) + +$ErrorActionPreference = "Stop" +$Here = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot "..\..")) +Set-Location $Here + +$py = Join-Path $Here ".venv\Scripts\python.exe" +if (-not (Test-Path $py)) { $py = (Get-Command python -ErrorAction Stop).Source } + +$version = (& $py -c "import zcode_gateway; print(zcode_gateway.__version__)").Trim() +if (-not $version) { throw "Could not read zcode_gateway.__version__" } +Write-Host "Zcode Gateway installer - v$version" -ForegroundColor Cyan + +if (-not $SkipAppBuild) { + & (Join-Path $Here "scripts\build\windows.ps1") + if ($LASTEXITCODE -ne 0) { throw "App build failed with exit code $LASTEXITCODE" } +} + +$exe = Join-Path $Here ".local\dist\ZcodeGateway.exe" +if (-not (Test-Path $exe)) { + throw "Missing $exe - run without -SkipAppBuild to build it first" +} + +$isccCandidates = @( + (Join-Path $Here ".local\tools\InnoSetup\ISCC.exe"), + (Join-Path ${env:ProgramFiles(x86)} "Inno Setup 7\ISCC.exe"), + (Join-Path ${env:ProgramFiles(x86)} "Inno Setup 6\ISCC.exe"), + (Join-Path $env:LOCALAPPDATA "Programs\Inno Setup 7\ISCC.exe"), + (Join-Path $env:LOCALAPPDATA "Programs\Inno Setup 6\ISCC.exe") +) +$iscc = $isccCandidates | Where-Object { $_ -and (Test-Path $_) } | Select-Object -First 1 +if (-not $iscc) { + $cmd = Get-Command ISCC.exe -ErrorAction SilentlyContinue + if ($cmd) { $iscc = $cmd.Source } +} +if (-not $iscc) { + throw "ISCC.exe not found. Extract Inno Setup portably to .local\tools\InnoSetup " + + "or install it from https://jrsoftware.org/isdl.php" +} +Write-Host " iscc : $iscc" + +Write-Host " wizard : regenerating brand bitmaps" -ForegroundColor DarkGray +& $py (Join-Path $Here "scripts\installer\make_wizard_images.py") --version $version +if ($LASTEXITCODE -ne 0) { throw "Wizard bitmap generation failed" } + +Push-Location (Join-Path $Here "scripts\installer") +try { + & $iscc "/DMyAppVersion=$version" "zcode-gateway.iss" + if ($LASTEXITCODE -ne 0) { throw "ISCC failed with exit code $LASTEXITCODE" } +} finally { + Pop-Location +} + +$setup = Join-Path $Here (".local\dist\ZcodeGateway-Setup-$version.exe") +if (-not (Test-Path $setup)) { throw "Expected installer missing: $setup" } + +$size = [math]::Round((Get-Item $setup).Length / 1MB, 1) +Write-Host "`n built: $setup ($size MB)" -ForegroundColor Green \ No newline at end of file diff --git a/scripts/installer/installed.flag b/scripts/installer/installed.flag new file mode 100644 index 0000000..a68c4cd --- /dev/null +++ b/scripts/installer/installed.flag @@ -0,0 +1 @@ +Installed by Zcode Gateway Setup \ No newline at end of file diff --git a/scripts/installer/make_wizard_images.py b/scripts/installer/make_wizard_images.py new file mode 100644 index 0000000..2dd7173 --- /dev/null +++ b/scripts/installer/make_wizard_images.py @@ -0,0 +1,168 @@ +"""Generate the Setup wizard bitmaps from the dashboard brand. + +Inno Setup wants 24-bit BMPs: a 164x314 side panel for the welcome/finish +pages and a 55x55 header mark for the inner pages. Everything is drawn at +4x and downsampled, which keeps the rounded logo and text edges clean at +100% and on HiDPI screens (Setup scales the bitmaps itself). + + python scripts/installer/make_wizard_images.py [--version 3.0.0] +""" +from __future__ import annotations + +import argparse +import re +from pathlib import Path + +from PIL import Image, ImageDraw, ImageFilter, ImageFont + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent.parent +ASSETS = HERE / "assets" + +ACCENT = (109, 90, 255) +ACCENT2 = (177, 140, 255) +BG_TOP = (11, 14, 21) +BG_BOTTOM = (15, 20, 32) +INK = (244, 246, 251) +MUTED = (139, 148, 167) +RULE = (124, 105, 255) +S = 4 # supersampling factor + + +def _font(name: str, size: int, bold: bool = False) -> ImageFont.FreeTypeFont: + candidates = [Path("C:/Windows/Fonts") / name] + candidates.append(Path("C:/Windows/Fonts") / ("segoeuib.ttf" if bold else "segoeui.ttf")) + for path in candidates: + try: + return ImageFont.truetype(str(path), size) + except OSError: + continue + return ImageFont.load_default(size) + + +def _vertical_gradient(size: tuple[int, int], top: tuple, bottom: tuple) -> Image.Image: + width, height = size + img = Image.new("RGB", size) + draw = ImageDraw.Draw(img) + for y in range(height): + t = y / max(height - 1, 1) + color = tuple(round(top[i] + (bottom[i] - top[i]) * t) for i in range(3)) + draw.line([(0, y), (width, y)], fill=color) + return img + + +def _diagonal_gradient(size: int) -> Image.Image: + img = Image.new("RGB", (size, size)) + px = img.load() + for y in range(size): + for x in range(size): + t = (x + y) / (2 * (size - 1)) + px[x, y] = tuple(round(ACCENT[i] + (ACCENT2[i] - ACCENT[i]) * t) for i in range(3)) + return img + + +def _rounded_mask(size: int, radius: int) -> Image.Image: + mask = Image.new("L", (size, size), 0) + ImageDraw.Draw(mask).rounded_rectangle([0, 0, size - 1, size - 1], radius=radius, fill=255) + return mask + + +def _logo(size_px: int, radius_px: int, z_ratio: float = 0.62) -> Image.Image: + """Gradient rounded square with a white Z, transparent background.""" + size = size_px * S + grad = _diagonal_gradient(size) + logo = Image.new("RGBA", (size, size), (0, 0, 0, 0)) + logo.paste(grad, (0, 0), _rounded_mask(size, radius_px * S)) + draw = ImageDraw.Draw(logo) + font = _font("segoeuib.ttf", round(size * z_ratio * 0.92)) + draw.text((size / 2, size / 2 - size * 0.02), "Z", font=font, fill=(255, 255, 255, 255), anchor="mm") + return logo.resize((size_px, size_px), Image.LANCZOS) + + +def _glow(size: tuple[int, int], center: tuple[float, float], radius: float, strength: int) -> Image.Image: + """Soft radial accent glow on a transparent layer.""" + width, height = size + layer = Image.new("RGBA", size, (0, 0, 0, 0)) + draw = ImageDraw.Draw(layer) + steps = 32 + cx, cy = center + for i in range(steps, 0, -1): + t = i / steps + r = radius * t + alpha = round(strength * (1 - t) ** 1.8) + draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=(*ACCENT2, alpha)) + return layer.filter(ImageFilter.GaussianBlur(radius * 0.12)) + + +def _centered_text(draw: ImageDraw.ImageDraw, cy: float, text: str, font, fill) -> None: + draw.text((draw.im.size[0] / 2, cy * S), text, font=font, fill=fill, anchor="mm") + + +def _rule(draw: ImageDraw.ImageDraw, cx: float, cy: float, width: int, height: int) -> None: + half = width * S / 2 + draw.rounded_rectangle([cx * S - half, cy * S - height * S / 2, + cx * S + half, cy * S + height * S / 2], + radius=height * S / 2, fill=RULE) + + +def make_large(version: str) -> Image.Image: + width, height = 164, 314 + img = _vertical_gradient((width * S, height * S), BG_TOP, BG_BOTTOM).convert("RGBA") + + grid = Image.new("RGBA", img.size, (0, 0, 0, 0)) + gdraw = ImageDraw.Draw(grid) + step = 20 * S + for x in range(0, width * S, step): + gdraw.line([(x, 0), (x, height * S)], fill=(255, 255, 255, 7)) + for y in range(0, height * S, step): + gdraw.line([(0, y), (width * S, y)], fill=(255, 255, 255, 7)) + img = Image.alpha_composite(img, grid) + + img = Image.alpha_composite(img, _glow((width * S, height * S), (width * 0.5, 108), 150 * S, 90)) + img = Image.alpha_composite(img, _glow((width * S, height * S), (width * 0.85, 300), 110 * S, 40)) + + logo = _logo(84, 20) + img.alpha_composite(logo, (round((width - 84) / 2) * S, 60 * S)) + + draw = ImageDraw.Draw(img) + cx = width / 2 + _rule(draw, cx, 176, 26, 3) + _centered_text(draw, 197, "Zcode", _font("segoeuib.ttf", 16 * S, bold=True), INK) + _centered_text(draw, 217, "Gateway", _font("segoeui.ttf", 16 * S), INK) + _centered_text(draw, 245, "Local AI control plane", _font("segoeui.ttf", 8 * S), MUTED) + _centered_text(draw, 290, f"v{version} · B3hnamR", _font("segoeui.ttf", 7 * S), (96, 105, 124)) + + return img.convert("RGB").resize((width, height), Image.LANCZOS) + + +def make_small() -> Image.Image: + size = 55 + img = Image.new("RGB", (size * S, size * S), (255, 255, 255)) + logo = _logo(45, 11) + img.paste(logo, (5 * S, 5 * S), logo) + return img.resize((size, size), Image.LANCZOS) + + +def _project_version() -> str: + text = (ROOT / "zcode_gateway" / "__init__.py").read_text(encoding="utf-8") + match = re.search(r'__version__\s*=\s*"([^"]+)"', text) + return match.group(1) if match else "3.0.0" + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--version", default=None) + args = parser.parse_args() + version = args.version or _project_version() + + ASSETS.mkdir(parents=True, exist_ok=True) + large = ASSETS / "wizard-large.bmp" + small = ASSETS / "wizard-small.bmp" + make_large(version).save(large, "BMP") + make_small().save(small, "BMP") + print(f"wrote {large} ({large.stat().st_size} bytes)") + print(f"wrote {small} ({small.stat().st_size} bytes)") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/scripts/installer/zcode-gateway.iss b/scripts/installer/zcode-gateway.iss new file mode 100644 index 0000000..a6a1552 --- /dev/null +++ b/scripts/installer/zcode-gateway.iss @@ -0,0 +1,86 @@ +; Zcode Gateway - Windows installer (Inno Setup 6.3+ / 7.x) +; +; Build with scripts\installer\build_installer.ps1, which builds the exe +; first and passes /DMyAppVersion. Compiling this file on its own works too +; as long as .local\dist\ZcodeGateway.exe already exists. +; +; Design notes: +; * admin install by default (Program Files); the mode dialog lets a user +; pick a per-user install instead (no UAC). +; * the app's own installed.flag next to the exe tells the gateway to keep +; config/accounts/logs in %LOCALAPPDATA%\ZcodeGateway, so uninstalling +; never touches user data. +; * AppMutex matches gui_main.MUTEX_NAME so Setup can close a running copy. + +#ifndef MyAppVersion + #define MyAppVersion "3.0.0" +#endif + +#define MyAppName "Zcode Gateway" +#define MyAppPublisher "B3hnamR" +#define MyAppURL "https://github.com/B3hnamR/AutoZcoder" +#define MyAppExeName "ZcodeGateway.exe" +#define RepoRoot AddBackslash(SourcePath) + "..\.." + +[Setup] +AppId={{982950A2-06F2-4F6A-B440-B34F9DEEB7D4} +AppName={#MyAppName} +AppVersion={#MyAppVersion} +AppVerName={#MyAppName} {#MyAppVersion} +AppPublisher={#MyAppPublisher} +AppPublisherURL={#MyAppURL} +AppSupportURL={#MyAppURL}/issues +AppUpdatesURL={#MyAppURL}/releases +VersionInfoVersion={#MyAppVersion}.0 +VersionInfoCompany={#MyAppPublisher} +VersionInfoDescription={#MyAppName} Setup +VersionInfoProductName={#MyAppName} +VersionInfoProductVersion={#MyAppVersion} +DefaultDirName={autopf}\{#MyAppName} +DisableProgramGroupPage=yes +DisableWelcomePage=no +LicenseFile={#RepoRoot}\LICENSE +PrivilegesRequired=admin +PrivilegesRequiredOverridesAllowed=dialog commandline +OutputDir={#RepoRoot}\.local\dist +OutputBaseFilename=ZcodeGateway-Setup-{#MyAppVersion} +SetupIconFile={#RepoRoot}\assets\zcode.ico +UninstallDisplayIcon={app}\{#MyAppExeName} +UninstallDisplayName={#MyAppName} +WizardStyle=modern +WizardImageFile={#RepoRoot}\scripts\installer\assets\wizard-large.bmp +WizardSmallImageFile={#RepoRoot}\scripts\installer\assets\wizard-small.bmp +WizardImageStretch=no +Compression=lzma2/max +SolidCompression=yes +ArchitecturesAllowed=x64compatible +ArchitecturesInstallIn64BitMode=x64compatible +MinVersion=10.0 +AppMutex=ZcodeGatewayByB3hnamR-SingleInstance +CloseApplications=yes +RestartApplications=no +SetupLogging=yes +ShowLanguageDialog=no +AllowNoIcons=yes +DefaultGroupName={#MyAppName} + +[Tasks] +Name: "desktopicon"; Description: "Create a &desktop shortcut"; GroupDescription: "Additional icons:" +Name: "autostart"; Description: "Start Zcode Gateway when I &sign in"; GroupDescription: "Startup:"; Flags: unchecked + +[Files] +Source: "{#RepoRoot}\.local\dist\ZcodeGateway.exe"; DestDir: "{app}"; Flags: ignoreversion +Source: "{#RepoRoot}\LICENSE"; DestDir: "{app}"; Flags: ignoreversion +; Tells zcode_gateway.paths.base_dir() to keep user data in +; %LOCALAPPDATA%\ZcodeGateway instead of the program folder. +Source: "installed.flag"; DestDir: "{app}"; Flags: ignoreversion + +[Icons] +Name: "{autoprograms}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}" +Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: desktopicon + +[Registry] +Root: HKA; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueType: string; ValueName: "ZcodeGateway"; ValueData: """{app}\{#MyAppExeName}"""; Flags: uninsdeletevalue; Tasks: autostart + +[Run] +Filename: "{app}\{#MyAppExeName}"; Description: "Launch {#MyAppName}"; Flags: nowait postinstall skipifsilent runasoriginaluser \ No newline at end of file From 9c00eb802049067da3dfc2b11c5305e5198cb5ca Mon Sep 17 00:00:00 2001 From: Esmail Sarhadi <45729949+Esmail-sarhadi@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:11:43 +0330 Subject: [PATCH 06/15] docs: record installer results and push hand-off steps --- WORKBUDDY_MEMORY.md | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/WORKBUDDY_MEMORY.md b/WORKBUDDY_MEMORY.md index b7b25e9..7650bf7 100644 --- a/WORKBUDDY_MEMORY.md +++ b/WORKBUDDY_MEMORY.md @@ -153,13 +153,30 @@ - Welcome page با `DisableWelcomePage=no` فعال شد تا برند دیده شود. - تغییری در کد اپ لازم نبود؛ فقط [Files] حالا `installed.flag` را نصب می‌کند تا uninstaller آن را هم پاک کند. -## 5. مراحل پیش رو +### 2026-11-30 00:35 — commit و وضعیت push +- commit 1: `6929e5a feat: redesign dashboard with overview page and fix NO_PROXY crash` (۱۴ فایل، +1158/−49). +- commit 2: `6cb45c0 feat: add Inno Setup installer and build pipeline` (۹ فایل، +390/−10). +- push با حساب `Esmail-sarhadi` رد شد: `Permission to B3hnamR/AutoZcoder.git denied` (403). راه‌حل در بخش «مراحل پیش رو». +- فایل‌های خروجی: `.local/dist/ZcodeGateway.exe` (97.8MB)، `.local/dist/ZcodeGateway-Setup-3.0.0.exe` (99.1MB). +- `.local/tools/InnoSetup` نسخه portable ابزار بیلد است (در git نیست). -1. کامپایل Setup: `.\scripts\installer\build_installer.ps1 -SkipAppBuild` (exe تازه ساخته شد). -2. تست دودی نصب بی‌صدا با `/CURRENTUSER` در `C:\ZcodeGatewayQA`، اجرا و health، سپس uninstall و بررسی باقی‌ماندن داده‌ها. -3. اجرای تست کامل `pytest tests -q` روی سورس. -4. commit روی `esmail/pr-overhaul` و آماده‌سازی متن PR. -5. push: `gh` و توکن در دسترس نیست؛ دستورهای دقیق به اسماعیل داده می‌شود. +--- + +## 5. مراحل پیش رو (تحویل به اسماعیل) + +کد و نصاب تمام شده؛ فقط push به GitHub مانده چون حساب محلی `Esmail-sarhadi` عضو `B3hnamR/AutoZcoder` نیست (403). + +1. **Fork**: در مرورگر https://github.com/B3hnamR/AutoZcoder/fork را باز کن و fork را زیر `Esmail-sarhadi` بساز. +2. سپس: + ``` + cd "C:\Users\esmail\WorkBuddy AI\2026-11-29-20-04-23\AutoZcoder" + git remote add fork https://github.com/Esmail-sarhadi/AutoZcoder.git + git push -u fork esmail/pr-overhaul + ``` +3. PR را از این لینک بساز: + `https://github.com/B3hnamR/AutoZcoder/compare/master...Esmail-sarhadi:esmail/pr-overhaul?expand=1` + +اگر اسماعیل به عنوان collaborator به ریپوی اصلی اضافه شود، `git push -u origin esmail/pr-overhaul` مستقیم کار می‌کند. --- From 77ae1cb2baa3e6e60d5923a8d8e2eda5975de6e1 Mon Sep 17 00:00:00 2001 From: Esmail Sarhadi <45729949+Esmail-sarhadi@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:16:27 +0330 Subject: [PATCH 07/15] docs: record pull request #7 status --- WORKBUDDY_MEMORY.md | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/WORKBUDDY_MEMORY.md b/WORKBUDDY_MEMORY.md index 7650bf7..60f15ff 100644 --- a/WORKBUDDY_MEMORY.md +++ b/WORKBUDDY_MEMORY.md @@ -162,21 +162,20 @@ --- -## 5. مراحل پیش رو (تحویل به اسماعیل) +### 2026-11-30 00:55 — PR #7 ساخته شد +- توکن GitHub داده‌شده مال حساب `Esmail-sarhadi` بود که `permissions.push=false` روی `B3hnamR/AutoZcoder` دارد؛ push مستقیم همچنان 403. +- fork با API ساخته شد و branch به fork push شد. خطای `GH007` (ایمیل خصوصی) با بازنویسی تاریخچه ۶ commit به noreply (`45729949+Esmail-sarhadi@users.noreply.github.com`) رفع شد؛ بکاپ محلی: `backup/esmail-pr-overhaul-preemail`. +- PR: **https://github.com/B3hnamR/AutoZcoder/pull/7** — ۶ commit، ۳۷ فایل، base `master`، state open. +- **یادآوری امنیتی:** توکن در چت آمده؛ باید در GitHub باطل/چرخش شود. -کد و نصاب تمام شده؛ فقط push به GitHub مانده چون حساب محلی `Esmail-sarhadi` عضو `B3hnamR/AutoZcoder` نیست (403). +--- -1. **Fork**: در مرورگر https://github.com/B3hnamR/AutoZcoder/fork را باز کن و fork را زیر `Esmail-sarhadi` بساز. -2. سپس: - ``` - cd "C:\Users\esmail\WorkBuddy AI\2026-11-29-20-04-23\AutoZcoder" - git remote add fork https://github.com/Esmail-sarhadi/AutoZcoder.git - git push -u fork esmail/pr-overhaul - ``` -3. PR را از این لینک بساز: - `https://github.com/B3hnamR/AutoZcoder/compare/master...Esmail-sarhadi:esmail/pr-overhaul?expand=1` +## 5. وضعیت تحویل -اگر اسماعیل به عنوان collaborator به ریپوی اصلی اضافه شود، `git push -u origin esmail/pr-overhaul` مستقیم کار می‌کند. +- PR #7 ساخته شد (از fork `Esmail-sarhadi`) و منتظر review/merge اسماعیل است. +- خروجی‌های بیلد در `.local/dist/` هستند و در git نیستند: `ZcodeGateway.exe` (97.8MB) و `ZcodeGateway-Setup-3.0.0.exe` (99.1MB). +- توکن GitHub که در چت آمد باید باطل/چرخش شود. +- اگر اسماعیل تو را collaborator کند، می‌توانی مستقیم روی خود ریپو کار کنی؛ الان branch روی fork است. --- From 3b7c8bd741e6e627a110615111a5641b7f087fad Mon Sep 17 00:00:00 2001 From: Esmail-sarhadi <45729949+Esmail-sarhadi@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:31:59 +0330 Subject: [PATCH 08/15] fix(dashboard): repair Config Doctor page load mount() is synchronous, so awaiting refresh() was a syntax error that blanked the whole page. Import every view module in a browser test to catch this class of bug, and mount the doctor view against fixtures. --- PR_PROPOSAL.md | 4 ++-- WORKBUDDY_MEMORY.md | 12 ++++++++++- tests/test_dashboard_review_fixes.py | 20 +++++++++++++++++++ .../dashboard/assets/js/views/doctor.js | 2 +- 4 files changed, 34 insertions(+), 4 deletions(-) diff --git a/PR_PROPOSAL.md b/PR_PROPOSAL.md index d0d8b94..49d1f8c 100644 --- a/PR_PROPOSAL.md +++ b/PR_PROPOSAL.md @@ -215,9 +215,9 @@ AutoZCoder هسته Gateway خوبی دارد، ولی تجربه کاربری برای رسیدن به ۲۵۰۰exact، فاز ۹ (فشار/انtegration) ≈ ۱۰۰ تست اضافه میکند. -**در همین PR**: ۵۴ تست معنیدار برای فاز ۱، رفع باگ reload، report generator، Config Doctor، Safe Mode و چرخش دامنه اضافه میشود (همه ۵۴ تا اجرا و سبز شدند). عددسازی نمیکنم. +**در همین PR**: ۵۶ تست معنیدار برای فاز ۱، رفع باگ reload، report generator، Config Doctor، Safe Mode و چرخش دامنه اضافه میشود (همه ۵۶ تا اجرا و سبز شدند). عددسازی نمیکنم. -نتیجه اجرای کامل سورس روی Python 3.13: **۱٬۵۲۴ تست passed، ۱۷۳ skipped**. تعدادی تست قدیمی در اجرای تکجریانی کامل، وابسته به ترتیب اجرا هستند (در اجرای جداگانه همان ماژولها سبزاند). +نتیجه اجرای کامل سورس روی Python 3.13: **۱٬۵۲۴ تست passed، ۱۷۳ skipped**؛ به‌علاوه ۲ تست جدید داشبورد (`test_every_dashboard_view_module_parses` و `test_config_doctor_mounts_checks`) که جداگانه اجرا و سبز شدند. تعدادی تست قدیمی در اجرای تکجریانی کامل، وابسته به ترتیب اجرا هستند (در اجرای جداگانه همان ماژولها سبزاند). --- diff --git a/WORKBUDDY_MEMORY.md b/WORKBUDDY_MEMORY.md index 60f15ff..f19c024 100644 --- a/WORKBUDDY_MEMORY.md +++ b/WORKBUDDY_MEMORY.md @@ -170,10 +170,20 @@ --- +### 2026-11-30 01:10 — اسکرین‌شات‌های نهایی + فیکس Config Doctor +- اسکرین‌شات‌های داشبورد با Playwright از سورس و با داده دموی `.local/dist`: `.local/qa3-overview.png`، `qa3-accounts.png`، `qa3-analytics.png`، `qa3-doctor.png`، `qa3-settings.png`، `qa3-overview-light.png`، `qa3-mobile.png` (تم تیره/روشن/موبایل). اسکرین‌شات صفحه Welcome نصاب: `.local/qa-installer-welcome.png`. +- حین QA معلوم شد صفحه Config Doctor با خطای SyntaxError («Unexpected reserved word») کلاً بالا نمی‌آمد: `await refresh()` داخل تابع غیر-async `mount` در `views/doctor.js`. +- فیکس: فراخوانی `refresh()` بدون await؛ دو تست Playwright اضافه شد: `test_every_dashboard_view_module_parses` (import همه ویوها) و `test_config_doctor_mounts_checks`. جمع تست‌های افزوده: ۵۶. +- exe و Setup با فیکس بازسازی شدند: `ZcodeGateway.exe` (102.5MB، 00:30) و `ZcodeGateway-Setup-3.0.0.exe` (99.1MB). +- تأیید exe جدید: صفحه Doctor با ۱۱ کارت و بدون خطای کنسول؛ نصب سایلنت per-user exit=0، اجرای نسخه نصب‌شده و سرو فایل اصلاح‌شده، آنینستال exit=0 و حذف کامل پوشه/شورتکات. + +--- + ## 5. وضعیت تحویل - PR #7 ساخته شد (از fork `Esmail-sarhadi`) و منتظر review/merge اسماعیل است. -- خروجی‌های بیلد در `.local/dist/` هستند و در git نیستند: `ZcodeGateway.exe` (97.8MB) و `ZcodeGateway-Setup-3.0.0.exe` (99.1MB). +- خروجی‌های بیلد در `.local/dist/` هستند و در git نیستند: `ZcodeGateway.exe` (102.5MB) و `ZcodeGateway-Setup-3.0.0.exe` (99.1MB) — بازسازی‌شده با فیکس Config Doctor در 2026-11-30 00:30. +- اسکرین‌شات‌های ارائه: `.local/qa3-*.png` و `.local/qa-installer-welcome.png`. - توکن GitHub که در چت آمد باید باطل/چرخش شود. - اگر اسماعیل تو را collaborator کند، می‌توانی مستقیم روی خود ریپو کار کنی؛ الان branch روی fork است. diff --git a/tests/test_dashboard_review_fixes.py b/tests/test_dashboard_review_fixes.py index ed3ee6b..7f513a7 100644 --- a/tests/test_dashboard_review_fixes.py +++ b/tests/test_dashboard_review_fixes.py @@ -35,6 +35,9 @@ def dashboard(): "/admin/dash/auth/login/status": {"state": "waiting"}, "/admin/dash/auth/login/cancel": {"ok": True}, "/admin/dash/logs": {"records": []}, + "/admin/dash/doctor": {"overall": "ok", "failed": [], + "checks": {"python": {"status": "ok", "detail": "fixture"}}}, + "/admin/dash/reports": {"reports": []}, } def handle(route): @@ -94,6 +97,23 @@ def mount(page, name): page.evaluate("name => mountView(name)", name) +def test_every_dashboard_view_module_parses(dashboard): + """A syntax error in any view module blanks that page, so import them all.""" + page, *_ = dashboard + names = sorted(path.stem for path in (ASSETS / "js/views").glob("*.js")) + assert names + assert page.evaluate( + "names => Promise.all(names.map((name) => import('/assets/js/views/' + name + '.js')" + ".then(() => name)))", names) == names + + +def test_config_doctor_mounts_checks(dashboard): + page, *_ = dashboard + mount(page, "doctor") + page.wait_for_selector(".doctor-grid .card") + assert "Everything ready" in page.inner_text(".doctor-summary") + + def test_dashboard_sidebar_opens_separate_generator_and_route_pages(dashboard): page, _, defaults, calls = dashboard defaults.update({ diff --git a/zcode_gateway/dashboard/assets/js/views/doctor.js b/zcode_gateway/dashboard/assets/js/views/doctor.js index 9f6049f..ae3a6d1 100644 --- a/zcode_gateway/dashboard/assets/js/views/doctor.js +++ b/zcode_gateway/dashboard/assets/js/views/doctor.js @@ -146,6 +146,6 @@ export function mount({ root, signal }) { actions: [reportGenerate], body: reportBox }), ]), ]); - await refresh(); + refresh(); return { refresh }; } From 9ca8af37228d6e850abf68ff4fdad5d4abc72088 Mon Sep 17 00:00:00 2001 From: Esmail-sarhadi <45729949+Esmail-sarhadi@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:57:03 +0330 Subject: [PATCH 09/15] fix: stop console flashes from health checks and captcha Config Doctor and the captcha sidecar spawned console programs from a windowed exe, so each Overview poll flashed cmd windows. Hide the children and reuse the last doctor snapshot between polls; refetch only on Run health check, repair, or a fresh mount. --- PR_PROPOSAL.md | 3 + WORKBUDDY_MEMORY.md | 9 ++ generator/claim_start.py | 3 +- tests/test_dashboard_review_fixes.py | 20 +++++ tests/test_workbuddy_additions.py | 82 +++++++++++++++++++ zcode_gateway/captcha_tickets.py | 12 ++- zcode_gateway/config_doctor.py | 12 ++- .../dashboard/assets/js/views/overview.js | 18 ++-- 8 files changed, 150 insertions(+), 9 deletions(-) diff --git a/PR_PROPOSAL.md b/PR_PROPOSAL.md index 49d1f8c..8c9ea0c 100644 --- a/PR_PROPOSAL.md +++ b/PR_PROPOSAL.md @@ -84,6 +84,9 @@ AutoZCoder هسته Gateway خوبی دارد، ولی تجربه کاربری > چک توکن Cloudflare **هیچوقت مقدار توکن را چاپ نمیکند**؛ فقط میگوید معتبر است یا کدام scope کم است. +- اجرای همه چک‌ها روی ویندوز بدون پنجره کنسول (`CREATE_NO_WINDOW` + `STARTUPINFO`): exe پنجره‌ای است و هر spawn بدون این فلگ یک cmd فلش می‌زد. همین برای sidecar کپچا و taskkill هم اعمال شد. +- نتیجه Doctor در Overview بین pollهای ۱۰ ثانیه‌ای کش می‌شود و فقط با «Run health check»، Repair یا ورود مجدد به صفحه دوباره اجرا می‌شود؛ قبلاً هر ۱۰ ثانیه چند پروسه Python/Node تازه spawn می‌شد. + --- ## 5. فاز ۳ — اوتوماسیون قابل اعتماد diff --git a/WORKBUDDY_MEMORY.md b/WORKBUDDY_MEMORY.md index f19c024..7eeb9c2 100644 --- a/WORKBUDDY_MEMORY.md +++ b/WORKBUDDY_MEMORY.md @@ -179,6 +179,15 @@ --- +### 2026-11-30 01:25 — رفع فلش‌زدن پنجره‌های cmd +- علت اصلی: صفحه Overview هر ۱۰ ثانیه `/admin/dash/doctor` را دوباره صدا می‌زد و Config Doctor هر بار ۴-۵ پروسه (python/node) را بدون `CREATE_NO_WINDOW` اجرا می‌کرد → پشت‌سرهم cmd فلش می‌زد. sidecar کپچا و `claim_start` هم فلگ مخفی نداشتند. +- فیکس: هِلپر `_hidden()` در `config_doctor.py` و `captcha_tickets.py`؛ فلگ مخفی در sidecar `generator/claim_start.py`؛ کش `lastDoctor` در `overview.js` (doctor فقط در لود اول، Run health check و بعد از Repair دوباره اجرا می‌شود). +- تست‌ها: ۲ یونیت ویندوزی برای فلگ‌ها + ۱ تست Playwright برای poll نشدن doctor؛ ۳۳ تست داشبورد و ۵۶ تست افزوده‌ها سبز. +- exe/Setup با این تغییر بازسازی شدند (exe 00:54، Setup 00:55). تست exe: در ۱۱.۵ ثانیه فقط ۱ درخواست doctor، کلیک Run health check یکی اضافه کرد؛ صفحه Doctor ۱۱ کارت؛ نسخه نصب‌شده هم asset جدید را سرو کرد و آنینستال تمیز بود. +- نکته: در تست اول، یک exe قدیمی جامانده (orphan) پورت 8788 را گرفته بود و نتیجه را گمراه کرد؛ kill شد. یک تغییر uncommitted در `zcode_gateway/api_dash.py` (ساعت 00:54) دیده شد که کار من نیست و دست‌نخورده ماند. + +--- + ## 5. وضعیت تحویل - PR #7 ساخته شد (از fork `Esmail-sarhadi`) و منتظر review/merge اسماعیل است. diff --git a/generator/claim_start.py b/generator/claim_start.py index e3fab77..2e19ed4 100644 --- a/generator/claim_start.py +++ b/generator/claim_start.py @@ -114,7 +114,8 @@ class Limits(ctypes.Structure): raise OSError('cannot create owned sidecar job') child = subprocess.Popen(argv, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - creationflags=(0x4 if os.name == 'nt' else 0), + creationflags=((0x4 | getattr(subprocess, 'CREATE_NO_WINDOW', 0)) + if os.name == 'nt' else 0), start_new_session=(os.name != 'nt')) if job and not kernel.AssignProcessToJobObject(job, int(child._handle)): raise OSError('cannot assign sidecar to owned job') diff --git a/tests/test_dashboard_review_fixes.py b/tests/test_dashboard_review_fixes.py index 7f513a7..a91e11f 100644 --- a/tests/test_dashboard_review_fixes.py +++ b/tests/test_dashboard_review_fixes.py @@ -35,6 +35,13 @@ def dashboard(): "/admin/dash/auth/login/status": {"state": "waiting"}, "/admin/dash/auth/login/cancel": {"ok": True}, "/admin/dash/logs": {"records": []}, + "/admin/dash/server": {"host": "127.0.0.1", "port": 8788, + "endpoints": {"openai": "/v1/chat/completions", + "anthropic": "/v1/messages", + "models": "/v1/models"}}, + "/admin/dash/generator/rate-limit": {}, + "/admin/dash/zcode-status": {}, + "/admin/dash/analytics/overview": {"summary": {}}, "/admin/dash/doctor": {"overall": "ok", "failed": [], "checks": {"python": {"status": "ok", "detail": "fixture"}}}, "/admin/dash/reports": {"reports": []}, @@ -114,6 +121,19 @@ def test_config_doctor_mounts_checks(dashboard): assert "Everything ready" in page.inner_text(".doctor-summary") +def test_overview_poll_does_not_rerun_doctor_checks(dashboard): + """Doctor checks spawn processes; the 10s poll must reuse the last result.""" + page, _, _, calls = dashboard + mount(page, "overview") + doctor = lambda: [call for call in calls if call[1] == "/admin/dash/doctor"] # noqa: E731 + assert len(doctor()) == 1 + page.evaluate("() => window.view.refresh()") + assert len(doctor()) == 1 + page.get_by_role("button", name="Run health check", exact=True).click() + page.wait_for_timeout(500) + assert len(doctor()) == 2 + + def test_dashboard_sidebar_opens_separate_generator_and_route_pages(dashboard): page, _, defaults, calls = dashboard defaults.update({ diff --git a/tests/test_workbuddy_additions.py b/tests/test_workbuddy_additions.py index 9995f9e..37583c7 100644 --- a/tests/test_workbuddy_additions.py +++ b/tests/test_workbuddy_additions.py @@ -484,3 +484,85 @@ def test_no_proxy_result_builds_httpx_client(monkeypatch): normalize_no_proxy() client = httpx.Client(timeout=1) client.close() + + +# ---- windowless child processes ----------------------------------------- # + +def test_doctor_run_hides_child_console(monkeypatch): + if os.name != "nt": + pytest.skip("Windows console flags") + from zcode_gateway import config_doctor as cd + + seen = {} + + class Proc: + returncode = 0 + stdout = "Python 3.13.0" + stderr = "" + + def fake_run(argv, **kwargs): + seen.update(kwargs) + return Proc() + + monkeypatch.setattr(cd.subprocess, "run", fake_run) + assert cd._run(["python", "--version"]) == (0, "Python 3.13.0") + assert seen["creationflags"] & cd.subprocess.CREATE_NO_WINDOW + assert seen["startupinfo"].dwFlags & cd.subprocess.STARTF_USESHOWWINDOW + + +def test_captcha_sidecar_hides_child_console(monkeypatch): + if os.name != "nt": + pytest.skip("Windows console flags") + from zcode_gateway import captcha_tickets as ct + + seen = {} + + class Proc: + returncode = 0 + stdout = "t" * 30 + " sgp\n" + stderr = "" + + def fake_run(argv, **kwargs): + seen.update(kwargs) + return Proc() + + monkeypatch.setenv("ZAI_CAPTCHA_CMD", "dummy-mint") + monkeypatch.setattr(ct.subprocess, "run", fake_run) + ticket = ct.sidecar_mint(timeout=5) + assert ticket is not None and ticket.region == "sgp" + assert seen["creationflags"] & ct.subprocess.CREATE_NO_WINDOW + assert seen["startupinfo"].dwFlags & ct.subprocess.STARTF_USESHOWWINDOW + + +# ---- doctor secret handling ----------------------------------------------- # + +def test_doctor_uses_live_mail_secrets_internally(): + from types import SimpleNamespace + from zcode_gateway.api_dash import _doctor_mail_cfg + + mgr = SimpleNamespace(mail_cfg={"cf_api_token": "cfat_secret123", + "inbox_secret": "supersecret"}) + live = _doctor_mail_cfg(mgr) + assert live["cf_api_token"] == "cfat_secret123" + assert live["inbox_secret"] == "supersecret" + assert _doctor_mail_cfg(None) == {} + + +def test_doctor_output_never_contains_live_secrets(monkeypatch): + from zcode_gateway import config_doctor as cd + + live = {"cf_api_token": "cfat_secret123", "inbox_secret": "supersecret", + "inbox_url": "https://worker.example/inbox", "domains": ["example.com"], + "cf_account_id": "a" * 32} + + monkeypatch.setattr(cd, "_http_json", lambda url, token="": (200, { + "success": True, + "result": [{"id": "z"}] if url.endswith("/zones?per_page=1") else [], + })) + checks = { + "cloudflare": cd.check_cloudflare(live), + "inbox": cd.check_inbox(live), + } + blob = str(checks) + assert "cfat_secret123" not in blob + assert "supersecret" not in blob diff --git a/zcode_gateway/captcha_tickets.py b/zcode_gateway/captcha_tickets.py index cb07d7d..79291c7 100644 --- a/zcode_gateway/captcha_tickets.py +++ b/zcode_gateway/captcha_tickets.py @@ -46,6 +46,16 @@ class CaptchaTicket: minted_at: float +def _hidden() -> dict: + """The gateway runs windowed: keep sidecar consoles invisible.""" + if os.name != "nt": + return {} + si = subprocess.STARTUPINFO() + si.dwFlags |= subprocess.STARTF_USESHOWWINDOW + si.wShowWindow = subprocess.SW_HIDE + return {"creationflags": subprocess.CREATE_NO_WINDOW, "startupinfo": si} + + def _find_sidecar() -> str: """The bundled captcha-mint binary, or '' when this install has none.""" name = "captcha-mint.exe" if os.name == "nt" else "captcha-mint" @@ -86,7 +96,7 @@ def sidecar_mint(timeout: float = 45.0) -> CaptchaTicket | None: try: out = subprocess.run([cmd], env=env, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, - shell=False) + shell=False, **_hidden()) except (OSError, subprocess.SubprocessError) as e: log.debug("captcha sidecar failed to run: %s", e) return None diff --git a/zcode_gateway/config_doctor.py b/zcode_gateway/config_doctor.py index d697ae5..8badb22 100644 --- a/zcode_gateway/config_doctor.py +++ b/zcode_gateway/config_doctor.py @@ -36,10 +36,20 @@ def result(ok, status, detail="", hint="", fixable=False) -> dict: } +def _hidden() -> dict: + """The app ships windowed: a bare spawn would flash a console window.""" + if os.name != "nt": + return {} + si = subprocess.STARTUPINFO() + si.dwFlags |= subprocess.STARTF_USESHOWWINDOW + si.wShowWindow = subprocess.SW_HIDE + return {"creationflags": subprocess.CREATE_NO_WINDOW, "startupinfo": si} + + def _run(argv, timeout=TIMEOUT) -> tuple[int, str]: try: proc = subprocess.run(argv, capture_output=True, text=True, - timeout=timeout, check=False) + timeout=timeout, check=False, **_hidden()) return proc.returncode, (proc.stdout or "") + (proc.stderr or "") except FileNotFoundError: return 127, "not found" diff --git a/zcode_gateway/dashboard/assets/js/views/overview.js b/zcode_gateway/dashboard/assets/js/views/overview.js index b2ab27d..c1dbcc1 100644 --- a/zcode_gateway/dashboard/assets/js/views/overview.js +++ b/zcode_gateway/dashboard/assets/js/views/overview.js @@ -199,12 +199,13 @@ export async function mount({ root, signal }) { // ---- data ------------------------------------------------------------- let repairing = false; + let lastDoctor = null; - async function load() { + async function load({ withDoctor = lastDoctor == null } = {}) { const paths = [ "/admin/dash/server", "/admin/pool/state", - "/admin/dash/doctor", + ...(withDoctor ? ["/admin/dash/doctor"] : []), "/admin/dash/generator/rate-limit", "/admin/dash/zcode-status", "/admin/dash/analytics/overview?range=24h", @@ -213,8 +214,11 @@ export async function mount({ root, signal }) { ]; const results = await Promise.allSettled(paths.map((path) => api.get(path, { signal }))); if (signal.aborted) return; - const [server, pool, doctor, rate, zcode, usage, reports, logs] = - results.map((result) => result.status === "fulfilled" ? result.value : null); + const values = results.map((result) => result.status === "fulfilled" ? result.value : null); + const [server, pool, ...rest] = values; + const doctor = withDoctor ? rest.shift() : lastDoctor; + const [rate, zcode, usage, reports, logs] = rest; + if (withDoctor) lastDoctor = doctor; paintHero(server, pool, doctor, zcode); paintAlerts(rate); @@ -417,8 +421,8 @@ export async function mount({ root, signal }) { healthBtn.setAttribute("aria-busy", "true"); healthBtn.disabled = true; try { - const doctor = await api.get("/admin/dash/doctor", { signal }); - await load(); + lastDoctor = await api.get("/admin/dash/doctor", { signal }); + await load({ withDoctor: false }); const failed = (doctor.failed || []).length; toast(failed ? "Health check finished — " + failed + " item(s) need attention" : "All checks pass", failed ? "warn" : "ok"); @@ -439,6 +443,7 @@ export async function mount({ root, signal }) { const leftover = (result.actions || []).filter((action) => action.error).length; toast(leftover ? "Repaired what was safe — " + leftover + " manual step(s) left" : "Safe repairs applied", leftover ? "warn" : "ok"); + lastDoctor = null; await load(); } catch (error) { toast("Repair failed: " + error.message, "err"); @@ -453,6 +458,7 @@ export async function mount({ root, signal }) { try { await api.post("/admin/dash/doctor/repair", { check: name }, { signal }); toast("Repair attempted for " + (CHECK_LABELS[name] || name), "ok"); + lastDoctor = null; await load(); } catch (error) { toast("Repair failed: " + error.message, "err"); From 246f92207edccc4c79c71cdbdb5e898074d76329 Mon Sep 17 00:00:00 2001 From: Esmail-sarhadi <45729949+Esmail-sarhadi@users.noreply.github.com> Date: Mon, 30 Nov 2026 01:09:13 +0330 Subject: [PATCH 10/15] fix(doctor): probe with live mail secrets and record reconfiguration --- WORKBUDDY_MEMORY.md | 15 +++++++++++++++ zcode_gateway/api_dash.py | 15 ++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/WORKBUDDY_MEMORY.md b/WORKBUDDY_MEMORY.md index 7eeb9c2..3f133b1 100644 --- a/WORKBUDDY_MEMORY.md +++ b/WORKBUDDY_MEMORY.md @@ -204,3 +204,18 @@ - تا ندیدهام «انجام شد» نمیگویم: تستها را اجرا میکنم و خروجی را میبینم. - سورس کاربر مال خودش است؛ در فایلهای اصلیاش جز تغییرات لازم دست نمیزنم. - توکن Cloudflare و inbox secret را دوباره در چت نمیآورم. + +--- + +### 2026-11-30 — بازپیکربندی نسخه نصب‌شده توسط اسماعیل +- نسخه جدید توسط اسماعیل نصب شده بود (`C:\Program Files\Zcode Gateway`)، ولی دادهها در `%LOCALAPPDATA%\ZcodeGateway` میرفتند؛ تنظیمات ایمیل در پوشه قدیمی `Downloads\generator-data` مانده بود و اپ هیچ دامنه/توکانی نمیدید. +- وضعیت قبل: Doctor `blocked`، Email setup خالی، Pool `0/0`. دلیل اصلی: جابجایی data dir در نسخه نصبی (`installed.flag`) نه خرابی ورکر. +- اقدام: + 1. توکن Cloudflare، account id، دامنه `esmailsarhadi.xyz`، inbox URL و secret از فایل قدیمی خوانده شد (مقادیر در چت چاپ نشدند). + 2. از طریق API داخلی اپ (`/admin/dash/generator/mail/cf-credentials`, `/mail`, `/mail/routing`) دوباره ذخیره شد. چرخش دامنه (`rotate: true`) هم روشن شد تا دامنههای بعدی هم استفاده شوند. + 3. تست inbox: `ok=true`, HTTP 200. Routing catch-all روی ورکر `zai-mail` هنوز فعال است (چک خواندنی از Cloudflare). + 4. شش snapshot اکانت از `Downloads\generator-data\results` به فرمت snapshot تبدیل و وارد pool شدند؛ ولی z.ai همه آنها را `ZCode token revoked` اعلام کرد. بنابراین حذف شدند و pool عمداً خالی ماند (آمار دروغین «4 ready» ننویسی). +- باگ پیدا شده: `mail_config()` توکن/secret را برای UI پاک میکند، ولی Config Doctor همان خروجی پاکشده را چک میکرد → همیشه میگفت «no token saved». فیکس: `_doctor_mail_cfg()` در `api_dash.py` مقادیر زنده داخلی را به Doctor میدهد؛ خروجی Doctor از `redact()` میگذرد. دو تست اضافه شد: 58 passed. +- exe و Setup دوباره ساخته شدند (v3.0.0). تست ایزوله با `ZGW_DATA_DIR` و پورت 8890 نشان داد Doctor بعد از بارگذاری تنظیمات ایمیل: `cloudflare=ok`, `inbox=ok`, `wrangler=ok`, `mail_rotation=ok`. فقط `pool` و `packages` به دلیل نبود اکانت معتبر و نبود yaml در Python سیستم باقی ماندند. +- نتوانستم exe را مستقیم در `Program Files` کپی کنم (دسترسی رد شد). نسخه نصبشده قدیمی دوباره راهاندازی شد و تنظیمات ایمیل در آن سالم است؛ برای فیکس Doctor باید Setup جدید اجرا شود: `.local\dist\ZcodeGateway-Setup-3.0.0.exe`. +- تغییرات uncommitted مال اسماعیل/جلسه دیگری دستنخورده ماندند؛ تنها `api_dash.py` و انتهای فایل تست توسط من تغییر یافتند. diff --git a/zcode_gateway/api_dash.py b/zcode_gateway/api_dash.py index 10ebb2b..cd98f68 100644 --- a/zcode_gateway/api_dash.py +++ b/zcode_gateway/api_dash.py @@ -1697,6 +1697,16 @@ async def generator_rate_limit(request: Request, key: str = Depends(admin_key)) return {**status(data_dir), "notice": compliance_notice()} +def _doctor_mail_cfg(mgr) -> dict: + """Live mail settings for internal health probes. + + The dashboard-facing mail_config() deliberately removes cf_api_token and + inbox_secret; Config Doctor must still be able to verify them. The result + never leaves the server: every doctor check is passed through redact(). + """ + return dict(getattr(mgr, "mail_cfg", {})) if mgr else {} + + @router.get("/admin/dash/doctor") async def doctor_get(request: Request, key: str = Depends(admin_key)) -> dict: """One-call, secret-safe health check of the whole installation.""" @@ -1704,7 +1714,10 @@ async def doctor_get(request: Request, key: str = Depends(admin_key)) -> dict: state = get_state(request) pool = await state.pool.snapshot() mgr = getattr(state, "generator", None) - mail = mgr.mail_config() if mgr and hasattr(mgr, "mail_config") else {} + # Doctor needs the live secret values to probe Cloudflare and the inbox; + # mail_config() strips them for dashboard display. Nothing from this dict + # is returned to the client: every check result goes through redact(). + mail = _doctor_mail_cfg(mgr) custom = {} if mgr: options = mgr.options() From 77efd5adc2f17bdac0f6ded9f8054c282be0e8a8 Mon Sep 17 00:00:00 2001 From: Esmail-sarhadi <45729949+Esmail-sarhadi@users.noreply.github.com> Date: Mon, 30 Nov 2026 09:14:50 +0330 Subject: [PATCH 11/15] fix: clear Safe Mode errors, open reports reliably and expose accounts folder --- WORKBUDDY_MEMORY.md | 12 +++ tests/test_workbuddy_additions.py | 41 ++++++++ zcode_gateway/api_dash.py | 93 ++++++++++++++++++- zcode_gateway/config_doctor.py | 34 +++++-- .../dashboard/assets/css/components.css | 81 ++++++++++++++++ zcode_gateway/dashboard/assets/js/boot.js | 13 ++- .../dashboard/assets/js/core/report.js | 33 +++++++ .../dashboard/assets/js/views/accounts.js | 42 ++++++++- .../assets/js/views/auto-generate.js | 31 ++++--- .../dashboard/assets/js/views/doctor.js | 15 ++- zcode_gateway/dashboard/index.html | 4 + zcode_gateway/rate_limit.py | 26 +++++- 12 files changed, 384 insertions(+), 41 deletions(-) create mode 100644 zcode_gateway/dashboard/assets/js/core/report.js diff --git a/WORKBUDDY_MEMORY.md b/WORKBUDDY_MEMORY.md index 3f133b1..3a46cd5 100644 --- a/WORKBUDDY_MEMORY.md +++ b/WORKBUDDY_MEMORY.md @@ -219,3 +219,15 @@ - exe و Setup دوباره ساخته شدند (v3.0.0). تست ایزوله با `ZGW_DATA_DIR` و پورت 8890 نشان داد Doctor بعد از بارگذاری تنظیمات ایمیل: `cloudflare=ok`, `inbox=ok`, `wrangler=ok`, `mail_rotation=ok`. فقط `pool` و `packages` به دلیل نبود اکانت معتبر و نبود yaml در Python سیستم باقی ماندند. - نتوانستم exe را مستقیم در `Program Files` کپی کنم (دسترسی رد شد). نسخه نصبشده قدیمی دوباره راهاندازی شد و تنظیمات ایمیل در آن سالم است؛ برای فیکس Doctor باید Setup جدید اجرا شود: `.local\dist\ZcodeGateway-Setup-3.0.0.exe`. - تغییرات uncommitted مال اسماعیل/جلسه دیگری دستنخورده ماندند؛ تنها `api_dash.py` و انتهای فایل تست توسط من تغییر یافتند. + +--- + +### 2026-11-30 09:15 — بازیابی اکانت‌ها + فیکس‌های Safe Mode، گزارش و UI +- **هیچ اکانتی پاک نشده بود.** پوشه `%LOCALAPPDATA%\ZcodeGateway\accounts` دقیقاً ۲۱ فایل داشت و بعد از restart همه ۲۱ به‌صورت ready بالا آمدند. علت خالی دیدن UI این بود که اپ برای تست build متوقف شده بود، نه حذف داده. +- ۱۵ فایل اکانت از `Downloads\accounts` به همان پوشه کپی شد (بدون overwrite فایل‌های تازه‌تر). بعد از `Reload pool`: **۳۶ اکانت، ۳۵ ready، ۱ dead** (فقط `kojaveh@gmail.com` با پیام `plan lost`). +- Safe Mode واقعی است: z.ai در ۰۸:۴۹ برای scope=`signup:ip` مقدار `retry_after_seconds=67245` (~۱۸h 40m) داده؛ unlock حدود ۰۳:۳۰ بامداد. هیچ دور زدنی انجام نشد. +- باگ `Internal Server Error` روی Resume: `guard()` بیرون از try صدا زده می‌شد و RuntimeError به 500 تبدیل می‌شد. حالا `_guard_rate_limit()` آن را به **409 با پیام واضح** تبدیل می‌کند و دکمه Resume در Safe Mode غیرفعال است. +- گزارش HTML باز نمی‌شد چون `window.open` بعد از `await fetch` توسط popup blocker مسدود می‌شد. `core/report.js` تب را همگام باز می‌کند و بعد blob را جایگزین می‌کند؛ لیست گزارش‌ها هم دکمه Open دارد. +- Doctor: به‌جای `mail_config()` ماسک‌شده از `mail_cfg` زنده استفاده می‌کند؛ پکیج‌ها با interpreter واقعی worker (`mgr.python_exe`) و لیست واقعی generator چک می‌شوند (yaml حذف شد)؛ مسیر generator از `mgr.gen_dir` خوانده می‌شود تا `_MEI...` قدیمی false negative ندهد. +- UI: انتخابگر تم در topbar، دکمه/کارت/بج صیقل‌خورده، نوار «Accounts folder» با Copy/Open، و دکمه «Import folder» در Accounts. +- تست‌ها: `61 passed`. Setup نهایی: `.local\dist\ZcodeGateway-Setup-3.0.0.exe`. اپ نصب‌شده فعلاً exe قدیمی دارد؛ برای اعمال این فیکس‌ها Setup جدید باید اجرا شود. diff --git a/tests/test_workbuddy_additions.py b/tests/test_workbuddy_additions.py index 37583c7..162674b 100644 --- a/tests/test_workbuddy_additions.py +++ b/tests/test_workbuddy_additions.py @@ -566,3 +566,44 @@ def test_doctor_output_never_contains_live_secrets(monkeypatch): blob = str(checks) assert "cfat_secret123" not in blob assert "supersecret" not in blob + + +# ---- safe-mode HTTP contract --------------------------------------------- # + +def test_guard_rate_limit_returns_409(tmp_path): + import json, time + from fastapi import HTTPException + from zcode_gateway.api_dash import _guard_rate_limit + (tmp_path / "rate_limit.json").write_text(json.dumps({ + "unlock_at": time.time() + 3600, + "retry_after_seconds": 3600, + "scope": "signup:ip", + }), encoding="utf-8") + try: + _guard_rate_limit(tmp_path) + except HTTPException as exc: + assert exc.status_code == 409 + assert "rate limit" in exc.detail.lower() + else: + raise AssertionError("Safe Mode should block start/resume with 409") + + +def test_rate_limit_status_has_human_countdown(tmp_path): + import json, time + from zcode_gateway import rate_limit + (tmp_path / "rate_limit.json").write_text(json.dumps({ + "unlock_at": time.time() + 3700, + "retry_after_seconds": 3700, + "scope": "signup:ip", + }), encoding="utf-8") + state = rate_limit.status(tmp_path) + assert state["active"] is True + assert "1h" in state["seconds_left_human"] + assert state["unlock_at_iso"] + + +def test_doctor_checks_generator_packages_not_gateway_yaml(): + from zcode_gateway import config_doctor as cd + assert "yaml" not in cd.REQUIRED_PACKAGES + assert "ddddocr" in cd.REQUIRED_PACKAGES + assert "playwright" in cd.REQUIRED_PACKAGES diff --git a/zcode_gateway/api_dash.py b/zcode_gateway/api_dash.py index cd98f68..fd433dd 100644 --- a/zcode_gateway/api_dash.py +++ b/zcode_gateway/api_dash.py @@ -11,6 +11,7 @@ import json import logging import os +import shutil import sys import threading import tempfile @@ -1757,6 +1758,78 @@ async def doctor_repair(request: Request, body: dict = Body(default={}), return {"check": check, "actions": actions} +@router.get("/admin/dash/accounts-folder") +async def accounts_folder_get(request: Request, key: str = Depends(admin_key)) -> dict: + """Where snapshots live for this install (portable vs Program Files).""" + from .paths import find_accounts_dir + folder = find_accounts_dir() + try: + count = sum(1 for p in folder.glob("*.txt") if p.is_file()) + except OSError: + count = 0 + return {"path": str(folder), "exists": folder.is_dir(), "count": count} + + +@router.post("/admin/dash/accounts-folder/open") +async def accounts_folder_open(request: Request, key: str = Depends(admin_key)) -> dict: + """Open the accounts folder in the desktop file manager (local only).""" + if not peer_is_local(request): + raise HTTPException(status_code=403, detail="only a local dashboard may open folders") + from .paths import find_accounts_dir + folder = find_accounts_dir() + if not folder.is_dir(): + raise HTTPException(status_code=404, detail="accounts folder does not exist yet") + if os.name != "nt": + raise HTTPException(status_code=400, detail="folder opening is only wired for Windows") + try: + os.startfile(str(folder)) # type: ignore[attr-defined] + except OSError as exc: + raise HTTPException(status_code=500, detail=f"could not open folder: {exc.__class__.__name__}") from None + return {"ok": True, "path": str(folder)} + + +@router.post("/admin/dash/accounts/import-folder") +async def accounts_import_folder(request: Request, body: dict = Body(default={}), + key: str = Depends(admin_key)) -> dict: + """Copy snapshot .txt files from an existing folder into this install. + + Read-only on the source folder: files are copied, never moved or changed. + """ + from .paths import find_accounts_dir + from .accounts_dir import parse_snapshot + raw = str((body or {}).get("path") or "").strip() + if not raw: + raise HTTPException(status_code=400, detail="paste the folder that holds the .txt snapshots") + source = Path(raw).expanduser() + if not source.is_dir(): + raise HTTPException(status_code=404, detail="that folder does not exist") + dest = find_accounts_dir() + dest.mkdir(parents=True, exist_ok=True) + copied = skipped = invalid = 0 + for path in sorted(source.glob("*.txt")): + try: + fields = parse_snapshot(path) + except Exception: + invalid += 1 + continue + if not fields.get("access_token"): + invalid += 1 + continue + target = dest / path.name + try: + if target.exists() and target.stat().st_mtime >= path.stat().st_mtime: + skipped += 1 + continue + shutil.copy2(path, target) + copied += 1 + except OSError: + invalid += 1 + from .api_admin import reload_pool_from_disk + loaded = await reload_pool_from_disk(get_state(request)) + return {"copied": copied, "skipped": skipped, "invalid": invalid, + "folder": str(dest), "pool": loaded} + + @router.get("/admin/dash/reports") async def reports_list(request: Request, key: str = Depends(admin_key)) -> dict: from .run_report import list_reports @@ -1886,6 +1959,20 @@ async def generator_vpn_settings(request: Request, kind: str, body: dict = Body( return await _vpn_action(_vpn_pool(request, kind).set_settings, body) +def _guard_rate_limit(data_dir: Path) -> None: + """Turn Safe Mode into a clear 409 instead of an unhandled 500. + + The old call let RuntimeError escape before the endpoint's try block, so + the dashboard showed "Internal Server Error" and then marked the gateway + unreachable even though only the signup route was rate-limited. + """ + from .rate_limit import guard + try: + guard(data_dir) + except RuntimeError as exc: + raise HTTPException(status_code=409, detail=str(exc)) from None + + @router.post("/admin/dash/generator/start") async def generator_start(request: Request, body: dict = Body(default={}), key: str = Depends(admin_key)) -> dict: @@ -1895,8 +1982,7 @@ async def generator_start(request: Request, body: dict = Body(default={}), except (TypeError, ValueError): raise HTTPException(status_code=400, detail="count must be an integer") from None count = max(1, min(count, 10)) - from .rate_limit import guard - guard(_runtime_data_dir(request)) + _guard_rate_limit(_runtime_data_dir(request)) mgr = _generator(request) def _emit(line: str) -> None: @@ -1945,8 +2031,7 @@ async def auto_generate_action(request: Request, action: str, key: str = Depends if action not in ("start", "pause", "resume", "stop"): raise HTTPException(404, "Unknown Auto Generate action") if action in ("start", "resume"): - from .rate_limit import guard - guard(_runtime_data_dir(request)) + _guard_rate_limit(_runtime_data_dir(request)) manager = _generator(request) controller = manager.auto_generate try: diff --git a/zcode_gateway/config_doctor.py b/zcode_gateway/config_doctor.py index 8badb22..4d9a0cb 100644 --- a/zcode_gateway/config_doctor.py +++ b/zcode_gateway/config_doctor.py @@ -22,7 +22,11 @@ from .run_report import redact TIMEOUT = 8 -REQUIRED_PACKAGES = ("playwright", "ddddocr", "cv2", "httpx", "yaml") +# What the bundled generator actually imports (generator/requirements.txt). +# yaml/httpx belong to the gateway itself and are already inside the exe; a +# system Python without them used to make the whole Doctor look blocked. +REQUIRED_PACKAGES = ("playwright", "ddddocr", "cv2", "PIL", "numpy", + "requests", "urllib3", "certifi", "socks") def result(ok, status, detail="", hint="", fixable=False) -> dict: @@ -72,8 +76,21 @@ def _http_json(url: str, token: str = "") -> tuple[int, dict | None]: return 0, None +def _generator_python(python_exe: str = "") -> str: + """The interpreter the generator will really use (venv, explicit, PATH). + + Checking a bare `python` on PATH was wrong on packaged installs: the app + runs workers with resolve_python(), which prefers its private genenv. + """ + try: + from .generator import resolve_python + return resolve_python(python_exe) + except Exception: + return python_exe.strip() or shutil.which("python") or sys.executable + + def check_python(python_exe: str = "") -> dict: - exe = python_exe.strip() or shutil.which("python") or sys.executable + exe = _generator_python(python_exe) code, output = _run([exe, "--version"]) version = " ".join(output.split())[:80] if code == 0 and version.lower().startswith("python"): @@ -84,7 +101,7 @@ def check_python(python_exe: str = "") -> dict: def check_packages(python_exe: str = "") -> dict: - exe = python_exe.strip() or shutil.which("python") or sys.executable + exe = _generator_python(python_exe) script = ("import importlib.util,json;print(json.dumps({m:bool(importlib.util.find_spec(m)) " "for m in %s}))" % json.dumps(list(REQUIRED_PACKAGES))) code, output = _run([exe, "-c", script], timeout=15) @@ -102,7 +119,7 @@ def check_packages(python_exe: str = "") -> dict: def check_chromium(python_exe: str = "") -> dict: - exe = python_exe.strip() or shutil.which("python") or sys.executable + exe = _generator_python(python_exe) script = ("from playwright.sync_api import sync_playwright\n" "with sync_playwright() as p: print(p.chromium.executable_path)") code, output = _run([exe, "-c", script], timeout=15) @@ -260,9 +277,14 @@ def run_doctor(state, pool_snapshot: dict | None = None, """Run every check. Safe to call from a worker thread.""" cfg = getattr(state, "cfg", None) gen = getattr(cfg, "generator", None) - python_exe = str(getattr(gen, "python_exe", "") or "") - configured_dir = str(getattr(gen, "zcodeauto_dir", "") or "") mgr = getattr(state, "generator", None) + # The manager has already resolved the interpreter workers will spawn with; + # checking a different `python` on PATH was the source of false "missing + # package" reports on packaged installs. + python_exe = str(getattr(mgr, "python_exe", "") or getattr(gen, "python_exe", "") or "") + # Prefer the directory the manager actually resolved (the PyInstaller + # _MEIPASS path changes on every launch, so the saved value goes stale). + configured_dir = str(getattr(mgr, "gen_dir", "") or getattr(gen, "zcodeauto_dir", "") or "") if mail_cfg is None: mail_cfg = mgr.mail_config() if mgr and hasattr(mgr, "mail_config") else {} data_dir = "" diff --git a/zcode_gateway/dashboard/assets/css/components.css b/zcode_gateway/dashboard/assets/css/components.css index de443b7..1c8f7f3 100644 --- a/zcode_gateway/dashboard/assets/css/components.css +++ b/zcode_gateway/dashboard/assets/css/components.css @@ -1542,3 +1542,84 @@ .ov-loading { display: grid; gap: var(--s-3); } .ov-loading .skeleton { height: 14px; } + +/* ---- polish pass: account folder, theme picker, tactile surfaces -------- */ +.accounts-folder { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: var(--s-3); + padding: var(--s-3) var(--s-4); + border: 1px solid var(--border-subtle); + border-radius: var(--r-lg); + background: color-mix(in srgb, var(--surface-2) 72%, transparent); +} +.accounts-folder__label { + color: var(--fg-muted); + font-size: var(--text-xs); + text-transform: uppercase; + letter-spacing: 0.05em; +} +.accounts-folder__path { + min-width: 0; + max-width: min(62ch, 100%); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--fg); + font-size: var(--text-xs); +} + +.theme-picker { + display: inline-flex; + align-items: center; + gap: var(--s-2); + padding: 0 var(--s-1); +} +.theme-picker__label { + color: var(--fg-faint); + font-size: var(--text-xs); + letter-spacing: 0.04em; + text-transform: uppercase; +} +.theme-picker select { + height: 28px; + max-width: 132px; + padding: 0 24px 0 var(--s-3); + border: 1px solid var(--border); + border-radius: var(--r-md); + background: var(--surface-2); + color: var(--fg); + font-size: var(--text-xs); +} +.theme-picker select:hover { border-color: var(--border-strong); } +.theme-picker select:focus-visible { box-shadow: var(--focus-ring); outline: none; } +@media (max-width: 760px) { + .theme-picker__label { display: none; } + .theme-picker select { max-width: 110px; } +} + +.card { + transition: border-color var(--dur-2) var(--ease-out), + box-shadow var(--dur-2) var(--ease-out), + transform var(--dur-2) var(--ease-out); +} +.card:hover { + border-color: color-mix(in srgb, var(--accent) 28%, var(--border)); + box-shadow: var(--shadow-md); +} +.metric { + transition: border-color var(--dur-2) var(--ease-out), + transform var(--dur-2) var(--ease-out); +} +.metric:hover { + border-color: color-mix(in srgb, var(--accent) 24%, var(--border)); + transform: translateY(-1px); +} +.btn { letter-spacing: 0.005em; } +.btn--primary:not(:disabled) { + background-size: 140% 140%; + background-position: 0% 50%; +} +.btn--primary:hover:not(:disabled) { background-position: 100% 50%; } +.badge { font-weight: var(--weight-semibold); letter-spacing: 0.01em; } diff --git a/zcode_gateway/dashboard/assets/js/boot.js b/zcode_gateway/dashboard/assets/js/boot.js index 43c3448..d182877 100644 --- a/zcode_gateway/dashboard/assets/js/boot.js +++ b/zcode_gateway/dashboard/assets/js/boot.js @@ -193,8 +193,19 @@ function wireLogin(onSuccess) { function wireChrome() { const themeBtn = $("#theme-toggle"); - const paintTheme = () => fill(themeBtn, icon(theme.isLight() ? ICONS.moon : ICONS.sun)); + const themeSelect = $("#theme-select"); + if (themeSelect) { + for (const [value, label] of Object.entries(theme.LABELS)) { + themeSelect.add(new Option(label, value)); + } + } + const paintTheme = () => { + fill(themeBtn, icon(theme.isLight() ? ICONS.moon : ICONS.sun)); + if (themeSelect) themeSelect.value = theme.current(); + themeBtn.title = "Theme: " + theme.LABELS[theme.current()] + " — click to cycle"; + }; themeBtn.addEventListener("click", () => { theme.toggle(); paintTheme(); }); + themeSelect?.addEventListener("change", () => { theme.apply(themeSelect.value); paintTheme(); }); paintTheme(); fill($("#btn-refresh"), icon(ICONS.refresh)); diff --git a/zcode_gateway/dashboard/assets/js/core/report.js b/zcode_gateway/dashboard/assets/js/core/report.js new file mode 100644 index 0000000..30d467c --- /dev/null +++ b/zcode_gateway/dashboard/assets/js/core/report.js @@ -0,0 +1,33 @@ +// Open an authenticated HTML report in a real tab. +// +// window.open() after an awaited fetch is treated as a popup and blocked by +// Chrome/Edge. Opening the blank tab synchronously (inside the click handler) +// keeps the user gesture, then we replace its location with the fetched blob. + +import { getKey } from "./api.js"; + +export async function openReport(url, { signal } = {}) { + const tab = window.open("", "_blank"); + if (!tab) { + throw new Error("Popup blocked — allow popups for this page, then retry"); + } + try { + tab.document.write( + "Loading report…" + + "Loading report…"); + tab.document.close(); + const response = await fetch(url, { + headers: { Authorization: "Bearer " + getKey() }, + signal, + }); + if (!response.ok) throw new Error("HTTP " + response.status); + const blob = new Blob([await response.text()], { type: "text/html" }); + const objectUrl = URL.createObjectURL(blob); + tab.location.replace(objectUrl); + setTimeout(() => URL.revokeObjectURL(objectUrl), 120000); + } catch (error) { + try { tab.close(); } catch (_) { /* already gone */ } + throw error; + } +} diff --git a/zcode_gateway/dashboard/assets/js/views/accounts.js b/zcode_gateway/dashboard/assets/js/views/accounts.js index 8814fa0..2150a1b 100644 --- a/zcode_gateway/dashboard/assets/js/views/accounts.js +++ b/zcode_gateway/dashboard/assets/js/views/accounts.js @@ -1,6 +1,6 @@ // Accounts: the pool table, per-account actions, and the Zcode login flow. -import { el, fill, $$ } from "../core/dom.js"; +import { el, fill, $$, copyText } from "../core/dom.js"; import { api } from "../core/api.js"; import { toast, confirmDialog } from "../core/toast.js"; import { card, table, toolbar, searchBox, button, stateBadge, badge, metric } from "../core/ui.js"; @@ -285,7 +285,7 @@ function applyFilter(root) { if (none) none.hidden = !(total > 0 && shown === 0); } -function render(root, accounts, pool, reload, signal, actions, campaign = {}, models) { +function render(root, accounts, pool, reload, signal, actions, campaign = {}, models, folder = null) { const rows = accounts.map((a) => Object.assign(a, { __searchText: [a.email, a.id, a.state, a.source, ...(a.capped_models || [])] .filter(Boolean).join(" ").toLowerCase(), @@ -326,6 +326,20 @@ function render(root, accounts, pool, reload, signal, actions, campaign = {}, mo const bar = toolbar([ button({ label: "Login with Zcode", icon: "key", variant: "primary", onClick: () => loginWithZcode(reload, signal) }), button({ label: "Import account", icon: "key", onClick: () => importJwt(reload) }), + button({ label: "Import folder", icon: "file", title: + "Copy snapshot .txt files from an existing accounts folder into this install", + onClick: async () => { + const path = window.prompt("Folder that contains the account .txt snapshots:", folder?.path || ""); + if (!path) return; + try { + const result = await api.post("/admin/dash/accounts/import-folder", { path }); + toast("Imported " + result.copied + " snapshot(s)" + + (result.skipped ? ", skipped " + result.skipped + " older" : "") + + (result.invalid ? ", ignored " + result.invalid + " invalid" : ""), + result.copied ? "ok" : "warn"); + await reload(true); + } catch (error) { toast("Import folder failed: " + error.message, "err"); } + } }), button({ label: "Copy all accounts", icon: "copy", onClick: copyAllAccountsForSharing }), // No desktop Zcode app on a server: the import would always 404. gate(button({ label: "Import from app", icon: "copy", onClick: () => importFromApp(reload) }), "import_from_app"), @@ -418,7 +432,23 @@ function render(root, accounts, pool, reload, signal, actions, campaign = {}, mo flush: true, }); - fill(root, el("div", { class: "stack" }, [summary, quotaTotals, bar, tableCard])); + const folderBar = el("div", { class: "accounts-folder" }, [ + el("span", { class: "accounts-folder__label", text: "Accounts folder" }), + el("code", { class: "mono accounts-folder__path", text: folder?.path || "not resolved yet", + title: folder?.path || "" }), + el("span", { class: "badge badge--info", text: (folder?.count ?? 0) + " file(s)" }), + el("span", { class: "spacer" }), + button({ label: "Copy path", variant: "quiet", + onClick: () => copyText(folder?.path || "").then(() => toast("Folder path copied", "ok")) }), + button({ label: "Open folder", variant: "quiet", disabled: !folder?.exists, + onClick: async () => { + try { await api.post("/admin/dash/accounts-folder/open", {}); + toast("Opened accounts folder", "ok"); } + catch (error) { toast("Could not open folder: " + error.message, "err"); } + } }), + ]); + + fill(root, el("div", { class: "stack" }, [summary, quotaTotals, bar, folderBar, tableCard])); applyFilter(root); } @@ -442,10 +472,11 @@ export async function mount({ root, signal }) { const load = async (force = false) => { if (signal.aborted || (actions.busy && !force)) return; const version = ++requestVersion; - const [accs, pool, campaign] = await Promise.all([ + const [accs, pool, campaign, folder] = await Promise.all([ api.get("/admin/accounts", { signal }), api.get("/admin/pool/state", { signal }), api.get("/admin/accounts/campaign_window", { signal }).catch(() => ({ gate: false })), + api.get("/admin/dash/accounts-folder", { signal }).catch(() => null), ]); if (signal.aborted || version !== requestVersion || (actions.busy && !force)) return; // Do not rebuild while the user is typing in the filter box. @@ -454,7 +485,8 @@ export async function mount({ root, signal }) { if (!force && filtering) { return; } - render(root, accs.accounts || [], pool || {}, load, signal, actions, campaign || {}, accs.models); + render(root, accs.accounts || [], pool || {}, load, signal, actions, + campaign || {}, accs.models, folder); if (filtering) root.querySelector('input[type="search"]')?.focus({ preventScroll: true }); }; diff --git a/zcode_gateway/dashboard/assets/js/views/auto-generate.js b/zcode_gateway/dashboard/assets/js/views/auto-generate.js index 72cfca1..c9cf189 100644 --- a/zcode_gateway/dashboard/assets/js/views/auto-generate.js +++ b/zcode_gateway/dashboard/assets/js/views/auto-generate.js @@ -1,9 +1,10 @@ import { el, fill, copyText } from "../core/dom.js"; import { toast } from "../core/toast.js"; -import { api, getKey } from "../core/api.js"; +import { api } from "../core/api.js"; import { card, button, stateBadge, badge } from "../core/ui.js"; import { platform } from "../core/caps.js"; import { logLineClass, logTone } from "../core/logs.js"; +import { openReport as openReportTab } from "../core/report.js"; const PATH = "/admin/dash/generator/auto"; const VPN_SOURCES = ["psiphon", "surfshark"]; @@ -333,7 +334,11 @@ export function createAutoGenerate({ signal } = {}) { pauseButton.hidden = !["preparing", "running", "starting", "cooling"].includes(status.state); resumeButton.hidden = !["paused", "interrupted"].includes(status.state); stopButton.hidden = !live(); - pauseButton.disabled = resumeButton.disabled = !!busy || !healthy || disposed; + pauseButton.disabled = !!busy || !healthy || disposed; + resumeButton.disabled = !!busy || !healthy || disposed || !!rateLock.active; + resumeButton.title = rateLock.active + ? "Safe Mode: provider rate limit is active until " + (rateLock.unlock_at_iso || "the timer ends") + : ""; stopButton.disabled = !!busy || !healthy || disposed || status.state === "stopping"; retryButton.disabled = !!busy || disposed; form.setAttribute("aria-busy", String(!!busy || !hydrated)); @@ -464,21 +469,16 @@ export function createAutoGenerate({ signal } = {}) { if (!disposed) paint(data); } catch (exception) { showError("Could not " + action + " session", exception); - healthy = false; + // A 409/429 is a valid server answer (e.g. Safe Mode). Only a transport + // failure should paint the whole gateway as unreachable. + if (exception.status == null || exception.status === 0) healthy = false; } finally { busy = ""; if (!disposed) renderControls(); } } async function openReport() { try { reportButton.disabled = true; const made = await api.post("/admin/dash/reports/generate", { run_id: runID || "" }); - const response = await fetch(made.url, { - headers: { Authorization: "Bearer " + getKey() }, signal: controller.signal, - }); - if (!response.ok) throw new Error("HTTP " + response.status); - const blob = new Blob([await response.text()], { type: "text/html" }); - const url = URL.createObjectURL(blob); - window.open(url, "_blank", "noopener,noreferrer"); - setTimeout(() => URL.revokeObjectURL(url), 60000); + await openReportTab(made.url, { signal: controller.signal }); toast("HTML report opened", "ok"); } catch (exception) { if (exception.name !== "AbortError") showError("Could not open report", exception); @@ -492,9 +492,12 @@ export function createAutoGenerate({ signal } = {}) { const left = Math.max(0, Math.ceil((rateLock.unlock_at - Date.now()) / 1000)); if (left <= 0) { rateLock.active = false; ratelimitNote.hidden = true; renderControls(); return; } rateLock.seconds_left = left; - const until = new Date(rateLock.unlock_at).toLocaleTimeString(); - ratelimitNote.textContent = "Safe Mode: محدودیت IP تا " + until - + " (" + left + " ثانیه). تلاش جدیدی شروع نمیشود."; + const until = new Date(rateLock.unlock_at).toLocaleString(); + const hours = Math.floor(left / 3600); + const minutes = Math.floor((left % 3600) / 60); + const human = hours ? hours + "h " + minutes + "m" : minutes + "m " + (left % 60) + "s"; + ratelimitNote.textContent = "Safe Mode: محدودیت ثبت‌نام روی IP فعال است. " + + "تا " + until + " (" + human + " دیگر) هیچ تلاش جدیدی شروع نمی‌شود."; ratelimitNote.hidden = false; } diff --git a/zcode_gateway/dashboard/assets/js/views/doctor.js b/zcode_gateway/dashboard/assets/js/views/doctor.js index ae3a6d1..b6f9ce0 100644 --- a/zcode_gateway/dashboard/assets/js/views/doctor.js +++ b/zcode_gateway/dashboard/assets/js/views/doctor.js @@ -2,10 +2,11 @@ // making the user read five different tabs. No secret is ever rendered here. import { el, fill } from "../core/dom.js"; -import { api, getKey } from "../core/api.js"; +import { api } from "../core/api.js"; import { toast } from "../core/toast.js"; import { card, button, badge } from "../core/ui.js"; import * as theme from "../core/theme.js"; +import { openReport } from "../core/report.js"; const DOCTOR = "/admin/dash/doctor"; const REPORTS = "/admin/dash/reports"; @@ -76,13 +77,7 @@ export function mount({ root, signal }) { onClick: async () => { try { const made = await api.post(REPORTS + "/generate", { run_id: "" }, { signal }); - const response = await fetch(made.url, { - headers: { Authorization: "Bearer " + getKey() }, signal, - }); - if (!response.ok) throw new Error("HTTP " + response.status); - const url = URL.createObjectURL(new Blob([await response.text()], { type: "text/html" })); - window.open(url, "_blank", "noopener,noreferrer"); - setTimeout(() => URL.revokeObjectURL(url), 60000); + await openReport(made.url, { signal }); await loadReports(); } catch (error) { toast("Report failed: " + error.message, "err"); } }, @@ -96,6 +91,10 @@ export function mount({ root, signal }) { ? rows.map((row) => el("div", { class: "row row--tight" }, [ el("span", { class: "mono text-sm", text: row.name }), el("span", { class: "muted text-xs", text: (row.size / 1024).toFixed(1) + " KB" }), + el("span", { class: "spacer" }), + button({ label: "Open", variant: "quiet", + onClick: () => openReport(REPORTS + "/file/" + encodeURIComponent(row.name), { signal }) + .catch((error) => toast("Report failed: " + error.message, "err")) }), ])) : el("p", { class: "auto-note", text: "No HTML reports yet. Generate one from Auto Generate or here." })); } catch (_) { /* the doctor call below reports reachability */ } diff --git a/zcode_gateway/dashboard/index.html b/zcode_gateway/dashboard/index.html index f37f620..e198b12 100644 --- a/zcode_gateway/dashboard/index.html +++ b/zcode_gateway/dashboard/index.html @@ -54,6 +54,10 @@ type="button" aria-label="Toggle navigation" aria-expanded="false">

    Server

    +