Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 73 additions & 5 deletions backend/core/appupdate.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,16 @@ def _read_json(path, default=None):
return default


def _read_text(path, limit=200):
"""读一段纯文本(安装脚本写的失败原因),读不到就返回 ''"""
try:
# 脚本用 UTF8 编码写(PS 5.1 的 -Encoding UTF8 带 BOM),utf-8-sig 兼容两边
with io.open(path, encoding='utf-8-sig') as f:
return f.read().strip()[:limit]
except Exception:
return ''


def _write_json(path, data):
os.makedirs(os.path.dirname(path) or '.', exist_ok=True)
tmp = path + '.tmp'
Expand Down Expand Up @@ -704,12 +714,41 @@ def prepare() -> dict:
}
Log '已备份 exe / version.json / _internal'

# 4) _internal 用 /MIR:新版本删掉的旧 DLL 也要清掉,否则新旧混装
& robocopy.exe (Join-Path $pkg '_internal') (Join-Path $root '_internal') /MIR /R:2 /W:1 /NFL /NDL /NJH /NJS /NP | Out-Null
$rc = $LASTEXITCODE
Log ('_internal 镜像完成 rc=' + $rc)
# 4) _internal 用 /MIR:新版本删掉的旧 DLL 也要清掉,否则新旧混装。
# 被别的进程打开的 DLL(MAA.exe 常从我们这儿捞 VCRUNTIME140*.dll)会
# 「拒绝访问」失败——2026-11-15 真机上 v2.5.3 连装两次都栽在这两个 DLL。
# 所以重试 4 次、间隔 2 秒;仍不行就把 robocopy 点名的文件写进错误提示,
# 别只留一个 rc=9 让人猜。
$srcInternal = Join-Path $pkg '_internal'
$dstInternal = Join-Path $root '_internal'
$rclog = Join-Path $here 'install-robocopy.log'
$rc = 0
for ($i = 1; $i -le 4; $i++) {
& robocopy.exe $srcInternal $dstInternal /MIR /R:2 /W:1 /NFL /NDL /NJH /NJS /NP /LOG:$rclog | Out-Null
$rc = $LASTEXITCODE
Log ('_internal 镜像第 ' + $i + ' 次 rc=' + $rc)
if ($rc -lt 8) { break }
if ($i -lt 4) { Start-Sleep -Seconds 2 }
}
# robocopy:0-7 都是成功(1=有复制、3=有额外文件),8 以上才是真失败
if ($rc -ge 8) { Fail ('替换 _internal 失败 rc=' + $rc) }
if ($rc -ge 8) {
$why = ''
if (Test-Path -LiteralPath $rclog) {
# 按 0x 十六进制码挑错误行,不认「错误 / ERROR」这种本地化字样:
# robocopy 的日志跟着系统语言走,中文系统写「错误」、英文系统写 ERROR,
# 但错误行里的 (0x00000020) 两种语言都一样。读取用 Default(= robocopy
# 写日志用的系统 ANSI),否则文件名前后的中文会变成乱码。
$bad = @(Get-Content -LiteralPath $rclog -Encoding Default |
Where-Object { $_ -match '0x[0-9A-Fa-f]{8}' } | Select-Object -First 3)
if ($bad.Count -gt 0) {
$why = '(' + (($bad | ForEach-Object { $_.Trim() }) -join ';') + ')'
} else {
$tail = @(Get-Content -LiteralPath $rclog -Encoding Default | Select-Object -Last 2)
if ($tail.Count -gt 0) { $why = '(' + (($tail | ForEach-Object { $_.Trim() }) -join ';') + ')' }
}
}
Fail ('替换 _internal 失败 rc=' + $rc + $why + ';多半是 MAA.exe 或杀毒软件占着这些文件,关掉后重试')
}

