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