diff --git a/PR_PROPOSAL.md b/PR_PROPOSAL.md new file mode 100644 index 0000000..8c9ea0c --- /dev/null +++ b/PR_PROPOSAL.md @@ -0,0 +1,241 @@ +# درخواست Pull Request: AutoZCoder، از یک اگزه قابل حمل به یک ابزار قابل نگهداری + +> نویسنده پیشنهاد: اسماعیل سرحدی +> تاریخ: 2026-11-29 +> شاخه پیشنهادی: `esmail/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 کار میکند. + +### 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 (تشخیص هوشمند) + +یک صفحه واحد «**پزشک تنظیمات**» که با یک دکمه 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 کم است. + +- اجرای همه چک‌ها روی ویندوز بدون پنجره کنسول (`CREATE_NO_WINDOW` + `STARTUPINFO`): exe پنجره‌ای است و هر spawn بدون این فلگ یک cmd فلش می‌زد. همین برای sidecar کپچا و taskkill هم اعمال شد. +- نتیجه Doctor در Overview بین pollهای ۱۰ ثانیه‌ای کش می‌شود و فقط با «Run health check»، Repair یا ورود مجدد به صفحه دوباره اجرا می‌شود؛ قبلاً هر ۱۰ ثانیه چند پروسه Python/Node تازه spawn می‌شد. + +--- + +## 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. + +--- + +## 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 لاگ ساختاریافته +- لاگها علاوه بر متن، به 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 را دور نمیزنند. + +### فاز ۶ب — ۱۰ قابلیت کاربردی 다른 (درخواست دوم اسماعیل) + +همانطور که اسماعیل خواست، ۱۰ قابلیت تازه جذاب و عملی هم اضافه میشود: + +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. فاز ۷ — رفع باگهای شناختهشده + +| باگ | محل | وضعیت در این 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، Config Doctor، Safe Mode و چرخش دامنه اضافه میشود (همه ۵۶ تا اجرا و سبز شدند). عددسازی نمیکنم. + +نتیجه اجرای کامل سورس روی Python 3.13: **۱٬۵۲۴ تست passed، ۱۷۳ skipped**؛ به‌علاوه ۲ تست جدید داشبورد (`test_every_dashboard_view_module_parses` و `test_config_doctor_mounts_checks`) که جداگانه اجرا و سبز شدند. تعدادی تست قدیمی در اجرای تکجریانی کامل، وابسته به ترتیب اجرا هستند (در اجرای جداگانه همان ماژولها سبزاند). + +--- + +## 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/README.md b/README.md index 6d21bcd..2cae76b 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,47 @@ and inspect usage in the web dashboard at `/dash`. **Generate when needed.** Optional browser-based account generation, proxy tooling and a Cloudflare mail worker live alongside the gateway, not in your client. + + + + + + + + + +
+ Overview page: health ring, KPIs, quick actions and Safe Mode banner in the dark theme. + Overview — health ring, KPIs, quick actions + + Accounts page: pool table with per-account state, plan and quota cells. + Accounts — pool table, quotas, JWT refresh +
+ Config Doctor: eleven health checks with safe one-click repairs and the Safe Mode toggle. + Config Doctor — 11 checks, safe repairs, Safe Mode + + Auto Generate: session controls, worker cards and live log. + Auto Generate — batch workers, live log, reports +
+ +
+Ten colour themes — click to see four of them + + + + + + + + + + +
Light themeLightOcean depth themeOcean depth
Sunset neon themeSunset neonCyber lime themeCyber lime
+ +Dark · Light · Midnight · Sepia · High contrast · Ocean · Forest · Sunset · Nord · Cyber — saved per device, cycled from the top bar or Config Doctor. + +
+

OpenAI and Anthropic clients connect to AutoZCoder with a client key. Its account pool routes requests to the ZCode coding-plan API.

