From 5824b38693412e0787d45bbd0167be495b69660f Mon Sep 17 00:00:00 2001 From: Felipe Coury Date: Sun, 22 Nov 2026 19:05:16 +0000 Subject: [PATCH] Let Codex open workspace files in the terminal sidebar (#63184) ## Why When Codex points a user to a document, image, or source line, it can show that file alongside the conversation so the user can inspect it in context. ## What changed Add the `open_in_codex` MCP tool to the terminal workspace. It accepts a file path and an optional one-based line number. Requests queue until the calling conversation is visible and the sidebar can show the file without taking keyboard focus from the chat. The embedded backend loads a sandboxed snapshot using the calling thread's workspace and read permissions. Backends without an in-process permissions reader prompt the user to open the file. Pressing Enter in the focused preview also opens a snapshot as a live, watched document. ## Testing Cover queued previews when returning to the calling conversation, sandboxed reads, confirmation before opening, and live updates after the user opens a snapshot. GitOrigin-RevId: ce55f2dfdc7504e2f07e26f5c6404a591eb64649 --- codex-rs/tui/BUILD.bazel | 1 + codex-rs/tui/src/app.rs | 18 +- codex-rs/tui/src/app/event_dispatch.rs | 39 +- codex-rs/tui/src/app/side_pane.rs | 3 +- codex-rs/tui/src/app/sidebar.rs | 12 +- codex-rs/tui/src/app/sidebar_document.rs | 315 ++++++++++-- .../src/app/sidebar_document/model_read.rs | 111 +++++ .../tui/src/app/sidebar_document/watch.rs | 31 +- .../tui/src/app/sidebar_model_documents.rs | 70 +++ .../src/app/sidebar_open_in_codex_tests.rs | 464 ++++++++++++++++++ ...dex_tests__open_in_codex_confirmation.snap | 8 + ...n_in_codex_tests__open_in_codex_model.snap | 38 ++ ...in_codex_tests__open_in_codex_sidebar.snap | 16 + codex-rs/tui/src/app/startup.rs | 2 + codex-rs/tui/src/app/test_support.rs | 1 + codex-rs/tui/src/app/tests.rs | 4 + .../src/app/tests/active_reconnect_tests.rs | 1 + .../app/tests/pagination_completion_tests.rs | 1 + .../tui/src/app/tests/safety_buffering.rs | 2 +- .../app/tests/session_lifecycle_requests.rs | 2 + codex-rs/tui/src/app_event.rs | 5 + codex-rs/tui/src/app_server_session.rs | 18 + codex-rs/tui/src/app_server_session/fs.rs | 52 +- .../app_server_session/fs_preview_tests.rs | 18 +- codex-rs/tui/src/dynamic_tools_mcp.rs | 37 +- codex-rs/tui/src/lib.rs | 1 + .../tui/src/managed_worktree_tools_tests.rs | 1 + codex-rs/tui/src/open_in_codex.rs | 135 +++++ 28 files changed, 1285 insertions(+), 121 deletions(-) create mode 100644 codex-rs/tui/src/app/sidebar_document/model_read.rs create mode 100644 codex-rs/tui/src/app/sidebar_model_documents.rs create mode 100644 codex-rs/tui/src/app/sidebar_open_in_codex_tests.rs create mode 100644 codex-rs/tui/src/app/snapshots/codex_tui__app__sidebar_open_in_codex_tests__open_in_codex_confirmation.snap create mode 100644 codex-rs/tui/src/app/snapshots/codex_tui__app__sidebar_open_in_codex_tests__open_in_codex_model.snap create mode 100644 codex-rs/tui/src/app/snapshots/codex_tui__app__sidebar_open_in_codex_tests__open_in_codex_sidebar.snap create mode 100644 codex-rs/tui/src/open_in_codex.rs diff --git a/codex-rs/tui/BUILD.bazel b/codex-rs/tui/BUILD.bazel index d061d83345..9d0847686e 100644 --- a/codex-rs/tui/BUILD.bazel +++ b/codex-rs/tui/BUILD.bazel @@ -8,6 +8,7 @@ codex_rust_crate( ]), crate_name = "codex_tui", extra_binaries = [ + "//codex-rs/bwrap:bwrap", "//codex-rs/cli:codex", "//codex-rs/rmcp-client:test_stdio_server", ], diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index e29191fc6e..2bf0974333 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -293,6 +293,10 @@ mod sidebar_close; mod sidebar_document; mod sidebar_files; pub(crate) mod sidebar_loading; +mod sidebar_model_documents; +#[cfg(all(test, not(windows)))] +#[path = "app/sidebar_open_in_codex_tests.rs"] +mod sidebar_open_in_codex_tests; mod sidebar_subagents; mod startup; pub(crate) mod startup_bootstrap; @@ -684,6 +688,7 @@ pub(crate) struct App { side_threads: HashMap, saved_openings: sidebar_loading::Openings, sidebars: HashMap, sidebar::SidebarPane>, + model_preview_load: Option, /// A parked parent view survives child cleanup until its own replay finishes. side_companions: HashMap, zoomed_thread: Option, @@ -1105,6 +1110,15 @@ impl App { return Ok(AppRunControl::Exit(ExitReason::UserRequested)); } let screen_size = tui.screen_size_for_event(&event)?; + let draws_history = matches!( + event, + TuiEvent::Draw | TuiEvent::Resume | TuiEvent::Resize(_) | TuiEvent::FocusGained + ); + if draws_history && self.model_preview_load.is_none() { + self.model_preview_load = self + .start_queued_model_document(tui, app_server, screen_size.width) + .await; + } if !matches!( &event, TuiEvent::Key(_) | TuiEvent::Mouse(_) | TuiEvent::Paste(_) | TuiEvent::FocusLost @@ -1354,10 +1368,6 @@ impl App { _ => {} } - let draws_history = matches!( - event, - TuiEvent::Draw | TuiEvent::Resume | TuiEvent::Resize(_) | TuiEvent::FocusGained - ); if self.overlay.is_some() { let _ = self .handle_backtrack_overlay_event(tui, app_server, event) diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 5227b9b3f4..e947806f6d 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -113,6 +113,7 @@ impl App { | AppEvent::StartQueuedSavedChat | AppEvent::OpenSidebarAgent { .. } | AppEvent::OpenSidebarDocument { .. } + | AppEvent::OpenModelSidebarDocument { .. } | AppEvent::SidebarDocumentResolved { .. } | AppEvent::SidebarDocumentLoaded { .. } | AppEvent::SidebarFilesLoaded { .. } @@ -3757,16 +3758,29 @@ impl App { Box::pin(self.open_document(tui, app_server, source, link)).await?; } } + AppEvent::OpenModelSidebarDocument { backend, thread_id, document } => { + let pending = self.sidebars.entry(Some(thread_id)).or_default() + .pending_documents.entry(backend).or_default(); + const MAX_PENDING_PER_THREAD: usize = 8; + pending.retain(|request| request.path != document.path); + if pending.len() == MAX_PENDING_PER_THREAD { + pending.pop_front(); + } + pending.push_back(document); + tui.frame_requester().schedule_frame(); + } AppEvent::SidebarDocumentResolved { backend_id, parent, source, request, original_path, path, location, } => { + let requested = self.sidebars.get_mut(&Some(parent)) + .and_then(|pane| pane.focus_document_request.take_if(|id| *id == request)) + .is_some(); + if requested { + tui.frame_requester().schedule_frame(); + } if backend_id == app_server.backend_id() && self.sidebar_parent() == Some(parent) - && let Some(pane) = self.sidebars.get_mut(&Some(parent)) + && self.sidebars.contains_key(&Some(parent)) { // Late opens can add their tabs without taking back the user's focus. - let requested = pane.focus_document_request == Some(request); - if requested { - pane.focus_document_request = None; - } let focus = requested && self.current_displayed_thread_id() == Some(source) && self.document_preview_available(tui, app_server); @@ -3778,12 +3792,21 @@ impl App { } } AppEvent::SidebarDocumentLoaded { backend_id, parent, tab, request, result } => { + let model_load = self.model_preview_load == Some(request); + if model_load { + self.model_preview_load = None; + tui.frame_requester().schedule_frame(); + } 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(); + if model_load && doc.model_loading() && app_server.backend_id() == backend_id { + doc.finish_model_load(app_server, result).await; + tui.frame_requester().schedule_frame(); + } else if doc.watch.as_ref().is_some_and(|(id, _)| *id == request) { + doc.loaded(result); + tui.frame_requester().schedule_frame(); + } } } AppEvent::SidebarFilesLoaded { backend_id, parent, request, page } => { diff --git a/codex-rs/tui/src/app/side_pane.rs b/codex-rs/tui/src/app/side_pane.rs index 691ad27e76..044a7cf2fa 100644 --- a/codex-rs/tui/src/app/side_pane.rs +++ b/codex-rs/tui/src/app/side_pane.rs @@ -32,6 +32,7 @@ use ratatui::widgets::StatefulWidgetRef; use std::time::Duration; pub(super) const GAP: u16 = 1; +pub(super) const MIN_SPLIT_WIDTH: u16 = 100; pub(super) const RESIZE_HINT: &str = "Resize · ←/h →/l · Shift+←/→ 10 cols · Enter/Esc done"; #[derive(Clone, Copy, PartialEq, Eq)] @@ -110,7 +111,7 @@ fn visible_split(app: &App, tui: &Tui, area: Rect) -> Option { pub(super) fn split_layout(app: &App, tui: &Tui, area: Rect) -> Option { let area = app.workspace_chat_area(area); let content = app.sidebar()?.visible_content()?; - if area.width < 100 + if area.width < MIN_SPLIT_WIDTH || app.conversation_frame.has_caller_inset() || !app.side_retention_enabled(tui) { diff --git a/codex-rs/tui/src/app/sidebar.rs b/codex-rs/tui/src/app/sidebar.rs index de9423e21f..7db856c205 100644 --- a/codex-rs/tui/src/app/sidebar.rs +++ b/codex-rs/tui/src/app/sidebar.rs @@ -93,6 +93,10 @@ pub(super) struct SidebarPane { pub(super) files: Option, pub(super) opened_files: Vec, pub(super) documents: HashMap, + pub(super) pending_documents: HashMap< + crate::backend_id::BackendId, + std::collections::VecDeque, + >, pub(super) focus_document_request: Option, content: SidebarContent, tabs: Vec, @@ -565,7 +569,9 @@ impl App { self.conversation_frame.panel_area().or_else(|| { match side_pane::split_layout(self, tui, screen) { Some(SidebarLayout::Panel { sidebar, .. }) => Some(sidebar), - _ if screen.width < 100 && self.chooser_focus() == Some(PaneFocus::Sidebar) => { + _ if screen.width < side_pane::MIN_SPLIT_WIDTH + && self.chooser_focus() == Some(PaneFocus::Sidebar) => + { Some(screen) } _ => None, @@ -749,7 +755,7 @@ pub(super) fn paint_layout(app: &mut App, tui: &Tui, area: Rect) -> Option= 100 + && area.width >= side_pane::MIN_SPLIT_WIDTH && app.local_settings.tui.animations && app.pane_resize.is_none() && app.divider_drag.is_none(); @@ -764,7 +770,7 @@ pub(super) fn paint_layout(app: &mut App, tui: &Tui, area: Rect) -> Option, + path: &PathUri, + location: Option, +) -> Result { + if !(FileLink { + path: path.inferred_native_path_string(), + location, + }) + .is_image() + { + return AppServerSession::preview_text(bytes).map(DocumentContent::Text); + } + 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? +} + #[derive(Debug)] struct FileCell { source: String, @@ -78,6 +103,28 @@ pub(super) struct DocumentRenderOptions<'a> { pub(super) image_protocol: Option, } +const MAX_MODEL_DOCUMENTS: usize = 8; + +pub(super) enum DocumentOrigin { + User { + focus: bool, + }, + Model { + permissions: Result>, + }, +} + +enum DocumentAccess { + User, + Model { load: Option }, +} + +struct ModelLoad { + permissions: Arc, + // Dropping the tab or replacing the backend cancels the read. + _cancel: oneshot::Sender<()>, +} + pub(super) struct Document { source: ThreadId, pub(super) path: PathUri, @@ -87,9 +134,11 @@ pub(super) struct Document { link: Option, location: Option, state: State, + access: DocumentAccess, } enum State { + AwaitingOpen, Loading(Instant), Failed { error: color_eyre::Report, @@ -146,8 +195,54 @@ impl Document { self.path.basename().unwrap_or_default() } + pub(super) fn awaits_open(&self) -> bool { + matches!(self.state, State::AwaitingOpen) + } + + fn is_model_snapshot(&self) -> bool { + matches!(self.access, DocumentAccess::Model { .. }) + && matches!(self.state, State::Ready { .. } | State::Image(_)) + } + + pub(super) fn model_loading(&self) -> bool { + matches!(self.access, DocumentAccess::Model { load: Some(_) }) + } + + pub(super) async fn finish_model_load( + &mut self, + server: &AppServerSession, + result: Result, + ) { + let DocumentAccess::Model { + load: Some(initial), + } = &mut self.access + 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(Some(current)) + if initial.profile == current.profile + && initial.workspace_roots == current.workspace_roots => + { + Ok(content) + } + _ => Err(eyre!( + "Workspace or permissions changed while loading the preview" + )), + }, + Err(error) => Err(error), + }; + self.loaded(result); + } + pub(super) fn connection_replaced(&mut self) { self.watch = None; + if let DocumentAccess::Model { load } = &mut self.access { + *load = None; + } if matches!(self.state, State::Loading(_)) { self.state = State::Failed { error: eyre!("Connection changed. Reopen this file to try again."), @@ -160,7 +255,7 @@ impl Document { let position = match &self.state { State::Ready { view, .. } => Some(view.document_position()), State::Failed { position, .. } => *position, - State::Loading(_) | State::Image(_) => None, + State::AwaitingOpen | State::Loading(_) | State::Image(_) => None, }; self.state = match result { Ok(DocumentContent::Image(image)) => State::Image(image), @@ -282,8 +377,32 @@ impl Document { } = options; let buf = &mut *frame.buffer; ratatui::widgets::Clear.render(area, buf); - let body = area.inner(ratatui::layout::Margin::new(1, 0)); + let mut body = area.inner(ratatui::layout::Margin::new(1, 0)); + if self.is_model_snapshot() && body.height > 1 { + "Snapshot · Enter to open live" + .dim() + .render(Rect { height: 1, ..body }, buf); + body.y += 1; + body.height -= 1; + } match &mut self.state { + State::AwaitingOpen => { + let path = self.path.inferred_native_path_string(); + let path = + crate::history_cell::sanitize_user_text(path.into()).replace(['\n', '\t'], " "); + let title = match self.location { + Some(location) => format!("Open {path} at line {}?", location.line), + None => format!("Open {path}?"), + }; + let mut lines = textwrap::wrap(&title, usize::from(body.width).max(1)) + .into_iter() + .map(|line| Line::from(line.into_owned())) + .collect::>(); + lines.push("Focus this pane and press Enter to open.".dim().into()); + Paragraph::new(lines) + .wrap(ratatui::widgets::Wrap { trim: true }) + .render(body, buf); + } State::Image(image) => { frame .image_placements @@ -468,9 +587,7 @@ impl App { ) -> bool { self.conversation_focus_available(tui) && self.sidebar_chooser_available() - && server.thread_params_mode() != crate::app_server_session::ThreadParamsMode::Cloud - && server.app_server_platform_family() != Some("windows") - && (server.uses_remote_workspace() || !cfg!(windows)) + && server.supports_document_previews() && self.current_displayed_thread_id().is_some() } @@ -493,8 +610,8 @@ impl App { let Some(parent) = self.sidebar_parent() else { return Ok(()); }; - let resolver = server.request_view(); - let backend_id = resolver.backend_id(); + let resolver = server.file_system(); + let backend_id = server.backend_id(); let tx = self.app_event_tx.clone(); let request = uuid::Uuid::new_v4(); let pane = self.sidebar_mut(); @@ -533,34 +650,148 @@ impl App { location: Option, focus: bool, ) -> Result<()> { - let Some(parent) = self.sidebar_parent() else { - return Ok(()); - }; + if let Some(id) = self.open_document_tab( + server, + source, + original_path, + path, + location, + DocumentOrigin::User { focus }, + ) { + if focus { + self.activate_sidebar_tab(tui, server, SidebarTab::Document(id)) + .await?; + } else { + tui.frame_requester().schedule_frame(); + } + } + Ok(()) + } + + pub(super) fn open_document_tab( + &mut self, + server: &AppServerSession, + source: ThreadId, + original_path: AppServerPath, + path: PathUri, + location: Option, + origin: DocumentOrigin, + ) -> Option { + let parent = self.sidebar_parent()?; let backend_id = server.backend_id(); + let tx = self.app_event_tx.clone(); + let environment = self.environment_manager.try_local_environment(); 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 { .. }))) - }) + pane.documents + .iter() + .find(|(_, doc)| doc.backend == backend_id && doc.path == path) + .map(|(&id, _)| id) }); - if let Some((id, failed)) = existing { - if !focus { - return Ok(()); - } - if !failed { - if let Some(doc) = self.sidebar_mut().documents.get_mut(&id) { + if let Some(id) = existing { + let doc = self.sidebar_mut().documents.get_mut(&id)?; + match (&origin, &doc.access) { + (DocumentOrigin::User { focus: false }, _) => return None, + (DocumentOrigin::User { focus: true }, DocumentAccess::User) + if !matches!(doc.state, State::Failed { .. }) => + { doc.go_to(location); + return Some(id); } - return self - .activate_sidebar_tab(tui, server, SidebarTab::Document(id)) - .await; + (DocumentOrigin::Model { permissions: Ok(_) }, DocumentAccess::User) + if doc.source == source => + { + // The user already authorized this tab. Keep the watch and use its content. + if location.is_some() { + doc.go_to(location); + } + return Some(id); + } + (DocumentOrigin::Model { .. }, DocumentAccess::User) => return None, + _ => self.sidebar_mut().remove_document(id), } - self.sidebar_mut().remove_document(id); + } + if matches!(origin, DocumentOrigin::Model { .. }) + && self + .sidebars + .values() + .flat_map(|pane| pane.documents.values()) + .filter(|doc| matches!(doc.access, DocumentAccess::Model { .. })) + .count() + >= MAX_MODEL_DOCUMENTS + { + self.chat_widget.add_warning_message( + "Close a model-opened sidebar tab to open another model preview.".to_owned(), + ); + return None; } let request = uuid::Uuid::new_v4(); - let tx = self.app_event_tx.clone(); + let (state, access) = match origin { + DocumentOrigin::User { .. } => (State::Loading(Instant::now()), DocumentAccess::User), + DocumentOrigin::Model { permissions } => { + let (state, load) = match (permissions, environment) { + (Ok(None), _) => (State::AwaitingOpen, None), + (Err(error), _) => ( + State::Failed { + error, + position: None, + }, + None, + ), + (Ok(Some(_)), None) => ( + State::Failed { + error: eyre!("Local filesystem is unavailable"), + position: None, + }, + None, + ), + (Ok(Some(permissions)), Some(environment)) => { + let reader = server.file_system(); + let task_tx = tx.clone(); + let task_path = path.clone(); + let task_original = original_path.clone(); + let permissions = Arc::new(permissions); + let initial = Arc::clone(&permissions); + let (cancel, canceled) = oneshot::channel(); + tokio::spawn(async move { + let read = model_read::read( + &reader, + &environment, + source, + &task_original, + &task_path, + &permissions, + ); + let result = tokio::select! { + biased; + _ = canceled => Err(eyre!("Preview closed")), + result = read => result, + }; + let result = match result { + Ok(bytes) => decode_document(bytes, &task_path, location).await, + Err(error) => Err(error), + }; + task_tx.send(AppEvent::SidebarDocumentLoaded { + backend_id, + parent, + tab: request, + request, + result, + }); + }); + ( + State::Loading(Instant::now()), + Some(ModelLoad { + permissions: initial, + _cancel: cancel, + }), + ) + } + }; + (state, DocumentAccess::Model { load }) + } + }; let pane = self.sidebar_mut(); - if !pane.opened_files.contains(&path) { + if matches!(access, DocumentAccess::User) && !pane.opened_files.contains(&path) { pane.opened_files.push(path.clone()); } let mut doc = Document { @@ -571,18 +802,13 @@ impl App { backend: backend_id, link: None, location, - state: State::Loading(Instant::now()), + state, + access, }; 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)) - .await?; - } else { - tui.frame_requester().schedule_frame(); - } - Ok(()) + Some(request) } pub(super) async fn handle_document_input( @@ -593,7 +819,8 @@ impl App { ) -> bool { let focused = self.panel_focus() == Some(PaneFocus::Sidebar); let area = self.conversation_frame.panel_area(); - let Some(pane) = self.sidebars.get_mut(&self.sidebar_parent()) else { + let parent = self.sidebar_parent(); + let Some(pane) = self.sidebars.get_mut(&parent) else { return false; }; let Some(SidebarContent::Document(id)) = pane.visible_content() else { @@ -627,6 +854,24 @@ impl App { if key.kind != KeyEventKind::Press && (escape || key.code == KeyCode::Enter) { return true; } + if crate::key_hint::plain(KeyCode::Enter).is_press(*key) + && let Some(parent) = parent + && (doc.awaits_open() + || (doc.is_model_snapshot() + && doc.link.is_none() + && !doc.owns_interaction_key(*key))) + { + doc.access = DocumentAccess::User; + if doc.awaits_open() { + doc.state = State::Loading(Instant::now()); + } + doc.subscribe(id, parent, server, self.app_event_tx.clone()); + if !pane.opened_files.contains(&doc.path) { + pane.opened_files.push(doc.path.clone()); + } + tui.frame_requester().schedule_frame(); + return true; + } if let State::Ready { view, cells, diff --git a/codex-rs/tui/src/app/sidebar_document/model_read.rs b/codex-rs/tui/src/app/sidebar_document/model_read.rs new file mode 100644 index 0000000000..9fb817ee49 --- /dev/null +++ b/codex-rs/tui/src/app/sidebar_document/model_read.rs @@ -0,0 +1,111 @@ +//! Bounded, sandboxed reads for model-requested previews on the embedded backend. + +use crate::app_server_session::fs::AppServerFileSystem; +use crate::app_server_session::fs::resolve_preview_path; +use codex_app_server_client::AppServerPath; +use codex_app_server_client::ThreadPermissions; +use codex_exec_server::Environment; +use codex_exec_server::FileSystemSandboxContext; +use codex_protocol::ThreadId; +use codex_protocol::models::PermissionProfile; +use codex_protocol::permissions::FileSystemAccessMode; +use codex_protocol::permissions::FileSystemSandboxEntry; +use codex_protocol::permissions::FileSystemSandboxPolicy; +use codex_protocol::permissions::NetworkSandboxPolicy; +use codex_protocol::permissions::ReadDenyMatcher; +use codex_utils_path_uri::PathUri; +use color_eyre::eyre::Result; +use color_eyre::eyre::ensure; +use color_eyre::eyre::eyre; +use futures::StreamExt; + +const MAX_PREVIEW_BYTES: usize = 8 * 1024 * 1024; + +pub(in crate::app) async fn read( + fs: &AppServerFileSystem, + environment: &Environment, + source: ThreadId, + original_path: &AppServerPath, + path: &PathUri, + permissions: &ThreadPermissions, +) -> Result> { + let cwd_uri = fs.preview_workspace(source).await?; + let cwd = cwd_uri.to_abs_path()?; + let roots = if permissions.workspace_roots.is_empty() { + std::slice::from_ref(&cwd_uri) + } else { + &permissions.workspace_roots + }; + ensure!( + *path == resolve_preview_path(original_path, &cwd_uri)? + && roots.iter().any(|root| path.starts_with(root)), + "The preview path is outside the calling workspace or the workspace changed" + ); + ensure!( + !matches!(permissions.profile, PermissionProfile::External { .. }), + "The thread's external sandbox cannot authorize a preview" + ); + let thread_policy = permissions.profile.file_system_sandbox_policy(); + let deny_matcher = ReadDenyMatcher::try_new_for_local_paths(&thread_policy, cwd.as_path()) + .map_err(|error| eyre!("{error}"))?; + let requested = path.to_abs_path()?; + let canonical = tokio::fs::canonicalize(requested.as_path()).await?; + let mut within_workspace = false; + for root in roots { + if let Ok(root) = root.to_abs_path() + && let Ok(root) = tokio::fs::canonicalize(root.as_path()).await + && canonical.starts_with(root) + { + within_workspace = true; + break; + } + } + ensure!( + within_workspace + && [requested.as_path(), canonical.as_path()] + .into_iter() + .all(|path| { + thread_policy.can_read_local_path_with_cwd(path, cwd.as_path()) + && !deny_matcher + .as_ref() + .is_some_and(|matcher| matcher.is_local_path_read_denied(path)) + }), + "The calling workspace permissions do not allow reading this preview" + ); + let path = PathUri::from_host_native_path(&canonical)?; + // Keep the actual open within the file's own allow rule and the thread's deny rules. + let mut file_policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry::new( + path.clone().into(), + FileSystemAccessMode::Read, + )]); + file_policy.preserve_deny_read_restrictions_from(&thread_policy); + let profile = + PermissionProfile::from_runtime_permissions(&file_policy, NetworkSandboxPolicy::Restricted); + let info = environment.info().await?; + let mut sandbox = FileSystemSandboxContext::from_permission_profile(profile, cwd_uri.clone()); + sandbox.workspace_roots = roots.to_vec(); + sandbox.user_home_dir = info.user_home_dir; + sandbox.temporary_directories = info.temporary_directories; + ensure!( + info.capabilities.sandboxed_file_streaming && sandbox.should_read_from_sandbox(), + "The executor does not support sandboxed file previews" + ); + let mut stream = environment + .get_filesystem() + .read_file_stream(&path, Some(&sandbox)) + .await?; + let mut contents = Vec::new(); + while let Some(chunk) = stream.next().await { + let chunk = chunk?; + ensure!( + chunk.len() <= MAX_PREVIEW_BYTES - contents.len(), + "The file exceeds the 8 MiB model preview limit" + ); + contents.extend_from_slice(&chunk); + } + ensure!( + fs.preview_workspace(source).await? == cwd_uri, + "Workspace changed while loading the preview" + ); + Ok(contents) +} diff --git a/codex-rs/tui/src/app/sidebar_document/watch.rs b/codex-rs/tui/src/app/sidebar_document/watch.rs index de72fa020e..145920f92c 100644 --- a/codex-rs/tui/src/app/sidebar_document/watch.rs +++ b/codex-rs/tui/src/app/sidebar_document/watch.rs @@ -5,9 +5,6 @@ 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; @@ -19,16 +16,15 @@ impl Document { server: &AppServerSession, tx: AppEventSender, ) { + if !matches!(self.access, super::DocumentAccess::User) { + return; + } 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 location = self.location; let request = uuid::Uuid::new_v4(); let (refresh, mut changes) = watch::channel(()); self.watch = Some((request, refresh)); @@ -36,23 +32,8 @@ impl Document { 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) - } + let bytes = fs.read_preview_file(source, &original_path, &path).await?; + super::decode_document(bytes, &path, location).await } .await; tx.send(AppEvent::SidebarDocumentLoaded { diff --git a/codex-rs/tui/src/app/sidebar_model_documents.rs b/codex-rs/tui/src/app/sidebar_model_documents.rs new file mode 100644 index 0000000000..2b2fc9f0a1 --- /dev/null +++ b/codex-rs/tui/src/app/sidebar_model_documents.rs @@ -0,0 +1,70 @@ +//! Show model-requested document tabs when their source conversation is visible. + +use super::side_pane::MIN_SPLIT_WIDTH; +use super::sidebar::PaneFocus; +use super::sidebar::SidebarContent; +use super::sidebar::SidebarPane; +use super::sidebar_document::Document; +use super::sidebar_document::DocumentOrigin; +use super::*; + +impl App { + pub(super) async fn start_queued_model_document( + &mut self, + tui: &tui::Tui, + server: &AppServerSession, + width: u16, + ) -> Option { + let source = self.current_displayed_thread_id()?; + if self.chat_widget.thread_id() != Some(source) + || self.zoomed_thread == Some(source) + || width < MIN_SPLIT_WIDTH + || !self.document_preview_available(tui, server) + || self.chat_widget.has_active_view() + || self.divider_drag.is_some() + || self.pane_resize.is_some() + || self.panel_focus() == Some(PaneFocus::Sidebar) + || self.sidebar().is_some_and(|pane| { + pane.close.is_some() + || pane.focus_document_request.is_some() + || pane.agents.pending_link.is_some() + || matches!(pane.visible_content(), Some(SidebarContent::Document(id)) + if pane.documents.get(&id).is_some_and(Document::awaits_open)) + }) + { + return None; + } + let document = self + .sidebars + .get_mut(&Some(source))? + .pending_documents + .get_mut(&server.backend_id())? + .pop_front()?; + // Another request may be ready even when this one doesn't start a read. + tui.frame_requester().schedule_frame(); + let permissions = server.model_preview_permissions(source).await; + let id = self.open_document_tab( + server, + source, + document.original_path, + document.path, + document.location, + DocumentOrigin::Model { permissions }, + )?; + // Leave a live companion selected so its composer remains visible. + if self.sidebar_parent() == Some(source) + && !matches!( + self.sidebar().and_then(SidebarPane::visible_content), + Some(SidebarContent::Chat(_)) + ) + && self.docked_agent().is_none() + { + self.sidebar_mut() + .show(SidebarContent::Document(id), PaneFocus::Main); + } + self.sidebar() + .and_then(|pane| pane.documents.get(&id)) + .filter(|doc| doc.model_loading()) + .map(|_| id) + } +} diff --git a/codex-rs/tui/src/app/sidebar_open_in_codex_tests.rs b/codex-rs/tui/src/app/sidebar_open_in_codex_tests.rs new file mode 100644 index 0000000000..0f61b1fbca --- /dev/null +++ b/codex-rs/tui/src/app/sidebar_open_in_codex_tests.rs @@ -0,0 +1,464 @@ +#![cfg(test)] + +use super::sidebar::PaneFocus; +use super::sidebar::SidebarContent; +use super::sidebar::SidebarPane; +use super::test_support::enable_side_retention; +use super::test_support::side_frame; +use super::*; +use crate::app::tests::make_test_app_with_channels; +use crate::legacy_core::config::ConfigBuilder; +use crate::legacy_core::config::ConfigOverrides; +use crate::test_support::boxed_future; +use codex_app_server_client::AppServerPath; +use codex_app_server_protocol::RequestId; +use codex_app_server_protocol::ThreadSettingsUpdateParams; +use codex_app_server_protocol::TurnStartParams; +use codex_app_server_protocol::TurnStartResponse; +use codex_exec_server::EnvironmentManager; +use codex_exec_server::ExecServerRuntimeOptions; +use codex_utils_path_uri::PathUri; +use core_test_support::context_snapshot; +use core_test_support::context_snapshot::ContextSnapshotOptions; +use core_test_support::responses; +use pretty_assertions::assert_eq; +use serde_json::json; +use tokio::sync::Semaphore; + +#[tokio::test] +async fn open_in_codex_reveals_a_file_when_the_calling_thread_returns() -> Result<()> { + core_test_support::skip_if_sandbox!(Ok(())); + boxed_future!(open_in_codex_scenario()).await +} + +async fn open_in_codex_scenario() -> Result<()> { + let model = responses::start_mock_server().await; + let (mut app, mut events, _) = make_test_app_with_channels().await; + let home = tempfile::tempdir()?; + let workspace = tempfile::tempdir()?; + let path = workspace.path().join("PLAN.md"); + std::fs::write( + &path, + format!( + "# Navigation\n{}Use the sidebar.\n", + "Before the target.\n".repeat(40) + ), + )?; + let denied_plan = serde_json::to_string(&dunce::canonicalize(&path)?)?; + app_test_support::MockResponsesConfig::new(&model.uri()) + .enable_feature(Feature::TuiWorkspace) + .with_extra_config(&format!( + "[permissions.no-plan.filesystem]\n\":root\" = \"read\"\n{denied_plan} = \"deny\"", + )) + .write(home.path())?; + let config = ConfigBuilder::default() + .codex_home(home.path().to_path_buf()) + .harness_overrides(ConfigOverrides { + cwd: Some(dunce::canonicalize(workspace.path())?), + ..Default::default() + }) + .build() + .await?; + app.config = config.clone(); + enable_side_retention(&mut app)?; + app.local_settings.tui.animations = false; + + #[cfg(target_os = "linux")] + let linux_sandbox_exe = Some(core_test_support::find_codex_linux_sandbox_exe()?); + #[cfg(not(target_os = "linux"))] + let linux_sandbox_exe = None; + let environment = EnvironmentManager::create_for_tests_with_local( + /*exec_server_url*/ None, + ExecServerRuntimeOptions::new(std::env::current_exe()?, linux_sandbox_exe)?, + ) + .await; + app.environment_manager = Arc::new(environment); + let mut server = crate::start_app_server_for_picker( + crate::backend_id::BackendId::new(), + &config, + &crate::AppServerTarget::Embedded, + Vec::new(), + codex_config::LoaderOverrides::without_managed_config_for_tests(), + /*state_db*/ None, + Arc::clone(&app.environment_manager), + ) + .await?; + server + .start_dynamic_tool_mcp( + config.clone(), + app.local_settings.workspace_enabled(&config), + app.app_event_tx.clone(), + app.dynamic_tool_status_updates.clone(), + ) + .await?; + let caller = server.start_thread(&config).await?; + let caller_id = caller.session.thread_id; + + let outside = dunce::canonicalize(home.path())?.join("outside.txt"); + std::fs::write(&outside, "outside")?; + let escape = config.cwd.join("escape.txt"); + std::os::unix::fs::symlink(&outside, &escape)?; + let system_escape = config.cwd.join("hosts.txt"); + std::os::unix::fs::symlink("/etc/hosts", &system_escape)?; + let fs = server.file_system(); + let permissions = server.model_preview_permissions(caller_id).await?.unwrap(); + let environment = app.environment_manager.try_local_environment().unwrap(); + let read_preview = async |path: &std::path::Path| { + let uri = PathUri::from_host_native_path(path)?; + super::sidebar_document::model_read::read( + &fs, + &environment, + caller_id, + &AppServerPath::from_app_server(uri.inferred_native_path_string()), + &uri, + &permissions, + ) + .await + }; + for denied in [outside.as_path(), escape.as_path(), system_escape.as_path()] { + assert!( + read_preview(denied).await.is_err(), + "preview must reject {denied:?}" + ); + } + let oversized = config.cwd.join("large.md"); + std::fs::File::create(&oversized)?.set_len(8 * 1024 * 1024 + 1)?; + let error = read_preview(oversized.as_path()).await.unwrap_err(); + assert!(error.to_string().contains("8 MiB"), "{error}"); + let background = server.start_thread(&config).await?; + let background_id = background.session.thread_id; + let switch_to = + async |app: &mut App, thread: &crate::app_server_session::AppServerStartedThread| { + app.clear_active_thread().await; + app.enqueue_primary_thread_session(thread.session.clone(), thread.turns.clone()) + .await + }; + switch_to(&mut app, &background).await?; + + let call = json!({"target":{"type":"file","path":"PLAN.md","line":42}}); + let model_requests = responses::mount_sse_sequence( + &model, + vec![ + responses::sse(vec![ + responses::ev_function_call_with_namespace( + "open-plan", + "mcp__codex_tui", + "open_in_codex", + &call.to_string(), + ), + responses::ev_completed("open"), + ]), + responses::sse(vec![ + responses::ev_assistant_message("reply", "I opened the plan."), + responses::ev_completed("done"), + ]), + ], + ) + .await; + let _: TurnStartResponse = server + .request_handle() + .request_typed(ClientRequest::TurnStart { + request_id: RequestId::String("open-plan-turn".into()), + params: TurnStartParams { + thread_id: caller_id.to_string(), + input: vec![codex_app_server_protocol::UserInput::Text { + text: "Show me line 42 of the plan.".into(), + text_elements: Vec::new(), + }], + ..Default::default() + }, + }) + .await?; + boxed_future!(super::tests::wait_for_turn_completed( + &mut app, + &mut server, + caller_id + )) + .await; + let requests = model_requests.requests(); + let output = requests[1].function_call_output("open-plan")["output"].to_string(); + assert!(output.contains(&caller_id.to_string()), "{output}"); + insta::assert_snapshot!( + "open_in_codex_model", + context_snapshot::format_request_history_snapshot( + "The model opens a workspace file and receives a queued result while the calling thread is in the background.", + &requests, + &ContextSnapshotOptions::default().rewrite_known_segments(), + ) + ); + + let size = Size::new(/*width*/ 120, /*height*/ 12); + let mut tui = crate::tui::test_support::make_test_tui_with_size(size)?; + tui.set_owned_screen(/*owned*/ true)?; + while let Ok(event) = events.try_recv() { + boxed_future!(app.handle_event(&mut tui, &mut server, event)).await?; + } + boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Draw)).await?; + assert_eq!(app.current_displayed_thread_id(), Some(background_id)); + let visible_content = |app: &App| app.sidebar().and_then(SidebarPane::visible_content); + assert!(visible_content(&app).is_none()); + + let slots = Arc::new(Semaphore::new(crate::open_in_codex::MAX_PENDING_DOCUMENTS)); + let backend = server.backend_id(); + let request = |thread_id, name: &str| AppEvent::OpenModelSidebarDocument { + backend, + thread_id, + document: crate::open_in_codex::DocumentRequest { + original_path: AppServerPath::from_app_server(name), + path: PathUri::from_abs_path(&config.cwd.join(name)), + location: None, + _pending: Arc::clone(&slots).try_acquire_owned().unwrap(), + }, + }; + // Even when one thread fills its queue, a request for the visible chat can be accepted. + for index in 0..9 { + boxed_future!(app.handle_event( + &mut tui, + &mut server, + request(background_id, &format!("{index}.md")), + )) + .await?; + } + assert_eq!( + slots.available_permits(), + crate::open_in_codex::MAX_PENDING_DOCUMENTS - 8 + ); + + switch_to(&mut app, &caller).await?; + let narrow = Size::new(/*width*/ 80, /*height*/ size.height); + boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Resize(narrow))).await?; + assert!(visible_content(&app).is_none()); + + // A pending user click takes priority until it resolves, even across a thread switch. + app.open_document( + &mut tui, + &mut server, + caller_id, + crate::markdown_render::FileLink { + path: "old.md".into(), + location: None, + }, + ) + .await?; + boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Resize(size))).await?; + assert!(visible_content(&app).is_none()); + switch_to(&mut app, &background).await?; + let mut finish_document_request = + async |app: &mut App, tui: &mut tui::Tui, server: &mut AppServerSession| -> Result<()> { + loop { + let event = events.recv().await.expect("document event"); + let outcome = match &event { + AppEvent::SidebarDocumentLoaded { + result: Err(error), .. + } => Err(color_eyre::eyre::eyre!("{error:#}")), + AppEvent::SidebarDocumentLoaded { .. } + | AppEvent::SidebarDocumentResolved { .. } => Ok(()), + _ => continue, + }; + boxed_future!(app.handle_event(tui, server, event)).await?; + assert!(app.model_preview_load.is_none()); + return outcome; + } + }; + finish_document_request(&mut app, &mut tui, &mut server).await?; + switch_to(&mut app, &caller).await?; + boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Draw)).await?; + assert_eq!(app.panel_focus(), Some(PaneFocus::Main)); + assert!(matches!( + visible_content(&app), + Some(SidebarContent::Document(_)) + )); + let first_load = app.model_preview_load.expect("model preview loading"); + let preview = |name: &str| request(caller_id, name); + boxed_future!(app.handle_event(&mut tui, &mut server, preview("PLAN.md"))).await?; + // Drop the pending requests in the other chat before returning to it. + app.sidebars + .get_mut(&Some(background_id)) + .unwrap() + .pending_documents + .clear(); + boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Draw)).await?; + assert_eq!(app.model_preview_load, Some(first_load)); + assert_eq!( + slots.available_permits(), + crate::open_in_codex::MAX_PENDING_DOCUMENTS - 1 + ); + finish_document_request(&mut app, &mut tui, &mut server).await?; + boxed_future!(app.handle_tui_event( + &mut tui, + &mut server, + TuiEvent::Paste("Keep typing".into()) + )) + .await?; + assert_eq!(app.chat_widget.composer_text_with_pending(), "Keep typing"); + assert_eq!(app.current_displayed_thread_id(), Some(caller_id)); + let screen = side_frame(&mut app, &mut tui, size)?; + let sidebar = screen + .lines() + .filter_map(|line| line.split_once('│').map(|(_, content)| content.trim_end())) + .collect::>() + .join("\n"); + insta::assert_snapshot!("open_in_codex_sidebar", sidebar.trim_end()); + + assert!( + server + .thread_settings_update(ThreadSettingsUpdateParams { + thread_id: caller_id.to_string(), + permissions: Some("no-plan".into()), + ..Default::default() + }) + .await? + ); + + // A concurrently running side chat stays selected even when the parent has focus. + app.sidebar_mut() + .show(SidebarContent::Chat(background_id), PaneFocus::Main); + boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Draw)).await?; + assert_eq!( + slots.available_permits(), + crate::open_in_codex::MAX_PENDING_DOCUMENTS + ); + assert!(app.model_preview_load.is_some()); + let error = finish_document_request(&mut app, &mut tui, &mut server) + .await + .expect_err("cached preview must be reauthorized"); + assert!( + error.to_string().contains("permissions do not allow"), + "{error}" + ); + assert!(visible_content(&app) == Some(SidebarContent::Chat(background_id))); + + // The same rule applies to a docked agent when the parent sends the request. + let note = config.cwd.join("note.md"); + std::fs::write(¬e, "Another workspace file")?; + let pane = app.sidebar_mut(); + pane.agents.detail = Some(background_id); + pane.show(SidebarContent::Subagents, PaneFocus::Main); + assert_eq!(app.docked_agent(), Some((caller_id, background_id))); + boxed_future!(app.handle_event(&mut tui, &mut server, preview("note.md"))).await?; + boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Draw)).await?; + let note_tab = app.model_preview_load.expect("model preview loading"); + finish_document_request(&mut app, &mut tui, &mut server).await?; + assert_eq!( + slots.available_permits(), + crate::open_in_codex::MAX_PENDING_DOCUMENTS, + "open tabs use a separate budget" + ); + assert_eq!(app.docked_agent(), Some((caller_id, background_id))); + assert_eq!(app.current_displayed_thread_id(), Some(caller_id)); + let enter = TuiEvent::Key(crossterm::event::KeyEvent::new( + crossterm::event::KeyCode::Enter, + crossterm::event::KeyModifiers::NONE, + )); + app.sidebar_mut() + .show(SidebarContent::Document(note_tab), PaneFocus::Sidebar); + assert!( + app.handle_document_input(&mut tui, &mut server, &enter) + .await + ); + finish_document_request(&mut app, &mut tui, &mut server).await?; + let doc = app.sidebar_mut().documents.get_mut(¬e_tab).unwrap(); + let (watch, refresh) = doc.watch.as_ref().unwrap(); + let watch = *watch; + std::fs::write(¬e, "Changed workspace file")?; + refresh.send(())?; + finish_document_request(&mut app, &mut tui, &mut server).await?; + let (_, cells) = app + .sidebar_mut() + .documents + .get_mut(¬e_tab) + .unwrap() + .reader() + .unwrap(); + assert_eq!(cells[0].copy_source(), Some("Changed workspace file")); + + // A model request for the live file keeps its tab and subscription. + app.sidebar_mut() + .show(SidebarContent::Chooser, PaneFocus::Main); + let mut revisit = preview("note.md"); + if let AppEvent::OpenModelSidebarDocument { document, .. } = &mut revisit { + document.location = Some(crate::markdown_render::SourceLocation { line: 1, column: 1 }); + } + boxed_future!(app.handle_event(&mut tui, &mut server, revisit)).await?; + boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Draw)).await?; + assert!(app.model_preview_load.is_none()); + assert_eq!( + app.sidebar().unwrap().documents[¬e_tab] + .watch + .as_ref() + .unwrap() + .0, + watch + ); + + // A backend without an in-process permissions reader requires an explicit open. + let pane = app.sidebar_mut(); + pane.remove_document(note_tab); + pane.agents.detail = None; + pane.show(SidebarContent::Chooser, PaneFocus::Main); + let mut daemon_view = server.request_view(); + boxed_future!(app.handle_event(&mut tui, &mut daemon_view, preview("note.md"))).await?; + boxed_future!(app.handle_tui_event(&mut tui, &mut daemon_view, TuiEvent::Draw)).await?; + let Some(SidebarContent::Document(tab)) = visible_content(&app) else { + panic!("model request should show a confirmation tab"); + }; + let doc = &app.sidebar().unwrap().documents[&tab]; + assert!(doc.awaits_open()); + assert!(doc.watch.is_none()); + assert_eq!( + slots.available_permits(), + crate::open_in_codex::MAX_PENDING_DOCUMENTS + ); + let wide = Size::new(/*width*/ 360, /*height*/ size.height); + let screen = side_frame(&mut app, &mut tui, wide)?; + let sidebar = screen + .replace(config.cwd.as_path().to_str().unwrap(), "") + .lines() + .filter_map(|line| { + line.split_once('│') + .map(|(_, content)| content.trim_end().to_owned()) + }) + .collect::>() + .join("\n"); + insta::assert_snapshot!("open_in_codex_confirmation", sidebar.trim_end()); + + assert!( + !app.handle_document_input(&mut tui, &mut daemon_view, &enter) + .await + ); + assert!(app.sidebar().unwrap().documents[&tab].watch.is_none()); + app.sidebar_mut() + .show(SidebarContent::Document(tab), PaneFocus::Sidebar); + assert!( + app.handle_document_input(&mut tui, &mut daemon_view, &enter) + .await + ); + assert!(app.sidebar().unwrap().documents[&tab].watch.is_some()); + assert_eq!( + slots.available_permits(), + crate::open_in_codex::MAX_PENDING_DOCUMENTS + ); + finish_document_request(&mut app, &mut tui, &mut daemon_view).await?; + + app.sidebar_mut().remove_document(tab); + let other = config.cwd.join("other.md"); + std::fs::write(&other, "Next preview")?; + app.sidebar_mut() + .show(SidebarContent::Chooser, PaneFocus::Main); + boxed_future!(app.handle_event(&mut tui, &mut server, preview("PLAN.md"))).await?; + boxed_future!(app.handle_event(&mut tui, &mut server, preview("other.md"))).await?; + boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Draw)).await?; + let canceled = app.model_preview_load.expect("first preview loading"); + app.sidebar_mut().remove_document(canceled); + let result = tokio::time::timeout( + std::time::Duration::from_secs(5), + finish_document_request(&mut app, &mut tui, &mut server), + ) + .await?; + assert!(result.unwrap_err().to_string().contains("Preview closed")); + boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Draw)).await?; + assert!(app.model_preview_load.is_some()); + finish_document_request(&mut app, &mut tui, &mut server).await?; + server.shutdown().await?; + Ok(()) +} diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__sidebar_open_in_codex_tests__open_in_codex_confirmation.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__sidebar_open_in_codex_tests__open_in_codex_confirmation.snap new file mode 100644 index 0000000000..733b33e00b --- /dev/null +++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__sidebar_open_in_codex_tests__open_in_codex_confirmation.snap @@ -0,0 +1,8 @@ +--- +source: tui/src/app/sidebar_open_in_codex_tests.rs +assertion_line: 341 +expression: sidebar.trim_end() +--- + Side chat × PLAN.md × Agent transcript × note.md × + + Open /note.md? + Focus this pane and press Enter to open. diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__sidebar_open_in_codex_tests__open_in_codex_model.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__sidebar_open_in_codex_tests__open_in_codex_model.snap new file mode 100644 index 0000000000..3c9d827448 --- /dev/null +++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__sidebar_open_in_codex_tests__open_in_codex_model.snap @@ -0,0 +1,38 @@ +--- +source: tui/src/app/sidebar_open_in_codex_tests.rs +expression: "context_snapshot::format_request_history_snapshot(\"The model opens a workspace file and receives a queued result while the calling thread is in the background.\",\n&requests, &ContextSnapshotOptions::default().rewrite_known_segments(),)" +--- +Scenario: The model opens a workspace file and receives a queued result while the calling thread is in the background. + +## Window 1 +-- request 1 (turn) -- +00:message/developer: + You are a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open...I. You are expected to be precise, safe, and helpful. [hash=5125daec1ed78d99] + + Your capabilities: + + - Receive user prompts and other context provided by the harness, such as files in the workspace. + - Communicate with the user by streaming thinking & responses, and by making & updating plans. + - Emit function calls to run terminal commands and apply patches. Depending on how this specific run is ... More on this in the "Sandbox and approvals" section. [hash=31cf026fa7b25d6d] + + + ## Shell commands + + When using the shell, you must adhere to the following guidelines: + + - When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much ...he `rg` command is not found, then use alternatives.) [hash=67af3ff3b546e946] + - Do not use python scripts to attempt to output larger chunks of a file. + + +01:message/developer[2]: + [01] + [02] +02:message/user: + +03:message/user: + Show me line 42 of the plan. +-- request 2 (turn) -- +04:function_call/mcp__codex_tui.open_in_codex:{"target":{"line":42,"path":"PLAN.md","type":"file"}} +05:function_call_output:Wall time: seconds + Output: + {"status":"queued","threadId":""} diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__sidebar_open_in_codex_tests__open_in_codex_sidebar.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__sidebar_open_in_codex_tests__open_in_codex_sidebar.snap new file mode 100644 index 0000000000..6a197f28b8 --- /dev/null +++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__sidebar_open_in_codex_tests__open_in_codex_sidebar.snap @@ -0,0 +1,16 @@ +--- +source: tui/src/app/sidebar_open_in_codex_tests.rs +expression: sidebar.trim_end() +--- + PLAN.md × + + Snapshot · Enter to open live + Use the sidebar. ↑ + + + + + + + + + ↑/↓ read · f3 find · Tab link … diff --git a/codex-rs/tui/src/app/startup.rs b/codex-rs/tui/src/app/startup.rs index 63a91cde27..5ac2e2e346 100644 --- a/codex-rs/tui/src/app/startup.rs +++ b/codex-rs/tui/src/app/startup.rs @@ -571,6 +571,7 @@ impl App { ) && let Err(error) = app_server .start_dynamic_tool_mcp( config.clone(), + local_settings.workspace_enabled(&config), app_event_tx.clone(), dynamic_tool_status_updates.clone(), ) @@ -1139,6 +1140,7 @@ See the Codex keymap documentation for supported actions and examples." side_threads: HashMap::new(), saved_openings: Default::default(), sidebars: HashMap::new(), + model_preview_load: None, side_companions: HashMap::new(), zoomed_thread: None, exact_sidebar_width: None, diff --git a/codex-rs/tui/src/app/test_support.rs b/codex-rs/tui/src/app/test_support.rs index f35f4d5bc8..27998c72fc 100644 --- a/codex-rs/tui/src/app/test_support.rs +++ b/codex-rs/tui/src/app/test_support.rs @@ -146,6 +146,7 @@ pub(crate) async fn make_test_app() -> Box { side_threads: HashMap::new(), saved_openings: Default::default(), sidebars: HashMap::new(), + model_preview_load: None, side_companions: HashMap::new(), zoomed_thread: None, exact_sidebar_width: None, diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 0c1d09874e..e5460de24a 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -94,6 +94,8 @@ mod recap_generation; #[path = "tests/resume_shutdown_tests.rs"] mod resume_shutdown_tests; mod safety_buffering; +#[cfg(not(windows))] +pub(super) use safety_buffering::wait_for_turn_completed; #[path = "tests/saved_chat_loading_tests.rs"] mod saved_chat_loading; #[path = "tests/session_lifecycle_requests.rs"] @@ -9285,6 +9287,7 @@ async fn make_test_app() -> Box { side_threads: HashMap::new(), saved_openings: Default::default(), sidebars: HashMap::new(), + model_preview_load: None, side_companions: HashMap::new(), zoomed_thread: None, exact_sidebar_width: None, @@ -9433,6 +9436,7 @@ pub(super) async fn make_test_app_with_channels() -> ( side_threads: HashMap::new(), saved_openings: Default::default(), sidebars: HashMap::new(), + model_preview_load: None, side_companions: HashMap::new(), zoomed_thread: None, exact_sidebar_width: None, diff --git a/codex-rs/tui/src/app/tests/active_reconnect_tests.rs b/codex-rs/tui/src/app/tests/active_reconnect_tests.rs index 083078e141..0f85ec35bb 100644 --- a/codex-rs/tui/src/app/tests/active_reconnect_tests.rs +++ b/codex-rs/tui/src/app/tests/active_reconnect_tests.rs @@ -189,6 +189,7 @@ async fn reconnect_restores_history_permissions_and_resumes_unsent_input() -> Re app.app_event_tx.clone(), app.dynamic_tool_status_updates.clone(), /*worktrees*/ None, + /*sidebar_backend*/ None, ) .await?, )); diff --git a/codex-rs/tui/src/app/tests/pagination_completion_tests.rs b/codex-rs/tui/src/app/tests/pagination_completion_tests.rs index bd5a0018c4..9bcf05018e 100644 --- a/codex-rs/tui/src/app/tests/pagination_completion_tests.rs +++ b/codex-rs/tui/src/app/tests/pagination_completion_tests.rs @@ -648,6 +648,7 @@ async fn closing_the_first_preview_populates_the_files_chooser() -> Result<()> { let original_path = codex_app_server_client::AppServerPath::from_app_server("notes.md"); let path = server + .file_system() .resolve_thread_file(thread_id, &original_path) .await?; Box::pin(app.open_resolved_document( diff --git a/codex-rs/tui/src/app/tests/safety_buffering.rs b/codex-rs/tui/src/app/tests/safety_buffering.rs index ac682acc32..e64b82022f 100644 --- a/codex-rs/tui/src/app/tests/safety_buffering.rs +++ b/codex-rs/tui/src/app/tests/safety_buffering.rs @@ -140,7 +140,7 @@ async fn next_turn_started( } } -pub(super) async fn wait_for_turn_completed( +pub(in crate::app) async fn wait_for_turn_completed( app: &mut App, app_server: &mut AppServerSession, thread_id: ThreadId, diff --git a/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs b/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs index 1f785d295d..de2e2b0128 100644 --- a/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs +++ b/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs @@ -3023,6 +3023,7 @@ async fn local_daemon_registers_approval_gated_mcp_tools_for_both_start_paths_sc .await?; Box::pin(app_server.start_dynamic_tool_mcp( app.config.clone(), + /*workspace_enabled*/ false, app.app_event_tx.clone(), app.dynamic_tool_status_updates.clone(), )) @@ -3344,6 +3345,7 @@ async fn local_mcp_respects_configured_servers_and_managed_requirements() -> Res let result = app_server .start_dynamic_tool_mcp( app.config.clone(), + /*workspace_enabled*/ false, app.app_event_tx.clone(), app.dynamic_tool_status_updates.clone(), ) diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index dfa6639cf5..db735c7101 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -555,6 +555,11 @@ pub(crate) enum AppEvent { source: ThreadId, link: crate::markdown_render::FileLink, }, + OpenModelSidebarDocument { + backend: crate::backend_id::BackendId, + thread_id: ThreadId, + document: crate::open_in_codex::DocumentRequest, + }, SidebarDocumentResolved { backend_id: crate::backend_id::BackendId, parent: ThreadId, diff --git a/codex-rs/tui/src/app_server_session.rs b/codex-rs/tui/src/app_server_session.rs index 14d186d3af..766d262a64 100644 --- a/codex-rs/tui/src/app_server_session.rs +++ b/codex-rs/tui/src/app_server_session.rs @@ -772,6 +772,7 @@ impl AppServerSession { pub(crate) async fn start_dynamic_tool_mcp( &mut self, config: Config, + workspace_enabled: bool, app_event_tx: AppEventSender, status_updates: tokio::sync::broadcast::Sender, ) -> std::io::Result<()> { @@ -837,6 +838,10 @@ impl AppServerSession { }); thread_start_params.daybreak_enabled = daybreak_launch_override.then_some(config.daybreak_enabled); + let sidebar_backend = (workspace_enabled + && !self.uses_remote_workspace() + && self.supports_document_previews()) + .then_some(self.backend_id()); let server = Arc::new( DynamicToolMcpServer::start( self.request_handle(), @@ -845,6 +850,7 @@ impl AppServerSession { app_event_tx, status_updates, worktrees, + sidebar_backend, ) .await?, ); @@ -890,6 +896,18 @@ impl AppServerSession { matches!(&self.request_handle, AppServerRequestHandle::InProcess(_)) } + pub(crate) async fn model_preview_permissions( + &self, + source: ThreadId, + ) -> Result> { + match &self.connection_owner { + Some(AppServerClient::InProcess(client)) => { + Ok(Some(client.thread_permissions(source).await?)) + } + _ => Ok(None), + } + } + /// Carry capabilities that may exist only in memory when the optional cache is unwritable. pub(crate) fn inherit_task_tool_capabilities(&mut self, previous: &Self) { self.task_tool_threads.extend(&previous.task_tool_threads); diff --git a/codex-rs/tui/src/app_server_session/fs.rs b/codex-rs/tui/src/app_server_session/fs.rs index befa865597..c0c862544d 100644 --- a/codex-rs/tui/src/app_server_session/fs.rs +++ b/codex-rs/tui/src/app_server_session/fs.rs @@ -28,7 +28,7 @@ use serde::de::DeserializeOwned; use serde_json::json; use uuid::Uuid; -impl AppServerSession { +impl AppServerFileSystem { pub(crate) async fn resolve_thread_file( &self, source: ThreadId, @@ -38,7 +38,7 @@ impl AppServerSession { resolve_preview_path(path, &cwd) } - async fn preview_workspace(&self, source: ThreadId) -> Result { + pub(crate) async fn preview_workspace(&self, source: ThreadId) -> Result { // Read only the environment metadata. Other paths in thread/read may be native // to a different operating system from the TUI. #[derive(serde::Deserialize)] @@ -51,7 +51,7 @@ impl AppServerSession { } let request_id = RequestId::String(Uuid::new_v4().to_string()); let response: Response = self - .request_handle() + .request_handle .request_typed(ClientRequest::ThreadRead { request_id, params: codex_app_server_protocol::ThreadReadParams { @@ -73,29 +73,6 @@ impl AppServerSession { }) } - pub(crate) async fn read_document( - &self, - source: ThreadId, - original_path: &AppServerPath, - resolved_path: &PathUri, - ) -> Result { - let bytes = self - .read_preview_file(source, original_path, resolved_path) - .await?; - Self::preview_text(bytes) - } - - pub(crate) fn preview_text(bytes: Vec) -> Result { - let text = String::from_utf8(bytes).wrap_err("Not a UTF-8 text file")?; - color_eyre::eyre::ensure!( - !text - .chars() - .any(|ch| ch.is_control() && !matches!(ch, '\t' | '\n' | '\r')), - "Not a text file" - ); - Ok(text) - } - pub(crate) async fn read_preview_file( &self, source: ThreadId, @@ -113,13 +90,32 @@ impl AppServerSession { ); // fs/readFile follows symlinks. Only a server-side open can enforce no-follow. let path = AppServerPath::from_app_server(resolved_path.inferred_native_path_string()); - let bytes = self.file_system().fs_read_file_path(&path).await?; + let bytes = self.fs_read_file_path(&path).await?; color_eyre::eyre::ensure!( self.preview_workspace(source).await? == workspace, "Workspace changed. Reopen the file to try again." ); Ok(bytes) } +} + +impl AppServerSession { + pub(crate) fn supports_document_previews(&self) -> bool { + self.thread_params_mode() != super::ThreadParamsMode::Cloud + && self.app_server_platform_family() != Some("windows") + && (self.uses_remote_workspace() || !cfg!(windows)) + } + + pub(crate) fn preview_text(bytes: Vec) -> Result { + let text = String::from_utf8(bytes).wrap_err("Not a UTF-8 text file")?; + color_eyre::eyre::ensure!( + !text + .chars() + .any(|ch| ch.is_control() && !matches!(ch, '\t' | '\n' | '\r')), + "Not a text file" + ); + Ok(text) + } pub(crate) fn file_system(&self) -> AppServerFileSystem { AppServerFileSystem { @@ -128,7 +124,7 @@ impl AppServerSession { } } -fn resolve_preview_path(path: &AppServerPath, cwd: &PathUri) -> Result { +pub(crate) fn resolve_preview_path(path: &AppServerPath, cwd: &PathUri) -> Result { let path = LegacyAppPathString::from_string(path.as_str()) .resolve_against(cwd, /*user_home_dir*/ None)?; color_eyre::eyre::ensure!( 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 6d2fbebca5..674f2ac2d7 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 @@ -75,12 +75,13 @@ async fn remote_preview_requests_the_source_thread_and_validates_text() -> Resul ThreadParamsMode::Remote, ); 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 fs = session.file_system(); + let resolved = fs.resolve_thread_file(source, &path).await?; + let read_text = async || { + AppServerSession::preview_text(fs.read_preview_file(source, &path, &resolved).await?) + }; + assert_eq!(read_text().await?, text); + let error = read_text().await.unwrap_err(); let Some(TypedRequestError::Server { method, source: rpc_error, @@ -103,10 +104,7 @@ async fn remote_preview_requests_the_source_thread_and_validates_text() -> Resul "Not a text file", "Workspace changed", ] { - let error = session - .read_document(source, &path, &resolved) - .await - .unwrap_err(); + let error = read_text().await.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. diff --git a/codex-rs/tui/src/dynamic_tools_mcp.rs b/codex-rs/tui/src/dynamic_tools_mcp.rs index 47b5cb126c..3936fac702 100644 --- a/codex-rs/tui/src/dynamic_tools_mcp.rs +++ b/codex-rs/tui/src/dynamic_tools_mcp.rs @@ -1,7 +1,8 @@ -//! Approval-gated MCP transport for task tools owned by a local TUI. +//! MCP transport for tools owned by the local interactive TUI. use crate::app_event_sender::AppEventSender; use crate::dynamic_tools; +use crate::open_in_codex; use axum::Router; use axum::body::Body; use axum::extract::State; @@ -44,6 +45,7 @@ use std::sync::Arc; use std::sync::PoisonError; use std::sync::RwLock; use tokio::net::TcpListener; +use tokio::sync::Semaphore; use tokio::sync::broadcast; use tokio::task::JoinHandle; use uuid::Uuid; @@ -127,6 +129,7 @@ impl DynamicToolMcpServer { app_event_tx: AppEventSender, status_updates: broadcast::Sender, worktrees: Option, + sidebar_backend: Option, ) -> std::io::Result { let listener = TcpListener::bind("127.0.0.1:0").await?; let address = listener.local_addr()?; @@ -153,6 +156,8 @@ impl DynamicToolMcpServer { status_updates, server_config: server_config.clone(), worktrees, + sidebar_backend, + sidebar_pending_slots: Arc::new(Semaphore::new(open_in_codex::MAX_PENDING_DOCUMENTS)), }; let service = StreamableHttpService::new( move || Ok(handler.clone()), @@ -209,6 +214,8 @@ struct DynamicToolMcpHandler { status_updates: broadcast::Sender, server_config: Value, worktrees: Option, + sidebar_backend: Option, + sidebar_pending_slots: Arc, } impl ServerHandler for DynamicToolMcpHandler { @@ -222,6 +229,9 @@ impl ServerHandler for DynamicToolMcpHandler { _context: RequestContext, ) -> Result { let mut tools = Vec::new(); + if self.sidebar_backend.is_some() { + tools.push(open_in_codex::tool()); + } let mut specs = dynamic_tools::tool_specs(); if self.worktrees.is_some() { specs.extend(crate::managed_worktree_tool_specs::specs()); @@ -296,11 +306,6 @@ impl ServerHandler for DynamicToolMcpHandler { tool: request.name.into_owned(), arguments: Value::Object(request.arguments.unwrap_or_default()), }; - let mut thread_start_params = self.thread_start_params.clone(); - thread_start_params.config.get_or_insert_default().insert( - format!("mcp_servers.{}", dynamic_tools::NAMESPACE), - self.server_config.clone(), - ); // Snapshot once: an in-flight call must never switch connections or replay a mutation. let (request_handle, app_event_tx) = self .connection @@ -310,6 +315,21 @@ impl ServerHandler for DynamicToolMcpHandler { .ok_or_else(|| { McpError::internal_error("TUI is reconnecting; tool was not sent", None) })?; + if params.tool == open_in_codex::NAME { + let backend = self.sidebar_backend.ok_or_else(|| { + McpError::invalid_params("The sidebar is unavailable on this connection", None) + })?; + return open_in_codex::execute( + request_handle, + &app_event_tx, + Arc::clone(&self.sidebar_pending_slots), + backend, + ¶ms.thread_id, + params.arguments, + ) + .await + .map(Into::into); + } let response = if matches!( params.tool.as_str(), "create_worktree" | "get_worktree_creation_status" | "list_worktrees" @@ -326,6 +346,11 @@ impl ServerHandler for DynamicToolMcpHandler { ) .await } else { + let mut thread_start_params = self.thread_start_params.clone(); + thread_start_params.config.get_or_insert_default().insert( + format!("mcp_servers.{}", dynamic_tools::NAMESPACE), + self.server_config.clone(), + ); dynamic_tools::execute( request_handle, params, diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 69b5998835..0efd05e109 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -200,6 +200,7 @@ mod notifications; #[cfg(any(not(debug_assertions), test))] mod npm_registry; pub(crate) mod onboarding; +mod open_in_codex; mod oss_selection; mod pager_overlay; mod projectless; diff --git a/codex-rs/tui/src/managed_worktree_tools_tests.rs b/codex-rs/tui/src/managed_worktree_tools_tests.rs index a20e0637a2..f55b03a3d4 100644 --- a/codex-rs/tui/src/managed_worktree_tools_tests.rs +++ b/codex-rs/tui/src/managed_worktree_tools_tests.rs @@ -48,6 +48,7 @@ async fn start_server( server .start_dynamic_tool_mcp( config.clone(), + /*workspace_enabled*/ false, crate::app_event_sender::AppEventSender::new(events), status, ) diff --git a/codex-rs/tui/src/open_in_codex.rs b/codex-rs/tui/src/open_in_codex.rs new file mode 100644 index 0000000000..37ad3ad266 --- /dev/null +++ b/codex-rs/tui/src/open_in_codex.rs @@ -0,0 +1,135 @@ +//! Model-facing requests to show files in the calling conversation's sidebar. + +use crate::app_event::AppEvent; +use crate::app_event_sender::AppEventSender; +use crate::app_server_session::fs::AppServerFileSystem; +use crate::backend_id::BackendId; +use crate::markdown_render::SourceLocation; +use codex_app_server_client::AppServerPath; +use codex_app_server_client::AppServerRequestHandle; +use codex_protocol::ThreadId; +use codex_utils_path_uri::PathUri; +use rmcp::ErrorData as McpError; +use rmcp::model::CallToolResult; +use rmcp::model::Tool; +use serde::Deserialize; +use serde_json::json; +use std::num::NonZeroUsize; +use std::sync::Arc; +use tokio::sync::OwnedSemaphorePermit; +use tokio::sync::Semaphore; + +pub(crate) const NAME: &str = "open_in_codex"; +pub(crate) const MAX_PENDING_DOCUMENTS: usize = 32; + +#[derive(Debug)] +pub(crate) struct DocumentRequest { + pub(crate) original_path: AppServerPath, + pub(crate) path: PathUri, + pub(crate) location: Option, + pub(crate) _pending: OwnedSemaphorePermit, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Arguments { + target: Target, +} + +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)] +enum Target { + File { + path: String, + #[serde(default, deserialize_with = "deserialize_line")] + line: Option, + }, +} + +fn deserialize_line<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + NonZeroUsize::deserialize(deserializer).map(Some) +} + +pub(crate) fn tool() -> Tool { + let schema = rmcp::object!({ + "type": "object", + "additionalProperties": false, + "required": ["target"], + "properties": { + "target": { + "type": "object", + "additionalProperties": false, + "required": ["type", "path"], + "properties": { + "type": {"type": "string", "const": "file"}, + "path": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "description": "File path, absolute or relative to the calling thread's working directory." + }, + "line": {"type": "integer", "minimum": 1, "description": "One-based source line."} + } + } + } + }); + Tool::new( + NAME, + "Show a workspace file in the calling thread's Codex sidebar. Use when showing a document, source location, or image would help the user. The request may queue until the thread is visible. This only opens the UI. Use file tools to inspect the content.", + Arc::new(schema), + ) +} + +pub(crate) async fn execute( + request_handle: AppServerRequestHandle, + events: &AppEventSender, + pending_slots: Arc, + backend: BackendId, + thread_id: &str, + arguments: serde_json::Value, +) -> Result { + let thread_id = ThreadId::from_string(thread_id) + .map_err(|_| McpError::invalid_params("Invalid calling thread ID", None))?; + let Arguments { + target: Target::File { path, line }, + } = serde_json::from_value(arguments).map_err(|_| { + McpError::invalid_params( + "Expected a file target with a path and optional positive line", + None, + ) + })?; + if path.is_empty() || path.len() > 4096 || path.chars().any(char::is_control) { + return Err(McpError::invalid_params("Invalid file path", None)); + } + let pending = pending_slots.try_acquire_owned().map_err(|_| { + McpError::internal_error("The model preview queue is full. Try again later.", None) + })?; + let original_path = AppServerPath::from_app_server(path); + let path = AppServerFileSystem { request_handle } + .resolve_thread_file(thread_id, &original_path) + .await + .map_err(|_| McpError::invalid_params("File preview is unavailable for this path", None))?; + let location = line.map(|line| SourceLocation { + line: line.get(), + column: 1, + }); + events + .app_event_tx + .send(AppEvent::OpenModelSidebarDocument { + backend, + thread_id, + document: DocumentRequest { + original_path, + path, + location, + _pending: pending, + }, + }) + .map_err(|_| McpError::internal_error("The TUI is no longer accepting requests", None))?; + Ok(CallToolResult::structured(json!({ + "status": "queued", + "threadId": thread_id, + }))) +}