Spaces:
Paused
Paused
feat: AutoTeam 大版本升级:安全轮换、并行、IPv6、指纹加固与前端重构
Browse files- 安全轮换逻辑:先踢人再换人,降低轮转冲突和失败回弹
- 并行能力:同步、注册与目标分发链路并发化,整体吞吐更高
- IPv6 支持:接入 IPv6 代理池与状态面,扩展可用出口
- 更安全的指纹:统一浏览器上下文与启动/会话参数,减少特征暴露
- 轮转增强:速度与安全性双提升,轮转后凭证即时同步到配置目标
- 更好的前端:Dashboard / Settings / Sync / Task 视图全面重构,实时性、信息密度和可读性提升
- 同步与诊断:统一 sync_targets 分发层,增强主号、注册和轮转后的诊断与目标同步
Files changed (44)
- .env.example+22
- src/autoteam/accounts.py+29-4
- src/autoteam/api.py+27-7
- src/autoteam/codex_auth.py+1-3
- src/autoteam/config.py+25
- src/autoteam/cpa_sync.py+93-30
- src/autoteam/invite.py+2-5
- src/autoteam/manager.py+51-1
- src/autoteam/sub2api_sync.pyAdded+1049
- src/autoteam/sync_targets.pyAdded+278
- src/autoteam/web/dist/assets/index-BSht6bmF.jsAdded
- src/autoteam/web/dist/assets/index-BZ-R3x09.jsDeleted
- src/autoteam/web/dist/assets/index-DHotZNsL.css → src/autoteam/web/dist/assets/index-CbNAiyvN.cssRenamed+1-1
- src/autoteam/web/dist/index.html+2-2
- tests/unit/test_accounts.py+24
- tests/unit/test_api_playwright_cleanup.py+59-2
- tests/unit/test_cpa_sync.py+124
- tests/unit/test_sub2api_sync.pyAdded+659
- tests/unit/test_sync_targets.pyAdded+110
- web/src/App.vue+41-88
- web/src/api.js+5-1
- web/src/components/AtButton.vue+6-6
- web/src/components/Dashboard.vue+240-94
- web/src/components/HealthDonut.vue+3-3
- web/src/components/LogViewer.vue+36-21
- web/src/components/MailProviderCard.vue+21-21
- web/src/components/MasterHealthBanner.vue+34-60
- web/src/components/OAuthPage.vue+21-21
- web/src/components/PoolHealthCard.vue+33-43
- web/src/components/Settings.vue+43-49
- web/src/components/SetupPage.vue+25-20
- web/src/components/Sidebar.vue+6-6
- web/src/components/StatusBadge.vue+3-2
- web/src/components/SyncPage.vue+5-3
- web/src/components/TaskHistory.vue+30-22
- web/src/components/TaskHistoryPage.vue+2-2
- web/src/components/TaskPanel.vue+48-37
- web/src/components/TasksPage.vue+1-1
- web/src/components/TeamMembers.vue+18-18
- web/src/components/ToastHost.vue+16-15
- web/src/composables/useAppState.jsAdded+259
- web/src/composables/useRotateStream.js+10-1
- web/src/composables/useStatus.js+20-8
- web/src/style.css+4-20
22 unmodified lines23242526272832 unmodified lines616263646566676822 unmodified linesCPA_URL=http://127.0.0.1:8317CPA_KEY=your_key# API 鉴权(不设置则不启用,任何人都可访问)API_KEY=32 unmodified lines# 自动巡检(API 模式下生效)AUTO_CHECK_INTERVAL=300 # 巡检间隔(秒),默认 5 分钟AUTO_CHECK_THRESHOLD=10 # 额度低于此百分比触发轮转,默认 10%AUTO_CHECK_MIN_LOW=2 # 至少几个账号低于阈值才触发,默认 2# 对账策略(autoteam reconcile / cmd_check 入口自动对账)# RECONCILE_KICK_ORPHAN=true:workspace 有 active + 本地 auth_file 缺失的"残废"自动 KICK22 unmodified lines2324252627282930313233343536373839404142434445464732 unmodified lines808182838485868788899022 unmodified linesCPA_URL=http://127.0.0.1:8317CPA_KEY=your_key# 远端同步目标开关(建议显式设置,避免占位值被误判为已启用)SYNC_TARGET_CPA=falseSYNC_TARGET_SUB2API=false# Sub2APISUB2API_URL=http://127.0.0.1:8080SUB2API_EMAIL=admin@example.comSUB2API_PASSWORD=your_passwordSUB2API_GROUP=SUB2API_PROXY=SUB2API_CONCURRENCY=10SUB2API_PRIORITY=1SUB2API_RATE_MULTIPLIER=1SUB2API_AUTO_PAUSE_ON_EXPIRED=trueSUB2API_MODEL_WHITELIST=SUB2API_OPENAI_WS_MODE=offSUB2API_OPENAI_PASSTHROUGH=falseSUB2API_OVERWRITE_ACCOUNT_SETTINGS=false# API 鉴权(不设置则不启用,任何人都可访问)API_KEY=32 unmodified lines# 自动巡检(API 模式下生效)AUTO_CHECK_INTERVAL=300 # 巡检间隔(秒),默认 5 分钟AUTO_CHECK_TARGET_SEATS=3 # 自动巡检目标 Team 总 seat 数(最多 1 母 + 2 子)AUTO_CHECK_THRESHOLD=10 # 额度低于此百分比触发轮转,默认 10%AUTO_CHECK_MIN_LOW=2 # 至少几个账号低于阈值才触发,默认 2AUTO_CHECK_RETRY_ADD_PHONE=true # 是否自动重试 add_phone(手机号验证)AUTO_CHECK_ADD_PHONE_MAX_RETRIES=3 # add_phone 最大自动重试次数# 对账策略(autoteam reconcile / cmd_check 入口自动对账)# RECONCILE_KICK_ORPHAN=true:workspace 有 active + 本地 auth_file 缺失的"残废"自动 KICK
81 unmodified lines82838485868788899091929394959697989910010110210310410540 unmodified lines14614714814915015168 unmodified lines2202212222232242252269 unmodified lines23623723823924024160 unmodified lines30230330430530630781 unmodified linesreturn bool(_normalized_email(email)) and _normalized_email(email) == _normalized_email(get_admin_email())def load_accounts():"""加载账号列表"""if ACCOUNTS_FILE.exists():text = read_text(ACCOUNTS_FILE).strip()if text:return json.loads(text)return []def save_accounts(accounts):"""保存账号列表"""write_text(ACCOUNTS_FILE, json.dumps(accounts, indent=2, ensure_ascii=False))def find_account(accounts, email):"""按邮箱查找账号"""for acc in accounts:if acc["email"] == email:return accreturn None40 unmodified lines"quota_exhausted_at": None, # 额度用完的时间"quota_resets_at": None, # 额度恢复时间"last_quota_check_at": None, # 最近一次 wham/usage 探测时间戳,用于 standby 探测去重# Round 11 V7 — 双失效探测(access_token + refresh_token 同时被 server-side invalidate):# 主循环周期性调 is_token_pair_invalidated,命中后落该字段供事后排查 / UI 展示。"last_token_pair_invalidated_at": None,68 unmodified linesdef get_active_accounts():"""获取所有活跃账号"""return [a for a in load_accounts() if a["status"] == STATUS_ACTIVE and not _is_main_account_email(a.get("email"))]def get_personal_accounts():9 unmodified linesfor a in accounts:if _is_main_account_email(a.get("email")):continueif a["status"] == STATUS_STANDBY:resets_at = a.get("quota_resets_at")if resets_at is None:60 unmodified lines"get_next_reusable_account","get_personal_accounts","get_standby_accounts","is_supported_plan","load_accounts","normalize_plan_type",81 unmodified lines82838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912040 unmodified lines16116216316416516616768 unmodified lines2362372382392402412422432442452462472489 unmodified lines25825926026126226326426560 unmodified lines32632732832933033133281 unmodified linesreturn bool(_normalized_email(email)) and _normalized_email(email) == _normalized_email(get_admin_email())def is_account_disabled(acc: dict | None) -> bool:"""Return whether an account is locally disabled for automation flows."""return bool((acc or {}).get("disabled", False))def _normalize_account(acc: dict) -> dict:normalized = dict(acc or {})normalized["disabled"] = bool(normalized.get("disabled", False))return normalizeddef load_accounts():"""加载账号列表"""if ACCOUNTS_FILE.exists():text = read_text(ACCOUNTS_FILE).strip()if text:data = json.loads(text)if isinstance(data, list):return [_normalize_account(acc) for acc in data if isinstance(acc, dict)]return []def save_accounts(accounts):"""保存账号列表"""normalized = [_normalize_account(acc) for acc in accounts if isinstance(acc, dict)]write_text(ACCOUNTS_FILE, json.dumps(normalized, indent=2, ensure_ascii=False))def find_account(accounts, email):"""按邮箱查找账号"""target = _normalized_email(email)for acc in accounts:if _normalized_email(acc.get("email")) == target:return accreturn None40 unmodified lines"quota_exhausted_at": None, # 额度用完的时间"quota_resets_at": None, # 额度恢复时间"last_quota_check_at": None, # 最近一次 wham/usage 探测时间戳,用于 standby 探测去重"disabled": False, # 本地禁用:保留记录和 auth_file,但自动化巡检/轮转/同步跳过# Round 11 V7 — 双失效探测(access_token + refresh_token 同时被 server-side invalidate):# 主循环周期性调 is_token_pair_invalidated,命中后落该字段供事后排查 / UI 展示。"last_token_pair_invalidated_at": None,68 unmodified linesdef get_active_accounts():"""获取所有活跃账号"""return [afor a in load_accounts()if a["status"] == STATUS_ACTIVEand not _is_main_account_email(a.get("email"))and not is_account_disabled(a)]def get_personal_accounts():9 unmodified linesfor a in accounts:if _is_main_account_email(a.get("email")):continueif is_account_disabled(a):continueif a["status"] == STATUS_STANDBY:resets_at = a.get("quota_resets_at")if resets_at is None:60 unmodified lines"get_next_reusable_account","get_personal_accounts","get_standby_accounts","is_account_disabled","is_supported_plan","load_accounts","normalize_plan_type",
882 unmodified lines883884885886887888889890891602 unmodified lines14941495149614971498149915001501150215031504150515061507391 unmodified lines1899190019011902190319041905458 unmodified lines236423652366236723682369237077 unmodified lines2448244924502451245224532454314 unmodified lines2769277027712772277327742775882 unmodified lines_main_codex_step = Noneif _playwright_lock.locked():_playwright_lock.release()return {"status": "completed","message": "主号 Codex 已同步到 CPA","codex": _main_codex_status(),"info": info,}602 unmodified lines_playwright_lock.release()from autoteam.codex_auth import get_saved_main_auth_filefrom autoteam.cpa_sync import sync_main_codex_to_cpasaved_auth_file = get_saved_main_auth_file()if saved_auth_file:sync_main_codex_to_cpa(saved_auth_file)return {"status": "completed","message": "主号 Codex 已同步到 CPA","codex": _main_codex_status(),"info": {"auth_file": saved_auth_file},}391 unmodified linesfrom autoteam.accounts import load_accountsfrom autoteam.chatgpt_api import ChatGPTTeamAPIfrom autoteam.cloudmail import CloudMailClientfrom autoteam.cpa_sync import sync_to_cparaw_emails = [(e or "").strip() for e in (params.emails or [])]emails = [e for e in raw_emails if e]458 unmodified linesquota_resets_at=quota_result_resets_at(info) or int(time.time() + 18000),)# 同步到 CPAfrom autoteam.cpa_sync import sync_to_cpasync_to_cpa()return {77 unmodified lines@app.post("/api/sync")def post_sync():"""同步认证文件到 CPA"""from autoteam.cpa_sync import sync_to_cpasync_to_cpa()return {"message": "同步完成"}314 unmodified lines@app.post("/api/sync/main-codex")def post_sync_main_codex():"""兼容旧接口:开始主号 Codex 登录并同步到 CPA。"""return post_main_codex_start()882 unmodified lines883884885886887888889890891892893894895896897898899900602 unmodified lines1503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527391 unmodified lines1919192019211922192319241925458 unmodified lines238423852386238723882389239077 unmodified lines2468246924702471247224732474314 unmodified lines2789279027912792279327942795882 unmodified lines_main_codex_step = Noneif _playwright_lock.locked():_playwright_lock.release()from autoteam.sync_targets import describe_sync_targets, get_enabled_sync_targetsenabled_targets = get_enabled_sync_targets()target_label = describe_sync_targets(enabled_targets)message = (f"主号 Codex 已同步到 {target_label}"if enabled_targetselse "主号 Codex 已保存,本轮未启用远端同步目标")return {"status": "completed","message": message,"codex": _main_codex_status(),"info": info,}602 unmodified lines_playwright_lock.release()from autoteam.codex_auth import get_saved_main_auth_filefrom autoteam.sync_targets import (describe_sync_targets,get_enabled_sync_targets,sync_main_codex_to_configured_targets as sync_main_codex_to_cpa,)saved_auth_file = get_saved_main_auth_file()if saved_auth_file:sync_main_codex_to_cpa(saved_auth_file)enabled_targets = get_enabled_sync_targets()target_label = describe_sync_targets(enabled_targets)message = (f"主号 Codex 已同步到 {target_label}"if enabled_targetselse "主号 Codex 已保存,本轮未启用远端同步目标")return {"status": "completed","message": message,"codex": _main_codex_status(),"info": {"auth_file": saved_auth_file},}391 unmodified linesfrom autoteam.accounts import load_accountsfrom autoteam.chatgpt_api import ChatGPTTeamAPIfrom autoteam.cloudmail import CloudMailClientfrom autoteam.sync_targets import sync_to_configured_targets as sync_to_cparaw_emails = [(e or "").strip() for e in (params.emails or [])]emails = [e for e in raw_emails if e]458 unmodified linesquota_resets_at=quota_result_resets_at(info) or int(time.time() + 18000),)# 同步到 CPAfrom autoteam.sync_targets import sync_to_configured_targets as sync_to_cpasync_to_cpa()return {77 unmodified lines@app.post("/api/sync")def post_sync():"""同步认证文件到 CPA"""from autoteam.sync_targets import sync_to_configured_targets as sync_to_cpasync_to_cpa()return {"message": "同步完成"}314 unmodified lines@app.post("/api/sync/main-codex")def post_sync_main_codex():"""兼容旧接口:开始主号 Codex 登录并同步到已启用远端目标。"""return post_main_codex_start()
2751 unmodified lines2752275327542755275627572758275927602751 unmodified linesdef complete(self):info = super().complete()from autoteam.cpa_sync import sync_main_codex_to_cpasync_main_codex_to_cpa(info["auth_file"])return {"email": info.get("email"),2751 unmodified lines27522753275427552756275727582751 unmodified linesdef complete(self):info = super().complete()from autoteam.sync_targets import sync_main_codex_to_configured_targets as sync_main_codex_to_cpasync_main_codex_to_cpa(info["auth_file"])return {"email": info.get("email"),
38 unmodified lines39404142434416 unmodified lines6162636465665 unmodified lines72737475767738 unmodified linesreturn "playwright"# CloudMail 配置CLOUDMAIL_BASE_URL = os.environ.get("CLOUDMAIL_BASE_URL", "")CLOUDMAIL_EMAIL = os.environ.get("CLOUDMAIL_EMAIL", "")16 unmodified lines# 自动巡检配置AUTO_CHECK_INTERVAL = _get_int_env("AUTO_CHECK_INTERVAL", 300) # 巡检间隔(秒),默认 5 分钟AUTO_CHECK_THRESHOLD = _get_int_env("AUTO_CHECK_THRESHOLD", 10) # 额度低于此百分比触发轮转,默认 10%AUTO_CHECK_MIN_LOW = _get_int_env("AUTO_CHECK_MIN_LOW", 2) # 至少几个账号低于阈值才触发,默认 25 unmodified linesreturn str(raw).strip().lower() in ("1", "true", "yes", "on", "y", "t")# Round 12 S3 — auth_repair 状态机配置(cherry-pick from upstream).# AUTO_CHECK_RETRY_ADD_PHONE=true(默认): 注册被 OpenAI 要求 add_phone 时,# 不立即放弃,而是按指数退避(2^n * AUTO_CHECK_INTERVAL)重试 N 次,N 由38 unmodified lines3940414243444546474849505116 unmodified lines686970717273745 unmodified lines808182838485868788899091929394959697989910010110238 unmodified linesreturn "playwright"def _normalize_sub2api_ws_mode(value: str) -> str:mode = str(value or "").strip().lower()if mode in {"off", "ctx_pool", "passthrough"}:return modereturn "off"# CloudMail 配置CLOUDMAIL_BASE_URL = os.environ.get("CLOUDMAIL_BASE_URL", "")CLOUDMAIL_EMAIL = os.environ.get("CLOUDMAIL_EMAIL", "")16 unmodified lines# 自动巡检配置AUTO_CHECK_INTERVAL = _get_int_env("AUTO_CHECK_INTERVAL", 300) # 巡检间隔(秒),默认 5 分钟AUTO_CHECK_TARGET_SEATS = max(1, _get_int_env("AUTO_CHECK_TARGET_SEATS", 3))AUTO_CHECK_THRESHOLD = _get_int_env("AUTO_CHECK_THRESHOLD", 10) # 额度低于此百分比触发轮转,默认 10%AUTO_CHECK_MIN_LOW = _get_int_env("AUTO_CHECK_MIN_LOW", 2) # 至少几个账号低于阈值才触发,默认 25 unmodified linesreturn str(raw).strip().lower() in ("1", "true", "yes", "on", "y", "t")# Sub2API target sync configuration. Empty required fields keep the target# disabled until explicitly configured.SUB2API_URL = os.environ.get("SUB2API_URL", "")SUB2API_EMAIL = os.environ.get("SUB2API_EMAIL", "")SUB2API_PASSWORD = os.environ.get("SUB2API_PASSWORD", "")SUB2API_GROUP = os.environ.get("SUB2API_GROUP", "")SUB2API_PROXY = _get_str_env("SUB2API_PROXY", "")SUB2API_CONCURRENCY = _get_int_env("SUB2API_CONCURRENCY", 10)SUB2API_PRIORITY = _get_int_env("SUB2API_PRIORITY", 1)SUB2API_RATE_MULTIPLIER = _get_float_env("SUB2API_RATE_MULTIPLIER", 1)SUB2API_AUTO_PAUSE_ON_EXPIRED = _get_bool_env("SUB2API_AUTO_PAUSE_ON_EXPIRED", True)SUB2API_MODEL_WHITELIST = _get_str_env("SUB2API_MODEL_WHITELIST", "")SUB2API_OPENAI_WS_MODE = _normalize_sub2api_ws_mode(_get_str_env("SUB2API_OPENAI_WS_MODE", "off"))SUB2API_OPENAI_PASSTHROUGH = _get_bool_env("SUB2API_OPENAI_PASSTHROUGH", False)SUB2API_OVERWRITE_ACCOUNT_SETTINGS = _get_bool_env("SUB2API_OVERWRITE_ACCOUNT_SETTINGS", False)# Round 12 S3 — auth_repair 状态机配置(cherry-pick from upstream).# AUTO_CHECK_RETRY_ADD_PHONE=true(默认): 注册被 OpenAI 要求 add_phone 时,# 不立即放弃,而是按指数退避(2^n * AUTO_CHECK_INTERVAL)重试 N 次,N 由
10 unmodified lines11121314151617191 unmodified lines209210211212213214444 unmodified lines6596606616626636642 unmodified lines6676686696706716722 unmodified lines67567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072119 unmodified lines74174274374474574674710 unmodified linesimport requestsfrom autoteam.auth_storage import AUTH_DIR, ensure_auth_dir, ensure_auth_file_permissionsfrom autoteam.config import CPA_KEY, CPA_URLfrom autoteam.textio import write_textlogger = logging.getLogger(__name__)191 unmodified lineslogger.warning("[CPA] IPv6 proxy_url 刷新失败,继续上传原凭证: %s (%s)", email, exc)def _normalized_auth_path(bundle, main=False):email = bundle.get("email", "")account_id = bundle.get("account_id", "")444 unmodified lines# CPA 认证文件cpa_files = list_cpa_files()cpa_names = {f["name"]: f for f in cpa_files if f.get("name")}logger.info("[CPA] 待同步认证文件: %d (Team=%d, Personal=%d), CPA 现有: %d",2 unmodified linessynced_personal,len(cpa_files),)# 上传:所有 active + personal 认证文件(覆盖同名文件,确保 token 最新)uploaded = 02 unmodified linesif upload_to_cpa(path):uploaded += 1# 删除:CPA 中有但不在同步列表的(仅限本地管理的账号 — 避免误删主号或 CPA 手动文件)# 注意:personal 号已计入 files_to_sync,这里不会被删掉;只有状态变成 STANDBY/EXHAUSTED 等才会清理## Bug 4B 防御:删 CPA 文件之前再加一道闸 —�� 若该 email 在本地 accounts.json 仍持有# **同名** auth_file(物理文件存在),说明本地仍认为这份 token 有用,只是 status 暂时# 不在 active/personal(可能是母号切换瞬间 sync_account_states 错刷成 standby、或者# exhausted 待 rotate 处置)。这种情况下删 CPA 文件等于把"还能用的实物 token"丢掉,# 即便事后状态修回来,CPA 端也得等下一次 sync_to_cpa 重新上传(且若 auth_file 期间# 被刷 token 失败,这份就永久丢失)。# 因此守卫规则:本地 auth_file 路径存在 + 文件名完全等于 CPA 端 name → 跳过删除,# 留 WARN log 让用户知道。让删除只在"本地真的没这份文件了/换名字了"时才发生。local_auth_by_email = {}for acc in accounts:email_l = (acc.get("email") or "").lower()auth_path_str = acc.get("auth_file")if not email_l or not auth_path_str:continuetry:ap = Path(auth_path_str)except Exception:continuelocal_auth_by_email[email_l] = apdeleted = 0skipped_protected = 0for name, cpa_file in cpa_names.items():email = cpa_file.get("email", "").lower()if email in local_emails and name not in files_to_sync:local_path = local_auth_by_email.get(email)if local_path is not None and local_path.exists() and local_path.name == name:logger.warning("[CPA] 跳过删除 %s — 本地仍持有同名 auth_file 物理文件,等下一轮状态稳定后再处理",name,)skipped_protected += 1continuelogger.info("[CPA] 删除非 active/personal 文件: %s (%s)", name, email)if delete_from_cpa(name):deleted += 1if skipped_protected:logger.info("[CPA] 守卫保留 %d 个 CPA 文件(本地仍持有,避免误删 token)", skipped_protected)if disabled_skipped:logger.info("[CPA] 跳过 %d 个本地禁用账号", disabled_skipped)19 unmodified lines"disabled_skipped": disabled_skipped,"local_duplicates_deleted": local_duplicates_deleted,"delete_guard": {"skipped_protected": skipped_protected,},}10 unmodified lines11121314151617191 unmodified lines209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260444 unmodified lines7057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377382 unmodified lines7417427437447457467477487497507517522 unmodified lines75575675775875976076176276376476576676776876977077177277377477577677777877978019 unmodified lines80080180280380480580680780880981010 unmodified linesimport requestsfrom autoteam.auth_storage import AUTH_DIR, ensure_auth_dir, ensure_auth_file_permissionsfrom autoteam.config import AUTO_CHECK_TARGET_SEATS, CPA_KEY, CPA_URLfrom autoteam.textio import write_textlogger = logging.getLogger(__name__)191 unmodified lineslogger.warning("[CPA] IPv6 proxy_url 刷新失败,继续上传原凭证: %s (%s)", email, exc)def _active_auth_publish_decision(acc: dict, path: Path) -> str:"""Return publish/delete_remote/keep_remote for a local active Codex auth file."""if not path.exists():return "delete_remote"try:auth_data = json.loads(path.read_text(encoding="utf-8"))except Exception as exc:logger.warning("[CPA] 跳过无法读取的 active 凭证 %s: %s", path.name, exc)return "delete_remote"access_token = auth_data.get("access_token")if not access_token:logger.warning("[CPA] 跳过缺少 access_token 的 active 凭证: %s", path.name)return "delete_remote"try:from autoteam.codex_auth import check_codex_quotaquota_status, _info = check_codex_quota(access_token, timeout=8)except Exception as exc:logger.warning("[CPA] active 凭证实时验证异常,保留远端副本等待下轮: %s (%s)", path.name, exc)return "keep_remote"if quota_status == "network_error":logger.warning("[CPA] active 凭证实时验证网络异常,保留远端副本等待下轮: %s", path.name)return "keep_remote"if quota_status == "ok":try:from autoteam.ipv6_pool import ipv6_poolemail = (acc.get("email") or auth_data.get("email") or "").strip().lower()proxy_url = ipv6_pool.ensure(email) or ""if proxy_url and auth_data.get("proxy_url") != proxy_url:auth_data["proxy_url"] = proxy_urlwrite_text(path, json.dumps(auth_data, indent=2, ensure_ascii=False))logger.info("[CPA] 已刷新 active 凭证 proxy_url: %s", email)except Exception as exc:logger.warning("[CPA] active 凭证 IPv6 proxy_url 刷新失败,继续上传原凭证: %s", exc)return "publish"logger.warning("[CPA] 跳过实时验证失败的 active 凭证: %s (%s)", path.name, quota_status)return "delete_remote"def _normalized_auth_path(bundle, main=False):email = bundle.get("email", "")account_id = bundle.get("account_id", "")444 unmodified lines# CPA 认证文件cpa_files = list_cpa_files()cpa_names = {f["name"]: f for f in cpa_files if f.get("name")}min_active_for_remote_delete = max(1, int(AUTO_CHECK_TARGET_SEATS) - 1)allow_remote_delete = synced_active >= min_active_for_remote_deletetry:from autoteam.manager import _is_protected_local_credential_seatexcept Exception:_is_protected_local_credential_seat = Noneprotected_remote_names = set()protected_remote_emails = set()if _is_protected_local_credential_seat is not None:for acc in accounts:if is_account_disabled(acc):continueemail = str(acc.get("email") or "").strip().lower()auth_path_value = acc.get("auth_file")if not email:continuetry:if _is_protected_local_credential_seat(acc):protected_remote_emails.add(email)if auth_path_value:protected_remote_names.add(Path(auth_path_value).name)except Exception as exc:logger.warning("[CPA] 判断受保护凭证失败,保留远端副本: %s (%s)", email, exc)protected_remote_emails.add(email)if auth_path_value:protected_remote_names.add(Path(auth_path_value).name)logger.info("[CPA] 待同步认证文件: %d (Team=%d, Personal=%d), CPA 现有: %d",2 unmodified linessynced_personal,len(cpa_files),)if not allow_remote_delete:logger.warning("[CPA] active 凭证不足,跳过本轮远端删除: %d/%d",synced_active,min_active_for_remote_delete,)# 上传:所有 active + personal 认证文件(覆盖同名文件,确保 token 最新)uploaded = 02 unmodified linesif upload_to_cpa(path):uploaded += 1deleted = 0skipped_remote_delete = 0skipped_protected = 0for name, cpa_file in cpa_names.items():email = cpa_file.get("email", "").lower()if email in local_emails and name not in files_to_sync:if name in protected_remote_names or email in protected_remote_emails:logger.info("[CPA] 保留受保护本地凭证远端副本: %s (%s)", name, email)skipped_protected += 1continueif not allow_remote_delete:skipped_remote_delete += 1continuelogger.info("[CPA] 删除非 active/personal 文件: %s (%s)", name, email)if delete_from_cpa(name):deleted += 1if skipped_protected:logger.info("[CPA] 守卫保留 %d 个 CPA 文件(本地仍持有,避免误删 token)", skipped_protected)if skipped_remote_delete:logger.warning("[CPA] 本轮因 active 凭证不足保留远端非 active 文件: %d", skipped_remote_delete)if disabled_skipped:logger.info("[CPA] 跳过 %d 个本地禁用账号", disabled_skipped)19 unmodified lines"disabled_skipped": disabled_skipped,"local_duplicates_deleted": local_duplicates_deleted,"delete_guard": {"allow_remote_delete": allow_remote_delete,"min_active_for_remote_delete": min_active_for_remote_delete,"skipped_remote_delete": skipped_remote_delete,"skipped_protected": skipped_protected,"skipped_protected_delete": skipped_protected,},}
31 unmodified lines32333435363738541 unmodified lines58058158258358458558658758858931 unmodified lines)from autoteam.chatgpt_api import ChatGPTTeamAPIfrom autoteam.cloudmail import CloudMailClientfrom autoteam.config import get_playwright_launch_optionsfrom autoteam.identity import random_passwordfrom autoteam.playwright_lifecycle import close_playwright_objectsfrom autoteam.signup_profile import generate_signup_profile541 unmodified linespage = Nonetry:browser = p.chromium.launch(**get_playwright_launch_options())context = browser.new_context(viewport={"width": 1280, "height": 800},user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",)page = context.new_page()result, pwd = register_with_invite(page, invite_link, email, mail_client)31 unmodified lines32333435363738541 unmodified lines58058158258358458558631 unmodified lines)from autoteam.chatgpt_api import ChatGPTTeamAPIfrom autoteam.cloudmail import CloudMailClientfrom autoteam.config import get_playwright_context_options, get_playwright_launch_optionsfrom autoteam.identity import random_passwordfrom autoteam.playwright_lifecycle import close_playwright_objectsfrom autoteam.signup_profile import generate_signup_profile541 unmodified linespage = Nonetry:browser = p.chromium.launch(**get_playwright_launch_options())context = browser.new_context(**get_playwright_context_options())page = context.new_page()result, pwd = register_with_invite(page, invite_link, email, mail_client)
64 unmodified lines656667686970717273747576114 unmodified lines1911921931941951962252 unmodified lines244924502451245224532454169 unmodified lines2624262526262627262826291593 unmodified lines42234224422542264227422864 unmodified linessave_auth_file,)from autoteam.config import get_playwright_context_options, get_playwright_launch_optionsfrom autoteam.cpa_sync import sync_from_cpa, sync_main_codex_to_cpa, sync_to_cpafrom autoteam.identity import random_birthday, random_passwordfrom autoteam.invite import RegisterBlocked # SPEC-2 shared/add-phone-detection §5 — 5 处 OAuth 调用方 catchfrom autoteam.playwright_lifecycle import close_playwright_objectsfrom autoteam.register_failures import MASTER_SUBSCRIPTION_DEGRADED, record_failurefrom autoteam.signup_profile import SignupProfile, generate_signup_profilefrom autoteam.textio import read_text, write_textlogger = logging.getLogger(__name__)114 unmodified linesreturn bool(auth_file) and Path(auth_file).exists()def _ensure_account_ipv6_proxy(email: str | None) -> tuple[str, str]:email = _normalized_email(email)if not email:2252 unmodified lines)# personal 分支:已主动退出 Team,bundle 是个人 free/plus plan,算 codex 席位update_account(email, **update_fields)logger.info("[注册] 免费号就绪: %s (plan=%s, attempts=%d)",email, bundle.get("plan_type"), len(plan_drift_history) + 1)_record_outcome("success", plan=bundle.get("plan_type"))169 unmodified linesstage="run_post_register_oauth_team")update_account(email, **update_fields)if update_fields["status"] == STATUS_ACTIVE:logger.info("[注册] 账号就绪: %s (seat=%s)", email, seat_label)_record_outcome("success", plan=bundle_plan)1593 unmodified lines"[轮转] %s _auth_repair_reset 抛异常(忽略): %s",email, repair_exc,)logger.info("[轮转] 旧账号已恢复: %s", email)return True64 unmodified lines6566676869707172737475767778798081114 unmodified lines1961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412252 unmodified lines24942495249624972498249925002501169 unmodified lines267126722673267426752676267726781593 unmodified lines427242734274427542764277427864 unmodified linessave_auth_file,)from autoteam.config import get_playwright_context_options, get_playwright_launch_optionsfrom autoteam.cpa_sync import sync_from_cpafrom autoteam.identity import random_birthday, random_passwordfrom autoteam.invite import RegisterBlocked # SPEC-2 shared/add-phone-detection §5 — 5 处 OAuth 调用方 catchfrom autoteam.playwright_lifecycle import close_playwright_objectsfrom autoteam.register_failures import MASTER_SUBSCRIPTION_DEGRADED, record_failurefrom autoteam.signup_profile import SignupProfile, generate_signup_profilefrom autoteam.sync_targets import (sync_account_to_configured_targets,sync_main_codex_to_configured_targets as sync_main_codex_to_cpa,sync_to_configured_targets as sync_to_cpa,)from autoteam.textio import read_text, write_textlogger = logging.getLogger(__name__)114 unmodified linesreturn bool(auth_file) and Path(auth_file).exists()def _has_account_mail_binding(acc: dict | None) -> bool:acc = acc or {}return acc.get("mail_account_id") is not None or acc.get("cloudmail_account_id") is not Nonedef _is_protected_local_credential_seat(acc: dict | None) -> bool:if not acc or acc.get("disabled") is True or _is_main_account_email(acc.get("email")):return Falsehas_auth = _has_auth_file(acc)if acc.get("status") == STATUS_EXHAUSTED:return Falseif acc.get("protect_team_seat") is True:return has_authif not has_auth:return Falseif acc.get("status") in (STATUS_STANDBY, STATUS_AUTH_INVALID):return Truereturn not _has_account_mail_binding(acc)def _sync_ready_credential_to_targets(email: str, auth_file: str | None, *, stage_label: str) -> dict:if not auth_file:logger.warning("%s 新凭证已就绪但缺少 auth_file,跳过即时同步: %s", stage_label, email)return {"ok": False, "skipped": True, "reason": "missing_auth_file"}try:result = sync_account_to_configured_targets(email, str(auth_file))except Exception as exc:logger.warning("%s 新凭证即时同步失败,保留本地结果: %s (%s)", stage_label, email, exc)return {"ok": False, "error": str(exc)}if isinstance(result, dict) and result.get("ok") and not result.get("skipped"):logger.info("%s 新凭证已即时同步: %s (%s)", stage_label, email, Path(auth_file).name)elif isinstance(result, dict) and result.get("ok") and result.get("skipped"):logger.info("%s 新凭证即时同步跳过: %s (%s)", stage_label, email, result.get("reason"))else:logger.warning("%s 新凭证即时同步未完全成功,保留本地结果: %s (%s)", stage_label, email, result)return result if isinstance(result, dict) else {"ok": False, "result": result}def _ensure_account_ipv6_proxy(email: str | None) -> tuple[str, str]:email = _normalized_email(email)if not email:2252 unmodified lines)# personal 分支:已主动退出 Team,bundle 是个人 free/plus plan,算 codex 席位update_account(email, **update_fields)if update_fields["status"] == STATUS_ACTIVE:_sync_ready_credential_to_targets(email, auth_file, stage_label="[注册]")logger.info("[注册] 免费号就绪: %s (plan=%s, attempts=%d)",email, bundle.get("plan_type"), len(plan_drift_history) + 1)_record_outcome("success", plan=bundle.get("plan_type"))169 unmodified linesstage="run_post_register_oauth_team")update_account(email, **update_fields)if update_fields["status"] == STATUS_ACTIVE:_sync_ready_credential_to_targets(email, auth_file, stage_label="[注册]")if update_fields["status"] == STATUS_ACTIVE:logger.info("[注册] 账号就绪: %s (seat=%s)", email, seat_label)_record_outcome("success", plan=bundle_plan)1593 unmodified lines"[轮转] %s _auth_repair_reset 抛异常(忽略): %s",email, repair_exc,)_sync_ready_credential_to_targets(email, auth_file, stage_label="[轮转]")logger.info("[轮转] 旧账号已恢复: %s", email)return True
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049"""Sub2API 账号同步。"""
from __future__ import annotations
import base64import jsonimport loggingimport timefrom datetime import datetime, timezonefrom pathlib import Path
import requests
from autoteam.codex_auth import CODEX_CLIENT_IDfrom autoteam.config import ( SUB2API_AUTO_PAUSE_ON_EXPIRED, SUB2API_CONCURRENCY, SUB2API_EMAIL, SUB2API_GROUP, SUB2API_MODEL_WHITELIST, SUB2API_OPENAI_PASSTHROUGH, SUB2API_OPENAI_WS_MODE, SUB2API_OVERWRITE_ACCOUNT_SETTINGS, SUB2API_PASSWORD, SUB2API_PRIORITY, SUB2API_PROXY, SUB2API_RATE_MULTIPLIER, SUB2API_URL,)from autoteam.textio import read_text
logger = logging.getLogger(__name__)
_TIMEOUT = 10_PAGE_SIZE = 200
_EXTRA_MANAGED = "autoteam_managed"_EXTRA_KIND = "autoteam_kind"_EXTRA_EMAIL = "autoteam_email"_EXTRA_AUTH_FILE = "autoteam_auth_file"_EXTRA_SOURCE = "autoteam_source"_EXTRA_LAST_SYNC_AT = "autoteam_last_sync_at"_EXTRA_GROUP_IDS = "autoteam_sub2api_group_ids"_EXTRA_GROUP_NAMES = "autoteam_sub2api_group_names"
_KIND_POOL = "pool"_KIND_MAIN = "main"
_REMOTE_AUTH_FILE_PREFIX = "sub2api-"
def _excerpt(text: str | bytes | None, limit: int = 200) -> str: value = text.decode("utf-8", errors="ignore") if isinstance(text, bytes) else str(text or "") value = value.strip().replace("\n", " ") if len(value) > limit: value = value[:limit] + "..." return value
def _api_base_url() -> str: base = (SUB2API_URL or "").strip().rstrip("/") if base.endswith("/api/v1"): return base if base.endswith("/api"): return f"{base}/v1" return f"{base}/api/v1"
def _request(method: str, path: str, *, token: str | None = None, label: str, **kwargs): url = f"{_api_base_url()}{path}" headers = dict(kwargs.pop("headers", {}) or {}) if token: headers["Authorization"] = f"Bearer {token}" resp = requests.request(method, url, headers=headers, timeout=_TIMEOUT, **kwargs)
try: payload = resp.json() except Exception as exc: raise RuntimeError(f"[Sub2API] {label}返回了非 JSON 内容: {_excerpt(resp.text)}") from exc
if resp.status_code != 200: message = payload.get("message") or payload.get("detail") or _excerpt(resp.text) raise RuntimeError(f"[Sub2API] {label}失败: HTTP {resp.status_code} {message}")
if payload.get("code", 0) != 0: message = payload.get("message") or _excerpt(resp.text) raise RuntimeError(f"[Sub2API] {label}失败: {message}")
return payload.get("data")
def _login() -> str: data = _request( "POST", "/auth/login", label="管理员登录", json={"email": SUB2API_EMAIL, "password": SUB2API_PASSWORD}, ) if not isinstance(data, dict): raise RuntimeError("[Sub2API] 管理员登录返回格式异常") if data.get("requires_2fa"): raise RuntimeError("[Sub2API] 当前账号启用了 2FA,AutoTeam 暂不支持自动同步到 Sub2API") access_token = (data.get("access_token") or "").strip() if not access_token: raise RuntimeError("[Sub2API] 管理员登录成功但未返回 access_token") return access_token
def _list_openai_oauth_accounts(token: str) -> list[dict]: items = [] page = 1
while True: data = _request( "GET", "/admin/accounts", token=token, label="获取账号列表", params={ "page": page, "page_size": _PAGE_SIZE, "platform": "openai", "type": "oauth", "sort_by": "id", "sort_order": "asc", }, ) page_items = data.get("items") if isinstance(data, dict) else None if not isinstance(page_items, list): break items.extend(page_items) total = int(data.get("total") or 0) if isinstance(data, dict) else 0 if not page_items or len(items) >= total: break page += 1
return items
def _is_managed_account(item: dict, *, kind: str | None = None) -> bool: extra = item.get("extra") or {} if not isinstance(extra, dict): return False if extra.get(_EXTRA_SOURCE) != "autoteam" and not extra.get(_EXTRA_MANAGED): return False if kind and extra.get(_EXTRA_KIND) != kind: return False return True
def _managed_email(item: dict) -> str: extra = item.get("extra") or {} credentials = item.get("credentials") or {} return (extra.get(_EXTRA_EMAIL) or credentials.get("email") or item.get("name") or "").strip().lower()
def _managed_auth_file(item: dict) -> str: extra = item.get("extra") or {} return (extra.get(_EXTRA_AUTH_FILE) or "").strip()
def _managed_group_ids(item: dict) -> list[int]: extra = item.get("extra") or {} values = extra.get(_EXTRA_GROUP_IDS) if not isinstance(values, list): return []
result = [] seen = set() for value in values: try: group_id = int(value) except (TypeError, ValueError): continue if group_id <= 0 or group_id in seen: continue seen.add(group_id) result.append(group_id) return result
def _remote_auth_file_name(local_name: str) -> str: value = str(local_name or "").strip() if not value: return "" if value.startswith(_REMOTE_AUTH_FILE_PREFIX): return value return f"{_REMOTE_AUTH_FILE_PREFIX}{value}"
def _remote_auth_file_candidates(names: list[str] | None) -> set[str]: candidates = set() for name in names or []: value = str(name or "").strip() if not value: continue candidates.add(value) candidates.add(_remote_auth_file_name(value)) return candidates
def _split_group_spec(value: str | None) -> list[str]: text = str(value or "").replace(",", ",") parts = [] seen = set() for raw in text.replace("\n", ",").split(","): item = raw.strip() if not item: continue lowered = item.lower() if lowered in seen: continue seen.add(lowered) parts.append(item) return parts
def _split_csv_spec(value: str | None) -> list[str]: text = str(value or "").replace(",", ",") parts = [] seen = set() for raw in text.replace("\n", ",").split(","): item = raw.strip() if not item: continue lowered = item.lower() if lowered in seen: continue seen.add(lowered) parts.append(item) return parts
def _build_managed_model_mapping(model_whitelist: str | None = None) -> dict[str, str] | None: models = _split_csv_spec(model_whitelist if model_whitelist is not None else SUB2API_MODEL_WHITELIST) if not models: return None return {model: model for model in models}
def _build_account_settings() -> dict: return { "concurrency": SUB2API_CONCURRENCY, "priority": SUB2API_PRIORITY, "rate_multiplier": SUB2API_RATE_MULTIPLIER, "auto_pause_on_expired": SUB2API_AUTO_PAUSE_ON_EXPIRED, }
def _apply_managed_credentials_settings(credentials: dict, *, model_whitelist: str | None = None) -> dict: model_mapping = _build_managed_model_mapping(model_whitelist) if model_mapping: credentials["model_mapping"] = model_mapping return credentials
def _apply_managed_extra_settings(extra: dict) -> dict: extra["openai_oauth_responses_websockets_v2_mode"] = SUB2API_OPENAI_WS_MODE extra["openai_oauth_responses_websockets_v2_enabled"] = SUB2API_OPENAI_WS_MODE != "off" if SUB2API_OPENAI_PASSTHROUGH: extra["openai_passthrough"] = True else: extra.pop("openai_passthrough", None) extra.pop("openai_oauth_passthrough", None) return extra
def _dedupe_managed_accounts(token: str, items: list[dict], *, kind: str) -> tuple[dict[str, dict], int]: deduped: dict[str, dict] = {} duplicates_deleted = 0
for item in items: if not _is_managed_account(item, kind=kind): continue
key = _managed_email(item) if not key: key = f"{kind}:{item.get('id')}"
previous = deduped.get(key) if previous is None or int(item.get("id") or 0) > int(previous.get("id") or 0): if previous is not None: _delete_account(token, previous, label="删除重复账号") duplicates_deleted += 1 deduped[key] = item else: _delete_account(token, item, label="删除重复账号") duplicates_deleted += 1
return deduped, duplicates_deleted
def _select_managed_account_by_email(items: list[dict], email: str, *, kind: str) -> tuple[dict | None, int]: matches = [ item for item in items if _is_managed_account(item, kind=kind) and _managed_email(item) == email.lower() ] if not matches: return None, 0 matches.sort(key=lambda item: int(item.get("id") or 0), reverse=True) return matches[0], max(0, len(matches) - 1)
def _parse_jwt_payload(token: str) -> dict: parts = (token or "").split(".") if len(parts) < 2: return {} payload = parts[1] payload += "=" * (-len(payload) % 4) try: return json.loads(base64.urlsafe_b64decode(payload)) except Exception: return {}
def _list_openai_groups(token: str) -> list[dict]: data = _request( "GET", "/admin/groups/all", token=token, label="获取 Sub2API 分组列表", params={"platform": "openai"}, ) return data if isinstance(data, list) else []
def _get_group_by_id(token: str, group_id: int) -> dict | None: try: data = _request( "GET", f"/admin/groups/{group_id}", token=token, label=f"获取 Sub2API 分组 {group_id}", ) except Exception: return None return data if isinstance(data, dict) else None
def _resolve_group_binding(token: str, group_spec: str | None = None) -> tuple[list[int], list[str]]: parts = _split_group_spec(group_spec if group_spec is not None else SUB2API_GROUP) if not parts: return [], []
groups = _list_openai_groups(token) by_id = {} by_name = {} for item in groups: if not isinstance(item, dict): continue try: group_id = int(item.get("id") or 0) except (TypeError, ValueError): continue if group_id <= 0: continue by_id[group_id] = item name = str(item.get("name") or "").strip() if name: by_name[name.lower()] = item
resolved_ids = [] resolved_names = [] seen_ids = set()
for part in parts: group = None if part.isdigit(): group = by_id.get(int(part)) or _get_group_by_id(token, int(part)) else: group = by_name.get(part.lower())
if not isinstance(group, dict): raise RuntimeError(f"[Sub2API] 未找到分组: {part}")
platform = str(group.get("platform") or "").strip().lower() if platform and platform != "openai": raise RuntimeError(f"[Sub2API] 分组 {part} 不是 openai 平台,当前平台: {platform}")
try: group_id = int(group.get("id") or 0) except (TypeError, ValueError): group_id = 0 if group_id <= 0: raise RuntimeError(f"[Sub2API] 分组 {part} 缺少有效 ID") if group_id in seen_ids: continue
seen_ids.add(group_id) resolved_ids.append(group_id) resolved_names.append(str(group.get("name") or group_id))
return resolved_ids, resolved_names
def _list_proxies(token: str) -> list[dict]: data = _request( "GET", "/admin/proxies/all", token=token, label="获取 Sub2API 代理列表", ) return data if isinstance(data, list) else []
def _resolve_proxy_id(token: str, proxy_spec: str | None = None) -> int | None: spec = str(proxy_spec if proxy_spec is not None else SUB2API_PROXY or "").strip() if not spec: return None
if spec.lstrip("+-").isdigit(): proxy_id = int(spec) if proxy_id <= 0: raise RuntimeError(f"[Sub2API] 代理 ID 必须是正整数: {spec}") return proxy_id
proxies = _list_proxies(token) matches = [] for item in proxies: if not isinstance(item, dict): continue name = str(item.get("name") or "").strip() if name.lower() == spec.lower(): matches.append(item)
if not matches: raise RuntimeError(f"[Sub2API] 未找到代理: {spec}") if len(matches) > 1: raise RuntimeError(f"[Sub2API] 找到多个同名代理: {spec}")
try: proxy_id = int(matches[0].get("id") or 0) except (TypeError, ValueError): proxy_id = 0 if proxy_id <= 0: raise RuntimeError(f"[Sub2API] 代理 {spec} 缺少有效 ID") return proxy_id
def _extract_organization_id(auth_claims: dict) -> str: organizations = auth_claims.get("organizations") if not isinstance(organizations, list): return "" for item in organizations: if not isinstance(item, dict): continue if item.get("is_default") and item.get("id"): return str(item["id"]) for item in organizations: if isinstance(item, dict) and item.get("id"): return str(item["id"]) return ""
def _parse_timestamp(value, *, default: int | None = None) -> int | None: if isinstance(value, (int, float)): return int(value) text = str(value or "").strip() if not text: return default try: return int(float(text)) except Exception: pass try: if text.endswith("Z"): return int(datetime.fromisoformat(text.replace("Z", "+00:00")).timestamp()) return int(datetime.fromisoformat(text).timestamp()) except Exception: return default
def _to_local_iso(ts: int | None) -> str: if not ts: return "" return datetime.fromtimestamp(int(ts), timezone.utc).astimezone().isoformat(timespec="seconds")
def _quota_extra_fields(quota_info: dict | None, *, now_ts: int | None = None) -> dict: if not isinstance(quota_info, dict): return {}
now_ts = int(now_ts or time.time()) primary_pct = int(quota_info.get("primary_pct", 0) or 0) weekly_pct = int(quota_info.get("weekly_pct", 0) or 0) primary_resets_at = _parse_timestamp(quota_info.get("primary_resets_at")) weekly_resets_at = _parse_timestamp(quota_info.get("weekly_resets_at"))
extra = { "codex_5h_used_percent": primary_pct, "codex_5h_window_minutes": 300, "codex_7d_used_percent": weekly_pct, "codex_7d_window_minutes": 10080, "codex_primary_used_percent": primary_pct, "codex_primary_window_minutes": 300, "codex_secondary_used_percent": weekly_pct, "codex_secondary_window_minutes": 10080, "codex_primary_over_secondary_percent": 0, "codex_usage_updated_at": _to_local_iso(now_ts), }
if primary_resets_at: primary_after = max(0, primary_resets_at - now_ts) extra.update( { "codex_5h_reset_after_seconds": primary_after, "codex_5h_reset_at": _to_local_iso(primary_resets_at), "codex_primary_reset_after_seconds": primary_after, } )
if weekly_resets_at: weekly_after = max(0, weekly_resets_at - now_ts) extra.update( { "codex_7d_reset_after_seconds": weekly_after, "codex_7d_reset_at": _to_local_iso(weekly_resets_at), "codex_secondary_reset_after_seconds": weekly_after, } )
return extra
def _load_auth_data(path: Path) -> dict: return json.loads(read_text(path))
def _build_credentials(auth_data: dict) -> dict: id_token = auth_data.get("id_token", "") claims = _parse_jwt_payload(id_token) if id_token else {} auth_claims = claims.get("https://api.openai.com/auth", {}) if isinstance(claims, dict) else {}
credentials = {"access_token": auth_data.get("access_token", "")}
expires_at = _parse_timestamp(auth_data.get("expired"), default=int(time.time()) + 3600) if expires_at: credentials["expires_at"] = expires_at
refresh_token = auth_data.get("refresh_token", "") if refresh_token: credentials["refresh_token"] = refresh_token if id_token: credentials["id_token"] = id_token
client_id = auth_data.get("client_id") or claims.get("aud", [""])[0] if isinstance(claims.get("aud"), list) else "" client_id = client_id or CODEX_CLIENT_ID if client_id: credentials["client_id"] = client_id
email = auth_data.get("email") or claims.get("email") or "" if email: credentials["email"] = email
account_id = auth_data.get("account_id") or auth_claims.get("chatgpt_account_id") or "" if account_id: credentials["chatgpt_account_id"] = account_id
user_id = auth_claims.get("chatgpt_user_id") or "" if user_id: credentials["chatgpt_user_id"] = user_id
organization_id = auth_claims.get("poid") or _extract_organization_id(auth_claims) if organization_id: credentials["organization_id"] = organization_id
plan_type = auth_claims.get("chatgpt_plan_type") or "" if plan_type: credentials["plan_type"] = plan_type
subscription_expires_at = auth_claims.get("chatgpt_subscription_active_until") or "" if subscription_expires_at: credentials["subscription_expires_at"] = subscription_expires_at
return credentials
def _build_extra(email: str, auth_file_name: str, *, kind: str, quota_info: dict | None = None) -> dict: extra = { _EXTRA_MANAGED: True, _EXTRA_KIND: kind, _EXTRA_EMAIL: email.lower(), _EXTRA_AUTH_FILE: _remote_auth_file_name(auth_file_name), _EXTRA_SOURCE: "autoteam", _EXTRA_LAST_SYNC_AT: int(time.time()), "email": email.lower(), } extra.update(_quota_extra_fields(quota_info)) return extra
def _attach_group_metadata(extra: dict, group_ids: list[int] | None, group_names: list[str] | None) -> dict: extra[_EXTRA_GROUP_IDS] = [int(value) for value in group_ids or []] extra[_EXTRA_GROUP_NAMES] = [str(value) for value in group_names or [] if str(value).strip()] return extra
def _account_group_ids(account: dict) -> list[int]: result = [] seen = set()
for value in account.get("group_ids") or []: try: group_id = int(value) except (TypeError, ValueError): continue if group_id <= 0 or group_id in seen: continue seen.add(group_id) result.append(group_id)
for item in account.get("groups") or []: if not isinstance(item, dict): continue try: group_id = int(item.get("id") or 0) except (TypeError, ValueError): continue if group_id <= 0 or group_id in seen: continue seen.add(group_id) result.append(group_id)
return result
def _merge_group_ids(account: dict, desired_group_ids: list[int] | None) -> list[int]: desired = set() for value in desired_group_ids or []: try: group_id = int(value) except (TypeError, ValueError): continue if group_id > 0: desired.add(group_id) existing = set(_account_group_ids(account)) previous_managed = set(_managed_group_ids(account)) merged = (existing - previous_managed) | desired return sorted(merged)
def _create_account( token: str, *, name: str, credentials: dict, extra: dict, label: str, group_ids: list[int] | None = None, account_settings: dict | None = None, proxy_id: int | None = None,) -> dict: payload = { "name": name, "platform": "openai", "type": "oauth", "credentials": credentials, "extra": extra, **_build_account_settings(), "group_ids": list(group_ids or []), } if proxy_id is not None: payload["proxy_id"] = int(proxy_id) if account_settings: payload.update(account_settings) return _request( "POST", "/admin/accounts", token=token, label=label, json=payload, )
def _update_account( token: str, account: dict, *, credentials: dict, extra: dict, name: str | None = None, status: str | None = None, group_ids: list[int] | None = None, account_settings: dict | None = None,): payload = {"credentials": credentials, "extra": extra} if name: payload["name"] = name if status: payload["status"] = status if group_ids is not None: payload["group_ids"] = list(group_ids) if account_settings: payload.update(account_settings) return _request( "PUT", f"/admin/accounts/{account['id']}", token=token, label=f"更新账号 {name or _managed_email(account) or account.get('id')}", json=payload, )
def _upsert_managed_pool_account( token: str, *, target: dict, existing: dict | None, group_ids: list[int], group_names: list[str], overwrite_account_settings: bool, proxy_id: int | None = None,) -> dict: email = target["email"] desired_credentials = _build_credentials(target["auth_data"]) desired_extra = _build_extra( email, target["auth_path"].name, kind=_KIND_POOL, quota_info=target.get("quota_info"), ) _attach_group_metadata(desired_extra, group_ids, group_names)
if existing: merged_credentials = dict(existing.get("credentials") or {}) merged_credentials.update(desired_credentials) merged_extra = dict(existing.get("extra") or {}) merged_extra.update(desired_extra) account_settings = None if overwrite_account_settings: account_settings = _build_account_settings() _apply_managed_credentials_settings(merged_credentials) _apply_managed_extra_settings(merged_extra) _update_account( token, existing, credentials=merged_credentials, extra=merged_extra, status="active" if existing.get("status") != "active" else None, group_ids=_merge_group_ids(existing, group_ids), account_settings=account_settings, ) logger.info("[Sub2API] 更新: %s", email) return {"action": "updated", "account_id": existing.get("id")}
_apply_managed_credentials_settings(desired_credentials) _apply_managed_extra_settings(desired_extra) created = _create_account( token, name=target["name"], credentials=desired_credentials, extra=desired_extra, label=f"创建账号 {email}", group_ids=group_ids, account_settings=_build_account_settings(), proxy_id=proxy_id, ) logger.info("[Sub2API] 创建: %s", email) account_id = created.get("id") if isinstance(created, dict) else None return {"action": "created", "account_id": account_id}
def _delete_account(token: str, account: dict, *, label: str = "删除账号") -> bool: _request( "DELETE", f"/admin/accounts/{account['id']}", token=token, label=f"{label} {account.get('name') or account.get('id')}", ) return True
def verify_sub2api_connection() -> bool: try: token = _login() accounts = _list_openai_oauth_accounts(token) group_ids, group_names = _resolve_group_binding(token) if group_ids: logger.info( "[验证] Sub2API 连接成功(当前 %d 个 OpenAI OAuth 账号,分组: %s)", len(accounts), ", ".join(f"{name}#{group_id}" for group_id, name in zip(group_ids, group_names)), ) else: logger.info("[验证] Sub2API 连接成功(当前 %d 个 OpenAI OAuth 账号)", len(accounts)) return True except Exception as exc: logger.error("[验证] Sub2API 连接失败: %s", exc) return False
def sync_to_sub2api(): from autoteam.accounts import STATUS_ACTIVE, is_account_disabled, load_accounts
accounts = load_accounts() local_emails = {str(acc.get("email") or "").lower() for acc in accounts if acc.get("email")} active_targets = {}
for acc in accounts: if is_account_disabled(acc): continue if acc.get("status") != STATUS_ACTIVE or not acc.get("auth_file"): continue auth_path = Path(acc["auth_file"]) if not auth_path.exists(): continue try: auth_data = _load_auth_data(auth_path) except Exception as exc: logger.warning("[Sub2API] 读取 auth 文件失败,跳过 %s: %s", auth_path, exc) continue
email = (auth_data.get("email") or acc.get("email") or "").strip().lower() if not email: continue
active_targets[email] = { "email": email, "name": acc.get("email") or email, "auth_path": auth_path, "auth_data": auth_data, "quota_info": acc.get("last_quota"), }
token = _login() group_ids, group_names = _resolve_group_binding(token) remote_accounts = _list_openai_oauth_accounts(token) existing_by_email, duplicates_deleted = _dedupe_managed_accounts(token, remote_accounts, kind=_KIND_POOL)
logger.info( "[Sub2API] active 账号: %d, Sub2API 管理账号: %d", len(active_targets), len(existing_by_email), ) if group_ids: logger.info( "[Sub2API] 目标分组: %s", ", ".join(f"{name}#{group_id}" for group_id, name in zip(group_ids, group_names)) )
created = 0 updated = 0 deleted = 0 overwrite_account_settings = SUB2API_OVERWRITE_ACCOUNT_SETTINGS proxy_id = None proxy_id_resolved = False
for email, target in active_targets.items(): existing = existing_by_email.get(email)
if not existing and not proxy_id_resolved: proxy_id = _resolve_proxy_id(token) proxy_id_resolved = True result = _upsert_managed_pool_account( token, target=target, existing=existing, group_ids=group_ids, group_names=group_names, overwrite_account_settings=overwrite_account_settings, proxy_id=proxy_id, ) if result["action"] == "created": created += 1 else: updated += 1
for email, account in existing_by_email.items(): if email in local_emails and email not in active_targets: _delete_account(token, account, label="删除非 active 账号") logger.info("[Sub2API] 删除非 active 账号: %s", email) deleted += 1
final_accounts = _list_openai_oauth_accounts(token) final_managed = [item for item in final_accounts if _is_managed_account(item, kind=_KIND_POOL)] logger.info( "[Sub2API] 同步完成: 创建 %d, 更新 %d, 删除 %d, 远端去重 %d", created, updated, deleted, duplicates_deleted, ) logger.info("[Sub2API] Sub2API 中本地管理: %d, 本地 active: %d", len(final_managed), len(active_targets)) return { "created": created, "updated": updated, "deleted": deleted, "remote_duplicates_deleted": duplicates_deleted, }
def sync_account_to_sub2api(email: str, filepath: str, *, quota_info: dict | None = None): auth_path = Path(filepath) if not auth_path.exists(): raise FileNotFoundError(f"账号认证文件不存在: {auth_path}")
auth_data = _load_auth_data(auth_path) email_hint = (email or "").strip().lower() auth_email = (auth_data.get("email") or "").strip().lower() target_email = auth_email or email_hint if not target_email: raise RuntimeError("[Sub2API] 账号认证文件中未找到邮箱") if email_hint and auth_email and email_hint != auth_email: logger.warning("[Sub2API] 认证文件邮箱与请求邮箱不一致,按认证文件邮箱同步: %s -> %s", email_hint, auth_email)
token = _login() group_ids, group_names = _resolve_group_binding(token) remote_accounts = _list_openai_oauth_accounts(token) existing, duplicates_seen = _select_managed_account_by_email(remote_accounts, target_email, kind=_KIND_POOL) proxy_id = None if existing else _resolve_proxy_id(token)
target = { "email": target_email, "name": target_email, "auth_path": auth_path, "auth_data": auth_data, "quota_info": quota_info, } result = _upsert_managed_pool_account( token, target=target, existing=existing, group_ids=group_ids, group_names=group_names, overwrite_account_settings=SUB2API_OVERWRITE_ACCOUNT_SETTINGS, proxy_id=proxy_id, )
remote_auth_name = _remote_auth_file_name(auth_path.name) logger.info( "[Sub2API] 单凭证同步完成: %s (%s, account_id=%s, duplicates_seen=%d)", remote_auth_name, result["action"], result.get("account_id"), duplicates_seen, ) return { "uploaded": remote_auth_name, "action": result["action"], "account_id": result.get("account_id"), "remote_duplicates_seen": duplicates_seen, }
def sync_main_codex_to_sub2api(filepath): auth_path = Path(filepath) if not auth_path.exists(): raise FileNotFoundError(f"主号认证文件不存在: {auth_path}")
auth_data = _load_auth_data(auth_path) email = (auth_data.get("email") or "").strip().lower() token = _login() group_ids, group_names = _resolve_group_binding(token) remote_accounts = _list_openai_oauth_accounts(token) existing_by_email, duplicates_deleted = _dedupe_managed_accounts(token, remote_accounts, kind=_KIND_MAIN)
desired_credentials = _build_credentials(auth_data) desired_extra = _build_extra(email, auth_path.name, kind=_KIND_MAIN) _attach_group_metadata(desired_extra, group_ids, group_names) name = f"AutoTeam Main | {email}" if email else "AutoTeam Main" overwrite_account_settings = SUB2API_OVERWRITE_ACCOUNT_SETTINGS
current = existing_by_email.get(email) if email else None if current: merged_credentials = dict(current.get("credentials") or {}) merged_credentials.update(desired_credentials) merged_extra = dict(current.get("extra") or {}) merged_extra.update(desired_extra) account_settings = None if overwrite_account_settings: account_settings = _build_account_settings() _apply_managed_credentials_settings(merged_credentials) _apply_managed_extra_settings(merged_extra) _update_account( token, current, credentials=merged_credentials, extra=merged_extra, name=name, status="active", group_ids=_merge_group_ids(current, group_ids), account_settings=account_settings, ) account_id = current.get("id") else: _apply_managed_credentials_settings(desired_credentials) _apply_managed_extra_settings(desired_extra) created = _create_account( token, name=name, credentials=desired_credentials, extra=desired_extra, label="创建主号账号", group_ids=group_ids, account_settings=_build_account_settings(), ) account_id = created.get("id") if isinstance(created, dict) else None
deleted = [] for item in existing_by_email.values(): if current and item.get("id") == current.get("id"): continue if email and _managed_email(item) == email: continue _delete_account(token, item, label="删除旧主号账号") deleted.append(item.get("id"))
remote_auth_name = _remote_auth_file_name(auth_path.name) logger.info( "[Sub2API] 主号 Codex 已同步: %s (account_id=%s, duplicates=%d, deleted_old=%d)", remote_auth_name, account_id, duplicates_deleted, len(deleted), ) return {"uploaded": remote_auth_name, "account_id": account_id, "deleted_old": deleted}
def delete_main_codex_from_sub2api(): token = _login() remote_accounts = _list_openai_oauth_accounts(token) deleted = []
for item in remote_accounts: if not _is_managed_account(item, kind=_KIND_MAIN): continue _delete_account(token, item, label="删除主号账号") deleted.append(item.get("name") or str(item.get("id")))
return {"deleted": deleted, "count": len(deleted)}
def delete_account_from_sub2api(email: str, *, auth_names: list[str] | None = None): token = _login() remote_accounts = _list_openai_oauth_accounts(token) auth_name_set = _remote_auth_file_candidates(auth_names) deleted = []
for item in remote_accounts: if not _is_managed_account(item, kind=_KIND_POOL): continue item_email = _managed_email(item) item_auth_name = _managed_auth_file(item) if item_email != email.lower() and item_auth_name not in auth_name_set: continue _delete_account(token, item, label="删除账号") deleted.append(item.get("name") or str(item.get("id")))
return {"deleted": deleted, "count": len(deleted)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278"""统一远端同步目标分发:CPA / Sub2API。"""
from __future__ import annotations
import loggingimport osfrom collections.abc import Mappingfrom pathlib import Path
from autoteam.textio import parse_env_value
logger = logging.getLogger(__name__)
SYNC_TARGET_CPA = "cpa"SYNC_TARGET_SUB2API = "sub2api"
_SYNC_TARGET_META = { SYNC_TARGET_CPA: { "label": "CPA", "toggle_key": "SYNC_TARGET_CPA", "config_keys": ("CPA_URL", "CPA_KEY"), }, SYNC_TARGET_SUB2API: { "label": "Sub2API", "toggle_key": "SYNC_TARGET_SUB2API", "config_keys": ("SUB2API_URL", "SUB2API_EMAIL", "SUB2API_PASSWORD"), },}
_TRUE_VALUES = {"1", "true", "yes", "on", "enabled"}
def _normalize_env(env: Mapping[str, object] | None = None) -> dict[str, str]: source = env or os.environ return {str(key): "" if value is None else str(value) for key, value in source.items()}
def parse_bool_env(value: object, default: bool = False) -> bool: if value is None: return default text = parse_env_value(str(value)) if not text: return default return text.strip().lower() in _TRUE_VALUES
def get_sync_target_meta(target: str) -> dict[str, object]: try: return _SYNC_TARGET_META[target] except KeyError as exc: raise KeyError(f"未知同步目标: {target}") from exc
def get_sync_target_states(env: Mapping[str, object] | None = None) -> dict[str, bool]: values = _normalize_env(env) states = {} for target, meta in _SYNC_TARGET_META.items(): toggle_key = str(meta["toggle_key"]) config_keys = tuple(meta["config_keys"]) raw_toggle = (values.get(toggle_key) or "").strip() if raw_toggle: states[target] = parse_bool_env(raw_toggle) else: states[target] = all((values.get(key) or "").strip() for key in config_keys) return states
def is_sync_target_enabled(target: str, env: Mapping[str, object] | None = None) -> bool: return get_sync_target_states(env).get(target, False)
def get_enabled_sync_targets(env: Mapping[str, object] | None = None) -> list[str]: states = get_sync_target_states(env) return [target for target in _SYNC_TARGET_META if states.get(target)]
def get_available_sync_targets(env: Mapping[str, object] | None = None) -> list[str]: values = _normalize_env(env) available = [] for target, meta in _SYNC_TARGET_META.items(): if all((values.get(key) or "").strip() for key in tuple(meta["config_keys"])): available.append(target) return available
def get_sync_target_labels(targets: list[str] | None = None) -> list[str]: if targets is None: targets = list(_SYNC_TARGET_META) labels = [] for target in targets: meta = _SYNC_TARGET_META.get(target) if meta: labels.append(str(meta["label"])) return labels
def describe_sync_targets(targets: list[str] | None = None) -> str: labels = get_sync_target_labels(targets) if not labels: return "未启用远端同步目标" return " + ".join(labels)
def get_missing_target_configs( targets: list[str] | None = None, env: Mapping[str, object] | None = None) -> list[tuple[str, str]]: values = _normalize_env(env) missing: list[tuple[str, str]] = [] for target in targets or []: meta = get_sync_target_meta(target) for key in tuple(meta["config_keys"]): value = (values.get(key) or "").strip() if not value: missing.append((key, str(meta["label"]))) return missing
def sync_to_configured_targets(): results = {} enabled_targets = get_enabled_sync_targets()
if SYNC_TARGET_CPA in enabled_targets: from autoteam.cpa_sync import sync_to_cpa
try: results[SYNC_TARGET_CPA] = sync_to_cpa() except Exception as exc: logger.warning("[Sync] CPA 同步失败,保留本地轮换结果: %s", exc) results[SYNC_TARGET_CPA] = {"ok": False, "error": str(exc)}
if SYNC_TARGET_SUB2API in enabled_targets: from autoteam.sub2api_sync import sync_to_sub2api
try: results[SYNC_TARGET_SUB2API] = sync_to_sub2api() except Exception as exc: logger.warning("[Sync] Sub2API 同步失败,保留本地轮换结果: %s", exc) results[SYNC_TARGET_SUB2API] = {"ok": False, "error": str(exc)}
return results
def sync_account_to_configured_targets(email: str, filepath: str): """只把一个已就绪的账号凭证同步到已启用目标,不触发远端清理。""" from autoteam.accounts import STATUS_ACTIVE, find_account, is_account_disabled, load_accounts
normalized_email = (email or "").strip().lower() auth_path = Path(filepath) if not normalized_email: return {"ok": False, "skipped": True, "reason": "missing_email"} if not auth_path.exists(): logger.warning("[Sync] 新凭证文件不存在,跳过即时同步: %s (%s)", normalized_email, auth_path) return {"ok": False, "skipped": True, "reason": "missing_auth_file", "auth_file": str(auth_path)}
account = find_account(load_accounts(), normalized_email) if not account: logger.warning("[Sync] 未找到账号记录,跳过新凭证即时同步: %s", normalized_email) return {"ok": False, "skipped": True, "reason": "account_missing", "auth_file": auth_path.name} if is_account_disabled(account): logger.info("[Sync] 账号已禁用,跳过新凭证即时同步: %s", normalized_email) return {"ok": False, "skipped": True, "reason": "account_disabled", "auth_file": auth_path.name} if account.get("status") != STATUS_ACTIVE: logger.info( "[Sync] 账号尚未 active,跳过新凭证即时同步: %s (status=%s)", normalized_email, account.get("status"), ) return { "ok": False, "skipped": True, "reason": "account_not_active", "status": account.get("status"), "auth_file": auth_path.name, }
account_auth = account.get("auth_file") if account_auth and Path(account_auth).name != auth_path.name: logger.info( "[Sync] 请求同步的凭证与账号当前 auth_file 不同,仍按请求文件上传: %s (%s -> %s)", normalized_email, Path(account_auth).name, auth_path.name, )
results = {} enabled_targets = get_enabled_sync_targets()
if SYNC_TARGET_CPA in enabled_targets: from autoteam.cpa_sync import upload_to_cpa
try: uploaded = upload_to_cpa(auth_path) results[SYNC_TARGET_CPA] = {"ok": bool(uploaded), "uploaded": auth_path.name} except Exception as exc: logger.warning("[Sync] CPA 新凭证即时同步失败,保留本地结果: %s", exc) results[SYNC_TARGET_CPA] = {"ok": False, "error": str(exc), "uploaded": auth_path.name}
if SYNC_TARGET_SUB2API in enabled_targets: from autoteam.sub2api_sync import sync_account_to_sub2api
try: quota_info = account.get("last_quota") if isinstance(account.get("last_quota"), dict) else None target_result = sync_account_to_sub2api(normalized_email, str(auth_path), quota_info=quota_info) results[SYNC_TARGET_SUB2API] = {"ok": True, **target_result} except Exception as exc: logger.warning("[Sync] Sub2API 新凭证即时同步失败,保留本地结果: %s", exc) results[SYNC_TARGET_SUB2API] = {"ok": False, "error": str(exc), "uploaded": auth_path.name}
if not results: logger.info("[Sync] 未启用远端同步目标,跳过新凭证即时同步: %s", normalized_email) return {"ok": True, "skipped": True, "reason": "no_enabled_targets", "auth_file": auth_path.name}
return { "ok": all(item.get("ok") for item in results.values()), "auth_file": auth_path.name, "targets": results, }
def sync_main_codex_to_configured_targets(filepath: str): results = {} enabled_targets = get_enabled_sync_targets()
if SYNC_TARGET_CPA in enabled_targets: from autoteam.cpa_sync import sync_main_codex_to_cpa
results[SYNC_TARGET_CPA] = sync_main_codex_to_cpa(filepath)
if SYNC_TARGET_SUB2API in enabled_targets: from autoteam.sub2api_sync import sync_main_codex_to_sub2api
results[SYNC_TARGET_SUB2API] = sync_main_codex_to_sub2api(filepath)
return results
def delete_main_codex_from_configured_targets(*, include_disabled: bool = False): results = {} targets = get_available_sync_targets() if include_disabled else get_enabled_sync_targets()
if SYNC_TARGET_CPA in targets: from autoteam.cpa_sync import delete_main_codex_from_cpa
results[SYNC_TARGET_CPA] = delete_main_codex_from_cpa()
if SYNC_TARGET_SUB2API in targets: from autoteam.sub2api_sync import delete_main_codex_from_sub2api
results[SYNC_TARGET_SUB2API] = delete_main_codex_from_sub2api()
return results
def delete_account_from_configured_targets( email: str, *, auth_names: list[str] | None = None, include_disabled: bool = False): results = {} targets = get_available_sync_targets() if include_disabled else get_enabled_sync_targets()
if SYNC_TARGET_CPA in targets: from autoteam.cpa_sync import delete_from_cpa, list_cpa_files
deleted = [] auth_name_set = set(auth_names or []) for item in list_cpa_files(): item_email = (item.get("email") or "").lower() item_name = item.get("name") or "" if item_email == email.lower() or item_name in auth_name_set: if delete_from_cpa(item_name): deleted.append(item_name) results[SYNC_TARGET_CPA] = {"deleted": deleted, "count": len(deleted)}
if SYNC_TARGET_SUB2API in targets: from autoteam.sub2api_sync import delete_account_from_sub2api
results[SYNC_TARGET_SUB2API] = delete_account_from_sub2api(email, auth_names=auth_names or [])
return results1*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(79 70 229 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(79 70 229 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:Manrope,ui-sans-serif,system-ui,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:JetBrains Mono,ui-monospace,SFMono-Regular,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.-right-0\.5{right:-.125rem}.-top-0\.5{top:-.125rem}.bottom-0{bottom:0}.bottom-2{bottom:.5rem}.left-0{left:0}.left-1\/4{left:25%}.right-0{right:0}.right-1\/4{right:25%}.right-2{right:.5rem}.right-3{right:.75rem}.top-0{top:0}.top-2{top:.5rem}.top-3{top:.75rem}.z-50{z-index:50}.z-\[100\]{z-index:100}.mx-1{margin-left:.25rem;margin-right:.25rem}.mx-5{margin-left:1.25rem;margin-right:1.25rem}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-0\.5{margin-left:.125rem}.ml-1{margin-left:.25rem}.ml-4{margin-left:1rem}.mr-1{margin-right:.25rem}.mr-1\.5{margin-right:.375rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-1\.5{margin-top:.375rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-5{margin-top:1.25rem}.mt-6{margin-top:1.5rem}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-0\.5{height:.125rem}.h-1{height:.25rem}.h-1\.5{height:.375rem}.h-10{height:2.5rem}.h-11{height:2.75rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-20{height:5rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-64{height:16rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-\[calc\(100vh-200px\)\]{height:calc(100vh - 200px)}.h-px{height:1px}.max-h-64{max-height:16rem}.max-h-\[80vh\]{max-height:80vh}.min-h-screen{min-height:100vh}.w-0\.5{width:.125rem}.w-1{width:.25rem}.w-1\.5{width:.375rem}.w-10{width:2.5rem}.w-11{width:2.75rem}.w-16{width:4rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-24{width:6rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-56{width:14rem}.w-6{width:1.5rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-fit{width:-moz-fit-content;width:fit-content}.w-full{width:100%}.min-w-0{min-width:0px}.min-w-\[180px\]{min-width:180px}.min-w-\[72px\]{min-width:72px}.max-w-2xl{max-width:42rem}.max-w-3xl{max-width:48rem}.max-w-screen-2xl{max-width:1536px}.max-w-sm{max-width:24rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.shrink-0{flex-shrink:0}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes ping{75%,to{transform:scale(2);opacity:0}}.animate-ping{animation:ping 1s cubic-bezier(0,0,.2,1) infinite}@keyframes pulseDot{0%,to{transform:scale(1);opacity:1}50%{transform:scale(1.6);opacity:.4}}.animate-pulse-dot{animation:pulseDot 1.8s ease-in-out infinite}@keyframes rise{0%{transform:translateY(6px);opacity:0}to{transform:translateY(0);opacity:1}}.animate-rise{animation:rise .36s cubic-bezier(.22,1,.36,1)}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}@keyframes toastIn{0%{transform:translateY(8px) scale(.96);opacity:0}to{transform:translateY(0) scale(1);opacity:1}}.animate-toast-in{animation:toastIn .22s cubic-bezier(.22,1,.36,1)}@keyframes toastOut{0%{transform:translateY(0);opacity:1}to{transform:translateY(-6px);opacity:0}}.animate-toast-out{animation:toastOut .18s ease-in forwards}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-2\.5{gap:.625rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.25rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-hairline>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(229 229 229 / var(--tw-divide-opacity, 1))}.justify-self-start{justify-self:start}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.whitespace-pre{white-space:pre}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-sm{border-radius:.125rem}.rounded-b-full{border-bottom-right-radius:9999px;border-bottom-left-radius:9999px}.rounded-r-full{border-top-right-radius:9999px;border-bottom-right-radius:9999px}.rounded-bl-lg{border-bottom-left-radius:.5rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-amber-200{--tw-border-opacity: 1;border-color:rgb(253 230 138 / var(--tw-border-opacity, 1))}.border-amber-400\/30{border-color:#fbbf244d}.border-amber-500\/20{border-color:#f59e0b33}.border-amber-700{--tw-border-opacity: 1;border-color:rgb(180 83 9 / var(--tw-border-opacity, 1))}.border-blue-200{--tw-border-opacity: 1;border-color:rgb(191 219 254 / var(--tw-border-opacity, 1))}.border-current{border-color:currentColor}.border-cyan-200{--tw-border-opacity: 1;border-color:rgb(165 243 252 / var(--tw-border-opacity, 1))}.border-emerald-200{--tw-border-opacity: 1;border-color:rgb(167 243 208 / var(--tw-border-opacity, 1))}.border-emerald-400\/30{border-color:#34d3994d}.border-emerald-500\/20{border-color:#10b98133}.border-hairline{--tw-border-opacity: 1;border-color:rgb(229 229 229 / var(--tw-border-opacity, 1))}.border-indigo-200{--tw-border-opacity: 1;border-color:rgb(199 210 254 / var(--tw-border-opacity, 1))}.border-indigo-500{--tw-border-opacity: 1;border-color:rgb(99 102 241 / var(--tw-border-opacity, 1))}.border-indigo-500\/30{border-color:#6366f14d}.border-lime-200{--tw-border-opacity: 1;border-color:rgb(217 249 157 / var(--tw-border-opacity, 1))}.border-orange-200{--tw-border-opacity: 1;border-color:rgb(254 215 170 / var(--tw-border-opacity, 1))}.border-orange-400\/40{border-color:#fb923c66}.border-orange-500\/30{border-color:#f973164d}.border-red-200{--tw-border-opacity: 1;border-color:rgb(254 202 202 / var(--tw-border-opacity, 1))}.border-red-500\/30{border-color:#ef44444d}.border-rose-200{--tw-border-opacity: 1;border-color:rgb(254 205 211 / var(--tw-border-opacity, 1))}.border-rose-400\/30{border-color:#fb71854d}.border-rose-500\/20{border-color:#f43f5e33}.border-rose-500\/30{border-color:#f43f5e4d}.border-sky-200{--tw-border-opacity: 1;border-color:rgb(186 230 253 / var(--tw-border-opacity, 1))}.border-sky-400\/30{border-color:#38bdf84d}.border-slate-200{--tw-border-opacity: 1;border-color:rgb(226 232 240 / var(--tw-border-opacity, 1))}.border-slate-400\/25{border-color:#94a3b840}.border-stone-300{--tw-border-opacity: 1;border-color:rgb(214 211 209 / var(--tw-border-opacity, 1))}.border-teal-200{--tw-border-opacity: 1;border-color:rgb(153 246 228 / var(--tw-border-opacity, 1))}.border-transparent{border-color:transparent}.border-yellow-200{--tw-border-opacity: 1;border-color:rgb(254 240 138 / var(--tw-border-opacity, 1))}.border-yellow-500\/30{border-color:#eab3084d}.border-t-transparent{border-top-color:transparent}.bg-amber-100{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.bg-amber-400{--tw-bg-opacity: 1;background-color:rgb(251 191 36 / var(--tw-bg-opacity, 1))}.bg-amber-50{--tw-bg-opacity: 1;background-color:rgb(255 251 235 / var(--tw-bg-opacity, 1))}.bg-amber-500{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-amber-500\/\[0\.08\]{background-color:#f59e0b14}.bg-blue-50{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.bg-canvas{--tw-bg-opacity: 1;background-color:rgb(250 250 250 / var(--tw-bg-opacity, 1))}.bg-cyan-50{--tw-bg-opacity: 1;background-color:rgb(236 254 255 / var(--tw-bg-opacity, 1))}.bg-cyan-700{--tw-bg-opacity: 1;background-color:rgb(14 116 144 / var(--tw-bg-opacity, 1))}.bg-emerald-100{--tw-bg-opacity: 1;background-color:rgb(209 250 229 / var(--tw-bg-opacity, 1))}.bg-emerald-400{--tw-bg-opacity: 1;background-color:rgb(52 211 153 / var(--tw-bg-opacity, 1))}.bg-emerald-50{--tw-bg-opacity: 1;background-color:rgb(236 253 245 / var(--tw-bg-opacity, 1))}.bg-emerald-500{--tw-bg-opacity: 1;background-color:rgb(16 185 129 / var(--tw-bg-opacity, 1))}.bg-emerald-500\/\[0\.08\]{background-color:#10b98114}.bg-indigo-50{--tw-bg-opacity: 1;background-color:rgb(238 242 255 / var(--tw-bg-opacity, 1))}.bg-indigo-600{--tw-bg-opacity: 1;background-color:rgb(79 70 229 / var(--tw-bg-opacity, 1))}.bg-ink-100{--tw-bg-opacity: 1;background-color:rgb(245 245 245 / var(--tw-bg-opacity, 1))}.bg-ink-400{--tw-bg-opacity: 1;background-color:rgb(163 163 163 / var(--tw-bg-opacity, 1))}.bg-ink-50{--tw-bg-opacity: 1;background-color:rgb(250 250 250 / var(--tw-bg-opacity, 1))}.bg-ink-600\/20{background-color:#52525233}.bg-lime-50{--tw-bg-opacity: 1;background-color:rgb(247 254 231 / var(--tw-bg-opacity, 1))}.bg-orange-100{--tw-bg-opacity: 1;background-color:rgb(255 237 213 / var(--tw-bg-opacity, 1))}.bg-orange-400{--tw-bg-opacity: 1;background-color:rgb(251 146 60 / var(--tw-bg-opacity, 1))}.bg-orange-50{--tw-bg-opacity: 1;background-color:rgb(255 247 237 / var(--tw-bg-opacity, 1))}.bg-orange-500\/\[0\.10\]{background-color:#f973161a}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-red-700\/\[0\.12\]{background-color:#b91c1c1f}.bg-rose-100{--tw-bg-opacity: 1;background-color:rgb(255 228 230 / var(--tw-bg-opacity, 1))}.bg-rose-400{--tw-bg-opacity: 1;background-color:rgb(251 113 133 / var(--tw-bg-opacity, 1))}.bg-rose-50{--tw-bg-opacity: 1;background-color:rgb(255 241 242 / var(--tw-bg-opacity, 1))}.bg-rose-500{--tw-bg-opacity: 1;background-color:rgb(244 63 94 / var(--tw-bg-opacity, 1))}.bg-rose-500\/\[0\.08\]{background-color:#f43f5e14}.bg-rose-600{--tw-bg-opacity: 1;background-color:rgb(225 29 72 / var(--tw-bg-opacity, 1))}.bg-rose-700\/80{background-color:#be123ccc}.bg-sky-400{--tw-bg-opacity: 1;background-color:rgb(56 189 248 / var(--tw-bg-opacity, 1))}.bg-sky-50{--tw-bg-opacity: 1;background-color:rgb(240 249 255 / var(--tw-bg-opacity, 1))}.bg-sky-500\/\[0\.08\]{background-color:#0ea5e914}.bg-slate-100{--tw-bg-opacity: 1;background-color:rgb(241 245 249 / var(--tw-bg-opacity, 1))}.bg-slate-400{--tw-bg-opacity: 1;background-color:rgb(148 163 184 / var(--tw-bg-opacity, 1))}.bg-slate-50{--tw-bg-opacity: 1;background-color:rgb(248 250 252 / var(--tw-bg-opacity, 1))}.bg-slate-500{--tw-bg-opacity: 1;background-color:rgb(100 116 139 / var(--tw-bg-opacity, 1))}.bg-slate-500\/\[0\.10\]{background-color:#64748b1a}.bg-stone-500{--tw-bg-opacity: 1;background-color:rgb(120 113 108 / var(--tw-bg-opacity, 1))}.bg-stone-500\/\[0\.08\]{background-color:#78716c14}.bg-surface{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-surface-hover{--tw-bg-opacity: 1;background-color:rgb(245 245 245 / var(--tw-bg-opacity, 1))}.bg-surface-hover\/60{background-color:#f5f5f599}.bg-surface\/95{background-color:#fffffff2}.bg-teal-50{--tw-bg-opacity: 1;background-color:rgb(240 253 250 / var(--tw-bg-opacity, 1))}.bg-yellow-400{--tw-bg-opacity: 1;background-color:rgb(250 204 21 / var(--tw-bg-opacity, 1))}.bg-yellow-50{--tw-bg-opacity: 1;background-color:rgb(254 252 232 / var(--tw-bg-opacity, 1))}.bg-yellow-600\/\[0\.10\]{background-color:#ca8a041a}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-amber-400\/15{--tw-gradient-from: rgb(251 191 36 / .15) var(--tw-gradient-from-position);--tw-gradient-to: rgb(251 191 36 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-amber-500\/25{--tw-gradient-from: rgb(245 158 11 / .25) var(--tw-gradient-from-position);--tw-gradient-to: rgb(245 158 11 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-emerald-400\/20{--tw-gradient-from: rgb(52 211 153 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(52 211 153 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-red-700\/20{--tw-gradient-from: rgb(185 28 28 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(185 28 28 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-rose-500\/15{--tw-gradient-from: rgb(244 63 94 / .15) var(--tw-gradient-from-position);--tw-gradient-to: rgb(244 63 94 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-sky-400\/20{--tw-gradient-from: rgb(56 189 248 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(56 189 248 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-slate-500\/15{--tw-gradient-from: rgb(100 116 139 / .15) var(--tw-gradient-from-position);--tw-gradient-to: rgb(100 116 139 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-stone-200\/70{--tw-gradient-from: rgb(231 229 228 / .7) var(--tw-gradient-from-position);--tw-gradient-to: rgb(231 229 228 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-transparent{--tw-gradient-from: transparent var(--tw-gradient-from-position);--tw-gradient-to: rgb(0 0 0 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-yellow-500\/15{--tw-gradient-from: rgb(234 179 8 / .15) var(--tw-gradient-from-position);--tw-gradient-to: rgb(234 179 8 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.via-amber-500\/10{--tw-gradient-to: rgb(245 158 11 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(245 158 11 / .1) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-blue-500\/10{--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(59 130 246 / .1) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-emerald-500\/10{--tw-gradient-to: rgb(16 185 129 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(16 185 129 / .1) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-indigo-400\/40{--tw-gradient-to: rgb(129 140 248 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(129 140 248 / .4) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-orange-500\/20{--tw-gradient-to: rgb(249 115 22 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(249 115 22 / .2) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-red-500\/10{--tw-gradient-to: rgb(239 68 68 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(239 68 68 / .1) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-rose-700\/15{--tw-gradient-to: rgb(190 18 60 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(190 18 60 / .15) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-stone-100\/50{--tw-gradient-to: rgb(245 245 244 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(245 245 244 / .5) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-yellow-500\/10{--tw-gradient-to: rgb(234 179 8 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(234 179 8 / .1) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-zinc-500\/10{--tw-gradient-to: rgb(113 113 122 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(113 113 122 / .1) var(--tw-gradient-via-position), var(--tw-gradient-to)}.to-amber-600\/15{--tw-gradient-to: rgb(217 119 6 / .15) var(--tw-gradient-to-position)}.to-indigo-500\/15{--tw-gradient-to: rgb(99 102 241 / .15) var(--tw-gradient-to-position)}.to-red-800\/20{--tw-gradient-to: rgb(153 27 27 / .2) var(--tw-gradient-to-position)}.to-rose-500\/25{--tw-gradient-to: rgb(244 63 94 / .25) var(--tw-gradient-to-position)}.to-rose-600\/15{--tw-gradient-to: rgb(225 29 72 / .15) var(--tw-gradient-to-position)}.to-slate-100\/60{--tw-gradient-to: rgb(241 245 249 / .6) var(--tw-gradient-to-position)}.to-slate-600\/15{--tw-gradient-to: rgb(71 85 105 / .15) var(--tw-gradient-to-position)}.to-teal-500\/15{--tw-gradient-to: rgb(20 184 166 / .15) var(--tw-gradient-to-position)}.to-transparent{--tw-gradient-to: transparent var(--tw-gradient-to-position)}.to-yellow-600\/15{--tw-gradient-to: rgb(202 138 4 / .15) var(--tw-gradient-to-position)}.p-1{padding:.25rem}.p-3{padding:.75rem}.p-3\.5{padding:.875rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-3\.5{padding-left:.875rem;padding-right:.875rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-3\.5{padding-top:.875rem;padding-bottom:.875rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pb-20{padding-bottom:5rem}.pb-3{padding-bottom:.75rem}.pt-1{padding-top:.25rem}.pt-4{padding-top:1rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.align-\[-2px\]{vertical-align:-2px}.font-mono{font-family:JetBrains Mono,ui-monospace,SFMono-Regular,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-\[12px\]{font-size:12px}.text-\[9px\]{font-size:9px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-extrabold{font-weight:800}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.normal-case{text-transform:none}.italic{font-style:italic}.leading-none{line-height:1}.leading-relaxed{line-height:1.625}.leading-tight{line-height:1.25}.tracking-\[0\.2em\]{letter-spacing:.2em}.tracking-\[0\.3em\]{letter-spacing:.3em}.tracking-normal{letter-spacing:0em}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.tracking-widest{letter-spacing:.1em}.text-amber-300{--tw-text-opacity: 1;color:rgb(252 211 77 / var(--tw-text-opacity, 1))}.text-amber-400{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.text-amber-700{--tw-text-opacity: 1;color:rgb(180 83 9 / var(--tw-text-opacity, 1))}.text-amber-800{--tw-text-opacity: 1;color:rgb(146 64 14 / var(--tw-text-opacity, 1))}.text-amber-900{--tw-text-opacity: 1;color:rgb(120 53 15 / var(--tw-text-opacity, 1))}.text-amber-950{--tw-text-opacity: 1;color:rgb(69 26 3 / var(--tw-text-opacity, 1))}.text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.text-blue-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.text-cyan-700{--tw-text-opacity: 1;color:rgb(14 116 144 / var(--tw-text-opacity, 1))}.text-emerald-300{--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.text-emerald-600{--tw-text-opacity: 1;color:rgb(5 150 105 / var(--tw-text-opacity, 1))}.text-emerald-700{--tw-text-opacity: 1;color:rgb(4 120 87 / var(--tw-text-opacity, 1))}.text-emerald-800{--tw-text-opacity: 1;color:rgb(6 95 70 / var(--tw-text-opacity, 1))}.text-emerald-900{--tw-text-opacity: 1;color:rgb(6 78 59 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-indigo-700{--tw-text-opacity: 1;color:rgb(67 56 202 / var(--tw-text-opacity, 1))}.text-ink-400{--tw-text-opacity: 1;color:rgb(163 163 163 / var(--tw-text-opacity, 1))}.text-ink-500{--tw-text-opacity: 1;color:rgb(115 115 115 / var(--tw-text-opacity, 1))}.text-ink-600{--tw-text-opacity: 1;color:rgb(82 82 82 / var(--tw-text-opacity, 1))}.text-ink-700{--tw-text-opacity: 1;color:rgb(64 64 64 / var(--tw-text-opacity, 1))}.text-ink-800{--tw-text-opacity: 1;color:rgb(38 38 38 / var(--tw-text-opacity, 1))}.text-ink-900{--tw-text-opacity: 1;color:rgb(23 23 23 / var(--tw-text-opacity, 1))}.text-ink-950{--tw-text-opacity: 1;color:rgb(10 10 10 / var(--tw-text-opacity, 1))}.text-lime-700{--tw-text-opacity: 1;color:rgb(77 124 15 / var(--tw-text-opacity, 1))}.text-orange-200{--tw-text-opacity: 1;color:rgb(254 215 170 / var(--tw-text-opacity, 1))}.text-orange-300{--tw-text-opacity: 1;color:rgb(253 186 116 / var(--tw-text-opacity, 1))}.text-orange-700{--tw-text-opacity: 1;color:rgb(194 65 12 / var(--tw-text-opacity, 1))}.text-orange-800{--tw-text-opacity: 1;color:rgb(154 52 18 / var(--tw-text-opacity, 1))}.text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-red-700{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.text-rose-300{--tw-text-opacity: 1;color:rgb(253 164 175 / var(--tw-text-opacity, 1))}.text-rose-700{--tw-text-opacity: 1;color:rgb(190 18 60 / var(--tw-text-opacity, 1))}.text-rose-800{--tw-text-opacity: 1;color:rgb(159 18 57 / var(--tw-text-opacity, 1))}.text-rose-900{--tw-text-opacity: 1;color:rgb(136 19 55 / var(--tw-text-opacity, 1))}.text-rose-950{--tw-text-opacity: 1;color:rgb(76 5 25 / var(--tw-text-opacity, 1))}.text-sky-300{--tw-text-opacity: 1;color:rgb(125 211 252 / var(--tw-text-opacity, 1))}.text-sky-700{--tw-text-opacity: 1;color:rgb(3 105 161 / var(--tw-text-opacity, 1))}.text-sky-800{--tw-text-opacity: 1;color:rgb(7 89 133 / var(--tw-text-opacity, 1))}.text-sky-900{--tw-text-opacity: 1;color:rgb(12 74 110 / var(--tw-text-opacity, 1))}.text-slate-300{--tw-text-opacity: 1;color:rgb(203 213 225 / var(--tw-text-opacity, 1))}.text-slate-600{--tw-text-opacity: 1;color:rgb(71 85 105 / var(--tw-text-opacity, 1))}.text-slate-700{--tw-text-opacity: 1;color:rgb(51 65 85 / var(--tw-text-opacity, 1))}.text-slate-950{--tw-text-opacity: 1;color:rgb(2 6 23 / var(--tw-text-opacity, 1))}.text-stone-700{--tw-text-opacity: 1;color:rgb(68 64 60 / var(--tw-text-opacity, 1))}.text-teal-700{--tw-text-opacity: 1;color:rgb(15 118 110 / var(--tw-text-opacity, 1))}.text-yellow-200{--tw-text-opacity: 1;color:rgb(254 240 138 / var(--tw-text-opacity, 1))}.text-yellow-700{--tw-text-opacity: 1;color:rgb(161 98 7 / var(--tw-text-opacity, 1))}.accent-indigo-500{accent-color:#6366f1}.accent-indigo-600{accent-color:#4f46e5}.opacity-40{opacity:.4}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-75{opacity:.75}.opacity-80{opacity:.8}.shadow-card{--tw-shadow: 0 1px 2px 0 rgba(0,0,0,.04), 0 1px 3px 0 rgba(0,0,0,.06);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color), 0 1px 3px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.ring-1{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-inset{--tw-ring-inset: inset}.ring-amber-600\/25{--tw-ring-color: rgb(217 119 6 / .25)}.ring-emerald-600\/20{--tw-ring-color: rgb(5 150 105 / .2)}.ring-orange-600\/25{--tw-ring-color: rgb(234 88 12 / .25)}.ring-rose-400\/40{--tw-ring-color: rgb(251 113 133 / .4)}.ring-rose-600\/25{--tw-ring-color: rgb(225 29 72 / .25)}.ring-slate-400\/30{--tw-ring-color: rgb(148 163 184 / .3)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-500{transition-duration:.5s}.text-gray-500{color:#737373}.text-emerald-300{color:#047857}.text-amber-300{color:#b45309}.text-rose-300{color:#be123c}.text-orange-200{color:#9a3412}.text-orange-300{color:#c2410c}.text-yellow-200{color:#854d0e}.text-sky-300{color:#0369a1}.text-slate-300{color:#475569}.text-red-300{color:#b91c1c}:root{color-scheme:light;--bg-canvas: #fafafa;--bg-surface: #ffffff;--bg-surface-hover: #f5f5f5;--hairline: #e5e5e5;--hairline-strong: #d4d4d4;--ink-950: #0a0a0a;--ink-700: #404040;--ink-600: #525252;--ink-500: #737373;--ink-400: #a3a3a3;--accent: #4f46e5;--accent-soft: #eef2ff}html,body{font-family:Manrope,ui-sans-serif,system-ui,sans-serif;font-feature-settings:"cv02","cv03","cv04","cv11","ss01";-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}body{background-color:var(--bg-canvas);background-image:none;color:var(--ink-700)}.font-mono,code,pre,.tabular{font-variant-numeric:tabular-nums}.glass{background:var(--bg-surface);-webkit-backdrop-filter:none;backdrop-filter:none;border:1px solid var(--hairline);box-shadow:0 1px 2px #0000000a,0 1px 3px #0000000f}.glass-soft{background:var(--bg-surface);border:1px solid var(--hairline);box-shadow:0 1px 2px #00000008}.shimmer-bg{background:linear-gradient(90deg,#00000008,#00000014,#00000008);background-size:200% 100%;animation:shimmer 2.4s ease-in-out infinite}.row-hoverable{position:relative;transition:background-color .18s ease,transform .18s ease}.row-hoverable:before{content:"";position:absolute;left:0;top:0;bottom:0;width:2px;background:linear-gradient(180deg,transparent,rgba(79,70,229,.5),transparent);opacity:0;transition:opacity .22s ease}.row-hoverable:hover:before{opacity:1}.row-hoverable:hover{background-color:var(--bg-surface-hover)}@keyframes graceUrgent{0%,to{box-shadow:0 0 #e11d4800}50%{box-shadow:0 0 0 4px #e11d482e}}.grace-urgent{animation:graceUrgent 2.2s ease-in-out infinite}::-webkit-scrollbar{width:10px;height:10px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:#0000001f;border-radius:8px;border:2px solid transparent;background-clip:padding-box}::-webkit-scrollbar-thumb:hover{background:#0003;background-clip:padding-box;border:2px solid transparent}#app{position:relative;z-index:1}.lift-hover{transition:transform .18s cubic-bezier(.22,1,.36,1),box-shadow .18s ease}.lift-hover:hover:not(:disabled){transform:translateY(-1px);box-shadow:0 4px 12px -2px #00000014,0 2px 4px -2px #0000000a}.lift-hover:active:not(:disabled){transform:translateY(0)}.focus-ring:focus-visible{outline:none;box-shadow:0 0 0 2px #4f46e566,0 0 0 4px #4f46e526}.page-enter-from{opacity:0;transform:translateY(4px)}.page-enter-active{transition:opacity .18s cubic-bezier(.22,1,.36,1),transform .18s cubic-bezier(.22,1,.36,1)}.page-enter-to,.page-leave-from{opacity:1;transform:translateY(0)}.page-leave-active{transition:opacity .12s ease-in,transform .12s ease-in}.page-leave-to{opacity:0;transform:translateY(-2px)}.text-on-accent{color:#fff!important}.placeholder\:text-ink-400::-moz-placeholder{--tw-text-opacity: 1;color:rgb(163 163 163 / var(--tw-text-opacity, 1))}.placeholder\:text-ink-400::placeholder{--tw-text-opacity: 1;color:rgb(163 163 163 / var(--tw-text-opacity, 1))}.hover\:border-hairline-strong:hover{--tw-border-opacity: 1;border-color:rgb(212 212 212 / var(--tw-border-opacity, 1))}.hover\:border-indigo-300:hover{--tw-border-opacity: 1;border-color:rgb(165 180 252 / var(--tw-border-opacity, 1))}.hover\:border-rose-300:hover{--tw-border-opacity: 1;border-color:rgb(253 164 175 / var(--tw-border-opacity, 1))}.hover\:bg-amber-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.hover\:bg-cyan-100:hover{--tw-bg-opacity: 1;background-color:rgb(207 250 254 / var(--tw-bg-opacity, 1))}.hover\:bg-cyan-600:hover{--tw-bg-opacity: 1;background-color:rgb(8 145 178 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-100:hover{--tw-bg-opacity: 1;background-color:rgb(209 250 229 / var(--tw-bg-opacity, 1))}.hover\:bg-hairline:hover{--tw-bg-opacity: 1;background-color:rgb(229 229 229 / var(--tw-bg-opacity, 1))}.hover\:bg-indigo-100:hover{--tw-bg-opacity: 1;background-color:rgb(224 231 255 / var(--tw-bg-opacity, 1))}.hover\:bg-indigo-500:hover{--tw-bg-opacity: 1;background-color:rgb(99 102 241 / var(--tw-bg-opacity, 1))}.hover\:bg-ink-100:hover{--tw-bg-opacity: 1;background-color:rgb(245 245 245 / var(--tw-bg-opacity, 1))}.hover\:bg-ink-50:hover{--tw-bg-opacity: 1;background-color:rgb(250 250 250 / var(--tw-bg-opacity, 1))}.hover\:bg-lime-100:hover{--tw-bg-opacity: 1;background-color:rgb(236 252 203 / var(--tw-bg-opacity, 1))}.hover\:bg-rose-100:hover{--tw-bg-opacity: 1;background-color:rgb(255 228 230 / var(--tw-bg-opacity, 1))}.hover\:bg-rose-50:hover{--tw-bg-opacity: 1;background-color:rgb(255 241 242 / var(--tw-bg-opacity, 1))}.hover\:bg-rose-700:hover{--tw-bg-opacity: 1;background-color:rgb(190 18 60 / var(--tw-bg-opacity, 1))}.hover\:bg-sky-100:hover{--tw-bg-opacity: 1;background-color:rgb(224 242 254 / var(--tw-bg-opacity, 1))}.hover\:bg-slate-100:hover{--tw-bg-opacity: 1;background-color:rgb(241 245 249 / var(--tw-bg-opacity, 1))}.hover\:bg-teal-100:hover{--tw-bg-opacity: 1;background-color:rgb(204 251 241 / var(--tw-bg-opacity, 1))}.hover\:text-ink-700:hover{--tw-text-opacity: 1;color:rgb(64 64 64 / var(--tw-text-opacity, 1))}.hover\:text-ink-950:hover{--tw-text-opacity: 1;color:rgb(10 10 10 / var(--tw-text-opacity, 1))}.hover\:text-rose-700:hover{--tw-text-opacity: 1;color:rgb(190 18 60 / var(--tw-text-opacity, 1))}.hover\:text-rose-800:hover{--tw-text-opacity: 1;color:rgb(159 18 57 / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:shadow-ring-accent:hover{--tw-shadow: 0 0 0 3px rgba(79, 70, 229, .15);--tw-shadow-colored: 0 0 0 3px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.focus\:border-cyan-500:focus{--tw-border-opacity: 1;border-color:rgb(6 182 212 / var(--tw-border-opacity, 1))}.focus\:border-indigo-500:focus{--tw-border-opacity: 1;border-color:rgb(99 102 241 / var(--tw-border-opacity, 1))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.active\:bg-indigo-700:active{--tw-bg-opacity: 1;background-color:rgb(67 56 202 / var(--tw-bg-opacity, 1))}.active\:bg-ink-200:active{--tw-bg-opacity: 1;background-color:rgb(229 229 229 / var(--tw-bg-opacity, 1))}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:border-hairline:disabled{--tw-border-opacity: 1;border-color:rgb(229 229 229 / var(--tw-border-opacity, 1))}.disabled\:bg-ink-100:disabled{--tw-bg-opacity: 1;background-color:rgb(245 245 245 / var(--tw-bg-opacity, 1))}.disabled\:text-ink-400:disabled{--tw-text-opacity: 1;color:rgb(163 163 163 / var(--tw-text-opacity, 1))}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:hover\:bg-ink-100:hover:disabled{--tw-bg-opacity: 1;background-color:rgb(245 245 245 / var(--tw-bg-opacity, 1))}@media(min-width:640px){.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.sm\:grid-cols-\[minmax\(0\,1fr\)_auto_auto\]{grid-template-columns:minmax(0,1fr) auto auto}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-self-end{justify-self:end}}@media(min-width:768px){.md\:col-span-2{grid-column:span 2 / span 2}.md\:flex{display:flex}.md\:hidden{display:none}.md\:h-\[600px\]{height:600px}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.md\:p-4{padding:1rem}.md\:p-6{padding:1.5rem}.md\:pb-6{padding-bottom:1.5rem}}@media(min-width:1024px){.lg\:w-auto{width:auto}.lg\:max-w-xs{max-width:20rem}.lg\:grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}.lg\:flex-row{flex-direction:row}.lg\:items-center{align-items:center}.lg\:p-5{padding:1.25rem}.lg\:p-6{padding:1.5rem}}1*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(79 70 229 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(79 70 229 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:Manrope,ui-sans-serif,system-ui,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:JetBrains Mono,ui-monospace,SFMono-Regular,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.-right-0\.5{right:-.125rem}.-top-0\.5{top:-.125rem}.bottom-0{bottom:0}.bottom-2{bottom:.5rem}.left-0{left:0}.left-1\/4{left:25%}.right-0{right:0}.right-1\/4{right:25%}.right-2{right:.5rem}.right-3{right:.75rem}.top-0{top:0}.top-2{top:.5rem}.top-3{top:.75rem}.z-50{z-index:50}.z-\[100\]{z-index:100}.mx-1{margin-left:.25rem;margin-right:.25rem}.mx-5{margin-left:1.25rem;margin-right:1.25rem}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-0\.5{margin-left:.125rem}.ml-1{margin-left:.25rem}.ml-4{margin-left:1rem}.mr-1{margin-right:.25rem}.mr-1\.5{margin-right:.375rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-1\.5{margin-top:.375rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-5{margin-top:1.25rem}.mt-6{margin-top:1.5rem}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-0\.5{height:.125rem}.h-1{height:.25rem}.h-1\.5{height:.375rem}.h-10{height:2.5rem}.h-11{height:2.75rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-20{height:5rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-64{height:16rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-\[calc\(100vh-200px\)\]{height:calc(100vh - 200px)}.h-px{height:1px}.max-h-64{max-height:16rem}.max-h-\[80vh\]{max-height:80vh}.min-h-screen{min-height:100vh}.w-0\.5{width:.125rem}.w-1{width:.25rem}.w-1\.5{width:.375rem}.w-10{width:2.5rem}.w-11{width:2.75rem}.w-16{width:4rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-24{width:6rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-56{width:14rem}.w-6{width:1.5rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-fit{width:-moz-fit-content;width:fit-content}.w-full{width:100%}.min-w-0{min-width:0px}.min-w-\[180px\]{min-width:180px}.min-w-\[72px\]{min-width:72px}.max-w-2xl{max-width:42rem}.max-w-3xl{max-width:48rem}.max-w-screen-2xl{max-width:1536px}.max-w-sm{max-width:24rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.shrink-0{flex-shrink:0}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes ping{75%,to{transform:scale(2);opacity:0}}.animate-ping{animation:ping 1s cubic-bezier(0,0,.2,1) infinite}@keyframes pulseDot{0%,to{transform:scale(1);opacity:1}50%{transform:scale(1.6);opacity:.4}}.animate-pulse-dot{animation:pulseDot 1.8s ease-in-out infinite}@keyframes rise{0%{transform:translateY(6px);opacity:0}to{transform:translateY(0);opacity:1}}.animate-rise{animation:rise .36s cubic-bezier(.22,1,.36,1)}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}@keyframes toastIn{0%{transform:translateY(8px) scale(.96);opacity:0}to{transform:translateY(0) scale(1);opacity:1}}.animate-toast-in{animation:toastIn .22s cubic-bezier(.22,1,.36,1)}@keyframes toastOut{0%{transform:translateY(0);opacity:1}to{transform:translateY(-6px);opacity:0}}.animate-toast-out{animation:toastOut .18s ease-in forwards}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-2\.5{gap:.625rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.25rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-hairline>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(229 229 229 / var(--tw-divide-opacity, 1))}.justify-self-start{justify-self:start}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.whitespace-pre{white-space:pre}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-sm{border-radius:.125rem}.rounded-b-full{border-bottom-right-radius:9999px;border-bottom-left-radius:9999px}.rounded-r-full{border-top-right-radius:9999px;border-bottom-right-radius:9999px}.rounded-bl-lg{border-bottom-left-radius:.5rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-amber-200{--tw-border-opacity: 1;border-color:rgb(253 230 138 / var(--tw-border-opacity, 1))}.border-amber-400\/30{border-color:#fbbf244d}.border-amber-500\/20{border-color:#f59e0b33}.border-amber-700{--tw-border-opacity: 1;border-color:rgb(180 83 9 / var(--tw-border-opacity, 1))}.border-blue-200{--tw-border-opacity: 1;border-color:rgb(191 219 254 / var(--tw-border-opacity, 1))}.border-current{border-color:currentColor}.border-cyan-200{--tw-border-opacity: 1;border-color:rgb(165 243 252 / var(--tw-border-opacity, 1))}.border-emerald-200{--tw-border-opacity: 1;border-color:rgb(167 243 208 / var(--tw-border-opacity, 1))}.border-emerald-400\/30{border-color:#34d3994d}.border-emerald-500\/20{border-color:#10b98133}.border-hairline{--tw-border-opacity: 1;border-color:rgb(229 229 229 / var(--tw-border-opacity, 1))}.border-indigo-200{--tw-border-opacity: 1;border-color:rgb(199 210 254 / var(--tw-border-opacity, 1))}.border-indigo-500{--tw-border-opacity: 1;border-color:rgb(99 102 241 / var(--tw-border-opacity, 1))}.border-indigo-500\/30{border-color:#6366f14d}.border-lime-200{--tw-border-opacity: 1;border-color:rgb(217 249 157 / var(--tw-border-opacity, 1))}.border-orange-200{--tw-border-opacity: 1;border-color:rgb(254 215 170 / var(--tw-border-opacity, 1))}.border-orange-400\/40{border-color:#fb923c66}.border-orange-500\/30{border-color:#f973164d}.border-red-200{--tw-border-opacity: 1;border-color:rgb(254 202 202 / var(--tw-border-opacity, 1))}.border-red-500\/30{border-color:#ef44444d}.border-rose-200{--tw-border-opacity: 1;border-color:rgb(254 205 211 / var(--tw-border-opacity, 1))}.border-rose-400\/30{border-color:#fb71854d}.border-rose-500\/20{border-color:#f43f5e33}.border-rose-500\/30{border-color:#f43f5e4d}.border-sky-200{--tw-border-opacity: 1;border-color:rgb(186 230 253 / var(--tw-border-opacity, 1))}.border-sky-400\/30{border-color:#38bdf84d}.border-slate-200{--tw-border-opacity: 1;border-color:rgb(226 232 240 / var(--tw-border-opacity, 1))}.border-slate-400\/25{border-color:#94a3b840}.border-stone-300{--tw-border-opacity: 1;border-color:rgb(214 211 209 / var(--tw-border-opacity, 1))}.border-teal-200{--tw-border-opacity: 1;border-color:rgb(153 246 228 / var(--tw-border-opacity, 1))}.border-transparent{border-color:transparent}.border-yellow-200{--tw-border-opacity: 1;border-color:rgb(254 240 138 / var(--tw-border-opacity, 1))}.border-yellow-500\/30{border-color:#eab3084d}.border-t-transparent{border-top-color:transparent}.bg-amber-100{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.bg-amber-400{--tw-bg-opacity: 1;background-color:rgb(251 191 36 / var(--tw-bg-opacity, 1))}.bg-amber-50{--tw-bg-opacity: 1;background-color:rgb(255 251 235 / var(--tw-bg-opacity, 1))}.bg-amber-500{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-amber-500\/\[0\.08\]{background-color:#f59e0b14}.bg-blue-50{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.bg-canvas{--tw-bg-opacity: 1;background-color:rgb(250 250 250 / var(--tw-bg-opacity, 1))}.bg-cyan-50{--tw-bg-opacity: 1;background-color:rgb(236 254 255 / var(--tw-bg-opacity, 1))}.bg-cyan-700{--tw-bg-opacity: 1;background-color:rgb(14 116 144 / var(--tw-bg-opacity, 1))}.bg-emerald-100{--tw-bg-opacity: 1;background-color:rgb(209 250 229 / var(--tw-bg-opacity, 1))}.bg-emerald-400{--tw-bg-opacity: 1;background-color:rgb(52 211 153 / var(--tw-bg-opacity, 1))}.bg-emerald-50{--tw-bg-opacity: 1;background-color:rgb(236 253 245 / var(--tw-bg-opacity, 1))}.bg-emerald-500{--tw-bg-opacity: 1;background-color:rgb(16 185 129 / var(--tw-bg-opacity, 1))}.bg-emerald-500\/\[0\.08\]{background-color:#10b98114}.bg-indigo-50{--tw-bg-opacity: 1;background-color:rgb(238 242 255 / var(--tw-bg-opacity, 1))}.bg-indigo-600{--tw-bg-opacity: 1;background-color:rgb(79 70 229 / var(--tw-bg-opacity, 1))}.bg-ink-100{--tw-bg-opacity: 1;background-color:rgb(245 245 245 / var(--tw-bg-opacity, 1))}.bg-ink-400{--tw-bg-opacity: 1;background-color:rgb(163 163 163 / var(--tw-bg-opacity, 1))}.bg-ink-50{--tw-bg-opacity: 1;background-color:rgb(250 250 250 / var(--tw-bg-opacity, 1))}.bg-ink-600\/20{background-color:#52525233}.bg-lime-50{--tw-bg-opacity: 1;background-color:rgb(247 254 231 / var(--tw-bg-opacity, 1))}.bg-orange-100{--tw-bg-opacity: 1;background-color:rgb(255 237 213 / var(--tw-bg-opacity, 1))}.bg-orange-400{--tw-bg-opacity: 1;background-color:rgb(251 146 60 / var(--tw-bg-opacity, 1))}.bg-orange-50{--tw-bg-opacity: 1;background-color:rgb(255 247 237 / var(--tw-bg-opacity, 1))}.bg-orange-500\/\[0\.10\]{background-color:#f973161a}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-red-700\/\[0\.12\]{background-color:#b91c1c1f}.bg-rose-100{--tw-bg-opacity: 1;background-color:rgb(255 228 230 / var(--tw-bg-opacity, 1))}.bg-rose-400{--tw-bg-opacity: 1;background-color:rgb(251 113 133 / var(--tw-bg-opacity, 1))}.bg-rose-50{--tw-bg-opacity: 1;background-color:rgb(255 241 242 / var(--tw-bg-opacity, 1))}.bg-rose-500{--tw-bg-opacity: 1;background-color:rgb(244 63 94 / var(--tw-bg-opacity, 1))}.bg-rose-500\/\[0\.08\]{background-color:#f43f5e14}.bg-rose-600{--tw-bg-opacity: 1;background-color:rgb(225 29 72 / var(--tw-bg-opacity, 1))}.bg-rose-700\/80{background-color:#be123ccc}.bg-sky-400{--tw-bg-opacity: 1;background-color:rgb(56 189 248 / var(--tw-bg-opacity, 1))}.bg-sky-50{--tw-bg-opacity: 1;background-color:rgb(240 249 255 / var(--tw-bg-opacity, 1))}.bg-sky-500\/\[0\.08\]{background-color:#0ea5e914}.bg-slate-100{--tw-bg-opacity: 1;background-color:rgb(241 245 249 / var(--tw-bg-opacity, 1))}.bg-slate-400{--tw-bg-opacity: 1;background-color:rgb(148 163 184 / var(--tw-bg-opacity, 1))}.bg-slate-50{--tw-bg-opacity: 1;background-color:rgb(248 250 252 / var(--tw-bg-opacity, 1))}.bg-slate-500{--tw-bg-opacity: 1;background-color:rgb(100 116 139 / var(--tw-bg-opacity, 1))}.bg-slate-500\/\[0\.10\]{background-color:#64748b1a}.bg-stone-500{--tw-bg-opacity: 1;background-color:rgb(120 113 108 / var(--tw-bg-opacity, 1))}.bg-stone-500\/\[0\.08\]{background-color:#78716c14}.bg-surface{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-surface-hover{--tw-bg-opacity: 1;background-color:rgb(245 245 245 / var(--tw-bg-opacity, 1))}.bg-surface-hover\/60{background-color:#f5f5f599}.bg-surface\/95{background-color:#fffffff2}.bg-teal-50{--tw-bg-opacity: 1;background-color:rgb(240 253 250 / var(--tw-bg-opacity, 1))}.bg-yellow-400{--tw-bg-opacity: 1;background-color:rgb(250 204 21 / var(--tw-bg-opacity, 1))}.bg-yellow-50{--tw-bg-opacity: 1;background-color:rgb(254 252 232 / var(--tw-bg-opacity, 1))}.bg-yellow-600\/\[0\.10\]{background-color:#ca8a041a}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-amber-400\/15{--tw-gradient-from: rgb(251 191 36 / .15) var(--tw-gradient-from-position);--tw-gradient-to: rgb(251 191 36 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-amber-500\/25{--tw-gradient-from: rgb(245 158 11 / .25) var(--tw-gradient-from-position);--tw-gradient-to: rgb(245 158 11 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-emerald-400\/20{--tw-gradient-from: rgb(52 211 153 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(52 211 153 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-red-700\/20{--tw-gradient-from: rgb(185 28 28 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(185 28 28 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-rose-500\/15{--tw-gradient-from: rgb(244 63 94 / .15) var(--tw-gradient-from-position);--tw-gradient-to: rgb(244 63 94 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-sky-400\/20{--tw-gradient-from: rgb(56 189 248 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(56 189 248 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-slate-500\/15{--tw-gradient-from: rgb(100 116 139 / .15) var(--tw-gradient-from-position);--tw-gradient-to: rgb(100 116 139 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-stone-200\/70{--tw-gradient-from: rgb(231 229 228 / .7) var(--tw-gradient-from-position);--tw-gradient-to: rgb(231 229 228 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-transparent{--tw-gradient-from: transparent var(--tw-gradient-from-position);--tw-gradient-to: rgb(0 0 0 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-yellow-500\/15{--tw-gradient-from: rgb(234 179 8 / .15) var(--tw-gradient-from-position);--tw-gradient-to: rgb(234 179 8 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.via-amber-500\/10{--tw-gradient-to: rgb(245 158 11 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(245 158 11 / .1) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-blue-500\/10{--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(59 130 246 / .1) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-emerald-500\/10{--tw-gradient-to: rgb(16 185 129 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(16 185 129 / .1) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-indigo-400\/40{--tw-gradient-to: rgb(129 140 248 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(129 140 248 / .4) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-orange-500\/20{--tw-gradient-to: rgb(249 115 22 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(249 115 22 / .2) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-red-500\/10{--tw-gradient-to: rgb(239 68 68 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(239 68 68 / .1) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-rose-700\/15{--tw-gradient-to: rgb(190 18 60 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(190 18 60 / .15) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-stone-100\/50{--tw-gradient-to: rgb(245 245 244 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(245 245 244 / .5) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-yellow-500\/10{--tw-gradient-to: rgb(234 179 8 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(234 179 8 / .1) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-zinc-500\/10{--tw-gradient-to: rgb(113 113 122 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(113 113 122 / .1) var(--tw-gradient-via-position), var(--tw-gradient-to)}.to-amber-600\/15{--tw-gradient-to: rgb(217 119 6 / .15) var(--tw-gradient-to-position)}.to-indigo-500\/15{--tw-gradient-to: rgb(99 102 241 / .15) var(--tw-gradient-to-position)}.to-red-800\/20{--tw-gradient-to: rgb(153 27 27 / .2) var(--tw-gradient-to-position)}.to-rose-500\/25{--tw-gradient-to: rgb(244 63 94 / .25) var(--tw-gradient-to-position)}.to-rose-600\/15{--tw-gradient-to: rgb(225 29 72 / .15) var(--tw-gradient-to-position)}.to-slate-100\/60{--tw-gradient-to: rgb(241 245 249 / .6) var(--tw-gradient-to-position)}.to-slate-600\/15{--tw-gradient-to: rgb(71 85 105 / .15) var(--tw-gradient-to-position)}.to-teal-500\/15{--tw-gradient-to: rgb(20 184 166 / .15) var(--tw-gradient-to-position)}.to-transparent{--tw-gradient-to: transparent var(--tw-gradient-to-position)}.to-yellow-600\/15{--tw-gradient-to: rgb(202 138 4 / .15) var(--tw-gradient-to-position)}.p-1{padding:.25rem}.p-3{padding:.75rem}.p-3\.5{padding:.875rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-3\.5{padding-left:.875rem;padding-right:.875rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-3\.5{padding-top:.875rem;padding-bottom:.875rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pb-20{padding-bottom:5rem}.pb-3{padding-bottom:.75rem}.pt-1{padding-top:.25rem}.pt-4{padding-top:1rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.align-\[-2px\]{vertical-align:-2px}.font-mono{font-family:JetBrains Mono,ui-monospace,SFMono-Regular,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-\[12px\]{font-size:12px}.text-\[9px\]{font-size:9px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-extrabold{font-weight:800}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.normal-case{text-transform:none}.italic{font-style:italic}.leading-none{line-height:1}.leading-relaxed{line-height:1.625}.leading-tight{line-height:1.25}.tracking-\[0\.2em\]{letter-spacing:.2em}.tracking-\[0\.3em\]{letter-spacing:.3em}.tracking-normal{letter-spacing:0em}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.tracking-widest{letter-spacing:.1em}.text-amber-300{--tw-text-opacity: 1;color:rgb(252 211 77 / var(--tw-text-opacity, 1))}.text-amber-400{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.text-amber-700{--tw-text-opacity: 1;color:rgb(180 83 9 / var(--tw-text-opacity, 1))}.text-amber-800{--tw-text-opacity: 1;color:rgb(146 64 14 / var(--tw-text-opacity, 1))}.text-amber-900{--tw-text-opacity: 1;color:rgb(120 53 15 / var(--tw-text-opacity, 1))}.text-amber-950{--tw-text-opacity: 1;color:rgb(69 26 3 / var(--tw-text-opacity, 1))}.text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.text-blue-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.text-cyan-700{--tw-text-opacity: 1;color:rgb(14 116 144 / var(--tw-text-opacity, 1))}.text-emerald-300{--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.text-emerald-600{--tw-text-opacity: 1;color:rgb(5 150 105 / var(--tw-text-opacity, 1))}.text-emerald-700{--tw-text-opacity: 1;color:rgb(4 120 87 / var(--tw-text-opacity, 1))}.text-emerald-800{--tw-text-opacity: 1;color:rgb(6 95 70 / var(--tw-text-opacity, 1))}.text-emerald-900{--tw-text-opacity: 1;color:rgb(6 78 59 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-indigo-700{--tw-text-opacity: 1;color:rgb(67 56 202 / var(--tw-text-opacity, 1))}.text-ink-400{--tw-text-opacity: 1;color:rgb(163 163 163 / var(--tw-text-opacity, 1))}.text-ink-500{--tw-text-opacity: 1;color:rgb(115 115 115 / var(--tw-text-opacity, 1))}.text-ink-600{--tw-text-opacity: 1;color:rgb(82 82 82 / var(--tw-text-opacity, 1))}.text-ink-700{--tw-text-opacity: 1;color:rgb(64 64 64 / var(--tw-text-opacity, 1))}.text-ink-800{--tw-text-opacity: 1;color:rgb(38 38 38 / var(--tw-text-opacity, 1))}.text-ink-900{--tw-text-opacity: 1;color:rgb(23 23 23 / var(--tw-text-opacity, 1))}.text-ink-950{--tw-text-opacity: 1;color:rgb(10 10 10 / var(--tw-text-opacity, 1))}.text-lime-700{--tw-text-opacity: 1;color:rgb(77 124 15 / var(--tw-text-opacity, 1))}.text-orange-200{--tw-text-opacity: 1;color:rgb(254 215 170 / var(--tw-text-opacity, 1))}.text-orange-300{--tw-text-opacity: 1;color:rgb(253 186 116 / var(--tw-text-opacity, 1))}.text-orange-700{--tw-text-opacity: 1;color:rgb(194 65 12 / var(--tw-text-opacity, 1))}.text-orange-800{--tw-text-opacity: 1;color:rgb(154 52 18 / var(--tw-text-opacity, 1))}.text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-red-700{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.text-rose-300{--tw-text-opacity: 1;color:rgb(253 164 175 / var(--tw-text-opacity, 1))}.text-rose-700{--tw-text-opacity: 1;color:rgb(190 18 60 / var(--tw-text-opacity, 1))}.text-rose-800{--tw-text-opacity: 1;color:rgb(159 18 57 / var(--tw-text-opacity, 1))}.text-rose-900{--tw-text-opacity: 1;color:rgb(136 19 55 / var(--tw-text-opacity, 1))}.text-rose-950{--tw-text-opacity: 1;color:rgb(76 5 25 / var(--tw-text-opacity, 1))}.text-sky-300{--tw-text-opacity: 1;color:rgb(125 211 252 / var(--tw-text-opacity, 1))}.text-sky-700{--tw-text-opacity: 1;color:rgb(3 105 161 / var(--tw-text-opacity, 1))}.text-sky-800{--tw-text-opacity: 1;color:rgb(7 89 133 / var(--tw-text-opacity, 1))}.text-sky-900{--tw-text-opacity: 1;color:rgb(12 74 110 / var(--tw-text-opacity, 1))}.text-slate-300{--tw-text-opacity: 1;color:rgb(203 213 225 / var(--tw-text-opacity, 1))}.text-slate-600{--tw-text-opacity: 1;color:rgb(71 85 105 / var(--tw-text-opacity, 1))}.text-slate-700{--tw-text-opacity: 1;color:rgb(51 65 85 / var(--tw-text-opacity, 1))}.text-slate-950{--tw-text-opacity: 1;color:rgb(2 6 23 / var(--tw-text-opacity, 1))}.text-stone-700{--tw-text-opacity: 1;color:rgb(68 64 60 / var(--tw-text-opacity, 1))}.text-teal-700{--tw-text-opacity: 1;color:rgb(15 118 110 / var(--tw-text-opacity, 1))}.text-yellow-200{--tw-text-opacity: 1;color:rgb(254 240 138 / var(--tw-text-opacity, 1))}.text-yellow-700{--tw-text-opacity: 1;color:rgb(161 98 7 / var(--tw-text-opacity, 1))}.accent-indigo-500{accent-color:#6366f1}.accent-indigo-600{accent-color:#4f46e5}.opacity-40{opacity:.4}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-75{opacity:.75}.opacity-80{opacity:.8}.shadow-card{--tw-shadow: 0 1px 2px 0 rgba(0,0,0,.04), 0 1px 3px 0 rgba(0,0,0,.06);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color), 0 1px 3px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.ring-1{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-inset{--tw-ring-inset: inset}.ring-amber-600\/25{--tw-ring-color: rgb(217 119 6 / .25)}.ring-emerald-600\/20{--tw-ring-color: rgb(5 150 105 / .2)}.ring-orange-600\/25{--tw-ring-color: rgb(234 88 12 / .25)}.ring-rose-400\/40{--tw-ring-color: rgb(251 113 133 / .4)}.ring-rose-600\/25{--tw-ring-color: rgb(225 29 72 / .25)}.ring-slate-400\/30{--tw-ring-color: rgb(148 163 184 / .3)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-500{transition-duration:.5s}.text-gray-500{color:#737373}.text-emerald-300{color:#047857}.text-amber-300{color:#b45309}.text-rose-300{color:#be123c}.text-orange-200{color:#9a3412}.text-orange-300{color:#c2410c}.text-yellow-200{color:#854d0e}.text-sky-300{color:#0369a1}.text-slate-300{color:#475569}.text-red-300{color:#b91c1c}:root{color-scheme:light;--bg-canvas: #fafafa;--bg-surface: #ffffff;--bg-surface-hover: #f5f5f5;--hairline: #e5e5e5;--hairline-strong: #d4d4d4;--ink-950: #0a0a0a;--ink-700: #404040;--ink-600: #525252;--ink-500: #737373;--ink-400: #a3a3a3;--accent: #4f46e5;--accent-soft: #eef2ff}html,body{font-family:Manrope,ui-sans-serif,system-ui,sans-serif;font-feature-settings:"cv02","cv03","cv04","cv11","ss01";-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}body{background-color:var(--bg-canvas);background-image:none;color:var(--ink-700)}.font-mono,code,pre,.tabular{font-variant-numeric:tabular-nums}.glass{background:var(--bg-surface);-webkit-backdrop-filter:none;backdrop-filter:none;border:1px solid var(--hairline);box-shadow:0 1px 2px #0000000a,0 1px 3px #0000000f}.glass-soft{background:var(--bg-surface);border:1px solid var(--hairline);box-shadow:0 1px 2px #00000008}.shimmer-bg{background:linear-gradient(90deg,#00000008,#00000014,#00000008);background-size:200% 100%;animation:shimmer 2.4s ease-in-out infinite}.row-hoverable{position:relative;transition:background-color .18s ease,transform .18s ease}.row-hoverable:before{content:"";position:absolute;left:0;top:0;bottom:0;width:2px;background:linear-gradient(180deg,transparent,rgba(79,70,229,.5),transparent);opacity:0;transition:opacity .22s ease}.row-hoverable:hover:before{opacity:1}.row-hoverable:hover{background-color:var(--bg-surface-hover)}@keyframes graceUrgent{0%,to{box-shadow:0 0 #e11d4800}50%{box-shadow:0 0 0 4px #e11d482e}}.grace-urgent{animation:graceUrgent 2.2s ease-in-out infinite}::-webkit-scrollbar{width:10px;height:10px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:#0000001f;border-radius:8px;border:2px solid transparent;background-clip:padding-box}::-webkit-scrollbar-thumb:hover{background:#0003;background-clip:padding-box;border:2px solid transparent}#app{position:relative;z-index:1}.lift-hover{transition:transform .18s cubic-bezier(.22,1,.36,1),box-shadow .18s ease}.lift-hover:hover:not(:disabled){transform:translateY(-1px);box-shadow:0 4px 12px -2px #00000014,0 2px 4px -2px #0000000a}.lift-hover:active:not(:disabled){transform:translateY(0)}.focus-ring:focus-visible{outline:none;box-shadow:0 0 0 2px #4f46e566,0 0 0 4px #4f46e526}.page-enter-from{opacity:0;transform:translateY(4px)}.page-enter-active{transition:opacity .18s cubic-bezier(.22,1,.36,1),transform .18s cubic-bezier(.22,1,.36,1)}.page-enter-to,.page-leave-from{opacity:1;transform:translateY(0)}.page-leave-active{transition:opacity .12s ease-in,transform .12s ease-in}.page-leave-to{opacity:0;transform:translateY(-2px)}.text-on-accent{color:#fff!important}.placeholder\:text-ink-400::-moz-placeholder{--tw-text-opacity: 1;color:rgb(163 163 163 / var(--tw-text-opacity, 1))}.placeholder\:text-ink-400::placeholder{--tw-text-opacity: 1;color:rgb(163 163 163 / var(--tw-text-opacity, 1))}.hover\:border-hairline-strong:hover{--tw-border-opacity: 1;border-color:rgb(212 212 212 / var(--tw-border-opacity, 1))}.hover\:border-indigo-300:hover{--tw-border-opacity: 1;border-color:rgb(165 180 252 / var(--tw-border-opacity, 1))}.hover\:border-rose-300:hover{--tw-border-opacity: 1;border-color:rgb(253 164 175 / var(--tw-border-opacity, 1))}.hover\:bg-amber-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.hover\:bg-cyan-100:hover{--tw-bg-opacity: 1;background-color:rgb(207 250 254 / var(--tw-bg-opacity, 1))}.hover\:bg-cyan-600:hover{--tw-bg-opacity: 1;background-color:rgb(8 145 178 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-100:hover{--tw-bg-opacity: 1;background-color:rgb(209 250 229 / var(--tw-bg-opacity, 1))}.hover\:bg-hairline:hover{--tw-bg-opacity: 1;background-color:rgb(229 229 229 / var(--tw-bg-opacity, 1))}.hover\:bg-indigo-100:hover{--tw-bg-opacity: 1;background-color:rgb(224 231 255 / var(--tw-bg-opacity, 1))}.hover\:bg-indigo-500:hover{--tw-bg-opacity: 1;background-color:rgb(99 102 241 / var(--tw-bg-opacity, 1))}.hover\:bg-ink-100:hover{--tw-bg-opacity: 1;background-color:rgb(245 245 245 / var(--tw-bg-opacity, 1))}.hover\:bg-ink-50:hover{--tw-bg-opacity: 1;background-color:rgb(250 250 250 / var(--tw-bg-opacity, 1))}.hover\:bg-lime-100:hover{--tw-bg-opacity: 1;background-color:rgb(236 252 203 / var(--tw-bg-opacity, 1))}.hover\:bg-rose-100:hover{--tw-bg-opacity: 1;background-color:rgb(255 228 230 / var(--tw-bg-opacity, 1))}.hover\:bg-rose-50:hover{--tw-bg-opacity: 1;background-color:rgb(255 241 242 / var(--tw-bg-opacity, 1))}.hover\:bg-rose-700:hover{--tw-bg-opacity: 1;background-color:rgb(190 18 60 / var(--tw-bg-opacity, 1))}.hover\:bg-sky-100:hover{--tw-bg-opacity: 1;background-color:rgb(224 242 254 / var(--tw-bg-opacity, 1))}.hover\:bg-slate-100:hover{--tw-bg-opacity: 1;background-color:rgb(241 245 249 / var(--tw-bg-opacity, 1))}.hover\:bg-teal-100:hover{--tw-bg-opacity: 1;background-color:rgb(204 251 241 / var(--tw-bg-opacity, 1))}.hover\:text-ink-700:hover{--tw-text-opacity: 1;color:rgb(64 64 64 / var(--tw-text-opacity, 1))}.hover\:text-ink-950:hover{--tw-text-opacity: 1;color:rgb(10 10 10 / var(--tw-text-opacity, 1))}.hover\:text-rose-700:hover{--tw-text-opacity: 1;color:rgb(190 18 60 / var(--tw-text-opacity, 1))}.hover\:text-rose-800:hover{--tw-text-opacity: 1;color:rgb(159 18 57 / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:shadow-ring-accent:hover{--tw-shadow: 0 0 0 3px rgba(79, 70, 229, .15);--tw-shadow-colored: 0 0 0 3px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.focus\:border-cyan-500:focus{--tw-border-opacity: 1;border-color:rgb(6 182 212 / var(--tw-border-opacity, 1))}.focus\:border-indigo-500:focus{--tw-border-opacity: 1;border-color:rgb(99 102 241 / var(--tw-border-opacity, 1))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.active\:bg-indigo-700:active{--tw-bg-opacity: 1;background-color:rgb(67 56 202 / var(--tw-bg-opacity, 1))}.active\:bg-ink-200:active{--tw-bg-opacity: 1;background-color:rgb(229 229 229 / var(--tw-bg-opacity, 1))}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:border-hairline:disabled{--tw-border-opacity: 1;border-color:rgb(229 229 229 / var(--tw-border-opacity, 1))}.disabled\:bg-ink-100:disabled{--tw-bg-opacity: 1;background-color:rgb(245 245 245 / var(--tw-bg-opacity, 1))}.disabled\:text-ink-400:disabled{--tw-text-opacity: 1;color:rgb(163 163 163 / var(--tw-text-opacity, 1))}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:hover\:bg-ink-100:hover:disabled{--tw-bg-opacity: 1;background-color:rgb(245 245 245 / var(--tw-bg-opacity, 1))}@media(min-width:640px){.sm\:inline{display:inline}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.sm\:grid-cols-\[minmax\(0\,1fr\)_auto_auto\]{grid-template-columns:minmax(0,1fr) auto auto}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-self-end{justify-self:end}}@media(min-width:768px){.md\:col-span-2{grid-column:span 2 / span 2}.md\:flex{display:flex}.md\:hidden{display:none}.md\:h-\[600px\]{height:600px}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.md\:p-4{padding:1rem}.md\:p-6{padding:1.5rem}.md\:pb-6{padding-bottom:1.5rem}}@media(min-width:1024px){.lg\:w-auto{width:auto}.lg\:max-w-xs{max-width:20rem}.lg\:grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}.lg\:flex-row{flex-direction:row}.lg\:items-center{align-items:center}.lg\:p-5{padding:1.25rem}.lg\:p-6{padding:1.5rem}}
6 unmodified lines78910111213146 unmodified lines<link rel="preconnect" href="https://fonts.googleapis.com" /><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /><link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet" /><script type="module" crossorigin src="/assets/index-BZ-R3x09.js"></script><link rel="stylesheet" crossorigin href="/assets/index-DHotZNsL.css"></head><body class="bg-canvas text-ink-700 min-h-screen"><div id="app"></div>6 unmodified lines78910111213146 unmodified lines<link rel="preconnect" href="https://fonts.googleapis.com" /><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /><link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet" /><script type="module" crossorigin src="/assets/index-BSht6bmF.js"></script><link rel="stylesheet" crossorigin href="/assets/index-CbNAiyvN.css"></head><body class="bg-canvas text-ink-700 min-h-screen"><div id="app"></div>
14 unmodified lines15161718192011 unmodified lines32333435363735 unmodified lines7374757677788 unmodified lines87888914 unmodified linesassert created[0]["email"] == "user@example.com"assert created[0]["cloudmail_account_id"] == 123assert created[0]["status"] == accounts.STATUS_PENDINGupdated = accounts.update_account("user@example.com", status=accounts.STATUS_ACTIVE, auth_file="auth.json")11 unmodified lines[{"email": "owner@example.com", "status": accounts.STATUS_ACTIVE},{"email": "member@example.com", "status": accounts.STATUS_ACTIVE},{"email": "standby@example.com", "status": accounts.STATUS_STANDBY},])35 unmodified lines"quota_resets_at": None,"quota_exhausted_at": None,},])8 unmodified linesassert standby[1]["_quota_recovered"] is Trueassert standby[2]["_quota_recovered"] is Falseassert accounts.get_next_reusable_account()["email"] == "always@example.com"14 unmodified lines1516171819202111 unmodified lines3334353637383935 unmodified lines757677787980818283848586878 unmodified lines9697989910010110210310410510610710810911011111211314 unmodified linesassert created[0]["email"] == "user@example.com"assert created[0]["cloudmail_account_id"] == 123assert created[0]["status"] == accounts.STATUS_PENDINGassert created[0]["disabled"] is Falseupdated = accounts.update_account("user@example.com", status=accounts.STATUS_ACTIVE, auth_file="auth.json")11 unmodified lines[{"email": "owner@example.com", "status": accounts.STATUS_ACTIVE},{"email": "member@example.com", "status": accounts.STATUS_ACTIVE},{"email": "disabled@example.com", "status": accounts.STATUS_ACTIVE, "disabled": True},{"email": "standby@example.com", "status": accounts.STATUS_STANDBY},])35 unmodified lines"quota_resets_at": None,"quota_exhausted_at": None,},{"email": "disabled@example.com","status": accounts.STATUS_STANDBY,"quota_resets_at": None,"quota_exhausted_at": None,"disabled": True,},])8 unmodified linesassert standby[1]["_quota_recovered"] is Trueassert standby[2]["_quota_recovered"] is Falseassert accounts.get_next_reusable_account()["email"] == "always@example.com"def test_load_accounts_normalizes_disabled_field(tmp_path, monkeypatch):accounts_file = tmp_path / "accounts.json"monkeypatch.setattr(accounts, "ACCOUNTS_FILE", accounts_file)accounts_file.write_text('[{"email":"legacy@example.com","status":"standby"},{"email":"off@example.com","status":"active","disabled":1}]',encoding="utf-8",)loaded = accounts.load_accounts()assert loaded[0]["disabled"] is Falseassert loaded[1]["disabled"] is True
41 unmodified lines424344454647105 unmodified lines15315415515615715813 unmodified lines17217317417517617717814 unmodified lines1931941951961971985 unmodified lines20420520620720820921021121221312 unmodified lines22622722822923023123214 unmodified lines2472482492502512522532542552562573 unmodified lines26126226326426526641 unmodified linesassert client.page is Nonedef test_chatgpt_stop_closes_page_context_browser_and_playwright():calls = []105 unmodified linesdef test_complete_registration_closes_page_context_browser_when_invite_registration_raises(monkeypatch):calls = []class FakeClosable:def __init__(self, name):13 unmodified linesdef __init__(self):super().__init__("browser")def new_context(self, **_kwargs):return FakeContext()class FakeChromium:14 unmodified linesraise RuntimeError("registration crashed")monkeypatch.setattr(manager, "sync_playwright", lambda: FakeSyncPlaywright())monkeypatch.setattr(invite, "register_with_invite", fail_register)with pytest.raises(RuntimeError, match="registration crashed"):5 unmodified lines)assert calls == ["close:page", "close:context", "close:browser"]def test_register_direct_once_cleans_browser_context_on_unhandled_page_error(monkeypatch):calls = []class FakePage:url = "about:blank"12 unmodified linescalls.append("close:context")class FakeBrowser:def new_context(self, **_kwargs):return FakeContext()def close(self):14 unmodified linesreturn Falsemonkeypatch.setattr(manager, "sync_playwright", lambda: FakeSyncPlaywright())with pytest.raises(RuntimeError, match="navigation exploded"):manager._register_direct_once(object(), "child@example.com", "password")assert calls == ["close:page", "close:context", "close:browser"]def test_registration_and_oauth_paths_use_unified_playwright_cleanup():3 unmodified linesassert "browser.close()" not in inspect.getsource(codex_auth.login_codex_via_browser)assert "close_playwright_objects" in inspect.getsource(manager._register_direct_once)assert "close_playwright_objects" in inspect.getsource(codex_auth.login_codex_via_browser)def test_session_codex_auth_flow_stops_chatgpt_when_page_start_fails(monkeypatch):41 unmodified lines424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889105 unmodified lines19519619719819920020113 unmodified lines21521621721821922022122214 unmodified lines2372382392402412422435 unmodified lines24925025125225325425525625725825926012 unmodified lines27327427527627727827928014 unmodified lines2952962972982993003013023033043053063073 unmodified lines31131231331431531631731831932032132232341 unmodified linesassert client.page is Nonedef test_launch_browser_uses_unified_context_options(monkeypatch):captured = {}class FakePage:def close(self):captured["closed_page"] = Trueclass FakeContext:def close(self):captured["closed_context"] = Truedef new_page(self):return FakePage()class FakePlaywright:def __init__(self):self.chromium = selfdef launch(self, **_kwargs):return selfdef new_context(self, **kwargs):captured["kwargs"] = kwargsreturn FakeContext()def stop(self):captured["stopped"] = Trueclass FakeSyncPlaywright:def start(self):return FakePlaywright()monkeypatch.setattr(chatgpt_api, "sync_playwright", lambda: FakeSyncPlaywright())monkeypatch.setattr(chatgpt_api, "get_playwright_launch_options", lambda: {})monkeypatch.setattr(chatgpt_api, "get_playwright_context_options", lambda: {"viewport": {"width": 100, "height": 200}})client = chatgpt_api.ChatGPTTeamAPI()client._launch_browser()assert captured["kwargs"] == {"viewport": {"width": 100, "height": 200}}def test_chatgpt_stop_closes_page_context_browser_and_playwright():calls = []105 unmodified linesdef test_complete_registration_closes_page_context_browser_when_invite_registration_raises(monkeypatch):calls = []captured = {}class FakeClosable:def __init__(self, name):13 unmodified linesdef __init__(self):super().__init__("browser")def new_context(self, **kwargs):captured["kwargs"] = kwargsreturn FakeContext()class FakeChromium:14 unmodified linesraise RuntimeError("registration crashed")monkeypatch.setattr(manager, "sync_playwright", lambda: FakeSyncPlaywright())monkeypatch.setattr(manager, "get_playwright_context_options", lambda: {"locale": "zh-CN"})monkeypatch.setattr(invite, "register_with_invite", fail_register)with pytest.raises(RuntimeError, match="registration crashed"):5 unmodified lines)assert calls == ["close:page", "close:context", "close:browser"]assert captured["kwargs"] == {"locale": "zh-CN"}def test_register_direct_once_cleans_browser_context_on_unhandled_page_error(monkeypatch):calls = []captured = {}class FakePage:url = "about:blank"12 unmodified linescalls.append("close:context")class FakeBrowser:def new_context(self, **kwargs):captured["kwargs"] = kwargsreturn FakeContext()def close(self):14 unmodified linesreturn Falsemonkeypatch.setattr(manager, "sync_playwright", lambda: FakeSyncPlaywright())monkeypatch.setattr(manager, "get_playwright_context_options", lambda: {"timezone_id": "Asia/Shanghai"})with pytest.raises(RuntimeError, match="navigation exploded"):manager._register_direct_once(object(), "child@example.com", "password")assert calls == ["close:page", "close:context", "close:browser"]assert captured["kwargs"] == {"timezone_id": "Asia/Shanghai"}def test_registration_and_oauth_paths_use_unified_playwright_cleanup():3 unmodified linesassert "browser.close()" not in inspect.getsource(codex_auth.login_codex_via_browser)assert "close_playwright_objects" in inspect.getsource(manager._register_direct_once)assert "close_playwright_objects" in inspect.getsource(codex_auth.login_codex_via_browser)assert "get_playwright_context_options()" in inspect.getsource(chatgpt_api.ChatGPTTeamAPI._launch_browser)assert "get_playwright_context_options()" in inspect.getsource(invite.run)assert "get_playwright_context_options()" in inspect.getsource(codex_auth.login_codex_via_browser)assert "get_playwright_context_options()" in inspect.getsource(manager._complete_registration)assert "get_playwright_context_options()" in inspect.getsource(manager._register_direct_once)assert "viewport={\"width\": 1280, \"height\": 800}" not in inspect.getsource(chatgpt_api.ChatGPTTeamAPI._launch_browser)assert "user_agent=\"Mozilla/5.0" not in inspect.getsource(chatgpt_api.ChatGPTTeamAPI._launch_browser)def test_session_codex_auth_flow_stops_chatgpt_when_page_start_fails(monkeypatch):
76 unmodified lines77787980818276 unmodified linesassert uploaded == [enabled_auth.name]assert deleted == []assert result["disabled_skipped"] == 1assert result["delete_guard"]["skipped_protected"] == 176 unmodified lines777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520676 unmodified linesassert uploaded == [enabled_auth.name]assert deleted == []assert result["disabled_skipped"] == 1assert result["delete_guard"]["allow_remote_delete"] is Falseassert result["delete_guard"]["skipped_remote_delete"] == 1def test_sync_to_cpa_allows_remote_delete_when_active_pool_is_stable(monkeypatch, tmp_path):first_auth = tmp_path / "codex-first@example.com-team-a.json"second_auth = tmp_path / "codex-second@example.com-team-b.json"stale_auth = tmp_path / "codex-stale@example.com-team-c.json"first_auth.write_text('{"access_token":"token-first"}', encoding="utf-8")second_auth.write_text('{"access_token":"token-second"}', encoding="utf-8")stale_auth.write_text('{"access_token":"token-stale"}', encoding="utf-8")monkeypatch.setattr("autoteam.accounts.load_accounts",lambda: [{"email": "first@example.com","status": "active","auth_file": str(first_auth),"disabled": False,},{"email": "second@example.com","status": "active","auth_file": str(second_auth),"disabled": False,},{"email": "stale@example.com","status": "standby","auth_file": "","disabled": False,},],)monkeypatch.setattr("autoteam.accounts.save_accounts", lambda _accounts: None)monkeypatch.setattr(cpa_sync, "_cleanup_local_duplicates", lambda _accounts: (0, False))monkeypatch.setattr(cpa_sync,"list_cpa_files",lambda: [{"name": first_auth.name, "email": "first@example.com"},{"name": second_auth.name, "email": "second@example.com"},{"name": stale_auth.name, "email": "stale@example.com"},],)uploaded = []deleted = []monkeypatch.setattr("autoteam.codex_auth.check_codex_quota", lambda *_args, **_kwargs: ("ok", {}))monkeypatch.setattr(cpa_sync, "upload_to_cpa", lambda path: uploaded.append(Path(path).name) or True)monkeypatch.setattr(cpa_sync, "delete_from_cpa", lambda name: deleted.append(name) or True)result = cpa_sync.sync_to_cpa()assert uploaded == [first_auth.name, second_auth.name]assert deleted == [stale_auth.name]assert result["delete_guard"]["allow_remote_delete"] is Trueassert result["delete_guard"]["skipped_remote_delete"] == 0def test_sync_to_cpa_preserves_credential_seat_when_remote_delete_is_allowed(monkeypatch, tmp_path):active_auth = tmp_path / "codex-active@example.com-team-a.json"second_active_auth = tmp_path / "codex-second-active@example.com-team-c.json"protected_auth = tmp_path / "codex-protected@example.com-team-b.json"active_auth.write_text('{"access_token":"token-active"}', encoding="utf-8")second_active_auth.write_text('{"access_token":"token-second-active"}', encoding="utf-8")protected_auth.write_text('{"access_token":"token-protected"}', encoding="utf-8")monkeypatch.setattr("autoteam.accounts.load_accounts",lambda: [{"email": "active@example.com","status": "active","auth_file": str(active_auth),"disabled": False,"mail_provider": "cloudflare_temp_email","mail_account_id": 1,"cloudmail_account_id": None,},{"email": "second-active@example.com","status": "active","auth_file": str(second_active_auth),"disabled": False,"mail_provider": "cloudflare_temp_email","mail_account_id": 2,"cloudmail_account_id": None,},{"email": "protected@example.com","status": "auth_invalid","auth_file": str(protected_auth),"disabled": False,"mail_provider": "","mail_account_id": None,"cloudmail_account_id": None,},],)monkeypatch.setattr("autoteam.accounts.save_accounts", lambda _accounts: None)monkeypatch.setattr(cpa_sync, "_cleanup_local_duplicates", lambda _accounts: (0, False))monkeypatch.setattr(cpa_sync,"list_cpa_files",lambda: [{"name": active_auth.name, "email": "active@example.com"},{"name": second_active_auth.name, "email": "second-active@example.com"},{"name": protected_auth.name, "email": "protected@example.com"},],)uploaded = []deleted = []monkeypatch.setattr("autoteam.codex_auth.check_codex_quota", lambda *_args, **_kwargs: ("ok", {}))monkeypatch.setattr(cpa_sync, "upload_to_cpa", lambda path: uploaded.append(Path(path).name) or True)monkeypatch.setattr(cpa_sync, "delete_from_cpa", lambda name: deleted.append(name) or True)result = cpa_sync.sync_to_cpa()assert uploaded == [active_auth.name, second_active_auth.name]assert deleted == []assert result["delete_guard"]["allow_remote_delete"] is Trueassert result["delete_guard"]["skipped_protected"] == 1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659import base64import jsonfrom datetime import datetime, timezone
import pytest
from autoteam import sub2api_syncfrom autoteam.codex_auth import CODEX_CLIENT_ID
def _jwt(payload: dict) -> str: header = base64.urlsafe_b64encode(json.dumps({"alg": "none"}).encode()).rstrip(b"=").decode() body = base64.urlsafe_b64encode(json.dumps(payload).encode()).rstrip(b"=").decode() return f"{header}.{body}."
def test_build_credentials_matches_openai_oauth_shape(): expires_iso = "2026-04-25T05:44:19Z" id_token = _jwt( { "aud": [CODEX_CLIENT_ID], "email": "tmp@example.com", "https://api.openai.com/auth": { "chatgpt_account_id": "acct-1", "chatgpt_user_id": "user-1", "chatgpt_plan_type": "team", "chatgpt_subscription_active_until": "2026-05-05T15:55:38+00:00", "organizations": [{"id": "org-1", "is_default": True}], }, } )
credentials = sub2api_sync._build_credentials( { "access_token": "at-1", "refresh_token": "rt-1", "id_token": id_token, "expired": expires_iso, } )
assert credentials == { "access_token": "at-1", "expires_at": int(datetime.fromisoformat(expires_iso.replace("Z", "+00:00")).timestamp()), "refresh_token": "rt-1", "id_token": id_token, "client_id": CODEX_CLIENT_ID, "email": "tmp@example.com", "chatgpt_account_id": "acct-1", "chatgpt_user_id": "user-1", "organization_id": "org-1", "plan_type": "team", "subscription_expires_at": "2026-05-05T15:55:38+00:00", }
def test_build_managed_model_mapping_uses_identity_mapping(): assert sub2api_sync._build_managed_model_mapping("gpt-5.4, gpt-5.4-mini") == { "gpt-5.4": "gpt-5.4", "gpt-5.4-mini": "gpt-5.4-mini", }
def test_build_managed_model_mapping_returns_none_when_blank(): assert sub2api_sync._build_managed_model_mapping("") is None
def test_apply_managed_extra_settings_supports_ws_mode_and_passthrough(monkeypatch): monkeypatch.setattr(sub2api_sync, "SUB2API_OPENAI_WS_MODE", "ctx_pool") monkeypatch.setattr(sub2api_sync, "SUB2API_OPENAI_PASSTHROUGH", True)
extra = {"openai_oauth_passthrough": False} sub2api_sync._apply_managed_extra_settings(extra)
assert extra["openai_oauth_responses_websockets_v2_mode"] == "ctx_pool" assert extra["openai_oauth_responses_websockets_v2_enabled"] is True assert extra["openai_passthrough"] is True assert extra["openai_oauth_passthrough"] is False
def test_apply_managed_extra_settings_removes_passthrough_when_disabled(monkeypatch): monkeypatch.setattr(sub2api_sync, "SUB2API_OPENAI_WS_MODE", "off") monkeypatch.setattr(sub2api_sync, "SUB2API_OPENAI_PASSTHROUGH", False)
extra = {"openai_passthrough": True, "openai_oauth_passthrough": True} sub2api_sync._apply_managed_extra_settings(extra)
assert extra["openai_oauth_responses_websockets_v2_mode"] == "off" assert extra["openai_oauth_responses_websockets_v2_enabled"] is False assert "openai_passthrough" not in extra assert "openai_oauth_passthrough" not in extra
def test_build_extra_includes_codex_usage_snapshot(monkeypatch): monkeypatch.setattr(sub2api_sync.time, "time", lambda: 1_700_000_000)
extra = sub2api_sync._build_extra( "tmp@example.com", "codex-tmp@example.com-team-123.json", kind="pool", quota_info={ "primary_pct": 42, "primary_resets_at": 1_700_003_600, "weekly_pct": 88, "weekly_resets_at": 1_700_086_400, }, )
assert extra["autoteam_managed"] is True assert extra["autoteam_kind"] == "pool" assert extra["autoteam_email"] == "tmp@example.com" assert extra["autoteam_auth_file"] == "sub2api-codex-tmp@example.com-team-123.json" assert extra["autoteam_source"] == "autoteam" assert extra["email"] == "tmp@example.com" assert extra["codex_5h_used_percent"] == 42 assert extra["codex_5h_reset_after_seconds"] == 3600 assert extra["codex_5h_reset_at"] == sub2api_sync._to_local_iso(1_700_003_600) assert extra["codex_7d_used_percent"] == 88 assert extra["codex_7d_reset_after_seconds"] == 86_400 assert extra["codex_7d_reset_at"] == sub2api_sync._to_local_iso(1_700_086_400) assert extra["codex_primary_used_percent"] == 42 assert extra["codex_secondary_used_percent"] == 88 assert extra["codex_usage_updated_at"] == datetime.fromtimestamp( 1_700_000_000, timezone.utc ).astimezone().isoformat(timespec="seconds")
def test_attach_group_metadata_records_autoteam_group_binding(): extra = sub2api_sync._build_extra("tmp@example.com", "codex-tmp@example.com-team-123.json", kind="pool") sub2api_sync._attach_group_metadata(extra, [7], ["Team Pool"])
assert extra["autoteam_sub2api_group_ids"] == [7] assert extra["autoteam_sub2api_group_names"] == ["Team Pool"]
def test_resolve_group_binding_supports_name_and_id(monkeypatch): monkeypatch.setattr( sub2api_sync, "_list_openai_groups", lambda token: [ {"id": 7, "name": "Team Pool", "platform": "openai"}, ], ) monkeypatch.setattr( sub2api_sync, "_get_group_by_id", lambda token, group_id: {"id": group_id, "name": f"Group-{group_id}", "platform": "openai"}, )
group_ids, group_names = sub2api_sync._resolve_group_binding("token", "Team Pool, 9")
assert group_ids == [7, 9] assert group_names == ["Team Pool", "Group-9"]
def test_resolve_proxy_id_supports_name_and_id(monkeypatch): monkeypatch.setattr( sub2api_sync, "_list_proxies", lambda token: [ {"id": 42, "name": "Residential Pool"}, ], )
assert sub2api_sync._resolve_proxy_id("token", "") is None assert sub2api_sync._resolve_proxy_id("token", "42") == 42 assert sub2api_sync._resolve_proxy_id("token", "residential pool") == 42
@pytest.mark.parametrize("proxy_spec", ["0", "-1"])def test_resolve_proxy_id_rejects_invalid_numeric_values(proxy_spec): with pytest.raises(RuntimeError, match="代理 ID 必须是正整数"): sub2api_sync._resolve_proxy_id("token", proxy_spec)
def test_resolve_proxy_id_reports_unknown_name(monkeypatch): monkeypatch.setattr(sub2api_sync, "_list_proxies", lambda token: [{"id": 42, "name": "Residential Pool"}])
with pytest.raises(RuntimeError, match="未找到代理"): sub2api_sync._resolve_proxy_id("token", "Missing Proxy")
def test_create_account_includes_proxy_id_only_when_provided(monkeypatch): payloads = []
def fake_request(method, path, **kwargs): payloads.append(kwargs["json"]) return {"id": len(payloads)}
monkeypatch.setattr(sub2api_sync, "_request", fake_request)
sub2api_sync._create_account( "token", name="with-proxy", credentials={"access_token": "at-1"}, extra={}, label="创建账号", proxy_id=42, ) sub2api_sync._create_account( "token", name="without-proxy", credentials={"access_token": "at-1"}, extra={}, label="创建账号", proxy_id=None, )
assert payloads[0]["proxy_id"] == 42 assert "proxy_id" not in payloads[1]
def test_merge_group_ids_preserves_manual_groups_and_replaces_previous_managed_group(): account = { "group_ids": [11, 21], "extra": { "autoteam_sub2api_group_ids": [21], }, }
assert sub2api_sync._merge_group_ids(account, [22]) == [11, 22] assert sub2api_sync._merge_group_ids(account, []) == [11]
def test_remote_auth_file_candidates_include_legacy_and_prefixed_names(): assert sub2api_sync._remote_auth_file_candidates(["codex-a.json"]) == { "codex-a.json", "sub2api-codex-a.json", }
def test_sync_account_to_sub2api_creates_single_account_without_remote_cleanup(monkeypatch, tmp_path): auth_file = tmp_path / "codex-tmp@example.com-team-abc.json" auth_file.write_text(json.dumps({"email": "tmp@example.com", "access_token": "at-1"}), encoding="utf-8") created_payloads = [] deleted = []
monkeypatch.setattr(sub2api_sync, "_login", lambda: "token") monkeypatch.setattr(sub2api_sync, "_resolve_group_binding", lambda token: ([7], ["Team Pool"])) monkeypatch.setattr( sub2api_sync, "_list_openai_oauth_accounts", lambda token: [ { "id": 99, "name": "other@example.com", "extra": { "autoteam_source": "autoteam", "autoteam_kind": "pool", "autoteam_email": "other@example.com", }, } ], ) monkeypatch.setattr(sub2api_sync, "_resolve_proxy_id", lambda token: 42) monkeypatch.setattr(sub2api_sync, "_delete_account", lambda *args, **kwargs: deleted.append((args, kwargs)) or True) monkeypatch.setattr( sub2api_sync, "_create_account", lambda token, **kwargs: created_payloads.append(kwargs) or {"id": 12}, )
result = sub2api_sync.sync_account_to_sub2api("tmp@example.com", str(auth_file), quota_info={"primary_pct": 12})
assert result == { "uploaded": f"sub2api-{auth_file.name}", "action": "created", "account_id": 12, "remote_duplicates_seen": 0, } assert deleted == [] assert created_payloads[0]["name"] == "tmp@example.com" assert created_payloads[0]["credentials"]["access_token"] == "at-1" assert created_payloads[0]["extra"]["autoteam_email"] == "tmp@example.com" assert created_payloads[0]["extra"]["codex_5h_used_percent"] == 12 assert created_payloads[0]["group_ids"] == [7] assert created_payloads[0]["proxy_id"] == 42
def test_sync_to_sub2api_preserves_existing_manual_settings_when_overwrite_disabled(monkeypatch, tmp_path): monkeypatch.setattr(sub2api_sync, "SUB2API_OVERWRITE_ACCOUNT_SETTINGS", False) monkeypatch.setattr(sub2api_sync, "SUB2API_PROXY", "Residential Pool") monkeypatch.setattr(sub2api_sync, "_login", lambda: "token") monkeypatch.setattr(sub2api_sync, "_resolve_group_binding", lambda token: ([7], ["Team Pool"])) monkeypatch.setattr( sub2api_sync, "_resolve_proxy_id", lambda token: (_ for _ in ()).throw(AssertionError("proxy should not be resolved without create")), ) monkeypatch.setattr(sub2api_sync, "_list_openai_oauth_accounts", lambda token: []) monkeypatch.setattr( sub2api_sync, "_dedupe_managed_accounts", lambda token, items, *, kind: ( { "tmp@example.com": { "id": 12, "status": "disabled", "credentials": {"model_mapping": {"manual-model": "manual-model"}}, "extra": { "openai_oauth_responses_websockets_v2_mode": "passthrough", "openai_oauth_responses_websockets_v2_enabled": True, "openai_passthrough": True, }, "group_ids": [99, 21], } }, 0, ), )
auth_path = tmp_path / "codex-tmp@example.com-team-123.json" auth_path.write_text("{}", encoding="utf-8")
monkeypatch.setattr( "autoteam.accounts.load_accounts", lambda: [ { "email": "tmp@example.com", "status": "active", "auth_file": str(auth_path), "last_quota": {"primary_pct": 10, "weekly_pct": 20}, } ], ) monkeypatch.setattr( sub2api_sync, "_load_auth_data", lambda path: { "email": "tmp@example.com", "access_token": "at-1", "refresh_token": "rt-1", }, )
captured = {}
def fake_update_account(token, account, **kwargs): captured.update(kwargs) return {"ok": True}
monkeypatch.setattr(sub2api_sync, "_update_account", fake_update_account)
sub2api_sync.sync_to_sub2api()
assert captured["credentials"]["model_mapping"] == {"manual-model": "manual-model"} assert captured["extra"]["openai_oauth_responses_websockets_v2_mode"] == "passthrough" assert captured["extra"]["openai_oauth_responses_websockets_v2_enabled"] is True assert captured["extra"]["openai_passthrough"] is True assert captured["account_settings"] is None assert "proxy_id" not in captured
def test_sync_to_sub2api_overwrites_managed_settings_when_enabled(monkeypatch, tmp_path): monkeypatch.setattr(sub2api_sync, "SUB2API_OVERWRITE_ACCOUNT_SETTINGS", True) monkeypatch.setattr(sub2api_sync, "SUB2API_CONCURRENCY", 12) monkeypatch.setattr(sub2api_sync, "SUB2API_PRIORITY", 3) monkeypatch.setattr(sub2api_sync, "SUB2API_RATE_MULTIPLIER", 1.5) monkeypatch.setattr(sub2api_sync, "SUB2API_AUTO_PAUSE_ON_EXPIRED", False) monkeypatch.setattr(sub2api_sync, "SUB2API_OPENAI_WS_MODE", "ctx_pool") monkeypatch.setattr(sub2api_sync, "SUB2API_OPENAI_PASSTHROUGH", False) monkeypatch.setattr(sub2api_sync, "SUB2API_MODEL_WHITELIST", "gpt-5.4,gpt-5.4-mini") monkeypatch.setattr(sub2api_sync, "_login", lambda: "token") monkeypatch.setattr(sub2api_sync, "_resolve_group_binding", lambda token: ([], [])) monkeypatch.setattr( sub2api_sync, "_resolve_proxy_id", lambda token: (_ for _ in ()).throw(AssertionError("proxy should not be resolved without create")), ) monkeypatch.setattr(sub2api_sync, "_list_openai_oauth_accounts", lambda token: []) monkeypatch.setattr( sub2api_sync, "_dedupe_managed_accounts", lambda token, items, *, kind: ( { "tmp@example.com": { "id": 12, "status": "disabled", "credentials": {"model_mapping": {"manual-model": "manual-model"}}, "extra": { "openai_oauth_responses_websockets_v2_mode": "off", "openai_oauth_responses_websockets_v2_enabled": False, "openai_passthrough": True, "openai_oauth_passthrough": True, }, "group_ids": [], } }, 0, ), )
auth_path = tmp_path / "codex-tmp@example.com-team-123.json" auth_path.write_text("{}", encoding="utf-8")
monkeypatch.setattr( "autoteam.accounts.load_accounts", lambda: [ { "email": "tmp@example.com", "status": "active", "auth_file": str(auth_path), "last_quota": None, } ], ) monkeypatch.setattr( sub2api_sync, "_load_auth_data", lambda path: { "email": "tmp@example.com", "access_token": "at-1", "refresh_token": "rt-1", }, )
captured = {}
def fake_update_account(token, account, **kwargs): captured.update(kwargs) return {"ok": True}
monkeypatch.setattr(sub2api_sync, "_update_account", fake_update_account)
sub2api_sync.sync_to_sub2api()
assert captured["account_settings"] == { "concurrency": 12, "priority": 3, "rate_multiplier": 1.5, "auto_pause_on_expired": False, } assert captured["credentials"]["model_mapping"] == { "gpt-5.4": "gpt-5.4", "gpt-5.4-mini": "gpt-5.4-mini", } assert captured["extra"]["openai_oauth_responses_websockets_v2_mode"] == "ctx_pool" assert captured["extra"]["openai_oauth_responses_websockets_v2_enabled"] is True assert "openai_passthrough" not in captured["extra"] assert "openai_oauth_passthrough" not in captured["extra"]
def test_sync_to_sub2api_does_not_resolve_proxy_when_only_deleting_non_active_accounts(monkeypatch): monkeypatch.setattr(sub2api_sync, "SUB2API_PROXY", "Missing Proxy") monkeypatch.setattr(sub2api_sync, "_login", lambda: "token") monkeypatch.setattr(sub2api_sync, "_resolve_group_binding", lambda token: ([], [])) monkeypatch.setattr( sub2api_sync, "_resolve_proxy_id", lambda token: (_ for _ in ()).throw(AssertionError("proxy should not be resolved without create")), ) monkeypatch.setattr(sub2api_sync, "_list_openai_oauth_accounts", lambda token: []) monkeypatch.setattr( "autoteam.accounts.load_accounts", lambda: [ { "email": "tmp@example.com", "status": "standby", "auth_file": "", "last_quota": None, } ], ) monkeypatch.setattr( sub2api_sync, "_dedupe_managed_accounts", lambda token, items, *, kind: ( { "tmp@example.com": { "id": 12, "status": "active", "credentials": {"email": "tmp@example.com"}, "extra": {}, "group_ids": [], } }, 0, ), )
deleted = []
def fake_delete_account(token, account, **kwargs): deleted.append((account["id"], kwargs["label"])) return {"ok": True}
monkeypatch.setattr(sub2api_sync, "_delete_account", fake_delete_account)
result = sub2api_sync.sync_to_sub2api()
assert result["deleted"] == 1 assert deleted == [(12, "删除非 active 账号")]
def test_sync_to_sub2api_skips_disabled_local_accounts(monkeypatch, tmp_path): monkeypatch.setattr(sub2api_sync, "_login", lambda: "token") monkeypatch.setattr(sub2api_sync, "_resolve_group_binding", lambda token: ([], [])) monkeypatch.setattr(sub2api_sync, "_list_openai_oauth_accounts", lambda token: []) monkeypatch.setattr( sub2api_sync, "_dedupe_managed_accounts", lambda token, items, *, kind: ( { "disabled@example.com": { "id": 12, "status": "active", "credentials": {"email": "disabled@example.com"}, "extra": {}, "group_ids": [], } }, 0, ), )
enabled_auth = tmp_path / "codex-enabled@example.com-team-a.json" disabled_auth = tmp_path / "codex-disabled@example.com-team-b.json" enabled_auth.write_text("{}", encoding="utf-8") disabled_auth.write_text("{}", encoding="utf-8")
monkeypatch.setattr( "autoteam.accounts.load_accounts", lambda: [ {"email": "enabled@example.com", "status": "active", "auth_file": str(enabled_auth), "disabled": False}, {"email": "disabled@example.com", "status": "active", "auth_file": str(disabled_auth), "disabled": True}, ], ) monkeypatch.setattr( sub2api_sync, "_load_auth_data", lambda path: { "email": "enabled@example.com" if "enabled@" in str(path) else "disabled@example.com", "access_token": "at-1", "refresh_token": "rt-1", }, )
created = [] updated = [] deleted = [] monkeypatch.setattr( sub2api_sync, "_create_account", lambda token, **kwargs: created.append(kwargs["name"]) or {"id": 99}, ) monkeypatch.setattr( sub2api_sync, "_update_account", lambda token, account, **kwargs: updated.append(account["id"]) or {"ok": True}, ) monkeypatch.setattr( sub2api_sync, "_delete_account", lambda token, account, **kwargs: deleted.append(account["id"]) or {"ok": True}, )
result = sub2api_sync.sync_to_sub2api()
assert result["created"] == 1 assert result["updated"] == 0 assert result["deleted"] == 1 assert created == ["enabled@example.com"] assert updated == [] assert deleted == [12]
def test_sync_to_sub2api_resolves_proxy_name_for_new_pool_accounts(monkeypatch, tmp_path): monkeypatch.setattr(sub2api_sync, "SUB2API_PROXY", "Residential Pool") monkeypatch.setattr(sub2api_sync, "_login", lambda: "token") monkeypatch.setattr(sub2api_sync, "_resolve_group_binding", lambda token: ([], [])) monkeypatch.setattr(sub2api_sync, "_list_proxies", lambda token: [{"id": 42, "name": "Residential Pool"}]) monkeypatch.setattr(sub2api_sync, "_list_openai_oauth_accounts", lambda token: []) monkeypatch.setattr(sub2api_sync, "_dedupe_managed_accounts", lambda token, items, *, kind: ({}, 0))
auth_path = tmp_path / "codex-tmp@example.com-team-123.json" auth_path.write_text("{}", encoding="utf-8") monkeypatch.setattr( "autoteam.accounts.load_accounts", lambda: [ { "email": "tmp@example.com", "status": "active", "auth_file": str(auth_path), "last_quota": None, } ], ) monkeypatch.setattr( sub2api_sync, "_load_auth_data", lambda path: { "email": "tmp@example.com", "access_token": "at-1", "refresh_token": "rt-1", }, )
captured = {}
def fake_create_account(token, **kwargs): captured.update(kwargs) return {"id": 99}
monkeypatch.setattr(sub2api_sync, "_create_account", fake_create_account)
result = sub2api_sync.sync_to_sub2api()
assert result["created"] == 1 assert captured["proxy_id"] == 42
def test_sync_main_codex_to_sub2api_creates_account_with_managed_defaults(monkeypatch, tmp_path): monkeypatch.setattr(sub2api_sync, "SUB2API_PROXY", "Residential Pool") monkeypatch.setattr(sub2api_sync, "SUB2API_CONCURRENCY", 8) monkeypatch.setattr(sub2api_sync, "SUB2API_PRIORITY", 2) monkeypatch.setattr(sub2api_sync, "SUB2API_RATE_MULTIPLIER", 2.5) monkeypatch.setattr(sub2api_sync, "SUB2API_AUTO_PAUSE_ON_EXPIRED", True) monkeypatch.setattr(sub2api_sync, "SUB2API_MODEL_WHITELIST", "gpt-5.4") monkeypatch.setattr(sub2api_sync, "SUB2API_OPENAI_WS_MODE", "passthrough") monkeypatch.setattr(sub2api_sync, "SUB2API_OPENAI_PASSTHROUGH", True) monkeypatch.setattr(sub2api_sync, "_login", lambda: "token") monkeypatch.setattr(sub2api_sync, "_resolve_group_binding", lambda token: ([7], ["Team Pool"])) monkeypatch.setattr(sub2api_sync, "_list_openai_oauth_accounts", lambda token: []) monkeypatch.setattr(sub2api_sync, "_dedupe_managed_accounts", lambda token, items, *, kind: ({}, 0))
auth_path = tmp_path / "main.json" auth_path.write_text("{}", encoding="utf-8") monkeypatch.setattr( sub2api_sync, "_load_auth_data", lambda path: { "email": "main@example.com", "access_token": "at-1", "refresh_token": "rt-1", }, )
captured = {}
def fake_create_account(token, **kwargs): captured.update(kwargs) return {"id": 99}
monkeypatch.setattr(sub2api_sync, "_create_account", fake_create_account)
result = sub2api_sync.sync_main_codex_to_sub2api(str(auth_path))
assert result["account_id"] == 99 assert captured["account_settings"] == { "concurrency": 8, "priority": 2, "rate_multiplier": 2.5, "auto_pause_on_expired": True, } assert captured["credentials"]["model_mapping"] == {"gpt-5.4": "gpt-5.4"} assert captured["extra"]["openai_oauth_responses_websockets_v2_mode"] == "passthrough" assert captured["extra"]["openai_oauth_responses_websockets_v2_enabled"] is True assert captured["extra"]["openai_passthrough"] is True assert "proxy_id" not in captured123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110from pathlib import Path
from autoteam import sync_targets
def test_get_sync_target_states_uses_implicit_config_presence(): env = { "CPA_URL": "http://127.0.0.1:8317", "CPA_KEY": "key-1", "SUB2API_URL": "http://sub2api.local", "SUB2API_EMAIL": "admin@example.com", "SUB2API_PASSWORD": "secret", }
assert sync_targets.get_sync_target_states(env) == { "cpa": True, "sub2api": True, }
def test_get_sync_target_states_respects_explicit_toggle_override(): env = { "SYNC_TARGET_CPA": "false", "CPA_URL": "http://127.0.0.1:8317", "CPA_KEY": "key-1", "SYNC_TARGET_SUB2API": "true", }
assert sync_targets.get_sync_target_states(env) == { "cpa": False, "sub2api": True, }
def test_describe_sync_targets_formats_labels(): assert sync_targets.describe_sync_targets(["cpa"]) == "CPA" assert sync_targets.describe_sync_targets(["cpa", "sub2api"]) == "CPA + Sub2API"
def test_sync_account_to_configured_targets_uploads_one_active_auth(monkeypatch, tmp_path): auth_file = tmp_path / "codex-user@example.com-team-a.json" auth_file.write_text('{"access_token":"token"}', encoding="utf-8")
monkeypatch.setattr( "autoteam.accounts.load_accounts", lambda: [ { "email": "user@example.com", "status": "active", "auth_file": str(auth_file), "disabled": False, "last_quota": {"primary_pct": 12}, } ], ) monkeypatch.setattr( sync_targets, "get_enabled_sync_targets", lambda: [sync_targets.SYNC_TARGET_CPA, sync_targets.SYNC_TARGET_SUB2API], )
cpa_uploads = [] sub2_uploads = [] monkeypatch.setattr("autoteam.cpa_sync.upload_to_cpa", lambda path: cpa_uploads.append(Path(path).name) or True) monkeypatch.setattr( "autoteam.sub2api_sync.sync_account_to_sub2api", lambda email, filepath, *, quota_info=None: sub2_uploads.append( (email, Path(filepath).name, quota_info) ) or {"uploaded": f"sub2api-{Path(filepath).name}", "action": "created", "account_id": 12}, )
result = sync_targets.sync_account_to_configured_targets("USER@example.com", str(auth_file))
assert result["ok"] is True assert cpa_uploads == [auth_file.name] assert sub2_uploads == [("user@example.com", auth_file.name, {"primary_pct": 12})] assert result["targets"]["cpa"]["uploaded"] == auth_file.name assert result["targets"]["sub2api"]["uploaded"] == f"sub2api-{auth_file.name}"
def test_sync_account_to_configured_targets_skips_non_active_auth(monkeypatch, tmp_path): auth_file = tmp_path / "codex-user@example.com-team-a.json" auth_file.write_text('{"access_token":"token"}', encoding="utf-8")
monkeypatch.setattr( "autoteam.accounts.load_accounts", lambda: [{"email": "user@example.com", "status": "standby", "auth_file": str(auth_file)}], ) monkeypatch.setattr( sync_targets, "get_enabled_sync_targets", lambda: [sync_targets.SYNC_TARGET_CPA, sync_targets.SYNC_TARGET_SUB2API], ) monkeypatch.setattr( "autoteam.cpa_sync.upload_to_cpa", lambda _path: (_ for _ in ()).throw(AssertionError("inactive account must not upload to CPA")), ) monkeypatch.setattr( "autoteam.sub2api_sync.sync_account_to_sub2api", lambda *_args, **_kwargs: (_ for _ in ()).throw( AssertionError("inactive account must not upload to Sub2API") ), )
result = sync_targets.sync_account_to_configured_targets("user@example.com", str(auth_file))
assert result["ok"] is False assert result["skipped"] is True assert result["reason"] == "account_not_active"3 unmodified lines4567891011121314151617181 unmodified line202122232425262711 unmodified lines39404142434445467 unmodified lines54555657585960616263646566676869707172733 unmodified lines777879808182832 unmodified lines868788899091929315 unmodified lines10911011111211311411511611711811912012112212312412512612712812913013113213313413525 unmodified lines1611621631641651661676 unmodified lines1741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072 unmodified lines21021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524610 unmodified lines25725825926026126226315 unmodified lines2792802812822832842852862872882893 unmodified lines<!-- 登录页 --><div v-else-if="!authenticated" class="min-h-screen flex items-center justify-center px-4"><div class="glass rounded-2xl p-8 w-full max-w-sm relative overflow-hidden"><div class="absolute -top-20 -right-20 w-56 h-56 rounded-full opacity-40 blur-3xl pointer-events-none"style="background: radial-gradient(circle, rgba(99, 102, 241, 0.45), transparent 60%);"></div><div class="relative"><div class="text-[10px] uppercase tracking-[0.3em] text-indigo-300/70 mb-1">Account Operations</div><h1 class="text-2xl font-extrabold text-white mb-1 tracking-tight">AutoTeam</h1><p class="text-sm text-gray-400 mb-6">输入管理 API Key 进入控制台</p><div v-if="authError"class="mb-4 px-3 py-2.5 rounded-lg text-sm bg-rose-500/10 text-rose-300 border border-rose-500/30">{{ authError }}</div><input1 unmodified linetype="password"placeholder="API Key"@keyup.enter="doLogin"class="w-full px-3.5 py-2.5 bg-white/[0.03] border border-white/10 rounded-xl text-sm text-whitefont-mono placeholder:text-gray-600 focus-ring focus:border-indigo-400/40 mb-4 transition" /><AtButton variant="primary" class="w-full" :loading="authLoading" :disabled="!inputKey" @click="doLogin">{{ authLoading ? '验证中…' : '进入控制台' }}</AtButton>11 unmodified lines<div class="flex-1 p-4 md:p-6 overflow-y-auto pb-20 md:pb-6 max-w-screen-2xl mx-auto w-full"><!-- 任务执行中提示 --><div v-if="busyTask"class="flex items-center gap-2.5 text-sm text-amber-300 mb-4 px-3 py-2 rounded-xl border border-amber-500/20 bg-amber-500/5 w-fit animate-rise"><span class="animate-spin inline-block w-3.5 h-3.5 border-2 border-amber-300 border-t-transparent rounded-full"></span><span class="font-medium">{{ busyTask.command === 'admin-login'? '管理员登录中...'7 unmodified lines<Transition name="page" mode="out-in"><Dashboard v-if="currentPage === 'dashboard'" key="dashboard":status="status" :loading="loading" :running-task="busyTask" :admin-status="adminStatus":master-health="masterHealth" @refresh="refresh" @reload-master-health="reloadMasterHealth" /><TeamMembers v-else-if="currentPage === 'team'" key="team" /><PoolPage v-else-if="currentPage === 'pool'" key="pool":running-task="busyTask" :admin-status="adminStatus" :master-health="masterHealth" :status="status"@task-started="onTaskStarted" @refresh="refresh" @reload-master-health="reloadMasterHealth" /><SyncPage v-else-if="currentPage === 'sync'" key="sync":running-task="busyTask" :admin-status="adminStatus"@task-started="onTaskStarted" @refresh="refresh" /><OAuthPage v-else-if="currentPage === 'oauth'" key="oauth":manual-account-status="manualAccountStatus" @refresh="refresh" @progress="onAdminProgress" /><TaskHistoryPage v-else-if="currentPage === 'tasks'" key="tasks":tasks="tasks" />3 unmodified lines<Settings v-else-if="currentPage === 'settings'" key="settings":admin-status="adminStatus" :codex-status="codexStatus":master-health="masterHealth" :status="status"@refresh="refresh" @admin-progress="onAdminProgress" @reload-master-health="reloadMasterHealth" /></Transition></div>2 unmodified lines</template><script setup>import { computed, ref, onMounted, onUnmounted, watch } from 'vue'import { api, setApiKey, clearApiKey } from './api.js'import SetupPage from './components/SetupPage.vue'import Sidebar from './components/Sidebar.vue'import Dashboard from './components/Dashboard.vue'15 unmodified linesconst inputKey = ref('')const currentPage = ref('dashboard')const status = ref(null)const adminStatus = ref(null)const codexStatus = ref(null)const manualAccountStatus = ref(null)const tasks = ref([])const loading = ref(false)const runningTask = ref(null)// Round 9 — master-health 提到 App 级,4 个页面共享同一份(避免每页各刷各的)const masterHealth = ref(null)const masterHealthLoading = ref(false)const busyTask = computed(() => {if (adminStatus.value?.login_in_progress) {return { command: 'admin-login' }}if (codexStatus.value?.in_progress) {return { command: 'main-codex-sync' }}return runningTask.value})let pollTimer = nullasync function checkAuth() {try {25 unmodified lines} else {inputKey.value = ''refresh()startPolling(600000)}} catch (e) {clearApiKey()6 unmodified linesfunction doLogout() {clearApiKey()authenticated.value = falsestopPolling()}async function refresh() {loading.value = truetry {const [s, t, admin, codex, manualAccount] = await Promise.all([api.getStatus(),api.getTasks(),api.getAdminStatus(),api.getMainCodexStatus(),api.getManualAccountStatus(),])status.value = stasks.value = tadminStatus.value = admincodexStatus.value = codexmanualAccountStatus.value = manualAccountrunningTask.value = t.find(t => t.status === 'running' || t.status === 'pending') || null} catch (e) {if (e.status === 401) {authenticated.value = falsereturn}console.error('刷新失败:', e)} finally {loading.value = false}}async function reloadMasterHealth(forceRefresh = false) {2 unmodified linestry {masterHealth.value = await api.getMasterHealth(!!forceRefresh)} catch (e) {console.error('加载母号健康度失败:', e)} finally {masterHealthLoading.value = false}}function onTaskStarted() {startPolling(10000)refresh()}function onAdminProgress() {startPolling(10000)refresh()}function startPolling(interval = 600000) {stopPolling()pollTimer = setInterval(async () => {await refresh()if (!busyTask.value && interval < 600000) {startPolling(600000)}}, interval)}function stopPolling() {if (pollTimer) {clearInterval(pollTimer)pollTimer = null}}async function checkSetup() {10 unmodified linescheckAuth().then(ok => {if (ok) {refresh()startPolling(600000)}})}15 unmodified linesconst ok = await checkAuth()if (ok) {refresh()startPolling(600000)}})onUnmounted(() => {stopPolling()})</script>3 unmodified lines456789101112131415161 unmodified line181920212223242511 unmodified lines37383940414243447 unmodified lines5253545556575859606162636465666768697071727374753 unmodified lines798081828384852 unmodified lines88899091929394959615 unmodified lines11211311411511611711811912012112212312412512612712812913013113213313425 unmodified lines1601611621631641656 unmodified lines1721731741751761771781791801812 unmodified lines18418518618718818919019119219319419519619719819920020120220320420510 unmodified lines21621721821922022115 unmodified lines2372382392402412423 unmodified lines<!-- 登录页 --><div v-else-if="!authenticated" class="min-h-screen flex items-center justify-center px-4"><div class="glass rounded-lg p-8 w-full max-w-sm"><div><div class="text-[10px] uppercase tracking-[0.3em] text-ink-400 mb-1">Account Operations</div><h1 class="text-2xl font-extrabold text-ink-950 mb-1 tracking-tight">AutoTeam</h1><p class="text-sm text-ink-500 mb-6">输入管理 API Key 进入控制台</p><div v-if="authError"class="mb-4 px-3 py-2.5 rounded-lg text-sm bg-rose-50 text-rose-700 border border-rose-200">{{ authError }}</div><input1 unmodified linetype="password"placeholder="API Key"@keyup.enter="doLogin"class="w-full px-3.5 py-2.5 bg-surface border border-hairline rounded-lg text-sm text-ink-950font-mono placeholder:text-ink-400 focus-ring mb-4 transition" /><AtButton variant="primary" class="w-full" :loading="authLoading" :disabled="!inputKey" @click="doLogin">{{ authLoading ? '验证中…' : '进入控制台' }}</AtButton>11 unmodified lines<div class="flex-1 p-4 md:p-6 overflow-y-auto pb-20 md:pb-6 max-w-screen-2xl mx-auto w-full"><!-- 任务执行中提示 --><div v-if="busyTask"class="flex items-center gap-2.5 text-sm text-amber-800 mb-4 px-3 py-2 rounded-lg border border-amber-200 bg-amber-50 w-fit animate-rise"><span class="animate-spin inline-block w-3.5 h-3.5 border-2 border-amber-700 border-t-transparent rounded-full"></span><span class="font-medium">{{ busyTask.command === 'admin-login'? '管理员登录中...'7 unmodified lines<Transition name="page" mode="out-in"><Dashboard v-if="currentPage === 'dashboard'" key="dashboard":status="status" :loading="loading" :running-task="busyTask" :admin-status="adminStatus":register-failures="registerFailures" :register-failures-loading="registerFailuresLoading":register-failures-unavailable="registerFailuresUnavailable":master-health="masterHealth" @refresh="onActionRefresh" @reload-master-health="reloadMasterHealth" /><TeamMembers v-else-if="currentPage === 'team'" key="team" /><PoolPage v-else-if="currentPage === 'pool'" key="pool":running-task="busyTask" :admin-status="adminStatus" :master-health="masterHealth" :status="status":rotate-stream="rotateStream"@task-started="onTaskStarted" @refresh="onActionRefresh" @reload-master-health="reloadMasterHealth" /><SyncPage v-else-if="currentPage === 'sync'" key="sync":running-task="busyTask" :admin-status="adminStatus":rotate-stream="rotateStream"@task-started="onTaskStarted" @refresh="onActionRefresh" /><OAuthPage v-else-if="currentPage === 'oauth'" key="oauth":manual-account-status="manualAccountStatus" @refresh="onActionRefresh" @progress="onAdminProgress" /><TaskHistoryPage v-else-if="currentPage === 'tasks'" key="tasks":tasks="tasks" />3 unmodified lines<Settings v-else-if="currentPage === 'settings'" key="settings":admin-status="adminStatus" :codex-status="codexStatus":master-health="masterHealth" :status="status"@refresh="onActionRefresh" @admin-progress="onAdminProgress" @reload-master-health="reloadMasterHealth" /></Transition></div>2 unmodified lines</template><script setup>import { ref, onMounted, watch } from 'vue'import { api, setApiKey, clearApiKey } from './api.js'import { useAppState } from './composables/useAppState.js'import SetupPage from './components/SetupPage.vue'import Sidebar from './components/Sidebar.vue'import Dashboard from './components/Dashboard.vue'15 unmodified linesconst inputKey = ref('')const currentPage = ref('dashboard')const appState = useAppState(authenticated)const {status,adminStatus,codexStatus,manualAccountStatus,registerFailures,registerFailuresLoading,registerFailuresUnavailable,tasks,loading,busyTask,rotateStream,} = appState// Round 9 — master-health 提到 App 级,4 个页面共享同一份(避免每页各刷各的)const masterHealth = ref(null)const masterHealthLoading = ref(false)async function checkAuth() {try {25 unmodified lines} else {inputKey.value = ''refresh()}} catch (e) {clearApiKey()6 unmodified linesfunction doLogout() {clearApiKey()authenticated.value = false}async function refresh() {await appState.refresh()}async function reloadMasterHealth(forceRefresh = false) {2 unmodified linestry {masterHealth.value = await api.getMasterHealth(!!forceRefresh)} catch (e) {masterHealth.value = null} finally {masterHealthLoading.value = false}}function onTaskStarted() {appState.notifyActionStarted()}function onAdminProgress() {appState.notifyActionStarted()}function onActionRefresh() {appState.notifyActionStarted()}async function checkSetup() {10 unmodified linescheckAuth().then(ok => {if (ok) {refresh()}})}15 unmodified linesconst ok = await checkAuth()if (ok) {refresh()}})</script>
12345645 unmodified lines525354555657const BASE = '/api'function getApiKey() {return localStorage.getItem('autoteam_api_key') || ''}45 unmodified linesgetAccounts: () => request('GET', '/accounts'),getActiveAccounts: () => request('GET', '/accounts/active'),getStandbyAccounts: () => request('GET', '/accounts/standby'),deleteAccount: (email) => request('DELETE', `/accounts/${encodeURIComponent(email)}`),deleteAccountsBatch: (emails, continueOnError = true) => request('POST', '/accounts/delete-batch', { emails, continue_on_error: continueOnError }),loginAccount: (email) => request('POST', '/accounts/login', { email }),12345645 unmodified lines52535455565758596061const BASE = '/api'export function getApiKey() {return localStorage.getItem('autoteam_api_key') || ''}45 unmodified linesgetAccounts: () => request('GET', '/accounts'),getActiveAccounts: () => request('GET', '/accounts/active'),getStandbyAccounts: () => request('GET', '/accounts/standby'),bulkDisableAccounts: (emails) => request('POST', '/accounts/bulk/disable', { emails }),bulkEnableAccounts: (emails) => request('POST', '/accounts/bulk/enable', { emails }),disableAccount: (email) => request('POST', `/accounts/${encodeURIComponent(email)}/disable`),enableAccount: (email) => request('POST', `/accounts/${encodeURIComponent(email)}/enable`),deleteAccount: (email) => request('DELETE', `/accounts/${encodeURIComponent(email)}`),deleteAccountsBatch: (emails, continueOnError = true) => request('POST', '/accounts/delete-batch', { emails, continue_on_error: continueOnError }),loginAccount: (email) => request('POST', '/accounts/login', { email }),
9 unmodified lines1011121314151646 unmodified lines63646566676869707172737475767778798081829 unmodified lines:disabled="disabled || loading"@click="onClick":class="classes"class="relative inline-flex items-center justify-center gap-2 font-medium rounded-xllift-hover focus-ring select-none whitespace-nowrapdisabled:cursor-not-allowed disabled:opacity-50"><span v-if="loading"46 unmodified linesconst variantClasses = computed(() => {if (props.variant === 'primary') {// round-12 F1 — text-on-accent 绕过 §Compat 层 text-white 翻转,保留白前景return ['text-on-accent border border-indigo-500/30','bg-gradient-to-br from-indigo-500 via-indigo-600 to-violet-600','shadow-card hover:shadow-ring-accent','hover:from-indigo-400 hover:via-indigo-500 hover:to-violet-500','active:from-indigo-600 active:via-indigo-700 active:to-violet-700',].join(' ')}if (props.variant === 'danger') {if (confirming.value) {return ['text-on-accent border border-rose-500/30','bg-gradient-to-br from-rose-500 via-red-600 to-rose-700','shadow-card ring-2 ring-rose-400/40',].join(' ')}9 unmodified lines1011121314151646 unmodified lines63646566676869707172737475767778798081829 unmodified lines:disabled="disabled || loading"@click="onClick":class="classes"class="relative inline-flex items-center justify-center gap-2 font-medium rounded-lglift-hover focus-ring select-none whitespace-nowrapdisabled:cursor-not-allowed disabled:opacity-50"><span v-if="loading"46 unmodified linesconst variantClasses = computed(() => {if (props.variant === 'primary') {// round-12 F1 — text-on-accent 绕过旧深色兼容层,保留高对比前景return ['text-on-accent border border-indigo-500/30','bg-indigo-600','shadow-card hover:shadow-ring-accent','hover:bg-indigo-500','active:bg-indigo-700',].join(' ')}if (props.variant === 'danger') {if (confirming.value) {return ['text-on-accent border border-rose-500/30','bg-rose-600','shadow-card ring-2 ring-rose-400/40',].join(' ')}
13 unmodified lines1415161718192021222324252 unmodified lines2829303132333435363738394041424344452 unmodified lines484950515253545556575859606162636465666768697071722 unmodified lines757677787980817 unmodified lines8990919293949596972 unmodified lines1001011021031041051061071081091101111121131148 unmodified lines12312412512612712812913013113213313413513 unmodified lines1491501511521531541551561571581591601611621631641651661671681691709 unmodified lines1801811821831841851861871881891901 unmodified line1921931941951961971981992002012022032042 unmodified lines2072082092102112122132142152162172182192202212222232242252 unmodified lines2282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622637 unmodified lines27127227327427527627727827928028128228328428528628728828929010 unmodified lines3013023033043053065 unmodified lines3123133143153163173183193203213223233243253263273283293303313323333343353363373383395 unmodified lines3453463473483493503513523533543553563573583595 unmodified lines36536636736836937037137237337437537637737837938038138238338420 unmodified lines4054064074084094104114 unmodified lines41641741841942042142242342442542642742862 unmodified lines4914924934944954963 unmodified lines50050150250350450562 unmodified lines56856957057157257311 unmodified lines58558658758858959013 unmodified lines:min-grace-until="minGraceUntil" /><!-- 状态分布卡片(色彩区分明显) --><div class="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-5 gap-3"><div v-for="card in cards" :key="card.label"class="glass-soft rounded-xl p-3.5 lift-hover relative overflow-hidden"><div class="absolute top-0 right-0 w-16 h-16 rounded-full opacity-20 blur-xl pointer-events-none":style="{ background: card.glow }"></div><div class="text-[10px] uppercase tracking-widest text-gray-500 font-semibold flex items-center gap-1.5"><span class="w-1 h-1 rounded-full" :style="{ background: card.dot }"></span>{{ card.label }}</div>2 unmodified lines</div><!-- 账号表格 --><div class="glass rounded-2xl overflow-hidden"><div class="px-5 py-4 border-b border-white/[0.04] flex items-center justify-between gap-3 flex-wrap"><div><h2 class="text-base font-bold text-white tracking-tight">账号列表</h2><p class="text-[11px] text-gray-500 mt-0.5">{{ status.accounts?.length || 0 }} 个账号 · 实时配额来自 quota_cache</p></div><div class="flex items-center gap-2"><AtButton v-if="selectedEmails.length"variant="danger" size="sm" :loading="batchDeleting" :disabled="actionDisabled"confirm @click="batchDelete"><template #icon><svg viewBox="0 0 16 16" class="w-3.5 h-3.5"><path fill="currentColor" d="M5 6v6h1V6H5zm2 0v6h1V6H7zm2 0v6h1V6H9zm2 0v6h1V6h-1zM4 4l1-2h6l1 2h2v1H2V4h2zm1 1v9a2 2 0 002 2h2a2 2 0 002-2V5H5z"/></svg></template>{{ batchDeleting ? `批量删除 ${batchProgress}` : `批量删除 (${selectedEmails.length})` }}</AtButton>2 unmodified lines</AtButton><AtButton variant="secondary" size="sm" :loading="syncing" @click="syncAccounts"><template #icon><svg viewBox="0 0 16 16" class="w-3.5 h-3.5"><path fill="none" stroke="currentColor" stroke-width="1.6" d="M3 8a5 5 0 018.5-3.5L13 3M13 8a5 5 0 01-8.5 3.5L3 13M13 3v3h-3M3 13v-3h3" stroke-linecap="round" stroke-linejoin="round"/></svg></template>{{ syncing ? '同步中…' : '同步账号' }}</AtButton></div></div><div v-if="message" class="mx-5 mt-4 px-4 py-2.5 rounded-xl text-sm border animate-rise" :class="messageClass">{{ message }}</div><div v-if="!adminReady"class="mx-5 mt-4 px-4 py-2.5 rounded-xl text-sm border bg-amber-500/10 text-amber-300 border-amber-500/30">请先在「设置」页完成管理员登录后,才能操作账号。</div><div class="overflow-x-auto"><table class="w-full text-sm"><thead><tr class="text-gray-500 text-left border-b border-white/[0.04] text-[10px] uppercase tracking-widest"><th class="px-3 py-3 font-semibold w-8"><inputtype="checkbox"2 unmodified lines@change="toggleSelectAll":disabled="!selectableEmails.length"class="accent-indigo-500 cursor-pointer w-3.5 h-3.5"title="全选/取消全选(主号除外)" /></th><th class="px-3 py-3 font-semibold">#</th><th class="px-4 py-3 font-semibold">邮箱</th>7 unmodified lines</tr></thead><tbody><tr v-for="(acc, i) in status.accounts" :key="acc.email"class="row-hoverable border-b border-white/[0.03] hover:bg-white/[0.02] group":class="isSelected(acc.email) ? 'bg-indigo-500/[0.05]' : ''"><td class="px-3 py-3.5"><inputv-if="!acc.is_main_account"2 unmodified lines@change="toggleSelect(acc.email)"class="accent-indigo-500 cursor-pointer w-3.5 h-3.5" /></td><td class="px-3 py-3.5 text-gray-600 font-mono text-xs">{{ String(i + 1).padStart(2, '0') }}</td><td class="px-4 py-3.5"><div class="flex items-center gap-2"><span v-if="acc.is_main_account"class="text-[9px] uppercase tracking-widest font-bold px-1.5 py-0.5 roundedbg-gradient-to-br from-indigo-500/30 to-violet-500/30 text-indigo-100 border border-indigo-400/30">Master</span><span class="font-mono text-[12px] text-gray-100">{{ acc.email }}</span></div></td><td class="px-4 py-3.5">8 unmodified lines<td class="px-4 py-3.5 text-right font-mono tabular text-[12px]" :class="pctColor(quota(acc, 'weekly'))">{{ quotaPct(acc, 'weekly') }}</td><td class="px-4 py-3.5 text-gray-500 font-mono text-[11px]">{{ quotaReset(acc, 'primary') }}</td><td class="px-4 py-3.5 text-gray-500 font-mono text-[11px]">{{ quotaReset(acc, 'weekly') }}</td><td class="px-4 py-3.5 text-right"><div class="flex items-center justify-end gap-1.5 flex-wrap"><span v-if="acc.status === 'personal' && !acc.auth_file"class="inline-block px-1.5 py-0.5 rounded text-[9px] uppercase tracking-widebg-amber-500/10 text-amber-300 border border-amber-500/30"title="未拿到 Codex auth_file,请点击补登录">缺认证</span>13 unmodified linestitle="立即调 cheap_codex_smoke + check_codex_quota,绕过 30min 节流">立即探活</AtButton><AtButton v-if="!acc.is_main_account && acc.status === 'active'"variant="secondary" size="sm":loading="actionEmail === acc.email && actionType === 'kick'":disabled="actionDisabled || (actionEmail === acc.email && actionType !== 'kick')"@click="kickAccount(acc.email)">移出</AtButton><AtButton v-if="acc.status === 'active' || acc.status === 'personal' || acc.is_main_account"variant="ghost" size="sm":disabled="actionEmail === acc.email"@click="exportCodexAuth(acc.email)"><template #icon><svg viewBox="0 0 16 16" class="w-3.5 h-3.5"><path fill="currentColor" d="M8 1l3 3h-2v5H7V4H5l3-3zM3 12v-2h1v2h8v-2h1v2a1 1 0 01-1 1H4a1 1 0 01-1-1z"/></svg></template>导出</AtButton><AtButton v-if="!acc.is_main_account"variant="danger" size="sm" confirm:loading="actionEmail === acc.email && actionType === 'delete'"9 unmodified lines</div><!-- 注册失败明细 --><div class="border-t border-white/[0.04] p-5 bg-black/10"><div class="flex items-center justify-between mb-3"><div><h2 class="text-sm font-bold text-white tracking-tight">注册失败明细</h2><div class="text-[11px] text-gray-500 mt-0.5">未能入池的注册尝试 (add-phone / duplicate / OAuth 失败 等)</div></div><AtButton variant="ghost" size="sm" :loading="failuresLoading" @click="loadFailures">刷新1 unmodified line</div><div v-if="failuresCounts && Object.keys(failuresCounts).length" class="flex flex-wrap gap-1.5 mb-3 text-[11px]"><span v-for="(cnt, cat) in failuresCounts" :key="cat"class="px-2 py-0.5 rounded-md border bg-white/[0.02] border-white/[0.06] text-gray-300">{{ cat }}: <span class="text-rose-300 font-mono ml-0.5 tabular">{{ cnt }}</span></span></div><div class="overflow-x-auto rounded-xl border border-white/[0.04]"><table class="w-full text-sm"><thead class="text-[10px] uppercase tracking-widest text-gray-500 border-b border-white/[0.04] bg-white/[0.01]"><tr><th class="text-left px-3 py-2 font-semibold">时间</th><th class="text-left px-3 py-2 font-semibold">邮箱</th>2 unmodified lines<th class="text-left px-3 py-2 font-semibold">附加</th></tr></thead><tbody class="divide-y divide-white/[0.03] text-xs"><tr v-if="!failuresItems.length"><td class="px-3 py-4 text-gray-600 italic" colspan="5">暂无失败记录</td></tr><tr v-for="(f, idx) in failuresItems" :key="idx" class="hover:bg-white/[0.02]"><td class="px-3 py-2 text-gray-500 font-mono">{{ fmtTs(f.timestamp) }}</td><td class="px-3 py-2 text-gray-300 font-mono">{{ f.email || '-' }}</td><td class="px-3 py-2"><span class="px-1.5 py-0.5 rounded-md border text-[10px] font-semibold uppercase tracking-wide":class="failureCategoryClass(f.category)">{{ f.category }}</span></td><td class="px-3 py-2 text-gray-400">{{ f.reason }}</td><td class="px-3 py-2 text-gray-600 font-mono text-[10px]">{{ fmtFailureExtra(f) }}</td></tr></tbody></table>2 unmodified lines<!-- Codex 认证导出弹窗 --><div v-if="exportData"class="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 flex items-center justify-center p-4 animate-rise"@click.self="exportData = null"><div class="glass rounded-2xl w-full max-w-2xl max-h-[80vh] flex flex-col"><div class="px-5 py-4 border-b border-white/[0.04] flex items-center justify-between"><h3 class="text-white font-bold tracking-tight">Codex CLI 认证文件</h3><button @click="exportData = null" class="text-gray-400 hover:text-white text-2xl leading-none transition">×</button></div><div class="p-5 space-y-3 overflow-y-auto flex-1"><div class="px-3 py-2.5 bg-amber-500/10 border border-amber-500/30 rounded-xl text-sm text-amber-200 space-y-2"><div class="font-semibold">使用步骤:</div><ol class="list-decimal list-inside space-y-1 text-xs text-amber-300/90"><li>退出当前 Codex CLI 会话</li><li>删除旧文件:<code class="bg-black/40 px-1 rounded">rm ~/.codex/auth.json</code></li><li>将下方内容保存到 <code class="bg-black/40 px-1 rounded">~/.codex/auth.json</code>(Windows: <code class="bg-black/40 px-1 rounded">%APPDATA%\codex\auth.json</code>)</li><li>重新启动 Codex CLI</li></ol><div class="text-xs text-amber-300/60">导出后 Codex CLI 直连 OpenAI,不走 CPA 代理,响应更快。</div></div><div class="relative"><pre class="bg-black/60 border border-white/[0.06] rounded-xl p-4 text-xs font-mono text-gray-300 overflow-x-auto whitespace-pre">{{ exportJson }}</pre><AtButton :variant="copied ? 'primary' : 'secondary'" size="sm"class="absolute top-2 right-2" @click="copyExport">{{ copied ? '已复制' : '复制' }}</AtButton></div></div><div class="px-5 py-4 border-t border-white/[0.04] flex justify-end gap-2"><AtButton variant="primary" @click="downloadExport"><template #icon><svg viewBox="0 0 16 16" class="w-3.5 h-3.5"><path fill="currentColor" d="M8 11l-4-4h2.5V2h3v5H12L8 11zM3 13h10v1H3z"/></svg></template>下载 auth.json</AtButton>7 unmodified lines<!-- Loading skeleton --><div v-else-if="loading" class="space-y-4"><div class="grid grid-cols-2 sm:grid-cols-4 gap-4"><div v-for="i in 4" :key="i" class="glass-soft rounded-xl p-4 h-20 shimmer-bg"></div></div><div class="glass-soft rounded-2xl h-64 shimmer-bg"></div></div></template><script setup>import { computed, onMounted, ref, watch } from 'vue'import { api } from '../api.js'import StatusBadge from './StatusBadge.vue'import UsabilityCell from './UsabilityCell.vue'import MasterHealthBanner from './MasterHealthBanner.vue'import PoolHealthCard from './PoolHealthCard.vue'import AtButton from './AtButton.vue'import {quotaRemainingPct as _qr,quotaPctText,10 unmodified linesrunningTask: Object,adminStatus: { type: Object, default: null },masterHealth: { type: Object, default: null },})const emit = defineEmits(['refresh', 'reload-master-health'])5 unmodified linesconst copied = ref(false)const messageClass = ref('')const masterHealthBusy = ref(false)// 批量删除选中态:按邮箱(小写)保存,便于跨刷新复用const selectedSet = ref(new Set())const batchDeleting = ref(false)const batchProgress = ref('')// 失败日志面板状态const failuresItems = ref([])const failuresCounts = ref({})const failuresLoading = ref(false)async function loadFailures() {failuresLoading.value = truetry {const r = await api.getRegisterFailures(50)failuresItems.value = r.items || []failuresCounts.value = r.counts || {}} catch (e) {console.error('loadFailures', e)} finally {failuresLoading.value = false}}function fmtTs(ts) {5 unmodified linesfunction failureCategoryClass(cat) {const map = {phone_blocked: 'bg-rose-500/10 text-rose-300 border-rose-500/30',duplicate_exhausted: 'bg-orange-500/10 text-orange-300 border-orange-500/30',register_failed: 'bg-amber-500/10 text-amber-300 border-amber-500/30',oauth_failed: 'bg-purple-500/10 text-purple-300 border-purple-500/30',kick_failed: 'bg-yellow-500/10 text-yellow-300 border-yellow-500/30',exception: 'bg-red-500/10 text-red-300 border-red-500/30',master_subscription_degraded: 'bg-orange-500/10 text-orange-300 border-orange-500/30',}return map[cat] || 'bg-gray-500/10 text-gray-400 border-gray-500/30'}function fmtFailureExtra(f) {5 unmodified linesreturn parts.join(' ') || '-'}onMounted(loadFailures)watch(() => props.runningTask, (cur, prev) => {if (prev && !cur) loadFailures()})const adminReady = computed(() => !!props.adminStatus?.configured)const actionDisabled = computed(() => !!props.runningTask || !adminReady.value)const selectableEmails = computed(() =>(props.status?.accounts || []).filter(a => !a.is_main_account).map(a => a.email))const selectedEmails = computed(() =>selectableEmails.value.filter(e => selectedSet.value.has(e.toLowerCase())))const allSelectableChecked = computed(() =>selectableEmails.value.length > 0 && selectedEmails.value.length === selectableEmails.value.length)20 unmodified lines// Round 9 — 派生 minGraceUntil:从所有 GRACE 子号取最早到期者,banner/PoolHealthCard 共用const minGraceUntil = computed(() => {let min = nullfor (const acc of props.status?.accounts || []) {if (acc.status === 'degraded_grace' && typeof acc.grace_until === 'number') {if (min === null || acc.grace_until < min) min = acc.grace_until}4 unmodified linesconst cards = computed(() => {if (!props.status) return []const s = props.status.summary || {}const dg = s.degraded_grace ?? (props.status.accounts || []).filter(a => a.status === 'degraded_grace').lengthreturn [{ label: 'Active', value: s.active || 0, color: 'text-emerald-300', dot: 'rgb(52, 211, 153)', glow: 'radial-gradient(circle, rgba(52, 211, 153, 0.45), transparent 60%)' },{ label: 'Standby', value: s.standby || 0, color: 'text-amber-300', dot: 'rgb(251, 191, 36)', glow: 'radial-gradient(circle, rgba(251, 191, 36, 0.40), transparent 60%)' },{ label: 'Grace', value: dg, color: 'text-orange-300', dot: 'rgb(251, 146, 60)', glow: 'radial-gradient(circle, rgba(251, 146, 60, 0.40), transparent 60%)' },{ label: 'Personal', value: s.personal || 0, color: 'text-violet-300', dot: 'rgb(167, 139, 250)', glow: 'radial-gradient(circle, rgba(167, 139, 250, 0.40), transparent 60%)' },{ label: 'Total', value: s.total || 0, color: 'text-white', dot: 'rgb(99, 102, 241)', glow: 'radial-gradient(circle, rgba(99, 102, 241, 0.45), transparent 60%)' },]})62 unmodified linesfunction canLogin(acc) {if (acc.is_main_account) return falseif (acc.status === 'active') return falseif (acc.status === 'personal' && acc.auth_file) return falseif (acc.status === 'degraded_grace') return false // grace 期内仍可用,无需补登录3 unmodified lines// (主号有自己的"立即重测"按钮在 MasterHealthBanner;orphan/pending 无 token 探不动)function canProbe(acc) {if (acc.is_main_account) return falseif (!acc.auth_file) return falseif (acc.status === 'pending' || acc.status === 'orphan') return falsereturn true62 unmodified lines}}async function removeAccount(email) {if (actionDisabled.value) return// 二次确认已在 AtButton(confirm) 内做了第一次,这里再用 native confirm 提示破坏性操作细节11 unmodified lines}}async function batchDelete() {if (actionDisabled.value || batchDeleting.value) returnconst emails = selectedEmails.value13 unmodified lines141516171819202122232 unmodified lines2627282930313233343536373839404142434445464748495051525354552 unmodified lines5859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061072 unmodified lines1101111121131141151167 unmodified lines1241251261271281291301311322 unmodified lines1351361371381391401411421431441451461471481498 unmodified lines15815916016116216316416516616716816917013 unmodified lines1841851861871881891901911921931941951961971981992002012022032042052062072082092102112129 unmodified lines2222232242252262272282292302312321 unmodified line2342352362372382392402412422432442452462472482492502 unmodified lines2532542552562572582592602612622632642652662672682692702712 unmodified lines2742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103117 unmodified lines31932032132232332432532632732832933033133233333433533633733833910 unmodified lines3503513523533543553563573585 unmodified lines3643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064075 unmodified lines4134144154164174184194204214224234244254264275 unmodified lines43343443543643743843944044144244344444544644744844945045145245345445545645720 unmodified lines4784794804814824834844 unmodified lines48949049149249349449549649749849950050150262 unmodified lines5655665675685695705713 unmodified lines57557657757857958058162 unmodified lines64464564664764864965065165265365465565665765865966066166266366466566666766866967067167267311 unmodified lines68568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573613 unmodified lines:min-grace-until="minGraceUntil" /><!-- 状态分布卡片(色彩区分明显) --><div class="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-6 gap-3"><div v-for="card in cards" :key="card.label"class="glass-soft rounded-lg p-3.5 lift-hover relative overflow-hidden"><div class="text-[10px] uppercase tracking-widest text-ink-500 font-semibold flex items-center gap-1.5"><span class="w-1 h-1 rounded-full" :style="{ background: card.dot }"></span>{{ card.label }}</div>2 unmodified lines</div><!-- 账号表格 --><div class="glass rounded-lg overflow-hidden"><div class="px-5 py-4 border-b border-hairline flex items-center justify-between gap-3 flex-wrap"><div><h2 class="text-base font-bold text-ink-950 tracking-tight">账号列表</h2><p class="text-[11px] text-ink-500 mt-0.5">{{ totalAccounts }} 个账号 · 每页 {{ ACCOUNT_PAGE_SIZE }} 条 · 实时配额来自 quota_cache</p></div><div class="flex items-center gap-2"><AtButton v-if="selectedDisableEmails.length"variant="secondary" size="sm" :loading="bulkToggling" :disabled="actionDisabled"@click="bulkDisableSelected">禁用自动化 ({{ selectedDisableEmails.length }})</AtButton><AtButton v-if="selectedEnableEmails.length"variant="primary" size="sm" :loading="bulkToggling" :disabled="actionDisabled"@click="bulkEnableSelected">启用自动化 ({{ selectedEnableEmails.length }})</AtButton><AtButton v-if="selectedEmails.length"variant="danger" size="sm" :loading="batchDeleting" :disabled="actionDisabled"confirm @click="batchDelete"><template #icon><Trash2 class="w-3.5 h-3.5" :stroke-width="2" /></template>{{ batchDeleting ? `批量删除 ${batchProgress}` : `批量删除 (${selectedEmails.length})` }}</AtButton>2 unmodified lines</AtButton><AtButton variant="secondary" size="sm" :loading="syncing" @click="syncAccounts"><template #icon><RefreshCw class="w-3.5 h-3.5" :stroke-width="2" /></template>{{ syncing ? '同步中…' : '同步账号' }}</AtButton></div></div><div v-if="message" class="mx-5 mt-4 px-4 py-2.5 rounded-lg text-sm border animate-rise" :class="messageClass">{{ message }}</div><div v-if="!adminReady"class="mx-5 mt-4 px-4 py-2.5 rounded-lg text-sm border bg-amber-50 text-amber-800 border-amber-200">请先在「设置」页完成管理员登录后,才能操作账号。</div><div v-if="hiddenAccountCount"class="mx-5 mt-4 px-4 py-2.5 rounded-lg text-sm border bg-sky-50 text-sky-800 border-sky-200">当前仅渲染第 {{ accountPageStart + 1 }}-{{ accountPageEnd }} 个账号,另有 {{ hiddenAccountCount }} 个账号在其它页,以控制页面资源占用。</div><div v-if="totalAccountPages > 1"class="mx-5 mt-4 px-3 py-2 rounded-lg border border-hairline bg-ink-50 flex items-center justify-between gap-3 flex-wrap"><div class="text-xs text-ink-600">显示 {{ accountPageStart + 1 }}-{{ accountPageEnd }} / {{ totalAccounts }}</div><div class="flex items-center gap-2"><AtButton variant="ghost" size="sm" :disabled="accountPage <= 1" @click="goAccountPage(accountPage - 1)"><template #icon><ChevronLeft class="w-3.5 h-3.5" :stroke-width="2" /></template>上一页</AtButton><span class="text-xs text-ink-600 tabular">第 {{ accountPage }} / {{ totalAccountPages }} 页</span><AtButton variant="ghost" size="sm" :disabled="accountPage >= totalAccountPages" @click="goAccountPage(accountPage + 1)"><template #icon><ChevronRight class="w-3.5 h-3.5" :stroke-width="2" /></template>下一页</AtButton></div></div><div class="overflow-x-auto"><table class="w-full text-sm"><thead><tr class="text-ink-500 text-left border-b border-hairline text-[10px] uppercase tracking-widest"><th class="px-3 py-3 font-semibold w-8"><inputtype="checkbox"2 unmodified lines@change="toggleSelectAll":disabled="!selectableEmails.length"class="accent-indigo-500 cursor-pointer w-3.5 h-3.5"title="全选/取消全选本页账号(主号除外)" /></th><th class="px-3 py-3 font-semibold">#</th><th class="px-4 py-3 font-semibold">邮箱</th>7 unmodified lines</tr></thead><tbody><tr v-for="(acc, i) in visibleAccounts" :key="acc.email"class="row-hoverable border-b border-hairline hover:bg-ink-50 group":class="[isSelected(acc.email) ? 'bg-indigo-50' : '', acc.disabled ? 'opacity-75' : '']"><td class="px-3 py-3.5"><inputv-if="!acc.is_main_account"2 unmodified lines@change="toggleSelect(acc.email)"class="accent-indigo-500 cursor-pointer w-3.5 h-3.5" /></td><td class="px-3 py-3.5 text-ink-400 font-mono text-xs">{{ String(accountPageStart + i + 1).padStart(2, '0') }}</td><td class="px-4 py-3.5"><div class="flex items-center gap-2"><span v-if="acc.is_main_account"class="text-[9px] uppercase tracking-widest font-bold px-1.5 py-0.5 roundedbg-indigo-50 text-indigo-700 border border-indigo-200">Master</span><span class="font-mono text-[12px] text-ink-900">{{ acc.email }}</span></div></td><td class="px-4 py-3.5">8 unmodified lines<td class="px-4 py-3.5 text-right font-mono tabular text-[12px]" :class="pctColor(quota(acc, 'weekly'))">{{ quotaPct(acc, 'weekly') }}</td><td class="px-4 py-3.5 text-ink-500 font-mono text-[11px]">{{ quotaReset(acc, 'primary') }}</td><td class="px-4 py-3.5 text-ink-500 font-mono text-[11px]">{{ quotaReset(acc, 'weekly') }}</td><td class="px-4 py-3.5 text-right"><div class="flex items-center justify-end gap-1.5 flex-wrap"><span v-if="acc.status === 'personal' && !acc.auth_file"class="inline-block px-1.5 py-0.5 rounded text-[9px] uppercase tracking-widebg-amber-50 text-amber-800 border border-amber-200"title="未拿到 Codex auth_file,请点击补登录">缺认证</span>13 unmodified linestitle="立即调 cheap_codex_smoke + check_codex_quota,绕过 30min 节流">立即探活</AtButton><AtButton v-if="!acc.is_main_account && !acc.disabled && acc.raw_status === 'active'"variant="secondary" size="sm":loading="actionEmail === acc.email && actionType === 'kick'":disabled="actionDisabled || (actionEmail === acc.email && actionType !== 'kick')"@click="kickAccount(acc.email)">移出</AtButton><AtButton v-if="acc.raw_status === 'active' || acc.raw_status === 'personal' || acc.is_main_account"variant="ghost" size="sm":disabled="actionEmail === acc.email"@click="exportCodexAuth(acc.email)"><template #icon><Download class="w-3.5 h-3.5" :stroke-width="2" /></template>导出</AtButton><AtButton v-if="!acc.is_main_account":variant="acc.disabled ? 'primary' : 'secondary'" size="sm":loading="actionEmail === acc.email && actionType === (acc.disabled ? 'enable' : 'disable')":disabled="actionDisabled || (actionEmail === acc.email && !['enable', 'disable'].includes(actionType))"@click="toggleAccountDisabled(acc)">{{ acc.disabled ? '启用' : '禁用' }}</AtButton><AtButton v-if="!acc.is_main_account"variant="danger" size="sm" confirm:loading="actionEmail === acc.email && actionType === 'delete'"9 unmodified lines</div><!-- 注册失败明细 --><div class="border-t border-hairline p-5 bg-ink-50"><div class="flex items-center justify-between mb-3"><div><h2 class="text-sm font-bold text-ink-950 tracking-tight">注册失败明细</h2><div class="text-[11px] text-ink-500 mt-0.5">未能入池的注册尝试 (add-phone / duplicate / OAuth 失败 等)</div></div><AtButton variant="ghost" size="sm" :loading="failuresLoading" @click="loadFailures">刷新1 unmodified line</div><div v-if="failuresCounts && Object.keys(failuresCounts).length" class="flex flex-wrap gap-1.5 mb-3 text-[11px]"><span v-for="(cnt, cat) in failuresCounts" :key="cat"class="px-2 py-0.5 rounded-md border bg-surface border-hairline text-ink-700">{{ cat }}: <span class="text-rose-700 font-mono ml-0.5 tabular">{{ cnt }}</span></span></div><div class="overflow-x-auto rounded-lg border border-hairline bg-surface"><div v-if="failuresUnavailable"class="px-3 py-3 text-xs text-amber-800 bg-amber-50 border-b border-amber-200">{{ failuresUnavailable }}</div><table class="w-full text-sm"><thead class="text-[10px] uppercase tracking-widest text-ink-500 border-b border-hairline bg-ink-50"><tr><th class="text-left px-3 py-2 font-semibold">时间</th><th class="text-left px-3 py-2 font-semibold">邮箱</th>2 unmodified lines<th class="text-left px-3 py-2 font-semibold">附加</th></tr></thead><tbody class="divide-y divide-hairline text-xs"><tr v-if="!failuresItems.length"><td class="px-3 py-4 text-ink-400 italic" colspan="5">暂无失败记录</td></tr><tr v-for="(f, idx) in failuresItems" :key="idx" class="hover:bg-ink-50"><td class="px-3 py-2 text-ink-500 font-mono">{{ fmtTs(f.timestamp) }}</td><td class="px-3 py-2 text-ink-700 font-mono">{{ f.email || '-' }}</td><td class="px-3 py-2"><span class="px-1.5 py-0.5 rounded-md border text-[10px] font-semibold uppercase tracking-wide":class="failureCategoryClass(f.category)">{{ f.category }}</span></td><td class="px-3 py-2 text-ink-600">{{ f.reason }}</td><td class="px-3 py-2 text-ink-400 font-mono text-[10px]">{{ fmtFailureExtra(f) }}</td></tr></tbody></table>2 unmodified lines<!-- Codex 认证导出弹窗 --><div v-if="exportData"class="fixed inset-0 bg-ink-600/20 z-50 flex items-center justify-center p-4 animate-rise"@click.self="exportData = null"><div class="glass rounded-lg w-full max-w-2xl max-h-[80vh] flex flex-col"><div class="px-5 py-4 border-b border-hairline flex items-center justify-between"><h3 class="text-ink-950 font-bold tracking-tight">Codex CLI 认证文件</h3><button @click="exportData = null" class="text-ink-500 hover:text-ink-950 transition focus-ring rounded-lg p-1"><X class="w-4 h-4" :stroke-width="2" /></button></div><div class="p-5 space-y-3 overflow-y-auto flex-1"><div class="px-3 py-2.5 bg-amber-50 border border-amber-200 rounded-lg text-sm text-amber-800 space-y-2"><div class="font-semibold">使用步骤:</div><ol class="list-decimal list-inside space-y-1 text-xs text-amber-700"><li>退出当前 Codex CLI 会话</li><li>删除旧文件:<code class="bg-amber-50 border border-amber-200 px-1 rounded">rm ~/.codex/auth.json</code></li><li>将下方内容保存到 <code class="bg-amber-50 border border-amber-200 px-1 rounded">~/.codex/auth.json</code>(Windows: <code class="bg-amber-50 border border-amber-200 px-1 rounded">%APPDATA%\codex\auth.json</code>)</li><li>重新启动 Codex CLI</li></ol><div class="text-xs text-amber-700">导出后 Codex CLI 直连 OpenAI,不走 CPA 代理,响应更快。</div></div><div class="relative"><pre class="bg-ink-50 border border-hairline rounded-lg p-4 text-xs font-mono text-ink-800 overflow-x-auto whitespace-pre">{{ exportJson }}</pre><AtButton :variant="copied ? 'primary' : 'secondary'" size="sm"class="absolute top-2 right-2" @click="copyExport">{{ copied ? '已复制' : '复制' }}</AtButton></div></div><div class="px-5 py-4 border-t border-hairline flex justify-end gap-2"><AtButton variant="primary" @click="downloadExport"><template #icon><Download class="w-3.5 h-3.5" :stroke-width="2" /></template>下载 auth.json</AtButton>7 unmodified lines<!-- Loading skeleton --><div v-else-if="loading" class="space-y-4"><div class="grid grid-cols-2 sm:grid-cols-4 gap-4"><div v-for="i in 4" :key="i" class="glass-soft rounded-lg p-4 h-20 shimmer-bg"></div></div><div class="glass-soft rounded-lg h-64 shimmer-bg"></div></div></template><script setup>import { computed, ref, watch } from 'vue'import { api } from '../api.js'import StatusBadge from './StatusBadge.vue'import UsabilityCell from './UsabilityCell.vue'import MasterHealthBanner from './MasterHealthBanner.vue'import PoolHealthCard from './PoolHealthCard.vue'import AtButton from './AtButton.vue'import { ChevronLeft, ChevronRight, Download, RefreshCw, Trash2, X } from 'lucide-vue-next'import {quotaRemainingPct as _qr,quotaPctText,10 unmodified linesrunningTask: Object,adminStatus: { type: Object, default: null },masterHealth: { type: Object, default: null },registerFailures: { type: Object, default: null },registerFailuresLoading: { type: Boolean, default: false },registerFailuresUnavailable: { type: String, default: '' },})const emit = defineEmits(['refresh', 'reload-master-health'])5 unmodified linesconst copied = ref(false)const messageClass = ref('')const masterHealthBusy = ref(false)const accountPage = ref(1)const ACCOUNT_PAGE_SIZE = 50// 批量删除选中态:按邮箱(小写)保存,便于跨刷新复用const selectedSet = ref(new Set())const batchDeleting = ref(false)const batchProgress = ref('')const bulkToggling = ref(false)const failuresItems = computed(() => props.registerFailures?.items || [])const failuresCounts = computed(() => props.registerFailures?.counts || {})const failuresLoading = computed(() => !!props.registerFailuresLoading)const failuresUnavailable = computed(() => props.registerFailuresUnavailable || '')const accounts = computed(() => props.status?.accounts || [])const totalAccounts = computed(() => accounts.value.length)const totalAccountPages = computed(() => Math.max(1, Math.ceil(totalAccounts.value / ACCOUNT_PAGE_SIZE)))const accountPageStart = computed(() => (accountPage.value - 1) * ACCOUNT_PAGE_SIZE)const accountPageEnd = computed(() => Math.min(accountPageStart.value + ACCOUNT_PAGE_SIZE, totalAccounts.value))const visibleAccounts = computed(() => accounts.value.slice(accountPageStart.value, accountPageEnd.value))const hiddenAccountCount = computed(() => Math.max(0, accounts.value.length - visibleAccounts.value.length))function goAccountPage(page) {const nextPage = Math.min(Math.max(1, page), totalAccountPages.value)if (nextPage === accountPage.value) returnaccountPage.value = nextPageclearSelection()}watch(totalAccountPages, pages => {if (accountPage.value > pages) {accountPage.value = pagesclearSelection()}})function loadFailures() {emit('refresh')}function fmtTs(ts) {5 unmodified linesfunction failureCategoryClass(cat) {const map = {phone_blocked: 'bg-rose-50 text-rose-700 border-rose-200',duplicate_exhausted: 'bg-orange-50 text-orange-700 border-orange-200',register_failed: 'bg-amber-50 text-amber-700 border-amber-200',oauth_failed: 'bg-sky-50 text-sky-700 border-sky-200',kick_failed: 'bg-yellow-50 text-yellow-700 border-yellow-200',exception: 'bg-red-50 text-red-700 border-red-200',master_subscription_degraded: 'bg-orange-50 text-orange-700 border-orange-200',}return map[cat] || 'bg-ink-50 text-ink-600 border-hairline'}function fmtFailureExtra(f) {5 unmodified linesreturn parts.join(' ') || '-'}const adminReady = computed(() => !!props.adminStatus?.configured)const actionDisabled = computed(() => !!props.runningTask || !adminReady.value || bulkToggling.value)const selectableEmails = computed(() =>visibleAccounts.value.filter(a => !a.is_main_account).map(a => a.email))const selectedEmails = computed(() =>selectableEmails.value.filter(e => selectedSet.value.has(e.toLowerCase())))const selectedDisableEmails = computed(() =>visibleAccounts.value.filter(a => !a.is_main_account && !a.disabled && selectedSet.value.has((a.email || '').toLowerCase())).map(a => a.email))const selectedEnableEmails = computed(() =>visibleAccounts.value.filter(a => !a.is_main_account && a.disabled && selectedSet.value.has((a.email || '').toLowerCase())).map(a => a.email))const allSelectableChecked = computed(() =>selectableEmails.value.length > 0 && selectedEmails.value.length === selectableEmails.value.length)20 unmodified lines// Round 9 — 派生 minGraceUntil:从所有 GRACE 子号取最早到期者,banner/PoolHealthCard 共用const minGraceUntil = computed(() => {let min = nullfor (const acc of accounts.value) {if (acc.status === 'degraded_grace' && typeof acc.grace_until === 'number') {if (min === null || acc.grace_until < min) min = acc.grace_until}4 unmodified linesconst cards = computed(() => {if (!props.status) return []const s = props.status.summary || {}const dg = s.degraded_grace ?? accounts.value.filter(a => a.status === 'degraded_grace').lengthreturn [{ label: 'Active', value: s.active || 0, color: 'text-emerald-700', dot: 'rgb(16, 185, 129)' },{ label: 'Standby', value: s.standby || 0, color: 'text-amber-700', dot: 'rgb(217, 119, 6)' },{ label: 'Grace', value: dg, color: 'text-orange-700', dot: 'rgb(234, 88, 12)' },{ label: 'Personal', value: s.personal || 0, color: 'text-sky-700', dot: 'rgb(2, 132, 199)' },{ label: 'Disabled', value: s.disabled || 0, color: 'text-stone-700', dot: 'rgb(120, 113, 108)' },{ label: 'Total', value: s.total || 0, color: 'text-ink-950', dot: 'rgb(79, 70, 229)' },]})62 unmodified linesfunction canLogin(acc) {if (acc.is_main_account) return falseif (acc.disabled) return falseif (acc.status === 'active') return falseif (acc.status === 'personal' && acc.auth_file) return falseif (acc.status === 'degraded_grace') return false // grace 期内仍可用,无需补登录3 unmodified lines// (主号有自己的"立即重测"按钮在 MasterHealthBanner;orphan/pending 无 token 探不动)function canProbe(acc) {if (acc.is_main_account) return falseif (acc.disabled) return falseif (!acc.auth_file) return falseif (acc.status === 'pending' || acc.status === 'orphan') return falsereturn true62 unmodified lines}}async function toggleAccountDisabled(acc) {if (actionDisabled.value) returnconst disabling = !acc.disabledconst ok = window.confirm(disabling? `确认禁用账号 ${acc.email}?\n禁用后会保留本地记录,但自动巡检、轮转和 CPA 同步会跳过该账号。`: `确认启用账号 ${acc.email}?\n启用后该账号会重新参与自动巡检、轮转和 CPA 同步。`)if (!ok) returnactionEmail.value = acc.emailactionType.value = disabling ? 'disable' : 'enable'try {const result = disabling? await api.disableAccount(acc.email): await api.enableAccount(acc.email)toast.success(disabling ? '账号已禁用' : '账号已启用', result.message || acc.email)emit('refresh')} catch (e) {toast.error(disabling ? '禁用失败' : '启用失败', e.message)} finally {actionEmail.value = ''; actionType.value = ''}}async function removeAccount(email) {if (actionDisabled.value) return// 二次确认已在 AtButton(confirm) 内做了第一次,这里再用 native confirm 提示破坏性操作细节11 unmodified lines}}async function bulkDisableSelected() {if (actionDisabled.value || bulkToggling.value) returnconst emails = selectedDisableEmails.valueif (!emails.length) returnconst preview = emails.slice(0, 8).join('\n')const more = emails.length > 8 ? `\n…还有 ${emails.length - 8} 个` : ''const ok = window.confirm(`确认批量禁用以下 ${emails.length} 个账号?\n禁用后会保留本地记录,但自动巡检、轮转和 CPA 同步会跳过它们。\n\n${preview}${more}`)if (!ok) returnbulkToggling.value = truetry {const result = await api.bulkDisableAccounts(emails)toast.success('批量禁用完成', result.message || `已禁用 ${emails.length} 个账号`)clearSelection()emit('refresh')} catch (e) {toast.error('批量禁用失败', e.message)} finally {bulkToggling.value = false}}async function bulkEnableSelected() {if (actionDisabled.value || bulkToggling.value) returnconst emails = selectedEnableEmails.valueif (!emails.length) returnconst preview = emails.slice(0, 8).join('\n')const more = emails.length > 8 ? `\n…还有 ${emails.length - 8} 个` : ''const ok = window.confirm(`确认批量启用以下 ${emails.length} 个账号?\n启用后它们会重新参与自动巡检、轮转和 CPA 同步。\n\n${preview}${more}`)if (!ok) returnbulkToggling.value = truetry {const result = await api.bulkEnableAccounts(emails)toast.success('批量启用完成', result.message || `已启用 ${emails.length} 个账号`)clearSelection()emit('refresh')} catch (e) {toast.error('批量启用失败', e.message)} finally {bulkToggling.value = false}}async function batchDelete() {if (actionDisabled.value || batchDeleting.value) returnconst emails = selectedEmails.value
18 unmodified lines19202122232425262718 unmodified linesclass="transition-all duration-500" /></svg><div class="absolute inset-0 flex flex-col items-center justify-center pointer-events-none"><div class="text-[10px] uppercase tracking-widest text-gray-500 leading-none">{{ centerLabel }}</div><div class="text-2xl font-bold text-white tabular leading-none mt-1">{{ centerValue }}</div><div v-if="centerHint" class="text-[10px] text-gray-500 mt-0.5">{{ centerHint }}</div></div></div></template>18 unmodified lines19202122232425262718 unmodified linesclass="transition-all duration-500" /></svg><div class="absolute inset-0 flex flex-col items-center justify-center pointer-events-none"><div class="text-[10px] uppercase tracking-widest text-ink-500 leading-none">{{ centerLabel }}</div><div class="text-2xl font-bold text-ink-950 tabular leading-none mt-1">{{ centerValue }}</div><div v-if="centerHint" class="text-[10px] text-ink-500 mt-0.5">{{ centerHint }}</div></div></div></template>
1234567891011121314151617181920212223242526272829303132333435363738394041424344451 unmodified line4748495051529 unmodified lines62636465666768697019 unmodified lines90919293949596979899<template><div><div class="flex items-center justify-between mb-6"><h2 class="text-xl font-bold text-white">日志</h2><div class="flex items-center gap-3"><label class="flex items-center gap-2 text-sm text-gray-400"><input type="checkbox" v-model="autoScroll" class="rounded bg-gray-800 border-gray-700" />自动滚动</label><button @click="fetchLogs" :disabled="loading"class="px-3 py-1.5 bg-gray-800 hover:bg-gray-700 text-sm rounded-lg border border-gray-700 transition disabled:opacity-50">刷新</button><button @click="clearLogs"class="px-3 py-1.5 bg-gray-800 hover:bg-gray-700 text-sm rounded-lg border border-gray-700 transition text-gray-400 hover:text-white">清空</button></div></div><div ref="logContainer"class="bg-gray-950 border border-gray-800 rounded-xl p-3 md:p-4 font-mono text-xs leading-relaxed h-[calc(100vh-200px)] md:h-[600px] overflow-y-auto"><div v-if="logs.length === 0" class="text-gray-600 text-center py-8">暂无日志</div><div v-for="(log, i) in logs" :key="i"class="py-0.5 flex gap-3 hover:bg-gray-900/50"><span class="text-gray-600 shrink-0">{{ formatTime(log.time) }}</span><span class="shrink-0 w-16":class="{'text-red-400': log.level === 'ERROR','text-yellow-400': log.level === 'WARNING','text-blue-400': log.level === 'INFO','text-gray-500': log.level === 'DEBUG',}">{{ log.level }}</span><span class="text-gray-300 break-all">{{ log.message }}</span></div></div></div></template><script setup>import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'import { api } from '../api.js'const logs = ref([])const loading = ref(false)1 unmodified lineconst logContainer = ref(null)let pollTimer = nulllet lastTime = 0function formatTime(ts) {const d = new Date(ts * 1000)9 unmodified lineslogs.value = result.logs} else {logs.value.push(...result.logs)// 保留最新 1000 条if (logs.value.length > 1000) {logs.value = logs.value.slice(-1000)}}lastTime = result.logs[result.logs.length - 1].time19 unmodified linesonMounted(() => {fetchLogs()pollTimer = setInterval(fetchLogs, 3000)})onUnmounted(() => {if (pollTimer) clearInterval(pollTimer)})</script>1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950511 unmodified line535455565758599 unmodified lines69707172737475767719 unmodified lines979899100101102103104105106107108109110111112113114<template><div><div class="flex items-center justify-between mb-6"><h2 class="text-xl font-bold text-ink-950">日志</h2><div class="flex items-center gap-3"><span class="text-[11px] text-ink-500 hidden sm:inline">保留最新 1000 条,页面隐藏时暂停轮询</span><label class="flex items-center gap-2 text-sm text-ink-600"><input type="checkbox" v-model="autoScroll" class="rounded border-hairline accent-indigo-600" />自动滚动</label><AtButton variant="secondary" size="sm" :loading="loading" @click="fetchLogs"><template #icon><RefreshCw class="w-3.5 h-3.5" :stroke-width="2" /></template>刷新</AtButton><button @click="clearLogs"class="inline-flex items-center gap-1.5 px-3 py-1.5 bg-surface hover:bg-ink-100 text-sm rounded-lg border border-hairline transition text-ink-600 hover:text-ink-950 focus-ring"><Trash2 class="w-3.5 h-3.5" :stroke-width="2" />清空</button></div></div><div ref="logContainer"class="bg-surface border border-hairline rounded-lg p-3 md:p-4 font-mono text-xs leading-relaxed h-[calc(100vh-200px)] md:h-[600px] overflow-y-auto"><div v-if="logs.length === 0" class="text-ink-400 text-center py-8">暂无日志</div><div v-for="(log, i) in logs" :key="i"class="py-0.5 flex gap-3 hover:bg-ink-50"><span class="text-ink-500 shrink-0">{{ formatTime(log.time) }}</span><span class="shrink-0 w-16":class="{'text-rose-700': log.level === 'ERROR','text-amber-700': log.level === 'WARNING','text-sky-700': log.level === 'INFO','text-ink-500': log.level === 'DEBUG',}">{{ log.level }}</span><span class="text-ink-700 break-all">{{ log.message }}</span></div></div></div></template><script setup>import { ref, onMounted, onUnmounted, nextTick } from 'vue'import { api } from '../api.js'import AtButton from './AtButton.vue'import { RefreshCw, Trash2 } from 'lucide-vue-next'const logs = ref([])const loading = ref(false)1 unmodified lineconst logContainer = ref(null)let pollTimer = nulllet lastTime = 0const LOG_RENDER_LIMIT = 1000function formatTime(ts) {const d = new Date(ts * 1000)9 unmodified lineslogs.value = result.logs} else {logs.value.push(...result.logs)// 保留最新 N 条if (logs.value.length > LOG_RENDER_LIMIT) {logs.value = logs.value.slice(-LOG_RENDER_LIMIT)}}lastTime = result.logs[result.logs.length - 1].time19 unmodified linesonMounted(() => {fetchLogs()pollTimer = setInterval(() => {if (!document.hidden) fetchLogs()}, 3000)document.addEventListener('visibilitychange', handleVisibility)})onUnmounted(() => {if (pollTimer) clearInterval(pollTimer)document.removeEventListener('visibilitychange', handleVisibility)})function handleVisibility() {if (!document.hidden) fetchLogs()}</script>
12 unmodified lines131415161718192021222 unmodified lines25262728293031324 unmodified lines373839404142431 unmodified line454647484950515253545556575859606162636465662 unmodified lines69707172737475767778798081821 unmodified line848586878889909192939413 unmodified lines10810911011111211311439 unmodified lines1541551561571581591601612 unmodified lines1641651661671681691701 unmodified line17217317417517617717817918012 unmodified lines<template><div class="mail-provider-card"><!-- 步骤 1:Provider 选择 --><div class="mb-3 p-3 bg-gray-800/40 border border-gray-800 rounded"><div class="flex items-center justify-between mb-2"><span class="text-sm text-white">{{ mode === 'setup' ? '1. 邮箱后端' : '1. 后端类型' }}</span><span class="text-xs" :class="state === 'PROVIDER' ? 'text-yellow-400' : 'text-green-400'">{{ state === 'PROVIDER' ? '请选择' : '已选 ' + form.MAIL_PROVIDER }}</span></div>2 unmodified linesv-for="opt in providerOptions" :key="opt.value"@click="selectProvider(opt.value)":class="form.MAIL_PROVIDER === opt.value? 'bg-blue-600 border-blue-500 text-white': 'bg-gray-800 border-gray-700 text-gray-300'"class="flex-1 px-3 py-2 border rounded text-sm transition"><div class="font-medium">{{ opt.label }}</div><div class="text-xs opacity-75 mt-0.5">{{ opt.desc }}</div>4 unmodified lines<!-- 步骤 2:服务器连接 --><div class="mb-3 p-3 rounded border" :class="cardClass('CONNECTION')"><div class="flex items-center justify-between mb-2"><span class="text-sm text-white">2. 服务器连接</span><span class="text-xs" :class="connectionStatusClass">{{ connectionStatus }}</span></div><div class="space-y-2" :class="state === 'PROVIDER' ? 'opacity-40 pointer-events-none' : ''">1 unmodified linev-model="form[baseUrlKey]"type="text":placeholder="form.MAIL_PROVIDER === 'maillab' ? 'https://your-maillab.example.com' : 'https://example.com/api'"class="w-full px-2 py-1.5 bg-gray-800 border border-gray-700 rounded text-sm text-white" /><inputv-if="form.MAIL_PROVIDER === 'maillab'"v-model="form.MAILLAB_USERNAME"type="text"placeholder="管理员邮箱 (MAILLAB_USERNAME)"class="w-full px-2 py-1.5 bg-gray-800 border border-gray-700 rounded text-sm text-white" /><inputv-model="form[passwordKey]"type="password":placeholder="passwordPlaceholder"class="w-full px-2 py-1.5 bg-gray-800 border border-gray-700 rounded text-sm text-white" /><button@click="testConnection":disabled="testing || !canTestConnection"class="px-3 py-1.5 bg-blue-600 hover:bg-blue-500 disabled:opacity-50 text-white text-xs rounded">{{ testing ? '测试中...' : '测试连接' }}</button></div>2 unmodified lines<!-- 步骤 3:域名归属 --><div class="mb-3 p-3 rounded border" :class="cardClass('DOMAIN')"><div class="flex items-center justify-between mb-2"><span class="text-sm text-white">3. 域名归属</span><span class="text-xs" :class="domainStatusClass">{{ domainStatus }}</span></div><div class="space-y-2" :class="!canEnterDomain ? 'opacity-40 pointer-events-none' : ''"><selectv-if="domainList && domainList.length"v-model="selectedDomain"class="w-full px-2 py-1.5 bg-gray-800 border border-gray-700 rounded text-sm text-white"><option v-for="d in domainList" :key="d" :value="stripAt(d)">{{ d }}</option></select><input1 unmodified linev-model="selectedDomain"type="text"placeholder="example.com"class="w-full px-2 py-1.5 bg-gray-800 border border-gray-700 rounded text-sm text-white" /><button@click="verifyDomain":disabled="verifying || !selectedDomain"class="px-3 py-1.5 bg-blue-600 hover:bg-blue-500 disabled:opacity-50 text-white text-xs rounded">{{ verifying ? '验证中...' : '验证归属' }}</button></div>13 unmodified linesconst emit = defineEmits(['update:modelValue', 'state-change', 'verified', 'error'])// form 通过 v-model 双向绑定;直接 mutate 内部对象再 emit 完整对象保持 reactivity。const form = computed({get: () => props.modelValue,set: (v) => emit('update:modelValue', v),})39 unmodified linesreturn detectedProvider.value ? `已通过 (${detectedProvider.value})` : '已通过'})const connectionStatusClass = computed(() => {if (state.value === 'PROVIDER' || state.value === 'CONNECTION') return 'text-yellow-400'return 'text-green-400'})const domainStatus = computed(() => {2 unmodified linesif (state.value === 'DOMAIN') return '请验证域名归属'return '已通过'})const domainStatusClass = computed(() => state.value === 'SAVE' ? 'text-green-400' : 'text-yellow-400')watch(state, (s) => emit('state-change', s))1 unmodified lineconst order = ['PROVIDER', 'CONNECTION', 'DOMAIN', 'SAVE']const cur = order.indexOf(state.value)const tgt = order.indexOf(targetState)if (tgt > cur) return 'bg-gray-800/20 border-gray-800'if (tgt < cur) return 'bg-green-900/10 border-green-900/40'return 'bg-blue-900/10 border-blue-700/40'}function stripAt(d) {12 unmodified lines131415161718192021222 unmodified lines25262728293031324 unmodified lines373839404142431 unmodified line454647484950515253545556575859606162636465662 unmodified lines69707172737475767778798081821 unmodified line848586878889909192939413 unmodified lines10810911011111211311439 unmodified lines1541551561571581591601612 unmodified lines1641651661671681691701 unmodified line17217317417517617717817918012 unmodified lines<template><div class="mail-provider-card"><!-- 步骤 1:Provider 选择 --><div class="mb-3 p-3 bg-ink-50 border border-hairline rounded"><div class="flex items-center justify-between mb-2"><span class="text-sm text-ink-950">{{ mode === 'setup' ? '1. 邮箱后端' : '1. 后端类型' }}</span><span class="text-xs" :class="state === 'PROVIDER' ? 'text-amber-700' : 'text-emerald-700'">{{ state === 'PROVIDER' ? '请选择' : '已选 ' + form.MAIL_PROVIDER }}</span></div>2 unmodified linesv-for="opt in providerOptions" :key="opt.value"@click="selectProvider(opt.value)":class="form.MAIL_PROVIDER === opt.value? 'bg-indigo-600 border-indigo-500 text-on-accent': 'bg-surface border-hairline text-ink-700 hover:bg-ink-100'"class="flex-1 px-3 py-2 border rounded text-sm transition"><div class="font-medium">{{ opt.label }}</div><div class="text-xs opacity-75 mt-0.5">{{ opt.desc }}</div>4 unmodified lines<!-- 步骤 2:服务器连接 --><div class="mb-3 p-3 rounded border" :class="cardClass('CONNECTION')"><div class="flex items-center justify-between mb-2"><span class="text-sm text-ink-950">2. 服务器连接</span><span class="text-xs" :class="connectionStatusClass">{{ connectionStatus }}</span></div><div class="space-y-2" :class="state === 'PROVIDER' ? 'opacity-40 pointer-events-none' : ''">1 unmodified linev-model="form[baseUrlKey]"type="text":placeholder="form.MAIL_PROVIDER === 'maillab' ? 'https://your-maillab.example.com' : 'https://example.com/api'"class="w-full px-2 py-1.5 bg-surface border border-hairline rounded text-sm text-ink-950 focus-ring" /><inputv-if="form.MAIL_PROVIDER === 'maillab'"v-model="form.MAILLAB_USERNAME"type="text"placeholder="管理员邮箱 (MAILLAB_USERNAME)"class="w-full px-2 py-1.5 bg-surface border border-hairline rounded text-sm text-ink-950 focus-ring" /><inputv-model="form[passwordKey]"type="password":placeholder="passwordPlaceholder"class="w-full px-2 py-1.5 bg-surface border border-hairline rounded text-sm text-ink-950 focus-ring" /><button@click="testConnection":disabled="testing || !canTestConnection"class="px-3 py-1.5 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-on-accent text-xs rounded focus-ring">{{ testing ? '测试中...' : '测试连接' }}</button></div>2 unmodified lines<!-- 步骤 3:域名归属 --><div class="mb-3 p-3 rounded border" :class="cardClass('DOMAIN')"><div class="flex items-center justify-between mb-2"><span class="text-sm text-ink-950">3. 域名归属</span><span class="text-xs" :class="domainStatusClass">{{ domainStatus }}</span></div><div class="space-y-2" :class="!canEnterDomain ? 'opacity-40 pointer-events-none' : ''"><selectv-if="domainList && domainList.length"v-model="selectedDomain"class="w-full px-2 py-1.5 bg-surface border border-hairline rounded text-sm text-ink-950 focus-ring"><option v-for="d in domainList" :key="d" :value="stripAt(d)">{{ d }}</option></select><input1 unmodified linev-model="selectedDomain"type="text"placeholder="example.com"class="w-full px-2 py-1.5 bg-surface border border-hairline rounded text-sm text-ink-950 focus-ring" /><button@click="verifyDomain":disabled="verifying || !selectedDomain"class="px-3 py-1.5 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-on-accent text-xs rounded focus-ring">{{ verifying ? '验证中...' : '验证归属' }}</button></div>13 unmodified linesconst emit = defineEmits(['update:modelValue', 'state-change', 'verified', 'error'])// form 通过 v-model 双向绑定;直接 mutate 内部对象再 emit 完整对象保持 reactivity。let form = computed({get: () => props.modelValue,set: (v) => emit('update:modelValue', v),})39 unmodified linesreturn detectedProvider.value ? `已通过 (${detectedProvider.value})` : '已通过'})const connectionStatusClass = computed(() => {if (state.value === 'PROVIDER' || state.value === 'CONNECTION') return 'text-amber-700'return 'text-emerald-700'})const domainStatus = computed(() => {2 unmodified linesif (state.value === 'DOMAIN') return '请验证域名归属'return '已通过'})const domainStatusClass = computed(() => state.value === 'SAVE' ? 'text-emerald-700' : 'text-amber-700')watch(state, (s) => emit('state-change', s))1 unmodified lineconst order = ['PROVIDER', 'CONNECTION', 'DOMAIN', 'SAVE']const cur = order.indexOf(state.value)const tgt = order.indexOf(targetState)if (tgt > cur) return 'bg-ink-50 border-hairline'if (tgt < cur) return 'bg-emerald-50 border-emerald-200'return 'bg-indigo-50 border-indigo-200'}function stripAt(d) {
9 unmodified lines1011121314151617181920211 unmodified line232425262728293031323334353637383940414243444 unmodified lines4950515253545527 unmodified lines83848586878897 unmodified lines1861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382399 unmodified linesrefresh: 立即重测按钮触发--><template><div v-if="visible" class="relative overflow-hidden rounded-2xl border lift-hover":class="[tone.border, 'shadow-2xl']" :style="containerStyle" role="alert"><!-- 背景装饰 --><div class="absolute inset-0 pointer-events-none opacity-60" :style="meshStyle"></div><!-- 角标 --><div class="absolute top-0 right-0 px-3 py-1 text-[10px] font-mono uppercase tracking-widest rounded-bl-xl":class="[tone.tagBg, tone.tagText]">{{ tone.tag }}</div>1 unmodified line<div class="relative px-5 py-4"><div class="flex items-start gap-4"><!-- 图标 --><div class="relative shrink-0 w-11 h-11 rounded-xl flex items-center justify-center":class="tone.iconWrap"><svg v-if="severity === 'critical'" viewBox="0 0 24 24" class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 9v4M12 17h.01M5.07 19h13.86c1.54 0 2.5-1.67 1.73-3L13.73 4a2 2 0 00-3.46 0L3.34 16c-.77 1.33.19 3 1.73 3z" stroke-linejoin="round" stroke-linecap="round"/></svg><svg v-else-if="severity === 'warning'" viewBox="0 0 24 24" class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"/><path d="M12 7v6M12 16h.01" stroke-linecap="round"/></svg><svg v-else-if="severity === 'info'" viewBox="0 0 24 24" class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"/><path d="M11 11h1v5h1M12 7.5h.01" stroke-linecap="round"/></svg><svg v-else viewBox="0 0 24 24" class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 13l4 4L19 7" stroke-linecap="round" stroke-linejoin="round"/></svg><span v-if="severity === 'critical'" class="absolute -top-0.5 -right-0.5 w-2.5 h-2.5 rounded-full bg-rose-400"><span class="absolute inset-0 rounded-full bg-rose-400 animate-ping opacity-75"></span>4 unmodified lines<div class="flex-1 min-w-0"><div class="flex items-center gap-3 flex-wrap"><h3 class="text-base font-bold" :class="tone.title">{{ title }}</h3><span v-if="graceCountdown" class="font-mono text-xs px-2 py-0.5 rounded-md bg-black/30 border border-white/10":class="graceCountdownColor">grace · {{ graceCountdown }}</span>27 unmodified lines<script setup>import { computed } from 'vue'import { formatGraceRemain, graceUrgencyClass, masterHealthSeverity } from '../composables/useStatus.js'const props = defineProps({masterHealth: { type: Object, default: null },97 unmodified linesif (severity.value === 'warning') {return {tag: 'GRACE',tagBg: 'bg-amber-500/30',tagText: 'text-amber-100',iconWrap: 'bg-amber-500/15 text-amber-300 border border-amber-400/30',title: 'text-amber-100',body: 'text-amber-100/80',border: 'border-amber-500/40',btn: 'bg-amber-500/15 hover:bg-amber-500/25 text-amber-100 border-amber-400/40',}}if (severity.value === 'info') {return {tag: 'STALE',tagBg: 'bg-slate-500/30',tagText: 'text-slate-100',iconWrap: 'bg-slate-500/15 text-slate-300 border border-slate-400/30',title: 'text-slate-100',body: 'text-slate-200/80',border: 'border-slate-500/30',btn: 'bg-slate-500/15 hover:bg-slate-500/25 text-slate-100 border-slate-400/30',}}return {tag: 'ALERT',tagBg: 'bg-rose-500/30',tagText: 'text-rose-100',iconWrap: 'bg-rose-500/15 text-rose-300 border border-rose-400/30',title: 'text-rose-100',body: 'text-rose-100/85',border: 'border-rose-500/40',btn: 'bg-rose-500/15 hover:bg-rose-500/25 text-rose-100 border-rose-400/40',}})const containerStyle = computed(() => {const bg = {warning: 'linear-gradient(135deg, rgba(120, 53, 15, 0.45) 0%, rgba(154, 52, 18, 0.35) 60%, rgba(159, 18, 57, 0.30) 100%)',critical: 'linear-gradient(135deg, rgba(127, 29, 29, 0.55) 0%, rgba(159, 18, 57, 0.42) 100%)',info: 'linear-gradient(135deg, rgba(30, 41, 59, 0.55) 0%, rgba(15, 23, 42, 0.45) 100%)',}return { background: bg[severity.value] || bg.critical }})const meshStyle = computed(() => {const m = {warning: 'radial-gradient(ellipse 60% 60% at 90% 10%, rgba(251, 146, 60, 0.18), transparent 60%), radial-gradient(ellipse 60% 80% at 10% 100%, rgba(251, 113, 133, 0.12), transparent 60%)',critical: 'radial-gradient(ellipse 70% 70% at 95% 0%, rgba(251, 113, 133, 0.20), transparent 60%), radial-gradient(ellipse 50% 70% at 0% 100%, rgba(220, 38, 38, 0.18), transparent 60%)',info: 'radial-gradient(ellipse 60% 60% at 100% 0%, rgba(148, 163, 184, 0.12), transparent 60%)',}return { background: m[severity.value] || m.critical }})</script>9 unmodified lines101112131415161718191 unmodified line2122232425262728293031324 unmodified lines3738394041424327 unmodified lines7172737475767797 unmodified lines1751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122139 unmodified linesrefresh: 立即重测按钮触发--><template><div v-if="visible" class="relative overflow-hidden rounded-lg border lift-hover shadow-card":class="[tone.border, tone.bg]" role="alert"><!-- 角标 --><div class="absolute top-0 right-0 px-3 py-1 text-[10px] font-mono uppercase tracking-widest rounded-bl-lg":class="[tone.tagBg, tone.tagText]">{{ tone.tag }}</div>1 unmodified line<div class="relative px-5 py-4"><div class="flex items-start gap-4"><!-- 图标 --><div class="relative shrink-0 w-11 h-11 rounded-lg flex items-center justify-center":class="tone.iconWrap"><AlertTriangle v-if="severity === 'critical'" class="w-5 h-5" :stroke-width="2" /><CircleAlert v-else-if="severity === 'warning'" class="w-5 h-5" :stroke-width="2" /><Info v-else-if="severity === 'info'" class="w-5 h-5" :stroke-width="2" /><Check v-else class="w-5 h-5" :stroke-width="2" /><span v-if="severity === 'critical'" class="absolute -top-0.5 -right-0.5 w-2.5 h-2.5 rounded-full bg-rose-400"><span class="absolute inset-0 rounded-full bg-rose-400 animate-ping opacity-75"></span>4 unmodified lines<div class="flex-1 min-w-0"><div class="flex items-center gap-3 flex-wrap"><h3 class="text-base font-bold" :class="tone.title">{{ title }}</h3><span v-if="graceCountdown" class="font-mono text-xs px-2 py-0.5 rounded-md bg-surface border border-hairline":class="graceCountdownColor">grace · {{ graceCountdown }}</span>27 unmodified lines<script setup>import { computed } from 'vue'import { formatGraceRemain, graceUrgencyClass, masterHealthSeverity } from '../composables/useStatus.js'import { AlertTriangle, Check, CircleAlert, Info } from 'lucide-vue-next'const props = defineProps({masterHealth: { type: Object, default: null },97 unmodified linesif (severity.value === 'warning') {return {tag: 'GRACE',tagBg: 'bg-amber-100',tagText: 'text-amber-800',bg: 'bg-amber-50',iconWrap: 'bg-amber-100 text-amber-700 border border-amber-200',title: 'text-amber-950',body: 'text-amber-800',border: 'border-amber-200',btn: 'bg-surface hover:bg-amber-100 text-amber-800 border-amber-200',}}if (severity.value === 'info') {return {tag: 'STALE',tagBg: 'bg-slate-100',tagText: 'text-slate-700',bg: 'bg-slate-50',iconWrap: 'bg-slate-100 text-slate-700 border border-slate-200',title: 'text-slate-950',body: 'text-slate-700',border: 'border-slate-200',btn: 'bg-surface hover:bg-slate-100 text-slate-700 border-slate-200',}}return {tag: 'ALERT',tagBg: 'bg-rose-100',tagText: 'text-rose-800',bg: 'bg-rose-50',iconWrap: 'bg-rose-100 text-rose-700 border border-rose-200',title: 'text-rose-950',body: 'text-rose-800',border: 'border-rose-200',btn: 'bg-surface hover:bg-rose-100 text-rose-800 border-rose-200',}})</script>
1234567891011121314151617185 unmodified lines24252627282930313233343536372 unmodified lines404142434445464748495051525354555657585960613 unmodified lines65666768697071723 unmodified lines767778798081821 unmodified line848586878889904 unmodified lines95969798991001011021031041051061071081091101111121 unmodified line11411511611711811912038 unmodified lines159160161162163164165166<template><div class="mt-6 space-y-6"><div class="bg-gray-900 border border-gray-800 rounded-xl p-4"><div class="flex items-center justify-between gap-4 mb-4"><div><h2 class="text-lg font-semibold text-white">OAuth 登录</h2><p class="text-sm text-gray-400 mt-1">参考 CLIProxyAPI 的手动 OAuth 思路:系统先生成认证链接,你在浏览器中手动完成登录,最后把回调 URL 粘贴回来完成认证。</p></div><spanclass="min-w-[72px] px-3 py-1.5 rounded-full text-xs text-center whitespace-nowrap border":class="manualAccountBusy? 'bg-yellow-500/10 text-yellow-300 border-yellow-500/20': 'bg-gray-800 text-gray-400 border-gray-700'">{{ manualAccountBusy ? '进行中' : '空闲' }}</span>5 unmodified lines<divv-if="manualAccountStatus?.status === 'completed' && manualAccountStatus?.account"class="mb-4 px-4 py-3 rounded-lg text-sm border bg-green-500/10 text-green-400 border-green-500/20">{{ manualAccountStatus.message || `已添加账号 ${manualAccountStatus.account.email}` }}</div><divv-else-if="manualAccountStatus?.status === 'error' && manualAccountStatus?.error"class="mb-4 px-4 py-3 rounded-lg text-sm border bg-red-500/10 text-red-400 border-red-500/20">{{ manualAccountStatus.error }}</div>2 unmodified lines<button@click="startManualAccount":disabled="manualSubmitting"class="px-4 py-2 bg-emerald-700 hover:bg-emerald-600 text-white text-sm rounded-lg transition disabled:opacity-50">{{ manualSubmitting ? '生成中...' : '生成 OAuth 链接' }}</button></div><div v-else class="space-y-4"><div class="text-sm text-gray-300">已生成 OAuth 链接。若当前机器可访问 <span class="font-mono">localhost:1455</span>,系统会自动接收回调;否则请手动粘贴最终回调 URL。</div><divclass="px-4 py-3 rounded-lg text-sm border":class="manualAccountStatus?.auto_callback_available? 'bg-blue-500/10 text-blue-300 border-blue-500/20': 'bg-amber-500/10 text-amber-300 border-amber-500/20'">{{manualAccountStatus?.auto_callback_available3 unmodified lines</div><div class="space-y-2"><div class="text-xs text-gray-500">OAuth 链接</div><div class="p-3 bg-gray-800 border border-gray-700 rounded-lg text-xs font-mono break-all text-gray-200">{{ manualAccountStatus?.auth_url }}</div></div>3 unmodified lines:href="manualAccountStatus?.auth_url"target="_blank"rel="noopener noreferrer"class="px-4 py-2 bg-emerald-700 hover:bg-emerald-600 text-white text-sm rounded-lg transition">打开 OAuth 链接</a>1 unmodified line<divv-if="manualAccountStatus?.callback_received"class="text-xs text-emerald-300">已收到{{ manualAccountStatus?.callback_source === 'auto' ? '自动' : '手动' }}回调,刷新轮询中…</div>4 unmodified linestype="text"placeholder="粘贴回调 URL,例如 http://localhost:1455/auth/callback?code=...&state=...":disabled="manualSubmitting"class="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-sm text-white focus:outline-none focus:border-blue-500"/><button@click="submitManualCallback":disabled="manualSubmitting || !manualCallbackUrl"class="px-4 py-2 bg-emerald-700 hover:bg-emerald-600 text-white text-sm rounded-lg transition disabled:opacity-50">{{ manualSubmitting ? '提交中...' : '提交回调 URL' }}</button></div><div v-if="manualSubmitting && manualSubmittingHint" class="text-xs text-emerald-300">{{ manualSubmittingHint }}</div>1 unmodified line<button@click="cancelManualAccount":disabled="manualSubmitting"class="px-4 py-2 bg-gray-800 hover:bg-gray-700 text-sm text-gray-200 rounded-lg border border-gray-700 transition disabled:opacity-50">取消 OAuth 登录</button>38 unmodified linesfunction setMessage(text, type = 'success') {message.value = textmessageClass.value = type === 'success'? 'bg-green-500/10 text-green-400 border-green-500/20': 'bg-red-500/10 text-red-400 border-red-500/20'window.clearTimeout(setMessage._timer)setMessage._timer = window.setTimeout(() => {message.value = ''1234567891011121314151617185 unmodified lines24252627282930313233343536372 unmodified lines404142434445464748495051525354555657585960613 unmodified lines65666768697071723 unmodified lines767778798081821 unmodified line848586878889904 unmodified lines95969798991001011021031041051061071081091101111121 unmodified line11411511611711811912038 unmodified lines159160161162163164165166<template><div class="mt-6 space-y-6"><div class="glass rounded-lg p-4"><div class="flex items-center justify-between gap-4 mb-4"><div><h2 class="text-lg font-semibold text-ink-950">OAuth 登录</h2><p class="text-sm text-ink-500 mt-1">参考 CLIProxyAPI 的手动 OAuth 思路:系统先生成认证链接,你在浏览器中手动完成登录,最后把回调 URL 粘贴回来完成认证。</p></div><spanclass="min-w-[72px] px-3 py-1.5 rounded-full text-xs text-center whitespace-nowrap border":class="manualAccountBusy? 'bg-amber-50 text-amber-800 border-amber-200': 'bg-ink-50 text-ink-600 border-hairline'">{{ manualAccountBusy ? '进行中' : '空闲' }}</span>5 unmodified lines<divv-if="manualAccountStatus?.status === 'completed' && manualAccountStatus?.account"class="mb-4 px-4 py-3 rounded-lg text-sm border bg-emerald-50 text-emerald-700 border-emerald-200">{{ manualAccountStatus.message || `已添加账号 ${manualAccountStatus.account.email}` }}</div><divv-else-if="manualAccountStatus?.status === 'error' && manualAccountStatus?.error"class="mb-4 px-4 py-3 rounded-lg text-sm border bg-rose-50 text-rose-700 border-rose-200">{{ manualAccountStatus.error }}</div>2 unmodified lines<button@click="startManualAccount":disabled="manualSubmitting"class="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 text-on-accent text-sm rounded-lg transition disabled:opacity-50 focus-ring">{{ manualSubmitting ? '生成中...' : '生成 OAuth 链接' }}</button></div><div v-else class="space-y-4"><div class="text-sm text-ink-700">已生成 OAuth 链接。若当前机器可访问 <span class="font-mono">localhost:1455</span>,系统会自动接收回调;否则请手动粘贴最终回调 URL。</div><divclass="px-4 py-3 rounded-lg text-sm border":class="manualAccountStatus?.auto_callback_available? 'bg-blue-50 text-blue-700 border-blue-200': 'bg-amber-50 text-amber-800 border-amber-200'">{{manualAccountStatus?.auto_callback_available3 unmodified lines</div><div class="space-y-2"><div class="text-xs text-ink-500">OAuth 链接</div><div class="p-3 bg-ink-50 border border-hairline rounded-lg text-xs font-mono break-all text-ink-700">{{ manualAccountStatus?.auth_url }}</div></div>3 unmodified lines:href="manualAccountStatus?.auth_url"target="_blank"rel="noopener noreferrer"class="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 text-on-accent text-sm rounded-lg transition focus-ring">打开 OAuth 链接</a>1 unmodified line<divv-if="manualAccountStatus?.callback_received"class="text-xs text-emerald-700">已收到{{ manualAccountStatus?.callback_source === 'auto' ? '自动' : '手动' }}回调,刷新轮询中…</div>4 unmodified linestype="text"placeholder="粘贴回调 URL,例如 http://localhost:1455/auth/callback?code=...&state=...":disabled="manualSubmitting"class="w-full px-3 py-2 bg-surface border border-hairline rounded-lg text-sm text-ink-950 focus-ring"/><button@click="submitManualCallback":disabled="manualSubmitting || !manualCallbackUrl"class="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 text-on-accent text-sm rounded-lg transition disabled:opacity-50 focus-ring">{{ manualSubmitting ? '提交中...' : '提交回调 URL' }}</button></div><div v-if="manualSubmitting && manualSubmittingHint" class="text-xs text-emerald-700">{{ manualSubmittingHint }}</div>1 unmodified line<button@click="cancelManualAccount":disabled="manualSubmitting"class="px-4 py-2 bg-surface hover:bg-ink-100 text-sm text-ink-700 rounded-lg border border-hairline transition disabled:opacity-50 focus-ring">取消 OAuth 登录</button>38 unmodified linesfunction setMessage(text, type = 'success') {message.value = textmessageClass.value = type === 'success'? 'bg-emerald-50 text-emerald-700 border-emerald-200': 'bg-rose-50 text-rose-700 border-rose-200'window.clearTimeout(setMessage._timer)setMessage._timer = window.setTimeout(() => {message.value = ''
4 unmodified lines567891011121314159 unmodified lines2526272829303111 unmodified lines4344454647484950515253545516 unmodified lines72737475767720 unmodified lines989910010110210310410510610710810911011111211311411511611711811912012112212312412512620 unmodified lines1471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911924 unmodified lines- master_health inline 状态--><template><div class="glass rounded-2xl p-5 lg:p-6 lift-hover relative overflow-hidden"><!-- 背景装饰 --><div class="absolute -top-16 -right-16 w-64 h-64 rounded-full opacity-30 blur-3xl pointer-events-none":style="{ background: 'radial-gradient(circle, rgba(99, 102, 241, 0.30), transparent 60%)' }"></div><div class="relative flex flex-col lg:flex-row items-start lg:items-center gap-6"><!-- 左:donut + 中心总数 --><div class="shrink-0">9 unmodified lines<!-- 中:四档数字 --><div class="flex-1 grid grid-cols-2 sm:grid-cols-4 gap-3 w-full"><div v-for="card in cards" :key="card.key"class="rounded-xl p-3 border bg-white/[0.02] hover:bg-white/[0.05] transition-all":class="card.borderClass"><div class="flex items-center gap-1.5 text-[10px] uppercase tracking-widest font-semibold":class="card.labelClass">11 unmodified lines<!-- 右:master health inline --><div class="shrink-0 lg:max-w-xs w-full lg:w-auto"><div class="rounded-xl border p-3 flex items-start gap-3":class="masterTone.border" :style="{ background: masterTone.bg }"><div class="shrink-0 w-9 h-9 rounded-lg flex items-center justify-center":class="masterTone.iconWrap"><svg viewBox="0 0 16 16" class="w-4 h-4"><path :fill="masterTone.iconFill" d="M3 2.5h10v3a4.99 4.99 0 0 1-5 5 4.99 4.99 0 0 1-5-5v-3zM5 12.5h6v1.5H5z"/></svg></div><div class="min-w-0 flex-1"><div class="text-[10px] uppercase tracking-widest font-semibold opacity-70" :class="masterTone.text">16 unmodified linesimport { computed } from 'vue'import HealthDonut from './HealthDonut.vue'import { computeUsability, formatGraceRemain } from '../composables/useStatus.js'const props = defineProps({accounts: { type: Array, default: () => [] },20 unmodified lineskey: 'usable', label: '可用', value: counts.value.usable,color: 'rgba(52, 211, 153, 1)',borderClass: 'border-emerald-500/20',labelClass: 'text-emerald-300',valueClass: 'text-emerald-200',},{key: 'grace', label: 'Grace', value: counts.value.grace,color: 'rgba(251, 146, 60, 1)',borderClass: 'border-orange-500/30',labelClass: 'text-orange-300',valueClass: 'text-orange-200',},{key: 'standby', label: '待机', value: counts.value.standby,color: 'rgba(251, 191, 36, 1)',borderClass: 'border-amber-500/20',labelClass: 'text-amber-300',valueClass: 'text-amber-200',},{key: 'unusable', label: '不可用', value: counts.value.unusable,color: 'rgba(244, 63, 94, 1)',borderClass: 'border-rose-500/20',labelClass: 'text-rose-300',valueClass: 'text-rose-200',},])20 unmodified lines// Round 11:subscription_grace = healthy=True 但 grace 期内,渲染橙色提示 (而非 healthy 绿色)if (r === 'subscription_grace') {return {bg: 'linear-gradient(135deg, rgba(251, 146, 60, 0.14), rgba(244, 63, 94, 0.10))',border: 'border-orange-500/30',iconWrap: 'bg-orange-500/15',iconFill: 'rgb(253, 186, 116)',text: 'text-orange-200',}}if (!m || m.healthy === true || r === 'active') {return {bg: 'linear-gradient(135deg, rgba(16, 185, 129, 0.10), rgba(20, 184, 166, 0.05))',border: 'border-emerald-500/20',iconWrap: 'bg-emerald-500/15',iconFill: 'rgb(110, 231, 183)',text: 'text-emerald-200',}}if (r === 'subscription_cancelled') {return {bg: 'linear-gradient(135deg, rgba(251, 146, 60, 0.14), rgba(244, 63, 94, 0.10))',border: 'border-orange-500/30',iconWrap: 'bg-orange-500/15',iconFill: 'rgb(253, 186, 116)',text: 'text-orange-200',}}if (r === 'network_error') {return {bg: 'linear-gradient(135deg, rgba(100, 116, 139, 0.14), rgba(71, 85, 105, 0.10))',border: 'border-slate-500/25',iconWrap: 'bg-slate-500/15',iconFill: 'rgb(203, 213, 225)',text: 'text-slate-200',}}return {bg: 'linear-gradient(135deg, rgba(244, 63, 94, 0.14), rgba(220, 38, 38, 0.10))',border: 'border-rose-500/30',iconWrap: 'bg-rose-500/15',iconFill: 'rgb(253, 164, 175)',text: 'text-rose-200',}})4 unmodified lines5678910119 unmodified lines2122232425262711 unmodified lines394041424344454647484916 unmodified lines6667686970717220 unmodified lines9394959697989910010110210310410510610710810911011111211311411511611711811912012120 unmodified lines1421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811824 unmodified lines- master_health inline 状态--><template><div class="glass rounded-lg p-5 lg:p-6 lift-hover relative overflow-hidden"><div class="relative flex flex-col lg:flex-row items-start lg:items-center gap-6"><!-- 左:donut + 中心总数 --><div class="shrink-0">9 unmodified lines<!-- 中:四档数字 --><div class="flex-1 grid grid-cols-2 sm:grid-cols-4 gap-3 w-full"><div v-for="card in cards" :key="card.key"class="rounded-lg p-3 border bg-surface hover:bg-ink-50 transition-all":class="card.borderClass"><div class="flex items-center gap-1.5 text-[10px] uppercase tracking-widest font-semibold":class="card.labelClass">11 unmodified lines<!-- 右:master health inline --><div class="shrink-0 lg:max-w-xs w-full lg:w-auto"><div class="rounded-lg border p-3 flex items-start gap-3":class="masterTone.border" :style="{ background: masterTone.bg }"><div class="shrink-0 w-9 h-9 rounded-lg flex items-center justify-center":class="masterTone.iconWrap"><ShieldCheck class="w-4 h-4" :stroke-width="2" /></div><div class="min-w-0 flex-1"><div class="text-[10px] uppercase tracking-widest font-semibold opacity-70" :class="masterTone.text">16 unmodified linesimport { computed } from 'vue'import HealthDonut from './HealthDonut.vue'import { computeUsability, formatGraceRemain } from '../composables/useStatus.js'import { ShieldCheck } from 'lucide-vue-next'const props = defineProps({accounts: { type: Array, default: () => [] },20 unmodified lineskey: 'usable', label: '可用', value: counts.value.usable,color: 'rgba(52, 211, 153, 1)',borderClass: 'border-emerald-500/20',labelClass: 'text-emerald-700',valueClass: 'text-emerald-700',},{key: 'grace', label: 'Grace', value: counts.value.grace,color: 'rgba(251, 146, 60, 1)',borderClass: 'border-orange-500/30',labelClass: 'text-orange-700',valueClass: 'text-orange-700',},{key: 'standby', label: '待机', value: counts.value.standby,color: 'rgba(251, 191, 36, 1)',borderClass: 'border-amber-500/20',labelClass: 'text-amber-700',valueClass: 'text-amber-700',},{key: 'unusable', label: '不可用', value: counts.value.unusable,color: 'rgba(244, 63, 94, 1)',borderClass: 'border-rose-500/20',labelClass: 'text-rose-700',valueClass: 'text-rose-700',},])20 unmodified lines// Round 11:subscription_grace = healthy=True 但 grace 期内,渲染橙色提示 (而非 healthy 绿色)if (r === 'subscription_grace') {return {bg: '#fff7ed',border: 'border-orange-200',iconWrap: 'bg-orange-100 text-orange-700',text: 'text-orange-800',}}if (!m || m.healthy === true || r === 'active') {return {bg: '#ecfdf5',border: 'border-emerald-200',iconWrap: 'bg-emerald-100 text-emerald-700',text: 'text-emerald-800',}}if (r === 'subscription_cancelled') {return {bg: '#fff7ed',border: 'border-orange-200',iconWrap: 'bg-orange-100 text-orange-700',text: 'text-orange-800',}}if (r === 'network_error') {return {bg: '#f8fafc',border: 'border-slate-200',iconWrap: 'bg-slate-100 text-slate-700',text: 'text-slate-700',}}return {bg: '#fff1f2',border: 'border-rose-200',iconWrap: 'bg-rose-100 text-rose-700',text: 'text-rose-800',}})
1234567893 unmodified lines131415161718192021222324252627282930313219 unmodified lines5253545556575859606156 unmodified lines11811912012112212312412512612712812959 unmodified lines18919019119219319419528 unmodified lines22422522622722822923023123223323423523623713 unmodified lines2512522532542552562572582592602612622639 unmodified lines27327427527627727827934 unmodified lines3143153163173183193209 unmodified lines3303313323333343353363373383393403413423433441 unmodified line3463473483493503513521 unmodified line35435535635735835936014 unmodified lines37537637737837938038138238338438538638738838939039139230 unmodified lines4234244254264274284294304314325 unmodified lines43843944044144244344417 unmodified lines4624634644654664674681 unmodified line470471472473474475476116 unmodified lines59359459559659759859960037 unmodified lines638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667214 unmodified lines8828838848858868878888898904 unmodified lines895896897898899900901902903904905906907<template><div class="space-y-5"><div><div class="text-[10px] uppercase tracking-[0.3em] text-indigo-300/70 mb-1">Configuration</div><h2 class="text-2xl font-extrabold text-ink-950 tracking-tight">设置</h2><p class="text-sm text-gray-400 mt-1">管理员登录、巡检策略、邮箱后端、生命周期参数,皆可在此调整。</p></div><!-- F3 — 共享父级 master-health banner -->3 unmodified lines:loading="masterHealthLoading"@refresh="onReloadMasterHealth" /><div class="glass rounded-2xl p-5"><div class="flex items-center justify-between gap-4 mb-4"><div><h2 class="text-lg font-semibold text-ink-950">管理员登录</h2><p class="text-sm text-gray-400 mt-1">首次启动先在这里完成主号登录,系统会统一写入单个 state.json 文件,保存邮箱、session、workspace ID、workspace 名称;如果你走了密码登录,也会保留密码供主号 Codex 复用。</p></div><spanclass="min-w-[72px] px-3 py-1.5 rounded-full text-xs text-center whitespace-nowrap border":class="adminConfigured? 'bg-green-500/10 text-green-400 border-green-500/20': adminBusy? 'bg-yellow-500/10 text-yellow-300 border-yellow-500/20': 'bg-surface-hover text-ink-500 border-hairline'">{{ adminConfigured ? '已配置' : adminBusy ? '登录中' : '未配置' }}19 unmodified lines</div><div class="px-3 py-3 bg-surface-hover border border-hairline rounded-lg md:col-span-2"><div class="text-gray-500 mb-1">Session Token</div><div v-if="props.adminStatus?.session_present" class="text-green-400 text-xs">已配置</div><div v-else class="space-y-2"><div class="text-amber-400 text-xs">未配置(Team 管理功能需要 session token)</div><div class="text-gray-400 text-xs space-y-2"><div>获取方式:</div><ol class="list-decimal list-inside space-y-1"><li>56 unmodified lines</button></div><div class="border border-hairline rounded-xl p-4 bg-surface-hover"><div class="text-sm font-medium text-ink-950">或手动导入 session_token</div><p class="text-xs text-gray-400 mt-1 mb-3">适合你已经在浏览器里拿到 <span class="font-mono">__Secure-next-auth.session-token</span> 的场景。系统会校验 token,并自动识别 workspace ID / 名称。</p><div class="text-gray-400 text-xs space-y-2 mb-3"><div>获取方式:</div><ol class="list-decimal list-inside space-y-1"><li>59 unmodified lines</div><div v-if="adminBusy" class="space-y-4"><div class="text-sm text-gray-300">当前邮箱: <span class="font-mono">{{ loginEmail || props.adminStatus?.email || '-' }}</span></div>28 unmodified lines<button@click="submitCode":disabled="submitting || !code"class="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 text-on-accent text-sm rounded-lg transition disabled:opacity-50 disabled:bg-gray-700 disabled:hover:bg-gray-700">{{ submitting ? '提交中...' : '提交验证码' }}</button></div><div v-else-if="props.adminStatus?.login_step === 'workspace_required'" class="space-y-3"><div class="text-sm text-gray-300">请选择要进入的组织 / workspace</div><select13 unmodified lines<button@click="submitWorkspace":disabled="submitting || !workspaceOptionId"class="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 text-on-accent text-sm rounded-lg transition disabled:opacity-50 disabled:bg-gray-700 disabled:hover:bg-gray-700">{{ submitting ? '提交中...' : '确认组织选择' }}</button></div><div v-if="submitting && adminSubmittingHint" class="text-xs text-blue-300">{{ adminSubmittingHint }}</div>9 unmodified lines</div><div v-if="codexBusy" class="mt-4 space-y-4 border-t border-hairline pt-4"><div class="text-sm text-gray-300">主号 Codex 登录继续中</div>34 unmodified lines</button></div><div v-if="syncingMain && codexSubmittingHint" class="text-xs text-cyan-300">{{ codexSubmittingHint }}</div>9 unmodified lines</div></div><div class="glass rounded-2xl p-5"><div class="flex items-center justify-between mb-4"><h2 class="text-lg font-semibold text-ink-950">巡检设置</h2><span v-if="saved" class="text-xs text-green-400 transition">已保存</span></div><div class="grid grid-cols-1 sm:grid-cols-3 gap-4"><div><label class="block text-sm text-gray-400 mb-1">巡检间隔</label><div class="flex items-center gap-2"><input v-model.number="form.interval" type="number" min="1"class="w-full px-3 py-2 bg-surface-hover border border-hairline rounded-lg text-sm text-ink-950 focus:outline-none focus:border-indigo-500" />1 unmodified line</div></div><div><label class="block text-sm text-gray-400 mb-1">额度阈值</label><div class="flex items-center gap-2"><input v-model.number="form.threshold" type="number" min="1" max="100"class="w-full px-3 py-2 bg-surface-hover border border-hairline rounded-lg text-sm text-ink-950 focus:outline-none focus:border-indigo-500" />1 unmodified line</div></div><div><label class="block text-sm text-gray-400 mb-1">触发账号数</label><div class="flex items-center gap-2"><input v-model.number="form.min_low" type="number" min="1"class="w-full px-3 py-2 bg-surface-hover border border-hairline rounded-lg text-sm text-ink-950 focus:outline-none focus:border-indigo-500" />14 unmodified lines</div><!-- SPEC-1 §FR-008 / AC-017 — 邮箱后端切换 (Settings 复用 SetupPage 4 步状态机) --><div class="glass rounded-2xl p-5"><div class="flex items-center justify-between gap-4 mb-4"><div><h2 class="text-lg font-semibold text-ink-950">邮箱后端</h2><p class="text-sm text-gray-400 mt-1">切换或重新配置临时邮箱服务(cf_temp_email / maillab)。SetupPage 完成后所有字段已落盘,这里仅在需要更换服务时使用。</p></div><spanclass="min-w-[72px] px-3 py-1.5 rounded-full text-xs text-center whitespace-nowrap border":class="mailFormDirty? 'bg-yellow-500/10 text-yellow-300 border-yellow-500/20': 'bg-surface-hover text-ink-500 border-hairline'">{{ mailFormDirty ? '有改动' : '已配置' }}30 unmodified lines</div><!-- SPEC-2 §席位策略 + 探测节流 --><div class="glass rounded-2xl p-5"><div class="mb-4"><h2 class="text-lg font-semibold text-ink-950">账号生命周期</h2><p class="text-sm text-gray-400 mt-1">控制邀请席位偏好(完整 ChatGPT 席位 vs 仅 Codex 席位),以及 sync 巡检识别"被踢"的探测节流。</p></div>5 unmodified lines<div class="mb-4 p-3 bg-surface-hover/60 border border-hairline rounded"><div class="flex items-center justify-between mb-2"><span class="text-sm text-ink-950">邀请席位偏好</span><span class="text-xs text-gray-400">{{ preferredSeatType === 'codex' ? '锁定 Codex 席位' : '优先 ChatGPT 完整席位' }}</span></div><div class="flex gap-2"><button17 unmodified lines<div class="text-sm text-ink-950 mb-2">sync 探测节流</div><div class="grid grid-cols-1 sm:grid-cols-2 gap-3"><div><div class="text-xs text-gray-400 mb-1">并发上限 (1-16)</div><inputv-model.number="syncProbeConcurrency"type="number"1 unmodified lineclass="w-full px-2 py-1.5 bg-surface-hover border border-hairline rounded text-sm text-ink-950" /></div><div><div class="text-xs text-gray-400 mb-1">同号去重冷却 (分钟,1-1440)</div><inputv-model.number="syncProbeCooldown"type="number"116 unmodified linesfunction setLifecycleMessage(text, type = 'success') {lifecycleMessage.value = textlifecycleMessageClass.value = type === 'success'? 'bg-green-500/10 text-green-400 border-green-500/20': 'bg-red-500/10 text-red-400 border-red-500/20'window.clearTimeout(setLifecycleMessage._t)setLifecycleMessage._t = window.setTimeout(() => { lifecycleMessage.value = '' }, 8000)}37 unmodified linesthreshold: cfg.threshold,min_low: cfg.min_low,}} catch (e) {console.error('加载巡检配置失败:', e)}try {const seat = await api.getPreferredSeatType()preferredSeatType.value = seat?.value || 'default'} catch (e) {console.error('加载邀请席位偏好失败:', e)}try {const sp = await api.getSyncProbe()syncProbeConcurrency.value = sp?.concurrency ?? 5syncProbeCooldown.value = sp?.cooldown_minutes ?? 30} catch (e) {console.error('加载 sync 探测节流失败:', e)}// F3 — 母号订阅健康度由 App 级共享 props.masterHealth,不再本组件自管})function setMessage(text, type = 'success') {message.value = textmessageClass.value = type === 'success'? 'bg-green-500/10 text-green-400 border-green-500/20': 'bg-red-500/10 text-red-400 border-red-500/20'window.clearTimeout(setMessage._timer)setMessage._timer = window.setTimeout(() => {message.value = ''214 unmodified linesfunction setMailMessage(text, type = 'success') {mailMessage.value = textif (type === 'success') mailMessageClass.value = 'bg-green-500/10 text-green-400 border-green-500/20'else if (type === 'warning') mailMessageClass.value = 'bg-yellow-500/10 text-yellow-400 border-yellow-500/20'else mailMessageClass.value = 'bg-red-500/10 text-red-400 border-red-500/20'window.clearTimeout(setMailMessage._timer)setMailMessage._timer = window.setTimeout(() => { mailMessage.value = '' }, 10000)}4 unmodified linesfunction onMailVerified(payload) {if (payload?.leakedProbe) {setMailMessage(`⚠️ 探测邮箱回收失败,请到后台手动删除: ${payload.leakedProbe.email}`, 'warning')}}function onMailError(resp) {if (resp?.soft && resp.warnings) {setMailMessage('⚠️ ' + resp.warnings.join('; '), 'warning')return}setMailMessage(`${resp.error_code || 'ERROR'}: ${resp.message || '未知错误'}` +1234567893 unmodified lines131415161718192021222324252627282930313219 unmodified lines5253545556575859606156 unmodified lines11811912012112212312412512612712812959 unmodified lines18919019119219319419528 unmodified lines22422522622722822923023123223323423523623713 unmodified lines2512522532542552562572582592602612622639 unmodified lines27327427527627727827934 unmodified lines3143153163173183193209 unmodified lines3303313323333343353363373383393403413423433441 unmodified line3463473483493503513521 unmodified line35435535635735835936014 unmodified lines37537637737837938038138238338438538638738838939039139230 unmodified lines4234244254264274284294304314325 unmodified lines43843944044144244344417 unmodified lines4624634644654664674681 unmodified line470471472473474475476116 unmodified lines59359459559659759859960037 unmodified lines638639640641642643644645646647648649650651652653654655656657658659660661214 unmodified lines8768778788798808818828838844 unmodified lines889890891892893894895896897898899900901<template><div class="space-y-5"><div><div class="text-[10px] uppercase tracking-[0.3em] text-indigo-700 mb-1">Configuration</div><h2 class="text-2xl font-extrabold text-ink-950 tracking-tight">设置</h2><p class="text-sm text-ink-500 mt-1">管理员登录、巡检策略、邮箱后端、生命周期参数,皆可在此调整。</p></div><!-- F3 — 共享父级 master-health banner -->3 unmodified lines:loading="masterHealthLoading"@refresh="onReloadMasterHealth" /><div class="glass rounded-lg p-5"><div class="flex items-center justify-between gap-4 mb-4"><div><h2 class="text-lg font-semibold text-ink-950">管理员登录</h2><p class="text-sm text-ink-500 mt-1">首次启动先在这里完成主号登录,系统会统一写入单个 state.json 文件,保存邮箱、session、workspace ID、workspace 名称;如果你走了密码登录,也会保留密码供主号 Codex 复用。</p></div><spanclass="min-w-[72px] px-3 py-1.5 rounded-full text-xs text-center whitespace-nowrap border":class="adminConfigured? 'bg-emerald-50 text-emerald-700 border-emerald-200': adminBusy? 'bg-amber-50 text-amber-700 border-amber-200': 'bg-surface-hover text-ink-500 border-hairline'">{{ adminConfigured ? '已配置' : adminBusy ? '登录中' : '未配置' }}19 unmodified lines</div><div class="px-3 py-3 bg-surface-hover border border-hairline rounded-lg md:col-span-2"><div class="text-gray-500 mb-1">Session Token</div><div v-if="props.adminStatus?.session_present" class="text-emerald-700 text-xs">已配置</div><div v-else class="space-y-2"><div class="text-amber-400 text-xs">未配置(Team 管理功能需要 session token)</div><div class="text-ink-500 text-xs space-y-2"><div>获取方式:</div><ol class="list-decimal list-inside space-y-1"><li>56 unmodified lines</button></div><div class="border border-hairline rounded-lg p-4 bg-surface-hover"><div class="text-sm font-medium text-ink-950">或手动导入 session_token</div><p class="text-xs text-ink-500 mt-1 mb-3">适合你已经在浏览器里拿到 <span class="font-mono">__Secure-next-auth.session-token</span> 的场景。系统会校验 token,并自动识别 workspace ID / 名称。</p><div class="text-ink-500 text-xs space-y-2 mb-3"><div>获取方式:</div><ol class="list-decimal list-inside space-y-1"><li>59 unmodified lines</div><div v-if="adminBusy" class="space-y-4"><div class="text-sm text-ink-700">当前邮箱: <span class="font-mono">{{ loginEmail || props.adminStatus?.email || '-' }}</span></div>28 unmodified lines<button@click="submitCode":disabled="submitting || !code"class="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 text-on-accent text-sm rounded-lg transition disabled:opacity-50 disabled:bg-ink-100 disabled:hover:bg-ink-100">{{ submitting ? '提交中...' : '提交验证码' }}</button></div><div v-else-if="props.adminStatus?.login_step === 'workspace_required'" class="space-y-3"><div class="text-sm text-ink-700">请选择要进入的组织 / workspace</div><select13 unmodified lines<button@click="submitWorkspace":disabled="submitting || !workspaceOptionId"class="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 text-on-accent text-sm rounded-lg transition disabled:opacity-50 disabled:bg-ink-100 disabled:hover:bg-ink-100">{{ submitting ? '提交中...' : '确认组织选择' }}</button></div><div v-if="submitting && adminSubmittingHint" class="text-xs text-sky-700">{{ adminSubmittingHint }}</div>9 unmodified lines</div><div v-if="codexBusy" class="mt-4 space-y-4 border-t border-hairline pt-4"><div class="text-sm text-ink-700">主号 Codex 登录继续中</div>34 unmodified lines</button></div><div v-if="syncingMain && codexSubmittingHint" class="text-xs text-cyan-700">{{ codexSubmittingHint }}</div>9 unmodified lines</div></div><div class="glass rounded-lg p-5"><div class="flex items-center justify-between mb-4"><h2 class="text-lg font-semibold text-ink-950">巡检设置</h2><span v-if="saved" class="text-xs text-emerald-700 transition">已保存</span></div><div class="grid grid-cols-1 sm:grid-cols-3 gap-4"><div><label class="block text-sm text-ink-500 mb-1">巡检间隔</label><div class="flex items-center gap-2"><input v-model.number="form.interval" type="number" min="1"class="w-full px-3 py-2 bg-surface-hover border border-hairline rounded-lg text-sm text-ink-950 focus:outline-none focus:border-indigo-500" />1 unmodified line</div></div><div><label class="block text-sm text-ink-500 mb-1">额度阈值</label><div class="flex items-center gap-2"><input v-model.number="form.threshold" type="number" min="1" max="100"class="w-full px-3 py-2 bg-surface-hover border border-hairline rounded-lg text-sm text-ink-950 focus:outline-none focus:border-indigo-500" />1 unmodified line</div></div><div><label class="block text-sm text-ink-500 mb-1">触发账号数</label><div class="flex items-center gap-2"><input v-model.number="form.min_low" type="number" min="1"class="w-full px-3 py-2 bg-surface-hover border border-hairline rounded-lg text-sm text-ink-950 focus:outline-none focus:border-indigo-500" />14 unmodified lines</div><!-- SPEC-1 §FR-008 / AC-017 — 邮箱后端切换 (Settings 复用 SetupPage 4 步状态机) --><div class="glass rounded-lg p-5"><div class="flex items-center justify-between gap-4 mb-4"><div><h2 class="text-lg font-semibold text-ink-950">邮箱后端</h2><p class="text-sm text-ink-500 mt-1">切换或重新配置临时邮箱服务(cf_temp_email / maillab)。SetupPage 完成后所有字段已落盘,这里仅在需要更换服务时使用。</p></div><spanclass="min-w-[72px] px-3 py-1.5 rounded-full text-xs text-center whitespace-nowrap border":class="mailFormDirty? 'bg-amber-50 text-amber-700 border-amber-200': 'bg-surface-hover text-ink-500 border-hairline'">{{ mailFormDirty ? '有改动' : '已配置' }}30 unmodified lines</div><!-- SPEC-2 §席位策略 + 探测节流 --><div class="glass rounded-lg p-5"><div class="mb-4"><h2 class="text-lg font-semibold text-ink-950">账号生命周期</h2><p class="text-sm text-ink-500 mt-1">控制邀请席位偏好(完整 ChatGPT 席位 vs 仅 Codex 席位),以及 sync 巡检识别"被踢"的探测节流。</p></div>5 unmodified lines<div class="mb-4 p-3 bg-surface-hover/60 border border-hairline rounded"><div class="flex items-center justify-between mb-2"><span class="text-sm text-ink-950">邀请席位偏好</span><span class="text-xs text-ink-500">{{ preferredSeatType === 'codex' ? '锁定 Codex 席位' : '优先 ChatGPT 完整席位' }}</span></div><div class="flex gap-2"><button17 unmodified lines<div class="text-sm text-ink-950 mb-2">sync 探测节流</div><div class="grid grid-cols-1 sm:grid-cols-2 gap-3"><div><div class="text-xs text-ink-500 mb-1">并发上限 (1-16)</div><inputv-model.number="syncProbeConcurrency"type="number"1 unmodified lineclass="w-full px-2 py-1.5 bg-surface-hover border border-hairline rounded text-sm text-ink-950" /></div><div><div class="text-xs text-ink-500 mb-1">同号去重冷却 (分钟,1-1440)</div><inputv-model.number="syncProbeCooldown"type="number"116 unmodified linesfunction setLifecycleMessage(text, type = 'success') {lifecycleMessage.value = textlifecycleMessageClass.value = type === 'success'? 'bg-emerald-50 text-emerald-700 border-emerald-200': 'bg-rose-50 text-rose-700 border-rose-200'window.clearTimeout(setLifecycleMessage._t)setLifecycleMessage._t = window.setTimeout(() => { lifecycleMessage.value = '' }, 8000)}37 unmodified linesthreshold: cfg.threshold,min_low: cfg.min_low,}} catch {}try {const seat = await api.getPreferredSeatType()preferredSeatType.value = seat?.value || 'default'} catch {}try {const sp = await api.getSyncProbe()syncProbeConcurrency.value = sp?.concurrency ?? 5syncProbeCooldown.value = sp?.cooldown_minutes ?? 30} catch {}// F3 — 母号订阅健康度由 App 级共享 props.masterHealth,不再本组件自管})function setMessage(text, type = 'success') {message.value = textmessageClass.value = type === 'success'? 'bg-emerald-50 text-emerald-700 border-emerald-200': 'bg-rose-50 text-rose-700 border-rose-200'window.clearTimeout(setMessage._timer)setMessage._timer = window.setTimeout(() => {message.value = ''214 unmodified linesfunction setMailMessage(text, type = 'success') {mailMessage.value = textif (type === 'success') mailMessageClass.value = 'bg-emerald-50 text-emerald-700 border-emerald-200'else if (type === 'warning') mailMessageClass.value = 'bg-amber-50 text-amber-700 border-amber-200'else mailMessageClass.value = 'bg-rose-50 text-rose-700 border-rose-200'window.clearTimeout(setMailMessage._timer)setMailMessage._timer = window.setTimeout(() => { mailMessage.value = '' }, 10000)}4 unmodified linesfunction onMailVerified(payload) {if (payload?.leakedProbe) {setMailMessage(`提醒: 探测邮箱回收失败,请到后台手动删除: ${payload.leakedProbe.email}`, 'warning')}}function onMailError(resp) {if (resp?.soft && resp.warnings) {setMailMessage('提醒: ' + resp.warnings.join('; '), 'warning')return}setMailMessage(`${resp.error_code || 'ERROR'}: ${resp.message || '未知错误'}` +
123456781 unmodified line1011121314151617181920212223242526272829303132333435361 unmodified line3839404142434440 unmodified lines8586878889909192939495969798991001011021031041051061071081091101111121131141153 unmodified lines11912012112212312412512612712812911 unmodified lines141142143144145146147<template><div class="min-h-screen flex items-center justify-center p-4"><div class="bg-gray-900 border border-gray-800 rounded-xl p-6 w-full max-w-2xl"><h1 class="text-xl font-bold text-white text-center mb-2">AutoTeam 初始配置</h1><p class="text-sm text-gray-400 text-center mb-6">首次使用请按步骤填写以下配置</p><div v-if="message" class="mb-4 px-4 py-3 rounded-lg text-sm border" :class="messageClass">{{ message }}1 unmodified line<!-- 卡片 1+2+3:Mail Provider 选择 / 连接 / 域名(Round 7 P2.2 抽 MailProviderCard) --><MailProviderCardv-model="form"mode="setup"@state-change="onMailStateChange"@verified="onMailVerified"@error="onMailError" /><!-- 卡片 4:其他配置 --><div class="mb-4 p-4 rounded-lg border" :class="cardClass('SAVE')"><h2 class="text-sm font-semibold text-white mb-3">4. 其他配置</h2><div class="space-y-3" :class="state !== 'SAVE' ? 'opacity-40 pointer-events-none' : ''"><div v-for="field in otherFields" :key="field.key"><label class="block text-xs text-gray-400 mb-1">{{ field.prompt }}<span v-if="!field.optional" class="text-red-400">*</span><span v-if="field.key === 'API_KEY'" class="text-gray-500 text-[10px] ml-1">(留空自动生成)</span></label><inputv-model="form[field.key]":type="field.key.includes('PASSWORD') || field.key.includes('KEY') ? 'password' : 'text'":placeholder="field.default || ''"class="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-sm text-white" /></div></div></div>1 unmodified line<button@click="save":disabled="saving || state !== 'SAVE'"class="w-full px-4 py-2.5 bg-blue-600 hover:bg-blue-500 disabled:opacity-50 text-white text-sm font-medium rounded-lg transition">{{ saving ? '验证并保存中...' : '保存配置' }}</button></div>40 unmodified linesconst order = ['PROVIDER', 'CONNECTION', 'DOMAIN', 'SAVE']const cur = order.indexOf(state.value)const tgt = order.indexOf(targetState)if (tgt > cur) return 'bg-gray-800/20 border-gray-800'if (tgt < cur) return 'bg-green-900/10 border-green-900/40'return 'bg-blue-900/10 border-blue-700/40'}function onMailStateChange(s) {state.value = s}function onMailVerified(payload) {if (payload?.leakedProbe) {message.value = `⚠️ 探测邮箱回收失败,请到后台手动删除: ${payload.leakedProbe.email}`messageClass.value = 'bg-yellow-500/10 text-yellow-400 border-yellow-500/20'}}function onMailError(resp) {if (resp?.soft && resp.warnings) {message.value = '⚠️ ' + resp.warnings.join('; ')messageClass.value = 'bg-yellow-500/10 text-yellow-400 border-yellow-500/20'return}message.value = `${resp.error_code || 'ERROR'}: ${resp.message || '未知错误'}` +(resp.hint ? ` — ${resp.hint}` : '')messageClass.value = 'bg-red-500/10 text-red-400 border-red-500/20'}async function save() {3 unmodified linesconst result = await api.saveSetup({ ...form })if (result.api_key) setApiKey(result.api_key)message.value = result.message || '保存成功'messageClass.value = 'bg-green-500/10 text-green-400 border-green-500/20'setTimeout(() => emit('configured'), 1000)} catch (e) {message.value = e.messagemessageClass.value = 'bg-red-500/10 text-red-400 border-red-500/20'} finally {saving.value = false}11 unmodified linesif (result.provider) form.MAIL_PROVIDER = result.provider} catch (e) {message.value = '获取配置状态失败: ' + e.messagemessageClass.value = 'bg-red-500/10 text-red-400 border-red-500/20'}})</script>123456781 unmodified line101112131415161718192021222324252627282930313233343536371 unmodified line3940414243444540 unmodified lines86878889909192939495969798991001011021031041051061071081091101111121131141151161171181191203 unmodified lines12412512612712812913013113213313411 unmodified lines146147148149150151152<template><div class="min-h-screen flex items-center justify-center p-4"><div class="glass rounded-lg p-6 w-full max-w-2xl"><h1 class="text-xl font-bold text-ink-950 text-center mb-2">AutoTeam 初始配置</h1><p class="text-sm text-ink-500 text-center mb-6">首次使用请按步骤填写以下配置</p><div v-if="message" class="mb-4 px-4 py-3 rounded-lg text-sm border" :class="messageClass">{{ message }}1 unmodified line<!-- 卡片 1+2+3:Mail Provider 选择 / 连接 / 域名(Round 7 P2.2 抽 MailProviderCard) --><MailProviderCard:model-value="form"mode="setup"@update:model-value="updateMailForm"@state-change="onMailStateChange"@verified="onMailVerified"@error="onMailError" /><!-- 卡片 4:其他配置 --><div class="mb-4 p-4 rounded-lg border" :class="cardClass('SAVE')"><h2 class="text-sm font-semibold text-ink-950 mb-3">4. 其他配置</h2><div class="space-y-3" :class="state !== 'SAVE' ? 'opacity-40 pointer-events-none' : ''"><div v-for="field in otherFields" :key="field.key"><label class="block text-xs text-ink-600 mb-1">{{ field.prompt }}<span v-if="!field.optional" class="text-red-400">*</span><span v-if="field.key === 'API_KEY'" class="text-ink-500 text-[10px] ml-1">(留空自动生成)</span></label><inputv-model="form[field.key]":type="field.key.includes('PASSWORD') || field.key.includes('KEY') ? 'password' : 'text'":placeholder="field.default || ''"class="w-full px-3 py-2 bg-surface border border-hairline rounded text-sm text-ink-950 focus-ring" /></div></div></div>1 unmodified line<button@click="save":disabled="saving || state !== 'SAVE'"class="w-full px-4 py-2.5 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-on-accent text-sm font-medium rounded-lg transition focus-ring">{{ saving ? '验证并保存中...' : '保存配置' }}</button></div>40 unmodified linesconst order = ['PROVIDER', 'CONNECTION', 'DOMAIN', 'SAVE']const cur = order.indexOf(state.value)const tgt = order.indexOf(targetState)if (tgt > cur) return 'bg-ink-50 border-hairline'if (tgt < cur) return 'bg-emerald-50 border-emerald-200'return 'bg-indigo-50 border-indigo-200'}function onMailStateChange(s) {state.value = s}function updateMailForm(value) {Object.assign(form, value || {})}function onMailVerified(payload) {if (payload?.leakedProbe) {message.value = `提醒: 探测邮箱回收失败,请到后台手动删除: ${payload.leakedProbe.email}`messageClass.value = 'bg-amber-50 text-amber-800 border-amber-200'}}function onMailError(resp) {if (resp?.soft && resp.warnings) {message.value = '提醒: ' + resp.warnings.join('; ')messageClass.value = 'bg-amber-50 text-amber-800 border-amber-200'return}message.value = `${resp.error_code || 'ERROR'}: ${resp.message || '未知错误'}` +(resp.hint ? ` — ${resp.hint}` : '')messageClass.value = 'bg-rose-50 text-rose-700 border-rose-200'}async function save() {3 unmodified linesconst result = await api.saveSetup({ ...form })if (result.api_key) setApiKey(result.api_key)message.value = result.message || '保存成功'messageClass.value = 'bg-emerald-50 text-emerald-700 border-emerald-200'setTimeout(() => emit('configured'), 1000)} catch (e) {message.value = e.messagemessageClass.value = 'bg-rose-50 text-rose-700 border-rose-200'} finally {saving.value = false}11 unmodified linesif (result.provider) form.MAIL_PROVIDER = result.provider} catch (e) {message.value = '获取配置状态失败: ' + e.messagemessageClass.value = 'bg-rose-50 text-rose-700 border-rose-200'}})</script>
6 unmodified lines789101112132 unmodified lines161718192021222324252627281 unmodified line303132333435363738394041429 unmodified lines525354555657586 unmodified lines<div class="mb-8 px-2"><div class="flex items-center gap-2 mb-1"><span class="inline-block w-2 h-2 rounded-sm bg-gradient-to-br from-indigo-500 to-violet-600"></span><h1 class="text-lg font-extrabold text-ink-950 tracking-tight">AutoTeam</h1></div><p class="text-[10px] uppercase tracking-[0.2em] text-ink-400 ml-4">Operations Console</p>2 unmodified lines<div class="space-y-0.5 flex-1"><button v-for="item in items" :key="item.key"@click="$emit('navigate', item.key)"class="w-full text-left px-3 py-2 rounded-xl text-sm transition-all flex items-center gap-2.5relative group focus-ring":class="active === item.key? 'bg-indigo-50 text-indigo-700': 'text-ink-600 hover:bg-ink-100 hover:text-ink-950'"><span v-if="active === item.key" class="absolute left-0 top-2 bottom-2 w-0.5 rounded-r-fullbg-gradient-to-b from-indigo-500 to-violet-600"></span><component :is="item.icon" class="w-4 h-4 shrink-0" :stroke-width="2" /><span class="font-medium">{{ item.label }}</span></button>1 unmodified line<div class="space-y-0.5 pt-4 border-t border-hairline"><button @click="$emit('refresh')" :disabled="loading"class="w-full text-left px-3 py-2 rounded-xl text-sm transition flex items-center gap-2.5text-ink-600 hover:bg-ink-100 hover:text-ink-950 disabled:opacity-50 focus-ring"><RefreshCw class="w-4 h-4 shrink-0" :class="loading ? 'animate-spin' : ''" :stroke-width="2" /><span class="font-medium">{{ loading ? '刷新中…' : '刷新数据' }}</span></button><button v-if="authRequired" @click="$emit('logout')"class="w-full text-left px-3 py-2 rounded-xl text-sm transition flex items-center gap-2.5text-ink-600 hover:bg-rose-50 hover:text-rose-700 focus-ring"><LogOut class="w-4 h-4 shrink-0" :stroke-width="2" /><span class="font-medium">登出</span>9 unmodified linesclass="flex-1 flex flex-col items-center py-2 text-[10px] transition relative":class="active === item.key ? 'text-indigo-700' : 'text-ink-500 hover:text-ink-700'"><span v-if="active === item.key"class="absolute top-0 left-1/4 right-1/4 h-0.5 rounded-b-full bg-gradient-to-r from-indigo-500 to-violet-600"></span><component :is="item.icon" class="w-5 h-5" :stroke-width="2" /><span class="mt-0.5 font-medium">{{ item.mobileLabel || item.label }}</span></button>6 unmodified lines789101112132 unmodified lines161718192021222324252627281 unmodified line303132333435363738394041429 unmodified lines525354555657586 unmodified lines<div class="mb-8 px-2"><div class="flex items-center gap-2 mb-1"><span class="inline-block w-2 h-2 rounded-sm bg-indigo-600"></span><h1 class="text-lg font-extrabold text-ink-950 tracking-tight">AutoTeam</h1></div><p class="text-[10px] uppercase tracking-[0.2em] text-ink-400 ml-4">Operations Console</p>2 unmodified lines<div class="space-y-0.5 flex-1"><button v-for="item in items" :key="item.key"@click="$emit('navigate', item.key)"class="w-full text-left px-3 py-2 rounded-lg text-sm transition-all flex items-center gap-2.5relative group focus-ring":class="active === item.key? 'bg-indigo-50 text-indigo-700': 'text-ink-600 hover:bg-ink-100 hover:text-ink-950'"><span v-if="active === item.key" class="absolute left-0 top-2 bottom-2 w-0.5 rounded-r-fullbg-indigo-600"></span><component :is="item.icon" class="w-4 h-4 shrink-0" :stroke-width="2" /><span class="font-medium">{{ item.label }}</span></button>1 unmodified line<div class="space-y-0.5 pt-4 border-t border-hairline"><button @click="$emit('refresh')" :disabled="loading"class="w-full text-left px-3 py-2 rounded-lg text-sm transition flex items-center gap-2.5text-ink-600 hover:bg-ink-100 hover:text-ink-950 disabled:opacity-50 focus-ring"><RefreshCw class="w-4 h-4 shrink-0" :class="loading ? 'animate-spin' : ''" :stroke-width="2" /><span class="font-medium">{{ loading ? '刷新中…' : '刷新数据' }}</span></button><button v-if="authRequired" @click="$emit('logout')"class="w-full text-left px-3 py-2 rounded-lg text-sm transition flex items-center gap-2.5text-ink-600 hover:bg-rose-50 hover:text-rose-700 focus-ring"><LogOut class="w-4 h-4 shrink-0" :stroke-width="2" /><span class="font-medium">登出</span>9 unmodified linesclass="flex-1 flex flex-col items-center py-2 text-[10px] transition relative":class="active === item.key ? 'text-indigo-700' : 'text-ink-500 hover:text-ink-700'"><span v-if="active === item.key"class="absolute top-0 left-1/4 right-1/4 h-0.5 rounded-b-full bg-indigo-600"></span><component :is="item.icon" class="w-5 h-5" :stroke-width="2" /><span class="mt-0.5 font-medium">{{ item.mobileLabel || item.label }}</span></button>
50 unmodified lines515253545556574 unmodified lines6263646566676850 unmodified linesconst isGrace = computed(() => props.status === 'degraded_grace')const remainText = computed(() => (isGrace.value ? formatGraceRemain(props.graceUntil) : ''))const graceDate = computed(() => formatGraceDate(props.graceUntil))const urgencyClass = computed(() => `${graceUrgencyClass(props.graceUntil)} bg-black/30`)const isGraceUrgent = computed(() => {if (!isGrace.value) return falseconst ms = graceRemainMs(props.graceUntil)4 unmodified linesconst bgStyle = computed(() => {const map = {active: 'linear-gradient(135deg, rgba(52, 211, 153, 0.20) 0%, rgba(20, 184, 166, 0.12) 100%)',personal: 'linear-gradient(135deg, rgba(167, 139, 250, 0.22) 0%, rgba(217, 70, 239, 0.14) 100%)',standby: 'linear-gradient(135deg, rgba(251, 191, 36, 0.18) 0%, rgba(245, 158, 11, 0.10) 100%)',degraded_grace: 'linear-gradient(135deg, rgba(251, 191, 36, 0.25) 0%, rgba(249, 115, 22, 0.22) 50%, rgba(244, 63, 94, 0.20) 100%)',auth_invalid: 'linear-gradient(135deg, rgba(244, 63, 94, 0.18) 0%, rgba(239, 68, 68, 0.12) 100%)',50 unmodified lines515253545556574 unmodified lines626364656667686950 unmodified linesconst isGrace = computed(() => props.status === 'degraded_grace')const remainText = computed(() => (isGrace.value ? formatGraceRemain(props.graceUntil) : ''))const graceDate = computed(() => formatGraceDate(props.graceUntil))const urgencyClass = computed(() => `${graceUrgencyClass(props.graceUntil)} bg-surface border border-hairline`)const isGraceUrgent = computed(() => {if (!isGrace.value) return falseconst ms = graceRemainMs(props.graceUntil)4 unmodified linesconst bgStyle = computed(() => {const map = {active: 'linear-gradient(135deg, rgba(52, 211, 153, 0.20) 0%, rgba(20, 184, 166, 0.12) 100%)',personal: 'linear-gradient(135deg, rgba(56, 189, 248, 0.20) 0%, rgba(59, 130, 246, 0.12) 100%)',disabled: 'linear-gradient(135deg, rgba(214, 211, 209, 0.70) 0%, rgba(241, 245, 249, 0.60) 100%)',standby: 'linear-gradient(135deg, rgba(251, 191, 36, 0.18) 0%, rgba(245, 158, 11, 0.10) 100%)',degraded_grace: 'linear-gradient(135deg, rgba(251, 191, 36, 0.25) 0%, rgba(249, 115, 22, 0.22) 50%, rgba(244, 63, 94, 0.20) 100%)',auth_invalid: 'linear-gradient(135deg, rgba(244, 63, 94, 0.18) 0%, rgba(239, 68, 68, 0.12) 100%)',
12345678910111213146 unmodified lines212223242526<template><div class="space-y-5"><div><div class="text-[10px] uppercase tracking-[0.3em] text-indigo-300/70 mb-1">Sync Center</div><h2 class="text-2xl font-extrabold text-white tracking-tight">同步中心</h2><p class="text-sm text-gray-400 mt-1">本地账号池对账、同步到 CPA、从 CPA 反向拉取认证文件。</p></div><TaskPanelmode="sync":running-task="runningTask":admin-status="adminStatus"@task-started="$emit('task-started')"@refresh="$emit('refresh')"/>6 unmodified linesdefineProps({runningTask: Object,adminStatus: Object,})defineEmits(['task-started', 'refresh'])1234567891011121314156 unmodified lines22232425262728<template><div class="space-y-5"><div><div class="text-[10px] uppercase tracking-[0.3em] text-indigo-700 mb-1">Sync Center</div><h2 class="text-2xl font-extrabold text-ink-950 tracking-tight">同步中心</h2><p class="text-sm text-ink-500 mt-1">本地账号池对账、同步到 CPA、从 CPA 反向拉取认证文件。</p></div><TaskPanelmode="sync":running-task="runningTask":admin-status="adminStatus":rotate-stream="rotateStream"@task-started="$emit('task-started')"@refresh="$emit('refresh')"/>6 unmodified linesdefineProps({runningTask: Object,adminStatus: Object,rotateStream: { type: Object, default: null },})defineEmits(['task-started', 'refresh'])
12345673 unmodified lines111213141516174 unmodified lines2223242526272829303132333435361 unmodified line3839404142434445464 unmodified lines51525354555657585960616263646566676869707172737475<template><div class="mt-6 bg-gray-900 border border-gray-800 rounded-xl overflow-hidden"><div class="px-4 py-3 border-b border-gray-800"><h2 class="text-lg font-semibold text-white">任务历史</h2></div><div v-if="tasks.length === 0" class="px-4 py-8 text-center text-gray-500 text-sm">3 unmodified lines<div v-else class="overflow-x-auto"><table class="w-full text-sm"><thead><tr class="text-gray-400 text-left border-b border-gray-800"><th class="px-4 py-3 font-medium">任务 ID</th><th class="px-4 py-3 font-medium">命令</th><th class="px-4 py-3 font-medium">参数</th>4 unmodified lines</tr></thead><tbody><tr v-for="task in tasks" :key="task.task_id"class="border-b border-gray-800/50 hover:bg-gray-800/30 transition"><td class="px-4 py-3 font-mono text-xs text-gray-400">{{ task.task_id }}</td><td class="px-4 py-3"><span class="px-2 py-0.5 bg-gray-800 rounded text-xs font-medium text-gray-300">{{ task.command }}</span></td><td class="px-4 py-3 text-xs text-gray-400">{{ formatParams(task.params) }}</td><td class="px-4 py-3"><span class="inline-flex items-center gap-1.5 text-xs font-medium" :class="taskStatusClass(task.status)"><span v-if="task.status === 'running'" class="animate-spin inline-block w-3 h-3 border-2 border-current border-t-transparent rounded-full"></span>1 unmodified line{{ taskStatusLabel(task.status) }}</span></td><td class="px-4 py-3 text-xs text-gray-400">{{ formatTime(task.created_at) }}</td><td class="px-4 py-3 text-xs text-gray-400">{{ duration(task) }}</td><td class="px-4 py-3 text-xs max-w-xs truncate" :class="task.error ? 'text-red-400' : 'text-gray-400'">{{ task.error || formatResult(task.result) }}</td></tr>4 unmodified lines</template><script setup>defineProps({tasks: { type: Array, default: () => [] },})function taskStatusClass(s) {return {pending: 'text-gray-400',running: 'text-yellow-400',completed: 'text-green-400',failed: 'text-red-400',}[s] || 'text-gray-400'}function taskDotClass(s) {return {pending: 'bg-gray-400',completed: 'bg-green-400',failed: 'bg-red-400',}[s] || 'bg-gray-400'}function taskStatusLabel(s) {123456789103 unmodified lines141516171819204 unmodified lines2526272829303132333435363738391 unmodified line4142434445464748494 unmodified lines545556575859606162636465666768697071727374757677787980818283<template><div class="mt-6 glass rounded-lg overflow-hidden"><div class="px-4 py-3 border-b border-hairline"><h2 class="text-lg font-semibold text-ink-950">任务历史</h2><p v-if="hiddenTaskCount" class="text-xs text-ink-500 mt-1">仅显示最新 {{ visibleTasks.length }} 条,已隐藏 {{ hiddenTaskCount }} 条较早记录。</p></div><div v-if="tasks.length === 0" class="px-4 py-8 text-center text-gray-500 text-sm">3 unmodified lines<div v-else class="overflow-x-auto"><table class="w-full text-sm"><thead><tr class="text-ink-500 text-left border-b border-hairline"><th class="px-4 py-3 font-medium">任务 ID</th><th class="px-4 py-3 font-medium">命令</th><th class="px-4 py-3 font-medium">参数</th>4 unmodified lines</tr></thead><tbody><tr v-for="task in visibleTasks" :key="task.task_id"class="border-b border-hairline hover:bg-ink-50 transition"><td class="px-4 py-3 font-mono text-xs text-ink-500">{{ task.task_id }}</td><td class="px-4 py-3"><span class="px-2 py-0.5 bg-ink-50 rounded text-xs font-medium text-ink-700 border border-hairline">{{ task.command }}</span></td><td class="px-4 py-3 text-xs text-ink-500">{{ formatParams(task.params) }}</td><td class="px-4 py-3"><span class="inline-flex items-center gap-1.5 text-xs font-medium" :class="taskStatusClass(task.status)"><span v-if="task.status === 'running'" class="animate-spin inline-block w-3 h-3 border-2 border-current border-t-transparent rounded-full"></span>1 unmodified line{{ taskStatusLabel(task.status) }}</span></td><td class="px-4 py-3 text-xs text-ink-500">{{ formatTime(task.created_at) }}</td><td class="px-4 py-3 text-xs text-ink-500">{{ duration(task) }}</td><td class="px-4 py-3 text-xs max-w-xs truncate" :class="task.error ? 'text-rose-700' : 'text-ink-500'">{{ task.error || formatResult(task.result) }}</td></tr>4 unmodified lines</template><script setup>import { computed } from 'vue'const props = defineProps({tasks: { type: Array, default: () => [] },})const visibleTasks = computed(() => props.tasks.slice(0, 200))const hiddenTaskCount = computed(() => Math.max(0, props.tasks.length - visibleTasks.value.length))function taskStatusClass(s) {return {pending: 'text-ink-500',running: 'text-amber-700',completed: 'text-emerald-700',failed: 'text-rose-700',}[s] || 'text-ink-500'}function taskDotClass(s) {return {pending: 'bg-ink-400',completed: 'bg-emerald-500',failed: 'bg-rose-500',}[s] || 'bg-ink-400'}function taskStatusLabel(s) {
1234567<template><div><h2 class="text-xl font-bold text-white mb-2">任务历史</h2><p class="text-sm text-gray-400 mb-6">查看后台任务的执行状态、耗时、参数和结果,便于排查失败原因。</p><TaskHistory :tasks="tasks" />1234567<template><div><h2 class="text-xl font-bold text-ink-950 mb-2">任务历史</h2><p class="text-sm text-ink-500 mb-6">查看后台任务的执行状态、耗时、参数和结果,便于排查失败原因。</p><TaskHistory :tasks="tasks" />
12345678910111213141 unmodified line161718192021222 unmodified lines25262728293031323334353637383940414243444532 unmodified lines7879808182838485868788899091929394959697989910010110210310410510610719 unmodified lines1271281291301311321332 unmodified lines13613713813914014114214314414514614714830 unmodified lines1791801811821831841851866 unmodified lines19319419519619719819 unmodified lines21821922022122222322422522622763 unmodified lines29129229329429529629729829930030130230330430530630730830929 unmodified lines339340341342343344345346347348349350351352353354355356357358359<template><div class="glass rounded-2xl p-5"><div class="flex items-center justify-between mb-4 gap-3 flex-wrap"><div><h2 class="text-base font-bold text-white tracking-tight">{{ panelTitle }}</h2><p class="text-[11px] text-gray-500 mt-0.5">点击按钮提交后台任务,轮询返回结果</p></div><div v-if="runningTask" class="flex items-center gap-2 text-xs"><span class="text-gray-500 uppercase tracking-widest text-[10px]">Running</span><span class="font-mono text-amber-300 px-2 py-0.5 rounded bg-amber-500/10 border border-amber-500/30">{{ runningTask.command }}</span><span class="font-mono text-gray-600">{{ runningTask.task_id ? runningTask.task_id.slice(0, 8) : '' }}</span><AtButton variant="danger" size="sm" :loading="cancelling" :disabled="cancelRequested" @click="cancelTask">{{ cancelRequested ? '停止中…' : '停止任务' }}</AtButton>1 unmodified line</div><div v-if="showAdminHint"class="mb-4 px-4 py-2.5 rounded-xl text-sm border bg-amber-500/10 text-amber-300 border-amber-500/30">{{ adminHint }}</div>2 unmodified lines<button v-for="action in visibleActions" :key="action.key"@click="execute(action)":disabled="isDisabled(action)"class="relative h-10 px-4 rounded-xl text-sm font-semibold border transition-alllift-hover focus-ring select-none whitespace-nowrapdisabled:opacity-50 disabled:cursor-not-allowed disabled:bg-ink-100 disabled:text-ink-400 disabled:border-hairline":class="actionColorClass(action)"><span class="inline-flex items-center gap-2"><component :is="action.icon" class="w-4 h-4 shrink-0" :stroke-width="2" />{{ action.label }}</span></button></div><!-- round-12 F2 — rotate 实时进度面板 (SSE) --><div class="mt-4 rounded-xl border border-hairline bg-surface"><button type="button"class="w-full flex items-center justify-between gap-3 px-4 py-2.5 text-sm focus-ring rounded-xl"@click="showProgress = !showProgress"><span class="inline-flex items-center gap-2 font-semibold text-ink-700"><Activity class="w-4 h-4" :class="rotateStream.isConnected.value ? 'text-emerald-600' : 'text-ink-400'" :stroke-width="2" />32 unmodified lines<!-- 注册域名切换(仅 pool 模式可见) --><div v-if="mode === 'pool'"class="mt-5 p-3 rounded-xl border border-white/[0.04] bg-white/[0.02] flex flex-wrap items-center gap-2 text-sm"><span class="text-[10px] uppercase tracking-widest text-gray-500 font-semibold mr-1">注册域名</span><span class="text-gray-600">@</span><input v-model="domainInput" type="text" placeholder="your-domain.com"class="flex-1 min-w-[180px] px-3 py-1.5 bg-black/30 border border-white/10 rounded-lg text-white text-sm font-mono focus-ring focus:border-indigo-400/40 transition" /><AtButton variant="primary" size="sm" :loading="domainBusy" :disabled="!domainInput" @click="saveDomain">保存并验证</AtButton><span v-if="currentDomain" class="text-[11px] text-gray-500 font-mono">当前: @{{ currentDomain }}</span><span v-if="domainMsg" class="ml-1 text-[11px] font-medium" :class="domainMsgOk ? 'text-emerald-300' : 'text-rose-300'">{{ domainMsg }}</span></div><!-- 参数输入 --><div v-if="showParams"class="mt-4 p-3 rounded-xl border border-indigo-500/30 bg-indigo-500/5 flex items-center gap-3 animate-rise"><label class="text-[11px] uppercase tracking-widest text-indigo-300 font-semibold">{{ paramLabel }}</label><input v-model.number="paramValue" type="number" min="1" :max="paramMax"class="w-24 px-3 py-1.5 bg-black/30 border border-white/10 rounded-lg text-white text-sm font-mono focus-ring focus:border-indigo-400/40 tabular" /><AtButton variant="primary" size="sm" @click="confirmAction">确认执行</AtButton><AtButton variant="ghost" size="sm" @click="showParams = false">取消</AtButton></div><!-- 结果提示 --><div v-if="message" class="mt-4 px-4 py-2.5 rounded-xl text-sm border animate-rise" :class="messageClass">{{ message }}</div></div>19 unmodified lines} from 'lucide-vue-next'import { api } from '../api.js'import AtButton from './AtButton.vue'import { useStatusInvalidator } from '../composables/useStatus.js'import { statusLabel } from '../composables/useStatus.js'const props = defineProps({2 unmodified linesmode: { type: String, default: 'all' },// Round 8 — 母号订阅健康度,degraded 时禁用 fill-personalmasterHealth: { type: Object, default: null },})const emit = defineEmits(['task-started', 'refresh'])// round-12 F2/F3 — SSE 实时进度 + vue-query invalidation// useStatusInvalidator 内部:SSE 事件 → invalidateQueries(['status'])// 它返回 useRotateStream 的 reactive ref,模板里直接 v-for eventsconst rotateStream = useStatusInvalidator()const showProgress = ref(false)function transitionIcon(ev) {30 unmodified linesconst actions = [{ key: 'rotate', group: 'pool', label: '智能轮转', icon: RotateCw, method: 'startRotate', needParam: true, paramName: 'target', tone: 'primary' },{ key: 'check', group: 'pool', label: '检查额度', icon: ChartPie, method: 'startCheck', needParam: false, tone: 'emerald' },{ key: 'fill', group: 'pool', label: '补满成员', icon: Plus, method: 'startFill', needParam: true, paramName: 'target', tone: 'violet' },{ key: 'fill-personal', group: 'pool', label: '生成免费号', icon: Coins, method: 'startFillPersonal', needParam: true, paramName: 'count', tone: 'fuchsia' },{ key: 'add', group: 'pool', label: '添加账号', icon: UserPlus, method: 'startAdd', needParam: false, tone: 'amber' },{ key: 'cleanup', group: 'pool', label: '清理成员', icon: Brush, method: 'startCleanup', needParam: false, tone: 'rose' },{ key: 'sync', group: 'sync', label: '同步 CPA', icon: RefreshCw, method: 'postSync', needParam: false, sync: true, allowWithoutAdmin: true, tone: 'cyan' },6 unmodified linesconst paramValue = ref(5)const paramMax = ref(20)const pendingAction = ref(null)const cancelling = ref(false)const cancelRequested = ref(false)19 unmodified linesconst r = await api.cancelTask()cancelRequested.value = truemessage.value = r.message || '已请求停止'messageClass.value = 'bg-amber-500/10 text-amber-300 border-amber-500/30'} catch (e) {message.value = `停���失败: ${e.message}`messageClass.value = 'bg-rose-500/10 text-rose-300 border-rose-500/30'} finally {cancelling.value = falsesetTimeout(() => { if (messageClass.value.includes('amber')) message.value = '' }, 10000)63 unmodified lines))function isDisabled(action) {if (props.runningTask) return trueif (!adminReady.value && !action.allowWithoutAdmin) return trueif (action.key === 'fill-personal' && masterDegraded.value) return truereturn false}// 按 tone 给按钮配色 — round-12 F1 Bright v1function actionColorClass(action) {const map = {primary: 'text-indigo-700 bg-indigo-50 border-indigo-200 hover:bg-indigo-100 hover:border-indigo-300',emerald: 'text-emerald-700 bg-emerald-50 border-emerald-200 hover:bg-emerald-100',violet: 'text-violet-700 bg-violet-50 border-violet-200 hover:bg-violet-100',fuchsia: 'text-fuchsia-700 bg-fuchsia-50 border-fuchsia-200 hover:bg-fuchsia-100',amber: 'text-amber-800 bg-amber-50 border-amber-200 hover:bg-amber-100',rose: 'text-rose-700 bg-rose-50 border-rose-200 hover:bg-rose-100',cyan: 'text-cyan-700 bg-cyan-50 border-cyan-200 hover:bg-cyan-100',29 unmodified lines}async function doExecute(action, param) {try {if (action.sync) {const result = await api[action.method]()message.value = result.message || '操作完成'messageClass.value = 'bg-emerald-500/10 text-emerald-300 border-emerald-500/30'emit('refresh')} else {const result = await api[action.method](param)message.value = `任务已提交: ${result.task_id}`messageClass.value = 'bg-blue-500/10 text-blue-300 border-blue-500/30'emit('task-started')}} catch (e) {message.value = e.messagemessageClass.value = 'bg-rose-500/10 text-rose-300 border-rose-500/30'}setTimeout(() => { message.value = '' }, 8000)}12345678910111213141 unmodified line161718192021222 unmodified lines2526272829303132333435363738394041424344454632 unmodified lines79808182838485868788899091929394959697989910010110210310410510610710819 unmodified lines1281291301311321331342 unmodified lines13713813914014114214314414514614714814930 unmodified lines1801811821831841851861876 unmodified lines19419519619719819920019 unmodified lines22022122222322422522622722822923063 unmodified lines29429529629729829930030130230330430530630730830931031131231331431531631729 unmodified lines347348349350351352353354355356357358359360361362363364365366367368369370<template><div class="glass rounded-lg p-5"><div class="flex items-center justify-between mb-4 gap-3 flex-wrap"><div><h2 class="text-base font-bold text-ink-950 tracking-tight">{{ panelTitle }}</h2><p class="text-[11px] text-ink-500 mt-0.5">提交后立即进入后台任务观察窗口,完成后自动同步状态。</p></div><div v-if="runningTask" class="flex items-center gap-2 text-xs"><span class="text-ink-500 uppercase tracking-widest text-[10px]">Running</span><span class="font-mono text-amber-800 px-2 py-0.5 rounded bg-amber-50 border border-amber-200">{{ runningTask.command }}</span><span class="font-mono text-ink-600">{{ runningTask.task_id ? runningTask.task_id.slice(0, 8) : '' }}</span><AtButton variant="danger" size="sm" :loading="cancelling" :disabled="cancelRequested" @click="cancelTask">{{ cancelRequested ? '停止中…' : '停止任务' }}</AtButton>1 unmodified line</div><div v-if="showAdminHint"class="mb-4 px-4 py-2.5 rounded-lg text-sm border bg-amber-50 text-amber-800 border-amber-200">{{ adminHint }}</div>2 unmodified lines<button v-for="action in visibleActions" :key="action.key"@click="execute(action)":disabled="isDisabled(action)"class="relative h-10 px-4 rounded-lg text-sm font-semibold border transition-alllift-hover focus-ring select-none whitespace-nowrapdisabled:opacity-50 disabled:cursor-not-allowed disabled:bg-ink-100 disabled:text-ink-400 disabled:border-hairline":class="actionColorClass(action)"><span class="inline-flex items-center gap-2"><span v-if="isSubmitting(action)" class="inline-block w-4 h-4 rounded-full border-2 border-current border-t-transparent animate-spin"></span><component v-else :is="action.icon" class="w-4 h-4 shrink-0" :stroke-width="2" />{{ isSubmitting(action) ? '提交中' : action.label }}</span></button></div><!-- round-12 F2 — rotate 实时进度面板 (SSE) --><div class="mt-4 rounded-lg border border-hairline bg-surface"><button type="button"class="w-full flex items-center justify-between gap-3 px-4 py-2.5 text-sm focus-ring rounded-lg"@click="showProgress = !showProgress"><span class="inline-flex items-center gap-2 font-semibold text-ink-700"><Activity class="w-4 h-4" :class="rotateStream.isConnected.value ? 'text-emerald-600' : 'text-ink-400'" :stroke-width="2" />32 unmodified lines<!-- 注册域名切换(仅 pool 模式可见) --><div v-if="mode === 'pool'"class="mt-5 p-3 rounded-lg border border-hairline bg-ink-50 flex flex-wrap items-center gap-2 text-sm"><span class="text-[10px] uppercase tracking-widest text-ink-500 font-semibold mr-1">注册域名</span><span class="text-ink-400">@</span><input v-model="domainInput" type="text" placeholder="your-domain.com"class="flex-1 min-w-[180px] px-3 py-1.5 bg-surface border border-hairline rounded-lg text-ink-950 text-sm font-mono focus-ring transition" /><AtButton variant="primary" size="sm" :loading="domainBusy" :disabled="!domainInput" @click="saveDomain">保存并验证</AtButton><span v-if="currentDomain" class="text-[11px] text-ink-500 font-mono">当前: @{{ currentDomain }}</span><span v-if="domainMsg" class="ml-1 text-[11px] font-medium" :class="domainMsgOk ? 'text-emerald-700' : 'text-rose-700'">{{ domainMsg }}</span></div><!-- 参数输入 --><div v-if="showParams"class="mt-4 p-3 rounded-lg border border-indigo-200 bg-indigo-50 flex items-center gap-3 animate-rise"><label class="text-[11px] uppercase tracking-widest text-indigo-700 font-semibold">{{ paramLabel }}</label><input v-model.number="paramValue" type="number" min="1" :max="paramMax"class="w-24 px-3 py-1.5 bg-surface border border-hairline rounded-lg text-ink-950 text-sm font-mono focus-ring tabular" /><AtButton variant="primary" size="sm" :loading="!!executingActionKey" @click="confirmAction">确认执行</AtButton><AtButton variant="ghost" size="sm" @click="showParams = false">取消</AtButton></div><!-- 结果提示 --><div v-if="message" class="mt-4 px-4 py-2.5 rounded-lg text-sm border animate-rise" :class="messageClass">{{ message }}</div></div>19 unmodified lines} from 'lucide-vue-next'import { api } from '../api.js'import AtButton from './AtButton.vue'import { useRotateStream } from '../composables/useRotateStream.js'import { statusLabel } from '../composables/useStatus.js'const props = defineProps({2 unmodified linesmode: { type: String, default: 'all' },// Round 8 — 母号订阅健康度,degraded 时禁用 fill-personalmasterHealth: { type: Object, default: null },rotateStream: { type: Object, default: null },})const emit = defineEmits(['task-started', 'refresh'])// round-12 F2/F3 — 共享 SSE 流直接用于实时进度展示;// App 级状态层负责统一 invalidation,这里不再额外挂一层桥接。const rotateStream = props.rotateStream || useRotateStream()const showProgress = ref(false)function transitionIcon(ev) {30 unmodified linesconst actions = [{ key: 'rotate', group: 'pool', label: '智能轮转', icon: RotateCw, method: 'startRotate', needParam: true, paramName: 'target', tone: 'primary' },{ key: 'check', group: 'pool', label: '检查额度', icon: ChartPie, method: 'startCheck', needParam: false, tone: 'emerald' },{ key: 'fill', group: 'pool', label: '补满成员', icon: Plus, method: 'startFill', needParam: true, paramName: 'target', tone: 'teal' },{ key: 'fill-personal', group: 'pool', label: '生成免费号', icon: Coins, method: 'startFillPersonal', needParam: true, paramName: 'count', tone: 'lime' },{ key: 'add', group: 'pool', label: '添加账号', icon: UserPlus, method: 'startAdd', needParam: false, tone: 'amber' },{ key: 'cleanup', group: 'pool', label: '清理成员', icon: Brush, method: 'startCleanup', needParam: false, tone: 'rose' },{ key: 'sync', group: 'sync', label: '同步 CPA', icon: RefreshCw, method: 'postSync', needParam: false, sync: true, allowWithoutAdmin: true, tone: 'cyan' },6 unmodified linesconst paramValue = ref(5)const paramMax = ref(20)const pendingAction = ref(null)const executingActionKey = ref('')const cancelling = ref(false)const cancelRequested = ref(false)19 unmodified linesconst r = await api.cancelTask()cancelRequested.value = truemessage.value = r.message || '已请求停止'messageClass.value = 'bg-amber-50 text-amber-800 border-amber-200'emit('refresh')} catch (e) {message.value = `停���失败: ${e.message}`messageClass.value = 'bg-rose-50 text-rose-700 border-rose-200'} finally {cancelling.value = falsesetTimeout(() => { if (messageClass.value.includes('amber')) message.value = '' }, 10000)63 unmodified lines))function isDisabled(action) {if (executingActionKey.value) return trueif (props.runningTask) return trueif (!adminReady.value && !action.allowWithoutAdmin) return trueif (action.key === 'fill-personal' && masterDegraded.value) return truereturn false}function isSubmitting(action) {return executingActionKey.value === action.key}// 按 tone 给按钮配色 — round-12 F1 Bright v1function actionColorClass(action) {const map = {primary: 'text-indigo-700 bg-indigo-50 border-indigo-200 hover:bg-indigo-100 hover:border-indigo-300',emerald: 'text-emerald-700 bg-emerald-50 border-emerald-200 hover:bg-emerald-100',teal: 'text-teal-700 bg-teal-50 border-teal-200 hover:bg-teal-100',lime: 'text-lime-700 bg-lime-50 border-lime-200 hover:bg-lime-100',amber: 'text-amber-800 bg-amber-50 border-amber-200 hover:bg-amber-100',rose: 'text-rose-700 bg-rose-50 border-rose-200 hover:bg-rose-100',cyan: 'text-cyan-700 bg-cyan-50 border-cyan-200 hover:bg-cyan-100',29 unmodified lines}async function doExecute(action, param) {executingActionKey.value = action.keytry {if (action.sync) {const result = await api[action.method]()message.value = result.message || '操作完成'messageClass.value = 'bg-emerald-50 text-emerald-700 border-emerald-200'emit('refresh')} else {const result = await api[action.method](param)message.value = `任务已提交: ${result.task_id}`messageClass.value = 'bg-sky-50 text-sky-700 border-sky-200'emit('task-started')}} catch (e) {message.value = e.messagemessageClass.value = 'bg-rose-50 text-rose-700 border-rose-200'} finally {executingActionKey.value = ''}setTimeout(() => { message.value = '' }, 8000)}
123456<template><div><h2 class="text-xl font-bold text-white mb-6">操作 & 任务</h2><TaskPanel :running-task="runningTask" :admin-status="adminStatus" @task-started="$emit('task-started')" @refresh="$emit('refresh')" /><TaskHistory :tasks="tasks" /></div>123456<template><div><h2 class="text-xl font-bold text-ink-950 mb-6">操作 & 任务</h2><TaskPanel :running-task="runningTask" :admin-status="adminStatus" @task-started="$emit('task-started')" @refresh="$emit('refresh')" /><TaskHistory :tasks="tasks" /></div>
1234567891011121314151617181920212223242526272829304 unmodified lines3536373839404142434445464748495051525354555657585960614 unmodified lines66676869707172736 unmodified lines80818283848586878889<template><div><div class="flex items-center justify-between mb-6"><h2 class="text-xl font-bold text-white">Team 成员</h2><button @click="fetchMembers" :disabled="loading"class="px-3 py-1.5 bg-gray-800 hover:bg-gray-700 text-sm rounded-lg border border-gray-700 transition disabled:opacity-50">{{ loading ? '加载中...' : '刷新' }}</button></div><div v-if="error" class="mb-4 px-4 py-3 rounded-lg text-sm bg-red-500/10 text-red-400 border border-red-500/20">{{ error }}</div><div v-if="data" class="space-y-4"><!-- 统计 --><div class="flex gap-4 text-sm"><span class="px-3 py-1.5 bg-gray-800 rounded-lg text-gray-300">成员: <span class="text-white font-medium">{{ data.total }}</span></span><span v-if="data.invites > 0" class="px-3 py-1.5 bg-gray-800 rounded-lg text-gray-300">待接受邀请: <span class="text-yellow-400 font-medium">{{ data.invites }}</span></span></div><!-- 成员表格 --><div class="bg-gray-900 border border-gray-800 rounded-xl overflow-hidden"><div class="overflow-x-auto"><table class="w-full text-sm"><thead><tr class="text-gray-400 text-left border-b border-gray-800"><th class="px-4 py-3 font-medium">#</th><th class="px-4 py-3 font-medium">邮箱</th><th class="px-4 py-3 font-medium">角色</th>4 unmodified lines</thead><tbody><tr v-for="(m, i) in data.members" :key="m.email + m.type"class="border-b border-gray-800/50 hover:bg-gray-800/30 transition"><td class="px-4 py-3 text-gray-500">{{ i + 1 }}</td><td class="px-4 py-3 font-mono text-xs">{{ m.email }}</td><td class="px-4 py-3"><span class="px-2 py-0.5 rounded text-xs font-medium":class="{'bg-purple-500/10 text-purple-400': m.role === 'account-owner','bg-blue-500/10 text-blue-400': m.role === 'account-admin','bg-gray-500/10 text-gray-300': m.role !== 'account-owner' && m.role !== 'account-admin',}">{{ m.role || 'member' }}</span></td><td class="px-4 py-3"><span class="px-2 py-0.5 rounded text-xs font-medium":class="m.type === 'invite' ? 'bg-yellow-500/10 text-yellow-400' : 'bg-green-500/10 text-green-400'">{{ m.type === 'invite' ? '待接受' : '已加入' }}</span></td><td class="px-4 py-3"><span class="text-xs" :class="m.is_local ? 'text-blue-400' : 'text-gray-500'">{{ m.is_local ? '本地管理' : '外部' }}</span></td>4 unmodified lines:disabled="removingId === memberKey(m)"class="px-3 py-1.5 rounded-lg text-xs font-medium border transition":class="removingId === memberKey(m)? 'bg-gray-800 text-gray-500 border-gray-700 cursor-not-allowed': 'bg-rose-600/10 text-rose-400 border-rose-500/30 hover:bg-rose-600/20'">{{ removingId === memberKey(m) ? '处理中...' : '移出' }}</button>6 unmodified lines</div><!-- Loading --><div v-else-if="loading" class="bg-gray-900 border border-gray-800 rounded-xl h-64 animate-pulse"></div><!-- Empty --><div v-else class="text-center text-gray-500 py-12">点击「刷新」加载 Team 成员列表</div></div>1234567891011121314151617181920212223242526272829304 unmodified lines3536373839404142434445464748495051525354555657585960614 unmodified lines66676869707172736 unmodified lines80818283848586878889<template><div><div class="flex items-center justify-between mb-6"><h2 class="text-xl font-bold text-ink-950">Team 成员</h2><button @click="fetchMembers" :disabled="loading"class="px-3 py-1.5 bg-surface hover:bg-ink-100 text-sm rounded-lg border border-hairline transition disabled:opacity-50 focus-ring text-ink-700">{{ loading ? '加载中...' : '刷新' }}</button></div><div v-if="error" class="mb-4 px-4 py-3 rounded-lg text-sm bg-rose-50 text-rose-700 border border-rose-200">{{ error }}</div><div v-if="data" class="space-y-4"><!-- 统计 --><div class="flex gap-4 text-sm"><span class="px-3 py-1.5 bg-ink-50 rounded-lg text-ink-600 border border-hairline">成员: <span class="text-ink-950 font-medium">{{ data.total }}</span></span><span v-if="data.invites > 0" class="px-3 py-1.5 bg-amber-50 rounded-lg text-amber-800 border border-amber-200">待接受邀请: <span class="font-medium">{{ data.invites }}</span></span></div><!-- 成员表格 --><div class="glass rounded-lg overflow-hidden"><div class="overflow-x-auto"><table class="w-full text-sm"><thead><tr class="text-ink-500 text-left border-b border-hairline"><th class="px-4 py-3 font-medium">#</th><th class="px-4 py-3 font-medium">邮箱</th><th class="px-4 py-3 font-medium">角色</th>4 unmodified lines</thead><tbody><tr v-for="(m, i) in data.members" :key="m.email + m.type"class="border-b border-hairline hover:bg-ink-50 transition"><td class="px-4 py-3 text-ink-500">{{ i + 1 }}</td><td class="px-4 py-3 font-mono text-xs">{{ m.email }}</td><td class="px-4 py-3"><span class="px-2 py-0.5 rounded text-xs font-medium":class="{'bg-indigo-50 text-indigo-700': m.role === 'account-owner','bg-sky-50 text-sky-700': m.role === 'account-admin','bg-ink-50 text-ink-600': m.role !== 'account-owner' && m.role !== 'account-admin',}">{{ m.role || 'member' }}</span></td><td class="px-4 py-3"><span class="px-2 py-0.5 rounded text-xs font-medium":class="m.type === 'invite' ? 'bg-amber-50 text-amber-700' : 'bg-emerald-50 text-emerald-700'">{{ m.type === 'invite' ? '待接受' : '已加入' }}</span></td><td class="px-4 py-3"><span class="text-xs" :class="m.is_local ? 'text-sky-700' : 'text-ink-500'">{{ m.is_local ? '本地管理' : '外部' }}</span></td>4 unmodified lines:disabled="removingId === memberKey(m)"class="px-3 py-1.5 rounded-lg text-xs font-medium border transition":class="removingId === memberKey(m)? 'bg-ink-100 text-ink-400 border-hairline cursor-not-allowed': 'bg-rose-50 text-rose-700 border-rose-200 hover:bg-rose-100'">{{ removingId === memberKey(m) ? '处理中...' : '移出' }}</button>6 unmodified lines</div><!-- Loading --><div v-else-if="loading" class="glass-soft rounded-lg h-64 shimmer-bg"></div><!-- Empty --><div v-else class="text-center text-ink-500 py-12">点击「刷新」加载 Team 成员列表</div></div>
4 unmodified lines567891011121314151617186 unmodified lines25262728293031323334353637383940414243444546474 unmodified lines<div class="fixed top-3 right-3 z-[100] space-y-2 max-w-sm pointer-events-none"><transition-group tag="div" class="space-y-2"><div v-for="t in state.items" :key="t.id"class="pointer-events-auto rounded-xl border backdrop-blur-md shadow-2xl px-4 py-3 flex items-start gap-3":class="[toneClass(t.tone), t.leaving ? 'animate-toast-out' : 'animate-toast-in']"@click="dismiss(t.id)"><span class="shrink-0 mt-0.5"><svg v-if="t.tone === 'success'" viewBox="0 0 16 16" class="w-4 h-4 text-emerald-300"><path fill="currentColor" d="M6.5 11.4L3.6 8.5l1.1-1.1 1.8 1.8L11.3 4l1.1 1.1z"/></svg><svg v-else-if="t.tone === 'error'" viewBox="0 0 16 16" class="w-4 h-4 text-rose-300"><path fill="currentColor" d="M4 4l8 8M12 4l-8 8" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg><svg v-else-if="t.tone === 'warning'" viewBox="0 0 16 16" class="w-4 h-4 text-amber-300"><path fill="currentColor" d="M8 1.5l7 12.5H1L8 1.5z"/></svg><svg v-else viewBox="0 0 16 16" class="w-4 h-4 text-blue-300"><circle cx="8" cy="8" r="6" fill="currentColor" opacity="0.4"/><circle cx="8" cy="8" r="3" fill="currentColor"/></svg></span><div class="flex-1 min-w-0"><div class="text-sm font-semibold leading-tight" :class="titleColor(t.tone)">{{ t.text }}</div>6 unmodified lines<script setup>import { useToast } from '../composables/useToast.js'const { state, dismiss } = useToast()function toneClass(tone) {return {success: 'bg-emerald-900/40 border-emerald-500/30',error: 'bg-rose-900/40 border-rose-500/30',warning: 'bg-amber-900/40 border-amber-500/30',info: 'bg-slate-900/60 border-slate-500/30',}[tone] || 'bg-slate-900/60 border-slate-500/30'}function titleColor(tone) {return {success: 'text-emerald-100',error: 'text-rose-100',warning: 'text-amber-100',info: 'text-slate-100',}[tone] || 'text-slate-100'}</script>4 unmodified lines567891011121314151617186 unmodified lines2526272829303132333435363738394041424344454647484 unmodified lines<div class="fixed top-3 right-3 z-[100] space-y-2 max-w-sm pointer-events-none"><transition-group tag="div" class="space-y-2"><div v-for="t in state.items" :key="t.id"class="pointer-events-auto rounded-lg border bg-surface shadow-card px-4 py-3 flex items-start gap-3":class="[toneClass(t.tone), t.leaving ? 'animate-toast-out' : 'animate-toast-in']"@click="dismiss(t.id)"><span class="shrink-0 mt-0.5"><Check v-if="t.tone === 'success'" class="w-4 h-4 text-emerald-700" :stroke-width="2" /><X v-else-if="t.tone === 'error'" class="w-4 h-4 text-rose-700" :stroke-width="2" /><TriangleAlert v-else-if="t.tone === 'warning'" class="w-4 h-4 text-amber-700" :stroke-width="2" /><Info v-else class="w-4 h-4 text-sky-700" :stroke-width="2" /></span><div class="flex-1 min-w-0"><div class="text-sm font-semibold leading-tight" :class="titleColor(t.tone)">{{ t.text }}</div>6 unmodified lines<script setup>import { useToast } from '../composables/useToast.js'import { Check, Info, TriangleAlert, X } from 'lucide-vue-next'const { state, dismiss } = useToast()function toneClass(tone) {return {success: 'bg-emerald-50 border-emerald-200',error: 'bg-rose-50 border-rose-200',warning: 'bg-amber-50 border-amber-200',info: 'bg-sky-50 border-sky-200',}[tone] || 'bg-sky-50 border-sky-200'}function titleColor(tone) {return {success: 'text-emerald-900',error: 'text-rose-900',warning: 'text-amber-900',info: 'text-sky-900',}[tone] || 'text-sky-900'}</script>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259import { computed, onUnmounted, ref, watch } from 'vue'import { useQuery, useQueryClient } from '@tanstack/vue-query'import { api } from '../api.js'import { useRotateStream } from './useRotateStream.js'
export const APP_QUERY_KEYS = { status: ['status'], tasks: ['tasks'], adminStatus: ['admin-status'], codexStatus: ['main-codex-status'], manualAccountStatus: ['manual-account-status'], registerFailures: ['register-failures'],}
export const REFRESH_POLICY = { activeMs: 3000, idleMs: 120000, burstMs: 90000, staleMs: 5000,}
function dataRef(query, fallback = null) { return computed(() => query.data.value ?? fallback)}
function activeTask(tasks) { return (tasks || []).find(task => task.status === 'running' || task.status === 'pending') || null}
export function useAppState(authenticated) { const queryClient = useQueryClient() const enabled = computed(() => !!authenticated.value) const burstUntil = ref(0) let activeTimer = null let burstTimer = null
const statusQuery = useQuery({ queryKey: APP_QUERY_KEYS.status, queryFn: () => api.getStatus(), enabled, staleTime: REFRESH_POLICY.staleMs, refetchInterval: computed(() => enabled.value ? REFRESH_POLICY.idleMs : false), refetchOnWindowFocus: true, keepPreviousData: true, })
const tasksQuery = useQuery({ queryKey: APP_QUERY_KEYS.tasks, queryFn: () => api.getTasks(), enabled, staleTime: REFRESH_POLICY.staleMs, refetchInterval: computed(() => enabled.value ? REFRESH_POLICY.idleMs : false), refetchOnWindowFocus: true, keepPreviousData: true, })
const adminStatusQuery = useQuery({ queryKey: APP_QUERY_KEYS.adminStatus, queryFn: () => api.getAdminStatus(), enabled, staleTime: REFRESH_POLICY.staleMs, refetchInterval: computed(() => enabled.value ? REFRESH_POLICY.idleMs : false), refetchOnWindowFocus: true, keepPreviousData: true, })
const codexStatusQuery = useQuery({ queryKey: APP_QUERY_KEYS.codexStatus, queryFn: () => api.getMainCodexStatus(), enabled, staleTime: REFRESH_POLICY.staleMs, refetchInterval: computed(() => enabled.value ? REFRESH_POLICY.idleMs : false), refetchOnWindowFocus: true, keepPreviousData: true, })
const manualAccountStatusQuery = useQuery({ queryKey: APP_QUERY_KEYS.manualAccountStatus, queryFn: () => api.getManualAccountStatus(), enabled, staleTime: REFRESH_POLICY.staleMs, refetchInterval: computed(() => enabled.value ? REFRESH_POLICY.idleMs : false), refetchOnWindowFocus: true, keepPreviousData: true, })
const registerFailuresQuery = useQuery({ queryKey: APP_QUERY_KEYS.registerFailures, queryFn: () => api.getRegisterFailures(50), enabled, staleTime: REFRESH_POLICY.staleMs, refetchInterval: computed(() => enabled.value ? REFRESH_POLICY.idleMs : false), refetchOnWindowFocus: true, keepPreviousData: true, })
const status = dataRef(statusQuery) const tasks = dataRef(tasksQuery, []) const adminStatus = dataRef(adminStatusQuery) const codexStatus = dataRef(codexStatusQuery) const manualAccountStatus = dataRef(manualAccountStatusQuery) const registerFailures = dataRef(registerFailuresQuery) const runningTask = computed(() => activeTask(tasks.value)) const busyTask = computed(() => { if (adminStatus.value?.login_in_progress) return { command: 'admin-login' } if (codexStatus.value?.in_progress) return { command: 'main-codex-sync' } return runningTask.value }) const loading = computed(() => ( statusQuery.isFetching.value || tasksQuery.isFetching.value || adminStatusQuery.isFetching.value || codexStatusQuery.isFetching.value || manualAccountStatusQuery.isFetching.value || registerFailuresQuery.isFetching.value )) const unauthorized = computed(() => [ statusQuery.error.value, tasksQuery.error.value, adminStatusQuery.error.value, codexStatusQuery.error.value, manualAccountStatusQuery.error.value, registerFailuresQuery.error.value, ].some(error => error?.status === 401)) const registerFailuresUnavailable = computed(() => { const error = registerFailuresQuery.error.value if (!error) return '' if (error.status === 404 || error.status === 405) { return '当前后端未提供注册失败明细 JSON 接口,前端已降级为空列表。' } return `获取注册失败明细失败: ${error.message || '未知错误'}` }) const registerFailuresLoading = computed(() => registerFailuresQuery.isFetching.value)
const rotateStream = useRotateStream({ immediate: false }) const offTransition = rotateStream.onTransition(() => { refetchCore() })
function invalidateCore() { for (const key of [ APP_QUERY_KEYS.status, APP_QUERY_KEYS.tasks, APP_QUERY_KEYS.adminStatus, APP_QUERY_KEYS.codexStatus, APP_QUERY_KEYS.manualAccountStatus, APP_QUERY_KEYS.registerFailures, ]) { queryClient.invalidateQueries({ queryKey: key }) } }
function clearCoreCache() { for (const key of [ APP_QUERY_KEYS.status, APP_QUERY_KEYS.tasks, APP_QUERY_KEYS.adminStatus, APP_QUERY_KEYS.codexStatus, APP_QUERY_KEYS.manualAccountStatus, APP_QUERY_KEYS.registerFailures, ]) { queryClient.removeQueries({ queryKey: key }) } }
async function refetchCore() { if (!enabled.value) return invalidateCore() await Promise.allSettled([ queryClient.refetchQueries({ queryKey: APP_QUERY_KEYS.status, type: 'active' }), queryClient.refetchQueries({ queryKey: APP_QUERY_KEYS.tasks, type: 'active' }), queryClient.refetchQueries({ queryKey: APP_QUERY_KEYS.adminStatus, type: 'active' }), queryClient.refetchQueries({ queryKey: APP_QUERY_KEYS.codexStatus, type: 'active' }), queryClient.refetchQueries({ queryKey: APP_QUERY_KEYS.manualAccountStatus, type: 'active' }), queryClient.refetchQueries({ queryKey: APP_QUERY_KEYS.registerFailures, type: 'active' }), ]) }
function stopActiveRefresh() { if (activeTimer) { clearInterval(activeTimer) activeTimer = null } }
function startActiveRefresh(durationMs = 0) { if (!enabled.value) return if (!activeTimer) { activeTimer = setInterval(refetchCore, REFRESH_POLICY.activeMs) } if (durationMs > 0) { burstUntil.value = Date.now() + durationMs clearTimeout(burstTimer) burstTimer = setTimeout(() => { burstUntil.value = 0 if (!busyTask.value) stopActiveRefresh() }, durationMs) } }
function notifyActionStarted() { startActiveRefresh(REFRESH_POLICY.burstMs) refetchCore() }
async function refresh() { await refetchCore() }
watch(enabled, (ok) => { if (ok) { rotateStream.connect() refetchCore() return } stopActiveRefresh() rotateStream.disconnect() clearCoreCache() }, { immediate: true })
watch(unauthorized, (hit) => { if (hit) { authenticated.value = false } })
watch(busyTask, (task) => { if (task) { startActiveRefresh() return } refetchCore() if (!burstUntil.value || Date.now() >= burstUntil.value) stopActiveRefresh() })
onUnmounted(() => { stopActiveRefresh() clearTimeout(burstTimer) offTransition && offTransition() rotateStream.disconnect() })
return { status, tasks, adminStatus, codexStatus, manualAccountStatus, registerFailures, registerFailuresLoading, registerFailuresUnavailable, runningTask, busyTask, loading, rotateStream, refresh, notifyActionStarted, }}13 unmodified lines14151617181913 unmodified lines33343536373810 unmodified lines4950515253545513 unmodified lines// { email, from, to, reason, ts, extra }import { onMounted, onUnmounted, ref } from 'vue'const DEFAULT_URL = '/api/rotate/stream'const MAX_EVENTS = 5013 unmodified lineslet stoppedByQuota = falseconst transitionCallbacks = new Set()function _push(payload) {// 首条 = 最新;超过 max 截尾events.value = [payload, ...events.value].slice(0, max)10 unmodified linesfunction connect() {if (source || stoppedByQuota) returntry {source = new EventSource(url)} catch (e) {console.warn('[useRotateStream] EventSource ctor failed', e)lastError.value = e13 unmodified lines1415161718192013 unmodified lines343536373839404142434445464710 unmodified lines5859606162636413 unmodified lines// { email, from, to, reason, ts, extra }import { onMounted, onUnmounted, ref } from 'vue'import { getApiKey } from '../api.js'const DEFAULT_URL = '/api/rotate/stream'const MAX_EVENTS = 5013 unmodified lineslet stoppedByQuota = falseconst transitionCallbacks = new Set()function urlWithAuthKey() {const key = getApiKey()if (!key) return urlconst target = new URL(url, window.location.origin)target.searchParams.set('key', key)return `${target.pathname}${target.search}`}function _push(payload) {// 首条 = 最新;超过 max 截尾events.value = [payload, ...events.value].slice(0, max)10 unmodified linesfunction connect() {if (source || stoppedByQuota) returntry {source = new EventSource(urlWithAuthKey())} catch (e) {console.warn('[useRotateStream] EventSource ctor failed', e)lastError.value = e
46 unmodified lines4748495051525354559 unmodified lines65666768697011 unmodified lines8283848586878889909192933 unmodified lines97989910010110244 unmodified lines14714814915015115215315415515615715846 unmodified lines// ['status'],vue-query 自动重拉(refetchOnMount + dedup)。//// 返回 useRotateStream 的所有 ref,组件可同时拿来渲染"实时进度"面板。export function useStatusInvalidator() {const queryClient = useQueryClient()const stream = useRotateStream()const offTransition = stream.onTransition(() => {// invalidateQueries 自身是 promise + dedup,不需要 debounce;// 若 30s polling 与 SSE 重叠,vue-query 会合并成单次网络请求。9 unmodified linesstandby: 'Standby',pending: 'Pending',personal: 'Personal',auth_invalid: '认证失效',orphan: '孤立',degraded_grace: 'Grace',11 unmodified linesgradient: 'from-emerald-400/20 via-emerald-500/10 to-teal-500/15',},personal: {base: 'bg-violet-500/[0.08]',text: 'text-violet-300',border: 'border-violet-400/30',dot: 'bg-violet-400',pulse: false,gradient: 'from-violet-400/20 via-fuchsia-500/15 to-purple-500/15',},standby: {base: 'bg-amber-500/[0.08]',3 unmodified linespulse: false,gradient: 'from-amber-400/15 via-yellow-500/10 to-amber-600/15',},// GRACE — 橙→红渐变,grace_until 越接近 0 越红degraded_grace: {base: 'bg-orange-500/[0.10]',44 unmodified linesreturn STATUS_STYLES[s] || STATUS_STYLES.pending}// F1 — "实际可用性" 派生:四档 ✅ ⚠️ 💤 ❌// 输入:account 对象(含 status, last_quota, grace_until 等)// 输出:{ kind: 'usable'|'grace'|'standby'|'unusable', label, hint, tone }export function computeUsability(acc) {if (!acc) return { kind: 'unknown', label: '—', hint: '', tone: 'neutral' }const s = acc.statusconst q = acc.last_quota || {}const noQuota = q.primary_total === 0 || q.no_quota === trueconst hasError = q.error || q.status === 'auth_error'46 unmodified lines4748495051525354559 unmodified lines6566676869707111 unmodified lines8384858687888990919293943 unmodified lines989910010110210310410510610710810911011144 unmodified lines15615715815916016116216316416516616716816917046 unmodified lines// ['status'],vue-query 自动重拉(refetchOnMount + dedup)。//// 返回 useRotateStream 的所有 ref,组件可同时拿来渲染"实时进度"面板。export function useStatusInvalidator(options = {}) {const queryClient = useQueryClient()const stream = options.stream || useRotateStream(options.streamOptions || {})const offTransition = stream.onTransition(() => {// invalidateQueries 自身是 promise + dedup,不需要 debounce;// 若 30s polling 与 SSE 重叠,vue-query 会合并成单次网络请求。9 unmodified linesstandby: 'Standby',pending: 'Pending',personal: 'Personal',disabled: 'Disabled',auth_invalid: '认证失效',orphan: '孤立',degraded_grace: 'Grace',11 unmodified linesgradient: 'from-emerald-400/20 via-emerald-500/10 to-teal-500/15',},personal: {base: 'bg-sky-500/[0.08]',text: 'text-sky-300',border: 'border-sky-400/30',dot: 'bg-sky-400',pulse: false,gradient: 'from-sky-400/20 via-blue-500/10 to-indigo-500/15',},standby: {base: 'bg-amber-500/[0.08]',3 unmodified linespulse: false,gradient: 'from-amber-400/15 via-yellow-500/10 to-amber-600/15',},disabled: {base: 'bg-stone-500/[0.08]',text: 'text-stone-700',border: 'border-stone-300',dot: 'bg-stone-500',pulse: false,gradient: 'from-stone-200/70 via-stone-100/50 to-slate-100/60',},// GRACE — 橙→红渐变,grace_until 越接近 0 越红degraded_grace: {base: 'bg-orange-500/[0.10]',44 unmodified linesreturn STATUS_STYLES[s] || STATUS_STYLES.pending}// F1 — "实际可用性" 派生四档状态// 输入:account 对象(含 status, last_quota, grace_until 等)// 输出:{ kind: 'usable'|'grace'|'standby'|'unusable', label, hint, tone }export function computeUsability(acc) {if (!acc) return { kind: 'unknown', label: '—', hint: '', tone: 'neutral' }const s = acc.statusif (s === 'disabled') {return { kind: 'standby', label: '禁用', hint: '已从自动化流程排除', tone: 'neutral' }}const q = acc.last_quota || {}const noQuota = q.primary_total === 0 || q.no_quota === trueconst hasError = q.error || q.status === 'auth_error'
128 unmodified lines1291301311321331341351361371381391401411421431441451461 unmodified line14814915015115215315414 unmodified lines16917017117217317417517617717817918018118218318418518626 unmodified lines213214215216217218219220221222223224225226227228128 unmodified lines.page-leave-active { transition: opacity 120ms ease-in, transform 120ms ease-in; }.page-leave-to { opacity: 0; transform: translateY(-2px); }/* ── 渐变按钮上的白前景(绕过 §Compat 层 text-white 翻转)──────── */.text-on-accent { color: #ffffff !important; }/* ─────────────────────────────────────────────────────────────────* § Compat Layer — 旧深色 utility → 明亮等价值* 21 组件仍硬编码 text-white / text-gray-X / bg-white/[0.0X] / border-white/[X]* 统一在此一次性翻转,避免逐文件改 21 套类名;视觉影响整体可控。* 渐变按钮等需要保留白前景的元素请使用 .text-on-accent。* ───────────────────────────────────────────────────────────────── */@layer utilities {/* 文字色翻转 */.text-white { color: #0a0a0a; }.text-gray-100 { color: #171717; }.text-gray-200 { color: #262626; }.text-gray-300 { color: #404040; }1 unmodified line.text-gray-500 { color: #737373; }.text-gray-600 { color: #a3a3a3; }.text-gray-700 { color: #d4d4d4; }.hover\:text-white:hover { color: #0a0a0a; }.hover\:text-gray-100:hover { color: #171717; }.hover\:text-gray-200:hover { color: #262626; }.hover\:text-gray-300:hover { color: #404040; }14 unmodified lines.hover\:bg-white\/\[0\.07\]:hover { background-color: rgba(0,0,0,0.06); }.hover\:bg-white\/\[0\.10\]:hover { background-color: rgba(0,0,0,0.07); }/* black/30 输入框深色背景 → 浅灰 */.bg-black\/30 { background-color: #f5f5f5; }.bg-black\/40 { background-color: #efefef; }.bg-black\/50 { background-color: #ebebeb; }/* gray-700/800/900 灰阶(Settings 等组件硬编码深色 input)→ 浅灰 */.bg-gray-700 { background-color: #ebebeb; }.bg-gray-800 { background-color: #f5f5f5; }.bg-gray-900 { background-color: #fafafa; }.bg-gray-800\/30 { background-color: rgba(0,0,0,0.02); }.bg-gray-800\/40 { background-color: rgba(0,0,0,0.03); }.bg-gray-800\/60 { background-color: rgba(0,0,0,0.04); }.hover\:bg-gray-700:hover { background-color: #e5e5e5; }.disabled\:bg-gray-700:disabled { background-color: #f5f5f5; }.disabled\:hover\:bg-gray-700:disabled:hover { background-color: #f5f5f5; }26 unmodified lines.text-rose-300 { color: #be123c; }.text-orange-200 { color: #9a3412; }.text-orange-300 { color: #c2410c; }.text-violet-100, .text-violet-200 { color: #5b21b6; }.text-violet-300 { color: #6d28d9; }.text-indigo-100, .text-indigo-200 { color: #3730a3; }.text-indigo-300 { color: #4338ca; }.text-blue-200 { color: #1e3a8a; }.text-blue-300 { color: #1d4ed8; }.text-yellow-200 { color: #854d0e; }.text-yellow-300 { color: #a16207; }.text-fuchsia-100, .text-fuchsia-200 { color: #86198f; }.text-fuchsia-300 { color: #a21caf; }.text-cyan-100, .text-cyan-200 { color: #155e75; }.text-cyan-300 { color: #0e7490; }.text-sky-100, .text-sky-200 { color: #0c4a6e; }128 unmodified lines1291301311321331341351361371381391401411421431441451 unmodified line14714814915015115214 unmodified lines16716816917017117217317426 unmodified lines201202203204205206207208209210211212128 unmodified lines.page-leave-active { transition: opacity 120ms ease-in, transform 120ms ease-in; }.page-leave-to { opacity: 0; transform: translateY(-2px); }/* ── 渐变按钮上的前景色固定(绕过旧深色兼容层)──────── */.text-on-accent { color: #ffffff !important; }/* ─────────────────────────────────────────────────────────────────* § Compat Layer — 旧深色 utility → 明亮等价值* 部分历史组件仍硬编码 text-gray-X / bg-white/[0.0X] / border-white/[X]。* 统一在此一次性翻转,避免无关页面在迁移中破版。* 渐变按钮等需要固定高对比前景的元素请使用 .text-on-accent。* ───────────────────────────────────────────────────────────────── */@layer utilities {/* 文字色翻转 */.text-gray-100 { color: #171717; }.text-gray-200 { color: #262626; }.text-gray-300 { color: #404040; }1 unmodified line.text-gray-500 { color: #737373; }.text-gray-600 { color: #a3a3a3; }.text-gray-700 { color: #d4d4d4; }.hover\:text-gray-100:hover { color: #171717; }.hover\:text-gray-200:hover { color: #262626; }.hover\:text-gray-300:hover { color: #404040; }14 unmodified lines.hover\:bg-white\/\[0\.07\]:hover { background-color: rgba(0,0,0,0.06); }.hover\:bg-white\/\[0\.10\]:hover { background-color: rgba(0,0,0,0.07); }/* gray-700/800/900 灰阶(Settings 等组件硬编码深色 input)→ 浅灰 */.bg-gray-700 { background-color: #ebebeb; }.hover\:bg-gray-700:hover { background-color: #e5e5e5; }.disabled\:bg-gray-700:disabled { background-color: #f5f5f5; }.disabled\:hover\:bg-gray-700:disabled:hover { background-color: #f5f5f5; }26 unmodified lines.text-rose-300 { color: #be123c; }.text-orange-200 { color: #9a3412; }.text-orange-300 { color: #c2410c; }.text-indigo-100, .text-indigo-200 { color: #3730a3; }.text-indigo-300 { color: #4338ca; }.text-blue-200 { color: #1e3a8a; }.text-blue-300 { color: #1d4ed8; }.text-yellow-200 { color: #854d0e; }.text-yellow-300 { color: #a16207; }.text-cyan-100, .text-cyan-200 { color: #155e75; }.text-cyan-300 { color: #0e7490; }.text-sky-100, .text-sky-200 { color: #0c4a6e; }
.env.example+22
src/autoteam/accounts.py+29-4
src/autoteam/api.py+27-7
src/autoteam/codex_auth.py+1-3
src/autoteam/config.py+25
src/autoteam/cpa_sync.py+93-30
src/autoteam/invite.py+2-5
src/autoteam/manager.py+51-1
src/autoteam/sub2api_sync.pyAdded+1049
src/autoteam/sync_targets.pyAdded+278
src/autoteam/web/dist/assets/index-BSht6bmF.jsAdded
src/autoteam/web/dist/assets/index-BZ-R3x09.jsDeleted
src/autoteam/web/dist/assets/index-DHotZNsL.css → src/autoteam/web/dist/assets/index-CbNAiyvN.cssRenamed+1-1
src/autoteam/web/dist/index.html+2-2
tests/unit/test_accounts.py+24
tests/unit/test_api_playwright_cleanup.py+59-2
tests/unit/test_cpa_sync.py+124
tests/unit/test_sub2api_sync.pyAdded+659
tests/unit/test_sync_targets.pyAdded+110
web/src/App.vue+41-88
web/src/api.js+5-1
web/src/components/AtButton.vue+6-6
web/src/components/Dashboard.vue+240-94
web/src/components/HealthDonut.vue+3-3
web/src/components/LogViewer.vue+36-21
web/src/components/MailProviderCard.vue+21-21
web/src/components/MasterHealthBanner.vue+34-60
web/src/components/OAuthPage.vue+21-21
web/src/components/PoolHealthCard.vue+33-43
web/src/components/Settings.vue+43-49
web/src/components/SetupPage.vue+25-20
web/src/components/Sidebar.vue+6-6
web/src/components/StatusBadge.vue+3-2
web/src/components/SyncPage.vue+5-3
web/src/components/TaskHistory.vue+30-22
web/src/components/TaskHistoryPage.vue+2-2
web/src/components/TaskPanel.vue+48-37
web/src/components/TasksPage.vue+1-1
web/src/components/TeamMembers.vue+18-18
web/src/components/ToastHost.vue+16-15
web/src/composables/useAppState.jsAdded+259
web/src/composables/useRotateStream.js+10-1
web/src/composables/useStatus.js+20-8
web/src/style.css+4-20