From db227aed42df3c9d842986860993714de8e6e4d5 Mon Sep 17 00:00:00 2001 From: Felipe Coury Date: Mon, 2 Nov 2026 21:27:02 +0000 Subject: [PATCH] Add opt-in side conversation panes to the TUI (#58992) ## What changed - Add the disabled-by-default `tui_workspace` feature for the owned transcript view. At terminal widths of at least 100 columns, show the parent conversation beside its side conversation, with only the focused composer accepting input. - Retain the inactive conversation's transcript, draft, and status, and restore reading and search state when switching focus. - Keep drawing and input paused until history replay completes, while refreshing skills in the background. ## Testing Add snapshots and regression tests for pane resizing and composer styling, retained streaming output, history search after replay, pending skills refreshes, and modal input protection. GitOrigin-RevId: 68938f263353b0cd3a9e9562e06293bfc8251cc6 --- codex-rs/core/config.schema.json | 6 + codex-rs/features/src/lib.rs | 8 + codex-rs/tui/src/app.rs | 4 + codex-rs/tui/src/app/background_requests.rs | 29 +- codex-rs/tui/src/app/event_dispatch.rs | 102 ++++++ codex-rs/tui/src/app/history_pagination.rs | 2 + codex-rs/tui/src/app/owned_transcript.rs | 38 ++- codex-rs/tui/src/app/session_lifecycle.rs | 76 ++++- codex-rs/tui/src/app/side.rs | 22 ++ codex-rs/tui/src/app/side_pane.rs | 134 ++++++++ codex-rs/tui/src/app/startup.rs | 20 +- codex-rs/tui/src/app/test_support.rs | 15 + codex-rs/tui/src/app/tests.rs | 290 +++++++++++++++++- .../app/tests/pagination_completion_tests.rs | 72 +++++ codex-rs/tui/src/app/tests/startup.rs | 39 +++ codex-rs/tui/src/app/thread_events.rs | 3 + codex-rs/tui/src/app/thread_routing.rs | 26 ++ codex-rs/tui/src/app_event.rs | 35 +++ codex-rs/tui/src/app_server_session.rs | 4 + .../tui/src/app_server_session/history.rs | 11 +- codex-rs/tui/src/bottom_pane/chat_composer.rs | 4 +- .../chat_composer/composer_layout.rs | 13 + .../bottom_pane/chat_composer/footer_state.rs | 2 + codex-rs/tui/src/bottom_pane/mod.rs | 1 - codex-rs/tui/src/chatwidget.rs | 2 - codex-rs/tui/src/chatwidget/input_restore.rs | 2 +- codex-rs/tui/src/chatwidget/streaming.rs | 74 ++++- ...tui__app__tests__side_composer_gutter.snap | 11 + ...dex_tui__app__tests__single_side_chat.snap | 21 ++ codex-rs/tui/src/streaming/commit_tick.rs | 11 +- codex-rs/tui/src/streaming/controller.rs | 16 +- codex-rs/tui/src/style.rs | 11 + codex-rs/tui/src/transcript_view.rs | 57 ++++ codex-rs/tui/src/transcript_view/mutations.rs | 25 +- codex-rs/tui/src/transcript_view/search.rs | 2 +- .../tui/src/transcript_view/search_tests.rs | 46 +++ codex-rs/tui/src/transcript_view/snapshot.rs | 23 +- 37 files changed, 1197 insertions(+), 60 deletions(-) create mode 100644 codex-rs/tui/src/app/side_pane.rs create mode 100644 codex-rs/tui/src/snapshots/codex_tui__app__tests__side_composer_gutter.snap create mode 100644 codex-rs/tui/src/snapshots/codex_tui__app__tests__single_side_chat.snap diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index d2316479dd..caced41390 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -1419,6 +1419,9 @@ "tui_multi_backend": { "type": "boolean" }, + "tui_workspace": { + "type": "boolean" + }, "ultrafast_mode": { "type": "boolean" }, @@ -8136,6 +8139,9 @@ "tui_multi_backend": { "type": "boolean" }, + "tui_workspace": { + "type": "boolean" + }, "ultrafast_mode": { "type": "boolean" }, diff --git a/codex-rs/features/src/lib.rs b/codex-rs/features/src/lib.rs index 4678ea4771..291ffd6976 100644 --- a/codex-rs/features/src/lib.rs +++ b/codex-rs/features/src/lib.rs @@ -125,6 +125,8 @@ pub enum Feature { DaemonAutoStart, /// Allow the TUI to discover and select among multiple conversation backends. TuiMultiBackend, + /// Enable workspace behavior for side conversations in the owned TUI. + TuiWorkspace, /// Render the configured status line through the experimental TUI Extensions renderer. TuiExtensionsStatusLine, /// Enable negotiated zstd compression for app-server WebSocket and UDS connections. @@ -1123,6 +1125,12 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::Removed, default_enabled: true, }, + FeatureSpec { + id: Feature::TuiWorkspace, + key: "tui_workspace", + stage: Stage::UnderDevelopment, + default_enabled: false, + }, FeatureSpec { id: Feature::TuiMultiBackend, key: "tui_multi_backend", diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 80459f4113..f3a81fc4ef 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -270,6 +270,7 @@ mod server_version_notice; mod session_lifecycle; mod session_picker; mod side; +mod side_pane; mod startup; pub(crate) mod startup_bootstrap; mod startup_prompts; @@ -300,6 +301,7 @@ use self::loaded_threads::find_loaded_subagent_threads_for_primary; use self::pending_interactive_replay::PendingInteractiveReplayState; pub(crate) use self::platform_actions::WindowsSandboxHost; use self::platform_actions::*; +use self::side::SideCompanion; use self::side::SideParentStatus; use self::side::SideParentStatusChange; use self::side::SideThreadState; @@ -645,6 +647,8 @@ pub(crate) struct App { agent_navigation: AgentNavigationState, agents_overview: agents_overview::AgentsOverviewState, side_threads: HashMap, + /// A parked parent view survives child cleanup until its own replay finishes. + side_companions: HashMap, abandoned_side_threads: HashSet, active_thread_id: Option, active_thread_rx: Option>, diff --git a/codex-rs/tui/src/app/background_requests.rs b/codex-rs/tui/src/app/background_requests.rs index 999931d53b..6894b98915 100644 --- a/codex-rs/tui/src/app/background_requests.rs +++ b/codex-rs/tui/src/app/background_requests.rs @@ -258,9 +258,17 @@ impl App { let app_event_tx = self.app_event_tx.clone(); let cwd = self.config.cwd.to_path_buf(); tokio::spawn(async move { - let result = fetch_skills_list(request_handle, cwd.clone()) - .await - .map_err(|err| format!("{err:#}")); + let request_id = RequestId::String(format!("startup-skills-list-{}", Uuid::new_v4())); + let result = fetch_skills_list( + request_handle, + request_id, + SkillsListParams { + cwds: vec![cwd.clone()], + force_reload: true, + }, + ) + .await + .map_err(|err| format!("{err:#}")); app_event_tx.send(AppEvent::SkillsListLoaded { cwd, result }); }); } @@ -685,6 +693,7 @@ impl App { let should_send = { let mut guard = store.lock().await; + guard.replay_may_have_output |= !guard.active; guard.push_buffered_event(ThreadBufferedEvent::FeedbackSubmission(event.clone())); guard.active }; @@ -918,19 +927,11 @@ pub(super) async fn send_add_credits_nudge_email( pub(super) async fn fetch_skills_list( request_handle: AppServerRequestHandle, - cwd: PathBuf, + request_id: RequestId, + params: SkillsListParams, ) -> Result { - let request_id = RequestId::String(format!("startup-skills-list-{}", Uuid::new_v4())); - // Use the cloneable request handle so startup can issue this RPC from a background task without - // extending a borrow of `AppServerSession` across the first frame render. request_handle - .request_typed(ClientRequest::SkillsList { - request_id, - params: SkillsListParams { - cwds: vec![cwd], - force_reload: true, - }, - }) + .request_typed(ClientRequest::SkillsList { request_id, params }) .await .wrap_err("skills/list failed in TUI") } diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index ff761c30af..aa861b8da4 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -8,6 +8,7 @@ use super::rate_limit_refresh::RateLimitRefreshOutcome; use super::resize_reflow::trailing_run_start; use super::session_lifecycle::ThreadAttachPresentation; use super::*; +use crate::app_event::CapturedSideStream; use crate::app_event::RecapTrigger; use crate::app_event::ThreadTitleDestination; use crate::app_server_session::ForkGoalContinuation; @@ -87,6 +88,8 @@ impl App { | AppEvent::RunDaemonUpdate(_) | AppEvent::InsertHistoryCell(_) | AppEvent::CommitRealtimeTranscriptHistory + | AppEvent::ParkSideCompanion { .. } + | AppEvent::SideReplayFinished(_) | AppEvent::ResetTranscriptForThreadSwitch | AppEvent::ResetTranscriptForThreadSwitchPreservingScreen | AppEvent::FinishPromptRevert { .. } @@ -930,10 +933,67 @@ impl App { AppEvent::BeginThreadSwitchHistoryReplayBuffer => { self.begin_thread_switch_history_replay_buffer(); } + AppEvent::ParkSideCompanion { pair, thread_id, stream, display } => { + if self.side_threads.contains_key(&pair) { + self.transcript_view.sync_history_tail(&self.transcript_cells); + if let Some(stream) = stream { + let cells = &mut self.transcript_cells; + let (start, replacement): (_, Arc) = match stream { + CapturedSideStream::Answer(cell) => { + (trailing_run_start::(cells), cell) + } + CapturedSideStream::Plan(cell) => { + (trailing_run_start::(cells), cell) + } + }; + let range = start..cells.len(); + self.transcript_view.replace_group(cells, range.clone(), &replacement); + cells.splice(range, [replacement]); + } + self.side_companions.insert(thread_id, SideCompanion { + display, + cells: std::mem::take(&mut self.transcript_cells), + view: std::mem::take(&mut self.transcript_view), + }); + } + } AppEvent::ResetTranscriptForThreadSwitch => { self.reset_for_thread_switch(tui)?; self.pending_thread_switch_resets -= 1; } + AppEvent::SideReplayFinished(id) => { + self.pending_thread_switch_resets -= 1; + let finished_current_replay = self.pending_thread_switch_resets == 0 + && self.current_displayed_thread_id() == Some(id); + // Keys typed against the old frame must not answer the newly revealed modal. + self.startup_protected_input_boundary |= + finished_current_replay && self.chat_widget.has_active_modal(); + if finished_current_replay && let Some(companion) = self.side_companions.remove(&id) + { + let replay_may_have_output = match self.thread_event_channels.get(&id) { + Some(channel) => channel.store.lock().await.replay_may_have_output, + None => true, + }; + self.transcript_view = companion.view; + self.transcript_view.restore_after_replay( + &companion.cells, + &self.transcript_cells, + replay_may_have_output, + self.chat_widget.active_cell_transcript_key(), + ); + self.scrollback_has_older_history = app_server.has_older_history(id); + if self.transcript_view.history == TranscriptHistoryState::LoadingOlder + && app_server.pending_older_history_cursor(id).is_none() + { + self.transcript_view.history = if self.scrollback_has_older_history { + TranscriptHistoryState::Partial + } else { + TranscriptHistoryState::Complete + }; + } + tui.frame_requester().schedule_frame(); + } + } AppEvent::ResetTranscriptForThreadSwitchPreservingScreen => { self.reset_transcript_state_after_clear(); tui.clear_pending_history_lines(); @@ -1144,6 +1204,34 @@ impl App { AppEvent::ImagesPrepared(id) => { self.chat_widget.on_images_prepared(id); } + AppEvent::CodexOp(AppCommand::ListSkills { cwds, force_reload: true }) + if self.awaiting_side_replay(tui) + && let Some(thread_id) = self.active_thread_id + && self.side_pair_key(thread_id).is_some() + && !self.thread_unavailable(thread_id) => + { + // Session replay refreshes skill metadata. Let focus paint while that RPC is pending. + let cwd = self.chat_widget.config_ref().cwd.to_path_buf(); + if cwds.contains(&cwd) { + let request_id = Uuid::new_v4(); + app_server.pending_side_skills_refresh = Some(request_id); + let rpc_id = app_server.next_request_id(); + let request_handle = app_server.request_handle(); + let app_event_tx = self.app_event_tx.clone(); + tokio::spawn(async move { + let result = background_requests::fetch_skills_list( + request_handle, + rpc_id, + SkillsListParams { cwds, force_reload: true }, + ) + .await + .map_err(|err| format!("{err:#}")); + app_event_tx.send(AppEvent::SideReplaySkillsLoaded { + request_id, thread_id, cwd, result, + }); + }); + } + } AppEvent::CodexOp(mut op) => { if let AppCommand::OverrideTurnContext { cwd, @@ -1803,6 +1891,20 @@ impl App { } => { self.handle_mcp_inventory_result(result, detail, thread_id); } + AppEvent::SideReplaySkillsLoaded { request_id, thread_id, cwd, result } => { + if app_server.pending_side_skills_refresh == Some(request_id) { + app_server.pending_side_skills_refresh = None; + if !self.awaiting_side_replay(tui) + && self.current_displayed_thread_id() == Some(thread_id) + && !cwds_differ(&cwd, self.chat_widget.config_ref().cwd.as_path()) + { + self.handle_skills_list_result( + result.map_err(|err| color_eyre::eyre::eyre!(err)), + "failed to refresh skills", + ); + } + } + } AppEvent::SkillsListLoaded { result, .. } => { self.handle_skills_list_result( result.map_err(|err| color_eyre::eyre::eyre!(err)), diff --git a/codex-rs/tui/src/app/history_pagination.rs b/codex-rs/tui/src/app/history_pagination.rs index 74f8b7edd1..8ee444d6f9 100644 --- a/codex-rs/tui/src/app/history_pagination.rs +++ b/codex-rs/tui/src/app/history_pagination.rs @@ -69,7 +69,9 @@ impl App { if !app_server.is_older_history_page_pending(thread_id, cursor) { return Ok(()); } + // The widget can already belong to the destination while the transcript still replays. if self.chat_widget.thread_id() != Some(thread_id) + || self.awaiting_side_replay(tui) || (tui.is_owned_screen() && !self.scrollback_has_older_history) { app_server.cancel_older_history_page(thread_id, cursor); diff --git a/codex-rs/tui/src/app/owned_transcript.rs b/codex-rs/tui/src/app/owned_transcript.rs index b1f74ccb42..831af8dc7e 100644 --- a/codex-rs/tui/src/app/owned_transcript.rs +++ b/codex-rs/tui/src/app/owned_transcript.rs @@ -1,4 +1,5 @@ //! Compose the owned transcript above the composer and route their selection gestures. +//! A docked side conversation paints the captured neighbor before the centered dialog. //! Painting records the screen regions used by selection and pointer input. //! Input that depends on those regions refreshes the layout before using them. //! Reserve a cleared row below activity and previews, immediately above the composer. @@ -30,6 +31,7 @@ use ratatui::widgets::Widget; #[derive(Default)] pub(super) struct ConversationFrame { inset: Option, + side_pane: bool, /// A dialog can obscure neighboring content in the terminal's completed buffer. behind_dialog: Option, caller_images: Vec, @@ -154,7 +156,7 @@ impl App { true } - fn sync_owned_transcript(&mut self, width: u16) -> bool { + pub(super) fn sync_owned_transcript(&mut self, width: u16) -> bool { self.transcript_view.image_protocol = self.prepare_frame_images(); let chat_widget = &self.chat_widget; let transcript_width = chat_widget.history_wrap_width(width); @@ -194,11 +196,22 @@ impl App { screen_size: Size, ) -> Result { let frames = tui.frame_requester(); - let prepared = - self.prepare_conversation(screen_size.into(), self.conversation_frame.inset, &frames); + if self.conversation_frame.side_pane { + // Recompute our own inset on every frame, including the first narrow frame. + self.conversation_frame = ConversationFrame::default(); + } + let caller_inset = self.conversation_frame.inset; + let dock = if caller_inset.is_none() { + side_pane::layout(self, tui, screen_size.into()) + } else { + None + }; + let inset = caller_inset.or_else(|| dock.as_ref().map(|panes| panes.focused)); + let prepared = self.prepare_conversation(screen_size.into(), inset, &frames); + self.conversation_frame.side_pane = dock.is_some(); // An input refresh opens a fresh terminal buffer. Carry the outer owner's // completed cells through it when only the conversation is being redrawn. - let backdrop = self.conversation_frame.inset.map(|_| { + let backdrop = caller_inset.map(|_| { self.conversation_frame .behind_dialog .take() @@ -223,6 +236,12 @@ impl App { } } painted = self.paint_conversation(frame, &prepared); + if let Some(panes) = dock + && let Some(companion) = self.side_companions.get_mut(&panes.passive_thread) + { + companion.view.image_protocol = self.transcript_view.image_protocol; + panes.paint_companion(companion, frame); + } self.paint_centered_dialog(frame); })?; self.finish_conversation(tui, painted) @@ -235,6 +254,7 @@ impl App { frames: &tui::FrameRequester, ) -> PreparedConversation { self.conversation_frame.inset = conversation_inset; + self.conversation_frame.side_pane = false; let area = self.conversation_area(viewport); if let Some((previous, reflowed)) = self.chat_widget.resize_owned_conversation(area.width) { self.transcript_view @@ -327,6 +347,7 @@ impl App { .min(area.height); let options = |interacting| ComposerRenderOptions { max_height: Some(max_composer_height), + extend_composer_background_left: self.conversation_frame.side_pane && area.x > 0, overlay_top: area.top(), command_popup_placement: if interacting { CommandPopupPlacement::Hidden @@ -483,7 +504,7 @@ impl App { ) -> Result { if self.conversation_frame.behind_dialog.is_none() { self.conversation_frame.caller_images.clear(); - if self.conversation_frame.inset.is_some() { + if self.conversation_frame.inset.is_some() && !self.conversation_frame.side_pane { self.conversation_frame.caller_images.extend( tui.retained_images .iter() @@ -513,7 +534,12 @@ impl App { return; }; let area = frame.area(); - if self.conversation_frame.inset.is_some() { + if self.conversation_frame.side_pane { + let covered = dialog.area(area); + frame + .image_placements + .retain(|placement| !covered.intersects(placement.area)); + } else if self.conversation_frame.inset.is_some() { self.conversation_frame.behind_dialog = Some(frame.buffer.clone()); // The conversation omits its own images while a dialog is open. Keep the // caller's registrations so dismissal can restore graphics behind the dialog. diff --git a/codex-rs/tui/src/app/session_lifecycle.rs b/codex-rs/tui/src/app/session_lifecycle.rs index 9203adf62c..1c2ee349eb 100644 --- a/codex-rs/tui/src/app/session_lifecycle.rs +++ b/codex-rs/tui/src/app/session_lifecycle.rs @@ -13,6 +13,7 @@ use crate::app_server_session::is_server_shutting_down_error; use crate::app_server_session::source_agent_path; use crate::app_server_session::thread_blocks_direct_input; use crate::chatwidget::ThreadInputStateRestoreMode; +use crate::streaming::commit_tick::CommitTickScope; use std::collections::HashSet; #[derive(Clone, Copy)] @@ -462,6 +463,18 @@ impl App { (session, turns, false) } }; + // A reattach can discover output missed while the server was disconnected. + let replay_may_have_output = if self.side_companions.contains_key(&thread_id) { + match self.thread_event_channels.get(&thread_id) { + Some(channel) => { + let store = channel.store.lock().await; + store.replay_may_have_output || store.session.is_none() || store.turns != turns + } + None => true, + } + } else { + false + }; self.agents_overview.activity.remove(&thread_id); let recap_progress = if live_attached && let Some(channel) = self.thread_event_channels.remove(&thread_id) { @@ -483,6 +496,7 @@ impl App { } let mut store = channel.store.lock().await; store.set_session(session, turns); + store.replay_may_have_output |= replay_may_have_output; store.merge_recap_progress(recap_progress); store.rebase_buffer_after_session_refresh(); Ok(live_attached) @@ -704,6 +718,27 @@ impl App { self.recap.seed_from_progress(recap_progress, now); self.schedule_recap_check(thread_id, now); + // Draining the old receiver can queue history insertions and stream consolidation. + // Park the transcript after those events and before the destination's reset and replay. + if self.side_retention_enabled(tui) + && self.pending_thread_switch_resets == 0 + && let Some(old) = previous_thread_id + && old != thread_id + && let Some(pair) = self.side_pair_key(old) + { + let conversation_width = self + .conversation_area(tui.terminal.last_known_screen_size.into()) + .width; + self.sync_owned_transcript(conversation_width); + let width = self.transcript_view.remaining_area().width.max(1); + let (stream, display) = self.chat_widget.take_side_display(width); + self.app_event_tx.send(AppEvent::ParkSideCompanion { + pair, + thread_id: old, + stream, + display, + }); + } self.render_thread_snapshot(tui, app_server, thread_id, snapshot, !is_replay_only)?; if is_replay_only && self @@ -734,6 +769,14 @@ impl App { snapshot: ThreadEventSnapshot, resume_restored_queue: bool, ) -> Result<()> { + let retain_side_view = self.side_retention_enabled(tui); + let preserve_screen = retain_side_view + && self.side_pair_key(thread_id).is_some_and(|pair| { + self.chat_widget + .thread_id() + .and_then(|id| self.side_pair_key(id)) + == Some(pair) + }); let init = self.chatwidget_init_for_forked_or_resumed_thread( tui, self.config.clone(), @@ -754,10 +797,21 @@ impl App { if self.agent_navigation.is_parent_owned(thread_id) { self.chat_widget.set_parent_owned_thread(); } - self.reset_for_thread_switch(tui)?; + if retain_side_view { + // Even a superseding selection must leave queued history its original cells and view. + tui.clear_pending_history_lines(); + if !preserve_screen { + tui.clear_for_thread_switch()?; + } + } else { + self.reset_for_thread_switch(tui)?; + } self.pending_thread_switch_resets += 1; - self.app_event_tx - .send(AppEvent::ResetTranscriptForThreadSwitch); + self.app_event_tx.send(if preserve_screen { + AppEvent::ResetTranscriptForThreadSwitchPreservingScreen + } else { + AppEvent::ResetTranscriptForThreadSwitch + }); self.replay_thread_snapshot(snapshot, resume_restored_queue); if let Some(thread_id) = self.chat_widget.thread_id() && let Some(active) = self @@ -776,6 +830,14 @@ impl App { if external_writer { self.chat_widget.show_external_writer_thread(); } + if retain_side_view { + // Hold drawing and input through the history events emitted by replay. + self.chat_widget + .run_commit_tick_with_scope(CommitTickScope::Replay); + self.pending_thread_switch_resets += 1; + self.app_event_tx + .send(AppEvent::SideReplayFinished(thread_id)); + } Ok(()) } @@ -834,6 +896,14 @@ impl App { }); self.thread_event_channels .retain(|id, _| Some(*id) == voice_owner || self.side_threads.contains_key(id)); + // A retained side can still display its parent even after the parent channel is detached. + self.side_companions.retain(|id, _| { + self.side_threads.contains_key(id) + || self + .side_threads + .values() + .any(|side| side.parent_thread_id == *id) + }); self.pending_realtime_speech_replay.clear(); self.pending_realtime_transcript_replay.clear(); self.realtime_replay_order.clear(); diff --git a/codex-rs/tui/src/app/side.rs b/codex-rs/tui/src/app/side.rs index 78b0fcda53..683ecb377c 100644 --- a/codex-rs/tui/src/app/side.rs +++ b/codex-rs/tui/src/app/side.rs @@ -209,6 +209,13 @@ impl SideParentStatusChange { } } +/// Transcript state retained while the other conversation is active. +pub(super) struct SideCompanion { + pub(super) display: crate::app_event::CapturedSideDisplay, + pub(super) cells: Vec>, + pub(super) view: crate::transcript_view::TranscriptView, +} + #[derive(Clone, Debug)] pub(super) struct SideThreadState { /// Thread to return to when the current side conversation is dismissed. @@ -308,6 +315,20 @@ impl App { .map(|state| state.parent_thread_id) } + pub(super) fn side_retention_enabled(&self, tui: &tui::Tui) -> bool { + self.config.features.enabled(Feature::TuiWorkspace) + && self.local_settings.transcript_mode.is_owned() + && tui.is_owned_screen() + } + + pub(super) fn side_pair_key(&self, thread_id: ThreadId) -> Option { + if self.side_threads.contains_key(&thread_id) { + Some(thread_id) + } else { + self.side_thread_for_parent(thread_id) + } + } + pub(super) fn side_thread_for_parent(&self, parent_thread_id: ThreadId) -> Option { self.side_threads.iter().find_map(|(thread_id, state)| { (state.parent_thread_id == parent_thread_id).then_some(*thread_id) @@ -543,6 +564,7 @@ impl App { self.pending_server_profiles.remove(&thread_id); self.agents_overview.activity.remove(&thread_id); self.side_threads.remove(&thread_id); + self.side_companions.remove(&thread_id); self.agent_navigation.remove(thread_id); if self.active_thread_id == Some(thread_id) { self.clear_active_thread().await; diff --git a/codex-rs/tui/src/app/side_pane.rs b/codex-rs/tui/src/app/side_pane.rs new file mode 100644 index 0000000000..43529a9353 --- /dev/null +++ b/codex-rs/tui/src/app/side_pane.rs @@ -0,0 +1,134 @@ +//! Layout and paint the two conversations. Only the displayed thread owns a live composer. + +use super::App; +use super::agents_overview::AGENTS_OVERVIEW_VIEW_ID; +use super::side::SideCompanion; +use crate::bottom_pane::inset_footer_hint_area; +use crate::custom_terminal::Frame; +use crate::line_truncation::truncate_line_with_ellipsis_if_overflow; +use codex_protocol::ThreadId; +use ratatui::layout::Constraint; +use ratatui::layout::Layout; +use ratatui::layout::Rect; +use ratatui::style::Stylize; +use ratatui::text::Text; +use ratatui::widgets::Widget; + +pub(super) struct SidePaneLayout { + pub(super) focused: Rect, + pub(super) passive_thread: ThreadId, + passive: Rect, + divider: u16, +} + +/// A wide terminal can show a pair once the outgoing conversation has been captured. +pub(super) fn layout(app: &App, tui: &crate::tui::Tui, area: Rect) -> Option { + if area.width < 100 + || !app.side_retention_enabled(tui) + || app + .chat_widget + .selected_index_for_present_view(AGENTS_OVERVIEW_VIEW_ID) + .is_some() + { + return None; + } + let active = app.current_displayed_thread_id()?; + let side = app.side_threads.get(&active); + let passive_thread = match side { + Some(child) => child.parent_thread_id, + None => app.side_thread_for_parent(active)?, + }; + if !app.side_companions.contains_key(&passive_thread) { + return None; + } + let child_width = (area.width / 3).max(36); + let [parent, child] = + Layout::horizontal([Constraint::Fill(1), Constraint::Length(child_width)]) + .spacing(2) + .areas(area); + let (focused, passive) = if side.is_some() { + (child, parent) + } else { + (parent, child) + }; + Some(SidePaneLayout { + focused, + passive, + passive_thread, + divider: parent.right(), + }) +} + +impl SidePaneLayout { + /// Paint the divider, retained transcript and draft without claiming the terminal cursor. + pub(super) fn paint_companion(&self, companion: &mut SideCompanion, frame: &mut Frame<'_>) { + let area = self.passive; + for y in area.y..area.bottom() { + frame.buffer[(self.divider, y)] + .set_symbol("│") + .set_style(ratatui::style::Style::default().dim()); + } + // Keep the live composer's bottom hint row blank on the inactive side. + let available = area.height.saturating_sub(1); + let composer_height = available.min(3); + let status_height = + u16::from(companion.display.status.is_some() && available > composer_height); + let above = available - composer_height - status_height; + let transcript = Rect { + height: above.saturating_sub(1), + ..area + }; + companion.view.render_parked( + transcript, + frame.buffer, + &companion.cells, + companion.display.active.as_deref(), + &companion.display.auxiliary, + ); + frame + .image_placements + .extend(companion.view.image_placements()); + + let composer = Rect { + y: area.y + above, + height: composer_height, + ..area + }; + let gutter = u16::from(composer.x > self.divider); + frame.buffer.set_style( + Rect { + x: composer.x - gutter, + width: composer.width + gutter, + ..composer + }, + crate::style::quiet_workspace_style(), + ); + let inset = u16::from(composer_height > 1); + let draft = Text::from(format!("› {}", companion.display.draft)); + let lines = crate::wrapping::word_wrap_lines( + draft.lines, + crate::wrapping::RtOptions::new(usize::from(composer.width)) + .word_splitter(textwrap::WordSplitter::NoHyphenation), + ); + Text::from(lines).render( + Rect { + y: composer.y + inset, + height: composer_height - inset, + ..composer + }, + frame.buffer, + ); + if let Some(status) = &companion.display.status { + let footer = inset_footer_hint_area(Rect { + y: composer.bottom(), + height: status_height, + ..area + }); + truncate_line_with_ellipsis_if_overflow( + status.clone().dim().into(), + usize::from(footer.width), + ) + .render(footer, frame.buffer); + } + } +} diff --git a/codex-rs/tui/src/app/startup.rs b/codex-rs/tui/src/app/startup.rs index fca1ef21b6..6fc0ac5729 100644 --- a/codex-rs/tui/src/app/startup.rs +++ b/codex-rs/tui/src/app/startup.rs @@ -163,6 +163,10 @@ impl App { } } + pub(super) fn awaiting_side_replay(&self, tui: &tui::Tui) -> bool { + self.pending_thread_switch_resets != 0 && self.side_retention_enabled(tui) + } + /// Keep the provisional loading frame until queued history reaches the owned transcript. /// Visible startup decisions and the agent overview must still render immediately. pub(super) fn render_startup_frame( @@ -170,7 +174,10 @@ impl App { tui: &mut tui::Tui, app_event_rx: &mpsc::UnboundedReceiver, ) -> Result<()> { - if tui.is_owned_screen() && !app_event_rx.is_empty() && !self.chat_widget.has_active_view() + if self.awaiting_side_replay(tui) + || (tui.is_owned_screen() + && !app_event_rx.is_empty() + && !self.chat_widget.has_active_view()) { return Ok(()); } @@ -1050,6 +1057,7 @@ See the Codex keymap documentation for supported actions and examples." agent_navigation: AgentNavigationState::default(), agents_overview, side_threads: HashMap::new(), + side_companions: HashMap::new(), abandoned_side_threads: HashSet::new(), active_thread_id: None, active_thread_rx: None, @@ -1397,6 +1405,7 @@ See the Codex keymap documentation for supported actions and examples." // widgets before those app events have been applied. let has_pending_app_events = !app_event_rx.is_empty(); let paused_backend = ((app.reconnect.offline && !app.pending_startup_thread_start) + || (app.awaiting_side_replay(tui) && has_pending_app_events) || (!matches!(app.app_server_target, AppServerTarget::Embedded) && has_pending_app_events)) .then_some(displayed_owner); @@ -1461,13 +1470,16 @@ See the Codex keymap documentation for supported actions and examples." } _ => displayed_session, }; - let had_active_modal = app.chat_widget.has_active_modal(); + // A modal deferred behind a snapshot reset still needs its first frame + // and protected-input drain when replay completes. + let had_visible_modal = app.chat_widget.has_active_modal() + && !app.awaiting_side_replay(tui); match Box::pin(app.handle_event(tui, backends.session_at_mut(event_session), event)).await { Ok(AppRunControl::Continue) => { if is_initial_session_header { waiting_for_initial_session_header = false; } - if !had_active_modal + if !had_visible_modal && app.chat_widget.has_active_modal() && let Err(err) = app.render_startup_frame(tui, &app_event_rx) { @@ -1499,7 +1511,9 @@ See the Codex keymap documentation for supported actions and examples." } AppRunControl::Continue } + // Dispatch the current composer's queued submission before a focus key can switch threads. event = tui_events.next(), if app.pending_thread_switch_resets == 0 + && (!app.side_retention_enabled(tui) || app_event_rx.is_empty()) && (app.reconnect.offline || !block_terminal_input_for_pending_startup_events) => { if let Some(event) = event { if (matches!( diff --git a/codex-rs/tui/src/app/test_support.rs b/codex-rs/tui/src/app/test_support.rs index 3d1c608ca1..23967605c1 100644 --- a/codex-rs/tui/src/app/test_support.rs +++ b/codex-rs/tui/src/app/test_support.rs @@ -5,12 +5,26 @@ //! app-owned behavior. //! Return the large fixture on the heap so async scenarios do not embed it in their stack frames. +use super::owned_transcript::tests::buffer_text; use super::*; use crate::chatwidget::tests::make_chatwidget_manual_with_sender; use crate::test_support::boxed_future; use codex_models_manager::test_support::construct_model_info_offline_for_tests; use codex_models_manager::test_support::get_model_offline_for_tests; +pub(super) fn enable_side_retention(app: &mut App) -> Result<()> { + app.config.features.enable(Feature::TuiWorkspace)?; + app.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Owned; + Ok(()) +} + +pub(super) fn side_frame(app: &mut App, tui: &mut tui::Tui, size: Size) -> Result { + let size = tui.screen_size_for_event(&TuiEvent::Resize(size))?; + app.handle_draw_pre_render(tui, size)?; + app.render_chat_widget_frame(tui, size)?; + Ok(buffer_text(tui.terminal.previous_buffer())) +} + pub(crate) async fn make_test_app() -> Box { let (mut chat_widget, app_event_tx, _rx, _op_rx) = boxed_future!(make_chatwidget_manual_with_sender()).await; @@ -100,6 +114,7 @@ pub(crate) async fn make_test_app() -> Box { agent_navigation: AgentNavigationState::default(), agents_overview: Default::default(), side_threads: HashMap::new(), + side_companions: HashMap::new(), abandoned_side_threads: HashSet::new(), active_thread_id: None, active_thread_rx: None, diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index af620adcc1..6d6c4a51cc 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -119,6 +119,9 @@ mod user_verification_routes; mod worktree_background_terminals_tests; use super::agent_navigation::AgentPickerThreadVisibility; +use super::owned_transcript::tests::buffer_text; +use super::test_support::enable_side_retention; +use super::test_support::side_frame; use super::*; use crate::app_backtrack::BacktrackSelection; use crate::app_backtrack::BacktrackState; @@ -1236,9 +1239,33 @@ async fn active_thread_drain_yields_after_frame_deadline_without_dropping_events Ok(()) } +async fn drain_app_events( + app: &mut App, + tui: &mut tui::Tui, + server: &mut AppServerSession, + events: &mut tokio::sync::mpsc::UnboundedReceiver, +) -> Result<()> { + while let Ok(event) = events.try_recv() { + boxed_future!(app.handle_event(tui, server, event)).await?; + } + Ok(()) +} + +fn read_side_history(app: &mut App, tui: &mut tui::Tui, label: &str) -> Result<()> { + app.transcript_cells = (0..64) + .map(|row| plain_line_cell(format!("{label}-{row:02}"))) + .collect(); + app.refresh_owned_transcript(tui)?; + app.transcript_view + .jump_to_entry(&app.transcript_cells, /*index*/ 24); + app.refresh_owned_transcript(tui) +} + #[tokio::test] async fn selected_side_thread_close_is_handled_by_foreground_event_owner() -> Result<()> { - let mut app = make_test_app().await; + let (mut app, mut events, _ops) = make_test_app_with_channels().await; + app.config.features.enable(Feature::TuiWorkspace)?; + app.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Owned; let mut app_server = crate::start_embedded_app_server_for_picker(&app.config).await?; let primary = app_server.start_thread(&app.config).await?; let primary_thread_id = primary.session.thread_id; @@ -1263,9 +1290,12 @@ async fn selected_side_thread_close_is_handled_by_foreground_event_owner() -> Re .insert(side_thread_id, SideThreadState::new(primary_thread_id)); let mut tui = crate::tui::test_support::make_test_tui()?; + tui.set_owned_screen(/*owned*/ true)?; + read_side_history(&mut app, &mut tui, "parent")?; app.select_agent_thread(&mut tui, &mut app_server, side_thread_id) .await?; 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() @@ -1279,6 +1309,9 @@ async fn selected_side_thread_close_is_handled_by_foreground_event_owner() -> Re 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()); + 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")); app_server.shutdown().await?; Ok(()) } @@ -1922,6 +1955,8 @@ async fn replay_thread_snapshot_restores_pending_pastes_for_submit() { let large = "x".repeat(1005); app.chat_widget.handle_paste(large.clone()); + app.chat_widget.handle_key_event(KeyCode::Char('!').into()); + let expected = format!("{large}!"); let expected_input_state = app .chat_widget .capture_thread_input_state() @@ -1944,7 +1979,7 @@ async fn replay_thread_snapshot_restores_pending_pastes_for_submit() { app.chat_widget = chat_widget; app.replay_thread_snapshot(snapshot, /*resume_restored_queue*/ true); - assert_eq!(app.chat_widget.composer_text_with_pending(), large); + assert_eq!(app.chat_widget.composer_text_with_pending(), expected); app.chat_widget .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); @@ -1953,7 +1988,7 @@ async fn replay_thread_snapshot_restores_pending_pastes_for_submit() { Op::UserTurn { items, .. } => assert_eq!( items, vec![UserInput::Text { - text: large, + text: expected, text_elements: Vec::new(), }] ), @@ -3199,6 +3234,92 @@ async fn refresh_agent_picker_thread_liveness_prunes_closed_metadata_only_thread Ok(()) } +#[tokio::test] +async fn docked_replay_finishes_while_skills_refresh_is_pending() -> Result<()> { + let (mut app, mut events, _ops) = make_test_app_with_channels().await; + let parent = ThreadId::new(); + let side = ThreadId::new(); + app.side_threads + .insert(side, side::SideThreadState::new(parent)); + enable_side_retention(&mut app)?; + let _ = app.config.features.disable(Feature::Plugins); + app.chat_widget.sync_plugin_mentions_config(&app.config); + let mut tui = crate::tui::test_support::make_test_tui()?; + tui.set_owned_screen(/*owned*/ true)?; + let cwd = app.chat_widget.config_ref().cwd.to_path_buf(); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let endpoint = crate::resolve_remote_addr(&format!("ws://{}", listener.local_addr()?))?; + let (pending_tx, mut pending_rx) = tokio::sync::mpsc::unbounded_channel(); + let proxy = tokio::spawn(async move { + let (stream, _) = listener.accept().await?; + let socket = tokio_tungstenite::accept_async(stream).await?; + disconnect::serve_reconnect_requests(socket, |request| { + assert_eq!(request.method, "skills/list"); + let (release, wait) = tokio::sync::oneshot::channel(); + pending_tx + .send((request.params, release)) + .expect("test is running"); + async move { + wait.await.expect("release the pending skills refresh"); + Some(serde_json::json!({"result": {"data": []}})) + } + }) + .await + }); + let mut app_server = AppServerSession::new( + crate::backend_id::BackendId::new(), + crate::connect_remote_app_server(endpoint).await?, + crate::app_server_session::ThreadParamsMode::Embedded, + ); + let deadline = std::time::Duration::from_secs(/*secs*/ 5); + while events.try_recv().is_ok() {} + + for thread_id in [side, parent] { + app.active_thread_id = Some(thread_id); + app.pending_thread_switch_resets = 1; + app.app_event_tx + .send(AppEvent::CodexOp(AppCommand::list_skills( + vec![cwd.clone()], + /*force_reload*/ true, + ))); + app.app_event_tx + .send(AppEvent::SideReplayFinished(thread_id)); + + time::timeout( + deadline, + drain_app_events(&mut app, &mut tui, &mut app_server, &mut events), + ) + .await??; + let (params, release) = time::timeout(deadline, pending_rx.recv()) + .await? + .expect("skills/list should be requested"); + assert_eq!( + params, + Some(serde_json::json!({"cwds": [cwd], "forceReload": true})) + ); + assert!(!app.awaiting_side_replay(&tui)); + + release + .send(()) + .expect("skills/list should still be pending"); + let event = time::timeout(deadline, events.recv()) + .await? + .expect("receive the skills refresh"); + assert!(matches!( + &event, + AppEvent::SideReplaySkillsLoaded { thread_id: loaded_thread_id, result: Ok(_), .. } + if *loaded_thread_id == thread_id + )); + boxed_future!(app.handle_event(&mut tui, &mut app_server, event)).await?; + assert_eq!(app_server.pending_side_skills_refresh, None); + } + + app_server.shutdown().await?; + proxy.await??; + Ok(()) +} + #[tokio::test] async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<()> { let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await; @@ -3318,8 +3439,15 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<() .await?; assert_eq!(app.active_thread_id, Some(side_thread_id)); assert_eq!(app.side_threads.len(), 1); + drain_app_events(&mut app, &mut tui, &mut app_server, &mut app_event_rx).await?; + enable_side_retention(&mut app)?; + tui.set_owned_screen(/*owned*/ true)?; + read_side_history(&mut app, &mut tui, "child")?; + app.chat_widget.insert_str("child draft"); + app.chat_widget.handle_key_event(KeyCode::Char('!').into()); app.select_agent_thread(&mut tui, &mut app_server, parent_thread_id) .await?; + drain_app_events(&mut app, &mut tui, &mut app_server, &mut app_event_rx).await?; app.select_permission_profile( &mut app_server, PermissionProfileSelection { @@ -3330,16 +3458,63 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<() }, ) .await; + drain_app_events(&mut app, &mut tui, &mut app_server, &mut app_event_rx).await?; + read_side_history(&mut app, &mut tui, "parent")?; + app.chat_widget.insert_str("parent draft"); app.select_agent_thread(&mut tui, &mut app_server, side_thread_id) .await?; + drain_app_events(&mut app, &mut tui, &mut app_server, &mut app_event_rx).await?; let settings = next_thread_settings_updated(&mut app_server, parent_thread_id).await; app.enqueue_thread_notification( parent_thread_id, ServerNotification::ThreadSettingsUpdated(settings), ) .await?; + app.enqueue_thread_notification( + parent_thread_id, + ServerNotification::ThreadProjectUpdated( + codex_app_server_protocol::ThreadProjectUpdatedNotification { + thread_id: parent_thread_id.to_string(), + project_id: Some("other-project".into()), + }, + ), + ) + .await?; app.select_agent_thread(&mut tui, &mut app_server, parent_thread_id) .await?; + drain_app_events(&mut app, &mut tui, &mut app_server, &mut app_event_rx).await?; + app.refresh_owned_transcript(&mut tui)?; + let frame = buffer_text(tui.terminal.previous_buffer()); + assert!( + frame.contains("parent-24") && !frame.contains("New activity"), + "{frame}" + ); + + app.select_agent_thread(&mut tui, &mut app_server, side_thread_id) + .await?; + drain_app_events(&mut app, &mut tui, &mut app_server, &mut app_event_rx).await?; + app.enqueue_thread_notification( + parent_thread_id, + agent_message_delta_notification( + parent_thread_id, + "background", + "reply", + "still working\n\n", + ), + ) + .await?; + app.select_agent_thread(&mut tui, &mut app_server, parent_thread_id) + .await?; + drain_app_events(&mut app, &mut tui, &mut app_server, &mut app_event_rx).await?; + app.refresh_owned_transcript(&mut tui)?; + let frame = buffer_text(tui.terminal.previous_buffer()); + let parent_row = "parent-24"; + let child_row = "child-24"; + assert!( + frame.contains(parent_row) && frame.contains("New activity"), + "{frame}" + ); + assert_eq!(app.chat_widget.composer_text_with_pending(), "parent draft"); assert_eq!( app.config .permissions @@ -3355,6 +3530,113 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<() )) ); + for width in [100, 99, 100] { + let frame = side_frame(&mut app, &mut tui, Size::new(width, /*height*/ 18))?; + assert!( + frame.contains(parent_row) && frame.contains("parent draft"), + "{frame}" + ); + for marker in [child_row, "child draft!", "│"] { + assert_eq!(frame.contains(marker), width == 100, "{frame}"); + } + assert!(tui.terminal.last_known_cursor_pos.x < 62); + assert!(frame.contains("New activity"), "{frame}"); + } + let wide = buffer_text(tui.terminal.previous_buffer()); + let (panel, _) = wide.rsplit_once('\n').expect("split frame has a footer"); + assert_app_snapshot!("single_side_chat", panel); + + let size = Size::new(/*width*/ 100, /*height*/ 18); + let composer_gutter = |app: &mut App, tui: &mut crate::tui::Tui| -> Result { + crate::terminal_palette::with_test_default_colors( + crate::terminal_probe::DefaultColors { + fg: (220, 220, 220), + bg: (20, 20, 20), + }, + || { + side_frame(app, tui, size)?; + let buffer = tui.terminal.previous_buffer(); + let divider = 62; + let row = (0..size.height) + .find(|&y| buffer[(divider + 2, y)].symbol() == "›") + .expect("right composer prompt"); + let snapshot_row = |y| { + (divider..=divider + 2) + .map(|x| { + let cell = &buffer[(x, y)]; + format!("{:?} {:?}", cell.symbol(), cell.bg) + }) + .collect::>() + .join(" | ") + }; + Ok(format!( + "{}\n{}", + snapshot_row(row), + snapshot_row(size.height - 1) + )) + }, + ) + }; + let inactive = composer_gutter(&mut app, &mut tui)?; + + let toggle = KeyEvent::new(KeyCode::Char('/'), KeyModifiers::CONTROL); + boxed_future!(app.handle_tui_event(&mut tui, &mut app_server, TuiEvent::Key(toggle))).await?; + drain_app_events(&mut app, &mut tui, &mut app_server, &mut app_event_rx).await?; + assert_eq!(app.current_displayed_thread_id(), Some(side_thread_id)); + let wide = side_frame(&mut app, &mut tui, size)?; + assert!( + wide.contains(parent_row) && wide.contains(child_row), + "{wide}" + ); + assert_eq!(tui.terminal.last_known_cursor_pos.x, 78); + let focused = composer_gutter(&mut app, &mut tui)?; + assert_app_snapshot!( + "side_composer_gutter", + format!("Inactive\n{inactive}\n\nFocused\n{focused}") + ); + + read_side_history(&mut app, &mut tui, "child")?; + // The upload finishes before the app event loop can park the now-inactive child. + app.app_event_tx.send(AppEvent::FeedbackSubmitted { + origin_thread_id: Some(side_thread_id), + category: FeedbackCategory::Bug, + include_logs: false, + result: Ok("uploaded-thread".to_string()), + }); + app.select_agent_thread(&mut tui, &mut app_server, parent_thread_id) + .await?; + drain_app_events(&mut app, &mut tui, &mut app_server, &mut app_event_rx).await?; + app.select_agent_thread(&mut tui, &mut app_server, side_thread_id) + .await?; + drain_app_events(&mut app, &mut tui, &mut app_server, &mut app_event_rx).await?; + let frame = side_frame(&mut app, &mut tui, size)?; + assert!( + frame.contains(child_row) && frame.contains("New activity"), + "{frame}" + ); + assert!(app.transcript_cells.iter().any(|cell| { + lines_to_single_string(&cell.display_lines(/*width*/ 120)) + .contains("Feedback recorded (no logs).") + })); + + // A delta queued just before switching must appear once in the inactive pane. + app.transcript_view.jump_to_latest(); + app.enqueue_thread_notification( + side_thread_id, + turn_started_notification(side_thread_id, "live"), + ) + .await?; + app.enqueue_thread_notification( + side_thread_id, + agent_message_delta_notification(side_thread_id, "live", "reply", "unfinished answer"), + ) + .await?; + app.select_agent_thread(&mut tui, &mut app_server, parent_thread_id) + .await?; + drain_app_events(&mut app, &mut tui, &mut app_server, &mut app_event_rx).await?; + let frame = side_frame(&mut app, &mut tui, size)?; + assert_eq!(frame.matches("unfinished answer").count(), 1, "{frame}"); + app_server.shutdown().await?; Ok(()) } @@ -6625,6 +6907,7 @@ async fn make_test_app() -> Box { pending_server_profiles: HashMap::new(), agents_overview: Default::default(), side_threads: HashMap::new(), + side_companions: HashMap::new(), abandoned_side_threads: HashSet::new(), active_thread_id: None, active_thread_rx: None, @@ -6752,6 +7035,7 @@ pub(super) async fn make_test_app_with_channels() -> ( pending_server_profiles: HashMap::new(), agents_overview: Default::default(), side_threads: HashMap::new(), + side_companions: HashMap::new(), abandoned_side_threads: HashSet::new(), active_thread_id: None, active_thread_rx: None, diff --git a/codex-rs/tui/src/app/tests/pagination_completion_tests.rs b/codex-rs/tui/src/app/tests/pagination_completion_tests.rs index ec7d8b433e..da51551b40 100644 --- a/codex-rs/tui/src/app/tests/pagination_completion_tests.rs +++ b/codex-rs/tui/src/app/tests/pagination_completion_tests.rs @@ -122,6 +122,78 @@ pub(super) async fn completed_history_app( Ok((app, codex_home, thread_id)) } +#[tokio::test] +async fn side_replay_retries_an_older_find_page_discarded_while_inactive() -> Result<()> { + let (mut app, _codex_home, thread_id) = completed_history_app(&["Oldest", "Newest"]).await?; + let mut app_server = crate::start_embedded_app_server_for_picker(&app.config).await?; + let started = app_server + .resume_thread( + &app.local_settings, + app.config.clone(), + thread_id, + crate::app_server_session::ResumeModelSettings::RestoreFromThread, + ) + .await?; + let session = started.session; + app.enqueue_primary_thread_session(session.clone(), started.turns) + .await?; + let (event_tx, mut events) = tokio::sync::mpsc::unbounded_channel(); + app.app_event_tx = crate::app_event_sender::AppEventSender::new(event_tx); + let mut tui = crate::tui::test_support::make_test_tui()?; + enable_side_retention(&mut app)?; + tui.set_owned_screen(/*owned*/ true)?; + + app.scrollback_has_older_history = app_server.has_older_history(thread_id); + app.transcript_cells = vec![plain_line_cell("Newest answer")]; + app.transcript_view.history = TranscriptHistoryState::Partial; + app.transcript_view.begin_search(); + app.transcript_view.paste_search("Oldest answer"); + while app.transcript_view.advance_search(&app.transcript_cells) {} + app.request_owned_history(&mut tui, &mut app_server); + let page = tokio::time::timeout(Duration::from_secs(/*secs*/ 5), events.recv()) + .await? + .expect("first page requested by Find"); + + let child = ThreadId::new(); + app.side_threads + .insert(child, SideThreadState::new(thread_id)); + let (stream, display) = app.chat_widget.take_side_display(/*width*/ 100); + boxed_future!(app.handle_event( + &mut tui, + &mut app_server, + AppEvent::ParkSideCompanion { + pair: child, + thread_id, + stream, + display + }, + )) + .await?; + app.chat_widget + .handle_side_thread_session(test_thread_session(child, app.config.cwd.to_path_buf())); + boxed_future!(app.handle_event(&mut tui, &mut app_server, page)).await?; + + app.chat_widget.handle_thread_session(session); + app.transcript_cells = vec![plain_line_cell("Newest answer")]; + app.pending_thread_switch_resets = 1; + boxed_future!(app.handle_event( + &mut tui, + &mut app_server, + AppEvent::SideReplayFinished(thread_id) + )) + .await?; + app.request_owned_history(&mut tui, &mut app_server); + let retry = tokio::time::timeout(Duration::from_secs(/*secs*/ 5), events.recv()) + .await? + .expect("page retried by Find"); + boxed_future!(app.handle_event(&mut tui, &mut app_server, retry)).await?; + + let frame = side_frame(&mut app, &mut tui, Size::new(/*width*/ 100, /*height*/ 16))?; + assert!(frame.contains("Oldest answer"), "{frame}"); + app_server.shutdown().await?; + Ok(()) +} + #[tokio::test] async fn older_pagination_completion_footers_follow_answers_without_overlap_duplicates() -> Result<()> { diff --git a/codex-rs/tui/src/app/tests/startup.rs b/codex-rs/tui/src/app/tests/startup.rs index 316ae0e850..90a89fba54 100644 --- a/codex-rs/tui/src/app/tests/startup.rs +++ b/codex-rs/tui/src/app/tests/startup.rs @@ -909,6 +909,11 @@ async fn unattended_modals_survive_unfinished_terminal_input() -> Result<()> { ); } + let snapshot = app.thread_event_channels[&thread_id] + .store + .lock() + .await + .snapshot(); // After the drain has settled a fresh explicit decision works normally. app.handle_tui_event( &mut tui, @@ -918,6 +923,40 @@ async fn unattended_modals_survive_unfinished_terminal_input() -> Result<()> { .await?; assert!(!app.chat_widget.has_active_modal()); + // Replay the cached request with the startup boundary already ended. + while app_event_rx.try_recv().is_ok() {} + app.startup_protected_input_boundary = false; + app.config.features.enable(Feature::TuiWorkspace)?; + app.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Owned; + tui.set_owned_screen(/*owned*/ true)?; + crossterm::event::buffer_input(b"\rya")?; + app.render_thread_snapshot( + &mut tui, + &app_server, + thread_id, + snapshot, + /*resume_restored_queue*/ false, + )?; + assert!(app.chat_widget.has_active_modal()); + let before = tui.terminal.previous_buffer().clone(); + let cursor = tui.terminal.last_known_cursor_pos; + loop { + app.render_startup_frame(&mut tui, &app_event_rx)?; + assert_eq!(tui.terminal.previous_buffer(), &before); + assert_eq!(tui.terminal.last_known_cursor_pos, cursor); + let event = app_event_rx.try_recv()?; + let finished = matches!(event, AppEvent::SideReplayFinished(id) if id == thread_id); + boxed_future!(app.handle_event(&mut tui, &mut app_server, event)).await?; + if finished { + break; + } + } + assert!(crossterm::event::poll(std::time::Duration::ZERO)?); + app.render_startup_frame(&mut tui, &app_event_rx)?; + assert!(buffer_text(tui.terminal.previous_buffer()).contains("echo hello")); + assert!(!crossterm::event::poll(std::time::Duration::ZERO)?); + tui.set_owned_screen(/*owned*/ false)?; + // Overview can open before the first real input, and survives a server reconnect. let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await; app.startup_protected_input_boundary = true; diff --git a/codex-rs/tui/src/app/thread_events.rs b/codex-rs/tui/src/app/thread_events.rs index bddbd7719e..043abe6a7d 100644 --- a/codex-rs/tui/src/app/thread_events.rs +++ b/codex-rs/tui/src/app/thread_events.rs @@ -80,6 +80,8 @@ pub(super) struct ThreadEventStore { pub(super) input_state: Option, pub(super) capacity: usize, pub(super) active: bool, + /// Output received since deactivation can change the transcript rebuilt on replay. + pub(super) replay_may_have_output: bool, pub(super) buffered_agent_message_delta_bytes: usize, delegated_turns: VecDeque, recap_progress: recap::RecapProgress, @@ -125,6 +127,7 @@ impl ThreadEventStore { input_state: None, capacity, active: false, + replay_may_have_output: false, buffered_agent_message_delta_bytes: 0, delegated_turns: VecDeque::new(), recap_progress: recap::RecapProgress::default(), diff --git a/codex-rs/tui/src/app/thread_routing.rs b/codex-rs/tui/src/app/thread_routing.rs index b824a9f528..0cddd71fa7 100644 --- a/codex-rs/tui/src/app/thread_routing.rs +++ b/codex-rs/tui/src/app/thread_routing.rs @@ -128,6 +128,9 @@ impl App { 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; + } store.active = false; store.input_state = input_state; store.merge_recap_progress(recap_progress); @@ -1194,6 +1197,28 @@ impl App { { self.retain_inactive_realtime_transcript(thread_id, ¬ification); } + // Status traffic alone does not change the displayed transcript. + guard.replay_may_have_output |= !matches!( + ¬ification, + ServerNotification::ThreadStarted(_) + | ServerNotification::ThreadStatusChanged(_) + | ServerNotification::ThreadReadStateChanged(_) + | ServerNotification::ThreadTokenUsageUpdated(_) + | ServerNotification::ThreadNameUpdated(_) + | ServerNotification::ThreadProjectUpdated(_) + | ServerNotification::ThreadQueueChanged(_) + | ServerNotification::ThreadPredictionUpdated(_) + | ServerNotification::ThreadAttachmentUpdated(_) + | ServerNotification::ThreadSettingsUpdated(_) + | ServerNotification::McpToolCallProgress(_) + | ServerNotification::FileChangePatchUpdated(_) + | ServerNotification::ServerRequestResolved(_) + | ServerNotification::ThreadRealtimeOutputAudioDelta(_) + | ServerNotification::ThreadRealtimeSdp(_) + | ServerNotification::ThreadRealtimeItemAdded(_) + | ServerNotification::RawResponseItemCompleted(_) + | ServerNotification::RawResponseCompleted(_) + ); guard.push_notification(notification); None }; @@ -1657,6 +1682,7 @@ impl App { let AppServerStartedThread { session, turns, .. } = started; if let Some(channel) = self.thread_event_channels.get(&thread_id) { let mut store = channel.store.lock().await; + store.replay_may_have_output |= snapshot.turns != turns; store.set_session(session.clone(), turns.clone()); store.rebase_buffer_after_session_refresh(); snapshot.active_reasoning_item = store.active_reasoning_item.clone(); diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 9c848858c6..bd7eb5ed0c 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -293,6 +293,22 @@ pub(crate) struct AgentPickerThreadRefresh { pub(crate) archived_thread_ids: std::collections::HashSet, } +/// Source-backed replacement for the outgoing widget's width-bound streaming rows. +#[derive(Debug)] +pub(crate) enum CapturedSideStream { + Answer(Arc), + Plan(Arc), +} + +/// Presentation retained alongside the transcript while its composer is inactive. +#[derive(Debug)] +pub(crate) struct CapturedSideDisplay { + pub(crate) active: Option>, + pub(crate) auxiliary: Vec, + pub(crate) draft: String, + pub(crate) status: Option, +} + #[allow(clippy::large_enum_variant)] #[derive(Debug, IntoStaticStr)] pub(crate) enum AppEvent { @@ -629,6 +645,17 @@ pub(crate) enum AppEvent { name: Option, }, + /// Move the outgoing transcript once its previously queued history edits have run. + ParkSideCompanion { + pair: ThreadId, + thread_id: ThreadId, + stream: Option, + display: CapturedSideDisplay, + }, + + /// Release input and drawing after the destination snapshot's queued history edits. + SideReplayFinished(ThreadId), + /// Clear history queued by the previous thread before the new thread's replay events. ResetTranscriptForThreadSwitch, /// Reset queued history while keeping the startup draft visible until the next frame. @@ -1171,6 +1198,14 @@ pub(crate) enum AppEvent { result: Result, }, + /// Result of the skills refresh issued while replaying a docked conversation. + SideReplaySkillsLoaded { + request_id: Uuid, + thread_id: ThreadId, + cwd: PathBuf, + result: Result, + }, + /// Begin buffering initial resume replay rows before they are written to scrollback. BeginInitialHistoryReplayBuffer, diff --git a/codex-rs/tui/src/app_server_session.rs b/codex-rs/tui/src/app_server_session.rs index f6835199dd..78f5ab59f1 100644 --- a/codex-rs/tui/src/app_server_session.rs +++ b/codex-rs/tui/src/app_server_session.rs @@ -336,6 +336,8 @@ pub(crate) struct AppServerSession { request_id_namespace: Option, next_request_id: i64, automatic_name_writes: HashMap>, + /// The newest docked replay refresh on this connection. + pub(crate) pending_side_skills_refresh: Option, history_pagination: HashMap, pub(crate) focused_conversation: Option, pub(crate) attempted_revision: Option, @@ -542,6 +544,7 @@ impl AppServerSession { request_id_namespace: None, next_request_id: 1, automatic_name_writes: HashMap::new(), + pending_side_skills_refresh: None, history_pagination: HashMap::new(), focused_conversation: None, attempted_revision: None, @@ -1983,6 +1986,7 @@ impl AppServerSession { &mut self, params: SkillsListParams, ) -> Result { + self.pending_side_skills_refresh = None; let request_id = self.next_request_id(); self.request_handle .request_typed(ClientRequest::SkillsList { request_id, params }) diff --git a/codex-rs/tui/src/app_server_session/history.rs b/codex-rs/tui/src/app_server_session/history.rs index afeda6664d..ab0382b04e 100644 --- a/codex-rs/tui/src/app_server_session/history.rs +++ b/codex-rs/tui/src/app_server_session/history.rs @@ -190,9 +190,14 @@ impl AppServerSession { /// Match a completion to the page still pending for this thread, before interpreting its result. pub(crate) fn is_older_history_page_pending(&self, thread_id: ThreadId, cursor: &str) -> bool { - self.history_pagination.get(&thread_id).is_some_and(|page| { - page.loading_older && page.next_item_cursor.as_deref() == Some(cursor) - }) + self.pending_older_history_cursor(thread_id) == Some(cursor) + } + + pub(crate) fn pending_older_history_cursor(&self, thread_id: ThreadId) -> Option<&str> { + self.history_pagination + .get(&thread_id) + .filter(|page| page.loading_older) + .and_then(|page| page.next_item_cursor.as_deref()) } pub(crate) fn cancel_older_history_page(&mut self, thread_id: ThreadId, cursor: &str) { diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index bcc24561d8..3d90f8d33e 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -1881,7 +1881,6 @@ impl ChatComposer { self.attachments.local_image_paths() } - #[cfg(test)] pub(crate) fn status_line_content(&self) -> Option<&FooterContent> { self.footer.status_line_value.as_ref() } @@ -4933,7 +4932,8 @@ impl ChatComposer { selection.register(footer_rect.intersection(buf.area), changed); } let style = user_message_style(); - Block::default().style(style).render(composer_rect, buf); + let background = composer_layout::background_rect(composer_rect, buf.area, options); + Block::default().style(style).render(background, buf); if let Some(previews) = options.image_previews { previews.render( thumbnails, diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/composer_layout.rs b/codex-rs/tui/src/bottom_pane/chat_composer/composer_layout.rs index d687ed06a8..a5199f78dd 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/composer_layout.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/composer_layout.rs @@ -8,6 +8,19 @@ use crate::tui::FrameRequester; use ratatui::buffer::Buffer; use ratatui::layout::Rect; +pub(super) fn background_rect( + composer: Rect, + buffer: Rect, + options: ComposerRenderOptions<'_>, +) -> Rect { + let gutter = u16::from(options.extend_composer_background_left && composer.x > buffer.x); + Rect { + x: composer.x - gutter, + width: composer.width + gutter, + ..composer + } +} + impl ChatComposer { pub(crate) fn set_voice_strip( &mut self, diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/footer_state.rs b/codex-rs/tui/src/bottom_pane/chat_composer/footer_state.rs index 85ba7e945e..3d74ce3fa2 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/footer_state.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/footer_state.rs @@ -72,6 +72,8 @@ pub(crate) enum CommandPopupPlacement { pub(crate) struct ComposerRenderOptions<'a> { /// Fullscreen limits the composer independently of activity and modal views. pub(crate) max_height: Option, + /// Fill the empty cell next to the right pane's divider without moving the input. + pub(crate) extend_composer_background_left: bool, pub(crate) image_previews: Option<&'a crate::transcript_image::composer::ComposerImages>, pub(crate) rendered_selection: Option<&'a std::cell::RefCell>, diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index c5b0df8a74..7891b5eb0c 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -1376,7 +1376,6 @@ impl BottomPane { self.status_widget().is_some() } - #[cfg(test)] pub(crate) fn status_line_content(&self) -> Option<&footer_content::FooterContent> { self.composer.status_line_content() } diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index fd868b357f..4af0c2278e 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -2085,14 +2085,12 @@ impl ChatWidget { &self.config } - #[cfg(test)] pub(crate) fn status_line_text(&self) -> Option { self.status_line_content() .cloned() .map(|content| content.into_hyperlink_line().line.to_string()) } - #[cfg(test)] pub(crate) fn status_line_content( &self, ) -> Option<&crate::bottom_pane::footer_content::FooterContent> { diff --git a/codex-rs/tui/src/chatwidget/input_restore.rs b/codex-rs/tui/src/chatwidget/input_restore.rs index 559a851d0d..cf5086aabc 100644 --- a/codex-rs/tui/src/chatwidget/input_restore.rs +++ b/codex-rs/tui/src/chatwidget/input_restore.rs @@ -606,7 +606,7 @@ impl ChatWidget { pub(crate) fn capture_thread_input_state(&mut self) -> Option { self.cancel_image_submission(); - let draft = self.bottom_pane.composer_draft_snapshot(); + let draft = self.bottom_pane.composer_recovery_snapshot(); let composer = ThreadComposerState { text: draft.text, text_elements: draft.text_elements, diff --git a/codex-rs/tui/src/chatwidget/streaming.rs b/codex-rs/tui/src/chatwidget/streaming.rs index 6229fd735a..acbd7defc8 100644 --- a/codex-rs/tui/src/chatwidget/streaming.rs +++ b/codex-rs/tui/src/chatwidget/streaming.rs @@ -4,6 +4,8 @@ //! cells, commit ticks, and interrupt deferral. use super::*; +use crate::app_event::CapturedSideDisplay; +use crate::app_event::CapturedSideStream; use crate::markdown_render::ListSpacing; fn streamed_message_matches_completed(streamed: &str, completed: &str) -> bool { @@ -202,6 +204,71 @@ impl ChatWidget { self.status_state.pending_status_indicator_restore = false; } + /// Capture at handoff, while links and visualization directives still have the outgoing cwd. + pub(crate) fn take_side_display( + &mut self, + width: u16, + ) -> (Option, CapturedSideDisplay) { + self.flush_completed_tool_activity(); + let stream = if let Some(controller) = &self.stream_controller { + let source = controller.source_snapshot(); + let markdown = parse_assistant_markdown(&source, self.config.cwd.as_path()); + let context = self.thread_id.and_then(|id| { + crate::inline_visualization::InlineVisualizationContext::from_config( + &self.config, + id, + ) + }); + let cell = history_cell::AgentMarkdownCell::new_with_inline_visualizations( + markdown.visible_markdown, + &self.config.cwd, + context, + ) + .with_copy_source(Some(source)); + Some(CapturedSideStream::Answer(Arc::new(cell))) + } else if self.plan_stream_controller.is_some() { + Some(CapturedSideStream::Plan(Arc::new( + history_cell::new_proposed_plan( + self.transcript.plan_delta_buffer.clone(), + &self.config.cwd, + ), + ))) + } else { + None + }; + let active = self + .transcript + .take_active_cell() + .filter(|cell| match &stream { + Some(CapturedSideStream::Answer(_)) => { + !cell.as_any().is::() + } + Some(CapturedSideStream::Plan(_)) => { + !cell.as_any().is::() + } + None => true, + }); + let display = CapturedSideDisplay { + active, + auxiliary: self + .active_cell_transcript_hyperlink_lines(width) + .unwrap_or_default(), + draft: if self.bottom_pane.is_in_paste_burst() { + let draft = self.bottom_pane.composer_recovery_snapshot(); + crate::bottom_pane::ChatComposer::expand_pending_pastes( + &draft.text, + draft.text_elements, + &draft.pending_pastes, + ) + .0 + } else { + self.composer_text_with_pending() + }, + status: self.status_line_text(), + }; + (stream, display) + } + fn completed_agent_message_was_flushed(&self, message: &str) -> bool { self.transcript .last_completed_agent_message @@ -537,11 +604,10 @@ impl ChatWidget { /// Runs a commit tick for the current stream queue snapshot. /// - /// `scope` controls whether this call may commit in smooth mode or only when catch-up - /// is currently active. While lines are actively streaming we hide the status row to avoid - /// duplicate "in progress" affordances. Restoration is gated separately so we only re-show + /// `scope` selects paced, catch-up, or replay draining. While lines are actively streaming + /// we hide the status row to avoid duplicate "in progress" affordances. We only re-show /// the row after commentary completion once stream queues are idle. - pub(super) fn run_commit_tick_with_scope(&mut self, scope: CommitTickScope) { + pub(crate) fn run_commit_tick_with_scope(&mut self, scope: CommitTickScope) { let now = Instant::now(); let outcome = run_commit_tick( &mut self.adaptive_chunking, diff --git a/codex-rs/tui/src/snapshots/codex_tui__app__tests__side_composer_gutter.snap b/codex-rs/tui/src/snapshots/codex_tui__app__tests__side_composer_gutter.snap new file mode 100644 index 0000000000..9b2ccd7e69 --- /dev/null +++ b/codex-rs/tui/src/snapshots/codex_tui__app__tests__side_composer_gutter.snap @@ -0,0 +1,11 @@ +--- +source: tui/src/app/tests.rs +expression: "format!(\"Inactive\\n{inactive}\\n\\nFocused\\n{focused}\")" +--- +Inactive +"│" Reset | " " Rgb(31, 31, 31) | "›" Rgb(31, 31, 31) +"│" Reset | " " Reset | " " Reset + +Focused +"│" Reset | " " Rgb(48, 48, 48) | "›" Rgb(48, 48, 48) +"│" Reset | " " Reset | " " Reset diff --git a/codex-rs/tui/src/snapshots/codex_tui__app__tests__single_side_chat.snap b/codex-rs/tui/src/snapshots/codex_tui__app__tests__single_side_chat.snap new file mode 100644 index 0000000000..13997c1f74 --- /dev/null +++ b/codex-rs/tui/src/snapshots/codex_tui__app__tests__single_side_chat.snap @@ -0,0 +1,21 @@ +--- +source: tui/src/app/tests.rs +expression: panel +--- +parent-24 │ child-24 + │ +parent-25 │ child-25 + │ +parent-26 │ child-26 + │ +parent-27 │ child-27 + │ +parent-28 │ child-28 + │ +parent-29 │ child-29 + │ + New activity · ↓ Back to bottom · esc │ + │ +› parent draft │ › child draft! + │ + GPT-6.1-Sol default · /tmp/project · Main [default] │ GPT-6.1-Sol default · /tmp/project diff --git a/codex-rs/tui/src/streaming/commit_tick.rs b/codex-rs/tui/src/streaming/commit_tick.rs index 6c287ff9c3..7d46dcb0ff 100644 --- a/codex-rs/tui/src/streaming/commit_tick.rs +++ b/codex-rs/tui/src/streaming/commit_tick.rs @@ -26,13 +26,15 @@ use super::chunking::QueueSnapshot; use super::controller::PlanStreamController; use super::controller::StreamController; -/// Describes whether a commit tick may run in all modes or only in catch-up mode. +/// Selects how a commit tick drains queued stable lines. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum CommitTickScope { /// Always run the tick, regardless of current chunking mode. AnyMode, /// Run model transitions and policy updates, but commit lines only in `CatchUp`. CatchUpOnly, + /// Commit all stable replay lines before restoring the reader, leaving the live tail open. + Replay, } /// Describes what a single commit tick produced. @@ -78,6 +80,13 @@ pub(crate) fn run_commit_tick( plan_stream_controller.as_deref(), now, ); + if scope == CommitTickScope::Replay { + return apply_commit_tick_plan( + DrainPlan::Batch(snapshot.queued_lines), + stream_controller, + plan_stream_controller, + ); + } let decision = resolve_chunking_plan(policy, snapshot, now); if scope == CommitTickScope::CatchUpOnly && decision.mode != ChunkingMode::CatchUp { return CommitTickOutput::default(); diff --git a/codex-rs/tui/src/streaming/controller.rs b/codex-rs/tui/src/streaming/controller.rs index 8937b4c096..39f10f7c68 100644 --- a/codex-rs/tui/src/streaming/controller.rs +++ b/codex-rs/tui/src/streaming/controller.rs @@ -684,6 +684,16 @@ impl StreamController { self.core.has_tail() } + /// Include the unterminated line when handing an in-flight answer to another view. + pub(crate) fn source_snapshot(&self) -> String { + let collector = &self.core.state.collector; + format!( + "{}{}", + collector.committed_source(), + collector.pending_source() + ) + } + /// Completion must repair emitted rows when reference definitions can change earlier blocks. pub(crate) fn needs_scrollback_reflow(&self) -> bool { if self.has_live_tail() || self.core.render.has_reference_link_definition { @@ -694,11 +704,7 @@ impl StreamController { { return false; } - let source = format!( - "{}{}", - self.core.state.collector.committed_source(), - self.core.state.collector.pending_source(), - ); + let source = self.source_snapshot(); pulldown_cmark::Parser::new(&source) .reference_definitions() .iter() diff --git a/codex-rs/tui/src/style.rs b/codex-rs/tui/src/style.rs index bf54571c59..dab0e03dce 100644 --- a/codex-rs/tui/src/style.rs +++ b/codex-rs/tui/src/style.rs @@ -177,6 +177,17 @@ pub(crate) fn secondary_text_style() -> Style { .not_bold() } +/// Bring a focusable surface closer to the terminal background while keeping its text readable. +pub(crate) fn quiet_workspace_style() -> Style { + let base = Style::default().not_bold().not_reversed().not_underlined(); + let Some(bg) = default_bg() else { + return base.fg(Color::Reset).bg(Color::Reset).dim(); + }; + let fill = best_color(blend(user_message_bg_rgb(bg), bg, 0.40)); + let foreground = default_fg().map_or(Color::Reset, |fg| best_color(blend(fg, bg, 0.66))); + base.bg(fill).fg(readable_color_on(foreground, Some(fill))) +} + pub(crate) fn selection_style() -> Style { contrast::selection_style(default_bg(), effective_stdout_color_level()) } diff --git a/codex-rs/tui/src/transcript_view.rs b/codex-rs/tui/src/transcript_view.rs index 9911b8c439..226ef9a7e3 100644 --- a/codex-rs/tui/src/transcript_view.rs +++ b/codex-rs/tui/src/transcript_view.rs @@ -342,6 +342,63 @@ impl TranscriptView { placements } + /// Reflow the captured live owner without treating a passive paint as reading new output. + pub(crate) fn render_parked( + &mut self, + area: Rect, + buffer: &mut Buffer, + cells: &[Arc], + active: Option<&dyn HistoryCell>, + auxiliary: &[HyperlinkLine], + ) { + let width = area.width; + let unseen_activity = self.unseen_activity; + let ids = active.map_or_else(Vec::new, HistoryCell::activity_ids); + let disclose = !ids.is_empty() && self.mode == HistoryRenderMode::Rich; + let expanded = self.sync_live_activity(cells, ids); + let mode = self.mode; + let lines = |width| { + let mut lines = active.map_or_else(Vec::new, |c| c.transcript_hyperlink_lines(width)); + if !lines.is_empty() && !auxiliary.is_empty() { + lines.push("".into()); + } + lines.extend_from_slice(auxiliary); + (!lines.is_empty()).then_some(lines) + }; + self.sync_search_live_tail(width, None, lines); + if self.detailed { + self.sync_live_tail(width, None, lines); + } else { + self.sync_live_activity_tail(width, None, expanded && disclose, |width| { + let activity = active.map_or_else(Vec::new, |cell| { + if disclose && expanded { + cell.expanded_hyperlink_lines(width) + } else { + crate::history_cell::fullscreen_session_lines( + cell, width, /*detailed*/ false, mode, + ) + } + }); + let mut auxiliary = auxiliary.to_vec(); + if activity.is_empty() && auxiliary.is_empty() { + return None; + } + if !activity.is_empty() && !auxiliary.is_empty() { + auxiliary.insert(0, "".into()); + } + Some(ActivityTranscriptLines { + activity, + auxiliary, + disclosure: active + .filter(|_| disclose) + .and_then(|cell| cell.activity_disclosure(width)), + }) + }); + } + self.render(area, buffer, cells); + self.unseen_activity = unseen_activity; + } + pub(crate) fn sync_live_tail( &mut self, width: u16, diff --git a/codex-rs/tui/src/transcript_view/mutations.rs b/codex-rs/tui/src/transcript_view/mutations.rs index 97707d05a6..621a93acab 100644 --- a/codex-rs/tui/src/transcript_view/mutations.rs +++ b/codex-rs/tui/src/transcript_view/mutations.rs @@ -3,6 +3,7 @@ use std::ops::Range; use super::*; +use crate::history_cell::is_session_history_prefix_cell; impl TranscriptView { /// Rebuild the layout of an observed revision without counting the reflow as new output. @@ -183,9 +184,12 @@ impl TranscriptView { &mut self, cells: &[Arc], inserted: Range, - ) { + ) -> Range { + if inserted.is_empty() { + return inserted; + } let Some(snapshot) = self.snapshot_mut() else { - return; + return inserted; }; let existing = snapshot .cells @@ -198,21 +202,22 @@ impl TranscriptView { .cloned() .collect::>(); if older.is_empty() { - return; + return 0..0; } - let index = cells[..inserted.start] + let preceding = &cells[..inserted.start]; + let index = snapshot + .cells .iter() - .rev() - .find_map(|cell| { - snapshot - .cells - .iter() - .position(|retained| Arc::ptr_eq(retained, cell)) + .rposition(|retained| { + is_session_history_prefix_cell(retained.as_ref()) + || preceding.iter().any(|cell| Arc::ptr_eq(retained, cell)) }) .map_or(/*default*/ 0, |index| index + 1); + let retained = index..index + older.len(); let mut extended = snapshot.cells.to_vec(); extended.splice(index..index, older); snapshot.cells = extended.into(); + retained } } diff --git a/codex-rs/tui/src/transcript_view/search.rs b/codex-rs/tui/src/transcript_view/search.rs index 7511992c39..77ffcb1260 100644 --- a/codex-rs/tui/src/transcript_view/search.rs +++ b/codex-rs/tui/src/transcript_view/search.rs @@ -598,7 +598,7 @@ impl TranscriptView { { self.last_tail = cells.last().map(EntryKey::cell); } - self.prepend_snapshot_history(cells, inserted.clone()); + let inserted = self.prepend_snapshot_history(cells, inserted); if let Position::Reading(anchor) = self.position { let index = self.resolve(cells, anchor); self.position = Position::Reading(Anchor { diff --git a/codex-rs/tui/src/transcript_view/search_tests.rs b/codex-rs/tui/src/transcript_view/search_tests.rs index 8308ca55c1..079581c690 100644 --- a/codex-rs/tui/src/transcript_view/search_tests.rs +++ b/codex-rs/tui/src/transcript_view/search_tests.rs @@ -918,6 +918,52 @@ fn search_scans_a_page_inserted_after_the_retained_session_header() { assert!(Arc::ptr_eq(&cells[0], &header)); } +#[test] +fn search_finds_the_first_older_entry_after_replaying_the_session_header() { + let header = || -> Arc { + Arc::new(crate::history_cell::SessionHeaderHistoryCell::new( + "test model".to_string(), + /*reasoning_effort*/ None, + std::path::PathBuf::from("/project"), + "test", + )) + }; + let parked = vec![header(), cell("recent needle")]; + let mut view = TranscriptView { + history: TranscriptHistoryState::Partial, + ..TranscriptView::default() + }; + view.begin_search(); + view.paste_search("needle"); + finish_scan(&mut view, &parked); + view.handle_key(KeyCode::Enter.into(), &parked); + + let mut replayed = vec![header(), cell("recent needle")]; + view.restore_after_replay( + &parked, &replayed, /*replay_may_have_output*/ false, /*replayed_live*/ None, + ); + view.handle_key( + KeyEvent::new(KeyCode::Char('p'), KeyModifiers::CONTROL), + &replayed, + ); + finish_scan(&mut view, &replayed); + assert!(view.needs_history(&replayed)); + + let oldest = cell("oldest needle"); + replayed.splice(1..1, [Arc::clone(&oldest), cell("older messages")]); + view.history = TranscriptHistoryState::Complete; + view.history_loaded(&replayed, 1..3); + assert!(Arc::ptr_eq( + &view.snapshot().expect("held reading").cells[0], + &parked[0] + )); + finish_scan(&mut view, &replayed); + assert_eq!( + view.search.current.as_ref().map(|found| found.anchor.key), + Some(EntryKey::cell(&oldest)), + ); +} + #[test] fn next_previous_highlight_and_cancel_share_the_transcript_position() { let cells = vec![cell("Needle one"), cell("Needle two")]; diff --git a/codex-rs/tui/src/transcript_view/snapshot.rs b/codex-rs/tui/src/transcript_view/snapshot.rs index 5073db24a9..90aa45d4de 100644 --- a/codex-rs/tui/src/transcript_view/snapshot.rs +++ b/codex-rs/tui/src/transcript_view/snapshot.rs @@ -1,4 +1,4 @@ -//! Retain displayed revisions while selecting or reading a live tail or a replaced tool group. +//! Retain displayed revisions while selecting or reading across live updates and history replay. //! Pinned layouts respect manual disclosures; Find's expansion is applied only at display time. use std::collections::HashMap; @@ -81,6 +81,27 @@ impl TranscriptView { } } + /// Keep the parked reading revision and rebind a quiet tail to its replayed identity. + pub(crate) fn restore_after_replay( + &mut self, + parked: &[Arc], + replayed: &[Arc], + replay_may_have_output: bool, + replayed_live: Option, + ) { + if matches!(self.position, Position::Reading(_)) && self.snapshot().is_none() { + self.held_reading = Some(self.capture_snapshot(parked)); + } + if !replay_may_have_output { + self.last_tail = replayed.last().map(EntryKey::cell); + // The parked display and replayed widget may represent the same stream differently. + self.live_key = replayed_live.map(|mut key| { + key.cacheable = false; + (self.area.width, key) + }); + } + } + /// Keep a live, mutable, or replaced cell revision while reading inside it. Navigation /// rejoins current history when it reaches a surviving cell. pub(super) fn hold_live_reading(