Files
codex/codex-rs/tui/src/unarchive_prompt.rs
T
Eric Traut d7d9f2b9b5 Add selection and copying to the transcript viewer (#46732)
## What changed

- Add mouse selection, word and line selection, drag autoscrolling, and keyboard selection with `Ctrl+Space`. Support copying selected text and opening links with a modified click.
- Anchor reading positions and selections to source text so resizing, streaming completion, and history pagination preserve the displayed content. Preserve hard line breaks, indentation, tabs, and graphemes when copying, while excluding display gutters and soft wraps.
- Rejoin activity groups split across history pages while retaining the reader's displayed revision.
- Distinguish confirmed clipboard writes from unconfirmed terminal requests, and retain native clipboard ownership after the transcript overlay closes.
- Manage mouse capture and keyboard modes across overlay transitions, editor handoffs, and suspend/resume.

## Testing

Add regression tests for selection during live updates and pagination, source-text copying across resize, clipboard confirmation and lifetime, and terminal mode restoration.

GitOrigin-RevId: 6b2438f576567cbba755b2405915a25acf009b8d
2026-09-20 00:04:04 +00:00

228 lines
7.1 KiB
Rust

//! Archived-session recovery with shared picker rows and scoped terminal ownership.
use crate::bottom_pane::picker_option_list;
use crate::bottom_pane::render_menu_surface;
use crate::key_hint;
use crate::render::Insets;
use crate::render::renderable::FlexRenderable;
use crate::render::renderable::Renderable;
use crate::render::renderable::RenderableExt as _;
use crate::render::renderable::RenderableItem;
use crate::session_start::SessionStartAction;
use crate::tui::Tui;
use crate::tui::TuiEvent;
use codex_protocol::ThreadId;
use color_eyre::Result;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use crossterm::event::KeyModifiers;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Stylize as _;
use ratatui::text::Line;
use ratatui::widgets::Clear;
use ratatui::widgets::Paragraph;
use ratatui::widgets::Widget;
use ratatui::widgets::WidgetRef;
use ratatui::widgets::Wrap;
use tokio_stream::StreamExt;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum UnarchiveChoice {
Unarchive,
Cancel,
Quit,
}
pub(crate) async fn run_unarchive_prompt(
tui: &mut Tui,
thread_id: ThreadId,
action: SessionStartAction,
) -> Result<UnarchiveChoice> {
let mut guard = PromptScreenGuard::enter(tui)?;
let mut screen = UnarchivePrompt::new(thread_id, action);
guard.draw(&screen)?;
guard
.tui
.discard_pending_input_before_interactive_screen()?;
let events = guard.tui.event_stream();
tokio::pin!(events);
guard.draw(&screen)?;
loop {
let Some(event) = events.next().await else {
return Ok(UnarchiveChoice::Quit);
};
guard.tui.screen_size_for_event(&event)?;
match event {
TuiEvent::Key(key) => {
if let Some(choice) = screen.handle_key(key) {
return Ok(choice);
}
}
TuiEvent::Paste(_)
| TuiEvent::Draw
| TuiEvent::Resize(_)
| TuiEvent::Resume
| TuiEvent::FocusGained => {}
TuiEvent::Mouse(_) | TuiEvent::FocusLost => continue,
}
guard.draw(&screen)?;
}
}
/// Keep startup prompts out of normal scrollback when an alternate screen is available.
/// Inline mode owns only its content-height viewport, including when the terminal is resized.
struct PromptScreenGuard<'a> {
tui: &'a mut Tui,
entered_alt_screen: bool,
}
impl<'a> PromptScreenGuard<'a> {
fn enter(tui: &'a mut Tui) -> Result<Self> {
let was_alternate = tui.is_alt_screen_active();
if !was_alternate {
tui.enter_alt_screen()?;
}
let entered_alt_screen = !was_alternate && tui.is_alt_screen_active();
Ok(Self {
tui,
entered_alt_screen,
})
}
fn draw(&mut self, screen: &UnarchivePrompt) -> Result<()> {
let height = if self.tui.is_alt_screen_active() {
u16::MAX
} else {
screen
.content()
.desired_height(self.tui.terminal.size()?.width)
};
self.tui.draw(height, |frame| {
frame.render_widget_ref(screen, frame.area());
})?;
Ok(())
}
}
impl Drop for PromptScreenGuard<'_> {
fn drop(&mut self) {
let result = if self.entered_alt_screen {
self.tui.leave_alt_screen()
} else if !self.tui.is_alt_screen_active() {
let result = self.tui.terminal.clear();
let mut area = self.tui.terminal.viewport_area;
area.height = 0;
self.tui.terminal.set_viewport_area(area);
result
} else {
Ok(())
};
if let Err(err) = result {
tracing::warn!("failed to restore terminal after unarchive prompt: {err}");
}
}
}
struct UnarchivePrompt {
thread_id: ThreadId,
action: SessionStartAction,
highlighted: UnarchiveChoice,
}
impl UnarchivePrompt {
fn new(thread_id: ThreadId, action: SessionStartAction) -> Self {
Self {
thread_id,
action,
highlighted: UnarchiveChoice::Unarchive,
}
}
fn handle_key(&mut self, key: KeyEvent) -> Option<UnarchiveChoice> {
if key.kind == KeyEventKind::Release {
return None;
}
if key.modifiers.contains(KeyModifiers::CONTROL)
&& matches!(key.code, KeyCode::Char('c') | KeyCode::Char('d'))
{
return Some(UnarchiveChoice::Quit);
}
match key.code {
KeyCode::Up | KeyCode::Down | KeyCode::Char('k' | 'j') => {
self.highlighted = match self.highlighted {
UnarchiveChoice::Unarchive => UnarchiveChoice::Cancel,
UnarchiveChoice::Cancel | UnarchiveChoice::Quit => UnarchiveChoice::Unarchive,
};
None
}
KeyCode::Char('1' | 'y' | 'Y') => Some(UnarchiveChoice::Unarchive),
KeyCode::Esc | KeyCode::Char('2' | 'n' | 'N') => Some(UnarchiveChoice::Cancel),
KeyCode::Enter => Some(self.highlighted),
_ => None,
}
}
fn content(&self) -> FlexRenderable<'static> {
let mut column = FlexRenderable::new();
column.push(/*flex*/ 1, RenderableItem::Borrowed(&""));
column.push(
/*flex*/ 0,
Paragraph::new("This conversation is archived".bold())
.wrap(Wrap { trim: false })
.inset(Insets::vh(/*v*/ 0, /*h*/ 2)),
);
column.push(
/*flex*/ 0,
Paragraph::new(Line::from(self.thread_id.to_string()).dim())
.wrap(Wrap { trim: false })
.inset(Insets::vh(/*v*/ 0, /*h*/ 2)),
);
let selected_index = match self.highlighted {
UnarchiveChoice::Unarchive => 0,
UnarchiveChoice::Cancel | UnarchiveChoice::Quit => 1,
};
column.push(
/*flex*/ 1,
picker_option_list(
vec![
format!("Unarchive and {}", self.action.verb()),
"Cancel".to_string(),
],
selected_index,
),
);
column.push(
/*flex*/ 0,
Paragraph::new(Line::from(vec![
key_hint::plain(KeyCode::Enter).into(),
" continue · ".dim(),
key_hint::plain(KeyCode::Esc).into(),
" cancel".dim(),
]))
.wrap(Wrap { trim: false })
.inset(Insets::vh(/*v*/ 0, /*h*/ 2)),
);
column.push(/*flex*/ 1, RenderableItem::Borrowed(&""));
column
}
}
impl WidgetRef for &UnarchivePrompt {
fn render_ref(&self, area: Rect, buf: &mut Buffer) {
Clear.render(area, buf);
let content = self.content();
let panel = Rect {
height: content.desired_height(area.width).min(area.height),
..area
};
render_menu_surface(panel, buf);
content.render(panel, buf);
}
}
#[cfg(test)]
#[path = "unarchive_prompt_tests.rs"]
mod tests;