1#![allow(
9 clippy::disallowed_methods,
10 reason = "the one module that reads this process's environment"
11)]
12
13use crate::host::{Host, Os};
14use crate::provider::ProviderId;
15use crate::provider::claude::api::{Anthropic, Api};
16use crate::provider::codex::api::{Network as OpenAiNetwork, OpenAi};
17use crate::time::{Clock, SystemClock};
18use std::collections::HashMap;
19use std::ffi::{OsStr, OsString};
20use std::path::PathBuf;
21use std::sync::Arc;
22
23const READ: &[&str] = &[
36 "HOME",
37 "USER",
38 "PATH",
39 "SHELL",
40 "PITBOARD_HOME",
41 "PITBOARD_NO_ARGV",
42 "PITBOARD_API_BASE",
43 "PITBOARD_CLAUDE",
44 "PITBOARD_CODEX",
45 "CLAUDE_CONFIG_DIR",
46 "CLAUDE_SECURESTORAGE_CONFIG_DIR",
47 "CLAUDE_CODE_CUSTOM_OAUTH_URL",
48 "CLAUDE_CODE_HOVER_REST",
49 "CLAUDE_CODE_FORCE_WINDOWS_CREDMAN",
50 "CLAUDE_CODE_GIT_BASH_PATH",
51 "ANTHROPIC_PROFILE",
52 "ANTHROPIC_FEDERATION_RULE_ID",
53 "ANTHROPIC_ORGANIZATION_ID",
54 "ANTHROPIC_CONFIG_DIR",
55 "XDG_CONFIG_HOME",
56 "XDG_DATA_HOME",
57 "XDG_CACHE_HOME",
58 "XDG_RUNTIME_DIR",
59 "DBUS_SESSION_BUS_ADDRESS",
60 "WAYLAND_DISPLAY",
61 "DISPLAY",
62 "SSH_CONNECTION",
63 "WSL_DISTRO_NAME",
64 "CODEX_HOME",
65 "CODEX_INSTALL_DIR",
66 "NO_COLOR",
67 "XPC_SERVICE_NAME",
68 "SUDO_UID",
69 "USERPROFILE",
70 "USERNAME",
71 "APPDATA",
72 "LOCALAPPDATA",
73 "ProgramData",
74 "ProgramFiles",
75 "SystemRoot",
76 "PATHEXT",
77 "TEMP",
78 "TMP",
79 "OneDrive",
80 "OneDriveCommercial",
81 "OneDriveConsumer",
82];
83
84#[cfg(any(test, feature = "test-support"))]
86const READ_BY_BUILDS_FOR_TESTS: &[&str] = &[TEST_CLAUDE_DESKTOP, TEST_BUS];
87#[cfg(not(any(test, feature = "test-support")))]
88const READ_BY_BUILDS_FOR_TESTS: &[&str] = &[];
89
90#[cfg(any(test, feature = "test-support"))]
91const TEST_CLAUDE_DESKTOP: &str = "PITBOARD_TEST_CLAUDE_DESKTOP";
92#[cfg(any(test, feature = "test-support"))]
94const TEST_BUS: &str = "PITBOARD_TEST_BUS";
95
96pub(crate) fn variables() -> impl Iterator<Item = &'static str> {
98 READ.iter()
99 .chain(READ_BY_BUILDS_FOR_TESTS.iter())
100 .chain(crate::settings::OVERRIDING_ENV.iter())
101 .chain(crate::proxy::NAMING.iter())
102 .chain(crate::proxy::EXEMPTING.iter())
103 .copied()
104}
105
106#[derive(Clone, Debug, PartialEq, Eq)]
112pub struct Environment {
113 os: Os,
114 variables: HashMap<OsString, (OsString, OsString)>,
115}
116
117impl Default for Environment {
118 fn default() -> Environment {
119 Environment::on(crate::host::OS, std::iter::empty::<(OsString, OsString)>())
120 }
121}
122
123impl Environment {
124 pub(crate) fn of_this_process() -> Environment {
125 std::env::vars_os().collect()
126 }
127
128 pub(crate) fn on<K: Into<OsString>, V: Into<OsString>>(
129 os: Os,
130 pairs: impl IntoIterator<Item = (K, V)>,
131 ) -> Environment {
132 let mut variables = HashMap::new();
133 for (name, value) in pairs {
134 let (name, value) = (name.into(), value.into());
135 let key = os.variable_key(&name);
136 match os {
137 Os::MacOs | Os::Linux => {
138 variables.insert(key, (name, value));
139 }
140 Os::Windows => {
143 variables.entry(key).or_insert((name, value));
144 }
145 }
146 }
147 Environment { os, variables }
148 }
149
150 pub(crate) fn os(&self) -> Os {
151 self.os
152 }
153
154 pub(crate) fn path(&self, name: &str) -> Option<&OsStr> {
156 debug_assert!(
157 variables().any(|read| read == name),
158 "{name} is read but not listed in context::READ, so the tests would take it \
159 from whoever runs them"
160 );
161 self.variables
162 .get(&self.os.variable_key(OsStr::new(name)))
163 .map(|(_, value)| value.as_os_str())
164 }
165
166 pub(crate) fn text(&self, name: &str) -> Option<&str> {
169 self.path(name).and_then(OsStr::to_str)
170 }
171
172 pub(crate) fn spelling(&self, name: &str) -> Option<&OsStr> {
174 self.path(name)?;
175 self.variables
176 .get(&self.os.variable_key(OsStr::new(name)))
177 .map(|(spelled, _)| spelled.as_os_str())
178 }
179
180 pub(crate) fn set(&self, name: &str) -> bool {
182 self.text(name).is_some_and(|v| !v.is_empty())
183 }
184
185 pub(crate) fn named_folder(&self, name: &str) -> Option<PathBuf> {
187 self.path(name)
188 .filter(|folder| !folder.is_empty())
189 .map(PathBuf::from)
190 }
191
192 pub(crate) fn home(&self) -> PathBuf {
194 self.path(self.os.home_variable())
195 .map(PathBuf::from)
196 .or_else(crate::host::user::home)
197 .unwrap_or_default()
198 }
199
200 pub fn pitboard_home(&self) -> PathBuf {
202 self.path("PITBOARD_HOME")
203 .map(PathBuf::from)
204 .unwrap_or_else(|| self.os.default_pitboard_home(&self.home()))
205 }
206
207 #[cfg_attr(
209 windows,
210 allow(
211 dead_code,
212 reason = "what the login shell is given, and Windows has none (`host::login_path`)"
213 )
214 )]
215 pub(crate) fn iter(&self) -> impl Iterator<Item = (&OsStr, &OsStr)> {
216 self.variables
217 .values()
218 .map(|(name, value)| (name.as_os_str(), value.as_os_str()))
219 }
220}
221
222#[cfg(test)]
226fn unit_test_sentinel() -> PathBuf {
227 let thread = std::thread::current();
228 let test = thread.name().map_or_else(
229 || format!("{:?}", thread.id()),
230 |name| {
231 name.chars()
232 .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
233 .collect()
234 },
235 );
236 std::env::temp_dir()
237 .join(format!("pitboard-unit-test-{}", std::process::id()))
238 .join(test)
239}
240
241impl<K: Into<OsString>, V: Into<OsString>> FromIterator<(K, V)> for Environment {
242 fn from_iter<I: IntoIterator<Item = (K, V)>>(pairs: I) -> Environment {
243 Environment::on(crate::host::OS, pairs)
244 }
245}
246
247#[derive(Debug, Clone)]
249pub struct ScratchClaude {
250 pub data: PathBuf,
251 pub app: PathBuf,
252}
253
254#[cfg(any(test, feature = "test-support"))]
256pub(crate) fn refuse_a_real_claude(path: &std::path::Path) {
257 use crate::host::user;
258 assert!(
259 !path
260 .components()
261 .any(|part| part == std::path::Component::ParentDir),
262 "a test named {} for Claude through `..`, which may lead anywhere once a folder is made: \
263 give it a folder of its own",
264 path.display()
265 );
266 #[cfg(test)]
267 let fake = testing::guarded_home();
268 #[cfg(not(test))]
269 let fake: Option<PathBuf> = None;
270 let real = match crate::host::OS {
271 Os::MacOs | Os::Linux => {
272 ["Library/Application Support", "Applications/Claude.app"]
273 .into_iter()
274 .any(|below| {
275 user::lies_in_the_accounts_own(path, below)
276 || fake
277 .as_ref()
278 .is_some_and(|home| crate::host::lies_in(path, &home.join(below)))
279 })
280 || crate::host::lies_in(path, std::path::Path::new("/Applications/Claude.app"))
281 }
282 Os::Windows => {
283 let (mut roaming, mut local) = user::app_data_folders(true);
284 if let Some(home) = &fake {
285 roaming.push(home.join("AppData").join("Roaming"));
286 local.push(home.join("AppData").join("Local"));
287 }
288 crate::host::claude_desktop_on_windows(&roaming, &local)
289 .iter()
290 .any(|place| crate::host::lies_in(path, place))
291 }
292 };
293 assert!(
294 !real,
295 "a test named {} for Claude, which is, holds or lies in where this account's own \
296 Claude Desktop keeps its data or its app: give it a folder of its own",
297 path.display()
298 );
299}
300
301#[cfg(test)]
302pub(crate) mod testing {
303 use std::cell::RefCell;
304 use std::path::{Path, PathBuf};
305
306 thread_local! {
307 static GUARDED: RefCell<Option<PathBuf>> = const { RefCell::new(None) };
308 }
309
310 pub(crate) fn also_guarding(home: &Path) -> AlsoGuarding {
313 GUARDED.with(|guarded| *guarded.borrow_mut() = Some(home.to_path_buf()));
314 AlsoGuarding(())
315 }
316
317 pub(crate) struct AlsoGuarding(());
318
319 impl Drop for AlsoGuarding {
320 fn drop(&mut self) {
321 GUARDED.with(|guarded| guarded.borrow_mut().take());
322 }
323 }
324
325 pub(super) fn guarded_home() -> Option<PathBuf> {
326 GUARDED.with(|guarded| guarded.borrow().clone())
327 }
328}
329
330#[derive(Clone, Debug)]
331pub struct Context {
332 pub(crate) os: Os,
334 pub(crate) home: PathBuf,
335 pub(crate) pitboard_home: PathBuf,
336 pub(crate) claude_config_dir: Option<String>,
342 pub(crate) secure_storage_dir: Option<String>,
345 pub(crate) user: Option<String>,
347 pub(crate) custom_oauth: bool,
350 pub(crate) overriding_auth: Vec<String>,
354 pub(crate) anthropic: crate::settings::Profiles,
355 pub(crate) argv_fallback: bool,
360 pub(crate) caller: String,
363 pub(crate) programs: std::collections::BTreeMap<ProviderId, PathBuf>,
365 pub(crate) api_base: Option<String>,
367 pub(crate) proxy: crate::proxy::Proxies,
370 pub(crate) agent: crate::api::Agents,
373 pub(crate) hover_rest: bool,
375 pub(crate) credential_manager_forced: bool,
378 pub(crate) codex_home: Option<String>,
380 pub(crate) profile: Option<PathBuf>,
382 pub(crate) local_app_data: Option<PathBuf>,
384 pub(crate) program_files: Option<PathBuf>,
386 pub(crate) system_root: Option<PathBuf>,
387 pub(crate) sid: Option<String>,
389 pub(crate) one_drive: Vec<PathBuf>,
391 pub(crate) schedule_program: Option<PathBuf>,
395 pub(crate) search_path: Option<OsString>,
400 pub(crate) installer_places: std::collections::BTreeMap<ProviderId, Vec<PathBuf>>,
403 pub(crate) path_ext: Option<OsString>,
405 pub(crate) git_bash: Option<PathBuf>,
407 pub(crate) wsl_distro: Option<String>,
409 pub(crate) config_home: Option<PathBuf>,
412 pub(crate) data_home: Option<PathBuf>,
413 pub(crate) cache_home: Option<PathBuf>,
414 pub(crate) runtime_dir: Option<PathBuf>,
418 pub(crate) session_bus_address: Option<String>,
419 pub(crate) desktop_session: bool,
423 pub(crate) prompt_dismissed: Arc<std::sync::atomic::AtomicBool>,
426 pub(crate) scheduled_job: Option<String>,
429 pub(crate) started_by: Option<crate::schedule::Job>,
432 pub(crate) sudo: bool,
436 pub(crate) clock: Arc<dyn Clock>,
439 pub(crate) locks: crate::lock::Locks,
442 pub(crate) host: Arc<dyn Host>,
445 pub(crate) api: Arc<dyn Api>,
447 pub(crate) openai: Arc<dyn OpenAi>,
449 #[cfg(any(test, feature = "test-support"))]
453 pub(crate) sign_in_script: Option<Arc<dyn crate::switch::SignInScript>>,
454 #[cfg(any(test, feature = "test-support"))]
455 scratch_claude: Option<ScratchClaude>,
456 #[cfg(any(test, feature = "test-support"))]
458 test_bus: Option<String>,
459 #[cfg(any(test, feature = "test-support"))]
460 awaited_every: Option<std::time::Duration>,
461 #[cfg(test)]
462 unknown_machine: bool,
463 #[cfg(any(test, feature = "test-support"))]
467 pub(crate) warm_script: Option<Arc<dyn crate::duty::warm::run::WarmScript>>,
468}
469
470fn base_folder(
474 os: Os,
475 home: &std::path::Path,
476 named: Option<PathBuf>,
477 default: &[&str],
478) -> Option<PathBuf> {
479 match os {
480 Os::MacOs | Os::Linux => Some(named.filter(|folder| folder.is_absolute()).unwrap_or_else(
481 || {
482 default
483 .iter()
484 .fold(home.to_path_buf(), |at, part| at.join(part))
485 },
486 )),
487 Os::Windows => None,
488 }
489}
490
491#[derive(Clone, Debug, PartialEq, Eq)]
493#[cfg_attr(
494 not(target_os = "linux"),
495 allow(dead_code, reason = "only Linux has a session bus to find")
496)]
497pub(crate) enum SessionBus {
498 Address(String),
500 Socket(PathBuf),
502}
503
504const CONFIG_HOME: &[&str] = &[".config"];
505const DATA_HOME: &[&str] = &[".local", "share"];
506const CACHE_HOME: &[&str] = &[".cache"];
507
508fn programs(
509 named: impl Fn(ProviderId, crate::provider::Cli) -> PathBuf,
510) -> std::collections::BTreeMap<ProviderId, PathBuf> {
511 ProviderId::ALL
512 .iter()
513 .filter_map(|&tool| Some((tool, named(tool, tool.cli()?))))
514 .collect()
515}
516
517impl Context {
518 pub(crate) fn now(&self) -> i64 {
520 self.clock.now()
521 }
522
523 pub(crate) fn now_millis(&self) -> i64 {
525 self.clock.now_millis()
526 }
527
528 pub(crate) fn zone(&self) -> jiff::tz::TimeZone {
530 self.clock.zone()
531 }
532
533 pub(crate) fn home(&self) -> &std::path::Path {
535 &self.home
536 }
537
538 pub fn config_home(&self) -> Option<&std::path::Path> {
542 self.config_home.as_deref()
543 }
544
545 pub fn data_home(&self) -> Option<&std::path::Path> {
547 self.data_home.as_deref()
548 }
549
550 pub fn cache_home(&self) -> Option<&std::path::Path> {
552 self.cache_home.as_deref()
553 }
554
555 #[cfg_attr(
559 not(target_os = "linux"),
560 allow(dead_code, reason = "only Linux has a session bus to find")
561 )]
562 pub(crate) fn session_bus(&self) -> Option<SessionBus> {
563 match (&self.session_bus_address, &self.runtime_dir) {
564 (Some(address), _) => Some(SessionBus::Address(address.clone())),
565 (None, Some(runtime)) => Some(SessionBus::Socket(runtime.join("bus"))),
566 (None, None) => None,
567 }
568 }
569
570 #[cfg_attr(
573 not(target_os = "linux"),
574 allow(dead_code, reason = "only Linux's keyring is asked to unlock")
575 )]
576 pub(crate) fn in_the_desktop_session(&self) -> bool {
577 self.desktop_session
578 }
579
580 #[cfg_attr(
582 not(target_os = "linux"),
583 allow(dead_code, reason = "only Linux's keyring is asked to unlock")
584 )]
585 pub(crate) fn unlock_was_dismissed(&self) -> bool {
586 self.prompt_dismissed
587 .load(std::sync::atomic::Ordering::SeqCst)
588 }
589
590 #[cfg_attr(
591 not(target_os = "linux"),
592 allow(dead_code, reason = "only Linux's keyring is asked to unlock")
593 )]
594 pub(crate) fn unlock_dismissed(&self) {
595 self.prompt_dismissed
596 .store(true, std::sync::atomic::Ordering::SeqCst);
597 }
598
599 pub(crate) fn default_pitboard_home(&self) -> PathBuf {
601 self.os.default_pitboard_home(&self.home)
602 }
603
604 pub(crate) fn host(&self) -> &dyn Host {
606 self.host.as_ref()
607 }
608
609 pub(crate) fn openai(&self) -> &dyn OpenAi {
611 self.openai.as_ref()
612 }
613
614 pub(crate) fn api(&self) -> &dyn Api {
615 self.api.as_ref()
616 }
617
618 #[cfg(any(test, feature = "test-support"))]
619 #[doc(hidden)]
620 pub fn new(home: PathBuf) -> Context {
621 let base = |default| base_folder(crate::host::OS, &home, None, default);
622 let (config_home, data_home, cache_home) =
623 (base(CONFIG_HOME), base(DATA_HOME), base(CACHE_HOME));
624 Context {
625 os: crate::host::OS,
626 pitboard_home: crate::host::OS.default_pitboard_home(&home),
627 home,
628 claude_config_dir: None,
629 secure_storage_dir: None,
630 user: None,
631 custom_oauth: false,
632 argv_fallback: true,
633 overriding_auth: Vec::new(),
634 anthropic: crate::settings::Profiles::default(),
635 caller: "unknown".into(),
636 programs: programs(|tool, _| PathBuf::from(tool.program())),
637 api_base: None,
638 proxy: crate::proxy::Proxies::default(),
639 agent: crate::api::Agents::default(),
640 hover_rest: false,
641 credential_manager_forced: false,
642 codex_home: None,
643 profile: None,
644 local_app_data: None,
645 program_files: None,
646 system_root: None,
647 sid: None,
648 one_drive: Vec::new(),
649 schedule_program: None,
650 search_path: None,
651 installer_places: std::collections::BTreeMap::new(),
652 path_ext: None,
653 git_bash: None,
654 wsl_distro: None,
655 config_home,
656 data_home,
657 cache_home,
658 runtime_dir: None,
659 session_bus_address: None,
660 desktop_session: false,
661 prompt_dismissed: Arc::default(),
662 scheduled_job: None,
663 started_by: None,
664 sudo: false,
665 clock: Arc::new(SystemClock),
666 locks: crate::lock::Locks::CLAUDE_CODE,
667 host: crate::host::current(),
668 api: Arc::new(Anthropic),
669 openai: Arc::new(OpenAiNetwork),
670 #[cfg(any(test, feature = "test-support"))]
671 sign_in_script: None,
672 #[cfg(any(test, feature = "test-support"))]
673 scratch_claude: None,
674 #[cfg(any(test, feature = "test-support"))]
675 test_bus: None,
676 #[cfg(any(test, feature = "test-support"))]
677 awaited_every: None,
678 #[cfg(test)]
679 unknown_machine: false,
680 #[cfg(any(test, feature = "test-support"))]
681 warm_script: None,
682 }
683 }
684
685 pub fn with_codex_home(mut self, dir: String) -> Context {
687 self.codex_home = Some(dir).filter(|d| !d.is_empty());
688 self
689 }
690
691 pub(crate) fn codex_home(&self) -> Option<&str> {
692 self.codex_home.as_deref()
693 }
694
695 #[cfg(test)]
696 pub(crate) fn with_profile(mut self, profile: PathBuf) -> Context {
697 self.profile = Some(profile);
698 self
699 }
700
701 pub fn with_pitboard_home(mut self, dir: PathBuf) -> Context {
702 self.pitboard_home = dir;
703 self
704 }
705
706 #[cfg(any(test, feature = "test-support"))]
711 #[doc(hidden)]
712 pub fn with_claude_config_dir(mut self, dir: String) -> Context {
713 self.claude_config_dir = Some(dir);
714 self
715 }
716
717 pub(crate) fn signed_in_at(&self, dir: &std::path::Path) -> Context {
720 let mut ctx = self.clone();
721 ctx.claude_config_dir = Some(dir.to_string_lossy().into_owned());
722 ctx
723 }
724
725 #[cfg(test)]
728 pub(crate) fn with_secure_storage_dir(mut self, dir: String) -> Context {
729 self.secure_storage_dir = Some(dir);
730 self
731 }
732
733 #[cfg(any(test, feature = "test-support"))]
735 #[doc(hidden)]
736 pub fn with_argv_fallback(mut self, allowed: bool) -> Context {
737 self.argv_fallback = allowed;
738 self
739 }
740
741 pub(crate) fn custom_oauth(&self) -> bool {
743 self.custom_oauth
744 }
745
746 #[cfg(any(test, feature = "test-support"))]
747 #[doc(hidden)]
748 pub fn claude_program(&self) -> &std::path::Path {
749 &self.programs[&ProviderId::Claude]
750 }
751
752 pub(crate) fn argv_fallback(&self) -> bool {
754 self.argv_fallback
755 }
756
757 pub(crate) fn overriding_auth(&self) -> &[String] {
759 &self.overriding_auth
760 }
761
762 #[cfg(any(test, feature = "test-support"))]
764 #[doc(hidden)]
765 pub fn with_caller(mut self, caller: String) -> Context {
766 self.caller = caller;
767 self
768 }
769
770 #[cfg(any(test, feature = "test-support"))]
771 #[doc(hidden)]
772 pub fn with_user(mut self, user: String) -> Context {
773 self.user = Some(user);
774 self
775 }
776
777 #[cfg(any(test, feature = "test-support"))]
779 #[doc(hidden)]
780 pub fn with_claude_program(mut self, program: PathBuf) -> Context {
781 self.programs.insert(ProviderId::Claude, program);
782 self
783 }
784
785 #[cfg(any(test, feature = "test-support"))]
787 #[doc(hidden)]
788 pub fn with_codex_program(mut self, program: PathBuf) -> Context {
789 self.programs.insert(ProviderId::Codex, program);
790 self
791 }
792
793 #[cfg(any(test, feature = "test-support"))]
794 #[doc(hidden)]
795 pub fn codex_program(&self) -> &std::path::Path {
796 &self.programs[&ProviderId::Codex]
797 }
798
799 #[cfg(any(test, feature = "test-support"))]
802 #[doc(hidden)]
803 pub fn with_schedule_program(mut self, program: PathBuf) -> Context {
804 self.schedule_program = Some(program);
805 self
806 }
807
808 pub fn schedule_program(&self) -> Option<&std::path::Path> {
810 self.schedule_program.as_deref()
811 }
812
813 #[cfg(any(test, feature = "test-support"))]
818 #[doc(hidden)]
819 pub fn with_search_path(mut self, path: String) -> Context {
820 self.search_path = Some(path.into());
821 self
822 }
823
824 pub(crate) fn lookup(&self) -> crate::host::program::Lookup {
826 crate::host::program::Lookup::new(self.os, self.path_ext.as_deref())
827 }
828
829 pub(crate) fn search_path(&self) -> OsString {
831 self.search_path
832 .clone()
833 .or_else(|| std::env::var_os("PATH"))
834 .unwrap_or_default()
835 }
836
837 pub(crate) fn scheduled_job(&self) -> Option<&str> {
840 self.scheduled_job.as_deref()
841 }
842
843 pub(crate) fn sudo(&self) -> bool {
845 self.sudo
846 }
847
848 #[cfg(test)]
850 pub(crate) fn with_scheduled_job(mut self, label: String) -> Context {
851 self.scheduled_job = Some(label);
852 self
853 }
854
855 pub fn started_by_the_schedule(mut self) -> Context {
861 self.started_by = Some(crate::schedule::Job::Renew);
862 self
863 }
864
865 pub fn started_by_the_watch_service(mut self) -> Context {
870 self.started_by = Some(crate::schedule::Job::Watch);
871 crate::schedule::for_its_run(&self, crate::schedule::Job::Watch)
872 }
873
874 pub(crate) fn started_by(&self) -> Option<crate::schedule::Job> {
876 self.started_by
877 }
878
879 pub(crate) fn with_proxy_variables_over(mut self, given: &[(String, String)]) -> Context {
881 let os = self.os;
882 let key = |name: &str| os.variable_key(OsStr::new(name));
883 let own = self
884 .proxy
885 .variables()
886 .iter()
887 .filter(|(name, _)| !given.iter().any(|(over, _)| key(over) == key(name)))
888 .map(|(name, value)| ((*name).to_string(), value.clone()));
889 let env = Environment::on(os, given.iter().cloned().chain(own));
890 self.proxy = crate::proxy::Proxies::read(&env);
891 self.agent = crate::api::Agents::default();
892 self
893 }
894
895 pub(crate) fn program_for(&self, tool: ProviderId) -> Option<&std::path::Path> {
897 self.programs.get(&tool).map(PathBuf::as_path)
898 }
899
900 pub(crate) fn scratch_claude(&self) -> Option<&ScratchClaude> {
902 #[cfg(any(test, feature = "test-support"))]
903 {
904 self.scratch_claude.as_ref()
905 }
906 #[cfg(not(any(test, feature = "test-support")))]
907 {
908 None
909 }
910 }
911
912 #[cfg(any(test, feature = "test-support"))]
914 #[doc(hidden)]
915 pub fn with_scratch_claude(mut self, folder: PathBuf) -> Context {
916 assert!(
917 folder.is_absolute(),
918 "a test named its Claude folder {} relative to wherever it runs: name it in full",
919 folder.display()
920 );
921 let scratch = ScratchClaude {
922 data: folder.join("data"),
923 app: folder.join("Claude.app"),
924 };
925 for named in [&folder, &scratch.data, &scratch.app] {
926 refuse_a_real_claude(named);
927 }
928 self.scratch_claude = Some(scratch);
929 self
930 }
931
932 #[cfg(any(test, feature = "test-support"))]
934 #[cfg_attr(
935 not(target_os = "linux"),
936 allow(dead_code, reason = "only Linux has a session bus to find")
937 )]
938 pub(crate) fn test_bus(&self) -> Option<&str> {
939 self.test_bus.as_deref()
940 }
941
942 #[cfg(any(test, feature = "test-support"))]
945 #[doc(hidden)]
946 pub fn with_test_bus(mut self, address: String) -> Context {
947 self.test_bus = Some(address);
948 self
949 }
950
951 pub(crate) fn awaited_every(&self) -> std::time::Duration {
953 #[cfg(any(test, feature = "test-support"))]
954 if let Some(every) = self.awaited_every {
955 return every;
956 }
957 std::time::Duration::from_secs(1)
958 }
959
960 #[cfg(any(test, feature = "test-support"))]
961 #[doc(hidden)]
962 pub fn with_awaited_every(mut self, every: std::time::Duration) -> Context {
963 self.awaited_every = Some(every);
964 self
965 }
966
967 pub(crate) fn this_machine(&self) -> String {
969 #[cfg(test)]
970 if self.unknown_machine {
971 return crate::state::UNKNOWN_MACHINE.into();
972 }
973 crate::state::machine_id()
974 }
975
976 #[cfg(all(test, not(windows)))]
978 pub(crate) fn with_unknown_machine(mut self) -> Context {
979 self.unknown_machine = true;
980 self
981 }
982
983 pub fn from_env() -> Context {
985 Context::for_command_line(&Environment::of_this_process())
986 }
987
988 pub fn for_command_line(env: &Environment) -> Context {
991 Context::read(env, "cli")
992 }
993
994 #[cfg(test)]
1005 pub(crate) fn for_unit_test() -> Context {
1006 let sentinel = unit_test_sentinel().into_os_string();
1007 let homes = [
1008 "HOME",
1009 "USERPROFILE",
1010 "PITBOARD_HOME",
1011 "CLAUDE_CONFIG_DIR",
1012 "CODEX_HOME",
1013 ];
1014 let kept: Environment = std::env::vars_os()
1015 .filter(|(name, _)| !variables().any(|read| name == read))
1016 .chain(homes.map(|home| (home.into(), sentinel.clone())))
1017 .collect();
1018 Context::for_command_line(&kept)
1019 }
1020
1021 pub(crate) fn read(env: &Environment, caller: &str) -> Context {
1029 let home = env.home();
1030 let owned = |name: &str| env.text(name).map(str::to_owned);
1031 let program = |tool: ProviderId, cli: crate::provider::Cli| {
1032 env.path(cli.program_variable)
1033 .filter(|named| !named.is_empty())
1034 .map_or_else(|| PathBuf::from(tool.program()), PathBuf::from)
1035 };
1036 let base =
1037 |variable, default| base_folder(env.os(), &home, env.named_folder(variable), default);
1038 let (config_home, data_home, cache_home) = (
1039 base("XDG_CONFIG_HOME", CONFIG_HOME),
1040 base("XDG_DATA_HOME", DATA_HOME),
1041 base("XDG_CACHE_HOME", CACHE_HOME),
1042 );
1043 let read = Context {
1044 os: env.os(),
1045 pitboard_home: env.pitboard_home(),
1046 home,
1047 claude_config_dir: owned("CLAUDE_CONFIG_DIR"),
1048 secure_storage_dir: owned("CLAUDE_SECURESTORAGE_CONFIG_DIR"),
1049 user: owned(env.os().user_variable()),
1050 custom_oauth: env.set("CLAUDE_CODE_CUSTOM_OAUTH_URL"),
1051 argv_fallback: env.text("PITBOARD_NO_ARGV") != Some("1"),
1052 overriding_auth: crate::settings::OVERRIDING_ENV
1053 .iter()
1054 .filter(|name| env.set(name))
1055 .map(|name| (*name).to_string())
1056 .collect(),
1057 anthropic: crate::settings::Profiles::read(env),
1058 caller: caller.into(),
1059 programs: programs(program),
1060 api_base: owned("PITBOARD_API_BASE"),
1061 proxy: crate::proxy::Proxies::read(env),
1062 agent: crate::api::Agents::default(),
1063 hover_rest: matches!(env.text("CLAUDE_CODE_HOVER_REST"), Some("1" | "true")),
1064 credential_manager_forced: env.text("CLAUDE_CODE_FORCE_WINDOWS_CREDMAN") == Some("1"),
1065 codex_home: owned("CODEX_HOME").filter(|v| !v.is_empty()),
1066 profile: (env.os() == Os::Windows)
1067 .then(crate::host::user::profile)
1068 .flatten(),
1069 local_app_data: env
1070 .path("LOCALAPPDATA")
1071 .filter(|_| env.os() == Os::Windows)
1072 .map(PathBuf::from),
1073 program_files: env
1074 .named_folder("ProgramFiles")
1075 .filter(|_| env.os() == Os::Windows),
1076 system_root: env
1077 .named_folder("SystemRoot")
1078 .filter(|_| env.os() == Os::Windows),
1079 sid: (env.os() == Os::Windows)
1080 .then(crate::host::user::sid)
1081 .flatten(),
1082 one_drive: ["OneDrive", "OneDriveCommercial", "OneDriveConsumer"]
1083 .into_iter()
1084 .filter(|_| env.os() == Os::Windows)
1085 .filter_map(|name| env.path(name).filter(|folder| !folder.is_empty()))
1086 .map(PathBuf::from)
1087 .collect(),
1088 schedule_program: None,
1089 search_path: Some(env.path("PATH").unwrap_or_default().to_os_string()),
1091 installer_places: std::collections::BTreeMap::new(),
1092 path_ext: env.path("PATHEXT").map(OsStr::to_os_string),
1093 git_bash: env
1094 .path("CLAUDE_CODE_GIT_BASH_PATH")
1095 .filter(|named| env.os() == Os::Windows && !named.is_empty())
1096 .map(PathBuf::from),
1097 wsl_distro: env
1098 .path("WSL_DISTRO_NAME")
1099 .filter(|_| env.os() == Os::Linux)
1100 .map(|named| named.to_string_lossy().into_owned()),
1101 config_home,
1102 data_home,
1103 cache_home,
1104 runtime_dir: env
1105 .named_folder("XDG_RUNTIME_DIR")
1106 .filter(|folder| env.os() == Os::Linux && folder.is_absolute()),
1107 session_bus_address: owned("DBUS_SESSION_BUS_ADDRESS")
1108 .filter(|address| env.os() == Os::Linux && !address.is_empty()),
1109 desktop_session: env.os() == Os::Linux
1110 && (env.set("WAYLAND_DISPLAY") || env.set("DISPLAY"))
1111 && !env.set("SSH_CONNECTION"),
1112 prompt_dismissed: Arc::default(),
1113 scheduled_job: None,
1114 started_by: None,
1115 sudo: env.set("SUDO_UID"),
1116 clock: Arc::new(SystemClock),
1117 locks: crate::lock::Locks::CLAUDE_CODE,
1118 host: crate::host::current(),
1119 api: Arc::new(Anthropic),
1120 openai: Arc::new(OpenAiNetwork),
1121 #[cfg(any(test, feature = "test-support"))]
1122 sign_in_script: None,
1123 #[cfg(any(test, feature = "test-support"))]
1124 scratch_claude: None,
1125 #[cfg(any(test, feature = "test-support"))]
1126 test_bus: owned(TEST_BUS)
1127 .filter(|address| env.os() == Os::Linux && !address.is_empty()),
1128 #[cfg(any(test, feature = "test-support"))]
1129 awaited_every: None,
1130 #[cfg(test)]
1131 unknown_machine: false,
1132 #[cfg(any(test, feature = "test-support"))]
1133 warm_script: None,
1134 };
1135 #[cfg(any(test, feature = "test-support"))]
1136 if let Some(folder) = env.path(TEST_CLAUDE_DESKTOP).filter(|f| !f.is_empty()) {
1137 return read.with_scratch_claude(PathBuf::from(folder));
1138 }
1139 read
1140 }
1141
1142 #[cfg(any(test, feature = "test-support"))]
1146 #[doc(hidden)]
1147 pub fn with_scripted_api(mut self, api: Arc<crate::api::scripted::ScriptedApi>) -> Context {
1148 self.api = api.clone();
1149 self.openai = api;
1150 self
1151 }
1152
1153 #[cfg(any(test, feature = "test-support"))]
1156 #[doc(hidden)]
1157 pub fn with_memory_stores(mut self, memory: Arc<crate::host::memory::MemoryHost>) -> Context {
1158 self.host = memory;
1159 self
1160 }
1161
1162 #[cfg(any(test, feature = "test-support"))]
1165 #[doc(hidden)]
1166 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Context {
1167 self.clock = clock;
1168 self
1169 }
1170
1171 #[cfg(any(test, feature = "test-support"))]
1175 #[doc(hidden)]
1176 pub fn with_lock_waiting(mut self, retries: u32, every: std::time::Duration) -> Context {
1177 self.locks = crate::lock::Locks {
1178 write: self.locks.write.asked(retries, every),
1179 refresh: self.locks.refresh.asked(retries, every),
1180 };
1181 self
1182 }
1183
1184 #[cfg(any(test, feature = "test-support"))]
1189 #[doc(hidden)]
1190 pub fn with_sign_in_script(
1191 mut self,
1192 script: Arc<dyn crate::switch::enroll::SignInScript>,
1193 ) -> Context {
1194 self.sign_in_script = Some(script);
1195 self
1196 }
1197
1198 #[cfg(any(test, feature = "test-support"))]
1200 pub(crate) fn sign_in_script(&self) -> Option<&Arc<dyn crate::switch::enroll::SignInScript>> {
1201 self.sign_in_script.as_ref()
1202 }
1203
1204 #[cfg(any(test, feature = "test-support"))]
1207 #[doc(hidden)]
1208 pub fn with_warm_script(
1209 mut self,
1210 script: Arc<dyn crate::duty::warm::run::WarmScript>,
1211 ) -> Context {
1212 self.warm_script = Some(script);
1213 self
1214 }
1215
1216 #[cfg(any(test, feature = "test-support"))]
1218 pub(crate) fn warm_script(&self) -> Option<&Arc<dyn crate::duty::warm::run::WarmScript>> {
1219 self.warm_script.as_ref()
1220 }
1221
1222 #[cfg(any(test, feature = "test-support"))]
1223 fn reaches_only(
1224 &self,
1225 memory: &Arc<crate::host::memory::MemoryHost>,
1226 api: &Arc<crate::api::scripted::ScriptedApi>,
1227 ) -> bool {
1228 std::ptr::addr_eq(Arc::as_ptr(&self.host), Arc::as_ptr(memory))
1229 && std::ptr::addr_eq(Arc::as_ptr(&self.api), Arc::as_ptr(api))
1230 && std::ptr::addr_eq(Arc::as_ptr(&self.openai), Arc::as_ptr(api))
1231 }
1232}
1233
1234#[cfg(any(test, feature = "test-support"))]
1236#[doc(hidden)]
1237pub struct ScratchMachine {
1238 pub ctx: Context,
1239 pub host: Arc<crate::host::memory::MemoryHost>,
1240 pub api: Arc<crate::api::scripted::ScriptedApi>,
1241}
1242
1243#[cfg(any(test, feature = "test-support"))]
1244impl ScratchMachine {
1245 pub fn at(home: &std::path::Path, more: impl FnOnce(Context) -> Context) -> ScratchMachine {
1247 ScratchMachine::on(crate::host::memory::MemoryHost::new(), home, more)
1248 }
1249
1250 pub fn on(
1252 host: Arc<crate::host::memory::MemoryHost>,
1253 home: &std::path::Path,
1254 more: impl FnOnce(Context) -> Context,
1255 ) -> ScratchMachine {
1256 let api = crate::api::scripted::ScriptedApi::new();
1257 let ctx = more(
1258 Context::new(home.to_path_buf())
1259 .with_memory_stores(Arc::clone(&host))
1260 .with_scripted_api(Arc::clone(&api)),
1261 );
1262 assert!(
1263 ctx.reaches_only(&host, &api),
1264 "a scratch machine reaches this one's keychain or the network"
1265 );
1266 ScratchMachine { ctx, host, api }
1267 }
1268}
1269
1270#[cfg(test)]
1271mod tests {
1272 use super::*;
1273 use std::path::Path;
1274
1275 #[test]
1276 fn the_test_variable_is_listed_only_in_a_build_for_tests() {
1277 assert!(variables().any(|name| name == "PITBOARD_TEST_CLAUDE_DESKTOP"));
1278 assert!(!READ.contains(&"PITBOARD_TEST_CLAUDE_DESKTOP"));
1279 assert!(Context::for_unit_test().scratch_claude().is_none());
1280 let scratch = tempfile::tempdir().expect("a scratch folder");
1281 let folder = scratch.path().join("claude");
1282 let named = folder.to_string_lossy().into_owned();
1283 let env: Environment = [
1284 ("HOME", "/home/x"),
1285 ("PITBOARD_TEST_CLAUDE_DESKTOP", named.as_str()),
1286 ]
1287 .into_iter()
1288 .collect();
1289 let read = Context::for_command_line(&env);
1290 let scratch = read.scratch_claude().expect("named");
1291 assert_eq!(scratch.data, folder.join("data"));
1292 assert_eq!(scratch.app, folder.join("Claude.app"));
1293 }
1294
1295 #[test]
1297 fn the_test_bus_is_listed_only_in_a_build_for_tests_and_read_on_linux() {
1298 assert!(variables().any(|name| name == "PITBOARD_TEST_BUS"));
1299 assert!(!READ.contains(&"PITBOARD_TEST_BUS"));
1300 assert_eq!(Context::for_unit_test().test_bus(), None);
1301 let address = "unix:path=/tmp/pitboard-test/bus";
1302 let read = |os| {
1303 let pairs = [("HOME", "/home/x"), ("PITBOARD_TEST_BUS", address)];
1304 Context::read(&Environment::on(os, pairs), "cli")
1305 };
1306 assert_eq!(read(Os::Linux).test_bus(), Some(address));
1307 assert_eq!(read(Os::MacOs).test_bus(), None);
1308 }
1309
1310 #[test]
1312 #[cfg_attr(
1313 windows,
1314 ignore = "Claude Desktop is macOS only: Windows names no Application Support"
1315 )]
1316 fn a_scratch_inside_the_real_application_support_panics() {
1317 let home = {
1318 let _reaching = crate::host::user::testing::reaching_the_real_home();
1319 crate::host::user::home().expect("this account has a home")
1320 };
1321 let support = home.join("Library/Application Support");
1322 let named = |folder: PathBuf| {
1323 std::panic::catch_unwind(move || {
1324 Context::new("/nowhere".into()).with_scratch_claude(folder)
1325 })
1326 .is_err()
1327 };
1328 assert!(named(support.join("pitboard-test-never-made")));
1329 assert!(named(support.clone()));
1330 assert!(named(home.join("Library")), "it holds it");
1331 let scratch = tempfile::tempdir().expect("a scratch folder");
1333 let link = scratch.path().join("home-link");
1334 crate::host::fs::testing::link_dir(&home, &link).expect("a link");
1335 let through = named(link.join("Library/Application Support/pitboard-test-never-made"));
1336 let _ = std::fs::remove_file(&link);
1337 assert!(through, "through a link");
1338 assert!(!named(scratch.path().join("elsewhere")));
1339 let _guarding = testing::also_guarding(&scratch.path().join("fake-home"));
1340 assert!(
1341 named(support.join("pitboard-test-never-made")),
1342 "while a test guards a fake home too"
1343 );
1344 }
1345
1346 #[test]
1347 #[cfg(windows)]
1348 fn a_scratch_in_claude_desktops_windows_folders_panics() {
1349 let named = |folder: PathBuf| {
1350 std::panic::catch_unwind(move || {
1351 Context::new(PathBuf::from(r"C:\nowhere")).with_scratch_claude(folder)
1352 })
1353 .is_err()
1354 };
1355 let (roaming, local) = crate::host::user::app_data_folders(true);
1356 assert!(!roaming.is_empty() && !local.is_empty());
1357 for dir in &roaming {
1358 assert!(named(dir.join("Claude").join("pitboard-test-never-made")));
1359 assert!(named(dir.join("claude-3p")), "in any case");
1360 }
1361 for dir in &local {
1362 assert!(named(dir.join("AnthropicClaude")));
1363 }
1364 let scratch = tempfile::tempdir().expect("a scratch folder");
1365 assert!(!named(scratch.path().join("elsewhere")));
1366 let fake = scratch.path().join("fake-profile");
1367 let _guarding = testing::also_guarding(&fake);
1368 let roaming = fake.join("AppData").join("Roaming");
1369 assert!(named(roaming.join("Claude").join("x")), "a fake profile's");
1370 }
1371
1372 #[test]
1374 fn a_scratch_named_through_a_folder_not_made_yet_panics() {
1375 let scratch = tempfile::tempdir().expect("a scratch folder");
1376 let home = scratch.path().join("home");
1377 let _guarding = testing::also_guarding(&home);
1378 let climbed = std::panic::catch_unwind(|| {
1379 Context::new("/nowhere".into())
1380 .with_scratch_claude(home.join("never-made/../Library/Application Support/x"))
1381 });
1382 assert!(climbed.is_err());
1383 }
1384
1385 #[test]
1387 fn a_relative_name_lies_where_the_working_directory_puts_it() {
1388 let here = std::env::current_dir().expect("a working directory");
1389 let name = Path::new("pitboard-never-made");
1390 assert!(crate::host::lies_in(name, &here));
1391 assert!(!crate::host::lies_in(name, &here.join("elsewhere")));
1392 }
1393
1394 #[test]
1396 fn a_relative_scratch_panics() {
1397 let named = std::panic::catch_unwind(|| {
1398 Context::new("/nowhere".into()).with_scratch_claude("pitboard-scratch".into())
1399 });
1400 assert!(named.is_err());
1401 }
1402
1403 #[test]
1404 #[cfg_attr(
1405 windows,
1406 ignore = "Claude Desktop is macOS only: Windows makes no link"
1407 )]
1408 fn a_scratch_whose_data_or_app_links_to_a_real_place_panics() {
1409 let scratch = tempfile::tempdir().expect("a scratch folder");
1410 let root = scratch.path();
1411 let home = root.join("home");
1412 let support = home.join("Library/Application Support/Claude");
1413 let app = home.join("Applications/Claude.app");
1414 let other = root.join("other");
1415 for made in [&support, &app, &other] {
1416 std::fs::create_dir_all(made).expect("a folder to link to");
1417 }
1418 let _guarding = testing::also_guarding(&home);
1419 let linked = |scratch: &str, name: &str, to: &Path| {
1420 let scratch = root.join(scratch);
1421 std::fs::create_dir_all(&scratch).expect("a scratch");
1422 crate::host::fs::testing::link_dir(to, &scratch.join(name)).expect("a link");
1423 std::panic::catch_unwind(|| {
1424 Context::new("/nowhere".into()).with_scratch_claude(scratch)
1425 })
1426 .is_err()
1427 };
1428 let data = linked("one", "data", &support);
1429 let claude = linked("two", "Claude.app", &app);
1430 let elsewhere = linked("three", "data", &other);
1431 let not_made = linked("four", "data", &support.join("never-made"));
1432 let not_made_relative = linked(
1433 "five",
1434 "data",
1435 Path::new("../home/Library/Application Support/Claude/never-made"),
1436 );
1437 assert!(data, "data linked into Application Support");
1438 assert!(claude, "Claude.app linked to ~/Applications/Claude.app");
1439 assert!(!elsewhere, "data linked to a folder of the test's own");
1440 assert!(not_made, "data linked to a folder not made yet there");
1441 assert!(not_made_relative, "the same, by a relative link");
1442 }
1443
1444 #[test]
1445 #[cfg_attr(
1446 windows,
1447 ignore = "Claude Desktop is macOS only: Windows has no `/Applications`"
1448 )]
1449 fn a_scratch_of_an_applications_folder_panics() {
1450 let scratch = tempfile::tempdir().expect("a scratch folder");
1451 let home = scratch.path().join("home");
1452 let _guarding = testing::also_guarding(&home);
1453 let named = |folder: PathBuf| {
1454 std::panic::catch_unwind(move || {
1455 Context::new("/nowhere".into()).with_scratch_claude(folder)
1456 })
1457 .is_err()
1458 };
1459 assert!(named("/Applications".into()));
1460 assert!(named(home.join("Applications")));
1461 assert!(!named(home.join("Applications/elsewhere")));
1462 }
1463
1464 #[test]
1466 #[cfg_attr(
1467 not(target_os = "macos"),
1468 ignore = "a firmlink to the Data volume is macOS's own"
1469 )]
1470 fn a_scratch_named_through_the_data_volume_panics() {
1471 let scratch = tempfile::tempdir().expect("a scratch folder");
1472 let root = scratch.path();
1473 let support = root.join("home/Library/Application Support/Claude");
1474 let scratch = root.join("scratch");
1475 for made in [&support, &scratch] {
1476 std::fs::create_dir_all(made).expect("a folder of the test's own");
1477 }
1478 let through = |place: &Path| {
1479 let real = std::fs::canonicalize(place).expect("a folder of the test's own");
1480 Path::new("/System/Volumes/Data").join(real.strip_prefix("/").expect("from the root"))
1481 };
1482 crate::host::fs::testing::link_dir(&through(&support), &scratch.join("data"))
1483 .expect("a link");
1484 let _guarding = testing::also_guarding(&root.join("home"));
1485 let named = |folder: PathBuf| {
1486 std::panic::catch_unwind(move || {
1487 Context::new("/nowhere".into()).with_scratch_claude(folder)
1488 })
1489 .is_err()
1490 };
1491 let linked = named(scratch);
1492 let inside = named(through(&support).join("pitboard-test"));
1493 let own = named(through(root).join("own"));
1494 let applications = named("/System/Volumes/Data/Applications".into());
1495 assert!(
1496 linked,
1497 "data linked into Application Support through the Data volume"
1498 );
1499 assert!(
1500 inside,
1501 "a scratch in Application Support named through the Data volume"
1502 );
1503 assert!(
1504 !own,
1505 "a folder of the test's own named through the Data volume"
1506 );
1507 assert!(applications, "/Applications named through the Data volume");
1508 }
1509
1510 #[test]
1515 fn an_explicit_context_reads_claude_codes_settings_the_way_the_environment_does() {
1516 let (_scratch, home, named) = full_home();
1517 let ctx = Context::new(home.clone())
1518 .with_claude_config_dir(String::new())
1519 .with_secure_storage_dir(String::new());
1520 assert_eq!(
1521 ctx.pitboard_home,
1522 crate::host::OS.default_pitboard_home(&home)
1523 );
1524 assert_eq!(
1525 ctx.claude_config_dir.as_deref(),
1526 Some(""),
1527 "empty is the empty path for the config dir"
1528 );
1529 assert_eq!(
1530 ctx.secure_storage_dir.as_deref(),
1531 Some(""),
1532 "empty is set, and pins the default slot"
1533 );
1534 assert_eq!(ctx.claude_program(), Path::new("claude"));
1535 let env: Environment = [
1536 (crate::host::OS.home_variable(), named.as_str()),
1537 ("CLAUDE_CONFIG_DIR", ""),
1538 ]
1539 .into_iter()
1540 .collect();
1541 let read = Context::for_command_line(&env);
1542 assert_eq!(read.claude_config_dir, ctx.claude_config_dir);
1543 for ctx in [ctx, read] {
1544 assert!(
1545 matches!(
1546 crate::home::check_absolute(&ctx),
1547 Err(crate::error::Error::HomeNotAbsolute {
1548 variable: "CLAUDE_CONFIG_DIR",
1549 ..
1550 })
1551 ),
1552 "refused"
1553 );
1554 }
1555 }
1556
1557 #[test]
1558 fn a_scratch_machine_whose_context_reaches_another_host_or_api_panics() {
1559 use crate::api::scripted::ScriptedApi;
1560 use crate::host::memory::MemoryHost;
1561 let home = Path::new("/home/x");
1562 let made = ScratchMachine::at(home, |ctx| ctx.with_caller("app".into()));
1563 assert_eq!(made.ctx.home(), home);
1564 let another_machine = std::panic::catch_unwind(|| {
1565 ScratchMachine::at(home, |ctx| ctx.with_memory_stores(MemoryHost::new()))
1566 });
1567 assert!(another_machine.is_err());
1568 let other_services = std::panic::catch_unwind(|| {
1569 ScratchMachine::at(home, |ctx| ctx.with_scripted_api(ScriptedApi::new()))
1570 });
1571 assert!(other_services.is_err());
1572 }
1573
1574 #[test]
1576 fn a_context_says_whether_it_reaches_only_the_machine_and_services_it_was_given() {
1577 use crate::api::scripted::ScriptedApi;
1578 use crate::host::memory::MemoryHost;
1579 let (memory, api) = (MemoryHost::new(), ScriptedApi::new());
1580 let home = PathBuf::from("/home/x");
1581 let both = Context::new(home.clone())
1582 .with_memory_stores(Arc::clone(&memory))
1583 .with_scripted_api(Arc::clone(&api));
1584 assert!(both.reaches_only(&memory, &api));
1585 assert!(
1586 !Context::new(home.clone())
1587 .with_scripted_api(Arc::clone(&api))
1588 .reaches_only(&memory, &api),
1589 "this machine"
1590 );
1591 assert!(
1592 !Context::new(home)
1593 .with_memory_stores(Arc::clone(&memory))
1594 .reaches_only(&memory, &api),
1595 "the network"
1596 );
1597 assert!(
1598 !both.reaches_only(&MemoryHost::new(), &api),
1599 "another machine"
1600 );
1601 assert!(
1602 !both.reaches_only(&memory, &ScriptedApi::new()),
1603 "other services"
1604 );
1605 }
1606
1607 #[test]
1608 fn only_a_front_end_that_names_one_changes_what_the_schedule_runs() {
1609 assert_eq!(Context::for_unit_test().schedule_program(), None);
1610 let ctx = Context::new(PathBuf::from("/Users/x"));
1611 assert_eq!(ctx.schedule_program(), None);
1612 let bundled = PathBuf::from("/Applications/Pitboard.app/Contents/Helpers/pitboard");
1613 assert_eq!(
1614 ctx.with_schedule_program(bundled.clone())
1615 .schedule_program(),
1616 Some(bundled.as_path())
1617 );
1618 }
1619
1620 #[test]
1623 fn the_command_line_reads_the_environment_it_is_given() {
1624 let (_scratch, home, named) = full_home();
1625 let env: Environment = [
1626 (crate::host::OS.home_variable(), named.as_str()),
1627 ("PITBOARD_CLAUDE", "/elsewhere/claude"),
1628 ("PITBOARD_CODEX", ""),
1629 ("CLAUDE_CODE_CUSTOM_OAUTH_URL", "https://oauth.example"),
1630 ("ANTHROPIC_API_KEY", "not-a-key"),
1631 ("ANTHROPIC_AUTH_TOKEN", ""),
1632 ("PATH", "/opt/tools/bin:/usr/bin"),
1633 ]
1634 .into_iter()
1635 .collect();
1636 let ctx = Context::for_command_line(&env);
1637 assert_eq!(ctx.claude_program(), Path::new("/elsewhere/claude"));
1638 assert_eq!(
1639 ctx.codex_program(),
1640 Path::new("codex"),
1641 "empty names nothing"
1642 );
1643 assert!(ctx.custom_oauth());
1644 assert_eq!(
1645 ctx.overriding_auth(),
1646 ["ANTHROPIC_API_KEY"],
1647 "empty is unset"
1648 );
1649 assert_eq!(ctx.search_path(), "/opt/tools/bin:/usr/bin");
1650 assert_eq!(
1651 ctx.pitboard_home,
1652 crate::host::OS.default_pitboard_home(&home)
1653 );
1654 assert_eq!(ctx.caller, "cli");
1655 let no_path: Environment = [(crate::host::OS.home_variable(), named.as_str())]
1656 .into_iter()
1657 .collect();
1658 assert_eq!(
1659 Context::for_command_line(&no_path).search_path(),
1660 "",
1661 "no PATH is nowhere, not this process's"
1662 );
1663 }
1664
1665 #[test]
1668 fn a_windows_environment_has_one_value_per_name_in_any_case_and_the_first_wins() {
1669 let search_path = |os: Os, pairs: &[(&str, &str)]| {
1670 let home = [("HOME", "/home/x"), ("USERPROFILE", "/home/x")];
1671 let env = Environment::on(os, home.iter().chain(pairs).copied());
1672 Context::read(&env, "cli").search_path()
1673 };
1674 let windows = |pairs: &[(&str, &str)]| search_path(Os::Windows, pairs);
1675 assert_eq!(
1676 windows(&[("Path", "C:\\a")]),
1677 "C:\\a",
1678 "as a program gets it"
1679 );
1680 assert_eq!(windows(&[("PATH", "C:\\b")]), "C:\\b");
1681 assert_eq!(windows(&[("Path", "C:\\a"), ("PATH", "C:\\b")]), "C:\\a");
1682 assert_eq!(windows(&[("PATH", "C:\\b"), ("Path", "C:\\a")]), "C:\\b");
1683 for os in [Os::MacOs, Os::Linux] {
1684 assert_eq!(search_path(os, &[("Path", "/a")]), "", "{os:?}");
1685 assert_eq!(search_path(os, &[("Path", "/a"), ("PATH", "/b")]), "/b");
1686 }
1687 let both = Environment::on(Os::Windows, [("Path", "C:\\a"), ("PATH", "C:\\b")]);
1688 let given: Vec<_> = both.iter().collect();
1689 assert_eq!(
1690 given,
1691 [(OsStr::new("Path"), OsStr::new("C:\\a"))],
1692 "a child gets one"
1693 );
1694 assert_eq!(both.text("PATH"), Some("C:\\a"));
1695 }
1696
1697 #[test]
1699 fn the_person_is_named_by_the_systems_own_variable() {
1700 let user = |os: Os| {
1701 let pairs = [
1702 ("HOME", "/home/x"),
1703 ("USERPROFILE", "/home/x"),
1704 ("USER", "posix"),
1705 ("username", "windows"),
1706 ];
1707 Context::read(&Environment::on(os, pairs), "cli").user
1708 };
1709 assert_eq!(user(Os::Windows).as_deref(), Some("windows"));
1710 assert_eq!(user(Os::MacOs).as_deref(), Some("posix"));
1711 assert_eq!(user(Os::Linux).as_deref(), Some("posix"));
1712 }
1713
1714 #[test]
1716 fn each_tool_finds_its_home_in_userprofile_on_windows_whatever_home_says() {
1717 let scratch = tempfile::tempdir().expect("a scratch folder");
1718 let profile = scratch.path().to_path_buf();
1719 let named = profile.to_string_lossy().into_owned();
1720 let pairs = [("HOME", "/c/Users/x"), ("USERPROFILE", named.as_str())];
1721 let ctx = Context::read(&Environment::on(Os::Windows, pairs), "cli");
1722 assert_eq!(ctx.home, profile);
1723 assert_eq!(
1724 crate::provider::claude::paths::config_dir(&ctx),
1725 profile.join(".claude")
1726 );
1727 assert_eq!(
1728 crate::provider::claude::paths::config_file(&ctx),
1729 profile.join(".claude.json")
1730 );
1731 assert_eq!(
1732 crate::provider::codex::paths::home(&ctx),
1733 profile.join(".codex")
1734 );
1735 assert_eq!(
1736 ctx.pitboard_home,
1737 profile.join("AppData").join("Local").join("Pitboard")
1738 );
1739 let posix = Context::read(&Environment::on(Os::Linux, pairs), "cli");
1740 assert_eq!(posix.home, PathBuf::from("/c/Users/x"));
1741 }
1742
1743 #[test]
1745 fn a_relative_xdg_folder_is_taken_for_unset() {
1746 let (_scratch, home, named) = full_home();
1747 let elsewhere = home.with_file_name("elsewhere");
1748 let full = elsewhere.to_string_lossy().into_owned();
1749 let read = |os: Os, pairs: &[(&str, &str)]| {
1750 let homes = [("HOME", named.as_str()), ("USERPROFILE", named.as_str())];
1751 Context::read(
1752 &Environment::on(os, homes.iter().chain(pairs).copied()),
1753 "cli",
1754 )
1755 };
1756 let given = read(
1757 Os::Linux,
1758 &[
1759 ("XDG_CONFIG_HOME", &full),
1760 ("XDG_DATA_HOME", "relative/data"),
1761 ("XDG_CACHE_HOME", ""),
1762 ],
1763 );
1764 assert_eq!(given.config_home(), Some(elsewhere.as_path()));
1765 let data = home.join(".local").join("share");
1766 assert_eq!(given.data_home(), Some(data.as_path()), "relative");
1767 let cache = home.join(".cache");
1768 assert_eq!(given.cache_home(), Some(cache.as_path()), "empty");
1769 let unset = read(Os::MacOs, &[]);
1770 let config = home.join(".config");
1771 assert_eq!(
1772 (unset.config_home(), unset.data_home(), unset.cache_home()),
1773 (
1774 Some(config.as_path()),
1775 Some(data.as_path()),
1776 Some(cache.as_path())
1777 )
1778 );
1779 let windows = read(Os::Windows, &[("XDG_DATA_HOME", &full)]);
1780 assert_eq!(
1781 (
1782 windows.config_home(),
1783 windows.data_home(),
1784 windows.cache_home()
1785 ),
1786 (None, None, None),
1787 "Windows has none"
1788 );
1789 }
1790
1791 #[test]
1793 fn the_session_bus_is_found_as_sd_bus_finds_it() {
1794 let (_scratch, home, named) = full_home();
1795 let runtime = home.with_file_name("runtime");
1796 let full = runtime.to_string_lossy().into_owned();
1797 let read = |os: Os, pairs: &[(&str, &str)]| {
1798 let homes = [("HOME", named.as_str()), ("USERPROFILE", named.as_str())];
1799 Context::read(
1800 &Environment::on(os, homes.iter().chain(pairs).copied()),
1801 "cli",
1802 )
1803 };
1804 let address = "unix:path=/tmp/a%20bus,guid=0123456789abcdef0123456789abcdef";
1805 let both = [
1806 ("XDG_RUNTIME_DIR", full.as_str()),
1807 ("DBUS_SESSION_BUS_ADDRESS", address),
1808 ];
1809 let given = read(Os::Linux, &both);
1810 assert_eq!(
1811 given.session_bus(),
1812 Some(SessionBus::Address(address.into()))
1813 );
1814 let in_the_runtime_folder = read(
1815 Os::Linux,
1816 &[("XDG_RUNTIME_DIR", &full), ("DBUS_SESSION_BUS_ADDRESS", "")],
1817 );
1818 assert_eq!(
1819 in_the_runtime_folder.session_bus(),
1820 Some(SessionBus::Socket(runtime.join("bus")))
1821 );
1822 let relative = read(Os::Linux, &[("XDG_RUNTIME_DIR", "relative/runtime")]);
1823 assert_eq!(relative.session_bus(), None);
1824 let mac = read(Os::MacOs, &both);
1825 assert_eq!(mac.session_bus(), None);
1826 }
1827
1828 #[test]
1831 fn the_desktop_session_has_a_display_not_forwarded_over_ssh() {
1832 let (_scratch, _home, named) = full_home();
1833 let read = |os: Os, pairs: &[(&str, &str)]| {
1834 let home = [("HOME", named.as_str())];
1835 Context::read(
1836 &Environment::on(os, home.iter().chain(pairs).copied()),
1837 "cli",
1838 )
1839 .in_the_desktop_session()
1840 };
1841 assert!(read(Os::Linux, &[("WAYLAND_DISPLAY", "wayland-0")]));
1842 assert!(read(Os::Linux, &[("DISPLAY", ":0")]));
1843 assert!(!read(Os::Linux, &[]));
1844 assert!(!read(
1845 Os::Linux,
1846 &[("WAYLAND_DISPLAY", ""), ("DISPLAY", "")]
1847 ));
1848 assert!(!read(
1849 Os::Linux,
1850 &[
1851 ("DISPLAY", "localhost:10.0"),
1852 ("SSH_CONNECTION", "10.0.0.2 50022 10.0.0.1 22")
1853 ]
1854 ));
1855 assert!(!read(Os::MacOs, &[("DISPLAY", ":0")]));
1856 assert!(!Context::for_unit_test().in_the_desktop_session());
1857 }
1858
1859 fn full_home() -> (tempfile::TempDir, PathBuf, String) {
1861 let scratch = tempfile::tempdir().expect("a scratch folder");
1862 let home = scratch.path().join("home");
1863 let named = home.to_string_lossy().into_owned();
1864 (scratch, home, named)
1865 }
1866
1867 #[test]
1870 #[cfg(debug_assertions)]
1871 #[should_panic(expected = "PITBOARD_SOMETHING_NEW is read but not listed")]
1872 fn a_variable_read_without_being_listed_is_caught() {
1873 let _ = Environment::default().path("PITBOARD_SOMETHING_NEW");
1874 }
1875
1876 #[test]
1880 fn without_home_the_home_is_the_accounts_own() {
1881 let _real = crate::host::user::testing::reaching_the_real_home();
1882 let own = crate::host::user::home().expect("this account has a home");
1883 let ctx = Context::for_command_line(&Environment::default());
1884 assert_eq!(ctx.home, own);
1885 assert_eq!(
1886 ctx.pitboard_home,
1887 crate::host::OS.default_pitboard_home(&own)
1888 );
1889 let empty: Environment = [(crate::host::OS.home_variable(), "")]
1890 .into_iter()
1891 .collect();
1892 assert_eq!(
1893 Context::for_command_line(&empty).home,
1894 PathBuf::new(),
1895 "set, even empty, it is what the person said"
1896 );
1897 }
1898
1899 #[test]
1904 fn a_unit_tests_homes_are_a_folder_of_its_own_that_nothing_makes() {
1905 let ctx = Context::for_unit_test();
1906 let sentinel = ctx.home.clone();
1907 assert!(
1908 sentinel.starts_with(std::env::temp_dir()),
1909 "{}",
1910 sentinel.display()
1911 );
1912 assert!(!sentinel.exists(), "{}", sentinel.display());
1913 assert_eq!(ctx.pitboard_home, sentinel);
1914 assert_eq!(
1915 crate::provider::claude::paths::config_dir(&ctx),
1916 sentinel,
1917 "Claude Code's"
1918 );
1919 assert_eq!(
1920 crate::provider::codex::paths::home(&ctx),
1921 sentinel,
1922 "Codex's"
1923 );
1924 assert_eq!(Context::for_unit_test().home, sentinel, "the same test's");
1925 let another = std::thread::Builder::new()
1926 .name("another::test".into())
1927 .spawn(|| Context::for_unit_test().home)
1928 .expect("a thread")
1929 .join()
1930 .expect("its context");
1931 assert_ne!(another, sentinel, "another test's");
1932 assert!(another.ends_with("another--test"), "{}", another.display());
1933 }
1934
1935 #[test]
1939 fn the_homes_an_app_asks_for_are_the_contexts() {
1940 let _real = crate::host::user::testing::reaching_the_real_home();
1941 let cases: [&[(&str, &str)]; 5] = [
1942 &[],
1943 &[("HOME", "/Users/x")],
1944 &[("HOME", "/Users/x/")],
1945 &[
1946 ("HOME", "/Users/x"),
1947 ("PITBOARD_HOME", "/elsewhere/./pitboard/"),
1948 ],
1949 &[("PITBOARD_HOME", "")],
1950 ];
1951 for pairs in cases {
1952 let env: Environment = pairs.iter().copied().collect();
1953 let ctx = Context::for_command_line(&env);
1954 assert_eq!(env.home(), ctx.home, "{pairs:?}");
1955 assert_eq!(env.pitboard_home(), ctx.pitboard_home, "{pairs:?}");
1956 }
1957 let given: Environment = [("PITBOARD_HOME", "/elsewhere/./pitboard/")]
1958 .into_iter()
1959 .collect();
1960 assert_eq!(
1961 given.pitboard_home().as_os_str(),
1962 "/elsewhere/./pitboard/",
1963 "as the environment gives it"
1964 );
1965 }
1966}