| 1 | //! Desktop Phase 0 acceptance for the daemon socket: spawn the daemon, connect |
| 2 | //! over the unix socket, complete the attach/claim handshake, round-trip |
| 3 | //! requests through the same JSON-RPC dispatcher the stdio transport uses, |
| 4 | //! and shut down cleanly (socket file removed, listener gone). |
| 5 | |
| 6 | #![cfg(unix)] |
| 7 | |
| 8 | use std::os::unix::fs::PermissionsExt; |
| 9 | use std::path::{Path, PathBuf}; |
| 10 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 11 | use std::time::{Duration, SystemTime, UNIX_EPOCH}; |
| 12 | |
| 13 | use codewhale_app_server::daemon_socket::{ |
| 14 | DaemonSocketError, DaemonSocketOptions, bind_daemon_socket, |
| 15 | }; |
| 16 | use futures_util::{SinkExt as _, StreamExt as _}; |
| 17 | use serde_json::{Value, json}; |
| 18 | use tokio::net::UnixStream; |
| 19 | use tokio::task::JoinHandle; |
| 20 | use tokio_tungstenite::{WebSocketStream, tungstenite::Message}; |
| 21 | |
| 22 | static NONCE: AtomicU64 = AtomicU64::new(0); |
| 23 | |
| 24 | /// A short, unique socket path: unix socket paths are capped near 100 bytes, |
| 25 | /// so `std::env::temp_dir()` (deep under `/var/folders` on macOS) is too long. |
| 26 | /// `/tmp` is the same choice the hooks crate's socket test makes. |
| 27 | fn short_socket_root(label: &str) -> PathBuf { |
| 28 | let millis = SystemTime::now() |
| 29 | .duration_since(UNIX_EPOCH) |
| 30 | .expect("clock") |
| 31 | .as_millis() |
| 32 | % 1_000_000; |
| 33 | let nonce = NONCE.fetch_add(1, Ordering::Relaxed); |
| 34 | let pid = std::process::id(); |
| 35 | let root = PathBuf::from("/tmp") |
| 36 | .canonicalize() |
| 37 | .expect("selected temporary parent") |
| 38 | .join(format!("cw-ds-{label}-{pid}-{nonce}-{millis}")); |
| 39 | assert!( |
| 40 | root.as_os_str().len() < 60, |
| 41 | "socket root too long for a unix socket test: {}", |
| 42 | root.display() |
| 43 | ); |
| 44 | root |
| 45 | } |
| 46 | |
| 47 | struct Harness { |
| 48 | root: PathBuf, |
| 49 | socket_path: PathBuf, |
| 50 | _config_dir: tempfile::TempDir, |
| 51 | } |
| 52 | |
| 53 | impl Harness { |
| 54 | fn new(label: &str) -> Self { |
| 55 | let root = short_socket_root(label); |
| 56 | let config_dir = tempfile::tempdir().expect("tempdir"); |
| 57 | std::fs::write(config_dir.path().join("config.toml"), "").expect("config"); |
| 58 | Self { |
| 59 | socket_path: root.join("run").join("daemon.sock"), |
| 60 | root, |
| 61 | _config_dir: config_dir, |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | fn options(&self) -> DaemonSocketOptions { |
| 66 | DaemonSocketOptions { |
| 67 | socket_path: Some(self.socket_path.clone()), |
| 68 | config_path: Some(self._config_dir.path().join("config.toml")), |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | /// Bind and serve on a background task; returns the serve join handle. |
| 73 | async fn spawn_daemon(&self) -> JoinHandle<Result<(), DaemonSocketError>> { |
| 74 | let daemon = bind_daemon_socket(self.options()) |
| 75 | .await |
| 76 | .expect("bind daemon socket"); |
| 77 | assert_eq!(daemon.local_path(), self.socket_path.as_path()); |
| 78 | tokio::spawn(daemon.serve()) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | impl Drop for Harness { |
| 83 | fn drop(&mut self) { |
| 84 | let _ = std::fs::remove_dir_all(&self.root); |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | struct OwnedBootstrapChild(std::process::Child); |
| 89 | impl Drop for OwnedBootstrapChild { |
| 90 | fn drop(&mut self) { |
| 91 | if self.0.try_wait().ok().flatten().is_none() { |
| 92 | let _ = self.0.kill(); |
| 93 | } |
| 94 | let _ = self.0.wait(); |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | /// Transport-only publication fixture; actual store-lease proof lives in TUI. |
| 99 | struct BootstrapPublicationFixture { |
| 100 | harness: Harness, |
| 101 | parent: codewhale_config::private_directory::PrivateDirectory, |
| 102 | owner: codewhale_protocol::RuntimeOwnerReceipt, |
| 103 | bytes: Vec<u8>, |
| 104 | } |
| 105 | impl BootstrapPublicationFixture { |
| 106 | async fn new(label: &str, dead: bool, reused: bool) -> Self { |
| 107 | use codewhale_config::private_directory::PrivateDirectory; |
| 108 | let harness = Harness::new(label); |
| 109 | let parent = PrivateDirectory::admit(harness.socket_path.parent().unwrap()).unwrap(); |
| 110 | let socket = std::os::unix::net::UnixListener::bind(&harness.socket_path).unwrap(); |
| 111 | let identity = parent.socket_identity("daemon.sock").unwrap().unwrap(); |
| 112 | parent.protect_socket("daemon.sock", identity).unwrap(); |
| 113 | drop(socket); |
| 114 | let (pid, mut process_start) = if dead { |
| 115 | let mut child = OwnedBootstrapChild( |
| 116 | std::process::Command::new("/bin/sleep") |
| 117 | .arg("60") |
| 118 | .stdin(std::process::Stdio::null()) |
| 119 | .stdout(std::process::Stdio::null()) |
| 120 | .stderr(std::process::Stdio::null()) |
| 121 | .spawn() |
| 122 | .unwrap(), |
| 123 | ); |
| 124 | let pid = child.0.id(); |
| 125 | let start = codewhale_app_server::daemon_socket::capture_process_start(pid) |
| 126 | .await |
| 127 | .unwrap(); |
| 128 | child.0.kill().unwrap(); |
| 129 | child.0.wait().unwrap(); |
| 130 | (pid, start) |
| 131 | } else { |
| 132 | ( |
| 133 | std::process::id(), |
| 134 | codewhale_app_server::daemon_socket::capture_process_start(std::process::id()) |
| 135 | .await |
| 136 | .unwrap(), |
| 137 | ) |
| 138 | }; |
| 139 | if reused { |
| 140 | process_start.push_str("-different-generation"); |
| 141 | } |
| 142 | std::fs::create_dir_all(harness.root.join("runtime")).unwrap(); |
| 143 | let owner = codewhale_protocol::RuntimeOwnerReceipt { |
| 144 | version: 1, |
| 145 | data_dir: harness.root.join("runtime"), |
| 146 | execution_scope: "bootstrap-transport-store".into(), |
| 147 | lease_generation: "bootstrap-dead-generation".into(), |
| 148 | pid, |
| 149 | process_start, |
| 150 | principal: PrivateDirectory::current_user_id().to_string(), |
| 151 | socket_path: harness.socket_path.clone(), |
| 152 | config_path: harness.options().config_path, |
| 153 | }; |
| 154 | let bytes = serde_json::to_vec(&owner).unwrap(); |
| 155 | parent |
| 156 | .write_owned_file("daemon.sock.owner.json", &bytes, false) |
| 157 | .unwrap(); |
| 158 | Self { |
| 159 | harness, |
| 160 | parent, |
| 161 | owner, |
| 162 | bytes, |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | async fn capture( |
| 167 | &self, |
| 168 | ) -> std::sync::Arc<codewhale_app_server::daemon_client::UnavailablePublication> { |
| 169 | match codewhale_app_server::daemon_client::probe_owner_for_host_startup( |
| 170 | self.owner.config_path.clone(), |
| 171 | Some(self.owner.socket_path.clone()), |
| 172 | &self.owner.data_dir, |
| 173 | ) |
| 174 | .await |
| 175 | .unwrap() |
| 176 | { |
| 177 | codewhale_app_server::daemon_client::HostOwnerProbe::Unavailable(publication) => { |
| 178 | publication |
| 179 | } |
| 180 | _ => panic!("refused private endpoint must be captured before bootstrap"), |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | async fn bind_replacement( |
| 185 | &self, |
| 186 | recovery: Option< |
| 187 | std::sync::Arc<codewhale_app_server::daemon_client::UnavailablePublication>, |
| 188 | >, |
| 189 | ) -> anyhow::Result<codewhale_app_server::daemon_socket::DaemonSocket> { |
| 190 | let mut owner = self.owner.clone(); |
| 191 | owner.pid = std::process::id(); |
| 192 | owner.process_start = |
| 193 | codewhale_app_server::daemon_socket::capture_process_start(owner.pid).await?; |
| 194 | owner.lease_generation = "bootstrap-new-generation".into(); |
| 195 | let (daemon, _) = codewhale_app_server::bind_runtime_frontends( |
| 196 | owner.config_path.clone(), |
| 197 | None, |
| 198 | owner, |
| 199 | codewhale_app_server::RuntimeOwnerRouting { |
| 200 | endpoint: "127.0.0.1:1".parse().unwrap(), |
| 201 | workspace: None, |
| 202 | workers: None, |
| 203 | mobile: false, |
| 204 | web: false, |
| 205 | acp: false, |
| 206 | acp_only: false, |
| 207 | }, |
| 208 | None, |
| 209 | recovery, |
| 210 | ) |
| 211 | .await?; |
| 212 | Ok(daemon.expect("a private endpoint directory is available on this host")) |
| 213 | } |
| 214 | |
| 215 | fn assert_publication(&self, bytes: &[u8]) { |
| 216 | assert_eq!( |
| 217 | self.parent |
| 218 | .read_private_receipt("daemon.sock.owner.json", 16384) |
| 219 | .unwrap() |
| 220 | .unwrap() |
| 221 | .0, |
| 222 | bytes |
| 223 | ); |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | #[tokio::test] |
| 228 | async fn owner_bootstrap_unavailable_is_host_only_and_read_only() { |
| 229 | let fixture = BootstrapPublicationFixture::new("boot-read", true, false).await; |
| 230 | let identity = fixture.parent.socket_identity("daemon.sock").unwrap(); |
| 231 | let captured = fixture.capture().await; |
| 232 | assert_eq!(captured.receipt(), &fixture.owner); |
| 233 | assert!(captured.revalidate().await.unwrap()); |
| 234 | assert!( |
| 235 | codewhale_app_server::daemon_client::connect_if_published( |
| 236 | fixture.owner.config_path.clone(), |
| 237 | Some(fixture.owner.socket_path.clone()), |
| 238 | ) |
| 239 | .await |
| 240 | .is_err() |
| 241 | ); |
| 242 | assert!( |
| 243 | codewhale_app_server::daemon_client::connect( |
| 244 | fixture.owner.config_path.clone(), |
| 245 | Some(fixture.owner.socket_path.clone()), |
| 246 | ) |
| 247 | .await |
| 248 | .is_err() |
| 249 | ); |
| 250 | fixture.assert_publication(&fixture.bytes); |
| 251 | assert_eq!( |
| 252 | fixture.parent.socket_identity("daemon.sock").unwrap(), |
| 253 | identity |
| 254 | ); |
| 255 | assert_eq!( |
| 256 | std::fs::read_dir(&fixture.owner.data_dir).unwrap().count(), |
| 257 | 0, |
| 258 | "standalone control must not open or mint a store" |
| 259 | ); |
| 260 | } |
| 261 | |
| 262 | #[tokio::test] |
| 263 | async fn dead_owner_whose_store_was_deleted_is_discarded_and_startup_proceeds() { |
| 264 | let fixture = BootstrapPublicationFixture::new("boot-gone", true, false).await; |
| 265 | std::fs::remove_dir(&fixture.owner.data_dir).unwrap(); |
| 266 | assert!(matches!( |
| 267 | codewhale_app_server::daemon_client::probe_owner_for_host_startup( |
| 268 | fixture.owner.config_path.clone(), |
| 269 | Some(fixture.owner.socket_path.clone()), |
| 270 | &fixture.harness.root.join("another-store"), |
| 271 | ) |
| 272 | .await |
| 273 | .unwrap(), |
| 274 | codewhale_app_server::daemon_client::HostOwnerProbe::Unavailable(_) |
| 275 | )); |
| 276 | fixture.assert_publication(&fixture.bytes); |
| 277 | let probe = codewhale_app_server::daemon_client::probe_owner_for_host_startup( |
| 278 | fixture.owner.config_path.clone(), |
| 279 | Some(fixture.owner.socket_path.clone()), |
| 280 | &fixture.owner.data_dir, |
| 281 | ) |
| 282 | .await |
| 283 | .unwrap(); |
| 284 | assert!(matches!( |
| 285 | probe, |
| 286 | codewhale_app_server::daemon_client::HostOwnerProbe::Absent |
| 287 | )); |
| 288 | assert!( |
| 289 | fixture |
| 290 | .parent |
| 291 | .read_private_receipt("daemon.sock.owner.json", 16384) |
| 292 | .unwrap() |
| 293 | .is_none() |
| 294 | ); |
| 295 | assert!(!fixture.owner.data_dir.exists()); |
| 296 | fixture.bind_replacement(None).await.unwrap(); |
| 297 | } |
| 298 | |
| 299 | async fn assert_gone_store_spelled_as_is_discarded( |
| 300 | label: &str, |
| 301 | spell: impl FnOnce(&Path) -> PathBuf, |
| 302 | ) { |
| 303 | let fixture = BootstrapPublicationFixture::new(label, true, false).await; |
| 304 | std::fs::remove_dir(&fixture.owner.data_dir).unwrap(); |
| 305 | let spelled = spell(&fixture.harness.root); |
| 306 | assert_ne!(spelled, fixture.owner.data_dir); |
| 307 | assert!(matches!( |
| 308 | codewhale_app_server::daemon_client::probe_owner_for_host_startup( |
| 309 | fixture.owner.config_path.clone(), |
| 310 | Some(fixture.owner.socket_path.clone()), |
| 311 | &spelled, |
| 312 | ) |
| 313 | .await |
| 314 | .unwrap(), |
| 315 | codewhale_app_server::daemon_client::HostOwnerProbe::Absent |
| 316 | )); |
| 317 | assert!( |
| 318 | fixture |
| 319 | .parent |
| 320 | .read_private_receipt("daemon.sock.owner.json", 16384) |
| 321 | .unwrap() |
| 322 | .is_none() |
| 323 | ); |
| 324 | } |
| 325 | |
| 326 | #[tokio::test] |
| 327 | async fn dead_owner_is_discarded_when_the_selected_store_is_spelled_through_a_symlink() { |
| 328 | assert_gone_store_spelled_as_is_discarded("boot-gone-link", |root| { |
| 329 | std::os::unix::fs::symlink(root, root.join("alias")).unwrap(); |
| 330 | root.join("alias").join("runtime") |
| 331 | }) |
| 332 | .await; |
| 333 | } |
| 334 | |
| 335 | #[cfg(target_os = "macos")] |
| 336 | #[tokio::test] |
| 337 | async fn dead_owner_is_discarded_when_the_selected_store_is_spelled_in_another_letter_case() { |
| 338 | assert_gone_store_spelled_as_is_discarded("boot-gone-case", |root| { |
| 339 | let upper = PathBuf::from(root.to_string_lossy().to_uppercase()); |
| 340 | assert!(upper.exists(), "this test needs a case-insensitive volume"); |
| 341 | upper.join("RUNTIME") |
| 342 | }) |
| 343 | .await; |
| 344 | } |
| 345 | |
| 346 | #[tokio::test] |
| 347 | async fn live_owner_with_a_missing_store_is_never_discarded() { |
| 348 | let fixture = BootstrapPublicationFixture::new("boot-gone-live", false, false).await; |
| 349 | std::fs::remove_dir(&fixture.owner.data_dir).unwrap(); |
| 350 | fixture.capture().await; |
| 351 | fixture.assert_publication(&fixture.bytes); |
| 352 | } |
| 353 | |
| 354 | #[tokio::test] |
| 355 | async fn owner_bootstrap_live_process_and_reused_pid_refuse_retirement() { |
| 356 | for reused in [false, true] { |
| 357 | let fixture = BootstrapPublicationFixture::new("boot-live", false, reused).await; |
| 358 | let captured = fixture.capture().await; |
| 359 | let error = captured.revalidate().await.err().unwrap().to_string(); |
| 360 | assert!( |
| 361 | error.contains(if reused { "reused" } else { "still present" }), |
| 362 | "{error}" |
| 363 | ); |
| 364 | assert!(fixture.bind_replacement(Some(captured)).await.is_err()); |
| 365 | fixture.assert_publication(&fixture.bytes); |
| 366 | assert!( |
| 367 | fixture |
| 368 | .parent |
| 369 | .socket_identity("daemon.sock") |
| 370 | .unwrap() |
| 371 | .is_some() |
| 372 | ); |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | #[tokio::test] |
| 377 | async fn owner_bootstrap_equal_bytes_do_not_authorize_replaced_receipt() { |
| 378 | let fixture = BootstrapPublicationFixture::new("boot-file", true, false).await; |
| 379 | let captured = fixture.capture().await; |
| 380 | let identity = fixture.parent.socket_identity("daemon.sock").unwrap(); |
| 381 | std::fs::rename( |
| 382 | fixture |
| 383 | .harness |
| 384 | .socket_path |
| 385 | .with_file_name("daemon.sock.owner.json"), |
| 386 | fixture.harness.socket_path.with_file_name("old.owner.json"), |
| 387 | ) |
| 388 | .unwrap(); |
| 389 | fixture |
| 390 | .parent |
| 391 | .write_owned_file("daemon.sock.owner.json", &fixture.bytes, false) |
| 392 | .unwrap(); |
| 393 | assert!(!captured.revalidate().await.unwrap()); |
| 394 | assert!(fixture.bind_replacement(Some(captured)).await.is_err()); |
| 395 | fixture.assert_publication(&fixture.bytes); |
| 396 | assert_eq!( |
| 397 | fixture.parent.socket_identity("daemon.sock").unwrap(), |
| 398 | identity |
| 399 | ); |
| 400 | } |
| 401 | |
| 402 | #[tokio::test] |
| 403 | async fn owner_bootstrap_same_inode_content_change_is_preserved() { |
| 404 | let fixture = BootstrapPublicationFixture::new("boot-edit", true, false).await; |
| 405 | let captured = fixture.capture().await; |
| 406 | let mut edited = fixture.bytes.clone(); |
| 407 | edited.push(b'\n'); |
| 408 | std::fs::write( |
| 409 | fixture |
| 410 | .harness |
| 411 | .socket_path |
| 412 | .with_file_name("daemon.sock.owner.json"), |
| 413 | &edited, |
| 414 | ) |
| 415 | .unwrap(); |
| 416 | assert!(!captured.revalidate().await.unwrap()); |
| 417 | assert!(fixture.bind_replacement(Some(captured)).await.is_err()); |
| 418 | fixture.assert_publication(&edited); |
| 419 | } |
| 420 | |
| 421 | #[tokio::test] |
| 422 | async fn owner_bootstrap_replaced_socket_is_preserved() { |
| 423 | let fixture = BootstrapPublicationFixture::new("boot-sock", true, false).await; |
| 424 | let captured = fixture.capture().await; |
| 425 | std::fs::rename( |
| 426 | &fixture.harness.socket_path, |
| 427 | fixture.harness.socket_path.with_file_name("old.sock"), |
| 428 | ) |
| 429 | .unwrap(); |
| 430 | let replacement = std::os::unix::net::UnixListener::bind(&fixture.harness.socket_path).unwrap(); |
| 431 | let identity = fixture.parent.socket_identity("daemon.sock").unwrap(); |
| 432 | drop(replacement); |
| 433 | assert!(!captured.revalidate().await.unwrap()); |
| 434 | assert!(fixture.bind_replacement(Some(captured)).await.is_err()); |
| 435 | assert_eq!( |
| 436 | fixture.parent.socket_identity("daemon.sock").unwrap(), |
| 437 | identity |
| 438 | ); |
| 439 | fixture.assert_publication(&fixture.bytes); |
| 440 | } |
| 441 | |
| 442 | #[tokio::test] |
| 443 | async fn owner_bootstrap_fresh_bind_cannot_retire_uncaptured_publication() { |
| 444 | let fixture = BootstrapPublicationFixture::new("boot-fresh", true, false).await; |
| 445 | let identity = fixture.parent.socket_identity("daemon.sock").unwrap(); |
| 446 | assert!(fixture.bind_replacement(None).await.is_err()); |
| 447 | fixture.assert_publication(&fixture.bytes); |
| 448 | assert_eq!( |
| 449 | fixture.parent.socket_identity("daemon.sock").unwrap(), |
| 450 | identity |
| 451 | ); |
| 452 | } |
| 453 | |
| 454 | struct Client { |
| 455 | socket: WebSocketStream<UnixStream>, |
| 456 | } |
| 457 | |
| 458 | impl Client { |
| 459 | async fn connect(path: &Path) -> Self { |
| 460 | let stream = tokio::time::timeout(Duration::from_secs(5), UnixStream::connect(path)) |
| 461 | .await |
| 462 | .expect("connect timeout") |
| 463 | .expect("connect"); |
| 464 | let (socket, _) = tokio::time::timeout( |
| 465 | Duration::from_secs(5), |
| 466 | tokio_tungstenite::client_async("ws://localhost/", stream), |
| 467 | ) |
| 468 | .await |
| 469 | .expect("WebSocket upgrade timeout") |
| 470 | .expect("WebSocket upgrade"); |
| 471 | Self { socket } |
| 472 | } |
| 473 | |
| 474 | async fn call(&mut self, id: u64, method: &str, params: Value) -> Value { |
| 475 | let frame = json!({ |
| 476 | "id": id, |
| 477 | "method": method, |
| 478 | "params": params, |
| 479 | }); |
| 480 | self.socket |
| 481 | .send(Message::Text(frame.to_string().into())) |
| 482 | .await |
| 483 | .expect("write text frame"); |
| 484 | let response = tokio::time::timeout(Duration::from_secs(10), self.socket.next()) |
| 485 | .await |
| 486 | .expect("response timeout") |
| 487 | .expect("daemon closed before response") |
| 488 | .expect("read text frame"); |
| 489 | let Message::Text(response) = response else { |
| 490 | panic!("expected one JSON text frame, got {response:?}"); |
| 491 | }; |
| 492 | let value: Value = serde_json::from_str(&response).expect("json response"); |
| 493 | assert_eq!(value["id"], json!(id), "response id mismatch: {value}"); |
| 494 | assert!(value.get("jsonrpc").is_none()); |
| 495 | value |
| 496 | } |
| 497 | |
| 498 | async fn attach(&mut self, id: u64, name: &str, mode: &str) -> Value { |
| 499 | let response = self.call( |
| 500 | id, |
| 501 | "daemon/attach", |
| 502 | json!({ "client": { "name": name, "version": "0.0.0-test", "pid": std::process::id() }, "mode": mode }), |
| 503 | ) |
| 504 | .await; |
| 505 | if response.get("error").is_none() { |
| 506 | self.initialize().await; |
| 507 | } |
| 508 | response |
| 509 | } |
| 510 | |
| 511 | async fn initialize(&mut self) { |
| 512 | let initialized = self |
| 513 | .call( |
| 514 | 0, |
| 515 | "initialize", |
| 516 | json!({"clientInfo":{"name":"daemon-fixture","version":"1"}}), |
| 517 | ) |
| 518 | .await; |
| 519 | assert!(initialized.get("error").is_none(), "{initialized}"); |
| 520 | self.socket |
| 521 | .send(Message::Text("{\"method\":\"initialized\"}".into())) |
| 522 | .await |
| 523 | .expect("initialized notification"); |
| 524 | } |
| 525 | |
| 526 | async fn wait_for_close(mut self) { |
| 527 | let response = tokio::time::timeout(Duration::from_secs(10), self.socket.next()) |
| 528 | .await |
| 529 | .expect("close timeout"); |
| 530 | match response { |
| 531 | None | Some(Ok(Message::Close(_))) => {} |
| 532 | Some(Err(tokio_tungstenite::tungstenite::Error::Protocol( |
| 533 | tokio_tungstenite::tungstenite::error::ProtocolError::ResetWithoutClosingHandshake, |
| 534 | ))) => {} |
| 535 | Some(Err(tokio_tungstenite::tungstenite::Error::Io(error))) => assert!( |
| 536 | matches!( |
| 537 | error.kind(), |
| 538 | std::io::ErrorKind::UnexpectedEof |
| 539 | | std::io::ErrorKind::ConnectionReset |
| 540 | | std::io::ErrorKind::BrokenPipe |
| 541 | ), |
| 542 | "unexpected transport error: {error}" |
| 543 | ), |
| 544 | other => panic!("expected transport closure, got {other:?}"), |
| 545 | } |
| 546 | } |
| 547 | } |
| 548 | |
| 549 | async fn wait_for_socket_removed(path: &Path) { |
| 550 | tokio::time::timeout(Duration::from_secs(10), async { |
| 551 | while path.exists() { |
| 552 | tokio::time::sleep(Duration::from_millis(20)).await; |
| 553 | } |
| 554 | }) |
| 555 | .await |
| 556 | .expect("socket file must be removed on shutdown"); |
| 557 | } |
| 558 | |
| 559 | #[tokio::test] |
| 560 | async fn owner_attaches_round_trips_and_shuts_down_cleanly() { |
| 561 | let harness = Harness::new("owner"); |
| 562 | let server = harness.spawn_daemon().await; |
| 563 | |
| 564 | let socket_mode = std::fs::metadata(&harness.socket_path) |
| 565 | .expect("socket metadata") |
| 566 | .permissions() |
| 567 | .mode() |
| 568 | & 0o777; |
| 569 | assert_eq!(socket_mode, 0o600, "socket must be private to the user"); |
| 570 | let dir_mode = std::fs::metadata(harness.socket_path.parent().expect("parent")) |
| 571 | .expect("dir metadata") |
| 572 | .permissions() |
| 573 | .mode() |
| 574 | & 0o777; |
| 575 | assert_eq!(dir_mode, 0o700, "runtime dir must be private to the user"); |
| 576 | |
| 577 | let mut client = Client::connect(&harness.socket_path).await; |
| 578 | |
| 579 | // Anything but healthz before attaching is refused with a typed error: |
| 580 | // a read-only probe, a thread/* read, and a prompt run alike. |
| 581 | for (id, method, params) in [ |
| 582 | (1, "capabilities", json!({})), |
| 583 | (10, "thread/list", json!({})), |
| 584 | ( |
| 585 | 11, |
| 586 | "prompt/run", |
| 587 | json!({ "prompt": "hi", "allowed_tools": [] }), |
| 588 | ), |
| 589 | ] { |
| 590 | let early = client.call(id, method, params).await; |
| 591 | assert_eq!(early["error"]["code"], json!(-32010), "{method}: {early}"); |
| 592 | assert_eq!(early["error"]["data"]["error"], json!("attach_required")); |
| 593 | assert_eq!(early["error"]["data"]["method"], json!(method)); |
| 594 | } |
| 595 | |
| 596 | // healthz is allowed pre-attach so a shell can probe liveness first. |
| 597 | let health = client.call(2, "healthz", json!({})).await; |
| 598 | assert_eq!(health["result"]["status"], json!("ok"), "{health}"); |
| 599 | assert_eq!(health["result"]["transport"], json!("unix-socket")); |
| 600 | |
| 601 | let attached = client.attach(3, "codewhale-desktop", "claim").await; |
| 602 | assert_eq!(attached["result"]["attached"], json!(true), "{attached}"); |
| 603 | assert_eq!(attached["result"]["role"], json!("owner")); |
| 604 | assert_eq!(attached["result"]["transport"], json!("unix-socket")); |
| 605 | assert_eq!( |
| 606 | attached["result"]["daemon"]["pid"], |
| 607 | json!(std::process::id()) |
| 608 | ); |
| 609 | assert_eq!( |
| 610 | attached["result"]["daemon"]["version"], |
| 611 | json!(env!("CARGO_PKG_VERSION")) |
| 612 | ); |
| 613 | assert_eq!( |
| 614 | attached["result"]["owner"]["name"], |
| 615 | json!("codewhale-desktop") |
| 616 | ); |
| 617 | assert_eq!(attached["result"]["connections"], json!(1)); |
| 618 | |
| 619 | // Post-attach, the socket transport advertises its own handshake next to |
| 620 | // the stdio method set. |
| 621 | let advertised = client.call(8, "capabilities", json!({})).await; |
| 622 | let methods = advertised["result"]["methods"] |
| 623 | .as_array() |
| 624 | .expect("methods array"); |
| 625 | assert_eq!(methods[0], json!("healthz"), "{advertised}"); |
| 626 | assert_eq!(methods[1], json!("daemon/attach"), "{advertised}"); |
| 627 | assert!(methods.contains(&json!("shutdown"))); |
| 628 | |
| 629 | // Round-trip JSON-RPC requests through the shared dispatcher: `app/*` |
| 630 | // methods in, their JSON results out — byte-for-byte the shapes the |
| 631 | // stdio transport emits. (No protocol-crate Op/EventMsg envelope is on |
| 632 | // this wire; the framing is the stdio transport's newline-delimited |
| 633 | // JSON-RPC.) |
| 634 | let caps = client.call(4, "app/capabilities", json!({})).await; |
| 635 | assert_eq!(caps["result"]["ok"], json!(true), "{caps}"); |
| 636 | assert!(caps["result"]["data"]["routes"].is_array()); |
| 637 | let config = client |
| 638 | .call(5, "app/config/get", json!({ "key": "model" })) |
| 639 | .await; |
| 640 | assert_eq!(config["result"]["ok"], json!(true), "{config}"); |
| 641 | assert_eq!(config["result"]["data"]["key"], json!("model")); |
| 642 | |
| 643 | // A second attach on an attached connection is a typed refusal, not |
| 644 | // method_not_found. |
| 645 | let again = client.attach(6, "codewhale-desktop", "attach").await; |
| 646 | assert_eq!(again["error"]["code"], json!(-32014), "{again}"); |
| 647 | |
| 648 | let stopped = client.call(7, "shutdown", json!({})).await; |
| 649 | assert_eq!(stopped["result"]["status"], json!("stopped"), "{stopped}"); |
| 650 | |
| 651 | let outcome = tokio::time::timeout(Duration::from_secs(10), server) |
| 652 | .await |
| 653 | .expect("daemon must exit after the owner's shutdown") |
| 654 | .expect("join"); |
| 655 | outcome.expect("serve result"); |
| 656 | wait_for_socket_removed(&harness.socket_path).await; |
| 657 | client.wait_for_close().await; |
| 658 | } |
| 659 | |
| 660 | #[tokio::test] |
| 661 | async fn guests_share_the_daemon_but_cannot_stop_it() { |
| 662 | let harness = Harness::new("guest"); |
| 663 | let server = harness.spawn_daemon().await; |
| 664 | |
| 665 | let mut owner = Client::connect(&harness.socket_path).await; |
| 666 | let claimed = owner.attach(1, "desktop-window-1", "claim").await; |
| 667 | assert_eq!(claimed["result"]["role"], json!("owner"), "{claimed}"); |
| 668 | |
| 669 | let mut guest = Client::connect(&harness.socket_path).await; |
| 670 | let lost = guest.attach(1, "desktop-window-2", "claim").await; |
| 671 | assert_eq!(lost["error"]["code"], json!(-32011), "{lost}"); |
| 672 | assert_eq!( |
| 673 | lost["error"]["data"]["owner"]["name"], |
| 674 | json!("desktop-window-1") |
| 675 | ); |
| 676 | |
| 677 | let attached = guest.attach(2, "desktop-window-2", "attach").await; |
| 678 | assert_eq!(attached["result"]["role"], json!("attached"), "{attached}"); |
| 679 | assert_eq!( |
| 680 | attached["result"]["owner"]["name"], |
| 681 | json!("desktop-window-1") |
| 682 | ); |
| 683 | assert_eq!(attached["result"]["connections"], json!(2)); |
| 684 | |
| 685 | let health = guest.call(3, "healthz", json!({})).await; |
| 686 | assert_eq!(health["result"]["status"], json!("ok")); |
| 687 | |
| 688 | let refused = guest.call(4, "shutdown", json!({})).await; |
| 689 | assert_eq!(refused["error"]["code"], json!(-32012), "{refused}"); |
| 690 | assert_eq!(refused["error"]["data"]["error"], json!("not_daemon_owner")); |
| 691 | assert!( |
| 692 | !server.is_finished(), |
| 693 | "a guest's shutdown must not stop the daemon" |
| 694 | ); |
| 695 | assert!(harness.socket_path.exists()); |
| 696 | |
| 697 | // Once the owner leaves, the slot frees and a relaunched shell can claim. |
| 698 | drop(owner); |
| 699 | let mut relaunched = Client::connect(&harness.socket_path).await; |
| 700 | let reclaimed = tokio::time::timeout(Duration::from_secs(10), async { |
| 701 | loop { |
| 702 | let response = relaunched.attach(1, "desktop-relaunch", "claim").await; |
| 703 | if response.get("result").is_some() { |
| 704 | return response; |
| 705 | } |
| 706 | tokio::time::sleep(Duration::from_millis(20)).await; |
| 707 | } |
| 708 | }) |
| 709 | .await |
| 710 | .expect("owner slot must free when the owner disconnects"); |
| 711 | assert_eq!(reclaimed["result"]["role"], json!("owner"), "{reclaimed}"); |
| 712 | |
| 713 | // The guest is still attached and served while the new owner is in. |
| 714 | let health = guest.call(5, "healthz", json!({})).await; |
| 715 | assert_eq!(health["result"]["status"], json!("ok")); |
| 716 | |
| 717 | let stopped = relaunched.call(2, "shutdown", json!({})).await; |
| 718 | assert_eq!(stopped["result"]["status"], json!("stopped")); |
| 719 | tokio::time::timeout(Duration::from_secs(10), server) |
| 720 | .await |
| 721 | .expect("daemon exits") |
| 722 | .expect("join") |
| 723 | .expect("serve result"); |
| 724 | wait_for_socket_removed(&harness.socket_path).await; |
| 725 | // The owner's shutdown closes every other connection, not just its own. |
| 726 | guest.wait_for_close().await; |
| 727 | relaunched.wait_for_close().await; |
| 728 | } |
| 729 | |
| 730 | #[tokio::test] |
| 731 | async fn version_skew_is_refused_at_attach() { |
| 732 | let harness = Harness::new("skew"); |
| 733 | let server = harness.spawn_daemon().await; |
| 734 | let mut client = Client::connect(&harness.socket_path).await; |
| 735 | let refused = client |
| 736 | .call( |
| 737 | 1, |
| 738 | "daemon/attach", |
| 739 | json!({ "client": { "name": "old-desktop" }, "expect_daemon_version": "0.0.1-other" }), |
| 740 | ) |
| 741 | .await; |
| 742 | assert_eq!(refused["error"]["code"], json!(-32013), "{refused}"); |
| 743 | assert_eq!( |
| 744 | refused["error"]["data"]["actual"], |
| 745 | json!(env!("CARGO_PKG_VERSION")) |
| 746 | ); |
| 747 | |
| 748 | let daemon = bind_daemon_socket(harness.options()).await; |
| 749 | // Meanwhile the original daemon is live, so a second bind must refuse. |
| 750 | match daemon { |
| 751 | Err(DaemonSocketError::AlreadyRunning { path }) => { |
| 752 | assert_eq!(path, harness.socket_path); |
| 753 | } |
| 754 | Err(other) => panic!("unexpected error: {other}"), |
| 755 | Ok(_) => panic!("second daemon must not replace a live socket"), |
| 756 | } |
| 757 | server.abort(); |
| 758 | let _ = server.await; |
| 759 | } |
| 760 | |
| 761 | #[tokio::test] |
| 762 | async fn stale_socket_is_cleaned_up_and_foreign_files_are_refused() { |
| 763 | let harness = Harness::new("stale"); |
| 764 | std::fs::create_dir_all(harness.socket_path.parent().expect("parent")).expect("mkdir"); |
| 765 | std::fs::set_permissions( |
| 766 | harness.socket_path.parent().unwrap(), |
| 767 | std::fs::Permissions::from_mode(0o700), |
| 768 | ) |
| 769 | .expect("private stale fixture parent"); |
| 770 | |
| 771 | // A socket file whose listener is gone: bind must reclaim it. |
| 772 | { |
| 773 | let dead = tokio::net::UnixListener::bind(&harness.socket_path).expect("bind dead"); |
| 774 | drop(dead); |
| 775 | } |
| 776 | assert!( |
| 777 | harness.socket_path.exists(), |
| 778 | "dropping a listener leaves the file" |
| 779 | ); |
| 780 | let daemon = bind_daemon_socket(harness.options()) |
| 781 | .await |
| 782 | .expect("stale socket must be reclaimed"); |
| 783 | let handle = daemon.shutdown_handle(); |
| 784 | let server = tokio::spawn(daemon.serve()); |
| 785 | let mut client = Client::connect(&harness.socket_path).await; |
| 786 | let health = client.call(1, "healthz", json!({})).await; |
| 787 | assert_eq!(health["result"]["status"], json!("ok")); |
| 788 | handle.trigger(); |
| 789 | tokio::time::timeout(Duration::from_secs(10), server) |
| 790 | .await |
| 791 | .expect("daemon exits on handle") |
| 792 | .expect("join") |
| 793 | .expect("serve result"); |
| 794 | wait_for_socket_removed(&harness.socket_path).await; |
| 795 | |
| 796 | // A regular file at the path is never deleted. |
| 797 | std::fs::write(&harness.socket_path, b"not a socket").expect("write file"); |
| 798 | match bind_daemon_socket(harness.options()).await { |
| 799 | Err(DaemonSocketError::NotASocket { path }) => assert_eq!(path, harness.socket_path), |
| 800 | Err(other) => panic!("unexpected error: {other}"), |
| 801 | Ok(_) => panic!("must refuse to replace a non-socket"), |
| 802 | } |
| 803 | assert_eq!( |
| 804 | std::fs::read(&harness.socket_path).expect("file intact"), |
| 805 | b"not a socket" |
| 806 | ); |
| 807 | } |
| 808 | |
| 809 | #[tokio::test] |
| 810 | async fn binding_refuses_public_parent_and_drop_before_serve_retires_exact_socket() { |
| 811 | let harness = Harness::new("private"); |
| 812 | let parent = harness.socket_path.parent().unwrap(); |
| 813 | std::fs::create_dir_all(parent).unwrap(); |
| 814 | std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o755)).unwrap(); |
| 815 | assert!(bind_daemon_socket(harness.options()).await.is_err()); |
| 816 | assert_eq!( |
| 817 | std::fs::metadata(parent).unwrap().permissions().mode() & 0o777, |
| 818 | 0o755 |
| 819 | ); |
| 820 | assert!(!harness.socket_path.exists()); |
| 821 | std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700)).unwrap(); |
| 822 | let daemon = bind_daemon_socket(harness.options()).await.unwrap(); |
| 823 | assert!(harness.socket_path.exists()); |
| 824 | drop(daemon); |
| 825 | tokio::time::timeout(Duration::from_secs(5), async { |
| 826 | while harness.socket_path.exists() { |
| 827 | tokio::task::yield_now().await; |
| 828 | } |
| 829 | }) |
| 830 | .await |
| 831 | .expect("cancelled binder retirement finishes off-runtime"); |
| 832 | assert!(!harness.socket_path.exists()); |
| 833 | } |
| 834 | |
| 835 | #[tokio::test] |
| 836 | async fn dropping_bound_daemon_preserves_a_replacement_at_the_selected_path() { |
| 837 | let harness = Harness::new("replaced"); |
| 838 | let daemon = bind_daemon_socket(harness.options()).await.unwrap(); |
| 839 | let captured = harness.socket_path.with_extension("captured"); |
| 840 | std::fs::rename(&harness.socket_path, &captured).unwrap(); |
| 841 | std::fs::write(&harness.socket_path, b"operator replacement").unwrap(); |
| 842 | drop(daemon); |
| 843 | assert_eq!( |
| 844 | std::fs::read(&harness.socket_path).unwrap(), |
| 845 | b"operator replacement" |
| 846 | ); |
| 847 | assert!(captured.exists()); |
| 848 | } |
| 849 | |
| 850 | #[tokio::test] |
| 851 | async fn captured_owner_frontend_authenticates_generation_without_publishing_bearer() { |
| 852 | let harness = Harness::new("owner"); |
| 853 | let owner = codewhale_protocol::RuntimeOwnerReceipt { |
| 854 | version: 1, |
| 855 | data_dir: harness.root.join("runtime"), |
| 856 | execution_scope: "captured-test-store".into(), |
| 857 | lease_generation: "captured-test-generation".into(), |
| 858 | pid: std::process::id(), |
| 859 | process_start: codewhale_app_server::daemon_socket::capture_process_start( |
| 860 | std::process::id(), |
| 861 | ) |
| 862 | .await |
| 863 | .unwrap(), |
| 864 | principal: codewhale_config::private_directory::PrivateDirectory::current_user_id() |
| 865 | .to_string(), |
| 866 | socket_path: harness.socket_path.clone(), |
| 867 | config_path: harness.options().config_path, |
| 868 | }; |
| 869 | // Transport acceptance: the captured owner is a fixture, not an Engine/store proof. |
| 870 | let daemon = codewhale_app_server::bind_runtime_owner( |
| 871 | owner.config_path.clone(), |
| 872 | "127.0.0.1:1".parse().unwrap(), |
| 873 | Some("private-fixture-bearer".into()), |
| 874 | owner.clone(), |
| 875 | ) |
| 876 | .await |
| 877 | .unwrap(); |
| 878 | let receipt_path = harness.socket_path.with_file_name("daemon.sock.owner.json"); |
| 879 | let bytes = std::fs::read(&receipt_path).unwrap(); |
| 880 | assert_eq!( |
| 881 | serde_json::from_slice::<codewhale_protocol::RuntimeOwnerReceipt>(&bytes).unwrap(), |
| 882 | owner |
| 883 | ); |
| 884 | assert!( |
| 885 | !String::from_utf8(bytes) |
| 886 | .unwrap() |
| 887 | .contains("private-fixture-bearer") |
| 888 | ); |
| 889 | assert_eq!( |
| 890 | std::fs::metadata(&receipt_path) |
| 891 | .unwrap() |
| 892 | .permissions() |
| 893 | .mode() |
| 894 | & 0o777, |
| 895 | 0o600 |
| 896 | ); |
| 897 | let handle = daemon.shutdown_handle(); |
| 898 | let server = tokio::spawn(daemon.serve()); |
| 899 | let mut guest = Client::connect(&harness.socket_path).await; |
| 900 | let missing = guest.attach(1, "guest", "attach").await; |
| 901 | assert!(missing["error"].is_object()); |
| 902 | let mut stale = owner.clone(); |
| 903 | stale.lease_generation = "other-generation".into(); |
| 904 | let rejected = guest |
| 905 | .call( |
| 906 | 2, |
| 907 | "daemon/attach", |
| 908 | json!({"client":{"name":"guest"},"mode":"attach","expect_owner":stale}), |
| 909 | ) |
| 910 | .await; |
| 911 | assert!(rejected["error"].is_object()); |
| 912 | let claim = guest |
| 913 | .call( |
| 914 | 3, |
| 915 | "daemon/attach", |
| 916 | json!({"client":{"name":"guest"},"mode":"claim","expect_owner":owner}), |
| 917 | ) |
| 918 | .await; |
| 919 | assert!(claim["error"].is_object()); |
| 920 | let attached = guest |
| 921 | .call( |
| 922 | 4, |
| 923 | "daemon/attach", |
| 924 | json!({"client":{"name":"guest","pid":1},"mode":"attach","expect_owner":owner}), |
| 925 | ) |
| 926 | .await; |
| 927 | assert_eq!(attached["result"]["role"], "attached"); |
| 928 | assert_eq!(attached["result"]["owner_receipt"], json!(owner)); |
| 929 | guest.initialize().await; |
| 930 | // The display PID is deliberately false: authorization uses kernel peer credentials. |
| 931 | let denied = guest.call(5, "shutdown", json!({})).await; |
| 932 | assert!(denied["error"].is_object()); |
| 933 | assert!(guest.call(6, "healthz", json!({})).await["result"].is_object()); |
| 934 | handle.trigger(); |
| 935 | tokio::time::timeout(Duration::from_secs(5), server) |
| 936 | .await |
| 937 | .unwrap() |
| 938 | .unwrap() |
| 939 | .unwrap(); |
| 940 | assert!(!harness.socket_path.exists()); |
| 941 | assert!( |
| 942 | !receipt_path.exists(), |
| 943 | "normal shutdown awaits exact receipt retirement" |
| 944 | ); |
| 945 | } |
| 946 | |
| 947 | /// Native IPC transport proof with a fake owned Runtime; no Engine or |
| 948 | /// provider acceptance is inferred from this source fixture. |
| 949 | #[tokio::test] |
| 950 | async fn canonical_cli_control_uses_authenticated_owner_and_same_dispatcher() { |
| 951 | let harness = Harness::new("thread-control"); |
| 952 | let workspace = harness._config_dir.path().to_path_buf(); |
| 953 | let thread = serde_json::json!({"id":"canonical-transport","created_at":"2026-10-02T00:00:00Z", |
| 954 | "updated_at":"2026-10-02T00:00:00Z","model":"fixture-model","model_provider":"custom", |
| 955 | "model_provider_id":"fixture-owner","workspace":workspace,"archived":false}); |
| 956 | let owner = codewhale_protocol::RuntimeOwnerReceipt { |
| 957 | version: 1, |
| 958 | data_dir: harness.root.join("runtime"), |
| 959 | execution_scope: "control-fixture".into(), |
| 960 | lease_generation: "control-generation".into(), |
| 961 | pid: std::process::id(), |
| 962 | process_start: codewhale_app_server::daemon_socket::capture_process_start( |
| 963 | std::process::id(), |
| 964 | ) |
| 965 | .await |
| 966 | .unwrap(), |
| 967 | principal: codewhale_config::private_directory::PrivateDirectory::current_user_id() |
| 968 | .to_string(), |
| 969 | socket_path: harness.socket_path.clone(), |
| 970 | config_path: harness.options().config_path, |
| 971 | }; |
| 972 | let frontend = std::sync::Arc::new(ScopedControlFixture { |
| 973 | workers: 0, |
| 974 | config: owner.config_path.clone().unwrap(), |
| 975 | scopes: Default::default(), |
| 976 | owner: owner.clone(), |
| 977 | target: workspace.clone(), |
| 978 | records: vec![thread], |
| 979 | calls: Default::default(), |
| 980 | }); |
| 981 | let (daemon, _) = codewhale_app_server::bind_runtime_frontends( |
| 982 | owner.config_path.clone(), |
| 983 | Some("private-fixture-control".into()), |
| 984 | owner.clone(), |
| 985 | codewhale_app_server::RuntimeOwnerRouting { |
| 986 | endpoint: "127.0.0.1:1".parse().unwrap(), |
| 987 | workspace: None, |
| 988 | workers: None, |
| 989 | mobile: false, |
| 990 | web: false, |
| 991 | acp: true, |
| 992 | acp_only: false, |
| 993 | }, |
| 994 | Some(frontend), |
| 995 | None, |
| 996 | ) |
| 997 | .await |
| 998 | .unwrap(); |
| 999 | let daemon = daemon.expect("a private endpoint directory is available on this host"); |
| 1000 | let shutdown = daemon.shutdown_handle(); |
| 1001 | let socket = tokio::spawn(daemon.serve()); |
| 1002 | let result = codewhale_app_server::request_thread_control( |
| 1003 | owner.config_path.clone(), |
| 1004 | Some(harness.socket_path.clone()), |
| 1005 | None, |
| 1006 | codewhale_protocol::ThreadRequest::List(codewhale_protocol::ThreadListParams { |
| 1007 | include_archived: false, |
| 1008 | limit: None, |
| 1009 | }), |
| 1010 | ) |
| 1011 | .await |
| 1012 | .unwrap(); |
| 1013 | assert_eq!(result.threads.len(), 1); |
| 1014 | assert_eq!(result.threads[0].id, "canonical-transport"); |
| 1015 | assert_eq!(result.threads[0].model_provider, "fixture-owner"); |
| 1016 | assert!( |
| 1017 | !serde_json::to_string(&result) |
| 1018 | .unwrap() |
| 1019 | .contains("private-fixture-control") |
| 1020 | ); |
| 1021 | let error = codewhale_app_server::request_thread_control( |
| 1022 | owner.config_path.clone(), |
| 1023 | Some(harness.socket_path.clone()), |
| 1024 | Some(codewhale_app_server::ThreadControlSelection { |
| 1025 | workspace: Some(workspace), |
| 1026 | config_profile: None, |
| 1027 | config_source: None, |
| 1028 | }), |
| 1029 | codewhale_protocol::ThreadRequest::List(codewhale_protocol::ThreadListParams { |
| 1030 | include_archived: false, |
| 1031 | limit: None, |
| 1032 | }), |
| 1033 | ) |
| 1034 | .await |
| 1035 | .unwrap_err(); |
| 1036 | assert!(format!("{error:#}").contains("no captured worker setting")); |
| 1037 | shutdown.trigger(); |
| 1038 | tokio::time::timeout(Duration::from_secs(5), socket) |
| 1039 | .await |
| 1040 | .unwrap() |
| 1041 | .unwrap() |
| 1042 | .unwrap(); |
| 1043 | } |
| 1044 | |
| 1045 | /// This only validates the adapter's captured scope transport. Actual Runtime |
| 1046 | /// policy/Config admission is covered by the owning Runtime acceptance suite. |
| 1047 | struct ScopedControlFixture { |
| 1048 | workers: usize, |
| 1049 | config: PathBuf, |
| 1050 | scopes: std::sync::Arc<tokio::sync::Mutex<Vec<codewhale_app_server::RuntimeFrontendScope>>>, |
| 1051 | owner: codewhale_protocol::RuntimeOwnerReceipt, |
| 1052 | target: PathBuf, |
| 1053 | records: Vec<Value>, |
| 1054 | calls: std::sync::Arc<tokio::sync::Mutex<Vec<(String, Value)>>>, |
| 1055 | } |
| 1056 | |
| 1057 | fn thread_record(id: &str, root: &Path) -> Value { |
| 1058 | json!({"id":id,"created_at":"2026-10-02T00:00:00Z", |
| 1059 | "updated_at":"2026-10-02T00:00:00Z","model":"fixture-model","model_provider":"custom", |
| 1060 | "model_provider_id":"fixture-owner","workspace":root,"archived":false}) |
| 1061 | } |
| 1062 | |
| 1063 | impl codewhale_app_server::RuntimeOwnerFrontend for ScopedControlFixture { |
| 1064 | fn execute( |
| 1065 | &self, |
| 1066 | request: codewhale_app_server::RuntimeOwnerRequest, |
| 1067 | ) -> std::pin::Pin< |
| 1068 | Box<dyn std::future::Future<Output = anyhow::Result<serde_json::Value>> + Send + '_>, |
| 1069 | > { |
| 1070 | use codewhale_app_server::RuntimeOwnerRequest as Request; |
| 1071 | Box::pin(async move { |
| 1072 | let owner = &self.owner; |
| 1073 | let (name, body) = match &request { |
| 1074 | Request::HistoryLookup(body) => ("lookup", serde_json::to_value(body)?), |
| 1075 | Request::HistoryMutate(body) => ("mutate", serde_json::to_value(body)?), |
| 1076 | Request::HistorySnapshot { thread_id } => ("history", json!(thread_id)), |
| 1077 | Request::GetThread { thread_id } => ("thread", json!(thread_id)), |
| 1078 | Request::ListThreads { .. } => ("list", Value::Null), |
| 1079 | Request::RunningThreads => ("running", Value::Null), |
| 1080 | _ => anyhow::bail!("this captured frontend admits no ordinary native service"), |
| 1081 | }; |
| 1082 | self.calls.lock().await.push((name.into(), body.clone())); |
| 1083 | Ok(match request { |
| 1084 | Request::HistoryLookup(_) => json!({"state":"absent"}), |
| 1085 | Request::HistoryMutate(_) => { |
| 1086 | anyhow::ensure!(body["expected_data_dir"] == json!(owner.data_dir)); |
| 1087 | anyhow::ensure!(body["expected_execution_scope"] == owner.execution_scope); |
| 1088 | anyhow::ensure!(body["workspace"] == json!(self.target)); |
| 1089 | anyhow::ensure!( |
| 1090 | body["mutation"]["options"]["overrides"] |
| 1091 | == json!({"model":"explicit-model", "model_provider":"fixture-owner", "approval_policy":"on-request", "sandbox":"workspace-write"}) |
| 1092 | ); |
| 1093 | let fork = body["mutation"]["action"] == "fork"; |
| 1094 | json!({"version":1,"data_dir":owner.data_dir,"execution_scope":owner.execution_scope, |
| 1095 | "operation_key":body["operation_key"],"request_digest":"1".repeat(64),"history_digest":"2".repeat(64), |
| 1096 | "runtime_thread_id":if fork {"canonical-scoped-fork"} else {"canonical-source"}, |
| 1097 | "session_id":if fork {"session-scoped-fork"} else {"session-source"}}) |
| 1098 | } |
| 1099 | Request::HistorySnapshot { .. } => { |
| 1100 | json!({"version":1,"data_dir":owner.data_dir,"execution_scope":owner.execution_scope, |
| 1101 | "runtime_thread_id":"canonical-source","saved_session_id":"session-source", |
| 1102 | "saved_document_digest":"a".repeat(64),"session_goal_digest":"74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b", |
| 1103 | "document_digest":"b".repeat(64),"session":{"metadata":{"id":"session-source"},"messages":[],"journal":{"entries":[]}}}) |
| 1104 | } |
| 1105 | Request::RunningThreads => json!([]), |
| 1106 | Request::ListThreads { .. } => json!(self.records), |
| 1107 | Request::GetThread { thread_id } |
| 1108 | if thread_id == "canonical-source" || thread_id == "canonical-scoped-fork" => |
| 1109 | { |
| 1110 | thread_record(&thread_id, &self.target) |
| 1111 | } |
| 1112 | _ => anyhow::bail!("fixture route missing"), |
| 1113 | }) |
| 1114 | }) |
| 1115 | } |
| 1116 | fn events( |
| 1117 | &self, |
| 1118 | _thread_id: String, |
| 1119 | _since_seq: u64, |
| 1120 | ) -> std::pin::Pin< |
| 1121 | Box< |
| 1122 | dyn std::future::Future< |
| 1123 | Output = anyhow::Result<codewhale_app_server::RuntimeOwnerEventStream>, |
| 1124 | > + Send |
| 1125 | + '_, |
| 1126 | >, |
| 1127 | > { |
| 1128 | Box::pin(async { |
| 1129 | anyhow::bail!("this captured frontend admits no ordinary native observation") |
| 1130 | }) |
| 1131 | } |
| 1132 | fn validate_selection<'a>( |
| 1133 | &'a self, |
| 1134 | selection: &'a codewhale_app_server::RuntimeOwnerFrontendSelection, |
| 1135 | ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<()>> + Send + 'a>> { |
| 1136 | Box::pin(async move { |
| 1137 | let codewhale_app_server::RuntimeOwnerFrontendSelection::Control(scope) = selection |
| 1138 | else { |
| 1139 | anyhow::bail!("fixture expects the existing control frontend"); |
| 1140 | }; |
| 1141 | anyhow::ensure!( |
| 1142 | scope.workers == self.workers, |
| 1143 | "captured scheduler setting changed" |
| 1144 | ); |
| 1145 | anyhow::ensure!( |
| 1146 | scope.workspace.is_absolute() && scope.workspace.is_dir(), |
| 1147 | "fixture scope is not selected" |
| 1148 | ); |
| 1149 | anyhow::ensure!( |
| 1150 | scope |
| 1151 | .config_profile |
| 1152 | .as_deref() |
| 1153 | .is_none_or(|profile| profile == "reviewed"), |
| 1154 | "profile is not admitted by held owner" |
| 1155 | ); |
| 1156 | anyhow::ensure!( |
| 1157 | scope |
| 1158 | .config_source |
| 1159 | .as_ref() |
| 1160 | .is_none_or(|source| source == &self.config), |
| 1161 | "config is not admitted by held owner" |
| 1162 | ); |
| 1163 | self.scopes.lock().await.push(scope.clone()); |
| 1164 | Ok(()) |
| 1165 | }) |
| 1166 | } |
| 1167 | fn serve<'a>( |
| 1168 | &'a self, |
| 1169 | selection: codewhale_app_server::RuntimeOwnerFrontendSelection, |
| 1170 | compatibility: codewhale_app_server::AppState, |
| 1171 | input: Box<dyn tokio::io::AsyncBufRead + Send + Unpin>, |
| 1172 | output: Box<dyn tokio::io::AsyncWrite + Send + Unpin + 'a>, |
| 1173 | ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<()>> + Send + 'a>> { |
| 1174 | Box::pin(async move { |
| 1175 | let codewhale_app_server::RuntimeOwnerFrontendSelection::Control(scope) = selection |
| 1176 | else { |
| 1177 | anyhow::bail!("fixture expects control"); |
| 1178 | }; |
| 1179 | codewhale_app_server::run_guest_control(compatibility, scope.workspace, input, output) |
| 1180 | .await |
| 1181 | }) |
| 1182 | } |
| 1183 | } |
| 1184 | |
| 1185 | #[tokio::test] |
| 1186 | async fn canonical_cli_scoped_resume_fork_keep_exact_owner_workers_and_refuse_wrong_selection() { |
| 1187 | use std::sync::Arc; |
| 1188 | let harness = Harness::new("scoped-control"); |
| 1189 | let workspace = harness._config_dir.path().to_path_buf(); |
| 1190 | let selected = workspace.join("explicit-target"); |
| 1191 | std::fs::create_dir(&selected).unwrap(); |
| 1192 | let owner = codewhale_protocol::RuntimeOwnerReceipt { |
| 1193 | version: 1, |
| 1194 | data_dir: harness.root.join("runtime"), |
| 1195 | execution_scope: "scoped-control-store".into(), |
| 1196 | lease_generation: "scoped-control-generation".into(), |
| 1197 | pid: std::process::id(), |
| 1198 | process_start: codewhale_app_server::daemon_socket::capture_process_start( |
| 1199 | std::process::id(), |
| 1200 | ) |
| 1201 | .await |
| 1202 | .unwrap(), |
| 1203 | principal: codewhale_config::private_directory::PrivateDirectory::current_user_id() |
| 1204 | .to_string(), |
| 1205 | socket_path: harness.socket_path.clone(), |
| 1206 | config_path: harness.options().config_path, |
| 1207 | }; |
| 1208 | let calls = Arc::new(tokio::sync::Mutex::new(Vec::<(String, Value)>::new())); |
| 1209 | let endpoint: std::net::SocketAddr = "127.0.0.1:1".parse().unwrap(); |
| 1210 | let scopes = Arc::new(tokio::sync::Mutex::new(Vec::new())); |
| 1211 | let frontend = Arc::new(ScopedControlFixture { |
| 1212 | workers: 7, |
| 1213 | config: owner.config_path.clone().unwrap(), |
| 1214 | scopes: scopes.clone(), |
| 1215 | owner: owner.clone(), |
| 1216 | target: selected.clone(), |
| 1217 | records: vec![ |
| 1218 | thread_record("canonical-source", &selected), |
| 1219 | thread_record("other-workspace", Path::new("/recorded-other-workspace")), |
| 1220 | ], |
| 1221 | calls: calls.clone(), |
| 1222 | }); |
| 1223 | let (daemon, _) = codewhale_app_server::bind_runtime_frontends( |
| 1224 | owner.config_path.clone(), |
| 1225 | Some("fixture-private-scope-token".into()), |
| 1226 | owner.clone(), |
| 1227 | codewhale_app_server::RuntimeOwnerRouting { |
| 1228 | endpoint, |
| 1229 | workspace: Some(workspace), |
| 1230 | workers: Some(7), |
| 1231 | mobile: false, |
| 1232 | web: false, |
| 1233 | acp: true, |
| 1234 | acp_only: false, |
| 1235 | }, |
| 1236 | Some(frontend), |
| 1237 | None, |
| 1238 | ) |
| 1239 | .await |
| 1240 | .unwrap(); |
| 1241 | let daemon = daemon.expect("a private endpoint directory is available on this host"); |
| 1242 | let shutdown = daemon.shutdown_handle(); |
| 1243 | let socket = tokio::spawn(daemon.serve()); |
| 1244 | let selection = codewhale_app_server::ThreadControlSelection { |
| 1245 | workspace: Some(selected.clone()), |
| 1246 | config_profile: Some("reviewed".into()), |
| 1247 | config_source: owner.config_path.clone(), |
| 1248 | }; |
| 1249 | for (kind, operation, expected_id) in [ |
| 1250 | ("resume", "scoped-resume", "canonical-source"), |
| 1251 | ("fork", "scoped-fork", "canonical-scoped-fork"), |
| 1252 | ] { |
| 1253 | let request = serde_json::from_value( |
| 1254 | json!({"kind":kind,"thread_id":"canonical-source","operation_key":operation, |
| 1255 | "model":"explicit-model", "model_provider":"fixture-owner", "approval_policy":"on-request", "sandbox":"workspace-write"}), |
| 1256 | ) |
| 1257 | .unwrap(); |
| 1258 | let response = codewhale_app_server::request_thread_control( |
| 1259 | owner.config_path.clone(), |
| 1260 | Some(harness.socket_path.clone()), |
| 1261 | Some(selection.clone()), |
| 1262 | request, |
| 1263 | ) |
| 1264 | .await |
| 1265 | .unwrap(); |
| 1266 | assert_eq!(response.data["receipt"]["operation_key"], operation); |
| 1267 | assert_eq!(response.data["receipt"]["runtime_thread_id"], expected_id); |
| 1268 | assert_eq!(response.thread.unwrap().id, expected_id); |
| 1269 | } |
| 1270 | let list = codewhale_app_server::request_thread_control( |
| 1271 | owner.config_path.clone(), |
| 1272 | Some(harness.socket_path.clone()), |
| 1273 | Some(selection.clone()), |
| 1274 | codewhale_protocol::ThreadRequest::List(codewhale_protocol::ThreadListParams { |
| 1275 | include_archived: false, |
| 1276 | limit: None, |
| 1277 | }), |
| 1278 | ) |
| 1279 | .await |
| 1280 | .unwrap(); |
| 1281 | assert!( |
| 1282 | list.threads |
| 1283 | .iter() |
| 1284 | .any(|thread| thread.id == "other-workspace"), |
| 1285 | "scoped execution does not filter owner-store-wide read-only list" |
| 1286 | ); |
| 1287 | assert!(scopes.lock().await.iter().all(|scope| scope.workers == 7 |
| 1288 | && scope.workspace == selected |
| 1289 | && scope.config_profile.as_deref() == Some("reviewed"))); |
| 1290 | let before = calls.lock().await.len(); |
| 1291 | for wrong in [ |
| 1292 | codewhale_app_server::ThreadControlSelection { |
| 1293 | config_profile: Some("wrong".into()), |
| 1294 | ..selection.clone() |
| 1295 | }, |
| 1296 | codewhale_app_server::ThreadControlSelection { |
| 1297 | config_source: Some(selected.join("other.toml")), |
| 1298 | ..selection.clone() |
| 1299 | }, |
| 1300 | ] { |
| 1301 | let request = serde_json::from_value(json!({"kind":"resume","thread_id":"canonical-source","operation_key":"never-dispatched"})).unwrap(); |
| 1302 | assert!( |
| 1303 | codewhale_app_server::request_thread_control( |
| 1304 | owner.config_path.clone(), |
| 1305 | Some(harness.socket_path.clone()), |
| 1306 | Some(wrong), |
| 1307 | request |
| 1308 | ) |
| 1309 | .await |
| 1310 | .is_err() |
| 1311 | ); |
| 1312 | } |
| 1313 | assert_eq!( |
| 1314 | calls.lock().await.len(), |
| 1315 | before, |
| 1316 | "selection refusal happens before native effect dispatch" |
| 1317 | ); |
| 1318 | shutdown.trigger(); |
| 1319 | tokio::time::timeout(Duration::from_secs(5), socket) |
| 1320 | .await |
| 1321 | .unwrap() |
| 1322 | .unwrap() |
| 1323 | .unwrap(); |
| 1324 | } |
| 1325 |