recovered from aaronjaworski710
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
# Adding a provider
|
||||
|
||||
Copy the template, wire the registry, keep production authority honest.
|
||||
|
||||
## 1. Scaffold
|
||||
|
||||
```bash
|
||||
cp -R providers/_template providers/<name>
|
||||
# edit providers/<name>/README.md, run-register.sh (or Python entry)
|
||||
```
|
||||
|
||||
Choose a stack:
|
||||
|
||||
| Style | When | Email |
|
||||
|-------|------|-------|
|
||||
| **Black-box** | Existing Node/Python runner with own mail | `email_source=provider` only |
|
||||
| **In-process** | Pure Python using `EmailSource` | any registered source |
|
||||
|
||||
## 2. Adapter
|
||||
|
||||
Implement `RegisterProvider` in `register_core/providers/<name>_adapter.py`:
|
||||
|
||||
```python
|
||||
class FooProvider:
|
||||
name = "foo"
|
||||
|
||||
def register_one(self, *, email_source=None, extra=None) -> RegisterResult:
|
||||
# MUST attribute success to THIS run (offset / RESULT_JSON / ledger delta)
|
||||
...
|
||||
```
|
||||
|
||||
Register in `register_core/providers/registry.py` `_ensure_builtins`.
|
||||
|
||||
If black-box, add the name to `Pipeline._BLACKBOX_PROVIDERS`.
|
||||
|
||||
## 3. Verify + sink
|
||||
|
||||
- Optional: `register_core/verify/<name>.py` + registry
|
||||
- Pipeline can use `JsonlSink` (`O_CREAT|0600`)
|
||||
|
||||
## 4. Hub
|
||||
|
||||
```bash
|
||||
# register.sh — add a case that execs providers/<name>/run-register.sh
|
||||
./register.sh <name> [count]
|
||||
```
|
||||
|
||||
## 5. Tests (required)
|
||||
|
||||
Minimum offline cases:
|
||||
|
||||
1. Historical output file alone does **not** count as success
|
||||
2. Exit 0 with no this-run identity → fail
|
||||
3. `to_public_dict` never leaks full secret/password
|
||||
4. Black-box + external `--email-source` raises
|
||||
|
||||
```bash
|
||||
make test
|
||||
# or
|
||||
uv run python -m pytest tests/unit test_register_core_layers.py -q
|
||||
```
|
||||
|
||||
## 6. Docs
|
||||
|
||||
- `providers/<name>/README.md` — env, run, artifacts, CPA path if any
|
||||
- One line in `providers/README.md`
|
||||
- Changelog entry under Added
|
||||
|
||||
## Do not
|
||||
|
||||
- Read only the last line of a shared ledger as success
|
||||
- Commit keys, mail dumps, or live CPA YAML
|
||||
- Auto-write production CPA without an explicit operator command
|
||||
@@ -0,0 +1,118 @@
|
||||
# 已落地功能一览(ai-register-machine)
|
||||
|
||||
本索引汇总**已在 main 落地**的功能开发,便于一眼看清「开发了什么」。每条附代表 commit;对应的设计文档(design spec / plan)已归档至 [`docs/archive/`](archive/)。
|
||||
|
||||
> 生产现状:**双轨权威(有意)**——(1) CLI 单发:`./register.sh grok|mimo|chatgpt|typesafe` 经 `register_core` Pipeline(attribution / strategy burn-cool / 节点 preflight / 代理轮换 / 验证器 / JSONL sink);Grok/MiMo adapter 仍 shell-out legacy(`GROK_LEGACY`/`MIMO_LEGACY`/`CHATGPT_LEGACY=1` 回滚)。(2) **Grok 大批量**:`scripts/launch_batch_supervisor.sh` → `register_cli.py` 并发 chunk(**不经** register_core 串行外壳),disk-first:`CPA_EXPORT=true` / `PROBE_CHAT=false` / `REMOTE_INJECT=false`,成功=complete auth 落盘。CPA inject 独立链路,不绑产号成功。in-process 重写(B)未启动。下表「归档 spec/plan」指设计稿,不代表代码落点。
|
||||
|
||||
| 功能 | 交付内容 | 代表 commit | 归档 spec/plan |
|
||||
|---|---|---|---|
|
||||
| 多 provider hub + 目标架构 | register_machine 多产品中心、register_core 分层库(contracts/pipeline/providers/nodes/verify/sink)、MiMo provider、embedded mihomo | `4c0da27`、`96b641c`(改名为 ai-register-machine) | — |
|
||||
| ChatGPT code-align | protocol/OTP 诊断、soft cool、mail-proxy 拆分、PKCE 最佳努力残留、mint_method 戳、产品退出诚实计数、软/硬回收 + 致命停止不空转 | `4229542`、`97064a3`、`c02283f`、`cd46a2a`、`0eb97d8`、`691ce9f` | [chatgpt-code-align](archive/specs/2026-07-16-chatgpt-code-align-design.md) |
|
||||
| CPA mid-tier probe | 直连 vs CPA 双通道 chat gate 策略、hybrid mid-tier probe 接入 mint/export/backfill | `dc4002d`、`51689b4` | [cpa-mid-tier-probe](archive/specs/2026-07-16-cpa-mid-tier-probe-design.md) |
|
||||
| nodes target preflight | target-aware L1(ipify) + L2(provider 域名) 节点预检、import/batch 前只发 healthy、smart_order、urllib status 探针 | `9866e34`、`d2d1ef6`、`af3ceba` | [nodes-target-preflight](archive/specs/2026-07-17-nodes-target-preflight-design.md) |
|
||||
| register_profile_config(M1–M4) | profile 驱动 mailbox∥decode∥strategy;M2 burn+cool 策略;M3/M4 MiMo/Grok FIXED_EMAIL 注入;M2–M4 review 修复 | `ee668c5`、`57d620d`、`b520035` | [register-profile-config](archive/specs/2026-07-17-register-profile-config-design.md) |
|
||||
| Clash egress pinning | 权威 Clash egress 探针、pin ChatGPT 组/优选、真实 backend 标签、bare-curl 假 CN 判别 | `f3a65ab`、`8023f95`、`9525177` | [nodes-target-preflight](archive/specs/2026-07-17-nodes-target-preflight-design.md) |
|
||||
| ChatGPT human-pace | protocol API 步骤间 ~10s±1s 拟人节拍 | `f421837` | [chatgpt-code-align](archive/specs/2026-07-16-chatgpt-code-align-design.md) |
|
||||
| SPA-stuck browser_boot 回收 | pre-email「您正在登录」粘滞 → `AccountRetryNeeded browser_boot` slot-retry;legacy wording 兼容归类 | `773404c`、`e635334`、`530f770` | — |
|
||||
| Hotmail plus-alias 关停 | 别名农场 kill-switch(mode=off / allow=false),别名耗尽立即致命停止不空转 | `78fd894` | [chatgpt-code-align](archive/specs/2026-07-16-chatgpt-code-align-design.md) |
|
||||
| register_core 迁移 A(生产入口切 Pipeline) | `./register.sh grok\|mimo\|chatgpt` 统一经 register_core Pipeline 调度(attribution/strategy/节点 preflight/代理轮换/验证器/sink);Grok/MiMo 仍 shell-out legacy;`GROK_LEGACY`/`MIMO_LEGACY`/`CHATGPT_LEGACY=1` 回滚;退出码映射 0/1/2;路由静态门禁 `test_router.py` | `5c10946`、`18f2976`、(phase-3) | — |
|
||||
| mint 稳定性(disk-first smoke 暴露) | 单实例 flock(register_cli + smoke 包装);`scripts/smoke_diskfirst_one.sh` 官方单发 disk-first;device 页 `device_click_stall` 早停;`mint_fail_reason`/`phase` 进 SUMMARY_JSON;启动清理孤儿 Chrome + 无子进程 Xvfb/`/tmp/xvfb-run.*` | (本轮 commit) | — |
|
||||
|
||||
### mint 稳定性验证入口(disk-first)
|
||||
|
||||
```bash
|
||||
# 官方单发 smoke(flock + export=true/probe=false/inject=false;成功=complete+refresh)
|
||||
bash scripts/smoke_diskfirst_one.sh
|
||||
# 跳过 Clash 叶子 preflight(调试)
|
||||
SKIP_CLASH_PREFLIGHT=1 bash scripts/smoke_diskfirst_one.sh
|
||||
# 门禁
|
||||
python -m pytest test_mint_stability.py test_orphan_chrome_cleanup.py test_bulk_supervisor_disk_first.py -q
|
||||
```
|
||||
|
||||
## 待开发(backlog,未启动,本轮不做)
|
||||
|
||||
- **register_core 迁移收尾**:**A 已落地 / B in-process 未启动**。A(CLI 生产入口切 register_core 外壳)完成。**Bulk supervisor 有意保留直调 `register_cli` 并发**(见 ARCHITECTURE · Dual production tracks);B(in-process 并发 + 可选把 bulk 收进 Pipeline)未启动——勿把 bulk 强行串行化当「修双轨」。
|
||||
- **CF `token长度=0` 日志噪声**:P3,非阻塞。
|
||||
- 节点 catalog / Clash 产物进一步瘦身(`nodes.json` 2.2MB;可选)。
|
||||
|
||||
## Manual-required(需外部介入,本轮不解)
|
||||
|
||||
- **免费 Build chat 403 / console.x.ai entitlement**:账号侧权限,不 remint、不 soft inject;需 console 解锁或 grokbuild-proxy 服务端中转。
|
||||
- **OpenAI `registration_disallowed`**:IP/风控侧,与 chat 403 同属 external。**量化复核(2026-07-18,pxed 全 ChatGPT sink)**:77 attempts / 0 ok;error_kind 分布 `registration_disallowed` 59 / `mail_miss` 9 / `provider` 6 / `fatal` 2 / `verify` 1。8 个 distinct 数据中心 IP 轮询全 disallowed(IP 非单一封禁,是 ASN/供应商集合门控);canonical Clash GVPS(35.212.179.13)`https://auth.openai.com/` 返回 **403**(Google Cloud ASN 被 Cloudflare 预拒,未到 create_account)。`validate_otp` 全 200 / `mail_miss=0`(IP 轮询轮)→ 邮件/OTP 链无问题。**根因:当前代理池无未被 OpenAI 列禁的住宅 ISP ASN**;需住宅代理资产,本轮环境无解,不再烧号实跑。
|
||||
|
||||
验证入口:mint 后本地 probe `/v1/responses` 观察 403 body;ChatGPT 注册观察 create_account 是否仍 `registration_disallowed`(再测前先接住宅代理 ASN,否则 77/0 已充分)。
|
||||
|
||||
### 住宅代理接入(2026-07-19,进口+计数已落,真机冒烟 Manual 触发)
|
||||
|
||||
接了 5 个 1024proxy 住宅凭证(`cchv57025-region-Rand-sid-<token>-t-5`,sticky 5min、region-Rand 出口随机)。代码底座已落(commit `a82ce14`):`Node.tier/success_count/attempt_count/disallow_count` + 派生 `quality_score()`;`node_from_dict` 四段 `hpup`(`host:port:user:pass` 含 `region-`/`sid-`)→ `socks5h://user:pass@host:port` 归一化(socks5h 远端 DNS,住宅必需);`report_attempt_proxy_result` 各分支 credential 粒度计数(attempt 一次 / success / disallow)。tier 本轮 **在场不消费 rotation**,消费(加权 weight)下一 milestone。
|
||||
|
||||
本地已验证(非真机):
|
||||
- **住宅 egress 通 + 真 ISP ASN**:`curl --socks5-hostname <cred> api.ipify.org` → 凭证1 出口 `107.137.159.33` = **AT&T Enterprises, AS7018,Charlotte NC,`hosting:false proxy:false`**;凭证2 出口 `202.63.210.10`(不同 IP,region-Rand 生效)。即 pxed 77/0 `registration_disallowed` 缺的「未被列禁住宅 ISP ASN」现在有了。
|
||||
- **注册机消费住宅池**:5 凭证写 `nodes.json`(list 模式不经 Clash),`inject_attempt_proxy` round-robin 依次命中 5 个 socks5h URL、tier=1 全在;`report_attempt_proxy_result` 计数精确落盘(disallow→`score=-0.5`,success→`score=1.0`)。即凭据→注册机进口→注册机轮询→注册机计数→读产物,整链是注册机自己的路径,未手搓前端。
|
||||
|
||||
pxed 真机冒烟 Manual 触发(本地无 pxed Clash/tinyhost/真机浏览器环境,不硬跑):
|
||||
1. 在 pxed 把 5 凭证导住宅 catalog(每行 `{"url":"<hpup>","tier":1}`,hpup→socks5h 由 border 自动转):
|
||||
`python3 -c "...save via node_from_dict..."` 或追加进 pxed `nodes.json`,标 `tier=1`。
|
||||
2. Grok 优先用住宅池 list 模式跑(profile钉clash,override成list+PROXY_LIST=住宅池):
|
||||
`REGISTER_EGRESS=list PROXY_LIST=<5个socks5h,逗号分隔> SKIP_CLASH_PREFLIGHT=1 ./register.sh grok 1`
|
||||
住宅 socks5h 远端 DNS 走真 Grok egress,绕开 pxed Clash 机房 ASN。
|
||||
3. 读产物查 residential egress 是否解 block:`logs/` 最近 run-core log + `output/pipeline-grok.jsonl` sink + `nodes.json` credential 计数(`atom_count/success_count/disallow_count` 落盘即上轮底座生效);看前端到没到注册表单 / `registration_disallowed` 还出不出。
|
||||
1024proxy 账号 `cchv57025` 流量配额/订阅有效期是后台约束,代码无法判;配额耗尽需后台续费/换账号后导新凭证组。
|
||||
|
||||
设计稿:`docs/IP-ISOLATION-QUALITY-DESIGN.md`;tier 入 weighted rotation 留下一 milestone。
|
||||
|
||||
## 路由门禁验证入口(migrate milestone A)
|
||||
|
||||
生产入口外壳正确性(无需真机/真号):
|
||||
|
||||
```bash
|
||||
# dry Pipeline 编排冒烟(仅验证外壳打通,不期望产真号):
|
||||
SKIP_CLASH_PREFLIGHT=1 ./register.sh grok 1 # 经 register_core Pipeline + grok_adapter shell-out
|
||||
SKIP_CLASH_PREFLIGHT=1 ./register.sh chatgpt 1 # 经 register_core profile 路径(in-process)
|
||||
SKIP_CLASH_PREFLIGHT=1 ./register.sh mimo 1 # 经 register_core Pipeline + mimo_adapter shell-out
|
||||
# 日志应出现 [register_core.pipeline] StrategyEngine precheck + 节点 preflight + 验证器 + sink 写入
|
||||
```
|
||||
|
||||
回滚(单 provider 一行 env,复产号路径):
|
||||
|
||||
```bash
|
||||
GROK_LEGACY=1 ./register.sh grok N T # 回到 run-register.sh → register_cli.py legacy 并发
|
||||
MIMO_LEGACY=1 ./register.sh mimo N # 回到 providers/mimo/run-register.sh Node runner
|
||||
CHATGPT_LEGACY=1 ./register.sh chatgpt N # 回到 providers/chatgpt/run-register.sh env 驱动
|
||||
```
|
||||
|
||||
静态门禁:`python -m pytest test_router.py -q`(断言:三入口默认路由 register_core,`*_LEGACY=1` 回滚,`core` 子命令不变,chatgpt 按 `CHATGPT_EMAIL_SOURCE` 选 profile 并恢复 timeout 900 / proxy-rotate / sink 的 env override)。
|
||||
|
||||
环境变量契约(chatgpt 外壳切 register_core 后保留的 legacy 旋钮):
|
||||
- `CHATGPT_EMAIL_SOURCE`(默认 `cloudflare`)选 profile:`cloudflare→chatgpt-cf`、`tinyhost→chatgpt-tinyhost`、`gmail_imap→chatgpt-gmail`。**默认从 legacy `auto` 改为 `cloudflare`**(匹配 legacy runner 的 `CHATGPT_EMAIL_SOURCE=cloudflare` 默认)。
|
||||
- `CHATGPT_EMAIL_DOMAIN`:tinyhost profile 不再钉 `publicvm.com`,由 adapter 读 env(huychau.online 等 override 生效;cf/gmail profile 本不钉 domain)。
|
||||
- `CHATGPT_TIMEOUT`(默认 `900`)→ `--timeout`(修复 argparse 默认 1200 的静默覆盖)。
|
||||
- `CHATGPT_PROXY_ROTATE_MODE` / `CHATGPT_PROXY_ROTATE_EVERY` → `--proxy-rotate` / `--proxy-rotate-every`(legacy 已转发,切外壳找回)。
|
||||
- `CHATGPT_SINK`:仅显式设置时传 `--sink`;否则用 profile 的 `sink.path`(不再恒覆盖)。
|
||||
- `REGISTER_EGRESS` / `CHATGPT_PROXY` / `CHATGPT_PROXY_LIST`:按既有行为转发;未设时 profile 默认(chatgpt profile 为 `clash:7897`,与 legacy Clash egress 一致)。
|
||||
|
||||
egress 边界说明(Grok):grok-tinyhost profile 钉 `strategy.egress.mode: clash proxy 127.0.0.1:7897`,使 `profile_to_job` 设 `extra["proxy"]` → grok_adapter force-set 子进程 `PROXY/CPA_PROXY`(attempt proxy 胜过 ambient shell env),Pipeline 真正持有 Grok egress(而非靠 `run-register-core.sh` 继承的旧 `PROXY` env)。Pipeline 在此 backend 持有 attribution / strategy burn-cool / GrokChatVerifier / sink;Clash 叶子健康仍由 `preflight-clash-nodes.sh` 探(`nodes.json` L1/L2 catalog preflight 是 `list|auto` 独立 backend,非 Grok 默认)。
|
||||
|
||||
生产冒烟(Manual-required,非阻塞):pxed 上 `./register.sh grok 1` 真实节点产 Grok reg+mint 确认切外壳后仍产出;ChatGPT 仍 `registration_disallowed`(外部依赖)。
|
||||
|
||||
### Grok fatal 契约修复(phase-3 收尾,pxed smoke 发现)
|
||||
|
||||
pxed 上 `./register.sh grok 1` 切外壳后真跑暴露一个回归 bug 并已修复(commit `4d7812a`):
|
||||
|
||||
- 现象:register_cli 在邮件 OTP 阶段超时(tinyhost 桥 30s×5 轮询无码),exit=1,SUMMARY_JSON `"fatal":false,"fatal_reason":""`;但 grok_adapter 旧的致命探测 `any(k in lower(out) for k in ("alias","耗尽","exhausted","fatal","fail-fast","致命"))` 命中了 SUMMARY_JSON body 中**始终存在**的键 `"fatal"`/`"fatal_reason"` → 把一次可重试的 OTP 超时误升为 `FailFastError` → Pipeline `fail-fast stop` + exit=2(致命契约),整批停。
|
||||
- 根因:致命判定应走 register_cli 权威退出码契约,而非子串匹配。register_cli contract:`exit 2 = fatal`(`_fatal_stop` set,SUMMARY_JSON `"fatal":true` + `"fatal_reason"`);`exit 1 = 可重试 not-product`(OTP 超时/验证失败等);`exit 0 = product ok`。
|
||||
- 修复:grok_adapter 改用 `exit==2` 为致命主信号,SUMMARY_JSON `"fatal"`/`"fatal_reason"` 作交叉校验(JSON 内 `fatal:true` 即使 exit=1 也致命,以防契约漂移),仅当 register_cli 无任何输出(spawn 前 crash / 无 summary)时才落老逻辑判致命。致命时携带脱敏后的 register_cli 输出尾(边界证据日志,生产失败可诊断)。
|
||||
- 5 个契约测试固化(`test_register_core_layers.py::TestGrokFatalContract`):exit-1+fatal:false 不致命(pxed 回归)、exit-2 致命、summary fatal:true 升级、无输出 spawn 致命、带 Traceback 的 OTP 超时不致命。本地 + pxed 均 pass。
|
||||
- 真实验证(pxed):切外壳后 `./register.sh grok 1` 现在在可重试邮件超时下退出契约 1(not-product),而非契约 2(fatal)——Pipeline 不再因单次瞬时邮件失败停整批;账号本身是否产出仍取决于 tinyhost 邮件送达(外部依赖)。
|
||||
|
||||
### shell↔python exit-契约收口(milestone A review 修复)
|
||||
|
||||
`run-register-core.sh` 把 `register_core` 运行结果映射回 legacy 0/1/2 时,旧实现 grep 日志正文里的 `fail_fast|fatal:|Traceback|...` 推断致命,漏判两类 batch-stop:
|
||||
|
||||
- strategy 域名 burn 硬停:`stopped_reason="strategy: domain burned: ..."`,无 `fail_fast`/`fatal:` 子串 → 旧 grep 落 exit 1(not-product),但实际是域已不可用、需运维换域的 batch-stop,应是 exit 2。
|
||||
- post-loop `fail_fast` 停(读 `result.error_kind`):`stopped_reason` 为 `registration_disallowed` 之类(非 `"fatal"` 字面)→ 同样被降级为 exit 1。
|
||||
|
||||
修复:`register_core.cli.cmd_run` 增权威行 `CONTRACT_EXIT:N`,N 由 `_contract_exit_from_stats(stats)` 唯一推导——以 `stats.stopped_reason` 非空为 batch-stop 信号(Pipeline 内每条 early-break 路径都 set 它;可重试耗尽干净退出留空)。`run-register-core.sh` 改读该行,无该行时按 python 退出码兜底(`code==2`→fatal、`code==0`→ok、`code==1` 且有 Traceback→fatal 否则 not-product)。属 [[feedback-decode-once-at-boundary]] 同类反模式的 shell 侧收口:负责人信号只解一次。
|
||||
|
||||
- 7 个契约回归测试固化(`test_register_core_layers.py::TestContractExit`):ok→0、可重试耗尽→1、loop-fatal→2、strategy domain-burn→2、post-loop kind-stop→2、mail_miss→2、unexpected→2。
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
# 设计:IP 隔离层 + IP 质量信号采集
|
||||
|
||||
> 范围说清楚:本轮**只把数据底座和隔离结构抛好**,不动 rotation 的 weight 决策消费。
|
||||
> 下一轮(新 milestone)才把质量信号灌进 rotation 公式。这样符合"先把所有东西抛好再说"。
|
||||
> 待落地的设计稿;尚未走 writing-plans 出实施计划。
|
||||
|
||||
## 起因与现状基线(已核实,非臆测)
|
||||
|
||||
我们要接 5 个高质量**住宅代理(residential)** IP,它是目前能解 ChatGPT `registration_disallowed` 的唯一外部路径;现有"普通 IP"是 Clash leaf / 机房代理。三 provider(grok/mimo/chatgpt)共用,加权轮询,住宅优先、普通兜底混入。
|
||||
|
||||
核实结论:
|
||||
- `register_core/nodes/models.py:10-28` `Node` 是唯一节点载体,字段**无 tier / priority / source_pool / quality**;只有 `last_ok / fail_count / cooldown_until`(被动冷却),无成功计数。
|
||||
- `register_core/util/proxy.py:703` `report_attempt_proxy_result` 已是**质量信号天然入库点**:按 proxy url(`mgr.find_by_url`)找 node、按 kind 分流、`save_nodes` 持久化。现做:成功清 fail_count;`registration_disallowed` 风险冷却 600s;network fail mark+冷却;其他 kind 不动 node。
|
||||
- `register_core/nodes/catalog.py:76` `save_nodes` 已落盘;import CLI 默认 persist(`--no-save` 关) → 质量信号不会随进程结束丢失。
|
||||
- `register_core/util/proxy.py:359` `inject_attempt_proxy` 按 pool 原序轮询,**无主动优先级排序/打分**——所有 IP 同权重 + 被动 burn/cool。
|
||||
- 全树**无任何主动 IP 质量打分/优先级排序/主动淘汰**逻辑。`registration_disallowed` 只软冷却、不计 disallow 次。
|
||||
|
||||
## P0/P1 范围(本轮)
|
||||
|
||||
P0(阻塞接 IP):节点隔离层
|
||||
1. `Node` 加 `tier: int = 0` 字段(0=机房普通默认,向后兼容现有 nodes.json;1=住宅高质量)。导入/profile/单条 JSON 均可标 tier。
|
||||
2. 住宅池与普通池"概念隔离"通过 `tier` 字段表达,不做独立文件/pool registry(避免 C 方案超范围)。
|
||||
|
||||
P0(阻塞质量底座):质量信号采集
|
||||
3. `Node` 加 `success_count: int = 0`、`attempt_count: int = 0`、`disallow_count: int = 0` 三个计数控;加**派生** `quality_score()`(`success_count / max(1, attempt_count) - λ * disallow_count`,λ 默认 0.5,环境变量可调,本轮不参与决策只展示/落盘)。
|
||||
4. 在 `report_attempt_proxy_result` 各回写分支里加计数:
|
||||
- 进入函数、找到 node 后(proxy 非空且 node 在 catalog):`node.attempt_count += 1`。
|
||||
- success 分支:`node.success_count += 1`(在现有清 fail_count 处并加)。
|
||||
- `registration_disallowed` 分支:`node.disallow_count += 1`(在现有 600s 风险冷却处并加)。
|
||||
- network_fail / 其他:不另加 disallow(attempt_count 已 +1)。
|
||||
- 持久化复用现有各分支结尾的 `save_nodes`,**不新增 I/O / hook**。
|
||||
|
||||
P1(固化):测试 + 导入透传
|
||||
5. import 解析路径透传 tier(除非单条 JSON/profile 已带,否则默认 0);uri_list `--tier N` 整批标注;`nodes add --tier N` 单条标。**新增 `host:port:user:pass` 四段冒号串 → `socks5://user:pass@host:port` 的归一化**(在 `node_from_dict` 字符串分支)。新增 import border 测试:带 tier 的 JSON/uri_list 落到 Node.tier;`hpup` 串归一化为 socks5 URL 后建 Node 不丢 tier。
|
||||
6. 回归测试:模拟 success / disallow / network-fail 各分支,断言三个计数正确、quality_score 派生正确、节点持久化字段对(attempt/success/disallow 落盘,tier 不丢)。
|
||||
|
||||
## 不做的 P2/P3 / Manual-required
|
||||
|
||||
- **不碰 rotation weight 公式**(层2决策消费)——下一 milestone。本轮 tier 加进去但 `inject_attempt_proxy` 仍按原序轮询,tier 字段"在场不参与"。这点要在测试里显式断言:tier 不影响轮询顺序(防现轮引入未验证的优先级行为)。
|
||||
- 不做"主动按 score 淘汰/降权"(score 只采集+展示)。
|
||||
- 不为 tier 加新的 egress backend / new preflight;preflight 复用现有 `preflight_nodes_for_register`,不分 tier 探活(健康与否与 tier 正交)。
|
||||
- 不写独立 Pool registry / 分池文件(C 方案,超本轮)。
|
||||
- 不引入归因里"这个 IP 被禁 vs 这个 IP 质量差"的新二分——`registration_disallowed` 的 disallow_count 既是被禁信号也是质量负信号,本轮合并记、下一轮再细化区分。
|
||||
- Manual-required:5 个住宅凭证导入后,真机 `./register.sh chatgpt 1` 用住宅池跑,确认 `registration_disallowed` 出现率下降(本轮 shell 改完即 Manual 触发,非阻塞)。**1024proxy 账号 `cchv57025` 的流量配额 / 订阅有效期是外部约束**,代码无法判断;配额耗尽需用户在后台续费/换账号后重新导入新凭证组,本轮不自动处理。
|
||||
|
||||
## 关键设计决策
|
||||
|
||||
1. **回写键是 Node id(= proxy url),不是 last_ip**。last_ip 会变(同一住宅代理首次出站的真实 IP 较稳但代理端可能轮转出口),proxy url 才稳定。沿 `mgr.find_by_url(proxy)` 现有检索,不新开 IPIP 路径。`last_ip` 仅诊断展示。
|
||||
|
||||
2. **tier 是隔离标签 + 质量档位双语义**:隔离(pool 边界由 tier 划分)、质量档位(下一轮 weight 公式会读)。本轮只落地前者语义、后者"在场不消费"。
|
||||
|
||||
3. **质量信号采集改在现成 hook,不引新通路**。`pipeline.py:459` `_feedback_proxy → report_attempt_proxy_result` 已被每个 attempt 结果调用(含成功路径),是唯一回写点。本轮只是"在那里多记三笔",不动调用方。
|
||||
|
||||
4. **tier 的 import 标注入口**:profile.yaml 节点段可 `tier: 1` 单条标;uri_list 导入加 `--tier N` 整批标;单条 JSON 节点 `{"url":..., "tier":1}`。三入口都解析,默认 0。5 个住宅 IP 到手时,用其中一种导入即可隔离标好(你给我 IP 时告诉我格式,我配对应入口)。
|
||||
|
||||
5. **加权轮询的"消费"留下一轮**:本轮 `inject_attempt_proxy` 不读 tier/score。下一 milestone 才把它改成"按 tier+score 算 weight、住宅 weight 高、池内轮询、高 tier 优先命中"。这样本轮纯采集、零 risk 改 rotation、零 risk 烧住宅池。
|
||||
|
||||
## 住宅代理凭证特性(1024proxy,region-Rand + sticky sid,转运导入影响)
|
||||
|
||||
用户提供的 5 个凭证格式 `hostname:port:username:password`:
|
||||
```
|
||||
us.1024proxy.io:3000:cchv57025-region-Rand-sid-<rand>-t-5:tyfnvdhr
|
||||
```
|
||||
- 它们**不是 5 个固定出口 IP**,是 **5 个住宅代理凭证**。username 内含粘性会话句柄:
|
||||
- `region-Rand` = 出口地区随机(每次会话轮换地区)。
|
||||
- `sid-<token>-t-5` = sticky 会话 5 分钟;5 min 后 sid 释出、下一次该凭证出口换新 IP。
|
||||
- 账号 `cchv57025` 与密码 `tyfnvdhr` 是 1024proxy 订阅凭证,**有效期取决于该账号流量配额**(用户在 1024proxy 后台可知,代码无法判断);sid token 本身不"过期失效",只 5 min 换 IP。**不需每 5 min 重新生成**;账号配额耗尽时需后台续费/换账号 → 届时再导新凭证组即可。
|
||||
- 标准化形态:`socks5://<username>:<password>@us.1024proxy.io:3000`。
|
||||
|
||||
**对设计的两点深化**(不是问题,是 advantage):
|
||||
|
||||
6. **凭证粒度质量评估更贴合 region-Rand**:因出口 IP 每 5 min 随机漂移,**按出口 IP 记质量会错乱**;按凭证(url)记则跨多次出口累积成功率——正好契合决策 1"回写键是 Node id (=url)"。`quality_score` 在凭证粒度上语义 = "这 5 个住宅凭证整体住宅路径的平均成功率",而非"单个出口 IP 质量"。这是住宅 region-Rand 天然决定的,不是我们选的,但与现有按 url 回写设计天然吻合。
|
||||
7. **import border 必须做 `hpup` → socks5 URL 归一化**:现有 `node_from_dict`(`models.py:86`)的字符串分支把整行原样当 `url`,**不识别 `host:port:user:pass` 四段串**,下游用 url 当 proxy 时会解析失败。本轮 import border 必须加归一化:识别"恰好四段冒号、第三段含 `region-`/`sid-`/credentials 特征、本机可走 HTTP/SOCKS"的串,转成 `socks5://user:pass@host:port`。
|
||||
|
||||
## 导入这 5 个住宅凭证的具体方式(本轮实现后)
|
||||
|
||||
最干净:**单文件 5 行 JSON**,每行带 `tier:1`,归一化由 border 自动转 socks5 URL:
|
||||
```json
|
||||
[{"url":"us.1024proxy.io:3000:cchv57025-region-Rand-sid-pA5pnsjK-t-5:tyfnvdhr","tier":1},
|
||||
... 共 5 行 ...]
|
||||
```
|
||||
import 文件后 catalog 落 5 个 Node,`tier=1`、`url` 已归一化为 `socks5://...`。
|
||||
|
||||
import CLI 入口需补:`node_from_dict` 字符串分支判定四段冒号 + `cmd_add`/`--tier` 选项透传。**此入口完善属本轮 P1**(见 P1 范围第 5 项的"导入透传 tier")。
|
||||
|
||||
## 验证(端到端)
|
||||
|
||||
|
||||
1. 构建/类型:`python -m compileall register_core/nodes register_core/util/proxy.py`。
|
||||
2. 单元/集成:`python -m pytest -q` 全绿;新增 6~7 个测试:
|
||||
- import border:tier 从 JSON/uri_list 落到 Node。
|
||||
- report success:attempt+1、success+1、fail_count 清零、save_nodes 调用。
|
||||
- report disallow:attempt+1、disallow+1、600s 风险冷却不变、持久化。
|
||||
- report network fail:attempt+1、不增 disallow、mark_result 不变。
|
||||
- report non-proxy kind:attempt+1(仅)、其他不变。
|
||||
- quality_score 派生:构造计数 → 断言公式。
|
||||
- tier 不影响轮询顺序(固化"在场不消费")。
|
||||
3. 手动(Manual-required,非阻塞):5 个住宅 IP 到手后导入(带 tier=1)、`./register.sh chatgpt 1` 跑,看日质量计数随结果增长、`registration_disallowed` 率下降。
|
||||
|
||||
## 回滚
|
||||
|
||||
- `Node` 新增字段均为 `= 0` / `= ""` 默认值,向后兼容现有 nodes.json(旧文件无这些键加载后取默认)。回滚即把字段与各 `+= 1` 三行删掉,不动 rotation 因为本轮没改它。
|
||||
- import 的 `--tier` 与单条 JSON 的 `tier` 为可选键;解析端默认 0,旧导入不受影响。
|
||||
|
||||
## 后续(下一 milestone,不在本轮)
|
||||
|
||||
- 层2决策消费:`inject_attempt_proxy` 读 tier+score 算 weight,住宅高权、加权轮询、score 差的 IP 降权/踢出。
|
||||
- epoch 持久化 + 历史 window quality(看 N 次注册成功率,不是全期)。
|
||||
- registration_disallowed 的 disallow 与"质量差"细区分(让 `registration_disallowed` 不烧号但降 tier 权重)。
|
||||
@@ -0,0 +1,20 @@
|
||||
# Repository layout (quick)
|
||||
|
||||
See [ARCHITECTURE.md](../ARCHITECTURE.md) for the full map.
|
||||
|
||||
| Path | Role |
|
||||
|------|------|
|
||||
| `register.sh` | Multi-provider hub |
|
||||
| `register_core/` | Layered orchestration library |
|
||||
| `providers/<name>/` | Product package (scripts, README, env) |
|
||||
| `providers/_template/` | Copy-me for new products |
|
||||
| `apps/` | Human map of CLI/GUI entrypoints |
|
||||
| `docs/` | How-to and layout |
|
||||
| `docs/DEVELOPED.md` | 已落地功能一览(历史设计见 [`docs/archive/`](archive/)) |
|
||||
| `examples/` | Minimal safe samples |
|
||||
| `scripts/` | Ops (doctor, remint, setup) |
|
||||
| `tests/` | Preferred location for **new** tests |
|
||||
| Root `test_*.py` | Legacy offline tests (CI still runs them) |
|
||||
| `cpa_xai/`, `register_cli.py`, `grok_register_ttk.py` | Grok production (root until migrate) |
|
||||
|
||||
Runtime secrets stay gitignored: `config.json`, `.env`, `mail_credentials.txt`, `accounts_*.txt`, `cpa_auths/`, `backups/`, `logs/`, `providers/*/output/`.
|
||||
@@ -0,0 +1,10 @@
|
||||
# Archive — 已完成历史设计文档
|
||||
|
||||
本目录收藏**已在 main 落地**的设计文档(design spec + 实现 plan),仅作历史留档,不再活跃。
|
||||
|
||||
- `specs/` — 设计稿(brainstorming 产出)
|
||||
- `plans/` — 实现计划(writing-plans 产出)
|
||||
|
||||
对应的已落地功能与代表 commit,见 [`../DEVELOPED.md`](../DEVELOPED.md)。
|
||||
|
||||
新的设计文档请直接写在 `../superpowers/specs/` 与 `../superpowers/plans/`(未来开发的落点,沿用 superpowers 约定)。
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,832 @@
|
||||
# free Build chat mid-tier probe (tebi CPA) 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:** Product chat gate (`chat_ok` / inject) probes free Build through existing tebi CLIProxyAPI when safe; otherwise hybrid keeps direct entitlement stamps. Auth files still store cli-chat-proxy `base_url`.
|
||||
|
||||
**Architecture:** Add a `ProbeTransport` abstraction in `cpa_xai/probe.py` with `direct_bearer` (current) and `cpa_openai` (CPA OpenAI-compatible base + CPA API key). `probe_models` / `probe_mini_response` / `probe_chat_with_retries` take an optional transport. Because CPA pool routing may not pin a just-minted credential, default product mode is **hybrid**: entitlement gate remains direct-bearer with the mint token; optional post-path `probe_via_cpa_ok` is observational only and never replaces `chat_ok` for inject. Full `cpa` gate mode is only enabled when `cpa_probe_credential_pin` is configured and non-empty.
|
||||
|
||||
**Tech Stack:** Python 3 stdlib (`urllib`), existing `cpa_xai` package, config.json / env secrets, unit tests via `test_cpa_chat_entitlement_gate.py` style (no pytest required).
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Hard gate stays: `cpa_probe_chat` / `cpa_probe_chat_required` default true; 403 → `entitlement_denied`; no remint spin; no inject without `chat_ok=true`.
|
||||
- Auth JSON `base_url` remains `https://cli-chat-proxy.grok.com/v1` (or config `cpa_base_url` upstream). Never write public CPA URL into auth files.
|
||||
- Do not deploy standalone grokbuild-proxy; mid-tier = tebi CPA only.
|
||||
- Do not change OAuth mint (PKCE/device), remint skip-denied, or ledger shape.
|
||||
- No real secrets in git; config.example only placeholders + comments.
|
||||
- Do not commit `_live_activation_test.py`.
|
||||
- Classify CPA API-key 401/403 as ops/config (`auth_or_protocol` / non-entitlement), not `entitlement_denied`.
|
||||
- If pin unavailable, **forbid** defaulting product gate to unpinned `cpa` (spec §6.2 / §9).
|
||||
|
||||
## File structure
|
||||
|
||||
| File | Responsibility |
|
||||
|---|---|
|
||||
| `cpa_xai/probe.py` | Transport types + direct/CPA HTTP; reuse `classify_chat_probe` |
|
||||
| `cpa_xai/mint.py` | Pass probe transport options into probe helpers |
|
||||
| `cpa_export.py` | Resolve probe config from cfg/env; wire mint + optional hybrid CPA smoke |
|
||||
| `scripts/backfill_chat_stamps.py` | Same transport resolution as mint |
|
||||
| `config.example.json` | Document new keys (placeholders only) |
|
||||
| `test_cpa_chat_entitlement_gate.py` | Transport + hybrid + gate regression tests |
|
||||
| (optional later) Obsidian free Build note | ops note mid-tier = tebi CPA — Manual/docs, not code gate |
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Probe transport abstraction + CPA HTTP path
|
||||
|
||||
**Files:**
|
||||
- Modify: `cpa_xai/probe.py`
|
||||
- Test: `test_cpa_chat_entitlement_gate.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: existing `classify_chat_probe`, `_opener`, `DEFAULT_CLIENT_HEADERS`, `DEFAULT_BASE_URL`
|
||||
- Produces:
|
||||
- `ProbeTransport` TypedDict / dataclass fields:
|
||||
- `mode: str` — `"direct"` | `"cpa"`
|
||||
- `base_url: str`
|
||||
- `api_key: str` — CPA gateway key when mode=`cpa`; empty for direct
|
||||
- `credential_pin: str` — optional header value for per-auth routing (email or auth filename); empty = unpinned
|
||||
- `pin_header: str` — header name if pin used; default `"X-CPA-Credential"` (overridable via config later)
|
||||
- `resolve_probe_transport(...)` pure helper (may live in probe.py or export; prefer probe.py for reuse)
|
||||
- `probe_models(..., transport: ProbeTransport | None = None)`
|
||||
- `probe_mini_response(..., transport: ProbeTransport | None = None)`
|
||||
- `probe_chat_with_retries(..., transport: ProbeTransport | None = None)`
|
||||
- `is_cpa_gateway_auth_error(result) -> bool` helper for failure mapping
|
||||
|
||||
- [ ] **Step 1: Write the failing tests**
|
||||
|
||||
Append to `test_cpa_chat_entitlement_gate.py`:
|
||||
|
||||
```python
|
||||
def test_probe_transport_direct_uses_bearer_and_cli_headers() -> None:
|
||||
probe = _load("cpa_xai.probe_transport", ROOT / "cpa_xai" / "probe.py")
|
||||
assert hasattr(probe, "build_probe_transport")
|
||||
assert hasattr(probe, "probe_request_headers")
|
||||
t = probe.build_probe_transport(
|
||||
via="direct",
|
||||
upstream_base_url="https://cli-chat-proxy.grok.com/v1",
|
||||
cpa_base_url="https://cpa.example/v1",
|
||||
cpa_api_key="sk-cpa",
|
||||
access_token="tok-xai",
|
||||
)
|
||||
assert t["mode"] == "direct"
|
||||
assert t["base_url"].rstrip("/") == "https://cli-chat-proxy.grok.com/v1"
|
||||
h = probe.probe_request_headers(t, access_token="tok-xai")
|
||||
assert h["Authorization"] == "Bearer tok-xai"
|
||||
assert "x-grok-client-identifier" in h
|
||||
assert h.get("x-grok-client-identifier") == "grok-pager"
|
||||
print("PASS direct transport headers")
|
||||
|
||||
|
||||
def test_probe_transport_cpa_uses_api_key_not_xai_token() -> None:
|
||||
probe = _load("cpa_xai.probe_transport2", ROOT / "cpa_xai" / "probe.py")
|
||||
t = probe.build_probe_transport(
|
||||
via="cpa",
|
||||
upstream_base_url="https://cli-chat-proxy.grok.com/v1",
|
||||
cpa_base_url="https://cpa.mangoq.ccwu.cc/v1",
|
||||
cpa_api_key="sk-cpa-key",
|
||||
access_token="tok-xai-should-not-be-auth",
|
||||
credential_pin="xai-user@example.com.json",
|
||||
pin_header="X-CPA-Credential",
|
||||
)
|
||||
assert t["mode"] == "cpa"
|
||||
assert t["base_url"].endswith("/v1") or "cpa.mangoq" in t["base_url"]
|
||||
h = probe.probe_request_headers(t, access_token="tok-xai-should-not-be-auth")
|
||||
assert h["Authorization"] == "Bearer sk-cpa-key"
|
||||
assert h.get("X-CPA-Credential") == "xai-user@example.com.json"
|
||||
# Must NOT send xAI access_token as Authorization when mode=cpa
|
||||
assert "tok-xai" not in h["Authorization"]
|
||||
print("PASS cpa transport headers")
|
||||
|
||||
|
||||
def test_build_probe_transport_rejects_unpinned_cpa_as_gate_mode() -> None:
|
||||
"""Spec §6: unpinned cpa must not be used as entitlement gate without hybrid."""
|
||||
probe = _load("cpa_xai.probe_transport3", ROOT / "cpa_xai" / "probe.py")
|
||||
# Prefer: resolve_gate_transport returns hybrid policy when via=cpa but no pin
|
||||
policy = probe.resolve_gate_probe_policy(
|
||||
via="cpa",
|
||||
cpa_base_url="https://cpa.example/v1",
|
||||
cpa_api_key="sk",
|
||||
credential_pin="", # missing
|
||||
allow_unpinned_cpa_gate=False,
|
||||
)
|
||||
assert policy["gate_via"] == "direct"
|
||||
assert policy["cpa_smoke"] is True # optional observational path allowed
|
||||
assert policy["reason"] in ("unpinned_cpa_hybrid", "hybrid")
|
||||
print("PASS unpinned cpa → hybrid policy")
|
||||
|
||||
|
||||
def test_cpa_gateway_401_not_entitlement() -> None:
|
||||
probe = _load("cpa_xai.probe_cls_gw", ROOT / "cpa_xai" / "probe.py")
|
||||
out = {
|
||||
"ok": False,
|
||||
"status": 401,
|
||||
"error": "invalid api key",
|
||||
"transport_mode": "cpa",
|
||||
"error_code": "unauthorized",
|
||||
}
|
||||
# Either classify_chat_probe with transport_mode, or post-classify remap
|
||||
cls = probe.classify_chat_probe(out)
|
||||
if out.get("transport_mode") == "cpa" and out.get("status") in (401, 403):
|
||||
# gateway layer: not account entitlement
|
||||
remapped = probe.remap_cpa_gateway_failure(out, cls)
|
||||
assert remapped["entitlement_denied"] is False
|
||||
assert remapped["reason"] in ("auth_or_protocol", "cpa_gateway_auth")
|
||||
else:
|
||||
remapped = probe.remap_cpa_gateway_failure(out, cls)
|
||||
assert remapped["entitlement_denied"] is False
|
||||
print("PASS cpa gateway 401 not entitlement")
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run tests to verify they fail**
|
||||
|
||||
Run:
|
||||
```bash
|
||||
cd /Users/mango/project/claude-project/grok-register
|
||||
.venv/bin/python -u test_cpa_chat_entitlement_gate.py
|
||||
```
|
||||
Expected: FAIL / AttributeError on missing `build_probe_transport` / `resolve_gate_probe_policy` (or only old tests pass if new tests not yet invoked — ensure `main` calls the new tests).
|
||||
|
||||
- [ ] **Step 3: Implement transport helpers in `cpa_xai/probe.py`**
|
||||
|
||||
Add near top (after imports):
|
||||
|
||||
```python
|
||||
from typing import Any, Mapping, MutableMapping
|
||||
|
||||
# Product default: never use unpinned CPA pool as chat entitlement truth.
|
||||
DEFAULT_CPA_PIN_HEADER = "X-CPA-Credential"
|
||||
|
||||
|
||||
def build_probe_transport(
|
||||
*,
|
||||
via: str,
|
||||
upstream_base_url: str = DEFAULT_BASE_URL,
|
||||
cpa_base_url: str = "",
|
||||
cpa_api_key: str = "",
|
||||
access_token: str = "",
|
||||
credential_pin: str = "",
|
||||
pin_header: str = DEFAULT_CPA_PIN_HEADER,
|
||||
) -> dict[str, Any]:
|
||||
mode = (via or "direct").strip().lower()
|
||||
if mode not in {"direct", "cpa"}:
|
||||
mode = "direct"
|
||||
if mode == "cpa":
|
||||
base = (cpa_base_url or "").strip().rstrip("/")
|
||||
if not base:
|
||||
# Fail closed to direct if misconfigured
|
||||
mode = "direct"
|
||||
base = (upstream_base_url or DEFAULT_BASE_URL).rstrip("/")
|
||||
return {
|
||||
"mode": mode,
|
||||
"base_url": base,
|
||||
"api_key": (cpa_api_key or "").strip(),
|
||||
"credential_pin": (credential_pin or "").strip(),
|
||||
"pin_header": (pin_header or DEFAULT_CPA_PIN_HEADER).strip(),
|
||||
"upstream_base_url": (upstream_base_url or DEFAULT_BASE_URL).rstrip("/"),
|
||||
}
|
||||
return {
|
||||
"mode": "direct",
|
||||
"base_url": (upstream_base_url or DEFAULT_BASE_URL).rstrip("/"),
|
||||
"api_key": "",
|
||||
"credential_pin": "",
|
||||
"pin_header": "",
|
||||
"upstream_base_url": (upstream_base_url or DEFAULT_BASE_URL).rstrip("/"),
|
||||
}
|
||||
|
||||
|
||||
def resolve_gate_probe_policy(
|
||||
*,
|
||||
via: str,
|
||||
cpa_base_url: str = "",
|
||||
cpa_api_key: str = "",
|
||||
credential_pin: str = "",
|
||||
allow_unpinned_cpa_gate: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Decide which path stamps chat_ok (gate) vs optional CPA smoke.
|
||||
|
||||
Spec: unpinned CPA must not stamp chat_ok. Hybrid keeps gate=direct.
|
||||
"""
|
||||
v = (via or "direct").strip().lower()
|
||||
if v not in {"direct", "cpa", "hybrid"}:
|
||||
v = "direct"
|
||||
pin = (credential_pin or "").strip()
|
||||
has_cpa = bool((cpa_base_url or "").strip() and (cpa_api_key or "").strip())
|
||||
|
||||
if v == "direct" or not has_cpa:
|
||||
return {
|
||||
"gate_via": "direct",
|
||||
"cpa_smoke": False,
|
||||
"reason": "direct" if v == "direct" else "cpa_config_missing",
|
||||
}
|
||||
if v == "hybrid":
|
||||
return {"gate_via": "direct", "cpa_smoke": has_cpa, "reason": "hybrid"}
|
||||
# via == cpa
|
||||
if pin or allow_unpinned_cpa_gate:
|
||||
return {
|
||||
"gate_via": "cpa",
|
||||
"cpa_smoke": False,
|
||||
"reason": "cpa_pinned" if pin else "cpa_unpinned_allowed",
|
||||
}
|
||||
return {"gate_via": "direct", "cpa_smoke": has_cpa, "reason": "unpinned_cpa_hybrid"}
|
||||
|
||||
|
||||
def probe_request_headers(
|
||||
transport: Mapping[str, Any],
|
||||
*,
|
||||
access_token: str,
|
||||
) -> dict[str, str]:
|
||||
mode = str(transport.get("mode") or "direct")
|
||||
if mode == "cpa":
|
||||
key = str(transport.get("api_key") or "").strip()
|
||||
headers = {
|
||||
"Authorization": f"Bearer {key}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
pin = str(transport.get("credential_pin") or "").strip()
|
||||
pin_h = str(transport.get("pin_header") or DEFAULT_CPA_PIN_HEADER).strip()
|
||||
if pin and pin_h:
|
||||
headers[pin_h] = pin
|
||||
return headers
|
||||
return {
|
||||
"Authorization": f"Bearer {access_token}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
**DEFAULT_CLIENT_HEADERS,
|
||||
}
|
||||
|
||||
|
||||
def remap_cpa_gateway_failure(
|
||||
raw: Mapping[str, Any],
|
||||
classified: Mapping[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""CPA API-key / gateway failures must not stamp entitlement_denied."""
|
||||
out = dict(classified)
|
||||
if str(raw.get("transport_mode") or "") != "cpa":
|
||||
return out
|
||||
status = int(raw.get("status") or 0)
|
||||
if status in (401, 403) and not raw.get("upstream_entitlement"):
|
||||
# Treat as gateway/config unless body clearly is free-Build permission-denied
|
||||
err = str(raw.get("error") or "").lower()
|
||||
if "permission" in err and "denied" in err and "console.x.ai" in err:
|
||||
out["upstream_entitlement"] = True
|
||||
return out
|
||||
if status == 401 or "api key" in err or "unauthorized" in err or "invalid key" in err:
|
||||
out["entitlement_denied"] = False
|
||||
out["retryable"] = False
|
||||
out["reason"] = "cpa_gateway_auth"
|
||||
out["error_code"] = str(raw.get("error_code") or status)
|
||||
return out
|
||||
# Ambiguous CPA 403: still do not mark entitlement without clear body
|
||||
if status == 403 and "permission" not in err:
|
||||
out["entitlement_denied"] = False
|
||||
out["retryable"] = True
|
||||
out["reason"] = "cpa_gateway_error"
|
||||
return out
|
||||
```
|
||||
|
||||
Update `probe_models` and `probe_mini_response` signatures to accept optional `transport: dict | None = None`. When `transport` is None, behave exactly as today (direct + `base_url` arg + DEFAULT_CLIENT_HEADERS).
|
||||
|
||||
Core change pattern for `probe_mini_response`:
|
||||
|
||||
```python
|
||||
def probe_mini_response(
|
||||
access_token: str,
|
||||
*,
|
||||
base_url: str = DEFAULT_BASE_URL,
|
||||
timeout: float = 60.0,
|
||||
proxy: str | None = None,
|
||||
transport: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
t = transport or build_probe_transport(
|
||||
via="direct",
|
||||
upstream_base_url=base_url,
|
||||
access_token=access_token,
|
||||
)
|
||||
base = str(t.get("base_url") or base_url).rstrip("/")
|
||||
url = f"{base}/responses"
|
||||
payload = {
|
||||
"model": "grok-4.5",
|
||||
"stream": False,
|
||||
"input": "Reply with exactly MINT_OK",
|
||||
"reasoning": {"effort": "low"},
|
||||
}
|
||||
headers = probe_request_headers(t, access_token=access_token)
|
||||
# ensure Content-Type for POST
|
||||
headers.setdefault("Content-Type", "application/json")
|
||||
opener = _opener(proxy)
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=json.dumps(payload).encode("utf-8"),
|
||||
headers=headers,
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
with opener.open(req, timeout=timeout) as resp:
|
||||
body = json.loads(resp.read().decode("utf-8"))
|
||||
texts: list[str] = []
|
||||
for item in body.get("output") or []:
|
||||
if item.get("type") == "message":
|
||||
for c in item.get("content") or []:
|
||||
if c.get("type") == "output_text":
|
||||
texts.append(c.get("text") or "")
|
||||
out = {
|
||||
"ok": True,
|
||||
"status": getattr(resp, "status", 200),
|
||||
"model": body.get("model"),
|
||||
"text": "\n".join(texts),
|
||||
"usage": body.get("usage"),
|
||||
"transport_mode": t.get("mode") or "direct",
|
||||
}
|
||||
cls = classify_chat_probe(out)
|
||||
out.update(cls)
|
||||
return out
|
||||
except urllib.error.HTTPError as e:
|
||||
err_body = e.read().decode("utf-8", errors="replace")[:800]
|
||||
out = {
|
||||
"ok": False,
|
||||
"status": e.code,
|
||||
"error": err_body,
|
||||
"error_code": _extract_error_code(err_body),
|
||||
"transport_mode": t.get("mode") or "direct",
|
||||
}
|
||||
cls = classify_chat_probe(out)
|
||||
out.update(remap_cpa_gateway_failure(out, cls))
|
||||
return out
|
||||
except Exception as e: # noqa: BLE001
|
||||
out = {
|
||||
"ok": False,
|
||||
"status": 0,
|
||||
"error": str(e),
|
||||
"transport_mode": t.get("mode") or "direct",
|
||||
}
|
||||
out.update(classify_chat_probe(out))
|
||||
return out
|
||||
```
|
||||
|
||||
Mirror the same `transport` / `transport_mode` / `remap_cpa_gateway_failure` pattern in `probe_models` (GET `/models`).
|
||||
|
||||
Update `probe_chat_with_retries` to pass `transport=` through to `probe_mini_response`.
|
||||
|
||||
- [ ] **Step 4: Wire new tests into main() and run**
|
||||
|
||||
Ensure bottom of `test_cpa_chat_entitlement_gate.py` `main` calls the four new tests. Run:
|
||||
|
||||
```bash
|
||||
.venv/bin/python -u test_cpa_chat_entitlement_gate.py
|
||||
```
|
||||
|
||||
Expected: ALL PASS (existing + new).
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add cpa_xai/probe.py test_cpa_chat_entitlement_gate.py
|
||||
git commit -m "feat(cpa): probe transport direct vs CPA with hybrid gate policy"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Config surface + mint/export/backfill wiring
|
||||
|
||||
**Files:**
|
||||
- Modify: `cpa_xai/mint.py`
|
||||
- Modify: `cpa_export.py`
|
||||
- Modify: `scripts/backfill_chat_stamps.py`
|
||||
- Modify: `config.example.json`
|
||||
- Test: `test_cpa_chat_entitlement_gate.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `build_probe_transport`, `resolve_gate_probe_policy`, `probe_*` with `transport=`
|
||||
- Produces:
|
||||
- Config keys (example.json + runtime):
|
||||
- `cpa_probe_via`: `"direct"` | `"cpa"` | `"hybrid"` — **default `"hybrid"`** until pin proven in ops
|
||||
- `cpa_probe_base_url`: e.g. `https://cpa.mangoq.ccwu.cc/v1` or tunnel `http://127.0.0.1:8317/v1`
|
||||
- `cpa_probe_api_key`: empty in example; prefer env `CPA_PROBE_API_KEY`
|
||||
- `cpa_probe_credential_pin_mode`: `"none"` | `"email"` | `"auth_filename"` — default `"auth_filename"` when via=cpa
|
||||
- `cpa_probe_pin_header`: default `X-CPA-Credential`
|
||||
- `cpa_probe_allow_unpinned_cpa_gate`: default `false` (safety)
|
||||
- `mint_and_export(..., probe_via=..., cpa_probe_base_url=..., cpa_probe_api_key=..., probe_credential_pin=..., ...)`
|
||||
- Result fields: existing stamps + optional `probe_via_cpa_ok: bool | None`, `probe_gate_via: str`, `probe_policy_reason: str`
|
||||
|
||||
- [ ] **Step 1: Failing tests for config wiring + hybrid result fields**
|
||||
|
||||
```python
|
||||
def test_config_example_documents_mid_tier_probe_keys() -> None:
|
||||
raw = (ROOT / "config.example.json").read_text(encoding="utf-8")
|
||||
assert "cpa_probe_via" in raw
|
||||
assert "cpa_probe_base_url" in raw
|
||||
assert "cpa_probe_api_key" in raw
|
||||
assert "cpa_probe_credential_pin_mode" in raw
|
||||
# base_url semantics unchanged
|
||||
assert "cli-chat-proxy.grok.com" in raw
|
||||
print("PASS config.example mid-tier keys")
|
||||
|
||||
|
||||
def test_mint_passes_transport_kwargs_signature() -> None:
|
||||
src = (ROOT / "cpa_xai" / "mint.py").read_text(encoding="utf-8")
|
||||
assert "probe_via" in src
|
||||
assert "build_probe_transport" in src or "resolve_gate_probe_policy" in src
|
||||
assert "probe_via_cpa_ok" in src or "cpa_smoke" in src
|
||||
# Must not rewrite base_url to CPA public host for auth write
|
||||
assert "build_cpa_xai_auth" in src
|
||||
print("PASS mint transport kwargs signature")
|
||||
|
||||
|
||||
def test_export_resolves_env_api_key() -> None:
|
||||
src = (ROOT / "cpa_export.py").read_text(encoding="utf-8")
|
||||
assert "cpa_probe_via" in src
|
||||
assert "CPA_PROBE_API_KEY" in src
|
||||
assert "resolve_gate_probe_policy" in src
|
||||
print("PASS export mid-tier resolve")
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run to verify fail**
|
||||
|
||||
```bash
|
||||
.venv/bin/python -u -c "
|
||||
import test_cpa_chat_entitlement_gate as t
|
||||
t.test_config_example_documents_mid_tier_probe_keys()
|
||||
"
|
||||
```
|
||||
Expected: AssertionError on missing keys.
|
||||
|
||||
- [ ] **Step 3: Extend `config.example.json`**
|
||||
|
||||
After `cpa_probe_chat_required` block, insert:
|
||||
|
||||
```json
|
||||
"// cpa_probe_via": "chat gate transport: direct=本地直连 cli-chat-proxy(回归默认路径);cpa=经 tebi CPA(需 credential pin,否则自动 hybrid);hybrid=门禁仍 direct,成功后可选 CPA smoke 写 probe_via_cpa_ok(不替代 chat_ok)。生产在 pin 能力确认前推荐 hybrid。",
|
||||
"cpa_probe_via": "hybrid",
|
||||
"// cpa_probe_base_url": "CPA OpenAI-compatible base(含 /v1)。公网 https://cpa.mangoq.ccwu.cc/v1 或与 inject 一致的 tunnel/内网 http://127.0.0.1:8317/v1。不要写进 xai-*.json base_url。",
|
||||
"cpa_probe_base_url": "",
|
||||
"// cpa_probe_api_key": "调用 CPA 的 API key(不是 xAI access_token)。优先 env CPA_PROBE_API_KEY;禁止提交真实 key。",
|
||||
"cpa_probe_api_key": "",
|
||||
"// cpa_probe_credential_pin_mode": "cpa 门禁钉凭据:none|email|auth_filename。无 pin 且 via=cpa 时强制 hybrid。",
|
||||
"cpa_probe_credential_pin_mode": "auth_filename",
|
||||
"// cpa_probe_pin_header": "钉凭据请求头名;取决于 tebi CLIProxyAPI 版本是否支持。不支持则保持 hybrid。",
|
||||
"cpa_probe_pin_header": "X-CPA-Credential",
|
||||
"// cpa_probe_allow_unpinned_cpa_gate": "危险开关:true 允许无 pin 的 CPA 池结果盖 chat_ok(假阳/假阴)。默认 false。",
|
||||
"cpa_probe_allow_unpinned_cpa_gate": false,
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Wire `mint_and_export`**
|
||||
|
||||
Add kwargs (defaults preserve current behavior):
|
||||
|
||||
```python
|
||||
probe_via: str = "direct",
|
||||
cpa_probe_base_url: str = "",
|
||||
cpa_probe_api_key: str = "",
|
||||
probe_credential_pin: str = "",
|
||||
probe_pin_header: str = "X-CPA-Credential",
|
||||
allow_unpinned_cpa_gate: bool = False,
|
||||
```
|
||||
|
||||
In the probe section after write:
|
||||
|
||||
```python
|
||||
from .probe import (
|
||||
apply_chat_probe_to_result,
|
||||
build_probe_transport,
|
||||
probe_chat_with_retries,
|
||||
probe_models,
|
||||
resolve_gate_probe_policy,
|
||||
)
|
||||
|
||||
policy = resolve_gate_probe_policy(
|
||||
via=probe_via,
|
||||
cpa_base_url=cpa_probe_base_url,
|
||||
cpa_api_key=cpa_probe_api_key,
|
||||
credential_pin=probe_credential_pin,
|
||||
allow_unpinned_cpa_gate=allow_unpinned_cpa_gate,
|
||||
)
|
||||
result["probe_gate_via"] = policy["gate_via"]
|
||||
result["probe_policy_reason"] = policy["reason"]
|
||||
gate_transport = build_probe_transport(
|
||||
via=policy["gate_via"],
|
||||
upstream_base_url=base_url,
|
||||
cpa_base_url=cpa_probe_base_url,
|
||||
cpa_api_key=cpa_probe_api_key,
|
||||
access_token=tokens["access_token"],
|
||||
credential_pin=probe_credential_pin,
|
||||
pin_header=probe_pin_header,
|
||||
)
|
||||
log(
|
||||
f"probe policy gate_via={policy['gate_via']} cpa_smoke={policy['cpa_smoke']} "
|
||||
f"reason={policy['reason']}"
|
||||
)
|
||||
|
||||
run_models = bool(probe or probe_chat)
|
||||
if run_models:
|
||||
pr = probe_models(
|
||||
tokens["access_token"],
|
||||
base_url=base_url,
|
||||
proxy=resolved or None,
|
||||
transport=gate_transport,
|
||||
)
|
||||
# ... existing models handling ...
|
||||
if probe_chat and pr.get("has_grok_45"):
|
||||
ch = probe_chat_with_retries(
|
||||
tokens["access_token"],
|
||||
base_url=base_url,
|
||||
proxy=resolved or None,
|
||||
max_attempts=3,
|
||||
log=log,
|
||||
transport=gate_transport,
|
||||
)
|
||||
apply_chat_probe_to_result(result, ch)
|
||||
# ... existing entitlement log ...
|
||||
|
||||
# Optional observational CPA smoke — NEVER sets chat_ok by itself
|
||||
if policy.get("cpa_smoke") and result.get("chat_ok") is True:
|
||||
smoke_t = build_probe_transport(
|
||||
via="cpa",
|
||||
upstream_base_url=base_url,
|
||||
cpa_base_url=cpa_probe_base_url,
|
||||
cpa_api_key=cpa_probe_api_key,
|
||||
access_token=tokens["access_token"],
|
||||
credential_pin=probe_credential_pin,
|
||||
pin_header=probe_pin_header,
|
||||
)
|
||||
try:
|
||||
smoke = probe_mini_response(
|
||||
tokens["access_token"],
|
||||
base_url=base_url,
|
||||
proxy=resolved or None,
|
||||
transport=smoke_t,
|
||||
)
|
||||
result["probe_via_cpa_ok"] = bool(smoke.get("ok"))
|
||||
result["probe_via_cpa"] = smoke
|
||||
log(f"cpa smoke ok={smoke.get('ok')} status={smoke.get('status')}")
|
||||
except Exception as e: # noqa: BLE001
|
||||
result["probe_via_cpa_ok"] = False
|
||||
result["probe_via_cpa_error"] = str(e)[:200]
|
||||
```
|
||||
|
||||
Important: `build_cpa_xai_auth(..., base_url=base_url)` keeps using upstream `cpa_base_url` config (cli-chat-proxy), **not** `cpa_probe_base_url`.
|
||||
|
||||
- [ ] **Step 5: Wire `cpa_export.py` config resolution**
|
||||
|
||||
Near other probe flags (~852):
|
||||
|
||||
```python
|
||||
probe_via = str(cfg.get("cpa_probe_via") or "hybrid").strip().lower() or "hybrid"
|
||||
cpa_probe_base_url = (
|
||||
str(cfg.get("cpa_probe_base_url") or os.environ.get("CPA_PROBE_BASE_URL") or "")
|
||||
.strip()
|
||||
)
|
||||
cpa_probe_api_key = (
|
||||
str(
|
||||
cfg.get("cpa_probe_api_key")
|
||||
or os.environ.get("CPA_PROBE_API_KEY")
|
||||
or ""
|
||||
).strip()
|
||||
)
|
||||
pin_mode = str(cfg.get("cpa_probe_credential_pin_mode") or "auth_filename").strip().lower()
|
||||
pin_header = str(cfg.get("cpa_probe_pin_header") or "X-CPA-Credential").strip()
|
||||
allow_unpinned = _config_bool(cfg.get("cpa_probe_allow_unpinned_cpa_gate"), default=False)
|
||||
|
||||
# pin value computed after path known — pass email/filename into mint
|
||||
# For mint call, precompute from email:
|
||||
from cpa_xai.schema import credential_file_name
|
||||
if pin_mode == "email":
|
||||
probe_pin = email
|
||||
elif pin_mode == "auth_filename":
|
||||
probe_pin = credential_file_name(email) # existing helper if present; else f"xai-{email}.json"
|
||||
else:
|
||||
probe_pin = ""
|
||||
|
||||
result = mint_and_export(
|
||||
...
|
||||
probe_via=probe_via,
|
||||
cpa_probe_base_url=cpa_probe_base_url,
|
||||
cpa_probe_api_key=cpa_probe_api_key,
|
||||
probe_credential_pin=probe_pin,
|
||||
probe_pin_header=pin_header,
|
||||
allow_unpinned_cpa_gate=allow_unpinned,
|
||||
)
|
||||
```
|
||||
|
||||
If `credential_file_name` is not exported, use:
|
||||
|
||||
```python
|
||||
def _auth_filename_for_email(email: str) -> str:
|
||||
# Mirror writer/schema naming: xai-<sanitized-email>.json
|
||||
from cpa_xai.schema import credential_file_name
|
||||
return credential_file_name(email)
|
||||
```
|
||||
|
||||
Verify `schema.credential_file_name` exists (it is imported in `__init__.py`). Use it.
|
||||
|
||||
- [ ] **Step 6: Wire `scripts/backfill_chat_stamps.py`**
|
||||
|
||||
In `_probe_and_stamp` and `main`, read same config keys; build gate transport via `resolve_gate_probe_policy` + `build_probe_transport`; pass `transport=` to `probe_models` / `probe_chat_with_retries`. Default via from config (`hybrid`). Add CLI:
|
||||
|
||||
```python
|
||||
ap.add_argument("--probe-via", default="", help="Override cpa_probe_via: direct|cpa|hybrid")
|
||||
```
|
||||
|
||||
Resolve: `via = args.probe_via or cfg.get("cpa_probe_via") or "hybrid"`.
|
||||
|
||||
- [ ] **Step 7: Run full unit suite for CPA gate**
|
||||
|
||||
```bash
|
||||
.venv/bin/python -u test_cpa_chat_entitlement_gate.py
|
||||
.venv/bin/python -u test_cpa_one_click_chain.py
|
||||
.venv/bin/python -u test_cpa_remote_inject.py
|
||||
.venv/bin/python -m py_compile cpa_xai/probe.py cpa_xai/mint.py cpa_export.py scripts/backfill_chat_stamps.py
|
||||
```
|
||||
|
||||
Expected: ALL PASS.
|
||||
|
||||
- [ ] **Step 8: Commit**
|
||||
|
||||
```bash
|
||||
git add cpa_xai/mint.py cpa_export.py scripts/backfill_chat_stamps.py config.example.json test_cpa_chat_entitlement_gate.py
|
||||
git commit -m "feat(cpa): wire hybrid/CPA mid-tier probe config into mint export backfill"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Inject gate regression + docs acceptance checks
|
||||
|
||||
**Files:**
|
||||
- Modify: `test_cpa_chat_entitlement_gate.py` (inject still requires `chat_ok`; CPA smoke alone insufficient)
|
||||
- Modify: `cpa_xai/writer.py` only if optional stamp field `probe_via_cpa_ok` should persist (recommended: stamp if present, never required for inject)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `evaluate_remote_inject_gate` / `stamp_auth_chat_fields`
|
||||
- Produces: stamp may include `probe_via_cpa_ok` when present; inject gate ignores it
|
||||
|
||||
- [ ] **Step 1: Write failing inject regression**
|
||||
|
||||
```python
|
||||
def test_inject_gate_ignores_probe_via_cpa_ok_alone() -> None:
|
||||
"""chat_ok remains sole product gate; CPA smoke cannot unlock inject."""
|
||||
export = _load("cpa_export_gate", ROOT / "cpa_export.py")
|
||||
# denied account with smoke true must still block
|
||||
r = {
|
||||
"ok": False,
|
||||
"chat_ok": False,
|
||||
"entitlement_denied": True,
|
||||
"probe_via_cpa_ok": True,
|
||||
"path": "/tmp/xai-x.json",
|
||||
"email": "x@e.com",
|
||||
}
|
||||
gate = export.evaluate_remote_inject_gate(
|
||||
r,
|
||||
{
|
||||
"cpa_remote_inject": True,
|
||||
"cpa_remote_inject_require_chat_ok": True,
|
||||
"cpa_probe_chat": True,
|
||||
},
|
||||
)
|
||||
assert gate.get("allow") is False
|
||||
|
||||
# chat_ok true may allow even if smoke false/missing
|
||||
r2 = {
|
||||
"ok": True,
|
||||
"chat_ok": True,
|
||||
"entitlement_denied": False,
|
||||
"probe_via_cpa_ok": False,
|
||||
"path": "/tmp/xai-y.json",
|
||||
"email": "y@e.com",
|
||||
}
|
||||
gate2 = export.evaluate_remote_inject_gate(
|
||||
r2,
|
||||
{
|
||||
"cpa_remote_inject": True,
|
||||
"cpa_remote_inject_require_chat_ok": True,
|
||||
"cpa_probe_chat": True,
|
||||
},
|
||||
)
|
||||
assert gate2.get("allow") is True
|
||||
print("PASS inject gate ignores cpa smoke")
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run — should pass if evaluate_remote_inject_gate only checks chat_ok (likely already)**
|
||||
|
||||
If it fails because `ok` false blocks, adjust fixture `ok=True`/`chat_ok=False` combo to match real gate function semantics — read `evaluate_remote_inject_gate` and assert the actual `chat_ok is True` requirement still holds.
|
||||
|
||||
- [ ] **Step 3: Optional stamp field in writer**
|
||||
|
||||
In `build_chat_stamp_from_result` / `stamp_auth_chat_fields`, if `result` has `probe_via_cpa_ok` key, copy it into stamp dict. Do **not** require it for completeness. Do **not** let missing `probe_via_cpa_ok` fail stamp.
|
||||
|
||||
```python
|
||||
if "probe_via_cpa_ok" in r:
|
||||
stamp["probe_via_cpa_ok"] = bool(r.get("probe_via_cpa_ok"))
|
||||
if r.get("probe_gate_via"):
|
||||
stamp["probe_gate_via"] = str(r.get("probe_gate_via"))
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Source-level acceptance checks**
|
||||
|
||||
```python
|
||||
def test_auth_write_base_url_not_cpa_public() -> None:
|
||||
mint_src = (ROOT / "cpa_xai" / "mint.py").read_text(encoding="utf-8")
|
||||
# build_cpa_xai_auth must use base_url param (upstream), not cpa_probe_base_url
|
||||
assert "build_cpa_xai_auth(" in mint_src
|
||||
assert "base_url=base_url" in mint_src
|
||||
assert "base_url=cpa_probe_base_url" not in mint_src
|
||||
print("PASS auth write base_url remains upstream")
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Full verification**
|
||||
|
||||
```bash
|
||||
.venv/bin/python -u test_cpa_chat_entitlement_gate.py
|
||||
.venv/bin/python -u test_cpa_one_click_chain.py
|
||||
.venv/bin/python -u test_cpa_remote_inject.py
|
||||
.venv/bin/python -u test_cpa_pkce_mint.py
|
||||
.venv/bin/python -c "from cpa_xai.probe import build_probe_transport, resolve_gate_probe_policy; print(resolve_gate_probe_policy(via='cpa', cpa_base_url='http://x/v1', cpa_api_key='k', credential_pin=''))"
|
||||
```
|
||||
|
||||
Expected: policy `gate_via=direct`, `cpa_smoke=True`, `reason=unpinned_cpa_hybrid`.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add cpa_xai/writer.py test_cpa_chat_entitlement_gate.py
|
||||
git commit -m "test(cpa): inject hard gate ignores CPA smoke; stamp optional probe_via_cpa_ok"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Manual-required pin capability check (ops, not product code)
|
||||
|
||||
**Files:**
|
||||
- Create (optional ops note only if writing vault): none required in repo for milestone close
|
||||
- Or append short section to plan completion summary
|
||||
|
||||
- [ ] **Step 1: Read-only check tebi CPA for credential pin**
|
||||
|
||||
On operator machine (not required for unit green):
|
||||
|
||||
```bash
|
||||
# Prefer tunnel consistent with inject
|
||||
ssh tebi-tunnel 'curl -sS http://127.0.0.1:8317/v1/models -H "Authorization: Bearer $CPA_API_KEY" | head -c 200'
|
||||
# Document whether any header selects auth file (search CPA docs / binary help)
|
||||
ssh tebi-tunnel 'cli-proxy-api --help 2>/dev/null | head -50 || true'
|
||||
```
|
||||
|
||||
Record outcome in commit message or ops note:
|
||||
- If pin header exists → ops may set `cpa_probe_via=cpa` + pin mode after smoke.
|
||||
- If not → keep `hybrid` (code default).
|
||||
|
||||
- [ ] **Step 2: No code change if pin absent**
|
||||
|
||||
Do not invent fake pin behavior. Default hybrid already implements safe path.
|
||||
|
||||
- [ ] **Step 3: Milestone stop**
|
||||
|
||||
Do **not** auto-deploy to pxed in this plan unless user explicitly asks after green tests. Deploy remains Manual-required follow-up:
|
||||
- tar/scp registerer code to `/personal/grok-register`
|
||||
- set `CPA_PROBE_API_KEY` on pxed env / config.json (not git)
|
||||
- small backfill smoke with `--probe-via hybrid`
|
||||
|
||||
---
|
||||
|
||||
## Self-review (plan vs spec)
|
||||
|
||||
| Spec section | Task coverage |
|
||||
|---|---|
|
||||
| §2 Goals mid-tier via tebi CPA | Task 1–2 transport + config |
|
||||
| §2 auth base_url stays cli-chat-proxy | Task 2 mint write; Task 3 assert |
|
||||
| §2 hard gate kept | Task 3 inject regression |
|
||||
| §2 debug direct switch | `cpa_probe_via=direct` |
|
||||
| §3 non-goals (no new proxy, no soft gate, no OAuth change) | Global constraints; tasks avoid |
|
||||
| §6 pinning + hybrid fallback | Task 1 `resolve_gate_probe_policy` |
|
||||
| §6.2 forbid live-inject-to-probe loop | No inject-before-probe in code |
|
||||
| §7 config surface | Task 2 example.json + export |
|
||||
| §8 touch map | Tasks 1–3 |
|
||||
| §9 failure mapping gateway vs entitlement | Task 1 `remap_cpa_gateway_failure` |
|
||||
| §11 acceptance | Task 3 verification commands |
|
||||
| §13 open questions | Task 4 manual pin check; default hybrid + tunnel preference documented in config comments |
|
||||
|
||||
Placeholder scan: none. Types: `build_probe_transport` / `resolve_gate_probe_policy` consistent across tasks.
|
||||
|
||||
## Default freeze (implementation decisions)
|
||||
|
||||
| Decision | Value | Why |
|
||||
|---|---|---|
|
||||
| Default `cpa_probe_via` | `hybrid` | Pin capability unconfirmed; safe for chat_ok truth |
|
||||
| Default pin mode | `auth_filename` | Stable id for future pin header |
|
||||
| Env for key | `CPA_PROBE_API_KEY` | Avoid secrets in git |
|
||||
| Smoke field | `probe_via_cpa_ok` optional stamp | Observability only |
|
||||
| Gate on smoke | never | Spec §6 / §11 |
|
||||
|
||||
---
|
||||
|
||||
## Execution Handoff
|
||||
|
||||
Plan complete and saved to `docs/superpowers/plans/2026-07-16-cpa-mid-tier-probe.md`.
|
||||
|
||||
**Two execution options:**
|
||||
|
||||
1. **Subagent-Driven (recommended)** — dispatch a fresh subagent per task, review between tasks
|
||||
2. **Inline Execution** — execute tasks in this session with checkpoints
|
||||
|
||||
**Which approach?**
|
||||
@@ -0,0 +1,40 @@
|
||||
# Target-Aware Node Preflight Implementation Plan
|
||||
|
||||
> **For agentic workers:** single-phase milestone; implement in place, verify tests, commit once.
|
||||
|
||||
**Goal:** Seed register rotation only with proxies that pass L1 (ipify) **and** L2 (provider business domain).
|
||||
|
||||
**Architecture:** Resolve target URLs from provider/extra/env → layered probe → `proxy_list = pool_ready` → empty fail-fast on list.
|
||||
|
||||
**Tech Stack:** Python 3, existing `curl_cffi`/urllib probe stack, unittest.
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Do not break Clash preflight path.
|
||||
- Do not burn email domains on proxy RST.
|
||||
- Do not soft-inject CPA without chat_ok.
|
||||
- Never commit secrets / nodes.json / ops noise.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Targets + layered probe + wire + tests + docs
|
||||
|
||||
**Files:**
|
||||
- Create: `register_core/nodes/targets.py`
|
||||
- Modify: `register_core/nodes/health.py`
|
||||
- Modify: `register_core/nodes/manager.py`
|
||||
- Modify: `register_core/util/proxy.py`
|
||||
- Modify: `register_core/pipeline.py`
|
||||
- Modify: `register_core/nodes/README.md`
|
||||
- Modify: `ARCHITECTURE.md`
|
||||
- Modify: `test_register_core_nodes.py`
|
||||
- Create: design + plan under `docs/superpowers/`
|
||||
|
||||
- [x] Implement `resolve_probe_targets` + default map
|
||||
- [x] Implement `probe_reachable` (any status) + `probe_node_layered`
|
||||
- [x] `NodeManager.preflight(probe_urls=...)` builds pool from layered ok
|
||||
- [x] `preflight_nodes_for_register` resolves targets; pipeline sets provider
|
||||
- [x] Add empty-response markers to proxy network heuristic
|
||||
- [x] Unit tests for filter / fail-fast / resolve
|
||||
- [x] Docs product contract
|
||||
- [x] Run tests + commit
|
||||
@@ -0,0 +1,297 @@
|
||||
# Design: ChatGPT 代码层面对齐开源最佳实践
|
||||
|
||||
**Date:** 2026-07-16
|
||||
**Status:** approved (user: Scope A + Layer C + success B; §1–§2 OK; proceed implement)
|
||||
**Repo:** local `grok-register` / remote register-machine monorepo
|
||||
**Approach:** Core-first 契约扩展(Approach 1)
|
||||
|
||||
## 1. Context
|
||||
|
||||
pxed ChatGPT smoke(2026-07-16)协议路径到 `send_otp` 200,随后 Gmail catch-all **未收到** OpenAI OTP → fail-fast `mail_miss`。对照开源(zhuce6 / open-reg-auto / gpt-free-register):成功关键不是另一套 client_id,而是:
|
||||
|
||||
1. 邮箱投递质量(本轮 **不接** 商业邮箱 API 实现)
|
||||
2. 注册 egress 与邮件路径分离
|
||||
3. OTP 等待可观测 diagnostics
|
||||
4. 节点时间冷却(soft)与业务失败隔离
|
||||
5. 细错误分类(尤其 `registration_disallowed`)
|
||||
|
||||
本设计只做 **代码层能力对齐**;OTP 投递/住宅声誉仍为 Manual-required。
|
||||
|
||||
## 2. Goals / Non-goals
|
||||
|
||||
### Goals
|
||||
|
||||
| ID | 目标 |
|
||||
|---|---|
|
||||
| G1 | OTP diagnostics:poll 次数、扫信数、first_seen/matched 延迟、failure_class |
|
||||
| G2 | 细 `error_kind`:`mail_miss` / `registration_disallowed` / `captcha` / `proxy`/`network` / `provider` / `verify` / `fatal` / `other` |
|
||||
| G3 | 邮件路径默认不继承注册 proxy;可选独立 `mail_proxy` / `EMAIL_PROXY` |
|
||||
| G4 | `NodeManager` 时间冷却 API + 接线(risk/network soft-cool;mail_miss 永不 cool/quarantine) |
|
||||
| G5 | 配置面文档化(`.env.example` / provider README / config 注释) |
|
||||
| G6 | 单测全绿 + pxed COUNT=1 smoke 可解释失败类;**禁止** 空转与误 quarantine |
|
||||
|
||||
### Non-goals
|
||||
|
||||
- 新商业邮箱(MaliAPI / cfmail 实现)
|
||||
- ChatGPT 自动 CPA inject
|
||||
- 保证现有 gmail+clash 必出号
|
||||
- Grok free Build chat 403 / grokbuild-proxy 中转
|
||||
- Approach 3 大重构(EgressPolicy 全家桶)
|
||||
|
||||
### Success standard B(用户选定)
|
||||
|
||||
拆成两道门禁:
|
||||
|
||||
1. **代码门禁(必须):** 契约+实现+单测绿+smoke 诊断诚实
|
||||
2. **出号门禁(尽量):** `ok=1`;若资产不足 → 交付「代码 ✅ / 出号 ⚠️ Manual-required」,不伪造成功
|
||||
|
||||
## 3. Architecture
|
||||
|
||||
```
|
||||
register_core/
|
||||
contracts.py # OtpWaitDiagnostics; error_kind 注释/常量
|
||||
errors.py # MailMissError.diagnostics 可选属性
|
||||
email/base.py # 文档约定 last_wait_diagnostics(Protocol 签名不炸)
|
||||
email/sources/* # gmail_imap / tinyhost 写 diagnostics
|
||||
email/registry.py # get_email_source 支持 mail_proxy 与 register proxy 分离
|
||||
nodes/models.py # cooldown_until / cooldown_reason
|
||||
nodes/manager.py # is_cooling / cooldown() / pick 跳过冷却
|
||||
util/proxy.py # report_attempt_proxy_result → soft cool on risk/network
|
||||
providers/chatgpt_adapter.py # 解耦 mail proxy;放宽 kind allowlist;artifacts.otp_wait
|
||||
providers/chatgpt/protocol/flow.py # registration_disallowed kind;otp_sent_at
|
||||
```
|
||||
|
||||
**原则:** 通用化在 core;ChatGPT 只接线。Grok/MiMo 不受破坏性变更影响(additive)。
|
||||
|
||||
## 4. Error taxonomy
|
||||
|
||||
### 4.1 `error_kind` 权威表
|
||||
|
||||
| kind | 含义 | hard quarantine | soft cooldown | fail-fast |
|
||||
|---|---|---|---|---|
|
||||
| `mail_miss` | OTP 未达/未匹配 | 否 | 否 | 单次停(现状) |
|
||||
| `registration_disallowed` | OpenAI risk code | 否 | **是** | 单次 fail,不整批 fatal |
|
||||
| `captcha` | PoW/人机 | 否 | 可选 | 否 |
|
||||
| `proxy` / `network` | 连接/TLS/隧道 | 计入 fail_count | 是 | 否 |
|
||||
| `provider` | 其它产品流 | 否 | 否 | 否 |
|
||||
| `verify` | 后验能力失败 | 否 | 否 | 否 |
|
||||
| `fatal` | 配置/源耗尽 | 否 | 否 | **整批** |
|
||||
| `other` | 未归类 | 否 | 否 | 否 |
|
||||
|
||||
### 4.2 必改现状
|
||||
|
||||
1. `flow.py` create_account:识别 risk 后 `kind="registration_disallowed"`(现误为 `provider`)
|
||||
2. `chatgpt_adapter` allowlist 纳入 `registration_disallowed` / `proxy` / `network` / `fatal`
|
||||
3. `is_proxy_network_failure` 已排除 risk — **保持**;另增 soft-cooldown 路径
|
||||
4. `RegisterResult.error_kind` 注释同步
|
||||
|
||||
### 4.3 `failure_class`(mail 细分,不进 error_kind 爆炸)
|
||||
|
||||
| failure_class | 何时 |
|
||||
|---|---|
|
||||
| `no_mail` | 窗口内 0 封新信 |
|
||||
| `parse_fail` | 有信无 OTP |
|
||||
| `stale_code` | 码过期/已用 |
|
||||
| `imap_error` | IMAP 层错误(auth 可升 fatal) |
|
||||
| `aborted` | 外部中止 |
|
||||
|
||||
`error_kind` 仍多为 `mail_miss`;细分在 `artifacts["otp_wait"]`。
|
||||
|
||||
## 5. OTP diagnostics 数据模型
|
||||
|
||||
```python
|
||||
@dataclass(slots=True)
|
||||
class OtpWaitDiagnostics:
|
||||
poll_count: int = 0
|
||||
message_scan_count: int = 0
|
||||
empty_rounds: int = 0
|
||||
elapsed_seconds: float = 0.0
|
||||
timeout_s: float = 0.0
|
||||
first_message_seen_at: float | None = None
|
||||
matched_at: float | None = None
|
||||
first_seen_after_seconds: float | None = None
|
||||
matched_after_seconds: float | None = None
|
||||
abort_reason: str = ""
|
||||
failure_class: str = "" # no_mail | parse_fail | stale_code | imap_error | aborted | ""
|
||||
provider: str = ""
|
||||
sender_hint: str = ""
|
||||
notes: str = ""
|
||||
```
|
||||
|
||||
**挂载:**
|
||||
|
||||
- `MailMissError.diagnostics: OtpWaitDiagnostics | None`(`str(exc)` 行为不变)
|
||||
- Source 实例可选 `last_wait_diagnostics`
|
||||
- Adapter:`artifacts["otp_wait"] = asdict(diag)`;public 路径无 raw MIME/token
|
||||
- ChatGPT flow 记 `otp_sent_at` 供延迟字段
|
||||
|
||||
**EmailSource Protocol:** 不强制改 `poll_otp` 签名;约定 `last_wait_diagnostics` 属性。
|
||||
|
||||
## 6. 邮件 / 代理分离
|
||||
|
||||
### 6.1 现状问题
|
||||
|
||||
`chatgpt_adapter` 把 **注册 proxy** 传入 `get_email_source(..., proxy=proxy)` → `TinyhostSource` 经 ProxyHandler 走同一出口;邮件 API 与 OpenAI 风险出口耦合。zhuce 对邮箱路径 `del proxy` 直连。
|
||||
|
||||
### 6.2 规则
|
||||
|
||||
| 路径 | 默认 proxy |
|
||||
|---|---|
|
||||
| OpenAI register(curl_cffi session) | 注册 egress(PROXY_LIST / nodes / CHATGPT_PROXY) |
|
||||
| EmailSource allocate/poll(HTTP API) | **None(直连)**,除非显式 mail proxy |
|
||||
| Gmail IMAP | 本机 IMAP;不走注册 proxy(现状基本已是) |
|
||||
|
||||
### 6.3 配置
|
||||
|
||||
优先级(mail):
|
||||
|
||||
1. `extra["mail_proxy"]`
|
||||
2. `CHATGPT_MAIL_PROXY` / `EMAIL_PROXY` / `MAIL_PROXY`
|
||||
3. 默认 `""`(直连)
|
||||
|
||||
**禁止** 再把 register proxy 静默塞进 email source kwargs(breaking intentional)。
|
||||
|
||||
Adapter:
|
||||
|
||||
```python
|
||||
mail_proxy = resolve_mail_proxy(extra) # never falls back to register proxy
|
||||
source = get_email_source(name, proxy=mail_proxy or None, ...)
|
||||
```
|
||||
|
||||
`artifacts` 增加:`mail_proxy`(redact)、`register_proxy`(已有 proxy 字段)。
|
||||
|
||||
## 7. 节点时间冷却
|
||||
|
||||
### 7.1 与 quarantine 区别
|
||||
|
||||
| 机制 | 触发 | 效果 | 解除 |
|
||||
|---|---|---|---|
|
||||
| hard quarantine | `fail_count >= MAX` 且 last_ok False | 永久跳过直到 probe ok | `check_all` / 手动 |
|
||||
| soft cooldown | risk / 用后 / network 软失败 | `now < cooldown_until` 时 skip pick | 时间到期 |
|
||||
|
||||
### 7.2 Node 字段(runtime + 可持久化)
|
||||
|
||||
```python
|
||||
cooldown_until: float | None = None # epoch
|
||||
cooldown_reason: str = "" # registration_disallowed | per_use | network | ...
|
||||
```
|
||||
|
||||
### 7.3 API
|
||||
|
||||
```python
|
||||
NodeManager.cooldown(url, seconds: float, reason: str = "", *, persist=True) -> Node | None
|
||||
NodeManager.is_cooling(n: Node) -> bool
|
||||
# enabled_nodes / pick: skip is_cooling
|
||||
```
|
||||
|
||||
默认秒数(env):
|
||||
|
||||
- `REGISTER_NODES_COOLDOWN_PER_USE` 默认 `0`(关闭「每次用完都 cool」,避免小池饿死;zhuce 120s 作可选)
|
||||
- `REGISTER_NODES_COOLDOWN_RISK` 默认 `600`(registration_disallowed)
|
||||
- `REGISTER_NODES_COOLDOWN_NETWORK` 默认 `120`(network fail 在 quarantine 前的 soft 层;仍保留 fail_count)
|
||||
|
||||
### 7.4 `report_attempt_proxy_result` 接线
|
||||
|
||||
- `ok` → clear fail_count;可选 per_use cool(仅 env>0)
|
||||
- `registration_disallowed` → **不** quarantine;`cooldown(RISK)`
|
||||
- `mail_miss` / `captcha` / `verify` / `fatal` → 不 cool、不 quarantine
|
||||
- network → 现有 mark fail + 可选 NETWORK cool
|
||||
|
||||
## 8. ChatGPT 接线清单
|
||||
|
||||
| 文件 | 变更 |
|
||||
|---|---|
|
||||
| `register_core/contracts.py` | `OtpWaitDiagnostics`;error_kind 注释;可选 `ALLOWED_ERROR_KINDS` |
|
||||
| `register_core/errors.py` | `MailMissError.__init__(msg, *, diagnostics=None)` |
|
||||
| `register_core/email/sources/gmail_imap.py` | poll 写 last_wait_diagnostics;auth 分类 |
|
||||
| `register_core/email/sources/tinyhost.py` | poll 循环写 diagnostics;默认可不接 register proxy |
|
||||
| `register_core/nodes/models.py` | cooldown 字段序列化 |
|
||||
| `register_core/nodes/manager.py` | cooldown API;pick 跳过 |
|
||||
| `register_core/util/proxy.py` | risk → soft cool |
|
||||
| `register_core/providers/chatgpt_adapter.py` | mail_proxy 分离;kind allowlist;otp_wait artifacts |
|
||||
| `providers/chatgpt/protocol/flow.py` | registration_disallowed;otp_sent_at 日志 |
|
||||
| `providers/chatgpt/README.md` + `.env.example` | 配置说明 |
|
||||
| 新单测 | taxonomy / diagnostics / mail_proxy / cooldown |
|
||||
|
||||
**不变:** 无 CPA inject;fail-fast 不空转;secrets 不进 git。
|
||||
|
||||
## 9. 配置面
|
||||
|
||||
| 变量 | 默认 | 含义 |
|
||||
|---|---|---|
|
||||
| `CHATGPT_EMAIL_SOURCE` | `gmail_imap` | 邮箱源 |
|
||||
| `CHATGPT_OTP_TIMEOUT` | `180` | 总 OTP 预算(秒) |
|
||||
| `CHATGPT_PROXY` / 节点池 | — | **仅**注册 egress |
|
||||
| `CHATGPT_MAIL_PROXY` / `EMAIL_PROXY` | 空=直连 | 邮件 HTTP API |
|
||||
| `REGISTER_NODES_MAX_FAIL` | `3` | hard quarantine |
|
||||
| `REGISTER_NODES_COOLDOWN_RISK` | `600` | risk soft cool |
|
||||
| `REGISTER_NODES_COOLDOWN_NETWORK` | `120` | network soft cool |
|
||||
| `REGISTER_NODES_COOLDOWN_PER_USE` | `0` | 用后 cool(默认关) |
|
||||
|
||||
## 10. 测试与验收
|
||||
|
||||
### 离线(必须)
|
||||
|
||||
- `test_chatgpt_error_kinds.py`(或扩现有):disallowed 不被抹成 provider
|
||||
- cooldown:RISK cool 后 pick 跳过,到期恢复
|
||||
- mail_proxy:adapter 构造 source 时 kwargs.proxy 不等于 register proxy(除非显式 mail)
|
||||
- diagnostics:mail_miss artifacts 含 `otp_wait.failure_class`
|
||||
- 既有 `test_fail_policy` / `test_cpa_remote_inject` 不回归(ChatGPT 无关也勿破坏)
|
||||
|
||||
### pxed smoke(出号门禁)
|
||||
|
||||
```bash
|
||||
# 解析 GMAIL_* 勿 source 整份 .env
|
||||
COUNT=1 hub register.sh chatgpt 1 # 或项目现行入口
|
||||
```
|
||||
|
||||
期望:
|
||||
|
||||
- 若 `ok=1`:tokens 落盘;无 CPA inject
|
||||
- 若仍失败:SUMMARY/`error_kind` + `otp_wait` 可区分 `no_mail` vs `registration_disallowed` vs `proxy`
|
||||
- 节点不会因 mail_miss 被 quarantine
|
||||
|
||||
## 11. Milestone 执行契约
|
||||
|
||||
```text
|
||||
Milestone:ChatGPT 代码层 OSS 对齐(core-first)
|
||||
目标:G1–G6;尽量实测 ok=1
|
||||
P0/P1:taxonomy + diagnostics + mail/proxy 分离 + soft cooldown + 单测 + smoke
|
||||
不做的 P2/P3:商业邮箱源、CPA inject、大重构、Grok chat 403
|
||||
Manual-required:OpenAI OTP 投递与住宅出口声誉
|
||||
阶段上限:3
|
||||
阶段拆分:
|
||||
1) core 契约 + errors + diagnostics 类型 + 单测骨架
|
||||
2) nodes cooldown + proxy 反馈 + email sources/adapter/flow 接线
|
||||
3) 文档 + 全量相关单测 + pxed smoke 记录
|
||||
验收标准:单测绿;smoke 诊断诚实;出号尽量
|
||||
停止条件:P0/P1 完成或 3 阶段耗尽或外部资产阻塞出号(代码仍可交付)
|
||||
```
|
||||
|
||||
## 12. Risks
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 小节点池 + per_use cool 饿死 | 默认 PER_USE=0 |
|
||||
| diagnostics 泄露 MIME | 只存计数/epoch/failure_class;public redact |
|
||||
| gmail_imap 依赖 grok_register_ttk 黑盒 | 外层包 diagnostics;auth 错误字符串分类 |
|
||||
| 出号仍失败 | 诚实 Manual-required;不放宽 inject |
|
||||
|
||||
## 13. Implementation order
|
||||
|
||||
1. contracts + errors + 常量
|
||||
2. Node cooldown + tests
|
||||
3. proxy report 接线
|
||||
4. gmail_imap / tinyhost diagnostics
|
||||
5. chatgpt adapter mail_proxy + allowlist + artifacts
|
||||
6. flow.py kind + otp_sent_at
|
||||
7. docs/env
|
||||
8. pxed smoke
|
||||
|
||||
Commit 风格:`feat(core): …` / `fix(chatgpt): …` / `test: …` / `docs: …`
|
||||
|
||||
## 14. References
|
||||
|
||||
- pxed smoke memory:`project_pxed_smoke_20260716`
|
||||
- zhuce6:`last_wait_diagnostics`、`del proxy` on mail、proxy_pool cooldown 120/600
|
||||
- 本仓库:`register_core/providers/chatgpt_adapter.py`、`providers/chatgpt/protocol/flow.py`、`register_core/util/proxy.py`
|
||||
@@ -0,0 +1,190 @@
|
||||
# Design: free Build chat 经 tebi CPA 中转 probe
|
||||
|
||||
**Date:** 2026-07-16
|
||||
**Status:** approved approach A (user: `a`)
|
||||
**Repo:** `dengyie/ai-register-machine` (local: grok-register)
|
||||
**Related:** [[Grok 注册机与 free Build CPA]], CPA 文档索引, chat entitlement hard gate (`cpa_xai/probe.py`, `writer.py`)
|
||||
|
||||
---
|
||||
|
||||
## 1. Problem
|
||||
|
||||
注册机 mint 后的 **chat gate** 目前 **本地直连** `https://cli-chat-proxy.grok.com/v1`,手搓 `DEFAULT_CLIENT_HEADERS`(已与 grokbuild-proxy 默认常量对齐)。
|
||||
|
||||
生产客户端则走 **tebi CLIProxyAPI**(`:8317` / `cpa.mangoq.ccwu.cc`):CPA 对 free Build 已具备 rewrite(空 / `api.x.ai` → cli-chat-proxy)与 CLI 头注入。
|
||||
|
||||
结果:
|
||||
|
||||
- **双身份路径**:gate 测的是「注册机 + 直连 + 本地头」;线上成功定义是「CPA 中转」。
|
||||
- backlog「grokbuild-proxy / CLIProxyAPI 中转架构」指的是 **统一 mid-tier**,不是再起一个与 tebi CPA 平行的 grokbuild-proxy 生产面。
|
||||
- **L4 403 entitlement** 仍是账号侧问题;中转 **不能** 当解锁手段。
|
||||
|
||||
## 2. Goals
|
||||
|
||||
1. 产品级 `chat_ok` / inject 门禁的 probe,默认经 **现有 tebi CPA** 中转(与 live 路径一致)。
|
||||
2. 写入的 `xai-*.json` 仍保持 CPA 期望的上游 `base_url`(cli-chat-proxy),不把公网 CPA URL 写进 auth 文件。
|
||||
3. 保持现有产品规则:hard gate、`entitlement_denied` fail-fast、禁止无 `chat_ok` live inject。
|
||||
4. 保留 debug 直连开关,便于区分「号问题」与「CPA/网络问题」。
|
||||
|
||||
## 3. Non-goals
|
||||
|
||||
| 不做 | 原因 |
|
||||
|---|---|
|
||||
| 修复 L4 permission-denied | 账号 entitlement / console.x.ai;Manual-required |
|
||||
| 软化 `probe_chat` hard gate | 用户明确保持 |
|
||||
| 部署独立 grokbuild-proxy 服务 | 与 tebi CPA free Build 能力重叠;运维成本高 |
|
||||
| 改 OAuth mint(PKCE / device) | mint 仍打 auth.x.ai;中转只覆盖 **probe HTTP** |
|
||||
| 在 pxed 起生产 CPA | 生产只在 tebi |
|
||||
| 第三方 GrokFree 中转 token | 与官方 OAuth free Build 无关 |
|
||||
|
||||
## 4. Decision
|
||||
|
||||
**选用方案 A:经现有 tebi CLIProxyAPI 做 mid-tier probe。**
|
||||
|
||||
放弃方案 B(独立 grokbuild-proxy)作为本 milestone 交付。
|
||||
方案 C(双 probe)仅以配置开关形式保留诊断能力,不当第二真相源。
|
||||
|
||||
### 4.1 为什么是 A
|
||||
|
||||
- tebi CPA **已支持** free Build rewrite + CLI 身份。
|
||||
- 注册机已有 `cpa_remote_inject` → tebi live/inventory 的运维路径;中转应复用同一生产面。
|
||||
- 头对齐(`grok-pager` / dual UA)已在 `cpa_xai/schema.py` 完成;剩余是 **路径统一**,不是再抄一套 client.go。
|
||||
|
||||
## 5. Architecture
|
||||
|
||||
```text
|
||||
Mac 开发
|
||||
↔ pxed /personal/grok-register (注册 + mint + probe)
|
||||
↔ tebi /personal/cpa + /root/.cli-proxy-api (生产 CPA :8317)
|
||||
公网 cpa.mangoq.ccwu.cc → tebi CPA
|
||||
|
||||
[mint]
|
||||
SSO/PKCE → access_token → write cpa_auths/xai-<email>.json
|
||||
base_url = https://cli-chat-proxy.grok.com/v1 # 上游,供 CPA rewrite
|
||||
|
||||
[probe 默认 cpa_probe_via=cpa]
|
||||
registerer → CPA OpenAI-compatible base (cpa.mangoq.ccwu.cc/v1 或 tunnel)
|
||||
+ CPA API key
|
||||
+ 必须钉到「本账号」凭据(见 §6)
|
||||
→ CPA → cli-chat-proxy(rewrite + headers)
|
||||
→ classify → stamp chat_ok / entitlement_denied / …
|
||||
|
||||
[probe debug cpa_probe_via=direct]
|
||||
registerer → cli-chat-proxy + DEFAULT_CLIENT_HEADERS + Bearer access_token
|
||||
(现行为;保留)
|
||||
|
||||
[inject]
|
||||
仅 chat_ok → live /root/.cli-proxy-api + inventory /personal/cpa/auths
|
||||
cpa_remote_inject_require_chat_ok=true 不变
|
||||
```
|
||||
|
||||
## 6. Credential pinning(P0 语义)
|
||||
|
||||
CPA 默认从 **池** 选 xAI 凭据。若 probe 不钉死「刚 mint 的 email」,会出现:
|
||||
|
||||
- **假阳性**:池里别的 chat_ok 号替测 → 错误 inject
|
||||
- **假阴性**:池里坏号挡枪 → 误杀好号
|
||||
|
||||
### 6.1 策略顺序(实现时按序探测能力)
|
||||
|
||||
1. **Preferred — 管理/API 按 credential 路由**
|
||||
若 tebi 当前 CPA 版本支持按 auth 文件名 / email / credential_id 指定上游凭据:probe 必须带该标识。
|
||||
2. **Fallback — inventory-only + 钉凭据**
|
||||
gate 前只允许写 inventory,不写 live;probe 仍钉该文件。
|
||||
3. **Hybrid(能力不足时的安全默认)**
|
||||
- **账号门禁**(`chat_ok` / `entitlement_denied` stamp)继续 **direct** + 本 token
|
||||
- **中转验证**:inject 后(或 inventory 写入后)再打一枪 CPA 路径 smoke,结果写入可选字段(如 `probe_via_cpa_ok`),**不得**单独作为 inject 放行条件替代 `chat_ok`
|
||||
|
||||
实现计划必须 **先核实 tebi CPA 是否可钉凭据**;不可钉则交付 hybrid,并在 ops 文档标明。
|
||||
|
||||
### 6.2 禁止
|
||||
|
||||
- 为了 probe 先 live inject 再测(循环依赖 + 污染 live 池)
|
||||
- 用池级任意成功响应给当前 email 盖 `chat_ok=true`
|
||||
|
||||
## 7. Config surface
|
||||
|
||||
新增(示例;默认值以实现计划冻结为准):
|
||||
|
||||
| Key | 含义 |
|
||||
|---|---|
|
||||
| `cpa_probe_via` | `cpa` \| `direct`(推荐默认:能力确认后 `cpa`,否则 hybrid 下门禁仍 direct) |
|
||||
| `cpa_probe_base_url` | CPA 对外 OpenAI base,如 `https://cpa.mangoq.ccwu.cc/v1` |
|
||||
| `cpa_probe_api_key` | 调用 CPA 的 API key(非 xAI access_token) |
|
||||
| `cpa_base_url` | **不变语义**:写入 auth 与 direct probe 的上游 base(cli-chat-proxy) |
|
||||
| `cpa_probe_chat` / `cpa_probe_chat_required` | 不变,硬门禁默认 true |
|
||||
|
||||
密钥:优先 env / 已有 secrets 约定;禁止提交真实 key。`config.example.json` 只写注释与占位。
|
||||
|
||||
## 8. Code touch map(实现阶段,非本 spec 交付代码)
|
||||
|
||||
| 区域 | 变更方向 |
|
||||
|---|---|
|
||||
| `cpa_xai/probe.py` | 抽象 transport:`direct_bearer` vs `cpa_openai`;分类逻辑复用 `classify_chat_probe` |
|
||||
| `cpa_xai/mint.py` / `cpa_export.py` | 从 config 传入 probe via / base / key;stamp 字段集合不变 |
|
||||
| `scripts/backfill_chat_stamps.py` | 同 transport,避免 backfill 与 mint 分叉 |
|
||||
| `config.example.json` | 文档化新键 |
|
||||
| 测试 | mock 两种 transport;inject hard gate 仍要求 `chat_ok`;403 仍 entitlement |
|
||||
| Obsidian | 更新「Grok 注册机与 free Build CPA」:mid-tier = tebi CPA |
|
||||
|
||||
**不改:** OAuth PKCE/device、remint skip denied、ledger、`build_chat_stamp_from_result` 禁止 null `chat_ok`。
|
||||
|
||||
## 9. Failure mapping
|
||||
|
||||
| 现象 | 产品分类 | 动作 |
|
||||
|---|---|---|
|
||||
| `/responses` 403 permission-denied | `entitlement_denied` | stamp + ledger;不 remint;不 inject |
|
||||
| 直连 426 version outdated | `auth_or_protocol` | 查头;非账号农场 |
|
||||
| CPA API key 401/403 | 运维配置错误 | 不标 entitlement_denied |
|
||||
| CPA 502 / timeout / 429 中转层 | `transient` / retryable(按现有策略) | 可重试;不 inject |
|
||||
| free-usage-exhausted | `usage_exhausted` | 不 inject;非 entitlement |
|
||||
| 钉不住凭据且未走 hybrid | **实现阻断** | 禁止默认真 `cpa` 门禁 |
|
||||
|
||||
## 10. Risks & mitigations
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 假 `chat_ok`(错凭据) | §6 pinning;否则 hybrid |
|
||||
| pxed→tebi 网络不稳 | 与 inject 同 tunnel(tebi-tunnel);timeout/retry 对齐 |
|
||||
| 双模式分叉 | 单入口 `probe_*` + transport 参数;单测强制两路径分类一致 |
|
||||
| 把中转当成 L4 解药 | 文档 + 验收:denied 号经 CPA 仍 denied |
|
||||
|
||||
## 11. Acceptance criteria
|
||||
|
||||
1. 现有 entitlement / remint / inject / inventory 单测全过。
|
||||
2. 配置 `cpa_probe_via=direct`:行为与当前生产一致(回归)。
|
||||
3. 在 **可钉凭据** 或 **hybrid** 约定下:
|
||||
- 已知 denied 号 → `entitlement_denied`,无 remint 空转
|
||||
- 已知 chat_ok 号 → stamp 后可 inject;经 CPA 客户端 MINT_OK
|
||||
4. auth 文件 `base_url` 仍为 cli-chat-proxy,不被改成 cpa.mangoq。
|
||||
5. 无真实 secret 进入 git。
|
||||
|
||||
## 12. Rollout sketch
|
||||
|
||||
1. 核实 tebi CPA 钉凭据能力(read-only / 文档 / 管理 API)。
|
||||
2. 实现 transport + config + 测试。
|
||||
3. 默认:若可钉 → `cpa`;否则 hybrid + 文档。
|
||||
4. pxed 部署注册机;小流量 backfill/smoke。
|
||||
5. 更新 Obsidian free Build 文与 CPA 索引交叉链接。
|
||||
|
||||
## 13. Open questions (implementation, not design blockers)
|
||||
|
||||
1. tebi 当前 `eceasy/cli-proxy-api` 版本是否暴露 per-credential 路由头/管理字段?
|
||||
2. probe 走公网 `cpa.mangoq.ccwu.cc` 还是 SSH 隧道内网 `:8317`(延迟/鉴权差异)?
|
||||
3. hybrid 时 `probe_via_cpa_ok` 是否写入 auth 文件(可选观测字段)?
|
||||
|
||||
默认实现倾向:优先 tunnel/内网与 inject 一致;观测字段可进 stamp 但不进 inject 门闩。
|
||||
|
||||
## 14. Spec self-review
|
||||
|
||||
- [x] 无 TBD 作为核心行为空洞(open questions 仅实现选型)
|
||||
- [x] 与 hard gate / inject 规则无矛盾
|
||||
- [x] 范围单 milestone:probe 中转统一,不扩 OAuth/新服务
|
||||
- [x] 钉凭据失败路径有明确 hybrid,避免 silent wrong gate
|
||||
|
||||
---
|
||||
|
||||
## Approval
|
||||
|
||||
- Approach: **A** (user message `a`, 2026-07-16)
|
||||
- Next: user review of this file → `writing-plans` → implementation milestone (P0/P1 only)
|
||||
@@ -0,0 +1,117 @@
|
||||
# Target-Aware Node Preflight (L1 ∧ L2) Design
|
||||
|
||||
**Date:** 2026-07-17
|
||||
**Status:** Approved (user: make small milestone + development docs; strategy-group domain preflight before inject)
|
||||
**Goal:** Before seeding the register rotation pool from `nodes.json`, live-probe not only generic egress (ipify) but the **business domains required by the current provider**, and inject only the dual-pass subset.
|
||||
|
||||
## Context
|
||||
|
||||
### Evidence (2026-07-17)
|
||||
|
||||
- Imported auth proxies: **299 unique → pxed probe ok=258** (L1 = `api.ipify.org`).
|
||||
- Grok smoke with one random L1-healthy list node: browser **ERR_EMPTY_RESPONSE / RST** on `accounts.x.ai`.
|
||||
- Sample of 40 L1-healthy catalog nodes → **0** reachable for `accounts.x.ai` (almost all Connection reset).
|
||||
- Clash mixed-port `127.0.0.1:7897` → `accounts.x.ai` **200**.
|
||||
|
||||
Root cause: product “healthy” was **shallow** — “can egress to ipify” ≠ “can reach registration target”.
|
||||
|
||||
### Dual backends (unchanged)
|
||||
|
||||
| Backend | Entry | Probe | Scope of this milestone |
|
||||
|---------|-------|-------|-------------------------|
|
||||
| Clash mihomo (pxed Grok prod) | `preflight-clash-nodes.sh` | controller delay API + strategy groups | **Out of scope** (already target-group aware) |
|
||||
| `nodes.json` list\|auto | `preflight_nodes_for_register` | HTTP via proxy | **In scope** — add L2 business targets |
|
||||
|
||||
## Architecture
|
||||
|
||||
```text
|
||||
nodes import → catalog (schema; optional L1 --check)
|
||||
│
|
||||
pipeline.run(egress=list|auto, provider=P)
|
||||
│
|
||||
preflight_nodes_for_register
|
||||
resolve_probe_targets(P | extra | env)
|
||||
│
|
||||
for each candidate node (smart order, limit):
|
||||
L1: GET https://api.ipify.org?format=json → require 2xx + optional IP
|
||||
L2: GET each business URL through same proxy
|
||||
→ require *transport success* (any HTTP status OK)
|
||||
→ fail on RST / tunnel timeout / empty / connect error
|
||||
│
|
||||
pool_ready = L1 ∧ L2
|
||||
│
|
||||
seed proxy_list = pool_ready only
|
||||
0 pool_ready on list|required → FailFastError (no account burn)
|
||||
│
|
||||
register attempts on pool_ready only
|
||||
│
|
||||
runtime proxy/network fail (incl. ERR_EMPTY_RESPONSE)
|
||||
→ mark/cool/quarantine proxy; never burn email domain
|
||||
```
|
||||
|
||||
### Health layers
|
||||
|
||||
| Layer | Probe | Pass rule | Mutates `last_ok` |
|
||||
|-------|-------|-----------|-------------------|
|
||||
| **L1** egress | `DEFAULT_PROBE_URL` (ipify) | HTTP 2xx | **Yes** (catalog stamp) |
|
||||
| **L2** target | provider business URL(s) | TCP/TLS/HTTP response received (status ignored) | **No** — filters pool only |
|
||||
| **L3** runtime | register outcome | existing `report_attempt_proxy_result` | fail_count / cool / quarantine |
|
||||
|
||||
**Why L2 ignores HTTP status:** registration targets often return 302/403/426 without cookies/CLI headers. That still proves the proxy can open the path. RST / `ERR_EMPTY_RESPONSE` is the failure mode we observed.
|
||||
|
||||
### Default target map (strategy-group analogue)
|
||||
|
||||
| Provider aliases | Default L2 URL(s) |
|
||||
|------------------|-------------------|
|
||||
| `grok`, `xai` | `https://accounts.x.ai/` |
|
||||
| `chatgpt`, `openai` | `https://auth.openai.com/` |
|
||||
| `mimo`, `xiaomi`, `mimo-tts` | `https://api.xiaomimimo.com/` |
|
||||
| unknown / empty | L1 only (backward compatible) |
|
||||
|
||||
### Override order (highest first)
|
||||
|
||||
1. `extra["probe_targets"]` / `extra["nodes_probe_targets"]` — list or comma string
|
||||
2. Env `REGISTER_NODES_PROBE_TARGETS` / `NODES_PROBE_TARGETS` — comma URLs
|
||||
3. Provider map from `extra["provider"]` / `extra["_provider"]` (pipeline injects `self.provider.name`)
|
||||
4. Empty → L1-only (legacy)
|
||||
|
||||
`REGISTER_NODES_PROBE_TARGETS=0` or `none` disables L2 explicitly.
|
||||
|
||||
## Module plan
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `register_core/nodes/targets.py` | **New** — map + `resolve_probe_targets` |
|
||||
| `register_core/nodes/health.py` | `probe_reachable`; `probe_node_layered` (L1∧L2) |
|
||||
| `register_core/nodes/manager.py` | `check_all` / `preflight` accept `probe_urls`; pool from result when L2 on |
|
||||
| `register_core/util/proxy.py` | resolve targets; pass into manager; empty_response markers |
|
||||
| `register_core/pipeline.py` | stash `provider` name on extra before preflight |
|
||||
| `register_core/nodes/README.md` + `ARCHITECTURE.md` | product contract L1/L2 |
|
||||
| `test_register_core_nodes.py` | L2 filter + empty pool fail-fast + resolve map |
|
||||
|
||||
## Non-goals (P2/P3 backlog)
|
||||
|
||||
- Clash strategy-group rewrite inside monorepo preflight
|
||||
- Persist `last_ok_by_target` on Node (runtime filter is enough for M1)
|
||||
- AND across many L2 URLs beyond first resolved set (defaults are 1 URL)
|
||||
- Soft-inject CPA on chat 403
|
||||
- Changing import to require L2
|
||||
|
||||
## Manual-required
|
||||
|
||||
- Grok production on pxed: keep **Clash 7897** until an L2-ready catalog pool is non-empty for `accounts.x.ai`.
|
||||
- Free Build chat 403 remains account entitlement, unrelated to this milestone.
|
||||
|
||||
## Acceptance
|
||||
|
||||
1. Unit: L1-only path unchanged when no provider/targets.
|
||||
2. Unit: L1 pass + L2 fail → URL **not** in seeded `proxy_list`.
|
||||
3. Unit: all L2 fail on `egress=list` → `FailFastError`.
|
||||
4. Unit: pipeline/extra provider `grok` resolves `accounts.x.ai`.
|
||||
5. Docs: ARCHITECTURE + nodes README describe L1∧L2 gate.
|
||||
6. Runtime markers include empty response / connection reset language.
|
||||
|
||||
## Git
|
||||
|
||||
Single commit preferred:
|
||||
`feat(nodes): target-aware L1+L2 preflight before pool inject`
|
||||
@@ -0,0 +1,252 @@
|
||||
# Register Profile Config Abstraction Design
|
||||
|
||||
**Date:** 2026-07-17
|
||||
**Status:** Approved (approach 1; user: continue without pause)
|
||||
**Goal:** Drive the whole register machine from one profile: mailbox, decode, provider, strategy (runtime + risk), verify, sink, secrets.
|
||||
|
||||
## Context
|
||||
|
||||
Today layers exist (`email/*`, `providers/*`, `verify/*`, `pipeline`) but wiring is scattered across CLI flags, env vars, and `RegisterJob.extra`. ChatGPT is in-process; Grok/MiMo are black-box and ignore `EmailSource`. Operators want:
|
||||
|
||||
1. **Decode** — CF Worker / Gmail / … as config
|
||||
2. **Register** — target site as config
|
||||
3. **Strategy** — runtime + risk/asset policy as config
|
||||
4. **Mailbox** — address allocation separate from decode
|
||||
|
||||
Decisions locked in brainstorming:
|
||||
|
||||
| Topic | Choice |
|
||||
|-------|--------|
|
||||
| Strategy | **D** — runtime + risk/burn in `strategy`; product params on provider |
|
||||
| Config form | **A** — one YAML/JSON profile is authority |
|
||||
| Product scope | **B** — all three products truly share mailbox+decode (phased) |
|
||||
| Mailbox vs decode | **B** — split two layers |
|
||||
| Secrets | **C** — dev may plaintext; prod forces `*_env` refs |
|
||||
| Architecture | **Approach 1** — Profile → RuntimeBundle four-layer runtime |
|
||||
|
||||
## Architecture (end state)
|
||||
|
||||
```text
|
||||
profiles/<name>.yaml # single run authority
|
||||
│
|
||||
ProfileLoader (schema + secrets resolve + CLI overrides)
|
||||
│
|
||||
RuntimeBundle
|
||||
├─ MailboxProvider allocate / release only
|
||||
├─ OtpDecoder wait_otp(mailbox) only
|
||||
├─ RegisterProvider site protocol; consumes mailbox+decoder
|
||||
├─ StrategyEngine fail-fast, egress, burn/cool, mail≠register proxy
|
||||
└─ Verifier + Sink
|
||||
│
|
||||
Pipeline.run(count)
|
||||
```
|
||||
|
||||
### Hard boundaries (production discipline)
|
||||
|
||||
1. Mail proxy never inherits register egress.
|
||||
2. Fail-fast on configured `error_kind`s; no empty retry same IP+domain class.
|
||||
3. Success = this-run attribution only.
|
||||
4. No soft-inject without verify pass.
|
||||
5. Prod profiles: no plaintext secrets.
|
||||
6. Three products share the same Pipeline contracts eventually.
|
||||
|
||||
## Profile schema (v1)
|
||||
|
||||
```yaml
|
||||
# profiles/chatgpt-cf-clash.example.yaml
|
||||
apiVersion: register.v1
|
||||
kind: RegisterProfile
|
||||
metadata:
|
||||
name: chatgpt-cf-clash
|
||||
description: ChatGPT via CF Worker mailbox+decode, Clash egress
|
||||
|
||||
spec:
|
||||
provider:
|
||||
name: chatgpt # chatgpt | grok | mimo
|
||||
# product-local knobs only
|
||||
options:
|
||||
otp_timeout_s: 180
|
||||
headless: true # ignored by chatgpt; used by grok/mimo later
|
||||
|
||||
count: 1
|
||||
|
||||
mailbox:
|
||||
type: cloudflare # cloudflare | tinyhost | gmail_imap | duckmail | local_part
|
||||
# type-specific:
|
||||
domain: mangoqwq.com # optional pin for tinyhost/local_part
|
||||
# local: random | fixed:<name>
|
||||
|
||||
decode:
|
||||
type: cloudflare # cloudflare | gmail_imap | tinyhost | duckmail
|
||||
options:
|
||||
timeout_s: 180
|
||||
poll_interval_s: 2.5
|
||||
sender_hint: "" # optional
|
||||
|
||||
strategy:
|
||||
fail_fast: true
|
||||
fail_fast_kinds:
|
||||
- registration_disallowed
|
||||
- unsupported_email
|
||||
- fatal
|
||||
- verify
|
||||
egress:
|
||||
mode: clash # auto | core | clash | list | direct
|
||||
proxy: "http://127.0.0.1:7897" # optional fixed
|
||||
proxy_list: "" # path or comma URLs
|
||||
rotate_every: 1
|
||||
rotate_required: false
|
||||
mail_proxy: direct # direct | url | env:MAIL_PROXY
|
||||
burn:
|
||||
enabled: true
|
||||
track: [ip, domain]
|
||||
on_kinds: [registration_disallowed, unsupported_email]
|
||||
state_path: ".register/burn_state.json" # optional; empty = memory only
|
||||
cool:
|
||||
soft_seconds: 0 # 0 = off in M1
|
||||
|
||||
verify:
|
||||
enabled: true
|
||||
name: auto # auto = provider default; or noop
|
||||
|
||||
sink:
|
||||
path: "providers/chatgpt/output/pipeline.jsonl" # empty = no sink
|
||||
|
||||
secrets:
|
||||
mode: prod # dev | prod
|
||||
# prod: only env refs allowed for secret fields
|
||||
# map used by mailbox/decode constructors:
|
||||
# cloudflare_api_base_env: CLOUDFLARE_API_BASE
|
||||
# cloudflare_api_key_env: CLOUDFLARE_API_KEY
|
||||
```
|
||||
|
||||
### Compatibility aliases
|
||||
|
||||
- `mailbox.type` / `decode.type`: `cf` → `cloudflare`, `gmail` → `gmail_imap`
|
||||
- If only legacy `email_source: cloudflare` is present (CLI path), loader builds matching mailbox+decode pair of the same type (paired mode).
|
||||
|
||||
### Paired vs split
|
||||
|
||||
| Mode | Meaning |
|
||||
|------|---------|
|
||||
| **paired** | mailbox.type == decode.type and both talk to same backend (CF allocate + CF poll). Default for M1 adapters. |
|
||||
| **split** | Different types (e.g. mailbox local_part@mangoqwq.com + decode gmail_imap). Allowed when both layers can cooperate on the same address. |
|
||||
|
||||
M1 implements paired fully; split is validated only when both types support `Mailbox.token` / address contract (documented per pair). Unsupported splits fail-fast at load.
|
||||
|
||||
## Interfaces
|
||||
|
||||
### MailboxProvider
|
||||
|
||||
```python
|
||||
class MailboxProvider(Protocol):
|
||||
name: str
|
||||
def allocate(self) -> Mailbox: ...
|
||||
def release(self, mailbox: Mailbox, *, success: bool) -> None: ...
|
||||
```
|
||||
|
||||
### OtpDecoder
|
||||
|
||||
```python
|
||||
class OtpDecoder(Protocol):
|
||||
name: str
|
||||
def wait_otp(
|
||||
self,
|
||||
mailbox: Mailbox,
|
||||
*,
|
||||
timeout_s: float = 180,
|
||||
poll_interval_s: float = 3,
|
||||
used_codes: set[str] | None = None,
|
||||
newer_than_epoch: float | None = None,
|
||||
sender_hint: str | None = None,
|
||||
) -> OtpCode: ...
|
||||
# optional: last_wait_diagnostics
|
||||
```
|
||||
|
||||
### Composite EmailSource (compat bridge)
|
||||
|
||||
```python
|
||||
class CompositeEmailSource:
|
||||
"""EmailSource façade over MailboxProvider + OtpDecoder for existing adapters."""
|
||||
name: str # f"{mailbox.name}+{decode.name}" or single if paired
|
||||
def allocate(...): return mailbox.allocate()
|
||||
def poll_otp(...): return decoder.wait_otp(...)
|
||||
def release(...): return mailbox.release(...)
|
||||
```
|
||||
|
||||
Existing `ChatGPTProvider` keeps accepting `EmailSource`; Pipeline injects `CompositeEmailSource` from profile. No adapter rewrite required for M1.
|
||||
|
||||
### StrategyEngine (M2 full; M1 subset)
|
||||
|
||||
M1: read fail_fast + egress + mail_proxy from profile into `RegisterJob` / `extra` (same keys pipeline already understands).
|
||||
M2: burn state file + feedback hooks centralized (today partially in proxy util + ops scripts).
|
||||
|
||||
### RegisterProvider (unchanged signature M1)
|
||||
|
||||
```python
|
||||
def register_one(*, email_source: EmailSource | None = None, extra: dict | None = None) -> RegisterResult
|
||||
```
|
||||
|
||||
M3/M4: Grok/MiMo must consume injected EmailSource (composite); black-box internal mail becomes fallback only when profile says `mailbox.type: provider` / `decode.type: provider`.
|
||||
|
||||
## Loader rules
|
||||
|
||||
1. Accept `.yaml` / `.yml` / `.json`.
|
||||
2. `apiVersion` must be `register.v1`.
|
||||
3. Resolve secrets:
|
||||
- `secrets.mode=prod`: any field ending in secret-like names must be env ref or empty; plaintext non-empty secrets → load error.
|
||||
- `dev`: plaintext allowed.
|
||||
4. CLI overrides (non-secret): `--count`, `--no-verify`, `--egress`, `--proxy`, `--sink`, `--no-fail-fast`.
|
||||
5. Env still fills constructor secrets when profile uses `*_env` keys or legacy env (CLOUDFLARE_API_BASE, GMAIL_IMAP_*).
|
||||
6. Output: `RegisterJob` + resolved RuntimeBundle metadata in `job.extra["_profile"]` (name, path, mailbox, decode types — no secrets).
|
||||
|
||||
## CLI
|
||||
|
||||
```bash
|
||||
# New (preferred)
|
||||
python -m register_core run --profile profiles/chatgpt-cf-clash.yaml
|
||||
|
||||
# Legacy flags still work (build ephemeral profile in memory)
|
||||
python -m register_core run -p chatgpt --email-source cloudflare -n 1 --egress clash
|
||||
```
|
||||
|
||||
When both `--profile` and `-p` are set: profile is base; CLI provider must match or fail-fast.
|
||||
|
||||
## Data flow (one attempt)
|
||||
|
||||
1. Strategy preflight egress (existing nodes preflight).
|
||||
2. Strategy inject attempt proxy into `extra`.
|
||||
3. Provider `register_one(email_source=composite, extra=...)`.
|
||||
4. composite.allocate → site protocol → composite.poll_otp → token.
|
||||
5. Verifier; Sink; Strategy feedback (burn on configured kinds).
|
||||
|
||||
## Migration milestones
|
||||
|
||||
| ID | Deliverable | Done when |
|
||||
|----|-------------|-----------|
|
||||
| **M1** | Schema + Loader + Mailbox/Decode protocols + Composite + ChatGPT via `--profile` | unit tests; offline load; ChatGPT path equivalent to flags |
|
||||
| **M2** | StrategyEngine burn/cool state | burn file updates on registration_disallowed without residual shell |
|
||||
| **M3** | MiMo consumes EmailSource | profile can switch CF/Gmail for MiMo |
|
||||
| **M4** | Grok consumes EmailSource | same |
|
||||
|
||||
## Non-goals (this design)
|
||||
|
||||
- Soft inject / remint spin
|
||||
- Hotmail plus-alias farm
|
||||
- Unifying Grok Drission DOM into curl_cffi
|
||||
- Live chat entitlement unlock
|
||||
- Plugin marketplace / DAG workflow language
|
||||
|
||||
## Testing (M1)
|
||||
|
||||
- Load example profiles (dev + prod secret rejection)
|
||||
- Composite allocate/poll delegates
|
||||
- Pipeline.from_job still works with legacy email_source
|
||||
- Pipeline.from_profile builds job with mail_proxy + egress
|
||||
- ChatGPT verifier still accepts rt.1
|
||||
|
||||
## Example profiles shipped
|
||||
|
||||
- `profiles/chatgpt-cf.example.yaml`
|
||||
- `profiles/chatgpt-tinyhost.example.yaml`
|
||||
- `profiles/chatgpt-gmail.example.yaml`
|
||||
@@ -0,0 +1,37 @@
|
||||
# Grok Register Deployment Experience (2026-07-29)
|
||||
|
||||
## Overview
|
||||
Deployment of the grok-register project follows a **manual scp** model rather than full CI/CD for the Python batch layer. The `deploy.yml` CI pipeline only builds and ships the **console10 static SPA** to `/data/grok-register/apps/web` on pxed. The 4 core Python files (`node_score.py`, `proxy_rotate.py`, `mail_pool_probe.py`, `register_cli.py`) are **manually scp'd** to `pxed:/data/grok-register/` after each merge (or after relevant changes). The pxed tree is a **live directory** — not a git checkout — so there is no `git pull`; files are overwritten in place.
|
||||
|
||||
## Deployment Steps
|
||||
1. After a feature branch (e.g. `feat/email-ip-correlation`) is merged to main via PR, the changed Python files are scp'd:
|
||||
```bash
|
||||
scp node_score.py proxy_rotate.py mail_pool_probe.py register_cli.py pxed:/data/grok-register/
|
||||
```
|
||||
(or `scp register_cli <host>` pattern used historically)
|
||||
|
||||
2. The SPA is auto-deployed by CI (`deploy.yml` only affects `/apps/web`).
|
||||
|
||||
3. No git operations on pxed — atomic `.next`→rename on SPA side; Python files overwritten directly.
|
||||
|
||||
## Current pxed State (post-merge)
|
||||
- Files overwritten to merged-main sizes (e.g. node_score.py:590, proxy_rotate.py:1408, etc.)
|
||||
- `py_compile` succeeds
|
||||
- `correlation_enabled()` = `False` (OFF by default — `EMAIL_IP_CORRELATION` unset in `.env`/`config.json`)
|
||||
- `_registration_domain` = ''; no `register_cli` running
|
||||
- Batch remains inert until operator sets `EMAIL_IP_CORRELATION=1` + restarts the batch process.
|
||||
|
||||
## Activation
|
||||
To enable the email×IP correlation feature:
|
||||
```bash
|
||||
# On host or via console
|
||||
set EMAIL_IP_CORRELATION=1 in .env or config.json
|
||||
# Restart batch supervisor / relevant process
|
||||
```
|
||||
|
||||
## Related
|
||||
- See [[project_email_ip_correlation_merge_deploy_20260729.md]] for full merge+deploy notes
|
||||
- SPA auto-deploy documented in [[project_console10_ci_deploy_20260725.md]]
|
||||
- Manual scp pattern confirmed across prior deploys (e.g. [[project_full_pool_mail_probe_deploy_20260727.md]])
|
||||
|
||||
**Note to self:** Always verify `correlation_enabled()` after scp and before next batch run. Feature ships OFF-by-default per spec.
|
||||
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」默认折叠
|
||||
- 窄屏(<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 和计数分支。
|
||||
Reference in New Issue
Block a user