feat: add reusable diff indexes and preserve confirmed CPU settings

Add automatically saved portable Diff Studio version indexes with import/export and regression coverage. Improve macOS package discovery, clarify update compatibility, and remove the shared E5 bootloader-state gate. Preserve confirmed voltage settings across normal power removal while retaining safe first-boot recovery.
This commit is contained in:
kanoqwq committed 2026-10-25 03:39:17 +08:00
1 parent cc0ecce71e
commit fb0b28e728
38 files changed
+1156 -113

No files matched your search

+26 -6
View File
@@ -38,20 +38,32 @@ OpenWrt 在 S08(根文件系统挂载之后)读取配置并加载模块;
其他系统由 extra-modules 加载;旧 rootfs 无平台适配器时,initramfs 从该 rootfs
加载零偏移模块以维持普通调频。绝不在早期初始化基带。
## 回退
## 断电与启动验证
配置在 `/etc/unisoc-modem/cpu-voltage.json`。应用非零值前写入
`cpu-voltage-armed.json` 并同步磁盘。正常系统 shutdown 清除标记,服务 stop 不清除。
下次启动若发现上一次留下的标记,将配置改名为 `.json.rejected`,加载零偏移。
直接拔电也视为异常关机;请重新保存后再正常重启,不会自动重试被拒绝的配置。
`cpu-voltage-armed.json` 并同步磁盘。启动到 S99 后,逐个核对三个 CPU 簇的实际
电压偏移,匹配后记录为已确认。正常 shutdown 也可确认匹配的读回值;服务 stop
不修改记录。确认只说明完成了启动,不保证该偏移通过了长期稳定性测试。
已确认的同一组设置会在后续启动继续使用。F50、V50 等无电池机型直接拔电属于
正常使用,不会因为没有执行 shutdown 就撤销配置;即使后一次启动途中断电,
先前已经确认的设置也保留。新保存的不同偏移需要重新完成启动确认。
首次应用一组新设置后若未完成确认,下次先以默认电压启动,并暂停自动重试。
这只能证明首次启动没有完成确认,不能据此认定发生崩溃,更不能认定由调压引起。
配置不会删除或改名;进入默认电压的系统后重新保存即可明确重试。损坏的启动记录
同样暂停自动应用并提示原因。旧版本记录会在首次启动中迁移,不把旧标记视为
异常断电证据。旧版已生成的 `.json.rejected` 不会自动恢复,需要用户重新选择。
“恢复默认电压”保存全零,当前已生效的偏移仍需重启才撤销。
如果无法进入 OpenWrt,可在 Android 挂载 TF 后移除这两个 JSON 文件再启动。
此回退依赖文件系统可读写,不替代原有 Android 启动失败保护。
此保护依赖文件系统可读写,不替代原有 Android 启动失败保护。它不监控运行中的
崩溃,不会因为单次 watchdog/panic 或缺少关机标记就撤销已经确认的设置。
## 验证
`tests/cpu_voltage_fixture.sh` 用假 sysfs/固件适配器验证范围、步进、未知固件、
缺失 domain、保存/回读、正常重启、异常重启和恢复默认;不访问实际电源寄存器。
缺失 domain、保存/回读、确认后的直接断电、首次未完成启动、明确重试及恢复默认;
不访问实际电源寄存器。
`tests/test_cpu_voltage.py` 覆盖编码往返、模块一次性约束、RPC 权限和打包清单。
实机电压与启动验证结果必须另行记录,不能以隔离测试代替。
@@ -63,3 +75,11 @@ S08 实测发现 by-name 软链尚未创建,已修正为用内核 PARTNAME 直
再保存全零并正常重启,31 个档位逐项回到原始电压,模块参数为 `0,0,0`,
armed 标记被正常清除;AT 返回 OK,USB 管理网、5 GHz/80 MHz AP 和蜂窝连接恢复。
这不是极限降压或长时间稳定性认证,未在实机进行故意断电/死机试验。
2026-10-24:移除“未执行 shutdown 就拒绝配置”的判定,改为上述启动确认记录。
原生 OpenWrt ucode 隔离测试覆盖确认后连续拔电、未完成首次启动的暂停、配置保留、
手动重试、错误读回、旧记录迁移、损坏记录及恢复默认,全部通过。
宿主测试 4 项通过;缺少本机 ucode/jsonfilter 的 1 项由上述容器实际运行替代。
前端语法检查通过;翻译测试 13 项通过、1 项缺少 po2lmo 跳过,另 1 项因既有
TTL 菜单缺少 PO 条目失败(菜单和 PO 文件不在本轮修改中)。
本轮仅修改共享后端、启动服务、页面提示与文档,没有编译内核、打包或连接设备。
+20 -4
View File
@@ -6,20 +6,22 @@
安装前备份重要文件,确认安装包适用于你的机型,并保持设备稳定供电。在 Android 中开启 USB 调试,允许这台电脑调试,并准备好 Magisk/root。
E5 系列不要求预先解锁 BL;仍需允许 ADB 调试并取得 root 权限。
MU300 系列在 Windows 通过有线 ADB 检查设备时,安装器会自动禁用该设备的 MTP 文件传输接口并显示通知,以避开原厂 USB 冲突。ADB、USB 网卡和串口保持启用,MTP 不会自动恢复。禁用失败只提示,不中断安装。无额外安装器确认步骤;Windows 可能请求管理权限。无线 ADB、macOS 和 E5 系列跳过处理。
只有无线 ADB 时,先将电脑连接到设备所在网络,展开设备选择区的“无线 ADB 连接”,填写 `192.168.0.1` 并点击“连接”。地址或端口不同请填写实际值,例如 `192.168.0.1:5555`。设备需已开启无线 ADB;Android 要求配对时,先按设备提示完成配对。
也可手动运行 `adb connect 192.168.0.1`。Windows 可在安装包目录打开 PowerShell,运行 `.\tools\adb.exe connect 192.168.0.1`。
Apple Silicon Mac 请打开完整解压目录中的 **OpenWrt-Installer.app**,保留相邻的 `tools`、`files` 等目录,无需另装 Python、Node 或 Rust。如果 macOS 阻止打开,请确认安装包来源后,在“系统设置 → 隐私与安全性”中允许打开。若安装器要求选择目录,请选择完整解压的安装包文件夹。
Apple Silicon Mac 请打开完整解压目录中的 **OpenWrt-Installer.app**,保留相邻的 `tools`、`files` 等目录,无需另装 Python、Node 或 Rust。不要只把 APP 拖到“应用程序”目录。如果 macOS 阻止打开,请确认安装包来源后,在“系统设置 → 隐私与安全性”中允许打开。若提示找不到安装包,请选择完整解压、同时包含 APP 和 `tools` 的安装包目录;缺少文件时请重新完整解压。选错目录可以重新选择,取消则退出安装器。
Linux、Intel Mac 或需要 Python 命令行入口时,可使用 **OpenWrt-Installer.py**,需另行安装 Python 和依赖。Apple Silicon Mac 的 `launchers/start-installer.sh` 可直接使用随包命令行后端。使用 Magisk 安装时,直接选择完整 ZIP;这会部署到 TF 卡并清空选定目标,请先备份卡内数据。
### 选择用途
- **安装 OpenWrt**:首次安装到 TF 卡或独立内置分区。校验安装包,选择设备并检查,然后核对安装计划。
- **更新 OpenWrt**:保留已有设置和容量更新系统。设备需运行 OpenWrt,电脑需连接它的网络,并提供管理地址和 SSH root 密码。
- **更新 OpenWrt**:仅支持相同内核、相同 OpenWrt 系统版本的更新,保留已有设置和容量。**不支持跨内核、跨 OpenWrt 系统版本升级;如需更换,请先备份重要数据,再重新安装。**设备需运行 OpenWrt,电脑需连接它的网络,并提供管理地址和 SSH root 密码。
- **继续未完成的安装**:选择原安装记录,接着完成中断的安装或 Android 重置后的续装。
- **临时启动已安装的 OpenWrt**:从 Android 切换到已安装的 OpenWrt,仅本次启动生效,不会设为默认系统。完成后按提示重启。
- **高级选项**:重装已有内置分区,或使用 userdata 镜像。重装会替换原 OpenWrt 系统和设置,保留 Android。**userdata 镜像是实验性功能,可能损坏 Android F2FS 文件系统**,建议优先选择 TF 卡或独立内置分区。
@@ -66,6 +68,12 @@ Linux、Intel Mac 或需要 Python 命令行入口时,可使用 **OpenWrt-Inst
若设备已经开机却一直等待,请核对电脑连接的设备网络、管理地址和密码,然后点击“我已进入 OpenWrt,开始校验”。地址或密码改过时,填写实际值。
#### Diff Studio:保存与复用版本摘要
Diff Studio 的旧版输入可选择完整 ZIP,也可选择之前保存的 `.owrt-index.json` 版本摘要;新版仍须选择完整 ZIP。分析通过后会自动保存新版摘要,结果区可“导出版本摘要”,左侧可“打开版本摘要目录”。摘要按版本分别保留,不需要保留旧版大包也能生成下一次差异包。
请选择与设备实际安装版本对应的旧包或摘要。保存摘要不代表设备已经完成更新;摘要不含系统文件,不能代替新版安装包或用于刷机。
### 卸载内置 OpenWrt 并归还空间
先在 OpenWrt 管理页面导出需要保留的配置,再通过设备的系统切换功能回到 Android,开启调试并授予 root。在安装器的“高级选项”中选择“卸载并归还空间”,检查设备并查看卸载计划。有原安装记录和完整备份时,优先按原记录归还空间;换过电脑时可以先导入原备份目录。
@@ -138,20 +146,22 @@ Extract the complete package and run **OpenWrt-Installer.exe** at its root. Keep
Back up important files, check that the package matches your model and keep the device powered. Enable USB debugging in Android, authorize this computer and have Magisk/root ready.
E5-family installation does not require prior bootloader unlocking. Authorized ADB debugging and root access are still required.
For MU300-series devices checked over wired ADB on Windows, the installer automatically disables only that device's MTP interface and displays a notification, avoiding the stock USB conflict. ADB, USB networking and serial interfaces stay enabled; MTP is not re-enabled. Failure only shows a warning and does not interrupt installation. There is no extra installer confirmation; Windows may request administrator permission. Wireless ADB, macOS and the E5 adapter skip this workaround.
For wireless ADB only, connect the computer to the device’s network, expand Wireless ADB connection, enter `192.168.0.1` and select Connect. Use the actual address and port if different, for example `192.168.0.1:5555`. Wireless ADB must already be enabled. If Android requires pairing, complete it on the device first.
Alternatively, manually run `adb connect 192.168.0.1`. On Windows, open PowerShell in the package folder and run `.\tools\adb.exe connect 192.168.0.1`.
On an Apple Silicon Mac, open **OpenWrt-Installer.app** in the fully extracted package. Keep the adjacent `tools`, `files` and other folders. No Python, Node or Rust installation is needed. If macOS blocks it, verify the package source, then allow it in System Settings → Privacy & Security. If the installer asks for a folder, select the fully extracted package directory.
On an Apple Silicon Mac, open **OpenWrt-Installer.app** in the fully extracted package. Keep the adjacent `tools`, `files` and other folders; do not move just the APP to Applications. No Python, Node or Rust installation is needed. If macOS blocks it, verify the package source, then allow it in System Settings → Privacy & Security. If the package cannot be found, select the fully extracted folder containing both the APP and `tools`. Extract the entire archive again if files are missing. An incorrect selection can be retried; Cancel closes the installer.
For Linux, Intel Macs or the Python command-line entry, run **OpenWrt-Installer.py** with Python and its dependencies installed. On Apple Silicon, `launchers/start-installer.sh` uses the bundled command-line backend directly. To install through Magisk, select the complete ZIP. This installs to the TF card and erases the selected target, so back up the card first.
### Choose your purpose
- **Install OpenWrt**: install to a TF card or an independent internal partition. Verify the package, select and inspect the device, then review the plan.
- **Update OpenWrt**: update while keeping settings and capacity. OpenWrt must be running, and the computer must be connected to its network. Enter its management address and SSH root password.
- **Update OpenWrt**: update only with matching kernel and OpenWrt system versions, keeping settings and capacity. **Updates across kernels or OpenWrt system versions are not supported; back up important data and reinstall to change either.** OpenWrt must be running, and the computer must be connected to its network. Enter its management address and SSH root password.
- **Continue an unfinished installation**: select the original record to resume an interrupted installation or continue after an Android reset.
- **Boot installed OpenWrt once**: switch from Android to the installed OpenWrt for one boot, without changing the default system. Restart when prompted.
- **Advanced options**: reinstall an existing internal partition or use a userdata image. Reinstallation replaces OpenWrt and its settings while keeping Android. **Userdata image installation is experimental and may damage Android F2FS.** Prefer a TF card or an independent internal partition.
@@ -192,6 +202,12 @@ After submission, the device restarts automatically and the network disconnects
If the device has started but the installer keeps waiting, check the connected network, address and password, then select OpenWrt is running — verify now. Use the actual address and password if they have changed.
#### Diff Studio: save and reuse version indexes
The old input accepts a full ZIP or a previously saved `.owrt-index.json` version index. The new input still requires a full ZIP. Successful analysis automatically saves the new version index. Use Export version index in the results or Open version index folder on the left. Versions are retained separately, so the old full package is no longer needed for the next comparison.
Choose the old package or index matching the version actually installed on the device. Saving an index does not mean an update has completed. Indexes contain no system file contents and cannot replace the new package or be flashed.
### Remove internal OpenWrt and return space
First export needed configuration from the OpenWrt management page, then return to rooted Android using the device’s system switch, enable debugging and authorize this computer. Under Advanced options, choose Uninstall and return space, inspect the device and review the plan. Matching original installation records and full backups are preferred; they can be imported on another computer.
+6
View File
@@ -1,5 +1,11 @@
# Installer protocol and recovery contract
## Diff Studio version indexes
`ota_analyze {old,new}` and `ota_export {output}` return an optional `index_path` after a compatible analysis. Old input may be a complete release or a validated version-1 `openwrt-release-index` JSON; new input must remain complete. The index captures the generated target descriptors, not an installation receipt. `ota_export_index {output}` copies only the coordinator's last successful cached index, refusing existing destinations and stale/failed analysis state. No device operation is involved.
Native `pick_ota_input {kind:"old"}` permits ZIP/JSON selection; other input kinds retain ZIP/OTA filtering. `save_index` selects an export destination, and `open_index_data` opens the fixed application-data `release-indexes` directory. No arbitrary shell or opener target is accepted.
The canonical implementation is `e5-linux/installer`. `sync.py <mu300-repository>` generates the other repository's mirror and `SHARED-SOURCE.json`. Edit the canonical source, synchronize, and run `--check`. Do not independently maintain two frontends/state machines. Both builds use the same Tauri executable and backend; repository-specific behavior is in `backend/adapter.py` and the existing Python/device scripts.
Protocol 1: one JSON object per line on stdin/stdout. A request is `{"protocol":1,"id":1,"command":"hello","params":{}}`. Responses contain the same `id`, `type:"response"` and `data:{ok,result}` or `{ok:false,error}`. Events use `type:"transaction"`, `"transfer"`, `"log"`. No terminal-text matching. Legacy stdout/stderr becomes sanitized diagnostic log events, independently of named state/effect callbacks.
+10
View File
@@ -1,5 +1,13 @@
# Building the desktop installer
## Diff Studio version indexes
Successful compatible analysis automatically writes a content-addressed `.owrt-index.json` under the application's `release-indexes` directory. The old input accepts a full release or this index; the new input still requires a complete release. The native old-file dialog starts in the index folder when it exists. Open-folder and export actions are available without assuming a device has been updated.
`backend/release_index.py` defines format `openwrt-release-index`, version 1. The SHA-256 covers canonical family/version/kernel metadata, file descriptors (type, hash, size, permissions, ownership, links and xattrs), APK version/dependency records and the boot-image hash. No payload contents or device identifiers are saved. The baseline is captured after inserting the actual target updater files. Import validates paths, descriptors, format, duplicate fields, integrity and size.
`analyze(..., index_directory=...)` opts into host persistence; GUI and CLI both use it. `ota_export_index` exports only the successfully analyzed cached index. Invalid or blocked analysis saves no new index and clears export state. Cache files are named by version/content, flushed and atomically published. The standalone assembler includes the module; no extra rootfs or dependency is added. User instructions are in GUIDE; see [verification](verification/diff-index-20261025.md).
The shared sidebar credits installer author Minikano and provides four copy-number QQ buttons plus two fixed project links. E5 points to `https://github.com/sprd-linux-devs/e5-linux` (Enceka and Minikano), and MU300 points to `https://github.com/dikeckaan/mu300-linux` (dikeckaan and Minikano). Minikano is credited as co-author of both. Native `open_repository` accepts only the IDs `e5` and `mu300`, which map to those two literal URLs; it does not accept a URL or shell command.
`ui/src/components/support.tsx` provides an optional donation notice on every application launch, followed by onboarding when applicable. Closing it lasts for that window only; older `support-notice-v1` acknowledgements are ignored. A labeled sidebar button reopens it. Both repository entries include a Lucide GitHub icon, and the dialog invites a Star through the same fixed-ID repository opener. Opening the page does not automatically star anything. Only the donation image host is added to CSP `img-src`; scripts and IPC/network command permissions remain restricted. Online loading uses a normal no-referrer image request, with a five-second timeout/error fallback to `ui/src/assets/donation-fallback.png`. The checked-in 613×514 PNG was downloaded from `https://api.kanokano.cn/pay/zsm.png` on 2026-10-15: 161,701 bytes, SHA-256 `22c0d03221750cfb7a8c59692ff0e7d7530e56b807fe731ed23522403ce99be3`. It is fingerprinted and embedded in the GUI release, not the device rootfs. To refresh it, download that exact source, inspect the image and update this provenance before rebuilding.
@@ -14,6 +22,8 @@ python installer/build.py
## Apple Silicon macOS and combined releases
Package discovery accepts an explicitly selected extracted root, APP/Contents or payload directory, and a single archive wrapper. Ambiguous selections require a specific release; invalid selections can be retried and Cancel exits normally. Payload verification retains the existing hashes and model checks. The native resolver and retry/cancel loop have standalone Rust tests run by `tests/test_distribution_paths.py`; see [the regression report](verification/macos-path-discovery-20261025.md) for executed checks and macOS runtime limitations. New native source files must be included in `package_gui.sources()` so old artifacts are rejected.
Run the same `python installer/build.py` on an Apple Silicon Mac with Xcode Command Line Tools, native ARM64 Python 3.12, Node 22 and Rust 1.90.0. Install the same Python build dependencies first. It creates `installer/artifacts/macos-arm64/OpenWrt-Installer.app`, `tools/macos/adb`, the private Python backend under `tools/macos/backend`, and a source/binary fingerprint manifest. macOS uses system WebKit, the native `open` command and `~/Library/Application Support/OpenWrt-Installer` for recovery records. The app locates either E5's `files/device-profile.json` or MU300's `desktop/manifest.json`; Finder translocation prompts for the extracted package folder. The macOS command-line launcher uses the same bundled backend, without a system Python dependency.
The build checks GUI architecture, applies and verifies an ad-hoc app signature, and pins Google's Darwin platform-tools archive in `platform-tools-macos.json`. The bundle version and identifier come from Tauri configuration. This is ARM64 support only; it does not produce an Intel or universal app. Ad-hoc signing is not Developer ID signing or Apple notarization, so downloaded applications may require explicit permission in Privacy & Security. See [Tauri's macOS distribution instructions](https://v2.tauri.app/distribute/macos-application-bundle/) and [signing documentation](https://v2.tauri.app/distribute/sign/macos/).
+30 -13
View File
@@ -5,21 +5,21 @@
".gitignore": "a5773f83330fc9adddfd159fe0391bccffbf7663dccb2b873f6b2d1b2d2eca11",
"backend_entry.py": "238a3534a790ce46ae396040623117299f78b9fc9fc89fe152bfdd5788f7b664",
"build.py": "f84fd40d9db9b39a0f8a35cee32dafc08f7dc774e17d76b060f49df73b5c8a10",
"GUIDE.md": "4c2eff2ac412d3205d86f9a605f77aed348d3e4213644b6897c1692ab851a17d",
"package_gui.py": "bcc61763c43b02c45cae27a7452516dd0d76c871a11ded98a04c4711becd1b62",
"GUIDE.md": "f5f9d457db705fac2d4f0a2e32670a81a364bed5c3e5359e526330757cef941b",
"package_gui.py": "493df19d77a996daf975d3bbb322ce25bc1eff52529f2c8252fdd331c33f0623",
"platform-tools.json": "d8fcf938e150bc314b5e6b2660c540976bb12ea6108fa75a8fb183115ebbd01e",
"PROTOCOL.md": "59a1aa39860f52c2f712224d6d3856373e23e25cdc3984d6dea11a577ca14483",
"README.md": "fb8ed271afbc38d7a569fb5b701e48c2659eb5a42be7808950ca725f65f2a5db",
"PROTOCOL.md": "1ac4b6d83356eff0e4bca1a21c194623d53ec1943b895e5175f60caf8362c199",
"README.md": "19bf4be4d7c7040332b8bc2a8c6679a4b23d1ebd3643896f24215ba7134f5f77",
"release.py": "f85a99a67802d4dee2b1cc782c9bdecb8e28240921d5c51f5230824179c35e10",
"requirements-build.txt": "762ee573a22c790eb3c5ccba4616632373d947dc88eb91fc85f3c678ac7b2259",
"sync.py": "978d022cc59ec653b64f58d1feec59b8a07dd37aa354324d99e78b5e6fe3522c",
"VERIFICATION.md": "3764dac5f830b67ed3b6e480fd89296b0f07f42b19c073076cd959d59aa16761",
"backend/adapter.py": "7483d83118b7c95035f11e69dc073132ed856aa3fb2ef6b90d460c5ee5dbe35e",
"VERIFICATION.md": "73c53a039c8464ddb87d91c2bed7dc009491eea55148968a5ef19c0b2bc37599",
"backend/adapter.py": "01aea8dcf853b9aa2b0de547fe5620a425058ac8a730217f886afae18ccbe6a1",
"backend/diagnostics.py": "529a7e2ac8d173c51a27ed825586263e9c0808f003c7ab1b36ca27e647e663df",
"backend/gpt.py": "4eca5ccf458ef86b9dfcea6388da61defe61af6389565cadf2fda6616e28b791",
"backend/helpers.py": "ac5422e60bcdd0273baa5d5796d64aa5b1e0687a709afc5bdf9c8501a7154d36",
"backend/package.py": "5c55e91f2c348ac957d7803810e6396edf3aae573da401ecf46e773ac75e70ee",
"backend/service.py": "47b708150228f8463be3dfb318d6c60f68dc39b69894fc7407807dfb951b7a87",
"backend/package.py": "1ff097d9437a308a3e78950430d554baab661107a094022988abd891f1a43310",
"backend/service.py": "3c66d53d81d3035172e526b181b7378aa8738e1271f61edb22396a8580dc9f85",
"backend/state.py": "bc17eac46b099524b2f2ad687d9fd6fcd3d867929487ef4a80d528992d6b3d48",
"backend/transport.py": "d438422b855a38d785b953c7d15e2814da3fbb6ea41e3983480089a07dff0d27",
"backend/__init__.py": "4227d63763e764fd2de7fc2bc13e474ae5de33176fb57aa0fd51cbb4ad80b88c",
@@ -69,7 +69,7 @@
"tests/test_flow_boundaries.py": "1ad4828a56744052b59d030522cf6e5264c87ac466b57a1600972d002a3294a2",
"tests/test_helpers.py": "41dce69cae63b53e681981c5ca13ed5d825965b8ed9d4d589ca14bf644f74eef",
"tests/test_legacy_binding.py": "b2bbae1ef0c2ecdecb2b3caeaee47047293d89507bf890592c1bd23d76908c82",
"tests/test_method_routing.py": "ae1053f1299935e473b1ee3fe64da6e323607967ead439e7c5769f52f6de5867",
"tests/test_method_routing.py": "b7cafa433cb0857d3947404d16e6a4465bc2226b1ec1b9f2d5aae9d3d2301dd4",
"tests/test_openwrt_confirmation.py": "ed9fb932cb6be775a52cd569b61a245c787bbe2b2935a21d469f38daf3c0c469",
"tests/test_recovery.py": "7b066dc300ee5df2e4e819aa2a7c2ab6a9c1e8a07d044da2ca3d3b2860945a64",
"tests/test_state.py": "ee80f34e9b295ffd4a92280836ceb6090b17d531e5914f0f5b86fa3bce0dca19",
@@ -159,8 +159,8 @@
"verification/windows-packages.json": "2527a520a27d9eb0f9243aa9e2ed05b0e4b90caefc8257ea3afe76acdb75a19d",
"ui/src/help-data.ts": "19fa8dd35fcef0ebc2726c16c641e5c357dfefe1342f9460c8da848339fb146b",
"ui/src/help-i18n.ts": "041a7fa8ac2c3f0adfc3d2f25331801e907915ad58d08eaa464d4165f0a6e5f1",
"ui/src/i18n.ts": "c4fb9704d766ed172729561d8e8aa2c9b8fabba9598e9a1faf47f045feb0619f",
"ui/src/main.tsx": "c9d670a83be5ea1277da61fae8417f0b2d54c2a513c732d48388cf1b79fe9257",
"ui/src/i18n.ts": "85de9bb6e3eaa42320e0cf5b0c258b367ec0c74ea649d13aeb786549c19db64c",
"ui/src/main.tsx": "cfd613868c879d9a22df19fab466154fc3b56ccad7eed35689cce4dc46eef061",
"ui/src/protocol.ts": "de30687657a75e06498fdcfd03727c8a1c6b09eadbb5e189ad62d7db8865ef17",
"ui/src/style.css": "9cc7a11d7d484842d6e2ec48b0ff24d16949305217585ff11620edcd5e6c0921",
"ui/src/utils.ts": "dd51582c0905c3507bd5dc3d32215a43fc156f6432042a7deb393fe4258b05ba",
@@ -177,7 +177,7 @@
"ui/src/components/ui/sonner.tsx": "59738d9ced20160c9d74971beb4fd23b794e5ff0682b998af55f604f92fdc9f8",
"ui/src-tauri/capabilities/default.json": "84a9a609f4cae132de6b7ee626a8d5c396eee5c2030d416922f4db5dc9624299",
"ui/src-tauri/icons/icon.ico": "5851131da4274abc593d41fa701a14ea3a99fda2da02bc5845c70664f7766094",
"ui/src-tauri/src/main.rs": "4c845718504083e3306135218098a652c20dabec8e0ef879e68b6971e958417a",
"ui/src-tauri/src/main.rs": "8bfc3792e118a04b835f4aace3c389693a52d0207c879d0da4bc533c24ce3bad",
"ui/src-tauri/gen/schemas/acl-manifests.json": "bdc3ced2ae416f11b23bc9c9b62341a3a59aa7bb5322f04f197bb08cb610409f",
"ui/src-tauri/gen/schemas/capabilities.json": "a4a9ce710aadc06946c296cfb8a0df506767ed310de13e32b5914d295fc81e56",
"ui/src-tauri/gen/schemas/desktop-schema.json": "4a946fe48fbb0c7c535ea53e6070bd8276f3f3d74f96efbaa6d85bd7b53b0f05",
@@ -278,7 +278,24 @@
"screenshots/uninstall-plan-device-gap-en.png": "005eb55faacdaa4f4fcdc3d50de25f4358d482ea8efcd704cb08ef90915e92d9",
"backend/windows_mtp.py": "81cb440841774681b82c569a3dd64e69c98dfb36be6c73d47194e210b79fc964",
"tests/test_windows_mtp.py": "ec1d1eddf48a7a274beec6815eca666c31ca85a846a3d76c6c77cdf8c4d37776",
"tests/mtp_smoke.py": "fce3ededebe84a34a42a0ef6671b7f6502e2a5a4597243f191760e38e5c20e60"
"tests/mtp_smoke.py": "fce3ededebe84a34a42a0ef6671b7f6502e2a5a4597243f191760e38e5c20e60",
"ui/src-tauri/src/distribution.rs": "c46e334a37c80ed9a449f49ff5dec9dc5a7fb41342d81982f365c98b7f6e126b",
"tests/test_package_paths.py": "3b70efc34fc43fb31e88fe06e34e4945cc41a51456cb6f00f90d79de0b69f131",
"tests/test_distribution_paths.py": "4d3affee346124926bf030d888e3d0a86a144044dbbf938159a4efbf80f8c6e8",
"verification/macos-path-discovery-20261025.md": "076c846d159c8a8a898709579787da90a63c6ad9667a78d7f57c182136839c94",
"tests/test_e5_boot_state.py": "47f0a99ac7191814b1bbe0b50988d3bac173fd228a12b1f66b5fc32c47351ccf",
"verification/e5-bl-preflight-20261025.md": "fc9c6e6642d978c2bd549f6eeaea9f724a1917a82e226b2c4907b1441478a33a",
"backend/ota_package.py": "50e0b27ba6bd7049fd384668cc5c22783165f5d88890b80b31f0ae9ed338d4d9",
"backend/ota_desktop.py": "b353d6b39d657b9fd15ef0c67275f5c5df344be7391826ebad2d7606c59f9fae",
"backend/release_index.py": "f4077a50bfee00bbbf3d332c638d61f0fcd08dbc76c8d55931a9cb71e44f6f0c",
"ota-tool.py": "1da55725c05f110c4b3d64bbe2e9a60d8de347f5e7b9e50261ba88bed62ce020",
"build-ota.py": "97f0e2e2a6293333e9da49b4e152fba9c41cc4097a9d4f13096321484fc05af8",
"ui/src/ota.tsx": "270f9015210eedfdf7683b35eb697872f0342a847caac14cc4574bd566ab06ce",
"ui/src/ota.css": "b9198011033cc66324ee475ca62820b9a74e3f47d201151055b4d3ab069127a0",
"tests/test_release_index.py": "0ed8eda40c5c27c9adff707a19c8fa736aa2fa733ba57c2131425e43677a2f15",
"tests/test_ota_ext4.py": "7acd465afbd02ae290b55f8cd943722f4d345cb678d028a3893d8e0af1879c8f",
"tests/ota_browser.py": "c94788a286df694ae6f7e9c5c8554639bec5bd868ca65d495db283a408241ede",
"verification/diff-index-20261025.md": "03ac557959fc95770ffc36c3f3cd8039371dce1804db5cb9964d8c5595c9c83c"
},
"compatibility_files": {
"desktop/binary_io.py": "25e30cf4f3b23e960b05ae512f06d617dd958835125678ea4c07a2fbc4d3420f",
+4
View File
@@ -1,5 +1,9 @@
# Windows installer verification — 2026-10-15
Diff Studio version-index validation: [2026-10-25 report](verification/diff-index-20261025.md).
Latest E5 BL-state preflight checks: [2026-10-25 report](verification/e5-bl-preflight-20261025.md).
## Wireless ADB Windows revision (2026-10-16)
The device section connects a user-supplied TCP endpoint and disconnects only the selected observed wireless device. Actual enumeration determines connected/unauthorized/offline state; terminal wording is ignored. Connection is also available at safe Android setup/root waits without changing the saved device binding. Disconnect is blocked for an active worker and by the shared serial mutex if another installer process owns the transport. The endpoint validator rejects options and command text. No debugging enablement, pairing, device shell, ADB-server restart or network-adapter changes are performed.
+2 -2
View File
@@ -258,8 +258,8 @@ class Adapter:
if device['model'] not in profile['android_models']:
raise ValueError('Package model differs / 安装包机型不匹配: ' + device['model'])
device['profile'] = profile['profile']
if device['slot'] != '_a' or properties['ro.boot.verifiedbootstate'] != 'orange':
raise ValueError('E5 requires unlocked Android slot A / E5 要求已解锁且当前 Android 在 A 槽')
if device['slot'] != '_a':
raise ValueError('E5 requires Android slot A / E5 要求当前 Android 在 A 槽')
else:
device['profile'] = self.legacy.android_profile(device['model'] + '\n' + properties['ro.product.device'], properties['ro.board.platform'])
# Trial boot uses only the boot signature, boot-chain check and misc.
+14 -3
View File
@@ -135,7 +135,7 @@ def refresh_rpc(client):
class Desktop:
def __init__(self, root, emit):
def __init__(self, root, emit, data_directory=None):
self.root = Path(root)
self.emit = emit
self.analysis = None
@@ -145,6 +145,9 @@ class Desktop:
self.activated = set()
self.pending_reboot = None
self.last_event = 0
from .release_index import index_directory
self.index_directory = Path(data_directory)/'release-indexes' if data_directory is not None else index_directory()
self.index_path = None
def progress(self, stage, path):
if time.monotonic() - self.last_event >= .4:
@@ -154,7 +157,13 @@ class Desktop:
def dispatch(self, command, p):
self.emit('ota_activity', {'busy': True})
try:
if command == 'ota_export_index':
if not self.index_path:
raise ValueError('Analyze a compatible release first / 请先完成兼容版本的差异分析')
from .release_index import read_index, write_index
return {'path':str(write_index(p['output'],read_index(self.index_path)))}
if command in ('ota_analyze', 'ota_export'):
self.index_path = None
if command == 'ota_analyze':
self.analysis = dict(old=p['old'], new=p['new'])
if not self.analysis:
@@ -162,13 +171,15 @@ class Desktop:
if command == 'ota_export' and p.get('output', '').lower().endswith('.zip'):
with tempfile.TemporaryDirectory(prefix='openwrt-ota-') as directory:
patch = Path(directory) / 'update.ota'
result = analyze(self.analysis['old'], self.analysis['new'], patch, self.progress)
result = analyze(self.analysis['old'], self.analysis['new'], patch, self.progress, index_directory=self.index_directory)
self.index_path = result.get('index_path')
from .ota_bundle import export_bundle
export_bundle(patch, p['output'], self.root)
result['output'] = p['output']
return result
result = analyze(self.analysis['old'], self.analysis['new'],
p.get('output') if command == 'ota_export' else None, self.progress)
p.get('output') if command == 'ota_export' else None, self.progress, index_directory=self.index_directory)
self.index_path = result.get('index_path')
return result
if command == 'ota_package':
archive = Path(p.get('path') or self.root / 'update.ota')
+14 -3
View File
@@ -346,13 +346,24 @@ def compare(old, new):
removed=sum(o['after'] is None for o in operations)), extra
def analyze(old_path, new_path, output=None, progress=lambda *_: None):
def analyze(old_path, new_path, output=None, progress=lambda *_: None, index_directory=None):
if not Path(new_path).is_dir() and Path(new_path).suffix.lower() == '.json':
raise ValueError('The new release must be a full package, not a version index / 新版必须选择完整安装包,不能使用版本摘要')
# Old image is released before decompressing the new one. Only the previous
# index survives; no pair of multi-GiB roots is retained.
with Release(old_path, progress) as old:
pass
if Path(old_path).suffix.lower() == '.json':
from .release_index import load_index
old = load_index(old_path)
else:
with Release(old_path, progress) as old:
pass
with Release(new_path, progress) as new:
result, extra = compare(old, new)
if index_directory is not None and result['can_export']:
from .release_index import save_index
# compare() includes the updater files actually supplied by this
# generator. Keep that target baseline, not stale package defaults.
result['index_path'] = str(save_index(new,index_directory))
if output:
if result['blockers']:
raise ValueError('; '.join(result['blockers'][:12]))
+32 -1
View File
@@ -13,8 +13,39 @@ def safe_file(root, name):
return path
def locate_package(directory):
"""Normalize a user-selected root, APP or payload folder, never search CWD."""
selected = Path(directory).expanduser().resolve()
if not selected.is_dir():
raise ValueError('Select a fully extracted package folder, not a ZIP / 请选择完整解压的安装包目录,不能选择 ZIP: ' + str(selected))
def has_layout(root):
return (root/'desktop/manifest.json').is_file() or (root/'files/device-profile.json').is_file()
# An incomplete root is still this package: report its missing file rather
# than choosing another release nested inside it.
def is_package(root):
return has_layout(root) or (root/'OpenWrt-Installer.py').is_file()
if is_package(selected):
return selected
app = next((p for p in (selected, *selected.parents) if p.suffix.lower() == '.app'), None)
if app:
selected = app.parent
elif selected.name in ('files', 'desktop'):
selected = selected.parent
if is_package(selected):
return selected
candidates = [p for p in selected.iterdir() if p.is_dir() and has_layout(p)]
if len(candidates) == 1:
return candidates[0].resolve()
if candidates:
raise ValueError('Multiple OpenWrt packages found; select the exact release folder / 此目录包含多个安装包,请明确选择其中一个安装包目录')
raise ValueError('No extracted OpenWrt package found; select the folder containing OpenWrt-Installer.py and files or desktop / 未找到解压后的安装包,请选择包含 OpenWrt-Installer.py 和 files 或 desktop 的目录: ' + str(selected))
def inspect_package(directory):
root = Path(directory).resolve()
root = locate_package(directory)
mu = root / 'desktop/manifest.json'
if mu.is_file():
manifest = json.loads(mu.read_text(encoding='utf-8'))
+113
View File
@@ -0,0 +1,113 @@
"""Portable, content-checked release baselines; contains no payload or device data."""
import hashlib
import json
import os
from pathlib import Path
import re
import sys
import tempfile
from types import SimpleNamespace
from .ota_engine import canonical, safe_name, validate_descriptor
FORMAT = 'openwrt-release-index'
SUFFIX = '.owrt-index.json'
MAX_SIZE = 64 << 20
def index_directory():
if sys.platform == 'darwin':
base = Path.home()/'Library/Application Support'
else:
base = Path(os.environ.get('LOCALAPPDATA', Path.home()/'.local/share'))
return base/'OpenWrt-Installer/release-indexes'
def validate(data):
if not isinstance(data, dict) or set(data) != {'format','version','sha256','release'} or data.get('format') != FORMAT or type(data.get('version')) is not int or data['version'] != 1:
raise ValueError('Unsupported release index / 不支持的版本摘要格式')
release = data['release']
if not isinstance(release, dict) or set(release) != {'family','meta','entries','packages','boot_digest'}:
raise ValueError('Incomplete release index / 版本摘要不完整')
if data['sha256'] != hashlib.sha256(canonical(release)).hexdigest():
raise ValueError('Release index checksum mismatch / 版本摘要校验失败')
if release['family'] not in ('e5','mu300'):
raise ValueError('Invalid release index family')
meta = release['meta']
if not isinstance(meta, dict) or set(meta) != {'profile','image_version','kernel_release','openwrt'} or any(not isinstance(v,str) or not v or len(v)>256 or any(ord(c)<32 for c in v) for v in meta.values()):
raise ValueError('Invalid release index identity')
if not re.fullmatch(r'[a-z0-9][a-z0-9_-]{0,63}',meta['profile']) or not isinstance(release['boot_digest'],str) or not re.fullmatch('[a-f0-9]{64}',release['boot_digest']):
raise ValueError('Invalid release index profile/boot hash')
entries = release['entries']
if not isinstance(entries,dict) or not entries or len(entries)>250000:
raise ValueError('Invalid release index file table')
for name, desc in entries.items():
if not isinstance(name,str):raise ValueError('Invalid release index path')
safe_name(name)
if not isinstance(desc,dict) or not isinstance(desc.get('xattrs',{}),dict) or set(desc)-{'kind','mode','uid','gid','size','sha256','target','xattrs'}:
raise ValueError('Invalid release index descriptor')
validate_descriptor(desc)
packages = release['packages']
if not isinstance(packages,dict) or any(not isinstance(k,str) or not k or len(k)>256 or not isinstance(v,dict)
or set(v)!={'V','A','D'} or any(not isinstance(s,str) or len(s)>65536 for s in v.values()) for k,v in packages.items()):
raise ValueError('Invalid release index packages')
return data
def snapshot(release):
body = dict(family=release.family,meta={k:release.meta[k] for k in ('profile','image_version','kernel_release','openwrt')},
entries=release.entries,packages=release.packages,boot_digest=release.boot_digest)
return validate(dict(format=FORMAT,version=1,sha256=hashlib.sha256(canonical(body)).hexdigest(),release=body))
def _unique(pairs):
result = {}
for key,value in pairs:
if key in result:raise ValueError('Duplicate release index key / 版本摘要存在重复字段')
result[key] = value
return result
def read_index(path):
with Path(path).open('rb') as stream:
raw = stream.read(MAX_SIZE+1)
if len(raw)>MAX_SIZE:raise ValueError('Release index exceeds 64 MiB')
try:
return validate(json.loads(raw,object_pairs_hook=_unique))
except (TypeError,AttributeError,UnicodeError,RecursionError) as error:
raise ValueError('Invalid release index / 版本摘要损坏') from error
def load_index(path):
data = read_index(path)
return SimpleNamespace(source=Path(path),**data['release'])
def write_index(path,data,reuse=False):
validate(data)
path = Path(path)
raw = canonical(data)+b'\n'
if len(raw)>MAX_SIZE:raise ValueError('Release index exceeds 64 MiB')
path.parent.mkdir(parents=True,exist_ok=True)
if os.path.lexists(path):
if reuse and read_index(path)==data:return path
raise ValueError('Release index destination already exists / 版本摘要目标文件已存在: '+str(path))
fd,temp = tempfile.mkstemp(prefix='.release-index-',dir=path.parent)
try:
with os.fdopen(fd,'wb') as stream:
stream.write(raw);stream.flush();os.fsync(stream.fileno())
os.replace(temp,path)
if os.name != 'nt':
directory = os.open(path.parent,os.O_RDONLY | os.O_DIRECTORY)
try:os.fsync(directory)
finally:os.close(directory)
finally:
if os.path.exists(temp):os.unlink(temp)
return path
def save_index(release,directory):
data = snapshot(release)
label = re.sub('[^A-Za-z0-9._-]','_',release.meta['image_version'])[:100]
path = Path(directory)/('OpenWrt-'+label+'-'+data['sha256']+SUFFIX)
return write_index(path,data,reuse=True)
+1 -1
View File
@@ -102,7 +102,7 @@ class Service:
self.verification_request = None
self.verification_wake = threading.Event()
from .ota_desktop import Desktop
self.ota = Desktop(self.package_root, self.emit)
self.ota = Desktop(self.package_root, self.emit, self.store.base)
def emit(self, kind, data, request_id=None):
event = {'protocol': 1, 'type': kind, 'data': data}
+2 -2
View File
@@ -29,7 +29,7 @@ def main():
raise ValueError('Select a new output directory (Windows --refresh requires an unchanged owned directory)')
recorded=json.loads((a.output/'diff-tool.json').read_text(encoding='utf-8'))
expected={'OpenWrt-Diff-Studio.exe','OpenWrt-Diff-Studio.py'}
expected.update('backend/'+n for n in ('__init__.py','ota_engine.py','ota_package.py','ota_desktop.py','ota_bundle.py','ota_runtime.py','boot.py','rpc.py','proxy.sh','lz4raw-aarch64.so','errors.js','unisoc-ota.js','unisoc-ota.json'))
expected.update('backend/'+n for n in ('__init__.py','ota_engine.py','ota_package.py','release_index.py','ota_desktop.py','ota_bundle.py','ota_runtime.py','boot.py','rpc.py','proxy.sh','lz4raw-aarch64.so','errors.js','unisoc-ota.js','unisoc-ota.json'))
expected.update(path.relative_to(artifact).as_posix() for path in (artifact/'tools/backend').rglob('*') if path.is_file())
actual={path.relative_to(a.output).as_posix() for path in a.output.rglob('*') if path.is_file() and path.name!='diff-tool.json'}
if recorded.get('protocol')!=1 or set(recorded.get('files',{}))!=expected or actual!=expected:
@@ -61,7 +61,7 @@ def main():
shutil.copytree(artifact / 'tools/backend', a.output / 'tools/backend', dirs_exist_ok=a.refresh)
shutil.copy2(installer / 'ota-tool.py', a.output / 'OpenWrt-Diff-Studio.py')
(a.output / 'backend').mkdir(exist_ok=a.refresh)
for name in ('__init__.py', 'ota_engine.py', 'ota_package.py', 'ota_desktop.py', 'ota_bundle.py', 'ota_runtime.py', 'boot.py', 'rpc.py', 'proxy.sh', 'lz4raw-aarch64.so', 'errors.js', 'unisoc-ota.js', 'unisoc-ota.json'):
for name in ('__init__.py', 'ota_engine.py', 'ota_package.py', 'release_index.py', 'ota_desktop.py', 'ota_bundle.py', 'ota_runtime.py', 'boot.py', 'rpc.py', 'proxy.sh', 'lz4raw-aarch64.so', 'errors.js', 'unisoc-ota.js', 'unisoc-ota.json'):
source = installer.parent/'openwrt/luci-app-unisoc-ota/root/usr/lib/unisoc-ota/engine.py' if name=='ota_engine.py' else installer.parent/'openwrt/luci-app-unisoc-ota/root/usr/lib/unisoc-ota'/name if name in ('boot.py','rpc.py','proxy.sh','lz4raw-aarch64.so','errors.js','unisoc-ota.js','unisoc-ota.json') else installer/'backend'/name
if name == 'lz4raw-aarch64.so': source = installer/'ota-native'/name
extra = {'errors.js':'htdocs/luci-static/resources/unisoc-ota/errors.js','unisoc-ota.js':'htdocs/luci-static/resources/view/system/unisoc-ota.js','unisoc-ota.json':'root/usr/share/rpcd/acl.d/unisoc-ota.json'}
+4 -3
View File
@@ -12,8 +12,8 @@ def main():
sub = p.add_subparsers(dest='command', required=True)
for name in ('analyze', 'generate'):
q = sub.add_parser(name)
q.add_argument('old')
q.add_argument('new')
q.add_argument('old',help='Old release ZIP/folder or saved .owrt-index.json')
q.add_argument('new',help='New complete release ZIP/folder')
if name == 'generate':
q.add_argument('output')
q = sub.add_parser('update')
@@ -21,7 +21,8 @@ def main():
q.add_argument('--host', required=True)
args = p.parse_args()
if args.command != 'update':
result = analyze(args.old, args.new, getattr(args, 'output', None))
from backend.release_index import index_directory
result = analyze(args.old, args.new, getattr(args, 'output', None), index_directory=index_directory())
else:
import getpass
d = Desktop(Path(__file__).parent, lambda *_: None)
+1 -1
View File
@@ -25,7 +25,7 @@ def sources():
paths += [HERE/'build-ota-native.py']
paths += [p for p in (HERE/'ui/src').rglob('*') if p.is_file()]
paths += [HERE/'ui'/n for n in ('package.json','package-lock.json','vite.config.ts','tailwind.config.js','postcss.config.js','tsconfig.json','index.html','diff.html','ota.html','rust-toolchain.toml')]
paths += [HERE/'ui/src-tauri'/n for n in ('Cargo.toml','Cargo.lock','build.rs','tauri.conf.json','src/main.rs','capabilities/default.json','icons/icon.ico','icons/icon.icns','icons/icon.png')]
paths += [HERE/'ui/src-tauri'/n for n in ('Cargo.toml','Cargo.lock','build.rs','tauri.conf.json','src/main.rs','src/distribution.rs','capabilities/default.json','icons/icon.ico','icons/icon.icns','icons/icon.png')]
plugin = HERE.parent/'openwrt/luci-app-unisoc-ota'
paths += list((plugin/'htdocs').rglob('*.js'))
paths += [plugin/'root/usr/share/rpcd/acl.d/unisoc-ota.json']
+40 -3
View File
@@ -18,10 +18,13 @@ window.__TAURI_INTERNALS__={metadata:{currentWindow:{label:'main'},currentWebvie
if(cmd==='plugin:event|listen'){listeners.set(++eventId,args);return eventId;}
if(cmd==='plugin:event|unlisten'){listeners.delete(args.eventId);return;}
if(cmd==='pick_ota_input')return window.selectedFile||(++picked===1?'D:/Releases/old.zip':'D:/Releases/new.zip');
if(cmd==='save_index')return window.cancelIndex?null:'D:/Saved/new.owrt-index.json';
if(cmd==='open_index_data'){window.indexOpened=(window.indexOpened||0)+1;return;}
if(cmd==='save_ota'){window.saveArgs=args;return window.cancelSave?null:(window.manualOutput||'D:/Releases/update.ota');}
const command=args?.command;
if(command==='ota_package'){if(window.packageError)throw Error(window.packageError);if(window.badPackage)throw Error('Invalid selected patch');return {path:'D:/Releases/update.ota',manifest};}
if(command==='ota_analyze'){window.analyzeArgs=args.params;return {suggested_name:'OpenWrt-patch-T551M-25.12.5-k6.18.54-20261019.170725-g11111111-to-20261020.180000-g22222222.zip',manifest:window.testBlocked?{...manifest,operations:Array.from({length:180},(_,i)=>({path:`usr/lib/example/changed-file-${i}.js`,before:{},after:{}}))}:manifest,blockers:window.testBlocked?Array.from({length:12},(_,i)=>`Core runtime/module/updater changed; use the full installer: usr/lib/unisoc-ota/changed-file-${i}.py`):[],can_export:!window.testBlocked,payload_bytes:53720,files:window.testBlocked?180:1,added:0,removed:0};}
if(command==='ota_analyze'){window.analyzeArgs=args.params;return {suggested_name:'OpenWrt-patch-T551M-25.12.5-k6.18.54-20261019.170725-g11111111-to-20261020.180000-g22222222.zip',manifest:window.testBlocked?{...manifest,operations:Array.from({length:180},(_,i)=>({path:`usr/lib/example/changed-file-${i}.js`,before:{},after:{}}))}:manifest,blockers:window.testBlocked?Array.from({length:12},(_,i)=>`Core runtime/module/updater changed; use the full installer: usr/lib/unisoc-ota/changed-file-${i}.py`):[],can_export:!window.testBlocked,payload_bytes:53720,files:window.testBlocked?180:1,added:0,removed:0,index_path:window.testBlocked?undefined:'D:/App Data/release-indexes/new.owrt-index.json'};}
if(command==='ota_export_index'){window.indexExport=args.params.output;return {path:args.params.output};}
if(command==='ota_export'){window.exportArgs=args.params;return {output:args.params.output};}
if(command==='ota_probe')return {token:'reviewed',check:{applicable:!window.testConflict,conflicts:window.testConflict?['usr/libexec/unisoc-modem/action']:[],package_conflicts:[],required_bytes:20000000,free_bytes:1000000000}};
if(command==='ota_apply'){window.autoRebootRequested=args.params.auto_reboot;return {status:'running'};}
@@ -122,6 +125,40 @@ async def check_drag_and_names(page):
assert await page.get_by_role('button',name='导出差异包').count()==0,'Replacing a release kept stale analysis'
async def check_release_indexes(page):
await page.goto(ORIGIN+'/diff.html')
await page.get_by_role('button',name='打开版本摘要目录').click()
assert await page.evaluate('window.indexOpened')==1
await drop_file(page,'old',['D:/Saved/上次更新.owrt-index.json'])
await drop_file(page,'new',['D:/Releases/new.zip'])
await page.get_by_role('button',name='分析差异').click()
await page.get_by_text('新版版本摘要已自动保存',exact=True).wait_for()
assert await page.evaluate('window.analyzeArgs.old')=='D:/Saved/上次更新.owrt-index.json'
assert '不代表设备已完成更新' in await page.locator('.ota-index').inner_text()
await page.set_viewport_size({'width':800,'height':650})
await page.get_by_role('button',name='导出版本摘要',exact=True).scroll_into_view_if_needed()
assert await page.evaluate('document.documentElement.scrollHeight<=innerHeight')
assert await page.evaluate('document.documentElement.scrollWidth<=innerWidth')
await page.get_by_role('button',name='Theme',exact=True).click()
await page.screenshot(path=str(Path(__file__).resolve().parents[2]/'work/diff-index-preview.png'),animations='disabled')
await page.set_viewport_size({'width':1120,'height':860})
await page.evaluate('window.cancelIndex=true')
await page.get_by_role('button',name='导出版本摘要',exact=True).click()
assert await page.evaluate('window.indexExport||null') is None
await page.evaluate('window.cancelIndex=false')
await page.get_by_role('button',name='导出版本摘要',exact=True).click()
await page.get_by_role('status').filter(has_text='版本摘要已导出').wait_for()
assert await page.evaluate('window.indexExport')=='D:/Saved/new.owrt-index.json'
await drop_file(page,'new',['D:/Saved/wrong.json'])
await page.get_by_role('alert').filter(has_text='新版必须选择完整 ZIP').wait_for()
assert 'new.zip' in await page.locator('[data-ota-drop="new"]').inner_text()
await page.get_by_role('button',name='English',exact=True).click()
assert 'New version index saved automatically' in await page.locator('.ota-index').inner_text()
await page.get_by_role('button',name='中文',exact=True).click()
await drop_file(page,'new',['D:/Releases/replacement.zip'])
await page.locator('.ota-index').wait_for(state='detached')
async def main():
async with async_playwright() as p:
browser=await p.chromium.launch(headless=True)
@@ -129,11 +166,11 @@ async def main():
await page.add_init_script(BRIDGE)
errors=[]
page.on('pageerror',lambda e:errors.append(str(e)))
await check_release_indexes(page)
await check_drag_and_names(page)
await page.goto(ORIGIN+'/diff.html')
await check_footer_spacing(page)
choices=page.get_by_role('button',name='选择 ZIP 文件')
await choices.nth(0).click();await choices.nth(0).click()
await page.locator('[data-ota-drop="old"]').click();await page.locator('[data-ota-drop="new"]').click()
await page.get_by_role('button',name='分析差异').click()
await page.get_by_role('button',name='导出差异包').wait_for()
await page.get_by_role('button',name='导出差异包').click()
@@ -0,0 +1,24 @@
"""Compile and execute the actual native path resolver without Tauri/WebView."""
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
class DistributionPathTest(unittest.TestCase):
@unittest.skipUnless(shutil.which('rustc'), 'Rust compiler required for native resolver tests')
def test_native_resolver(self):
source = Path(__file__).resolve().parents[1]/'ui/src-tauri/src/distribution.rs'
with tempfile.TemporaryDirectory() as folder:
binary = Path(folder)/'distribution-tests.exe'
compiled = subprocess.run(['rustc', '--edition=2021', '--test', str(source), '-o', str(binary)],
capture_output=True, text=True, encoding='utf-8')
self.assertEqual(compiled.returncode, 0, compiled.stdout+compiled.stderr)
result = subprocess.run([str(binary)], capture_output=True, text=True, encoding='utf-8')
self.assertEqual(result.returncode, 0, result.stdout+result.stderr)
self.assertIn('0 failed', result.stdout)
if __name__ == '__main__':
unittest.main()
+59
View File
@@ -0,0 +1,59 @@
"""Exercise the compatible Android preflight without transports or device writes."""
from contextlib import redirect_stdout, redirect_stderr
import importlib.util
import io
from pathlib import Path
import sys
import unittest
from unittest.mock import patch
SOURCE=Path(__file__).resolve().parents[2]/'openwrt/bundle/flash.py'
@unittest.skipUnless(SOURCE.is_file(), 'E5 compatible CLI source is tested in the E5 repository')
class E5BootState(unittest.TestCase):
def setUp(self):
spec=importlib.util.spec_from_file_location('e5_boot_state_fixture',SOURCE)
self.flash=importlib.util.module_from_spec(spec)
spec.loader.exec_module(self.flash)
def check(self, profile, model, board, slot, reported_model=None, uid='0'):
values={'id -u':uid, 'getprop ro.product.model':reported_model or model,
'getprop ro.product.device':board, 'getprop ro.boot.slot_suffix':slot}
def shell(command):
if command.endswith(' -c id'):return 'uid=2000(shell)'
# Any attempt to query the old BL gate is a test failure.
self.assertIn(command,values,command)
return values[command]
with patch.multiple(self.flash,SERIAL='fixture',GUI=None), \
patch.object(self.flash,'adb',return_value='List of devices attached\nfixture\tdevice\n'), \
patch.object(self.flash,'sh',side_effect=shell), \
patch.object(self.flash,'package_profile',return_value={'profile':profile,'android_models':[model]}), \
patch.object(self.flash,'su',return_value='ok') as root, \
patch.object(self.flash,'android_tools') as tools, redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
try:self.flash.android_checks()
except SystemExit:
tools.assert_not_called();root.assert_not_called()
raise
self.assertEqual(self.flash.current_slots(),(slot[1:],'b' if slot=='_a' else 'a'))
self.assertIn('boot_'+self.flash.LINUX_SLOT,root.call_args.args[0])
self.assertIn('l_agdsp_'+self.flash.ANDROID_SLOT,root.call_args.args[0])
tools.assert_called_once()
def test_all_profiles_check_root_and_slots_without_a_bl_requirement(self):
profiles=[('e5','E5','fixture'),('m8','M8','fixture'),('t551m','T551M','fixture'),
('t512n','T512N','fixture'),('yuanhang41s','ZTE 7546N','P720S11'),('k1','angelcare K1','ums9157_2h10')]
for profile,model,board in profiles:
for slot in ('_a','_b'):
with self.subTest(profile=profile,slot=slot):self.check(profile,model,board,slot)
def test_missing_root_wrong_model_board_or_slot_still_stop_before_tool_upload(self):
cases=[dict(uid='2000'),dict(reported_model='wrong-model'),dict(slot=''),dict(slot='_c')]
for change in cases:
args=dict(profile='e5',model='E5',board='fixture',slot='_a');args.update(change)
with self.subTest(change=change),self.assertRaises(SystemExit):self.check(**args)
for profile,model in [('k1','angelcare K1'),('yuanhang41s','ZTE 7546N')]:
with self.subTest(profile=profile),self.assertRaises(SystemExit):self.check(profile,model,'wrong-board','_a')
if __name__=='__main__':unittest.main()
+28
View File
@@ -71,6 +71,34 @@ class MethodRouting(unittest.TestCase):
self.assertNotIn('tf_bytes',device)
if method=='boot':a.read_gpt.assert_not_called()
def test_e5_boot_state_does_not_gate_rooted_installations(self):
profiles=[('e5','E5','fixture'),('m8','M8','fixture'),('t551m','T551M','fixture'),
('t512n','T512N','fixture'),('yuanhang41s','ZTE 7546N','P720S11'),('k1','angelcare K1','ums9157_2h10')]
for profile,model,board in profiles:
for state in ('orange','green','yellow','red','',None):
for method in ('part','reinstall','image','boot'):
with self.subTest(profile=profile,state=state,method=method):
a=self.adapter()
properties=a.adb.properties()
properties.update({'ro.product.model':model,'ro.product.device':board})
if state is None:properties.pop('ro.boot.verifiedbootstate')
else:properties['ro.boot.verifiedbootstate']=state
a.adb.properties=Mock(return_value=properties)
a.legacy.package_profile.return_value={'profile':profile,'android_models':[model]}
result=a.probe(SERIAL,method)
self.assertEqual(result['profile'],profile)
self.assertTrue(result['root'])
def test_e5_without_bl_gate_still_requires_root_model_and_slot(self):
a=self.adapter();a.adb.root_status=Mock(return_value='root_permission')
self.assertFalse(a.probe(SERIAL,'part')['root'])
a.read_gpt.assert_not_called()
for field,value,error in [('ro.product.model','wrong-model','model differs'),('ro.boot.slot_suffix','','slot')]:
a=self.adapter();properties=a.adb.properties();properties[field]=value
a.adb.properties=Mock(return_value=properties)
with self.subTest(field=field),self.assertRaisesRegex(ValueError,error):a.probe(SERIAL,'part')
a.read_gpt.assert_not_called()
def test_reinstall_plan_on_device_without_card(self):
for kind in ('e5','mu300'):
with self.subTest(kind=kind), tempfile.TemporaryDirectory() as directory:
+9 -2
View File
@@ -31,7 +31,7 @@ class Ext4Tests(unittest.TestCase):
(repo/'work').mkdir(exist_ok=True)
with tempfile.TemporaryDirectory(prefix='ota-test-',dir=repo/'work') as d:
d=Path(d)
for i in (1,2):
for i in (1,2,3):
release=d/str(i);source=release/'root';(source/'usr/lib').mkdir(parents=True)
(source/'etc/config').mkdir(parents=True)
(source/'usr/lib/example').write_bytes(('version '+str(i)).encode())
@@ -52,12 +52,19 @@ class Ext4Tests(unittest.TestCase):
(files/'device-profile.json').write_text(json.dumps({'profile':'e5'}))
(files/'RELEASE.json').write_text(json.dumps(dict(profile='e5',image_version='e5-r'+str(i),kernel_release='6.18.54-e5-test',openwrt='25.12.5')))
(files/'SHA256SUMS').write_text(''.join(hashlib.sha256((files/n).read_bytes()).hexdigest()+' files/'+n+'\n' for n in ('boot.img','openwrt.ext4.gz')))
out=d/'patch.ota';result=analyze(d/'1',d/'2',out)
out=d/'patch.ota';result=analyze(d/'1',d/'2',out,index_directory=d/'indexes')
self.assertTrue(result['can_export'],result['blockers'])
self.assertEqual([o['path'] for o in result['manifest']['operations']],['usr/lib/example'])
with Patch(out) as patch:
h=result['manifest']['operations'][0]['after']['sha256']
self.assertEqual(patch.archive.read('blobs/'+h),b'version 2')
expected=analyze(d/'2',d/'3')
shutil.rmtree(d/'2')
from_index=analyze(result['index_path'],d/'3',d/'from-index.ota')
self.assertEqual(from_index['manifest'],expected['manifest'])
with Patch(d/'from-index.ota') as patch:
h=from_index['manifest']['operations'][0]['after']['sha256']
self.assertEqual(patch.archive.read('blobs/'+h),b'version 3')
self.assertFalse(any(p.name.startswith('tmp') for p in d.rglob('*')))
+95
View File
@@ -0,0 +1,95 @@
"""Actual package verification through macOS/Finder-style directory selections."""
import hashlib
import json
from pathlib import Path
import tempfile
import unittest
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from backend.package import inspect_package, locate_package
class PackagePathTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.base = Path(self.temp.name)
def package(self, name, family):
root = self.base/name
root.mkdir(parents=True)
(root/'OpenWrt-Installer.py').write_text('# fixture', encoding='utf-8')
(root/'OpenWrt-Installer.app/Contents/MacOS').mkdir(parents=True)
if family == 'e5':
(root/'files').mkdir()
(root/'files/device-profile.json').write_text(json.dumps({'profile': 'e5'}))
payloads = ['files/boot.img', 'files/openwrt.ext4.gz', 'files/ext4-tools.tar']
else:
(root/'desktop').mkdir()
payloads = ['boot-linux.img', 'mu300-openwrt.tar.gz', 'busybox', 'rootfs-critical.sha256', 'rootfs.requirements']
checks = {}
for name in payloads:
data = ('fixture '+name).encode()
(root/name).write_bytes(data)
checks[name] = hashlib.sha256(data).hexdigest()
if family == 'e5':
(root/'files/SHA256SUMS').write_text(''.join(f'{h} {name}\n' for name, h in checks.items()))
else:
(root/'desktop/manifest.json').write_text(json.dumps({'kernel': '7.2', 'magisk': checks, 'desktop': {}}))
return root
def test_actual_hash_verification_from_app_payload_and_wrapper(self):
for family, subdir in [('e5', 'files'), ('mu300', 'desktop')]:
root = self.package('下载 安装包 '+family+'/release', family)
expected = inspect_package(root)
for selection in [root.parent, root/'OpenWrt-Installer.app', root/'OpenWrt-Installer.app/Contents/MacOS', root/subdir]:
with self.subTest(selection=str(selection)):
self.assertEqual(inspect_package(selection), expected)
def test_two_releases_require_explicit_selection(self):
root = self.package('downloads/first', 'mu300')
self.package('downloads/second', 'e5')
with self.assertRaisesRegex(ValueError, 'Multiple'):
inspect_package(root.parent)
self.assertEqual(inspect_package(root)['adapter'], 'mu300')
def test_corruption_is_not_hidden_by_path_normalization(self):
root = self.package('release', 'e5')
(root/'files/boot.img').write_bytes(b'corrupt')
with self.assertRaisesRegex(ValueError, 'checksum mismatch'):
inspect_package(root/'OpenWrt-Installer.app')
def test_incomplete_root_never_switches_to_nested_release(self):
root = self.package('release', 'e5')
(root/'files/boot.img').unlink()
self.package('release/other', 'mu300')
with self.assertRaisesRegex(ValueError, 'Missing or unsafe package file'):
inspect_package(root)
def test_zip_missing_and_app_only_are_actionable_errors(self):
archive = self.base/'package.zip'
archive.write_bytes(b'fixture')
for path in [archive, self.base/'missing']:
with self.assertRaisesRegex(ValueError, 'fully extracted'):
inspect_package(path)
app = self.base/'AppTranslocation/random/d/OpenWrt-Installer.app'
(app/'Contents/MacOS').mkdir(parents=True)
self.package('Downloads/unrelated', 'mu300')
with self.assertRaisesRegex(ValueError, 'No extracted'):
inspect_package(app)
def test_release_folder_can_itself_be_named_files(self):
root = self.package('files', 'e5')
self.assertEqual(locate_package(root), root.resolve())
@unittest.skipIf(sys.platform == 'win32', 'POSIX symlink fixture')
def test_macos_directory_alias(self):
root = self.package('下载 安装包', 'mu300')
alias = self.base/'alias'
alias.symlink_to(root, target_is_directory=True)
self.assertEqual(inspect_package(alias), inspect_package(root))
if __name__ == '__main__':
unittest.main()
+187
View File
@@ -0,0 +1,187 @@
"""Portable baselines and real patch exports using disposable releases only."""
import copy
import hashlib
import json
import io
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
from types import SimpleNamespace
import unittest
from unittest.mock import patch
import zipfile
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from backend.ota_package import Release, analyze
from backend.ota_desktop import Desktop
from backend.ota_engine import canonical, Patch, Engine
from backend.release_index import FORMAT, read_index, load_index, save_index, snapshot, write_index
from backend.service import Service
from backend.state import Store
from test_ota import mu_release, file
class ReleaseIndexTest(unittest.TestCase):
def setUp(self):
self.temp=tempfile.TemporaryDirectory();self.addCleanup(self.temp.cleanup)
self.root=Path(self.temp.name)
self.cache=self.root/'app/release-indexes'
def releases(self):
for version in range(1,4):
mu_release(self.root/str(version),'mu300-r'+str(version),
{'usr/lib/test':str(version).encode(),
'lib/apk/db/installed':b'P:base\nV:1.0\nA:aarch64\nD:libc\n\n'},boot=('boot'+str(version)).encode())
return [self.root/str(v) for v in range(1,4)]
def test_old_package_can_be_deleted_and_result_matches_full_release(self):
a,b,c=self.releases()
result=analyze(a,b,index_directory=self.cache)
index=Path(result['index_path'])
expected=analyze(b,c,self.root/'full.ota')
shutil.rmtree(a);shutil.rmtree(b)
actual=analyze(index,c,self.root/'indexed.ota',index_directory=self.cache)
self.assertEqual(actual['manifest'],expected['manifest'])
self.assertEqual(actual['payload_bytes'],expected['payload_bytes'])
with zipfile.ZipFile(self.root/'full.ota') as x,zipfile.ZipFile(self.root/'indexed.ota') as y:
self.assertEqual({n:x.read(n) for n in x.namelist()},{n:y.read(n) for n in y.namelist()})
with Patch(self.root/'indexed.ota'):pass
self.assertTrue(Path(actual['index_path']).is_file())
self.assertEqual(len(list(self.cache.glob('*.json'))),2)
self.assertEqual(load_index(index).packages['base']['V'],'1.0')
def test_cache_is_deduplicated_and_indexes_can_move(self):
a,b,c=self.releases()
first=analyze(a,b,index_directory=self.cache)['index_path']
again=analyze(a,b,index_directory=self.cache)['index_path']
self.assertEqual(first,again)
self.assertEqual(len(list(self.cache.iterdir())),1)
moved=self.root/'移动 目录/renamed.json'
moved.parent.mkdir();shutil.move(first,moved)
self.assertTrue(analyze(moved,c)['can_export'])
def test_index_contains_effective_updater_overlay_and_no_file_contents(self):
a,b,_=self.releases()
desc=file(b'new generated engine')
def runtime(release):
return {'usr/bin/python3':file(b'python'),'ota/engine.py':desc,
**{'ota/'+name:file(name.encode()) for name in ('boot.py','rpc.py','proxy.sh','unisoc-ota.js','errors.js','unisoc-ota.json')}},file(b'busybox'),{}
# No device/bootstrap execution: retain the real compare() overlay, while
# skipping runtime manifest checks irrelevant to this synthetic fixture.
with patch('backend.ota_runtime.build',side_effect=runtime),patch('backend.ota_runtime.bootstrap',return_value=b'bootstrap'),patch('backend.ota_package.validate_manifest'):
result=analyze(a,b,index_directory=self.cache)
saved=load_index(result['index_path'])
self.assertEqual(saved.entries['usr/lib/unisoc-ota/engine.py'],desc)
self.assertNotIn(b'new generated engine',Path(result['index_path']).read_bytes())
self.assertEqual(saved.boot_digest,hashlib.sha256(b'boot2').hexdigest())
def test_descriptors_roundtrip_permissions_links_xattrs_and_e5_identity(self):
release=SimpleNamespace(family='e5',meta={'profile':'k1','image_version':'k1-r1','kernel_release':'6.18.54-k1','openwrt':'25.12.5'},
entries={'usr/lib/file':dict(file(),mode=0o4755,xattrs={'user.test':'eA=='}),
'usr/lib/link':dict(kind='symlink',mode=0o777,uid=0,gid=0,target='file',xattrs={}),
'usr/lib':dict(kind='dir',mode=0o755,uid=0,gid=0,xattrs={})},packages={},boot_digest='a'*64)
index=save_index(release,self.cache)
loaded=load_index(index)
self.assertEqual(loaded.entries,release.entries)
self.assertEqual(loaded.family,'e5')
def test_corrupt_unknown_duplicate_and_unsafe_indexes_are_rejected(self):
a,b,_=self.releases();index=analyze(a,b,index_directory=self.cache)['index_path']
original=read_index(index)
for field,value in [('format','unknown'),('version',2),('sha256','0'*64)]:
bad=copy.deepcopy(original);bad[field]=value
path=self.root/'bad.json';path.write_bytes(canonical(bad))
with self.subTest(field=field),self.assertRaises(ValueError):load_index(path)
for name,desc in [('../etc/shadow',file()),('usr/lib/a',dict(file(),mode=999999)),('usr/lib/b',dict(file(),sha256='bad'))]:
bad=copy.deepcopy(original);bad['release']['entries'][name]=desc
bad['sha256']=hashlib.sha256(canonical(bad['release'])).hexdigest()
path.write_bytes(canonical(bad))
with self.subTest(name=name),self.assertRaises(ValueError):load_index(path)
path.write_bytes(b'{"format":"x","format":"y"}')
with self.assertRaisesRegex(ValueError,'Duplicate'):load_index(path)
path.write_bytes(b'{"truncated"')
with self.assertRaises(ValueError):load_index(path)
def test_failed_analysis_does_not_create_an_index_or_retain_export(self):
a,b,c=self.releases();desktop=Desktop(self.root,lambda *_:None,self.root/'app')
result=desktop.dispatch('ota_analyze',{'old':str(a),'new':str(b)})
export=self.root/'export.json'
self.assertEqual(desktop.dispatch('ota_export_index',{'output':str(export)})['path'],str(export))
self.assertEqual(read_index(export),read_index(result['index_path']))
with self.assertRaisesRegex(ValueError,'already exists'):desktop.dispatch('ota_export_index',{'output':str(export)})
meta=c/'desktop/release.json';data=json.loads(meta.read_text());data['profile']='other';meta.write_text(json.dumps(data))
with self.assertRaisesRegex(ValueError,'Incompatible'):desktop.dispatch('ota_analyze',{'old':str(b),'new':str(c)})
with self.assertRaisesRegex(ValueError,'Analyze'):desktop.dispatch('ota_export_index',{'output':str(self.root/'wrong.json')})
self.assertEqual(len(list(self.cache.glob('*.json'))),1)
def test_atomic_failure_leaves_no_partial_cache(self):
a,b,_=self.releases()
with Release(b) as release:data=snapshot(release)
with patch('backend.release_index.os.replace',side_effect=OSError('simulated disk error')):
with self.assertRaises(OSError):write_index(self.cache/'new.json',data)
self.assertEqual(list(self.cache.iterdir()),[])
def test_service_reopens_with_saved_index_under_its_own_app_data(self):
a,b,c=self.releases()
store=Store(self.root/'service-state')
service=Service(self.root,store,io.StringIO())
result=service.dispatch({'protocol':1,'command':'ota_analyze','params':{'old':str(a),'new':str(b)}})
self.assertEqual(Path(result['index_path']).parent,store.base/'release-indexes')
shutil.rmtree(a);shutil.rmtree(b)
reopened=Service(self.root,store,io.StringIO())
result=reopened.dispatch({'protocol':1,'command':'ota_analyze','params':{'old':result['index_path'],'new':str(c)}})
self.assertEqual(read_index(result['index_path'])['release']['meta']['image_version'],'mu300-r3')
def test_portable_cli_saves_index_and_generates_without_old_package(self):
a,b,c=self.releases()
tool=Path(__file__).resolve().parents[1]/'ota-tool.py'
env=dict(os.environ,LOCALAPPDATA=str(self.root/'cache'),HOME=str(self.root/'home'))
result=subprocess.run([sys.executable,str(tool),'analyze',str(a),str(b)],env=env,capture_output=True,text=True,encoding='utf-8',check=True)
index=Path(json.loads(result.stdout)['index_path'])
self.assertTrue(index.is_relative_to(self.root))
shutil.rmtree(a);shutil.rmtree(b)
output=self.root/'cli.ota'
subprocess.run([sys.executable,str(tool),'generate',str(index),str(c),str(output)],env=env,capture_output=True,check=True)
with Patch(output) as patch:self.assertEqual(patch.manifest['target_version'],'mu300-r3')
def test_index_cannot_replace_the_new_payload_and_blocked_analysis_saves_nothing(self):
a,b,_=self.releases()
result=analyze(a,b,index_directory=self.cache)
with self.assertRaisesRegex(ValueError,'new release must be a full package'):
analyze(a,result['index_path'])
empty=self.root/'blocked-cache'
result=analyze(b,b,index_directory=empty)
self.assertFalse(result['can_export'])
self.assertFalse(empty.exists())
@unittest.skipUnless(sys.platform=='linux','Real engine permissions/locking require Linux; temporary files only')
def test_two_real_patch_transactions_with_injected_runtime_use_saved_target(self):
device=self.root/'device';device.mkdir()
for version in range(1,4):
meta=dict(profile='mu300',image_version='mu300-r'+str(version),kernel_release='7.2.8',openwrt='25.12.5')
files={'usr/lib/test':str(version).encode(),'usr/bin/python3':b'interpreter fixture',
'etc/mu300/release.json':canonical(meta)}
release=self.root/str(version)
mu_release(release,meta['image_version'],files,boot=b'same boot')
(release/'payload/busybox').write_bytes(b'busybox fixture, never executed')
if version==1:
for directory in ('usr','usr/lib','usr/bin','etc','etc/config','etc/mu300',
'usr/share/rpcd/acl.d','www/luci-static/resources/view/system',
'www/luci-static/resources/unisoc-ota'):
(device/directory).mkdir(parents=True,exist_ok=True)
for name,data in files.items():(device/name).write_bytes(data)
first=analyze(self.root/'1',self.root/'2',self.root/'one.ota',index_directory=self.cache)
engine=Engine(device)
with Patch(self.root/'one.ota') as p:self.assertEqual(engine.apply(p)['status'],'complete')
shutil.rmtree(self.root/'2')
second=analyze(first['index_path'],self.root/'3',self.root/'two.ota',index_directory=self.cache)
self.assertNotIn('usr/lib/unisoc-ota/engine.py',[o['path'] for o in second['manifest']['operations']])
with Patch(self.root/'two.ota') as p:self.assertEqual(engine.apply(p)['status'],'complete')
self.assertEqual(engine.identity()['version'],'mu300-r3')
self.assertEqual((device/'usr/lib/test').read_bytes(),b'3')
if __name__=='__main__':unittest.main()
+184
View File
@@ -0,0 +1,184 @@
//! Portable package discovery. No CWD search, downloads or device access.
use std::path::{Path, PathBuf};
pub fn app_bundle(path: &Path) -> Option<&Path> {
path.ancestors().find(|p| p.extension().and_then(|ext| ext.to_str()).is_some_and(|ext| ext.eq_ignore_ascii_case("app")))
}
fn has_entry(root: &Path) -> bool {
(root.join("OpenWrt-Installer.py").is_file()
&& (root.join("desktop/manifest.json").is_file()
|| root.join("files/device-profile.json").is_file()))
|| root.join("OpenWrt-Diff-Studio.py").is_file()
|| root.join("update.ota").is_file()
}
pub fn check_root(root: &Path, backend: &str) -> Result<PathBuf, String> {
if !has_entry(root) {
return Err(format!("No extracted OpenWrt package here / 此目录没有完整解压的 OpenWrt 安装包:\n{}\nSelect the folder containing the app, tools and package files.\n请选择同时包含 APP、tools 和安装文件的目录。", root.display()));
}
let runtime = root.join(backend);
if !runtime.is_file() {
return Err(format!("Package backend is missing / 安装包缺少后端:\n{}\nExtract the entire archive again; copying only the APP is insufficient.\n请重新完整解压安装包,不能只复制 APP。", runtime.display()));
}
root.canonicalize().map_err(|e| format!("Cannot access package / 无法访问安装包:\n{}\n{e}", root.display()))
}
pub fn selected_root(selected: &Path, backend: &str) -> Result<PathBuf, String> {
if has_entry(selected) {
return check_root(selected, backend);
}
// A user may select the APP, its Contents directory, or the payload folder.
let root = if let Some(app) = app_bundle(selected) {
app.parent().unwrap_or(selected)
} else if selected.file_name().is_some_and(|n| n == "files" || n == "desktop") {
selected.parent().unwrap_or(selected)
} else {
selected
};
// A damaged package must not silently switch to a different nested package.
if has_entry(root) {
return check_root(root, backend);
}
// Permit one archive wrapper only, and never choose between releases.
let mut candidates = Vec::new();
if let Ok(entries) = std::fs::read_dir(root) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() && has_entry(&path) {
candidates.push(path);
}
}
}
match candidates.len() {
1 => check_root(&candidates[0], backend),
0 => check_root(root, backend),
_ => Err("Multiple OpenWrt packages found. Select the exact release folder.\n此目录包含多个安装包,请明确选择其中一个安装包目录。".into()),
}
}
pub fn choose_root(
backend: &str,
mut pick: impl FnMut() -> Option<PathBuf>,
mut report: impl FnMut(&str),
) -> Option<PathBuf> {
while let Some(selected) = pick() {
match selected_root(&selected, backend) {
Ok(root) => return Some(root),
Err(message) => report(&message),
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
const BACKEND: &str = "tools/macos/backend/openwrt-backend";
static NEXT: AtomicUsize = AtomicUsize::new(0);
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
let root = std::env::temp_dir().join(format!("openwrt-path-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
std::fs::create_dir_all(&root).unwrap();
Self(root)
}
fn file(root: &Path, name: &str) {
let path = root.join(name);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, b"fixture").unwrap();
}
fn package(&self, name: &str, marker: &str) -> PathBuf {
let root = self.0.join(name);
for file in ["OpenWrt-Installer.py", marker, BACKEND, "OpenWrt-Installer.app/Contents/MacOS/openwrt-installer"] {
Self::file(&root, file);
}
root
}
}
impl Drop for Fixture {
fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); }
}
#[test]
fn e5_and_mu300_support_spaces_unicode_and_app_selection() {
let f = Fixture::new();
for marker in ["files/device-profile.json", "desktop/manifest.json"] {
let root = f.package(&format!("下载 固件 {}", marker.split('/').next().unwrap()), marker);
for selection in [root.clone(), root.join("OpenWrt-Installer.app"), root.join("OpenWrt-Installer.app/Contents/MacOS"), root.join(marker).parent().unwrap().to_path_buf()] {
assert_eq!(selected_root(&selection, BACKEND).unwrap(), root.canonicalize().unwrap());
}
}
}
#[test]
fn explicit_wrapper_selection_requires_one_package() {
let f = Fixture::new();
let root = f.package("release", "desktop/manifest.json");
assert_eq!(selected_root(&f.0, BACKEND).unwrap(), root.canonicalize().unwrap());
f.package("other", "files/device-profile.json");
assert!(selected_root(&f.0, BACKEND).unwrap_err().contains("Multiple"));
}
#[test]
fn incomplete_package_reports_the_actual_missing_backend() {
let f = Fixture::new();
let root = f.package("release", "desktop/manifest.json");
std::fs::remove_file(root.join(BACKEND)).unwrap();
f.package("release/nested", "desktop/manifest.json");
let message = selected_root(&root, BACKEND).unwrap_err();
assert!(message.contains(BACKEND));
assert!(message.contains("missing"));
}
#[test]
fn translocated_or_copied_app_never_searches_elsewhere() {
let f = Fixture::new();
let app = f.0.join("AppTranslocation/random/d/OpenWrt-Installer.app");
Fixture::file(&app, "Contents/MacOS/openwrt-installer");
let root = app.parent().unwrap();
assert!(check_root(root, BACKEND).is_err());
let original = f.package("Downloads/release", "desktop/manifest.json");
assert_eq!(selected_root(&original, BACKEND).unwrap(), original.canonicalize().unwrap());
}
#[test]
fn empty_and_unextracted_paths_fail() {
let f = Fixture::new();
assert!(selected_root(&f.0, BACKEND).is_err());
Fixture::file(&f.0, "release.zip");
assert!(selected_root(&f.0.join("release.zip"), BACKEND).is_err());
assert!(selected_root(&f.0.join("nonexistent"), BACKEND).is_err());
}
#[test]
fn studio_and_exported_updater_keep_their_layouts() {
let f = Fixture::new();
for marker in ["OpenWrt-Diff-Studio.py", "update.ota"] {
let root = f.0.join(marker.replace('.', "-"));
Fixture::file(&root, marker);
Fixture::file(&root, BACKEND);
assert_eq!(check_root(&root, BACKEND).unwrap(), root.canonicalize().unwrap());
}
}
#[test]
fn incorrect_selection_can_retry_and_cancel_is_not_an_error() {
let f = Fixture::new();
let root = f.package("release", "desktop/manifest.json");
let mut selections = [f.0.join("missing"), root.clone()].into_iter();
let mut errors = Vec::new();
let chosen = choose_root(BACKEND, || selections.next(), |e| errors.push(e.to_owned()));
assert_eq!(chosen.unwrap(), root.canonicalize().unwrap());
assert_eq!(errors.len(), 1);
assert!(choose_root(BACKEND, || None, |_| panic!("Cancel must not report an error")).is_none());
let mut selections = [f.0.join("missing")].into_iter();
let mut count = 0;
assert!(choose_root(BACKEND, || selections.next(), |_| count += 1).is_none());
assert_eq!(count, 1);
}
#[cfg(unix)]
#[test]
fn macos_directory_aliases_resolve_without_losing_unicode() {
let f = Fixture::new();
let root = f.package("下载 固件", "desktop/manifest.json");
let alias = f.0.join("alias");
std::os::unix::fs::symlink(&root, &alias).unwrap();
assert_eq!(selected_root(&alias, BACKEND).unwrap(), root.canonicalize().unwrap());
}
}
+50 -22
View File
@@ -1,12 +1,14 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod distribution;
use serde_json::{json, Value};
use std::{collections::HashMap, io::{BufRead, BufReader, Write}, path::PathBuf,
process::{ChildStdin, Command, Stdio}, sync::{Arc, Mutex, atomic::{AtomicBool, AtomicU64, Ordering}}};
use tauri::{Emitter, Manager, State};
use tokio::sync::oneshot;
const COMMANDS: &[&str] = &["hello","snapshot","list","package","devices","adb_connect","adb_disconnect","probe","probe_update","plan","start","resume","retry","cancel","can_close","export","import","diagnostics","verify_openwrt","ota_analyze","ota_export","ota_package","ota_probe","ota_apply","ota_status","ota_reboot"];
const COMMANDS: &[&str] = &["hello","snapshot","list","package","devices","adb_connect","adb_disconnect","probe","probe_update","plan","start","resume","retry","cancel","can_close","export","import","diagnostics","verify_openwrt","ota_analyze","ota_export","ota_export_index","ota_package","ota_probe","ota_apply","ota_status","ota_reboot"];
struct Bridge {
input: Mutex<Option<ChildStdin>>,
pending: Mutex<HashMap<u64, oneshot::Sender<Result<Value, String>>>>,
@@ -40,8 +42,27 @@ async fn pick_package() -> Option<String> {
tauri::async_runtime::spawn_blocking(|| rfd::FileDialog::new().set_title("OpenWrt package / 安装包目录").pick_folder().map(|p|p.to_string_lossy().to_string())).await.ok().flatten()
}
#[tauri::command]
async fn pick_ota_input() -> Option<String> {
tauri::async_runtime::spawn_blocking(|| rfd::FileDialog::new().set_title("Select release ZIP or OTA / 选择发行包或差异包").add_filter("OpenWrt packages", &["zip","ota"]).pick_file().map(|p|p.to_string_lossy().to_string())).await.ok().flatten()
async fn pick_ota_input(kind: Option<String>) -> Option<String> {
tauri::async_runtime::spawn_blocking(move || {
let dialog = rfd::FileDialog::new().set_title("Select OpenWrt package / 选择安装包或版本摘要");
let dialog = if kind.as_deref() == Some("old") {
let dialog = dialog.add_filter("Release ZIP or version index / 发行包或版本摘要", &["zip","json"]);
let directory = data_directory().join("release-indexes");
if directory.is_dir() { dialog.set_directory(directory) } else { dialog }
} else { dialog.add_filter("OpenWrt packages", &["zip","ota"]) };
dialog.pick_file().map(|p|p.to_string_lossy().to_string())
}).await.ok().flatten()
}
#[tauri::command]
async fn save_index() -> Option<String> {
tauri::async_runtime::spawn_blocking(|| rfd::FileDialog::new().set_file_name("OpenWrt-Version.owrt-index.json")
.add_filter("OpenWrt version index", &["json"]).save_file().map(|p|p.to_string_lossy().to_string())).await.ok().flatten()
}
#[tauri::command]
fn open_index_data() -> Result<(), String> {
let directory = data_directory().join("release-indexes");
std::fs::create_dir_all(&directory).map_err(|e|e.to_string())?;
open_native(&directory)
}
#[tauri::command]
async fn save_ota(suggested_name: Option<String>, release_path: Option<String>) -> Option<String> {
@@ -116,29 +137,34 @@ fn data_directory() -> PathBuf {
return std::env::var_os("LOCALAPPDATA").map(PathBuf::from).unwrap_or_else(std::env::temp_dir).join("OpenWrt-Installer");
}
fn distribution_root(executable: &std::path::Path) -> Result<PathBuf, String> {
fn distribution_root(executable: &std::path::Path) -> Result<Option<PathBuf>, String> {
#[cfg(target_os = "macos")]
for ancestor in executable.ancestors() {
if ancestor.extension().is_some_and(|ext| ext == "app") {
let root = ancestor.parent().ok_or("Application has no parent directory")?;
if root.join("OpenWrt-Installer.py").is_file()
&& (root.join("desktop/manifest.json").is_file() || root.join("files/device-profile.json").is_file())
|| root.join("OpenWrt-Diff-Studio.py").is_file() || root.join("update.ota").is_file() {
return Ok(root.to_path_buf());
}
// Finder may translocate quarantined applications. Ask for the
// extracted package rather than guessing its original location.
return rfd::FileDialog::new().set_title("Select extracted OpenWrt package / 选择完整解压的安装包")
.pick_folder().ok_or_else(|| "No package selected".into());
if let Some(app) = distribution::app_bundle(executable) {
let adjacent = app.parent().ok_or("Application has no parent directory")?;
let backend = "tools/macos/backend/openwrt-backend";
if let Ok(root) = distribution::check_root(adjacent, backend) {
return Ok(Some(root));
}
// Gatekeeper can run the APP from AppTranslocation without its sibling
// files. Only an explicit selection may choose another distribution.
rfd::MessageDialog::new().set_title("Locate OpenWrt package / 选择安装包")
.set_description("The app cannot access its adjacent package files. macOS may be running an isolated copy, or the app was moved. Select the fully extracted package folder containing tools and the installation files. Cancel closes the installer.\nAPP 无法访问相邻的安装文件,可能正由 macOS 隔离运行,或 APP 已被单独移动。请选择完整解压、包含 tools 和安装文件的目录;取消即可退出。")
.set_level(rfd::MessageLevel::Info).show();
return Ok(distribution::choose_root(backend,
|| rfd::FileDialog::new()
.set_title("Select extracted OpenWrt package / 选择完整解压的安装包")
.pick_folder(),
|message| { rfd::MessageDialog::new().set_title("Select package again / 请重新选择安装包")
.set_description(message).set_level(rfd::MessageLevel::Error).show(); },
));
}
executable.parent().map(|p|p.to_path_buf()).ok_or_else(|| "Executable has no directory".into())
executable.parent().map(|p|Some(p.to_path_buf())).ok_or_else(|| "Executable has no directory".into())
}
fn entry_page(executable: &std::path::Path, has_patch: bool) -> (&'static str, &'static str) {
// Exported macOS updaters retain the studio's internal executable name.
// Their enclosing app bundle is the public entry point instead.
let entry = executable.ancestors().find(|p| p.extension().is_some_and(|ext| ext == "app"))
let entry = distribution::app_bundle(executable)
.unwrap_or(executable).file_stem().unwrap_or_default().to_string_lossy().to_lowercase();
if entry.contains("updater") {
("ota.html", "OpenWrt Patch Updater")
@@ -163,14 +189,14 @@ fn configure_entry(config: &mut tauri::Config, executable: &std::path::Path, has
fn run() -> Result<(), Box<dyn std::error::Error>> {
let executable = std::env::current_exe()?;
let root = distribution_root(&executable).map_err(std::io::Error::other)?;
let Some(root) = distribution_root(&executable).map_err(std::io::Error::other)? else { return Ok(()); };
let mut context = tauri::generate_context!();
configure_entry(context.config_mut(), &executable, root.join("update.ota").is_file());
let directory = data_directory();
let bridge = Arc::new(Bridge {input:Mutex::new(None),pending:Mutex::new(HashMap::new()),sequence:AtomicU64::new(1),busy:AtomicBool::new(false),directory,export_log:Mutex::new(None)});
let setup_state = bridge.clone();
let app = tauri::Builder::default().manage(bridge.clone())
.invoke_handler(tauri::generate_handler![backend_request,pick_package,pick_ota_input,save_ota,pick_recovery,save_backup,save_log,write_log,open_data,open_repository])
.invoke_handler(tauri::generate_handler![backend_request,pick_package,pick_ota_input,save_ota,save_index,open_index_data,pick_recovery,save_backup,save_log,write_log,open_data,open_repository])
.setup(move |app| {
#[cfg(target_os = "macos")]
let backend = "tools/macos/backend/openwrt-backend";
@@ -178,6 +204,7 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
let backend = "tools/backend/openwrt-backend.exe";
let mut process = Command::new(root.join(backend));
process.args(["--package-root", &root.to_string_lossy(), "--data-dir", &setup_state.directory.to_string_lossy()]);
process.current_dir(&root);
process.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null());
#[cfg(windows)] { use std::os::windows::process::CommandExt; process.creation_flags(0x08000000); }
match process.spawn() {
@@ -214,8 +241,9 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
let _ = child.wait();
});
}
Err(_) => {
rfd::MessageDialog::new().set_title("OpenWrt Installer").set_description("Backend is missing. Extract the complete package, including tools/backend.\n后端缺失,请完整解压安装包(含 tools/backend 目录)。").set_level(rfd::MessageLevel::Error).show();
Err(error) => {
let message = format!("Cannot start the installer backend / 无法启动安装器后端:\n{}\n\n{error}\n\nKeep the complete extracted package together. Check the file exists and is allowed to run.\n请保留完整解压目录,并确认该文件存在且允许运行。", root.join(backend).display());
rfd::MessageDialog::new().set_title("OpenWrt Installer").set_description(&message).set_level(rfd::MessageLevel::Error).show();
}
}
Ok(())
+4 -2
View File
@@ -36,7 +36,8 @@ export const strings = {
copied:'日志已复制', exportedLog:'日志已导出', exportedBackup:'事务与备份已导出', imported:'恢复记录已导入', openedData:'事务目录已打开', inspected:'设备检查完成', refreshed:'设备列表已刷新', noDevices:'未发现设备,请连接 USB 并开启调试。', multipleDevices:'检测到多台设备,请明确选择本次操作的设备。', pauseRequested:'已请求暂停,将在安全边界生效。', dismiss:'关闭提示', notifications:'操作通知', deviceStates:{device:'已连接',unauthorized:'等待调试授权',offline:'离线'},
title:'OpenWrt 安装器', subtitle:'安装、更新与恢复', home:'开始', package:'安装包', choosePackage:'选择安装包目录', verify:'校验安装包', verified:'校验通过',
device:'设备', refresh:'刷新设备', select:'请选择设备', connect:'通过 USB 连接设备,开启调试并允许电脑访问。', inspect:'检查设备',
install:'安装 OpenWrt', installDesc:'选择 TF 卡或独立内置分区,逐步完成安装。', update:'更新 OpenWrt', updateDesc:'保留设置、已有容量和本机固件。',
install:'安装 OpenWrt', installDesc:'选择 TF 卡或独立内置分区,逐步完成安装。', update:'更新 OpenWrt', updateDesc:'仅限相同内核和 OpenWrt 系统版本,保留设置、已有容量和本机固件。',
updateCompatibilityTitle:'更新前请确认版本一致', updateCompatibilityWarning:'不支持跨内核、跨 OpenWrt 系统版本升级。请确认设备当前运行的内核和 OpenWrt 系统版本与安装包一致;如需更换,请先备份重要数据,再重新安装。',
resume:'继续未完成的安装', resumeDesc:'从电脑上的安装记录继续,也可用于 Android 重置后续装。', boot:'临时启动已安装的 OpenWrt', bootDesc:'仅本次启动进入 OpenWrt,不改变默认启动设置。',
advanced:'高级选项', advancedDesc:'重装或卸载内置 OpenWrt,或使用实验性 userdata 镜像。', tf:'TF 卡', part:'独立内置分区', reinstall:'重装已有内置分区', image:'userdata 镜像',
experimental:'实验性功能:可能损坏 Android F2FS 文件系统。', size:'OpenWrt 分配容量(GiB)', grow:'使用全部已分配的 OpenWrt 分区容量', growHelp:'扩满所选分区。分配大小由上方容量决定。',
@@ -103,7 +104,8 @@ export const strings = {
copied:'Log copied', exportedLog:'Log exported', exportedBackup:'Transaction and backups exported', imported:'Recovery record imported', openedData:'Transaction folder opened', inspected:'Device inspection complete', refreshed:'Device list refreshed', noDevices:'No devices found. Connect USB and enable debugging.', multipleDevices:'Multiple devices found. Select the device for this operation.', pauseRequested:'Pause requested. It will take effect at a safe boundary.', dismiss:'Dismiss notification', notifications:'Operation notifications', deviceStates:{device:'Connected',unauthorized:'Awaiting debugging authorization',offline:'Offline'},
title:'OpenWrt Installer',subtitle:'Install, update and recover',home:'Start',package:'Package',choosePackage:'Choose package folder',verify:'Verify package',verified:'Verified',
device:'Device',refresh:'Refresh devices',select:'Select a device',connect:'Connect by USB, enable debugging and authorize this computer.',inspect:'Inspect device',
install:'Install OpenWrt',installDesc:'Install step by step on a TF card or an independent internal partition.',update:'Update OpenWrt',updateDesc:'Keep settings, existing capacity and device firmware.',
install:'Install OpenWrt',installDesc:'Install step by step on a TF card or an independent internal partition.',update:'Update OpenWrt',updateDesc:'For matching kernel and OpenWrt versions only. Keep settings, existing capacity and device firmware.',
updateCompatibilityTitle:'Check versions before updating',updateCompatibilityWarning:'Updates across kernels or OpenWrt system versions are not supported. Confirm that the running kernel and OpenWrt system version match this package. To change either, back up important data and reinstall.',
resume:'Continue an unfinished installation',resumeDesc:'Continue from a saved installation record, including after an Android reset.',boot:'Boot installed OpenWrt once',bootDesc:'Start OpenWrt for this boot without changing the default system.',
advanced:'Advanced options',advancedDesc:'Reinstall or remove internal OpenWrt, or use an experimental userdata image.',tf:'TF card',part:'Independent internal partition',reinstall:'Reinstall internal partition',image:'Userdata image',
experimental:'Experimental: may damage the Android F2FS filesystem.',size:'OpenWrt allocation (GiB)',grow:'Use all capacity allocated to the OpenWrt partition',growHelp:'Grow to fill the selected partition. The allocation above controls its size.',
+1
View File
@@ -334,6 +334,7 @@ function App() {
<div className="purpose-list scroll-area">{purposes.map(({id, icon:Icon, title, description}, index) => <m.button initial={{opacity:0,y:reduceMotion ? 0 : 6}} animate={{opacity:1,y:0}} transition={{delay:reduceMotion ? 0 : index*0.025,duration:0.18}} whileHover={reduceMotion ? undefined : {x:3}} whileTap={reduceMotion ? undefined : {scale:0.992}} key={id} disabled={busy} onClick={() => navigate(id)} className="purpose"><div className="purpose-icon"><Icon size={21}/></div><div><h2>{title}</h2><p>{description}</p></div><ArrowRight size={18}/></m.button>)}</div>
</>}
{['install','update','boot','advanced'].includes(view) && <><h1 tabIndex={-1}>{purposes.find(p => p.id === view)?.title}</h1><p className="intro">{purposes.find(p => p.id === view)?.description}</p>
{view === 'update' && <div className="alert" role="note"><CircleAlert size={20}/><div><strong>{t.updateCompatibilityTitle}</strong><p>{t.updateCompatibilityWarning}</p></div></div>}
<div className="page-scroll scroll-area"><section><div className="section-title"><h2>{t.package}</h2>{pkg && <span className="badge"><Check size={13}/>{t.verified}</span>}</div>
<div className="package-row"><div className="file-path" title={path}>{pkg?.release_version || pkg?.name || path || t.choosePackage}</div><Button variant="outline" disabled={busy} onClick={choosePackage}><FolderOpen size={16}/>{t.choosePackage}</Button><Button disabled={busy || !path} onClick={() => verify()}>{t.verify}</Button></div></section>
{view === 'update' ? <section><h2>{t.device}</h2><div className="form-grid"><label>{t.host}<input disabled={busy} value={host} onChange={e => setHost(e.target.value)} autoComplete="off"/></label><label>{t.password}<input disabled={busy} type="password" value={password} onChange={e => setPassword(e.target.value)} autoComplete="off"/></label></div><p className="device-hint">{t.existingLogin}</p><Button variant="outline" disabled={busy || !pkg} onClick={async () => {setDevice(undefined); const d = await task(() => request<Device>('probe_update', {host, password}), t.inspected); if (d) setDevice(d);}}>{t.checkUpdate}</Button></section> : <section><div className="section-title"><h2>{t.device}</h2><Button variant="ghost" disabled={busy} onClick={refresh}><RefreshCw size={15}/>{t.refresh}</Button></div><div className="device-select"><Smartphone size={18}/><select disabled={busy} aria-label={t.select} value={serial} onChange={e => {setSerial(e.target.value); setDevice(undefined);}}><option value="">{devicesLoaded && !devices.length ? t.noDevicesShort : t.select}</option>{devices.map(d => <option key={d.serial} value={d.serial}>{d.label} · {d.wireless ? d.serial : '••••'+d.serial.slice(-4)} · {t.deviceStates[d.state as keyof typeof t.deviceStates] || d.state}</option>)}</select><Button variant="outline" disabled={!serial || !pkg || busy} onClick={inspect}>{t.inspect}</Button></div>{devicesLoaded && !devices.length && <p className="device-hint" role="status">{t.noDevices}</p>}{!pkg && <p className="device-hint">{t.inspectNeedsPackage}</p>}{wirelessControls()}</section>}
+1
View File
@@ -2,5 +2,6 @@
.dark .ota-error{color:#ffb4ab}.ota-error,.ota-versions,.ota-files{-webkit-user-select:text;user-select:text}
.ota-picker.is-dragover:enabled{border-color:hsl(var(--primary));background:hsl(var(--primary)/.1);box-shadow:0 0 0 2px hsl(var(--primary)/.2)}
.ota-index{margin:18px 0;padding:14px;border:1px solid hsl(var(--border));border-radius:10px;font-size:12px}.ota-index p{margin:6px 0;color:hsl(var(--muted-foreground))}.ota-index code{display:block;overflow-wrap:anywhere;user-select:text;-webkit-user-select:text;margin:8px 0}.ota-index>div{display:flex;gap:8px;flex-wrap:wrap}
.ota-intro,.ota-notice{flex-shrink:0}.ota-notice{max-height:84px;overflow-y:auto}.ota-intro{margin-bottom:20px}@media(max-height:720px){.ota-main{padding-top:16px}.ota-intro h1{font-size:23px}.ota-intro p{font-size:12px;margin-top:8px}.ota-card{padding:16px}.ota-card h2{margin-bottom:14px}.ota-footer{margin-top:12px;padding:10px 0}}@media(max-width:680px){.ota-grid{grid-template-columns:1fr;grid-template-rows:repeat(2,minmax(0,1fr))}.ota-intro h1{font-size:21px}}
+10 -8
View File
@@ -11,7 +11,7 @@ import {explainError} from '../../../openwrt/luci-app-unisoc-ota/htdocs/luci-sta
interface Operation {path:string; before:unknown; after:unknown}
interface Manifest {family:string;profile:string;base_version:string;target_version:string;kernel_release:string;operations:Operation[];preserved:string[];boot?:{size:number};runtime?:unknown}
interface Analysis {manifest:Manifest;blockers:string[];can_export:boolean;payload_bytes:number;files:number;added:number;removed:number;output?:string;suggested_name?:string}
interface Analysis {manifest:Manifest;blockers:string[];can_export:boolean;payload_bytes:number;files:number;added:number;removed:number;output?:string;suggested_name?:string;index_path?:string}
interface Review {token:string;check:{applicable:boolean;conflicts:string[];package_conflicts:string[];required_bytes:number;free_bytes:number}}
interface Status {identity:{version:string};transaction?:{started:number;total:number;status?:string};job?:{status:string;result?:{error?:string}};reboot?:{status:string;error?:string};activation?:{status:string;error?:string}}
const size = (n:number) => n >= 1048576 ? (n / 1048576).toFixed(1) + ' MiB' : (n / 1024).toFixed(1) + ' KiB';
@@ -100,13 +100,13 @@ function Studio() {
finally {setBusy(false);}
}
async function pick(which:'old'|'new'|'patch') {
const path = await work(()=>native('pick_ota_input'));
const path = await work(()=>native('pick_ota_input',{kind:which}));
if (!path) return;
await selectInput(which,path);
}
async function selectInput(which:'old'|'new'|'patch',path:string) {
if(!(which==='patch'?/\.ota$/i:/\.zip$/i).test(path)) {
setError(which==='patch'?tr('请选择 .ota 差异包。','Select an .ota patch.'):tr('请选择完整 ZIP 发行包。','Select a full release ZIP.'));return;
if(!(which==='patch'?/\.ota$/i:which==='old'?/\.(zip|json)$/i:/\.zip$/i).test(path)) {
setError(which==='patch'?tr('请选择 .ota 差异包。','Select an .ota patch.'):which==='old'?tr('请选择旧版 ZIP 或版本摘要 JSON。','Select an old release ZIP or version index JSON.'):tr('新版必须选择完整 ZIP 发行包。','The new release must be a full ZIP.'));return;
}
setError('');
setReview(undefined);setAnalysis(undefined);setSuccess('');setRebootReady(false);
@@ -130,18 +130,20 @@ function Studio() {
return <div className="ota-shell">
<header><div className="brand"><div className="brand-icon">{generator?<GitCompareArrows size={24}/>:<PackageCheck size={24}/>}</div><div><strong>{generator?'OpenWrt Diff Studio':'OpenWrt Patch Updater'}</strong><small>{tr('保留数据 · 只更新变更文件','Keep your data · Update changed files')}</small></div></div>
<div className="preferences"><Button variant="ghost" disabled={blocked} onClick={()=>{setEn(!en);localStorage.setItem('language',en?'zh':'en');}}>{en?'中文':'English'}</Button><Button variant="ghost" onClick={()=>setDark(!dark)} aria-label="Theme">{dark?<Sun size={18}/>:<Moon size={18}/>}</Button></div></header>
<main className="ota-main"><div className="ota-intro"><span className="ota-eyebrow">{generator?'RELEASE TO PATCH':'DIFFERENTIAL SYSTEM UPDATE'}</span><h1>{generator?tr('把两版发行包,变成一次轻量更新','Two releases. One compact update.'):tr('更新系统,留下你的设置','Update the system. Keep your setup.')}</h1><p>{generator?tr('点击选择,或将旧版和新版完整 ZIP 分别拖入对应框。相同内容只保存一份。','Select or drop the old and new full ZIPs into their respective boxes. Identical content is stored once.'):tr('导入可信差异包,连接正在运行 OpenWrt 的设备,先检查再应用。','Import a trusted patch and connect to a running OpenWrt device. Review before applying.')}</p></div>
<main className="ota-main"><div className="ota-intro"><span className="ota-eyebrow">{generator?'RELEASE TO PATCH':'DIFFERENTIAL SYSTEM UPDATE'}</span><h1>{generator?tr('把两版发行包,变成一次轻量更新','Two releases. One compact update.'):tr('更新系统,留下你的设置','Update the system. Keep your setup.')}</h1><p>{generator?tr('旧版可选择完整 ZIP 或已保存的版本摘要,新版请选择完整 ZIP。分析成功后自动保存新版摘要。','Choose an old release ZIP or saved version index, and a new full ZIP. A new version index is saved automatically after successful analysis.'):tr('导入可信差异包,连接正在运行 OpenWrt 的设备,先检查再应用。','Import a trusted patch and connect to a running OpenWrt device. Review before applying.')}</p></div>
<div className="ota-grid"><section className="ota-card"><h2><span className="ota-number">1</span>{generator?tr('选择发行版本','Select releases'):tr('选择补丁与设备','Select patch and device')}</h2>
{generator?<><label className="ota-label">{tr('旧版完整包','Old full release')}</label><button className={'ota-picker'+(dropTarget==='old'?' is-dragover':'')} data-ota-drop="old" disabled={blocked} onClick={()=>void pick('old')}><FileArchive/><span>{old || tr('选择 ZIP 文件','Select ZIP file')}</span><FolderOpen size={18}/></button><div className="ota-arrow"><ArrowRight size={18}/></div><label className="ota-label">{tr('新版完整包','New full release')}</label><button className={'ota-picker'+(dropTarget==='new'?' is-dragover':'')} data-ota-drop="new" disabled={blocked} onClick={()=>void pick('new')}><FileArchive/><span>{next || tr('选择 ZIP 文件','Select ZIP file')}</span><FolderOpen size={18}/></button>
<Button className="ota-wide" disabled={blocked || !old || !next} onClick={()=>void work(async()=>{const r=await request<Analysis>('ota_analyze',{old,new:next});setAnalysis(r);})}>{busy?<LoaderCircle className="animate-spin" size={18}/>:<GitCompareArrows size={18}/>} {tr('分析差异','Analyze changes')}</Button></>
{generator?<><label className="ota-label">{tr('旧版完整包或版本摘要','Old full release or version index')}</label><button className={'ota-picker'+(dropTarget==='old'?' is-dragover':'')} data-ota-drop="old" disabled={blocked} onClick={()=>void pick('old')}><FileArchive/><span>{old || tr('选择 ZIP 或版本摘要 JSON','Select ZIP or version index JSON')}</span><FolderOpen size={18}/></button><div className="ota-arrow"><ArrowRight size={18}/></div><label className="ota-label">{tr('新版完整包','New full release')}</label><button className={'ota-picker'+(dropTarget==='new'?' is-dragover':'')} data-ota-drop="new" disabled={blocked} onClick={()=>void pick('new')}><FileArchive/><span>{next || tr('选择 ZIP 文件','Select ZIP file')}</span><FolderOpen size={18}/></button>
<Button variant="ghost" disabled={blocked} onClick={()=>void work(()=>native('open_index_data'))}><FolderOpen size={16}/>{tr('打开版本摘要目录','Open version index folder')}</Button>
<Button className="ota-wide" disabled={blocked || !old || !next} onClick={()=>void work(async()=>{setAnalysis(undefined);const r=await request<Analysis>('ota_analyze',{old,new:next});setAnalysis(r);})}>{busy?<LoaderCircle className="animate-spin" size={18}/>:<GitCompareArrows size={18}/>} {tr('分析差异','Analyze changes')}</Button></>
:<><button className={'ota-picker'+(dropTarget==='patch'?' is-dragover':'')} data-ota-drop="patch" disabled={blocked} onClick={()=>void pick('patch')}><FileArchive/><span>{patch || tr('选择 .ota 差异包','Select .ota patch')}</span><FolderOpen size={18}/></button><label className="ota-label">{tr('设备管理地址','Device management address')}</label><input value={host} disabled={blocked} onChange={e=>{setHost(e.target.value);setReview(undefined);setRebootReady(false);}}/><label className="ota-label">SSH root {tr('密码','password')}</label><input type="password" value={password} disabled={blocked} onChange={e=>{setPassword(e.target.value);setReview(undefined);setRebootReady(false);}} autoComplete="off"/>
<Button className="ota-wide" disabled={blocked || !patch || !host} onClick={()=>void work(async()=>{setReview(await request<Review>('ota_probe',{host,password,path:patch}));})}><ShieldCheck size={18}/>{tr('连接并检查','Connect and review')}</Button><Button variant="ghost" className="ota-wide" disabled={busy || !host} onClick={()=>void work(async()=>{const s=await request<Status>('ota_status',{host,password,path:patch});setRunning(s.job?.status==='running');showStatus(s);})}>{tr('重新检查设备状态','Check device status')}</Button></>}
</section><section className="ota-card ota-result"><h2><span className="ota-number">2</span>{tr('检查并继续','Review and continue')}</h2><div className="ota-result-body" tabIndex={0} aria-label={tr('检查结果','Review results')}>
{analysis || manifest?<><div className="ota-release"><small>{tr('目标设备','Target profile')}</small><strong>{(analysis?.manifest || manifest)!.profile}</strong><small>{(analysis?.manifest || manifest)!.kernel_release}</small></div><p className="ota-versions">{(analysis?.manifest || manifest)!.base_version}<ArrowRight size={16}/>{(analysis?.manifest || manifest)!.target_version}</p></>:<div className="ota-empty"><ShieldCheck size={42}/><p>{tr('选择文件后,在这里查看版本与兼容检查结果。','Select files to review versions and compatibility here.')}</p></div>}
{(analysis?.manifest || manifest)?.boot && <p className="ota-notice">{tr('包含内核与启动镜像更新,配套模块随系统差异一起更新;用户插件、配置和数据保留。','Includes kernel/boot update and matching module changes. User packages, settings and data are retained.')}</p>}
{analysis?.index_path && <div className="ota-index"><strong>{tr('新版版本摘要已自动保存','New version index saved automatically')}</strong><p>{tr('下次可将它作为旧版输入;保存摘要不代表设备已完成更新。','Use it as the old release next time. Saving an index does not mean a device has been updated.')}</p><code>{analysis.index_path}</code><div><Button variant="outline" disabled={blocked} onClick={()=>void work(async()=>{const output=await native('save_index');if(!output)return;const r=await request<{path:string}>('ota_export_index',{output});setSuccess(tr('版本摘要已导出:','Version index exported: ')+r.path);})}><Upload size={15}/>{tr('导出版本摘要','Export version index')}</Button></div></div>}
{analysis && <><div className="ota-stats"><div><strong>{analysis.files}</strong><small>{tr('文件变更','Changed files')}</small></div><div><strong>{size(analysis.payload_bytes)}</strong><small>{tr('未压缩载荷','Uncompressed payload')}</small></div><div><strong>{analysis.added} / {analysis.removed}</strong><small>{tr('新增 / 删除','Added / removed')}</small></div></div>
{!!analysis.blockers.length && <div className="ota-error ota-blockers" tabIndex={0} role="region" aria-label={tr('无法生成的原因','Reasons export is unavailable')}>{analysis.blockers.map((b,i)=><p key={i}>{explainBlocker(b)}</p>)}<details><summary>{tr('技术详情','Technical details')}</summary><pre style={{whiteSpace:'pre-wrap',overflowWrap:'anywhere'}}>{analysis.blockers.join('\n')}</pre></details></div>}<details className="ota-files"><summary>{tr('查看文件清单','View file list')}</summary>{analysis.manifest.operations.map(o=><div key={o.path}>{o.before?(o.after?'~':'−'):'+'} {o.path}</div>)}</details>
<Button className="ota-wide" disabled={blocked || !analysis.can_export} onClick={()=>void work(async()=>{const output=await native('save_ota',{suggestedName:analysis.suggested_name,releasePath:next});if(!output)return;const r=await request<Analysis>('ota_export',{output});setSuccess(tr('已生成差异包:','Patch saved: ')+r.output);})}><Upload size={18}/>{tr('导出差异包','Export patch')}</Button></>}
<Button className="ota-wide" disabled={blocked || !analysis.can_export} onClick={()=>void work(async()=>{const output=await native('save_ota',{suggestedName:analysis.suggested_name,releasePath:next});if(!output)return;const r=await request<Analysis>('ota_export',{output});setAnalysis(previous=>previous?{...previous,...r}:r);setSuccess(tr('已生成差异包:','Patch saved: ')+r.output);})}><Upload size={18}/>{tr('导出差异包','Export patch')}</Button></>}
{review && <><p>{tr('所需空间 / 可用空间:','Required / available: ')}{size(review.check.required_bytes)} / {size(review.check.free_bytes)}</p>{!![...review.check.conflicts,...review.check.package_conflicts].length && <div className="ota-error">{tr('本地文件或依赖冲突,未写入:','Local file or dependency conflicts; nothing written: ')}{[...review.check.conflicts,...review.check.package_conflicts].join(', ')}</div>}<label style={{display:'flex',gap:10,alignItems:'center',margin:'16px 0',fontSize:14}}><input type="checkbox" style={{width:'auto',height:'auto',margin:0}} checked={autoReboot} disabled={blocked} onChange={e=>setAutoReboot(e.target.checked)}/>{tr('更新完成后自动重启','Automatically reboot after updating')}</label><Button className="ota-wide" disabled={blocked || !review.check.applicable} onClick={()=>void work(async()=>{await request('ota_apply',{host,password,token:review.token,auto_reboot:autoReboot});setRebootReady(false);setRunning(true);setReview(undefined);})}><PackageCheck size={18}/>{tr('确认应用此补丁','Apply reviewed patch')}</Button></>}
</div></section></div>
{(busy || running) && <div className="ota-notice"><LoaderCircle className="animate-spin" size={18}/><span>{running?tr('设备正在写入,关闭电脑更新器不会终止设备事务。','Device is writing. Closing this app does not cancel its transaction.'):tr('正在处理,请稍候…','Processing…')}<small>{progress}</small></span></div>}
@@ -0,0 +1,21 @@
# Diff Studio version indexes — 2026-10-25
Implemented in the shared installer and mirrored into MU300. Native Windows/macOS file dialogs accept an old full ZIP or version-index JSON, retain full-package input for the new release, and provide index-folder/export actions. Successful compatible analysis saves the generated target baseline automatically under application data/release-indexes. There is no automatic claim that the device has installed that version.
The version-1 index stores release identity, boot hash, full file descriptors and APK version/dependency records, with a SHA-256 over canonical data. It carries no file payloads or device identifiers. Generated updater overlays are included before snapshotting. Import checks format/version, integrity, duplicate keys, path safety, descriptors, bounded file size and metadata. Content-addressed version files are retained separately. Atomic writes flush the file; POSIX also flushes the directory. Existing export files are not overwritten. Invalid/blocked analyses clear the current export binding and do not save a new target.
Validation used only temporary releases, regular-file filesystems, fake UI transports and local browser servers:
- Full Windows installer suites: E5 351 cases, 288 passed/63 skipped; MU300 343 cases, 276 passed/67 skipped.
- Final focused index suite: Linux 11 passed; Windows 10 passed/1 Linux-engine case skipped, in each repository's host tests.
- Complete old-package and saved-index generation produced identical patch manifests and payload bytes after deleting the old releases. Repeated caching, moved/renamed indexes, boot hashes, package records, permissions, links and xattrs were checked.
- The real E5 ext4 reader fixture creates three small ext4 files with mke2fs in WSL. It deletes the middle release, generates the next patch using its index, and verifies the exported payload with Patch.
- Two real Engine transactions were applied to a temporary Linux root using injected updater/runtime files. The second patch used the saved target index after its full package was deleted, preserved updater descriptors correctly and reached the third release.
- Service reopening/custom application data and the real portable CLI analyze/generate commands were exercised without the old package.
- Corruption, unsupported versions, duplicate JSON fields, traversal, invalid descriptors, missing new payloads, blocked/incompatible analysis, existing export targets and interrupted publication were rejected.
- Both production frontend builds and Windows Tauri cargo check --offline --tests -j 2 passed.
- Both Diff Studio/Patch Updater browser suites passed, including JSON drag/drop, export/cancel, folder actions, stale-state clearing, bilingual UI, themes, minimum-size bounded scrolling, HiDPI drops, existing patch export, update checks and restart/status flows.
Build/test logs are under out/build-logs with diff-index-* task labels. Browser logs are diff-index-browser-20261025.log in each repository; screenshots are work/diff-index-preview.png and work/ota-ui-preview.png. Windows test fixture Git signing was disabled only in the test process, without changing Git configuration.
No ADB/SSH connection, device mutation, native installer release build or firmware packaging was performed. Native macOS dialog/runtime behavior remains untested on actual macOS. Existing APP/EXE and release archives are unchanged; future distribution must rebuild the matching native artifacts through the existing build workflow.
@@ -0,0 +1,18 @@
# E5 bootloader-state preflight — 2026-10-25
The E5 GUI adapter, compatible Python entry and Magisk TF worker no longer require an orange verified-boot property or prior bootloader unlocking. The shared adapter's E5 compatibility branch in the MU300 repository has the same BL policy; its MU300-specific branch is unchanged. No unlock command, AVB-disabling operation or partition write was added.
Preflight still requires working root, matching package/model/board, valid Android slots, the existing boot/firmware partitions and bundled tools. Boot-chain checks, Android slot protection, backups, hashes and readback verification remain in their existing paths. Documentation no longer declares bootloader unlocking mandatory.
Device-free validation:
- E5 installer suite: 342 tests, 280 passed, 62 environment-dependent skips.
- MU300 mirror suite: 334 tests, 268 passed, 66 environment-dependent skips.
- GUI probe tests cover six E5 profiles with orange, green, yellow, red, empty and missing boot-state values. Missing root, wrong model and invalid slot still prevent further inspection.
- Real compatible CLI preflight executes for all six profiles on Android A and B without querying the former BL gate. Missing root, wrong model/board or invalid slot stops before tool upload.
- Native Magisk preflight: one test with 63 simulated cases, including both Android slots, five boot states for each profile, missing geometry tools and wrong K1/41S boards. Valid cases reach an intercepted boot-control check; no real block device is used.
- Hybrid package tests: 8 passed. Android root-tool tests: 6 passed. Slot-role and boot-image/AVB preservation tests: 6 passed.
Logs are in out/build-logs under the e5-bl-* task labels. The first WSL slot-role run lacked the Python lz4 module; the same six tests passed using the existing Windows Python environment. A mirror-suite fixture commit initially waited for the host's GPG signing configuration; the full rerun disabled signing only in that test process and passed. No repository or global Git signing setting was changed.
No device was connected, flashed or unlocked. Locked-device hardware boot acceptance was not tested. Existing executable artifacts and firmware packages were not rebuilt; new native sidecars and compatibility executables are required before distributing this change.
@@ -0,0 +1,15 @@
## macOS package discovery regression (2026-10-25)
The original report did not include its exact error or launch step, so its specific cause remains unconfirmed. Source inspection found that the macOS startup folder picker accepted an unchecked selection once, cancellation became a startup error, and every backend spawn failure was reported as a missing Windows backend. These defects are corrected in the shared native host.
Startup validates the selected distribution and the macOS backend before launch. An invalid selection can be retried; cancellation exits normally. Folder resolution handles the APP/Contents, files/desktop, spaces, Unicode and one explicitly selected archive wrapper. Multiple releases require an explicit choice. No working-directory or unrelated-folder search is used, and a damaged package never silently switches to a nested release. Backend verification normalizes the same user selections before applying the existing payload hashes and model checks. The child process uses the selected root as its working directory. Spawn failures show the actual platform-specific executable and OS error. The new Rust module is included in artifact source fingerprints.
Validation used disposable host files and simulated package structures, without ADB/SSH or device writes:
- E5 Windows installer suite: 339 tests, 277 passed and 62 environment-dependent skips.
- MU300 Windows installer suite: 330 tests, 266 passed and 64 environment-dependent skips.
- Linux package-path suite: 7 passed, including real directory symlinks.
- The native resolver is compiled and executed directly by test_distribution_paths.py: 7 Rust tests passed on Windows, including invalid-selection retry and cancellation.
- Windows cargo check --offline --tests -j 2 passed for the complete Tauri host; Rustfmt parsing and scoped whitespace checks passed.
Logs are under out/build-logs in each repository, tasks macos-package-regression, macos-path-posix, macos-path-native-check and macos-path-final-native. Native macOS Finder/Gatekeeper launch and the users' original failures have not been reproduced. Existing APP/EXE artifacts and firmware archives were not rebuilt or repackaged; changed source fingerprints require fresh native artifacts before a future release.
@@ -617,7 +617,8 @@ var DASH_I18N = {
'已保存,将在下次重启时应用': ['Saved; applies on next reboot', 'Kaydedildi; sonraki yeniden başlatmada uygulanır'],
'当前电压偏移与保存值一致': ['Active voltage offsets match the saved values', 'Etkin voltaj ofsetleri kayıtlı değerlerle aynı'],
'当前内核或固件不支持电压调整': ['This kernel or firmware does not support voltage adjustment', 'Bu çekirdek veya donanım yazılımı voltaj ayarını desteklemiyor'],
'检测到异常关机,已停用上次的电压设置并恢复默认。': ['An unclean shutdown was detected. The previous voltage profile was disabled and defaults restored.', 'Düzgün kapanmama algılandı. Önceki voltaj profili devre dışı bırakılıp varsayılanlar geri yüklendi.'],
'上次电压设置未完成启动确认,已使用默认电压;设置仍保留,重新保存可重试。': ['The previous voltage trial did not finish boot confirmation. Factory voltage is active; your settings are kept. Save again to retry.', 'Önceki voltaj denemesinin açılış onayı tamamlanmadı. Varsayılan voltaj kullanılıyor; ayarlar korundu. Yeniden denemek için tekrar kaydedin.'],
'电压启动记录损坏,已暂停自动应用;设置仍保留,重新保存可重试。': ['The voltage boot record is invalid. Automatic application is paused; your settings are kept. Save again to retry.', 'Voltaj açılış kaydı geçersiz. Otomatik uygulama duraklatıldı; ayarlar korundu. Yeniden denemek için tekrar kaydedin.'],
'当前偏移': ['Active offset', 'Etkin ofset'],
'偏移预设': ['Offset presets', 'Ofset ön ayarları'],
'默认电压': ['Default voltage', 'Varsayılan voltaj'],
@@ -629,7 +630,7 @@ var DASH_I18N = {
'当前固件电压表': ['Current firmware voltage table', 'Geçerli donanım yazılımı voltaj tablosu'],
'保存电压设置': ['Save voltage settings', 'Voltaj ayarlarını kaydet'],
'恢复默认电压': ['Restore default voltage', 'Varsayılan voltajı geri yükle'],
'调压可能导致死机或数据丢失,请从小幅调整开始。异常断电或重启后会停用电压配置;正常关机保留。保存不会立即调压或自动重启。': ['Voltage changes may cause crashes or data loss; start with small adjustments. An unclean shutdown disables the profile; clean shutdown preserves it. Saving does not change live voltage or reboot.', 'Voltaj değişiklikleri çökmeye veya veri kaybına yol açabilir; küçük ayarlarla başlayın. Düzgün olmayan kapanma profili devre dışı bırakır; normal kapanma korur. Kaydetmek anlık voltajı değiştirmez veya yeniden başlatmaz.'],
'调压可能导致死机或数据丢失,请从小幅调整开始。完成启动确认后,直接断电会保留设置;首次应用未完成确认时暂停重试。保存不会立即调压或自动重启。': ['Voltage changes may cause crashes or data loss; start with small adjustments. Confirmed settings survive unplugging. An unfinished first boot pauses retries. Saving does not change live voltage or reboot.', 'Voltaj değişiklikleri çökmeye veya veri kaybına yol açabilir; küçük ayarlarla başlayın. Onaylanan ayarlar güç kesilince korunur. Tamamlanmamış ilk açılış yeniden denemeleri duraklatır. Kaydetmek anlık voltajı değiştirmez veya yeniden başlatmaz.'],
'CPU 电压配置无效': ['Invalid CPU voltage settings', 'Geçersiz CPU voltaj ayarları'],
'恢复默认电压?': ['Restore default voltage?', 'Varsayılan voltaj geri yüklensin mi?'],
'保存电压设置?': ['Save voltage settings?', 'Voltaj ayarları kaydedilsin mi?'],
@@ -229,7 +229,7 @@ return view.extend({
updatePending(voltage);
pending.hidden = !(voltage.domains || []).length;
if (!voltage.supported) section.append(node('p', M.translate('当前内核或固件不支持电压调整'), 'mud-note'));
if (voltage.recovery) section.append(node('p', M.translate('检测到异常关机,已停用上次的电压设置并恢复默认。'), 'mud-note'));
if (voltage.recovery) section.append(node('p', M.translate(voltage.recovery === 'invalid_boot_record' ? '电压启动记录损坏,已暂停自动应用;设置仍保留,重新保存可重试。' : '上次电压设置未完成启动确认,已使用默认电压;设置仍保留,重新保存可重试。'), 'mud-note'));
(voltage.domains || []).forEach(function(d) {
var card = node('div', null, 'mud-cpu-cluster'), input = node('input');
input.type = 'number'; input.min = -50; input.max = 25; input.step = 3.125;
@@ -275,7 +275,7 @@ return view.extend({
var save = node('button', M.translate('保存电压设置'), 'mud-btn on'), reset = node('button', M.translate('恢复默认电压'), 'mud-btn');
save.disabled = !voltage.supported;
var actions = node('div', null, 'mud-cpu-actions'); actions.append(pending, save, reset);
section.append(voltageGrid, actions, node('p', M.translate('调压可能导致死机或数据丢失,请从小幅调整开始。异常断电或重启后会停用电压配置;正常关机保留。保存不会立即调压或自动重启。'), 'mud-note mud-cpu-warning'));
section.append(voltageGrid, actions, node('p', M.translate('调压可能导致死机或数据丢失,请从小幅调整开始。完成启动确认后,直接断电会保留设置;首次应用未完成确认时暂停重试。保存不会立即调压或自动重启。'), 'mud-note mud-cpu-warning'));
function submitVoltage(defaults) {
if (self.busy) return;
var values = [0, 0, 0];
@@ -4,9 +4,12 @@ START=99
STOP=89
start() {
/usr/libexec/unisoc-modem/cpu boot | logger -t unisoc-cpu
# Boot reached S99 and voltage readback must match before confirming.
/usr/libexec/unisoc-modem/cpu-voltage confirm | logger -t unisoc-cpu-voltage
[ ! -f /etc/unisoc-modem/cpu-voltage-armed.json ] || sync
}
shutdown() {
# Only a real clean system shutdown disarms recovery, not service stop.
# Clean shutdown may confirm matching readback too. Service stop does not.
/usr/libexec/unisoc-modem/cpu-voltage shutdown >/dev/null
sync
}
@@ -1,4 +1,4 @@
/etc/unisoc-modem/cpu.json
/etc/unisoc-modem/cpu-voltage.json
# Preserve an armed profile's guard: an unclean upgrade must not bypass recovery.
# Preserve pending/confirmed/paused voltage validation across upgrades.
/etc/unisoc-modem/cpu-voltage-armed.json
@@ -5,6 +5,7 @@ const DIR=getenv('MU300_CPU_VOLTAGE_DIR') || '/etc/unisoc-modem';
const RUN=getenv('MU300_CPU_VOLTAGE_RUN') || '/run';
const ROOT=getenv('MU300_CPU_SYS') || '/sys/devices/system/cpu/cpufreq';
const CONFIG=DIR+'/cpu-voltage.json', ARMED=DIR+'/cpu-voltage-armed.json';
const RECOVERY=RUN+'/unisoc-cpu-voltage-recovery.json';
const BOOT=trim(fs.readfile(getenv('MU300_CPU_BOOT_ID') || '/proc/sys/kernel/random/boot_id') || '');
const PLATFORM=getenv('MU300_CPU_PLATFORM') || '/opt/mu300/bin/cpu-voltage-platform';
function readjson(path) { try { return json(fs.readfile(path) || 'null'); } catch(e) { return null; } }
@@ -13,6 +14,7 @@ function valid(v) {
for(let n in v) if(type(n)!='int' || n < -50000 || n > 25000 || n%3125) return false;
return true;
}
function same(a,b) { return valid(a) && valid(b) && join(',',a)==join(',',b); }
function store(path,value) {
let s=sprintf('%J\n',value), tmp=path+'.new';
fs.mkdir(DIR,448);
@@ -63,23 +65,57 @@ function save(input) {
let nonzero=length(filter(input.offsets,n=>n!=0))>0;
if(nonzero && (!supported(true) || length(current())!=3)) return {ok:0,error:'当前内核或固件不支持电压调整'};
if(!store(CONFIG,{version:1,offsets:input.offsets})) return {ok:0,error:'无法保存 CPU 设置'};
// Do not clear ARMED while running at nonzero voltage, even on reset.
// Explicit saving retries a paused trial only from observed factory voltage.
// Saving while an offset is active must not erase its boot evidence.
let armed=readjson(ARMED), domains=current();
if(armed?.phase=='paused' && length(domains)==3 && !length(filter(domains,d=>d.offset!=0))) {
if(!fs.unlink(ARMED)) return {ok:0,error:'无法保存 CPU 设置'};
fs.unlink(RECOVERY);
}
return status();
}
function bootargs() {
let config=readjson(CONFIG), armed=readjson(ARMED), reason=null;
let config=readjson(CONFIG), armed=readjson(ARMED);
if(fs.stat(ARMED)) {
if(BOOT && armed?.boot==BOOT) return '0,0,0'; // never apply twice
reason='unclean_shutdown';
if(fs.stat(CONFIG) && !fs.rename(CONFIG,CONFIG+'.rejected')) return '0,0,0';
fs.unlink(ARMED); config=null;
}
if(reason) store(RUN+'/unisoc-cpu-voltage-recovery.json',{reason});
if(config?.version!=1 || !valid(config.offsets) || !length(filter(config.offsets,n=>n!=0))) return '0,0,0';
if(config?.version!=1 || !valid(config.offsets)) return '0,0,0';
if(!length(filter(config.offsets,n=>n!=0))) {
if(BOOT) { fs.unlink(ARMED); fs.unlink(RECOVERY); }
return '0,0,0';
}
if(!BOOT || !supported(true)) return '0,0,0';
if(!store(ARMED,{boot:BOOT,offsets:config.offsets})) return '0,0,0';
// Missing shutdown is normal on externally powered F50/V50. Confirmed
// settings survive any power cut. Only an unfinished NEW trial is paused;
// it is not evidence of a crash and never rejects or deletes the profile.
let reason=null;
if(fs.stat(ARMED) && (!valid(armed?.offsets) ||
(armed.version!=null && armed.version!=2) ||
(armed.version==2 && index(['pending','confirmed','paused'],armed.phase)<0))) reason='invalid_boot_record';
else if(armed?.version==2 && same(armed.offsets,config.offsets) &&
(armed.phase=='pending' || armed.phase=='paused')) reason='boot_unconfirmed';
if(reason) {
store(ARMED,{version:2,boot:BOOT,offsets:config.offsets,phase:'paused'});
store(RECOVERY,{reason});
return '0,0,0';
}
let confirmed=armed?.version==2 && armed.phase=='confirmed' && same(armed.offsets,config.offsets);
if(!store(ARMED,{version:2,boot:BOOT,offsets:config.offsets,phase:confirmed?'confirmed':'pending'})) return '0,0,0';
fs.unlink(RECOVERY);
return join(',',config.offsets);
}
function confirm() {
let armed=readjson(ARMED);
if(!fs.stat(ARMED) || armed?.phase=='paused') return {ok:1};
if(!BOOT || armed?.boot!=BOOT || !valid(armed.offsets)) return {ok:0,error:'无法确认 CPU 电压启动状态'};
let domains=current();
if(length(domains)!=3 || length(filter(domains,d=>d.offset!=armed.offsets[d.id])))
return {ok:0,error:'CPU 电压读回与启动设置不符'};
if(armed.version==2 && armed.phase=='confirmed') return {ok:1};
if(!store(ARMED,{version:2,boot:BOOT,offsets:armed.offsets,phase:'confirmed'}))
return {ok:0,error:'无法确认 CPU 电压启动状态'};
return {ok:1};
}
let action=ARGV[0]||'get', result;
try {
if(action=='boot-args') { print(bootargs()+'\n'); exit(0); }
@@ -87,10 +123,8 @@ try {
else if(action=='save') {
let text=fs.stdin.read(4097);
result=length(text)>4096?{ok:0,error:'CPU 电压配置无效'}:save(json(text));
} else if(action=='shutdown') {
let armed=readjson(ARMED);
result={ok:!fs.stat(ARMED) || (BOOT && armed?.boot==BOOT && fs.unlink(ARMED))?1:0};
} else result={ok:0,error:'CPU 电压配置无效'};
} else if(action=='confirm' || action=='shutdown') result=confirm();
else result={ok:0,error:'CPU 电压配置无效'};
} catch(e) {
if(action=='boot-args') { print('0,0,0\n'); exit(0); }
result={ok:0,error:'CPU 电压配置无效'};
+73 -19
View File
@@ -32,27 +32,81 @@ test "$(call boot-args)" = '-3125,0,6250'
test -f "$base/etc/cpu-voltage-armed.json"
# Repeating startup cannot apply an offset twice.
test "$(call boot-args)" = '0,0,0'
# Reset while running must not erase the crash guard.
# Readback must match all domains before startup is confirmed.
if call confirm > "$base/out"; then echo 'confirmed wrong voltage'; exit 1; fi
test "$(check "$(cat "$base/etc/cpu-voltage-armed.json")" '@.phase')" = pending
printf '%s\n' -3125 > "$base/sys/policy0/scaling_voltage_offset"
printf '%s\n' 6250 > "$base/sys/policy2/scaling_voltage_offset"
call confirm > "$base/out"
test "$(check "$(cat "$base/etc/cpu-voltage-armed.json")" '@.phase')" = confirmed
test "$(call boot-args)" = '0,0,0'
# F50/V50 unplug: no shutdown action is invoked, and settings survive.
printf 'boot-two\n' > "$base/boot"
test "$(call boot-args)" = '-3125,0,6250'
# Even a subsequent power loss before S99 keeps this already confirmed profile.
printf 'boot-three\n' > "$base/boot"
test "$(call boot-args)" = '-3125,0,6250'
# A new, unconfirmed profile is paused after an interrupted first boot.
printf '{"offsets":[0,3125,0]}' | call save > "$base/out"
printf 'boot-four\n' > "$base/boot"
test "$(call boot-args)" = '0,3125,0'
printf 'boot-five\n' > "$base/boot"
for d in 0 1 2; do printf '0\n' > "$base/sys/policy$d/scaling_voltage_offset"; done
test "$(call boot-args)" = '0,0,0'
test -f "$base/etc/cpu-voltage.json"
test ! -e "$base/etc/cpu-voltage.json.rejected"
out=$(call get)
test "$(check "$out" '@.recovery')" = boot_unconfirmed
# Further power loss cannot retry the paused profile without explicit saving.
printf 'boot-six\n' > "$base/boot"
test "$(call boot-args)" = '0,0,0'
call shutdown > "$base/out"
printf 'boot-seven\n' > "$base/boot"
test "$(call boot-args)" = '0,0,0'
# Explicit retry is accepted only after observed default-voltage boot.
printf '%s\n' -3125 > "$base/sys/policy0/scaling_voltage_offset"
printf '{"offsets":[0,3125,0]}' | call save > "$base/out"
test "$(check "$(cat "$base/etc/cpu-voltage-armed.json")" '@.phase')" = paused
printf '0\n' > "$base/sys/policy0/scaling_voltage_offset"
printf '{"offsets":[0,3125,0]}' | call save > "$base/out"
test ! -e "$base/etc/cpu-voltage-armed.json"
test "$(call boot-args)" = '0,3125,0'
printf '3125\n' > "$base/sys/policy1/scaling_voltage_offset"
call shutdown > "$base/out"
test "$(check "$(cat "$base/etc/cpu-voltage-armed.json")" '@.phase')" = confirmed
printf 'boot-eight\n' > "$base/boot"
test "$(call boot-args)" = '0,3125,0'
# Pending save of different offsets is not discarded with an older trial.
printf '{"offsets":[3125,0,0]}' | call save > "$base/out"
printf 'boot-nine\n' > "$base/boot"
test "$(call boot-args)" = '3125,0,0'
printf '{"offsets":[6250,0,0]}' | call save > "$base/out"
printf 'boot-ten\n' > "$base/boot"
test "$(call boot-args)" = '6250,0,0'
# Legacy lifetime guard migrates without declaring an unplug to be a crash.
printf '{"boot":"old-version","offsets":[6250,0,0]}' > "$base/etc/cpu-voltage-armed.json"
printf 'boot-eleven\n' > "$base/boot"
test "$(call boot-args)" = '6250,0,0'
printf '6250\n' > "$base/sys/policy0/scaling_voltage_offset"
printf '0\n' > "$base/sys/policy1/scaling_voltage_offset"
call confirm > "$base/out"
# Saving factory values while an offset runs preserves its evidence until boot.
printf '{"offsets":[0,0,0]}' | call save > "$base/out"
test -f "$base/etc/cpu-voltage-armed.json"
call shutdown > "$base/out"
test ! -e "$base/etc/cpu-voltage-armed.json"
printf '{"offsets":[-3125,0,0]}' | call save > "$base/out"
test "$(call boot-args)" = '-3125,0,0'
# Simulate an unclean boot, reject persisted voltage and never retry it.
printf 'boot-two\n' > "$base/boot"
printf 'boot-defaults\n' > "$base/boot"
test "$(call boot-args)" = '0,0,0'
test -f "$base/etc/cpu-voltage.json.rejected"
test ! -e "$base/etc/cpu-voltage.json"
out=$(call get)
test "$(check "$out" '@.recovery')" = unclean_shutdown
# A clean shutdown preserves a saved profile across boots.
printf '{"offsets":[0,3125,0]}' | call save > "$base/out"
test "$(call boot-args)" = '0,3125,0'
call shutdown > "$base/out"
printf 'boot-three\n' > "$base/boot"
test "$(call boot-args)" = '0,3125,0'
call shutdown > "$base/out"
test ! -e "$base/etc/cpu-voltage-armed.json"
printf '{"offsets":[6250,0,0]}' | call save > "$base/out"
test "$(call boot-args)" = '6250,0,0'
# Corrupt records fail closed without erasing the saved user profile.
printf '{bad' > "$base/etc/cpu-voltage-armed.json"
printf 'boot-twelve\n' > "$base/boot"
test "$(call boot-args)" = '0,0,0'
test "$(check "$(call get)" '@.recovery')" = invalid_boot_record
test -f "$base/etc/cpu-voltage.json"
for d in 0 1 2; do printf '0\n' > "$base/sys/policy$d/scaling_voltage_offset"; done
printf '{"offsets":[0,0,0]}' | call save > "$base/out"
test ! -e "$base/etc/cpu-voltage-armed.json"
# Unknown firmware may reset to defaults, but may not save/apply an offset.
touch "$base/unsupported"
if printf '{"offsets":[-3125,0,0]}' | call save > "$base/out"; then exit 1; fi
@@ -62,4 +116,4 @@ printf '{"offsets":[0,0,0]}' | call save > "$base/out"
rm "$base/unsupported" "$base/sys/policy2/scaling_voltage_domain"
if printf '{"offsets":[0,0,3125]}' | call save > "$base/out"; then exit 1; fi
test ! -e "$base/etc/cpu-voltage-armed.json"
echo "PASS voltage validation/gate/persistence/reset/clean+unclean recovery: $base"
echo "PASS voltage validation/gate/confirmed unplug/unfinished trial/manual retry/legacy recovery: $base"
+2
View File
@@ -39,6 +39,8 @@ class CpuVoltage(unittest.TestCase):
init=(APP/'root/etc/init.d/unisoc-cpu').read_text()
self.assertIn('shutdown()',init)
self.assertNotIn('stop()',init)
self.assertIn('cpu-voltage confirm', init)
self.assertIn('START=99', init)
@unittest.skipUnless(shutil.which('ucode') and shutil.which('jsonfilter'), 'requires OpenWrt ucode/jsonfilter; also run cpu_voltage_fixture.sh in the OpenWrt container')
def test_isolated_profiles(self):