diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 75c76c8d4f..f4f9b9cb59 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -3709,7 +3709,7 @@ impl App { && self.document_preview_available(tui, app_server); match path { Ok(path) => Box::pin(self.open_resolved_document(tui, app_server, source, original_path, path, location, focus)).await?, - Err(error) if focus => self.chat_widget.add_error_message(format!("Could not open file: {error}")), + Err(error) if focus => self.chat_widget.add_error_message(format!("Could not open {original_path}: {error}")), Err(_) => {} } } diff --git a/codex-rs/tui/src/app/sidebar_document.rs b/codex-rs/tui/src/app/sidebar_document.rs index 4d7f4fb10d..f4a8b3cf02 100644 --- a/codex-rs/tui/src/app/sidebar_document.rs +++ b/codex-rs/tui/src/app/sidebar_document.rs @@ -1,5 +1,7 @@ //! Read-only Markdown previews use the focused thread's workspace and app-server. +mod open_error; + use super::sidebar::PaneFocus; use super::sidebar::SidebarContent; use super::*; @@ -22,6 +24,7 @@ use crate::transcript_view::ViewAction; use codex_app_server_client::AppServerPath; use codex_utils_path_uri::LegacyAppPathString; use codex_utils_path_uri::PathUri; +use color_eyre::eyre::eyre; use ratatui::layout::Position; use ratatui::widgets::Widget; use unicode_segmentation::UnicodeSegmentation; @@ -84,7 +87,7 @@ pub(super) struct Document { enum State { Loading(Instant), - Failed(String), + Failed(color_eyre::Report), Image(Box), Ready { view: Box, @@ -138,11 +141,11 @@ impl Document { pub(super) fn connection_replaced(&mut self) { if matches!(self.state, State::Loading(_)) { - self.state = State::Failed("Connection changed. Reopen this file to try again.".into()); + self.state = State::Failed(eyre!("Connection changed. Reopen this file to try again.")); } } - pub(super) fn loaded(&mut self, result: Result) { + pub(super) fn loaded(&mut self, result: Result) { self.state = match result { Ok(DocumentContent::Image(image)) => State::Image(image), Ok(DocumentContent::Text(source)) => { @@ -151,7 +154,7 @@ impl Document { 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("Source preview limit is 1 MiB".into()); + self.state = State::Failed(eyre!("Source preview limit is 1 MiB")); return; } // Like the transcript layout, count one LF per logical line, including CRLF input. @@ -171,7 +174,7 @@ impl Document { const MAX_SOURCE_LINES: usize = 10_000; if line_starts.len() > MAX_SOURCE_LINES { self.state = - State::Failed(format!("Source preview limit is {MAX_SOURCE_LINES} lines")); + State::Failed(eyre!("Source preview limit is {MAX_SOURCE_LINES} lines")); return; } let language = code.then(|| { @@ -264,9 +267,18 @@ impl Document { .render(body, buf); } State::Failed(error) => { - Paragraph::new(format!("Could not open file: {error}")) - .wrap(ratatui::widgets::Wrap { trim: false }) - .render(body, buf); + 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) { + lines.insert(0, Line::default()); + if resize_hint.is_none() { + let esc = crate::key_hint::plain(KeyCode::Esc); + let footer = Rect::new(body.x, body.bottom() - 1, body.width, 1); + crate::footer_hint::shortcut(&esc.display_label(), "close") + .render(footer, buf); + } + } + Paragraph::new(lines).render(body, buf); } State::Ready { view, @@ -563,8 +575,7 @@ impl App { .map(DocumentContent::Text) } } - .await - .map_err(|error| format!("{error:#}")); + .await; tx.send(AppEvent::SidebarDocumentLoaded { backend_id, parent, diff --git a/codex-rs/tui/src/app/sidebar_document/open_error.rs b/codex-rs/tui/src/app/sidebar_document/open_error.rs new file mode 100644 index 0000000000..5ab6879158 --- /dev/null +++ b/codex-rs/tui/src/app/sidebar_document/open_error.rs @@ -0,0 +1,78 @@ +//! Show the attempted path even when its tab label is truncated. +use crate::style; +use crate::style::StatusTone; +use codex_app_server_client::TypedRequestError; +use codex_utils_path_uri::PathUri; +use color_eyre::Report; +use ratatui::style::Styled; + +use ratatui::style::Stylize; +use ratatui::text::Line; + +pub(super) fn lines(path: &PathUri, error: &Report, width: u16) -> Vec> { + // The server sends the OS message, but uses the same RPC code for unrelated failures. + // Only classify errors from the file read itself (not, for example, a missing thread). + let failure = style::status_style(StatusTone::Failure); + let (heading, hint) = match error.downcast_ref::() { + Some(TypedRequestError::Server { method, source }) if method == "fs/readFile" => { + let message = source.message.as_str(); + match message + .split_once(" (os error ") + .map_or(message, |(reason, _)| reason) + { + "No such file or directory" + | "The system cannot find the file specified." + | "The system cannot find the path specified." => ( + "File not found" + .set_style(style::warning_notice_style()) + .bold(), + "This file may have moved since the link was added.".to_owned(), + ), + "Permission denied" | "Operation not permitted" | "Access is denied." => ( + "Permission denied".set_style(failure), + "Check your read access, then reopen the link.".to_owned(), + ), + _ => ("Could not open file".set_style(failure), message.to_owned()), + } + } + _ => ( + "Could not open file".set_style(failure), + format!("{error:#}"), + ), + }; + + let width = usize::from(width); + let mut lines = vec![Line::from(heading), Line::default()]; + let full_path = path.inferred_native_path_string(); + let basename = path.basename(); + // Split the displayed path, so the directory keeps the owning host's separators. + let (directory, filename) = basename + .as_deref() + .and_then(|name| full_path.strip_suffix(name).map(|prefix| (prefix, name))) + .unwrap_or(("", &full_path)); + let options = + textwrap::Options::new(width).word_splitter(textwrap::WordSplitter::NoHyphenation); + lines.extend( + textwrap::wrap(filename, &options) + .into_iter() + .map(|part| Line::from(part.into_owned()).bold()), + ); + if !directory.is_empty() { + let directory_options = options.word_separator(textwrap::WordSeparator::Custom(|s| { + Box::new( + s.split_inclusive(['/', '\\']) + .map(textwrap::core::Word::from), + ) + })); + for part in textwrap::wrap(&format!("in {directory}"), directory_options) { + lines.push(Line::from(part.into_owned()).set_style(style::secondary_text_style())); + } + } + lines.push(Line::default()); + lines.extend( + textwrap::wrap(&hint, width) + .into_iter() + .map(|line| Line::from(line.into_owned())), + ); + lines +} diff --git a/codex-rs/tui/src/app/sidebar_document_tests.rs b/codex-rs/tui/src/app/sidebar_document_tests.rs index f77cd43f78..5c4fcf7845 100644 --- a/codex-rs/tui/src/app/sidebar_document_tests.rs +++ b/codex-rs/tui/src/app/sidebar_document_tests.rs @@ -120,8 +120,19 @@ async fn document_preview_scenario() -> Result<()> { assert!(loading.contains("Opening…"), "{loading}"); Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(false).await)).await?; - let error = side_frame(&mut app, &mut tui, size)?; - assert!(error.contains("Could not open file"), "{error}"); + let error = side_frame(&mut app, &mut tui, Size::new(size.width, /*height*/ 24))?; + let pane_text: String = error + .lines() + .filter_map(|line| line.split_once('│')) + .map(|(_, pane)| pane.trim()) + .collect(); + let directory = dir.path().canonicalize()?; + assert!( + pane_text.contains(&format!("File not foundguide.mdin {}", directory.display())), + "{error}" + ); + + assert!(pane_text.ends_with("esc close"), "{error}"); std::fs::write( dir.path().join("guide.md"), @@ -660,6 +671,24 @@ size 123 .expect("tab strip"); let narrow_labels = visible_sidebar_row(&tui, strip, strip.y); insta::assert_snapshot!(narrow_labels, @"‹ 1:f…ld/g…d× 2:f…ld/g…d× +"); + // If resolution itself fails, there is no new tab in which to show the path. + let tab_count = app.sidebar().unwrap().documents.len(); + app.open_document( + &mut tui, + &mut server, + parent, + FileLink { + path: "~/notes.md".into(), + location: None, + }, + ) + .await?; + Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(true).await)).await?; + assert_eq!(app.sidebar().unwrap().documents.len(), tab_count); + assert!(std::iter::from_fn(|| events.try_recv().ok()).any(|event| { + matches!(event, AppEvent::InsertHistoryCell(cell) if cell.display_lines(/*width*/ 120).iter() + .any(|line| line.to_string().contains("Could not open ~/notes.md:"))) + })); server.shutdown().await?; Ok(()) } @@ -672,3 +701,39 @@ fn visible_sidebar_row(tui: &crate::tui::Tui, sidebar: Rect, row: u16) -> String .trim() .to_owned() } + +#[test] +fn preview_error_keeps_the_filename_visible_in_a_narrow_pane() -> Result<()> { + let path = PathUri::parse("file:///archive/worktrees/docs/2026-09-11-tmux-attach-freeze.md")?; + let message = |method: &str, reason: &str| { + let error = codex_app_server_client::TypedRequestError::Server { + method: method.into(), + source: codex_app_server_protocol::JSONRPCErrorError { + code: -32603, + data: None, + message: reason.into(), + }, + }; + open_error::lines(&path, &error.into(), /*width*/ 38) + .iter() + .map(Line::to_string) + .collect::>() + .join("\n") + }; + insta::assert_snapshot!(message("fs/readFile", "No such file or directory (os error 2)"), @" + File not found + + 2026-09-11-tmux-attach-freeze.md + in /archive/worktrees/docs/ + + This file may have moved since the + link was added. + "); + + let denied = message("fs/readFile", "Permission denied (os error 13)"); + assert_eq!(denied.lines().next(), Some("Permission denied")); + let thread_error = message("thread/read", "No such file or directory (os error 2)"); + assert_eq!(thread_error.lines().next(), Some("Could not open file")); + assert!(message("fs/readFile", "Storage offline").ends_with("Storage offline")); + Ok(()) +} diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 9c2c5844f1..95b3a70f86 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -563,7 +563,7 @@ pub(crate) enum AppEvent { backend_id: crate::backend_id::BackendId, parent: ThreadId, request: uuid::Uuid, - result: Result, + result: color_eyre::Result, }, SidebarFilesLoaded { backend_id: crate::backend_id::BackendId, diff --git a/codex-rs/tui/src/app_server_session/fs.rs b/codex-rs/tui/src/app_server_session/fs.rs index d8b7e8a71d..56bc1e9b85 100644 --- a/codex-rs/tui/src/app_server_session/fs.rs +++ b/codex-rs/tui/src/app_server_session/fs.rs @@ -5,6 +5,7 @@ use base64::Engine; use base64::engine::general_purpose::STANDARD; use codex_app_server_client::AppServerPath; use codex_app_server_client::AppServerRequestHandle; +use codex_app_server_client::TypedRequestError; use codex_app_server_protocol::ClientRequest; use codex_app_server_protocol::FsCreateDirectoryParams; use codex_app_server_protocol::FsCreateDirectoryResponse; @@ -238,8 +239,13 @@ impl AppServerFileSystem { }) .await .wrap_err_with(|| format!("{method} failed in TUI"))?; - serde_json::from_value(response.map_err(|source| { - color_eyre::eyre::eyre!("{method} failed in TUI: {}", source.message) + serde_json::from_value(response.map_err(|mut source| { + // Callers log these errors. Keep raw server diagnostics out of the logs. + source.data = None; + TypedRequestError::Server { + method: method.to_string(), + source, + } })?) .wrap_err_with(|| format!("{method} returned invalid data")) } diff --git a/codex-rs/tui/src/app_server_session/fs_preview_tests.rs b/codex-rs/tui/src/app_server_session/fs_preview_tests.rs index 239dcde6d9..2a5dda51cc 100644 --- a/codex-rs/tui/src/app_server_session/fs_preview_tests.rs +++ b/codex-rs/tui/src/app_server_session/fs_preview_tests.rs @@ -3,6 +3,7 @@ use super::*; use crate::app_server_session::ThreadParamsMode; use crate::backend_id::BackendId; +use codex_app_server_protocol::JSONRPCErrorError; use codex_app_server_protocol::JSONRPCMessage; use futures::SinkExt; use futures::StreamExt; @@ -16,18 +17,22 @@ async fn remote_preview_requests_the_source_thread_and_validates_text() -> Resul let endpoint = crate::resolve_remote_addr(&format!("ws://{}", listener.local_addr()?))?; let source = ThreadId::new(); let text = "\tfirst\r\nsecond\n".repeat(80_000); - let encoded_text = STANDARD.encode(&text); + let responses = [ + json!({"result": {"dataBase64": STANDARD.encode(&text)}}), + json!({"error": { + "code": -32603, + "message": "No such file or directory (os error 2)", + "data": {"detail": "private diagnostic marker"} + }}), + json!({"result": {"dataBase64": STANDARD.encode([0xff])}}), + json!({"result": {"dataBase64": STANDARD.encode(b"bad\0")}}), + json!({"result": {"dataBase64": STANDARD.encode("stale")}}), + ]; let server = tokio::spawn(async move { let (stream, _) = listener.accept().await?; let mut socket = tokio_tungstenite::accept_async(stream).await?; let mut workspace = "/workspace"; - let mut responses = [ - encoded_text, - STANDARD.encode([0xff]), - STANDARD.encode(b"bad\0"), - STANDARD.encode("stale"), - ] - .into_iter(); + let mut responses = responses.into_iter(); while let Some(Ok(Message::Text(wire))) = socket.next().await { let JSONRPCMessage::Request(request) = serde_json::from_str(&wire)? else { continue; @@ -50,11 +55,11 @@ async fn remote_preview_requests_the_source_thread_and_validates_text() -> Resul } "fs/readFile" => { assert_eq!(request.params, Some(json!({"path": "/workspace/notes.md"}))); - let data_base64 = responses.next().expect("one preview request per case"); + let reply = responses.next().expect("one preview request per case"); if responses.len() == 0 { workspace = "/other"; } - json!({"result": {"dataBase64": data_base64}}) + reply } method => panic!("unexpected RPC: {method}"), }; @@ -72,6 +77,27 @@ async fn remote_preview_requests_the_source_thread_and_validates_text() -> Resul let path = AppServerPath::from_app_server("notes.md"); let resolved = session.resolve_thread_file(source, &path).await?; assert_eq!(session.read_document(source, &path, &resolved).await?, text); + let error = session + .read_document(source, &path, &resolved) + .await + .unwrap_err(); + let Some(TypedRequestError::Server { + method, + source: rpc_error, + }) = error.downcast_ref::() + else { + panic!("expected a typed filesystem error: {error:#}"); + }; + assert_eq!(method, "fs/readFile"); + assert_eq!( + rpc_error, + &JSONRPCErrorError { + code: -32603, + message: "No such file or directory (os error 2)".into(), + data: None, + } + ); + assert!(!error.to_string().contains("private diagnostic marker")); for expected in [ "Not a UTF-8 text file", "Not a text file",