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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<project>.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/<uuid>/` 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.

Expand Down
5 changes: 4 additions & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<uuid>/` in the local app data dir, one per running instance (D-39).

## Front end
Expand Down
53 changes: 53 additions & 0 deletions docs/decisions/D-61-file-format-versions.md
Original file line number Diff line number Diff line change
@@ -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
`<name>.broken-<unix seconds>` and the app goes on with the defaults.
- Newer than this build: it is copied to `<name>.v<N>-<unix seconds>` (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<N>-…` 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.
3 changes: 2 additions & 1 deletion docs/decisions/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
8 changes: 8 additions & 0 deletions src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Mutex<Option<crate::memguard::Held>>>,
/// What loading the app's own files found that the user should know (a file moved aside, D-61).
pub startup_notices: Mutex<Vec<String>>,
}

type R<T> = Result<T, String>;
Expand Down Expand Up @@ -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<String> {
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)?;
Expand Down
12 changes: 10 additions & 2 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand All @@ -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));
Expand All @@ -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,
Expand Down
20 changes: 17 additions & 3 deletions src-tauri/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down Expand Up @@ -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))
}
Expand Down
70 changes: 64 additions & 6 deletions src-tauri/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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<String, Value>,
}

impl Default for AppSettings {
fn default() -> Self {
AppSettings {
version: 1,
version: SETTINGS_VERSION,
profiles: Vec::new(),
active_profile_id: None,
speech_exe: String::new(),
Expand All @@ -92,6 +102,7 @@ impl Default for AppSettings {
playback_volume: 1.0,
playback_muted: false,
memory_guard: GuardLevel::default(),
extra: Map::new(),
}
}
}
Expand All @@ -116,16 +127,30 @@ impl AppSettings {
self.profiles.iter().find(|p| p.id == id)
}

pub fn load(path: &Path) -> Option<Self> {
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<Self> {
let mut l: stored::Loaded<Self> = 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) {
Expand All @@ -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::*;
Expand All @@ -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);
Expand All @@ -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);
}
}
Loading