Refresh open sidebar file previews when files change (#62583)

## Why

Sidebar previews load a snapshot of the file when opened, so edits on disk
leave the open tab showing stale content.

## What changed

Watch each previewed file’s parent directory through the app server so the
preview refreshes even when an editor saves by atomically replacing the file.
Poll every three seconds when a watch cannot be registered, and resubscribe
when reconnecting to the same backend.

Preserve the text preview’s reading position across reloads, including when
the file temporarily becomes unreadable and then returns.

## Testing

The sidebar test covers atomic saves and recovery after moving a directory
away and back. It checks that the tab shows updated content at the existing
reading position.

GitOrigin-RevId: d5f7507d1a81a118fb10a0febf5e274c18f19d81
This commit is contained in:
Felipe Coury
2026-11-19 20:13:14 +00:00
committed by copyberry
parent 40a848caf4
commit 81ef12b617
12 changed files with 305 additions and 62 deletions
+21
View File
@@ -196,6 +196,27 @@ impl App {
app_server_client: &AppServerSession,
mut notification: ServerNotification,
) {
if let ServerNotification::FsChanged(change) = &notification
&& let Ok(request) = uuid::Uuid::parse_str(&change.watch_id)
{
for doc in self
.sidebars
.values()
.flat_map(|pane| pane.documents.values())
{
if doc.backend == app_server_client.backend_id()
&& let Some((token, refresh)) = &doc.watch
&& *token == request
&& change.changed_paths.iter().any(|path| {
doc.path
.starts_with(&codex_utils_path_uri::PathUri::from_abs_path(path))
})
{
refresh.send_replace(());
break;
}
}
}
if let ServerNotification::TurnModerationMetadata(metadata) = &mut notification
&& (!super::safety_recourse::supports_server(app_server_client)
|| self
+3 -2
View File
@@ -3723,9 +3723,10 @@ impl App {
}
}
}
AppEvent::SidebarDocumentLoaded { backend_id, parent, request, result } => {
if let Some(doc) = self.sidebars.get_mut(&Some(parent)).and_then(|pane| pane.documents.get_mut(&request))
AppEvent::SidebarDocumentLoaded { backend_id, parent, tab, request, result } => {
if let Some(doc) = self.sidebars.get_mut(&Some(parent)).and_then(|pane| pane.documents.get_mut(&tab))
&& doc.backend == backend_id
&& doc.watch.as_ref().is_some_and(|(id, _)| *id == request)
{
doc.loaded(result);
tui.frame_requester().schedule_frame();
+9 -3
View File
@@ -418,11 +418,17 @@ impl App {
self.app_event_tx = AppEventSender::new(tx);
self.app_server_backend_id = Some(session.backend_id());
*app_event_rx = rx;
for pane in self.sidebars.values_mut() {
for (parent, pane) in &mut self.sidebars {
pane.focus_document_request = None;
pane.agents.pending_link = None;
for doc in pane.documents.values_mut() {
doc.connection_replaced();
for (tab, doc) in &mut pane.documents {
if let Some(parent) = parent
&& doc.backend == session.backend_id()
{
doc.subscribe(*tab, *parent, &session, self.app_event_tx.clone());
} else {
doc.connection_replaced();
}
}
if let Some(files) = &mut pane.files {
files.connection_replaced();
+54 -55
View File
@@ -1,6 +1,7 @@
//! Read-only Markdown previews use the focused thread's workspace and app-server.
mod open_error;
mod watch;
use super::sidebar::PaneFocus;
use super::sidebar::SidebarContent;
@@ -19,6 +20,7 @@ use crate::sidebar_tab_strip::SidebarTab;
use crate::terminal_hyperlinks::HyperlinkLine;
use crate::terminal_hyperlinks::ReaderLink;
use crate::terminal_hyperlinks::visible_lines;
use crate::transcript_view::DocumentPosition;
use crate::transcript_view::TranscriptView;
use crate::transcript_view::ViewAction;
use codex_app_server_client::AppServerPath;
@@ -79,6 +81,8 @@ pub(super) struct DocumentRenderOptions<'a> {
pub(super) struct Document {
source: ThreadId,
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>,
location: Option<SourceLocation>,
@@ -87,7 +91,10 @@ pub(super) struct Document {
enum State {
Loading(Instant),
Failed(color_eyre::Report),
Failed {
error: color_eyre::Report,
position: Option<DocumentPosition>,
},
Image(Box<SidebarImage>),
Ready {
view: Box<TranscriptView>,
@@ -140,21 +147,39 @@ impl Document {
}
pub(super) fn connection_replaced(&mut self) {
self.watch = None;
if matches!(self.state, State::Loading(_)) {
self.state = State::Failed(eyre!("Connection changed. Reopen this file to try again."));
self.state = State::Failed {
error: eyre!("Connection changed. Reopen this file to try again."),
position: None,
};
}
}
pub(super) fn loaded(&mut self, result: Result<DocumentContent>) {
let position = match &self.state {
State::Ready { view, .. } => Some(view.document_position()),
State::Failed { position, .. } => *position,
State::Loading(_) | State::Image(_) => None,
};
self.state = match result {
Ok(DocumentContent::Image(image)) => State::Image(image),
Ok(DocumentContent::Text(source)) => {
if let State::Ready { cells, .. } = &self.state
&& cells[0].copy_source() == Some(source.as_str())
{
return;
}
self.link = None;
let title = self.title();
let code =
self.location.is_some() || !crate::markdown_render::is_markdown_file(&title);
const MAX_SOURCE_BYTES: usize = 1024 * 1024;
if code && source.len() > MAX_SOURCE_BYTES {
self.state = State::Failed(eyre!("Source preview limit is 1 MiB"));
self.state = State::Failed {
error: eyre!("Source preview limit is 1 MiB"),
position,
};
return;
}
// Like the transcript layout, count one LF per logical line, including CRLF input.
@@ -173,8 +198,10 @@ impl Document {
};
const MAX_SOURCE_LINES: usize = 10_000;
if line_starts.len() > MAX_SOURCE_LINES {
self.state =
State::Failed(eyre!("Source preview limit is {MAX_SOURCE_LINES} lines"));
self.state = State::Failed {
error: eyre!("Source preview limit is {MAX_SOURCE_LINES} lines"),
position,
};
return;
}
let language = code.then(|| {
@@ -190,7 +217,11 @@ impl Document {
let mut view = Box::<TranscriptView>::default();
view.document_links = true;
view.show_follow_control = false;
view.jump_to_offset(&cells, target.map_or(0, |(_, offset)| offset));
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, |(_, offset)| offset)),
}
State::Ready {
view,
cells,
@@ -198,7 +229,7 @@ impl Document {
target,
}
}
Err(error) => State::Failed(error),
Err(error) => State::Failed { error, position },
};
}
@@ -224,6 +255,7 @@ impl Document {
if restore_markdown || (location.is_some() && line_starts.is_empty()) {
// Coordinate links show source. Plain Markdown links restore rendering.
let source = source.to_owned();
self.state = State::Loading(Instant::now());
self.loaded(Ok(DocumentContent::Text(source)));
} else {
*target = location.and_then(|location| source_target(source, line_starts, location));
@@ -266,7 +298,7 @@ impl Document {
])
.render(body, buf);
}
State::Failed(error) => {
State::Failed { error, .. } => {
let mut lines = open_error::lines(&self.path, error, body.width);
// On short panes, keep the space for the filename and recovery message.
if lines.len() + 2 < usize::from(body.height) {
@@ -508,7 +540,7 @@ impl App {
let existing = self.sidebar().and_then(|pane| {
pane.documents.iter().find_map(|(&id, doc)| {
(doc.backend == backend_id && doc.path == path)
.then_some((id, matches!(doc.state, State::Failed(_))))
.then_some((id, matches!(doc.state, State::Failed { .. })))
})
});
if let Some((id, failed)) = existing {
@@ -526,21 +558,23 @@ impl App {
self.sidebar_mut().remove_document(id);
}
let request = uuid::Uuid::new_v4();
let tx = self.app_event_tx.clone();
let pane = self.sidebar_mut();
if !pane.opened_files.contains(&path) {
pane.opened_files.push(path.clone());
}
pane.documents.insert(
request,
Document {
source,
path: path.clone(),
backend: backend_id,
link: None,
location,
state: State::Loading(Instant::now()),
},
);
let mut doc = Document {
source,
path,
original_path,
watch: None,
backend: backend_id,
link: None,
location,
state: State::Loading(Instant::now()),
};
doc.subscribe(request, parent, server, tx);
pane.documents.insert(request, doc);
pane.add_document_tab(request);
if focus {
self.activate_sidebar_tab(tui, server, SidebarTab::Document(request))
@@ -548,41 +582,6 @@ impl App {
} else {
tui.frame_requester().schedule_frame();
}
let reader = server.request_view();
let tx = self.app_event_tx.clone();
tokio::spawn(async move {
let result = async {
if (FileLink {
path: path.inferred_native_path_string(),
location,
})
.is_image()
{
let bytes = reader
.read_preview_file(source, &original_path, &path)
.await?;
tokio::task::spawn_blocking(move || match SidebarImage::decode(&bytes) {
Ok(image) => Ok(DocumentContent::Image(Box::new(image))),
Err(image_error) => AppServerSession::preview_text(bytes)
.map(DocumentContent::Text)
.map_err(|_| image_error),
})
.await?
} else {
reader
.read_document(source, &original_path, &path)
.await
.map(DocumentContent::Text)
}
}
.await;
tx.send(AppEvent::SidebarDocumentLoaded {
backend_id,
parent,
request,
result,
});
});
Ok(())
}
@@ -0,0 +1,88 @@
//! One subscription per open tab. Dropping or replacing its sender releases the server watch.
use super::AppEvent;
use super::AppEventSender;
use super::AppServerPath;
use super::AppServerSession;
use super::Document;
use super::DocumentContent;
use super::FileLink;
use super::SidebarImage;
use super::ThreadId;
use tokio::sync::watch;
impl Document {
pub(in crate::app) fn subscribe(
&mut self,
tab: uuid::Uuid,
parent: ThreadId,
server: &AppServerSession,
tx: AppEventSender,
) {
let reader = server.request_view();
let backend_id = self.backend;
let source = self.source;
let path = self.path.clone();
let original_path = self.original_path.clone();
let is_image = (FileLink {
path: path.inferred_native_path_string(),
location: self.location,
})
.is_image();
let request = uuid::Uuid::new_v4();
let (refresh, mut changes) = watch::channel(());
self.watch = Some((request, refresh));
tokio::spawn(async move {
let fs = reader.file_system();
let load = || async {
let result = async {
if is_image {
let bytes = reader
.read_preview_file(source, &original_path, &path)
.await?;
tokio::task::spawn_blocking(move || match SidebarImage::decode(&bytes) {
Ok(image) => Ok(DocumentContent::Image(Box::new(image))),
Err(image_error) => AppServerSession::preview_text(bytes)
.map(DocumentContent::Text)
.map_err(|_| image_error),
})
.await?
} else {
reader
.read_document(source, &original_path, &path)
.await
.map(DocumentContent::Text)
}
}
.await;
tx.send(AppEvent::SidebarDocumentLoaded {
backend_id,
parent,
tab,
request,
result,
});
};
// Watch the parent so replacing the file atomically doesn't lose our subscription.
// Register before reading so edits between the initial read and registration can't be missed.
let watched = if let Some(dir) = path.parent() {
let dir = AppServerPath::from_app_server(dir.inferred_native_path_string());
fs.watch_document(&dir, request).await.is_ok()
} else {
false
};
while changes.has_changed().is_ok() {
load().await;
tokio::select! {
result = changes.changed() => if result.is_err() { break; },
// Older servers can read a file without supporting fs/watch.
_ = tokio::time::sleep(std::time::Duration::from_secs(3)), if !watched => {}
}
}
if watched {
fs.unwatch_document(request).await;
}
});
}
}
+58 -2
View File
@@ -406,6 +406,8 @@ async fn document_preview_scenario() -> Result<()> {
)
.await?;
Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(true).await)).await?;
// A closed tab can cancel its read. Hold an already completed result to test late dispatch.
let closed_document_result = next_document_event(false).await;
Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into())))
.await?;
Box::pin(app.handle_tui_event(
@@ -418,7 +420,7 @@ async fn document_preview_scenario() -> Result<()> {
)),
))
.await?;
Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(false).await)).await?;
Box::pin(app.handle_event(&mut tui, &mut server, closed_document_result)).await?;
assert_eq!(app.sidebar().unwrap().documents.len(), 1);
std::fs::write(
dir.path().join("main.rs"),
@@ -648,9 +650,13 @@ size 123
.expect("tab strip");
let narrow_labels = visible_sidebar_row(&tui, strip, strip.y);
insta::assert_snapshot!(narrow_labels, @"‹ fe…eA/g…md× fe…eB/g…md× +");
let long_file = "Before the fold.\n\n".repeat(24);
for directory in ["feature-alpha-build", "feature-beta-build"] {
std::fs::create_dir_all(dir.path().join(directory))?;
std::fs::write(dir.path().join(directory).join("guide.md"), "# Guide")?;
std::fs::write(
dir.path().join(directory).join("guide.md"),
format!("{long_file}Original ending."),
)?;
Box::pin(app.open_document(
&mut tui,
&mut server,
@@ -689,6 +695,56 @@ size 123
matches!(event, AppEvent::InsertHistoryCell(cell) if cell.display_lines(/*width*/ 120).iter()
.any(|line| line.to_string().contains("Could not open ~/notes.md:")))
}));
// Replace the file like an editor doing an atomic save. The new last line should
// appear in the still-open tab without reopening the file or jumping to the top.
app.sidebar_mut()
.active_document()
.unwrap()
.reader()
.unwrap()
.0
.jump_to_latest();
assert!(side_frame(&mut app, &mut tui, size)?.contains("Original ending."));
let mut wait_for_preview =
async |app: &mut App, tui: &mut tui::Tui, server: &mut AppServerSession, text: &str| {
tokio::time::timeout(std::time::Duration::from_secs(10), async {
loop {
tokio::select! {
Some(event) = server.next_event() => {
Box::pin(app.handle_app_server_event(server, event.event)).await;
}
Some(event @ AppEvent::SidebarDocumentLoaded { .. }) = events.recv() => {
Box::pin(app.handle_event(tui, server, event)).await?;
if side_frame(app, tui, size)?.contains(text) {
return Ok::<_, color_eyre::Report>(());
}
}
}
}
})
.await
.unwrap_or_else(|_| panic!("open preview did not show {text:?}"))
};
let directory = dir.path().join("feature-beta-build");
let saved = tempfile::NamedTempFile::new_in(dir.path())?;
std::fs::write(saved.path(), format!("{long_file}Updated ending."))?;
saved.persist(directory.join("guide.md"))?;
wait_for_preview(&mut app, &mut tui, &mut server, "Updated ending.").await?;
// Moving the whole folder makes the file unreadable; bringing it back must
// restore the scrolled reader, even after the intervening error frame.
let moved = dir.path().join("moved");
std::fs::rename(&directory, &moved)?;
wait_for_preview(&mut app, &mut tui, &mut server, "File not found").await?;
std::fs::rename(moved, directory)?;
wait_for_preview(&mut app, &mut tui, &mut server, "Updated ending.").await?;
let sidebar = app.conversation_frame.panel_area().expect("document panel");
let visible = (sidebar.y..sidebar.bottom())
.map(|row| visible_sidebar_row(&tui, sidebar, row))
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!("refreshed_sidebar_at_reading_position", visible);
server.shutdown().await?;
Ok(())
}
@@ -0,0 +1,16 @@
---
source: tui/src/app/sidebar_document_tests.rs
expression: visible
---
‹ 1:f…ld/g…d× 2:f…ld/g…d× +
Before the fold. ↑
Before the fold.
Before the fold.
Before the fold.
Updated ending.
↑/↓ read · f3 find · Tab link …
+1
View File
@@ -562,6 +562,7 @@ pub(crate) enum AppEvent {
SidebarDocumentLoaded {
backend_id: crate::backend_id::BackendId,
parent: ThreadId,
tab: uuid::Uuid,
request: uuid::Uuid,
result: color_eyre::Result<crate::sidebar_image::DocumentContent>,
},
+29
View File
@@ -217,6 +217,35 @@ impl AppServerFileSystem {
.map(drop)
}
pub(crate) async fn watch_document(&self, path: &AppServerPath, id: Uuid) -> Result<()> {
// fs/changed notifications use client-native absolute paths. If we can't represent
// this directory, don't register a watch whose notifications we can't decode.
let path = AbsolutePathBuf::from_absolute_path_checked(path.as_str())?;
let _: codex_app_server_protocol::FsWatchResponse = self
.request_handle
.request_typed(ClientRequest::FsWatch {
request_id: RequestId::String(format!("tui-fs-{}", Uuid::new_v4())),
params: codex_app_server_protocol::FsWatchParams {
watch_id: id.to_string(),
path,
},
})
.await?;
Ok(())
}
pub(crate) async fn unwatch_document(&self, id: Uuid) {
let _: Result<codex_app_server_protocol::FsUnwatchResponse, _> = self
.request_handle
.request_typed(ClientRequest::FsUnwatch {
request_id: RequestId::String(format!("tui-fs-{}", Uuid::new_v4())),
params: codex_app_server_protocol::FsUnwatchParams {
watch_id: id.to_string(),
},
})
.await;
}
async fn request_fs_path<T: DeserializeOwned>(
&self,
method: &str,
@@ -109,6 +109,17 @@ async fn remote_preview_requests_the_source_thread_and_validates_text() -> Resul
.unwrap_err();
assert!(format!("{error:#}").contains(expected), "{error:#}");
}
// No fs/watch should reach the server for a path its client can't decode in fs/changed.
let foreign = if cfg!(windows) {
"/workspace"
} else {
r"C:\workspace"
};
let watch = session
.file_system()
.watch_document(&AppServerPath::from_app_server(foreign), Uuid::new_v4())
.await;
assert!(watch.is_err());
session.shutdown().await?;
server.await??;
Ok(())
+1
View File
@@ -11,6 +11,7 @@ mod composer_gap;
mod copy_mode;
mod disclosure;
mod document;
pub(crate) use document::DocumentPosition;
mod follow_control;
mod footer;
mod input;
@@ -7,7 +7,21 @@ use ratatui::widgets::Widget;
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,
}
impl TranscriptView {
pub(crate) fn document_position(&self) -> DocumentPosition {
match self.position {
Position::Reading(anchor) => DocumentPosition::Offset(anchor.offset),
Position::Latest => DocumentPosition::Latest,
}
}
pub(crate) fn render_document(
&mut self,
area: Rect,