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 @@
搜一个关卡开始
卫戍协议—
+
+
`;
- }).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 => `
+
`).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)