1use std::collections::BTreeMap;
7use std::fs;
8use std::io;
9use std::path::{Path, PathBuf};
10
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13
14use crate::{
15 Secret,
16 features::{FeatureSpec, FeatureStage},
17};
18mod acp;
19mod board_files;
20mod mcp;
21mod notice;
22mod parser;
23pub mod web_boards;
24
25pub use acp::{AcpAgent, AcpConfig};
26pub use board_files::board_file;
27pub use mcp::{McpFieldError, McpSettings};
28pub use notice::{Notice, NoticeKind};
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct Config {
33 pub terminal: serde_json::Map<String, Value>,
36 pub board_order: Vec<String>,
37 pub auto_refresh: bool,
38 pub chat: ChatConfig,
39 pub mcp: McpSettings,
40 pub web: WebConfig,
41 pub github: GitHub,
42 pub repos: Vec<String>,
44 pub boards: BTreeMap<String, bool>,
47 pub features: BTreeMap<String, bool>,
50 pub board_settings: BTreeMap<String, serde_json::Map<String, Value>>,
53 pub web_boards: Vec<web_boards::WebBoard>,
54}
55
56impl Default for Config {
57 fn default() -> Self {
58 Self {
59 terminal: serde_json::Map::new(),
60 board_order: Vec::new(),
61 auto_refresh: true,
62 chat: ChatConfig::default(),
63 mcp: McpSettings::default(),
64 web: WebConfig::default(),
65 github: GitHub::default(),
66 repos: Vec::new(),
67 boards: BTreeMap::new(),
68 features: BTreeMap::new(),
69 board_settings: BTreeMap::new(),
70 web_boards: Vec::new(),
71 }
72 }
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
76#[serde(rename_all = "lowercase")]
77pub enum ChatEngine {
78 #[default]
79 Off,
80 Copilot,
81 Pi,
82 Acp,
84}
85
86impl ChatEngine {
87 pub fn label(self) -> &'static str {
88 match self {
89 Self::Off => "Off",
90 Self::Copilot => "Copilot",
91 Self::Pi => "Pi",
92 Self::Acp => "ACP agent",
93 }
94 }
95}
96
97#[derive(Debug, Clone, PartialEq, Eq, Default)]
98pub struct ChatConfig {
99 pub engine: ChatEngine,
100 pub acp: AcpConfig,
101}
102
103#[derive(Debug, Clone, PartialEq, Eq, Default)]
105pub struct WebConfig {
106 pub allowed_hosts: Vec<String>,
108 pub silent_allowed_hosts: Vec<String>,
110 pub search: WebSearchConfig,
111}
112
113#[derive(Debug, Clone, PartialEq, Eq, Default)]
115pub struct WebSearchConfig {
116 pub provider: Option<String>,
117 pub endpoint: Option<String>,
118}
119
120#[derive(Debug, Clone, PartialEq, Eq, Default)]
121pub struct GitHub {
122 pub token: Option<Secret>,
123}
124
125impl Config {
126 pub fn board_enabled(&self, id: &str) -> bool {
129 self.boards.get(id).copied().unwrap_or(true)
130 }
131
132 pub fn board_enabled_or(&self, id: &str, default_enabled: bool) -> bool {
134 self.boards.get(id).copied().unwrap_or(default_enabled)
135 }
136
137 pub fn feature_enabled(&self, spec: &FeatureSpec) -> bool {
139 if !crate::features::valid_id(spec.id) {
140 return false;
141 }
142 if let Some(owner_and_feature) = spec.id.strip_prefix("board.") {
143 let owner = owner_and_feature
144 .split_once('.')
145 .map(|(owner, _)| owner)
146 .unwrap_or_default();
147 if !self.boards.get(owner).copied().unwrap_or(true) {
148 return false;
149 }
150 }
151 match (spec.stage, spec.toggleable) {
152 (FeatureStage::Removed, _) | (FeatureStage::Experimental, false) => false,
153 (FeatureStage::Experimental, true) => {
154 self.features.get(spec.id).copied().unwrap_or(false)
155 }
156 (FeatureStage::Stable, false) => spec.default_enabled,
157 (FeatureStage::Stable, true) => self
158 .features
159 .get(spec.id)
160 .copied()
161 .unwrap_or(spec.default_enabled),
162 }
163 }
164
165 fn has_tokens(&self) -> bool {
166 self.github.token.is_some()
167 || self
168 .web_boards
169 .iter()
170 .any(|board| !board.secrets.is_empty())
171 }
172
173 fn clear_tokens(&mut self) {
174 self.github.token = None;
175 self.web_boards
176 .iter_mut()
177 .for_each(|board| board.secrets.clear());
178 }
179}
180
181pub fn path() -> Option<PathBuf> {
184 dirs::config_dir().map(|dir| dir.join(crate::state::directory_name()).join("config.json"))
185}
186
187pub fn place() -> String {
190 path().map_or_else(
191 || "the config file".into(),
192 |path| path.display().to_string(),
193 )
194}
195
196pub fn load(file: &Path) -> (Config, Vec<Notice>) {
198 let text = match fs::read_to_string(file) {
199 Ok(text) => text,
200 Err(error) if error.kind() == io::ErrorKind::NotFound => return Default::default(),
201 Err(error) => {
202 let notice = warning(file, format!("cannot read the file: {error}"));
203 return (Config::default(), vec![notice]);
204 }
205 };
206 let (mut config, mut notices) = parse(&text, file);
207 if config.has_tokens() && open_to_others(file) {
208 config.clear_tokens();
209 notices.push(warning(
210 file,
211 format!(
212 "other users can read or write this file, so Subspace ignores its tokens; \
213 run `chmod 600 {}`",
214 file.display()
215 ),
216 ));
217 }
218 (config, notices)
219}
220
221pub fn load_with_boards<'a>(
223 file: &Path,
224 ids: impl IntoIterator<Item = &'a str>,
225) -> (Config, Vec<Notice>) {
226 let (mut config, mut notices) = load(file);
227 let (boards, board_notices) = board_files::load(file, ids);
228 config.board_settings = boards;
229 notices.extend(board_notices);
230 (config, notices)
231}
232
233fn warning(file: &Path, message: impl Into<String>) -> Notice {
234 Notice {
235 kind: NoticeKind::Warning,
236 file: file.into(),
237 key: String::new(),
238 message: message.into(),
239 }
240}
241
242#[cfg(unix)]
244fn open_to_others(file: &Path) -> bool {
245 use std::os::unix::fs::PermissionsExt;
246 fs::metadata(file).map_or(true, |meta| meta.permissions().mode() & 0o066 != 0)
248}
249
250#[cfg(not(unix))]
251fn open_to_others(_file: &Path) -> bool {
252 false
253}
254
255pub fn parse(text: &str, file: &Path) -> (Config, Vec<Notice>) {
259 parse_with(text, file, &crate::former_ids::installed())
260}
261
262pub(crate) fn parse_with(
264 text: &str,
265 file: &Path,
266 renames: &crate::former_ids::Renames,
267) -> (Config, Vec<Notice>) {
268 parser::parse(text, file, renames)
269}
270
271pub fn is_repo(value: &str) -> bool {
273 let part = |part: &str| {
274 !part.is_empty()
275 && part
276 .chars()
277 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
278 };
279 value
280 .split_once('/')
281 .is_some_and(|(owner, name)| part(owner) && part(name))
282}
283
284const MAX_NOTICE_CHARS: usize = 80;
286
287fn show(value: &Value) -> String {
289 value.to_string().chars().take(MAX_NOTICE_CHARS).collect()
290}
291
292#[cfg(test)]
293mod tests {
294 use std::path::Path;
295
296 use super::{ChatEngine, Config, is_repo, parse};
297 use crate::features::{FeatureSpec, FeatureStage};
298
299 fn parsed(text: &str) -> (Config, Vec<String>) {
300 let (config, notices) = parse(text, Path::new("/c/config.json"));
301 (config, notices.iter().map(ToString::to_string).collect())
302 }
303
304 #[test]
305 fn a_full_file_parses() {
306 let (config, notices) = parsed(
307 r#"{
308 "github": {"token": " gh "},
309 "chat": {"engine": "pi"},
310 "terminal": {"fontFamily": "Menlo"},
311 "boardOrder": ["github", "github-copilot-agents"],
312 "autoRefresh": false,
313 "repos": ["o/b", "O/A"],
314 "unknown": 1
315 }"#,
316 );
317 assert_eq!(notices, Vec::<String>::new());
318 assert_eq!(config.github.token.as_ref().map(|t| t.expose()), Some("gh"));
319 assert_eq!(config.repos, ["o/b", "O/A"]);
320 assert_eq!(config.chat.engine, ChatEngine::Pi);
321 assert_eq!(config.terminal["fontFamily"], "Menlo");
322 assert_eq!(config.board_order, ["github", "github-copilot-agents"]);
323 assert!(!config.auto_refresh);
324 }
325
326 #[test]
327 fn invalid_json_gives_the_defaults_and_a_notice_with_the_path() {
328 let (config, notices) = parsed("{ nope");
329 assert_eq!(config, Config::default());
330 assert_eq!(notices.len(), 1);
331 assert!(
332 notices[0].starts_with("/c/config.json: invalid JSON"),
333 "{notices:?}"
334 );
335 }
336
337 #[test]
338 fn invalid_values_keep_their_defaults_and_name_their_key() {
339 let (config, notices) =
340 parsed(r#"{"github": [], "web": {"search": {"endpoint": "http://search"}}}"#);
341 assert_eq!(config, Config::default());
342 assert_eq!(
343 notices,
344 [
345 "/c/config.json: web.search.endpoint: must be a plain https URL \
346 (no credentials, query or fragment)",
347 "/c/config.json: github: expected an object; using the defaults",
348 ]
349 );
350 }
351
352 #[test]
353 fn chat_engine_defaults_to_off_and_preserves_explicit_choices() {
354 assert_eq!(parsed("{}").0.chat.engine, ChatEngine::Off);
355 for engine in [
356 ChatEngine::Off,
357 ChatEngine::Copilot,
358 ChatEngine::Pi,
359 ChatEngine::Acp,
360 ] {
361 let config = serde_json::json!({ "chat": { "engine": engine } });
362 let (config, notices) = parsed(&config.to_string());
363 assert_eq!(config.chat.engine, engine);
364 assert!(notices.is_empty());
365 }
366 assert_eq!(ChatEngine::Copilot.label(), "Copilot");
367 assert_eq!(ChatEngine::Pi.label(), "Pi");
368 }
369
370 #[test]
371 fn web_research_is_disabled_by_default_and_parses_safe_boundaries() {
372 let defaults = parsed("{}").0;
373 assert!(defaults.web.allowed_hosts.is_empty());
374 assert_eq!(defaults.web.search.provider, None);
375
376 let (config, notices) = parsed(
377 r#"{"web":{"allowedHosts":["example.com","*.example.org"],"silentAllowedHosts":["docs.example.org"],"search":{"provider":"fixture","endpoint":"https://search.example.com/api"}}}"#,
378 );
379 assert!(notices.is_empty(), "{notices:?}");
380 assert_eq!(config.web.allowed_hosts, ["example.com", "*.example.org"]);
381 assert_eq!(config.web.silent_allowed_hosts, ["docs.example.org"]);
382 assert_eq!(config.web.search.provider.as_deref(), Some("fixture"));
383 assert_eq!(
384 config.web.search.endpoint.as_deref(),
385 Some("https://search.example.com/api")
386 );
387 }
388
389 #[test]
390 fn the_terminal_object_is_kept_as_written_and_a_non_object_is_a_notice() {
391 let (config, notices) = parsed(r#"{"terminal":{"fontSize":13,"other":true}}"#);
392 assert_eq!(config.terminal["fontSize"], 13);
393 assert_eq!(config.terminal["other"], true);
394 assert!(notices.is_empty());
395 let (config, notices) = parsed(r#"{"terminal":"bottom"}"#);
396 assert!(config.terminal.is_empty());
397 assert_eq!(notices.len(), 1);
398 }
399
400 #[test]
401 fn board_order_and_auto_refresh_have_safe_defaults_and_parse() {
402 let defaults = parsed("{}").0;
403 assert!(defaults.auto_refresh);
404 assert!(defaults.board_order.is_empty());
405
406 let (config, notices) =
407 parsed(r#"{"boardOrder":["irc",7,"irc","github"],"autoRefresh":false}"#);
408 assert_eq!(notices, Vec::<String>::new());
409 assert_eq!(config.board_order, ["irc", "irc", "github"]);
410 assert!(!config.auto_refresh);
411 }
412
413 #[test]
414 fn malformed_chat_settings_warn_and_leave_chat_off() {
415 let (config, notices) = parsed(r#"{"chat":{"engine":"other"}}"#);
416 assert_eq!(config.chat.engine, ChatEngine::Off);
417 assert_eq!(
418 notices,
419 [
420 "/c/config.json: chat.engine: expected \"off\", \"copilot\", \"pi\" or \"acp\", got \"other\"; using the default"
421 ]
422 );
423
424 let (config, notices) = parsed(r#"{"chat":[]}"#);
425 assert_eq!(config.chat.engine, ChatEngine::Off);
426 assert_eq!(
427 notices,
428 ["/c/config.json: chat: expected an object; using the defaults"]
429 );
430 }
431
432 #[test]
433 fn empty_tokens_count_as_unset() {
434 for text in [
435 r#"{"github": {"token": ""}}"#,
436 r#"{"github": {"token": null}}"#,
437 ] {
438 let (config, notices) = parsed(text);
439 assert!(notices.is_empty());
440 assert_eq!(config.github.token, None);
441 }
442 }
443
444 #[test]
445 fn repos_follow_the_my_repos_rules() {
446 let (config, notices) = parsed(
447 r#"{
448 "repos": ["Org/One", "org/one", "bad", 5, "org/two"]
449 }"#,
450 );
451 assert_eq!(config.repos, ["Org/One", "org/two"]);
452 let keys: Vec<&str> = notices
453 .iter()
454 .map(|notice| notice.split(": ").nth(1).unwrap_or_default())
455 .collect();
456 assert_eq!(keys, ["repos[2]", "repos[3]"]);
457 }
458
459 #[test]
460 fn repo_pattern() {
461 assert!(is_repo("sede-x/eva.infra_1"));
462 for bad in ["", "a", "a/", "/b", "a/b/c", "a b/c", "a/b?"] {
463 assert!(!is_repo(bad), "{bad}");
464 }
465 }
466
467 #[cfg(unix)]
468 #[test]
469 fn tokens_in_a_file_others_can_read_are_ignored() {
470 use std::fs;
471 use std::os::unix::fs::PermissionsExt;
472
473 use super::load;
474
475 let dir = tempfile::tempdir().unwrap();
476 let file = dir.path().join("config.json");
477 fs::write(&file, r#"{"github": {"token": "gh"}, "repos": ["o/a"]}"#).unwrap();
478
479 fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).unwrap();
480 let (config, notices) = load(&file);
481 assert_eq!(config.github.token, None);
482 assert_eq!(config.repos, ["o/a"]);
483 assert_eq!(notices.len(), 1);
484 assert!(notices[0].to_string().contains("chmod 600"));
485 assert!(notices[0].file == file);
486
487 fs::set_permissions(&file, fs::Permissions::from_mode(0o600)).unwrap();
488 let (config, notices) = load(&file);
489 assert!(notices.is_empty());
490 assert!(config.github.token.is_some());
491 }
492
493 #[test]
494 fn every_board_is_enabled_until_the_file_turns_one_off() {
495 let (config, notices) = parsed(r#"{"boards": {"irc": false, "github": true}}"#);
496 assert!(notices.is_empty());
497 assert!(!config.board_enabled("irc"));
498 assert!(config.board_enabled("github"));
499 assert!(
500 config.board_enabled("actions"),
501 "an unnamed board is active"
502 );
503 assert!(Config::default().board_enabled("irc"));
504 }
505
506 #[test]
507 fn board_defaults_apply_only_when_the_file_has_no_explicit_choice() {
508 let (config, notices) = parsed(r#"{"boards": {"irc": true}}"#);
509 assert!(notices.is_empty());
510 assert!(!config.board_enabled_or("actions", false));
511 assert!(config.board_enabled_or("actions", true));
512 assert!(config.board_enabled_or("irc", false));
513 }
514
515 #[test]
516 fn an_unusable_board_entry_keeps_the_product_default_and_warns() {
517 let (config, notices) = parsed(
518 r#"{"boards": {"irc": "false", "github": 0, "actions": null, " ": true,
519 "github-copilot-agents": false}}"#,
520 );
521 assert!(config.board_enabled("irc"), "a string is not coerced");
522 assert!(config.board_enabled("github"));
523 assert!(
524 config.board_enabled("actions"),
525 "null leaves the board active"
526 );
527 assert!(!config.board_enabled("github-copilot-agents"));
528 assert!(!config.board_enabled_or("irc", false));
529 assert!(config.board_enabled_or("irc", true));
530 assert!(!config.board_enabled_or("github", false));
531 assert!(config.board_enabled_or("github", true));
532 assert!(!config.board_enabled_or("actions", false));
533 assert!(config.board_enabled_or("actions", true));
534 let mut notices = notices;
535 notices.sort();
536 assert_eq!(
537 notices,
538 [
539 "/c/config.json: boards.actions: expected true or false, got null; \
540 the product default applies",
541 "/c/config.json: boards.github: expected true or false, got 0; \
542 the product default applies",
543 "/c/config.json: boards.irc: expected true or false, got \"false\"; \
544 the product default applies",
545 "/c/config.json: boards: expected a board id; ignored",
546 ]
547 );
548 }
549
550 #[test]
551 fn feature_policy_preserves_choices_through_graduation_and_removal() {
552 let mut config = Config::default();
553 config.features.insert("app.preview".into(), false);
554 let experimental = FeatureSpec {
555 id: "app.preview",
556 title: "Preview",
557 description: "Preview behavior",
558 stage: FeatureStage::Experimental,
559 default_enabled: true,
560 toggleable: true,
561 };
562 let stable = FeatureSpec {
563 stage: FeatureStage::Stable,
564 ..experimental
565 };
566 let removed = FeatureSpec {
567 stage: FeatureStage::Removed,
568 ..experimental
569 };
570
571 assert!(!config.feature_enabled(&experimental));
572 assert!(!config.feature_enabled(&stable));
573 assert!(!config.feature_enabled(&removed));
574 assert!(!config.features[experimental.id]);
575 }
576
577 #[test]
578 fn feature_defaults_and_owners_are_isolated() {
579 let mut config = Config::default();
580 config.features.insert("app.preview".into(), true);
581 config.features.insert("board.github.preview".into(), false);
582 config.features.insert("board.irc.preview".into(), true);
583 let app = FeatureSpec {
584 id: "app.preview",
585 title: "App preview",
586 description: "App preview behavior",
587 stage: FeatureStage::Experimental,
588 default_enabled: false,
589 toggleable: true,
590 };
591 let board = FeatureSpec {
592 id: "board.github.preview",
593 title: "Board preview",
594 description: "Board preview behavior",
595 ..app
596 };
597 let stable_fixed = FeatureSpec {
598 id: "board.irc.fixed",
599 title: "Fixed",
600 description: "Fixed stable behavior",
601 stage: FeatureStage::Stable,
602 default_enabled: true,
603 toggleable: false,
604 };
605 let irc = FeatureSpec {
606 id: "board.irc.preview",
607 title: "IRC preview",
608 description: "IRC preview behavior",
609 ..app
610 };
611 config.features.insert(stable_fixed.id.into(), false);
612 config.boards.insert("github".into(), false);
613
614 assert!(config.feature_enabled(&app));
615 assert!(!config.feature_enabled(&board));
616 assert!(config.feature_enabled(&irc));
617 assert!(config.feature_enabled(&stable_fixed));
618 assert!(!Config::default().feature_enabled(&app));
619 assert!(!config.features[board.id]);
620 assert!(config.features[irc.id]);
621 }
622
623 #[test]
624 fn disabling_a_board_suspends_but_does_not_delete_its_feature_choices() {
625 let feature = FeatureSpec {
626 id: "board.github.preview",
627 title: "GitHub preview",
628 description: "GitHub preview behavior",
629 stage: FeatureStage::Experimental,
630 default_enabled: false,
631 toggleable: true,
632 };
633 let malformed = FeatureSpec {
634 id: "board.github",
635 ..feature
636 };
637 let mut config = Config::default();
638 config.features.insert(feature.id.into(), true);
639 config.features.insert(malformed.id.into(), true);
640 config.boards.insert("github".into(), false);
641
642 assert!(!config.feature_enabled(&feature));
643 assert!(!config.feature_enabled(&malformed));
644 assert!(config.features[feature.id]);
645
646 config.boards.remove("github");
647 assert!(config.feature_enabled(&feature));
648 assert!(!config.feature_enabled(&malformed));
649 }
650
651 #[test]
652 fn malformed_feature_entries_warn_and_valid_unknown_flags_survive() {
653 let (config, notices) = parsed(
654 r#"{"features":{"app.pi-chat":true,"board.future.deep.option":false,"bad":true,"app.wrong":"yes","board..empty":false}}"#,
655 );
656
657 assert_eq!(config.features.len(), 2);
658 assert!(config.features["app.pi-chat"]);
659 assert!(!config.features["board.future.deep.option"]);
660 assert_eq!(notices.len(), 3);
661 assert!(notices.iter().any(|notice| notice.contains("features.bad")));
662 assert!(
663 notices
664 .iter()
665 .any(|notice| notice.contains("features.app.wrong"))
666 );
667 assert!(notices.iter().any(|notice| notice.contains("board..empty")));
668
669 let (config, notices) = parsed(r#"{"features":[]}"#);
670 assert!(config.features.is_empty());
671 assert_eq!(
672 notices,
673 ["/c/config.json: features: expected an object; using the defaults"]
674 );
675 }
676
677 #[test]
678 fn a_boards_value_that_is_not_an_object_keeps_every_board() {
679 let (config, notices) = parsed(r#"{"boards": ["irc"]}"#);
680 assert!(config.boards.is_empty());
681 assert!(config.board_enabled("irc"));
682 assert_eq!(
683 notices,
684 ["/c/config.json: boards: expected an object; using the defaults"]
685 );
686 }
687
688 #[test]
689 fn a_missing_file_gives_the_defaults_without_a_notice() {
690 let dir = tempfile::tempdir().unwrap();
691 let (config, notices) = super::load(&dir.path().join("config.json"));
692 assert_eq!(config, Config::default());
693 assert!(notices.is_empty());
694 }
695}