From 4405152729aed7a71f985d327ea9f0bd74916fbc Mon Sep 17 00:00:00 2001 From: eddybean <38001995+eddybean@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:55:42 +0900 Subject: [PATCH] Version settings.json and voices.json, and set unreadable or newer files aside (D-61) settings.json had a version nothing read: when it failed to parse, the app saved first-run settings over it and the user's profiles were lost. voices.json was a bare list with no version: when it failed to parse, the next new voice overwrote the list. - stored.rs: shared loader. Reads the format version, upgrades an older file one step at a time with the file's migrate, moves an unreadable file to .broken- and copies a newer one to .v- before going on, and returns a notice for the user. - settings.json: SETTINGS_VERSION, migrate, and extra members kept. - voices.json: now {version, voices}; the bare list reads as v0. Voices keep unknown members too. - .vsproj: a migrate step on load beside the existing TooNew check. - take_startup_notices: the UI shows the notices at start. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 1 + docs/architecture.md | 5 +- docs/decisions/D-61-file-format-versions.md | 53 +++++ docs/decisions/README.md | 3 +- src-tauri/src/commands.rs | 8 + src-tauri/src/lib.rs | 12 +- src-tauri/src/project.rs | 20 +- src-tauri/src/settings.rs | 70 ++++++- src-tauri/src/stored.rs | 220 ++++++++++++++++++++ src-tauri/src/voices.rs | 102 +++++++-- src/lib/ipc.ts | 2 + src/store/app.ts | 2 + 12 files changed, 472 insertions(+), 26 deletions(-) create mode 100644 docs/decisions/D-61-file-format-versions.md create mode 100644 src-tauri/src/stored.rs diff --git a/CLAUDE.md b/CLAUDE.md index dddcd71..174f0ce 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -65,6 +65,7 @@ VS_SPEECH_EXE=.engine/speech.exe VS_DRAMA_MODEL=path/to/Drama-35B-A3B-Japanese-v **Persistence.** - A project is a `.vsproj` JSON file plus a `.takes/` folder of WAVs. The `.vsproj` records the folder name (`takesDir`) and an `id` that the folder's `.speechorus-project` marker repeats, so a hand-renamed `.vsproj` still finds its takes and the next save renames the folder (D-49). `project_prune` removes WAVs that are no longer referenced. - App settings (model profiles: adapter, GGUF, speech.exe, device, env; the playback volume, D-46) are stored in the app config dir as `settings.json`. A `catalog.json` there overrides the bundled catalog. +- `.vsproj`, `settings.json` and `voices.json` carry a format `version`, upgraded on load by each file's `migrate`; members a newer version added are kept (`extra`). An unreadable or newer `settings.json`/`voices.json` is moved or copied aside (`stored.rs`) instead of being overwritten, and the user is told at start (D-61). Raise the version, with a migrate step, for any change that would read an older file wrongly. - The voice library (`.voice.gguf` files) lives in the app data dir under `voices/`. - Scratch audio lives in `work//` in the local app data dir, one per running instance and locked by its `.lock` (`work.rs`, D-39): untitled projects' takes, `design/` candidates and `trimmed/` references. At start, folders that no running instance holds are swept. diff --git a/docs/architecture.md b/docs/architecture.md index ac713ed..169d52a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -85,7 +85,10 @@ bracket cues and speaker tokens (D-04). Tag palettes: `assets/tags/*.json`; cata saves keep the WAVs the history can bring back (D-40, D-41). - **App settings** (`settings.json` in the app config dir): profiles, the active profile, speech.exe, the ASR model, theme, tags, recent projects, volume, memory guard. A `catalog.json` there overrides the bundled catalog. -- **Voice library**: app data dir, `voices/` (D-06). +- **Voice library**: app data dir, `voices/` (D-06); `voices.json` lists the voices. +- **Format versions** (D-61): `.vsproj`, `settings.json` and `voices.json` carry a `version`, upgraded on load by + each file's `migrate`, and keep members a newer version added. A newer project is refused; an unreadable or newer + `settings.json` / `voices.json` is moved or copied aside (`stored.rs`) and the user is told at start. - **Scratch audio**: `work//` in the local app data dir, one per running instance (D-39). ## Front end diff --git a/docs/decisions/D-61-file-format-versions.md b/docs/decisions/D-61-file-format-versions.md new file mode 100644 index 0000000..0239ba6 --- /dev/null +++ b/docs/decisions/D-61-file-format-versions.md @@ -0,0 +1,53 @@ +# D-61 Saved files carry a format version; unreadable or newer app files are set aside, never overwritten + +- **Status**: Accepted (2026-11-28) +- **Code**: `src-tauri/src/stored.rs`, `src-tauri/src/settings.rs` (`SETTINGS_VERSION`, `migrate`), + `src-tauri/src/voices.rs` (`VOICES_VERSION`, `migrate`), `src-tauri/src/project.rs` (`PROJECT_VERSION`, `migrate`), + `src-tauri/src/lib.rs`, `commands.rs` (`take_startup_notices`), `src/store/app.ts` + +## Context + +`.vsproj` already had a `version`, refused a newer project and kept members it did not know (`extra`). The app's own +files did not: + +- `settings.json` had a `version` that nothing read. When it failed to parse (a damaged file, or a future change of + a member's type), the app started with first-run settings and saved them over it, so the user's profiles were lost + without a word. Members a newer version had added were dropped by the next save. +- `voices.json` was a bare list with no version. When it failed to parse, the library opened empty and the next new + voice overwrote the list; the `.voice.gguf` files stayed, but their names and references were lost. + +So a breaking change to either file, or a newer build followed by an older one, could destroy user data. + +## Decision + +- `.vsproj`, `settings.json` and `voices.json` each have a format version (`PROJECT_VERSION`, `SETTINGS_VERSION`, + `VOICES_VERSION`, all 1) and a `migrate(value, from)` that upgrades the JSON one version at a time on load. Raise + the version, with a step, only when a change would read an older file wrongly (a member renamed, moved or given + another meaning); adding a member with a serde default needs neither. +- `voices.json` becomes `{"version": 1, "voices": [...]}`. The old bare list reads as version 0 and is upgraded. +- All three keep members they do not know (`#[serde(flatten)] extra`, also on each `Voice`), so an older build saving + a newer file does not drop them. +- `settings.json` and `voices.json` (`stored::load`): + - Unreadable (not JSON, wrong shape, a failed migration, or a read error): the file is renamed to + `.broken-` and the app goes on with the defaults. + - Newer than this build: it is copied to `.v-` (once; later starts reuse the copy) and read + as far as this build understands it. The next save writes this build's version. + - Either way the user gets a notice at start (`take_startup_notices`, shown as an error notice so it stays up for 12 s) + with the path of the file set aside. +- A newer `.vsproj` is still refused (`TooNew`): it is the user's document, and opening it read-only is not offered. + +## Alternatives not taken + +- Refusing to start on an unreadable or newer `settings.json`: the user could then not reach the settings to fix it. +- Keeping the newer version number when an older build saves: a newer build would then skip the migration for data + the older build wrote in the older shape. Writing this build's version makes the newer build migrate again, and the + copy keeps the original. +- A version per profile or per voice: one per file is enough while the file is written as a whole. + +## Consequences + +- A newer build's settings, read by an older build, may lose meaning that was not expressed in members the older + build knows; the `.v-…` copy is there to restore by hand. +- Backups are not cleaned up; they are small and few (one per incident). +- `catalog.json` (an override in the config folder) is not covered: an unreadable one already falls back to the + bundled catalog, and nothing writes to it. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 64c300d..cfb4cdf 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -83,8 +83,9 @@ Sections that have nothing to say may be left out. Mention the user only for dec | [D-58](D-58-memory-guard.md) | A free-memory check before the engine starts | engine | | [D-59](D-59-explicit-downloads.md) | Models are resolved from `speech models`; only the catalog downloads | engine, models | | [D-60](D-60-bump-app-token.md) | The release PR is opened with a GitHub App token, not `GITHUB_TOKEN` | CI, release | +| [D-61](D-61-file-format-versions.md) | Saved files carry a format version; unreadable or newer app files are set aside | project, settings, voices | -Next free ID: D-61. +Next free ID: D-62. ## Retired diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 2cbb522..2242dcf 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -30,6 +30,8 @@ pub struct AppState { pub catalog_override: PathBuf, /// What the running engine holds on its device, to count as free when another start stops it (D-58). pub engine_memory: Arc>>, + /// What loading the app's own files found that the user should know (a file moved aside, D-61). + pub startup_notices: Mutex>, } type R = Result; @@ -61,6 +63,12 @@ pub fn get_settings(st: State<'_, AppState>) -> AppSettings { st.settings.lock().unwrap().clone() } +/// The startup notices, once: a second call returns none. +#[tauri::command] +pub fn take_startup_notices(st: State<'_, AppState>) -> Vec { + std::mem::take(&mut *st.startup_notices.lock().unwrap()) +} + #[tauri::command] pub fn save_settings(st: State<'_, AppState>, settings: AppSettings) -> R<()> { settings.save(&st.settings_path).map_err(e)?; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 2b4c72e..e8fdccf 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -12,6 +12,7 @@ mod memory; pub mod models; pub mod project; pub mod settings; +pub mod stored; pub mod tools; pub mod voices; pub mod work; @@ -69,7 +70,11 @@ pub fn run() { let data = app.path().app_data_dir()?; let local = app.path().app_local_data_dir()?; let settings_path = cfg.join("settings.json"); - let settings = settings::AppSettings::load(&settings_path) + let mut notices = Vec::new(); + let loaded = settings::AppSettings::load(&settings_path); + notices.extend(loaded.notice); + let settings = loaded + .value .map(|mut s| { s.speech_exe = strip_verbatim(&s.speech_exe); for p in &mut s.profiles { @@ -82,7 +87,8 @@ pub fn run() { let _ = s.save(&settings_path); s }); - let voices = voices::VoiceLibrary::open(&data.join("voices")); + let (voices, notice) = voices::VoiceLibrary::open(&data.join("voices")); + notices.extend(notice); let _ = app.asset_protocol_scope().allow_directory(&voices.dir, true); // Trimmed references used to be kept here (before D-39); they now live in the work folder. let _ = std::fs::remove_dir_all(voices.dir.join(work::TRIMMED)); @@ -100,11 +106,13 @@ pub fn run() { downloads: Default::default(), catalog_override: cfg.join("catalog.json"), engine_memory: Default::default(), + startup_notices: Mutex::new(notices), }); Ok(()) }) .invoke_handler(tauri::generate_handler![ commands::get_settings, + commands::take_startup_notices, commands::save_settings, commands::new_profile, commands::list_adapters, diff --git a/src-tauri/src/project.rs b/src-tauri/src/project.rs index 543238d..c1ac0cc 100644 --- a/src-tauri/src/project.rs +++ b/src-tauri/src/project.rs @@ -132,6 +132,15 @@ pub enum ProjectError { Json(#[from] serde_json::Error), #[error("このプロジェクトは新しいバージョン ({0}) で保存されています")] TooNew(u32), + #[error("プロジェクトを今の形式に変換できません: {0}")] + Migrate(String), +} + +/// Upgrades a `.vsproj` from version `from` to `from + 1` (D-61). Raise [`PROJECT_VERSION`] with a step here when a +/// change would read an older project wrongly; adding a member with a default needs neither. There is no older +/// format yet. +fn migrate(_v: &mut Value, from: u32) -> Result<(), String> { + Err(format!("v{from} からの変換方法がありません")) } /// `dir/name.vsproj` → `dir/name.takes`. @@ -259,10 +268,15 @@ pub fn save_project( pub fn load_project(path: &Path) -> Result<(Project, PathBuf), ProjectError> { let s = std::fs::read_to_string(path).map_err(|e| ProjectError::Io(path.display().to_string(), e))?; - let p: Project = serde_json::from_str(&s)?; - if p.version > PROJECT_VERSION { - return Err(ProjectError::TooNew(p.version)); + let mut v: Value = serde_json::from_str(&s)?; + let version = crate::stored::version_member(&v, PROJECT_VERSION); + if version > PROJECT_VERSION { + return Err(ProjectError::TooNew(version)); + } + for from in version..PROJECT_VERSION { + migrate(&mut v, from).map_err(ProjectError::Migrate)?; } + let p: Project = serde_json::from_value(v)?; let dir = find_takes_dir(path, &p); Ok((p, dir)) } diff --git a/src-tauri/src/settings.rs b/src-tauri/src/settings.rs index d353d9b..2616390 100644 --- a/src-tauri/src/settings.rs +++ b/src-tauri/src/settings.rs @@ -4,8 +4,15 @@ use std::collections::BTreeMap; use std::path::Path; use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; use crate::memguard::GuardLevel; +use crate::stored; + +/// The format of `settings.json` this version writes (D-61). Raise it with a step in [`migrate`] when a change +/// would read an older file wrongly (a member renamed, moved or given another meaning); adding a member with a +/// default needs neither. +pub const SETTINGS_VERSION: u32 = 1; use crate::models::adapter_for; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] @@ -74,12 +81,15 @@ pub struct AppSettings { pub playback_muted: bool, /// System protection: how hard the free-memory check before an engine start is (D-58). pub memory_guard: GuardLevel, + /// Members a later version added; kept as they are. + #[serde(flatten)] + pub extra: Map, } impl Default for AppSettings { fn default() -> Self { AppSettings { - version: 1, + version: SETTINGS_VERSION, profiles: Vec::new(), active_profile_id: None, speech_exe: String::new(), @@ -92,6 +102,7 @@ impl Default for AppSettings { playback_volume: 1.0, playback_muted: false, memory_guard: GuardLevel::default(), + extra: Map::new(), } } } @@ -116,16 +127,30 @@ impl AppSettings { self.profiles.iter().find(|p| p.id == id) } - pub fn load(path: &Path) -> Option { - let s = std::fs::read_to_string(path).ok()?; - serde_json::from_str(&s).ok() + /// Reads `settings.json`, upgrading an older format. A file that cannot be read is moved aside (value None), so + /// the first-run settings saved in its place do not destroy it; the notice says where it went. + pub fn load(path: &Path) -> stored::Loaded { + let mut l: stored::Loaded = stored::load( + path, + SETTINGS_VERSION, + |v| stored::version_member(v, 1), + migrate, + "アプリ設定 (settings.json)", + ); + if let Some(s) = &mut l.value { + // Saved from now on in this version's format. + s.version = SETTINGS_VERSION; + } + l } pub fn save(&self, path: &Path) -> std::io::Result<()> { if let Some(d) = path.parent() { std::fs::create_dir_all(d)?; } - crate::project::write_atomic(path, serde_json::to_string_pretty(self)?.as_bytes()) + let mut s = self.clone(); + s.version = SETTINGS_VERSION; + crate::project::write_atomic(path, serde_json::to_string_pretty(&s)?.as_bytes()) } pub fn push_recent_project(&mut self, p: &str) { @@ -135,6 +160,12 @@ impl AppSettings { } } +/// Upgrades `settings.json` from version `from` to `from + 1`. There is no older format yet: the first step goes here +/// as `1 => { … }`, followed by setting `version`. +fn migrate(_v: &mut Value, from: u32) -> Result<(), String> { + Err(format!("v{from} からの変換方法がありません")) +} + #[cfg(test)] mod tests { use super::*; @@ -157,7 +188,7 @@ mod tests { s.push_recent_project("b.vsproj"); s.push_recent_project("a.vsproj"); s.save(&p).unwrap(); - assert_eq!(AppSettings::load(&p).unwrap(), s); + assert_eq!(AppSettings::load(&p).value.unwrap(), s); assert_eq!(s.recent_projects, ["a.vsproj", "b.vsproj"]); let partial: AppSettings = serde_json::from_str(r#"{"showNsfwTags":true}"#).unwrap(); assert!(partial.show_nsfw_tags); @@ -166,4 +197,31 @@ mod tests { assert!(!partial.playback_muted); assert_eq!(partial.memory_guard, GuardLevel::Standard); } + + #[test] + fn unreadable_settings_are_moved_aside_not_overwritten() { + let dir = tempfile::tempdir().unwrap(); + let p = dir.path().join("settings.json"); + std::fs::write(&p, r#"{"profiles":"not a list"}"#).unwrap(); + let l = AppSettings::load(&p); + assert!(l.value.is_none()); + assert!(l.notice.unwrap().contains("settings.json.broken-")); + assert!(!p.exists()); + } + + #[test] + fn newer_settings_keep_unknown_members() { + let dir = tempfile::tempdir().unwrap(); + let p = dir.path().join("settings.json"); + std::fs::write(&p, r#"{"version":9,"theme":"light","futureThing":{"a":1}}"#).unwrap(); + let l = AppSettings::load(&p); + assert!(l.notice.unwrap().contains("v9")); + let s = l.value.unwrap(); + assert_eq!(s.theme, "light"); + assert_eq!(s.version, SETTINGS_VERSION); + s.save(&p).unwrap(); + let back: Value = serde_json::from_str(&std::fs::read_to_string(&p).unwrap()).unwrap(); + assert_eq!(back["futureThing"]["a"], 1); + assert_eq!(back["version"], SETTINGS_VERSION); + } } diff --git a/src-tauri/src/stored.rs b/src-tauri/src/stored.rs new file mode 100644 index 0000000..24eb0c9 --- /dev/null +++ b/src-tauri/src/stored.rs @@ -0,0 +1,220 @@ +//! Versioned JSON files the app keeps for itself (`settings.json`, `voices.json`) (D-61). +//! +//! Each file carries a format version. Loading reads it, upgrades an older file one step at a time with the caller's +//! `migrate`, and turns the result into the caller's type. A file that cannot be read is moved aside, and a file +//! written by a newer version is copied aside, before the app goes on, so that the next save never silently replaces +//! what the user had. The caller shows `notice` to the user. + +use std::path::{Path, PathBuf}; + +use serde::de::DeserializeOwned; +use serde_json::Value; + +/// What [`load`] found. +pub struct Loaded { + /// None when there is no file, or when it could not be read (it was moved aside; see `notice`). + pub value: Option, + /// Something the user should be told: the file was unreadable, or newer than this version. + pub notice: Option, +} + +/// One step of an upgrade: turns a file of version `from` into version `from + 1`. +pub type Migrate = fn(&mut Value, u32) -> Result<(), String>; + +/// Reads `path`, a JSON file of format `current`. +/// - `version_of` gives the version of a file as read (for a file older than the version member, what it was). +/// - `migrate` is called for each version from the file's up to `current - 1`. +/// - `what` names the file to the user (`アプリ設定`). +pub fn load( + path: &Path, + current: u32, + version_of: fn(&Value) -> u32, + migrate: Migrate, + what: &str, +) -> Loaded { + let text = match std::fs::read_to_string(path) { + Ok(t) => t, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Loaded { value: None, notice: None }, + Err(e) => return unreadable(path, what, &e.to_string()), + }; + let mut v: Value = match serde_json::from_str(&text) { + Ok(v) => v, + Err(e) => return unreadable(path, what, &e.to_string()), + }; + let version = version_of(&v); + let mut notice = None; + if version > current { + // Read what this version understands; members it does not know are kept by the caller's `extra`. The next + // save writes this version's format, so keep the newer file as it was. + // One copy is enough: until this version saves, every start finds the same newer file. + let tag = format!("v{version}"); + let (kept, copied) = match existing_backup(path, &tag) { + Some(k) => (k, Ok(0)), + None => { + let k = backup_path(path, &tag); + let r = std::fs::copy(path, &k); + (k, r) + } + }; + notice = Some(match copied { + Ok(_) => format!( + "{what}は新しいバージョンの形式 (v{version}) で保存されています。読める範囲で読み込みました。元のファイルは {} に残しています。", + kept.display() + ), + Err(e) => format!( + "{what}は新しいバージョンの形式 (v{version}) で保存されています。読める範囲で読み込みましたが、元のファイルを残せませんでした ({e})。" + ), + }); + } else { + for from in version..current { + if let Err(e) = migrate(&mut v, from) { + return unreadable(path, what, &format!("v{from} からの変換に失敗: {e}")); + } + } + } + match serde_json::from_value(v) { + Ok(t) => Loaded { value: Some(t), notice }, + Err(e) => unreadable(path, what, &e.to_string()), + } +} + +/// Moves an unreadable file aside, so that the defaults the caller goes on with do not overwrite it. +fn unreadable(path: &Path, what: &str, why: &str) -> Loaded { + let aside = backup_path(path, "broken"); + let notice = match std::fs::rename(path, &aside) { + Ok(()) => format!( + "{what}を読めなかったため初期設定で起動しました ({why})。元のファイルは {} に移しました。", + aside.display() + ), + Err(e) => format!( + "{what}を読めなかったため初期設定で起動しました ({why})。元のファイルを退避できませんでした ({e})。" + ), + }; + Loaded { value: None, notice: Some(notice) } +} + +/// `settings.json` → `settings.json.-` (with `-2`, `-3`… when that exists). +fn backup_path(path: &Path, tag: &str) -> PathBuf { + let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let base = path.with_file_name(format!("{name}.{tag}-{secs}")); + let mut p = base.clone(); + let mut n = 2; + while p.exists() { + p = PathBuf::from(format!("{}-{n}", base.display())); + n += 1; + } + p +} + +/// A backup made earlier by [`backup_path`] with this tag. +fn existing_backup(path: &Path, tag: &str) -> Option { + let name = path.file_name()?.to_string_lossy().into_owned(); + let prefix = format!("{name}.{tag}-"); + std::fs::read_dir(path.parent()?) + .ok()? + .flatten() + .find(|e| e.file_name().to_string_lossy().starts_with(&prefix)) + .map(|e| e.path()) +} + +/// The `version` member of an object, or `default` when it has none. +pub fn version_member(v: &Value, default: u32) -> u32 { + v.get("version").and_then(Value::as_u64).map(|n| n.min(u32::MAX as u64) as u32).unwrap_or(default) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde::Deserialize; + + #[derive(Debug, Deserialize, PartialEq)] + struct Doc { + version: u32, + name: String, + } + + fn version_of(v: &Value) -> u32 { + version_member(v, 1) + } + + /// v1 had `title`; v2 calls it `name`. + fn migrate(v: &mut Value, from: u32) -> Result<(), String> { + let o = v.as_object_mut().ok_or("not an object")?; + match from { + 1 => { + let t = o.remove("title").unwrap_or_default(); + o.insert("name".into(), t); + } + _ => return Err(format!("unknown version {from}")), + } + o.insert("version".into(), (from + 1).into()); + Ok(()) + } + + fn files(dir: &Path) -> Vec { + let mut v: Vec = + std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + v.sort(); + v + } + + #[test] + fn missing_file_is_quiet() { + let d = tempfile::tempdir().unwrap(); + let l: Loaded = load(&d.path().join("a.json"), 2, version_of, migrate, "テスト"); + assert!(l.value.is_none() && l.notice.is_none()); + } + + #[test] + fn older_file_is_migrated() { + let d = tempfile::tempdir().unwrap(); + let p = d.path().join("a.json"); + std::fs::write(&p, r#"{"title":"x"}"#).unwrap(); + let l: Loaded = load(&p, 2, version_of, migrate, "テスト"); + assert_eq!(l.value.unwrap(), Doc { version: 2, name: "x".into() }); + assert!(l.notice.is_none()); + assert_eq!(files(d.path()), ["a.json"]); + } + + #[test] + fn broken_file_is_moved_aside() { + let d = tempfile::tempdir().unwrap(); + let p = d.path().join("a.json"); + std::fs::write(&p, "{ not json").unwrap(); + let l: Loaded = load(&p, 2, version_of, migrate, "テスト"); + assert!(l.value.is_none()); + assert!(l.notice.unwrap().contains("読めなかった")); + let f = files(d.path()); + assert_eq!(f.len(), 1); + assert!(f[0].starts_with("a.json.broken-")); + assert_eq!(std::fs::read_to_string(d.path().join(&f[0])).unwrap(), "{ not json"); + } + + #[test] + fn wrong_shape_is_moved_aside_too() { + let d = tempfile::tempdir().unwrap(); + let p = d.path().join("a.json"); + std::fs::write(&p, r#"{"version":2,"name":5}"#).unwrap(); + let l: Loaded = load(&p, 2, version_of, migrate, "テスト"); + assert!(l.value.is_none() && l.notice.is_some()); + assert!(!p.exists()); + } + + #[test] + fn newer_file_is_read_and_copied_aside() { + let d = tempfile::tempdir().unwrap(); + let p = d.path().join("a.json"); + std::fs::write(&p, r#"{"version":3,"name":"y","more":1}"#).unwrap(); + let l: Loaded = load(&p, 2, version_of, migrate, "テスト"); + assert_eq!(l.value.unwrap(), Doc { version: 3, name: "y".into() }); + assert!(l.notice.unwrap().contains("v3")); + let f = files(d.path()); + assert_eq!(f[0], "a.json"); + assert!(f[1].starts_with("a.json.v3-")); + // The next start reuses that copy. + let l: Loaded = load(&p, 2, version_of, migrate, "テスト"); + assert!(l.notice.unwrap().contains(&f[1])); + assert_eq!(files(d.path()).len(), 2); + } +} diff --git a/src-tauri/src/voices.rs b/src-tauri/src/voices.rs index ee68c8d..2950efc 100644 --- a/src-tauri/src/voices.rs +++ b/src-tauri/src/voices.rs @@ -3,8 +3,13 @@ use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; use crate::models::{ModelAdapter, VoiceBuild, VoiceInput}; +use crate::stored; + +/// The format of `voices.json` this version writes (D-61). Version 0 was the bare list of voices. +pub const VOICES_VERSION: u32 = 1; #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase", default)] @@ -24,6 +29,9 @@ pub struct Voice { /// A voice described in words only (no file): Drama-3 writes it as a leading cue with `voice none`, /// Irodori sends it as `instructions`. pub prompt: String, + /// Members a later version added; kept as they are. + #[serde(flatten)] + pub extra: Map, } impl Voice { @@ -36,23 +44,51 @@ impl Voice { pub struct VoiceLibrary { pub dir: PathBuf, pub voices: Vec, + /// Top-level members of `voices.json` a later version added; kept as they are. + extra: Map, +} + +/// `voices.json`. +#[derive(Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +struct VoicesFile { + version: u32, + voices: Vec, + #[serde(flatten)] + extra: Map, +} + +/// Upgrades `voices.json` from version `from` to `from + 1`. +fn migrate(v: &mut Value, from: u32) -> Result<(), String> { + match from { + // The bare list becomes `{version, voices}`. + 0 => *v = serde_json::json!({ "version": 1, "voices": v.take() }), + _ => return Err(format!("v{from} からの変換方法がありません")), + } + Ok(()) +} + +fn version_of(v: &Value) -> u32 { + if v.is_array() { + 0 + } else { + stored::version_member(v, VOICES_VERSION) + } } impl VoiceLibrary { - pub fn open(dir: &Path) -> Self { - let voices = std::fs::read_to_string(dir.join("voices.json")) - .ok() - .and_then(|s| serde_json::from_str(&s).ok()) - .unwrap_or_default(); - VoiceLibrary { dir: dir.to_path_buf(), voices } + /// Opens the library, with a notice for the user when `voices.json` was unreadable (and moved aside) or newer. + pub fn open(dir: &Path) -> (Self, Option) { + let l: stored::Loaded = + stored::load(&dir.join("voices.json"), VOICES_VERSION, version_of, migrate, "声ライブラリ (voices.json)"); + let f = l.value.unwrap_or_default(); + (VoiceLibrary { dir: dir.to_path_buf(), voices: f.voices, extra: f.extra }, l.notice) } pub fn save(&self) -> std::io::Result<()> { std::fs::create_dir_all(&self.dir)?; - crate::project::write_atomic( - &self.dir.join("voices.json"), - serde_json::to_string_pretty(&self.voices)?.as_bytes(), - ) + let f = VoicesFile { version: VOICES_VERSION, voices: self.voices.clone(), extra: self.extra.clone() }; + crate::project::write_atomic(&self.dir.join("voices.json"), serde_json::to_string_pretty(&f)?.as_bytes()) } pub fn get(&self, id: &str) -> Option<&Voice> { @@ -195,7 +231,7 @@ mod tests { let d = tempfile::tempdir().unwrap(); let wav = d.path().join("me.wav"); std::fs::write(&wav, b"RIFF").unwrap(); - let mut lib = VoiceLibrary::open(&d.path().join("lib")); + let mut lib = VoiceLibrary::open(&d.path().join("lib")).0; let (b, v) = lib .plan( &Drama3Adapter, @@ -212,7 +248,7 @@ mod tests { std::fs::write(&v.file, b"GGUF").unwrap(); let vid = v.id.clone(); lib.insert(v).unwrap(); - assert!(VoiceLibrary::open(&lib.dir).get(&vid).is_some()); + assert!(VoiceLibrary::open(&lib.dir).0.get(&vid).is_some()); let plan = lib.plan_combined("m.gguf", &[None, Some(vid.clone())]).unwrap(); let CombinePlan::Build(b, cv) = plan else { panic!() }; @@ -232,6 +268,46 @@ mod tests { assert_eq!(pv.prompt, "落ち着いた25歳の女性。"); assert!(pv.file.is_empty()); assert!(matches!(lib.plan_combined("m.gguf", &[Some(pv.id.clone())]).unwrap(), CombinePlan::NoneNeeded)); - assert_eq!(VoiceLibrary::open(&lib.dir).get(&pv.id).unwrap().prompt, "落ち着いた25歳の女性。"); + assert_eq!(VoiceLibrary::open(&lib.dir).0.get(&pv.id).unwrap().prompt, "落ち着いた25歳の女性。"); + } + + #[test] + fn reads_the_old_bare_list_and_saves_the_versioned_form() { + let d = tempfile::tempdir().unwrap(); + std::fs::write(d.path().join("voices.json"), r#"[{"id":"a","name":"私","family":"drama3","speakers":1}]"#) + .unwrap(); + let (lib, notice) = VoiceLibrary::open(d.path()); + assert!(notice.is_none()); + assert_eq!(lib.get("a").unwrap().name, "私"); + lib.save().unwrap(); + let v: Value = serde_json::from_str(&std::fs::read_to_string(d.path().join("voices.json")).unwrap()).unwrap(); + assert_eq!(v["version"], VOICES_VERSION); + assert_eq!(v["voices"][0]["id"], "a"); + } + + #[test] + fn an_unreadable_list_is_moved_aside() { + let d = tempfile::tempdir().unwrap(); + std::fs::write(d.path().join("voices.json"), "[{").unwrap(); + let (lib, notice) = VoiceLibrary::open(d.path()); + assert!(lib.voices.is_empty()); + assert!(notice.unwrap().contains("voices.json.broken-")); + assert!(!d.path().join("voices.json").exists()); + } + + #[test] + fn newer_members_survive_a_save() { + let d = tempfile::tempdir().unwrap(); + std::fs::write( + d.path().join("voices.json"), + r#"{"version":5,"folders":["x"],"voices":[{"id":"a","name":"n","tags":["t"]}]}"#, + ) + .unwrap(); + let (lib, notice) = VoiceLibrary::open(d.path()); + assert!(notice.unwrap().contains("v5")); + lib.save().unwrap(); + let v: Value = serde_json::from_str(&std::fs::read_to_string(d.path().join("voices.json")).unwrap()).unwrap(); + assert_eq!(v["folders"][0], "x"); + assert_eq!(v["voices"][0]["tags"][0], "t"); } } diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts index d564aa5..a18089b 100644 --- a/src/lib/ipc.ts +++ b/src/lib/ipc.ts @@ -22,6 +22,8 @@ export const inTauri = typeof window !== "undefined" && "__TAURI_INTERNALS__" in export const ipc = { getSettings: () => invoke("get_settings"), + /** What loading settings.json / voices.json found, once (a file moved aside; D-61). */ + takeStartupNotices: () => invoke("take_startup_notices"), saveSettings: (settings: AppSettings) => invoke("save_settings", { settings }), newProfile: (adapter: string, id: string, name: string, model: string, speechExe: string) => invoke("new_profile", { adapter, id, name, model, speechExe }), diff --git a/src/store/app.ts b/src/store/app.ts index f5b479c..ce0e2c0 100644 --- a/src/store/app.ts +++ b/src/store/app.ts @@ -150,6 +150,8 @@ export const useApp = create()((set, get) => ({ p.load(p.project, null, workDir); document.documentElement.dataset.theme = settings.theme; set({ settings, adapters, engine, voices, ready: true }); + // Shown as errors so they stay up long enough to read the path of the file that was moved aside. + for (const n of await ipc.takeStartupNotices().catch(() => [])) get().notify("error", n); unlisten?.(); unlisten = await onAppEvent((ev) => { if (ev.kind === "engine") {