Skip to main content

subspace_core/
settings.rs

1use crate::{
2    Secret,
3    config::{self, ChatEngine, Config, NoticeKind},
4    state,
5};
6use serde_json::{Map, Value};
7use std::collections::BTreeMap;
8use std::path::{Path, PathBuf};
9use std::{fs, io};
10use thiserror::Error;
11
12mod board_fields;
13mod board_file;
14mod merge;
15#[cfg(test)]
16mod native_board_tests;
17mod repos;
18mod web_boards;
19
20pub use board_fields::BoardFieldEdits;
21
22#[derive(Clone)]
23pub enum TokenEdit {
24    Keep,
25    Replace(Secret),
26    Clear,
27}
28#[derive(Clone)]
29pub struct ServiceSettings {
30    pub mcp: config::McpSettings,
31    pub chat_engine: ChatEngine,
32    /// `chat.acp.agent`. Its command overrides stay as the file has them.
33    pub acp_agent: config::AcpAgent,
34    pub board_order: Vec<String>,
35    pub auto_refresh: bool,
36    /// The config file's `terminal` object. Save sets each key, and removes
37    /// one whose value is `null`.
38    pub terminal: Map<String, Value>,
39    /// Explicit board choices from the config file. A missing id is enabled.
40    pub boards: BTreeMap<String, bool>,
41    /// Explicit registered-feature choices, including valid future flags.
42    pub features: BTreeMap<String, bool>,
43    /// The favourite repositories, `owner/name`, in saved order.
44    pub repos: Vec<String>,
45    pub github_token: TokenEdit,
46    /// Changes to boards' own run-time settings; empty when none changed.
47    pub board_fields: Vec<BoardFieldEdits>,
48    /// Changes to native boards' own settings files, keyed by board id:
49    /// the top-level keys to set. Empty when none changed.
50    pub board_files: BTreeMap<String, Map<String, Value>>,
51}
52#[derive(Debug, Error)]
53pub enum SettingsError {
54    #[error("cannot read settings file: {0}")]
55    Io(#[from] io::Error),
56    #[error("settings file contains invalid JSON")]
57    Json(#[from] serde_json::Error),
58    #[error("settings file has invalid values")]
59    Invalid,
60    #[error("invalid {field}: {reason}")]
61    Validation {
62        field: &'static str,
63        reason: &'static str,
64    },
65    #[error("settings file changed externally; reopen it before saving")]
66    Stale,
67    #[error("{}: {error}", file.display())]
68    BoardFile {
69        file: PathBuf,
70        #[source]
71        error: Box<SettingsError>,
72    },
73}
74pub struct SettingsFile {
75    file: PathBuf,
76    original: Option<String>,
77    root: Map<String, Value>,
78    values: ServiceSettings,
79    github_token_present: bool,
80    /// The native boards' own files opened so far, keyed by board id.
81    boards: BTreeMap<String, board_file::BoardFile>,
82    /// The former Space ids the file was read with.
83    renames: crate::former_ids::Renames,
84}
85
86impl SettingsFile {
87    /// Opens the config file for editing. Settings saved under a Space's
88    /// former id are read, and later saved, as the Space's own (see
89    /// [`crate::former_ids`]).
90    pub fn open(file: &Path) -> Result<Self, SettingsError> {
91        Self::open_with(file, &crate::former_ids::installed())
92    }
93
94    /// As [`SettingsFile::open`], with the former ids `renames`.
95    pub(crate) fn open_with(
96        file: &Path,
97        renames: &crate::former_ids::Renames,
98    ) -> Result<Self, SettingsError> {
99        let original = read_existing(file)?;
100        let mut root = match original.as_deref() {
101            None => Map::new(),
102            Some(text) => match serde_json::from_str::<Value>(text)? {
103                Value::Object(v) => v,
104                _ => return Err(SettingsError::Invalid),
105            },
106        };
107        crate::former_ids::rename_config(&mut root, renames);
108        let (config, notices) = match original.as_deref() {
109            None => (Config::default(), Vec::new()),
110            Some(text) => config::parse_with(text, file, renames),
111        };
112        if notices
113            .iter()
114            .any(|notice| notice.kind == NoticeKind::Warning)
115        {
116            return Err(SettingsError::Invalid);
117        }
118        let github_token_present = config.github.token.is_some();
119        let values = from_config(config, &root);
120        Ok(Self {
121            file: file.into(),
122            original,
123            root,
124            values,
125            github_token_present,
126            boards: BTreeMap::new(),
127            renames: renames.clone(),
128        })
129    }
130    pub fn values(&self) -> &ServiceSettings {
131        &self.values
132    }
133    /// Opens native board `id`'s own settings file for this transaction, once,
134    /// and returns its saved settings. A missing file has none.
135    pub fn open_board_file(&mut self, id: &str) -> Result<Map<String, Value>, SettingsError> {
136        if !self.boards.contains_key(id) {
137            let file = self.board_path(id);
138            let opened = board_file::BoardFile::open(file.clone())
139                .map_err(|error| board_error(&file, error))?;
140            self.boards.insert(id.to_owned(), opened);
141        }
142        Ok(self.board_file_values(id))
143    }
144    /// Native board `id`'s settings file as it resolves now (see
145    /// [`config::board_file`]).
146    fn board_path(&self, id: &str) -> PathBuf {
147        let dir = self.file.parent().unwrap_or_else(|| Path::new(""));
148        crate::former_ids::board_file(dir, id, &self.renames)
149    }
150    /// The saved settings of native board `id`'s opened file.
151    pub fn board_file_values(&self, id: &str) -> Map<String, Value> {
152        self.boards
153            .get(id)
154            .map(|board| board.values().clone())
155            .unwrap_or_default()
156    }
157    /// The saved values of the board whose config section is `section`.
158    pub fn board_values(&self, section: &[String]) -> Map<String, Value> {
159        board_fields::values(&self.root, section)
160    }
161    /// Whether the board at `section` has a saved secret `key`.
162    pub fn board_secret_present(&self, section: &[String], key: &str) -> bool {
163        board_fields::secret_present(&self.root, section, key)
164    }
165    /// The keys of the secrets saved for the board at `section`, never
166    /// their values.
167    pub fn board_secret_keys(&self, section: &[String]) -> Vec<String> {
168        board_fields::secret_keys(&self.root, section)
169    }
170    pub fn board_permission(&self, section: &[String], key: &str) -> bool {
171        board_fields::permission(&self.root, section, key)
172    }
173    pub fn token_present(&self, section: &str) -> bool {
174        section == "github" && self.github_token_present
175    }
176    /// Writes the config file, then each changed board file. Every file is
177    /// checked before the first write, so a conflict writes nothing.
178    pub fn save(&mut self, values: &ServiceSettings) -> Result<(), SettingsError> {
179        self.check_current()?;
180        let mut root = self.root.clone();
181        merge(&mut root, values, self.github_token_present)?;
182        let boards = self.edited_board_files(&values.board_files)?;
183        self.write_root(root)?;
184        self.write_board_files(boards)
185    }
186
187    /// Persist the switcher order without changing other settings.
188    pub fn save_board_order(&mut self, order: &[String]) -> Result<(), SettingsError> {
189        let mut root = self.root.clone();
190        merge::write_board_order(&mut root, order);
191        self.write_root(root)
192    }
193
194    /// Persist the board choices (`boards`) without changing other settings,
195    /// as Save writes them: a missing id uses the product default.
196    pub fn save_board_choices(
197        &mut self,
198        boards: &BTreeMap<String, bool>,
199    ) -> Result<(), SettingsError> {
200        let mut root = self.root.clone();
201        merge::write_board_choices(&mut root, boards);
202        self.write_root(root)
203    }
204
205    fn check_current(&self) -> Result<(), SettingsError> {
206        if read_existing(&self.file)? != self.original {
207            return Err(SettingsError::Stale);
208        }
209        Ok(())
210    }
211
212    fn edited_board_files(
213        &mut self,
214        edits: &BTreeMap<String, Map<String, Value>>,
215    ) -> Result<Vec<(String, Map<String, Value>)>, SettingsError> {
216        let mut edited = Vec::with_capacity(edits.len());
217        for (id, changes) in edits {
218            self.open_board_file(id)?;
219            let Some(board) = self.boards.get(id) else {
220                continue;
221            };
222            let root = board
223                .edited_at(&self.board_path(id), changes)
224                .map_err(|error| board_error(board.path(), error))?;
225            edited.push((id.clone(), root));
226        }
227        Ok(edited)
228    }
229
230    fn write_board_files(
231        &mut self,
232        edited: Vec<(String, Map<String, Value>)>,
233    ) -> Result<(), SettingsError> {
234        for (id, root) in edited {
235            if let Some(board) = self.boards.get_mut(&id) {
236                let file = board.path().to_owned();
237                board
238                    .write(root)
239                    .map_err(|error| board_error(&file, error))?;
240            }
241        }
242        Ok(())
243    }
244
245    fn write_root(&mut self, root: Map<String, Value>) -> Result<(), SettingsError> {
246        let text = serde_json::to_string_pretty(&Value::Object(root.clone()))? + "\n";
247        let (config, notices) = config::parse(&text, &self.file);
248        if notices
249            .iter()
250            .any(|notice| notice.kind == NoticeKind::Warning)
251        {
252            return Err(SettingsError::Validation {
253                field: "settings",
254                reason: "values do not satisfy config constraints",
255            });
256        }
257        self.check_current()?;
258        state::write_atomic(&self.file, &text)?;
259        self.original = Some(text);
260        self.root = root;
261        self.github_token_present = config.github.token.is_some();
262        self.values = from_config(config, &self.root);
263        Ok(())
264    }
265}
266fn from_config(c: Config, root: &Map<String, Value>) -> ServiceSettings {
267    let repos = root
268        .get("repos")
269        .and_then(Value::as_array)
270        .filter(|items| items.iter().all(Value::is_string))
271        .map(|items| {
272            items
273                .iter()
274                .filter_map(Value::as_str)
275                .map(str::to_owned)
276                .collect()
277        })
278        .unwrap_or_default();
279    ServiceSettings {
280        mcp: c.mcp,
281        chat_engine: c.chat.engine,
282        acp_agent: c.chat.acp.agent,
283        board_order: c.board_order,
284        auto_refresh: c.auto_refresh,
285        terminal: c.terminal,
286        boards: c.boards,
287        features: c.features,
288        repos,
289        github_token: TokenEdit::Keep,
290        board_fields: Vec::new(),
291        board_files: BTreeMap::new(),
292    }
293}
294/// The file's text, or `None` when it does not exist.
295fn read_existing(file: &Path) -> io::Result<Option<String>> {
296    match fs::read_to_string(file) {
297        Ok(text) => Ok(Some(text)),
298        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
299        Err(error) => Err(error),
300    }
301}
302fn board_error(file: &Path, error: SettingsError) -> SettingsError {
303    SettingsError::BoardFile {
304        file: file.to_owned(),
305        error: Box::new(error),
306    }
307}
308fn section(root: &Map<String, Value>, key: &str) -> Map<String, Value> {
309    root.get(key)
310        .and_then(Value::as_object)
311        .cloned()
312        .unwrap_or_default()
313}
314fn token(section: &mut Map<String, Value>, edit: &TokenEdit, present: bool) {
315    match edit {
316        TokenEdit::Keep => {
317            if !present {
318                section.remove("token");
319            }
320        }
321        TokenEdit::Replace(v) => {
322            section.insert("token".into(), Value::String(v.expose().into()));
323        }
324        TokenEdit::Clear => {
325            section.remove("token");
326        }
327    }
328}
329fn merge(
330    root: &mut Map<String, Value>,
331    v: &ServiceSettings,
332    github_token_present: bool,
333) -> Result<(), SettingsError> {
334    merge::validate(v)?;
335    board_fields::validate(&v.board_fields)?;
336    merge::write_values(root, v, github_token_present)?;
337    board_fields::write(root, &v.board_fields)
338}
339
340#[cfg(test)]
341mod tests {
342    use super::{ChatEngine, ServiceSettings, SettingsError, SettingsFile, TokenEdit};
343    use crate::Secret;
344    use serde_json::Value;
345    use std::collections::BTreeMap;
346    use std::fs;
347
348    fn values() -> ServiceSettings {
349        ServiceSettings {
350            mcp: crate::config::McpSettings::default(),
351            chat_engine: ChatEngine::Copilot,
352            acp_agent: crate::config::AcpAgent::OpenCode,
353            board_order: Vec::new(),
354            auto_refresh: true,
355            terminal: serde_json::Map::new(),
356            boards: BTreeMap::new(),
357            features: BTreeMap::new(),
358            repos: vec!["owner/repo".into()],
359            github_token: TokenEdit::Keep,
360            board_fields: Vec::new(),
361            board_files: BTreeMap::new(),
362        }
363    }
364
365    #[test]
366    fn board_fields_are_saved_in_the_same_write() {
367        let dir = tempfile::tempdir().unwrap();
368        let path = dir.path().join("config.json");
369        fs::write(
370            &path,
371            r#"{"webBoards": {"notes": {"url": "https://notes.example"}}}"#,
372        )
373        .unwrap();
374        let mut file = SettingsFile::open(&path).unwrap();
375        let section = vec!["webBoards".to_owned(), "notes".to_owned()];
376        let mut settings = values();
377        settings.board_fields = vec![super::BoardFieldEdits {
378            section: section.clone(),
379            values: BTreeMap::from([("limit".into(), Some(Value::from(5)))]),
380            secrets: BTreeMap::from([("token".into(), TokenEdit::Replace(Secret::new("t")))]),
381            permissions: BTreeMap::new(),
382        }];
383        file.save(&settings).unwrap();
384        assert_eq!(file.board_values(&section)["limit"], Value::from(5));
385        assert!(file.board_secret_present(&section, "token"));
386        let (config, notices) = crate::config::load(&path);
387        assert!(notices.is_empty(), "{notices:?}");
388        assert_eq!(config.web_boards[0].secrets["token"].expose(), "t");
389        assert!(file.values().board_fields.is_empty());
390    }
391
392    #[test]
393    fn mcp_round_trips_every_key_and_preserves_extensions() {
394        let dir = tempfile::tempdir().unwrap();
395        let path = dir.path().join("config.json");
396        fs::write(&path, r#"{"mcp":{"extension":7},"unknown":true}"#).unwrap();
397        let mut file = SettingsFile::open(&path).unwrap();
398        let mut settings = file.values().clone();
399        settings.mcp.enabled = true;
400        settings.mcp.bind = "::1".parse().unwrap();
401        settings.mcp.port = 7400;
402        settings.mcp.require_token = true;
403        settings.mcp.groups.insert("github".into(), false);
404        file.save(&settings).unwrap();
405        let reopened = SettingsFile::open(&path).unwrap();
406        assert_eq!(reopened.values().mcp, settings.mcp);
407        assert_eq!(json(&path)["mcp"]["extension"], 7);
408        assert_eq!(json(&path)["unknown"], true);
409        let before = fs::read(&path).unwrap();
410        settings.mcp.bind = "0.0.0.0".parse().unwrap();
411        settings.mcp.require_token = false;
412        assert!(file.save(&settings).is_err());
413        assert_eq!(fs::read(&path).unwrap(), before);
414    }
415
416    #[test]
417    fn board_order_refresh_and_terminal_settings_round_trip() {
418        let dir = tempfile::tempdir().unwrap();
419        let file = dir.path().join("config.json");
420        fs::write(&file, "{}\n").unwrap();
421        let mut settings = SettingsFile::open(&file).unwrap();
422        let mut values = settings.values().clone();
423        values.board_order = vec!["irc".into(), "github".into()];
424        values.auto_refresh = false;
425        values.terminal = serde_json::json!({"fontFamily": "Menlo", "fontSize": null})
426            .as_object()
427            .cloned()
428            .unwrap();
429        settings.save(&values).unwrap();
430
431        let reopened = SettingsFile::open(&file).unwrap();
432        assert_eq!(reopened.values().board_order, ["irc", "github"]);
433        assert!(!reopened.values().auto_refresh);
434        assert_eq!(
435            Value::Object(reopened.values().terminal.clone()),
436            serde_json::json!({"fontFamily": "Menlo"})
437        );
438    }
439
440    #[test]
441    fn board_choices_save_alone_and_match_a_full_save() {
442        let dir = tempfile::tempdir().unwrap();
443        let file = dir.path().join("config.json");
444        fs::write(&file, r#"{"boards": {"irc": true}, "autoRefresh": false}"#).unwrap();
445        let mut alone = SettingsFile::open(&file).unwrap();
446        let mut boards = alone.values().boards.clone();
447        boards.insert("github".into(), false);
448        alone.save_board_choices(&boards).unwrap();
449        assert_eq!(
450            json(&file),
451            serde_json::json!({"boards": {"github": false, "irc": true}, "autoRefresh": false})
452        );
453
454        let full = dir.path().join("full.json");
455        fs::write(&full, r#"{"boards": {"irc": true}, "autoRefresh": false}"#).unwrap();
456        let mut saved = SettingsFile::open(&full).unwrap();
457        let mut values = saved.values().clone();
458        values.boards.clone_from(&boards);
459        saved.save(&values).unwrap();
460        assert_eq!(json(&full)["boards"], json(&file)["boards"]);
461        assert_eq!(alone.values().boards, saved.values().boards);
462
463        alone.save_board_choices(&BTreeMap::new()).unwrap();
464        assert!(json(&file).get("boards").is_none());
465    }
466
467    fn source() -> &'static str {
468        r#"{
469          "unknown": {"keep": true, "nested": {"value": 7}},
470          "github": {"token":"gh", "other": {"keep": "yes"}},
471          "terminal": {"fontSize": 13, "extension": {"keep": 7}},
472          "repos": ["owner/repo"]
473        }"#
474    }
475    fn json(file: &std::path::Path) -> Value {
476        serde_json::from_str(&fs::read_to_string(file).unwrap()).unwrap()
477    }
478
479    #[test]
480    fn preserves_unknown_properties_and_all_kept_tokens() {
481        let dir = tempfile::tempdir().unwrap();
482        let file = dir.path().join("config.json");
483        fs::write(&file, source()).unwrap();
484        let mut editor = SettingsFile::open(&file).unwrap();
485        let kept = editor.values().clone();
486        editor.save(&kept).unwrap();
487        let root = json(&file);
488        assert_eq!(
489            root["unknown"],
490            serde_json::json!({"keep":true,"nested":{"value":7}})
491        );
492        assert_eq!(root["github"]["other"], serde_json::json!({"keep":"yes"}));
493        assert_eq!(root["github"]["token"], "gh");
494        assert_eq!(root["terminal"]["fontSize"], 13);
495        assert_eq!(root["terminal"]["extension"], serde_json::json!({"keep":7}));
496        assert_eq!(root["repos"], serde_json::json!(["owner/repo"]));
497        assert!(matches!(editor.values().github_token, TokenEdit::Keep));
498    }
499
500    #[test]
501    fn chat_engine_saves_without_replacing_unknown_chat_settings() {
502        let dir = tempfile::tempdir().unwrap();
503        let file = dir.path().join("config.json");
504        fs::write(
505            &file,
506            r#"{"chat":{"engine":"copilot","extension":{"keep":true}},"other":7}"#,
507        )
508        .unwrap();
509        let mut editor = SettingsFile::open(&file).unwrap();
510        let mut edited = editor.values().clone();
511        edited.chat_engine = crate::config::ChatEngine::Pi;
512        editor.save(&edited).unwrap();
513
514        let saved = json(&file);
515        assert_eq!(saved["chat"]["engine"], "pi");
516        assert_eq!(saved["chat"]["extension"], serde_json::json!({"keep":true}));
517        assert_eq!(saved["other"], 7);
518        assert_eq!(
519            crate::config::load(&file).0.chat.engine,
520            crate::config::ChatEngine::Pi
521        );
522    }
523
524    #[test]
525    fn acp_agent_saves_without_replacing_its_command_overrides() {
526        let dir = tempfile::tempdir().unwrap();
527        let file = dir.path().join("config.json");
528        fs::write(
529            &file,
530            r#"{"chat":{"engine":"copilot","acp":{"agent":"opencode","command":"/opt/agent","args":["acp"]}}}"#,
531        )
532        .unwrap();
533        let mut editor = SettingsFile::open(&file).unwrap();
534        let mut edited = editor.values().clone();
535        edited.chat_engine = ChatEngine::Acp;
536        edited.acp_agent = crate::config::AcpAgent::Claude;
537        editor.save(&edited).unwrap();
538
539        let saved = json(&file);
540        assert_eq!(saved["chat"]["engine"], "acp");
541        assert_eq!(saved["chat"]["acp"]["agent"], "claude");
542        assert_eq!(saved["chat"]["acp"]["command"], "/opt/agent");
543        assert_eq!(saved["chat"]["acp"]["args"], serde_json::json!(["acp"]));
544        let config = crate::config::load(&file).0;
545        assert_eq!(config.chat.acp.agent, crate::config::AcpAgent::Claude);
546    }
547
548    #[test]
549    fn cancelling_or_conflicting_chat_engine_edits_does_not_write_them() {
550        let dir = tempfile::tempdir().unwrap();
551        let file = dir.path().join("config.json");
552        let original = b"{\"chat\":{\"engine\":\"copilot\"}}\n";
553        fs::write(&file, original).unwrap();
554        let editor = SettingsFile::open(&file).unwrap();
555        let mut cancelled = editor.values().clone();
556        cancelled.chat_engine = crate::config::ChatEngine::Pi;
557        drop(editor);
558        assert_eq!(fs::read(&file).unwrap(), original);
559
560        let mut editor = SettingsFile::open(&file).unwrap();
561        let mut edited = editor.values().clone();
562        edited.chat_engine = crate::config::ChatEngine::Pi;
563        fs::write(&file, r#"{"external":true}"#).unwrap();
564        assert!(matches!(editor.save(&edited), Err(SettingsError::Stale)));
565        assert_eq!(json(&file), serde_json::json!({"external":true}));
566    }
567
568    #[test]
569    fn board_choices_save_transactionally_and_omitted_boards_stay_enabled() {
570        let dir = tempfile::tempdir().unwrap();
571        let file = dir.path().join("config.json");
572        fs::write(
573            &file,
574            r#"{"boards":{"irc":false,"excluded":true},"extension":{"keep":true}}"#,
575        )
576        .unwrap();
577        let mut editor = SettingsFile::open(&file).unwrap();
578        assert!(!editor.values().boards["irc"]);
579        assert!(!editor.values().boards.contains_key("github"));
580
581        let mut edited = editor.values().clone();
582        edited.boards.remove("irc");
583        edited.boards.insert("github".into(), false);
584        editor.save(&edited).unwrap();
585
586        let saved = json(&file);
587        assert_eq!(
588            saved["boards"],
589            serde_json::json!({"excluded": true, "github": false})
590        );
591        assert_eq!(saved["extension"], serde_json::json!({"keep": true}));
592        let config = crate::config::load(&file).0;
593        assert!(config.board_enabled("irc"));
594        assert!(!config.board_enabled("github"));
595        assert!(config.board_enabled("actions"));
596    }
597
598    #[test]
599    fn opening_and_cancelling_board_edits_does_not_write_the_file() {
600        let dir = tempfile::tempdir().unwrap();
601        let file = dir.path().join("config.json");
602        let original = b"{\n  \"boards\": {\"github-copilot-agents\": false}\n}\n";
603        fs::write(&file, original).unwrap();
604        let editor = SettingsFile::open(&file).unwrap();
605        let mut cancelled = editor.values().clone();
606        cancelled.boards.remove("github-copilot-agents");
607        drop(editor);
608        assert_eq!(fs::read(&file).unwrap(), original);
609    }
610
611    #[test]
612    fn feature_choices_preserve_unknown_flags_and_save_transactionally() {
613        let dir = tempfile::tempdir().unwrap();
614        let file = dir.path().join("config.json");
615        fs::write(
616            &file,
617            r#"{"features":{"app.pi-chat":false,"board.future.preview":true},"extension":{"keep":7}}"#,
618        )
619        .unwrap();
620        let mut editor = SettingsFile::open(&file).unwrap();
621        assert!(editor.values().features["board.future.preview"]);
622        let mut edited = editor.values().clone();
623        edited.features.insert("app.pi-chat".into(), true);
624        editor.save(&edited).unwrap();
625
626        let saved = json(&file);
627        assert_eq!(saved["features"]["app.pi-chat"], true);
628        assert_eq!(saved["features"]["board.future.preview"], true);
629        assert_eq!(saved["extension"]["keep"], 7);
630        assert!(crate::config::load(&file).0.features["board.future.preview"]);
631    }
632
633    #[test]
634    fn cancelling_or_conflicting_feature_edits_does_not_write_them() {
635        let dir = tempfile::tempdir().unwrap();
636        let file = dir.path().join("config.json");
637        let original = b"{\"features\":{\"app.pi-chat\":false}}\n";
638        fs::write(&file, original).unwrap();
639        let editor = SettingsFile::open(&file).unwrap();
640        let mut cancelled = editor.values().clone();
641        cancelled.features.insert("app.pi-chat".into(), true);
642        drop(editor);
643        assert_eq!(fs::read(&file).unwrap(), original);
644
645        let mut editor = SettingsFile::open(&file).unwrap();
646        let mut edited = editor.values().clone();
647        edited.features.insert("app.pi-chat".into(), true);
648        fs::write(&file, r#"{"external":true}"#).unwrap();
649        assert!(matches!(editor.save(&edited), Err(SettingsError::Stale)));
650        assert_eq!(json(&file), serde_json::json!({"external":true}));
651    }
652
653    #[test]
654    fn malformed_feature_keys_or_values_refuse_settings_file() {
655        let dir = tempfile::tempdir().unwrap();
656        for source in [
657            r#"{"features":{"not-namespaced":true}}"#,
658            r#"{"features":{"app.pi-chat":"true"}}"#,
659        ] {
660            let file = dir.path().join(format!("{}.json", source.len()));
661            fs::write(&file, source).unwrap();
662            assert!(matches!(
663                SettingsFile::open(&file),
664                Err(SettingsError::Invalid)
665            ));
666        }
667    }
668
669    #[test]
670    fn replaces_and_clears_tokens_without_retaining_secret() {
671        let dir = tempfile::tempdir().unwrap();
672        let file = dir.path().join("config.json");
673        fs::write(&file, source()).unwrap();
674        let mut editor = SettingsFile::open(&file).unwrap();
675        let mut edited = editor.values().clone();
676        edited.github_token = TokenEdit::Replace(Secret::new("replacement"));
677        editor.save(&edited).unwrap();
678        assert_eq!(json(&file)["github"]["token"], "replacement");
679        assert!(matches!(editor.values().github_token, TokenEdit::Keep));
680        edited = editor.values().clone();
681        edited.github_token = TokenEdit::Clear;
682        editor.save(&edited).unwrap();
683        assert!(json(&file)["github"].get("token").is_none());
684        assert!(matches!(editor.values().github_token, TokenEdit::Keep));
685    }
686
687    #[test]
688    fn distinguishes_missing_empty_and_externally_created_files() {
689        let dir = tempfile::tempdir().unwrap();
690        let missing = dir.path().join("missing.json");
691        let mut editor = SettingsFile::open(&missing).unwrap();
692        fs::write(&missing, "").unwrap();
693        assert!(matches!(editor.save(&values()), Err(SettingsError::Stale)));
694        assert!(matches!(
695            SettingsFile::open(&missing),
696            Err(SettingsError::Json(_))
697        ));
698        let empty = dir.path().join("empty.json");
699        fs::write(&empty, "").unwrap();
700        assert!(matches!(
701            SettingsFile::open(&empty),
702            Err(SettingsError::Json(_))
703        ));
704    }
705
706    #[test]
707    fn detects_deleted_files_as_stale() {
708        let dir = tempfile::tempdir().unwrap();
709        let file = dir.path().join("config.json");
710        fs::write(&file, "{}").unwrap();
711        let mut editor = SettingsFile::open(&file).unwrap();
712        fs::remove_file(&file).unwrap();
713        assert!(matches!(editor.save(&values()), Err(SettingsError::Stale)));
714    }
715
716    #[test]
717    fn invalid_edits_are_safe_and_leave_original_bytes() {
718        let dir = tempfile::tempdir().unwrap();
719        let file = dir.path().join("config.json");
720        fs::write(&file, source()).unwrap();
721        let original = fs::read(&file).unwrap();
722        let mut editor = SettingsFile::open(&file).unwrap();
723        let mut invalid = editor.values().clone();
724        invalid.github_token = TokenEdit::Replace(Secret::new(""));
725        assert!(matches!(
726            editor.save(&invalid),
727            Err(SettingsError::Validation { .. })
728        ));
729        assert_eq!(fs::read(&file).unwrap(), original);
730        invalid = editor.values().clone();
731        invalid.repos = vec!["not a repo".into()];
732        assert!(matches!(
733            editor.save(&invalid),
734            Err(SettingsError::Validation { .. })
735        ));
736        assert_eq!(fs::read(&file).unwrap(), original);
737    }
738
739    #[cfg(unix)]
740    #[test]
741    fn new_and_existing_files_are_private_and_loadable() {
742        use std::os::unix::fs::PermissionsExt;
743        let dir = tempfile::tempdir().unwrap();
744        let existing = dir.path().join("existing.json");
745        fs::write(&existing, r#"{"github":{"token":"old"}}"#).unwrap();
746        fs::set_permissions(&existing, fs::Permissions::from_mode(0o644)).unwrap();
747        let mut existing_editor = SettingsFile::open(&existing).unwrap();
748        let existing_values = existing_editor.values().clone();
749        existing_editor.save(&existing_values).unwrap();
750        assert_eq!(
751            fs::metadata(&existing).unwrap().permissions().mode() & 0o777,
752            0o600
753        );
754        assert_eq!(
755            crate::config::load(&existing)
756                .0
757                .github
758                .token
759                .unwrap()
760                .expose(),
761            "old"
762        );
763        let new_file = dir.path().join("new.json");
764        let mut new_editor = SettingsFile::open(&new_file).unwrap();
765        let mut new_values = values();
766        new_values.github_token = TokenEdit::Replace(Secret::new("new"));
767        new_editor.save(&new_values).unwrap();
768        assert_eq!(
769            fs::metadata(&new_file).unwrap().permissions().mode() & 0o777,
770            0o600
771        );
772        assert_eq!(
773            crate::config::load(&new_file)
774                .0
775                .github
776                .token
777                .unwrap()
778                .expose(),
779            "new"
780        );
781    }
782}