# 5) 根级文件(exe / version.json / README)覆盖复制:不带 /MIR,
# 目标侧多出来的用户数据不会被删;/XD 把用户数据目录整个排除
Expand Down Expand Up @@ -737,6 +776,7 @@ def prepare() -> dict:
try { Start-Process -FilePath $exe -WorkingDirectory $root } catch { Log ('启动失败:' + $_.Exception.Message) }
CleanUp
Remove-Item -Path (Join-Path $here '*.zip') -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath $rclog -Force -ErrorAction SilentlyContinue
Log '=== 安装结束 ==='
Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue
'''
Expand Down Expand Up @@ -777,6 +817,25 @@ def _write_installer(stage_exe: str, version: str = '') -> str:
return ''


# ---------------------------------------------------------------- 安装前预检
# _internal 里的文件被别的进程打开时,robocopy 只回一个 rc=9(连文件名都不给),
# 脚本为了不留下半新半旧的安装会整体回滚——用户看到的就是「点了重启并安装,
# 回来还是旧版本,再装还是旧版本」。2026-11-15 真机:MAA.exe 把我们的
# VCRUNTIME140*.dll 捞去加载了,v2.5.3 连装两次都失败。所以点按钮前先把话
# 问清楚,别让用户白重启一次。
#
# 为什么不去逐个试开 _internal 里的文件:MAA-PRTS 自己就加载着二十多个
# (python312.dll、webview、pythonnet…),那样判定只会把每次更新都拦下。
# 真正会长期占住我们文件的只有 MAA.exe,剩下的交给脚本里的重试与明细。
def precheck() -> str:
"""替换前检查有没有拦路虎:有问题返回给用户看的文案,没问题返回 ''"""
from . import maa # 局部导入:maa 的依赖链会绕回本模块
if maa.is_running():
return ('MAA 正在运行,它锁着程序目录里的 VCRUNTIME140*.dll,替换会失败。'
'请先关闭 MAA 再安装(MAA-PRTS 自己会退出)')
return ''


def _powershell() -> str:
"""定位 powershell.exe:先按系统目录拼绝对路径,再退到 PATH

Expand Down Expand Up @@ -828,6 +887,9 @@ def install() -> dict:
"""一键:解压 → 写脚本 → 拉起 → 让主进程退出(前端会看到窗口关闭)"""
if not settings.FROZEN:
return {'ok': False, 'error': '源码模式不支持自动替换,请手动覆盖(真机请用打包版)'}
blocked = precheck()
if blocked:
return {'ok': False, 'error': blocked}
r = prepare()
if not r['ok']:
return r
Expand Down Expand Up @@ -887,6 +949,12 @@ def on_start() -> dict:
'ok': ok,
'state': 'done' if ok else 'stale',
}
if not ok:
# 安装脚本失败时把 rc / 被占用的文件写进 install-error.txt:带出去让
# 前端能说清「为什么没成」,否则用户只看到一句「没生效」又重试一遍
reason = _read_text(os.path.join(update_dir(), 'install-error.txt'))
if reason:
info['error'] = reason
st = _state()
st['lastInstall'] = info
_save_state(st)
Expand Down
17 changes: 15 additions & 2 deletions backend/core/maa.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,16 @@ def close(maa_dir=None):
return not is_running()


def _path_key(p: str) -> str:
"""PATH 条目的比较键:大小写、正反斜杠、尾部分隔符都不算区别

以前只做 normcase,`...\\_internal\\`(带尾斜杠)或 8.3 短名就漏过去了,
MAA.exe 照样能从我们包里捞 VCRUNTIME140.dll,然后锁死自动更新
(2026-11-15:v2.5.3 更新连装两次失败在 rc=9)。
"""
return os.path.normcase(os.path.normpath(p.strip().strip('"')).rstrip('\\/') or p)


def _launch_env():
"""启动 MAA 用的环境:把 PyInstaller 注入 PATH 的包内目录剔掉。

Expand All @@ -246,9 +256,12 @@ def _launch_env():
"""
env = os.environ.copy()
me = os.path.dirname(os.path.abspath(sys.executable))
drop = {os.path.normcase(me), os.path.normcase(os.path.join(me, '_internal'))}
drop = {_path_key(me), _path_key(os.path.join(me, '_internal'))}
meipass = getattr(sys, '_MEIPASS', '') or ''
if meipass:
drop.add(_path_key(meipass))
parts = [p for p in env.get('PATH', '').split(os.pathsep)
if p and os.path.normcase(p) not in drop]
if p and _path_key(p) not in drop]
env['PATH'] = os.pathsep.join(parts)
return env

Expand Down
5 changes: 3 additions & 2 deletions docs/backend.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,10 @@ pywebview 窗口与浏览器直开都是同源,不受影响。
| 版本比较 | 按数字比(`2.10 > 2.9`);预发布 `-beta.N` 永远小于同号正式;解析失败一律不触发 |
| 下载 | `github.com` 直链 → `gh-proxy` → `ghfast`,校验字节数 + sha256 + zip 内含 `MAA-PRTS.exe` |
| 解压 | 拒绝绝对路径与 `..`(zip-slip),落到 `<运行根>/update/stage/` |
| 替换 | 程序退出后由 `update/install.ps1` 执行:按 PID 等进程退出 → 备份 exe → `robocopy /MIR` 镜像 `_internal` → 覆盖根级文件 → 校验版本号 → 重启,失败则回滚并重新拉起旧版 |
| 预检 | `precheck()`:MAA.exe 在跑直接拒绝(它会把 `_internal/VCRUNTIME140*.dll` 加载进自己进程,镜像必失败)。不逐个试开 `_internal`——MAA-PRTS 自己就锁着二十多个 DLL,那样判定恒误报 |
| 替换 | 程序退出后由 `update/install.ps1` 执行:按 PID 等进程退出 → 备份 exe → `robocopy /MIR` 镜像 `_internal`(失败重试 4 次,仍失败把点名的文件写进 `install-error.txt`)→ 覆盖根级文件 → 校验版本号 → 重启,失败则整体回滚并重新拉起旧版 |
| 不动的东西 | `config/`、`debug/`、`resources/`——那是用户数据,脚本里一个字都不出现 |
| 结算 | 写 `update/pending.json`;新版本启动时版本号对上才算成功,否则日志留警告 |
| 结算 | 写 `update/pending.json`;新版本启动时版本号对上才算成功,否则日志留警告,并把 `install-error.txt` 的原因带进 `/api/app/status.lastInstall.error` |

`install()` 需要让整个进程退出,而 api 层不能 import main,所以 main 启动时
把退出函数注册进 `appupdate.set_quit_hook()`。源码模式一律拒绝自动替换。
Expand Down
23 changes: 18 additions & 5 deletions docs/update.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,13 @@ Windows 上运行中的 exe 不能覆盖,`_internal/` 里的 DLL 也不能删
↓
写 <运行根>/update/install.ps1,写 update/pending.json
↓ ← 用户点「重启并安装」
预检:MAA.exe 在跑就先拦下(它占着 _internal 里的 VCRUNTIME140*.dll)
↓
无窗口拉起 install.ps1(脱离父进程),主进程退出
↓
PowerShell:按 PID 等旧进程退出(最多 60 秒)→ 备份 exe 到 update/backup/
→ robocopy /MIR 镜像 _internal → robocopy 覆盖根级文件(exe、version.json)
→ robocopy /MIR 镜像 _internal(失败重试 4 次)
→ robocopy 覆盖根级文件(exe、version.json)
→ 校验版本号 → 启动程序 → 清 stage/zip → 自删
```

Expand Down Expand Up @@ -112,11 +115,20 @@ MAA-PRTS/ ← 程序本体整个换掉

### 失败怎么办

- **MAA 在跑就别装**:`MAA.exe` 会从我们 `_internal` 里加载 `VCRUNTIME140*.dll`
(PyInstaller 把包内目录前插进 PATH,子进程原样继承),此后它反向锁死发布包,
`robocopy /MIR` 只能回 `rc=9`。2026-11-15 真机上 v2.5.3 连装两次都栽在这:
窗口重启回来还是 2.5.2。所以点「重启并安装」前先跑 `appupdate.precheck()`,
MAA 在跑就直接弹提示让用户关掉,不白重启一次;真装的时候脚本还会重试 4 次
(间隔 2 秒),仍失败就把 robocopy 点名的文件写进 `install-error.txt`。
- 替换失败(`robocopy` 返回 ≥ 8、压缩包不完整、版本号没换成功):脚本先把
`update/backup/MAA-PRTS.exe` 还原,写 `update/install-error.txt`(附原因),
然后**把旧版本重新拉起来**——不会出现「点了安装,程序没了」;
`_internal`、`backup/MAA-PRTS.exe`、`backup/version.json` 一起还原,写
`update/install-error.txt`(附原因),然后**把旧版本重新拉起来**——不会出现
「点了安装,程序没了」;
- 成功了但版本没变:`update/pending.json` 不会被清掉,新版本启动时日志记一条
`[警告] 上次更新到 X 没生效`,前端第一次启动会弹一次提示。
`[警告] 上次更新到 X 没生效`,前端第一次启动会弹一次提示,并把
`install-error.txt` 里的原因一起带出来(「:替换 _internal 失败 rc=9」这种,
而不是只报一句没生效)。

排查时直接看 `debug/app.log` 里 `程序已更新:2.3.0 → 2.4.0` 或那条警告,
再看 `update/install.log`。
Expand All @@ -139,7 +151,8 @@ MAA-PRTS/ ← 程序本体整个换掉
| 一直没红点 | 设置里关了「启动后检查程序新版本」;或 6 小时内已查过;或最新 Release 是预发布而没开开关 |
| 提示有新版本但「下载并安装」是灰的 | 只拿到了版本号,API 被墙/限流,拿不到下载地址与 sha256。只能「前往下载页」 |
| 点「重启并安装」弹出黑窗口,然后一直不动 | **≤ v2.4.0 的已知缺陷**:cmd 版 `tasklist \| find` 死锁,安装卡在第一步。v2.4.1 起改成 `install.ps1`。旧版本请手动覆盖安装一次 |
| 点完「重启并安装」窗口关了但版本没变 | 看 `update/install.log` 与 `install-error.txt`;多半是杀软拦了脚本或 `robocopy` |
| 点完「重启并安装」窗口关了但版本没变 | 看 `update/install.log` 与 `install-error.txt` |
| `install-error.txt` 写「替换 _internal 失败 rc=9」 | **MAA.exe 还在跑**:它把 `_internal/VCRUNTIME140*.dll` 加载进了自己的进程,镜像必然失败。关掉 MAA 再点安装;v2.5.4 起点按钮前就会拦下并提示(`precheck()`) |
| 安装失败后程序自己又起来了,版本没变 | 这是有意设计:失败会回滚 exe 并重新拉起旧版本,不会让你「程序没了」 |
| 下载很慢或超时 | GitHub 直链慢,会自动退到 `gh-proxy` / `ghfast`;都失败就是网络问题,用下载页手动下 |
| 源码模式点不了安装 | 正常。源码运行不替换文件,要测请用打包版 |
Expand Down
5 changes: 4 additions & 1 deletion frontend/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -754,7 +754,10 @@ async function appAutoCheck(force) {
const li = st && st.lastInstall;
if (li && li.state === 'stale' && !S.staleNoticed) {
S.staleNoticed = true;
toast(`上次更新到 ${li.to} 没有生效,可以再试一次`, 'err', 6000);
// 安装脚本失败时会留下原因(rc / 被占用的 DLL):一并说出来,
// 用户才知道是「MAA 没关」而不是「更新坏了」
const why = li.error ? ':' + li.error : '';
toast(`上次更新到 ${li.to} 没有生效${why}`, 'err', 9000);
}
return st;
} catch (e) {
Expand Down
20 changes: 20 additions & 0 deletions tools/smoketest/smoke_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1269,6 +1269,26 @@ def check_app_update():
assert 'install-error.txt' in text and 'Start-Process' in text, \
'失败路径要留痕并重新拉起旧版本'

# 2026-11-15 真机:MAA.exe 把 _internal 里的 VCRUNTIME140*.dll 捞去加载,
# robocopy 镜像 rc=9,装到一半回滚,用户看到「更新完还是旧版本」还不知
# 道为什么。脚本必须重试,并把 robocopy 点名的文件写进错误提示。
assert 'install-robocopy.log' in text, '镜像失败要留下 robocopy 明细,别只剩一个 rc'
assert 'for ($i = 1; $i -le 4; $i++)' in text, '_internal 镜像要重试,不能一次失败就回滚'
assert 'Start-Sleep -Seconds 2' in text, '重试之间要等占用方释放文件'

# 7. 安装前预检:MAA 在跑时必须拦下并点名 MAA,别让用户白重启一次
#(不去逐个试开 _internal:MAA-PRTS 自己就锁着二十多个,那样恒误报)
import inspect as _inspect
assert 'precheck()' in _inspect.getsource(A.install), 'install() 必须先跑预检'
from core import maa as M
was = M.is_running
M.is_running = lambda: True
try:
why = A.precheck()
assert 'MAA' in why, 'MAA 在跑时预检必须拦住并点名 MAA,实际:%r' % why
finally:
M.is_running = was

# 拉起方式:PowerShell + 无窗口,且不能再走 cmd
import inspect
src = inspect.getsource(A.launch) + inspect.getsource(A._powershell)
Expand Down
Loading