| 1 | //! ACP stdio projection of the existing Runtime/Engine owner. |
| 2 | //! History, provider requests, tools, approval and cancellation are Core facts. |
| 3 | //! This module keeps only connection configuration and canonical bindings; the |
| 4 | //! official ACP SDK owns framing, request ids and correlation. Secure |
| 5 | //! cross-process attachment is not yet qualified. |
| 6 | //! |
| 7 | //! Known limits: a slow editor no longer slows a turn, because updates queue |
| 8 | //! (SDK queue, then 256 frames of up to 8 MiB each) and memory is bounded only |
| 9 | //! by what one turn emits; `$/cancel_request` for a running `session/prompt` is |
| 10 | //! not honored (only `session/cancel` is). Requested file arguments carry no |
| 11 | //! verified full preimage, so live approvals and replay omit structured diffs. |
| 12 | use agent_client_protocol::Error as SdkError; |
| 13 | use agent_client_protocol::schema::ProtocolVersion; |
| 14 | use agent_client_protocol::v1::schema as acp; |
| 15 | use anyhow::{Result, anyhow}; |
| 16 | use codewhale_config::AppMode; |
| 17 | use codewhale_config::ProviderKind; |
| 18 | use codewhale_engine::core::authority::{SandboxNetworkAccess, sandbox_policy_for_turn}; |
| 19 | #[cfg(test)] |
| 20 | use codewhale_engine::runtime_threads::manager::RuntimeThreadManagerConfig; |
| 21 | use codewhale_engine::runtime_threads::{ |
| 22 | manager::CreateThreadRequest, manager::RuntimeThreadManager, manager::UpdateThreadRequest, |
| 23 | }; |
| 24 | use codewhale_execpolicy::ApprovalMode; |
| 25 | use codewhale_runtime::config::Config; |
| 26 | use codewhale_runtime::features::Feature; |
| 27 | use serde_json::{Value, json}; |
| 28 | use std::collections::{HashMap, VecDeque}; |
| 29 | use std::path::{Path, PathBuf}; |
| 30 | use std::sync::Arc; |
| 31 | use tokio::io::{AsyncBufRead, AsyncWrite}; |
| 32 | #[cfg(test)] |
| 33 | use tokio::io::{AsyncWriteExt, BufReader}; |
| 34 | mod connection; |
| 35 | mod runtime; |
| 36 | use connection::serve_connection; |
| 37 | const MAX_ACP_SESSIONS: usize = 64; |
| 38 | const TOOL_CALL_CONTENT_PREVIEW_CHARS: usize = 4_000; |
| 39 | |
| 40 | pub async fn run_acp_server( |
| 41 | config: Config, |
| 42 | model: String, |
| 43 | default_cwd: PathBuf, |
| 44 | plugins: Arc<codewhale_plugins::PluginDiscoveryContext>, |
| 45 | config_path: Option<PathBuf>, |
| 46 | config_profile: Option<String>, |
| 47 | ) -> Result<()> { |
| 48 | ensure_acp_approval_posture(&config)?; |
| 49 | eprintln!("{}", acp_startup_posture(&config, &default_cwd)); |
| 50 | crate::runtime_api::run_http_server( |
| 51 | config, |
| 52 | default_cwd, |
| 53 | plugins, |
| 54 | crate::runtime_api::RuntimeApiOptions { |
| 55 | port: 0, |
| 56 | config_path, |
| 57 | config_profile, |
| 58 | control_frontend: Some( |
| 59 | codewhale_runtime::runtime_control::RuntimeControlFrontend::Acp { model }, |
| 60 | ), |
| 61 | ..Default::default() |
| 62 | }, |
| 63 | ) |
| 64 | .await |
| 65 | } |
| 66 | |
| 67 | pub struct CapturedAcpFrontend { |
| 68 | config: Config, |
| 69 | model: String, |
| 70 | cwd: PathBuf, |
| 71 | manager: Arc<RuntimeThreadManager>, |
| 72 | sessions_dir: PathBuf, |
| 73 | config_path: Option<PathBuf>, |
| 74 | config_profile: Option<String>, |
| 75 | } |
| 76 | pub fn capture_frontend( |
| 77 | config: Config, |
| 78 | model: String, |
| 79 | cwd: PathBuf, |
| 80 | manager: Arc<RuntimeThreadManager>, |
| 81 | sessions_dir: PathBuf, |
| 82 | config_path: Option<PathBuf>, |
| 83 | config_profile: Option<String>, |
| 84 | ) -> Result<Arc<CapturedAcpFrontend>> { |
| 85 | ensure_acp_approval_posture(&config)?; |
| 86 | Ok(Arc::new(CapturedAcpFrontend { |
| 87 | config, |
| 88 | model, |
| 89 | cwd, |
| 90 | manager, |
| 91 | sessions_dir, |
| 92 | config_path, |
| 93 | config_profile, |
| 94 | })) |
| 95 | } |
| 96 | impl CapturedAcpFrontend { |
| 97 | pub fn serve<'a>( |
| 98 | &'a self, |
| 99 | input: Box<dyn AsyncBufRead + Send + Unpin>, |
| 100 | output: Box<dyn AsyncWrite + Send + Unpin + 'a>, |
| 101 | ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>> { |
| 102 | Box::pin(async move { |
| 103 | let server = AcpServer::new( |
| 104 | self.config.clone(), |
| 105 | self.model.clone(), |
| 106 | self.cwd.clone(), |
| 107 | self.manager.clone(), |
| 108 | self.sessions_dir.clone(), |
| 109 | self.config_path.clone(), |
| 110 | self.config_profile.clone(), |
| 111 | ); |
| 112 | serve_connection(server, input, output).await.map(drop) |
| 113 | }) |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | #[cfg(test)] |
| 118 | impl crate::RuntimeOwnerFrontend for CapturedAcpFrontend { |
| 119 | fn execute( |
| 120 | &self, |
| 121 | _request: crate::RuntimeOwnerRequest, |
| 122 | ) -> std::pin::Pin< |
| 123 | Box<dyn std::future::Future<Output = anyhow::Result<serde_json::Value>> + Send + '_>, |
| 124 | > { |
| 125 | Box::pin(async { |
| 126 | anyhow::bail!("this captured frontend admits no ordinary native service") |
| 127 | }) |
| 128 | } |
| 129 | fn events( |
| 130 | &self, |
| 131 | _thread_id: String, |
| 132 | _since_seq: u64, |
| 133 | ) -> std::pin::Pin< |
| 134 | Box< |
| 135 | dyn std::future::Future<Output = anyhow::Result<crate::RuntimeOwnerEventStream>> |
| 136 | + Send |
| 137 | + '_, |
| 138 | >, |
| 139 | > { |
| 140 | Box::pin(async { |
| 141 | anyhow::bail!("this captured frontend admits no ordinary native observation") |
| 142 | }) |
| 143 | } |
| 144 | fn validate_selection<'a>( |
| 145 | &'a self, |
| 146 | selection: &'a crate::RuntimeOwnerFrontendSelection, |
| 147 | ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>> { |
| 148 | Box::pin(async move { |
| 149 | anyhow::ensure!( |
| 150 | matches!(selection, crate::RuntimeOwnerFrontendSelection::Acp { .. }), |
| 151 | "ACP fixture does not capture HTTP services" |
| 152 | ); |
| 153 | Ok(()) |
| 154 | }) |
| 155 | } |
| 156 | fn serve<'a>( |
| 157 | &'a self, |
| 158 | selection: crate::RuntimeOwnerFrontendSelection, |
| 159 | _compatibility: crate::AppState, |
| 160 | input: Box<dyn AsyncBufRead + Send + Unpin>, |
| 161 | output: Box<dyn AsyncWrite + Send + Unpin + 'a>, |
| 162 | ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>> { |
| 163 | Box::pin(async move { |
| 164 | anyhow::ensure!( |
| 165 | matches!(selection, crate::RuntimeOwnerFrontendSelection::Acp { .. }), |
| 166 | "ACP fixture does not capture HTTP services" |
| 167 | ); |
| 168 | CapturedAcpFrontend::serve(self, input, output).await |
| 169 | }) |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | struct AcpServer { |
| 174 | config: Arc<Config>, |
| 175 | model: String, |
| 176 | default_cwd: PathBuf, |
| 177 | runtime: Arc<RuntimeThreadManager>, |
| 178 | sessions_dir: PathBuf, |
| 179 | config_path: Option<PathBuf>, |
| 180 | config_profile: Option<String>, |
| 181 | sessions: HashMap<String, AcpSession>, |
| 182 | insertion_order: VecDeque<String>, |
| 183 | client_supports_terminal: bool, |
| 184 | } |
| 185 | /// A transport binding, never another conversation or executable registry. |
| 186 | struct AcpSession { |
| 187 | thread_id: String, |
| 188 | } |
| 189 | struct PendingToolCall { |
| 190 | execution_id: String, |
| 191 | name: String, |
| 192 | input: Value, |
| 193 | } |
| 194 | #[derive(Debug)] |
| 195 | struct AcpError { |
| 196 | code: i32, |
| 197 | message: String, |
| 198 | } |
| 199 | enum Outgoing { |
| 200 | Update(acp::SessionNotification), |
| 201 | Permission { |
| 202 | key: String, |
| 203 | request: acp::RequestPermissionRequest, |
| 204 | }, |
| 205 | } |
| 206 | enum Inbound { |
| 207 | Cancel { session: String }, |
| 208 | Permission { key: String, allow: bool }, |
| 209 | Eof, |
| 210 | } |
| 211 | type Emit<'a> = &'a mut (dyn FnMut(Outgoing) -> Result<()> + Send); |
| 212 | struct SessionViewContext { |
| 213 | config: Arc<Config>, |
| 214 | runtime: Arc<RuntimeThreadManager>, |
| 215 | thread_id: String, |
| 216 | } |
| 217 | |
| 218 | struct NewSessionContext { |
| 219 | config: Arc<Config>, |
| 220 | model: String, |
| 221 | default_cwd: PathBuf, |
| 222 | runtime: Arc<RuntimeThreadManager>, |
| 223 | sessions_dir: PathBuf, |
| 224 | config_path: Option<PathBuf>, |
| 225 | config_profile: Option<String>, |
| 226 | shell_allowed: bool, |
| 227 | } |
| 228 | |
| 229 | struct LoadSessionContext { |
| 230 | config: Arc<Config>, |
| 231 | runtime: Arc<RuntimeThreadManager>, |
| 232 | sessions_dir: PathBuf, |
| 233 | config_path: Option<PathBuf>, |
| 234 | config_profile: Option<String>, |
| 235 | shell_allowed: bool, |
| 236 | } |
| 237 | |
| 238 | struct SetSessionConfigContext { |
| 239 | view: SessionViewContext, |
| 240 | config_path: Option<PathBuf>, |
| 241 | config_profile: Option<String>, |
| 242 | shell_allowed: bool, |
| 243 | } |
| 244 | |
| 245 | async fn spawn_blocking_io<T, F>(f: F) -> std::result::Result<T, tokio::task::JoinError> |
| 246 | where |
| 247 | T: Send + 'static, |
| 248 | F: FnOnce() -> T + Send + 'static, |
| 249 | { |
| 250 | #[cfg(any(test, feature = "test-support"))] |
| 251 | let env_ticket = codewhale_engine::test_support::env_scope_ticket(); |
| 252 | tokio::task::spawn_blocking(move || { |
| 253 | #[cfg(any(test, feature = "test-support"))] |
| 254 | let _membership = codewhale_engine::test_support::join_env_scope(env_ticket); |
| 255 | f() |
| 256 | }) |
| 257 | .await |
| 258 | } |
| 259 | |
| 260 | async fn create_new_session( |
| 261 | ctx: NewSessionContext, |
| 262 | params: Value, |
| 263 | ) -> std::result::Result<(String, String), AcpError> { |
| 264 | validate_mcp_servers(¶ms)?; |
| 265 | let cwd = absolute_cwd(¶ms, "session/new")?.unwrap_or(ctx.default_cwd); |
| 266 | let identity = ctx |
| 267 | .config |
| 268 | .active_provider_identity() |
| 269 | .map_err(|error| AcpError::internal(error.to_string()))?; |
| 270 | let thread = Box::pin( |
| 271 | ctx.runtime.create_thread_with_shell_policy( |
| 272 | CreateThreadRequest { |
| 273 | model: Some(ctx.model), |
| 274 | model_provider: Some(identity.persisted_kind().to_string()), |
| 275 | model_provider_id: identity.persisted_id().map(str::to_string), |
| 276 | workspace: Some(cwd), |
| 277 | mode: Some( |
| 278 | if acp_mode(&ctx.config) == AppMode::Plan { |
| 279 | "plan" |
| 280 | } else { |
| 281 | "agent" |
| 282 | } |
| 283 | .to_string(), |
| 284 | ), |
| 285 | permission_posture: Some(acp_permission_value(&ctx.config).to_string()), |
| 286 | allow_shell: Some(ctx.shell_allowed), |
| 287 | ..Default::default() |
| 288 | }, |
| 289 | ctx.config_path.as_deref(), |
| 290 | ctx.config_profile.as_deref(), |
| 291 | ), |
| 292 | ) |
| 293 | .await |
| 294 | .map_err(|error| AcpError::internal(error.to_string()))?; |
| 295 | let id = uuid::Uuid::new_v4().to_string(); |
| 296 | Box::pin(crate::runtime_api::sessions::initialize_empty_session( |
| 297 | &ctx.runtime, |
| 298 | &ctx.sessions_dir, |
| 299 | &thread.id, |
| 300 | &id, |
| 301 | )) |
| 302 | .await |
| 303 | .map_err(|error| AcpError::internal(error.message))?; |
| 304 | Ok((id, thread.id)) |
| 305 | } |
| 306 | |
| 307 | async fn list_sessions_from_dir( |
| 308 | sessions_dir: PathBuf, |
| 309 | params: Value, |
| 310 | ) -> std::result::Result<Value, AcpError> { |
| 311 | let cwd = match params.get("cwd") { |
| 312 | None | Some(Value::Null) => None, |
| 313 | Some(Value::String(path)) if std::path::Path::new(path).is_absolute() => { |
| 314 | Some(PathBuf::from(path)) |
| 315 | } |
| 316 | Some(_) => { |
| 317 | return Err(AcpError::invalid_params( |
| 318 | "session/list cwd must be an absolute path", |
| 319 | )); |
| 320 | } |
| 321 | }; |
| 322 | let sessions = spawn_blocking_io(move || { |
| 323 | codewhale_engine::session_manager::SessionManager::new(sessions_dir) |
| 324 | .ok() |
| 325 | .map(|manager| manager.list_sessions_lenient()) |
| 326 | .unwrap_or_default() |
| 327 | }) |
| 328 | .await |
| 329 | .map_err(|error| AcpError::internal(format!("list sessions task failed: {error}")))?; |
| 330 | let sessions: Vec<acp::SessionInfo> = sessions |
| 331 | .into_iter() |
| 332 | .filter(|meta| { |
| 333 | cwd.as_ref().is_none_or(|cwd| { |
| 334 | codewhale_engine::session_manager::paths_equivalent(&meta.workspace, cwd) |
| 335 | }) |
| 336 | }) |
| 337 | .map(|meta| { |
| 338 | acp::SessionInfo::new( |
| 339 | meta.id, |
| 340 | PathBuf::from(meta.workspace.to_string_lossy().into_owned()), |
| 341 | ) |
| 342 | .title(meta.title) |
| 343 | .updated_at(meta.updated_at.to_rfc3339()) |
| 344 | .meta(codewhale_meta(json!({ |
| 345 | "createdAt": meta.created_at.to_rfc3339(), |
| 346 | "messageCount": meta.message_count, |
| 347 | }))) |
| 348 | }) |
| 349 | .collect(); |
| 350 | to_wire(&acp::ListSessionsResponse::new(sessions)) |
| 351 | } |
| 352 | |
| 353 | async fn resolve_saved_session_id( |
| 354 | sessions_dir: PathBuf, |
| 355 | requested: String, |
| 356 | ) -> std::result::Result<String, AcpError> { |
| 357 | spawn_blocking_io(move || { |
| 358 | let store = codewhale_engine::session_manager::SessionManager::new(sessions_dir) |
| 359 | .map_err(|error| AcpError::internal(error.to_string()))?; |
| 360 | store |
| 361 | .resume_session_by_prefix(&requested) |
| 362 | .map(|resumed| resumed.session.metadata.id) |
| 363 | .map_err(|error| { |
| 364 | AcpError::invalid_params(format!("could not load session {requested}: {error}")) |
| 365 | }) |
| 366 | }) |
| 367 | .await |
| 368 | .map_err(|error| AcpError::internal(format!("load session task failed: {error}")))? |
| 369 | } |
| 370 | |
| 371 | async fn resume_and_configure_loaded_session( |
| 372 | ctx: &LoadSessionContext, |
| 373 | id: &str, |
| 374 | ) -> std::result::Result<String, AcpError> { |
| 375 | let (_, axum::Json(resumed)) = |
| 376 | Box::pin(crate::runtime_api::sessions::resume_session_in_runtime( |
| 377 | &ctx.runtime, |
| 378 | &ctx.sessions_dir, |
| 379 | id, |
| 380 | crate::runtime_api::sessions::ResumeSessionRequest { |
| 381 | model: None, |
| 382 | mode: (acp_mode(&ctx.config) == AppMode::Plan).then(|| "plan".to_string()), |
| 383 | }, |
| 384 | (ctx.config_path.as_deref(), ctx.config_profile.as_deref()), |
| 385 | Some(ctx.shell_allowed), |
| 386 | )) |
| 387 | .await |
| 388 | .map_err(|error| AcpError::internal(error.message))?; |
| 389 | // A saved posture cannot widen the server, and connection terminal |
| 390 | // negotiation only narrows the canonical thread's shell ceiling. |
| 391 | Box::pin(ctx.runtime.update_thread_with_shell_policy( |
| 392 | &resumed.thread_id, |
| 393 | UpdateThreadRequest { |
| 394 | permission_posture: Some(acp_permission_value(&ctx.config).to_string()), |
| 395 | allow_shell: Some(ctx.shell_allowed), |
| 396 | ..Default::default() |
| 397 | }, |
| 398 | ctx.config_path.as_deref(), |
| 399 | ctx.config_profile.as_deref(), |
| 400 | )) |
| 401 | .await |
| 402 | .map_err(|error| AcpError::internal(error.to_string()))?; |
| 403 | Ok(resumed.thread_id) |
| 404 | } |
| 405 | |
| 406 | async fn history_updates_for( |
| 407 | sessions_dir: PathBuf, |
| 408 | config: Arc<Config>, |
| 409 | session_id: String, |
| 410 | ) -> Result<Vec<acp::SessionUpdate>> { |
| 411 | use codewhale_models::ContentBlock; |
| 412 | let saved = spawn_blocking_io(move || { |
| 413 | codewhale_engine::session_manager::SessionManager::new(sessions_dir)? |
| 414 | .load_session(&session_id) |
| 415 | }) |
| 416 | .await |
| 417 | .map_err(|error| anyhow!("load session history task failed: {error}"))??; |
| 418 | let secrets = Box::pin( |
| 419 | codewhale_engine::runtime_threads::manager::receipt_secret_values((*config).clone()), |
| 420 | ) |
| 421 | .await?; |
| 422 | let mut calls = HashMap::new(); |
| 423 | let mut updates = Vec::new(); |
| 424 | for message in &saved.messages { |
| 425 | let chunk: Option<fn(acp::ContentChunk) -> acp::SessionUpdate> = match message.role.as_str() |
| 426 | { |
| 427 | "user" => Some(acp::SessionUpdate::UserMessageChunk), |
| 428 | "assistant" => Some(acp::SessionUpdate::AgentMessageChunk), |
| 429 | _ => None, |
| 430 | }; |
| 431 | if let Some(chunk) = chunk |
| 432 | && !codewhale_engine::runtime_handoff::is_internal_runtime_handoff(message) |
| 433 | && codewhale_models::turn_classify::restored_subagent_checkpoint_display(message) |
| 434 | .is_none() |
| 435 | { |
| 436 | let mut chunks = Vec::<String>::new(); |
| 437 | let mut coalesce = false; |
| 438 | for (index, block) in message.content.iter().enumerate() { |
| 439 | match block { |
| 440 | ContentBlock::Text { text, .. } => { |
| 441 | if codewhale_engine::runtime_handoff::is_turn_metadata_block( |
| 442 | message, index, text, |
| 443 | ) { |
| 444 | continue; |
| 445 | } |
| 446 | if text.starts_with("[tool_history_repair]") |
| 447 | || (message.role == "assistant" |
| 448 | && codewhale_engine::runtime_handoff::archived_context_parts(text) |
| 449 | .is_some()) |
| 450 | { |
| 451 | coalesce = false; |
| 452 | continue; |
| 453 | } |
| 454 | if coalesce { |
| 455 | if let Some(chunk) = chunks.last_mut() { |
| 456 | if !chunk.is_empty() { |
| 457 | chunk.push('\n'); |
| 458 | } |
| 459 | chunk.push_str(text); |
| 460 | } |
| 461 | } else { |
| 462 | chunks.push(text.clone()); |
| 463 | } |
| 464 | coalesce = true; |
| 465 | } |
| 466 | ContentBlock::Thinking { thinking, .. } |
| 467 | if thinking != "(reasoning omitted)" => |
| 468 | { |
| 469 | coalesce = false; |
| 470 | } |
| 471 | ContentBlock::ToolUse { name, .. } if name == "update_plan" => { |
| 472 | coalesce = false; |
| 473 | } |
| 474 | _ => {} |
| 475 | } |
| 476 | } |
| 477 | updates.extend( |
| 478 | chunks |
| 479 | .into_iter() |
| 480 | .map(|text| chunk(acp::ContentChunk::new(acp::ContentBlock::from(text)))), |
| 481 | ); |
| 482 | } |
| 483 | for block in &message.content { |
| 484 | let Some(key) = block.tool_call_key().map(|key| key.as_str().to_string()) else { |
| 485 | continue; |
| 486 | }; |
| 487 | match block { |
| 488 | ContentBlock::ToolUse { name, input, .. } => { |
| 489 | let call = PendingToolCall { |
| 490 | execution_id: key.clone(), |
| 491 | name: name.clone(), |
| 492 | input: input.clone(), |
| 493 | }; |
| 494 | updates.push(acp::SessionUpdate::ToolCall(tool_call_start( |
| 495 | &call, |
| 496 | &saved.metadata.workspace, |
| 497 | None, |
| 498 | ))); |
| 499 | calls.insert(key, call); |
| 500 | } |
| 501 | ContentBlock::ToolResult { |
| 502 | content, is_error, .. |
| 503 | } => { |
| 504 | if let Some(call) = calls.remove(&key) { |
| 505 | let status = if is_error.unwrap_or(false) { |
| 506 | acp::ToolCallStatus::Failed |
| 507 | } else { |
| 508 | acp::ToolCallStatus::Completed |
| 509 | }; |
| 510 | let detail = |
| 511 | codewhale_engine::runtime_threads::manager::tool_receipt_detail( |
| 512 | &call.name, content, &secrets, |
| 513 | ); |
| 514 | updates.push(acp::SessionUpdate::ToolCallUpdate(tool_call_update( |
| 515 | &call, |
| 516 | &saved.metadata.workspace, |
| 517 | status, |
| 518 | Some(&detail), |
| 519 | &[], |
| 520 | None, |
| 521 | ))); |
| 522 | } |
| 523 | } |
| 524 | _ => {} |
| 525 | } |
| 526 | } |
| 527 | } |
| 528 | Ok(updates) |
| 529 | } |
| 530 | |
| 531 | async fn current_acp_locale() -> codewhale_localization::Locale { |
| 532 | let settings = |
| 533 | spawn_blocking_io(|| codewhale_runtime::settings::Settings::load().unwrap_or_default()) |
| 534 | .await |
| 535 | .unwrap_or_default(); |
| 536 | codewhale_localization::resolve_locale(&settings.locale) |
| 537 | } |
| 538 | |
| 539 | async fn session_view_from( |
| 540 | ctx: &SessionViewContext, |
| 541 | session_id: &str, |
| 542 | locale: codewhale_localization::Locale, |
| 543 | ) -> std::result::Result<acp::NewSessionResponse, AcpError> { |
| 544 | use codewhale_localization::{MessageId, tr}; |
| 545 | let thread = ctx |
| 546 | .runtime |
| 547 | .get_thread(&ctx.thread_id) |
| 548 | .await |
| 549 | .map_err(|error| AcpError::internal(error.to_string()))?; |
| 550 | let identity = ctx |
| 551 | .config |
| 552 | .resolve_persisted_provider_identity( |
| 553 | thread.model_provider.as_deref(), |
| 554 | thread.model_provider_id.as_deref(), |
| 555 | ) |
| 556 | .map_err(AcpError::invalid_params)?; |
| 557 | let mut models = codewhale_engine::provider_lake::models_for_provider(&ctx.config, &identity); |
| 558 | if !models.contains(&thread.model) { |
| 559 | models.push(thread.model.clone()); |
| 560 | } |
| 561 | let mut modes = vec![ |
| 562 | acp::SessionMode::new("plan", tr(locale, MessageId::AppModePlan).to_string()) |
| 563 | .description(tr(locale, MessageId::AppModePlanHint).to_string()), |
| 564 | ]; |
| 565 | // #6310: the permission posture is server-owned (a client can never |
| 566 | // relax it), but it must be discoverable. Work under Full Access must |
| 567 | // not claim that edits ask for approval, and the posture is surfaced |
| 568 | // below as a read-only select that names how Full Access is enabled. |
| 569 | let posture = acp_approval_mode(&ctx.config); |
| 570 | let agent_hint = if posture == ApprovalMode::Bypass { |
| 571 | tr(locale, MessageId::HomeYoloModeTip) |
| 572 | } else { |
| 573 | tr(locale, MessageId::AppModeAgentHint) |
| 574 | }; |
| 575 | if acp_mode(&ctx.config) != AppMode::Plan { |
| 576 | modes.insert( |
| 577 | 0, |
| 578 | acp::SessionMode::new("agent", tr(locale, MessageId::AppModeAgent).to_string()) |
| 579 | .description(agent_hint.to_string()), |
| 580 | ); |
| 581 | } |
| 582 | let current_mode = if thread.mode == "plan" { |
| 583 | "plan" |
| 584 | } else { |
| 585 | "agent" |
| 586 | }; |
| 587 | let (posture_value, posture_name, posture_description) = match posture { |
| 588 | ApprovalMode::Bypass => ( |
| 589 | "full-access", |
| 590 | MessageId::ConfigChoiceFullAccess, |
| 591 | MessageId::PermissionsPostureBypass, |
| 592 | ), |
| 593 | ApprovalMode::Auto => ( |
| 594 | "auto-review", |
| 595 | MessageId::ConfigChoiceAutoReview, |
| 596 | MessageId::PermissionsPostureAuto, |
| 597 | ), |
| 598 | ApprovalMode::Never => ( |
| 599 | "never", |
| 600 | MessageId::ConfigChoiceNever, |
| 601 | MessageId::PermissionsPostureNever, |
| 602 | ), |
| 603 | ApprovalMode::Suggest | ApprovalMode::AcceptEdits => ( |
| 604 | "ask", |
| 605 | MessageId::ConfigChoiceAsk, |
| 606 | MessageId::PermissionsPostureAsk, |
| 607 | ), |
| 608 | }; |
| 609 | let mode_choices: Vec<acp::SessionConfigSelectOption> = modes |
| 610 | .iter() |
| 611 | .map(|mode| { |
| 612 | acp::SessionConfigSelectOption::new(mode.id.0.clone(), mode.name.clone()) |
| 613 | .description(mode.description.clone()) |
| 614 | }) |
| 615 | .collect(); |
| 616 | let model_choices: Vec<acp::SessionConfigSelectOption> = models |
| 617 | .iter() |
| 618 | .map(|model| acp::SessionConfigSelectOption::new(model.clone(), model.clone())) |
| 619 | .collect(); |
| 620 | let options = vec![ |
| 621 | acp::SessionConfigOption::select( |
| 622 | "mode", |
| 623 | tr(locale, MessageId::SettingSubjectMode).to_string(), |
| 624 | current_mode, |
| 625 | mode_choices, |
| 626 | ) |
| 627 | .category(acp::SessionConfigOptionCategory::Mode), |
| 628 | acp::SessionConfigOption::select( |
| 629 | "model", |
| 630 | tr(locale, MessageId::SettingSubjectModel).to_string(), |
| 631 | thread.model.clone(), |
| 632 | model_choices, |
| 633 | ) |
| 634 | .category(acp::SessionConfigOptionCategory::Model), |
| 635 | // Exactly one option: the posture the server was started |
| 636 | // with. Offering a looser value here would let a client relax |
| 637 | // the operator's floor. |
| 638 | acp::SessionConfigOption::select( |
| 639 | "permission", |
| 640 | tr(locale, MessageId::SettingSubjectPermissions).to_string(), |
| 641 | posture_value, |
| 642 | vec![ |
| 643 | acp::SessionConfigSelectOption::new( |
| 644 | posture_value, |
| 645 | tr(locale, posture_name).to_string(), |
| 646 | ) |
| 647 | .description(tr(locale, posture_description).to_string()), |
| 648 | ], |
| 649 | ) |
| 650 | .category(acp::SessionConfigOptionCategory::Other( |
| 651 | "_permission".to_string(), |
| 652 | )) |
| 653 | .meta(codewhale_meta(json!({ |
| 654 | "readOnly": true, |
| 655 | "fullAccess": posture == ApprovalMode::Bypass, |
| 656 | "enableFullAccess": tr(locale, MessageId::AcpFullAccessHint).to_string(), |
| 657 | }))), |
| 658 | ]; |
| 659 | Ok(acp::NewSessionResponse::new(session_id.to_string()) |
| 660 | .modes(acp::SessionModeState::new(current_mode, modes)) |
| 661 | .config_options(options)) |
| 662 | } |
| 663 | |
| 664 | fn parse_set_session_config_params( |
| 665 | params: &Value, |
| 666 | ) -> std::result::Result<(String, String, String), AcpError> { |
| 667 | let session_id = params |
| 668 | .get("sessionId") |
| 669 | .and_then(Value::as_str) |
| 670 | .ok_or_else(|| AcpError::invalid_params("sessionId is required"))?; |
| 671 | let config_id = params |
| 672 | .get("configId") |
| 673 | .and_then(Value::as_str) |
| 674 | .ok_or_else(|| AcpError::invalid_params("configId is required"))?; |
| 675 | let value = params |
| 676 | .get("value") |
| 677 | .and_then(Value::as_str) |
| 678 | .ok_or_else(|| AcpError::invalid_params("value must be an offered string option"))?; |
| 679 | Ok(( |
| 680 | session_id.to_string(), |
| 681 | config_id.to_string(), |
| 682 | value.to_string(), |
| 683 | )) |
| 684 | } |
| 685 | |
| 686 | async fn set_session_config_with( |
| 687 | ctx: SetSessionConfigContext, |
| 688 | session_id: &str, |
| 689 | config_id: &str, |
| 690 | value: &str, |
| 691 | ) -> std::result::Result<Value, AcpError> { |
| 692 | let locale = current_acp_locale().await; |
| 693 | let options = Box::pin(session_view_from(&ctx.view, session_id, locale)) |
| 694 | .await? |
| 695 | .config_options |
| 696 | .unwrap_or_default(); |
| 697 | let offered = options.iter().any(|option| { |
| 698 | &*option.id.0 == config_id |
| 699 | && match &option.kind { |
| 700 | acp::SessionConfigKind::Select(select) => match &select.options { |
| 701 | acp::SessionConfigSelectOptions::Ungrouped(choices) => { |
| 702 | choices.iter().any(|choice| &*choice.value.0 == value) |
| 703 | } |
| 704 | _ => false, |
| 705 | }, |
| 706 | _ => false, |
| 707 | } |
| 708 | }); |
| 709 | if !offered { |
| 710 | return Err(AcpError::invalid_params( |
| 711 | "unknown configuration option or value", |
| 712 | )); |
| 713 | } |
| 714 | let request = match config_id { |
| 715 | "model" => UpdateThreadRequest { |
| 716 | model: Some(value.to_string()), |
| 717 | ..Default::default() |
| 718 | }, |
| 719 | "mode" => UpdateThreadRequest { |
| 720 | mode: Some(value.to_string()), |
| 721 | allow_shell: Some(value != "plan" && ctx.shell_allowed), |
| 722 | ..Default::default() |
| 723 | }, |
| 724 | "permission" => { |
| 725 | return to_wire(&acp::SetSessionConfigOptionResponse::new(options)); |
| 726 | } |
| 727 | _ => unreachable!("validated offered option"), |
| 728 | }; |
| 729 | Box::pin(ctx.view.runtime.update_thread_with_shell_policy( |
| 730 | &ctx.view.thread_id, |
| 731 | request, |
| 732 | ctx.config_path.as_deref(), |
| 733 | ctx.config_profile.as_deref(), |
| 734 | )) |
| 735 | .await |
| 736 | .map_err(|error| AcpError::internal(error.to_string()))?; |
| 737 | let options = Box::pin(session_view_from(&ctx.view, session_id, locale)) |
| 738 | .await? |
| 739 | .config_options |
| 740 | .unwrap_or_default(); |
| 741 | to_wire(&acp::SetSessionConfigOptionResponse::new(options)) |
| 742 | } |
| 743 | |
| 744 | impl AcpServer { |
| 745 | fn new( |
| 746 | config: impl Into<Arc<Config>>, |
| 747 | model: String, |
| 748 | default_cwd: PathBuf, |
| 749 | runtime: Arc<RuntimeThreadManager>, |
| 750 | sessions_dir: PathBuf, |
| 751 | config_path: Option<PathBuf>, |
| 752 | config_profile: Option<String>, |
| 753 | ) -> Self { |
| 754 | Self { |
| 755 | config: config.into(), |
| 756 | model, |
| 757 | default_cwd, |
| 758 | runtime, |
| 759 | sessions_dir, |
| 760 | config_path, |
| 761 | config_profile, |
| 762 | sessions: HashMap::new(), |
| 763 | insertion_order: VecDeque::new(), |
| 764 | client_supports_terminal: false, |
| 765 | } |
| 766 | } |
| 767 | fn prompt_run(&self) -> runtime::PromptRun { |
| 768 | runtime::PromptRun { |
| 769 | runtime: Arc::clone(&self.runtime), |
| 770 | sessions_dir: self.sessions_dir.clone(), |
| 771 | } |
| 772 | } |
| 773 | |
| 774 | fn session_view_context( |
| 775 | &self, |
| 776 | session_id: &str, |
| 777 | ) -> std::result::Result<SessionViewContext, AcpError> { |
| 778 | let binding = self |
| 779 | .sessions |
| 780 | .get(session_id) |
| 781 | .ok_or_else(|| AcpError::invalid_params("unknown sessionId"))?; |
| 782 | Ok(SessionViewContext { |
| 783 | config: Arc::clone(&self.config), |
| 784 | runtime: Arc::clone(&self.runtime), |
| 785 | thread_id: binding.thread_id.clone(), |
| 786 | }) |
| 787 | } |
| 788 | |
| 789 | fn new_session_context(&self) -> NewSessionContext { |
| 790 | NewSessionContext { |
| 791 | config: Arc::clone(&self.config), |
| 792 | model: self.model.clone(), |
| 793 | default_cwd: self.default_cwd.clone(), |
| 794 | runtime: Arc::clone(&self.runtime), |
| 795 | sessions_dir: self.sessions_dir.clone(), |
| 796 | config_path: self.config_path.clone(), |
| 797 | config_profile: self.config_profile.clone(), |
| 798 | shell_allowed: self.shell_allowed(), |
| 799 | } |
| 800 | } |
| 801 | |
| 802 | fn load_session_context(&self) -> LoadSessionContext { |
| 803 | LoadSessionContext { |
| 804 | config: Arc::clone(&self.config), |
| 805 | runtime: Arc::clone(&self.runtime), |
| 806 | sessions_dir: self.sessions_dir.clone(), |
| 807 | config_path: self.config_path.clone(), |
| 808 | config_profile: self.config_profile.clone(), |
| 809 | shell_allowed: self.shell_allowed(), |
| 810 | } |
| 811 | } |
| 812 | |
| 813 | fn set_session_config_context( |
| 814 | &self, |
| 815 | session_id: &str, |
| 816 | ) -> std::result::Result<SetSessionConfigContext, AcpError> { |
| 817 | Ok(SetSessionConfigContext { |
| 818 | view: self.session_view_context(session_id)?, |
| 819 | config_path: self.config_path.clone(), |
| 820 | config_profile: self.config_profile.clone(), |
| 821 | shell_allowed: self.shell_allowed(), |
| 822 | }) |
| 823 | } |
| 824 | |
| 825 | fn handle_sync_request( |
| 826 | &mut self, |
| 827 | method: &str, |
| 828 | params: Value, |
| 829 | ) -> std::result::Result<Value, SdkError> { |
| 830 | match method { |
| 831 | "initialize" => { |
| 832 | if let Some(terminal) = params |
| 833 | .pointer("/clientCapabilities/terminal") |
| 834 | .and_then(Value::as_bool) |
| 835 | { |
| 836 | self.client_supports_terminal = terminal; |
| 837 | } |
| 838 | let terminal_auth = params |
| 839 | .pointer("/clientCapabilities/auth/terminal") |
| 840 | .and_then(Value::as_bool) |
| 841 | .unwrap_or(false); |
| 842 | Ok(to_wire(&initialize_result(&self.config, terminal_auth))?) |
| 843 | } |
| 844 | "session/listProviders" => Ok(self.list_providers()), |
| 845 | "session/currentModel" => Ok(self.current_model()), |
| 846 | "session/selectModel" => Ok(self.select_model(params)?), |
| 847 | _ => Err(SdkError::method_not_found().data(Value::String(method.to_string()))), |
| 848 | } |
| 849 | } |
| 850 | |
| 851 | async fn handle_request_shared( |
| 852 | server: &tokio::sync::Mutex<Self>, |
| 853 | method: &str, |
| 854 | params: Value, |
| 855 | ) -> std::result::Result<Value, SdkError> { |
| 856 | match method { |
| 857 | "initialize" |
| 858 | | "session/listProviders" |
| 859 | | "session/currentModel" |
| 860 | | "session/selectModel" => server.lock().await.handle_sync_request(method, params), |
| 861 | "session/list" => { |
| 862 | let sessions_dir = server.lock().await.sessions_dir.clone(); |
| 863 | Ok(Box::pin(list_sessions_from_dir(sessions_dir, params)).await?) |
| 864 | } |
| 865 | "session/new" => { |
| 866 | let ctx = server.lock().await.new_session_context(); |
| 867 | let (id, thread_id) = Box::pin(create_new_session(ctx, params)).await?; |
| 868 | let view_ctx = { |
| 869 | let mut guard = server.lock().await; |
| 870 | guard.remember(id.clone(), thread_id); |
| 871 | guard.session_view_context(&id)? |
| 872 | }; |
| 873 | let locale = current_acp_locale().await; |
| 874 | Ok(to_wire( |
| 875 | &Box::pin(session_view_from(&view_ctx, &id, locale)).await?, |
| 876 | )?) |
| 877 | } |
| 878 | "session/load" => Ok(Box::pin(Self::load_session_shared(server, params)).await?), |
| 879 | "session/set_config_option" => { |
| 880 | let (session_id, config_id, value) = parse_set_session_config_params(¶ms)?; |
| 881 | let ctx = server |
| 882 | .lock() |
| 883 | .await |
| 884 | .set_session_config_context(&session_id)?; |
| 885 | Ok(Box::pin(set_session_config_with( |
| 886 | ctx, |
| 887 | &session_id, |
| 888 | &config_id, |
| 889 | &value, |
| 890 | )) |
| 891 | .await?) |
| 892 | } |
| 893 | "session/set_mode" | "session/set_model" => { |
| 894 | let (config_id, field) = if method == "session/set_mode" { |
| 895 | ("mode", "modeId") |
| 896 | } else { |
| 897 | ("model", "modelId") |
| 898 | }; |
| 899 | let normalized = json!({ |
| 900 | "sessionId": params.get("sessionId"), |
| 901 | "configId": config_id, |
| 902 | "value": params.get(field), |
| 903 | }); |
| 904 | let (session_id, config_id, value) = parse_set_session_config_params(&normalized)?; |
| 905 | let ctx = server |
| 906 | .lock() |
| 907 | .await |
| 908 | .set_session_config_context(&session_id)?; |
| 909 | Box::pin(set_session_config_with( |
| 910 | ctx, |
| 911 | &session_id, |
| 912 | &config_id, |
| 913 | &value, |
| 914 | )) |
| 915 | .await?; |
| 916 | Ok(to_wire(&acp::SetSessionModeResponse::new())?) |
| 917 | } |
| 918 | _ => Err(SdkError::method_not_found().data(Value::String(method.to_string()))), |
| 919 | } |
| 920 | } |
| 921 | |
| 922 | async fn load_session_shared( |
| 923 | server: &tokio::sync::Mutex<Self>, |
| 924 | params: Value, |
| 925 | ) -> std::result::Result<Value, AcpError> { |
| 926 | validate_mcp_servers(¶ms)?; |
| 927 | absolute_cwd(¶ms, "session/load")?; |
| 928 | let requested = params |
| 929 | .get("sessionId") |
| 930 | .and_then(Value::as_str) |
| 931 | .ok_or_else(|| AcpError::invalid_params("session/load requires sessionId"))? |
| 932 | .to_string(); |
| 933 | let initial = { |
| 934 | let guard = server.lock().await; |
| 935 | match guard.session_view_context(&requested) { |
| 936 | Ok(view_ctx) => Ok(view_ctx), |
| 937 | Err(_) => Err(guard.load_session_context()), |
| 938 | } |
| 939 | }; |
| 940 | let ctx = match initial { |
| 941 | Ok(view_ctx) => { |
| 942 | let locale = current_acp_locale().await; |
| 943 | return to_wire(&Box::pin(session_view_from(&view_ctx, &requested, locale)).await?); |
| 944 | } |
| 945 | Err(ctx) => ctx, |
| 946 | }; |
| 947 | let id = resolve_saved_session_id(ctx.sessions_dir.clone(), requested).await?; |
| 948 | let existing = { |
| 949 | let guard = server.lock().await; |
| 950 | guard.session_view_context(&id).ok() |
| 951 | }; |
| 952 | if let Some(view_ctx) = existing { |
| 953 | let locale = current_acp_locale().await; |
| 954 | return to_wire(&Box::pin(session_view_from(&view_ctx, &id, locale)).await?); |
| 955 | } |
| 956 | let thread_id = Box::pin(resume_and_configure_loaded_session(&ctx, &id)).await?; |
| 957 | let view_ctx = { |
| 958 | let mut guard = server.lock().await; |
| 959 | guard.remember(id.clone(), thread_id); |
| 960 | guard.session_view_context(&id)? |
| 961 | }; |
| 962 | let locale = current_acp_locale().await; |
| 963 | to_wire(&Box::pin(session_view_from(&view_ctx, &id, locale)).await?) |
| 964 | } |
| 965 | |
| 966 | #[cfg(test)] |
| 967 | async fn handle_request( |
| 968 | &mut self, |
| 969 | method: &str, |
| 970 | params: Value, |
| 971 | ) -> std::result::Result<Value, SdkError> { |
| 972 | match method { |
| 973 | "initialize" |
| 974 | | "session/listProviders" |
| 975 | | "session/currentModel" |
| 976 | | "session/selectModel" => self.handle_sync_request(method, params), |
| 977 | "session/new" => Ok(Box::pin(self.new_session(params)).await?), |
| 978 | "session/list" => Ok(Box::pin(self.list_sessions(params)).await?), |
| 979 | "session/load" => Ok(Box::pin(self.load_session(params)).await?), |
| 980 | "session/set_config_option" => Ok(Box::pin(self.set_session_config(params)).await?), |
| 981 | "session/set_mode" | "session/set_model" => { |
| 982 | let (config_id, field) = if method == "session/set_mode" { |
| 983 | ("mode", "modeId") |
| 984 | } else { |
| 985 | ("model", "modelId") |
| 986 | }; |
| 987 | Box::pin(self.set_session_config(json!({ |
| 988 | "sessionId": params.get("sessionId"), |
| 989 | "configId": config_id, |
| 990 | "value": params.get(field), |
| 991 | }))) |
| 992 | .await?; |
| 993 | Ok(to_wire(&acp::SetSessionModeResponse::new())?) |
| 994 | } |
| 995 | _ => Err(SdkError::method_not_found().data(Value::String(method.to_string()))), |
| 996 | } |
| 997 | } |
| 998 | |
| 999 | fn validate_prompt(&self, params: &Value) -> std::result::Result<(String, String), AcpError> { |
| 1000 | let id = params |
| 1001 | .get("sessionId") |
| 1002 | .and_then(Value::as_str) |
| 1003 | .ok_or_else(|| AcpError::invalid_params("sessionId is required"))?; |
| 1004 | if !self.sessions.contains_key(id) { |
| 1005 | return Err(AcpError::invalid_params("unknown sessionId")); |
| 1006 | } |
| 1007 | if let Some(kind) = unsupported_prompt_block(params.get("prompt")) { |
| 1008 | return Err(AcpError::invalid_params(format!( |
| 1009 | "unsupported prompt content block `{kind}`: this agent accepts text, resource and resource_link blocks only" |
| 1010 | ))); |
| 1011 | } |
| 1012 | let prompt = extract_prompt_text(params.get("prompt")) |
| 1013 | .filter(|text| !text.trim().is_empty()) |
| 1014 | .ok_or_else(|| AcpError::invalid_params("prompt must include text content"))?; |
| 1015 | Ok((id.to_string(), prompt)) |
| 1016 | } |
| 1017 | fn shell_allowed(&self) -> bool { |
| 1018 | self.client_supports_terminal && self.config.allow_shell() |
| 1019 | } |
| 1020 | fn remember(&mut self, id: String, thread_id: String) { |
| 1021 | if self.sessions.contains_key(&id) { |
| 1022 | return; |
| 1023 | } |
| 1024 | if self.sessions.len() >= MAX_ACP_SESSIONS |
| 1025 | && let Some(old) = self.insertion_order.pop_front() |
| 1026 | { |
| 1027 | self.sessions.remove(&old); |
| 1028 | } |
| 1029 | self.insertion_order.push_back(id.clone()); |
| 1030 | self.sessions.insert(id, AcpSession { thread_id }); |
| 1031 | } |
| 1032 | #[cfg(test)] |
| 1033 | async fn new_session(&mut self, params: Value) -> std::result::Result<Value, AcpError> { |
| 1034 | let (id, thread_id) = create_new_session(self.new_session_context(), params).await?; |
| 1035 | self.remember(id.clone(), thread_id); |
| 1036 | self.session_configuration(&id).await |
| 1037 | } |
| 1038 | /// Durable Codewhale sessions an ACP client can resume (#5864). |
| 1039 | /// |
| 1040 | /// ACP transport bindings are in-memory and capped; Core sessions are the |
| 1041 | /// durable record, and an IDE that offers "resume" means those. A store |
| 1042 | /// that cannot be read is an empty list, not a failed request: enumeration |
| 1043 | /// is discovery, and a client asking what exists should not be broken by a |
| 1044 | /// missing sessions directory. |
| 1045 | #[cfg(test)] |
| 1046 | async fn list_sessions(&self, params: Value) -> std::result::Result<Value, AcpError> { |
| 1047 | list_sessions_from_dir(self.sessions_dir.clone(), params).await |
| 1048 | } |
| 1049 | |
| 1050 | #[cfg(test)] |
| 1051 | async fn load_session(&mut self, params: Value) -> std::result::Result<Value, AcpError> { |
| 1052 | validate_mcp_servers(¶ms)?; |
| 1053 | absolute_cwd(¶ms, "session/load")?; |
| 1054 | let requested = params |
| 1055 | .get("sessionId") |
| 1056 | .and_then(Value::as_str) |
| 1057 | .ok_or_else(|| AcpError::invalid_params("session/load requires sessionId"))? |
| 1058 | .to_string(); |
| 1059 | if self.sessions.contains_key(&requested) { |
| 1060 | return self.session_configuration(&requested).await; |
| 1061 | } |
| 1062 | let id = resolve_saved_session_id(self.sessions_dir.clone(), requested).await?; |
| 1063 | if self.sessions.contains_key(&id) { |
| 1064 | return self.session_configuration(&id).await; |
| 1065 | } |
| 1066 | let ctx = self.load_session_context(); |
| 1067 | let thread_id = Box::pin(resume_and_configure_loaded_session(&ctx, &id)).await?; |
| 1068 | self.remember(id.clone(), thread_id); |
| 1069 | self.session_configuration(&id).await |
| 1070 | } |
| 1071 | #[cfg(test)] |
| 1072 | async fn history_updates(&self, session_id: &str) -> Result<Vec<acp::SessionUpdate>> { |
| 1073 | history_updates_for( |
| 1074 | self.sessions_dir.clone(), |
| 1075 | Arc::clone(&self.config), |
| 1076 | session_id.to_string(), |
| 1077 | ) |
| 1078 | .await |
| 1079 | } |
| 1080 | #[cfg(test)] |
| 1081 | async fn session_configuration( |
| 1082 | &self, |
| 1083 | session_id: &str, |
| 1084 | ) -> std::result::Result<Value, AcpError> { |
| 1085 | let locale = current_acp_locale().await; |
| 1086 | to_wire(&self.session_view_for_locale(session_id, locale).await?) |
| 1087 | } |
| 1088 | #[cfg(test)] |
| 1089 | async fn session_view_for_locale( |
| 1090 | &self, |
| 1091 | session_id: &str, |
| 1092 | locale: codewhale_localization::Locale, |
| 1093 | ) -> std::result::Result<acp::NewSessionResponse, AcpError> { |
| 1094 | let ctx = self.session_view_context(session_id)?; |
| 1095 | session_view_from(&ctx, session_id, locale).await |
| 1096 | } |
| 1097 | |
| 1098 | #[cfg(test)] |
| 1099 | async fn set_session_config(&mut self, params: Value) -> std::result::Result<Value, AcpError> { |
| 1100 | let (session_id, config_id, value) = parse_set_session_config_params(¶ms)?; |
| 1101 | let ctx = self.set_session_config_context(&session_id)?; |
| 1102 | set_session_config_with(ctx, &session_id, &config_id, &value).await |
| 1103 | } |
| 1104 | |
| 1105 | fn list_providers(&self) -> Value { |
| 1106 | let mut providers = self.config.provider_identities().into_iter().filter(|identity| identity.provider != ProviderKind::Antigravity).map(|identity| { |
| 1107 | json!({"id": identity.key, "displayName": identity.compatibility().map(|row| row.label).unwrap_or(identity.key.as_str()), "defaultModel": codewhale_engine::model_inventory::provider_default_model(&self.config, &identity)}) |
| 1108 | }).collect::<Vec<_>>(); |
| 1109 | providers.extend(self.config.unadmitted_provider_keys().into_iter().map(|key| json!({"id": key, "displayName": format!("{key} (unavailable)"), "defaultModel": "", "available": false, "reason": "provider_identity_unavailable"}))); |
| 1110 | json!({"providers": providers}) |
| 1111 | } |
| 1112 | |
| 1113 | fn current_model(&self) -> Value { |
| 1114 | // Prefer the raw configured provider key so a custom `[providers.<name>]` |
| 1115 | // entry round-trips through ACP instead of canonicalizing to "custom". |
| 1116 | let provider = self |
| 1117 | .config |
| 1118 | .active_provider_identity() |
| 1119 | .ok() |
| 1120 | .map(|identity| identity.key.to_string()) |
| 1121 | .or_else(|| self.config.provider.clone()) |
| 1122 | .unwrap_or_else(|| "unavailable".to_string()); |
| 1123 | json!({ |
| 1124 | "provider": provider, |
| 1125 | "model": self.model.as_str() |
| 1126 | }) |
| 1127 | } |
| 1128 | |
| 1129 | fn select_model(&mut self, params: Value) -> std::result::Result<Value, AcpError> { |
| 1130 | let model = params |
| 1131 | .get("model") |
| 1132 | .and_then(Value::as_str) |
| 1133 | .ok_or_else(|| AcpError::invalid_params("model is required"))? |
| 1134 | .to_string(); |
| 1135 | |
| 1136 | if let Some(provider_value) = params.get("provider") { |
| 1137 | let provider_name = provider_value |
| 1138 | .as_str() |
| 1139 | .ok_or_else(|| AcpError::invalid_params("provider must be a string"))?; |
| 1140 | let identity = self |
| 1141 | .config |
| 1142 | .resolve_provider_selection_identity(provider_name) |
| 1143 | .map_err(AcpError::invalid_params)?; |
| 1144 | Arc::make_mut(&mut self.config) |
| 1145 | .scope_to_provider_identity(&identity) |
| 1146 | .map_err(AcpError::invalid_params)?; |
| 1147 | } |
| 1148 | |
| 1149 | self.model = model; |
| 1150 | Ok(self.current_model()) |
| 1151 | } |
| 1152 | } |
| 1153 | |
| 1154 | fn acp_permission_value(config: &Config) -> &'static str { |
| 1155 | match acp_approval_mode(config) { |
| 1156 | ApprovalMode::Bypass => "full-access", |
| 1157 | ApprovalMode::Auto => "auto-review", |
| 1158 | ApprovalMode::Never => "never", |
| 1159 | ApprovalMode::Suggest | ApprovalMode::AcceptEdits => "ask", |
| 1160 | } |
| 1161 | } |
| 1162 | |
| 1163 | fn acp_startup_posture(config: &Config, workspace: &Path) -> String { |
| 1164 | let approval = acp_approval_mode(config); |
| 1165 | let sandbox = sandbox_policy_for_turn( |
| 1166 | acp_mode(config), |
| 1167 | approval, |
| 1168 | config.sandbox_mode.as_deref(), |
| 1169 | workspace, |
| 1170 | SandboxNetworkAccess::from_config(config.sandbox_network_access), |
| 1171 | ); |
| 1172 | let mut line = format!( |
| 1173 | "ACP permission: {}; sandbox: {}.", |
| 1174 | acp_permission_value(config), |
| 1175 | sandbox.config_value() |
| 1176 | ); |
| 1177 | if approval != ApprovalMode::Bypass { |
| 1178 | line.push_str( |
| 1179 | " For Full Access start with `codewhale serve --acp --full-access` or set `yolo = true`; sandbox_mode alone never turns it on.", |
| 1180 | ); |
| 1181 | } |
| 1182 | line |
| 1183 | } |
| 1184 | |
| 1185 | fn acp_mode(config: &Config) -> AppMode { |
| 1186 | if config.sandbox_mode.as_deref() == Some("read-only") { |
| 1187 | AppMode::Plan |
| 1188 | } else { |
| 1189 | AppMode::Agent |
| 1190 | } |
| 1191 | } |
| 1192 | |
| 1193 | /// Approval posture for ACP turns, derived from server config instead of |
| 1194 | /// hardcoded: `--yolo` resolves to Bypass so an unattended headless session |
| 1195 | /// actually executes tools (#6337); otherwise the configured approval policy, |
| 1196 | /// else the Suggest default. Plan mode still pins read-only downstream |
| 1197 | /// regardless of posture. |
| 1198 | fn acp_approval_mode(config: &Config) -> ApprovalMode { |
| 1199 | if config.yolo.unwrap_or(false) && !config.approval_policy_is_requirements_managed() { |
| 1200 | ApprovalMode::Bypass |
| 1201 | } else { |
| 1202 | match config |
| 1203 | .approval_policy |
| 1204 | .as_deref() |
| 1205 | .and_then(ApprovalMode::from_config_value) |
| 1206 | .unwrap_or_default() |
| 1207 | { |
| 1208 | ApprovalMode::AcceptEdits => ApprovalMode::Suggest, |
| 1209 | mode => mode, |
| 1210 | } |
| 1211 | } |
| 1212 | } |
| 1213 | |
| 1214 | fn ensure_acp_approval_posture(config: &Config) -> Result<()> { |
| 1215 | anyhow::ensure!( |
| 1216 | acp_approval_mode(config) != ApprovalMode::Never, |
| 1217 | "approval_policy \"never\" is not supported by `codewhale serve --acp`: ACP sessions run under Ask, Auto-Review or Full Access. Set approval_policy = \"on-request\" for this server, or start it with --full-access for Full Access." |
| 1218 | ); |
| 1219 | Ok(()) |
| 1220 | } |
| 1221 | |
| 1222 | /// ACP `kind` hint for a tool call, used by the client to pick an icon/label. |
| 1223 | /// Falls back to `"other"` for tools without an obvious category. |
| 1224 | /// |
| 1225 | /// `File` is a single canonical tool covering read/list/search/write/edit/ |
| 1226 | /// patch (#4625), so its kind depends on the `action` argument rather than |
| 1227 | /// the tool name alone. |
| 1228 | fn tool_call_kind(call: &PendingToolCall) -> acp::ToolKind { |
| 1229 | match call.name.as_str() { |
| 1230 | "File" => match call.input.get("action").and_then(Value::as_str) { |
| 1231 | Some("write" | "edit" | "patch") => acp::ToolKind::Edit, |
| 1232 | _ => acp::ToolKind::Read, |
| 1233 | }, |
| 1234 | "apply_patch" | "write" | "edit" | "write_file" | "edit_file" => acp::ToolKind::Edit, |
| 1235 | "read" | "read_file" => acp::ToolKind::Read, |
| 1236 | "Git" => acp::ToolKind::Read, |
| 1237 | "bash" | "Bash" | "terminal_run" | "terminal_send" | "terminal_wait" |
| 1238 | | "terminal_cancel" | "terminal_reset" | "terminal/run" | "terminal/send" |
| 1239 | | "terminal/wait" | "terminal/cancel" | "terminal/reset" => acp::ToolKind::Execute, |
| 1240 | _ => acp::ToolKind::Other, |
| 1241 | } |
| 1242 | } |
| 1243 | |
| 1244 | /// Human-readable title for a tool call: the tool name plus its primary |
| 1245 | /// argument (path/command/pattern) when present, so the client's tool-call |
| 1246 | /// card is legible without expanding raw input. |
| 1247 | fn tool_call_title(call: &PendingToolCall) -> String { |
| 1248 | let detail = call |
| 1249 | .input |
| 1250 | .get("path") |
| 1251 | .or_else(|| call.input.get("command")) |
| 1252 | .or_else(|| call.input.get("pattern")) |
| 1253 | .or_else(|| call.input.get("task_id")) |
| 1254 | .and_then(Value::as_str); |
| 1255 | let action = if call.name == "File" { |
| 1256 | call.input.get("action").and_then(Value::as_str) |
| 1257 | } else { |
| 1258 | None |
| 1259 | }; |
| 1260 | let name = action.map_or_else(|| call.name.clone(), |action| format!("File {action}")); |
| 1261 | match detail { |
| 1262 | Some(detail) => format!("{name}: {detail}"), |
| 1263 | None => name, |
| 1264 | } |
| 1265 | } |
| 1266 | |
| 1267 | fn truncate_for_acp(content: &str) -> String { |
| 1268 | if content.chars().count() <= TOOL_CALL_CONTENT_PREVIEW_CHARS { |
| 1269 | return content.to_string(); |
| 1270 | } |
| 1271 | let truncated: String = content |
| 1272 | .chars() |
| 1273 | .take(TOOL_CALL_CONTENT_PREVIEW_CHARS) |
| 1274 | .collect(); |
| 1275 | format!("{truncated}\n… [truncated for display; the full result was sent to the model]") |
| 1276 | } |
| 1277 | |
| 1278 | fn tool_call_location(call: &PendingToolCall, workspace: &Path) -> Option<PathBuf> { |
| 1279 | matches!( |
| 1280 | tool_call_kind(call), |
| 1281 | acp::ToolKind::Read | acp::ToolKind::Edit |
| 1282 | ) |
| 1283 | .then(|| { |
| 1284 | ["path", "file_path", "filePath"] |
| 1285 | .iter() |
| 1286 | .find_map(|key| call.input.get(*key).and_then(Value::as_str)) |
| 1287 | }) |
| 1288 | .flatten() |
| 1289 | .filter(|path| !path.is_empty()) |
| 1290 | .and_then(|path| { |
| 1291 | let resolved = codewhale_engine::tools::spec::resolve_home_path(path) |
| 1292 | .ok() |
| 1293 | .flatten() |
| 1294 | .unwrap_or_else(|| workspace.join(path)); |
| 1295 | let normalized = codewhale_engine::tools::spec::normalize_path(&resolved); |
| 1296 | normalized.to_str().map(PathBuf::from) |
| 1297 | }) |
| 1298 | } |
| 1299 | |
| 1300 | fn tool_call_requested_diffs(_call: &PendingToolCall, _workspace: &Path) -> Vec<acp::Diff> { |
| 1301 | Vec::new() |
| 1302 | } |
| 1303 | |
| 1304 | fn external_locations(value: &Value) -> Option<Vec<acp::ToolCallLocation>> { |
| 1305 | value.as_array().map(|entries| { |
| 1306 | entries |
| 1307 | .iter() |
| 1308 | .filter_map(|entry| { |
| 1309 | let path = entry.get("path").and_then(Value::as_str)?; |
| 1310 | let mut location = acp::ToolCallLocation::new(PathBuf::from(path)); |
| 1311 | if let Some(line) = entry.get("line").and_then(Value::as_u64) { |
| 1312 | location = location.line(line as u32); |
| 1313 | } |
| 1314 | Some(location) |
| 1315 | }) |
| 1316 | .collect() |
| 1317 | }) |
| 1318 | } |
| 1319 | |
| 1320 | fn tool_call_start( |
| 1321 | call: &PendingToolCall, |
| 1322 | workspace: &Path, |
| 1323 | external_locations: Option<Vec<acp::ToolCallLocation>>, |
| 1324 | ) -> acp::ToolCall { |
| 1325 | let foreign = external_locations.is_some(); |
| 1326 | let mut start = acp::ToolCall::new(call.execution_id.clone(), tool_call_title(call)) |
| 1327 | .kind(tool_call_kind(call)) |
| 1328 | .status(acp::ToolCallStatus::Pending); |
| 1329 | if let Some(locations) = external_locations { |
| 1330 | start = start.locations(locations); |
| 1331 | } else { |
| 1332 | start = start.locations( |
| 1333 | tool_call_location(call, workspace) |
| 1334 | .map(acp::ToolCallLocation::new) |
| 1335 | .into_iter() |
| 1336 | .collect(), |
| 1337 | ); |
| 1338 | } |
| 1339 | if !foreign { |
| 1340 | start = start.content( |
| 1341 | tool_call_requested_diffs(call, workspace) |
| 1342 | .into_iter() |
| 1343 | .map(acp::ToolCallContent::Diff) |
| 1344 | .collect(), |
| 1345 | ); |
| 1346 | } |
| 1347 | start.raw_input((!call.input.is_null()).then(|| call.input.clone())) |
| 1348 | } |
| 1349 | |
| 1350 | fn tool_call_update( |
| 1351 | call: &PendingToolCall, |
| 1352 | workspace: &Path, |
| 1353 | status: acp::ToolCallStatus, |
| 1354 | content: Option<&str>, |
| 1355 | rich_blocks: &[codewhale_tools::ToolResultContentBlock], |
| 1356 | external_locations: Option<Vec<acp::ToolCallLocation>>, |
| 1357 | ) -> acp::ToolCallUpdate { |
| 1358 | let foreign = external_locations.is_some(); |
| 1359 | let mut fields = acp::ToolCallUpdateFields::new().status(status); |
| 1360 | if let Some(locations) = external_locations { |
| 1361 | fields = fields.locations(locations); |
| 1362 | } |
| 1363 | if content.is_some() || !rich_blocks.is_empty() { |
| 1364 | let mut blocks = Vec::with_capacity(rich_blocks.len() + 2); |
| 1365 | if !foreign { |
| 1366 | blocks.extend( |
| 1367 | tool_call_requested_diffs(call, workspace) |
| 1368 | .into_iter() |
| 1369 | .map(acp::ToolCallContent::Diff), |
| 1370 | ); |
| 1371 | } |
| 1372 | if let Some(content) = content { |
| 1373 | blocks.push(acp::ToolCallContent::from(truncate_for_acp(content))); |
| 1374 | } |
| 1375 | blocks.extend(rich_blocks.iter().map(|block| match block { |
| 1376 | codewhale_tools::ToolResultContentBlock::Image { mime_type, data } => { |
| 1377 | acp::ToolCallContent::from(acp::ContentBlock::Image(acp::ImageContent::new( |
| 1378 | data.clone(), |
| 1379 | mime_type.clone(), |
| 1380 | ))) |
| 1381 | } |
| 1382 | })); |
| 1383 | fields = fields.content(blocks); |
| 1384 | } |
| 1385 | acp::ToolCallUpdate::new(call.execution_id.clone(), fields) |
| 1386 | } |
| 1387 | |
| 1388 | fn agent_text(text: String) -> acp::SessionUpdate { |
| 1389 | acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(acp::ContentBlock::from(text))) |
| 1390 | } |
| 1391 | |
| 1392 | impl AcpError { |
| 1393 | fn invalid_params(message: impl Into<String>) -> Self { |
| 1394 | Self { |
| 1395 | code: -32602, |
| 1396 | message: message.into(), |
| 1397 | } |
| 1398 | } |
| 1399 | |
| 1400 | /// JSON-RPC internal error: the request was well-formed and the agent |
| 1401 | /// could not serve it. |
| 1402 | fn internal(message: impl Into<String>) -> Self { |
| 1403 | Self { |
| 1404 | code: -32603, |
| 1405 | message: message.into(), |
| 1406 | } |
| 1407 | } |
| 1408 | } |
| 1409 | |
| 1410 | impl From<AcpError> for SdkError { |
| 1411 | fn from(error: AcpError) -> Self { |
| 1412 | SdkError::new(error.code, error.message) |
| 1413 | } |
| 1414 | } |
| 1415 | |
| 1416 | fn to_wire<T: serde::Serialize>(value: &T) -> std::result::Result<Value, AcpError> { |
| 1417 | serde_json::to_value(value).map_err(|error| AcpError::internal(error.to_string())) |
| 1418 | } |
| 1419 | |
| 1420 | fn codewhale_meta(fields: Value) -> acp::Meta { |
| 1421 | let mut meta = acp::Meta::new(); |
| 1422 | meta.insert("codewhale".to_string(), fields); |
| 1423 | meta |
| 1424 | } |
| 1425 | |
| 1426 | fn validate_mcp_servers(params: &Value) -> std::result::Result<(), AcpError> { |
| 1427 | match params.get("mcpServers") { |
| 1428 | None => Ok(()), |
| 1429 | Some(Value::Array(servers)) if servers.is_empty() => Ok(()), |
| 1430 | Some(Value::Array(_)) => Err(AcpError::invalid_params( |
| 1431 | "Client-supplied MCP servers are unsupported by Codewhale's ACP adapter. Use an empty mcpServers list; sessions use the MCP servers and plugins configured in Codewhale itself.", |
| 1432 | )), |
| 1433 | Some(_) => Err(AcpError::invalid_params("mcpServers must be an array")), |
| 1434 | } |
| 1435 | } |
| 1436 | |
| 1437 | fn initialize_result(config: &Config, terminal_auth: bool) -> acp::InitializeResponse { |
| 1438 | let features = config.features(); |
| 1439 | // ACP `SessionCapabilities` fields are objects, never booleans: |
| 1440 | // `{}` means "supported", absent/null means "not supported" |
| 1441 | // (#5969 — a boolean here made JetBrains' strictly-typed client |
| 1442 | // fail the handshake and kill the agent). `session/load` support |
| 1443 | // is advertised by the top-level `loadSession`; it is not a |
| 1444 | // field of `sessionCapabilities`. We only claim `list` because |
| 1445 | // `session/list` is the only one of the optional session methods |
| 1446 | // this server dispatches. |
| 1447 | let capabilities = acp::AgentCapabilities::new() |
| 1448 | .load_session(true) |
| 1449 | .prompt_capabilities(acp::PromptCapabilities::new().embedded_context(true)) |
| 1450 | .mcp_capabilities(acp::McpCapabilities::new()) |
| 1451 | .session_capabilities( |
| 1452 | acp::SessionCapabilities::new().list(acp::SessionListCapabilities::new()), |
| 1453 | ) |
| 1454 | .meta(codewhale_meta(json!({ |
| 1455 | "plugins": features.enabled(Feature::ExtensionHost) |
| 1456 | && codewhale_plugins::activation::extension_host_policy_enabled(), |
| 1457 | "configuredMcpServers": features.enabled(Feature::Mcp), |
| 1458 | "clientMcpServers": false |
| 1459 | }))); |
| 1460 | acp::InitializeResponse::new(ProtocolVersion::V1) |
| 1461 | .agent_capabilities(capabilities) |
| 1462 | .agent_info( |
| 1463 | acp::Implementation::new("codewhale", env!("CARGO_PKG_VERSION")).title("codewhale"), |
| 1464 | ) |
| 1465 | .auth_methods(acp_auth_methods(config, terminal_auth)) |
| 1466 | } |
| 1467 | |
| 1468 | fn acp_auth_methods(config: &Config, terminal_auth: bool) -> Vec<acp::AuthMethod> { |
| 1469 | let Some(identity) = terminal_auth |
| 1470 | .then(|| config.active_provider_identity().ok()) |
| 1471 | .flatten() |
| 1472 | .filter(|identity| { |
| 1473 | identity.provider != ProviderKind::Custom |
| 1474 | && identity.provider != ProviderKind::Antigravity |
| 1475 | }) |
| 1476 | else { |
| 1477 | return Vec::new(); |
| 1478 | }; |
| 1479 | let provider = identity.provider.as_str(); |
| 1480 | vec![acp::AuthMethod::Terminal( |
| 1481 | acp::AuthMethodTerminal::new("codewhale-terminal-auth", "Set Codewhale API key") |
| 1482 | .description(format!( |
| 1483 | "Run Codewhale's terminal credential setup for the {provider} provider." |
| 1484 | )) |
| 1485 | .args( |
| 1486 | ["auth", "set", "--provider", provider] |
| 1487 | .map(str::to_string) |
| 1488 | .to_vec(), |
| 1489 | ), |
| 1490 | )] |
| 1491 | } |
| 1492 | |
| 1493 | fn extract_prompt_text(prompt: Option<&Value>) -> Option<String> { |
| 1494 | match prompt? { |
| 1495 | Value::String(text) => Some(text.clone()), |
| 1496 | Value::Array(blocks) => { |
| 1497 | let parts = blocks |
| 1498 | .iter() |
| 1499 | .filter_map(content_block_text) |
| 1500 | .collect::<Vec<_>>(); |
| 1501 | (!parts.is_empty()).then(|| parts.join("\n\n")) |
| 1502 | } |
| 1503 | _ => None, |
| 1504 | } |
| 1505 | } |
| 1506 | |
| 1507 | fn unsupported_prompt_block(prompt: Option<&Value>) -> Option<String> { |
| 1508 | let Value::Array(blocks) = prompt? else { |
| 1509 | return None; |
| 1510 | }; |
| 1511 | blocks.iter().find_map(|block| { |
| 1512 | let kind = block |
| 1513 | .get("type") |
| 1514 | .and_then(Value::as_str) |
| 1515 | .unwrap_or("unknown"); |
| 1516 | content_block_text(block) |
| 1517 | .is_none() |
| 1518 | .then(|| kind.to_string()) |
| 1519 | }) |
| 1520 | } |
| 1521 | |
| 1522 | fn absolute_cwd(params: &Value, method: &str) -> std::result::Result<Option<PathBuf>, AcpError> { |
| 1523 | match params.get("cwd") { |
| 1524 | None | Some(Value::Null) => Ok(None), |
| 1525 | Some(Value::String(path)) if Path::new(path).is_absolute() => Ok(Some(PathBuf::from(path))), |
| 1526 | Some(_) => Err(AcpError::invalid_params(format!( |
| 1527 | "{method} cwd must be an absolute path" |
| 1528 | ))), |
| 1529 | } |
| 1530 | } |
| 1531 | |
| 1532 | fn content_block_text(block: &Value) -> Option<String> { |
| 1533 | match block.get("type").and_then(Value::as_str)? { |
| 1534 | "text" => block |
| 1535 | .get("text") |
| 1536 | .and_then(Value::as_str) |
| 1537 | .map(str::to_string), |
| 1538 | "resource" => resource_text(block), |
| 1539 | "resource_link" | "resourceLink" => resource_link_text(block), |
| 1540 | _ => None, |
| 1541 | } |
| 1542 | } |
| 1543 | |
| 1544 | fn resource_text(block: &Value) -> Option<String> { |
| 1545 | let resource = block.get("resource").unwrap_or(block); |
| 1546 | if let Some(text) = resource.get("text").and_then(Value::as_str) { |
| 1547 | return Some(text.to_string()); |
| 1548 | } |
| 1549 | resource_link_text(resource) |
| 1550 | } |
| 1551 | |
| 1552 | fn resource_link_text(block: &Value) -> Option<String> { |
| 1553 | let uri = block |
| 1554 | .get("uri") |
| 1555 | .or_else(|| block.pointer("/resource/uri")) |
| 1556 | .and_then(Value::as_str)?; |
| 1557 | Some(format!("@{uri}")) |
| 1558 | } |
| 1559 | |
| 1560 | #[cfg(test)] |
| 1561 | mod tests { |
| 1562 | use super::*; |
| 1563 | use codewhale_engine::llm_client::mock::{MockLlmClient, canned}; |
| 1564 | use codewhale_models::{ContentBlock, Role}; |
| 1565 | use codewhale_util::bounded_lines::MAX_FRAME_BYTES; |
| 1566 | use std::time::Duration; |
| 1567 | |
| 1568 | fn replayed(updates: Vec<acp::SessionUpdate>) -> Vec<Value> { |
| 1569 | updates |
| 1570 | .into_iter() |
| 1571 | .map(|update| json!({"params":{"update":serde_json::to_value(update).unwrap()}})) |
| 1572 | .collect() |
| 1573 | } |
| 1574 | pub(super) fn fixture_config() -> Config { |
| 1575 | let mut config = { |
| 1576 | let __cw_config_init_0_0 = Some("acp-fixture".into()); |
| 1577 | let __cw_config_init_0_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1578 | custom: HashMap::from([( |
| 1579 | "acp-fixture".into(), |
| 1580 | codewhale_runtime::config::ProviderConfig { |
| 1581 | kind: Some("openai-compatible".into()), |
| 1582 | base_url: Some("http://127.0.0.1:18181/v1".into()), |
| 1583 | model: Some("fixture-model".into()), |
| 1584 | api_key: Some("local-test-key".into()), |
| 1585 | ..Default::default() |
| 1586 | }, |
| 1587 | )]), |
| 1588 | ..Default::default() |
| 1589 | }); |
| 1590 | let __cw_config_init_0_2 = Some(codewhale_runtime::config::SnapshotsConfig { |
| 1591 | enabled: false, |
| 1592 | ..Default::default() |
| 1593 | }); |
| 1594 | let mut __cw_config_init_0_value: Config = Default::default(); |
| 1595 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 1596 | __cw_config_init_0_value.providers = __cw_config_init_0_1; |
| 1597 | __cw_config_init_0_value.snapshots = __cw_config_init_0_2; |
| 1598 | __cw_config_init_0_value |
| 1599 | }; |
| 1600 | config.set_feature("mcp", false).unwrap(); |
| 1601 | config.set_feature("subagents", false).unwrap(); |
| 1602 | config |
| 1603 | } |
| 1604 | pub(super) struct Editor { |
| 1605 | lines: tokio::io::Lines<BufReader<tokio::io::ReadHalf<tokio::io::DuplexStream>>>, |
| 1606 | pub(super) write: tokio::io::WriteHalf<tokio::io::DuplexStream>, |
| 1607 | pub(super) next_id: u64, |
| 1608 | pub(super) seen: Vec<Value>, |
| 1609 | } |
| 1610 | impl Editor { |
| 1611 | pub(super) async fn send(&mut self, message: Value) -> Result<()> { |
| 1612 | let mut line = serde_json::to_vec(&message)?; |
| 1613 | line.push(b'\n'); |
| 1614 | self.write.write_all(&line).await?; |
| 1615 | self.write.flush().await?; |
| 1616 | Ok(()) |
| 1617 | } |
| 1618 | pub(super) async fn send_raw(&mut self, line: &str) -> Result<()> { |
| 1619 | self.write.write_all(line.as_bytes()).await?; |
| 1620 | self.write.write_all(b"\n").await?; |
| 1621 | self.write.flush().await?; |
| 1622 | Ok(()) |
| 1623 | } |
| 1624 | pub(super) async fn recv(&mut self) -> Result<Value> { |
| 1625 | let line = tokio::time::timeout(Duration::from_secs(30), self.lines.next_line()) |
| 1626 | .await |
| 1627 | .map_err(|_| anyhow!("no frame within 30s"))?? |
| 1628 | .ok_or_else(|| anyhow!("the agent closed the transport"))?; |
| 1629 | let frame: Value = serde_json::from_str(&line)?; |
| 1630 | self.seen.push(frame.clone()); |
| 1631 | Ok(frame) |
| 1632 | } |
| 1633 | pub(super) async fn until_response(&mut self, id: &Value) -> Result<(Value, Vec<Value>)> { |
| 1634 | let mut frames = Vec::new(); |
| 1635 | loop { |
| 1636 | let frame = self.recv().await?; |
| 1637 | if frame["id"] == *id && frame.get("method").is_none() { |
| 1638 | return Ok((frame, frames)); |
| 1639 | } |
| 1640 | frames.push(frame); |
| 1641 | } |
| 1642 | } |
| 1643 | pub(super) async fn request( |
| 1644 | &mut self, |
| 1645 | method: &str, |
| 1646 | params: Value, |
| 1647 | ) -> Result<(Value, Vec<Value>)> { |
| 1648 | self.next_id += 1; |
| 1649 | let id = json!(self.next_id); |
| 1650 | self.send(json!({"jsonrpc":"2.0","id":id,"method":method,"params":params})) |
| 1651 | .await?; |
| 1652 | self.until_response(&id).await |
| 1653 | } |
| 1654 | pub(super) async fn until_permission(&mut self) -> Result<Value> { |
| 1655 | loop { |
| 1656 | let frame = self.recv().await?; |
| 1657 | if frame["method"] == "session/request_permission" { |
| 1658 | return Ok(frame); |
| 1659 | } |
| 1660 | } |
| 1661 | } |
| 1662 | } |
| 1663 | pub(super) struct Rig { |
| 1664 | pub(super) server: AcpServer, |
| 1665 | mock: Arc<MockLlmClient>, |
| 1666 | pub(super) workspace: PathBuf, |
| 1667 | _home: codewhale_engine::test_support::SealedHome, |
| 1668 | _dir: tempfile::TempDir, |
| 1669 | } |
| 1670 | impl Rig { |
| 1671 | pub(super) fn new( |
| 1672 | config: Config, |
| 1673 | turns: Vec<codewhale_engine::llm_client::mock::CannedTurn>, |
| 1674 | ) -> Result<Self> { |
| 1675 | Self::with_base(config, turns, true) |
| 1676 | } |
| 1677 | fn with_base( |
| 1678 | config: Config, |
| 1679 | turns: Vec<codewhale_engine::llm_client::mock::CannedTurn>, |
| 1680 | acp: bool, |
| 1681 | ) -> Result<Self> { |
| 1682 | let dir = tempfile::tempdir()?; |
| 1683 | let home = codewhale_engine::test_support::SealedHome::at(dir.path()); |
| 1684 | let workspace = dir.path().join("workspace"); |
| 1685 | std::fs::create_dir(&workspace)?; |
| 1686 | let runtime_dir = dir.path().join("runtime"); |
| 1687 | let manager_config = RuntimeThreadManagerConfig { |
| 1688 | mcp_auth_context: Default::default(), |
| 1689 | data_dir: runtime_dir.clone(), |
| 1690 | task_data_dir: runtime_dir, |
| 1691 | sessions_dir: None, |
| 1692 | max_active_threads: 4, |
| 1693 | }; |
| 1694 | let plugins = Arc::new(codewhale_plugins::PluginRegistry::empty(&workspace)); |
| 1695 | let manager = Arc::new(if acp { |
| 1696 | RuntimeThreadManager::open_host( |
| 1697 | config.clone(), |
| 1698 | workspace.clone(), |
| 1699 | manager_config, |
| 1700 | plugins, |
| 1701 | codewhale_engine::core::engine::EngineHostProfile::Acp, |
| 1702 | None, |
| 1703 | None, |
| 1704 | )? |
| 1705 | } else { |
| 1706 | RuntimeThreadManager::open_with_plugin_registry( |
| 1707 | config.clone(), |
| 1708 | workspace.clone(), |
| 1709 | manager_config, |
| 1710 | plugins, |
| 1711 | )? |
| 1712 | }); |
| 1713 | let mock = Arc::new(MockLlmClient::new(turns)); |
| 1714 | manager.set_test_model_client(mock.clone()); |
| 1715 | let sessions = codewhale_engine::session_manager::default_sessions_dir()?; |
| 1716 | Ok(Self { |
| 1717 | server: AcpServer::new( |
| 1718 | config, |
| 1719 | "fixture-model".into(), |
| 1720 | workspace.clone(), |
| 1721 | manager, |
| 1722 | sessions, |
| 1723 | None, |
| 1724 | None, |
| 1725 | ), |
| 1726 | mock, |
| 1727 | workspace, |
| 1728 | _home: home, |
| 1729 | _dir: dir, |
| 1730 | }) |
| 1731 | } |
| 1732 | pub(super) async fn new_session(&mut self) -> String { |
| 1733 | self.server.new_session(json!({})).await.unwrap()["sessionId"] |
| 1734 | .as_str() |
| 1735 | .unwrap() |
| 1736 | .to_string() |
| 1737 | } |
| 1738 | fn placeholder(&self) -> AcpServer { |
| 1739 | AcpServer::new( |
| 1740 | self.server.config.clone(), |
| 1741 | self.server.model.clone(), |
| 1742 | self.server.default_cwd.clone(), |
| 1743 | Arc::clone(&self.server.runtime), |
| 1744 | self.server.sessions_dir.clone(), |
| 1745 | None, |
| 1746 | None, |
| 1747 | ) |
| 1748 | } |
| 1749 | pub(super) async fn drive<T>( |
| 1750 | &mut self, |
| 1751 | script: impl AsyncFnOnce(&mut Editor) -> Result<T>, |
| 1752 | ) -> Result<(T, Vec<Value>)> { |
| 1753 | let (editor_end, agent_end) = tokio::io::duplex(1 << 20); |
| 1754 | let (agent_read, agent_write) = tokio::io::split(agent_end); |
| 1755 | let (read, write) = tokio::io::split(editor_end); |
| 1756 | let mut editor = Editor { |
| 1757 | lines: tokio::io::AsyncBufReadExt::lines(BufReader::new(read)), |
| 1758 | write, |
| 1759 | next_id: 0, |
| 1760 | seen: Vec::new(), |
| 1761 | }; |
| 1762 | let placeholder = self.placeholder(); |
| 1763 | let server = std::mem::replace(&mut self.server, placeholder); |
| 1764 | let serving = super::connection::serve_connection( |
| 1765 | server, |
| 1766 | Box::new(BufReader::new(agent_read)), |
| 1767 | Box::new(agent_write), |
| 1768 | ); |
| 1769 | let scripted = async { |
| 1770 | let result = script(&mut editor).await; |
| 1771 | let _ = editor.write.shutdown().await; |
| 1772 | result |
| 1773 | }; |
| 1774 | let (served, scripted) = tokio::time::timeout( |
| 1775 | Duration::from_secs(if cfg!(windows) { 120 } else { 20 }), |
| 1776 | async { tokio::join!(serving, scripted) }, |
| 1777 | ) |
| 1778 | .await?; |
| 1779 | let shared = served?; |
| 1780 | self.server = Arc::try_unwrap(shared) |
| 1781 | .map_err(|_| anyhow!("the connection kept a server reference"))? |
| 1782 | .into_server(); |
| 1783 | while let Some(line) = editor.lines.next_line().await? { |
| 1784 | editor.seen.push(serde_json::from_str(&line)?); |
| 1785 | } |
| 1786 | Ok((scripted?, editor.seen)) |
| 1787 | } |
| 1788 | async fn prompt(&mut self, session: &str, text: &str) -> Result<(String, Vec<Value>)> { |
| 1789 | let (response, frames) = self |
| 1790 | .drive(async |editor| { |
| 1791 | let (response, _) = editor |
| 1792 | .request("session/prompt", json!({"sessionId":session,"prompt":text})) |
| 1793 | .await?; |
| 1794 | Ok(response) |
| 1795 | }) |
| 1796 | .await?; |
| 1797 | if let Some(error) = response.get("error") { |
| 1798 | anyhow::bail!("{error}"); |
| 1799 | } |
| 1800 | let reason = response["result"]["stopReason"] |
| 1801 | .as_str() |
| 1802 | .ok_or_else(|| anyhow!("{response}"))? |
| 1803 | .to_string(); |
| 1804 | let updates = frames |
| 1805 | .into_iter() |
| 1806 | .filter(|frame| frame["method"] == "session/update") |
| 1807 | .collect(); |
| 1808 | Ok((reason, updates)) |
| 1809 | } |
| 1810 | async fn history(&self, session: &str) -> Vec<codewhale_models::Message> { |
| 1811 | let thread = &self.server.sessions[session].thread_id; |
| 1812 | self.server |
| 1813 | .runtime |
| 1814 | .get_engine(thread) |
| 1815 | .await |
| 1816 | .unwrap() |
| 1817 | .get_session_snapshot() |
| 1818 | .await |
| 1819 | .unwrap() |
| 1820 | .messages |
| 1821 | } |
| 1822 | pub(super) async fn close(&self) { |
| 1823 | self.server.runtime.shutdown_and_wait().await.unwrap(); |
| 1824 | } |
| 1825 | } |
| 1826 | #[cfg(any(unix, windows))] |
| 1827 | #[tokio::test(flavor = "current_thread")] |
| 1828 | async fn authenticated_acp_owner_projects_actual_engine_and_guest_eof_preserves_lease() |
| 1829 | -> Result<()> { |
| 1830 | authenticated_owner_profile_case(true).await |
| 1831 | } |
| 1832 | #[cfg(any(unix, windows))] |
| 1833 | #[tokio::test(flavor = "current_thread")] |
| 1834 | async fn normal_owner_admits_authenticated_acp_then_ordinary_successor_without_profile_leak() |
| 1835 | -> Result<()> { |
| 1836 | authenticated_owner_profile_case(false).await |
| 1837 | } |
| 1838 | #[cfg(any(unix, windows))] |
| 1839 | async fn authenticated_owner_profile_case(base_acp: bool) -> Result<()> { |
| 1840 | struct AbortOnDrop(tokio::task::AbortHandle); |
| 1841 | impl Drop for AbortOnDrop { |
| 1842 | fn drop(&mut self) { |
| 1843 | self.0.abort(); |
| 1844 | } |
| 1845 | } |
| 1846 | async fn correlated( |
| 1847 | guest: &mut crate::daemon_client::OwnerClient, |
| 1848 | id: Value, |
| 1849 | ) -> Result<Value> { |
| 1850 | tokio::time::timeout(Duration::from_secs(30), async { |
| 1851 | loop { |
| 1852 | let frame = guest |
| 1853 | .recv() |
| 1854 | .await? |
| 1855 | .ok_or_else(|| anyhow!("ACP owner closed before reply"))?; |
| 1856 | if frame["id"] == id { |
| 1857 | return Ok(frame); |
| 1858 | } |
| 1859 | } |
| 1860 | }) |
| 1861 | .await? |
| 1862 | } |
| 1863 | let config = fixture_config(); |
| 1864 | let rig = Rig::with_base( |
| 1865 | config.clone(), |
| 1866 | vec![canned::simple_text_turn("same owner answer")], |
| 1867 | base_acp, |
| 1868 | )?; |
| 1869 | let manager = rig.server.runtime.clone(); |
| 1870 | let capture = manager.clone(); |
| 1871 | let (binding, generation) = |
| 1872 | codewhale_runtime::runtime_control::owner_work(move || capture.capture_control_owner()) |
| 1873 | .await?; |
| 1874 | #[cfg(unix)] |
| 1875 | let socket_directory = rig._dir.path().canonicalize()?.join("endpoint"); |
| 1876 | #[cfg(unix)] |
| 1877 | let _socket_directory = |
| 1878 | codewhale_config::private_directory::PrivateDirectory::open(&socket_directory)?; |
| 1879 | #[cfg(unix)] |
| 1880 | let socket_path = socket_directory.join("acp-owner.sock"); |
| 1881 | #[cfg(windows)] |
| 1882 | let socket_path = PathBuf::from(format!( |
| 1883 | r"\\.\pipe\codewhale-acp-test-{}", |
| 1884 | uuid::Uuid::new_v4() |
| 1885 | )); |
| 1886 | #[cfg(unix)] |
| 1887 | let principal = |
| 1888 | codewhale_config::private_directory::PrivateDirectory::current_user_id().to_string(); |
| 1889 | #[cfg(windows)] |
| 1890 | let principal = codewhale_runtime::runtime_control::owner_work(|| { |
| 1891 | codewhale_config::windows_identity::CurrentWindowsUser::open()?.sid_string() |
| 1892 | }) |
| 1893 | .await?; |
| 1894 | let receipt = codewhale_protocol::RuntimeOwnerReceipt { |
| 1895 | version: 1, |
| 1896 | data_dir: binding.data_dir, |
| 1897 | execution_scope: binding.execution_scope, |
| 1898 | lease_generation: generation, |
| 1899 | pid: std::process::id(), |
| 1900 | process_start: crate::daemon_socket::capture_process_start(std::process::id()).await?, |
| 1901 | principal, |
| 1902 | socket_path: socket_path.clone(), |
| 1903 | config_path: None, |
| 1904 | }; |
| 1905 | let frontend = capture_frontend( |
| 1906 | config, |
| 1907 | "fixture-model".into(), |
| 1908 | rig.workspace.clone(), |
| 1909 | manager.clone(), |
| 1910 | rig.server.sessions_dir.clone(), |
| 1911 | None, |
| 1912 | None, |
| 1913 | )?; |
| 1914 | // ACP calls the held manager directly through its captured projection; |
| 1915 | // this closed endpoint has no fake HTTP service and is never used. |
| 1916 | let (daemon, _state) = crate::bind_runtime_frontends( |
| 1917 | None, |
| 1918 | None, |
| 1919 | receipt.clone(), |
| 1920 | crate::RuntimeOwnerRouting { |
| 1921 | workers: None, |
| 1922 | workspace: Some(rig.workspace.clone()), |
| 1923 | endpoint: "127.0.0.1:1".parse()?, |
| 1924 | mobile: false, |
| 1925 | web: false, |
| 1926 | acp: true, |
| 1927 | acp_only: base_acp, |
| 1928 | }, |
| 1929 | Some(frontend), |
| 1930 | None, |
| 1931 | ) |
| 1932 | .await?; |
| 1933 | // ACP publications are discovered through this socket, so an |
| 1934 | // unbound one is a failure here rather than a degraded start. |
| 1935 | let daemon = daemon.ok_or_else(|| { |
| 1936 | anyhow!("this filesystem cannot hold the private runtime endpoint directory") |
| 1937 | })?; |
| 1938 | let shutdown = daemon.shutdown_handle(); |
| 1939 | let owner = tokio::spawn(daemon.serve()); |
| 1940 | let _abort = AbortOnDrop(owner.abort_handle()); |
| 1941 | let mut guest = |
| 1942 | crate::daemon_client::connect_acp_if_published(None, Some(socket_path.clone())) |
| 1943 | .await? |
| 1944 | .ok_or_else(|| anyhow!("published ACP owner unavailable"))?; |
| 1945 | assert_eq!(guest.receipt(), &receipt); |
| 1946 | assert!(guest.routing().is_some_and(|routing| routing.acp)); |
| 1947 | guest |
| 1948 | .send( |
| 1949 | json!(1), |
| 1950 | "initialize", |
| 1951 | json!({"protocolVersion":1,"clientCapabilities":{}}), |
| 1952 | ) |
| 1953 | .await?; |
| 1954 | assert!(correlated(&mut guest, json!(1)).await?["error"].is_null()); |
| 1955 | guest |
| 1956 | .send(json!(2), "session/new", json!({"cwd":rig.workspace})) |
| 1957 | .await?; |
| 1958 | let created = correlated(&mut guest, json!(2)).await?; |
| 1959 | let session = created["result"]["sessionId"] |
| 1960 | .as_str() |
| 1961 | .ok_or_else(|| anyhow!("{created}"))? |
| 1962 | .to_string(); |
| 1963 | guest |
| 1964 | .send( |
| 1965 | json!(3), |
| 1966 | "session/prompt", |
| 1967 | json!({"sessionId":session,"prompt":"one actual turn"}), |
| 1968 | ) |
| 1969 | .await?; |
| 1970 | let completed = correlated(&mut guest, json!(3)).await?; |
| 1971 | assert_eq!(completed["result"]["stopReason"], "end_turn", "{completed}"); |
| 1972 | tokio::time::timeout( |
| 1973 | Duration::from_secs(5), |
| 1974 | guest.forward(tokio::io::empty(), tokio::io::sink()), |
| 1975 | ) |
| 1976 | .await??; |
| 1977 | let mut shutdown_guest = |
| 1978 | crate::daemon_client::connect_acp_if_published(None, Some(socket_path.clone())) |
| 1979 | .await? |
| 1980 | .ok_or_else(|| anyhow!("owner ended after guest EOF"))?; |
| 1981 | shutdown_guest.send(json!(4), "shutdown", json!({})).await?; |
| 1982 | let closed = correlated(&mut shutdown_guest, json!(4)).await?; |
| 1983 | assert!(closed["error"].is_null()); |
| 1984 | assert!( |
| 1985 | tokio::time::timeout(Duration::from_secs(5), shutdown_guest.recv()) |
| 1986 | .await?? |
| 1987 | .is_none(), |
| 1988 | "ACP shutdown closes only this connection" |
| 1989 | ); |
| 1990 | let rows = manager |
| 1991 | .list_threads( |
| 1992 | codewhale_engine::runtime_threads::manager::ThreadListFilter::IncludeArchived, |
| 1993 | None, |
| 1994 | ) |
| 1995 | .await?; |
| 1996 | assert_eq!(rows.len(), 1); |
| 1997 | let detail = manager.get_thread_detail(&rows[0].id).await?; |
| 1998 | assert_eq!(detail.turns.len(), 1); |
| 1999 | assert_eq!(rig.mock.call_count(), 1); |
| 2000 | if !base_acp { |
| 2001 | rig.mock |
| 2002 | .push_turn(canned::simple_text_turn("ordinary successor")); |
| 2003 | let ordinary = manager |
| 2004 | .start_turn( |
| 2005 | &rows[0].id, |
| 2006 | codewhale_engine::runtime_threads::manager::StartTurnRequest { |
| 2007 | prompt: "ordinary successor".into(), |
| 2008 | ..Default::default() |
| 2009 | }, |
| 2010 | ) |
| 2011 | .await?; |
| 2012 | tokio::time::timeout(Duration::from_secs(30), async { |
| 2013 | loop { |
| 2014 | let detail = manager.get_thread_detail(&rows[0].id).await?; |
| 2015 | if detail.turns.iter().any(|t| { |
| 2016 | t.id == ordinary.id |
| 2017 | && t.status |
| 2018 | == codewhale_engine::runtime_threads::RuntimeTurnStatus::Completed |
| 2019 | }) { |
| 2020 | return Ok::<_, anyhow::Error>(()); |
| 2021 | } |
| 2022 | tokio::time::sleep(Duration::from_millis(20)).await; |
| 2023 | } |
| 2024 | }) |
| 2025 | .await??; |
| 2026 | let requests = rig.mock.captured_requests(); |
| 2027 | assert_eq!(requests.len(), 2); |
| 2028 | let acp = requests[0] |
| 2029 | .tools |
| 2030 | .as_ref() |
| 2031 | .ok_or_else(|| anyhow!("ACP tools missing"))?; |
| 2032 | assert!(acp.iter().all(|tool| !matches!( |
| 2033 | tool.name.as_str(), |
| 2034 | "update_goal" |
| 2035 | | "create_goal" |
| 2036 | | "request_user_input" |
| 2037 | | "tool_search" |
| 2038 | | "spawn_agent" |
| 2039 | ))); |
| 2040 | let normal = requests[1] |
| 2041 | .tools |
| 2042 | .as_ref() |
| 2043 | .ok_or_else(|| anyhow!("ordinary tools missing"))?; |
| 2044 | assert_ne!( |
| 2045 | acp.iter().map(|t| &t.name).collect::<Vec<_>>(), |
| 2046 | normal.iter().map(|t| &t.name).collect::<Vec<_>>(), |
| 2047 | "ordinary successor must rebuild its ordinary catalog" |
| 2048 | ); |
| 2049 | assert_eq!(manager.get_thread_detail(&rows[0].id).await?.turns.len(), 2); |
| 2050 | } |
| 2051 | let capture = manager.clone(); |
| 2052 | let (after, generation) = |
| 2053 | codewhale_runtime::runtime_control::owner_work(move || capture.capture_control_owner()) |
| 2054 | .await?; |
| 2055 | assert_eq!(after.data_dir, receipt.data_dir); |
| 2056 | assert_eq!( |
| 2057 | generation, receipt.lease_generation, |
| 2058 | "guest EOF cannot release the host lease" |
| 2059 | ); |
| 2060 | shutdown.trigger(); |
| 2061 | tokio::time::timeout(Duration::from_secs(5), owner).await???; |
| 2062 | assert!( |
| 2063 | crate::daemon_client::connect_acp_if_published(None, Some(socket_path)) |
| 2064 | .await? |
| 2065 | .is_none(), |
| 2066 | "shutdown withdraws the authenticated owner receipt instead of advertising a guest" |
| 2067 | ); |
| 2068 | rig.close().await; |
| 2069 | Ok(()) |
| 2070 | } |
| 2071 | |
| 2072 | #[test] |
| 2073 | fn acp_approval_mode_derives_from_server_config() { |
| 2074 | // #6337: `--yolo --danger-full-access` must not silently run as Ask. |
| 2075 | let yolo = { |
| 2076 | let __cw_config_init_1_0 = Some(true); |
| 2077 | let mut __cw_config_init_1_value: Config = Config::default(); |
| 2078 | __cw_config_init_1_value.yolo = __cw_config_init_1_0; |
| 2079 | __cw_config_init_1_value |
| 2080 | }; |
| 2081 | assert_eq!(acp_approval_mode(&yolo), ApprovalMode::Bypass); |
| 2082 | let requirements = tempfile::tempdir().expect("requirements directory"); |
| 2083 | let requirements_path = requirements.path().join("requirements.toml"); |
| 2084 | std::fs::write( |
| 2085 | &requirements_path, |
| 2086 | "allowed_approval_policies = ['on-request']\n", |
| 2087 | ) |
| 2088 | .expect("requirements file"); |
| 2089 | let mut managed_yolo = Config::default(); |
| 2090 | managed_yolo.requirements_path = Some(requirements_path.display().to_string()); |
| 2091 | managed_yolo.yolo = Some(true); |
| 2092 | assert_eq!( |
| 2093 | acp_approval_mode(&managed_yolo), |
| 2094 | ApprovalMode::Suggest, |
| 2095 | "requirements must outrank the CLI Full Access override" |
| 2096 | ); |
| 2097 | let policy = { |
| 2098 | let __cw_config_init_2_0 = Some("never".into()); |
| 2099 | let mut __cw_config_init_2_value: Config = Config::default(); |
| 2100 | __cw_config_init_2_value.approval_policy = __cw_config_init_2_0; |
| 2101 | __cw_config_init_2_value |
| 2102 | }; |
| 2103 | assert_eq!(acp_approval_mode(&policy), ApprovalMode::Never); |
| 2104 | assert_eq!(acp_approval_mode(&Config::default()), ApprovalMode::Suggest); |
| 2105 | } |
| 2106 | |
| 2107 | #[test] |
| 2108 | fn initialize_advertises_baseline_acp_agent() { |
| 2109 | let result = to_wire(&initialize_result(&Config::default(), true)).unwrap(); |
| 2110 | |
| 2111 | assert_eq!(result["protocolVersion"], 1); |
| 2112 | assert_eq!(result["agentInfo"]["name"], "codewhale"); |
| 2113 | // #5864: enumerating and resuming durable Codewhale sessions is now |
| 2114 | // served, so the capability says so rather than declining it. |
| 2115 | // #5969: this test used to assert `list == true` and `load == true`, |
| 2116 | // certifying the wire format that broke every strictly-typed client. |
| 2117 | // `loadSession` is the top-level boolean that advertises |
| 2118 | // `session/load`; inside `sessionCapabilities` every field is a |
| 2119 | // capability *object*, and `load` is not a field at all. Comparing the |
| 2120 | // whole object pins both halves: a boolean `list` or a resurrected |
| 2121 | // `load` key fails here. |
| 2122 | assert_eq!(result["agentCapabilities"]["loadSession"], true); |
| 2123 | assert_eq!( |
| 2124 | result["agentCapabilities"]["sessionCapabilities"], |
| 2125 | json!({"list": {}}) |
| 2126 | ); |
| 2127 | assert!( |
| 2128 | result["agentCapabilities"]["sessionCapabilities"]["list"].is_object(), |
| 2129 | "sessionCapabilities.list must be a SessionListCapabilities object, got {}", |
| 2130 | result["agentCapabilities"]["sessionCapabilities"]["list"] |
| 2131 | ); |
| 2132 | assert_eq!( |
| 2133 | result["agentCapabilities"]["promptCapabilities"]["embeddedContext"], |
| 2134 | true |
| 2135 | ); |
| 2136 | assert_eq!(result["authMethods"][0]["type"], "terminal"); |
| 2137 | assert_eq!( |
| 2138 | result["authMethods"][0]["args"], |
| 2139 | json!(["auth", "set", "--provider", "deepseek"]) |
| 2140 | ); |
| 2141 | } |
| 2142 | |
| 2143 | #[test] |
| 2144 | fn initialize_stays_inside_the_official_capability_shape() { |
| 2145 | let result = to_wire(&initialize_result(&Config::default(), false)).unwrap(); |
| 2146 | |
| 2147 | assert!(result["agentCapabilities"].get("modelSelection").is_none()); |
| 2148 | assert_eq!(result["authMethods"], json!([])); |
| 2149 | assert_eq!(result["agentCapabilities"]["auth"], json!({})); |
| 2150 | } |
| 2151 | |
| 2152 | #[test] |
| 2153 | fn initialize_advertises_configured_plugins_and_mcp_but_not_client_servers() { |
| 2154 | let _policy = codewhale_plugins::activation::TestPolicyGuard::extension_host(true); |
| 2155 | let mut config = Config::default(); |
| 2156 | config.set_feature("extension_host", true).unwrap(); |
| 2157 | config.set_feature("mcp", true).unwrap(); |
| 2158 | let result = to_wire(&initialize_result(&config, false)).unwrap(); |
| 2159 | let meta = &result["agentCapabilities"]["_meta"]["codewhale"]; |
| 2160 | |
| 2161 | assert_eq!(meta["plugins"], true); |
| 2162 | assert_eq!(meta["configuredMcpServers"], true); |
| 2163 | assert_eq!(meta["clientMcpServers"], false); |
| 2164 | assert_eq!( |
| 2165 | result["agentCapabilities"]["mcpCapabilities"]["http"], |
| 2166 | false |
| 2167 | ); |
| 2168 | |
| 2169 | config.set_feature("extension_host", false).unwrap(); |
| 2170 | config.set_feature("mcp", false).unwrap(); |
| 2171 | let off = to_wire(&initialize_result(&config, false)).unwrap(); |
| 2172 | assert_eq!( |
| 2173 | off["agentCapabilities"]["_meta"]["codewhale"]["plugins"], |
| 2174 | false |
| 2175 | ); |
| 2176 | assert_eq!( |
| 2177 | off["agentCapabilities"]["_meta"]["codewhale"]["configuredMcpServers"], |
| 2178 | false |
| 2179 | ); |
| 2180 | } |
| 2181 | |
| 2182 | #[test] |
| 2183 | fn extract_prompt_text_accepts_text_and_resource_blocks() { |
| 2184 | let prompt = json!([ |
| 2185 | { "type": "text", "text": "Review this file" }, |
| 2186 | { |
| 2187 | "type": "resource", |
| 2188 | "resource": { |
| 2189 | "uri": "file:///tmp/app.rs", |
| 2190 | "mimeType": "text/rust", |
| 2191 | "text": "fn main() {}" |
| 2192 | } |
| 2193 | }, |
| 2194 | { "type": "resource_link", "uri": "file:///tmp/lib.rs" } |
| 2195 | ]); |
| 2196 | |
| 2197 | let text = extract_prompt_text(Some(&prompt)).expect("prompt text"); |
| 2198 | |
| 2199 | assert!(text.contains("Review this file")); |
| 2200 | assert!(text.contains("fn main() {}")); |
| 2201 | assert!(text.contains("@file:///tmp/lib.rs")); |
| 2202 | } |
| 2203 | |
| 2204 | #[tokio::test(flavor = "current_thread")] |
| 2205 | async fn the_connection_echoes_ids_and_answers_only_requests() -> Result<()> { |
| 2206 | let mut rig = Rig::new(fixture_config(), vec![])?; |
| 2207 | let (_, frames) = rig |
| 2208 | .drive(async |editor| { |
| 2209 | for info in [json!({}), json!({"clientInfo":{"name":"zed","version":"1"}})] { |
| 2210 | let mut params = json!({"protocolVersion":1,"clientCapabilities":{}}); |
| 2211 | params.as_object_mut().unwrap().extend(info.as_object().unwrap().clone()); |
| 2212 | let (reply, _) = editor.request("initialize", params).await?; |
| 2213 | assert!(reply["id"].is_number(), "{reply}"); |
| 2214 | } |
| 2215 | editor |
| 2216 | .send(json!({"jsonrpc":"2.0","method":"$/cancel_request","params":{"requestId":999}})) |
| 2217 | .await?; |
| 2218 | editor |
| 2219 | .send(json!({"jsonrpc":"2.0","method":"session/not_a_notification","params":{}})) |
| 2220 | .await?; |
| 2221 | editor.send_raw("not json").await?; |
| 2222 | let parse = editor.recv().await?; |
| 2223 | assert_eq!(parse["id"], Value::Null); |
| 2224 | assert_eq!(parse["error"]["code"], -32700); |
| 2225 | let (unknown, _) = editor.request("session/resume", json!({})).await?; |
| 2226 | assert_eq!(unknown["error"]["code"], -32601); |
| 2227 | Ok(()) |
| 2228 | }) |
| 2229 | .await?; |
| 2230 | assert!( |
| 2231 | frames |
| 2232 | .iter() |
| 2233 | .all(|frame| frame["id"].is_number() || frame["id"].is_null()), |
| 2234 | "{frames:?}" |
| 2235 | ); |
| 2236 | assert_eq!( |
| 2237 | frames.iter().filter(|frame| frame["id"].is_null()).count(), |
| 2238 | 1, |
| 2239 | "a notification is never answered: {frames:?}" |
| 2240 | ); |
| 2241 | rig.close().await; |
| 2242 | Ok(()) |
| 2243 | } |
| 2244 | |
| 2245 | #[tokio::test(flavor = "current_thread")] |
| 2246 | async fn an_oversize_line_is_refused_and_the_connection_continues() -> Result<()> { |
| 2247 | let mut rig = Rig::new(fixture_config(), vec![])?; |
| 2248 | let (_, _) = rig |
| 2249 | .drive(async |editor| { |
| 2250 | editor.send_raw(&"a".repeat(MAX_FRAME_BYTES + 16)).await?; |
| 2251 | let refused = editor.recv().await?; |
| 2252 | assert_eq!(refused["id"], Value::Null); |
| 2253 | assert_eq!(refused["error"]["code"], -32700); |
| 2254 | let (initialized, _) = editor |
| 2255 | .request("initialize", json!({"protocolVersion":1})) |
| 2256 | .await?; |
| 2257 | assert_eq!(initialized["result"]["protocolVersion"], 1); |
| 2258 | Ok(()) |
| 2259 | }) |
| 2260 | .await?; |
| 2261 | rig.close().await; |
| 2262 | Ok(()) |
| 2263 | } |
| 2264 | |
| 2265 | #[test] |
| 2266 | fn an_oversize_response_becomes_an_error_and_anything_else_ends_the_connection() { |
| 2267 | let big = "x".repeat(MAX_FRAME_BYTES); |
| 2268 | let response = json!({"jsonrpc":"2.0","id":7,"result":{"big":big}}).to_string(); |
| 2269 | let replaced: Value = |
| 2270 | serde_json::from_str(&connection::bound_outgoing(response).unwrap()).unwrap(); |
| 2271 | assert_eq!(replaced["id"], 7); |
| 2272 | assert_eq!(replaced["error"]["code"], -32603); |
| 2273 | let update = |
| 2274 | json!({"jsonrpc":"2.0","method":"session/update","params":{"big":big}}).to_string(); |
| 2275 | let error = connection::bound_outgoing(update).unwrap_err(); |
| 2276 | assert!(crate::stdio::is_frame_refusal(&error)); |
| 2277 | } |
| 2278 | |
| 2279 | #[tokio::test(flavor = "current_thread")] |
| 2280 | async fn the_session_cap_evicts_the_oldest_binding() -> Result<()> { |
| 2281 | let mut rig = Rig::new(fixture_config(), vec![])?; |
| 2282 | for index in 0..=MAX_ACP_SESSIONS { |
| 2283 | rig.server |
| 2284 | .remember(format!("session-{index}"), format!("thread-{index}")); |
| 2285 | } |
| 2286 | assert_eq!(rig.server.sessions.len(), MAX_ACP_SESSIONS); |
| 2287 | assert!(!rig.server.sessions.contains_key("session-0")); |
| 2288 | assert!( |
| 2289 | rig.server |
| 2290 | .sessions |
| 2291 | .contains_key(&format!("session-{MAX_ACP_SESSIONS}")) |
| 2292 | ); |
| 2293 | rig.close().await; |
| 2294 | Ok(()) |
| 2295 | } |
| 2296 | |
| 2297 | #[test] |
| 2298 | fn file_tool_start_preserves_requests_without_speculative_diffs() { |
| 2299 | let directory = tempfile::tempdir().expect("workspace"); |
| 2300 | let workspace = directory.path(); |
| 2301 | std::fs::create_dir(workspace.join("src")).expect("source directory"); |
| 2302 | std::fs::write(workspace.join("src/lib.rs"), "prefix a middle c suffix") |
| 2303 | .expect("existing file"); |
| 2304 | let at = |rel: &str| { |
| 2305 | codewhale_engine::tools::spec::normalize_path(&workspace.join(rel)) |
| 2306 | .to_string_lossy() |
| 2307 | .into_owned() |
| 2308 | }; |
| 2309 | let abs_new = codewhale_engine::tools::spec::normalize_path(&workspace.join("src/lib.rs")); |
| 2310 | let abs_new_str = abs_new.to_string_lossy().into_owned(); |
| 2311 | let start = |name: &str, input: Value| { |
| 2312 | to_wire(&tool_call_start( |
| 2313 | &PendingToolCall { |
| 2314 | execution_id: "call-1".to_string(), |
| 2315 | name: name.to_string(), |
| 2316 | input, |
| 2317 | }, |
| 2318 | workspace, |
| 2319 | None, |
| 2320 | )) |
| 2321 | .expect("ACP tool call") |
| 2322 | }; |
| 2323 | let edit = start( |
| 2324 | "File", |
| 2325 | json!({"action": "edit", "path": "src/lib.rs", "old_string": "a", "new_string": "b"}), |
| 2326 | ); |
| 2327 | assert_eq!(edit["locations"], json!([{"path": at("src/lib.rs")}])); |
| 2328 | assert_eq!(edit["title"], "File edit: src/lib.rs"); |
| 2329 | assert_eq!(edit["rawInput"]["old_string"], "a"); |
| 2330 | assert!(edit.get("content").is_none_or(|c| c == &json!([]))); |
| 2331 | let write = start("write_file", json!({"path": abs_new_str, "content": "hi"})); |
| 2332 | assert_eq!(write["locations"], json!([{"path": abs_new_str}])); |
| 2333 | assert!(write.get("content").is_none_or(|c| c == &json!([]))); |
| 2334 | assert_eq!(write["rawInput"]["content"], "hi"); |
| 2335 | let read = start("File", json!({"action": "read", "path": "README.md"})); |
| 2336 | assert_eq!(read["locations"], json!([{"path": at("README.md")}])); |
| 2337 | assert!(read.get("content").is_none_or(|c| c == &json!([]))); |
| 2338 | let shell = start("bash", json!({"command": "ls", "path": "x"})); |
| 2339 | assert!(shell.get("locations").is_none_or(|l| l == &json!([]))); |
| 2340 | let aliased = start("write", json!({"file_path": "a.txt", "content": "x"})); |
| 2341 | assert_eq!(aliased["locations"], json!([{"path": at("a.txt")}])); |
| 2342 | let completed = to_wire(&tool_call_update( |
| 2343 | &PendingToolCall { |
| 2344 | execution_id: "exec-edit".to_string(), |
| 2345 | name: "File".to_string(), |
| 2346 | input: json!({"action": "edit", "path": "src/lib.rs", "search": "a", "replace": "b"}), |
| 2347 | }, |
| 2348 | workspace, |
| 2349 | acp::ToolCallStatus::Completed, |
| 2350 | Some("edited"), |
| 2351 | &[], |
| 2352 | None, |
| 2353 | )) |
| 2354 | .expect("ACP update"); |
| 2355 | assert_eq!(completed["content"].as_array().unwrap().len(), 1); |
| 2356 | assert_eq!(completed["content"][0]["content"]["text"], "edited"); |
| 2357 | let home = codewhale_paths::user_home().expect("home"); |
| 2358 | let home_edit = start( |
| 2359 | "File", |
| 2360 | json!({"action": "edit", "path": "~/notes.txt", "old_string": "a", "new_string": "b"}), |
| 2361 | ); |
| 2362 | let expected_home_note = |
| 2363 | codewhale_engine::tools::spec::normalize_path(&home.join("notes.txt")); |
| 2364 | assert_eq!( |
| 2365 | home_edit["locations"], |
| 2366 | json!([{"path": expected_home_note.to_string_lossy()}]) |
| 2367 | ); |
| 2368 | let edits_array = start( |
| 2369 | "edit", |
| 2370 | json!({"path": "src/lib.rs", "edits": [ |
| 2371 | {"oldText": "a", "newText": "b"}, |
| 2372 | {"oldText": "c", "newText": "d"} |
| 2373 | ]}), |
| 2374 | ); |
| 2375 | assert!(edits_array.get("content").is_none_or(|c| c == &json!([]))); |
| 2376 | assert_eq!( |
| 2377 | edits_array["rawInput"]["edits"].as_array().unwrap().len(), |
| 2378 | 2 |
| 2379 | ); |
| 2380 | let encoded = start( |
| 2381 | "edit", |
| 2382 | json!({"path": "src/lib.rs", "edits": "[{\"oldText\":\"a\",\"newText\":\"b\"}]"}), |
| 2383 | ); |
| 2384 | assert!(encoded.get("content").is_none_or(|c| c == &json!([]))); |
| 2385 | let dotted = start( |
| 2386 | "File", |
| 2387 | json!({"action": "read", "path": "./sub/../README.md"}), |
| 2388 | ); |
| 2389 | assert_eq!(dotted["locations"], json!([{"path": at("README.md")}])); |
| 2390 | } |
| 2391 | |
| 2392 | #[test] |
| 2393 | fn external_tool_start_forwards_agent_locations_without_fabricated_diff() { |
| 2394 | let workspace = Path::new("/work/repo"); |
| 2395 | let start = to_wire(&tool_call_start( |
| 2396 | &PendingToolCall { |
| 2397 | execution_id: "call-1".to_string(), |
| 2398 | name: "File".to_string(), |
| 2399 | input: json!({"action": "edit", "path": "notes.txt", "edits": [{"oldText": "a", "newText": "b"}]}), |
| 2400 | }, |
| 2401 | workspace, |
| 2402 | Some(vec![acp::ToolCallLocation::new(Path::new( |
| 2403 | "/other/agent-workspace/notes.txt", |
| 2404 | ))]), |
| 2405 | )) |
| 2406 | .expect("ACP tool call"); |
| 2407 | assert_eq!( |
| 2408 | start["locations"], |
| 2409 | json!([{"path": "/other/agent-workspace/notes.txt"}]) |
| 2410 | ); |
| 2411 | assert!(start["content"].as_array().is_none_or(|c| c.is_empty())); |
| 2412 | let suppressed = to_wire(&tool_call_update( |
| 2413 | &PendingToolCall { |
| 2414 | execution_id: "call-1".to_string(), |
| 2415 | name: "File".to_string(), |
| 2416 | input: json!({"action": "edit", "path": "notes.txt", "edits": [{"oldText": "a", "newText": "b"}]}), |
| 2417 | }, |
| 2418 | workspace, |
| 2419 | acp::ToolCallStatus::Completed, |
| 2420 | Some("edited"), |
| 2421 | &[], |
| 2422 | Some(Vec::new()), |
| 2423 | )) |
| 2424 | .expect("ACP update"); |
| 2425 | assert!( |
| 2426 | suppressed["update"]["content"] |
| 2427 | .as_array() |
| 2428 | .is_none_or(|c| c.iter().all(|block| block["type"] != "diff")) |
| 2429 | ); |
| 2430 | } |
| 2431 | |
| 2432 | #[test] |
| 2433 | fn tool_update_emits_typed_acp_image_content() { |
| 2434 | let call = PendingToolCall { |
| 2435 | execution_id: uuid::Uuid::new_v4().to_string(), |
| 2436 | name: "read".to_string(), |
| 2437 | input: json!({"path": "shot.png"}), |
| 2438 | }; |
| 2439 | let update = to_wire(&tool_call_update( |
| 2440 | &call, |
| 2441 | Path::new("/"), |
| 2442 | acp::ToolCallStatus::Completed, |
| 2443 | Some("screenshot captured"), |
| 2444 | &[codewhale_tools::ToolResultContentBlock::Image { |
| 2445 | mime_type: "image/png".to_string(), |
| 2446 | data: "QUJD".to_string(), |
| 2447 | }], |
| 2448 | None, |
| 2449 | )) |
| 2450 | .expect("ACP update"); |
| 2451 | let content = update["content"].as_array().expect("ACP content blocks"); |
| 2452 | assert_eq!(content[0]["content"]["type"], "text"); |
| 2453 | assert_eq!(content[1]["content"]["type"], "image"); |
| 2454 | assert_eq!(content[1]["content"]["mimeType"], "image/png"); |
| 2455 | assert_eq!(content[1]["content"]["data"], "QUJD"); |
| 2456 | } |
| 2457 | |
| 2458 | #[tokio::test(flavor = "current_thread")] |
| 2459 | async fn new_session_returns_durable_bare_uuid_without_provider_or_history() -> Result<()> { |
| 2460 | let mut rig = Rig::new(fixture_config(), vec![])?; |
| 2461 | for servers in [ |
| 2462 | json!([{"name":"fixture","command":"must-not-execute","args":[],"env":[]}]), |
| 2463 | json!({}), |
| 2464 | Value::Null, |
| 2465 | ] { |
| 2466 | let error = rig |
| 2467 | .server |
| 2468 | .new_session(json!({"mcpServers":servers})) |
| 2469 | .await |
| 2470 | .unwrap_err(); |
| 2471 | assert_eq!(error.code, -32602); |
| 2472 | assert!(rig.server.sessions.is_empty()); |
| 2473 | assert!(rig.server.insertion_order.is_empty()); |
| 2474 | } |
| 2475 | let id = rig.new_session().await; |
| 2476 | uuid::Uuid::parse_str(&id)?; |
| 2477 | let store = codewhale_engine::session_manager::SessionManager::new( |
| 2478 | rig.server.sessions_dir.clone(), |
| 2479 | )?; |
| 2480 | let saved = store.load_session(&id)?; |
| 2481 | assert!(saved.messages.is_empty()); |
| 2482 | assert_eq!( |
| 2483 | saved.metadata.runtime_store.as_ref(), |
| 2484 | Some(&rig.server.runtime.session_store_binding()) |
| 2485 | ); |
| 2486 | let thread = rig.server.sessions[&id].thread_id.clone(); |
| 2487 | assert_eq!( |
| 2488 | rig.server |
| 2489 | .runtime |
| 2490 | .get_thread(&thread) |
| 2491 | .await? |
| 2492 | .session_id |
| 2493 | .as_deref(), |
| 2494 | Some(id.as_str()) |
| 2495 | ); |
| 2496 | assert_eq!(rig.mock.call_count(), 0); |
| 2497 | for requested in [id.as_str(), &id[..8]] { |
| 2498 | let error = rig.server.load_session(json!({"sessionId":requested,"mcpServers":[{"name":"fixture","command":"must-not-execute","args":[],"env":[]}]})).await.unwrap_err(); |
| 2499 | assert_eq!(error.code, -32602); |
| 2500 | assert_eq!(rig.server.sessions.len(), 1); |
| 2501 | assert_eq!(rig.mock.call_count(), 0); |
| 2502 | } |
| 2503 | let loaded = rig |
| 2504 | .server |
| 2505 | .load_session(json!({"sessionId":&id[..8]})) |
| 2506 | .await |
| 2507 | .unwrap(); |
| 2508 | assert_eq!(loaded["sessionId"], id); |
| 2509 | assert_eq!(rig.server.sessions.len(), 1); |
| 2510 | assert_eq!(rig.server.insertion_order.len(), 1); |
| 2511 | assert!( |
| 2512 | rig.server |
| 2513 | .load_session(json!({"sessionId":uuid::Uuid::new_v4().to_string()})) |
| 2514 | .await |
| 2515 | .is_err() |
| 2516 | ); |
| 2517 | rig.close().await; |
| 2518 | Ok(()) |
| 2519 | } |
| 2520 | #[tokio::test(flavor = "current_thread")] |
| 2521 | async fn canonical_sessions_keep_independent_history_and_scoped_configuration() -> Result<()> { |
| 2522 | let mut rig = Rig::new( |
| 2523 | fixture_config(), |
| 2524 | vec![ |
| 2525 | canned::simple_text_turn("A answer"), |
| 2526 | canned::simple_text_turn("B answer"), |
| 2527 | ], |
| 2528 | )?; |
| 2529 | let a = rig.new_session().await; |
| 2530 | let b = rig.new_session().await; |
| 2531 | rig.server |
| 2532 | .set_session_config(json!({"sessionId":a,"configId":"mode","value":"plan"})) |
| 2533 | .await |
| 2534 | .unwrap(); |
| 2535 | assert_eq!( |
| 2536 | rig.server.session_configuration(&a).await.unwrap()["modes"]["currentModeId"], |
| 2537 | "plan" |
| 2538 | ); |
| 2539 | assert_eq!( |
| 2540 | rig.server.session_configuration(&b).await.unwrap()["modes"]["currentModeId"], |
| 2541 | "agent" |
| 2542 | ); |
| 2543 | assert!( |
| 2544 | rig.server |
| 2545 | .set_session_config( |
| 2546 | json!({"sessionId":a,"configId":"permission","value":"full-access"}) |
| 2547 | ) |
| 2548 | .await |
| 2549 | .is_err() |
| 2550 | ); |
| 2551 | assert!( |
| 2552 | rig.server |
| 2553 | .set_session_config(json!({"sessionId":a,"configId":"mode","value":"fabricated"})) |
| 2554 | .await |
| 2555 | .is_err() |
| 2556 | ); |
| 2557 | assert_eq!(rig.prompt(&a, "A prompt").await?.0, "end_turn"); |
| 2558 | assert_eq!(rig.prompt(&b, "B prompt").await?.0, "end_turn"); |
| 2559 | let ah = serde_json::to_string(&rig.history(&a).await)?; |
| 2560 | let bh = serde_json::to_string(&rig.history(&b).await)?; |
| 2561 | assert!(ah.contains("A prompt") && ah.contains("A answer") && !ah.contains("B prompt")); |
| 2562 | assert!(bh.contains("B prompt") && bh.contains("B answer") && !bh.contains("A prompt")); |
| 2563 | for (session, prompt, answer) in |
| 2564 | [(&a, "A prompt", "A answer"), (&b, "B prompt", "B answer")] |
| 2565 | { |
| 2566 | let updates = replayed(rig.server.history_updates(session).await?); |
| 2567 | let text: Vec<_> = updates |
| 2568 | .iter() |
| 2569 | .map(|update| { |
| 2570 | ( |
| 2571 | update["params"]["update"]["sessionUpdate"] |
| 2572 | .as_str() |
| 2573 | .unwrap(), |
| 2574 | update["params"]["update"]["content"]["text"] |
| 2575 | .as_str() |
| 2576 | .unwrap(), |
| 2577 | ) |
| 2578 | }) |
| 2579 | .collect(); |
| 2580 | assert_eq!( |
| 2581 | text, |
| 2582 | vec![ |
| 2583 | ("user_message_chunk", prompt), |
| 2584 | ("agent_message_chunk", answer) |
| 2585 | ] |
| 2586 | ); |
| 2587 | } |
| 2588 | let listed = rig |
| 2589 | .server |
| 2590 | .list_sessions(json!({"cwd":rig.workspace})) |
| 2591 | .await |
| 2592 | .unwrap(); |
| 2593 | assert_eq!(listed["sessions"].as_array().unwrap().len(), 2); |
| 2594 | let store = codewhale_engine::session_manager::SessionManager::new( |
| 2595 | rig.server.sessions_dir.clone(), |
| 2596 | )?; |
| 2597 | let mut saved = store.load_session(&a)?; |
| 2598 | saved.messages = serde_json::from_value(json!([ |
| 2599 | {"role":"user","content":[ |
| 2600 | {"type":"text","text":""}, |
| 2601 | {"type":"text","text":"alpha"}, |
| 2602 | {"type":"text","text":"<turn_meta>hidden middle</turn_meta>"}, |
| 2603 | {"type":"text","text":"beta"}, |
| 2604 | {"type":"thinking","thinking":"(reasoning omitted)"}, |
| 2605 | {"type":"text","text":"gamma"}, |
| 2606 | {"type":"thinking","thinking":"private reasoning"}, |
| 2607 | {"type":"text","text":"delta"}, |
| 2608 | {"type":"tool_use","id":"saved-plan","name":"update_plan","input":{}}, |
| 2609 | {"type":"text","text":"epsilon"}, |
| 2610 | {"type":"text","text":"[tool_history_repair] hidden repair"}, |
| 2611 | {"type":"text","text":"zeta"}, |
| 2612 | {"type":"text","text":"<turn_meta>hidden tail</turn_meta>"} |
| 2613 | ]}, |
| 2614 | {"role":"assistant","content":[ |
| 2615 | {"type":"text","text":"before archive"}, |
| 2616 | {"type":"text","text":"<archived_context level=\"1\">summary</archived_context>"}, |
| 2617 | {"type":"text","text":"after archive"}, |
| 2618 | {"type":"text","text":"<archived_context</archived_context>"}, |
| 2619 | {"type":"tool_use","id":"saved-read","name":"read","input":{}}, |
| 2620 | {"type":"text","text":"tail"} |
| 2621 | ]}, |
| 2622 | {"role":"user","content":[ |
| 2623 | {"type":"text","text":"<turn_meta>literal example</turn_meta>"} |
| 2624 | ]}, |
| 2625 | {"role":"assistant_interrupted","content":[ |
| 2626 | {"type":"text","text":"interrupted answer"} |
| 2627 | ]} |
| 2628 | ]))?; |
| 2629 | saved |
| 2630 | .messages |
| 2631 | .push(codewhale_engine::runtime_handoff::operate_contract_runtime_message()); |
| 2632 | saved.messages.extend( |
| 2633 | codewhale_engine::runtime_handoff::project_owned_messages_for_restore(vec![ |
| 2634 | codewhale_engine::runtime_handoff::subagent_completion_runtime_message("{}"), |
| 2635 | ]), |
| 2636 | ); |
| 2637 | store.save_session(&saved)?; |
| 2638 | let updates = replayed(rig.server.history_updates(&a).await?); |
| 2639 | let text: Vec<_> = updates |
| 2640 | .iter() |
| 2641 | .filter_map(|update| { |
| 2642 | let kind = update["params"]["update"]["sessionUpdate"].as_str()?; |
| 2643 | matches!(kind, "user_message_chunk" | "agent_message_chunk").then(|| { |
| 2644 | ( |
| 2645 | kind, |
| 2646 | update["params"]["update"]["content"]["text"] |
| 2647 | .as_str() |
| 2648 | .unwrap(), |
| 2649 | ) |
| 2650 | }) |
| 2651 | }) |
| 2652 | .collect(); |
| 2653 | assert_eq!( |
| 2654 | text, |
| 2655 | vec![ |
| 2656 | ("user_message_chunk", "alpha\nbeta\ngamma"), |
| 2657 | ("user_message_chunk", "delta"), |
| 2658 | ("user_message_chunk", "epsilon"), |
| 2659 | ("user_message_chunk", "zeta"), |
| 2660 | ("agent_message_chunk", "before archive"), |
| 2661 | ( |
| 2662 | "agent_message_chunk", |
| 2663 | "after archive\n<archived_context</archived_context>\ntail" |
| 2664 | ), |
| 2665 | ( |
| 2666 | "user_message_chunk", |
| 2667 | "<turn_meta>literal example</turn_meta>" |
| 2668 | ), |
| 2669 | ] |
| 2670 | ); |
| 2671 | rig.close().await; |
| 2672 | Ok(()) |
| 2673 | } |
| 2674 | #[tokio::test(flavor = "current_thread")] |
| 2675 | async fn agentic_turn_chains_real_write_read_and_retains_full_core_pairs() -> Result<()> { |
| 2676 | let mut config = fixture_config(); |
| 2677 | config.yolo = Some(true); |
| 2678 | let mut rig = Rig::new( |
| 2679 | config, |
| 2680 | vec![ |
| 2681 | canned::tool_call_turn( |
| 2682 | "provider-write", |
| 2683 | "write", |
| 2684 | r#"{"path":"receipt.txt","content":"full receipt"}"#, |
| 2685 | ), |
| 2686 | canned::tool_call_turn("provider-read", "read", r#"{"path":"receipt.txt"}"#), |
| 2687 | canned::simple_text_turn("done"), |
| 2688 | ], |
| 2689 | )?; |
| 2690 | let id = rig.new_session().await; |
| 2691 | let (reason, wire) = rig.prompt(&id, "write then read").await?; |
| 2692 | assert_eq!(reason, "end_turn"); |
| 2693 | assert_eq!( |
| 2694 | std::fs::read_to_string(rig.workspace.join("receipt.txt"))?, |
| 2695 | "full receipt" |
| 2696 | ); |
| 2697 | assert!( |
| 2698 | !wire |
| 2699 | .iter() |
| 2700 | .any(|v| v["method"] == "session/request_permission") |
| 2701 | ); |
| 2702 | let statuses: Vec<_> = wire |
| 2703 | .iter() |
| 2704 | .filter_map(|v| { |
| 2705 | v.pointer("/params/update/status") |
| 2706 | .and_then(Value::as_str) |
| 2707 | .or_else(|| { |
| 2708 | (v.pointer("/params/update/sessionUpdate") == Some(&json!("tool_call"))) |
| 2709 | .then_some("pending") |
| 2710 | }) |
| 2711 | }) |
| 2712 | .collect(); |
| 2713 | assert_eq!( |
| 2714 | statuses, |
| 2715 | vec![ |
| 2716 | "pending", |
| 2717 | "in_progress", |
| 2718 | "completed", |
| 2719 | "pending", |
| 2720 | "in_progress", |
| 2721 | "completed" |
| 2722 | ] |
| 2723 | ); |
| 2724 | let history = rig.history(&id).await; |
| 2725 | let uses = history |
| 2726 | .iter() |
| 2727 | .flat_map(|m| &m.content) |
| 2728 | .filter(|b| matches!(b, ContentBlock::ToolUse { .. })) |
| 2729 | .count(); |
| 2730 | let results = history |
| 2731 | .iter() |
| 2732 | .flat_map(|m| &m.content) |
| 2733 | .filter(|b| matches!(b, ContentBlock::ToolResult { .. })) |
| 2734 | .count(); |
| 2735 | assert_eq!(uses, 2); |
| 2736 | assert_eq!(results, 2); |
| 2737 | let saved = codewhale_engine::session_manager::SessionManager::new( |
| 2738 | rig.server.sessions_dir.clone(), |
| 2739 | )? |
| 2740 | .load_session(&id)?; |
| 2741 | assert_eq!( |
| 2742 | saved.messages, history, |
| 2743 | "checkpoint is the full Engine snapshot, not display chunks" |
| 2744 | ); |
| 2745 | let request = rig.mock.captured_requests(); |
| 2746 | assert_eq!(request.len(), 3); |
| 2747 | assert!( |
| 2748 | request.iter().all( |
| 2749 | |r| r.tools.as_ref().is_some_and(|t| t.iter().all(|t| !matches!( |
| 2750 | t.name.as_str(), |
| 2751 | "code_execution" | "execute_tools" | "tool_search" | "task" | "subagent" |
| 2752 | ))) |
| 2753 | ) |
| 2754 | ); |
| 2755 | rig.close().await; |
| 2756 | Ok(()) |
| 2757 | } |
| 2758 | #[tokio::test(flavor = "current_thread")] |
| 2759 | async fn agentic_turn_preserves_core_partial_write_when_later_provider_fails() -> Result<()> { |
| 2760 | let mut config = fixture_config(); |
| 2761 | config.yolo = Some(true); |
| 2762 | let mut rig = Rig::new( |
| 2763 | config, |
| 2764 | vec![canned::tool_call_turn( |
| 2765 | "partial", |
| 2766 | "write", |
| 2767 | r#"{"path":"partial.txt","content":"completed effect"}"#, |
| 2768 | )], |
| 2769 | )?; |
| 2770 | rig.mock.push_error("fixture terminal provider refusal"); |
| 2771 | let id = rig.new_session().await; |
| 2772 | let error = rig.prompt(&id, "write then fail").await.unwrap_err(); |
| 2773 | assert!(!error.to_string().is_empty()); |
| 2774 | assert_eq!( |
| 2775 | std::fs::read_to_string(rig.workspace.join("partial.txt"))?, |
| 2776 | "completed effect" |
| 2777 | ); |
| 2778 | let history = rig.history(&id).await; |
| 2779 | assert!( |
| 2780 | history |
| 2781 | .iter() |
| 2782 | .flat_map(|m| &m.content) |
| 2783 | .any(|b| matches!(b, ContentBlock::ToolResult { .. })) |
| 2784 | ); |
| 2785 | let saved = codewhale_engine::session_manager::SessionManager::new( |
| 2786 | rig.server.sessions_dir.clone(), |
| 2787 | )? |
| 2788 | .load_session(&id)?; |
| 2789 | assert_eq!(saved.messages, history); |
| 2790 | let detail = rig |
| 2791 | .server |
| 2792 | .runtime |
| 2793 | .get_thread_detail(&rig.server.sessions[&id].thread_id) |
| 2794 | .await?; |
| 2795 | assert_eq!( |
| 2796 | detail.turns.last().unwrap().status, |
| 2797 | codewhale_engine::runtime_threads::RuntimeTurnStatus::Failed |
| 2798 | ); |
| 2799 | rig.close().await; |
| 2800 | Ok(()) |
| 2801 | } |
| 2802 | #[tokio::test(flavor = "current_thread")] |
| 2803 | async fn core_prompt_is_stable_after_instruction_write_and_streams_each_text_delta() |
| 2804 | -> Result<()> { |
| 2805 | let mut config = fixture_config(); |
| 2806 | config.yolo = Some(true); |
| 2807 | let final_turn = vec![ |
| 2808 | canned::message_start("final"), |
| 2809 | canned::text_block_start(0), |
| 2810 | canned::text_delta(0, "hello"), |
| 2811 | canned::text_delta(0, " world"), |
| 2812 | canned::block_stop(0), |
| 2813 | canned::message_delta("end_turn", None), |
| 2814 | canned::message_stop(), |
| 2815 | ]; |
| 2816 | let mut rig = Rig::new( |
| 2817 | config, |
| 2818 | vec![ |
| 2819 | canned::tool_call_turn("law-read", "read", r#"{"path":"AGENTS.md"}"#), |
| 2820 | canned::tool_call_turn( |
| 2821 | "law-write", |
| 2822 | "write", |
| 2823 | r#"{"path":"AGENTS.md","content":"new-self-authored-law"}"#, |
| 2824 | ), |
| 2825 | final_turn, |
| 2826 | ], |
| 2827 | )?; |
| 2828 | std::fs::write(rig.workspace.join("AGENTS.md"), "initial-project-law")?; |
| 2829 | let id = rig.new_session().await; |
| 2830 | let (reason, wire) = rig.prompt(&id, "update instructions then answer").await?; |
| 2831 | assert_eq!(reason, "end_turn"); |
| 2832 | assert_eq!( |
| 2833 | std::fs::read_to_string(rig.workspace.join("AGENTS.md"))?, |
| 2834 | "new-self-authored-law" |
| 2835 | ); |
| 2836 | let requests = rig.mock.captured_requests(); |
| 2837 | assert_eq!(requests.len(), 3); |
| 2838 | assert_eq!( |
| 2839 | serde_json::to_vec(&requests[0].system)?, |
| 2840 | serde_json::to_vec(&requests[2].system)? |
| 2841 | ); |
| 2842 | let prompt = codewhale_engine::prompts::system_prompt_flat_text( |
| 2843 | requests[0].system.as_ref().unwrap(), |
| 2844 | ); |
| 2845 | assert!(prompt.contains(codewhale_engine::prompts::text::BASE_PROMPT.trim())); |
| 2846 | assert!(!prompt.contains("initial-project-law")); |
| 2847 | assert!(!prompt.contains("new-self-authored-law")); |
| 2848 | assert!(serde_json::to_string(&requests[0].messages)?.contains("initial-project-law")); |
| 2849 | let chunks: Vec<_> = wire |
| 2850 | .iter() |
| 2851 | .filter(|v| { |
| 2852 | v.pointer("/params/update/sessionUpdate") == Some(&json!("agent_message_chunk")) |
| 2853 | }) |
| 2854 | .filter_map(|v| { |
| 2855 | v.pointer("/params/update/content/text") |
| 2856 | .and_then(Value::as_str) |
| 2857 | }) |
| 2858 | .collect(); |
| 2859 | // Runtime may coalesce provider frames. ACP must project its durable |
| 2860 | // deltas once each, rather than inventing a second streaming source. |
| 2861 | let events = rig |
| 2862 | .server |
| 2863 | .runtime |
| 2864 | .events_since(&rig.server.sessions[&id].thread_id, None)?; |
| 2865 | let deltas: Vec<_> = events |
| 2866 | .iter() |
| 2867 | .filter(|event| { |
| 2868 | event.event == "item.delta" |
| 2869 | && event.payload["kind"].as_str() == Some("agent_message") |
| 2870 | }) |
| 2871 | .collect(); |
| 2872 | let canonical_chunks: Vec<_> = deltas |
| 2873 | .iter() |
| 2874 | .map(|event| event.payload["delta"].as_str().unwrap()) |
| 2875 | .collect(); |
| 2876 | assert!(!chunks.is_empty()); |
| 2877 | assert_eq!(chunks, canonical_chunks); |
| 2878 | assert_eq!(chunks.concat(), "hello world"); |
| 2879 | let completed = events |
| 2880 | .iter() |
| 2881 | .find(|event| event.event == "turn.completed") |
| 2882 | .unwrap(); |
| 2883 | assert!(deltas.iter().all(|event| event.seq < completed.seq)); |
| 2884 | let history = serde_json::to_string(&rig.history(&id).await)?; |
| 2885 | assert!(history.contains("hello world")); |
| 2886 | rig.close().await; |
| 2887 | Ok(()) |
| 2888 | } |
| 2889 | #[tokio::test(flavor = "current_thread")] |
| 2890 | async fn core_file_batch_orders_real_results_and_returns_missing_path_to_model() -> Result<()> { |
| 2891 | let mut events = vec![canned::message_start("file-batch")]; |
| 2892 | for (index, id, name, input) in [ |
| 2893 | (0, "list", "list_dir", r#"{"path":"."}"#), |
| 2894 | (1, "read", "read", r#"{"path":"present.txt"}"#), |
| 2895 | (2, "missing", "read", r#"{"path":"missing.txt"}"#), |
| 2896 | ] { |
| 2897 | events.extend([ |
| 2898 | canned::tool_use_block_start(index, id, name), |
| 2899 | canned::tool_input_delta(index, input), |
| 2900 | canned::block_stop(index), |
| 2901 | ]); |
| 2902 | } |
| 2903 | events.extend([ |
| 2904 | canned::message_delta("tool_use", None), |
| 2905 | canned::message_stop(), |
| 2906 | ]); |
| 2907 | let mut rig = Rig::new( |
| 2908 | fixture_config(), |
| 2909 | vec![events, canned::simple_text_turn("handled file failure")], |
| 2910 | )?; |
| 2911 | std::fs::write(rig.workspace.join("present.txt"), "real-file-marker")?; |
| 2912 | let id = rig.new_session().await; |
| 2913 | let (reason, wire) = rig |
| 2914 | .prompt(&id, "list then read present and missing") |
| 2915 | .await?; |
| 2916 | assert_eq!(reason, "end_turn"); |
| 2917 | let statuses: Vec<_> = wire |
| 2918 | .iter() |
| 2919 | .filter_map(|v| { |
| 2920 | v.pointer("/params/update/status") |
| 2921 | .and_then(Value::as_str) |
| 2922 | .or_else(|| { |
| 2923 | (v.pointer("/params/update/sessionUpdate") == Some(&json!("tool_call"))) |
| 2924 | .then_some("pending") |
| 2925 | }) |
| 2926 | }) |
| 2927 | .collect(); |
| 2928 | assert_eq!( |
| 2929 | statuses, |
| 2930 | vec![ |
| 2931 | "pending", |
| 2932 | "pending", |
| 2933 | "pending", |
| 2934 | "in_progress", |
| 2935 | "completed", |
| 2936 | "in_progress", |
| 2937 | "completed", |
| 2938 | "in_progress", |
| 2939 | "failed" |
| 2940 | ] |
| 2941 | ); |
| 2942 | let requests = rig.mock.captured_requests(); |
| 2943 | assert_eq!(requests.len(), 2); |
| 2944 | let feedback = serde_json::to_string(&requests[1].messages)?; |
| 2945 | assert!( |
| 2946 | feedback.contains("present.txt") |
| 2947 | && feedback.contains("real-file-marker") |
| 2948 | && feedback.contains("missing.txt") |
| 2949 | ); |
| 2950 | assert!( |
| 2951 | requests[1] |
| 2952 | .messages |
| 2953 | .iter() |
| 2954 | .flat_map(|m| &m.content) |
| 2955 | .any(|b| matches!( |
| 2956 | b, |
| 2957 | ContentBlock::ToolResult { |
| 2958 | is_error: Some(true), |
| 2959 | .. |
| 2960 | } |
| 2961 | )) |
| 2962 | ); |
| 2963 | rig.close().await; |
| 2964 | Ok(()) |
| 2965 | } |
| 2966 | #[derive(Clone, Copy)] |
| 2967 | enum PermissionReply { |
| 2968 | AllowAfterWrong, |
| 2969 | ForeignCancelAndBusy, |
| 2970 | Reject, |
| 2971 | CancelLateAllow, |
| 2972 | Eof, |
| 2973 | } |
| 2974 | async fn permission_case(reply: PermissionReply) -> Result<()> { |
| 2975 | permission_case_with_base(reply, true).await |
| 2976 | } |
| 2977 | async fn permission_case_with_base(reply: PermissionReply, base_acp: bool) -> Result<()> { |
| 2978 | let mut rig = Rig::with_base( |
| 2979 | fixture_config(), |
| 2980 | vec![ |
| 2981 | canned::tool_call_turn( |
| 2982 | "provider-id-not-authority", |
| 2983 | "write", |
| 2984 | r#"{"path":"ask.txt","content":"allowed"}"#, |
| 2985 | ), |
| 2986 | canned::simple_text_turn("settled"), |
| 2987 | ], |
| 2988 | base_acp, |
| 2989 | )?; |
| 2990 | let id = rig.new_session().await; |
| 2991 | let thread = rig.server.sessions[&id].thread_id.clone(); |
| 2992 | let manager = Arc::clone(&rig.server.runtime); |
| 2993 | let target = rig.workspace.join("ask.txt"); |
| 2994 | let sid = id.clone(); |
| 2995 | let target_in = target.clone(); |
| 2996 | let (outcome, wire) = rig |
| 2997 | .drive(async |editor| { |
| 2998 | editor.next_id += 1; |
| 2999 | let prompt_id = json!(editor.next_id); |
| 3000 | editor |
| 3001 | .send(json!({"jsonrpc":"2.0","id":prompt_id,"method":"session/prompt","params":{"sessionId":sid,"prompt":"write under Ask"}})) |
| 3002 | .await?; |
| 3003 | let v = editor.until_permission().await?; |
| 3004 | assert!( |
| 3005 | v.pointer("/params/toolCall/content") |
| 3006 | .and_then(Value::as_array) |
| 3007 | .is_some_and(|content| { |
| 3008 | content.iter().any(|item| { |
| 3009 | item.pointer("/content/text") |
| 3010 | .and_then(Value::as_str) |
| 3011 | .is_some_and(|text| !text.is_empty()) |
| 3012 | }) |
| 3013 | }) |
| 3014 | ); |
| 3015 | let detail = manager.get_thread_detail(&thread).await?; |
| 3016 | let pending = detail |
| 3017 | .pending_approvals |
| 3018 | .first() |
| 3019 | .ok_or_else(|| anyhow!("actual pending approval missing"))?; |
| 3020 | assert_eq!( |
| 3021 | pending.tool_call_id.as_deref(), |
| 3022 | v.pointer("/params/toolCall/toolCallId") |
| 3023 | .and_then(Value::as_str) |
| 3024 | ); |
| 3025 | assert!(!target_in.exists()); |
| 3026 | assert!( |
| 3027 | !editor |
| 3028 | .seen |
| 3029 | .iter() |
| 3030 | .any(|v| v.pointer("/params/update/status") == Some(&json!("in_progress"))), |
| 3031 | "no dispatch before the real decision" |
| 3032 | ); |
| 3033 | let allow = json!({"outcome":{"outcome":"selected","optionId":"allow-once"}}); |
| 3034 | match reply { |
| 3035 | PermissionReply::AllowAfterWrong => { |
| 3036 | editor.send(json!({"jsonrpc":"2.0","id":"wrong-id","result":allow})).await?; |
| 3037 | tokio::time::sleep(Duration::from_millis(30)).await; |
| 3038 | assert!(!target_in.exists()); |
| 3039 | assert_eq!(manager.get_thread_detail(&thread).await?.pending_approvals.len(), 1); |
| 3040 | editor.send(json!({"jsonrpc":"2.0","id":v["id"],"result":allow})).await?; |
| 3041 | } |
| 3042 | PermissionReply::ForeignCancelAndBusy => { |
| 3043 | editor.send(json!({"jsonrpc":"2.0","id":41,"method":"session/cancel","params":{"sessionId":"foreign-session"}})).await?; |
| 3044 | editor.send(json!({"jsonrpc":"2.0","id":42,"method":"session/prompt","params":{"sessionId":sid,"prompt":"must not run"}})).await?; |
| 3045 | for expected in [41, 42] { |
| 3046 | let (response, _) = editor.until_response(&json!(expected)).await?; |
| 3047 | if expected == 41 { |
| 3048 | assert_eq!(response["result"], Value::Null); |
| 3049 | } else { |
| 3050 | assert_eq!(response["error"]["code"], -32603); |
| 3051 | } |
| 3052 | } |
| 3053 | assert!(!target_in.exists()); |
| 3054 | assert_eq!(manager.get_thread_detail(&thread).await?.pending_approvals.len(), 1); |
| 3055 | editor.send(json!({"jsonrpc":"2.0","id":v["id"],"result":allow})).await?; |
| 3056 | } |
| 3057 | PermissionReply::Reject => { |
| 3058 | editor.send(json!({"jsonrpc":"2.0","id":v["id"],"result":{"outcome":{"outcome":"selected","optionId":"fabricated"}}})).await?; |
| 3059 | } |
| 3060 | PermissionReply::Eof => { |
| 3061 | editor.write.shutdown().await?; |
| 3062 | } |
| 3063 | PermissionReply::CancelLateAllow => { |
| 3064 | editor.send(json!({"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":sid}})).await?; |
| 3065 | editor.send(json!({"jsonrpc":"2.0","id":v["id"],"result":allow})).await?; |
| 3066 | } |
| 3067 | } |
| 3068 | if !matches!(reply, PermissionReply::Eof) { |
| 3069 | editor.until_response(&prompt_id).await?; |
| 3070 | } |
| 3071 | Ok(prompt_id) |
| 3072 | }) |
| 3073 | .await?; |
| 3074 | let response = wire |
| 3075 | .iter() |
| 3076 | .find(|frame| frame["id"] == outcome && frame.get("method").is_none()) |
| 3077 | .ok_or_else(|| anyhow!("the prompt was never answered: {wire:?}"))?; |
| 3078 | let result = response["result"]["stopReason"] |
| 3079 | .as_str() |
| 3080 | .ok_or_else(|| anyhow!("{response}")); |
| 3081 | match reply { |
| 3082 | PermissionReply::AllowAfterWrong | PermissionReply::ForeignCancelAndBusy => { |
| 3083 | assert_eq!(result?, "end_turn"); |
| 3084 | assert_eq!(std::fs::read_to_string(&target)?, "allowed"); |
| 3085 | assert_eq!( |
| 3086 | wire.iter() |
| 3087 | .filter( |
| 3088 | |v| v.pointer("/params/update/status") == Some(&json!("in_progress")) |
| 3089 | ) |
| 3090 | .count(), |
| 3091 | 1 |
| 3092 | ); |
| 3093 | } |
| 3094 | PermissionReply::Reject => { |
| 3095 | assert_eq!(result?, "end_turn"); |
| 3096 | assert!(!target.exists()); |
| 3097 | } |
| 3098 | PermissionReply::CancelLateAllow | PermissionReply::Eof => { |
| 3099 | assert_eq!(result?, "cancelled"); |
| 3100 | assert!(!target.exists()); |
| 3101 | } |
| 3102 | } |
| 3103 | let saved = codewhale_engine::session_manager::SessionManager::new( |
| 3104 | rig.server.sessions_dir.clone(), |
| 3105 | )? |
| 3106 | .load_session(&id)?; |
| 3107 | assert!(saved.messages.iter().any(|m| m.role == Role::User)); |
| 3108 | if !base_acp { |
| 3109 | let thread = rig.server.sessions[&id].thread_id.clone(); |
| 3110 | let successor = rig |
| 3111 | .server |
| 3112 | .runtime |
| 3113 | .start_turn( |
| 3114 | &thread, |
| 3115 | codewhale_engine::runtime_threads::manager::StartTurnRequest { |
| 3116 | prompt: "ordinary after cancelled ACP".into(), |
| 3117 | ..Default::default() |
| 3118 | }, |
| 3119 | ) |
| 3120 | .await?; |
| 3121 | wait_real_turn(&rig.server.runtime, &thread, &successor.id).await?; |
| 3122 | let requests = rig.mock.captured_requests(); |
| 3123 | assert_eq!( |
| 3124 | requests.len(), |
| 3125 | 2, |
| 3126 | "cancelled approval cannot replay the original model request" |
| 3127 | ); |
| 3128 | assert_ne!( |
| 3129 | requests[0].tools, requests[1].tools, |
| 3130 | "cancelled ACP narrowing must not leak into its ordinary successor" |
| 3131 | ); |
| 3132 | assert!( |
| 3133 | !target.exists(), |
| 3134 | "late allow cannot execute after cancellation" |
| 3135 | ); |
| 3136 | } |
| 3137 | rig.close().await; |
| 3138 | Ok(()) |
| 3139 | } |
| 3140 | #[tokio::test(flavor = "current_thread")] |
| 3141 | async fn normal_owner_acp_cancel_then_ordinary_successor_keeps_effects_and_profile_scoped() |
| 3142 | -> Result<()> { |
| 3143 | permission_case_with_base(PermissionReply::CancelLateAllow, false).await |
| 3144 | } |
| 3145 | |
| 3146 | async fn wait_real_turn( |
| 3147 | manager: &RuntimeThreadManager, |
| 3148 | thread: &str, |
| 3149 | turn: &str, |
| 3150 | ) -> Result<codewhale_engine::runtime_threads::TurnRecord> { |
| 3151 | tokio::time::timeout(Duration::from_secs(30), async { |
| 3152 | loop { |
| 3153 | let detail = manager.get_thread_detail(thread).await?; |
| 3154 | if let Some(record) = detail.turns.iter().find(|record| { |
| 3155 | record.id == turn |
| 3156 | && !matches!( |
| 3157 | record.status, |
| 3158 | codewhale_engine::runtime_threads::RuntimeTurnStatus::InProgress |
| 3159 | | codewhale_engine::runtime_threads::RuntimeTurnStatus::Queued |
| 3160 | ) |
| 3161 | }) && manager |
| 3162 | .events_since_async(thread, None) |
| 3163 | .await? |
| 3164 | .iter() |
| 3165 | .any(|event| { |
| 3166 | event.event == "turn.completed" && event.turn_id.as_deref() == Some(turn) |
| 3167 | }) |
| 3168 | { |
| 3169 | return Ok::<_, anyhow::Error>(record.clone()); |
| 3170 | } |
| 3171 | tokio::time::sleep(Duration::from_millis(20)).await; |
| 3172 | } |
| 3173 | }) |
| 3174 | .await? |
| 3175 | } |
| 3176 | |
| 3177 | #[tokio::test(flavor = "current_thread")] |
| 3178 | async fn real_normal_engine_acp_operation_replay_is_profile_bound_and_successor_is_ordinary() |
| 3179 | -> Result<()> { |
| 3180 | let mut rig = Rig::with_base( |
| 3181 | fixture_config(), |
| 3182 | vec![canned::simple_text_turn("ACP initial")], |
| 3183 | false, |
| 3184 | )?; |
| 3185 | let session = rig.new_session().await; |
| 3186 | let thread = rig.server.sessions[&session].thread_id.clone(); |
| 3187 | let request = codewhale_engine::runtime_threads::manager::StartTurnRequest { |
| 3188 | prompt: "same semantic request".into(), |
| 3189 | operation_key: Some("acp-operation".into()), |
| 3190 | ..Default::default() |
| 3191 | }; |
| 3192 | let first = rig |
| 3193 | .server |
| 3194 | .runtime |
| 3195 | .start_acp_turn(&thread, request.clone()) |
| 3196 | .await?; |
| 3197 | let replay = rig |
| 3198 | .server |
| 3199 | .runtime |
| 3200 | .start_acp_turn(&thread, request.clone()) |
| 3201 | .await?; |
| 3202 | assert_eq!(replay.id, first.id); |
| 3203 | assert!( |
| 3204 | rig.server |
| 3205 | .runtime |
| 3206 | .start_turn(&thread, request.clone()) |
| 3207 | .await |
| 3208 | .is_err(), |
| 3209 | "ordinary admission cannot redeem an ACP operation binding" |
| 3210 | ); |
| 3211 | assert_eq!( |
| 3212 | wait_real_turn(&rig.server.runtime, &thread, &first.id) |
| 3213 | .await? |
| 3214 | .status, |
| 3215 | codewhale_engine::runtime_threads::RuntimeTurnStatus::Completed |
| 3216 | ); |
| 3217 | assert_eq!( |
| 3218 | rig.mock.call_count(), |
| 3219 | 1, |
| 3220 | "exact replay executes the Engine once" |
| 3221 | ); |
| 3222 | rig.mock |
| 3223 | .push_turn(canned::simple_text_turn("ordinary initial")); |
| 3224 | let ordinary_request = codewhale_engine::runtime_threads::manager::StartTurnRequest { |
| 3225 | operation_key: Some("ordinary-operation".into()), |
| 3226 | ..request |
| 3227 | }; |
| 3228 | let ordinary = rig |
| 3229 | .server |
| 3230 | .runtime |
| 3231 | .start_turn(&thread, ordinary_request.clone()) |
| 3232 | .await?; |
| 3233 | assert!( |
| 3234 | rig.server |
| 3235 | .runtime |
| 3236 | .start_acp_turn(&thread, ordinary_request.clone()) |
| 3237 | .await |
| 3238 | .is_err(), |
| 3239 | "ACP admission cannot redeem an ordinary historical binding" |
| 3240 | ); |
| 3241 | assert_eq!( |
| 3242 | wait_real_turn(&rig.server.runtime, &thread, &ordinary.id) |
| 3243 | .await? |
| 3244 | .status, |
| 3245 | codewhale_engine::runtime_threads::RuntimeTurnStatus::Completed |
| 3246 | ); |
| 3247 | assert_eq!( |
| 3248 | rig.server |
| 3249 | .runtime |
| 3250 | .start_turn(&thread, ordinary_request) |
| 3251 | .await? |
| 3252 | .id, |
| 3253 | ordinary.id |
| 3254 | ); |
| 3255 | assert_eq!(rig.mock.call_count(), 2); |
| 3256 | assert_eq!( |
| 3257 | rig.server |
| 3258 | .runtime |
| 3259 | .get_thread_detail(&thread) |
| 3260 | .await? |
| 3261 | .turns |
| 3262 | .len(), |
| 3263 | 2 |
| 3264 | ); |
| 3265 | let requests = rig.mock.captured_requests(); |
| 3266 | assert_ne!( |
| 3267 | requests[0].tools, requests[1].tools, |
| 3268 | "ordinary successor must retain its own catalog" |
| 3269 | ); |
| 3270 | rig.close().await; |
| 3271 | Ok(()) |
| 3272 | } |
| 3273 | |
| 3274 | #[tokio::test(flavor = "current_thread")] |
| 3275 | async fn read_and_config_requests_are_served_while_a_turn_awaits_approval() -> Result<()> { |
| 3276 | let mut rig = Rig::new( |
| 3277 | fixture_config(), |
| 3278 | vec![ |
| 3279 | canned::tool_call_turn("w", "write", r#"{"path":"busy.txt","content":"x"}"#), |
| 3280 | canned::simple_text_turn("done"), |
| 3281 | ], |
| 3282 | )?; |
| 3283 | let id = rig.new_session().await; |
| 3284 | let (_, wire) = rig |
| 3285 | .drive(async |editor| { |
| 3286 | editor.next_id += 1; |
| 3287 | let prompt_id = json!(editor.next_id); |
| 3288 | editor |
| 3289 | .send(json!({"jsonrpc":"2.0","id":prompt_id,"method":"session/prompt","params":{"sessionId":id,"prompt":"write"}})) |
| 3290 | .await?; |
| 3291 | let permission = editor.until_permission().await?; |
| 3292 | let (listed, _) = editor.request("session/list", json!({})).await?; |
| 3293 | assert!(listed["result"]["sessions"].is_array(), "{listed}"); |
| 3294 | let (model, _) = editor |
| 3295 | .request("session/set_config_option", json!({"sessionId":id,"configId":"model","value":"fixture-model"})) |
| 3296 | .await?; |
| 3297 | assert!(model["result"]["configOptions"].is_array(), "{model}"); |
| 3298 | let (created, _) = editor.request("session/new", json!({})).await?; |
| 3299 | assert_eq!(created["error"]["code"], -32603); |
| 3300 | editor |
| 3301 | .send(json!({"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":id}})) |
| 3302 | .await?; |
| 3303 | editor |
| 3304 | .send(json!({"jsonrpc":"2.0","id":permission["id"],"result":{"outcome":{"outcome":"cancelled"}}})) |
| 3305 | .await?; |
| 3306 | let (done, _) = editor.until_response(&prompt_id).await?; |
| 3307 | assert_eq!(done["result"]["stopReason"], "cancelled"); |
| 3308 | Ok(()) |
| 3309 | }) |
| 3310 | .await?; |
| 3311 | assert!(!rig.workspace.join("busy.txt").exists()); |
| 3312 | assert!(!wire.is_empty()); |
| 3313 | rig.close().await; |
| 3314 | Ok(()) |
| 3315 | } |
| 3316 | #[tokio::test(flavor = "current_thread")] |
| 3317 | async fn acp_permission_allow_after_wrong_id_executes_once() -> Result<()> { |
| 3318 | permission_case(PermissionReply::AllowAfterWrong).await |
| 3319 | } |
| 3320 | #[tokio::test(flavor = "current_thread")] |
| 3321 | async fn foreign_cancel_and_busy_request_leave_the_same_core_approval_pending() -> Result<()> { |
| 3322 | permission_case(PermissionReply::ForeignCancelAndBusy).await |
| 3323 | } |
| 3324 | #[tokio::test(flavor = "current_thread")] |
| 3325 | async fn acp_permission_invalid_option_refuses_without_effect() -> Result<()> { |
| 3326 | permission_case(PermissionReply::Reject).await |
| 3327 | } |
| 3328 | #[tokio::test(flavor = "current_thread")] |
| 3329 | async fn acp_permission_cancel_ignores_late_allow_and_never_runs_tool() -> Result<()> { |
| 3330 | permission_case(PermissionReply::CancelLateAllow).await |
| 3331 | } |
| 3332 | #[tokio::test(flavor = "current_thread")] |
| 3333 | async fn plan_and_operator_floor_cannot_be_relaxed_by_full_access_or_client() -> Result<()> { |
| 3334 | let mut config = fixture_config(); |
| 3335 | config.yolo = Some(true); |
| 3336 | config.sandbox_mode = Some("read-only".into()); |
| 3337 | let mut rig = Rig::new( |
| 3338 | config, |
| 3339 | vec![ |
| 3340 | canned::tool_call_turn( |
| 3341 | "write-denied", |
| 3342 | "write", |
| 3343 | r#"{"path":"denied.txt","content":"forbidden"}"#, |
| 3344 | ), |
| 3345 | canned::simple_text_turn("read only"), |
| 3346 | ], |
| 3347 | )?; |
| 3348 | let id = rig.new_session().await; |
| 3349 | assert!( |
| 3350 | rig.server |
| 3351 | .set_session_config(json!({"sessionId":id,"configId":"mode","value":"agent"})) |
| 3352 | .await |
| 3353 | .is_err() |
| 3354 | ); |
| 3355 | let view = rig.server.session_configuration(&id).await.unwrap(); |
| 3356 | assert_eq!(view["modes"]["currentModeId"], "plan"); |
| 3357 | assert_eq!( |
| 3358 | view["configOptions"][2]["options"] |
| 3359 | .as_array() |
| 3360 | .unwrap() |
| 3361 | .len(), |
| 3362 | 1 |
| 3363 | ); |
| 3364 | let (_, wire) = rig.prompt(&id, "try write").await?; |
| 3365 | assert!(!rig.workspace.join("denied.txt").exists()); |
| 3366 | assert!( |
| 3367 | !wire |
| 3368 | .iter() |
| 3369 | .any(|v| v["method"] == "session/request_permission") |
| 3370 | ); |
| 3371 | rig.close().await; |
| 3372 | Ok(()) |
| 3373 | } |
| 3374 | #[tokio::test(flavor = "current_thread")] |
| 3375 | async fn acp_full_access_keeps_repo_law_without_permission_modal() -> Result<()> { |
| 3376 | let mut config = fixture_config(); |
| 3377 | config.approval_policy = Some("full-access".into()); |
| 3378 | config.allow_shell = Some(true); |
| 3379 | let mut rig = Rig::new( |
| 3380 | config, |
| 3381 | vec![ |
| 3382 | canned::tool_call_turn( |
| 3383 | "ordinary-write", |
| 3384 | "write", |
| 3385 | r#"{"path":"ordinary.txt","content":"allowed"}"#, |
| 3386 | ), |
| 3387 | // ACP reviews even foreground bash as Headless. Full Access |
| 3388 | // skips the deterministic floor, so the harmless fixture |
| 3389 | // writes its own sentinel instead of holding. |
| 3390 | canned::tool_call_turn( |
| 3391 | "floor-run", |
| 3392 | "bash", |
| 3393 | r#"{"command":"echo \"rm -rf /\" > floor-sentinel.txt"}"#, |
| 3394 | ), |
| 3395 | canned::tool_call_turn( |
| 3396 | "law-held", |
| 3397 | "write", |
| 3398 | r#"{"path":"CHANGELOG.md","content":"must not be written"}"#, |
| 3399 | ), |
| 3400 | canned::simple_text_turn("ordinary write completed; protected changes refused"), |
| 3401 | ], |
| 3402 | )?; |
| 3403 | std::fs::write(rig.workspace.join("floor-sentinel.txt"), "guarded\n")?; |
| 3404 | std::fs::create_dir_all(rig.workspace.join(".codewhale"))?; |
| 3405 | std::fs::write( |
| 3406 | rig.workspace.join(".codewhale/constitution.json"), |
| 3407 | r#"{"protected_invariants":[{"text":"Release notes need human review","paths":["CHANGELOG.md"]}]}"#, |
| 3408 | )?; |
| 3409 | let config_path = rig._dir.path().join("operator.toml"); |
| 3410 | std::fs::write( |
| 3411 | &config_path, |
| 3412 | "allow_shell = true\napproval_policy = \"full-access\"\n", |
| 3413 | )?; |
| 3414 | rig.server.config_path = Some(config_path); |
| 3415 | rig.server |
| 3416 | .handle_request( |
| 3417 | "initialize", |
| 3418 | json!({"protocolVersion":1,"clientCapabilities":{"terminal":true}}), |
| 3419 | ) |
| 3420 | .await |
| 3421 | .unwrap(); |
| 3422 | let session = rig.new_session().await; |
| 3423 | let (reason, wire) = rig |
| 3424 | .prompt(&session, "write ordinary and protected files") |
| 3425 | .await?; |
| 3426 | assert_eq!(reason, "end_turn"); |
| 3427 | assert_eq!( |
| 3428 | std::fs::read_to_string(rig.workspace.join("ordinary.txt"))?, |
| 3429 | "allowed" |
| 3430 | ); |
| 3431 | let sentinel = rig.workspace.join("floor-sentinel.txt"); |
| 3432 | for _ in 0..180 { |
| 3433 | if codewhale_engine::test_support::read_shell_sentinel(&sentinel) == "rm -rf /" { |
| 3434 | break; |
| 3435 | } |
| 3436 | tokio::time::sleep(std::time::Duration::from_millis(500)).await; |
| 3437 | } |
| 3438 | assert_eq!( |
| 3439 | codewhale_engine::test_support::read_shell_sentinel(&sentinel), |
| 3440 | "rm -rf /" |
| 3441 | ); |
| 3442 | assert!(!rig.workspace.join("CHANGELOG.md").exists()); |
| 3443 | assert!( |
| 3444 | !wire |
| 3445 | .iter() |
| 3446 | .any(|frame| frame["method"] == "session/request_permission") |
| 3447 | ); |
| 3448 | let statuses: Vec<_> = wire |
| 3449 | .iter() |
| 3450 | .filter_map(|frame| { |
| 3451 | frame |
| 3452 | .pointer("/params/update/status") |
| 3453 | .and_then(Value::as_str) |
| 3454 | }) |
| 3455 | .collect(); |
| 3456 | assert_eq!( |
| 3457 | statuses |
| 3458 | .iter() |
| 3459 | .filter(|status| **status == "in_progress") |
| 3460 | .count(), |
| 3461 | 2 |
| 3462 | ); |
| 3463 | assert_eq!( |
| 3464 | statuses |
| 3465 | .iter() |
| 3466 | .filter(|status| **status == "completed") |
| 3467 | .count(), |
| 3468 | 2 |
| 3469 | ); |
| 3470 | assert_eq!( |
| 3471 | statuses |
| 3472 | .iter() |
| 3473 | .filter(|status| **status == "failed") |
| 3474 | .count(), |
| 3475 | 1 |
| 3476 | ); |
| 3477 | let requests = rig.mock.captured_requests(); |
| 3478 | assert_eq!(requests.len(), 4, "no guardian or provider replay"); |
| 3479 | assert!( |
| 3480 | requests[0] |
| 3481 | .tools |
| 3482 | .iter() |
| 3483 | .flatten() |
| 3484 | .any(|tool| tool.name == "bash"), |
| 3485 | "the floor fixture must exercise an admitted shell tool" |
| 3486 | ); |
| 3487 | let history = rig.history(&session).await; |
| 3488 | for (request, call, error, refusal_reason) in [ |
| 3489 | (1, "ordinary-write", false, None), |
| 3490 | (2, "floor-run", false, None), |
| 3491 | (3, "law-held", true, Some("Release notes need human review")), |
| 3492 | ] { |
| 3493 | let results: Vec<_> = history |
| 3494 | .iter() |
| 3495 | .flat_map(|message| &message.content) |
| 3496 | .filter_map(|block| match block { |
| 3497 | ContentBlock::ToolResult { |
| 3498 | tool_use_id, |
| 3499 | content, |
| 3500 | is_error, |
| 3501 | .. |
| 3502 | } if tool_use_id == call => Some((content.as_str(), *is_error)), |
| 3503 | _ => None, |
| 3504 | }) |
| 3505 | .collect(); |
| 3506 | assert_eq!(results.len(), 1, "one paired result for {call}"); |
| 3507 | assert_eq!(results[0].1.unwrap_or(false), error, "{call}: {results:?}"); |
| 3508 | assert!(!results[0].0.is_empty(), "{call}"); |
| 3509 | let provider_results: Vec<_> = requests[request] |
| 3510 | .messages |
| 3511 | .iter() |
| 3512 | .flat_map(|message| &message.content) |
| 3513 | .filter_map(|block| match block { |
| 3514 | ContentBlock::ToolResult { |
| 3515 | tool_use_id, |
| 3516 | content, |
| 3517 | is_error, |
| 3518 | .. |
| 3519 | } if tool_use_id == call => Some((content.as_str(), *is_error)), |
| 3520 | _ => None, |
| 3521 | }) |
| 3522 | .collect(); |
| 3523 | assert_eq!( |
| 3524 | provider_results, results, |
| 3525 | "the next provider request must receive the exact paired Core result for {call}" |
| 3526 | ); |
| 3527 | if let Some(reason) = refusal_reason { |
| 3528 | assert!( |
| 3529 | provider_results[0].0.contains(reason), |
| 3530 | "{call} must report its actual policy hold: {provider_results:?}" |
| 3531 | ); |
| 3532 | } |
| 3533 | } |
| 3534 | let saved = codewhale_engine::session_manager::SessionManager::new( |
| 3535 | rig.server.sessions_dir.clone(), |
| 3536 | )? |
| 3537 | .load_session(&session)?; |
| 3538 | assert_eq!( |
| 3539 | saved.messages, history, |
| 3540 | "ACP persists the full paired Core history" |
| 3541 | ); |
| 3542 | let detail = rig |
| 3543 | .server |
| 3544 | .runtime |
| 3545 | .get_thread_detail(&rig.server.sessions[&session].thread_id) |
| 3546 | .await?; |
| 3547 | assert!(detail.pending_approvals.is_empty()); |
| 3548 | assert_eq!(detail.turns.len(), 1); |
| 3549 | assert_eq!( |
| 3550 | detail.turns[0].status, |
| 3551 | codewhale_engine::runtime_threads::RuntimeTurnStatus::Completed |
| 3552 | ); |
| 3553 | rig.close().await; |
| 3554 | Ok(()) |
| 3555 | } |
| 3556 | #[tokio::test(flavor = "current_thread")] |
| 3557 | async fn foreign_canonical_store_refuses_before_allocating_or_copying_history() -> Result<()> { |
| 3558 | let mut rig = Rig::new(fixture_config(), vec![])?; |
| 3559 | let id = rig.new_session().await; |
| 3560 | let store = codewhale_engine::session_manager::SessionManager::new( |
| 3561 | rig.server.sessions_dir.clone(), |
| 3562 | )?; |
| 3563 | let mut saved = store.load_session(&id)?; |
| 3564 | let path = store.save_session(&saved)?; |
| 3565 | let original = std::fs::read(&path)?; |
| 3566 | saved.metadata.runtime_store.as_mut().unwrap().data_dir = |
| 3567 | rig.workspace.join("foreign-owner"); |
| 3568 | let write_error = store.save_session(&saved).unwrap_err(); |
| 3569 | assert_eq!(write_error.kind(), std::io::ErrorKind::PermissionDenied); |
| 3570 | assert_eq!(std::fs::read(&path)?, original); |
| 3571 | // A normal writer rejects this binding. Inject a synthetic stale |
| 3572 | // document only into this private fixture to exercise load refusal. |
| 3573 | std::fs::write(&path, serde_json::to_vec_pretty(&saved)?)?; |
| 3574 | rig.server.sessions.clear(); |
| 3575 | rig.server.insertion_order.clear(); |
| 3576 | let before = rig |
| 3577 | .server |
| 3578 | .runtime |
| 3579 | .list_threads( |
| 3580 | codewhale_engine::runtime_threads::manager::ThreadListFilter::IncludeArchived, |
| 3581 | None, |
| 3582 | ) |
| 3583 | .await? |
| 3584 | .len(); |
| 3585 | let error = rig |
| 3586 | .server |
| 3587 | .load_session(json!({"sessionId":id})) |
| 3588 | .await |
| 3589 | .unwrap_err(); |
| 3590 | assert!(error.message.contains("secure owner attachment")); |
| 3591 | assert_eq!( |
| 3592 | rig.server |
| 3593 | .runtime |
| 3594 | .list_threads( |
| 3595 | codewhale_engine::runtime_threads::manager::ThreadListFilter::IncludeArchived, |
| 3596 | None |
| 3597 | ) |
| 3598 | .await? |
| 3599 | .len(), |
| 3600 | before |
| 3601 | ); |
| 3602 | assert_eq!(rig.mock.call_count(), 0); |
| 3603 | rig.close().await; |
| 3604 | Ok(()) |
| 3605 | } |
| 3606 | #[tokio::test(flavor = "current_thread")] |
| 3607 | async fn transport_eof_cancels_actual_turn_and_retains_checkpoint() -> Result<()> { |
| 3608 | permission_case(PermissionReply::Eof).await |
| 3609 | } |
| 3610 | #[tokio::test(flavor = "current_thread")] |
| 3611 | async fn real_image_tool_result_projects_typed_blocks_without_losing_core_history() -> Result<()> |
| 3612 | { |
| 3613 | use base64::Engine as _; |
| 3614 | let mut rig = Rig::new( |
| 3615 | fixture_config(), |
| 3616 | vec![ |
| 3617 | canned::tool_call_turn("image", "read", r#"{"path":"shot.png"}"#), |
| 3618 | canned::simple_text_turn("image read"), |
| 3619 | ], |
| 3620 | )?; |
| 3621 | let image = codewhale_engine::image_attach::test_support::runtime_image_fixture(21); |
| 3622 | std::fs::write( |
| 3623 | rig.workspace.join("shot.png"), |
| 3624 | base64::engine::general_purpose::STANDARD.decode(image.data_base64)?, |
| 3625 | )?; |
| 3626 | let id = rig.new_session().await; |
| 3627 | let (_, wire) = rig.prompt(&id, "read image").await?; |
| 3628 | assert!( |
| 3629 | wire.iter() |
| 3630 | .filter_map(|v| v |
| 3631 | .pointer("/params/update/content") |
| 3632 | .and_then(Value::as_array)) |
| 3633 | .flatten() |
| 3634 | .any(|block| block.pointer("/content/type") == Some(&json!("image"))) |
| 3635 | ); |
| 3636 | assert!(rig.history(&id).await.iter().flat_map(|m|&m.content).any(|b|matches!(b,ContentBlock::ToolResult{content_blocks:Some(blocks),..} if !blocks.is_empty()))); |
| 3637 | rig.close().await; |
| 3638 | Ok(()) |
| 3639 | } |
| 3640 | #[tokio::test(flavor = "current_thread")] |
| 3641 | async fn finite_engine_step_budget_is_a_typed_acp_stop_reason() -> Result<()> { |
| 3642 | finite_engine_step_budget_case(true).await |
| 3643 | } |
| 3644 | #[tokio::test(flavor = "current_thread")] |
| 3645 | async fn normal_owner_acp_step_stop_preserves_ordinary_successor() -> Result<()> { |
| 3646 | finite_engine_step_budget_case(false).await |
| 3647 | } |
| 3648 | async fn finite_engine_step_budget_case(base_acp: bool) -> Result<()> { |
| 3649 | let mut config = fixture_config(); |
| 3650 | config.tui = Some(codewhale_runtime::config::TuiConfig { |
| 3651 | max_model_steps: Some(1), |
| 3652 | ..Default::default() |
| 3653 | }); |
| 3654 | let mut rig = Rig::with_base( |
| 3655 | config, |
| 3656 | vec![ |
| 3657 | canned::tool_call_turn("budget", "read", r#"{"path":"one.txt"}"#), |
| 3658 | canned::simple_text_turn("bounded final report"), |
| 3659 | ], |
| 3660 | base_acp, |
| 3661 | )?; |
| 3662 | std::fs::write(rig.workspace.join("one.txt"), "one")?; |
| 3663 | let id = rig.new_session().await; |
| 3664 | assert_eq!( |
| 3665 | rig.prompt(&id, "read until budget").await?.0, |
| 3666 | "max_turn_requests" |
| 3667 | ); |
| 3668 | let detail = rig |
| 3669 | .server |
| 3670 | .runtime |
| 3671 | .get_thread_detail(&rig.server.sessions[&id].thread_id) |
| 3672 | .await?; |
| 3673 | assert_eq!( |
| 3674 | detail |
| 3675 | .turns |
| 3676 | .last() |
| 3677 | .unwrap() |
| 3678 | .model_request_diagnostics |
| 3679 | .as_ref() |
| 3680 | .unwrap() |
| 3681 | .stop_reason, |
| 3682 | Some(codewhale_engine::runtime_threads::RuntimeTurnStopReason::StepBudgetExhausted) |
| 3683 | ); |
| 3684 | assert_eq!( |
| 3685 | rig.mock.call_count(), |
| 3686 | 2, |
| 3687 | "one admitted model step plus existing Core final-report step" |
| 3688 | ); |
| 3689 | if !base_acp { |
| 3690 | rig.mock |
| 3691 | .push_turn(canned::simple_text_turn("ordinary after ACP step stop")); |
| 3692 | let thread = rig.server.sessions[&id].thread_id.clone(); |
| 3693 | let successor = rig |
| 3694 | .server |
| 3695 | .runtime |
| 3696 | .start_turn( |
| 3697 | &thread, |
| 3698 | codewhale_engine::runtime_threads::manager::StartTurnRequest { |
| 3699 | prompt: "ordinary after step stop".into(), |
| 3700 | ..Default::default() |
| 3701 | }, |
| 3702 | ) |
| 3703 | .await?; |
| 3704 | assert_eq!( |
| 3705 | wait_real_turn(&rig.server.runtime, &thread, &successor.id) |
| 3706 | .await? |
| 3707 | .status, |
| 3708 | codewhale_engine::runtime_threads::RuntimeTurnStatus::Completed |
| 3709 | ); |
| 3710 | let requests = rig.mock.captured_requests(); |
| 3711 | assert_eq!(requests.len(), 3); |
| 3712 | assert_ne!(requests[0].tools, requests[2].tools); |
| 3713 | } |
| 3714 | rig.close().await; |
| 3715 | Ok(()) |
| 3716 | } |
| 3717 | #[tokio::test(flavor = "current_thread")] |
| 3718 | async fn invalid_prompt_and_rpc_shapes_refuse_before_core_admission() -> Result<()> { |
| 3719 | let mut rig = Rig::new(fixture_config(), vec![])?; |
| 3720 | let id = rig.new_session().await; |
| 3721 | let (_, wire) = rig |
| 3722 | .drive(async |editor| { |
| 3723 | for (id, method, params) in [ |
| 3724 | (3, "session/prompt", json!({"sessionId":id,"prompt":[]})), |
| 3725 | ( |
| 3726 | 4, |
| 3727 | "session/prompt", |
| 3728 | json!({"sessionId":"unknown","prompt":"x"}), |
| 3729 | ), |
| 3730 | (5, "fabricated", json!({})), |
| 3731 | (6, "shutdown", json!({})), |
| 3732 | ] { |
| 3733 | editor |
| 3734 | .send(json!({"jsonrpc":"2.0","id":id,"method":method,"params":params})) |
| 3735 | .await?; |
| 3736 | } |
| 3737 | Ok(()) |
| 3738 | }) |
| 3739 | .await?; |
| 3740 | assert_eq!(wire[0]["error"]["code"], -32602); |
| 3741 | assert_eq!(wire[1]["error"]["code"], -32602); |
| 3742 | assert_eq!(wire[2]["error"]["code"], -32601); |
| 3743 | assert_eq!(wire[0]["id"], 3); |
| 3744 | assert_eq!(rig.mock.call_count(), 0); |
| 3745 | assert!( |
| 3746 | rig.server |
| 3747 | .runtime |
| 3748 | .get_thread_detail(&rig.server.sessions[&id].thread_id) |
| 3749 | .await? |
| 3750 | .turns |
| 3751 | .is_empty() |
| 3752 | ); |
| 3753 | rig.close().await; |
| 3754 | Ok(()) |
| 3755 | } |
| 3756 | #[tokio::test(flavor = "current_thread")] |
| 3757 | async fn canonical_thread_shell_ceiling_requires_operator_and_client_opt_in() -> Result<()> { |
| 3758 | for (operator, client, expected) in [ |
| 3759 | (true, false, false), |
| 3760 | (false, true, false), |
| 3761 | (true, true, true), |
| 3762 | ] { |
| 3763 | let mut config = fixture_config(); |
| 3764 | config.allow_shell = Some(operator); |
| 3765 | let operator_config = format!("allow_shell = {operator}\n"); |
| 3766 | let mut rig = Rig::new(config, vec![])?; |
| 3767 | let config_path = rig._dir.path().join("operator.toml"); |
| 3768 | std::fs::write(&config_path, operator_config)?; |
| 3769 | rig.server.config_path = Some(config_path); |
| 3770 | rig.server.client_supports_terminal = client; |
| 3771 | let id = rig.new_session().await; |
| 3772 | let thread = rig |
| 3773 | .server |
| 3774 | .runtime |
| 3775 | .get_thread(&rig.server.sessions[&id].thread_id) |
| 3776 | .await?; |
| 3777 | assert_eq!(thread.allow_shell, expected); |
| 3778 | assert_eq!(rig.mock.call_count(), 0); |
| 3779 | rig.close().await; |
| 3780 | } |
| 3781 | let mut config = fixture_config(); |
| 3782 | config.allow_shell = Some(true); |
| 3783 | let mut rig = Rig::new(config, vec![])?; |
| 3784 | rig.server.client_supports_terminal = true; |
| 3785 | let error = rig.server.new_session(json!({})).await.unwrap_err(); |
| 3786 | assert!(error.message.contains("unresolved configuration source")); |
| 3787 | assert!(rig.server.sessions.is_empty()); |
| 3788 | assert!( |
| 3789 | rig.server |
| 3790 | .runtime |
| 3791 | .list_threads( |
| 3792 | codewhale_engine::runtime_threads::manager::ThreadListFilter::IncludeArchived, |
| 3793 | None, |
| 3794 | ) |
| 3795 | .await? |
| 3796 | .is_empty() |
| 3797 | ); |
| 3798 | assert_eq!(rig.mock.call_count(), 0); |
| 3799 | rig.close().await; |
| 3800 | Ok(()) |
| 3801 | } |
| 3802 | #[tokio::test(flavor = "current_thread")] |
| 3803 | async fn model_discovery_and_selection_keep_custom_provider_identity_and_refuse_invalid_values() |
| 3804 | -> Result<()> { |
| 3805 | let mut rig = Rig::new(fixture_config(), vec![])?; |
| 3806 | assert_eq!(rig.server.current_model()["provider"], "acp-fixture"); |
| 3807 | assert_eq!(rig.server.current_model()["model"], "fixture-model"); |
| 3808 | assert!( |
| 3809 | rig.server.list_providers()["providers"] |
| 3810 | .as_array() |
| 3811 | .unwrap() |
| 3812 | .iter() |
| 3813 | .any(|p| p["id"] == "acp-fixture") |
| 3814 | ); |
| 3815 | assert!( |
| 3816 | rig.server |
| 3817 | .select_model(json!({"provider":"not-a-provider","model":"x"})) |
| 3818 | .is_err() |
| 3819 | ); |
| 3820 | assert!( |
| 3821 | rig.server |
| 3822 | .select_model(json!({"provider":"acp-fixture"})) |
| 3823 | .is_err() |
| 3824 | ); |
| 3825 | let selected = rig |
| 3826 | .server |
| 3827 | .select_model(json!({"provider":"acp-fixture","model":"fixture-model"})) |
| 3828 | .unwrap(); |
| 3829 | assert_eq!(selected["provider"], "acp-fixture"); |
| 3830 | assert_eq!(rig.mock.call_count(), 0); |
| 3831 | rig.close().await; |
| 3832 | Ok(()) |
| 3833 | } |
| 3834 | struct FailingInput(tokio::sync::mpsc::UnboundedReceiver<std::io::Result<Vec<u8>>>); |
| 3835 | impl tokio::io::AsyncRead for FailingInput { |
| 3836 | fn poll_read( |
| 3837 | self: std::pin::Pin<&mut Self>, |
| 3838 | cx: &mut std::task::Context<'_>, |
| 3839 | buf: &mut tokio::io::ReadBuf<'_>, |
| 3840 | ) -> std::task::Poll<std::io::Result<()>> { |
| 3841 | match self.get_mut().0.poll_recv(cx) { |
| 3842 | std::task::Poll::Ready(Some(Ok(bytes))) => { |
| 3843 | buf.put_slice(&bytes); |
| 3844 | std::task::Poll::Ready(Ok(())) |
| 3845 | } |
| 3846 | std::task::Poll::Ready(Some(Err(error))) => std::task::Poll::Ready(Err(error)), |
| 3847 | std::task::Poll::Ready(None) => std::task::Poll::Ready(Ok(())), |
| 3848 | std::task::Poll::Pending => std::task::Poll::Pending, |
| 3849 | } |
| 3850 | } |
| 3851 | } |
| 3852 | struct FailingOutput { |
| 3853 | fail_on: Option<&'static str>, |
| 3854 | } |
| 3855 | impl AsyncWrite for FailingOutput { |
| 3856 | fn poll_write( |
| 3857 | self: std::pin::Pin<&mut Self>, |
| 3858 | _: &mut std::task::Context<'_>, |
| 3859 | bytes: &[u8], |
| 3860 | ) -> std::task::Poll<std::io::Result<usize>> { |
| 3861 | if self |
| 3862 | .fail_on |
| 3863 | .is_some_and(|marker| String::from_utf8_lossy(bytes).contains(marker)) |
| 3864 | { |
| 3865 | return std::task::Poll::Ready(Err(std::io::Error::new( |
| 3866 | std::io::ErrorKind::BrokenPipe, |
| 3867 | "the editor stopped reading", |
| 3868 | ))); |
| 3869 | } |
| 3870 | std::task::Poll::Ready(Ok(bytes.len())) |
| 3871 | } |
| 3872 | fn poll_flush( |
| 3873 | self: std::pin::Pin<&mut Self>, |
| 3874 | _: &mut std::task::Context<'_>, |
| 3875 | ) -> std::task::Poll<std::io::Result<()>> { |
| 3876 | std::task::Poll::Ready(Ok(())) |
| 3877 | } |
| 3878 | fn poll_shutdown( |
| 3879 | self: std::pin::Pin<&mut Self>, |
| 3880 | _: &mut std::task::Context<'_>, |
| 3881 | ) -> std::task::Poll<std::io::Result<()>> { |
| 3882 | std::task::Poll::Ready(Ok(())) |
| 3883 | } |
| 3884 | } |
| 3885 | #[derive(Clone, Copy, PartialEq)] |
| 3886 | enum Failure { |
| 3887 | OutputAtPermission, |
| 3888 | InputError, |
| 3889 | OutputAfterWrite, |
| 3890 | } |
| 3891 | async fn transport_failure_case(mode: Failure) -> Result<()> { |
| 3892 | let mut config = fixture_config(); |
| 3893 | config.yolo = (mode == Failure::OutputAfterWrite).then_some(true); |
| 3894 | let mut rig = Rig::new( |
| 3895 | config, |
| 3896 | vec![ |
| 3897 | canned::tool_call_turn( |
| 3898 | "review-probe", |
| 3899 | "write", |
| 3900 | r#"{"path":"writer-failure.txt","content":"completed"}"#, |
| 3901 | ), |
| 3902 | canned::simple_text_turn("settled"), |
| 3903 | ], |
| 3904 | )?; |
| 3905 | let id = rig.new_session().await; |
| 3906 | let thread = rig.server.sessions[&id].thread_id.clone(); |
| 3907 | let manager = Arc::clone(&rig.server.runtime); |
| 3908 | let (lines, input) = tokio::sync::mpsc::unbounded_channel::<std::io::Result<Vec<u8>>>(); |
| 3909 | let mut prompt = serde_json::to_vec( |
| 3910 | &json!({"jsonrpc":"2.0","id":1,"method":"session/prompt","params":{"sessionId":id,"prompt":"write under Ask"}}), |
| 3911 | )?; |
| 3912 | prompt.push(b'\n'); |
| 3913 | lines |
| 3914 | .send(Ok(prompt)) |
| 3915 | .map_err(|_| anyhow!("review probe input closed early"))?; |
| 3916 | let placeholder = rig.placeholder(); |
| 3917 | let server = std::mem::replace(&mut rig.server, placeholder); |
| 3918 | let serving = tokio::time::timeout( |
| 3919 | Duration::from_secs(60), |
| 3920 | super::connection::serve_connection( |
| 3921 | server, |
| 3922 | Box::new(BufReader::new(FailingInput(input))), |
| 3923 | Box::new(FailingOutput { |
| 3924 | fail_on: match mode { |
| 3925 | Failure::OutputAtPermission => Some("session/request_permission"), |
| 3926 | Failure::OutputAfterWrite => Some("agent_message_chunk"), |
| 3927 | Failure::InputError => None, |
| 3928 | }, |
| 3929 | }), |
| 3930 | ), |
| 3931 | ); |
| 3932 | let breaking = async { |
| 3933 | if mode == Failure::InputError { |
| 3934 | let waited = tokio::time::timeout(Duration::from_secs(30), async { |
| 3935 | loop { |
| 3936 | if !manager |
| 3937 | .get_thread_detail(&thread) |
| 3938 | .await? |
| 3939 | .pending_approvals |
| 3940 | .is_empty() |
| 3941 | { |
| 3942 | return Ok::<_, anyhow::Error>(()); |
| 3943 | } |
| 3944 | tokio::time::sleep(Duration::from_millis(10)).await; |
| 3945 | } |
| 3946 | }) |
| 3947 | .await; |
| 3948 | let _ = lines.send(Err(std::io::Error::new( |
| 3949 | std::io::ErrorKind::ConnectionReset, |
| 3950 | "the editor's socket was reset", |
| 3951 | ))); |
| 3952 | waited??; |
| 3953 | } |
| 3954 | Ok::<_, anyhow::Error>(()) |
| 3955 | }; |
| 3956 | let (served, broke) = tokio::join!(serving, breaking); |
| 3957 | broke?; |
| 3958 | let served = served.map_err(|_| anyhow!("serve did not return in 60s"))?; |
| 3959 | let ended_with_error = served.is_err(); |
| 3960 | drop(served); |
| 3961 | let terminal = tokio::time::timeout(Duration::from_secs(40), async { |
| 3962 | loop { |
| 3963 | let detail = manager.get_thread_detail(&thread).await?; |
| 3964 | if detail.turns.last().is_some_and(|turn| { |
| 3965 | !matches!( |
| 3966 | turn.status, |
| 3967 | codewhale_engine::runtime_threads::RuntimeTurnStatus::Queued |
| 3968 | | codewhale_engine::runtime_threads::RuntimeTurnStatus::InProgress |
| 3969 | ) |
| 3970 | }) { |
| 3971 | return Ok::<_, anyhow::Error>(format!( |
| 3972 | "{:?}", |
| 3973 | detail.turns.last().map(|turn| &turn.status) |
| 3974 | )); |
| 3975 | } |
| 3976 | tokio::time::sleep(Duration::from_millis(25)).await; |
| 3977 | } |
| 3978 | }) |
| 3979 | .await |
| 3980 | .map_err(|_| anyhow!("the Core turn never settled"))??; |
| 3981 | tokio::time::sleep(Duration::from_millis(500)).await; |
| 3982 | let saved_user_messages = codewhale_engine::session_manager::SessionManager::new( |
| 3983 | rig.server.sessions_dir.clone(), |
| 3984 | )? |
| 3985 | .load_session(&id) |
| 3986 | .map(|saved| { |
| 3987 | saved |
| 3988 | .messages |
| 3989 | .iter() |
| 3990 | .filter(|m| m.role == Role::User) |
| 3991 | .count() |
| 3992 | }); |
| 3993 | drop(lines); |
| 3994 | rig.close().await; |
| 3995 | assert!( |
| 3996 | ended_with_error, |
| 3997 | "a failed transport must end serve with an error" |
| 3998 | ); |
| 3999 | assert!( |
| 4000 | matches!(saved_user_messages, Ok(count) if count > 0), |
| 4001 | "no checkpoint after a mid-turn transport failure ({}); Core turn ended {terminal}; saved user messages: {saved_user_messages:?}", |
| 4002 | mode as u8 |
| 4003 | ); |
| 4004 | if mode == Failure::OutputAfterWrite { |
| 4005 | assert_eq!( |
| 4006 | std::fs::read_to_string(rig.workspace.join("writer-failure.txt"))?, |
| 4007 | "completed" |
| 4008 | ); |
| 4009 | } |
| 4010 | Ok(()) |
| 4011 | } |
| 4012 | #[tokio::test(flavor = "current_thread")] |
| 4013 | async fn a_failed_output_write_mid_turn_keeps_the_checkpoint() -> Result<()> { |
| 4014 | transport_failure_case(Failure::OutputAtPermission).await |
| 4015 | } |
| 4016 | #[tokio::test(flavor = "current_thread")] |
| 4017 | async fn a_failed_input_read_mid_turn_keeps_the_checkpoint() -> Result<()> { |
| 4018 | transport_failure_case(Failure::InputError).await |
| 4019 | } |
| 4020 | #[tokio::test(flavor = "current_thread")] |
| 4021 | async fn failed_transport_after_completed_write_retains_actual_core_terminal_and_checkpoint() |
| 4022 | -> Result<()> { |
| 4023 | transport_failure_case(Failure::OutputAfterWrite).await |
| 4024 | } |
| 4025 | |
| 4026 | #[tokio::test(flavor = "current_thread")] |
| 4027 | async fn an_oversize_update_fails_the_connection_without_dropping_the_turn() -> Result<()> { |
| 4028 | use futures_util::SinkExt; |
| 4029 | let rig = Rig::new(fixture_config(), vec![])?; |
| 4030 | let shared = Arc::new(super::connection::Shared::new(rig.placeholder())); |
| 4031 | let (frames, mut queued) = tokio::sync::mpsc::channel(4); |
| 4032 | let mut sink = Box::pin(super::connection::outgoing_lines( |
| 4033 | frames, |
| 4034 | Arc::clone(&shared), |
| 4035 | )); |
| 4036 | let update = json!({"jsonrpc":"2.0","method":"session/update","params":{"big":"x".repeat(MAX_FRAME_BYTES)}}) |
| 4037 | .to_string(); |
| 4038 | sink.send(update).await?; |
| 4039 | assert!(queued.try_recv().is_err()); |
| 4040 | assert!(shared.take_failure().is_some()); |
| 4041 | rig.close().await; |
| 4042 | Ok(()) |
| 4043 | } |
| 4044 | |
| 4045 | #[tokio::test(flavor = "current_thread")] |
| 4046 | async fn acp_full_access_hint_is_localized_for_every_shipped_locale() -> Result<()> { |
| 4047 | use codewhale_localization::{Locale, MessageId, tr}; |
| 4048 | let mut rig = Rig::new(fixture_config(), vec![])?; |
| 4049 | let id = rig.new_session().await; |
| 4050 | let english = tr(Locale::En, MessageId::AcpFullAccessHint); |
| 4051 | for &locale in Locale::shipped_complete() { |
| 4052 | let view = to_wire( |
| 4053 | &rig.server |
| 4054 | .session_view_for_locale(&id, locale) |
| 4055 | .await |
| 4056 | .unwrap(), |
| 4057 | ) |
| 4058 | .unwrap(); |
| 4059 | let hint = view["configOptions"][2]["_meta"]["codewhale"]["enableFullAccess"] |
| 4060 | .as_str() |
| 4061 | .expect("permission option must include enableFullAccess hint"); |
| 4062 | assert_eq!( |
| 4063 | hint, |
| 4064 | tr(locale, MessageId::AcpFullAccessHint), |
| 4065 | "{} enableFullAccess did not use localized MessageId::AcpFullAccessHint", |
| 4066 | locale.tag() |
| 4067 | ); |
| 4068 | assert!(hint.contains("codewhale serve --acp --full-access")); |
| 4069 | assert!(hint.contains("--yolo")); |
| 4070 | assert!(hint.contains("yolo = true")); |
| 4071 | assert!(hint.contains("sandbox_mode")); |
| 4072 | if locale != Locale::En { |
| 4073 | assert_ne!( |
| 4074 | hint, |
| 4075 | english, |
| 4076 | "{} enableFullAccess fell back to English", |
| 4077 | locale.tag() |
| 4078 | ); |
| 4079 | } |
| 4080 | } |
| 4081 | rig.close().await; |
| 4082 | Ok(()) |
| 4083 | } |
| 4084 | |
| 4085 | #[tokio::test(flavor = "current_thread")] |
| 4086 | async fn acp_load_session_offloads_store_io_and_releases_server_mutex_across_awaits() |
| 4087 | -> Result<()> { |
| 4088 | use std::future::Future; |
| 4089 | use std::task::{Context, Poll, Waker}; |
| 4090 | |
| 4091 | let mut rig = Rig::new(fixture_config(), vec![])?; |
| 4092 | let id = rig.new_session().await; |
| 4093 | let store = codewhale_engine::session_manager::SessionManager::new( |
| 4094 | rig.server.sessions_dir.clone(), |
| 4095 | )?; |
| 4096 | let mut saved = store.load_session(&id)?; |
| 4097 | saved.messages = serde_json::from_value(Value::Array( |
| 4098 | (0..64) |
| 4099 | .map(|i| { |
| 4100 | json!({ |
| 4101 | "role": if i % 2 == 0 { "user" } else { "assistant" }, |
| 4102 | "content": [{ "type": "text", "text": format!("message-{i}: {}", "x".repeat(512)) }] |
| 4103 | }) |
| 4104 | }) |
| 4105 | .collect(), |
| 4106 | ))?; |
| 4107 | store.save_session(&saved)?; |
| 4108 | rig.server.sessions.clear(); |
| 4109 | rig.server.insertion_order.clear(); |
| 4110 | |
| 4111 | let worker_thread = std::thread::current().id(); |
| 4112 | let blocking_thread = super::spawn_blocking_io(|| std::thread::current().id()).await?; |
| 4113 | assert_ne!( |
| 4114 | worker_thread, blocking_thread, |
| 4115 | "spawn_blocking_io must run off the Tokio async worker thread" |
| 4116 | ); |
| 4117 | |
| 4118 | let placeholder = rig.placeholder(); |
| 4119 | let server = tokio::sync::Mutex::new(std::mem::replace(&mut rig.server, placeholder)); |
| 4120 | let mut load_fut = Box::pin(super::AcpServer::load_session_shared( |
| 4121 | &server, |
| 4122 | json!({ "sessionId": id }), |
| 4123 | )); |
| 4124 | let waker = Waker::noop(); |
| 4125 | let mut cx = Context::from_waker(waker); |
| 4126 | let mut pending_polls = 0usize; |
| 4127 | let mut concurrent_served = false; |
| 4128 | let loaded = loop { |
| 4129 | match load_fut.as_mut().poll(&mut cx) { |
| 4130 | Poll::Ready(result) => break result.unwrap(), |
| 4131 | Poll::Pending => { |
| 4132 | pending_polls += 1; |
| 4133 | assert!( |
| 4134 | server.try_lock().is_ok(), |
| 4135 | "server mutex must not be held across await points during session/load" |
| 4136 | ); |
| 4137 | if !concurrent_served { |
| 4138 | let model = super::AcpServer::handle_request_shared( |
| 4139 | &server, |
| 4140 | "session/currentModel", |
| 4141 | json!({}), |
| 4142 | ) |
| 4143 | .await |
| 4144 | .unwrap(); |
| 4145 | assert!(model.get("model").is_some()); |
| 4146 | concurrent_served = true; |
| 4147 | } |
| 4148 | tokio::task::yield_now().await; |
| 4149 | } |
| 4150 | } |
| 4151 | }; |
| 4152 | drop(load_fut); |
| 4153 | assert!( |
| 4154 | pending_polls > 0, |
| 4155 | "session/load must yield off the async worker" |
| 4156 | ); |
| 4157 | assert!(concurrent_served); |
| 4158 | assert_eq!(loaded["sessionId"], id); |
| 4159 | |
| 4160 | let (sessions_dir, config) = { |
| 4161 | let guard = server.lock().await; |
| 4162 | (guard.sessions_dir.clone(), guard.config.clone()) |
| 4163 | }; |
| 4164 | let updates = super::history_updates_for(sessions_dir, config, id).await?; |
| 4165 | assert_eq!(updates.len(), 64); |
| 4166 | |
| 4167 | rig.server = server.into_inner(); |
| 4168 | rig.close().await; |
| 4169 | Ok(()) |
| 4170 | } |
| 4171 | } |
| 4172 |