diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 768128b335..37a74f3bce 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -257,9 +257,8 @@ mod thread_session_state; mod thread_settings; mod thread_title; mod transcript_export; -#[cfg_attr(not(test), allow(dead_code))] +mod user_verification; mod user_verification_errors; -#[allow(dead_code)] // Connected by the following verification UI integration. mod user_verification_requests; mod working_directory; @@ -282,6 +281,10 @@ enum ThreadInteractiveRequest { AppLink(AppLinkViewParams), Approval(ApprovalRequest), McpServerElicitation(McpServerElicitationFormRequest), + UserVerification { + thread_id: ThreadId, + request: crate::bottom_pane::user_verification::UserVerificationRequest, + }, } /// Extracts `receiver_thread_ids` from collab agent tool-call notifications. diff --git a/codex-rs/tui/src/app/app_server_requests.rs b/codex-rs/tui/src/app/app_server_requests.rs index 4530e7a5b8..1c6a9b00f6 100644 --- a/codex-rs/tui/src/app/app_server_requests.rs +++ b/codex-rs/tui/src/app/app_server_requests.rs @@ -96,6 +96,15 @@ impl PendingAppServerRequests { self.user_verification.clear(); } + pub(super) fn cancel_thread_verification(&mut self, thread_id: &str) { + for (server_name, request_id) in self.user_verification.cancel_thread(thread_id) { + self.mcp_requests.remove(&McpRequestKey { + server_name, + request_id, + }); + } + } + pub(super) fn note_server_request( &mut self, request: &ServerRequest, diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index d505940070..dda2e76e1e 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -67,6 +67,13 @@ impl App { } match event { + AppEvent::UserVerificationApproved { thread_id, server_name, request_id } => { + Box::pin(self.start_user_verification(app_server, thread_id, server_name, request_id)).await?; + } + AppEvent::UserVerificationFinished { thread_id, server_name, request_id, attempt_id, result } => { + // Keep this RPC future out of the event loop's stack frame. + Box::pin(self.finish_user_verification(app_server, thread_id, server_name, request_id, attempt_id, result)).await?; + } AppEvent::ReviewMisalignment(review) => { self.open_misalignment_review(tui, review); } diff --git a/codex-rs/tui/src/app/side.rs b/codex-rs/tui/src/app/side.rs index db616b3aa2..b1e56429b0 100644 --- a/codex-rs/tui/src/app/side.rs +++ b/codex-rs/tui/src/app/side.rs @@ -408,7 +408,14 @@ impl App { }; self.select_agent_thread(tui, app_server, target_thread_id) - .await + .await?; + if self.active_thread_id == Some(target_thread_id) + && self.active_side_parent_thread_id().is_none() + { + self.surface_pending_inactive_thread_interactive_requests() + .await?; + } + Ok(()) } pub(super) async fn discard_side_thread( @@ -438,6 +445,9 @@ impl App { app_server: &mut AppServerSession, thread_id: ThreadId, ) { + self.abandoned_side_threads.insert(thread_id); + self.pending_app_server_requests + .cancel_thread_verification(&thread_id.to_string()); let turn_id = self .active_turn_id_for_thread(thread_id) .await @@ -447,7 +457,6 @@ impl App { let retry_interrupt_request_id = app_server.next_request_id(); let unsubscribe_request_id = app_server.next_request_id(); - self.abandoned_side_threads.insert(thread_id); self.discard_thread_local_state(thread_id).await; tokio::spawn(async move { @@ -497,6 +506,8 @@ impl App { } pub(super) async fn discard_thread_local_state(&mut self, thread_id: ThreadId) { + self.pending_app_server_requests + .cancel_thread_verification(&thread_id.to_string()); let app_event_tx = self.app_event_tx.clone(); self.dynamic_tool_tasks .retain(|request_id, (source, task)| { diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__user_verification__tests__older_binary_verification_warning.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__user_verification__tests__older_binary_verification_warning.snap new file mode 100644 index 0000000000..01d537a93a --- /dev/null +++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__user_verification__tests__older_binary_verification_warning.snap @@ -0,0 +1,6 @@ +--- +source: tui/src/app/user_verification_tests.rs +assertion_line: 275 +expression: rendered +--- +⚠ The local Codex binary could not complete user verification. diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__user_verification__tests__remote_workspace_verification_warning.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__user_verification__tests__remote_workspace_verification_warning.snap new file mode 100644 index 0000000000..e961e9b929 --- /dev/null +++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__user_verification__tests__remote_workspace_verification_warning.snap @@ -0,0 +1,6 @@ +--- +source: tui/src/app/user_verification_tests.rs +assertion_line: 273 +expression: rendered +--- +⚠ User verification is unavailable for remote workspaces. diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index a3d6f456dd..5a5b59fdb8 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -65,6 +65,8 @@ mod thread_usage; mod transcript_composer; #[path = "tests/turn_submission.rs"] mod turn_submission; +#[path = "tests/user_verification_routes_tests.rs"] +mod user_verification_routes; use super::*; use crate::app_backtrack::BacktrackSelection; diff --git a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__user_verification_routes__inactive_thread_user_verification_foreground_history.snap b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__user_verification_routes__inactive_thread_user_verification_foreground_history.snap new file mode 100644 index 0000000000..2957f3e2b1 --- /dev/null +++ b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__user_verification_routes__inactive_thread_user_verification_foreground_history.snap @@ -0,0 +1,6 @@ +--- +source: tui/src/app/tests/user_verification_routes.rs +assertion_line: 194 +expression: "app.render_transcript_lines_for_reflow(80).lines.iter().map(rendered_line_text).collect::>().join(\"\\n\")" +--- +• The foreground answer continues. diff --git a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__user_verification_routes__inactive_thread_user_verification_prompt.snap b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__user_verification_routes__inactive_thread_user_verification_prompt.snap new file mode 100644 index 0000000000..4087c6a561 --- /dev/null +++ b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__user_verification_routes__inactive_thread_user_verification_prompt.snap @@ -0,0 +1,17 @@ +--- +source: tui/src/app/tests/user_verification_routes.rs +assertion_line: 67 +expression: "render_bottom_popup(&app.chat_widget, 80)" +--- + Approve deployment? + + Thread: Verifier [worker] + + Server: deployments + + Verify the production deployment. + +› 1. Verify and approve (y) + 2. Cancel this request (c) + + Press enter to confirm or esc to cancel diff --git a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__user_verification_routes__side_toggle_surfaces_pending_user_verification.snap b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__user_verification_routes__side_toggle_surfaces_pending_user_verification.snap new file mode 100644 index 0000000000..d0e5c5a673 --- /dev/null +++ b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__user_verification_routes__side_toggle_surfaces_pending_user_verification.snap @@ -0,0 +1,16 @@ +--- +source: tui/src/app/tests/user_verification_routes.rs +expression: "render_bottom_popup(&app.chat_widget, 80)" +--- + Approve deployment? + + Thread: Verifier [worker] + + Server: deployments + + Verify the production deployment. + +› 1. Verify and approve (y) + 2. Cancel this request (c) + + Press enter to confirm or esc to cancel diff --git a/codex-rs/tui/src/app/tests/user_verification_routes_tests.rs b/codex-rs/tui/src/app/tests/user_verification_routes_tests.rs new file mode 100644 index 0000000000..95d00bbcfc --- /dev/null +++ b/codex-rs/tui/src/app/tests/user_verification_routes_tests.rs @@ -0,0 +1,335 @@ +use super::*; +use pretty_assertions::assert_eq; + +fn user_verification_server_request(thread_id: ThreadId, request_id: i64) -> ServerRequest { + ServerRequest::McpServerElicitationRequest { + request_id: AppServerRequestId::Integer(request_id), + params: McpServerElicitationRequestParams { + thread_id: thread_id.to_string(), + turn_id: Some("turn-verification".to_string()), + server_name: "deployments".to_string(), + request: McpServerElicitationRequest::UserVerification { + title: "Approve deployment?".to_string(), + description: "Verify the production deployment.".to_string(), + challenge: "AQID".to_string(), + }, + }, + } +} + +async fn next_submitted_thread_op( + app_event_rx: &mut tokio::sync::mpsc::UnboundedReceiver, +) -> (ThreadId, Op) { + time::timeout(std::time::Duration::from_secs(/*secs*/ 1), async { + loop { + match app_event_rx.recv().await { + Some(AppEvent::SubmitThreadOp { thread_id, op }) => break (thread_id, op), + Some(_) => {} + None => panic!("app event channel closed before submitting an operation"), + } + } + }) + .await + .expect("user-verification operation should be submitted promptly") +} + +#[tokio::test] +async fn inactive_thread_user_verification_replays_queued_request_once() -> Result<()> { + let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await; + let primary_thread_id = ThreadId::new(); + let side_thread_id = ThreadId::new(); + let thread_id = ThreadId::new(); + let request = user_verification_server_request(thread_id, /*request_id*/ 11); + + app.primary_thread_id = Some(primary_thread_id); + app.active_thread_id = Some(side_thread_id); + app.side_threads + .insert(side_thread_id, SideThreadState::new(primary_thread_id)); + app.agent_navigation.upsert( + thread_id, + Some("Verifier".to_string()), + Some("worker".to_string()), + /*is_closed*/ false, + ); + app.enqueue_thread_request(thread_id, request.clone()) + .await?; + + assert!(!app.chat_widget.has_active_view()); + assert_eq!( + app.pending_inactive_thread_requests().await, + vec![(thread_id, request)] + ); + + app.side_threads.remove(&side_thread_id); + app.active_thread_id = Some(primary_thread_id); + app.surface_pending_inactive_thread_interactive_requests() + .await?; + app.surface_pending_inactive_thread_interactive_requests() + .await?; + insta::assert_snapshot!( + "inactive_thread_user_verification_prompt", + render_bottom_popup(&app.chat_widget, /*width*/ 80) + ); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + + assert_eq!( + next_submitted_thread_op(&mut app_event_rx).await, + ( + thread_id, + Op::ResolveUserVerification { + server_name: "deployments".to_string(), + request_id: AppServerRequestId::Integer(11), + response: crate::app_command::UserVerificationResponse::Cancel, + } + ) + ); + assert!(!app.chat_widget.has_active_view()); + assert!( + !std::iter::from_fn(|| app_event_rx.try_recv().ok()) + .any(|event| matches!(event, AppEvent::SubmitThreadOp { .. })) + ); + Ok(()) +} + +#[tokio::test] +async fn side_toggle_surfaces_pending_verification_from_an_inactive_thread() -> Result<()> { + Box::pin(async { + let (mut app, _events, _ops) = make_test_app_with_channels().await; + let mut app_server = + crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref()).await?; + let primary = app_server.start_thread(&app.config).await?; + let primary_thread_id = primary.session.thread_id; + app.enqueue_primary_thread_session(primary.session, primary.turns) + .await?; + + let side_thread_id = ThreadId::new(); + app.side_threads + .insert(side_thread_id, SideThreadState::new(primary_thread_id)); + app.thread_event_channels.insert( + side_thread_id, + ThreadEventChannel::new_with_session( + /*capacity*/ 4, + test_thread_session(side_thread_id, test_path_buf("/tmp/side")), + Vec::new(), + ), + ); + let mut tui = crate::tui::test_support::make_test_tui()?; + app.select_agent_thread(&mut tui, &mut app_server, side_thread_id) + .await?; + assert_eq!(app.active_thread_id, Some(side_thread_id)); + + let agent_thread_id = ThreadId::new(); + app.agent_navigation.upsert( + agent_thread_id, + Some("Verifier".to_string()), + Some("worker".to_string()), + /*is_closed*/ false, + ); + app.enqueue_thread_request( + agent_thread_id, + user_verification_server_request(agent_thread_id, /*request_id*/ 17), + ) + .await?; + assert!(!app.chat_widget.has_active_view()); + + app.toggle_side_conversation(&mut tui, &mut app_server) + .await?; + assert_eq!(app.active_thread_id, Some(primary_thread_id)); + insta::assert_snapshot!( + "side_toggle_surfaces_pending_user_verification", + render_bottom_popup(&app.chat_widget, /*width*/ 80) + ); + app_server.shutdown().await?; + Ok(()) + }) + .await +} + +#[tokio::test] +async fn discarding_side_cancels_verification_and_ignores_late_proof() -> Result<()> { + let (mut app, mut events, _ops) = make_test_app_with_channels().await; + let mut app_server = + crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref()).await?; + let primary_thread_id = ThreadId::new(); + let side_thread_id = ThreadId::new(); + let request = user_verification_server_request(side_thread_id, /*request_id*/ 19); + app.active_thread_id = Some(primary_thread_id); + app.side_threads + .insert(side_thread_id, SideThreadState::new(primary_thread_id)); + app.thread_event_channels + .insert(side_thread_id, ThreadEventChannel::new(/*capacity*/ 4)); + app.pending_app_server_requests + .note_server_request(&request); + let attempt = app + .pending_app_server_requests + .user_verification + .begin("deployments", request.id()) + .expect("pending side-thread verification"); + + app.discard_side_thread_in_background(&mut app_server, side_thread_id) + .await; + assert!(attempt.cancelled.is_cancelled()); + assert!( + !app.pending_app_server_requests + .contains_server_request(&request) + ); + + app.finish_user_verification( + &mut app_server, + side_thread_id, + "deployments".to_string(), + request.id().clone(), + attempt.id, + Ok(codex_app_server_protocol::UserVerificationProof { + credential_id: "discarded-credential".to_string(), + signature: "discarded-signature".to_string(), + }), + ) + .await?; + assert!( + !std::iter::from_fn(|| events.try_recv().ok()) + .any(|event| matches!(event, AppEvent::SubmitThreadOp { .. })) + ); + app_server.shutdown().await?; + Ok(()) +} + +#[tokio::test] +async fn inactive_thread_user_verification_preserves_foreground_stream() -> Result<()> { + let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await; + let foreground_thread_id = ThreadId::new(); + let thread_id = ThreadId::new(); + app.primary_thread_id = Some(foreground_thread_id); + app.active_thread_id = Some(foreground_thread_id); + app.chat_widget.handle_thread_session(test_thread_session( + foreground_thread_id, + test_path_buf("/tmp/project"), + )); + while app_event_rx.try_recv().is_ok() {} + app.chat_widget.handle_server_notification( + agent_message_delta_notification( + foreground_thread_id, + "turn-foreground", + "message-foreground", + "The foreground answer", + ), + /*replay_kind*/ None, + ); + assert!(app.chat_widget.has_active_agent_stream()); + + app.enqueue_thread_request( + thread_id, + user_verification_server_request(thread_id, /*request_id*/ 13), + ) + .await?; + assert!(app.chat_widget.has_active_view()); + assert!(app.chat_widget.has_active_agent_stream()); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + app.chat_widget.handle_server_notification( + agent_message_delta_notification( + foreground_thread_id, + "turn-foreground", + "message-foreground", + " continues.", + ), + /*replay_kind*/ None, + ); + app.chat_widget.handle_server_notification( + ServerNotification::ItemCompleted(codex_app_server_protocol::ItemCompletedNotification { + thread_id: foreground_thread_id.to_string(), + turn_id: "turn-foreground".to_string(), + completed_at_ms: 0, + item: ThreadItem::AgentMessage { + id: "message-foreground".to_string(), + text: "The foreground answer continues.".to_string(), + phase: None, + memory_citation: None, + delivery: None, + questions: None, + }, + }), + /*replay_kind*/ None, + ); + + let mut approved = Vec::new(); + let mut completed_messages = Vec::new(); + let mut tui = crate::tui::test_support::make_test_tui()?; + while let Ok(event) = app_event_rx.try_recv() { + match event { + AppEvent::UserVerificationApproved { + thread_id, + server_name, + request_id, + } => approved.push((thread_id, server_name, request_id)), + AppEvent::InsertHistoryCell(cell) => app.insert_history_cell(&mut tui, cell), + AppEvent::ConsolidateAgentMessage { + source, + cwd, + inline_visualization_context, + scrollback_reflow, + deferred_history_cell, + } => { + completed_messages.push(source.clone()); + app.handle_consolidate_agent_message( + &mut tui, + source, + cwd, + inline_visualization_context, + scrollback_reflow, + deferred_history_cell, + )?; + app.chat_widget.note_stream_consolidation_completed(); + } + _ => {} + } + } + assert_eq!( + approved, + vec![( + thread_id, + "deployments".to_string(), + AppServerRequestId::Integer(13) + )] + ); + assert_eq!(completed_messages, vec!["The foreground answer continues."]); + assert!(!app.chat_widget.has_active_agent_stream()); + insta::assert_snapshot!( + "inactive_thread_user_verification_foreground_history", + app.render_transcript_lines_for_reflow(/*width*/ 80) + .lines + .iter() + .map(rendered_line_text) + .collect::>() + .join("\n") + ); + Ok(()) +} + +#[tokio::test] +async fn active_thread_user_verification_cancels_through_original_request() { + let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await; + let thread_id = ThreadId::new(); + let request = user_verification_server_request(thread_id, /*request_id*/ 12); + + let ServerRequest::McpServerElicitationRequest { request_id, params } = request else { + panic!("elicitation request") + }; + app.chat_widget + .handle_elicitation_request_now(request_id, params); + app.chat_widget + .handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + + let (submitted_thread_id, op) = next_submitted_thread_op(&mut app_event_rx).await; + assert_eq!(submitted_thread_id, thread_id); + assert_eq!( + op, + Op::ResolveUserVerification { + server_name: "deployments".to_string(), + request_id: AppServerRequestId::Integer(12), + response: crate::app_command::UserVerificationResponse::Cancel, + } + ); +} diff --git a/codex-rs/tui/src/app/thread_routing.rs b/codex-rs/tui/src/app/thread_routing.rs index 45b370a8bd..165a8ec0cd 100644 --- a/codex-rs/tui/src/app/thread_routing.rs +++ b/codex-rs/tui/src/app/thread_routing.rs @@ -331,14 +331,18 @@ impl App { message: message.clone(), }), )), - codex_app_server_protocol::McpServerElicitationRequest::UserVerification { .. } => { - self.app_event_tx.resolve_elicitation( - thread_id, params.server_name.clone(), request_id.clone(), - codex_app_server_protocol::McpServerElicitationAction::Cancel, - /*content*/ None, /*meta*/ None, - ); - None - } + codex_app_server_protocol::McpServerElicitationRequest::UserVerification { + title, description, .. + } => Some(ThreadInteractiveRequest::UserVerification { + thread_id, + request: crate::bottom_pane::user_verification::UserVerificationRequest { + thread_label, + server_name: params.server_name.clone(), + request_id: request_id.clone(), + title: title.clone(), + description: description.clone(), + }, + }), codex_app_server_protocol::McpServerElicitationRequest::OpenAiForm { .. } @@ -397,6 +401,10 @@ impl App { self.startup_pending_protected_request = true; } } + ThreadInteractiveRequest::UserVerification { thread_id, request } => { + self.chat_widget + .push_user_verification_request(thread_id, request); + } ThreadInteractiveRequest::McpServerElicitation(request) => { self.chat_widget .push_mcp_server_elicitation_request(request); @@ -1914,9 +1922,7 @@ impl App { }; match ¶ms.request { - codex_app_server_protocol::McpServerElicitationRequest::UserVerification { .. } => { - false - } + codex_app_server_protocol::McpServerElicitationRequest::UserVerification { .. } => true, codex_app_server_protocol::McpServerElicitationRequest::Form { .. } => true, codex_app_server_protocol::McpServerElicitationRequest::OpenAiForm { .. } | codex_app_server_protocol::McpServerElicitationRequest::OpenAiElicitationForm { diff --git a/codex-rs/tui/src/app/user_verification.rs b/codex-rs/tui/src/app/user_verification.rs new file mode 100644 index 0000000000..5b34f22e1c --- /dev/null +++ b/codex-rs/tui/src/app/user_verification.rs @@ -0,0 +1,139 @@ +//! Coordinates approval through the local app-server, keeping proofs out of views. +//! +//! Attempt IDs are UI-local generations: cancellation, resolution, or reconnect removes the +//! pending generation, so a late RPC response cannot approve a newly surfaced request. + +use codex_app_server_protocol::ClientRequest; +use codex_app_server_protocol::RequestId; +use codex_app_server_protocol::ServerNotification; +use codex_app_server_protocol::UserVerificationProof; +use codex_app_server_protocol::UserVerificationVerifyResponse; +use codex_app_server_protocol::WarningNotification; +use codex_protocol::ThreadId; +use uuid::Uuid; + +use super::App; +use super::app_server_requests::ResolvedAppServerRequest; +use super::user_verification_errors::verification_error_message; +use crate::app_command::AppCommand; +use crate::app_command::UserVerificationResponse; +use crate::app_event::AppEvent; +use crate::app_server_session::AppServerSession; + +impl App { + pub(super) async fn start_user_verification( + &mut self, + app_server: &AppServerSession, + thread_id: ThreadId, + server_name: String, + request_id: RequestId, + ) -> color_eyre::Result<()> { + if app_server.uses_remote_workspace() { + self.chat_widget.dismiss_app_server_request( + &ResolvedAppServerRequest::McpElicitation { + server_name: server_name.clone(), + request_id: request_id.clone(), + }, + ); + self.enqueue_thread_notification( + thread_id, + ServerNotification::Warning(WarningNotification { + thread_id: Some(thread_id.to_string()), + message: "User verification is unavailable for remote workspaces.".to_string(), + }), + ) + .await?; + self.app_event_tx.resolve_user_verification( + thread_id, + server_name, + request_id, + UserVerificationResponse::Cancel, + ); + return Ok(()); + } + let Some(attempt) = self + .pending_app_server_requests + .user_verification + .begin(&server_name, &request_id) + else { + return Ok(()); + }; + let handle = app_server.request_handle(); + let app_event_tx = self.app_event_tx.clone(); + tokio::spawn(async move { + let attempt_id = attempt.id; + let verification = handle.request_typed::( + ClientRequest::UserVerificationVerify { + request_id: RequestId::String(format!("user-verification-{attempt_id}")), + params: attempt.params, + }, + ); + let result = tokio::select! { + biased; + _ = attempt.cancelled.cancelled() => return, + result = verification => result, + } + .map(|response| response.proof) + .map_err(|error| verification_error_message(&error).to_string()); + app_event_tx.send(AppEvent::UserVerificationFinished { + thread_id, + server_name, + request_id, + attempt_id, + result, + }); + }); + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + pub(super) async fn finish_user_verification( + &mut self, + app_server: &mut AppServerSession, + thread_id: ThreadId, + server_name: String, + request_id: RequestId, + attempt_id: Uuid, + result: Result, + ) -> color_eyre::Result<()> { + if self.abandoned_side_threads.contains(&thread_id) + || !self + .pending_app_server_requests + .user_verification + .is_pending(&server_name, &request_id, attempt_id) + { + return Ok(()); + } + let response = match result { + Ok(proof) => UserVerificationResponse::Accept { proof }, + Err(message) => { + self.enqueue_thread_notification( + thread_id, + ServerNotification::Warning(WarningNotification { + thread_id: Some(thread_id.to_string()), + message, + }), + ) + .await?; + // Another trusted device may be supported later. For now every incomplete + // verification cancels the original elicitation without a fallback provider. + UserVerificationResponse::Cancel + } + }; + self.chat_widget + .dismiss_app_server_request(&ResolvedAppServerRequest::McpElicitation { + server_name: server_name.clone(), + request_id: request_id.clone(), + }); + self.submit_thread_op( + app_server, + thread_id, + AppCommand::resolve_user_verification(server_name, request_id, response), + ) + .await + } +} + +#[cfg(test)] +#[path = "user_verification_tests.rs"] +mod tests; diff --git a/codex-rs/tui/src/app/user_verification_requests.rs b/codex-rs/tui/src/app/user_verification_requests.rs index 667d945054..dcbe7484bd 100644 --- a/codex-rs/tui/src/app/user_verification_requests.rs +++ b/codex-rs/tui/src/app/user_verification_requests.rs @@ -16,6 +16,7 @@ pub(super) struct UserVerificationRequests { #[derive(Debug)] struct PendingVerification { + thread_id: String, params: UserVerificationVerifyParams, attempt: Option, cancelled: CancellationToken, @@ -48,6 +49,7 @@ impl UserVerificationRequests { self.pending.insert( (params.server_name.clone(), request_id.clone()), PendingVerification { + thread_id: params.thread_id.clone(), params: UserVerificationVerifyParams { title: title.clone(), description: description.clone(), @@ -96,6 +98,19 @@ impl UserVerificationRequests { .remove(&(server_name.to_string(), request_id.clone())); } + pub(super) fn cancel_thread(&mut self, thread_id: &str) -> Vec<(String, RequestId)> { + let discarded_keys = self + .pending + .iter() + .filter(|(_, pending)| pending.thread_id == thread_id) + .map(|(key, _)| key.clone()) + .collect::>(); + for (server_name, request_id) in &discarded_keys { + self.remove(server_name, request_id); + } + discarded_keys + } + pub(super) fn clear(&mut self) { self.pending.clear(); } diff --git a/codex-rs/tui/src/app/user_verification_requests_tests.rs b/codex-rs/tui/src/app/user_verification_requests_tests.rs index b23a4285a9..19234b203c 100644 --- a/codex-rs/tui/src/app/user_verification_requests_tests.rs +++ b/codex-rs/tui/src/app/user_verification_requests_tests.rs @@ -72,6 +72,51 @@ fn user_verification_cancellation_invalidates_the_inflight_result() { assert!(attempt.cancelled.is_cancelled()); } +#[test] +fn discarded_thread_cancels_only_its_verification_attempts() { + let mut pending = PendingAppServerRequests::default(); + let request = verification_request(); + let ServerRequest::McpServerElicitationRequest { params, .. } = &request else { + unreachable!() + }; + let discarded_thread_id = params.thread_id.clone(); + pending.note_server_request(&request); + let discarded_attempt = pending + .user_verification + .begin("deployments", request.id()) + .expect("discarded thread attempt"); + + let mut other_request = verification_request(); + let ServerRequest::McpServerElicitationRequest { request_id, params } = &mut other_request + else { + unreachable!() + }; + *request_id = RequestId::Integer(8); + params.thread_id = ThreadId::new().to_string(); + pending.note_server_request(&other_request); + let other_attempt = pending + .user_verification + .begin("deployments", other_request.id()) + .expect("other thread attempt"); + + pending.cancel_thread_verification(&discarded_thread_id); + + assert!(discarded_attempt.cancelled.is_cancelled()); + assert!(!pending.contains_server_request(&request)); + assert!(!pending.user_verification.is_pending( + "deployments", + request.id(), + discarded_attempt.id + )); + assert!(!other_attempt.cancelled.is_cancelled()); + assert!(pending.contains_server_request(&other_request)); + assert!(pending.user_verification.is_pending( + "deployments", + other_request.id(), + other_attempt.id + )); +} + #[test] fn user_verification_reconnect_cannot_accept_a_previous_connections_proof() { let mut pending = PendingAppServerRequests::default(); diff --git a/codex-rs/tui/src/app/user_verification_tests.rs b/codex-rs/tui/src/app/user_verification_tests.rs new file mode 100644 index 0000000000..4b7b9f8bf9 --- /dev/null +++ b/codex-rs/tui/src/app/user_verification_tests.rs @@ -0,0 +1,305 @@ +//! Covers the controller's RPC boundary, cancellation generations, and proof redaction. + +use super::*; +use codex_app_server_protocol::McpServerElicitationRequest; +use codex_app_server_protocol::McpServerElicitationRequestParams; +use codex_app_server_protocol::ServerRequest; +use futures::SinkExt; +use futures::StreamExt; +use pretty_assertions::assert_eq; + +fn verification_request() -> ServerRequest { + ServerRequest::McpServerElicitationRequest { + request_id: RequestId::Integer(7), + params: McpServerElicitationRequestParams { + thread_id: ThreadId::new().to_string(), + turn_id: None, + server_name: "deployments".to_string(), + request: McpServerElicitationRequest::UserVerification { + title: "Approve deployment?".to_string(), + description: "Deploy the reviewed change.".to_string(), + challenge: "AQID".to_string(), + }, + }, + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum RpcScenario { + Success, + MethodNotFound, + CancelWhilePending, + RemoteWorkspace, +} + +#[tokio::test] +async fn user_verification_controller_uses_the_local_binary_rpc_and_original_response() +-> color_eyre::Result<()> { + run_verification_rpc_scenario(RpcScenario::Success).await +} + +#[tokio::test] +async fn user_verification_controller_cancels_for_an_older_binary() -> color_eyre::Result<()> { + run_verification_rpc_scenario(RpcScenario::MethodNotFound).await +} + +#[tokio::test] +async fn user_verification_controller_suppresses_a_late_proof_after_cancellation() +-> color_eyre::Result<()> { + run_verification_rpc_scenario(RpcScenario::CancelWhilePending).await +} + +#[tokio::test] +async fn user_verification_remote_workspace_dismisses_the_waiting_prompt() -> color_eyre::Result<()> +{ + run_verification_rpc_scenario(RpcScenario::RemoteWorkspace).await +} + +async fn run_verification_rpc_scenario(scenario: RpcScenario) -> color_eyre::Result<()> { + use codex_app_server_protocol::JSONRPCMessage; + use tokio_tungstenite::tungstenite::Message; + + let (mut app, mut event_rx, _op_rx) = crate::app::tests::make_test_app_with_channels().await; + let mut tui = crate::tui::test_support::make_test_tui()?; + let foreground_thread_id = ThreadId::new(); + app.active_thread_id = Some(foreground_thread_id); + app.primary_thread_id = Some(foreground_thread_id); + let request = verification_request(); + let ServerRequest::McpServerElicitationRequest { request_id, params } = &request else { + unreachable!() + }; + let thread_id = ThreadId::from_string(¶ms.thread_id)?; + app.pending_app_server_requests + .note_server_request(&request); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let endpoint = crate::resolve_remote_addr(&format!("ws://{}", listener.local_addr()?))?; + let expected_params = serde_json::json!({ "title": "Approve deployment?", "description": "Deploy the reviewed change.", "challenge": "AQID" }); + let proof = + serde_json::json!({ "credentialId": "issued-credential", "signature": "issued-signature" }); + let (verify_started_tx, verify_started_rx) = tokio::sync::oneshot::channel(); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await?; + let mut socket = tokio_tungstenite::accept_async(stream).await?; + let mut verify_started_tx = Some(verify_started_tx); + let mut pending_verification_id = None; + let mut response_received = false; + while let Some(frame) = socket.next().await { + let Message::Text(text) = frame? else { + continue; + }; + match serde_json::from_str::(&text)? { + JSONRPCMessage::Request(request) => { + let response = match request.method.as_str() { + "initialize" => { + serde_json::json!({ "id": request.id, "result": { "userAgent": "codex-tui-test", "codexHome": std::env::temp_dir(), "platformFamily": std::env::consts::FAMILY, "platformOs": std::env::consts::OS } }) + } + "userVerification/verify" => { + assert_eq!(request.params, Some(expected_params.clone())); + let _ = verify_started_tx + .take() + .expect("one verification attempt") + .send(()); + if scenario == RpcScenario::CancelWhilePending { + pending_verification_id = Some(request.id); + continue; + } + if scenario == RpcScenario::MethodNotFound { + serde_json::json!({ "id": request.id, "error": { "code": -32601, "message": "unknown method: private server diagnostic" } }) + } else { + serde_json::json!({ "id": request.id, "result": { "proof": proof } }) + } + } + "userVerification/status" => { + assert!(response_received); + socket.send(Message::Text(serde_json::json!({ "id": request.id, "result": { "unavailableReason": null, "unavailableMessage": null, "credentialId": null } }).to_string().into())).await?; + return Ok::<_, color_eyre::Report>(()); + } + method => panic!("unexpected RPC: {method}"), + }; + socket + .send(Message::Text(response.to_string().into())) + .await?; + } + JSONRPCMessage::Response(response) => { + assert!( + !response_received, + "a cancelled verification must never send a later acceptance" + ); + response_received = true; + assert_eq!(response.id, RequestId::Integer(7)); + let expected = if scenario == RpcScenario::Success { + serde_json::json!({ "action": "accept", "content": proof, "_meta": null }) + } else { + serde_json::json!({ "action": "cancel", "content": null, "_meta": null }) + }; + assert_eq!(response.result, expected); + if let Some(id) = pending_verification_id.take() { + socket + .send(Message::Text( + serde_json::json!({ "id": id, "result": { "proof": proof } }) + .to_string() + .into(), + )) + .await?; + continue; + } + return Ok::<_, color_eyre::Report>(()); + } + JSONRPCMessage::Notification(_) => {} + JSONRPCMessage::Error(error) => { + panic!("unexpected RPC error: {}", error.error.code) + } + } + } + color_eyre::eyre::bail!("connection closed before the elicitation response") + }); + let client = crate::connect_remote_app_server(endpoint).await?; + let mode = if scenario == RpcScenario::RemoteWorkspace { + app.chat_widget + .handle_elicitation_request_now(request_id.clone(), params.clone()); + app.chat_widget + .handle_key_event(crossterm::event::KeyEvent::new( + crossterm::event::KeyCode::Enter, + crossterm::event::KeyModifiers::NONE, + )); + assert!( + crate::chatwidget::tests::helpers::render_bottom_popup( + &app.chat_widget, + /*width*/ 80 + ) + .contains("Waiting for verification") + ); + crate::app_server_session::ThreadParamsMode::Remote + } else { + crate::app_server_session::ThreadParamsMode::Embedded + }; + let mut session = AppServerSession::new(client, mode); + let approval = if scenario == RpcScenario::RemoteWorkspace { + event_rx.recv().await.expect("approval event") + } else { + AppEvent::UserVerificationApproved { + thread_id, + server_name: "deployments".to_string(), + request_id: request_id.clone(), + } + }; + app.handle_event(&mut tui, &mut session, approval).await?; + if scenario == RpcScenario::RemoteWorkspace { + assert!( + !crate::chatwidget::tests::helpers::render_bottom_popup( + &app.chat_widget, + /*width*/ 80 + ) + .contains("Waiting for verification") + ); + let AppEvent::SubmitThreadOp { thread_id, op } = + event_rx.recv().await.expect("cancel request") + else { + panic!("expected cancel response"); + }; + app.submit_thread_op(&mut session, thread_id, op).await?; + } + if scenario == RpcScenario::CancelWhilePending { + tokio::time::timeout( + std::time::Duration::from_secs(/*secs*/ 5), + verify_started_rx, + ) + .await??; + app.submit_thread_op( + &mut session, + thread_id, + AppCommand::resolve_user_verification( + "deployments".to_string(), + request_id.clone(), + UserVerificationResponse::Cancel, + ), + ) + .await?; + } + if matches!(scenario, RpcScenario::Success | RpcScenario::MethodNotFound) { + let completion = + tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 5), event_rx.recv()) + .await? + .expect("controller result"); + assert!(matches!( + &completion, + AppEvent::UserVerificationFinished { .. } + )); + app.handle_event(&mut tui, &mut session, completion).await?; + } + if scenario == RpcScenario::CancelWhilePending { + // Flush the client command queue after processing the late proof. The mock rejects any + // second elicitation response before acknowledging this harmless read. + session + .request_handle() + .request_typed::( + ClientRequest::UserVerificationStatus { + request_id: RequestId::String("after-cancel".to_string()), + params: codex_app_server_protocol::UserVerificationStatusParams {}, + }, + ) + .await?; + assert!( + event_rx.try_recv().is_err(), + "cancelled verification must drop its RPC future" + ); + } + if matches!( + scenario, + RpcScenario::MethodNotFound | RpcScenario::RemoteWorkspace + ) { + // A failure for the background request must not enter the foreground transcript. + assert!(event_rx.try_recv().is_err()); + let snapshot = app.thread_event_channels[&thread_id] + .store + .lock() + .await + .snapshot(); + assert_eq!(snapshot.events.len(), 1); + let crate::app::ThreadBufferedEvent::Notification(notification) = &snapshot.events[0] + else { + panic!("expected verification warning"); + }; + let message = if scenario == RpcScenario::RemoteWorkspace { + "User verification is unavailable for remote workspaces." + } else { + "The local Codex binary could not complete user verification." + }; + let ServerNotification::Warning(warning) = notification.as_ref() else { + panic!("expected warning notification"); + }; + assert_eq!( + warning, + &WarningNotification { + thread_id: Some(thread_id.to_string()), + message: message.to_string(), + } + ); + // Render the buffered warning as it appears when the requesting thread is displayed. + app.chat_widget + .handle_server_notification(*notification.clone(), /*replay_kind*/ None); + let AppEvent::InsertHistoryCell(cell) = event_rx.recv().await.expect("warning history") + else { + panic!("expected warning history cell"); + }; + let rendered = cell + .display_lines(/*width*/ 80) + .iter() + .map(|line| { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect::() + }) + .collect::>() + .join("\n"); + if scenario == RpcScenario::RemoteWorkspace { + insta::assert_snapshot!("remote_workspace_verification_warning", rendered); + } else { + insta::assert_snapshot!("older_binary_verification_warning", rendered); + } + } + tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 5), server).await???; + session.shutdown().await?; + Ok(()) +} diff --git a/codex-rs/tui/src/app_command.rs b/codex-rs/tui/src/app_command.rs index 500c2d5d8c..6ce89a19b8 100644 --- a/codex-rs/tui/src/app_command.rs +++ b/codex-rs/tui/src/app_command.rs @@ -162,7 +162,6 @@ pub(crate) enum AppCommand { content: Option, meta: Option, }, - #[allow(dead_code)] // Connected by the following verification UI integration. ResolveUserVerification { server_name: String, request_id: AppServerRequestId, @@ -194,7 +193,6 @@ pub(crate) enum AppCommand { } #[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[allow(dead_code)] // Connected by the following verification UI integration. pub(crate) enum UserVerificationResponse { Accept { // AppCommand serialization is used by session recording, not the RPC wire response. @@ -313,7 +311,6 @@ impl AppCommand { } } - #[allow(dead_code)] // Connected by the following verification UI integration. pub(crate) fn resolve_user_verification( server_name: String, request_id: AppServerRequestId, diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 7ce594462e..b24a3dc439 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -350,6 +350,21 @@ pub(crate) enum AppEvent { prompt: UserMessage, }, + /// Sign the challenge associated with an approved elicitation. + UserVerificationApproved { + thread_id: ThreadId, + server_name: String, + request_id: AppServerRequestId, + }, + /// Return a controller-owned verification result, never a native provider handle. + UserVerificationFinished { + thread_id: ThreadId, + server_name: String, + request_id: AppServerRequestId, + attempt_id: Uuid, + result: Result, + }, + /// Interrupt, fork, and retry a safety-buffered turn with the server-selected model. RetrySafetyBufferedTurn { thread_id: ThreadId, diff --git a/codex-rs/tui/src/app_event_sender.rs b/codex-rs/tui/src/app_event_sender.rs index 6c1606761d..69d1fc4620 100644 --- a/codex-rs/tui/src/app_event_sender.rs +++ b/codex-rs/tui/src/app_event_sender.rs @@ -6,6 +6,7 @@ use std::path::PathBuf; use crate::app_command::AppCommand; +use crate::app_command::UserVerificationResponse; use codex_app_server_protocol::CommandExecutionApprovalDecision; use codex_app_server_protocol::FileChangeApprovalDecision; use codex_app_server_protocol::McpServerElicitationAction; @@ -121,4 +122,17 @@ impl AppEventSender { op: AppCommand::resolve_elicitation(server_name, request_id, decision, content, meta), }); } + + pub(crate) fn resolve_user_verification( + &self, + thread_id: ThreadId, + server_name: String, + request_id: AppServerRequestId, + response: UserVerificationResponse, + ) { + self.send(AppEvent::SubmitThreadOp { + thread_id, + op: AppCommand::resolve_user_verification(server_name, request_id, response), + }); + } } diff --git a/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs b/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs index 6d33284eb6..84e373830e 100644 --- a/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs +++ b/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs @@ -144,6 +144,11 @@ pub(crate) trait BottomPaneView: Renderable { Some(request) } + /// Return true when this view already presents the matching app-server request. + fn matches_app_server_request(&self, _request: &ResolvedAppServerRequest) -> bool { + false + } + /// Dismiss a request that was resolved by another client. /// /// Returns `true` when the view changed state. diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 37ecd4fd03..8c75f87b39 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -77,7 +77,6 @@ mod status_line_setup; mod status_line_style; mod status_surface_preview; mod title_setup; -#[allow(dead_code)] // Connected by the following verification UI integration. pub(crate) mod user_verification; mod voice_strip; pub(crate) use action_required_title::ACTION_REQUIRED_PREVIEW_PREFIX; diff --git a/codex-rs/tui/src/bottom_pane/user_verification.rs b/codex-rs/tui/src/bottom_pane/user_verification.rs index 0e8a48fa60..9a4dc2091c 100644 --- a/codex-rs/tui/src/bottom_pane/user_verification.rs +++ b/codex-rs/tui/src/bottom_pane/user_verification.rs @@ -199,10 +199,13 @@ impl BottomPaneView for UserVerificationView { } } - fn dismiss_app_server_request(&mut self, request: &ResolvedAppServerRequest) -> bool { - if matches!(request, ResolvedAppServerRequest::McpElicitation { server_name, request_id } + fn matches_app_server_request(&self, request: &ResolvedAppServerRequest) -> bool { + matches!(request, ResolvedAppServerRequest::McpElicitation { server_name, request_id } if server_name == &self.request.server_name && request_id == &self.request.request_id) - { + } + + fn dismiss_app_server_request(&mut self, request: &ResolvedAppServerRequest) -> bool { + if self.matches_app_server_request(request) { self.state = UserVerificationState::Complete(ViewCompletion::Accepted); true } else { @@ -300,3 +303,54 @@ fn waiting_view(request: &UserVerificationRequest, keymap: &ListKeymap) -> Box { + app_event_tx.send(crate::app_event::AppEvent::UserVerificationApproved { + thread_id, + server_name: server_name.clone(), + request_id: request_id.clone(), + }); + } + UserVerificationDecision::Cancel => app_event_tx.resolve_user_verification( + thread_id, + server_name.clone(), + request_id.clone(), + crate::app_command::UserVerificationResponse::Cancel, + ), + }), + ); + self.pause_status_timer_for_modal(); + self.set_composer_input_enabled( + /*enabled*/ false, + Some("Complete user verification to continue.".to_string()), + ); + self.push_view(Box::new(view)); + } +} diff --git a/codex-rs/tui/src/chatwidget/tool_requests.rs b/codex-rs/tui/src/chatwidget/tool_requests.rs index 8f7a4216b2..6f35d0c08f 100644 --- a/codex-rs/tui/src/chatwidget/tool_requests.rs +++ b/codex-rs/tui/src/chatwidget/tool_requests.rs @@ -373,14 +373,18 @@ impl ChatWidget { self.bottom_pane .push_approval_request(request, &self.config.features); } - McpServerElicitationRequest::UserVerification { .. } => { - self.app_event_tx.resolve_elicitation( + McpServerElicitationRequest::UserVerification { + title, description, .. + } => { + self.bottom_pane.push_user_verification_request( thread_id, - params.server_name, - request_id, - codex_app_server_protocol::McpServerElicitationAction::Cancel, - /*content*/ None, - /*meta*/ None, + crate::bottom_pane::user_verification::UserVerificationRequest { + thread_label: None, + server_name: params.server_name, + request_id, + title, + description, + }, ); } McpServerElicitationRequest::OpenAiForm { .. } @@ -414,6 +418,21 @@ impl ChatWidget { self.request_redraw(); } + pub(crate) fn push_user_verification_request( + &mut self, + thread_id: ThreadId, + request: crate::bottom_pane::user_verification::UserVerificationRequest, + ) { + // Inactive-thread prompts must leave the foreground stream and command activity intact. + self.bottom_pane + .push_user_verification_request(thread_id, request); + self.set_ambient_pet_notification( + crate::pets::PetNotificationKind::Waiting, + /*body*/ None, + ); + self.request_redraw(); + } + pub(crate) fn push_mcp_server_elicitation_request( &mut self, request: McpServerElicitationFormRequest,