mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Enable MCP user verification in the TUI (#43712)
## Why The TUI automatically canceled MCP user verification requests, preventing users from completing verification and approving them. ## What changed - Show verification prompts for active and inactive threads, with actions to verify and approve or cancel. - Run approved verification through the local app-server's `userVerification/verify` RPC and return the proof to the original request. Cancel on failure and show a warning in the requesting thread; remote workspaces remain unsupported. - Deduplicate prompts, preserve foreground streaming when another thread requests verification, and surface queued prompts when returning from a side conversation. - Cancel verification when its thread is discarded and ignore stale results after cancellation. ## Testing Add RPC, routing, and snapshot tests covering successful verification, unsupported binaries and remote workspaces, cancellation and late proofs, prompt replay, side conversation switching, and foreground stream preservation. GitOrigin-RevId: 2ae12f47c443e17de25f4ec033f6078ac28b1e03
This commit is contained in:
1 parent
95327467c3
commit
c7f81afc19
23 files changed
+1060
-29
No files matched your search
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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)| {
|
||||
|
||||
+6
@@ -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.
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
---
|
||||
source: tui/src/app/user_verification_tests.rs
|
||||
assertion_line: 273
|
||||
expression: rendered
|
||||
---
|
||||
⚠ User verification is unavailable for remote workspaces.
|
||||
@@ -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;
|
||||
|
||||
+6
@@ -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::<Vec<_>>().join(\"\\n\")"
|
||||
---
|
||||
• The foreground answer continues.
|
||||
+17
@@ -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
|
||||
+16
@@ -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
|
||||
@@ -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<AppEvent>,
|
||||
) -> (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::<Vec<_>>()
|
||||
.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,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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::<UserVerificationVerifyResponse>(
|
||||
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<UserVerificationProof, String>,
|
||||
) -> 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;
|
||||
@@ -16,6 +16,7 @@ pub(super) struct UserVerificationRequests {
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PendingVerification {
|
||||
thread_id: String,
|
||||
params: UserVerificationVerifyParams,
|
||||
attempt: Option<Uuid>,
|
||||
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::<Vec<_>>();
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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::<JSONRPCMessage>(&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::<codex_app_server_protocol::UserVerificationStatusResponse>(
|
||||
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::<String>()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.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(())
|
||||
}
|
||||
Reference in new issue
Block a user