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>) {
257 parser::parse(text, file)
258}
259
260pub fn is_repo(value: &str) -> bool {
262 let part = |part: &str| {
263 !part.is_empty()
264 && part
265 .chars()
266 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
267 };
268 value
269 .split_once('/')
270 .is_some_and(|(owner, name)| part(owner) && part(name))
271}
272
273const MAX_NOTICE_CHARS: usize = 80;
275
276fn show(value: &Value) -> String {
278 value.to_string().chars().take(MAX_NOTICE_CHARS).collect()
279}
280
281#[cfg(test)]
282mod tests {
283 use std::path::Path;
284
285 use super::{ChatEngine, Config, is_repo, parse};
286 use crate::features::{FeatureSpec, FeatureStage};
287
288 fn parsed(text: &str) -> (Config, Vec<String>) {
289 let (config, notices) = parse(text, Path::new("/c/config.json"));
290 (config, notices.iter().map(ToString::to_string).collect())
291 }
292
293 #[test]
294 fn a_full_file_parses() {
295 let (config, notices) = parsed(
296 r#"{
297 "github": {"token": " gh "},
298 "chat": {"engine": "pi"},
299 "terminal": {"fontFamily": "Menlo"},
300 "boardOrder": ["github", "github-copilot-agents"],
301 "autoRefresh": false,
302 "repos": ["o/b", "O/A"],
303 "unknown": 1
304 }"#,
305 );
306 assert_eq!(notices, Vec::<String>::new());
307 assert_eq!(config.github.token.as_ref().map(|t| t.expose()), Some("gh"));
308 assert_eq!(config.repos, ["o/b", "O/A"]);
309 assert_eq!(config.chat.engine, ChatEngine::Pi);
310 assert_eq!(config.terminal["fontFamily"], "Menlo");
311 assert_eq!(config.board_order, ["github", "github-copilot-agents"]);
312 assert!(!config.auto_refresh);
313 }
314
315 #[test]
316 fn invalid_json_gives_the_defaults_and_a_notice_with_the_path() {
317 let (config, notices) = parsed("{ nope");
318 assert_eq!(config, Config::default());
319 assert_eq!(notices.len(), 1);
320 assert!(
321 notices[0].starts_with("/c/config.json: invalid JSON"),
322 "{notices:?}"
323 );
324 }
325
326 #[test]
327 fn invalid_values_keep_their_defaults_and_name_their_key() {
328 let (config, notices) =
329 parsed(r#"{"github": [], "web": {"search": {"endpoint": "http://search"}}}"#);
330 assert_eq!(config, Config::default());
331 assert_eq!(
332 notices,
333 [
334 "/c/config.json: web.search.endpoint: must be a plain https URL \
335 (no credentials, query or fragment)",
336 "/c/config.json: github: expected an object; using the defaults",
337 ]
338 );
339 }
340
341 #[test]
342 fn chat_engine_defaults_to_off_and_preserves_explicit_choices() {
343 assert_eq!(parsed("{}").0.chat.engine, ChatEngine::Off);
344 for engine in [
345 ChatEngine::Off,
346 ChatEngine::Copilot,
347 ChatEngine::Pi,
348 ChatEngine::Acp,
349 ] {
350 let config = serde_json::json!({ "chat": { "engine": engine } });
351 let (config, notices) = parsed(&config.to_string());
352 assert_eq!(config.chat.engine, engine);
353 assert!(notices.is_empty());
354 }
355 assert_eq!(ChatEngine::Copilot.label(), "Copilot");
356 assert_eq!(ChatEngine::Pi.label(), "Pi");
357 }
358
359 #[test]
360 fn web_research_is_disabled_by_default_and_parses_safe_boundaries() {
361 let defaults = parsed("{}").0;
362 assert!(defaults.web.allowed_hosts.is_empty());
363 assert_eq!(defaults.web.search.provider, None);
364
365 let (config, notices) = parsed(
366 r#"{"web":{"allowedHosts":["example.com","*.example.org"],"silentAllowedHosts":["docs.example.org"],"search":{"provider":"fixture","endpoint":"https://search.example.com/api"}}}"#,
367 );
368 assert!(notices.is_empty(), "{notices:?}");
369 assert_eq!(config.web.allowed_hosts, ["example.com", "*.example.org"]);
370 assert_eq!(config.web.silent_allowed_hosts, ["docs.example.org"]);
371 assert_eq!(config.web.search.provider.as_deref(), Some("fixture"));
372 assert_eq!(
373 config.web.search.endpoint.as_deref(),
374 Some("https://search.example.com/api")
375 );
376 }
377
378 #[test]
379 fn the_terminal_object_is_kept_as_written_and_a_non_object_is_a_notice() {
380 let (config, notices) = parsed(r#"{"terminal":{"fontSize":13,"other":true}}"#);
381 assert_eq!(config.terminal["fontSize"], 13);
382 assert_eq!(config.terminal["other"], true);
383 assert!(notices.is_empty());
384 let (config, notices) = parsed(r#"{"terminal":"bottom"}"#);
385 assert!(config.terminal.is_empty());
386 assert_eq!(notices.len(), 1);
387 }
388
389 #[test]
390 fn board_order_and_auto_refresh_have_safe_defaults_and_parse() {
391 let defaults = parsed("{}").0;
392 assert!(defaults.auto_refresh);
393 assert!(defaults.board_order.is_empty());
394
395 let (config, notices) =
396 parsed(r#"{"boardOrder":["irc",7,"irc","github"],"autoRefresh":false}"#);
397 assert_eq!(notices, Vec::<String>::new());
398 assert_eq!(config.board_order, ["irc", "irc", "github"]);
399 assert!(!config.auto_refresh);
400 }
401
402 #[test]
403 fn malformed_chat_settings_warn_and_leave_chat_off() {
404 let (config, notices) = parsed(r#"{"chat":{"engine":"other"}}"#);
405 assert_eq!(config.chat.engine, ChatEngine::Off);
406 assert_eq!(
407 notices,
408 [
409 "/c/config.json: chat.engine: expected \"off\", \"copilot\", \"pi\" or \"acp\", got \"other\"; using the default"
410 ]
411 );
412
413 let (config, notices) = parsed(r#"{"chat":[]}"#);
414 assert_eq!(config.chat.engine, ChatEngine::Off);
415 assert_eq!(
416 notices,
417 ["/c/config.json: chat: expected an object; using the defaults"]
418 );
419 }
420
421 #[test]
422 fn empty_tokens_count_as_unset() {
423 for text in [
424 r#"{"github": {"token": ""}}"#,
425 r#"{"github": {"token": null}}"#,
426 ] {
427 let (config, notices) = parsed(text);
428 assert!(notices.is_empty());
429 assert_eq!(config.github.token, None);
430 }
431 }
432
433 #[test]
434 fn repos_follow_the_my_repos_rules() {
435 let (config, notices) = parsed(
436 r#"{
437 "repos": ["Org/One", "org/one", "bad", 5, "org/two"]
438 }"#,
439 );
440 assert_eq!(config.repos, ["Org/One", "org/two"]);
441 let keys: Vec<&str> = notices
442 .iter()
443 .map(|notice| notice.split(": ").nth(1).unwrap_or_default())
444 .collect();
445 assert_eq!(keys, ["repos[2]", "repos[3]"]);
446 }
447
448 #[test]
449 fn repo_pattern() {
450 assert!(is_repo("sede-x/eva.infra_1"));
451 for bad in ["", "a", "a/", "/b", "a/b/c", "a b/c", "a/b?"] {
452 assert!(!is_repo(bad), "{bad}");
453 }
454 }
455
456 #[cfg(unix)]
457 #[test]
458 fn tokens_in_a_file_others_can_read_are_ignored() {
459 use std::fs;
460 use std::os::unix::fs::PermissionsExt;
461
462 use super::load;
463
464 let dir = tempfile::tempdir().unwrap();
465 let file = dir.path().join("config.json");
466 fs::write(&file, r#"{"github": {"token": "gh"}, "repos": ["o/a"]}"#).unwrap();
467
468 fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).unwrap();
469 let (config, notices) = load(&file);
470 assert_eq!(config.github.token, None);
471 assert_eq!(config.repos, ["o/a"]);
472 assert_eq!(notices.len(), 1);
473 assert!(notices[0].to_string().contains("chmod 600"));
474 assert!(notices[0].file == file);
475
476 fs::set_permissions(&file, fs::Permissions::from_mode(0o600)).unwrap();
477 let (config, notices) = load(&file);
478 assert!(notices.is_empty());
479 assert!(config.github.token.is_some());
480 }
481
482 #[test]
483 fn every_board_is_enabled_until_the_file_turns_one_off() {
484 let (config, notices) = parsed(r#"{"boards": {"irc": false, "github": true}}"#);
485 assert!(notices.is_empty());
486 assert!(!config.board_enabled("irc"));
487 assert!(config.board_enabled("github"));
488 assert!(
489 config.board_enabled("actions"),
490 "an unnamed board is active"
491 );
492 assert!(Config::default().board_enabled("irc"));
493 }
494
495 #[test]
496 fn board_defaults_apply_only_when_the_file_has_no_explicit_choice() {
497 let (config, notices) = parsed(r#"{"boards": {"irc": true}}"#);
498 assert!(notices.is_empty());
499 assert!(!config.board_enabled_or("actions", false));
500 assert!(config.board_enabled_or("actions", true));
501 assert!(config.board_enabled_or("irc", false));
502 }
503
504 #[test]
505 fn an_unusable_board_entry_keeps_the_product_default_and_warns() {
506 let (config, notices) = parsed(
507 r#"{"boards": {"irc": "false", "github": 0, "actions": null, " ": true,
508 "github-copilot-agents": false}}"#,
509 );
510 assert!(config.board_enabled("irc"), "a string is not coerced");
511 assert!(config.board_enabled("github"));
512 assert!(
513 config.board_enabled("actions"),
514 "null leaves the board active"
515 );
516 assert!(!config.board_enabled("github-copilot-agents"));
517 assert!(!config.board_enabled_or("irc", false));
518 assert!(config.board_enabled_or("irc", true));
519 assert!(!config.board_enabled_or("github", false));
520 assert!(config.board_enabled_or("github", true));
521 assert!(!config.board_enabled_or("actions", false));
522 assert!(config.board_enabled_or("actions", true));
523 let mut notices = notices;
524 notices.sort();
525 assert_eq!(
526 notices,
527 [
528 "/c/config.json: boards.actions: expected true or false, got null; \
529 the product default applies",
530 "/c/config.json: boards.github: expected true or false, got 0; \
531 the product default applies",
532 "/c/config.json: boards.irc: expected true or false, got \"false\"; \
533 the product default applies",
534 "/c/config.json: boards: expected a board id; ignored",
535 ]
536 );
537 }
538
539 #[test]
540 fn feature_policy_preserves_choices_through_graduation_and_removal() {
541 let mut config = Config::default();
542 config.features.insert("app.preview".into(), false);
543 let experimental = FeatureSpec {
544 id: "app.preview",
545 title: "Preview",
546 description: "Preview behavior",
547 stage: FeatureStage::Experimental,
548 default_enabled: true,
549 toggleable: true,
550 };
551 let stable = FeatureSpec {
552 stage: FeatureStage::Stable,
553 ..experimental
554 };
555 let removed = FeatureSpec {
556 stage: FeatureStage::Removed,
557 ..experimental
558 };
559
560 assert!(!config.feature_enabled(&experimental));
561 assert!(!config.feature_enabled(&stable));
562 assert!(!config.feature_enabled(&removed));
563 assert!(!config.features[experimental.id]);
564 }
565
566 #[test]
567 fn feature_defaults_and_owners_are_isolated() {
568 let mut config = Config::default();
569 config.features.insert("app.preview".into(), true);
570 config.features.insert("board.github.preview".into(), false);
571 config.features.insert("board.irc.preview".into(), true);
572 let app = FeatureSpec {
573 id: "app.preview",
574 title: "App preview",
575 description: "App preview behavior",
576 stage: FeatureStage::Experimental,
577 default_enabled: false,
578 toggleable: true,
579 };
580 let board = FeatureSpec {
581 id: "board.github.preview",
582 title: "Board preview",
583 description: "Board preview behavior",
584 ..app
585 };
586 let stable_fixed = FeatureSpec {
587 id: "board.irc.fixed",
588 title: "Fixed",
589 description: "Fixed stable behavior",
590 stage: FeatureStage::Stable,
591 default_enabled: true,
592 toggleable: false,
593 };
594 let irc = FeatureSpec {
595 id: "board.irc.preview",
596 title: "IRC preview",
597 description: "IRC preview behavior",
598 ..app
599 };
600 config.features.insert(stable_fixed.id.into(), false);
601 config.boards.insert("github".into(), false);
602
603 assert!(config.feature_enabled(&app));
604 assert!(!config.feature_enabled(&board));
605 assert!(config.feature_enabled(&irc));
606 assert!(config.feature_enabled(&stable_fixed));
607 assert!(!Config::default().feature_enabled(&app));
608 assert!(!config.features[board.id]);
609 assert!(config.features[irc.id]);
610 }
611
612 #[test]
613 fn disabling_a_board_suspends_but_does_not_delete_its_feature_choices() {
614 let feature = FeatureSpec {
615 id: "board.github.preview",
616 title: "GitHub preview",
617 description: "GitHub preview behavior",
618 stage: FeatureStage::Experimental,
619 default_enabled: false,
620 toggleable: true,
621 };
622 let malformed = FeatureSpec {
623 id: "board.github",
624 ..feature
625 };
626 let mut config = Config::default();
627 config.features.insert(feature.id.into(), true);
628 config.features.insert(malformed.id.into(), true);
629 config.boards.insert("github".into(), false);
630
631 assert!(!config.feature_enabled(&feature));
632 assert!(!config.feature_enabled(&malformed));
633 assert!(config.features[feature.id]);
634
635 config.boards.remove("github");
636 assert!(config.feature_enabled(&feature));
637 assert!(!config.feature_enabled(&malformed));
638 }
639
640 #[test]
641 fn malformed_feature_entries_warn_and_valid_unknown_flags_survive() {
642 let (config, notices) = parsed(
643 r#"{"features":{"app.pi-chat":true,"board.future.deep.option":false,"bad":true,"app.wrong":"yes","board..empty":false}}"#,
644 );
645
646 assert_eq!(config.features.len(), 2);
647 assert!(config.features["app.pi-chat"]);
648 assert!(!config.features["board.future.deep.option"]);
649 assert_eq!(notices.len(), 3);
650 assert!(notices.iter().any(|notice| notice.contains("features.bad")));
651 assert!(
652 notices
653 .iter()
654 .any(|notice| notice.contains("features.app.wrong"))
655 );
656 assert!(notices.iter().any(|notice| notice.contains("board..empty")));
657
658 let (config, notices) = parsed(r#"{"features":[]}"#);
659 assert!(config.features.is_empty());
660 assert_eq!(
661 notices,
662 ["/c/config.json: features: expected an object; using the defaults"]
663 );
664 }
665
666 #[test]
667 fn a_boards_value_that_is_not_an_object_keeps_every_board() {
668 let (config, notices) = parsed(r#"{"boards": ["irc"]}"#);
669 assert!(config.boards.is_empty());
670 assert!(config.board_enabled("irc"));
671 assert_eq!(
672 notices,
673 ["/c/config.json: boards: expected an object; using the defaults"]
674 );
675 }
676
677 #[test]
678 fn a_missing_file_gives_the_defaults_without_a_notice() {
679 let dir = tempfile::tempdir().unwrap();
680 let (config, notices) = super::load(&dir.path().join("config.json"));
681 assert_eq!(config, Config::default());
682 assert!(notices.is_empty());
683 }
684}