返回 CodeWhale
scope.rs
1 use std::path::Path;
2
3 use std::path::PathBuf;
4
5 use codewhale_config::ProviderKind;
6
7 use codewhale_runtime::config::Config;
8
9 use codewhale_engine::provider_readiness::ResolvedProviderReadiness;
10
11 use codewhale_engine::provider_readiness::resolve_for_model;
12
13 struct HomeGuard {
14 prev_home: Option<std::ffi::OsString>,
15 prev_config_path: Option<std::ffi::OsString>,
16 }
17
18 impl Drop for HomeGuard {
19 fn drop(&mut self) {
20 // SAFETY: serialised by lock_test_env held by the caller.
21 unsafe {
22 match &self.prev_home {
23 Some(v) => std::env::set_var("CODEWHALE_HOME", v),
24 None => std::env::remove_var("CODEWHALE_HOME"),
25 }
26 match &self.prev_config_path {
27 Some(v) => std::env::set_var("CODEWHALE_CONFIG_PATH", v),
28 None => std::env::remove_var("CODEWHALE_CONFIG_PATH"),
29 }
30 }
31 }
32 }
33
34 /// Sealed user-global home with a saved DeepSeek API key, created once per
35 /// process. Tests must hold `lock_test_env` before touching it.
36 fn sealed_home() -> &'static Path {
37 static HOME: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
38 HOME.get_or_init(|| {
39 let dir = crate::test_support::test_scratch_dir("codewhale-config-stay-home");
40 std::fs::create_dir_all(&dir).expect("temp home");
41 // Seed the user-global config: DeepSeek is the authorized provider.
42 // The config lives at $CODEWHALE_HOME/config.toml (the primary path
43 // when CODEWHALE_HOME is explicit).
44 std::fs::write(
45 dir.join("config.toml"),
46 r#"provider = "deepseek"
47 [providers.deepseek]
48 api_key = "sk-test-scope-deepseek"
49 "#,
50 )
51 .expect("write config");
52 dir
53 })
54 }
55
56 /// Point `CODEWHALE_HOME` at the sealed home (optionally also pinning
57 /// `CODEWHALE_CONFIG_PATH`). Caller must hold `lock_test_env`.
58 fn sealed_env(config_path: Option<&Path>) -> HomeGuard {
59 let prev_home = std::env::var_os("CODEWHALE_HOME");
60 let prev_config_path = std::env::var_os("CODEWHALE_CONFIG_PATH");
61 // SAFETY: serialised by lock_test_env held by the caller.
62 unsafe {
63 std::env::set_var("CODEWHALE_HOME", sealed_home());
64 match config_path {
65 Some(path) => std::env::set_var("CODEWHALE_CONFIG_PATH", path),
66 None => std::env::remove_var("CODEWHALE_CONFIG_PATH"),
67 }
68 }
69 HomeGuard {
70 prev_home,
71 prev_config_path,
72 }
73 }
74
75 fn deepseek_readiness(config: &Config) -> ResolvedProviderReadiness {
76 resolve_for_model(
77 config,
78 &(config).test_identity_for_kind(ProviderKind::Deepseek),
79 "deepseek-v4-pro",
80 &codewhale_engine::provider_readiness::ProviderReadinessSnapshot::default(),
81 )
82 }
83
84 fn workspace_with_config(dir: &Path, provider: &str) -> PathBuf {
85 let ws = dir.join(provider);
86 std::fs::create_dir_all(ws.join(".codewhale")).expect("workspace dir");
87 std::fs::write(
88 ws.join(".codewhale").join("config.toml"),
89 format!(
90 r#"provider = "{provider}"
91
92 [providers.{provider}]
93 # deliberately no api_key — this workspace selects a route it never
94 # authorized anywhere.
95 "#
96 ),
97 )
98 .expect("write workspace config");
99 ws
100 }
101
102 #[test]
103 fn readiness_is_identical_across_unrelated_workspaces() {
104 let _lock = crate::test_support::lock_test_env();
105 let _home = sealed_env(None);
106
107 let base = tempfile::TempDir::new().expect("temp base");
108 let ws_a = base.path().join("project-a");
109 let ws_b = base.path().join("project-b");
110 std::fs::create_dir_all(&ws_a).expect("ws a");
111 std::fs::create_dir_all(&ws_b).expect("ws b");
112
113 // Same user-global home, two unrelated folders, no workspace overrides.
114 let config_a = codewhale_plugins::providers::load_config(None, None).expect("load from A");
115 let config_b = codewhale_plugins::providers::load_config(None, None).expect("load from B");
116
117 let readiness_a = deepseek_readiness(&config_a);
118 let readiness_b = deepseek_readiness(&config_b);
119 assert_eq!(
120 readiness_a.label(),
121 readiness_b.label(),
122 "readiness must not depend on the launch folder: {} vs {}",
123 readiness_a.label(),
124 readiness_b.label()
125 );
126 assert!(
127 readiness_a.can_attempt(),
128 "the user-global key must make DeepSeek attemptable from A: {}",
129 readiness_a.label()
130 );
131 assert!(
132 readiness_b.can_attempt(),
133 "the user-global key must make DeepSeek attemptable from B: {}",
134 readiness_b.label()
135 );
136 }
137
138 #[test]
139 fn explicit_workspace_config_selects_its_route_without_locking_user_global() {
140 let _lock = crate::test_support::lock_test_env();
141 let base = tempfile::TempDir::new().expect("temp base");
142 // Workspace A deliberately selects zai with no credential anywhere.
143 let ws_a = workspace_with_config(base.path(), "zai");
144 // The explicit config path is the workspace file — this is the
145 // "launched from that folder with --config" shape.
146 let config_path = ws_a.join(".codewhale").join("config.toml");
147 let _home = sealed_env(Some(&config_path));
148
149 let config = codewhale_plugins::providers::load_config(Some(config_path.clone()), None)
150 .expect("load workspace config");
151 // The workspace selection IS honored for the session route.
152 assert_eq!(
153 config.active_provider_identity().unwrap().provider,
154 ProviderKind::Zai,
155 "the explicit workspace config selects zai"
156 );
157
158 // The user-global DeepSeek authorization did not disappear: it resolves
159 // from the user-global credential sources regardless of which config file
160 // was loaded.
161 let deepseek = deepseek_readiness(&config);
162 assert!(
163 deepseek.can_attempt(),
164 "authorization established once must stay visible: {}",
165 deepseek.label()
166 );
167
168 // The uncredentialed zai route is unavailable with a precise reason —
169 // never a lie, never a silent substitution.
170 let zai = resolve_for_model(
171 &config,
172 &(config).test_identity_for_kind(ProviderKind::Zai),
173 "GLM-5.2",
174 &codewhale_engine::provider_readiness::ProviderReadinessSnapshot::default(),
175 );
176 assert!(
177 !zai.can_attempt(),
178 "zai has no credential anywhere: {}",
179 zai.label()
180 );
181 let reason = zai.blocked_reason().map(|r| r.into_owned());
182 assert!(
183 reason.as_ref().is_some_and(|r| !r.trim().is_empty()),
184 "unavailable must carry a precise reason: {reason:?}"
185 );
186 }
187
188 fn write_nested_zai_config(base: &std::path::Path) -> std::path::PathBuf {
189 let nested = base.join("parent-repo").join("nested-repo");
190 std::fs::create_dir_all(nested.join(".codewhale")).expect("nested dir");
191 std::fs::write(
192 nested.join(".codewhale").join("config.toml"),
193 r#"provider = "zai"
194
195 [providers.zai]
196 "#,
197 )
198 .expect("nested config");
199 nested
200 }
201
202 fn assert_user_global_survives_workspace(label: &str, config_path: std::path::PathBuf) {
203 let _home = sealed_env(Some(&config_path));
204 let config = codewhale_plugins::providers::load_config(Some(config_path.clone()), None)
205 .unwrap_or_else(|err| panic!("load from {label}: {err}"));
206 let deepseek = deepseek_readiness(&config);
207 assert!(
208 deepseek.can_attempt(),
209 "{label}: user-global authorization must survive: {}",
210 deepseek.label()
211 );
212 }
213
214 #[test]
215 fn nested_repo_does_not_change_readiness() {
216 let _lock = crate::test_support::lock_test_env();
217 let base = tempfile::TempDir::new().expect("temp base");
218 let nested = write_nested_zai_config(base.path());
219 assert_user_global_survives_workspace("nested", nested.join(".codewhale/config.toml"));
220 }
221
222 #[cfg(unix)]
223 #[test]
224 fn symlinked_worktree_does_not_change_readiness() {
225 let _lock = crate::test_support::lock_test_env();
226 let base = tempfile::TempDir::new().expect("temp base");
227 let nested = write_nested_zai_config(base.path());
228 let symlinked = base.path().join("symlink-worktree");
229 std::os::unix::fs::symlink(&nested, &symlinked).expect("symlink");
230 assert_user_global_survives_workspace("symlinked", symlinked.join(".codewhale/config.toml"));
231 }
232
233 #[test]
234 fn unavailable_truly_means_unavailable_with_a_reason() {
235 let _lock = crate::test_support::lock_test_env();
236 let _home = sealed_env(None);
237
238 let config = codewhale_plugins::providers::load_config(None, None).expect("load config");
239 // Moonshot has no key anywhere in the sealed fixtures.
240 let moonshot = resolve_for_model(
241 &config,
242 &(config).test_identity_for_kind(ProviderKind::Moonshot),
243 "kimi-k2.6",
244 &codewhale_engine::provider_readiness::ProviderReadinessSnapshot::default(),
245 );
246 assert!(!moonshot.can_attempt());
247 let reason = moonshot.blocked_reason().map(|r| r.into_owned());
248 assert!(
249 reason.as_ref().is_some_and(|r| !r.trim().is_empty()),
250 "unavailable must carry a precise reason: {reason:?}"
251 );
252 }
253
254 #[test]
255 fn repeated_readers_never_rewrite_configuration() {
256 let _lock = crate::test_support::lock_test_env();
257 let _home = sealed_env(None);
258
259 let config_path = sealed_home().join("config.toml");
260 let before = std::fs::read(&config_path).expect("read config before");
261
262 // Resolve twice from the same sealed fixtures — a reader must never
263 // write anything, so a later process can never revert a newer selection
264 // by merely loading it. (Thread spawns are deliberately not used: they
265 // would contend on the process-wide test env lock; the property under
266 // test is that loading is side-effect-free, which a second load proves.)
267 for _ in 0..2 {
268 let config = codewhale_plugins::providers::load_config(Some(config_path.clone()), None)
269 .expect("load");
270 let readiness = deepseek_readiness(&config);
271 assert!(readiness.can_attempt());
272 }
273
274 let after = std::fs::read(&config_path).expect("read config after");
275 assert_eq!(before, after, "readers must never rewrite configuration");
276 }
277
278 /// The scope contract visible to the UI: a workspace selection changes only
279 /// that workspace's selected configuration. Proven at the store level so the
280 /// Fleet selection files behave the same way as the config path above.
281 #[test]
282 fn workspace_fleet_selection_affects_only_that_workspace() {
283 use codewhale_engine::fleet::store::{
284 FleetFile, FleetScope, save_fleet, selected_fleet, set_selected,
285 };
286 let _lock = crate::test_support::lock_test_env();
287 // A FRESH personal home per test: the shared sealed home would pick up
288 // the parallel personal-selection test's writes.
289 let home = tempfile::TempDir::new().expect("temp home");
290 std::fs::create_dir_all(home.path().join("fleets")).expect("fleets dir");
291 let prev = std::env::var_os("CODEWHALE_HOME");
292 // SAFETY: serialised by lock_test_env.
293 unsafe { std::env::set_var("CODEWHALE_HOME", home.path()) };
294
295 let base = tempfile::TempDir::new().expect("temp base");
296 let ws_a = base.path().join("ws-a");
297 let ws_b = base.path().join("ws-b");
298 std::fs::create_dir_all(&ws_a).expect("ws a");
299 std::fs::create_dir_all(&ws_b).expect("ws b");
300
301 let fleet = FleetFile::new("Team A".to_string(), None).expect("fleet");
302 save_fleet(&fleet, FleetScope::Personal, &ws_a).expect("save personal");
303
304 // Workspace A selects the fleet for this folder only — the selection may
305 // point at the personal Fleet, never silently shadowing or copying it.
306 set_selected("Team A", FleetScope::Workspace, &ws_a).expect("select in A");
307
308 // B is untouched: no selection there.
309 assert!(
310 selected_fleet(&ws_a).is_some(),
311 "A has its folder selection"
312 );
313 assert!(selected_fleet(&ws_b).is_none(), "B must be unaffected");
314
315 // A's selection resolves to the personal Fleet file (no copy was made),
316 // labeled by the scope it actually lives in.
317 let sel = selected_fleet(&ws_a).expect("selected in A");
318 assert_eq!(sel.scope, FleetScope::Personal);
319 assert!(
320 !ws_a.join(".codewhale/fleets/team-a.toml").exists(),
321 "a workspace selection must not copy the fleet file"
322 );
323 // SAFETY: serialised by lock_test_env.
324 unsafe {
325 match prev {
326 Some(v) => std::env::set_var("CODEWHALE_HOME", v),
327 None => std::env::remove_var("CODEWHALE_HOME"),
328 }
329 }
330 }
331
332 /// A saved personal Fleet persists across a "restart": a fresh load from the
333 /// same sealed home still resolves the selection.
334 #[test]
335 fn personal_fleet_selection_persists_across_restart() {
336 use codewhale_engine::fleet::store::{
337 FleetFile, FleetScope, save_fleet, selected_fleet, set_selected,
338 };
339 let _lock = crate::test_support::lock_test_env();
340 // Fresh personal home per test (see the workspace-selection test).
341 let home = tempfile::TempDir::new().expect("temp home");
342 std::fs::create_dir_all(home.path().join("fleets")).expect("fleets dir");
343 let prev = std::env::var_os("CODEWHALE_HOME");
344 // SAFETY: serialised by lock_test_env.
345 unsafe { std::env::set_var("CODEWHALE_HOME", home.path()) };
346
347 let ws = tempfile::TempDir::new().expect("temp ws");
348 let fleet = FleetFile::new("My Default".to_string(), None).expect("fleet");
349 save_fleet(&fleet, FleetScope::Personal, ws.path()).expect("save personal");
350 set_selected("My Default", FleetScope::Personal, ws.path()).expect("select");
351
352 // "Restart": a fresh resolution from the same home.
353 let sel = selected_fleet(ws.path()).expect("selection after restart");
354 assert_eq!(sel.name, "My Default");
355 assert_eq!(sel.scope, FleetScope::Personal);
356 // SAFETY: serialised by lock_test_env.
357 unsafe {
358 match prev {
359 Some(v) => std::env::set_var("CODEWHALE_HOME", v),
360 None => std::env::remove_var("CODEWHALE_HOME"),
361 }
362 }
363 }
364
364 lines RUST