| 1 | use super::*; |
| 2 | use codewhale_config::user_constitution::{ProfileConstitution, ProfileConstitutionSnapshot}; |
| 3 | |
| 4 | #[tokio::test] |
| 5 | async fn profile_constitution_reaches_real_engine_requests_and_survives_history_repair() { |
| 6 | use crate::llm_client::mock::{MockLlmClient, canned}; |
| 7 | let _home = crate::test_support::SealedHome::new(); |
| 8 | let workspace = tempfile::tempdir().unwrap(); |
| 9 | let config = Config::default(); |
| 10 | let mock = Arc::new(MockLlmClient::new(vec![ |
| 11 | canned::simple_text_turn("Done"), |
| 12 | canned::simple_text_turn("Done again"), |
| 13 | canned::simple_text_turn("Follow-up done"), |
| 14 | ])); |
| 15 | let (mut engine, handle) = Engine::new_with_model_client( |
| 16 | deterministic_engine_config(workspace.path()), |
| 17 | &config, |
| 18 | mock.clone(), |
| 19 | ); |
| 20 | let drainer = |
| 21 | tokio::spawn(async move { while handle.rx_event.write().await.recv().await.is_some() {} }); |
| 22 | for (revision, note) in [ |
| 23 | (1, "Profile alpha preference"), |
| 24 | (2, "Profile beta preference"), |
| 25 | ] { |
| 26 | let Op::SendMessage(mut spec) = |
| 27 | external_user_message_op("Say hello", AppMode::Agent, &config) |
| 28 | else { |
| 29 | unreachable!() |
| 30 | }; |
| 31 | spec.profile_constitution = Some(ProfileConstitutionSnapshot { |
| 32 | account_id: "acct_fixture".into(), |
| 33 | revision, |
| 34 | constitution: ProfileConstitution { |
| 35 | notes: note.into(), |
| 36 | ..ProfileConstitution::default() |
| 37 | }, |
| 38 | }); |
| 39 | let outcome = engine.handle_send_message(spec).await; |
| 40 | assert!(!matches!(outcome, SendMessageOutcome::NotStarted { .. })); |
| 41 | let requests = mock.captured_requests(); |
| 42 | let request = serde_json::to_string(requests.last().unwrap()).unwrap(); |
| 43 | assert!(request.contains(note)); |
| 44 | assert!(request.contains("replaces all earlier personal constitution snapshots")); |
| 45 | assert!(request.contains("do not change permissions")); |
| 46 | } |
| 47 | let latest = engine |
| 48 | .session |
| 49 | .messages |
| 50 | .iter() |
| 51 | .rev() |
| 52 | .find(|message| crate::runtime_handoff::constitution_display(message).is_some()) |
| 53 | .unwrap() |
| 54 | .clone(); |
| 55 | assert!( |
| 56 | crate::runtime_handoff::constitution_display(&latest) |
| 57 | .unwrap() |
| 58 | .contains("revision 2") |
| 59 | ); |
| 60 | let Op::SendMessage(mut continuation) = |
| 61 | external_user_message_op("A background task finished", AppMode::Agent, &config) |
| 62 | else { |
| 63 | unreachable!() |
| 64 | }; |
| 65 | continuation.provenance = UserInputProvenance::Runtime; |
| 66 | // A host can admit a runtime follow-up itself, so this must not depend on |
| 67 | // the Engine's autonomous scheduling flag. |
| 68 | let outcome = engine.handle_admitted_message(continuation, false).await; |
| 69 | assert!(!matches!(outcome, SendMessageOutcome::NotStarted { .. })); |
| 70 | assert!( |
| 71 | serde_json::to_string(mock.captured_requests().last().unwrap()) |
| 72 | .unwrap() |
| 73 | .contains("Profile beta preference") |
| 74 | ); |
| 75 | assert_eq!( |
| 76 | engine |
| 77 | .session |
| 78 | .messages |
| 79 | .iter() |
| 80 | .rev() |
| 81 | .find(|message| crate::runtime_handoff::constitution_display(message).is_some()), |
| 82 | Some(&latest) |
| 83 | ); |
| 84 | engine.session.messages.clear(); |
| 85 | engine.record_current_constitution().await; |
| 86 | assert_eq!(engine.session.messages.last(), Some(&latest)); |
| 87 | let count = engine.session.messages.len(); |
| 88 | engine.record_current_constitution().await; |
| 89 | assert_eq!(engine.session.messages.len(), count); |
| 90 | engine.constitution_block = None; |
| 91 | engine.record_current_constitution().await; |
| 92 | assert!( |
| 93 | crate::runtime_handoff::constitution_display(engine.session.messages.last().unwrap()) |
| 94 | .unwrap() |
| 95 | .contains("withdrawn") |
| 96 | ); |
| 97 | engine.session.messages.clear(); |
| 98 | engine.record_current_constitution().await; |
| 99 | assert!( |
| 100 | engine.session.messages.is_empty(), |
| 101 | "a withdrawal with no earlier snapshot is a no-op" |
| 102 | ); |
| 103 | drainer.abort(); |
| 104 | } |
| 105 | |
| 106 | const END_OF_EVENTS: &str = "profile constitution test: end of events"; |
| 107 | |
| 108 | /// Every event delivered before the `END_OF_EVENTS` status, in order. The |
| 109 | /// sentinel keeps the receiver drained during a turn without racing the turn. |
| 110 | fn collect_timed_events( |
| 111 | handle: EngineHandle, |
| 112 | ) -> tokio::sync::oneshot::Receiver<Vec<(std::time::Instant, Event)>> { |
| 113 | let (sender, receiver) = tokio::sync::oneshot::channel(); |
| 114 | std::thread::spawn(move || { |
| 115 | let runtime = tokio::runtime::Builder::new_current_thread() |
| 116 | .build() |
| 117 | .unwrap(); |
| 118 | let _ = sender.send(runtime.block_on(async move { |
| 119 | let mut events = Vec::new(); |
| 120 | let mut receiver = handle.rx_event.write().await; |
| 121 | while let Some(event) = receiver.recv().await { |
| 122 | if matches!(&event, Event::Status { message } if message == END_OF_EVENTS) { |
| 123 | break; |
| 124 | } |
| 125 | events.push((std::time::Instant::now(), event)); |
| 126 | } |
| 127 | events |
| 128 | })); |
| 129 | }); |
| 130 | receiver |
| 131 | } |
| 132 | |
| 133 | fn collect_events(handle: EngineHandle) -> tokio::task::JoinHandle<Vec<Event>> { |
| 134 | let timed = collect_timed_events(handle); |
| 135 | tokio::spawn(async move { |
| 136 | timed |
| 137 | .await |
| 138 | .unwrap() |
| 139 | .into_iter() |
| 140 | .map(|(_, event)| event) |
| 141 | .collect() |
| 142 | }) |
| 143 | } |
| 144 | |
| 145 | fn fallback_notice(engine: &Engine) -> String { |
| 146 | codewhale_localization::tr( |
| 147 | codewhale_localization::resolve_locale(&engine.config.locale_tag), |
| 148 | codewhale_localization::MessageId::ProfileConstitutionUnavailableLocal, |
| 149 | ) |
| 150 | .to_string() |
| 151 | } |
| 152 | |
| 153 | fn save_local_constitution() { |
| 154 | codewhale_config::UserConstitution { |
| 155 | about: Some("Local fallback preference.".to_string()), |
| 156 | ..Default::default() |
| 157 | } |
| 158 | .save() |
| 159 | .unwrap(); |
| 160 | } |
| 161 | |
| 162 | #[tokio::test] |
| 163 | async fn engine_loaded_profile_failure_uses_the_local_constitution_and_says_so_once() { |
| 164 | use crate::llm_client::mock::{MockLlmClient, canned}; |
| 165 | let _home = crate::test_support::SealedHome::new(); |
| 166 | save_local_constitution(); |
| 167 | let workspace = tempfile::tempdir().unwrap(); |
| 168 | let config = Config::default(); |
| 169 | let mock = Arc::new(MockLlmClient::new(vec![ |
| 170 | canned::simple_text_turn("Done"), |
| 171 | canned::simple_text_turn("Done again"), |
| 172 | ])); |
| 173 | let (mut engine, handle) = Engine::new_with_model_client( |
| 174 | deterministic_engine_config(workspace.path()), |
| 175 | &config, |
| 176 | mock.clone(), |
| 177 | ); |
| 178 | let events = collect_events(handle); |
| 179 | let _unavailable = crate::profile_constitution::fail_account_load_for_test( |
| 180 | "Your profile could not be loaded (HTTP 401). Sign in again or retry", |
| 181 | ); |
| 182 | for _ in 0..2 { |
| 183 | let Op::SendMessage(spec) = external_user_message_op("Say hello", AppMode::Agent, &config) |
| 184 | else { |
| 185 | unreachable!() |
| 186 | }; |
| 187 | let outcome = engine.handle_send_message(spec).await; |
| 188 | assert!(!matches!(outcome, SendMessageOutcome::NotStarted { .. })); |
| 189 | let requests = mock.captured_requests(); |
| 190 | let request = serde_json::to_string(requests.last().unwrap()).unwrap(); |
| 191 | assert!(request.contains("Local fallback preference.")); |
| 192 | assert!(!request.contains("Account profile constitution,")); |
| 193 | assert!( |
| 194 | engine |
| 195 | .constitution_block |
| 196 | .as_deref() |
| 197 | .is_some_and(|block| block.contains("Local fallback preference.")) |
| 198 | ); |
| 199 | } |
| 200 | assert!(engine.profile_constitution_fallback_noticed); |
| 201 | let notice = fallback_notice(&engine); |
| 202 | engine |
| 203 | .send_event(Event::status(END_OF_EVENTS)) |
| 204 | .await |
| 205 | .unwrap(); |
| 206 | let events = events.await.unwrap(); |
| 207 | assert_eq!( |
| 208 | events |
| 209 | .iter() |
| 210 | .filter(|event| matches!(event, Event::Status { message } if *message == notice)) |
| 211 | .count(), |
| 212 | 1, |
| 213 | "the fallback is announced once per engine, not once per turn" |
| 214 | ); |
| 215 | assert!( |
| 216 | !events |
| 217 | .iter() |
| 218 | .any(|event| matches!(event, Event::Error { envelope, .. } |
| 219 | if envelope.code == "profile_constitution_unavailable")) |
| 220 | ); |
| 221 | } |
| 222 | |
| 223 | #[tokio::test] |
| 224 | async fn host_supplied_invalid_profile_refuses_the_turn_without_a_local_fallback() { |
| 225 | use crate::llm_client::mock::{MockLlmClient, canned}; |
| 226 | let _home = crate::test_support::SealedHome::new(); |
| 227 | save_local_constitution(); |
| 228 | let workspace = tempfile::tempdir().unwrap(); |
| 229 | let config = Config::default(); |
| 230 | let mock = Arc::new(MockLlmClient::new(vec![canned::simple_text_turn( |
| 231 | "must not run", |
| 232 | )])); |
| 233 | let (mut engine, handle) = Engine::new_with_model_client( |
| 234 | deterministic_engine_config(workspace.path()), |
| 235 | &config, |
| 236 | mock.clone(), |
| 237 | ); |
| 238 | let events = collect_events(handle); |
| 239 | // An unavailable account service must not turn a host's own snapshot into |
| 240 | // a local-fallback turn either. |
| 241 | let _unavailable = |
| 242 | crate::profile_constitution::fail_account_load_for_test("account service unreachable"); |
| 243 | let Op::SendMessage(mut spec) = external_user_message_op("Say hello", AppMode::Agent, &config) |
| 244 | else { |
| 245 | unreachable!() |
| 246 | }; |
| 247 | spec.profile_constitution = Some(ProfileConstitutionSnapshot { |
| 248 | account_id: "acct_fixture".into(), |
| 249 | revision: 1, |
| 250 | constitution: ProfileConstitution { |
| 251 | notes: "x".repeat(codewhale_config::user_constitution::MAX_NOTES_LEN + 1), |
| 252 | ..ProfileConstitution::default() |
| 253 | }, |
| 254 | }); |
| 255 | let outcome = engine.handle_send_message(spec).await; |
| 256 | let SendMessageOutcome::NotStarted { error: Some(error) } = outcome else { |
| 257 | panic!("an invalid host-supplied profile must refuse its turn"); |
| 258 | }; |
| 259 | assert!(error.contains("Constitution notes cannot exceed")); |
| 260 | assert_eq!(mock.call_count(), 0); |
| 261 | assert!(!engine.profile_constitution_fallback_noticed); |
| 262 | assert!(engine.constitution_block.is_none()); |
| 263 | let notice = fallback_notice(&engine); |
| 264 | engine |
| 265 | .send_event(Event::status(END_OF_EVENTS)) |
| 266 | .await |
| 267 | .unwrap(); |
| 268 | let events = events.await.unwrap(); |
| 269 | assert_eq!( |
| 270 | events |
| 271 | .iter() |
| 272 | .filter(|event| matches!(event, Event::Error { envelope, .. } |
| 273 | if envelope.code == "profile_constitution_unavailable")) |
| 274 | .count(), |
| 275 | 1 |
| 276 | ); |
| 277 | assert!(!events.iter().any(|event| matches!( |
| 278 | event, |
| 279 | Event::TurnStarted { .. } | Event::TurnComplete { .. } |
| 280 | ))); |
| 281 | assert!( |
| 282 | !events |
| 283 | .iter() |
| 284 | .any(|event| matches!(event, Event::Status { message } if *message == notice)) |
| 285 | ); |
| 286 | } |
| 287 | |
| 288 | fn account_me(notes: &str) -> serde_json::Value { |
| 289 | serde_json::json!({"user":{"id":"acct_fixture","settingsRevision":7, |
| 290 | "preferences":{"constitution":ProfileConstitution { notes: notes.into(), ..Default::default() }}}}) |
| 291 | } |
| 292 | |
| 293 | async fn slow_account_service(reads: &[(&str, Duration)]) -> wiremock::MockServer { |
| 294 | use wiremock::{ |
| 295 | Mock, MockServer, ResponseTemplate, |
| 296 | matchers::{method, path}, |
| 297 | }; |
| 298 | let server = MockServer::start().await; |
| 299 | for (index, (note, delay)) in reads.iter().enumerate() { |
| 300 | let read = Mock::given(method("GET")) |
| 301 | .and(path("/api/me")) |
| 302 | .respond_with( |
| 303 | ResponseTemplate::new(200) |
| 304 | .set_body_json(account_me(note)) |
| 305 | .set_delay(*delay), |
| 306 | ); |
| 307 | let read = if index + 1 < reads.len() { |
| 308 | read.up_to_n_times(1) |
| 309 | } else { |
| 310 | read |
| 311 | }; |
| 312 | read.mount(&server).await; |
| 313 | } |
| 314 | server |
| 315 | } |
| 316 | |
| 317 | async fn account_requests(server: &wiremock::MockServer) -> usize { |
| 318 | server |
| 319 | .received_requests() |
| 320 | .await |
| 321 | .map_or(0, |requests| requests.len()) |
| 322 | } |
| 323 | |
| 324 | async fn prompt_turn( |
| 325 | engine: &mut Engine, |
| 326 | config: &Config, |
| 327 | mock: &crate::llm_client::mock::MockLlmClient, |
| 328 | ) -> (std::time::Instant, String) { |
| 329 | let Op::SendMessage(spec) = external_user_message_op("Say hello", AppMode::Agent, config) |
| 330 | else { |
| 331 | unreachable!() |
| 332 | }; |
| 333 | let started = std::time::Instant::now(); |
| 334 | let outcome = engine.handle_send_message(spec).await; |
| 335 | assert!(!matches!(outcome, SendMessageOutcome::NotStarted { .. })); |
| 336 | ( |
| 337 | started, |
| 338 | serde_json::to_string(mock.captured_requests().last().unwrap()).unwrap(), |
| 339 | ) |
| 340 | } |
| 341 | |
| 342 | #[tokio::test] |
| 343 | async fn slow_account_service_does_not_delay_the_turn_and_its_read_is_used_next_turn() { |
| 344 | use crate::llm_client::mock::{MockLlmClient, canned}; |
| 345 | let _home = crate::test_support::SealedHome::new(); |
| 346 | save_local_constitution(); |
| 347 | let read = Duration::from_secs(3); |
| 348 | let first_read = "Account profile preference."; |
| 349 | let fresh_read = "Account profile preference, read during the second turn."; |
| 350 | let server = |
| 351 | slow_account_service(&[(first_read, read), (fresh_read, Duration::from_secs(4))]).await; |
| 352 | let _account = crate::profile_constitution::serve_account_for_test( |
| 353 | crate::profile_constitution::fixture_account_store(&server.uri()), |
| 354 | server.uri(), |
| 355 | crate::profile_constitution::TURN_WAIT, |
| 356 | ); |
| 357 | let workspace = tempfile::tempdir().unwrap(); |
| 358 | let config = Config::default(); |
| 359 | let mock = Arc::new(MockLlmClient::new(vec![ |
| 360 | canned::simple_text_turn("Done"), |
| 361 | canned::simple_text_turn("Done again"), |
| 362 | ])); |
| 363 | let (mut engine, handle) = Engine::new_with_model_client( |
| 364 | deterministic_engine_config(workspace.path()), |
| 365 | &config, |
| 366 | mock.clone(), |
| 367 | ); |
| 368 | let events = collect_timed_events(handle); |
| 369 | let (first_started, first) = prompt_turn(&mut engine, &config, &mock).await; |
| 370 | assert!(first.contains("Local fallback preference.")); |
| 371 | assert!(!first.contains("Account profile preference")); |
| 372 | let deadline = std::time::Instant::now() + Duration::from_secs(30); |
| 373 | while engine.account_constitution.read_in_flight() { |
| 374 | assert!( |
| 375 | std::time::Instant::now() < deadline, |
| 376 | "the account read never finished" |
| 377 | ); |
| 378 | tokio::time::sleep(Duration::from_millis(20)).await; |
| 379 | } |
| 380 | let (_, second) = prompt_turn(&mut engine, &config, &mock).await; |
| 381 | assert!( |
| 382 | second.contains(first_read), |
| 383 | "the finished read reaches the next turn" |
| 384 | ); |
| 385 | assert!( |
| 386 | !second.contains(fresh_read), |
| 387 | "the second turn waited for its own account read" |
| 388 | ); |
| 389 | assert!(account_requests(&server).await >= 2); |
| 390 | let loading = codewhale_localization::tr( |
| 391 | codewhale_localization::resolve_locale(&engine.config.locale_tag), |
| 392 | codewhale_localization::MessageId::ProfileConstitutionLoadingLocal, |
| 393 | ) |
| 394 | .to_string(); |
| 395 | let unavailable = fallback_notice(&engine); |
| 396 | engine |
| 397 | .send_event(Event::status(END_OF_EVENTS)) |
| 398 | .await |
| 399 | .unwrap(); |
| 400 | let events = events.await.unwrap(); |
| 401 | let count = |wanted: &str| { |
| 402 | events |
| 403 | .iter() |
| 404 | .filter(|(_, event)| matches!(event, Event::Status { message } if message == wanted)) |
| 405 | .count() |
| 406 | }; |
| 407 | assert_eq!( |
| 408 | count(&loading), |
| 409 | 1, |
| 410 | "the person is told once that the account read is late" |
| 411 | ); |
| 412 | let waited = events |
| 413 | .iter() |
| 414 | .find_map(|(at, event)| { |
| 415 | matches!(event, Event::Status { message } if *message == loading).then_some(*at) |
| 416 | }) |
| 417 | .unwrap() |
| 418 | .duration_since(first_started); |
| 419 | assert!( |
| 420 | waited < crate::profile_constitution::TURN_WAIT + Duration::from_secs(1), |
| 421 | "the turn waited {waited:?} on a {read:?} account read" |
| 422 | ); |
| 423 | assert_eq!(count(&unavailable), 0); |
| 424 | assert_eq!( |
| 425 | events |
| 426 | .iter() |
| 427 | .filter(|(_, event)| matches!(event, Event::TurnStarted { .. })) |
| 428 | .count(), |
| 429 | 2 |
| 430 | ); |
| 431 | } |
| 432 | |
| 433 | #[tokio::test] |
| 434 | async fn stop_ends_a_slow_account_read_at_once_for_interactive_and_hosted_turns() { |
| 435 | use crate::llm_client::mock::{MockLlmClient, canned}; |
| 436 | let _home = crate::test_support::SealedHome::new(); |
| 437 | let server = |
| 438 | slow_account_service(&[("Account profile preference.", Duration::from_secs(30))]).await; |
| 439 | let _account = crate::profile_constitution::serve_account_for_test( |
| 440 | crate::profile_constitution::fixture_account_store(&server.uri()), |
| 441 | server.uri(), |
| 442 | Duration::from_secs(60), |
| 443 | ); |
| 444 | let workspace = tempfile::tempdir().unwrap(); |
| 445 | let config = Config::default(); |
| 446 | let hosted = EngineConfig { |
| 447 | runtime_services: crate::tools::spec::RuntimeToolServices { |
| 448 | active_thread_id: Some("thr_host_managed".to_string()), |
| 449 | ..crate::tools::spec::RuntimeToolServices::default() |
| 450 | }, |
| 451 | ..deterministic_engine_config(workspace.path()) |
| 452 | }; |
| 453 | for (engine_config, host_managed) in [ |
| 454 | (deterministic_engine_config(workspace.path()), false), |
| 455 | (hosted, true), |
| 456 | ] { |
| 457 | let mock = Arc::new(MockLlmClient::new(vec![canned::simple_text_turn( |
| 458 | "must not run", |
| 459 | )])); |
| 460 | let (mut engine, handle) = |
| 461 | Engine::new_with_model_client(engine_config, &config, mock.clone()); |
| 462 | assert_eq!(engine.host_managed_turns(), host_managed); |
| 463 | let stopper = handle.clone(); |
| 464 | let events = collect_timed_events(handle); |
| 465 | let Op::SendMessage(spec) = external_user_message_op("Say hello", AppMode::Agent, &config) |
| 466 | else { |
| 467 | unreachable!() |
| 468 | }; |
| 469 | let seen = account_requests(&server).await; |
| 470 | let ((outcome, ended), stopped) = tokio::join!( |
| 471 | async { |
| 472 | let outcome = engine.handle_send_message(spec).await; |
| 473 | (outcome, std::time::Instant::now()) |
| 474 | }, |
| 475 | async { |
| 476 | while account_requests(&server).await == seen { |
| 477 | tokio::time::sleep(Duration::from_millis(5)).await; |
| 478 | } |
| 479 | let stopped = std::time::Instant::now(); |
| 480 | stopper.cancel(); |
| 481 | stopped |
| 482 | } |
| 483 | ); |
| 484 | let after_stop = ended.checked_duration_since(stopped).unwrap(); |
| 485 | assert!( |
| 486 | after_stop < Duration::from_secs(1), |
| 487 | "Stop took {after_stop:?} while the account read was pending" |
| 488 | ); |
| 489 | assert_eq!(mock.call_count(), 0); |
| 490 | let input_recorded = engine.session.messages.iter().any(|message| { |
| 491 | message.role == Role::User |
| 492 | && message.content.iter().any( |
| 493 | |block| matches!(block, ContentBlock::Text { text, .. } if text == "Say hello"), |
| 494 | ) |
| 495 | }); |
| 496 | assert_eq!(input_recorded, host_managed); |
| 497 | engine |
| 498 | .send_event(Event::status(END_OF_EVENTS)) |
| 499 | .await |
| 500 | .unwrap(); |
| 501 | let lifecycle: Vec<_> = events |
| 502 | .await |
| 503 | .unwrap() |
| 504 | .into_iter() |
| 505 | .filter_map(|(received, event)| match event { |
| 506 | Event::TurnStarted { .. } => Some(None), |
| 507 | Event::TurnComplete { |
| 508 | status, |
| 509 | tool_catalog, |
| 510 | .. |
| 511 | } => { |
| 512 | let delivered = received.checked_duration_since(stopped).unwrap(); |
| 513 | assert!( |
| 514 | delivered < Duration::from_secs(1), |
| 515 | "hosted Stop took {delivered:?} to deliver TurnComplete" |
| 516 | ); |
| 517 | assert!(tool_catalog.is_none()); |
| 518 | Some(Some(status)) |
| 519 | } |
| 520 | _ => None, |
| 521 | }) |
| 522 | .collect(); |
| 523 | if host_managed { |
| 524 | assert_eq!(lifecycle, [None, Some(TurnOutcomeStatus::Interrupted)]); |
| 525 | } else { |
| 526 | assert!(matches!(outcome, SendMessageOutcome::NotStarted { .. })); |
| 527 | assert!(lifecycle.is_empty()); |
| 528 | } |
| 529 | } |
| 530 | } |
| 531 |