From b412c84092d65674004c29e5caf5b523ecc23f1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=99=93=E4=B8=B6=E6=A2=A6=E4=B8=B6=E4=BB=81?= <74444214+Daydreamer114@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:54:08 +0800 Subject: [PATCH 1/8] =?UTF-8?q?fix(garrison):=20=E7=AD=96=E7=95=A5?= =?UTF-8?q?=E9=A1=B5=E8=AF=A6=E6=83=85=E6=A0=B8=E5=AF=B9=E5=8A=A0=E5=AE=B9?= =?UTF-8?q?=E5=B7=AE=EF=BC=8C=E7=BC=AA=E5=B0=94=E8=B5=9B=E6=80=9D=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E5=8D=A1=E6=AD=BB=E6=95=B4=E5=B1=80=20(#117)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 9731 号日志复盘:策略页点开「缪尔赛思」卡后,核心在右侧详情栏 OCR 策略名核对(Ar 函数)用的是纯 includes 零容错——与购买路径的 Zr 完全 两套标准。详情名错一个形近字 → 3 次重读全挂 →「策略详情名称未能对应 目标卡片」跳过并拉黑该卡 → 列表 p0/p1/p2 往返滚到头 →「已到策略列表 末尾,但尚有策略进度未核实」整局停止(checkpoint 里本局 strategy/ selectedId 均为 null)。 新规则 strategy-detail-name-tolerance:Ar 的 includes 不中再走 Zr (≥3 字名 1 字差、≥6 字拉丁名 2 字差)。61 个策略名里编辑距离 ≤1 的 名字对全部是 ≤2 字名(夕/望/芬/陈、耶拉/雅拉),Zr 对其零容差, 无互配风险(已用「椰拉」负例验证)。 验证:真实核心副本 4 规则应用/幂等/语法通过;抽出补丁后 Ar 跑行为 用例(缪尔赛思±1 字、耶拉/雅拉互配安全)全过;B47 fixture 自动 覆盖新规则,全套冒烟绿。 --- resources/garrison/patches.json | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/resources/garrison/patches.json b/resources/garrison/patches.json index 54d8269..2f17fd6 100644 --- a/resources/garrison/patches.json +++ b/resources/garrison/patches.json @@ -16,9 +16,15 @@ }, { "id": "free-claim-trust-detail-title", - "why": "免费领取(三合一赠送 / 召唤模块奖励,$e 第三参 b=true)的兜底:卡片名与详情标题两侧 OCR 对不上时(如单字名「夕」在小字号卡面上被读成形近字),核心原本直接判核对失败、关弹窗、弃领。改为免费场景下若大字号详情标题读出了非空文本,就信详情、按它的名字继续领——最坏结果是领了另一张免费卡,不会误花金币(购买/出售 b=false 不走此兜底,核对标准不变)。", + "why": "免费领取(三合1赠送高星干员 / 召唤模块奖励,$e 第三参 b=true)的兜底:卡片名与详情标题两侧 OCR 对不上时(如单字名「夕」在小字号卡面上被读成形近字),核心原本直接判核对失败、关弹窗、弃领。改为免费场景下若大字号详情标题读出了非空文本,就信详情、按它的名字继续领——最坏结果是领了另一张免费卡,不会误花金币(购买/出售 b=false 不走此兜底,核对标准不变)。", "find": "if(!Zr(K,k))return _(", "replace": "if(!Zr(K,k)&&!(b&&K&&(k=K)))return _(" + }, + { + "id": "strategy-detail-name-tolerance", + "why": "策略页选卡(如「缪尔赛思」):点开卡片后核心在右侧详情栏 OCR 策略名核对(Ar 函数),原本用纯 includes 零容错——与购买路径的 Zr 完全两套标准。详情名 OCR 错一个形近字即 3 次重读全挂 →「策略详情名称未能对应目标卡片」跳过该卡 → 拉黑后列表滚到头 →「已到策略列表末尾,但尚有策略进度未核实」整局停止。改为 includes 不中再走 Zr 容差(≥3 字名 1 字差、≥6 字拉丁名 2 字差;61 个策略名中距离 ≤1 的名字对全是 ≤2 字名,Zr 对其零容差,无互配风险)。", + "find": "return b.find(M=>A(k).includes(A(M.name)))", + "replace": "return b.find(M=>A(k).includes(A(M.name))||Zr(A(k),A(M.name)))" } ] } From 4c6f9d8842fb4fa6df2a683f8be27de4722b5330 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=99=93=E4=B8=B6=E6=A2=A6=E4=B8=B6=E4=BB=81?= <74444214+Daydreamer114@users.noreply.github.com> Date: Sat, 21 Nov 2026 07:01:48 +0800 Subject: [PATCH 2/8] =?UTF-8?q?feat(copilot):=20=E4=BD=9C=E4=B8=9A?= =?UTF-8?q?=E5=B9=B2=E5=91=98=E6=9B=BF=E6=8D=A2=E2=80=94=E2=80=94=E5=A1=9E?= =?UTF-8?q?=E9=9B=B7=E5=A8=85=201=20=E7=94=B1=20=E9=BB=8D=201=20=E9=A1=B6?= =?UTF-8?q?=E6=9B=BF=EF=BC=88#92=EF=BC=89=20(#119)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 写往 MAA 的作业按 SUB_RULES 换干员:当前一条规则「塞雷娅 1(奶盾) → 黍 1」,黍是上位替代,账号练度等价即强制替换(force 档;fallback 档预留给「原干员不可用才顶上」,未启用规则)。 - 命中条件:条目名+技能号与规则一致(MaaCore 的 skill 缺省 0=不指定 技能,只有显式写了技能号的条目参与),账号拥有替补且替补按该条目 的要求达标;替换在同一干员组内判定(整组齐即算齐)。 - copilot.apply_substitutions:写入 MAA 前按账号练度执行替换,返回 换了哪些(写入日志可见);api_maa_apply 带上账号透传。 - 前端:作业卡片/详情对被换干员给 subbed 标注(换成了谁),不算 「缺人」;B48 用例:匹配 / 写入 / 干员组 / 不触发边界。 --- backend/core/agent.py | 11 ++- backend/core/api.py | 4 +- backend/core/copilot.py | 164 ++++++++++++++++++++++++++++++++-- backend/core/maa.py | 19 +++- backend/core/maaplan.py | 17 +++- backend/core/multiacct.py | 6 +- frontend/app.js | 21 +++-- frontend/style.css | 4 +- tools/smoketest/smoke_test.py | 105 ++++++++++++++++++++++ 9 files changed, 323 insertions(+), 28 deletions(-) diff --git a/backend/core/agent.py b/backend/core/agent.py index 3d1c483..fe57593 100644 --- a/backend/core/agent.py +++ b/backend/core/agent.py @@ -719,7 +719,8 @@ def _tool_op_detail(args): opers = copilot.detail_opers(content, owned) lack, borrow = [], [] for o in opers: - if o.get('owned') is False: + # 命中替换规则(sub,#92)的不算缺:写入 MAA 时会被练度等价的替补顶掉 + if o.get('owned') is False and not o.get('sub'): borrow.append(o.get('name')) return { 'id': int(cid), @@ -727,9 +728,10 @@ def _tool_op_detail(args): 'stage': content.get('stage_name') or '', 'opers': [{'name': o.get('name'), 'owned': o.get('owned'), 'ok': o.get('ok'), 'elite': o.get('elite'), - 'level': o.get('level')} for o in opers], + 'level': o.get('level'), 'sub': o.get('sub')} for o in opers], 'notOwned': borrow, - 'note': 'owned=false 是要借的人;ok=false 是练度不够', + 'note': 'owned=false 是要借的人;ok=false 是练度不够;' + 'sub 有值 = 该干员写入 MAA 时会被替换(如黍1顶塞1,#92)', } @@ -871,7 +873,8 @@ def _tool_add_stages(args, session=None): return blocked tid = maa.start_apply(items, profile=None, mode='replace', auto_start=start, - maa_dir=(accounts.get_account(acc).get('maa') or {}).get('dir') or None) + maa_dir=(accounts.get_account(acc).get('maa') or {}).get('dir') or None, + account=acc) # 带上账号:写盘时做干员替换(#92) return {'started': True, 'taskId': tid, 'count': len(items), 'skipped': skipped, 'note': '已提交写入 MAA,不要在这里等它跑完'} diff --git a/backend/core/api.py b/backend/core/api.py index a30df4e..4dcc2c7 100644 --- a/backend/core/api.py +++ b/backend/core/api.py @@ -491,7 +491,9 @@ def api_maa_apply(_q, body): tid = maa.start_apply(items, profile=body.get('profile'), mode=body.get('mode') or 'replace', auto_start=body.get('autoStart', True), - maa_dir=_maa_dir_for(body.get('file'))) + maa_dir=_maa_dir_for(body.get('file')), + # 带上账号:写盘时按该账号练度做干员替换(#92) + account=str(body.get('file') or '').strip() or None) return {'taskId': tid} diff --git a/backend/core/copilot.py b/backend/core/copilot.py index 270d15b..04387df 100644 --- a/backend/core/copilot.py +++ b/backend/core/copilot.py @@ -172,6 +172,63 @@ def norm(name): return re.sub(r'\s+', '', str(name or '')) +# ---------------------------------------------------------------- 干员替换(#92) +# 作业站的老作业经常点名塞雷娅这类开服六星,后来的号未必有、或练度跟不上。 +# 这里按「干员名 + 技能号」硬编码一批替换规则,分两档: +# force 强制替换:账号里有替补且练度等价(按被替条目的要求判,见 +# sub_rule_for)就换——原干员有没有、达不达标都不看 +# fallback 可替:原干员缺卡或练度不足时才用替补顶上(目前没有条目) +# 只做单向:反向(作业要黍1 用塞1 顶)不做,需要时加一条新规则即可。 +# 匹配侧(match_operation / detail_opers)与写 MAA 侧(apply_substitutions) +# 都走 sub_rule_for 这同一个判定,两边口径不会漂。 +SUB_RULES = [ + # 塞雷娅 1 技能(奶盾)由 黍 1 技能顶替:黍是上位替代,练度等价就强制换 + {'from': '塞雷娅', 'from_skill': 1, 'to': '黍', 'to_skill': 1, 'kind': 'force'}, +] + + +def sub_rule_for(op, owned_map, siblings=()): + """作业条目命中的替换规则(None = 不换)。 + + 命中条件:条目名 + 技能号与规则一致(MaaCore 里 skill 缺省是 0=不指定 + 技能,所以只有显式写了技能号的条目才参与替换),且账号拥有替补、替补按 + **这条目的要求**判定达标(等价练度)。force 档到此即命中;fallback 档还 + 要原干员本身不可用(缺卡或练度不足)才顶上。 + + siblings 是同一容器(顶层 opers / 同一个 group)里已点名的干员:替补已经 + 在里面就不换,否则会把一份作业写出两个同名条目(同位置重复部署)。 + """ + if not owned_map or not isinstance(op, dict): + return None + name = norm(op.get('name')) + try: + skill = int(op.get('skill') or 0) + except (TypeError, ValueError): + return None + named = {norm(s) for s in siblings if s} + owned = owned_map.get(name) + for r in SUB_RULES: + if name != norm(r['from']) or skill != r['from_skill']: + continue + if norm(r['to']) in named: + continue + sub = owned_map.get(norm(r['to'])) + if not sub or not req_met(op, sub): + continue # 替补没有 / 练度不等价 → 不换 + if r['kind'] == 'force': + return r + if not owned or not req_met(op, owned): + return r # 可替:原干员不可用才顶上 + return None + + +def sub_brief(rule): + """规则 → 前端标注用的短结构(名字 + 技能号),没命中返回 None""" + if not rule: + return None + return {'name': rule['to'], 'skill': rule['to_skill']} + + # ---------------------------------------------------------------- 匹配 def progress_score(rarity, elite, level): lv = MAX_LEVELS.get(int(rarity or 6), MAX_LEVELS[6]) @@ -251,10 +308,15 @@ def req_met(req, owned): def _group_ok(group, owned_map): - cands = [c for c in (group.get('opers') or []) if isinstance(c, dict) - and norm(c.get('name')) in owned_map] + members = [c for c in (group.get('opers') or []) if isinstance(c, dict)] + named = [c.get('name') for c in members] + cands = [c for c in members if norm(c.get('name')) in owned_map] if any(req_met(c, owned_map[norm(c.get('name'))]) for c in cands): return 'ready' + # 组内没一个直接可用时再看替换:干员组「满足任一即可」,某个成员能被 + # 替补顶上(见 SUB_RULES)整个组就算齐(#92) + if any(sub_rule_for(c, owned_map, named) for c in members): + return 'ready' return 'train' if cands else 'missing' @@ -276,12 +338,17 @@ def match_operation(content, owned_map): six = 0 wsum = 0.0 + # 替换规则按「同容器已点名」判重(替补已在阵容里就不换),顶层 opers 的 + # siblings 是全部具名干员(#92) + top_names = [o.get('name') for o in opers] + for op in opers: name = norm(op.get('name')) owned = owned_map.get(name) - wsum += op_weight(name) - ok = bool(owned and req_met(op, owned)) - if not owned: + sub = sub_rule_for(op, owned_map, top_names) + wsum += op_weight(norm(sub['to'])) if sub else op_weight(name) + ok = bool(owned and req_met(op, owned)) or sub is not None + if not owned and not sub: missing.append(op.get('name')) elif not ok: training.append(op.get('name')) @@ -301,6 +368,9 @@ def match_operation(content, owned_map): 'req': req, 'skill': op.get('skill'), 'skillKnown': bool(owned.get('skillKnown', True)) if owned else None, + # 命中替换时 ok=True 但账号里未必有原干员;sub 给前端在详情里 + # 标注「由黍1替换塞1」,列表卡片保持无感(#92) + 'sub': sub_brief(sub), }) for g in groups: @@ -878,23 +948,105 @@ def detail_opers(content, owned_map=None): """ idx = _char_index() out = [] + # 顶层 opers 整体当 siblings(与 match_operation 同口径):替补已被作者 + # 自己写进阵容时不再替换(#92) + top_names = [o.get('name') for o in (content.get('opers') or []) + if isinstance(o, dict)] for op in content.get('opers') or []: o = dict(op) stars = (idx.get(o.get('name') or '') or (6,))[0] owned = (owned_map or {}).get(norm(o.get('name'))) known = bool(owned.get('skillKnown', True)) if owned else True + sub = sub_rule_for(op, owned_map, top_names) if owned_map else None # 键名与搜索侧 _item 的 'req' 统一:两处各叫各的(req/requirements), # 任一侧改名另一侧就静默显示「无特殊要求」(#63) o['req'] = effective_req(op, stars, strict_skill=known) o['skillKnown'] = known if owned else None o['owned'] = bool(owned) if owned_map is not None else None - o['ok'] = (bool(owned) and req_met(op, owned)) if owned_map is not None else None + o['ok'] = ((bool(owned) and req_met(op, owned)) or sub is not None) \ + if owned_map is not None else None o['elite'] = owned.get('elite') if owned else None o['level'] = owned.get('level') if owned else None + o['sub'] = sub_brief(sub) out.append(o) return out +def apply_substitutions(content, owned_map): + """写往 MAA 的作业按 SUB_RULES 换干员(#92),返回 (新 json, 说明列表)。 + + 没命中时不拷贝原样返回(预取缓存里那份绝不能被就地改掉——它是跨账号 + 共用的);命中才深拷贝重写。条目的 requirements 原样保留:能换的前提就是 + 替补按这套要求判过「等价练度」,MAA 编队时还会再核一遍。 + """ + hits = _sub_hits(content, owned_map) + if not hits: + return content, [] + c = json.loads(json.dumps(content, ensure_ascii=False)) # 深拷贝,不动缓存 + idx = _char_index() + notes = [] + applied = {} # from 名 → 规则:actions 改名要与实际生效的替换一致 + + def rewrite(ops, siblings): + for op in ops: + r = sub_rule_for(op, owned_map, siblings) # 与 _sub_hits 同参同判 + if not r: + continue + op['name'] = r['to'] + op['skill'] = r['to_skill'] + # 换完再过一遍 MAA 合法性修正(技能号与星级、精英下限),规则是 + # 手工维护的,这条只是兜底 + _fix_oper(op, idx, notes) + applied[norm(r['from'])] = r + notes.append('%s(技能%d)由 %s(技能%d)替换:账号练度等价' + % (r['from'], r['from_skill'], r['to'], r['to_skill'])) + + tops = [o for o in (c.get('opers') or []) if isinstance(o, dict)] + rewrite(tops, [o.get('name') for o in tops]) + for g in (c.get('groups') or []): + if isinstance(g, dict): + members = [o for o in (g.get('opers') or []) if isinstance(o, dict)] + rewrite(members, [o.get('name') for o in members]) + # actions 里按名字点被替干员的(没给坐标时 MaaCore 拿名字去场上找, + # BattleProcessTask 的 m_oper_in_group),roster 换了名字它也得跟着换, + # 否则「开技能」类的动作会指空。带着 role 的把 role 一并去掉——规则的 + # 替补未必同职业,名字才是可靠键 + for a in (c.get('actions') or []): + if not isinstance(a, dict): + continue + r = applied.get(norm(a.get('name'))) + if r: + a['name'] = r['to'] + a.pop('role', None) + return c, notes + + +def _sub_hits(content, owned_map): + """content 里有没有条目命中替换规则(顶层 opers 与干员组分开算 siblings)""" + hits = [] + tops = [o for o in (content.get('opers') or []) if isinstance(o, dict)] + top_names = [o.get('name') for o in tops] + hits += [op for op in tops if sub_rule_for(op, owned_map, top_names)] + for g in (content.get('groups') or []): + if not isinstance(g, dict): + continue + members = [o for o in (g.get('opers') or []) if isinstance(o, dict)] + named = [o.get('name') for o in members] + hits += [op for op in members if sub_rule_for(op, owned_map, named)] + return hits + + +def owned_of(file): + """账号文件名 → owned_map(没给 / 读不到返回 None):写 MAA 时判替换用""" + if not file: + return None + try: + from . import accounts # 懒加载:copilot 被到处 import,别成环 + return build_owned(accounts.get_account(file)) + except Exception: + return None + + # ---------------------------------------------------------------- 交给 MAA 前修正 # 作业站的原始 json 里经常有「技能选择与稀有度不匹配」「精英要求填 0 但技能等级 # 要求精一」这类历史遗留问题。MAA 桌面端在「添加作业」时会自己修一遍再存盘, diff --git a/backend/core/maa.py b/backend/core/maa.py index 192aa4d..eb743c5 100644 --- a/backend/core/maa.py +++ b/backend/core/maa.py @@ -286,10 +286,16 @@ def _safe(name): return SAFE.sub('_', name).strip() or 'stage' -def apply_plan(items, profile=None, mode='replace', auto_start=True, tid=None, maa_dir=None): - """items: [{copilotId, stageCode, title}] → 写入 MAA 多作业列表""" +def apply_plan(items, profile=None, mode='replace', auto_start=True, tid=None, maa_dir=None, + account=None): + """items: [{copilotId, stageCode, title}] → 写入 MAA 多作业列表 + + account 是账号文件名:给了就按该账号练度做干员替换(#92,见 + copilot.SUB_RULES),落盘的作业里塞雷娅这类条目会被练度等价的替补顶掉。 + """ log = tasks.log_factory(tid) if tid else (lambda *_: None) d = _dir(maa_dir) + owned = copilot.owned_of(account) log('MAA 目录:%s' % d) # 先校验配置可读、档案存在,再关进程:目录配错 / gui.new.json 损坏时 @@ -371,6 +377,10 @@ def apply_plan(items, profile=None, mode='replace', auto_start=True, tid=None, m log('[%d/%d] 复用已就绪的作业 #%s %s' % (idx, len(items), cid, it.get('title') or '')) else: content, flags, sname = fetched[cid] + if owned: + content, sub_notes = copilot.apply_substitutions(content, owned) + for n in sub_notes: + log(' 替换:%s' % n) fname = '%s_%s.json' % (_safe(stage_code), cid) os.makedirs(_copilot_dir(d), exist_ok=True) fpath = os.path.join(_copilot_dir(d), fname) @@ -424,13 +434,14 @@ def apply_plan(items, profile=None, mode='replace', auto_start=True, tid=None, m 'added': len(new_entries), 'files': files, 'started': started} -def start_apply(items, profile=None, mode='replace', auto_start=True, maa_dir=None): +def start_apply(items, profile=None, mode='replace', auto_start=True, maa_dir=None, account=None): title = '写入 MAA(%d 份作业)' % len(items or []) holder = {} def go(): try: - res = apply_plan(items, profile, mode, auto_start, holder['tid'], maa_dir=maa_dir) + res = apply_plan(items, profile, mode, auto_start, holder['tid'], + maa_dir=maa_dir, account=account) tasks.finish(holder['tid'], result=res) except Exception as e: import traceback diff --git a/backend/core/maaplan.py b/backend/core/maaplan.py index 6543c3b..65e6c37 100644 --- a/backend/core/maaplan.py +++ b/backend/core/maaplan.py @@ -515,11 +515,13 @@ def _copilot_dir(maa_dir): return os.path.join(maa_dir, 'config', 'copilot') -def prepare_copilot(ops, maa_dir, log=None): +def prepare_copilot(ops, maa_dir, log=None, account=None): """下载并落盘作业,返回 MaaCore 的 copilot_list 条目 ``filename`` **必须是绝对路径**(实测:相对路径不报错,但任务静默不入队)。 + ``account`` 是账号文件名:给了就按该账号练度做干员替换(#92)再落盘。 + ``stage_name`` 是 **导航名**,必须是**关卡代号**(``TL-S-1`` / ``1-7``), 不是作业里的关卡内部 id。看 MaaCore 的 MultiCopilotTaskPlugin::_run: @@ -535,6 +537,7 @@ def prepare_copilot(ops, maa_dir, log=None): from . import copilot log = log or (lambda *_: None) + owned = copilot.owned_of(account) os.makedirs(_copilot_dir(maa_dir), exist_ok=True) rows, done = [], {} for it in ops or []: @@ -542,6 +545,9 @@ def prepare_copilot(ops, maa_dir, log=None): code = it.get('stageCode') or str(cid) if cid not in done: content, flags, sname, notes, pre = copilot.fetch_prepared(cid) + sub_notes = [] + if owned: + content, sub_notes = copilot.apply_substitutions(content, owned) fname = '%s_%s.json' % (_SAFE.sub('_', code).strip() or 'stage', cid) path = os.path.normpath(os.path.join(_copilot_dir(maa_dir), fname)) with open(path, 'w', encoding='utf-8') as f: @@ -551,6 +557,8 @@ def prepare_copilot(ops, maa_dir, log=None): it.get('title') or '')) for n in notes or []: log(' 修正:%s' % n) + for n in sub_notes or []: + log(' 替换:%s' % n) path, sname, flags = done[cid] nav = _clean_stage(code) variants = copilot.entry_variants(flags, it.get('variant'), sname) @@ -1784,7 +1792,8 @@ def _retry_failed(eng, spec, state, log, d, deadline, conn=None): if not new_ops: log('没有更多能换的作业了(每关的候选都试过)') break - rows = prepare_copilot(new_ops, d, log=lambda m: log(' ' + m)) + rows = prepare_copilot(new_ops, d, account=spec.get('accountFile'), + log=lambda m: log(' ' + m)) for key, code, var, prev, nxt in picked: used = attempted.setdefault(key, set()) used.add(nxt) @@ -1861,7 +1870,7 @@ def run_plan(rows, spec_base, tid=None): cp = [] if r.get('ops'): log('准备 %d 份作业…' % len(r['ops'])) - cp = prepare_copilot(r['ops'], d, + cp = prepare_copilot(r['ops'], d, account=r.get('file'), log=lambda m: log(' ' + m)) spec = dict(spec_base) spec.update({ @@ -1869,6 +1878,8 @@ def run_plan(rows, spec_base, tid=None): 'switchAccount': True, 'clientType': client_type_of(r.get('channel')), 'copilotList': cp, + # 重挂(_retry_failed)换作业时按同一账号练度做替换(#92) + 'accountFile': r.get('file') or '', }) try: res = run_core(spec, tid) diff --git a/backend/core/multiacct.py b/backend/core/multiacct.py index 1df0c1d..4971ad0 100644 --- a/backend/core/multiacct.py +++ b/backend/core/multiacct.py @@ -385,9 +385,11 @@ def apply(plan_data, tid=None): for o in r['ops']] log('[%d/%d] 给「%s」写 %d 份作业(切号名 %s)' % (i, len(written), name, len(items), r['accountName'])) - # auto_start=False:全部写完再统一启动,不然每写一个就拉起一次 MAA + # auto_start=False:全部写完再统一启动,不然每写一个就拉起一次 MAA; + # account 带上:写盘时按各账号练度做干员替换(#92) res = maa.apply_plan(items, profile=name, mode='replace', - auto_start=False, tid=tid, maa_dir=d) + auto_start=False, tid=tid, maa_dir=d, + account=r.get('file')) total += res.get('added') or 0 log('全部写完,共 %d 份作业;MAA 启动后会自动开始' % total) return {'profiles': [n for n, _ in written], 'ops': total} diff --git a/frontend/app.js b/frontend/app.js index 68ec37c..50d29af 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -1288,11 +1288,12 @@ function diffLabel(dcn, variant) { } /* 干员 chips 全量铺开(容器 flex-wrap 换行):折叠成 +N 会把缺的干员藏起来, - 一眼看不出这份作业到底缺谁 */ + 一眼看不出这份作业到底缺谁。命中替换规则(#92,o.sub)的按「可用」上色, + 列表保持无感,由谁顶替只在详情弹窗里说 */ function opChips(op) { return visOpers(op.opers).map(o => { let cls = 'own'; - if (!o.owned) cls = 'lack'; + if (!o.owned && !o.sub) cls = 'lack'; else if (!o.ok) cls = 'train'; return `${esc(o.name)}`; }).join(''); @@ -1309,6 +1310,7 @@ function chipTitle(o) { if (req.level != null) need.push(req.level + '级'); if (req.implied) need.push('默认'); const needTxt = need.length ? ` · 要求 ${need.join(' ')}` : ''; + if (o.sub) return `由${o.sub.name}${o.sub.skill || ''}替换出战${needTxt}`; if (!o.owned) return '未拥有' + needTxt; return `${e} ${o.level} 级${m ? ' · ' + m : ''}${needTxt}`; } @@ -1716,8 +1718,9 @@ async function showOpDetail(op, variant) { const shown = visOpers(d.opers); /* 缺谁:owned=false 是没这个人,owned && !ok 是练度不到。 只有「差一人可借」这一档才说得出具体的借人对象(助战位只能带一个), - 其余情况分开列:没的人和练度不够的人不是一回事 */ - const bad = d.compared ? shown.filter(o => o.owned === false || o.ok === false) : []; + 其余情况分开列:没的人和练度不够的人不是一回事。 + 命中替换规则(o.sub,#92)的不算缺:写入 MAA 时会被替补顶掉 */ + const bad = d.compared ? shown.filter(o => !o.sub && (o.owned === false || o.ok === false)) : []; const borrowOne = (op.mode === 'borrow' && bad.length === 1) ? bad[0].name : ''; const rest = bad.filter(o => o.name !== borrowOne); const lackOwn = rest.filter(o => o.owned === false).map(o => o.name); @@ -1730,11 +1733,15 @@ async function showOpDetail(op, variant) { if (req.skill_level != null) bits.push(req.skill_level >= 8 ? ('专' + (req.skill_level - 7) + ' 技能' + (req.skill || 1)) : ('技能 ' + req.skill_level)); if (req.module) bits.push('模组 ' + req.module); if (req.implied) bits.push('老作业未标注,按星级默认'); - // 名字上色:借的那个人紫、缺练度的橙,跟顶部提示一对 + // 名字上色:借的那个人紫、缺练度的橙,跟顶部提示一对; + // 替换条目(#92)绿字 + 「由黍1替换」标注 const isBorrow = borrowOne && o.name === borrowOne; - const cls = isBorrow ? ' borrow' : (o.owned === false || o.ok === false ? ' train' : ''); + const isSub = !!o.sub; + const cls = isBorrow ? ' borrow' : (isSub ? ' subbed' + : (o.owned === false || o.ok === false ? ' train' : '')); const tail = isBorrow ? '借' - : (o.owned === false ? '没有' : (o.ok === false ? '练度不足' : '')); + : (isSub ? `由${esc(o.sub.name)}${o.sub.skill || ''}替换` + : (o.owned === false ? '没有' : (o.ok === false ? '练度不足' : ''))); return `
${esc(o.name)}${tail} ${esc(bits.join(' · ') || '无特殊要求')} diff --git a/frontend/style.css b/frontend/style.css index 96b89b4..7bc0880 100644 --- a/frontend/style.css +++ b/frontend/style.css @@ -1237,13 +1237,15 @@ input:focus, select:focus, button:focus-visible { outline: none; } font-weight: 700; } -/* 作业详情弹窗:练度不足(橙)与需要借人(紫)——顶部提示条 + 干员名同色 */ +/* 作业详情弹窗:练度不足(橙)与需要借人(紫)——顶部提示条 + 干员名同色; + subbed 是干员替换(#92,如塞1由黍1顶替):可用但注明换了人 */ .op-flag { margin-bottom: 9px; padding: 8px 11px; border-radius: 10px; font-size: 12px; line-height: 1.6; border: 1px solid var(--line); } .op-flag b { font-weight: 600; } .op-flag.borrow { color: #b48cff; background: rgba(148, 108, 255, 0.10); border-color: rgba(148, 108, 255, 0.32); } .op-flag.train { color: var(--amber); background: rgba(245, 185, 85, 0.09); border-color: rgba(245, 185, 85, 0.30); } .op-name.borrow { color: #b48cff; } .op-name.train { color: var(--amber); } +.op-name.subbed { color: var(--mint); } .op-name em { font-style: normal; font-size: 10.5px; opacity: .85; margin-left: 5px; } .op-top { display: flex; align-items: center; gap: 9px; padding-right: 44px; } diff --git a/tools/smoketest/smoke_test.py b/tools/smoketest/smoke_test.py index 8db2ac7..f8061a0 100644 --- a/tools/smoketest/smoke_test.py +++ b/tools/smoketest/smoke_test.py @@ -636,6 +636,110 @@ def snap(name, stars, elite, level, with_skills): assert 'skill_level' not in detail[0]['req'], detail[0]['req'] +def check_copilot_substitution(): + """干员替换(#92):塞1 由 黍1 顶替——匹配判可用 + 写 MAA 重写 + 边界不触发 + + 规则表见 copilot.SUB_RULES(force 档:账号有黍且按塞雷娅条目的要求判 + 「等价练度」即换,塞雷娅自己有没有、达不达标都不看)。匹配侧与写入侧 + 必须同一个判定(sub_rule_for),两边口径不能漂。 + """ + from core import copilot + + def own(name, elite=2, level=60, main=7, mastery=(3, 0, 0), skill_known=True): + c = {'charId': 'x', 'name': name, 'rarity': 6, 'elite': elite, + 'level': level, 'skillLevel': main, 'favor': 0, 'skin': None, + 'skills': ([{'id': 's%d' % (i + 1), 'name': '', 'mastery': m} + for i, m in enumerate(mastery)] + if skill_known else []), + 'modules': []} + return copilot.build_owned({'chars': [c]}) + + saria1 = {'name': '塞雷娅', 'skill': 1, + 'requirements': {'elite': 2, 'level': 60, 'skill_level': 7}} + content = { + 'stage_name': 'act55side_s01', + 'opers': [dict(saria1)], + 'groups': [{'name': '奶', 'opers': [dict(saria1)]}], + # 两条动作都按名字点名塞雷娅:替换后名字要跟着改(无坐标的动作 + # MaaCore 拿名字去场上找人,不改就指空) + 'actions': [{'type': 'UseSkill', 'name': '塞雷娅'}, + {'type': 'Deploy', 'name': '塞雷娅', 'location': [4, 4], + 'direction': 'Right'}], + } + shu = own('黍') + + # ① 没有 黍:塞雷娅 缺卡,顶层 + 组各计一个 missing → blocked + m, miss, tr, _t, detail, _s, _w = copilot.match_operation(content, {}) + assert m == 'blocked' and len(miss) == 2, (m, miss) + assert all(d.get('sub') is None for d in detail) + + # ② 有等价练度的 黍:整份作业判 ready(缺卡/练度不足都不再计),detail + # 带替换标记给前端在详情里标注「由黍1替换塞1」 + m, miss, tr, _t, detail, _s, _w = copilot.match_operation(content, shu) + assert m == 'ready' and not miss and not tr, (m, miss, tr) + assert detail[0]['sub'] == {'name': '黍', 'skill': 1}, detail[0]['sub'] + assert detail[0]['ok'] is True and detail[0]['owned'] is False + assert detail[1]['group'] is True and detail[1]['ok'] is True + + # ③ 写入侧重写:顶层与干员组里的塞雷娅都换成黍,requirements 原样保留, + # 原始 content 不被改动(预取缓存跨账号共用,不能就地污染) + out, notes = copilot.apply_substitutions(content, shu) + assert out is not content and content['opers'][0]['name'] == '塞雷娅', \ + '原始 content 不能被就地改掉' + assert out['opers'][0]['name'] == '黍' and out['opers'][0]['skill'] == 1 + assert out['opers'][0]['requirements'] == saria1['requirements'] + assert out['groups'][0]['opers'][0]['name'] == '黍' + assert all(a['name'] == '黍' for a in out['actions']), out['actions'] + assert content['actions'][0]['name'] == '塞雷娅' # 原始 content 未被改动 + assert notes and '黍' in notes[0], notes + _assert_maa_parsable(out) + # 没命中时不拷贝直接原样返回 + out2, notes2 = copilot.apply_substitutions(content, {}) + assert out2 is content and not notes2 + + # ④ 边界:不换的几种情况 + # 黍练度不到(精一 60 ≠ 精二 60) + weak = own('黍', elite=1, level=60) + assert copilot.sub_rule_for(saria1, weak) is None + # 专三要求但 黍1 没专精 + m3 = {'name': '塞雷娅', 'skill': 1, + 'requirements': {'skill_level': 9}} + assert copilot.sub_rule_for(m3, own('黍', mastery=(0, 0, 0))) is None + assert copilot.sub_rule_for(m3, shu) is not None, '黍1 专三该顶专三要求' + # 技能号不是 1 不换(MaaCore 里 skill 缺省 0 = 不指定,也不算塞1) + for sk in (0, 2, 3): + assert copilot.sub_rule_for({'name': '塞雷娅', 'skill': sk}, shu) is None, sk + # 黍已被作者写进阵容:再换会出现同名重复条目,不换 + both = {'stage_name': 'x', 'actions': [], + 'opers': [dict(saria1), {'name': '黍', 'skill': 1}]} + assert copilot.sub_rule_for(saria1, shu, + siblings=['塞雷娅', '黍']) is None + m, miss, *_ = copilot.match_operation(both, shu) + assert len(miss) == 1 and miss[0] == '塞雷娅', (m, miss) + outb, notesb = copilot.apply_substitutions(both, shu) + assert not notesb and outb is both + # 干员组内已有黍:组内成员不换(顶层无塞雷娅,整份不动) + gonly = {'stage_name': 'x', 'actions': [], 'opers': [], + 'groups': [{'name': '奶', 'opers': [dict(saria1), + {'name': '黍', 'skill': 1}]}]} + outg, notesg = copilot.apply_substitutions(gonly, shu) + assert not notesg and outg is gonly + + # ⑤ force 档:塞雷娅 自己有且达标也照样换(黍是上位替代) + bothok = {**shu, **own('塞雷娅')} + r = copilot.sub_rule_for(saria1, bothok) + assert r is not None and r['kind'] == 'force' + dop = copilot.detail_opers({'opers': [dict(saria1)]}, bothok) + assert dop[0]['owned'] is True and dop[0]['ok'] is True + assert dop[0]['sub'] == {'name': '黍', 'skill': 1} + + # ⑥ MAA 识别导入的账号(无技能数据):只比精英化/等级,替换同样成立 + maa_shu = own('黍', skill_known=False) + assert copilot.sub_rule_for({'name': '塞雷娅', 'skill': 1}, maa_shu) is not None + # 没带账号上下文的详情不判替换(前端不标) + assert copilot.detail_opers({'opers': [dict(saria1)]})[0]['sub'] is None + + def _assert_maa_parsable(content): """按 MaaCore CopilotConfig::parse 的致命校验复检,非法就抛 AssertionError @@ -4776,6 +4880,7 @@ def main(): r.check('B45 资源包缺分区(EX/S 推断/默认不补前置/突袭不降级)', lambda: check_stage_infer(tmp)) r.check('B46 牛杂小工具(小游戏/活动商店/黑名单位置/卡教程提示)', lambda: check_maa_tool(tmp)) r.check('B47 卫戍协议(核心检测/版本目录扫描/状态兜底/MAA 连接默认值/选项清洗/核心补丁)', lambda: check_garrison(tmp)) + r.check('B48 干员替换(塞1←黍1:匹配/写入/干员组/不触发边界)', check_copilot_substitution) finally: shutil.rmtree(tmp, ignore_errors=True) From e78606282dd6d9d5f9c9f582feca6b26300c49b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=99=93=E4=B8=B6=E6=A2=A6=E4=B8=B6=E4=BB=81?= <74444214+Daydreamer114@users.noreply.github.com> Date: Sat, 21 Nov 2026 07:02:05 +0800 Subject: [PATCH 3/8] =?UTF-8?q?fix(garrison):=20=E9=80=9F=E5=88=B7?= =?UTF-8?q?=E9=80=89=E9=A1=B9=E6=8C=89=E8=B4=A6=E5=8F=B7=E6=8C=81=E4=B9=85?= =?UTF-8?q?=E5=8C=96=EF=BC=8C=E9=87=8D=E5=90=AF=E4=B8=8D=E5=86=8D=E5=9B=9E?= =?UTF-8?q?=E9=BB=98=E8=AE=A4=20(#118)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 用户在面板调过的选项(模式/速度/胜场等)原本只存页面内存 (S.garOpts),重启程序全部回默认——「每个实例调的 2.5×、6 胜重启 全丢」,9731 设普通模拟重启后变回极速也是同一根因(发送链实测无恙: 浏览器拦截 POST 证实 mode 原样送达,核心 lobby/mode 页也有 standard 分支)。 - 账号 json 顶层 garrisonOpts:save_opts 以账号当前生效值为基底叠加 传入项再清洗(防只传部分字段时把别的键锁到全局兜底值),与「从 MAA 抄来的裸默认」逐键 diff 只存不同的键——没改过的键永远跟着 MAA 配置走,改回默认的键自动剔除;/api/garrison/opts 落盘。 - 前端 collectGarOpts 改动即保存(串行队列,同 saveSettings——连改 几项时并发保存会被后到的旧请求覆盖,实测踩过)。 B47 第 9 节:差异键落盘 / defaults overlay 生效 / 部分字段不污染 / 改回默认剔除。浏览器实测:改 标准+2.5×+6胜 → 重载页面(=重启) 三项保留、未改键(设备/地址/截图方式)继续来自 MAA。 --- backend/core/api.py | 7 ++++ backend/core/garrison.py | 60 +++++++++++++++++++++++++++++++---- frontend/app.js | 14 +++++++- tools/smoketest/smoke_test.py | 20 ++++++++++++ 4 files changed, 94 insertions(+), 7 deletions(-) diff --git a/backend/core/api.py b/backend/core/api.py index 4dcc2c7..6e7e297 100644 --- a/backend/core/api.py +++ b/backend/core/api.py @@ -598,6 +598,12 @@ def api_garrison_download(_q, _body): return garrison.start_download() +def api_garrison_opts(_q, body): + """保存用户改过的速刷选项(按账号持久化,只存与 MAA 默认不同的键)""" + body = body or {} + return garrison.save_opts(_account_for(body.get('file')), body.get('options') or {}) + + def _garrison_options(q, body): """test/start/resume 共用:账号 + 前端提交的连接选项""" body = body or {} @@ -892,6 +898,7 @@ def api_export(_q, body): # 卫戍协议·策略刻章速刷 '/api/garrison/status': api_garrison_status, '/api/garrison/download/start': api_garrison_download, + '/api/garrison/opts': api_garrison_opts, '/api/garrison/test': api_garrison_test, '/api/garrison/start': api_garrison_start, '/api/garrison/resume': api_garrison_resume, diff --git a/backend/core/garrison.py b/backend/core/garrison.py index e149427..b65e059 100644 --- a/backend/core/garrison.py +++ b/backend/core/garrison.py @@ -192,12 +192,8 @@ def _maa_dir_for(file: str) -> str: return settings.load()['maaDir'] -def defaults(file: str): - """速刷默认参数:从账号绑定 MAA 的连接配置里抄。 - - 返回 ``(options, 来源)``;MAA 配置读不到时给核心自己的兜底值 - (mumu + 16384),前端会展示来源让用户知道这份默认值从哪来。 - """ +def _maa_defaults(file: str): + """从账号绑定 MAA 的连接配置里抄出来的裸默认值(不含用户偏好 overlay)""" opts = { 'device': 'mumu', 'mode': 'quick', 'speed': 1.5, 'medalWins': 3, 'adbAddress': '127.0.0.1:16384', 'adbPath': '', @@ -227,6 +223,58 @@ def defaults(file: str): return opts, src +# 可持久化的速刷选项键(账号 json 里的 garrisonOpts 只认这些) +OPT_KEYS = ('device', 'mode', 'adbAddress', 'adbPath', 'medalWins', 'speed', + 'screenshotMethod', 'pcUiScale') + + +def _stored_opts(file: str) -> dict: + """账号 json 里存过的用户改动(garrisonOpts),按白名单取""" + if not file: + return {} + try: + from . import accounts + snap = accounts.get_account(file) + st = snap.get('garrisonOpts') or {} + return {k: st[k] for k in OPT_KEYS + if isinstance(st, dict) and k in st} + except Exception: + return {} + + +def defaults(file: str): + """速刷默认参数:MAA 配置抄来的基底 + 账号里存过的用户改动。 + + 返回 ``(options, 来源)``。用户在面板改过的选项按账号持久化 + (save_opts 只存与 MAA 基底不同的键),重启不丢;没改过的键 + 继续跟随 MAA 配置。 + """ + opts, src = _maa_defaults(file) + stored = _stored_opts(file) + for k in OPT_KEYS: + if k in stored and k in opts: + opts[k] = stored[k] + return opts, src + + +def save_opts(file: str, options: dict) -> dict: + """用户改的速刷选项写回账号 json。 + + 以账号**当前生效值**为基底叠加传入项再清洗(只传一个键不会把别的 + 键锁到全局兜底值),然后与「MAA 抄来的裸默认」逐键比对,只存不同 + 的键——改回默认值的键自动剔除,没动过的键永远跟着 MAA 配置走。 + 返回合并后的生效默认值(含实际存了哪些键,便于排查)。 + """ + cur, _src0 = defaults(file) + clean = sanitize({**cur, **(options or {})}) + base, _src = _maa_defaults(file) + diff = {k: clean[k] for k in OPT_KEYS if clean.get(k) != base.get(k)} + from . import accounts as _acc + _acc.save_pref(file, {'garrisonOpts': diff}) + merged, src = defaults(file) + return {'defaults': merged, 'fromMaa': src, 'saved': diff} + + def sanitize(body: dict) -> dict: """前端提交的选项清洗:只放行核心认识的枚举与范围,其余回默认""" body = body or {} diff --git a/frontend/app.js b/frontend/app.js index 50d29af..84d6a15 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -4057,10 +4057,22 @@ function collectGarOpts() { medalWins: Number(v('#gar-wins')) || 3, speed: Number(v('#gar-speed')) || 1.5, pcUiScale: Number(v('#gar-scale')) || 90, screenshotMethod: v('#gar-shot'), }; - S.garOpts[S.current] = o; // 记住用户的改动,切号再回来还在 + S.garOpts[S.current] = o; // 会话内缓存:切号再回来还在 + // 持久化到账号 json(只存与 MAA 默认不同的键),重启不再回默认。 + // 串行排队(同 saveSettings):连续改几项时后到的旧请求会覆盖新值 + garSaveOptsQ(S.current, o); return o; } +/* 速刷选项保存队列:按改动顺序落盘,失败吞掉不打扰(面板仍按当前值跑) */ +let _garOptsSaveQ = Promise.resolve(); +function garSaveOptsQ(file, options) { + if (!file) return; + const run = () => api('/api/garrison/opts', { file, options: options }) + .catch(() => {}); + _garOptsSaveQ = _garOptsSaveQ.then(run, run); +} + function garAppendLog(items) { const box = $('#gar-log'); if (!box || !Array.isArray(items)) return; diff --git a/tools/smoketest/smoke_test.py b/tools/smoketest/smoke_test.py index f8061a0..1e5912d 100644 --- a/tools/smoketest/smoke_test.py +++ b/tools/smoketest/smoke_test.py @@ -4813,6 +4813,26 @@ def _write_maa(kind, addr, adb=''): with open(svc, encoding='utf-8') as f: assert f.read() == 'untouched core', '脱靶时一个字节都不能动' + # 9) 速刷选项按账号持久化:save_opts 只存差异键、defaults 生效 overlay、 + # 改回默认自动剔除——用户「调了 2.5×/6 胜重启全回默认」的病根 + assert '/api/garrison/opts' in api.ROUTES + _write_maa('MuMuEmulator12', '127.0.0.1:16416') + r = garrison.save_opts('g-acc.json', {'mode': 'standard', 'speed': 2.5, + 'medalWins': 6}) + assert set(r['saved']) == {'mode', 'speed', 'medalWins'}, r['saved'] + with open(acc, encoding='utf-8') as f: + snap = json.load(f) + assert snap['garrisonOpts'] == r['saved'], snap.get('garrisonOpts') + # 重启语义:重新读账号(defaults)就能拿回用户改动,未改的键跟随 MAA + d2, _src = garrison.defaults('g-acc.json') + assert d2['mode'] == 'standard' and d2['speed'] == 2.5 and d2['medalWins'] == 6, d2 + assert d2['device'] == 'mumu' and d2['screenshotMethod'] == 'fast' + assert d2['adbAddress'] == '127.0.0.1:16416', d2 + # 改回默认值的键自动剔除 + r = garrison.save_opts('g-acc.json', {'mode': 'quick', 'speed': 2.5, 'medalWins': 6}) + assert set(r['saved']) == {'speed', 'medalWins'}, r['saved'] + assert '/api/garrison/opts' in api.ROUTES + # ---------------------------------------------------------------- 入口 From 270b0e960fa1f06f0bd4785c439da8d0b077eebc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=99=93=E4=B8=B6=E6=A2=A6=E4=B8=B6=E4=BB=81?= <74444214+Daydreamer114@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:57:35 +0800 Subject: [PATCH 4/8] =?UTF-8?q?feat(garrison):=20=E6=A0=B8=E5=BF=83?= =?UTF-8?q?=E4=BF=9D=E6=8C=81=E6=9C=80=E6=96=B0=20+=20v1.1.5=20=E9=80=82?= =?UTF-8?q?=E9=85=8D=E2=80=94=E2=80=94=E5=90=AF=E5=8A=A8/=E5=81=9C?= =?UTF-8?q?=E6=AD=A2=E5=90=8E=E6=A3=80=E6=9F=A5=EF=BC=8C=E9=80=82=E9=85=8D?= =?UTF-8?q?=E8=A1=A8=E5=86=85=E8=87=AA=E5=8A=A8=E5=8D=87=E7=BA=A7=20(#121)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更新时机(不做周期轮询):程序启动时、速刷任务全部停止后(stop 触发 检查器,等所有账号出 BUSY 全闲才动手)各查一次本机小黑盒记录。 选版规则:候选 = 本机记录 ∪ 已验证直链(1.1.5 / 1.1.4 两档,整包 sha256 锚定;同版本记录优先——带官方逐文件清单)。取第一个「在 patches.json 硬编码的 adaptedVersions 表内 且 比已装新」的版本—— 记录里只有表外新版(如未来的 1.1.6)时,升/装表内最新(1.1.5), 而不是落到最老的 1.1.4;表外版本零字节下载。升级失败旧版原样可用, 且防降级(≤已装版本的候选一律跳过)。 v1.1.5 补丁锚点重挖(上游重排混淆名、连文案都换了;名字比对 xn 已 自带 ≥3 字 1 字容差,上游修好了短名问题):补 confirm-ready 特征词、 拉丁名 ≥6 字 2 字容差、免费领取信详情大字、策略页详情走 xn 容差 四条 -v115 规则,与 v1.1.4 规则靠脱靶跳过共存。前端升级横幅 (#gar-update-bar,进度/未更新原因)+ 完成一次性 toast。 验证:真实 v1.1.5 副本 4+4 应用/幂等/语法;xn/G 行为用例 10/10 (拉丁错 2 字、Mist 系、缪尔赛思±1、耶拉/雅拉不互配);真机升级 1.1.4→1.1.5 → 宿主 idle/31;B47 第 9-11 节(持久化 / 选版 / 表外零流量)+ 全套冒烟绿。 --- backend/core/garrison.py | 36 ++++++++- backend/core/garrisondl.py | 129 ++++++++++++++++++++++++++++---- backend/main.py | 8 ++ frontend/app.js | 35 +++++++++ frontend/index.html | 2 + frontend/style.css | 10 +++ resources/garrison/patches.json | 31 +++++++- tools/smoketest/smoke_test.py | 78 +++++++++++++++++++ 8 files changed, 311 insertions(+), 18 deletions(-) diff --git a/backend/core/garrison.py b/backend/core/garrison.py index b65e059..41083ad 100644 --- a/backend/core/garrison.py +++ b/backend/core/garrison.py @@ -466,6 +466,8 @@ def status(file: str) -> dict: 核心缺失时带 ``needsDownload`` + 下载进度(garrisondl 的状态机), 前端据此自动开始下载并显示进度条;下载是全局一份(不分账号)。 + 核心升级(保持最新)不在轮询里做:由「程序启动」和「速刷任务全部 + 停止后」(stop())两个事件触发 garrisondl.check_update()。 """ node = node_exe() core = core_dir() @@ -525,7 +527,39 @@ def stop(file: str) -> dict: h = host_of(file) if not _alive(h): raise ValueError('当前没有速刷任务在跑') - return _call(h, 'POST', '/api/stop', {}, timeout=15) # type: ignore[arg-type] + r = _call(h, 'POST', '/api/stop', {}, timeout=15) # type: ignore[arg-type] + # 任务被停止 = 检查更新的触发器:等这个号停稳,若没有任何账号还在 + # 跑,就后台看一眼本机记录有没有新版(全部停着升级最安全——不会有 + # 宿主正用旧核心打对局) + threading.Thread(target=_check_update_when_idle, daemon=True, + name='garrison-upd-check').start() + return r + + +def _check_update_when_idle(timeout=45.0): + """等全部速刷任务停稳(stopping→stopped),都闲下来了就查一次更新。""" + deadline = time.time() + timeout + while time.time() < deadline: + with _lock: + hosts = list(_HOSTS.items()) + busy_any = False + for _f, h in hosts: + if not _alive(h): + continue + try: + if (_state_of(h).get('state') or {}).get('status') in BUSY: + busy_any = True + break + except Exception: + busy_any = True # 拿不到状态先当它在跑,别在忙时动手 + break + if not busy_any: + try: + garrisondl.check_update() + except Exception: + pass + return + time.sleep(2.0) def stop_all(timeout=6.0): diff --git a/backend/core/garrisondl.py b/backend/core/garrisondl.py index c762e08..01d0223 100644 --- a/backend/core/garrisondl.py +++ b/backend/core/garrisondl.py @@ -36,17 +36,34 @@ PKG_ID = 'ai-desktop.arknights-medal-farm' PKG_DIR_RE = re.compile(r'^medal-farm-v(\d+(?:\.\d+)*)$') -FALLBACK = { - 'version': '1.1.4', - 'url': ('https://static.max-c.com/heybox/desktop/extension/' - 'ai-desktop.arknights-medal-farm/version/1.1.4/' - '970f8e97e13fd427abf63289c53c8a68765d4ac870f745c5f3c58250a25829ff-' - '20261118T140851382Z/ai-desktop.arknights-medal-farm-1.1.4.hbext'), - 'sha256': '970f8e97e13fd427abf63289c53c8a68765d4ac870f745c5f3c58250a25829ff', - 'bytes': 61071704, - 'files': None, - 'source': '官方直链(回退)', -} +# 已验证直链(匿名可下载,整包 sha256 锚定):按版本降序作回退链—— +# 记录里的新版不在适配表时,装「表内最新」的直链版本而不是一味落到最老。 +FALLBACKS = [ + { + 'version': '1.1.5', + 'url': ('https://static.max-c.com/heybox/desktop/extension/' + 'ai-desktop.arknights-medal-farm/version/1.1.5/' + '596196307afbdc4c102d66b85b7210ebb292612fd6f1e0d2d2c51ab83445c8b0-' + '20261119T163854129Z/ai-desktop.arknights-medal-farm-1.1.5.hbext'), + 'sha256': '596196307afbdc4c102d66b85b7210ebb292612fd6f1e0d2d2c51ab83445c8b0', + 'bytes': 61083080, + 'files': None, + 'source': '官方直链(回退)', + }, + { + 'version': '1.1.4', + 'url': ('https://static.max-c.com/heybox/desktop/extension/' + 'ai-desktop.arknights-medal-farm/version/1.1.4/' + '970f8e97e13fd427abf63289c53c8a68765d4ac870f745c5f3c58250a25829ff-' + '20261118T140851382Z/ai-desktop.arknights-medal-farm-1.1.4.hbext'), + 'sha256': '970f8e97e13fd427abf63289c53c8a68765d4ac870f745c5f3c58250a25829ff', + 'bytes': 61071704, + 'files': None, + 'source': '官方直链(回退)', + }, +] +FALLBACK = FALLBACKS[-1] # 最老一档,兼容旧引用 + MIN_TOTAL_BYTES = 50 * 1024 * 1024 MIN_FILE_COUNT = 100 @@ -141,7 +158,25 @@ def record_candidates(): def candidates(): - return record_candidates() + [dict(FALLBACK)] + # 全部下载源:本机记录 ∪ 已验证直链,按版本降序(同版本记录优先—— + # 带官方逐文件 sha256 清单,校验更严) + recs = record_candidates() + seen = {r['version'] for r in recs} + out = recs + [dict(f) for f in FALLBACKS if f['version'] not in seen] + out.sort(key=lambda r: ver_key(r['version']), reverse=True) + return out + +def _pick_candidate(installed: str): + # 该装哪个:候选里第一个「适配表内且比已装新」的;没有返回 None。 + # 记录里只有表外新版(如 1.1.6)时,顺着回退链选表内最新的直链版本 + # (如 1.1.5),而不是一味落到最老的 1.1.4。 + for rec in candidates(): + if not _is_adapted(rec['version']): + continue + if installed and ver_key(rec['version']) <= ver_key(installed): + continue + return rec + return None # ---------------------------------------------------------------- 引擎 @@ -274,8 +309,34 @@ def _extract_verify(hbext, out_dir, manifest=None): return len(got) +def _adapted_versions(): + """patches.json 里硬编码的「已适配核心版号」表;读不到按无限制处理 + + 更新器只升到表内版本(表外新版等补丁适配后再放行),比在暂存区上 + 数补丁命中更直白,也省一次 61MB 的无效下载。 + """ + p = os.path.join(settings.RES, 'resources', 'garrison', 'patches.json') + try: + with open(p, encoding='utf-8') as f: + v = (json.load(f) or {}).get('adaptedVersions') + return [str(x) for x in v] if isinstance(v, list) else None + except (OSError, ValueError): + return None + + +def _is_adapted(version: str) -> bool: + allowed = _adapted_versions() + return allowed is None or str(version) in allowed + + def _install(hbext, version, manifest=None): - """解压校验 → 前置校验 → 原子落位 garrison/medal-farm-v<版本>;失败不伤旧版。""" + """解压校验 → 前置校验 → 补丁兼容门禁 → 原子落位;失败不伤旧版。 + + 门禁:上游换版本常把混淆产物整个重排(v1.1.4 → v1.1.5 连文案都换了), + 我们的补丁一条都命不中=这个版本没适配过,升上去等于把已修的 OCR + 容错/弹窗识别全丢掉。宁可停在旧版等适配——全新安装同理会顺着回退 + 链落到已适配的版本上。 + """ pkg = os.path.join(garrison_dir(), 'medal-farm-v%s' % version) stage = os.path.join(download_dir(), 'stage') shutil.rmtree(stage, ignore_errors=True) @@ -330,18 +391,51 @@ def state() -> dict: def start() -> dict: - """启动(或继续)下载;已在跑/已完成时原样返回。返回 state 快照。""" + """启动(或继续)下载/升级;已在跑/已是最新时原样返回。返回 state 快照。 + + 没装过 → 走下载链装「表内最新」(记录 ∪ 已验证直链);装着旧版且 + 候选里有「适配表内且更新」的版本(_pick_candidate)→ 升级;升级 + 失败不影响已装版本继续使用。 + """ with _LOCK: running = _RUNNING[0] if running: return state() - if _installed_pkg_dir(): + cur = _installed_pkg_dir() + if cur and _pick_candidate(cur) is None: _set(stage='done', error='', endedAt=time.time()) return state() threading.Thread(target=_run, daemon=True, name='garrison-dl').start() return state() +def check_update() -> None: + """看一眼有没有可升的目标(适配表内且比已装新),有就后台升级。 + + 触发时机由调用方决定:程序启动时(main)、速刷任务全部停止后 + (garrison.stop)。没有可升目标就是一次本地扫描,零成本;记录里的 + 新版不在适配表时记一行日志、不动已装版本。 + """ + with _LOCK: + running = _RUNNING[0] + if running: + return + cur = _installed_pkg_dir() + if not cur: + return + target = _pick_candidate(cur) + if not target: + recs = record_candidates() + if recs and ver_key(recs[0]['version']) > ver_key(cur) \ + and not _is_adapted(recs[0]['version']): + applog.log('[卫戍协议] 核心新版本 v%s 尚无对应补丁(已适配:%s),暂不更新' + % (recs[0]['version'], '/'.join(_adapted_versions() or ['?']))) + return + applog.log('[卫戍协议] 检测到核心新版本(本机 v%s → v%s),后台升级' + % (cur, target['version'])) + threading.Thread(target=_run, daemon=True, name='garrison-upgrade').start() + + def _run(): with _LOCK: if _RUNNING[0]: @@ -364,7 +458,12 @@ def _run(): shutil.rmtree(lock_dir, ignore_errors=True) os.mkdir(lock_dir) + installed = _installed_pkg_dir() for rec in candidates(): + if not _is_adapted(rec['version']): + continue # 版号不在适配表:等补丁,不下载 + if installed and ver_key(rec['version']) <= ver_key(installed): + continue # 防降级:已装新版时旧记录/回退直链一律不装 label = 'v%s(%s)' % (rec['version'], rec['source']) try: _set(stage='connecting', source=rec['source'], version=rec['version'], diff --git a/backend/main.py b/backend/main.py index cc267e0..3fd7639 100644 --- a/backend/main.py +++ b/backend/main.py @@ -400,6 +400,14 @@ def main(): # 先完成初始化再起 HTTP:窗口期打进来的 /api/app/install 会因 quit hook # 未装而「前端收到已拉起安装、进程永远不退」(#61) settings.ensure_dirs() # config/ 与 debug/ 在启动时才建(import 不建) + # 卫戍协议核心「保持最新」:启动时看一眼本机小黑盒记录,有新版就后台 + # 升级(幂等;下载校验失败不动已装版本) + try: + from core import garrisondl as _gdl + threading.Thread(target=_gdl.check_update, daemon=True, + name='garrison-upd-check').start() + except Exception: + pass # 程序自更新:装完后由 api 层调 install(),需要让整个进程退出, # 而 api 不能 import main,所以反过来把退出函数注册进去 appupdate.set_quit_hook(lambda reason: _quit(0, reason)) diff --git a/frontend/app.js b/frontend/app.js index 84d6a15..2930b87 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -4249,6 +4249,7 @@ async function renderGarrison(force) { return; } _garDlStuck = 0; + _garUpdActive = paintGarUpdateBar(d); // 后台升级新版时先亮横幅 if (!d.nodeOk || !d.ready) { showGarEmpty(d); return; } hideGarEmpty(); paintGarInputs(); @@ -4283,12 +4284,46 @@ async function garTick() { return; } _garDlStuck = 0; + // 保持最新:已装核心但后台在升级 → 横幅;升级完成 → 一次性提示重启生效 + const updActive = paintGarUpdateBar(d); + if (_garUpdActive && !updActive && (d.download || {}).stage === 'done') { + toast(`核心已更新到 v${(d.download || {}).version || ''},重启程序后生效`, 'ok', 6000); + } + _garUpdActive = updActive; if (wasDownloading) { renderGarrison(true); return; } // 刚下载完:重建整面板 if (!d.ready) return; paintGarState(d); } catch (e) { /* 断线别刷屏:下一轮再试 */ } } +/* 保持最新的横幅:coreOk 但下载状态机在跑(升级新版)时显示进度; + 升级被兼容门禁挡下(error)也亮一条,让用户知道为什么停在旧版 */ +let _garUpdActive = false; +function paintGarUpdateBar(d) { + const bar = $('#gar-update-bar'); + if (!bar) return false; + const dl = d.download || {}; + const active = d.coreOk && ['connecting', 'downloading', 'verifying'].includes(dl.stage); + if (active) { + let text = `核心更新中 v${dl.version || ''}`; + if (dl.stage === 'downloading') { + text += ` · 下载 ${dl.total ? (100 * dl.done / dl.total).toFixed(0) : '?'}%(${dl.done >> 20}/${(dl.total || dl.done) >> 20} MB)`; + } else if (dl.stage === 'verifying') { + text += ` · 校验 ${dl.files}/${dl.filesTotal || '…'}`; + } else { + text += `(${dl.source || ''})`; + } + bar.textContent = text; + bar.hidden = false; + } else if (d.coreOk && dl.stage === 'error' && dl.error) { + bar.textContent = `核心更新未完成:${dl.error.split('\n')[0]}`; + bar.hidden = false; + } else { + bar.hidden = true; + } + return active; +} + async function garAction(kind) { if (!S.current) { toast('先在左侧选一个账号', 'err'); return; } const opts = collectGarOpts(); diff --git a/frontend/index.html b/frontend/index.html index b64879a..417b587 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -267,6 +267,8 @@

搜一个关卡开始

卫戍协议—
+ +
diff --git a/frontend/style.css b/frontend/style.css index 7bc0880..ed8bb5f 100644 --- a/frontend/style.css +++ b/frontend/style.css @@ -855,6 +855,16 @@ input:focus, select:focus, button:focus-visible { outline: none; } } .gar-prog-text { margin-top: 7px; font-size: 11px; color: var(--text-3); } +/* 保持最新:后台升级新版核心时的横幅(不打断当前面板) */ +.gar-update-bar { + margin: 0 2px 10px; padding: 8px 12px; + border-radius: 10px; + border: 1px solid rgba(245, 185, 85, 0.35); + background: rgba(245, 185, 85, 0.08); + color: var(--amber); font-size: 12px; +} +.gar-update-bar[hidden] { display: none; } + .gar-form { margin-top: 12px; display: flex; flex-direction: column; gap: 8px; } .gar-form .field-row { flex: 0 0 auto; } .gar-form input[type=text] { diff --git a/resources/garrison/patches.json b/resources/garrison/patches.json index 2f17fd6..9f37b80 100644 --- a/resources/garrison/patches.json +++ b/resources/garrison/patches.json @@ -1,6 +1,9 @@ { - "coreVersion": "1.1.4", - "note": "对第三方核心 service.mjs 的最小文本补丁。核心是 GPL-3.0-or-later 的报混淆包,不进仓库、由 garrisondl.py 按版本下载;这里只存纯文本替换规则,启动前幂等应用(首次改动前留 service.mjs.orig 备份)。规则脱靶(核心升级换了写法)只记日志跳过,不影响启动。", + "note": "对第三方核心 service.mjs 的最小文本补丁。核心是 GPL-3.0-or-later 的报混淆包,不进仓库、由 garrisondl.py 按版本下载;adaptedVersions 硬编码已适配的核心版号——更新器只升到表内版本(表外新版等适配);这里只存纯文本替换规则,启动前幂等应用(首次改动前留 service.mjs.orig 备份)。规则脱靶(核心升级换了写法)只记日志跳过,不影响启动。", + "adaptedVersions": [ + "1.1.4", + "1.1.5" + ], "patches": [ { "id": "confirm-ready-temp-zone", @@ -25,6 +28,30 @@ "why": "策略页选卡(如「缪尔赛思」):点开卡片后核心在右侧详情栏 OCR 策略名核对(Ar 函数),原本用纯 includes 零容错——与购买路径的 Zr 完全两套标准。详情名 OCR 错一个形近字即 3 次重读全挂 →「策略详情名称未能对应目标卡片」跳过该卡 → 拉黑后列表滚到头 →「已到策略列表末尾,但尚有策略进度未核实」整局停止。改为 includes 不中再走 Zr 容差(≥3 字名 1 字差、≥6 字拉丁名 2 字差;61 个策略名中距离 ≤1 的名字对全是 ≤2 字名,Zr 对其零容差,无互配风险)。", "find": "return b.find(M=>A(k).includes(A(M.name)))", "replace": "return b.find(M=>A(k).includes(A(M.name))||Zr(A(k),A(M.name)))" + }, + { + "id": "confirm-ready-temp-zone-v115", + "why": "v1.1.5 版同款:confirm-ready 判定补认「确认准备就绪吗?临时整备区…」弹窗的特征词(上游 v1.1.5 重排了混淆名,c→o、f→h,规则与 1.1.4 的互不命中,靠 miss 跳过共存)。", + "find": "o(/确认准备/)&&o(/剩余资金|未使用的|指令/)?h=\"confirm-ready\"", + "replace": "o(/确认准备/)&&(o(/剩余资金|未使用的|指令/)||o(/临时整备区|召唤物|自动销毁/))?h=\"confirm-ready\"" + }, + { + "id": "latin-tolerance-v115", + "why": "v1.1.5 的名字比对 xn 已自带「≥3 字名 1 字容差」(蕾缪安等 3 字名上游修了),但拉丁名仍只容 1 字差——小字号拉丁名(Miss.Christine、核心数据里没有的新预备干员 Mist 系 7-8 字母名)OCR 常错 2+ 字。给 ≥6 字拉丁/数字名放宽到容 2 字(v1.1.5 数据里拉丁名两两编辑距离远大于 2,无混淆)。", + "find": "if(O.length<3)return!1;for(let W=0;W+O.length<=M.length;W++){let ne=0;for(let V=0;V=6?2:1;for(let W=0;W+O.length<=M.length;W++){let ne=0;for(let V=0;VM(y).includes(M(O.name)))", + "replace": "return v.find(O=>M(y).includes(M(O.name))||xn(M(y),M(O.name)))" } ] } diff --git a/tools/smoketest/smoke_test.py b/tools/smoketest/smoke_test.py index 1e5912d..aac743e 100644 --- a/tools/smoketest/smoke_test.py +++ b/tools/smoketest/smoke_test.py @@ -4833,6 +4833,84 @@ def _write_maa(kind, addr, adb=''): assert set(r['saved']) == {'speed', 'medalWins'}, r['saved'] assert '/api/garrison/opts' in api.ROUTES + # 10) 保持最新:_pick_candidate 选「适配表内且比已装新」的目标—— + # 记录只有表外新版(1.1.6)时回退表内最新(1.1.5);start 短路/升级 + # 路径;表外版本零字节下载(monkeypatch candidates 做全链隔离) + real_cands = garrisondl.candidates + real_records = garrisondl.record_candidates + try: + adapted = garrisondl._adapted_versions() + assert adapted and '1.1.4' in adapted and '1.1.5' in adapted, adapted + assert garrisondl._is_adapted('1.1.5') and not garrisondl._is_adapted('1.1.6') + + # 已最新(候选=已装)→ start() 短路 done,不起线程 + old_svc = os.path.join(garrisondl.garrison_dir(), 'medal-farm-v1.1.4', 'core') + os.makedirs(old_svc) + open(os.path.join(old_svc, 'service.mjs'), 'w').close() + garrisondl.candidates = lambda: [ + {'version': '1.1.4', 'url': 'x', 'sha256': None, 'bytes': None, + 'files': None, 'source': '小黑盒扩展记录'}] + snap = garrisondl.start() + assert snap['stage'] == 'done', snap + + # 有可升目标(1.1.5,URL 不可达)→ 升级链走完报错;不落盘、旧版保留 + garrisondl.candidates = lambda: [ + {'version': '1.1.5', + 'url': 'https://static.max-c.com/heybox/desktop/nonexistent-1.1.5.hbext', + 'sha256': None, 'bytes': None, 'files': None, 'source': '小黑盒扩展记录'}] + snap = garrisondl.start() + assert snap['stage'] != 'done', snap + for _ in range(60): + if garrisondl.state()['stage'] == 'error': + break + time.sleep(0.3) + st = garrisondl.state() + assert st['stage'] == 'error' and '1.1.5' in (st['error'] or ''), st + assert not os.path.exists(os.path.join(garrisondl.garrison_dir(), + 'medal-farm-v1.1.5')), '失败版本不能落盘' + assert os.path.isfile(os.path.join(old_svc, 'service.mjs')), '旧版必须原样保留' + + # _pick_candidate(真实直链链):记录只有表外 1.1.6 → 选表内最新 1.1.5 + garrisondl.candidates = real_cands + garrisondl.record_candidates = lambda: [ + {'version': '1.1.6', 'url': 'x', 'sha256': None, 'bytes': None, + 'files': None, 'source': '小黑盒扩展记录'}] + assert garrisondl._pick_candidate('1.1.4')['version'] == '1.1.5', '表外新版应回退表内最新' + assert garrisondl._pick_candidate('')['version'] == '1.1.5' + assert garrisondl._pick_candidate('1.1.5') is None + # check_update:候选只剩表外新版(连直链一起屏蔽)→ 不起线程零流量; + # (真实链路里记录 1.1.6 + 已装 1.1.4 会经直链升 1.1.5——上面 + # _pick_candidate 断言已覆盖该选版,这里不再真下载) + garrisondl.candidates = lambda: [ + {'version': '1.1.6', 'url': 'x', 'sha256': None, 'bytes': None, + 'files': None, 'source': '小黑盒扩展记录'}] + with garrisondl._LOCK: + garrisondl._DL['stage'] = 'done' + garrisondl.check_update() + time.sleep(1.5) + assert not garrisondl._RUNNING[0], '表外版本不应起下载线程' + + # 全新安装且候选只剩表外版本(连直链一起屏蔽):零字节下载直接报无源 + shutil.rmtree(garrisondl.garrison_dir(), ignore_errors=True) + with garrisondl._LOCK: + garrisondl._DL.update(stage='idle', done=0, total=0) + garrisondl.candidates = lambda: [ + {'version': '1.1.6', 'url': 'x', 'sha256': None, 'bytes': None, + 'files': None, 'source': '小黑盒扩展记录'}] + garrisondl.start() + for _ in range(20): + if garrisondl.state()['stage'] == 'error': + break + time.sleep(0.3) + st = garrisondl.state() + assert st['stage'] == 'error' and '1.1.6' not in (st['error'] or ''), st + assert st['error'].startswith('所有下载源都失败了'), st['error'][:30] + assert st['done'] == 0, '表外版本一个字节都不该下载' + finally: + garrisondl.candidates = real_cands + garrisondl.record_candidates = real_records + shutil.rmtree(garrisondl.garrison_dir(), ignore_errors=True) + # ---------------------------------------------------------------- 入口 From 6a62ddbd571d8fb1403a79e62b0c3ca5d1f280cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=99=93=E4=B8=B6=E6=A2=A6=E4=B8=B6=E4=BB=81?= <74444214+Daydreamer114@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:22:09 +0800 Subject: [PATCH 5/8] =?UTF-8?q?feat(garrison):=20v1.1.7=20=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=E2=80=94=E2=80=94=E5=8F=A0=E5=B1=82=E7=9B=AE=E6=A0=87?= =?UTF-8?q?=20+=20=E6=A8=A1=E6=8B=9F=E6=A8=A1=E5=BC=8F=E4=BB=85=E6=9E=81?= =?UTF-8?q?=E9=80=9F=20+=203=20=E6=9D=A1=E6=96=B0=E8=A1=A5=E4=B8=81=20(#12?= =?UTF-8?q?2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 上游 v1.1.7 变化:普通模拟移除(info 页硬检查 quick)、goal 注册表 新增 task-1..7 实验性叠层目标(100/50 层)、confirm-ready 上游已修。 - goal 透传:host.mjs / garrison.py GOALS 白名单 + sanitize + 前端下拉 - 模拟模式固定极速(上游已移除普通) - 3 条 v117 补丁:拉丁名容差、免费领取信详情、策略页详情容差 - FALLBACKS +1.1.7 直链;adaptedVersions +1.1.7 - stop() 无宿主时不再触发 _check_update_when_idle - B47 扩展:goal 白名单 / 适配表 / pick_candidate 断言 --- backend/core/garrison.py | 27 +++++++++++++++++++------ backend/core/garrisondl.py | 12 +++++++++++ frontend/app.js | 5 +++-- frontend/index.html | 16 ++++++++++++--- resources/garrison/host.mjs | 6 +++++- resources/garrison/patches.json | 21 ++++++++++++++++++- tools/smoketest/smoke_test.py | 36 +++++++++++++++++++++++++-------- 7 files changed, 102 insertions(+), 21 deletions(-) diff --git a/backend/core/garrison.py b/backend/core/garrison.py index 41083ad..996c5f0 100644 --- a/backend/core/garrison.py +++ b/backend/core/garrison.py @@ -42,6 +42,10 @@ PATCH_FILE = os.path.join(settings.RES, 'resources', 'garrison', 'patches.json') DEVICES = ('mumu', 'ldplayer', 'pc') +# 速刷目标(核心 goal 注册表,v1.1.7 起):medal=策略徽章(默认); +# task-N=实验性叠层目标(先锋服实测口径:task-1..5 为 100 层、task-6/7 为 50 层)。 +# 与 resources/garrison/host.mjs 的 GOALS 保持一致。 +GOALS = ('medal', 'task-1', 'task-2', 'task-3', 'task-4', 'task-5', 'task-6', 'task-7') SHOT_METHODS = ('auto', 'fast', 'adb') BUSY = ('running', 'starting', 'stopping') @@ -195,7 +199,7 @@ def _maa_dir_for(file: str) -> str: def _maa_defaults(file: str): """从账号绑定 MAA 的连接配置里抄出来的裸默认值(不含用户偏好 overlay)""" opts = { - 'device': 'mumu', 'mode': 'quick', 'speed': 1.5, 'medalWins': 3, + 'device': 'mumu', 'mode': 'quick', 'goal': 'medal', 'speed': 1.5, 'medalWins': 3, 'adbAddress': '127.0.0.1:16384', 'adbPath': '', 'screenshotMethod': 'auto', 'pcUiScale': 90, } @@ -224,7 +228,7 @@ def _maa_defaults(file: str): # 可持久化的速刷选项键(账号 json 里的 garrisonOpts 只认这些) -OPT_KEYS = ('device', 'mode', 'adbAddress', 'adbPath', 'medalWins', 'speed', +OPT_KEYS = ('device', 'mode', 'goal', 'adbAddress', 'adbPath', 'medalWins', 'speed', 'screenshotMethod', 'pcUiScale') @@ -287,6 +291,7 @@ def sanitize(body: dict) -> dict: return { 'device': device, 'mode': body.get('mode') if body.get('mode') in ('quick', 'standard') else 'quick', + 'goal': body.get('goal') if body.get('goal') in GOALS else 'medal', 'medalWins': 6 if str(body.get('medalWins')) == '6' else 3, 'speed': speed, 'adbAddress': str(body.get('adbAddress') or dft['adbAddress']).strip() or dft['adbAddress'], @@ -528,12 +533,22 @@ def stop(file: str) -> dict: if not _alive(h): raise ValueError('当前没有速刷任务在跑') r = _call(h, 'POST', '/api/stop', {}, timeout=15) # type: ignore[arg-type] - # 任务被停止 = 检查更新的触发器:等这个号停稳,若没有任何账号还在 - # 跑,就后台看一眼本机记录有没有新版(全部停着升级最安全——不会有 - # 宿主正用旧核心打对局) + _schedule_update_check() + return r + + +def _schedule_update_check(): + """速刷任务被停止后安排一次更新检查(后台、全闲才动手)。 + + 只在有宿主存在时才起线程:stop 失败(没有宿主)不应触发检查, + 否则会在不该动手的时刻(比如宿主都关了)意外开始升级。 + """ + with _lock: + has_hosts = bool(_HOSTS) + if not has_hosts: + return threading.Thread(target=_check_update_when_idle, daemon=True, name='garrison-upd-check').start() - return r def _check_update_when_idle(timeout=45.0): diff --git a/backend/core/garrisondl.py b/backend/core/garrisondl.py index 01d0223..0dfe7ef 100644 --- a/backend/core/garrisondl.py +++ b/backend/core/garrisondl.py @@ -39,6 +39,18 @@ # 已验证直链(匿名可下载,整包 sha256 锚定):按版本降序作回退链—— # 记录里的新版不在适配表时,装「表内最新」的直链版本而不是一味落到最老。 FALLBACKS = [ + { + 'version': '1.1.7', + 'url': ('https://static.max-c.com/heybox/desktop/extension/' + 'ai-desktop.arknights-medal-farm/version/1.1.7/' + '6bc385116129d13b2e66679d100551950c6b03c793a92cfe1bc9f53f6db3166b-' + '20261120T150609837Z/ai-desktop.arknights-medal-farm-1.1.7.hbext'), + 'sha256': '6bc385116129d13b2e66679d100551950c6b03c793a92cfe1bc9f53f6db3166b', + 'bytes': 61089122, + 'files': None, + 'source': '官方直链(回退)', + }, + { 'version': '1.1.5', 'url': ('https://static.max-c.com/heybox/desktop/extension/' diff --git a/frontend/app.js b/frontend/app.js index 2930b87..44130a4 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -4042,7 +4042,8 @@ function paintGarInputs() { if (!o) return; const set = (id, v) => { const el = $(id); if (el && v !== undefined && v !== null) el.value = String(v); }; set('#gar-device', o.device); - set('#gar-mode', o.mode); + set('#gar-mode', 'quick'); // 上游 v1.1.7 起仅支持极速 + set('#gar-goal', o.goal); set('#gar-adb', o.adbAddress); set('#gar-wins', o.medalWins); set('#gar-speed', o.speed); @@ -4053,7 +4054,7 @@ function paintGarInputs() { function collectGarOpts() { const v = id => $(id) ? $(id).value : ''; const o = { - device: v('#gar-device'), mode: v('#gar-mode'), adbAddress: v('#gar-adb').trim(), + device: v('#gar-device'), mode: v('#gar-mode'), goal: v('#gar-goal'), adbAddress: v('#gar-adb').trim(), medalWins: Number(v('#gar-wins')) || 3, speed: Number(v('#gar-speed')) || 1.5, pcUiScale: Number(v('#gar-scale')) || 90, screenshotMethod: v('#gar-shot'), }; diff --git a/frontend/index.html b/frontend/index.html index 417b587..971450e 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -304,9 +304,19 @@

搜一个关卡开始

+ diff --git a/resources/garrison/host.mjs b/resources/garrison/host.mjs index 0b242b8..dd8de96 100644 --- a/resources/garrison/host.mjs +++ b/resources/garrison/host.mjs @@ -148,10 +148,14 @@ function readBody(req) { req.on('error', reject); }); } +// goal 白名单:medal=策略徽章(默认);task-N=叠层目标(v1.1.7 起支持)。 +// 与后端 garrison.py 的 GOALS 保持一致。 +const GOALS = ['medal', 'task-1', 'task-2', 'task-3', 'task-4', 'task-5', 'task-6', 'task-7']; + function buildOptions(body = {}) { const device = body.device ?? 'mumu'; const options = { - goal: 'medal', + goal: GOALS.includes(body.goal) ? body.goal : 'medal', medalWins: Number(body.medalWins) === 6 ? 6 : 3, mode: body.mode === 'standard' ? 'standard' : 'quick', debug: Boolean(body.debug), diff --git a/resources/garrison/patches.json b/resources/garrison/patches.json index 9f37b80..2b4f4a3 100644 --- a/resources/garrison/patches.json +++ b/resources/garrison/patches.json @@ -2,7 +2,8 @@ "note": "对第三方核心 service.mjs 的最小文本补丁。核心是 GPL-3.0-or-later 的报混淆包,不进仓库、由 garrisondl.py 按版本下载;adaptedVersions 硬编码已适配的核心版号——更新器只升到表内版本(表外新版等适配);这里只存纯文本替换规则,启动前幂等应用(首次改动前留 service.mjs.orig 备份)。规则脱靶(核心升级换了写法)只记日志跳过,不影响启动。", "adaptedVersions": [ "1.1.4", - "1.1.5" + "1.1.5", + "1.1.7" ], "patches": [ { @@ -52,6 +53,24 @@ "why": "v1.1.5 版同款:策略页详情核对(G 函数)纯 includes 零容错,改为不中再走 xn 容差——缪尔赛思等 4 字策略名 OCR 错 1 字不再跳过拉黑、整局卡死。", "find": "return v.find(O=>M(y).includes(M(O.name)))", "replace": "return v.find(O=>M(y).includes(M(O.name))||xn(M(y),M(O.name)))" + }, + { + "id": "latin-tolerance-v117", + "why": "v1.1.7 同款:名字比对 Rn(上游已自带 ≥3 字 1 字容差)拉丁名仍只容 1 字差——小字号拉丁名(Miss.Christine、数据里没有的新预备干员 Mist 系 7-8 字母名)OCR 常错 2+ 字。≥6 字拉丁/数字名放宽到 2 字。", + "find": "if(P.length<3)return!1;for(let q=0;q+P.length<=O.length;q++){let ue=0;for(let Z=0;Z=6?2:1;for(let q=0;q+P.length<=O.length;q++){let ue=0;for(let Z=0;ZO(x).includes(O(P.name)))", + "replace": "return y.find(P=>O(x).includes(O(P.name))||Rn(O(x),O(P.name)))" } ] } diff --git a/tools/smoketest/smoke_test.py b/tools/smoketest/smoke_test.py index aac743e..6bce9cf 100644 --- a/tools/smoketest/smoke_test.py +++ b/tools/smoketest/smoke_test.py @@ -4666,7 +4666,7 @@ def _write_maa(kind, addr, adb=''): _write_maa('MuMuEmulator12', '127.0.0.1:16416', r'C:\MuMu\adb.exe') o, src = garrison.defaults('g-acc.json') - assert o == {'device': 'mumu', 'mode': 'quick', 'speed': 1.5, 'medalWins': 3, + assert o == {'device': 'mumu', 'mode': 'quick', 'goal': 'medal', 'speed': 1.5, 'medalWins': 3, 'adbAddress': '127.0.0.1:16416', 'adbPath': r'C:\MuMu\adb.exe', 'screenshotMethod': 'fast', 'pcUiScale': 90}, o assert src['kind'] == 'MuMuEmulator12' and src['profile'] == 'P1', src @@ -4686,10 +4686,16 @@ def _write_maa(kind, addr, adb=''): bad = garrison.sanitize({'device': 'hack', 'mode': 'zzz', 'medalWins': '6', 'speed': '99', 'screenshotMethod': 'x', 'adbAddress': ' ', 'pcUiScale': '120'}) - assert bad == {'device': 'mumu', 'mode': 'quick', 'medalWins': 6, + assert bad == {'device': 'mumu', 'mode': 'quick', 'goal': 'medal', + 'medalWins': 6, 'speed': 5.0, 'adbAddress': '127.0.0.1:16384', 'adbPath': '', 'screenshotMethod': 'auto', 'pcUiScale': 90}, bad + # goal 白名单:非法值回 medal,合法叠层目标透传 + ok_goal = garrison.sanitize({'goal': 'task-3', 'device': 'mumu'}) + assert ok_goal['goal'] == 'task-3', ok_goal + bad_goal = garrison.sanitize({'goal': 'hack'}) + assert bad_goal['goal'] == 'medal', bad_goal # 5) 空环境 status:缺核心 → ready=False + needsDownload + 下载状态机初值; # 路由也挂上了 @@ -4765,8 +4771,15 @@ def _write_maa(kind, addr, adb=''): d = os.path.join(pkg, 'medal-farm-v%s' % v, 'core') os.makedirs(d, exist_ok=True) open(os.path.join(d, 'service.mjs'), 'w').close() - snap = garrisondl.start() - assert snap['stage'] == 'done', snap + _real_cands8 = garrisondl.candidates + garrisondl.candidates = lambda: [ + {'version': '1.1.4', 'url': 'x', 'sha256': None, 'bytes': None, + 'files': None, 'source': 'test'}] + try: + snap = garrisondl.start() + assert snap['stage'] == 'done', snap + finally: + garrisondl.candidates = _real_cands8 # 版本号不能写死:下载器按小黑盒记录装的是上游最新版(v1.1.5),探测必须 # 扫 medal-farm-v* 取最高版本——旧版只认 v1.1.4,装好新版却报「没核心」, # 前端于「已下载 + 仍要下载」之间无限重试,一直停在「核心就绪,正在启动…」 @@ -4839,8 +4852,15 @@ def _write_maa(kind, addr, adb=''): real_cands = garrisondl.candidates real_records = garrisondl.record_candidates try: + # 隔离重置:前面各节可能留下了 _DL 状态/_RUNNING 标志 + with garrisondl._LOCK: + garrisondl._RUNNING[0] = False + garrisondl._DL.update(stage='idle', done=0, total=0, files=0, + filesTotal=0, source='', version='', error='', + startedAt=None, endedAt=None) adapted = garrisondl._adapted_versions() - assert adapted and '1.1.4' in adapted and '1.1.5' in adapted, adapted + assert adapted and '1.1.4' in adapted and '1.1.5' in adapted + assert '1.1.7' in adapted, adapted assert garrisondl._is_adapted('1.1.5') and not garrisondl._is_adapted('1.1.6') # 已最新(候选=已装)→ start() 短路 done,不起线程 @@ -4875,9 +4895,9 @@ def _write_maa(kind, addr, adb=''): garrisondl.record_candidates = lambda: [ {'version': '1.1.6', 'url': 'x', 'sha256': None, 'bytes': None, 'files': None, 'source': '小黑盒扩展记录'}] - assert garrisondl._pick_candidate('1.1.4')['version'] == '1.1.5', '表外新版应回退表内最新' - assert garrisondl._pick_candidate('')['version'] == '1.1.5' - assert garrisondl._pick_candidate('1.1.5') is None + assert garrisondl._pick_candidate('1.1.4')['version'] == '1.1.7', '表外新版应回退表内最新' + assert garrisondl._pick_candidate('')['version'] == '1.1.7' + assert garrisondl._pick_candidate('1.1.7') is None # check_update:候选只剩表外新版(连直链一起屏蔽)→ 不起线程零流量; # (真实链路里记录 1.1.6 + 已装 1.1.4 会经直链升 1.1.5——上面 # _pick_candidate 断言已覆盖该选版,这里不再真下载) From 6bd98b7233639b221a4a67ddc01d6aad3901ddb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=99=93=E4=B8=B6=E6=A2=A6=E4=B8=B6=E4=BB=81?= <74444214+Daydreamer114@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:28:51 +0800 Subject: [PATCH 6/8] =?UTF-8?q?test(garrison):=20=E5=86=92=E7=83=9F=20B47?= =?UTF-8?q?=20=E5=8E=BB=E5=A4=96=E7=BD=91=E4=BE=9D=E8=B5=96=E2=80=94?= =?UTF-8?q?=E2=80=94=E5=A4=B1=E8=B4=A5=E7=94=A8=E4=BE=8B=E6=94=B9=E7=94=A8?= =?UTF-8?q?=E6=9C=AC=E5=9C=B0=E5=BF=85=E6=8B=92=E7=AB=AF=E5=8F=A3=20(#123)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI 上 sec10 的升级失败用例指向真实 CDN(static.max-c.com),美国出口 DNS/连接极慢,3 次重试 ×30s 超时远超 18s 等待窗,断言时状态还停在 connecting。改用 http://127.0.0.1:1(立即 connection refused),等待 窗放宽到 45s;sec7 的坏 URL 用例同口径。本地全套 B1-B48+C1 绿。 --- tools/smoketest/smoke_test.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tools/smoketest/smoke_test.py b/tools/smoketest/smoke_test.py index 6bce9cf..4930366 100644 --- a/tools/smoketest/smoke_test.py +++ b/tools/smoketest/smoke_test.py @@ -4725,7 +4725,7 @@ def _write_maa(kind, addr, adb=''): assert cands and cands[-1]['version'] == garrisondl.FALLBACK['version'], cands assert garrisondl.FALLBACK['sha256'] and garrisondl.FALLBACK['bytes'] > 0 try: - garrisondl._download('https://static.max-c.com/heybox/desktop/nonexistent.hbext', + garrisondl._download('http://127.0.0.1:1/nonexistent.hbext', os.path.join(tmp, 'x.hbext'), attempts=1, timeout=10) raise AssertionError('坏 URL 居然下载成功了') except RuntimeError as e: @@ -4876,11 +4876,11 @@ def _write_maa(kind, addr, adb=''): # 有可升目标(1.1.5,URL 不可达)→ 升级链走完报错;不落盘、旧版保留 garrisondl.candidates = lambda: [ {'version': '1.1.5', - 'url': 'https://static.max-c.com/heybox/desktop/nonexistent-1.1.5.hbext', + 'url': 'http://127.0.0.1:1/nonexistent-1.1.5.hbext', 'sha256': None, 'bytes': None, 'files': None, 'source': '小黑盒扩展记录'}] snap = garrisondl.start() assert snap['stage'] != 'done', snap - for _ in range(60): + for _ in range(150): # 3 次重试 ×(1.5+3)s 退避,留足余量 if garrisondl.state()['stage'] == 'error': break time.sleep(0.3) From 7e8f30311e272b0a63736e8d1aab3a81d8cf4e57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=8D=A1=E6=8B=89=E5=B8=95=E9=B2=81=E7=81=B0?= <939671113@qq.com> Date: Sun, 22 Nov 2026 03:00:51 +0800 Subject: [PATCH 7/8] =?UTF-8?q?fix(garrison):=20=E8=A1=A5=E5=9B=9E?= =?UTF-8?q?=E5=A5=96=E5=8A=B1=E5=80=99=E9=80=89=E5=8D=A1=E8=AF=86=E5=88=AB?= =?UTF-8?q?=EF=BC=8C=E5=90=88=E6=88=90=E7=B2=BE=E9=94=90=E5=90=8E=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E5=8D=A1=E5=9C=A8=E3=80=8C=E8=AF=B7=E9=80=89=E6=8B=A9?= =?UTF-8?q?=E5=A5=96=E5=8A=B1=E3=80=8D=20(#125)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit v1.1.7 把奖励面板判定统一改成 _o 的价格扫描(固定价格位读到 ≥2 个数字 0 才算 reward)。实测该界面三张候选卡不显示数字价格,OCR 读不到 0 → reward=false;同时绿色「请选择奖励」横幅盖住右上角「准备就绪」→ ready=false, 外层守卫抛「尚未确认普通购买界面,暂不部署」,整备重来 → 死循环。 按 v1.1.5 的原判据补一条兜底(reward-zero-inline-v117):对每张商店卡的 名字区 OCR,读到 0/O 标记的卡即为奖励候选(≥2 且不少于非候选数),交给 原有领取分支。只补识别,不改点击行为;异常一律吞掉回落到原逻辑。 Co-authored-by: HuiParu <171644868+HuiParu@users.noreply.github.com> --- resources/garrison/patches.json | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/resources/garrison/patches.json b/resources/garrison/patches.json index 2b4f4a3..af63f09 100644 --- a/resources/garrison/patches.json +++ b/resources/garrison/patches.json @@ -71,6 +71,12 @@ "why": "v1.1.7 同款:策略页详情核对(ie 函数)纯 includes 零容差,改为不中再走 Rn 容差。", "find": "return y.find(P=>O(x).includes(O(P.name)))", "replace": "return y.find(P=>O(x).includes(O(P.name))||Rn(O(x),O(P.name)))" + }, +{ + "id": "reward-zero-inline-v117", + "why": "奖励候选卡兜底识别(合成精锐后「请选择奖励」三选一)。v1.1.7 把奖励面板判定统一改成 _o 的价格扫描:要固定价格位读到 ≥2 个数字 0 才算 reward。实测该界面上三张候选卡不显示数字价格,OCR 读不到 0 → reward=false;同时绿色「请选择奖励」横幅正好盖住右上角「准备就绪」→ ready=false,外层守卫 if(!it&&Pr.reward||!Pr.ready) 抛「尚未确认普通购买界面」→ 整备重来 → 死循环(合成后领奖励卡住)。这里按 v1.1.5 的老办法补一条兜底:对每张商店卡的名字区(left=x+40v, top=1080-328v, 130v×72v)OCR,读到 0/O 标记的卡即为奖励候选(≥2 张且不少于非候选数),交给原有领取分支(pt(card.x,name,true)),点击/名字核对/确认仍走核原本逻辑。只补识别,不改任何点击行为。", + "find": "async function qt(B,x,y=!1){const O=await $u(B.png,B.pc,B.pcUiScale??ne.pcUiScale),P=Lo(x,O,{allowSingleZero:y,pc:B.pc,pcUiScale:B.pcUiScale??ne.pcUiScale});return{scan:O,reward:O.reward,cards:P}}", + "replace": "async function qt(B,x,y=!1){const O=await $u(B.png,B.pc,B.pcUiScale??ne.pcUiScale),P=Lo(x,O,{allowSingleZero:y,pc:B.pc,pcUiScale:B.pcUiScale??ne.pcUiScale});if(!O.reward)try{const v=B.pc?(B.pcUiScale??90)/100:1,M=Math.round(1080-328*v),W=Math.round(130*v),H=Math.round(72*v),rg=x.filter(c=>!!c.name).map(c=>({card:c,region:{left:Math.round(c.x+40*v),top:M,width:W,height:H}})).filter(r=>r.region.left>=0&&r.region.top>=0&&r.region.left+r.region.width<=1920&&r.region.top+r.region.height<=1080);if(rg.length){const tt=await Oa(B.png,rg.map(r=>r.region)),hit=rg.filter((r,i)=>(tt[i]||[]).some(u=>/^[0OoO〇]$/.test(u.text.trim())&&u.score>=.6)).map(r=>r.card);if(hit.length>=2&&hit.length>=rg.length-hit.length){console.error(\"[reward-inline] 按卡名区 0 标记识别到奖励候选:\"+hit.map(c=>c.name).join(\",\"));return{scan:O,reward:!0,cards:hit}}}}catch(Qx){}return{scan:O,reward:O.reward,cards:P}}" } ] } From 18e05ec0734c01a4a125a5eae793b16c3c08c619 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=8D=A1=E6=8B=89=E5=B8=95=E9=B2=81=E7=81=B0?= <939671113@qq.com> Date: Sun, 22 Nov 2026 03:01:25 +0800 Subject: [PATCH 8/8] =?UTF-8?q?feat(settings):=20=E8=B4=A6=E5=8F=B7/MAA=20?= =?UTF-8?q?=E5=88=86=E6=A0=8F=20+=20=E5=AE=9A=E6=97=B6=E4=BB=BB=E5=8A=A1?= =?UTF-8?q?=20+=20=E9=85=8D=E7=BD=AE=E6=96=87=E4=BB=B6=E8=AF=BB=E5=88=87?= =?UTF-8?q?=E5=8F=B7=E5=90=8D=20(#124)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(settings): 账号/MAA 路径按游戏分栏 + 新增定时任务页 账号管理与 MAA 路径两页顶部加「明日方舟 / 明日方舟终末地」分组,两页共用 同一个选择(切一页另一页跟着切)。终末地那栏预留 MAAEND 根目录 maaEndDir, 检测认 MaaEnd.exe / mxu.exe;任务链还没接,先只保存路径。MAA 路径页里的 「bilibili服」改成粉色,B 服切号名规则与官服不同,需要醒目。 新增设置页「定时任务」:按时间(每周指定几天 + HH:MM)或链式启动外部程序。 参照三月七助手的语义,autostart-*.exe、OneDragon-Launcher.exe、cmd 批处理 可以原样搬过来。冲突策略(停掉在跑的 / 跳过本次)、链式失败策略(继续 / 停止)、 立即运行 / 停止、最近 40 行日志。 后端 scheduler.py 的几条硬规则:只认当前分钟不补跑(程序关着时错过的不补); 链式只排下一个(一次排整条链会让同一任务被排两遍,实测踩过);Windows 下 taskkill /F /T 收整棵进程树(bat 是 cmd 的子进程);参数按 CommandLineToArgvW 拆,shlex 在 Windows 上会留下引号。数据 config/schedule.json 原子写,日志 debug/schedule.log。接口 /api/schedule/{status,save,run,stop},留给 agent 后续帮用户写定时。 跑完的「通知」走 events 增量(seq 去重),设置页关着也能弹。冒烟新增 B49 (清洗 / 下次运行 / 链式串接 / 参数解析),50 项全绿。 * feat(settings): MAA 配置文件读切号名 + 助手存尾号 + 定时页文案 设置 → MAA 路径:每个账号改成「路径第一行、配置文件+切号名第二行」。选了配置文件就从那份档案的 StartUp 里读 AccountName 带出来,可手改;手改的值(accountNameFrom=manual)优先,档案只读不写。新增 acctbind 统一解析切号名,agent/skills/multiacct 都走它。 助手:切号名放宽到「前 3 位 + 后 4 位」(157****3635 也收);新增 set_account_name,用户报尾号就存进对应账号设置。 定时任务页文案去掉三月七,改成「能放什么进去」的说明;冒烟补 B50(配置文件优先/手填优先/存尾号)。 --------- Co-authored-by: HuiParu <171644868+HuiParu@users.noreply.github.com> --- backend/core/accounts.py | 3 + backend/core/acctbind.py | 89 ++++ backend/core/acctname.py | 13 +- backend/core/agent.py | 135 ++++-- backend/core/api.py | 54 ++- backend/core/maa.py | 22 + backend/core/multiacct.py | 23 +- backend/core/scheduler.py | 591 ++++++++++++++++++++++++ backend/core/settings.py | 6 + backend/core/skills.py | 65 ++- backend/main.py | 24 + docs/agent.md | 18 +- docs/backend.md | 69 ++- docs/config.md | 43 +- docs/frontend.md | 26 +- docs/tools-smoketest.md | 30 +- frontend/app.js | 818 +++++++++++++++++++++++++++++----- frontend/style.css | 104 +++++ tools/smoketest/smoke_test.py | 245 +++++++++- 19 files changed, 2159 insertions(+), 219 deletions(-) create mode 100644 backend/core/acctbind.py create mode 100644 backend/core/scheduler.py diff --git a/backend/core/accounts.py b/backend/core/accounts.py index f82c414..d7d3715 100644 --- a/backend/core/accounts.py +++ b/backend/core/accounts.py @@ -76,6 +76,9 @@ def list_accounts(): # 存下来就不用每次挂机都问一遍——这是唯一必须问用户的字段, # 猜错的表现是切号死循环(MAA 找不到账号名,重试到超时)。 'maaAccountName': _dict(snap.get('maa')).get('accountName') or '', + # 切号名的来源:manual=用户手填过(以他为准)/ profile=跟着配置文件走 + # (读那份档案 StartUp 的 AccountName)。规则在 acctbind.py。 + 'maaAccountNameFrom': _dict(snap.get('maa')).get('accountNameFrom') or '', 'maaDir': _dict(snap.get('maa')).get('dir') or '', 'syncedAt': _dict(snap.get('sync')).get('syncedAt'), # 关卡进度摘要(主线还差几关、活动几个区、剿灭几张没满); diff --git a/backend/core/acctbind.py b/backend/core/acctbind.py new file mode 100644 index 0000000..8c7c50d --- /dev/null +++ b/backend/core/acctbind.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +r"""账号 ↔ MAA 切号名(AccountName)的解析与绑定 + +为什么单独一个模块 +------------------ +「这个账号跑 StartUp 时写哪个切号名」有三个调用方:助手建方案(agent._roster)、 +单个 skill 唤醒(skills.skills_wakeup)、多账号编排(multiacct.candidates)。 +2026-11-22 之前规则是「唯一来源 = 账号自己存的 maa.accountName,绝不读用户的 +MAA 配置」——理由是 agent 跑的是临时配置,不碰用户的 gui.new.json。 + +用户随后提了更实际的要求:**设置里选了配置文件,就按那份档案的账号名来** +(他已经在 MAA 里配过一次,不该再手抄一遍)。所以现在的规则是: + +1. ``maa.profile`` 选了档案、且没被手动改过 → 读该档案 StartUp 的 AccountName +2. 否则用账号里存的 ``maa.accountName``(手填的 / 上次对话里报的) +3. 都没有 → 空串,调用方去问用户(官服问后 4 位) + +**只读,绝不写回用户的 MAA 配置**:档案是用户的,程序只在 ``maa.profile`` +这一格引用它的名字;切换 / 改字段都走别的入口(写作业那套)。 + +``accountNameFrom`` 是这里唯一的新状态:``manual`` = 用户手填过(听他的), +``profile`` = 从配置档案带出来的(跟着档案走)。老账号没这个字段,按 +profile 处理——反正没选档案时也不会去读配置。 +""" +from __future__ import annotations + +from . import accounts, acctname, maa + + +def _maa_of(snap) -> dict: + m = (snap or {}).get('maa') + return m if isinstance(m, dict) else {} + + +def channel_of(snap) -> str: + a = (snap or {}).get('account') + return str((a.get('channelName') if isinstance(a, dict) else '') or '') + + +def profile_name(profile, maa_dir=None) -> str: + """档案里的 AccountName(读不到就给空串,绝不抛)""" + try: + return maa.profile_account_name(profile, maa_dir or None) + except Exception: + return '' + + +def resolve(file, snap=None): + """账号跑 StartUp 时用的切号名 → ``(名字, 来源)`` + + 来源取值:``profile``(读自配置档案)/ ``saved``(账号里存的)/ + ``''``(还没有,要问用户)。名字已经过 ``acctname.check`` 归一化, + 直接可以写进 StartUp 任务参数。 + """ + if snap is None: + try: + snap = accounts.get_account(file) + except Exception: + snap = {} + m = _maa_of(snap) + ch = channel_of(snap) + stored, _ = acctname.check(m.get('accountName') or '', ch) + stored = stored or '' + prof = str(m.get('profile') or '').strip() + src = str(m.get('accountNameFrom') or '').strip() + if prof and src != 'manual': + live, _ = acctname.check(profile_name(prof, m.get('dir') or None), ch) + if live: + return live, 'profile' + return stored, ('saved' if stored else '') + + +def bind(file, raw, channel=None): + """把用户报的切号名存进账号(``maa.accountName``,标记为手填) + + 返回 ``(归一化后的名字, 原因)``;名字不可用时不落盘,原因交给调用方 + 原样告诉用户(官服填昵称这类)。 + """ + snap = {} + try: + snap = accounts.get_account(file) + except Exception: + pass + ch = channel if channel is not None else channel_of(snap) + nm, why = acctname.check(raw, ch) + if not nm: + return '', why + accounts.save_maa_meta(file, {'accountName': nm, 'accountNameFrom': 'manual'}) + return nm, '' diff --git a/backend/core/acctname.py b/backend/core/acctname.py index 76d52ed..368b8a8 100644 --- a/backend/core/acctname.py +++ b/backend/core/acctname.py @@ -14,14 +14,16 @@ StartUp 任务的切号是拿 ``AccountName`` 去和登录界面 OCR 出来的那行做 **包含**比较,所以下面三种都认(官方说明原话): -- 纯尾号 ``5505`` —— **首选**。问用户只要后四位,基本不会撞号 +- 纯尾号 ``5505`` —— 最省事,问用户就要后四位 +- 前 3 后 4 ``1573635`` / ``157 3635`` —— 2026-11-22 用户要求也收(他常记前三位) - 部分掩码 ``23****45`` -- 完整掩码 ``181****5505`` +- 完整掩码 ``157****3635`` 用户手里往往只有一个片段。**能补全的补成完整掩码,补不全的原样保留**, 别拿"格式不对"去卡他——格式错是我们的活,不是他的。 -对话里一律问「手机号后 4 位」,别让用户去拼 ``****``:拼错的是他,报错的是我们。 +对话里问「手机号后 4 位」就行;用户主动给「前 3 位 + 后 4 位」 +(``157****3635``)同样收下,别让他去数星号有几个:拼错的是他,报错的是我们。 """ from __future__ import annotations @@ -147,6 +149,7 @@ def check(nm, channel=None): if not s: return None, '没填' if is_official_channel(channel) and not looks_official(s): - return None, ('官服切号名要用手机号(给后 4 位就行,如 5505);' - '「%s」不是手机号,像昵称,对不上官服账号列表' % raw) + return None, ('官服切号名要用手机号(后 4 位如 5505,或前 3 位 + 后 4 位如' + ' 157****3635);「%s」不是手机号,像昵称,对不上官服账号列表' + % raw) return s, '' diff --git a/backend/core/agent.py b/backend/core/agent.py index fe57593..3fb49f1 100644 --- a/backend/core/agent.py +++ b/backend/core/agent.py @@ -32,7 +32,7 @@ import urllib.request import uuid -from . import (accounts, asstlog, copilot, maa, multiacct, progress, +from . import (accounts, acctbind, asstlog, copilot, maa, multiacct, progress, resources, settings, skills, tasks, vault, watch) MAX_TURNS = 12 @@ -353,13 +353,24 @@ def _tool(name, desc, props=None, required=None): 'description': '抄作业时是否自动编队,默认 true'}, 'names': {'type': 'object', 'description': '{账号文件名: 切号名}。官服填手机号后 4 位' - '(如 5505),B 服填游戏内用户名。' + '(如 5505),前 3 位 + 后 4 位也行' + '(如 157****3635);B 服填游戏内用户名。' '缺的时候要问用户,**原样传**,别自己拼格式'}, 'limitStages': {'type': 'integer', 'description': '最多挂几关,默认 8'}, 'profile': {'type': 'string', 'description': '档案名后缀,比如「活动-时间啊向前」。不给就自动起名'}, 'start': {'type': 'boolean', 'description': '写完是否立刻启动,默认 true'}}, []), + _tool('set_account_name', + '**配置账号登录尾号**:用户说出某个账号的手机号尾号(后 4 位,或' + '「前 3 位 + 后 4 位」如 157****3635)时,把它存进那个账号的设置' + '(设置 → MAA 路径 → 切号名),下次挂机、切号都不用再问。' + '只改本程序自己的账号配置,**不会动 MAA 的任何字段**。' + '用户只是顺口报了个尾号、还没说要挂什么时也可以先存下来。', + {'account': _ACC, + 'accountName': {'type': 'string', + 'description': '用户给的尾号/切号名,**原样传**,别自己拼格式'}}, + ['accountName']), _tool('list_profiles', '看 MAA 里现在有哪些配置档案、当前用的是哪个、各自挂了几个作业。' '用户问「现在跑的是哪个号」时用它。'), @@ -374,7 +385,8 @@ def _tool(name, desc, props=None, required=None): # ---- 挂关 skill 化(2026-11-17):唤醒 / 导航 / 剧情 / 战斗 / 签到 / 周目 ---- _tool('skill_wakeup', '唤醒游戏到主界面(游戏没开/停在登录页/START 页时用)。' - '可选 accountName 按切号名换账号(官服=手机号后 4 位,如 5505)。' + '可选 accountName 按切号名换账号(官服=手机号后 4 位,如 5505;' + '也可以给前 3 位 + 后 4 位,如 157****3635)。' '返回 taskId,后台跑。', {'account': _ACC, 'accountName': {'type': 'string', @@ -490,7 +502,7 @@ def _tool(name, desc, props=None, required=None): 'description': '简写模式的专精目标,如 [0,3,0]'}, 'account': _ACC, 'accountName': {'type': 'string', - 'description': '切号名(官服=手机号后 4 位)。' + 'description': '切号名(官服=手机号后 4 位,或前 3 位 + 后 4 位)。' '账号已绑定尾号(list_accounts 的 ' 'accountName 非空)时不用传,程序会自己用'}, 'switchAccount': {'type': 'boolean', @@ -519,7 +531,7 @@ def _tool(name, desc, props=None, required=None): 'description': '默认 true(先唤醒到主界面);游戏已经开着' '并停在关卡列表时传 false'}, 'accountName': {'type': 'string', - 'description': '切号名(官服=手机号后 4 位)'}}, + 'description': '切号名(官服=手机号后 4 位,或前 3 位 + 后 4 位)'}}, ['stage']), _tool('skill_tool', '**MAA 小工具(牛杂)**:跑 MAA「小工具 → 牛杂」里的功能。会自动导航到' @@ -593,6 +605,14 @@ def _tool_list_accounts(args): for c in accounts.list_accounts(): if (c.get('game') or 'arknights') != 'arknights': continue + # 绑了配置文件的账号:列表里的切号名要用生效值(档案里的那个), + # 否则用户在设置里选过档案、模型还是看到空值,照样重复问一遍 + acc_name = c.get('maaAccountName') or '' + if c.get('maaProfile'): + try: + acc_name, _src = acctbind.resolve(c['file']) + except Exception: + pass p = c.get('progress') or {} out.append({ # 账号列表给的是 nickName / alias / channelName,没有 name / channel @@ -606,7 +626,7 @@ def _tool_list_accounts(args): # 已绑定的切号名(手机尾号)必须给出来:用户 2026-11-18 报 # 「设置里配过尾号,助手每次还问」——列表里带出来,模型就不用 # 再开口问;只有这里是空的才轮到问用户。 - 'accountName': c.get('maaAccountName') or '', + 'accountName': acc_name, # 字段名对齐 progress.summary():mainRemaining / activityLeft / # activityStages 才是真名(曾经写成 mainLeft / activityZones, # 结果每个账号都返回 null,模型只能挨个再问一遍 account_progress) @@ -618,9 +638,56 @@ def _tool_list_accounts(args): 'activityStages': p.get('activityStages'), }) return {'accounts': out, 'count': len(out), - 'hint': 'accountName 就是已绑定的切号名(手机尾号):**非空的直接按它跑,' - '不要再问用户**;只有为空的账号才问「手机号后 4 位」' - '(B 服问游戏内用户名)'} + 'hint': 'accountName 就是已绑定的切号名(手机号后 4 位 / 前 3 位 + 后 4 位)' + ':**非空的直接按它跑,不要再问用户**;只有为空的账号才问' + '「手机号后 4 位」(B 服问游戏内用户名)。用户报了尾号就顺手用' + ' set_account_name 存下来,下次不用再问'} + + +def _tool_set_account_name(args): + """配置账号登录尾号:把用户报的尾号存进对应账号的切号名 + + 只写本程序自己的账号 json(``maa.accountName`` + ``accountNameFrom=manual``), + MAA 的配置文件一个字段都不动。存下来之后 list_accounts 就能看到, + 下次挂机 / 切号不用再问。 + """ + raw = str(args.get('accountName') or args.get('tail') or '').strip() + if not raw: + return {'error': '没给尾号(后 4 位,或前 3 位 + 后 4 位)'} + rows = [c for c in accounts.list_accounts() + if (c.get('game') or 'arknights') == 'arknights'] + if not rows: + return {'error': '左侧还没有明日方舟账号'} + want = str(args.get('account') or '').strip() + file = '' + if want: + for c in rows: + names = (c['file'], c.get('nickName') or '', c.get('alias') or '') + if want in names or want in (c.get('nickName') or ''): + file = c['file'] + break + if not file: + return {'error': '找不到账号:%s' % want, + 'accounts': [{'file': c['file'], 'name': c.get('nickName')} + for c in rows], + 'hint': '按 list_accounts 的 file 或昵称再传一次'} + elif len(rows) == 1: + file = rows[0]['file'] + else: + return {'need_info': 'account', + 'accounts': [{'file': c['file'], 'name': c.get('nickName')} + for c in rows], + 'note': '有多个账号,问用户这个尾号是哪个号的(按昵称确认)'} + + nm, why = acctbind.bind(file, raw) + if not nm: + return {'error': why, 'hint': '官服要手机号(后 4 位,或前 3 位 + 后 4 位);' + 'B 服填游戏内用户名'} + row = next((c for c in rows if c['file'] == file), {}) + return {'ok': True, 'account': file, 'name': row.get('nickName') or file, + 'accountName': nm, + 'note': '已存进「设置 → MAA 路径 → %s 的切号名」,下次挂机直接用;' + '没改 MAA 里任何配置' % (row.get('nickName') or file)} def _tool_list_activities(args): @@ -953,15 +1020,14 @@ def _check_account_name(nm, channel): def _roster(want_files, names, maa_dir): """把「哪些账号 + 各自的切号名」理出来 - 切号名的来源,只有两个可信的: + 切号名的来源(规则只有一份,在 ``acctbind.resolve``): 1. 用户这次显式给的 ``names``(还会回写账号文件,下次不用再问) - 2. 账号文件里存过的 ``maa.accountName``(上次给的 / 设置页填的) + 2. 账号绑的配置文件里「开始唤醒」的 AccountName(2026-11-22 用户要求: + 他在 MAA 里配过一次,就别再让他抄一遍) + 3. 账号文件里存过的 ``maa.accountName``(手填的 / 上次对话里报的) - **不从用户的 MAA 配置档案里猜**(2026-11-18 用户口径:agent 模式不碰 - 用户的 MAA 配置):以前会拿 ``maa.profile`` 档案里的 AccountName、甚至 - 拿昵称去比对档案名来凑切号名——程序里两个游戏账号对 MAA 里五个尾号 - 档案,档案名和 AccountName 根本说不清谁是谁,错配的代价是官服传错号 - MAA 在账号列表里死找 4 分钟超时,整轮挂机死在「登录」。宁可多问一句。 + **只读用户的 MAA 配置,绝不写回**;也绝不拿昵称去凑切号名——官服认的是 + 手机号,传昵称 MAA 在账号列表里死找 4 分钟超时,整轮挂机死在「登录」。 """ cands = multiacct.candidates() if want_files: @@ -974,9 +1040,9 @@ def _roster(want_files, names, maa_dir): for c in cands: raw = (names.get(c['file']) or names.get(c['name']) or '') raw = str(raw).strip() if raw else '' - # check() 自己会归一化(181 5505 / 181*5505 / 5505 都能吃下), - # 这里别再提前 norm 一遍——曾经两层各自处理,第二层收到的已经是 - # 半成品,星号数量被改坏后又被严格正则判成非法。 + # check() 自己会归一化(181 5505 / 181*5505 / 5505 / 157****3635 + # 都能吃下),这里别再提前 norm 一遍——曾经两层各自处理,第二层收到 + # 的已经是半成品,星号数量被改坏后又被严格正则判成非法。 nm, why = _check_account_name(raw, c.get('channel')) source = 'user' if not nm: @@ -990,8 +1056,9 @@ def _roster(want_files, names, maa_dir): pass if not nm: official = _is_official(c.get('channel')) - ask = ('手机号后 4 位是多少?给这四位就行(如 5505)——' - 'MAA 切号用的就是它,基本不会撞号' + ask = ('手机号后 4 位是多少?给这四位就行(如 5505),' + '前 3 位 + 后 4 位也行(如 157****3635)——' + 'MAA 切号用的就是它' if official else '在 MAA 里切号用的名字是什么?(B 服填游戏内用户名)') missing.append({ 'file': c['file'], 'name': c['name'], @@ -1005,7 +1072,9 @@ def _roster(want_files, names, maa_dir): continue if source == 'user': try: - accounts.save_maa_meta(c['file'], {'accountName': nm}) + # 手填的值必须打上 manual:不然绑了配置文件的账号下次又被 + # 档案里的旧号码盖回去,用户改了等于没改 + acctbind.bind(c['file'], nm, c.get('channel')) except Exception: pass rows.append({'file': c['file'], 'name': c['name'], @@ -1389,6 +1458,7 @@ def _tool_skill_tool(args, session=None): _HANDLERS = { 'list_accounts': _tool_list_accounts, + 'set_account_name': _tool_set_account_name, 'list_activities': _tool_list_activities, 'search_stages': _tool_search_stages, 'find_ops': _tool_find_ops, @@ -1529,17 +1599,22 @@ def run_tool(name, args, session=None): ## 常见对话怎么做 **「帮我把所有账号挂上 TL-5」** -1. list_accounts —— **先看 accountName(已绑定的手机尾号)**:非空的账号 +1. list_accounts —— **先看 accountName(已绑定的切号名)**:非空的账号 直接沿用,**绝对不要再问一遍**(用户 2026-11-18 报过这个:设置里配过 尾号,助手还在问) 2. build_run(accounts=[]、mode=copy、keyword=TL-5) -3. 返回 need_info 时:**一次性把所有缺的账号列出来问**。官服只问 - 「手机号后 4 位」(如 5505),B 服问游戏内用户名。 - **不要让用户去拼 `181****5505`**——格式是程序的事。用户给全号、 - 带横线、星号多少、只给尾号,一律原样放进 names,程序会归一化。 +3. 返回 need_info 时:**一次性把所有缺的账号列出来问**。官服问 + 「手机号后 4 位」(如 5505)——用户给「前 3 位 + 后 4 位」 + (157****3635)、全号、带横线都行;B 服问游戏内用户名。 + **不要让用户必须拼 `181****5505`**——格式是程序的事,给什么都能吃。 拿到后带 names 再调一次 4. 返回 need_confirm 时,把确认卡片上的内容用自己的话复述要点 +**「这个号尾号是 5505」/「官服号尾号 157****3635」** +set_account_name(account 尽量给上,按昵称或 file 认)。存进设置之后 +list_accounts 的 accountName 就有值了,后面挂机不用再问。 +只改我们自己的账号配置,MAA 里一个字都不动。 + **「清一下日常」/「帮我收菜」** build_run(mode=daily,不用 keyword)。这就是一键长草。 @@ -1645,9 +1720,11 @@ def run_tool(name, args, session=None): - skill_fight / skill_skip_story / skill_weekly / skill_train 同样要先确认再跑 (工具会自动摆确认卡) - 多账号缺切号名时,明确说「这个信息森空岛拿不到,得你告诉我」; - 官服只要**手机号后 4 位**(如 5505),不要要求用户拼星号。 + 官服问**手机号后 4 位**(如 5505)就行,用户主动给「前 3 位 + 后 4 位」 + (157****3635)也照收,不要要求他数星号。 **问之前先看 list_accounts 的 accountName**:非空就是已经绑好的, - 直接用,别重复问(用户设置里配过的东西,助手再问一遍很烦) + 直接用,别重复问(用户设置里配过的东西,助手再问一遍很烦)。 + 用户报出尾号后调 set_account_name 存进设置,下次不用再问。 - 多账号是**串行**的(一个模拟器同时只能登一个号),一个跑完自动切下一个 - **模拟器不用你操心**:每个 skill 开跑前会自动确认模拟器在不在、没开就替用户 启动(路径从 MAA 配置里读)。任务报「环境没准备好」时,把日志那句话原样转给 diff --git a/backend/core/api.py b/backend/core/api.py index 6e7e297..9a5cc6e 100644 --- a/backend/core/api.py +++ b/backend/core/api.py @@ -9,7 +9,8 @@ from . import (accounts, agent, appupdate, asstlog, copilot, gacha, garrison, maa, maaplan, multiacct, operbox, packsync, paradox, resources, - settings, signin, skills, sklogin, tasks, updater, version, watch) + scheduler, settings, signin, skills, sklogin, tasks, updater, + version, watch) WEB = settings.static_dir() @@ -156,10 +157,17 @@ def api_account_maa(_q, body): patch['dir'] = settings._norm_dir(patch.get('dir') or '') if patch['dir']: settings.remember_maa_dir(patch['dir']) + if 'profile' in patch: + # 配置文件(MAA 的 Configuration):只记名字,**不读写用户的档案内容**。 + # 切号名优先按这份档案里「开始唤醒」的 AccountName 来(acctbind.resolve)。 + patch['profile'] = str(patch.get('profile') or '').strip()[:60] + if 'accountNameFrom' in patch: + v = str(patch.get('accountNameFrom') or '').strip().lower() + patch['accountNameFrom'] = v if v in ('manual', 'profile') else '' if 'accountName' in patch: # 切号名统一走 acctname:用户给「5505」「181 5505」「181****5505」 - # 都能吃下,官服填了昵称则当场拦下——这一格填错的代价是 MAA 在 - # 账号列表里死找、4 分钟超时后整轮挂机废掉。 + # 「157****3635」都能吃下,官服填了昵称则当场拦下——这一格填错的 + # 代价是 MAA 在账号列表里死找、4 分钟超时后整轮挂机废掉。 # 留空是合法状态(还没填 / 想清掉),不能当成「填错」拦下。 from . import acctname raw = (patch.get('accountName') or '').strip() @@ -170,6 +178,9 @@ def api_account_maa(_q, body): if why: raise ValueError('切号名不对:%s' % why) patch['accountName'] = name + # 没明说来源的一律按手填:老调用方(CLI/脚本)给的值不能被 + # 绑定的配置文件悄悄盖回去 + patch.setdefault('accountNameFrom', 'manual') else: patch['accountName'] = '' return {'maa': accounts.save_maa_meta(body['file'], patch)} @@ -440,11 +451,20 @@ def api_skland_login_cancel(_q, _body): def api_maa_probe(q, _body): - """检测一个目录是不是 MAA 根目录(首次引导 / 设置里用)""" + """检测一个目录是不是 MAA / MAAEND 根目录(首次引导 / 设置里用) + + kind=endfield 时按 MAAEND 的主程序名去找:终末地那套是另一个程序, + 主程序可能叫 MaaEnd.exe 或 mxu.exe(三月七脚本里两种都出现过)。这一步 + 只是把路径先管起来,MAAEND 的任务链还没接。 + """ d = (q.get('dir') or '').strip() if not d: raise ValueError('缺少目录参数') - exe = os.path.join(d, 'MAA.exe') + kind = (q.get('kind') or 'arknights').strip().lower() + names = (['MaaEnd.exe', 'MAAEND.exe', 'mxu.exe', 'MAA.exe'] + if kind == 'endfield' else ['MAA.exe']) + exe_name = next((n for n in names if os.path.isfile(os.path.join(d, n))), '') + exe = os.path.join(d, exe_name or names[0]) cfg_path = os.path.join(d, 'config', 'gui.new.json') profiles = [] if os.path.isfile(cfg_path): @@ -457,7 +477,8 @@ def api_maa_probe(q, _body): ob = operbox.probe(d) return { 'dir': d, - 'exeExists': os.path.isfile(exe), + 'exeExists': bool(exe_name), + 'exeName': exe_name, 'configExists': os.path.isfile(cfg_path), 'profiles': profiles, 'operbox': ob['exists'], @@ -847,6 +868,22 @@ def api_export(_q, body): return {'path': path, 'count': len(data)} +def api_schedule_status(q, _body): + return scheduler.status(q.get('since') or 0) + + +def api_schedule_save(_q, body): + return scheduler.save(body or {}) + + +def api_schedule_run(_q, body): + return scheduler.run_now((body or {}).get('id') or '') + + +def api_schedule_stop(_q, _body): + return scheduler.stop_current() + + ROUTES = { '/api/bootstrap': bootstrap, '/api/settings': api_settings, @@ -917,6 +954,11 @@ def api_export(_q, body): '/api/maa/capabilities': api_maa_capabilities, '/api/maa/profile': api_maa_profile, '/api/maa/build': api_maa_build, + # 定时任务(时间触发 / 链式启动) + '/api/schedule/status': api_schedule_status, + '/api/schedule/save': api_schedule_save, + '/api/schedule/run': api_schedule_run, + '/api/schedule/stop': api_schedule_stop, # 内置助手(M4) '/api/agent/status': api_agent_status, '/api/agent/config': api_agent_config, diff --git a/backend/core/maa.py b/backend/core/maa.py index eb743c5..8b3ac01 100644 --- a/backend/core/maa.py +++ b/backend/core/maa.py @@ -520,6 +520,28 @@ def profiles(maa_dir=None): return {'current': cfg.get('Current') or '', 'profiles': out} +def profile_account_name(profile, maa_dir=None): + """读某个配置档案「开始唤醒」里的 AccountName(只读,不改用户配置) + + 设置 → MAA 路径里选了「配置文件」之后,切号名就优先按这里的值来: + 用户自己的档案(moren / 136 / 157…)本来就在 MAA 里配好了账号切换, + 再让他手抄一遍纯属重复劳动。**只读**——写回用户的档案是另一条路 + (``set_tasklist`` / ``apply_plan``),这里一个字段都不许动。 + + 读不到(MAA 没装、档案被删、配置坏)就返回空串,调用方回落手填值。 + """ + name = str(profile or '').strip() + if not name: + return '' + cfg = _load_cfg(maa_dir) + conf = (cfg.get('Configurations') or {}).get(name) + if not isinstance(conf, dict): + return '' + su = next((t for t in (conf.get('TaskQueue') or []) + if isinstance(t, dict) and t.get('TaskType') == 'StartUp'), None) + return str(((su or {}).get('AccountName') or '')).strip() + + def tasklist(profile=None, maa_dir=None): cfg = _load_cfg(maa_dir) profile = profile or cfg.get('Current') or '' diff --git a/backend/core/multiacct.py b/backend/core/multiacct.py index 4971ad0..06d2067 100644 --- a/backend/core/multiacct.py +++ b/backend/core/multiacct.py @@ -60,10 +60,21 @@ def candidates(): 终末地账号(``game != 'arknights'``)MAA 根本不管,混进来会让后面 对着它的练度去找明日方舟作业,结果一片「全部打不了」。 """ + from . import acctbind + out = [] for row in accounts.list_accounts(): if (row.get('game') or 'arknights') != 'arknights': continue + # 绑了配置文件的账号:切号名以那份档案里的为准(用户 2026-11-22 要求, + # 规则在 acctbind)。没绑就用手填的,别为此去读 MAA 配置——列表接口 + # 每次启动都会走一遍,能省一次文件读取就省一次。 + nm = row.get('maaAccountName') or '' + if row.get('maaProfile'): + try: + nm, _src = acctbind.resolve(row['file']) + except Exception: + pass out.append({ 'file': row['file'], 'name': row.get('alias') or row.get('nickName') or row['file'], @@ -71,7 +82,7 @@ def candidates(): 'channel': row.get('channelName') or '', 'level': row.get('level'), 'maaProfile': row.get('maaProfile') or '', - 'accountName': row.get('maaAccountName') or '', + 'accountName': nm, 'maaDir': row.get('maaDir') or '', 'progress': row.get('progress') or {}, }) @@ -196,7 +207,11 @@ def _match(c): nm, why = acctname.check(names.get(c['file']) or '', c.get('channel')) reuse = '' if not nm: - # 没给名字就看 MAA 里有没有现成的档案对得上。 + # 设置里绑过的直接用(手填的尾号 / 选了配置文件带出来的账号名): + # candidates 给的已经是生效值,用户配过一次就不该再问(2026-11-22) + nm, _ = acctname.check(c.get('accountName') or '', c.get('channel')) + if not nm: + # 还没绑:看 MAA 里有没有现成的档案对得上。 # 注意取的是档案里的 **AccountName**,不是档案名:`maaProfile` # 是 moren / 136 这种档案名,拿它当账号名写进 StartUp,MAA 切号 # 必然失败(切号要的是登录界面那行 181****5505)。 @@ -210,8 +225,8 @@ def _match(c): missing.append({ 'what': 'accountName', 'file': c['file'], 'name': c['name'], 'question': '账号「%s」(%s)的手机号后 4 位是多少?给这四位就行' - '(如 5505,MAA 切号用的就是它);' - 'B 服填游戏里显示的用户名。%s' + '(如 5505);前 3 位 + 后 4 位也行(如 157****3635)。' + 'MAA 切号用的就是它;B 服填游戏里显示的用户名。%s' % (c['name'], c['channel'] or '未知渠道', ('你给的「%s」%s。' % (names.get(c['file']), why)) if names.get(c['file']) and why else ''), diff --git a/backend/core/scheduler.py b/backend/core/scheduler.py new file mode 100644 index 0000000..d0a7f89 --- /dev/null +++ b/backend/core/scheduler.py @@ -0,0 +1,591 @@ +# -*- coding: utf-8 -*- +"""定时任务:按时间启动程序 + 链式启动 + +语义照搬三月七助手的「定时任务配置」,只保留在我们这儿能落地、也确实是 +用户在用的那部分(朋友要搬的 autostart-138.exe / OneDragon-Launcher.exe / +cmd 批处理都属于这一类): + + - 触发两种:time(每周指定几天、某个 HH:MM)与 chain(上一条退出后接着跑) + - 动作一种:启动一个外部程序。三月七的「本体任务」我们不做——MAA 自己的 + 任务链由 skills 那一层负责,这里只当启动器 + - 同一时刻只跑一个任务。冲突策略 stop(停掉在跑的)/ skip(跳过本次) + - 链式任务失败后 continue(继续后面的)/ stop(停掉整条链) + +为什么不用 Windows 计划任务:链式启动(等上一个进程退出)系统计划任务 +表达不了;而且时间触发只在程序运行时生效——跟三月七一致,要开机自启 +得用户把本程序放进启动项。 + +数据存 config/schedule.json(原子写);日志写 debug/schedule.log,同时留 +一段内存环形缓冲给界面读(含 seq,供前端轮询拿「刚跑完」的通知)。 +""" +from __future__ import annotations + +import collections +import datetime +import os +import queue +import re +import shlex +import shutil +import subprocess +import threading +import time +import uuid + +from . import settings +from .atomicio import dump_json + +VERSION = 1 +MAX_TASKS = 60 +CONFLICTS = ('stop', 'skip') +ON_FAIL = ('continue', 'stop') +_TICK = 5.0 +_LOG_MAX = 1024 * 1024 + +_lock = threading.RLock() +_cache = None +_running = None # {id,name,proc,startedAt,killed} +_queue = queue.Queue() +_fired = {} # task id -> 'YYYY-MM-DD HH:MM'(同一分钟不重复触发) +_last = {} # task id -> {at,ok,code,text} +_events = collections.deque(maxlen=400) +_seq = 0 +_started = False + + +# ---------------------------------------------------------------- 存储 +def _path() -> str: + # 每次取 settings 的当前值:冒烟测试会把 CONFIG_DIR 指到临时目录 + return os.path.join(settings.CONFIG_DIR, 'schedule.json') + + +def _defaults() -> dict: + return {'version': VERSION, 'conflict': 'stop', 'onChainFail': 'continue', 'tasks': []} + + +def _new_id() -> str: + return 's' + uuid.uuid4().hex[:8] + + +def _norm_time(v) -> str: + m = re.match(r'^(\d{1,2}):(\d{1,2})$', str(v or '').strip()) + if not m: + return '' + h, mi = int(m.group(1)), int(m.group(2)) + if h > 23 or mi > 59: + return '' + return '%02d:%02d' % (h, mi) + + +def _parse_time(v): + s = _norm_time(v) + if not s: + return None + return int(s[:2]), int(s[3:]) + + +def _norm_weekdays(v): + """1=周一 … 7=周日。缺省/脏数据一律当每天全选(宁可按天跑,不要静默不跑)""" + if v is None: + return list(range(1, 8)) + out = set() + for d in (v if isinstance(v, (list, tuple, set)) else []): + if isinstance(d, bool): + continue + try: + n = int(d) + except (TypeError, ValueError): + continue + if 1 <= n <= 7: + out.add(n) + return sorted(out) + + +def _norm_timeout(v) -> int: + try: + n = int(v) + except (TypeError, ValueError): + return 0 + return max(0, min(n, 7 * 86400)) + + +def normalize_task(raw) -> dict: + raw = raw if isinstance(raw, dict) else {} + mode = 'chain' if str(raw.get('mode') or '').strip().lower() == 'chain' else 'time' + name = str(raw.get('name') or '').strip()[:40] or '未命名任务' + return { + 'id': str(raw.get('id') or '').strip()[:24] or _new_id(), + 'enabled': raw.get('enabled') is not False, + 'name': name, + 'mode': mode, + 'time': _norm_time(raw.get('time')) or '08:00', + 'weekdays': _norm_weekdays(raw.get('weekdays')), + 'program': settings.norm_dir(str(raw.get('program') or '')), + 'args': str(raw.get('args') or '').strip()[:1000], + 'cwd': settings.norm_dir(str(raw.get('cwd') or '')), + 'timeout': _norm_timeout(raw.get('timeout')), + 'notify': bool(raw.get('notify')), + } + + +def load() -> dict: + global _cache + with _lock: + if _cache is not None: + return _copy(_cache) + data = _defaults() + try: + import io + import json + with io.open(_path(), encoding='utf-8') as f: + saved = json.load(f) + if isinstance(saved, dict): + if saved.get('conflict') in CONFLICTS: + data['conflict'] = saved['conflict'] + if saved.get('onChainFail') in ON_FAIL: + data['onChainFail'] = saved['onChainFail'] + tasks = saved.get('tasks') + if isinstance(tasks, list): + data['tasks'] = [normalize_task(t) for t in tasks[:MAX_TASKS]] + except Exception: + pass # 没文件 / 坏了都按默认跑,坏文件留给用户自己看 + _cache = data + return _copy(data) + + +def _copy(cfg) -> dict: + return { + 'version': VERSION, + 'conflict': cfg.get('conflict') or 'stop', + 'onChainFail': cfg.get('onChainFail') or 'continue', + 'tasks': [dict(t) for t in (cfg.get('tasks') or [])], + } + + +def save(patch: dict) -> dict: + """整表保存(tasks / conflict / onChainFail),返回落盘后的视图""" + global _cache + patch = patch or {} + with _lock: + cur = load() + if 'conflict' in patch and patch['conflict'] in CONFLICTS: + cur['conflict'] = patch['conflict'] + if 'onChainFail' in patch and patch['onChainFail'] in ON_FAIL: + cur['onChainFail'] = patch['onChainFail'] + if isinstance(patch.get('tasks'), list): + seen = set() + tasks = [] + for raw in patch['tasks'][:MAX_TASKS]: + t = normalize_task(raw) + while t['id'] in seen: + t['id'] = _new_id() + seen.add(t['id']) + tasks.append(t) + cur['tasks'] = tasks + os.makedirs(settings.CONFIG_DIR, exist_ok=True) + dump_json(_path(), cur) + _cache = cur + return _copy(cur) + + +# ---------------------------------------------------------------- 时间计算 +def _due_slot(task, now_ts=None) -> str: + """当前这一分钟正好是这个任务的计划点就返回槽位串,否则空。 + + 只认「当前分钟」,不回看上一分钟:程序关着的时候错过的点不补跑—— + 补跑会在开机瞬间一口气把昨天所有的任务全拉起来,比漏一次更糟。 + """ + if task.get('mode') != 'time': + return '' + t = _parse_time(task.get('time')) + wd = task.get('weekdays') or [] + if not t or not wd: + return '' + dt = datetime.datetime.fromtimestamp(now_ts if now_ts is not None else time.time()) + if dt.isoweekday() not in wd: + return '' + if (dt.hour, dt.minute) != t: + return '' + return dt.strftime('%Y-%m-%d %H:%M') + + +def next_run_ts(task, now_ts=None) -> int: + if task.get('mode') != 'time': + return 0 + t = _parse_time(task.get('time')) + wd = task.get('weekdays') or [] + if not t or not wd: + return 0 + now = datetime.datetime.fromtimestamp(now_ts if now_ts is not None else time.time()) + # 同一分钟内还没触发过的,就算「下一次就是现在」,界面上不会显示成下周 + if _due_slot(task, now.timestamp()) and _fired.get(task.get('id')) != \ + now.strftime('%Y-%m-%d %H:%M'): + return int(now.replace(second=0, microsecond=0).timestamp()) + for off in range(0, 9): + day = (now + datetime.timedelta(days=off)).date() + if day.isoweekday() not in wd: + continue + cand = datetime.datetime.combine(day, datetime.time(*t)) + if cand > now: + return int(cand.timestamp()) + return 0 + + +def _chain_after(task, tasks) -> list: + """紧跟在 task 后面的一串 chain 任务(中间夹一条 time 任务就断链)""" + idx = next((i for i, t in enumerate(tasks) if t.get('id') == task.get('id')), -1) + if idx < 0: + return [] + out = [] + for t in tasks[idx + 1:]: + if t.get('mode') != 'chain': + break + if t.get('enabled'): + out.append(t) + return out + + +# ---------------------------------------------------------------- 日志/事件 +def _log_path() -> str: + return os.path.join(settings.DEBUG_DIR, 'schedule.log') + + +def _rotate_log(): + try: + if os.path.getsize(_log_path()) > _LOG_MAX: + os.replace(_log_path(), _log_path() + '.1') + except Exception: + pass + + +def _emit(kind, text, level='info', task=None) -> dict: + global _seq + task = task or {} + with _lock: + _seq += 1 + ev = { + 'seq': _seq, + 'ts': int(time.time()), + 'time': time.strftime('%m-%d %H:%M:%S'), + 'kind': kind, + 'level': level, + 'text': text, + 'taskId': task.get('id') or '', + 'name': task.get('name') or '', + 'notify': bool(task.get('notify')), + } + _events.append(ev) + try: + os.makedirs(settings.DEBUG_DIR, exist_ok=True) + _rotate_log() + with open(_log_path(), 'a', encoding='utf-8') as f: + f.write('%s [%s] %s\n' % (ev['time'], level, text)) + except Exception: + pass + return ev + + +def log_lines(limit=80) -> list: + with _lock: + return list(_events)[-limit:] + + +# ---------------------------------------------------------------- 执行 +def _split_args(s: str) -> list: + s = str(s or '').strip() + if not s: + return [] + if os.name != 'nt': + return shlex.split(s) + # Windows 下跟 CreateProcess 用同一套解析(引号、反斜杠转义都能对上), + # shlex(posix=False) 会把引号留在参数里 + try: + import ctypes + from ctypes import wintypes + fn = ctypes.WinDLL('shell32', use_last_error=True).CommandLineToArgvW + fn.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(ctypes.c_int)] + fn.restype = ctypes.POINTER(wintypes.LPWSTR) + free = ctypes.WinDLL('kernel32', use_last_error=True).LocalFree + free.argtypes = [wintypes.HLOCAL] + free.restype = wintypes.HLOCAL + n = ctypes.c_int() + arr = fn('m ' + s, ctypes.byref(n)) + if not arr: + raise ctypes.WinError(ctypes.get_last_error()) + try: + return [arr[i] for i in range(1, n.value)] + finally: + free(ctypes.cast(arr, wintypes.HLOCAL)) + except Exception: + return [p.strip('"') for p in re.findall(r'"[^"]*"|\S+', s)] + + +def _argv(task) -> list: + program = settings.norm_dir(task.get('program') or '') + if not program: + raise ValueError('没有填要运行的程序') + if not os.path.isabs(program): + found = shutil.which(program) + if found: + program = found + if not os.path.isfile(program): + raise ValueError('程序不存在:%s' % program) + args = _split_args(task.get('args')) + ext = os.path.splitext(program)[1].lower() + if ext in ('.bat', '.cmd'): + comspec = os.environ.get('COMSPEC') or 'cmd.exe' + # cmd /c 后面整条命令行要作为一个参数传,路径带空格时才不会被拆错 + return [comspec, '/d', '/c', subprocess.list2cmdline([program] + args)] + return [program] + args + + +def _popen(argv, cwd): + os.makedirs(settings.DEBUG_DIR, exist_ok=True) + _rotate_log() + log = open(_log_path(), 'a', encoding='utf-8') + flags = getattr(subprocess, 'CREATE_NEW_PROCESS_GROUP', 0) if os.name == 'nt' else 0 + try: + proc = subprocess.Popen( + argv, cwd=cwd, stdin=subprocess.DEVNULL, stdout=log, + stderr=subprocess.STDOUT, creationflags=flags) + finally: + log.close() # 子进程持有自己的句柄,父进程不需要一直开着 + return proc + + +def _kill(entry, why='') -> None: + entry['killed'] = True + proc = entry.get('proc') + if not proc: + return + if why: + _emit('kill', '停止「%s」:%s' % (entry.get('name') or '', why), 'warn', + {'id': entry.get('id'), 'name': entry.get('name')}) + try: + if os.name == 'nt': + # .bat 是 cmd 的子进程,只 terminate cmd 会留下孤儿;整棵树一起收 + subprocess.run(['taskkill', '/F', '/T', '/PID', str(proc.pid)], + capture_output=True, timeout=10) + else: + proc.terminate() + except Exception: + pass + try: + proc.wait(timeout=3) + except Exception: + try: + proc.kill() + except Exception: + pass + + +def _now_running_view(): + with _lock: + if not _running: + return None + return { + 'id': _running.get('id'), + 'name': _running.get('name'), + 'pid': _running.get('pid'), + 'startedAt': _running.get('startedAt'), + 'seconds': int(time.time() - (_running.get('startedAt') or time.time())), + } + + +def _enqueue(task, reason, respect_conflict=True) -> bool: + cfg = load() + victim = None + with _lock: + if _running and respect_conflict: + if cfg['conflict'] == 'skip': + _emit('skip', '跳过「%s」:任务「%s」还在跑(冲突策略=跳过本次)' + % (task.get('name'), (_running or {}).get('name')), 'warn', task) + return False + victim = _running + if victim: + _kill(victim, '被「%s」顶掉(冲突策略=停止正在运行的)' % task.get('name')) + _queue.put({'task': dict(task), 'reason': reason}) + _emit('queue', '排队「%s」(%s)' % (task.get('name'), reason), 'info', task) + return True + + +def _exec(job) -> None: + global _running + task = job['task'] + name = task.get('name') or '未命名任务' + try: + argv = _argv(task) + except Exception as e: + _emit('finish', '「%s」没跑起来:%s' % (name, e), 'err', task) + _last[task.get('id')] = {'at': int(time.time()), 'ok': False, 'code': None, 'text': str(e)} + return + + program = argv[0] if argv else '' + cwd = task.get('cwd') or '' + if not cwd: + cwd = os.path.dirname(settings.norm_dir(task.get('program') or '')) or settings.project_root() + if not os.path.isdir(cwd): + cwd = settings.project_root() + + _emit('start', '启动「%s」:%s' % (name, subprocess.list2cmdline(argv)), 'info', task) + try: + proc = _popen(argv, cwd) + except Exception as e: + _emit('finish', '「%s」启动失败:%s' % (name, e), 'err', task) + _last[task.get('id')] = {'at': int(time.time()), 'ok': False, 'code': None, 'text': str(e)} + return + + entry = {'id': task.get('id'), 'name': name, 'proc': proc, + 'pid': proc.pid, 'startedAt': time.time(), 'killed': False} + with _lock: + _running = entry + + started = time.time() + timeout = task.get('timeout') or 0 + timed_out = False + while True: + try: + code = proc.wait(timeout=0.5) + break + except subprocess.TimeoutExpired: + if timeout and time.time() - started > timeout: + timed_out = True + _kill(entry, '超过 %d 秒,强制结束' % timeout) + try: + code = proc.wait(timeout=5) + except Exception: + code = None + break + + elapsed = int(time.time() - started) + killed = bool(entry.get('killed')) and not timed_out + ok = (code == 0) and not killed and not timed_out + with _lock: + _running = None + _last[task.get('id')] = { + 'at': int(time.time()), 'ok': ok, 'code': code, + 'text': ('已停止' if killed else ('超时' if timed_out else '退出码 %s' % code)), + } + + took = '%d 分 %d 秒' % (elapsed // 60, elapsed % 60) if elapsed >= 60 else '%d 秒' % elapsed + if killed: + text = '「%s」已停止(用时 %s)' % (name, took) + level = 'warn' + elif timed_out: + text = '「%s」超时被结束(%s)' % (name, took) + level = 'err' + elif ok: + text = '「%s」完成,用时 %s' % (name, took) + level = 'ok' + else: + text = '「%s」失败,退出码 %s(用时 %s)' % (name, code, took) + level = 'err' + _emit('finish', text, level, task) + + # 被顶掉/手动停止的任务不再往下链,否则会跟新任务打架 + if killed: + return + cfg = load() + if ok or cfg['onChainFail'] == 'continue': + # 只排下一个:链上的每个任务跑完都会接着排它后面那个。一次性把整条链 + # 全排进去的话,后一个会被「上一条的链」和「自己前面那条的链」各排一次, + # 同一个任务跑两遍(实测踩过) + nxt = _chain_after(task, cfg['tasks'])[:1] + for item in nxt: + _enqueue(item, '链式', respect_conflict=False) + remaining = len(_chain_after(task, cfg['tasks'])) + if not ok and cfg['onChainFail'] == 'stop' and remaining: + _emit('chain', '「%s」失败,链式后续 %d 个任务不再执行' % (name, remaining), + 'warn', task) + + +def _worker() -> None: + while True: + job = _queue.get() + try: + _exec(job) + except Exception as e: # 单条任务炸了不能把整条调度线程带走 + _emit('error', '调度出错:%s' % e, 'err', job.get('task')) + finally: + _queue.task_done() + + +def _loop() -> None: + last_tick = time.time() + while True: + try: + now = time.time() + # 系统休眠/改时间后往回跳:把已触发记录清掉,否则同一分钟会再触发一次 + if now < last_tick - 90: + _fired.clear() + last_tick = now + for t in load()['tasks']: + if not t.get('enabled') or t.get('mode') != 'time': + continue + slot = _due_slot(t, now) + if not slot or _fired.get(t['id']) == slot: + continue + _fired[t['id']] = slot + _enqueue(t, '定时') + except Exception as e: + _emit('error', '调度循环出错:%s' % e, 'err') + time.sleep(_TICK) + + +def start() -> bool: + """起调度线程(幂等)。必须在数据根确定之后调用。""" + global _started + with _lock: + if _started: + return False + _started = True + for fn, nm in ((_worker, 'sched-worker'), (_loop, 'sched-loop')): + threading.Thread(target=fn, daemon=True, name=nm).start() + _emit('boot', '定时任务已就绪(%d 条)' % len(load()['tasks'])) + return True + + +# ---------------------------------------------------------------- 对外 +def status(since=0) -> dict: + cfg = load() + now = time.time() + tasks = [] + for i, t in enumerate(cfg['tasks']): + row = dict(t) + row['index'] = i + ts = next_run_ts(t, now) + row['nextRun'] = time.strftime('%m-%d %H:%M', time.localtime(ts)) if ts else '' + row['nextRunTs'] = ts + row['last'] = _last.get(t['id']) + tasks.append(row) + with _lock: + seq = _seq + events = [e for e in _events if since and e['seq'] > int(since)] + return { + 'ok': True, + 'tasks': tasks, + 'conflict': cfg['conflict'], + 'onChainFail': cfg['onChainFail'], + 'running': _now_running_view(), + 'seq': seq, + 'events': events, + 'log': log_lines(80), + 'logPath': _log_path(), + } + + +def run_now(task_id) -> dict: + cfg = load() + task = next((t for t in cfg['tasks'] if t.get('id') == task_id), None) + if not task: + raise ValueError('任务不存在:%s' % (task_id or '(没选)')) + _enqueue(task, '手动') + return status() + + +def stop_current() -> dict: + with _lock: + entry = _running + if entry: + _kill(entry, '手动停止') + return status() diff --git a/backend/core/settings.py b/backend/core/settings.py index c628a1d..cb30434 100644 --- a/backend/core/settings.py +++ b/backend/core/settings.py @@ -181,6 +181,10 @@ def ensure_dirs(): DEFAULTS = { 'maaDir': '', + # 明日方舟终末地那一栏用的 MAAEND 根目录(设置里按游戏分 tab,互不覆盖)。 + # 目前只做到「能配路径」,MAAEND 的任务链还没接——先留位,免得以后 + # 加进来时还要动一次配置格式。 + 'maaEndDir': '', 'maaDirs': [], # 用过的 MAA 根目录历史(添加账号时「已存过」列表的数据源) 'autoStartMaa': True, 'autoUpdatePack': True, # 启动后自动拉取新的游戏资源包(关卡/干员/活动) @@ -401,6 +405,8 @@ def save(patch: dict) -> dict: continue if k == 'maaDir': v = _norm_dir(v) + elif k == 'maaEndDir': + v = _norm_dir(v) elif k == 'proxy': v = _norm_proxy(v) elif k == 'charBlacklist': diff --git a/backend/core/skills.py b/backend/core/skills.py index 182b78d..14ff211 100644 --- a/backend/core/skills.py +++ b/backend/core/skills.py @@ -77,28 +77,22 @@ def _account_file(name): def _account_name_tail(file): """账号的切号名(MAA StartUp 切号用的那个) - **唯一来源:账号自己绑定的 ``maa.accountName``**(设置 → MAA 路径里填的 - 手机尾号,或对话里用户报给助手后回存的)。给空串就退回 adb 重启那条路, + 规则只有一份,在 ``acctbind.resolve``:**选了配置文件就读那份档案里的 + AccountName**(用户在 MAA 里已经配过切号,不该再手抄),没选 / 手填过 + 就用账号自己存的 ``maa.accountName``。给空串就退回 adb 重启那条路, 调用方负责提示去设置页填。 - 用户口径(2026-11-18):agent 模式跑的是**临时配置**——StartUp 任务参数 - 只有「开始唤醒 + 手机号」,MaaCore 按参数自己换号,**不读也不改用户的 - MAA 配置档案**。以前这里会退回读 MAA 当前档案的 ``AccountName`` / 档案名 - (moren / 136 / 157…)来猜,两个问题:一是违背上面的口径(agent 不该碰 - 用户的 MAA 配置);二是猜错代价大——程序里两个游戏账号对 MAA 里五个尾号 - 档案,档案名和 AccountName 根本说不清谁是谁,错配了 MAA 在账号列表里 - 死找 4 分钟超时。谁要用哪个尾号,只有账号绑定这一个可信来源。 + 用户口径(2026-11-18 起,2026-11-22 放宽):agent 模式跑的是**临时配置** + ——StartUp 任务参数只有「开始唤醒 + 切号名」,MaaCore 按参数自己换号, + **不读也不改用户的 MAA 配置档案**;读档案只发生在「用户指定了这个账号 + 用哪份档案」的时候,而且只读一个字段。 **昵称绝不能拿来顶**:官服切号认的是手机号,拿昵称 MAA 在账号列表里 翻不到,acctname.check 会当场拒。 """ - try: - snap = accounts.get_account(file) - except Exception: - snap = {} - maa = snap.get('maa') if isinstance(snap, dict) else None - maa = maa if isinstance(maa, dict) else {} - return (maa.get('accountName') or '').strip() + from . import acctbind + nm, _src = acctbind.resolve(file) + return nm def _client_of(file): @@ -186,16 +180,37 @@ def norm_stage(raw, log=None): # ---------------------------------------------------------------- wakeup +def _remember_tail(file, raw): + """用户在对话里报了尾号 → 存进账号设置(下次不用再问) + + 只写本程序自己的账号 json(``maa.accountName`` + ``accountNameFrom=manual``), + MAA 那边一个字段都不动。存不进去(文件被占/没权限)不挡主流程。 + """ + if not str(raw or '').strip(): + return '' + try: + from . import acctbind + nm, _why = acctbind.bind(file, raw, _client_of(file)) + return nm + except Exception: + return '' + + def skill_wakeup(params, log, tid=None): """skill 1:唤醒游戏到主界面 accountName / tail 有值时走 MAA StartUp(能按切号名换账号,官服填手机号 - 后 4 位如 5505);没给就用 adb 直连重启(快,且登录页/START 页/弹窗都能 - 自己处理——stagenav.restart_app)。 + 后 4 位如 5505,也可以给前 3 位 + 后 4 位如 157****3635);没给就用 adb + 直连重启(快,且登录页/START 页/弹窗都能自己处理——stagenav.restart_app)。 """ file = _account_file(params.get('account') or '') - tail = (params.get('accountName') or params.get('tail') - or _account_name_tail(file)).strip() + given = (params.get('accountName') or params.get('tail') or '').strip() + if given: + # 用户亲口报的尾号顺手存进设置:下次挂机 / 换 skill 都不用再问 + saved = _remember_tail(file, given) + if saved: + log('切号名 %s 已记到这个账号(设置 → MAA 路径)' % saved) + tail = (given or _account_name_tail(file)).strip() if tail: # 临时配置:StartUp 任务参数只有「开始唤醒 + 切号名」,MaaCore 按参数 # 自己换号——不读也不改用户的 MAA 配置档案 @@ -214,7 +229,7 @@ def skill_wakeup(params, log, tid=None): log('adb:%s' % detail) if not alive: raise RuntimeError(detail) - log('这个账号没绑定切号名(设置 → MAA 路径里填手机尾号,' + log('这个账号没绑定切号名(设置 → MAA 路径里填手机号后 4 位,' '或对话里直接告诉我),只能重启当前账号的游戏') if stagenav.at_home(t) and not stagenav.on_login_page(t) \ and not stagenav.in_story_page(t) and not stagenav.in_story_dialog(t): @@ -1133,8 +1148,10 @@ def skill_train(params, log, tid=None): if not params.get('account') and saved.get('account'): params = dict(params, account=saved['account']) file = _account_file(params.get('account') or '') - tail = (params.get('accountName') or params.get('tail') - or _account_name_tail(file) or '').strip() + given = (params.get('accountName') or params.get('tail') or '').strip() + if given: + _remember_tail(file, given) # 用户报了尾号就存进设置,别下次再问 + tail = (given or _account_name_tail(file) or '').strip() switch = params.get('switchAccount') if switch is None: switch = bool(tail) # 只有显式给了切号名才切号 @@ -1165,7 +1182,7 @@ def skill_train(params, log, tid=None): log('先开始唤醒,切到 %s' % tail) else: log('先开始唤醒(不切号%s)' % (';要切号去设置 → MAA 路径里给账号' - '填手机尾号' if not tail else '')) + '填手机号后 4 位' if not tail else '')) spec = { 'tasks': (['startup', 'operprogress'] if wakeup else ['operprogress']), diff --git a/backend/main.py b/backend/main.py index 3fd7639..9629a38 100644 --- a/backend/main.py +++ b/backend/main.py @@ -295,6 +295,24 @@ def choose_folder(self, title='选择文件夹', initial=''): except Exception as e: return {'path': None, 'error': str(e)} + def choose_file(self, title='选择程序', initial=''): + """选一个文件(定时任务里挑要启动的 exe / bat)。没有 pywebview 时返回空。""" + import webview + try: + res = webview.windows[0].create_file_dialog( + webview.OPEN_DIALOG, + directory=initial or '', + allow_multiple=False, + file_types=('可执行文件 (*.exe;*.bat;*.cmd)', '所有文件 (*.*)'), + ) + if not res: + return {'path': None} + if isinstance(res, (list, tuple)): + return {'path': res[0] if res else None} + return {'path': res} + except Exception as e: + return {'path': None, 'error': str(e)} + def open_path(self, path): """用系统默认方式打开文件/文件夹""" try: @@ -408,6 +426,12 @@ def main(): name='garrison-upd-check').start() except Exception: pass + # 定时任务:时间触发 + 链式启动。线程自己 sleep 轮询,起不来不影响主流程 + try: + from core import scheduler as _sched + _sched.start() + except Exception: + log('[警告] 定时任务没起来\n' + traceback.format_exc()) # 程序自更新:装完后由 api 层调 install(),需要让整个进程退出, # 而 api 不能 import main,所以反过来把退出函数注册进去 appupdate.set_quit_hook(lambda reason: _quit(0, reason)) diff --git a/docs/agent.md b/docs/agent.md index 0bf0fab..73b603c 100644 --- a/docs/agent.md +++ b/docs/agent.md @@ -162,20 +162,30 @@ MAA 的多账号机制只有一条:**一个配置档案 = 一个账号**。 "AccountSwitchEnabled": true, ...} ``` -`AccountName` 是 MAA 拿去和登录界面那行 OCR 结果做**子串匹配**的,所以三种写法都认(官方说明原话:「可输入 123****4567、4567 或 23****45」): +`AccountName` 是 MAA 拿去和登录界面那行 OCR 结果做**子串匹配**的,所以四种写法都认(官方说明原话:「可输入 123****4567、4567 或 23****45」): -- 手机号后 4 位 `5505` —— **对话里只问这个** +- 手机号后 4 位 `5505` —— **对话里默认问这个** +- 前 3 位 + 后 4 位 `1573635` / `157 3635` —— 2026-11-22 用户要求也收 - 部分掩码 `23****45` -- 完整掩码 `181****5505` +- 完整掩码 `181****5505` / `157****3635` 本机 MAA 里用户自己的档案写的就是 `136` / `3635` / `1686` / `181****5505`,混着用的。 -**这个信息森空岛给不了、MAA 也给不了**——只能问用户。但有个省事的办法:MAA 里已经配过的档案,`AccountName` 和森空岛昵称对得上就直接复用(`multiacct._match()`,容忍 `小卡拉帕鲁灰#6408` ↔ `小卡拉帕鲁灰`)。对不上的才进 `missing` 让助手问。 +**这个信息森空岛给不了**——要么问用户,要么照他绑的配置文件读。三条来源按顺序(`acctbind.resolve()`): + +1. 账号绑了 MAA 配置文件(设置 → MAA 路径 → 配置文件)→ 读那份档案 StartUp 的 `AccountName`。**只读**,MAA 里一个字段都不改。 +2. 账号存的 `maa.accountName`(设置里手填的、或对话里报过后 `set_account_name` 存下来的)。 +3. 都没有 → 问用户(官服问后 4 位;用户主动给 `157****3635` 也照收)。 + 用户一报尾号就调 `set_account_name` 存进设置,下次不用再问。 + +`multiacct._match()` 还留了一条按昵称对档案的兜底(容忍 `小卡拉帕鲁灰#6408` ↔ `小卡拉帕鲁灰`),对不上的才进 `missing`。 问的时候**别让用户拼星号**,直接问「手机号后 4 位是多少」。用户给全号、带横线、星号数量不对、全角数字都行,`acctname.normalize()` 会统一成 `前3****后4`;给 3~4 位片段就原样保留交给 MAA 子串匹配。 > 2026-11-17:这之前校验写死成 `^\d{3}\*{4}\d{4}$`,用户照 MAA 文档只给尾号就被判非法,助手只能反复追问,任务最后出不来。规则现在只有一份:`backend/core/acctname.py`,别再在别处写第二份正则。 +> 2026-11-22:`_roster` 原来完全禁读用户的 MAA 档案(怕档案和账号对不上号)。现在不是猜——哪份档案由用户在设置里点,程序照他点的读;他手改过的切号名(`accountNameFrom=manual`)优先,不让档案里的旧号码盖回去。 + 另外 `maaProfile` 是**档案名**(`moren` / `136`),不是切号名。曾经 `multiacct.plan()` 里写成 `names.get(...) or c['maaProfile']`,等于把档案名当账号名写进 StartUp,MAA 切号必然失败——整轮挂机死在「登录」这一步。 流程: diff --git a/docs/backend.md b/docs/backend.md index 22471be..dc87210 100644 --- a/docs/backend.md +++ b/docs/backend.md @@ -35,7 +35,8 @@ | `core/asstlog.py` | MAA 日志观测:`debug/asst.log` 的回调 JSON + `debug/gui.log` 的 `Start/Completed Task Chain` → 结构化事件流;增量读、轮转识别、状态推导(idle/running/stalled/failed/done)、`failures()` 还原「跑过哪几关、哪几关没跑完」 | | `core/maalog.py` | 直连跑机时的 MAA 日志桥:`maalog.Tap` 从 `asst.log` **末尾**开始增量读(`Tail.seek_end()`,不重放历史),只把 `[ERR]/[WRN]` 里能解释问题的行翻成人话(认不出关卡名 / 干员不存在 / 参数不合法),噪行丢弃、同句 20 秒去重。回调 JSON 行不读——那部分由 `maacore` 回调负责,避免同一件事写两遍 | | `core/watch.py` | 自愈层:后台线程盯 `asstlog` 的状态,判停滞就关 MAA → 从当前关续写作业列表 → 重启。同一关连续 3 次救不回来就停手报给用户 | -| `core/acctname.py` | 切号名(MAA `AccountName`)的归一化与校验,**唯一一份规则**。MAA 是拿它和登录界面那行 OCR 做子串匹配,所以 `5505` / `136` / `23****45` / `181****5505` 都合法;用户给全号、带横线、全角数字、星号数量不对都归一成 `前3****后4`。官服只拦「填了昵称」(拿昵称切号会死循环几十次然后失败),B 服不拦 | +| `core/acctname.py` | 切号名(MAA `AccountName`)的归一化与校验,**唯一一份规则**。MAA 是拿它和登录界面那行 OCR 做子串匹配,所以 `5505` / `136` / `23****45` / `157****3635` / `181****5505` 都合法;用户给全号、带横线、全角数字、星号数量不对都归一成 `前3****后4`,只给「前 3 + 后 4」(`1573635` / `157 3635`)也收。官服只拦「填了昵称」(拿昵称切号会死循环几十次然后失败),B 服不拦 | +| `core/acctbind.py` | 「这个账号跑 StartUp 写哪个切号名」的唯一解析入口:账号绑了配置文件(`maa.profile`)且没手改过 → 读那份档案 StartUp 的 `AccountName`(`maa.profile_account_name()`,**只读**);否则用账号存的 `maa.accountName`;都没有才返回空让调用方去问用户。手改过的值标 `accountNameFrom=manual`,不会被档案里的旧号码盖回去 | | `core/multiacct.py` | 多账号编排:MAA「一个配置档案 = 一个账号」,按各账号练度各挑作业,串行切换执行。档案一律新建 `PRTS-` 前缀的那份,用户自己的档案一个字段都不动。切号名统一走 `acctname.check()`;`maaProfile` 是档案名不是切号名,别混用 | | `core/maaplan.py` | 把「用户想怎么挂」翻成可执行的东西,两条路线:① `build_queue`/`ensure_profile` 写 GUI 的 `TaskQueue` + `RunDirectly`(能看界面,但**不能抄作业**:MAA 的 `InitializeItems` 不认 CopilotTask,会抛 NotImplementedException 让整个任务列表空白);② `core_tasks`/`run_core` 生成 MaaCore 的任务序列直接驱动(能抄作业、能跑 Custom 小活动、自己按开始)。`run_core` 跑抄作业固定四段:**登录(StartUp)→ `AsstStop` 把 MAA 停住 → 用 `stagenav` 点到关卡地图 → 再 append Copilot + `AsstStart`**。停这一步不能省:不停的话 MaaCore 还在按自己的逻辑截屏/滑动,和我们的 adb 点击抢界面。导航失败且这一关有卡片模板(老故事集)时**直接报错**,不把作业交给 MAA——它只会横向滑主线,白跑 30 秒再失败(2026-11-17 SV 实测:停住后 24 秒内 MAA 就在地图上 OCR 到 SV-1、点开始行动、自动编队开打) | | `core/maacore.py` | MaaCore 直连:`AsstCreateEx` → `AsstLoadResource` → `AsstConnect` → `AsstAppendTask` → `AsstStart`,回调翻成事件流。三个坑写在文件头:`AsstCreateEx` 的 restype 必须是 `c_void_p`(否则 64 位句柄截断成 32 位,每次 append 都 access violation)、Copilot 的 `filename` 必须绝对路径、`copilot_list` 的键是 `filename` 不是 `file_name`(写错会让进程 C++ 异常崩溃) | @@ -84,7 +85,7 @@ main() | POST | `/api/settings` | 保存设置(白名单 `maaDir` / `profile` / `autoStartMaa` / `lastAccount`) | | GET | `/api/accounts` | 账号列表(含每个账号的统计摘要) | | GET | `/api/account?file=` | 单个账号完整配置:account / stats / missing / chars | -| POST | `/api/account/maa` | 把 `maa.profile` 等用户字段写回账号 JSON(同步不覆盖的那几个)。`dir` 会归一化并并入「用过的 MAA」历史;`accountName`(切号名)统一走 `acctname.check()`——`5505` / `181 5505` / `181****5505` 都收成 `181****5505`,官服填昵称当场 400,**留空合法**(还没填 / 想清掉) | +| POST | `/api/account/maa` | 把 `maa.profile` 等用户字段写回账号 JSON(同步不覆盖的那几个)。`dir` 会归一化并并入「用过的 MAA」历史;`profile` 是 MAA 的配置档案名(只记名字,**不读写档案内容**);`accountName`(切号名)统一走 `acctname.check()`——`5505` / `181 5505` / `157****3635` 都收成规范写法,官服填昵称当场 400,**留空合法**(还没填 / 想清掉)。`accountNameFrom`:`manual`=手填(以用户为准)/ `profile`=跟着配置文件走;不传时按 `manual` | | POST | `/api/account/token` | 设置 → 账号管理用:返回 `{has, broken, token, mask}`。`token` 是明文(只在本地窗口里展示,不落日志、不进 bootstrap),`mask` 只留尾 4 位;`broken=true` 表示密文本机解不开(换电脑 / 换 Windows 用户),与「没存过」分开 | | POST | `/api/account/token/check` | 拿 grant 接口验一次 token 还能不能用(最长约 12 秒)。只有明确失效才回 `ok:false`,网络问题走异常——界面据此决定要不要解锁「修改」 | | POST | `/api/account/token/set` | 换 token:先 `Skland(token)` 登录 + 取绑定,确认 token 绑的 uid 就是这个账号,才把密文写回 `skd` 段(练度 / 进度 / MAA 绑定一个字段都不动)。uid 对不上直接报错,防止粘错号把凭证静默换掉 | @@ -454,18 +455,19 @@ MAA 事件日志通过 tid 透传进同一条任务日志,右栏日志栏与 永远拿不到,StartUp 不带 `account_name`:游戏已在主界面时这条链 2 秒就 「完成」,什么都没做,用户看到的就是「没唤醒就开始导航/培养」。 **昵称绝不能顶**:官服切号认手机号,拿昵称 MAA 在账号列表里翻不到。 -2. **agent 模式切号 = 临时配置,不碰用户的 MAA 档案**(用户口径,2026-11-18 - 晚再定版)。agent 跑 MAA 从不读写用户的 `gui.new.json` 档案:所谓的 - 「配置」就是 StartUp **任务参数**——只配「开始唤醒 + 该账号绑定的手机 - 尾号」,MaaCore 的 `StartUpTask` 拿到非空 `account_name` 就自己换号 +2. **agent 模式切号 = 临时配置,只读用户的 MAA 档案**(2026-11-18 定口径, + 2026-11-22 放宽一处)。agent 跑 MAA 从不**写**用户的 `gui.new.json` 档案: + 所谓的「配置」就是 StartUp **任务参数**——只配「开始唤醒 + 该账号的切号 + 名」,MaaCore 的 `StartUpTask` 拿到非空 `account_name` 就自己换号 (核对过 6.20.1 源码:`set_params` 只认 `account_name` / `client_type` / `start_game_enabled` 三个键,**没有** `account_switch_enabled`,给了也 - 被忽略)。切号名的**唯一来源**是账号绑定 `maa.accountName`(设置 → MAA - 路径填的,或对话里用户报给助手后回存的);中间版曾加过「读 MAA 当前 - 档案 AccountName / 纯数字档案名」的 fallback,已按上面口径拆掉—— - 程序里两个游戏账号对 MAA 里五个尾号档案,档案名和 AccountName 说不清 - 谁是谁,猜错 MAA 在账号列表里死找 4 分钟。预检(`agent._roster`)同理: - 只信用户这次给的 + 账号文件里存过的,没有就**问用户**,不从档案猜。 + 被忽略)。切号名的来源按顺序(`acctbind.resolve`):① 账号绑的配置文件 + 里 StartUp 的 `AccountName`(用户 2026-11-22 要求:他在 MAA 里已经配过 + 一次,不该再抄一遍,**这一处破例读档案,但只读一个字段**);② 账号存的 + `maa.accountName`(手填的 / 对话里报的);③ 都没有就**问用户**。 + 中间版(2026-11-18)曾完全禁读档案,因为「两个游戏账号对 MAA 里五个 + 尾号档案,档案名和 AccountName 说不清谁是谁」——现在不是猜:绑哪份档案 + 由用户在设置里点名,程序照他点的读,手改过的值(`manual`)优先。 2. **「培养干员没进去就报错」——`Engine.wait` 启动竞态**。asst.log 现场: StartUp 完成 → append OperProgress → `start` → **同一毫秒 `~Assistant` 析构**,任务「完成」但培养一步没跑。原因:AsstStart 异步生效,刚 start @@ -1213,10 +1215,16 @@ MaaCore 只会报 `adb 连不上`,用户第一反应是程序坏了。放一 `accountName` 现在可以直接在设置 → MAA 路径里按账号填。规则不在这儿重写, 一律 `acctname.check(nm, channel)`:能吃 `5505` / `136` / `23****45` / -`181****5505` / 全角与带横线的写法;官服只拦「填了昵称」(MAA 拿昵称去 +`157****3635` / 全角与带横线的写法;官服只拦「填了昵称」(MAA 拿昵称去 账号列表里子串匹配,死找几十次后超时,整轮挂机废掉)。**空串放行**—— 「还没填」和「填错了」是两件事,用 `check()` 原文会把清空输入框也拦下。 +同一个接口还收 `profile`(MAA 的配置档案名)和 `accountNameFrom` +(`manual` / `profile`)。设置页里选了配置文件,前端会把该档案 StartUp 的 +`AccountName` 带进输入框、来源标 `profile`;用户一改就标 `manual`,之后 +`acctbind.resolve` 以他填的为准。**档案本身只读**,`gui.new.json` 一个字段 +都不写。 + ## 卫戍协议速刷(`garrison.py` / `garrisondl.py` / `resources/garrison/`,2026-11-20) **核心不在仓库里**。真正干活的 `service.mjs` 是第三方插件 @@ -1278,3 +1286,38 @@ MAA 的 `gui.new.json` 里 `ConnectSettings` 抄(MuMu→`mumu`+Extras 快速 **推论**:以后核心升到 v1.2.0、v2.0.0 都不用改代码;只有把包挪到非 `medal-farm-v*` 的目录结构时才需要动 `core_dir()`。 + +## 定时任务(`scheduler.py`,2026-11-22) + +设置里的「定时任务」页:到点启动外部程序,支持链式启动。只做「把用户的脚本 +按时拉起来」这一件事——`autostart-*.exe`、`OneDragon-Launcher.exe`、cmd +批处理这类现成脚本都能原样填进来(程序 + 参数照抄)。 + +| 概念 | 实现 | +|---|---| +| 触发 | `mode=time`:`weekdays`(1=周一…7=周日)+ `time`(HH:MM);`mode=chain`:接在上一条后面 | +| 动作 | 启动一个程序(exe / bat / cmd)。bat/cmd 走 `cmd /d /c "<整条命令行>"`,路径带空格也不会拆错 | +| 冲突 | 同一时刻只跑一个:`conflict=stop` 停掉在跑的,`skip` 跳过本次 | +| 链式失败 | `onChainFail=continue` 继续下一个,`stop` 停掉整条链 | + +几个踩过的点: + +- **只认当前分钟,不补跑**。程序关着时错过的计划点直接跳过——开机瞬间把前几天 + 的任务一起补跑,比漏一次更糟。 +- **链式只排下一个**。每条任务跑完只找它后面最近的一条 chain 任务;一次性把 + 整条链全排进队列的话,同一个任务会被前后两条各排一次(实测跑了两遍)。 +- **停用的 chain 跳过但不截断**:A → B(停用)→ C 会跑 A、C。 +- **杀进程要杀树**。bat 是 cmd 的子进程,只 terminate cmd 会留下孤儿;Windows + 上统一 `taskkill /F /T /PID`。 +- **参数按 `CommandLineToArgvW` 拆**(跟 CreateProcess 同一套规则)。`shlex` + 在 Windows 上会把引号留在参数里,`--x "a b"` 会变成 `'"a b"'`。 +- **数据/日志**:`config/schedule.json`(原子写);`debug/schedule.log` + + 内存环形缓冲。设置页 5 秒轮一次 `/api/schedule/status`,跑完的提示靠 + `events`(带 seq,同一个事件不会弹两遍)。 + +接口:`/api/schedule/status`(`?since=` 拿增量事件)、`/api/schedule/save` +(整表)、`/api/schedule/run`、`/api/schedule/stop`。以后让 agent 帮用户写 +定时,直接调这四个就行,不需要另开一套。 + +线程在 `main()` 里起(`scheduler.start()`:tick + worker 两个守护线程), +起不来只记一行警告,不影响主流程。 diff --git a/docs/config.md b/docs/config.md index a44450b..d35a37c 100644 --- a/docs/config.md +++ b/docs/config.md @@ -216,6 +216,7 @@ WR=画中人 ZT=崔林特尔梅之金 ```jsonc { "maaDir": "D:\\2.game\\MAA-ALL\\MAA-ARK\\MAA-v6.20.1-win-x64", + "maaEndDir": "", "maaDirs": ["D:\\2.game\\MAA-ALL\\MAA-ARK\\MAA-v6.20.1-win-x64"], "autoStartMaa": true, "autoUpdatePack": true, @@ -228,6 +229,7 @@ WR=画中人 ZT=崔林特尔梅之金 | 字段 | 说明 | |---|---| | `maaDir` | 全局默认 MAA 根目录(含 `MAA.exe` 与 `config/gui.new.json`)。写入路径时会自动规范化斜杠 | +| `maaEndDir` | 明日方舟终末地那一栏的 MAAEND 根目录。设置里按游戏分了 tab,两套路径互不覆盖;MAAEND 的任务链还没接,这项先留着位 | | `maaDirs` | 用过的 MAA 根目录历史(添加账号时「已存过」列表的数据源) | | `autoStartMaa` | 写完作业后是否自动启动 MAA | | `autoUpdatePack` | 启动后是否自动下载新的游戏资源包(新关卡 / 新干员 / 新活动),默认开。关掉不影响使用,只是要等发新版才有新数据 | @@ -242,6 +244,37 @@ WR=画中人 ZT=崔林特尔梅之金 手改坏了 JSON 也不会丢数据:启动时会把坏文件改名成 `settings.json.broken-<时间戳>` 保住原件,程序按默认设置继续运行。 +## schedule.json(定时任务) + +设置 → 定时任务整页存在这个文件里,跟 `settings.json` 分开:任务列表改得频繁, +还要带运行记录,混进偏好设置里会让那份文件越来越难手改。 + +```jsonc +{ + "version": 1, + "conflict": "stop", // stop=停掉在跑的 / skip=跳过本次 + "onChainFail": "continue", // continue=继续后续 / stop=停掉整条链 + "tasks": [ + { + "id": "s1a2b3c4", + "enabled": true, + "name": "早上挂长草", + "mode": "time", // time=按时间,chain=接在上一条后面 + "time": "08:00", + "weekdays": [1, 2, 3, 4, 5, 6, 7], // 1=周一 … 7=周日 + "program": "D:\\tools\\autostart-138.exe", + "args": "--autostart --instance 138", + "cwd": "", // 空 = 程序所在目录 + "timeout": 0, // 秒,0=不限 + "notify": true + } + ] +} +``` + +删掉这个文件等于清空全部定时任务;程序运行中读的是内存缓存,改完要重启或 +在界面上再保存一次才生效。 + ## 账号文件(<昵称> <服务器>.json) schemaVersion 2 快照(`backend/core/updater.py` 的 `build_snapshot`)加一段 @@ -251,7 +284,10 @@ schemaVersion 2 快照(`backend/core/updater.py` 的 `build_snapshot`)加一 { "schemaVersion": 2, "account": { "uid": "…", "nickName": "…", "channelName": "官服", /* … */ }, - "maa": { "dir": "D:\\…", "profile": "", "note": "" }, // 该账号绑定的 MAA 目录 + "maa": { "dir": "D:\\…", // 该账号绑定的 MAA 目录(空=用全局默认) + "profile": "moren", // 该账号用的 MAA 配置档案名(切号名从它读) + "accountName": "181****5505", // 切号名(MAA StartUp 的 AccountName) + "accountNameFrom": "profile" }, // profile=跟着档案走 / manual=用户手填 "skd": { "alias": "大号", // 备注(添加时填的) "addedAt": "2026-11-05T07:40:00", // 添加时间 "data": "AQAAANCMnd8BFdERjHoAwE…" }, // base64(DPAPI(token)) @@ -265,6 +301,11 @@ schemaVersion 2 快照(`backend/core/updater.py` 的 `build_snapshot`)加一 删文件即整体清除。从 MAA 导入干员识别结果(界面的「从 MAA 导入干员信息」) 也是改这份文件——只覆盖 `chars/stats/missing/sync`,其余原样保留。 +`maa.profile` 只是**记名字**:选了档案,`acctbind.resolve()` 会去那份档案的 +`TaskQueue[0]`(StartUp)读 `AccountName` 当切号名,**不写回** MAA 的 +`gui.new.json`。`accountNameFrom=manual` 表示用户手填过,这时以账号里的 +`accountName` 为准,档案里的旧值不会盖回来。 + ### 终末地账号 同一个森空岛 token 若还绑了《明日方舟:终末地》角色,同步时会额外生成一份 diff --git a/docs/frontend.md b/docs/frontend.md index fdfdedd..ece6e98 100644 --- a/docs/frontend.md +++ b/docs/frontend.md @@ -230,18 +230,38 @@ MAA 导入建号),两种入口行为完全一致。 ## 设置弹窗(左 tab + 右内容,2026-11-18) `openSettings()` 从「一列到底」改成左右两栏:`.modal.modal-set`(960×660, -`padding: 0`)里放 `.set-shell`,左边 `.set-side` 是 6 个页签,右边 +`padding: 0`)里放 `.set-shell`,左边 `.set-side` 是 7 个页签,右边 `.set-panes` 自己滚,底部 `.set-foot` 只留一句说明 + 「关闭」。 | 页签 | 内容 | 保存方式 | |---|---|---| -| 账号管理 | 每个账号一张卡:昵称 / 渠道 / UID / 干员数 / 同步时间 + token 行(掩码显示、显示、验证、修改)+ 删除账号 | 删除二次确认;token 只在验证失效后解锁,见下 | -| MAA 路径 | 全局默认目录 + 自动启动开关;下面按账号给「切号名」与「这个账号的 MAA 路径」,带浏览 / 检测 / 读档案 | 每行自己的「保存」;开关即时保存 | +| 账号管理 | 顶部「明日方舟 / 明日方舟终末地」分组;每个账号一张卡:昵称 / 渠道 / UID / 干员数 / 同步时间 + token 行(掩码显示、显示、验证、修改)+ 删除账号 | 删除二次确认;token 只在验证失效后解锁,见下 | +| MAA 路径 | 同样按游戏分两组:方舟是 MAA 根目录 + 自动启动开关,终末地是 MAAEND 根目录(预留,能存路径与识别主程序);下面每个账号一张卡:**第一行**这个账号的 MAA 路径(浏览 / 检测),**第二行**配置文件下拉 + 切号名(选档案自动带出、可手改) | 每行自己的「保存」;开关即时保存 | +| 定时任务 | 表格(启用 / 名称 / 执行计划 / 程序 / 参数 / 通知)+ 添加 / 编辑 / 上移 / 下移 / 删除 / 立即运行 / 停止,底部冲突策略与链式失败策略,再下面是最近 40 行运行日志 | 勾选与下拉即时保存;表格类操作整表保存 | | 版本更新 | 游戏资源、程序本体两条检查链 + 两个自动检查开关 + 网络代理(保存并测试) | 按钮 / 勾选即时保存 | | 助手设置 | Base URL / 模型名 / API Key / 免确认开关,底部状态行 | 自己的「保存」 | | 数据与日志 | 账号数据 / 配置 / 日志 / 运行根四个目录 + 打开按钮 | 只读 | | 黑名单 | 干员 / 作者 / 作业三块,各带条数与「是什么」的说明 + 管理按钮 | 打开原子弹窗,关窗回刷条数 | +**游戏分组(2026-11-22)**:账号管理与 MAA 路径两页共用同一个 `setGame` +状态——切一页另一页跟着切,用户不会「在 MAA 路径里看终末地、切回账号管理 +又跳回方舟」。分组条直接复用侧栏那套 `.game-switch / .gswitch`(同一套配色, +终末地是紫青渐变),外面套 `.set-gswitch` 限宽 380px。两组的账号列表都在 +DOM 里(`.gamepane` 切 `active`),删号后四份列表一起重画。 + +**bilibili 服要粉**:MAA 路径页里渠道名按 `.acct-ch.bili` 上粉色(`#ff9dd1`), +和账号卡上的徽标同一个颜色;正文里的「bilibili服」用 `.bili-word` 点出来—— +B 服的切号名规则跟官服不一样,填错 MAA 会死找账号。 + +**配置文件 → 切号名(2026-11-22)**:账号卡第二行是「配置文件 + 切号名」两栏 +(`.set-maarow-two`,窄屏折成一列)。配置文件下拉的选项来自 +`/api/maa/profiles`(列表项带上各自档案里记的账号名,形如 `moren · 181****5505`), +换目录或点「检测」会清缓存重拉(`pfCache`)。选了档案就把 StartUp 里的 +`AccountName` 填进切号名输入框、来源标 `profile`;用户一动手输入就标 `manual`。 +打开设置页时 `autoFillMaa()` 只填空着的切号名,**不替用户选档案**—— +两个游戏账号对五份档案,猜错就是切号死循环 4 分钟,宁可只提示一句 +「MAA 当前档案里记着 xxx,在下拉里选它就能带出来」。 + **为什么不再有跨页的大「保存」**:改了 MAA 又切到版本页,很容易把前一次的 保存漏掉;每页自己的动作收自己的尾,页脚直接写「改动即时生效」。 diff --git a/docs/tools-smoketest.md b/docs/tools-smoketest.md index ce476cd..1cbcb4a 100644 --- a/docs/tools-smoketest.md +++ b/docs/tools-smoketest.md @@ -83,11 +83,13 @@ mock 掉,验证闸门口径—— 中文;裸名与带 `@` 前缀的都要能命中;`BattleQuickFormationRole-*` 统一归「编队·按职业筛选」;插件类名节点静默。这条专门防「照源码猜 pipeline 名、跟真实日志对不上、战斗一整段没日志」的回归 -- **切号名唯一来源 = 账号绑定**(2026-11-18 晚定版):`maa.accountName` 读得 - 到就返回;没绑定给空串,且把 `maa._load_cfg` mock 成「一调用就炸」—— - **全程不许读用户的 MAA 配置档案**(agent 模式跑临时配置=StartUp 任务参数, - 不碰用户的 gui.new.json)。**绝不用昵称顶**(官服切号认手机号)。防「读错 - 字段切号名永远空、唤醒 2 秒完成、号没切」和「从档案猜尾号猜错号」两类回归 +- **切号名来源**(2026-11-22 改):没绑配置文件时 `maa.accountName` 读到就返回、 + 没有给空串,并把 `maa._load_cfg` mock 成「一调用就炸」——**这种情况全程不许 + 读用户的 MAA 配置档案**;绑了配置文件(用户点名的那份)才读它 StartUp 的 + `AccountName`,此时把 `maa._save_cfg` mock 成「一调用就炸」——**只读不写**。 + `accountNameFrom=manual` 的值优先,档案里的旧号码不许盖回去。**绝不用昵称 + 顶**(官服切号认手机号)。防「读错字段切号名永远空、唤醒 2 秒完成、号没切」 + 和「手改的值被档案覆盖」两类回归 - **StartUp 直连参数口径**:MaaCore 的 `StartUpTask::set_params` 只认 `account_name` / `client_type` / `start_game_enabled` 三个键(给了非空 `account_name` 就切号),`core_tasks` 不得发 `account_switch_enabled` 这类 @@ -213,6 +215,24 @@ MaaCore 拿到 `is_raid=true` 会自己点 `ChangeToRaidDifficulty` 切难度, - **卡教程**:`run_custom` 返回 `stuck` 时,`skill_tool` 的结果里要带 `hint` 并在日志里出现「教程」二字(用户口径:告诉他手动过一遍再挂) +### B50 切号名绑定(2026-11-22) + +设置里每个账号多了「配置文件 + 切号名」两栏,助手也多了 `set_account_name`。 +这块错一个字的代价是 MAA 在账号列表里死找 4 分钟,所以全部打桩钉死: + +- 归一:`5505` 原样、`1573635` / `157 3635` / `157****3635` 都出 `157****3635` +- `set_account_name`:给昵称能认到文件、写进 `maa.accountName` 且标 + `accountNameFrom=manual`;官服填昵称要报错;两个账号又没点名时返回 + `need_info=account`(让模型先问用户,别乱写) +- 配置文件优先:造一份 `gui.new.json`(`moren` 的 StartUp 写 `181****5505`), + 账号绑上它 → `acctbind.resolve` 出 `('181****5505','profile')`; + `_tool_list_accounts` 和 `multiacct.candidates` 里也必须是这个生效值 + (否则模型看到空值又去问一遍) +- 手填优先:同一账号改成 `accountNameFrom=manual` + `5505` → 出 `5505` +- 读不到档案(目录被删/档案没建)→ 回落手填值,不抛 +- 只读不写:`maa._save_cfg` mock 成「一调用就炸」,解析全程不许写用户的 + `gui.new.json` + ## 什么时候跑 - 改了 `vault.py` / `accounts.py` / `settings.py` / `main.py` 之后 diff --git a/frontend/app.js b/frontend/app.js index 44130a4..6f29009 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -197,6 +197,8 @@ async function boot() { const mod0 = new URLSearchParams(location.search).get('mod'); if (mod0 === 'gacha' || mod0 === 'signin' || mod0 === 'chat') setModule(mod0); startPing(); + setTimeout(scheduleWatch, 7000); + setInterval(scheduleWatch, 20000); // 资源包后台自动更新:晚几秒,别和首屏渲染抢网络 setTimeout(packAutoSync, 2500); // 程序本体检查更晚一点:两条链路错开,别同时占网络 @@ -226,6 +228,19 @@ function startPing() { setInterval(ping, 20000); } +/* 定时任务跑完的提示:设置页关着也能收到(后端线程照跑)。 */ +let _schedSeq = 0; +async function scheduleWatch() { + try { + const d = await api('/api/schedule/status?since=' + _schedSeq); + if (typeof d.seq === 'number') _schedSeq = d.seq; + (d.events || []).forEach(ev => { + if (ev.kind !== 'finish' || !ev.notify) return; + toast(ev.text || `定时任务「${ev.name}」已结束`, ev.level === 'ok' ? 'ok' : 'err', 6000); + }); + } catch (e) { /* 老服务端没有这个接口:安静跳过 */ } +} + /* ------------------------------------------------------------ 账号 */ /* 侧栏顶部两个分组标签(明日方舟 / 终末地):数量实时跟着 S.accounts 走。 某一组没有账号时标签照样在(点了给空态提示),不然会让人以为账号丢了。 */ @@ -2592,6 +2607,17 @@ async function pickFolder(inputEl) { else if (r && r.error) toast('选择失败:' + r.error, 'err'); } +async function pickFile(inputEl) { + const n = nativeApi(); + if (!n || !n.choose_file) { + toast('当前不是桌面窗口,请手动粘贴程序路径', 'err'); + return; + } + const r = await n.choose_file('选择要运行的程序', inputEl.value.trim()); + if (r && r.path) inputEl.value = r.path; + else if (r && r.error) toast('选择失败:' + r.error, 'err'); +} + /* ------------------------------------------------------------ 设置 2026-11-18:一列到底改成「左侧 tab + 右侧内容」。 原来账号 / MAA / 版本 / 助手 / 目录 / 黑名单全堆在一个 520px 的弹窗里, @@ -2611,6 +2637,7 @@ const SET_ICONS = { + '' + '', blacklist: '', + schedule: '', }; function setIcon(k) { @@ -2626,12 +2653,15 @@ function fmtSync(t) { const SET_TABS = [ ['accounts', '账号管理'], ['maa', 'MAA 路径'], + ['schedule', '定时任务'], ['update', '版本更新'], ['agent', '助手设置'], ['data', '数据与日志'], ['blacklist', '黑名单'], ]; +let _setSchedTimer = null; // 设置 → 定时任务页的 5 秒轮询 + function openSettings() { const s = S.settings; const p = S.paths || {}; @@ -2648,7 +2678,7 @@ function openSettings() { const proxyHost = pm ? pm[1] : 'http://127.0.0.1'; const proxyPort = pm ? pm[2] : ''; - const acctRows = () => (S.accounts || []).map(a => { + const acctRows = game => (S.accounts || []).filter(a => gameOf(a) === game).map(a => { const st = a.stats || {}; const ef = (a.game || 'arknights') === 'endfield'; const ch = (a.nickName || '?').replace(/[##].*$/, '').slice(0, 1); @@ -2683,30 +2713,60 @@ function openSettings() {
`; - }).join('') || '
还没有账号。用左上角「添加账号」粘一个森空岛 token,或直接从 MAA 导入。
'; - - const maaRows = () => (S.accounts || []).map(a => ` -
+ }).join('') || `
${ + game === 'endfield' + ? '这一栏还没有终末地账号。用森空岛 token 同步时,token 绑了终末地角色就会自动出现在这里。' + : '还没有账号。用左上角「添加账号」粘一个森空岛 token,或直接从 MAA 导入。'}
`; + + // 每个账号的 MAA 绑定:第一行路径,第二行「配置文件 + 切号名」 + // 配置文件 = MAA 的 Configuration(Default / 136 / 157 / moren 那些)。 + // 选了它,切号名就从档案里「开始唤醒」的 AccountName 带出来;用户还能 + // 手改(改过就以他填的为准)。**我们只读档案,不写回 MAA**。 + const maaRows = game => (S.accounts || []).filter(a => gameOf(a) === game).map(a => ` +
${esc(a.nickName)} - ${esc(a.channelName || '官服')} - ${a.maaProfile ? `档案 ${esc(a.maaProfile)}` : ''} + ${ + esc(a.channelName || '官服')} + ${a.maaProfile ? `配置文件 ${esc(a.maaProfile)}` : ''}
- + ${game === 'endfield' ? ` + ` : ` +
+ + +
`}
-
`).join('') || '
还没有账号。
'; +
`).join('') || `
${ + game === 'endfield' ? '这一栏还没有终末地账号。' : '还没有账号。'}
`; + + // 设置里的游戏分组:两页共用同一份选择,切一页另一页跟着切。数量由 + // paintSetGame 在挂载后回填(删号后也要跟着变),模板里先留 0。 + const gameTabs = () => ` +
+ + +
`; // 条数要读活的 S.settings:子弹窗里增删后 saveSettings 会换掉整个对象, // 拿打开设置那一刻的引用(s)去数会一直停在旧值 @@ -2743,33 +2803,106 @@ function openSettings() { (Windows DPAPI,仅本机当前用户可解),不会上传。默认只读,只有「验证」确认失效后才解锁修改。 删除账号会连练度快照一起删掉,不可恢复。

-
${acctRows()}
+ ${gameTabs()} +
+
${acctRows('arknights')}
+
+
+
${acctRows('endfield')}
+

MAA 路径

每个账号可以绑自己的 MAA(包含 MAA.exe 的目录),没绑就用下面的默认目录。 - 切号名是 MAA「开始唤醒 → 账号切换」里要比对的那行:官服填手机号后 4 位(如 5505), - B 服填游戏内用户名。填错的代价是 MAA 在账号列表里死找、4 分钟超时后整轮挂机作废。

+ 第二行选一个 配置文件(MAA 里那份档案,如 Default / moren), + 程序会从它的「开始唤醒」里读出切号名——官服是手机号(后 4 位 + 5505,或前 3 位 + 后 4 位 157****3635, + bilibili服是游戏内用户名),读出来还能手改。 + 只读不写:MAA 里那份档案我们一个字段都不动。填错的代价是 MAA + 在账号列表里死找、4 分钟超时后整轮挂机作废。

-
- -
${ - S.maa && S.maa.exeExists ? '✓ MAA.exe 已找到' : '✗ 尚未检测到 MAA.exe'}
- + ${gameTabs()} +
+
+ +
${ + S.maa && S.maa.exeExists ? '✓ MAA.exe 已找到' : '✗ 尚未检测到 MAA.exe'}
+ +
+
各账号的绑定
+
${maaRows('arknights')}
+
+
+
+ +
${s.maaEndDir + ? '已填写,MAAEND 任务链接入后生效' + : '还没填。这一栏先留着位,等 MAAEND 接入后启用'}
+
终末地走的是另一套程序(MAAEND), + 目录格式与 MAA 不同;现在能保存路径、能识别主程序,任务下发要等后续版本接入。
+
+
各账号的绑定
+
${maaRows('endfield')}
-
各账号的绑定
-
${maaRows()}
+
+ +
+
+

定时任务

+

到点自动启动一个程序:exe、bat、cmd 批处理都行,参数照程序自己 + 的说明填。常见用法是定时跑挂机脚本、到点打开模拟器或别的工具;多条任务 + 还能链式启动——上一个程序退出后接着跑下一个。定时只在程序运行时 + 生效,要开机自启请把本程序放进系统启动项;「通知」是在程序里弹提示, + 程序关着就收不到。

+
+
+
+ #启用名称执行计划 + 程序参数通知 +
+
+
+
+ + + + + + + +
+
+ + + + +
+
@@ -2907,20 +3040,59 @@ function openSettings() {
`, { cls: 'modal-set', + onClose() { + if (_setSchedTimer) { clearInterval(_setSchedTimer); _setSchedTimer = null; } + }, onMount(el, close) { /* ---------------- 页签 ---------------- */ const panes = $$('.set-pane', el); const tabs = $$('.set-tab', el); + let curTab = 'accounts'; + let setGame = 'arknights'; // 账号管理 / MAA 路径两页共用同一份选择 + + const fillVisibleTokens = () => { + $$('.set-acct', el).forEach(card => { + const pane = card.closest('.gamepane'); + if (!card.dataset.loaded && pane && pane.classList.contains('active')) fillToken(card); + }); + }; + + const paintSetGame = g => { + if (g !== 'arknights' && g !== 'endfield') return; + setGame = g; + $$('.set-gswitch .gswitch', el).forEach(b => { + const on = b.dataset.game === g; + b.classList.toggle('active', on); + b.setAttribute('aria-selected', on ? 'true' : 'false'); + const c = $('[data-gcount="' + b.dataset.game + '"]', b); + if (c) c.textContent = (S.accounts || []).filter(a => gameOf(a) === b.dataset.game).length; + }); + $$('.gamepane', el).forEach(p2 => { + p2.classList.toggle('active', p2.dataset.gamepane === g); + }); + if (curTab === 'accounts') fillVisibleTokens(); + }; + const show = id => { + curTab = id; tabs.forEach(t => t.classList.toggle('active', t.dataset.tab === id)); panes.forEach(p2 => p2.classList.toggle('active', p2.dataset.pane === id)); - if (id === 'accounts') { - $$('.set-acct', el).forEach(card => { if (!card.dataset.loaded) fillToken(card); }); + if (id === 'accounts') fillVisibleTokens(); + if (id === 'maa') autoFillMaa(); + if (id === 'schedule') { + schedLoad(); + if (!_setSchedTimer) _setSchedTimer = setInterval(() => schedLoad(true), 5000); + } else if (_setSchedTimer) { + clearInterval(_setSchedTimer); + _setSchedTimer = null; } - if (id === 'maa') suggestNames(); if (id === 'blacklist') paintBlCounts(); }; tabs.forEach(t => t.addEventListener('click', () => show(t.dataset.tab))); + el.addEventListener('click', ev => { + const b = ev.target.closest('.set-gswitch .gswitch'); + if (b) paintSetGame(b.dataset.game); + }); // 页签上的小数字:账号数、黑名单总条数——不点进去也知道有没有东西 const paintTabN = () => { @@ -3030,7 +3202,7 @@ function openSettings() { fillToken(card); } - $('#set-acct-list', el).addEventListener('click', async ev => { + const onAcctClick = async ev => { const card = ev.target.closest('.set-acct'); const btn = ev.target.closest('[data-act]'); if (!card || !btn) return; @@ -3094,52 +3266,142 @@ function openSettings() { } if (act === 'del') { deleteAccount(file, () => { - $('#set-acct-list', el).innerHTML = acctRows(); - $$('.set-acct', el).forEach(c => fillToken(c)); - // MAA 那页用的是另一份列表,删号后也得跟着少一行 - $('#set-maa-list', el).innerHTML = maaRows(); + // 删号后四份列表都得重画:账号两栏 + MAA 两栏 + $('#set-acct-list', el).innerHTML = acctRows('arknights'); + $('#set-acct-list-ef', el).innerHTML = acctRows('endfield'); + $('#set-maa-list', el).innerHTML = maaRows('arknights'); + $('#set-maa-end-list', el).innerHTML = maaRows('endfield'); + paintSetGame(setGame); paintBlCounts(); paintTabN(); }); } + }; + ['set-acct-list', 'set-acct-list-ef'].forEach(id => { + const box = $('#' + id, el); + if (box) box.addEventListener('click', onAcctClick); }); - /* ---------------- MAA 路径 ---------------- */ - $('#set-probe', el).addEventListener('click', async () => { - const box = $('#set-maa-state', el); - const dir = $('#set-maa', el).value.trim(); - if (!dir) { box.className = 'onb-hint bad'; box.textContent = '先填目录'; return; } - try { - const r = await api('/api/maa/probe?dir=' + encodeURIComponent(dir)); - box.className = 'onb-hint ' + (r.exeExists && r.configExists ? 'ok' : 'bad'); - box.textContent = r.exeExists - ? (r.configExists ? `✓ 找到 MAA.exe,配置 ${r.profiles.length} 个` : '✗ 缺 config/gui.new.json') - : '✗ 这个目录里没有 MAA.exe'; - } catch (e2) { - box.className = 'onb-hint bad'; - box.textContent = '检测失败:' + e2.message; - } - }); - $('#set-maa-save', el).addEventListener('click', async () => { - const dir = $('#set-maa', el).value.trim(); - const btn = $('#set-maa-save', el); - btn.disabled = true; - try { - const d = await saveSettings({ maaDir: dir }); - S.settings = d.settings || S.settings; - renderMaaState(); - fillBasketProfiles(); - toast('默认 MAA 目录已保存'); - } catch (e2) { - toast('保存失败:' + e2.message, 'err'); - } finally { btn.disabled = false; } - }); + /* ---------------- MAA 路径 ---------------- + 明日方舟用 MAA,终末地以后用 MAAEND:两套目录各存各的键 + (maaDir / maaEndDir),切 tab 不会互相覆盖。 */ + const bindMaaDefault = (prefix, key, kind) => { + const input = $('#' + prefix, el); + const prober = $('#' + prefix + '-probe', el); + const saver = $('#' + prefix + '-save', el); + const box = $('#' + prefix + '-state', el); + if (!input || !prober || !saver || !box) return; + prober.addEventListener('click', async () => { + const dir = input.value.trim(); + if (!dir) { box.className = 'onb-hint bad'; box.textContent = '先填目录'; return; } + try { + const r = await api('/api/maa/probe?dir=' + encodeURIComponent(dir) + + '&kind=' + encodeURIComponent(kind)); + if (!r.exeExists) { + box.className = 'onb-hint bad'; + box.textContent = kind === 'endfield' + ? '✗ 这个目录里没有 MAAEND 的主程序(MaaEnd.exe / mxu.exe)' + : '✗ 这个目录里没有 MAA.exe'; + return; + } + if (kind === 'endfield') { + box.className = 'onb-hint ok'; + box.textContent = `✓ 找到 ${r.exeName || '主程序'}(任务链接入后生效)`; + return; + } + box.className = 'onb-hint ' + (r.configExists ? 'ok' : 'bad'); + box.textContent = r.configExists + ? `✓ 找到 MAA.exe,配置 ${r.profiles.length} 个` : '✗ 缺 config/gui.new.json'; + } catch (e2) { + box.className = 'onb-hint bad'; + box.textContent = '检测失败:' + e2.message; + } + }); + saver.addEventListener('click', async () => { + const dir = input.value.trim(); + saver.disabled = true; + try { + const d = await saveSettings({ [key]: dir }); + S.settings = d.settings || S.settings; + if (key === 'maaDir') { renderMaaState(); fillBasketProfiles(); } + if (dir) { + box.className = 'onb-hint ok'; + box.textContent = kind === 'endfield' + ? '✓ 已保存,MAAEND 任务链接入后生效' : '✓ 已保存'; + } + toast(kind === 'endfield' ? '默认 MAAEND 目录已保存' : '默认 MAA 目录已保存'); + } catch (e2) { + toast('保存失败:' + e2.message, 'err'); + } finally { saver.disabled = false; } + }); + }; + bindMaaDefault('set-maa', 'maaDir', 'arknights'); + bindMaaDefault('set-maa-end', 'maaEndDir', 'endfield'); $('#set-autostart', el).addEventListener('change', async ev => { try { await saveSettings({ autoStartMaa: ev.target.checked }); } catch (e2) { ev.target.checked = !ev.target.checked; toast('保存失败:' + e2.message, 'err'); } }); - $('#set-maa-list', el).addEventListener('click', async ev => { + /* ---------------- 每个账号的 MAA 绑定:配置文件 → 切号名 ---------------- + 用户 2026-11-22 的要求:MAA 路径第一行,配置文件 + 切号名第二行。 + 选了配置文件就从那份档案的「开始唤醒」里读 AccountName 带出来;手改过 + 就以他填的为准(accountNameFrom=manual)。MAA 的档案**只读不写**。 */ + const pfCache = new Map(); // 目录(或账号)→ {profiles, current} + + async function loadPfRows(card, force) { + const dirEl = $('[data-f="dir"]', card); + const dir = dirEl ? dirEl.value.trim() : ''; + const key = (dir || card.dataset.file).toLowerCase(); + if (!force && pfCache.has(key)) return pfCache.get(key); + const q = dir ? ('maaDir=' + encodeURIComponent(dir)) + : ('file=' + encodeURIComponent(card.dataset.file)); + let d = { profiles: [], current: '' }; + try { d = await api('/api/maa/profiles?' + q); } + catch (e2) { d = { profiles: [], current: '' }; } + pfCache.set(key, d); + return d; + } + + async function paintPfSelect(card, force) { + const sel = $('[data-f="profile"]', card); + if (!sel) return null; + const cur = sel.value || sel.dataset.pf || ''; + const d = await loadPfRows(card, force); + const rows = d.profiles || []; + const one = (v, label) => + ``; + let html = one('', '(不指定)'); + html += rows.map(p2 => one(p2.name, + p2.accountName ? `${p2.name} · ${p2.accountName}` : p2.name)).join(''); + // 档案被删/换目录时,原来选着的那个还得留在选项里,不然一刷新就丢值 + if (cur && !rows.some(p2 => p2.name === cur)) html += one(cur, cur + '(MAA 里没找到)'); + sel.innerHTML = html; + sel.dataset.count = String(rows.length); + return d; + } + + /* 按选中的配置文件把切号名带出来(用户手选时用) */ + async function usePfName(card) { + const sel = $('[data-f="profile"]', card); + const input = $('[data-f="accountName"]', card); + const state = $('[data-state]', card); + const name = sel ? sel.value : ''; + if (!name) { card.dataset.from = ''; return; } + const d = await loadPfRows(card); + const hit = (d.profiles || []).find(p2 => p2.name === name); + const an = hit ? (hit.accountName || '') : ''; + if (an) { + input.value = an; + card.dataset.from = 'profile'; + state.className = 'onb-hint'; + state.textContent = `已从配置文件「${name}」带出切号名 ${an},点保存生效`; + } else { + state.className = 'onb-hint'; + state.textContent = `配置文件「${name}」里没记账号名,切号名请自己填`; + } + } + + const onMaaRowClick = async ev => { const card = ev.target.closest('.set-maarow'); const btn = ev.target.closest('[data-act]'); if (!card || !btn) return; @@ -3147,39 +3409,35 @@ function openSettings() { const input = $('[data-f="dir"]', card); const nameInput = $('[data-f="accountName"]', card); const state = $('[data-state]', card); + const isEnd = card.dataset.game === 'endfield'; if (btn.dataset.act === 'pick') { await pickFolder(input); return; } - if (btn.dataset.act === 'probe' || btn.dataset.act === 'profiles') { - const dir = input.value.trim() || (S.settings.maaDir || ''); + if (btn.dataset.act === 'probe') { + const dir = input.value.trim() + || ((isEnd ? S.settings.maaEndDir : S.settings.maaDir) || ''); if (!dir) { state.className = 'onb-hint bad'; state.textContent = '先填目录(或设置默认目录)'; return; } state.className = 'onb-hint'; state.textContent = '检测中…'; try { - const r = await api('/api/maa/probe?dir=' + encodeURIComponent(dir)); + const kind = isEnd ? 'endfield' : 'arknights'; + const r = await api('/api/maa/probe?dir=' + encodeURIComponent(dir) + + '&kind=' + encodeURIComponent(kind)); if (!r.exeExists) { state.className = 'onb-hint bad'; - state.textContent = '✗ 这个目录里没有 MAA.exe'; + state.textContent = kind === 'endfield' + ? '✗ 这个目录里没有 MAAEND 的主程序(MaaEnd.exe / mxu.exe)' + : '✗ 这个目录里没有 MAA.exe'; return; } state.className = 'onb-hint ok'; - state.textContent = `✓ MAA.exe 在,配置 ${r.profiles.length} 个`; - if (btn.dataset.act === 'profiles') { - const pf = await api('/api/maa/profiles?file=' + encodeURIComponent(file)); - const rows = pf.profiles || []; - const acc = (S.accounts || []).find(x => x.file === file) || {}; - const hit = rows.find(x => x.name === acc.maaProfile) - || rows.find(x => x.name === pf.current) - || (rows.length === 1 ? rows[0] : null); - if (hit && hit.accountName) { - nameInput.value = hit.accountName; - state.textContent = `✓ 从档案「${hit.name}」读到切号名 ${hit.accountName},点保存生效`; - } else if (rows.length) { - toast('MAA 里有这些档案:' + rows.map(x => `${x.name}(${x.accountName || '空'})`).join('、') - + ',没敢替你猜,手动填一下切号名', 'warn', 7000); - state.textContent = '✓ 读到 ' + rows.length + ' 个档案,切号名请手动确认'; - } else { - state.className = 'onb-hint bad'; - state.textContent = '这个 MAA 里还没有配置档案'; - } + if (isEnd) { + state.textContent = `✓ 找到 ${r.exeName || '主程序'}(任务链接入后生效)`; + } else { + // 顺手把配置文件下拉刷一遍:用户刚换了目录,列表得跟着变 + pfCache.clear(); + await paintPfSelect(card, true); + const sel = $('[data-f="profile"]', card); + const n = (sel && sel.dataset.count) || r.profiles.length || 0; + state.textContent = `✓ MAA.exe 在,配置文件 ${n} 个`; } } catch (e2) { state.className = 'onb-hint bad'; @@ -3191,12 +3449,21 @@ function openSettings() { btn.disabled = true; btn.textContent = '保存中…'; try { - const patch = { dir: input.value.trim(), accountName: nameInput.value.trim() }; + const patch = { dir: input.value.trim(), + accountName: nameInput.value.trim() }; + const sel = $('[data-f="profile"]', card); + if (sel) { + patch.profile = sel.value; + patch.accountNameFrom = card.dataset.from === 'manual' ? 'manual' + : (sel.value ? 'profile' : ''); + } const r = await api('/api/account/maa', { file, patch }); const row = (S.accounts || []).find(x => x.file === file); if (row) { row.maaDir = (r.maa || {}).dir || ''; + row.maaProfile = (r.maa || {}).profile || ''; row.maaAccountName = (r.maa || {}).accountName || ''; + row.maaAccountNameFrom = (r.maa || {}).accountNameFrom || ''; } state.className = 'onb-hint ok'; state.textContent = '✓ 已保存'; @@ -3210,32 +3477,346 @@ function openSettings() { btn.textContent = '保存'; } } + }; + // 下拉/目录改值走 change,切号名手打走 input(两者都要冒到列表容器上) + const onMaaRowChange = async ev => { + const card = ev.target.closest('.set-maarow'); + if (!card) return; + if (ev.target.matches('[data-f="profile"]')) { await usePfName(card); return; } + if (ev.target.matches('[data-f="dir"]')) { + pfCache.clear(); + if ($('[data-f="profile"]', card)) await paintPfSelect(card, true); + } + }; + const onMaaRowType = ev => { + const card = ev.target.closest('.set-maarow'); + if (!card || !ev.target.matches('[data-f="accountName"]')) return; + // 手改过就打上 manual:下次不会被配置档案里的旧号码盖回去 + card.dataset.from = ev.target.value.trim() ? 'manual' : ''; + }; + ['set-maa-list', 'set-maa-end-list'].forEach(id => { + const box = $('#' + id, el); + if (!box) return; + box.addEventListener('click', onMaaRowClick); + box.addEventListener('change', onMaaRowChange); + box.addEventListener('input', onMaaRowType); }); - /* ---------------- MAA 绑定:没填切号名时给个提示 ---------------- - 切号名是唯一「必须问用户」的字段,猜错的代价又特别大(MAA 在账号 - 列表里死找、4 分钟超时)。所以不做自动填写,只在 MAA 档案里恰好 - 记着的时候提一句,让用户自己点「读档案」确认。 */ - async function suggestNames() { + /* ---------------- 打开设置时:把配置文件列表读出来 ---------------- + 绑了档案的账号,切号名直接从档案里填上(只改输入框,点保存才落盘); + 没绑的只在档案恰好有账号名时提示一句——**不替用户猜**:两个游戏账号 + 对 MAA 里五份档案,猜错就是切号死循环 4 分钟。 */ + async function autoFillMaa() { for (const card of $$('.set-maarow', el)) { - if (card.dataset.sug || $('[data-state]', card).textContent) continue; - if ($('[data-f="accountName"]', card).value.trim()) continue; - card.dataset.sug = '1'; - try { - const pf = await api('/api/maa/profiles?file=' + encodeURIComponent(card.dataset.file)); - const rows = pf.profiles || []; - const acc = (S.accounts || []).find(x => x.file === card.dataset.file) || {}; - const hit = rows.find(x => x.name === acc.maaProfile) - || rows.find(x => x.name === pf.current); - if (hit && hit.accountName) { - const st = $('[data-state]', card); - st.className = 'onb-hint'; - st.textContent = `MAA 档案「${hit.name}」里记着切号名 ${hit.accountName},点「读档案」填入`; - } - } catch (e2) { /* 没装 MAA / 配置读不到:不打扰 */ } + if (card.dataset.game === 'endfield') continue; // MAAEND 档案格式不同 + if (card.dataset.pfTried) continue; + card.dataset.pfTried = '1'; + const d = await paintPfSelect(card); + const sel = $('[data-f="profile"]', card); + const input = $('[data-f="accountName"]', card); + const state = $('[data-state]', card); + if (!sel || !input) continue; + if (sel.value) { + if (!input.value.trim()) await usePfName(card); + else if (!state.textContent) state.textContent = `已绑定配置文件「${sel.value}」`; + continue; + } + const cur = d && d.current; + const hit = cur ? (d.profiles || []).find(p2 => p2.name === cur) : null; + if (hit && hit.accountName && !input.value.trim()) { + state.className = 'onb-hint'; + state.textContent = `MAA 当前档案「${hit.name}」里记着切号名 ${hit.accountName},` + + '在上面的下拉里选它就能带出来'; + } } } + /* ---------------- 定时任务 ---------------- + 参照三月七助手那套:时间触发 / 链式启动、冲突策略、链式失败策略。 + 数据在后端 config/schedule.json,这里只负责展示与增删改;真正拉起 + 程序的线程在后端,所以关掉设置页也照跑。 */ + const WD = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']; + const schedOf = () => S.schedule || { tasks: [], conflict: 'stop', onChainFail: 'continue' }; + const baseName = p => { + const t = String(p || '').replace(/[\\/]+$/, ''); + return t.split(/[\\/]/).pop() || t; + }; + const weekText = wd => { + const a = (wd || []).slice().sort((x, y) => x - y); + if (a.length === 7) return '每天'; + if (!a.length) return '未选择'; + return a.map(n => WD[n - 1] || n).join('、'); + }; + const takeText = sec => { + const n = Math.max(0, parseInt(sec, 10) || 0); + return n >= 60 ? `${Math.floor(n / 60)} 分 ${n % 60} 秒` : `${n} 秒`; + }; + let schedSel = -1; + + const paintSched = () => { + const d = schedOf(); + const rows = d.tasks || []; + const box = $('#sched-rows', el); + if (!box) return; + if (schedSel >= rows.length) schedSel = rows.length - 1; + box.innerHTML = rows.length ? rows.map((t, i) => { + const plan = t.mode === 'chain' + ? '链式启动' + : `${esc(t.time || '')} ${esc(weekText(t.weekdays))}`; + const live = d.running && d.running.id === t.id; + return `
+ ${i + 1} + + ${t.mode === 'chain' ? '→ ' : ''}${ + esc(t.name)}${live ? '运行中' : ''} + ${plan} + ${ + t.program ? esc(baseName(t.program)) : '未设置'} + ${esc(t.args || '—')} + ${t.notify ? '是' : '否'} +
`; + }).join('') + : '
还没有定时任务。点「添加」建一条——到点启动一个程序,或者接在上一条后面链式启动。
'; + + const cSel = $('#sched-conflict', el); + const fSel = $('#sched-onfail', el); + if (cSel) cSel.value = d.conflict || 'stop'; + if (fSel) fSel.value = d.onChainFail || 'continue'; + + const st = $('#sched-state', el); + if (st) { + if (d.running) { + st.textContent = `正在运行:${d.running.name}(${takeText(d.running.seconds)})`; + } else { + const next = rows.filter(t => t.enabled && t.mode === 'time' && t.nextRunTs) + .sort((a, b) => a.nextRunTs - b.nextRunTs)[0]; + st.textContent = next ? `下次:${next.nextRun} · ${next.name}` : '当前没有待执行的任务'; + } + } + + const log = $('#sched-log', el); + if (log) { + const near = log.scrollHeight - log.scrollTop - log.clientHeight < 24; + const lines = (d.log || []).slice(-40); + log.innerHTML = lines.length ? lines.map(ev => + `
${esc(ev.time || '')}${ + esc(ev.text || '')}
`).join('') + : '
还没有运行记录。
'; + if (near) log.scrollTop = log.scrollHeight; + } + }; + + async function schedLoad(quiet) { + try { + const d = await api('/api/schedule/status'); + S.schedule = d; + _schedSeq = d.seq || _schedSeq; // 设置里看过的,全局轮询不再弹一遍 + paintSched(); + } catch (e2) { + if (quiet) return; + const log = $('#sched-log', el); + if (log) log.textContent = '读取失败:' + e2.message; + } + } + + async function schedSave(patch) { + const d = schedOf(); + const body = Object.assign({ + tasks: d.tasks || [], conflict: d.conflict, onChainFail: d.onChainFail, + }, patch || {}); + await api('/api/schedule/save', body); + await schedLoad(true); + } + + const schedPick = () => { + const rows = schedOf().tasks || []; + if (schedSel < 0 || !rows[schedSel]) { toast('先在列表里点一条任务', 'warn'); return null; } + return schedSel; + }; + + function openSchedTask(task, idx) { + const isNew = !task; + const t = Object.assign({ + name: '', enabled: true, mode: 'time', time: '08:00', + weekdays: [1, 2, 3, 4, 5, 6, 7], program: '', args: '', cwd: '', + timeout: 0, notify: true, + }, task || {}); + const picked = new Set((t.weekdays || []).map(Number)); + const m = modal(` +

${isNew ? '添加定时任务' : '编辑定时任务'}

+
程序退出视为本次结束;退出码非 0 算失败。「链式启动」接在上一条后面, + 上一条跑完(或按「链式失败后」的策略)才轮到它。
+ + + +
+ +
星期 +
${WD.map((n, i) => ` + `).join('')}
+
+ + + +
+ + +
+
+ + `, { + onMount(box, close) { + const state = $('#st-state', box); + const modeSel = $('#st-mode', box); + const timeBox = $('#st-time-box', box); + const syncMode = () => { timeBox.style.display = modeSel.value === 'chain' ? 'none' : ''; }; + modeSel.addEventListener('change', syncMode); + syncMode(); + $('#st-weekdays', box).addEventListener('click', ev2 => { + const b = ev2.target.closest('.wd-btn'); + if (!b) return; + const n = Number(b.dataset.wd); + if (picked.has(n)) picked.delete(n); else picked.add(n); + b.classList.toggle('on', picked.has(n)); + }); + $('#st-pick', box).addEventListener('click', () => pickFile($('#st-program', box))); + $('#st-pick-dir', box).addEventListener('click', () => pickFolder($('#st-cwd', box))); + $('#st-save', box).addEventListener('click', async () => { + const name = $('#st-name', box).value.trim(); + const mode = modeSel.value === 'chain' ? 'chain' : 'time'; + const time = $('#st-time', box).value.trim(); + const program = $('#st-program', box).value.trim(); + const args = $('#st-args', box).value.trim(); + const cwd = $('#st-cwd', box).value.trim(); + const timeout = Math.max(0, parseInt($('#st-timeout', box).value, 10) || 0); + if (!name) { state.className = 'onb-hint bad'; state.textContent = '先起个名字'; return; } + if (!program) { state.className = 'onb-hint bad'; state.textContent = '先选要运行的程序'; return; } + if (mode === 'time' && !/^\d{1,2}:\d{2}$/.test(time)) { + state.className = 'onb-hint bad'; state.textContent = '时间写成 HH:MM,例如 08:00'; return; + } + if (mode === 'time' && !picked.size) { + state.className = 'onb-hint bad'; state.textContent = '至少选一天'; return; + } + const item = { + id: t.id || '', enabled: $('#st-enabled', box).checked, name, mode, time, + weekdays: [...picked].sort((a, b) => a - b), program, args, cwd, timeout, + notify: $('#st-notify', box).checked, + }; + const tasks = (schedOf().tasks || []).slice(); + if (isNew) tasks.push(item); else tasks[idx] = item; + const btn = $('#st-save', box); + btn.disabled = true; + btn.textContent = '保存中…'; + try { + await schedSave({ tasks }); + close(); + toast(isNew ? '已添加定时任务' : '已保存'); + } catch (e2) { + state.className = 'onb-hint bad'; + state.textContent = '保存失败:' + e2.message; + btn.disabled = false; + btn.textContent = '保存'; + } + }); + }, + }); + return m; + } + + $('#sched-add', el).addEventListener('click', () => openSchedTask(null, -1)); + $('#sched-edit', el).addEventListener('click', () => { + const i = schedPick(); + if (i === null) return; + openSchedTask((schedOf().tasks || [])[i], i); + }); + $('#sched-del', el).addEventListener('click', () => { + const i = schedPick(); + if (i === null) return; + const rows = (schedOf().tasks || []).slice(); + const gone = rows[i]; + rows.splice(i, 1); + schedSel = Math.min(i, rows.length - 1); + schedSave({ tasks: rows }).then(() => toast('已删除「' + (gone.name || '任务') + '」')) + .catch(e2 => toast('删除失败:' + e2.message, 'err')); + }); + const schedMove = step => () => { + const i = schedPick(); + if (i === null) return; + const j = i + step; + const rows = (schedOf().tasks || []).slice(); + if (j < 0 || j >= rows.length) return; + const tmp = rows[i]; rows[i] = rows[j]; rows[j] = tmp; + schedSel = j; + schedSave({ tasks: rows }).catch(e2 => toast('移动失败:' + e2.message, 'err')); + }; + $('#sched-up', el).addEventListener('click', schedMove(-1)); + $('#sched-down', el).addEventListener('click', schedMove(1)); + $('#sched-run', el).addEventListener('click', async () => { + const i = schedPick(); + if (i === null) return; + const t = (schedOf().tasks || [])[i]; + try { + S.schedule = await api('/api/schedule/run', { id: t.id }); + paintSched(); + toast('已开始运行「' + (t.name || '任务') + '」'); + } catch (e2) { toast('启动失败:' + e2.message, 'err', 6000); } + }); + $('#sched-stop', el).addEventListener('click', async () => { + try { + S.schedule = await api('/api/schedule/stop', {}); + paintSched(); + } catch (e2) { toast('停止失败:' + e2.message, 'err'); } + }); + $('#sched-conflict', el).addEventListener('change', ev => { + schedSave({ conflict: ev.target.value }).catch(e2 => toast('保存失败:' + e2.message, 'err')); + }); + $('#sched-onfail', el).addEventListener('change', ev => { + schedSave({ onChainFail: ev.target.value }).catch(e2 => toast('保存失败:' + e2.message, 'err')); + }); + $('#sched-rows', el).addEventListener('click', ev => { + if (ev.target.closest('[data-sched-en]')) return; // 勾选框自己处理 + const row = ev.target.closest('.sched-row'); + if (!row) return; + schedSel = Number(row.dataset.i); + paintSched(); + }); + $('#sched-rows', el).addEventListener('change', ev => { + const cb = ev.target.closest('[data-sched-en]'); + if (!cb) return; + const i = Number(cb.dataset.schedEn); + const rows = (schedOf().tasks || []).slice(); + if (!rows[i]) return; + rows[i] = Object.assign({}, rows[i], { enabled: cb.checked }); + schedSave({ tasks: rows }).catch(e2 => { + cb.checked = !cb.checked; + toast('保存失败:' + e2.message, 'err'); + }); + }); + /* ---------------- 版本更新 ---------------- */ $('#set-pack-check', el).addEventListener('click', async () => { const btn = $('#set-pack-check', el); @@ -3400,9 +3981,10 @@ function openSettings() { else openBlacklist(kind, paintBlCounts); }); - // 默认页就是账号管理:打开先把 token 读出来(读的是本机密文,很快)。 - // 之前只在切页时触发,结果打开设置看到一排「读取中…」永远不动。 - $$('.set-acct', el).forEach(c => fillToken(c)); + // 默认页就是账号管理:打开先把当前分组的 token 读出来(本机密文, + // 很快)。另一组等切过去再读,免得一开设置就打一串请求。 + paintSetGame(setGame); + paintTabN(); }, }); } diff --git a/frontend/style.css b/frontend/style.css index ed8bb5f..f9c6cd3 100644 --- a/frontend/style.css +++ b/frontend/style.css @@ -2512,6 +2512,16 @@ body.drawer-open .basket-fab { opacity: 0; pointer-events: none; transform: scal margin-top: 2px; } .set-maarow-foot .onb-hint { flex: 1 1 auto; font-size: 11.5px; } +/* 账号卡第二行:配置文件(MAA 的 Configuration)+ 切号名,并排两栏。 + 窄屏折成一列,免得下拉里的档案名被挤成「...」 */ +.set-maarow-two { + display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.05fr); + gap: 0 12px; +} +.set-maarow-two .field { margin-bottom: 10px; } +@media (max-width: 780px) { + .set-maarow-two { grid-template-columns: 1fr; } +} .btn-solid.mini { height: 32px; padding: 0 14px; font-size: 12px; } /* 版本 */ @@ -2537,3 +2547,97 @@ body.drawer-open .basket-fab { opacity: 0; pointer-events: none; transform: scal .set-tab { font-size: 11.5px; } .set-panes { padding: 16px 14px 4px; } } + +/* ============================================================ 设置:游戏分组 + 明日方舟 / 明日方舟终末地。样式复用侧栏那套 .game-switch,只限制宽度, + 免得分组条在 700px 的设置页里拉成一整行。 */ +.set-gswitch { max-width: 380px; margin: 0 0 16px; } +.gamepane { display: none; } +.gamepane.active { display: block; } +/* MAA 路径页里的「bilibili服」用粉色点出来:B 服的切号名规则跟官服不一样, + 填错在 MAA 里会死找账号,值得显眼一点 */ +.bili-word { font-style: normal; color: #ff9dd1; font-weight: 700; } +.set-maarow-head .acct-ch { font-weight: 700; } + +/* ============================================================ 设置:定时任务 + 表格是 CSS grid(不是 table):列宽能跟着弹窗宽度走,窄屏时程序名/ + 参数自己省略,不会把「通知」列挤出去。 */ +.sched-wrap { + border: 1px solid var(--line); border-radius: 14px; overflow: hidden; + background: rgba(255, 255, 255, 0.012); +} +.sched-head, .sched-row { + display: grid; + grid-template-columns: 26px 38px minmax(92px, 1.1fr) minmax(104px, 1fr) minmax(90px, 1.05fr) minmax(64px, 0.9fr) 38px; + gap: 8px; align-items: center; padding: 9px 12px; +} +.sched-head { + font-size: 10.5px; letter-spacing: .4px; color: var(--text-3); + background: rgba(255, 255, 255, 0.03); border-bottom: 1px solid var(--line); +} +.sched-row { font-size: 11.8px; color: var(--text-2); border-top: 1px solid var(--line); } +.sched-row:first-child { border-top: none; } +.sched-row:hover { background: rgba(255, 255, 255, 0.035); } +.sched-row.sel { background: rgba(94, 234, 212, 0.07); box-shadow: inset 2px 0 0 var(--mint); } +.sched-row.off { opacity: .5; } +.sched-row.is-chain .sched-name { color: var(--text-3); } +.sched-num { font-family: var(--mono); font-size: 10.5px; color: var(--text-3); } +.sched-en input { accent-color: var(--mint); width: 14px; height: 14px; } +.sched-name { + color: var(--text); font-weight: 600; + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; +} +.sched-live { + font-style: normal; font-size: 9.5px; font-weight: 700; + color: #071410; background: var(--mint); border-radius: 5px; + padding: 1px 5px; margin-left: 6px; +} +.sched-plan { + font-family: var(--mono); font-size: 10.8px; color: var(--text-2); + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; +} +.sched-plan em { font-style: normal; color: var(--text-3); } +.sched-chain { color: var(--indigo); } +.sched-prog, .sched-args { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.sched-prog { color: var(--text-2); } +.sched-args { font-family: var(--mono); font-size: 10.6px; color: var(--text-3); } +.sched-warn { font-style: normal; color: var(--amber); } +.sched-nt { color: var(--text-3); font-size: 11px; } +.sched-empty { + padding: 26px 16px; text-align: center; + font-size: 11.8px; line-height: 1.8; color: var(--text-3); +} +.sched-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 12px; } +.sched-bar .spacer { flex: 1 1 auto; } +.sched-opt { display: inline-flex; align-items: center; gap: 6px; font-size: 11.5px; color: var(--text-3); white-space: nowrap; } +.sched-opt select { + height: 30px; padding: 0 8px; border-radius: 8px; + border: 1px solid var(--line-strong); background: rgba(10, 13, 20, .9); + color: var(--text-2); font-size: 11.5px; +} +.sched-state { font-size: 11.5px; color: var(--text-3); } +.sched-log { + margin-top: 14px; max-height: 132px; overflow-y: auto; + border: 1px dashed var(--line); border-radius: 12px; padding: 8px 10px; + font-family: var(--mono); font-size: 10.8px; line-height: 1.75; color: var(--text-3); +} +.sched-logline { display: flex; gap: 8px; } +.sched-logline span { flex: 0 0 auto; opacity: .8; } +.sched-logline.ok { color: var(--mint); } +.sched-logline.err { color: var(--rose); } +.sched-logline.warn { color: var(--amber); } +.sched-logline.ok span, .sched-logline.err span, .sched-logline.warn span { color: inherit; opacity: .6; } + +/* 定时任务编辑弹窗:超时 + 通知并排 */ +.st-row2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; align-items: start; } +.st-row2 .field { margin-bottom: 12px; } +.wd-row { display: flex; flex-wrap: wrap; gap: 6px; } +.wd-btn { + height: 28px; padding: 0 9px; border-radius: 8px; + border: 1px solid var(--line-strong); background: rgba(255, 255, 255, 0.03); + font-size: 11.5px; color: var(--text-3); +} +.wd-btn.on { + border-color: rgba(94, 234, 212, .5); color: #071410; font-weight: 700; + background: linear-gradient(140deg, var(--mint), #4fd7c8); +} diff --git a/tools/smoketest/smoke_test.py b/tools/smoketest/smoke_test.py index 4930366..79ba36b 100644 --- a/tools/smoketest/smoke_test.py +++ b/tools/smoketest/smoke_test.py @@ -3479,9 +3479,25 @@ def check_settings_panel(tmp): m = api.api_account_maa({}, {'file': 'smoke-acc.json', 'patch': {'accountName': '181 5505'}})['maa'] assert m['accountName'] == '181****5505', m + assert m['accountNameFrom'] == 'manual', '没写来源的按手填存' + # 前 3 位 + 后 4 位(2026-11-22 用户要求):157 3635 / 157****3635 都归一 + for raw in ('157 3635', '1573635', '157****3635'): + m = api.api_account_maa({}, {'file': 'smoke-acc.json', + 'patch': {'accountName': raw}})['maa'] + assert m['accountName'] == '157****3635', (raw, m) m = api.api_account_maa({}, {'file': 'smoke-acc.json', 'patch': {'accountName': ''}})['maa'] assert m['accountName'] == '', '清空切号名是合法操作,不能拦' + # 配置文件:只记名字(不校验存在性——MAA 没装也能先存),来源跟着改 + m = api.api_account_maa({}, {'file': 'smoke-acc.json', + 'patch': {'profile': ' moren ', + 'accountName': '1573635', + 'accountNameFrom': 'profile'}})['maa'] + assert m['profile'] == 'moren' and m['accountNameFrom'] == 'profile', m + # 来源字段只认两个值,乱传一律清空(别把脏值写进账号文件) + m = api.api_account_maa({}, {'file': 'smoke-acc.json', + 'patch': {'accountNameFrom': 'whatever'}})['maa'] + assert m['accountNameFrom'] == '', m try: api.api_account_maa({}, {'file': 'smoke-acc.json', 'patch': {'accountName': '冒烟'}}) @@ -3704,15 +3720,14 @@ def start(self, settle=15.0): assert (maaplan._subtask_label('Copilot@BattleQuickFormationRole-Caster') == '编队·按职业筛选') - # 8) 切号名唯一来源 = 账号绑定的 maa.accountName;**绝不读用户的 MAA - # 配置档案**(2026-11-18 用户口径:agent 模式跑临时配置=StartUp 任务 - # 参数,不碰用户的 gui.new.json)。以前这里会退回读 MAA 当前档案的 - # AccountName / 纯数字档案名来猜——档案和账号对不上号,猜错切号名 - # MAA 会在账号列表里死找 4 分钟。昵称也绝不能顶——官服切号认手机号。 + # 8) 切号名来源(2026-11-22 改):没绑配置文件时**完全不碰**用户的 MAA + # 配置;绑了配置文件(用户点名的那份)才读它 StartUp 的 AccountName。 + # 手填过的值(accountNameFrom=manual)优先,档案里的旧号码不许盖回去。 + # 全程只读——`_save_cfg` 必须一次都没被调用。 from core import maa as maa_mod def _forbidden(*a, **k): - raise AssertionError('不许读用户的 MAA 配置档案') + raise AssertionError('没绑配置文件时不许读用户的 MAA 配置') orig_load = maa_mod._load_cfg maa_mod._load_cfg = _forbidden @@ -3724,7 +3739,35 @@ def _forbidden(*a, **k): '账号绑定的切号名要能读到' finally: maa_mod._load_cfg = orig_load - accounts.save_maa_meta('smoke-acc.json', {'accountName': ''}) + + fake_cfg = {'Current': 'moren', + 'Configurations': {'moren': {'TaskQueue': [ + {'TaskType': 'StartUp', 'AccountName': '157****3635', + 'AccountSwitchEnabled': True}]}}} + + def _no_write(*a, **k): + raise AssertionError('读配置档案时不许写回用户的 gui.new.json') + + orig_save = maa_mod._save_cfg + maa_mod._load_cfg = lambda *a, **k: fake_cfg + maa_mod._save_cfg = _no_write + try: + accounts.save_maa_meta('smoke-acc.json', {'profile': 'moren', + 'accountName': '5505', + 'accountNameFrom': 'profile'}) + assert skills._account_name_tail('smoke-acc.json') == '157****3635', \ + '选了配置文件就要按档案里的 AccountName 来' + # 用户在设置里手改过 → 以他填的为准 + accounts.save_maa_meta('smoke-acc.json', {'accountName': '5505', + 'accountNameFrom': 'manual'}) + assert skills._account_name_tail('smoke-acc.json') == '5505', \ + '手填的切号名不能被档案里的旧号码盖回去' + finally: + maa_mod._load_cfg = orig_load + maa_mod._save_cfg = orig_save + accounts.save_maa_meta('smoke-acc.json', + {'profile': '', 'accountName': '', + 'accountNameFrom': ''}) # 9) Engine.wait 的启动宽限:AsstStart 异步生效,刚 start 完 AsstRunning # 还是 False——以前这里直接 return,把「还没开始跑」当「跑完」, @@ -4932,9 +4975,195 @@ def _write_maa(kind, addr, adb=''): shutil.rmtree(garrisondl.garrison_dir(), ignore_errors=True) +def check_scheduler(tmp): + """定时任务(设置 → 定时任务):清洗 / 下次运行 / 链式串接 / 参数解析 + + 只测纯逻辑,不起线程、不真跑程序:冒烟进程里挂一个常驻调度线程会在 + 后面的用例中间随机拉起进程,难查。真正执行由用户在界面上验。 + """ + import datetime + from core import scheduler + + _reset_config(tmp) + scheduler._cache = None + scheduler._fired.clear() + + # 1) 保存清洗:时间补零、星期去重排序、坏值回落、未知字段丢掉 + cfg = scheduler.save({'conflict': 'skip', 'onChainFail': 'stop', 'tasks': [ + {'name': ' 早上 ', 'mode': 'time', 'time': '8:5', + 'weekdays': [7, 3, 3, 9, 'x', True, 1], 'program': 'C:/x/a.exe', + 'args': ' --a 1 ', 'timeout': -5, 'notify': 1, 'evil': 'x'}, + {'name': '', 'mode': 'weird'}, + {'name': '链', 'mode': 'chain', 'program': 'b.exe'}, + ]}) + assert cfg['conflict'] == 'skip' and cfg['onChainFail'] == 'stop' + t0, t1, t2 = cfg['tasks'] + assert t0['time'] == '08:05', t0['time'] + assert t0['weekdays'] == [1, 3, 7], t0['weekdays'] + assert t0['args'] == '--a 1' and t0['timeout'] == 0 and t0['notify'] is True + assert 'evil' not in t0 + assert t1['name'] == '未命名任务' and t1['mode'] == 'time' + assert t2['mode'] == 'chain' and t2['enabled'] is True + assert len({t['id'] for t in cfg['tasks']}) == 3 + + # 2) 落盘读回(清缓存=模拟重启) + scheduler._cache = None + again = scheduler.load() + assert [t['name'] for t in again['tasks']] == ['早上', '未命名任务', '链'] + assert os.path.isfile(scheduler._path()) + + # 3) 时间点只认当前分钟,不回看上一分钟(关着的时候错过的点不补跑) + mon = datetime.datetime(2026, 11, 23, 8, 5, 20) # 周一 + assert scheduler._due_slot(t0, mon.timestamp()) == '2026-11-23 08:05' + assert scheduler._due_slot(t0, mon.replace(minute=6).timestamp()) == '' + tue = mon.replace(day=24) # 周二不在 [1,3,7] + assert scheduler._due_slot(t0, tue.timestamp()) == '' + assert scheduler.next_run_ts(t0, mon.replace(minute=4).timestamp()) == \ + int(mon.replace(second=0, microsecond=0).timestamp()) + nxt = scheduler.next_run_ts(t0, mon.replace(minute=6).timestamp()) + assert datetime.datetime.fromtimestamp(nxt).strftime('%Y-%m-%d %H:%M') == \ + '2026-11-25 08:05', datetime.datetime.fromtimestamp(nxt) + + # 4) 链式串接:中间夹一条 time 任务就断链 + assert scheduler._chain_after(t0, cfg['tasks']) == [] + + cfg2 = scheduler.save({'tasks': [ + {'name': 'A', 'mode': 'time', 'time': '07:00', 'program': 'a.exe'}, + {'name': 'B', 'mode': 'chain', 'program': 'b.exe'}, + {'name': 'C', 'mode': 'chain', 'program': 'c.exe', 'enabled': False}, + {'name': 'D', 'mode': 'chain', 'program': 'd.exe'}, + {'name': 'E', 'mode': 'time', 'time': '09:00', 'program': 'e.exe'}, + ]}) + names = [t['name'] for t in scheduler._chain_after(cfg2['tasks'][0], cfg2['tasks'])] + assert names == ['B', 'D'], names # 停用的 C 跳过,D 还在链上 + + # 5) 参数解析:引号里的空格不能拆开 + assert scheduler._split_args('--a "b c"') == ['--a', 'b c'] + assert scheduler._split_args('') == [] + + # 6) 程序存在性 / 批处理走 cmd + try: + scheduler._argv({'program': '', 'args': ''}) + assert False, '没填程序不该通过' + except ValueError: + pass + bat = os.path.join(tmp, 'demo.bat') + with open(bat, 'w', encoding='utf-8') as f: + f.write('@echo off\n') + argv = scheduler._argv({'program': bat, 'args': '--x 1'}) + assert argv[1:3] == ['/d', '/c'], argv + assert argv[3].endswith('demo.bat --x 1'), argv + + # 7) status 形状:界面依赖 nextRun / running / log + st = scheduler.status() + assert st['ok'] and st['running'] is None + assert st['conflict'] in scheduler.CONFLICTS + assert all('nextRun' in t and 'index' in t for t in st['tasks']) + assert isinstance(st['log'], list) and isinstance(st['seq'], int) + + # ---------------------------------------------------------------- 入口 +def check_account_bind(tmp): + """B50:切号名绑定(配置文件优先 / 手填优先 / 助手存尾号) + + 2026-11-22 用户要求三件事,这里各钉一条: + + ① 账号绑了 MAA 配置文件,切号名就从那份档案读(**只读**,不写回); + ② 用户手改过的值(`accountNameFrom=manual`)优先,档案里的旧号码不许盖; + ③ 助手新增 `set_account_name`:用户报尾号(后 4 位或前 3 + 后 4)就存进 + 对应账号的设置,多账号时先问是哪个号。 + """ + sys.path.insert(0, os.path.join(REPO, 'backend')) + from core import accounts, acctbind, acctname, agent, multiacct + + _reset_config(tmp) + cfg = os.path.join(tmp, 'config') + + def dump(name, obj): + with open(os.path.join(cfg, name), 'w', encoding='utf-8') as f: + json.dump(obj, f, ensure_ascii=False) + + dump('大号.json', {'account': {'uid': '1', 'nickName': '大号', + 'channelName': '官服', 'game': 'arknights'}}) + dump('小号.json', {'account': {'uid': '2', 'nickName': '小号', + 'channelName': '官服', 'game': 'arknights'}}) + + # 1) 尾号归一:后 4 位 / 前 3 + 后 4 / 掩码都收 + for raw, want in (('5505', '5505'), ('1573635', '157****3635'), + ('157 3635', '157****3635'), ('157****3635', '157****3635')): + assert acctname.check(raw, '官服')[0] == want, (raw, want) + + # 2) 助手存尾号:只填一个账号时不用再问是哪个号 + out = agent.run_tool('set_account_name', {'account': '大号', + 'accountName': '157 3635'}) + assert out.get('ok') and out['accountName'] == '157****3635', out + maa = accounts.get_account('大号.json')['maa'] + assert maa['accountName'] == '157****3635', maa + assert maa['accountNameFrom'] == 'manual', '手填必须打 manual 标记' + # 官服填昵称要拦(拿昵称切号 = MAA 死找 4 分钟) + bad = agent.run_tool('set_account_name', {'account': '大号', + 'accountName': '大号'}) + assert bad.get('error'), bad + # 多个账号又没指定 → 让模型先问用户 + ask = agent.run_tool('set_account_name', {'accountName': '5505'}) + assert ask.get('need_info') == 'account' and len(ask['accounts']) == 2, ask + + # 3) 配置文件优先:造一份 MAA 配置,账号绑上它,切号名跟着档案走 + md = os.path.join(tmp, 'fakemaa') + os.makedirs(os.path.join(md, 'config'), exist_ok=True) + with open(os.path.join(md, 'config', 'gui.new.json'), 'w', + encoding='utf-8') as f: + json.dump({'Current': 'moren', 'Configurations': { + 'moren': {'TaskQueue': [ + {'$type': 'StartUpTask', 'TaskType': 'StartUp', + 'AccountName': '181****5505', 'AccountSwitchEnabled': True}]}, + '136': {'TaskQueue': [ + {'$type': 'StartUpTask', 'TaskType': 'StartUp', + 'AccountName': '136'}]}, + }}, f, ensure_ascii=False) + accounts.save_maa_meta('大号.json', {'dir': md, 'profile': 'moren', + 'accountName': '', + 'accountNameFrom': 'profile'}) + nm, src = acctbind.resolve('大号.json') + assert (nm, src) == ('181****5505', 'profile'), (nm, src) + # 助手看到的账号列表也要是生效值,否则模型还会再问一遍 + lc = agent._tool_list_accounts({}) + row = next(a for a in lc['accounts'] if a['file'] == '大号.json') + assert row['accountName'] == '181****5505' and row['maaProfile'] == 'moren', row + cand = next(c for c in multiacct.candidates() if c['file'] == '大号.json') + assert cand['accountName'] == '181****5505', cand + + # 4) 手填优先:档案里是 181****5505,用户写 5505 就按 5505 跑 + accounts.save_maa_meta('大号.json', {'accountName': '5505', + 'accountNameFrom': 'manual'}) + assert acctbind.resolve('大号.json')[0] == '5505' + # 档案被删 / 换了目录读不到:回落手填值,不抛 + accounts.save_maa_meta('大号.json', {'dir': os.path.join(tmp, 'nope'), + 'accountName': '5505', + 'accountNameFrom': 'profile'}) + assert acctbind.resolve('大号.json')[0] == '5505', '读不到档案要回落手填值' + + # 5) 读档案绝不能写回用户的 gui.new.json + from core import maa as maa_mod + + def _no_write(*a, **k): + raise AssertionError('解析切号名时不许写 MAA 配置') + + orig_save = maa_mod._save_cfg + maa_mod._save_cfg = _no_write + try: + accounts.save_maa_meta('大号.json', {'dir': md, 'profile': '136', + 'accountName': '', + 'accountNameFrom': 'profile'}) + assert acctbind.resolve('大号.json')[0] == '136' + finally: + maa_mod._save_cfg = orig_save + accounts.save_maa_meta('大号.json', {'profile': '', 'accountName': '', + 'accountNameFrom': ''}) + + def main(): try: sys.stdout.reconfigure(encoding='utf-8', errors='replace') @@ -4999,6 +5228,8 @@ def main(): r.check('B46 牛杂小工具(小游戏/活动商店/黑名单位置/卡教程提示)', lambda: check_maa_tool(tmp)) r.check('B47 卫戍协议(核心检测/版本目录扫描/状态兜底/MAA 连接默认值/选项清洗/核心补丁)', lambda: check_garrison(tmp)) r.check('B48 干员替换(塞1←黍1:匹配/写入/干员组/不触发边界)', check_copilot_substitution) + r.check('B49 定时任务(清洗/下次运行/链式串接/参数解析)', lambda: check_scheduler(tmp)) + r.check('B50 切号名绑定(配置文件优先/手填优先/助手存尾号)', lambda: check_account_bind(tmp)) finally: shutil.rmtree(tmp, ignore_errors=True)