A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
fix(windows): make preferences resilient to corrupt files
Fabian-2026d8d293943568
diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rsindex 714103e5..d9ec3353 100644--- a/windows/src-tauri/src/lib.rs+++ b/windows/src-tauri/src/lib.rs@@ -69,7 +69,7 @@ fn save_settings(app: AppHandle, shared: State<Shared>, settings: Settings) {(screen_changed, autostart_changed)};if let Err(err) = settings::save(&settings) {- eprintln!("[coucou] could not save settings: {err}");+ log::line(format!("could not save settings: {err}"));}if autostart_changed {let manager = app.autolaunch();@@ -204,7 +204,9 @@ fn hooks_apply(let updated = {let mut current = shared.settings.lock().unwrap();current.hooks_installed = install;- let _ = settings::save(¤t);+ if let Err(err) = settings::save(¤t) {+ log::line(format!("could not save settings: {err}"));+ }current.clone()};let _ = app.emit("settings-changed", updated);diff --git a/windows/src-tauri/src/settings.rs b/windows/src-tauri/src/settings.rsindex 2a8d7d35..17f63e1c 100644--- a/windows/src-tauri/src/settings.rs+++ b/windows/src-tauri/src/settings.rs@@ -2,10 +2,15 @@// No secret ever lands here — API keys live in the OS keychain (see secrets.rs).use serde::{Deserialize, Serialize};-use std::path::PathBuf;+use serde_json::{Map, Value};+use std::io::ErrorKind;+use std::path::{Path, PathBuf};+use std::sync::{Mutex, MutexGuard, PoisonError};+/// A field the file lacks takes its value from `Default`, so a settings.json+/// written by an older build still loads, whatever has been added since.#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]+#[serde(rename_all = "camelCase", default)]pub struct Settings {pub sound_enabled: bool,pub sound_volume: f64,@@ -17,8 +22,6 @@ pub struct Settings {pub autostart: bool,pub hooks_installed: bool,/// Claude model used by the chat. Changeable in the settings window.- /// Defaulted explicitly so a settings.json written by an older build still loads.- #[serde(default = "default_model")]pub model: String,}@@ -58,16 +61,611 @@ fn settings_path() -> PathBuf {}pub fn load() -> Settings {- match std::fs::read(settings_path()) {- Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_default(),- Err(_) => Settings::default(),- }+ load_from(&settings_path())}pub fn save(settings: &Settings) -> std::io::Result<()> {let dir = config_dir();crate::platform::ensure_private_dir(&dir)?;+ save_to(&settings_path(), settings)+}++/// How many copies `set_aside` can make within one second before it gives up.+const MAX_COPIES_PER_SECOND: u32 = 100;++/// settings.json files that are there but whose contents never made it into+/// memory: they could not be read, or could not be used and could not be copied+/// aside either. What is in memory for them is the defaults, so the next save+/// must not quietly replace them — see `keep_what_was_not_loaded`.+static NOT_LOADED: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());++fn not_loaded() -> MutexGuard<'static, Vec<PathBuf>> {+ NOT_LOADED.lock().unwrap_or_else(PoisonError::into_inner)+}++/// One line in coucou.log. Tests must never write to the real one.+fn note(message: String) {+ #[cfg(not(test))]+ crate::log::line(message);+ #[cfg(test)]+ eprintln!("{message}");+}++/// The settings held in the bytes of a settings.json, or `None` when there is+/// nothing usable in them. Split from `load_from` so it can be tested without a+/// file.+fn parse(bytes: &[u8]) -> Option<Settings> {+ // PowerShell 5 and Notepad write a UTF-8 BOM, and serde_json refuses it.+ let text = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes);+ if text.iter().all(u8::is_ascii_whitespace) {+ return Some(Settings::default());+ }+ let Value::Object(fields) = serde_json::from_slice(text).ok()? else {+ return None;+ };+ let whole = serde_json::from_value(Value::Object(fields.clone()));+ Some(whole.unwrap_or_else(|_| salvage(fields)))+}++/// Settings from the fields of a settings.json that does not load as a whole.+/// Each field is taken on its own: one that is not the kind of value expected+/// falls back to its default instead of costing every other setting.+fn salvage(fields: Map<String, Value>) -> Settings {+ let Ok(Value::Object(mut kept)) = serde_json::to_value(Settings::default()) else {+ return Settings::default();+ };+ for (key, value) in fields {+ let mut candidate = kept.clone();+ candidate.insert(key.clone(), value);+ if serde_json::from_value::<Settings>(Value::Object(candidate.clone())).is_ok() {+ kept = candidate;+ } else {+ note(unusable_field(&key));+ }+ }+ serde_json::from_value(Value::Object(kept)).unwrap_or_default()+}++/// The log line for a field `salvage` had to drop. The name comes straight from+/// the file, so it is written escaped: a line break in it must not be able to+/// start what looks like another line of coucou.log.+fn unusable_field(key: &str) -> String {+ format!("settings.json: {key:?} is not usable — its default is used instead")+}++/// `load`, for the file at `path`: tests point it at a temporary directory.+///+/// Only a file that is not there means "start from the defaults" with nothing+/// more to do. One that cannot be read, or cannot be used, also gives the+/// defaults, but it still holds what the user had: it is kept, not written over.+fn load_from(path: &Path) -> Settings {+ let bytes = match std::fs::read(path) {+ Ok(bytes) => bytes,+ Err(err) if err.kind() == ErrorKind::NotFound => return Settings::default(),+ Err(err) => {+ note(format!("can't read {}: {err} — using the defaults", path.display()));+ protect(path);+ return Settings::default();+ }+ };+ parse(&bytes).unwrap_or_else(|| {+ match set_aside(path, "corrupt", &bytes) {+ Ok(copy) => note(format!(+ "{} is not usable — kept as {}, using the defaults",+ path.display(),+ copy.display()+ )),+ Err(err) => {+ note(format!("{} is not usable and could not be copied: {err}", path.display()));+ protect(path);+ }+ }+ Settings::default()+ })+}++/// Marks `path` as holding something the next save must not write over.+fn protect(path: &Path) {+ let mut pending = not_loaded();+ if !pending.iter().any(|p| p == path) {+ pending.push(path.to_path_buf());+ }+}++/// Before the first save over a file `load_from` could not load: copies it+/// aside if it can be read by now, and refuses the save if it still cannot.+fn keep_what_was_not_loaded(path: &Path) -> std::io::Result<()> {+ let mut pending = not_loaded();+ let Some(index) = pending.iter().position(|p| p == path) else {+ return Ok(());+ };+ match std::fs::read(path) {+ Ok(bytes) => {+ let copy = set_aside(path, "unread", &bytes)?;+ note(format!("{} was never loaded — kept as {}", path.display(), copy.display()));+ }+ // Gone since: nothing is left to protect.+ Err(err) if err.kind() == ErrorKind::NotFound => {}+ Err(err) => {+ return Err(std::io::Error::new(+ err.kind(),+ format!("{} still can't be read, so it is left as it is: {err}", path.display()),+ ));+ }+ }+ pending.swap_remove(index);+ Ok(())+}++/// Keeps `bytes`, the contents of `path`, in a file beside it named after it+/// with `.<kind>-YYYYMMDD-HHMMSS` appended. Contents an earlier copy of that+/// kind already holds are not copied again: a file nobody repairs would+/// otherwise leave one more copy behind at every launch.+fn set_aside(path: &Path, kind: &str, bytes: &[u8]) -> std::io::Result<PathBuf> {+ if let Some(copy) = same_copy(path, kind, bytes) {+ return Ok(copy);+ }+ let t = crate::platform::local_time();+ let stamp = format!(+ "{:04}{:02}{:02}-{:02}{:02}{:02}",+ t.year, t.month, t.day, t.hour, t.minute, t.second+ );+ set_aside_as(path, kind, &stamp, bytes, write_whole)+}++/// The copy of `path` of this `kind` that already holds exactly `bytes`.+fn same_copy(path: &Path, kind: &str, bytes: &[u8]) -> Option<PathBuf> {+ let prefix = format!("{}.{kind}-", path.file_name()?.to_string_lossy());+ std::fs::read_dir(path.parent()?)+ .ok()?+ .filter_map(Result::ok)+ .filter(|entry| entry.file_name().to_string_lossy().starts_with(&prefix))+ .filter(|entry| entry.metadata().is_ok_and(|m| m.len() == bytes.len() as u64))+ .map(|entry| entry.path())+ .find(|copy| std::fs::read(copy).is_ok_and(|held| held == bytes))+}++/// `set_aside` for a given time stamp, writing through `write`. `-1`, `-2`… are+/// appended while the name is taken, so a copy that is already there is never+/// written over; and a copy that could not be written whole is removed, never+/// left looking like a faithful one.+fn set_aside_as(+ path: &Path,+ kind: &str,+ stamp: &str,+ bytes: &[u8],+ write: fn(&mut std::fs::File, &[u8]) -> std::io::Result<()>,+) -> std::io::Result<PathBuf> {+ let name = path.file_name().unwrap_or_default().to_string_lossy();+ let base = format!("{name}.{kind}-{stamp}");+ for attempt in 0..MAX_COPIES_PER_SECOND {+ let copy = match attempt {+ 0 => path.with_file_name(&base),+ n => path.with_file_name(format!("{base}-{n}")),+ };+ match std::fs::OpenOptions::new().write(true).create_new(true).open(©) {+ Ok(mut file) => {+ let written = write(&mut file, bytes);+ drop(file);+ if written.is_err() {+ let _ = std::fs::remove_file(©);+ }+ return written.map(|()| copy);+ }+ Err(err) if err.kind() == ErrorKind::AlreadyExists => continue,+ Err(err) => return Err(err),+ }+ }+ Err(std::io::Error::new(ErrorKind::AlreadyExists, format!("too many copies named {base}")))+}++/// Writes `bytes` to `file` and waits until they are on the disk.+fn write_whole(file: &mut std::fs::File, bytes: &[u8]) -> std::io::Result<()> {+ use std::io::Write;+ file.write_all(bytes)?;+ file.sync_all()+}++/// `save`, for the file at `path`, whose directory already exists.+fn save_to(path: &Path, settings: &Settings) -> std::io::Result<()> {+ keep_what_was_not_loaded(path)?;let json = serde_json::to_vec_pretty(settings)- .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;- std::fs::write(settings_path(), json)+ .map_err(|e| std::io::Error::new(ErrorKind::InvalidData, e))?;++ // A dotfiles setup can make settings.json a symlink: write to the file it+ // points at, so the link survives the rename below.+ #[cfg(unix)]+ let resolved = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());+ #[cfg(unix)]+ let path = resolved.as_path();++ // Write beside the target and rename over it: a crash, a full disk or a+ // power cut leaves the previous settings.json intact rather than half a file.+ let temp = path.with_extension(format!("json.coucou-{}", std::process::id()));+ let written = std::fs::File::create(&temp)+ .and_then(|mut file| write_whole(&mut file, &json))+ .and_then(|()| std::fs::rename(&temp, path));+ if written.is_err() {+ let _ = std::fs::remove_file(&temp);+ }+ written+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::{json, Value};++ /// A settings.json in which no value is the default one.+ const CUSTOM: &str = r#"{+ "soundEnabled": false,+ "soundVolume": 0.5,+ "autoCloseInterval": 30.0,+ "absenceInterval": 60.0,+ "activeIntegrations": ["integration_notion"],+ "screen": "cursor",+ "autostart": true,+ "hooksInstalled": true,+ "model": "some-model"+}"#;++ fn custom() -> Value {+ serde_json::from_str(CUSTOM).unwrap()+ }++ /// `CUSTOM` with one key replaced, or removed when `value` is `None`.+ fn custom_with(key: &str, value: Option<Value>) -> Vec<u8> {+ let mut object = custom().as_object().unwrap().clone();+ match value {+ Some(value) => object.insert(key.to_string(), value),+ None => object.remove(key),+ };+ serde_json::to_vec(&object).unwrap()+ }++ /// Settings compare through their JSON: the struct has no `PartialEq`.+ fn shown(settings: &Settings) -> Value {+ serde_json::to_value(settings).unwrap()+ }++ fn defaults() -> Value {+ shown(&Settings::default())+ }++ /// A fresh directory of our own, and the settings.json it will hold.+ fn scratch(name: &str) -> (PathBuf, PathBuf) {+ let dir = std::env::temp_dir()+ .join(format!("coucou-settings-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let file = dir.join("settings.json");+ (dir, file)+ }++ fn names(dir: &Path) -> Vec<String> {+ let mut names: Vec<String> = std::fs::read_dir(dir)+ .unwrap()+ .map(|entry| entry.unwrap().file_name().to_string_lossy().to_string())+ .collect();+ names.sort();+ names+ }++ /// What was set aside under `settings.json.<kind>-…`.+ fn kept(dir: &Path, kind: &str) -> Vec<Vec<u8>> {+ let prefix = format!("settings.json.{kind}-");+ names(dir)+ .iter()+ .filter(|name| name.starts_with(&prefix))+ .map(|name| std::fs::read(dir.join(name)).unwrap())+ .collect()+ }++ // ── Reading ───────────────────────────────────────────────────────────────++ #[test]+ fn a_missing_file_is_the_defaults_and_is_not_created() {+ let (dir, file) = scratch("missing");+ assert_eq!(shown(&load_from(&file)), defaults());+ assert!(names(&dir).is_empty());+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn an_empty_file_is_the_defaults_and_nothing_is_set_aside() {+ let (dir, file) = scratch("empty");+ for nothing in [&b""[..], &b" \r\n\t "[..]] {+ std::fs::write(&file, nothing).unwrap();+ assert_eq!(shown(&load_from(&file)), defaults());+ }+ assert_eq!(names(&dir), ["settings.json"]);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn unknown_fields_are_ignored_and_the_known_ones_kept() {+ let bytes = custom_with("somethingFromALaterVersion", Some(json!({ "a": [1, 2] })));+ assert_eq!(shown(&parse(&bytes).unwrap()), custom());+ }++ #[test]+ fn a_file_from_before_the_model_setting_keeps_everything_else() {+ let loaded = shown(&parse(&custom_with("model", None)).unwrap());+ let mut expected = custom();+ expected["model"] = json!(crate::claude::DEFAULT_MODEL);+ assert_eq!(loaded, expected);+ }++ #[test]+ fn a_missing_field_takes_its_default_and_the_rest_are_kept() {+ for key in custom().as_object().unwrap().keys() {+ let loaded = parse(&custom_with(key, None))+ .unwrap_or_else(|| panic!("a file without {key} was thrown away"));+ let mut expected = custom();+ expected[key] = defaults()[key].clone();+ assert_eq!(shown(&loaded), expected, "without {key}");+ }+ }++ #[test]+ fn a_field_of_the_wrong_type_takes_its_default_and_the_rest_are_kept() {+ for (key, wrong) in [+ ("soundVolume", json!("loud")),+ ("soundEnabled", json!(1)),+ ("activeIntegrations", json!("integration_n8n")),+ ("screen", Value::Null),+ ] {+ let loaded = parse(&custom_with(key, Some(wrong)))+ .unwrap_or_else(|| panic!("a file with a bad {key} was thrown away"));+ let mut expected = custom();+ expected[key] = defaults()[key].clone();+ assert_eq!(shown(&loaded), expected, "bad {key}");+ }+ }++ #[test]+ fn a_utf8_bom_is_not_corruption() {+ // What PowerShell 5's `Set-Content -Encoding utf8` and Notepad write.+ let (dir, file) = scratch("bom");+ let mut bytes = vec![0xEF, 0xBB, 0xBF];+ bytes.extend_from_slice(CUSTOM.as_bytes());+ std::fs::write(&file, &bytes).unwrap();+ assert_eq!(shown(&load_from(&file)), custom());+ assert_eq!(names(&dir), ["settings.json"]);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn an_unusable_file_is_the_defaults_and_is_set_aside_byte_for_byte() {+ for (name, bad) in [+ ("invalid", &b"{ \"soundVolume\": 0.5, \xff oops"[..]),+ ("not-an-object", &b"[1, 2, 3]"[..]),+ ] {+ let (dir, file) = scratch(name);+ std::fs::write(&file, bad).unwrap();+ assert_eq!(shown(&load_from(&file)), defaults());+ assert_eq!(kept(&dir, "corrupt"), [bad.to_vec()], "{name}");+ let _ = std::fs::remove_dir_all(&dir);+ }+ }++ #[test]+ fn a_second_unusable_file_never_replaces_the_copy_of_the_first() {+ // Both within the same second: the names must still differ.+ let (dir, file) = scratch("twice");+ let (first, second) = (&b"{ first"[..], &b"{ second"[..]);+ std::fs::write(&file, first).unwrap();+ load_from(&file);+ std::fs::write(&file, second).unwrap();+ load_from(&file);+ let mut copies = kept(&dir, "corrupt");+ copies.sort();+ assert_eq!(copies, [first.to_vec(), second.to_vec()]);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn something_that_is_not_a_readable_file_is_the_defaults_and_is_left_alone() {+ // A directory in the file's place: a read error that is not "not found".+ let (dir, file) = scratch("unreadable");+ std::fs::create_dir(&file).unwrap();+ assert_eq!(shown(&load_from(&file)), defaults());+ assert_eq!(names(&dir), ["settings.json"]);+ assert!(file.is_dir());+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// Opens `path` the way a process that shares nothing does: nobody else can+ /// read or write it until the handle is dropped.+ #[cfg(windows)]+ fn locked(path: &Path) -> std::fs::File {+ use std::os::windows::fs::OpenOptionsExt;+ std::fs::OpenOptions::new().read(true).share_mode(0).open(path).unwrap()+ }++ #[cfg(windows)]+ #[test]+ fn a_file_that_could_not_be_read_is_set_aside_before_it_is_saved_over() {+ let (dir, file) = scratch("locked-then-free");+ std::fs::write(&file, CUSTOM).unwrap();+ let lock = locked(&file);+ let loaded = load_from(&file);+ assert_eq!(shown(&loaded), defaults());+ drop(lock);++ save_to(&file, &loaded).unwrap();+ assert_eq!(kept(&dir, "unread"), [CUSTOM.as_bytes().to_vec()]);+ assert_eq!(shown(&load_from(&file)), defaults());+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[cfg(windows)]+ #[test]+ fn a_file_that_still_cannot_be_read_is_not_saved_over() {+ let (dir, file) = scratch("locked");+ std::fs::write(&file, CUSTOM).unwrap();+ let lock = locked(&file);+ let loaded = load_from(&file);+ assert!(save_to(&file, &loaded).is_err());+ drop(lock);+ assert_eq!(std::fs::read(&file).unwrap(), CUSTOM.as_bytes());+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn what_could_not_be_read_is_never_saved_over_unseen() {+ // The same as the two locked-file tests above, on every platform: a+ // directory in the file's place cannot be read either.+ let (dir, file) = scratch("unread");+ std::fs::create_dir(&file).unwrap();+ let loaded = load_from(&file);++ // Still unreadable: the save is refused and nothing is touched.+ assert!(save_to(&file, &loaded).is_err());+ assert!(file.is_dir());+ assert_eq!(names(&dir), ["settings.json"]);++ // Readable by now: kept aside first, and only then saved over.+ std::fs::remove_dir(&file).unwrap();+ std::fs::write(&file, CUSTOM).unwrap();+ save_to(&file, &loaded).unwrap();+ assert_eq!(kept(&dir, "unread"), [CUSTOM.as_bytes().to_vec()]);+ assert_eq!(shown(&load_from(&file)), defaults());+ let _ = std::fs::remove_dir_all(&dir);+ }++ // ── Copies set aside ──────────────────────────────────────────────────────++ #[test]+ fn an_unusable_file_is_set_aside_once_however_often_it_is_loaded() {+ let (dir, file) = scratch("once");+ std::fs::write(&file, b"{ broken").unwrap();+ for _ in 0..3 {+ load_from(&file);+ }+ assert_eq!(kept(&dir, "corrupt"), [b"{ broken".to_vec()]);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn copies_made_within_the_same_second_are_numbered_and_none_is_written_over() {+ let (dir, file) = scratch("numbered");+ let stamp = "20260102-030405";+ let contents = [&b"one"[..], &b"two"[..], &b"three"[..]];+ let copies: Vec<PathBuf> = contents+ .iter()+ .map(|bytes| set_aside_as(&file, "corrupt", stamp, bytes, write_whole).unwrap())+ .collect();++ let named = |suffix: &str| dir.join(format!("settings.json.corrupt-{stamp}{suffix}"));+ assert_eq!(copies, [named(""), named("-1"), named("-2")]);+ for (copy, bytes) in copies.iter().zip(contents) {+ assert_eq!(std::fs::read(copy).unwrap(), bytes);+ }+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_copy_that_could_not_be_written_whole_is_removed() {+ fn half_then_fail(file: &mut std::fs::File, bytes: &[u8]) -> std::io::Result<()> {+ use std::io::Write;+ file.write_all(&bytes[..bytes.len() / 2])?;+ Err(std::io::Error::other("the disk is full"))+ }+ let (dir, file) = scratch("half");+ let copy = set_aside_as(&file, "corrupt", "20260102-030405", b"all of it", half_then_fail);+ assert!(copy.is_err());+ assert!(names(&dir).is_empty());+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_field_name_cannot_start_a_line_of_its_own_in_the_log() {+ let forged = "volume\r\n2026-01-02 03:04:05 hook id=1 answered allow";+ let line = unusable_field(forged);+ assert!(!line.contains(['\r', '\n']));+ assert!(line.contains(r"volume\r\n2026-01-02"));+ }++ // ── Writing ───────────────────────────────────────────────────────────────++ /// A dotfiles setup keeps the real file elsewhere and links to it.+ #[cfg(unix)]+ #[test]+ fn a_save_through_a_symlink_keeps_the_link_and_writes_its_target() {+ let (dir, file) = scratch("symlink");+ let real = dir.join("dotfiles-settings.json");+ std::fs::write(&real, CUSTOM).unwrap();+ std::os::unix::fs::symlink(&real, &file).unwrap();++ save_to(&file, &Settings::default()).unwrap();+ assert!(std::fs::symlink_metadata(&file).unwrap().file_type().is_symlink());+ assert_eq!(shown(&parse(&std::fs::read(&real).unwrap()).unwrap()), defaults());+ assert_eq!(names(&dir), ["dotfiles-settings.json", "settings.json"]);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn every_field_survives_a_save_and_a_load() {+ let (dir, file) = scratch("round-trip");+ let settings: Settings = serde_json::from_str(CUSTOM).unwrap();+ save_to(&file, &settings).unwrap();+ assert_eq!(shown(&load_from(&file)), custom());+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn the_file_holds_the_camel_case_keys_the_front_end_uses() {+ let (dir, file) = scratch("keys");+ save_to(&file, &Settings::default()).unwrap();+ let written: Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap();+ let keys: Vec<&str> = written.as_object().unwrap().keys().map(String::as_str).collect();+ assert_eq!(+ keys,+ [+ "soundEnabled",+ "soundVolume",+ "autoCloseInterval",+ "absenceInterval",+ "activeIntegrations",+ "screen",+ "autostart",+ "hooksInstalled",+ "model",+ ]+ );+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_save_replaces_the_file_that_was_there() {+ let (dir, file) = scratch("replace");+ std::fs::write(&file, CUSTOM).unwrap();+ save_to(&file, &Settings::default()).unwrap();+ assert_eq!(shown(&load_from(&file)), defaults());+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_save_leaves_nothing_but_settings_json_behind() {+ let (dir, file) = scratch("tidy");+ save_to(&file, &Settings::default()).unwrap();+ save_to(&file, &Settings::default()).unwrap();+ assert_eq!(names(&dir), ["settings.json"]);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_temporary_file_that_cannot_be_written_leaves_the_original_alone() {+ // The new contents go to a file beside the target first. With a+ // directory squatting on that name, the write cannot even start.+ let (dir, file) = scratch("blocked");+ std::fs::write(&file, CUSTOM).unwrap();+ let temp = dir.join(format!("settings.json.coucou-{}", std::process::id()));+ std::fs::create_dir(&temp).unwrap();++ assert!(save_to(&file, &Settings::default()).is_err());+ assert_eq!(std::fs::read(&file).unwrap(), CUSTOM.as_bytes());+ let _ = std::fs::remove_dir_all(&dir);+ }}