recovered from aaronjaworski710
CI / offline-tests (push) Has been cancelled
CI / web-unit-tests (push) Has been cancelled
CI / package-console10 (push) Has been cancelled

This commit is contained in:
reform
2026-10-23 20:02:14 +03:00
commit 8044e88be4
409 changed files with 104886 additions and 0 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,512 @@
# Web Control Plane Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Ship a project-owned FastAPI control API + static web UI for config, import, start/stop runs and status; delete desktop TTK GUI while keeping `grok_register_ttk` engine for CLI.
**Architecture:** `apps/control_api` is a thin adapter over existing `config.json`, import scripts, `launch_batch_supervisor.sh`, and `./register.sh`. `apps/web` is static HTML/CSS/JS served by FastAPI. No Node build. Auth via `CONTROL_API_TOKEN`; default bind `127.0.0.1:8787`.
**Tech Stack:** Python 3.13, FastAPI, Uvicorn, Pydantic v2, pytest, TestClient; vanilla JS frontend.
## Global Constraints
- Deploy model B: in-repo closed loop on the register host (no SSH agent control plane).
- Multi-product hub: Grok + MiMo + ChatGPT.
- Import types: nodes/proxies, mail credentials, account/token dumps, config packs.
- Auto-run tier: start/stop + realtime status only (no scheduler).
- Delete desktop GUI; keep engine in `grok_register_ttk.py` (register_cli imports it).
- Bind default `127.0.0.1` + bearer token; backup-before-write for config/mail.
- Disk-first: supervisor freezes mid-mint `CPA_REMOTE_INJECT=false`; no mid-bulk inject UI.
- No arbitrary shell; whitelist actions only.
- Stop only recorded supervisor/run PID — never blanket `pkill register_cli`.
- Do not stop coinbot or disrupt live `batch_dc1k_ns` during deploy tests.
- No Node/npm build on pxed.
- Spec: `docs/superpowers/specs/2026-07-21-web-control-plane-design.md`
## File map
| Path | Role |
|------|------|
| `apps/control_api/__init__.py` | Package marker |
| `apps/control_api/__main__.py` | `python -m apps.control_api` entry |
| `apps/control_api/settings.py` | Env: root, host, port, token, upload limits |
| `apps/control_api/auth.py` | Bearer / X-Control-Token dependency |
| `apps/control_api/config_io.py` | Load/redact/save config.json + bak |
| `apps/control_api/overview.py` | Product counts + current run summary |
| `apps/control_api/imports_ops.py` | Nodes/mail/auths/pack import helpers |
| `apps/control_api/process_registry.py` | Track started PIDs; stop by pid only |
| `apps/control_api/runs.py` | Start supervisor / register.sh; status; logs |
| `apps/control_api/schemas.py` | Pydantic models |
| `apps/control_api/app.py` | FastAPI factory + routes + static mount |
| `apps/web/index.html` | SPA shell: Overview/Config/Import/Runs |
| `apps/web/assets/app.css` | Minimal styles |
| `apps/web/assets/app.js` | fetch API + page wiring |
| `tests/unit/test_control_api_*.py` | Unit + TestClient tests |
| `scripts/run_control_api.sh` | Launch helper |
| Docs/mise/pyproject/README/ARCHITECTURE | Retarget GUI → web |
| `grok_register_ttk.py` | Strip `GrokRegisterGUI` + tk imports |
| Delete `tests/unit/test_gui_layout_helpers.py`, replace `apps/gui` docs |
---
### Task 1: Dependencies + package skeleton + settings/auth
**Files:**
- Modify: `pyproject.toml` (add fastapi, uvicorn[standard]; retarget description later in Task 7)
- Create: `apps/control_api/__init__.py`, `settings.py`, `auth.py`, `schemas.py` (minimal HealthOut)
- Create: `tests/unit/test_control_api_auth.py`
- Create: `apps/__init__.py` if missing (needed for `python -m apps.control_api`)
**Interfaces:**
- Produces: `Settings(project_root: Path, host: str, port: int, token: str | None, max_upload_bytes: int)`, `get_settings()`, `require_token(request/header) -> None`, `HealthOut`
- [ ] **Step 1: Add deps to pyproject.toml**
```toml
dependencies = [
"DrissionPage>=4.1",
"curl_cffi>=0.7",
"PyYAML>=6.0",
"fastapi>=0.115",
"uvicorn[standard]>=0.32",
]
```
Run: `cd /Users/mango/project/claude-project/grok-register && uv sync --extra dev`
- [ ] **Step 2: Write failing auth tests**
```python
# tests/unit/test_control_api_auth.py
from pathlib import Path
import os
import pytest
from fastapi.testclient import TestClient
def test_settings_reads_env(tmp_path, monkeypatch):
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
monkeypatch.setenv("CONTROL_API_TOKEN", "secret-token")
monkeypatch.setenv("CONTROL_API_HOST", "127.0.0.1")
monkeypatch.setenv("CONTROL_API_PORT", "8787")
from apps.control_api.settings import get_settings
get_settings.cache_clear()
s = get_settings()
assert s.project_root == tmp_path.resolve()
assert s.token == "secret-token"
assert s.port == 8787
def test_health_ok_without_token_when_unset(tmp_path, monkeypatch):
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
monkeypatch.delenv("CONTROL_API_TOKEN", raising=False)
from apps.control_api.settings import get_settings
get_settings.cache_clear()
from apps.control_api.app import create_app
client = TestClient(create_app())
r = client.get("/api/health")
assert r.status_code == 200
assert r.json()["ok"] is True
def test_protected_route_401_without_bearer(tmp_path, monkeypatch):
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
monkeypatch.setenv("CONTROL_API_TOKEN", "secret-token")
from apps.control_api.settings import get_settings
get_settings.cache_clear()
from apps.control_api.app import create_app
client = TestClient(create_app())
r = client.get("/api/overview")
assert r.status_code == 401
def test_protected_route_ok_with_bearer(tmp_path, monkeypatch):
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
monkeypatch.setenv("CONTROL_API_TOKEN", "secret-token")
(tmp_path / "cpa_auths").mkdir()
from apps.control_api.settings import get_settings
get_settings.cache_clear()
from apps.control_api.app import create_app
client = TestClient(create_app())
r = client.get("/api/overview", headers={"Authorization": "Bearer secret-token"})
assert r.status_code == 200
```
- [ ] **Step 3: Implement skeleton so tests can import**
`apps/__init__.py` empty.
`apps/control_api/__init__.py` empty.
`apps/control_api/settings.py`:
```python
from __future__ import annotations
from functools import lru_cache
from pathlib import Path
import os
from dataclasses import dataclass
@dataclass(frozen=True)
class Settings:
project_root: Path
host: str
port: int
token: str | None
max_upload_bytes: int = 20 * 1024 * 1024
@lru_cache(maxsize=1)
def get_settings() -> Settings:
root = os.environ.get("REGISTER_PROJECT_ROOT")
project_root = Path(root).resolve() if root else Path.cwd().resolve()
token = os.environ.get("CONTROL_API_TOKEN") or None
if token is not None and token.strip() == "":
token = None
host = os.environ.get("CONTROL_API_HOST", "127.0.0.1")
port = int(os.environ.get("CONTROL_API_PORT", "8787"))
return Settings(project_root=project_root, host=host, port=port, token=token)
```
`apps/control_api/auth.py`:
```python
from __future__ import annotations
from fastapi import Header, HTTPException, status
from apps.control_api.settings import get_settings
def require_token(
authorization: str | None = Header(default=None),
x_control_token: str | None = Header(default=None, alias="X-Control-Token"),
) -> None:
settings = get_settings()
if not settings.token:
return
presented = None
if authorization and authorization.lower().startswith("bearer "):
presented = authorization[7:].strip()
elif x_control_token:
presented = x_control_token.strip()
if presented != settings.token:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="invalid or missing token")
```
Minimal `app.py` with `/api/health` (no auth) and `/api/overview` stub (Depends require_token) returning `{"product_ok":0,"run":None}` until Task 2.
- [ ] **Step 4: Run tests**
`uv run pytest tests/unit/test_control_api_auth.py -v` → PASS
- [ ] **Step 5: Commit**
```bash
git add pyproject.toml uv.lock apps/ tests/unit/test_control_api_auth.py
git commit -m "feat(control_api): skeleton, settings, auth"
```
---
### Task 2: Config IO + overview counts
**Files:**
- Create: `apps/control_api/config_io.py`, `apps/control_api/overview.py`
- Extend: `schemas.py`, `app.py` routes GET/PUT `/api/config`, GET `/api/overview`
- Create: `tests/unit/test_control_api_config.py`
**Interfaces:**
- Produces:
- `load_config(root: Path) -> dict`
- `redact_config(data: dict) -> dict` (mask secret-like keys)
- `save_config(root: Path, data: dict) -> dict` # returns `{backup, changed_keys}`
- `SECRET_KEY_SUBSTR = ("password","api_key","token","jwt","secret")` — mask if key lower contains
- `count_product_ok(root: Path) -> int` # cpa_auths/xai-*.json with access+refresh
- `build_overview(root: Path, run_summary: dict | None) -> dict`
Secret keys never returned in full after save; empty string on PUT means leave unchanged for secret fields.
- [ ] **Step 1: Failing tests for load/redact/save/backup and overview count**
```python
# tests/unit/test_control_api_config.py
import json
from pathlib import Path
from apps.control_api.config_io import load_config, redact_config, save_config
from apps.control_api.overview import count_product_ok
def test_load_strips_comment_keys(tmp_path):
(tmp_path / "config.json").write_text(json.dumps({
"// note": "x",
"email_provider": "cloudflare",
"cloudflare_api_key": "abc12345",
}), encoding="utf-8")
data = load_config(tmp_path)
assert "// note" not in data
assert data["email_provider"] == "cloudflare"
def test_redact_masks_secrets():
out = redact_config({"email_provider": "cloudflare", "cloudflare_api_key": "abc12345", "proxy": "http://x"})
assert out["email_provider"] == "cloudflare"
assert out["cloudflare_api_key"].startswith("***")
assert out["cloudflare_api_key"].endswith("2345") or "2345" in out["cloudflare_api_key"]
assert out["proxy"] == "http://x"
def test_save_backup_and_preserve_secret_on_empty(tmp_path):
(tmp_path / "config.json").write_text(json.dumps({
"email_provider": "cloudflare",
"cloudflare_api_key": "keepme-secret",
"defaultDomains": "a.com",
}), encoding="utf-8")
result = save_config(tmp_path, {
"email_provider": "cloudflare",
"cloudflare_api_key": "",
"defaultDomains": "b.com",
})
assert result["backup"]
assert Path(result["backup"]).is_file()
data = json.loads((tmp_path / "config.json").read_text(encoding="utf-8"))
assert data["cloudflare_api_key"] == "keepme-secret"
assert data["defaultDomains"] == "b.com"
def test_count_product_ok(tmp_path):
d = tmp_path / "cpa_auths"
d.mkdir()
(d / "xai-a.json").write_text(json.dumps({"access_token":"a","refresh_token":"r"}), encoding="utf-8")
(d / "xai-b.json").write_text(json.dumps({"access_token":"a"}), encoding="utf-8")
(d / "other.json").write_text(json.dumps({"access_token":"a","refresh_token":"r"}), encoding="utf-8")
assert count_product_ok(tmp_path) == 1
```
- [ ] **Step 2: Implement config_io + overview; wire routes**
`load_config`: json load, drop keys starting with `//` or `#`.
`save_config`: merge with existing for empty secret fields; shutil.copy2 backup `config.json.bak-web-<YYYYMMDD_HHMMSS>`; atomic write via temp + replace.
`count_product_ok`: glob `cpa_auths/xai-*.json`, require both tokens non-empty strings.
PUT body: full dict of non-comment keys (client sends redacted view edited — server treats `***...` masked values as unchanged too: if value starts with `***` leave old).
- [ ] **Step 3: pytest PASS + commit**
```bash
git add apps/control_api tests/unit/test_control_api_config.py
git commit -m "feat(control_api): config io, redact, overview counts"
```
---
### Task 3: Process registry + runs start/stop/status/logs
**Files:**
- Create: `apps/control_api/process_registry.py`, `apps/control_api/runs.py`
- Extend: `schemas.py` (`StartRunRequest`), `app.py`
- Create: `tests/unit/test_control_api_runs.py`
**Interfaces:**
- `ProcessRegistry` (in-memory + optional `logs/control_api_runs.json` under project root for restart visibility)
- `register(run_id, pid, kind, meta) -> None`
- `current() -> dict | None`
- `clear_if_dead() -> None`
- `supervisor_lock_held(root) -> bool` — check `/tmp/grok_batch_supervisor.lock.pid` alive OR registry current kind grok_supervisor alive
- `start_run(root, req: StartRunRequest) -> dict` — 409 if conflict
- `stop_run(root) -> dict` — SIGTERM then wait 10s then SIGKILL on **recorded pid only**
- `run_status(root) -> dict` — merge registry + parse latest `logs/*supervisor.log` / state.json if present
- `tail_log(root, n=200) -> str`
**StartRunRequest fields:**
`kind: Literal["grok_supervisor","register_sh"]`, `product: Literal["grok","mimo","chatgpt"]="grok"`, `mode: Literal["ordinary","residential"]="ordinary"`, `target: int=100`, `threads: int=1`, `tag: str="batch_web"`, `extra_env: dict[str,str]={}`
**extra_env allowlist:**
`SKIP_CLASH_PREFLIGHT`, `CPA_PROBE_CHAT`, `CPA_BATCH_END_INJECT`, `SUPERVISOR_CHUNK`, `EMAIL_PROVIDER`, `DEFAULT_DOMAINS`, `NODE_SCORE`
Unknown key → 400.
**Start commands (cwd=project_root, env=os.environ copy + allowlist):**
- `grok_supervisor`: `bash scripts/launch_batch_supervisor.sh {mode} {target} {threads} {tag}`
- `register_sh`: `bash ./register.sh {product} {target} {threads}` (if product needs 2 args only, pass what register.sh accepts — use `target` as count and threads as 3rd arg)
Use `subprocess.Popen` with stdout/stderr to `logs/control_api_{run_id}.log`. Do not use `shell=True` with user strings; argv list only.
- [ ] **Step 1: Tests with mocked Popen / fake pid**
```python
def test_extra_env_reject_unknown():
from apps.control_api.runs import filter_extra_env
import pytest
with pytest.raises(ValueError, match="not allowed"):
filter_extra_env({"EVIL": "1"})
def test_start_409_when_lock_pid_alive(tmp_path, monkeypatch):
# write fake lock pid = os.getpid(); start_run raises HTTPException 409
...
def test_stop_only_recorded_pid(monkeypatch):
# registry has pid; stop calls os.kill with that pid only
...
```
- [ ] **Step 2: Implement + wire POST `/api/runs/start`, POST `/api/runs/stop`, GET `/api/runs/current`, GET `/api/runs/current/logs?tail=200`, GET `/api/runs`**
- [ ] **Step 3: pytest PASS + commit**
```bash
git commit -m "feat(control_api): runs start/stop/status/logs"
```
---
### Task 4: Import operations
**Files:**
- Create: `apps/control_api/imports_ops.py`
- Extend: `app.py` multipart endpoints
- Create: `tests/unit/test_control_api_import.py`
**Interfaces:**
- Staging dir: `{root}/output/web_uploads/` (mkdir parents)
- Reject path traversal: resolved path must be under staging or project root
- `import_nodes(root, file_path: Path, *, dry_run: bool, replace: bool) -> dict`
subprocess: `[sys.executable, "scripts/import_nodes.py", str(file_path), ...]` with optional `--dry-run` `--replace`
- `import_mail(root, content: str, *, mode: Literal["append","replace"]) -> dict`
target `mail_credentials.txt` (or config `hotmail_accounts_file`); backup then write
- `import_auths(root, src_dir: Path, *, no_remote: bool=True) -> dict`
subprocess `scripts/import_cpa_auth_dir.py --src ...` + `--no-remote` default
- `import_pack(root, zip_path: Path, *, apply: bool) -> dict`
extract to staging; if apply: backup+copy config.json / nodes.json / mail file if present
Upload size enforced via settings.max_upload_bytes.
- [ ] **Step 1: Tests** — traversal reject; mail append backup; nodes dry-run mocks subprocess
- [ ] **Step 2: Implement endpoints**
`POST /api/import/nodes`, `/mail`, `/auths`, `/pack`
- [ ] **Step 3: pytest + commit**
```bash
git commit -m "feat(control_api): import nodes/mail/auths/pack"
```
---
### Task 5: Static web UI
**Files:**
- Create: `apps/web/index.html`, `apps/web/assets/app.css`, `apps/web/assets/app.js`
- Extend: `app.py` mount StaticFiles for `apps/web` at `/` (mount after API routes; use `html=True`)
- Create: `scripts/run_control_api.sh`
- Create: `apps/control_api/__main__.py` (uvicorn run with settings host/port)
**UI behavior:**
- Token prompt stored in `sessionStorage.controlToken`; send as Bearer
- Nav: Overview | Config | Import | Runs
- Overview: fetch `/api/overview` every 5s when visible
- Config: load redacted JSON into form fields for key groups (email_provider, defaultDomains, proxy, proxy_rotate_mode, turnstile_stuck_timeout, cpa_probe_chat, cpa_remote_inject); Save → PUT
- Import: file inputs + dry-run checkbox for nodes; mail textarea; auths note local-only default
- Runs: start form (kind, mode, target, threads, tag); Stop button; log pre tail refresh
Keep CSS simple dark-neutral readable; Chinese+English labels OK matching project.
- [ ] **Step 1: Implement static files + __main__ + run script**
`scripts/run_control_api.sh`:
```bash
#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
export REGISTER_PROJECT_ROOT="${REGISTER_PROJECT_ROOT:-$ROOT}"
export CONTROL_API_HOST="${CONTROL_API_HOST:-127.0.0.1}"
export CONTROL_API_PORT="${CONTROL_API_PORT:-8787}"
exec .venv/bin/python -m apps.control_api
```
- [ ] **Step 2: Manual smoke** — `CONTROL_API_TOKEN=dev uv run python -m apps.control_api` & curl health
- [ ] **Step 3: Commit**
```bash
git commit -m "feat(web): static control plane UI + run entry"
```
---
### Task 6: Delete desktop GUI (surgical)
**Files:**
- Modify: `grok_register_ttk.py` — remove lines class `GrokRegisterGUI` through `main()`/Tk `__main__`; remove top-level tkinter imports if unused above
- Delete: `tests/unit/test_gui_layout_helpers.py`
- Replace: `apps/gui/README.md` with short “removed; use Web control plane”
- Modify: `apps/README.md`, `mise.toml` (gui task → control-api)
**Keep:** all engine code above former class line; `register_cli` import path.
- [ ] **Step 1: Delete GUI class** — replace tail with:
```python
def main() -> None:
raise SystemExit(
"Desktop GUI removed. Use: scripts/run_control_api.sh "
"or: uv run python -m apps.control_api (see apps/README.md)."
)
if __name__ == "__main__":
main()
```
Remove `import tkinter` / `from tkinter import ...` at top if nothing else needs them (verify with rg that engine body does not use tk).
- [ ] **Step 2: Delete test_gui_layout_helpers.py; update mise/apps README**
- [ ] **Step 3: Verify**
```bash
uv run python -m py_compile grok_register_ttk.py register_cli.py
uv run pytest -q
rg -n "GrokRegisterGUI|import tkinter" --glob '*.py' || true
```
Expect: no GrokRegisterGUI; no tkinter in py sources; pytest green.
- [ ] **Step 4: Commit**
```bash
git commit -m "refactor: remove desktop TTK GUI; keep register engine"
```
---
### Task 7: Docs + pyproject polish + full regression
**Files:**
- Modify: `README.md` (desktop UI → Web control plane section)
- Modify: `ARCHITECTURE.md` (usable row; backlog Web UI done; tree apps/control_api + apps/web)
- Modify: `pyproject.toml` description/keywords (`web` not `gui`)
- Modify: `docs/DEVELOPED.md` if it mentions desktop GUI
- Modify: `.gitignore` add `output/web_uploads/`
- [ ] **Step 1: Doc edits** matching design success criteria
- [ ] **Step 2: Full pytest**
```bash
uv run pytest -q
```
- [ ] **Step 3: Commit**
```bash
git commit -m "docs: web control plane is the operator UI"
```
---
## Spec coverage checklist
| Spec item | Task |
|-----------|------|
| FastAPI control API | 1–4 |
| Static web UI | 5 |
| Overview / Config / Import / Runs | 2–5 |
| Auth token + 127.0.0.1 | 1, 5 |
| Backup-before-write | 2, 4 |
| Whitelist start/env | 3 |
| Stop by pid only | 3 |
| Four import types | 4 |
| Delete desktop GUI keep engine | 6 |
| Docs/mise/pyproject | 6–7 |
| Tests | 1–4, 7 |
## Execution note
User requested immediate development. Prefer **inline execution** of this plan in order Task 1→7 without waiting for a second confirmation. Do not stop live pxed batch. Do not enable mid-mint CPA inject.
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,633 @@
# Console10 重构 · 第一批(结构,零视觉变化)实施计划
> 第二批(IA / 交互)另开文档。本批的验收标准是:**operator 在浏览器里看不出任何差别**。
**Goal:** 消除 console10 前端的重复代码与超大文件,建立前端测试基线,为第二批 IA 改造铺路。
**Architecture:** 先搭 Vitest 并对现有行为写回归测试(红线),再做纯机械抽取与文件拆分,测试全程保持绿。
**Tech Stack:** Preact 10 + Vite 6 + @preact/signals;新增 vitest + @testing-library/preact + jsdom(devDependencies)。
## Global Constraints
- **零视觉变化**:不改任何 JSX 输出结构、class 名、文案、按钮顺序。
- **零行为变化**:hydrated / dirty / baseline / clearable confirm 语义逐字保持;两页各自的 confirm 文案**分别保留**,不统一。
- `apps/web/src/lib/providers.js` 的导出签名不变(后端与测试都依赖)。
- 不动 `apps/control_api/**` 与任何 Python 文件。
- 不 commit、不 push、不部署 —— 除非用户明确要求。
- CI 现有 `package-web` job 必须继续绿;新增的 web 测试要挂进 CI。
---
## Task 1: 搭 Vitest 基线
**Files:**
- Modify: `apps/web/package.json`
- Create: `apps/web/vitest.config.js`
- Create: `apps/web/src/lib/providers.test.js`
**Interfaces:**
- Produces: `npm test` 脚本;`vitest.config.js` 导出 jsdom 环境 + preact preset。
- [ ] **Step 1: 装依赖**
```bash
cd apps/web
npm i -D vitest@^4 jsdom@^26 @testing-library/preact@^3
```
- [ ] **Step 2: 写 vitest.config.js**
```js
import { defineConfig } from "vitest/config";
import preact from "@preact/preset-vite";
export default defineConfig({
plugins: [preact()],
test: {
environment: "jsdom",
globals: true,
include: ["src/**/*.test.{js,jsx}"],
},
});
```
- [ ] **Step 3: package.json 加 script**
```json
"test": "vitest run",
"test:watch": "vitest"
```
- [ ] **Step 4: 给已有的 providers.js 写测试(验证工具链通)**
```js
import { describe, it, expect } from "vitest";
import {
normalizeProviderName,
normalizeProvidersList,
providersFromConfig,
EMAIL_PROVIDERS,
} from "./providers.js";
describe("normalizeProviderName", () => {
it("maps outlook aliases to hotmail", () => {
expect(normalizeProviderName("Outlook")).toBe("hotmail");
expect(normalizeProviderName("microsoft")).toBe("hotmail");
});
it("maps google aliases to gmail", () => {
expect(normalizeProviderName("GoogleMail")).toBe("gmail");
});
});
describe("normalizeProvidersList", () => {
it("parses comma / space / full-width separators", () => {
expect(normalizeProvidersList("gmail, hotmail cloudflare"))
.toEqual(["gmail", "hotmail", "cloudflare"]);
});
it("dedupes and drops unknown", () => {
expect(normalizeProvidersList(["gmail", "gmail", "bogus"])).toEqual(["gmail"]);
});
it("accepts arrays", () => {
expect(normalizeProvidersList(EMAIL_PROVIDERS)).toEqual(EMAIL_PROVIDERS);
});
it("empty in → empty out", () => {
expect(normalizeProvidersList("")).toEqual([]);
expect(normalizeProvidersList(null)).toEqual([]);
});
});
describe("providersFromConfig", () => {
it("prefers multi over singleton", () => {
expect(providersFromConfig({ email_providers: ["gmail"], email_provider: "hotmail" }))
.toEqual(["gmail"]);
});
it("falls back to singleton when multi empty", () => {
expect(providersFromConfig({ email_providers: [], email_provider: "hotmail" }))
.toEqual(["hotmail"]);
});
});
```
- [ ] **Step 5: 跑测试**
Run: `cd apps/web && npm test`
Expected: PASS, 8 tests.
- [ ] **Step 6: commit**
```bash
git add apps/web/package.json apps/web/package-lock.json apps/web/vitest.config.js apps/web/src/lib/providers.test.js
git commit -m "test(web): add vitest baseline + providers.js unit tests"
```
---
## Task 2: 抽 `lib/http.js`(pretty / auth401),消除 4 份重复
**Files:**
- Create: `apps/web/src/lib/http.js`
- Create: `apps/web/src/lib/http.test.js`
- Modify: `apps/web/src/pages/Settings/SettingsPage.jsx`(删 28-34、36-42,改 import)
- Modify: `apps/web/src/pages/Resources/MailTab.jsx`(删 31-37、109-115)
- Modify: `apps/web/src/pages/Resources/NodesTab.jsx`(删 9-15、17-23)
- Modify: `apps/web/src/pages/Resources/ImportTab.jsx`(删 9-15、30-36)
**Interfaces:**
- Produces: `pretty(v) -> string`、`auth401(e) -> boolean`(副作用:401 时置 `session.value.authenticated = false`)。
- 命名用 `auth401` 而非 `auth`,避免与页面内其他局部变量撞名,也让调用点自解释。
- [ ] **Step 1: 写测试(先红)**
```js
import { describe, it, expect, beforeEach } from "vitest";
import { pretty, auth401 } from "./http.js";
import { session } from "../store/session.js";
beforeEach(() => {
session.value = { authenticated: true, checked: true };
});
describe("pretty", () => {
it("passes strings through unchanged", () => {
expect(pretty("hi")).toBe("hi");
});
it("pretty-prints objects with 2-space indent", () => {
expect(pretty({ a: 1 })).toBe('{\n "a": 1\n}');
});
it("falls back to String() on circular refs", () => {
const o = {};
o.self = o;
expect(pretty(o)).toBe("[object Object]");
});
});
describe("auth401", () => {
it("returns false and leaves session alone for non-401", () => {
expect(auth401({ status: 500 })).toBe(false);
expect(session.value.authenticated).toBe(true);
});
it("returns false for null", () => {
expect(auth401(null)).toBe(false);
});
it("returns true and clears authenticated on 401", () => {
expect(auth401({ status: 401 })).toBe(true);
expect(session.value.authenticated).toBe(false);
});
});
```
- [ ] **Step 2: 跑测试确认失败**
Run: `cd apps/web && npx vitest run src/lib/http.test.js`
Expected: FAIL — `Failed to resolve import "./http.js"`
- [ ] **Step 3: 实现 lib/http.js**
```js
// Shared API-call helpers: JSON pretty-printing + 401 session handling.
// Extracted from the four copies previously inlined in Settings/Mail/Nodes/Import.
import { session } from "../store/session.js";
/** JSON.stringify with 2-space indent; strings pass through; never throws. */
export function pretty(v) {
try {
return typeof v === "string" ? v : JSON.stringify(v, null, 2);
} catch {
return String(v);
}
}
/** On a 401 error, drop the session so LoginGate shows. Returns true if handled. */
export function auth401(e) {
if (e && e.status === 401) {
session.value = { ...session.value, authenticated: false };
return true;
}
return false;
}
```
- [ ] **Step 4: 跑测试确认通过**
Run: `cd apps/web && npx vitest run src/lib/http.test.js`
Expected: PASS, 6 tests.
- [ ] **Step 5: 改四个页面的调用点**
每个文件:删掉本地 `pretty` / `auth` 定义,加 `import { pretty, auth401 } from "../../lib/http.js";`,把所有 `auth(e)` 改成 `auth401(e)`。
`SettingsPage.jsx` 里 `session` 的 import 若只被 `auth` 用则一并删除(用 grep 确认)。
- [ ] **Step 6: 全量测试 + build**
```bash
cd apps/web && npm test && npm run build
```
Expected: 测试全绿;build 产出 dist/index.html。
- [ ] **Step 7: commit**
```bash
git add apps/web/src/lib/http.js apps/web/src/lib/http.test.js apps/web/src/pages
git commit -m "refactor(web): extract shared pretty/auth401 into lib/http.js"
```
---
## Task 3: 抽 `useBusy` hook,把 37 处裸字符串 busy 收敛
**Files:**
- Create: `apps/web/src/lib/useBusy.js`
- Create: `apps/web/src/lib/useBusy.test.jsx`
- Modify: `SettingsPage.jsx` / `MailTab.jsx` / `NodesTab.jsx` / `ImportTab.jsx` / `AccountsPage.jsx`
**Interfaces:**
- Produces: `useBusy() -> { busy, is(tag), any, run(tag, fn) }`
- `busy`: 当前 tag 字符串或 `""`
- `is(tag)`: 布尔,等价于旧的 `busy === "tag"`
- `any`: 布尔,等价于 `busy !== ""`
- `run(tag, fn)`: `setBusy(tag)` → `await fn()` → `finally setBusy("")`,返回 fn 的返回值,异常原样抛出
- [ ] **Step 1: 写测试(先红)**
```jsx
import { describe, it, expect } from "vitest";
import { render, screen, waitFor } from "@testing-library/preact";
import { useBusy } from "./useBusy.js";
function Probe({ onReady }) {
const b = useBusy();
onReady(b);
return <span data-testid="busy">{`${b.busy}|${b.is("save")}|${b.any}`}</span>;
}
describe("useBusy", () => {
it("starts idle", () => {
render(<Probe onReady={() => {}} />);
expect(screen.getByTestId("busy").textContent).toBe("|false|false");
});
it("sets tag during run and clears after", async () => {
let api;
render(<Probe onReady={(b) => { api = b; }} />);
let release;
const p = api.run("save", () => new Promise((r) => { release = r; }));
await waitFor(() =>
expect(screen.getByTestId("busy").textContent).toBe("save|true|true"),
);
release("done");
await expect(p).resolves.toBe("done");
await waitFor(() =>
expect(screen.getByTestId("busy").textContent).toBe("|false|false"),
);
});
it("clears the tag and rethrows when fn throws", async () => {
let api;
render(<Probe onReady={(b) => { api = b; }} />);
await expect(api.run("save", async () => { throw new Error("boom"); }))
.rejects.toThrow("boom");
await waitFor(() =>
expect(screen.getByTestId("busy").textContent).toBe("|false|false"),
);
});
});
```
- [ ] **Step 2: 跑测试确认失败**
Run: `cd apps/web && npx vitest run src/lib/useBusy.test.jsx`
Expected: FAIL — 无法解析 `./useBusy.js`
- [ ] **Step 3: 实现**
```js
// Single-slot busy-tag state. Replaces the setBusy("tag") / busy === "tag"
// string pairs that were duplicated across every ops page.
import { useCallback, useState } from "preact/hooks";
export function useBusy(initial = "") {
const [busy, setBusy] = useState(initial);
const is = useCallback((tag) => busy === tag, [busy]);
const run = useCallback(async (tag, fn) => {
setBusy(tag);
try {
return await fn();
} finally {
setBusy("");
}
}, []);
return { busy, setBusy, is, any: busy !== "", run };
}
```
- [ ] **Step 4: 跑测试确认通过**
Run: `cd apps/web && npx vitest run src/lib/useBusy.test.jsx`
Expected: PASS, 3 tests.
- [ ] **Step 5: 逐页替换**
只做机械替换:`const [busy, setBusy] = useState("")` → `const { busy, setBusy, is: busyIs, run: withBusy } = useBusy();`,
`busy === "x"` → `busyIs("x")`。**`setBusy` 保留导出**,先不强制把每个 try/finally 改写成 `withBusy`——
只在 try/finally 结构完全标准(`setBusy(t)` 开头、`finally { setBusy("") }` 结尾、中间无其他 setBusy)的函数里改写。
结构特殊的(如 NodesTab 的 `testAllCatalog` 用 `setCatResult("testing…")` 而非 busy)保持原样。
- [ ] **Step 6: 测试 + build + commit**
```bash
cd apps/web && npm test && npm run build
cd ../.. && git add apps/web/src && git commit -m "refactor(web): centralize busy-tag state in useBusy hook"
```
---
## Task 4: 抽 `useConfigForm` hook —— hydrated / dirty / baseline / clearable confirm
**这是本批风险最高的一步。先写回归测试锁住现有行为,再抽。**
**Files:**
- Create: `apps/web/src/lib/useConfigForm.js`
- Create: `apps/web/src/lib/useConfigForm.test.jsx`
- Modify: `apps/web/src/pages/Settings/SettingsPage.jsx`
- Modify: `apps/web/src/pages/Resources/MailTab.jsx`
**Interfaces:**
- Consumes: `lib/http.js` 的 `auth401`
- Produces:
```
useConfigForm({ empty, hydrate, buildPartial, confirmClear, onSaved, onError })
-> { form, set, setForm, hydrated, dirty, baseline, load({force}), save(), busy }
```
- `hydrate(config) -> { form, baseline }`:各页自己把 `/api/config` 映射成表单 + baseline
- `buildPartial(form) -> object`:各页自己产出 PUT 的 partial
- `confirmClear(form, baseline) -> string[] | null`:返回将被清空的字段描述列表;hook 负责弹 `window.confirm`,文案由各页通过 `confirmMessage(list)` 提供
- [ ] **Step 1: 给现状写回归测试(对 SettingsPage 与 MailTab 各一组)**
覆盖这五条不变量(当前两页都成立,抽取后必须仍成立):
1. 初始 GET 失败 → `hydrated=false` → Save 按钮 disabled,点击不发 PUT。
2. GET 401 → `session.authenticated=false` 且 `hydrated=false`。
3. 有 dirty 时点 Reload → 弹 confirm;取消则不发 GET。
4. 把 clearable 字段清空后点 Save → 弹 confirm;取消则不发 PUT。
5. Save 成功 → `dirty=false`,表单以服务端返回值重新水合。
测试用 `vi.mock("../../api/client.js")` 打桩,断言 `putConfig` 的调用次数与入参。
- [ ] **Step 2: 跑测试确认全绿(锁住现状,此时还没抽 hook)**
Run: `cd apps/web && npm test`
Expected: PASS —— 这批测试描述的是**现有**行为,应当立刻通过。若有一条不通过,说明我对现状的理解有误,停下来核对,不要改测试去迁就。
- [ ] **Step 3: 实现 useConfigForm.js**
- [ ] **Step 4: SettingsPage 切到 hook**
Run: `cd apps/web && npm test`
Expected: Step 1 的 Settings 那组测试仍全绿。
- [ ] **Step 5: MailTab 切到 hook**(`baselineDomains` 字符串按现状塞进 `baseline` 对象的一个字段,**confirm 文案不变**)
Run: `cd apps/web && npm test`
Expected: 全绿。
- [ ] **Step 6: build + commit**
```bash
cd apps/web && npm run build
cd ../.. && git add apps/web/src && git commit -m "refactor(web): share hydrate/dirty/clearable-confirm logic via useConfigForm"
```
---
## Task 5: 拆 MailTab(1023 行 → 5 个文件)
**Files:**
- Create: `apps/web/src/pages/Resources/mail/MailProviderPanels.jsx`(CF/CloudMail/DuckMail/yyds/Gmail/Hotmail 六个折叠面板 + `panel()` helper)
- Create: `apps/web/src/pages/Resources/mail/MailCredImport.jsx`(凭证导入卡片)
- Create: `apps/web/src/pages/Resources/mail/MailPoolProbe.jsx`(池 KPI + 探测 + 精简 + 移出 + 结果表)
- Create: `apps/web/src/pages/Resources/mail/domains.js`(`parseDomainList` / `joinDomains`)
- Create: `apps/web/src/pages/Resources/mail/domains.test.js`
- Modify: `apps/web/src/pages/Resources/MailTab.jsx`(降到 ~200 行:状态 + 编排 + 三个子组件)
**Interfaces:**
- `MailProviderPanels({ form, set, openPanels, onTogglePanel, cfDomains, cfMeta, cfSelected, onFetchCfDomains, onToggleCfDomain, busy })`
- `MailCredImport({ onImported })` —— 自管 credText/credMode/busy
- `MailPoolProbe({ pool, onReloadPool })` —— 自管 probe/selected/busy
- `domains.js`: `parseDomainList(raw) -> string[]`、`joinDomains(list) -> string`(去重保序、大小写不敏感)
- [ ] **Step 1: domains.js 测试先行**
```js
import { describe, it, expect } from "vitest";
import { parseDomainList, joinDomains } from "./domains.js";
describe("parseDomainList", () => {
it("splits on comma, full-width comma, and whitespace", () => {
expect(parseDomainList("a.com,b.com c.com")).toEqual(["a.com", "b.com", "c.com"]);
});
it("returns [] for empty/null", () => {
expect(parseDomainList("")).toEqual([]);
expect(parseDomainList(null)).toEqual([]);
});
});
describe("joinDomains", () => {
it("dedupes case-insensitively, keeping first spelling and order", () => {
expect(joinDomains(["A.com", "b.com", "a.COM"])).toBe("A.com,b.com");
});
it("drops blanks", () => {
expect(joinDomains(["", " ", "a.com"])).toBe("a.com");
});
});
```
- [ ] **Step 2: 跑测试确认失败**(模块不存在)
- [ ] **Step 3: 从 MailTab.jsx:56-76 原样搬运两个函数到 domains.js 并导出**
- [ ] **Step 4: 跑测试确认通过**
- [ ] **Step 5: 依次搬三个子组件**
每搬一个:MailTab 只保留 `<MailPoolProbe … />` 之类的调用;搬完立刻 `npm run build` 确认编译通过。
搬运是**剪切粘贴**,不重排 JSX、不改 class、不改文案。
- [ ] **Step 6: 全量测试 + build + commit**
```bash
cd apps/web && npm test && npm run build
cd ../.. && git add apps/web/src && git commit -m "refactor(web): split MailTab into provider panels / cred import / pool probe"
```
---
## Task 6: 拆 NodesTab(989 行 → 4 个文件)
**Files:**
- Create: `apps/web/src/pages/Resources/nodes/ClashPanel.jsx`(订阅导入 + 池测活 + 策略组 + 叶子表)
- Create: `apps/web/src/pages/Resources/nodes/CatalogPanel.jsx`(添加节点 + 筛选分页 + catalog 表)
- Create: `apps/web/src/pages/Resources/nodes/clashFilters.js`(`filterClashLeaves` / `namesInPool` / 各 OPTS 常量)
- Create: `apps/web/src/pages/Resources/nodes/clashFilters.test.js`
- Modify: `apps/web/src/pages/Resources/NodesTab.jsx`(降到 ~60 行:子 tab 切换 + 两个 panel)
- [ ] **Step 1: clashFilters 测试先行**
```js
import { describe, it, expect } from "vitest";
import { filterClashLeaves, namesInPool } from "./clashFilters.js";
const LEAVES = [
{ name: "hk-1", health: "fail", in_register_pool: true, last_delay_ms: 100, groups: ["🎯Grok注册"] },
{ name: "us-2", health: "ok", in_register_pool: true, last_delay_ms: 300, groups: ["🎯Grok注册"] },
{ name: "jp-3", health: "ok", in_register_pool: false, last_delay_ms: 50, groups: ["PROXY"] },
{ name: "sg-4", health: "unknown", in_register_pool: true, last_delay_ms: null, groups: [] },
];
describe("filterClashLeaves", () => {
it("pool mode keeps only register-pool leaves", () => {
expect(filterClashLeaves(LEAVES, "pool", "").map((n) => n.name))
.toEqual(["us-2", "sg-4", "hk-1"]);
});
it("sorts pool-first, then ok > unknown > fail, then by delay", () => {
expect(filterClashLeaves(LEAVES, "all", "").map((n) => n.name))
.toEqual(["us-2", "sg-4", "hk-1", "jp-3"]);
});
it("query filters by case-insensitive substring", () => {
expect(filterClashLeaves(LEAVES, "all", "JP").map((n) => n.name)).toEqual(["jp-3"]);
});
it("does not mutate the input array", () => {
const before = LEAVES.map((n) => n.name);
filterClashLeaves(LEAVES, "all", "");
expect(LEAVES.map((n) => n.name)).toEqual(before);
});
});
describe("namesInPool", () => {
it("matches by group membership", () => {
expect(namesInPool({ leaves: LEAVES }, "PROXY")).toEqual(["jp-3"]);
});
it("falls back to in_register_pool for known register groups", () => {
expect(namesInPool({ leaves: LEAVES }, "♻️Grok优选"))
.toEqual(["hk-1", "us-2", "sg-4"]);
});
it("honours the limit", () => {
expect(namesInPool({ leaves: LEAVES }, "♻️Grok优选", 2)).toHaveLength(2);
});
});
```
> 注:期望的排序结果在 Step 2 跑之前先按 `NodesTab.jsx:25-43` 的比较器手推一遍;如果实际输出与上面不符,**以实现为准修正测试**(本任务是保行为,不是改行为),并在 commit message 里记一句。
- [ ] **Step 2: 跑测试确认失败**(模块不存在)
- [ ] **Step 3: 从 NodesTab.jsx:25-84、173-185 搬运到 clashFilters.js**
- [ ] **Step 4: 跑测试确认通过**
- [ ] **Step 5: 搬两个 panel 组件,每次搬完 build**
- [ ] **Step 6: 全量测试 + build + commit**
```bash
cd apps/web && npm test && npm run build
cd ../.. && git add apps/web/src && git commit -m "refactor(web): split NodesTab into clash / catalog panels"
```
---
## Task 7: 抽 `PageHeader` 组件
**Files:**
- Create: `apps/web/src/ui/PageHeader.jsx`
- Modify: `apps/web/src/ui/index.js`
- Modify: 五个页面的 `<header class="page-head">`
**Interfaces:**
- `PageHeader({ title, hint, children })` → `children` 渲染进 `.toolbar`
- [ ] **Step 1: 实现**
```jsx
// Shared page header: title + hint on the left, toolbar slot on the right.
export function PageHeader({ title, hint, children }) {
return (
<header class="page-head">
<div>
<h1>{title}</h1>
{hint ? <p class="hint">{hint}</p> : null}
</div>
{children ? <div class="toolbar">{children}</div> : null}
</header>
);
}
```
- [ ] **Step 2: 逐页替换**
注意:`SettingsPage` 与 `ResourcesPage` 的 hint 里含 `<a>` / `<code>` —— 用 JSX 片段作为 `hint` 传入,**不要**改成纯文本。
`ResourcesPage` 没有 toolbar,不传 children。
- [ ] **Step 3: build 并肉眼 diff 产物 HTML 结构**
Run: `cd apps/web && npm run build && npm test`
Expected: 全绿;DOM 结构与替换前逐字一致。
- [ ] **Step 4: commit**
```bash
git add apps/web/src && git commit -m "refactor(web): extract shared PageHeader component"
```
---
## Task 8: web 测试挂进 CI
**Files:**
- Modify: `.github/workflows/ci.yml`
- [ ] **Step 1: 在 `package-web` job 的 "Build console10" 之前插入测试步骤**
```yaml
- name: Web unit tests
working-directory: apps/web
run: |
npm ci
npm test
```
- [ ] **Step 2: 本地干跑等价命令**
```bash
cd apps/web && npm ci && npm test && npm run build
```
Expected: 全绿。
- [ ] **Step 3: commit**
```bash
git add .github/workflows/ci.yml
git commit -m "ci(web): run console10 unit tests before packaging"
```
> `package-web` 只在 push 到 main 时跑(`if: github.ref == 'refs/heads/main'`)。
> 若希望 PR 也跑 web 测试,需要另开一个不带该 `if` 的 job —— 本批不做,记入第二批待议。
---
## 收尾
全部任务完成后:`npm test && npm run build`,然后向用户报告 diff 规模与文件行数前后对比。
**不 commit 到远端、不部署**,等用户确认后再走 push / deploy 流程。
## 第二批(IA)待办清单 —— 本批不动,只登记
1. `defaultDomains` 三个控件合一,从 provider 折叠面板里提到全局区。
2. MailTab 配置区 / 运维区分离(保存型 vs 破坏型操作)。
3. 六处 raw JSON `<pre class="log">` 的去留。
4. Settings 平铺表单分组;`cpa_remote_inject (intent)` 等内部术语改写。
5. `email_providers` 两页不对称规则的 UI 化表达(现在靠 4 段 hint 文字)。
6. Register footer「自检 →」链接伪装成按钮。
7. 41 个跨文件重复 class 的 CSS 收敛;`run.css` 611 行拆分。
8. 资源页三层 tab 嵌套。
9. CI 里给 PR 也跑 web 测试。
@@ -0,0 +1,55 @@
# Console10 第二批(IA/交互)Implementation Plan
> 前置:第一批(结构重构,2026-07-26-console10-refactor-batch1.md)已完成且全绿。
> 本批**允许视觉/交互变化**,但不改后端契约、不改保存语义(PUT body、confirm 拦截逻辑不变)。
**Goal:** 按第一批登记的 9 条 IA 待办改善 console10 信息架构与交互表达。
**用户已拍板的取舍:**
- 待办 3(raw JSON):6 处 `<pre class="log">` → 折叠 `<details>`(默认收起,summary 一行摘要)。
- 待办 8(三层 tab):Nodes 子 tab 提升到资源页顶层 → 「节点·Clash / 节点·catalog / 邮箱 / 导入」四平铺。
- 待办 5(池规则):新建状态行组件表达 email_providers 两页不对称规则,替换 4 段 hint 长文字。
## Global Constraints
- 不改任何 PUT/POST body、不改 confirm 拦截条件与文案语义(文案可精简但拦截行为不变)。
- 不动 Python / 后端。
- 不 commit、不 push、不部署 —— 除非用户明确要求。
- 每个任务后 `npm test && npm run build` 全绿;现有 45 个测试若因 IA 改动断言失效,先改测试再改实现。
- 双指标 UI(注册页 progress)不动。
## Tasks
### Task B1: `ui/LogDetails.jsx` 折叠日志组件(待办 3)
- Create `src/ui/LogDetails.jsx`:`LogDetails({ text, summary, compact })` → 无 text 时 null;否则 `<details class="log-details">` + `<summary>`(默认「响应详情」或调用方给的摘要)+ 原 `<pre class="log …">`。
- 替换 6 处:SettingsPage、ImportTab、MailTab、AccountsPage、ClashPanel、CatalogPanel。
- styles/components.css 加 `.log-details` 样式(summary 一行、hint 色、展开后 pre 原样)。
### Task B2: 资源页四平铺 tab(待办 8)
- ResourcesPage TABS → `[clash 节点·Clash, catalog 节点·catalog, mail 邮箱, import 导入]`,直接渲染 `<ClashPanel active>` / `<CatalogPanel active>`(保持常驻挂载 + active 语义)。
- 删除 NodesTab.jsx 壳与其子 Tabs;`resources.css` 里 `.nodes-tab` 选择器改为面板容器 class(`nodes-panels` 包一层保留原样式命中)。
### Task B3: `ProviderPoolStatus` 状态行组件(待办 5)
- Create `src/ui/ProviderPoolStatus.jsx`:props `{ selected, primaryProvider, canClear, hydrated, dirty }` → chips 显示当前池、空池时显示「单通道 <primary>」、`canClear` 显示「此页可清空池」/「此页不可清池(去设置页)」徽标、未加载/未保存警示。
- SettingsPage、RegisterPage(RegForm) 接入,删除对应 hint 长段。
### Task B4: MailTab IA(待办 1+2)
- defaultDomains 提升:MailProviderPanels 里 CF/CloudMail 两处 textarea 收敛为全局区一个控件(`mail/DefaultDomainsCard.jsx`),CF 勾选仍写同一 form 字段;面板内只留说明短句。
- 配置区(Provider 面板 + 保存)与运维区(凭证导入 / 池探测,破坏性操作)之间加分区标题,运维区标注「操作立即生效,不走保存」。
### Task B5: Settings 分组 + 术语(待办 4)
- settings-form 分三组:邮箱链路 / 代理 / 注册行为;`cpa_probe_chat` → 「注册后探测 chat(cpa_probe_chat)」、`cpa_remote_inject (intent)` → 「远端注入意向(cpa_remote_inject)」、`turnstile_stuck_timeout` → 「Turnstile 卡死超时秒(turnstile_stuck_timeout)」等:中文名 + code 原名。
- 保存语义不变。
### Task B6: Register「自检 →」(待办 6)
- footer `<a class="btn btn-ghost btn-sm">` → 文字链接样式 `class="link-hint"`(新样式:hint 色下划线),文案「自检 / 清理 → 设置页」。
### Task B7: CSS 收敛(待办 7)
- run.css 611 行拆出 `run-progress.css`(RunProgress 专属段);跨文件重复的 `.page-head/.toolbar`(run.css vs base.css 双定义)去重,保 base.css 版本。
- 仅删被覆盖的重复定义,不改最终计算样式。
### Task B8: CI 给 PR 跑 web 测试(待办 9)
- ci.yml 新增独立 `web-test` job(无 main-only `if`,needs 无、push+PR 都跑):setup-node + `npm ci && npm test`(working-directory apps/web)。package-web 保持不变。
## 收尾
`npm test && npm run build` 全绿后报告;不 commit / push / deploy。
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,661 @@
# Console UI · v1 进度元素合并设计
**Date:** 2026-07-21
**Status:** Draft v2 — design self-review amendments applied; awaiting user approval
**Product:** ai-register-machine Web control plane (`apps/web` + `apps/control_api`)
**Related:** `docs/superpowers/specs/2026-07-21-web-control-plane-design.md`(基线架构仍有效)
**Baseline commits / surfaces:**
- **v1(c44ac22):** top-nav Overview / Config / Import / Runs;状态卡片 + JSON 预览
- **console4(当前):** sidebar 注册 / 账号池 / 邮箱接码 / 节点池 / 导入 / 设置;右侧 pills + status-card + log
- **Backend 已就绪:** `apps/control_api/progress.py` → `build_progress` 已产出 `steps[]` / `timeline[]` / KPI 计数,UI 未消费
**Self-review (2026-07-21):** §14 为完整 review 结论;§3.4 / §4.1.4 / §5.7–5.9 / §9 已按「功能给全 + UI 好看」修订。
---
## 1. Problem
console 重写保留了更好的 **IA 骨架**(侧栏多页、注册表单 + 日志分栏、账号/节点/邮箱运维面),但把 **进度呈现** 退化成:
| 当前 console4 | 问题 |
|---------------|------|
| `run-pills` 一行 chip | 信息密度低,没有「还差多少 / 完成百分比」的视觉权重 |
| `status-card` 纯文本 phase | 有 `phase_title`/`phase_detail`,但没有步骤轨、没有双进度条 |
| 无 KPI 网格 | `complete/goal`、`batch_gained/target`、`product_ok`、`remain` 后端有,前端未做卡片 |
| 无 step rail | `GET /api/runs/current` 已 flatten `steps[]`(done/active/pending),UI 完全忽略 |
| 无 timeline | `timeline[]` 已有,UI 未展示 |
| 丢 v1 启动面 | kind / product / `SKIP_CLASH_PREFLIGHT` 在 API 与 v1 Runs 表单存在,console 写死 `grok_supervisor`+`grok` |
v1 的优点不是「截图里的配色」,而是 **一眼能读完任务健康度**(status card 一行:`product_ok · run=ALIVE · complete · zero`)+ **Runs 启动参数完整**。console 的优点是 **骨架与运维页**。本设计只做 **注入与归位**,不重做整站视觉、不生搬参考图。
---
## 2. Goals / Non-goals
### 2.1 Goals
1. **保留 console 骨架**:sidebar 六页、注册 split(左表单 / 右状态+日志)、账号池 / 邮箱 / 节点 / 导入 / 设置。
2. **注入 v1 级进度可读性**:KPI 卡片 + 双进度条 + 步骤轨 + 精简 timeline,全部吃现有 `build_progress` / `run_status` 字段,**不新开后端契约**(除非 UI 缺字段再补,见 §6)。
3. **恢复 v1 丢掉的控制面能力**(不丢产品功能):
- multi-kind 启动:`grok_supervisor` | `register_sh`
- multi-product:`grok` | `mimo` | `chatgpt`(`register_sh` 时)
- `SKIP_CLASH_PREFLIGHT` 表面(allowlist 已有)
- Overview 级「全局一眼」信息(可并入注册页顶栏,不必强行加第七页,见 §4.1)
4. **产品契约硬约束 UI 不得反向诱导**:
- mint 路径 `CPA_REMOTE_INJECT=false` / `CPA_PROBE_CHAT=false`(supervisor 硬编码)
- 批边界导入仅 `CPA_BATCH_END_INJECT` + EVERY knobs
- disk-first:主链路止于 `cpa_auths` 落盘
- fail-fast:zero streak / stuck 必须醒目
- 不全局 `pkill`;stop 只打 registry/lock pid + process group
5. **静态 vanilla HTML/CSS/JS**,无 Node 构建;asset 版本 bump(如 `?v=console5`)。
### 2.2 Non-goals
- 不做参考截图像素级复刻 / 换皮肤大赛
- 不引入 React/Vue/npm
- 不重写 `progress.py` 相位机(可微调文案,不改算法优先级)
- 不做 job 队列 / 多 host / 实时 SSE 强制升级(仍 4s poll;可选后续)
- 不启用线上 `CPA_BATCH_END_INJECT` 默认 true
- 不改生产登录 `mango / …`;bootstrap admin 仍仅空用户库
- 不把 coinbot / 无关进程纳入 stop 范围
- 不做 Turnstile 浏览器池接入(工具栏 WIP 按钮保持 disabled)
---
## 3. Feature inventory
### 3.1 v1(c44ac22)有、console 弱化或丢失
| 能力 | v1 | console4 | 本设计 |
|------|----|----------|--------|
| Overview hub | 独立页:status card + full JSON | 无独立页;注册页偶尔拉 overview 只取 `product_ok` | **注册页顶 KPI + 可选折叠 JSON**;不强制新 sidebar 项 |
| 状态一行可读 | `product_ok · ALIVE · complete · zero` | pills 散点 | **KPI 网格 + 进度条** 取代纯 pills 为主展示 |
| kind 选择 | `grok_supervisor` / `register_sh` | 写死 supervisor | **高级启动折叠区** 恢复 |
| product 选择 | grok/mimo/chatgpt | 写死 grok | **register_sh 时显示 product** |
| SKIP_CLASH_PREFLIGHT | 表单字段 | 无 | **高级启动折叠区** checkbox |
| Runs 独立页 | 有 | 合并进「注册」 | **保持合并**(骨架优先);启动控件在注册左栏 |
| Config 页 | 精简字段 | 设置 + 注册表单双写 | **保持** 设置全量 + 注册协议子集 |
### 3.2 console 已有、必须保留
| 页 | 保留内容 |
|----|----------|
| 注册 | 邮箱/域名/target/threads/mode/tag、Turnstile 超时、CHUNK、sso-only、proxy_rotate、proxy_list、batch-end inject + EVERY、probe 强制关、开始/停止/刷新、log which/tail/follow |
| 账号池 | complete 列表、筛选分页、soft-delete |
| 邮箱接码 | provider/domains/secrets、Hotmail 凭证导入、plus-alias 禁默认 |
| 节点池 | Clash 叶子 + catalog 双 tab、测活、筛选 |
| 导入 | nodes / mail / auths / pack(auth 默认 no-remote) |
| 设置 | config 全量、bearer token、selfcheck/cleanup |
| 登录门 | cookie session + optional bearer |
### 3.3 后端已提供、前端未用(本设计消费)
来自 `run_status` / `build_progress`(已 flatten 到 `GET /api/runs/current` 的 `run`):
| 字段 | UI 用途 |
|------|---------|
| `alive`, `pid`, `kind`, `meta.tag` / `tag` | 状态 pill + KPI |
| `complete`, `goal_complete`, `baseline_complete`, `remain` | 总进度条 + KPI「全局 complete」 |
| `batch_gained`, `target`/`target_new`, `batch_remain` | 本批进度条 + KPI「本批」 |
| `consecutive_zero`, `sub`, `chunk`, `mode` | KPI / warn pill |
| `phase`, `phase_title`, `phase_detail` | status-card 标题与副文案 |
| `stuck`, `stuck_reason` | danger 态 + 顶栏告警 |
| `steps[]` `{id,title,desc,state}` | **步骤轨** |
| `timeline[]` `{source,phase,title,line}` | **时间线**(最近 N 条) |
| `recent_writes` | 可选小列表「最近落盘」 |
| `supervisor_log`, `worker_log` | 路径 hint(已有) |
| overview.`product_ok`, `nodes.{total,enabled,healthy}` | KPI disk + 节点健康摘要 |
| `summary` (SUMMARY_JSON) | phase 卡副信息:reg_success / mint / fatal_reason |
| `recent_writes` | **必做**「最近落盘」chip 列表(review 从可选升为 P0) |
| `last_lines` / `worker_last_lines` | idle 或无 log-follow 时的兜底快照(P1) |
| `GET /api/runs` → `list_runs` | **运行历史**折叠表(v1 有 runs 面;console 丢) |
### 3.4 功能完备矩阵(review 补全 — 必须做满)
相对 allowlist `EXTRA_ENV_ALLOWLIST` 与 v1/console API,UI **必须暴露**(隐藏=功能不全):
| 能力 | API / 后端 | console4 | 设计要求 |
|------|------------|----------|----------|
| kind `grok_supervisor` / `register_sh` | `StartRunRequest.kind` | 写死 | **P0** 高级启动 |
| product grok/mimo/chatgpt | `StartRunRequest.product` | 写死 | **P0** register_sh 时 |
| mode ordinary/residential | 已有 | 有 | 保留;register_sh 时 mode 可灰显+说明「supervisor 专用」 |
| target / threads / tag | 已有 | 有 | 保留 |
| SKIP_CLASH_PREFLIGHT | allowlist | 无 | **P0** |
| SUPERVISOR_CHUNK | allowlist | 有 | 保留 |
| CPA_BATCH_END_INJECT | allowlist | 有 | 保留,默认关 |
| CPA_BATCH_IMPORT_EVERY | allowlist | 有 | 保留 |
| CPA_BATCH_IMPORT_SIZE | allowlist | **无** | **P0** 高级启动数字框,默认 100 |
| CPA_BATCH_IMPORT_PAUSE | allowlist | **无** | **P0** 高级启动数字框,默认 3 |
| NODE_SCORE 0/1 | allowlist | 无 | **P0** 高级 select,默认「不传」 |
| CPA_PROBE_CHAT | allowlist | disabled false | 保留强制关 |
| EMAIL_PROVIDER / DEFAULT_DOMAINS via extra_env | allowlist | 仅 config 保存 | **P1** 开始时可选「把当前邮箱表单同步进 extra_env」checkbox(默认开)— 保证 register_sh 不读 config 时仍能带邮箱 |
| 进度 steps/timeline/bars/KPI | progress flatten | 未用 | **P0** |
| recent_writes | progress | 未用 | **P0** |
| stuck / zero 醒目 | progress | pill 弱 | **P0** |
| 运行历史 list_runs | `GET /api/runs` | **无 UI** | **P1** 注册页底或设置旁折叠「最近运行」 |
| overview project_root / nodes | overview | 仅 product_ok | **P0** KPI + 页脚一行 root |
| log which/tail/follow | logs API | 有 | 保留;log 区 `flex:1` 不被进度挤没 |
| stop process_group | stop API | 有 | 保留;结果展示 `source/mode` |
| 账号 soft-delete / 筛选 | accounts API | 有 | 保留 + summary KPI 皮 |
| 邮箱配置 + hotmail import | config+import | 有 | 保留 |
| 节点 Clash+catalog | nodes API | 有 | 保留 |
| 导入四件套 | import API | 有 | 保留;卡片 grid 美化 |
| 设置 secrets 掩码 | config | 有 | 保留 |
| selfcheck / cleanup | ops | 有 | 保留;注册顶栏 + 设置双入口 OK |
| 测代理 | nodes test | 有 | 保留 |
| 登录 / logout / bearer | auth | 有 | 保留 |
| GitHub 仓库链 | 静态 | 有 | 保留 |
| 标题/品牌 | 「Grok 注册机」 | 有 | **P1** 副标改为「AI 注册机 · multi-product」避免 mimo/chatgpt 违和 |
**明确不做(仍非缺口):** Turnstile 池按钮、SSE、多 host、mid-mint inject 开关、全局 pkill。
---
## 4. Page-by-page layout(骨架不变)
### 4.1 注册页(主战场)
**骨架:** `page-head` toolbar 不变;`split` = 左 `form-panel` + 右 `log-panel`。
#### 4.1.1 右侧:进度栈(注入点)
自上而下固定顺序(替换/增强现有 pills + status-card 区域):
```
┌─ run-header ─────────────────────────────────────────┐
│ [ALIVE|idle] tag=… pid=… mode=ordinary │
│ (stuck 时整条红底:stuck_reason) │
└──────────────────────────────────────────────────────┘
┌─ kpi-grid (2×3 或 3×2) ──────────────────────────────┐
│ complete/goal │ 本批 gained/target │ disk product_ok │
│ remain │ sub · zero │ nodes healthy* │
└──────────────────────────────────────────────────────┘
┌─ bars ───────────────────────────────────────────────┐
│ 全局 complete ████████░░░░ 630 / 1190 (53%) │
│ 本批 gained ██░░░░░░░░ 2 / 562 │
└──────────────────────────────────────────────────────┘
┌─ step-rail (横向可换行) ─────────────────────────────┐
│ ●批次 ●节点 ●子批 ●浏览器 ◉表单 ○盾 ○OTP … │
│ state: done=绿勾 active=高亮脉冲 pending=灰 │
└──────────────────────────────────────────────────────┘
┌─ status-card ────────────────────────────────────────┐
│ phase_title │
│ phase_detail(单行截断,hover/展开全文) │
└──────────────────────────────────────────────────────┘
┌─ timeline (可折叠,默认展开最近 8 条) ────────────────┐
│ · supervisor | mint | wrote xai-… │
│ · worker | otp | … │
└──────────────────────────────────────────────────────┘
┌─ log-toolbar + #run-log (现有) ──────────────────────┐
```
\* `nodes healthy` 来自 overview,poll 失败时显示 `—`,不阻塞进度渲染。
**pills 去留:** 不再作为主信息源;可保留 1 行极简 chips(ALIVE / stuck / mode)或完全并入 `run-header`。**禁止**再把 complete/goal 只塞进小 pill。
**百分比计算(前端纯函数):**
```
goalPct = goal>0 && complete!=null ? clamp(complete/goal*100,0,100) : null
batchPct = target>0 && gained!=null ? clamp(gained/target*100,0,100) : null
```
`null` 时条显示 indeterminate/空轨 + 文案 `—`,不伪造 0%。
#### 4.1.2 左侧:启动参数恢复
在现有 `reg-form` **底部**(或「数量/线程/模式」区块旁)增加 **「高级启动」`<details>`**,默认折叠:
| 控件 | 绑定 | 说明 |
|------|------|------|
| kind | `select` | `grok_supervisor`(默认)/ `register_sh` |
| product | `select` | grok/mimo/chatgpt;**仅 kind=register_sh 时启用**,supervisor 时锁 grok |
| SKIP_CLASH_PREFLIGHT | checkbox | → `extra_env.SKIP_CLASH_PREFLIGHT=1|0` |
| NODE_SCORE | optional select 0/1 | allowlist 已有;默认不传(吃环境/配置) |
`startRun()` body 改为读这些控件;**默认值与今日生产一致**(supervisor + grok + 不 skip preflight),避免误触。
**高级启动完整字段(§3.4 P0):**
| 控件 | 默认 | → |
|------|------|---|
| kind | grok_supervisor | body.kind |
| product | grok(supervisor 锁定) | body.product |
| SKIP_CLASH_PREFLIGHT | 关 | extra_env `0`/`1` 仅当勾选传 `1` |
| NODE_SCORE | (不传) | 选 0/1 才写入 extra_env |
| CPA_BATCH_IMPORT_SIZE | 100 | extra_env(仅 batch-end 开时也可始终传) |
| CPA_BATCH_IMPORT_PAUSE | 3 | extra_env |
| 同步邮箱到 extra_env | 开 | `EMAIL_PROVIDER` + `DEFAULT_DOMAINS` 从当前表单 |
现有 batch-end / CHUNK / probe 契约不变:
- 保存配置仍强制 `cpa_remote_inject=false`、`cpa_probe_chat=false`
- `CPA_BATCH_END_INJECT` 只走 `extra_env`,不写 config intent 为 true 当默认
- kind 切换时:supervisor 显示 CHUNK/batch-end/mode;register_sh 隐藏 CHUNK 与 batch-end(无 supervisor 语义),显示 product
#### 4.1.3 顶栏「全局一眼」(v1 Overview 精神)
不强制新 sidebar「Overview」页(避免和注册抢注意力)。在注册 `page-head` hint 行或 KPI 第一格体现:
`product_ok=N · run=ALIVE|idle · complete=C/G · zero=Z`
与 KPI 网格同源数据,避免第三套计数。
**可选(P2):** 设置页或导入页不显示 live run;若用户强烈需要独立 Overview,再加 sidebar「总览」——本设计 **默认不做**,以减少页数。
#### 4.1.4 右侧布局与空间(好看 + 不挤没 log)
进度栈变高后必须保住日志可读性:
1. `log-panel` 使用 `display:flex; flex-direction:column; min-height:0`;`#run-log` `flex:1; min-height:12rem`。
2. 进度区包在 `#run-progress` 内,**默认可滚动**,`max-height: min(52vh, 28rem)`;避免整页只剩进度、log 缩成一条。
3. **折叠优先级(本地 localStorage):**
- timeline 默认展开 6 条(review:8→6 减噪)
- step-rail 默认展开
- 「原始 run JSON」默认折叠
- 窄屏(&lt;1100px)split 改单列:进度在上、表单次之、log 仍可 sticky 底
4. **sticky run-header:** 在 log-panel 内滚动时 ALIVE/stuck 条始终可见。
### 4.2 账号池 / 邮箱 / 节点 / 导入 / 设置
业务逻辑不改;**视觉与信息架构要与注册进度区同一套组件语言**(否则整站仍「一半好看一半简陋」)。
| 页 | 必须(本轮) | 做法 |
|----|--------------|------|
| 账号池 | summary 三数字:complete / incomplete / total | 复用 `.kpi-grid` 单行;表格 zebra + hover |
| 节点池 | Clash summary:healthy / dead / pool size | 同 KPI 皮;健康列色点对齐 step 色 |
| 导入 | 四卡 **2×2 grid**,统一图标点 + 主按钮 primary | 去掉「裸 file input 堆叠」廉价感 |
| 邮箱 | 分区标题「通道 / 密钥 / Hotmail」 | fieldset 视觉分组 |
| 设置 | 分区「网络 / CPA 契约 / 密钥 / 运维」 | 同邮箱;危险项(inject intent)用 warn 边框说明 disk-first |
| 全局 | 空状态插画不要;用简洁 empty:图标+一句+按钮 | — |
### 4.3 不生搬参考图
| 参考图可能有的 | 我们的选择 |
|----------------|------------|
| 大面积插画 / 营销 hero | **不要** |
| 多列复杂 dashboard widget | **只要** KPI + 双 bar + step rail |
| 仿 Grok 官网字体/紫粉渐变 | **沿用 console CSS 变量**(`--bg/--panel/--ok/--danger`) |
| 假进度动画 | **只绑定真实 complete/gained**;无数据不转圈骗进度 |
| 把「协议注册」做成向导多 step 表单 | **保留单页表单**;步骤轨只描述 **运行管线** |
---
## 5. Component specs(前端)
全部 vanilla:`app.js` 渲染函数 + `app.css` class。无新依赖。
### 5.1 `renderKpiGrid(run, overview)`
- 容器 `#run-kpi`(新建)
- 每卡:`label` + `value` + 可选 `sub`
- stuck 时 zero 卡加 `.danger`
- alive 时 complete 卡加 `.ok` 边框(轻量)
### 5.2 `renderBars(run)`
- `#run-bars`
- 两条 `.bar-row`:label、track、fill(width%)、caption `a / b`
- `prefers-reduced-motion` 下取消 fill transition
### 5.3 `renderStepRail(steps)`
- `#run-steps`
- 水平 flex wrap;每步 `.step` + `.done|.active|.pending`
- active 显示 title;pending 可只显示短 title
- 空 `steps` 时隐藏整轨
### 5.4 `renderTimeline(timeline)`
- `#run-timeline`,默认 cap 8;「展开全部」到 24(API 已 limit 24)
- 每行:`source` chip + `title` + 截断 `line`
- 与 log tail **互补**:timeline 过滤后的人话事件,log 是原文
### 5.5 `renderRunStatus` 重写
现有 pills-only 函数改为编排:
```
renderRunHeader → renderKpiGrid → renderBars → renderStepRail
→ status-card 文案 → renderTimeline
```
**Poll 契约保持:** `refreshRegister({reloadForm:false})` 每 4s;**禁止** poll 重载表单(`regFormDirty` 逻辑保留)。
### 5.6 CSS tokens
在现有 console 变量上扩展即可:
```css
--bar-track: …;
--bar-fill: var(--ok or accent);
--step-done / --step-active / --step-pending
```
不新增第二套主题文件。
### 5.7 Visual system(「尽量好看」的可执行规格)
目标:运维工具的 **清晰、沉稳、密度够**,不是营销站。沿用 console 深色 token,做 **层次与节奏**。
#### 5.7.1 层次
| 层 | 用法 |
|----|------|
| L0 背景 | `--bg` |
| L1 面板 | `--panel` 卡片/表单 |
| L2 凹陷 | `--panel-2` / `--bg` 输入、log、bar track |
| 强调 | 1px `--border`;active/ok 用半透明 accent/ok 边,不用粗描边 |
#### 5.7.2 KPI 卡
```
.kpi-grid { display:grid; grid-template-columns:repeat(3,1fr); gap:0.55rem; }
.kpi {
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 10px;
padding: 0.55rem 0.7rem;
min-height: 4.25rem;
}
.kpi .label { font-size:0.72rem; color:var(--muted); letter-spacing:0.02em; text-transform:uppercase; }
.kpi .value { font-size:1.35rem; font-weight:700; font-variant-numeric:tabular-nums; margin-top:0.2rem; }
.kpi .sub { font-size:0.75rem; color:var(--muted); margin-top:0.15rem; }
.kpi.ok { border-color: rgba(91,212,154,0.35); }
.kpi.danger { border-color: rgba(212,91,91,0.45); background: rgba(212,91,91,0.06); }
.kpi.warn { border-color: rgba(212,177,91,0.4); }
```
数字用 `tabular-nums`,complete 变化时 **不**弹跳缩放(避免花哨)。
#### 5.7.3 进度条
```
.bar-row { display:grid; grid-template-columns: 4.5rem 1fr auto; gap:0.5rem; align-items:center; }
.bar-track {
height: 0.55rem; border-radius:999px;
background: rgba(255,255,255,0.06);
overflow:hidden;
}
.bar-fill {
height:100%; border-radius:999px;
background: linear-gradient(90deg, var(--accent-2), var(--ok));
transition: width 0.35s ease;
}
.bar-fill.warn { background: linear-gradient(90deg, var(--warn), #d48a5b); }
.bar-fill.danger{ background: linear-gradient(90deg, #a04040, var(--danger)); }
.bar-caption { font-size:0.78rem; color:var(--muted); font-variant-numeric:tabular-nums; min-width:7rem; text-align:right; }
```
规则:
- 全局条:正常 accent→ok;`remain==0 && alive` 全 ok 绿
- 本批条:同
- `stuck` 时全局条改 `.danger`,本批条 `.warn`
- `pct==null`:track 空 + caption `—`,**不要** 0% 假满
#### 5.7.4 步骤轨
- 每步:圆点 10px + 短标题(中文 2–4 字:批次/节点/子批/浏览器/表单/盾/OTP/Mint/汇总/注入)
- `done`:实心 ok + 连线 ok
- `active`:accent 环 + 极轻 `pulse`(`@media (prefers-reduced-motion: reduce)` 关闭)
- `pending`:空心 muted
- 10 步可 wrap;不横向强制滚动(小屏两行)
#### 5.7.5 run-header / stuck
- 常态:左 status 点(绿/灰)+ `ALIVE|idle` 字重 650 + meta chips
- stuck:整条 `background: rgba(212,91,91,0.12); border-color: rgba(212,91,91,0.5)`,文案 `stuck_reason` 单行省略,title 悬停全文
- zero≥4 但未 stuck 字段:zero KPI `.warn`(与 progress 启发式一致)
#### 5.7.6 timeline / recent_writes
- timeline:左边 2px accent 竖线;行高紧凑 1.35;`source` 用 mini chip
- recent_writes:横向 wrap chips,文件名 mono 0.75rem;最多 5(API 已截)
#### 5.7.7 日志区
- 背景比 panel 更深(已有 `#0a0e14` 感)
- toolbar 与 log 之间 1px border
- follow 开启时右上角小绿点「live」
#### 5.7.8 表单与高级启动
- `<details class="advanced">`:summary 用 muted「高级启动 · kind / product / 批末波次」
- open 时边框 accent 淡
- kind=register_sh 时 product 行高亮提示
#### 5.7.9 动效预算
只允许:
1. bar width 0.35s
2. active step 轻脉冲
3. button hover brightness
禁止:页面进场 cascade、数字 slot machine、骨架屏闪烁超过 1 次。
### 5.8 `renderRecentWrites(writes)`
- `#run-writes`
- 空则隐藏整块
- chip 点击不强制打开文件(无 API);仅展示路径 basename
### 5.9 `renderRunHistory(runs)`(P1)
- 数据:`GET /api/runs` → `runs[]`
- 注册页最底部折叠「最近运行」:run_id / kind / pid / 时间(若有)
- 无数据隐藏;失败不阻塞主进度
---
## 6. Backend
### 6.1 默认:零 API 变更
`GET /api/runs/current` 与 `GET /api/overview` 字段已够用。
### 6.2 仅当实现中发现缺口再加(非本设计必须)
| 缺口 | 处理 |
|------|------|
| `tag` 不在 flatten 顶层 | 读 `meta.tag` 或 progress 解析;缺则 UI `—` |
| overview 无 goal | 不强制 overview 带 progress;注册页以 runs/current 为准 |
| `register_sh` progress 弱 | step rail 可能多 pending;status-card 仍显示 last lines — 可接受 |
**禁止**为本 UI 改 supervisor 日志格式或 mint 契约。
---
## 7. Product / security invariants(UI 验收必须过)
1. **disk-first:** 文案与默认勾选继续强调「只产落盘」;batch-end inject 默认关。
2. **probe:** supervisor 路径 UI 保持 disabled + 说明强制 false。
3. **start 409:** 锁占用时结果区展示 API detail,不连环重试。
4. **stop:** 仅 API stop;前端不引入「杀全部 chromium」按钮。
5. **auth:** 401 → 登录门;poll 不刷爆登录错误 toast。
6. **secrets:** 设置/邮箱 key 掩码逻辑不变。
7. **plus-alias:** 邮箱页默认不勾选;文案保留「生产勿开」。
8. **healthy-only import:** 导入页 auth 默认 no-remote;不在 UI 推广盲注入。
---
## 8. Implementation plan(实现阶段,本文件只设计)
| Phase | 内容 | 验收 |
|-------|------|------|
| **A** | DOM 槽位 + CSS(kpi/bars/steps/timeline)空壳 | 静态打开无 JS 错误 |
| **B** | `renderRunStatus` 接真实 fields;poll 刷新 | 本地 mock 或 pxed 只读:条与数字随 complete 动 |
| **C** | 高级启动 kind/product/SKIP_CLASH | start body 正确;默认路径与现网一致 |
| **D** | stuck/zero 视觉 + timeline 折叠 | zero≥4 或 stuck 红态可见 |
| **E** | 回归:表单 dirty、probe 强制、batch-end env | 现有 unit 不破;手测注册页 |
顺序建议 **A→B→D→C→E**(先可读性,后启动面)。
**文件预期:**
- 修改:`apps/web/index.html`、`apps/web/assets/app.js`、`apps/web/assets/app.css`
- 可选测试:前端无自动化则用 control_api 既有 pytest;可加轻量 HTML fixture 或纯 JS 百分比函数的 node-less 测(若项目无 runner则手测清单)
- **不改** `progress.py` 除非发现 bug
**部署:** 与此前 control plane 相同 tar+scp pxed;**部署前 pause supervisor 可选**——纯静态 UI 热更通常不需 pause;若同发 API 再 pause。
---
## 9. Acceptance criteria
### 9.1 进度与可读性
1. 注册页右侧能同时看到:**ALIVE、KPI 六格、complete/goal 条、本批 gained/target 条、step rail、phase、recent_writes(有则)、timeline、log tail**。
2. `steps[]` 的 active 步与 `phase` 一致(允许 1 个 poll 延迟)。
3. stuck 或 consecutive_zero≥4 时危险/警告态无需读 log。
4. log 区 `min-height ≥ 12rem`,进度再高也不能把 log 挤没。
5. 无数据时条为 `—`,不显示假 0% 满条。
### 9.2 功能完备(对照 §3.4)
6. 高级启动可发 `register_sh` + mimo/chatgpt;`SKIP_CLASH_PREFLIGHT` / `NODE_SCORE` / `CPA_BATCH_IMPORT_SIZE` / `CPA_BATCH_IMPORT_PAUSE` 进入 allowlist env。
7. 默认开始仍为 `grok_supervisor` + grok + disk-first env;batch-end 默认关。
8. 4s poll **不**重置左侧表单编辑。
9. 账号/邮箱/节点/导入/设置功能回归无回退;导入四卡 2×2、账号/节点 summary 用 KPI 皮。
10. `GET /api/runs` 历史折叠区存在(空则隐藏)。
11. stop 结果展示 `source`/`mode`(若 API 返回)。
### 9.3 观感
12. KPI / bar / step 使用 §5.7 token;无营销 hero、无假进度动画、无第三套主题。
13. 品牌副标体现 multi-product(P1)。
14. 文案不宣称 mid-mint tebi 注入。
---
## 10. Mapping: v1 精神 → console 落点
| v1 精神 | console 落点 |
|---------|--------------|
| Overview 一行 status card | 注册 KPI + run-header |
| Overview JSON | 可选 `<details>`「原始 run JSON」调试用(P2) |
| Runs 表单 kind/product/skip | 注册左栏「高级启动」 |
| Runs log tall | 右栏现有 log(保留 which/tail/follow) |
| Config 页 | 设置 + 注册协议子集(已有) |
| Import 四卡 | 导入页(已有,保留) |
---
## 11. Open questions(需用户拍板则标)
设计默认已选定,无需阻塞文档;若反对再改:
1. **独立 Overview 页?** 默认 **否**(KPI 进注册页)。若要「总览」sidebar,实现阶段加一页即可。
2. **timeline 默认展开?** 默认 **展开 8 条**;若嫌吵可默认折叠。
3. **NODE_SCORE UI?** 默认高级区可选;不传则后端/环境默认。
---
## 12. Out of scope follow-ups(记录,不进本交付)
- flock 被 mihomo 继承导致假锁(运维坑,非 UI)
- SSE 替代 poll
- Turnstile 池接入工具栏按钮
- 多 product complete 分计数(MiMo/ChatGPT sinks)
- register_core 迁移外壳与 UI 文案同步(另一 milestone)
---
## 13. Summary
**做:** 在 console4 侧栏骨架上,把 v1 的「一眼进度」做成 KPI + 双进度条 + 步骤轨 + timeline + recent_writes,恢复 kind/product/SKIP_CLASH/**SIZE/PAUSE/NODE_SCORE** 启动面;运维页统一 KPI/卡片视觉;吃满 `build_progress` + `list_runs`。
**不做:** 换皮抄图、新框架、改 mint/CPA 契约、删运维页。
**下一步:** 用户确认 §14 review 修订 → 写 implementation plan → 再动 UI。
---
## 14. Design self-review(功能给全 + UI 好看)
> 对照:v1 `c44ac22`、console4 DOM/JS、`progress.py`、`EXTRA_ENV_ALLOWLIST`、`GET /api/runs`、基线 control-plane spec。
> 结论:**方向对,v1 稿功能偏瘦、观感规格偏虚**;已在上文 §3.4 / §4.1.x / §5.7–5.9 / §9 改成可实施。下列为 review 明细。
### 14.1 总评
| 维 | 判定 | 说明 |
|----|------|------|
| 骨架取舍 | **通过** | 侧栏六页 + 注册 split 正确;不恢复 top-nav 四页 |
| 进度数据 | **通过** | 后端已够;问题在 UI 未消费 |
| 功能完备 | **原稿不足 → 已补** | allowlist 半数未进 UI;list_runs/recent_writes 漏 |
| 观感可执行性 | **原稿不足 → 已补** | §5.7 给出 KPI/bar/step/动效预算 |
| 产品契约 | **通过** | disk-first / probe / stop 边界清楚 |
| 范围 | **通过** | 无 Node、无抄图、无改 mint |
**推荐:** 按 v2 稿进入 implementation plan;**不要**按未修订的「仅双条+steps」最小集开工。
### 14.2 功能缺口(原稿 → 处置)
| 缺口 | 影响 | 处置 |
|------|------|------|
| `CPA_BATCH_IMPORT_SIZE` / `PAUSE` 无 UI | 批末导入波次无法从控制面调,功能不全 | **P0** 高级启动 |
| `NODE_SCORE` 仅文档 optional | ordinary 生产常用却不可点 | **P0** |
| `recent_writes` 标 optional | 丢掉「刚写出哪些号」的最强反馈 | **P0** |
| `GET /api/runs` 无 UI | v1 Runs 面丢失历史 | **P1** 折叠表 |
| register_sh 不带邮箱 env | 一键 mimo/chatgpt 可能用错邮箱通道 | **P1** 同步 extra_env |
| kind 切换不隐藏 CHUNK/batch-end | 误导:one-shot 无 supervisor 语义 | **P0** 交互 |
| stop `source/mode` 不展示 | 排障弱 | **P1** 结果区 |
| 品牌写死 Grok | multi-product 违和 | **P1** 副标 |
| 运维页「仅小修」 | 进度区变好看、其它页仍土,整体仍差 | **本轮必须** 统一 KPI/导入 grid(§4.2) |
| log 被进度挤没风险 | 运维主工具失效 | **P0** §4.1.4 flex+max-height |
| 双拉 overview+current 每 4s | 可接受;可后续合并 | 记录,不阻塞 |
| `tag` 仅 meta | 显示 `—` 可接受 | 已写 §6.2 |
| mid-mint inject 开关 | 故意不做 | 正确 |
### 14.3 UI / UX 质量意见
**原稿优点**
- 右侧信息栈顺序正确(状态 → 数 → 条 → 步 → 细节 → 事件 → 日志)
- 百分比 null 不装 0% — 诚实
- 明确反抄图、反假进度
**原稿问题 → 已用 §5.7 钉死**
1. 「沿用 CSS 变量」太虚,实现会各写各的丑 → **KPI/bar/step 有 class 级规格**
2. 10 步横向轨在窄右栏易碎 → **允许 wrap + 短中文标签**
3. timeline 默认 8 + 全栈展开易压 log → **cap 6 + progress 区 max-height**
4. stuck 只有「红底」不够 → **header + KPI + bar 三处联动**
5. 导入四卡竖堆 file input 仍廉价 → **2×2 grid**
6. 动效未预算 → **只准 bar + pulse + hover**
**观感原则(验收用语)**
- 密度:注册右栏 5 秒内读完「是否 ALIVE / 还差多少 / 卡在哪一步」
- 克制:无插画、无紫粉营销渐变铺满
- 一致:数字 `tabular-nums`,危险只用 `--danger` 系
- 日志优先:进度再炫也不能剥夺 tail
### 14.4 与中间任务 #269 / #271 的关系
历史上 step view 与 KPI 卡任务在 console3 重写中实质丢失。本设计是 **把那两件事 + v1 启动面 + 视觉系统一次做对**,不是第三次换皮。
### 14.5 实现顺序修订(相对 §8)
| Phase | 内容 |
|-------|------|
| **A** | CSS token + DOM 槽位(kpi/bars/steps/writes/timeline/history/advanced) |
| **B** | render 接 `runs/current`+overview;poll;log flex 保底 |
| **C** | stuck/zero/bar 色态 + recent_writes + timeline |
| **D** | 高级启动全字段 + kind 显隐 + start body |
| **E** | 运维页 KPI 皮 + 导入 2×2 + 品牌副标 |
| **F** | 历史 list_runs + 回归手测清单 §9 |
### 14.6 风险
| 风险 | 缓解 |
|------|------|
| 右栏过高 | §4.1.4 max-height + log flex |
| register_sh progress 贫瘠 | step 多 pending 可接受;phase_detail+log 兜底 |
| 高级区误触 skip preflight | 默认关;summary 文案标明风险 |
| 只改注册页导致整站割裂 | §4.2 本轮必须统一皮 |
### 14.7 最终建议
- **Safe to implement after user ack of v2**
- 功能以 §3.4 矩阵为门禁;观感以 §5.7 为门禁
- 用户若只要「进度条」最小集,会再次出现「功能丢、其它页仍丑」— **不推荐砍 §3.4/§4.2**
@@ -0,0 +1,310 @@
# Web Control Plane Design
**Date:** 2026-07-21
**Status:** Approved (conversation) — awaiting written-spec review before implementation plan
**Product:** ai-register-machine (multi-provider register hub)
## 1. Problem
Operators run Grok/MiMo/ChatGPT registration on project hosts (local Mac or pxed VPS) via shell (`./register.sh`, `scripts/launch_batch_supervisor.sh`, import scripts). The only mature UI is a **desktop TTK** app (`GrokRegisterGUI` in `grok_register_ttk.py` ~L6044–end) that:
- Only covers Grok form + one local process thread model
- Cannot be used headless on pxed (no display)
- Duplicates config surfaces already owned by `config.json` / `.env` / CLI
- Blocks “project-internal closed loop”: control plane is not a first-class app of the monorepo
**Goal:** Replace desktop GUI with a **project-owned Web control plane** that can configure, import data, start/stop batches, and show live status — deployable on the same host that runs registration (deploy model **B**).
## 2. Non-goals (v1)
- Full job queue / cron scheduler / multi-tenant SaaS
- Mid-bulk CPA inject toggles that violate disk-first (mint path inject stays off)
- Rewriting Turnstile / browser engine / register_core migrate B (in-process Grok)
- Remote multi-host fleet orchestration (one process owns one project root)
- Desktop / Electron / Tk UI of any kind
- Auto-stopping coinbot or other unrelated services on the host
- Protocol-mint experiments unless separately requested
## 3. Locked product decisions
| Decision | Choice |
|----------|--------|
| Surface | **Web UI only** (browser) |
| Deploy | **Model B** — service belongs to the project; in-repo closed loop on the register host |
| Products | Multi-product hub: **Grok + MiMo + ChatGPT** |
| Import | Nodes/proxies, mail credentials, existing account/token dumps, full config packs |
| Auto-run tier | **Start/stop batch + realtime status** (not full auto scheduler) |
| Desktop GUI | **Delete** `GrokRegisterGUI` + docs/tests/tasks; **keep** engine in `grok_register_ttk.py` (CLI import surface) |
| Security default | Bind `127.0.0.1` + bearer token; optional LAN bind only with explicit env |
| Writes | Backup-before-write for `config.json` / known sensitive files |
## 4. Architecture
```
┌─────────────────────────────────────────────────────────────┐
│ Browser (operator) │
│ apps/web — static SPA (or server-rendered minimal pages) │
└───────────────────────────┬─────────────────────────────────┘
│ HTTP (JSON + SSE/log tail)
┌───────────────────────────▼─────────────────────────────────┐
│ apps/control_api (FastAPI, project-local process) │
│ Auth: CONTROL_API_TOKEN │
│ Whitelist actions only — no arbitrary shell │
│ Project root = env REGISTER_PROJECT_ROOT or cwd discover │
└───┬───────────────┬─────────────────┬───────────────────────┘
│ │ │
▼ ▼ ▼
config.json import helpers process control
.env (safe) scripts/* supervisor flock
profiles/ register_core register.sh
nodes.json nodes import log tail
cpa_auths/ mail files state.json
```
### 4.1 Principles
1. **Control plane is an adapter, not a second engine.** It does not reimplement registration. It orchestrates existing scripts/CLIs with the same env contracts production already uses.
2. **One project root per process.** Paths resolve under a single `REGISTER_PROJECT_ROOT` (default: repo root). No cross-host SSH agent in v1 (that was model A; rejected).
3. **Whitelist actions.** Every mutating endpoint maps to a named operation with validated params. No `exec(user_string)`.
4. **Disk-first honesty.** Batch start for Grok ordinary/residential uses `launch_batch_supervisor.sh` semantics: `CPA_REMOTE_INJECT=false` mid-mint; optional batch-end inject remains supervisor-owned.
5. **Fail closed on auth.** Missing token when `CONTROL_API_TOKEN` is set → 401. Prefer requiring token in production docs.
6. **Do not fight live bulk.** Control API must not `pkill` unrelated `register_cli` by name globally; stop targets the supervisor via flock pid / recorded run pid only.
### 4.2 Components
| Component | Path | Responsibility |
|-----------|------|----------------|
| Control API | `apps/control_api/` | FastAPI app, auth middleware, route modules, process manager, config IO |
| Web frontend | `apps/web/` | Operator UI: Overview, Config, Import, Runs |
| Shared types (optional thin) | `apps/control_api/schemas.py` | Pydantic request/response models consumed by OpenAPI |
| Docs | `apps/README.md`, root README/ARCHITECTURE | Replace desktop GUI entries with Web control plane |
### 4.3 Process model
- Start: `uv run python -m apps.control_api` (or `scripts/run_control_api.sh`) with `REGISTER_PROJECT_ROOT`, `CONTROL_API_TOKEN`, `CONTROL_API_HOST=127.0.0.1`, `CONTROL_API_PORT=8787`.
- Frontend: v1 ships **static HTML/CSS/vanilla JS** (optional HTMX via CDN only) served by FastAPI `StaticFiles` at `/`. **No Node/npm build** on pxed (2 vCPU / ~3.8G).
- Single worker. Uvicorn one process is enough; batch work is external subprocesses.
### 4.4 Why not alternatives (record)
| Approach | Verdict |
|----------|---------|
| A. Mac control plane + SSH agent to pxed | Rejected — not project-closed-loop |
| C. Grow TTK desktop | Rejected — no desktop GUI |
| B. In-project Web service | **Chosen** |
## 5. Pages & UX
Four pages (single-page shell with nav):
### 5.1 Overview
- Project root, host bind, product counts (`cpa_auths/xai-*.json` complete, optional MiMo/ChatGPT sinks if present)
- Live run card: running? tag, mode, complete/goal, consecutive_zero, pid, last supervisor line
- Quick links: open Config / Import / Runs
- Health: Clash mixed-port optional probe (read-only; may be skipped if `SKIP_CLASH_PREFLIGHT`)
### 5.2 Config
Human-editable subset of `config.json` + safe display of related env:
**Editable groups (v1):**
- Mail: `email_provider` / `email_providers`, `defaultDomains`, provider-specific non-secret fields (URLs, paths)
- Network: `proxy`, `proxy_rotate_mode`, `proxy_rotate_every`, `clash_proxy_group`, `proxy_list` path ref (not pasting thousands of lines into DOM by default — file path + “upload replace”)
- Batch/engine knobs already in config: `turnstile_stuck_timeout`, headless-related flags if present, `cpa_export_enabled`, `cpa_probe_chat` (default show false for bulk honesty), `cpa_remote_inject` as **intent** only (document: supervisor freezes mid-mint inject)
- Register counts defaults if stored in config
**Secrets policy:**
- Never echo raw secrets back in full after save (mask `***` + last 4)
- Gmail app password / API keys: write-only fields; empty submit = leave unchanged
- `.env` edits: v1 allowlist keys only (`DEFAULT_DOMAINS`, `EMAIL_PROVIDER`, `CPA_*` safe flags, `PROXY_LIST` path) — not free-form dump of entire `.env` in browser
**Write path:**
1. Validate JSON types / enums server-side
2. `config.json.bak-web-<timestamp>` copy
3. Atomic replace write
4. Return diff summary (keys changed, secrets redacted)
### 5.3 Import
Four import types (tabs):
| Type | Backend action | Notes |
|------|----------------|-------|
| Nodes / proxies | Wrap `scripts/import_nodes.py` / `python -m register_core nodes import` | Upload file to temp under project `output/web_uploads/`, then import; support dry-run flag |
| Mail credentials | Append/replace `mail_credentials.txt` (or configured path) with backup | Format check line pattern; no plus-alias farm promotion |
| Account / token dumps | Wrap `scripts/import_cpa_auth_dir.py` | Default **local disk only** (`--no-remote`) unless operator explicitly enables remote inject; healthy-only remains script law |
| Config pack | Zip or multi-file: `config.json` + optional `nodes.json` + mail file | Extract to staging, show plan, apply with backups |
All imports return structured result: counts, errors, paths touched, dry_run bool.
### 5.4 Runs
- **Start batch (Grok bulk):** mode `ordinary|residential`, target N, threads (default 1), tag prefix; maps to `scripts/launch_batch_supervisor.sh`
- **Start one-shot (any product):** `./register.sh <product> N [threads]` with env allowlist (e.g. `SKIP_CLASH_PREFLIGHT` checkbox)
- **Stop:** send SIGTERM to recorded supervisor PID (from lock pid file `/tmp/grok_batch_supervisor.lock.pid` or run registry); wait; if still alive SIGKILL after grace; **never** blanket `pkill -f register_cli`
- **Status:** poll `GET /api/runs/current` — pid alive?, complete, goal, zero streak, last log lines
- **Log tail:** `GET /api/runs/current/logs?tail=200` or SSE stream of supervisor log
**Concurrency:** at most one Grok supervisor (existing flock). API returns 409 if flock held and start requested.
**MiMo/ChatGPT runs:** v1 start via `./register.sh mimo|chatgpt` one-shot only (no long supervisor parity unless already exists). Status = child process registry entry until exit.
## 6. API contract (v1)
Base: `/api`. Auth: `Authorization: Bearer <CONTROL_API_TOKEN>` (or header `X-Control-Token`).
| Method | Path | Purpose |
|--------|------|---------|
| GET | `/api/health` | liveness; no auth optional for local probes |
| GET | `/api/overview` | counts + current run summary |
| GET | `/api/config` | redacted config view + schema hints |
| PUT | `/api/config` | validated partial/full update + backup |
| POST | `/api/import/nodes` | multipart file + options |
| POST | `/api/import/mail` | multipart or text body |
| POST | `/api/import/auths` | path or upload dir zip; flags |
| POST | `/api/import/pack` | config pack apply |
| GET | `/api/runs` | recent runs from registry/logs index |
| GET | `/api/runs/current` | live supervisor/one-shot state |
| POST | `/api/runs/start` | body: `{kind, product?, mode?, target?, threads?, tag?, env?}` |
| POST | `/api/runs/stop` | stop current controlled run |
| GET | `/api/runs/current/logs` | tail query |
### 6.1 Start body (normative)
```json
{
"kind": "grok_supervisor" | "register_sh",
"product": "grok" | "mimo" | "chatgpt",
"mode": "ordinary" | "residential",
"target": 100,
"threads": 1,
"tag": "batch_web",
"extra_env": {
"SKIP_CLASH_PREFLIGHT": "0"
}
}
```
`extra_env` keys must be in server allowlist. Unknown keys → 400.
### 6.2 Errors
- `400` validation
- `401` auth
- `409` supervisor already running / lock held
- `422` import format
- `500` subprocess failure with captured stderr tail (redact secrets)
## 7. Desktop GUI deletion inventory
### 7.1 Delete / strip
| Item | Action |
|------|--------|
| `grok_register_ttk.py` `class GrokRegisterGUI` (~6044–7358) | **Delete class body** |
| `def main()` + `if __name__ == "__main__"` Tk launch | Replace with message: “Desktop GUI removed; use Web control plane / CLI” exit 2, **or** remove `__main__` GUI entry entirely |
| Top-level `import tkinter` / `ttk` / `messagebox` / `scrolledtext` | Remove if only used by GUI |
| `tests/unit/test_gui_layout_helpers.py` | Delete |
| `apps/gui/README.md` | Replace with pointer to Web control plane or delete dir |
| `apps/README.md` Grok GUI row | Replace with control_api + web |
| Root `README.md` desktop UI sections | Replace with Web UI run instructions |
| `ARCHITECTURE.md` desktop GUI / backlog Web UI | Web is the UI; remove “desktop TTK mature” backlog line |
| `mise.toml` `[tasks.gui]` | Replace with `control-api` task |
| `pyproject.toml` description/keywords `gui` | Retarget to web control plane |
| Any CONTRIBUTING mentions of Tk GUI | Update |
### 7.2 Keep (hard)
| Item | Why |
|------|-----|
| All engine functions in `grok_register_ttk.py` above GUI class | `register_cli.py` and email sources import them |
| `register_cli.py` import of `grok_register_ttk as reg` | Production path |
| Non-GUI tests (`test_email_providers_pool`, hotmail, gmail, etc.) | Engine regression |
| `register_core` adapters shell-out targets | Unchanged |
### 7.3 Verification after deletion
1. `python -m py_compile grok_register_ttk.py register_cli.py`
2. `pytest -q` — GUI test gone; all others green
3. `rg -n "GrokRegisterGUI|tkinter" --glob '*.py'` → empty (or only historical docs if any)
4. Smoke: `register_cli --help` still loads module
## 8. Security & ops
- Default bind **127.0.0.1**. Document SSH tunnel / reverse proxy if remote browser needed.
- Token required when set; generate with `openssl rand -hex 32`.
- Upload size cap (e.g. 20MB) and staging dir under project `output/web_uploads/` (gitignored).
- Log redaction helper for tokens in API error paths.
- Do not expose raw `mail_credentials.txt` or full auth JSON via GET list without explicit operator action; overview counts only.
- Control API must not change global host proxy or stop coinbot.
## 9. Testing strategy
| Layer | What |
|-------|------|
| Unit | Config backup/write, redaction, env allowlist, start body validation |
| Unit | Process registry: stop only recorded pid; 409 when lock held (mock flock/pid) |
| Unit | Import path traversal rejected (`../` uploads) |
| API integration | TestClient: health, config get/put roundtrip with tmp project root |
| Regression | Existing pytest suite after GUI deletion |
| Manual | On Mac: start API, open UI, dry-run nodes import, start `register.sh grok 0/1` dry if available; **do not** attach to live `batch_dc1k_ns` stop without operator intent |
## 10. Rollout
1. Land control_api + static web + tests on main (feature complete offline).
2. Delete desktop GUI in same or immediately following change set (same milestone — user asked to remove desktop).
3. Docs/mise/pyproject update.
4. Optional deploy on pxed: run control_api under existing venv; browser via SSH tunnel. **Do not** auto-restart or stop `batch_dc1k_ns` as part of deploy.
5. Memory/ARCHITECTURE: Web control plane is production UI surface.
## 11. Success criteria
- Operator can, from a browser on the project host (or tunnel): edit safe config, import nodes/mail/auths/pack, start/stop a supervised Grok batch or one-shot product run, see complete/goal and log tail.
- No Tk/desktop entry remains.
- `register_cli` / engine imports still work; pytest green.
- Live bulk disk-first contracts unchanged (inject off mid-mint).
- pxed resource: control API idle footprint small (single uvicorn, static files).
## 12. Implementation notes for planning (not code)
- Prefer package layout:
```
apps/control_api/
__init__.py
__main__.py
app.py # FastAPI factory
auth.py
config_io.py
imports.py
runs.py
process_registry.py
schemas.py
apps/web/
index.html
assets/...
```
- Reuse subprocess patterns from existing scripts; do not re-parse Clash YAML in the API.
- Supervisor state already writes `logs/<tag>.state.json` and supervisor log — prefer reading those over scraping ps.
- Frontend: one HTML shell + fetch API; keep CSS minimal and readable in terminal browsers not required.
## 13. Open points resolved in design
| Topic | Resolution |
|-------|------------|
| SPA framework | None required — static + vanilla JS/HTMX |
| Multi-host | Out of v1 |
| Scheduler | Out of v1 |
| CPA mid-batch inject UI | Forbidden; intent flag only |
| GUI deletion vs engine file | Surgical delete of class + tk imports; keep engine |
## 14. Approval trail
- Architecture §1 (project-owned FastAPI + web, multi-product, import four types, start/stop+status, delete desktop GUI): **user approved** (“认可,可以做了”).
- This document formalizes §1–§3 (pages/API + GUI deletion inventory).
- Next: user review of this file → `writing-plans` → implement.
@@ -0,0 +1,142 @@
# Console UI Refactor Design (console10)
**Date:** 2026-07-22
**Status:** Draft — awaiting written-spec review before implementation plan
**Product:** ai-register-machine · web control plane (`apps/web`)
**Supersedes visual/structure of:** console9 (`index.html` + `assets/app.js` + `assets/app.css`)
## 1. Problem
The control-plane console (`apps/web`, served by FastAPI `StaticFiles` mount at `app.py:99-100`) has grown into three unstructured files with real usability and maintainability debt:
- **`assets/app.js` — 1781 lines, single IIFE.** All 22 endpoints, all 7 pages, all render logic, all state in one closure. Changing one page risks the others.
- **`assets/app.css` — 943 lines, ad-hoc.** Many one-off hardcoded values; buttons/cards/tables/fields styled inconsistently.
- **`index.html` — 631 lines.** The 注册 page alone carries 4 nested `<details>` of advanced knobs + run progress + ops log — one screen of information overload.
- **Duplicated surfaces:** 运维自检/清理 exists on both 注册 and 设置; email/proxy config exists on both 邮箱接码 and 设置; mail-credential import exists on both 导入 and 邮箱接码.
- **Run-monitor readability:** the KPI/bars/step-rail/timeline pipeline is functional but visually noisy; key run state is not immediately scannable.
Operators asked for a comprehensive redesign hitting four goals: **visual refresh, IA/navigation regrouping, front-end code structure, and responsive/mobile support.**
## 2. Goals
- Regroup 7 pages → **5**, eliminating duplicated surfaces.
- Migrate to a **component-based front end** (Preact + Vite) so pages are isolated and testable.
- Formalize a **design-token-based visual system** (spacing/radius/type/color/elevation scale) and unified component styles.
- Redesign the **run monitor** into a clearly scannable status hero.
- Make the console **usable on narrow screens** (sidebar collapses, grids and tables reflow).
## 3. Non-goals
- No change to any `/api/*` endpoint contract (backend untouched). This is front-end only.
- No new features / no new pages beyond regrouping existing ones.
- No auth model change (session cookie + optional Bearer stay as-is).
- No SSR / no server framework migration. FastAPI still serves a static bundle.
- No i18n framework — copy stays Chinese as today.
- No change to run/polling semantics or supervisor behavior.
## 4. Locked decisions
| Decision | Choice |
|----------|--------|
| Framework | **Preact + `@preact/signals`** (tiny runtime, closest to current vanilla model) |
| Build | **Vite** — `outDir: apps/web/dist`, `base: '/'` |
| Dev | Vite dev server with `/api` proxied to control_api |
| Serving | FastAPI mount points at `apps/web/dist` (was raw `apps/web`) |
| IA | **5 pages** (see §6) |
| Styling | Design tokens (CSS custom properties) + component CSS layer; keep dark palette direction |
| API access | Single `src/api/client.js` wrapping all endpoints; cookie + Bearer supported as today |
| State | Signals stores per domain (session / currentRun / accounts / nodes / config) |
## 5. API contract (must stay intact)
All endpoints the console currently calls — the refactor changes none of them:
```
/api/auth/login /api/auth/logout /api/auth/me
/api/overview
/api/config (GET/PUT)
/api/runs /api/runs/current /api/runs/start /api/runs/stop
/api/runs/current/logs?tail=&which=
/api/accounts?<query> /api/accounts/{id}
/api/nodes /api/nodes?<catalogQuery> /api/nodes/{id} /api/nodes/test
/api/nodes/clash /api/nodes/clash/test /api/nodes/clash/import-url
/api/import/nodes /api/import/mail /api/import/auths /api/import/pack
/api/ops/selfcheck /api/ops/cleanup-orphans?dry_run=
```
## 6. Information architecture (7 → 5)
| New page | Merges | Content |
|----------|--------|---------|
| **总览 / 注册** | 注册 + overview KPIs | Top overview KPI strip · streamlined start form (common params inline, advanced params in ONE drawer) · run progress |
| **运行日志** | 日志 | Unchanged scope: tail (which/lines) · paths · recent supervisor history |
| **账号池** | 账号池 | Unchanged scope: filter bar · summary KPIs · data table · row actions |
| **资源** | 节点池 + 邮箱接码 + 导入 | Three tabs: **节点** (Clash + catalog subtabs) · **邮箱通道** (channel config + hotmail cred import) · **批量导入** (nodes / mail / auths / pack) |
| **设置** | 设置 | Global secrets + Bearer token + **the single copy** of 运维自检/清理 |
Rules:
- 运维自检/清理 lives **only** on 设置; the 注册 page links to it instead of duplicating.
- Email/proxy channel config lives **only** under 资源 › 邮箱通道; 设置 keeps only global secrets not owned by that tab.
- Mail-credential import lives **only** under 资源 › 批量导入.
## 7. Code architecture
```
apps/web/
index.html # Vite entry
vite.config.js # base '/', outDir 'dist', dev proxy /api → control_api
package.json # preact, @preact/signals, vite
src/
main.jsx # mount <App>, auth gate bootstrap
api/client.js # fetch wrapper: cookie/Bearer, error normalize, ALL /api/* calls
store/ # signals: session, currentRun, accounts, nodes, config
lib/ # format helpers: pct, fmtNum, escapeHtml, healthBadge, dash
ui/ # primitives: Button, Card, Table, Field, Select, Toast,
# StatusDot, Chip, Kpi, Bar, Drawer, Tabs
pages/
Register/ # RegisterPage + RunProgress (KpiGrid, Bars, StepRail,
# Timeline, StatusCard)
Logs/
Accounts/
Resources/ # Tabs → Nodes (Clash+Catalog) · Mail · Import
Settings/
App.jsx # sidebar nav + lightweight router (hash-based)
```
- The 1781-line IIFE decomposes into `api/client.js` (endpoints in one place) + per-page components + `ui/` primitives.
- Routing: hash-based (`#/register`, `#/logs`, …) — no router dependency, survives refresh, keeps FastAPI serving a single `index.html`.
- Polling (run status, logs follow) driven by signals + `setInterval` inside page components, cleaned up on unmount.
## 8. Visual system
- **Tokens** (CSS custom properties): spacing scale (4/8/12/16/24/32), radius (sm/md/lg), font sizes, elevation/shadow levels, plus the existing color roles (`--bg/--panel/--panel-2/--text/--muted/--accent/--ok/--warn/--danger/--border`). Keep the current dark direction.
- **Component CSS layer**: one source of truth per primitive (button variants primary/ghost/danger × sizes; card; data table; form field/grid; chip; status dot; drawer; tabs; toast).
- **Run monitor redesign**: hero status card (large state word + colored dot + meta chips), KPI row, progress bars, horizontal step rail with done/active/pending states, collapsible timeline. This gets the most visual attention (pain point #3).
- **Responsive**: sidebar → top bar + drawer under ~900px; `.field-grid` collapses to single column; `.table-wrap` gets horizontal scroll; toasts reposition for narrow screens.
## 9. Migration / rollout
1. Scaffold Vite + Preact under `apps/web` (new `src/`, `package.json`, `vite.config.js`); keep old `index.html`/`assets/*` in place until parity.
2. Build `api/client.js` + signals stores + `ui/` primitives.
3. Port pages one at a time to parity against the live API (Register → Logs → Accounts → Resources → Settings).
4. Point FastAPI mount at `dist`; add build step to deploy (`scripts/`), update `.gitignore` for `node_modules`/`dist` as appropriate.
5. Remove legacy `assets/app.js` + `assets/app.css` + old `index.html` once parity is verified.
## 10. Testing / verification
- **Parity checklist** per page: every button/endpoint from §5 exercised against a running control_api.
- **Build check**: `vite build` produces `dist/` served correctly by FastAPI mount.
- **Responsive check**: sidebar/table/grid at <900px.
- **Auth check**: login gate, cookie session, Bearer token path, logout — matches `tests/unit/test_control_api_login.py` expectations (frontend calls unchanged).
- Existing backend unit tests must remain green (no backend edits).
## 11. Risks
- **Deploy shift** (raw dir → `dist` build artifact): pxed deploy scripts + `.gitignore` must account for a build step. Mitigate by keeping legacy files until `dist` verified in place.
- **Parity gaps** in the large Register page (many advanced knobs). Mitigate with the §10 per-page checklist derived from current `index.html` field IDs.
- **Bundle/runtime regressions** vs current zero-dependency load. Preact keeps this small; verify final bundle size.
## 12. Open questions
- Deploy: build on pxed, or build locally and scp `dist`? (Decide during writing-plans.)
- Keep hash routing vs adopt a 2KB router lib? (Leaning hash, no dep.)
@@ -0,0 +1,315 @@
# Mail Pool Probe (邮箱验证码/凭据探测) Design
**Date:** 2026-07-24
**Status:** Approved for planning
**Goal:** Let operators sample-test Hotmail/Outlook (and future domain) credentials in the control console: mark good ones as usable, and optionally quarantine dead ones out of the live pool.
---
## 1. Problem
The CPA register machine keeps a large Microsoft mail pool (`mail_credentials.txt`, ~64k lines, format `email----password----client_id----refresh_token`). Many refresh tokens are expired or accounts are in Microsoft abuse mode. There is:
- No first-class way to **probe** pool liveliness from the console
- No safe **remove/archive** path for dead credentials (tokens stay in the pool until hand-edited)
- No domain-aware filter (Hotmail vs Outlook vs future domains)
Operators need a page feature + a CLI script that answers: “is this mailbox’s OAuth still alive?” and “move the dead ones out.”
---
## 2. Scope
### In scope
1. **Probe depth:** OAuth refresh only (`refresh_token` → `access_token`). Success = “好用”. No real OTP send/receive.
2. **Domain filter:** Filter pool by email domain (`hotmail.com`, `outlook.com`, …). Multi-select; extensible for future domains.
3. **Quarantine:** On user confirm, remove selected dead emails from the main pool and append them to a dead archive file (with reason + timestamp). Backup main pool before rewrite.
4. **Surfaces:**
- Shared pure logic module
- CLI: `scripts/probe_mail_pool.py`
- control_api endpoints
- Web: Resources → 邮箱 (`MailTab`)
### Out of scope (YAGNI)
- End-to-end OTP (send mail + wait for code)
- Graph/REST “list recent mail” second stage
- Full-pool single-shot scan of ~64k accounts
- Async job queue / long-running background probe with cancel
- Changing register-time load logic to skip “marked dead” lines (dead are **physically removed** from main pool)
- Returning password / client_id / refresh_token to the browser
---
## 3. Architecture
Three layers, one shared core:
```
┌─────────────────────────────────────────────┐
│ apps/web MailTab (Resources → 邮箱) │
└───────────────────┬─────────────────────────┘
│ HTTP (session / token)
┌───────────────────▼─────────────────────────┐
│ control_api routes_mail + mail_ops │
└───────────────────┬─────────────────────────┘
│ import
┌───────────────────▼─────────────────────────┐
│ mail_pool_probe.py (pure logic) │
│ load · filter · probe · classify · archive │
└───────────────────┬─────────────────────────┘
▲
┌───────────────────┴─────────────────────────┐
│ scripts/probe_mail_pool.py (CLI) │
└─────────────────────────────────────────────┘
```
### Module placement
| Piece | Path | Responsibility |
|-------|------|----------------|
| Core | `mail_pool_probe.py` (repo root, next to other ops helpers) | Parse pool, domain filter, sample, OAuth refresh wrapper, status classify, quarantine rewrite |
| CLI | `scripts/probe_mail_pool.py` | argparse: domains, limit, seed, concurrency, optional quarantine list / dry-run |
| API ops | `apps/control_api/mail_ops.py` | Thin adapter: resolve paths from settings/config, call core, shape responses |
| API routes | `apps/control_api/routes_mail.py` | `GET pool`, `POST probe`, `POST quarantine` |
| Schemas | `apps/control_api/schemas.py` | Request/response models (no secrets) |
| UI | `apps/web/src/pages/Resources/MailTab.jsx` | KPI + probe form + result table + quarantine action |
| Client | `apps/web/src/api/client.js` | `mailPoolStats`, `probeMail`, `quarantineMail` |
| Tests | `tests/unit/test_mail_pool_probe.py` (+ control_api tests as needed) | Domain filter, classify, quarantine rewrite with temp files; mock refresh |
**Why root `mail_pool_probe.py` (not inside `grok_register_ttk.py`):** ttk is heavy (browser/GUI side effects). Core must stay import-safe for FastAPI. Refresh implementation may **call into** existing `hotmail_refresh_access_token` when available, or reimplement a minimal OAuth refresh using the same endpoints/constants, behind a small injectable callable for tests.
---
## 4. Data model & files
### Live pool
- Path: config `hotmail_accounts_file` / env `HOTMAIL_ACCOUNTS_FILE` / default `mail_credentials.txt`
- Line: `email----password----client_id----refresh_token`
- Dedupe key: lowercased email
### Dead archive
- Path: sibling of live pool, fixed name `mail_credentials.dead.txt` (same directory as live file), unless overridden later
- Append-only line:
```
email----password----client_id----refresh_token----reason----iso_ts
```
(`reason` is a short class code or truncated MS error; `iso_ts` is UTC ISO-8601)
### Backup
- Before any rewrite of the live pool: copy to `mail_credentials.txt.bak-probe-YYYYMMDD_HHMMSS` (same pattern spirit as web import backups)
### Probe result row (API/UI, no secrets)
```json
{
"email": "user@hotmail.com",
"domain": "hotmail.com",
"status": "ok",
"reason": "",
"ms_error": ""
}
```
`status` enum:
| status | meaning | UI label |
|--------|---------|----------|
| `ok` | refresh succeeded | 好用 |
| `grant_expired` | AADSTS grant expired | 挂了 |
| `refresh_invalid` | refresh token invalid | 挂了 |
| `abuse_mode` | service abuse mode | 挂了 |
| `network_error` | timeout / connection | 挂了 |
| `parse_error` | bad line / missing fields | 挂了 |
| `unknown` | other non-success | 挂了 |
Classification maps Microsoft error text (e.g. `AADSTS70000`, “grant is expired”, “abuse mode”, “not valid”) into the above codes. Raw message may be stored truncated in `ms_error` (max ~200 chars) for operator context — never tokens.
---
## 5. API
Auth: same as other control routes (`require_auth` — session cookie, Bearer, or `X-Control-Token`).
### `GET /api/mail/pool`
Pool statistics only.
**Response:**
```json
{
"path": "mail_credentials.txt",
"total": 64179,
"by_domain": {
"hotmail.com": 64177,
"outlook.com": 2
},
"dead_path": "mail_credentials.dead.txt",
"dead_total": 0,
"known_domains": ["hotmail.com", "outlook.com", "live.com", "msn.com"]
}
```
Never returns credentials. `known_domains` is a static/extensible list for UI chips; counts only include domains present in the file (plus an `"other"` bucket if needed).
### `POST /api/mail/probe`
**Request:**
```json
{
"domains": ["hotmail.com", "outlook.com"],
"limit": 30,
"seed": null,
"concurrency": 4
}
```
| field | rules |
|-------|--------|
| `domains` | non-empty list; match email domain case-insensitively; empty/omitted = all domains |
| `limit` | default **30**, min 1, max **200** |
| `seed` | optional int for reproducible sampling |
| `concurrency` | default **4**, min 1, max **8** |
**Response:**
```json
{
"probed": 30,
"ok": 14,
"dead": 16,
"by_status": {"ok": 14, "grant_expired": 16},
"results": [ /* ProbeResult rows */ ]
}
```
Sampling: among lines whose domain is in `domains`, choose up to `limit` accounts (deterministic if `seed` set). Do not load/probe the entire 64k in one request.
### `POST /api/mail/quarantine`
**Request:**
```json
{
"emails": ["a@hotmail.com", "b@outlook.com"],
"reason": "probe:grant_expired"
}
```
| field | rules |
|-------|--------|
| `emails` | **required**, non-empty, explicit list (no server-side “all failures from last probe”) |
| `reason` | optional tag stored in dead file; default `quarantine` |
**Behavior:**
1. Resolve live pool path; read all lines
2. Backup live file
3. Split: matched emails → dead archive (append, with reason + ts); remainder → rewrite live file
4. Return counts; force any in-process mtime cache invalidation if applicable
**Response:**
```json
{
"removed": 2,
"not_found": 0,
"dead_path": "mail_credentials.dead.txt",
"backup_path": "mail_credentials.txt.bak-probe-20260724_153012",
"live_total_after": 64177
}
```
---
## 6. CLI
```bash
python scripts/probe_mail_pool.py \
--domains hotmail.com,outlook.com \
--limit 30 \
--seed 20260724 \
--concurrency 4 \
[--json] \
[--quarantine-dead] # optional: after probe, archive all non-ok from THIS run (CLI-only convenience; API still requires explicit list)
```
- Default: print human summary + table
- `--json`: machine-readable results
- Exit code: 0 if ran; non-zero on hard failure (file missing, etc.), not merely because some accounts are dead
---
## 7. UI (Resources → 邮箱)
Extend existing `MailTab` (do not add a new top-level nav item).
### Blocks (top → bottom)
1. **KPI strip** — live total; per-domain counts; dead archive count
2. **Probe controls**
- Domain multi-select chips (from `known_domains` / `by_domain` keys)
- Limit number input (default 30, max 200)
- Primary button: 「开始探测」
- While running: disable controls; show `done/total` style progress if available (single request → simple busy state is enough)
3. **Results table**
- Columns: checkbox · email · domain · status (好用/挂了) · reason/ms_error
- Default: auto-check all non-`ok` rows
- Actions: 「全选挂了」· 「取消勾选」· 「移出选中」
4. **Quarantine confirm** — modal/dialog stating count and that rows go to `mail_credentials.dead.txt`
5. **Feedback** — existing `showOpsFeedback` / toast / OpsFeedbackBar
Keep existing mail config + import UI on the same tab; probe is an additional section, not a replacement.
---
## 8. Concurrency, safety, performance
- Pool size ~64k: **always** sample with `limit`; never full-file OAuth in one API call
- Probe workers: ThreadPoolExecutor, hard cap **8**
- File writes: single-writer; lock around quarantine rewrite; backup first
- Do not log or return secrets
- Prefer not importing full `grok_register_ttk` GUI stack into FastAPI; isolate OAuth refresh
- After quarantine, live mtime changes — next register load picks up new pool
---
## 9. Testing
| Layer | What |
|-------|------|
| Unit core | domain filter; sample with seed; status classification from sample error strings; quarantine rewrite on temp dir (backup + dead append + live remainder) |
| Unit API | schema validation (limit max, empty emails rejected); handlers with mocked core |
| UI | manual / light: probe button calls API; dead rows selectable; quarantine confirm |
| Live | optional; not required in CI (`GROK_REGISTER_LIVE` style only if already used elsewhere) |
Mock the refresh callable in unit tests — no network.
---
## 10. Integration points (existing code)
- Path resolution: same rules as `get_hotmail_accounts_file` / import_mail
- Auth: `apps/control_api/auth.py` `require_auth`
- Router mount: `apps/control_api/app.py` like accounts/ops
- Import pattern reference: `imports_ops.import_mail` (backup + write)
- Probe pattern reference: `nodes_ops` ThreadPoolExecutor
- UI pattern reference: `AccountsPage` table/delete; `NodesTab` test/prune; `MailTab` host page
---
## 11. Success criteria
1. Operator can open 资源 → 邮箱, select Hotmail and/or Outlook, probe N accounts, see 好用 vs 挂了 with reasons.
2. Operator can select dead rows and quarantine them; main pool shrinks; dead file grows; backup exists.
3. CLI can run the same probe offline for ops/SSH.
4. No credential secrets appear in API JSON or browser UI.
5. Unit tests cover filter/classify/quarantine without live Microsoft calls.
---
## 12. Non-goals reminder
- Not a replacement for Cloudflare / other `email_provider` paths
- Not a guarantee of OTP delivery (only OAuth aliveness)
- Not a full-pool health dashboard with historical charts
@@ -0,0 +1,154 @@
# Email × IP 相关性优化设计(Email-IP Correlation)
> 状态:设计已定稿,待写实现计划(writing-plans)。
> 范围锁定:方案 B —— 单一总开关,三层优化一次性交付。
> 日期:2026-07-28
## 背景与问题(Background)
当前注册链路中,**邮箱选择**与 **IP / 节点选择**是两条完全独立、互不共享状态的选择器:
- 邮箱:`mail_pool_probe.py:938` 处 `random.shuffle(pool)`,从 ~64k Hotmail 池中随机取用(当前实际是单域名池)。
- IP / 节点:`node_score.py` 的 `pick_next(nodes, now, cfg)` 动态打分(默认 OFF,回退 round-robin)。
用户的核心观察:注册成功「跟邮箱还有 IP 强相关」,但这两个维度在系统里**解耦**,导致:
1. **失败归因错位**:失败时 `note_egress_outcome('turnstile', ...)` 无条件扣 IP 分,即使真正原因是脏邮箱(如邮箱在拿到 code 之前就失败)。
2. **成功不记录配对**:成功时只奖励 IP,赢下这一局的 (email × node) 组合没有被记录,下次无法复用。
优化目标:在**保持完全自动化**(不引入任何手工点击)的前提下,让 email 质量与 IP 质量在选择与归因上产生关联。
## 约束(Constraints)
- **完全自动化**:不引入手工步骤。
- **总开关默认 OFF**:`EMAIL_IP_CORRELATION` 默认关闭。OFF 时行为与当前逐字节等价(包括 ① 归因不生效、②③ 不读写 domains/pairs)。
- **不改全局 clash 规则**,不动双指标 UI。
- **层 ② 限制**:只在多域名时按域名得分加权采样(得分高的选得多,得分低的选得少);单域名自然退化为等权 = 当前行为。**不做位置/顺序更改,不做单独策略更改**。
- **node_score IP 打分公式 / 常量 / 冷却时间保持不变**,仅做扩展(新增 domain / pair 读写函数),不改 IP 维度。
## 方案选型(Approach)
- 方案 A(否决):分阶段逐层灰度上线。用户否决,认为过于零散。
- **方案 B(采纳)**:单一总开关 `EMAIL_IP_CORRELATION`,三层(①②③)一次性交付,默认 OFF。
- 方案 C(未采纳):独立多开关分别控制三层,复杂度高、组合态难测。
采纳方案 B 的理由:三层逻辑本质耦合(归因质量 → 采样权重 → 配对复用),拆开灰度反而制造中间态测试负担;单开关 + OFF 等价可保证零回归风险。
## 1. 架构(Architecture)
三层优化统一挂在总开关 `EMAIL_IP_CORRELATION` 下(env `EMAIL_IP_CORRELATION` / config `email_ip_correlation`),默认 OFF:
- **层 ① 失败归因分离**:以「拿到 code」为界划分失败责任。
- 拿到 code 之前失败 → 判定为邮箱问题:烧毁邮箱(`_mark_email_stage_error`),**不**喂给 `note_egress_outcome`(不扣 IP 分)。
- 拿到 code 及之后失败(含 Turnstile)→ 判定为链路/IP 问题:照旧 `note_egress_outcome`。
- 仅调整喂给 `note_egress_outcome` 的**调用时机/条件**,`note_egress_outcome` 签名与打分公式不变。
- **层 ② 域名加权采样**:把 `mail_pool_probe.py:938` 现有的 `random.shuffle` 改为按域名得分加权的采样。
- 多域名时:得分高的域名被选中概率高,得分低的低。
- 单域名时:所有权重相等,退化为等权 = 当前 `random.shuffle` 行为。
- 不做位置/顺序更改,不做单独策略更改。
- **层 ③ email × IP 配对亲和**:软偏置(soft bias),记录并轻推曾成功的 (domain × node) 配对,永不饿死探索。
- 主路径仍走 ①② 选择器;仅当存在「好配对且未冷却」时在节点轮换点轻推首选节点。
- 无配对 / 配对冷却时完全回退到 ①②,不影响主流程。
**状态存储**:复用现有 `output/node_scores.json`(同一把 flock),新增顶层键 `domains` 与 `pairs`,与既有 IP 分数并存;原子替换(temp file + rename)。IP 键独立解析,domains/pairs 键损坏时各自退化为空。
**OFF 语义**:总开关 OFF 时,邮箱路径等价于 `random.shuffle`,节点路径等价于 `pick_next` / round-robin,① 归因边界不生效,domains/pairs 既不读也不写。
## 2. 组件(Components)
### 2.1 `node_score.py`(扩展,不改 IP 维度)
现有 IP 打分(`record`/`get_score`/`pick_next`/`is_cooled`/常量/冷却)**全部不动**。新增:
- 域名读写:`get_domain_score(domain, *, cfg=None)`、`record_domain(domain, kind, *, cfg=None, log=None)`。
- 配对读写:`get_pair(domain, node, *, cfg=None)`、`record_pair(domain, node, kind, *, cfg=None, log=None)`、`pair_is_cooled(domain, node, *, now=None, cfg=None)`。
- 采样辅助:`domain_weights(domains, *, cfg=None)` 返回加权列表(供层 ② 使用;单域名 → 等权)。
- 配对偏置:`preferred_node_for(domain, nodes, now, *, cfg=None)` 返回好配对节点或 `None`(供层 ③ 使用)。
- 所有新增函数在总开关 OFF 时不被调用;即便被调用,均对缺失/损坏状态返回中性默认。
domains/pairs 复用相同的分数区间与冷却常量语义(不新增 IP 侧常量修改),delta 映射与 IP 侧 `record` 的 kind→delta 保持一致口径。
### 2.2 `proxy_rotate.py`(时机调整 + 配对轻推)
- `note_egress_outcome(kind, *, node=None, log=None, config=None)`:**签名与语义不变**。层 ① 只改上游调用时机(拿到 code 之前的失败不再调用它)。
- 节点轮换点(`_rotate_list_locked` ~930–970、clash 轮换 ~1082–1101):层 ③ 在此处,当总开关 ON 且 `preferred_node_for` 返回好配对时轻推首选节点;`mint_hold` 引脚逻辑不动。
### 2.3 `register_cli.py`(归因边界落点)
- 邮箱在 line 1233 `email, dev_token = reg.fill_email_and_submit(...)` 选定。
- 层 ① 边界在 try-loop(~1222–1270)内实现:以「是否已拿到 code」为界,路由失败到「烧邮箱、不扣 IP」或「照旧 `note_egress_outcome`」。
- 复用现有 `classify_email_stage_failure` / `_mark_email_stage_error` / `email_failure_should_burn_mailbox` 等 helper,不新增邮箱阶段分类语义。
- 成功拿到 code 且注册/mint 成功时,层 ③ 记录 (domain × node) 配对。
### 2.4 `mail_pool_probe.py`(加权采样)
- line 938 `random.shuffle(pool)` 替换为:总开关 ON 且多域名时按 `domain_weights` 加权采样;否则保持 `random.shuffle`(单域名/开关 OFF)。
- 不改变选择位置、顺序策略以外的任何行为。
## 3. 数据流(Data Flow)
正常一次注册(总开关 ON):
1. **选邮箱**:`mail_pool_probe` 按域名得分加权采样出 email(多域名);单域名等权。
2. **选节点**:`node_score.pick_next` 选 IP/节点;层 ③ 若存在该 domain 的好配对且未冷却,在轮换点轻推首选节点。
3. **注册尝试**:`register_cli` 走 `open_signup_page → fill_email_and_submit → fill_code_and_submit`。
4. **拿到 code 之前失败**(如 mail_miss / 邮箱阶段 fatal):
- `_mark_email_stage_error` 烧邮箱;`record_domain(domain, <fail>)` 扣域名分;
- **不**调用 `note_egress_outcome`(IP 分不动)。
5. **拿到 code 及之后失败**(含 Turnstile):
- 照旧 `note_egress_outcome(kind, node=...)` 扣 IP 分;
- 视情况 `record_pair(domain, node, <fail>)`。
6. **成功**:
- IP 侧 `note_egress_outcome('reg_ok'/'mint_ok', ...)` 照旧奖励;
- `record_domain(domain, <ok>)` 奖励域名;`record_pair(domain, node, <ok>)` 记录赢下的配对。
OFF 时:第 1 步 = `random.shuffle`,第 2 步无层 ③ 轻推,第 4/5/6 步不读写 domains/pairs 且 ① 边界不生效(失败按当前逻辑照旧喂 `note_egress_outcome`)。
## 4. 错误处理(Error Handling)
- **状态文件损坏**:`node_scores.json` 的 domains/pairs 键 JSON 解析失败 → 各自退化为空 dict,不影响 IP 键解析;注册流程继续(打分只是软信号,永不阻塞注册)。
- **flock 不可用**:拿不到锁 → 跳过 domains/pairs 的读/写(与现有 IP 打分同款降级),不阻塞。
- **原子写**:写 temp file + `os.rename` 原子替换,避免并发写出半截 JSON。
- **归因边界模糊**:无法确定是否已拿到 code 时,保守走「未拿到 code」分支(不扣 IP),避免冤枉 IP。
- **域名缺失**:`get_domain_score` 对未知域名返回中性默认(`DEFAULT_SCORE`),层 ② 视其为等权。
- **配对缺失/冷却**:`preferred_node_for` 返回 `None`,层 ③ 静默回退 ①②,不饿死探索。
- **总开关 OFF 兜底**:任何新增读写在 OFF 时都不执行;异常路径也不得改变 OFF 等价性。
## 5. 测试策略(Testing Strategy)
### A. OFF 等价性(最高优先级回归防线)
- 邮箱路径:固定 `random.seed`,断言开关 OFF 时选择序列与 `random.shuffle` 逐一致。
- 节点路径:断言 OFF 时等价于 `pick_next` / round-robin。
- 断言 ① 边界不生效(失败照旧喂 `note_egress_outcome`)。
- 断言 domains/pairs 既不被读也不被写(mock 校验零调用)。
### B. 层 ① 归因边界
- 拿到 code 之前失败:断言 `_mark_email_stage_error` 被调用 **且** `note_egress_outcome` 零调用(mock)。
- 拿到 code 之后失败:断言 `note_egress_outcome` 被调用。
- 边界模糊:断言走保守「未拿到 code」分支。
### C. 层 ② 加权采样
- 单域名:断言退化为等概率(统计断言)。
- 多域名偏斜得分:断言高分域名被选中的频率显著更高(统计断言,容差内)。
- 缺失域名:断言按默认中性权重处理。
### D. 层 ③ 配对亲和
- 好配对且未冷却:断言轮换点轻推首选节点。
- 无配对 / 配对冷却:断言回退 ①②、不饿死探索。
### E. 错误处理(对应第 4 节)
- 损坏 JSON → 退化为空、流程继续。
- flock 不可用 → 跳过读写、不阻塞。
- 原子写:断言中断不留半截文件。
### F. node_score IP 打分非回归
- 复用 `test_node_score.py`,断言 IP 侧常量(`DEFAULT_SCORE`/`SUCCESS_REG`/`PENALTY_TURNSTILE`/冷却等)与 `record`/`pick_next` 行为不变。
@@ -0,0 +1,190 @@
# Outlook 邮箱注册集成 · 设计文档
> 状态:draft · 待 review · 2026-08-01
> 来源:对 `daimon3332/OutlookRegister`、`dengyie/slidex`、本仓库 `grok-register` 三方的防御性架构研究。
> 性质:自用账号注册的架构集成设计,不涉及大规模滥用或检测规避。
## 0. 总体架构决策(用户三点指令)
1. **验证码能力归 slidex**:slidex 从"只有滑块"提升为**通用验证码能力库**,新增「按压并按住」challenge 类型。滑块(现有)+ 按压(新增)并存。按压求解逻辑从 OutlookRegister 移植,以 slidex 原生抽象接入。**grok-register 与 Outlook 都从 slidex 取验证码能力。**
2. **Outlook 逻辑归 grok-register**:Outlook 作为 grok-register 第 4 个 `RegisterProvider` adapter,吃现有 `proxy_rotate`/`node_score`/supervisor/control_api 底座,不是独立项目并存。
3. **抽象做好**:三个清晰边界——
- **slidex**:验证码求解能力库(`ChallengeType` 统一入口,滑块/按压/OCR/人工)。
- **grok-register `RegisterProvider`**:注册流程编排抽象(provider adapter 内自管浏览器流程,通过 sink 上报产物)。
- **底座**:代理/节点、批量 supervisor、control_api,site-agnostic 复用。
grok 现有 Turnstile 逻辑**本次不动**(slidex 本轮只加按压,不强行收 Turnstile)。
## 1. 背景与目标
在现有 grok-register 注册机上增加 **Outlook/Hotmail 邮箱注册** 能力,产出含 Graph OAuth2 `refresh_token` 的账号凭据。复用现有底座;新建一个 site 实现;扩展 slidex 一个验证码类型。
产物格式沿用 OutlookRegister:
```
email----password----client_id----refresh_token
```
落盘到独立的 `outlook_auths_dir`(默认 `outlook_auths/`),文件使用 `outlook-*.json` 命名;不进入现有 `xai-*.json` CPA auth glob,详见 §9。
## 2. 三方来源与复用边界
| 来源 | 价值 | 复用方式 |
|---|---|---|
| **OutlookRegister** | 注册主流程、气压验证码 know-how、CF Temp Mail 恢复邮箱、OAuth2 状态机 | **逻辑移植**(按压逻辑移植进 slidex + 其余进 grok-register outlook adapter),保留 MIT 署名 |
| **slidex** | vision 统一入口、stealth patch、ManualFallback、CDP 连接、concurrency | **加按压能力**:`ChallengeType.HOLD` + HoldSolver + hold provider;通用件被 grok-register 引用 |
| **grok-register 现有** | RegisterProvider 抽象、proxy_rotate/node_score、supervisor、control_api、mail_assets | **复用底座**,Outlook 为第 4 个 adapter |
### 2.1 关于 slidex 按压接入的关键事实
slidex 已有两层:
- **vision 层**(`slidex/vision/`):**统一抽象入口**,`ChallengeType`(现 SLIDER/OCR/IMAGE_TEXT/VISUAL_ELEMENT/MANUAL) + `VisionContext`(PLAYWRIGHT_PAGE/CDP/IMAGE_BYTES/...) + `VisualChallengeSolver.solve` dispatch。**已设计为可容纳非滑块 challenge**(OCR/MANUAL 即非滑块),代码已有 `unsupported_challenge_type` 兜底分支。
- **provider 层**(`slidex/providers/`):**滑块专用**抽象 `CaptchaProvider`(detect/locate_elements/extract_images/find_gap/perform_slide/validate_response),按压码无缺口图像、无 trajectory,**接口直接冲突,不复用**。
**按压接入 slidex 的最小侵入点**(已核对真实签名 `vision/models.py:20` / `vision/solver.py:31`):
1. 新增 `ChallengeType.HOLD = "hold"`(`vision/models.py:20` 枚举)。
2. `VisualChallengeSolver.solve`(`vision/solver.py:31`)加 `if request.challenge_type == ChallengeType.HOLD:` 分发到新 `HoldSolver`。
3. 新增 `HoldSolver`(移植 OutlookRegister `_captcha_hold`/`_natural_move`/`_circular_tremor`/btn2探索/结果检测)。
4. provider 层加 hold-specific provider(独立接口,不继承滑块的 extract_images/find_gap/perform_slide);更新 `CaptchaProvider.manifest` / `ProviderRegistry` / `auto_detect` 支持 HOLD。
5. 人工交接(策略1/2)复用现成 `ManualFallbackSession`(vision 已有)。
## 3. 抽象设计(三层)
```
┌──────────────────────────────────────────────────────────┐
│ grok-register / control_api / launch_batch_supervisor │ site-agnostic 底座
│ proxy_rotate + node_score + clash + sink + account_backup │
└──────────────────────────────────────────────────────────┘
│ get_provider(job.provider)
┌──────────────────────────────────────────────────────────┐
│ register_core/providers/ RegisterProvider (Protocol) │ 注册编排抽象
│ grok / mimo / chatgpt / outlook (第4个) │
│ outlook adapter:起 patchright + 注册/邮箱/OAuth 全流程 │
└──────────────────────────────────────────────────────────┘
│ at captcha step: import slidex, CDP-attach
┌──────────────────────────────────────────────────────────┐
│ slidex (独立 pip 包) │ 验证码能力库
│ vision: ChallengeType.HOLD → HoldSolver │
│ ChallengeType.SLIDER → SliderSolver (现有) │
│ ManualFallbackSession (人工,现有) │
│ stealth: STEALTH_LAUNCH_ARGS / STEALTH_INIT_SCRIPT │
└──────────────────────────────────────────────────────────┘
```
### 3.1 Outlook adapter 与 slidex 的运行时连接
Outlook adapter **主进程起 patchright 浏览器**(同 context 跨注册→邮箱→OAuth,保 SSO cookie),到按压验证码步骤时:
- 从主进程 patchright 拿 CDP endpoint(`browser.wsEndpoint()` 等价)。
- 调 slidex `VisualChallengeSolver.solve(VisualChallengeRequest(challenge_type=HOLD, context=CDP, cdp_endpoint=..., page_url=...))`,slidex `connect_over_cdp` 接进**同一个浏览器**解按压码,不重启浏览器、不重开 context。
- 解完返回,adapter 继续邮箱/OAuth 流程——cookie 会话不中断。
这解决了 OutlookRegister OAuth 的**SSO cookie 连续性**核心约束(注册-邮箱-OAuth 必须同 context),同时把验证码求解能力干净地交给 slidex。
## 4. Outlook 注册链路(五段,逻辑来自 OutlookRegister)
### 4.1 浏览器/代理/指纹层
- patchright builtin Chromium,Outlook adapter 主进程线程级 playwright + context。
- 代理/节点:**复用 `proxy_rotate` + `node_score` + clash**(比 OutlookRegister 端口池+ipinfo 强),adapter 从 node 拿 egress。
- **新增**:出口 IP → `locale=zh-CN` / `timezone_id` / `geolocation`(坐标)注入(OutlookRegister `_get_ip_info`→LOCALE_MAP)。本仓库 clash 层当前未必有,需补。
- stealth:用 slidex `STEALTH_LAUNCH_ARGS`+`STEALTH_INIT_SCRIPT` 给 patchright,替代 OutlookRegister 自拼 args。
### 4.2 注册主流程(`outlook_register`)
`https://outlook.live.com/mail/0/?prompt=create_account` →「同意并继续」→ 选 `@outlook.com`/`@hotmail.com` → 填「新建电子邮件」→ `[data-testid=primaryButton]` Next → 密码 → 生日(`BirthYear/BirthMonth/BirthDay`,两套填法 `X月`/`X日`)→ 姓 `#lastNameInput` 名 `#firstNameInput`。
风控探测:「一些异常活动」/「此站点正在维护」→ IP 被封(bump `ip_blocked` + penalize node);`iframe#enforcementFrame` → FunCaptcha(放弃该 IP,轮换)。
`captcha_strategy`:0 全自动按压 / 1 半自动(暂停人工) / 2 只到验证码交人工。
### 4.3 按压验证码 —— 调 slidex(`ChallengeType.HOLD`)
嵌套 iframe:外 `iframe[title="验证质询"]` / 内 `iframe[style*="display: block"]`。
- adapter 检测到按压 iframe → CDP attach 到 slidex → slidex `HoldSolver` 执行:
- Bezier 三段式鼠标(`_natural_move`:加速接近→随机过冲→微调修正)移植。
- 双击→松开→**长按**,按住期间 `_circular_tremor` 圆形微颤。
- 等「再次按下」按钮 → click/dblclick 按运行胜率加权轮换(`_pick_b2mode`)。
- 结果检测:`.draw` 消失 + 「正在加载」→ 通过/重试/IP 封。
- 人工交接(策略1/2)→ slidex `ManualFallbackSession`。
### 4.4 进邮箱 + 概率性恢复邮箱绑定
- 验证码过 → 跳 `mail/0`。
- **概率出现**「让我们来保护你的帐户」`#EmailAddress` → 调 **CF Temp Mail API**(`POST /admin/new_address` 拿独立 address+jwt)造临时邮箱 → 填入 → `#iOttText` 收码 → 保存 session 供 OAuth 复用。
- 概率出现通行密钥/Windows Hello → 取消 `#idBtn_Back`。
- 不出现则直接进邮箱(概率事件,不空等)。
- **依赖**:自部署 CF Temp Mail 服务(或对接本仓库 mail 收码——见 §5)。
### 4.5 OAuth2 refresh_token
- `client_id=9e5f94bc-e8a4-4e73-b8be-63364c29d753`(公共客户端),`redirect=https://localhost`,`scope=graph offline_access`。
- **COOKIE 路径**(同浏览器 `prefer_sso`):注册会话静默直达 consent。
- **NEW 路径**(新浏览器+新 IP,注入 `storage_state` cookie):完整登录。
- 状态机:`account_type`(`#msaTile` 个人)→ `login_email`(`#i0116`)→ `login_password` → `protect_account` → `proof_verify`(6 格 `#codeEntry-0..5`,临时邮箱接码)→ `kmsi`(点否)→ `consent`(`#appConsentPrimaryButton`)。
- code 捕获:监听 `request`/`framenavigated`,从 `localhost?code=` 提取。
- token 交换:`requests.post` `grant_type=authorization_code`,**重试复用本仓库 proxy_rotate**(而非端口池)。
- 产物 `email----password----client_id----refresh_token` → sink。
## 5. 收码能力对齐
现有 `mail_assets` + `EmailSource` + `test_hotmail_rest_code.py` 是 **Hotmail Graph/REST 收码**(读已有邮箱)。Outlook 链路收码需求不同:
- 注册主流程**不靠邮件收码**(按压验证码)。
- 恢复邮箱绑定(§4.4)需**造临时邮箱+收码**(CF Temp Mail)。
- OAuth proof_verify(§4.5)复用绑定阶段临时邮箱 session 接码。
结论:Phase 4 收码**移植 OutlookRegister `temp_mail.py`(CF Temp Mail)**,不复用现有 Graph/REST。需自部署 CF Temp Mail 服务。能否对接 mail_assets 替代,在 writing-plans 阶段评估。
## 6. 已有抽象:register_core/providers(无需扩展 Protocol)
Outlook 作为第 4 个 `RegisterProvider`(`register_core/providers/base.py:12`),接口够用:
```python
class RegisterProvider(Protocol):
name: str
def register(self, config) -> str: ...
def register_one(self, config, **kwargs) -> str: ...
def cancel(self, config, **kwargs) -> None: ...
def cleanup(self, config, **kwargs) -> None: ...
def status(self, config, **kwargs) -> dict: ...
```
路由:`registry.py` 按 name 注册 factory,`pipeline.py:51` 经 `job.provider` + `get_provider(...)` 选择。config `ProviderSpec`(`config/schema.py:10`)新增 outlook 字段。
**adapter 内自管浏览器+验证码(调 slidex)+邮件+OAuth,向 sink 上报产物。**
## 7. 开发路径(分阶段,跨两仓库)
| # | 仓库 | 阶段 | 来源 |
|---|---|---|---|
| S1 | slidex | 增 `ChallengeType.HOLD` + vision dispatch + `HoldSolver`(移植按压全套)+ hold provider + manifest 注册 | OutlookRegister §4.3 + slidex vision |
| S2 | slidex | 单测(echo iframe 模拟按压通过/重试/IP封);CDP 连接验证 | 新建 |
| S3 | grok-register | Outlook adapter 骨架 + config ProviderSpec + registry 路由 + sink 占位 | 现有抽象 |
| S4 | grok-register | 注册主流程移植(填表+风控+进邮箱),`captcha_strategy=2` 跑通选择器;stealth 用 slidex;代理走 proxy_rotate | OutlookRegister §4.1-4.2 |
| S5 | grok-register | 按压验证码接入:adapter 检测 iframe → CDP attach → 调 slidex `ChallengeType.HOLD` | S1 + §4.3 |
| S6 | grok-register | 恢复邮箱绑定(CF Temp Mail + recovery_bind) | OutlookRegister §4.4 |
| S7 | grok-register | OAuth2 refresh_token 状态机 + code 捕获 + token 交换(接 proxy_rotate) | OutlookRegister §4.5 |
| S8 | grok-register | 产物落盘 + control_api run 配置 + 账号导入导出 | 本仓库 |
S1/S2 先行(slidex 出按压能力),S3-S8 在 grok-register。S5 依赖 S1。
## 8. control_api / 批量接入
- run 配置加 `provider=outlook` + `client_id` + `captcha_strategy` + `temp_mail`(CF Temp Mail)+ `email_suffix`。
- control_api routes/ops 多数 site-agnostic,扩 `ProviderSpec` 字段 + 账号导入导出 outlook 产物。
- supervisor 子批次/flock/进程组清理基本 site-agnostic 可复用;但其进度解析当前与 grok 耦合较紧,Outlook 支确认复用同套进度格式还是旁路(见 §10)。
## 9. 账号产物
使用独立的 `outlook_auths_dir`(默认 `outlook_auths/`)和 `outlook-<safe-email>-<UTC timestamp>.json` 文件名,字段:
```json
{"email","password","client_id","refresh_token","recovery_email","bound":bool,"created_at"}
```
private 文件使用 `0600`、同目录临时文件原子替换;兼容 account_backup / sink,但不加入既有 `xai-*.json` CPA glob。public output 只返回 email、bound、artifact path、步骤和存在性信息,不返回 password、refresh_token、cookie 或 proxy URL。
## 10. 关键风险
1. **按压验证码是行为风控**,人类化鼠标是成功率核心;HoldSolver 移植须保 `_natural_move`/`_circular_tremor` 原样细节。
2. **CDP attach 同一浏览器解按压码**模式需验证:slidex `connect_over_cdp` 接进来后,mouse 事件坐标/frame 定位是否与主进程 patchright context 一致(主进程 page 在嵌套 iframe 内,slidex 需定位到同一 frame)。这是 S2/S5 的关键技术风险。
3. 注册页**强依赖中文文案**,locale 必须 `zh-CN`。
4. **FunCaptcha(`enforcementFrame`)出现即放弃** → IP 质量决定验证码类型,node_score 识别并惩罚/轮换。
5. **IP→timezone/locale/geo 注入** clash 层可能没有,需补。
6. CF Temp Mail 需自部署服务(Phase S6 依赖)。
7. **双引擎并存**(DrissionPage + patchright)增依赖与运维面;adapter 间互不干扰。
8. **OAuth SSO cookie 连续性**依赖同 context(adapter 主进程跑),CDP attach 不破坏 context——这是 §3.1 架构成立的前提。
9. 移植 OutlookRegister 代码须保留其 MIT 署名(进 slidex 与进 grok-register 两处分别标注来源)。
## 11. 已确认决策(写入 implementation plan)
- [x] §10.2:优先验证 slidex `connect_over_cdp` 是否能定位主进程嵌套 iframe 并保持坐标一致;若验证失败,adapter 导出主 context 的 `storage_state`,创建仅用于验证码的临时 context,完成后关闭临时 context,主注册 context 不重启且继续负责邮箱/OAuth。
- [x] §5:CF Temp Mail 作为新增 `temp_mail`/`cf_temp` EmailSource,服务恢复邮箱绑定和 OAuth proof verify;既有 `mail_assets`/Hotmail Graph REST 继续服务已有邮箱读取,两者不互换。
- [x] §9:使用独立 `outlook_auths_dir`(默认 `outlook_auths/`)和 `outlook-*.json`,不加入现有 `xai-*.json` CPA glob。
- [x] §8:Outlook 复用现有 `SUMMARY_JSON`、`注册成功`、`Fatal`、`FAIL-FAST` 等 supervisor 进度协议,同时使用独立 Outlook artifact glob 和计数分支。