Add keyboard copy selection to the owned transcript (#50434)

## What changed

- Make `/copy` select the latest completed response directly in the owned transcript. Navigate user messages, code blocks, and blockquotes with arrow keys or `j`/`k`, use `g`/`G` to jump to the ends, and press Enter to copy or Escape to close.
- Highlight selected blocks and keep surrounding context visible during navigation and resizing. Preserve source payloads for code and quotes, including rendered Mermaid diagrams and fenced Markdown tables.
- Pause queued submissions until copy mode closes, and report clipboard results in the transcript footer.

## Testing

Add tests for copy routing, keyboard navigation, highlighting and resize behavior, source whitespace and line endings, clipboard completion, and queued-input resumption.

GitOrigin-RevId: bd4f58ec17568f95d0e91014e5ddba33ca8bd57c
This commit is contained in:
Benjamin Carlsson
2026-10-02 21:42:23 +00:00
committed by copyberry
parent 66561d0301
commit c536ffcb18
38 changed files with 1712 additions and 65 deletions
@@ -8,7 +8,6 @@
//! resize re-renders. The retained view preserves its displayed revision before that
//! replacement, then repaints without replaying terminal scrollback.
use std::path::PathBuf;
use std::sync::Arc;
use color_eyre::eyre::Result;
@@ -18,7 +17,6 @@ use super::resize_reflow::trailing_run_start;
use crate::app_event::ConsolidationScrollbackReflow;
use crate::history_cell;
use crate::history_cell::HistoryCell;
use crate::inline_visualization::InlineVisualizationContext;
use crate::pager_overlay::Overlay;
use crate::tui;
@@ -26,9 +24,7 @@ impl App {
pub(super) fn handle_consolidate_agent_message(
&mut self,
tui: &mut tui::Tui,
source: String,
cwd: PathBuf,
inline_visualization_context: Option<InlineVisualizationContext>,
source: history_cell::AgentMarkdownCell,
scrollback_reflow: ConsolidationScrollbackReflow,
deferred_history_cell: Option<Box<dyn HistoryCell>>,
) -> Result<()> {
@@ -51,20 +47,14 @@ impl App {
let end = self.transcript_cells.len();
tracing::debug!(
"ConsolidateAgentMessage: transcript_cells.len()={end}, source_len={}",
source.len()
source.copy_source().map_or(/*default*/ 0, str::len)
);
let start = trailing_run_start::<history_cell::AgentMessageCell>(&self.transcript_cells);
if start < end {
tracing::debug!(
"ConsolidateAgentMessage: replacing cells [{start}..{end}] with AgentMarkdownCell"
);
let consolidated: Arc<dyn HistoryCell> = Arc::new(
history_cell::AgentMarkdownCell::new_with_inline_visualizations(
source,
&cwd,
inline_visualization_context,
),
);
let consolidated: Arc<dyn HistoryCell> = Arc::new(source);
self.native_history
.consolidate(&self.transcript_cells[start..end], &consolidated);
if tui.is_owned_screen() {
+15 -3
View File
@@ -56,6 +56,8 @@ impl App {
| AppEvent::CopyWarning(_)
| AppEvent::UpdateWarnings { .. }
| AppEvent::CopySelection { .. }
| AppEvent::SelectTranscriptCopy { .. }
| AppEvent::TranscriptCopyClosed
| AppEvent::ConfirmDaemonUpdate(_)
| AppEvent::RunDaemonUpdate(_)
| AppEvent::InsertHistoryCell(_)
@@ -391,6 +393,17 @@ impl App {
self.chat_widget.maybe_send_next_queued_input();
}
}
AppEvent::TranscriptCopyClosed => {
self.chat_widget.maybe_send_next_queued_input();
}
AppEvent::SelectTranscriptCopy { guard } => {
let size = tui.prepare_draw_size()?;
self.render_owned_transcript(tui, size)?;
if !self.transcript_view.begin_copy_mode(&self.transcript_cells, Some(guard)) {
self.chat_widget.add_info_message("Nothing to copy".into(), /*hint*/ None);
}
tui.frame_requester().schedule_frame();
}
AppEvent::CopySelection { text, label, format } => {
let result = tui.clipboard.copy(text, format, tui.frame_requester());
self.chat_widget.show_copy_result(&label, result);
@@ -879,6 +892,7 @@ impl App {
}
AppEvent::ConsolidateAgentMessage {
source,
copy_source,
cwd,
inline_visualization_context,
scrollback_reflow,
@@ -886,9 +900,7 @@ impl App {
} => {
self.handle_consolidate_agent_message(
tui,
source,
cwd,
inline_visualization_context,
history_cell::AgentMarkdownCell::new_with_inline_visualizations(source, &cwd, inline_visualization_context).with_copy_source(copy_source),
scrollback_reflow,
deferred_history_cell,
)?;
-2
View File
@@ -568,8 +568,6 @@ impl App {
&text,
!copy_on_select,
);
self.transcript_view
.show_copy_feedback(&result, text.chars().count());
if resume_following
&& matches!(result, Ok(crate::clipboard_copy::CopyStatus::Pending(_)))
{
@@ -178,9 +178,10 @@ async fn list_spacing_completion_preserves_the_scrolled_reader() -> Result<()> {
assert!(buffer_text(&before).contains("• c"));
app.handle_consolidate_agent_message(
&mut tui,
"- First item wraps onto a second row\n- b\n- c".into(),
app.config.cwd.to_path_buf(),
/*inline_visualization_context*/ None,
crate::history_cell::AgentMarkdownCell::new(
"- First item wraps onto a second row\n- b\n- c".into(),
&app.config.cwd,
),
ConsolidationScrollbackReflow::Required,
/*deferred_history_cell*/ None,
)?;
+10 -7
View File
@@ -1,5 +1,7 @@
//! App-level orchestration tests for the TUI.
#[path = "tests/copy_mode_tests.rs"]
mod copy_mode_tests;
#[path = "tests/mcp_login_tests.rs"]
mod mcp_login_tests;
@@ -6868,6 +6870,8 @@ async fn closing_fullscreen_inline_overlay_restores_history_once() -> Result<()>
#[tokio::test]
async fn copy_picker_opening_preserves_terminal_scrollback_without_reflow() {
let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await;
app.chat_widget.local_settings.transcript_mode =
crate::transcript_mode::TranscriptMode::Terminal;
let response = "Existing response\n\n```rust\nkeep_scrollback();\n```";
app.chat_widget.handle_server_notification(
ServerNotification::ItemCompleted(codex_app_server_protocol::ItemCompletedNotification {
@@ -7066,9 +7070,7 @@ async fn directive_only_completion_removes_streamed_directive() -> Result<()> {
let mut tui = crate::tui::test_support::make_test_tui()?;
app.handle_consolidate_agent_message(
&mut tui,
String::new(),
PathBuf::from("/tmp"),
/*inline_visualization_context*/ None,
AgentMarkdownCell::new(String::new(), Path::new("/tmp")),
ConsolidationScrollbackReflow::Required,
/*deferred_history_cell*/ None,
)?;
@@ -7111,10 +7113,11 @@ async fn required_stream_reflow_during_capped_initial_replay_survives_transcript
let mut tui = crate::tui::test_support::make_test_tui()?;
app.handle_consolidate_agent_message(
&mut tui,
"Final answer:\n\n| Pattern | Outcome |\n| --- | --- |\n| Table tail | Preserved |"
.to_string(),
PathBuf::from("/tmp"),
/*inline_visualization_context*/ None,
AgentMarkdownCell::new(
"Final answer:\n\n| Pattern | Outcome |\n| --- | --- |\n| Table tail | Preserved |"
.into(),
Path::new("/tmp"),
),
ConsolidationScrollbackReflow::Required,
/*deferred_history_cell*/ None,
)?;
@@ -0,0 +1,30 @@
//! Exercise copy entry through the app dispatcher, including an empty transcript.
use super::*;
#[tokio::test]
async fn empty_owned_copy_reports_feedback() -> Result<()> {
let (mut app, mut rx, _op_rx) = make_test_app_with_channels().await;
let mut app_server = start_config_write_test_app_server(&app).await?;
let mut tui = crate::tui::test_support::make_test_tui()?;
let guard = Arc::new(crate::copy_input_guard::CopyInputGuard(
app.app_event_tx.clone(),
));
app.handle_event(
&mut tui,
&mut app_server,
AppEvent::SelectTranscriptCopy { guard },
)
.await?;
let lines = std::iter::from_fn(|| rx.try_recv().ok())
.filter_map(|event| match event {
AppEvent::InsertHistoryCell(cell) => Some(cell.display_lines(/*width*/ 80)),
_ => None,
})
.flatten()
.map(|line| line.to_string())
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(lines, @"• Nothing to copy");
Ok(())
}
@@ -268,6 +268,7 @@ async fn inactive_thread_user_verification_preserves_foreground_stream() -> Resu
AppEvent::InsertHistoryCell(cell) => app.insert_history_cell(&mut tui, cell),
AppEvent::ConsolidateAgentMessage {
source,
copy_source,
cwd,
inline_visualization_context,
scrollback_reflow,
@@ -276,9 +277,12 @@ async fn inactive_thread_user_verification_preserves_foreground_stream() -> Resu
completed_messages.push(source.clone());
app.handle_consolidate_agent_message(
&mut tui,
source,
cwd,
inline_visualization_context,
history_cell::AgentMarkdownCell::new_with_inline_visualizations(
source,
&cwd,
inline_visualization_context,
)
.with_copy_source(copy_source),
scrollback_reflow,
deferred_history_cell,
)?;
+9
View File
@@ -474,6 +474,14 @@ pub(crate) enum AppEvent {
destination: TranscriptExportDestination,
},
/// Select a response or block directly in the owned transcript.
SelectTranscriptCopy {
guard: Arc<crate::copy_input_guard::CopyInputGuard>,
},
/// Retry queued input after the transcript copy owner is released.
TranscriptCopyClosed,
/// Copy text through the session clipboard worker.
CopySelection {
text: Arc<str>,
@@ -1166,6 +1174,7 @@ pub(crate) enum AppEvent {
/// transcript without first writing its provisional render to scrollback.
ConsolidateAgentMessage {
source: String,
copy_source: Option<String>,
cwd: PathBuf,
inline_visualization_context: Option<InlineVisualizationContext>,
scrollback_reflow: ConsolidationScrollbackReflow,
@@ -8,6 +8,17 @@ use crate::text_formatting::truncate_text;
impl ChatWidget {
pub(super) fn show_copy_picker(&mut self) {
if self.local_settings.transcript_mode.is_owned()
&& self.transcript.last_status_copy_targets.is_none()
{
let guard = Arc::new(crate::copy_input_guard::CopyInputGuard(
self.app_event_tx.clone(),
));
self.input_queue.transcript_copy = Arc::downgrade(&guard);
self.app_event_tx
.send(AppEvent::SelectTranscriptCopy { guard });
return;
}
let mut choices = Vec::new();
if let Some(status_targets) = &self.transcript.last_status_copy_targets {
choices.push((
+3 -3
View File
@@ -60,7 +60,7 @@ impl ChatWidget {
self.app_event_tx.send(AppEvent::FollowTranscript);
let should_submit_now = self.is_session_configured()
&& !self.is_plan_streaming_in_tui()
&& !self.input_queue.suppress_queue_autosend
&& !self.input_queue.submissions_paused()
&& !self.input_queue.rate_limit_recovery_pending
&& (!self.input_queue.user_turn_pending_start
|| self.turn_lifecycle.agent_turn_running);
@@ -170,7 +170,7 @@ impl ChatWidget {
}
let should_run_now = self.is_session_configured()
&& !self.is_user_turn_pending_or_running()
&& !self.input_queue.suppress_queue_autosend
&& !self.input_queue.submissions_paused()
&& !self.input_queue.rate_limit_recovery_pending;
if action != QueuedInputAction::ParseSlash {
self.empty_state_animation.borrow_mut().dismiss();
@@ -237,7 +237,7 @@ impl ChatWidget {
if !self.is_session_configured()
|| self.fork_in_progress
|| self.has_misalignment_policy_violation()
|| self.input_queue.suppress_queue_autosend
|| self.input_queue.submissions_paused()
|| self.input_queue.rate_limit_recovery_pending
|| self.input_queue.recovered_queue
|| self.input_queue.has_unconfirmed_messages()
@@ -49,6 +49,7 @@ pub(super) struct InputQueueState {
/// fresh user turn instead of restoring them into the composer.
pub(super) submit_pending_steers_after_interrupt: bool,
pub(super) suppress_queue_autosend: bool,
pub(super) transcript_copy: std::sync::Weak<crate::copy_input_guard::CopyInputGuard>,
/// Hold submissions while a usage failure or backend-directed model fallback is resolved.
pub(super) rate_limit_recovery_pending: bool,
/// Pause for user recovery (for example an image or permission failure), independent of delivery.
@@ -56,6 +57,10 @@ pub(super) struct InputQueueState {
}
impl InputQueueState {
pub(super) fn submissions_paused(&self) -> bool {
self.suppress_queue_autosend || self.transcript_copy.strong_count() > 0
}
pub(super) fn has_unconfirmed_messages(&self) -> bool {
self.queued_user_messages
.iter()
+1 -1
View File
@@ -133,7 +133,7 @@ impl ChatWidget {
}
let main = self.bottom_pane.composer_draft_snapshot();
let accepted = if queued
|| self.input_queue.suppress_queue_autosend
|| self.input_queue.submissions_paused()
|| self.is_plan_streaming_in_tui()
|| self.input_queue.user_turn_pending_start
&& !self.turn_lifecycle.agent_turn_running
@@ -51,7 +51,7 @@ impl ChatWidget {
|| self.startup_submission_has_protected_input()
|| self.is_plan_streaming_in_tui()
|| self.is_user_turn_pending_or_running()
|| self.input_queue.suppress_queue_autosend
|| self.input_queue.submissions_paused()
|| self.input_queue.rate_limit_recovery_pending
|| self.input_queue.recovered_queue
|| self.input_queue.has_unconfirmed_messages()
+14 -8
View File
@@ -89,7 +89,10 @@ impl ChatWidget {
let needs_scrollback_reflow = controller.needs_scrollback_reflow();
self.clear_active_stream_tail();
let (cell, streamed_source) = controller.finalize();
let completed_message_differs = completed_message.is_some_and(|completed| {
let completed_display = completed_message.map(|source| {
parse_assistant_markdown(source, self.config.cwd.as_path()).visible_markdown
});
let completed_message_differs = completed_display.as_deref().is_some_and(|completed| {
let Some(streamed) = streamed_source.as_deref() else {
return true;
};
@@ -117,10 +120,9 @@ impl ChatWidget {
};
// Consolidate the run of streaming AgentMessageCells into a single AgentMarkdownCell
// that can re-render from source on resize.
let source = completed_message.map(str::to_owned).or_else(|| {
streamed_source.map(|source| {
parse_assistant_markdown(&source, self.config.cwd.as_path()).visible_markdown
})
let copy_source = completed_message.map(str::to_owned).or(streamed_source);
let source = copy_source.as_deref().map(|source| {
parse_assistant_markdown(source, self.config.cwd.as_path()).visible_markdown
});
if let Some(source) = source {
let inline_visualization_context = self.thread_id.and_then(|thread_id| {
@@ -132,6 +134,7 @@ impl ChatWidget {
self.note_stream_consolidation_queued();
self.app_event_tx.send(AppEvent::ConsolidateAgentMessage {
source,
copy_source,
cwd: self.config.cwd.to_path_buf(),
inline_visualization_context,
scrollback_reflow,
@@ -189,7 +192,9 @@ impl ChatWidget {
&& let Some(message) = message
&& !message.is_empty()
{
self.handle_streaming_delta(message.to_string());
let displayed =
parse_assistant_markdown(message, self.config.cwd.as_path()).visible_markdown;
self.handle_streaming_delta(displayed);
}
// Item completion is authoritative. Use it for consolidation so any
// deltas dropped by a saturated transport cannot truncate the transcript.
@@ -439,12 +444,13 @@ impl ChatWidget {
parsed.visible_markdown.clone(),
self.config.cwd.as_path(),
context,
),
)
.with_copy_source(Some(message.clone())),
);
self.handle_stream_finished();
self.request_redraw();
} else {
self.finalize_completed_assistant_message(Some(parsed.visible_markdown.as_str()));
self.finalize_completed_assistant_message(Some(&message));
}
if !parsed.visible_markdown.is_empty() {
self.transcript
@@ -8,6 +8,7 @@ use pretty_assertions::assert_eq;
#[tokio::test]
async fn whole_response_copy_uses_followup_labels() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
let directive = r#":codex-followup[**Inspect items[0]**]{prompt="private"}"#;
let literal =
format!("\n\n`{directive}`\n\n```text\n{directive}\n```\n\n:codex-followup[unfinished");
@@ -37,6 +38,7 @@ async fn whole_response_copy_uses_followup_labels() {
#[tokio::test]
async fn completed_response_copy_preserves_markdown_line_endings() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
let markdown = "Hard break: \nstarts a new line.\n\n```text\ncode with trailing spaces \n```";
replay_agent_message(
&mut chat,
@@ -59,6 +61,7 @@ async fn completed_response_copy_preserves_markdown_line_endings() {
#[tokio::test]
async fn copy_export_picker_custom_keys_preserve_payloads_and_composer_draft() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
let mut keymap = crate::keymap::RuntimeKeymap::defaults();
keymap.list.accept = vec![key_hint::plain(KeyCode::F(/*n*/ 3))];
keymap.list.cancel = vec![key_hint::plain(KeyCode::F(/*n*/ 2))];
@@ -127,3 +130,41 @@ async fn copy_export_picker_custom_keys_preserve_payloads_and_composer_draft() {
assert!(chat.no_modal_or_popup_active());
assert_eq!(chat.bottom_pane.composer_text(), "Keep this draft");
}
#[tokio::test]
async fn owned_copy_opens_transcript_selection() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Owned;
let markdown = "Latest **response**\n\n```sh\necho hello \n```";
chat.transcript.last_agent_markdown = Some(markdown.into());
chat.show_copy_picker();
assert!(
std::iter::from_fn(|| rx.try_recv().ok())
.any(|event| matches!(event, AppEvent::SelectTranscriptCopy { .. }))
);
assert!(chat.no_modal_or_popup_active());
}
#[tokio::test]
async fn completed_copy_source_survives_replay_and_stream_consolidation() {
let source = "Intro\r\n\r\n```sh\r\necho x \r\n```\r\n";
for replay in [false, true] {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
if replay {
replay_agent_message(&mut chat, "source", source, ReplayKind::ThreadSnapshot);
} else {
complete_assistant_message(
&mut chat,
"source",
source,
Some(MessagePhase::FinalAnswer),
);
}
let retained = std::iter::from_fn(|| rx.try_recv().ok()).find_map(|event| match event {
AppEvent::InsertHistoryCell(cell) => cell.copy_source().map(str::to_owned),
AppEvent::ConsolidateAgentMessage { copy_source, .. } => copy_source,
_ => None,
});
assert_eq!(retained.as_deref(), Some(source));
}
}
@@ -1562,6 +1562,7 @@ async fn slash_copy_state_tracks_turn_complete_final_reply() {
#[tokio::test]
async fn slash_copy_picker_uses_completed_commentary_during_active_turn() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
complete_turn_with_message(&mut chat, "turn-1", Some("Previous final response"));
handle_turn_started(&mut chat, "active");
let commentary = "Here is the command:\n\n```sh\necho current\n```";
@@ -1596,6 +1597,7 @@ async fn slash_copy_picker_uses_completed_commentary_during_active_turn() {
#[tokio::test]
async fn slash_copy_state_tracks_plan_item_completion() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
complete_turn_with_message(&mut chat, "previous", Some("```rust\nstale();\n```"));
let plan_text = "## Plan\n\n1. Build it\n2. Test it\n\n```sh\r\njust test \r\n```".to_string();
@@ -1653,6 +1655,7 @@ async fn slash_copy_state_tracks_plan_item_completion() {
#[tokio::test]
async fn slash_copy_picker_preserves_completed_source_whitespace_and_hides_directives() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
let source = concat!(
"Intro ::git-push{cwd=\"/repo\"}\r\n\r\n",
"```powershell\r\nWrite-Output value \r\nWrite-Output done\t\r\n```\r\n\r\n",
@@ -1709,6 +1712,7 @@ async fn slash_copy_picker_defers_queued_input_until_selection_or_cancellation_s
for close_key in [KeyCode::Enter, KeyCode::Esc] {
let (mut chat, mut rx, mut op_rx) =
make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
chat.thread_id = Some(ThreadId::new());
complete_turn_with_message(&mut chat, "previous", Some("Previous response"));
handle_turn_started(&mut chat, "active");
@@ -1762,6 +1766,7 @@ async fn slash_copy_picker_defers_queued_input_until_selection_or_cancellation_s
#[tokio::test]
async fn slash_copy_picker_previews_whole_response_code_blocks_and_blockquotes() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
chat.transcript.last_agent_markdown = Some(
"Overview\n\n```python\nprint('first')\nprint('second')\n```\n\n> Important quote\n\n```sh\necho done\n```"
.to_string(),
@@ -1881,6 +1886,7 @@ async fn slash_copy_status_yields_to_later_turns_and_commands_even_after_refresh
NextTurn::ShellCommand,
] {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.4")).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
chat.thread_id = Some(ThreadId::new());
complete_turn_with_message(&mut chat, "turn-1", Some("Original reply"));
set_chatgpt_auth(&mut chat);
@@ -1929,6 +1935,7 @@ async fn slash_copy_status_yields_to_later_turns_and_commands_even_after_refresh
async fn slash_copy_status_yields_to_queued_commands_after_queued_status() {
for command in ["/rename Queued rename", "!echo hello"] {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
chat.thread_id = Some(ThreadId::new());
handle_turn_started(&mut chat, "turn-1");
queue_composer_text_with_tab(&mut chat, "/status");
@@ -1955,6 +1962,7 @@ async fn slash_copy_status_yields_to_queued_commands_after_queued_status() {
async fn slash_copy_picker_waits_for_submission_after_typing_or_autocomplete() {
for select_from_autocomplete in [false, true] {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
chat.transcript.last_agent_markdown = Some("Ready to copy".to_string());
chat.bottom_pane
.set_composer_text("/cop".to_string(), Vec::new(), Vec::new());
@@ -1990,6 +1998,7 @@ async fn slash_copy_picker_waits_for_submission_after_typing_or_autocomplete() {
#[tokio::test]
async fn slash_copy_picker_waits_for_submission_after_paste() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
chat.transcript.last_agent_markdown = Some("Ready to copy".to_string());
chat.handle_paste("/copy".to_string());
@@ -2009,6 +2018,7 @@ async fn slash_copy_picker_waits_for_submission_after_paste() {
#[tokio::test]
async fn slash_copy_picker_numeric_shortcuts_copy_whole_response_and_exact_code() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
let markdown = "Intro\n\n```rust\nfn main() {\n run();\n}\n```";
chat.transcript.last_agent_markdown = Some(markdown.to_string());
@@ -2035,6 +2045,7 @@ async fn slash_copy_picker_renders_only_whole_responses_as_markdown() {
use crate::clipboard_copy::CopyFormat;
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
let markdown = "**Intro**\n\n```text\n# literal *code*\n```\n\n> **Quote**\n";
chat.transcript.last_agent_markdown = Some(markdown.to_string());
for (key, expected) in [
@@ -2064,6 +2075,7 @@ async fn slash_copy_picker_renders_only_whole_responses_as_markdown() {
#[tokio::test]
async fn slash_copy_picker_preserves_nested_blockquote_markdown_and_code() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
chat.transcript.last_agent_markdown =
Some("> **outer**\n> > _nested_\n> ```sh\n> nested()\n> ```\n".to_string());
@@ -2088,6 +2100,7 @@ async fn slash_copy_picker_preserves_nested_blockquote_markdown_and_code() {
#[tokio::test]
async fn slash_copy_picker_supports_arrow_navigation_enter_and_scrolling() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
chat.transcript.last_agent_markdown = Some(
(1..=11)
.map(|index| format!("```sh\nexample_{index}()\n```\n"))
@@ -2114,6 +2127,7 @@ async fn slash_copy_picker_supports_arrow_navigation_enter_and_scrolling() {
#[tokio::test]
async fn slash_copy_picker_escape_dismisses_without_copying() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
chat.transcript.last_agent_markdown = Some("Nothing copied".to_string());
chat.dispatch_command(SlashCommand::Copy);
@@ -2128,6 +2142,7 @@ async fn slash_copy_picker_escape_dismisses_without_copying() {
#[tokio::test]
async fn slash_copy_picker_remains_available_from_parent_owned_threads() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
chat.transcript.last_agent_markdown = Some("Safe local copy".to_string());
chat.set_parent_owned_thread();
chat.bottom_pane
@@ -2240,6 +2255,7 @@ async fn slash_daybreak_offers_an_application_when_unavailable() {
#[tokio::test]
async fn slash_copy_reports_when_no_agent_response_exists() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
chat.dispatch_command(SlashCommand::Copy);
@@ -3732,3 +3748,35 @@ async fn transcript_copy_feedback_stays_in_the_footer_without_history_or_interru
render_bottom_popup(&chat, /*width*/ 80)
);
}
#[tokio::test]
async fn owned_copy_guard_defers_queued_input_until_released() {
for queued in ["/new", "/clear", "follow-up prompt"] {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Owned;
chat.thread_id = Some(ThreadId::new());
complete_turn_with_message(&mut chat, "previous", Some("Previous response"));
handle_turn_started(&mut chat, "active");
queue_composer_text_with_tab(&mut chat, queued);
chat.dispatch_command(SlashCommand::Copy);
let guard = std::iter::from_fn(|| rx.try_recv().ok())
.find_map(|event| match event {
AppEvent::SelectTranscriptCopy { guard, .. } => Some(guard),
_ => None,
})
.unwrap();
complete_turn_with_message(&mut chat, "active", Some("New response"));
assert_eq!(chat.input_queue.queued_user_messages.len(), 1);
assert_matches!(op_rx.try_recv(), Err(TryRecvError::Empty));
while let Ok(event) = rx.try_recv() {
assert!(!matches!(
event,
AppEvent::NewSession { .. } | AppEvent::ClearUi { .. }
));
}
drop(guard);
assert_matches!(rx.try_recv(), Ok(AppEvent::TranscriptCopyClosed));
chat.maybe_send_next_queued_input();
assert!(chat.input_queue.queued_user_messages.is_empty());
}
}
+13
View File
@@ -0,0 +1,13 @@
//! Keep queued submissions paused until the transcript selector releases its owner.
use crate::app_event::AppEvent;
use crate::app_event_sender::AppEventSender;
#[derive(Debug)]
pub(crate) struct CopyInputGuard(pub(crate) AppEventSender);
impl Drop for CopyInputGuard {
fn drop(&mut self) {
self.0.send(AppEvent::TranscriptCopyClosed);
}
}
+11
View File
@@ -502,6 +502,7 @@ impl HistoryCell for AgentMessageCell {
#[derive(Debug)]
pub(crate) struct AgentMarkdownCell {
markdown_source: String,
copy_source: Option<String>,
cwd: PathBuf,
inline_visualization_context: Option<crate::inline_visualization::InlineVisualizationContext>,
rendered_lines: Option<MarkdownRenderCache>,
@@ -509,6 +510,11 @@ pub(crate) struct AgentMarkdownCell {
}
impl AgentMarkdownCell {
pub(crate) fn with_copy_source(mut self, source: Option<String>) -> Self {
self.copy_source = source;
self
}
/// Create a finalized source-backed assistant message cell.
///
/// `markdown_source` must be the raw source accumulated by the stream controller, not already
@@ -535,6 +541,7 @@ impl AgentMarkdownCell {
.then(MarkdownRenderCache::default);
Self {
markdown_source,
copy_source: None,
cwd: cwd.to_path_buf(),
inline_visualization_context,
rendered_lines,
@@ -621,6 +628,10 @@ impl AgentMarkdownCell {
}
impl HistoryCell for AgentMarkdownCell {
fn copy_source(&self) -> Option<&str> {
Some(self.copy_source.as_deref().unwrap_or(&self.markdown_source))
}
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
visible_lines(self.display_hyperlink_lines(width))
}
+5
View File
@@ -213,6 +213,11 @@ pub(crate) trait HistoryCell: std::fmt::Debug + Send + Sync + Any {
Vec::new()
}
/// Original Markdown for semantic copy targets, independent of presentation.
fn copy_source(&self) -> Option<&str> {
None
}
/// Returns the logical lines for the main chat viewport.
fn display_lines(&self, width: u16) -> Vec<Line<'static>>;
+4
View File
@@ -148,6 +148,10 @@ impl ProposedPlanCell {
}
impl HistoryCell for ProposedPlanCell {
fn copy_source(&self) -> Option<&str> {
Some(&self.plan_markdown)
}
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
visible_lines(self.display_hyperlink_lines(width))
}
+1
View File
@@ -125,6 +125,7 @@ mod clock_format;
mod collaboration_modes;
mod color;
mod config_update;
mod copy_input_guard;
pub(crate) mod custom_terminal;
mod daybreak;
mod experimental_features;
+38 -13
View File
@@ -97,17 +97,23 @@ pub(crate) fn render_markdown_agent_with_list_spacing(
list_spacing: ListSpacing,
) -> Vec<HyperlinkLine> {
let rewritten = rewrite_inline_visualizations(markdown_source, inline_visualization_context);
let normalized = normalize_markdown_for_rendering(&rewritten.markdown);
let mut code_sources = Vec::new();
let normalized = if crate::markdown_render::preferences::current().tables {
unwrap_markdown_fences_with_sources(&rewritten.markdown, &mut code_sources)
} else {
Cow::Borrowed(rewritten.markdown.as_ref())
};
let is_hidden_link_destination = |destination: &str| {
rewritten.trusted_file_links.contains_key(destination)
|| crate::markdown_render::hide_web_link_destination(destination)
};
let mut lines = crate::markdown_render::render_streaming_markdown_lines_with_width_and_cwd(
let mut lines = crate::markdown_render::render_with_copy_sources(
&normalized,
width,
cwd,
&is_hidden_link_destination,
list_spacing,
code_sources,
)
.lines;
for hyperlink in lines.iter_mut().flat_map(|line| &mut line.hyperlinks) {
@@ -266,7 +272,14 @@ pub(crate) fn normalize_markdown_for_rendering(markdown_source: &str) -> Cow<'_,
/// The fence unwrapping is intentionally conservative: it buffers the entire fence body before
/// deciding, and an unclosed fence at end-of-input is re-emitted with its opening line so partial
/// streams degrade to code display.
pub(crate) fn unwrap_markdown_fences<'a>(markdown_source: &'a str) -> Cow<'a, str> {
pub(crate) fn unwrap_markdown_fences(markdown_source: &str) -> Cow<'_, str> {
unwrap_markdown_fences_with_sources(markdown_source, &mut Vec::new())
}
fn unwrap_markdown_fences_with_sources<'a>(
markdown_source: &'a str,
sources: &mut Vec<crate::markdown_copy::SourceBlock>,
) -> Cow<'a, str> {
// Zero-copy fast path: most messages contain no fences at all.
if !markdown_source.contains("```") && !markdown_source.contains("~~~") {
return Cow::Borrowed(markdown_source);
@@ -396,7 +409,7 @@ pub(crate) fn unwrap_markdown_fences<'a>(markdown_source: &'a str) -> Cow<'a, st
let mut active_fence: Option<ActiveFence> = None;
let mut source_offset = 0usize;
let mut push_source_range = |range: Range<usize>| {
let push_source_range = |out: &mut String, range: Range<usize>| {
if !range.is_empty() {
out.push_str(&markdown_source[range]);
}
@@ -410,7 +423,7 @@ pub(crate) fn unwrap_markdown_fences<'a>(markdown_source: &'a str) -> Cow<'a, st
if let Some(active) = active_fence.take() {
match active {
ActiveFence::Passthrough(fence) => {
push_source_range(line_range);
push_source_range(&mut out, line_range);
if !is_close_fence(line, fence) {
active_fence = Some(ActiveFence::Passthrough(fence));
}
@@ -421,15 +434,27 @@ pub(crate) fn unwrap_markdown_fences<'a>(markdown_source: &'a str) -> Cow<'a, st
&content_from_ranges(markdown_source, &data.content_ranges),
data.fence.is_blockquoted,
) {
let start = out.len();
for range in data.content_ranges {
push_source_range(range);
push_source_range(&mut out, range);
}
let fenced = &markdown_source[data.opening_range.start..line_range.end];
if let Some(CopyTarget::Code { content, .. }) =
extract_copy_targets(fenced)
.into_iter()
.find(|target| matches!(target, CopyTarget::Code { .. }))
{
sources.push(crate::markdown_copy::SourceBlock {
range: start..out.len(),
content,
});
}
} else {
push_source_range(data.opening_range);
push_source_range(&mut out, data.opening_range);
for range in data.content_ranges {
push_source_range(range);
push_source_range(&mut out, range);
}
push_source_range(line_range);
push_source_range(&mut out, line_range);
}
} else {
data.content_ranges.push(line_range);
@@ -450,22 +475,22 @@ pub(crate) fn unwrap_markdown_fences<'a>(markdown_source: &'a str) -> Cow<'a, st
},
)));
} else {
push_source_range(line_range);
push_source_range(&mut out, line_range);
active_fence = Some(ActiveFence::Passthrough(fence));
}
continue;
}
push_source_range(line_range);
push_source_range(&mut out, line_range);
}
if let Some(active) = active_fence {
match active {
ActiveFence::Passthrough(_) => {}
ActiveFence::MarkdownCandidate(data) => {
push_source_range(data.opening_range);
push_source_range(&mut out, data.opening_range);
for range in data.content_ranges {
push_source_range(range);
push_source_range(&mut out, range);
}
}
}
+22
View File
@@ -16,6 +16,24 @@ use crate::terminal_hyperlinks::LogicalLineSource;
pub(crate) mod table;
/// A transformed fenced block and its coordinates in the renderer input.
#[derive(Clone)]
pub(crate) struct SourceBlock {
pub(crate) range: Range<usize>,
pub(crate) content: Arc<str>,
}
pub(crate) fn quote_content(source: &str) -> String {
source
.split_inclusive('\n')
.map(|line| {
line.trim_start_matches(' ')
.strip_prefix('>')
.map_or(line, |line| line.strip_prefix(' ').unwrap_or(line))
})
.collect()
}
// Bound retained inline stacks and container prefixes independently of parser nesting.
pub(crate) const MAX_COPY_DEPTH: usize = 64;
@@ -60,6 +78,10 @@ pub(crate) struct CopyLine {
/// Restore the containing item when a multiline selection starts in its later paragraph.
pub(crate) item_prefix: String,
pub(crate) code: bool,
/// Source shared by rows when rendering replaces code with a diagram or table.
pub(crate) code_source: Option<Arc<str>>,
/// Outer quote source, retained even when it contains only code.
pub(crate) quote_source: Option<Arc<str>>,
pub(crate) table: Option<table::TableLine>,
table_cell: bool,
pub(crate) rule: bool,
+39 -2
View File
@@ -81,6 +81,7 @@ mod mermaid;
pub(crate) mod preferences;
mod source_tables;
mod streaming;
pub(crate) use streaming::render_with_copy_sources;
mod table_key_value;
mod task_lists;
mod web_links;
@@ -447,6 +448,9 @@ struct Writer<'a, 'policy> {
inline_styles: Vec<Style>,
copy_inline: Vec<crate::markdown_copy::Inline>,
copy_line: crate::markdown_copy::CopyLine,
quote_sources: Vec<std::sync::Arc<str>>,
code_sources: Vec<crate::markdown_copy::SourceBlock>,
transformed_code_source: Option<std::sync::Arc<str>>,
indent_stack: Vec<IndentContext>,
list_indices: Vec<Option<u64>>,
list_needs_blank_before_next_item: Vec<bool>,
@@ -489,6 +493,9 @@ impl<'a, 'policy> Writer<'a, 'policy> {
inline_styles: Vec::new(),
copy_inline: Vec::new(),
copy_line: Default::default(),
quote_sources: Vec::new(),
code_sources: Vec::new(),
transformed_code_source: None,
indent_stack: Vec::new(),
list_indices: Vec::new(),
list_needs_blank_before_next_item: Vec::new(),
@@ -532,6 +539,20 @@ impl<'a, 'policy> Writer<'a, 'policy> {
where
I: Iterator<Item = (Event<'a>, Range<usize>)>,
{
let source = self
.code_sources
.iter()
.find(|source| source.range.contains(&range.start))
.map(|source| std::sync::Arc::clone(&source.content));
let same_source = match (&source, &self.transformed_code_source) {
(Some(source), Some(current)) => std::sync::Arc::ptr_eq(source, current),
(None, None) => true,
_ => false,
};
if !same_source {
self.flush_current_line();
self.transformed_code_source = source;
}
self.prepare_for_event(&event);
let copy_inline = crate::markdown_copy::Inline::from_event(&event);
if let Some(inline) = &copy_inline {
@@ -608,7 +629,13 @@ impl<'a, 'policy> Writer<'a, 'policy> {
match tag {
Tag::Paragraph => self.start_paragraph(),
Tag::Heading { level, .. } => self.start_heading(level),
Tag::BlockQuote => self.start_blockquote(),
Tag::BlockQuote => {
self.start_blockquote();
let source = self.quote_sources.first().cloned().unwrap_or_else(|| {
crate::markdown_copy::quote_content(&self.input[range]).into()
});
self.quote_sources.push(source);
}
Tag::CodeBlock(kind) => {
self.code_block_content_end = range.end;
let indent = match kind {
@@ -692,7 +719,11 @@ impl<'a, 'policy> Writer<'a, 'policy> {
self.end_paragraph();
}
TagEnd::Heading(_) => self.end_heading(),
TagEnd::BlockQuote => self.end_blockquote(),
TagEnd::BlockQuote => {
self.flush_current_line();
self.end_blockquote();
self.quote_sources.pop();
}
TagEnd::CodeBlock => self.end_codeblock(range),
TagEnd::List(_) => self.end_list(),
TagEnd::Item => {
@@ -1116,8 +1147,10 @@ impl<'a, 'policy> Writer<'a, 'policy> {
Some(diagram) => diagram,
None => highlight_code_to_lines(&code, &lang),
};
let source: std::sync::Arc<str> = code.into();
for hl_line in highlighted {
self.push_line(Line::default());
self.copy_line.code_source = Some(std::sync::Arc::clone(&source));
for span in hl_line.spans {
self.push_span(span);
}
@@ -2347,6 +2380,8 @@ impl<'a, 'policy> Writer<'a, 'policy> {
.and_then(|source| source.copy.as_deref())
.cloned()
.unwrap_or_default();
copy.code_source = self.transformed_code_source.clone();
copy.quote_source = self.quote_sources.first().cloned();
copy.prefix = self.copy_prefix(pending_marker_line);
copy.continuation = self.copy_prefix(/*pending_marker_line*/ false);
copy.item_prefix = self.copy_prefix(/*pending_marker_line*/ true);
@@ -2381,6 +2416,8 @@ impl<'a, 'policy> Writer<'a, 'policy> {
self.copy_line.continuation = self.copy_prefix(/*pending_marker_line*/ false);
self.copy_line.item_prefix = self.copy_prefix(/*pending_marker_line*/ true);
self.copy_line.code = self.in_code_block;
self.copy_line.code_source = self.transformed_code_source.clone();
self.copy_line.quote_source = self.quote_sources.first().cloned();
// Heading markers are already visible; retain them as Markdown syntax.
self.copy_line
.push(line.spans.iter().map(|span| span.content.len()).sum(), &[]);
@@ -42,6 +42,24 @@ pub(crate) fn render_streaming_markdown_lines_with_width_and_cwd(
cwd: Option<&Path>,
is_hidden_link_destination: &dyn Fn(&str) -> bool,
list_spacing: ListSpacing,
) -> StreamingMarkdownRender {
render_with_copy_sources(
input,
width,
cwd,
is_hidden_link_destination,
list_spacing,
Vec::new(),
)
}
pub(crate) fn render_with_copy_sources(
input: &str,
width: Option<usize>,
cwd: Option<&Path>,
is_hidden_link_destination: &dyn Fn(&str) -> bool,
list_spacing: ListSpacing,
code_sources: Vec<crate::markdown_copy::SourceBlock>,
) -> StreamingMarkdownRender {
let mut options = Options::empty();
options.insert(Options::ENABLE_STRIKETHROUGH);
@@ -69,6 +87,7 @@ pub(crate) fn render_streaming_markdown_lines_with_width_and_cwd(
// Drop the consumed parser before the rendering state, including on unwind.
let mut parser = parser;
writer.list_spacing = list_spacing;
writer.code_sources = code_sources;
writer.run(&mut parser);
StreamingMarkdownRender {
lines: writer.text,
+19
View File
@@ -8,6 +8,7 @@
mod activity;
mod bookmark;
mod composer_gap;
mod copy_mode;
mod disclosure;
mod follow_control;
mod footer;
@@ -103,6 +104,7 @@ pub(crate) struct TranscriptView {
suppressed_prompt_header: Option<prompt_header::SuppressedHeader>,
visible: Vec<VisibleRow>,
selection: Option<Selection>,
copy_mode: Option<copy_mode::CopyMode>,
held_reading: Option<ViewSnapshot>,
search: Search,
detailed: bool,
@@ -138,6 +140,7 @@ impl Default for TranscriptView {
suppressed_prompt_header: None,
visible: Vec::new(),
selection: None,
copy_mode: None,
held_reading: None,
search: Search::default(),
detailed: false,
@@ -177,15 +180,21 @@ impl TranscriptView {
let cells = snapshot.as_deref().unwrap_or(cells);
let suppressed_prompt_header = self.suppressed_prompt_header.take();
Clear.render(area, buf);
let previous_height = self.area.height;
let resized = self.area.width != area.width || self.area.bottom() != area.bottom();
self.prepare_width(area.width);
self.area = area;
self.normalize_selection(cells);
if resized {
self.reveal_copy_context(cells);
}
self.visible.clear();
if area.is_empty() {
self.tail_visible = false;
return;
}
let initial_start = self.start(cells);
let initial_position = self.position;
let mut start = initial_start;
let mut body = area;
let header_position = prompt_header::SuppressedHeader {
@@ -200,7 +209,12 @@ impl TranscriptView {
self.suppressed_prompt_header = Some(header_position);
} else if area.height >= 4 && prompt_header::line(cells, start.0, area.width).is_some() {
body = Rect::new(area.x, area.y + 1, area.width, area.height - 1);
let resized = resized || previous_height != body.height;
self.area = body;
// Copy targets must also leave context after the prompt reserves its row.
if resized {
self.reveal_copy_context(cells);
}
// Following may advance into the next turn after reserving the header row.
start = self.start(cells);
if let Some(header) = prompt_header::line(cells, start.0, area.width) {
@@ -209,6 +223,9 @@ impl TranscriptView {
body = area;
self.area = area;
start = initial_start;
if resized && self.copy_mode.is_some() {
self.position = initial_position;
}
self.suppressed_prompt_header = Some(header_position);
}
}
@@ -336,6 +353,7 @@ impl TranscriptView {
return;
}
self.selection = None;
self.copy_mode = None;
self.release_live_reading();
self.cache.clear();
self.suppressed_prompt_header = None;
@@ -381,6 +399,7 @@ impl TranscriptView {
self.cancel_beginning();
self.position = Position::Latest;
self.selection = None;
self.copy_mode = None;
self.release_live_reading();
self.unseen_activity = false;
self.disclosure.focused = None;
@@ -0,0 +1,381 @@
//! Semantic copy navigation over the selection's frozen transcript revision.
//! Targets retain their original payloads and leave surrounding context when revealed.
use super::*;
use crate::history_cell::AgentMarkdownCell;
use crate::history_cell::ProposedPlanCell;
use crate::history_cell::UserHistoryCell;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyModifiers;
use std::ops::Range;
pub(super) struct CopyMode {
_guard: Option<Arc<crate::copy_input_guard::CopyInputGuard>>,
pub(super) response: Option<(EntryKey, Arc<str>)>,
pub(super) whole: bool,
pub(super) source: Option<String>,
pub(super) label: &'static str,
}
impl TranscriptView {
pub(crate) fn begin_copy_mode(
&mut self,
cells: &[Arc<dyn HistoryCell>],
guard: Option<Arc<crate::copy_input_guard::CopyInputGuard>>,
) -> bool {
self.jump_to_latest();
self.hold_position();
let latest = cells.iter().rposition(is_response);
self.copy_mode = Some(CopyMode {
_guard: guard,
response: latest.and_then(|index| {
let cell = &cells[index];
let text = if cell.as_any().is::<AgentMarkdownCell>() {
// Raw lines retain this cell's visible Markdown after hidden directives
// were removed during consolidation, independently of the latest cache.
let markdown = cell
.raw_lines()
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join("\n");
crate::markdown_render::followup_labels(&markdown).into_owned()
} else {
cell.copy_source()?.to_owned()
};
Some((EntryKey::cell(cell), Arc::from(text)))
}),
whole: true,
source: None,
label: "Whole response",
});
if !self.select_copy_response(cells) {
self.move_copy_target(cells, KeyCode::Up);
}
if self.selection.is_none() {
self.jump_to_latest();
}
self.copy_mode.is_some()
}
pub(super) fn handle_copy_mode_key(
&mut self,
key: KeyEvent,
cells: &[Arc<dyn HistoryCell>],
) -> Option<ViewAction> {
self.copy_mode.as_ref()?;
let code = match crate::key_hint::normalize_key_parts(key.code, key.modifiers) {
(KeyCode::Char('k'), KeyModifiers::NONE) => KeyCode::Up,
(KeyCode::Char('j'), KeyModifiers::NONE) => KeyCode::Down,
(KeyCode::Char('g'), KeyModifiers::NONE) => KeyCode::Home,
(KeyCode::Char('g'), KeyModifiers::SHIFT) => KeyCode::End,
_ => key.code,
};
match code {
KeyCode::Up | KeyCode::Down | KeyCode::Home | KeyCode::End => {
self.move_copy_target(cells, code)
}
KeyCode::Esc => self.jump_to_latest(),
_ if key.code == KeyCode::Enter || crate::text_selection::is_copy_key(key) => {
return Some(ViewAction::CopyAndFollow(
self.selected_text(cells).unwrap_or_default(),
));
}
KeyCode::PageUp | KeyCode::PageDown => return self.handle_scroll_key(key, cells),
_ => return Some(ViewAction::Changed),
}
Some(ViewAction::Changed)
}
fn move_copy_target(&mut self, cells: &[Arc<dyn HistoryCell>], direction: KeyCode) {
let snapshot = self.snapshot_cells();
let cells = snapshot.as_deref().unwrap_or(cells);
self.normalize_selection(cells);
if direction == KeyCode::End && self.select_copy_response(cells) {
return;
}
let Some(mode) = &self.copy_mode else { return };
let label = mode.label;
let edge = matches!(direction, KeyCode::Home | KeyCode::End);
let older = matches!(direction, KeyCode::Up | KeyCode::End);
if mode.whole && !older && !edge {
return;
}
let current = self
.selection
.as_ref()
.filter(|_| !mode.whole && !edge)
.map(|s| (s.start.index, s.start.offset..s.end.offset));
let indices: Box<dyn Iterator<Item = usize>> = if older {
Box::new((0..current.as_ref().map_or(cells.len(), |(index, _)| index + 1)).rev())
} else {
Box::new(current.as_ref().map_or(0, |(index, _)| *index)..cells.len())
};
for index in indices {
let user = cells[index].as_any().downcast_ref::<UserHistoryCell>();
if user.is_none() && !is_response(&cells[index]) {
continue;
}
let Some(layout) = self.layout(cells, index) else {
continue;
};
let mut ranges = if let Some(user) = user {
user_ranges(layout.text(), &user.message)
} else if self.mode == crate::history_cell::HistoryRenderMode::Raw {
user_ranges(layout.text(), "")
.into_iter()
.filter(|(_, label, _)| *label != "User message")
.collect()
} else {
layout.copy_block_ranges()
};
ranges.sort_by_key(|(range, _, _)| (range.start, std::cmp::Reverse(range.end)));
if let Some(source) = user
.map(|user| user.message.as_str())
.or_else(|| cells[index].copy_source())
{
let targets = crate::markdown::extract_copy_targets(source);
let mut codes = targets
.iter()
.filter_map(|target| match target {
crate::markdown::CopyTarget::Code { content, .. } => Some(content),
crate::markdown::CopyTarget::Quote(_) => None,
})
.collect::<Vec<_>>();
let mut depth = 0;
let mut quotes = Vec::new();
for (event, span) in pulldown_cmark::Parser::new(source).into_offset_iter() {
match event {
pulldown_cmark::Event::Start(pulldown_cmark::Tag::BlockQuote) => {
if depth == 0 {
quotes.push(crate::markdown_copy::quote_content(&source[span]));
}
depth += 1;
}
pulldown_cmark::Event::End(pulldown_cmark::TagEnd::BlockQuote) => {
depth -= 1
}
_ => {}
}
}
let normalized = |text: &str| {
crate::markdown::normalize_markdown_for_rendering(text)
.lines()
.map(str::trim_end)
.collect::<Vec<_>>()
.join("\n")
.trim()
.to_owned()
};
for (range, label, payload) in &mut ranges {
if *label == "Code block" {
// Match rendered text, not ordinal position: indented code and
// source-preserving tables need not have a fenced counterpart.
let displayed = payload.as_deref().unwrap_or(&layout.text()[range.clone()]);
if let Some(at) = codes
.iter()
.position(|code| normalized(code) == normalized(displayed))
{
*payload = Some(codes.remove(at).to_string());
}
} else if user.is_none()
&& *label == "Blockquote"
&& let Some(displayed) = payload.as_deref()
&& let Some(at) = quotes.iter().position(|quote| {
let visible = quote
.split_inclusive('\n')
.map(|line| {
crate::git_action_directives::strip_line_directives(line).0
})
.collect::<String>();
normalized(&visible) == normalized(displayed)
|| normalized(quote) == normalized(displayed)
})
{
*payload = Some(
quotes
.remove(at)
.split_inclusive('\n')
.map(|line| {
crate::git_action_directives::strip_line_directives(line).0
})
.collect(),
);
}
}
}
let boundary =
current
.as_ref()
.filter(|(at, _)| *at == index)
.and_then(|(_, range)| {
ranges.iter().position(|(candidate, candidate_label, _)| {
candidate == range && *candidate_label == label
})
});
let target = if older {
ranges[..boundary.unwrap_or(ranges.len())].last()
} else {
ranges.get(boundary.map_or(0, |at| at + 1))
};
if let Some((range, label, source)) = target {
let range = range.clone();
if let Some(mode) = &mut self.copy_mode {
mode.whole = false;
mode.label = label;
mode.source = source.clone();
}
self.select_copy_range(cells, index, range);
return;
}
}
if !older {
self.select_copy_response(cells);
} else if self.history.has_unloaded_history() {
self.jump_to_entry(cells, /*index*/ 0);
}
}
/// Keep fitting targets inside a central band, scrolling only to the nearest margin.
/// Oversized targets show their beginning with context above rather than clipping it.
pub(super) fn reveal_copy_context(&mut self, cells: &[Arc<dyn HistoryCell>]) {
if self.copy_mode.is_none() {
return;
}
let Some(selection) = &self.selection else {
return;
};
let (start, end) = (selection.start, selection.end);
let index = self.resolve(cells, start);
let Some(layout) = self.layout(cells, index) else {
return;
};
let first = layout.row_for_offset(start.offset);
// Match block painting: whole-entry highlights include final padding.
let finish = if start.offset == 0 && end.offset == layout.text().len() {
end.offset
} else {
end.offset.saturating_sub(/*rhs*/ 1)
};
let last = layout.row_for_offset(finish);
let height = usize::from(self.area.height);
if height == 0 {
return;
}
let target_height = last.saturating_sub(first) + 1;
// Reserve a quarter of the viewport, reducing the margin for taller targets.
let margin = (height / 4)
.max(1)
.min(height.saturating_sub(target_height) / 2);
let bottom_margin = (height / 4)
.max(1)
.min(height.saturating_sub(target_height).div_ceil(2));
let top = self.start(cells);
let inner_top = self.move_rows(cells, top.0, top.1, margin as isize);
let inner_bottom = self.move_rows(
cells,
top.0,
top.1,
height.saturating_sub(bottom_margin + 1) as isize,
);
if target_height < height && (index, first) >= inner_top && (index, last) <= inner_bottom {
return;
}
let inset = if target_height >= height {
height / 4
} else if (index, first) < inner_top {
margin
} else {
height - bottom_margin - target_height
};
let (index, row) = self.move_rows(cells, index, first, -(inset as isize));
if let Some(layout) = self.layout(cells, index) {
let offset = layout.position_at(row, /*column*/ 0);
self.position = Position::Reading(Anchor {
key: self.entry_key(cells, index),
index,
offset,
row_bias: layout.row_for_offset(offset) as isize - row as isize,
});
}
}
fn select_copy_response(&mut self, cells: &[Arc<dyn HistoryCell>]) -> bool {
let Some(mode) = &mut self.copy_mode else {
return false;
};
let Some((key, _)) = &mode.response else {
return false;
};
let Some(index) = cells.iter().position(|cell| EntryKey::cell(cell) == *key) else {
return false;
};
mode.whole = true;
mode.source = None;
mode.label = "Whole response";
let Some(layout) = self.layout(cells, index) else {
return false;
};
self.select_copy_range(cells, index, 0..layout.text().len());
true
}
}
fn is_response(cell: &Arc<dyn HistoryCell>) -> bool {
cell.as_any().is::<AgentMarkdownCell>() || cell.as_any().is::<ProposedPlanCell>()
}
fn user_ranges(text: &str, message: &str) -> Vec<(Range<usize>, &'static str, Option<String>)> {
use pulldown_cmark::Event;
use pulldown_cmark::Tag;
use pulldown_cmark::TagEnd;
let mut ranges = Vec::new();
if !text.trim().is_empty() {
ranges.push((
0..text.len(),
"User message",
(!message.is_empty())
.then(|| crate::history_cell::sanitize_user_text(message.into()).into_owned()),
));
}
let mut depth = 0;
let mut code: Option<(Range<usize>, String)> = None;
for (event, range) in pulldown_cmark::Parser::new(text).into_offset_iter() {
match event {
Event::Start(Tag::BlockQuote) => {
if depth == 0 {
let source = message
.is_empty()
.then(|| crate::markdown_copy::quote_content(&text[range.clone()]));
ranges.push((range, "Blockquote", source));
}
depth += 1;
}
Event::End(TagEnd::BlockQuote) => depth -= 1,
Event::Start(Tag::CodeBlock(_)) => {
code = Some((range.start..range.start, String::new()))
}
Event::Text(text) => {
if let Some((source, content)) = code.as_mut() {
content.push_str(&text);
if source.start == source.end {
source.start = range.start;
}
source.end = range.end;
}
}
Event::End(TagEnd::CodeBlock) => {
if let Some((range, content)) = code.take().filter(|(range, _)| !range.is_empty()) {
ranges.push((range, "Code block", Some(content)));
}
}
_ => {}
}
}
ranges
}
#[cfg(test)]
#[path = "copy_mode_tests.rs"]
mod tests;
@@ -0,0 +1,707 @@
//! Covers transcript copy navigation, rendering, and original-source clipboard payloads.
use super::*;
use crate::clipboard_copy::CopyStatus;
use crate::transcript_view::tests::render;
use crate::transcript_view::tests::text;
use crossterm::event::KeyModifiers;
use pretty_assertions::assert_eq;
use std::path::Path;
fn payload(view: &mut TranscriptView, cells: &[Arc<dyn HistoryCell>]) -> String {
let selected = view.selected_text(cells).unwrap();
let mut copied = String::new();
view.copy_selected_text_with(
cells,
&selected,
/*clear_selection*/ false,
|text, _| {
copied = text.to_owned();
Ok(CopyStatus::Confirmed)
},
)
.unwrap();
copied
}
#[test]
fn navigate_copy_resize_and_exit() {
let cells: Vec<Arc<dyn HistoryCell>> = vec![
Arc::new(AgentMarkdownCell::new(
"Old answer\n\n```\nold code\n```".into(),
Path::new("/"),
)),
Arc::new(crate::history_cell::new_user_prompt(
"User text\n\n> user quote\n\n```\nuser code\n```".into(),
Vec::new(),
Vec::new(),
Vec::new(),
)),
Arc::new(crate::history_cell::new_proposed_plan(
"Latest **plan**\n\n> assistant quote\n\n```rust\nassistant code\n```".into(),
Path::new("/"),
)),
];
let mut view = TranscriptView::default();
render(&mut view, &cells, /*width*/ 50, /*height*/ 8);
view.begin_copy_mode(&cells, /*guard*/ None);
render(&mut view, &cells, /*width*/ 50, /*height*/ 8);
assert_eq!(
payload(&mut view, &cells),
"Latest **plan**\n\n> assistant quote\n\n```rust\nassistant code\n```"
);
for expected in [
"assistant code\n",
"assistant quote\n",
"user code\n",
"> user quote\n",
"User text\n\n> user quote\n\n```\nuser code\n```",
"old code\n",
"old code\n",
] {
view.move_copy_target(&cells, KeyCode::Up);
assert_eq!(payload(&mut view, &cells), expected);
render(&mut view, &cells, /*width*/ 50, /*height*/ 8);
}
for _ in 0..5 {
view.move_copy_target(&cells, KeyCode::Down);
}
let buffer = render(&mut view, &cells, /*width*/ 50, /*height*/ 8);
assert!(
buffer
.content
.iter()
.any(|cell| cell.modifier.contains(ratatui::style::Modifier::REVERSED))
);
insta::assert_snapshot!(text(&buffer), @"
› User text > user quote ``` user code ```
Latest plan
> assistant quote
assistant code
");
insta::assert_snapshot!(
view.footer_with_navigation(/*width*/ 50, crate::motion::MotionMode::Reduced, "")
.unwrap()
.text
.to_string(), @"
Copy code block
↑/↓/j/k select · g/G ends · enter copy · esc close
"
);
render(&mut view, &cells, /*width*/ 14, /*height*/ 8);
assert_eq!(payload(&mut view, &cells), "assistant code\n");
view.move_copy_target(&cells, KeyCode::Down);
assert_eq!(
payload(&mut view, &cells),
"Latest **plan**\n\n> assistant quote\n\n```rust\nassistant code\n```"
);
let selected = view.selected_text(&cells).unwrap();
view.copy_selected_text_with(
&cells,
&selected,
/*clear_selection*/ true,
|_, _| Ok(CopyStatus::Confirmed),
)
.unwrap();
assert!(view.is_following());
view.begin_copy_mode(&cells, /*guard*/ None);
for (key, expected) in [
('g', "old code\n"),
(
'G',
"Latest **plan**\n\n> assistant quote\n\n```rust\nassistant code\n```",
),
('k', "assistant code\n"),
] {
view.handle_key(
KeyEvent::new(KeyCode::Char(key), KeyModifiers::NONE),
&cells,
);
render(&mut view, &cells, /*width*/ 50, /*height*/ 8);
assert_eq!(payload(&mut view, &cells), expected);
}
view.handle_copy_mode_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE), &cells);
assert!(view.is_following());
}
#[test]
fn copy_reveals_offscreen_block_with_context() {
let cells: Vec<Arc<dyn HistoryCell>> = vec![Arc::new(AgentMarkdownCell::new(
format!("{}\n```sh\nlast code\n```", "line\n".repeat(/*n*/ 20)),
Path::new("/"),
))];
let mut view = TranscriptView::default();
render(&mut view, &cells, /*width*/ 50, /*height*/ 5);
view.scroll(&cells, /*rows*/ -5);
render(&mut view, &cells, /*width*/ 50, /*height*/ 5);
view.begin_copy_mode(&cells, /*guard*/ None);
render(&mut view, &cells, /*width*/ 50, /*height*/ 5);
view.move_copy_target(&cells, KeyCode::Up);
let after = render(&mut view, &cells, /*width*/ 50, /*height*/ 5);
insta::assert_snapshot!(text(&after), @"
line
line
last code
");
}
#[test]
fn user_messages_support_vim_navigation_without_an_assistant_response() {
let messages = ["First **user** message", "\nPlain prompt with wrapping\n\n"];
let cells: Vec<Arc<dyn HistoryCell>> = messages
.iter()
.map(|message| {
Arc::new(crate::history_cell::new_user_prompt(
(*message).into(),
Vec::new(),
Vec::new(),
Vec::new(),
)) as Arc<dyn HistoryCell>
})
.collect();
let mut view = TranscriptView::default();
render(&mut view, &cells, /*width*/ 50, /*height*/ 8);
view.begin_copy_mode(&cells, /*guard*/ None);
assert_eq!(payload(&mut view, &cells), messages[1]);
for (code, modifiers, expected) in [
(KeyCode::Char('k'), KeyModifiers::NONE, messages[0]),
(KeyCode::Char('j'), KeyModifiers::NONE, messages[1]),
(KeyCode::Char('g'), KeyModifiers::NONE, messages[0]),
(KeyCode::Char('G'), KeyModifiers::NONE, messages[1]),
(KeyCode::Char('g'), KeyModifiers::NONE, messages[0]),
(KeyCode::Char('g'), KeyModifiers::SHIFT, messages[1]),
] {
view.handle_key(KeyEvent::new(code, modifiers), &cells);
render(&mut view, &cells, /*width*/ 18, /*height*/ 8);
assert_eq!(payload(&mut view, &cells), expected);
}
insta::assert_snapshot!(
view.footer_with_navigation(/*width*/ 60, crate::motion::MotionMode::Reduced, "")
.unwrap().text.to_string(), @"
Copy user message
↑/↓/j/k select · g/G ends · enter copy · esc close
"
);
}
#[test]
fn copy_highlight_fills_a_block_across_blank_and_wrapped_rows() {
let cells: Vec<Arc<dyn HistoryCell>> = vec![Arc::new(AgentMarkdownCell::new(
"Before\n\n```text\nlonger line\n\nx\n```\n\nAfter".into(),
Path::new("/"),
))];
let mut view = TranscriptView::default();
render(&mut view, &cells, /*width*/ 16, /*height*/ 12);
view.begin_copy_mode(&cells, /*guard*/ None);
view.move_copy_target(&cells, KeyCode::Up);
let selected = ratatui::buffer::Cell::default()
.set_style(crate::style::selection_style())
.style();
let mut snapshots = Vec::new();
for width in [16, 8] {
let buffer = render(&mut view, &cells, width, /*height*/ 12);
let rows: Vec<String> = buffer
.content
.chunks(usize::from(width))
.map(|row| {
let mask: String = row
.iter()
.map(|cell| if cell.style() == selected { '#' } else { '.' })
.collect();
format!(
"{mask} | {}",
row.iter()
.map(ratatui::buffer::Cell::symbol)
.collect::<String>()
)
})
.collect();
snapshots.push(rows.join("\n"));
assert_eq!(payload(&mut view, &cells), "longer line\n\nx\n");
}
insta::assert_snapshot!(snapshots.join("\n---\n"));
}
#[test]
fn whole_user_turn_highlight_includes_bottom_padding() {
let selected = ratatui::buffer::Cell::default()
.set_style(crate::style::selection_style())
.style();
let mut snapshots = Vec::new();
for (message, width, height) in [("Short prompt", 20, 4), ("Longer message\n\nlast", 10, 8)] {
let cells: Vec<Arc<dyn HistoryCell>> =
vec![Arc::new(crate::history_cell::new_user_prompt(
message.into(),
Vec::new(),
Vec::new(),
Vec::new(),
))];
let mut view = TranscriptView::default();
render(&mut view, &cells, width, height);
view.begin_copy_mode(&cells, /*guard*/ None);
let buffer = render(&mut view, &cells, width, height);
let rows: Vec<String> = buffer
.content
.chunks(usize::from(width))
.map(|row| {
let mask: String = row
.iter()
.map(|cell| if cell.style() == selected { '#' } else { '.' })
.collect();
format!(
"{mask} | {}",
row.iter()
.map(ratatui::buffer::Cell::symbol)
.collect::<String>()
)
})
.collect();
snapshots.push(rows.join("\n"));
assert_eq!(payload(&mut view, &cells), message);
}
insta::assert_snapshot!(snapshots.join("\n---\n"));
}
#[test]
fn rendered_mermaid_copies_source() {
let cells: Vec<Arc<dyn HistoryCell>> = vec![Arc::new(AgentMarkdownCell::new(
"```mermaid\ngraph LR\nA --> B\n```".into(),
Path::new("/"),
))];
let mut view = TranscriptView::default();
let buffer = render(&mut view, &cells, /*width*/ 50, /*height*/ 8);
assert!(!text(&buffer).contains("graph LR"));
view.begin_copy_mode(&cells, /*guard*/ None);
view.move_copy_target(&cells, KeyCode::Up);
assert_eq!(payload(&mut view, &cells), "graph LR\nA --> B\n");
}
#[test]
fn copy_source_survives_raw_rich_rendering_and_whitespace_normalization() {
let source = "Before\r\n\r\n```sh\r\necho x \r\n \r\n```\r\n\r\n> **quote**\r\n";
let displayed = crate::git_action_directives::parse_assistant_markdown(source, Path::new("/"))
.visible_markdown;
for mode in [
crate::history_cell::HistoryRenderMode::Rich,
crate::history_cell::HistoryRenderMode::Raw,
] {
let cells: Vec<Arc<dyn HistoryCell>> = vec![Arc::new(
AgentMarkdownCell::new(displayed.clone(), Path::new("/"))
.with_copy_source(Some(source.into())),
)];
let mut view = TranscriptView::default();
view.set_presentation(/*detailed*/ false, mode);
render(&mut view, &cells, /*width*/ 50, /*height*/ 20);
view.begin_copy_mode(&cells, /*guard*/ None);
view.move_copy_target(&cells, KeyCode::Up);
assert_eq!(payload(&mut view, &cells), "**quote**\r\n");
view.move_copy_target(&cells, KeyCode::Up);
assert_eq!(payload(&mut view, &cells), "echo x \r\n \r\n");
}
}
#[test]
fn copy_completion_keeps_payload_count_and_follow_intent() {
let cells: Vec<Arc<dyn HistoryCell>> = vec![Arc::new(AgentMarkdownCell::new(
"**bold**".into(),
Path::new("/"),
))];
for result in [CopyStatus::Confirmed, CopyStatus::Pending(7)] {
let mut view = TranscriptView::default();
render(&mut view, &cells, /*width*/ 40, /*height*/ 5);
view.begin_copy_mode(&cells, /*guard*/ None);
let selected = view.selected_text(&cells).unwrap();
view.copy_selected_text_with(
&cells,
&selected,
/*clear_selection*/ true,
|_, _| Ok(result),
)
.unwrap();
assert_eq!(view.copy_feedback.as_ref().unwrap().characters, 8);
if matches!(result, CopyStatus::Pending(_)) {
assert_eq!(
view.finish_copy(
&cells,
&(7, Ok(CopyStatus::Confirmed)),
/*current*/ true
),
Some(true)
);
view.jump_to_latest();
}
assert!(view.is_following());
let area = ratatui::layout::Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 40, /*height*/ 1,
);
let mut buffer = ratatui::buffer::Buffer::empty(area);
view.render_composer_gap(
Some(area),
/*hint*/ None,
&mut buffer,
std::time::Instant::now(),
);
insta::allow_duplicates! {
insta::assert_snapshot!(text(&buffer).trim(), @"Copied 8 chars to host clipboard");
}
assert_eq!(view.copy_feedback.as_ref().unwrap().characters, 8);
}
}
#[test]
fn find_and_shift_click_release_copy_payload() {
let cells: Vec<Arc<dyn HistoryCell>> = vec![Arc::new(AgentMarkdownCell::new(
"**bold** needle".into(),
Path::new("/"),
))];
for detailed in [false, true] {
let mut view = TranscriptView::default();
view.set_presentation(detailed, crate::history_cell::HistoryRenderMode::Rich);
render(&mut view, &cells, /*width*/ 40, /*height*/ 5);
view.begin_copy_mode(&cells, /*guard*/ None);
view.begin_search();
assert!(view.copy_mode.is_none());
assert!(view.paste_search("needle"));
view.advance_search(&cells);
assert!(
view.footer_with_navigation(/*width*/ 80, crate::motion::MotionMode::Reduced, "")
.unwrap()
.text
.to_string()
.contains("needle")
);
}
let mut view = TranscriptView::default();
render(&mut view, &cells, /*width*/ 40, /*height*/ 5);
view.begin_copy_mode(&cells, /*guard*/ None);
render(&mut view, &cells, /*width*/ 40, /*height*/ 5);
let row = view.area.y
+ view
.visible
.iter()
.position(|row| row.layout.text().contains("needle"))
.unwrap() as u16;
view.extend_selection(/*column*/ 6, row);
assert!(view.copy_mode.is_none());
assert_eq!(payload(&mut view, &cells), "**bold**");
}
#[test]
fn empty_copy_releases_input_guard() {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let guard = Arc::new(crate::copy_input_guard::CopyInputGuard(
crate::app_event_sender::AppEventSender::new(tx),
));
let weak = Arc::downgrade(&guard);
let mut view = TranscriptView::default();
assert!(!view.begin_copy_mode(&[], Some(guard)));
assert!(weak.upgrade().is_none());
assert!(matches!(
rx.try_recv(),
Ok(crate::app_event::AppEvent::TranscriptCopyClosed)
));
}
#[test]
fn copy_input_guard_is_released_on_all_selector_exits() {
let cells: Vec<Arc<dyn HistoryCell>> = vec![Arc::new(AgentMarkdownCell::new(
"response".into(),
Path::new("/"),
))];
for exit in ["escape", "find", "mouse", "confirmed", "presentation"] {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let guard = Arc::new(crate::copy_input_guard::CopyInputGuard(
crate::app_event_sender::AppEventSender::new(tx),
));
let weak = Arc::downgrade(&guard);
let mut view = TranscriptView::default();
render(&mut view, &cells, /*width*/ 40, /*height*/ 5);
view.begin_copy_mode(&cells, Some(guard));
assert!(weak.upgrade().is_some());
match exit {
"escape" => {
view.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE), &cells);
}
"find" => view.begin_search(),
"mouse" => {
view.begin_selection(&cells, /*column*/ 2, /*row*/ 0, /*clicks*/ 1)
}
"confirmed" => {
view.copy_selected_text_with(
&cells,
"response",
/*clear_selection*/ true,
|_, _| Ok(CopyStatus::Confirmed),
)
.unwrap();
}
"presentation" => view.set_presentation(
/*detailed*/ true,
crate::history_cell::HistoryRenderMode::Raw,
),
_ => unreachable!(),
}
assert!(weak.upgrade().is_none(), "{exit}");
assert!(matches!(
rx.try_recv(),
Ok(crate::app_event::AppEvent::TranscriptCopyClosed)
));
}
}
#[test]
fn user_code_blocks_preserve_original_line_endings() {
let cells: Vec<Arc<dyn HistoryCell>> = vec![Arc::new(crate::history_cell::new_user_prompt(
"```sh\r\necho user \r\n```\r\n".into(),
Vec::new(),
Vec::new(),
Vec::new(),
))];
let mut view = TranscriptView::default();
render(&mut view, &cells, /*width*/ 40, /*height*/ 10);
view.begin_copy_mode(&cells, /*guard*/ None);
assert_eq!(payload(&mut view, &cells), "echo user \r\n");
}
#[test]
fn latest_partial_response_owns_its_payload() {
let cells: Vec<Arc<dyn HistoryCell>> = vec![
Arc::new(AgentMarkdownCell::new(
"Previous completed answer".into(),
Path::new("/"),
)),
Arc::new(AgentMarkdownCell::new(
"Interrupted **partial** answer".into(),
Path::new("/"),
)),
];
let mut view = TranscriptView::default();
render(&mut view, &cells, /*width*/ 60, /*height*/ 12);
view.begin_copy_mode(&cells, /*guard*/ None);
assert_eq!(payload(&mut view, &cells), "Interrupted **partial** answer");
}
#[test]
fn source_targets_survive_quotes_lists_and_rendered_tables() {
for (source, expected) in [
(
"> ```sh\n> echo first\n> ```\n\n> later **prose**\n",
vec![
"later **prose**\n",
"echo first\n",
"```sh\necho first\n```\n",
],
),
(
"- ```mermaid\n graph LR\n A --> B\n ```\n",
vec!["graph LR\nA --> B\n"],
),
(
"> first ::git-push{cwd=\"/repo\"}\r\n\r\n> second\r\n",
vec!["first \r\n", "second\r\n"],
),
(
"```md\n| A |\n| --- |\n| x |\n```\n\n```md\n| A |\n| --- |\n| x |\n```\n",
vec!["| A |\n| --- |\n| x |\n", "| A |\n| --- |\n| x |\n"],
),
(
"```md\n| A | B |\n| --- | --- |\n| x | y |\n```\n",
vec!["| A | B |\n| --- | --- |\n| x | y |\n"],
),
] {
for mode in [
crate::history_cell::HistoryRenderMode::Rich,
crate::history_cell::HistoryRenderMode::Raw,
] {
let cells: Vec<Arc<dyn HistoryCell>> = vec![Arc::new(AgentMarkdownCell::new(
source.into(),
Path::new("/"),
))];
let mut view = TranscriptView::default();
view.set_presentation(/*detailed*/ false, mode);
render(&mut view, &cells, /*width*/ 60, /*height*/ 20);
view.begin_copy_mode(&cells, /*guard*/ None);
let mut actual = Vec::new();
for _ in &expected {
view.move_copy_target(&cells, KeyCode::Up);
actual.push(payload(&mut view, &cells));
}
actual.sort();
let mut expected = expected.clone();
expected.sort();
assert_eq!(actual, expected, "{mode:?}: {source}");
}
}
}
#[test]
fn rendered_fenced_table_has_a_block_highlight() {
let cells: Vec<Arc<dyn HistoryCell>> = vec![Arc::new(AgentMarkdownCell::new(
"Before\n\n```md\n| A | B |\n| --- | --- |\n| x | y |\n```\n\nAfter".into(),
Path::new("/"),
))];
let mut view = TranscriptView::default();
render(&mut view, &cells, /*width*/ 30, /*height*/ 10);
view.begin_copy_mode(&cells, /*guard*/ None);
view.move_copy_target(&cells, KeyCode::Up);
let buffer = render(&mut view, &cells, /*width*/ 30, /*height*/ 10);
let style = ratatui::buffer::Cell::default()
.set_style(crate::style::selection_style())
.style();
let rows = buffer
.content
.chunks(30)
.map(|row| {
let mark = if row.iter().all(|cell| cell.style() == style) {
"selected"
} else {
" "
};
format!(
"{mark} | {}",
row.iter()
.map(ratatui::buffer::Cell::symbol)
.collect::<String>()
.trim_end()
)
})
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(rows);
}
#[test]
fn copy_navigation_leaves_context_and_preserves_the_center_band() {
let context = (0..12)
.map(|i| format!("Context {i}\n\n"))
.collect::<String>();
let source = format!(
"{context}```sh\nfirst target\n```\n\n{context}```sh\nsecond target\n```\n\n{context}"
);
let cells: Vec<Arc<dyn HistoryCell>> =
vec![Arc::new(AgentMarkdownCell::new(source, Path::new("/")))];
let mut view = TranscriptView::default();
render(&mut view, &cells, /*width*/ 50, /*height*/ 16);
view.begin_copy_mode(&cells, /*guard*/ None);
for (key, expected_row) in [(KeyCode::Up, 11), (KeyCode::Up, 4), (KeyCode::Down, 11)] {
view.move_copy_target(&cells, key);
let buffer = render(&mut view, &cells, /*width*/ 50, /*height*/ 16);
let selection_style = ratatui::buffer::Cell::default()
.set_style(crate::style::selection_style())
.style();
let selected_rows = buffer
.content
.chunks(50)
.enumerate()
.filter_map(|(row, cells)| {
cells
.iter()
.any(|cell| cell.style() == selection_style)
.then_some(row)
})
.collect::<Vec<_>>();
assert_eq!(selected_rows, vec![expected_row]);
let before = text(&buffer);
view.reveal_copy_context(&cells);
assert_eq!(
text(&render(
&mut view, &cells, /*width*/ 50, /*height*/ 16
)),
before
);
}
let buffer = render(&mut view, &cells, /*width*/ 50, /*height*/ 10);
insta::assert_snapshot!(text(&buffer));
}
#[test]
fn copy_resize_keeps_whole_user_padding_inside_context() {
let user = |message: &str| -> Arc<dyn HistoryCell> {
Arc::new(crate::history_cell::new_user_prompt(
message.into(),
Vec::new(),
Vec::new(),
Vec::new(),
))
};
let cells: Vec<Arc<dyn HistoryCell>> = vec![
user("Earlier prompt"),
Arc::new(AgentMarkdownCell::new(
"Earlier context\n\n".repeat(12),
Path::new("/"),
)),
user("One\nTwo\nThree\nFour\nFive\nSix"),
Arc::new(AgentMarkdownCell::new(
"Later context\n\n".repeat(12),
Path::new("/"),
)),
];
let mut view = TranscriptView::default();
render(&mut view, &cells, /*width*/ 50, /*height*/ 20);
view.begin_copy_mode(&cells, /*guard*/ None);
let len = view.layout(&cells, /*index*/ 2).unwrap().text().len();
view.select_copy_range(&cells, /*index*/ 2, 0..len);
render(&mut view, &cells, /*width*/ 50, /*height*/ 20);
let buffer = render(&mut view, &cells, /*width*/ 50, /*height*/ 10);
let selected = ratatui::buffer::Cell::default()
.set_style(crate::style::selection_style())
.style();
let rows = buffer
.content
.chunks(50)
.enumerate()
.filter_map(|(row, cells)| {
cells
.iter()
.any(|cell| cell.style() == selected)
.then_some(row)
})
.collect::<Vec<_>>();
assert!(!rows.is_empty());
assert!(
rows[0] > 0 && *rows.last().unwrap() < 9,
"selected rows: {rows:?}"
);
insta::assert_snapshot!(text(&buffer));
}
#[test]
fn copy_navigation_keeps_bottom_context_when_prompt_header_appears() {
let cells: Vec<Arc<dyn HistoryCell>> = vec![
Arc::new(crate::history_cell::new_user_prompt(
"First prompt".into(),
Vec::new(),
Vec::new(),
Vec::new(),
)),
Arc::new(AgentMarkdownCell::new(
format!(
"{}\n```sh\necho target\n```\n\nLater context",
"Earlier context\n\n".repeat(/*n*/ 12)
),
Path::new("/"),
)),
];
let mut view = TranscriptView::default();
render(&mut view, &cells, /*width*/ 50, /*height*/ 7);
view.begin_copy_mode(&cells, /*guard*/ None);
view.move_copy_target(&cells, KeyCode::Home);
render(&mut view, &cells, /*width*/ 50, /*height*/ 7);
view.move_copy_target(&cells, KeyCode::Down);
let buffer = render(&mut view, &cells, /*width*/ 50, /*height*/ 7);
let rows = text(&buffer);
assert_eq!(
rows.lines().position(|line| line.contains("echo target")),
Some(5)
);
assert_eq!(
text(&render(
&mut view, &cells, /*width*/ 50, /*height*/ 7
)),
rows
);
}
@@ -20,6 +20,17 @@ impl TranscriptView {
motion: MotionMode,
latest_navigation: &str,
) -> Option<TranscriptFooter> {
if let Some(mode) = &self.copy_mode {
return Some(TranscriptFooter {
text: vec![
Line::from(format!("Copy {}", mode.label.to_lowercase())).bold(),
navigation_line("↑/↓/j/k select · g/G ends · enter copy · esc close"),
]
.into(),
cursor_column: None,
is_interactive: true,
});
}
// A mouse-down anchor owns the gesture, but has no text to copy yet. Compare
// source positions so movement across wrapping or padding is not a selection.
let has_selected_text = self.selection.as_ref().is_some_and(|selection| {
+7 -1
View File
@@ -135,6 +135,9 @@ impl TranscriptView {
{
return true;
}
if self.copy_mode.is_some() {
return true;
}
if self.selection.is_some() {
return crate::text_selection::is_copy_key(key)
|| code == KeyCode::Esc
@@ -164,6 +167,9 @@ impl TranscriptView {
if key.kind == KeyEventKind::Release {
return None;
}
if let Some(action) = self.handle_copy_mode_key(key, cells) {
return Some(action);
}
if let Some(action) = self.handle_disclosure_key(key, cells) {
return Some(action);
}
@@ -336,7 +342,7 @@ impl TranscriptView {
self.handle_scroll_key(key, cells)
}
fn handle_scroll_key(
pub(super) fn handle_scroll_key(
&mut self,
key: KeyEvent,
cells: &[Arc<dyn HistoryCell>],
@@ -102,6 +102,7 @@ impl TranscriptView {
if self.is_search_editing() {
return;
}
self.copy_mode = None;
let saved_position = self.position;
let saved_snapshot = self
.selection
+86 -5
View File
@@ -20,6 +20,7 @@ struct PendingCopy {
detailed: bool,
follow: bool,
clear_selection: bool,
characters: usize,
}
pub(super) struct Selection {
@@ -41,6 +42,49 @@ pub(super) struct Selection {
}
impl TranscriptView {
pub(super) fn select_copy_range(
&mut self,
cells: &[Arc<dyn HistoryCell>],
index: usize,
range: std::ops::Range<usize>,
) {
let Some(layout) = self.layout(cells, index) else {
return;
};
let key = self.entry_key(cells, index);
let start = Anchor {
key,
index,
offset: range.start,
row_bias: 0,
};
let end = Anchor {
offset: range.end,
..start
};
let mut snapshot = self.capture_snapshot(cells);
snapshot.pinned.retain(|key, _| *key == EntryKey::Live);
snapshot.pinned.insert(key, layout);
self.selection = Some(Selection {
pending_copy: None,
primary_owner: None,
snapshot,
start,
end,
dragging: false,
moved: false,
moved_vertically: false,
pointer_origin_row: 0,
resume_on_empty: false,
pointer: None,
pressed_link: None,
origin: (start, end),
unit: SelectionUnit::Character,
preferred_column: None,
});
self.reveal_copy_context(cells);
}
pub(super) fn begin_selection(
&mut self,
cells: &[Arc<dyn HistoryCell>],
@@ -48,6 +92,7 @@ impl TranscriptView {
row: u16,
clicks: u8,
) {
self.copy_mode = None;
let Some((anchor, layout)) = self.hit_test(column, row) else {
return;
};
@@ -90,6 +135,7 @@ impl TranscriptView {
/// Rejoin current history, retaining Find offsets or a replaced group until navigation.
/// Real selections keep their reading position, including a retired live revision.
pub(crate) fn end_selection(&mut self, cells: &[Arc<dyn HistoryCell>]) {
self.copy_mode = None;
let Some(selection) = self.selection.take() else {
return;
};
@@ -133,6 +179,7 @@ impl TranscriptView {
let Some(mut selection) = self.selection.take() else {
return;
};
self.copy_mode = None;
// A Shift-click starts a new pointer gesture while retaining the text anchor.
if !selection.dragging {
selection.pointer_origin_row = row;
@@ -297,12 +344,33 @@ impl TranscriptView {
layout.copy_lines(range, separator, &mut lines);
previous = Some(layout);
}
let (text, format) = crate::markdown_copy::selection(&lines, text);
let override_payload = self.copy_mode.as_ref().and_then(|mode| {
if mode.whole {
mode.response.as_ref().map(|(_, text)| {
(
text.to_string(),
crate::clipboard_copy::CopyFormat::Markdown,
)
})
} else {
mode.source
.as_ref()
.map(|text| (text.clone(), crate::clipboard_copy::CopyFormat::PlainText))
}
});
let (text, format) =
override_payload.unwrap_or_else(|| crate::markdown_copy::selection(&lines, text));
let characters = text.chars().count();
let result = copy(&text, format);
self.show_copy_feedback(&result, characters);
match result {
Ok(crate::clipboard_copy::CopyStatus::Confirmed) => {
if clear_selection {
let copy_mode = self.copy_mode.is_some();
self.end_selection(cells);
if copy_mode {
self.jump_to_latest();
}
}
}
Ok(crate::clipboard_copy::CopyStatus::Pending(id)) => {
@@ -313,8 +381,9 @@ impl TranscriptView {
end: selection.end,
position: self.position,
detailed: self.detailed,
follow: false,
follow: clear_selection && self.copy_mode.is_some(),
clear_selection,
characters,
});
}
}
@@ -369,9 +438,7 @@ impl TranscriptView {
{
return None;
}
let characters = self
.selected_text(cells)
.map_or(/*default*/ 0, |text| text.chars().count());
let characters = pending.characters;
if pending.clear_selection
&& completion.1 == Ok(crate::clipboard_copy::CopyStatus::Confirmed)
{
@@ -525,6 +592,20 @@ impl TranscriptView {
self.area.width,
/*height*/ 1,
);
if self.copy_mode.is_some() {
// Full-entry selections include final padding; partial ranges stay half-open.
let last = if begin == 0 && finish == visible.layout.text().len() {
finish
} else {
finish.saturating_sub(/*rhs*/ 1)
};
let rows =
visible.layout.row_for_offset(begin)..=visible.layout.row_for_offset(last);
if rows.contains(&visible.row) {
buf.set_style(area, crate::style::selection_style());
}
continue;
}
let next = (visible.index + 1..=end.index)
.filter_map(|index| {
selection
@@ -0,0 +1,30 @@
---
source: tui/src/transcript_view/copy_mode_tests.rs
assertion_line: 169
expression: "snapshots.join(\"\\n---\\n\")"
---
................ | • Before
................ |
################ | longer line
################ |
################ | x
................ |
................ | After
................ |
................ |
................ |
................ |
................ |
---
........ | • Before
........ |
######## | longer
######## | line
######## |
######## | x
........ |
........ | After
........ |
........ |
........ |
........ |
@@ -0,0 +1,14 @@
---
source: tui/src/transcript_view/copy_mode_tests.rs
expression: text(&buffer)
---
Context 9
Context 10
Context 11
second target
Context 0
@@ -0,0 +1,13 @@
---
source: tui/src/transcript_view/copy_mode_tests.rs
assertion_line: 620
expression: text(&buffer)
---
› One
Two
Three
Four
Five
Six
@@ -0,0 +1,15 @@
---
source: tui/src/transcript_view/copy_mode_tests.rs
assertion_line: 568
expression: rows
---
| • Before
|
selected | A B
selected | ━━━━━ ━━━━━
selected | x y
|
| After
|
|
|
@@ -0,0 +1,18 @@
---
source: tui/src/transcript_view/copy_mode_tests.rs
assertion_line: 235
expression: "snapshots.join(\"\\n---\\n\")"
---
#################### |
#################### | › Short prompt
#################### |
.................... |
---
########## |
########## | › Longer
########## | message
########## |
########## | last
########## |
.......... |
.......... |
+56
View File
@@ -69,6 +69,62 @@ struct TextRow {
}
impl TextLayout {
pub(super) fn copy_block_ranges(&self) -> Vec<(Range<usize>, &'static str, Option<String>)> {
let mut ranges = Vec::new();
for (label, code) in [("Code block", true), ("Blockquote", false)] {
let mut active: Option<(Range<usize>, Option<std::sync::Arc<str>>)> = None;
let mut offset = 0;
for line in &self.logical {
let end = offset + line.origin.range.len();
let metadata = line.origin.copy.as_deref();
let matches = metadata.is_some_and(|copy| {
if code {
copy.code || copy.code_source.is_some()
} else {
copy.prefix.contains('>')
}
});
if matches {
let source = metadata.and_then(|copy| {
if code {
copy.code_source.as_ref()
} else {
copy.quote_source.as_ref()
}
});
// Shared source identity survives wrapping and separates adjacent blocks,
// including equal payloads. A list marker can precede the first source row.
if let Some(source) = source
&& active
.as_ref()
.and_then(|(_, retained)| retained.as_ref())
.is_some_and(|retained| !std::sync::Arc::ptr_eq(retained, source))
&& let Some((range, retained)) = active.take()
{
ranges.push((range, label, retained.map(|source| source.to_string())));
}
let (range, retained) = active.get_or_insert((offset..end, None));
range.end = end;
if retained.is_none() {
*retained = source.cloned();
}
} else if let Some((range, source)) = active.take() {
ranges.push((range, label, source.map(|source| source.to_string())));
}
offset = end + 1;
}
if let Some((range, source)) = active {
ranges.push((range, label, source.map(|source| source.to_string())));
}
}
ranges.retain(|(range, _, _)| {
self.text
.get(range.clone())
.is_some_and(|text| !text.trim().is_empty())
});
ranges
}
pub(super) fn new(lines: Vec<HyperlinkLine>, width: u16) -> Self {
let logical = logical_lines(&lines);
Self::from_logical(logical, width)