recovered from aaronjaworski710
This commit is contained in:
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
Reference in New Issue
Block a user