@@ -43,7 +84,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 +94,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 +310,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 new file mode 100644 index 0000000..d077aef --- /dev/null +++ b/WORKBUDDY_MEMORY.md @@ -0,0 +1,260 @@ +# یادداشت کاری دایی گل — 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` +- شاخه محلی `esmail/pr-overhaul` ساخته شد (مرحله بعدی). +- این فایل حافظه ساخته شد. + +--- + +### 2026-11-29 22:05 +- `PR_PROPOSAL.md` نوشته شد: درخواست Pull Request فازبندیشده، فارسی/RTL، با ۸ فاز، ۱۰ قابلیت خلاقانه، جدول رفع باگها و نقشه واقعی ۲۵۰۰ تست. +- مرز قانونی در آن صریح است: قابلیت جدید برای کپچا/IP/claim نمینویسم. + +### 2026-11-29 22:08 +- شاخه `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=. +- `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 واقعی اجرا شد: لیست مهاجرت درست نشان داده شد، هیچ فایلی کپی نشد. + +### 2026-11-29 22:15 +- `git compile` روی تمام فایلهای Python تغییریافته ok. +- `git status` تمیز شد و commit محلی زده شد: + `62939dd feat: add PR proposal, installer, HTML reports and auto-reload fix` + روی شاخه `esmail/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 درست. + +### 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 نام ورکبادی نیامد. + +### 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 آن را هم پاک کند. + +### 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 نیست). + +--- + +### 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 باطل/چرخش شود. + +--- + +### 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 و حذف کامل پوشه/شورتکات. + +--- + +### 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 اسماعیل است. +- خروجی‌های بیلد در `.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 است. + +--- + +## 6. یادآورهای شخصی + +- عدد از خودم درنمیآورم: ۲۵۰۰ تست را ادعا نمیکنم؛ مینویسم «هدف مرحلهای». +- تا ندیدهام «انجام شد» نمیگویم: تستها را اجرا میکنم و خروجی را میبینم. +- سورس کاربر مال خودش است؛ در فایلهای اصلیاش جز تغییرات لازم دست نمیزنم. +- توکن 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` و انتهای فایل تست توسط من تغییر یافتند. + +--- + +### 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 جدید باید اجرا شود. + +--- + +### 2026-11-30 09:35 — گزارش در مرورگر واقعی، کلید Safe Mode، ۱۰ تم و انیمیشن +- علت «Get an app to open this 'blob' link»: WebView2 لینک `blob:` را به ویندوز می‌دهد، نه به مرورگر. حالا گزارش با یک URL کوتاه‌عمر (`/reports/view/`) و فراخوانی `webbrowser.open()` در **مرورگر پیش‌فرض** باز می‌شود؛ fallback هم تب واقعی است، نه blob. +- Safe Mode دستی: فایل `generator-data/safe_mode.json` + API `GET/POST /admin/dash/safe-mode`؛ کارت «Safe Mode» در Config Doctor با چک‌باکس و تأیید. خاموش کردن فقط قفل محلی را برمی‌دارد؛ محدودیت provider را تغییر نمی‌دهد. +- ۵ تم جدید (Ocean, Forest, Sunset, Nord, Cyber) به ۵ تم قبلی اضافه شد؛ مجموع ۱۰ تم. انتخابگر تم در topbar و Doctor. +- انیمیشن‌ها: ورود view، بالا آمدن کارت‌ها با stagger، breathe لوگو، pulse وضعیت، shine دکمه primary؛ با `prefers-reduced-motion` غیرفعال می‌شوند. +- تست نهایی روی exe ایزوله: `doctor overall=ok`، `link + /reports/view` = 200، `open` = ok، `safe-mode` off/on کار کرد، تم‌های جدید در باندل هستند. `63 passed`. +- Setup نهایی دوباره ساخته شد (`.local\dist\ZcodeGateway-Setup-3.0.0.exe`). + +--- + +### 2026-11-30 10:20 — اتصال مدل‌های گیت‌وی به WorkBuddy +- WorkBuddy از Custom Model (OpenAI-compatible) پشتیبانی می‌کند؛ فایل `%USERPROFILE%\.workbuddy-ai\models.json`. +- دو مدل به آن اضافه شد: `GLM-5.3-Flash` و `GLM-5.4`، با `url=http://127.0.0.1:8788/v1` و همان client key محلی. هر دو tool-call، vision و reasoning را true دارند؛ max input 1,048,576 و max output به‌ترتیب 128k/131k. +- تست واقعی گیت‌وی: `/v1/models` هر دو مدل را داد، `/v1/chat/completions` (stream و tool call) هر دو 200 بودند. +- بکاپ قبل از تغییر: `models.json.bak-20261130-102021`. برای دیده شدن در WorkBuddy، کلاینت باید یک‌بار restart شود. + +--- + +### 2026-11-30 11:25 — آپلود بیلد نهایی روی GitHub خود اسماعیل +- برنچ `artifacts/build-3.0.0` در fork `Esmail-sarhadi/AutoZcoder` ساخته شد (anchor برای release). +- Release عمومی پیش‌نمایش: tag `v3.0.0-build` — https://github.com/Esmail-sarhadi/AutoZcoder/releases/tag/v3.0.0-build +- فایل‌ها: `ZcodeGateway-Setup-3.0.0.exe` (103,917,716 bytes) و `ZcodeGateway-portable.exe` (102,577,763 bytes). +- SHA-256 (دستگاه محلی): Setup `2014fd15538823a2…`، Portable `d3494757de9cbcb0…` (کاربر می‌تواند با `certutil -hashfile` چک کند). +- API release از همان credential یار `git credential fill` استفاده کرد؛ توکن چاپ نشد. diff --git a/assets/readme-hero.svg b/assets/readme-hero.svg index 5289146..787f9a4 100644 --- a/assets/readme-hero.svg +++ b/assets/readme-hero.svg @@ -1,23 +1,106 @@ - + AutoZCoder - Your ZCode accounts. One gateway. Self-hosted on Windows and Linux, with OpenAI and Anthropic compatible APIs. - - - - - - - SELF-HOSTED / DEVELOPER TOOLS - AutoZCoder - Your ZCode accounts. - One gateway. - OpenAI + Anthropic APIs - - Windows + Linux + Your ZCode accounts. One gateway. OpenAI and Anthropic compatible APIs on Windows and Linux, with ten themes and live HTML reports. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - + + + + + SELF-HOSTED AI GATEWAY + + AutoZCoder + Your ZCode accounts. + One gateway. + OpenAI + Anthropic compatible · pool · generator · HTML reports + + + + + + 10 themes + + + HTML reports + + + Config Doctor + + + + + + + + + + + + 127.0.0.1:8788/dash + + + + + 100% + System health + + + + + POOL READY + 34 / 36 + + REQUESTS · 24H + 396 + + TOKENS · 24H + 26.7M + + + + + + + + + + [11:23:41] Attempt 26 finished: qualified + [11:23:44] pool reload → 36 loaded, 35 ready + + + + + + diff --git a/docs/releases/3.0.0.md b/docs/releases/3.0.0.md index 581eced..5e9c7b2 100644 --- a/docs/releases/3.0.0.md +++ b/docs/releases/3.0.0.md @@ -86,3 +86,30 @@ update and deploy fixes. Replace the executable (Windows) or run the installer (Linux). Saved options, accounts, VPN keys and Auto profiles are kept. + +## Dashboard refresh (3.0.0 builds of Nov 30) + +- **Overview page.** Health ring, four KPI cards (pool ready, requests 24h, + tokens 24h, checks passing), quick actions and an HTML reports card on one + screen, with a Safe Mode banner when the provider rate-limits signups. +- **Config Doctor.** Eleven secret-safe checks with one-click safe repairs, + a manual Safe Mode toggle (with confirmation), and the colour theme picker. +- **Reports open in the real browser.** Short-lived server links replace + blob: URLs, so Chrome/Edge/Firefox opens the report instead of WebView2 + asking for an app. +- **Ten colour themes.** Dark, Light, Midnight, Sepia, High contrast, + Ocean, Forest, Sunset, Nord and Cyber — chosen in the top bar or Config + Doctor, saved per device. +- **Motion design.** View-enter and card-rise animations, brand breathing + glow, status dot pulse and a shine sweep on primary buttons; all disabled + under `prefers-reduced-motion`. +- **Accounts page.** Accounts-folder bar (Copy path / Open folder), folder + import, and 409-with-message instead of a 500 when Safe Mode blocks + start/resume. + +## Screenshots + +| | | +| :---: | :---: | +| ![Overview](../screenshots/dashboard-overview.png) | ![Accounts](../screenshots/accounts.png) | +| ![Config Doctor](../screenshots/config-doctor.png) | ![Auto Generate](../screenshots/auto-generate.png) | diff --git a/docs/screenshots/accounts.png b/docs/screenshots/accounts.png new file mode 100644 index 0000000..08741c7 Binary files /dev/null and b/docs/screenshots/accounts.png differ diff --git a/docs/screenshots/auto-generate.png b/docs/screenshots/auto-generate.png new file mode 100644 index 0000000..3d2f0e4 Binary files /dev/null and b/docs/screenshots/auto-generate.png differ diff --git a/docs/screenshots/config-doctor.png b/docs/screenshots/config-doctor.png new file mode 100644 index 0000000..eebd144 Binary files /dev/null and b/docs/screenshots/config-doctor.png differ diff --git a/docs/screenshots/dashboard-overview.png b/docs/screenshots/dashboard-overview.png new file mode 100644 index 0000000..96ed807 Binary files /dev/null and b/docs/screenshots/dashboard-overview.png differ diff --git a/docs/screenshots/theme-cyber.png b/docs/screenshots/theme-cyber.png new file mode 100644 index 0000000..9f291ab Binary files /dev/null and b/docs/screenshots/theme-cyber.png differ diff --git a/docs/screenshots/theme-light.png b/docs/screenshots/theme-light.png new file mode 100644 index 0000000..730d465 Binary files /dev/null and b/docs/screenshots/theme-light.png differ diff --git a/docs/screenshots/theme-ocean.png b/docs/screenshots/theme-ocean.png new file mode 100644 index 0000000..92de1da Binary files /dev/null and b/docs/screenshots/theme-ocean.png differ diff --git a/docs/screenshots/theme-sunset.png b/docs/screenshots/theme-sunset.png new file mode 100644 index 0000000..4d7e0ba Binary files /dev/null and b/docs/screenshots/theme-sunset.png differ 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/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/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/installer/assets/wizard-large.bmp b/scripts/installer/assets/wizard-large.bmp new file mode 100644 index 0000000..ac59df3 Binary files /dev/null and b/scripts/installer/assets/wizard-large.bmp differ diff --git a/scripts/installer/assets/wizard-small.bmp b/scripts/installer/assets/wizard-small.bmp new file mode 100644 index 0000000..6d6c9be Binary files /dev/null and b/scripts/installer/assets/wizard-small.bmp differ 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 diff --git a/scripts/report/generate_html.py b/scripts/report/generate_html.py new file mode 100644 index 0000000..7cb9cc5 --- /dev/null +++ b/scripts/report/generate_html.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""CLI wrapper around :mod:`zcode_gateway.run_report`. + +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 sys +from pathlib import Path + +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: + 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_dashboard_review_fixes.py b/tests/test_dashboard_review_fixes.py index ed3ee6b..a91e11f 100644 --- a/tests/test_dashboard_review_fixes.py +++ b/tests/test_dashboard_review_fixes.py @@ -35,6 +35,16 @@ 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": []}, } def handle(route): @@ -94,6 +104,36 @@ 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_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 new file mode 100644 index 0000000..f7df939 --- /dev/null +++ b/tests/test_workbuddy_additions.py @@ -0,0 +1,638 @@ +"""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" + + +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): + 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"] + + +# ---- 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_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) + report = cd.run_doctor(state, {}, {}) + assert report["overall"] == "ok" + assert set(report["checks"]) == {"python", "packages", "chromium", "generator", + "node", "wrangler", "cloudflare", "inbox", + "mail_rotation", "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_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) + 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" + + +# ---- 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 + + +# ---- 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() + + +# ---- 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 + + +# ---- 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 + + +# ---- manual Safe Mode switch --------------------------------------------- # + +def test_safe_mode_can_be_disabled(tmp_path): + import json, time + from zcode_gateway import 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") + assert rate_limit.status(tmp_path)["active"] is True + assert rate_limit.enabled(tmp_path) is True + rate_limit.set_enabled(tmp_path, False) + assert rate_limit.enabled(tmp_path) is False + rate_limit.guard(tmp_path) # must not raise when manually disabled + state = rate_limit.status(tmp_path) + assert state["enabled"] is False + rate_limit.set_enabled(tmp_path, True) + assert rate_limit.enabled(tmp_path) is True + + +def test_report_link_store_is_short_lived(): + from zcode_gateway import api_dash + token = api_dash._new_report_link("run_test.html") + assert token + entry = api_dash._REPORT_LINKS[token] + assert entry[0] == "run_test.html" + assert entry[1] > 0 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..9cd9232 100644 --- a/zcode_gateway/api_dash.py +++ b/zcode_gateway/api_dash.py @@ -11,10 +11,13 @@ import json import logging import os +import secrets +import shutil import sys import threading import tempfile import time +import webbrowser import math from functools import wraps from pathlib import Path @@ -34,6 +37,24 @@ router = APIRouter(tags=["dashboard"]) +# Short-lived, single-purpose links so an HTML report can open in the real +# default browser. A browser tab cannot send the admin Authorization header, +# and a blob: URL is handed to the OS by WebView2 (Windows asks "get an app"). +_REPORT_LINKS: dict[str, tuple[str, float]] = {} +_REPORT_LINKS_LOCK = threading.Lock() +_REPORT_LINK_TTL = 600 + + +def _new_report_link(name: str) -> str: + token = secrets.token_urlsafe(24) + now = time.time() + with _REPORT_LINKS_LOCK: + for key, (_, expiry) in list(_REPORT_LINKS.items()): + if expiry <= now: + _REPORT_LINKS.pop(key, None) + _REPORT_LINKS[token] = (name, now + _REPORT_LINK_TTL) + return token + def _dash_dir() -> Path: """Bundle-aware: PyInstaller unpacks data to sys._MEIPASS.""" import sys @@ -1484,6 +1505,31 @@ 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): + 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: + 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: @@ -1651,6 +1697,252 @@ 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 _runtime_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/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/safe-mode") +async def safe_mode_get(request: Request, key: str = Depends(admin_key)) -> dict: + 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.post("/admin/dash/safe-mode") +async def safe_mode_set(request: Request, body: dict = Body(default={}), + key: str = Depends(admin_key)) -> dict: + """Turn the local guard off/on. It never changes the provider's own limit.""" + from .rate_limit import compliance_notice, scan, set_enabled, status + data_dir = _runtime_data_dir(request) + set_enabled(data_dir, bool((body or {}).get("enabled", True))) + scan(data_dir) + 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.""" + from .config_doctor import run_doctor + state = get_state(request) + pool = await state.pool.snapshot() + mgr = getattr(state, "generator", None) + # 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() + 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", "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", + "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/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 + 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, _runtime_data_dir(request), + str((body or {}).get("run_id") or "")) + return {"name": path.name, "url": "/admin/dash/reports/file/" + path.name} + + +def _report_file(request: Request, name: str) -> Path: + import re + if not re.fullmatch(r"run_[A-Za-z0-9_-]+\.html", name): + raise HTTPException(status_code=400, detail="invalid report name") + path = _runtime_data_dir(request) / "reports" / name + if not path.is_file(): + raise HTTPException(status_code=404, detail="report not found") + return path + + +@router.get("/admin/dash/reports/file/{name}") +async def reports_file(request: Request, name: str, + key: str = Depends(admin_key)) -> HTMLResponse: + path = _report_file(request, name) + return HTMLResponse(path.read_text(encoding="utf-8")) + + +@router.get("/admin/dash/reports/link/{name}") +async def reports_link(request: Request, name: str, + key: str = Depends(admin_key)) -> dict: + """Create a short-lived browser URL (the tab cannot send our auth header).""" + _report_file(request, name) + return {"name": name, "url": "/reports/view/" + _new_report_link(name)} + + +@router.post("/admin/dash/reports/open/{name}") +async def reports_open_external(request: Request, name: str, + key: str = Depends(admin_key)) -> dict: + """Open the report in the OS default browser (Chrome, Edge, Firefox...).""" + _report_file(request, name) + token = _new_report_link(name) + base = str(request.base_url).rstrip("/") + url = base + "/reports/view/" + token + opened = False + try: + opened = bool(webbrowser.open(url)) + except Exception: + opened = False + return {"ok": opened, "url": url, "name": name} + + +@router.get("/reports/view/{token}", include_in_schema=False) +async def reports_view(request: Request, token: str) -> HTMLResponse: + """Public, token-scoped report view; expires after a few minutes.""" + now = time.time() + with _REPORT_LINKS_LOCK: + entry = _REPORT_LINKS.get(token) + if entry and entry[1] <= now: + _REPORT_LINKS.pop(token, None) + entry = None + if not entry: + raise HTTPException(status_code=404, detail="report link expired; generate a new one") + path = _runtime_data_dir(request) / "reports" / entry[0] + if not path.is_file(): + raise HTTPException(status_code=404, detail="report not found") + return HTMLResponse(path.read_text(encoding="utf-8"), + headers={"Cache-Control": "no-store"}) + + @router.get("/admin/dash/generator/status") async def generator_status(request: Request, key: str = Depends(admin_key)) -> dict: try: @@ -1753,6 +2045,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: @@ -1762,6 +2068,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)) + _guard_rate_limit(_runtime_data_dir(request)) mgr = _generator(request) def _emit(line: str) -> None: @@ -1809,6 +2116,8 @@ 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"): + _guard_rate_limit(_runtime_data_dir(request)) manager = _generator(request) controller = manager.auto_generate try: 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/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/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 new file mode 100644 index 0000000..4d9a0cb --- /dev/null +++ b/zcode_gateway/config_doctor.py @@ -0,0 +1,315 @@ +"""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 +# 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: + """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 _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, **_hidden()) + 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 _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 = _generator_python(python_exe) + 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 = _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) + 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 = _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) + 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_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) + 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) + 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 = "" + 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), + "mail_rotation": check_domain_rotation(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..bdf0a31 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); } -.btn:active:not(:disabled) { transform: translateY(0.5px); } +.btn:hover:not(:disabled) { + background: var(--surface-3); + border-color: var(--fg-faint); + transform: translateY(-1px); +} +.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); @@ -1009,6 +1047,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; } @@ -1058,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; } } @@ -1086,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; } } @@ -1116,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); } @@ -1139,3 +1201,478 @@ .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); } + +/* ---- 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; } + +/* ---- 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; } + +/* ---- motion: make the console feel alive, not busy --------------------- */ +@keyframes view-enter { + from { opacity: 0; transform: translateY(7px); } + to { opacity: 1; transform: none; } +} +@keyframes card-rise { + from { opacity: 0; transform: translateY(8px) scale(.997); } + to { opacity: 1; transform: none; } +} +@keyframes brand-breathe { + 0%, 100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--accent) 0%, transparent); } + 50% { box-shadow: 0 0 0 7px color-mix(in srgb, var(--accent) 10%, transparent); } +} +@keyframes dot-pulse { + 0%, 100% { opacity: 1; } + 50% { opacity: .45; } +} +@keyframes shine-sweep { + from { transform: translateX(-120%) skewX(-18deg); } + to { transform: translateX(240%) skewX(-18deg); } +} + +.view__inner { animation: view-enter var(--dur-3) var(--ease-out) both; } +.card { animation: card-rise var(--dur-3) var(--ease-out) both; } +.grid > .card:nth-child(2) { animation-delay: 35ms; } +.grid > .card:nth-child(3) { animation-delay: 70ms; } +.grid > .card:nth-child(4) { animation-delay: 105ms; } +.grid > .card:nth-child(5) { animation-delay: 140ms; } +.grid > .card:nth-child(6) { animation-delay: 175ms; } +.brand__mark { animation: brand-breathe 6.5s ease-in-out infinite; } +.chip .dot { animation: dot-pulse 2.6s ease-in-out infinite; } + +.btn--primary { position: relative; overflow: hidden; } +.btn--primary::before { + content: ""; + position: absolute; + inset: -20% auto -20% 0; + width: 38%; + background: linear-gradient(90deg, transparent, rgb(255 255 255 / .28), transparent); + opacity: 0; + pointer-events: none; +} +.btn--primary:hover:not(:disabled)::before { + opacity: 1; + animation: shine-sweep .7s var(--ease-out); +} + +@media (prefers-reduced-motion: reduce) { + .view__inner, .card, .brand__mark, .chip .dot { animation: none !important; } + .btn, .card, .metric { transition: none !important; } + .btn--primary:hover:not(:disabled)::before { animation: none; opacity: 0; } +} 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 951aa7f..c2b8c21 100644 --- a/zcode_gateway/dashboard/assets/css/tokens.css +++ b/zcode_gateway/dashboard/assets/css/tokens.css @@ -164,3 +164,269 @@ --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; +} + +/* ---- 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); +} + +/* ---- ocean: deep teal, cyan current ----------------------------------- */ +:root[data-theme="ocean"] { + color-scheme: dark; + --bg: #06141a; --bg-sunken: #031016; + --surface: #0b1f27; --surface-2: #0f2a34; --surface-3: #143642; --surface-hover: #12303b; + --border: #1c4553; --border-strong: #2b6374; --border-subtle: #12323d; + --fg: #e6fbff; --fg-muted: #93c7d3; --fg-faint: #5f97a5; --fg-on-accent: #042027; + --accent: #22d3ee; --accent-hover: #67e8f9; --accent-fg: #a5f3fc; --accent-bg: #082c36; --accent-border: #0e5b6b; + --ok: #34d399; --ok-bg: #062c22; --ok-border: #0d5c47; + --warn: #fbbf24; --warn-bg: #302407; --warn-border: #6b4d0d; + --err: #fb7185; --err-bg: #33101a; --err-border: #6b2233; + --info: #38bdf8; --info-bg: #072a3d; --info-border: #0d5473; + --shadow-sm: 0 1px 2px rgb(0 0 0 / .45); --shadow-md: 0 4px 18px rgb(0 0 0 / .5); --shadow-lg: 0 16px 48px rgb(0 0 0 / .62); + --focus-ring: 0 0 0 2px var(--bg), 0 0 0 4px var(--accent); + --accent-2: #38bdf8; --ring-track: #123642; + --shadow-card: 0 1px 2px rgb(0 0 0 / .25), 0 14px 34px -22px rgb(0 0 0 / .55); +} + +/* ---- forest: green canopy at night ------------------------------------ */ +:root[data-theme="forest"] { + color-scheme: dark; + --bg: #07130c; --bg-sunken: #040d07; + --surface: #0c1d12; --surface-2: #112718; --surface-3: #17321f; --surface-hover: #142d1b; + --border: #22432c; --border-strong: #356346; --border-subtle: #15301e; + --fg: #eafff0; --fg-muted: #9cc9a8; --fg-faint: #679b76; --fg-on-accent: #052012; + --accent: #4ade80; --accent-hover: #86efac; --accent-fg: #bbf7d0; --accent-bg: #0b2e1b; --accent-border: #1b5c35; + --ok: #4ade80; --ok-bg: #0a2e1b; --ok-border: #1c5c35; + --warn: #facc15; --warn-bg: #302707; --warn-border: #6b5510; + --err: #fb7185; --err-bg: #33101a; --err-border: #6b2233; + --info: #7dd3fc; --info-bg: #082b3a; --info-border: #0f5570; + --shadow-sm: 0 1px 2px rgb(0 0 0 / .45); --shadow-md: 0 4px 18px rgb(0 0 0 / .5); --shadow-lg: 0 16px 48px rgb(0 0 0 / .62); + --focus-ring: 0 0 0 2px var(--bg), 0 0 0 4px var(--accent); + --accent-2: #a3e635; --ring-track: #17321f; + --shadow-card: 0 1px 2px rgb(0 0 0 / .25), 0 14px 34px -22px rgb(0 0 0 / .55); +} + +/* ---- sunset: warm neon dusk ------------------------------------------ */ +:root[data-theme="sunset"] { + color-scheme: dark; + --bg: #170b16; --bg-sunken: #10070f; + --surface: #24101f; --surface-2: #2e1528; --surface-3: #3b1b33; --surface-hover: #35172d; + --border: #4b2440; --border-strong: #6b3559; --border-subtle: #381a30; + --fg: #fff1f2; --fg-muted: #d3a3b3; --fg-faint: #9e6d7e; --fg-on-accent: #2a0714; + --accent: #fb7185; --accent-hover: #fda4af; --accent-fg: #fecdd3; --accent-bg: #3a1020; --accent-border: #76233d; + --ok: #34d399; --ok-bg: #062c22; --ok-border: #0d5c47; + --warn: #f59e0b; --warn-bg: #342207; --warn-border: #6f480d; + --err: #fb7185; --err-bg: #3a101a; --err-border: #7a2434; + --info: #f0abfc; --info-bg: #2d0b33; --info-border: #61206b; + --shadow-sm: 0 1px 2px rgb(0 0 0 / .45); --shadow-md: 0 4px 18px rgb(0 0 0 / .5); --shadow-lg: 0 16px 48px rgb(0 0 0 / .62); + --focus-ring: 0 0 0 2px var(--bg), 0 0 0 4px var(--accent); + --accent-2: #f59e0b; --ring-track: #3b1b33; + --shadow-card: 0 1px 2px rgb(0 0 0 / .25), 0 14px 34px -22px rgb(0 0 0 / .55); +} + +/* ---- nord: cool daylight --------------------------------------------- */ +:root[data-theme="nord"] { + color-scheme: light; + --bg: #eef2f7; --bg-sunken: #e3e9f1; + --surface: #ffffff; --surface-2: #f7f9fc; --surface-3: #edf1f7; --surface-hover: #f1f5fa; + --border: #d6deea; --border-strong: #b7c3d5; --border-subtle: #e6ecf4; + --fg: #2e3440; --fg-muted: #5e6b80; --fg-faint: #8895a8; --fg-on-accent: #ffffff; + --accent: #5e81ac; --accent-hover: #4c6f99; --accent-fg: #3f5f88; --accent-bg: #e7eef8; --accent-border: #b9cbe3; + --ok: #2f7d5b; --ok-bg: #e2f2ea; --ok-border: #b4dcc9; + --warn: #9a6b00; --warn-bg: #fbf0d2; --warn-border: #e4cd93; + --err: #b23a48; --err-bg: #f8e2e5; --err-border: #e3b4bb; + --info: #2f6f8f; --info-bg: #e1f0f7; --info-border: #b4d4e3; + --shadow-sm: 0 1px 2px rgb(30 45 70 / .07); --shadow-md: 0 4px 16px rgb(30 45 70 / .11); --shadow-lg: 0 16px 48px rgb(30 45 70 / .16); + --focus-ring: 0 0 0 2px var(--surface), 0 0 0 4px var(--accent); + --accent-2: #88c0d0; --ring-track: #dfe7f1; + --shadow-card: 0 1px 2px rgb(16 22 32 / .05), 0 12px 30px -22px rgb(16 22 32 / .28); + --topbar-tint: color-mix(in srgb, var(--bg) 88%, transparent); +} + +/* ---- cyber: black glass + lime/pink signal --------------------------- */ +:root[data-theme="cyber"] { + color-scheme: dark; + --bg: #050505; --bg-sunken: #000000; + --surface: #0d0f0d; --surface-2: #121612; --surface-3: #192019; --surface-hover: #151b15; + --border: #283328; --border-strong: #425442; --border-subtle: #1a221a; + --fg: #f2ffe6; --fg-muted: #a6b8a0; --fg-faint: #74866e; --fg-on-accent: #071000; + --accent: #b6ff3b; --accent-hover: #ccff70; --accent-fg: #d9ffa3; --accent-bg: #1b2a08; --accent-border: #43651a; + --ok: #b6ff3b; --ok-bg: #1b2a08; --ok-border: #43651a; + --warn: #ffd166; --warn-bg: #2f2608; --warn-border: #6b5813; + --err: #ff3bd4; --err-bg: #2f0a27; --err-border: #701a5e; + --info: #3bf0ff; --info-bg: #072b30; --info-border: #12616b; + --shadow-sm: 0 1px 2px rgb(0 0 0 / .6); --shadow-md: 0 4px 18px rgb(0 0 0 / .6); --shadow-lg: 0 16px 48px rgb(0 0 0 / .7); + --focus-ring: 0 0 0 2px var(--bg), 0 0 0 4px var(--accent); + --accent-2: #ff3bd4; --ring-track: #192019; + --shadow-card: 0 1px 2px rgb(0 0 0 / .3), 0 14px 34px -22px rgb(0 0 0 / .7); +} diff --git a/zcode_gateway/dashboard/assets/js/boot.js b/zcode_gateway/dashboard/assets/js/boot.js index e6a3ce4..d182877 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, @@ -46,6 +48,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, @@ -155,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; @@ -169,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(); }); } @@ -177,8 +193,19 @@ function wireLogin(onSuccess) { function wireChrome() { const themeBtn = $("#theme-toggle"); - const paintTheme = () => fill(themeBtn, icon(theme.current() === "dark" ? ICONS.sun : ICONS.moon)); + 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/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/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/report.js b/zcode_gateway/dashboard/assets/js/core/report.js new file mode 100644 index 0000000..23d09f9 --- /dev/null +++ b/zcode_gateway/dashboard/assets/js/core/report.js @@ -0,0 +1,22 @@ +// Open a report in the real default browser. +// +// The dashboard can run inside WebView2, which hands blob: URLs to the OS +// ("Get an app to open this 'blob' link"). We instead ask the local gateway +// for a short-lived http URL and let the server call webbrowser.open(), so +// Chrome/Edge/Firefox is used directly. If that fails, a normal tab is the +// fallback — still a real URL, never a blob. + +import { api } from "./api.js"; + +export async function openReport(name, { signal } = {}) { + const opened = await api.post( + "/admin/dash/reports/open/" + encodeURIComponent(name), {}, { signal }); + if (opened?.ok) return opened; + const link = await api.get( + "/admin/dash/reports/link/" + encodeURIComponent(name), { signal }); + const tab = window.open(link.url, "_blank"); + if (!tab) { + throw new Error("مرورگر باز نشد — یک مرورگر پیش‌فرض انتخاب کن و دوباره امتحان کن"); + } + return link; +} diff --git a/zcode_gateway/dashboard/assets/js/core/theme.js b/zcode_gateway/dashboard/assets/js/core/theme.js index 82ac913..7c43fb9 100644 --- a/zcode_gateway/dashboard/assets/js/core/theme.js +++ b/zcode_gateway/dashboard/assets/js/core/theme.js @@ -1,28 +1,49 @@ -// 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", + "ocean", "forest", "sunset", "nord", "cyber"]; +export const LABELS = { + dark: "Dark", + light: "Light", + midnight: "Midnight blue", + sepia: "Sepia (warm light)", + contrast: "High contrast", + ocean: "Ocean depth", + forest: "Forest night", + sunset: "Sunset neon", + nord: "Nord daylight", + cyber: "Cyber lime", +}; 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/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 551cab4..ba44d2a 100644 --- a/zcode_gateway/dashboard/assets/js/views/auto-generate.js +++ b/zcode_gateway/dashboard/assets/js/views/auto-generate.js @@ -3,6 +3,8 @@ import { toast } from "../core/toast.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"]; @@ -62,7 +64,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, ]); } @@ -88,8 +90,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"); @@ -101,6 +107,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 +238,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, @@ -237,12 +252,14 @@ 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; }, 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 +269,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, @@ -313,11 +330,15 @@ 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(); - 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)); @@ -400,9 +421,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; } @@ -447,9 +469,53 @@ 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 || "" }); + await openReportTab(made.name, { signal: controller.signal }); + toast("HTML report opened", "ok"); + } catch (exception) { + if (exception.name !== "AbortError") showError("Could not open report", exception); + } finally { + if (!disposed) reportButton.disabled = false; + } + } + + 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).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; + } + + 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) { + 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}`, @@ -483,6 +549,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) { @@ -501,6 +568,7 @@ export function createAutoGenerate({ signal } = {}) { } function destroy() { disposed = true; + if (countdownTimer) { clearInterval(countdownTimer); countdownTimer = null; } controller.abort(); signal?.removeEventListener("abort", destroy); renderControls(); @@ -508,6 +576,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 new file mode 100644 index 0000000..13bb72d --- /dev/null +++ b/zcode_gateway/dashboard/assets/js/views/doctor.js @@ -0,0 +1,202 @@ +// 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 } 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"; + +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", + mail_rotation: "Domain rotation", + 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 safeToggle = el("input", { type: "checkbox", id: "safe-mode-toggle" }); + const safeState = el("p", { class: "auto-note", text: "Checking Safe Mode…" }); + let safeMode = { enabled: true, active: false, seconds_left: 0, message: "" }; + + 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: "Ten looks: dark, light, midnight, sepia, contrast, ocean, forest, sunset, nord and cyber. 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 }); + await openReport(made.name, { signal }); + 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("span", { class: "spacer" }), + button({ label: "Open", variant: "quiet", + onClick: () => openReport(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 */ } + } + + 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 loadSafeMode() { + try { + safeMode = await api.get("/admin/dash/safe-mode", { signal }); + } catch (_) { /* the doctor summary already reports reachability */ } + safeToggle.checked = safeMode.enabled !== false; + if (safeMode.enabled === false) { + safeState.textContent = "Off — new attempts are allowed, but the provider can still reject them."; + safeState.className = "auto-note text-warn"; + } else if (safeMode.active) { + safeState.textContent = safeMode.message || "Rate limit active."; + safeState.className = "auto-note text-warn"; + } else { + safeState.textContent = "On — no active rate limit. New attempts are allowed."; + safeState.className = "auto-note text-sm"; + } + } + + safeToggle.addEventListener("change", async () => { + const want = safeToggle.checked; + if (!want && !window.confirm( + "Safe Mode جلوی تلاش‌های تکراری در زمان rate-limit را می‌گیرد.\n\n" + + "خاموش کردنش محدودیت z.ai را برنمی‌دارد؛ فقط اپ دیگر جلوی تو را نمی‌گیرد " + + "و ممکن است ایمیل/سهمیه هدر برود. مطمئنی؟")) { + safeToggle.checked = true; + return; + } + try { + await api.post("/admin/dash/safe-mode", { enabled: want }, { signal }); + toast(want ? "Safe Mode روشن شد" : "Safe Mode خاموش شد", want ? "ok" : "warn"); + await loadSafeMode(); + } catch (error) { + safeToggle.checked = !want; + toast("تغییر Safe Mode نشد: " + error.message, "err"); + } + }); + + const safeCard = card({ + title: "Safe Mode", + desc: "یک قفل محلی؛ محدودیت خود provider را تغییر نمی‌دهد.", + body: el("div", { class: "stack--tight" }, [ + el("label", { class: "checkline" }, [ + safeToggle, + el("span", { text: "While the provider rate-limits this IP, block new signup attempts" }), + ]), + safeState, + ]), + }); + + 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 loadSafeMode(); + 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." }), + el("p", { class: "auto-note text-sm", text: "ساخت انبوه اکانت و دور زدن محدودیتها بر خلاف قوانین سرویسدهنده است." }), + busy, summary, checks, safeCard, appearance, + card({ title: "HTML reports", desc: "Redacted, printable, safe to share.", + actions: [reportGenerate], body: reportBox }), + ]), + ]); + refresh(); + return { refresh }; +} 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/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..c1dbcc1 --- /dev/null +++ b/zcode_gateway/dashboard/assets/js/views/overview.js @@ -0,0 +1,521 @@ +// 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; + let lastDoctor = null; + + async function load({ withDoctor = lastDoctor == null } = {}) { + const paths = [ + "/admin/dash/server", + "/admin/pool/state", + ...(withDoctor ? ["/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 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); + 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 { + 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"); + } 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"); + lastDoctor = null; + 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"); + lastDoctor = null; + 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..e198b12 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) {} @@ -53,6 +54,10 @@ type="button" aria-label="Toggle navigation" aria-expanded="false">

Server

+