diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index e4f5040023..69d46a760f 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -705,7 +705,6 @@ pub(crate) struct App { sidebar_press: Option, abandoned_side_threads: HashSet, active_thread_id: Option, - active_thread_rx: Option>, primary_thread_id: Option, last_subagent_backfill_attempt: Option, primary_session_configured: Option, diff --git a/codex-rs/tui/src/app/agents_overview_tests.rs b/codex-rs/tui/src/app/agents_overview_tests.rs index fa94a64087..29b297aec0 100644 --- a/codex-rs/tui/src/app/agents_overview_tests.rs +++ b/codex-rs/tui/src/app/agents_overview_tests.rs @@ -3277,11 +3277,7 @@ async fn check_resume_round_trip(round_trip: ResumeRoundTrip) -> Result<()> { ), ) .await?; - assert!( - app.active_thread_rx - .as_ref() - .is_some_and(|rx| !rx.is_empty()) - ); + assert!(app.active_thread_rx().is_some_and(|rx| !rx.is_empty())); } let view = app.agents_overview_view(Vec::new(), /*selected_thread_id*/ None); app.chat_widget.show_bottom_pane_view(Box::new(view)); @@ -3913,7 +3909,7 @@ async fn overview_fork_keeps_idle_source_input_queued() -> Result<()> { if cached_primary { Box::pin(app.select_agents_overview_thread(&mut tui, &mut server, source)).await?; assert_eq!(app.current_displayed_thread_id(), Some(source)); - app.store_active_thread_receiver().await; + app.save_active_thread_state().await; } app.chat_widget .set_queue_autosend_suppressed(/*suppressed*/ true); diff --git a/codex-rs/tui/src/app/backend_selection.rs b/codex-rs/tui/src/app/backend_selection.rs index 51ac6a236f..9f13f6fe10 100644 --- a/codex-rs/tui/src/app/backend_selection.rs +++ b/codex-rs/tui/src/app/backend_selection.rs @@ -514,7 +514,7 @@ impl App { self.detach_current_thread_for_navigation(outgoing_session, Some(thread_id)) .await; let destination = backends.session_at_mut(destination_slot); - self.store_active_thread_receiver().await; + self.save_active_thread_state().await; self.clear_active_thread().await; self.agents_overview.search_matches.clear(); self.agents_overview.pending_usage = None; diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 76d51c91d5..126bcb8df0 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -1075,8 +1075,8 @@ impl App { self.chat_widget.restore_user_message_to_composer(prompt); self.chat_widget.set_queue_autosend_suppressed(/*suppressed*/ true); self.abort_thread_event_listener(thread_id); - if let Some(mut rx) = self.active_thread_rx.take() { - while let Ok(event) = rx.try_recv() { + if let Some(channel) = self.thread_event_channels.get_mut(&thread_id) { + while let Ok(event) = channel.receiver.try_recv() { if let ThreadBufferedEvent::Notification(notification) = event { self.chat_widget.handle_server_notification(*notification, Some(ReplayKind::ThreadSnapshot)); } diff --git a/codex-rs/tui/src/app/misalignment_policy.rs b/codex-rs/tui/src/app/misalignment_policy.rs index 85062a96c9..ecbea4a4fc 100644 --- a/codex-rs/tui/src/app/misalignment_policy.rs +++ b/codex-rs/tui/src/app/misalignment_policy.rs @@ -104,10 +104,7 @@ impl App { } } if self.current_displayed_thread_id() != Some(review.thread_id) - || self - .active_thread_rx - .as_ref() - .is_some_and(|rx| !rx.is_empty()) + || self.active_thread_rx().is_some_and(|rx| !rx.is_empty()) || !self.chat_widget.is_current_misalignment_review(&review) { return; diff --git a/codex-rs/tui/src/app/reconnect.rs b/codex-rs/tui/src/app/reconnect.rs index da089bd47f..48b094a254 100644 --- a/codex-rs/tui/src/app/reconnect.rs +++ b/codex-rs/tui/src/app/reconnect.rs @@ -416,7 +416,7 @@ impl App { if let Some(input) = input.as_mut() { input.reconnect_pending = true; } - self.store_active_thread_receiver().await; + self.save_active_thread_state().await; // Old request handles stay attached to the dead connection. Rotating the event channel // prevents their late completions from submitting follow-up operations on the new one. let (tx, rx) = mpsc::unbounded_channel(); @@ -599,10 +599,9 @@ impl App { self.thread_event_channels.insert(id, channel); } if let Some(id) = displayed - && let Some((receiver, snapshot)) = self.activate_thread_for_replay(id).await + && let Some(snapshot) = self.activate_thread_for_replay(id).await { self.active_thread_id = Some(id); - self.active_thread_rx = Some(receiver); self.recap.seed_from_turns(&snapshot.turns, Instant::now()); if let Err(err) = self .render_thread_snapshot( @@ -627,7 +626,6 @@ impl App { } } else { self.active_thread_id = None; - self.active_thread_rx = None; self.primary_thread_id = None; self.primary_session_configured = None; let init = self.chatwidget_init_for_forked_or_resumed_thread( diff --git a/codex-rs/tui/src/app/session_lifecycle.rs b/codex-rs/tui/src/app/session_lifecycle.rs index 6406377f32..ea0d32f272 100644 --- a/codex-rs/tui/src/app/session_lifecycle.rs +++ b/codex-rs/tui/src/app/session_lifecycle.rs @@ -441,19 +441,17 @@ impl App { } ); let replace_active = self.active_thread_id == Some(thread_id) - && self.active_thread_rx.is_some() && matches!(&prepared, PreparedAttachment::Live(_)); if replace_active { - // The active receiver belongs to the channel that installation will replace. - self.drain_outgoing_thread_events().await; - self.store_active_thread_receiver().await; + // A new live attachment supersedes the old stream's close notification. + self.drain_outgoing_thread_events(Some(thread_id)).await; + self.save_active_thread_state().await; } let live = self .install_thread_attachment(app_server, thread_id, prepared, ChannelMode::ReplaceLive) .await; if replace_active { self.set_thread_active(thread_id, /*active*/ true).await; - self.active_thread_rx = self.ensure_thread_channel(thread_id).receiver.take(); } self.ensure_thread_channel(thread_id).archived = archived; Ok(live) @@ -742,11 +740,6 @@ impl App { if let Some(pane) = self.sidebars.get_mut(&self.sidebar_parent()) { pane.agents.pending_link = None; } - if self.active_thread_id == Some(thread_id) { - // Detach the cached receiver before a successful attachment replaces its channel. - self.store_active_thread_receiver().await; - } - let known_side = self.side_threads.contains_key(&thread_id) && self.thread_event_channels.contains_key(&thread_id); // The live parent already receives lifecycle notifications while its child has focus. @@ -840,18 +833,17 @@ impl App { // Notifications already routed to the active channel must reach the old // widget before its transcript state is transferred. Events routed after // deactivation are retained separately for that thread. - if let Some(mut receiver) = self.active_thread_rx.take() { - while let Ok(event) = receiver.try_recv() { - self.handle_thread_event_now_recovering_file_changes(event) - .await; - } - self.active_thread_rx = Some(receiver); + // A live same-thread replacement already drained its old receiver. On failed + // reattachment leave a queued close to the normal shutdown/failover handler. + if previous_thread_id != Some(thread_id) { + self.drain_outgoing_thread_events(/*reattached*/ None).await; } - self.store_active_thread_receiver().await; + self.save_active_thread_state().await; self.active_thread_id = None; - let Some((receiver, mut snapshot)) = self.activate_thread_for_replay(thread_id).await - else { - self.add_agents_overview_error(format!("Agent thread {thread_id} is already active.")); + let Some(mut snapshot) = self.activate_thread_for_replay(thread_id).await else { + self.add_agents_overview_error(format!( + "Agent thread {thread_id} is no longer available." + )); if let Some(previous_thread_id) = previous_thread_id { self.activate_thread_channel(previous_thread_id).await; } @@ -910,7 +902,6 @@ impl App { .or(self.agents_overview.input_states.remove(&thread_id)); self.active_thread_id = Some(thread_id); - self.active_thread_rx = Some(receiver); self.recap.note_focus_gained(); self.recap = recap::RecapState::default(); @@ -1177,7 +1168,6 @@ impl App { self.agents_overview.activity.clear(); self.agent_navigation.clear(); self.active_thread_id = None; - self.active_thread_rx = None; self.primary_thread_id = None; self.last_subagent_backfill_attempt = None; self.primary_session_configured = None; @@ -1713,13 +1703,19 @@ impl App { .await } - async fn drain_outgoing_thread_events(&mut self) { - if let Some(mut receiver) = self.active_thread_rx.take() { - while let Ok(event) = receiver.try_recv() { - self.handle_thread_event_now_recovering_file_changes(event) - .await; + async fn drain_outgoing_thread_events(&mut self, reattached: Option) { + while let Some(receiver) = self.active_thread_rx_mut() + && let Ok(event) = receiver.try_recv() + { + if let Some(id) = reattached + && self.pending_shutdown_exit_thread_id != Some(id) + && let ThreadBufferedEvent::Notification(notification) = &event + && matches!(notification.as_ref(), ServerNotification::ThreadClosed(closed) if closed.thread_id == id.to_string()) + { + continue; } - self.active_thread_rx = Some(receiver); + self.handle_thread_event_now_recovering_file_changes(event) + .await; } } @@ -1754,7 +1750,7 @@ impl App { presentation, ThreadAttachPresentation::SessionLineageAfterClear ) { - self.drain_outgoing_thread_events().await; + self.drain_outgoing_thread_events(/*reattached*/ None).await; } if let Some(thread_id) = source_thread && (self.agents_overview.blank_sessions.contains_key(&thread_id) @@ -1763,7 +1759,7 @@ impl App { { self.agents_overview.input_states.insert(thread_id, input); } - self.store_active_thread_receiver().await; + self.save_active_thread_state().await; self.refresh_transcript_document_links(); self.reset_transcript_state_after_clear(); tui.clear_pending_history_lines(); @@ -2072,7 +2068,7 @@ impl App { tui: &mut tui::Tui, handoff: std::sync::Arc<()>, ) -> Result> { - self.drain_outgoing_thread_events().await; + self.drain_outgoing_thread_events(/*reattached*/ None).await; // A docked open keeps the outgoing frame until the synchronized destination draw. if !self.docked_task_opening(tui) && let Err(error) = tui.clear_for_thread_switch() diff --git a/codex-rs/tui/src/app/side.rs b/codex-rs/tui/src/app/side.rs index a221102b2b..1d3e02fae7 100644 --- a/codex-rs/tui/src/app/side.rs +++ b/codex-rs/tui/src/app/side.rs @@ -1033,7 +1033,7 @@ impl App { if already_selected { // Selection normally skips the live thread. Replay the initialized snapshot // even if the picker exposed this child before the boundary RPC completed. - self.store_active_thread_receiver().await; + self.save_active_thread_state().await; self.active_thread_id = None; } if let Err(err) = self diff --git a/codex-rs/tui/src/app/startup.rs b/codex-rs/tui/src/app/startup.rs index 1b7d90a2f6..d57432efc4 100644 --- a/codex-rs/tui/src/app/startup.rs +++ b/codex-rs/tui/src/app/startup.rs @@ -238,19 +238,16 @@ impl App { pub(super) fn has_queued_startup_protected_request(&self) -> bool { self.startup_protected_input_boundary && (self - .active_thread_rx - .as_ref() - .is_some_and(|receiver| !receiver.is_empty()) - && self - .active_thread_id - .and_then(|thread_id| self.thread_event_channels.get(&thread_id)) - .is_none_or(|channel| { - // A bounded drain can leave ordinary notifications queued. Only protect - // input for pending requests, or when their state cannot be inspected. - channel.store.try_lock().map_or(/*default*/ true, |store| { + .active_thread_id + .and_then(|id| self.thread_event_channels.get(&id)) + .is_some_and(|channel| { + // A bounded drain can leave ordinary notifications queued. Only protect + // input for pending requests, or when their state cannot be inspected. + !channel.receiver.is_empty() + && channel.store.try_lock().map_or(/*default*/ true, |store| { store.side_parent_pending_status().is_some() }) - }) + }) || self .pending_primary_events .iter() @@ -1154,7 +1151,6 @@ See the Codex keymap documentation for supported actions and examples." sidebar_press: None, abandoned_side_threads: HashSet::new(), active_thread_id: None, - active_thread_rx: None, primary_thread_id: None, last_subagent_backfill_attempt: None, primary_session_configured: None, @@ -1297,7 +1293,7 @@ See the Codex keymap documentation for supported actions and examples." } if Self::should_handle_active_thread_events( wait_for_initial_session_configured, - app.active_thread_rx.is_some(), + app.active_thread_rx().is_some(), ) && let Err(err) = app.drain_active_thread_events(tui).await { return shutdown_on_startup_error(app_server, &mut other_backends, err).await; @@ -1751,14 +1747,14 @@ See the Codex keymap documentation for supported actions and examples." } } active = async { - if let Some(rx) = app.active_thread_rx.as_mut() { - rx.recv().await + if let Some(channel) = app.active_thread_id.and_then(|id| app.thread_event_channels.get_mut(&id)) { + channel.receiver.recv().await } else { None } }, if App::should_handle_active_thread_events( waiting_for_initial_session_configured, - app.active_thread_rx.is_some() + app.active_thread_rx().is_some() ) && !has_pending_app_events && !app.reconnect.offline => { if let Some(event) = active { if let Err(err) = app.handle_active_thread_event(tui, backends.session_at_mut(displayed_session), event).await { @@ -1783,8 +1779,7 @@ See the Codex keymap documentation for supported actions and examples." && app_event_rx.is_empty() && !app.startup_pending_protected_request && app - .active_thread_rx - .as_ref() + .active_thread_rx() .is_none_or(tokio::sync::mpsc::Receiver::is_empty) && !app.pending_primary_events.iter().any(|event| { matches!(event, ThreadBufferedEvent::Request(_)) diff --git a/codex-rs/tui/src/app/test_support.rs b/codex-rs/tui/src/app/test_support.rs index 82bfdfb98b..dacaa7f522 100644 --- a/codex-rs/tui/src/app/test_support.rs +++ b/codex-rs/tui/src/app/test_support.rs @@ -157,7 +157,6 @@ pub(crate) async fn make_test_app() -> Box { sidebar_press: None, abandoned_side_threads: HashSet::new(), active_thread_id: None, - active_thread_rx: None, primary_thread_id: None, last_subagent_backfill_attempt: None, primary_session_configured: None, diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index cd727beefc..2876c31c88 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -693,8 +693,7 @@ async fn enqueue_primary_thread_session_replays_buffered_approval_after_attach() .await?; let rx = app - .active_thread_rx - .as_mut() + .active_thread_rx_mut() .expect("primary thread receiver should be active"); let event = time::timeout(Duration::from_millis(50), rx.recv()) .await @@ -821,8 +820,7 @@ async fn resolved_buffered_approval_does_not_become_actionable_after_drain() -> while app_event_rx.try_recv().is_ok() {} let rx = app - .active_thread_rx - .as_mut() + .active_thread_rx_mut() .expect("primary thread receiver should be active"); let event = time::timeout(Duration::from_millis(50), rx.recv()) .await @@ -1168,13 +1166,11 @@ async fn enqueue_thread_event_does_not_block_when_channel_full() -> Result<()> { .await .expect("enqueue_thread_notification blocked on a full channel")?; - let mut rx = app + let rx = &mut app .thread_event_channels .get_mut(&thread_id) .expect("missing thread channel") - .receiver - .take() - .expect("missing receiver"); + .receiver; time::timeout(Duration::from_millis(50), rx.recv()) .await @@ -1222,8 +1218,7 @@ async fn active_thread_drain_yields_after_frame_deadline_without_dropping_events } ); assert!( - app.active_thread_rx - .as_ref() + app.active_thread_rx() .is_some_and(|receiver| !receiver.is_empty()), "an expired frame deadline should preserve queued notifications" ); @@ -1234,8 +1229,7 @@ async fn active_thread_drain_yields_after_frame_deadline_without_dropping_events app.drain_active_thread_events(&mut tui).await?; assert!( - app.active_thread_rx - .as_ref() + app.active_thread_rx() .is_some_and(tokio::sync::mpsc::Receiver::is_empty), "the next foreground frame should deliver the preserved notification" ); @@ -1312,8 +1306,7 @@ async fn selected_side_thread_close_is_handled_by_foreground_event_owner() -> Re assert_eq!(app.active_thread_id, Some(side_thread_id)); drain_app_events(&mut app, &mut tui, &mut app_server, &mut events).await?; let event = app - .active_thread_rx - .as_mut() + .active_thread_rx_mut() .expect("selected side thread should retain its receiver") .try_recv() .expect("thread closure should remain queued for the foreground loop"); @@ -1323,7 +1316,7 @@ async fn selected_side_thread_close_is_handled_by_foreground_event_owner() -> Re assert_eq!(app.active_thread_id, Some(primary_thread_id)); assert!(!app.side_threads.contains_key(&side_thread_id)); assert!(!app.thread_event_channels.contains_key(&side_thread_id)); - assert!(app.active_thread_rx.is_some()); + assert!(app.active_thread_rx().is_some()); drain_app_events(&mut app, &mut tui, &mut app_server, &mut events).await?; app.refresh_owned_transcript(&mut tui)?; assert!(buffer_text(tui.terminal.previous_buffer()).contains("parent-24")); @@ -1359,8 +1352,7 @@ async fn active_history_batch_is_delivered_without_replay_buffering() -> Result< .get_mut(&thread_id) .expect("missing thread channel"); assert!(channel.store.lock().await.buffer.is_empty()); - let mut receiver = channel.receiver.take().expect("missing receiver"); - let delivered = time::timeout(Duration::from_millis(50), receiver.recv()) + let delivered = time::timeout(Duration::from_millis(50), channel.receiver.recv()) .await .expect("timed out waiting for history batch") .expect("missing history batch"); @@ -1406,8 +1398,8 @@ async fn replay_thread_snapshot_renders_only_retained_agent_message_deltas() { } } - app.store_active_thread_receiver().await; - let (_receiver, snapshot) = app + app.save_active_thread_state().await; + let snapshot = app .activate_thread_for_replay(thread_id) .await .expect("detached thread should reactivate for replay"); @@ -1480,7 +1472,7 @@ async fn replay_thread_snapshot_restores_draft_and_queued_input() { .capture_thread_input_state() .expect("expected thread input state"); - app.store_active_thread_receiver().await; + app.save_active_thread_state().await; let snapshot = { let channel = app @@ -1558,7 +1550,7 @@ async fn replay_thread_snapshot_restores_the_matching_safety_buffer_prompt() { .capture_thread_input_state() .expect("expected thread input state"); - app.store_active_thread_receiver().await; + app.save_active_thread_state().await; let snapshot = { let channel = app .thread_event_channels @@ -1977,7 +1969,7 @@ async fn replay_thread_snapshot_restores_pending_pastes_for_submit() { .capture_thread_input_state() .expect("expected thread input state"); - app.store_active_thread_receiver().await; + app.save_active_thread_state().await; let snapshot = { let channel = app @@ -8612,8 +8604,7 @@ async fn active_side_thread_renders_live_mcp_startup_notifications() { ) .await; let event = app - .active_thread_rx - .as_mut() + .active_thread_rx_mut() .expect("side thread receiver") .try_recv() .expect("startup notification"); @@ -9304,7 +9295,6 @@ async fn make_test_app() -> Box { sidebar_press: None, abandoned_side_threads: HashSet::new(), active_thread_id: None, - active_thread_rx: None, primary_thread_id: None, last_subagent_backfill_attempt: None, primary_session_configured: None, @@ -9454,7 +9444,6 @@ pub(super) async fn make_test_app_with_channels() -> ( sidebar_press: None, abandoned_side_threads: HashSet::new(), active_thread_id: None, - active_thread_rx: None, primary_thread_id: None, last_subagent_backfill_attempt: None, primary_session_configured: None, diff --git a/codex-rs/tui/src/app/tests/agents_navigation_tests.rs b/codex-rs/tui/src/app/tests/agents_navigation_tests.rs index 044ed5e75e..1a9963d642 100644 --- a/codex-rs/tui/src/app/tests/agents_navigation_tests.rs +++ b/codex-rs/tui/src/app/tests/agents_navigation_tests.rs @@ -1,6 +1,35 @@ use super::*; use pretty_assertions::assert_eq; +#[tokio::test] +async fn clearing_focus_keeps_unread_events_on_the_original_thread() -> Result<()> { + let mut app = make_test_app().await; + let first = ThreadId::new(); + let second = ThreadId::new(); + app.ensure_thread_channel(first); + app.ensure_thread_channel(second); + app.activate_thread_channel(first).await; + app.enqueue_thread_notification(first, thread_closed_notification(first)) + .await?; + + app.clear_active_thread().await; + assert!(app.active_thread_rx().is_none()); + app.activate_thread_channel(second).await; + assert!(app.active_thread_rx().unwrap().is_empty()); + + app.clear_active_thread().await; + app.activate_thread_channel(first).await; + let event = app.active_thread_rx_mut().unwrap().try_recv()?; + let ThreadBufferedEvent::Notification(notification) = event else { + panic!("expected the original notification"); + }; + let ServerNotification::ThreadClosed(closed) = *notification else { + panic!("expected thread closure"); + }; + assert_eq!(closed.thread_id, first.to_string()); + Ok(()) +} + #[tokio::test] async fn agents_navigation_opens_the_command_center_on_every_target() -> Result<()> { let endpoint = crate::RemoteAppServerEndpoint::UnixSocket { @@ -431,6 +460,26 @@ fn thread_links_navigate_and_missing_threads_preserve_the_draft() -> Result<()> (Some(root), Some(target)) ); } + if scenario == "root" { + for exiting in [false, true] { + app.ensure_thread_channel(root).mark_replay_only(); + app.chat_widget.show_external_writer_thread(); + app.pending_shutdown_exit_thread_id = exiting.then_some(root); + app.enqueue_thread_notification(root, thread_closed_notification(root)).await?; + Box::pin(app.select_agent_thread(&mut tui, &mut app_server, root)).await?; + assert_eq!(app.thread_event_channels[&root].attachment(), ThreadEventAttachment::Live); + let mut saw_exit = false; + while let Ok(event) = events.try_recv() { + if matches!(event, AppEvent::Exit(ExitMode::Immediate)) { + saw_exit = true; + } else { + Box::pin(app.handle_event(&mut tui, &mut app_server, event)).await?; + } + } + assert_eq!(saw_exit, exiting); + } + app.pending_shutdown_exit_thread_id = None; + } if scenario == "grandchild" { let intermediate = intermediate.expect("grandchild has an intermediate parent"); Box::pin(app.select_agent_thread(&mut tui, &mut app_server, intermediate)).await?; @@ -440,13 +489,13 @@ fn thread_links_navigate_and_missing_threads_preserve_the_draft() -> Result<()> Box::pin(thread_links::open_thread_link(&mut app, &mut tui, &mut app_server, target)).await?; Box::pin(app.select_agent_thread(&mut tui, &mut app_server, intermediate)).await?; assert_eq!(app.active_thread_id, Some(intermediate)); - while app.active_thread_rx.as_mut().unwrap().try_recv().is_ok() {} + while app.active_thread_rx_mut().unwrap().try_recv().is_ok() {} let event = ThreadBufferedEvent::Notification(Box::new( agent_message_delta_notification(intermediate, "turn", "item", "fresh delivery"), )); app.thread_event_channels[&intermediate].sender.send(event).await?; let ThreadBufferedEvent::Notification(notification) = - app.active_thread_rx.as_mut().unwrap().try_recv()? + app.active_thread_rx_mut().unwrap().try_recv()? else { panic!("expected an agent message notification"); }; diff --git a/codex-rs/tui/src/app/tests/backend_banner_fallback_tests.rs b/codex-rs/tui/src/app/tests/backend_banner_fallback_tests.rs index f6b6949f42..927a990fec 100644 --- a/codex-rs/tui/src/app/tests/backend_banner_fallback_tests.rs +++ b/codex-rs/tui/src/app/tests/backend_banner_fallback_tests.rs @@ -188,7 +188,7 @@ async fn backend_banner_fallback_uses_current_task_and_accepted_generation() -> /*initial_user_message*/ None, ); app.replace_chat_widget(ChatWidget::new_with_app_event(init)); - app.store_active_thread_receiver().await; + app.save_active_thread_state().await; app.active_thread_id = None; app.enqueue_primary_thread_session(second.session, second.turns) .await?; diff --git a/codex-rs/tui/src/app/tests/history_hydration_tests.rs b/codex-rs/tui/src/app/tests/history_hydration_tests.rs index 1920e21d2e..07803a1966 100644 --- a/codex-rs/tui/src/app/tests/history_hydration_tests.rs +++ b/codex-rs/tui/src/app/tests/history_hydration_tests.rs @@ -500,7 +500,7 @@ async fn cloud_complete_transcript_includes_error_from_an_older_zero_item_turn() ); app.enqueue_thread_notification(id, ServerNotification::ItemCompleted(completed)) .await?; - let event = app.active_thread_rx.as_mut().unwrap().recv().await.unwrap(); + let event = app.active_thread_rx_mut().unwrap().recv().await.unwrap(); app.handle_thread_event_now(event); drain_app_events(&mut app, &mut tui, &mut server, &mut events).await?; } diff --git a/codex-rs/tui/src/app/tests/mcp_startup.rs b/codex-rs/tui/src/app/tests/mcp_startup.rs index cf649b0cd0..44f355e26c 100644 --- a/codex-rs/tui/src/app/tests/mcp_startup.rs +++ b/codex-rs/tui/src/app/tests/mcp_startup.rs @@ -274,8 +274,7 @@ async fn subagent_mcp_startup_settles_while_cached_servers_remain_deferred() { ) .await; let event = app - .active_thread_rx - .as_mut() + .active_thread_rx_mut() .expect("subagent receiver should be active") .try_recv() .expect("MCP startup update should reach the active subagent"); diff --git a/codex-rs/tui/src/app/tests/navigation_reconnect_tests.rs b/codex-rs/tui/src/app/tests/navigation_reconnect_tests.rs index 0ca984ac01..98f318471d 100644 --- a/codex-rs/tui/src/app/tests/navigation_reconnect_tests.rs +++ b/codex-rs/tui/src/app/tests/navigation_reconnect_tests.rs @@ -69,7 +69,7 @@ async fn reconnect_daemon_command_center_after_socket_replacement_without_a_conv ); app.chat_widget .restore_user_message_to_composer("old draft".into()); - app.store_active_thread_receiver().await; + app.save_active_thread_state().await; app.chat_widget .handle_key_event(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL)); assert!(app.chat_widget.composer_is_empty()); @@ -641,7 +641,7 @@ async fn reconnect_daemon_command_center_after_socket_replacement_without_a_conv agent_message_delta_notification(id, "new-turn", "new-item", "fresh delivery"), )); channel.sender.send(event).await?; - assert!(app.active_thread_rx.as_mut().unwrap().try_recv().is_ok()); + assert!(app.active_thread_rx_mut().unwrap().try_recv().is_ok()); } session.shutdown().await?; let methods = server.await??; diff --git a/codex-rs/tui/src/app/tests/new_session_tests.rs b/codex-rs/tui/src/app/tests/new_session_tests.rs index 563c4be407..7d8e0cc373 100644 --- a/codex-rs/tui/src/app/tests/new_session_tests.rs +++ b/codex-rs/tui/src/app/tests/new_session_tests.rs @@ -1199,7 +1199,7 @@ async fn replacement_failure_keeps_current_task_and_restores_input() -> Result<( .await; assert_eq!(app.chat_widget.thread_id(), Some(current)); assert_eq!(app.active_thread_id, Some(current)); - assert!(app.active_thread_rx.is_some()); + assert!(app.active_thread_rx().is_some()); assert_eq!(app.config, original_config); assert_eq!( app.chat_widget.composer_text_with_pending(), @@ -1262,7 +1262,7 @@ async fn replacement_failure_keeps_current_task_and_restores_input() -> Result<( assert_eq!(backends.displayed_owner(), source_id); assert_eq!(app.config, original_config); assert_eq!(app.active_thread_id, Some(current)); - assert!(app.active_thread_rx.is_some()); + assert!(app.active_thread_rx().is_some()); assert_eq!(app.chat_widget.thread_id(), Some(current)); assert_eq!( app.chat_widget.composer_text_with_pending(), @@ -1455,7 +1455,7 @@ async fn resumed_backend_handoff_detaches_through_the_source_connection() -> Res assert!(app.finish_docked_task_opening(&tui, resumed_id)); assert!(app.startup_protected_input_boundary); - while let Ok(event) = app.active_thread_rx.as_mut().unwrap().try_recv() { + while let Ok(event) = app.active_thread_rx_mut().unwrap().try_recv() { app.handle_thread_event_now(event); } assert!(app.chat_widget.has_active_modal()); diff --git a/codex-rs/tui/src/app/tests/realtime_requests.rs b/codex-rs/tui/src/app/tests/realtime_requests.rs index 97e0f663d8..d5ddd46b16 100644 --- a/codex-rs/tui/src/app/tests/realtime_requests.rs +++ b/codex-rs/tui/src/app/tests/realtime_requests.rs @@ -502,13 +502,12 @@ async fn switching_agent_threads_preserves_backend_voice_and_routes_pending_spee matches!(speech, Op::RealtimeConversationSpeech { .. }), "{speech:?}" ); - let mut source_channel = ThreadEventChannel::new_with_session( + let source_channel = ThreadEventChannel::new_with_session( THREAD_EVENT_CHANNEL_CAPACITY, test_thread_session(source, app.config.cwd.to_path_buf()), Vec::new(), ); source_channel.store.lock().await.active = true; - app.active_thread_rx = source_channel.receiver.take(); app.thread_event_channels.insert(source, source_channel); // Routed to the active channel, but not yet delivered to the old widget. app.enqueue_thread_notification( diff --git a/codex-rs/tui/src/app/tests/safety_buffering.rs b/codex-rs/tui/src/app/tests/safety_buffering.rs index e64b82022f..9bbf0224ea 100644 --- a/codex-rs/tui/src/app/tests/safety_buffering.rs +++ b/codex-rs/tui/src/app/tests/safety_buffering.rs @@ -103,8 +103,7 @@ fn submit_prompt(app: &mut App, prompt: &str) { fn drain_active_thread_events(app: &mut App) { while let Some(event) = app - .active_thread_rx - .as_mut() + .active_thread_rx_mut() .and_then(|receiver| receiver.try_recv().ok()) { app.handle_thread_event_now(event); diff --git a/codex-rs/tui/src/app/tests/saved_chat_loading_tests.rs b/codex-rs/tui/src/app/tests/saved_chat_loading_tests.rs index 268567ea52..b866a4df30 100644 --- a/codex-rs/tui/src/app/tests/saved_chat_loading_tests.rs +++ b/codex-rs/tui/src/app/tests/saved_chat_loading_tests.rs @@ -91,7 +91,7 @@ async fn saved_chat_retry_and_supersession_with_pending_requests() -> Result<()> events = rx; } else if index == 4 { // Switching away and back cannot resurrect the original parent's intent. - app.store_active_thread_receiver().await; + app.save_active_thread_state().await; } else if index == 5 { // An archive from another client wins over a read that is already in flight. boxed_future!(app.handle_event( diff --git a/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs b/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs index 5dd23ae217..b24ec5e5d6 100644 --- a/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs +++ b/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs @@ -953,7 +953,7 @@ async fn cloud_resume_picker_reconciles_admitted_steers() -> Result<()> { completed(other, ongoing, directive.clone()), ] { app.enqueue_thread_notification(other, notification).await?; - let event = app.active_thread_rx.as_mut().unwrap().recv().await.unwrap(); + let event = app.active_thread_rx_mut().unwrap().recv().await.unwrap(); app.handle_thread_event_now(event); } drain_app_events(&mut app, &mut tui, &mut server, &mut events).await?; @@ -999,7 +999,7 @@ async fn cloud_resume_picker_reconciles_admitted_steers() -> Result<()> { ), ] { app.enqueue_thread_notification(other, notification).await?; - let event = app.active_thread_rx.as_mut().unwrap().recv().await.unwrap(); + let event = app.active_thread_rx_mut().unwrap().recv().await.unwrap(); app.handle_thread_event_now(event); } drain_app_events(&mut app, &mut tui, &mut server, &mut events).await?; @@ -1035,7 +1035,7 @@ async fn cloud_resume_picker_reconciles_admitted_steers() -> Result<()> { turn_completed_notification(other, ongoing, TurnStatus::Completed), ] { app.enqueue_thread_notification(other, notification).await?; - let event = app.active_thread_rx.as_mut().unwrap().recv().await.unwrap(); + let event = app.active_thread_rx_mut().unwrap().recv().await.unwrap(); app.handle_thread_event_now(event); } drain_app_events(&mut app, &mut tui, &mut server, &mut events).await?; @@ -1135,7 +1135,7 @@ async fn cloud_resume_picker_reconciles_admitted_steers() -> Result<()> { ] { app.enqueue_thread_notification(original, notification) .await?; - let event = app.active_thread_rx.as_mut().unwrap().recv().await.unwrap(); + let event = app.active_thread_rx_mut().unwrap().recv().await.unwrap(); app.handle_thread_event_now(event); } drain_app_events(&mut app, &mut tui, &mut server, &mut events).await?; diff --git a/codex-rs/tui/src/app/tests/startup.rs b/codex-rs/tui/src/app/tests/startup.rs index 72ceabee47..7b7438c05e 100644 --- a/codex-rs/tui/src/app/tests/startup.rs +++ b/codex-rs/tui/src/app/tests/startup.rs @@ -437,8 +437,7 @@ async fn queued_startup_requests_block_terminal_input_after_draft_handoff() -> R app.enqueue_primary_thread_request(request).await?; assert!( - app.active_thread_rx - .as_ref() + app.active_thread_rx() .is_some_and(|receiver| !receiver.is_empty()) ); assert!( @@ -457,8 +456,7 @@ async fn queued_startup_requests_block_terminal_input_after_draft_handoff() -> R } let event = app - .active_thread_rx - .as_mut() + .active_thread_rx_mut() .expect("primary thread receiver should be active") .try_recv() .expect("protected request should be queued on the active thread"); @@ -518,8 +516,7 @@ async fn queued_startup_requests_block_draft_restore_until_drained() -> Result<( assert!(app.chat_widget.composer_is_empty()); let event = app - .active_thread_rx - .as_mut() + .active_thread_rx_mut() .expect("primary thread receiver should be active") .try_recv() .expect("protected request should be queued on the active thread"); @@ -562,8 +559,7 @@ async fn startup_draft_handoff_keeps_approval_shortcuts_in_recently_active_compo .note_server_request(&approval_request); app.enqueue_primary_thread_request(approval_request).await?; let approval_event = app - .active_thread_rx - .as_mut() + .active_thread_rx_mut() .expect("primary thread receiver should be active") .try_recv() .expect("approval should be queued on the active thread"); @@ -627,8 +623,7 @@ async fn startup_draft_delayed_approval_becomes_protected_on_redraw() -> Result< .note_server_request(&approval_request); app.enqueue_primary_thread_request(approval_request).await?; let approval_event = app - .active_thread_rx - .as_mut() + .active_thread_rx_mut() .expect("primary thread receiver should be active") .try_recv() .expect("approval should be queued on the active thread"); @@ -767,8 +762,7 @@ async fn later_thread_approval_preserves_input_after_startup_boundary_ends() -> .note_server_request(&approval_request); app.enqueue_primary_thread_request(approval_request).await?; let approval_event = app - .active_thread_rx - .as_mut() + .active_thread_rx_mut() .expect("primary thread receiver should be active") .try_recv() .expect("approval should be queued on the active thread"); @@ -883,7 +877,7 @@ async fn unattended_modals_survive_unfinished_terminal_input() -> Result<()> { .pending_app_server_requests .note_server_request(&request); app.enqueue_primary_thread_request(request).await?; - let event = app.active_thread_rx.as_mut().unwrap().try_recv()?; + let event = app.active_thread_rx_mut().unwrap().try_recv()?; app.handle_active_thread_event(&mut tui, &mut app_server, event) .await?; assert!(app.chat_widget.has_active_modal()); @@ -1145,8 +1139,7 @@ async fn startup_draft_handoff_protects_delayed_question_until_resolved() -> Res .note_server_request(&request); app.enqueue_primary_thread_request(request).await?; let event = app - .active_thread_rx - .as_mut() + .active_thread_rx_mut() .expect("primary thread receiver should be active") .try_recv() .expect("user input request should be queued on the active thread"); @@ -1218,8 +1211,7 @@ async fn fresh_startup_thread_drains_buffered_approval_before_draft_handoff() -> assert!(matches!(control, AppRunControl::Continue)); assert!( - app.active_thread_rx - .as_ref() + app.active_thread_rx() .is_some_and(|receiver| !receiver.is_empty()) ); assert!(!app.chat_widget.has_active_view()); @@ -1638,8 +1630,7 @@ async fn startup_thread_started_discards_another_threads_buffered_events() { assert!(app.pending_primary_events.is_empty()); assert!( - app.active_thread_rx - .as_mut() + app.active_thread_rx_mut() .is_some_and(|rx| rx.try_recv().is_err()) ); } diff --git a/codex-rs/tui/src/app/tests/streaming_interleave_e2e.rs b/codex-rs/tui/src/app/tests/streaming_interleave_e2e.rs index 2b85e61a7e..94e5b73e9c 100644 --- a/codex-rs/tui/src/app/tests/streaming_interleave_e2e.rs +++ b/codex-rs/tui/src/app/tests/streaming_interleave_e2e.rs @@ -219,12 +219,11 @@ async fn command_start_before_message_completion_does_not_duplicate_preamble() - ); for replay in [false, true] { if replay { - app.store_active_thread_receiver().await; - let (receiver, snapshot) = app + app.save_active_thread_state().await; + let snapshot = app .activate_thread_for_replay(thread_id) .await .expect("thread should retain its buffered notifications"); - app.active_thread_rx = Some(receiver); app.render_thread_snapshot( &mut tui, &mut app_server, diff --git a/codex-rs/tui/src/app/thread_events.rs b/codex-rs/tui/src/app/thread_events.rs index 282074b878..e8892a6f0a 100644 --- a/codex-rs/tui/src/app/thread_events.rs +++ b/codex-rs/tui/src/app/thread_events.rs @@ -651,7 +651,7 @@ pub(super) struct ThreadEventChannel { /// Set on backend handoff so a retained channel is detached through its owning session. pub(super) backend_id: Option, pub(super) sender: mpsc::Sender, - pub(super) receiver: Option>, + pub(super) receiver: mpsc::Receiver, pub(super) store: Arc>, /// Live Attach restored delivery without reading the history from the gap. pub(super) history_may_be_incomplete: bool, @@ -665,7 +665,7 @@ impl ThreadEventChannel { let (sender, receiver) = mpsc::channel(capacity); Self { sender, - receiver: Some(receiver), + receiver, store: Arc::new(Mutex::new(ThreadEventStore::new(capacity))), backend_id: None, history_may_be_incomplete: false, @@ -703,7 +703,7 @@ impl ThreadEventChannel { let (sender, receiver) = mpsc::channel(capacity); Self { sender, - receiver: Some(receiver), + receiver, store: Arc::new(Mutex::new(ThreadEventStore::new_with_session( capacity, session, turns, ))), diff --git a/codex-rs/tui/src/app/thread_routing.rs b/codex-rs/tui/src/app/thread_routing.rs index 2446bc402e..47acb41b3a 100644 --- a/codex-rs/tui/src/app/thread_routing.rs +++ b/codex-rs/tui/src/app/thread_routing.rs @@ -116,16 +116,31 @@ impl App { } } + pub(super) fn active_thread_rx(&self) -> Option<&mpsc::Receiver> { + Some( + &self + .thread_event_channels + .get(&self.active_thread_id?)? + .receiver, + ) + } + + pub(super) fn active_thread_rx_mut( + &mut self, + ) -> Option<&mut mpsc::Receiver> { + Some( + &mut self + .thread_event_channels + .get_mut(&self.active_thread_id?)? + .receiver, + ) + } + pub(super) async fn activate_thread_channel(&mut self, thread_id: ThreadId) { if self.active_thread_id.is_some() { return; } self.set_thread_active(thread_id, /*active*/ true).await; - let receiver = if let Some(channel) = self.thread_event_channels.get_mut(&thread_id) { - channel.receiver.take() - } else { - None - }; if let Some(startup_pane) = self.sidebars.remove(&None) && let std::collections::hash_map::Entry::Vacant(entry) = self.sidebars.entry(Some(thread_id)) @@ -138,11 +153,10 @@ impl App { } } self.active_thread_id = Some(thread_id); - self.active_thread_rx = receiver; self.refresh_pending_thread_approvals().await; } - pub(super) async fn store_active_thread_receiver(&mut self) { + pub(super) async fn save_active_thread_state(&mut self) { let Some(active_id) = self.active_thread_id else { return; }; @@ -153,7 +167,6 @@ impl App { let input_state = self.chat_widget.capture_thread_input_state(); let recap_progress = self.recap.progress(); if let Some(channel) = self.thread_event_channels.get_mut(&active_id) { - let receiver = self.active_thread_rx.take(); let mut store = channel.store.lock().await; if store.active { store.replay_may_have_output = false; @@ -161,9 +174,6 @@ impl App { store.active = false; store.input_state = input_state; store.merge_recap_progress(recap_progress); - if let Some(receiver) = receiver { - channel.receiver = Some(receiver); - } } } @@ -192,20 +202,17 @@ impl App { pub(super) async fn activate_thread_for_replay( &mut self, thread_id: ThreadId, - ) -> Option<(mpsc::Receiver, ThreadEventSnapshot)> { - let channel = self.thread_event_channels.get_mut(&thread_id)?; - let receiver = channel.receiver.take()?; + ) -> Option { + let channel = self.thread_event_channels.get(&thread_id)?; let mut store = channel.store.lock().await; store.active = true; - let snapshot = store.snapshot(); - Some((receiver, snapshot)) + Some(store.snapshot()) } pub(super) async fn clear_active_thread(&mut self) { if let Some(active_id) = self.active_thread_id.take() { self.set_thread_active(active_id, /*active*/ false).await; } - self.active_thread_rx = None; self.refresh_pending_thread_approvals().await; } @@ -1887,12 +1894,7 @@ impl App { tui: &mut tui::Tui, frame_deadline: Instant, ) -> Result<()> { - let Some(mut rx) = self.active_thread_rx.take() else { - return Ok(()); - }; - - let mut disconnected = false; - loop { + while let Some(rx) = self.active_thread_rx_mut() { match rx.try_recv() { Ok(event) => { self.handle_thread_event_now_recovering_file_changes(event) @@ -1900,7 +1902,7 @@ impl App { } Err(TryRecvError::Empty) => break, Err(TryRecvError::Disconnected) => { - disconnected = true; + self.clear_active_thread().await; break; } } @@ -1909,12 +1911,6 @@ impl App { } } - if !disconnected { - self.active_thread_rx = Some(rx); - } else { - self.clear_active_thread().await; - } - if self.backtrack_render_pending { tui.frame_requester().schedule_frame(); }