| 1 | #![cfg(unix)] |
| 2 | |
| 3 | use anyhow::Result; |
| 4 | use codewhale_app_server::{ |
| 5 | AppState, RuntimeOwnerEventFrame, RuntimeOwnerEventStream, RuntimeOwnerFrontend, |
| 6 | RuntimeOwnerFrontendSelection, RuntimeOwnerRequest, |
| 7 | }; |
| 8 | use codewhale_app_server_protocol::runtime::NativeRuntimeRequest; |
| 9 | use serde_json::{Value, json}; |
| 10 | use std::path::PathBuf; |
| 11 | use std::sync::{ |
| 12 | Arc, |
| 13 | atomic::{AtomicUsize, Ordering}, |
| 14 | }; |
| 15 | use std::time::Duration; |
| 16 | use tokio::sync::Notify; |
| 17 | |
| 18 | type Future<'a, T> = std::pin::Pin<Box<dyn std::future::Future<Output = Result<T>> + Send + 'a>>; |
| 19 | |
| 20 | struct Captured { |
| 21 | workspace: PathBuf, |
| 22 | admitted: Notify, |
| 23 | release: tokio::sync::Semaphore, |
| 24 | completed: AtomicUsize, |
| 25 | calls: AtomicUsize, |
| 26 | } |
| 27 | |
| 28 | impl RuntimeOwnerFrontend for Captured { |
| 29 | fn execute(&self, request: RuntimeOwnerRequest) -> Future<'_, Value> { |
| 30 | Box::pin(async move { |
| 31 | let RuntimeOwnerRequest::Native { workspace, request } = request else { |
| 32 | anyhow::bail!("ordinary control is not a native projection") |
| 33 | }; |
| 34 | anyhow::ensure!(workspace == self.workspace, "wrong workspace"); |
| 35 | self.calls.fetch_add(1, Ordering::SeqCst); |
| 36 | match request { |
| 37 | NativeRuntimeRequest::StartTurn(params) => { |
| 38 | self.admitted.notify_one(); |
| 39 | self.release.acquire().await?.forget(); |
| 40 | self.completed.fetch_add(1, Ordering::SeqCst); |
| 41 | Ok(json!({"thread":{"id":params.thread_id},"turn":{"id":"turn-1"}})) |
| 42 | } |
| 43 | NativeRuntimeRequest::Subscribe(_) => Ok(Value::Null), |
| 44 | NativeRuntimeRequest::Capabilities(_) => Ok( |
| 45 | json!({"native_runtime":codewhale_app_server::native_runtime::capabilities()}), |
| 46 | ), |
| 47 | _ => Ok(json!({"captured":true})), |
| 48 | } |
| 49 | }) |
| 50 | } |
| 51 | fn events(&self, _thread_id: String, _since_seq: u64) -> Future<'_, RuntimeOwnerEventStream> { |
| 52 | Box::pin(async { |
| 53 | let stream: RuntimeOwnerEventStream = Box::pin(futures_util::stream::iter([ |
| 54 | RuntimeOwnerEventFrame { |
| 55 | event: "turn.started".into(), |
| 56 | data: json!({"turn_id":"turn-1"}), |
| 57 | sequence: Some(42), |
| 58 | }, |
| 59 | RuntimeOwnerEventFrame { |
| 60 | event: "stream.end".into(), |
| 61 | data: json!({"reason":"owner_stopping","last_seq":42,"retryable":true}), |
| 62 | sequence: None, |
| 63 | }, |
| 64 | ])); |
| 65 | Ok(stream) |
| 66 | }) |
| 67 | } |
| 68 | fn validate_selection<'a>( |
| 69 | &'a self, |
| 70 | _selection: &'a RuntimeOwnerFrontendSelection, |
| 71 | ) -> Future<'a, ()> { |
| 72 | Box::pin(async { anyhow::bail!("not a scoped fixture") }) |
| 73 | } |
| 74 | fn serve<'a>( |
| 75 | &'a self, |
| 76 | _selection: RuntimeOwnerFrontendSelection, |
| 77 | _compatibility: AppState, |
| 78 | _input: Box<dyn tokio::io::AsyncBufRead + Send + Unpin>, |
| 79 | _output: Box<dyn tokio::io::AsyncWrite + Send + Unpin + 'a>, |
| 80 | ) -> Future<'a, ()> { |
| 81 | Box::pin(async { anyhow::bail!("not another frontend") }) |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | struct Harness { |
| 86 | _root: tempfile::TempDir, |
| 87 | owner: codewhale_protocol::RuntimeOwnerReceipt, |
| 88 | captured: Arc<Captured>, |
| 89 | shutdown: codewhale_app_server::daemon_socket::DaemonShutdownHandle, |
| 90 | server: |
| 91 | tokio::task::JoinHandle<Result<(), codewhale_app_server::daemon_socket::DaemonSocketError>>, |
| 92 | } |
| 93 | |
| 94 | impl Harness { |
| 95 | async fn new() -> Self { |
| 96 | let root = tempfile::Builder::new() |
| 97 | .prefix("cw-native-") |
| 98 | .tempdir_in("/tmp") |
| 99 | .unwrap(); |
| 100 | let canonical = root.path().canonicalize().unwrap(); |
| 101 | let config = canonical.join("config.toml"); |
| 102 | std::fs::write(&config, "").unwrap(); |
| 103 | let workspace = canonical.join("workspace"); |
| 104 | std::fs::create_dir(&workspace).unwrap(); |
| 105 | let owner = codewhale_protocol::RuntimeOwnerReceipt { |
| 106 | version: 1, |
| 107 | data_dir: canonical.join("runtime"), |
| 108 | execution_scope: "native-fixture".into(), |
| 109 | lease_generation: uuid::Uuid::new_v4().to_string(), |
| 110 | pid: std::process::id(), |
| 111 | process_start: codewhale_app_server::daemon_socket::capture_process_start( |
| 112 | std::process::id(), |
| 113 | ) |
| 114 | .await |
| 115 | .unwrap(), |
| 116 | principal: codewhale_config::private_directory::PrivateDirectory::current_user_id() |
| 117 | .to_string(), |
| 118 | socket_path: canonical.join("run/daemon.sock"), |
| 119 | config_path: Some(config), |
| 120 | }; |
| 121 | let captured = Arc::new(Captured { |
| 122 | workspace, |
| 123 | admitted: Notify::new(), |
| 124 | release: tokio::sync::Semaphore::new(0), |
| 125 | completed: AtomicUsize::new(0), |
| 126 | calls: AtomicUsize::new(0), |
| 127 | }); |
| 128 | let (daemon, _) = codewhale_app_server::bind_runtime_frontends( |
| 129 | owner.config_path.clone(), |
| 130 | None, |
| 131 | owner.clone(), |
| 132 | codewhale_app_server::RuntimeOwnerRouting { |
| 133 | endpoint: "127.0.0.1:1".parse().unwrap(), |
| 134 | workspace: Some(captured.workspace.clone()), |
| 135 | workers: None, |
| 136 | mobile: false, |
| 137 | web: false, |
| 138 | acp: true, |
| 139 | acp_only: false, |
| 140 | }, |
| 141 | Some(captured.clone()), |
| 142 | None, |
| 143 | ) |
| 144 | .await |
| 145 | .unwrap(); |
| 146 | let daemon = daemon.unwrap(); |
| 147 | let shutdown = daemon.shutdown_handle(); |
| 148 | let server = tokio::spawn(daemon.serve()); |
| 149 | Self { |
| 150 | _root: root, |
| 151 | owner, |
| 152 | captured, |
| 153 | shutdown, |
| 154 | server, |
| 155 | } |
| 156 | } |
| 157 | async fn connect(&self) -> codewhale_app_server::daemon_client::OwnerClient { |
| 158 | codewhale_app_server::daemon_client::connect_native( |
| 159 | self.owner.clone(), |
| 160 | self.captured.workspace.clone(), |
| 161 | ) |
| 162 | .await |
| 163 | .unwrap() |
| 164 | } |
| 165 | async fn stop(self) { |
| 166 | self.shutdown.trigger(); |
| 167 | tokio::time::timeout(Duration::from_secs(5), self.server) |
| 168 | .await |
| 169 | .unwrap() |
| 170 | .unwrap() |
| 171 | .unwrap(); |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | async fn receive(client: &mut codewhale_app_server::daemon_client::OwnerClient) -> Value { |
| 176 | tokio::time::timeout(Duration::from_secs(5), client.recv()) |
| 177 | .await |
| 178 | .unwrap() |
| 179 | .unwrap() |
| 180 | .unwrap() |
| 181 | } |
| 182 | |
| 183 | #[tokio::test] |
| 184 | async fn native_attach_requires_exact_generation_workspace_and_explicit_capability() { |
| 185 | let harness = Harness::new().await; |
| 186 | let mut stale = harness.owner.clone(); |
| 187 | stale.lease_generation = "retired".into(); |
| 188 | assert!( |
| 189 | codewhale_app_server::daemon_client::connect_native( |
| 190 | stale, |
| 191 | harness.captured.workspace.clone() |
| 192 | ) |
| 193 | .await |
| 194 | .is_err() |
| 195 | ); |
| 196 | assert!( |
| 197 | codewhale_app_server::daemon_client::connect_native( |
| 198 | harness.owner.clone(), |
| 199 | harness.owner.data_dir.clone() |
| 200 | ) |
| 201 | .await |
| 202 | .is_err() |
| 203 | ); |
| 204 | let mut native = harness.connect().await; |
| 205 | native |
| 206 | .send(json!(1), "runtime/capabilities", json!({})) |
| 207 | .await |
| 208 | .unwrap(); |
| 209 | assert_eq!( |
| 210 | receive(&mut native).await["result"]["native_runtime"]["capabilities"], |
| 211 | json!(["native_runtime_v1"]) |
| 212 | ); |
| 213 | let before = harness.captured.calls.load(Ordering::SeqCst); |
| 214 | for (id, method, params) in [ |
| 215 | (2, "config/set", json!({})), |
| 216 | (3, "shutdown", json!({})), |
| 217 | ( |
| 218 | 4, |
| 219 | "runtime/thread/create", |
| 220 | json!({"body":{"operation_key":"k","auto_approve":true}}), |
| 221 | ), |
| 222 | ( |
| 223 | 5, |
| 224 | "runtime/turn/start", |
| 225 | json!({"thread_id":"t","body":{"operation_key":"k","prompt":"hi","profile_constitution":{}}}), |
| 226 | ), |
| 227 | ] { |
| 228 | native.send(json!(id), method, params).await.unwrap(); |
| 229 | assert_eq!( |
| 230 | receive(&mut native).await["error"]["data"]["outcome"], |
| 231 | "not_started" |
| 232 | ); |
| 233 | } |
| 234 | assert_eq!(harness.captured.calls.load(Ordering::SeqCst), before); |
| 235 | let mut legacy = codewhale_app_server::daemon_client::connect( |
| 236 | harness.owner.config_path.clone(), |
| 237 | Some(harness.owner.socket_path.clone()), |
| 238 | ) |
| 239 | .await |
| 240 | .unwrap(); |
| 241 | legacy |
| 242 | .send(json!(9), "runtime/capabilities", json!({})) |
| 243 | .await |
| 244 | .unwrap(); |
| 245 | assert!(receive(&mut legacy).await.get("error").is_some()); |
| 246 | drop(native); |
| 247 | drop(legacy); |
| 248 | harness.stop().await; |
| 249 | } |
| 250 | |
| 251 | #[tokio::test] |
| 252 | async fn native_subscription_ack_precedes_original_frames_and_null_sequence_end() { |
| 253 | let harness = Harness::new().await; |
| 254 | let mut client = harness.connect().await; |
| 255 | client |
| 256 | .send( |
| 257 | json!(1), |
| 258 | "runtime/events/subscribe", |
| 259 | json!({"thread_id":"t","since_seq":41}), |
| 260 | ) |
| 261 | .await |
| 262 | .unwrap(); |
| 263 | let ack = receive(&mut client).await; |
| 264 | let subscription = ack["result"]["subscription_id"].clone(); |
| 265 | assert_eq!(ack["id"], 1); |
| 266 | let event = receive(&mut client).await; |
| 267 | assert_eq!(event["params"]["subscription_id"], subscription); |
| 268 | assert_eq!(event["params"]["frame"]["sequence"], 42); |
| 269 | let end = receive(&mut client).await; |
| 270 | assert_eq!(end["params"]["frame"]["event"], "stream.end"); |
| 271 | assert!(end["params"]["frame"]["sequence"].is_null()); |
| 272 | for id in [2, 3] { |
| 273 | client |
| 274 | .send( |
| 275 | json!(id), |
| 276 | "runtime/events/unsubscribe", |
| 277 | json!({"subscription_id":subscription}), |
| 278 | ) |
| 279 | .await |
| 280 | .unwrap(); |
| 281 | let response = receive(&mut client).await; |
| 282 | assert_eq!(response["id"], id); |
| 283 | } |
| 284 | drop(client); |
| 285 | harness.stop().await; |
| 286 | } |
| 287 | |
| 288 | #[tokio::test] |
| 289 | async fn native_disconnect_does_not_cancel_or_replay_admitted_mutation() { |
| 290 | let harness = Harness::new().await; |
| 291 | let mut client = harness.connect().await; |
| 292 | client.send(json!(1),"runtime/turn/start",json!({"thread_id":"t","body":{"operation_key":"intent-1","prompt":"hi","allowed_tools":[]}})).await.unwrap(); |
| 293 | tokio::time::timeout(Duration::from_secs(5), harness.captured.admitted.notified()) |
| 294 | .await |
| 295 | .unwrap(); |
| 296 | drop(client); |
| 297 | harness.captured.release.add_permits(1); |
| 298 | tokio::time::timeout(Duration::from_secs(5), async { |
| 299 | while harness.captured.completed.load(Ordering::SeqCst) == 0 { |
| 300 | tokio::task::yield_now().await; |
| 301 | } |
| 302 | }) |
| 303 | .await |
| 304 | .unwrap(); |
| 305 | let fresh = harness.connect().await; |
| 306 | drop(fresh); |
| 307 | assert_eq!(harness.captured.completed.load(Ordering::SeqCst), 1); |
| 308 | harness.stop().await; |
| 309 | } |
| 310 | |
| 311 | #[tokio::test] |
| 312 | async fn native_absent_owner_prelude_never_creates_selected_store() { |
| 313 | let root = tempfile::tempdir().unwrap(); |
| 314 | let workspace = root.path().canonicalize().unwrap(); |
| 315 | let data_dir = workspace.join("absent-store"); |
| 316 | let request = json!({"jsonrpc":"2.0","id":"attach-1","method":"runtime/attach","params":{"contract_version":1,"target_id":"target-1","selection_revision":1,"workspace":workspace,"expect_owner":{"version":1,"data_dir":data_dir,"execution_scope":"absent","lease_generation":"absent","pid":1,"process_start":"absent","principal":"absent","socket_path":workspace.join("absent/daemon.sock"),"config_path":null}}}); |
| 317 | let input = format!("{request}\n"); |
| 318 | assert!( |
| 319 | codewhale_app_server::native_runtime::attach_io( |
| 320 | false, |
| 321 | tokio::io::BufReader::new(input.as_bytes()), |
| 322 | tokio::io::sink() |
| 323 | ) |
| 324 | .await |
| 325 | .is_err() |
| 326 | ); |
| 327 | assert!(!data_dir.exists()); |
| 328 | assert!(!workspace.join("absent").exists()); |
| 329 | let oversized = format!("{}\n", " ".repeat(16385)); |
| 330 | assert!( |
| 331 | codewhale_app_server::native_runtime::attach_io( |
| 332 | false, |
| 333 | tokio::io::BufReader::new(oversized.as_bytes()), |
| 334 | tokio::io::sink() |
| 335 | ) |
| 336 | .await |
| 337 | .is_err() |
| 338 | ); |
| 339 | } |
| 340 | |
| 341 | #[tokio::test] |
| 342 | async fn native_sixty_fifth_request_is_refused_before_owner_execution() { |
| 343 | let harness = Harness::new().await; |
| 344 | let mut client = harness.connect().await; |
| 345 | for id in 1..=65 { |
| 346 | client.send(json!(id),"runtime/turn/start",json!({"thread_id":"t","body":{"operation_key":format!("intent-{id}"),"prompt":"hi","allowed_tools":[]}})).await.unwrap(); |
| 347 | } |
| 348 | let busy = receive(&mut client).await; |
| 349 | assert_eq!(busy["id"], 65); |
| 350 | assert_eq!(busy["error"]["data"]["code"], "busy"); |
| 351 | assert_eq!(busy["error"]["data"]["outcome"], "not_started"); |
| 352 | tokio::time::timeout(Duration::from_secs(5), async { |
| 353 | while harness.captured.calls.load(Ordering::SeqCst) < 65 { |
| 354 | tokio::task::yield_now().await; |
| 355 | } |
| 356 | }) |
| 357 | .await |
| 358 | .unwrap(); |
| 359 | assert_eq!(harness.captured.calls.load(Ordering::SeqCst), 65); |
| 360 | drop(client); |
| 361 | harness.captured.release.add_permits(64); |
| 362 | tokio::time::timeout(Duration::from_secs(5), async { |
| 363 | while harness.captured.completed.load(Ordering::SeqCst) < 64 { |
| 364 | tokio::task::yield_now().await; |
| 365 | } |
| 366 | }) |
| 367 | .await |
| 368 | .unwrap(); |
| 369 | assert_eq!(harness.captured.completed.load(Ordering::SeqCst), 64); |
| 370 | harness.stop().await; |
| 371 | } |
| 372 |