Open /diff in a TUI sidebar tab (#64258)

## Why

The full-screen diff pager takes the conversation off screen. A sidebar tab lets users review working-tree changes alongside the conversation.

## What changed

- Open a read-only `Diff` tab when the sidebar is available, and fall back to the full-screen pager otherwise.
- Reuse the tab on repeated runs. Keep the previous patch visible while Git runs, preserve the reading position on refresh, and apply only the latest result without stealing focus.
- Render large patches in chunks and derive scroll indicators from visible rows so redraws can skip layout of the off-screen tail.

## Testing

Cover tab reuse, stale result handling, and the visibility of the last hunk across resize and refresh. Verify that scroll indicators render without laying out the off-screen tail.

GitOrigin-RevId: 812ea99896dfd3131af9cf356cb844f4f0f7c267
This commit is contained in:
Felipe Coury
2026-11-27 04:54:59 +00:00
committed by copyberry
parent fe6dca3422
commit cd30214700
17 changed files with 706 additions and 121 deletions
+8 -2
View File
@@ -1732,12 +1732,18 @@ impl App {
self.enqueue_thread_history_entry_response(thread_id, event)
.await?;
}
AppEvent::OpenDiff { thread_id, cwd } => {
if thread_id == self.chat_widget.thread_id() && &cwd == self.chat_widget.session_cwd() {
Box::pin(self.open_diff(tui, app_server, thread_id, cwd)).await?;
}
}
AppEvent::SidebarDiffLoaded { request, text } => {
self.finish_sidebar_diff(tui, app_server.backend_id(), request, text).await;
}
AppEvent::DiffResult { thread_id, cwd, text } => {
if thread_id != self.chat_widget.thread_id() || &cwd != self.chat_widget.session_cwd() {
return Ok(AppRunControl::Continue);
}
// Clear the in-progress state in the bottom pane
self.chat_widget.on_diff_complete();
// Enter alternate screen using TUI helper and build pager lines
let _ = tui.enter_alt_screen();
let pager_lines: Vec<ratatui::text::Line<'static>> = if text.trim().is_empty() {
+3
View File
@@ -465,6 +465,9 @@ impl App {
for (parent, pane) in &mut self.sidebars {
pane.focus_document_request = None;
pane.agents.pending_link = None;
if let Some(tab) = pane.diff_tab() {
pane.remove_document(tab);
}
for (tab, doc) in &mut pane.documents {
if let Some(parent) = parent
&& doc.backend == session.backend_id()
+10 -6
View File
@@ -213,6 +213,10 @@ impl App {
self.sidebar_mut()
.show(SidebarContent::Chooser, PaneFocus::Sidebar);
self.activate_sidebar_tab(tui, server, previous).await?;
} else if pane.visible_content().is_none() {
// Closing the last Diff tab dismisses the pane.
self.zoomed_thread = None;
self.focus_current_parent_view(tui);
} else {
self.open_sidebar_tabs(tui, server).await?;
}
@@ -278,14 +282,14 @@ impl App {
} else {
None
};
let document_shortcut = document.is_some_and(|id| {
self.sidebar()
.and_then(|pane| pane.documents.get(&id))
.is_some_and(|doc| doc.allows_tab_shortcut(key, &self.keymap))
});
let doc = document.and_then(|id| self.sidebar()?.documents.get(&id));
let document_shortcut = doc.is_some_and(|doc| doc.allows_tab_shortcut(key, &self.keymap));
let close = if let Some(id) = document {
(bindings.close_sidebar_tab.is_pressed(key)
|| (document_shortcut && crate::key_hint::plain(KeyCode::Esc).is_press(key)))
|| (document_shortcut
&& (crate::key_hint::plain(KeyCode::Esc).is_press(key)
|| (doc.is_some_and(sidebar_document::Document::is_diff)
&& self.keymap.pager.close.is_pressed(key)))))
.then_some(SidebarTab::Document(id))
} else if bindings.close_sidebar_tab.is_pressed(key) {
self.current_displayed_thread_id().and_then(|id| {
+18 -3
View File
@@ -401,16 +401,25 @@ impl SidebarPane {
self.documents.get_mut(&id)
}
pub(super) fn diff_tab(&self) -> Option<uuid::Uuid> {
self.documents
.iter()
.find_map(|(&id, doc)| doc.is_diff().then_some(id))
}
pub(super) fn document_title(&self, id: uuid::Uuid, width: usize) -> String {
let Some(document) = self.documents.get(&id) else {
return String::new();
};
if document.is_diff() {
return "Diff".to_owned();
}
let path = document.path.inferred_native_path_string();
let parts: Vec<_> = path.rsplit(['/', '\\']).collect();
let depth = self
.documents
.values()
.filter(|other| other.path != document.path)
.filter(|other| !other.is_diff() && other.path != document.path)
.map(|other| {
parts
.iter()
@@ -427,7 +436,7 @@ impl SidebarPane {
let mut index = 1;
let mut collision = false;
for (&other_id, other) in &self.documents {
if other_id == id {
if other_id == id || other.is_diff() {
continue;
}
let other_path = other.path.inferred_native_path_string();
@@ -459,11 +468,17 @@ impl SidebarPane {
}
pub(super) fn remove_document(&mut self, id: uuid::Uuid) {
self.documents.remove(&id);
let is_diff = self.documents.remove(&id).is_some_and(|doc| doc.is_diff());
let tab = SidebarTab::Document(id);
self.tabs.retain(|other| *other != tab);
self.visits.retain(|other| *other != tab);
self.tabs_revision += 1;
if is_diff && self.content == SidebarContent::Document(id) {
self.content = SidebarContent::Chooser;
self.focus = None;
self.hidden = false;
self.motion = PaneMotion::default();
}
}
pub(super) fn close_agents(&mut self) -> bool {
+104 -39
View File
@@ -1,5 +1,6 @@
//! Read-only Markdown previews use the focused thread's workspace and app-server.
//! Sidebar files and working tree diffs share a reader. Only file tabs subscribe to changes.
mod diff;
pub(super) mod footer;
pub(super) mod model_read;
mod open_error;
@@ -131,10 +132,18 @@ struct ModelLoad {
_cancel: oneshot::Sender<()>,
}
enum DocumentSource {
File {
thread: ThreadId,
original_path: AppServerPath,
},
Diff(diff::DiffSource),
}
pub(super) struct Document {
source: ThreadId,
source: DocumentSource,
/// The file path, or the working directory of the conversation that ran `/diff`.
pub(super) path: PathUri,
original_path: AppServerPath,
pub(super) watch: Option<(uuid::Uuid, tokio::sync::watch::Sender<()>)>,
pub(super) backend: crate::backend_id::BackendId,
link: Option<usize>,
@@ -155,13 +164,39 @@ enum State {
Image(Box<SidebarImage>),
Ready {
view: Box<TranscriptView>,
cells: [Arc<dyn HistoryCell>; 1],
cells: Vec<Arc<dyn HistoryCell>>,
line_starts: Vec<usize>,
target: Option<DocumentTarget>,
},
}
impl Document {
fn new(
source: DocumentSource,
path: PathUri,
backend: crate::backend_id::BackendId,
location: Option<SourceLocation>,
state: State,
access: DocumentAccess,
) -> Self {
Self {
source,
path,
watch: None,
backend,
link: None,
location,
highlight_dismissed: false,
state,
access,
path_actions: PathActions::default(),
}
}
pub(super) fn is_diff(&self) -> bool {
matches!(self.source, DocumentSource::Diff(_))
}
pub(super) fn link_at(&self, column: u16, row: u16) -> Option<ReaderLink> {
if self.path_actions.scroll.is_some() {
return None;
@@ -193,6 +228,9 @@ impl Document {
}
pub(super) fn path_actions_available(&self) -> bool {
if self.is_diff() {
return false;
}
match &self.state {
State::AwaitingOpen => false,
State::Ready { view, .. } => self.link.is_none() && !view.has_active_interaction(),
@@ -250,10 +288,13 @@ impl Document {
else {
return;
};
let DocumentSource::File { thread, .. } = self.source else {
return;
};
let initial = Arc::clone(&initial.permissions);
self.access = DocumentAccess::Model { load: None };
let result = match result {
Ok(content) => match server.model_preview_permissions(self.source).await {
Ok(content) => match server.model_preview_permissions(thread).await {
Ok(Some(current))
if initial.profile == current.profile
&& initial.workspace_roots == current.workspace_roots =>
@@ -282,12 +323,37 @@ impl Document {
}
}
pub(super) fn loaded(&mut self, result: Result<DocumentContent>) {
let position = match &self.state {
fn position(&self) -> Option<DocumentPosition> {
match &self.state {
State::Ready { view, .. } => Some(view.document_position()),
State::Failed { position, .. } => *position,
State::AwaitingOpen | State::Loading(_) | State::Image(_) => None,
};
}
}
fn ready(
&self,
cells: Vec<Arc<dyn HistoryCell>>,
line_starts: Vec<usize>,
target: Option<DocumentTarget>,
) -> State {
let mut view = Box::<TranscriptView>::default();
view.document_links = !self.is_diff();
view.show_follow_control = false;
match self.position() {
Some(position) => view.restore_document_position(&cells, position),
None => view.jump_to_offset(&cells, target.map_or(0, |target| target.offset)),
}
State::Ready {
view,
cells,
line_starts,
target,
}
}
pub(super) fn loaded(&mut self, result: Result<DocumentContent>) {
let position = self.position();
self.state = match result {
Ok(DocumentContent::Image(image)) => State::Image(image),
Ok(DocumentContent::Text(source)) => {
@@ -340,21 +406,11 @@ impl Document {
.location
.filter(|_| !self.highlight_dismissed)
.and_then(|loc| source_target(&source, &line_starts, loc));
let cells: [Arc<dyn HistoryCell>; 1] = [Arc::new(FileCell { source, language })];
let mut view = Box::<TranscriptView>::default();
view.document_links = true;
view.show_follow_control = false;
match position {
Some(DocumentPosition::Latest) => view.jump_to_latest(),
Some(DocumentPosition::Offset(offset)) => view.jump_to_offset(&cells, offset),
None => view.jump_to_offset(&cells, target.map_or(0, |target| target.offset)),
}
State::Ready {
view,
cells,
self.ready(
vec![Arc::new(FileCell { source, language })],
line_starts,
target,
}
)
}
Err(error) => State::Failed { error, position },
};
@@ -536,6 +592,7 @@ impl Document {
line_starts,
target,
} => {
let refreshing = matches!(&self.source, DocumentSource::Diff(source) if source.pending.is_some());
view.set_document_resize_preview(resize_preview);
view.set_keymap_bindings(keymap);
if view.tick_selection(cells) {
@@ -568,7 +625,8 @@ impl Document {
if self.link.is_some() && available(KeyCode::Enter) {
hints.push(Hint::key("enter", "open link"));
}
let link = available(KeyCode::Tab).then(|| Hint::key("Tab", "link"));
let link = (view.document_links && available(KeyCode::Tab))
.then(|| Hint::key("Tab", "link"));
hints.extend(footer::reading_hints(
keymap,
footer::PagerHints::WithChords,
@@ -622,9 +680,17 @@ impl Document {
let gap =
(gap_height > 0).then(|| Rect::new(body.x, content.bottom(), body.width, 1));
view.paint_document_scroll_indicators(content, buf, cells);
if let Some(delay) = view.render_composer_gap(gap, /*hint*/ None, buf, now) {
if let Some(delay) = view.render_composer_gap(
gap.filter(|_| !refreshing),
/*hint*/ None,
buf,
now,
) {
frames.schedule_frame_in(delay);
}
if refreshing && let Some(gap) = gap {
Line::from("Refreshing…".dim()).render(gap, buf);
}
if height > 0 {
let footer_area =
Rect::new(body.x, content.bottom() + gap_height, body.width, height);
@@ -798,7 +864,7 @@ impl App {
let existing = self.sidebar().and_then(|pane| {
pane.documents
.iter()
.find(|(_, doc)| doc.backend == backend_id && doc.path == path)
.find(|(_, doc)| !doc.is_diff() && doc.backend == backend_id && doc.path == path)
.map(|(&id, _)| id)
});
if let Some(id) = existing {
@@ -811,8 +877,7 @@ impl App {
doc.go_to(location);
return Some(id);
}
(DocumentOrigin::Model { permissions: Ok(_) }, DocumentAccess::User)
if doc.source == source =>
(DocumentOrigin::Model { permissions: Ok(_) }, DocumentAccess::User) if matches!(doc.source, DocumentSource::File { thread, .. } if thread == source) =>
{
// The user already authorized this tab. Keep the watch and use its content.
if location.is_some() {
@@ -908,19 +973,17 @@ impl App {
if matches!(access, DocumentAccess::User) && !pane.opened_files.contains(&path) {
pane.opened_files.push(path.clone());
}
let mut doc = Document {
source,
let mut doc = Document::new(
DocumentSource::File {
thread: source,
original_path,
},
path,
original_path,
watch: None,
backend: backend_id,
link: None,
backend_id,
location,
highlight_dismissed: false,
state,
access,
path_actions: PathActions::default(),
};
);
doc.subscribe(request, parent, server, tx);
pane.documents.insert(request, doc);
pane.add_document_tab(request);
@@ -1000,6 +1063,7 @@ impl App {
tui.frame_requester().schedule_frame();
return true;
}
let path_actions_available = doc.path_actions_available();
if let State::Ready {
view,
cells,
@@ -1034,7 +1098,8 @@ impl App {
{
doc.link = None;
Some(ViewAction::Changed)
} else if !view.has_active_interaction()
} else if view.document_links
&& !view.has_active_interaction()
&& let (code @ (KeyCode::Tab | KeyCode::BackTab), KeyModifiers::NONE) =
crate::key_hint::normalize_key_parts(key.code, key.modifiers)
{
@@ -1045,7 +1110,7 @@ impl App {
&& let Some(index) = doc.link.take()
{
view.document_link(cells, index).map(ViewAction::from)
} else if doc.link.is_none() && !view.has_active_interaction() {
} else if path_actions_available {
doc.path_actions.handle_key(*key, &doc.path, tui);
None
} else {
@@ -1060,7 +1125,7 @@ impl App {
}
}
} else {
if doc.path_actions_available() {
if path_actions_available {
doc.path_actions.handle_key(*key, &doc.path, tui);
}
None
@@ -1135,13 +1200,13 @@ impl App {
match action {
Some(ViewAction::OpenDocument(link)) => {
if let Some(doc) = pane.documents.get(&id)
&& let DocumentSource::File { thread: source, .. } = doc.source
&& let Some(parent) = doc.path.parent()
{
let result = match LegacyAppPathString::from_string(link.path)
.resolve_against(&parent, /*user_home_dir*/ None)
{
Ok(path) if !path.to_url().has_host() => {
let source = doc.source;
let original_path =
AppServerPath::from_app_server(path.inferred_native_path_string());
self.open_resolved_document(
@@ -0,0 +1,175 @@
//! Manual working tree diffs use the invoking session's Git runner. Selecting the tab is
//! synchronous with the request, so a background completion only replaces its reader content.
use super::*;
use crate::backend_id::BackendId;
use crate::get_git_diff::get_git_diff;
use itertools::Itertools;
use tokio_util::task::AbortOnDropHandle;
use uuid::Uuid;
#[cfg(test)]
#[path = "diff_tests.rs"]
mod tests;
pub(super) struct DiffSource {
thread: Option<ThreadId>,
pub(super) pending: Option<(Uuid, AbortOnDropHandle<()>)>,
}
/// Keep the entire patch in order, but only decode ANSI and lay out nearby lines
/// as the reader scrolls. Continuations avoid blank rows between chunks.
#[derive(Debug)]
struct DiffChunk(String);
impl HistoryCell for DiffChunk {
fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
self.raw_lines()
}
fn raw_lines(&self) -> Vec<Line<'static>> {
if self.0.is_empty() {
vec!["No changes detected.".italic().into()]
} else {
self.0.lines().map(ansi_escape_line).collect()
}
}
fn is_stream_continuation(&self) -> bool {
true
}
}
fn cells(text: &str) -> Vec<Arc<dyn HistoryCell>> {
const LINES_PER_CHUNK: usize = 128;
if text.trim().is_empty() {
return vec![Arc::new(DiffChunk(String::new()))];
}
text.split_inclusive('\n')
.chunks(LINES_PER_CHUNK)
.into_iter()
.map(|chunk| Arc::new(DiffChunk(chunk.collect())) as Arc<dyn HistoryCell>)
.collect()
}
impl App {
pub(in crate::app) async fn open_diff(
&mut self,
tui: &mut tui::Tui,
server: &mut AppServerSession,
thread_id: Option<ThreadId>,
cwd: PathUri,
) -> Result<()> {
let runner = self.workspace_command_runner.clone();
let profile = self.chat_widget.diff_permission_profile();
let path = cwd.to_path_buf();
let load = async move {
let Some(runner) = runner else {
return "Failed to compute diff: workspace command runner unavailable".into();
};
match get_git_diff(runner.as_ref(), &path, profile.as_deref()).await {
Ok((true, text)) => text,
Ok((false, _)) => "`/diff` — _not inside a git repository_".into(),
Err(error) => format!("Failed to compute diff: {error}"),
}
};
let tx = self.app_event_tx.clone();
if !self.side_retention_enabled(tui) || !self.sidebar_chooser_available() {
tokio::spawn(async move {
tx.send(AppEvent::DiffResult {
thread_id,
cwd,
text: load.await,
});
});
return Ok(());
}
let backend = server.backend_id();
let request = Uuid::new_v4();
let task = tokio::spawn(async move {
tx.send(AppEvent::SidebarDiffLoaded {
request,
text: load.await,
});
});
let source = DocumentSource::Diff(DiffSource {
thread: thread_id,
pending: Some((request, AbortOnDropHandle::new(task))),
});
let parent = self.sidebar_parent();
let pane = self.sidebar_mut();
let tab = pane.diff_tab().unwrap_or(request);
if let Some(doc) = pane.documents.get_mut(&tab)
&& doc.backend == backend
&& doc.path == cwd
&& matches!(&doc.source, DocumentSource::Diff(s) if s.thread.or(parent) == thread_id)
{
doc.source = source;
} else {
pane.documents.insert(
tab,
Document::new(
source,
cwd,
backend,
/*location*/ None,
State::Loading(Instant::now()),
DocumentAccess::User,
),
);
}
pane.add_document_tab(tab);
self.activate_sidebar_tab(tui, server, SidebarTab::Document(tab))
.await
}
pub(in crate::app) async fn finish_sidebar_diff(
&mut self,
tui: &mut tui::Tui,
backend: BackendId,
request: Uuid,
text: String,
) {
// Looking up the request in its pane also covers the startup pane moving to the
// first thread while Git runs.
let Some((parent, tab, thread, owner, cwd)) =
self.sidebars.iter().find_map(|(&parent, pane)| {
pane.documents.iter().find_map(|(&tab, doc)| {
let DocumentSource::Diff(source) = &doc.source else {
return None;
};
(source.pending.as_ref()?.0 == request).then_some((
parent,
tab,
source.thread.or(parent),
doc.backend,
&doc.path,
))
})
})
else {
return;
};
let current = if thread == self.chat_widget.thread_id() {
owner == backend && cwd == self.chat_widget.session_cwd()
} else if let Some(id) = thread {
self.thread_backend_id(id).unwrap_or(backend) == owner
&& self.thread_cwd(id).await.as_ref() == Some(cwd)
} else {
false
};
let Some(pane) = self.sidebars.get_mut(&parent) else {
return;
};
if !current {
pane.remove_document(tab);
} else if let Some(doc) = pane.documents.get_mut(&tab) {
if let DocumentSource::Diff(source) = &mut doc.source {
source.pending = None;
}
doc.state = doc.ready(cells(&text), Vec::new(), /*target*/ None);
}
tui.frame_requester().schedule_frame();
}
}
@@ -0,0 +1,188 @@
#![cfg(test)]
use super::*;
use crate::app::test_support::enable_side_retention;
use crate::app::test_support::side_frame;
use crate::app::tests::make_test_app_with_channels;
use crate::app::tests::test_thread_session;
use crate::slash_command::SlashCommand;
use crate::test_support::boxed_future;
use codex_app_server_client::AppServerClient;
use pretty_assertions::assert_eq;
use ratatui::layout::Size;
use tokio::sync::mpsc::UnboundedReceiver;
async fn invoke(
app: &mut App,
tui: &mut tui::Tui,
server: &mut AppServerSession,
events: &mut UnboundedReceiver<AppEvent>,
) -> Result<Uuid> {
app.chat_widget.dispatch_command(SlashCommand::Diff);
loop {
let event = events.recv().await.unwrap();
match event {
AppEvent::OpenDiff { .. } => {
boxed_future!(app.handle_event(tui, server, event)).await?;
}
AppEvent::SidebarDiffLoaded { request, .. } => return Ok(request),
AppEvent::DiffResult { .. } => panic!("expected sidebar"),
_ => {}
}
}
}
#[tokio::test]
async fn slash_diff_opens_one_reader_and_only_the_latest_result_updates_it() -> Result<()> {
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
let (client, _commands, _events) =
codex_app_server_client::CloudClient::channel(/*capacity*/ 1);
let mut server = AppServerSession::new(
BackendId::new(),
AppServerClient::Cloud(client),
crate::ThreadParamsMode::Cloud,
);
let thread = ThreadId::new();
let local_session = test_thread_session(thread, app.config.cwd.to_path_buf());
let mut remote_session = local_session.clone();
let foreign_path = if cfg!(windows) { "/repo" } else { r"D:\repo" };
remote_session.cwd = PathUri::try_from(LegacyAppPathString::from_string(foreign_path))?;
app.chat_widget.handle_thread_session(remote_session);
enable_side_retention(&mut app)?;
app.local_settings.tui.animations = false;
let mut tui = crate::tui::test_support::make_test_tui()?;
tui.set_owned_screen(/*owned*/ true)?;
let wide = Size::new(/*width*/ 110, /*height*/ 12);
let narrow = Size::new(/*width*/ 42, /*height*/ 12);
let complete = |request, patch: &str| AppEvent::SidebarDiffLoaded {
request,
text: patch.to_owned(),
};
let patch = "diff --git a/fees.rs b/fees.rs\n\x1b[36m@@ -1 +1 @@\x1b[m\n\x1b[31m-const FEE: u32 = 5;\x1b[m\n\x1b[32m+const FEE: u32 = 7;\x1b[m\n";
let first = invoke(&mut app, &mut tui, &mut server, &mut events).await?;
assert_eq!(app.panel_focus(), Some(PaneFocus::Sidebar));
assert!(side_frame(&mut app, &mut tui, wide)?.contains("Opening…"));
let latest = invoke(&mut app, &mut tui, &mut server, &mut events).await?;
boxed_future!(app.handle_event(&mut tui, &mut server, complete(latest, patch))).await?;
boxed_future!(app.handle_event(&mut tui, &mut server, complete(first, "old patch"))).await?;
let small = side_frame(&mut app, &mut tui, narrow)?;
let buf = tui.terminal.previous_buffer();
for (label, fg) in [
("-const", ratatui::style::Color::Red),
("+const", ratatui::style::Color::Green),
] {
let (row, col) = small
.lines()
.enumerate()
.find_map(|(y, l)| l.find(label).map(|x| (y, x)))
.unwrap();
assert_eq!(buf[(col as u16, row as u16)].fg, fg);
}
let refresh = invoke(&mut app, &mut tui, &mut server, &mut events).await?;
let refreshing = side_frame(&mut app, &mut tui, narrow)?;
assert!(refreshing.contains("Refreshing…"));
assert!(refreshing.contains("+const FEE: u32 = 7;"));
app.focus_workspace_composer(&mut tui);
let updated = patch.replace("= 7", "= 8");
boxed_future!(app.handle_event(&mut tui, &mut server, complete(refresh, &updated))).await?;
assert_eq!(app.panel_focus(), Some(PaneFocus::Main));
let split = side_frame(&mut app, &mut tui, wide)?;
assert!(!split.contains("Refreshing…"));
let sidebar_text = |frame: &str| {
frame
.lines()
.filter_map(|l| l.split_once('│').map(|(_, rhs)| rhs))
.collect::<Vec<_>>()
.join("\n")
};
let sidebar = sidebar_text(&split);
let clean = invoke(&mut app, &mut tui, &mut server, &mut events).await?;
boxed_future!(app.handle_event(&mut tui, &mut server, complete(clean, ""))).await?;
assert!(side_frame(&mut app, &mut tui, wide)?.contains("No changes detected."));
let pending = invoke(&mut app, &mut tui, &mut server, &mut events).await?;
app.focus_workspace_composer(&mut tui);
let refreshing_clean = side_frame(&mut app, &mut tui, wide)?;
assert!(refreshing_clean.contains("No changes detected."));
assert!(refreshing_clean.contains("Refreshing…"));
let refreshing_clean = sidebar_text(&refreshing_clean);
insta::assert_snapshot!(
"slash_diff_sidebar",
format!(
"Focused at 42 columns\n{small}\n\nRefreshing at 42 columns\n{refreshing}\n\nRefreshed beside chat\n{sidebar}\n\nRefreshing a clean tree beside chat\n{refreshing_clean}"
)
);
let tab = SidebarTab::Document(app.sidebar().unwrap().diff_tab().unwrap());
app.activate_sidebar_tab(&mut tui, &mut server, tab).await?;
boxed_future!(app.handle_tui_event(
&mut tui,
&mut server,
TuiEvent::Key(KeyCode::Char('q').into())
))
.await?;
boxed_future!(app.handle_event(&mut tui, &mut server, complete(pending, patch))).await?;
assert_eq!(app.panel_focus(), None);
assert!(
app.sidebar()
.unwrap()
.recent_tab(/*excluding*/ None)
.is_none()
);
let pending = invoke(&mut app, &mut tui, &mut server, &mut events).await?;
app.chat_widget.handle_thread_session(local_session);
boxed_future!(app.handle_event(&mut tui, &mut server, complete(pending, patch))).await?;
assert_eq!(app.panel_focus(), None);
assert!(
app.sidebar()
.unwrap()
.recent_tab(/*excluding*/ None)
.is_none()
);
Ok(())
}
#[tokio::test]
async fn large_diff_keeps_its_last_hunk_visible_across_resize_and_refresh() -> Result<()> {
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
let (client, _commands, _events) =
codex_app_server_client::CloudClient::channel(/*capacity*/ 1);
let mut server = AppServerSession::new(
BackendId::new(),
AppServerClient::Cloud(client),
crate::ThreadParamsMode::Cloud,
);
enable_side_retention(&mut app)?;
app.local_settings.tui.animations = false;
let mut tui = crate::tui::test_support::make_test_tui()?;
tui.set_owned_screen(/*owned*/ true)?;
let wide = Size::new(/*width*/ 120, /*height*/ 12);
let narrow = Size::new(/*width*/ 34, /*height*/ 12);
let mut text = "+a line of generated output\n".repeat(66_000);
for tail in ["+last hunk", "+refreshed hunk"] {
text.push_str(tail);
text.push('\n');
let request = invoke(&mut app, &mut tui, &mut server, &mut events).await?;
if tail == "+refreshed hunk" {
let pending = side_frame(&mut app, &mut tui, narrow)?;
assert!(pending.contains("Refreshing…"));
assert!(pending.contains("+last hunk"));
}
let loaded = AppEvent::SidebarDiffLoaded {
request,
text: text.clone(),
};
boxed_future!(app.handle_event(&mut tui, &mut server, loaded)).await?;
if tail == "+last hunk" {
assert!(side_frame(&mut app, &mut tui, wide)?.contains("generated output"));
boxed_future!(app.handle_tui_event(
&mut tui,
&mut server,
TuiEvent::Key(KeyCode::End.into())
))
.await?;
}
assert!(side_frame(&mut app, &mut tui, wide)?.contains(tail));
assert!(side_frame(&mut app, &mut tui, narrow)?.contains(tail));
}
Ok(())
}
@@ -0,0 +1,59 @@
---
source: tui/src/app/sidebar_document/diff_tests.rs
expression: "format!(\"Focused at 42 columns\\n{small}\\n\\nRefreshing at 42 columns\\n{refreshing}\\n\\nRefreshed beside chat\\n{sidebar}\\n\\nRefreshing a clean tree beside chat\\n{refreshing_clean}\")"
---
Focused at 42 columns
Diff × + ›
diff --git a/fees.rs b/fees.rs
@@ -1 +1 @@
-const FEE: u32 = 5;
+const FEE: u32 = 7;
esc close · ↑/↓ read · f3 find …
Refreshing at 42 columns
Diff × + ›
diff --git a/fees.rs b/fees.rs
@@ -1 +1 @@
-const FEE: u32 = 5;
+const FEE: u32 = 7;
Refreshing…
esc close · ↑/↓ read · f3 find …
Refreshed beside chat
Diff × + ›
diff --git a/fees.rs b/fees.rs
@@ -1 +1 @@
-const FEE: u32 = 5;
+const FEE: u32 = 8;
⌃x s focus sidebar
Refreshing a clean tree beside chat
Diff × + ›
No changes detected.
Refreshing…
⌃x s focus sidebar
@@ -21,9 +21,15 @@ impl Document {
}
let reader = server.request_view();
let backend_id = self.backend;
let source = self.source;
let super::DocumentSource::File {
thread: source,
ref original_path,
} = self.source
else {
return;
};
let path = self.path.clone();
let original_path = self.original_path.clone();
let original_path = original_path.clone();
let location = self.location;
let request = uuid::Uuid::new_v4();
let (refresh, mut changes) = watch::channel(());
+11 -6
View File
@@ -27,15 +27,20 @@ impl App {
thread_id: Option<ThreadId>,
) -> Option<crate::backend_id::BackendId> {
thread_id
.and_then(|thread_id| {
self.thread_event_channels
.get(&thread_id)
.and_then(|channel| channel.backend_id)
.or_else(|| self.backend_registry.owner(thread_id))
})
.and_then(|thread_id| self.thread_backend_id(thread_id))
.or(self.app_server_backend_id)
}
pub(super) fn thread_backend_id(
&self,
thread_id: ThreadId,
) -> Option<crate::backend_id::BackendId> {
self.thread_event_channels
.get(&thread_id)
.and_then(|channel| channel.backend_id)
.or_else(|| self.backend_registry.owner(thread_id))
}
pub(super) async fn stop_realtime_conversation(&mut self, app_server: &mut AppServerSession) {
let thread_id = self
.background_voice
+13 -1
View File
@@ -1097,7 +1097,19 @@ pub(crate) enum AppEvent {
result: Result<ConnectorsSnapshot, String>,
},
/// Result of computing a `/diff` command.
/// Start a working tree diff in the invoking conversation.
OpenDiff {
thread_id: Option<ThreadId>,
cwd: PathUri,
},
/// Result for a specific, possibly backgrounded Diff tab.
SidebarDiffLoaded {
request: Uuid,
text: String,
},
/// Result for the standalone `/diff` pager.
DiffResult {
thread_id: Option<ThreadId>,
cwd: PathUri,
-9
View File
@@ -228,7 +228,6 @@ use crate::exec_cell::ExecCell;
use crate::exec_cell::new_active_exec_command;
use crate::exec_command::split_command_string;
use crate::exec_command::strip_bash_lc_and_escape;
use crate::get_git_diff::get_git_diff;
use crate::history_cell;
use crate::history_cell::HistoryCell;
use crate::history_cell::HistoryRenderMode;
@@ -1542,14 +1541,6 @@ impl ChatWidget {
self.interrupted_turn_notice_mode = mode;
}
pub(crate) fn add_diff_in_progress(&mut self) {
self.request_redraw();
}
pub(crate) fn on_diff_complete(&mut self) {
self.request_redraw();
}
pub(crate) fn add_debug_config_output(&mut self) {
self.add_to_history(crate::debug_config::new_debug_config_output(
&self.config,
+4 -35
View File
@@ -87,7 +87,7 @@ impl ChatWidget {
/// Re-anchor the local daemon's sandbox at the session cwd. A profile ID
/// cannot carry extra runtime roots or permissions from a remote executor.
pub(super) fn diff_permission_profile(&self) -> Option<String> {
pub(crate) fn diff_permission_profile(&self) -> Option<String> {
if !self.remote_connection.as_ref()?.is_local_daemon {
return None;
}
@@ -543,40 +543,9 @@ impl ChatWidget {
}
SlashCommand::Tui => self.show_tui_mode_picker(),
SlashCommand::Diff => {
self.add_diff_in_progress();
let tx = self.app_event_tx.clone();
let runner = self.workspace_command_runner.clone();
let thread_id = self.thread_id();
let cwd = self.session_cwd().clone();
let profile = self.diff_permission_profile();
tokio::spawn(async move {
let text = match runner {
Some(runner) => {
match get_git_diff(
runner.as_ref(),
&cwd.to_path_buf(),
profile.as_deref(),
)
.await
{
Ok((is_git_repo, diff_text)) => {
if is_git_repo {
diff_text
} else {
"`/diff` — _not inside a git repository_".to_string()
}
}
Err(e) => format!("Failed to compute diff: {e}"),
}
}
None => "Failed to compute diff: workspace command runner unavailable"
.to_string(),
};
tx.send(AppEvent::DiffResult {
thread_id,
cwd,
text,
});
self.app_event_tx.send(AppEvent::OpenDiff {
thread_id: self.thread_id(),
cwd: self.session_cwd().clone(),
});
}
SlashCommand::Mention => {
+18 -3
View File
@@ -96,6 +96,11 @@ struct VisibleRow {
activity_ids: Arc<[String]>,
}
enum RenderContent {
Transcript,
Document,
}
/// Shared scrolling and interaction state for compact and detailed transcript presentations.
pub(crate) struct TranscriptView {
pub(crate) image_protocol: Option<crate::pets::ImageProtocol>,
@@ -217,11 +222,17 @@ impl TranscriptView {
}
pub(crate) fn render(&mut self, area: Rect, buf: &mut Buffer, cells: &[Arc<dyn HistoryCell>]) {
self.paint_rows(area, buf, cells);
self.paint_rows(area, buf, cells, RenderContent::Transcript);
self.finish_collapse_layout(cells);
}
fn paint_rows(&mut self, area: Rect, buf: &mut Buffer, cells: &[Arc<dyn HistoryCell>]) {
fn paint_rows(
&mut self,
area: Rect,
buf: &mut Buffer,
cells: &[Arc<dyn HistoryCell>],
content: RenderContent,
) {
let previous_viewport_height =
self.area.height + u16::from(self.prompt_header_target.is_some());
self.composer_tip = None;
@@ -379,7 +390,11 @@ impl TranscriptView {
{
self.extend_selection(pointer.x, pointer.y);
}
self.tail_visible = self.current_tail_is_visible(current_cells);
self.tail_visible = match content {
RenderContent::Transcript => self.current_tail_is_visible(current_cells),
// Documents have immutable chunks and no hidden reasoning or live tail.
RenderContent::Document => !self.document_has_rows_below(cells),
};
if self.tail_visible {
self.unseen_activity = false;
}
+37 -14
View File
@@ -1,4 +1,5 @@
//! Render source locations in the file reader using the transcript's wrapped rows.
//! Document chunks have no hidden entries, so scroll state needs only the visible rows.
use ratatui::style::Color;
use ratatui::style::Modifier;
@@ -11,10 +12,7 @@ use super::*;
/// A document can be replaced on disk; retain the offset, not the old rendered cells.
#[derive(Clone, Copy)]
pub(crate) enum DocumentPosition {
Offset(usize),
Latest,
}
pub(crate) struct DocumentPosition(Position);
/// Resolved logical lines and the grapheme-aligned byte offset used for scrolling.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -57,9 +55,23 @@ impl TranscriptView {
}
pub(crate) fn document_position(&self) -> DocumentPosition {
match self.position {
Position::Reading(anchor) => DocumentPosition::Offset(anchor.offset),
Position::Latest => DocumentPosition::Latest,
DocumentPosition(self.position)
}
pub(crate) fn restore_document_position(
&mut self,
cells: &[Arc<dyn HistoryCell>],
position: DocumentPosition,
) {
if let Position::Reading(anchor) = position.0
&& let Some(cell) = cells.get(anchor.index)
{
self.position = Position::Reading(Anchor {
key: EntryKey::cell(cell),
..anchor
});
} else {
self.jump_to_latest();
}
}
@@ -81,7 +93,8 @@ impl TranscriptView {
0
};
let text = Rect::new(area.x + gutter, area.y, area.width - gutter, area.height);
self.render(text, buf, cells);
self.paint_rows(text, buf, cells, RenderContent::Document);
self.finish_collapse_layout(cells);
if line_starts.is_empty() {
return;
}
@@ -129,7 +142,7 @@ impl TranscriptView {
}
pub(crate) fn paint_document_scroll_indicators(
&mut self,
&self,
area: Rect,
buf: &mut Buffer,
cells: &[Arc<dyn HistoryCell>],
@@ -137,11 +150,15 @@ impl TranscriptView {
if area.height < 2 || area.width < 3 {
return;
}
let start = self.start(cells);
for (visible, row, arrow) in [
(start > (0, 0), area.top(), "↑"),
(start < self.bottom_start(cells), area.bottom() - 1, "↓"),
] {
// The rendered rows already tell us whether more document content follows.
// Measuring the final chunk here can evict the visible chunk on every redraw.
let above = self
.visible
.first()
.is_some_and(|row| (row.index, row.row) > (0, 0));
let below = self.document_has_rows_below(cells);
for (visible, row, arrow) in [(above, area.top(), "↑"), (below, area.bottom() - 1, "↓")]
{
if visible {
buf[(area.right() - 1, row)]
.set_symbol(arrow)
@@ -149,4 +166,10 @@ impl TranscriptView {
}
}
}
pub(super) fn document_has_rows_below(&self, cells: &[Arc<dyn HistoryCell>]) -> bool {
self.visible
.last()
.is_some_and(|row| row.row + 1 < row.layout.row_count() || row.index + 1 < cells.len())
}
}
+2 -1
View File
@@ -32,6 +32,7 @@ impl TranscriptView {
},
buf,
cells,
RenderContent::Transcript,
);
// The final viewport includes prompt-header and footer reservations. Let the tip yield
// rather than leave only completion metadata visible on a short terminal.
@@ -39,7 +40,7 @@ impl TranscriptView {
&& self.visible.first().is_none_or(|row| row.key == key)
{
self.turn_tip_key = None;
self.paint_rows(area, buf, cells);
self.paint_rows(area, buf, cells, RenderContent::Transcript);
return None;
}
tip?;
+48
View File
@@ -73,6 +73,54 @@ pub(super) fn text(buffer: &Buffer) -> String {
.join("\n")
}
#[test]
fn document_scroll_indicators_use_visible_rows_without_laying_out_the_tail() {
let tail_renders = Arc::<AtomicUsize>::default();
let cells = vec![
cell("first\nsecond\nthird\nfourth\nfifth"),
Arc::new(TestCell {
text: "last line wraps across several rows".into(),
renders: Arc::clone(&tail_renders),
}) as Arc<dyn HistoryCell>,
];
let mut view = TranscriptView::default();
view.jump_to_offset(&cells, /*offset*/ 0);
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 12, /*height*/ 3,
);
let viewport = Rect { width: 11, ..area };
let mut buffer = Buffer::empty(area);
for _ in 0..3 {
view.render_document(viewport, &mut buffer, &cells, &[], /*target*/ None);
view.paint_document_scroll_indicators(area, &mut buffer, &cells);
assert_eq!(
[buffer[(11, 0)].symbol(), buffer[(11, 2)].symbol()],
[" ", "↓"]
);
}
assert_eq!(tail_renders.load(Ordering::Relaxed), 0);
// The first chunk ends exactly at the viewport edge, but another chunk follows.
view.jump_to_offset(&cells, "first\nsecond\n".len());
buffer.reset();
view.render_document(viewport, &mut buffer, &cells, &[], /*target*/ None);
view.paint_document_scroll_indicators(area, &mut buffer, &cells);
assert_eq!(
[buffer[(11, 0)].symbol(), buffer[(11, 2)].symbol()],
["↑", "↓"]
);
assert_eq!(tail_renders.load(Ordering::Relaxed), 0);
view.jump_to_latest();
buffer.reset();
view.render_document(viewport, &mut buffer, &cells, &[], /*target*/ None);
view.paint_document_scroll_indicators(area, &mut buffer, &cells);
assert_eq!(
[buffer[(11, 0)].symbol(), buffer[(11, 2)].symbol()],
["↑", " "]
);
}
#[test]
fn consecutive_user_prompts_share_one_background_block() {
use crate::history_cell::AgentMessageCell;