mirror of
https://github.com/openai/codex.git
synced 2026-12-03 00:41:03 +00:00
Scope TUI reconnect recovery to the affected backend (#65154)
## Why When the active backend reconnects, the TUI can discard pending work on other connected backends. Completions queued before the reconnect can also arrive after the replacement connection is active. ## What changed - Preserve pending requests and thread state for other connected backends. Track asynchronous completions by connection so retired connections cannot update the TUI. - Apply request resolution from background backends to pending prompts and the agents overview. Require users to end a voice call before switching sessions across backends. - Close the verification prompt when verification finishes and suppress queued proofs when the user cancels the prompt. ## Testing Add regression coverage for preserving another backend's pending work during reconnect, dropping stale completions, resolving background requests, and cancelling verification after a proof has been queued. GitOrigin-RevId: fc932b0d13fd1cf04404bd5ccfce71ff776e259f
This commit is contained in:
committed by
copyberry
parent
028590df7d
commit
ed3ccd4c21
@@ -579,6 +579,7 @@ pub(crate) struct App {
|
||||
pub(crate) session_telemetry: SessionTelemetry,
|
||||
terminal_size_tags: crate::terminal_size_telemetry::LaunchTags,
|
||||
pub(crate) app_event_tx: AppEventSender,
|
||||
backend_event_generations: HashMap<crate::backend_id::BackendId, uuid::Uuid>,
|
||||
backend_registry: backend_registry::BackendRegistry,
|
||||
pub(crate) chat_widget: ChatWidget,
|
||||
workspace_command_runner: Option<WorkspaceCommandRunner>,
|
||||
|
||||
@@ -792,9 +792,9 @@ impl App {
|
||||
});
|
||||
return;
|
||||
}
|
||||
let app_event_tx = self.backend_completion_sender(backend_id);
|
||||
let generation = uuid::Uuid::new_v4();
|
||||
let request_handle = app_server_client.request_handle();
|
||||
let app_event_tx = self.app_event_tx.for_backend(backend_id);
|
||||
let status_updates = self.dynamic_tool_status_updates.subscribe();
|
||||
let request_id = request_id.clone();
|
||||
let task_request_id = request_id.clone();
|
||||
|
||||
@@ -88,13 +88,20 @@ impl PendingAppServerRequests {
|
||||
.unwrap_or_else(|_| thread_id.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn clear(&mut self) {
|
||||
self.exec_approvals.clear();
|
||||
self.file_change_approvals.clear();
|
||||
self.permissions_approvals.clear();
|
||||
self.user_inputs.clear();
|
||||
self.mcp_requests.clear();
|
||||
self.user_verification.clear();
|
||||
self.retain_threads(|_| false);
|
||||
}
|
||||
|
||||
pub(super) fn retain_threads(&mut self, mut keep: impl FnMut(&str) -> bool) {
|
||||
self.exec_approvals.retain(|(thread, _), _| keep(thread));
|
||||
self.file_change_approvals
|
||||
.retain(|(thread, _), _| keep(thread));
|
||||
self.permissions_approvals
|
||||
.retain(|(thread, _), _| keep(thread));
|
||||
self.user_inputs.retain(|(thread, _), _| keep(thread));
|
||||
self.mcp_requests.retain(|key, _| keep(&key.thread_id));
|
||||
self.user_verification.retain_threads(keep);
|
||||
}
|
||||
|
||||
pub(super) fn cancel_thread_verification(&mut self, thread_id: &str) {
|
||||
|
||||
@@ -63,6 +63,25 @@ impl App {
|
||||
&& let ServerNotificationThreadTarget::Thread(thread_id) =
|
||||
server_notification_thread_target(notification)
|
||||
{
|
||||
if self.backend_registry.owner(thread_id) == Some(event.backend_id)
|
||||
&& let ServerNotification::ServerRequestResolved(resolved) = notification
|
||||
{
|
||||
if let Some(requests) =
|
||||
self.agents_overview.dispatched_requests.get_mut(&thread_id)
|
||||
{
|
||||
requests.retain(|request| request.request.id() != &resolved.request_id);
|
||||
}
|
||||
self.pending_app_server_requests
|
||||
.resolve_notification(&resolved.thread_id, &resolved.request_id);
|
||||
if let Some(channel) = self.thread_event_channels.get(&thread_id) {
|
||||
channel
|
||||
.store
|
||||
.lock()
|
||||
.await
|
||||
.push_notification_ref(notification);
|
||||
}
|
||||
self.repaint_agents_overview();
|
||||
}
|
||||
if self.backend_registry.owner(thread_id) == Some(event.backend_id)
|
||||
&& let Some((_, sender)) = self.temporary_structured_requests.get(&thread_id)
|
||||
&& matches!(
|
||||
|
||||
@@ -626,6 +626,10 @@ impl App {
|
||||
{
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
if self.voice_owner_thread_id().is_some() {
|
||||
self.add_session_picker_error("End the voice call before switching.".into());
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
if let Some(thread_id) = self.current_displayed_thread_id()
|
||||
&& self.active_turn_id_for_thread(thread_id).await.is_some()
|
||||
{
|
||||
|
||||
@@ -13,7 +13,40 @@ pub(super) struct DynamicToolTask {
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) fn backend_completion_sender(
|
||||
&mut self,
|
||||
owner: BackendId,
|
||||
) -> crate::app_event_sender::AppEventSender {
|
||||
#[cfg(test)]
|
||||
if self.backend_event_generations.is_empty() {
|
||||
return self.app_event_tx.for_backend(owner);
|
||||
}
|
||||
let generation = *self
|
||||
.backend_event_generations
|
||||
.entry(owner)
|
||||
.or_insert_with(uuid::Uuid::new_v4);
|
||||
self.saved_openings.tx.for_connection(owner, generation)
|
||||
}
|
||||
|
||||
pub(super) fn accept_backend_completion(
|
||||
&self,
|
||||
event: crate::app_event::AppEvent,
|
||||
) -> Option<crate::app_event::AppEvent> {
|
||||
match event {
|
||||
crate::app_event::AppEvent::BackendCompletion {
|
||||
backend_id,
|
||||
generation,
|
||||
event,
|
||||
} if self.backend_event_generations.get(&backend_id) == Some(&generation) => {
|
||||
Some(*event)
|
||||
}
|
||||
crate::app_event::AppEvent::BackendCompletion { .. } => None,
|
||||
event => Some(event),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn cancel_dynamic_tools_for_backend(&mut self, owner: BackendId) {
|
||||
self.backend_event_generations.remove(&owner);
|
||||
for (_, task) in self
|
||||
.dynamic_tool_tasks
|
||||
.extract_if(|(backend, _), _| *backend == owner)
|
||||
|
||||
@@ -179,6 +179,7 @@ impl App {
|
||||
| AppEvent::BeginInitialHistoryReplayBuffer
|
||||
| AppEvent::BeginThreadSwitchHistoryReplayBuffer
|
||||
| AppEvent::EndInitialHistoryReplayBuffer
|
||||
| AppEvent::UserVerificationFinished { .. }
|
||||
| AppEvent::DynamicToolCallCompleted { .. }
|
||||
| AppEvent::DynamicToolThreadStarted { .. }
|
||||
| AppEvent::TaskToolsAvailable { .. }
|
||||
@@ -293,6 +294,7 @@ impl App {
|
||||
event => (event, None),
|
||||
};
|
||||
match event {
|
||||
AppEvent::BackendCompletion { .. } => {}
|
||||
AppEvent::OpenDaemonMenu => {
|
||||
let policy_error = if self.daemon_cli_executable.is_some()
|
||||
&& !matches!(self.app_server_target, AppServerTarget::Remote { .. } | AppServerTarget::Cloud)
|
||||
@@ -330,12 +332,16 @@ impl App {
|
||||
self.pending_update_action = Some(UpdateAction::Daemon(source));
|
||||
return Ok(self.handle_exit_mode(app_server, ExitMode::Immediate).await);
|
||||
}
|
||||
AppEvent::UserVerificationApproved { thread_id, server_name, request_id } => {
|
||||
Box::pin(self.start_user_verification(app_server, thread_id, server_name, request_id)).await?;
|
||||
AppEvent::UserVerificationApproved { prompt_cancelled, thread_id, server_name, request_id } => {
|
||||
if !prompt_cancelled.is_cancelled() {
|
||||
Box::pin(self.start_user_verification(app_server, thread_id, server_name, request_id, prompt_cancelled)).await?;
|
||||
}
|
||||
}
|
||||
AppEvent::UserVerificationFinished { thread_id, server_name, request_id, attempt_id, result } => {
|
||||
AppEvent::UserVerificationFinished { prompt_cancelled, backend_id: _, 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?;
|
||||
if !prompt_cancelled.is_cancelled() {
|
||||
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);
|
||||
|
||||
@@ -247,7 +247,7 @@ impl App {
|
||||
.map(|profile| profile.id),
|
||||
};
|
||||
let backend_id = app_server.backend_id();
|
||||
let event_sender = self.app_event_tx.clone();
|
||||
let event_sender = self.backend_completion_sender(backend_id);
|
||||
let task = tokio::spawn(async move {
|
||||
let result = start_temporary_thread(&request_handle, options)
|
||||
.await
|
||||
@@ -354,7 +354,7 @@ impl App {
|
||||
.insert(temporary_thread_id, (TemporaryThreadKind::Recap, sender));
|
||||
|
||||
let backend_id = app_server.backend_id();
|
||||
let event_sender = self.app_event_tx.clone();
|
||||
let event_sender = self.backend_completion_sender(backend_id);
|
||||
let task = tokio::spawn(async move {
|
||||
let result = run_temporary_structured_turn(
|
||||
request_handle,
|
||||
|
||||
@@ -279,11 +279,17 @@ impl App {
|
||||
{
|
||||
self.chat_widget.restore_user_message_to_composer(message);
|
||||
}
|
||||
if let Some(owner) = self.background_voice.as_mut() {
|
||||
owner.record_realtime_disconnect_failure();
|
||||
owner.reset_realtime_conversation();
|
||||
if self
|
||||
.voice_owner_thread_id()
|
||||
.and_then(|thread| self.backend_registry.owner(thread))
|
||||
== self.app_server_backend_id
|
||||
{
|
||||
if let Some(owner) = self.background_voice.as_mut() {
|
||||
owner.record_realtime_disconnect_failure();
|
||||
owner.reset_realtime_conversation();
|
||||
}
|
||||
self.retire_background_voice();
|
||||
}
|
||||
self.retire_background_voice();
|
||||
self.saved_openings.abandon();
|
||||
for pane in self.sidebars.values_mut() {
|
||||
pane.invalidate_discovery(self.app_server_backend_id);
|
||||
@@ -528,7 +534,19 @@ impl App {
|
||||
.for_backend(app_server.backend_id(), &mut self.provider_writes)
|
||||
.with_collaboration_modes(bootstrap.collaboration_modes),
|
||||
);
|
||||
self.pending_app_server_requests.clear();
|
||||
let interrupted_overview_owner =
|
||||
self.agents_overview.active_refresh.map(|(_, owner)| owner);
|
||||
if let Some(owner) = interrupted_overview_owner {
|
||||
self.cancel_agents_overview_refresh(owner);
|
||||
}
|
||||
let reconnecting = app_server.backend_id();
|
||||
let registry = &self.backend_registry;
|
||||
self.pending_app_server_requests.retain_threads(|id| {
|
||||
ThreadId::from_string(id)
|
||||
.ok()
|
||||
.and_then(|id| registry.owner(id))
|
||||
.is_some_and(|owner| owner != reconnecting)
|
||||
});
|
||||
// The displayed task was resumed above. Keep offscreen selections pending until those
|
||||
// tasks can be resumed from the server too; their old confirmations cannot arrive.
|
||||
let pending_displayed_profile = displayed.and_then(|id| {
|
||||
@@ -548,18 +566,34 @@ impl App {
|
||||
self.pending_primary_events.clear();
|
||||
self.pending_plugin_enabled_writes.clear();
|
||||
self.pending_hook_enabled_writes.clear();
|
||||
self.temporary_structured_requests.clear();
|
||||
for (_, cancellation) in self.pending_thread_titles.drain() {
|
||||
cancellation.cancel();
|
||||
}
|
||||
self.agents_overview.dispatched_requests.clear();
|
||||
let interrupted_overview_owner =
|
||||
self.agents_overview.active_refresh.map(|(_, owner)| owner);
|
||||
if let Some(owner) = interrupted_overview_owner {
|
||||
self.cancel_agents_overview_refresh(owner);
|
||||
}
|
||||
for input in self.agents_overview.input_states.values_mut() {
|
||||
input.reconnect_pending = true;
|
||||
self.temporary_structured_requests.retain(|thread, _| {
|
||||
registry
|
||||
.owner(*thread)
|
||||
.is_some_and(|owner| owner != reconnecting)
|
||||
});
|
||||
self.pending_thread_titles
|
||||
.retain(|(thread, _), cancellation| {
|
||||
if registry
|
||||
.owner(*thread)
|
||||
.is_some_and(|owner| owner != reconnecting)
|
||||
{
|
||||
true
|
||||
} else {
|
||||
cancellation.cancel();
|
||||
false
|
||||
}
|
||||
});
|
||||
self.agents_overview
|
||||
.dispatched_requests
|
||||
.retain(|thread, _| {
|
||||
registry
|
||||
.owner(*thread)
|
||||
.is_some_and(|owner| owner != reconnecting)
|
||||
});
|
||||
for (thread, input) in &mut self.agents_overview.input_states {
|
||||
if registry.owner(*thread) == Some(reconnecting) {
|
||||
input.reconnect_pending = true;
|
||||
}
|
||||
}
|
||||
self.pending_startup_thread_start = matches!(
|
||||
self.reconnect.presentation,
|
||||
@@ -568,6 +602,12 @@ impl App {
|
||||
// Move cached UI state into fresh channels. Old producers retain the old sender/store,
|
||||
// so their late requests cannot leak into recovery. Background threads attach on selection.
|
||||
for (&thread_id, channel) in &mut self.thread_event_channels {
|
||||
if registry
|
||||
.owner(thread_id)
|
||||
.is_some_and(|owner| owner != reconnecting)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut replacement = ThreadEventChannel::new(THREAD_EVENT_CHANNEL_CAPACITY);
|
||||
replacement.archived = channel.archived || archived_thread == Some(thread_id);
|
||||
replacement.backend_id = channel.backend_id;
|
||||
@@ -709,11 +749,9 @@ impl App {
|
||||
);
|
||||
}
|
||||
// Only accept fresh task-tool calls once this connection and its event queue are adopted.
|
||||
let sender = self.backend_completion_sender(app_server.backend_id());
|
||||
if let ThreadToolTransport::Mcp(server) = app_server.thread_tool_transport() {
|
||||
server.reconnect(
|
||||
app_server.request_handle(),
|
||||
self.app_event_tx.for_backend(app_server.backend_id()),
|
||||
);
|
||||
server.reconnect(app_server.request_handle(), sender);
|
||||
}
|
||||
self.reconnect.offline = false;
|
||||
if self.chat_widget.refresh_config_panel(/*notice*/ None) {
|
||||
|
||||
@@ -86,11 +86,15 @@ async fn open_in_codex_scenario() -> Result<()> {
|
||||
Arc::clone(&app.environment_manager),
|
||||
)
|
||||
.await?;
|
||||
let generation = uuid::Uuid::new_v4();
|
||||
app.backend_event_generations
|
||||
.insert(server.backend_id(), generation);
|
||||
server
|
||||
.start_dynamic_tool_mcp(
|
||||
config.clone(),
|
||||
app.local_settings.workspace_enabled(&config),
|
||||
app.app_event_tx.clone(),
|
||||
app.app_event_tx
|
||||
.for_connection(server.backend_id(), generation),
|
||||
app.dynamic_tool_status_updates.clone(),
|
||||
)
|
||||
.await?;
|
||||
@@ -194,6 +198,8 @@ async fn open_in_codex_scenario() -> Result<()> {
|
||||
let mut tui = crate::tui::test_support::make_test_tui_with_size(size)?;
|
||||
tui.set_owned_screen(/*owned*/ true)?;
|
||||
while let Ok(event) = events.try_recv() {
|
||||
assert!(!matches!(event, AppEvent::OpenModelSidebarDocument { .. }));
|
||||
let event = app.accept_backend_completion(event).unwrap();
|
||||
boxed_future!(app.handle_event(&mut tui, &mut server, event)).await?;
|
||||
}
|
||||
boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Draw)).await?;
|
||||
|
||||
@@ -370,6 +370,7 @@ impl App {
|
||||
startup_try!(target.ensure_backend(app_server.backend_id()));
|
||||
}
|
||||
let (app_event_tx, mut app_event_rx) = unbounded_channel();
|
||||
let saved_openings = super::sidebar_loading::Openings::default();
|
||||
let app_event_tx = AppEventSender::new(app_event_tx);
|
||||
if let Some(message) = project_config_warning(&config) {
|
||||
app_event_tx.send(AppEvent::InsertHistoryCell(Box::new(
|
||||
@@ -620,6 +621,7 @@ impl App {
|
||||
.cloud_config_bundle(cloud_config_bundle.clone()),
|
||||
));
|
||||
let dynamic_tool_status_updates = tokio::sync::broadcast::channel(/*capacity*/ 64).0;
|
||||
let initial_generation = uuid::Uuid::new_v4();
|
||||
if matches!(
|
||||
&app_server_target,
|
||||
AppServerTarget::LocalDaemon { .. } | AppServerTarget::Embedded
|
||||
@@ -630,7 +632,9 @@ impl App {
|
||||
.start_dynamic_tool_mcp(
|
||||
config.clone(),
|
||||
local_settings.workspace_enabled(&config),
|
||||
app_event_tx.for_backend(app_server.backend_id()),
|
||||
saved_openings
|
||||
.tx
|
||||
.for_connection(app_server.backend_id(), initial_generation),
|
||||
dynamic_tool_status_updates.clone(),
|
||||
)
|
||||
.await
|
||||
@@ -1122,6 +1126,10 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
session_telemetry: session_telemetry.clone(),
|
||||
terminal_size_tags: tui.terminal_size_tags.clone(),
|
||||
app_event_tx,
|
||||
backend_event_generations: HashMap::from([(
|
||||
app_server.backend_id(),
|
||||
initial_generation,
|
||||
)]),
|
||||
chat_widget,
|
||||
workspace_command_runner: Some(workspace_command_runner),
|
||||
backend_preference_context,
|
||||
@@ -1209,7 +1217,7 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
),
|
||||
agents_overview,
|
||||
side_threads: HashMap::new(),
|
||||
saved_openings: Default::default(),
|
||||
saved_openings,
|
||||
sidebars: HashMap::new(),
|
||||
model_preview_load: None,
|
||||
side_companions: HashMap::new(),
|
||||
@@ -1717,6 +1725,7 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
AppRunControl::Continue
|
||||
}
|
||||
Some(event) = app.saved_openings.next_event(&mut app_event_rx) => {
|
||||
let Some(event) = app.accept_backend_completion(event) else { continue };
|
||||
if let AppEvent::ArchiveFinished { backend_id, thread_id, result: Ok(()) } = &event
|
||||
&& *backend_id != displayed_owner
|
||||
&& let Some(slot) = backends.slot(*backend_id)
|
||||
@@ -1794,6 +1803,7 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
}
|
||||
AppEvent::DynamicToolThreadStarted { backend_id: Some(backend_id), .. }
|
||||
| AppEvent::TaskToolsAvailable { backend_id, .. }
|
||||
| AppEvent::UserVerificationFinished { backend_id, .. }
|
||||
| AppEvent::ThreadTitleStarted { backend_id, .. }
|
||||
| AppEvent::GeneratedThreadTitle { backend_id, .. }
|
||||
| AppEvent::RecapStarted { backend_id, .. }
|
||||
|
||||
@@ -63,6 +63,7 @@ pub(crate) async fn make_test_app() -> Box<App> {
|
||||
model_catalog: chat_widget.model_catalog(),
|
||||
session_telemetry,
|
||||
terminal_size_tags: Vec::new(),
|
||||
backend_event_generations: HashMap::new(),
|
||||
app_event_tx,
|
||||
backend_registry: Default::default(),
|
||||
local_settings: chat_widget.local_settings.clone(),
|
||||
|
||||
@@ -9160,6 +9160,7 @@ async fn make_test_app() -> Box<App> {
|
||||
model_catalog: chat_widget.model_catalog(),
|
||||
session_telemetry,
|
||||
terminal_size_tags: Vec::new(),
|
||||
backend_event_generations: HashMap::new(),
|
||||
app_event_tx,
|
||||
chat_widget,
|
||||
workspace_command_runner: None,
|
||||
@@ -9306,6 +9307,7 @@ pub(super) async fn make_test_app_with_channels() -> (
|
||||
model_catalog: chat_widget.model_catalog(),
|
||||
session_telemetry,
|
||||
terminal_size_tags: Vec::new(),
|
||||
backend_event_generations: HashMap::new(),
|
||||
app_event_tx,
|
||||
chat_widget,
|
||||
workspace_command_runner: None,
|
||||
|
||||
@@ -5,6 +5,7 @@ use crate::app::reconnect::ReconnectPresentation;
|
||||
use crate::app::reconnect::reconnect;
|
||||
use codex_config::types::KeybindingSpec;
|
||||
use codex_config::types::KeybindingsSpec;
|
||||
use futures::FutureExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tokio::net::TcpListener;
|
||||
@@ -239,6 +240,33 @@ async fn reconnect_restores_history_permissions_and_resumes_unsent_input() -> Re
|
||||
let view = app.agents_overview_view(Vec::new(), /*selected_thread_id*/ None);
|
||||
app.chat_widget.show_bottom_pane_view(Box::new(view));
|
||||
}
|
||||
app.app_server_backend_id = Some(session.backend_id());
|
||||
let foreign_owner = crate::backend_id::BackendId::new();
|
||||
let foreign_thread = ThreadId::new();
|
||||
app.backend_registry.observe(foreign_owner, foreign_thread);
|
||||
app.backend_registry.observe(session.backend_id(), id);
|
||||
let foreign_approval = exec_approval_request(
|
||||
foreign_thread,
|
||||
"turn-a",
|
||||
"item-a",
|
||||
/*approval_id*/ None,
|
||||
);
|
||||
let local_approval =
|
||||
exec_approval_request(id, "turn-b", "item-b", /*approval_id*/ None);
|
||||
app.pending_app_server_requests
|
||||
.note_server_request(&foreign_approval);
|
||||
app.pending_app_server_requests
|
||||
.note_server_request(&local_approval);
|
||||
app.agents_overview
|
||||
.dispatched_requests
|
||||
.entry(foreign_thread)
|
||||
.or_default();
|
||||
app.thread_event_channels
|
||||
.insert(foreign_thread, ThreadEventChannel::new(/*capacity*/ 4));
|
||||
app.backend_event_generations
|
||||
.insert(foreign_owner, uuid::Uuid::new_v4());
|
||||
let source_sender = app.backend_completion_sender(foreign_owner);
|
||||
let stale_sender = app.backend_completion_sender(session.backend_id());
|
||||
app.begin_reconnect();
|
||||
if deferred_notice {
|
||||
assert_eq!(
|
||||
@@ -313,6 +341,43 @@ async fn reconnect_restores_history_permissions_and_resumes_unsent_input() -> Re
|
||||
app.finish_reconnect(&mut tui, &mut session, &mut events, connected, "2.1.0")
|
||||
.await?;
|
||||
assert_eq!(session.backend_id(), backend_id);
|
||||
assert!(
|
||||
app.pending_app_server_requests
|
||||
.contains_server_request(&foreign_approval)
|
||||
);
|
||||
assert!(
|
||||
!app.pending_app_server_requests
|
||||
.contains_server_request(&local_approval)
|
||||
);
|
||||
assert!(
|
||||
app.agents_overview
|
||||
.dispatched_requests
|
||||
.contains_key(&foreign_thread)
|
||||
);
|
||||
assert!(app.thread_event_channels.contains_key(&foreign_thread));
|
||||
source_sender.send(AppEvent::TaskToolsAvailable {
|
||||
backend_id: foreign_owner,
|
||||
thread_id: foreign_thread,
|
||||
});
|
||||
stale_sender.send(AppEvent::TaskToolsAvailable {
|
||||
backend_id,
|
||||
thread_id: id,
|
||||
});
|
||||
let (_tx, mut empty_events) = tokio::sync::mpsc::unbounded_channel();
|
||||
let queued: Vec<_> = std::iter::from_fn(|| {
|
||||
app.saved_openings
|
||||
.next_event(&mut empty_events)
|
||||
.now_or_never()
|
||||
.flatten()
|
||||
})
|
||||
.collect();
|
||||
let completions: Vec<_> = queued
|
||||
.into_iter()
|
||||
.filter_map(|event| app.accept_backend_completion(event))
|
||||
.collect();
|
||||
assert!(
|
||||
matches!(completions.as_slice(), [AppEvent::TaskToolsAvailable { backend_id, thread_id }] if *backend_id == foreign_owner && *thread_id == foreign_thread)
|
||||
);
|
||||
if edit_offline {
|
||||
assert!(!app.chat_widget.has_active_view());
|
||||
assert!(
|
||||
|
||||
@@ -103,6 +103,57 @@ async fn background_archive_and_delete_remove_only_owned_rows() -> Result<()> {
|
||||
assert!(!app.agents_overview.removed_threads.contains(&id));
|
||||
}
|
||||
}
|
||||
let owned = ThreadId::new();
|
||||
assert!(app.backend_registry.observe(owner, owned));
|
||||
for target in [collision, owned] {
|
||||
let request = exec_approval_request(target, "turn", "item", /*approval_id*/ None);
|
||||
app.pending_app_server_requests
|
||||
.note_server_request(&request);
|
||||
app.agents_overview.dispatched_requests.insert(
|
||||
target,
|
||||
vec![
|
||||
super::super::app_server_requests::BufferedServerRequest::new(
|
||||
request.clone(),
|
||||
&server.request_handle(),
|
||||
),
|
||||
],
|
||||
);
|
||||
let channel = ThreadEventChannel::new(/*capacity*/ 4);
|
||||
channel.store.lock().await.push_request(request.clone());
|
||||
app.thread_event_channels.insert(target, channel);
|
||||
app.handle_polled_backend_event(
|
||||
&server,
|
||||
displayed,
|
||||
&mut HashMap::new(),
|
||||
AppServerSessionEvent {
|
||||
backend_id: owner,
|
||||
event: AppServerEvent::ServerNotification(Box::new(
|
||||
ServerNotification::ServerRequestResolved(
|
||||
codex_app_server_protocol::ServerRequestResolvedNotification {
|
||||
thread_id: target.to_string(),
|
||||
request_id: request.id().clone(),
|
||||
},
|
||||
),
|
||||
)),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let remains = target == collision;
|
||||
assert_eq!(
|
||||
(
|
||||
app.pending_app_server_requests
|
||||
.contains_server_request(&request),
|
||||
!app.agents_overview.dispatched_requests[&target].is_empty(),
|
||||
!app.thread_event_channels[&target]
|
||||
.store
|
||||
.lock()
|
||||
.await
|
||||
.pending_replay_requests()
|
||||
.is_empty()
|
||||
),
|
||||
(remains, remains, remains),
|
||||
);
|
||||
}
|
||||
app.backend_registry.connect(&server);
|
||||
app.agents_overview
|
||||
.discovery
|
||||
|
||||
@@ -2458,7 +2458,7 @@ async fn provider_continuation_starts_current_provider_and_drafts_saved_referenc
|
||||
#[tokio::test]
|
||||
async fn backend_cycling_waits_for_foreground_and_parked_voice_calls() -> Result<()> {
|
||||
for parked in [false, true] {
|
||||
let (mut app, _events, _ops) = make_test_app_with_channels().await;
|
||||
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
|
||||
let source = crate::start_embedded_app_server_for_picker(&app.config).await?;
|
||||
let destination = crate::start_embedded_app_server_for_picker(&app.config).await?;
|
||||
let source_id = source.backend_id();
|
||||
@@ -2472,9 +2472,10 @@ async fn backend_cycling_waits_for_foreground_and_parked_voice_calls() -> Result
|
||||
assert!(app.backend_draft().is_some());
|
||||
crate::chatwidget::activate_voice_for_thread(&mut app.chat_widget, thread_id);
|
||||
if parked {
|
||||
let (visible, _, _, _) =
|
||||
let (visible, _, visible_events, _) =
|
||||
crate::chatwidget::tests::make_chatwidget_manual_with_sender().await;
|
||||
app.background_voice = Some(Box::new(std::mem::replace(&mut app.chat_widget, visible)));
|
||||
events = visible_events;
|
||||
}
|
||||
app.chat_widget
|
||||
.restore_user_message_to_composer("keep draft".into());
|
||||
@@ -2493,6 +2494,22 @@ async fn backend_cycling_waits_for_foreground_and_parked_voice_calls() -> Result
|
||||
insta::allow_duplicates! {
|
||||
insta::assert_snapshot!(error, @"End the voice call before switching.");
|
||||
}
|
||||
while events.try_recv().is_ok() {}
|
||||
app.resume_backend_session(
|
||||
&mut tui,
|
||||
&mut backends,
|
||||
crate::resume_picker::SessionTarget {
|
||||
backend_id: destination_id,
|
||||
path: None,
|
||||
thread_id: ThreadId::new(),
|
||||
cwd: None,
|
||||
history_mode: None,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
insta::allow_duplicates! {
|
||||
insta::assert_snapshot!(next_history_message(&mut events), @"■ End the voice call before switching.");
|
||||
}
|
||||
assert_eq!(backends.displayed_owner(), source_id);
|
||||
assert_eq!(app.voice_owner_thread_id(), Some(thread_id));
|
||||
assert_eq!(app.chat_widget.composer_text_with_pending(), "keep draft");
|
||||
|
||||
@@ -284,6 +284,7 @@ async fn inactive_thread_user_verification_preserves_foreground_stream() -> Resu
|
||||
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 {
|
||||
|
||||
@@ -1098,9 +1098,12 @@ impl App {
|
||||
};
|
||||
|
||||
if let Err(err) = reply.resolve(resolution.result).await {
|
||||
self.chat_widget.add_error_message(format!(
|
||||
"Failed to resolve app-server request for thread {thread_id}: {err}"
|
||||
));
|
||||
tracing::warn!(%thread_id, %err, "failed to resolve app-server request");
|
||||
if self.current_displayed_thread_id() == Some(thread_id) {
|
||||
self.chat_widget.add_error_message(format!(
|
||||
"Failed to resolve app-server request for thread {thread_id}: {err}"
|
||||
));
|
||||
}
|
||||
}
|
||||
if ThreadEventStore::op_can_change_pending_replay_state(op) {
|
||||
self.note_thread_outbound_op(thread_id, op).await;
|
||||
|
||||
@@ -116,7 +116,7 @@ impl App {
|
||||
};
|
||||
let effort = (model == THREAD_TITLE_MODEL).then_some(ReasoningEffort::Low);
|
||||
let backend_id = app_server.backend_id();
|
||||
let event_sender = self.app_event_tx.clone();
|
||||
let event_sender = self.backend_completion_sender(backend_id);
|
||||
if let AppServerRequestHandle::Cloud(handle) = request_handle {
|
||||
let writer = app_server.automatic_thread_name_writer(thread_id, expected_name);
|
||||
let mut shutdown = self.cloud_title_shutdown.subscribe();
|
||||
@@ -239,7 +239,7 @@ impl App {
|
||||
.insert(temporary_thread_id, (TemporaryThreadKind::Title, sender));
|
||||
|
||||
let backend_id = app_server.backend_id();
|
||||
let event_sender = self.app_event_tx.clone();
|
||||
let event_sender = self.backend_completion_sender(backend_id);
|
||||
tokio::spawn(async move {
|
||||
let result = run_temporary_structured_turn(
|
||||
request_handle,
|
||||
|
||||
@@ -30,6 +30,7 @@ impl App {
|
||||
thread_id: ThreadId,
|
||||
server_name: String,
|
||||
request_id: RequestId,
|
||||
prompt_cancelled: tokio_util::sync::CancellationToken,
|
||||
) -> color_eyre::Result<()> {
|
||||
if app_server.uses_remote_workspace() {
|
||||
self.chat_widget.dismiss_app_server_request(
|
||||
@@ -66,7 +67,8 @@ impl App {
|
||||
return Ok(());
|
||||
};
|
||||
let handle = app_server.request_handle();
|
||||
let app_event_tx = self.app_event_tx.clone();
|
||||
let backend_id = app_server.backend_id();
|
||||
let app_event_tx = self.backend_completion_sender(backend_id);
|
||||
tokio::spawn(async move {
|
||||
let attempt_id = attempt.id;
|
||||
let verification = handle.request_typed::<UserVerificationVerifyResponse>(
|
||||
@@ -83,6 +85,8 @@ impl App {
|
||||
.map(|response| response.proof)
|
||||
.map_err(|error| verification_failure(&error));
|
||||
app_event_tx.send(AppEvent::UserVerificationFinished {
|
||||
prompt_cancelled,
|
||||
backend_id,
|
||||
thread_id,
|
||||
server_name,
|
||||
request_id,
|
||||
@@ -134,17 +138,22 @@ impl App {
|
||||
}
|
||||
}
|
||||
};
|
||||
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
|
||||
if self.app_server_backend_id == Some(app_server.backend_id()) {
|
||||
self.chat_widget.dismiss_app_server_request(
|
||||
&ResolvedAppServerRequest::McpElicitation {
|
||||
server_name: server_name.clone(),
|
||||
request_id: request_id.clone(),
|
||||
},
|
||||
);
|
||||
}
|
||||
let op = AppCommand::resolve_user_verification(server_name, request_id, response);
|
||||
if self.app_server_backend_id != Some(app_server.backend_id())
|
||||
|| self.current_displayed_thread_id() != Some(thread_id)
|
||||
{
|
||||
self.try_resolve_app_server_request(thread_id, &op).await?;
|
||||
return Ok(());
|
||||
}
|
||||
self.submit_thread_op(app_server, thread_id, op).await
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -127,8 +127,8 @@ impl UserVerificationRequests {
|
||||
discarded
|
||||
}
|
||||
|
||||
pub(super) fn clear(&mut self) {
|
||||
self.pending.clear();
|
||||
pub(super) fn retain_threads(&mut self, mut keep: impl FnMut(&str) -> bool) {
|
||||
self.pending.retain(|(thread, _, _), _| keep(thread));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,7 @@ enum RpcScenario {
|
||||
expected_reason: &'static str,
|
||||
},
|
||||
CancelWhilePending,
|
||||
CancelWithQueuedProof,
|
||||
RemoteWorkspace,
|
||||
}
|
||||
|
||||
@@ -53,7 +54,8 @@ async fn user_verification_controller_cancels_for_an_older_binary() -> color_eyr
|
||||
#[tokio::test]
|
||||
async fn user_verification_controller_suppresses_a_late_proof_after_cancellation()
|
||||
-> color_eyre::Result<()> {
|
||||
run_verification_rpc_scenario(RpcScenario::CancelWhilePending).await
|
||||
run_verification_rpc_scenario(RpcScenario::CancelWhilePending).await?;
|
||||
run_verification_rpc_scenario(RpcScenario::CancelWithQueuedProof).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -166,7 +168,8 @@ async fn run_verification_rpc_scenario(scenario: RpcScenario) -> color_eyre::Res
|
||||
_ => {
|
||||
let reason = match scenario {
|
||||
RpcScenario::MethodNotFound => "serviceError",
|
||||
RpcScenario::CancelWhilePending => "userCancelled",
|
||||
RpcScenario::CancelWhilePending
|
||||
| RpcScenario::CancelWithQueuedProof => "userCancelled",
|
||||
RpcScenario::RemoteWorkspace => "providerUnavailable",
|
||||
RpcScenario::VerificationError {
|
||||
expected_reason, ..
|
||||
@@ -198,7 +201,11 @@ async fn run_verification_rpc_scenario(scenario: RpcScenario) -> color_eyre::Res
|
||||
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 {
|
||||
let shows_prompt = matches!(
|
||||
scenario,
|
||||
RpcScenario::Success | RpcScenario::CancelWithQueuedProof | RpcScenario::RemoteWorkspace
|
||||
);
|
||||
if shows_prompt {
|
||||
app.chat_widget
|
||||
.handle_elicitation_request_now(request_id.clone(), params.clone());
|
||||
app.chat_widget
|
||||
@@ -213,21 +220,27 @@ async fn run_verification_rpc_scenario(scenario: RpcScenario) -> color_eyre::Res
|
||||
)
|
||||
.contains("Waiting for verification")
|
||||
);
|
||||
}
|
||||
let mode = if scenario == RpcScenario::RemoteWorkspace {
|
||||
crate::app_server_session::ThreadParamsMode::Remote
|
||||
} else {
|
||||
crate::app_server_session::ThreadParamsMode::Embedded
|
||||
};
|
||||
let mut session = AppServerSession::new(crate::backend_id::BackendId::new(), client, mode);
|
||||
if scenario == RpcScenario::Success {
|
||||
app.app_server_backend_id = Some(session.backend_id());
|
||||
}
|
||||
let buffered = crate::app::app_server_requests::BufferedServerRequest::new(
|
||||
request.clone(),
|
||||
&session.request_handle(),
|
||||
);
|
||||
app.pending_app_server_requests
|
||||
.note_buffered_request(&buffered);
|
||||
let approval = if scenario == RpcScenario::RemoteWorkspace {
|
||||
let approval = if shows_prompt {
|
||||
event_rx.recv().await.expect("approval event")
|
||||
} else {
|
||||
AppEvent::UserVerificationApproved {
|
||||
prompt_cancelled: Default::default(),
|
||||
thread_id,
|
||||
server_name: "deployments".to_string(),
|
||||
request_id: request_id.clone(),
|
||||
@@ -266,9 +279,9 @@ async fn run_verification_rpc_scenario(scenario: RpcScenario) -> color_eyre::Res
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
if matches!(
|
||||
if !matches!(
|
||||
scenario,
|
||||
RpcScenario::Success | RpcScenario::MethodNotFound | RpcScenario::VerificationError { .. }
|
||||
RpcScenario::RemoteWorkspace | RpcScenario::CancelWhilePending
|
||||
) {
|
||||
let completion =
|
||||
tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 5), event_rx.recv())
|
||||
@@ -278,7 +291,26 @@ async fn run_verification_rpc_scenario(scenario: RpcScenario) -> color_eyre::Res
|
||||
&completion,
|
||||
AppEvent::UserVerificationFinished { .. }
|
||||
));
|
||||
if scenario == RpcScenario::CancelWithQueuedProof {
|
||||
app.chat_widget
|
||||
.handle_key_event(crossterm::event::KeyCode::Esc.into());
|
||||
}
|
||||
app.handle_event(&mut tui, &mut session, completion).await?;
|
||||
if scenario == RpcScenario::CancelWithQueuedProof {
|
||||
let AppEvent::SubmitThreadOp { thread_id, op } = event_rx.try_recv()? else {
|
||||
panic!("expected queued Cancel");
|
||||
};
|
||||
app.submit_thread_op(&mut session, thread_id, op).await?;
|
||||
}
|
||||
if scenario == RpcScenario::Success {
|
||||
assert!(
|
||||
!crate::chatwidget::tests::helpers::render_bottom_popup(
|
||||
&app.chat_widget,
|
||||
/*width*/ 80
|
||||
)
|
||||
.contains("Waiting for verification")
|
||||
);
|
||||
}
|
||||
}
|
||||
if scenario == RpcScenario::CancelWhilePending {
|
||||
// Flush the client command queue after processing the late proof. The mock rejects any
|
||||
|
||||
@@ -364,6 +364,11 @@ impl std::fmt::Debug for OriginRequestHandle {
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
#[derive(Debug, IntoStaticStr)]
|
||||
pub(crate) enum AppEvent {
|
||||
BackendCompletion {
|
||||
backend_id: BackendId,
|
||||
generation: Uuid,
|
||||
event: Box<AppEvent>,
|
||||
},
|
||||
StatuslineRead(crate::chatwidget::StatuslineReadEvent),
|
||||
AccountEmailLoaded {
|
||||
request_id: uuid::Uuid,
|
||||
@@ -620,12 +625,15 @@ pub(crate) enum AppEvent {
|
||||
|
||||
/// Sign the challenge associated with an approved elicitation.
|
||||
UserVerificationApproved {
|
||||
prompt_cancelled: tokio_util::sync::CancellationToken,
|
||||
thread_id: ThreadId,
|
||||
server_name: String,
|
||||
request_id: AppServerRequestId,
|
||||
},
|
||||
/// Return a controller-owned verification result, never a native provider handle.
|
||||
UserVerificationFinished {
|
||||
prompt_cancelled: tokio_util::sync::CancellationToken,
|
||||
backend_id: BackendId,
|
||||
thread_id: ThreadId,
|
||||
server_name: String,
|
||||
request_id: AppServerRequestId,
|
||||
|
||||
@@ -28,6 +28,7 @@ pub(crate) struct AppEventSender {
|
||||
pub(crate) pasted_images: Arc<crate::clipboard_paste::PastedImages>,
|
||||
pub(crate) voice_only: Arc<AtomicBool>,
|
||||
pub(crate) backend_id: Option<crate::backend_id::BackendId>,
|
||||
generation: Option<uuid::Uuid>,
|
||||
}
|
||||
|
||||
impl AppEventSender {
|
||||
@@ -37,9 +38,11 @@ impl AppEventSender {
|
||||
voice_only: Arc::default(),
|
||||
pasted_images: Arc::default(),
|
||||
backend_id: None,
|
||||
generation: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn for_backend(&self, backend_id: crate::backend_id::BackendId) -> Self {
|
||||
Self {
|
||||
backend_id: Some(backend_id),
|
||||
@@ -54,6 +57,19 @@ impl AppEventSender {
|
||||
voice_only: Arc::default(),
|
||||
pasted_images: self.pasted_images.clone(),
|
||||
backend_id: None,
|
||||
generation: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn for_connection(
|
||||
&self,
|
||||
backend_id: crate::backend_id::BackendId,
|
||||
generation: uuid::Uuid,
|
||||
) -> Self {
|
||||
Self {
|
||||
backend_id: Some(backend_id),
|
||||
generation: Some(generation),
|
||||
..self.new_scope(self.app_event_tx.clone())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,11 +102,23 @@ impl AppEventSender {
|
||||
if !matches!(event, AppEvent::CodexOp(_)) {
|
||||
session_log::log_inbound_app_event(&event);
|
||||
}
|
||||
if let Err(e) = self.app_event_tx.send(event) {
|
||||
tracing::error!("failed to send event: {e}");
|
||||
if self.try_send_scoped(event).is_none() {
|
||||
tracing::error!("failed to send event: channel closed");
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn try_send_scoped(&self, event: AppEvent) -> Option<()> {
|
||||
let event = match (self.backend_id, self.generation) {
|
||||
(Some(backend_id), Some(generation)) => AppEvent::BackendCompletion {
|
||||
backend_id,
|
||||
generation,
|
||||
event: Box::new(event),
|
||||
},
|
||||
_ => event,
|
||||
};
|
||||
self.app_event_tx.send(event).ok()
|
||||
}
|
||||
|
||||
pub(crate) fn interrupt(&self) {
|
||||
self.send(AppEvent::CodexOp(AppCommand::interrupt()));
|
||||
}
|
||||
|
||||
@@ -343,6 +343,7 @@ impl super::BottomPane {
|
||||
let app_event_tx = self.app_event_tx.clone();
|
||||
let server_name = request.server_name.clone();
|
||||
let request_id = request.request_id.clone();
|
||||
let prompt_cancelled = tokio_util::sync::CancellationToken::new();
|
||||
let view = UserVerificationView::new(
|
||||
request,
|
||||
self.app_event_tx.clone(),
|
||||
@@ -351,17 +352,22 @@ impl super::BottomPane {
|
||||
Box::new(move |decision| match decision {
|
||||
UserVerificationDecision::Verify => {
|
||||
app_event_tx.send(crate::app_event::AppEvent::UserVerificationApproved {
|
||||
prompt_cancelled: prompt_cancelled.clone(),
|
||||
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,
|
||||
),
|
||||
UserVerificationDecision::Cancel => {
|
||||
// A signing result can already be waiting on the other event queue.
|
||||
prompt_cancelled.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();
|
||||
|
||||
@@ -113,8 +113,7 @@ pub(crate) async fn execute(
|
||||
.map_err(|_| McpError::invalid_params("File preview is unavailable for this path", None))?;
|
||||
let location = line.map(|line| SourceLocation::single(line.get(), /*column*/ None));
|
||||
events
|
||||
.app_event_tx
|
||||
.send(AppEvent::OpenModelSidebarDocument {
|
||||
.try_send_scoped(AppEvent::OpenModelSidebarDocument {
|
||||
backend,
|
||||
thread_id,
|
||||
document: DocumentRequest {
|
||||
@@ -124,7 +123,7 @@ pub(crate) async fn execute(
|
||||
_pending: pending,
|
||||
},
|
||||
})
|
||||
.map_err(|_| McpError::internal_error("The TUI is no longer accepting requests", None))?;
|
||||
.ok_or_else(|| McpError::internal_error("The TUI is no longer accepting requests", None))?;
|
||||
Ok(CallToolResult::structured(json!({
|
||||
"status": "queued",
|
||||
"threadId": thread_id,
|
||||
|
||||
Reference in New Issue
Block a user