fix(m161): 收更新键/按钮/矮窗口/启动错误/导入结果五笔债

① update.auto_check / update.channel 登记进 core setting schema(1.6.0)
   - 新增 setting/keys/update.rs(两键 + UPDATE_CHANNELS,只允许 stable);
     SettingSchema 加 with_all 供域键表批量登记。
   - 新增 setting/update_prefs.rs:cache/update/prefs.json → launcher.json 的一次性迁移。
     四条硬约束:源指纹闸门(幂等)、不丢 false、新值胜出、旧文件改名 .migrated 后不再被读;
     主配置不可写时不动旧文件。收据 config/update-prefs-migration.json。
   - presenter Runtime 建会话时迁一次并把结局留在 migration();prefs 字段换成
     auto_check + 每次派发从主配置读 channel(不再硬编码 Channel::Stable)。
     保留旧字段 auto_check 的真实来源(原有测试 cases 会断言)。
   - CLI config get/set/dump 先跑同一次迁移(幂等),输出里给 migration 段与收据路径。

② presenter/dto/events.rs 的「本次会话不再弹提示条」注释改成真实语义
   (记的是版本号:同版本压住、更高版本照弹、手动检查清掉)。

③ 检查/下载进行中按钮禁用:pages/update/busy.rs 的 busy/can_check/can_apply;
   设置页两颗按钮改画禁用(不是消失),app 层 on_update_action 再挡一道
   (忙碌时 CheckNow/Apply 不派发);新增两条用例(含「忙完恢回可点」)。

④ 内容库低高度:content_layout::MIN_BODY_HEIGHT=460 + BodyMode(按固定件+三整行算出来,
   用例守着算式);frame::body_height 从 Ui::metrics 算正文可用高,pages::Model 带 window_height。
   ≥460 列表自己滚;<460 主列整列一个滚动条、列表按自然高度铺开。

⑤ 启动错误文案本地化:presenter 删掉 launch_summary / 「启动失败:」前缀 / 五条中文阶段前缀,
   改发 LaunchFailureView{stage,detail};LaunchFinished 改带 exit_code/uptime_ms/failure,
   Toast 由 app 层按 i18n key 现求(与 install_cancelled 同构)。InstancesFailed 拆成
   InstancesFailedStage(列表单行)+ LaunchStageFailed(详情/Toast 全文)。

⑥ 导入结果块:ImportReportView 加 failure_stage(NotStarted/RolledBack/RollbackIncomplete,
   由 core 的 rollback 机器位推出);标题、图标、底色三处分档,预检失败不再说「已回滚」。

顺带:六处注释/文档漂移(update.rs 的分工表与偏好落点、pack 的「已整包回滚」、
build_request 的 Errors、settings/update 的按钮禁用说明等),
以及为守 400 行把 update/cli-config/core-keys/presenter-dto/presenter-launch/i18n-golden
里贴线或越线的文件按模块拆开(纯搬移,行为不变)。
This commit is contained in:
AskaEth committed 2026-11-07 15:02:13 +08:00
1 parent b2d9f3927f
commit 03741ecd2d
69 files changed
+2653 -707

No files matched your search

