| 1 | //! Remote-control bridge: `/rc` event draining, local-turn attachment, and |
| 2 | //! session start projection, extracted from the composition root |
| 3 | //! (docs/architecture/TUI_MODULARIZATION.md slice 3). The controller in `codewhale_app_server::remote_control` |
| 4 | //! owns connection state; this module only projects its events into the UI. |
| 5 | |
| 6 | use super::*; |
| 7 | |
| 8 | pub(crate) async fn drain_remote_control_events( |
| 9 | app: &mut App, |
| 10 | config: &Config, |
| 11 | engine_handle: &EngineHandle, |
| 12 | ) -> Result<bool> { |
| 13 | // A connection can become ready while a local approval card still owns |
| 14 | // the decision. Keep that card local; once it closes, bind the same |
| 15 | // already-running typed turn on the next loop tick. If the turn ended in |
| 16 | // the meantime this remains an ordinary idle attachment. |
| 17 | let mut changed = try_attach_active_local_turn_to_remote(app).await; |
| 18 | loop { |
| 19 | let event = app.remote_control.try_next_event_async().await; |
| 20 | let Some(event) = event else { |
| 21 | break; |
| 22 | }; |
| 23 | changed = true; |
| 24 | match event { |
| 25 | codewhale_app_server::remote_control::RemoteEvent::Notice(message) => { |
| 26 | app.add_message(HistoryCell::System { |
| 27 | content: message.clone(), |
| 28 | }); |
| 29 | |
| 30 | show_remote_control_banner(app, message); |
| 31 | } |
| 32 | codewhale_app_server::remote_control::RemoteEvent::Connected { |
| 33 | account_ref, |
| 34 | runner_id, |
| 35 | attachment, |
| 36 | links, |
| 37 | .. |
| 38 | } => { |
| 39 | app.remote_control |
| 40 | .upload_snapshot_async(&attachment.run_id, &app.api_messages) |
| 41 | .await; |
| 42 | let active_local_turn = local_turn_is_active(app); |
| 43 | let attached_active_turn = try_attach_active_local_turn_to_remote(app).await; |
| 44 | let status = codewhale_app_server::remote_control::remote_control_banner( |
| 45 | &account_ref, |
| 46 | &runner_id, |
| 47 | links.run_url.as_deref(), |
| 48 | ); |
| 49 | let mirror_note = if active_local_turn && !attached_active_turn { |
| 50 | "A local approval card still owns the current decision; the web joins this turn once it closes." |
| 51 | } else { |
| 52 | "Web mirror connected. Both surfaces can prompt and decide; one turn runs at a time." |
| 53 | }; |
| 54 | app.add_message(HistoryCell::System { |
| 55 | content: format!("{status}\n\n{mirror_note}"), |
| 56 | }); |
| 57 | if let Some(run_url) = links.run_url.as_deref() { |
| 58 | app.add_message(HistoryCell::System { |
| 59 | content: codewhale_app_server::remote_control::remote_control_link_notice( |
| 60 | run_url, |
| 61 | ), |
| 62 | }); |
| 63 | } |
| 64 | |
| 65 | show_remote_control_banner(app, status); |
| 66 | } |
| 67 | codewhale_app_server::remote_control::RemoteEvent::Attachment { |
| 68 | attachment, .. |
| 69 | } => { |
| 70 | // Reconnect responses carry the server's current cursor and |
| 71 | // snapshot receipt. `try_next_event` applies that truth before |
| 72 | // this handler, so this is either a no-op or one bounded retry. |
| 73 | app.remote_control |
| 74 | .upload_snapshot_async(&attachment.run_id, &app.api_messages) |
| 75 | .await; |
| 76 | } |
| 77 | codewhale_app_server::remote_control::RemoteEvent::RuntimeCursor { .. } => { |
| 78 | // The controller has already retired the acknowledged prefix. |
| 79 | } |
| 80 | codewhale_app_server::remote_control::RemoteEvent::RuntimeChatHostReleased => { |
| 81 | // Internal provider-config handoff; the controller has already |
| 82 | // reopened the isolated host and queued its fresh catalog. |
| 83 | } |
| 84 | codewhale_app_server::remote_control::RemoteEvent::RuntimeChatProjection(_) => { |
| 85 | // The controller journaled this isolated native event before |
| 86 | // exposing it to the UI bridge. It is web-Chat output, not a |
| 87 | // mutation of the current interactive TUI transcript. |
| 88 | } |
| 89 | codewhale_app_server::remote_control::RemoteEvent::FailedPreLease(error) => { |
| 90 | let status = format!("WEB MIRROR · could not start · {error} · /rc to retry"); |
| 91 | report_remote_control_failure(app, status); |
| 92 | } |
| 93 | codewhale_app_server::remote_control::RemoteEvent::Failed(error) => { |
| 94 | let status = format!( |
| 95 | "WEB MIRROR LOST · {error} · this terminal is unaffected; reconnecting waits briefly for the server lease to drain" |
| 96 | ); |
| 97 | report_remote_control_failure(app, status); |
| 98 | } |
| 99 | codewhale_app_server::remote_control::RemoteEvent::Stopped => { |
| 100 | app.retire_progress_notice(StatusToastKind::RemoteMirror); |
| 101 | app.show_command_result("Web mirror stopped.".to_string(), StatusToastLevel::Info); |
| 102 | } |
| 103 | codewhale_app_server::remote_control::RemoteEvent::OwnershipRestored { approvals } => { |
| 104 | app.retire_progress_notice(StatusToastKind::RemoteMirror); |
| 105 | app.show_command_result( |
| 106 | "The web mirror lease expired; pending approvals stay actionable here." |
| 107 | .to_string(), |
| 108 | StatusToastLevel::Warning, |
| 109 | ); |
| 110 | // Mirror semantics: approval cards were never hidden from |
| 111 | // this terminal, so there is nothing to re-show. The drained |
| 112 | // list only tells us the web can no longer answer them. |
| 113 | let _ = approvals; |
| 114 | } |
| 115 | codewhale_app_server::remote_control::RemoteEvent::Command { |
| 116 | run_id, |
| 117 | seq, |
| 118 | command, |
| 119 | } => { |
| 120 | match app.remote_control.claim_command(&run_id, seq, &command) { |
| 121 | Ok(true) => {} |
| 122 | Ok(false) => { |
| 123 | // The native Runtime operation key makes Chat replay |
| 124 | // safe. Re-enter it and reissue the terminal command |
| 125 | // acknowledgement: the previous provider submission |
| 126 | // may be durable even though its acknowledgement POST |
| 127 | // was lost with a worker failure. |
| 128 | if let codewhale_app_server::remote_control::RemoteCommand::RuntimeChatPrompt(prompt) = |
| 129 | &command |
| 130 | { |
| 131 | match app.remote_control.apply_runtime_chat_prompt(prompt).await { |
| 132 | Ok(()) => app |
| 133 | .remote_control |
| 134 | .acknowledge(&run_id, seq, &command, "applied", None), |
| 135 | Err(error) => app.remote_control.acknowledge( |
| 136 | &run_id, |
| 137 | seq, |
| 138 | &command, |
| 139 | "failed", |
| 140 | Some(error), |
| 141 | ), |
| 142 | } |
| 143 | } |
| 144 | continue; |
| 145 | } |
| 146 | Err(error) => { |
| 147 | app.remote_control.acknowledge( |
| 148 | &run_id, |
| 149 | seq, |
| 150 | &command, |
| 151 | "failed", |
| 152 | Some(error.clone()), |
| 153 | ); |
| 154 | app.remote_control.stop_async().await; |
| 155 | app.retire_progress_notice(StatusToastKind::RemoteMirror); |
| 156 | app.show_command_result(error, StatusToastLevel::Error); |
| 157 | continue; |
| 158 | } |
| 159 | } |
| 160 | if matches!( |
| 161 | &command, |
| 162 | codewhale_app_server::remote_control::RemoteCommand::RuntimeChatPrompt(_) |
| 163 | ) && local_turn_is_active(app) |
| 164 | { |
| 165 | app.remote_control.acknowledge( |
| 166 | &run_id, |
| 167 | seq, |
| 168 | &command, |
| 169 | "failed", |
| 170 | Some( |
| 171 | "Finish or interrupt the active local turn before starting Runtime Chat." |
| 172 | .to_string(), |
| 173 | ), |
| 174 | ); |
| 175 | continue; |
| 176 | } |
| 177 | match command.clone() { |
| 178 | codewhale_app_server::remote_control::RemoteCommand::RuntimeChatPrompt( |
| 179 | prompt, |
| 180 | ) => match app.remote_control.apply_runtime_chat_prompt(&prompt).await { |
| 181 | Ok(()) => app |
| 182 | .remote_control |
| 183 | .acknowledge(&run_id, seq, &command, "applied", None), |
| 184 | Err(error) => app.remote_control.acknowledge( |
| 185 | &run_id, |
| 186 | seq, |
| 187 | &command, |
| 188 | "failed", |
| 189 | Some(error), |
| 190 | ), |
| 191 | }, |
| 192 | codewhale_app_server::remote_control::RemoteCommand::Prompt { |
| 193 | turn_id, |
| 194 | prompt, |
| 195 | } => { |
| 196 | if app.is_loading || app.dispatch_in_flight { |
| 197 | app.remote_control.acknowledge( |
| 198 | &run_id, |
| 199 | seq, |
| 200 | &command, |
| 201 | "failed", |
| 202 | Some( |
| 203 | "A turn is already running; the next prompt starts when it finishes." |
| 204 | .to_string(), |
| 205 | ), |
| 206 | ); |
| 207 | continue; |
| 208 | } |
| 209 | app.remote_control |
| 210 | .upload_snapshot_async(&run_id, &app.api_messages) |
| 211 | .await; |
| 212 | if let Err(error) = app |
| 213 | .remote_control |
| 214 | .activate_prompt_async(&run_id, &turn_id) |
| 215 | .await |
| 216 | { |
| 217 | app.remote_control.acknowledge( |
| 218 | &run_id, |
| 219 | seq, |
| 220 | &command, |
| 221 | "failed", |
| 222 | Some(error), |
| 223 | ); |
| 224 | continue; |
| 225 | } |
| 226 | let message = QueuedMessage::new(prompt, None).without_owner_input(); |
| 227 | app.remote_control.set_applying_remote_command(true); |
| 228 | let result = dispatch_user_message_with_recovery( |
| 229 | app, |
| 230 | config, |
| 231 | engine_handle, |
| 232 | message, |
| 233 | DispatchRecovery::Immediate, |
| 234 | ) |
| 235 | .await; |
| 236 | app.remote_control.set_applying_remote_command(false); |
| 237 | match result { |
| 238 | Ok(()) if app.is_loading || app.dispatch_in_flight => { |
| 239 | app.remote_control |
| 240 | .acknowledge(&run_id, seq, &command, "applied", None); |
| 241 | } |
| 242 | Ok(()) => { |
| 243 | app.remote_control |
| 244 | .fail_active_dispatch_async( |
| 245 | "The remote prompt was blocked before dispatch.", |
| 246 | ) |
| 247 | .await; |
| 248 | app.remote_control.acknowledge( |
| 249 | &run_id, |
| 250 | seq, |
| 251 | &command, |
| 252 | "failed", |
| 253 | Some( |
| 254 | "The remote prompt was blocked before dispatch." |
| 255 | .to_string(), |
| 256 | ), |
| 257 | ); |
| 258 | } |
| 259 | Err(error) => { |
| 260 | app.remote_control |
| 261 | .fail_active_dispatch_async(&error.to_string()) |
| 262 | .await; |
| 263 | app.remote_control.acknowledge( |
| 264 | &run_id, |
| 265 | seq, |
| 266 | &command, |
| 267 | "failed", |
| 268 | Some(error.to_string()), |
| 269 | ); |
| 270 | } |
| 271 | } |
| 272 | } |
| 273 | codewhale_app_server::remote_control::RemoteCommand::Approval { |
| 274 | gate, |
| 275 | approved, |
| 276 | } => { |
| 277 | // Keep the gate pending until the engine takes the |
| 278 | // decision: a failed send leaves it retryable (U03-07). |
| 279 | let Some(tool_id) = app.remote_control.pending_approval_tool_id(&gate) |
| 280 | else { |
| 281 | app.remote_control.acknowledge( |
| 282 | &run_id, |
| 283 | seq, |
| 284 | &command, |
| 285 | "failed", |
| 286 | Some("This approval is no longer pending.".to_string()), |
| 287 | ); |
| 288 | continue; |
| 289 | }; |
| 290 | let result = if approved { |
| 291 | engine_handle.approve_tool_call(tool_id.clone()).await |
| 292 | } else { |
| 293 | engine_handle.deny_tool_call(tool_id.clone()).await |
| 294 | }; |
| 295 | match result { |
| 296 | Ok(()) => { |
| 297 | note_human_decision_delivered(app, &tool_id); |
| 298 | let _ = app.remote_control.take_pending_approval(&gate); |
| 299 | app.retire_action_notices(Some(&tool_id)); |
| 300 | // First decision wins: the web answered this |
| 301 | // gate, so dismiss exactly the matching card — |
| 302 | // never an unrelated approval that happens to |
| 303 | // be on top (concurrent approvals, fleet). |
| 304 | // The card may sit under another view |
| 305 | // (a child's card, a pager): remove it at |
| 306 | // any depth, and forget its pending entry. |
| 307 | if app.view_stack.remove_approval_for_gate(&gate) { |
| 308 | app.needs_redraw = true; |
| 309 | } |
| 310 | crate::tui::pending_requests::resolve(app, &tool_id); |
| 311 | let (message_id, level) = if approved { |
| 312 | ( |
| 313 | MessageId::NotificationWebApproved, |
| 314 | StatusToastLevel::Success, |
| 315 | ) |
| 316 | } else { |
| 317 | (MessageId::NotificationWebDenied, StatusToastLevel::Warning) |
| 318 | }; |
| 319 | app.push_status_toast_record( |
| 320 | StatusToast::new(app.tr(message_id), level, Some(5_000)) |
| 321 | .for_event(format!("web-decision:{tool_id}")), |
| 322 | ); |
| 323 | app.remote_control |
| 324 | .acknowledge(&run_id, seq, &command, "applied", None); |
| 325 | } |
| 326 | Err(error) => app.remote_control.acknowledge( |
| 327 | &run_id, |
| 328 | seq, |
| 329 | &command, |
| 330 | "failed", |
| 331 | Some(error.to_string()), |
| 332 | ), |
| 333 | } |
| 334 | } |
| 335 | codewhale_app_server::remote_control::RemoteCommand::Control { |
| 336 | runtime_chat: Some(scope), |
| 337 | turn_id: Some(turn_id), |
| 338 | .. |
| 339 | } => { |
| 340 | match app |
| 341 | .remote_control |
| 342 | .interrupt_runtime_chat(&run_id, &scope, &turn_id) |
| 343 | .await |
| 344 | { |
| 345 | Ok(()) => app |
| 346 | .remote_control |
| 347 | .acknowledge(&run_id, seq, &command, "applied", None), |
| 348 | Err(error) => app.remote_control.acknowledge( |
| 349 | &run_id, |
| 350 | seq, |
| 351 | &command, |
| 352 | "failed", |
| 353 | Some(error), |
| 354 | ), |
| 355 | } |
| 356 | } |
| 357 | codewhale_app_server::remote_control::RemoteCommand::Control { |
| 358 | turn_id, |
| 359 | .. |
| 360 | } => { |
| 361 | let exact_active_turn = turn_id.as_deref().is_some_and(|turn_id| { |
| 362 | app.remote_control.active_turn_matches(&run_id, turn_id) |
| 363 | }); |
| 364 | if !exact_active_turn { |
| 365 | app.remote_control.acknowledge( |
| 366 | &run_id, |
| 367 | seq, |
| 368 | &command, |
| 369 | "failed", |
| 370 | Some("This turn no longer owns active Work.".to_string()), |
| 371 | ); |
| 372 | continue; |
| 373 | } |
| 374 | engine_handle.cancel(); |
| 375 | mark_active_turn_cancelled_locally(app); |
| 376 | app.remote_control |
| 377 | .acknowledge(&run_id, seq, &command, "applied", None); |
| 378 | } |
| 379 | } |
| 380 | } |
| 381 | } |
| 382 | } |
| 383 | // A Connected event and the local approval decision may be drained in the |
| 384 | // same UI iteration. Re-check after the event batch so the current turn is |
| 385 | // attached without waiting for another key or frame. |
| 386 | changed |= try_attach_active_local_turn_to_remote(app).await; |
| 387 | Ok(changed) |
| 388 | } |
| 389 | |
| 390 | fn local_turn_is_active(app: &App) -> bool { |
| 391 | app.is_loading |
| 392 | || app.dispatch_in_flight |
| 393 | || matches!(app.runtime_turn_status.as_deref(), Some("in_progress")) |
| 394 | } |
| 395 | |
| 396 | /// Attach `/rc` to the current local turn only after the server has supplied |
| 397 | /// a real run id and no pre-attachment approval card still owns the decision. |
| 398 | async fn try_attach_active_local_turn_to_remote(app: &mut App) -> bool { |
| 399 | if app.remote_control.runtime_chat_blocks_local_dispatch() { |
| 400 | return false; |
| 401 | } |
| 402 | if !local_turn_is_active(app) { |
| 403 | // A dispatch can fail before its typed TurnStarted receipt. In that |
| 404 | // case there is no turn to hand off and the connected attachment is |
| 405 | // simply idle, so do not strand a synthetic active lease. |
| 406 | return app |
| 407 | .remote_control |
| 408 | .release_unstarted_local_turn_async() |
| 409 | .await; |
| 410 | } |
| 411 | if app |
| 412 | .view_stack |
| 413 | .contains_kind(crate::tui::views::ModalKind::Approval) |
| 414 | { |
| 415 | return false; |
| 416 | } |
| 417 | // `runtime_turn_id` intentionally survives the end of a turn for saved |
| 418 | // receipts. It is authoritative for this handoff only while the matching |
| 419 | // typed status is still in progress; a new dispatch otherwise parks until |
| 420 | // its own TurnStarted arrives instead of binding the previous turn id. |
| 421 | let turn_id = if matches!(app.runtime_turn_status.as_deref(), Some("in_progress")) { |
| 422 | app.runtime_turn_id.clone() |
| 423 | } else { |
| 424 | None |
| 425 | }; |
| 426 | app.remote_control |
| 427 | .attach_current_local_turn_async(turn_id.as_deref()) |
| 428 | .await |
| 429 | } |
| 430 | |
| 431 | pub(crate) fn show_remote_control_banner(app: &mut App, status: String) { |
| 432 | app.retire_progress_notice(StatusToastKind::RemoteMirror); |
| 433 | let mut banner = StatusToast::new(status, StatusToastLevel::Warning, None); |
| 434 | banner.kind = StatusToastKind::RemoteMirror; |
| 435 | app.push_status_toast_record(banner); |
| 436 | } |
| 437 | |
| 438 | fn report_remote_control_failure(app: &mut App, error: String) { |
| 439 | let error = codewhale_config::persistence::redact_secrets(&error); |
| 440 | tracing::warn!(%error, "remote-control failure"); |
| 441 | app.add_message(HistoryCell::System { |
| 442 | content: error.clone(), |
| 443 | }); |
| 444 | app.show_owned_command_result( |
| 445 | StatusToastKind::RemoteMirror, |
| 446 | error, |
| 447 | StatusToastLevel::Error, |
| 448 | ); |
| 449 | } |
| 450 | |
| 451 | fn report_remote_control_start_failure(app: &mut App, error: String) { |
| 452 | app.remote_control.record_start_failure(&error); |
| 453 | if app.remote_control.status() == codewhale_app_server::remote_control::Status::Failed { |
| 454 | report_remote_control_failure(app, error); |
| 455 | } else { |
| 456 | app.push_status_toast( |
| 457 | codewhale_config::persistence::redact_secrets(&error), |
| 458 | StatusToastLevel::Error, |
| 459 | Some(12_000), |
| 460 | ); |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | pub(crate) async fn start_remote_control_session(app: &mut App, config: &Config) { |
| 465 | let session_id = app |
| 466 | .current_session_id |
| 467 | .clone() |
| 468 | .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); |
| 469 | app.current_session_id = Some(session_id.clone()); |
| 470 | // The target is the folder, not the session: repeated `/rc` runs in the |
| 471 | // same folder reuse one enrollment grant instead of minting a new one. |
| 472 | let target_ref = codewhale_app_server::remote_control::target_ref(&app.workspace); |
| 473 | let workspace_label = app |
| 474 | .workspace |
| 475 | .file_name() |
| 476 | .and_then(|value| value.to_str()) |
| 477 | .filter(|value| !value.is_empty()) |
| 478 | .unwrap_or("Codewhale session") |
| 479 | .to_string(); |
| 480 | let git_remote = codewhale_engine::git_status::observed_git_repo(&app.workspace); |
| 481 | let runtime_commit = option_env!("CODEWHALE_BUILD_COMMIT") |
| 482 | .unwrap_or("") |
| 483 | .to_string(); |
| 484 | // The crash-recoverable delivery journal is mandatory outside tests: it is |
| 485 | // what lets an interrupted session prove which terminal/approval events |
| 486 | // never reached the account before handing the session back. |
| 487 | let journal_dir = match codewhale_config::codewhale_home() { |
| 488 | Ok(home) => home.join("remote-control"), |
| 489 | Err(_) => { |
| 490 | let error = |
| 491 | "Remote control needs a writable Codewhale home directory for its delivery journal." |
| 492 | .to_string(); |
| 493 | report_remote_control_start_failure(app, error); |
| 494 | return; |
| 495 | } |
| 496 | }; |
| 497 | if let Err(error) = app |
| 498 | .remote_control |
| 499 | .prepare_remote_control_session_journal_async(&journal_dir, &target_ref, &session_id) |
| 500 | .await |
| 501 | { |
| 502 | report_remote_control_start_failure(app, error); |
| 503 | return; |
| 504 | } |
| 505 | if let Err(error) = app |
| 506 | .remote_control |
| 507 | .configure_runtime_chat_async( |
| 508 | config.clone(), |
| 509 | std::sync::Arc::clone(&app.plugin_registry), |
| 510 | journal_dir.join("runtime-chat"), |
| 511 | target_ref.clone(), |
| 512 | session_id.clone(), |
| 513 | ) |
| 514 | .await |
| 515 | { |
| 516 | report_remote_control_start_failure(app, error); |
| 517 | return; |
| 518 | } |
| 519 | match app |
| 520 | .remote_control |
| 521 | .start_async(codewhale_app_server::remote_control::RemoteStart { |
| 522 | workspace_label, |
| 523 | target_ref, |
| 524 | session_id, |
| 525 | runtime_version: env!("CARGO_PKG_VERSION").to_string(), |
| 526 | runtime_commit, |
| 527 | journal_dir: Some(journal_dir), |
| 528 | git_remote, |
| 529 | }) |
| 530 | .await |
| 531 | { |
| 532 | Ok(()) => { |
| 533 | let status = app.remote_control.status_line(); |
| 534 | |
| 535 | show_remote_control_banner(app, status); |
| 536 | } |
| 537 | Err(error) => { |
| 538 | report_remote_control_start_failure(app, error); |
| 539 | } |
| 540 | } |
| 541 | } |
| 542 |