+11
View File
@@ -42,6 +42,17 @@ impl SettingSchema {
self
}
/// 一次登记一批键(M161:某个域的键表拆到自己的文件后,主表只留一行)。
///
/// 重复键的断言与 [`Self::with`] 同源(`with` 负责),所以批量登记不会绕过那条守门。
#[must_use]
pub fn with_all(mut self, specs: impl IntoIterator<Item = SettingSpec>) -> Self {
for spec in specs {
self = self.with(spec);
}
self
}
/// 种类。
#[must_use]
pub const fn id(&self) -> SchemaId {
+14 -13
View File
@@ -1,7 +1,5 @@
//! `config/launcher.json` 的键表(全局设置)。
//!
//! 键名与默认值对齐 `DevDocs/PlanDoc/04-data-and-config.md` §2-§3 与 `05/06/07/08` 各专题;
//! AI 可写 + 敏感分级按 `02-ai-agent-design.md` §3.1 的边界落:**密钥类一律 locked**。
//! `config/launcher.json` 的键表(全局设置)。键名与默认值对齐 `04-data-and-config.md` §2-§3;
//! AI 可写 + 敏感分级按 `02-ai-agent-design.md` §3.1 落:**密钥类一律 locked**。
use super::catalog::SettingSchema;
use super::schema::{SchemaId, SchemaVersion};
@@ -36,11 +34,13 @@ pub const INSTANCE_MODES: &[&str] = &["isolated", "shared"];
/// `java.installRoot` 未设置时的哨兵(空串 = 按数据目录模式派生落点)。
pub const JAVA_INSTALL_ROOT_UNSET: &str = "";
/// `java.vendorPriority` 的允许值(D23:四家发行版,顺序即优先级)。
///
/// 与 `crate::game::java::vendor::VENDOR_IDS` 必须是同一份集合——setting 层不依赖 game 层
/// (分层纪律),一致性由 `tests/setting/java_install_keys.rs` 的契约测试固定。
/// 与 `game::java::vendor::VENDOR_IDS` 必须同一份集合(setting 层不依赖 game 层),
/// 一致性由 `tests/setting/java_install_keys.rs` 的契约测试固定。
pub const JDK_VENDORS: &[&str] = &["temurin", "oracle", "microsoft", "zulu", "termux"];
/// 自更新两键(M161;拆到自己的文件守 400 行)。
pub mod update;
/// launcher.json 当前 schema 版本。
///
/// `1.1.0` 登记 D20 实例隔离键(`instances.mode` 等)。
@@ -49,11 +49,11 @@ pub const JDK_VENDORS: &[&str] = &["temurin", "oracle", "microsoft", "zulu", "te
/// 迁移链(按 major 走)不需要新步骤;`1.1.0 → 1.2.0` 的差异只体现在文件里出现新键之后。
/// `1.3.0` 登记 D17 的「外观(高级)」P1 键(`appearance.bg_image*` / `panel_alpha` / `glass` /
/// `accent_color`):同一套纯增量语义——出厂全默认(高级特性全关)即等于老文件缺键。
/// `1.4.0` 登记 P4 的外观下层三键(`appearance.window_opacity` / `titlebar_mode` /
/// `palette_source`,M91 · D36/D37/D38):仍然只推 minor、不加迁移步骤——三者的出厂值
/// (不透明 / auto / 内置色卡)正是「老文件没有这些键」时的等价物。
/// `1.5.0` 登记 M116 的窗口圆角策略(`appearance.window_corner`,出厂 `system`):
/// 同一套纯增量语义——**新读旧**:老文件缺该键 ⇒ 读默认 `system` ⇒ 跟随系统,与写进文件后行为一致。
/// `1.4.0` 登记 P4 的外观下层三键(`window_opacity` / `titlebar_mode` / `palette_source`,M91):
/// 仍然只推 minor、不加迁移步骤——三者的出厂值正是「老文件没有这些键」时的等价物。
/// `1.5.0` 登记 M116 的窗口圆角策略(`appearance.window_corner`,出厂 `system`):纯增量。
/// `1.6.0` 登记 M161 的「自更新」两键(见 [`update`]):纯增量但带一步数据迁移
/// (此前住在 `cache/update/prefs.json`,迁移见 [`super::update_prefs`])。
///
/// **旧读新(方向相反,措辞必须精确)**:1.4.0 的客户端读 1.5.0 的文件时,
/// [`super::schema::SchemaCompat::check_url`] 走 `found.minor > expected.minor` →
@@ -64,7 +64,7 @@ pub const JDK_VENDORS: &[&str] = &["temurin", "oracle", "microsoft", "zulu", "te
/// `$schema` 那一行里,不看版本号无从排查。
#[must_use]
pub fn launcher_version() -> SchemaVersion {
SchemaVersion::new(1, 5, 0)
SchemaVersion::new(1, 6, 0)
}
/// `config/launcher.json` 的 schema。
@@ -395,4 +395,5 @@ pub fn launcher_schema() -> SettingSchema {
AiPolicy::audited(),
"启动器日志级别",
))
.with_all(update::specs())
}
+39
View File
@@ -0,0 +1,39 @@
//! 自更新两键(M161:从更新域自己的 `cache/update/prefs.json` 迁进主配置)。
//!
//! 从 `keys.rs` 拆出(那边贴着 400 行硬线):这两个键连同它们的允许值与理由一起搬,
//! 主表只留一行 `.with(update::register(..))`。
//!
//! 为什么必须进 schema:`ull config get update.auto_check` 读的是**这一份**文件;域内文件对
//! CLI 不可见(用户在 GUI 里关掉自动检查,CLI 永远报默认值 `true`)。存量迁移(幂等 + 收据)
//! 在 [`crate::setting::update_prefs`]。
use crate::setting::spec::{AiPolicy, SettingSpec};
/// `update.channel` 允许值。
///
/// D50:先只发 stable。**加值必须与宿主层同步**——`presenter::host::update::Runtime` 现在真的
/// 读这个键(`UpdateView::channel` 与检查用的渠道同源),但 core 的 `Job::check/apply` 仍按
/// 传入的渠道准入,所以只有清单里真有那个渠道的发布时才该加值。现在写死一个值:用户
/// `config set update.channel beta` 会被 schema **当面拒绝**,而不是写进文件后被静默忽略
/// (那是更坏的谎)。
pub const UPDATE_CHANNELS: &[&str] = &["stable"];
/// 两个自更新键的完整登记项(主表一行 `.with_all(specs())`)。
#[must_use]
pub fn specs() -> Vec<SettingSpec> {
vec![
SettingSpec::bool(
"update.auto_check",
true,
AiPolicy::audited(),
"启动时静默检查更新(关掉之后启动一次网络都不发;发现新版本才弹提示条)",
),
SettingSpec::enumeration(
"update.channel",
"stable",
UPDATE_CHANNELS,
AiPolicy::audited(),
"更新渠道(D50 先只发 stable;清单里没有的渠道不许写进文件)",
),
]
}
+3
View File
@@ -19,6 +19,8 @@
//! - [`store`]:单文件加载降级 + 原子保存 + 坏文件备份;
//! - [`save`] / [`save_worker`]:200ms 去抖攒批与后台保存线程;
//! - [`migrate`]:`schemaVersion N → N+1` 迁移链 + 收据闸门。
//! - [`update_prefs`]:自更新偏好(旧 `cache/update/prefs.json`)→ `launcher.json` 的一次性迁移
//! (M161:幂等、源指纹闸门、旧文件退役、收据可查)。
pub mod appearance;
pub mod catalog;
@@ -34,3 +36,4 @@ pub mod save_worker;
pub mod schema;
pub mod spec;
pub mod store;
pub mod update_prefs;
+303
View File
@@ -0,0 +1,303 @@
//! 自更新偏好 `<数据根>/cache/update/prefs.json` → `<数据根>/config/launcher.json` 的迁移(M161)。
//!
//! # 为什么要有这一步
//!
//! M159 把「启动时静默检查」临时落在更新域自己的文件里(当时 `crates/core/src/setting/**`
//! 不在那条 mission 的 scope)。后果是**同一个开关有两个真相源**:GUI 读写 `prefs.json`,
//! 而 `ull config get update.auto_check` 读 `launcher.json`——用户在 GUI 里关掉自动检查,
//! CLI 永远回答默认值 `true`。M161 把两个键([`KEY_AUTO_CHECK`] / [`KEY_CHANNEL`])登记进
//! schema,本模块负责把**存量值**搬过去。
//!
//! # 四条硬约束(每条都有对应用例,见 `tests/setting/update_keys.rs`)
//!
//! 1. **幂等**:跑两次的第二遍什么都不做。判据不是「文件还在不在」(改名可能失败),而是
//! [`crate::platform::receipt`] 里的源指纹——同一份源文件内容只迁一次;
//! 2. **不丢值**:旧文件里 `auto_check: false` 必须迁成 `false`。默认值是 `true`,所以
//! 「用默认值兜底」会把用户的关闭状态**静默打开**——这是本条里最贵的一种错;
//! 3. **新值胜出**:主配置里**已经有**这个键时绝不覆盖(用户可能在前一版 GUI 之后手改过
//! `launcher.json`,或者刚从 CLI 设过)。旧文件照样退役,但不写字;
//! 4. **旧文件迁完不能再被读**:改名为 `prefs.json.migrated`(不删——留着是取证材料,
//! 但不再有任何读路径,`Prefs::load` 已经从宿主层删掉)。
//!
//! 写不进去(只读/不可读的 `launcher.json`)时**不退役旧文件**:宁可下一次再试,
//! 也不能让用户的值在两边都不存在。
use std::path::{Path, PathBuf};
use serde::Deserialize;
use serde_json::json;
use crate::platform::receipt::{self, MigrationReceipt};
use crate::setting::document::SettingDocument;
use crate::setting::keys::launcher_schema;
use crate::setting::store::SettingStore;
/// 主配置里的「启动时静默检查」键。
pub const KEY_AUTO_CHECK: &str = "update.auto_check";
/// 主配置里的「更新渠道」键。
pub const KEY_CHANNEL: &str = "update.channel";
/// 旧域内文件里的同义键(`serde` 的字段名,别改)。
pub const LEGACY_AUTO_CHECK: &str = "auto_check";
/// `update.auto_check` 的出厂值(与 `keys::launcher_schema` 里那份**必须一致**,契约用例守着)。
pub const DEFAULT_AUTO_CHECK: bool = true;
/// `update.channel` 的出厂值。
pub const DEFAULT_CHANNEL: &str = "stable";
/// 收据文件名(落在 `<数据根>/config/` 下;与数据目录迁移的 `migration-receipt.json` 分开)。
pub const RECEIPT_FILE: &str = "update-prefs-migration.json";
/// 旧文件退役后的后缀(`prefs.json` → `prefs.json.migrated`)。
pub const RETIRED_SUFFIX: &str = "migrated";
/// 迁移需要知道的三个路径(都由调用方按数据根算:core 不猜布局)。
#[derive(Debug, Clone, Copy)]
pub struct Targets<'a> {
/// `<数据根>/config/launcher.json`
pub launcher: &'a Path,
/// `<数据根>/cache/update/prefs.json`(旧域内文件)
pub legacy: &'a Path,
/// 收据落点(`<数据根>/config/update-prefs-migration.json`)
pub receipt: &'a Path,
}
/// 迁移结局(**每一种都要能被调用方如实转述**,不许折叠成 bool)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Migration {
/// 没有旧文件(绝大多数用户),或已经迁过(源指纹相同)。
Nothing,
/// 迁进去了:值来自旧文件。
Migrated {
/// 迁过去的取值
auto_check: bool,
/// 收据路径
receipt: PathBuf,
/// 退役后的旧文件路径
retired: PathBuf,
},
/// 主配置里已经有这个键 ⇒ 新值胜出,一个字都没写;旧文件照样退役。
NewValueWins {
/// 主配置里那个生效值
auto_check: bool,
/// 收据路径
receipt: PathBuf,
/// 退役后的旧文件路径
retired: PathBuf,
},
/// 旧文件读不出来(坏 JSON / 读失败):**什么都不动**,旧文件原样留着等下一次。
Unreadable {
/// 旧文件路径
path: PathBuf,
/// 原因(人读)
reason: String,
},
/// 主配置写不进去:不退役旧文件(用户的值不能两边都没有)。
Refused {
/// 原因(人读)
reason: String,
},
}
impl Migration {
/// 有没有真的改动主配置或旧文件。
#[must_use]
pub const fn touched(&self) -> bool {
matches!(self, Self::Migrated { .. } | Self::NewValueWins { .. })
}
/// 收据路径(没写收据时为 `None`)。
#[must_use]
pub fn receipt(&self) -> Option<&Path> {
match self {
Self::Migrated { receipt, .. } | Self::NewValueWins { receipt, .. } => Some(receipt),
_ => None,
}
}
/// 稳定 id(日志 / CLI 输出 / 测试用;**不要改名**)。
#[must_use]
pub const fn as_str(&self) -> &'static str {
match self {
Self::Nothing => "nothing",
Self::Migrated { .. } => "migrated",
Self::NewValueWins { .. } => "new_value_wins",
Self::Unreadable { .. } => "unreadable",
Self::Refused { .. } => "refused",
}
}
}
/// 旧域内文件的结构(只有一个字段,但**保留 `serde(default)`**:
/// 少了字段的旧文件按出厂值处理,而不是整个解析失败)。
#[derive(Debug, Clone, Copy, Deserialize)]
struct LegacyPrefs {
#[serde(default = "default_auto_check")]
auto_check: bool,
}
const fn default_auto_check() -> bool {
DEFAULT_AUTO_CHECK
}
/// 执行一次迁移(幂等)。
///
/// `now_ms` = 毫秒 since UNIX_EPOCH(注入便于断言收据内容)。
#[must_use]
pub fn migrate(targets: Targets<'_>, now_ms: u64) -> Migration {
let Ok(bytes) = std::fs::read(targets.legacy) else {
// 文件不在(或读不动=一样当没有):绝大多数用户走这一支。
return Migration::Nothing;
};
let fingerprint = receipt::fingerprint_bytes(&bytes);
// ① 收据闸门:同一份源文件内容只迁一次。
if matches!(
receipt::read(targets.receipt),
Ok(Some(existing)) if existing.source_fingerprint == fingerprint
) {
retire(targets.legacy);
return Migration::Nothing;
}
// ② 旧文件必须能解析:坏文件不猜(猜错就等于替用户关掉/打开自动检查)。
let legacy: LegacyPrefs = match serde_json::from_slice(&bytes) {
Ok(value) => value,
Err(error) => {
return Migration::Unreadable {
path: targets.legacy.to_path_buf(),
reason: error.to_string(),
}
}
};
let mut store = SettingStore::load(targets.launcher, launcher_schema());
if !store.access().can_save() {
return Migration::Refused {
reason: format!(
"主配置不可写({}):{}",
targets.launcher.display(),
store.access().as_str()
),
};
}
// ③ 新值胜出:主配置里**显式**有这个键就不覆盖(`effective` 会兜默认值,用 `get`)。
let explicit = store
.doc()
.get(KEY_AUTO_CHECK)
.and_then(serde_json::Value::as_bool);
let outcome = if let Some(current) = explicit {
Migration::NewValueWins {
auto_check: current,
receipt: targets.receipt.to_path_buf(),
retired: retired_path(targets.legacy),
}
} else {
// ④ 只在**非出厂值**时写盘:出厂值(`true`)不落盘是 `document` 的既定语义
// (「默认值不落盘」),写进去只是给文件添一行噪音。`false` 必须写。
if legacy.auto_check != DEFAULT_AUTO_CHECK {
if let Err(error) = store.set(KEY_AUTO_CHECK, json!(legacy.auto_check)) {
return Migration::Refused {
reason: format!("写 {KEY_AUTO_CHECK} 被拒:{error}"),
};
}
match store.save() {
Ok(saved) if saved.wrote() || !store.is_dirty() => {}
Ok(saved) => {
return Migration::Refused {
reason: format!("主配置没落盘({})", format_save(&saved)),
}
}
Err(error) => {
return Migration::Refused {
reason: format!("写主配置失败:{error}"),
}
}
}
}
Migration::Migrated {
auto_check: legacy.auto_check,
receipt: targets.receipt.to_path_buf(),
retired: retired_path(targets.legacy),
}
};
// ⑤ 收据(写不成也不回滚主配置:值已经在主配置里生效了,收据丢了下一次会重跑一遍,
// 而重跑是幂等的——正如「新值胜出」那一支不会覆盖)。
let record = MigrationReceipt::legacy_config(
targets.legacy.to_path_buf(),
targets.launcher.to_path_buf(),
fingerprint,
now_ms,
);
let _ = receipt::write(targets.receipt, &record);
// ⑥ 旧文件退役(改名失败就留着:主配置已经是真相源,`prefs.json` 不再有读路径)。
retire(targets.legacy);
outcome
}
/// 退役后的路径(`prefs.json` → `prefs.json.migrated`)。
#[must_use]
pub fn retired_path(legacy: &Path) -> PathBuf {
let name = legacy
.file_name()
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_else(|| "prefs.json".to_string());
legacy.with_file_name(format!("{name}.{RETIRED_SUFFIX}"))
}
/// 把旧文件改名成 `.migrated`(不存在 / 改不动都算成功:它不是真相源了)。
fn retire(legacy: &Path) {
if legacy.exists() {
let _ = std::fs::rename(legacy, retired_path(legacy));
}
}
fn format_save(outcome: &crate::setting::store::SaveOutcome) -> String {
match outcome {
crate::setting::store::SaveOutcome::Saved(path) => format!("已写 {}", path.display()),
crate::setting::store::SaveOutcome::Skipped(reason) => reason.as_str().to_string(),
}
}
/// 「启动时静默检查」的生效值(**唯一**取值点:宿主层与 CLI 都从这里读)。
#[must_use]
pub fn auto_check(doc: &SettingDocument) -> bool {
doc.effective_bool(KEY_AUTO_CHECK)
.unwrap_or(DEFAULT_AUTO_CHECK)
}
/// 「更新渠道」的生效值(同上;空串/坏值都回出厂渠道)。
#[must_use]
pub fn channel(doc: &SettingDocument) -> &str {
doc.effective_str(KEY_CHANNEL)
.filter(|text| !text.trim().is_empty())
.unwrap_or(DEFAULT_CHANNEL)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn retired_name_keeps_the_original_stem() {
assert_eq!(
retired_path(Path::new("/data/cache/update/prefs.json")),
Path::new("/data/cache/update/prefs.json.migrated")
);
}
#[test]
fn defaults_agree_with_the_schema() {
// 契约:本文件里的常量与 `keys::launcher_schema()` 的默认值必须一致
// (两份字面量漂移 = 「迁过去的值」和「不迁时的值」不同)。
let schema = launcher_schema();
assert_eq!(
schema.spec(KEY_AUTO_CHECK).expect("键已登记").default,
json!(DEFAULT_AUTO_CHECK)
);
assert_eq!(
schema.spec(KEY_CHANNEL).expect("键已登记").default,
json!(DEFAULT_CHANNEL)
);
}
}
+2 -2
View File
@@ -131,8 +131,8 @@ fn appearance_keys_are_all_ai_writable_and_registered() {
fn schema_registration_shape_is_right() {
assert_eq!(
launcher_version().minor,
5,
"1.5.0 登记 M116 的窗口圆角策略键"
6,
"1.6.0 登记 M161 的自更新两键(update.auto_check / update.channel)"
);
let schema = launcher_schema();
assert_eq!(
+3 -2
View File
@@ -128,9 +128,10 @@ fn overrides_key_is_an_enum_whitelist() {
#[test]
fn schema_versions_register_the_new_keys_without_migration() {
// 1.5.0 登记 M116 的窗口圆角策略键(1.4.0 = M91 外观下层三键,1.3.0 = D17「外观(高级)」,
// 1.6.0 登记 M161 的自更新两键(`update.auto_check` / `update.channel`;
// 1.5.0 = M116 窗口圆角,1.4.0 = M91 外观下层三键,1.3.0 = D17「外观(高级)」,
// 1.2.0 = D23 的 JDK 落点/优先级键)。
assert_eq!(launcher_version(), SchemaVersion::new(1, 5, 0));
assert_eq!(launcher_version(), SchemaVersion::new(1, 6, 0));
assert_eq!(instance_version(), SchemaVersion::new(1, 1, 0));
assert_eq!(launcher_schema().id(), SchemaId::LAUNCHER);
// major 仍是 1:迁移链(按 major 走)不需要新步骤,老文件缺键即默认值。
@@ -66,7 +66,8 @@ fn install_root_accepts_a_path_and_keeps_empty_as_unset() {
#[test]
fn schema_version_bumps_minor_only_so_no_migration_step_is_needed() {
assert_eq!(launcher_version(), SchemaVersion::new(1, 5, 0));
// 1.6.0 = M161 的自更新两键(此前 1.5.0 是 M116 窗口圆角)。
assert_eq!(launcher_version(), SchemaVersion::new(1, 6, 0));
assert_eq!(
launcher_version().major,
1,
+1
View File
@@ -19,3 +19,4 @@ mod redirect;
mod schema_compat;
mod spec_ai;
mod store;
mod update_keys;
+234
View File
@@ -0,0 +1,234 @@
//! M161:`update.auto_check` / `update.channel` 的 schema 契约 + 旧 `cache/update/prefs.json` 的迁移。
//!
//! 迁移的四条硬约束在这里逐条钉住(幂等 / 不丢 `false` / 新值胜出 / 旧文件退役),
//! 另外还有一条 schema 层面的:`update.channel` 现在只允许 `stable`——清单里没有的渠道
//! 写进文件等于「设了但没生效」,宁可让 `config set` 当面拒绝。
use serde_json::json;
use unlucky_core::setting::document::{RenderMode, SettingDocument};
use unlucky_core::setting::keys::launcher_schema;
use unlucky_core::setting::keys::update::UPDATE_CHANNELS;
use unlucky_core::setting::spec::{Sensitivity, ValueKind};
use unlucky_core::setting::store::SettingStore;
use unlucky_core::setting::update_prefs::{
self, Migration, Targets, DEFAULT_AUTO_CHECK, DEFAULT_CHANNEL, KEY_AUTO_CHECK, KEY_CHANNEL,
RECEIPT_FILE,
};
use super::common::TempDir;
/// 三个路径(`<root>/config/launcher.json` + `<root>/cache/update/prefs.json` + 收据)。
fn targets(_temp: &TempDir) -> (String, String, String) {
(
"config/launcher.json".to_string(),
"cache/update/prefs.json".to_string(),
format!("config/{RECEIPT_FILE}"),
)
}
fn run(temp: &TempDir) -> Migration {
let (launcher, legacy, receipt) = targets(temp);
update_prefs::migrate(
Targets {
launcher: &temp.child(&launcher),
legacy: &temp.child(&legacy),
receipt: &temp.child(&receipt),
},
1_700_000_000_000,
)
}
/// 读主配置里的显式值(`None` = 文件里没这个键)。
fn explicit(temp: &TempDir, key: &str) -> Option<serde_json::Value> {
let store = SettingStore::load(temp.child("config/launcher.json"), launcher_schema());
store.doc().get(key).cloned()
}
#[test]
fn the_two_keys_are_registered_with_the_expected_shape() {
let schema = launcher_schema();
let auto = schema
.spec(KEY_AUTO_CHECK)
.expect("update.auto_check 必须登记");
assert_eq!(auto.default, json!(DEFAULT_AUTO_CHECK), "出厂是开");
assert_eq!(auto.kind, ValueKind::Bool);
assert_eq!(
auto.ai.sensitivity,
Sensitivity::Medium,
"改它会让启动器自己下载并替换 exe,AI 改过要留审计痕迹"
);
let channel = schema.spec(KEY_CHANNEL).expect("update.channel 必须登记");
assert_eq!(channel.default, json!(DEFAULT_CHANNEL));
assert_eq!(channel.kind, ValueKind::Enum(UPDATE_CHANNELS));
assert!(schema.validate(KEY_CHANNEL, &json!("stable")).is_ok());
// 清单里还没有的渠道:**当面拒绝**(写进文件等于「设了但没生效」)。
assert!(schema.validate(KEY_CHANNEL, &json!("beta")).is_err());
assert!(schema.validate(KEY_CHANNEL, &json!("nightly")).is_err());
assert!(schema.validate(KEY_AUTO_CHECK, &json!(1)).is_err());
}
#[test]
fn the_keys_render_in_the_nested_shape() {
let (mut document, problems) = SettingDocument::load(&launcher_schema(), &json!({}));
assert!(problems.is_empty(), "{problems:?}");
// 默认值不落盘:空文档渲染出来不该有 update 段。
assert!(
document.render(RenderMode::Full).get("update").is_none(),
"出厂值不该写进文件"
);
document.set(KEY_AUTO_CHECK, json!(false)).expect("写");
document.set(KEY_CHANNEL, json!("stable")).expect("写");
let rendered = document.render(RenderMode::Full);
assert_eq!(
rendered["update"],
json!({ "auto_check": false, "channel": "stable" }),
"点分键在文件里是嵌套对象(与既有键同一形状)"
);
// 读回来也要是同一个值(IPC/CLI 都读这一份)。
let (reloaded, problems) = SettingDocument::load(&launcher_schema(), &rendered);
assert!(problems.is_empty(), "{problems:?}");
assert!(
!update_prefs::auto_check(&reloaded),
"读回来的生效值必须是文件里的 false"
);
assert_eq!(update_prefs::channel(&reloaded), "stable");
}
#[test]
fn a_false_switch_is_migrated_and_the_old_file_is_retired() {
let temp = TempDir::new("m161-migrate-false");
temp.write("cache/update/prefs.json", r#"{"auto_check": false}"#);
let outcome = run(&temp);
let Migration::Migrated {
auto_check,
retired,
receipt,
} = outcome.clone()
else {
panic!("应当迁入,实际 {outcome:?}");
};
assert!(!auto_check, "旧文件里的 false 不许被默认值盖掉");
// 主配置里是显式的 false(不是「缺键取默认」)。
assert_eq!(explicit(&temp, KEY_AUTO_CHECK), Some(json!(false)));
// 旧文件不能再被读到。
assert!(!temp.exists("cache/update/prefs.json"), "旧文件必须退役");
assert!(temp.exists("cache/update/prefs.json.migrated"), "留着取证");
assert_eq!(retired, temp.child("cache/update/prefs.json.migrated"));
// 收据可查:落盘、类型/指纹/端点齐全。
assert!(receipt.exists(), "收据要落盘:{}", receipt.display());
let text = temp.read(&format!("config/{RECEIPT_FILE}"));
assert!(text.contains("\"legacy_config\""), "{text}");
assert!(text.contains("prefs.json"), "{text}");
assert!(text.contains("launcher.json"), "{text}");
assert!(text.contains("\"applied_at_ms\": 1700000000000"), "{text}");
}
#[test]
fn running_twice_is_idempotent() {
let temp = TempDir::new("m161-migrate-twice");
temp.write("cache/update/prefs.json", r#"{"auto_check": false}"#);
assert!(run(&temp).touched(), "第一遍要真的动手");
let after_first = temp.read("config/launcher.json");
let receipt_first = temp.read(&format!("config/{RECEIPT_FILE}"));
// 第二遍:旧文件已经改名 ⇒ 什么都没得做。
let second = run(&temp);
assert_eq!(second, Migration::Nothing, "第二遍必须是空操作");
assert_eq!(temp.read("config/launcher.json"), after_first, "文件不许变");
assert_eq!(
temp.read(&format!("config/{RECEIPT_FILE}")),
receipt_first,
"收据也不该被重写(源指纹相同 = 跳过)"
);
}
#[test]
fn a_missing_legacy_file_is_a_silent_noop() {
let temp = TempDir::new("m161-migrate-absent");
assert_eq!(run(&temp), Migration::Nothing);
// 连主配置都不该建(没有值要写,就不该白建一个文件)。
assert!(!temp.exists("config/launcher.json"), "不该凭空建配置");
assert!(
!temp.exists(&format!("config/{RECEIPT_FILE}")),
"不该写收据"
);
}
#[test]
fn an_explicit_new_value_wins_over_the_legacy_file() {
let temp = TempDir::new("m161-migrate-new-wins");
temp.write(
"config/launcher.json",
&json!({
"$schema": schema_url(),
"schemaVersion": 1,
"update": { "auto_check": true }
})
.to_string(),
);
temp.write("cache/update/prefs.json", r#"{"auto_check": false}"#);
let outcome = run(&temp);
assert_eq!(
outcome.as_str(),
"new_value_wins",
"主配置里有显式值时不许覆盖:{outcome:?}"
);
assert_eq!(
explicit(&temp, KEY_AUTO_CHECK),
Some(json!(true)),
"新值胜出"
);
// 旧文件照样退役(它已经不是真相源),收据也写了。
assert!(!temp.exists("cache/update/prefs.json"));
assert!(temp.exists(&format!("config/{RECEIPT_FILE}")));
}
#[test]
fn the_default_true_is_not_written_but_the_file_still_retires() {
let temp = TempDir::new("m161-migrate-default");
temp.write("cache/update/prefs.json", r#"{"auto_check": true}"#);
let outcome = run(&temp);
assert_eq!(outcome.as_str(), "migrated");
// 「默认值不落盘」:写进去只是噪音,生效值本来就是 true。
assert_eq!(explicit(&temp, KEY_AUTO_CHECK), None, "出厂值不落盘");
assert!(!temp.exists("cache/update/prefs.json"), "旧文件仍要退役");
let store = SettingStore::load(temp.child("config/launcher.json"), launcher_schema());
assert!(update_prefs::auto_check(store.doc()));
}
#[test]
fn a_corrupt_legacy_file_touches_nothing() {
let temp = TempDir::new("m161-migrate-corrupt");
temp.write("cache/update/prefs.json", "{ not json");
let outcome = run(&temp);
assert_eq!(outcome.as_str(), "unreadable", "{outcome:?}");
// 坏文件保持原样:下一次还能再试(我们既不猜值也不删证据)。
assert!(temp.exists("cache/update/prefs.json"));
assert!(!temp.exists(&format!("config/{RECEIPT_FILE}")));
}
#[test]
fn an_empty_legacy_file_still_means_the_default() {
// `serde(default)`:老文件里没有 auto_check 字段(或整份是 `{}`)⇒ 按出厂值处理,
// 而不是把整份文件判成坏文件。
let temp = TempDir::new("m161-migrate-empty");
temp.write("cache/update/prefs.json", "{}");
let outcome = run(&temp);
assert_eq!(outcome.as_str(), "migrated");
let store = SettingStore::load(temp.child("config/launcher.json"), launcher_schema());
assert!(update_prefs::auto_check(store.doc()), "缺字段取出厂值 true");
}
/// 真 `$schema`(加载不降级才看得到显式值)。
fn schema_url() -> String {
use unlucky_core::setting::keys::launcher_version;
use unlucky_core::setting::schema::{SchemaId, SchemaRef};
SchemaRef::new(SchemaId::LAUNCHER, launcher_version()).url()
}